sahab-utils 2.1.8 → 2.2.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/index.d.ts CHANGED
@@ -16,6 +16,7 @@ export * from './ts/orderActivity';
16
16
  export * from './ts/orderAdjustment';
17
17
  export * from './ts/payLink';
18
18
  export * from './ts/tap';
19
+ export * from './ts/providerApi';
19
20
  export * from './ts/push';
20
21
  export * from './ts/utils';
21
22
  export * from './ts/wheel';
package/dist/index.js CHANGED
@@ -32,6 +32,7 @@ __exportStar(require("./ts/orderActivity"), exports);
32
32
  __exportStar(require("./ts/orderAdjustment"), exports);
33
33
  __exportStar(require("./ts/payLink"), exports);
34
34
  __exportStar(require("./ts/tap"), exports);
35
+ __exportStar(require("./ts/providerApi"), exports);
35
36
  __exportStar(require("./ts/push"), exports);
36
37
  __exportStar(require("./ts/utils"), exports);
37
38
  __exportStar(require("./ts/wheel"), exports);
@@ -1,10 +1,10 @@
1
1
  import type { Permissions, StaffRole } from './staffAccess';
2
2
  /** Which alerts a back-office admin gets. The shared contract between sahab-website (the Admin notifications page) and cloudFun. */
3
3
  /** App (push) alerts, each sent to the admin's customer-app account. */
4
- export declare const ADMIN_PUSH_KINDS: readonly ["newOrder", "newCarwash", "newGift", "newClient", "newCarModel", "needsAttention", "statements"];
4
+ export declare const ADMIN_PUSH_KINDS: readonly ["newOrder", "newCarwash", "newGift", "newClient", "newCarModel", "needsAttention", "statements", "newApiApp", "newApiConnection"];
5
5
  export type AdminPushKind = (typeof ADMIN_PUSH_KINDS)[number];
6
6
  /** Every switch on the page: the app alerts plus the lead e-mail. */
7
- export declare const ADMIN_NOTIFICATION_KEYS: readonly ["newOrder", "newCarwash", "newGift", "newClient", "newCarModel", "needsAttention", "statements", "leadEmails"];
7
+ export declare const ADMIN_NOTIFICATION_KEYS: readonly ["newOrder", "newCarwash", "newGift", "newClient", "newCarModel", "needsAttention", "statements", "newApiApp", "newApiConnection", "leadEmails"];
8
8
  export type AdminNotificationKey = (typeof ADMIN_NOTIFICATION_KEYS)[number];
9
9
  export type AdminNotificationPrefs = Record<AdminNotificationKey, boolean>;
