@fabriktor/fx 0.0.184 → 0.0.186

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.
@@ -42,6 +42,7 @@ export * from "./notifications/route.js";
42
42
  export * from "./payments/payments.js";
43
43
  export * from "./payrolls/payrolls.js";
44
44
  export * from "./payrolls/workspace.js";
45
+ export * from "./preferences/app.js";
45
46
  export * from "./preferences/preferences.js";
46
47
  export * from "./privacy/privacy.js";
47
48
  export * from "./processes/processes.js";
package/dist/src/index.js CHANGED
@@ -42,6 +42,7 @@ export * from "./notifications/route.js";
42
42
  export * from "./payments/payments.js";
43
43
  export * from "./payrolls/payrolls.js";
44
44
  export * from "./payrolls/workspace.js";
45
+ export * from "./preferences/app.js";
45
46
  export * from "./preferences/preferences.js";
46
47
  export * from "./privacy/privacy.js";
47
48
  export * from "./processes/processes.js";
@@ -5,6 +5,7 @@ import { type NotificationsFXOperator } from "./notifications.js";
5
5
  export type NotificationInboxState = SearchState<Notification> & {
6
6
  readonly identity: string;
7
7
  readonly reading: readonly string[];
8
+ readonly deleting: readonly string[];
8
9
  readonly has_unread: boolean;
9
10
  };
