diff --git a/.changeset/35355-working-calendar-objects-setup.md b/.changeset/35355-working-calendar-objects-setup.md new file mode 100644 index 00000000000..1576e490e06 --- /dev/null +++ b/.changeset/35355-working-calendar-objects-setup.md @@ -0,0 +1,22 @@ +--- +'@objectstack/platform-objects': minor +'@objectstack/spec': patch +'@objectstack/cli': patch +'@objectstack/objectql': patch +'@object-ui/plugin-form': patch +--- + +feat: working calendars in Setup — `sys_work_calendar` and `sys_work_calendar_exception` (ADR-0157, part two of two) + +Clause-②: yes (widening) +Metadata-protocol: added + +Not released alone; pair #35641/#35642. The first half, #35641 (the calendar service and its arithmetic), is merged; this half ships in the same release as it, with the working-day formula functions (#35356) and the approval escalation's working-time clock (#35357), ADR-0157 D4. + +- **Two platform objects** (`@objectstack/platform-objects`). `sys_work_calendar` holds a calendar's `code` (unique per organization, snake_case), `name`, required IANA `timezone`, `is_default` (one per organization), the required `maintained_from` .. `maintained_through` span its holidays are entered for, and one period column per weekday (`monday_periods` … `sunday_periods`, `HH:mm-HH:mm` periods separated by commas, blank for a day off). `sys_work_calendar_exception` holds dated overrides: `calendar`, `date`, `kind` (`off`, no periods; `on`, that date's full periods), `periods` and `note`, one row per calendar and date. Both are organization data an administrator keeps, audited, like `sys_exchange_rate`; a package may seed rows under the existing seed contract and name a calendar by code. Their names join the platform object name list (`@objectstack/spec`). +- **Setup.** Two entries under Exchange Rates: Working Calendars (with a Needs Maintenance list of every calendar whose maintained span ends within 60 days) and Calendar Exceptions, whose list page imports a year of holidays from a file; the `calendar` column names a calendar by its code or name. Labels and help text ship in all eleven locales. +- **Time zone on create** (`@object-ui/plugin-form`, ADR-0157 D7). A create form opens a required time-zone field that declares no default (`valueDomain: 'iana_time_zone'`) on the organization's time zone, as it opens a record-currency field on the organization's currency; the user can change it. A create that leaves the calendar's `timezone` out takes the same zone on the server. An optional time-zone field, where blank means "take the parent's", is not prefilled. +- **Refusal wording** (`@objectstack/objectql`). The refusal of a create that marks a calendar the default in another organization no longer assumes the writer is working in an organization. +- **A calendar stays in its organization** (`@objectstack/objectql`). An update that changes the organization of a calendar or of an exception date is refused with `400 VALIDATION_FAILED` on `organization_id` (`invalid_value`), before any read and for every writer, system writes included. To have a calendar in another organization, create it there. An edit that leaves `organization_id` out or repeats the stored one is judged as before; a predicate update is judged row by row, and one matched row whose organization would change refuses it. +- **An exception date names a calendar of its own organization** (`@objectstack/objectql`). On a create, and on an update that carries `calendar`, the calendar is read by id in the exception's organization; when it is not there, the write is refused with `400 VALIDATION_FAILED` on `calendar` (`invalid_value`). A calendar of another organization and an id that names no calendar get the same refusal, word for word. The import door is judged the same way, row by row. +- **Organization ownership** (`@objectstack/cli`). Both objects are organization-owned; an exception reaches its organization through its calendar. diff --git a/content/docs/ui/apps.mdx b/content/docs/ui/apps.mdx index fe1bacc6d69..a1d4ffbc4cb 100644 --- a/content/docs/ui/apps.mdx +++ b/content/docs/ui/apps.mdx @@ -888,7 +888,7 @@ The Setup app's anchors: | `group_people_org` | Users, organizations, business units, teams, invitations | | `group_access_control` | Positions, permission sets, sharing rules, API keys | | `group_approvals` | Approvals inbox, requests, history, delegations | -| `group_configuration` | Settings, localization, exchange rates, authentication, email, storage, AI, branding | +| `group_configuration` | Settings, localization, exchange rates, working calendars, authentication, email, storage, AI, branding | | `group_diagnostics` | Sessions, notification events, audit log | | `group_integrations` | Webhooks, cloud connection | | `group_advanced` | OAuth applications | @@ -899,6 +899,17 @@ of the row's currency, from its effective date until a later row for that curren add one row per currency with the first day of the month as the effective date; a correction is an edit to that row, and every change lands in the audit log. +**Working Calendars** (`sys_work_calendar`, after Exchange Rates) holds an organization's working calendars +(ADR-0157): each one's working periods per weekday, in the calendar's time zone; the span its holidays are +entered for (Maintained From to Maintained Through); and whether it is the default, which a calculation that +names no calendar uses. The create form opens with the organization's time zone (Localization → Default +timezone) in the Time Zone field. The **Needs Maintenance** list shows every calendar whose span ends within 60 +days, so next year's holidays are entered before they are needed. **Calendar Exceptions** +(`sys_work_calendar_exception`) holds a calendar's dated overrides, one row per calendar and date: a Day Off, or +a Working Day carrying that date's full periods, such as a make-up workday. Its list page imports a year of +holidays from a file whose `calendar` column names the calendar by its code or name. Both pages need a grant on +their object, and every change lands in the audit log. + Setup is for platform administration and needs `setup.access`. For project-specific administration pages, declare an app of your own. diff --git a/packages/cli/src/utils/organization-ownership-inventory.ts b/packages/cli/src/utils/organization-ownership-inventory.ts index 9af89898b10..71478b397d3 100644 --- a/packages/cli/src/utils/organization-ownership-inventory.ts +++ b/packages/cli/src/utils/organization-ownership-inventory.ts @@ -855,6 +855,11 @@ export const ORGANIZATION_OWNERSHIP_INVENTORY: readonly InventoryEntry[] = [ // organization's administrators author its own units; the platform ships no // row, and no parent row anchors a unit. { object: 'sys_unit', census: PMAIN, fate: 'attribution', citation: `${CENSUS_MAIN} (in reach, added since the first census); ${D10_SINGLE}`, anchors: [] }, + // Working calendars (`@objectstack/platform-objects`, ADR-0157 D1): an + // organization's administrators author its calendars, and an exception's + // calendar carries the organization. + { object: 'sys_work_calendar', census: PMAIN, fate: 'attribution', citation: `${CENSUS_MAIN} (in reach, added since the first census); ${D10_SINGLE}`, anchors: [] }, + { object: 'sys_work_calendar_exception', census: PMAIN, fate: 'attribution', citation: `${CENSUS_MAIN} (in reach, added since the first census); the exception's calendar carries the organization`, anchors: [parent('calendar', 'sys_work_calendar')] }, // The recycle bin (`@objectstack/platform-objects`, ADR-0148, #30237): the // engine writes each entry with the organization of the record it holds, // else the deleting context's. A NULL row comes only from a delete with diff --git a/packages/cli/test/connect-agent-both-halves-wire.pin.test.ts b/packages/cli/test/connect-agent-both-halves-wire.pin.test.ts index b1b173208c6..ac747f610fe 100644 --- a/packages/cli/test/connect-agent-both-halves-wire.pin.test.ts +++ b/packages/cli/test/connect-agent-both-halves-wire.pin.test.ts @@ -264,7 +264,7 @@ describe('#17647 — Connect-an-Agent visibility: BOTH halves, over the wire', ( // The Setup tree the platform admin is served BY THIS COMPOSITION: 9 // authored groups less `group_approvals`, `group_integrations` and // `group_apps`, which nothing in it contributes into and the filter - // collapses, plus the 24 entries `SETUP_NAV_CONTRIBUTIONS` carries, + // collapses, plus the 27 entries `SETUP_NAV_CONTRIBUTIONS` carries, // plus the MCP one. // (25 until #25098 moved the unfiltered Packages entry to Studio; 24 // until #30204 removed the Feature Flags entry with its namespace; 32 @@ -276,13 +276,16 @@ describe('#17647 — Connect-an-Agent visibility: BOTH halves, over the wire', ( // the Packaged Actions entry, `nav_packaged_actions`, the one entry // `group_apps` held here, so that group collapses too; 31 until the // Units of Measure entry, `nav_units_of_measure`, joined Configuration - // (#35488).) + // (#35488); 32 until the working-calendar pair, `nav_work_calendars` + // and `nav_work_calendar_exceptions`, joined it, ADR-0157.) // `nav_settings_branding` is not among them, and not because of a // tenancy wall (this harness boots none): since #24766 it is // contributed by `@objectstack/service-settings` together with the // `branding` namespace, offered only where no organization wall stands, // and this harness composes platform-objects and the MCP bundle alone. - expect(allowedIds).toHaveLength(32); + expect(allowedIds).toHaveLength(34); + expect(allowedIds).toContain('nav_work_calendars'); + expect(allowedIds).toContain('nav_work_calendar_exceptions'); expect(allowedIds).not.toContain('nav_packaged_actions'); expect(allowedIds).toContain('nav_settings_access_policy'); expect(allowedIds).toContain('nav_recycle_bin'); @@ -309,8 +312,8 @@ describe('#17647 — Connect-an-Agent visibility: BOTH halves, over the wire', ( expect(withAccountHalf.statusCode).toBe(200); expect(withoutAccountHalf.statusCode).toBe(200); expect(navIds(withAccountHalf.body?.item)).toEqual(navIds(withoutAccountHalf.body?.item)); - // 32: the composition the count in the test above states. - expect(navIds(withAccountHalf.body?.item)).toHaveLength(32); + // 34: the composition the count in the test above states. + expect(navIds(withAccountHalf.body?.item)).toHaveLength(34); // The mechanism behind the invariance, asserted rather than assumed: // the bundle aims exactly one contribution at `setup` and one at diff --git a/packages/objectql/src/federated-injected-column-readers.test.ts b/packages/objectql/src/federated-injected-column-readers.test.ts index 9bc0d20a2ff..dfcd732c285 100644 --- a/packages/objectql/src/federated-injected-column-readers.test.ts +++ b/packages/objectql/src/federated-injected-column-readers.test.ts @@ -579,6 +579,14 @@ const READERS: Record = { disposition: 'not-a-read', why: 'names the column in refusal text', }, + // ADR-0157 D2: a calendar or exception update may not change the row's organization. + 'work-calendar-service.ts#refuseOrganizationChange :: organization_id': { + disposition: 'row-value', + why: + 'compares the update payload in hand with the stored row the engine passed the hook, and names the column ' + + 'in the refusal; it reads no storage, and its objects, sys_work_calendar and sys_work_calendar_exception, ' + + 'are platform objects, never federated', + }, 'federated-object.ts#isFederatedUnprovisionedInjectedColumn :: isFederatedObject()': { disposition: 'definition', why: 'the general predicate', diff --git a/packages/objectql/src/work-calendar-service.test.ts b/packages/objectql/src/work-calendar-service.test.ts index f134ccf8040..63fcf42856c 100644 --- a/packages/objectql/src/work-calendar-service.test.ts +++ b/packages/objectql/src/work-calendar-service.test.ts @@ -313,6 +313,7 @@ describe('the calendar objects\' write door (ADR-0157 D2, D7, D10)', () => { }); it('refuses an off row with periods and an on row without them (D10)', async () => { + await insertCalendar({ id: 'cal_cn' }); // the calendar the rows name, so the CONTROL lands const insertException = (row: Row) => engine.insert(WORK_CALENDAR_EXCEPTION_OBJECT, row, { context: { isSystem: true } }); const off = await refusal(insertException({ id: 'x1', calendar: 'cal_cn', date: '2026-10-01', kind: 'off', periods: '09:00-12:00' })); expect(resolveThrownHttpError(off)).toMatchObject({ status: 400, code: 'VALIDATION_FAILED' }); diff --git a/packages/objectql/src/work-calendar-service.ts b/packages/objectql/src/work-calendar-service.ts index a38ad0325a4..4d11c70dfb5 100644 --- a/packages/objectql/src/work-calendar-service.ts +++ b/packages/objectql/src/work-calendar-service.ts @@ -56,7 +56,8 @@ * one. Judged: the period columns (D7: no period crosses midnight; D10: * `24:00` is a legal end; `off` carries none, `on` carries its date's full * periods); `maintained_from` on or before `maintained_through`; one default - * per organization. A create that leaves `timezone` out takes the + * per organization; an exception's calendar is one of its own organization's. + * A create that leaves `timezone` out takes the * organization's `localization.timezone` (D7), stored as the calendar's own. * * The hooks take the organization from the session, every writer's alike: a @@ -72,6 +73,26 @@ * calendar's default must therefore load pinned to its organization, or set * the default by an update afterwards. Such a create without a default passes, * and gets no time-zone fill. + * + * A calendar, and each of its exception dates, stays in the organization it + * was created in: an update whose `organization_id` differs from the stored + * row's is refused at the door on `organization_id`, before any read, every + * writer's alike, system writes included. To have the calendar in another + * organization, create it there. An update that repeats the stored + * organization is no change and is judged as any other edit. A predicate + * update is judged row by row, as the engine hands the hook each matched row + * with its stored image: one matched row whose organization would change + * refuses the whole write. + * + * An exception date names a calendar of its own organization. On a create, + * and on an update that carries `calendar`, the hooks read the calendar by id + * in the exception's organization (the session's on a create, by the rule + * above; the stored row's on an update) and refuse on `calendar` when none + * comes back. A calendar of another organization and an id that names no + * calendar meet the same refusal, word for word, so it tells a writer nothing + * about any other organization. A create the hooks cannot read for (its row + * names an organization other than the session's, or it has no organization + * outside `single`) is refused the same way: write it under its organization. */ import { @@ -293,6 +314,12 @@ function periodsRefusal(field: string, value: unknown): FieldRefusal | undefined return { field, code: 'invalid_value', message, value }; } +/** Where an update's elevated reads run: the stored row's own organization (see the module note). */ +function updateReadOrganization(previous: Row, posture: TenancyPosture): ReadScope { + const organizationId = organizationOf(previous.organization_id); + return mayReadIn(organizationId, posture) ? { read: true, organizationId } : { read: false }; +} + /** * Where an insert's elevated reads run: the session's organization (see the * module note), `read: false` when the hooks make none. @@ -351,7 +378,7 @@ async function judgeCalendar( field: 'is_default', code: 'invalid_value', message: - 'This calendar is created in an organization other than the one you are working in, so it cannot be marked ' + + 'This calendar names an organization this write does not run in, so it cannot be marked ' + 'the default here. Create it while working in that organization, or create it without Default and set ' + 'Default afterwards by editing it.', value: true, @@ -375,6 +402,43 @@ async function judgeCalendar( if (problems.length > 0) refuse(WORK_CALENDAR_OBJECT, problems); } +/** The fixed reasons for an update that changes a row's organization (ADR-0157 D2). */ +const STAYS_IN_ORGANIZATION: Record = { + [WORK_CALENDAR_OBJECT]: 'A calendar stays in the organization it was created in; create it in the other organization instead.', + [WORK_CALENDAR_EXCEPTION_OBJECT]: "An exception date stays in its calendar's organization.", +}; + +/** Refuse an update that changes the stored row's organization, before any read (see the module note). */ +function refuseOrganizationChange(object: string, data: Row, previous: Row): void { + if (!hasOwn(data, 'organization_id')) return; + if (organizationOf(data.organization_id) === organizationOf(previous.organization_id)) return; + refuse(object, [{ field: 'organization_id', code: 'invalid_value', message: STAYS_IN_ORGANIZATION[object]! }]); +} + +/** The fixed reason for an exception whose calendar its organization does not hold: no organization, code or id. */ +const CALENDAR_OF_OWN_ORGANIZATION = 'An exception date names a calendar of its own organization.'; + +/** + * Refuse an exception whose `calendar` its own organization does not hold: + * one read by id in `scope`'s organization (see the module note). A blank is + * left to `required`. + */ +async function refuseForeignCalendar(engine: WorkCalendarReadEngine, ctx: any, data: Row, scope: ReadScope): Promise { + if (!hasOwn(data, 'calendar')) return; + const ref = data.calendar; + if (ref === undefined || ref === null || ref === '') return; + if (scope.read && (typeof ref === 'string' || typeof ref === 'number')) { + const held = (await engine.find(WORK_CALENDAR_OBJECT, { + where: { id: String(ref) }, + fields: ['id'], + limit: 1, + context: readContext(scope.organizationId, ctx?.transaction), + })).filter(isRow); + if (held.length > 0) return; + } + refuse(WORK_CALENDAR_EXCEPTION_OBJECT, [{ field: 'calendar', code: 'invalid_value', message: CALENDAR_OF_OWN_ORGANIZATION }]); +} + /** Judge an exception row's post-image (ADR-0157 D10) when the write carries its kind or periods. */ function judgeException(data: Row, previous: Row | undefined): void { if (!hasOwn(data, 'kind') && !hasOwn(data, 'periods')) return; @@ -431,18 +495,23 @@ export function installWorkCalendarHooks( const data = ctx?.input?.data; const previous = isRow(ctx?.previous) ? ctx.previous : undefined; if (!isRow(data) || !previous) return; + refuseOrganizationChange(WORK_CALENDAR_OBJECT, data, previous); // The stored row's own organization: the engine read it under the write's own scope. - const organizationId = organizationOf(previous.organization_id); - const scope: ReadScope = mayReadIn(organizationId, postureNow()) ? { read: true, organizationId } : { read: false }; - await judgeCalendar(engine, ctx, data, previous, scope); + await judgeCalendar(engine, ctx, data, previous, updateReadOrganization(previous, postureNow())); }); - bind('beforeInsert', WORK_CALENDAR_EXCEPTION_OBJECT, (ctx: any) => { + bind('beforeInsert', WORK_CALENDAR_EXCEPTION_OBJECT, async (ctx: any) => { const row = ctx?.input?.data; - if (isRow(row)) judgeException(row, undefined); + if (!isRow(row)) return; + judgeException(row, undefined); + await refuseForeignCalendar(engine, ctx, row, insertReadOrganization(ctx, row, postureNow())); }); - bind('beforeUpdate', WORK_CALENDAR_EXCEPTION_OBJECT, (ctx: any) => { + bind('beforeUpdate', WORK_CALENDAR_EXCEPTION_OBJECT, async (ctx: any) => { const data = ctx?.input?.data; - if (isRow(data) && isRow(ctx?.previous)) judgeException(data, ctx.previous); + const previous = isRow(ctx?.previous) ? ctx.previous : undefined; + if (!isRow(data) || !previous) return; + refuseOrganizationChange(WORK_CALENDAR_EXCEPTION_OBJECT, data, previous); + judgeException(data, previous); + await refuseForeignCalendar(engine, ctx, data, updateReadOrganization(previous, postureNow())); }); const both = [WORK_CALENDAR_OBJECT, WORK_CALENDAR_EXCEPTION_OBJECT]; for (const event of ['afterInsert', 'afterUpdate', 'afterDelete']) bind(event, both, () => service.invalidate()); diff --git a/packages/platform-objects/scripts/i18n-extract.config.ts b/packages/platform-objects/scripts/i18n-extract.config.ts index 1edd6352b2b..cc3fe5a38ae 100644 --- a/packages/platform-objects/scripts/i18n-extract.config.ts +++ b/packages/platform-objects/scripts/i18n-extract.config.ts @@ -204,6 +204,8 @@ import { SysMigration, SysExchangeRate, SysUnit, + SysWorkCalendar, + SysWorkCalendarException, } from '../src/system/index.js'; // ── Existing Setup app + dashboards + translations ──────────────────────── @@ -362,6 +364,8 @@ const config: ObjectStackDefinition = defineStack({ SysMigration, SysExchangeRate, SysUnit, + SysWorkCalendar, + SysWorkCalendarException, ] as any, apps: [SETUP_APP, STUDIO_APP, ACCOUNT_APP] as any, diff --git a/packages/platform-objects/src/apps/setup-nav.contributions.ts b/packages/platform-objects/src/apps/setup-nav.contributions.ts index e88cb7ba273..2cd8fc1768e 100644 --- a/packages/platform-objects/src/apps/setup-nav.contributions.ts +++ b/packages/platform-objects/src/apps/setup-nav.contributions.ts @@ -139,6 +139,13 @@ export const SETUP_NAV_CONTRIBUTIONS: NavigationContribution[] = [ // `requiredPermissions`: the object grant decides (every member reads, // organization admins write), and Setup itself already needs `setup.access`. { id: 'nav_units_of_measure', type: 'object', label: 'Units of Measure', objectName: 'sys_unit', viewName: 'all_units', icon: 'ruler' }, + // [ADR-0157 D1, D3] Working calendars and their holidays, beside the + // other organization reference data Localization governs. The exceptions + // get their own entry because their list page is the import door for a + // year of holidays; the calendar list's `needs_maintenance` view is the + // D8 notice. Access as Exchange Rates: the object grant decides. + { id: 'nav_work_calendars', type: 'object', label: 'Working Calendars', objectName: 'sys_work_calendar', viewName: 'all_calendars', icon: 'calendar-clock' }, + { id: 'nav_work_calendar_exceptions', type: 'object', label: 'Calendar Exceptions', objectName: 'sys_work_calendar_exception', viewName: 'all_exceptions', icon: 'calendar-x' }, { id: 'nav_settings_company', type: 'url', label: 'Company', url: '/apps/setup/system/settings/company', icon: 'building-2' }, // `nav_settings_branding` is contributed by `@objectstack/service-settings` // with the `branding` namespace, which is offered only where no diff --git a/packages/platform-objects/src/apps/translations/ar.objects.generated.ts b/packages/platform-objects/src/apps/translations/ar.objects.generated.ts index a3641d37e38..8921dc0efe6 100644 --- a/packages/platform-objects/src/apps/translations/ar.objects.generated.ts +++ b/packages/platform-objects/src/apps/translations/ar.objects.generated.ts @@ -4495,5 +4495,128 @@ export const arObjects: NonNullable = { message: "A retired unit cannot be brought back. Create a unit with a new code instead." } } + }, + sys_work_calendar: { + label: "تقويم العمل", + pluralLabel: "تقويمات العمل", + description: "تقويمات العمل: ساعات العمل الأسبوعية، والمنطقة الزمنية التي تُحسب بها، وإلى أي تاريخ أُدخلت العطلات. تقرؤها تواريخ الاستحقاق المحسوبة بوقت العمل.", + fields: { + id: { + label: "المعرّف" + }, + code: { + label: "الرمز", + help: "الرمز الآلي الذي تُسمّي به الصيغ وتصعيدات الموافقة والحزم هذا التقويم، مثل cn_standard: أحرف صغيرة وأرقام وشرطات سفلية." + }, + name: { + label: "الاسم" + }, + timezone: { + label: "المنطقة الزمنية", + help: "منطقة IANA الزمنية التي تُحسب بها فترات العمل، مثل Asia/Shanghai. يُفتح نموذج الإنشاء على المنطقة الزمنية للمؤسسة (الإعدادات ← الترجمة والإعدادات المحلية)، وأي إنشاء يتركها فارغة يأخذ المنطقة نفسها." + }, + is_default: { + label: "افتراضي", + help: "التقويم الذي يستخدمه تاريخ الاستحقاق عندما لا يحدد تقويمًا. واحد لكل مؤسسة." + }, + maintained_from: { + label: "مُحدَّث من", + help: "أول تاريخ أُدخلت منه العطلات وأيام العمل التعويضية. يُرفض أي حساب يحتاج إلى تاريخ أسبق." + }, + maintained_through: { + label: "مُحدَّث حتى", + help: "آخر تاريخ أُدخلت حتى نهايته العطلات وأيام العمل التعويضية. يُرفض أي حساب يحتاج إلى تاريخ لاحق: أدخل عطلات العام التالي، ثم انقل هذا التاريخ." + }, + monday_periods: { + label: "الاثنين", + help: "فترات العمل في ذلك اليوم بالمنطقة الزمنية للتقويم، بصيغة HH:mm-HH:mm مفصولة بفواصل، مثل 09:00-12:00, 13:00-18:00. تنتهي الفترة بعد بدايتها في اليوم نفسه؛ وآخر نهاية ممكنة هي 24:00. اتركها فارغة ليوم الإجازة." + }, + tuesday_periods: { + label: "الثلاثاء", + help: "فترات العمل في ذلك اليوم بالمنطقة الزمنية للتقويم، بصيغة HH:mm-HH:mm مفصولة بفواصل، مثل 09:00-12:00, 13:00-18:00. تنتهي الفترة بعد بدايتها في اليوم نفسه؛ وآخر نهاية ممكنة هي 24:00. اتركها فارغة ليوم الإجازة." + }, + wednesday_periods: { + label: "الأربعاء", + help: "فترات العمل في ذلك اليوم بالمنطقة الزمنية للتقويم، بصيغة HH:mm-HH:mm مفصولة بفواصل، مثل 09:00-12:00, 13:00-18:00. تنتهي الفترة بعد بدايتها في اليوم نفسه؛ وآخر نهاية ممكنة هي 24:00. اتركها فارغة ليوم الإجازة." + }, + thursday_periods: { + label: "الخميس", + help: "فترات العمل في ذلك اليوم بالمنطقة الزمنية للتقويم، بصيغة HH:mm-HH:mm مفصولة بفواصل، مثل 09:00-12:00, 13:00-18:00. تنتهي الفترة بعد بدايتها في اليوم نفسه؛ وآخر نهاية ممكنة هي 24:00. اتركها فارغة ليوم الإجازة." + }, + friday_periods: { + label: "الجمعة", + help: "فترات العمل في ذلك اليوم بالمنطقة الزمنية للتقويم، بصيغة HH:mm-HH:mm مفصولة بفواصل، مثل 09:00-12:00, 13:00-18:00. تنتهي الفترة بعد بدايتها في اليوم نفسه؛ وآخر نهاية ممكنة هي 24:00. اتركها فارغة ليوم الإجازة." + }, + saturday_periods: { + label: "السبت", + help: "فترات العمل في ذلك اليوم بالمنطقة الزمنية للتقويم، بصيغة HH:mm-HH:mm مفصولة بفواصل، مثل 09:00-12:00, 13:00-18:00. تنتهي الفترة بعد بدايتها في اليوم نفسه؛ وآخر نهاية ممكنة هي 24:00. اتركها فارغة ليوم الإجازة." + }, + sunday_periods: { + label: "الأحد", + help: "فترات العمل في ذلك اليوم بالمنطقة الزمنية للتقويم، بصيغة HH:mm-HH:mm مفصولة بفواصل، مثل 09:00-12:00, 13:00-18:00. تنتهي الفترة بعد بدايتها في اليوم نفسه؛ وآخر نهاية ممكنة هي 24:00. اتركها فارغة ليوم الإجازة." + } + }, + _views: { + all_calendars: { + label: "الكل", + emptyState: { + title: "لا توجد تقويمات عمل بعد", + message: "أضف تقويمًا بساعات عمله الأسبوعية وحدّد أحدها تقويمًا افتراضيًا، ثم أدخل عطلاته وأيام العمل التعويضية." + } + }, + needs_maintenance: { + label: "بحاجة إلى تحديث", + emptyState: { + title: "جميع التقويمات محدَّثة مسبقًا", + message: "يظهر التقويم هنا عندما تنتهي عطلاته المُدخلة خلال الـ 60 يومًا القادمة؛ وتُرفض تواريخ الاستحقاق التي تتجاوز ذلك التاريخ." + } + } + }, + _validations: { + work_calendar_code_shape: { + message: "يجب أن يبدأ الرمز بحرف صغير وأن يحتوي فقط على أحرف صغيرة وأرقام وشرطات سفلية، مثل cn_standard." + } + } + }, + sys_work_calendar_exception: { + label: "استثناء تقويم", + pluralLabel: "استثناءات التقويم", + description: "استثناءات مؤرّخة لتقويم العمل: العطلات الرسمية وأيام العمل التعويضية وأيام الإغلاق. يحمل يوم العمل فترات عمله كاملة.", + fields: { + id: { + label: "المعرّف" + }, + calendar: { + label: "التقويم" + }, + date: { + label: "التاريخ" + }, + kind: { + label: "النوع", + help: "يوم إجازة: التاريخ كله إجازة. يوم عمل: يُعمل في التاريخ وفق الفترات أدناه، مثل يوم عمل تعويضي.", + options: { + off: "يوم إجازة", + on: "يوم عمل" + } + }, + periods: { + label: "الفترات", + help: "ليوم العمل، كل ساعات ذلك التاريخ؛ ولا تُؤخذ أبدًا من يوم الأسبوع. فترات العمل في ذلك اليوم بالمنطقة الزمنية للتقويم، بصيغة HH:mm-HH:mm مفصولة بفواصل، مثل 09:00-12:00, 13:00-18:00. تنتهي الفترة بعد بدايتها في اليوم نفسه؛ وآخر نهاية ممكنة هي 24:00. اتركها فارغة ليوم الإجازة." + }, + note: { + label: "ملاحظة", + help: "ما هو هذا التاريخ، مثل العيد الوطني أو يوم عمل تعويضي لعيد الربيع." + } + }, + _views: { + all_exceptions: { + label: "الكل", + emptyState: { + title: "لا توجد استثناءات تقويم بعد", + message: "أضف صفًا لكل عطلة أو يوم عمل تعويضي، أو استورد سنة كاملة منها من ملف." + } + } + } } }; diff --git a/packages/platform-objects/src/apps/translations/ar.ts b/packages/platform-objects/src/apps/translations/ar.ts index 20296403eeb..2ae20a8951a 100644 --- a/packages/platform-objects/src/apps/translations/ar.ts +++ b/packages/platform-objects/src/apps/translations/ar.ts @@ -95,6 +95,8 @@ export const ar: TranslationData = { nav_settings_localization: { label: 'الترجمة والإعدادات المحلية' }, nav_exchange_rates: { label: 'أسعار الصرف' }, nav_units_of_measure: { label: 'وحدات القياس' }, + nav_work_calendars: { label: 'تقويمات العمل' }, + nav_work_calendar_exceptions: { label: 'استثناءات التقويم' }, nav_settings_company: { label: 'الشركة' }, nav_settings_mail: { label: 'إرسال البريد' }, nav_settings_sms: { label: 'إرسال الرسائل النصية' }, diff --git a/packages/platform-objects/src/apps/translations/bundle-ownership.test.ts b/packages/platform-objects/src/apps/translations/bundle-ownership.test.ts index 450ca84c8db..143a0c008c6 100644 --- a/packages/platform-objects/src/apps/translations/bundle-ownership.test.ts +++ b/packages/platform-objects/src/apps/translations/bundle-ownership.test.ts @@ -56,6 +56,7 @@ const OWNED_OBJECTS = new Set([ 'sys_metadata', 'sys_metadata_history', 'sys_metadata_audit', 'sys_metadata_commit', // system 'sys_setting', 'sys_platform_setting', 'sys_secret', 'sys_setting_audit', 'sys_platform_setting_audit', 'sys_migration', 'sys_exchange_rate', 'sys_unit', + 'sys_work_calendar', 'sys_work_calendar_exception', ]); describe('objects translation bundle ownership (ADR-0029 D8)', () => { diff --git a/packages/platform-objects/src/apps/translations/de.objects.generated.ts b/packages/platform-objects/src/apps/translations/de.objects.generated.ts index 7f8ae4e8064..ae79ce9f681 100644 --- a/packages/platform-objects/src/apps/translations/de.objects.generated.ts +++ b/packages/platform-objects/src/apps/translations/de.objects.generated.ts @@ -4495,5 +4495,128 @@ export const deObjects: NonNullable = { message: "A retired unit cannot be brought back. Create a unit with a new code instead." } } + }, + sys_work_calendar: { + label: "Arbeitskalender", + pluralLabel: "Arbeitskalender", + description: "Arbeitskalender: die wöchentlichen Arbeitszeiten, die Zeitzone, in der sie gelten, und bis wann die Feiertage gepflegt sind. Fälligkeitsdaten, die in Arbeitszeit gezählt werden, lesen sie.", + fields: { + id: { + label: "ID" + }, + code: { + label: "Code", + help: "Maschinencode, mit dem Formeln, Genehmigungseskalationen und Pakete diesen Kalender benennen, z. B. cn_standard: Kleinbuchstaben, Ziffern und Unterstriche." + }, + name: { + label: "Name" + }, + timezone: { + label: "Zeitzone", + help: "IANA-Zeitzone, in der die Arbeitszeiten gelten, z. B. Asia/Shanghai. Das Formular zum Anlegen öffnet sich mit der Zeitzone der Organisation (Einstellungen → Lokalisierung), und ein Anlegen ohne Angabe erhält dieselbe Zeitzone." + }, + is_default: { + label: "Standard", + help: "Der Kalender, den ein Fälligkeitsdatum verwendet, wenn es keinen nennt. Einer pro Organisation." + }, + maintained_from: { + label: "Gepflegt ab", + help: "Erstes Datum, ab dem Feiertage und Ersatzarbeitstage erfasst sind. Eine Berechnung, die ein früheres Datum braucht, wird abgelehnt." + }, + maintained_through: { + label: "Gepflegt bis", + help: "Letztes Datum, bis zu dem Feiertage und Ersatzarbeitstage erfasst sind. Eine Berechnung, die ein späteres Datum braucht, wird abgelehnt: Erfassen Sie die Feiertage des nächsten Jahres und verschieben Sie dann dieses Datum." + }, + monday_periods: { + label: "Montag", + help: "Arbeitszeiten an diesem Tag in der Zeitzone des Kalenders, HH:mm-HH:mm durch Kommas getrennt, z. B. 09:00-12:00, 13:00-18:00. Ein Zeitraum endet am selben Tag später, als er beginnt; 24:00 ist das späteste Ende. Für einen freien Tag leer lassen." + }, + tuesday_periods: { + label: "Dienstag", + help: "Arbeitszeiten an diesem Tag in der Zeitzone des Kalenders, HH:mm-HH:mm durch Kommas getrennt, z. B. 09:00-12:00, 13:00-18:00. Ein Zeitraum endet am selben Tag später, als er beginnt; 24:00 ist das späteste Ende. Für einen freien Tag leer lassen." + }, + wednesday_periods: { + label: "Mittwoch", + help: "Arbeitszeiten an diesem Tag in der Zeitzone des Kalenders, HH:mm-HH:mm durch Kommas getrennt, z. B. 09:00-12:00, 13:00-18:00. Ein Zeitraum endet am selben Tag später, als er beginnt; 24:00 ist das späteste Ende. Für einen freien Tag leer lassen." + }, + thursday_periods: { + label: "Donnerstag", + help: "Arbeitszeiten an diesem Tag in der Zeitzone des Kalenders, HH:mm-HH:mm durch Kommas getrennt, z. B. 09:00-12:00, 13:00-18:00. Ein Zeitraum endet am selben Tag später, als er beginnt; 24:00 ist das späteste Ende. Für einen freien Tag leer lassen." + }, + friday_periods: { + label: "Freitag", + help: "Arbeitszeiten an diesem Tag in der Zeitzone des Kalenders, HH:mm-HH:mm durch Kommas getrennt, z. B. 09:00-12:00, 13:00-18:00. Ein Zeitraum endet am selben Tag später, als er beginnt; 24:00 ist das späteste Ende. Für einen freien Tag leer lassen." + }, + saturday_periods: { + label: "Samstag", + help: "Arbeitszeiten an diesem Tag in der Zeitzone des Kalenders, HH:mm-HH:mm durch Kommas getrennt, z. B. 09:00-12:00, 13:00-18:00. Ein Zeitraum endet am selben Tag später, als er beginnt; 24:00 ist das späteste Ende. Für einen freien Tag leer lassen." + }, + sunday_periods: { + label: "Sonntag", + help: "Arbeitszeiten an diesem Tag in der Zeitzone des Kalenders, HH:mm-HH:mm durch Kommas getrennt, z. B. 09:00-12:00, 13:00-18:00. Ein Zeitraum endet am selben Tag später, als er beginnt; 24:00 ist das späteste Ende. Für einen freien Tag leer lassen." + } + }, + _views: { + all_calendars: { + label: "Alle", + emptyState: { + title: "Noch keine Arbeitskalender", + message: "Fügen Sie einen Kalender mit seinen wöchentlichen Arbeitszeiten hinzu, markieren Sie einen als Standard und erfassen Sie dann seine Feiertage und Ersatzarbeitstage." + } + }, + needs_maintenance: { + label: "Pflege erforderlich", + emptyState: { + title: "Alle Kalender sind vorausschauend gepflegt", + message: "Ein Kalender erscheint hier, wenn seine Feiertage innerhalb der nächsten 60 Tage enden; Fälligkeitsdaten nach diesem Datum werden abgelehnt." + } + } + }, + _validations: { + work_calendar_code_shape: { + message: "Der Code muss mit einem Kleinbuchstaben beginnen und darf nur Kleinbuchstaben, Ziffern und Unterstriche enthalten, z. B. cn_standard." + } + } + }, + sys_work_calendar_exception: { + label: "Kalenderausnahme", + pluralLabel: "Kalenderausnahmen", + description: "Datierte Abweichungen von einem Arbeitskalender: Feiertage, Ersatzarbeitstage und Betriebsruhen. Ein Arbeitstag trägt seine vollständigen Arbeitszeiten.", + fields: { + id: { + label: "ID" + }, + calendar: { + label: "Kalender" + }, + date: { + label: "Datum" + }, + kind: { + label: "Art", + help: "Frei: Der ganze Tag ist frei. Arbeitstag: An dem Datum wird mit den Zeiträumen unten gearbeitet, z. B. an einem Ersatzarbeitstag.", + options: { + off: "Frei", + on: "Arbeitstag" + } + }, + periods: { + label: "Zeiträume", + help: "Für einen Arbeitstag alle Stunden dieses Datums; sie werden nie vom Wochentag übernommen. Arbeitszeiten an diesem Tag in der Zeitzone des Kalenders, HH:mm-HH:mm durch Kommas getrennt, z. B. 09:00-12:00, 13:00-18:00. Ein Zeitraum endet am selben Tag später, als er beginnt; 24:00 ist das späteste Ende. Für einen freien Tag leer lassen." + }, + note: { + label: "Notiz", + help: "Was das Datum ist, z. B. Nationalfeiertag oder ein Ersatzarbeitstag zum Frühlingsfest." + } + }, + _views: { + all_exceptions: { + label: "Alle", + emptyState: { + title: "Noch keine Kalenderausnahmen", + message: "Fügen Sie pro Feiertag oder Ersatzarbeitstag eine Zeile hinzu oder importieren Sie ein Jahr davon aus einer Datei." + } + } + } } }; diff --git a/packages/platform-objects/src/apps/translations/de.source-hashes.generated.ts b/packages/platform-objects/src/apps/translations/de.source-hashes.generated.ts index aa568ef6ee7..5b0371a36b6 100644 --- a/packages/platform-objects/src/apps/translations/de.source-hashes.generated.ts +++ b/packages/platform-objects/src/apps/translations/de.source-hashes.generated.ts @@ -266,4 +266,8 @@ export const deGeneratedSourceHashes: Readonly> = { "objects.sys_user.fields.name.label": "5274417ff1ccaf01", "objects.sys_user.fields.principal_kind.options.human": "ed18d3469e10aef2", "objects.sys_user.fields.source.options.idp_pending": "3751093c5b65b072", + "objects.sys_work_calendar.fields.code.label": "083180bdf83435b3", + "objects.sys_work_calendar.fields.id.label": "00b0385c9c152888", + "objects.sys_work_calendar.fields.name.label": "5274417ff1ccaf01", + "objects.sys_work_calendar_exception.fields.id.label": "00b0385c9c152888", }; diff --git a/packages/platform-objects/src/apps/translations/de.ts b/packages/platform-objects/src/apps/translations/de.ts index 1c880264407..be27d6ad545 100644 --- a/packages/platform-objects/src/apps/translations/de.ts +++ b/packages/platform-objects/src/apps/translations/de.ts @@ -97,6 +97,8 @@ export const de: TranslationData = { nav_settings_localization: { label: 'Lokalisierung' }, nav_exchange_rates: { label: 'Wechselkurse' }, nav_units_of_measure: { label: 'Maßeinheiten' }, + nav_work_calendars: { label: 'Arbeitskalender' }, + nav_work_calendar_exceptions: { label: 'Kalenderausnahmen' }, nav_settings_company: { label: 'Unternehmen' }, nav_settings_mail: { label: 'E-Mail-Versand' }, nav_settings_sms: { label: 'SMS-Versand' }, diff --git a/packages/platform-objects/src/apps/translations/en.objects.generated.ts b/packages/platform-objects/src/apps/translations/en.objects.generated.ts index ade2e693e94..e5165598536 100644 --- a/packages/platform-objects/src/apps/translations/en.objects.generated.ts +++ b/packages/platform-objects/src/apps/translations/en.objects.generated.ts @@ -4495,5 +4495,128 @@ export const enObjects: NonNullable = { message: "A retired unit cannot be brought back. Create a unit with a new code instead." } } + }, + sys_work_calendar: { + label: "Working Calendar", + pluralLabel: "Working Calendars", + description: "Working calendars: the weekly working hours, the time zone they are local to, and how far the holidays are maintained. Due dates counted in working time read them.", + fields: { + id: { + label: "ID" + }, + code: { + label: "Code", + help: "Machine code formulas, approval escalations and packages name this calendar by, such as cn_standard: lowercase letters, digits and underscores." + }, + name: { + label: "Name" + }, + timezone: { + label: "Time Zone", + help: "IANA time zone the working periods are local to, such as Asia/Shanghai. The create form opens with the organization's time zone (Settings → Localization), and a create that leaves it out takes the same zone." + }, + is_default: { + label: "Default", + help: "The calendar a due date uses when it names none. One per organization." + }, + maintained_from: { + label: "Maintained From", + help: "First date the holidays and make-up workdays are entered from. A computation that needs an earlier date is refused." + }, + maintained_through: { + label: "Maintained Through", + help: "Last date the holidays and make-up workdays are entered through. A computation that needs a later date is refused: enter next year's holidays, then move this date." + }, + monday_periods: { + label: "Monday", + help: "Working periods that day in the calendar's time zone, HH:mm-HH:mm separated by commas, such as 09:00-12:00, 13:00-18:00. A period ends later than it starts on the same day; 24:00 is the latest end. Leave blank for a day off." + }, + tuesday_periods: { + label: "Tuesday", + help: "Working periods that day in the calendar's time zone, HH:mm-HH:mm separated by commas, such as 09:00-12:00, 13:00-18:00. A period ends later than it starts on the same day; 24:00 is the latest end. Leave blank for a day off." + }, + wednesday_periods: { + label: "Wednesday", + help: "Working periods that day in the calendar's time zone, HH:mm-HH:mm separated by commas, such as 09:00-12:00, 13:00-18:00. A period ends later than it starts on the same day; 24:00 is the latest end. Leave blank for a day off." + }, + thursday_periods: { + label: "Thursday", + help: "Working periods that day in the calendar's time zone, HH:mm-HH:mm separated by commas, such as 09:00-12:00, 13:00-18:00. A period ends later than it starts on the same day; 24:00 is the latest end. Leave blank for a day off." + }, + friday_periods: { + label: "Friday", + help: "Working periods that day in the calendar's time zone, HH:mm-HH:mm separated by commas, such as 09:00-12:00, 13:00-18:00. A period ends later than it starts on the same day; 24:00 is the latest end. Leave blank for a day off." + }, + saturday_periods: { + label: "Saturday", + help: "Working periods that day in the calendar's time zone, HH:mm-HH:mm separated by commas, such as 09:00-12:00, 13:00-18:00. A period ends later than it starts on the same day; 24:00 is the latest end. Leave blank for a day off." + }, + sunday_periods: { + label: "Sunday", + help: "Working periods that day in the calendar's time zone, HH:mm-HH:mm separated by commas, such as 09:00-12:00, 13:00-18:00. A period ends later than it starts on the same day; 24:00 is the latest end. Leave blank for a day off." + } + }, + _views: { + all_calendars: { + label: "All", + emptyState: { + title: "No working calendars yet", + message: "Add a calendar with its weekly hours and mark one as the default, then enter its holidays and make-up workdays." + } + }, + needs_maintenance: { + label: "Needs Maintenance", + emptyState: { + title: "Every calendar is maintained ahead", + message: "A calendar appears here when its holidays run out within the next 60 days; due dates past that date are refused." + } + } + }, + _validations: { + work_calendar_code_shape: { + message: "Code must start with a lowercase letter and use only lowercase letters, digits and underscores, such as cn_standard." + } + } + }, + sys_work_calendar_exception: { + label: "Calendar Exception", + pluralLabel: "Calendar Exceptions", + description: "Dated overrides of a working calendar: public holidays, make-up workdays and shutdowns. A working day carries its full working periods.", + fields: { + id: { + label: "ID" + }, + calendar: { + label: "Calendar" + }, + date: { + label: "Date" + }, + kind: { + label: "Kind", + help: "Day Off: the whole date is off. Working Day: the date is worked with the periods below, such as a make-up workday.", + options: { + off: "Day Off", + on: "Working Day" + } + }, + periods: { + label: "Periods", + help: "For a working day, all of that date's hours; they are never taken from the weekday. Working periods that day in the calendar's time zone, HH:mm-HH:mm separated by commas, such as 09:00-12:00, 13:00-18:00. A period ends later than it starts on the same day; 24:00 is the latest end. Leave blank for a day off." + }, + note: { + label: "Note", + help: "What the date is, such as National Day or a make-up workday for Spring Festival." + } + }, + _views: { + all_exceptions: { + label: "All", + emptyState: { + title: "No calendar exceptions yet", + message: "Add one row per holiday or make-up workday, or import a year of them from a file." + } + } + } } }; diff --git a/packages/platform-objects/src/apps/translations/en.ts b/packages/platform-objects/src/apps/translations/en.ts index 209cf5e9542..b5661f1bd4c 100644 --- a/packages/platform-objects/src/apps/translations/en.ts +++ b/packages/platform-objects/src/apps/translations/en.ts @@ -131,6 +131,8 @@ export const en: TranslationData = { nav_settings_localization: { label: 'Localization' }, nav_exchange_rates: { label: 'Exchange Rates' }, nav_units_of_measure: { label: 'Units of Measure' }, + nav_work_calendars: { label: 'Working Calendars' }, + nav_work_calendar_exceptions: { label: 'Calendar Exceptions' }, nav_settings_company: { label: 'Company' }, nav_settings_mail: { label: 'Mail Delivery' }, nav_settings_sms: { label: 'SMS Delivery' }, diff --git a/packages/platform-objects/src/apps/translations/es-ES.objects.generated.ts b/packages/platform-objects/src/apps/translations/es-ES.objects.generated.ts index 1775ccb2b6c..922c98c2e1b 100644 --- a/packages/platform-objects/src/apps/translations/es-ES.objects.generated.ts +++ b/packages/platform-objects/src/apps/translations/es-ES.objects.generated.ts @@ -4495,5 +4495,128 @@ export const esESObjects: NonNullable = { message: "A retired unit cannot be brought back. Create a unit with a new code instead." } } + }, + sys_work_calendar: { + label: "Calendario laboral", + pluralLabel: "Calendarios laborales", + description: "Calendarios laborales: el horario semanal, la zona horaria en la que se aplica y hasta cuándo están mantenidos los festivos. Las fechas de vencimiento contadas en tiempo laborable los leen.", + fields: { + id: { + label: "ID" + }, + code: { + label: "Código", + help: "Código de máquina con el que las fórmulas, las escalaciones de aprobación y los paquetes nombran este calendario, p. ej. cn_standard: letras minúsculas, dígitos y guiones bajos." + }, + name: { + label: "Nombre" + }, + timezone: { + label: "Zona horaria", + help: "Zona horaria IANA en la que se aplican las franjas de trabajo, p. ej. Asia/Shanghai. El formulario de creación se abre con la zona horaria de la organización (Ajustes → Localización), y una creación que la omite recibe la misma zona." + }, + is_default: { + label: "Predeterminado", + help: "El calendario que usa una fecha de vencimiento cuando no indica ninguno. Uno por organización." + }, + maintained_from: { + label: "Mantenido desde", + help: "Primera fecha desde la que se registran los festivos y los días laborables de recuperación. Se rechaza un cálculo que necesite una fecha anterior." + }, + maintained_through: { + label: "Mantenido hasta", + help: "Última fecha hasta la que se registran los festivos y los días laborables de recuperación. Se rechaza un cálculo que necesite una fecha posterior: registra los festivos del año siguiente y luego mueve esta fecha." + }, + monday_periods: { + label: "Lunes", + help: "Franjas de trabajo de ese día en la zona horaria del calendario, HH:mm-HH:mm separadas por comas, p. ej. 09:00-12:00, 13:00-18:00. Una franja termina después de empezar, el mismo día; 24:00 es el final más tardío. Déjalo vacío para un día libre." + }, + tuesday_periods: { + label: "Martes", + help: "Franjas de trabajo de ese día en la zona horaria del calendario, HH:mm-HH:mm separadas por comas, p. ej. 09:00-12:00, 13:00-18:00. Una franja termina después de empezar, el mismo día; 24:00 es el final más tardío. Déjalo vacío para un día libre." + }, + wednesday_periods: { + label: "Miércoles", + help: "Franjas de trabajo de ese día en la zona horaria del calendario, HH:mm-HH:mm separadas por comas, p. ej. 09:00-12:00, 13:00-18:00. Una franja termina después de empezar, el mismo día; 24:00 es el final más tardío. Déjalo vacío para un día libre." + }, + thursday_periods: { + label: "Jueves", + help: "Franjas de trabajo de ese día en la zona horaria del calendario, HH:mm-HH:mm separadas por comas, p. ej. 09:00-12:00, 13:00-18:00. Una franja termina después de empezar, el mismo día; 24:00 es el final más tardío. Déjalo vacío para un día libre." + }, + friday_periods: { + label: "Viernes", + help: "Franjas de trabajo de ese día en la zona horaria del calendario, HH:mm-HH:mm separadas por comas, p. ej. 09:00-12:00, 13:00-18:00. Una franja termina después de empezar, el mismo día; 24:00 es el final más tardío. Déjalo vacío para un día libre." + }, + saturday_periods: { + label: "Sábado", + help: "Franjas de trabajo de ese día en la zona horaria del calendario, HH:mm-HH:mm separadas por comas, p. ej. 09:00-12:00, 13:00-18:00. Una franja termina después de empezar, el mismo día; 24:00 es el final más tardío. Déjalo vacío para un día libre." + }, + sunday_periods: { + label: "Domingo", + help: "Franjas de trabajo de ese día en la zona horaria del calendario, HH:mm-HH:mm separadas por comas, p. ej. 09:00-12:00, 13:00-18:00. Una franja termina después de empezar, el mismo día; 24:00 es el final más tardío. Déjalo vacío para un día libre." + } + }, + _views: { + all_calendars: { + label: "Todos", + emptyState: { + title: "Aún no hay calendarios laborales", + message: "Añade un calendario con su horario semanal y marca uno como predeterminado; después registra sus festivos y días laborables de recuperación." + } + }, + needs_maintenance: { + label: "Requiere mantenimiento", + emptyState: { + title: "Todos los calendarios están mantenidos con antelación", + message: "Un calendario aparece aquí cuando sus festivos se acaban en los próximos 60 días; se rechazan las fechas de vencimiento posteriores a esa fecha." + } + } + }, + _validations: { + work_calendar_code_shape: { + message: "El código debe empezar por una letra minúscula y usar solo letras minúsculas, dígitos y guiones bajos, p. ej. cn_standard." + } + } + }, + sys_work_calendar_exception: { + label: "Excepción de calendario", + pluralLabel: "Excepciones de calendario", + description: "Excepciones fechadas a un calendario laboral: festivos, días laborables de recuperación y cierres. Un día laborable lleva sus franjas de trabajo completas.", + fields: { + id: { + label: "ID" + }, + calendar: { + label: "Calendario" + }, + date: { + label: "Fecha" + }, + kind: { + label: "Clase", + help: "Día libre: la fecha entera es libre. Día laborable: la fecha se trabaja con las franjas de abajo, p. ej. un día laborable de recuperación.", + options: { + off: "Día libre", + on: "Día laborable" + } + }, + periods: { + label: "Franjas", + help: "Para un día laborable, todas las horas de esa fecha; nunca se toman del día de la semana. Franjas de trabajo de ese día en la zona horaria del calendario, HH:mm-HH:mm separadas por comas, p. ej. 09:00-12:00, 13:00-18:00. Una franja termina después de empezar, el mismo día; 24:00 es el final más tardío. Déjalo vacío para un día libre." + }, + note: { + label: "Nota", + help: "Qué es la fecha, p. ej. la Fiesta Nacional o un día laborable de recuperación por el Festival de Primavera." + } + }, + _views: { + all_exceptions: { + label: "Todos", + emptyState: { + title: "Aún no hay excepciones de calendario", + message: "Añade una fila por cada festivo o día laborable de recuperación, o importa un año de ellos desde un archivo." + } + } + } } }; diff --git a/packages/platform-objects/src/apps/translations/es-ES.source-hashes.generated.ts b/packages/platform-objects/src/apps/translations/es-ES.source-hashes.generated.ts index 083d6760f5e..16a789fc601 100644 --- a/packages/platform-objects/src/apps/translations/es-ES.source-hashes.generated.ts +++ b/packages/platform-objects/src/apps/translations/es-ES.source-hashes.generated.ts @@ -194,4 +194,6 @@ export const esESGeneratedSourceHashes: Readonly> = { "objects.sys_unit.pluralLabel": "b52fcf82e54fdb7e", "objects.sys_user._actions.import_sso_users.params.csv.label": "bfb77802b66a9222", "objects.sys_user.fields.source.options.idp_pending": "3751093c5b65b072", + "objects.sys_work_calendar.fields.id.label": "00b0385c9c152888", + "objects.sys_work_calendar_exception.fields.id.label": "00b0385c9c152888", }; diff --git a/packages/platform-objects/src/apps/translations/es-ES.ts b/packages/platform-objects/src/apps/translations/es-ES.ts index 4d25c35819d..8cd297bebcc 100644 --- a/packages/platform-objects/src/apps/translations/es-ES.ts +++ b/packages/platform-objects/src/apps/translations/es-ES.ts @@ -86,6 +86,8 @@ export const esES: TranslationData = { nav_settings_localization: { label: 'Localización' }, nav_exchange_rates: { label: 'Tipos de cambio' }, nav_units_of_measure: { label: 'Unidades de medida' }, + nav_work_calendars: { label: 'Calendarios laborales' }, + nav_work_calendar_exceptions: { label: 'Excepciones de calendario' }, nav_settings_company: { label: 'Empresa' }, nav_settings_mail: { label: 'Envío de correo' }, nav_settings_sms: { label: 'Envío de SMS' }, diff --git a/packages/platform-objects/src/apps/translations/fr.objects.generated.ts b/packages/platform-objects/src/apps/translations/fr.objects.generated.ts index 33bc167a618..b83c9c39094 100644 --- a/packages/platform-objects/src/apps/translations/fr.objects.generated.ts +++ b/packages/platform-objects/src/apps/translations/fr.objects.generated.ts @@ -4495,5 +4495,128 @@ export const frObjects: NonNullable = { message: "A retired unit cannot be brought back. Create a unit with a new code instead." } } + }, + sys_work_calendar: { + label: "Calendrier de travail", + pluralLabel: "Calendriers de travail", + description: "Calendriers de travail : les horaires hebdomadaires, le fuseau horaire dans lequel ils s’appliquent et jusqu’à quand les jours fériés sont tenus à jour. Les échéances comptées en temps ouvré les lisent.", + fields: { + id: { + label: "ID" + }, + code: { + label: "Code", + help: "Code machine par lequel les formules, les escalades d’approbation et les packages désignent ce calendrier, par ex. cn_standard : lettres minuscules, chiffres et traits de soulignement." + }, + name: { + label: "Nom" + }, + timezone: { + label: "Fuseau horaire", + help: "Fuseau horaire IANA dans lequel s’appliquent les plages de travail, par ex. Asia/Shanghai. Le formulaire de création s’ouvre sur le fuseau horaire de l’organisation (Paramètres → Localisation), et une création qui l’omet reçoit le même fuseau." + }, + is_default: { + label: "Par défaut", + help: "Le calendrier utilisé par une échéance qui n’en désigne aucun. Un par organisation." + }, + maintained_from: { + label: "Tenu à jour depuis", + help: "Première date à partir de laquelle les jours fériés et les jours de récupération sont saisis. Un calcul qui exige une date antérieure est refusé." + }, + maintained_through: { + label: "Tenu à jour jusqu’au", + help: "Dernière date jusqu’à laquelle les jours fériés et les jours de récupération sont saisis. Un calcul qui exige une date ultérieure est refusé : saisissez les jours fériés de l’année suivante, puis reportez cette date." + }, + monday_periods: { + label: "Lundi", + help: "Plages de travail ce jour-là dans le fuseau horaire du calendrier, au format HH:mm-HH:mm séparées par des virgules, par ex. 09:00-12:00, 13:00-18:00. Une plage se termine après son début, le même jour ; 24:00 est la fin la plus tardive. Laissez vide pour un jour non travaillé." + }, + tuesday_periods: { + label: "Mardi", + help: "Plages de travail ce jour-là dans le fuseau horaire du calendrier, au format HH:mm-HH:mm séparées par des virgules, par ex. 09:00-12:00, 13:00-18:00. Une plage se termine après son début, le même jour ; 24:00 est la fin la plus tardive. Laissez vide pour un jour non travaillé." + }, + wednesday_periods: { + label: "Mercredi", + help: "Plages de travail ce jour-là dans le fuseau horaire du calendrier, au format HH:mm-HH:mm séparées par des virgules, par ex. 09:00-12:00, 13:00-18:00. Une plage se termine après son début, le même jour ; 24:00 est la fin la plus tardive. Laissez vide pour un jour non travaillé." + }, + thursday_periods: { + label: "Jeudi", + help: "Plages de travail ce jour-là dans le fuseau horaire du calendrier, au format HH:mm-HH:mm séparées par des virgules, par ex. 09:00-12:00, 13:00-18:00. Une plage se termine après son début, le même jour ; 24:00 est la fin la plus tardive. Laissez vide pour un jour non travaillé." + }, + friday_periods: { + label: "Vendredi", + help: "Plages de travail ce jour-là dans le fuseau horaire du calendrier, au format HH:mm-HH:mm séparées par des virgules, par ex. 09:00-12:00, 13:00-18:00. Une plage se termine après son début, le même jour ; 24:00 est la fin la plus tardive. Laissez vide pour un jour non travaillé." + }, + saturday_periods: { + label: "Samedi", + help: "Plages de travail ce jour-là dans le fuseau horaire du calendrier, au format HH:mm-HH:mm séparées par des virgules, par ex. 09:00-12:00, 13:00-18:00. Une plage se termine après son début, le même jour ; 24:00 est la fin la plus tardive. Laissez vide pour un jour non travaillé." + }, + sunday_periods: { + label: "Dimanche", + help: "Plages de travail ce jour-là dans le fuseau horaire du calendrier, au format HH:mm-HH:mm séparées par des virgules, par ex. 09:00-12:00, 13:00-18:00. Une plage se termine après son début, le même jour ; 24:00 est la fin la plus tardive. Laissez vide pour un jour non travaillé." + } + }, + _views: { + all_calendars: { + label: "Tous", + emptyState: { + title: "Aucun calendrier de travail pour le moment", + message: "Ajoutez un calendrier avec ses horaires hebdomadaires et marquez-en un comme calendrier par défaut, puis saisissez ses jours fériés et ses jours de récupération." + } + }, + needs_maintenance: { + label: "À mettre à jour", + emptyState: { + title: "Tous les calendriers sont tenus à jour à l’avance", + message: "Un calendrier apparaît ici lorsque ses jours fériés s’arrêtent dans les 60 prochains jours ; les échéances au-delà de cette date sont refusées." + } + } + }, + _validations: { + work_calendar_code_shape: { + message: "Le code doit commencer par une lettre minuscule et ne contenir que des lettres minuscules, des chiffres et des traits de soulignement, par ex. cn_standard." + } + } + }, + sys_work_calendar_exception: { + label: "Exception de calendrier", + pluralLabel: "Exceptions de calendrier", + description: "Dérogations datées à un calendrier de travail : jours fériés, jours de récupération et fermetures. Un jour travaillé porte ses plages de travail complètes.", + fields: { + id: { + label: "ID" + }, + calendar: { + label: "Calendrier" + }, + date: { + label: "Date" + }, + kind: { + label: "Type", + help: "Jour chômé : toute la date est chômée. Jour travaillé : la date est travaillée selon les plages ci-dessous, par ex. un jour de récupération.", + options: { + off: "Jour chômé", + on: "Jour travaillé" + } + }, + periods: { + label: "Plages", + help: "Pour un jour travaillé, toutes les heures de cette date ; elles ne sont jamais reprises du jour de la semaine. Plages de travail ce jour-là dans le fuseau horaire du calendrier, au format HH:mm-HH:mm séparées par des virgules, par ex. 09:00-12:00, 13:00-18:00. Une plage se termine après son début, le même jour ; 24:00 est la fin la plus tardive. Laissez vide pour un jour non travaillé." + }, + note: { + label: "Note", + help: "Ce qu’est la date, par ex. la fête nationale ou un jour de récupération pour la fête du Printemps." + } + }, + _views: { + all_exceptions: { + label: "Tous", + emptyState: { + title: "Aucune exception de calendrier pour le moment", + message: "Ajoutez une ligne par jour férié ou jour de récupération, ou importez-en une année depuis un fichier." + } + } + } } }; diff --git a/packages/platform-objects/src/apps/translations/fr.source-hashes.generated.ts b/packages/platform-objects/src/apps/translations/fr.source-hashes.generated.ts index 0db69dce538..0ce08db8d83 100644 --- a/packages/platform-objects/src/apps/translations/fr.source-hashes.generated.ts +++ b/packages/platform-objects/src/apps/translations/fr.source-hashes.generated.ts @@ -294,4 +294,9 @@ export const frGeneratedSourceHashes: Readonly> = { "objects.sys_user._actions.remove_sso_user.label": "27e40f055ed9dc98", "objects.sys_user._actions.remove_sso_user.successMessage": "45facf16a8b5ebc7", "objects.sys_user.fields.source.options.idp_pending": "3751093c5b65b072", + "objects.sys_work_calendar.fields.code.label": "083180bdf83435b3", + "objects.sys_work_calendar.fields.id.label": "00b0385c9c152888", + "objects.sys_work_calendar_exception.fields.date.label": "767cabc93ccbdaa0", + "objects.sys_work_calendar_exception.fields.id.label": "00b0385c9c152888", + "objects.sys_work_calendar_exception.fields.note.label": "f78f61778f71bf68", }; diff --git a/packages/platform-objects/src/apps/translations/fr.ts b/packages/platform-objects/src/apps/translations/fr.ts index 78dfd740927..4c5aa108121 100644 --- a/packages/platform-objects/src/apps/translations/fr.ts +++ b/packages/platform-objects/src/apps/translations/fr.ts @@ -97,6 +97,8 @@ export const fr: TranslationData = { nav_settings_localization: { label: 'Localisation' }, nav_exchange_rates: { label: 'Taux de change' }, nav_units_of_measure: { label: 'Unités de mesure' }, + nav_work_calendars: { label: 'Calendriers de travail' }, + nav_work_calendar_exceptions: { label: 'Exceptions de calendrier' }, nav_settings_company: { label: 'Entreprise' }, nav_settings_mail: { label: 'Envoi des e-mails' }, nav_settings_sms: { label: 'Envoi des SMS' }, diff --git a/packages/platform-objects/src/apps/translations/ja-JP.objects.generated.ts b/packages/platform-objects/src/apps/translations/ja-JP.objects.generated.ts index 673397b6584..1fe0d29c16c 100644 --- a/packages/platform-objects/src/apps/translations/ja-JP.objects.generated.ts +++ b/packages/platform-objects/src/apps/translations/ja-JP.objects.generated.ts @@ -4495,5 +4495,128 @@ export const jaJPObjects: NonNullable = { message: "A retired unit cannot be brought back. Create a unit with a new code instead." } } + }, + sys_work_calendar: { + label: "稼働カレンダー", + pluralLabel: "稼働カレンダー", + description: "稼働カレンダー:週ごとの稼働時間、その時間帯の基準となるタイムゾーン、祝日をどこまで登録済みか。稼働時間で数える期日はこれを参照します。", + fields: { + id: { + label: "ID" + }, + code: { + label: "コード", + help: "数式、承認エスカレーション、パッケージがこのカレンダーを指すときの機械コード(例: cn_standard)。英小文字、数字、アンダースコアのみ使用できます。" + }, + name: { + label: "名前" + }, + timezone: { + label: "タイムゾーン", + help: "稼働時間帯の基準となる IANA タイムゾーン(例: Asia/Shanghai)。作成フォームには組織のタイムゾーン(設定 → ローカリゼーション)があらかじめ入力され、省略して作成した場合も同じタイムゾーンになります。" + }, + is_default: { + label: "既定", + help: "期日がカレンダーを指定しないときに使うカレンダー。組織ごとに 1 つです。" + }, + maintained_from: { + label: "登録開始日", + help: "祝日と振替出勤日を登録している最初の日付。これより前の日付を必要とする計算は拒否されます。" + }, + maintained_through: { + label: "登録終了日", + help: "祝日と振替出勤日を登録している最後の日付。これより後の日付を必要とする計算は拒否されます。翌年の祝日を登録してから、この日付を延ばしてください。" + }, + monday_periods: { + label: "月曜日", + help: "その日の稼働時間帯(カレンダーのタイムゾーン基準)。HH:mm-HH:mm 形式をカンマで区切ります。例: 09:00-12:00, 13:00-18:00。時間帯は同じ日の中で開始より後に終わる必要があり、最も遅い終了は 24:00 です。休みの日は空欄にします。" + }, + tuesday_periods: { + label: "火曜日", + help: "その日の稼働時間帯(カレンダーのタイムゾーン基準)。HH:mm-HH:mm 形式をカンマで区切ります。例: 09:00-12:00, 13:00-18:00。時間帯は同じ日の中で開始より後に終わる必要があり、最も遅い終了は 24:00 です。休みの日は空欄にします。" + }, + wednesday_periods: { + label: "水曜日", + help: "その日の稼働時間帯(カレンダーのタイムゾーン基準)。HH:mm-HH:mm 形式をカンマで区切ります。例: 09:00-12:00, 13:00-18:00。時間帯は同じ日の中で開始より後に終わる必要があり、最も遅い終了は 24:00 です。休みの日は空欄にします。" + }, + thursday_periods: { + label: "木曜日", + help: "その日の稼働時間帯(カレンダーのタイムゾーン基準)。HH:mm-HH:mm 形式をカンマで区切ります。例: 09:00-12:00, 13:00-18:00。時間帯は同じ日の中で開始より後に終わる必要があり、最も遅い終了は 24:00 です。休みの日は空欄にします。" + }, + friday_periods: { + label: "金曜日", + help: "その日の稼働時間帯(カレンダーのタイムゾーン基準)。HH:mm-HH:mm 形式をカンマで区切ります。例: 09:00-12:00, 13:00-18:00。時間帯は同じ日の中で開始より後に終わる必要があり、最も遅い終了は 24:00 です。休みの日は空欄にします。" + }, + saturday_periods: { + label: "土曜日", + help: "その日の稼働時間帯(カレンダーのタイムゾーン基準)。HH:mm-HH:mm 形式をカンマで区切ります。例: 09:00-12:00, 13:00-18:00。時間帯は同じ日の中で開始より後に終わる必要があり、最も遅い終了は 24:00 です。休みの日は空欄にします。" + }, + sunday_periods: { + label: "日曜日", + help: "その日の稼働時間帯(カレンダーのタイムゾーン基準)。HH:mm-HH:mm 形式をカンマで区切ります。例: 09:00-12:00, 13:00-18:00。時間帯は同じ日の中で開始より後に終わる必要があり、最も遅い終了は 24:00 です。休みの日は空欄にします。" + } + }, + _views: { + all_calendars: { + label: "すべて", + emptyState: { + title: "稼働カレンダーはまだありません", + message: "週ごとの稼働時間を入れてカレンダーを追加し、1 つを既定に設定してから、祝日と振替出勤日を登録します。" + } + }, + needs_maintenance: { + label: "要メンテナンス", + emptyState: { + title: "すべてのカレンダーが先まで登録済みです", + message: "祝日の登録が 60 日以内に切れるカレンダーがここに表示されます。その日付を過ぎる期日の計算は拒否されます。" + } + } + }, + _validations: { + work_calendar_code_shape: { + message: "コードは英小文字で始め、英小文字、数字、アンダースコアのみを使用してください(例: cn_standard)。" + } + } + }, + sys_work_calendar_exception: { + label: "カレンダー例外", + pluralLabel: "カレンダー例外", + description: "稼働カレンダーの日付ごとの上書き:祝日、振替出勤日、休業日。稼働日にはその日の稼働時間帯をすべて入力します。", + fields: { + id: { + label: "ID" + }, + calendar: { + label: "カレンダー" + }, + date: { + label: "日付" + }, + kind: { + label: "種類", + help: "休日:終日休みです。稼働日:下の時間帯で稼働する日です(振替出勤日など)。", + options: { + off: "休日", + on: "稼働日" + } + }, + periods: { + label: "稼働時間帯", + help: "稼働日の場合、その日のすべての稼働時間を入力します。曜日の設定は引き継がれません。その日の稼働時間帯(カレンダーのタイムゾーン基準)。HH:mm-HH:mm 形式をカンマで区切ります。例: 09:00-12:00, 13:00-18:00。時間帯は同じ日の中で開始より後に終わる必要があり、最も遅い終了は 24:00 です。休みの日は空欄にします。" + }, + note: { + label: "メモ", + help: "その日付の内容(例: 国慶節、春節の振替出勤日)。" + } + }, + _views: { + all_exceptions: { + label: "すべて", + emptyState: { + title: "カレンダー例外はまだありません", + message: "祝日または振替出勤日ごとに 1 行追加するか、ファイルから 1 年分をインポートします。" + } + } + } } }; diff --git a/packages/platform-objects/src/apps/translations/ja-JP.source-hashes.generated.ts b/packages/platform-objects/src/apps/translations/ja-JP.source-hashes.generated.ts index d32dc63c581..45d2394e914 100644 --- a/packages/platform-objects/src/apps/translations/ja-JP.source-hashes.generated.ts +++ b/packages/platform-objects/src/apps/translations/ja-JP.source-hashes.generated.ts @@ -184,4 +184,6 @@ export const jaJPGeneratedSourceHashes: Readonly> = { "objects.sys_unit.pluralLabel": "b52fcf82e54fdb7e", "objects.sys_user._actions.import_sso_users.params.csv.label": "bfb77802b66a9222", "objects.sys_user.fields.source.options.idp_pending": "3751093c5b65b072", + "objects.sys_work_calendar.fields.id.label": "00b0385c9c152888", + "objects.sys_work_calendar_exception.fields.id.label": "00b0385c9c152888", }; diff --git a/packages/platform-objects/src/apps/translations/ja-JP.ts b/packages/platform-objects/src/apps/translations/ja-JP.ts index a22990d5464..11b5700cff3 100644 --- a/packages/platform-objects/src/apps/translations/ja-JP.ts +++ b/packages/platform-objects/src/apps/translations/ja-JP.ts @@ -86,6 +86,8 @@ export const jaJP: TranslationData = { nav_settings_localization: { label: 'ローカリゼーション' }, nav_exchange_rates: { label: '為替レート' }, nav_units_of_measure: { label: '計量単位' }, + nav_work_calendars: { label: '稼働カレンダー' }, + nav_work_calendar_exceptions: { label: 'カレンダー例外' }, nav_settings_company: { label: '会社' }, nav_settings_mail: { label: 'メール配信' }, nav_settings_sms: { label: 'SMS 配信' }, diff --git a/packages/platform-objects/src/apps/translations/ko.objects.generated.ts b/packages/platform-objects/src/apps/translations/ko.objects.generated.ts index 42bdfb4a3eb..ffd7da58376 100644 --- a/packages/platform-objects/src/apps/translations/ko.objects.generated.ts +++ b/packages/platform-objects/src/apps/translations/ko.objects.generated.ts @@ -4495,5 +4495,128 @@ export const koObjects: NonNullable = { message: "A retired unit cannot be brought back. Create a unit with a new code instead." } } + }, + sys_work_calendar: { + label: "근무 캘린더", + pluralLabel: "근무 캘린더", + description: "근무 캘린더: 주간 근무 시간, 그 시간의 기준 시간대, 공휴일이 어디까지 관리되었는지를 담습니다. 근무 시간으로 계산하는 기한이 이를 참조합니다.", + fields: { + id: { + label: "ID" + }, + code: { + label: "코드", + help: "수식, 승인 에스컬레이션, 패키지가 이 캘린더를 가리킬 때 쓰는 기계 코드(예: cn_standard)로, 영문 소문자, 숫자, 밑줄만 사용합니다." + }, + name: { + label: "이름" + }, + timezone: { + label: "시간대", + help: "근무 시간대의 기준이 되는 IANA 시간대(예: Asia/Shanghai). 생성 양식에는 조직의 시간대(설정 → 현지화)가 미리 채워지며, 비워 두고 생성해도 같은 시간대가 적용됩니다." + }, + is_default: { + label: "기본값", + help: "기한이 캘린더를 지정하지 않을 때 사용하는 캘린더입니다. 조직당 하나입니다." + }, + maintained_from: { + label: "관리 시작일", + help: "공휴일과 대체 근무일이 입력되기 시작한 날짜입니다. 이보다 이른 날짜가 필요한 계산은 거부됩니다." + }, + maintained_through: { + label: "관리 종료일", + help: "공휴일과 대체 근무일이 입력된 마지막 날짜입니다. 이보다 늦은 날짜가 필요한 계산은 거부됩니다. 다음 해 공휴일을 입력한 뒤 이 날짜를 옮기세요." + }, + monday_periods: { + label: "월요일", + help: "캘린더 시간대 기준 그날의 근무 시간대로, HH:mm-HH:mm 형식을 쉼표로 구분합니다(예: 09:00-12:00, 13:00-18:00). 시간대는 같은 날 안에서 시작보다 늦게 끝나야 하며, 가장 늦은 종료는 24:00입니다. 쉬는 날은 비워 두세요." + }, + tuesday_periods: { + label: "화요일", + help: "캘린더 시간대 기준 그날의 근무 시간대로, HH:mm-HH:mm 형식을 쉼표로 구분합니다(예: 09:00-12:00, 13:00-18:00). 시간대는 같은 날 안에서 시작보다 늦게 끝나야 하며, 가장 늦은 종료는 24:00입니다. 쉬는 날은 비워 두세요." + }, + wednesday_periods: { + label: "수요일", + help: "캘린더 시간대 기준 그날의 근무 시간대로, HH:mm-HH:mm 형식을 쉼표로 구분합니다(예: 09:00-12:00, 13:00-18:00). 시간대는 같은 날 안에서 시작보다 늦게 끝나야 하며, 가장 늦은 종료는 24:00입니다. 쉬는 날은 비워 두세요." + }, + thursday_periods: { + label: "목요일", + help: "캘린더 시간대 기준 그날의 근무 시간대로, HH:mm-HH:mm 형식을 쉼표로 구분합니다(예: 09:00-12:00, 13:00-18:00). 시간대는 같은 날 안에서 시작보다 늦게 끝나야 하며, 가장 늦은 종료는 24:00입니다. 쉬는 날은 비워 두세요." + }, + friday_periods: { + label: "금요일", + help: "캘린더 시간대 기준 그날의 근무 시간대로, HH:mm-HH:mm 형식을 쉼표로 구분합니다(예: 09:00-12:00, 13:00-18:00). 시간대는 같은 날 안에서 시작보다 늦게 끝나야 하며, 가장 늦은 종료는 24:00입니다. 쉬는 날은 비워 두세요." + }, + saturday_periods: { + label: "토요일", + help: "캘린더 시간대 기준 그날의 근무 시간대로, HH:mm-HH:mm 형식을 쉼표로 구분합니다(예: 09:00-12:00, 13:00-18:00). 시간대는 같은 날 안에서 시작보다 늦게 끝나야 하며, 가장 늦은 종료는 24:00입니다. 쉬는 날은 비워 두세요." + }, + sunday_periods: { + label: "일요일", + help: "캘린더 시간대 기준 그날의 근무 시간대로, HH:mm-HH:mm 형식을 쉼표로 구분합니다(예: 09:00-12:00, 13:00-18:00). 시간대는 같은 날 안에서 시작보다 늦게 끝나야 하며, 가장 늦은 종료는 24:00입니다. 쉬는 날은 비워 두세요." + } + }, + _views: { + all_calendars: { + label: "전체", + emptyState: { + title: "아직 근무 캘린더 없음", + message: "주간 근무 시간과 함께 캘린더를 추가하고 하나를 기본값으로 지정한 다음, 공휴일과 대체 근무일을 입력하세요." + } + }, + needs_maintenance: { + label: "관리 필요", + emptyState: { + title: "모든 캘린더가 미리 관리되어 있음", + message: "공휴일 입력이 60일 이내에 끝나는 캘린더가 여기에 표시됩니다. 그 날짜를 넘는 기한 계산은 거부됩니다." + } + } + }, + _validations: { + work_calendar_code_shape: { + message: "코드는 영문 소문자로 시작하고 영문 소문자, 숫자, 밑줄만 사용해야 합니다(예: cn_standard)." + } + } + }, + sys_work_calendar_exception: { + label: "캘린더 예외", + pluralLabel: "캘린더 예외", + description: "근무 캘린더의 날짜별 재정의: 공휴일, 대체 근무일, 휴업일. 근무일에는 그날의 전체 근무 시간대를 입력합니다.", + fields: { + id: { + label: "ID" + }, + calendar: { + label: "캘린더" + }, + date: { + label: "날짜" + }, + kind: { + label: "종류", + help: "휴무일: 하루 종일 쉽니다. 근무일: 아래 시간대로 근무하는 날입니다(예: 대체 근무일).", + options: { + off: "휴무일", + on: "근무일" + } + }, + periods: { + label: "근무 시간대", + help: "근무일이면 그날의 모든 근무 시간을 입력합니다. 요일 설정을 이어받지 않습니다. 캘린더 시간대 기준 그날의 근무 시간대로, HH:mm-HH:mm 형식을 쉼표로 구분합니다(예: 09:00-12:00, 13:00-18:00). 시간대는 같은 날 안에서 시작보다 늦게 끝나야 하며, 가장 늦은 종료는 24:00입니다. 쉬는 날은 비워 두세요." + }, + note: { + label: "메모", + help: "해당 날짜가 무엇인지(예: 국경절, 춘절 대체 근무일)." + } + }, + _views: { + all_exceptions: { + label: "전체", + emptyState: { + title: "아직 캘린더 예외 없음", + message: "공휴일이나 대체 근무일마다 한 행을 추가하거나, 파일에서 1년 치를 가져오세요." + } + } + } } }; diff --git a/packages/platform-objects/src/apps/translations/ko.source-hashes.generated.ts b/packages/platform-objects/src/apps/translations/ko.source-hashes.generated.ts index 411acd1c50d..fa0559d9bbc 100644 --- a/packages/platform-objects/src/apps/translations/ko.source-hashes.generated.ts +++ b/packages/platform-objects/src/apps/translations/ko.source-hashes.generated.ts @@ -152,4 +152,6 @@ export const koGeneratedSourceHashes: Readonly> = { "objects.sys_user._actions.remove_sso_user.label": "27e40f055ed9dc98", "objects.sys_user._actions.remove_sso_user.successMessage": "45facf16a8b5ebc7", "objects.sys_user.fields.source.options.idp_pending": "3751093c5b65b072", + "objects.sys_work_calendar.fields.id.label": "00b0385c9c152888", + "objects.sys_work_calendar_exception.fields.id.label": "00b0385c9c152888", }; diff --git a/packages/platform-objects/src/apps/translations/ko.ts b/packages/platform-objects/src/apps/translations/ko.ts index cd8f7ba6b75..3d2ac860ff8 100644 --- a/packages/platform-objects/src/apps/translations/ko.ts +++ b/packages/platform-objects/src/apps/translations/ko.ts @@ -96,6 +96,8 @@ export const ko: TranslationData = { nav_settings_localization: { label: '현지화' }, nav_exchange_rates: { label: '환율' }, nav_units_of_measure: { label: '측정 단위' }, + nav_work_calendars: { label: '근무 캘린더' }, + nav_work_calendar_exceptions: { label: '캘린더 예외' }, nav_settings_company: { label: '회사' }, nav_settings_mail: { label: '메일 전송' }, nav_settings_sms: { label: 'SMS 전송' }, diff --git a/packages/platform-objects/src/apps/translations/pt-BR.objects.generated.ts b/packages/platform-objects/src/apps/translations/pt-BR.objects.generated.ts index 3e5e728008b..1e9eb992859 100644 --- a/packages/platform-objects/src/apps/translations/pt-BR.objects.generated.ts +++ b/packages/platform-objects/src/apps/translations/pt-BR.objects.generated.ts @@ -4495,5 +4495,128 @@ export const ptBRObjects: NonNullable = { message: "A retired unit cannot be brought back. Create a unit with a new code instead." } } + }, + sys_work_calendar: { + label: "Calendário de trabalho", + pluralLabel: "Calendários de trabalho", + description: "Calendários de trabalho: o horário semanal, o fuso horário em que ele vale e até quando os feriados estão mantidos. Prazos contados em tempo útil os leem.", + fields: { + id: { + label: "ID" + }, + code: { + label: "Código", + help: "Código de máquina pelo qual fórmulas, escalonamentos de aprovação e pacotes nomeiam este calendário, por exemplo cn_standard: letras minúsculas, dígitos e sublinhados." + }, + name: { + label: "Nome" + }, + timezone: { + label: "Fuso horário", + help: "Fuso horário IANA em que os períodos de trabalho valem, por exemplo Asia/Shanghai. O formulário de criação abre com o fuso horário da organização (Configurações → Localização), e uma criação que o omite recebe o mesmo fuso." + }, + is_default: { + label: "Padrão", + help: "O calendário que um prazo usa quando não indica nenhum. Um por organização." + }, + maintained_from: { + label: "Mantido desde", + help: "Primeira data a partir da qual feriados e dias úteis de compensação estão cadastrados. Um cálculo que precise de uma data anterior é recusado." + }, + maintained_through: { + label: "Mantido até", + help: "Última data até a qual feriados e dias úteis de compensação estão cadastrados. Um cálculo que precise de uma data posterior é recusado: cadastre os feriados do próximo ano e depois mova esta data." + }, + monday_periods: { + label: "Segunda-feira", + help: "Períodos de trabalho nesse dia no fuso horário do calendário, HH:mm-HH:mm separados por vírgulas, por exemplo 09:00-12:00, 13:00-18:00. Um período termina depois de começar, no mesmo dia; 24:00 é o término mais tardio. Deixe em branco para um dia de folga." + }, + tuesday_periods: { + label: "Terça-feira", + help: "Períodos de trabalho nesse dia no fuso horário do calendário, HH:mm-HH:mm separados por vírgulas, por exemplo 09:00-12:00, 13:00-18:00. Um período termina depois de começar, no mesmo dia; 24:00 é o término mais tardio. Deixe em branco para um dia de folga." + }, + wednesday_periods: { + label: "Quarta-feira", + help: "Períodos de trabalho nesse dia no fuso horário do calendário, HH:mm-HH:mm separados por vírgulas, por exemplo 09:00-12:00, 13:00-18:00. Um período termina depois de começar, no mesmo dia; 24:00 é o término mais tardio. Deixe em branco para um dia de folga." + }, + thursday_periods: { + label: "Quinta-feira", + help: "Períodos de trabalho nesse dia no fuso horário do calendário, HH:mm-HH:mm separados por vírgulas, por exemplo 09:00-12:00, 13:00-18:00. Um período termina depois de começar, no mesmo dia; 24:00 é o término mais tardio. Deixe em branco para um dia de folga." + }, + friday_periods: { + label: "Sexta-feira", + help: "Períodos de trabalho nesse dia no fuso horário do calendário, HH:mm-HH:mm separados por vírgulas, por exemplo 09:00-12:00, 13:00-18:00. Um período termina depois de começar, no mesmo dia; 24:00 é o término mais tardio. Deixe em branco para um dia de folga." + }, + saturday_periods: { + label: "Sábado", + help: "Períodos de trabalho nesse dia no fuso horário do calendário, HH:mm-HH:mm separados por vírgulas, por exemplo 09:00-12:00, 13:00-18:00. Um período termina depois de começar, no mesmo dia; 24:00 é o término mais tardio. Deixe em branco para um dia de folga." + }, + sunday_periods: { + label: "Domingo", + help: "Períodos de trabalho nesse dia no fuso horário do calendário, HH:mm-HH:mm separados por vírgulas, por exemplo 09:00-12:00, 13:00-18:00. Um período termina depois de começar, no mesmo dia; 24:00 é o término mais tardio. Deixe em branco para um dia de folga." + } + }, + _views: { + all_calendars: { + label: "Todas", + emptyState: { + title: "Nenhum calendário de trabalho ainda", + message: "Adicione um calendário com seu horário semanal e marque um como padrão; depois cadastre seus feriados e dias úteis de compensação." + } + }, + needs_maintenance: { + label: "Precisa de manutenção", + emptyState: { + title: "Todos os calendários estão mantidos com antecedência", + message: "Um calendário aparece aqui quando seus feriados acabam nos próximos 60 dias; prazos além dessa data são recusados." + } + } + }, + _validations: { + work_calendar_code_shape: { + message: "O código deve começar com uma letra minúscula e usar apenas letras minúsculas, dígitos e sublinhados, por exemplo cn_standard." + } + } + }, + sys_work_calendar_exception: { + label: "Exceção de calendário", + pluralLabel: "Exceções de calendário", + description: "Exceções datadas de um calendário de trabalho: feriados, dias úteis de compensação e paralisações. Um dia útil traz seus períodos de trabalho completos.", + fields: { + id: { + label: "ID" + }, + calendar: { + label: "Calendário" + }, + date: { + label: "Data" + }, + kind: { + label: "Tipo", + help: "Folga: a data inteira é de folga. Dia útil: a data é trabalhada com os períodos abaixo, por exemplo um dia útil de compensação.", + options: { + off: "Folga", + on: "Dia útil" + } + }, + periods: { + label: "Períodos", + help: "Para um dia útil, todas as horas dessa data; nunca são herdadas do dia da semana. Períodos de trabalho nesse dia no fuso horário do calendário, HH:mm-HH:mm separados por vírgulas, por exemplo 09:00-12:00, 13:00-18:00. Um período termina depois de começar, no mesmo dia; 24:00 é o término mais tardio. Deixe em branco para um dia de folga." + }, + note: { + label: "Observação", + help: "O que é a data, por exemplo o Dia Nacional ou um dia útil de compensação do Festival da Primavera." + } + }, + _views: { + all_exceptions: { + label: "Todas", + emptyState: { + title: "Nenhuma exceção de calendário ainda", + message: "Adicione uma linha por feriado ou dia útil de compensação, ou importe um ano deles de um arquivo." + } + } + } } }; diff --git a/packages/platform-objects/src/apps/translations/pt-BR.source-hashes.generated.ts b/packages/platform-objects/src/apps/translations/pt-BR.source-hashes.generated.ts index 12ea7be5231..7b83f1bca2c 100644 --- a/packages/platform-objects/src/apps/translations/pt-BR.source-hashes.generated.ts +++ b/packages/platform-objects/src/apps/translations/pt-BR.source-hashes.generated.ts @@ -196,4 +196,6 @@ export const ptBRGeneratedSourceHashes: Readonly> = { "objects.sys_user._actions.remove_sso_user.label": "27e40f055ed9dc98", "objects.sys_user._actions.remove_sso_user.successMessage": "45facf16a8b5ebc7", "objects.sys_user.fields.source.options.idp_pending": "3751093c5b65b072", + "objects.sys_work_calendar.fields.id.label": "00b0385c9c152888", + "objects.sys_work_calendar_exception.fields.id.label": "00b0385c9c152888", }; diff --git a/packages/platform-objects/src/apps/translations/pt-BR.ts b/packages/platform-objects/src/apps/translations/pt-BR.ts index 02bd5fd65d2..654a0abe4fc 100644 --- a/packages/platform-objects/src/apps/translations/pt-BR.ts +++ b/packages/platform-objects/src/apps/translations/pt-BR.ts @@ -97,6 +97,8 @@ export const ptBR: TranslationData = { nav_settings_localization: { label: 'Localização' }, nav_exchange_rates: { label: 'Taxas de câmbio' }, nav_units_of_measure: { label: 'Unidades de medida' }, + nav_work_calendars: { label: 'Calendários de trabalho' }, + nav_work_calendar_exceptions: { label: 'Exceções de calendário' }, nav_settings_company: { label: 'Empresa' }, nav_settings_mail: { label: 'Envio de e-mail' }, nav_settings_sms: { label: 'Envio de SMS' }, diff --git a/packages/platform-objects/src/apps/translations/ru.objects.generated.ts b/packages/platform-objects/src/apps/translations/ru.objects.generated.ts index 954dc22ecb8..d78bbd61631 100644 --- a/packages/platform-objects/src/apps/translations/ru.objects.generated.ts +++ b/packages/platform-objects/src/apps/translations/ru.objects.generated.ts @@ -4495,5 +4495,128 @@ export const ruObjects: NonNullable = { message: "A retired unit cannot be brought back. Create a unit with a new code instead." } } + }, + sys_work_calendar: { + label: "Рабочий календарь", + pluralLabel: "Рабочие календари", + description: "Рабочие календари: еженедельный график работы, часовой пояс, в котором он действует, и дата, до которой внесены праздники. Сроки, отсчитываемые в рабочем времени, берутся из них.", + fields: { + id: { + label: "ID" + }, + code: { + label: "Код", + help: "Машинный код, по которому формулы, эскалации согласований и пакеты ссылаются на этот календарь, например cn_standard: строчные латинские буквы, цифры и подчёркивания." + }, + name: { + label: "Название" + }, + timezone: { + label: "Часовой пояс", + help: "Часовой пояс IANA, в котором действуют рабочие интервалы, например Asia/Shanghai. Форма создания открывается с часовым поясом организации (Настройки → Локализация), и запись, созданная без него, получает тот же пояс." + }, + is_default: { + label: "По умолчанию", + help: "Календарь, который используется для срока, если календарь не указан. Один на организацию." + }, + maintained_from: { + label: "Ведётся с", + help: "Первая дата, начиная с которой внесены праздники и рабочие дни переноса. Расчёт, которому нужна более ранняя дата, отклоняется." + }, + maintained_through: { + label: "Ведётся по", + help: "Последняя дата, по которую внесены праздники и рабочие дни переноса. Расчёт, которому нужна более поздняя дата, отклоняется: внесите праздники следующего года, затем передвиньте эту дату." + }, + monday_periods: { + label: "Понедельник", + help: "Рабочие интервалы в этот день в часовом поясе календаря, HH:mm-HH:mm через запятую, например 09:00-12:00, 13:00-18:00. Интервал заканчивается позже, чем начинается, в тот же день; самое позднее окончание — 24:00. Оставьте пустым для выходного." + }, + tuesday_periods: { + label: "Вторник", + help: "Рабочие интервалы в этот день в часовом поясе календаря, HH:mm-HH:mm через запятую, например 09:00-12:00, 13:00-18:00. Интервал заканчивается позже, чем начинается, в тот же день; самое позднее окончание — 24:00. Оставьте пустым для выходного." + }, + wednesday_periods: { + label: "Среда", + help: "Рабочие интервалы в этот день в часовом поясе календаря, HH:mm-HH:mm через запятую, например 09:00-12:00, 13:00-18:00. Интервал заканчивается позже, чем начинается, в тот же день; самое позднее окончание — 24:00. Оставьте пустым для выходного." + }, + thursday_periods: { + label: "Четверг", + help: "Рабочие интервалы в этот день в часовом поясе календаря, HH:mm-HH:mm через запятую, например 09:00-12:00, 13:00-18:00. Интервал заканчивается позже, чем начинается, в тот же день; самое позднее окончание — 24:00. Оставьте пустым для выходного." + }, + friday_periods: { + label: "Пятница", + help: "Рабочие интервалы в этот день в часовом поясе календаря, HH:mm-HH:mm через запятую, например 09:00-12:00, 13:00-18:00. Интервал заканчивается позже, чем начинается, в тот же день; самое позднее окончание — 24:00. Оставьте пустым для выходного." + }, + saturday_periods: { + label: "Суббота", + help: "Рабочие интервалы в этот день в часовом поясе календаря, HH:mm-HH:mm через запятую, например 09:00-12:00, 13:00-18:00. Интервал заканчивается позже, чем начинается, в тот же день; самое позднее окончание — 24:00. Оставьте пустым для выходного." + }, + sunday_periods: { + label: "Воскресенье", + help: "Рабочие интервалы в этот день в часовом поясе календаря, HH:mm-HH:mm через запятую, например 09:00-12:00, 13:00-18:00. Интервал заканчивается позже, чем начинается, в тот же день; самое позднее окончание — 24:00. Оставьте пустым для выходного." + } + }, + _views: { + all_calendars: { + label: "Все", + emptyState: { + title: "Рабочих календарей пока нет", + message: "Добавьте календарь с еженедельным графиком и отметьте один как календарь по умолчанию, затем внесите его праздники и рабочие дни переноса." + } + }, + needs_maintenance: { + label: "Требует обновления", + emptyState: { + title: "Все календари заполнены наперёд", + message: "Календарь появляется здесь, когда его праздники заканчиваются в ближайшие 60 дней; сроки после этой даты отклоняются." + } + } + }, + _validations: { + work_calendar_code_shape: { + message: "Код должен начинаться со строчной латинской буквы и содержать только строчные латинские буквы, цифры и подчёркивания, например cn_standard." + } + } + }, + sys_work_calendar_exception: { + label: "Исключение календаря", + pluralLabel: "Исключения календаря", + description: "Датированные исключения из рабочего календаря: праздники, рабочие дни переноса и простои. Рабочий день содержит полный набор рабочих интервалов.", + fields: { + id: { + label: "ID" + }, + calendar: { + label: "Календарь" + }, + date: { + label: "Дата" + }, + kind: { + label: "Тип", + help: "Выходной: вся дата нерабочая. Рабочий день: в эту дату работают по интервалам ниже, например рабочий день переноса.", + options: { + off: "Выходной", + on: "Рабочий день" + } + }, + periods: { + label: "Интервалы", + help: "Для рабочего дня — все часы этой даты; они никогда не берутся из дня недели. Рабочие интервалы в этот день в часовом поясе календаря, HH:mm-HH:mm через запятую, например 09:00-12:00, 13:00-18:00. Интервал заканчивается позже, чем начинается, в тот же день; самое позднее окончание — 24:00. Оставьте пустым для выходного." + }, + note: { + label: "Примечание", + help: "Что это за дата, например Национальный день или рабочий день переноса к Празднику весны." + } + }, + _views: { + all_exceptions: { + label: "Все", + emptyState: { + title: "Исключений календаря пока нет", + message: "Добавьте по строке на каждый праздник или рабочий день переноса либо импортируйте их за год из файла." + } + } + } } }; diff --git a/packages/platform-objects/src/apps/translations/ru.source-hashes.generated.ts b/packages/platform-objects/src/apps/translations/ru.source-hashes.generated.ts index 23dd8275115..448291c5695 100644 --- a/packages/platform-objects/src/apps/translations/ru.source-hashes.generated.ts +++ b/packages/platform-objects/src/apps/translations/ru.source-hashes.generated.ts @@ -151,4 +151,6 @@ export const ruGeneratedSourceHashes: Readonly> = { "objects.sys_user._actions.remove_sso_user.label": "27e40f055ed9dc98", "objects.sys_user._actions.remove_sso_user.successMessage": "45facf16a8b5ebc7", "objects.sys_user.fields.source.options.idp_pending": "3751093c5b65b072", + "objects.sys_work_calendar.fields.id.label": "00b0385c9c152888", + "objects.sys_work_calendar_exception.fields.id.label": "00b0385c9c152888", }; diff --git a/packages/platform-objects/src/apps/translations/ru.ts b/packages/platform-objects/src/apps/translations/ru.ts index ccad773ff3e..5efdec002b1 100644 --- a/packages/platform-objects/src/apps/translations/ru.ts +++ b/packages/platform-objects/src/apps/translations/ru.ts @@ -97,6 +97,8 @@ export const ru: TranslationData = { nav_settings_localization: { label: 'Локализация' }, nav_exchange_rates: { label: 'Курсы валют' }, nav_units_of_measure: { label: 'Единицы измерения' }, + nav_work_calendars: { label: 'Рабочие календари' }, + nav_work_calendar_exceptions: { label: 'Исключения календаря' }, nav_settings_company: { label: 'Компания' }, nav_settings_mail: { label: 'Доставка почты' }, nav_settings_sms: { label: 'Доставка SMS' }, diff --git a/packages/platform-objects/src/apps/translations/zh-CN.objects.generated.ts b/packages/platform-objects/src/apps/translations/zh-CN.objects.generated.ts index 61d876999d5..ea97d7ed86c 100644 --- a/packages/platform-objects/src/apps/translations/zh-CN.objects.generated.ts +++ b/packages/platform-objects/src/apps/translations/zh-CN.objects.generated.ts @@ -4495,5 +4495,128 @@ export const zhCNObjects: NonNullable = { message: "已停用的单位不能恢复。请用新代码新建一个单位。" } } + }, + sys_work_calendar: { + label: "工作日历", + pluralLabel: "工作日历", + description: "工作日历:每周的工作时段、时段所在的时区,以及节假日维护到哪一天。按工作时间计算的到期日读取它们。", + fields: { + id: { + label: "ID" + }, + code: { + label: "代码", + help: "公式、审批升级和软件包用来指称此日历的机器代码,如 cn_standard:仅限小写字母、数字和下划线。" + }, + name: { + label: "名称" + }, + timezone: { + label: "时区", + help: "工作时段所在的 IANA 时区,如 Asia/Shanghai。新建表单会预填组织的时区(设置 → 本地化);创建时留空也取同一时区。" + }, + is_default: { + label: "默认", + help: "到期日未指定日历时使用的日历。每个组织一个。" + }, + maintained_from: { + label: "维护起始日", + help: "节假日和调休工作日从这一天开始录入。需要更早日期的计算会被拒绝。" + }, + maintained_through: { + label: "维护截止日", + help: "节假日和调休工作日录入到这一天为止。需要更晚日期的计算会被拒绝:请录入下一年的节假日,再顺延此日期。" + }, + monday_periods: { + label: "星期一", + help: "当天的工作时段,按日历的时区计,格式为 HH:mm-HH:mm,多个时段用逗号分隔,如 09:00-12:00, 13:00-18:00。时段须在同一天内且结束晚于开始;最晚结束为 24:00。留空表示当天休息。" + }, + tuesday_periods: { + label: "星期二", + help: "当天的工作时段,按日历的时区计,格式为 HH:mm-HH:mm,多个时段用逗号分隔,如 09:00-12:00, 13:00-18:00。时段须在同一天内且结束晚于开始;最晚结束为 24:00。留空表示当天休息。" + }, + wednesday_periods: { + label: "星期三", + help: "当天的工作时段,按日历的时区计,格式为 HH:mm-HH:mm,多个时段用逗号分隔,如 09:00-12:00, 13:00-18:00。时段须在同一天内且结束晚于开始;最晚结束为 24:00。留空表示当天休息。" + }, + thursday_periods: { + label: "星期四", + help: "当天的工作时段,按日历的时区计,格式为 HH:mm-HH:mm,多个时段用逗号分隔,如 09:00-12:00, 13:00-18:00。时段须在同一天内且结束晚于开始;最晚结束为 24:00。留空表示当天休息。" + }, + friday_periods: { + label: "星期五", + help: "当天的工作时段,按日历的时区计,格式为 HH:mm-HH:mm,多个时段用逗号分隔,如 09:00-12:00, 13:00-18:00。时段须在同一天内且结束晚于开始;最晚结束为 24:00。留空表示当天休息。" + }, + saturday_periods: { + label: "星期六", + help: "当天的工作时段,按日历的时区计,格式为 HH:mm-HH:mm,多个时段用逗号分隔,如 09:00-12:00, 13:00-18:00。时段须在同一天内且结束晚于开始;最晚结束为 24:00。留空表示当天休息。" + }, + sunday_periods: { + label: "星期日", + help: "当天的工作时段,按日历的时区计,格式为 HH:mm-HH:mm,多个时段用逗号分隔,如 09:00-12:00, 13:00-18:00。时段须在同一天内且结束晚于开始;最晚结束为 24:00。留空表示当天休息。" + } + }, + _views: { + all_calendars: { + label: "全部", + emptyState: { + title: "还没有工作日历", + message: "添加一个日历并填写每周工作时段,将其中一个设为默认,然后录入它的节假日和调休工作日。" + } + }, + needs_maintenance: { + label: "待维护", + emptyState: { + title: "所有日历都已提前维护", + message: "节假日将在 60 天内用完的日历会出现在这里;超出该日期的到期日计算会被拒绝。" + } + } + }, + _validations: { + work_calendar_code_shape: { + message: "代码须以小写字母开头,且只能包含小写字母、数字和下划线,如 cn_standard。" + } + } + }, + sys_work_calendar_exception: { + label: "日历例外", + pluralLabel: "日历例外", + description: "工作日历的按日期覆盖:法定节假日、调休工作日和停工日。工作日须带上当天完整的工作时段。", + fields: { + id: { + label: "ID" + }, + calendar: { + label: "日历" + }, + date: { + label: "日期" + }, + kind: { + label: "类型", + help: "休息日:整天休息。工作日:当天按下方时段上班,如调休工作日。", + options: { + off: "休息日", + on: "工作日" + } + }, + periods: { + label: "工作时段", + help: "工作日须填写当天的全部工作时间,不会从对应星期的时段继承。当天的工作时段,按日历的时区计,格式为 HH:mm-HH:mm,多个时段用逗号分隔,如 09:00-12:00, 13:00-18:00。时段须在同一天内且结束晚于开始;最晚结束为 24:00。留空表示当天休息。" + }, + note: { + label: "备注", + help: "该日期是什么,如国庆节或春节调休工作日。" + } + }, + _views: { + all_exceptions: { + label: "全部", + emptyState: { + title: "还没有日历例外", + message: "每个节假日或调休工作日录一行,或从文件导入一整年的数据。" + } + } + } } }; diff --git a/packages/platform-objects/src/apps/translations/zh-CN.source-hashes.generated.ts b/packages/platform-objects/src/apps/translations/zh-CN.source-hashes.generated.ts index efbf3898dfc..eee746ae3fc 100644 --- a/packages/platform-objects/src/apps/translations/zh-CN.source-hashes.generated.ts +++ b/packages/platform-objects/src/apps/translations/zh-CN.source-hashes.generated.ts @@ -92,4 +92,6 @@ export const zhCNGeneratedSourceHashes: Readonly> = { "objects.sys_unit.fields.id.label": "00b0385c9c152888", "objects.sys_user._actions.import_sso_users.params.csv.label": "bfb77802b66a9222", "objects.sys_user.fields.source.options.idp_pending": "3751093c5b65b072", + "objects.sys_work_calendar.fields.id.label": "00b0385c9c152888", + "objects.sys_work_calendar_exception.fields.id.label": "00b0385c9c152888", }; diff --git a/packages/platform-objects/src/apps/translations/zh-CN.ts b/packages/platform-objects/src/apps/translations/zh-CN.ts index d90a82dca05..3bbf4596e63 100644 --- a/packages/platform-objects/src/apps/translations/zh-CN.ts +++ b/packages/platform-objects/src/apps/translations/zh-CN.ts @@ -90,6 +90,8 @@ export const zhCN: TranslationData = { nav_settings_localization: { label: '本地化' }, nav_exchange_rates: { label: '汇率' }, nav_units_of_measure: { label: '计量单位' }, + nav_work_calendars: { label: '工作日历' }, + nav_work_calendar_exceptions: { label: '日历例外' }, nav_settings_company: { label: '公司' }, nav_settings_mail: { label: '邮件投递' }, nav_settings_sms: { label: '短信投递' }, diff --git a/packages/platform-objects/src/apps/translations/zh-Hant.objects.generated.ts b/packages/platform-objects/src/apps/translations/zh-Hant.objects.generated.ts index 1b8d0495af9..fd9801bbbfa 100644 --- a/packages/platform-objects/src/apps/translations/zh-Hant.objects.generated.ts +++ b/packages/platform-objects/src/apps/translations/zh-Hant.objects.generated.ts @@ -4495,5 +4495,128 @@ export const zhHantObjects: NonNullable = { message: "A retired unit cannot be brought back. Create a unit with a new code instead." } } + }, + sys_work_calendar: { + label: "工作日曆", + pluralLabel: "工作日曆", + description: "工作日曆:每週的工作時段、時段所在的時區,以及假日維護到哪一天。依工作時間計算的到期日會讀取它們。", + fields: { + id: { + label: "ID" + }, + code: { + label: "代碼", + help: "公式、審批升級與套件用來指稱此日曆的機器代碼,如 cn_standard:僅限小寫字母、數字和底線。" + }, + name: { + label: "名稱" + }, + timezone: { + label: "時區", + help: "工作時段所在的 IANA 時區,如 Asia/Shanghai。新增表單會預填組織的時區(設定 → 在地化);建立時留空也取同一時區。" + }, + is_default: { + label: "預設", + help: "到期日未指定日曆時使用的日曆。每個組織一個。" + }, + maintained_from: { + label: "維護起始日", + help: "假日與補班日從這一天開始登錄。需要更早日期的計算會被拒絕。" + }, + maintained_through: { + label: "維護截止日", + help: "假日與補班日登錄到這一天為止。需要更晚日期的計算會被拒絕:請登錄下一年的假日,再順延此日期。" + }, + monday_periods: { + label: "星期一", + help: "當天的工作時段,依日曆的時區計,格式為 HH:mm-HH:mm,多個時段以逗號分隔,如 09:00-12:00, 13:00-18:00。時段須在同一天內且結束晚於開始;最晚結束為 24:00。留空表示當天休息。" + }, + tuesday_periods: { + label: "星期二", + help: "當天的工作時段,依日曆的時區計,格式為 HH:mm-HH:mm,多個時段以逗號分隔,如 09:00-12:00, 13:00-18:00。時段須在同一天內且結束晚於開始;最晚結束為 24:00。留空表示當天休息。" + }, + wednesday_periods: { + label: "星期三", + help: "當天的工作時段,依日曆的時區計,格式為 HH:mm-HH:mm,多個時段以逗號分隔,如 09:00-12:00, 13:00-18:00。時段須在同一天內且結束晚於開始;最晚結束為 24:00。留空表示當天休息。" + }, + thursday_periods: { + label: "星期四", + help: "當天的工作時段,依日曆的時區計,格式為 HH:mm-HH:mm,多個時段以逗號分隔,如 09:00-12:00, 13:00-18:00。時段須在同一天內且結束晚於開始;最晚結束為 24:00。留空表示當天休息。" + }, + friday_periods: { + label: "星期五", + help: "當天的工作時段,依日曆的時區計,格式為 HH:mm-HH:mm,多個時段以逗號分隔,如 09:00-12:00, 13:00-18:00。時段須在同一天內且結束晚於開始;最晚結束為 24:00。留空表示當天休息。" + }, + saturday_periods: { + label: "星期六", + help: "當天的工作時段,依日曆的時區計,格式為 HH:mm-HH:mm,多個時段以逗號分隔,如 09:00-12:00, 13:00-18:00。時段須在同一天內且結束晚於開始;最晚結束為 24:00。留空表示當天休息。" + }, + sunday_periods: { + label: "星期日", + help: "當天的工作時段,依日曆的時區計,格式為 HH:mm-HH:mm,多個時段以逗號分隔,如 09:00-12:00, 13:00-18:00。時段須在同一天內且結束晚於開始;最晚結束為 24:00。留空表示當天休息。" + } + }, + _views: { + all_calendars: { + label: "全部", + emptyState: { + title: "還沒有工作日曆", + message: "新增一個日曆並填寫每週工作時段,將其中一個設為預設,然後登錄它的假日與補班日。" + } + }, + needs_maintenance: { + label: "待維護", + emptyState: { + title: "所有日曆都已提前維護", + message: "假日將在 60 天內用完的日曆會出現在這裡;超出該日期的到期日計算會被拒絕。" + } + } + }, + _validations: { + work_calendar_code_shape: { + message: "代碼須以小寫字母開頭,且只能包含小寫字母、數字和底線,如 cn_standard。" + } + } + }, + sys_work_calendar_exception: { + label: "日曆例外", + pluralLabel: "日曆例外", + description: "工作日曆的依日期覆寫:國定假日、補班日與停工日。工作日須帶上當天完整的工作時段。", + fields: { + id: { + label: "ID" + }, + calendar: { + label: "日曆" + }, + date: { + label: "日期" + }, + kind: { + label: "類型", + help: "休息日:整天休息。工作日:當天依下方時段上班,如補班日。", + options: { + off: "休息日", + on: "工作日" + } + }, + periods: { + label: "工作時段", + help: "工作日須填寫當天的全部工作時間,不會從對應星期的時段繼承。當天的工作時段,依日曆的時區計,格式為 HH:mm-HH:mm,多個時段以逗號分隔,如 09:00-12:00, 13:00-18:00。時段須在同一天內且結束晚於開始;最晚結束為 24:00。留空表示當天休息。" + }, + note: { + label: "備註", + help: "該日期是什麼,如國慶日或春節補班日。" + } + }, + _views: { + all_exceptions: { + label: "全部", + emptyState: { + title: "還沒有日曆例外", + message: "每個假日或補班日登錄一列,或從檔案匯入一整年的資料。" + } + } + } } }; diff --git a/packages/platform-objects/src/apps/translations/zh-Hant.source-hashes.generated.ts b/packages/platform-objects/src/apps/translations/zh-Hant.source-hashes.generated.ts index 4687a89b941..ddfb741fe91 100644 --- a/packages/platform-objects/src/apps/translations/zh-Hant.source-hashes.generated.ts +++ b/packages/platform-objects/src/apps/translations/zh-Hant.source-hashes.generated.ts @@ -145,4 +145,6 @@ export const zhHantGeneratedSourceHashes: Readonly> = { "objects.sys_user._actions.remove_sso_user.label": "27e40f055ed9dc98", "objects.sys_user._actions.remove_sso_user.successMessage": "45facf16a8b5ebc7", "objects.sys_user.fields.source.options.idp_pending": "3751093c5b65b072", + "objects.sys_work_calendar.fields.id.label": "00b0385c9c152888", + "objects.sys_work_calendar_exception.fields.id.label": "00b0385c9c152888", }; diff --git a/packages/platform-objects/src/apps/translations/zh-Hant.ts b/packages/platform-objects/src/apps/translations/zh-Hant.ts index 4f231af1a92..1fbe2060100 100644 --- a/packages/platform-objects/src/apps/translations/zh-Hant.ts +++ b/packages/platform-objects/src/apps/translations/zh-Hant.ts @@ -95,6 +95,8 @@ export const zhHant: TranslationData = { nav_settings_localization: { label: '在地化' }, nav_exchange_rates: { label: '匯率' }, nav_units_of_measure: { label: '計量單位' }, + nav_work_calendars: { label: '工作日曆' }, + nav_work_calendar_exceptions: { label: '日曆例外' }, nav_settings_company: { label: '公司' }, nav_settings_mail: { label: '郵件投遞' }, nav_settings_sms: { label: '簡訊投遞' }, diff --git a/packages/platform-objects/src/platform-objects.test.ts b/packages/platform-objects/src/platform-objects.test.ts index c61106bdeb4..9f8f2b235f8 100644 --- a/packages/platform-objects/src/platform-objects.test.ts +++ b/packages/platform-objects/src/platform-objects.test.ts @@ -37,7 +37,7 @@ import { SysMetadata, SysMetadataHistoryObject, } from './metadata/index.js'; -import { SysExchangeRate, SysSecret, SysSetting, SysUnit } from './system/index.js'; +import { SysExchangeRate, SysSecret, SysSetting, SysUnit, SysWorkCalendar, SysWorkCalendarException } from './system/index.js'; import { ACCOUNT_APP, SETUP_APP, SETUP_NAV_CONTRIBUTIONS, STUDIO_APP } from './apps/index.js'; import { AppSchema } from '@objectstack/spec/ui'; import { resolveEffectiveApiMethods, isApiOperationAllowed, canServeApiOperation } from '@objectstack/spec/data'; @@ -610,6 +610,8 @@ describe('@objectstack/platform-objects', () => { sys_unit: SysUnit, sys_user: SysUser, sys_user_preference: SysUserPreference, + sys_work_calendar: SysWorkCalendar, + sys_work_calendar_exception: SysWorkCalendarException, }; // Targets owned by another package (contributed there, gated by // `requiresObject`), so nothing here can read their `enable`. Named diff --git a/packages/platform-objects/src/plugin.test.ts b/packages/platform-objects/src/plugin.test.ts index 11f0f2520d6..2169b0a770d 100644 --- a/packages/platform-objects/src/plugin.test.ts +++ b/packages/platform-objects/src/plugin.test.ts @@ -11,7 +11,7 @@ import { describe, it, expect } from 'vitest'; import { assertEngineFindOnePredicate, assertEngineUpdateDispatch } from '@objectstack/metadata-core'; import { ObjectSchema, RECYCLE_BIN_ENTRY_FIELDS, RECYCLE_BIN_OBJECT } from '@objectstack/spec/data'; import { PlatformObjectsPlugin } from './plugin.js'; -import { SysExchangeRate, SysUnit, SysLifecycleState, SysMetadataActivation, SysMigration, SysMigrationJournal, SysRecycleBin, SysSecret, SysSeedLandedKey, SysTrustedKey } from './system/index.js'; +import { SysExchangeRate, SysUnit, SysLifecycleState, SysMetadataActivation, SysMigration, SysMigrationJournal, SysRecycleBin, SysSecret, SysSeedLandedKey, SysTrustedKey, SysWorkCalendar, SysWorkCalendarException } from './system/index.js'; /** * Hand-rolled fake PluginContext (mirrors the service-plugin tests) — this @@ -47,7 +47,7 @@ function makeCtx() { } describe('PlatformObjectsPlugin: platform-infrastructure object registration (#4243, #4270)', () => { - it('registers SysMigration, SysMigrationJournal, SysSecret, SysExchangeRate, SysUnit, SysTrustedKey, SysLifecycleState, SysRecycleBin and SysSeedLandedKey through the manifest service', async () => { + it('registers SysMigration, SysMigrationJournal, SysSecret, SysExchangeRate, SysUnit, SysWorkCalendar, SysWorkCalendarException, SysTrustedKey, SysLifecycleState, SysRecycleBin and SysSeedLandedKey through the manifest service', async () => { const ctx = makeCtx(); const manifests: any[] = []; ctx.registerService('manifest', { register: (m: any) => manifests.push(m) }); @@ -57,7 +57,7 @@ describe('PlatformObjectsPlugin: platform-infrastructure object registration (#4 const infra = manifests.find((m) => m.id === 'com.objectstack.platform-objects'); expect(infra).toBeDefined(); expect(infra.scope).toBe('system'); - expect(infra.objects).toEqual([SysMigration, SysMigrationJournal, SysSecret, SysExchangeRate, SysUnit, SysTrustedKey, SysLifecycleState, SysRecycleBin, SysSeedLandedKey]); + expect(infra.objects).toEqual([SysMigration, SysMigrationJournal, SysSecret, SysExchangeRate, SysUnit, SysWorkCalendar, SysWorkCalendarException, SysTrustedKey, SysLifecycleState, SysRecycleBin, SysSeedLandedKey]); expect(infra.objects.map((o: any) => o.name)).toEqual([ 'sys_migration', // ADR-0119 D2 (#4617). Registered UNCONDITIONALLY, alongside the flag @@ -74,6 +74,10 @@ describe('PlatformObjectsPlugin: platform-infrastructure object registration (#4 // read by the engine's unit membership check and by the display of a // quantity with its unit, so it registers beside the exchange rates. 'sys_unit', + // [ADR-0157 D1] Working calendars and their exceptions, read by the + // engine's calendar service; organization data on the project database. + 'sys_work_calendar', + 'sys_work_calendar_exception', // [ADR-0025 §3.5 M1, #27123] The environment's trusted plugin-publisher // keys, read by `os plugin install` from a one-shot boot that composes // this plugin and nothing that would register it otherwise. diff --git a/packages/platform-objects/src/plugin.ts b/packages/platform-objects/src/plugin.ts index 1ae62e63402..32062c8b629 100644 --- a/packages/platform-objects/src/plugin.ts +++ b/packages/platform-objects/src/plugin.ts @@ -8,6 +8,8 @@ import { SysMigrationJournal } from './system/sys-migration-journal.object.js'; import { SysSecret } from './system/sys-secret.object.js'; import { SysExchangeRate } from './system/sys-exchange-rate.object.js'; import { SysUnit } from './system/sys-unit.object.js'; +import { SysWorkCalendar } from './system/sys-work-calendar.object.js'; +import { SysWorkCalendarException } from './system/sys-work-calendar-exception.object.js'; import { SysTrustedKey } from './system/sys-trusted-key.object.js'; import { SysLifecycleState } from './system/sys-lifecycle-state.object.js'; import { SysRecycleBin } from './system/sys-recycle-bin.object.js'; @@ -121,6 +123,12 @@ import { SEED_SETTLEMENT_SERVICE } from '@objectstack/spec/contracts'; * in every composition that can write or read a record, so it has no * on/off capability boundary of its own (ADR-0029 D2) and registers here, * in the first manifest beside the exchange rates. + * - **`sys_work_calendar`** / **`sys_work_calendar_exception`** — the + * organization's working calendars and their dated holidays and make-up + * workdays (ADR-0157 D1). Registered here for the reason the rate table + * is: their readers are the ObjectQL engine's calendar service and what it + * serves — the working-day formula functions and the approval sweep's + * working-time clock — not one optional service. Same manifest. * - **Fresh-datastore attestation** (#3438, ADR-0104 2026-07-30) — * travels with the ledger registration: a store this boot created from * empty is attested once that boot's own data has settled @@ -230,7 +238,7 @@ export class PlatformObjectsPlugin { version: this.version, type: 'plugin', scope: 'system', - objects: [SysMigration, SysMigrationJournal, SysSecret, SysExchangeRate, SysUnit, SysTrustedKey, SysLifecycleState, SysRecycleBin, SysSeedLandedKey], + objects: [SysMigration, SysMigrationJournal, SysSecret, SysExchangeRate, SysUnit, SysWorkCalendar, SysWorkCalendarException, SysTrustedKey, SysLifecycleState, SysRecycleBin, SysSeedLandedKey], }); ctx?.getService?.('manifest')?.register?.({ ...ACTIVATION_LEDGER_MANIFEST, diff --git a/packages/platform-objects/src/system/index.ts b/packages/platform-objects/src/system/index.ts index 3a49d55eb48..596236bca98 100644 --- a/packages/platform-objects/src/system/index.ts +++ b/packages/platform-objects/src/system/index.ts @@ -47,6 +47,13 @@ export { UNIT_RATIO_PRECISION, UNIT_DECIMAL_PLACES_MAX, } from './sys-unit.object.js'; +// [ADR-0157 D1] Working calendars and their dated exceptions, read by the +// calendar service (`@objectstack/objectql`). +export { + SysWorkCalendar, + WORK_CALENDAR_PERIODS_HELP, +} from './sys-work-calendar.object.js'; +export { SysWorkCalendarException } from './sys-work-calendar-exception.object.js'; export { readDataMigrationFlag, isDataMigrationVerified, diff --git a/packages/platform-objects/src/system/sys-work-calendar-exception.object.ts b/packages/platform-objects/src/system/sys-work-calendar-exception.object.ts new file mode 100644 index 00000000000..07a80c252d6 --- /dev/null +++ b/packages/platform-objects/src/system/sys-work-calendar-exception.object.ts @@ -0,0 +1,126 @@ +// Copyright (c) 2026 ObjectStack. Licensed under the Apache-2.0 license. + +import { ObjectSchema, Field } from '@objectstack/spec/data'; +import { WORK_CALENDAR_PERIODS_HELP } from './sys-work-calendar.object.js'; + +/** + * sys_work_calendar_exception — Calendar Exception (ADR-0157 D1, D10) + * + * One dated override of a working calendar's weekly pattern. One table holds + * public holidays, 调休 make-up workdays and plant shutdowns: + * + * - **`off`** — the whole date is off, and the row carries no periods. + * - **`on`** — the date is worked, and the row carries that date's FULL + * periods (a half day is shortened periods). It never borrows its weekday's: + * with borrowing, a later edit to the weekday would silently rewrite every + * past make-up day (D10, 「每条写全时段」). + * + * One row per calendar and date (the unique key below). The date is a calendar + * day, never an instant (ADR-0053). The period format and its validation are + * the calendar's ({@link WORK_CALENDAR_PERIODS_HELP}, which the `periods` help reuses), + * refused at write by the calendar service's hooks (`@objectstack/objectql`). + * Tenancy, write grant and audit as `sys_work_calendar`. Deleting a calendar + * deletes its exceptions. + * + * **Import** — opt-in on `system-data`, as `sys_exchange_rate` opts in: an + * administrator loads a year of holidays in one file through the generic + * import door (`sys_import_job`). The `calendar` column names the calendar by + * its code or its name; a line repeating a (calendar, date) on file is refused + * for that row alone by the unique key. + * + * @namespace sys + */ +export const SysWorkCalendarException = ObjectSchema.create({ + name: 'sys_work_calendar_exception', + label: 'Calendar Exception', + pluralLabel: 'Calendar Exceptions', + icon: 'calendar-x', + isSystem: true, + // Platform-defined schema, organization-administered data. + managedBy: 'system-data', + userActions: { import: true }, + description: + 'Dated overrides of a working calendar: public holidays, make-up workdays and shutdowns. ' + + 'A working day carries its full working periods.', + displayNameField: 'date', + nameField: 'date', // [ADR-0079] canonical primary-title pointer (mirrors deprecated displayNameField) + highlightFields: ['calendar', 'date', 'kind', 'periods'], + + fields: { + id: Field.text({ label: 'ID', required: true, readonly: true, group: 'System' }), + + calendar: Field.lookup('sys_work_calendar', { + label: 'Calendar', + required: true, + // A calendar's exceptions mean nothing without it. + deleteBehavior: 'cascade', + trackHistory: true, + group: 'Exception', + }), + + date: Field.date({ + label: 'Date', + required: true, + trackHistory: true, + group: 'Exception', + }), + + kind: Field.select( + [ + { value: 'off', label: 'Day Off' }, + { value: 'on', label: 'Working Day' }, + ], + { + label: 'Kind', + required: true, + trackHistory: true, + description: 'Day Off: the whole date is off. Working Day: the date is worked with the periods below, such as a make-up workday.', + group: 'Exception', + }, + ), + + periods: Field.text({ + label: 'Periods', + maxLength: 255, + trackHistory: true, + description: + "For a working day, all of that date's hours; they are never taken from the weekday. " + WORK_CALENDAR_PERIODS_HELP, + group: 'Exception', + }), + + note: Field.text({ + label: 'Note', + maxLength: 255, + trackHistory: true, + description: 'What the date is, such as National Day or a make-up workday for Spring Festival.', + group: 'Exception', + }), + }, + + indexes: [ + { fields: ['calendar', 'date'], unique: 'organization' }, + ], + + listViews: { + all_exceptions: { + type: 'grid', + name: 'all_exceptions', + label: 'All', + data: { provider: 'object', object: 'sys_work_calendar_exception' }, + columns: ['calendar', 'date', 'kind', 'periods', 'note'], + sort: [{ field: 'date', order: 'desc' }], + pagination: { pageSize: 50 }, + emptyState: { + title: 'No calendar exceptions yet', + message: 'Add one row per holiday or make-up workday, or import a year of them from a file.', + }, + }, + }, + + enable: { + trackHistory: true, + searchable: false, + apiEnabled: true, + feeds: false, + }, +}); diff --git a/packages/platform-objects/src/system/sys-work-calendar.object.ts b/packages/platform-objects/src/system/sys-work-calendar.object.ts new file mode 100644 index 00000000000..c31cd0436b0 --- /dev/null +++ b/packages/platform-objects/src/system/sys-work-calendar.object.ts @@ -0,0 +1,186 @@ +// Copyright (c) 2026 ObjectStack. Licensed under the Apache-2.0 license. + +import { ObjectSchema, Field, WORK_CALENDAR_CODE_PATTERN, WORK_CALENDAR_MAINTENANCE_LEAD_DAYS } from '@objectstack/spec/data'; + +/** + * The help every weekday's period column carries, stated once so the seven + * columns and the exception's `periods` can never disagree about the format + * (ADR-0157 D1, D7, D10). + */ +export const WORK_CALENDAR_PERIODS_HELP = + 'Working periods that day in the calendar\'s time zone, HH:mm-HH:mm separated by commas, such as 09:00-12:00, 13:00-18:00. ' + + 'A period ends later than it starts on the same day; 24:00 is the latest end. Leave blank for a day off.'; + +const weekday = (label: string) => + Field.text({ label, maxLength: 255, description: WORK_CALENDAR_PERIODS_HELP, group: 'Weekly Hours' }); + +/** + * sys_work_calendar — Working Calendar (ADR-0157 D1) + * + * One row per working calendar per organization: a weekly pattern of local + * working periods, the zone they are local to, and the span its exceptions + * (`sys_work_calendar_exception`) are maintained for. Runtime data an + * organization administrator keeps, never package metadata: holidays change + * every year, and a holiday is a row, not a release (D1). The precedent is + * `sys_exchange_rate` (ADR-0144), and every bullet of its tenancy, write-grant + * and audit note holds here unchanged — organization-scoped through the + * Layer 0 wall, written by organization administrators, every change audited. + * + * - **Code** — what a consumer names (a formula argument, the approval + * escalation's `calendar`), and what a package seeds a row under (D13: the + * existing seed contract, create-only unless the package declares a mode). + * Unique per organization, so a seeded code means one calendar in each. + * - **Default** — the calendar a computation takes when it names none (D2). + * One per organization: a second is refused at write by the calendar + * service's hooks (`@objectstack/objectql`), and a read that still meets two + * refuses rather than picking one. + * - **Time zone** — required (D7); the periods are local to it and the + * computation reads only it. A create that leaves it out takes the + * organization's `localization.timezone`, stored as the calendar's own. + * - **Periods** — one column per weekday, validated by the calendar itself + * (D10: `24:00` is a legal end, which the platform's `time` value refuses); + * a period crossing midnight is refused (D7). + * - **Maintained span** — `maintained_from` .. `maintained_through`, both + * required (open point 2): a blank must not read as "no holidays from here + * on". A computation needing a date outside the span is refused (D8, and the + * same refusal on the past side), and the `needs_maintenance` list marks a + * calendar {@link WORK_CALENDAR_MAINTENANCE_LEAD_DAYS} days ahead (D8). + * + * @namespace sys + */ +export const SysWorkCalendar = ObjectSchema.create({ + name: 'sys_work_calendar', + label: 'Working Calendar', + pluralLabel: 'Working Calendars', + icon: 'calendar-clock', + isSystem: true, + // Platform-defined schema, organization-administered data. + managedBy: 'system-data', + description: + 'Working calendars: the weekly working hours, the time zone they are local to, and how far the holidays are maintained. ' + + 'Due dates counted in working time read them.', + displayNameField: 'name', + nameField: 'name', // [ADR-0079] canonical primary-title pointer (mirrors deprecated displayNameField) + highlightFields: ['code', 'timezone', 'is_default', 'maintained_through'], + + fields: { + id: Field.text({ label: 'ID', required: true, readonly: true, group: 'System' }), + + code: Field.text({ + label: 'Code', + required: true, + searchable: true, + maxLength: 64, + unique: 'organization', + trackHistory: true, + description: + 'Machine code formulas, approval escalations and packages name this calendar by, such as cn_standard: lowercase letters, digits and underscores.', + group: 'Calendar', + }), + + name: Field.text({ + label: 'Name', + required: true, + searchable: true, + maxLength: 255, + trackHistory: true, + group: 'Calendar', + }), + + timezone: Field.text({ + label: 'Time Zone', + required: true, + maxLength: 64, + valueDomain: 'iana_time_zone', + trackHistory: true, + description: + "IANA time zone the working periods are local to, such as Asia/Shanghai. The create form opens with the organization's time zone (Settings → Localization), and a create that leaves it out takes the same zone.", + group: 'Calendar', + }), + + is_default: Field.boolean({ + label: 'Default', + defaultValue: false, + trackHistory: true, + description: 'The calendar a due date uses when it names none. One per organization.', + group: 'Calendar', + }), + + maintained_from: Field.date({ + label: 'Maintained From', + required: true, + trackHistory: true, + description: + 'First date the holidays and make-up workdays are entered from. A computation that needs an earlier date is refused.', + group: 'Maintenance', + }), + + maintained_through: Field.date({ + label: 'Maintained Through', + required: true, + trackHistory: true, + description: + "Last date the holidays and make-up workdays are entered through. A computation that needs a later date is refused: enter next year's holidays, then move this date.", + group: 'Maintenance', + }), + + monday_periods: weekday('Monday'), + tuesday_periods: weekday('Tuesday'), + wednesday_periods: weekday('Wednesday'), + thursday_periods: weekday('Thursday'), + friday_periods: weekday('Friday'), + saturday_periods: weekday('Saturday'), + sunday_periods: weekday('Sunday'), + }, + + listViews: { + all_calendars: { + type: 'grid', + name: 'all_calendars', + label: 'All', + data: { provider: 'object', object: 'sys_work_calendar' }, + columns: ['name', 'code', 'timezone', 'is_default', 'maintained_through'], + sort: [{ field: 'name', order: 'asc' }], + pagination: { pageSize: 50 }, + emptyState: { + title: 'No working calendars yet', + message: 'Add a calendar with its weekly hours and mark one as the default, then enter its holidays and make-up workdays.', + }, + }, + // [ADR-0157 D8] The notice ahead of the refusals: every calendar whose + // maintained span ends within the lead time. + needs_maintenance: { + type: 'grid', + name: 'needs_maintenance', + label: 'Needs Maintenance', + data: { provider: 'object', object: 'sys_work_calendar' }, + columns: ['name', 'code', 'maintained_through'], + filter: [{ field: 'maintained_through', operator: 'less_than_or_equal', value: `{${WORK_CALENDAR_MAINTENANCE_LEAD_DAYS}_days_from_now}` }], + sort: [{ field: 'maintained_through', order: 'asc' }], + pagination: { pageSize: 50 }, + emptyState: { + title: 'Every calendar is maintained ahead', + message: `A calendar appears here when its holidays run out within the next ${WORK_CALENDAR_MAINTENANCE_LEAD_DAYS} days; due dates past that date are refused.`, + }, + }, + }, + + validations: [ + { + type: 'format', + name: 'work_calendar_code_shape', + field: 'code', + regex: WORK_CALENDAR_CODE_PATTERN, + severity: 'error', + message: 'Code must start with a lowercase letter and use only lowercase letters, digits and underscores, such as cn_standard.', + }, + ], + + enable: { + trackHistory: true, + searchable: false, + apiEnabled: true, + // A calendar is reference data, not a discussion surface. + feeds: false, + }, +}); diff --git a/packages/rest/src/import-work-calendar-csv.test.ts b/packages/rest/src/import-work-calendar-csv.test.ts new file mode 100644 index 00000000000..9d1a86a30ac --- /dev/null +++ b/packages/rest/src/import-work-calendar-csv.test.ts @@ -0,0 +1,399 @@ +// Copyright (c) 2026 ObjectStack. Licensed under the Apache-2.0 license. + +/** + * ADR-0157 D1, D3, D7, D10: the platform's real working-calendar objects + * (`@objectstack/platform-objects`, not a mirror), on a real sqlite engine, + * with the calendar service's write hooks bound as the kernel binds them + * (`installWorkCalendarHooks`), written through the generic data doors: + * + * - a calendar created without `timezone` takes the organization's zone: the + * hooks run before `required` is judged, so the fill is what `required` sees; + * - a code outside the calendar-code shape is refused by the object's format + * rule, naming `code`; + * - one exception row per (calendar, date) in an organization: a second is + * refused by the unique key, while the same date on another calendar lands; + * - an exception file through the generic async import door names its + * calendar by code, and a bad line is refused for that row alone while the + * rest of the file lands; + * - an edit to a calendar is judged in the organization of the stored row: + * its one read for "one default per organization" runs there, whatever + * organization the session or the payload names; + * - a calendar, and each of its exception dates, stays in its organization: + * an update that changes `organization_id` is refused before any read, + * system writes included, while an edit that keeps it lands; + * - an exception date names a calendar of its own organization: a calendar + * of another organization and an id that names no calendar meet one + * refusal, the same body for both. + */ + +import { describe, it, expect, beforeEach, afterEach } from 'vitest'; +import { resolveThrownHttpError } from '@objectstack/types'; +import { ObjectQL, WorkCalendarService, installWorkCalendarHooks } from '@objectstack/objectql'; +import { SqlDriver } from '@objectstack/driver-sql'; +import { ObjectStackProtocolImplementation } from '@objectstack/metadata-protocol'; +import { SysMetadataAuditObject, SysMetadataCommitObject, SysMetadataHistoryObject, SysMetadataObject } from '@objectstack/metadata-core'; +import { SysImportJob } from '@objectstack/platform-objects/audit'; +import { SysWorkCalendar, SysWorkCalendarException } from '@objectstack/platform-objects/system'; +import { RestServer } from './rest-server'; +import { DEFAULT_ORGANIZATION_ID, installDefaultOrganization } from './default-organization.testkit.js'; + +const ORG = DEFAULT_ORGANIZATION_ID; +/** A calendar code (a record's `code` column), never an error code. */ +const CN_STANDARD = 'cn_standard'; +/** An organization with no `localization.timezone`. */ +const ZONELESS_ORG = 'org_zoneless'; + +const liveEngines: ObjectQL[] = []; +afterEach(async () => { + while (liveEngines.length) { + try { await liveEngines.pop()?.destroy(); } catch { /* noop */ } + } +}); + +function createMockServer() { + const noop = () => {}; + return { get: noop, post: noop, put: noop, delete: noop, patch: noop, use: noop, listen: async () => {}, close: async () => {} }; +} + +function makeRes() { + const res: any = { + write: () => true, end: () => {}, + header: () => res, + status: (code: number) => { res._status = code; return res; }, + json: (body: any) => { res._json = body; return res; }, + }; + return res; +} + +async function boot() { + const driver = new SqlDriver({ client: 'better-sqlite3', connection: { filename: ':memory:' }, useNullAsDefault: true }); + const engine = new ObjectQL(); + liveEngines.push(engine); + engine.registerDriver(driver, true); + await engine.init(); + engine.registry.registerObject(SysWorkCalendar as any); + engine.registry.registerObject(SysWorkCalendarException as any); + engine.registry.registerObject(SysImportJob as any); + await engine.syncSchemas(); + await installDefaultOrganization(engine); + for (const o of [SysMetadataObject, SysMetadataHistoryObject, SysMetadataAuditObject, SysMetadataCommitObject]) { + if (!engine.registry.getObject(o.name)) engine.registry.registerObject(o as any); + } + // As the kernel binds them: the organization's zone answers a create that leaves `timezone` out. + const service = new WorkCalendarService({ getEngine: () => engine as any }); + installWorkCalendarHooks(engine as any, service, { + timezoneOf: async (organizationId) => (organizationId === ORG ? 'Asia/Shanghai' : undefined), + }); + const protocol = new ObjectStackProtocolImplementation(engine as any); + const rest = new RestServer(createMockServer() as any, protocol as any, { api: { requireAuth: false } } as any); + // The request's execution context, as the kernel resolves it: the active organization is `tenantId`. + const session = { organizationId: ORG }; + (rest as any).resolveExecCtx = async () => ({ userId: 'calendar-admin', tenantId: session.organizationId }); + rest.registerRoutes(); + const routes = rest.getRoutes(); + const find = (method: string, path: string) => { + const route = routes.find((r: any) => r.method === method && r.path === path); + if (!route) throw new Error(`route not registered: ${method} ${path}`); + return route; + }; + return { + engine, + session, + post: find('POST', '/api/v1/data/:object'), + create: find('POST', '/api/v1/data/:object/import/jobs'), + progress: find('GET', '/api/v1/data/import/jobs/:jobId'), + results: find('GET', '/api/v1/data/import/jobs/:jobId/results'), + }; +} + +type Booted = Awaited>; + +/** POST one record to the generic create door: the status and the body. */ +async function post(ctx: Booted, object: string, body: Record): Promise<{ status: number; json: any }> { + const res = makeRes(); + await ctx.post.handler({ params: { object }, body, query: {} } as any, res); + return { status: res._status, json: res._json }; +} + +const WEEK = { + monday_periods: '09:00-12:00, 13:00-18:00', + tuesday_periods: '09:00-12:00, 13:00-18:00', + wednesday_periods: '09:00-12:00, 13:00-18:00', + thursday_periods: '09:00-12:00, 13:00-18:00', + friday_periods: '09:00-12:00, 13:00-18:00', +}; + +const calendar = (code: string, extra: Record = {}) => ({ + name: code, code, ...WEEK, maintained_from: '2026-01-01', maintained_through: '2026-12-31', ...extra, +}); + +/** POST the CSV to the async door and wait for the job's terminal state. */ +async function importCsv(ctx: Booted, object: string, csv: string): Promise<{ job: any; results: any[] }> { + const res = makeRes(); + await ctx.create.handler({ params: { object }, body: { format: 'csv', csv } } as any, res); + expect(res._status).toBe(201); + const jobId = res._json.jobId; + for (let i = 0; i < 200; i++) { + const p = makeRes(); + await ctx.progress.handler({ params: { jobId }, query: {} } as any, p); + if (['succeeded', 'failed', 'cancelled'].includes(p._json?.status)) { + const r = makeRes(); + await ctx.results.handler({ params: { jobId }, query: {} } as any, r); + return { job: p._json, results: r._json.results }; + } + await new Promise((resolve) => setTimeout(resolve, 5)); + } + throw new Error(`import job ${jobId} did not finish`); +} + +const byCalendarDate = (a: any, b: any) => `${a.calendar}${a.date}`.localeCompare(`${b.calendar}${b.date}`); + +const exceptions = async (ctx: Booted) => + (await ctx.engine.find('sys_work_calendar_exception', { context: { isSystem: true, tenantId: ORG } as any })) + .map((r: any) => ({ calendar: r.calendar, date: String(r.date).slice(0, 10), kind: r.kind, periods: r.periods ?? null })) + .sort(byCalendarDate); + +describe('sys_work_calendar through the create door (ADR-0157 D1, D7)', () => { + let ctx: Booted; + beforeEach(async () => { + ctx = await boot(); + }); + + it('a create that leaves timezone out stores the organization zone', async () => { + const { status, json } = await post(ctx, 'sys_work_calendar', calendar(CN_STANDARD)); + expect(status).toBe(201); + const stored: any = await ctx.engine.findOne('sys_work_calendar', { where: { id: json.id }, context: { isSystem: true, tenantId: ORG } as any }); + expect(stored).toMatchObject({ code: CN_STANDARD, timezone: 'Asia/Shanghai', organization_id: ORG }); + }); + + it('CONTROL: with no organization zone to take, the blank is refused as required', async () => { + ctx.session.organizationId = ZONELESS_ORG; + const { status, json } = await post(ctx, 'sys_work_calendar', calendar('cn_standard')); + expect(status).toBe(400); + expect(json).toMatchObject({ code: 'VALIDATION_FAILED', fields: [{ field: 'timezone', code: 'required' }] }); + }); + + it('refuses a code outside the calendar-code shape, naming code', async () => { + const { status, json } = await post(ctx, 'sys_work_calendar', calendar('CN Standard')); + expect(status).toBe(400); + expect(json.code).toBe('VALIDATION_FAILED'); + expect(json.fields.map((f: any) => [f.field, f.code])).toEqual([['code', 'invalid_format']]); + }); +}); + +describe('sys_work_calendar_exception through the data doors (ADR-0157 D3, D10)', () => { + let ctx: Booted; + let cn: string; + let plant: string; + beforeEach(async () => { + ctx = await boot(); + cn = (await post(ctx, 'sys_work_calendar', calendar('cn_standard'))).json.id; + plant = (await post(ctx, 'sys_work_calendar', calendar('plant_a'))).json.id; + }); + + it('holds one row per (calendar, date): a second is refused, the same date on another calendar lands', async () => { + expect((await post(ctx, 'sys_work_calendar_exception', { calendar: cn, date: '2026-10-01', kind: 'off' })).status).toBe(201); + + const second = await post(ctx, 'sys_work_calendar_exception', { calendar: cn, date: '2026-10-01', kind: 'on', periods: '09:00-18:00' }); + expect(second.status).toBe(409); + expect(second.json.code).toBe('UNIQUE_VIOLATION'); + expect((await post(ctx, 'sys_work_calendar_exception', { calendar: plant, date: '2026-10-01', kind: 'on', periods: '08:00-16:00' })).status).toBe(201); + + expect(await exceptions(ctx)).toEqual([ + { calendar: cn, date: '2026-10-01', kind: 'off', periods: null }, + { calendar: plant, date: '2026-10-01', kind: 'on', periods: '08:00-16:00' }, + ].sort(byCalendarDate)); + }); + + it('imports a file of exceptions naming the calendar by code; a bad line is refused alone', async () => { + const { job, results } = await importCsv(ctx, 'sys_work_calendar_exception', [ + 'calendar,date,kind,periods,note', + 'cn_standard,2026-10-01,off,,National Day', + 'cn_standard,2026-10-02,off,09:00-12:00,National Day', // a day off carries no periods: refused + 'cn_standard,2026-09-27,on,09:00-12:00,Make-up workday', + ].join('\n')); + + expect(job).toMatchObject({ status: 'succeeded', total: 3, created: 2, errors: 1 }); + expect(results[0]).toMatchObject({ row: 1, ok: true, action: 'created' }); + expect(results[1]).toMatchObject({ row: 2, ok: false, field: 'periods', code: 'invalid_value' }); + expect(results[2]).toMatchObject({ row: 3, ok: true, action: 'created' }); + expect(await exceptions(ctx)).toEqual([ + { calendar: cn, date: '2026-09-27', kind: 'on', periods: '09:00-12:00' }, + { calendar: cn, date: '2026-10-01', kind: 'off', periods: null }, + ]); + }); +}); + +/** Every one-default read the hooks make, by the organization it ran in. */ +function recordDefaultReads(engine: ObjectQL): string[] { + const reads: string[] = []; + const find = engine.find.bind(engine); + (engine as any).find = (object: string, query: any) => { + if (object === 'sys_work_calendar' && query?.where?.is_default === true) reads.push(String(query?.context?.tenantId ?? '(none)')); + return find(object, query); + }; + return reads; +} + +async function seed(posture: 'group' | 'isolated') { + const ctx = await boot(); + ctx.engine.setTenancyPostureProvider(() => posture); + const put = async (organizationId: string, code: string, extra: Record = {}) => + String(((await ctx.engine.insert('sys_work_calendar', calendar(code, { timezone: 'UTC', ...extra }), { + context: { userId: 'calendar-admin', tenantId: organizationId } as any, + })) as any).id); + // org_b holds a default; org_a holds none, so a read in org_a would admit the edit. + const storedDefault = await put('org_b', 'b_main', { is_default: true }); + const stored = await put('org_b', 'b_alt'); + const foreign = await put('org_a', 'a_main'); + return { ctx, stored, storedDefault, foreign, reads: recordDefaultReads(ctx.engine) }; +} + +/** The refusal an engine write meets, or `undefined` when it lands. */ +const refusalOf = (write: Promise): Promise => write.then(() => undefined, (e: unknown) => e); + +describe('an edit is judged in the organization of the stored row (ADR-0157 D2)', () => { + it('group: a session in org_a editing a row stored in org_b makes exactly one read, in org_b', async () => { + const { ctx, stored, reads } = await seed('group'); + const err = await refusalOf(ctx.engine.update('sys_work_calendar', { id: stored, is_default: true, organization_id: 'org_a' }, { + context: { userId: 'calendar-admin', tenantId: 'org_a', accessible_org_ids: ['org_a', 'org_b'] } as any, + })); + + expect(reads).toEqual(['org_b']); + expect(err?.code).toBe('VALIDATION_FAILED'); + expect(err?.fields?.map((f: any) => [f.field, f.code])).toEqual([['is_default', 'invalid_value']]); + }); + + it('isolated: a session in org_a does not reach a row stored in org_b, and the hooks read nothing', async () => { + const { ctx, stored, reads } = await seed('isolated'); + const err = await refusalOf(ctx.engine.update('sys_work_calendar', { id: stored, is_default: true, organization_id: 'org_a' }, { + context: { userId: 'calendar-admin', tenantId: 'org_a' } as any, + })); + + expect(reads).toEqual([]); + expect(err?.code).toBe('RECORD_NOT_FOUND'); + }); +}); + +describe('a calendar and its exceptions stay in their organization (ADR-0157 D2)', () => { + // A system writer in the row's own organization: its payload reaches the + // hooks with `organization_id` in it, as sent. + const asSystem = { context: { userId: 'calendar-admin', tenantId: 'org_b', isSystem: true } as any }; + const CALENDAR_STAYS = 'A calendar stays in the organization it was created in; create it in the other organization instead.'; + const EXCEPTION_STAYS = "An exception date stays in its calendar's organization."; + + /** The refusal's status, code and field, and whether its message carries the fixed reason. */ + const refused = (err: any, reason: string) => ({ + http: (({ status, code }) => ({ status, code }))(resolveThrownHttpError(err)), + fields: err?.fields?.map((f: any) => [f.field, f.code]), + reason: String(err?.message).includes(reason), + }); + const REFUSED = { http: { status: 400, code: 'VALIDATION_FAILED' }, fields: [['organization_id', 'invalid_value']], reason: true }; + + const organizationOf = async (ctx: Booted, object: string, id: string) => + ((await ctx.engine.findOne(object, { where: { id }, context: { isSystem: true } as any })) as any)?.organization_id; + + it('refuses moving a calendar, with or without Default, before any read', async () => { + const { ctx, stored, storedDefault, reads } = await seed('isolated'); + for (const data of [ + { id: storedDefault, organization_id: 'org_a' }, // stays the default + { id: stored, is_default: true, organization_id: 'org_a' }, // sets the default + { id: stored, organization_id: 'org_a' }, // no default at all + { id: stored, organization_id: null }, // clears the organization + ]) { + const err = await refusalOf(ctx.engine.update('sys_work_calendar', data, asSystem)); + expect(refused(err, CALENDAR_STAYS)).toEqual(REFUSED); + } + expect(reads).toEqual([]); + expect([await organizationOf(ctx, 'sys_work_calendar', storedDefault), await organizationOf(ctx, 'sys_work_calendar', stored)]).toEqual(['org_b', 'org_b']); + }); + + it('refuses moving an exception date to another organization', async () => { + const { ctx, stored } = await seed('isolated'); + const day = String(((await ctx.engine.insert('sys_work_calendar_exception', { calendar: stored, date: '2026-10-01', kind: 'off' }, asSystem)) as any).id); + const err = await refusalOf(ctx.engine.update('sys_work_calendar_exception', { id: day, organization_id: 'org_a' }, asSystem)); + + expect(refused(err, EXCEPTION_STAYS)).toEqual(REFUSED); + expect(await organizationOf(ctx, 'sys_work_calendar_exception', day)).toBe('org_b'); + }); + + it('refuses a predicate update that would change a matched row\'s organization, on either object', async () => { + const { ctx, stored, reads } = await seed('isolated'); + await ctx.engine.insert('sys_work_calendar_exception', { calendar: stored, date: '2026-10-01', kind: 'off' }, asSystem); + const where = { multi: true, where: { name: 'b_alt' }, ...asSystem } as any; + expect(refused(await refusalOf(ctx.engine.update('sys_work_calendar', { organization_id: 'org_a' }, where)), CALENDAR_STAYS)).toEqual(REFUSED); + const days = { multi: true, where: { kind: 'off' }, ...asSystem } as any; + expect(refused(await refusalOf(ctx.engine.update('sys_work_calendar_exception', { organization_id: 'org_a' }, days)), EXCEPTION_STAYS)).toEqual(REFUSED); + expect(reads).toEqual([]); + }); + + it('CONTROL: an edit that keeps the organization lands, whether it leaves organization_id out or repeats it', async () => { + const { ctx, stored } = await seed('isolated'); + const day = String(((await ctx.engine.insert('sys_work_calendar_exception', { calendar: stored, date: '2026-10-01', kind: 'off' }, asSystem)) as any).id); + for (const data of [{ id: stored, name: 'B Alt' }, { id: stored, name: 'B Alternate', organization_id: 'org_b' }]) { + expect(await refusalOf(ctx.engine.update('sys_work_calendar', data, asSystem))).toBeUndefined(); + } + for (const data of [{ id: day, note: 'National Day' }, { id: day, note: 'National Day holiday', organization_id: 'org_b' }]) { + expect(await refusalOf(ctx.engine.update('sys_work_calendar_exception', data, asSystem))).toBeUndefined(); + } + const calendarRow: any = await ctx.engine.findOne('sys_work_calendar', { where: { id: stored }, context: { isSystem: true } as any }); + const dayRow: any = await ctx.engine.findOne('sys_work_calendar_exception', { where: { id: day }, context: { isSystem: true } as any }); + expect([calendarRow.name, calendarRow.organization_id, dayRow.note, dayRow.organization_id]).toEqual(['B Alternate', 'org_b', 'National Day holiday', 'org_b']); + }); +}); + +describe('an exception date names a calendar of its own organization (ADR-0157 D2)', () => { + // A system writer in org_b, where `stored` lives; `foreign` lives in org_a. + const asSystem = { context: { userId: 'calendar-admin', tenantId: 'org_b', isSystem: true } as any }; + const REASON = 'An exception date names a calendar of its own organization.'; + const NO_SUCH_CALENDAR = 'cal_no_such_calendar'; + const day = (calendar: string, date = '2026-10-01') => ({ calendar, date, kind: 'off' }); + + /** The refusal as a caller meets it: the resolved envelope, whole. */ + const envelope = (err: unknown) => resolveThrownHttpError(err) as any; + const REFUSED = { status: 400, code: 'VALIDATION_FAILED', details: { fields: [expect.objectContaining({ field: 'calendar', code: 'invalid_value' })] } }; + + const daysOf = async (ctx: Booted) => + ((await ctx.engine.find('sys_work_calendar_exception', { context: { isSystem: true } as any })) as any[]) + .map((r) => [r.calendar, String(r.date).slice(0, 10), r.organization_id]); + + it('refuses a calendar of another organization, on create and on an update that carries calendar', async () => { + const { ctx, stored, foreign } = await seed('isolated'); + const created = await refusalOf(ctx.engine.insert('sys_work_calendar_exception', day(foreign), asSystem)); + expect(envelope(created)).toMatchObject(REFUSED); + expect(envelope(created).message).toContain(REASON); + + // A create whose row names the calendar's organization, not the session's, is not read for: the same refusal. + const elsewhere = await refusalOf(ctx.engine.insert('sys_work_calendar_exception', { ...day(foreign), organization_id: 'org_a' }, asSystem)); + expect(envelope(elsewhere)).toMatchObject(REFUSED); + + const own = String(((await ctx.engine.insert('sys_work_calendar_exception', day(stored), asSystem)) as any).id); + const repointed = await refusalOf(ctx.engine.update('sys_work_calendar_exception', { id: own, calendar: foreign }, asSystem)); + expect(envelope(repointed)).toMatchObject(REFUSED); + expect(await daysOf(ctx)).toEqual([[stored, '2026-10-01', 'org_b']]); + }); + + it('refuses an id that names no calendar with the same body as a calendar of another organization', async () => { + const { ctx, foreign } = await seed('isolated'); + const other = await refusalOf(ctx.engine.insert('sys_work_calendar_exception', day(foreign), asSystem)); + const none = await refusalOf(ctx.engine.insert('sys_work_calendar_exception', day(NO_SUCH_CALENDAR), asSystem)); + + expect(envelope(none)).toMatchObject(REFUSED); + expect(JSON.stringify(envelope(none))).toBe(JSON.stringify(envelope(other))); + for (const named of [foreign, NO_SUCH_CALENDAR, 'org_a', 'org_b', 'a_main']) expect(JSON.stringify(envelope(other))).not.toContain(named); + + // The same through the create door, for a member of org_b: one body for both. + ctx.session.organizationId = 'org_b'; + const viaOther = await post(ctx, 'sys_work_calendar_exception', day(foreign)); + const viaNone = await post(ctx, 'sys_work_calendar_exception', day(NO_SUCH_CALENDAR)); + expect(viaOther).toMatchObject({ status: 400, json: { code: 'VALIDATION_FAILED', fields: [expect.objectContaining({ field: 'calendar', code: 'invalid_value' })] } }); + expect(JSON.stringify(viaNone)).toBe(JSON.stringify(viaOther)); + }); + + it('CONTROL: a calendar of its own organization lands, on create and on update', async () => { + const { ctx, stored, storedDefault } = await seed('isolated'); + const own = String(((await ctx.engine.insert('sys_work_calendar_exception', day(stored), asSystem)) as any).id); + expect(await refusalOf(ctx.engine.update('sys_work_calendar_exception', { id: own, calendar: storedDefault }, asSystem))).toBeUndefined(); + expect(await daysOf(ctx)).toEqual([[storedDefault, '2026-10-01', 'org_b']]); + }); +}); diff --git a/packages/spec/src/system/constants/platform-object-names.ts b/packages/spec/src/system/constants/platform-object-names.ts index 170c8604967..917ddad63f9 100644 --- a/packages/spec/src/system/constants/platform-object-names.ts +++ b/packages/spec/src/system/constants/platform-object-names.ts @@ -103,6 +103,8 @@ export const PLATFORM_OBJECTS_BY_PACKAGE: Readonly = ({ const { userId: currentUserId } = perms; // ADR-0144 D8 rule 4 — the organization currency a record-currency code // field opens on in create mode. - const { currency: homeCurrency } = useLocalization(); + const { currency: homeCurrency, timezone: homeTimeZone } = useLocalization(); const { t } = useDiscardTranslation(); // The heading of the trailing ungrouped-fields bucket (`deriveFieldGroupSections`). const ungroupedLabel = t('common.ungroupedSection'); @@ -422,7 +422,7 @@ const DrawerFormBody: React.FC = ({ // Declared static defaults are this form's opening values (#4047) — // see `schemaDefaults` for the create-only boundary and for why // runtime defaults are left to the server. - setFormData(seedCreateValues(objectSchema, resolveInitialRecord(schema), { currentUserId, homeCurrency })); + setFormData(seedCreateValues(objectSchema, resolveInitialRecord(schema), { currentUserId, homeCurrency, homeTimeZone })); // Not a read, so no earlier record read's failure describes the form. run.commit(); setLoading(false); diff --git a/ui/packages/plugin-form/src/ModalForm.tsx b/ui/packages/plugin-form/src/ModalForm.tsx index a550ec3baa1..130d4cc64a7 100644 --- a/ui/packages/plugin-form/src/ModalForm.tsx +++ b/ui/packages/plugin-form/src/ModalForm.tsx @@ -384,7 +384,7 @@ const ModalFormBody: React.FC = ({ const perms = usePermissions(); // ADR-0144 D8 rule 4 — the organization currency a record-currency code // field opens on in create mode. - const { currency: homeCurrency } = useLocalization(); + const { currency: homeCurrency, timezone: homeTimeZone } = useLocalization(); const [objectSchema, setObjectSchema] = useState(null); const [formData, setFormData] = useState>({}); // The ONE field-gate step every layout draws through (`gateFormFields`, @@ -640,7 +640,7 @@ const ModalFormBody: React.FC = ({ // supplied initial values still win. See `schemaDefaults` for why // runtime defaults (`NOW()`, `current_user`, CEL envelopes) are left // to the server and why option-level `default` is not read here. - setFormData(seedCreateValues(objectSchema, resolveInitialRecord(schema), { currentUserId: perms.userId, homeCurrency })); + setFormData(seedCreateValues(objectSchema, resolveInitialRecord(schema), { currentUserId: perms.userId, homeCurrency, homeTimeZone })); // Not a read, so no earlier record read's failure describes the form. run.commit(); setLoading(false); diff --git a/ui/packages/plugin-form/src/ObjectForm.tsx b/ui/packages/plugin-form/src/ObjectForm.tsx index 178db0a698a..c81879780be 100644 --- a/ui/packages/plugin-form/src/ObjectForm.tsx +++ b/ui/packages/plugin-form/src/ObjectForm.tsx @@ -1222,14 +1222,14 @@ const SimpleObjectForm: React.FC<{ schema: LocalizedObjectFormSchema; dataSource const isCreateForm = isCreateFormMode(schema); // ADR-0144 D8 rule 4 — the organization currency a record-currency code // field opens on in create mode. - const { currency: homeCurrency } = useLocalization(); + const { currency: homeCurrency, timezone: homeTimeZone } = useLocalization(); // [#5683] `currentUserId` lets the one client-resolvable token // (`current_user`) pre-fill with the id the server would stamp anyway; // null/unloaded seeds nothing and keeps the omit-and-let-the-engine-resolve // contract above. const schemaDefaults = React.useMemo( - () => (isCreateForm ? schemaDefaultValues(objectSchema, { currentUserId: perms.userId, homeCurrency }) : {}), - [objectSchema, isCreateForm, perms.userId, homeCurrency], + () => (isCreateForm ? schemaDefaultValues(objectSchema, { currentUserId: perms.userId, homeCurrency, homeTimeZone }) : {}), + [objectSchema, isCreateForm, perms.userId, homeCurrency, homeTimeZone], ); // What the form OPENS with: the seeded defaults, overlaid with the caller's diff --git a/ui/packages/plugin-form/src/TabbedForm.tsx b/ui/packages/plugin-form/src/TabbedForm.tsx index 113cb850162..81b68dfe167 100644 --- a/ui/packages/plugin-form/src/TabbedForm.tsx +++ b/ui/packages/plugin-form/src/TabbedForm.tsx @@ -305,7 +305,7 @@ export const TabbedForm: React.FC = ({ const { userId: currentUserId } = perms; // ADR-0144 D8 rule 4 — the organization currency a record-currency code // field opens on in create mode. - const { currency: homeCurrency } = useLocalization(); + const { currency: homeCurrency, timezone: homeTimeZone } = useLocalization(); const [objectSchema, setObjectSchema] = useState(null); // Upload-in-flight gate (objectui#10166): a `file`/`image` value is only its // fileId once the presigned upload settles, so a save during that window @@ -402,7 +402,7 @@ export const TabbedForm: React.FC = ({ // Declared static defaults are this form's opening values (#4047) — // see `schemaDefaults` for the create-only boundary and for why // runtime defaults are left to the server. - setFormData(seedCreateValues(objectSchema, resolveInitialRecord(schema), { currentUserId, homeCurrency })); + setFormData(seedCreateValues(objectSchema, resolveInitialRecord(schema), { currentUserId, homeCurrency, homeTimeZone })); // Not a read, so no earlier record read's failure describes the form. run.commit(); setLoading(false); diff --git a/ui/packages/plugin-form/src/WizardForm.tsx b/ui/packages/plugin-form/src/WizardForm.tsx index 02be997cb77..117c3fb59ef 100644 --- a/ui/packages/plugin-form/src/WizardForm.tsx +++ b/ui/packages/plugin-form/src/WizardForm.tsx @@ -486,7 +486,7 @@ export const WizardForm: React.FC = ({ const { userId: currentUserId } = perms; // ADR-0144 D8 rule 4 — the organization currency a record-currency code // field opens on in create mode. - const { currency: homeCurrency } = useLocalization(); + const { currency: homeCurrency, timezone: homeTimeZone } = useLocalization(); const { t } = useWizardTranslation(); // Upload-in-flight gate (objectui#10166). Scoped to the FINAL commit, not to // step navigation: moving between steps writes nothing, and blocking Next @@ -662,7 +662,7 @@ export const WizardForm: React.FC = ({ // Declared static defaults are this wizard's opening values (#4047) // — see `schemaDefaults` for the create-only boundary and for why // runtime defaults are left to the server. - setFormData(holdCreateSeed(createSeedRef, seedCreateValues(objectSchema, resolveInitialRecord(schema), { currentUserId, homeCurrency }))); + setFormData(holdCreateSeed(createSeedRef, seedCreateValues(objectSchema, resolveInitialRecord(schema), { currentUserId, homeCurrency, homeTimeZone }))); seededRef.current = true; } // Not a read, so no earlier record read's failure describes the form. @@ -1155,7 +1155,7 @@ export const WizardForm: React.FC = ({ // Back to a fresh step 1 for the next entry — "fresh" means the // same opening values the wizard had, defaults included (#4047), // not a blank object the first entry never started from. - setFormData(holdCreateSeed(createSeedRef, seedCreateValues(objectSchema, resolveInitialRecord(schema), { currentUserId, homeCurrency }))); + setFormData(holdCreateSeed(createSeedRef, seedCreateValues(objectSchema, resolveInitialRecord(schema), { currentUserId, homeCurrency, homeTimeZone }))); setCompletedSteps(new Set()); setCurrentStep(0); setResetNonce((n) => n + 1); @@ -1212,7 +1212,7 @@ export const WizardForm: React.FC = ({ if (schema.resetOnSuccess && schema.mode === 'create') { // Back to a fresh step 1 for the next entry — same opening values // as the first entry, defaults included (#4047). - setFormData(holdCreateSeed(createSeedRef, seedCreateValues(objectSchema, resolveInitialRecord(schema), { currentUserId, homeCurrency }))); + setFormData(holdCreateSeed(createSeedRef, seedCreateValues(objectSchema, resolveInitialRecord(schema), { currentUserId, homeCurrency, homeTimeZone }))); setCompletedSteps(new Set()); setCurrentStep(0); setResetNonce((n) => n + 1); diff --git a/ui/packages/plugin-form/src/__tests__/organizationZoneSeed-35355.test.tsx b/ui/packages/plugin-form/src/__tests__/organizationZoneSeed-35355.test.tsx new file mode 100644 index 00000000000..738c5419299 --- /dev/null +++ b/ui/packages/plugin-form/src/__tests__/organizationZoneSeed-35355.test.tsx @@ -0,0 +1,80 @@ +/** + * ObjectUI + * Copyright (c) 2024-present ObjectStack Inc. + * + * This source code is licensed under the MIT license found in the + * LICENSE file in the root directory of this source tree. + */ + +/** + * ADR-0157 D7 — a create form opens a REQUIRED `iana_time_zone` text field + * that declares no default on the organization's time zone, the zone the + * server gives a create that leaves the field out. An optional zone field + * (blank means "take the parent's") is never seeded; the author's + * `defaultValue` and the caller's record win; an unknown zone seeds nothing. + */ + +import { describe, it, expect, afterEach } from 'vitest'; +import { render, waitFor, cleanup } from '@testing-library/react'; +import '@testing-library/jest-dom'; +import React from 'react'; +import { LocalizationProvider } from '@object-ui/i18n'; +import { registerAllFields } from '@object-ui/fields'; +import { schemaDefaultValues, seedCreateValues } from '../schemaDefaults'; +import { ModalForm } from '../ModalForm'; +import { ObjectForm } from '../ObjectForm'; + +registerAllFields(); +afterEach(cleanup); + +// The shape of the working-calendar object's `timezone`, plus an optional +// zone field shaped like a business unit's. +const CALENDAR = { + name: 'zone_calendar', + fields: { + name: { type: 'text', label: 'Name', required: true }, + timezone: { type: 'text', label: 'Time Zone', required: true, maxLength: 64, valueDomain: 'iana_time_zone' }, + unit_zone: { type: 'text', label: 'Unit zone', required: false, valueDomain: 'iana_time_zone' }, + }, +}; + +describe('create-form seeding of a required time-zone field (ADR-0157 D7)', () => { + it('pre-fills the required zone field with the organization time zone, and only that field', () => { + expect(schemaDefaultValues(CALENDAR, { homeTimeZone: 'Asia/Shanghai' })).toEqual({ timezone: 'Asia/Shanghai' }); + }); + + it('seeds nothing while the organization time zone is unknown', () => { + expect(schemaDefaultValues(CALENDAR, { homeTimeZone: undefined })).toEqual({}); + expect(schemaDefaultValues(CALENDAR)).toEqual({}); + }); + + it("the author's defaultValue wins", () => { + const schema = { fields: { ...CALENDAR.fields, timezone: { ...CALENDAR.fields.timezone, defaultValue: 'UTC' } } }; + expect(schemaDefaultValues(schema, { homeTimeZone: 'Asia/Shanghai' }).timezone).toBe('UTC'); + }); + + it("the caller's record wins", () => { + expect(seedCreateValues(CALENDAR, { timezone: 'Europe/Paris' }, { homeTimeZone: 'Asia/Shanghai' }).timezone).toBe('Europe/Paris'); + }); +}); + +describe('the create form opens on the organization time zone (ADR-0157 D7)', () => { + const ds = { getObjectSchema: async () => CALENDAR, create: async (_o: string, d: unknown) => d }; + + for (const host of ['modal', 'inline'] as const) { + it(`${host}: the Time Zone input holds the zone the localization context carries`, async () => { + const base = { type: 'object-form', objectName: 'zone_calendar', mode: 'create' } as any; + const form = host === 'modal' + ? + : ; + render({form}); + await waitFor(() => { + const input = document.querySelector('[data-field="timezone"] input') as HTMLInputElement | null; + if (!input) throw new Error('form not ready'); + expect(input.value).toBe('Asia/Shanghai'); + }, { timeout: 5000 }); + const unit = document.querySelector('[data-field="unit_zone"] input') as HTMLInputElement | null; + expect(unit?.value ?? '').toBe(''); + }); + } +}); diff --git a/ui/packages/plugin-form/src/schemaDefaults.ts b/ui/packages/plugin-form/src/schemaDefaults.ts index 7c5683a99e5..8b8f78c9c03 100644 --- a/ui/packages/plugin-form/src/schemaDefaults.ts +++ b/ui/packages/plugin-form/src/schemaDefaults.ts @@ -152,6 +152,8 @@ type SeedFieldLike = NonNullable[ options?: unknown; multiple?: unknown; currencyConfig?: unknown; + required?: unknown; + valueDomain?: unknown; }; /** @@ -199,6 +201,31 @@ export interface SeedContext { * explicit value, and the server never fills one in. Unset seeds nothing. */ homeCurrency?: string | null; + /** + * The organization's time zone (`localization.timezone`, via + * `useLocalization().timezone`), or null/undefined when none is known. A + * REQUIRED `iana_time_zone` text field with no declared default opens + * pre-filled with it ({@link isOrganizationZoneSeedField}), so a create form + * shows the zone a create that leaves the field out would be given + * (ADR-0157 D7) instead of refusing a blank. Unknown seeds nothing. + */ + homeTimeZone?: string | null; +} + +/** + * Whether a field opens on the organization's time zone: a `required` text + * field whose `valueDomain` is `iana_time_zone` (ADR-0157 D7). Required only: + * on an optional zone field a blank is a legal answer ("take the parent's", + * as on a business unit), and a pre-filled value would replace it with an + * explicit zone the user never chose. On a required one a blank is refused + * anyway, so the seed only turns that refusal into a visible, editable value. + */ +function isOrganizationZoneSeedField(f: SeedFieldLike | undefined): boolean { + return ( + f?.required === true && + (f.type === undefined || f.type === 'text') && + f.valueDomain === 'iana_time_zone' + ); } /** @@ -349,6 +376,10 @@ export function schemaDefaultValues( // VALUE the user submits (or changes), so the stored code is always // explicit; a declared `defaultValue` is the author's and wins. else if (codeFields?.has(name) && ctx?.homeCurrency) defaults[name] = ctx.homeCurrency; + // ADR-0157 D7 — a required time-zone field with no declared default + // opens on the organization's zone, the one the server gives a create + // that leaves it out; the user submits it (or another zone) explicitly. + else if (ctx?.homeTimeZone && isOrganizationZoneSeedField(f)) defaults[name] = ctx.homeTimeZone; } } return defaults;