10
10
  export declare const ADMIN_NOTIFICATION_LABELS: Record<AdminNotificationKey, {
@@ -4,7 +4,7 @@ exports.isValidAppUid = exports.isValidAdminEmail = exports.normalizeAdminEmail
4
4
  exports.normalizeAdminNotificationPrefs = normalizeAdminNotificationPrefs;
5
5
  /** Which alerts a back-office admin gets. The shared contract between sahab-website (the Admin notifications page) and cloudFun. */
6
6
  /** App (push) alerts, each sent to the admin's customer-app account. */
7
- exports.ADMIN_PUSH_KINDS = ['newOrder', 'newCarwash', 'newGift', 'newClient', 'newCarModel', 'needsAttention', 'statements'];
7
+ exports.ADMIN_PUSH_KINDS = ['newOrder', 'newCarwash', 'newGift', 'newClient', 'newCarModel', 'needsAttention', 'statements', 'newApiApp', 'newApiConnection'];
8
8
  /** Every switch on the page: the app alerts plus the lead e-mail. */
9
9
  exports.ADMIN_NOTIFICATION_KEYS = [...exports.ADMIN_PUSH_KINDS, 'leadEmails'];
10
10
  exports.ADMIN_NOTIFICATION_LABELS = {
@@ -15,6 +15,8 @@ exports.ADMIN_NOTIFICATION_LABELS = {
15
15
  newCarModel: { label: 'Car model to review', description: 'An order uses a car model Sahab has not reviewed yet.' },
16
16
  needsAttention: { label: 'Carwash needs attention', description: 'A carwash changed something that needs a look.' },
17
17
  statements: { label: 'Statements', description: 'The daily and weekly statements are ready.' },
18
+ newApiApp: { label: 'New API app', description: 'A developer creates an app on the provider API.' },
19
+ newApiConnection: { label: 'New API connection', description: 'A carwash connects an outside app to its account.' },
18
20
  leadEmails: { label: 'Lead e-mails', description: 'A visitor sends an enquiry or a carwash request on the website.' },
19
21
  };
20
22
  /** Nothing is switched on until an admin is set up. */
@@ -19,12 +19,16 @@ export declare function isPackageVisit(order?: Order): boolean;
19
19
  /** What the minimum is compared against: what the customer paid. A visit holds only a slice of the
20
20
  * package, so it uses the package price — otherwise later visits of a qualifying package would not stamp. */
21
21
  export declare function loyaltyQualifyingAmount(order: Order): number;
22
+ /** Why a finished order does not earn a stamp; the one place the reasons are decided, so the rule and the verdict kept on the order cannot disagree. */
23
+ export type LoyaltyRefusal = 'no_offer' | 'not_settled' | 'unpaid' | 'other_provider' | 'gift_redemption' | 'loyalty_redemption' | 'below_minimum';
24
+ /** The first reason `order` earns no stamp for `offer`, or undefined when it does. */
25
+ export declare function loyaltyStampRefusal(order: Order | undefined, offer: Discount | undefined): LoyaltyRefusal | undefined;
22
26
  /** Whether a finished order earns a stamp. For a multi-visit package this is asked per visit: every
23
27
  * completed visit earns one, not the package once. A redemption order earns none. */
24
28
  export declare function orderEarnsLoyaltyStamp(order: Order | undefined, offer: Discount | undefined): boolean;
25
29
  export type LoyaltyCheckResult = 'stamped' | 'not_eligible' | 'already_counted';
26
30
  /** One offer's verdict on a completed order, kept on `order.loyaltyChecks`. The offer can be edited later, so its
27
- * terms are copied; the parts with no Firestore dependency — the server adds `checkedAt`. */
31
+ * terms are copied. This part has no Firestore dependency; the server adds `checkedAt`. */
28
32
  export type LoyaltyCheckFields = {
29
33
  promoCodeId: string;
30
34
  buyQuantity: number;
@@ -32,6 +36,8 @@ export type LoyaltyCheckFields = {
32
36
  /** What the minimum was compared against (`loyaltyQualifyingAmount`). */
33
37
  qualifyingAmount: number;
34
38
  result: LoyaltyCheckResult;
39
+ /** Why it was not eligible; absent for the other results. */
40
+ reason?: LoyaltyRefusal;
35
41
  };
36
42
  /** The verdict to record for `order` against `offer`, with the terms in force right now. */
37
43
  export declare function loyaltyCheckFields(order: Order, offer: Discount, result: LoyaltyCheckResult): LoyaltyCheckFields;
@@ -8,6 +8,7 @@ exports.loyaltyOfferMatchesTestMode = loyaltyOfferMatchesTestMode;
8
8
  exports.isLoyaltyRedemption = isLoyaltyRedemption;
9
9
  exports.isPackageVisit = isPackageVisit;
10
10
  exports.loyaltyQualifyingAmount = loyaltyQualifyingAmount;
11
+ exports.loyaltyStampRefusal = loyaltyStampRefusal;
11
12
  exports.orderEarnsLoyaltyStamp = orderEarnsLoyaltyStamp;
12
13
  exports.loyaltyCheckFields = loyaltyCheckFields;
13
14
  exports.giftEarnsLoyaltyStamp = giftEarnsLoyaltyStamp;
@@ -78,39 +79,38 @@ function loyaltyQualifyingAmount(order) {
78
79
  return (0, utils_1.preventNaN)(order.originalPrice);
79
80
  return (0, calcs_1.getCustomerTotalToPay)(order);
80
81
  }
81
- /** Whether a finished order earns a stamp. For a multi-visit package this is asked per visit: every
82
- * completed visit earns one, not the package once. A redemption order earns none. */
83
- function orderEarnsLoyaltyStamp(order, offer) {
82
+ /** The first reason `order` earns no stamp for `offer`, or undefined when it does. */
83
+ function loyaltyStampRefusal(order, offer) {
84
84
  var _a, _b;
85
85
  if (!order || !(offer === null || offer === void 0 ? void 0 : offer.loyalty))
86
- return false;
86
+ return 'no_offer';
87
87
  if (!SETTLED_STATUSES.includes((_a = order.orderStatus) !== null && _a !== void 0 ? _a : types_1.OrderStatus.PENDING))
88
- return false;
88
+ return 'not_settled';
89
89
  if (!order.isPaid)
90
- return false;
90
+ return 'unpaid';
91
91
  if (!loyaltyCoversProvider(offer, order.providerId))
92
- return false;
92
+ return 'other_provider';
93
93
  // A gift redemption stamps the giver (who paid), not the recipient — see `giftEarnsLoyaltyStamp`.
94
94
  // Without this, the recipient's total is 0, so any programme with no minimum would wrongly stamp them.
95
95
  if ((0, gifts_1.isGiftRedemption)(order))
96
- return false;
96
+ return 'gift_redemption';
97
97
  if (isLoyaltyRedemption(order))
98
- return false;
98
+ return 'loyalty_redemption';
99
99
  const min = (0, utils_1.preventNaN)((_b = offer.loyalty.minOrderAmount) !== null && _b !== void 0 ? _b : 0);
100
100
  if (min > 0 && loyaltyQualifyingAmount(order) < min)
101
- return false;
102
- return true;
101
+ return 'below_minimum';
102
+ return undefined;
103
+ }
104
+ /** Whether a finished order earns a stamp. For a multi-visit package this is asked per visit: every
105
+ * completed visit earns one, not the package once. A redemption order earns none. */
106
+ function orderEarnsLoyaltyStamp(order, offer) {
107
+ return loyaltyStampRefusal(order, offer) === undefined;
103
108
  }
104
109
  /** The verdict to record for `order` against `offer`, with the terms in force right now. */
105
110
  function loyaltyCheckFields(order, offer, result) {
106
111
  var _a, _b, _c;
107
- return {
108
- promoCodeId: (_a = offer.promoCodeId) !== null && _a !== void 0 ? _a : '',
109
- buyQuantity: (0, utils_1.preventNaN)((_b = offer.loyalty) === null || _b === void 0 ? void 0 : _b.buyQuantity),
110
- minOrderAmount: (0, utils_1.preventNaN)((_c = offer.loyalty) === null || _c === void 0 ? void 0 : _c.minOrderAmount),
111
- qualifyingAmount: loyaltyQualifyingAmount(order),
112
- result,
113
- };
112
+ const reason = result === 'not_eligible' ? loyaltyStampRefusal(order, offer) : undefined;
113
+ return Object.assign({ promoCodeId: (_a = offer.promoCodeId) !== null && _a !== void 0 ? _a : '', buyQuantity: (0, utils_1.preventNaN)((_b = offer.loyalty) === null || _b === void 0 ? void 0 : _b.buyQuantity), minOrderAmount: (0, utils_1.preventNaN)((_c = offer.loyalty) === null || _c === void 0 ? void 0 : _c.minOrderAmount), qualifyingAmount: loyaltyQualifyingAmount(order), result }, (reason ? { reason } : {}));
114
114
  }
115
115
  /** Whether buying a gift earns the giver a stamp. Awarded at purchase, not redemption — the reward
116
116
  * shouldn't hinge on whether the recipient ever spends it. The minimum is fair here since the giver really paid it. */
@@ -0,0 +1,268 @@
1
+ import { CarSize } from '../constants/types';
2
+ /** The public provider API (api.sahabapp.net/v1): permissions, events, errors and the public order shape. Shared by cloudFun, the provider app, the back office and the developer portal. */
3
+ export declare const API_VERSION = "v1";
4
+ export declare const API_PERMISSIONS: readonly ["services.read", "drivers.read", "orders.events", "orders.create", "orders.payment_link", "orders.custom_total", "orders.cancel"];
5
+ export type ApiPermission = (typeof API_PERMISSIONS)[number];
6
+ /** A permission that only makes sense with another one. */
7
+ export declare const API_PERMISSION_REQUIRES: Partial<Record<ApiPermission, ApiPermission>>;
8
+ type Bilingual = {
9
+ ar: string;
10
+ en: string;
11
+ };
12
+ /** What a provider owner reads on the consent screen, in the provider app's formal register. */
13
+ export declare const API_PERMISSION_LABELS: Record<ApiPermission, {
14
+ label: Bilingual;
15
+ description: Bilingual;
16
+ }>;
17
+ export declare const isApiPermission: (value: unknown) => value is ApiPermission;
18
+ /** Known permissions, once each, in canonical order, limited to `allowed` when given; one whose requirement is missing is dropped. */
19
+ export declare function normalizeApiPermissions(raw: unknown, allowed?: readonly ApiPermission[]): ApiPermission[];
20
+ export declare const API_EVENT_TYPES: readonly ["order.created", "order.payment_pending", "order.paid", "order.payment_expired", "order.rescheduled", "order.reassigned", "order.started", "order.in_progress", "order.completed", "order.cancelled", "order.rated", "connection.created", "connection.revoked"];
21
+ export type ApiEventType = (typeof API_EVENT_TYPES)[number];
22
+ /** Every error the API answers, with its HTTP status. Codes are stable; messages may change. */
23
+ export declare const API_ERRORS: {
24
+ readonly invalid_request: {
25
+ readonly status: 400;
26
+ readonly message: "The request body is not valid.";
27
+ };
28
+ readonly invalid_api_key: {
29
+ readonly status: 401;
30
+ readonly message: "The API key is missing, unknown or revoked.";
31
+ };
32
+ readonly invalid_token: {
33
+ readonly status: 401;
34
+ readonly message: "The access token is missing, invalid or expired.";
35
+ };
36
+ readonly app_suspended: {
37
+ readonly status: 403;
38
+ readonly message: "This app is suspended. Contact Sahab support.";
39
+ };
40
+ readonly not_connected: {
41
+ readonly status: 403;
42
+ readonly message: "This provider has not connected the app, or revoked it.";
43
+ };
44
+ readonly permission_denied: {
45
+ readonly status: 403;
46
+ readonly message: "The provider did not grant the permission this call needs.";
47
+ };
48
+ readonly custom_total_not_allowed: {
49
+ readonly status: 403;
50
+ readonly message: "This provider is not allowed to charge a custom total.";
51
+ };
52
+ readonly live_orders_disabled: {
53
+ readonly status: 403;
54
+ readonly message: "Live orders are not enabled for this app yet. Use the test key.";
55
+ };
56
+ readonly not_found: {
57
+ readonly status: 404;
58
+ readonly message: "Not found.";
59
+ };
60
+ readonly unknown_driver: {
61
+ readonly status: 400;
62
+ readonly message: "The driver is not one of the provider’s active drivers.";
63
+ };
64
+ readonly unknown_service: {
65
+ readonly status: 400;
66
+ readonly message: "A service or add-on is not offered for this car size.";
67
+ };
68
+ readonly driver_busy: {
69
+ readonly status: 409;
70
+ readonly message: "The driver is busy at that time.";
71
+ };
72
+ readonly slot_unavailable: {
73
+ readonly status: 409;
74
+ readonly message: "The provider has no free capacity at that time.";
75
+ };
76
+ readonly not_cancellable: {
77
+ readonly status: 409;
78
+ readonly message: "The order can no longer be cancelled.";
79
+ };
80
+ readonly already_paid: {
81
+ readonly status: 409;
82
+ readonly message: "The customer already paid; the order was confirmed instead.";
83
+ };
84
+ readonly rate_limited: {
85
+ readonly status: 429;
86
+ readonly message: "Too many requests. Slow down and retry later.";
87
+ };
88
+ readonly limit_reached: {
89
+ readonly status: 429;
90
+ readonly message: "A daily limit was reached for this provider or phone number.";
91
+ };
92
+ readonly unavailable: {
93
+ readonly status: 503;
94
+ readonly message: "Temporarily unavailable. Retry with the same requestId.";
95
+ };
96
+ readonly server_error: {
97
+ readonly status: 500;
98
+ readonly message: "Something went wrong on our side. Quote the requestId to support.";
99
+ };
100
+ };
101
+ export type ApiErrorCode = keyof typeof API_ERRORS;
102
+ export type ApiErrorBody = {
103
+ error: {
104
+ code: ApiErrorCode | string;
105
+ message: string;
106
+ requestId: string;
107
+ detail?: string;
108
+ };
109
+ };
110
+ export type PublicOrderStatus = 'pending' | 'confirmed' | 'rejected' | 'expired' | 'in_progress' | 'completed' | 'cancelled' | 'rated' | 'started' | 'payment_pending';
111
+ export type PublicPaymentMethod = 'apple_pay' | 'card' | 'cash' | 'google_pay' | 'samsung_pay' | 'stc_pay' | 'tabby' | 'tamara' | 'payment_link' | 'none';
112
+ export type PublicOrderLine = {
113
+ type: 'service' | 'addon';
114
+ id: string | null;
115
+ name: Bilingual;
116
+ quantity: number;
117
+ unitPrice: number;
118
+ durationMinutes: number;
119
+ };
120
+ export type PublicVehicle = {
121
+ make: string;
122
+ model: string;
123
+ size: CarSize | null;
124
+ lines: PublicOrderLine[];
125
+ };
126
+ export type PublicOrderSource = 'customer' | 'provider' | 'api' | 'staff';
127
+ /** An order as an outside app sees it: the customer's first name only, no phone, e-mail, plate, saved places, payment ids or links. */
128
+ export type PublicOrder = {
129
+ id: string;
130
+ providerId: string;
131
+ status: PublicOrderStatus;
132
+ source: PublicOrderSource;
133
+ scheduledAt: string | null;
134
+ durationMinutes: number;
135
+ customer: {
136
+ firstName: string;
137
+ ref: string;
138
+ };
139
+ location: {
140
+ lat: number;
141
+ lng: number;
142
+ url: string | null;
143
+ } | null;
144
+ vehicles: PublicVehicle[];
145
+ driver: {
146
+ id: string;
147
+ name: string;
148
+ } | null;
149
+ payment: {
150
+ method: PublicPaymentMethod;
151
+ paid: boolean;
152
+ amount: number | null;
153
+ };
154
+ rating: number | null;
155
+ };
156
+ type Loose = Record<string, any>;
157
+ /** Builds the public order from an allowlist of fields; `customerRef` is an id scoped to the provider, computed by the server. */
158
+ export declare function toPublicOrder(order: Loose, { customerRef }: {
159
+ customerRef: string;
160
+ }): PublicOrder;
161
+ export type CancelReasonCode = 'cancelled_by_customer' | 'cancelled_by_provider' | 'cancelled_by_sahab' | 'payment_not_completed' | 'moved_to_another_provider' | 'removed';
162
+ export type Cancellation = {
163
+ by: 'customer' | 'provider' | 'sahab';
164
+ reasonCode: CancelReasonCode;
165
+ reason: string | null;
166
+ };
167
+ export type ApiEvent = {
168
+ id: string;
169
+ type: ApiEventType;
170
+ apiVersion: typeof API_VERSION;
171
+ createdAt: string;
172
+ providerId: string;
173
+ /** Grows with every change to one order, so a receiver can drop events older than one it already applied. */
174
+ sequence: number;
175
+ data: {
176
+ order?: PublicOrder | {
177
+ id: string;
178
+ providerId: string;
179
+ status: PublicOrderStatus;
180
+ };
181
+ cancellation?: Cancellation;
182
+ previous?: {
183
+ scheduledAt?: string | null;
184
+ driver?: {
185
+ id: string;
186
+ name: string;
187
+ } | null;
188
+ };
189
+ connection?: {
190
+ providerId: string;
191
+ providerName: Bilingual;
192
+ permissions: ApiPermission[];
193
+ };
194
+ };
195
+ };
196
+ export type ApiService = {
197
+ id: string;
198
+ type: 'service' | 'addon';
199
+ name: Bilingual;
200
+ durationMinutes: number;
201
+ prices: {
202
+ carSize: CarSize;
203
+ price: number;
204
+ }[];
205
+ };
206
+ export type ApiDriver = {
207
+ id: string;
208
+ name: string;
209
+ };
210
+ export type ApiConnection = {
211
+ providerId: string;
212
+ providerName: Bilingual;
213
+ permissions: ApiPermission[];
214
+ status: 'active' | 'revoked';
215
+ connectedAt: string | null;
216
+ };
217
+ export type ApiTokenResponse = {
218
+ accessToken: string;
219
+ tokenType: 'Bearer';
220
+ expiresIn: number;
221
+ providerId: string;
222
+ permissions: ApiPermission[];
223
+ mode: 'live' | 'test';
224
+ };
225
+ /** POST /v1/provider/orders. The provider comes from the token, never the body. */
226
+ export type ApiCreateOrderRequest = {
227
+ requestId: string;
228
+ scheduledAt: string;
229
+ driverId?: string;
230
+ durationMinutes?: number;
231
+ locationUrl?: string;
232
+ location?: {
233
+ lat: number;
234
+ lng: number;
235
+ };
236
+ customer?: {
237
+ phone?: string;
238
+ language?: 'ar' | 'en';
239
+ };
240
+ paymentLink?: boolean;
241
+ carSize?: CarSize;
242
+ serviceIds?: string[];
243
+ addonIds?: string[];
244
+ customTotal?: number;
245
+ };
246
+ export type ApiCreateOrderResponse = {
247
+ orderId: string;
248
+ status: PublicOrderStatus;
249
+ smsSent: boolean;
250
+ paymentLinkUrl: string | null;
251
+ paymentDeadline: string | null;
252
+ };
253
+ /** What a test key answers: realistic data that never touches a real provider. */
254
+ export declare const API_SANDBOX: {
255
+ providerId: string;
256
+ providerName: {
257
+ ar: string;
258
+ en: string;
259
+ };
260
+ services: ApiService[];
261
+ drivers: ApiDriver[];
262
+ customerFirstName: string;
263
+ location: {
264
+ lat: number;
265
+ lng: number;
266
+ };
267
+ };
268
+ export {};
@@ -0,0 +1,199 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.API_SANDBOX = exports.API_ERRORS = exports.API_EVENT_TYPES = exports.isApiPermission = exports.API_PERMISSION_LABELS = exports.API_PERMISSION_REQUIRES = exports.API_PERMISSIONS = exports.API_VERSION = void 0;
4
+ exports.normalizeApiPermissions = normalizeApiPermissions;
5
+ exports.toPublicOrder = toPublicOrder;
6
+ const types_1 = require("../constants/types");
7
+ /** The public provider API (api.sahabapp.net/v1): permissions, events, errors and the public order shape. Shared by cloudFun, the provider app, the back office and the developer portal. */
8
+ exports.API_VERSION = 'v1';
9
+ exports.API_PERMISSIONS = ['services.read', 'drivers.read', 'orders.events', 'orders.create', 'orders.payment_link', 'orders.custom_total', 'orders.cancel'];
10
+ /** A permission that only makes sense with another one. */
11
+ exports.API_PERMISSION_REQUIRES = {
12
+ 'orders.payment_link': 'orders.create',
13
+ 'orders.custom_total': 'orders.payment_link',
14
+ };
15
+ /** What a provider owner reads on the consent screen, in the provider app's formal register. */
16
+ exports.API_PERMISSION_LABELS = {
17
+ 'services.read': {
18
+ label: { ar: 'عرض الخدمات', en: 'View services' },
19
+ description: { ar: 'قراءة خدماتك وإضافاتك وأسعارها حسب حجم السيارة.', en: 'Read your services and add-ons with their prices per car size.' },
20
+ },
21
+ 'drivers.read': {
22
+ label: { ar: 'عرض السائقين', en: 'View drivers' },
23
+ description: { ar: 'قراءة أسماء سائقيك فقط.', en: 'Read your drivers’ names only.' },
24
+ },
25
+ 'orders.events': {
26
+ label: { ar: 'استلام الطلبات', en: 'Receive orders' },
27
+ description: { ar: 'إشعار التطبيق بطلباتك الجديدة وتحديثاتها.', en: 'Notify the app of your new orders and their updates.' },
28
+ },
29
+ 'orders.create': {
30
+ label: { ar: 'إنشاء مواعيد', en: 'Create bookings' },
31
+ description: { ar: 'حجز مواعيد في جدولك نيابة عنك.', en: 'Book slots in your schedule on your behalf.' },
32
+ },
33
+ 'orders.payment_link': {
34
+ label: { ar: 'إرسال روابط دفع', en: 'Send payment links' },
35
+ description: { ar: 'إرسال رسالة نصية للعميل برابط دفع بأسعار خدماتك.', en: 'Text the customer a payment link at your service prices.' },
36
+ },
37
+ 'orders.custom_total': {
38
+ label: { ar: 'تحديد مبلغ مخصص', en: 'Set a custom total' },
39
+ description: { ar: 'إرسال رابط دفع بمبلغ تحدده بدل أسعار الخدمات.', en: 'Send a payment link for an amount you set instead of service prices.' },
40
+ },
41
+ 'orders.cancel': {
42
+ label: { ar: 'إلغاء الطلبات', en: 'Cancel bookings' },
43
+ description: { ar: 'إلغاء الطلبات التي أنشأها هذا التطبيق فقط.', en: 'Cancel only the bookings this app created.' },
44
+ },
45
+ };
46
+ const isApiPermission = (value) => exports.API_PERMISSIONS.includes(value);
47
+ exports.isApiPermission = isApiPermission;
48
+ /** Known permissions, once each, in canonical order, limited to `allowed` when given; one whose requirement is missing is dropped. */
49
+ function normalizeApiPermissions(raw, allowed) {
50
+ const wanted = new Set((Array.isArray(raw) ? raw : []).filter(exports.isApiPermission));
51
+ const kept = exports.API_PERMISSIONS.filter((p) => wanted.has(p) && (!allowed || allowed.includes(p)));
52
+ const result = [];
53
+ for (const permission of kept) {
54
+ const needs = exports.API_PERMISSION_REQUIRES[permission];
55
+ if (!needs || result.includes(needs))
56
+ result.push(permission);
57
+ }
58
+ return result;
59
+ }
60
+ exports.API_EVENT_TYPES = [
61
+ 'order.created',
62
+ 'order.payment_pending',
63
+ 'order.paid',
64
+ 'order.payment_expired',
65
+ 'order.rescheduled',
66
+ 'order.reassigned',
67
+ 'order.started',
68
+ 'order.in_progress',
69
+ 'order.completed',
70
+ 'order.cancelled',
71
+ 'order.rated',
72
+ 'connection.created',
73
+ 'connection.revoked',
74
+ ];
75
+ /** Every error the API answers, with its HTTP status. Codes are stable; messages may change. */
76
+ exports.API_ERRORS = {
77
+ invalid_request: { status: 400, message: 'The request body is not valid.' },
78
+ invalid_api_key: { status: 401, message: 'The API key is missing, unknown or revoked.' },
79
+ invalid_token: { status: 401, message: 'The access token is missing, invalid or expired.' },
80
+ app_suspended: { status: 403, message: 'This app is suspended. Contact Sahab support.' },
81
+ not_connected: { status: 403, message: 'This provider has not connected the app, or revoked it.' },
82
+ permission_denied: { status: 403, message: 'The provider did not grant the permission this call needs.' },
83
+ custom_total_not_allowed: { status: 403, message: 'This provider is not allowed to charge a custom total.' },
84
+ live_orders_disabled: { status: 403, message: 'Live orders are not enabled for this app yet. Use the test key.' },
85
+ not_found: { status: 404, message: 'Not found.' },
86
+ unknown_driver: { status: 400, message: 'The driver is not one of the provider’s active drivers.' },
87
+ unknown_service: { status: 400, message: 'A service or add-on is not offered for this car size.' },
88
+ driver_busy: { status: 409, message: 'The driver is busy at that time.' },
89
+ slot_unavailable: { status: 409, message: 'The provider has no free capacity at that time.' },
90
+ not_cancellable: { status: 409, message: 'The order can no longer be cancelled.' },
91
+ already_paid: { status: 409, message: 'The customer already paid; the order was confirmed instead.' },
92
+ rate_limited: { status: 429, message: 'Too many requests. Slow down and retry later.' },
93
+ limit_reached: { status: 429, message: 'A daily limit was reached for this provider or phone number.' },
94
+ unavailable: { status: 503, message: 'Temporarily unavailable. Retry with the same requestId.' },
95
+ server_error: { status: 500, message: 'Something went wrong on our side. Quote the requestId to support.' },
96
+ };
97
+ const STATUS_NAMES = {
98
+ [types_1.OrderStatus.PENDING]: 'pending',
99
+ [types_1.OrderStatus.CONFIRMED]: 'confirmed',
100
+ [types_1.OrderStatus.REJECTED]: 'rejected',
101
+ [types_1.OrderStatus.EXPIRED]: 'expired',
102
+ [types_1.OrderStatus.IN_PROGRESS]: 'in_progress',
103
+ [types_1.OrderStatus.COMPLETED]: 'completed',
104
+ [types_1.OrderStatus.CANCELLED]: 'cancelled',
105
+ [types_1.OrderStatus.RATED]: 'rated',
106
+ [types_1.OrderStatus.STARTED]: 'started',
107
+ [types_1.OrderStatus.PENDING_PAYMENT]: 'payment_pending',
108
+ };
109
+ const PAYMENT_NAMES = {
110
+ [types_1.OrderPaymentType.APPLE_PAY]: 'apple_pay',
111
+ [types_1.OrderPaymentType.CREDIT]: 'card',
112
+ [types_1.OrderPaymentType.CASH]: 'cash',
113
+ [types_1.OrderPaymentType.GOOGLE_PAY]: 'google_pay',
114
+ [types_1.OrderPaymentType.SAMSUNG_PAY]: 'samsung_pay',
115
+ [types_1.OrderPaymentType.STC_PAY]: 'stc_pay',
116
+ [types_1.OrderPaymentType.TABBY]: 'tabby',
117
+ [types_1.OrderPaymentType.TAMARA]: 'tamara',
118
+ };
119
+ const isoOf = (value) => {
120
+ var _a, _b, _c;
121
+ if (!value)
122
+ return null;
123
+ if (typeof value.toMillis === 'function')
124
+ return new Date(value.toMillis()).toISOString();
125
+ const seconds = (_a = value.seconds) !== null && _a !== void 0 ? _a : value._seconds;
126
+ if (typeof seconds === 'number')
127
+ return new Date(seconds * 1000 + Math.floor(((_c = (_b = value.nanoseconds) !== null && _b !== void 0 ? _b : value._nanoseconds) !== null && _c !== void 0 ? _c : 0) / 1e6)).toISOString();
128
+ if (value instanceof Date)
129
+ return value.toISOString();
130
+ if (typeof value === 'number')
131
+ return new Date(value).toISOString();
132
+ return null;
133
+ };
134
+ const finite = (n) => typeof n === 'number' && Number.isFinite(n);
135
+ const text = (v) => (typeof v === 'string' ? v : '');
136
+ const bilingual = (v) => ({ ar: text(v === null || v === void 0 ? void 0 : v.ar), en: text(v === null || v === void 0 ? void 0 : v.en) });
137
+ function lineOf(line) {
138
+ var _a;
139
+ const isAddon = (line === null || line === void 0 ? void 0 : line.type) === 'addon';
140
+ return {
141
+ type: isAddon ? 'addon' : 'service',
142
+ id: text(isAddon ? line === null || line === void 0 ? void 0 : line.addonId : line === null || line === void 0 ? void 0 : line.serviceId) || null,
143
+ name: bilingual(line === null || line === void 0 ? void 0 : line.name),
144
+ quantity: finite(line === null || line === void 0 ? void 0 : line.quantity) && line.quantity > 0 ? line.quantity : 1,
145
+ unitPrice: finite((_a = line === null || line === void 0 ? void 0 : line.price) === null || _a === void 0 ? void 0 : _a.price) ? line.price.price : 0,
146
+ durationMinutes: finite(line === null || line === void 0 ? void 0 : line.time) ? line.time : 0,
147
+ };
148
+ }
149
+ const sourceOf = (order) => (order.createdByApp ? 'api' : order.createdByStaff ? 'staff' : order.crossedOrder || order.isDummyOrder ? 'provider' : 'customer');
150
+ /** Builds the public order from an allowlist of fields; `customerRef` is an id scoped to the provider, computed by the server. */
151
+ function toPublicOrder(order, { customerRef }) {
152
+ var _a, _b, _c, _d, _e, _f;
153
+ const vehicles = (Array.isArray(order.services) ? order.services : []).map((entry) => {
154
+ var _a, _b, _c;
155
+ return ({
156
+ make: text((_a = entry === null || entry === void 0 ? void 0 : entry.car) === null || _a === void 0 ? void 0 : _a.manufacturer),
157
+ model: text((_b = entry === null || entry === void 0 ? void 0 : entry.car) === null || _b === void 0 ? void 0 : _b.model),
158
+ size: finite((_c = entry === null || entry === void 0 ? void 0 : entry.car) === null || _c === void 0 ? void 0 : _c.size) ? entry.car.size : null,
159
+ lines: (Array.isArray(entry === null || entry === void 0 ? void 0 : entry.services) ? entry.services : []).map(lineOf),
160
+ });
161
+ });
162
+ const durationMinutes = vehicles.reduce((sum, v) => sum + v.lines.reduce((s, l) => s + l.durationMinutes * l.quantity, 0), 0);
163
+ const geo = order.location;
164
+ const lat = (_a = geo === null || geo === void 0 ? void 0 : geo.latitude) !== null && _a !== void 0 ? _a : geo === null || geo === void 0 ? void 0 : geo._latitude;
165
+ const lng = (_b = geo === null || geo === void 0 ? void 0 : geo.longitude) !== null && _b !== void 0 ? _b : geo === null || geo === void 0 ? void 0 : geo._longitude;
166
+ const driverId = text((_c = order.servedBy) === null || _c === void 0 ? void 0 : _c.id);
167
+ const status = (_d = STATUS_NAMES[order.orderStatus]) !== null && _d !== void 0 ? _d : 'pending';
168
+ const method = order.paymentLinkId ? 'payment_link' : (_e = PAYMENT_NAMES[order.paymentType]) !== null && _e !== void 0 ? _e : 'none';
169
+ return {
170
+ id: text(order.orderId),
171
+ providerId: text(order.providerId),
172
+ status,
173
+ source: sourceOf(order),
174
+ scheduledAt: isoOf(order.orderDate),
175
+ durationMinutes,
176
+ customer: { firstName: text((_f = order.client) === null || _f === void 0 ? void 0 : _f.firstName).trim(), ref: customerRef },
177
+ location: finite(lat) && finite(lng) ? { lat, lng, url: text(order.locationUrl) || null } : null,
178
+ vehicles,
179
+ driver: driverId && driverId !== text(order.providerId) ? { id: driverId, name: text(order.servedByName) } : null,
180
+ payment: { method, paid: order.isPaid === true, amount: order.isDummyOrder ? null : finite(order.paymentAmount) ? order.paymentAmount : null },
181
+ rating: (status === 'rated' || order.orderStatus === types_1.OrderStatus.RATED) && finite(order.clientRating) && order.clientRating > 0 ? order.clientRating : null,
182
+ };
183
+ }
184
+ /** What a test key answers: realistic data that never touches a real provider. */
185
+ exports.API_SANDBOX = {
186
+ providerId: 'prov_test_0001',
187
+ providerName: { ar: 'مغسلة تجريبية', en: 'Test Carwash' },
188
+ services: [
189
+ { id: 'svc_test_exterior', type: 'service', name: { ar: 'غسيل خارجي', en: 'Exterior wash' }, durationMinutes: 30, prices: [{ carSize: types_1.CarSize.SMALL, price: 41.2 }, { carSize: types_1.CarSize.MEDIUM, price: 51.5 }, { carSize: types_1.CarSize.LARGE, price: 61.8 }] },
190
+ { id: 'svc_test_full', type: 'service', name: { ar: 'غسيل داخلي وخارجي', en: 'Full wash' }, durationMinutes: 60, prices: [{ carSize: types_1.CarSize.SMALL, price: 82.4 }, { carSize: types_1.CarSize.MEDIUM, price: 92.7 }, { carSize: types_1.CarSize.LARGE, price: 103 }] },
191
+ { id: 'add_test_wax', type: 'addon', name: { ar: 'تلميع', en: 'Wax' }, durationMinutes: 15, prices: [{ carSize: types_1.CarSize.SMALL, price: 20.6 }, { carSize: types_1.CarSize.MEDIUM, price: 20.6 }, { carSize: types_1.CarSize.LARGE, price: 25.75 }] },
192
+ ],
193
+ drivers: [
194
+ { id: 'drv_test_0001', name: 'Test Driver One' },
195
+ { id: 'drv_test_0002', name: 'Test Driver Two' },
196
+ ],
197
+ customerFirstName: 'Sara',
198
+ location: { lat: 24.7136, lng: 46.6753 },
199
+ };
@@ -11,7 +11,8 @@ export declare enum Permissions {
11
11
  VIEW_PROMO = 7,// 7
12
12
  VIEW_BANNERS = 8,// 8
13
13
  VIEW_INVESTOR_NUMBERS = 9,// 9
14
- VIEW_CAR_MODELS = 10
14
+ VIEW_CAR_MODELS = 10,// 10
15
+ VIEW_API_APPS = 11
15
16
  }
16
17
  export declare const ALL_PERMISSIONS: Permissions[];
17
18
  export declare const PERMISSION_LABELS: Record<Permissions, {
@@ -17,6 +17,7 @@ var Permissions;
17
17
  Permissions[Permissions["VIEW_BANNERS"] = 8] = "VIEW_BANNERS";
18
18
  Permissions[Permissions["VIEW_INVESTOR_NUMBERS"] = 9] = "VIEW_INVESTOR_NUMBERS";
19
19
  Permissions[Permissions["VIEW_CAR_MODELS"] = 10] = "VIEW_CAR_MODELS";
20
+ Permissions[Permissions["VIEW_API_APPS"] = 11] = "VIEW_API_APPS";
20
21
  })(Permissions || (exports.Permissions = Permissions = {}));
21
22
  exports.ALL_PERMISSIONS = [
22
23
  Permissions.VIEW_KPI,
@@ -30,6 +31,7 @@ exports.ALL_PERMISSIONS = [
30
31
  Permissions.VIEW_BANNERS,
31
32
  Permissions.VIEW_INVESTOR_NUMBERS,
32
33
  Permissions.VIEW_CAR_MODELS,
34
+ Permissions.VIEW_API_APPS,
33
35
  ];
34
36
  exports.PERMISSION_LABELS = {
35
37
  [Permissions.VIEW_KPI]: { label: 'KPIs', description: 'Business KPIs for a chosen period.' },
@@ -43,6 +45,7 @@ exports.PERMISSION_LABELS = {
43
45
  [Permissions.VIEW_BANNERS]: { label: 'Banners', description: 'The app banners.' },
44
46
  [Permissions.VIEW_INVESTOR_NUMBERS]: { label: 'Investor numbers', description: 'Financial and unit-economics figures.' },
45
47
  [Permissions.VIEW_CAR_MODELS]: { label: 'Car models', description: 'Review car models customers entered, and fix the size of unverified cars.' },
48
+ [Permissions.VIEW_API_APPS]: { label: 'API apps', description: 'Developer apps on the provider API, their connections and failures; suspend an app.' },
46
49
  };
47
50
  /** ADMIN opens every page; STAFF opens only the pages in their list. */
48
51
  exports.STAFF_ROLES = ['ADMIN', 'STAFF'];
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "sahab-utils",
3
- "version": "2.1.8",
3
+ "version": "2.2.0",
4
4
  "description": "This package contains types and utils functions",
5
5
  "main": "dist/index.js",
6
6
  "types": "dist/index.d.ts",
@@ -8,7 +8,7 @@
8
8
  "build": "tsc",
9
9
  "prepublishOnly": "npm run build",
10
10
  "deploy": "npm run build && npm publish",
11
- "test": "npm run build && node tests/loyalty.test.js && node tests/gifts.test.js && node tests/cashback.test.js && node tests/utils.test.js && node tests/wheel.test.js && node tests/calcs.test.js && node tests/orderActivity.test.js && node tests/push.test.js && node tests/broadcast.test.js && node tests/iban.test.js && node tests/cash.test.js && node tests/workingHours.test.js && node tests/payLink.test.js && node tests/offerings.test.js && node tests/capacity.test.js && node tests/tap.test.js && node tests/orderAdjustment.test.js && node tests/adminNotifications.test.js && node tests/staffAccess.test.js && node tests/carCatalogue.test.js && node tests/crossedOrder.test.js"
11
+ "test": "npm run build && node tests/loyalty.test.js && node tests/gifts.test.js && node tests/cashback.test.js && node tests/utils.test.js && node tests/wheel.test.js && node tests/calcs.test.js && node tests/orderActivity.test.js && node tests/push.test.js && node tests/broadcast.test.js && node tests/iban.test.js && node tests/cash.test.js && node tests/workingHours.test.js && node tests/payLink.test.js && node tests/offerings.test.js && node tests/capacity.test.js && node tests/tap.test.js && node tests/orderAdjustment.test.js && node tests/adminNotifications.test.js && node tests/staffAccess.test.js && node tests/carCatalogue.test.js && node tests/crossedOrder.test.js && node tests/providerApi.test.js"
12
12
  },
13
13
  "repository": {
14
14
  "type": "git",
@@ -24,7 +24,8 @@
24
24
  },
25
25
  "homepage": "https://github.com/SahabApp/sahab-utils#readme",
26
26
  "files": [
27
- "dist"
27
+ "dist",
28
+ "openapi"
28
29
  ],
29
30
  "devDependencies": {
30
31
  "@types/lodash": "^4.17.24",