@fabriktor/fx 0.0.192 → 0.0.194

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,7 @@
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;
@@ -0,0 +1,38 @@
1
+ import { inDateAtTimestamp, isValidInputDate, isZeroDateTime, } from "../core/date.js";
2
+ import { PreActionBlocked } from "../core/pre-action.js";
3
+ const minuteMS = 60_000;
4
+ const hourMS = 60 * minuteMS;
5
+ // Return actual instants for civil input; gaps have none and repeated DST times have two.
6
+ export function timesheetDateChoices(value) {
7
+ if (!isValidInputDate(value))
8
+ return [];
9
+ const wall = Date.UTC(value.y, value.m - 1, value.d, value.h, value.min);
10
+ const offsets = new Set();
11
+ for (let h = -48; h <= 48; h += 6) {
12
+ const instant = wall + h * hourMS;
13
+ const local = inDateAtTimestamp(new Date(instant).toISOString(), value.tz);
14
+ offsets.add(Date.UTC(local.y, local.m - 1, local.d, local.h, local.min) - instant);
15
+ }
16
+ const out = [];
17
+ for (const offset of offsets) {
18
+ const utc = new Date(wall - offset).toISOString();
19
+ const local = inDateAtTimestamp(utc, value.tz);
20
+ if (["y", "m", "d", "h", "min"].every((key) => local[key] === value[key]))
21
+ out.push({ ...value, utc });
22
+ }
23
+ return out.sort((a, b) => Date.parse(a.utc) - Date.parse(b.utc));
24
+ }
25
+ export function timesheetDate(value) {
26
+ const choices = timesheetDateChoices(value);
27
+ const selected = value.utc && !isZeroDateTime(value.utc)
28
+ ? choices.find((choice) => Date.parse(choice.utc) === Date.parse(value.utc))
29
+ : choices.length === 1
30
+ ? choices[0]
31
+ : undefined;
32
+ if (!selected)
33
+ throw new PreActionBlocked("timesheets_invalid_day");
34
+ return selected;
35
+ }
36
+ export function timesheetDateTime(value) {
37
+ return Date.parse(timesheetDate(value).utc);
38
+ }
@@ -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,7 @@ 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";
50
57
  readonly InvalidSync: "timesheets_invalid_sync";
51
58
  readonly Unconfirmed: "timesheets_unconfirmed";
52
59
  };
@@ -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, } 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,7 @@ export const TimesheetsBlock = {
10
11
  Locked: "timesheets_locked",
11
12
  Active: "timesheets_active",
12
13
  InvalidDay: "timesheets_invalid_day",
14
+ FinishRequired: "timesheets_finish_required",
13
15
  InvalidSync: "timesheets_invalid_sync",
14
16
  Unconfirmed: "timesheets_unconfirmed",
15
17
  };
@@ -35,17 +37,20 @@ export function timesheetCanApprove(sheet) {
35
37
  }
36
38
  export function timesheetCanSyncSource(sheet) {
37
39
  const punches = timesheetPunches(sheet);
38
- return punches.length > 0 && punches.every((punch) => punch.punch_status === PunchStatusPending || punch.punch_status === PunchStatusApproved);
40
+ return (punches.length > 0 &&
41
+ punches.every((punch) => punch.punch_status === PunchStatusPending ||
42
+ punch.punch_status === PunchStatusApproved));
39
43
  }
40
44
  export function timesheetCanSync(source, destination) {
41
- return timesheetCanSyncSource(source) && !destination.is_archived &&
45
+ return (timesheetCanSyncSource(source) &&
46
+ !destination.is_archived &&
42
47
  timesheetPunches(destination).every((punch) => punch.punch_status === PunchStatusPending) &&
43
48
  destination.employer_id === source.employer_id &&
44
49
  destination.id !== source.id &&
45
50
  destination.period_index === source.period_index &&
46
51
  destination.period === source.period &&
47
52
  destination.period_year === source.period_year &&
48
- destination.timezone === source.timezone;
53
+ destination.timezone === source.timezone);
49
54
  }
