@classytic/work-period 0.0.0-stage → 0.1.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/CHANGELOG.md ADDED
@@ -0,0 +1,13 @@
1
+ # Changelog
2
+
3
+ ## 0.1.0 — 2026-10-18
4
+
5
+ First published release: a country-neutral approved work-period and locked payroll-facts kernel.
6
+
7
+ - `defineWorkPeriod()` describe/bind engine, the `WorkPeriod` model and `WorkPeriodRepository` (`create`, `reconcile`, and the submit, approve, reject, reopen and lock transitions, each guarded by a compare-and-set on status).
8
+ - A period carries its attendance facts, leave facts and policy reference, so payroll reads a frozen, approved set of facts and not live bridges.
9
+ - Events: `WORK_PERIOD_EVENTS` and `workPeriodEventDefinitions` (created, reconciled, submitted, approved, rejected, reopened, locked), with `InProcessWorkPeriodBus`.
10
+ - Typed errors: duplicate period, invalid transition, approval, capability, concurrency, not found.
11
+ - Peers: `@classytic/mongokit` `>=3.41.0`, `@classytic/primitives` `>=0.32.0`, `@classytic/repo-core` `>=0.31.0`, `mongoose` `>=9.11.0` (`zod >=4.0.0` unchanged).
12
+ - Entries: `.` and `./schemas`.
13
+ - Licensed under the Classytic Source-Available License, as the other `@classytic/hr` packages.
package/LICENSE ADDED
@@ -0,0 +1,75 @@
1
+ Classytic Source-Available License (Community & Commercial), Version 1.0
2
+
3
+ Copyright (c) 2026 Classytic LLC. All rights reserved.
4
+
5
+ This software is source-available, not open source. Please read this License
6
+ before using it.
7
+
8
+ 1. DEFINITIONS
9
+ "Software" means the contents of this package and any accompanying source
10
+ code, object code, or documentation, in any form.
11
+ "Licensor" means Classytic LLC, a limited liability company organized in the
12
+ United States.
13
+ "You" means the individual or legal entity exercising rights under this
14
+ License.
15
+ "Evaluation Use" means use for evaluation, development, testing,
16
+ experimentation, or internal non-commercial purposes only.
17
+ "Production Use" means any use of the Software that is live, commercial,
18
+ revenue-generating, or customer-facing, or any use other than Evaluation Use.
19
+ "Commercial License" means a separate written agreement executed with
20
+ Licensor that grants Production Use rights.
21
+
22
+ 2. OWNERSHIP
23
+ The Software is licensed, not sold. Licensor retains all right, title, and
24
+ interest in and to the Software, including all intellectual property rights.
25
+ All rights not expressly granted in this License are reserved by Licensor.
26
+
27
+ 3. EVALUATION GRANT
28
+ Subject to Your compliance with this License, Licensor grants You a
29
+ worldwide, royalty-free, non-exclusive, non-transferable, revocable license
30
+ to download, install, run, and modify the Software solely for Evaluation Use.
31
+
32
+ 4. PRODUCTION USE REQUIRES A COMMERCIAL LICENSE
33
+ Production Use of the Software is NOT permitted under this License and
34
+ requires a Commercial License from Licensor. A Commercial License may be
35
+ granted at Licensor's discretion, with or without a fee, and may confer
36
+ perpetual, irrevocable, and transferable Production Use rights as set out in
37
+ that agreement. Contact licensing@classytic.com to obtain one.
38
+
39
+ 5. RESTRICTIONS
40
+ You may not:
41
+ (a) make any Production Use of the Software without a Commercial License;
42
+ (b) redistribute, resell, rent, sublicense, or otherwise make the Software
43
+ (in whole or in part, original or modified) available to third parties as
44
+ a stand-alone product, framework, library, or hosted/managed service that
45
+ competes with the Software or with Licensor;
46
+ (c) remove, obscure, or alter any copyright, license, or attribution notice.
47
+
48
+ 6. FEEDBACK AND CONTRIBUTIONS
49
+ Any feedback, suggestions, or contributions You provide relating to the
50
+ Software may be used by Licensor for any purpose without obligation to You.
51
+
52
+ 7. TERMINATION
53
+ This License and the Evaluation Grant terminate automatically if You breach
54
+ any term. Upon termination You must cease all use of the Software and destroy
55
+ all copies in Your possession. Rights under a Commercial License are governed
56
+ by that agreement's own terms and survive termination of this License to the
57
+ extent stated there.
58
+
59
+ 8. DISCLAIMER OF WARRANTY
60
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
61
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
62
+ FITNESS FOR A PARTICULAR PURPOSE, AND NONINFRINGEMENT.
63
+
64
+ 9. LIMITATION OF LIABILITY
65
+ TO THE MAXIMUM EXTENT PERMITTED BY LAW, IN NO EVENT SHALL LICENSOR BE LIABLE
66
+ FOR ANY CLAIM, DAMAGES, OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT,
67
+ TORT, OR OTHERWISE, ARISING FROM, OUT OF, OR IN CONNECTION WITH THE SOFTWARE
68
+ OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
69
+
70
+ 10. GOVERNING LAW
71
+ This License is governed by the laws of the State of Delaware, United States,
72
+ without regard to its conflict-of-laws principles. (Adjust to Your LLC's state
73
+ of formation.)
74
+
75
+ For commercial licensing, contact: licensing@classytic.com
@@ -0,0 +1,12 @@
1
+ import { OperationContext } from "@classytic/primitives/context";
2
+ import { RetryPolicy } from "@classytic/repo-core/repository";
3
+ //#region src/context.d.ts
4
+ export interface WorkPeriodContext extends OperationContext {
5
+ organizationId: string;
6
+ actorId: string;
7
+ actorKind: 'user' | 'system' | 'service';
8
+ correlationId: string;
9
+ signal?: AbortSignal | undefined;
10
+ retryPolicy?: RetryPolicy | undefined;
11
+ }
12
+ //#endregion
@@ -0,0 +1,47 @@
1
+ import { WorkPeriodContext } from "./context.mjs";
2
+ import { WorkPeriodDocument } from "./model.mjs";
3
+ import { WorkPeriodRepository } from "./repository.mjs";
4
+ import { MultiTenantOptions, PluginType } from "@classytic/mongokit";
5
+ import { ResolvedTenantConfig, TenantConfig } from "@classytic/repo-core/tenant";
6
+ import { EventTransport } from "@classytic/primitives/events";
7
+ import { Connection, Model } from "mongoose";
8
+ import { OutboxStore } from "@classytic/primitives/outbox";
9
+ //#region src/engine.d.ts
10
+ export type WorkPeriodTenantOptions = TenantConfig & Pick<MultiTenantOptions, 'skipOperations' | 'skipWhen' | 'resolveContext' | 'allowDataInjection' | 'onMismatch'>;
11
+ export interface WorkPeriodShape {
12
+ tenant?: WorkPeriodTenantOptions | boolean | undefined;
13
+ autoIndex?: boolean | undefined;
14
+ collectionPrefix?: string | undefined;
15
+ forceRecreate?: boolean | undefined;
16
+ }
17
+ export interface WorkPeriodRuntime {
18
+ eventTransport?: EventTransport | undefined;
19
+ outbox?: OutboxStore | undefined;
20
+ repositoryPlugins?: PluginType[] | undefined;
21
+ logger?: {
22
+ error(message: string, ...args: unknown[]): void;
23
+ } | undefined;
24
+ }
25
+ export interface WorkPeriodEngine {
26
+ readonly config: Readonly<{
27
+ tenant: ResolvedTenantConfig;
28
+ hasOutbox: boolean;
29
+ }>;
30
+ readonly models: Readonly<{
31
+ WorkPeriod: Model<WorkPeriodDocument>;
32
+ }>;
33
+ readonly repositories: Readonly<{
34
+ workPeriod: WorkPeriodRepository;
35
+ }>;
36
+ readonly events: EventTransport;
37
+ readonly outbox: OutboxStore | undefined;
38
+ syncIndexes(): Promise<void>;
39
+ close(): Promise<void>;
40
+ }
41
+ export interface WorkPeriodBlueprint {
42
+ readonly id: 'work-period';
43
+ readonly modelNames: readonly string[];
44
+ bind(connection: Connection, runtime?: WorkPeriodRuntime): WorkPeriodEngine;
45
+ }
46
+ export declare function defineWorkPeriod(shape?: WorkPeriodShape): WorkPeriodBlueprint;
47
+ //#endregion
@@ -0,0 +1,77 @@
1
+ import { WorkPeriodCapabilityError } from "./errors.mjs";
2
+ import { InProcessWorkPeriodBus } from "./events.mjs";
3
+ import { injectTenantField } from "./inject-tenant.mjs";
4
+ import { buildWorkPeriodSchema } from "./model.mjs";
5
+ import { WorkPeriodRepository } from "./repository.mjs";
6
+ import { defineModels, multiTenantPlugin } from "@classytic/mongokit";
7
+ import { resolveTenantConfig } from "@classytic/repo-core/tenant";
8
+ //#region src/engine.ts
9
+ function defineWorkPeriod(shape = {}) {
10
+ const tenant = resolveTenantConfig(shape.tenant);
11
+ const modelsBlueprint = defineModels({
12
+ models: [{
13
+ name: "WorkPeriod",
14
+ collection: `${shape.collectionPrefix ?? ""}work_periods`,
15
+ schema: () => {
16
+ const schema = buildWorkPeriodSchema();
17
+ injectTenantField(schema, tenant);
18
+ if (shape.autoIndex !== void 0) schema.set("autoIndex", shape.autoIndex);
19
+ return schema;
20
+ },
21
+ existing: shape.forceRecreate ? {
22
+ mode: "replace",
23
+ environment: "test"
24
+ } : { mode: "throw" }
25
+ }],
26
+ assemble: (models) => ({ WorkPeriod: models.get("WorkPeriod") })
27
+ });
28
+ return {
29
+ id: "work-period",
30
+ modelNames: modelsBlueprint.modelNames,
31
+ bind(connection, runtime = {}) {
32
+ if (runtime.outbox && runtime.outbox.transactionalSave !== true) throw new WorkPeriodCapabilityError(["outbox.transactionalSave"]);
33
+ const models = modelsBlueprint.bind(connection);
34
+ const logger = runtime.logger ?? console;
35
+ const ownsTransport = runtime.eventTransport === void 0;
36
+ const events = runtime.eventTransport ?? new InProcessWorkPeriodBus();
37
+ const tenantPlugins = tenant.enabled && tenant.strategy === "field" ? [multiTenantPlugin({
38
+ tenantField: tenant.tenantField,
39
+ fieldType: tenant.fieldType,
40
+ contextKey: tenant.contextKey,
41
+ required: tenant.required,
42
+ ...typeof shape.tenant === "object" && shape.tenant.skipOperations ? { skipOperations: shape.tenant.skipOperations } : {},
43
+ ...typeof shape.tenant === "object" && shape.tenant.skipWhen ? { skipWhen: shape.tenant.skipWhen } : {},
44
+ ...typeof shape.tenant === "object" && shape.tenant.resolveContext ? { resolveContext: shape.tenant.resolveContext } : {},
45
+ ...typeof shape.tenant === "object" && shape.tenant.allowDataInjection !== void 0 ? { allowDataInjection: shape.tenant.allowDataInjection } : {},
46
+ ...typeof shape.tenant === "object" && shape.tenant.onMismatch ? { onMismatch: shape.tenant.onMismatch } : {}
47
+ })] : [];
48
+ const workPeriod = new WorkPeriodRepository({
49
+ model: models.WorkPeriod,
50
+ plugins: [...tenantPlugins, ...runtime.repositoryPlugins ?? []],
51
+ eventTransport: events,
52
+ outbox: runtime.outbox,
53
+ logger
54
+ });
55
+ if (runtime.outbox && workPeriod.capabilities.transactions !== true) throw new WorkPeriodCapabilityError(["transactions"]);
56
+ const engine = {
57
+ config: Object.freeze({
58
+ tenant,
59
+ hasOutbox: runtime.outbox !== void 0
60
+ }),
61
+ models: Object.freeze(models),
62
+ repositories: Object.freeze({ workPeriod }),
63
+ events,
64
+ outbox: runtime.outbox,
65
+ async syncIndexes() {
66
+ await models.WorkPeriod.syncIndexes();
67
+ },
68
+ async close() {
69
+ if (ownsTransport) await events.close?.();
70
+ }
71
+ };
72
+ return Object.freeze(engine);
73
+ }
74
+ };
75
+ }
76
+ //#endregion
77
+ export { defineWorkPeriod };
@@ -0,0 +1,27 @@
1
+ import { HttpError } from "@classytic/repo-core/errors";
2
+ //#region src/errors.d.ts
3
+ export declare class WorkPeriodError extends Error implements HttpError {
4
+ readonly code: string;
5
+ readonly status: number;
6
+ constructor(message: string, code: string, status: number);
7
+ }
8
+ export declare class WorkPeriodNotFoundError extends WorkPeriodError {
9
+ constructor(id: string);
10
+ }
11
+ export declare class InvalidWorkPeriodTransitionError extends WorkPeriodError {
12
+ constructor(from: string, to: string);
13
+ }
14
+ /** The period changed after it was read; reload and retry. */
15
+ export declare class WorkPeriodConcurrencyError extends WorkPeriodError {
16
+ constructor(id: string);
17
+ }
18
+ export declare class WorkPeriodApprovalError extends WorkPeriodError {
19
+ constructor();
20
+ }
21
+ export declare class DuplicateWorkPeriodError extends WorkPeriodError {
22
+ constructor(subjectModel: string, subjectRef: string);
23
+ }
24
+ export declare class WorkPeriodCapabilityError extends WorkPeriodError {
25
+ constructor(missing: readonly string[]);
26
+ }
27
+ //#endregion
@@ -0,0 +1,44 @@
1
+ //#region src/errors.ts
2
+ var WorkPeriodError = class extends Error {
3
+ code;
4
+ status;
5
+ constructor(message, code, status) {
6
+ super(message);
7
+ this.code = code;
8
+ this.status = status;
9
+ this.name = this.constructor.name;
10
+ }
11
+ };
12
+ var WorkPeriodNotFoundError = class extends WorkPeriodError {
13
+ constructor(id) {
14
+ super(`Work period ${id} not found`, "work_period.not_found", 404);
15
+ }
16
+ };
17
+ var InvalidWorkPeriodTransitionError = class extends WorkPeriodError {
18
+ constructor(from, to) {
19
+ super(`Work period cannot transition from ${from} to ${to}`, "work_period.invalid_transition", 409);
20
+ }
21
+ };
22
+ /** The period changed after it was read; reload and retry. */
23
+ var WorkPeriodConcurrencyError = class extends WorkPeriodError {
24
+ constructor(id) {
25
+ super(`Work period ${id} was modified concurrently`, "work_period.concurrent_modification", 409);
26
+ }
27
+ };
28
+ var WorkPeriodApprovalError = class extends WorkPeriodError {
29
+ constructor() {
30
+ super("Work period approval chain is not approved", "work_period.approval_incomplete", 422);
31
+ }
32
+ };
33
+ var DuplicateWorkPeriodError = class extends WorkPeriodError {
34
+ constructor(subjectModel, subjectRef) {
35
+ super(`A work period already exists for ${subjectModel}:${subjectRef} and that range`, "work_period.duplicate", 409);
36
+ }
37
+ };
38
+ var WorkPeriodCapabilityError = class extends WorkPeriodError {
39
+ constructor(missing) {
40
+ super(`Work period backend is missing: ${missing.join(", ")}`, "work_period.invalid_configuration", 500);
41
+ }
42
+ };
43
+ //#endregion
44
+ export { DuplicateWorkPeriodError, InvalidWorkPeriodTransitionError, WorkPeriodApprovalError, WorkPeriodCapabilityError, WorkPeriodConcurrencyError, WorkPeriodError, WorkPeriodNotFoundError };
@@ -0,0 +1,39 @@
1
+ import { WorkPeriodEventName } from "./events.mjs";
2
+ import { DomainEvent, EventMeta } from "@classytic/primitives/events";
3
+ import { z } from "zod";
4
+ //#region src/event-catalog.d.ts
5
+ /** JSON-Schema object produced by `z.toJSONSchema` — what arc's registry consumes. */
6
+ export type WorkPeriodEventSchema = Record<string, unknown>;
7
+ export declare const workPeriodEventPayloadSchema: z.ZodObject<{
8
+ workPeriodId: z.ZodString;
9
+ organizationId: z.ZodString;
10
+ subjectRef: z.ZodString;
11
+ subjectModel: z.ZodString;
12
+ status: z.ZodEnum<{
13
+ approved: "approved";
14
+ locked: "locked";
15
+ open: "open";
16
+ rejected: "rejected";
17
+ submitted: "submitted";
18
+ }>;
19
+ factsVersion: z.ZodNumber;
20
+ }, z.core.$strip>;
21
+ export type WorkPeriodEventPayload = z.infer<typeof workPeriodEventPayloadSchema>;
22
+ /** Structurally identical to arc's `EventDefinitionOutput` — do NOT import arc. */
23
+ export interface WorkPeriodEventDefinition {
24
+ name: WorkPeriodEventName;
25
+ version: number;
26
+ description: string;
27
+ zodSchema: typeof workPeriodEventPayloadSchema;
28
+ schema: WorkPeriodEventSchema;
29
+ create(payload: WorkPeriodEventPayload, meta?: Partial<EventMeta>): DomainEvent<WorkPeriodEventPayload>;
30
+ }
31
+ export declare const WorkPeriodCreated: WorkPeriodEventDefinition;
32
+ export declare const WorkPeriodReconciled: WorkPeriodEventDefinition;
33
+ export declare const WorkPeriodSubmitted: WorkPeriodEventDefinition;
34
+ export declare const WorkPeriodApproved: WorkPeriodEventDefinition;
35
+ export declare const WorkPeriodRejected: WorkPeriodEventDefinition;
36
+ export declare const WorkPeriodReopened: WorkPeriodEventDefinition;
37
+ export declare const WorkPeriodLocked: WorkPeriodEventDefinition;
38
+ export declare const workPeriodEventDefinitions: ReadonlyArray<WorkPeriodEventDefinition>;
39
+ //#endregion
@@ -0,0 +1,54 @@
1
+ import { WORK_PERIOD_EVENTS } from "./events.mjs";
2
+ import { WORK_PERIOD_STATUS_VALUES } from "./model.mjs";
3
+ import { createEvent } from "@classytic/primitives/events";
4
+ import { z } from "zod";
5
+ //#region src/event-catalog.ts
6
+ /**
7
+ * Zod-source event catalog (PACKAGE_RULES rule 18) — one definition per `WORK_PERIOD_EVENTS`
8
+ * name. Hosts register them with arc's `EventRegistry`; the shape is structurally arc's
9
+ * `EventDefinitionOutput`, with no arc import. Every lifecycle event carries the same payload.
10
+ */
11
+ const workPeriodEventPayloadSchema = z.object({
12
+ workPeriodId: z.string(),
13
+ organizationId: z.string(),
14
+ subjectRef: z.string(),
15
+ subjectModel: z.string(),
16
+ status: z.enum(WORK_PERIOD_STATUS_VALUES),
17
+ factsVersion: z.number().int().min(1)
18
+ });
19
+ const jsonSchema = z.toJSONSchema(workPeriodEventPayloadSchema);
20
+ function defineWorkPeriodEvent(name, description) {
21
+ return {
22
+ name,
23
+ version: 1,
24
+ description,
25
+ zodSchema: workPeriodEventPayloadSchema,
26
+ schema: jsonSchema,
27
+ create(payload, meta) {
28
+ return createEvent(name, payload, {
29
+ resource: "work-period",
30
+ source: "work-period",
31
+ ...meta
32
+ });
33
+ }
34
+ };
35
+ }
36
+ const WorkPeriodCreated = defineWorkPeriodEvent(WORK_PERIOD_EVENTS.CREATED, "createPeriod() opened a period.");
37
+ const WorkPeriodReconciled = defineWorkPeriodEvent(WORK_PERIOD_EVENTS.RECONCILED, "reconcile() replaced the facts of an open period and bumped factsVersion.");
38
+ const WorkPeriodSubmitted = defineWorkPeriodEvent(WORK_PERIOD_EVENTS.SUBMITTED, "submit() moved a period open → submitted with its approval chain.");
39
+ const WorkPeriodApproved = defineWorkPeriodEvent(WORK_PERIOD_EVENTS.APPROVED, "approve() moved a fully approved period submitted → approved.");
40
+ const WorkPeriodRejected = defineWorkPeriodEvent(WORK_PERIOD_EVENTS.REJECTED, "reject() moved a period submitted → rejected.");
41
+ const WorkPeriodReopened = defineWorkPeriodEvent(WORK_PERIOD_EVENTS.REOPENED, "reopen() moved a period rejected → open and cleared its approval state.");
42
+ const WorkPeriodLocked = defineWorkPeriodEvent(WORK_PERIOD_EVENTS.LOCKED, "lock() froze an approved period as payroll facts.");
43
+ const catalog = {
44
+ [WORK_PERIOD_EVENTS.CREATED]: WorkPeriodCreated,
45
+ [WORK_PERIOD_EVENTS.RECONCILED]: WorkPeriodReconciled,
46
+ [WORK_PERIOD_EVENTS.SUBMITTED]: WorkPeriodSubmitted,
47
+ [WORK_PERIOD_EVENTS.APPROVED]: WorkPeriodApproved,
48
+ [WORK_PERIOD_EVENTS.REJECTED]: WorkPeriodRejected,
49
+ [WORK_PERIOD_EVENTS.REOPENED]: WorkPeriodReopened,
50
+ [WORK_PERIOD_EVENTS.LOCKED]: WorkPeriodLocked
51
+ };
52
+ const workPeriodEventDefinitions = Object.values(catalog);
53
+ //#endregion
54
+ export { WorkPeriodApproved, WorkPeriodCreated, WorkPeriodLocked, WorkPeriodReconciled, WorkPeriodRejected, WorkPeriodReopened, WorkPeriodSubmitted, workPeriodEventDefinitions, workPeriodEventPayloadSchema };
@@ -0,0 +1,30 @@
1
+ import "./context.mjs";
2
+ import "./event-catalog.mjs";
3
+ import { DomainEvent, EventHandler, EventTransport } from "@classytic/primitives/events";
4
+ import { OutboxStore } from "@classytic/primitives/outbox";
5
+ //#region src/events.d.ts
6
+ export declare const WORK_PERIOD_EVENTS: {
7
+ readonly CREATED: 'work-period:created';
8
+ readonly RECONCILED: 'work-period:reconciled';
9
+ readonly SUBMITTED: 'work-period:submitted';
10
+ readonly APPROVED: 'work-period:approved';
11
+ readonly REJECTED: 'work-period:rejected';
12
+ readonly REOPENED: 'work-period:reopened';
13
+ readonly LOCKED: 'work-period:locked';
14
+ };
15
+ export type WorkPeriodEventName = (typeof WORK_PERIOD_EVENTS)[keyof typeof WORK_PERIOD_EVENTS];
16
+ export interface EventChannels {
17
+ eventTransport?: EventTransport | undefined;
18
+ outbox?: OutboxStore | undefined;
19
+ logger: {
20
+ error(message: string, ...args: unknown[]): void;
21
+ };
22
+ }
23
+ export declare class InProcessWorkPeriodBus implements EventTransport {
24
+ readonly name = "in-process-work-period";
25
+ private readonly handlers;
26
+ publish(event: DomainEvent): Promise<void>;
27
+ subscribe(pattern: string, handler: EventHandler): Promise<() => void>;
28
+ close(): Promise<void>;
29
+ }
30
+ //#endregion
@@ -0,0 +1,51 @@
1
+ import { createScopedEvent, matchEventPattern } from "@classytic/primitives/events";
2
+ //#region src/events.ts
3
+ const WORK_PERIOD_EVENTS = {
4
+ CREATED: "work-period:created",
5
+ RECONCILED: "work-period:reconciled",
6
+ SUBMITTED: "work-period:submitted",
7
+ APPROVED: "work-period:approved",
8
+ REJECTED: "work-period:rejected",
9
+ REOPENED: "work-period:reopened",
10
+ LOCKED: "work-period:locked"
11
+ };
12
+ async function emitWorkPeriodEvent(channels, type, payload, ctx, resourceId) {
13
+ if (ctx.session && !channels.outbox) throw new Error("[work-period] a caller-owned session requires a transactional outbox");
14
+ const event = createScopedEvent("work-period", type, payload, ctx, {
15
+ resource: "work-period",
16
+ resourceId
17
+ });
18
+ if (channels.outbox) {
19
+ const options = {};
20
+ if (ctx.session) options.session = ctx.session;
21
+ await channels.outbox.save(event, options);
22
+ }
23
+ if (channels.eventTransport && !ctx.session) try {
24
+ await channels.eventTransport.publish(event);
25
+ } catch (error) {
26
+ channels.logger.error(`[work-period] publish failed for ${type}:`, error);
27
+ }
28
+ }
29
+ var InProcessWorkPeriodBus = class {
30
+ name = "in-process-work-period";
31
+ handlers = /* @__PURE__ */ new Map();
32
+ async publish(event) {
33
+ for (const [pattern, handlers] of this.handlers) {
34
+ if (!matchEventPattern(pattern, event.type)) continue;
35
+ for (const handler of handlers) await handler(event);
36
+ }
37
+ }
38
+ async subscribe(pattern, handler) {
39
+ const handlers = this.handlers.get(pattern) ?? /* @__PURE__ */ new Set();
40
+ handlers.add(handler);
41
+ this.handlers.set(pattern, handlers);
42
+ return () => {
43
+ handlers.delete(handler);
44
+ };
45
+ }
46
+ async close() {
47
+ this.handlers.clear();
48
+ }
49
+ };
50
+ //#endregion
51
+ export { InProcessWorkPeriodBus, WORK_PERIOD_EVENTS, emitWorkPeriodEvent };
@@ -0,0 +1,8 @@
1
+ import { WorkPeriodContext } from "./context.mjs";
2
+ import { WORK_PERIOD_STATUS_VALUES, WorkPeriodAttendanceFacts, WorkPeriodDocument, WorkPeriodLeaveFacts, WorkPeriodPolicyRef, WorkPeriodStatus, buildWorkPeriodSchema } from "./model.mjs";
3
+ import { WorkPeriodApproved, WorkPeriodCreated, WorkPeriodEventDefinition, WorkPeriodEventPayload, WorkPeriodEventSchema, WorkPeriodLocked, WorkPeriodReconciled, WorkPeriodRejected, WorkPeriodReopened, WorkPeriodSubmitted, workPeriodEventDefinitions, workPeriodEventPayloadSchema } from "./event-catalog.mjs";
4
+ import { InProcessWorkPeriodBus, WORK_PERIOD_EVENTS, WorkPeriodEventName } from "./events.mjs";
5
+ import { CreateWorkPeriodInput, ReconcileWorkPeriodInput, WorkPeriodRepository, WorkPeriodRepositoryConfig } from "./repository.mjs";
6
+ import { WorkPeriodBlueprint, WorkPeriodEngine, WorkPeriodRuntime, WorkPeriodShape, defineWorkPeriod } from "./engine.mjs";
7
+ import { DuplicateWorkPeriodError, InvalidWorkPeriodTransitionError, WorkPeriodApprovalError, WorkPeriodCapabilityError, WorkPeriodConcurrencyError, WorkPeriodError, WorkPeriodNotFoundError } from "./errors.mjs";
8
+ export { type CreateWorkPeriodInput, DuplicateWorkPeriodError, InProcessWorkPeriodBus, InvalidWorkPeriodTransitionError, type ReconcileWorkPeriodInput, WORK_PERIOD_EVENTS, WORK_PERIOD_STATUS_VALUES, WorkPeriodApprovalError, WorkPeriodApproved, type WorkPeriodAttendanceFacts, type WorkPeriodBlueprint, WorkPeriodCapabilityError, WorkPeriodConcurrencyError, type WorkPeriodContext, WorkPeriodCreated, type WorkPeriodDocument, type WorkPeriodEngine, WorkPeriodError, type WorkPeriodEventDefinition, type WorkPeriodEventName, type WorkPeriodEventPayload, type WorkPeriodEventSchema, type WorkPeriodLeaveFacts, WorkPeriodLocked, WorkPeriodNotFoundError, type WorkPeriodPolicyRef, WorkPeriodReconciled, WorkPeriodRejected, WorkPeriodReopened, WorkPeriodRepository, type WorkPeriodRepositoryConfig, type WorkPeriodRuntime, type WorkPeriodShape, type WorkPeriodStatus, WorkPeriodSubmitted, buildWorkPeriodSchema, defineWorkPeriod, workPeriodEventDefinitions, workPeriodEventPayloadSchema };
package/dist/index.mjs ADDED
@@ -0,0 +1,7 @@
1
+ import { DuplicateWorkPeriodError, InvalidWorkPeriodTransitionError, WorkPeriodApprovalError, WorkPeriodCapabilityError, WorkPeriodConcurrencyError, WorkPeriodError, WorkPeriodNotFoundError } from "./errors.mjs";
2
+ import { InProcessWorkPeriodBus, WORK_PERIOD_EVENTS } from "./events.mjs";
3
+ import { WORK_PERIOD_STATUS_VALUES, buildWorkPeriodSchema } from "./model.mjs";
4
+ import { WorkPeriodRepository } from "./repository.mjs";
5
+ import { defineWorkPeriod } from "./engine.mjs";
6
+ import { WorkPeriodApproved, WorkPeriodCreated, WorkPeriodLocked, WorkPeriodReconciled, WorkPeriodRejected, WorkPeriodReopened, WorkPeriodSubmitted, workPeriodEventDefinitions, workPeriodEventPayloadSchema } from "./event-catalog.mjs";
7
+ export { DuplicateWorkPeriodError, InProcessWorkPeriodBus, InvalidWorkPeriodTransitionError, WORK_PERIOD_EVENTS, WORK_PERIOD_STATUS_VALUES, WorkPeriodApprovalError, WorkPeriodApproved, WorkPeriodCapabilityError, WorkPeriodConcurrencyError, WorkPeriodCreated, WorkPeriodError, WorkPeriodLocked, WorkPeriodNotFoundError, WorkPeriodReconciled, WorkPeriodRejected, WorkPeriodReopened, WorkPeriodRepository, WorkPeriodSubmitted, buildWorkPeriodSchema, defineWorkPeriod, workPeriodEventDefinitions, workPeriodEventPayloadSchema };
@@ -0,0 +1,21 @@
1
+ import mongoose from "mongoose";
2
+ //#region src/inject-tenant.ts
3
+ function injectTenantField(schema, tenant) {
4
+ schema.add({ [tenant.tenantField]: {
5
+ type: tenant.fieldType === "objectId" ? mongoose.Schema.Types.ObjectId : String,
6
+ ...tenant.enabled && tenant.required ? { required: true } : {},
7
+ ...tenant.fieldType === "objectId" && tenant.ref ? { ref: tenant.ref } : {}
8
+ } });
9
+ if (!tenant.enabled || tenant.strategy !== "field") return;
10
+ const indexes = schema._indexes;
11
+ for (const index of indexes ?? []) {
12
+ if (index[0][tenant.tenantField] !== void 0) continue;
13
+ index[0] = {
14
+ [tenant.tenantField]: 1,
15
+ ...index[0]
16
+ };
17
+ }
18
+ if (!(indexes ?? []).some(([fields]) => Object.keys(fields)[0] === tenant.tenantField)) schema.index({ [tenant.tenantField]: 1 });
19
+ }
20
+ //#endregion
21
+ export { injectTenantField };
@@ -0,0 +1,56 @@
1
+ import { Document, Schema, Types } from "mongoose";
2
+ import { ApprovalChain } from "@classytic/primitives/approval";
3
+ import { ExternalRef } from "@classytic/primitives/reference";
4
+ //#region src/model.d.ts
5
+ export declare const WORK_PERIOD_STATUS_VALUES: readonly ['open', 'submitted', 'approved', 'rejected', 'locked'];
6
+ export type WorkPeriodStatus = (typeof WORK_PERIOD_STATUS_VALUES)[number];
7
+ export interface WorkPeriodAttendanceFacts {
8
+ workedMinutes: number;
9
+ scheduledMinutes: number;
10
+ breakMinutes: number;
11
+ absentCount?: number;
12
+ overtimeMinutes?: number;
13
+ }
14
+ export interface WorkPeriodLeaveFacts {
15
+ approvedByType: Readonly<Record<string, number>>;
16
+ totalApprovedDays: number;
17
+ unpaidDays: number;
18
+ }
19
+ export interface WorkPeriodPolicyRef {
20
+ source: ExternalRef;
21
+ version: string;
22
+ }
23
+ export interface WorkPeriodDocument extends Document {
24
+ _id: Types.ObjectId;
25
+ organizationId: Types.ObjectId | string;
26
+ subjectRef: string;
27
+ subjectModel: string;
28
+ range: {
29
+ start: Date;
30
+ end: Date;
31
+ };
32
+ status: WorkPeriodStatus;
33
+ attendance?: WorkPeriodAttendanceFacts;
34
+ leave?: WorkPeriodLeaveFacts;
35
+ values?: Record<string, unknown>;
36
+ sourceRefs: ExternalRef[];
37
+ policyRefs: WorkPeriodPolicyRef[];
38
+ factsVersion: number;
39
+ approvals?: ApprovalChain;
40
+ approvalPolicyId?: string | null;
41
+ approvalPolicyVersion?: number | null;
42
+ submittedAt?: Date;
43
+ submittedBy?: string;
44
+ approvedAt?: Date;
45
+ approvedBy?: string;
46
+ rejectedAt?: Date;
47
+ rejectedBy?: string;
48
+ rejectionReason?: string;
49
+ lockedAt?: Date;
50
+ lockedBy?: string;
51
+ createdAt: Date;
52
+ updatedAt: Date;
53
+ version: number;
54
+ }
55
+ export declare function buildWorkPeriodSchema(): Schema<WorkPeriodDocument>;
56
+ //#endregion
package/dist/model.mjs ADDED
@@ -0,0 +1,161 @@
1
+ import { Schema } from "mongoose";
2
+ //#region src/model.ts
3
+ const WORK_PERIOD_STATUS_VALUES = [
4
+ "open",
5
+ "submitted",
6
+ "approved",
7
+ "rejected",
8
+ "locked"
9
+ ];
10
+ const externalRefSchema = new Schema({
11
+ sourceId: {
12
+ type: String,
13
+ required: true,
14
+ trim: true
15
+ },
16
+ sourceModel: {
17
+ type: String,
18
+ required: true,
19
+ trim: true
20
+ }
21
+ }, { _id: false });
22
+ function buildWorkPeriodSchema() {
23
+ const schema = new Schema({
24
+ subjectRef: {
25
+ type: String,
26
+ required: true,
27
+ trim: true
28
+ },
29
+ subjectModel: {
30
+ type: String,
31
+ required: true,
32
+ trim: true
33
+ },
34
+ range: {
35
+ start: {
36
+ type: Date,
37
+ required: true
38
+ },
39
+ end: {
40
+ type: Date,
41
+ required: true
42
+ }
43
+ },
44
+ status: {
45
+ type: String,
46
+ enum: WORK_PERIOD_STATUS_VALUES,
47
+ required: true,
48
+ default: "open"
49
+ },
50
+ attendance: { type: new Schema({
51
+ workedMinutes: {
52
+ type: Number,
53
+ required: true,
54
+ min: 0
55
+ },
56
+ scheduledMinutes: {
57
+ type: Number,
58
+ required: true,
59
+ min: 0
60
+ },
61
+ breakMinutes: {
62
+ type: Number,
63
+ required: true,
64
+ min: 0
65
+ },
66
+ absentCount: {
67
+ type: Number,
68
+ min: 0
69
+ },
70
+ overtimeMinutes: {
71
+ type: Number,
72
+ min: 0
73
+ }
74
+ }, { _id: false }) },
75
+ leave: { type: new Schema({
76
+ approvedByType: {
77
+ type: Schema.Types.Mixed,
78
+ required: true
79
+ },
80
+ totalApprovedDays: {
81
+ type: Number,
82
+ required: true,
83
+ min: 0
84
+ },
85
+ unpaidDays: {
86
+ type: Number,
87
+ required: true,
88
+ min: 0
89
+ }
90
+ }, { _id: false }) },
91
+ values: { type: Schema.Types.Mixed },
92
+ sourceRefs: {
93
+ type: [externalRefSchema],
94
+ required: true,
95
+ default: []
96
+ },
97
+ policyRefs: {
98
+ type: [new Schema({
99
+ source: {
100
+ type: externalRefSchema,
101
+ required: true
102
+ },
103
+ version: {
104
+ type: String,
105
+ required: true
106
+ }
107
+ }, { _id: false })],
108
+ required: true,
109
+ default: []
110
+ },
111
+ factsVersion: {
112
+ type: Number,
113
+ required: true,
114
+ min: 1,
115
+ default: 1
116
+ },
117
+ approvals: { type: Schema.Types.Mixed },
118
+ approvalPolicyId: {
119
+ type: String,
120
+ default: null
121
+ },
122
+ approvalPolicyVersion: {
123
+ type: Number,
124
+ default: null
125
+ },
126
+ submittedAt: Date,
127
+ submittedBy: String,
128
+ approvedAt: Date,
129
+ approvedBy: String,
130
+ rejectedAt: Date,
131
+ rejectedBy: String,
132
+ rejectionReason: String,
133
+ lockedAt: Date,
134
+ lockedBy: String,
135
+ version: {
136
+ type: Number,
137
+ required: true,
138
+ default: 0
139
+ }
140
+ }, {
141
+ timestamps: true,
142
+ minimize: false,
143
+ optimisticConcurrency: true
144
+ });
145
+ schema.index({
146
+ subjectModel: 1,
147
+ subjectRef: 1,
148
+ "range.start": 1,
149
+ "range.end": 1
150
+ }, {
151
+ unique: true,
152
+ name: "work_period_unique_subject_range"
153
+ });
154
+ schema.index({
155
+ status: 1,
156
+ "range.end": -1
157
+ });
158
+ return schema;
159
+ }
160
+ //#endregion
161
+ export { WORK_PERIOD_STATUS_VALUES, buildWorkPeriodSchema };
@@ -0,0 +1,46 @@
1
+ import { WorkPeriodContext } from "./context.mjs";
2
+ import { WorkPeriodAttendanceFacts, WorkPeriodDocument, WorkPeriodLeaveFacts, WorkPeriodPolicyRef } from "./model.mjs";
3
+ import { EventChannels } from "./events.mjs";
4
+ import { PluginType, Repository } from "@classytic/mongokit";
5
+ import { Model } from "mongoose";
6
+ import { ApprovalChain } from "@classytic/primitives/approval";
7
+ import { ExternalRef } from "@classytic/primitives/reference";
8
+ import { DateRange } from "@classytic/primitives/period";
9
+ //#region src/repository.d.ts
10
+ export interface CreateWorkPeriodInput {
11
+ subjectRef: string;
12
+ subjectModel: string;
13
+ range: DateRange;
14
+ attendance?: WorkPeriodAttendanceFacts | undefined;
15
+ leave?: WorkPeriodLeaveFacts | undefined;
16
+ values?: Record<string, unknown> | undefined;
17
+ sourceRefs: readonly ExternalRef[];
18
+ policyRefs?: readonly WorkPeriodPolicyRef[] | undefined;
19
+ }
20
+ export type ReconcileWorkPeriodInput = Pick<CreateWorkPeriodInput, 'attendance' | 'leave' | 'values' | 'sourceRefs' | 'policyRefs'>;
21
+ export interface WorkPeriodRepositoryConfig extends EventChannels {
22
+ model: Model<WorkPeriodDocument>;
23
+ plugins?: PluginType[] | undefined;
24
+ }
25
+ export declare class WorkPeriodRepository extends Repository<WorkPeriodDocument> {
26
+ private readonly channels;
27
+ constructor(config: WorkPeriodRepositoryConfig);
28
+ createPeriod(input: CreateWorkPeriodInput, ctx: WorkPeriodContext): Promise<WorkPeriodDocument>;
29
+ submit(id: string, approvals: ApprovalChain, ctx: WorkPeriodContext): Promise<WorkPeriodDocument>;
30
+ reconcile(id: string, input: ReconcileWorkPeriodInput, ctx: WorkPeriodContext): Promise<WorkPeriodDocument>;
31
+ updateApprovals(id: string, approvals: ApprovalChain, ctx: WorkPeriodContext): Promise<WorkPeriodDocument>;
32
+ approve(id: string, ctx: WorkPeriodContext): Promise<WorkPeriodDocument>;
33
+ reject(id: string, reason: string, ctx: WorkPeriodContext): Promise<WorkPeriodDocument>;
34
+ reopen(id: string, ctx: WorkPeriodContext): Promise<WorkPeriodDocument>;
35
+ lock(id: string, ctx: WorkPeriodContext): Promise<WorkPeriodDocument>;
36
+ findLocked(subjectRef: string, subjectModel: string, range: DateRange, ctx: WorkPeriodContext): Promise<WorkPeriodDocument | null>;
37
+ /**
38
+ * Write `update` only if the period is still at the status AND version that was read,
39
+ * moving it to `to`. Every write bumps `version`, so any change since the read (approvals,
40
+ * facts, a reject/reopen cycle) refuses the write instead of acting on a stale check.
41
+ */
42
+ private transition;
43
+ private load;
44
+ private emitDomain;
45
+ }
46
+ //#endregion
@@ -0,0 +1,223 @@
1
+ import { DuplicateWorkPeriodError, InvalidWorkPeriodTransitionError, WorkPeriodApprovalError, WorkPeriodConcurrencyError, WorkPeriodError, WorkPeriodNotFoundError } from "./errors.mjs";
2
+ import { WORK_PERIOD_EVENTS, emitWorkPeriodEvent } from "./events.mjs";
3
+ import { Repository, isDuplicateKeyError, withTransaction } from "@classytic/mongokit";
4
+ import { isApproved } from "@classytic/primitives/approval";
5
+ //#region src/repository.ts
6
+ var WorkPeriodRepository = class extends Repository {
7
+ channels;
8
+ constructor(config) {
9
+ super(config.model, config.plugins ?? [], { maxLimit: 200 });
10
+ this.channels = config;
11
+ }
12
+ async createPeriod(input, ctx) {
13
+ if (this.channels.outbox && !ctx.session) return withTransaction(this.Model.db, (session) => this.createPeriod(input, {
14
+ ...ctx,
15
+ session
16
+ }));
17
+ if (input.range.end.getTime() <= input.range.start.getTime()) throw new WorkPeriodError("Work period end must be after start", "work_period.invalid_range", 422);
18
+ if (input.sourceRefs.length === 0) throw new WorkPeriodError("Work period requires at least one source reference", "work_period.missing_source", 422);
19
+ try {
20
+ const created = await this.create({
21
+ organizationId: ctx.organizationId,
22
+ subjectRef: input.subjectRef,
23
+ subjectModel: input.subjectModel,
24
+ range: input.range,
25
+ status: "open",
26
+ ...input.attendance ? { attendance: input.attendance } : {},
27
+ ...input.leave ? { leave: input.leave } : {},
28
+ ...input.values ? { values: input.values } : {},
29
+ sourceRefs: [...input.sourceRefs],
30
+ policyRefs: [...input.policyRefs ?? []],
31
+ factsVersion: 1,
32
+ version: 0
33
+ }, repoOptions(ctx));
34
+ await this.emitDomain(WORK_PERIOD_EVENTS.CREATED, created, ctx);
35
+ return created;
36
+ } catch (error) {
37
+ if (isDuplicateKeyError(error)) throw new DuplicateWorkPeriodError(input.subjectModel, input.subjectRef);
38
+ throw error;
39
+ }
40
+ }
41
+ async submit(id, approvals, ctx) {
42
+ if (this.channels.outbox && !ctx.session) return withTransaction(this.Model.db, (session) => this.submit(id, approvals, {
43
+ ...ctx,
44
+ session
45
+ }));
46
+ const current = await this.load(id, ctx);
47
+ if (current.status !== "open") throw new InvalidWorkPeriodTransitionError(current.status, "submitted");
48
+ const updated = await this.transition(current, "submitted", { $set: {
49
+ approvals,
50
+ submittedAt: /* @__PURE__ */ new Date(),
51
+ submittedBy: ctx.actorId
52
+ } }, ctx);
53
+ await this.emitDomain(WORK_PERIOD_EVENTS.SUBMITTED, updated, ctx);
54
+ return updated;
55
+ }
56
+ async reconcile(id, input, ctx) {
57
+ if (this.channels.outbox && !ctx.session) return withTransaction(this.Model.db, (session) => this.reconcile(id, input, {
58
+ ...ctx,
59
+ session
60
+ }));
61
+ if (input.sourceRefs.length === 0) throw new WorkPeriodError("Work period requires at least one source reference", "work_period.missing_source", 422);
62
+ const current = await this.load(id, ctx);
63
+ if (current.status !== "open") throw new InvalidWorkPeriodTransitionError(current.status, "open");
64
+ const updated = await this.transition(current, "open", {
65
+ $set: {
66
+ sourceRefs: [...input.sourceRefs],
67
+ policyRefs: [...input.policyRefs ?? []],
68
+ ...input.attendance ? { attendance: input.attendance } : {},
69
+ ...input.leave ? { leave: input.leave } : {},
70
+ ...input.values ? { values: input.values } : {}
71
+ },
72
+ $unset: {
73
+ ...input.attendance ? {} : { attendance: 1 },
74
+ ...input.leave ? {} : { leave: 1 },
75
+ ...input.values ? {} : { values: 1 }
76
+ },
77
+ $inc: { factsVersion: 1 }
78
+ }, ctx);
79
+ await this.emitDomain(WORK_PERIOD_EVENTS.RECONCILED, updated, ctx);
80
+ return updated;
81
+ }
82
+ async updateApprovals(id, approvals, ctx) {
83
+ if (this.channels.outbox && !ctx.session) return withTransaction(this.Model.db, (session) => this.updateApprovals(id, approvals, {
84
+ ...ctx,
85
+ session
86
+ }));
87
+ const current = await this.load(id, ctx);
88
+ if (current.status !== "submitted") throw new InvalidWorkPeriodTransitionError(current.status, "submitted");
89
+ return this.transition(current, "submitted", { $set: { approvals } }, ctx);
90
+ }
91
+ async approve(id, ctx) {
92
+ if (this.channels.outbox && !ctx.session) return withTransaction(this.Model.db, (session) => this.approve(id, {
93
+ ...ctx,
94
+ session
95
+ }));
96
+ const current = await this.load(id, ctx);
97
+ if (current.status !== "submitted") throw new InvalidWorkPeriodTransitionError(current.status, "approved");
98
+ if (!current.approvals || !isApproved(current.approvals)) throw new WorkPeriodApprovalError();
99
+ const updated = await this.transition(current, "approved", { $set: {
100
+ approvedAt: /* @__PURE__ */ new Date(),
101
+ approvedBy: ctx.actorId
102
+ } }, ctx);
103
+ await this.emitDomain(WORK_PERIOD_EVENTS.APPROVED, updated, ctx);
104
+ return updated;
105
+ }
106
+ async reject(id, reason, ctx) {
107
+ if (this.channels.outbox && !ctx.session) return withTransaction(this.Model.db, (session) => this.reject(id, reason, {
108
+ ...ctx,
109
+ session
110
+ }));
111
+ const current = await this.load(id, ctx);
112
+ if (current.status !== "submitted") throw new InvalidWorkPeriodTransitionError(current.status, "rejected");
113
+ const updated = await this.transition(current, "rejected", { $set: {
114
+ rejectedAt: /* @__PURE__ */ new Date(),
115
+ rejectedBy: ctx.actorId,
116
+ rejectionReason: reason
117
+ } }, ctx);
118
+ await this.emitDomain(WORK_PERIOD_EVENTS.REJECTED, updated, ctx);
119
+ return updated;
120
+ }
121
+ async reopen(id, ctx) {
122
+ if (this.channels.outbox && !ctx.session) return withTransaction(this.Model.db, (session) => this.reopen(id, {
123
+ ...ctx,
124
+ session
125
+ }));
126
+ const current = await this.load(id, ctx);
127
+ if (current.status !== "rejected") throw new InvalidWorkPeriodTransitionError(current.status, "open");
128
+ const updated = await this.transition(current, "open", { $unset: {
129
+ approvals: 1,
130
+ submittedAt: 1,
131
+ submittedBy: 1,
132
+ rejectedAt: 1,
133
+ rejectedBy: 1,
134
+ rejectionReason: 1
135
+ } }, ctx);
136
+ await this.emitDomain(WORK_PERIOD_EVENTS.REOPENED, updated, ctx);
137
+ return updated;
138
+ }
139
+ async lock(id, ctx) {
140
+ if (this.channels.outbox && !ctx.session) return withTransaction(this.Model.db, (session) => this.lock(id, {
141
+ ...ctx,
142
+ session
143
+ }));
144
+ const current = await this.load(id, ctx);
145
+ if (current.status !== "approved") throw new InvalidWorkPeriodTransitionError(current.status, "locked");
146
+ const updated = await this.transition(current, "locked", { $set: {
147
+ lockedAt: /* @__PURE__ */ new Date(),
148
+ lockedBy: ctx.actorId
149
+ } }, ctx);
150
+ await this.emitDomain(WORK_PERIOD_EVENTS.LOCKED, updated, ctx);
151
+ return updated;
152
+ }
153
+ async findLocked(subjectRef, subjectModel, range, ctx) {
154
+ return this.getOne({
155
+ subjectRef,
156
+ subjectModel,
157
+ status: "locked",
158
+ "range.start": range.start,
159
+ "range.end": range.end
160
+ }, {
161
+ ...repoOptions(ctx),
162
+ throwOnNotFound: false
163
+ });
164
+ }
165
+ /**
166
+ * Write `update` only if the period is still at the status AND version that was read,
167
+ * moving it to `to`. Every write bumps `version`, so any change since the read (approvals,
168
+ * facts, a reject/reopen cycle) refuses the write instead of acting on a stale check.
169
+ */
170
+ async transition(current, to, update, ctx) {
171
+ const set = to === current.status ? update.$set : {
172
+ ...update.$set,
173
+ status: to
174
+ };
175
+ const updated = await this.claimVersion(current._id, {
176
+ from: current.version,
177
+ where: { status: current.status }
178
+ }, {
179
+ ...update,
180
+ ...set ? { $set: set } : {}
181
+ }, {
182
+ ...repoOptions(ctx),
183
+ idField: "_id"
184
+ });
185
+ if (updated) return updated;
186
+ const latest = await this.load(String(current._id), ctx);
187
+ if (latest.status !== current.status) throw new InvalidWorkPeriodTransitionError(latest.status, to);
188
+ throw new WorkPeriodConcurrencyError(String(current._id));
189
+ }
190
+ async load(id, ctx) {
191
+ const period = await this.getById(id, {
192
+ ...repoOptions(ctx),
193
+ idField: "_id",
194
+ throwOnNotFound: false
195
+ });
196
+ if (!period) throw new WorkPeriodNotFoundError(id);
197
+ return period;
198
+ }
199
+ emitDomain(type, period, ctx) {
200
+ return emitWorkPeriodEvent(this.channels, type, {
201
+ workPeriodId: String(period._id),
202
+ organizationId: String(period.organizationId),
203
+ subjectRef: period.subjectRef,
204
+ subjectModel: period.subjectModel,
205
+ status: period.status,
206
+ factsVersion: period.factsVersion
207
+ }, ctx, String(period._id));
208
+ }
209
+ };
210
+ function repoOptions(ctx) {
211
+ return {
212
+ organizationId: ctx.organizationId,
213
+ actorId: ctx.actorId,
214
+ actorKind: ctx.actorKind,
215
+ correlationId: ctx.correlationId,
216
+ ...ctx.session ? { session: ctx.session } : {},
217
+ ...ctx.signal ? { signal: ctx.signal } : {},
218
+ ...ctx.retryPolicy ? { retryPolicy: ctx.retryPolicy } : {},
219
+ ...ctx.idempotencyKey ? { idempotencyKey: ctx.idempotencyKey } : {}
220
+ };
221
+ }
222
+ //#endregion
223
+ export { WorkPeriodRepository };
@@ -0,0 +1,71 @@
1
+ import { z } from "zod";
2
+ //#region src/schemas.d.ts
3
+ export declare const createWorkPeriodSchema: z.ZodObject<{
4
+ subjectRef: z.ZodString;
5
+ subjectModel: z.ZodString;
6
+ range: z.ZodObject<{
7
+ start: z.ZodISODateTime;
8
+ end: z.ZodISODateTime;
9
+ }, z.core.$strict>;
10
+ attendance: z.ZodOptional<z.ZodObject<{
11
+ workedMinutes: z.ZodNumber;
12
+ scheduledMinutes: z.ZodNumber;
13
+ breakMinutes: z.ZodNumber;
14
+ absentCount: z.ZodOptional<z.ZodNumber>;
15
+ overtimeMinutes: z.ZodOptional<z.ZodNumber>;
16
+ }, z.core.$strict>>;
17
+ leave: z.ZodOptional<z.ZodObject<{
18
+ approvedByType: z.ZodRecord<z.ZodString, z.ZodNumber>;
19
+ totalApprovedDays: z.ZodNumber;
20
+ unpaidDays: z.ZodNumber;
21
+ }, z.core.$strict>>;
22
+ values: z.ZodOptional<z.ZodRecord<z.ZodString, z.ZodUnknown>>;
23
+ sourceRefs: z.ZodArray<z.ZodObject<{
24
+ sourceModel: z.ZodString;
25
+ sourceId: z.ZodString;
26
+ }, z.core.$strict>>;
27
+ policyRefs: z.ZodOptional<z.ZodArray<z.ZodObject<{
28
+ source: z.ZodObject<{
29
+ sourceModel: z.ZodString;
30
+ sourceId: z.ZodString;
31
+ }, z.core.$strict>;
32
+ version: z.ZodString;
33
+ }, z.core.$strict>>>;
34
+ }, z.core.$strict>;
35
+ export declare const rejectWorkPeriodSchema: z.ZodObject<{
36
+ reason: z.ZodString;
37
+ }, z.core.$strict>;
38
+ export declare const emptyActionSchema: z.ZodObject<{}, z.core.$strict>;
39
+ export declare function toCreateWorkPeriodInput(value: z.infer<typeof createWorkPeriodSchema>): {
40
+ subjectRef: string;
41
+ subjectModel: string;
42
+ attendance?: {
43
+ workedMinutes: number;
44
+ scheduledMinutes: number;
45
+ breakMinutes: number;
46
+ absentCount?: number | undefined;
47
+ overtimeMinutes?: number | undefined;
48
+ } | undefined;
49
+ leave?: {
50
+ approvedByType: Record<string, number>;
51
+ totalApprovedDays: number;
52
+ unpaidDays: number;
53
+ } | undefined;
54
+ values?: Record<string, unknown> | undefined;
55
+ sourceRefs: {
56
+ sourceModel: string;
57
+ sourceId: string;
58
+ }[];
59
+ policyRefs?: {
60
+ source: {
61
+ sourceModel: string;
62
+ sourceId: string;
63
+ };
64
+ version: string;
65
+ }[] | undefined;
66
+ range: {
67
+ start: Date;
68
+ end: Date;
69
+ };
70
+ };
71
+ //#endregion
@@ -0,0 +1,48 @@
1
+ import { z } from "zod";
2
+ //#region src/schemas.ts
3
+ const externalRef = z.strictObject({
4
+ sourceModel: z.string().min(1),
5
+ sourceId: z.string().min(1)
6
+ });
7
+ const range = z.strictObject({
8
+ start: z.iso.datetime(),
9
+ end: z.iso.datetime()
10
+ });
11
+ const attendance = z.strictObject({
12
+ workedMinutes: z.number().int().nonnegative(),
13
+ scheduledMinutes: z.number().int().nonnegative(),
14
+ breakMinutes: z.number().int().nonnegative(),
15
+ absentCount: z.number().int().nonnegative().optional(),
16
+ overtimeMinutes: z.number().int().nonnegative().optional()
17
+ });
18
+ const leave = z.strictObject({
19
+ approvedByType: z.record(z.string(), z.number().nonnegative()),
20
+ totalApprovedDays: z.number().nonnegative(),
21
+ unpaidDays: z.number().nonnegative()
22
+ });
23
+ const createWorkPeriodSchema = z.strictObject({
24
+ subjectRef: z.string().min(1),
25
+ subjectModel: z.string().min(1),
26
+ range,
27
+ attendance: attendance.optional(),
28
+ leave: leave.optional(),
29
+ values: z.record(z.string(), z.unknown()).optional(),
30
+ sourceRefs: z.array(externalRef).min(1),
31
+ policyRefs: z.array(z.strictObject({
32
+ source: externalRef,
33
+ version: z.string().min(1)
34
+ })).optional()
35
+ });
36
+ const rejectWorkPeriodSchema = z.strictObject({ reason: z.string().min(1).max(2e3) });
37
+ const emptyActionSchema = z.strictObject({});
38
+ function toCreateWorkPeriodInput(value) {
39
+ return {
40
+ ...value,
41
+ range: {
42
+ start: new Date(value.range.start),
43
+ end: new Date(value.range.end)
44
+ }
45
+ };
46
+ }
47
+ //#endregion
48
+ export { createWorkPeriodSchema, emptyActionSchema, rejectWorkPeriodSchema, toCreateWorkPeriodInput };
package/package.json CHANGED
@@ -1,6 +1,70 @@
1
1
  {
2
2
  "name": "@classytic/work-period",
3
- "version": "0.0.0-stage",
4
- "stub": true,
5
- "description": "Temporary package placeholder for staged publishing"
6
- }
3
+ "version": "0.1.0",
4
+ "description": "Country-neutral approved work-period and locked payroll-facts kernel.",
5
+ "type": "module",
6
+ "sideEffects": false,
7
+ "engines": {
8
+ "node": ">=22"
9
+ },
10
+ "publishConfig": {
11
+ "access": "public"
12
+ },
13
+ "exports": {
14
+ ".": {
15
+ "types": "./dist/index.d.mts",
16
+ "default": "./dist/index.mjs"
17
+ },
18
+ "./schemas": {
19
+ "types": "./dist/schemas.d.mts",
20
+ "default": "./dist/schemas.mjs"
21
+ }
22
+ },
23
+ "main": "./dist/index.mjs",
24
+ "types": "./dist/index.d.mts",
25
+ "files": [
26
+ "dist",
27
+ "CHANGELOG.md",
28
+ "LICENSE"
29
+ ],
30
+ "scripts": {
31
+ "build": "tsdown",
32
+ "typecheck": "tsc --noEmit",
33
+ "test": "vitest run",
34
+ "prepublishOnly": "npm run typecheck && npm test && npm run build",
35
+ "push": "classytic-push",
36
+ "release:tag": "node -e \"require('child_process').execSync('npm run push -- v'+require('./package.json').version,{stdio:'inherit'})\"",
37
+ "release": "npm run push -- main && npm run release:tag && npm publish"
38
+ },
39
+ "peerDependencies": {
40
+ "@classytic/mongokit": ">=3.41.0",
41
+ "@classytic/primitives": ">=0.32.0",
42
+ "@classytic/repo-core": ">=0.31.0",
43
+ "mongoose": ">=9.11.0",
44
+ "zod": ">=4.0.0"
45
+ },
46
+ "devDependencies": {
47
+ "@classytic/dev-tools": "^0.2.1",
48
+ "@classytic/mongokit": "^3.43.0",
49
+ "@classytic/primitives": "^0.34.0",
50
+ "@classytic/repo-core": "^0.31.1",
51
+ "@types/node": "^26.6.5",
52
+ "mongodb-memory-server": "^11.3.0",
53
+ "mongoose": "^9.11.2",
54
+ "publint": "^0.3.25",
55
+ "tsdown": "^0.23.1",
56
+ "typescript": "^7.0.2",
57
+ "vitest": "^5.0.5",
58
+ "zod": "^4.6.7"
59
+ },
60
+ "license": "SEE LICENSE IN LICENSE",
61
+ "author": "Classytic",
62
+ "repository": {
63
+ "type": "git",
64
+ "url": "git+https://github.com/classytic/work-period.git"
65
+ },
66
+ "homepage": "https://github.com/classytic/work-period#readme",
67
+ "bugs": {
68
+ "url": "https://github.com/classytic/work-period/issues"
69
+ }
70
+ }
package/README.md DELETED
@@ -1,3 +0,0 @@
1
- # Temporary Holding Version
2
-
3
- This version is a temporary placeholder for this package. An operational version to replace this has been submitted for review and is awaiting a staged release.