feat(G1,P16A,P16B): 收口主数据核心与节假日日历增强
这个提交包含在:
@@ -61,6 +61,10 @@ OCR_TIMEOUT_MS="5000"
|
||||
# ===== 发票验真(P6)=====
|
||||
INVOICE_VERIFICATION_ENABLED="false"
|
||||
# INVOICE_VERIFICATION_ENABLED 作为Env硬闸;在线灰度由 /api/system/feature-flags 管理
|
||||
|
||||
# ===== 请假日历增强(P16B)=====
|
||||
LEAVE_HOLIDAY_CALENDAR_ENABLED="false"
|
||||
# LEAVE_HOLIDAY_CALENDAR_ENABLED 作为Env硬闸;在线灰度由 /api/system/feature-flags 管理
|
||||
VERIFICATION_PROVIDER="mock" # mock|tax
|
||||
VERIFICATION_POLL_CRON="* * * * *"
|
||||
VERIFICATION_MAX_ATTEMPTS="3"
|
||||
|
||||
@@ -0,0 +1,91 @@
|
||||
-- CreateEnum
|
||||
CREATE TYPE "DocumentCategoryEntityType" AS ENUM ('reimbursement', 'leave', 'purchase_request', 'asset_card', 'general');
|
||||
|
||||
-- CreateTable
|
||||
CREATE TABLE "legal_entities" (
|
||||
"id" UUID NOT NULL,
|
||||
"code" TEXT NOT NULL,
|
||||
"name" TEXT NOT NULL,
|
||||
"short_name" TEXT,
|
||||
"currency_code" VARCHAR(8) NOT NULL DEFAULT 'CNY',
|
||||
"tax_no" TEXT,
|
||||
"enabled" BOOLEAN NOT NULL DEFAULT true,
|
||||
"archived_at" TIMESTAMP(3),
|
||||
"created_at" TIMESTAMP(3) NOT NULL DEFAULT CURRENT_TIMESTAMP,
|
||||
"created_by" UUID,
|
||||
"updated_at" TIMESTAMP(3) NOT NULL,
|
||||
"updated_by" UUID,
|
||||
|
||||
CONSTRAINT "legal_entities_pkey" PRIMARY KEY ("id")
|
||||
);
|
||||
|
||||
-- CreateTable
|
||||
CREATE TABLE "cost_centers" (
|
||||
"id" UUID NOT NULL,
|
||||
"legal_entity_id" UUID NOT NULL,
|
||||
"code" TEXT NOT NULL,
|
||||
"name" TEXT NOT NULL,
|
||||
"parent_id" UUID,
|
||||
"owner_employee_id" UUID,
|
||||
"enabled" BOOLEAN NOT NULL DEFAULT true,
|
||||
"archived_at" TIMESTAMP(3),
|
||||
"created_at" TIMESTAMP(3) NOT NULL DEFAULT CURRENT_TIMESTAMP,
|
||||
"created_by" UUID,
|
||||
"updated_at" TIMESTAMP(3) NOT NULL,
|
||||
"updated_by" UUID,
|
||||
|
||||
CONSTRAINT "cost_centers_pkey" PRIMARY KEY ("id")
|
||||
);
|
||||
|
||||
-- CreateTable
|
||||
CREATE TABLE "document_categories" (
|
||||
"id" UUID NOT NULL,
|
||||
"code" TEXT NOT NULL,
|
||||
"name" TEXT NOT NULL,
|
||||
"entity_type" "DocumentCategoryEntityType" NOT NULL,
|
||||
"sequence_prefix" TEXT NOT NULL,
|
||||
"number_length" INTEGER NOT NULL DEFAULT 4,
|
||||
"reset_period" "DocumentResetPeriod" NOT NULL,
|
||||
"default_workflow_key" TEXT,
|
||||
"enabled" BOOLEAN NOT NULL DEFAULT true,
|
||||
"archived_at" TIMESTAMP(3),
|
||||
"created_at" TIMESTAMP(3) NOT NULL DEFAULT CURRENT_TIMESTAMP,
|
||||
"created_by" UUID,
|
||||
"updated_at" TIMESTAMP(3) NOT NULL,
|
||||
"updated_by" UUID,
|
||||
|
||||
CONSTRAINT "document_categories_pkey" PRIMARY KEY ("id")
|
||||
);
|
||||
|
||||
-- CreateIndex
|
||||
CREATE UNIQUE INDEX "legal_entities_code_key" ON "legal_entities"("code");
|
||||
|
||||
-- CreateIndex
|
||||
CREATE INDEX "idx_legal_entities_status" ON "legal_entities"("enabled", "archived_at");
|
||||
|
||||
-- CreateIndex
|
||||
CREATE INDEX "idx_cost_centers_legal_entity_status" ON "cost_centers"("legal_entity_id", "enabled", "archived_at");
|
||||
|
||||
-- CreateIndex
|
||||
CREATE INDEX "idx_cost_centers_parent" ON "cost_centers"("parent_id");
|
||||
|
||||
-- CreateIndex
|
||||
CREATE INDEX "idx_cost_centers_owner" ON "cost_centers"("owner_employee_id");
|
||||
|
||||
-- CreateIndex
|
||||
CREATE UNIQUE INDEX "legal_entity_cost_center_code_ux" ON "cost_centers"("legal_entity_id", "code");
|
||||
|
||||
-- CreateIndex
|
||||
CREATE UNIQUE INDEX "document_categories_code_key" ON "document_categories"("code");
|
||||
|
||||
-- CreateIndex
|
||||
CREATE INDEX "idx_document_categories_entity_status" ON "document_categories"("entity_type", "enabled", "archived_at");
|
||||
|
||||
-- AddForeignKey
|
||||
ALTER TABLE "cost_centers" ADD CONSTRAINT "cost_centers_legal_entity_id_fkey" FOREIGN KEY ("legal_entity_id") REFERENCES "legal_entities"("id") ON DELETE RESTRICT ON UPDATE CASCADE;
|
||||
|
||||
-- AddForeignKey
|
||||
ALTER TABLE "cost_centers" ADD CONSTRAINT "cost_centers_parent_id_fkey" FOREIGN KEY ("parent_id") REFERENCES "cost_centers"("id") ON DELETE RESTRICT ON UPDATE CASCADE;
|
||||
|
||||
-- AddForeignKey
|
||||
ALTER TABLE "cost_centers" ADD CONSTRAINT "cost_centers_owner_employee_id_fkey" FOREIGN KEY ("owner_employee_id") REFERENCES "employees"("id") ON DELETE SET NULL ON UPDATE CASCADE;
|
||||
@@ -0,0 +1,71 @@
|
||||
-- CreateEnum
|
||||
CREATE TYPE "HolidayCalendarDayType" AS ENUM ('holiday', 'workday', 'adjusted_workday');
|
||||
|
||||
-- AlterTable
|
||||
ALTER TABLE "employees" ADD COLUMN "legal_entity_id" UUID;
|
||||
|
||||
-- AlterTable
|
||||
ALTER TABLE "legal_entities" ADD COLUMN "default_holiday_calendar_id" UUID;
|
||||
|
||||
-- CreateTable
|
||||
CREATE TABLE "holiday_calendars" (
|
||||
"id" UUID NOT NULL,
|
||||
"code" TEXT NOT NULL,
|
||||
"name" TEXT NOT NULL,
|
||||
"timezone" VARCHAR(64) NOT NULL DEFAULT 'Asia/Shanghai',
|
||||
"legal_entity_id" UUID,
|
||||
"enabled" BOOLEAN NOT NULL DEFAULT true,
|
||||
"archived_at" TIMESTAMP(3),
|
||||
"created_at" TIMESTAMP(3) NOT NULL DEFAULT CURRENT_TIMESTAMP,
|
||||
"created_by" UUID,
|
||||
"updated_at" TIMESTAMP(3) NOT NULL,
|
||||
"updated_by" UUID,
|
||||
|
||||
CONSTRAINT "holiday_calendars_pkey" PRIMARY KEY ("id")
|
||||
);
|
||||
|
||||
-- CreateTable
|
||||
CREATE TABLE "holiday_calendar_days" (
|
||||
"id" UUID NOT NULL,
|
||||
"calendar_id" UUID NOT NULL,
|
||||
"date" DATE NOT NULL,
|
||||
"day_type" "HolidayCalendarDayType" NOT NULL,
|
||||
"name" TEXT NOT NULL,
|
||||
"note" TEXT,
|
||||
"created_at" TIMESTAMP(3) NOT NULL DEFAULT CURRENT_TIMESTAMP,
|
||||
"created_by" UUID,
|
||||
"updated_at" TIMESTAMP(3) NOT NULL,
|
||||
"updated_by" UUID,
|
||||
|
||||
CONSTRAINT "holiday_calendar_days_pkey" PRIMARY KEY ("id")
|
||||
);
|
||||
|
||||
-- CreateIndex
|
||||
CREATE UNIQUE INDEX "holiday_calendars_code_key" ON "holiday_calendars"("code");
|
||||
|
||||
-- CreateIndex
|
||||
CREATE INDEX "idx_holiday_calendars_legal_entity_status" ON "holiday_calendars"("legal_entity_id", "enabled", "archived_at");
|
||||
|
||||
-- CreateIndex
|
||||
CREATE INDEX "idx_holiday_calendar_days_calendar_date" ON "holiday_calendar_days"("calendar_id", "date");
|
||||
|
||||
-- CreateIndex
|
||||
CREATE UNIQUE INDEX "holiday_calendar_day_ux" ON "holiday_calendar_days"("calendar_id", "date");
|
||||
|
||||
-- CreateIndex
|
||||
CREATE INDEX "idx_employees_legal_entity" ON "employees"("legal_entity_id");
|
||||
|
||||
-- CreateIndex
|
||||
CREATE INDEX "idx_legal_entities_default_calendar" ON "legal_entities"("default_holiday_calendar_id");
|
||||
|
||||
-- AddForeignKey
|
||||
ALTER TABLE "employees" ADD CONSTRAINT "employees_legal_entity_id_fkey" FOREIGN KEY ("legal_entity_id") REFERENCES "legal_entities"("id") ON DELETE SET NULL ON UPDATE CASCADE;
|
||||
|
||||
-- AddForeignKey
|
||||
ALTER TABLE "legal_entities" ADD CONSTRAINT "legal_entities_default_holiday_calendar_id_fkey" FOREIGN KEY ("default_holiday_calendar_id") REFERENCES "holiday_calendars"("id") ON DELETE SET NULL ON UPDATE CASCADE;
|
||||
|
||||
-- AddForeignKey
|
||||
ALTER TABLE "holiday_calendars" ADD CONSTRAINT "holiday_calendars_legal_entity_id_fkey" FOREIGN KEY ("legal_entity_id") REFERENCES "legal_entities"("id") ON DELETE SET NULL ON UPDATE CASCADE;
|
||||
|
||||
-- AddForeignKey
|
||||
ALTER TABLE "holiday_calendar_days" ADD CONSTRAINT "holiday_calendar_days_calendar_id_fkey" FOREIGN KEY ("calendar_id") REFERENCES "holiday_calendars"("id") ON DELETE CASCADE ON UPDATE CASCADE;
|
||||
+137
-3
@@ -90,6 +90,20 @@ enum DocumentResetPeriod {
|
||||
yearly
|
||||
}
|
||||
|
||||
enum DocumentCategoryEntityType {
|
||||
reimbursement
|
||||
leave
|
||||
purchase_request
|
||||
asset_card
|
||||
general
|
||||
}
|
||||
|
||||
enum HolidayCalendarDayType {
|
||||
holiday
|
||||
workday
|
||||
adjusted_workday
|
||||
}
|
||||
|
||||
enum WorkflowInstanceStatus {
|
||||
pending
|
||||
approved
|
||||
@@ -163,6 +177,7 @@ model Employee {
|
||||
phone String @unique
|
||||
email String @unique
|
||||
department_id String @db.Uuid
|
||||
legal_entity_id String? @db.Uuid
|
||||
title String
|
||||
direct_manager_id String? @db.Uuid
|
||||
hire_date DateTime @db.Date
|
||||
@@ -185,9 +200,10 @@ model Employee {
|
||||
updated_at DateTime @updatedAt
|
||||
updated_by String? @db.Uuid
|
||||
|
||||
department Department @relation(fields: [department_id], references: [id], onDelete: Restrict)
|
||||
direct_manager Employee? @relation("EmployeeToManager", fields: [direct_manager_id], references: [id], onDelete: Restrict)
|
||||
subordinates Employee[] @relation("EmployeeToManager")
|
||||
department Department @relation(fields: [department_id], references: [id], onDelete: Restrict)
|
||||
legal_entity LegalEntity? @relation(fields: [legal_entity_id], references: [id], onDelete: SetNull)
|
||||
direct_manager Employee? @relation("EmployeeToManager", fields: [direct_manager_id], references: [id], onDelete: Restrict)
|
||||
subordinates Employee[] @relation("EmployeeToManager")
|
||||
|
||||
roles EmployeeRole[]
|
||||
|
||||
@@ -203,6 +219,7 @@ model Employee {
|
||||
paid_reimbursements ReimbursementForm[] @relation("ReimbursementPaidBy")
|
||||
leave_requests LeaveRequest[]
|
||||
leave_ledgers LeaveLedger[]
|
||||
owned_cost_centers CostCenter[] @relation("CostCenterOwner")
|
||||
|
||||
owned_invoices InvoicePool[] @relation("InvoiceOwner")
|
||||
uploaded_invoices InvoicePool[] @relation("InvoiceUploader")
|
||||
@@ -220,6 +237,7 @@ model Employee {
|
||||
password_reset_codes PasswordResetCode[]
|
||||
|
||||
@@index([department_id])
|
||||
@@index([legal_entity_id], map: "idx_employees_legal_entity")
|
||||
@@index([direct_manager_id])
|
||||
@@map("employees")
|
||||
}
|
||||
@@ -371,6 +389,122 @@ model DocumentSequence {
|
||||
@@map("document_sequences")
|
||||
}
|
||||
|
||||
model LegalEntity {
|
||||
id String @id @default(uuid()) @db.Uuid
|
||||
code String @unique
|
||||
name String
|
||||
short_name String?
|
||||
currency_code String @default("CNY") @db.VarChar(8)
|
||||
tax_no String?
|
||||
default_holiday_calendar_id String? @db.Uuid
|
||||
enabled Boolean @default(true)
|
||||
archived_at DateTime?
|
||||
|
||||
created_at DateTime @default(now())
|
||||
created_by String? @db.Uuid
|
||||
updated_at DateTime @updatedAt
|
||||
updated_by String? @db.Uuid
|
||||
|
||||
default_holiday_calendar HolidayCalendar? @relation("LegalEntityDefaultHolidayCalendar", fields: [default_holiday_calendar_id], references: [id], onDelete: SetNull)
|
||||
cost_centers CostCenter[]
|
||||
employees Employee[]
|
||||
holiday_calendars HolidayCalendar[] @relation("HolidayCalendarLegalEntity")
|
||||
|
||||
@@index([enabled, archived_at], map: "idx_legal_entities_status")
|
||||
@@index([default_holiday_calendar_id], map: "idx_legal_entities_default_calendar")
|
||||
@@map("legal_entities")
|
||||
}
|
||||
|
||||
model CostCenter {
|
||||
id String @id @default(uuid()) @db.Uuid
|
||||
legal_entity_id String @db.Uuid
|
||||
code String
|
||||
name String
|
||||
parent_id String? @db.Uuid
|
||||
owner_employee_id String? @db.Uuid
|
||||
enabled Boolean @default(true)
|
||||
archived_at DateTime?
|
||||
|
||||
created_at DateTime @default(now())
|
||||
created_by String? @db.Uuid
|
||||
updated_at DateTime @updatedAt
|
||||
updated_by String? @db.Uuid
|
||||
|
||||
legal_entity LegalEntity @relation(fields: [legal_entity_id], references: [id], onDelete: Restrict)
|
||||
parent CostCenter? @relation("CostCenterToParent", fields: [parent_id], references: [id], onDelete: Restrict)
|
||||
children CostCenter[] @relation("CostCenterToParent")
|
||||
owner_employee Employee? @relation("CostCenterOwner", fields: [owner_employee_id], references: [id], onDelete: SetNull)
|
||||
|
||||
@@unique([legal_entity_id, code], map: "legal_entity_cost_center_code_ux")
|
||||
@@index([legal_entity_id, enabled, archived_at], map: "idx_cost_centers_legal_entity_status")
|
||||
@@index([parent_id], map: "idx_cost_centers_parent")
|
||||
@@index([owner_employee_id], map: "idx_cost_centers_owner")
|
||||
@@map("cost_centers")
|
||||
}
|
||||
|
||||
model DocumentCategory {
|
||||
id String @id @default(uuid()) @db.Uuid
|
||||
code String @unique
|
||||
name String
|
||||
entity_type DocumentCategoryEntityType
|
||||
sequence_prefix String
|
||||
number_length Int @default(4)
|
||||
reset_period DocumentResetPeriod
|
||||
default_workflow_key String?
|
||||
enabled Boolean @default(true)
|
||||
archived_at DateTime?
|
||||
|
||||
created_at DateTime @default(now())
|
||||
created_by String? @db.Uuid
|
||||
updated_at DateTime @updatedAt
|
||||
updated_by String? @db.Uuid
|
||||
|
||||
@@index([entity_type, enabled, archived_at], map: "idx_document_categories_entity_status")
|
||||
@@map("document_categories")
|
||||
}
|
||||
|
||||
model HolidayCalendar {
|
||||
id String @id @default(uuid()) @db.Uuid
|
||||
code String @unique
|
||||
name String
|
||||
timezone String @default("Asia/Shanghai") @db.VarChar(64)
|
||||
legal_entity_id String? @db.Uuid
|
||||
enabled Boolean @default(true)
|
||||
archived_at DateTime?
|
||||
|
||||
created_at DateTime @default(now())
|
||||
created_by String? @db.Uuid
|
||||
updated_at DateTime @updatedAt
|
||||
updated_by String? @db.Uuid
|
||||
|
||||
legal_entity LegalEntity? @relation("HolidayCalendarLegalEntity", fields: [legal_entity_id], references: [id], onDelete: SetNull)
|
||||
days HolidayCalendarDay[]
|
||||
default_for_legal_entities LegalEntity[] @relation("LegalEntityDefaultHolidayCalendar")
|
||||
|
||||
@@index([legal_entity_id, enabled, archived_at], map: "idx_holiday_calendars_legal_entity_status")
|
||||
@@map("holiday_calendars")
|
||||
}
|
||||
|
||||
model HolidayCalendarDay {
|
||||
id String @id @default(uuid()) @db.Uuid
|
||||
calendar_id String @db.Uuid
|
||||
date DateTime @db.Date
|
||||
day_type HolidayCalendarDayType
|
||||
name String
|
||||
note String?
|
||||
|
||||
created_at DateTime @default(now())
|
||||
created_by String? @db.Uuid
|
||||
updated_at DateTime @updatedAt
|
||||
updated_by String? @db.Uuid
|
||||
|
||||
calendar HolidayCalendar @relation(fields: [calendar_id], references: [id], onDelete: Cascade)
|
||||
|
||||
@@unique([calendar_id, date], map: "holiday_calendar_day_ux")
|
||||
@@index([calendar_id, date], map: "idx_holiday_calendar_days_calendar_date")
|
||||
@@map("holiday_calendar_days")
|
||||
}
|
||||
|
||||
model ReimbursementForm {
|
||||
id String @id @default(uuid()) @db.Uuid
|
||||
form_number String? @unique
|
||||
|
||||
@@ -26,6 +26,8 @@ const delegationRoutes = require("./routes/delegations");
|
||||
const auditRoutes = require("./routes/audit");
|
||||
const usersRoutes = require("./routes/users");
|
||||
const departmentsRoutes = require("./routes/departments");
|
||||
const masterDataRoutes = require("./routes/masterData");
|
||||
const masterDataHolidayCalendarsRoutes = require("./routes/masterDataHolidayCalendars");
|
||||
const employeesRoutes = require("./routes/employees");
|
||||
const expenseTypesRoutes = require("./routes/expenseTypes");
|
||||
const configReadRoutes = require("./routes/configRead");
|
||||
@@ -282,6 +284,8 @@ async function buildApp() {
|
||||
await app.register(usersRoutes, { prefix: "/api" });
|
||||
await app.register(employeesRoutes, { prefix: "/api" });
|
||||
await app.register(departmentsRoutes, { prefix: "/api" });
|
||||
await app.register(masterDataRoutes, { prefix: "/api" });
|
||||
await app.register(masterDataHolidayCalendarsRoutes, { prefix: "/api" });
|
||||
await app.register(expenseTypesRoutes, { prefix: "/api" });
|
||||
await app.register(configReadRoutes, { prefix: "/api" });
|
||||
await app.register(approvalRulesRoutes, { prefix: "/api" });
|
||||
|
||||
@@ -92,6 +92,7 @@ function getConfig() {
|
||||
ocrTimeoutMs: Number(process.env.OCR_TIMEOUT_MS ?? 5000),
|
||||
|
||||
invoiceVerificationEnabled: process.env.INVOICE_VERIFICATION_ENABLED === "true",
|
||||
leaveHolidayCalendarEnabled: process.env.LEAVE_HOLIDAY_CALENDAR_ENABLED === "true",
|
||||
invoiceVerificationFlagEnv: process.env.INVOICE_VERIFICATION_ENABLED ?? "false",
|
||||
verificationProvider: process.env.VERIFICATION_PROVIDER ?? "mock",
|
||||
verificationPollCron: process.env.VERIFICATION_POLL_CRON ?? "* * * * *",
|
||||
|
||||
@@ -16,6 +16,9 @@ const LEAVE_SELF_SERVICE_PERMISSIONS = [
|
||||
"leave.submit",
|
||||
];
|
||||
|
||||
const MASTERDATA_VIEW_PERMISSIONS = ["masterdata.view"];
|
||||
const MASTERDATA_MANAGE_PERMISSIONS = ["masterdata.manage"];
|
||||
|
||||
const EMPLOYEE_BASE_PERMISSIONS = [
|
||||
...EXPENSE_SELF_SERVICE_PERMISSIONS,
|
||||
...LEAVE_SELF_SERVICE_PERMISSIONS,
|
||||
@@ -68,6 +71,7 @@ const ROLE_PERMISSIONS = {
|
||||
],
|
||||
ceo: [
|
||||
...EMPLOYEE_BASE_PERMISSIONS,
|
||||
...MASTERDATA_VIEW_PERMISSIONS,
|
||||
"expense.approve",
|
||||
"expense.transfer",
|
||||
"expense.view_all",
|
||||
@@ -78,6 +82,7 @@ const ROLE_PERMISSIONS = {
|
||||
],
|
||||
finance: [
|
||||
...EMPLOYEE_BASE_PERMISSIONS,
|
||||
...MASTERDATA_VIEW_PERMISSIONS,
|
||||
"invoice.manage",
|
||||
"invoice.verify",
|
||||
"report.dashboard.view",
|
||||
@@ -88,6 +93,7 @@ const ROLE_PERMISSIONS = {
|
||||
],
|
||||
finance_mgr: [
|
||||
...EMPLOYEE_BASE_PERMISSIONS,
|
||||
...MASTERDATA_MANAGE_PERMISSIONS,
|
||||
"invoice.manage",
|
||||
"invoice.verify",
|
||||
"report.dashboard.view",
|
||||
|
||||
@@ -99,6 +99,7 @@ async function authPlugin(fastify) {
|
||||
status: true,
|
||||
token_version: true,
|
||||
department_id: true,
|
||||
legal_entity_id: true,
|
||||
roles: { select: { role_code: true } },
|
||||
},
|
||||
});
|
||||
@@ -126,6 +127,7 @@ async function authPlugin(fastify) {
|
||||
status: employee.status,
|
||||
token_version: employee.token_version,
|
||||
department_id: employee.department_id,
|
||||
legal_entity_id: employee.legal_entity_id ?? null,
|
||||
roleCodes,
|
||||
permissionCodes,
|
||||
};
|
||||
|
||||
+60
-1
@@ -3,9 +3,11 @@ const { z } = require("zod");
|
||||
const { AppError } = require("../utils/AppError");
|
||||
const { sendData } = require("../utils/reply");
|
||||
const { resolveActionableStep } = require("../utils/workflow");
|
||||
const { FEATURE_FLAG_KEYS, evaluateFeatureFlag } = require("../services/featureFlags");
|
||||
const {
|
||||
DEFAULT_ATTACHMENT_MIME_TYPES,
|
||||
calculateRequestedDays,
|
||||
calculateRequestedDaysByWorkingCalendar,
|
||||
createLeaveLedgerEntry,
|
||||
formatDateOnly,
|
||||
leaveRangesOverlap,
|
||||
@@ -165,6 +167,61 @@ function parseCreateBody(body) {
|
||||
};
|
||||
}
|
||||
|
||||
async function resolveRequestedDaysForCreate(fastify, employee, body) {
|
||||
if (!employee?.legal_entity_id) {
|
||||
return body.requestedDays;
|
||||
}
|
||||
|
||||
const featureFlag = await evaluateFeatureFlag({
|
||||
prisma: fastify.prisma,
|
||||
config: fastify.config,
|
||||
flagKey: FEATURE_FLAG_KEYS.leaveHolidayCalendar,
|
||||
departmentId: employee.department_id ?? null,
|
||||
strictDepartment: false,
|
||||
});
|
||||
|
||||
if (!featureFlag.enabled) {
|
||||
return body.requestedDays;
|
||||
}
|
||||
|
||||
const legalEntity = await fastify.prisma.legalEntity.findUnique({
|
||||
where: { id: employee.legal_entity_id },
|
||||
select: {
|
||||
default_holiday_calendar: {
|
||||
select: {
|
||||
id: true,
|
||||
archived_at: true,
|
||||
days: {
|
||||
where: {
|
||||
date: {
|
||||
gte: body.startDate,
|
||||
lte: body.endDate,
|
||||
},
|
||||
},
|
||||
select: {
|
||||
date: true,
|
||||
day_type: true,
|
||||
},
|
||||
},
|
||||
},
|
||||
},
|
||||
},
|
||||
});
|
||||
|
||||
const calendar = legalEntity?.default_holiday_calendar;
|
||||
if (!calendar || calendar.archived_at) {
|
||||
return body.requestedDays;
|
||||
}
|
||||
|
||||
return calculateRequestedDaysByWorkingCalendar({
|
||||
startDate: body.startDate,
|
||||
endDate: body.endDate,
|
||||
startSession: body.startSession,
|
||||
endSession: body.endSession,
|
||||
calendarDays: calendar.days,
|
||||
});
|
||||
}
|
||||
|
||||
async function collectCreatePayload(request) {
|
||||
if (typeof request.isMultipart === "function" && request.isMultipart()) {
|
||||
const fields = {};
|
||||
@@ -428,6 +485,8 @@ async function leaveRoutes(fastify) {
|
||||
request.employee.id,
|
||||
);
|
||||
|
||||
const requestedDays = await resolveRequestedDaysForCreate(fastify, request.employee, body);
|
||||
|
||||
const leave = await fastify.prisma.leaveRequest.create({
|
||||
data: {
|
||||
owner_id: request.employee.id,
|
||||
@@ -437,7 +496,7 @@ async function leaveRoutes(fastify) {
|
||||
end_date: body.endDate,
|
||||
start_session: body.startSession,
|
||||
end_session: body.endSession,
|
||||
requested_days: body.requestedDays,
|
||||
requested_days: requestedDays,
|
||||
reason: body.reason,
|
||||
attachment_storage_path: attachment?.storagePath ?? null,
|
||||
attachment_original_name: attachment?.originalName ?? null,
|
||||
|
||||
文件差异内容过多而无法显示
加载差异
@@ -0,0 +1,703 @@
|
||||
const { z } = require("zod");
|
||||
|
||||
const { AppError } = require("../utils/AppError");
|
||||
const { buildAuditLogData } = require("../utils/audit");
|
||||
const { sendData } = require("../utils/reply");
|
||||
|
||||
const BOOLEAN_QUERY_SCHEMA = z.enum(["0", "1", "true", "false"]).optional();
|
||||
const UUID_SCHEMA = z.string().uuid();
|
||||
const DATE_ONLY_SCHEMA = z.string().regex(/^\d{4}-\d{2}-\d{2}$/);
|
||||
const HOLIDAY_DAY_TYPE_VALUES = ["holiday", "workday", "adjusted_workday"];
|
||||
|
||||
const holidayCalendarListQuerySchema = z.object({
|
||||
includeArchived: BOOLEAN_QUERY_SCHEMA,
|
||||
enabled: BOOLEAN_QUERY_SCHEMA,
|
||||
legalEntityId: UUID_SCHEMA.optional(),
|
||||
});
|
||||
|
||||
const holidayCalendarCreateBodySchema = z
|
||||
.object({
|
||||
code: z.string().trim().min(2).max(64),
|
||||
name: z.string().trim().min(1).max(120),
|
||||
timezone: z.string().trim().min(1).max(64).optional(),
|
||||
legalEntityId: UUID_SCHEMA.nullable().optional(),
|
||||
enabled: z.boolean().optional(),
|
||||
})
|
||||
.strict();
|
||||
|
||||
const holidayCalendarPatchBodySchema = holidayCalendarCreateBodySchema.partial();
|
||||
|
||||
const holidayCalendarDaySchema = z
|
||||
.object({
|
||||
date: DATE_ONLY_SCHEMA,
|
||||
dayType: z.enum(HOLIDAY_DAY_TYPE_VALUES),
|
||||
name: z.string().trim().min(1).max(120),
|
||||
note: z.string().trim().max(500).nullable().optional(),
|
||||
})
|
||||
.strict();
|
||||
|
||||
const holidayCalendarDaysReplaceBodySchema = z
|
||||
.object({
|
||||
items: z.array(holidayCalendarDaySchema).max(500),
|
||||
})
|
||||
.strict();
|
||||
|
||||
function buildValidationError(details, statusCode = 400) {
|
||||
return new AppError({
|
||||
code: "VALID_001",
|
||||
message: "参数校验失败",
|
||||
statusCode,
|
||||
details,
|
||||
});
|
||||
}
|
||||
|
||||
function parseUuid(value) {
|
||||
const parsed = UUID_SCHEMA.safeParse(value);
|
||||
if (!parsed.success) {
|
||||
throw buildValidationError({ id: "invalid_uuid" });
|
||||
}
|
||||
return parsed.data;
|
||||
}
|
||||
|
||||
function parseBooleanQueryValue(rawValue) {
|
||||
if (rawValue == null) {
|
||||
return null;
|
||||
}
|
||||
return rawValue === "1" || rawValue === "true";
|
||||
}
|
||||
|
||||
function parseListQuery(query) {
|
||||
const parsed = holidayCalendarListQuerySchema.safeParse(query ?? {});
|
||||
if (!parsed.success) {
|
||||
throw buildValidationError(parsed.error.flatten());
|
||||
}
|
||||
|
||||
return {
|
||||
...parsed.data,
|
||||
includeArchived: parseBooleanQueryValue(parsed.data.includeArchived) ?? false,
|
||||
enabled: parseBooleanQueryValue(parsed.data.enabled),
|
||||
};
|
||||
}
|
||||
|
||||
function parseCreateBody(body) {
|
||||
const parsed = holidayCalendarCreateBodySchema.safeParse(body ?? {});
|
||||
if (!parsed.success) {
|
||||
throw buildValidationError(parsed.error.flatten());
|
||||
}
|
||||
return parsed.data;
|
||||
}
|
||||
|
||||
function parsePatchBody(body) {
|
||||
const parsed = holidayCalendarPatchBodySchema.safeParse(body ?? {});
|
||||
if (!parsed.success) {
|
||||
throw buildValidationError(parsed.error.flatten());
|
||||
}
|
||||
if (!Object.keys(parsed.data).length) {
|
||||
throw buildValidationError({ body: "empty" });
|
||||
}
|
||||
return parsed.data;
|
||||
}
|
||||
|
||||
function parseReplaceDaysBody(body) {
|
||||
const parsed = holidayCalendarDaysReplaceBodySchema.safeParse(body ?? {});
|
||||
if (!parsed.success) {
|
||||
throw buildValidationError(parsed.error.flatten());
|
||||
}
|
||||
|
||||
const seenDates = new Set();
|
||||
for (const item of parsed.data.items) {
|
||||
if (seenDates.has(item.date)) {
|
||||
throw buildValidationError({ date: "duplicate" }, 409);
|
||||
}
|
||||
seenDates.add(item.date);
|
||||
}
|
||||
|
||||
return parsed.data.items;
|
||||
}
|
||||
|
||||
function normalizeCalendarPayload(body) {
|
||||
return {
|
||||
code: typeof body.code === "string" ? body.code.trim().toUpperCase() : undefined,
|
||||
name: typeof body.name === "string" ? body.name.trim() : undefined,
|
||||
timezone: typeof body.timezone === "string" ? body.timezone.trim() : undefined,
|
||||
legalEntityId: Object.prototype.hasOwnProperty.call(body, "legalEntityId")
|
||||
? body.legalEntityId ?? null
|
||||
: undefined,
|
||||
enabled: body.enabled,
|
||||
};
|
||||
}
|
||||
|
||||
function normalizeHolidayCalendarDay(item) {
|
||||
return {
|
||||
date: item.date,
|
||||
dayType: item.dayType,
|
||||
name: item.name.trim(),
|
||||
note: item.note?.trim() ? item.note.trim() : null,
|
||||
};
|
||||
}
|
||||
|
||||
function toDateOnly(value) {
|
||||
return new Date(`${value}T00:00:00.000Z`);
|
||||
}
|
||||
|
||||
function mapHolidayCalendar(record) {
|
||||
const defaultCalendarId = record.legal_entity?.default_holiday_calendar_id ?? null;
|
||||
|
||||
return {
|
||||
id: record.id,
|
||||
code: record.code,
|
||||
name: record.name,
|
||||
timezone: record.timezone,
|
||||
legalEntityId: record.legal_entity_id ?? null,
|
||||
enabled: Boolean(record.enabled),
|
||||
archivedAt: record.archived_at?.toISOString?.() ?? null,
|
||||
createdAt: record.created_at?.toISOString?.() ?? null,
|
||||
updatedAt: record.updated_at?.toISOString?.() ?? null,
|
||||
daysCount:
|
||||
typeof record.days_count === "number"
|
||||
? record.days_count
|
||||
: typeof record._count?.days === "number"
|
||||
? record._count.days
|
||||
: 0,
|
||||
isDefaultForLegalEntity: defaultCalendarId === record.id,
|
||||
legalEntity: record.legal_entity
|
||||
? {
|
||||
id: record.legal_entity.id,
|
||||
code: record.legal_entity.code,
|
||||
name: record.legal_entity.name,
|
||||
}
|
||||
: null,
|
||||
};
|
||||
}
|
||||
|
||||
function mapHolidayCalendarDay(record) {
|
||||
return {
|
||||
id: record.id,
|
||||
date: record.date.toISOString().slice(0, 10),
|
||||
dayType: record.day_type,
|
||||
name: record.name,
|
||||
note: record.note ?? null,
|
||||
createdAt: record.created_at?.toISOString?.() ?? null,
|
||||
updatedAt: record.updated_at?.toISOString?.() ?? null,
|
||||
};
|
||||
}
|
||||
|
||||
async function ensureLegalEntityAvailable(tx, legalEntityId) {
|
||||
if (!legalEntityId) {
|
||||
return null;
|
||||
}
|
||||
|
||||
const legalEntity = await tx.legalEntity.findUnique({
|
||||
where: { id: legalEntityId },
|
||||
select: {
|
||||
id: true,
|
||||
code: true,
|
||||
name: true,
|
||||
archived_at: true,
|
||||
default_holiday_calendar_id: true,
|
||||
},
|
||||
});
|
||||
|
||||
if (!legalEntity) {
|
||||
throw buildValidationError({ legalEntityId: "not_found" });
|
||||
}
|
||||
|
||||
if (legalEntity.archived_at) {
|
||||
throw buildValidationError({ legalEntityId: "archived" }, 409);
|
||||
}
|
||||
|
||||
return legalEntity;
|
||||
}
|
||||
|
||||
function assertMasterDataViewPermission(fastify, request) {
|
||||
const canView =
|
||||
fastify.hasPermission(request.employee, "masterdata.view") ||
|
||||
fastify.hasPermission(request.employee, "masterdata.manage");
|
||||
|
||||
if (!canView) {
|
||||
throw new AppError({
|
||||
code: "PERM_001",
|
||||
message: "无权限",
|
||||
statusCode: 403,
|
||||
details: { permission: "masterdata.view" },
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
async function masterDataHolidayCalendarsRoutes(fastify) {
|
||||
fastify.get(
|
||||
"/master-data/holiday-calendars",
|
||||
{
|
||||
preHandler: fastify.authenticate,
|
||||
schema: {
|
||||
tags: ["master-data"],
|
||||
summary: "List holiday calendars",
|
||||
security: [{ bearerAuth: [] }],
|
||||
},
|
||||
},
|
||||
async (request, reply) => {
|
||||
assertMasterDataViewPermission(fastify, request);
|
||||
const query = parseListQuery(request.query);
|
||||
|
||||
const items = await fastify.prisma.holidayCalendar.findMany({
|
||||
where: {
|
||||
...(query.includeArchived ? {} : { archived_at: null }),
|
||||
...(query.enabled == null ? {} : { enabled: query.enabled }),
|
||||
...(query.legalEntityId ? { legal_entity_id: query.legalEntityId } : {}),
|
||||
},
|
||||
orderBy: [{ code: "asc" }],
|
||||
select: {
|
||||
id: true,
|
||||
code: true,
|
||||
name: true,
|
||||
timezone: true,
|
||||
legal_entity_id: true,
|
||||
enabled: true,
|
||||
archived_at: true,
|
||||
created_at: true,
|
||||
updated_at: true,
|
||||
legal_entity: {
|
||||
select: {
|
||||
id: true,
|
||||
code: true,
|
||||
name: true,
|
||||
default_holiday_calendar_id: true,
|
||||
},
|
||||
},
|
||||
_count: {
|
||||
select: { days: true },
|
||||
},
|
||||
},
|
||||
});
|
||||
|
||||
return sendData(reply, request, {
|
||||
includeArchived: query.includeArchived,
|
||||
items: items.map(mapHolidayCalendar),
|
||||
});
|
||||
},
|
||||
);
|
||||
|
||||
fastify.post(
|
||||
"/master-data/holiday-calendars",
|
||||
{
|
||||
preHandler: fastify.requirePermission("masterdata.manage"),
|
||||
schema: {
|
||||
tags: ["master-data"],
|
||||
summary: "Create holiday calendar",
|
||||
security: [{ bearerAuth: [] }],
|
||||
},
|
||||
},
|
||||
async (request, reply) => {
|
||||
const body = normalizeCalendarPayload(parseCreateBody(request.body));
|
||||
|
||||
try {
|
||||
const result = await fastify.prisma.$transaction(async (tx) => {
|
||||
const legalEntity = await ensureLegalEntityAvailable(tx, body.legalEntityId ?? null);
|
||||
const holidayCalendar = await tx.holidayCalendar.create({
|
||||
data: {
|
||||
code: body.code,
|
||||
name: body.name,
|
||||
timezone: body.timezone ?? "Asia/Shanghai",
|
||||
legal_entity_id: body.legalEntityId ?? null,
|
||||
enabled: body.enabled ?? true,
|
||||
created_by: request.employee.id,
|
||||
updated_by: request.employee.id,
|
||||
},
|
||||
select: {
|
||||
id: true,
|
||||
code: true,
|
||||
name: true,
|
||||
timezone: true,
|
||||
legal_entity_id: true,
|
||||
enabled: true,
|
||||
archived_at: true,
|
||||
created_at: true,
|
||||
updated_at: true,
|
||||
legal_entity: {
|
||||
select: {
|
||||
id: true,
|
||||
code: true,
|
||||
name: true,
|
||||
default_holiday_calendar_id: true,
|
||||
},
|
||||
},
|
||||
_count: {
|
||||
select: { days: true },
|
||||
},
|
||||
},
|
||||
});
|
||||
|
||||
if (legalEntity && !legalEntity.default_holiday_calendar_id) {
|
||||
await tx.legalEntity.update({
|
||||
where: { id: legalEntity.id },
|
||||
data: {
|
||||
default_holiday_calendar_id: holidayCalendar.id,
|
||||
updated_by: request.employee.id,
|
||||
},
|
||||
});
|
||||
holidayCalendar.legal_entity.default_holiday_calendar_id = holidayCalendar.id;
|
||||
}
|
||||
|
||||
await tx.auditLog.create({
|
||||
data: buildAuditLogData(request, {
|
||||
actorId: request.employee.id,
|
||||
action: "HOLIDAY_CALENDAR_CREATE",
|
||||
targetType: "holiday_calendar",
|
||||
targetId: holidayCalendar.id,
|
||||
extra: {
|
||||
code: holidayCalendar.code,
|
||||
legalEntityId: holidayCalendar.legal_entity_id,
|
||||
},
|
||||
}),
|
||||
});
|
||||
|
||||
return holidayCalendar;
|
||||
});
|
||||
|
||||
return sendData(reply, request, { holidayCalendar: mapHolidayCalendar(result) });
|
||||
} catch (error) {
|
||||
if (error?.code === "P2002") {
|
||||
throw buildValidationError({ code: "duplicate" }, 409);
|
||||
}
|
||||
throw error;
|
||||
}
|
||||
},
|
||||
);
|
||||
|
||||
fastify.patch(
|
||||
"/master-data/holiday-calendars/:id",
|
||||
{
|
||||
preHandler: fastify.requirePermission("masterdata.manage"),
|
||||
schema: {
|
||||
tags: ["master-data"],
|
||||
summary: "Patch holiday calendar",
|
||||
security: [{ bearerAuth: [] }],
|
||||
},
|
||||
},
|
||||
async (request, reply) => {
|
||||
const holidayCalendarId = parseUuid(request.params?.id);
|
||||
const body = normalizeCalendarPayload(parsePatchBody(request.body));
|
||||
|
||||
const current = await fastify.prisma.holidayCalendar.findUnique({
|
||||
where: { id: holidayCalendarId },
|
||||
select: {
|
||||
id: true,
|
||||
code: true,
|
||||
archived_at: true,
|
||||
},
|
||||
});
|
||||
|
||||
if (!current) {
|
||||
throw new AppError({ code: "SYS_404", message: "Not Found", statusCode: 404 });
|
||||
}
|
||||
|
||||
if (current.archived_at) {
|
||||
throw buildValidationError({ status: "archived" }, 409);
|
||||
}
|
||||
|
||||
try {
|
||||
const result = await fastify.prisma.$transaction(async (tx) => {
|
||||
if (body.legalEntityId !== undefined) {
|
||||
await ensureLegalEntityAvailable(tx, body.legalEntityId);
|
||||
}
|
||||
|
||||
const holidayCalendar = await tx.holidayCalendar.update({
|
||||
where: { id: holidayCalendarId },
|
||||
data: {
|
||||
...(body.code !== undefined ? { code: body.code } : {}),
|
||||
...(body.name !== undefined ? { name: body.name } : {}),
|
||||
...(body.timezone !== undefined ? { timezone: body.timezone } : {}),
|
||||
...(body.legalEntityId !== undefined ? { legal_entity_id: body.legalEntityId } : {}),
|
||||
...(body.enabled !== undefined ? { enabled: body.enabled } : {}),
|
||||
updated_by: request.employee.id,
|
||||
},
|
||||
select: {
|
||||
id: true,
|
||||
code: true,
|
||||
name: true,
|
||||
timezone: true,
|
||||
legal_entity_id: true,
|
||||
enabled: true,
|
||||
archived_at: true,
|
||||
created_at: true,
|
||||
updated_at: true,
|
||||
legal_entity: {
|
||||
select: {
|
||||
id: true,
|
||||
code: true,
|
||||
name: true,
|
||||
default_holiday_calendar_id: true,
|
||||
},
|
||||
},
|
||||
_count: {
|
||||
select: { days: true },
|
||||
},
|
||||
},
|
||||
});
|
||||
|
||||
await tx.auditLog.create({
|
||||
data: buildAuditLogData(request, {
|
||||
actorId: request.employee.id,
|
||||
action: "HOLIDAY_CALENDAR_UPDATE",
|
||||
targetType: "holiday_calendar",
|
||||
targetId: holidayCalendar.id,
|
||||
extra: {
|
||||
code: holidayCalendar.code,
|
||||
legalEntityId: holidayCalendar.legal_entity_id,
|
||||
},
|
||||
}),
|
||||
});
|
||||
|
||||
return holidayCalendar;
|
||||
});
|
||||
|
||||
return sendData(reply, request, { holidayCalendar: mapHolidayCalendar(result) });
|
||||
} catch (error) {
|
||||
if (error?.code === "P2002") {
|
||||
throw buildValidationError({ code: "duplicate" }, 409);
|
||||
}
|
||||
throw error;
|
||||
}
|
||||
},
|
||||
);
|
||||
|
||||
fastify.get(
|
||||
"/master-data/holiday-calendars/:id/days",
|
||||
{
|
||||
preHandler: fastify.authenticate,
|
||||
schema: {
|
||||
tags: ["master-data"],
|
||||
summary: "Get holiday calendar days",
|
||||
security: [{ bearerAuth: [] }],
|
||||
},
|
||||
},
|
||||
async (request, reply) => {
|
||||
assertMasterDataViewPermission(fastify, request);
|
||||
const holidayCalendarId = parseUuid(request.params?.id);
|
||||
|
||||
const holidayCalendar = await fastify.prisma.holidayCalendar.findUnique({
|
||||
where: { id: holidayCalendarId },
|
||||
select: { id: true },
|
||||
});
|
||||
|
||||
if (!holidayCalendar) {
|
||||
throw new AppError({ code: "SYS_404", message: "Not Found", statusCode: 404 });
|
||||
}
|
||||
|
||||
const items = await fastify.prisma.holidayCalendarDay.findMany({
|
||||
where: { calendar_id: holidayCalendarId },
|
||||
orderBy: [{ date: "asc" }, { created_at: "asc" }],
|
||||
select: {
|
||||
id: true,
|
||||
date: true,
|
||||
day_type: true,
|
||||
name: true,
|
||||
note: true,
|
||||
created_at: true,
|
||||
updated_at: true,
|
||||
},
|
||||
});
|
||||
|
||||
return sendData(reply, request, { items: items.map(mapHolidayCalendarDay) });
|
||||
},
|
||||
);
|
||||
|
||||
fastify.put(
|
||||
"/master-data/holiday-calendars/:id/days",
|
||||
{
|
||||
preHandler: fastify.requirePermission("masterdata.manage"),
|
||||
schema: {
|
||||
tags: ["master-data"],
|
||||
summary: "Replace holiday calendar days",
|
||||
security: [{ bearerAuth: [] }],
|
||||
},
|
||||
},
|
||||
async (request, reply) => {
|
||||
const holidayCalendarId = parseUuid(request.params?.id);
|
||||
const items = parseReplaceDaysBody(request.body).map(normalizeHolidayCalendarDay);
|
||||
const now = new Date();
|
||||
|
||||
const result = await fastify.prisma.$transaction(async (tx) => {
|
||||
const current = await tx.holidayCalendar.findUnique({
|
||||
where: { id: holidayCalendarId },
|
||||
select: {
|
||||
id: true,
|
||||
code: true,
|
||||
archived_at: true,
|
||||
},
|
||||
});
|
||||
|
||||
if (!current) {
|
||||
throw new AppError({ code: "SYS_404", message: "Not Found", statusCode: 404 });
|
||||
}
|
||||
|
||||
if (current.archived_at) {
|
||||
throw buildValidationError({ status: "archived" }, 409);
|
||||
}
|
||||
|
||||
await tx.holidayCalendarDay.deleteMany({
|
||||
where: { calendar_id: holidayCalendarId },
|
||||
});
|
||||
|
||||
if (items.length) {
|
||||
await tx.holidayCalendarDay.createMany({
|
||||
data: items.map((item) => ({
|
||||
calendar_id: holidayCalendarId,
|
||||
date: toDateOnly(item.date),
|
||||
day_type: item.dayType,
|
||||
name: item.name,
|
||||
note: item.note,
|
||||
created_at: now,
|
||||
created_by: request.employee.id,
|
||||
updated_at: now,
|
||||
updated_by: request.employee.id,
|
||||
})),
|
||||
});
|
||||
}
|
||||
|
||||
await tx.auditLog.create({
|
||||
data: buildAuditLogData(request, {
|
||||
actorId: request.employee.id,
|
||||
action: "HOLIDAY_CALENDAR_DAYS_REPLACE",
|
||||
targetType: "holiday_calendar",
|
||||
targetId: holidayCalendarId,
|
||||
extra: {
|
||||
count: items.length,
|
||||
code: current.code,
|
||||
},
|
||||
}),
|
||||
});
|
||||
|
||||
return current;
|
||||
});
|
||||
|
||||
return sendData(reply, request, {
|
||||
holidayCalendarId: result.id,
|
||||
replacedCount: items.length,
|
||||
});
|
||||
},
|
||||
);
|
||||
|
||||
fastify.post(
|
||||
"/master-data/holiday-calendars/:id/archive",
|
||||
{
|
||||
preHandler: fastify.requirePermission("masterdata.manage"),
|
||||
schema: {
|
||||
tags: ["master-data"],
|
||||
summary: "Archive holiday calendar",
|
||||
security: [{ bearerAuth: [] }],
|
||||
},
|
||||
},
|
||||
async (request, reply) => {
|
||||
const holidayCalendarId = parseUuid(request.params?.id);
|
||||
const now = new Date();
|
||||
|
||||
const result = await fastify.prisma.$transaction(async (tx) => {
|
||||
const current = await tx.holidayCalendar.findUnique({
|
||||
where: { id: holidayCalendarId },
|
||||
select: {
|
||||
id: true,
|
||||
code: true,
|
||||
name: true,
|
||||
timezone: true,
|
||||
legal_entity_id: true,
|
||||
enabled: true,
|
||||
archived_at: true,
|
||||
created_at: true,
|
||||
updated_at: true,
|
||||
legal_entity: {
|
||||
select: {
|
||||
id: true,
|
||||
code: true,
|
||||
name: true,
|
||||
default_holiday_calendar_id: true,
|
||||
},
|
||||
},
|
||||
_count: {
|
||||
select: { days: true },
|
||||
},
|
||||
},
|
||||
});
|
||||
|
||||
if (!current) {
|
||||
throw new AppError({ code: "SYS_404", message: "Not Found", statusCode: 404 });
|
||||
}
|
||||
|
||||
if (current.archived_at) {
|
||||
return { holidayCalendar: current, outcome: "already_archived" };
|
||||
}
|
||||
|
||||
const boundLegalEntity = await tx.legalEntity.findFirst({
|
||||
where: {
|
||||
default_holiday_calendar_id: holidayCalendarId,
|
||||
archived_at: null,
|
||||
},
|
||||
select: { id: true, code: true, name: true },
|
||||
});
|
||||
|
||||
if (boundLegalEntity) {
|
||||
throw buildValidationError(
|
||||
{
|
||||
holidayCalendar: "bound_as_default",
|
||||
legalEntityCode: boundLegalEntity.code,
|
||||
},
|
||||
409,
|
||||
);
|
||||
}
|
||||
|
||||
const holidayCalendar = await tx.holidayCalendar.update({
|
||||
where: { id: holidayCalendarId },
|
||||
data: {
|
||||
enabled: false,
|
||||
archived_at: now,
|
||||
updated_by: request.employee.id,
|
||||
},
|
||||
select: {
|
||||
id: true,
|
||||
code: true,
|
||||
name: true,
|
||||
timezone: true,
|
||||
legal_entity_id: true,
|
||||
enabled: true,
|
||||
archived_at: true,
|
||||
created_at: true,
|
||||
updated_at: true,
|
||||
legal_entity: {
|
||||
select: {
|
||||
id: true,
|
||||
code: true,
|
||||
name: true,
|
||||
default_holiday_calendar_id: true,
|
||||
},
|
||||
},
|
||||
_count: {
|
||||
select: { days: true },
|
||||
},
|
||||
},
|
||||
});
|
||||
|
||||
await tx.auditLog.create({
|
||||
data: buildAuditLogData(request, {
|
||||
actorId: request.employee.id,
|
||||
action: "HOLIDAY_CALENDAR_ARCHIVE",
|
||||
targetType: "holiday_calendar",
|
||||
targetId: holidayCalendar.id,
|
||||
extra: {
|
||||
code: holidayCalendar.code,
|
||||
legalEntityId: holidayCalendar.legal_entity_id,
|
||||
},
|
||||
}),
|
||||
});
|
||||
|
||||
return { holidayCalendar, outcome: "archived" };
|
||||
});
|
||||
|
||||
return sendData(reply, request, {
|
||||
holidayCalendar: mapHolidayCalendar(result.holidayCalendar),
|
||||
outcome: result.outcome,
|
||||
});
|
||||
},
|
||||
);
|
||||
}
|
||||
|
||||
module.exports = masterDataHolidayCalendarsRoutes;
|
||||
@@ -106,6 +106,83 @@ const DEFAULT_LEAVE_WORKFLOW_DEFINITION = {
|
||||
};
|
||||
|
||||
|
||||
const DEFAULT_DOCUMENT_CATEGORIES = [
|
||||
{
|
||||
code: "reimbursement_general",
|
||||
name: "通用报销单",
|
||||
entity_type: "reimbursement",
|
||||
sequence_prefix: "BX",
|
||||
number_length: 4,
|
||||
reset_period: "yearly",
|
||||
default_workflow_key: null,
|
||||
enabled: true,
|
||||
},
|
||||
{
|
||||
code: "leave_request",
|
||||
name: "请假申请单",
|
||||
entity_type: "leave",
|
||||
sequence_prefix: "JQ",
|
||||
number_length: 4,
|
||||
reset_period: "yearly",
|
||||
default_workflow_key: null,
|
||||
enabled: true,
|
||||
},
|
||||
{
|
||||
code: "purchase_general",
|
||||
name: "日常采购申请",
|
||||
entity_type: "purchase_request",
|
||||
sequence_prefix: "CG",
|
||||
number_length: 4,
|
||||
reset_period: "yearly",
|
||||
default_workflow_key: null,
|
||||
enabled: true,
|
||||
},
|
||||
{
|
||||
code: "asset_it",
|
||||
name: "IT 固资台账",
|
||||
entity_type: "asset_card",
|
||||
sequence_prefix: "ZC",
|
||||
number_length: 4,
|
||||
reset_period: "yearly",
|
||||
default_workflow_key: null,
|
||||
enabled: true,
|
||||
},
|
||||
{
|
||||
code: "general_record",
|
||||
name: "通用业务单据",
|
||||
entity_type: "general",
|
||||
sequence_prefix: "GEN",
|
||||
number_length: 4,
|
||||
reset_period: "yearly",
|
||||
default_workflow_key: null,
|
||||
enabled: true,
|
||||
},
|
||||
];
|
||||
|
||||
const DEFAULT_FEATURE_FLAGS = [
|
||||
{
|
||||
flag_key: "erp_sync",
|
||||
override_mode: "force_off",
|
||||
rollout_type: "global",
|
||||
department_ids: [],
|
||||
note: "bootstrap default: force_off",
|
||||
},
|
||||
{
|
||||
flag_key: "invoice_verification",
|
||||
override_mode: "force_off",
|
||||
rollout_type: "global",
|
||||
department_ids: [],
|
||||
note: "bootstrap default: force_off",
|
||||
},
|
||||
{
|
||||
flag_key: "leave_holiday_calendar",
|
||||
override_mode: "force_off",
|
||||
rollout_type: "global",
|
||||
department_ids: [],
|
||||
note: "bootstrap default: force_off",
|
||||
},
|
||||
];
|
||||
|
||||
const DEFAULT_LEAVE_TYPES = [
|
||||
{
|
||||
code: "annual_leave",
|
||||
@@ -216,6 +293,72 @@ async function seedDocumentSequence(prisma) {
|
||||
});
|
||||
}
|
||||
|
||||
async function seedDocumentCategories(prisma) {
|
||||
const now = new Date();
|
||||
|
||||
for (const item of DEFAULT_DOCUMENT_CATEGORIES) {
|
||||
await prisma.documentCategory.upsert({
|
||||
where: { code: item.code },
|
||||
update: {
|
||||
name: item.name,
|
||||
entity_type: item.entity_type,
|
||||
sequence_prefix: item.sequence_prefix,
|
||||
number_length: item.number_length,
|
||||
reset_period: item.reset_period,
|
||||
default_workflow_key: item.default_workflow_key,
|
||||
enabled: item.enabled,
|
||||
archived_at: null,
|
||||
updated_at: now,
|
||||
updated_by: null,
|
||||
},
|
||||
create: {
|
||||
code: item.code,
|
||||
name: item.name,
|
||||
entity_type: item.entity_type,
|
||||
sequence_prefix: item.sequence_prefix,
|
||||
number_length: item.number_length,
|
||||
reset_period: item.reset_period,
|
||||
default_workflow_key: item.default_workflow_key,
|
||||
enabled: item.enabled,
|
||||
archived_at: null,
|
||||
created_at: now,
|
||||
created_by: null,
|
||||
updated_at: now,
|
||||
updated_by: null,
|
||||
},
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
async function seedFeatureFlags(prisma) {
|
||||
const now = new Date();
|
||||
|
||||
for (const item of DEFAULT_FEATURE_FLAGS) {
|
||||
await prisma.featureFlag.upsert({
|
||||
where: { flag_key: item.flag_key },
|
||||
update: {
|
||||
override_mode: item.override_mode,
|
||||
rollout_type: item.rollout_type,
|
||||
department_ids: item.department_ids,
|
||||
note: item.note,
|
||||
updated_at: now,
|
||||
updated_by: null,
|
||||
},
|
||||
create: {
|
||||
flag_key: item.flag_key,
|
||||
override_mode: item.override_mode,
|
||||
rollout_type: item.rollout_type,
|
||||
department_ids: item.department_ids,
|
||||
note: item.note,
|
||||
created_at: now,
|
||||
created_by: null,
|
||||
updated_at: now,
|
||||
updated_by: null,
|
||||
},
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
async function seedLeaveTypes(prisma) {
|
||||
const now = new Date();
|
||||
|
||||
@@ -345,8 +488,10 @@ async function main() {
|
||||
await seedExpenseTypes(prisma);
|
||||
await seedApprovalRules(prisma);
|
||||
await seedDocumentSequence(prisma);
|
||||
await seedDocumentCategories(prisma);
|
||||
await seedWorkflowDefinition(prisma);
|
||||
await seedLeaveTypes(prisma);
|
||||
await seedFeatureFlags(prisma);
|
||||
|
||||
// eslint-disable-next-line no-console
|
||||
console.log("Seeded config data:");
|
||||
@@ -357,11 +502,15 @@ async function main() {
|
||||
// eslint-disable-next-line no-console
|
||||
console.log("- document sequence: reimbursement(reset_period=none)");
|
||||
// eslint-disable-next-line no-console
|
||||
console.log(`- document categories: ${DEFAULT_DOCUMENT_CATEGORIES.length} seeded`);
|
||||
// eslint-disable-next-line no-console
|
||||
console.log("- workflow definition: reimbursement v1 (1-step role=ceo)");
|
||||
// eslint-disable-next-line no-console
|
||||
console.log("- workflow definition: leave v1 (1-step department_manager)");
|
||||
// eslint-disable-next-line no-console
|
||||
console.log(`- leave types: ${DEFAULT_LEAVE_TYPES.length} seeded with default policies`);
|
||||
// eslint-disable-next-line no-console
|
||||
console.log(`- feature flags: ${DEFAULT_FEATURE_FLAGS.length} seeded`);
|
||||
} finally {
|
||||
await prisma.$disconnect();
|
||||
await pool.end();
|
||||
|
||||
@@ -33,6 +33,147 @@ async function ensureDepartment(prisma, payload) {
|
||||
});
|
||||
}
|
||||
|
||||
async function ensureLegalEntity(prisma, payload) {
|
||||
const now = new Date();
|
||||
const existing = await prisma.legalEntity.findUnique({
|
||||
where: { code: payload.code },
|
||||
select: { id: true },
|
||||
});
|
||||
|
||||
if (existing) {
|
||||
return prisma.legalEntity.update({
|
||||
where: { id: existing.id },
|
||||
data: {
|
||||
name: payload.name,
|
||||
short_name: payload.shortName ?? null,
|
||||
currency_code: payload.currencyCode,
|
||||
tax_no: payload.taxNo ?? null,
|
||||
enabled: true,
|
||||
archived_at: null,
|
||||
updated_at: now,
|
||||
},
|
||||
});
|
||||
}
|
||||
|
||||
return prisma.legalEntity.create({
|
||||
data: {
|
||||
code: payload.code,
|
||||
name: payload.name,
|
||||
short_name: payload.shortName ?? null,
|
||||
currency_code: payload.currencyCode,
|
||||
tax_no: payload.taxNo ?? null,
|
||||
enabled: true,
|
||||
archived_at: null,
|
||||
created_at: now,
|
||||
updated_at: now,
|
||||
},
|
||||
});
|
||||
}
|
||||
|
||||
async function ensureCostCenter(prisma, payload) {
|
||||
const now = new Date();
|
||||
const existing = await prisma.costCenter.findFirst({
|
||||
where: {
|
||||
legal_entity_id: payload.legalEntityId,
|
||||
code: payload.code,
|
||||
},
|
||||
select: { id: true },
|
||||
});
|
||||
|
||||
if (existing) {
|
||||
return prisma.costCenter.update({
|
||||
where: { id: existing.id },
|
||||
data: {
|
||||
name: payload.name,
|
||||
parent_id: payload.parentId ?? null,
|
||||
owner_employee_id: payload.ownerEmployeeId ?? null,
|
||||
enabled: true,
|
||||
archived_at: null,
|
||||
updated_at: now,
|
||||
},
|
||||
});
|
||||
}
|
||||
|
||||
return prisma.costCenter.create({
|
||||
data: {
|
||||
legal_entity_id: payload.legalEntityId,
|
||||
code: payload.code,
|
||||
name: payload.name,
|
||||
parent_id: payload.parentId ?? null,
|
||||
owner_employee_id: payload.ownerEmployeeId ?? null,
|
||||
enabled: true,
|
||||
archived_at: null,
|
||||
created_at: now,
|
||||
updated_at: now,
|
||||
},
|
||||
});
|
||||
}
|
||||
|
||||
async function ensureHolidayCalendar(prisma, payload) {
|
||||
const now = new Date();
|
||||
const existing = await prisma.holidayCalendar.findUnique({
|
||||
where: { code: payload.code },
|
||||
select: { id: true },
|
||||
});
|
||||
|
||||
const calendar = existing
|
||||
? await prisma.holidayCalendar.update({
|
||||
where: { id: existing.id },
|
||||
data: {
|
||||
name: payload.name,
|
||||
timezone: payload.timezone ?? "Asia/Shanghai",
|
||||
legal_entity_id: payload.legalEntityId ?? null,
|
||||
enabled: true,
|
||||
archived_at: null,
|
||||
updated_at: now,
|
||||
},
|
||||
})
|
||||
: await prisma.holidayCalendar.create({
|
||||
data: {
|
||||
code: payload.code,
|
||||
name: payload.name,
|
||||
timezone: payload.timezone ?? "Asia/Shanghai",
|
||||
legal_entity_id: payload.legalEntityId ?? null,
|
||||
enabled: true,
|
||||
archived_at: null,
|
||||
created_at: now,
|
||||
updated_at: now,
|
||||
},
|
||||
});
|
||||
|
||||
await prisma.holidayCalendarDay.deleteMany({
|
||||
where: { calendar_id: calendar.id },
|
||||
});
|
||||
|
||||
if (payload.days?.length) {
|
||||
await prisma.holidayCalendarDay.createMany({
|
||||
data: payload.days.map((item) => ({
|
||||
calendar_id: calendar.id,
|
||||
date: new Date(`${item.date}T00:00:00.000Z`),
|
||||
day_type: item.dayType,
|
||||
name: item.name,
|
||||
note: item.note ?? null,
|
||||
created_at: now,
|
||||
created_by: null,
|
||||
updated_at: now,
|
||||
updated_by: null,
|
||||
})),
|
||||
});
|
||||
}
|
||||
|
||||
if (payload.setAsDefault && payload.legalEntityId) {
|
||||
await prisma.legalEntity.update({
|
||||
where: { id: payload.legalEntityId },
|
||||
data: {
|
||||
default_holiday_calendar_id: calendar.id,
|
||||
updated_at: now,
|
||||
},
|
||||
});
|
||||
}
|
||||
|
||||
return calendar;
|
||||
}
|
||||
|
||||
async function ensureEmployee(prisma, payload) {
|
||||
const now = new Date();
|
||||
const passwordHash = await hashPassword(payload.password);
|
||||
@@ -50,6 +191,7 @@ async function ensureEmployee(prisma, payload) {
|
||||
name: payload.name,
|
||||
phone: payload.phone,
|
||||
department_id: payload.departmentId,
|
||||
legal_entity_id: payload.legalEntityId ?? null,
|
||||
title: payload.title,
|
||||
direct_manager_id: payload.directManagerId,
|
||||
hire_date: payload.hireDate,
|
||||
@@ -86,6 +228,7 @@ async function ensureEmployee(prisma, payload) {
|
||||
phone: payload.phone,
|
||||
email: payload.email,
|
||||
department_id: payload.departmentId,
|
||||
legal_entity_id: payload.legalEntityId ?? null,
|
||||
title: payload.title,
|
||||
direct_manager_id: payload.directManagerId,
|
||||
hire_date: payload.hireDate,
|
||||
@@ -141,6 +284,14 @@ async function main() {
|
||||
parent_id: rootDepartment.id,
|
||||
});
|
||||
|
||||
const legalEntity = await ensureLegalEntity(prisma, {
|
||||
code: "HYB_CN",
|
||||
name: "海音达科技有限公司",
|
||||
shortName: "海音达",
|
||||
currencyCode: "CNY",
|
||||
taxNo: null,
|
||||
});
|
||||
|
||||
const ceo = await ensureEmployee(prisma, {
|
||||
employeeNo: process.env.SEED_CEO_EMPLOYEE_NO ?? "E0001",
|
||||
name: "CEO",
|
||||
@@ -148,6 +299,7 @@ async function main() {
|
||||
email: process.env.SEED_CEO_EMAIL ?? "[email protected]",
|
||||
password: process.env.SEED_CEO_PASSWORD ?? "CeoPassword1234",
|
||||
departmentId: rootDepartment.id,
|
||||
legalEntityId: legalEntity.id,
|
||||
title: "总经理",
|
||||
directManagerId: null,
|
||||
roles: ["ceo", "employee"],
|
||||
@@ -161,6 +313,7 @@ async function main() {
|
||||
email: process.env.SEED_ADMIN_EMAIL ?? "[email protected]",
|
||||
password: process.env.SEED_ADMIN_PASSWORD ?? "AdminPassword1234",
|
||||
departmentId: managementDepartment.id,
|
||||
legalEntityId: legalEntity.id,
|
||||
title: "系统管理员",
|
||||
directManagerId: ceo.id,
|
||||
roles: ["admin", "employee"],
|
||||
@@ -174,6 +327,7 @@ async function main() {
|
||||
email: process.env.SEED_MANAGER_EMAIL ?? "[email protected]",
|
||||
password: process.env.SEED_MANAGER_PASSWORD ?? "ManagerPassword1234",
|
||||
departmentId: rdDepartment.id,
|
||||
legalEntityId: legalEntity.id,
|
||||
title: "研发经理",
|
||||
directManagerId: ceo.id,
|
||||
roles: ["manager", "employee"],
|
||||
@@ -187,6 +341,7 @@ async function main() {
|
||||
email: process.env.SEED_EMPLOYEE_EMAIL ?? "[email protected]",
|
||||
password: process.env.SEED_EMPLOYEE_PASSWORD ?? "EmployeePassword1234",
|
||||
departmentId: rdDepartment.id,
|
||||
legalEntityId: legalEntity.id,
|
||||
title: "研发工程师",
|
||||
directManagerId: manager.id,
|
||||
roles: ["employee"],
|
||||
@@ -200,6 +355,7 @@ async function main() {
|
||||
email: process.env.SEED_FINANCE_EMAIL ?? "[email protected]",
|
||||
password: process.env.SEED_FINANCE_PASSWORD ?? "FinancePassword1234",
|
||||
departmentId: financeDepartment.id,
|
||||
legalEntityId: legalEntity.id,
|
||||
title: "财务专员",
|
||||
directManagerId: ceo.id,
|
||||
roles: ["finance", "employee"],
|
||||
@@ -213,6 +369,7 @@ async function main() {
|
||||
email: process.env.SEED_FINANCE_MGR_EMAIL ?? "[email protected]",
|
||||
password: process.env.SEED_FINANCE_MGR_PASSWORD ?? "FinanceMgrPassword1234",
|
||||
departmentId: financeDepartment.id,
|
||||
legalEntityId: legalEntity.id,
|
||||
title: "财务主管",
|
||||
directManagerId: ceo.id,
|
||||
roles: ["finance", "finance_mgr", "employee"],
|
||||
@@ -226,6 +383,7 @@ async function main() {
|
||||
email: process.env.SEED_HR_EMAIL ?? "[email protected]",
|
||||
password: process.env.SEED_HR_PASSWORD ?? "HrPassword1234",
|
||||
departmentId: hrDepartment.id,
|
||||
legalEntityId: legalEntity.id,
|
||||
title: "人事专员",
|
||||
directManagerId: ceo.id,
|
||||
roles: ["hr"],
|
||||
@@ -239,12 +397,51 @@ async function main() {
|
||||
email: process.env.SEED_ADMINISTRATION_EMAIL ?? "[email protected]",
|
||||
password: process.env.SEED_ADMINISTRATION_PASSWORD ?? "AdministrationPassword1234",
|
||||
departmentId: administrationDepartment.id,
|
||||
legalEntityId: legalEntity.id,
|
||||
title: "行政专员",
|
||||
directManagerId: manager.id,
|
||||
roles: ["administration"],
|
||||
hireDate,
|
||||
});
|
||||
|
||||
const holidayCalendar = await ensureHolidayCalendar(prisma, {
|
||||
code: "HYB_CN_STD",
|
||||
name: "海音达默认日历",
|
||||
timezone: "Asia/Shanghai",
|
||||
legalEntityId: legalEntity.id,
|
||||
setAsDefault: true,
|
||||
days: [
|
||||
{ date: "2026-05-04", dayType: "holiday", name: "公司调休假" },
|
||||
{ date: "2026-05-05", dayType: "holiday", name: "公司调休假" },
|
||||
{ date: "2026-05-09", dayType: "adjusted_workday", name: "周末补班" },
|
||||
],
|
||||
});
|
||||
|
||||
await ensureCostCenter(prisma, {
|
||||
legalEntityId: legalEntity.id,
|
||||
code: "MGMT",
|
||||
name: "管理中心",
|
||||
ownerEmployeeId: admin.id,
|
||||
});
|
||||
await ensureCostCenter(prisma, {
|
||||
legalEntityId: legalEntity.id,
|
||||
code: "FIN",
|
||||
name: "财务中心",
|
||||
ownerEmployeeId: financeMgr.id,
|
||||
});
|
||||
await ensureCostCenter(prisma, {
|
||||
legalEntityId: legalEntity.id,
|
||||
code: "HR",
|
||||
name: "人力中心",
|
||||
ownerEmployeeId: hr.id,
|
||||
});
|
||||
await ensureCostCenter(prisma, {
|
||||
legalEntityId: legalEntity.id,
|
||||
code: "RD",
|
||||
name: "研发中心",
|
||||
ownerEmployeeId: manager.id,
|
||||
});
|
||||
|
||||
// eslint-disable-next-line no-console
|
||||
console.log("Seeded dev users:");
|
||||
// eslint-disable-next-line no-console
|
||||
@@ -263,6 +460,10 @@ async function main() {
|
||||
console.log(`- HR: ${hr.email} / ${process.env.SEED_HR_PASSWORD ?? "HrPassword1234"}`);
|
||||
// eslint-disable-next-line no-console
|
||||
console.log(`- Administration: ${administration.email} / ${process.env.SEED_ADMINISTRATION_PASSWORD ?? "AdministrationPassword1234"}`);
|
||||
// eslint-disable-next-line no-console
|
||||
console.log(`- Legal Entity: ${legalEntity.code} / ${legalEntity.name}`);
|
||||
// eslint-disable-next-line no-console
|
||||
console.log(`- HolidayCalendar: ${holidayCalendar.code} / ${holidayCalendar.name}`);
|
||||
} finally {
|
||||
await prisma.$disconnect();
|
||||
await pool.end();
|
||||
|
||||
@@ -1,6 +1,7 @@
|
||||
const FEATURE_FLAG_KEYS = {
|
||||
erpSync: "erp_sync",
|
||||
invoiceVerification: "invoice_verification",
|
||||
leaveHolidayCalendar: "leave_holiday_calendar",
|
||||
};
|
||||
|
||||
const FEATURE_FLAG_KEY_LIST = Object.freeze(Object.values(FEATURE_FLAG_KEYS));
|
||||
@@ -62,6 +63,10 @@ function resolveEnvGate(config, flagKey) {
|
||||
return Boolean(config.invoiceVerificationEnabled);
|
||||
}
|
||||
|
||||
if (flagKey === FEATURE_FLAG_KEYS.leaveHolidayCalendar) {
|
||||
return Boolean(config.leaveHolidayCalendarEnabled);
|
||||
}
|
||||
|
||||
return false;
|
||||
}
|
||||
|
||||
|
||||
@@ -82,6 +82,100 @@ function calculateRequestedDays({ startDate, endDate, startSession, endSession }
|
||||
return fromHalfDayUnits(endSlot - startSlot + 1);
|
||||
}
|
||||
|
||||
function isWeekendDate(dateValue) {
|
||||
const date = normalizeDateOnly(dateValue);
|
||||
const weekday = date.getUTCDay();
|
||||
return weekday === 0 || weekday === 6;
|
||||
}
|
||||
|
||||
function buildHolidayCalendarDayMap(calendarDays = []) {
|
||||
const map = new Map();
|
||||
for (const item of calendarDays) {
|
||||
const key = formatDateOnly(item.date);
|
||||
if (key) {
|
||||
map.set(key, item.day_type ?? item.dayType ?? null);
|
||||
}
|
||||
}
|
||||
return map;
|
||||
}
|
||||
|
||||
function isWorkingDateByCalendar(dateValue, calendarDayMap) {
|
||||
const dateKey = formatDateOnly(dateValue);
|
||||
const configuredType = dateKey ? calendarDayMap.get(dateKey) ?? null : null;
|
||||
|
||||
if (configuredType === "holiday") {
|
||||
return false;
|
||||
}
|
||||
|
||||
if (configuredType === "workday" || configuredType === "adjusted_workday") {
|
||||
return true;
|
||||
}
|
||||
|
||||
return !isWeekendDate(dateValue);
|
||||
}
|
||||
|
||||
function countHalfDayUnitsForDate({ date, startDate, endDate, startSession, endSession }) {
|
||||
const normalizedDate = formatDateOnly(date);
|
||||
const startDateOnly = formatDateOnly(startDate);
|
||||
const endDateOnly = formatDateOnly(endDate);
|
||||
|
||||
if (normalizedDate === startDateOnly && normalizedDate === endDateOnly) {
|
||||
return toHalfDaySlot(endDate, endSession) - toHalfDaySlot(startDate, startSession) + 1;
|
||||
}
|
||||
|
||||
if (normalizedDate === startDateOnly) {
|
||||
return startSession === "pm" ? 1 : 2;
|
||||
}
|
||||
|
||||
if (normalizedDate === endDateOnly) {
|
||||
return endSession === "am" ? 1 : 2;
|
||||
}
|
||||
|
||||
return 2;
|
||||
}
|
||||
|
||||
function calculateRequestedDaysByWorkingCalendar({
|
||||
startDate,
|
||||
endDate,
|
||||
startSession,
|
||||
endSession,
|
||||
calendarDays = [],
|
||||
}) {
|
||||
const startSlot = toHalfDaySlot(startDate, startSession);
|
||||
const endSlot = toHalfDaySlot(endDate, endSession);
|
||||
|
||||
if (endSlot < startSlot) {
|
||||
throw buildLeaveValidationError({ leave: "invalid_range" });
|
||||
}
|
||||
|
||||
const calendarDayMap = buildHolidayCalendarDayMap(calendarDays);
|
||||
const current = normalizeDateOnly(startDate);
|
||||
const finalDate = normalizeDateOnly(endDate);
|
||||
let cursor = current;
|
||||
let totalUnits = 0;
|
||||
|
||||
while (cursor.getTime() <= finalDate.getTime()) {
|
||||
if (isWorkingDateByCalendar(cursor, calendarDayMap)) {
|
||||
totalUnits += countHalfDayUnitsForDate({
|
||||
date: cursor,
|
||||
startDate,
|
||||
endDate,
|
||||
startSession,
|
||||
endSession,
|
||||
});
|
||||
}
|
||||
|
||||
cursor = new Date(`${formatDateOnly(cursor)}T00:00:00.000Z`);
|
||||
cursor.setUTCDate(cursor.getUTCDate() + 1);
|
||||
}
|
||||
|
||||
if (totalUnits <= 0) {
|
||||
throw buildLeaveValidationError({ leave: "non_working_range" });
|
||||
}
|
||||
|
||||
return fromHalfDayUnits(totalUnits);
|
||||
}
|
||||
|
||||
function leaveRangesOverlap(left, right) {
|
||||
const leftStart = toHalfDaySlot(left.startDate, left.startSession);
|
||||
const leftEnd = toHalfDaySlot(left.endDate, left.endSession);
|
||||
@@ -478,6 +572,7 @@ async function persistLeaveAttachment({ config, employeeId, filePart }) {
|
||||
module.exports = {
|
||||
DEFAULT_ATTACHMENT_MIME_TYPES,
|
||||
calculateRequestedDays,
|
||||
calculateRequestedDaysByWorkingCalendar,
|
||||
createLeaveLedgerEntry,
|
||||
consumeReservedLeave,
|
||||
currentLeavePeriod,
|
||||
|
||||
@@ -21,6 +21,14 @@ describe("Permission Constants", () => {
|
||||
expect(hasPermission(resolvePermissionsForRoles(["hr"]), "leave.approve")).toBe(false);
|
||||
});
|
||||
|
||||
|
||||
it("grants master data permissions to finance and finance manager roles", () => {
|
||||
expect(hasPermission(resolvePermissionsForRoles(["finance"]), "masterdata.view")).toBe(true);
|
||||
expect(hasPermission(resolvePermissionsForRoles(["finance"]), "masterdata.manage")).toBe(false);
|
||||
expect(hasPermission(resolvePermissionsForRoles(["finance_mgr"]), "masterdata.manage")).toBe(true);
|
||||
expect(hasPermission(resolvePermissionsForRoles(["ceo"]), "masterdata.view")).toBe(true);
|
||||
});
|
||||
|
||||
it("grants hr leave view-all and manage permissions", () => {
|
||||
const hrPermissions = resolvePermissionsForRoles(["hr"]);
|
||||
|
||||
|
||||
@@ -39,7 +39,7 @@ describe("evaluateFeatureFlag", () => {
|
||||
it("returns env_hard_off when env gate is closed", async () => {
|
||||
const result = await evaluateFeatureFlag({
|
||||
prisma: buildPrisma(),
|
||||
config: { erpSyncEnabled: false, invoiceVerificationEnabled: true },
|
||||
config: { erpSyncEnabled: false, invoiceVerificationEnabled: true, leaveHolidayCalendarEnabled: true },
|
||||
flagKey: FEATURE_FLAG_KEYS.erpSync,
|
||||
});
|
||||
|
||||
@@ -50,7 +50,7 @@ describe("evaluateFeatureFlag", () => {
|
||||
it("returns missing_flag_record when record does not exist", async () => {
|
||||
const result = await evaluateFeatureFlag({
|
||||
prisma: buildPrisma(),
|
||||
config: { erpSyncEnabled: true, invoiceVerificationEnabled: true },
|
||||
config: { erpSyncEnabled: true, invoiceVerificationEnabled: true, leaveHolidayCalendarEnabled: true },
|
||||
flagKey: FEATURE_FLAG_KEYS.erpSync,
|
||||
});
|
||||
|
||||
@@ -68,7 +68,7 @@ describe("evaluateFeatureFlag", () => {
|
||||
|
||||
const result = await evaluateFeatureFlag({
|
||||
prisma,
|
||||
config: { erpSyncEnabled: true, invoiceVerificationEnabled: true },
|
||||
config: { erpSyncEnabled: true, invoiceVerificationEnabled: true, leaveHolidayCalendarEnabled: true },
|
||||
flagKey: FEATURE_FLAG_KEYS.erpSync,
|
||||
});
|
||||
|
||||
@@ -87,7 +87,7 @@ describe("evaluateFeatureFlag", () => {
|
||||
|
||||
const result = await evaluateFeatureFlag({
|
||||
prisma,
|
||||
config: { erpSyncEnabled: true, invoiceVerificationEnabled: true },
|
||||
config: { erpSyncEnabled: true, invoiceVerificationEnabled: true, leaveHolidayCalendarEnabled: true },
|
||||
flagKey: FEATURE_FLAG_KEYS.erpSync,
|
||||
});
|
||||
|
||||
@@ -106,14 +106,14 @@ describe("evaluateFeatureFlag", () => {
|
||||
|
||||
const missingDepartment = await evaluateFeatureFlag({
|
||||
prisma,
|
||||
config: { erpSyncEnabled: true, invoiceVerificationEnabled: true },
|
||||
config: { erpSyncEnabled: true, invoiceVerificationEnabled: true, leaveHolidayCalendarEnabled: true },
|
||||
flagKey: FEATURE_FLAG_KEYS.erpSync,
|
||||
strictDepartment: true,
|
||||
});
|
||||
|
||||
const blockedDepartment = await evaluateFeatureFlag({
|
||||
prisma,
|
||||
config: { erpSyncEnabled: true, invoiceVerificationEnabled: true },
|
||||
config: { erpSyncEnabled: true, invoiceVerificationEnabled: true, leaveHolidayCalendarEnabled: true },
|
||||
flagKey: FEATURE_FLAG_KEYS.erpSync,
|
||||
departmentId: "dept-b",
|
||||
strictDepartment: true,
|
||||
@@ -121,7 +121,7 @@ describe("evaluateFeatureFlag", () => {
|
||||
|
||||
const allowedDepartment = await evaluateFeatureFlag({
|
||||
prisma,
|
||||
config: { erpSyncEnabled: true, invoiceVerificationEnabled: true },
|
||||
config: { erpSyncEnabled: true, invoiceVerificationEnabled: true, leaveHolidayCalendarEnabled: true },
|
||||
flagKey: FEATURE_FLAG_KEYS.erpSync,
|
||||
departmentId: "dept-a",
|
||||
strictDepartment: true,
|
||||
@@ -144,7 +144,7 @@ describe("evaluateFeatureFlag", () => {
|
||||
|
||||
const result = await evaluateFeatureFlag({
|
||||
prisma,
|
||||
config: { erpSyncEnabled: true, invoiceVerificationEnabled: true },
|
||||
config: { erpSyncEnabled: true, invoiceVerificationEnabled: true, leaveHolidayCalendarEnabled: true },
|
||||
flagKey: FEATURE_FLAG_KEYS.invoiceVerification,
|
||||
strictDepartment: false,
|
||||
});
|
||||
@@ -164,7 +164,7 @@ describe("evaluateFeatureFlag", () => {
|
||||
|
||||
const result = await evaluateFeatureFlag({
|
||||
prisma,
|
||||
config: { erpSyncEnabled: true, invoiceVerificationEnabled: true },
|
||||
config: { erpSyncEnabled: true, invoiceVerificationEnabled: true, leaveHolidayCalendarEnabled: true },
|
||||
flagKey: FEATURE_FLAG_KEYS.invoiceVerification,
|
||||
strictDepartment: true,
|
||||
});
|
||||
@@ -174,6 +174,19 @@ describe("evaluateFeatureFlag", () => {
|
||||
});
|
||||
});
|
||||
|
||||
describe("leave holiday calendar flag", () => {
|
||||
it("uses the dedicated env gate", async () => {
|
||||
const result = await evaluateFeatureFlag({
|
||||
prisma: buildPrisma(),
|
||||
config: { erpSyncEnabled: true, invoiceVerificationEnabled: true, leaveHolidayCalendarEnabled: false },
|
||||
flagKey: FEATURE_FLAG_KEYS.leaveHolidayCalendar,
|
||||
});
|
||||
|
||||
expect(result.enabled).toBe(false);
|
||||
expect(result.reason).toBe("env_hard_off");
|
||||
});
|
||||
});
|
||||
|
||||
describe("listFeatureFlags", () => {
|
||||
it("returns all known keys even if part of records are missing", async () => {
|
||||
const prisma = buildPrisma({
|
||||
@@ -188,13 +201,14 @@ describe("listFeatureFlags", () => {
|
||||
invoiceVerificationEnabled: true,
|
||||
});
|
||||
|
||||
expect(items).toHaveLength(2);
|
||||
expect(items).toHaveLength(3);
|
||||
expect(items.map((item) => item.flagKey).sort()).toEqual([
|
||||
FEATURE_FLAG_KEYS.erpSync,
|
||||
FEATURE_FLAG_KEYS.invoiceVerification,
|
||||
FEATURE_FLAG_KEYS.leaveHolidayCalendar,
|
||||
]);
|
||||
|
||||
const missingItem = items.find((item) => item.flagKey === FEATURE_FLAG_KEYS.invoiceVerification);
|
||||
const missingItem = items.find((item) => item.flagKey === FEATURE_FLAG_KEYS.leaveHolidayCalendar);
|
||||
expect(missingItem.id).toBeNull();
|
||||
expect(missingItem.effectiveEnabled).toBe(false);
|
||||
});
|
||||
|
||||
@@ -13,7 +13,7 @@ describe("FeatureFlags Service", () => {
|
||||
it("returns env_hard_off when config disables it globally", async () => {
|
||||
const result = await featureFlags.evaluateFeatureFlag({
|
||||
prisma: {},
|
||||
config: { invoiceVerificationEnabled: false },
|
||||
config: { invoiceVerificationEnabled: false, leaveHolidayCalendarEnabled: true },
|
||||
flagKey: featureFlags.FEATURE_FLAG_KEYS.invoiceVerification,
|
||||
});
|
||||
expect(result.enabled).toBe(false);
|
||||
@@ -34,7 +34,7 @@ describe("FeatureFlags Service", () => {
|
||||
|
||||
const result = await featureFlags.evaluateFeatureFlag({
|
||||
prisma: mockPrisma,
|
||||
config: { invoiceVerificationEnabled: true },
|
||||
config: { invoiceVerificationEnabled: true, leaveHolidayCalendarEnabled: true },
|
||||
flagKey: featureFlags.FEATURE_FLAG_KEYS.invoiceVerification,
|
||||
});
|
||||
|
||||
@@ -56,7 +56,7 @@ describe("FeatureFlags Service", () => {
|
||||
|
||||
const result = await featureFlags.evaluateFeatureFlag({
|
||||
prisma: mockPrisma,
|
||||
config: { invoiceVerificationEnabled: true },
|
||||
config: { invoiceVerificationEnabled: true, leaveHolidayCalendarEnabled: true },
|
||||
flagKey: featureFlags.FEATURE_FLAG_KEYS.invoiceVerification,
|
||||
departmentId: "dep_B",
|
||||
strictDepartment: true
|
||||
@@ -80,7 +80,7 @@ describe("FeatureFlags Service", () => {
|
||||
|
||||
const result = await featureFlags.evaluateFeatureFlag({
|
||||
prisma: mockPrisma,
|
||||
config: { invoiceVerificationEnabled: true },
|
||||
config: { invoiceVerificationEnabled: true, leaveHolidayCalendarEnabled: true },
|
||||
flagKey: featureFlags.FEATURE_FLAG_KEYS.invoiceVerification,
|
||||
departmentId: "dep_B",
|
||||
});
|
||||
|
||||
@@ -1,5 +1,6 @@
|
||||
const {
|
||||
calculateRequestedDays,
|
||||
calculateRequestedDaysByWorkingCalendar,
|
||||
leaveRangesOverlap,
|
||||
summarizeLeaveLedgerEntries,
|
||||
} = require("../../../src/services/leave");
|
||||
@@ -49,6 +50,54 @@ describe("Leave Service", () => {
|
||||
});
|
||||
});
|
||||
|
||||
describe("calculateRequestedDaysByWorkingCalendar", () => {
|
||||
it("skips weekend days by default and respects adjusted workdays", () => {
|
||||
expect(
|
||||
calculateRequestedDaysByWorkingCalendar({
|
||||
startDate: "2026-03-20",
|
||||
endDate: "2026-03-22",
|
||||
startSession: "am",
|
||||
endSession: "pm",
|
||||
calendarDays: [],
|
||||
}),
|
||||
).toBe(1);
|
||||
|
||||
expect(
|
||||
calculateRequestedDaysByWorkingCalendar({
|
||||
startDate: "2026-03-20",
|
||||
endDate: "2026-03-22",
|
||||
startSession: "am",
|
||||
endSession: "pm",
|
||||
calendarDays: [{ date: "2026-03-21", day_type: "adjusted_workday" }],
|
||||
}),
|
||||
).toBe(2);
|
||||
});
|
||||
|
||||
it("skips configured holidays inside a weekday span", () => {
|
||||
expect(
|
||||
calculateRequestedDaysByWorkingCalendar({
|
||||
startDate: "2026-03-16",
|
||||
endDate: "2026-03-17",
|
||||
startSession: "am",
|
||||
endSession: "pm",
|
||||
calendarDays: [{ date: "2026-03-17", day_type: "holiday" }],
|
||||
}),
|
||||
).toBe(1);
|
||||
});
|
||||
|
||||
it("rejects ranges that become fully non-working after calendar adjustment", () => {
|
||||
expect(() =>
|
||||
calculateRequestedDaysByWorkingCalendar({
|
||||
startDate: "2026-03-21",
|
||||
endDate: "2026-03-22",
|
||||
startSession: "am",
|
||||
endSession: "pm",
|
||||
calendarDays: [],
|
||||
}),
|
||||
).toThrow(/参数校验失败/);
|
||||
});
|
||||
});
|
||||
|
||||
describe("leaveRangesOverlap", () => {
|
||||
it("detects overlapping half-day ranges", () => {
|
||||
expect(
|
||||
|
||||
在新工单中引用
屏蔽一个用户