-- 考勤：考勤调整记录菜单
-- 执行环境：lqerp_dev / 生产（按需）
-- 说明：调整记录菜单挂在考勤管理下；手动修改考勤暂不做按钮权限，进入打卡记录页即可操作
-- 幂等：同 URL/EnCode 不重复插入；菜单授权按真实 F_Id 授权

-- 1) 考勤调整记录菜单（Type=2，父级考勤管理 816879900139980037）
-- 仅当 URL 与 EnCode 均不存在时插入，避免与已有 kqtzjl 菜单重复
INSERT INTO BASE_MODULE (
  F_Id, F_ParentId, F_Type, F_FullName, F_EnCode, F_UrlAddress, F_Icon,
  F_SortCode, F_EnabledMark, F_Category, F_DeleteMark, F_LinkTarget,
  F_PropertyJson, F_IsButtonAuthorize, F_IsColumnAuthorize, F_IsDataAuthorize,
  F_IsFormAuthorize, F_CreatorTime
)
SELECT
  'lvq-attendance-adjust',
  '816879900139980037',
  2,
  '考勤调整记录',
  'attendanceAdjust',
  'attendance-adjust',
  'icon-ym icon-ym-clock',
  4,
  1,
  'Web',
  NULL,
  '_self',
  '{"moduleId":"","iconBackgroundColor":"","isTree":0}',
  1, 1, 1, 1,
  NOW()
FROM (SELECT 1) AS _seed
WHERE NOT EXISTS (
  SELECT 1 FROM BASE_MODULE
  WHERE F_UrlAddress = 'attendance-adjust'
    AND F_DeleteMark IS NULL
)
AND NOT EXISTS (
  SELECT 1 FROM BASE_MODULE
  WHERE F_EnCode IN ('kqtzjl', 'attendanceAdjust')
    AND F_DeleteMark IS NULL
);

-- 2) 菜单授权：复制打卡记录模块已有角色，授权到真实菜单 F_Id
INSERT INTO BASE_AUTHORIZE (
  F_Id, F_ItemType, F_ItemId, F_ObjectType, F_ObjectId, F_SortCode, F_CreatorTime, F_CreatorUserId
)
SELECT LEFT(SHA2(CONCAT(m.F_Id, ':', t.F_ObjectId), 256), 50),
       'module', m.F_Id, 'Role', t.F_ObjectId, 1, NOW(), 'admin'
FROM (
  SELECT DISTINCT F_ObjectId
  FROM BASE_AUTHORIZE
  WHERE F_ItemId = 'lvq-attendance-record' AND F_ItemType = 'module' AND F_ObjectType = 'Role'
) t
CROSS JOIN (
  SELECT F_Id
  FROM BASE_MODULE
  WHERE F_UrlAddress = 'attendance-adjust'
    AND F_DeleteMark IS NULL
  ORDER BY F_CreatorTime
  LIMIT 1
) m
WHERE NOT EXISTS (
  SELECT 1 FROM BASE_AUTHORIZE a
  WHERE a.F_ItemId = m.F_Id
    AND a.F_ItemType = 'module'
    AND a.F_ObjectType = 'Role'
    AND a.F_ObjectId = t.F_ObjectId
);
