@fabriktor/fx 0.0.193 → 0.0.195

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/README.md CHANGED
@@ -14,6 +14,15 @@
14
14
  This package is designed exclusively for Fabriktor's frontend operational needs and is
15
15
  not intended for public usage.
16
16
 
17
+ The Timesheets workspace restores open punches across employers and payroll
18
+ periods before consulting current preferences. It follows the stored start for
19
+ work and transport, confirms the actual returned punch, and requires an explicit
20
+ time when continuing a shift from an earlier day. Manual day replacement is one
21
+ request. Civil time input resolves to UTC with an explicit choice for repeated
22
+ daylight-saving times; the backend remains authoritative for duration, overlap
23
+ and persistence rules. Route arrival cues follow the stored active transport
24
+ across midnight; unresolved multiple open punches still require recovery first.
25
+
17
26
  ---
18
27
 
19
28
  ## License
@@ -62,6 +62,7 @@ export * from "./storage/capture.js";
62
62
  export * from "./storage/storage.js";
63
63
  export * from "./timesheets/access.js";
64
64
  export * from "./timesheets/timesheets.js";
65
+ export * from "./timesheets/time.js";
65
66
  export * from "./timesheets/workspace.js";
66
67
  export * from "./users/email.js";
67
68
  export * from "./users/phone.js";
package/dist/src/index.js CHANGED
@@ -62,6 +62,7 @@ export * from "./storage/capture.js";
62
62
  export * from "./storage/storage.js";
63
63
  export * from "./timesheets/access.js";
64
64
  export * from "./timesheets/timesheets.js";
65
+ export * from "./timesheets/time.js";
65
66
  export * from "./timesheets/workspace.js";
66
67
  export * from "./users/email.js";
67
68
  export * from "./users/phone.js";
@@ -39,9 +39,11 @@ export class RouteArrivalCue {
39
39
  }
40
40
  }
