-- Add employee and salary maintenance tables to an existing financial_system database.
-- Execute with:
--   mysql -h localhost -P 3306 -u root -p12345678 < financial_system/database/sql/upgrade_20260616_employee_salary.sql

USE `financial_system`;

CREATE TABLE IF NOT EXISTS `employees` (
  `id` INT NOT NULL AUTO_INCREMENT COMMENT '员工主键ID',
  `employee_no` VARCHAR(64) NOT NULL COMMENT '员工编号，全局唯一，系统自动生成，默认ZA前缀',
  `name` VARCHAR(128) NOT NULL COMMENT '员工姓名',
  `dingtalk_user_id` VARCHAR(128) NOT NULL DEFAULT '' COMMENT '钉钉用户ID，用于对接钉钉考勤',
  `department` VARCHAR(128) NOT NULL DEFAULT '' COMMENT '部门名称',
  `position` VARCHAR(128) NOT NULL DEFAULT '' COMMENT '岗位名称',
  `phone` VARCHAR(32) NOT NULL DEFAULT '' COMMENT '手机号',
  `employment_status` VARCHAR(32) NOT NULL DEFAULT 'active' COMMENT '员工状态：active在职、inactive离职',
  `remark` TEXT NOT NULL COMMENT '员工备注',
  `created_at` DATETIME NOT NULL DEFAULT CURRENT_TIMESTAMP COMMENT '创建时间',
  `updated_at` DATETIME NOT NULL DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP COMMENT '更新时间',
  PRIMARY KEY (`id`),
  UNIQUE KEY `ix_employees_employee_no` (`employee_no`),
  KEY `ix_employees_name` (`name`),
  KEY `ix_employees_dingtalk_user_id` (`dingtalk_user_id`),
  KEY `ix_employees_employment_status` (`employment_status`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci
  COMMENT='员工基础档案表，维护员工编号、姓名、部门、岗位和钉钉用户ID';

CREATE TABLE IF NOT EXISTS `salary_profiles` (
  `id` INT NOT NULL AUTO_INCREMENT COMMENT '薪资档案主键ID',
  `employee_id` INT NOT NULL COMMENT '关联员工ID，一名员工一条当前薪资档案',
  `base_salary` FLOAT NOT NULL DEFAULT 0 COMMENT '基础工资或底薪',
  `commission_amount` FLOAT NOT NULL DEFAULT 0 COMMENT '手工维护的提成费用',
  `overtime_rate` FLOAT NOT NULL DEFAULT 0 COMMENT '加班费小时单价，独立于基础工资维护',
  `effective_month` VARCHAR(7) NOT NULL DEFAULT '' COMMENT '生效月份，格式YYYY-MM；为空表示长期当前档案',
  `remark` TEXT NOT NULL COMMENT '薪资备注',
  `created_at` DATETIME NOT NULL DEFAULT CURRENT_TIMESTAMP COMMENT '创建时间',
  `updated_at` DATETIME NOT NULL DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP COMMENT '更新时间',
  PRIMARY KEY (`id`),
  UNIQUE KEY `ix_salary_profiles_employee_id` (`employee_id`),
  CONSTRAINT `fk_salary_profiles_employee_id`
    FOREIGN KEY (`employee_id`) REFERENCES `employees` (`id`)
    ON DELETE CASCADE
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci
  COMMENT='员工薪资档案表，维护底薪、手工提成和独立加班费单价';

SET @has_payroll_commission_amount := (
  SELECT COUNT(*) FROM INFORMATION_SCHEMA.COLUMNS
  WHERE TABLE_SCHEMA = DATABASE() AND TABLE_NAME = 'payroll_results' AND COLUMN_NAME = 'commission_amount'
);
SET @ddl := IF(@has_payroll_commission_amount = 0,
  'ALTER TABLE `payroll_results` ADD COLUMN `commission_amount` FLOAT NOT NULL DEFAULT 0 COMMENT ''手工维护的提成费用'' AFTER `base_salary`',
  'SELECT 1'
);
PREPARE stmt FROM @ddl;
EXECUTE stmt;
DEALLOCATE PREPARE stmt;