50
55
  export function timesheetStateKey(state) {
51
56
  return JSON.stringify([
@@ -63,13 +68,6 @@ export function timesheetWeekDay(date) {
63
68
  function sameDay(a, b) {
64
69
  return a.y === b.y && a.m === b.m && a.d === b.d;
65
70
  }
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
71
  export class TimesheetsWorkspace {
74
72
  client;
75
73
  actions;
@@ -111,27 +109,35 @@ export class TimesheetsWorkspace {
111
109
  }
112
110
  async punchState(opts) {
113
111
  requireState(!!opts.owner_id && !!opts.timezone, TimesheetsBlock.InvalidDay);
114
- const today = opts.date ?? inDateAtTimestamp((await this.now()).toISOString(), opts.timezone);
112
+ const today = opts.date ??
113
+ inDateAtTimestamp((await this.now()).toISOString(), opts.timezone);
115
114
  const week_day = timesheetWeekDay(today);
116
115
  // Check every open work punch, including other employers/locations/weeks.
117
116
  // A scope selection must never hide an already open shift.
118
117
  const active = await this.weeks({
119
118
  owner_ids: [opts.owner_id],
120
- is_archived: false,
121
119
  punch_status: PunchStatusWorking,
122
120
  });
123
121
  const open = active.flatMap((week_sheet) => week_sheet.sheets.flatMap((day) => day.punches
124
122
  .filter((p) => p.punch_status === PunchStatusWorking)
125
123
  .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 {
124
+ open.sort((a, b) => timesheetDateTime(a.punch.punch_in_time) -
125
+ timesheetDateTime(b.punch.punch_in_time));
126
+ if (open.length) {
127
+ const now = await this.now();
128
+ const states = open.map((current) => ({
131
129
  ...current,
132
- stale_day: !sameDay(current.punch.punch_in_time, opts.date ?? date),
133
- };
130
+ stale_day: !sameDay(current.punch.punch_in_time, inDateAtTimestamp(now.toISOString(), current.punch.timezone)),
131
+ }));
132
+ const current = opts.target
133
+ ? states.find((state) => state.week_sheet.id === opts.target.week_sheet_id &&
134
+ timesheetDateTime(state.punch.punch_in_time) ===
135
+ timesheetDateTime(opts.target.start))
136
+ : states[0];
137
+ requireState(!!current, TimesheetsBlock.Changed);
138
+ return { ...current, open_punches: states };
134
139
  }
140
+ requireState(!opts.target, TimesheetsBlock.Changed);
135
141
  if (!opts.employer_id)
136
142
  return { week_day, stale_day: false };
137
143
  const indexes = await this.periods(opts.employer_id, today);
@@ -161,11 +167,23 @@ export class TimesheetsWorkspace {
161
167
  ...opts,
162
168
  action: PunchTypeIn,
163
169
  });
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 };
170
+ const day = week_sheet.sheets.find((day) => day.punches.some((p) => p.punch_status === PunchStatusWorking));
171
+ const punch = day?.punches.find((p) => p.punch_status === PunchStatusWorking);
172
+ requireState(!!day && !!punch, TimesheetsBlock.Unconfirmed);
173
+ expected = {
174
+ week_sheet,
175
+ punch,
176
+ week_day: day.week_day,
177
+ stale_day: false,
178
+ };
179
+ const now = await this.now();
180
+ opts = {
181
+ ...opts,
182
+ date: {
183
+ ...inDateAtTimestamp(now.toISOString(), punch.timezone),
184
+ utc: new Date(Math.floor(now.getTime() / 60_000) * 60_000).toISOString(),
185
+ },
186
+ };
169
187
  }
170
188
  return await this.performPunch({
171
189
  ...opts,
@@ -189,9 +207,19 @@ export class TimesheetsWorkspace {
189
207
  async performPunch(opts) {
190
208
  if (opts.date)
191
209
  await this.validateDay(opts.date, opts.timezone);
192
- const current = await this.punchState(opts);
210
+ const current = await this.punchState({
211
+ ...opts,
212
+ target: opts.expected.punch?.punch_status === PunchStatusWorking &&
213
+ opts.expected.week_sheet
214
+ ? {
215
+ week_sheet_id: opts.expected.week_sheet.id,
216
+ start: opts.expected.punch.punch_in_time,
217
+ }
218
+ : undefined,
219
+ });
193
220
  requireState(timesheetStateKey(current) === timesheetStateKey(opts.expected), TimesheetsBlock.Changed);
194
- requireState(!current.stale_day, TimesheetsBlock.InvalidDay);
221
+ requireState(!current.stale_day || !!opts.date, TimesheetsBlock.FinishRequired);
222
+ requireState(opts.action === PunchTypeOut || (current.open_punches?.length ?? 0) <= 1, TimesheetsBlock.Active);
195
223
  requireState(!current.week_sheet || timesheetIsMutable(current.week_sheet), TimesheetsBlock.Locked);
196
224
  const controls = this.actions.punchControls(current);
197
225
  const allowed = {
@@ -207,15 +235,20 @@ export class TimesheetsWorkspace {
207
235
  current.punch.timezone === opts.timezone, TimesheetsBlock.Changed);
208
236
  }
209
237
  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);
238
+ requireState(opts.action === PunchTypeOut
239
+ ? timesheetDateTime(opts.date) >
240
+ timesheetDateTime(current.punch.punch_in_time)
241
+ : timesheetDateTime(opts.date) >=
242
+ timesheetDateTime(current.punch.punch_in_time), TimesheetsBlock.InvalidDay);
212
243
  }
213
244
  opts.before_request?.();
214
245
  const context = {
215
246
  employer_id: opts.employer_id,
216
247
  location_id: opts.location_id,
217
248
  timezone: opts.timezone,
218
- explicit_date: opts.date ? schemaDate(opts.date) : undefined,
249
+ explicit_date: opts.date ? timesheetDate(opts.date) : undefined,
250
+ week_sheet_id: opts.action !== PunchTypeIn ? current.week_sheet?.id : undefined,
251
+ punch_in_date: opts.action !== PunchTypeIn ? current.punch?.punch_in_time : undefined,
219
252
  };
220
253
  const result = opts.action === PunchTypeIn
221
254
  ? await this.actions.punchIn(context)
@@ -230,9 +263,16 @@ export class TimesheetsWorkspace {
230
263
  : await this.actions.rideOut(context);
231
264
  requireState(!!result.id, TimesheetsBlock.Unconfirmed);
232
265
  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);
266
+ const matches = sheet.sheets
267
+ .flatMap((day) => day.punches)
268
+ .filter((p) => p.location_id === opts.location_id &&
269
+ p.employer_id === opts.employer_id &&
270
+ (opts.action === PunchTypeIn
271
+ ? p.punch_status === PunchStatusWorking
272
+ : !!current.punch &&
273
+ timesheetDateTime(p.punch_in_time) ===
274
+ timesheetDateTime(current.punch.punch_in_time)));
275
+ const last = matches.length === 1 ? matches[0] : undefined;
236
276
  requireState(!!last &&
237
277
  last.location_id === opts.location_id &&
238
278
  !sheet.is_archived &&
@@ -248,14 +288,14 @@ export class TimesheetsWorkspace {
248
288
  async saveDay(opts) {
249
289
  await this.validateDay(opts.start, opts.timezone);
250
290
  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
- });
291
+ requireState(timesheetDateTime(opts.end) > timesheetDateTime(opts.start), TimesheetsBlock.InvalidDay);
292
+ const matches = opts.replace
293
+ ? [await this.week(opts.replace.id)]
294
+ : await this.weeks({
295
+ owner_ids: [opts.owner_id],
296
+ employer_ids: [opts.employer_id],
297
+ period_indexes: await this.periods(opts.employer_id, opts.start),
298
+ });
259
299
  requireState(matches.length <= 1, TimesheetsBlock.Changed);
260
300
  const sheet = matches[0];
261
301
  const day = sheet?.sheets.find((d) => d.week_day === timesheetWeekDay(opts.start));
@@ -271,7 +311,6 @@ export class TimesheetsWorkspace {
271
311
  requireState(!day?.punches.some((p) => p.punch_status === PunchStatusWorking), TimesheetsBlock.Active);
272
312
  const open = await this.weeks({
273
313
  owner_ids: [opts.owner_id],
274
- is_archived: false,
275
314
  punch_status: PunchStatusWorking,
276
315
  });
277
316
  requireState(open.length === 0, TimesheetsBlock.Active);
@@ -279,8 +318,9 @@ export class TimesheetsWorkspace {
279
318
  employer_id: opts.employer_id,
280
319
  location_id: opts.location_id,
281
320
  timezone: opts.timezone,
282
- punch_in_date: schemaDate(opts.start),
283
- punch_out_date: schemaDate(opts.end),
321
+ week_sheet_id: sheet?.id,
322
+ punch_in_date: timesheetDate(opts.start),
323
+ punch_out_date: timesheetDate(opts.end),
284
324
  total_pause_minutes: opts.total_pause_minutes,
285
325
  total_meal_minutes: opts.total_meal_minutes,
286
326
  });
@@ -299,7 +339,8 @@ export class TimesheetsWorkspace {
299
339
  employer_id: sheet.employer_id,
300
340
  location_id: punch.location_id,
301
341
  timezone: punch.timezone,
302
- explicit_date: schemaDate(date),
342
+ explicit_date: timesheetDate(date),
343
+ week_sheet_id: sheet.id,
303
344
  });
304
345
  }
305
346
  async removeWeek(actor_id, expected) {
@@ -319,7 +360,7 @@ export class TimesheetsWorkspace {
319
360
  requireState(matches.length === 0, TimesheetsBlock.Changed);
320
361
  const result = await this.actions.createBlankWeekSheet({
321
362
  ...opts,
322
- explicit_date: schemaDate(opts.date),
363
+ explicit_date: timesheetDate(opts.date),
323
364
  });
324
365
  requireState(!!result.id, TimesheetsBlock.Unconfirmed);
325
366
  return this.week(result.id);
@@ -347,21 +388,8 @@ export class TimesheetsWorkspace {
347
388
  return sheet;
348
389
  }
349
390
  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);
391
+ const now = await this.now();
392
+ requireState(date.tz === timezone && timesheetDateTime(date) <= now.getTime(), TimesheetsBlock.InvalidDay);
365
393
  }
366
394
  }
367
395
  function emptyScope(opts) {
@@ -1,6 +1,6 @@
1
1
  import { type InUser, type User } from "@fabriktor/schema";
2
2
  export type UserCardInput = Pick<InUser, "bio" | "urls" | "show_as_company" | "banner_id" | "banner_preview">;
3
- export type UserCardIdentity = Pick<User, "id" | "username" | "full_name" | "company_name"> & Partial<Pick<User, "show_as_company">>;
3
+ export type UserCardIdentity = Pick<User, "id" | "username" | "full_name" | "company_name"> & Partial<Pick<User, "account_identity" | "show_as_company">>;
4
4
  export type BannerFrame = {
5
5
  x: number;
6
6
  y: number;
@@ -1,4 +1,4 @@
1
- import { ZeroID, HTTPSScheme, UserURLHostPattern, UserBioMaxLength, UserURLsMaxCount, UserURLMaxLength, UserBannerMaxBytes, UserBannerWidth, UserBannerHeight, } from "@fabriktor/schema";
1
+ import { ZeroID, HTTPSScheme, UserURLHostPattern, UserBioMaxLength, UserURLsMaxCount, UserURLMaxLength, UserBannerMaxBytes, UserBannerWidth, UserBannerHeight, UserTypeEmployer, } from "@fabriktor/schema";
2
2
  import { errValidation } from "../core/err.js";
3
3
  import { publicLinkURL } from "../core/links.js";
4
4
  import { resolvedID } from "../core/id.js";
@@ -9,7 +9,7 @@ const msgBannerRequired = "A valid banner preview is required.";
9
9
  export const defaultBannerFrame = { x: 0.5, y: 0.5, zoom: 1 };
10
10
  export const bannerMaxZoom = 4;
11
11
  export function userDisplayName(user) {
12
- return ((user.show_as_company
12
+ return ((user.account_identity === UserTypeEmployer && user.show_as_company
13
13
  ? user.company_name?.trim()
14
14
  : user.full_name?.trim()) ||
15
15
  user.full_name?.trim() ||
@@ -35,6 +35,7 @@ export type UpdateUserProfileOptions = GetByUIDOptions & {
35
35
  export type PublicUserProfileOptions = Parameters<UsersOperator["publicProfile"]>[0];
36
36
  export type UpdateUserCardOptions = GetByUIDOptions & {
37
37
  id: string;
38
+ account_identity: User["account_identity"];
38
39
  in: UserCardInput;
39
40
  signal?: AbortSignal;
40
41
  };
@@ -165,6 +165,8 @@ export class UsersFX {
165
165
  }
166
166
  async updateUserCard(opts) {
167
167
  const input = normalizeUserCardInput(opts.in);
168
+ input.show_as_company =
169
+ opts.account_identity === UserTypeEmployer && input.show_as_company;
168
170
  validateUserCardInput(input);
169
171
  if (!resolvedID(opts.id) || !opts.uid.trim())
170
172
  throw errValidation({ msg: msgProfileRequired });
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@fabriktor/fx",
3
- "version": "0.0.192",
3
+ "version": "0.0.194",
4
4
  "description": "![Fabriktor Logo](./img/fabriktor-character.gif)",
5
5
  "type": "module",
6
6
  "exports": {
@@ -17,7 +17,7 @@
17
17
  "typescript": "^6.0.3"
18
18
  },
19
19
  "dependencies": {
20
- "@fabriktor/client": "0.0.117",
20
+ "@fabriktor/client": "0.0.118",
21
21
  "@fabriktor/fx": "0.0.94",
22
22
  "@fabriktor/schema": "0.0.88",
23
23
  "convert": "8.0.2"