41
41
  export function routeHasActiveTransport(actor, route, vehicle_id, state, location_id) {
42
+ // A prior-day start requires explicit recovery, not an inactive transport.
43
+ // Keep the cue tied to stored state; the punch workflow validates its finish.
42
44
  return (actor.active_mode === UserTypeEmployee &&
43
45
  routeCanTrack(actor, route, vehicle_id, actor.owner_id) &&
44
- !state.stale_day &&
46
+ (state.open_punches?.length ?? 0) <= 1 &&
45
47
  !state.week_sheet?.is_archived &&
46
48
  state.punch?.employer_id === route.owner_id &&
47
49
  state.punch.punch_status === PunchStatusWorking &&
@@ -0,0 +1,17 @@
1
+ import type { Date as SchemaDate, InDate } from "@fabriktor/schema";
2
+ export type TimesheetDate = InDate & {
3
+ utc?: string;
4
+ };
5
+ export declare function timesheetDateChoices(value: InDate): SchemaDate[];
6
+ export declare function timesheetDate(value: TimesheetDate): SchemaDate;
7
+ export declare function timesheetDateTime(value: TimesheetDate): number;
8
+ export declare function timesheetPunchDeadline(start: TimesheetDate): number;
9
+ export declare function timesheetPunchWindow(opts: {
10
+ start: TimesheetDate;
11
+ now: Date;
12
+ minimum?: TimesheetDate;
13
+ allow_equal?: boolean;
14
+ }): {
15
+ minimum: number;
16
+ maximum: number;
17
+ };
@@ -0,0 +1,49 @@
1
+ import { TimesheetMaxPunchHours } from "@fabriktor/schema";
2
+ import { inDateAtTimestamp, isValidInputDate, isZeroDateTime, } from "../core/date.js";
3
+ import { PreActionBlocked } from "../core/pre-action.js";
4
+ const minuteMS = 60_000;
5
+ const hourMS = 60 * minuteMS;
6
+ // Return actual instants for civil input; gaps have none and repeated DST times have two.
7
+ export function timesheetDateChoices(value) {
8
+ if (!isValidInputDate(value))
9
+ return [];
10
+ const wall = Date.UTC(value.y, value.m - 1, value.d, value.h, value.min);
11
+ const offsets = new Set();
12
+ for (let h = -48; h <= 48; h += 6) {
13
+ const instant = wall + h * hourMS;
14
+ const local = inDateAtTimestamp(new Date(instant).toISOString(), value.tz);
15
+ offsets.add(Date.UTC(local.y, local.m - 1, local.d, local.h, local.min) - instant);
16
+ }
17
+ const out = [];
18
+ for (const offset of offsets) {
19
+ const utc = new Date(wall - offset).toISOString();
20
+ const local = inDateAtTimestamp(utc, value.tz);
21
+ if (["y", "m", "d", "h", "min"].every((key) => local[key] === value[key]))
22
+ out.push({ ...value, utc });
23
+ }
24
+ return out.sort((a, b) => Date.parse(a.utc) - Date.parse(b.utc));
25
+ }
26
+ export function timesheetDate(value) {
27
+ const choices = timesheetDateChoices(value);
28
+ const selected = value.utc && !isZeroDateTime(value.utc)
29
+ ? choices.find((choice) => Date.parse(choice.utc) === Date.parse(value.utc))
30
+ : choices.length === 1
31
+ ? choices[0]
32
+ : undefined;
33
+ if (!selected)
34
+ throw new PreActionBlocked("timesheets_invalid_day");
35
+ return selected;
36
+ }
37
+ export function timesheetDateTime(value) {
38
+ return Date.parse(timesheetDate(value).utc);
39
+ }
40
+ export function timesheetPunchDeadline(start) {
41
+ return timesheetDateTime(start) + TimesheetMaxPunchHours * hourMS;
42
+ }
43
+ export function timesheetPunchWindow(opts) {
44
+ const start = timesheetDateTime(opts.start);
45
+ return {
46
+ minimum: Math.max(start + (opts.allow_equal ? 0 : minuteMS), opts.minimum ? timesheetDateTime(opts.minimum) : start),
47
+ maximum: Math.min(opts.now.getTime(), timesheetPunchDeadline(opts.start)),
48
+ };
49
+ }
@@ -1,4 +1,4 @@
1
- import { type Date as SchemaDate, type OperationResult, type Summary, type WeekSheet } from "@fabriktor/schema";
1
+ import { type Date as SchemaDate, type OperationResult, type Punch, type Summary, type WeekSheet } from "@fabriktor/schema";
2
2
  import type { BillableOperator, TimesheetsOperator } from "@fabriktor/client";
3
3
  import type { ContactsFXOperator } from "../contacts/contacts.js";
4
4
  import type { NowProvider } from "../core/server-clock.js";
@@ -6,9 +6,7 @@ import type { MultiCreateAttempt } from "../core/multi-create.js";
6
6
  import { type LoadTimesheetsReadContextOptions, type QueryTimesheetSyncDestinationsOptions, type QueryTimesheetSyncSourcesOptions, type TimesheetsReadContext, type TimesheetsReadOptions, type TimesheetSyncTarget } from "./access.js";
7
7
  import { TimesheetsWorkspace } from "./workspace.js";
8
8
  type PunchPayload = Parameters<TimesheetsOperator["punch"]>[0];
9
- type WeekSheetReplaceOptions = Parameters<TimesheetsOperator["replaceOneWeekSheet"]>[0];
10
9
  type SummaryReplaceOptions = Parameters<TimesheetsOperator["replaceOneSummary"]>[0];
11
- export type ReplaceWeekSheetOptions = WeekSheetReplaceOptions;
12
10
  export type ReplaceSummaryOptions = SummaryReplaceOptions;
13
11
  export type TimesheetsFXOptions = {
14
12
  timesheets: TimesheetsOperator;
@@ -16,7 +14,10 @@ export type TimesheetsFXOptions = {
16
14
  billable?: BillableOperator;
17
15
  now?: NowProvider;
18
16
  };
19
- export type PunchContext = Pick<PunchPayload, "timezone" | "location_id" | "employer_id">;
17
+ export type PunchContext = Pick<PunchPayload, "timezone" | "location_id" | "employer_id"> & {
18
+ week_sheet_id?: WeekSheet["id"];
19
+ punch_in_date?: SchemaDate;
20
+ };
20
21
  export type PunchInOptions = PunchContext & {
21
22
  explicit_date?: SchemaDate;
22
23
  };
@@ -50,6 +51,7 @@ export type CreateBlankWeekSheetOptions = PunchContext & {
50
51
  export type PunchControlsOptions = {
51
52
  week_sheet?: WeekSheet;
52
53
  week_day: number;
54
+ punch?: Punch;
53
55
  };
54
56
  export type PunchControls = {
55
57
  can_punch_in: boolean;
@@ -79,7 +81,6 @@ export interface TimesheetsFXOperator {
79
81
  querySyncDestinations(opts: QueryTimesheetSyncDestinationsOptions): Promise<WeekSheet[]>;
80
82
  querySyncSources(opts: QueryTimesheetSyncSourcesOptions): Promise<WeekSheet[]>;
81
83
  querySyncTargets(opts: QueryTimesheetSyncDestinationsOptions): Promise<TimesheetSyncTarget[]>;
82
- replaceWeekSheet(opts: ReplaceWeekSheetOptions): Promise<WeekSheet>;
83
84
  replaceSummary(opts: ReplaceSummaryOptions): Promise<Summary>;
84
85
  punchControls(opts: PunchControlsOptions): PunchControls;
85
86
  punchIn(opts: PunchInOptions): Promise<OperationResult>;
@@ -105,7 +106,6 @@ export declare class TimesheetsFX implements TimesheetsFXOperator {
105
106
  querySyncDestinations(opts: QueryTimesheetSyncDestinationsOptions): Promise<WeekSheet[]>;
106
107
  querySyncSources(opts: QueryTimesheetSyncSourcesOptions): Promise<WeekSheet[]>;
107
108
  querySyncTargets(opts: QueryTimesheetSyncDestinationsOptions): Promise<TimesheetSyncTarget[]>;
108
- replaceWeekSheet(opts: ReplaceWeekSheetOptions): Promise<WeekSheet>;
109
109
  replaceSummary(opts: ReplaceSummaryOptions): Promise<Summary>;
110
110
  punchControls(opts: PunchControlsOptions): PunchControls;
111
111
  punchIn(opts: PunchInOptions): Promise<OperationResult>;
@@ -91,15 +91,12 @@ export class TimesheetsFX {
91
91
  const matches = weeks.filter((week) => week.owner_id === owner_id);
92
92
  if (matches.length === 0)
93
93
  targets.push({ owner_id });
94
- else if (matches.length === 1 && timesheetCanSyncDestination(opts.context, source, matches[0]))
94
+ else if (matches.length === 1 &&
95
+ timesheetCanSyncDestination(opts.context, source, matches[0]))
95
96
  targets.push({ owner_id, week_sheet: matches[0] });
96
97
  }
97
98
  return targets;
98
99
  }
99
- async replaceWeekSheet(opts) {
100
- await this.timesheets.replaceOneWeekSheet(opts);
101
- return await this.findWeekSheet(opts.id);
102
- }
103
100
  async replaceSummary(opts) {
104
101
  await this.timesheets.replaceOneSummary(opts);
105
102
  return await this.findSummary(opts.id);
@@ -110,7 +107,7 @@ export class TimesheetsFX {
110
107
  return disabledPunchControls();
111
108
  }
112
109
  const day = opts.week_sheet?.sheets.find((sheet) => sheet.week_day === opts.week_day);
113
- const latest_punch = day?.punches.at(-1);
110
+ const latest_punch = opts.punch ?? day?.punches.at(-1);
114
111
  if (latest_punch === undefined) {
115
112
  return readyToPunchInControls();
116
113
  }
@@ -189,28 +186,19 @@ export class TimesheetsFX {
189
186
  validateMinutes(opts.total_pause_minutes, "total_pause_minutes");
190
187
  validateMinutes(opts.total_meal_minutes, "total_meal_minutes");
191
188
  return await this.runPunch(async () => {
192
- const punch_in = await this.timesheets.punch(buildPunch({
189
+ const input = buildPunch({
193
190
  context: opts,
194
191
  punch_type: PunchTypeIn,
195
192
  punch_mode: PunchModeReplace,
196
- punch_status: PunchStatusWorking,
197
- total_pause_minutes: 0,
198
- total_meal_minutes: 0,
199
- explicit_date: opts.punch_in_date,
200
- }));
201
- const punch_out = await this.timesheets.punch(buildPunch({
202
- context: opts,
203
- punch_type: PunchTypeOut,
204
- punch_mode: PunchModeDefault,
205
193
  punch_status: PunchStatusPending,
206
194
  total_pause_minutes: opts.total_pause_minutes,
207
195
  total_meal_minutes: opts.total_meal_minutes,
208
- explicit_date: opts.punch_out_date,
209
- }));
210
- return {
211
- punch_in,
212
- punch_out,
213
- };
196
+ explicit_date: opts.punch_in_date,
197
+ });
198
+ input.punch_in_time = cloneDate(opts.punch_in_date);
199
+ input.punch_out_time = cloneDate(opts.punch_out_date);
200
+ const out = await this.timesheets.punch(input);
201
+ return { punch_in: out, punch_out: out };
214
202
  });
215
203
  }
216
204
  async deleteDay(opts) {
@@ -417,7 +405,12 @@ export function newTimesheetsFX(opts) {
417
405
  function buildPunch(opts) {
418
406
  const context = normalizePunchContext(opts.context);
419
407
  return {
420
- punch_in_time: zeroDate(),
408
+ ...(opts.context.week_sheet_id
409
+ ? { week_sheet_id: opts.context.week_sheet_id }
410
+ : {}),
411
+ punch_in_time: opts.context.punch_in_date
412
+ ? cloneDate(opts.context.punch_in_date)
413
+ : zeroDate(),
421
414
  punch_out_time: zeroDate(),
422
415
  rides: [],
423
416
  punch_status: opts.punch_status,
@@ -1,5 +1,6 @@
1
1
  import { type BillableOperator, type TimesheetsOperator } from "@fabriktor/client";
2
- import { PunchTypeIn, PunchTypeOut, PunchTypeRideIn, PunchTypeRideOut, type InDate, type Punch, type Summary, type WeekSheet } from "@fabriktor/schema";
2
+ import { PunchTypeIn, PunchTypeOut, PunchTypeRideIn, PunchTypeRideOut, type Date as SchemaDate, type InDate, type Punch, type Summary, type WeekSheet } from "@fabriktor/schema";
3
+ import { type TimesheetDate } from "./time.js";
3
4
  import type { NowProvider } from "../core/server-clock.js";
4
5
  import type { TimesheetsFXOperator } from "./timesheets.js";
5
6
  export type TimesheetFilters = {
@@ -15,13 +16,18 @@ export type PunchStateOptions = {
15
16
  owner_id: string;
16
17
  employer_id: string;
17
18
  timezone: string;
18
- date?: InDate;
19
+ date?: TimesheetDate;
20
+ target?: {
21
+ week_sheet_id: string;
22
+ start: SchemaDate;
23
+ };
19
24
  };
20
25
  export type TimesheetPunchState = {
21
26
  week_sheet?: WeekSheet;
22
27
  punch?: Punch;
23
28
  week_day: number;
24
29
  stale_day: boolean;
30
+ open_punches?: TimesheetPunchState[];
25
31
  };
26
32
  export type TimesheetPunchAction = typeof PunchTypeIn | typeof PunchTypeOut | typeof PunchTypeRideIn | typeof PunchTypeRideOut;
27
33
  export type CheckedPunchOptions = PunchStateOptions & {
@@ -35,8 +41,8 @@ export type CheckedPunchOptions = PunchStateOptions & {
35
41
  export type StartTimesheetTransportOptions = Omit<CheckedPunchOptions, "action" | "total_pause_minutes" | "total_meal_minutes">;
36
42
  export type SaveTimesheetDayOptions = PunchStateOptions & {
37
43
  location_id: string;
38
- start: InDate;
39
- end: InDate;
44
+ start: TimesheetDate;
45
+ end: TimesheetDate;
40
46
  total_pause_minutes: number;
41
47
  total_meal_minutes: number;
42
48
  replace?: WeekSheet;
@@ -47,6 +53,9 @@ export declare const TimesheetsBlock: {
47
53
  readonly Locked: "timesheets_locked";
48
54
  readonly Active: "timesheets_active";
49
55
  readonly InvalidDay: "timesheets_invalid_day";
56
+ readonly FinishRequired: "timesheets_finish_required";
57
+ readonly Duration: "timesheets_duration";
58
+ readonly TimeUnavailable: "timesheets_time_unavailable";
50
59
  readonly InvalidSync: "timesheets_invalid_sync";
51
60
  readonly Unconfirmed: "timesheets_unconfirmed";
52
61
  };
@@ -1,6 +1,7 @@
1
1
  import { mergeQueryOptions, queryNestedParam, queryParams, } from "@fabriktor/client";
2
2
  import { PunchStatusApproved, PunchStatusPending, PunchStatusWorking, PunchTypeIn, PunchTypeOut, PunchTypeRideIn, PunchTypeRideOut, } from "@fabriktor/schema";
3
- import { inDateAtTimestamp, zeroDate } from "../core/date.js";
3
+ import { inDateAtTimestamp } from "../core/date.js";
4
+ import { timesheetDate, timesheetDateTime, timesheetPunchDeadline, } from "./time.js";
4
5
  import { errRequired } from "../core/err.js";
5
6
  import { PreActionBlocked } from "../core/pre-action.js";
6
7
  import { queryRecordParams, runOwnerScopeQuery, } from "../core/query.js";
@@ -10,6 +11,9 @@ export const TimesheetsBlock = {
10
11
  Locked: "timesheets_locked",
11
12
  Active: "timesheets_active",
12
13
  InvalidDay: "timesheets_invalid_day",
14
+ FinishRequired: "timesheets_finish_required",
15
+ Duration: "timesheets_duration",
16
+ TimeUnavailable: "timesheets_time_unavailable",
13
17
  InvalidSync: "timesheets_invalid_sync",
14
18
  Unconfirmed: "timesheets_unconfirmed",
15
19
  };
@@ -35,17 +39,20 @@ export function timesheetCanApprove(sheet) {
35
39
  }
36
40
  export function timesheetCanSyncSource(sheet) {
37
41
  const punches = timesheetPunches(sheet);
38
- return punches.length > 0 && punches.every((punch) => punch.punch_status === PunchStatusPending || punch.punch_status === PunchStatusApproved);
42
+ return (punches.length > 0 &&
43
+ punches.every((punch) => punch.punch_status === PunchStatusPending ||
44
+ punch.punch_status === PunchStatusApproved));
39
45
  }
40
46
  export function timesheetCanSync(source, destination) {
41
- return timesheetCanSyncSource(source) && !destination.is_archived &&
47
+ return (timesheetCanSyncSource(source) &&
48
+ !destination.is_archived &&
42
49
  timesheetPunches(destination).every((punch) => punch.punch_status === PunchStatusPending) &&
43
50
  destination.employer_id === source.employer_id &&
44
51
  destination.id !== source.id &&
45
52
  destination.period_index === source.period_index &&
46
53
  destination.period === source.period &&
47
54
  destination.period_year === source.period_year &&
48
- destination.timezone === source.timezone;
55
+ destination.timezone === source.timezone);
49
56
  }
50
57
  export function timesheetStateKey(state) {
51
58
  return JSON.stringify([
@@ -63,20 +70,15 @@ export function timesheetWeekDay(date) {
63
70
  function sameDay(a, b) {
64
71
  return a.y === b.y && a.m === b.m && a.d === b.d;
65
72
  }
66
- function wallTime(date) {
67
- return Date.UTC(date.y, date.m - 1, date.d, date.h, date.min);
68
- }
69
- function schemaDate(date) {
70
- // The backend computes UTC from the supplied wall-clock fields and tz.
71
- return { ...zeroDate(), ...date };
72
- }
73
73
  export class TimesheetsWorkspace {
74
74
  client;
75
75
  actions;
76
76
  billable;
77
77
  now;
78
78
  punchPending = false;
79
- constructor(client, actions, billable, now = () => new Date()) {
79
+ constructor(client, actions, billable, now = () => {
80
+ throw new PreActionBlocked(TimesheetsBlock.TimeUnavailable);
81
+ }) {
80
82
  this.client = client;
81
83
  this.actions = actions;
82
84
  this.billable = billable;
@@ -111,27 +113,35 @@ export class TimesheetsWorkspace {
111
113
  }
112
114
  async punchState(opts) {
113
115
  requireState(!!opts.owner_id && !!opts.timezone, TimesheetsBlock.InvalidDay);
114
- const today = opts.date ?? inDateAtTimestamp((await this.now()).toISOString(), opts.timezone);
116
+ const today = opts.date ??
117
+ inDateAtTimestamp((await this.now()).toISOString(), opts.timezone);
115
118
  const week_day = timesheetWeekDay(today);
116
119
  // Check every open work punch, including other employers/locations/weeks.
117
120
  // A scope selection must never hide an already open shift.
118
121
  const active = await this.weeks({
119
122
  owner_ids: [opts.owner_id],
120
- is_archived: false,
121
123
  punch_status: PunchStatusWorking,
122
124
  });
123
125
  const open = active.flatMap((week_sheet) => week_sheet.sheets.flatMap((day) => day.punches
124
126
  .filter((p) => p.punch_status === PunchStatusWorking)
125
127
  .map((punch) => ({ week_sheet, punch, week_day: day.week_day }))));
126
- requireState(open.length <= 1, TimesheetsBlock.Active);
127
- if (open[0]) {
128
- const current = open[0];
129
- const date = inDateAtTimestamp((await this.now()).toISOString(), current.punch.timezone);
130
- return {
128
+ open.sort((a, b) => timesheetDateTime(a.punch.punch_in_time) -
129
+ timesheetDateTime(b.punch.punch_in_time));
130
+ if (open.length) {
131
+ const now = await this.now();
132
+ const states = open.map((current) => ({
131
133
  ...current,
132
- stale_day: !sameDay(current.punch.punch_in_time, opts.date ?? date),
133
- };
134
+ stale_day: !sameDay(current.punch.punch_in_time, inDateAtTimestamp(now.toISOString(), current.punch.timezone)),
135
+ }));
136
+ const current = opts.target
137
+ ? states.find((state) => state.week_sheet.id === opts.target.week_sheet_id &&
138
+ timesheetDateTime(state.punch.punch_in_time) ===
139
+ timesheetDateTime(opts.target.start))
140
+ : states[0];
141
+ requireState(!!current, TimesheetsBlock.Changed);
142
+ return { ...current, open_punches: states };
134
143
  }
144
+ requireState(!opts.target, TimesheetsBlock.Changed);
135
145
  if (!opts.employer_id)
136
146
  return { week_day, stale_day: false };
137
147
  const indexes = await this.periods(opts.employer_id, today);
@@ -161,11 +171,23 @@ export class TimesheetsWorkspace {
161
171
  ...opts,
162
172
  action: PunchTypeIn,
163
173
  });
164
- const week_day = expected.week_day;
165
- const punch = week_sheet.sheets
166
- .find((day) => day.week_day === week_day)
167
- ?.punches.at(-1);
168
- expected = { week_sheet, punch, week_day, stale_day: false };
174
+ const day = week_sheet.sheets.find((day) => day.punches.some((p) => p.punch_status === PunchStatusWorking));
175
+ const punch = day?.punches.find((p) => p.punch_status === PunchStatusWorking);
176
+ requireState(!!day && !!punch, TimesheetsBlock.Unconfirmed);
177
+ expected = {
178
+ week_sheet,
179
+ punch,
180
+ week_day: day.week_day,
181
+ stale_day: false,
182
+ };
183
+ const now = await this.now();
184
+ opts = {
185
+ ...opts,
186
+ date: {
187
+ ...inDateAtTimestamp(now.toISOString(), punch.timezone),
188
+ utc: new Date(Math.floor(now.getTime() / 60_000) * 60_000).toISOString(),
189
+ },
190
+ };
169
191
  }
170
192
  return await this.performPunch({
171
193
  ...opts,
@@ -189,9 +211,19 @@ export class TimesheetsWorkspace {
189
211
  async performPunch(opts) {
190
212
  if (opts.date)
191
213
  await this.validateDay(opts.date, opts.timezone);
192
- const current = await this.punchState(opts);
214
+ const current = await this.punchState({
215
+ ...opts,
216
+ target: opts.expected.punch?.punch_status === PunchStatusWorking &&
217
+ opts.expected.week_sheet
218
+ ? {
219
+ week_sheet_id: opts.expected.week_sheet.id,
220
+ start: opts.expected.punch.punch_in_time,
221
+ }
222
+ : undefined,
223
+ });
193
224
  requireState(timesheetStateKey(current) === timesheetStateKey(opts.expected), TimesheetsBlock.Changed);
194
- requireState(!current.stale_day, TimesheetsBlock.InvalidDay);
225
+ requireState(!current.stale_day || !!opts.date, TimesheetsBlock.FinishRequired);
226
+ requireState(opts.action === PunchTypeOut || (current.open_punches?.length ?? 0) <= 1, TimesheetsBlock.Active);
195
227
  requireState(!current.week_sheet || timesheetIsMutable(current.week_sheet), TimesheetsBlock.Locked);
196
228
  const controls = this.actions.punchControls(current);
197
229
  const allowed = {
@@ -207,15 +239,22 @@ export class TimesheetsWorkspace {
207
239
  current.punch.timezone === opts.timezone, TimesheetsBlock.Changed);
208
240
  }
209
241
  if (opts.date && current.punch && opts.action !== PunchTypeIn) {
210
- requireState(sameDay(opts.date, current.punch.punch_in_time) &&
211
- wallTime(opts.date) >= wallTime(current.punch.punch_in_time), TimesheetsBlock.InvalidDay);
242
+ requireState(opts.action === PunchTypeOut
243
+ ? timesheetDateTime(opts.date) >
244
+ timesheetDateTime(current.punch.punch_in_time)
245
+ : timesheetDateTime(opts.date) >=
246
+ timesheetDateTime(current.punch.punch_in_time), TimesheetsBlock.InvalidDay);
247
+ requireState(timesheetDateTime(opts.date) <=
248
+ timesheetPunchDeadline(current.punch.punch_in_time), TimesheetsBlock.Duration);
212
249
  }
213
250
  opts.before_request?.();
214
251
  const context = {
215
252
  employer_id: opts.employer_id,
216
253
  location_id: opts.location_id,
217
254
  timezone: opts.timezone,
218
- explicit_date: opts.date ? schemaDate(opts.date) : undefined,
255
+ explicit_date: opts.date ? timesheetDate(opts.date) : undefined,
256
+ week_sheet_id: opts.action !== PunchTypeIn ? current.week_sheet?.id : undefined,
257
+ punch_in_date: opts.action !== PunchTypeIn ? current.punch?.punch_in_time : undefined,
219
258
  };
220
259
  const result = opts.action === PunchTypeIn
221
260
  ? await this.actions.punchIn(context)
@@ -230,9 +269,16 @@ export class TimesheetsWorkspace {
230
269
  : await this.actions.rideOut(context);
231
270
  requireState(!!result.id, TimesheetsBlock.Unconfirmed);
232
271
  const sheet = await this.week(result.id);
233
- const last = sheet.sheets
234
- .find((day) => day.week_day === current.week_day)
235
- ?.punches.at(-1);
272
+ const matches = sheet.sheets
273
+ .flatMap((day) => day.punches)
274
+ .filter((p) => p.location_id === opts.location_id &&
275
+ p.employer_id === opts.employer_id &&
276
+ (opts.action === PunchTypeIn
277
+ ? p.punch_status === PunchStatusWorking
278
+ : !!current.punch &&
279
+ timesheetDateTime(p.punch_in_time) ===
280
+ timesheetDateTime(current.punch.punch_in_time)));
281
+ const last = matches.length === 1 ? matches[0] : undefined;
236
282
  requireState(!!last &&
237
283
  last.location_id === opts.location_id &&
238
284
  !sheet.is_archived &&
@@ -248,14 +294,15 @@ export class TimesheetsWorkspace {
248
294
  async saveDay(opts) {
249
295
  await this.validateDay(opts.start, opts.timezone);
250
296
  await this.validateDay(opts.end, opts.timezone);
251
- requireState(sameDay(opts.start, opts.end) &&
252
- wallTime(opts.end) > wallTime(opts.start), TimesheetsBlock.InvalidDay);
253
- const indexes = await this.periods(opts.employer_id, opts.start);
254
- const matches = await this.weeks({
255
- owner_ids: [opts.owner_id],
256
- employer_ids: [opts.employer_id],
257
- period_indexes: indexes,
258
- });
297
+ requireState(timesheetDateTime(opts.end) > timesheetDateTime(opts.start), TimesheetsBlock.InvalidDay);
298
+ requireState(timesheetDateTime(opts.end) <= timesheetPunchDeadline(opts.start), TimesheetsBlock.Duration);
299
+ const matches = opts.replace
300
+ ? [await this.week(opts.replace.id)]
301
+ : await this.weeks({
302
+ owner_ids: [opts.owner_id],
303
+ employer_ids: [opts.employer_id],
304
+ period_indexes: await this.periods(opts.employer_id, opts.start),
305
+ });
259
306
  requireState(matches.length <= 1, TimesheetsBlock.Changed);
260
307
  const sheet = matches[0];
261
308
  const day = sheet?.sheets.find((d) => d.week_day === timesheetWeekDay(opts.start));
@@ -271,7 +318,6 @@ export class TimesheetsWorkspace {
271
318
  requireState(!day?.punches.some((p) => p.punch_status === PunchStatusWorking), TimesheetsBlock.Active);
272
319
  const open = await this.weeks({
273
320
  owner_ids: [opts.owner_id],
274
- is_archived: false,
275
321
  punch_status: PunchStatusWorking,
276
322
  });
277
323
  requireState(open.length === 0, TimesheetsBlock.Active);
@@ -279,8 +325,9 @@ export class TimesheetsWorkspace {
279
325
  employer_id: opts.employer_id,
280
326
  location_id: opts.location_id,
281
327
  timezone: opts.timezone,
282
- punch_in_date: schemaDate(opts.start),
283
- punch_out_date: schemaDate(opts.end),
328
+ week_sheet_id: sheet?.id,
329
+ punch_in_date: timesheetDate(opts.start),
330
+ punch_out_date: timesheetDate(opts.end),
284
331
  total_pause_minutes: opts.total_pause_minutes,
285
332
  total_meal_minutes: opts.total_meal_minutes,
286
333
  });
@@ -299,7 +346,8 @@ export class TimesheetsWorkspace {
299
346
  employer_id: sheet.employer_id,
300
347
  location_id: punch.location_id,
301
348
  timezone: punch.timezone,
302
- explicit_date: schemaDate(date),
349
+ explicit_date: timesheetDate(date),
350
+ week_sheet_id: sheet.id,
303
351
  });
304
352
  }
305
353
  async removeWeek(actor_id, expected) {
@@ -319,7 +367,7 @@ export class TimesheetsWorkspace {
319
367
  requireState(matches.length === 0, TimesheetsBlock.Changed);
320
368
  const result = await this.actions.createBlankWeekSheet({
321
369
  ...opts,
322
- explicit_date: schemaDate(opts.date),
370
+ explicit_date: timesheetDate(opts.date),
323
371
  });
324
372
  requireState(!!result.id, TimesheetsBlock.Unconfirmed);
325
373
  return this.week(result.id);
@@ -347,21 +395,8 @@ export class TimesheetsWorkspace {
347
395
  return sheet;
348
396
  }
349
397
  async validateDay(date, timezone) {
350
- const now = inDateAtTimestamp((await this.now()).toISOString(), timezone);
351
- const calendar = new Date(Date.UTC(date.y, date.m - 1, date.d));
352
- requireState(!!now &&
353
- date.tz === timezone &&
354
- date.y > 1 &&
355
- date.m >= 1 &&
356
- date.m <= 12 &&
357
- calendar.getUTCDate() === date.d &&
358
- Number.isInteger(date.h) &&
359
- date.h >= 0 &&
360
- date.h < 24 &&
361
- Number.isInteger(date.min) &&
362
- date.min >= 0 &&
363
- date.min < 60 &&
364
- wallTime(date) <= wallTime(now), TimesheetsBlock.InvalidDay);
398
+ const now = await this.now();
399
+ requireState(date.tz === timezone && timesheetDateTime(date) <= now.getTime(), TimesheetsBlock.InvalidDay);
365
400
  }
366
401
  }
367
402
  function emptyScope(opts) {
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@fabriktor/fx",
3
- "version": "0.0.193",
3
+ "version": "0.0.195",
4
4
  "description": "![Fabriktor Logo](./img/fabriktor-character.gif)",
5
5
  "type": "module",
6
6
  "exports": {
@@ -17,9 +17,9 @@
17
17
  "typescript": "^6.0.3"
18
18
  },
19
19
  "dependencies": {
20
- "@fabriktor/client": "0.0.117",
20
+ "@fabriktor/client": "0.0.119",
21
21
  "@fabriktor/fx": "0.0.94",
22
- "@fabriktor/schema": "0.0.88",
22
+ "@fabriktor/schema": "0.0.89",
23
23
  "convert": "8.0.2"
24
24
  }
25
25
  }