@azlib/cms 0.4.0 → 0.6.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +132 -42
- package/dist/index.cjs +3500 -47
- package/dist/index.d.cts +885 -1
- package/dist/index.d.cts.map +1 -1
- package/dist/index.d.mts +885 -1
- package/dist/index.d.mts.map +1 -1
- package/dist/index.mjs +3444 -48
- package/dist/index.mjs.map +1 -1
- package/package.json +3 -2
package/dist/index.mjs
CHANGED
|
@@ -1,3 +1,4 @@
|
|
|
1
|
+
import ExcelJS from "exceljs";
|
|
1
2
|
//#region src/content/schema.ts
|
|
2
3
|
const fields = {
|
|
3
4
|
text(options) {
|
|
@@ -2856,7 +2857,7 @@ var EcommerceService = class {
|
|
|
2856
2857
|
};
|
|
2857
2858
|
//#endregion
|
|
2858
2859
|
//#region src/plugins/ecommerce/routes.ts
|
|
2859
|
-
function json(data, status = 200) {
|
|
2860
|
+
function json$2(data, status = 200) {
|
|
2860
2861
|
return new Response(JSON.stringify(data), {
|
|
2861
2862
|
status,
|
|
2862
2863
|
headers: {
|
|
@@ -2865,11 +2866,11 @@ function json(data, status = 200) {
|
|
|
2865
2866
|
}
|
|
2866
2867
|
});
|
|
2867
2868
|
}
|
|
2868
|
-
function badRequest(message) {
|
|
2869
|
-
return json({ error: message }, 400);
|
|
2869
|
+
function badRequest$2(message) {
|
|
2870
|
+
return json$2({ error: message }, 400);
|
|
2870
2871
|
}
|
|
2871
|
-
function notFound(message) {
|
|
2872
|
-
return json({ error: message }, 404);
|
|
2872
|
+
function notFound$2(message) {
|
|
2873
|
+
return json$2({ error: message }, 404);
|
|
2873
2874
|
}
|
|
2874
2875
|
function registerEcommerceRoutes(ctx, service, options = {}) {
|
|
2875
2876
|
const prefix = (options.apiPrefix ?? "/api/ecommerce").replace(/\/+$/, "");
|
|
@@ -2892,7 +2893,7 @@ function registerEcommerceRoutes(ctx, service, options = {}) {
|
|
|
2892
2893
|
const offsetStr = url.searchParams.get("offset");
|
|
2893
2894
|
const limit = limitStr ? parseInt(limitStr, 10) : 20;
|
|
2894
2895
|
const offset = offsetStr ? parseInt(offsetStr, 10) : 0;
|
|
2895
|
-
return json(await service.listProducts({
|
|
2896
|
+
return json$2(await service.listProducts({
|
|
2896
2897
|
categorySlug,
|
|
2897
2898
|
categoryId,
|
|
2898
2899
|
tagSlug,
|
|
@@ -2908,7 +2909,7 @@ function registerEcommerceRoutes(ctx, service, options = {}) {
|
|
|
2908
2909
|
offset
|
|
2909
2910
|
}));
|
|
2910
2911
|
} catch (err) {
|
|
2911
|
-
return badRequest(err instanceof Error ? err.message : String(err));
|
|
2912
|
+
return badRequest$2(err instanceof Error ? err.message : String(err));
|
|
2912
2913
|
}
|
|
2913
2914
|
});
|
|
2914
2915
|
ctx.registerRoute("GET", `${prefix}/products/:id`, async (_req, { params, url }) => {
|
|
@@ -2920,32 +2921,32 @@ function registerEcommerceRoutes(ctx, service, options = {}) {
|
|
|
2920
2921
|
product = await service.getProduct(id);
|
|
2921
2922
|
if (!product) product = await service.getProductBySlug(id);
|
|
2922
2923
|
}
|
|
2923
|
-
if (!product) return notFound(`Product '${id}' not found`);
|
|
2924
|
-
return json(product);
|
|
2924
|
+
if (!product) return notFound$2(`Product '${id}' not found`);
|
|
2925
|
+
return json$2(product);
|
|
2925
2926
|
});
|
|
2926
2927
|
ctx.registerRoute("POST", `${prefix}/products`, async (req) => {
|
|
2927
2928
|
try {
|
|
2928
2929
|
const body = await req.json();
|
|
2929
|
-
if (!body.title) return badRequest("Product 'title' is required.");
|
|
2930
|
-
if (body.price === void 0 || body.price < 0) return badRequest("Valid product 'price' is required.");
|
|
2931
|
-
return json(await service.createProduct(body), 201);
|
|
2930
|
+
if (!body.title) return badRequest$2("Product 'title' is required.");
|
|
2931
|
+
if (body.price === void 0 || body.price < 0) return badRequest$2("Valid product 'price' is required.");
|
|
2932
|
+
return json$2(await service.createProduct(body), 201);
|
|
2932
2933
|
} catch (err) {
|
|
2933
|
-
return badRequest(err instanceof Error ? err.message : String(err));
|
|
2934
|
+
return badRequest$2(err instanceof Error ? err.message : String(err));
|
|
2934
2935
|
}
|
|
2935
2936
|
});
|
|
2936
2937
|
ctx.registerRoute("PUT", `${prefix}/products/:id`, async (req, { params }) => {
|
|
2937
2938
|
try {
|
|
2938
2939
|
const body = await req.json();
|
|
2939
2940
|
const updated = await service.updateProduct(params.id, body);
|
|
2940
|
-
if (!updated) return notFound(`Product '${params.id}' not found.`);
|
|
2941
|
-
return json(updated);
|
|
2941
|
+
if (!updated) return notFound$2(`Product '${params.id}' not found.`);
|
|
2942
|
+
return json$2(updated);
|
|
2942
2943
|
} catch (err) {
|
|
2943
|
-
return badRequest(err instanceof Error ? err.message : String(err));
|
|
2944
|
+
return badRequest$2(err instanceof Error ? err.message : String(err));
|
|
2944
2945
|
}
|
|
2945
2946
|
});
|
|
2946
2947
|
ctx.registerRoute("DELETE", `${prefix}/products/:id`, async (_req, { params }) => {
|
|
2947
|
-
if (!await service.deleteProduct(params.id)) return notFound(`Product '${params.id}' not found.`);
|
|
2948
|
-
return json({
|
|
2948
|
+
if (!await service.deleteProduct(params.id)) return notFound$2(`Product '${params.id}' not found.`);
|
|
2949
|
+
return json$2({
|
|
2949
2950
|
success: true,
|
|
2950
2951
|
id: params.id
|
|
2951
2952
|
});
|
|
@@ -2953,8 +2954,8 @@ function registerEcommerceRoutes(ctx, service, options = {}) {
|
|
|
2953
2954
|
ctx.registerRoute("POST", `${prefix}/products/:id/images`, async (req, { params }) => {
|
|
2954
2955
|
try {
|
|
2955
2956
|
const body = await req.json();
|
|
2956
|
-
if (!body.filename || !body.mimeType) return badRequest("'filename' and 'mimeType' are required.");
|
|
2957
|
-
return json(await service.uploadProductImage(params.id, {
|
|
2957
|
+
if (!body.filename || !body.mimeType) return badRequest$2("'filename' and 'mimeType' are required.");
|
|
2958
|
+
return json$2(await service.uploadProductImage(params.id, {
|
|
2958
2959
|
filename: body.filename,
|
|
2959
2960
|
mimeType: body.mimeType,
|
|
2960
2961
|
sizeBytes: body.sizeBytes ?? 0,
|
|
@@ -2966,68 +2967,68 @@ function registerEcommerceRoutes(ctx, service, options = {}) {
|
|
|
2966
2967
|
isFeatured: body.isFeatured
|
|
2967
2968
|
}), 201);
|
|
2968
2969
|
} catch (err) {
|
|
2969
|
-
return badRequest(err instanceof Error ? err.message : String(err));
|
|
2970
|
+
return badRequest$2(err instanceof Error ? err.message : String(err));
|
|
2970
2971
|
}
|
|
2971
2972
|
});
|
|
2972
2973
|
ctx.registerRoute("GET", `${prefix}/categories`, async (_req, { url }) => {
|
|
2973
2974
|
try {
|
|
2974
|
-
if (url.searchParams.get("tree") === "true") return json(await service.getCategoryTree());
|
|
2975
|
+
if (url.searchParams.get("tree") === "true") return json$2(await service.getCategoryTree());
|
|
2975
2976
|
const parentId = url.searchParams.get("parentId");
|
|
2976
|
-
return json(await service.getCategories({ parentId: parentId === "null" ? null : parentId ?? void 0 }));
|
|
2977
|
+
return json$2(await service.getCategories({ parentId: parentId === "null" ? null : parentId ?? void 0 }));
|
|
2977
2978
|
} catch (err) {
|
|
2978
|
-
return badRequest(err instanceof Error ? err.message : String(err));
|
|
2979
|
+
return badRequest$2(err instanceof Error ? err.message : String(err));
|
|
2979
2980
|
}
|
|
2980
2981
|
});
|
|
2981
2982
|
ctx.registerRoute("POST", `${prefix}/categories`, async (req) => {
|
|
2982
2983
|
try {
|
|
2983
2984
|
const body = await req.json();
|
|
2984
|
-
if (!body.name) return badRequest("Category 'name' is required.");
|
|
2985
|
-
return json(await service.createCategory(body), 201);
|
|
2985
|
+
if (!body.name) return badRequest$2("Category 'name' is required.");
|
|
2986
|
+
return json$2(await service.createCategory(body), 201);
|
|
2986
2987
|
} catch (err) {
|
|
2987
|
-
return badRequest(err instanceof Error ? err.message : String(err));
|
|
2988
|
+
return badRequest$2(err instanceof Error ? err.message : String(err));
|
|
2988
2989
|
}
|
|
2989
2990
|
});
|
|
2990
2991
|
if (options.enableDiscounts !== false) {
|
|
2991
2992
|
ctx.registerRoute("POST", `${prefix}/discounts`, async (req) => {
|
|
2992
2993
|
try {
|
|
2993
2994
|
const body = await req.json();
|
|
2994
|
-
if (!body.title || !body.code) return badRequest("'title' and 'code' are required.");
|
|
2995
|
-
if (body.value === void 0 || body.value < 0) return badRequest("Valid discount 'value' is required.");
|
|
2996
|
-
return json(await service.createDiscount(body), 201);
|
|
2995
|
+
if (!body.title || !body.code) return badRequest$2("'title' and 'code' are required.");
|
|
2996
|
+
if (body.value === void 0 || body.value < 0) return badRequest$2("Valid discount 'value' is required.");
|
|
2997
|
+
return json$2(await service.createDiscount(body), 201);
|
|
2997
2998
|
} catch (err) {
|
|
2998
|
-
return badRequest(err instanceof Error ? err.message : String(err));
|
|
2999
|
+
return badRequest$2(err instanceof Error ? err.message : String(err));
|
|
2999
3000
|
}
|
|
3000
3001
|
});
|
|
3001
3002
|
ctx.registerRoute("POST", `${prefix}/discounts/validate`, async (req) => {
|
|
3002
3003
|
try {
|
|
3003
3004
|
const body = await req.json();
|
|
3004
|
-
if (!body.code) return badRequest("Discount 'code' is required.");
|
|
3005
|
+
if (!body.code) return badRequest$2("Discount 'code' is required.");
|
|
3005
3006
|
const subtotal = Number(body.subtotal ?? 0);
|
|
3006
3007
|
const productIds = Array.isArray(body.productIds) ? body.productIds : [];
|
|
3007
|
-
return json(await service.validateDiscount(body.code, subtotal, productIds));
|
|
3008
|
+
return json$2(await service.validateDiscount(body.code, subtotal, productIds));
|
|
3008
3009
|
} catch (err) {
|
|
3009
|
-
return badRequest(err instanceof Error ? err.message : String(err));
|
|
3010
|
+
return badRequest$2(err instanceof Error ? err.message : String(err));
|
|
3010
3011
|
}
|
|
3011
3012
|
});
|
|
3012
3013
|
}
|
|
3013
3014
|
ctx.registerRoute("POST", `${prefix}/cart/calculate`, async (req) => {
|
|
3014
3015
|
try {
|
|
3015
3016
|
const body = await req.json();
|
|
3016
|
-
if (!body.items || !Array.isArray(body.items) || body.items.length === 0) return badRequest("'items' array is required and must not be empty.");
|
|
3017
|
-
return json(await service.calculateCart(body));
|
|
3017
|
+
if (!body.items || !Array.isArray(body.items) || body.items.length === 0) return badRequest$2("'items' array is required and must not be empty.");
|
|
3018
|
+
return json$2(await service.calculateCart(body));
|
|
3018
3019
|
} catch (err) {
|
|
3019
|
-
return badRequest(err instanceof Error ? err.message : String(err));
|
|
3020
|
+
return badRequest$2(err instanceof Error ? err.message : String(err));
|
|
3020
3021
|
}
|
|
3021
3022
|
});
|
|
3022
3023
|
if (options.enableOrders !== false) {
|
|
3023
3024
|
ctx.registerRoute("POST", `${prefix}/orders`, async (req) => {
|
|
3024
3025
|
try {
|
|
3025
3026
|
const body = await req.json();
|
|
3026
|
-
if (!body.customerEmail) return badRequest("'customerEmail' is required.");
|
|
3027
|
-
if (!body.items || !Array.isArray(body.items) || body.items.length === 0) return badRequest("'items' array is required.");
|
|
3028
|
-
return json(await service.createOrder(body), 201);
|
|
3027
|
+
if (!body.customerEmail) return badRequest$2("'customerEmail' is required.");
|
|
3028
|
+
if (!body.items || !Array.isArray(body.items) || body.items.length === 0) return badRequest$2("'items' array is required.");
|
|
3029
|
+
return json$2(await service.createOrder(body), 201);
|
|
3029
3030
|
} catch (err) {
|
|
3030
|
-
return badRequest(err instanceof Error ? err.message : String(err));
|
|
3031
|
+
return badRequest$2(err instanceof Error ? err.message : String(err));
|
|
3031
3032
|
}
|
|
3032
3033
|
});
|
|
3033
3034
|
ctx.registerRoute("GET", `${prefix}/orders/:id`, async (_req, { params, url }) => {
|
|
@@ -3039,18 +3040,18 @@ function registerEcommerceRoutes(ctx, service, options = {}) {
|
|
|
3039
3040
|
order = await service.getOrder(id);
|
|
3040
3041
|
if (!order) order = await service.getOrderByNumber(id);
|
|
3041
3042
|
}
|
|
3042
|
-
if (!order) return notFound(`Order '${id}' not found.`);
|
|
3043
|
-
return json(order);
|
|
3043
|
+
if (!order) return notFound$2(`Order '${id}' not found.`);
|
|
3044
|
+
return json$2(order);
|
|
3044
3045
|
});
|
|
3045
3046
|
ctx.registerRoute("PATCH", `${prefix}/orders/:id/status`, async (req, { params }) => {
|
|
3046
3047
|
try {
|
|
3047
3048
|
const body = await req.json();
|
|
3048
|
-
if (!body.status) return badRequest("New 'status' is required.");
|
|
3049
|
+
if (!body.status) return badRequest$2("New 'status' is required.");
|
|
3049
3050
|
const updated = await service.updateOrderStatus(params.id, body.status, body.note);
|
|
3050
|
-
if (!updated) return notFound(`Order '${params.id}' not found.`);
|
|
3051
|
-
return json(updated);
|
|
3051
|
+
if (!updated) return notFound$2(`Order '${params.id}' not found.`);
|
|
3052
|
+
return json$2(updated);
|
|
3052
3053
|
} catch (err) {
|
|
3053
|
-
return badRequest(err instanceof Error ? err.message : String(err));
|
|
3054
|
+
return badRequest$2(err instanceof Error ? err.message : String(err));
|
|
3054
3055
|
}
|
|
3055
3056
|
});
|
|
3056
3057
|
}
|
|
@@ -3234,6 +3235,3401 @@ function getEcommerceService(engine, options) {
|
|
|
3234
3235
|
return service;
|
|
3235
3236
|
}
|
|
3236
3237
|
//#endregion
|
|
3237
|
-
|
|
3238
|
+
//#region src/plugins/hrms/schemas.ts
|
|
3239
|
+
/**
|
|
3240
|
+
* Creates the collection configuration for Employers (Organizations / Companies).
|
|
3241
|
+
*/
|
|
3242
|
+
function createEmployerCollection(options = {}) {
|
|
3243
|
+
return collection({
|
|
3244
|
+
slug: options.employerCollectionSlug ?? "employers",
|
|
3245
|
+
label: "Employers",
|
|
3246
|
+
singularLabel: "Employer",
|
|
3247
|
+
description: "Companies and organizational entities managing employees, shifts, and leave policies",
|
|
3248
|
+
timestamps: true,
|
|
3249
|
+
revisions: true,
|
|
3250
|
+
draftable: true,
|
|
3251
|
+
defaultSort: {
|
|
3252
|
+
field: "createdAt",
|
|
3253
|
+
direction: "desc"
|
|
3254
|
+
},
|
|
3255
|
+
fields: [
|
|
3256
|
+
fields.text({
|
|
3257
|
+
name: "companyName",
|
|
3258
|
+
label: "Company Name",
|
|
3259
|
+
required: true
|
|
3260
|
+
}),
|
|
3261
|
+
fields.slug({
|
|
3262
|
+
from: "companyName",
|
|
3263
|
+
unique: true
|
|
3264
|
+
}),
|
|
3265
|
+
fields.text({
|
|
3266
|
+
name: "legalName",
|
|
3267
|
+
label: "Legal Entity Name"
|
|
3268
|
+
}),
|
|
3269
|
+
fields.text({
|
|
3270
|
+
name: "taxId",
|
|
3271
|
+
label: "Tax / EIN Number"
|
|
3272
|
+
}),
|
|
3273
|
+
fields.text({
|
|
3274
|
+
name: "email",
|
|
3275
|
+
label: "Primary Email"
|
|
3276
|
+
}),
|
|
3277
|
+
fields.text({
|
|
3278
|
+
name: "phone",
|
|
3279
|
+
label: "Phone Number"
|
|
3280
|
+
}),
|
|
3281
|
+
fields.text({
|
|
3282
|
+
name: "website",
|
|
3283
|
+
label: "Website URL"
|
|
3284
|
+
}),
|
|
3285
|
+
fields.image({
|
|
3286
|
+
name: "logo",
|
|
3287
|
+
label: "Company Logo"
|
|
3288
|
+
}),
|
|
3289
|
+
fields.json({
|
|
3290
|
+
name: "address",
|
|
3291
|
+
label: "Company Address"
|
|
3292
|
+
}),
|
|
3293
|
+
fields.text({
|
|
3294
|
+
name: "timezone",
|
|
3295
|
+
label: "Primary Timezone",
|
|
3296
|
+
defaultValue: "UTC"
|
|
3297
|
+
}),
|
|
3298
|
+
fields.json({
|
|
3299
|
+
name: "workSchedule",
|
|
3300
|
+
label: "Standard Work Schedule",
|
|
3301
|
+
defaultValue: {
|
|
3302
|
+
startTime: options.workScheduleStart ?? "09:00",
|
|
3303
|
+
endTime: options.workScheduleEnd ?? "17:00",
|
|
3304
|
+
standardHoursPerDay: options.standardWorkDayHours ?? 8,
|
|
3305
|
+
gracePeriodMinutes: options.gracePeriodMinutes ?? 15,
|
|
3306
|
+
workDays: [
|
|
3307
|
+
1,
|
|
3308
|
+
2,
|
|
3309
|
+
3,
|
|
3310
|
+
4,
|
|
3311
|
+
5
|
|
3312
|
+
]
|
|
3313
|
+
}
|
|
3314
|
+
}),
|
|
3315
|
+
fields.select({
|
|
3316
|
+
name: "status",
|
|
3317
|
+
label: "Status",
|
|
3318
|
+
options: ["active", "inactive"],
|
|
3319
|
+
defaultValue: "active"
|
|
3320
|
+
})
|
|
3321
|
+
]
|
|
3322
|
+
});
|
|
3323
|
+
}
|
|
3324
|
+
/**
|
|
3325
|
+
* Creates the collection configuration for Employees.
|
|
3326
|
+
*/
|
|
3327
|
+
function createEmployeeCollection(options = {}) {
|
|
3328
|
+
const slug = options.employeeCollectionSlug ?? "employees";
|
|
3329
|
+
const employerSlug = options.employerCollectionSlug ?? "employers";
|
|
3330
|
+
return collection({
|
|
3331
|
+
slug,
|
|
3332
|
+
label: "Employees",
|
|
3333
|
+
singularLabel: "Employee",
|
|
3334
|
+
description: "Employee profiles, job assignments, emergency contacts, and attached records",
|
|
3335
|
+
timestamps: true,
|
|
3336
|
+
revisions: true,
|
|
3337
|
+
draftable: true,
|
|
3338
|
+
taxonomies: [options.departmentsTaxonomySlug ?? "hrms_departments", options.designationsTaxonomySlug ?? "hrms_designations"],
|
|
3339
|
+
defaultSort: {
|
|
3340
|
+
field: "createdAt",
|
|
3341
|
+
direction: "desc"
|
|
3342
|
+
},
|
|
3343
|
+
fields: [
|
|
3344
|
+
fields.relationship({
|
|
3345
|
+
name: "employerId",
|
|
3346
|
+
label: "Employer",
|
|
3347
|
+
targetCollection: employerSlug,
|
|
3348
|
+
required: true
|
|
3349
|
+
}),
|
|
3350
|
+
fields.text({
|
|
3351
|
+
name: "userId",
|
|
3352
|
+
label: "Associated User ID",
|
|
3353
|
+
description: "Optional reference to an authenticated user account"
|
|
3354
|
+
}),
|
|
3355
|
+
fields.text({
|
|
3356
|
+
name: "employeeNumber",
|
|
3357
|
+
label: "Employee Number",
|
|
3358
|
+
required: true,
|
|
3359
|
+
unique: true
|
|
3360
|
+
}),
|
|
3361
|
+
fields.text({
|
|
3362
|
+
name: "firstName",
|
|
3363
|
+
label: "First Name",
|
|
3364
|
+
required: true
|
|
3365
|
+
}),
|
|
3366
|
+
fields.text({
|
|
3367
|
+
name: "lastName",
|
|
3368
|
+
label: "Last Name",
|
|
3369
|
+
required: true
|
|
3370
|
+
}),
|
|
3371
|
+
fields.text({
|
|
3372
|
+
name: "email",
|
|
3373
|
+
label: "Work Email",
|
|
3374
|
+
required: true
|
|
3375
|
+
}),
|
|
3376
|
+
fields.text({
|
|
3377
|
+
name: "phone",
|
|
3378
|
+
label: "Contact Phone"
|
|
3379
|
+
}),
|
|
3380
|
+
fields.image({
|
|
3381
|
+
name: "avatar",
|
|
3382
|
+
label: "Profile Picture"
|
|
3383
|
+
}),
|
|
3384
|
+
fields.text({
|
|
3385
|
+
name: "jobTitle",
|
|
3386
|
+
label: "Job Title"
|
|
3387
|
+
}),
|
|
3388
|
+
fields.select({
|
|
3389
|
+
name: "employmentType",
|
|
3390
|
+
label: "Employment Type",
|
|
3391
|
+
options: [
|
|
3392
|
+
"full_time",
|
|
3393
|
+
"part_time",
|
|
3394
|
+
"contractor",
|
|
3395
|
+
"intern"
|
|
3396
|
+
],
|
|
3397
|
+
defaultValue: "full_time"
|
|
3398
|
+
}),
|
|
3399
|
+
fields.select({
|
|
3400
|
+
name: "status",
|
|
3401
|
+
label: "Status",
|
|
3402
|
+
options: [
|
|
3403
|
+
"active",
|
|
3404
|
+
"on_leave",
|
|
3405
|
+
"terminated",
|
|
3406
|
+
"suspended"
|
|
3407
|
+
],
|
|
3408
|
+
defaultValue: "active"
|
|
3409
|
+
}),
|
|
3410
|
+
fields.date({
|
|
3411
|
+
name: "hireDate",
|
|
3412
|
+
label: "Hire Date",
|
|
3413
|
+
required: true
|
|
3414
|
+
}),
|
|
3415
|
+
fields.date({
|
|
3416
|
+
name: "terminationDate",
|
|
3417
|
+
label: "Termination Date"
|
|
3418
|
+
}),
|
|
3419
|
+
fields.relationship({
|
|
3420
|
+
name: "managerId",
|
|
3421
|
+
label: "Reporting Manager",
|
|
3422
|
+
targetCollection: slug
|
|
3423
|
+
}),
|
|
3424
|
+
fields.json({
|
|
3425
|
+
name: "emergencyContact",
|
|
3426
|
+
label: "Emergency Contact"
|
|
3427
|
+
}),
|
|
3428
|
+
fields.repeater({
|
|
3429
|
+
name: "documents",
|
|
3430
|
+
label: "Attached Documents & Contracts",
|
|
3431
|
+
fields: [
|
|
3432
|
+
fields.text({
|
|
3433
|
+
name: "title",
|
|
3434
|
+
label: "Document Title",
|
|
3435
|
+
required: true
|
|
3436
|
+
}),
|
|
3437
|
+
fields.text({
|
|
3438
|
+
name: "fileUrl",
|
|
3439
|
+
label: "File URL",
|
|
3440
|
+
required: true
|
|
3441
|
+
}),
|
|
3442
|
+
fields.text({
|
|
3443
|
+
name: "category",
|
|
3444
|
+
label: "Category"
|
|
3445
|
+
}),
|
|
3446
|
+
fields.text({
|
|
3447
|
+
name: "uploadedAt",
|
|
3448
|
+
label: "Uploaded Date"
|
|
3449
|
+
})
|
|
3450
|
+
]
|
|
3451
|
+
}),
|
|
3452
|
+
fields.number({
|
|
3453
|
+
name: "salary",
|
|
3454
|
+
label: "Base Salary"
|
|
3455
|
+
}),
|
|
3456
|
+
fields.text({
|
|
3457
|
+
name: "notes",
|
|
3458
|
+
label: "Internal Notes"
|
|
3459
|
+
})
|
|
3460
|
+
]
|
|
3461
|
+
});
|
|
3462
|
+
}
|
|
3463
|
+
/**
|
|
3464
|
+
* Creates the collection configuration for Daily Attendance.
|
|
3465
|
+
*/
|
|
3466
|
+
function createAttendanceCollection(options = {}) {
|
|
3467
|
+
const slug = options.attendanceCollectionSlug ?? "attendance";
|
|
3468
|
+
const employerSlug = options.employerCollectionSlug ?? "employers";
|
|
3469
|
+
const employeeSlug = options.employeeCollectionSlug ?? "employees";
|
|
3470
|
+
return collection({
|
|
3471
|
+
slug,
|
|
3472
|
+
label: "Attendance",
|
|
3473
|
+
singularLabel: "Attendance Record",
|
|
3474
|
+
description: "Daily check-in and check-out logs, hours worked, overtime, and punctuality status",
|
|
3475
|
+
timestamps: true,
|
|
3476
|
+
revisions: false,
|
|
3477
|
+
draftable: false,
|
|
3478
|
+
defaultSort: {
|
|
3479
|
+
field: "date",
|
|
3480
|
+
direction: "desc"
|
|
3481
|
+
},
|
|
3482
|
+
fields: [
|
|
3483
|
+
fields.relationship({
|
|
3484
|
+
name: "employerId",
|
|
3485
|
+
label: "Employer",
|
|
3486
|
+
targetCollection: employerSlug,
|
|
3487
|
+
required: true
|
|
3488
|
+
}),
|
|
3489
|
+
fields.relationship({
|
|
3490
|
+
name: "employeeId",
|
|
3491
|
+
label: "Employee",
|
|
3492
|
+
targetCollection: employeeSlug,
|
|
3493
|
+
required: true
|
|
3494
|
+
}),
|
|
3495
|
+
fields.date({
|
|
3496
|
+
name: "date",
|
|
3497
|
+
label: "Date",
|
|
3498
|
+
required: true
|
|
3499
|
+
}),
|
|
3500
|
+
fields.text({
|
|
3501
|
+
name: "checkInAt",
|
|
3502
|
+
label: "Check-In Timestamp",
|
|
3503
|
+
required: true
|
|
3504
|
+
}),
|
|
3505
|
+
fields.text({
|
|
3506
|
+
name: "checkOutAt",
|
|
3507
|
+
label: "Check-Out Timestamp"
|
|
3508
|
+
}),
|
|
3509
|
+
fields.number({
|
|
3510
|
+
name: "totalHours",
|
|
3511
|
+
label: "Total Hours",
|
|
3512
|
+
defaultValue: 0
|
|
3513
|
+
}),
|
|
3514
|
+
fields.number({
|
|
3515
|
+
name: "overtimeHours",
|
|
3516
|
+
label: "Overtime Hours",
|
|
3517
|
+
defaultValue: 0
|
|
3518
|
+
}),
|
|
3519
|
+
fields.select({
|
|
3520
|
+
name: "status",
|
|
3521
|
+
label: "Status",
|
|
3522
|
+
options: [
|
|
3523
|
+
"present",
|
|
3524
|
+
"late",
|
|
3525
|
+
"half_day",
|
|
3526
|
+
"absent",
|
|
3527
|
+
"on_leave"
|
|
3528
|
+
],
|
|
3529
|
+
defaultValue: "present"
|
|
3530
|
+
}),
|
|
3531
|
+
fields.text({
|
|
3532
|
+
name: "location",
|
|
3533
|
+
label: "Location / IP / Geofence"
|
|
3534
|
+
}),
|
|
3535
|
+
fields.text({
|
|
3536
|
+
name: "notes",
|
|
3537
|
+
label: "Notes"
|
|
3538
|
+
})
|
|
3539
|
+
]
|
|
3540
|
+
});
|
|
3541
|
+
}
|
|
3542
|
+
/**
|
|
3543
|
+
* Creates the collection configuration for Leave Types.
|
|
3544
|
+
*/
|
|
3545
|
+
function createLeaveTypeCollection(options = {}) {
|
|
3546
|
+
const slug = options.leaveTypeCollectionSlug ?? "leave_types";
|
|
3547
|
+
const employerSlug = options.employerCollectionSlug ?? "employers";
|
|
3548
|
+
return collection({
|
|
3549
|
+
slug,
|
|
3550
|
+
label: "Leave Types",
|
|
3551
|
+
singularLabel: "Leave Type",
|
|
3552
|
+
description: "Available leave categories (Annual, Sick, Unpaid) and yearly quotas",
|
|
3553
|
+
timestamps: true,
|
|
3554
|
+
revisions: true,
|
|
3555
|
+
draftable: false,
|
|
3556
|
+
fields: [
|
|
3557
|
+
fields.relationship({
|
|
3558
|
+
name: "employerId",
|
|
3559
|
+
label: "Employer",
|
|
3560
|
+
targetCollection: employerSlug
|
|
3561
|
+
}),
|
|
3562
|
+
fields.text({
|
|
3563
|
+
name: "name",
|
|
3564
|
+
label: "Leave Name",
|
|
3565
|
+
required: true
|
|
3566
|
+
}),
|
|
3567
|
+
fields.text({
|
|
3568
|
+
name: "code",
|
|
3569
|
+
label: "Leave Code",
|
|
3570
|
+
required: true
|
|
3571
|
+
}),
|
|
3572
|
+
fields.number({
|
|
3573
|
+
name: "daysAllowedPerYear",
|
|
3574
|
+
label: "Days Allowed Per Year",
|
|
3575
|
+
required: true,
|
|
3576
|
+
defaultValue: 15,
|
|
3577
|
+
min: 0
|
|
3578
|
+
}),
|
|
3579
|
+
fields.boolean({
|
|
3580
|
+
name: "paid",
|
|
3581
|
+
label: "Paid Leave",
|
|
3582
|
+
defaultValue: true
|
|
3583
|
+
}),
|
|
3584
|
+
fields.boolean({
|
|
3585
|
+
name: "requiresApproval",
|
|
3586
|
+
label: "Requires Manager Approval",
|
|
3587
|
+
defaultValue: true
|
|
3588
|
+
}),
|
|
3589
|
+
fields.text({
|
|
3590
|
+
name: "color",
|
|
3591
|
+
label: "Display Color Code"
|
|
3592
|
+
}),
|
|
3593
|
+
fields.text({
|
|
3594
|
+
name: "description",
|
|
3595
|
+
label: "Description / Policy"
|
|
3596
|
+
})
|
|
3597
|
+
]
|
|
3598
|
+
});
|
|
3599
|
+
}
|
|
3600
|
+
/**
|
|
3601
|
+
* Creates the collection configuration for Leave Requests.
|
|
3602
|
+
*/
|
|
3603
|
+
function createLeaveRequestCollection(options = {}) {
|
|
3604
|
+
const slug = options.leaveRequestCollectionSlug ?? "leave_requests";
|
|
3605
|
+
const employerSlug = options.employerCollectionSlug ?? "employers";
|
|
3606
|
+
const employeeSlug = options.employeeCollectionSlug ?? "employees";
|
|
3607
|
+
const leaveTypeSlug = options.leaveTypeCollectionSlug ?? "leave_types";
|
|
3608
|
+
return collection({
|
|
3609
|
+
slug,
|
|
3610
|
+
label: "Leave Requests",
|
|
3611
|
+
singularLabel: "Leave Request",
|
|
3612
|
+
description: "Employee time-off requests, approval tracking, and deducted balances",
|
|
3613
|
+
timestamps: true,
|
|
3614
|
+
revisions: true,
|
|
3615
|
+
draftable: false,
|
|
3616
|
+
defaultSort: {
|
|
3617
|
+
field: "createdAt",
|
|
3618
|
+
direction: "desc"
|
|
3619
|
+
},
|
|
3620
|
+
fields: [
|
|
3621
|
+
fields.relationship({
|
|
3622
|
+
name: "employerId",
|
|
3623
|
+
label: "Employer",
|
|
3624
|
+
targetCollection: employerSlug,
|
|
3625
|
+
required: true
|
|
3626
|
+
}),
|
|
3627
|
+
fields.relationship({
|
|
3628
|
+
name: "employeeId",
|
|
3629
|
+
label: "Employee",
|
|
3630
|
+
targetCollection: employeeSlug,
|
|
3631
|
+
required: true
|
|
3632
|
+
}),
|
|
3633
|
+
fields.relationship({
|
|
3634
|
+
name: "leaveTypeId",
|
|
3635
|
+
label: "Leave Type",
|
|
3636
|
+
targetCollection: leaveTypeSlug,
|
|
3637
|
+
required: true
|
|
3638
|
+
}),
|
|
3639
|
+
fields.date({
|
|
3640
|
+
name: "startDate",
|
|
3641
|
+
label: "Start Date",
|
|
3642
|
+
required: true
|
|
3643
|
+
}),
|
|
3644
|
+
fields.date({
|
|
3645
|
+
name: "endDate",
|
|
3646
|
+
label: "End Date",
|
|
3647
|
+
required: true
|
|
3648
|
+
}),
|
|
3649
|
+
fields.number({
|
|
3650
|
+
name: "daysCount",
|
|
3651
|
+
label: "Days Count",
|
|
3652
|
+
required: true,
|
|
3653
|
+
min: .5
|
|
3654
|
+
}),
|
|
3655
|
+
fields.text({
|
|
3656
|
+
name: "reason",
|
|
3657
|
+
label: "Reason"
|
|
3658
|
+
}),
|
|
3659
|
+
fields.select({
|
|
3660
|
+
name: "status",
|
|
3661
|
+
label: "Request Status",
|
|
3662
|
+
options: [
|
|
3663
|
+
"pending",
|
|
3664
|
+
"approved",
|
|
3665
|
+
"rejected",
|
|
3666
|
+
"cancelled"
|
|
3667
|
+
],
|
|
3668
|
+
defaultValue: "pending"
|
|
3669
|
+
}),
|
|
3670
|
+
fields.relationship({
|
|
3671
|
+
name: "approvedBy",
|
|
3672
|
+
label: "Approved / Rejected By",
|
|
3673
|
+
targetCollection: employeeSlug
|
|
3674
|
+
}),
|
|
3675
|
+
fields.text({
|
|
3676
|
+
name: "approvedAt",
|
|
3677
|
+
label: "Decision Timestamp"
|
|
3678
|
+
}),
|
|
3679
|
+
fields.text({
|
|
3680
|
+
name: "rejectionReason",
|
|
3681
|
+
label: "Rejection Reason"
|
|
3682
|
+
})
|
|
3683
|
+
]
|
|
3684
|
+
});
|
|
3685
|
+
}
|
|
3686
|
+
/**
|
|
3687
|
+
* Creates the standard HRMS taxonomies: departments and designations.
|
|
3688
|
+
*/
|
|
3689
|
+
function createHRMSTaxonomies(options = {}) {
|
|
3690
|
+
const employeeSlug = options.employeeCollectionSlug ?? "employees";
|
|
3691
|
+
const deptSlug = options.departmentsTaxonomySlug ?? "hrms_departments";
|
|
3692
|
+
const desigSlug = options.designationsTaxonomySlug ?? "hrms_designations";
|
|
3693
|
+
return [{
|
|
3694
|
+
slug: deptSlug,
|
|
3695
|
+
label: "Departments",
|
|
3696
|
+
singularLabel: "Department",
|
|
3697
|
+
hierarchical: true,
|
|
3698
|
+
postTypes: [employeeSlug],
|
|
3699
|
+
description: "Hierarchical departmental tree (e.g. Engineering, Sales, HR)"
|
|
3700
|
+
}, {
|
|
3701
|
+
slug: desigSlug,
|
|
3702
|
+
label: "Designations",
|
|
3703
|
+
singularLabel: "Designation",
|
|
3704
|
+
hierarchical: false,
|
|
3705
|
+
postTypes: [employeeSlug],
|
|
3706
|
+
description: "Job titles and designations across the workforce"
|
|
3707
|
+
}];
|
|
3708
|
+
}
|
|
3709
|
+
//#endregion
|
|
3710
|
+
//#region src/plugins/hrms/service.ts
|
|
3711
|
+
var HRMSService = class {
|
|
3712
|
+
engine;
|
|
3713
|
+
options;
|
|
3714
|
+
employerSlug;
|
|
3715
|
+
employeeSlug;
|
|
3716
|
+
attendanceSlug;
|
|
3717
|
+
leaveTypeSlug;
|
|
3718
|
+
leaveRequestSlug;
|
|
3719
|
+
departmentsTaxonomy;
|
|
3720
|
+
designationsTaxonomy;
|
|
3721
|
+
standardWorkDayHours;
|
|
3722
|
+
workScheduleStart;
|
|
3723
|
+
workScheduleEnd;
|
|
3724
|
+
gracePeriodMinutes;
|
|
3725
|
+
constructor(engine, options = {}) {
|
|
3726
|
+
this.engine = engine;
|
|
3727
|
+
this.options = options;
|
|
3728
|
+
this.employerSlug = options.employerCollectionSlug ?? "employers";
|
|
3729
|
+
this.employeeSlug = options.employeeCollectionSlug ?? "employees";
|
|
3730
|
+
this.attendanceSlug = options.attendanceCollectionSlug ?? "attendance";
|
|
3731
|
+
this.leaveTypeSlug = options.leaveTypeCollectionSlug ?? "leave_types";
|
|
3732
|
+
this.leaveRequestSlug = options.leaveRequestCollectionSlug ?? "leave_requests";
|
|
3733
|
+
this.departmentsTaxonomy = options.departmentsTaxonomySlug ?? "hrms_departments";
|
|
3734
|
+
this.designationsTaxonomy = options.designationsTaxonomySlug ?? "hrms_designations";
|
|
3735
|
+
this.standardWorkDayHours = options.standardWorkDayHours ?? 8;
|
|
3736
|
+
this.workScheduleStart = options.workScheduleStart ?? "09:00";
|
|
3737
|
+
this.workScheduleEnd = options.workScheduleEnd ?? "17:00";
|
|
3738
|
+
this.gracePeriodMinutes = options.gracePeriodMinutes ?? 15;
|
|
3739
|
+
}
|
|
3740
|
+
get employersCollection() {
|
|
3741
|
+
return this.engine.collection(this.employerSlug);
|
|
3742
|
+
}
|
|
3743
|
+
get employeesCollection() {
|
|
3744
|
+
return this.engine.collection(this.employeeSlug);
|
|
3745
|
+
}
|
|
3746
|
+
get attendanceCollection() {
|
|
3747
|
+
return this.engine.collection(this.attendanceSlug);
|
|
3748
|
+
}
|
|
3749
|
+
get leaveTypesCollection() {
|
|
3750
|
+
return this.engine.collection(this.leaveTypeSlug);
|
|
3751
|
+
}
|
|
3752
|
+
get leaveRequestsCollection() {
|
|
3753
|
+
return this.engine.collection(this.leaveRequestSlug);
|
|
3754
|
+
}
|
|
3755
|
+
async createEmployer(input, authorId) {
|
|
3756
|
+
const employerData = {
|
|
3757
|
+
companyName: input.companyName,
|
|
3758
|
+
legalName: input.legalName,
|
|
3759
|
+
taxId: input.taxId,
|
|
3760
|
+
email: input.email,
|
|
3761
|
+
phone: input.phone,
|
|
3762
|
+
website: input.website,
|
|
3763
|
+
logo: input.logo,
|
|
3764
|
+
address: input.address,
|
|
3765
|
+
timezone: input.timezone ?? "UTC",
|
|
3766
|
+
workSchedule: input.workSchedule ?? {
|
|
3767
|
+
startTime: this.workScheduleStart,
|
|
3768
|
+
endTime: this.workScheduleEnd,
|
|
3769
|
+
standardHoursPerDay: this.standardWorkDayHours,
|
|
3770
|
+
gracePeriodMinutes: this.gracePeriodMinutes,
|
|
3771
|
+
workDays: [
|
|
3772
|
+
1,
|
|
3773
|
+
2,
|
|
3774
|
+
3,
|
|
3775
|
+
4,
|
|
3776
|
+
5
|
|
3777
|
+
]
|
|
3778
|
+
},
|
|
3779
|
+
status: input.status ?? "active"
|
|
3780
|
+
};
|
|
3781
|
+
const employer = await this.employersCollection.create({
|
|
3782
|
+
title: input.companyName,
|
|
3783
|
+
status: input.status === "inactive" ? "draft" : "published",
|
|
3784
|
+
data: employerData
|
|
3785
|
+
}, authorId);
|
|
3786
|
+
await this.engine.hooks.doAction("hrms.employer_created", employer);
|
|
3787
|
+
return employer;
|
|
3788
|
+
}
|
|
3789
|
+
async getEmployer(id) {
|
|
3790
|
+
return this.employersCollection.findById(id);
|
|
3791
|
+
}
|
|
3792
|
+
async getEmployerBySlug(slug) {
|
|
3793
|
+
return this.employersCollection.findBySlug(slug);
|
|
3794
|
+
}
|
|
3795
|
+
async updateEmployer(id, input, authorId) {
|
|
3796
|
+
const existing = await this.getEmployer(id);
|
|
3797
|
+
if (!existing) return null;
|
|
3798
|
+
const updatedData = {
|
|
3799
|
+
...existing.data,
|
|
3800
|
+
...input.companyName !== void 0 ? { companyName: input.companyName } : {},
|
|
3801
|
+
...input.legalName !== void 0 ? { legalName: input.legalName } : {},
|
|
3802
|
+
...input.taxId !== void 0 ? { taxId: input.taxId } : {},
|
|
3803
|
+
...input.email !== void 0 ? { email: input.email } : {},
|
|
3804
|
+
...input.phone !== void 0 ? { phone: input.phone } : {},
|
|
3805
|
+
...input.website !== void 0 ? { website: input.website } : {},
|
|
3806
|
+
...input.logo !== void 0 ? { logo: input.logo } : {},
|
|
3807
|
+
...input.address !== void 0 ? { address: input.address } : {},
|
|
3808
|
+
...input.timezone !== void 0 ? { timezone: input.timezone } : {},
|
|
3809
|
+
...input.workSchedule !== void 0 ? { workSchedule: input.workSchedule } : {},
|
|
3810
|
+
...input.status !== void 0 ? { status: input.status } : {}
|
|
3811
|
+
};
|
|
3812
|
+
const updated = await this.employersCollection.update(id, {
|
|
3813
|
+
title: input.companyName ?? existing.title,
|
|
3814
|
+
data: updatedData
|
|
3815
|
+
}, authorId);
|
|
3816
|
+
if (updated) await this.engine.hooks.doAction("hrms.employer_updated", updated);
|
|
3817
|
+
return updated;
|
|
3818
|
+
}
|
|
3819
|
+
async listEmployers(query = {}) {
|
|
3820
|
+
const limit = query.limit ?? 20;
|
|
3821
|
+
const offset = query.page ? (query.page - 1) * limit : 0;
|
|
3822
|
+
let items = (await this.employersCollection.find({ limit: 500 })).items;
|
|
3823
|
+
if (query.status) items = items.filter((item) => item.data.status === query.status);
|
|
3824
|
+
const total = items.length;
|
|
3825
|
+
return {
|
|
3826
|
+
items: items.slice(offset, offset + limit),
|
|
3827
|
+
total,
|
|
3828
|
+
limit,
|
|
3829
|
+
offset,
|
|
3830
|
+
hasMore: offset + limit < total
|
|
3831
|
+
};
|
|
3832
|
+
}
|
|
3833
|
+
async createEmployee(input, authorId) {
|
|
3834
|
+
if (!await this.getEmployer(input.employerId)) throw new Error(`[HRMSService] Employer with ID '${input.employerId}' not found.`);
|
|
3835
|
+
if (await this.getEmployeeByNumber(input.employerId, input.employeeNumber)) throw new Error(`[HRMSService] Employee number '${input.employeeNumber}' is already registered for this employer.`);
|
|
3836
|
+
const employeeData = {
|
|
3837
|
+
employerId: input.employerId,
|
|
3838
|
+
userId: input.userId,
|
|
3839
|
+
employeeNumber: input.employeeNumber,
|
|
3840
|
+
firstName: input.firstName,
|
|
3841
|
+
lastName: input.lastName,
|
|
3842
|
+
email: input.email,
|
|
3843
|
+
phone: input.phone,
|
|
3844
|
+
avatar: input.avatar,
|
|
3845
|
+
jobTitle: input.jobTitle,
|
|
3846
|
+
employmentType: input.employmentType ?? "full_time",
|
|
3847
|
+
status: input.status ?? "active",
|
|
3848
|
+
hireDate: input.hireDate,
|
|
3849
|
+
managerId: input.managerId,
|
|
3850
|
+
emergencyContact: input.emergencyContact,
|
|
3851
|
+
documents: input.documents ?? [],
|
|
3852
|
+
salary: input.salary,
|
|
3853
|
+
notes: input.notes
|
|
3854
|
+
};
|
|
3855
|
+
const title = `${input.firstName} ${input.lastName}`;
|
|
3856
|
+
const employee = await this.employeesCollection.create({
|
|
3857
|
+
title,
|
|
3858
|
+
status: input.status === "terminated" ? "draft" : "published",
|
|
3859
|
+
data: employeeData
|
|
3860
|
+
}, authorId);
|
|
3861
|
+
if (input.departmentSlug) {
|
|
3862
|
+
const term = await this.engine.taxonomies.getTermBySlug(this.departmentsTaxonomy, input.departmentSlug);
|
|
3863
|
+
if (term) await this.engine.taxonomies.assignTerms(employee.id, [term.id]);
|
|
3864
|
+
}
|
|
3865
|
+
await this.engine.hooks.doAction("hrms.employee_created", employee);
|
|
3866
|
+
return employee;
|
|
3867
|
+
}
|
|
3868
|
+
async getEmployee(id) {
|
|
3869
|
+
return this.employeesCollection.findById(id);
|
|
3870
|
+
}
|
|
3871
|
+
async getEmployeeByNumber(employerId, employeeNumber) {
|
|
3872
|
+
return (await this.employeesCollection.find({ limit: 500 })).items.find((e) => e.data.employerId === employerId && e.data.employeeNumber === employeeNumber) ?? null;
|
|
3873
|
+
}
|
|
3874
|
+
async updateEmployee(id, input, authorId) {
|
|
3875
|
+
const existing = await this.getEmployee(id);
|
|
3876
|
+
if (!existing) return null;
|
|
3877
|
+
const updatedData = {
|
|
3878
|
+
...existing.data,
|
|
3879
|
+
...input.employerId !== void 0 ? { employerId: input.employerId } : {},
|
|
3880
|
+
...input.userId !== void 0 ? { userId: input.userId } : {},
|
|
3881
|
+
...input.employeeNumber !== void 0 ? { employeeNumber: input.employeeNumber } : {},
|
|
3882
|
+
...input.firstName !== void 0 ? { firstName: input.firstName } : {},
|
|
3883
|
+
...input.lastName !== void 0 ? { lastName: input.lastName } : {},
|
|
3884
|
+
...input.email !== void 0 ? { email: input.email } : {},
|
|
3885
|
+
...input.phone !== void 0 ? { phone: input.phone } : {},
|
|
3886
|
+
...input.avatar !== void 0 ? { avatar: input.avatar } : {},
|
|
3887
|
+
...input.jobTitle !== void 0 ? { jobTitle: input.jobTitle } : {},
|
|
3888
|
+
...input.employmentType !== void 0 ? { employmentType: input.employmentType } : {},
|
|
3889
|
+
...input.status !== void 0 ? { status: input.status } : {},
|
|
3890
|
+
...input.hireDate !== void 0 ? { hireDate: input.hireDate } : {},
|
|
3891
|
+
...input.terminationDate !== void 0 ? { terminationDate: input.terminationDate } : {},
|
|
3892
|
+
...input.managerId !== void 0 ? { managerId: input.managerId } : {},
|
|
3893
|
+
...input.emergencyContact !== void 0 ? { emergencyContact: input.emergencyContact } : {},
|
|
3894
|
+
...input.documents !== void 0 ? { documents: input.documents } : {},
|
|
3895
|
+
...input.salary !== void 0 ? { salary: input.salary } : {},
|
|
3896
|
+
...input.notes !== void 0 ? { notes: input.notes } : {}
|
|
3897
|
+
};
|
|
3898
|
+
const title = input.firstName || input.lastName ? `${updatedData.firstName} ${updatedData.lastName}` : existing.title;
|
|
3899
|
+
const updated = await this.employeesCollection.update(id, {
|
|
3900
|
+
title,
|
|
3901
|
+
data: updatedData
|
|
3902
|
+
}, authorId);
|
|
3903
|
+
if (updated) {
|
|
3904
|
+
if (input.departmentSlug) {
|
|
3905
|
+
const term = await this.engine.taxonomies.getTermBySlug(this.departmentsTaxonomy, input.departmentSlug);
|
|
3906
|
+
if (term) await this.engine.taxonomies.assignTerms(id, [term.id]);
|
|
3907
|
+
}
|
|
3908
|
+
await this.engine.hooks.doAction("hrms.employee_updated", updated);
|
|
3909
|
+
}
|
|
3910
|
+
return updated;
|
|
3911
|
+
}
|
|
3912
|
+
async deleteEmployee(id) {
|
|
3913
|
+
const deleted = await this.employeesCollection.delete(id);
|
|
3914
|
+
if (deleted) await this.engine.hooks.doAction("hrms.employee_deleted", id);
|
|
3915
|
+
return deleted;
|
|
3916
|
+
}
|
|
3917
|
+
async listEmployees(query = {}) {
|
|
3918
|
+
const limit = query.limit ?? 20;
|
|
3919
|
+
const offset = query.page ? (query.page - 1) * limit : 0;
|
|
3920
|
+
let termIds;
|
|
3921
|
+
if (query.department) {
|
|
3922
|
+
const term = await this.engine.taxonomies.getTermBySlug(this.departmentsTaxonomy, query.department);
|
|
3923
|
+
if (term) termIds = [term.id];
|
|
3924
|
+
else return {
|
|
3925
|
+
items: [],
|
|
3926
|
+
total: 0,
|
|
3927
|
+
limit,
|
|
3928
|
+
offset,
|
|
3929
|
+
hasMore: false
|
|
3930
|
+
};
|
|
3931
|
+
}
|
|
3932
|
+
let items = (await this.employeesCollection.find({
|
|
3933
|
+
termIds,
|
|
3934
|
+
limit: 1e3
|
|
3935
|
+
})).items;
|
|
3936
|
+
if (query.employerId) items = items.filter((e) => e.data.employerId === query.employerId);
|
|
3937
|
+
if (query.employmentType) items = items.filter((e) => e.data.employmentType === query.employmentType);
|
|
3938
|
+
if (query.status) items = items.filter((e) => e.data.status === query.status);
|
|
3939
|
+
if (query.search) {
|
|
3940
|
+
const s = query.search.toLowerCase();
|
|
3941
|
+
items = items.filter((e) => e.data.firstName.toLowerCase().includes(s) || e.data.lastName.toLowerCase().includes(s) || e.data.email.toLowerCase().includes(s) || e.data.employeeNumber.toLowerCase().includes(s) || e.data.jobTitle && e.data.jobTitle.toLowerCase().includes(s));
|
|
3942
|
+
}
|
|
3943
|
+
const total = items.length;
|
|
3944
|
+
return {
|
|
3945
|
+
items: items.slice(offset, offset + limit),
|
|
3946
|
+
total,
|
|
3947
|
+
limit,
|
|
3948
|
+
offset,
|
|
3949
|
+
hasMore: offset + limit < total
|
|
3950
|
+
};
|
|
3951
|
+
}
|
|
3952
|
+
async getDirectReports(managerId) {
|
|
3953
|
+
return (await this.employeesCollection.find({ limit: 1e3 })).items.filter((e) => e.data.managerId === managerId);
|
|
3954
|
+
}
|
|
3955
|
+
parseTimeToMinutes(timeStr) {
|
|
3956
|
+
const [hours, minutes] = timeStr.split(":").map((v) => parseInt(v, 10));
|
|
3957
|
+
return (hours || 0) * 60 + (minutes || 0);
|
|
3958
|
+
}
|
|
3959
|
+
formatDateString(date, timezone) {
|
|
3960
|
+
if (!timezone || timezone === "UTC") return date.toISOString().slice(0, 10);
|
|
3961
|
+
try {
|
|
3962
|
+
return new Intl.DateTimeFormat("en-CA", {
|
|
3963
|
+
timeZone: timezone,
|
|
3964
|
+
year: "numeric",
|
|
3965
|
+
month: "2-digit",
|
|
3966
|
+
day: "2-digit"
|
|
3967
|
+
}).format(date);
|
|
3968
|
+
} catch {
|
|
3969
|
+
return date.toISOString().slice(0, 10);
|
|
3970
|
+
}
|
|
3971
|
+
}
|
|
3972
|
+
getHoursAndMinutes(date, timezone) {
|
|
3973
|
+
if (!timezone || timezone === "UTC") return {
|
|
3974
|
+
hours: date.getUTCHours(),
|
|
3975
|
+
minutes: date.getUTCMinutes()
|
|
3976
|
+
};
|
|
3977
|
+
try {
|
|
3978
|
+
const parts = new Intl.DateTimeFormat("en-US", {
|
|
3979
|
+
timeZone: timezone,
|
|
3980
|
+
hour: "numeric",
|
|
3981
|
+
minute: "numeric",
|
|
3982
|
+
hour12: false
|
|
3983
|
+
}).formatToParts(date);
|
|
3984
|
+
const hoursPart = parts.find((p) => p.type === "hour");
|
|
3985
|
+
const minutesPart = parts.find((p) => p.type === "minute");
|
|
3986
|
+
return {
|
|
3987
|
+
hours: hoursPart ? parseInt(hoursPart.value, 10) : date.getUTCHours(),
|
|
3988
|
+
minutes: minutesPart ? parseInt(minutesPart.value, 10) : date.getUTCMinutes()
|
|
3989
|
+
};
|
|
3990
|
+
} catch {
|
|
3991
|
+
return {
|
|
3992
|
+
hours: date.getUTCHours(),
|
|
3993
|
+
minutes: date.getUTCMinutes()
|
|
3994
|
+
};
|
|
3995
|
+
}
|
|
3996
|
+
}
|
|
3997
|
+
/**
|
|
3998
|
+
* Check in an employee for today (or specified timestamp).
|
|
3999
|
+
*/
|
|
4000
|
+
async checkIn(input) {
|
|
4001
|
+
const employee = await this.getEmployee(input.employeeId);
|
|
4002
|
+
if (!employee) throw new Error(`[HRMSService] Employee with ID '${input.employeeId}' not found.`);
|
|
4003
|
+
const employer = await this.getEmployer(employee.data.employerId);
|
|
4004
|
+
const timezone = employer?.data?.timezone ?? "UTC";
|
|
4005
|
+
const checkInDate = input.timestamp ? new Date(input.timestamp) : /* @__PURE__ */ new Date();
|
|
4006
|
+
const dateStr = this.formatDateString(checkInDate, timezone);
|
|
4007
|
+
const existing = await this.getDailyAttendance(employee.id, dateStr);
|
|
4008
|
+
if (existing && existing.data.checkInAt) throw new Error(`[HRMSService] Employee '${employee.id}' is already checked in for date ${dateStr}.`);
|
|
4009
|
+
const schedule = employer?.data?.workSchedule;
|
|
4010
|
+
const schedStart = schedule?.startTime ?? this.workScheduleStart;
|
|
4011
|
+
const grace = schedule?.gracePeriodMinutes ?? this.gracePeriodMinutes;
|
|
4012
|
+
const schedMinutes = this.parseTimeToMinutes(schedStart);
|
|
4013
|
+
const { hours: punchHours, minutes: punchMins } = this.getHoursAndMinutes(checkInDate, timezone);
|
|
4014
|
+
const status = punchHours * 60 + punchMins > schedMinutes + grace ? "late" : "present";
|
|
4015
|
+
const attendanceData = {
|
|
4016
|
+
employerId: employee.data.employerId,
|
|
4017
|
+
employeeId: employee.id,
|
|
4018
|
+
date: dateStr,
|
|
4019
|
+
checkInAt: checkInDate.toISOString(),
|
|
4020
|
+
totalHours: 0,
|
|
4021
|
+
overtimeHours: 0,
|
|
4022
|
+
status,
|
|
4023
|
+
location: input.location,
|
|
4024
|
+
notes: input.notes
|
|
4025
|
+
};
|
|
4026
|
+
const attendance = await this.attendanceCollection.create({
|
|
4027
|
+
title: `${employee.title} - ${dateStr}`,
|
|
4028
|
+
status: "published",
|
|
4029
|
+
data: attendanceData
|
|
4030
|
+
});
|
|
4031
|
+
await this.engine.hooks.doAction("hrms.checked_in", attendance, employee);
|
|
4032
|
+
return attendance;
|
|
4033
|
+
}
|
|
4034
|
+
/**
|
|
4035
|
+
* Check out an employee for today (or specified timestamp).
|
|
4036
|
+
*/
|
|
4037
|
+
async checkOut(input) {
|
|
4038
|
+
const employee = await this.getEmployee(input.employeeId);
|
|
4039
|
+
if (!employee) throw new Error(`[HRMSService] Employee with ID '${input.employeeId}' not found.`);
|
|
4040
|
+
const employer = await this.getEmployer(employee.data.employerId);
|
|
4041
|
+
const timezone = employer?.data?.timezone ?? "UTC";
|
|
4042
|
+
const checkOutDate = input.timestamp ? new Date(input.timestamp) : /* @__PURE__ */ new Date();
|
|
4043
|
+
const dateStr = this.formatDateString(checkOutDate, timezone);
|
|
4044
|
+
const record = await this.getDailyAttendance(employee.id, dateStr);
|
|
4045
|
+
if (!record || !record.data.checkInAt) throw new Error(`[HRMSService] No active check-in record found for employee '${employee.id}' on ${dateStr}.`);
|
|
4046
|
+
if (record.data.checkOutAt) throw new Error(`[HRMSService] Employee '${employee.id}' has already checked out for date ${dateStr}.`);
|
|
4047
|
+
const checkInDate = new Date(record.data.checkInAt);
|
|
4048
|
+
const durationMs = Math.max(0, checkOutDate.getTime() - checkInDate.getTime());
|
|
4049
|
+
const totalHours = Math.round(durationMs / (1e3 * 60 * 60) * 100) / 100;
|
|
4050
|
+
const standardHours = employer?.data?.workSchedule?.standardHoursPerDay ?? this.standardWorkDayHours;
|
|
4051
|
+
const overtimeHours = Math.max(0, Math.round((totalHours - standardHours) * 100) / 100);
|
|
4052
|
+
let status = record.data.status;
|
|
4053
|
+
if (totalHours < standardHours / 2 && status === "present") status = "half_day";
|
|
4054
|
+
const updatedData = {
|
|
4055
|
+
...record.data,
|
|
4056
|
+
checkOutAt: checkOutDate.toISOString(),
|
|
4057
|
+
totalHours,
|
|
4058
|
+
overtimeHours,
|
|
4059
|
+
status,
|
|
4060
|
+
...input.location ? { location: input.location } : {},
|
|
4061
|
+
...input.notes ? { notes: input.notes } : {}
|
|
4062
|
+
};
|
|
4063
|
+
const updated = await this.attendanceCollection.update(record.id, { data: updatedData });
|
|
4064
|
+
if (!updated) throw new Error(`[HRMSService] Failed to update attendance record for '${employee.id}'.`);
|
|
4065
|
+
await this.engine.hooks.doAction("hrms.checked_out", updated, employee);
|
|
4066
|
+
return updated;
|
|
4067
|
+
}
|
|
4068
|
+
async getDailyAttendance(employeeId, date) {
|
|
4069
|
+
return (await this.attendanceCollection.find({ limit: 1e3 })).items.find((a) => a.data.employeeId === employeeId && a.data.date === date) ?? null;
|
|
4070
|
+
}
|
|
4071
|
+
async recordAttendanceManual(input) {
|
|
4072
|
+
const existing = await this.getDailyAttendance(input.employeeId, input.date);
|
|
4073
|
+
const attendanceData = {
|
|
4074
|
+
employerId: input.employerId,
|
|
4075
|
+
employeeId: input.employeeId,
|
|
4076
|
+
date: input.date,
|
|
4077
|
+
checkInAt: input.checkInAt,
|
|
4078
|
+
checkOutAt: input.checkOutAt,
|
|
4079
|
+
totalHours: input.totalHours ?? 0,
|
|
4080
|
+
overtimeHours: input.overtimeHours ?? 0,
|
|
4081
|
+
status: input.status ?? "present",
|
|
4082
|
+
location: input.location,
|
|
4083
|
+
notes: input.notes
|
|
4084
|
+
};
|
|
4085
|
+
if (existing) {
|
|
4086
|
+
const updated = await this.attendanceCollection.update(existing.id, { data: attendanceData });
|
|
4087
|
+
if (!updated) throw new Error(`[HRMSService] Failed to update attendance for '${input.employeeId}'.`);
|
|
4088
|
+
return updated;
|
|
4089
|
+
}
|
|
4090
|
+
return this.attendanceCollection.create({
|
|
4091
|
+
title: `${input.employeeId} - ${input.date}`,
|
|
4092
|
+
status: "published",
|
|
4093
|
+
data: attendanceData
|
|
4094
|
+
});
|
|
4095
|
+
}
|
|
4096
|
+
async listAttendance(query = {}) {
|
|
4097
|
+
const limit = query.limit ?? 30;
|
|
4098
|
+
const offset = query.page ? (query.page - 1) * limit : 0;
|
|
4099
|
+
let items = (await this.attendanceCollection.find({ limit: 2e3 })).items;
|
|
4100
|
+
if (query.employerId) items = items.filter((a) => a.data.employerId === query.employerId);
|
|
4101
|
+
if (query.employeeId) items = items.filter((a) => a.data.employeeId === query.employeeId);
|
|
4102
|
+
if (query.date) items = items.filter((a) => a.data.date === query.date);
|
|
4103
|
+
if (query.startDate) items = items.filter((a) => a.data.date >= query.startDate);
|
|
4104
|
+
if (query.endDate) items = items.filter((a) => a.data.date <= query.endDate);
|
|
4105
|
+
if (query.status) items = items.filter((a) => a.data.status === query.status);
|
|
4106
|
+
const total = items.length;
|
|
4107
|
+
return {
|
|
4108
|
+
items: items.slice(offset, offset + limit),
|
|
4109
|
+
total,
|
|
4110
|
+
limit,
|
|
4111
|
+
offset,
|
|
4112
|
+
hasMore: offset + limit < total
|
|
4113
|
+
};
|
|
4114
|
+
}
|
|
4115
|
+
async createLeaveType(input, authorId) {
|
|
4116
|
+
const leaveTypeData = {
|
|
4117
|
+
employerId: input.employerId,
|
|
4118
|
+
name: input.name,
|
|
4119
|
+
code: input.code.toUpperCase(),
|
|
4120
|
+
daysAllowedPerYear: input.daysAllowedPerYear,
|
|
4121
|
+
paid: input.paid ?? true,
|
|
4122
|
+
requiresApproval: input.requiresApproval ?? true,
|
|
4123
|
+
color: input.color,
|
|
4124
|
+
description: input.description
|
|
4125
|
+
};
|
|
4126
|
+
const item = await this.leaveTypesCollection.create({
|
|
4127
|
+
title: input.name,
|
|
4128
|
+
status: "published",
|
|
4129
|
+
data: leaveTypeData
|
|
4130
|
+
}, authorId);
|
|
4131
|
+
await this.engine.hooks.doAction("hrms.leave_type_created", item);
|
|
4132
|
+
return item;
|
|
4133
|
+
}
|
|
4134
|
+
async getLeaveType(id) {
|
|
4135
|
+
return this.leaveTypesCollection.findById(id);
|
|
4136
|
+
}
|
|
4137
|
+
async listLeaveTypes(employerId) {
|
|
4138
|
+
const result = await this.leaveTypesCollection.find({ limit: 100 });
|
|
4139
|
+
if (!employerId) return result.items;
|
|
4140
|
+
return result.items.filter((lt) => !lt.data.employerId || lt.data.employerId === employerId);
|
|
4141
|
+
}
|
|
4142
|
+
/**
|
|
4143
|
+
* Calculate leave balance report for an employee for a given year.
|
|
4144
|
+
*/
|
|
4145
|
+
async calculateLeaveBalance(employeeId, year) {
|
|
4146
|
+
const targetYear = year ?? (/* @__PURE__ */ new Date()).getFullYear();
|
|
4147
|
+
const employee = await this.getEmployee(employeeId);
|
|
4148
|
+
if (!employee) throw new Error(`[HRMSService] Employee with ID '${employeeId}' not found.`);
|
|
4149
|
+
const leaveTypes = await this.listLeaveTypes(employee.data.employerId);
|
|
4150
|
+
const allRequests = await this.leaveRequestsCollection.find({ limit: 1e3 });
|
|
4151
|
+
const yearStr = String(targetYear);
|
|
4152
|
+
const employeeRequests = allRequests.items.filter((r) => r.data.employeeId === employeeId && (r.data.startDate.startsWith(yearStr) || r.data.endDate.startsWith(yearStr)));
|
|
4153
|
+
const balances = leaveTypes.map((lt) => {
|
|
4154
|
+
const approved = employeeRequests.filter((r) => r.data.leaveTypeId === lt.id && r.data.status === "approved");
|
|
4155
|
+
const pending = employeeRequests.filter((r) => r.data.leaveTypeId === lt.id && r.data.status === "pending");
|
|
4156
|
+
const usedDays = approved.reduce((sum, r) => sum + (r.data.daysCount || 0), 0);
|
|
4157
|
+
const pendingDays = pending.reduce((sum, r) => sum + (r.data.daysCount || 0), 0);
|
|
4158
|
+
const allocatedDays = lt.data.daysAllowedPerYear ?? 0;
|
|
4159
|
+
const remainingDays = Math.max(0, allocatedDays - usedDays);
|
|
4160
|
+
return {
|
|
4161
|
+
leaveTypeId: lt.id,
|
|
4162
|
+
leaveTypeName: lt.data.name,
|
|
4163
|
+
leaveTypeCode: lt.data.code,
|
|
4164
|
+
allocatedDays,
|
|
4165
|
+
usedDays,
|
|
4166
|
+
pendingDays,
|
|
4167
|
+
remainingDays
|
|
4168
|
+
};
|
|
4169
|
+
});
|
|
4170
|
+
const report = {
|
|
4171
|
+
employeeId,
|
|
4172
|
+
year: targetYear,
|
|
4173
|
+
balances,
|
|
4174
|
+
totalAllocated: balances.reduce((sum, b) => sum + b.allocatedDays, 0),
|
|
4175
|
+
totalUsed: balances.reduce((sum, b) => sum + b.usedDays, 0),
|
|
4176
|
+
totalRemaining: balances.reduce((sum, b) => sum + b.remainingDays, 0)
|
|
4177
|
+
};
|
|
4178
|
+
return this.engine.hooks.applyFilters("hrms.calculate_leave_balance", report, employeeId, targetYear);
|
|
4179
|
+
}
|
|
4180
|
+
/**
|
|
4181
|
+
* Submit a new leave request.
|
|
4182
|
+
*/
|
|
4183
|
+
async requestLeave(input, authorId) {
|
|
4184
|
+
const employee = await this.getEmployee(input.employeeId);
|
|
4185
|
+
if (!employee) throw new Error(`[HRMSService] Employee with ID '${input.employeeId}' not found.`);
|
|
4186
|
+
const leaveType = await this.getLeaveType(input.leaveTypeId);
|
|
4187
|
+
if (!leaveType) throw new Error(`[HRMSService] Leave type with ID '${input.leaveTypeId}' not found.`);
|
|
4188
|
+
if (input.startDate > input.endDate) throw new Error(`[HRMSService] Start date '${input.startDate}' cannot be after end date '${input.endDate}'.`);
|
|
4189
|
+
const start = new Date(input.startDate);
|
|
4190
|
+
const end = new Date(input.endDate);
|
|
4191
|
+
const calculatedDays = Math.max(1, Math.round((end.getTime() - start.getTime()) / (1e3 * 60 * 60 * 24)) + 1);
|
|
4192
|
+
const daysCount = input.daysCount ?? calculatedDays;
|
|
4193
|
+
const startYear = start.getFullYear();
|
|
4194
|
+
const balance = (await this.calculateLeaveBalance(employee.id, startYear)).balances.find((b) => b.leaveTypeId === leaveType.id);
|
|
4195
|
+
if (balance && leaveType.data.requiresApproval && daysCount > balance.remainingDays) throw new Error(`[HRMSService] Insufficient leave balance for ${leaveType.data.name}. Requested: ${daysCount}, Remaining: ${balance.remainingDays}.`);
|
|
4196
|
+
const leaveRequestData = {
|
|
4197
|
+
employerId: input.employerId ?? employee.data.employerId,
|
|
4198
|
+
employeeId: employee.id,
|
|
4199
|
+
leaveTypeId: leaveType.id,
|
|
4200
|
+
startDate: input.startDate,
|
|
4201
|
+
endDate: input.endDate,
|
|
4202
|
+
daysCount,
|
|
4203
|
+
reason: input.reason,
|
|
4204
|
+
status: "pending"
|
|
4205
|
+
};
|
|
4206
|
+
const item = await this.leaveRequestsCollection.create({
|
|
4207
|
+
title: `${employee.title} - ${leaveType.data.name} (${input.startDate})`,
|
|
4208
|
+
status: "published",
|
|
4209
|
+
data: leaveRequestData
|
|
4210
|
+
}, authorId);
|
|
4211
|
+
await this.engine.hooks.doAction("hrms.leave_requested", item, employee);
|
|
4212
|
+
return item;
|
|
4213
|
+
}
|
|
4214
|
+
/**
|
|
4215
|
+
* Approve a pending leave request.
|
|
4216
|
+
*/
|
|
4217
|
+
async approveLeave(input) {
|
|
4218
|
+
const request = await this.leaveRequestsCollection.findById(input.requestId);
|
|
4219
|
+
if (!request) throw new Error(`[HRMSService] Leave request with ID '${input.requestId}' not found.`);
|
|
4220
|
+
if (request.data.status !== "pending") throw new Error(`[HRMSService] Cannot approve leave request with status '${request.data.status}'.`);
|
|
4221
|
+
const updated = await this.leaveRequestsCollection.update(request.id, { data: {
|
|
4222
|
+
...request.data,
|
|
4223
|
+
status: "approved",
|
|
4224
|
+
approvedBy: input.approverId,
|
|
4225
|
+
approvedAt: (/* @__PURE__ */ new Date()).toISOString()
|
|
4226
|
+
} });
|
|
4227
|
+
if (!updated) throw new Error(`[HRMSService] Failed to update leave request.`);
|
|
4228
|
+
await this.engine.hooks.doAction("hrms.leave_approved", updated);
|
|
4229
|
+
return updated;
|
|
4230
|
+
}
|
|
4231
|
+
/**
|
|
4232
|
+
* Reject a pending leave request.
|
|
4233
|
+
*/
|
|
4234
|
+
async rejectLeave(input) {
|
|
4235
|
+
const request = await this.leaveRequestsCollection.findById(input.requestId);
|
|
4236
|
+
if (!request) throw new Error(`[HRMSService] Leave request with ID '${input.requestId}' not found.`);
|
|
4237
|
+
if (request.data.status !== "pending") throw new Error(`[HRMSService] Cannot reject leave request with status '${request.data.status}'.`);
|
|
4238
|
+
const updated = await this.leaveRequestsCollection.update(request.id, { data: {
|
|
4239
|
+
...request.data,
|
|
4240
|
+
status: "rejected",
|
|
4241
|
+
approvedBy: input.approverId,
|
|
4242
|
+
rejectionReason: input.reason,
|
|
4243
|
+
approvedAt: (/* @__PURE__ */ new Date()).toISOString()
|
|
4244
|
+
} });
|
|
4245
|
+
if (!updated) throw new Error(`[HRMSService] Failed to update leave request.`);
|
|
4246
|
+
await this.engine.hooks.doAction("hrms.leave_rejected", updated);
|
|
4247
|
+
return updated;
|
|
4248
|
+
}
|
|
4249
|
+
/**
|
|
4250
|
+
* Cancel a leave request.
|
|
4251
|
+
*/
|
|
4252
|
+
async cancelLeave(requestId) {
|
|
4253
|
+
const request = await this.leaveRequestsCollection.findById(requestId);
|
|
4254
|
+
if (!request) throw new Error(`[HRMSService] Leave request with ID '${requestId}' not found.`);
|
|
4255
|
+
if (request.data.status === "cancelled") return request;
|
|
4256
|
+
const updated = await this.leaveRequestsCollection.update(request.id, { data: {
|
|
4257
|
+
...request.data,
|
|
4258
|
+
status: "cancelled"
|
|
4259
|
+
} });
|
|
4260
|
+
if (!updated) throw new Error(`[HRMSService] Failed to cancel leave request.`);
|
|
4261
|
+
await this.engine.hooks.doAction("hrms.leave_cancelled", updated);
|
|
4262
|
+
return updated;
|
|
4263
|
+
}
|
|
4264
|
+
async listLeaveRequests(query = {}) {
|
|
4265
|
+
const limit = query.limit ?? 20;
|
|
4266
|
+
const offset = query.page ? (query.page - 1) * limit : 0;
|
|
4267
|
+
let items = (await this.leaveRequestsCollection.find({ limit: 1e3 })).items;
|
|
4268
|
+
if (query.employerId) items = items.filter((r) => r.data.employerId === query.employerId);
|
|
4269
|
+
if (query.employeeId) items = items.filter((r) => r.data.employeeId === query.employeeId);
|
|
4270
|
+
if (query.leaveTypeId) items = items.filter((r) => r.data.leaveTypeId === query.leaveTypeId);
|
|
4271
|
+
if (query.status) items = items.filter((r) => r.data.status === query.status);
|
|
4272
|
+
if (query.year) {
|
|
4273
|
+
const yearStr = String(query.year);
|
|
4274
|
+
items = items.filter((r) => r.data.startDate.startsWith(yearStr) || r.data.endDate.startsWith(yearStr));
|
|
4275
|
+
}
|
|
4276
|
+
const total = items.length;
|
|
4277
|
+
return {
|
|
4278
|
+
items: items.slice(offset, offset + limit),
|
|
4279
|
+
total,
|
|
4280
|
+
limit,
|
|
4281
|
+
offset,
|
|
4282
|
+
hasMore: offset + limit < total
|
|
4283
|
+
};
|
|
4284
|
+
}
|
|
4285
|
+
};
|
|
4286
|
+
//#endregion
|
|
4287
|
+
//#region src/plugins/hrms/routes.ts
|
|
4288
|
+
function json$1(data, status = 200) {
|
|
4289
|
+
return new Response(JSON.stringify(data), {
|
|
4290
|
+
status,
|
|
4291
|
+
headers: {
|
|
4292
|
+
"Content-Type": "application/json",
|
|
4293
|
+
"Access-Control-Allow-Origin": "*"
|
|
4294
|
+
}
|
|
4295
|
+
});
|
|
4296
|
+
}
|
|
4297
|
+
function badRequest$1(message) {
|
|
4298
|
+
return json$1({ error: message }, 400);
|
|
4299
|
+
}
|
|
4300
|
+
function notFound$1(message) {
|
|
4301
|
+
return json$1({ error: message }, 404);
|
|
4302
|
+
}
|
|
4303
|
+
function registerHRMSRoutes(ctx, service, options = {}) {
|
|
4304
|
+
const prefix = (options.apiPrefix ?? "/api/hrms").replace(/\/+$/, "");
|
|
4305
|
+
ctx.registerRoute("GET", `${prefix}/employers`, async (_req, { url }) => {
|
|
4306
|
+
try {
|
|
4307
|
+
const status = url.searchParams.get("status");
|
|
4308
|
+
const pageStr = url.searchParams.get("page");
|
|
4309
|
+
const limitStr = url.searchParams.get("limit");
|
|
4310
|
+
const page = pageStr ? parseInt(pageStr, 10) : void 0;
|
|
4311
|
+
const limit = limitStr ? parseInt(limitStr, 10) : void 0;
|
|
4312
|
+
return json$1(await service.listEmployers({
|
|
4313
|
+
status,
|
|
4314
|
+
page,
|
|
4315
|
+
limit
|
|
4316
|
+
}));
|
|
4317
|
+
} catch (err) {
|
|
4318
|
+
return badRequest$1(err instanceof Error ? err.message : String(err));
|
|
4319
|
+
}
|
|
4320
|
+
});
|
|
4321
|
+
ctx.registerRoute("POST", `${prefix}/employers`, async (req) => {
|
|
4322
|
+
try {
|
|
4323
|
+
const body = await req.json();
|
|
4324
|
+
if (!body.companyName) return badRequest$1("companyName is required.");
|
|
4325
|
+
return json$1(await service.createEmployer(body), 201);
|
|
4326
|
+
} catch (err) {
|
|
4327
|
+
return badRequest$1(err instanceof Error ? err.message : String(err));
|
|
4328
|
+
}
|
|
4329
|
+
});
|
|
4330
|
+
ctx.registerRoute("GET", `${prefix}/employers/:id`, async (_req, { params }) => {
|
|
4331
|
+
try {
|
|
4332
|
+
const employer = await service.getEmployer(params.id);
|
|
4333
|
+
if (!employer) return notFound$1(`Employer '${params.id}' not found.`);
|
|
4334
|
+
return json$1(employer);
|
|
4335
|
+
} catch (err) {
|
|
4336
|
+
return badRequest$1(err instanceof Error ? err.message : String(err));
|
|
4337
|
+
}
|
|
4338
|
+
});
|
|
4339
|
+
ctx.registerRoute("PUT", `${prefix}/employers/:id`, async (req, { params }) => {
|
|
4340
|
+
try {
|
|
4341
|
+
const body = await req.json();
|
|
4342
|
+
const updated = await service.updateEmployer(params.id, body);
|
|
4343
|
+
if (!updated) return notFound$1(`Employer '${params.id}' not found.`);
|
|
4344
|
+
return json$1(updated);
|
|
4345
|
+
} catch (err) {
|
|
4346
|
+
return badRequest$1(err instanceof Error ? err.message : String(err));
|
|
4347
|
+
}
|
|
4348
|
+
});
|
|
4349
|
+
ctx.registerRoute("GET", `${prefix}/employees`, async (_req, { url }) => {
|
|
4350
|
+
try {
|
|
4351
|
+
const employerId = url.searchParams.get("employerId") ?? void 0;
|
|
4352
|
+
const department = url.searchParams.get("department") ?? void 0;
|
|
4353
|
+
const employmentType = url.searchParams.get("employmentType");
|
|
4354
|
+
const status = url.searchParams.get("status");
|
|
4355
|
+
const search = url.searchParams.get("search") ?? void 0;
|
|
4356
|
+
const pageStr = url.searchParams.get("page");
|
|
4357
|
+
const limitStr = url.searchParams.get("limit");
|
|
4358
|
+
const page = pageStr ? parseInt(pageStr, 10) : void 0;
|
|
4359
|
+
const limit = limitStr ? parseInt(limitStr, 10) : void 0;
|
|
4360
|
+
return json$1(await service.listEmployees({
|
|
4361
|
+
employerId,
|
|
4362
|
+
department,
|
|
4363
|
+
employmentType,
|
|
4364
|
+
status,
|
|
4365
|
+
search,
|
|
4366
|
+
page,
|
|
4367
|
+
limit
|
|
4368
|
+
}));
|
|
4369
|
+
} catch (err) {
|
|
4370
|
+
return badRequest$1(err instanceof Error ? err.message : String(err));
|
|
4371
|
+
}
|
|
4372
|
+
});
|
|
4373
|
+
ctx.registerRoute("POST", `${prefix}/employees`, async (req) => {
|
|
4374
|
+
try {
|
|
4375
|
+
const body = await req.json();
|
|
4376
|
+
if (!body.employerId) return badRequest$1("employerId is required.");
|
|
4377
|
+
if (!body.employeeNumber) return badRequest$1("employeeNumber is required.");
|
|
4378
|
+
if (!body.firstName || !body.lastName) return badRequest$1("firstName and lastName are required.");
|
|
4379
|
+
if (!body.email) return badRequest$1("email is required.");
|
|
4380
|
+
return json$1(await service.createEmployee(body), 201);
|
|
4381
|
+
} catch (err) {
|
|
4382
|
+
return badRequest$1(err instanceof Error ? err.message : String(err));
|
|
4383
|
+
}
|
|
4384
|
+
});
|
|
4385
|
+
ctx.registerRoute("GET", `${prefix}/employees/:id`, async (_req, { params }) => {
|
|
4386
|
+
try {
|
|
4387
|
+
const employee = await service.getEmployee(params.id);
|
|
4388
|
+
if (!employee) return notFound$1(`Employee '${params.id}' not found.`);
|
|
4389
|
+
return json$1(employee);
|
|
4390
|
+
} catch (err) {
|
|
4391
|
+
return badRequest$1(err instanceof Error ? err.message : String(err));
|
|
4392
|
+
}
|
|
4393
|
+
});
|
|
4394
|
+
ctx.registerRoute("PUT", `${prefix}/employees/:id`, async (req, { params }) => {
|
|
4395
|
+
try {
|
|
4396
|
+
const body = await req.json();
|
|
4397
|
+
const updated = await service.updateEmployee(params.id, body);
|
|
4398
|
+
if (!updated) return notFound$1(`Employee '${params.id}' not found.`);
|
|
4399
|
+
return json$1(updated);
|
|
4400
|
+
} catch (err) {
|
|
4401
|
+
return badRequest$1(err instanceof Error ? err.message : String(err));
|
|
4402
|
+
}
|
|
4403
|
+
});
|
|
4404
|
+
ctx.registerRoute("DELETE", `${prefix}/employees/:id`, async (_req, { params }) => {
|
|
4405
|
+
try {
|
|
4406
|
+
if (!await service.deleteEmployee(params.id)) return notFound$1(`Employee '${params.id}' not found.`);
|
|
4407
|
+
return json$1({ success: true });
|
|
4408
|
+
} catch (err) {
|
|
4409
|
+
return badRequest$1(err instanceof Error ? err.message : String(err));
|
|
4410
|
+
}
|
|
4411
|
+
});
|
|
4412
|
+
ctx.registerRoute("GET", `${prefix}/employees/:id/leave-balance`, async (_req, { params, url }) => {
|
|
4413
|
+
try {
|
|
4414
|
+
const yearStr = url.searchParams.get("year");
|
|
4415
|
+
const year = yearStr ? parseInt(yearStr, 10) : void 0;
|
|
4416
|
+
return json$1(await service.calculateLeaveBalance(params.id, year));
|
|
4417
|
+
} catch (err) {
|
|
4418
|
+
return badRequest$1(err instanceof Error ? err.message : String(err));
|
|
4419
|
+
}
|
|
4420
|
+
});
|
|
4421
|
+
ctx.registerRoute("GET", `${prefix}/employees/:id/direct-reports`, async (_req, { params }) => {
|
|
4422
|
+
try {
|
|
4423
|
+
const reports = await service.getDirectReports(params.id);
|
|
4424
|
+
return json$1({
|
|
4425
|
+
items: reports,
|
|
4426
|
+
total: reports.length
|
|
4427
|
+
});
|
|
4428
|
+
} catch (err) {
|
|
4429
|
+
return badRequest$1(err instanceof Error ? err.message : String(err));
|
|
4430
|
+
}
|
|
4431
|
+
});
|
|
4432
|
+
ctx.registerRoute("POST", `${prefix}/attendance/check-in`, async (req) => {
|
|
4433
|
+
try {
|
|
4434
|
+
const body = await req.json();
|
|
4435
|
+
if (!body.employeeId) return badRequest$1("employeeId is required.");
|
|
4436
|
+
return json$1(await service.checkIn(body), 201);
|
|
4437
|
+
} catch (err) {
|
|
4438
|
+
return badRequest$1(err instanceof Error ? err.message : String(err));
|
|
4439
|
+
}
|
|
4440
|
+
});
|
|
4441
|
+
ctx.registerRoute("POST", `${prefix}/attendance/check-out`, async (req) => {
|
|
4442
|
+
try {
|
|
4443
|
+
const body = await req.json();
|
|
4444
|
+
if (!body.employeeId) return badRequest$1("employeeId is required.");
|
|
4445
|
+
return json$1(await service.checkOut(body));
|
|
4446
|
+
} catch (err) {
|
|
4447
|
+
return badRequest$1(err instanceof Error ? err.message : String(err));
|
|
4448
|
+
}
|
|
4449
|
+
});
|
|
4450
|
+
ctx.registerRoute("GET", `${prefix}/attendance`, async (_req, { url }) => {
|
|
4451
|
+
try {
|
|
4452
|
+
const employerId = url.searchParams.get("employerId") ?? void 0;
|
|
4453
|
+
const employeeId = url.searchParams.get("employeeId") ?? void 0;
|
|
4454
|
+
const date = url.searchParams.get("date") ?? void 0;
|
|
4455
|
+
const startDate = url.searchParams.get("startDate") ?? void 0;
|
|
4456
|
+
const endDate = url.searchParams.get("endDate") ?? void 0;
|
|
4457
|
+
const status = url.searchParams.get("status");
|
|
4458
|
+
const pageStr = url.searchParams.get("page");
|
|
4459
|
+
const limitStr = url.searchParams.get("limit");
|
|
4460
|
+
const page = pageStr ? parseInt(pageStr, 10) : void 0;
|
|
4461
|
+
const limit = limitStr ? parseInt(limitStr, 10) : void 0;
|
|
4462
|
+
return json$1(await service.listAttendance({
|
|
4463
|
+
employerId,
|
|
4464
|
+
employeeId,
|
|
4465
|
+
date,
|
|
4466
|
+
startDate,
|
|
4467
|
+
endDate,
|
|
4468
|
+
status,
|
|
4469
|
+
page,
|
|
4470
|
+
limit
|
|
4471
|
+
}));
|
|
4472
|
+
} catch (err) {
|
|
4473
|
+
return badRequest$1(err instanceof Error ? err.message : String(err));
|
|
4474
|
+
}
|
|
4475
|
+
});
|
|
4476
|
+
ctx.registerRoute("POST", `${prefix}/attendance/manual`, async (req) => {
|
|
4477
|
+
try {
|
|
4478
|
+
const body = await req.json();
|
|
4479
|
+
if (!body.employerId || !body.employeeId || !body.date || !body.checkInAt) return badRequest$1("employerId, employeeId, date, and checkInAt are required.");
|
|
4480
|
+
return json$1(await service.recordAttendanceManual(body), 201);
|
|
4481
|
+
} catch (err) {
|
|
4482
|
+
return badRequest$1(err instanceof Error ? err.message : String(err));
|
|
4483
|
+
}
|
|
4484
|
+
});
|
|
4485
|
+
ctx.registerRoute("GET", `${prefix}/leave-types`, async (_req, { url }) => {
|
|
4486
|
+
try {
|
|
4487
|
+
const employerId = url.searchParams.get("employerId") ?? void 0;
|
|
4488
|
+
const types = await service.listLeaveTypes(employerId);
|
|
4489
|
+
return json$1({
|
|
4490
|
+
items: types,
|
|
4491
|
+
total: types.length
|
|
4492
|
+
});
|
|
4493
|
+
} catch (err) {
|
|
4494
|
+
return badRequest$1(err instanceof Error ? err.message : String(err));
|
|
4495
|
+
}
|
|
4496
|
+
});
|
|
4497
|
+
ctx.registerRoute("POST", `${prefix}/leave-types`, async (req) => {
|
|
4498
|
+
try {
|
|
4499
|
+
const body = await req.json();
|
|
4500
|
+
if (!body.name || !body.code || body.daysAllowedPerYear === void 0) return badRequest$1("name, code, and daysAllowedPerYear are required.");
|
|
4501
|
+
return json$1(await service.createLeaveType(body), 201);
|
|
4502
|
+
} catch (err) {
|
|
4503
|
+
return badRequest$1(err instanceof Error ? err.message : String(err));
|
|
4504
|
+
}
|
|
4505
|
+
});
|
|
4506
|
+
ctx.registerRoute("GET", `${prefix}/leave-types/:id`, async (_req, { params }) => {
|
|
4507
|
+
try {
|
|
4508
|
+
const leaveType = await service.getLeaveType(params.id);
|
|
4509
|
+
if (!leaveType) return notFound$1(`Leave type '${params.id}' not found.`);
|
|
4510
|
+
return json$1(leaveType);
|
|
4511
|
+
} catch (err) {
|
|
4512
|
+
return badRequest$1(err instanceof Error ? err.message : String(err));
|
|
4513
|
+
}
|
|
4514
|
+
});
|
|
4515
|
+
ctx.registerRoute("GET", `${prefix}/leave-requests`, async (_req, { url }) => {
|
|
4516
|
+
try {
|
|
4517
|
+
const employerId = url.searchParams.get("employerId") ?? void 0;
|
|
4518
|
+
const employeeId = url.searchParams.get("employeeId") ?? void 0;
|
|
4519
|
+
const leaveTypeId = url.searchParams.get("leaveTypeId") ?? void 0;
|
|
4520
|
+
const status = url.searchParams.get("status");
|
|
4521
|
+
const yearStr = url.searchParams.get("year");
|
|
4522
|
+
const year = yearStr ? parseInt(yearStr, 10) : void 0;
|
|
4523
|
+
const pageStr = url.searchParams.get("page");
|
|
4524
|
+
const limitStr = url.searchParams.get("limit");
|
|
4525
|
+
const page = pageStr ? parseInt(pageStr, 10) : void 0;
|
|
4526
|
+
const limit = limitStr ? parseInt(limitStr, 10) : void 0;
|
|
4527
|
+
return json$1(await service.listLeaveRequests({
|
|
4528
|
+
employerId,
|
|
4529
|
+
employeeId,
|
|
4530
|
+
leaveTypeId,
|
|
4531
|
+
status,
|
|
4532
|
+
year,
|
|
4533
|
+
page,
|
|
4534
|
+
limit
|
|
4535
|
+
}));
|
|
4536
|
+
} catch (err) {
|
|
4537
|
+
return badRequest$1(err instanceof Error ? err.message : String(err));
|
|
4538
|
+
}
|
|
4539
|
+
});
|
|
4540
|
+
ctx.registerRoute("POST", `${prefix}/leave-requests`, async (req) => {
|
|
4541
|
+
try {
|
|
4542
|
+
const body = await req.json();
|
|
4543
|
+
if (!body.employeeId || !body.leaveTypeId || !body.startDate || !body.endDate) return badRequest$1("employeeId, leaveTypeId, startDate, and endDate are required.");
|
|
4544
|
+
return json$1(await service.requestLeave(body), 201);
|
|
4545
|
+
} catch (err) {
|
|
4546
|
+
return badRequest$1(err instanceof Error ? err.message : String(err));
|
|
4547
|
+
}
|
|
4548
|
+
});
|
|
4549
|
+
ctx.registerRoute("POST", `${prefix}/leave-requests/:id/approve`, async (req, { params }) => {
|
|
4550
|
+
try {
|
|
4551
|
+
const approverId = (await req.json().catch(() => ({}))).approverId ?? "admin";
|
|
4552
|
+
return json$1(await service.approveLeave({
|
|
4553
|
+
requestId: params.id,
|
|
4554
|
+
approverId
|
|
4555
|
+
}));
|
|
4556
|
+
} catch (err) {
|
|
4557
|
+
return badRequest$1(err instanceof Error ? err.message : String(err));
|
|
4558
|
+
}
|
|
4559
|
+
});
|
|
4560
|
+
ctx.registerRoute("POST", `${prefix}/leave-requests/:id/reject`, async (req, { params }) => {
|
|
4561
|
+
try {
|
|
4562
|
+
const body = await req.json().catch(() => ({}));
|
|
4563
|
+
const approverId = body.approverId ?? "admin";
|
|
4564
|
+
return json$1(await service.rejectLeave({
|
|
4565
|
+
requestId: params.id,
|
|
4566
|
+
approverId,
|
|
4567
|
+
reason: body.reason
|
|
4568
|
+
}));
|
|
4569
|
+
} catch (err) {
|
|
4570
|
+
return badRequest$1(err instanceof Error ? err.message : String(err));
|
|
4571
|
+
}
|
|
4572
|
+
});
|
|
4573
|
+
ctx.registerRoute("POST", `${prefix}/leave-requests/:id/cancel`, async (_req, { params }) => {
|
|
4574
|
+
try {
|
|
4575
|
+
return json$1(await service.cancelLeave(params.id));
|
|
4576
|
+
} catch (err) {
|
|
4577
|
+
return badRequest$1(err instanceof Error ? err.message : String(err));
|
|
4578
|
+
}
|
|
4579
|
+
});
|
|
4580
|
+
}
|
|
4581
|
+
//#endregion
|
|
4582
|
+
//#region src/plugins/hrms/client.ts
|
|
4583
|
+
var HRMSClient = class {
|
|
4584
|
+
client;
|
|
4585
|
+
options;
|
|
4586
|
+
service;
|
|
4587
|
+
prefix;
|
|
4588
|
+
constructor(client, options = {}) {
|
|
4589
|
+
this.client = client;
|
|
4590
|
+
this.options = options;
|
|
4591
|
+
this.prefix = (options.apiPrefix ?? "/api/hrms").replace(/\/+$/, "");
|
|
4592
|
+
const engine = client.getEngine();
|
|
4593
|
+
if (engine) this.service = new HRMSService(engine, options);
|
|
4594
|
+
}
|
|
4595
|
+
employers = {
|
|
4596
|
+
find: async (query = {}) => {
|
|
4597
|
+
if (this.service) return this.service.listEmployers(query);
|
|
4598
|
+
const params = new URLSearchParams();
|
|
4599
|
+
if (query.status) params.set("status", query.status);
|
|
4600
|
+
if (query.page) params.set("page", String(query.page));
|
|
4601
|
+
if (query.limit) params.set("limit", String(query.limit));
|
|
4602
|
+
const q = params.toString() ? `?${params.toString()}` : "";
|
|
4603
|
+
return this.client.request(`${this.prefix}/employers${q}`);
|
|
4604
|
+
},
|
|
4605
|
+
get: async (id) => {
|
|
4606
|
+
if (this.service) return this.service.getEmployer(id);
|
|
4607
|
+
return this.client.request(`${this.prefix}/employers/${encodeURIComponent(id)}`);
|
|
4608
|
+
},
|
|
4609
|
+
create: async (input) => {
|
|
4610
|
+
if (this.service) return this.service.createEmployer(input);
|
|
4611
|
+
return this.client.request(`${this.prefix}/employers`, {
|
|
4612
|
+
method: "POST",
|
|
4613
|
+
body: JSON.stringify(input)
|
|
4614
|
+
});
|
|
4615
|
+
},
|
|
4616
|
+
update: async (id, input) => {
|
|
4617
|
+
if (this.service) return this.service.updateEmployer(id, input);
|
|
4618
|
+
return this.client.request(`${this.prefix}/employers/${encodeURIComponent(id)}`, {
|
|
4619
|
+
method: "PUT",
|
|
4620
|
+
body: JSON.stringify(input)
|
|
4621
|
+
});
|
|
4622
|
+
}
|
|
4623
|
+
};
|
|
4624
|
+
employees = {
|
|
4625
|
+
find: async (query = {}) => {
|
|
4626
|
+
if (this.service) return this.service.listEmployees(query);
|
|
4627
|
+
const params = new URLSearchParams();
|
|
4628
|
+
if (query.employerId) params.set("employerId", query.employerId);
|
|
4629
|
+
if (query.department) params.set("department", query.department);
|
|
4630
|
+
if (query.employmentType) params.set("employmentType", query.employmentType);
|
|
4631
|
+
if (query.status) params.set("status", query.status);
|
|
4632
|
+
if (query.search) params.set("search", query.search);
|
|
4633
|
+
if (query.page) params.set("page", String(query.page));
|
|
4634
|
+
if (query.limit) params.set("limit", String(query.limit));
|
|
4635
|
+
const q = params.toString() ? `?${params.toString()}` : "";
|
|
4636
|
+
return this.client.request(`${this.prefix}/employees${q}`);
|
|
4637
|
+
},
|
|
4638
|
+
get: async (id) => {
|
|
4639
|
+
if (this.service) return this.service.getEmployee(id);
|
|
4640
|
+
return this.client.request(`${this.prefix}/employees/${encodeURIComponent(id)}`);
|
|
4641
|
+
},
|
|
4642
|
+
getByNumber: async (employerId, employeeNumber) => {
|
|
4643
|
+
if (this.service) return this.service.getEmployeeByNumber(employerId, employeeNumber);
|
|
4644
|
+
return (await this.employees.find({
|
|
4645
|
+
employerId,
|
|
4646
|
+
search: employeeNumber
|
|
4647
|
+
})).items.find((e) => e.data.employeeNumber === employeeNumber) ?? null;
|
|
4648
|
+
},
|
|
4649
|
+
create: async (input) => {
|
|
4650
|
+
if (this.service) return this.service.createEmployee(input);
|
|
4651
|
+
return this.client.request(`${this.prefix}/employees`, {
|
|
4652
|
+
method: "POST",
|
|
4653
|
+
body: JSON.stringify(input)
|
|
4654
|
+
});
|
|
4655
|
+
},
|
|
4656
|
+
update: async (id, input) => {
|
|
4657
|
+
if (this.service) return this.service.updateEmployee(id, input);
|
|
4658
|
+
return this.client.request(`${this.prefix}/employees/${encodeURIComponent(id)}`, {
|
|
4659
|
+
method: "PUT",
|
|
4660
|
+
body: JSON.stringify(input)
|
|
4661
|
+
});
|
|
4662
|
+
},
|
|
4663
|
+
delete: async (id) => {
|
|
4664
|
+
if (this.service) return this.service.deleteEmployee(id);
|
|
4665
|
+
return (await this.client.request(`${this.prefix}/employees/${encodeURIComponent(id)}`, { method: "DELETE" })).success;
|
|
4666
|
+
},
|
|
4667
|
+
getLeaveBalance: async (employeeId, year) => {
|
|
4668
|
+
if (this.service) return this.service.calculateLeaveBalance(employeeId, year);
|
|
4669
|
+
const q = year ? `?year=${year}` : "";
|
|
4670
|
+
return this.client.request(`${this.prefix}/employees/${encodeURIComponent(employeeId)}/leave-balance${q}`);
|
|
4671
|
+
},
|
|
4672
|
+
getDirectReports: async (managerId) => {
|
|
4673
|
+
if (this.service) return this.service.getDirectReports(managerId);
|
|
4674
|
+
return (await this.client.request(`${this.prefix}/employees/${encodeURIComponent(managerId)}/direct-reports`)).items;
|
|
4675
|
+
}
|
|
4676
|
+
};
|
|
4677
|
+
attendance = {
|
|
4678
|
+
checkIn: async (input) => {
|
|
4679
|
+
if (this.service) return this.service.checkIn(input);
|
|
4680
|
+
return this.client.request(`${this.prefix}/attendance/check-in`, {
|
|
4681
|
+
method: "POST",
|
|
4682
|
+
body: JSON.stringify(input)
|
|
4683
|
+
});
|
|
4684
|
+
},
|
|
4685
|
+
checkOut: async (input) => {
|
|
4686
|
+
if (this.service) return this.service.checkOut(input);
|
|
4687
|
+
return this.client.request(`${this.prefix}/attendance/check-out`, {
|
|
4688
|
+
method: "POST",
|
|
4689
|
+
body: JSON.stringify(input)
|
|
4690
|
+
});
|
|
4691
|
+
},
|
|
4692
|
+
getDaily: async (employeeId, date) => {
|
|
4693
|
+
if (this.service) return this.service.getDailyAttendance(employeeId, date);
|
|
4694
|
+
return (await this.attendance.find({
|
|
4695
|
+
employeeId,
|
|
4696
|
+
date
|
|
4697
|
+
})).items[0] ?? null;
|
|
4698
|
+
},
|
|
4699
|
+
find: async (query = {}) => {
|
|
4700
|
+
if (this.service) return this.service.listAttendance(query);
|
|
4701
|
+
const params = new URLSearchParams();
|
|
4702
|
+
if (query.employerId) params.set("employerId", query.employerId);
|
|
4703
|
+
if (query.employeeId) params.set("employeeId", query.employeeId);
|
|
4704
|
+
if (query.date) params.set("date", query.date);
|
|
4705
|
+
if (query.startDate) params.set("startDate", query.startDate);
|
|
4706
|
+
if (query.endDate) params.set("endDate", query.endDate);
|
|
4707
|
+
if (query.status) params.set("status", query.status);
|
|
4708
|
+
if (query.page) params.set("page", String(query.page));
|
|
4709
|
+
if (query.limit) params.set("limit", String(query.limit));
|
|
4710
|
+
const q = params.toString() ? `?${params.toString()}` : "";
|
|
4711
|
+
return this.client.request(`${this.prefix}/attendance${q}`);
|
|
4712
|
+
},
|
|
4713
|
+
recordManual: async (input) => {
|
|
4714
|
+
if (this.service) return this.service.recordAttendanceManual(input);
|
|
4715
|
+
return this.client.request(`${this.prefix}/attendance/manual`, {
|
|
4716
|
+
method: "POST",
|
|
4717
|
+
body: JSON.stringify(input)
|
|
4718
|
+
});
|
|
4719
|
+
}
|
|
4720
|
+
};
|
|
4721
|
+
leaves = {
|
|
4722
|
+
listTypes: async (employerId) => {
|
|
4723
|
+
if (this.service) return this.service.listLeaveTypes(employerId);
|
|
4724
|
+
const q = employerId ? `?employerId=${encodeURIComponent(employerId)}` : "";
|
|
4725
|
+
return (await this.client.request(`${this.prefix}/leave-types${q}`)).items;
|
|
4726
|
+
},
|
|
4727
|
+
createType: async (input) => {
|
|
4728
|
+
if (this.service) return this.service.createLeaveType(input);
|
|
4729
|
+
return this.client.request(`${this.prefix}/leave-types`, {
|
|
4730
|
+
method: "POST",
|
|
4731
|
+
body: JSON.stringify(input)
|
|
4732
|
+
});
|
|
4733
|
+
},
|
|
4734
|
+
getType: async (id) => {
|
|
4735
|
+
if (this.service) return this.service.getLeaveType(id);
|
|
4736
|
+
return this.client.request(`${this.prefix}/leave-types/${encodeURIComponent(id)}`);
|
|
4737
|
+
},
|
|
4738
|
+
findRequests: async (query = {}) => {
|
|
4739
|
+
if (this.service) return this.service.listLeaveRequests(query);
|
|
4740
|
+
const params = new URLSearchParams();
|
|
4741
|
+
if (query.employerId) params.set("employerId", query.employerId);
|
|
4742
|
+
if (query.employeeId) params.set("employeeId", query.employeeId);
|
|
4743
|
+
if (query.leaveTypeId) params.set("leaveTypeId", query.leaveTypeId);
|
|
4744
|
+
if (query.status) params.set("status", query.status);
|
|
4745
|
+
if (query.year) params.set("year", String(query.year));
|
|
4746
|
+
if (query.page) params.set("page", String(query.page));
|
|
4747
|
+
if (query.limit) params.set("limit", String(query.limit));
|
|
4748
|
+
const q = params.toString() ? `?${params.toString()}` : "";
|
|
4749
|
+
return this.client.request(`${this.prefix}/leave-requests${q}`);
|
|
4750
|
+
},
|
|
4751
|
+
request: async (input) => {
|
|
4752
|
+
if (this.service) return this.service.requestLeave(input);
|
|
4753
|
+
return this.client.request(`${this.prefix}/leave-requests`, {
|
|
4754
|
+
method: "POST",
|
|
4755
|
+
body: JSON.stringify(input)
|
|
4756
|
+
});
|
|
4757
|
+
},
|
|
4758
|
+
approve: async (input) => {
|
|
4759
|
+
if (this.service) return this.service.approveLeave(input);
|
|
4760
|
+
return this.client.request(`${this.prefix}/leave-requests/${encodeURIComponent(input.requestId)}/approve`, {
|
|
4761
|
+
method: "POST",
|
|
4762
|
+
body: JSON.stringify({ approverId: input.approverId })
|
|
4763
|
+
});
|
|
4764
|
+
},
|
|
4765
|
+
reject: async (input) => {
|
|
4766
|
+
if (this.service) return this.service.rejectLeave(input);
|
|
4767
|
+
return this.client.request(`${this.prefix}/leave-requests/${encodeURIComponent(input.requestId)}/reject`, {
|
|
4768
|
+
method: "POST",
|
|
4769
|
+
body: JSON.stringify({
|
|
4770
|
+
approverId: input.approverId,
|
|
4771
|
+
reason: input.reason
|
|
4772
|
+
})
|
|
4773
|
+
});
|
|
4774
|
+
},
|
|
4775
|
+
cancel: async (requestId) => {
|
|
4776
|
+
if (this.service) return this.service.cancelLeave(requestId);
|
|
4777
|
+
return this.client.request(`${this.prefix}/leave-requests/${encodeURIComponent(requestId)}/cancel`, { method: "POST" });
|
|
4778
|
+
}
|
|
4779
|
+
};
|
|
4780
|
+
};
|
|
4781
|
+
/**
|
|
4782
|
+
* Get or create an HRMSClient adapter for a CMSClient.
|
|
4783
|
+
*/
|
|
4784
|
+
function getHRMSClient(client, options) {
|
|
4785
|
+
return new HRMSClient(client, options);
|
|
4786
|
+
}
|
|
4787
|
+
//#endregion
|
|
4788
|
+
//#region src/plugins/hrms/index.ts
|
|
4789
|
+
/**
|
|
4790
|
+
* @azlib/cms - Built-in HRMS Plugin
|
|
4791
|
+
*/
|
|
4792
|
+
/**
|
|
4793
|
+
* Built-in HRMS plugin factory for @azlib/cms.
|
|
4794
|
+
* Equips the CMS engine with multi-tenant employers, employee profiles,
|
|
4795
|
+
* daily attendance check-in/out tracking, and leave quota approval workflows.
|
|
4796
|
+
*/
|
|
4797
|
+
const hrmsPlugin = definePlugin((options) => {
|
|
4798
|
+
const opts = options || {};
|
|
4799
|
+
const collections = [createEmployeeCollection(opts)];
|
|
4800
|
+
if (opts.enableEmployers !== false) collections.unshift(createEmployerCollection(opts));
|
|
4801
|
+
if (opts.enableAttendance !== false) collections.push(createAttendanceCollection(opts));
|
|
4802
|
+
if (opts.enableLeaves !== false) {
|
|
4803
|
+
collections.push(createLeaveTypeCollection(opts));
|
|
4804
|
+
collections.push(createLeaveRequestCollection(opts));
|
|
4805
|
+
}
|
|
4806
|
+
return {
|
|
4807
|
+
name: "hrms",
|
|
4808
|
+
version: "1.0.0",
|
|
4809
|
+
description: "Built-in Human Resource Management System (HRMS) plugin for employers, employees, attendance, and leave management",
|
|
4810
|
+
collections,
|
|
4811
|
+
taxonomies: createHRMSTaxonomies(opts),
|
|
4812
|
+
setup(ctx) {
|
|
4813
|
+
const service = new HRMSService(ctx.engine, opts);
|
|
4814
|
+
ctx.engine.__hrmsService = service;
|
|
4815
|
+
registerHRMSRoutes(ctx, service, opts);
|
|
4816
|
+
}
|
|
4817
|
+
};
|
|
4818
|
+
});
|
|
4819
|
+
/**
|
|
4820
|
+
* Retrieve the active HRMSService instance associated with a CMSEngine.
|
|
4821
|
+
*/
|
|
4822
|
+
function getHRMSService(engine, options) {
|
|
4823
|
+
if (engine.__hrmsService) return engine.__hrmsService;
|
|
4824
|
+
const service = new HRMSService(engine, options);
|
|
4825
|
+
engine.__hrmsService = service;
|
|
4826
|
+
return service;
|
|
4827
|
+
}
|
|
4828
|
+
//#endregion
|
|
4829
|
+
//#region src/plugins/transfer/parsers/json.ts
|
|
4830
|
+
/**
|
|
4831
|
+
* @azlib/cms - Universal JSON Data Parser
|
|
4832
|
+
*/
|
|
4833
|
+
function parseJsonSource(input) {
|
|
4834
|
+
if (Array.isArray(input)) return input.filter((item) => Boolean(item && typeof item === "object" && !Array.isArray(item)));
|
|
4835
|
+
let text;
|
|
4836
|
+
if (typeof input === "string") text = input.trim();
|
|
4837
|
+
else if (input instanceof Uint8Array || Buffer.isBuffer(input)) text = new TextDecoder("utf-8").decode(input).trim();
|
|
4838
|
+
else if (input && typeof input === "object") {
|
|
4839
|
+
const obj = input;
|
|
4840
|
+
if (Array.isArray(obj.data)) return parseJsonSource(obj.data);
|
|
4841
|
+
if (Array.isArray(obj.items)) return parseJsonSource(obj.items);
|
|
4842
|
+
return [obj];
|
|
4843
|
+
} else throw new Error("[TransferParser] Invalid JSON input: expected string, buffer, or array.");
|
|
4844
|
+
if (text.charCodeAt(0) === 65279) text = text.slice(1);
|
|
4845
|
+
if (!text) return [];
|
|
4846
|
+
try {
|
|
4847
|
+
const parsed = JSON.parse(text);
|
|
4848
|
+
if (Array.isArray(parsed)) return parsed.filter((item) => Boolean(item && typeof item === "object" && !Array.isArray(item)));
|
|
4849
|
+
if (parsed && typeof parsed === "object") {
|
|
4850
|
+
if (Array.isArray(parsed.data)) return parseJsonSource(parsed.data);
|
|
4851
|
+
if (Array.isArray(parsed.items)) return parseJsonSource(parsed.items);
|
|
4852
|
+
return [parsed];
|
|
4853
|
+
}
|
|
4854
|
+
return [];
|
|
4855
|
+
} catch {
|
|
4856
|
+
const lines = text.split(/\r?\n/).map((l) => l.trim()).filter(Boolean);
|
|
4857
|
+
const records = [];
|
|
4858
|
+
for (const line of lines) try {
|
|
4859
|
+
const item = JSON.parse(line);
|
|
4860
|
+
if (item && typeof item === "object" && !Array.isArray(item)) records.push(item);
|
|
4861
|
+
} catch (err) {
|
|
4862
|
+
throw new Error(`[TransferParser] Failed to parse JSON source: ${err instanceof Error ? err.message : String(err)}`);
|
|
4863
|
+
}
|
|
4864
|
+
return records;
|
|
4865
|
+
}
|
|
4866
|
+
}
|
|
4867
|
+
//#endregion
|
|
4868
|
+
//#region src/plugins/transfer/parsers/csv.ts
|
|
4869
|
+
/**
|
|
4870
|
+
* @azlib/cms - Universal RFC 4180 CSV Data Parser
|
|
4871
|
+
*/
|
|
4872
|
+
function parseCsvSource(input) {
|
|
4873
|
+
let text;
|
|
4874
|
+
if (typeof input === "string") text = input;
|
|
4875
|
+
else if (input instanceof Uint8Array || Buffer.isBuffer(input)) text = new TextDecoder("utf-8").decode(input);
|
|
4876
|
+
else throw new Error("[TransferParser] Invalid CSV input: expected string or buffer.");
|
|
4877
|
+
if (text.charCodeAt(0) === 65279) text = text.slice(1);
|
|
4878
|
+
const rows = parseCsvRows(text);
|
|
4879
|
+
if (rows.length === 0) return [];
|
|
4880
|
+
const headers = rows[0].map((h, i) => {
|
|
4881
|
+
return h.trim() || `column_${i + 1}`;
|
|
4882
|
+
});
|
|
4883
|
+
const records = [];
|
|
4884
|
+
for (let r = 1; r < rows.length; r++) {
|
|
4885
|
+
const row = rows[r];
|
|
4886
|
+
if (row.length === 0 || row.length === 1 && row[0].trim() === "") continue;
|
|
4887
|
+
const record = {};
|
|
4888
|
+
for (let c = 0; c < headers.length; c++) {
|
|
4889
|
+
const header = headers[c];
|
|
4890
|
+
record[header] = coerceCsvValue(c < row.length ? row[c].trim() : "");
|
|
4891
|
+
}
|
|
4892
|
+
records.push(record);
|
|
4893
|
+
}
|
|
4894
|
+
return records;
|
|
4895
|
+
}
|
|
4896
|
+
/**
|
|
4897
|
+
* Tokenize CSV into 2D array of string cells following RFC 4180.
|
|
4898
|
+
*/
|
|
4899
|
+
function parseCsvRows(text) {
|
|
4900
|
+
const rows = [];
|
|
4901
|
+
let currentRow = [];
|
|
4902
|
+
let currentCell = "";
|
|
4903
|
+
let insideQuotes = false;
|
|
4904
|
+
let i = 0;
|
|
4905
|
+
const len = text.length;
|
|
4906
|
+
while (i < len) {
|
|
4907
|
+
const char = text[i];
|
|
4908
|
+
if (insideQuotes) if (char === "\"") if (i + 1 < len && text[i + 1] === "\"") {
|
|
4909
|
+
currentCell += "\"";
|
|
4910
|
+
i += 2;
|
|
4911
|
+
continue;
|
|
4912
|
+
} else {
|
|
4913
|
+
insideQuotes = false;
|
|
4914
|
+
i++;
|
|
4915
|
+
continue;
|
|
4916
|
+
}
|
|
4917
|
+
else {
|
|
4918
|
+
currentCell += char;
|
|
4919
|
+
i++;
|
|
4920
|
+
continue;
|
|
4921
|
+
}
|
|
4922
|
+
if (char === "\"") {
|
|
4923
|
+
insideQuotes = true;
|
|
4924
|
+
i++;
|
|
4925
|
+
continue;
|
|
4926
|
+
}
|
|
4927
|
+
if (char === ",") {
|
|
4928
|
+
currentRow.push(currentCell);
|
|
4929
|
+
currentCell = "";
|
|
4930
|
+
i++;
|
|
4931
|
+
continue;
|
|
4932
|
+
}
|
|
4933
|
+
if (char === "\r") {
|
|
4934
|
+
if (i + 1 < len && text[i + 1] === "\n") i++;
|
|
4935
|
+
currentRow.push(currentCell);
|
|
4936
|
+
rows.push(currentRow);
|
|
4937
|
+
currentRow = [];
|
|
4938
|
+
currentCell = "";
|
|
4939
|
+
i++;
|
|
4940
|
+
continue;
|
|
4941
|
+
}
|
|
4942
|
+
if (char === "\n") {
|
|
4943
|
+
currentRow.push(currentCell);
|
|
4944
|
+
rows.push(currentRow);
|
|
4945
|
+
currentRow = [];
|
|
4946
|
+
currentCell = "";
|
|
4947
|
+
i++;
|
|
4948
|
+
continue;
|
|
4949
|
+
}
|
|
4950
|
+
currentCell += char;
|
|
4951
|
+
i++;
|
|
4952
|
+
}
|
|
4953
|
+
if (currentCell.length > 0 || currentRow.length > 0) {
|
|
4954
|
+
currentRow.push(currentCell);
|
|
4955
|
+
rows.push(currentRow);
|
|
4956
|
+
}
|
|
4957
|
+
return rows;
|
|
4958
|
+
}
|
|
4959
|
+
/**
|
|
4960
|
+
* Coerce obvious numeric / boolean CSV strings to primitives when lossless.
|
|
4961
|
+
*/
|
|
4962
|
+
function coerceCsvValue(val) {
|
|
4963
|
+
if (val === "") return "";
|
|
4964
|
+
if (val.toLowerCase() === "true") return true;
|
|
4965
|
+
if (val.toLowerCase() === "false") return false;
|
|
4966
|
+
if (val.toLowerCase() === "null") return null;
|
|
4967
|
+
if (/^-?\d+(\.\d+)?$/.test(val)) {
|
|
4968
|
+
if (val.length > 1 && val.startsWith("0") && !val.startsWith("0.")) return val;
|
|
4969
|
+
const num = Number(val);
|
|
4970
|
+
if (!Number.isNaN(num)) return num;
|
|
4971
|
+
}
|
|
4972
|
+
return val;
|
|
4973
|
+
}
|
|
4974
|
+
//#endregion
|
|
4975
|
+
//#region src/plugins/transfer/parsers/excel.ts
|
|
4976
|
+
/**
|
|
4977
|
+
* @azlib/cms - Universal Excel (.xlsx) Data Parser using ExcelJS
|
|
4978
|
+
*/
|
|
4979
|
+
async function parseExcelSource(input, options = {}) {
|
|
4980
|
+
const workbook = new ExcelJS.Workbook();
|
|
4981
|
+
let buffer;
|
|
4982
|
+
if (Buffer.isBuffer(input)) buffer = input;
|
|
4983
|
+
else if (input instanceof Uint8Array) buffer = Buffer.from(input.buffer, input.byteOffset, input.byteLength);
|
|
4984
|
+
else if (input instanceof ArrayBuffer) buffer = Buffer.from(input);
|
|
4985
|
+
else throw new Error("[TransferParser] Invalid Excel input: expected Buffer, Uint8Array, or ArrayBuffer.");
|
|
4986
|
+
await workbook.xlsx.load(buffer);
|
|
4987
|
+
const sheetNames = workbook.worksheets.map((s) => s.name);
|
|
4988
|
+
if (sheetNames.length === 0) return {
|
|
4989
|
+
sheets: [],
|
|
4990
|
+
selectedSheet: "",
|
|
4991
|
+
records: []
|
|
4992
|
+
};
|
|
4993
|
+
let worksheet = options.sheetName ? workbook.getWorksheet(options.sheetName) : void 0;
|
|
4994
|
+
if (!worksheet) worksheet = workbook.worksheets[0];
|
|
4995
|
+
const selectedSheet = worksheet.name;
|
|
4996
|
+
const records = [];
|
|
4997
|
+
const headerRow = worksheet.getRow(1);
|
|
4998
|
+
const headers = [];
|
|
4999
|
+
headerRow.eachCell({ includeEmpty: false }, (cell, colNumber) => {
|
|
5000
|
+
let headerText = String(cell.value ?? "").trim();
|
|
5001
|
+
if (!headerText) headerText = `column_${colNumber}`;
|
|
5002
|
+
headers[colNumber] = headerText;
|
|
5003
|
+
});
|
|
5004
|
+
if (headers.length === 0) return {
|
|
5005
|
+
sheets: sheetNames,
|
|
5006
|
+
selectedSheet,
|
|
5007
|
+
records: []
|
|
5008
|
+
};
|
|
5009
|
+
const rowCount = worksheet.rowCount;
|
|
5010
|
+
for (let r = 2; r <= rowCount; r++) {
|
|
5011
|
+
const row = worksheet.getRow(r);
|
|
5012
|
+
let hasValues = false;
|
|
5013
|
+
const record = {};
|
|
5014
|
+
for (let c = 1; c < headers.length; c++) {
|
|
5015
|
+
const header = headers[c];
|
|
5016
|
+
if (!header) continue;
|
|
5017
|
+
const val = extractCellValue(row.getCell(c).value);
|
|
5018
|
+
if (val !== void 0 && val !== null && val !== "") hasValues = true;
|
|
5019
|
+
record[header] = val;
|
|
5020
|
+
}
|
|
5021
|
+
if (hasValues) records.push(record);
|
|
5022
|
+
}
|
|
5023
|
+
return {
|
|
5024
|
+
sheets: sheetNames,
|
|
5025
|
+
selectedSheet,
|
|
5026
|
+
records
|
|
5027
|
+
};
|
|
5028
|
+
}
|
|
5029
|
+
/**
|
|
5030
|
+
* Normalizes ExcelJS cell values (handles formulas, dates, rich text, hyperlinks).
|
|
5031
|
+
*/
|
|
5032
|
+
function extractCellValue(val) {
|
|
5033
|
+
if (val === void 0 || val === null) return null;
|
|
5034
|
+
if (val instanceof Date) return val.toISOString();
|
|
5035
|
+
if (typeof val === "object") {
|
|
5036
|
+
if ("formula" in val) return extractCellValue(val.result);
|
|
5037
|
+
if ("text" in val && "hyperlink" in val) return val.text;
|
|
5038
|
+
if ("richText" in val && Array.isArray(val.richText)) return val.richText.map((t) => t.text).join("");
|
|
5039
|
+
if ("error" in val) return null;
|
|
5040
|
+
}
|
|
5041
|
+
return val;
|
|
5042
|
+
}
|
|
5043
|
+
//#endregion
|
|
5044
|
+
//#region src/plugins/transfer/parsers/index.ts
|
|
5045
|
+
/**
|
|
5046
|
+
* Detect the format of an input payload if not explicitly provided.
|
|
5047
|
+
*/
|
|
5048
|
+
function detectFormat(input, fileName) {
|
|
5049
|
+
if (Array.isArray(input)) return "json";
|
|
5050
|
+
if (fileName) {
|
|
5051
|
+
const lower = fileName.toLowerCase();
|
|
5052
|
+
if (lower.endsWith(".xlsx") || lower.endsWith(".xls")) return "excel";
|
|
5053
|
+
if (lower.endsWith(".csv")) return "csv";
|
|
5054
|
+
if (lower.endsWith(".json") || lower.endsWith(".ndjson")) return "json";
|
|
5055
|
+
}
|
|
5056
|
+
if (input instanceof Uint8Array || Buffer.isBuffer(input)) {
|
|
5057
|
+
if (input.length >= 4 && input[0] === 80 && input[1] === 75 && input[2] === 3 && input[3] === 4) return "excel";
|
|
5058
|
+
try {
|
|
5059
|
+
const head = new TextDecoder("utf-8").decode(input.slice(0, 100)).trim();
|
|
5060
|
+
if (head.startsWith("{") || head.startsWith("[")) return "json";
|
|
5061
|
+
if (head.includes(",") && head.includes("\n")) return "csv";
|
|
5062
|
+
} catch {}
|
|
5063
|
+
}
|
|
5064
|
+
if (typeof input === "string") {
|
|
5065
|
+
const trimmed = input.trim();
|
|
5066
|
+
if (trimmed.startsWith("{") || trimmed.startsWith("[")) return "json";
|
|
5067
|
+
if (trimmed.includes(",") || trimmed.includes("\n")) return "csv";
|
|
5068
|
+
}
|
|
5069
|
+
return "json";
|
|
5070
|
+
}
|
|
5071
|
+
/**
|
|
5072
|
+
* Universal source parser that handles JSON, CSV, and Excel (.xlsx).
|
|
5073
|
+
*/
|
|
5074
|
+
async function parseSource(input, options = {}) {
|
|
5075
|
+
switch (options.format || detectFormat(input, options.fileName)) {
|
|
5076
|
+
case "excel": {
|
|
5077
|
+
const excelResult = await parseExcelSource(input, { sheetName: options.sheetName });
|
|
5078
|
+
return {
|
|
5079
|
+
format: "excel",
|
|
5080
|
+
sheets: excelResult.sheets,
|
|
5081
|
+
selectedSheet: excelResult.selectedSheet,
|
|
5082
|
+
records: excelResult.records
|
|
5083
|
+
};
|
|
5084
|
+
}
|
|
5085
|
+
case "csv": return {
|
|
5086
|
+
format: "csv",
|
|
5087
|
+
records: parseCsvSource(input)
|
|
5088
|
+
};
|
|
5089
|
+
default: return {
|
|
5090
|
+
format: "json",
|
|
5091
|
+
records: parseJsonSource(input)
|
|
5092
|
+
};
|
|
5093
|
+
}
|
|
5094
|
+
}
|
|
5095
|
+
//#endregion
|
|
5096
|
+
//#region src/plugins/transfer/serializers/json.ts
|
|
5097
|
+
function serializeJson(records, options = {}) {
|
|
5098
|
+
const indent = options.pretty !== false ? 2 : void 0;
|
|
5099
|
+
return JSON.stringify(records, null, indent);
|
|
5100
|
+
}
|
|
5101
|
+
//#endregion
|
|
5102
|
+
//#region src/plugins/transfer/serializers/csv.ts
|
|
5103
|
+
function serializeCsv(records, options = {}) {
|
|
5104
|
+
if (records.length === 0) return "";
|
|
5105
|
+
let columns = options.columns;
|
|
5106
|
+
if (!columns || columns.length === 0) {
|
|
5107
|
+
const keys = /* @__PURE__ */ new Set();
|
|
5108
|
+
for (const record of records) for (const key of Object.keys(record)) keys.add(key);
|
|
5109
|
+
columns = Array.from(keys).map((k) => ({
|
|
5110
|
+
key: k,
|
|
5111
|
+
header: k
|
|
5112
|
+
}));
|
|
5113
|
+
}
|
|
5114
|
+
const lines = [];
|
|
5115
|
+
lines.push(columns.map((c) => escapeCsvCell(c.header)).join(","));
|
|
5116
|
+
for (const record of records) {
|
|
5117
|
+
const rowCells = columns.map((col) => {
|
|
5118
|
+
const val = record[col.key];
|
|
5119
|
+
return escapeCsvCell(formatCsvValue(val));
|
|
5120
|
+
});
|
|
5121
|
+
lines.push(rowCells.join(","));
|
|
5122
|
+
}
|
|
5123
|
+
return lines.join("\r\n");
|
|
5124
|
+
}
|
|
5125
|
+
function formatCsvValue(val) {
|
|
5126
|
+
if (val === void 0 || val === null) return "";
|
|
5127
|
+
if (typeof val === "object") {
|
|
5128
|
+
if (val instanceof Date) return val.toISOString();
|
|
5129
|
+
return JSON.stringify(val);
|
|
5130
|
+
}
|
|
5131
|
+
return String(val);
|
|
5132
|
+
}
|
|
5133
|
+
function escapeCsvCell(cell) {
|
|
5134
|
+
if (cell.includes(",") || cell.includes("\"") || cell.includes("\n") || cell.includes("\r")) return `"${cell.replace(/"/g, "\"\"")}"`;
|
|
5135
|
+
return cell;
|
|
5136
|
+
}
|
|
5137
|
+
//#endregion
|
|
5138
|
+
//#region src/plugins/transfer/serializers/excel.ts
|
|
5139
|
+
/**
|
|
5140
|
+
* @azlib/cms - Universal Excel (.xlsx) Serializer using ExcelJS
|
|
5141
|
+
*/
|
|
5142
|
+
async function serializeExcel(records, options = {}) {
|
|
5143
|
+
const workbook = new ExcelJS.Workbook();
|
|
5144
|
+
const sheetName = (options.sheetName || "Export").replace(/[:\\/?*\[\]]/g, "_");
|
|
5145
|
+
const worksheet = workbook.addWorksheet(sheetName.slice(0, 31));
|
|
5146
|
+
let columns = options.columns;
|
|
5147
|
+
if (!columns || columns.length === 0) {
|
|
5148
|
+
const keys = /* @__PURE__ */ new Set();
|
|
5149
|
+
for (const record of records) for (const key of Object.keys(record)) keys.add(key);
|
|
5150
|
+
columns = Array.from(keys).map((k) => ({
|
|
5151
|
+
key: k,
|
|
5152
|
+
header: formatHeaderLabel(k)
|
|
5153
|
+
}));
|
|
5154
|
+
}
|
|
5155
|
+
worksheet.columns = columns.map((col) => {
|
|
5156
|
+
let maxLen = col.header.length;
|
|
5157
|
+
for (let i = 0; i < Math.min(records.length, 100); i++) {
|
|
5158
|
+
const val = records[i][col.key];
|
|
5159
|
+
if (val !== void 0 && val !== null) {
|
|
5160
|
+
const str = typeof val === "object" ? JSON.stringify(val) : String(val);
|
|
5161
|
+
if (str.length > maxLen) maxLen = Math.min(str.length, 50);
|
|
5162
|
+
}
|
|
5163
|
+
}
|
|
5164
|
+
return {
|
|
5165
|
+
header: col.header,
|
|
5166
|
+
key: col.key,
|
|
5167
|
+
width: Math.max(maxLen + 4, col.width ?? 12)
|
|
5168
|
+
};
|
|
5169
|
+
});
|
|
5170
|
+
const headerRow = worksheet.getRow(1);
|
|
5171
|
+
headerRow.height = 28;
|
|
5172
|
+
headerRow.eachCell((cell) => {
|
|
5173
|
+
cell.font = {
|
|
5174
|
+
bold: true,
|
|
5175
|
+
color: { argb: "FF1E293B" },
|
|
5176
|
+
size: 11
|
|
5177
|
+
};
|
|
5178
|
+
cell.fill = {
|
|
5179
|
+
type: "pattern",
|
|
5180
|
+
pattern: "solid",
|
|
5181
|
+
fgColor: { argb: "FFF1F5F9" }
|
|
5182
|
+
};
|
|
5183
|
+
cell.alignment = {
|
|
5184
|
+
vertical: "middle",
|
|
5185
|
+
horizontal: "center",
|
|
5186
|
+
wrapText: true
|
|
5187
|
+
};
|
|
5188
|
+
cell.border = {
|
|
5189
|
+
top: {
|
|
5190
|
+
style: "thin",
|
|
5191
|
+
color: { argb: "FFE2E8F0" }
|
|
5192
|
+
},
|
|
5193
|
+
bottom: {
|
|
5194
|
+
style: "medium",
|
|
5195
|
+
color: { argb: "FFCBD5E1" }
|
|
5196
|
+
},
|
|
5197
|
+
left: {
|
|
5198
|
+
style: "thin",
|
|
5199
|
+
color: { argb: "FFE2E8F0" }
|
|
5200
|
+
},
|
|
5201
|
+
right: {
|
|
5202
|
+
style: "thin",
|
|
5203
|
+
color: { argb: "FFE2E8F0" }
|
|
5204
|
+
}
|
|
5205
|
+
};
|
|
5206
|
+
});
|
|
5207
|
+
for (const record of records) {
|
|
5208
|
+
const rowValues = {};
|
|
5209
|
+
for (const col of columns) {
|
|
5210
|
+
const val = record[col.key];
|
|
5211
|
+
rowValues[col.key] = formatExcelCellValue(val);
|
|
5212
|
+
}
|
|
5213
|
+
const row = worksheet.addRow(rowValues);
|
|
5214
|
+
row.height = 20;
|
|
5215
|
+
row.eachCell((cell) => {
|
|
5216
|
+
cell.alignment = { vertical: "middle" };
|
|
5217
|
+
cell.border = {
|
|
5218
|
+
top: {
|
|
5219
|
+
style: "thin",
|
|
5220
|
+
color: { argb: "FFF1F5F9" }
|
|
5221
|
+
},
|
|
5222
|
+
bottom: {
|
|
5223
|
+
style: "thin",
|
|
5224
|
+
color: { argb: "FFF1F5F9" }
|
|
5225
|
+
},
|
|
5226
|
+
left: {
|
|
5227
|
+
style: "thin",
|
|
5228
|
+
color: { argb: "FFF1F5F9" }
|
|
5229
|
+
},
|
|
5230
|
+
right: {
|
|
5231
|
+
style: "thin",
|
|
5232
|
+
color: { argb: "FFF1F5F9" }
|
|
5233
|
+
}
|
|
5234
|
+
};
|
|
5235
|
+
});
|
|
5236
|
+
}
|
|
5237
|
+
const arrayBuffer = await workbook.xlsx.writeBuffer();
|
|
5238
|
+
return new Uint8Array(arrayBuffer);
|
|
5239
|
+
}
|
|
5240
|
+
function formatHeaderLabel(key) {
|
|
5241
|
+
return key.replace(/([a-z])([A-Z])/g, "$1 $2").replace(/_/g, " ").replace(/\b\w/g, (c) => c.toUpperCase());
|
|
5242
|
+
}
|
|
5243
|
+
function formatExcelCellValue(val) {
|
|
5244
|
+
if (val === void 0 || val === null) return "";
|
|
5245
|
+
if (typeof val === "number" || typeof val === "boolean") return val;
|
|
5246
|
+
if (val instanceof Date) return val;
|
|
5247
|
+
if (typeof val === "object") return JSON.stringify(val);
|
|
5248
|
+
return String(val);
|
|
5249
|
+
}
|
|
5250
|
+
//#endregion
|
|
5251
|
+
//#region src/plugins/transfer/serializers/index.ts
|
|
5252
|
+
async function serializeSource(records, options = {}) {
|
|
5253
|
+
const format = options.format || "json";
|
|
5254
|
+
const baseName = options.fileName || "export";
|
|
5255
|
+
switch (format) {
|
|
5256
|
+
case "excel": return {
|
|
5257
|
+
format: "excel",
|
|
5258
|
+
data: await serializeExcel(records, {
|
|
5259
|
+
sheetName: options.sheetName,
|
|
5260
|
+
columns: options.columns
|
|
5261
|
+
}),
|
|
5262
|
+
mimeType: "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet",
|
|
5263
|
+
fileName: baseName.endsWith(".xlsx") ? baseName : `${baseName}.xlsx`,
|
|
5264
|
+
totalRecords: records.length
|
|
5265
|
+
};
|
|
5266
|
+
case "csv": return {
|
|
5267
|
+
format: "csv",
|
|
5268
|
+
data: serializeCsv(records, { columns: options.columns }),
|
|
5269
|
+
mimeType: "text/csv; charset=utf-8",
|
|
5270
|
+
fileName: baseName.endsWith(".csv") ? baseName : `${baseName}.csv`,
|
|
5271
|
+
totalRecords: records.length
|
|
5272
|
+
};
|
|
5273
|
+
default: return {
|
|
5274
|
+
format: "json",
|
|
5275
|
+
data: serializeJson(records, { pretty: true }),
|
|
5276
|
+
mimeType: "application/json; charset=utf-8",
|
|
5277
|
+
fileName: baseName.endsWith(".json") ? baseName : `${baseName}.json`,
|
|
5278
|
+
totalRecords: records.length
|
|
5279
|
+
};
|
|
5280
|
+
}
|
|
5281
|
+
}
|
|
5282
|
+
//#endregion
|
|
5283
|
+
//#region src/plugins/transfer/inspect.ts
|
|
5284
|
+
/**
|
|
5285
|
+
* Inspect an uploaded source file or payload to discover its schema,
|
|
5286
|
+
* infer column types, and generate auto-mapping suggestions against a target collection.
|
|
5287
|
+
*/
|
|
5288
|
+
async function inspectSource(input, options = {}) {
|
|
5289
|
+
const parsed = await parseSource(input, {
|
|
5290
|
+
format: options.format,
|
|
5291
|
+
fileName: options.fileName,
|
|
5292
|
+
sheetName: options.sheetName
|
|
5293
|
+
});
|
|
5294
|
+
const records = parsed.records;
|
|
5295
|
+
const totalRows = records.length;
|
|
5296
|
+
const previewLimit = options.previewLimit ?? 5;
|
|
5297
|
+
const previewRows = records.slice(0, previewLimit);
|
|
5298
|
+
const fieldKeys = /* @__PURE__ */ new Set();
|
|
5299
|
+
for (const row of records) for (const key of Object.keys(row)) fieldKeys.add(key);
|
|
5300
|
+
const sourceFields = [];
|
|
5301
|
+
for (const key of fieldKeys) {
|
|
5302
|
+
let nullCount = 0;
|
|
5303
|
+
const samples = [];
|
|
5304
|
+
const detectedTypes = [];
|
|
5305
|
+
for (const row of records) {
|
|
5306
|
+
const val = row[key];
|
|
5307
|
+
if (val === void 0 || val === null || val === "") nullCount++;
|
|
5308
|
+
else {
|
|
5309
|
+
if (samples.length < 5) samples.push(val);
|
|
5310
|
+
detectedTypes.push(inferValueType(val));
|
|
5311
|
+
}
|
|
5312
|
+
}
|
|
5313
|
+
sourceFields.push({
|
|
5314
|
+
name: key,
|
|
5315
|
+
inferredType: resolveDominantType(detectedTypes),
|
|
5316
|
+
sampleValues: samples,
|
|
5317
|
+
nullCount,
|
|
5318
|
+
totalCount: totalRows
|
|
5319
|
+
});
|
|
5320
|
+
}
|
|
5321
|
+
let targetSchema;
|
|
5322
|
+
let suggestedMapping;
|
|
5323
|
+
if (options.collectionConfig) {
|
|
5324
|
+
targetSchema = summarizeCollection(options.collectionConfig);
|
|
5325
|
+
suggestedMapping = generateSuggestedMapping(sourceFields.map((f) => f.name), targetSchema);
|
|
5326
|
+
}
|
|
5327
|
+
return {
|
|
5328
|
+
format: parsed.format,
|
|
5329
|
+
sheets: parsed.sheets,
|
|
5330
|
+
selectedSheet: parsed.selectedSheet,
|
|
5331
|
+
totalRows,
|
|
5332
|
+
sourceFields,
|
|
5333
|
+
targetSchema,
|
|
5334
|
+
suggestedMapping,
|
|
5335
|
+
previewRows
|
|
5336
|
+
};
|
|
5337
|
+
}
|
|
5338
|
+
/**
|
|
5339
|
+
* Summarize a CMS CollectionConfig into consumer-friendly schema details.
|
|
5340
|
+
*/
|
|
5341
|
+
function summarizeCollection(config) {
|
|
5342
|
+
return {
|
|
5343
|
+
slug: config.slug,
|
|
5344
|
+
label: config.label,
|
|
5345
|
+
singularLabel: config.singularLabel || config.label,
|
|
5346
|
+
description: config.description,
|
|
5347
|
+
taxonomies: config.taxonomies || [],
|
|
5348
|
+
fields: config.fields.map((f) => ({
|
|
5349
|
+
name: f.name,
|
|
5350
|
+
label: f.label || f.name,
|
|
5351
|
+
type: f.type,
|
|
5352
|
+
required: Boolean(f.required),
|
|
5353
|
+
unique: Boolean(f.unique),
|
|
5354
|
+
description: f.description,
|
|
5355
|
+
defaultValue: f.defaultValue,
|
|
5356
|
+
targetCollection: f.targetCollection,
|
|
5357
|
+
options: f.options
|
|
5358
|
+
}))
|
|
5359
|
+
};
|
|
5360
|
+
}
|
|
5361
|
+
/**
|
|
5362
|
+
* Generates intelligent auto-mapping suggestions matching source headers to CMS fields.
|
|
5363
|
+
*/
|
|
5364
|
+
function generateSuggestedMapping(sourceHeaders, targetSchema) {
|
|
5365
|
+
const suggestions = [];
|
|
5366
|
+
const matchedTargets = /* @__PURE__ */ new Set();
|
|
5367
|
+
for (const sourceHeader of sourceHeaders) {
|
|
5368
|
+
let bestMatch = null;
|
|
5369
|
+
for (const targetField of targetSchema.fields) {
|
|
5370
|
+
if (matchedTargets.has(targetField.name)) continue;
|
|
5371
|
+
const score = calculateMatchConfidence(sourceHeader, targetField);
|
|
5372
|
+
if (score >= .6 && (!bestMatch || score > bestMatch.confidence)) bestMatch = {
|
|
5373
|
+
field: targetField.name,
|
|
5374
|
+
confidence: score
|
|
5375
|
+
};
|
|
5376
|
+
}
|
|
5377
|
+
if (bestMatch) {
|
|
5378
|
+
matchedTargets.add(bestMatch.field);
|
|
5379
|
+
suggestions.push({
|
|
5380
|
+
sourceField: sourceHeader,
|
|
5381
|
+
targetField: bestMatch.field,
|
|
5382
|
+
confidence: Number(bestMatch.confidence.toFixed(2))
|
|
5383
|
+
});
|
|
5384
|
+
}
|
|
5385
|
+
}
|
|
5386
|
+
return suggestions;
|
|
5387
|
+
}
|
|
5388
|
+
function normalize(str) {
|
|
5389
|
+
return str.toLowerCase().replace(/[^a-z0-9]/g, "");
|
|
5390
|
+
}
|
|
5391
|
+
/**
|
|
5392
|
+
* Common field synonyms dictionary for intuitive fuzzy matching.
|
|
5393
|
+
*/
|
|
5394
|
+
const SYNONYMS = {
|
|
5395
|
+
employeeNumber: [
|
|
5396
|
+
"empid",
|
|
5397
|
+
"employeeid",
|
|
5398
|
+
"empnumber",
|
|
5399
|
+
"staffid",
|
|
5400
|
+
"badgenumber",
|
|
5401
|
+
"staffno",
|
|
5402
|
+
"empno"
|
|
5403
|
+
],
|
|
5404
|
+
companyName: [
|
|
5405
|
+
"company",
|
|
5406
|
+
"organization",
|
|
5407
|
+
"employer",
|
|
5408
|
+
"businessname",
|
|
5409
|
+
"employername",
|
|
5410
|
+
"firm"
|
|
5411
|
+
],
|
|
5412
|
+
firstName: [
|
|
5413
|
+
"fname",
|
|
5414
|
+
"givenname",
|
|
5415
|
+
"first"
|
|
5416
|
+
],
|
|
5417
|
+
lastName: [
|
|
5418
|
+
"lname",
|
|
5419
|
+
"surname",
|
|
5420
|
+
"familyname",
|
|
5421
|
+
"last"
|
|
5422
|
+
],
|
|
5423
|
+
email: [
|
|
5424
|
+
"mail",
|
|
5425
|
+
"workemail",
|
|
5426
|
+
"primaryemail",
|
|
5427
|
+
"emailaddress"
|
|
5428
|
+
],
|
|
5429
|
+
phone: [
|
|
5430
|
+
"mobile",
|
|
5431
|
+
"cell",
|
|
5432
|
+
"telephone",
|
|
5433
|
+
"phonenumber",
|
|
5434
|
+
"contactnumber",
|
|
5435
|
+
"tel"
|
|
5436
|
+
],
|
|
5437
|
+
employerId: [
|
|
5438
|
+
"employer",
|
|
5439
|
+
"companyid",
|
|
5440
|
+
"company",
|
|
5441
|
+
"organizationid",
|
|
5442
|
+
"orgid"
|
|
5443
|
+
],
|
|
5444
|
+
hireDate: [
|
|
5445
|
+
"startdate",
|
|
5446
|
+
"joiningdate",
|
|
5447
|
+
"hired",
|
|
5448
|
+
"dateofjoining"
|
|
5449
|
+
],
|
|
5450
|
+
jobTitle: [
|
|
5451
|
+
"title",
|
|
5452
|
+
"position",
|
|
5453
|
+
"role",
|
|
5454
|
+
"designation"
|
|
5455
|
+
],
|
|
5456
|
+
employmentType: [
|
|
5457
|
+
"contracttype",
|
|
5458
|
+
"worktype",
|
|
5459
|
+
"jobtype"
|
|
5460
|
+
],
|
|
5461
|
+
salary: [
|
|
5462
|
+
"compensation",
|
|
5463
|
+
"wage",
|
|
5464
|
+
"pay",
|
|
5465
|
+
"rate",
|
|
5466
|
+
"annualsalary"
|
|
5467
|
+
],
|
|
5468
|
+
taxId: [
|
|
5469
|
+
"ein",
|
|
5470
|
+
"vat",
|
|
5471
|
+
"taxnumber",
|
|
5472
|
+
"tin"
|
|
5473
|
+
],
|
|
5474
|
+
status: ["state", "active"]
|
|
5475
|
+
};
|
|
5476
|
+
function calculateMatchConfidence(sourceHeader, targetField) {
|
|
5477
|
+
const normSource = normalize(sourceHeader);
|
|
5478
|
+
const normTargetName = normalize(targetField.name);
|
|
5479
|
+
const normTargetLabel = normalize(targetField.label);
|
|
5480
|
+
if (sourceHeader === targetField.name) return 1;
|
|
5481
|
+
if (normSource === normTargetName) return .95;
|
|
5482
|
+
if (sourceHeader.toLowerCase() === targetField.label.toLowerCase()) return .92;
|
|
5483
|
+
if (normSource === normTargetLabel) return .9;
|
|
5484
|
+
const synonyms = SYNONYMS[targetField.name];
|
|
5485
|
+
if (synonyms && synonyms.includes(normSource)) return .85;
|
|
5486
|
+
if (normSource.includes(normTargetName) || normTargetName.includes(normSource)) return .7;
|
|
5487
|
+
if (normSource.includes(normTargetLabel) || normTargetLabel.includes(normSource)) return .65;
|
|
5488
|
+
return 0;
|
|
5489
|
+
}
|
|
5490
|
+
function inferValueType(val) {
|
|
5491
|
+
if (typeof val === "boolean") return "boolean";
|
|
5492
|
+
if (typeof val === "number") return "number";
|
|
5493
|
+
if (Array.isArray(val)) return "array";
|
|
5494
|
+
if (val && typeof val === "object") return "object";
|
|
5495
|
+
if (typeof val === "string") {
|
|
5496
|
+
const s = val.trim();
|
|
5497
|
+
if (s.toLowerCase() === "true" || s.toLowerCase() === "false") return "boolean";
|
|
5498
|
+
if (/^-?\d+(\.\d+)?$/.test(s) && !/^0\d+/.test(s)) return "number";
|
|
5499
|
+
if (/^\d{4}-\d{2}-\d{2}(T\d{2}:\d{2}(:\d{2})?(\.\d+)?(Z|[+-]\d{2}:?\d{2})?)?$/.test(s)) {
|
|
5500
|
+
const parsed = Date.parse(s);
|
|
5501
|
+
if (!Number.isNaN(parsed)) return "date";
|
|
5502
|
+
}
|
|
5503
|
+
}
|
|
5504
|
+
return "string";
|
|
5505
|
+
}
|
|
5506
|
+
function resolveDominantType(types) {
|
|
5507
|
+
if (types.length === 0) return "string";
|
|
5508
|
+
const counts = /* @__PURE__ */ new Map();
|
|
5509
|
+
for (const t of types) counts.set(t, (counts.get(t) || 0) + 1);
|
|
5510
|
+
let dominant = "string";
|
|
5511
|
+
let maxCount = 0;
|
|
5512
|
+
for (const [t, count] of counts) if (count > maxCount) {
|
|
5513
|
+
maxCount = count;
|
|
5514
|
+
dominant = t;
|
|
5515
|
+
}
|
|
5516
|
+
return dominant;
|
|
5517
|
+
}
|
|
5518
|
+
//#endregion
|
|
5519
|
+
//#region src/plugins/transfer/mapping.ts
|
|
5520
|
+
/**
|
|
5521
|
+
* Apply a mapping definition to transform an external raw record into a CMS content payload.
|
|
5522
|
+
*/
|
|
5523
|
+
function mapSourceRecord(rawRecord, mapping) {
|
|
5524
|
+
const mappedData = {};
|
|
5525
|
+
const mappedTargetFields = /* @__PURE__ */ new Set();
|
|
5526
|
+
for (const rule of mapping.fields) {
|
|
5527
|
+
mappedTargetFields.add(rule.targetField);
|
|
5528
|
+
const sourceVal = rawRecord[rule.sourceField];
|
|
5529
|
+
const transformed = applyFieldTransform(rule, sourceVal, rawRecord);
|
|
5530
|
+
if (transformed !== void 0) mappedData[rule.targetField] = transformed;
|
|
5531
|
+
}
|
|
5532
|
+
if (mapping.options?.ignoreUnmappedFields === false) {
|
|
5533
|
+
for (const [key, val] of Object.entries(rawRecord)) if (!mapping.fields.some((r) => r.sourceField === key)) mappedData[key] = val;
|
|
5534
|
+
}
|
|
5535
|
+
let title = typeof mappedData.title === "string" ? mappedData.title : void 0;
|
|
5536
|
+
if (!title) {
|
|
5537
|
+
if (typeof mappedData.companyName === "string") title = mappedData.companyName;
|
|
5538
|
+
else if (typeof mappedData.name === "string") title = mappedData.name;
|
|
5539
|
+
else if (typeof mappedData.firstName === "string" || typeof mappedData.lastName === "string") {
|
|
5540
|
+
const parts = [mappedData.firstName, mappedData.lastName].filter(Boolean);
|
|
5541
|
+
if (parts.length > 0) title = parts.join(" ");
|
|
5542
|
+
}
|
|
5543
|
+
}
|
|
5544
|
+
let slug = typeof mappedData.slug === "string" ? mappedData.slug : void 0;
|
|
5545
|
+
if (!slug && mapping.options?.autoGenerateSlug !== false && title) slug = slugify(title);
|
|
5546
|
+
let status = mapping.options?.defaultStatus;
|
|
5547
|
+
if (mapping.options?.statusField && mappedData[mapping.options.statusField]) status = String(mappedData[mapping.options.statusField]);
|
|
5548
|
+
return {
|
|
5549
|
+
data: mappedData,
|
|
5550
|
+
title,
|
|
5551
|
+
slug,
|
|
5552
|
+
status
|
|
5553
|
+
};
|
|
5554
|
+
}
|
|
5555
|
+
/**
|
|
5556
|
+
* Applies transform preset or custom function to a field value.
|
|
5557
|
+
*/
|
|
5558
|
+
function applyFieldTransform(rule, value, rawRecord) {
|
|
5559
|
+
let val = value;
|
|
5560
|
+
if (typeof rule.transform === "function") try {
|
|
5561
|
+
val = rule.transform(val, rawRecord);
|
|
5562
|
+
} catch (err) {
|
|
5563
|
+
throw new Error(`Transform error on field '${rule.sourceField}': ${err instanceof Error ? err.message : String(err)}`);
|
|
5564
|
+
}
|
|
5565
|
+
else if (rule.transform && typeof rule.transform === "string") val = applyPresetTransform(rule.transform, val);
|
|
5566
|
+
if (val === void 0 || val === null || val === "") {
|
|
5567
|
+
if (rule.defaultValue !== void 0) val = rule.defaultValue;
|
|
5568
|
+
}
|
|
5569
|
+
return val;
|
|
5570
|
+
}
|
|
5571
|
+
function applyPresetTransform(preset, val) {
|
|
5572
|
+
if (val === void 0 || val === null) return val;
|
|
5573
|
+
switch (preset) {
|
|
5574
|
+
case "trim": return typeof val === "string" ? val.trim() : val;
|
|
5575
|
+
case "lowercase": return typeof val === "string" ? val.toLowerCase() : val;
|
|
5576
|
+
case "uppercase": return typeof val === "string" ? val.toUpperCase() : val;
|
|
5577
|
+
case "number": {
|
|
5578
|
+
if (typeof val === "number") return val;
|
|
5579
|
+
const parsed = Number(val);
|
|
5580
|
+
return Number.isNaN(parsed) ? val : parsed;
|
|
5581
|
+
}
|
|
5582
|
+
case "boolean": {
|
|
5583
|
+
if (typeof val === "boolean") return val;
|
|
5584
|
+
const s = String(val).toLowerCase().trim();
|
|
5585
|
+
if (s === "true" || s === "1" || s === "yes") return true;
|
|
5586
|
+
if (s === "false" || s === "0" || s === "no") return false;
|
|
5587
|
+
return Boolean(val);
|
|
5588
|
+
}
|
|
5589
|
+
case "date": {
|
|
5590
|
+
if (val instanceof Date) return val.toISOString();
|
|
5591
|
+
const s = String(val).trim();
|
|
5592
|
+
const parsed = Date.parse(s);
|
|
5593
|
+
return Number.isNaN(parsed) ? s : new Date(parsed).toISOString();
|
|
5594
|
+
}
|
|
5595
|
+
case "json":
|
|
5596
|
+
if (typeof val === "object") return val;
|
|
5597
|
+
try {
|
|
5598
|
+
return JSON.parse(String(val));
|
|
5599
|
+
} catch {
|
|
5600
|
+
return val;
|
|
5601
|
+
}
|
|
5602
|
+
case "slug": return slugify(String(val));
|
|
5603
|
+
case "split_comma":
|
|
5604
|
+
if (Array.isArray(val)) return val;
|
|
5605
|
+
return String(val).split(",").map((s) => s.trim()).filter(Boolean);
|
|
5606
|
+
default: return val;
|
|
5607
|
+
}
|
|
5608
|
+
}
|
|
5609
|
+
/**
|
|
5610
|
+
* Reverse mapping for export: transforms a CMS ContentItem into an external export record.
|
|
5611
|
+
*/
|
|
5612
|
+
function mapCmsItemForExport(item, mapping, options = {}) {
|
|
5613
|
+
const exportRecord = {};
|
|
5614
|
+
if (mapping && mapping.fields.length > 0) {
|
|
5615
|
+
for (const rule of mapping.fields) {
|
|
5616
|
+
const val = item.data[rule.targetField] !== void 0 ? item.data[rule.targetField] : item[rule.targetField];
|
|
5617
|
+
exportRecord[rule.sourceField] = val !== void 0 ? val : rule.defaultValue ?? "";
|
|
5618
|
+
}
|
|
5619
|
+
return exportRecord;
|
|
5620
|
+
}
|
|
5621
|
+
if (options.includeId !== false) exportRecord.id = item.id;
|
|
5622
|
+
if (item.title) exportRecord.title = item.title;
|
|
5623
|
+
if (item.slug) exportRecord.slug = item.slug;
|
|
5624
|
+
if (item.status) exportRecord.status = item.status;
|
|
5625
|
+
for (const [k, v] of Object.entries(item.data)) exportRecord[k] = v;
|
|
5626
|
+
if (options.includeTimestamps) {
|
|
5627
|
+
exportRecord.createdAt = item.createdAt;
|
|
5628
|
+
exportRecord.updatedAt = item.updatedAt;
|
|
5629
|
+
}
|
|
5630
|
+
return exportRecord;
|
|
5631
|
+
}
|
|
5632
|
+
//#endregion
|
|
5633
|
+
//#region src/plugins/transfer/validator.ts
|
|
5634
|
+
/**
|
|
5635
|
+
* Validates a batch of source records against a target CMS collection configuration
|
|
5636
|
+
* and live database constraints.
|
|
5637
|
+
*/
|
|
5638
|
+
async function validateTransferBatch(rawRecords, mapping, collectionConfig, options = {}) {
|
|
5639
|
+
const errors = [];
|
|
5640
|
+
const previewRows = [];
|
|
5641
|
+
const previewLimit = options.previewLimit ?? 10;
|
|
5642
|
+
const onDuplicate = options.onDuplicate ?? mapping.options?.onDuplicate ?? "error";
|
|
5643
|
+
const uniqueFields = collectionConfig.fields.filter((f) => Boolean(f.unique) || f.name === "slug");
|
|
5644
|
+
const relationshipFields = collectionConfig.fields.filter((f) => f.type === "relationship" && Boolean(f.targetCollection));
|
|
5645
|
+
const seenUniqueValues = /* @__PURE__ */ new Map();
|
|
5646
|
+
for (const uf of uniqueFields) seenUniqueValues.set(uf.name, /* @__PURE__ */ new Map());
|
|
5647
|
+
let validCount = 0;
|
|
5648
|
+
for (let i = 0; i < rawRecords.length; i++) {
|
|
5649
|
+
const rowNumber = i + 1;
|
|
5650
|
+
const raw = rawRecords[i];
|
|
5651
|
+
const rowErrors = [];
|
|
5652
|
+
let mappedResult;
|
|
5653
|
+
try {
|
|
5654
|
+
mappedResult = mapSourceRecord(raw, mapping);
|
|
5655
|
+
} catch (err) {
|
|
5656
|
+
const errDetail = {
|
|
5657
|
+
rowNumber,
|
|
5658
|
+
code: "TRANSFORM_ERROR",
|
|
5659
|
+
reason: err instanceof Error ? err.message : String(err)
|
|
5660
|
+
};
|
|
5661
|
+
rowErrors.push(errDetail);
|
|
5662
|
+
errors.push(errDetail);
|
|
5663
|
+
if (previewRows.length < previewLimit) previewRows.push({
|
|
5664
|
+
rowNumber,
|
|
5665
|
+
raw,
|
|
5666
|
+
mapped: {},
|
|
5667
|
+
valid: false,
|
|
5668
|
+
errors: rowErrors
|
|
5669
|
+
});
|
|
5670
|
+
continue;
|
|
5671
|
+
}
|
|
5672
|
+
const data = mappedResult.data;
|
|
5673
|
+
for (const field of collectionConfig.fields) validateField(field, data, rowNumber, rowErrors);
|
|
5674
|
+
for (const rule of mapping.fields) if (rule.required && !collectionConfig.fields.some((f) => f.name === rule.targetField)) {
|
|
5675
|
+
const val = data[rule.targetField];
|
|
5676
|
+
if (val === void 0 || val === null || val === "") rowErrors.push({
|
|
5677
|
+
rowNumber,
|
|
5678
|
+
field: rule.targetField,
|
|
5679
|
+
value: val,
|
|
5680
|
+
code: "REQUIRED_FIELD_MISSING",
|
|
5681
|
+
reason: `Field '${rule.targetField}' is required by mapping definition.`
|
|
5682
|
+
});
|
|
5683
|
+
}
|
|
5684
|
+
for (const uf of uniqueFields) {
|
|
5685
|
+
const val = data[uf.name] ?? (uf.name === "slug" ? mappedResult.slug : void 0);
|
|
5686
|
+
if (val !== void 0 && val !== null && val !== "") {
|
|
5687
|
+
const seenMap = seenUniqueValues.get(uf.name);
|
|
5688
|
+
if (seenMap.has(val)) {
|
|
5689
|
+
const prevRow = seenMap.get(val);
|
|
5690
|
+
rowErrors.push({
|
|
5691
|
+
rowNumber,
|
|
5692
|
+
field: uf.name,
|
|
5693
|
+
value: val,
|
|
5694
|
+
code: "CONSTRAINT_UNIQUE_VIOLATION",
|
|
5695
|
+
reason: `${uf.label || uf.name} value '${val}' is duplicated in row ${prevRow} and row ${rowNumber}.`
|
|
5696
|
+
});
|
|
5697
|
+
} else seenMap.set(val, rowNumber);
|
|
5698
|
+
if (options.storage && onDuplicate === "error") {
|
|
5699
|
+
if (await checkExistingUnique(options.storage, collectionConfig.slug, uf.name, val)) rowErrors.push({
|
|
5700
|
+
rowNumber,
|
|
5701
|
+
field: uf.name,
|
|
5702
|
+
value: val,
|
|
5703
|
+
code: "CONSTRAINT_UNIQUE_VIOLATION",
|
|
5704
|
+
reason: `${uf.label || uf.name} value '${val}' already exists in database.`
|
|
5705
|
+
});
|
|
5706
|
+
}
|
|
5707
|
+
}
|
|
5708
|
+
}
|
|
5709
|
+
if (options.storage) for (const rf of relationshipFields) {
|
|
5710
|
+
const targetColl = rf.targetCollection;
|
|
5711
|
+
const refVal = data[rf.name];
|
|
5712
|
+
if (refVal !== void 0 && refVal !== null && refVal !== "") {
|
|
5713
|
+
if (!await checkRelationshipExists(options.storage, targetColl, refVal)) rowErrors.push({
|
|
5714
|
+
rowNumber,
|
|
5715
|
+
field: rf.name,
|
|
5716
|
+
value: refVal,
|
|
5717
|
+
code: "CONSTRAINT_FOREIGN_KEY_VIOLATION",
|
|
5718
|
+
reason: `Referenced ${rf.label || rf.name} with identifier '${refVal}' does not exist in collection '${targetColl}'.`
|
|
5719
|
+
});
|
|
5720
|
+
}
|
|
5721
|
+
}
|
|
5722
|
+
if (rowErrors.length === 0) validCount++;
|
|
5723
|
+
else errors.push(...rowErrors);
|
|
5724
|
+
if (previewRows.length < previewLimit) previewRows.push({
|
|
5725
|
+
rowNumber,
|
|
5726
|
+
raw,
|
|
5727
|
+
mapped: data,
|
|
5728
|
+
valid: rowErrors.length === 0,
|
|
5729
|
+
errors: rowErrors.length > 0 ? rowErrors : void 0
|
|
5730
|
+
});
|
|
5731
|
+
}
|
|
5732
|
+
return {
|
|
5733
|
+
valid: errors.length === 0,
|
|
5734
|
+
totalRows: rawRecords.length,
|
|
5735
|
+
validCount,
|
|
5736
|
+
errorCount: errors.length,
|
|
5737
|
+
errors,
|
|
5738
|
+
previewRows
|
|
5739
|
+
};
|
|
5740
|
+
}
|
|
5741
|
+
/**
|
|
5742
|
+
* Validates a single field against its FieldDefinition.
|
|
5743
|
+
*/
|
|
5744
|
+
function validateField(field, data, rowNumber, errors) {
|
|
5745
|
+
const val = data[field.name];
|
|
5746
|
+
const label = field.label || field.name;
|
|
5747
|
+
if (field.required && (val === void 0 || val === null || val === "")) {
|
|
5748
|
+
errors.push({
|
|
5749
|
+
rowNumber,
|
|
5750
|
+
field: field.name,
|
|
5751
|
+
value: val,
|
|
5752
|
+
code: "REQUIRED_FIELD_MISSING",
|
|
5753
|
+
reason: `${label} is required.`
|
|
5754
|
+
});
|
|
5755
|
+
return;
|
|
5756
|
+
}
|
|
5757
|
+
if (val === void 0 || val === null || val === "") return;
|
|
5758
|
+
switch (field.type) {
|
|
5759
|
+
case "number": {
|
|
5760
|
+
const num = typeof val === "number" ? val : Number(val);
|
|
5761
|
+
if (Number.isNaN(num)) errors.push({
|
|
5762
|
+
rowNumber,
|
|
5763
|
+
field: field.name,
|
|
5764
|
+
value: val,
|
|
5765
|
+
code: "INVALID_DATA_TYPE",
|
|
5766
|
+
reason: `${label} must be a valid number, received '${val}'.`
|
|
5767
|
+
});
|
|
5768
|
+
else {
|
|
5769
|
+
data[field.name] = num;
|
|
5770
|
+
const min = field.min;
|
|
5771
|
+
const max = field.max;
|
|
5772
|
+
if (min !== void 0 && num < min) errors.push({
|
|
5773
|
+
rowNumber,
|
|
5774
|
+
field: field.name,
|
|
5775
|
+
value: val,
|
|
5776
|
+
code: "VALIDATION_RULE_FAILED",
|
|
5777
|
+
reason: `${label} must be greater than or equal to ${min}.`
|
|
5778
|
+
});
|
|
5779
|
+
if (max !== void 0 && num > max) errors.push({
|
|
5780
|
+
rowNumber,
|
|
5781
|
+
field: field.name,
|
|
5782
|
+
value: val,
|
|
5783
|
+
code: "VALIDATION_RULE_FAILED",
|
|
5784
|
+
reason: `${label} must be less than or equal to ${max}.`
|
|
5785
|
+
});
|
|
5786
|
+
}
|
|
5787
|
+
break;
|
|
5788
|
+
}
|
|
5789
|
+
case "boolean":
|
|
5790
|
+
if (typeof val !== "boolean") {
|
|
5791
|
+
const s = String(val).toLowerCase().trim();
|
|
5792
|
+
if (s === "true" || s === "1" || s === "yes") data[field.name] = true;
|
|
5793
|
+
else if (s === "false" || s === "0" || s === "no") data[field.name] = false;
|
|
5794
|
+
else errors.push({
|
|
5795
|
+
rowNumber,
|
|
5796
|
+
field: field.name,
|
|
5797
|
+
value: val,
|
|
5798
|
+
code: "INVALID_DATA_TYPE",
|
|
5799
|
+
reason: `${label} must be a boolean (true/false), received '${val}'.`
|
|
5800
|
+
});
|
|
5801
|
+
}
|
|
5802
|
+
break;
|
|
5803
|
+
case "date": {
|
|
5804
|
+
const parsed = Date.parse(String(val));
|
|
5805
|
+
if (Number.isNaN(parsed)) errors.push({
|
|
5806
|
+
rowNumber,
|
|
5807
|
+
field: field.name,
|
|
5808
|
+
value: val,
|
|
5809
|
+
code: "INVALID_DATA_TYPE",
|
|
5810
|
+
reason: `${label} must be a valid date, received '${val}'.`
|
|
5811
|
+
});
|
|
5812
|
+
break;
|
|
5813
|
+
}
|
|
5814
|
+
case "select": {
|
|
5815
|
+
const options = field.options;
|
|
5816
|
+
if (options && options.length > 0) {
|
|
5817
|
+
const allowedValues = options.map((opt) => typeof opt === "object" ? String(opt.value) : String(opt));
|
|
5818
|
+
if (!allowedValues.includes(String(val))) errors.push({
|
|
5819
|
+
rowNumber,
|
|
5820
|
+
field: field.name,
|
|
5821
|
+
value: val,
|
|
5822
|
+
code: "INVALID_SELECT_OPTION",
|
|
5823
|
+
reason: `${label} value '${val}' is not a valid option (allowed: ${allowedValues.join(", ")}).`
|
|
5824
|
+
});
|
|
5825
|
+
}
|
|
5826
|
+
break;
|
|
5827
|
+
}
|
|
5828
|
+
case "json":
|
|
5829
|
+
if (typeof val === "string") try {
|
|
5830
|
+
data[field.name] = JSON.parse(val);
|
|
5831
|
+
} catch {
|
|
5832
|
+
errors.push({
|
|
5833
|
+
rowNumber,
|
|
5834
|
+
field: field.name,
|
|
5835
|
+
value: val,
|
|
5836
|
+
code: "INVALID_DATA_TYPE",
|
|
5837
|
+
reason: `${label} must be a valid JSON structure.`
|
|
5838
|
+
});
|
|
5839
|
+
}
|
|
5840
|
+
break;
|
|
5841
|
+
}
|
|
5842
|
+
if (typeof field.validate === "function") try {
|
|
5843
|
+
const res = field.validate(val, data);
|
|
5844
|
+
if (typeof res === "string") errors.push({
|
|
5845
|
+
rowNumber,
|
|
5846
|
+
field: field.name,
|
|
5847
|
+
value: val,
|
|
5848
|
+
code: "VALIDATION_RULE_FAILED",
|
|
5849
|
+
reason: res
|
|
5850
|
+
});
|
|
5851
|
+
else if (res === false) errors.push({
|
|
5852
|
+
rowNumber,
|
|
5853
|
+
field: field.name,
|
|
5854
|
+
value: val,
|
|
5855
|
+
code: "VALIDATION_RULE_FAILED",
|
|
5856
|
+
reason: `${label} failed custom validation constraint.`
|
|
5857
|
+
});
|
|
5858
|
+
} catch (err) {
|
|
5859
|
+
errors.push({
|
|
5860
|
+
rowNumber,
|
|
5861
|
+
field: field.name,
|
|
5862
|
+
value: val,
|
|
5863
|
+
code: "VALIDATION_RULE_FAILED",
|
|
5864
|
+
reason: err instanceof Error ? err.message : String(err)
|
|
5865
|
+
});
|
|
5866
|
+
}
|
|
5867
|
+
}
|
|
5868
|
+
async function checkExistingUnique(storage, collectionSlug, fieldName, value) {
|
|
5869
|
+
if (fieldName === "slug") return await storage.getContentBySlug(collectionSlug, String(value)) !== null;
|
|
5870
|
+
return (await storage.findContent(collectionSlug, {
|
|
5871
|
+
where: { [fieldName]: value },
|
|
5872
|
+
limit: 1
|
|
5873
|
+
})).items.length > 0;
|
|
5874
|
+
}
|
|
5875
|
+
async function checkRelationshipExists(storage, targetCollection, refId) {
|
|
5876
|
+
const idStr = String(refId);
|
|
5877
|
+
if (await storage.getContent(targetCollection, idStr) !== null) return true;
|
|
5878
|
+
return await storage.getContentBySlug(targetCollection, idStr) !== null;
|
|
5879
|
+
}
|
|
5880
|
+
//#endregion
|
|
5881
|
+
//#region src/plugins/transfer/presets/hrms.ts
|
|
5882
|
+
/**
|
|
5883
|
+
* Preconfigured mapping definition for importing and exporting HRMS Employers.
|
|
5884
|
+
*/
|
|
5885
|
+
const HRMS_EMPLOYER_TRANSFER_PRESET = {
|
|
5886
|
+
id: "hrms_employers_preset",
|
|
5887
|
+
name: "HRMS Employers Standard Mapping",
|
|
5888
|
+
collectionSlug: "employers",
|
|
5889
|
+
fields: [
|
|
5890
|
+
{
|
|
5891
|
+
sourceField: "Company Name",
|
|
5892
|
+
targetField: "companyName",
|
|
5893
|
+
required: true
|
|
5894
|
+
},
|
|
5895
|
+
{
|
|
5896
|
+
sourceField: "Legal Name",
|
|
5897
|
+
targetField: "legalName"
|
|
5898
|
+
},
|
|
5899
|
+
{
|
|
5900
|
+
sourceField: "Tax ID",
|
|
5901
|
+
targetField: "taxId"
|
|
5902
|
+
},
|
|
5903
|
+
{
|
|
5904
|
+
sourceField: "Primary Email",
|
|
5905
|
+
targetField: "email",
|
|
5906
|
+
transform: "trim"
|
|
5907
|
+
},
|
|
5908
|
+
{
|
|
5909
|
+
sourceField: "Phone",
|
|
5910
|
+
targetField: "phone",
|
|
5911
|
+
transform: "trim"
|
|
5912
|
+
},
|
|
5913
|
+
{
|
|
5914
|
+
sourceField: "Website",
|
|
5915
|
+
targetField: "website"
|
|
5916
|
+
},
|
|
5917
|
+
{
|
|
5918
|
+
sourceField: "Timezone",
|
|
5919
|
+
targetField: "timezone",
|
|
5920
|
+
defaultValue: "UTC"
|
|
5921
|
+
},
|
|
5922
|
+
{
|
|
5923
|
+
sourceField: "Status",
|
|
5924
|
+
targetField: "status",
|
|
5925
|
+
defaultValue: "active"
|
|
5926
|
+
}
|
|
5927
|
+
],
|
|
5928
|
+
options: {
|
|
5929
|
+
autoGenerateSlug: true,
|
|
5930
|
+
defaultStatus: "published",
|
|
5931
|
+
onDuplicate: "update",
|
|
5932
|
+
uniqueIdentifierField: "taxId"
|
|
5933
|
+
}
|
|
5934
|
+
};
|
|
5935
|
+
/**
|
|
5936
|
+
* Preconfigured mapping definition for importing and exporting HRMS Employees.
|
|
5937
|
+
*/
|
|
5938
|
+
const HRMS_EMPLOYEE_TRANSFER_PRESET = {
|
|
5939
|
+
id: "hrms_employees_preset",
|
|
5940
|
+
name: "HRMS Employees Standard Mapping",
|
|
5941
|
+
collectionSlug: "employees",
|
|
5942
|
+
fields: [
|
|
5943
|
+
{
|
|
5944
|
+
sourceField: "Employer ID",
|
|
5945
|
+
targetField: "employerId",
|
|
5946
|
+
required: true
|
|
5947
|
+
},
|
|
5948
|
+
{
|
|
5949
|
+
sourceField: "Employee Number",
|
|
5950
|
+
targetField: "employeeNumber",
|
|
5951
|
+
required: true,
|
|
5952
|
+
transform: "trim"
|
|
5953
|
+
},
|
|
5954
|
+
{
|
|
5955
|
+
sourceField: "First Name",
|
|
5956
|
+
targetField: "firstName",
|
|
5957
|
+
required: true,
|
|
5958
|
+
transform: "trim"
|
|
5959
|
+
},
|
|
5960
|
+
{
|
|
5961
|
+
sourceField: "Last Name",
|
|
5962
|
+
targetField: "lastName",
|
|
5963
|
+
required: true,
|
|
5964
|
+
transform: "trim"
|
|
5965
|
+
},
|
|
5966
|
+
{
|
|
5967
|
+
sourceField: "Work Email",
|
|
5968
|
+
targetField: "email",
|
|
5969
|
+
required: true,
|
|
5970
|
+
transform: "lowercase"
|
|
5971
|
+
},
|
|
5972
|
+
{
|
|
5973
|
+
sourceField: "Phone",
|
|
5974
|
+
targetField: "phone",
|
|
5975
|
+
transform: "trim"
|
|
5976
|
+
},
|
|
5977
|
+
{
|
|
5978
|
+
sourceField: "Job Title",
|
|
5979
|
+
targetField: "jobTitle"
|
|
5980
|
+
},
|
|
5981
|
+
{
|
|
5982
|
+
sourceField: "Employment Type",
|
|
5983
|
+
targetField: "employmentType",
|
|
5984
|
+
defaultValue: "full_time"
|
|
5985
|
+
},
|
|
5986
|
+
{
|
|
5987
|
+
sourceField: "Hire Date",
|
|
5988
|
+
targetField: "hireDate",
|
|
5989
|
+
required: true,
|
|
5990
|
+
transform: "date"
|
|
5991
|
+
},
|
|
5992
|
+
{
|
|
5993
|
+
sourceField: "Status",
|
|
5994
|
+
targetField: "status",
|
|
5995
|
+
defaultValue: "active"
|
|
5996
|
+
}
|
|
5997
|
+
],
|
|
5998
|
+
options: {
|
|
5999
|
+
autoGenerateSlug: true,
|
|
6000
|
+
defaultStatus: "published",
|
|
6001
|
+
onDuplicate: "error",
|
|
6002
|
+
uniqueIdentifierField: "employeeNumber"
|
|
6003
|
+
}
|
|
6004
|
+
};
|
|
6005
|
+
//#endregion
|
|
6006
|
+
//#region src/plugins/transfer/service.ts
|
|
6007
|
+
var TransferService = class {
|
|
6008
|
+
engine;
|
|
6009
|
+
options;
|
|
6010
|
+
presets = /* @__PURE__ */ new Map();
|
|
6011
|
+
constructor(engine, options = {}) {
|
|
6012
|
+
this.engine = engine;
|
|
6013
|
+
this.options = options;
|
|
6014
|
+
this.registerPreset(HRMS_EMPLOYER_TRANSFER_PRESET);
|
|
6015
|
+
this.registerPreset(HRMS_EMPLOYEE_TRANSFER_PRESET);
|
|
6016
|
+
}
|
|
6017
|
+
/**
|
|
6018
|
+
* List all registered collections across all active plugins in the engine.
|
|
6019
|
+
*/
|
|
6020
|
+
listCollections() {
|
|
6021
|
+
return this.engine.getCollections().map(summarizeCollection);
|
|
6022
|
+
}
|
|
6023
|
+
/**
|
|
6024
|
+
* Get the collection schema summary for a specific collection slug.
|
|
6025
|
+
*/
|
|
6026
|
+
getCollectionSchema(collectionSlug) {
|
|
6027
|
+
return summarizeCollection(this.getCollectionConfigOrThrow(collectionSlug));
|
|
6028
|
+
}
|
|
6029
|
+
/**
|
|
6030
|
+
* Register a reusable data mapping preset.
|
|
6031
|
+
*/
|
|
6032
|
+
registerPreset(preset) {
|
|
6033
|
+
const id = preset.id || `${preset.collectionSlug}_${preset.name || "preset"}`;
|
|
6034
|
+
this.presets.set(id, {
|
|
6035
|
+
...preset,
|
|
6036
|
+
id
|
|
6037
|
+
});
|
|
6038
|
+
}
|
|
6039
|
+
/**
|
|
6040
|
+
* Get a registered preset by ID.
|
|
6041
|
+
*/
|
|
6042
|
+
getPreset(id) {
|
|
6043
|
+
return this.presets.get(id);
|
|
6044
|
+
}
|
|
6045
|
+
/**
|
|
6046
|
+
* Get all registered presets, optionally filtered by target collection.
|
|
6047
|
+
*/
|
|
6048
|
+
getPresets(collectionSlug) {
|
|
6049
|
+
const all = Array.from(this.presets.values());
|
|
6050
|
+
if (collectionSlug) return all.filter((p) => p.collectionSlug === collectionSlug);
|
|
6051
|
+
return all;
|
|
6052
|
+
}
|
|
6053
|
+
/**
|
|
6054
|
+
* Generate a 1:1 default mapping template for any collection.
|
|
6055
|
+
*/
|
|
6056
|
+
getMappingTemplate(collectionSlug) {
|
|
6057
|
+
const config = this.getCollectionConfigOrThrow(collectionSlug);
|
|
6058
|
+
return {
|
|
6059
|
+
id: `${collectionSlug}_default_template`,
|
|
6060
|
+
name: `${config.label} Default Template`,
|
|
6061
|
+
collectionSlug,
|
|
6062
|
+
fields: config.fields.map((f) => ({
|
|
6063
|
+
sourceField: f.name,
|
|
6064
|
+
targetField: f.name,
|
|
6065
|
+
required: Boolean(f.required),
|
|
6066
|
+
defaultValue: f.defaultValue
|
|
6067
|
+
})),
|
|
6068
|
+
options: {
|
|
6069
|
+
autoGenerateSlug: true,
|
|
6070
|
+
defaultStatus: config.draftable ? "draft" : "published",
|
|
6071
|
+
onDuplicate: "error"
|
|
6072
|
+
}
|
|
6073
|
+
};
|
|
6074
|
+
}
|
|
6075
|
+
/**
|
|
6076
|
+
* Inspect any source payload or file (JSON, Excel, CSV) to extract headers,
|
|
6077
|
+
* infer data types, and generate auto-mapping suggestions against a target collection.
|
|
6078
|
+
*/
|
|
6079
|
+
async inspectSource(input, options = {}) {
|
|
6080
|
+
const config = options.collectionSlug ? this.engine.getCollectionConfig(options.collectionSlug) : void 0;
|
|
6081
|
+
return inspectSource(input, {
|
|
6082
|
+
...options,
|
|
6083
|
+
collectionConfig: config
|
|
6084
|
+
});
|
|
6085
|
+
}
|
|
6086
|
+
/**
|
|
6087
|
+
* Dry-run validation of a source batch against a target collection's schema
|
|
6088
|
+
* and live database constraints without committing any changes.
|
|
6089
|
+
*/
|
|
6090
|
+
async validateImport(collectionSlug, input, mapping, options = {}) {
|
|
6091
|
+
const config = this.getCollectionConfigOrThrow(collectionSlug);
|
|
6092
|
+
const parsed = await parseSource(input, {
|
|
6093
|
+
format: options.format,
|
|
6094
|
+
fileName: options.fileName,
|
|
6095
|
+
sheetName: options.sheetName
|
|
6096
|
+
});
|
|
6097
|
+
const activeMapping = mapping || this.getMappingTemplate(collectionSlug);
|
|
6098
|
+
return validateTransferBatch(parsed.records, activeMapping, config, {
|
|
6099
|
+
storage: this.engine.storage,
|
|
6100
|
+
onDuplicate: options.onDuplicate,
|
|
6101
|
+
previewLimit: options.previewLimit
|
|
6102
|
+
});
|
|
6103
|
+
}
|
|
6104
|
+
/**
|
|
6105
|
+
* Execute an import batch from raw data or an external file (JSON, Excel, CSV)
|
|
6106
|
+
* into a target CMS collection.
|
|
6107
|
+
*/
|
|
6108
|
+
async importData(collectionSlug, input, mapping, options = {}) {
|
|
6109
|
+
const config = this.getCollectionConfigOrThrow(collectionSlug);
|
|
6110
|
+
const parsed = await parseSource(input, {
|
|
6111
|
+
format: options.format,
|
|
6112
|
+
fileName: options.fileName,
|
|
6113
|
+
sheetName: options.sheetName
|
|
6114
|
+
});
|
|
6115
|
+
const activeMapping = mapping || this.getMappingTemplate(collectionSlug);
|
|
6116
|
+
const rawRecords = parsed.records;
|
|
6117
|
+
const onDuplicate = options.onDuplicate ?? activeMapping.options?.onDuplicate ?? "error";
|
|
6118
|
+
const abortOnError = options.abortOnError ?? activeMapping.options?.abortOnError ?? false;
|
|
6119
|
+
const validation = await validateTransferBatch(rawRecords, activeMapping, config, {
|
|
6120
|
+
storage: this.engine.storage,
|
|
6121
|
+
onDuplicate
|
|
6122
|
+
});
|
|
6123
|
+
if (options.dryRun) return {
|
|
6124
|
+
success: validation.valid,
|
|
6125
|
+
collectionSlug,
|
|
6126
|
+
totalRows: rawRecords.length,
|
|
6127
|
+
importedCount: validation.validCount,
|
|
6128
|
+
updatedCount: 0,
|
|
6129
|
+
skippedCount: 0,
|
|
6130
|
+
failedCount: validation.errorCount,
|
|
6131
|
+
createdIds: [],
|
|
6132
|
+
updatedIds: [],
|
|
6133
|
+
errors: validation.errors
|
|
6134
|
+
};
|
|
6135
|
+
if (abortOnError && !validation.valid) return {
|
|
6136
|
+
success: false,
|
|
6137
|
+
collectionSlug,
|
|
6138
|
+
totalRows: rawRecords.length,
|
|
6139
|
+
importedCount: 0,
|
|
6140
|
+
updatedCount: 0,
|
|
6141
|
+
skippedCount: 0,
|
|
6142
|
+
failedCount: validation.errorCount,
|
|
6143
|
+
createdIds: [],
|
|
6144
|
+
updatedIds: [],
|
|
6145
|
+
errors: validation.errors
|
|
6146
|
+
};
|
|
6147
|
+
await this.engine.hooks.doAction("cms.transfer_import_started", {
|
|
6148
|
+
collectionSlug,
|
|
6149
|
+
totalRows: rawRecords.length
|
|
6150
|
+
});
|
|
6151
|
+
const createdIds = [];
|
|
6152
|
+
const updatedIds = [];
|
|
6153
|
+
const errors = [...validation.errors];
|
|
6154
|
+
let importedCount = 0;
|
|
6155
|
+
let updatedCount = 0;
|
|
6156
|
+
let skippedCount = 0;
|
|
6157
|
+
const rowErrorsMap = /* @__PURE__ */ new Map();
|
|
6158
|
+
for (const err of validation.errors) {
|
|
6159
|
+
const list = rowErrorsMap.get(err.rowNumber) || [];
|
|
6160
|
+
list.push(err);
|
|
6161
|
+
rowErrorsMap.set(err.rowNumber, list);
|
|
6162
|
+
}
|
|
6163
|
+
const collService = this.engine.collection(collectionSlug);
|
|
6164
|
+
for (let i = 0; i < rawRecords.length; i++) {
|
|
6165
|
+
const rowNumber = i + 1;
|
|
6166
|
+
const rowErrors = rowErrorsMap.get(rowNumber);
|
|
6167
|
+
if (rowErrors && rowErrors.length > 0) {
|
|
6168
|
+
if (rowErrors.some((e) => e.code !== "CONSTRAINT_UNIQUE_VIOLATION" || onDuplicate === "error")) continue;
|
|
6169
|
+
}
|
|
6170
|
+
const raw = rawRecords[i];
|
|
6171
|
+
let mapped;
|
|
6172
|
+
try {
|
|
6173
|
+
mapped = mapSourceRecord(raw, activeMapping);
|
|
6174
|
+
} catch (err) {
|
|
6175
|
+
errors.push({
|
|
6176
|
+
rowNumber,
|
|
6177
|
+
code: "TRANSFORM_ERROR",
|
|
6178
|
+
reason: err instanceof Error ? err.message : String(err)
|
|
6179
|
+
});
|
|
6180
|
+
continue;
|
|
6181
|
+
}
|
|
6182
|
+
mapped = await this.engine.hooks.applyFilters("cms.transfer_before_import_row", mapped, {
|
|
6183
|
+
collectionSlug,
|
|
6184
|
+
rowNumber,
|
|
6185
|
+
raw
|
|
6186
|
+
});
|
|
6187
|
+
const identifierField = options.uniqueIdentifierField || activeMapping.options?.uniqueIdentifierField || this.detectUniqueField(config);
|
|
6188
|
+
let existingItem = null;
|
|
6189
|
+
if (identifierField && mapped.data[identifierField] !== void 0) {
|
|
6190
|
+
const val = mapped.data[identifierField];
|
|
6191
|
+
if (identifierField === "slug") existingItem = await this.engine.storage.getContentBySlug(collectionSlug, String(val));
|
|
6192
|
+
else existingItem = (await this.engine.storage.findContent(collectionSlug, {
|
|
6193
|
+
where: { [identifierField]: val },
|
|
6194
|
+
limit: 1
|
|
6195
|
+
})).items[0] || null;
|
|
6196
|
+
}
|
|
6197
|
+
if (existingItem) {
|
|
6198
|
+
if (onDuplicate === "skip") {
|
|
6199
|
+
skippedCount++;
|
|
6200
|
+
continue;
|
|
6201
|
+
}
|
|
6202
|
+
if (onDuplicate === "update") {
|
|
6203
|
+
try {
|
|
6204
|
+
const updated = await collService.update(existingItem.id, {
|
|
6205
|
+
title: mapped.title ?? existingItem.title,
|
|
6206
|
+
slug: mapped.slug ?? existingItem.slug,
|
|
6207
|
+
status: mapped.status ?? existingItem.status,
|
|
6208
|
+
data: {
|
|
6209
|
+
...existingItem.data,
|
|
6210
|
+
...mapped.data
|
|
6211
|
+
}
|
|
6212
|
+
}, options.authorId, options.revisionNote || "Import transfer update");
|
|
6213
|
+
if (updated) {
|
|
6214
|
+
updatedIds.push(updated.id);
|
|
6215
|
+
updatedCount++;
|
|
6216
|
+
await this.engine.hooks.doAction("cms.transfer_row_imported", {
|
|
6217
|
+
collectionSlug,
|
|
6218
|
+
action: "update",
|
|
6219
|
+
item: updated
|
|
6220
|
+
});
|
|
6221
|
+
}
|
|
6222
|
+
} catch (err) {
|
|
6223
|
+
errors.push({
|
|
6224
|
+
rowNumber,
|
|
6225
|
+
code: "VALIDATION_RULE_FAILED",
|
|
6226
|
+
reason: err instanceof Error ? err.message : String(err)
|
|
6227
|
+
});
|
|
6228
|
+
}
|
|
6229
|
+
continue;
|
|
6230
|
+
}
|
|
6231
|
+
}
|
|
6232
|
+
try {
|
|
6233
|
+
const created = await collService.create({
|
|
6234
|
+
title: mapped.title,
|
|
6235
|
+
slug: mapped.slug,
|
|
6236
|
+
status: mapped.status,
|
|
6237
|
+
data: mapped.data
|
|
6238
|
+
}, options.authorId);
|
|
6239
|
+
createdIds.push(created.id);
|
|
6240
|
+
importedCount++;
|
|
6241
|
+
await this.engine.hooks.doAction("cms.transfer_row_imported", {
|
|
6242
|
+
collectionSlug,
|
|
6243
|
+
action: "create",
|
|
6244
|
+
item: created
|
|
6245
|
+
});
|
|
6246
|
+
} catch (err) {
|
|
6247
|
+
errors.push({
|
|
6248
|
+
rowNumber,
|
|
6249
|
+
code: "VALIDATION_RULE_FAILED",
|
|
6250
|
+
reason: err instanceof Error ? err.message : String(err)
|
|
6251
|
+
});
|
|
6252
|
+
}
|
|
6253
|
+
}
|
|
6254
|
+
const result = {
|
|
6255
|
+
success: errors.length === 0,
|
|
6256
|
+
collectionSlug,
|
|
6257
|
+
totalRows: rawRecords.length,
|
|
6258
|
+
importedCount,
|
|
6259
|
+
updatedCount,
|
|
6260
|
+
skippedCount,
|
|
6261
|
+
failedCount: rawRecords.length - (importedCount + updatedCount + skippedCount),
|
|
6262
|
+
createdIds,
|
|
6263
|
+
updatedIds,
|
|
6264
|
+
errors
|
|
6265
|
+
};
|
|
6266
|
+
await this.engine.hooks.doAction("cms.transfer_import_completed", result);
|
|
6267
|
+
await this.engine.hooks.doAction(`cms.${collectionSlug}_transferred`, result);
|
|
6268
|
+
return result;
|
|
6269
|
+
}
|
|
6270
|
+
/**
|
|
6271
|
+
* Export CMS collection records to JSON, Excel (.xlsx), or CSV.
|
|
6272
|
+
*/
|
|
6273
|
+
async exportData(collectionSlug, options = {}) {
|
|
6274
|
+
const config = this.getCollectionConfigOrThrow(collectionSlug);
|
|
6275
|
+
const collService = this.engine.collection(collectionSlug);
|
|
6276
|
+
const query = options.query || { limit: 1e4 };
|
|
6277
|
+
const items = (await collService.find(query)).items;
|
|
6278
|
+
const exportRecords = [];
|
|
6279
|
+
for (const item of items) {
|
|
6280
|
+
let mappedRow = mapCmsItemForExport(item, options.mapping, {
|
|
6281
|
+
includeId: options.includeId,
|
|
6282
|
+
includeTimestamps: options.includeTimestamps
|
|
6283
|
+
});
|
|
6284
|
+
mappedRow = await this.engine.hooks.applyFilters("cms.transfer_before_export_row", mappedRow, {
|
|
6285
|
+
collectionSlug,
|
|
6286
|
+
item
|
|
6287
|
+
});
|
|
6288
|
+
exportRecords.push(mappedRow);
|
|
6289
|
+
}
|
|
6290
|
+
return serializeSource(exportRecords, {
|
|
6291
|
+
format: options.format || "json",
|
|
6292
|
+
fileName: options.fileName || `${collectionSlug}_export_${(/* @__PURE__ */ new Date()).toISOString().split("T")[0]}`,
|
|
6293
|
+
sheetName: options.sheetName || config.label
|
|
6294
|
+
});
|
|
6295
|
+
}
|
|
6296
|
+
getCollectionConfigOrThrow(collectionSlug) {
|
|
6297
|
+
const config = this.engine.getCollectionConfig(collectionSlug);
|
|
6298
|
+
if (!config) throw new Error(`[TransferService] Collection '${collectionSlug}' is not registered in the CMS engine.`);
|
|
6299
|
+
return config;
|
|
6300
|
+
}
|
|
6301
|
+
detectUniqueField(config) {
|
|
6302
|
+
const unique = config.fields.find((f) => Boolean(f.unique));
|
|
6303
|
+
if (unique) return unique.name;
|
|
6304
|
+
const slugField = config.fields.find((f) => f.type === "slug" || f.name === "slug");
|
|
6305
|
+
if (slugField) return slugField.name;
|
|
6306
|
+
}
|
|
6307
|
+
};
|
|
6308
|
+
//#endregion
|
|
6309
|
+
//#region src/plugins/transfer/routes.ts
|
|
6310
|
+
function json(data, status = 200, headers = {}) {
|
|
6311
|
+
return new Response(JSON.stringify(data), {
|
|
6312
|
+
status,
|
|
6313
|
+
headers: {
|
|
6314
|
+
"Content-Type": "application/json",
|
|
6315
|
+
"Access-Control-Allow-Origin": "*",
|
|
6316
|
+
...headers
|
|
6317
|
+
}
|
|
6318
|
+
});
|
|
6319
|
+
}
|
|
6320
|
+
function badRequest(message) {
|
|
6321
|
+
return json({ error: message }, 400);
|
|
6322
|
+
}
|
|
6323
|
+
function notFound(message) {
|
|
6324
|
+
return json({ error: message }, 404);
|
|
6325
|
+
}
|
|
6326
|
+
function registerTransferRoutes(ctx, service, options = {}) {
|
|
6327
|
+
const prefix = (options.apiPrefix ?? "/api/transfer").replace(/\/+$/, "");
|
|
6328
|
+
ctx.registerRoute("GET", `${prefix}/collections`, async () => {
|
|
6329
|
+
try {
|
|
6330
|
+
return json({ collections: service.listCollections() });
|
|
6331
|
+
} catch (err) {
|
|
6332
|
+
return badRequest(err instanceof Error ? err.message : String(err));
|
|
6333
|
+
}
|
|
6334
|
+
});
|
|
6335
|
+
ctx.registerRoute("GET", `${prefix}/presets`, async (_req, { url }) => {
|
|
6336
|
+
try {
|
|
6337
|
+
const collectionSlug = url.searchParams.get("collection") || void 0;
|
|
6338
|
+
return json({ presets: service.getPresets(collectionSlug) });
|
|
6339
|
+
} catch (err) {
|
|
6340
|
+
return badRequest(err instanceof Error ? err.message : String(err));
|
|
6341
|
+
}
|
|
6342
|
+
});
|
|
6343
|
+
ctx.registerRoute("POST", `${prefix}/presets`, async (req) => {
|
|
6344
|
+
try {
|
|
6345
|
+
const body = await req.json();
|
|
6346
|
+
if (!body.collectionSlug || !Array.isArray(body.fields)) return badRequest("collectionSlug and fields array are required.");
|
|
6347
|
+
service.registerPreset(body);
|
|
6348
|
+
return json({
|
|
6349
|
+
success: true,
|
|
6350
|
+
preset: body
|
|
6351
|
+
}, 201);
|
|
6352
|
+
} catch (err) {
|
|
6353
|
+
return badRequest(err instanceof Error ? err.message : String(err));
|
|
6354
|
+
}
|
|
6355
|
+
});
|
|
6356
|
+
ctx.registerRoute("GET", `${prefix}/:collection/schema`, async (_req, { params }) => {
|
|
6357
|
+
try {
|
|
6358
|
+
return json({
|
|
6359
|
+
schema: service.getCollectionSchema(params.collection),
|
|
6360
|
+
template: service.getMappingTemplate(params.collection)
|
|
6361
|
+
});
|
|
6362
|
+
} catch (err) {
|
|
6363
|
+
return notFound(err instanceof Error ? err.message : String(err));
|
|
6364
|
+
}
|
|
6365
|
+
});
|
|
6366
|
+
ctx.registerRoute("POST", `${prefix}/inspect`, async (req) => {
|
|
6367
|
+
try {
|
|
6368
|
+
const payload = await extractPayload(req);
|
|
6369
|
+
return json(await service.inspectSource(payload.data, {
|
|
6370
|
+
collectionSlug: payload.collectionSlug,
|
|
6371
|
+
format: payload.format,
|
|
6372
|
+
fileName: payload.fileName,
|
|
6373
|
+
sheetName: payload.sheetName
|
|
6374
|
+
}));
|
|
6375
|
+
} catch (err) {
|
|
6376
|
+
return badRequest(err instanceof Error ? err.message : String(err));
|
|
6377
|
+
}
|
|
6378
|
+
});
|
|
6379
|
+
ctx.registerRoute("POST", `${prefix}/:collection/preview`, async (req, { params }) => {
|
|
6380
|
+
try {
|
|
6381
|
+
const payload = await extractPayload(req);
|
|
6382
|
+
return json(await service.validateImport(params.collection, payload.data, payload.mapping, {
|
|
6383
|
+
format: payload.format,
|
|
6384
|
+
fileName: payload.fileName,
|
|
6385
|
+
sheetName: payload.sheetName,
|
|
6386
|
+
onDuplicate: payload.onDuplicate
|
|
6387
|
+
}));
|
|
6388
|
+
} catch (err) {
|
|
6389
|
+
return badRequest(err instanceof Error ? err.message : String(err));
|
|
6390
|
+
}
|
|
6391
|
+
});
|
|
6392
|
+
ctx.registerRoute("POST", `${prefix}/:collection/import`, async (req, { params }) => {
|
|
6393
|
+
try {
|
|
6394
|
+
const payload = await extractPayload(req);
|
|
6395
|
+
const result = await service.importData(params.collection, payload.data, payload.mapping, {
|
|
6396
|
+
format: payload.format,
|
|
6397
|
+
fileName: payload.fileName,
|
|
6398
|
+
sheetName: payload.sheetName,
|
|
6399
|
+
onDuplicate: payload.onDuplicate,
|
|
6400
|
+
uniqueIdentifierField: payload.uniqueIdentifierField,
|
|
6401
|
+
abortOnError: payload.abortOnError,
|
|
6402
|
+
authorId: payload.authorId,
|
|
6403
|
+
revisionNote: payload.revisionNote
|
|
6404
|
+
});
|
|
6405
|
+
return json(result, result.success ? 200 : 207);
|
|
6406
|
+
} catch (err) {
|
|
6407
|
+
return badRequest(err instanceof Error ? err.message : String(err));
|
|
6408
|
+
}
|
|
6409
|
+
});
|
|
6410
|
+
ctx.registerRoute("POST", `${prefix}/:collection/export`, async (req, { params }) => {
|
|
6411
|
+
try {
|
|
6412
|
+
const body = await req.json();
|
|
6413
|
+
const result = await service.exportData(params.collection, {
|
|
6414
|
+
format: body.format,
|
|
6415
|
+
mapping: body.mapping,
|
|
6416
|
+
query: body.query,
|
|
6417
|
+
fileName: body.fileName,
|
|
6418
|
+
sheetName: body.sheetName,
|
|
6419
|
+
includeId: body.includeId,
|
|
6420
|
+
includeTimestamps: body.includeTimestamps
|
|
6421
|
+
});
|
|
6422
|
+
return new Response(result.data, {
|
|
6423
|
+
status: 200,
|
|
6424
|
+
headers: {
|
|
6425
|
+
"Content-Type": result.mimeType,
|
|
6426
|
+
"Content-Disposition": `attachment; filename="${result.fileName}"`,
|
|
6427
|
+
"Access-Control-Allow-Origin": "*"
|
|
6428
|
+
}
|
|
6429
|
+
});
|
|
6430
|
+
} catch (err) {
|
|
6431
|
+
return badRequest(err instanceof Error ? err.message : String(err));
|
|
6432
|
+
}
|
|
6433
|
+
});
|
|
6434
|
+
ctx.registerRoute("GET", `${prefix}/:collection/export`, async (_req, { params, url }) => {
|
|
6435
|
+
try {
|
|
6436
|
+
const format = url.searchParams.get("format") || "json";
|
|
6437
|
+
const fileName = url.searchParams.get("fileName") || void 0;
|
|
6438
|
+
const status = url.searchParams.get("status") || void 0;
|
|
6439
|
+
const search = url.searchParams.get("search") || void 0;
|
|
6440
|
+
const result = await service.exportData(params.collection, {
|
|
6441
|
+
format,
|
|
6442
|
+
fileName,
|
|
6443
|
+
query: {
|
|
6444
|
+
status,
|
|
6445
|
+
search
|
|
6446
|
+
}
|
|
6447
|
+
});
|
|
6448
|
+
return new Response(result.data, {
|
|
6449
|
+
status: 200,
|
|
6450
|
+
headers: {
|
|
6451
|
+
"Content-Type": result.mimeType,
|
|
6452
|
+
"Content-Disposition": `attachment; filename="${result.fileName}"`,
|
|
6453
|
+
"Access-Control-Allow-Origin": "*"
|
|
6454
|
+
}
|
|
6455
|
+
});
|
|
6456
|
+
} catch (err) {
|
|
6457
|
+
return badRequest(err instanceof Error ? err.message : String(err));
|
|
6458
|
+
}
|
|
6459
|
+
});
|
|
6460
|
+
}
|
|
6461
|
+
/**
|
|
6462
|
+
* Helper to extract payload and options from JSON or Multipart requests.
|
|
6463
|
+
*/
|
|
6464
|
+
async function extractPayload(req) {
|
|
6465
|
+
if ((req.headers.get("content-type") || "").includes("multipart/form-data")) {
|
|
6466
|
+
const formData = await req.formData();
|
|
6467
|
+
const file = formData.get("file");
|
|
6468
|
+
let data = null;
|
|
6469
|
+
let fileName;
|
|
6470
|
+
if (file && typeof file === "object" && "arrayBuffer" in file) {
|
|
6471
|
+
data = new Uint8Array(await file.arrayBuffer());
|
|
6472
|
+
fileName = file.name;
|
|
6473
|
+
}
|
|
6474
|
+
const mappingRaw = formData.get("mapping");
|
|
6475
|
+
const mapping = mappingRaw ? JSON.parse(String(mappingRaw)) : void 0;
|
|
6476
|
+
return {
|
|
6477
|
+
data,
|
|
6478
|
+
collectionSlug: formData.get("collectionSlug") || void 0,
|
|
6479
|
+
format: formData.get("format") || void 0,
|
|
6480
|
+
fileName: formData.get("fileName") || fileName,
|
|
6481
|
+
sheetName: formData.get("sheetName") || void 0,
|
|
6482
|
+
mapping,
|
|
6483
|
+
onDuplicate: formData.get("onDuplicate") || void 0,
|
|
6484
|
+
uniqueIdentifierField: formData.get("uniqueIdentifierField") || void 0,
|
|
6485
|
+
abortOnError: formData.get("abortOnError") === "true",
|
|
6486
|
+
authorId: formData.get("authorId") || void 0,
|
|
6487
|
+
revisionNote: formData.get("revisionNote") || void 0
|
|
6488
|
+
};
|
|
6489
|
+
}
|
|
6490
|
+
const body = await req.json();
|
|
6491
|
+
let data = body.data;
|
|
6492
|
+
if (typeof body.base64 === "string") data = Buffer.from(body.base64, "base64");
|
|
6493
|
+
return {
|
|
6494
|
+
data: data !== void 0 ? data : body,
|
|
6495
|
+
collectionSlug: body.collectionSlug,
|
|
6496
|
+
format: body.format,
|
|
6497
|
+
fileName: body.fileName,
|
|
6498
|
+
sheetName: body.sheetName,
|
|
6499
|
+
mapping: body.mapping,
|
|
6500
|
+
onDuplicate: body.onDuplicate,
|
|
6501
|
+
uniqueIdentifierField: body.uniqueIdentifierField,
|
|
6502
|
+
abortOnError: body.abortOnError,
|
|
6503
|
+
authorId: body.authorId,
|
|
6504
|
+
revisionNote: body.revisionNote
|
|
6505
|
+
};
|
|
6506
|
+
}
|
|
6507
|
+
//#endregion
|
|
6508
|
+
//#region src/plugins/transfer/client.ts
|
|
6509
|
+
var TransferClient = class {
|
|
6510
|
+
client;
|
|
6511
|
+
options;
|
|
6512
|
+
service;
|
|
6513
|
+
prefix;
|
|
6514
|
+
constructor(client, options = {}) {
|
|
6515
|
+
this.client = client;
|
|
6516
|
+
this.options = options;
|
|
6517
|
+
this.prefix = (options.apiPrefix ?? "/api/transfer").replace(/\/+$/, "");
|
|
6518
|
+
const engine = client.getEngine();
|
|
6519
|
+
if (engine) this.service = new TransferService(engine, options);
|
|
6520
|
+
}
|
|
6521
|
+
/**
|
|
6522
|
+
* List all registered collections across all active plugins.
|
|
6523
|
+
*/
|
|
6524
|
+
async listCollections() {
|
|
6525
|
+
if (this.service) return this.service.listCollections();
|
|
6526
|
+
return (await this.client.request(`${this.prefix}/collections`)).collections;
|
|
6527
|
+
}
|
|
6528
|
+
/**
|
|
6529
|
+
* Get the collection schema and default mapping template.
|
|
6530
|
+
*/
|
|
6531
|
+
async getSchema(collectionSlug) {
|
|
6532
|
+
if (this.service) return {
|
|
6533
|
+
schema: this.service.getCollectionSchema(collectionSlug),
|
|
6534
|
+
template: this.service.getMappingTemplate(collectionSlug)
|
|
6535
|
+
};
|
|
6536
|
+
return this.client.request(`${this.prefix}/${collectionSlug}/schema`);
|
|
6537
|
+
}
|
|
6538
|
+
/**
|
|
6539
|
+
* Inspect a source file or payload.
|
|
6540
|
+
*/
|
|
6541
|
+
async inspect(data, options = {}) {
|
|
6542
|
+
if (this.service) return this.service.inspectSource(data, options);
|
|
6543
|
+
return this.client.request(`${this.prefix}/inspect`, {
|
|
6544
|
+
method: "POST",
|
|
6545
|
+
body: JSON.stringify({
|
|
6546
|
+
data,
|
|
6547
|
+
...options
|
|
6548
|
+
})
|
|
6549
|
+
});
|
|
6550
|
+
}
|
|
6551
|
+
/**
|
|
6552
|
+
* Dry-run validation of a source batch against a target collection and database constraints.
|
|
6553
|
+
*/
|
|
6554
|
+
async preview(collectionSlug, data, mapping, options = {}) {
|
|
6555
|
+
if (this.service) return this.service.validateImport(collectionSlug, data, mapping, options);
|
|
6556
|
+
return this.client.request(`${this.prefix}/${collectionSlug}/preview`, {
|
|
6557
|
+
method: "POST",
|
|
6558
|
+
body: JSON.stringify({
|
|
6559
|
+
data,
|
|
6560
|
+
mapping,
|
|
6561
|
+
...options
|
|
6562
|
+
})
|
|
6563
|
+
});
|
|
6564
|
+
}
|
|
6565
|
+
/**
|
|
6566
|
+
* Execute an import batch into a target collection.
|
|
6567
|
+
*/
|
|
6568
|
+
async import(collectionSlug, data, mapping, options = {}) {
|
|
6569
|
+
if (this.service) return this.service.importData(collectionSlug, data, mapping, options);
|
|
6570
|
+
return this.client.request(`${this.prefix}/${collectionSlug}/import`, {
|
|
6571
|
+
method: "POST",
|
|
6572
|
+
body: JSON.stringify({
|
|
6573
|
+
data,
|
|
6574
|
+
mapping,
|
|
6575
|
+
...options
|
|
6576
|
+
})
|
|
6577
|
+
});
|
|
6578
|
+
}
|
|
6579
|
+
/**
|
|
6580
|
+
* Export collection records to JSON, Excel, or CSV.
|
|
6581
|
+
*/
|
|
6582
|
+
async export(collectionSlug, options = {}) {
|
|
6583
|
+
if (this.service) return this.service.exportData(collectionSlug, options);
|
|
6584
|
+
return await this.client.request(`${this.prefix}/${collectionSlug}/export`, {
|
|
6585
|
+
method: "POST",
|
|
6586
|
+
body: JSON.stringify(options)
|
|
6587
|
+
});
|
|
6588
|
+
}
|
|
6589
|
+
};
|
|
6590
|
+
/**
|
|
6591
|
+
* Access or instantiate the TransferClient associated with a CMSClient instance.
|
|
6592
|
+
*/
|
|
6593
|
+
function getTransferClient(client, options) {
|
|
6594
|
+
if (client.__transferClient) return client.__transferClient;
|
|
6595
|
+
const tc = new TransferClient(client, options);
|
|
6596
|
+
client.__transferClient = tc;
|
|
6597
|
+
return tc;
|
|
6598
|
+
}
|
|
6599
|
+
//#endregion
|
|
6600
|
+
//#region src/plugins/transfer/index.ts
|
|
6601
|
+
/**
|
|
6602
|
+
* @azlib/cms - Built-in Universal Transfer Plugin
|
|
6603
|
+
*/
|
|
6604
|
+
/**
|
|
6605
|
+
* Built-in Universal Data Transfer plugin factory for @azlib/cms.
|
|
6606
|
+
* Equips the CMS engine with dynamic, schema-driven import and export capabilities
|
|
6607
|
+
* across all collections, featuring file schema discovery, definition mapping,
|
|
6608
|
+
* multi-level data validation, database constraint verification, and multi-format support.
|
|
6609
|
+
*/
|
|
6610
|
+
const transferPlugin = definePlugin((options) => {
|
|
6611
|
+
const opts = options || {};
|
|
6612
|
+
return {
|
|
6613
|
+
name: "transfer",
|
|
6614
|
+
version: "1.0.0",
|
|
6615
|
+
description: "Universal schema-driven data transfer plugin supporting import/export, definition mapping, and constraint validation",
|
|
6616
|
+
setup(ctx) {
|
|
6617
|
+
const service = new TransferService(ctx.engine, opts);
|
|
6618
|
+
ctx.engine.__transferService = service;
|
|
6619
|
+
if (opts.enableRoutes !== false) registerTransferRoutes(ctx, service, opts);
|
|
6620
|
+
}
|
|
6621
|
+
};
|
|
6622
|
+
});
|
|
6623
|
+
/**
|
|
6624
|
+
* Retrieve the active TransferService instance associated with a CMSEngine.
|
|
6625
|
+
*/
|
|
6626
|
+
function getTransferService(engine, options) {
|
|
6627
|
+
if (engine.__transferService) return engine.__transferService;
|
|
6628
|
+
const service = new TransferService(engine, options);
|
|
6629
|
+
engine.__transferService = service;
|
|
6630
|
+
return service;
|
|
6631
|
+
}
|
|
6632
|
+
//#endregion
|
|
6633
|
+
export { CMSClient, CMSEngine, CMSRouter, ContentLifecycle, DEFAULT_COLLECTIONS, DEFAULT_ROLE_CAPABILITIES, EcommerceClient, EcommerceService, HRMSClient, HRMSService, HRMS_EMPLOYEE_TRANSFER_PRESET, HRMS_EMPLOYER_TRANSFER_PRESET, HooksManager, MediaManager, MemoryStorageAdapter, OptionsManager, RBACManager, RevisionManager, TaxonomyManager, TransferClient, TransferService, VALID_STATUS_TRANSITIONS, applyFieldTransform, collection, createAttendanceCollection, createCMSEngine, createCMSRouter, createCmsClient, createDiscountCollection, createEcommerceTaxonomies, createEmployeeCollection, createEmployerCollection, createHRMSTaxonomies, createLeaveRequestCollection, createLeaveTypeCollection, createOrderCollection, createProductCollection, defaultHooks, defineConfig, definePlugin, detectFormat, ecommercePlugin, fields, generateSuggestedMapping, getEcommerceClient, getEcommerceService, getHRMSClient, getHRMSService, getTransferClient, getTransferService, hrmsPlugin, inspectSource, mapCmsItemForExport, mapSourceRecord, normalizeConfig, parseCsvSource, parseExcelSource, parseJsonSource, parseSource, resolveUniqueSlug, serializeCsv, serializeExcel, serializeJson, serializeSource, slugify, summarizeCollection, transferPlugin, validateAndNormalizeData, validateTransferBatch };
|
|
3238
6634
|
|
|
3239
6635
|
//# sourceMappingURL=index.mjs.map
|