10
11
  export type NotificationInboxOptions = {
@@ -17,6 +18,7 @@ export declare class NotificationInboxController {
17
18
  private readonly options;
18
19
  private readonly search;
19
20
  private readonly stopRead;
21
+ private readonly stopDelete;
20
22
  private ownerID;
21
23
  private identity;
22
24
  private session;
@@ -25,6 +27,8 @@ export declare class NotificationInboxController {
25
27
  private unreadRequest?;
26
28
  private hasUnread;
27
29
  private readonly reads;
30
+ private readonly deletes;
31
+ private readonly deleted;
28
32
  constructor(options: NotificationInboxOptions);
29
33
  get state(): NotificationInboxState;
30
34
  setOwner(owner_id?: string, session_id?: string): void;
@@ -32,6 +36,7 @@ export declare class NotificationInboxController {
32
36
  loadMore(): Promise<void>;
33
37
  retry(): Promise<void>;
34
38
  markRead(id: string): Promise<void>;
39
+ delete(id: string): Promise<boolean>;
35
40
  dispose(): void;
36
41
  private refreshUnread;
37
42
  private clear;
@@ -7,6 +7,7 @@ export class NotificationInboxController {
7
7
  options;
8
8
  search;
9
9
  stopRead;
10
+ stopDelete;
10
11
  ownerID = "";
11
12
  identity = "";
12
13
  session = new AbortController();
@@ -15,6 +16,8 @@ export class NotificationInboxController {
15
16
  unreadRequest;
16
17
  hasUnread = false;
17
18
  reads = new Map();
19
+ deletes = new Map();
20
+ deleted = new Set();
18
21
  constructor(options) {
19
22
  this.options = options;
20
23
  this.search = new SearchController({
@@ -27,12 +30,29 @@ export class NotificationInboxController {
27
30
  this.search.patchResult(id, { is_read: true });
28
31
  void this.refreshUnread();
29
32
  });
33
+ this.stopDelete = options.events.subscribe(NotificationsEvents.Deleted, ({ owner_id, id }) => {
34
+ if (owner_id !== this.ownerID)
35
+ return;
36
+ this.deleted.add(id);
37
+ this.unreadRequest?.abort();
38
+ this.publish();
39
+ // Refill the displayed pages: deleting a row shifts later page offsets.
40
+ void this.refresh();
41
+ });
30
42
  }
31
43
  get state() {
44
+ const state = this.search.state;
45
+ // An older in-flight response must never restore a confirmed deletion.
46
+ const results = state.results.filter((item) => !this.deleted.has(item.id));
32
47
  return {
33
- ...this.search.state,
48
+ ...state,
49
+ results,
50
+ total_count: state.total_count === undefined
51
+ ? undefined
52
+ : Math.max(0, state.total_count - (state.results.length - results.length)),
34
53
  identity: this.identity,
35
54
  reading: [...this.reads.keys()],
55
+ deleting: [...this.deletes.keys()],
36
56
  has_unread: this.hasUnread,
37
57
  };
38
58
  }
@@ -88,7 +108,7 @@ export class NotificationInboxController {
88
108
  await Promise.all([this.search.retry(), this.refreshUnread()]);
89
109
  }
90
110
  markRead(id) {
91
- if (!this.ownerID)
111
+ if (!this.ownerID || this.deleted.has(id) || this.deletes.has(id))
92
112
  return Promise.resolve();
93
113
  const pending = this.reads.get(id);
94
114
  if (pending)
@@ -115,8 +135,47 @@ export class NotificationInboxController {
115
135
  this.publish();
116
136
  return run;
117
137
  }
138
+ delete(id) {
139
+ if (!this.ownerID)
140
+ return Promise.resolve(false);
141
+ if (this.deleted.has(id))
142
+ return Promise.resolve(true);
143
+ const pending = this.deletes.get(id);
144
+ if (pending)
145
+ return pending;
146
+ const session = this.session;
147
+ const owner_id = this.ownerID;
148
+ const run = Promise.resolve()
149
+ .then(async () => {
150
+ // Finish an already-started read before deleting the same document.
151
+ await this.reads.get(id)?.catch(() => undefined);
152
+ if (session.signal.aborted)
153
+ return false;
154
+ await this.options.notifications.deleteNotification({
155
+ id,
156
+ owner_id,
157
+ signal: session.signal,
158
+ });
159
+ return !session.signal.aborted;
160
+ })
161
+ .catch((error) => {
162
+ if (session.signal.aborted)
163
+ return false;
164
+ throw error;
165
+ })
166
+ .finally(() => {
167
+ if (this.deletes.get(id) !== run)
168
+ return;
169
+ this.deletes.delete(id);
170
+ this.publish();
171
+ });
172
+ this.deletes.set(id, run);
173
+ this.publish();
174
+ return run;
175
+ }
118
176
  dispose() {
119
177
  this.stopRead();
178
+ this.stopDelete();
120
179
  this.clear();
121
180
  }
122
181
  async refreshUnread() {
@@ -155,6 +214,8 @@ export class NotificationInboxController {
155
214
  this.refreshing = undefined;
156
215
  this.refreshPending = false;
157
216
  this.reads.clear();
217
+ this.deletes.clear();
218
+ this.deleted.clear();
158
219
  this.search.clear();
159
220
  }
160
221
  publish() {
@@ -4,6 +4,7 @@ import { EventBus } from "../core/events.js";
4
4
  import { type OwnerSearchOptions, type SearchPage } from "../core/search.js";
5
5
  export declare const NotificationsEvents: {
6
6
  readonly Read: import("../index.js").EventKey<Pick<Notification, "id" | "owner_id">>;
7
+ readonly Deleted: import("../index.js").EventKey<Pick<Notification, "id" | "owner_id">>;
7
8
  };
8
9
  export type DeviceTokenProvider = () => Promise<string>;
9
10
  export type NotificationsFXOptions = {
@@ -14,6 +15,7 @@ export type NotificationsFXOptions = {
14
15
  export type SearchNotificationsOptions = OwnerSearchOptions & Partial<Pick<Notification, "is_read" | "notif_k" | "key">>;
15
16
  export type SearchNotificationsPage = SearchPage<Notification>;
16
17
  export type MarkNotificationReadOptions = RequestOptions & Pick<Notification, "id" | "owner_id">;
18
+ export type DeleteNotificationOptions = Pick<RequestOptions, "signal"> & Pick<Notification, "id" | "owner_id">;
17
19
  export type SyncDeviceTokenOptions = {
18
20
  owner_id: string;
19
21
  previous_id?: string;
@@ -28,6 +30,7 @@ export type SyncDeviceTokenResult = Awaited<ReturnType<NotificationsOperator["up
28
30
  export interface NotificationsFXOperator {
29
31
  searchNotifications(opts: SearchNotificationsOptions): Promise<SearchNotificationsPage>;
30
32
  markNotificationRead(opts: MarkNotificationReadOptions): Promise<void>;
33
+ deleteNotification(opts: DeleteNotificationOptions): Promise<void>;
31
34
  syncDeviceToken(opts: SyncDeviceTokenOptions): Promise<SyncDeviceTokenResult>;
32
35
  unregisterDeviceToken(opts: UnregisterDeviceTokenOptions): Promise<void>;
33
36
  }
@@ -38,6 +41,7 @@ export declare class NotificationsFX implements NotificationsFXOperator {
38
41
  constructor(opts: NotificationsFXOptions);
39
42
  searchNotifications(opts: SearchNotificationsOptions): Promise<SearchNotificationsPage>;
40
43
  markNotificationRead(opts: MarkNotificationReadOptions): Promise<void>;
44
+ deleteNotification(opts: DeleteNotificationOptions): Promise<void>;
41
45
  syncDeviceToken(opts: SyncDeviceTokenOptions): Promise<SyncDeviceTokenResult>;
42
46
  unregisterDeviceToken(opts: UnregisterDeviceTokenOptions): Promise<void>;
43
47
  }
@@ -1,11 +1,12 @@
1
1
  import { IDKey, OwnerIDKey, ZeroID, PushTransportFCM, } from "@fabriktor/schema";
2
- import { queryParams, } from "@fabriktor/client";
2
+ import { isClientErr, queryParams, } from "@fabriktor/client";
3
3
  import { errRequired } from "../core/err.js";
4
4
  import { createEvent, EventBus } from "../core/events.js";
5
5
  import { requiredOperationID, resolvedID } from "../core/id.js";
6
6
  import { runOwnerSearch, } from "../core/search.js";
7
7
  export const NotificationsEvents = {
8
8
  Read: createEvent(),
9
+ Deleted: createEvent(),
9
10
  };
10
11
  const msgOwnerIDRequired = "Owner ID is required.";
11
12
  const msgNotificationIDRequired = "Notification ID is required.";
@@ -60,6 +61,35 @@ export class NotificationsFX {
60
61
  });
61
62
  this.events.publish(NotificationsEvents.Read, { owner_id, id });
62
63
  }
64
+ async deleteNotification(opts) {
65
+ const owner_id = resolvedID(opts.owner_id);
66
+ if (owner_id === undefined) {
67
+ throw errRequired({
68
+ field: OwnerIDKey,
69
+ msg: msgOwnerIDRequired,
70
+ });
71
+ }
72
+ const id = resolvedID(opts.id);
73
+ if (id === undefined) {
74
+ throw errRequired({
75
+ field: IDKey,
76
+ msg: msgNotificationIDRequired,
77
+ });
78
+ }
79
+ opts.signal?.throwIfAborted();
80
+ try {
81
+ await this.notifications.deleteOneNotification({
82
+ id,
83
+ signal: opts.signal,
84
+ });
85
+ }
86
+ catch (error) {
87
+ if (!isClientErr(error) || error.status !== 404)
88
+ throw error;
89
+ }
90
+ opts.signal?.throwIfAborted();
91
+ this.events.publish(NotificationsEvents.Deleted, { owner_id, id });
92
+ }
63
93
  async syncDeviceToken(opts) {
64
94
  const owner_id = opts.owner_id.trim();
65
95
  if (owner_id === "" || owner_id === ZeroID) {
@@ -0,0 +1,33 @@
1
+ import { type ColorMode, type InPrefApp } from "@fabriktor/schema";
2
+ import type { PreferencesFXOperator } from "./preferences.js";
3
+ export declare const colorModes: readonly ["light", "concrete", "dark"];
4
+ export declare function isColorMode(value: unknown): value is ColorMode;
5
+ export type AppPreferencesInput = Pick<InPrefApp, "color_mode" | "quiet_mode">;
6
+ export type AppPreferencesState = AppPreferencesInput & {
7
+ readonly ready: boolean;
8
+ readonly loading: boolean;
9
+ readonly saving: boolean;
10
+ readonly show_unread: boolean;
11
+ readonly error?: unknown;
12
+ };
13
+ export type AppPreferencesOptions = {
14
+ preferences: Pick<PreferencesFXOperator, "getPrefApp" | "savePrefApp">;
15
+ on_change: (state: AppPreferencesState) => void;
16
+ on_error?: (error: unknown) => void;
17
+ };
18
+ export declare class AppPreferencesController {
19
+ private readonly options;
20
+ private ownerID;
21
+ private identity;
22
+ private session;
23
+ private current?;
24
+ private pending?;
25
+ private saving;
26
+ private error?;
27
+ constructor(options: AppPreferencesOptions);
28
+ get state(): AppPreferencesState;
29
+ setOwner(ownerID?: string, identity?: string): void;
30
+ refresh(): Promise<void>;
31
+ save(input: Partial<AppPreferencesInput>): Promise<void>;
32
+ private publish;
33
+ }
@@ -0,0 +1,127 @@
1
+ import { ColorModeConcrete, ColorModeDark, ColorModeLight, } from "@fabriktor/schema";
2
+ import { notifyObserver } from "../core/events.js";
3
+ import { errRequired, errValidation } from "../core/err.js";
4
+ export const colorModes = [
5
+ ColorModeLight,
6
+ ColorModeConcrete,
7
+ ColorModeDark,
8
+ ];
9
+ export function isColorMode(value) {
10
+ return colorModes.some((mode) => mode === value);
11
+ }
12
+ // One account's presentation preferences. Notification delivery and unread data
13
+ // remain independent of this state.
14
+ export class AppPreferencesController {
15
+ options;
16
+ ownerID = "";
17
+ identity = "";
18
+ session = new AbortController();
19
+ current;
20
+ pending;
21
+ saving = false;
22
+ error;
23
+ constructor(options) {
24
+ this.options = options;
25
+ }
26
+ get state() {
27
+ const quiet = this.current?.quiet_mode ?? false;
28
+ return {
29
+ color_mode: this.current?.color_mode ?? ColorModeDark,
30
+ quiet_mode: quiet,
31
+ ready: this.current !== undefined,
32
+ loading: this.pending !== undefined,
33
+ saving: this.saving,
34
+ show_unread: this.current !== undefined && !quiet,
35
+ error: this.error,
36
+ };
37
+ }
38
+ setOwner(ownerID = "", identity = "") {
39
+ if (ownerID === this.ownerID && identity === this.identity)
40
+ return;
41
+ this.session.abort();
42
+ this.session = new AbortController();
43
+ this.ownerID = ownerID;
44
+ this.identity = identity;
45
+ this.current = undefined;
46
+ this.pending = undefined;
47
+ this.saving = false;
48
+ this.error = undefined;
49
+ this.publish();
50
+ if (ownerID)
51
+ void this.refresh();
52
+ }
53
+ refresh() {
54
+ if (this.pending)
55
+ return this.pending;
56
+ if (!this.ownerID || this.saving)
57
+ return Promise.resolve();
58
+ const signal = this.session.signal;
59
+ const ownerID = this.ownerID;
60
+ const pending = Promise.resolve().then(async () => {
61
+ try {
62
+ const pref = await this.options.preferences.getPrefApp({
63
+ owner_id: ownerID,
64
+ signal,
65
+ });
66
+ if (signal.aborted)
67
+ return;
68
+ this.current = pref;
69
+ this.error = undefined;
70
+ }
71
+ catch (error) {
72
+ if (signal.aborted)
73
+ return;
74
+ this.error = error;
75
+ notifyObserver(() => this.options.on_error?.(error));
76
+ }
77
+ finally {
78
+ if (!signal.aborted) {
79
+ this.pending = undefined;
80
+ this.publish();
81
+ }
82
+ }
83
+ });
84
+ this.pending = pending;
85
+ this.publish();
86
+ return pending;
87
+ }
88
+ async save(input) {
89
+ if (!this.ownerID)
90
+ throw errRequired({ field: "owner_id", msg: "An account is required." });
91
+ if (this.saving)
92
+ throw errValidation({
93
+ msg: "Application preferences are already being saved.",
94
+ });
95
+ const signal = this.session.signal;
96
+ const ownerID = this.ownerID;
97
+ this.saving = true;
98
+ this.publish();
99
+ try {
100
+ await this.pending;
101
+ if (signal.aborted)
102
+ return;
103
+ const pref = await this.options.preferences.savePrefApp({
104
+ owner_id: ownerID,
105
+ in: input,
106
+ signal,
107
+ });
108
+ if (signal.aborted)
109
+ return;
110
+ this.current = pref;
111
+ this.error = undefined;
112
+ }
113
+ catch (error) {
114
+ if (!signal.aborted)
115
+ throw error;
116
+ }
117
+ finally {
118
+ if (!signal.aborted) {
119
+ this.saving = false;
120
+ this.publish();
121
+ }
122
+ }
123
+ }
124
+ publish() {
125
+ notifyObserver(() => this.options.on_change(this.state));
126
+ }
127
+ }
@@ -1,6 +1,13 @@
1
1
  import type { PreferencesOperator } from "@fabriktor/client";
2
- import { type InPrefClient, type InPrefCompany, type InPrefEmployee, type OperationResult, type PrefPayment, type PrefClient, type PrefEmployee, type PrefCompany, type PrefVisibility, type PrefLanguage, type PrefNotif, type PrefEmail, type PrefTutorial } from "@fabriktor/schema";
2
+ import { type InPrefApp, type PrefApp, type InPrefClient, type InPrefCompany, type InPrefEmployee, type OperationResult, type PrefPayment, type PrefClient, type PrefEmployee, type PrefCompany, type PrefVisibility, type PrefLanguage, type PrefNotif, type PrefEmail, type PrefTutorial } from "@fabriktor/schema";
3
3
  import { EventBus } from "../core/events.js";
4
+ export type GetPrefAppOptions = {
5
+ owner_id: string;
6
+ signal?: AbortSignal;
7
+ };
8
+ export type SavePrefAppOptions = GetPrefAppOptions & {
9
+ in: Partial<Pick<InPrefApp, "color_mode" | "quiet_mode">>;
10
+ };
4
11
  export declare const PreferencesEvents: {
5
12
  readonly CompanySaved: import("../index.js").EventKey<PrefCompany>;
6
13
  };
@@ -85,6 +92,8 @@ export type SaveSpeechToTextSourceLanguageOptions = {
85
92
  speech_to_text_source_language: string;
86
93
  };
87
94
  export interface PreferencesFXOperator {
95
+ getPrefApp(opts: GetPrefAppOptions): Promise<PrefApp>;
96
+ savePrefApp(opts: SavePrefAppOptions): Promise<PrefApp>;
88
97
  createPrefPayment(opts: CreatePrefPaymentOptions): Promise<PrefPayment>;
89
98
  replacePrefPayment(opts: ReplacePrefPaymentOptions): Promise<PrefPayment>;
90
99
  createPrefClient(opts: CreatePrefClientOptions): Promise<PrefClient>;
@@ -122,6 +131,8 @@ export declare class PreferencesFX implements PreferencesFXOperator {
122
131
  private preferences;
123
132
  private readonly events;
124
133
  constructor(opts: PreferencesFXOptions);
134
+ getPrefApp(opts: GetPrefAppOptions): Promise<PrefApp>;
135
+ savePrefApp(opts: SavePrefAppOptions): Promise<PrefApp>;
125
136
  createPrefPayment(opts: CreatePrefPaymentOptions): Promise<PrefPayment>;
126
137
  replacePrefPayment(opts: ReplacePrefPaymentOptions): Promise<PrefPayment>;
127
138
  createPrefClient(opts: CreatePrefClientOptions): Promise<PrefClient>;
@@ -1,8 +1,9 @@
1
1
  import { queryParam } from "@fabriktor/client";
2
2
  import { OwnerIDKey, } from "@fabriktor/schema";
3
- import { errResolveFailed } from "../core/err.js";
3
+ import { errResolveFailed, errRequired, errValidation } from "../core/err.js";
4
4
  import { createEvent, EventBus } from "../core/events.js";
5
5
  import { requiredOperationID } from "../core/id.js";
6
+ import { isColorMode } from "./app.js";
6
7
  export const PreferencesEvents = {
7
8
  CompanySaved: createEvent(),
8
9
  };
@@ -44,6 +45,97 @@ export class PreferencesFX {
44
45
  this.preferences = opts.preferences;
45
46
  this.events = opts.events ?? new EventBus();
46
47
  }
48
+ async getPrefApp(opts) {
49
+ if (!opts.owner_id.trim())
50
+ throw errRequired({ field: "owner_id", msg: "An account is required." });
51
+ const out = await this.preferences.queryPrefApps({
52
+ query: queryParam(OwnerIDKey, opts.owner_id),
53
+ signal: opts.signal,
54
+ });
55
+ const pref = out.value?.[0];
56
+ if (!pref)
57
+ throw errResolveFailed({
58
+ resource: "pref_app",
59
+ msg: "Application preferences could not be resolved.",
60
+ });
61
+ return pref;
62
+ }
63
+ async savePrefApp(opts) {
64
+ if (opts.in.color_mode !== undefined && !isColorMode(opts.in.color_mode)) {
65
+ throw errValidation({
66
+ field: "color_mode",
67
+ msg: "Unsupported color mode.",
68
+ });
69
+ }
70
+ if (opts.in.quiet_mode !== undefined &&
71
+ typeof opts.in.quiet_mode !== "boolean") {
72
+ throw errValidation({
73
+ field: "quiet_mode",
74
+ msg: "Quiet mode must be a boolean.",
75
+ });
76
+ }
77
+ let pref = await this.getPrefApp(opts);
78
+ opts.signal?.throwIfAborted();
79
+ // Patch only the requested fields; another device may change the other setting.
80
+ const input = { is_default: false };
81
+ if (opts.in.color_mode !== undefined)
82
+ input.color_mode = opts.in.color_mode;
83
+ if (opts.in.quiet_mode !== undefined)
84
+ input.quiet_mode = opts.in.quiet_mode;
85
+ if (opts.in.color_mode === undefined && opts.in.quiet_mode === undefined)
86
+ return pref;
87
+ let id = pref.id;
88
+ if (pref.is_default) {
89
+ try {
90
+ const out = await this.preferences.insertOnePrefApp({
91
+ in: {
92
+ is_default: false,
93
+ color_mode: opts.in.color_mode ?? pref.color_mode,
94
+ quiet_mode: opts.in.quiet_mode ?? pref.quiet_mode,
95
+ },
96
+ signal: opts.signal,
97
+ });
98
+ id = requiredOperationID(out, "Created application preference response did not contain an ID.");
99
+ }
100
+ catch (error) {
101
+ // A concurrent first save or a lost response can leave a persisted record.
102
+ opts.signal?.throwIfAborted();
103
+ try {
104
+ pref = await this.getPrefApp(opts);
105
+ }
106
+ catch {
107
+ throw error;
108
+ }
109
+ opts.signal?.throwIfAborted();
110
+ if (pref.is_default)
111
+ throw error;
112
+ id = pref.id;
113
+ await this.preferences.replaceOnePrefApp({
114
+ id,
115
+ in: input,
116
+ signal: opts.signal,
117
+ });
118
+ }
119
+ }
120
+ else {
121
+ await this.preferences.replaceOnePrefApp({
122
+ id,
123
+ in: input,
124
+ signal: opts.signal,
125
+ });
126
+ }
127
+ opts.signal?.throwIfAborted();
128
+ const out = await this.preferences.findOnePrefApp({
129
+ id,
130
+ signal: opts.signal,
131
+ });
132
+ if (!out.value)
133
+ throw errResolveFailed({
134
+ resource: "pref_app",
135
+ msg: "Application preferences could not be resolved after saving.",
136
+ });
137
+ return out.value;
138
+ }
47
139
  async createPrefPayment(opts) {
48
140
  const out = await this.preferences.insertOnePrefPayment(opts);
49
141
  const id = requiredOperationID(out, msgCreatedPrefPaymentIDMissing);
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@fabriktor/fx",
3
- "version": "0.0.184",
3
+ "version": "0.0.186",
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.112",
20
+ "@fabriktor/client": "0.0.114",
21
21
  "@fabriktor/fx": "0.0.94",
22
- "@fabriktor/schema": "0.0.84",
22
+ "@fabriktor/schema": "0.0.85",
23
23
  "convert": "8.0.2"
24
24
  }
25
25
  }