@nymbalhq/platform 1.3.0 → 1.4.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/{chunk-2PLYK5RU.js → chunk-GMV3B3SC.js} +3369 -606
- package/dist/chunk-GMV3B3SC.js.map +1 -0
- package/dist/{chunk-QN56IB4G.js → chunk-SNNK2OX3.js} +119 -5
- package/dist/chunk-SNNK2OX3.js.map +1 -0
- package/dist/db/schema/index.d.ts +1766 -404
- package/dist/db/schema/index.js +1 -1
- package/dist/index.d.ts +224 -10
- package/dist/index.js +659 -2172
- package/dist/index.js.map +1 -1
- package/dist/register-N2XGSFUF.js +8 -0
- package/migrations/postgres/0013_order_access_keys.sql +11 -0
- package/migrations/postgres/0014_alert_subscriptions.sql +22 -0
- package/migrations/postgres/0015_events_retry_at.sql +1 -0
- package/migrations/postgres/meta/0013_snapshot.json +2000 -0
- package/migrations/postgres/meta/0014_snapshot.json +2185 -0
- package/migrations/postgres/meta/0015_snapshot.json +2191 -0
- package/migrations/postgres/meta/_journal.json +21 -0
- package/migrations/sqlite/0013_order_access_keys.sql +11 -0
- package/migrations/sqlite/0014_alert_subscriptions.sql +22 -0
- package/migrations/sqlite/0015_events_retry_at.sql +1 -0
- package/migrations/sqlite/meta/0013_snapshot.json +1788 -0
- package/migrations/sqlite/meta/0014_snapshot.json +1931 -0
- package/migrations/sqlite/meta/0015_snapshot.json +1938 -0
- package/migrations/sqlite/meta/_journal.json +21 -0
- package/package.json +19 -19
- package/dist/chunk-2PLYK5RU.js.map +0 -1
- package/dist/chunk-QN56IB4G.js.map +0 -1
- package/dist/register-UUQ64HZP.js +0 -8
- /package/dist/{register-UUQ64HZP.js.map → register-N2XGSFUF.js.map} +0 -0
|
@@ -5,11 +5,11 @@ import {
|
|
|
5
5
|
settings,
|
|
6
6
|
settings2,
|
|
7
7
|
sqlite_exports
|
|
8
|
-
} from "./chunk-
|
|
8
|
+
} from "./chunk-SNNK2OX3.js";
|
|
9
9
|
|
|
10
10
|
// src/routes/register.ts
|
|
11
11
|
import {
|
|
12
|
-
ConfigError as
|
|
12
|
+
ConfigError as ConfigError7
|
|
13
13
|
} from "@nymbalhq/types";
|
|
14
14
|
|
|
15
15
|
// src/events/correlation.ts
|
|
@@ -951,8 +951,659 @@ function createAuthMiddleware(auth) {
|
|
|
951
951
|
|
|
952
952
|
// src/routes/auth.ts
|
|
953
953
|
import {
|
|
954
|
-
AuthError
|
|
954
|
+
AuthError as AuthError3
|
|
955
|
+
} from "@nymbalhq/types";
|
|
956
|
+
|
|
957
|
+
// src/services/auth-service.ts
|
|
958
|
+
import { v7 as uuidv73 } from "uuid";
|
|
959
|
+
import bcrypt from "bcryptjs";
|
|
960
|
+
import { SignJWT, jwtVerify } from "jose";
|
|
961
|
+
import { createHash as createHash2 } from "crypto";
|
|
962
|
+
import {
|
|
963
|
+
AuthError,
|
|
964
|
+
EVT_CUSTOMER_CREATED,
|
|
965
|
+
ValidationError as ValidationError2
|
|
966
|
+
} from "@nymbalhq/types";
|
|
967
|
+
|
|
968
|
+
// src/history/views.ts
|
|
969
|
+
import {
|
|
970
|
+
paymentState
|
|
971
|
+
} from "@nymbalhq/types";
|
|
972
|
+
function orderViewOf(order) {
|
|
973
|
+
const {
|
|
974
|
+
notes: _notes,
|
|
975
|
+
metadata: _metadata,
|
|
976
|
+
updatedAt: _updatedAt,
|
|
977
|
+
capturedAt: _capturedAt,
|
|
978
|
+
captureMethod: _captureMethod,
|
|
979
|
+
...rest
|
|
980
|
+
} = order;
|
|
981
|
+
const { payment: _payment, history: _history, ...view } = rest;
|
|
982
|
+
return {
|
|
983
|
+
...view,
|
|
984
|
+
payment: {
|
|
985
|
+
state: paymentState(order),
|
|
986
|
+
capturedMinor: order.capturedMinor,
|
|
987
|
+
refundedMinor: order.refundedMinor,
|
|
988
|
+
currency: order.currency
|
|
989
|
+
}
|
|
990
|
+
};
|
|
991
|
+
}
|
|
992
|
+
function toProductAsOf(snapshot2) {
|
|
993
|
+
return {
|
|
994
|
+
...snapshot2,
|
|
995
|
+
variants: snapshot2.variants.map(({ updatedAt: _updatedAt, ...variant }) => variant),
|
|
996
|
+
// A set: product.created keeps the order it was sent in, a read the repository's.
|
|
997
|
+
categoryIds: [...snapshot2.categoryIds].sort()
|
|
998
|
+
};
|
|
999
|
+
}
|
|
1000
|
+
function toCustomerSnapshot(customer) {
|
|
1001
|
+
return {
|
|
1002
|
+
id: customer.id,
|
|
1003
|
+
email: customer.email,
|
|
1004
|
+
firstName: customer.firstName,
|
|
1005
|
+
lastName: customer.lastName,
|
|
1006
|
+
phone: customer.phone,
|
|
1007
|
+
addresses: customer.addresses,
|
|
1008
|
+
createdAt: customer.createdAt
|
|
1009
|
+
};
|
|
1010
|
+
}
|
|
1011
|
+
|
|
1012
|
+
// src/services/auth-service.ts
|
|
1013
|
+
var { hash: bcryptHash, compare: bcryptCompare } = bcrypt;
|
|
1014
|
+
function parseDurationToMs(s) {
|
|
1015
|
+
const match = /^(\d+)(ms|s|m|h|d)$/.exec(s);
|
|
1016
|
+
if (!match) throw new ValidationError2(`invalid duration: ${s}`);
|
|
1017
|
+
const qty = Number(match[1]);
|
|
1018
|
+
switch (match[2]) {
|
|
1019
|
+
case "ms":
|
|
1020
|
+
return qty;
|
|
1021
|
+
case "s":
|
|
1022
|
+
return qty * 1e3;
|
|
1023
|
+
case "m":
|
|
1024
|
+
return qty * 60 * 1e3;
|
|
1025
|
+
case "h":
|
|
1026
|
+
return qty * 60 * 60 * 1e3;
|
|
1027
|
+
case "d":
|
|
1028
|
+
return qty * 24 * 60 * 60 * 1e3;
|
|
1029
|
+
/* c8 ignore next 2 -- regex above only matches ms|s|m|h|d, making this unreachable */
|
|
1030
|
+
default:
|
|
1031
|
+
throw new ValidationError2(`invalid duration unit: ${match[2]}`);
|
|
1032
|
+
}
|
|
1033
|
+
}
|
|
1034
|
+
function hashRefresh(token) {
|
|
1035
|
+
return createHash2("sha256").update(token).digest("hex");
|
|
1036
|
+
}
|
|
1037
|
+
function stripPassword(c) {
|
|
1038
|
+
const { passwordHash: _pw, ...rest } = c;
|
|
1039
|
+
return rest;
|
|
1040
|
+
}
|
|
1041
|
+
function createAuthService(deps) {
|
|
1042
|
+
const { repos, publisher, logger, jwtSecret, accessTtl, refreshTtl } = deps;
|
|
1043
|
+
const { store } = repos.customer;
|
|
1044
|
+
const issuer = deps.issuer ?? "nymbal";
|
|
1045
|
+
const secretKey = new TextEncoder().encode(jwtSecret);
|
|
1046
|
+
const accessTtlMs = parseDurationToMs(accessTtl);
|
|
1047
|
+
const refreshTtlMs = parseDurationToMs(refreshTtl);
|
|
1048
|
+
async function mintAccess(customer) {
|
|
1049
|
+
return new SignJWT({
|
|
1050
|
+
sub: customer.id,
|
|
1051
|
+
email: customer.email,
|
|
1052
|
+
roles: customer.roles,
|
|
1053
|
+
type: "access"
|
|
1054
|
+
}).setProtectedHeader({ alg: "HS256" }).setIssuedAt().setIssuer(issuer).setExpirationTime(new Date(Date.now() + accessTtlMs)).sign(secretKey);
|
|
1055
|
+
}
|
|
1056
|
+
async function mintRefresh(customer, jti) {
|
|
1057
|
+
return new SignJWT({
|
|
1058
|
+
sub: customer.id,
|
|
1059
|
+
email: customer.email,
|
|
1060
|
+
roles: ["customer"],
|
|
1061
|
+
type: "refresh",
|
|
1062
|
+
jti
|
|
1063
|
+
}).setProtectedHeader({ alg: "HS256" }).setIssuedAt().setJti(jti).setIssuer(issuer).setExpirationTime(new Date(Date.now() + refreshTtlMs)).sign(secretKey);
|
|
1064
|
+
}
|
|
1065
|
+
async function issueTokens(customer) {
|
|
1066
|
+
const jti = uuidv73();
|
|
1067
|
+
const refreshToken = await mintRefresh(customer, jti);
|
|
1068
|
+
await store.transaction(
|
|
1069
|
+
(tx) => repos.refreshToken.insert(tx, {
|
|
1070
|
+
id: jti,
|
|
1071
|
+
customerId: customer.id,
|
|
1072
|
+
tokenHash: hashRefresh(refreshToken),
|
|
1073
|
+
expiresAt: new Date(Date.now() + refreshTtlMs),
|
|
1074
|
+
createdAt: /* @__PURE__ */ new Date()
|
|
1075
|
+
})
|
|
1076
|
+
);
|
|
1077
|
+
const accessToken = await mintAccess(customer);
|
|
1078
|
+
return {
|
|
1079
|
+
accessToken,
|
|
1080
|
+
refreshToken,
|
|
1081
|
+
expiresIn: Math.floor(accessTtlMs / 1e3)
|
|
1082
|
+
};
|
|
1083
|
+
}
|
|
1084
|
+
return {
|
|
1085
|
+
async register(input) {
|
|
1086
|
+
audit.note("customer.register");
|
|
1087
|
+
if (!input.email.includes("@")) throw new ValidationError2("invalid email");
|
|
1088
|
+
if (input.password.length < 8) throw new ValidationError2("password must be \u2265 8 characters");
|
|
1089
|
+
const email = input.email.toLowerCase();
|
|
1090
|
+
const existing = await store.read((tx) => repos.customer.findByEmail(tx, email));
|
|
1091
|
+
if (existing) {
|
|
1092
|
+
throw new AuthError("invalid_credentials", "An account with this email already exists");
|
|
1093
|
+
}
|
|
1094
|
+
const id2 = uuidv73();
|
|
1095
|
+
const passwordHash = await bcryptHash(input.password, 10);
|
|
1096
|
+
const now = /* @__PURE__ */ new Date();
|
|
1097
|
+
const customer = await store.transaction(async (tx) => {
|
|
1098
|
+
audit.note("customer.register", [{ type: "customer", id: id2 }]);
|
|
1099
|
+
await repos.customer.insert(tx, {
|
|
1100
|
+
id: id2,
|
|
1101
|
+
email,
|
|
1102
|
+
passwordHash,
|
|
1103
|
+
...input.firstName !== void 0 && { firstName: input.firstName },
|
|
1104
|
+
...input.lastName !== void 0 && { lastName: input.lastName },
|
|
1105
|
+
...input.phone !== void 0 && { phone: input.phone },
|
|
1106
|
+
createdAt: now,
|
|
1107
|
+
updatedAt: now
|
|
1108
|
+
});
|
|
1109
|
+
const inserted = await repos.customer.findById(tx, id2);
|
|
1110
|
+
if (!inserted) throw new Error("customer disappeared after insert");
|
|
1111
|
+
await publisher.publish(EVT_CUSTOMER_CREATED, {
|
|
1112
|
+
customerId: id2,
|
|
1113
|
+
email,
|
|
1114
|
+
customer: toCustomerSnapshot(inserted)
|
|
1115
|
+
});
|
|
1116
|
+
return inserted;
|
|
1117
|
+
});
|
|
1118
|
+
const tokens = await issueTokens(customer);
|
|
1119
|
+
logger.info({ customerId: id2 }, "customer registered");
|
|
1120
|
+
return { customer: stripPassword(customer), tokens };
|
|
1121
|
+
},
|
|
1122
|
+
async login(email, password) {
|
|
1123
|
+
const customer = await store.read((tx) => repos.customer.findByEmail(tx, email.toLowerCase()));
|
|
1124
|
+
if (!customer) throw new AuthError("invalid_credentials", "Invalid email or password");
|
|
1125
|
+
const ok2 = await bcryptCompare(password, customer.passwordHash);
|
|
1126
|
+
if (!ok2) throw new AuthError("invalid_credentials", "Invalid email or password");
|
|
1127
|
+
const tokens = await issueTokens(customer);
|
|
1128
|
+
logger.info({ customerId: customer.id }, "customer login");
|
|
1129
|
+
return { customer: stripPassword(customer), tokens };
|
|
1130
|
+
},
|
|
1131
|
+
async refresh(refreshToken) {
|
|
1132
|
+
let verified;
|
|
1133
|
+
try {
|
|
1134
|
+
verified = await jwtVerify(refreshToken, secretKey, { issuer });
|
|
1135
|
+
} catch {
|
|
1136
|
+
throw new AuthError("token_invalid", "refresh token invalid");
|
|
1137
|
+
}
|
|
1138
|
+
const payload = verified.payload;
|
|
1139
|
+
if (payload.type !== "refresh" || !payload.jti || !payload.sub) {
|
|
1140
|
+
throw new AuthError("token_invalid", "not a refresh token");
|
|
1141
|
+
}
|
|
1142
|
+
const jti = payload.jti;
|
|
1143
|
+
const customerId = payload.sub;
|
|
1144
|
+
const record2 = await store.read((tx) => repos.refreshToken.findById(tx, jti));
|
|
1145
|
+
if (!record2) throw new AuthError("token_invalid", "refresh token unknown");
|
|
1146
|
+
if (record2.revokedAt) throw new AuthError("token_invalid", "refresh token revoked");
|
|
1147
|
+
if (record2.tokenHash !== hashRefresh(refreshToken)) {
|
|
1148
|
+
await store.transaction((tx) => repos.refreshToken.revokeAllForCustomer(tx, customerId));
|
|
1149
|
+
throw new AuthError("token_invalid", "refresh token mismatch; revoking chain");
|
|
1150
|
+
}
|
|
1151
|
+
const customer = await store.read((tx) => repos.customer.findById(tx, customerId));
|
|
1152
|
+
if (!customer) throw new AuthError("token_invalid", "customer missing");
|
|
1153
|
+
const nextJti = uuidv73();
|
|
1154
|
+
const nextRefresh = await mintRefresh(customer, nextJti);
|
|
1155
|
+
await store.transaction(
|
|
1156
|
+
(tx) => repos.refreshToken.rotate(tx, jti, {
|
|
1157
|
+
id: nextJti,
|
|
1158
|
+
customerId: customer.id,
|
|
1159
|
+
tokenHash: hashRefresh(nextRefresh),
|
|
1160
|
+
expiresAt: new Date(Date.now() + refreshTtlMs),
|
|
1161
|
+
createdAt: /* @__PURE__ */ new Date()
|
|
1162
|
+
})
|
|
1163
|
+
);
|
|
1164
|
+
const accessToken = await mintAccess(customer);
|
|
1165
|
+
return {
|
|
1166
|
+
accessToken,
|
|
1167
|
+
refreshToken: nextRefresh,
|
|
1168
|
+
expiresIn: Math.floor(accessTtlMs / 1e3)
|
|
1169
|
+
};
|
|
1170
|
+
},
|
|
1171
|
+
async logout(refreshToken) {
|
|
1172
|
+
try {
|
|
1173
|
+
const verified = await jwtVerify(refreshToken, secretKey, { issuer });
|
|
1174
|
+
const payload = verified.payload;
|
|
1175
|
+
const { jti } = payload;
|
|
1176
|
+
if (jti) await store.transaction((tx) => repos.refreshToken.revoke(tx, jti));
|
|
1177
|
+
} catch {
|
|
1178
|
+
}
|
|
1179
|
+
},
|
|
1180
|
+
async verifyAccessToken(token) {
|
|
1181
|
+
try {
|
|
1182
|
+
const verified = await jwtVerify(token, secretKey, { issuer });
|
|
1183
|
+
const payload = verified.payload;
|
|
1184
|
+
if (payload.type !== "access") throw new AuthError("token_invalid", "not an access token");
|
|
1185
|
+
return payload;
|
|
1186
|
+
} catch (err) {
|
|
1187
|
+
if (err instanceof AuthError) throw err;
|
|
1188
|
+
throw new AuthError("token_invalid", "access token invalid", { cause: err });
|
|
1189
|
+
}
|
|
1190
|
+
},
|
|
1191
|
+
async importCustomer(input) {
|
|
1192
|
+
if (!input.email.includes("@")) throw new ValidationError2("invalid email");
|
|
1193
|
+
const email = input.email.toLowerCase();
|
|
1194
|
+
const customer = await store.transaction(async (tx) => {
|
|
1195
|
+
const existing = await repos.customer.findByEmail(tx, email);
|
|
1196
|
+
if (existing) return existing;
|
|
1197
|
+
const id2 = uuidv73();
|
|
1198
|
+
audit.note("customer.import", [{ type: "customer", id: id2 }]);
|
|
1199
|
+
const now = /* @__PURE__ */ new Date();
|
|
1200
|
+
await repos.customer.insert(tx, {
|
|
1201
|
+
id: id2,
|
|
1202
|
+
email,
|
|
1203
|
+
passwordHash: "IMPORTED_NO_PASSWORD",
|
|
1204
|
+
requiresPasswordReset: true,
|
|
1205
|
+
...input.firstName !== void 0 && { firstName: input.firstName },
|
|
1206
|
+
...input.lastName !== void 0 && { lastName: input.lastName },
|
|
1207
|
+
...input.phone !== void 0 && { phone: input.phone },
|
|
1208
|
+
...input.addresses !== void 0 && { addresses: input.addresses },
|
|
1209
|
+
...input.metadata !== void 0 && { metadata: input.metadata },
|
|
1210
|
+
roles: ["customer"],
|
|
1211
|
+
createdAt: now,
|
|
1212
|
+
updatedAt: now
|
|
1213
|
+
});
|
|
1214
|
+
const inserted = await repos.customer.findById(tx, id2);
|
|
1215
|
+
if (!inserted) throw new Error("customer disappeared after insert");
|
|
1216
|
+
await publisher.publish(EVT_CUSTOMER_CREATED, {
|
|
1217
|
+
customerId: id2,
|
|
1218
|
+
email,
|
|
1219
|
+
customer: toCustomerSnapshot(inserted)
|
|
1220
|
+
});
|
|
1221
|
+
logger.info({ customerId: id2 }, "customer imported");
|
|
1222
|
+
return inserted;
|
|
1223
|
+
});
|
|
1224
|
+
return stripPassword(customer);
|
|
1225
|
+
}
|
|
1226
|
+
};
|
|
1227
|
+
}
|
|
1228
|
+
|
|
1229
|
+
// src/routes/recently-viewed.ts
|
|
1230
|
+
import { v7 as uuidv74 } from "uuid";
|
|
1231
|
+
import {
|
|
1232
|
+
AuthError as AuthError2
|
|
1233
|
+
} from "@nymbalhq/types";
|
|
1234
|
+
|
|
1235
|
+
// src/read-models/recently-viewed.ts
|
|
1236
|
+
import {
|
|
1237
|
+
EVT_CUSTOMER_DELETED,
|
|
1238
|
+
EVT_PRODUCT_VIEWED,
|
|
1239
|
+
EVT_VISITOR_MERGED
|
|
955
1240
|
} from "@nymbalhq/types";
|
|
1241
|
+
|
|
1242
|
+
// src/handlers/derived.ts
|
|
1243
|
+
async function subscribeDerived(eventBus, handlers) {
|
|
1244
|
+
for (const h of handlers) {
|
|
1245
|
+
const pattern = h.types.length === 1 ? h.types[0] : [...h.types];
|
|
1246
|
+
await eventBus.subscribe(pattern, h.handle, { name: h.name, derived: true });
|
|
1247
|
+
}
|
|
1248
|
+
}
|
|
1249
|
+
|
|
1250
|
+
// src/handlers/projections/recently-viewed-projection.ts
|
|
1251
|
+
function recentlyViewedProjection(deps) {
|
|
1252
|
+
const { documentStore, logger } = deps;
|
|
1253
|
+
const docs = {
|
|
1254
|
+
get: (key) => documentStore.get(RECENTLY_VIEWED, key),
|
|
1255
|
+
put: (key, doc) => documentStore.put(RECENTLY_VIEWED, key, doc),
|
|
1256
|
+
delete: (key) => documentStore.delete(RECENTLY_VIEWED, key)
|
|
1257
|
+
};
|
|
1258
|
+
const handle = async (event) => {
|
|
1259
|
+
await foldEvent(docs, event);
|
|
1260
|
+
logger.debug({ type: event.type }, "recently viewed projected");
|
|
1261
|
+
};
|
|
1262
|
+
return [{ name: "recently-viewed-projection", types: RECENTLY_VIEWED_TYPES, handle }];
|
|
1263
|
+
}
|
|
1264
|
+
async function registerRecentlyViewedProjection(deps) {
|
|
1265
|
+
await subscribeDerived(deps.eventBus, recentlyViewedProjection(deps));
|
|
1266
|
+
}
|
|
1267
|
+
|
|
1268
|
+
// src/order-history-notes.ts
|
|
1269
|
+
var REFUND_NOTE_PREFIX = "refund of ";
|
|
1270
|
+
|
|
1271
|
+
// src/read-models/order-timeline.ts
|
|
1272
|
+
var MOVES = {
|
|
1273
|
+
shipped: "shipped",
|
|
1274
|
+
delivered: "delivered",
|
|
1275
|
+
cancelled: "cancelled",
|
|
1276
|
+
refunded: "refunded",
|
|
1277
|
+
partially_refunded: "partially_refunded"
|
|
1278
|
+
};
|
|
1279
|
+
function kindOf(row) {
|
|
1280
|
+
const { fromStatus: from, toStatus: to } = row;
|
|
1281
|
+
if (from === null) return to === "pending" ? "placed" : null;
|
|
1282
|
+
if (from === to) {
|
|
1283
|
+
return to === "partially_refunded" && row.note.startsWith(REFUND_NOTE_PREFIX) ? "partially_refunded" : null;
|
|
1284
|
+
}
|
|
1285
|
+
if (from === "pending" && to === "confirmed") return "paid";
|
|
1286
|
+
return MOVES[to] ?? null;
|
|
1287
|
+
}
|
|
1288
|
+
function orderTimeline(history) {
|
|
1289
|
+
const entries = [];
|
|
1290
|
+
for (const row of history) {
|
|
1291
|
+
const kind = kindOf(row);
|
|
1292
|
+
if (kind !== null) entries.push({ kind, at: row.timestamp });
|
|
1293
|
+
}
|
|
1294
|
+
return entries;
|
|
1295
|
+
}
|
|
1296
|
+
|
|
1297
|
+
// src/read-models/builders.ts
|
|
1298
|
+
var CATEGORIES = "categories";
|
|
1299
|
+
var PRODUCTS = "products";
|
|
1300
|
+
var PRODUCTS_BY_CATEGORY = "products-by-category";
|
|
1301
|
+
var ORDERS = "orders";
|
|
1302
|
+
var ORDERS_BY_CUSTOMER = "orders-by-customer";
|
|
1303
|
+
var CUSTOMER_PROFILES = "customer-profiles";
|
|
1304
|
+
var RECENTLY_VIEWED = "recently-viewed";
|
|
1305
|
+
function buildCategoryDoc(category, storeId) {
|
|
1306
|
+
return {
|
|
1307
|
+
id: category.id,
|
|
1308
|
+
storeId,
|
|
1309
|
+
parentId: category.parentId,
|
|
1310
|
+
slug: category.slug,
|
|
1311
|
+
name: category.name,
|
|
1312
|
+
description: category.description,
|
|
1313
|
+
position: category.position,
|
|
1314
|
+
createdAt: category.createdAt
|
|
1315
|
+
};
|
|
1316
|
+
}
|
|
1317
|
+
var isVariantOption = (o) => typeof o === "object" && o !== null && typeof o.name === "string" && typeof o.value === "string";
|
|
1318
|
+
function variantOptions(raw, sku, logger) {
|
|
1319
|
+
let value = raw;
|
|
1320
|
+
if (typeof raw === "string") {
|
|
1321
|
+
try {
|
|
1322
|
+
value = JSON.parse(raw);
|
|
1323
|
+
} catch (err) {
|
|
1324
|
+
logger?.warn({ sku, err }, "variant options are not JSON; projected as none");
|
|
1325
|
+
return [];
|
|
1326
|
+
}
|
|
1327
|
+
}
|
|
1328
|
+
if (!Array.isArray(value)) return [];
|
|
1329
|
+
return value.filter(isVariantOption).map((o) => ({ name: o.name, value: o.value }));
|
|
1330
|
+
}
|
|
1331
|
+
function buildProductDoc(p, categories, ctx) {
|
|
1332
|
+
const prices = p.variants.map((v) => v.priceMinor);
|
|
1333
|
+
return {
|
|
1334
|
+
id: p.id,
|
|
1335
|
+
storeId: ctx.storeId,
|
|
1336
|
+
slug: p.slug,
|
|
1337
|
+
name: p.name,
|
|
1338
|
+
description: p.description,
|
|
1339
|
+
shortDescription: p.shortDescription,
|
|
1340
|
+
status: p.status,
|
|
1341
|
+
type: p.type,
|
|
1342
|
+
media: p.media,
|
|
1343
|
+
variantCount: p.variants.length,
|
|
1344
|
+
inStock: p.variants.some((v) => v.stock > 0),
|
|
1345
|
+
priceRange: prices.length ? { minMinor: Math.min(...prices), maxMinor: Math.max(...prices) } : null,
|
|
1346
|
+
currency: ctx.currency,
|
|
1347
|
+
priceMinor: prices[0] ?? null,
|
|
1348
|
+
variants: p.variants.map((v) => ({
|
|
1349
|
+
id: v.id,
|
|
1350
|
+
sku: v.sku,
|
|
1351
|
+
name: v.name,
|
|
1352
|
+
priceMinor: v.priceMinor,
|
|
1353
|
+
stock: v.stock,
|
|
1354
|
+
options: variantOptions(v.options, v.sku, ctx.logger)
|
|
1355
|
+
})),
|
|
1356
|
+
categoryIds: p.categoryIds,
|
|
1357
|
+
categories: p.categoryIds.flatMap((id2) => {
|
|
1358
|
+
const c = categories.get(id2);
|
|
1359
|
+
return c ? [{ id: c.id, name: c.name, slug: c.slug }] : [];
|
|
1360
|
+
}),
|
|
1361
|
+
createdAt: p.createdAt,
|
|
1362
|
+
updatedAt: p.updatedAt
|
|
1363
|
+
};
|
|
1364
|
+
}
|
|
1365
|
+
var productByCategoryKey = (categorySlug, productSlug) => `category:${categorySlug}#product:${productSlug}`;
|
|
1366
|
+
function productWrites(doc) {
|
|
1367
|
+
return [
|
|
1368
|
+
{ collection: PRODUCTS, key: doc.slug, doc },
|
|
1369
|
+
...doc.categories.map((c) => ({
|
|
1370
|
+
collection: PRODUCTS_BY_CATEGORY,
|
|
1371
|
+
key: productByCategoryKey(c.slug, doc.slug),
|
|
1372
|
+
doc: { ...doc, partitionKey: `category:${c.slug}`, sortKey: `product:${doc.slug}` }
|
|
1373
|
+
}))
|
|
1374
|
+
];
|
|
1375
|
+
}
|
|
1376
|
+
function customerSortKey(o) {
|
|
1377
|
+
return `order:${String(Number.MAX_SAFE_INTEGER - new Date(String(o.createdAt)).getTime()).padStart(16, "0")}:${o.orderNumber}`;
|
|
1378
|
+
}
|
|
1379
|
+
function buildOrderDoc(order, history) {
|
|
1380
|
+
const rows = history.map((h) => ({
|
|
1381
|
+
fromStatus: h.fromStatus,
|
|
1382
|
+
toStatus: h.toStatus,
|
|
1383
|
+
actor: h.actor,
|
|
1384
|
+
note: h.note,
|
|
1385
|
+
timestamp: String(h.timestamp)
|
|
1386
|
+
}));
|
|
1387
|
+
return { ...order, history: rows, timeline: orderTimeline(rows) };
|
|
1388
|
+
}
|
|
1389
|
+
function orderWrites(doc) {
|
|
1390
|
+
const writes = [{ collection: ORDERS, key: doc.orderNumber, doc }];
|
|
1391
|
+
if (doc.customerId) {
|
|
1392
|
+
const sortKey = customerSortKey(doc);
|
|
1393
|
+
writes.push({
|
|
1394
|
+
collection: ORDERS_BY_CUSTOMER,
|
|
1395
|
+
key: `customer:${doc.customerId}#${sortKey}`,
|
|
1396
|
+
doc: { ...doc, partitionKey: `customer:${doc.customerId}`, sortKey }
|
|
1397
|
+
});
|
|
1398
|
+
}
|
|
1399
|
+
return writes;
|
|
1400
|
+
}
|
|
1401
|
+
function buildCustomerProfile(c) {
|
|
1402
|
+
const { orderCount, totalSpentMinor } = c;
|
|
1403
|
+
return {
|
|
1404
|
+
customerId: c.id,
|
|
1405
|
+
orderCount,
|
|
1406
|
+
totalSpentMinor,
|
|
1407
|
+
segment: totalSpentMinor > 1e5 ? "vip" : orderCount > 3 ? "returning" : orderCount > 0 ? "active" : "new",
|
|
1408
|
+
createdAt: String(c.createdAt)
|
|
1409
|
+
};
|
|
1410
|
+
}
|
|
1411
|
+
var partitioned = (doc) => {
|
|
1412
|
+
const { partitionKey, sortKey } = doc;
|
|
1413
|
+
return `${String(partitionKey)}#${String(sortKey)}`;
|
|
1414
|
+
};
|
|
1415
|
+
var KEY_OF = {
|
|
1416
|
+
[CATEGORIES]: (doc) => String(doc.slug),
|
|
1417
|
+
[PRODUCTS]: (doc) => String(doc.slug),
|
|
1418
|
+
[PRODUCTS_BY_CATEGORY]: partitioned,
|
|
1419
|
+
[ORDERS]: (doc) => String(doc.orderNumber),
|
|
1420
|
+
[ORDERS_BY_CUSTOMER]: partitioned,
|
|
1421
|
+
[CUSTOMER_PROFILES]: (doc) => String(doc.customerId),
|
|
1422
|
+
[RECENTLY_VIEWED]: (doc) => String(doc.viewer)
|
|
1423
|
+
};
|
|
1424
|
+
function buildSearchDoc(p) {
|
|
1425
|
+
return {
|
|
1426
|
+
id: p.id,
|
|
1427
|
+
type: "product",
|
|
1428
|
+
fields: {
|
|
1429
|
+
slug: p.slug,
|
|
1430
|
+
name: p.name,
|
|
1431
|
+
description: p.description,
|
|
1432
|
+
status: p.status,
|
|
1433
|
+
categoryIds: p.categoryIds,
|
|
1434
|
+
variants: p.variants.map((v) => ({ sku: v.sku, name: v.name, priceMinor: v.priceMinor }))
|
|
1435
|
+
}
|
|
1436
|
+
};
|
|
1437
|
+
}
|
|
1438
|
+
|
|
1439
|
+
// src/read-models/recently-viewed.ts
|
|
1440
|
+
var RECENT_VIEWS_KEPT = 12;
|
|
1441
|
+
var RECENT_VIEWS_WINDOW_DAYS = 30;
|
|
1442
|
+
var RECENTLY_VIEWED_TYPES = [
|
|
1443
|
+
EVT_PRODUCT_VIEWED,
|
|
1444
|
+
EVT_VISITOR_MERGED,
|
|
1445
|
+
EVT_CUSTOMER_DELETED
|
|
1446
|
+
];
|
|
1447
|
+
function viewerKey(v) {
|
|
1448
|
+
return `${v.kind}:${v.id}`;
|
|
1449
|
+
}
|
|
1450
|
+
var newestFirst = (a, b) => a.viewedAt === b.viewedAt ? a.productId < b.productId ? -1 : a.productId > b.productId ? 1 : 0 : a.viewedAt < b.viewedAt ? 1 : -1;
|
|
1451
|
+
function ranked(items) {
|
|
1452
|
+
const newest = /* @__PURE__ */ new Map();
|
|
1453
|
+
for (const { productId, viewedAt } of items) {
|
|
1454
|
+
const held = newest.get(productId);
|
|
1455
|
+
if (held === void 0 || viewedAt > held) newest.set(productId, viewedAt);
|
|
1456
|
+
}
|
|
1457
|
+
return [...newest].map(([productId, viewedAt]) => ({ productId, viewedAt })).sort(newestFirst).slice(0, RECENT_VIEWS_KEPT);
|
|
1458
|
+
}
|
|
1459
|
+
function withView(doc, viewer, productId, viewedAt) {
|
|
1460
|
+
return { viewer, items: ranked([...doc?.items ?? [], { productId, viewedAt }]) };
|
|
1461
|
+
}
|
|
1462
|
+
function merged(visitor, customer, customerKey) {
|
|
1463
|
+
if (visitor === null) return customer;
|
|
1464
|
+
if (customer === null) return { viewer: customerKey, items: visitor.items };
|
|
1465
|
+
return { viewer: customerKey, items: ranked([...customer.items, ...visitor.items]) };
|
|
1466
|
+
}
|
|
1467
|
+
async function foldEvent(docs, event) {
|
|
1468
|
+
if (event.type === EVT_PRODUCT_VIEWED) {
|
|
1469
|
+
const { productId, viewer } = event.payload;
|
|
1470
|
+
const key = viewerKey(viewer);
|
|
1471
|
+
await docs.put(key, withView(await docs.get(key), key, productId, event.timestamp));
|
|
1472
|
+
} else if (event.type === EVT_VISITOR_MERGED) {
|
|
1473
|
+
const { visitorId, customerId } = event.payload;
|
|
1474
|
+
const visitorKey = viewerKey({ kind: "visitor", id: visitorId });
|
|
1475
|
+
const customerKey = viewerKey({ kind: "customer", id: customerId });
|
|
1476
|
+
const next = merged(await docs.get(visitorKey), await docs.get(customerKey), customerKey);
|
|
1477
|
+
if (next !== null) await docs.put(customerKey, next);
|
|
1478
|
+
await docs.delete(visitorKey);
|
|
1479
|
+
} else if (event.type === EVT_CUSTOMER_DELETED) {
|
|
1480
|
+
const { customerId } = event.payload;
|
|
1481
|
+
await docs.delete(viewerKey({ kind: "customer", id: customerId }));
|
|
1482
|
+
}
|
|
1483
|
+
}
|
|
1484
|
+
async function readRecentlyViewed(deps, viewer) {
|
|
1485
|
+
if (viewer === null) return [];
|
|
1486
|
+
const doc = await deps.documentStore.get(RECENTLY_VIEWED, viewer);
|
|
1487
|
+
if (doc === null) return [];
|
|
1488
|
+
const days = Math.min(RECENT_VIEWS_WINDOW_DAYS, deps.retentionDays);
|
|
1489
|
+
const since = new Date(deps.now().getTime() - days * 864e5).toISOString();
|
|
1490
|
+
const recent = doc.items.filter((i) => i.viewedAt >= since);
|
|
1491
|
+
const { product } = deps.repos;
|
|
1492
|
+
const slugs = await product.store.read(async (tx) => {
|
|
1493
|
+
const out = [];
|
|
1494
|
+
for (const { productId } of recent) {
|
|
1495
|
+
const row = await product.findById(tx, productId);
|
|
1496
|
+
if (row?.status === "active") out.push(row.slug);
|
|
1497
|
+
}
|
|
1498
|
+
return out;
|
|
1499
|
+
});
|
|
1500
|
+
const docs = await deps.documentStore.batchGet(PRODUCTS, slugs);
|
|
1501
|
+
return slugs.flatMap((slug) => {
|
|
1502
|
+
const found = docs.get(slug);
|
|
1503
|
+
return found === void 0 ? [] : [found];
|
|
1504
|
+
});
|
|
1505
|
+
}
|
|
1506
|
+
var recentlyViewed = {
|
|
1507
|
+
name: "recently-viewed",
|
|
1508
|
+
target: "documents",
|
|
1509
|
+
collections: [RECENTLY_VIEWED],
|
|
1510
|
+
async *rebuild(ctx) {
|
|
1511
|
+
const held = /* @__PURE__ */ new Map();
|
|
1512
|
+
const docs = {
|
|
1513
|
+
get: async (key) => held.get(key) ?? null,
|
|
1514
|
+
put: async (key, doc) => {
|
|
1515
|
+
held.set(key, doc);
|
|
1516
|
+
},
|
|
1517
|
+
delete: async (key) => {
|
|
1518
|
+
held.delete(key);
|
|
1519
|
+
}
|
|
1520
|
+
};
|
|
1521
|
+
for await (const page of ctx.events(RECENTLY_VIEWED_TYPES)) {
|
|
1522
|
+
for (const { event } of page) await foldEvent(docs, event);
|
|
1523
|
+
}
|
|
1524
|
+
for (const [key, doc] of held) yield { collection: RECENTLY_VIEWED, key, doc };
|
|
1525
|
+
},
|
|
1526
|
+
handlers({ documentStore, logger }) {
|
|
1527
|
+
return recentlyViewedProjection({ documentStore, logger });
|
|
1528
|
+
}
|
|
1529
|
+
};
|
|
1530
|
+
|
|
1531
|
+
// src/routes/recently-viewed.ts
|
|
1532
|
+
var VISITOR_COOKIE = "nymbal.visitor";
|
|
1533
|
+
var UUID = /^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i;
|
|
1534
|
+
var BOT = /bot|crawl|spider|slurp/i;
|
|
1535
|
+
var NOT_STORED = { "Cache-Control": "private, no-store" };
|
|
1536
|
+
function visitorCookie(id2) {
|
|
1537
|
+
return {
|
|
1538
|
+
name: VISITOR_COOKIE,
|
|
1539
|
+
value: id2,
|
|
1540
|
+
path: "/",
|
|
1541
|
+
httpOnly: true,
|
|
1542
|
+
sameSite: "lax",
|
|
1543
|
+
secure: process.env.NODE_ENV === "production",
|
|
1544
|
+
maxAge: RECENT_VIEWS_WINDOW_DAYS * 86400
|
|
1545
|
+
};
|
|
1546
|
+
}
|
|
1547
|
+
function expiredVisitorCookie() {
|
|
1548
|
+
return { name: VISITOR_COOKIE, value: "", path: "/", maxAge: 0, httpOnly: true };
|
|
1549
|
+
}
|
|
1550
|
+
function visitorOf(ctx) {
|
|
1551
|
+
const id2 = ctx.cookies[VISITOR_COOKIE];
|
|
1552
|
+
return id2 !== void 0 && UUID.test(id2) ? id2 : void 0;
|
|
1553
|
+
}
|
|
1554
|
+
function lapsedBearer(ctx) {
|
|
1555
|
+
if (ctx.headers.authorization === void 0 || ctx.auth?.userId !== void 0) return void 0;
|
|
1556
|
+
return renderError(new AuthError2("token_invalid", "the access token is not valid"));
|
|
1557
|
+
}
|
|
1558
|
+
function foldViewsOnSignIn(recentlyViewed2) {
|
|
1559
|
+
return async (ctx, customerId) => {
|
|
1560
|
+
const visitorId = visitorOf(ctx);
|
|
1561
|
+
if (visitorId === void 0) return [];
|
|
1562
|
+
await recentlyViewed2.fold(visitorId, customerId);
|
|
1563
|
+
return [expiredVisitorCookie()];
|
|
1564
|
+
};
|
|
1565
|
+
}
|
|
1566
|
+
function registerRecentlyViewedRoutes(adapter, deps) {
|
|
1567
|
+
const { recentlyViewed: recentlyViewed2, documentStore, productRepo, retentionDays } = deps;
|
|
1568
|
+
const now = deps.now ?? (() => /* @__PURE__ */ new Date());
|
|
1569
|
+
adapter.registerRoute("POST", "/api/recently-viewed", async (ctx) => {
|
|
1570
|
+
try {
|
|
1571
|
+
const refused2 = lapsedBearer(ctx);
|
|
1572
|
+
if (refused2 !== void 0) return refused2;
|
|
1573
|
+
const agent = ctx.headers["user-agent"];
|
|
1574
|
+
if (typeof agent === "string" && BOT.test(agent)) return { status: 204 };
|
|
1575
|
+
const { productId } = ctx.body;
|
|
1576
|
+
const customerId = ctx.auth?.userId;
|
|
1577
|
+
if (customerId !== void 0) {
|
|
1578
|
+
await recentlyViewed2.record({ kind: "customer", id: customerId }, productId);
|
|
1579
|
+
return { status: 204 };
|
|
1580
|
+
}
|
|
1581
|
+
const visitorId = visitorOf(ctx) ?? uuidv74();
|
|
1582
|
+
const recorded = await recentlyViewed2.record({ kind: "visitor", id: visitorId }, productId);
|
|
1583
|
+
return recorded ? { status: 204, cookies: [visitorCookie(visitorId)] } : { status: 204 };
|
|
1584
|
+
} catch (err) {
|
|
1585
|
+
return renderError(err);
|
|
1586
|
+
}
|
|
1587
|
+
});
|
|
1588
|
+
adapter.registerRoute("GET", "/api/recently-viewed", async (ctx) => {
|
|
1589
|
+
try {
|
|
1590
|
+
const refused2 = lapsedBearer(ctx);
|
|
1591
|
+
if (refused2 !== void 0) return refused2;
|
|
1592
|
+
const visitorId = visitorOf(ctx);
|
|
1593
|
+
const customerId = ctx.auth?.userId;
|
|
1594
|
+
const viewer = customerId !== void 0 ? viewerKey({ kind: "customer", id: customerId }) : visitorId !== void 0 ? viewerKey({ kind: "visitor", id: visitorId }) : null;
|
|
1595
|
+
const items = await readRecentlyViewed(
|
|
1596
|
+
{ documentStore, repos: { product: productRepo }, retentionDays, now },
|
|
1597
|
+
viewer
|
|
1598
|
+
);
|
|
1599
|
+
return { ...ok({ items }), headers: NOT_STORED };
|
|
1600
|
+
} catch (err) {
|
|
1601
|
+
return renderError(err);
|
|
1602
|
+
}
|
|
1603
|
+
});
|
|
1604
|
+
}
|
|
1605
|
+
|
|
1606
|
+
// src/routes/auth.ts
|
|
956
1607
|
var REFRESH_COOKIE = "nymbal.refresh";
|
|
957
1608
|
function refreshCookies(token, maxAgeSeconds) {
|
|
958
1609
|
return [
|
|
@@ -968,9 +1619,24 @@ function refreshCookies(token, maxAgeSeconds) {
|
|
|
968
1619
|
];
|
|
969
1620
|
}
|
|
970
1621
|
function expiredCookies() {
|
|
971
|
-
return [
|
|
1622
|
+
return [
|
|
1623
|
+
{ name: REFRESH_COOKIE, value: "", path: "/", maxAge: 0, httpOnly: true },
|
|
1624
|
+
expiredVisitorCookie()
|
|
1625
|
+
];
|
|
972
1626
|
}
|
|
973
|
-
function
|
|
1627
|
+
async function runAfterSignIn(hooks2, ctx, customerId) {
|
|
1628
|
+
const cookies = [];
|
|
1629
|
+
for (const hook of hooks2) {
|
|
1630
|
+
try {
|
|
1631
|
+
cookies.push(...await hook(ctx, customerId));
|
|
1632
|
+
} catch (err) {
|
|
1633
|
+
ctx.logger.warn({ err, customerId }, "an after-sign-in hook failed; the sign-in stands");
|
|
1634
|
+
}
|
|
1635
|
+
}
|
|
1636
|
+
return cookies;
|
|
1637
|
+
}
|
|
1638
|
+
function registerAuthRoutes(adapter, auth, refreshTtl, afterSignIn = []) {
|
|
1639
|
+
const refreshMaxAge = Math.floor(parseDurationToMs(refreshTtl) / 1e3);
|
|
974
1640
|
adapter.registerRoute("POST", "/api/auth/register", async (ctx) => {
|
|
975
1641
|
try {
|
|
976
1642
|
const body = ctx.body;
|
|
@@ -986,11 +1652,18 @@ function registerAuthRoutes(adapter, auth) {
|
|
|
986
1652
|
};
|
|
987
1653
|
const result = await auth.register(registerInput);
|
|
988
1654
|
const envelope = ok(
|
|
989
|
-
{
|
|
1655
|
+
{
|
|
1656
|
+
customer: result.customer,
|
|
1657
|
+
accessToken: result.tokens.accessToken,
|
|
1658
|
+
expiresIn: result.tokens.expiresIn
|
|
1659
|
+
},
|
|
990
1660
|
void 0,
|
|
991
1661
|
201
|
|
992
1662
|
);
|
|
993
|
-
envelope.cookies =
|
|
1663
|
+
envelope.cookies = [
|
|
1664
|
+
...refreshCookies(result.tokens.refreshToken, refreshMaxAge),
|
|
1665
|
+
...await runAfterSignIn(afterSignIn, ctx, result.customer.id)
|
|
1666
|
+
];
|
|
994
1667
|
return envelope;
|
|
995
1668
|
} catch (err) {
|
|
996
1669
|
return renderError(err);
|
|
@@ -1008,7 +1681,10 @@ function registerAuthRoutes(adapter, auth) {
|
|
|
1008
1681
|
accessToken: result.tokens.accessToken,
|
|
1009
1682
|
expiresIn: result.tokens.expiresIn
|
|
1010
1683
|
});
|
|
1011
|
-
envelope.cookies =
|
|
1684
|
+
envelope.cookies = [
|
|
1685
|
+
...refreshCookies(result.tokens.refreshToken, refreshMaxAge),
|
|
1686
|
+
...await runAfterSignIn(afterSignIn, ctx, result.customer.id)
|
|
1687
|
+
];
|
|
1012
1688
|
return envelope;
|
|
1013
1689
|
} catch (err) {
|
|
1014
1690
|
return renderError(err);
|
|
@@ -1018,10 +1694,10 @@ function registerAuthRoutes(adapter, auth) {
|
|
|
1018
1694
|
try {
|
|
1019
1695
|
const body = ctx.body;
|
|
1020
1696
|
const refreshToken = body?.refreshToken ?? ctx.cookies[REFRESH_COOKIE];
|
|
1021
|
-
if (!refreshToken) throw new
|
|
1697
|
+
if (!refreshToken) throw new AuthError3("token_invalid", "refresh token missing");
|
|
1022
1698
|
const tokens = await auth.refresh(refreshToken);
|
|
1023
1699
|
const envelope = ok({ accessToken: tokens.accessToken, expiresIn: tokens.expiresIn });
|
|
1024
|
-
envelope.cookies = refreshCookies(tokens.refreshToken,
|
|
1700
|
+
envelope.cookies = refreshCookies(tokens.refreshToken, refreshMaxAge);
|
|
1025
1701
|
return envelope;
|
|
1026
1702
|
} catch (err) {
|
|
1027
1703
|
return renderError(err);
|
|
@@ -1210,449 +1886,1057 @@ import {
|
|
|
1210
1886
|
DEFAULT_PRODUCT_SORT as DEFAULT_PRODUCT_SORT2,
|
|
1211
1887
|
PRODUCT_SORT_KEYS
|
|
1212
1888
|
} from "@nymbalhq/types";
|
|
1213
|
-
|
|
1214
|
-
|
|
1889
|
+
|
|
1890
|
+
// src/services/product-service.ts
|
|
1891
|
+
import { v7 as uuidv75 } from "uuid";
|
|
1892
|
+
import {
|
|
1893
|
+
EVT_PRODUCT_CREATED,
|
|
1894
|
+
EVT_PRODUCT_UPDATED,
|
|
1895
|
+
EVT_PRODUCT_DELETED,
|
|
1896
|
+
EVT_PRODUCT_PUBLISHED,
|
|
1897
|
+
EVT_PRODUCT_UNPUBLISHED,
|
|
1898
|
+
EVT_PRODUCT_VARIANT_PRICE_CHANGED,
|
|
1899
|
+
HttpError as HttpError2,
|
|
1900
|
+
NotFoundError as NotFoundError3,
|
|
1901
|
+
ValidationError as ValidationError3
|
|
1902
|
+
} from "@nymbalhq/types";
|
|
1903
|
+
async function snapshot(tx, repos, product) {
|
|
1904
|
+
const [variants, categoryIds] = await Promise.all([
|
|
1905
|
+
repos.variant.findByProduct(tx, product.id),
|
|
1906
|
+
repos.productCategory.listCategoriesForProduct(tx, product.id)
|
|
1907
|
+
]);
|
|
1908
|
+
return { ...product, variants, categoryIds };
|
|
1909
|
+
}
|
|
1910
|
+
function createProductService(deps) {
|
|
1911
|
+
const { store, repos, publisher, currency } = deps;
|
|
1912
|
+
async function requireProduct(tx, id2) {
|
|
1913
|
+
const product = await repos.product.findById(tx, id2);
|
|
1914
|
+
if (!product) throw new NotFoundError3("product", id2);
|
|
1915
|
+
return product;
|
|
1916
|
+
}
|
|
1215
1917
|
return {
|
|
1216
|
-
|
|
1217
|
-
|
|
1218
|
-
|
|
1918
|
+
async create(input) {
|
|
1919
|
+
audit.note("product.create");
|
|
1920
|
+
if (!input.slug.trim()) throw new ValidationError3("Product slug is required");
|
|
1921
|
+
if (!input.name.trim()) throw new ValidationError3("Product name is required");
|
|
1922
|
+
const existing = await store.read((tx) => repos.product.findBySlug(tx, input.slug));
|
|
1923
|
+
if (existing) {
|
|
1924
|
+
throw new ValidationError3(`Product slug already exists: ${input.slug}`, {
|
|
1925
|
+
context: { slug: input.slug }
|
|
1926
|
+
});
|
|
1927
|
+
}
|
|
1928
|
+
return store.transaction(async (tx) => {
|
|
1929
|
+
const now = /* @__PURE__ */ new Date();
|
|
1930
|
+
const productId = uuidv75();
|
|
1931
|
+
audit.note("product.create", [{ type: "product", id: productId }]);
|
|
1932
|
+
const insert = {
|
|
1933
|
+
id: productId,
|
|
1934
|
+
slug: input.slug,
|
|
1935
|
+
name: input.name,
|
|
1936
|
+
...input.description !== void 0 && { description: input.description },
|
|
1937
|
+
...input.shortDescription !== void 0 && { shortDescription: input.shortDescription },
|
|
1938
|
+
...input.status !== void 0 && { status: input.status },
|
|
1939
|
+
...input.type !== void 0 && { type: input.type },
|
|
1940
|
+
...input.seoTitle !== void 0 && { seoTitle: input.seoTitle },
|
|
1941
|
+
...input.seoDescription !== void 0 && { seoDescription: input.seoDescription },
|
|
1942
|
+
...input.media !== void 0 && { media: input.media },
|
|
1943
|
+
...input.metadata !== void 0 && { metadata: input.metadata },
|
|
1944
|
+
createdAt: now,
|
|
1945
|
+
updatedAt: now
|
|
1946
|
+
};
|
|
1947
|
+
await repos.product.insert(tx, insert);
|
|
1948
|
+
const variantRows = [];
|
|
1949
|
+
for (const v of input.variants ?? []) {
|
|
1950
|
+
const id2 = v.id ?? uuidv75();
|
|
1951
|
+
const vi = {
|
|
1952
|
+
...v,
|
|
1953
|
+
id: id2,
|
|
1954
|
+
productId,
|
|
1955
|
+
createdAt: now,
|
|
1956
|
+
updatedAt: now
|
|
1957
|
+
};
|
|
1958
|
+
await repos.variant.insert(tx, vi);
|
|
1959
|
+
const stored = await repos.variant.findById(tx, id2);
|
|
1960
|
+
if (stored) variantRows.push(stored);
|
|
1961
|
+
}
|
|
1962
|
+
for (const categoryId of input.categoryIds ?? []) {
|
|
1963
|
+
await repos.productCategory.attach(tx, productId, categoryId);
|
|
1964
|
+
}
|
|
1965
|
+
const created = await requireProduct(tx, productId);
|
|
1966
|
+
const snap = {
|
|
1967
|
+
...created,
|
|
1968
|
+
variants: variantRows,
|
|
1969
|
+
categoryIds: input.categoryIds ?? []
|
|
1970
|
+
};
|
|
1971
|
+
await publisher.publish(EVT_PRODUCT_CREATED, { product: snap });
|
|
1972
|
+
return snap;
|
|
1973
|
+
});
|
|
1219
1974
|
},
|
|
1220
|
-
|
|
1221
|
-
|
|
1222
|
-
|
|
1975
|
+
async update(id2, input) {
|
|
1976
|
+
return store.transaction(async (tx) => {
|
|
1977
|
+
audit.note("product.update", [{ type: "product", id: id2 }]);
|
|
1978
|
+
const product = await requireProduct(tx, id2);
|
|
1979
|
+
const current = new Map(
|
|
1980
|
+
(await repos.variant.findByProduct(tx, product.id)).map((v) => [v.id, v])
|
|
1981
|
+
);
|
|
1982
|
+
for (const item of input.variants ?? []) {
|
|
1983
|
+
if (!current.has(item.id)) {
|
|
1984
|
+
throw new HttpError2(400, `Variant ${item.id} is not a variant of this product`, {
|
|
1985
|
+
code: "product.variant_unknown"
|
|
1986
|
+
});
|
|
1987
|
+
}
|
|
1988
|
+
}
|
|
1989
|
+
const now = /* @__PURE__ */ new Date();
|
|
1990
|
+
const updateInput = {
|
|
1991
|
+
...input.name !== void 0 && { name: input.name },
|
|
1992
|
+
...input.description !== void 0 && { description: input.description },
|
|
1993
|
+
...input.shortDescription !== void 0 && { shortDescription: input.shortDescription },
|
|
1994
|
+
...input.status !== void 0 && { status: input.status },
|
|
1995
|
+
...input.type !== void 0 && { type: input.type },
|
|
1996
|
+
...input.seoTitle !== void 0 && { seoTitle: input.seoTitle },
|
|
1997
|
+
...input.seoDescription !== void 0 && { seoDescription: input.seoDescription },
|
|
1998
|
+
...input.media !== void 0 && { media: input.media },
|
|
1999
|
+
...input.metadata !== void 0 && { metadata: input.metadata },
|
|
2000
|
+
updatedAt: now
|
|
2001
|
+
};
|
|
2002
|
+
await repos.product.update(tx, product.id, updateInput);
|
|
2003
|
+
if (input.categoryIds) {
|
|
2004
|
+
await repos.productCategory.detachAllForProduct(tx, product.id);
|
|
2005
|
+
for (const categoryId of input.categoryIds) {
|
|
2006
|
+
await repos.productCategory.attach(tx, product.id, categoryId);
|
|
2007
|
+
}
|
|
2008
|
+
}
|
|
2009
|
+
for (const item of input.variants ?? []) {
|
|
2010
|
+
const before = current.get(item.id);
|
|
2011
|
+
const compareAtPriceMinor = item.compareAtPriceMinor === void 0 ? before.compareAtPriceMinor : item.compareAtPriceMinor;
|
|
2012
|
+
if (item.priceMinor === before.priceMinor && compareAtPriceMinor === before.compareAtPriceMinor) {
|
|
2013
|
+
continue;
|
|
2014
|
+
}
|
|
2015
|
+
await repos.variant.update(tx, item.id, {
|
|
2016
|
+
priceMinor: item.priceMinor,
|
|
2017
|
+
compareAtPriceMinor,
|
|
2018
|
+
updatedAt: now
|
|
2019
|
+
});
|
|
2020
|
+
current.set(item.id, { ...before, priceMinor: item.priceMinor, compareAtPriceMinor });
|
|
2021
|
+
await publisher.publish(EVT_PRODUCT_VARIANT_PRICE_CHANGED, {
|
|
2022
|
+
productId: product.id,
|
|
2023
|
+
variantId: item.id,
|
|
2024
|
+
previousPriceMinor: before.priceMinor,
|
|
2025
|
+
priceMinor: item.priceMinor,
|
|
2026
|
+
previousCompareAtPriceMinor: before.compareAtPriceMinor,
|
|
2027
|
+
compareAtPriceMinor,
|
|
2028
|
+
currency
|
|
2029
|
+
});
|
|
2030
|
+
}
|
|
2031
|
+
const snap = await snapshot(tx, repos, await requireProduct(tx, product.id));
|
|
2032
|
+
await publisher.publish(EVT_PRODUCT_UPDATED, { product: snap });
|
|
2033
|
+
return snap;
|
|
2034
|
+
});
|
|
2035
|
+
},
|
|
2036
|
+
async delete(id2) {
|
|
2037
|
+
await store.transaction(async (tx) => {
|
|
2038
|
+
audit.note("product.delete", [{ type: "product", id: id2 }]);
|
|
2039
|
+
const product = await requireProduct(tx, id2);
|
|
2040
|
+
await repos.productCategory.detachAllForProduct(tx, product.id);
|
|
2041
|
+
const variants = await repos.variant.findByProduct(tx, product.id);
|
|
2042
|
+
for (const v of variants) await repos.variant.delete(tx, v.id);
|
|
2043
|
+
await repos.product.delete(tx, product.id);
|
|
2044
|
+
await publisher.publish(EVT_PRODUCT_DELETED, {
|
|
2045
|
+
productId: product.id,
|
|
2046
|
+
slug: product.slug
|
|
2047
|
+
});
|
|
2048
|
+
});
|
|
2049
|
+
},
|
|
2050
|
+
async publish(id2) {
|
|
2051
|
+
await store.transaction(async (tx) => {
|
|
2052
|
+
audit.note("product.publish", [{ type: "product", id: id2 }]);
|
|
2053
|
+
const product = await requireProduct(tx, id2);
|
|
2054
|
+
if (product.status === "active") return;
|
|
2055
|
+
await repos.product.setStatus(tx, product.id, "active", /* @__PURE__ */ new Date());
|
|
2056
|
+
await publisher.publish(EVT_PRODUCT_PUBLISHED, {
|
|
2057
|
+
productId: product.id,
|
|
2058
|
+
slug: product.slug
|
|
2059
|
+
});
|
|
2060
|
+
const fresh = await requireProduct(tx, product.id);
|
|
2061
|
+
const snap = await snapshot(tx, repos, fresh);
|
|
2062
|
+
await publisher.publish(EVT_PRODUCT_UPDATED, { product: snap });
|
|
2063
|
+
});
|
|
2064
|
+
},
|
|
2065
|
+
async unpublish(id2) {
|
|
2066
|
+
await store.transaction(async (tx) => {
|
|
2067
|
+
audit.note("product.unpublish", [{ type: "product", id: id2 }]);
|
|
2068
|
+
const product = await requireProduct(tx, id2);
|
|
2069
|
+
if (product.status === "draft") return;
|
|
2070
|
+
await repos.product.setStatus(tx, product.id, "draft", /* @__PURE__ */ new Date());
|
|
2071
|
+
await publisher.publish(EVT_PRODUCT_UNPUBLISHED, {
|
|
2072
|
+
productId: product.id,
|
|
2073
|
+
slug: product.slug
|
|
2074
|
+
});
|
|
2075
|
+
const fresh = await requireProduct(tx, product.id);
|
|
2076
|
+
const snap = await snapshot(tx, repos, fresh);
|
|
2077
|
+
await publisher.publish(EVT_PRODUCT_UPDATED, { product: snap });
|
|
2078
|
+
});
|
|
2079
|
+
},
|
|
2080
|
+
async getById(id2) {
|
|
2081
|
+
return store.read(async (tx) => snapshot(tx, repos, await requireProduct(tx, id2)));
|
|
2082
|
+
},
|
|
2083
|
+
async getBySlug(slug) {
|
|
2084
|
+
return store.read(async (tx) => {
|
|
2085
|
+
const product = await repos.product.findBySlug(tx, slug);
|
|
2086
|
+
if (!product) throw new NotFoundError3("product", slug);
|
|
2087
|
+
return snapshot(tx, repos, product);
|
|
2088
|
+
});
|
|
2089
|
+
},
|
|
2090
|
+
async list(opts = {}) {
|
|
2091
|
+
return store.read(async (tx) => {
|
|
2092
|
+
const products = await repos.product.list(tx, opts);
|
|
2093
|
+
const out = [];
|
|
2094
|
+
for (const p of products) {
|
|
2095
|
+
out.push(await snapshot(tx, repos, p));
|
|
2096
|
+
}
|
|
2097
|
+
return out;
|
|
2098
|
+
});
|
|
2099
|
+
}
|
|
1223
2100
|
};
|
|
1224
2101
|
}
|
|
1225
|
-
function registerCapabilitiesRoute(adapter, adapters) {
|
|
1226
|
-
adapter.registerRoute("GET", "/api/capabilities", async () => {
|
|
1227
|
-
try {
|
|
1228
|
-
return ok(storeCapabilities(adapters));
|
|
1229
|
-
} catch (err) {
|
|
1230
|
-
return renderError(err);
|
|
1231
|
-
}
|
|
1232
|
-
});
|
|
1233
|
-
}
|
|
1234
2102
|
|
|
1235
|
-
// src/
|
|
1236
|
-
|
|
1237
|
-
|
|
1238
|
-
|
|
1239
|
-
|
|
1240
|
-
|
|
1241
|
-
|
|
1242
|
-
|
|
1243
|
-
|
|
1244
|
-
|
|
1245
|
-
|
|
1246
|
-
|
|
2103
|
+
// src/services/category-service.ts
|
|
2104
|
+
import { v7 as uuidv76 } from "uuid";
|
|
2105
|
+
import {
|
|
2106
|
+
EVT_CATEGORY_CREATED,
|
|
2107
|
+
EVT_CATEGORY_UPDATED,
|
|
2108
|
+
EVT_CATEGORY_DELETED,
|
|
2109
|
+
NotFoundError as NotFoundError4,
|
|
2110
|
+
ValidationError as ValidationError4
|
|
2111
|
+
} from "@nymbalhq/types";
|
|
2112
|
+
function createCategoryService(deps) {
|
|
2113
|
+
const { repos, publisher } = deps;
|
|
2114
|
+
const { store } = repos.category;
|
|
2115
|
+
return {
|
|
2116
|
+
async list() {
|
|
2117
|
+
return store.read((tx) => repos.category.list(tx));
|
|
2118
|
+
},
|
|
2119
|
+
async getById(id2) {
|
|
2120
|
+
const c = await store.read((tx) => repos.category.findById(tx, id2));
|
|
2121
|
+
if (!c) throw new NotFoundError4("category", id2);
|
|
2122
|
+
return c;
|
|
2123
|
+
},
|
|
2124
|
+
async getBySlug(slug) {
|
|
2125
|
+
const c = await store.read((tx) => repos.category.findBySlug(tx, slug));
|
|
2126
|
+
if (!c) throw new NotFoundError4("category", slug);
|
|
2127
|
+
return c;
|
|
2128
|
+
},
|
|
2129
|
+
async create(input) {
|
|
2130
|
+
audit.note("category.create");
|
|
2131
|
+
if (!input.slug.trim()) throw new ValidationError4("Category slug is required");
|
|
2132
|
+
return store.transaction(async (tx) => {
|
|
2133
|
+
if (await repos.category.findBySlug(tx, input.slug)) {
|
|
2134
|
+
throw new ValidationError4(`Category slug already exists: ${input.slug}`);
|
|
2135
|
+
}
|
|
2136
|
+
const now = /* @__PURE__ */ new Date();
|
|
2137
|
+
const id2 = uuidv76();
|
|
2138
|
+
audit.note("category.create", [{ type: "category", id: id2 }]);
|
|
2139
|
+
const category = {
|
|
2140
|
+
id: id2,
|
|
2141
|
+
parentId: input.parentId ?? null,
|
|
2142
|
+
slug: input.slug,
|
|
2143
|
+
name: input.name,
|
|
2144
|
+
description: input.description ?? "",
|
|
2145
|
+
position: input.position ?? 0,
|
|
2146
|
+
createdAt: now.toISOString()
|
|
2147
|
+
};
|
|
2148
|
+
await repos.category.insert(tx, { ...category, createdAt: now });
|
|
2149
|
+
await publisher.publish(EVT_CATEGORY_CREATED, { category });
|
|
2150
|
+
return category;
|
|
2151
|
+
});
|
|
2152
|
+
},
|
|
2153
|
+
async update(id2, input) {
|
|
2154
|
+
return store.transaction(async (tx) => {
|
|
2155
|
+
audit.note("category.update", [{ type: "category", id: id2 }]);
|
|
2156
|
+
const existing = await repos.category.findById(tx, id2);
|
|
2157
|
+
if (!existing) throw new NotFoundError4("category", id2);
|
|
2158
|
+
await repos.category.update(tx, id2, input);
|
|
2159
|
+
const fresh = await repos.category.findById(tx, id2);
|
|
2160
|
+
await publisher.publish(EVT_CATEGORY_UPDATED, { category: fresh });
|
|
2161
|
+
return fresh;
|
|
2162
|
+
});
|
|
2163
|
+
},
|
|
2164
|
+
async delete(id2) {
|
|
2165
|
+
await store.transaction(async (tx) => {
|
|
2166
|
+
audit.note("category.delete", [{ type: "category", id: id2 }]);
|
|
2167
|
+
const existing = await repos.category.findById(tx, id2);
|
|
2168
|
+
if (!existing) throw new NotFoundError4("category", id2);
|
|
2169
|
+
await repos.category.delete(tx, id2);
|
|
2170
|
+
await publisher.publish(EVT_CATEGORY_DELETED, {
|
|
2171
|
+
categoryId: existing.id,
|
|
2172
|
+
slug: existing.slug
|
|
2173
|
+
});
|
|
2174
|
+
});
|
|
1247
2175
|
}
|
|
1248
|
-
}
|
|
2176
|
+
};
|
|
1249
2177
|
}
|
|
1250
2178
|
|
|
1251
|
-
// src/
|
|
1252
|
-
import "
|
|
1253
|
-
|
|
1254
|
-
|
|
1255
|
-
|
|
1256
|
-
|
|
1257
|
-
|
|
1258
|
-
|
|
1259
|
-
|
|
1260
|
-
|
|
1261
|
-
|
|
1262
|
-
|
|
1263
|
-
|
|
1264
|
-
|
|
1265
|
-
|
|
1266
|
-
}
|
|
1267
|
-
|
|
1268
|
-
const
|
|
1269
|
-
|
|
1270
|
-
|
|
1271
|
-
|
|
1272
|
-
|
|
1273
|
-
|
|
1274
|
-
|
|
1275
|
-
|
|
1276
|
-
|
|
1277
|
-
|
|
1278
|
-
|
|
1279
|
-
|
|
1280
|
-
|
|
1281
|
-
|
|
1282
|
-
|
|
1283
|
-
|
|
1284
|
-
|
|
1285
|
-
|
|
1286
|
-
|
|
1287
|
-
|
|
1288
|
-
|
|
1289
|
-
|
|
1290
|
-
|
|
1291
|
-
|
|
1292
|
-
|
|
1293
|
-
|
|
2179
|
+
// src/services/cart-service.ts
|
|
2180
|
+
import { v7 as uuidv77 } from "uuid";
|
|
2181
|
+
import {
|
|
2182
|
+
EVT_CART_CREATED,
|
|
2183
|
+
EVT_CART_ITEM_ADDED,
|
|
2184
|
+
EVT_CART_ITEM_REMOVED,
|
|
2185
|
+
EVT_CART_UPDATED,
|
|
2186
|
+
NotFoundError as NotFoundError5,
|
|
2187
|
+
ValidationError as ValidationError5
|
|
2188
|
+
} from "@nymbalhq/types";
|
|
2189
|
+
var TTL_SECONDS_DEFAULT = 60 * 60 * 24 * 30;
|
|
2190
|
+
function calcSubtotal(items) {
|
|
2191
|
+
return items.reduce((sum, item) => sum + item.priceMinor * item.qty, 0);
|
|
2192
|
+
}
|
|
2193
|
+
function createCartService(deps) {
|
|
2194
|
+
const { store, carts, publisher, currency } = deps;
|
|
2195
|
+
const ttlMs = (deps.ttlSeconds ?? TTL_SECONDS_DEFAULT) * 1e3;
|
|
2196
|
+
const now = deps.now ?? (() => /* @__PURE__ */ new Date());
|
|
2197
|
+
function live(cart, at) {
|
|
2198
|
+
return cart !== null && Date.parse(cart.expiresAt) > at.getTime();
|
|
2199
|
+
}
|
|
2200
|
+
function written(cart, items, at) {
|
|
2201
|
+
return {
|
|
2202
|
+
...cart,
|
|
2203
|
+
items,
|
|
2204
|
+
subtotalMinor: calcSubtotal(items),
|
|
2205
|
+
updatedAt: at.toISOString(),
|
|
2206
|
+
expiresAt: new Date(at.getTime() + ttlMs).toISOString()
|
|
2207
|
+
};
|
|
2208
|
+
}
|
|
2209
|
+
async function requireCart(tx, token, at) {
|
|
2210
|
+
const cart = await carts.lock(tx, token);
|
|
2211
|
+
if (!live(cart, at)) throw new NotFoundError5("cart", token);
|
|
2212
|
+
return cart;
|
|
2213
|
+
}
|
|
2214
|
+
async function emitUpdated(cart) {
|
|
2215
|
+
await publisher.publish(EVT_CART_UPDATED, {
|
|
2216
|
+
cartId: cart.token,
|
|
2217
|
+
itemCount: cart.items.reduce((n, i) => n + i.qty, 0),
|
|
2218
|
+
totalMinor: cart.subtotalMinor
|
|
2219
|
+
});
|
|
2220
|
+
}
|
|
2221
|
+
function command(token, change) {
|
|
2222
|
+
return store.transaction(async (tx) => {
|
|
2223
|
+
const at = now();
|
|
2224
|
+
const next = await change(await requireCart(tx, token, at), at);
|
|
2225
|
+
await carts.put(tx, next);
|
|
2226
|
+
await emitUpdated(next);
|
|
2227
|
+
return next;
|
|
2228
|
+
});
|
|
2229
|
+
}
|
|
2230
|
+
return {
|
|
2231
|
+
async getOrCreate(token, customerId = null) {
|
|
2232
|
+
return store.transaction(async (tx) => {
|
|
2233
|
+
const at = now();
|
|
2234
|
+
const { cart, created } = await carts.create(tx, {
|
|
2235
|
+
token: token ?? uuidv77(),
|
|
2236
|
+
customerId,
|
|
2237
|
+
items: [],
|
|
2238
|
+
subtotalMinor: 0,
|
|
2239
|
+
currency,
|
|
2240
|
+
expiresAt: new Date(at.getTime() + ttlMs).toISOString(),
|
|
2241
|
+
createdAt: at.toISOString(),
|
|
2242
|
+
updatedAt: at.toISOString()
|
|
1294
2243
|
});
|
|
1295
|
-
|
|
1296
|
-
|
|
1297
|
-
|
|
1298
|
-
|
|
1299
|
-
|
|
1300
|
-
|
|
1301
|
-
|
|
1302
|
-
|
|
1303
|
-
|
|
1304
|
-
|
|
1305
|
-
|
|
1306
|
-
|
|
1307
|
-
|
|
1308
|
-
|
|
2244
|
+
if (created) {
|
|
2245
|
+
await publisher.publish(EVT_CART_CREATED, { cartId: cart.token, token: cart.token });
|
|
2246
|
+
}
|
|
2247
|
+
return cart;
|
|
2248
|
+
});
|
|
2249
|
+
},
|
|
2250
|
+
async get(token) {
|
|
2251
|
+
const at = now();
|
|
2252
|
+
const cart = await store.read((tx) => carts.findByToken(tx, token));
|
|
2253
|
+
return live(cart, at) ? cart : null;
|
|
2254
|
+
},
|
|
2255
|
+
async addItem(token, item) {
|
|
2256
|
+
return command(token, async (cart, at) => {
|
|
2257
|
+
const qty = item.qty ?? 1;
|
|
2258
|
+
if (qty <= 0) throw new ValidationError5(`qty must be positive, got ${qty}`);
|
|
2259
|
+
const onCart = cart.items.some((i) => i.variantId === item.variantId);
|
|
2260
|
+
const items = onCart ? cart.items.map((i) => i.variantId === item.variantId ? { ...i, qty: i.qty + qty } : i) : [
|
|
2261
|
+
...cart.items,
|
|
2262
|
+
{
|
|
2263
|
+
variantId: item.variantId,
|
|
2264
|
+
productId: item.productId,
|
|
2265
|
+
productName: item.productName,
|
|
2266
|
+
variantName: item.variantName,
|
|
2267
|
+
priceMinor: item.priceMinor,
|
|
2268
|
+
imageUrl: item.imageUrl,
|
|
2269
|
+
qty
|
|
2270
|
+
}
|
|
2271
|
+
];
|
|
2272
|
+
await publisher.publish(EVT_CART_ITEM_ADDED, {
|
|
2273
|
+
cartId: cart.token,
|
|
2274
|
+
variantId: item.variantId,
|
|
2275
|
+
qty
|
|
2276
|
+
});
|
|
2277
|
+
return written(cart, items, at);
|
|
2278
|
+
});
|
|
2279
|
+
},
|
|
2280
|
+
async updateItemQuantity(token, variantId, qty) {
|
|
2281
|
+
if (qty < 0) throw new ValidationError5(`qty must be non-negative, got ${qty}`);
|
|
2282
|
+
return command(token, async (cart, at) => {
|
|
2283
|
+
if (!cart.items.some((i) => i.variantId === variantId)) {
|
|
2284
|
+
throw new NotFoundError5("cart_item", variantId);
|
|
2285
|
+
}
|
|
2286
|
+
if (qty === 0) {
|
|
2287
|
+
await publisher.publish(EVT_CART_ITEM_REMOVED, { cartId: cart.token, variantId });
|
|
2288
|
+
return written(
|
|
2289
|
+
cart,
|
|
2290
|
+
cart.items.filter((i) => i.variantId !== variantId),
|
|
2291
|
+
at
|
|
2292
|
+
);
|
|
2293
|
+
}
|
|
2294
|
+
return written(
|
|
2295
|
+
cart,
|
|
2296
|
+
cart.items.map((i) => i.variantId === variantId ? { ...i, qty } : i),
|
|
2297
|
+
at
|
|
2298
|
+
);
|
|
2299
|
+
});
|
|
2300
|
+
},
|
|
2301
|
+
async removeItem(token, variantId) {
|
|
2302
|
+
return command(token, async (cart, at) => {
|
|
2303
|
+
const items = cart.items.filter((i) => i.variantId !== variantId);
|
|
2304
|
+
if (items.length < cart.items.length) {
|
|
2305
|
+
await publisher.publish(EVT_CART_ITEM_REMOVED, { cartId: cart.token, variantId });
|
|
2306
|
+
}
|
|
2307
|
+
return written(cart, items, at);
|
|
2308
|
+
});
|
|
2309
|
+
},
|
|
2310
|
+
async clear(token) {
|
|
2311
|
+
return command(token, async (cart, at) => written(cart, [], at));
|
|
2312
|
+
},
|
|
2313
|
+
async attachCustomer(token, customerId) {
|
|
2314
|
+
return command(token, async (cart, at) => ({ ...written(cart, cart.items, at), customerId }));
|
|
2315
|
+
},
|
|
2316
|
+
async merge(guestToken, customerToken) {
|
|
2317
|
+
return store.transaction(async (tx) => {
|
|
2318
|
+
const at = now();
|
|
2319
|
+
const guest = await carts.lock(tx, guestToken);
|
|
2320
|
+
if (!live(guest, at)) return requireCart(tx, customerToken, at);
|
|
2321
|
+
const customerCart = await carts.lock(tx, customerToken);
|
|
2322
|
+
let merged2;
|
|
2323
|
+
if (live(customerCart, at)) {
|
|
2324
|
+
const held = customerCart.items;
|
|
2325
|
+
const items = [
|
|
2326
|
+
...held.map((i) => {
|
|
2327
|
+
const g = guest.items.find((x) => x.variantId === i.variantId);
|
|
2328
|
+
return g ? { ...i, qty: Math.max(i.qty, g.qty) } : i;
|
|
2329
|
+
}),
|
|
2330
|
+
...guest.items.filter((g) => !held.some((i) => i.variantId === g.variantId))
|
|
2331
|
+
];
|
|
2332
|
+
merged2 = written(customerCart, items, at);
|
|
2333
|
+
} else {
|
|
2334
|
+
merged2 = written({ ...guest, token: customerToken }, guest.items, at);
|
|
2335
|
+
}
|
|
2336
|
+
await carts.remove(tx, guestToken);
|
|
2337
|
+
await carts.put(tx, merged2);
|
|
2338
|
+
await emitUpdated(merged2);
|
|
2339
|
+
return merged2;
|
|
1309
2340
|
});
|
|
1310
|
-
const env = ok(updated);
|
|
1311
|
-
env.cookies = cookie(token);
|
|
1312
|
-
return env;
|
|
1313
|
-
} catch (err) {
|
|
1314
|
-
return renderError(err);
|
|
1315
|
-
}
|
|
1316
|
-
});
|
|
1317
|
-
adapter.registerRoute("PATCH", "/api/cart/items/:variantId", async (ctx) => {
|
|
1318
|
-
try {
|
|
1319
|
-
const token = ctx.cookies[CART_COOKIE];
|
|
1320
|
-
if (!token) return fail("cart.missing", "no active cart", 404);
|
|
1321
|
-
const variantId = ctx.params.variantId;
|
|
1322
|
-
if (!variantId) return fail("cart.variant_required", "variantId param required", 400);
|
|
1323
|
-
const qty = ctx.body?.qty ?? 0;
|
|
1324
|
-
const updated = await cart.updateItemQuantity(token, variantId, qty);
|
|
1325
|
-
return ok(updated);
|
|
1326
|
-
} catch (err) {
|
|
1327
|
-
return renderError(err);
|
|
1328
|
-
}
|
|
1329
|
-
});
|
|
1330
|
-
adapter.registerRoute("DELETE", "/api/cart/items/:variantId", async (ctx) => {
|
|
1331
|
-
try {
|
|
1332
|
-
const token = ctx.cookies[CART_COOKIE];
|
|
1333
|
-
if (!token) return fail("cart.missing", "no active cart", 404);
|
|
1334
|
-
const variantId = ctx.params.variantId;
|
|
1335
|
-
if (!variantId) return fail("cart.variant_required", "variantId param required", 400);
|
|
1336
|
-
const updated = await cart.removeItem(token, variantId);
|
|
1337
|
-
return ok(updated);
|
|
1338
|
-
} catch (err) {
|
|
1339
|
-
return renderError(err);
|
|
1340
|
-
}
|
|
1341
|
-
});
|
|
1342
|
-
adapter.registerRoute("DELETE", "/api/cart", async (ctx) => {
|
|
1343
|
-
try {
|
|
1344
|
-
const token = ctx.cookies[CART_COOKIE];
|
|
1345
|
-
if (!token) return fail("cart.missing", "no active cart", 404);
|
|
1346
|
-
const cleared = await cart.clear(token);
|
|
1347
|
-
return ok(cleared);
|
|
1348
|
-
} catch (err) {
|
|
1349
|
-
return renderError(err);
|
|
1350
2341
|
}
|
|
1351
|
-
}
|
|
2342
|
+
};
|
|
1352
2343
|
}
|
|
1353
2344
|
|
|
1354
|
-
// src/
|
|
1355
|
-
import "
|
|
1356
|
-
|
|
1357
|
-
|
|
1358
|
-
|
|
1359
|
-
|
|
1360
|
-
|
|
1361
|
-
|
|
1362
|
-
|
|
1363
|
-
|
|
1364
|
-
|
|
1365
|
-
|
|
1366
|
-
|
|
1367
|
-
|
|
1368
|
-
|
|
1369
|
-
|
|
1370
|
-
|
|
1371
|
-
|
|
1372
|
-
|
|
2345
|
+
// src/services/customer-service.ts
|
|
2346
|
+
import { v7 as uuidv78 } from "uuid";
|
|
2347
|
+
import {
|
|
2348
|
+
EVT_CUSTOMER_UPDATED,
|
|
2349
|
+
NotFoundError as NotFoundError6,
|
|
2350
|
+
ValidationError as ValidationError6
|
|
2351
|
+
} from "@nymbalhq/types";
|
|
2352
|
+
function stripPassword2(c) {
|
|
2353
|
+
const { passwordHash: _pw, ...rest } = c;
|
|
2354
|
+
return rest;
|
|
2355
|
+
}
|
|
2356
|
+
function createCustomerService(deps) {
|
|
2357
|
+
const { repos, publisher } = deps;
|
|
2358
|
+
const { store } = repos.customer;
|
|
2359
|
+
async function loadOrThrow(tx, id2) {
|
|
2360
|
+
const c = await repos.customer.findById(tx, id2);
|
|
2361
|
+
if (!c) throw new NotFoundError6("customer", id2);
|
|
2362
|
+
return c;
|
|
2363
|
+
}
|
|
2364
|
+
async function publishUpdated(tx, customerId) {
|
|
2365
|
+
const fresh = stripPassword2(await loadOrThrow(tx, customerId));
|
|
2366
|
+
await publisher.publish(EVT_CUSTOMER_UPDATED, {
|
|
2367
|
+
customerId,
|
|
2368
|
+
customer: toCustomerSnapshot(fresh)
|
|
2369
|
+
});
|
|
2370
|
+
return fresh;
|
|
2371
|
+
}
|
|
2372
|
+
return {
|
|
2373
|
+
async getProfile(customerId) {
|
|
2374
|
+
return stripPassword2(await store.read((tx) => loadOrThrow(tx, customerId)));
|
|
2375
|
+
},
|
|
2376
|
+
async updateProfile(customerId, patch) {
|
|
2377
|
+
return store.transaction(async (tx) => {
|
|
2378
|
+
audit.note("customer.update", [{ type: "customer", id: customerId }]);
|
|
2379
|
+
await loadOrThrow(tx, customerId);
|
|
2380
|
+
const now = /* @__PURE__ */ new Date();
|
|
2381
|
+
await repos.customer.update(tx, customerId, { ...patch, updatedAt: now });
|
|
2382
|
+
return publishUpdated(tx, customerId);
|
|
1373
2383
|
});
|
|
1374
|
-
|
|
1375
|
-
|
|
1376
|
-
|
|
1377
|
-
|
|
1378
|
-
|
|
1379
|
-
|
|
1380
|
-
|
|
1381
|
-
|
|
2384
|
+
},
|
|
2385
|
+
async listAddresses(customerId) {
|
|
2386
|
+
const customer = await store.read((tx) => loadOrThrow(tx, customerId));
|
|
2387
|
+
return customer.addresses;
|
|
2388
|
+
},
|
|
2389
|
+
async addAddress(customerId, addr) {
|
|
2390
|
+
return store.transaction(async (tx) => {
|
|
2391
|
+
audit.note("customer.addAddress", [{ type: "customer", id: customerId }]);
|
|
2392
|
+
const customer = await loadOrThrow(tx, customerId);
|
|
2393
|
+
const newAddr = { ...addr, id: uuidv78() };
|
|
2394
|
+
const defaultBilling = newAddr.isDefaultBilling;
|
|
2395
|
+
const defaultShipping = newAddr.isDefaultShipping;
|
|
2396
|
+
const addresses = customer.addresses.map((a) => ({
|
|
2397
|
+
...a,
|
|
2398
|
+
isDefaultBilling: defaultBilling ? false : a.isDefaultBilling,
|
|
2399
|
+
isDefaultShipping: defaultShipping ? false : a.isDefaultShipping
|
|
2400
|
+
}));
|
|
2401
|
+
addresses.push(newAddr);
|
|
2402
|
+
const now = /* @__PURE__ */ new Date();
|
|
2403
|
+
await repos.customer.update(tx, customerId, { addresses, updatedAt: now });
|
|
2404
|
+
await publishUpdated(tx, customerId);
|
|
2405
|
+
return newAddr;
|
|
2406
|
+
});
|
|
2407
|
+
},
|
|
2408
|
+
async deleteAddress(customerId, addressId) {
|
|
2409
|
+
await store.transaction(async (tx) => {
|
|
2410
|
+
audit.note("customer.removeAddress", [{ type: "customer", id: customerId }]);
|
|
2411
|
+
const customer = await loadOrThrow(tx, customerId);
|
|
2412
|
+
const addresses = customer.addresses.filter((a) => a.id !== addressId);
|
|
2413
|
+
if (addresses.length === customer.addresses.length) {
|
|
2414
|
+
throw new NotFoundError6("address", addressId);
|
|
2415
|
+
}
|
|
2416
|
+
if (!addresses.length) {
|
|
2417
|
+
throw new ValidationError6("Cannot remove last address");
|
|
2418
|
+
}
|
|
2419
|
+
const now = /* @__PURE__ */ new Date();
|
|
2420
|
+
await repos.customer.update(tx, customerId, { addresses, updatedAt: now });
|
|
2421
|
+
await publishUpdated(tx, customerId);
|
|
1382
2422
|
});
|
|
1383
|
-
} catch (err) {
|
|
1384
|
-
return renderError(err);
|
|
1385
2423
|
}
|
|
1386
|
-
}
|
|
2424
|
+
};
|
|
1387
2425
|
}
|
|
1388
2426
|
|
|
1389
|
-
// src/
|
|
2427
|
+
// src/services/order-service.ts
|
|
2428
|
+
import { v7 as uuidv79 } from "uuid";
|
|
1390
2429
|
import {
|
|
1391
|
-
|
|
2430
|
+
EVT_ORDER_CANCELLED,
|
|
2431
|
+
EVT_ORDER_CONFIRMATION_RESEND_REQUESTED,
|
|
2432
|
+
EVT_ORDER_DELIVERED,
|
|
2433
|
+
EVT_ORDER_PLACED,
|
|
2434
|
+
EVT_ORDER_SHIPPED,
|
|
2435
|
+
EVT_ORDER_STATUS_CHANGED,
|
|
2436
|
+
NotFoundError as NotFoundError7,
|
|
2437
|
+
OrderConflictError as OrderConflictError2,
|
|
2438
|
+
StatusTransitionError as StatusTransitionError2,
|
|
2439
|
+
ValidationError as ValidationError7,
|
|
2440
|
+
assertOrderTransition
|
|
1392
2441
|
} from "@nymbalhq/types";
|
|
1393
2442
|
|
|
1394
|
-
// src/
|
|
1395
|
-
import {
|
|
1396
|
-
|
|
1397
|
-
|
|
1398
|
-
|
|
1399
|
-
|
|
1400
|
-
}
|
|
1401
|
-
return handler(ctx);
|
|
1402
|
-
};
|
|
2443
|
+
// src/order-access-key.ts
|
|
2444
|
+
import { createHash as createHash3, randomBytes } from "crypto";
|
|
2445
|
+
var ORDER_KEY = /^[A-Za-z0-9_-]{43}$/;
|
|
2446
|
+
function mintOrderKey() {
|
|
2447
|
+
const key = randomBytes(32).toString("base64url");
|
|
2448
|
+
return { key, hash: hashOrderKey(key) };
|
|
1403
2449
|
}
|
|
1404
|
-
function
|
|
1405
|
-
return (
|
|
1406
|
-
|
|
1407
|
-
|
|
1408
|
-
|
|
1409
|
-
if (!ctx.auth.roles?.includes(role)) {
|
|
1410
|
-
return fail("auth.forbidden", `Role required: ${role}`, 403);
|
|
1411
|
-
}
|
|
1412
|
-
return handler(ctx);
|
|
1413
|
-
};
|
|
2450
|
+
function hashOrderKey(key) {
|
|
2451
|
+
return createHash3("sha256").update(key).digest("hex");
|
|
2452
|
+
}
|
|
2453
|
+
function isOrderKey(value) {
|
|
2454
|
+
return typeof value === "string" && ORDER_KEY.test(value);
|
|
1414
2455
|
}
|
|
1415
2456
|
|
|
1416
|
-
// src/
|
|
1417
|
-
|
|
1418
|
-
|
|
1419
|
-
|
|
1420
|
-
|
|
1421
|
-
|
|
1422
|
-
|
|
1423
|
-
|
|
1424
|
-
|
|
1425
|
-
|
|
1426
|
-
|
|
1427
|
-
|
|
1428
|
-
|
|
1429
|
-
|
|
1430
|
-
|
|
1431
|
-
|
|
1432
|
-
|
|
1433
|
-
|
|
1434
|
-
|
|
1435
|
-
|
|
1436
|
-
|
|
1437
|
-
|
|
1438
|
-
|
|
1439
|
-
|
|
1440
|
-
|
|
1441
|
-
|
|
1442
|
-
|
|
1443
|
-
|
|
1444
|
-
|
|
1445
|
-
|
|
1446
|
-
|
|
1447
|
-
|
|
1448
|
-
|
|
1449
|
-
|
|
1450
|
-
|
|
1451
|
-
|
|
1452
|
-
|
|
1453
|
-
|
|
1454
|
-
|
|
1455
|
-
|
|
1456
|
-
|
|
1457
|
-
|
|
1458
|
-
|
|
1459
|
-
|
|
1460
|
-
|
|
1461
|
-
|
|
1462
|
-
|
|
1463
|
-
|
|
1464
|
-
|
|
1465
|
-
|
|
1466
|
-
|
|
1467
|
-
|
|
1468
|
-
|
|
1469
|
-
"/api/customers/me",
|
|
1470
|
-
requireAuth(async (ctx) => {
|
|
1471
|
-
try {
|
|
1472
|
-
const patch = ctx.body;
|
|
1473
|
-
const profile = await customers.updateProfile(ctx.auth.userId, {
|
|
1474
|
-
...typeof patch.firstName === "string" && { firstName: patch.firstName },
|
|
1475
|
-
...typeof patch.lastName === "string" && { lastName: patch.lastName },
|
|
1476
|
-
...typeof patch.phone === "string" && { phone: patch.phone }
|
|
2457
|
+
// src/services/order-service.ts
|
|
2458
|
+
var NO_CONFIRMATION_DUE = /* @__PURE__ */ new Set(["pending", "cancelled"]);
|
|
2459
|
+
function createOrderService(deps) {
|
|
2460
|
+
const { store, repos, publisher } = deps;
|
|
2461
|
+
async function requireOrder(tx, id2) {
|
|
2462
|
+
const order = await repos.order.findById(tx, id2);
|
|
2463
|
+
if (!order) throw new NotFoundError7("order", id2);
|
|
2464
|
+
return order;
|
|
2465
|
+
}
|
|
2466
|
+
async function doTransition(tx, order, toStatus, actor, note) {
|
|
2467
|
+
assertOrderTransition(order.status, toStatus);
|
|
2468
|
+
const now = /* @__PURE__ */ new Date();
|
|
2469
|
+
await repos.order.setStatus(tx, order.id, toStatus, now);
|
|
2470
|
+
await repos.orderHistory.append(tx, {
|
|
2471
|
+
id: uuidv79(),
|
|
2472
|
+
orderId: order.id,
|
|
2473
|
+
fromStatus: order.status,
|
|
2474
|
+
toStatus,
|
|
2475
|
+
actor,
|
|
2476
|
+
note,
|
|
2477
|
+
timestamp: now
|
|
2478
|
+
});
|
|
2479
|
+
return requireOrder(tx, order.id);
|
|
2480
|
+
}
|
|
2481
|
+
return {
|
|
2482
|
+
async createFromCheckout(input) {
|
|
2483
|
+
return store.transaction(async (tx) => {
|
|
2484
|
+
audit.note("order.place", [{ type: "order", id: input.orderId }]);
|
|
2485
|
+
const sequence = await repos.orderSequence.nextSequence(tx, deps.orderNumberStart);
|
|
2486
|
+
const orderNumber = `${deps.orderNumberPrefix}-${sequence + 1}`;
|
|
2487
|
+
const now = /* @__PURE__ */ new Date();
|
|
2488
|
+
await repos.order.insert(tx, {
|
|
2489
|
+
id: input.orderId,
|
|
2490
|
+
orderNumber,
|
|
2491
|
+
sequence,
|
|
2492
|
+
customerId: input.customerId,
|
|
2493
|
+
status: "pending",
|
|
2494
|
+
email: input.email,
|
|
2495
|
+
billingAddress: input.billingAddress,
|
|
2496
|
+
shippingAddress: input.shippingAddress,
|
|
2497
|
+
lineItems: input.lineItems,
|
|
2498
|
+
subtotalMinor: input.subtotalMinor,
|
|
2499
|
+
taxTotalMinor: input.taxTotalMinor,
|
|
2500
|
+
shippingTotalMinor: input.shippingTotalMinor,
|
|
2501
|
+
discountTotalMinor: input.discountTotalMinor,
|
|
2502
|
+
totalMinor: input.totalMinor,
|
|
2503
|
+
currency: input.currency,
|
|
2504
|
+
notes: input.notes ?? "",
|
|
2505
|
+
metadata: input.metadata ?? {},
|
|
2506
|
+
paymentIntentId: input.paymentIntentId ?? null,
|
|
2507
|
+
cartToken: input.cartToken ?? null,
|
|
2508
|
+
createdAt: now,
|
|
2509
|
+
updatedAt: now
|
|
1477
2510
|
});
|
|
1478
|
-
|
|
1479
|
-
|
|
1480
|
-
|
|
1481
|
-
|
|
1482
|
-
|
|
1483
|
-
|
|
1484
|
-
|
|
1485
|
-
|
|
1486
|
-
"/api/customers/me/addresses",
|
|
1487
|
-
requireAuth(async (ctx) => {
|
|
1488
|
-
try {
|
|
1489
|
-
return ok(await customers.listAddresses(ctx.auth.userId));
|
|
1490
|
-
} catch (err) {
|
|
1491
|
-
return renderError(err);
|
|
1492
|
-
}
|
|
1493
|
-
})
|
|
1494
|
-
);
|
|
1495
|
-
adapter.registerRoute(
|
|
1496
|
-
"POST",
|
|
1497
|
-
"/api/customers/me/addresses",
|
|
1498
|
-
requireAuth(async (ctx) => {
|
|
1499
|
-
try {
|
|
1500
|
-
const body = ctx.body;
|
|
1501
|
-
if (!body || !body.addressLine1) return fail("address.invalid", "address invalid", 400);
|
|
1502
|
-
const addr = await customers.addAddress(ctx.auth.userId, {
|
|
1503
|
-
firstName: body.firstName,
|
|
1504
|
-
lastName: body.lastName,
|
|
1505
|
-
addressLine1: body.addressLine1,
|
|
1506
|
-
city: body.city,
|
|
1507
|
-
region: body.region,
|
|
1508
|
-
postalCode: body.postalCode,
|
|
1509
|
-
country: body.country,
|
|
1510
|
-
isDefaultBilling: body.isDefaultBilling ?? false,
|
|
1511
|
-
isDefaultShipping: body.isDefaultShipping ?? false,
|
|
1512
|
-
...body.addressLine2 !== void 0 && { addressLine2: body.addressLine2 },
|
|
1513
|
-
...body.company !== void 0 && { company: body.company },
|
|
1514
|
-
...body.phone !== void 0 && { phone: body.phone }
|
|
2511
|
+
await repos.orderHistory.append(tx, {
|
|
2512
|
+
id: uuidv79(),
|
|
2513
|
+
orderId: input.orderId,
|
|
2514
|
+
fromStatus: null,
|
|
2515
|
+
toStatus: "pending",
|
|
2516
|
+
actor: "system:checkout",
|
|
2517
|
+
note: "order draft created",
|
|
2518
|
+
timestamp: now
|
|
1515
2519
|
});
|
|
1516
|
-
|
|
1517
|
-
|
|
1518
|
-
return
|
|
1519
|
-
}
|
|
1520
|
-
}
|
|
1521
|
-
|
|
1522
|
-
|
|
1523
|
-
|
|
1524
|
-
|
|
1525
|
-
|
|
1526
|
-
|
|
1527
|
-
|
|
1528
|
-
|
|
1529
|
-
|
|
1530
|
-
|
|
1531
|
-
|
|
1532
|
-
|
|
1533
|
-
|
|
1534
|
-
|
|
1535
|
-
|
|
1536
|
-
|
|
1537
|
-
|
|
1538
|
-
|
|
1539
|
-
|
|
1540
|
-
|
|
1541
|
-
|
|
1542
|
-
|
|
1543
|
-
|
|
1544
|
-
|
|
1545
|
-
try {
|
|
1546
|
-
return ok({
|
|
1547
|
-
userId: ctx.auth.userId,
|
|
1548
|
-
roles: ctx.auth.roles,
|
|
1549
|
-
storeName: config.store.name,
|
|
1550
|
-
environment: process.env["NODE_ENV"] ?? "development"
|
|
2520
|
+
const fresh = await requireOrder(tx, input.orderId);
|
|
2521
|
+
await publisher.publish(EVT_ORDER_PLACED, { order: fresh });
|
|
2522
|
+
return fresh;
|
|
2523
|
+
});
|
|
2524
|
+
},
|
|
2525
|
+
async getById(id2) {
|
|
2526
|
+
return store.read((tx) => requireOrder(tx, id2));
|
|
2527
|
+
},
|
|
2528
|
+
async getByOrderNumber(orderNumber) {
|
|
2529
|
+
const order = await store.read((tx) => repos.order.findByOrderNumber(tx, orderNumber));
|
|
2530
|
+
if (!order) throw new NotFoundError7("order", orderNumber);
|
|
2531
|
+
return order;
|
|
2532
|
+
},
|
|
2533
|
+
async listByCustomer(customerId) {
|
|
2534
|
+
return store.read((tx) => repos.order.listByCustomer(tx, customerId));
|
|
2535
|
+
},
|
|
2536
|
+
async keyOpens(orderId, key) {
|
|
2537
|
+
if (!isOrderKey(key)) return false;
|
|
2538
|
+
return store.read((tx) => repos.orderAccessKey.opens(tx, orderId, hashOrderKey(key)));
|
|
2539
|
+
},
|
|
2540
|
+
async updateStatus(id2, toStatus, actor, note = "") {
|
|
2541
|
+
return store.transaction(async (tx) => {
|
|
2542
|
+
audit.note("order.updateStatus", [{ type: "order", id: id2 }]);
|
|
2543
|
+
const order = await requireOrder(tx, id2);
|
|
2544
|
+
const fresh = await doTransition(tx, order, toStatus, actor, note);
|
|
2545
|
+
await publisher.publish(EVT_ORDER_STATUS_CHANGED, {
|
|
2546
|
+
orderId: fresh.id,
|
|
2547
|
+
from: order.status,
|
|
2548
|
+
to: fresh.status
|
|
1551
2549
|
});
|
|
1552
|
-
|
|
1553
|
-
|
|
1554
|
-
|
|
1555
|
-
|
|
1556
|
-
|
|
1557
|
-
}
|
|
1558
|
-
|
|
1559
|
-
|
|
1560
|
-
|
|
1561
|
-
|
|
1562
|
-
|
|
1563
|
-
|
|
1564
|
-
|
|
1565
|
-
"/api/admin/dashboard",
|
|
1566
|
-
requireRole("admin", async () => {
|
|
1567
|
-
try {
|
|
1568
|
-
const startOfToday = new Date((/* @__PURE__ */ new Date()).setHours(0, 0, 0, 0));
|
|
1569
|
-
const allOrders = await store.read((tx) => repos.order.list(tx, { limit: 200 }));
|
|
1570
|
-
const todayOrders = allOrders.filter((o) => new Date(o.createdAt) >= startOfToday);
|
|
1571
|
-
const shippedStatuses = /* @__PURE__ */ new Set(["shipped", "delivered"]);
|
|
1572
|
-
const todayOrderCount = todayOrders.length;
|
|
1573
|
-
const todayRevenueMinor = todayOrders.reduce(
|
|
1574
|
-
(sum, o) => sum + o.capturedMinor - o.refundedMinor,
|
|
1575
|
-
0
|
|
2550
|
+
return fresh;
|
|
2551
|
+
});
|
|
2552
|
+
},
|
|
2553
|
+
async markShipped(id2, trackingNumber, carrier, actor) {
|
|
2554
|
+
return store.transaction(async (tx) => {
|
|
2555
|
+
audit.note("order.ship", [{ type: "order", id: id2 }]);
|
|
2556
|
+
const order = await requireOrder(tx, id2);
|
|
2557
|
+
const fresh = await doTransition(
|
|
2558
|
+
tx,
|
|
2559
|
+
order,
|
|
2560
|
+
"shipped",
|
|
2561
|
+
actor,
|
|
2562
|
+
`Shipped via ${carrier}: ${trackingNumber}`
|
|
1576
2563
|
);
|
|
1577
|
-
|
|
1578
|
-
|
|
1579
|
-
|
|
1580
|
-
|
|
1581
|
-
const out = [];
|
|
1582
|
-
for (const product of products) {
|
|
1583
|
-
out.push({ product, variants: await repos.variant.findByProduct(tx, product.id) });
|
|
1584
|
-
}
|
|
1585
|
-
return out;
|
|
2564
|
+
await publisher.publish(EVT_ORDER_SHIPPED, {
|
|
2565
|
+
orderId: fresh.id,
|
|
2566
|
+
trackingNumber,
|
|
2567
|
+
carrier
|
|
1586
2568
|
});
|
|
1587
|
-
|
|
1588
|
-
|
|
1589
|
-
|
|
1590
|
-
|
|
1591
|
-
|
|
1592
|
-
|
|
1593
|
-
|
|
1594
|
-
|
|
1595
|
-
|
|
1596
|
-
|
|
1597
|
-
|
|
1598
|
-
|
|
1599
|
-
|
|
1600
|
-
|
|
1601
|
-
|
|
2569
|
+
return fresh;
|
|
2570
|
+
});
|
|
2571
|
+
},
|
|
2572
|
+
async markDelivered(id2, actor) {
|
|
2573
|
+
return store.transaction(async (tx) => {
|
|
2574
|
+
audit.note("order.markDelivered", [{ type: "order", id: id2 }]);
|
|
2575
|
+
const order = await requireOrder(tx, id2);
|
|
2576
|
+
const fresh = await doTransition(tx, order, "delivered", actor, "Delivered");
|
|
2577
|
+
await publisher.publish(EVT_ORDER_DELIVERED, { orderId: fresh.id });
|
|
2578
|
+
return fresh;
|
|
2579
|
+
});
|
|
2580
|
+
},
|
|
2581
|
+
async cancel(id2, reason, actor) {
|
|
2582
|
+
return store.transaction(async (tx) => {
|
|
2583
|
+
audit.note("order.cancel", [{ type: "order", id: id2 }]);
|
|
2584
|
+
const order = await repos.order.lock(tx, id2);
|
|
2585
|
+
if (!order) throw new NotFoundError7("order", id2);
|
|
2586
|
+
if (order.capturedMinor > 0) {
|
|
2587
|
+
throw new OrderConflictError2(
|
|
2588
|
+
"order.paid",
|
|
2589
|
+
`Order ${order.orderNumber} is paid: refund it instead of cancelling`
|
|
2590
|
+
);
|
|
1602
2591
|
}
|
|
1603
|
-
|
|
1604
|
-
|
|
1605
|
-
|
|
1606
|
-
|
|
1607
|
-
|
|
1608
|
-
|
|
1609
|
-
|
|
1610
|
-
|
|
2592
|
+
assertOrderTransition(order.status, "cancelled");
|
|
2593
|
+
const now = /* @__PURE__ */ new Date();
|
|
2594
|
+
if (!await repos.order.setStatusIf(tx, order.id, order.status, "cancelled", now)) {
|
|
2595
|
+
const current = await requireOrder(tx, order.id);
|
|
2596
|
+
throw new StatusTransitionError2("order", current.status, "cancelled");
|
|
2597
|
+
}
|
|
2598
|
+
await repos.orderHistory.append(tx, {
|
|
2599
|
+
id: uuidv79(),
|
|
2600
|
+
orderId: order.id,
|
|
2601
|
+
fromStatus: order.status,
|
|
2602
|
+
toStatus: "cancelled",
|
|
2603
|
+
actor,
|
|
2604
|
+
note: reason,
|
|
2605
|
+
timestamp: now
|
|
2606
|
+
});
|
|
2607
|
+
const fresh = await requireOrder(tx, order.id);
|
|
2608
|
+
await publisher.publish(EVT_ORDER_CANCELLED, { orderId: fresh.id, reason });
|
|
2609
|
+
return fresh;
|
|
2610
|
+
});
|
|
2611
|
+
},
|
|
2612
|
+
async resendConfirmation(id2) {
|
|
2613
|
+
return store.transaction(async (tx) => {
|
|
2614
|
+
audit.note("order.resendConfirmation", [{ type: "order", id: id2 }]);
|
|
2615
|
+
const order = await requireOrder(tx, id2);
|
|
2616
|
+
if (NO_CONFIRMATION_DUE.has(order.status)) {
|
|
2617
|
+
throw new OrderConflictError2(
|
|
2618
|
+
"order.unpaid",
|
|
2619
|
+
`Order ${order.orderNumber} is ${order.status}: no confirmation is due`,
|
|
2620
|
+
{ context: { status: order.status } }
|
|
2621
|
+
);
|
|
2622
|
+
}
|
|
2623
|
+
await publisher.publish(EVT_ORDER_CONFIRMATION_RESEND_REQUESTED, { orderId: order.id });
|
|
2624
|
+
return order;
|
|
2625
|
+
});
|
|
2626
|
+
},
|
|
2627
|
+
async importOrder(input) {
|
|
2628
|
+
const capturedMinor = input.capturedMinor ?? 0;
|
|
2629
|
+
const refundedMinor = input.refundedMinor ?? 0;
|
|
2630
|
+
if (!(0 <= refundedMinor && refundedMinor <= capturedMinor && capturedMinor <= input.totalMinor) || capturedMinor > 0 !== (input.captureMethod != null)) {
|
|
2631
|
+
throw new ValidationError7("imported payment amounts are inconsistent", {
|
|
2632
|
+
context: { capturedMinor, refundedMinor, totalMinor: input.totalMinor }
|
|
1611
2633
|
});
|
|
1612
|
-
} catch (err) {
|
|
1613
|
-
return renderError(err);
|
|
1614
2634
|
}
|
|
1615
|
-
|
|
1616
|
-
|
|
2635
|
+
return store.transaction(async (tx) => {
|
|
2636
|
+
audit.note("order.import", [{ type: "order", id: input.orderId }]);
|
|
2637
|
+
const sequence = await repos.orderSequence.nextSequence(tx, deps.orderNumberStart);
|
|
2638
|
+
await repos.order.insert(tx, {
|
|
2639
|
+
id: input.orderId,
|
|
2640
|
+
orderNumber: input.orderNumber,
|
|
2641
|
+
sequence,
|
|
2642
|
+
customerId: input.customerId,
|
|
2643
|
+
status: input.status,
|
|
2644
|
+
email: input.email,
|
|
2645
|
+
billingAddress: input.billingAddress,
|
|
2646
|
+
shippingAddress: input.shippingAddress,
|
|
2647
|
+
lineItems: input.lineItems,
|
|
2648
|
+
subtotalMinor: input.subtotalMinor,
|
|
2649
|
+
taxTotalMinor: input.taxTotalMinor,
|
|
2650
|
+
shippingTotalMinor: input.shippingTotalMinor,
|
|
2651
|
+
discountTotalMinor: input.discountTotalMinor,
|
|
2652
|
+
totalMinor: input.totalMinor,
|
|
2653
|
+
currency: input.currency,
|
|
2654
|
+
notes: input.notes ?? "",
|
|
2655
|
+
metadata: input.metadata ?? {},
|
|
2656
|
+
paymentIntentId: input.paymentIntentId ?? null,
|
|
2657
|
+
...input.captureMethod != null && {
|
|
2658
|
+
capture: {
|
|
2659
|
+
amountMinor: capturedMinor,
|
|
2660
|
+
method: input.captureMethod,
|
|
2661
|
+
at: input.createdAt,
|
|
2662
|
+
refundedMinor
|
|
2663
|
+
}
|
|
2664
|
+
},
|
|
2665
|
+
createdAt: input.createdAt,
|
|
2666
|
+
updatedAt: input.createdAt
|
|
2667
|
+
});
|
|
2668
|
+
const fresh = await requireOrder(tx, input.orderId);
|
|
2669
|
+
await publisher.publish(EVT_ORDER_PLACED, { order: fresh });
|
|
2670
|
+
return fresh;
|
|
2671
|
+
});
|
|
2672
|
+
}
|
|
2673
|
+
};
|
|
1617
2674
|
}
|
|
1618
2675
|
|
|
1619
|
-
// src/
|
|
1620
|
-
import {
|
|
1621
|
-
OrderConflictError as OrderConflictError3,
|
|
1622
|
-
canTransitionOrder as canTransitionOrder2
|
|
1623
|
-
} from "@nymbalhq/types";
|
|
1624
|
-
|
|
1625
|
-
// src/services/refund-service.ts
|
|
1626
|
-
import { v7 as uuidv73 } from "uuid";
|
|
2676
|
+
// src/services/inventory-service.ts
|
|
2677
|
+
import { v7 as uuidv710 } from "uuid";
|
|
1627
2678
|
import {
|
|
1628
|
-
|
|
1629
|
-
|
|
1630
|
-
|
|
1631
|
-
|
|
1632
|
-
|
|
1633
|
-
|
|
1634
|
-
|
|
1635
|
-
|
|
1636
|
-
|
|
1637
|
-
paymentState,
|
|
1638
|
-
refundableMinor
|
|
2679
|
+
AdapterError as AdapterError2,
|
|
2680
|
+
NotFoundError as NotFoundError8,
|
|
2681
|
+
ValidationError as ValidationError8,
|
|
2682
|
+
EVT_INVENTORY_CHANGED,
|
|
2683
|
+
EVT_INVENTORY_RESERVED,
|
|
2684
|
+
EVT_INVENTORY_RELEASED,
|
|
2685
|
+
EVT_INVENTORY_LOW_STOCK,
|
|
2686
|
+
EVT_INVENTORY_OUT_OF_STOCK,
|
|
2687
|
+
EVT_PRODUCT_RESTOCKED
|
|
1639
2688
|
} from "@nymbalhq/types";
|
|
1640
|
-
|
|
1641
|
-
|
|
1642
|
-
|
|
1643
|
-
|
|
1644
|
-
const format = new Intl.NumberFormat("en-GB", { style: "currency", currency: code });
|
|
1645
|
-
const digits = format.resolvedOptions().maximumFractionDigits ?? 2;
|
|
1646
|
-
return format.format(amountMinor / 10 ** digits);
|
|
2689
|
+
function classifyStock(stock, threshold) {
|
|
2690
|
+
if (stock <= 0) return "out_of_stock";
|
|
2691
|
+
if (stock <= threshold) return "low_stock";
|
|
2692
|
+
return "in_stock";
|
|
1647
2693
|
}
|
|
1648
|
-
|
|
1649
|
-
|
|
1650
|
-
|
|
1651
|
-
function
|
|
2694
|
+
function createInventoryService(deps) {
|
|
2695
|
+
const { store, repos, publisher, logger } = deps;
|
|
2696
|
+
const defaultTtl = deps.defaultReservationTtlSeconds ?? 15 * 60;
|
|
2697
|
+
async function emitThresholdEvents(variantId, newQty, threshold) {
|
|
2698
|
+
if (newQty <= 0) {
|
|
2699
|
+
await publisher.publish(EVT_INVENTORY_OUT_OF_STOCK, { variantId });
|
|
2700
|
+
} else if (newQty <= threshold) {
|
|
2701
|
+
await publisher.publish(EVT_INVENTORY_LOW_STOCK, {
|
|
2702
|
+
variantId,
|
|
2703
|
+
currentQty: newQty,
|
|
2704
|
+
threshold
|
|
2705
|
+
});
|
|
2706
|
+
}
|
|
2707
|
+
}
|
|
2708
|
+
async function emitRestocked(variantId, previousQty, newQty, productIdOf) {
|
|
2709
|
+
if (previousQty <= 0 && newQty > 0) {
|
|
2710
|
+
const productId = await productIdOf();
|
|
2711
|
+
await publisher.publish(EVT_PRODUCT_RESTOCKED, { productId, variantId, previousQty, newQty });
|
|
2712
|
+
}
|
|
2713
|
+
}
|
|
2714
|
+
async function take(variantId, qty, orderRef, ttlSeconds) {
|
|
2715
|
+
if (qty <= 0) throw new ValidationError8(`Reservation qty must be positive, got ${qty}`);
|
|
2716
|
+
return store.transaction(async (tx) => {
|
|
2717
|
+
audit.note("inventory.reserve", [{ type: "variant", id: variantId }]);
|
|
2718
|
+
const variant = await repos.variant.findById(tx, variantId);
|
|
2719
|
+
if (!variant) throw new NotFoundError8("variant", variantId);
|
|
2720
|
+
const now = /* @__PURE__ */ new Date();
|
|
2721
|
+
const remaining = await repos.variant.decrementStock(tx, variant.id, qty, now);
|
|
2722
|
+
if (remaining === null) return { available: variant.stock };
|
|
2723
|
+
const expiresAt = new Date(now.getTime() + (ttlSeconds ?? defaultTtl) * 1e3);
|
|
2724
|
+
const reservationId = uuidv710();
|
|
2725
|
+
await repos.inventoryReservation.insert(tx, {
|
|
2726
|
+
reservationId,
|
|
2727
|
+
variantId: variant.id,
|
|
2728
|
+
qty,
|
|
2729
|
+
orderRef,
|
|
2730
|
+
expiresAt,
|
|
2731
|
+
createdAt: now
|
|
2732
|
+
});
|
|
2733
|
+
await publisher.publish(EVT_INVENTORY_RESERVED, {
|
|
2734
|
+
variantId: variant.id,
|
|
2735
|
+
qty,
|
|
2736
|
+
reservationId,
|
|
2737
|
+
expiresAt: expiresAt.toISOString()
|
|
2738
|
+
});
|
|
2739
|
+
await publisher.publish(EVT_INVENTORY_CHANGED, {
|
|
2740
|
+
variantId: variant.id,
|
|
2741
|
+
previousQty: remaining + qty,
|
|
2742
|
+
newQty: remaining,
|
|
2743
|
+
reason: "manual"
|
|
2744
|
+
});
|
|
2745
|
+
await emitThresholdEvents(variant.id, remaining, variant.lowStockThreshold);
|
|
2746
|
+
return { reservationId, expiresAt: expiresAt.toISOString() };
|
|
2747
|
+
});
|
|
2748
|
+
}
|
|
1652
2749
|
return {
|
|
1653
|
-
|
|
1654
|
-
|
|
1655
|
-
|
|
2750
|
+
async adjustStock(variantId, delta, reason, actor) {
|
|
2751
|
+
return store.transaction(async (tx) => {
|
|
2752
|
+
audit.note("inventory.adjust", [{ type: "variant", id: variantId }]);
|
|
2753
|
+
const variant = await repos.variant.findById(tx, variantId);
|
|
2754
|
+
if (!variant) throw new NotFoundError8("variant", variantId);
|
|
2755
|
+
const now = /* @__PURE__ */ new Date();
|
|
2756
|
+
const newQty = delta < 0 ? await repos.variant.decrementStock(tx, variant.id, -delta, now) : await repos.variant.incrementStock(tx, variant.id, delta, now);
|
|
2757
|
+
if (newQty === null) {
|
|
2758
|
+
throw new ValidationError8(`Cannot reduce stock below zero (variant ${variantId})`, {
|
|
2759
|
+
context: { variantId, stock: variant.stock, delta }
|
|
2760
|
+
});
|
|
2761
|
+
}
|
|
2762
|
+
const previousQty = newQty - delta;
|
|
2763
|
+
await repos.stockAdjustment.append(tx, {
|
|
2764
|
+
id: uuidv710(),
|
|
2765
|
+
variantId: variant.id,
|
|
2766
|
+
adjustment: delta,
|
|
2767
|
+
reason,
|
|
2768
|
+
actor,
|
|
2769
|
+
previousQty,
|
|
2770
|
+
newQty,
|
|
2771
|
+
timestamp: now
|
|
2772
|
+
});
|
|
2773
|
+
await publisher.publish(EVT_INVENTORY_CHANGED, {
|
|
2774
|
+
variantId: variant.id,
|
|
2775
|
+
previousQty,
|
|
2776
|
+
newQty,
|
|
2777
|
+
reason
|
|
2778
|
+
});
|
|
2779
|
+
await emitRestocked(variant.id, previousQty, newQty, async () => variant.productId);
|
|
2780
|
+
await emitThresholdEvents(variant.id, newQty, variant.lowStockThreshold);
|
|
2781
|
+
logger.debug({ variantId, delta, newQty, reason }, "stock adjusted");
|
|
2782
|
+
return { newQty };
|
|
2783
|
+
});
|
|
2784
|
+
},
|
|
2785
|
+
async reserveStock(variantId, qty, orderRef = null, ttlSeconds) {
|
|
2786
|
+
const taken = await take(variantId, qty, orderRef, ttlSeconds);
|
|
2787
|
+
if ("available" in taken) {
|
|
2788
|
+
throw new AdapterError2(
|
|
2789
|
+
"inventory.insufficient",
|
|
2790
|
+
`Insufficient stock for variant ${variantId}`,
|
|
2791
|
+
{
|
|
2792
|
+
context: { variantId, requested: qty, available: taken.available }
|
|
2793
|
+
}
|
|
2794
|
+
);
|
|
2795
|
+
}
|
|
2796
|
+
return taken;
|
|
2797
|
+
},
|
|
2798
|
+
async tryReserveStock(variantId, qty, orderRef = null, ttlSeconds) {
|
|
2799
|
+
const taken = await take(variantId, qty, orderRef, ttlSeconds);
|
|
2800
|
+
return "available" in taken ? null : taken;
|
|
2801
|
+
},
|
|
2802
|
+
async releaseReservation(reservationId, reason) {
|
|
2803
|
+
await store.transaction(async (tx) => {
|
|
2804
|
+
const reservation = await repos.inventoryReservation.deleteById(tx, reservationId);
|
|
2805
|
+
if (!reservation) {
|
|
2806
|
+
logger.debug(
|
|
2807
|
+
{ reservationId },
|
|
2808
|
+
"reservation already released, committed or never existed"
|
|
2809
|
+
);
|
|
2810
|
+
return;
|
|
2811
|
+
}
|
|
2812
|
+
audit.note("inventory.release", [{ type: "variant", id: reservation.variantId }]);
|
|
2813
|
+
const now = /* @__PURE__ */ new Date();
|
|
2814
|
+
const newQty = await repos.variant.incrementStock(
|
|
2815
|
+
tx,
|
|
2816
|
+
reservation.variantId,
|
|
2817
|
+
reservation.qty,
|
|
2818
|
+
now
|
|
2819
|
+
);
|
|
2820
|
+
if (newQty !== null) {
|
|
2821
|
+
const previousQty = newQty - reservation.qty;
|
|
2822
|
+
await repos.stockAdjustment.append(tx, {
|
|
2823
|
+
id: uuidv710(),
|
|
2824
|
+
variantId: reservation.variantId,
|
|
2825
|
+
adjustment: reservation.qty,
|
|
2826
|
+
reason: "reservation-release",
|
|
2827
|
+
actor: `system:release:${reason}`,
|
|
2828
|
+
previousQty,
|
|
2829
|
+
newQty,
|
|
2830
|
+
timestamp: now
|
|
2831
|
+
});
|
|
2832
|
+
await publisher.publish(EVT_INVENTORY_CHANGED, {
|
|
2833
|
+
variantId: reservation.variantId,
|
|
2834
|
+
previousQty,
|
|
2835
|
+
newQty,
|
|
2836
|
+
reason: "reservation-release"
|
|
2837
|
+
});
|
|
2838
|
+
await emitRestocked(reservation.variantId, previousQty, newQty, async () => {
|
|
2839
|
+
const variant = await repos.variant.findById(tx, reservation.variantId);
|
|
2840
|
+
return variant.productId;
|
|
2841
|
+
});
|
|
2842
|
+
}
|
|
2843
|
+
await publisher.publish(EVT_INVENTORY_RELEASED, {
|
|
2844
|
+
variantId: reservation.variantId,
|
|
2845
|
+
qty: reservation.qty,
|
|
2846
|
+
reservationId: reservation.reservationId,
|
|
2847
|
+
reason
|
|
2848
|
+
});
|
|
2849
|
+
});
|
|
2850
|
+
},
|
|
2851
|
+
async commitReservation(reservationId, actor) {
|
|
2852
|
+
await store.transaction(async (tx) => {
|
|
2853
|
+
const reservation = await repos.inventoryReservation.deleteById(tx, reservationId);
|
|
2854
|
+
if (!reservation) throw new NotFoundError8("reservation", reservationId);
|
|
2855
|
+
audit.note("inventory.commit", [{ type: "variant", id: reservation.variantId }]);
|
|
2856
|
+
const variant = await repos.variant.findById(tx, reservation.variantId);
|
|
2857
|
+
if (!variant) throw new NotFoundError8("variant", reservation.variantId);
|
|
2858
|
+
await repos.stockAdjustment.append(tx, {
|
|
2859
|
+
id: uuidv710(),
|
|
2860
|
+
variantId: variant.id,
|
|
2861
|
+
adjustment: -reservation.qty,
|
|
2862
|
+
reason: "reservation-commit",
|
|
2863
|
+
actor,
|
|
2864
|
+
previousQty: variant.stock + reservation.qty,
|
|
2865
|
+
newQty: variant.stock,
|
|
2866
|
+
timestamp: /* @__PURE__ */ new Date()
|
|
2867
|
+
});
|
|
2868
|
+
await publisher.publish(EVT_INVENTORY_RELEASED, {
|
|
2869
|
+
variantId: reservation.variantId,
|
|
2870
|
+
qty: reservation.qty,
|
|
2871
|
+
reservationId: reservation.reservationId,
|
|
2872
|
+
reason: "committed"
|
|
2873
|
+
});
|
|
2874
|
+
});
|
|
2875
|
+
},
|
|
2876
|
+
async getStockStatus(variantId) {
|
|
2877
|
+
const variant = await store.read((tx) => repos.variant.findById(tx, variantId));
|
|
2878
|
+
if (!variant) throw new NotFoundError8("variant", variantId);
|
|
2879
|
+
return {
|
|
2880
|
+
stock: variant.stock,
|
|
2881
|
+
threshold: variant.lowStockThreshold,
|
|
2882
|
+
status: classifyStock(variant.stock, variant.lowStockThreshold)
|
|
2883
|
+
};
|
|
2884
|
+
}
|
|
2885
|
+
};
|
|
2886
|
+
}
|
|
2887
|
+
|
|
2888
|
+
// src/services/checkout-service.ts
|
|
2889
|
+
import { v5 as uuidv5, v7 as uuidv712 } from "uuid";
|
|
2890
|
+
import {
|
|
2891
|
+
CheckoutError as CheckoutError2,
|
|
2892
|
+
EVT_CART_CONVERTED,
|
|
2893
|
+
EVT_CART_UPDATED as EVT_CART_UPDATED2,
|
|
2894
|
+
EVT_ORDER_PAID,
|
|
2895
|
+
EVT_PAYMENT_CAPTURED,
|
|
2896
|
+
EVT_PAYMENT_FAILED,
|
|
2897
|
+
EVT_PAYMENT_INTENT_CREATED,
|
|
2898
|
+
EVT_PAYMENT_REFUNDED as EVT_PAYMENT_REFUNDED2,
|
|
2899
|
+
NotFoundError as NotFoundError10,
|
|
2900
|
+
OrderConflictError as OrderConflictError4,
|
|
2901
|
+
PaymentError as PaymentError2,
|
|
2902
|
+
StatusTransitionError as StatusTransitionError4
|
|
2903
|
+
} from "@nymbalhq/types";
|
|
2904
|
+
|
|
2905
|
+
// src/money.ts
|
|
2906
|
+
function formatMoney(amountMinor, currency) {
|
|
2907
|
+
const code = currency.toUpperCase();
|
|
2908
|
+
const format = new Intl.NumberFormat("en-GB", { style: "currency", currency: code });
|
|
2909
|
+
const digits = format.resolvedOptions().maximumFractionDigits ?? 2;
|
|
2910
|
+
return format.format(amountMinor / 10 ** digits);
|
|
2911
|
+
}
|
|
2912
|
+
|
|
2913
|
+
// src/services/order-correlation.ts
|
|
2914
|
+
function inOrderScope(order, fn) {
|
|
2915
|
+
const id2 = order?.metadata?.correlationId;
|
|
2916
|
+
return typeof id2 === "string" ? runWithCorrelation(id2, fn) : fn();
|
|
2917
|
+
}
|
|
2918
|
+
|
|
2919
|
+
// src/services/refund-service.ts
|
|
2920
|
+
import { v7 as uuidv711 } from "uuid";
|
|
2921
|
+
import {
|
|
2922
|
+
EVT_ORDER_PARTIALLY_REFUNDED,
|
|
2923
|
+
EVT_ORDER_REFUNDED,
|
|
2924
|
+
EVT_PAYMENT_REFUNDED,
|
|
2925
|
+
NotFoundError as NotFoundError9,
|
|
2926
|
+
OrderConflictError as OrderConflictError3,
|
|
2927
|
+
PaymentError,
|
|
2928
|
+
StatusTransitionError as StatusTransitionError3,
|
|
2929
|
+
ValidationError as ValidationError9,
|
|
2930
|
+
canTransitionOrder,
|
|
2931
|
+
paymentState as paymentState2,
|
|
2932
|
+
refundableMinor
|
|
2933
|
+
} from "@nymbalhq/types";
|
|
2934
|
+
var PROVIDER_REFUND_REASON = "requested_by_customer";
|
|
2935
|
+
function orderPayment(order, refunds) {
|
|
2936
|
+
return {
|
|
2937
|
+
state: paymentState2(order),
|
|
2938
|
+
capturedMinor: order.capturedMinor,
|
|
2939
|
+
refundedMinor: order.refundedMinor,
|
|
1656
2940
|
refundableMinor: refundableMinor(order, refunds),
|
|
1657
2941
|
currency: order.currency,
|
|
1658
2942
|
refunds
|
|
@@ -1676,12 +2960,12 @@ function createRefundService(deps) {
|
|
|
1676
2960
|
async function hold2(tx, input) {
|
|
1677
2961
|
audit.note("order.refund", [{ type: "order", id: input.orderId }]);
|
|
1678
2962
|
const order = await repos.order.lock(tx, input.orderId);
|
|
1679
|
-
if (!order) throw new
|
|
2963
|
+
if (!order) throw new NotFoundError9("order", input.orderId);
|
|
1680
2964
|
if (input.requestId !== void 0) {
|
|
1681
2965
|
const earlier = await repos.orderRefund.findByRequestId(tx, order.id, input.requestId);
|
|
1682
2966
|
if (earlier !== null) {
|
|
1683
2967
|
if (earlier.amountMinor !== input.amountMinor) {
|
|
1684
|
-
throw new
|
|
2968
|
+
throw new OrderConflictError3(
|
|
1685
2969
|
"refund.request_reused",
|
|
1686
2970
|
`Request ${input.requestId} already refunded ${formatMoney(earlier.amountMinor, earlier.currency)} on order ${order.orderNumber}`,
|
|
1687
2971
|
{
|
|
@@ -1694,24 +2978,24 @@ function createRefundService(deps) {
|
|
|
1694
2978
|
}
|
|
1695
2979
|
}
|
|
1696
2980
|
if (order.capturedMinor <= 0 || order.captureMethod === "provider" && !order.paymentIntentId) {
|
|
1697
|
-
throw new
|
|
2981
|
+
throw new OrderConflictError3(
|
|
1698
2982
|
"refund.not_captured",
|
|
1699
2983
|
`Order ${order.orderNumber} has no captured payment to refund`
|
|
1700
2984
|
);
|
|
1701
2985
|
}
|
|
1702
2986
|
const refundable = refundableMinor(order, await repos.orderRefund.listByOrder(tx, order.id));
|
|
1703
2987
|
if (input.amountMinor > refundable) {
|
|
1704
|
-
throw new
|
|
2988
|
+
throw new OrderConflictError3(
|
|
1705
2989
|
"refund.exceeds_captured",
|
|
1706
2990
|
`Refund of ${formatMoney(input.amountMinor, order.currency)} exceeds the ${formatMoney(refundable, order.currency)} refundable on order ${order.orderNumber}`,
|
|
1707
2991
|
{ context: { amountMinor: input.amountMinor, refundableMinor: refundable } }
|
|
1708
2992
|
);
|
|
1709
2993
|
}
|
|
1710
2994
|
if (!canTransitionOrder(order.status, "refunded")) {
|
|
1711
|
-
throw new
|
|
2995
|
+
throw new StatusTransitionError3("order", order.status, "refunded");
|
|
1712
2996
|
}
|
|
1713
2997
|
const row = {
|
|
1714
|
-
id:
|
|
2998
|
+
id: uuidv711(),
|
|
1715
2999
|
orderId: order.id,
|
|
1716
3000
|
amountMinor: input.amountMinor,
|
|
1717
3001
|
currency: order.currency,
|
|
@@ -1756,7 +3040,7 @@ function createRefundService(deps) {
|
|
|
1756
3040
|
}
|
|
1757
3041
|
async function settle(tx, orderId, row, settlement) {
|
|
1758
3042
|
const order = await repos.order.lock(tx, orderId);
|
|
1759
|
-
if (!order) throw new
|
|
3043
|
+
if (!order) throw new NotFoundError9("order", orderId);
|
|
1760
3044
|
await repos.orderRefund.settle(tx, row.id, {
|
|
1761
3045
|
status: settlement.status,
|
|
1762
3046
|
providerRefundId: settlement.providerRefundId
|
|
@@ -1771,7 +3055,7 @@ function createRefundService(deps) {
|
|
|
1771
3055
|
async function recordSucceeded(tx, order, refundedMinor, refund, now) {
|
|
1772
3056
|
const full = refundedMinor >= order.capturedMinor;
|
|
1773
3057
|
const target = full ? "refunded" : "partially_refunded";
|
|
1774
|
-
const note =
|
|
3058
|
+
const note = `${REFUND_NOTE_PREFIX}${formatMoney(refund.amountMinor, refund.currency)}${refund.reason ? `: ${refund.reason}` : ""}`;
|
|
1775
3059
|
let toStatus = order.status;
|
|
1776
3060
|
if (order.status !== target && canTransitionOrder(order.status, target)) {
|
|
1777
3061
|
await repos.order.setStatus(tx, order.id, target, now);
|
|
@@ -1783,7 +3067,7 @@ function createRefundService(deps) {
|
|
|
1783
3067
|
);
|
|
1784
3068
|
}
|
|
1785
3069
|
await repos.orderHistory.append(tx, {
|
|
1786
|
-
id:
|
|
3070
|
+
id: uuidv711(),
|
|
1787
3071
|
orderId: order.id,
|
|
1788
3072
|
fromStatus: order.status,
|
|
1789
3073
|
toStatus,
|
|
@@ -1814,19 +3098,1333 @@ function createRefundService(deps) {
|
|
|
1814
3098
|
async refund(input) {
|
|
1815
3099
|
audit.note("order.refund", [{ type: "order", id: input.orderId }]);
|
|
1816
3100
|
if (!Number.isInteger(input.amountMinor) || input.amountMinor <= 0) {
|
|
1817
|
-
throw new
|
|
3101
|
+
throw new ValidationError9("amountMinor must be a positive whole number of minor units", {
|
|
1818
3102
|
context: { amountMinor: input.amountMinor }
|
|
1819
3103
|
});
|
|
1820
3104
|
}
|
|
1821
|
-
const held = await store.transaction((tx) => hold2(tx, input));
|
|
1822
|
-
if ("repeat" in held) return held.repeat;
|
|
1823
|
-
const { order, row } = held;
|
|
1824
|
-
const settlement = await moveMoney(order, row);
|
|
1825
|
-
return store.transaction((tx) => settle(tx, order.id, row, settlement));
|
|
1826
|
-
}
|
|
1827
|
-
};
|
|
3105
|
+
const held = await store.transaction((tx) => hold2(tx, input));
|
|
3106
|
+
if ("repeat" in held) return held.repeat;
|
|
3107
|
+
const { order, row } = held;
|
|
3108
|
+
const settlement = await moveMoney(order, row);
|
|
3109
|
+
return store.transaction((tx) => settle(tx, order.id, row, settlement));
|
|
3110
|
+
}
|
|
3111
|
+
};
|
|
3112
|
+
}
|
|
3113
|
+
|
|
3114
|
+
// src/services/checkout-service.ts
|
|
3115
|
+
var StockUnavailable = class extends Error {
|
|
3116
|
+
constructor(variantId) {
|
|
3117
|
+
super(`stock unavailable for variant ${variantId}`);
|
|
3118
|
+
this.variantId = variantId;
|
|
3119
|
+
}
|
|
3120
|
+
variantId;
|
|
3121
|
+
};
|
|
3122
|
+
var NoLongerPending = class extends Error {
|
|
3123
|
+
};
|
|
3124
|
+
var PROVIDER_CAPTURE = {
|
|
3125
|
+
method: "provider",
|
|
3126
|
+
actor: "system:checkout",
|
|
3127
|
+
note: "payment captured"
|
|
3128
|
+
};
|
|
3129
|
+
var FINALIZE_ACTOR = "system:checkout-finalize";
|
|
3130
|
+
var CANCEL_ACTOR = "system:checkout-cancel";
|
|
3131
|
+
var DUPLICATE_CAPTURE = "duplicate_capture_refunded";
|
|
3132
|
+
var DUPLICATE_CAPTURE_HANDLER = "checkout:duplicate-capture";
|
|
3133
|
+
var CAPTURE_REFUND_NAMESPACE = "49e623d3-5784-4331-80e9-6f951d97f7c0";
|
|
3134
|
+
var SUPERSEDE_ATTEMPTS = 3;
|
|
3135
|
+
var ABANDON_AFTER_MS = 12e4;
|
|
3136
|
+
function outcomeOf(status) {
|
|
3137
|
+
if (status === "succeeded") return "succeeded";
|
|
3138
|
+
if (status === "failed" || status === "cancelled") return "failed";
|
|
3139
|
+
return "requires_action";
|
|
3140
|
+
}
|
|
3141
|
+
function sameLines(order, cart) {
|
|
3142
|
+
if (order.totalMinor !== cart.subtotalMinor || order.currency !== cart.currency) return false;
|
|
3143
|
+
if (order.lineItems.length !== cart.items.length) return false;
|
|
3144
|
+
return cart.items.every((item, i) => {
|
|
3145
|
+
const line = order.lineItems[i];
|
|
3146
|
+
return line?.variantId === item.variantId && line.qty === item.qty && line.unitPriceMinor === item.priceMinor;
|
|
3147
|
+
});
|
|
3148
|
+
}
|
|
3149
|
+
function createCheckoutService(deps) {
|
|
3150
|
+
const { store, repos, publisher, logger, cart, orders, inventory, payments, currency } = deps;
|
|
3151
|
+
async function mintKey(tx, orderId) {
|
|
3152
|
+
const { key, hash } = mintOrderKey();
|
|
3153
|
+
await repos.orderAccessKey.insert(tx, {
|
|
3154
|
+
id: uuidv712(),
|
|
3155
|
+
orderId,
|
|
3156
|
+
keyHash: hash,
|
|
3157
|
+
purpose: "checkout",
|
|
3158
|
+
createdAt: /* @__PURE__ */ new Date()
|
|
3159
|
+
});
|
|
3160
|
+
return key;
|
|
3161
|
+
}
|
|
3162
|
+
async function withOrderKey(err) {
|
|
3163
|
+
if (!(err instanceof CheckoutError2)) return err;
|
|
3164
|
+
const orderNumber = err.context["orderNumber"];
|
|
3165
|
+
if (typeof orderNumber !== "string") return err;
|
|
3166
|
+
const order = await store.read((tx) => repos.order.findByOrderNumber(tx, orderNumber));
|
|
3167
|
+
if (order === null) return err;
|
|
3168
|
+
err.context["orderKey"] = await store.transaction((tx) => mintKey(tx, order.id));
|
|
3169
|
+
return err;
|
|
3170
|
+
}
|
|
3171
|
+
async function cartEmpty(token) {
|
|
3172
|
+
const converted = await store.read((tx) => repos.order.findLastConvertedByCartToken(tx, token));
|
|
3173
|
+
return new CheckoutError2(
|
|
3174
|
+
"cart_empty",
|
|
3175
|
+
"Cart has no items",
|
|
3176
|
+
converted ? { context: { orderNumber: converted.orderNumber } } : {}
|
|
3177
|
+
);
|
|
3178
|
+
}
|
|
3179
|
+
async function loadValidCart(token) {
|
|
3180
|
+
const c = await cart.get(token);
|
|
3181
|
+
if (!c) throw new NotFoundError10("cart", token);
|
|
3182
|
+
if (!c.items.length) throw await cartEmpty(token);
|
|
3183
|
+
if (c.currency !== currency) {
|
|
3184
|
+
throw new CheckoutError2(
|
|
3185
|
+
"cart_empty",
|
|
3186
|
+
`Cart currency ${c.currency} does not match store currency ${currency}`
|
|
3187
|
+
);
|
|
3188
|
+
}
|
|
3189
|
+
return c;
|
|
3190
|
+
}
|
|
3191
|
+
async function settled(tx, paymentIntentId, order, paid) {
|
|
3192
|
+
if (order === null) return recordOutcome(tx, paymentIntentId, null, "no_order");
|
|
3193
|
+
if (order.captureMethod === "manual" || order.captureMethod === "import") {
|
|
3194
|
+
return refundDuplicateCapture(tx, paymentIntentId, paid, order);
|
|
3195
|
+
}
|
|
3196
|
+
if (order.status === "confirmed") return { orderNumber: order.orderNumber, finalized: true };
|
|
3197
|
+
if (order.status === "cancelled") {
|
|
3198
|
+
if (order.capturedMinor === 0) await refundCancelledCapture(paymentIntentId, paid, order);
|
|
3199
|
+
return recordOutcome(tx, paymentIntentId, order, "order_cancelled_refunded");
|
|
3200
|
+
}
|
|
3201
|
+
return recordOutcome(tx, paymentIntentId, order, `order_not_pending: ${order.status}`);
|
|
3202
|
+
}
|
|
3203
|
+
async function recordOutcome(tx, paymentIntentId, order, reason, detail) {
|
|
3204
|
+
await publisher.publish(EVT_PAYMENT_FAILED, {
|
|
3205
|
+
paymentId: paymentIntentId,
|
|
3206
|
+
orderId: order?.id ?? "",
|
|
3207
|
+
reason
|
|
3208
|
+
});
|
|
3209
|
+
if (order !== null) {
|
|
3210
|
+
audit.note("payment.recordOutcome", [{ type: "order", id: order.id }]);
|
|
3211
|
+
await repos.orderHistory.append(tx, {
|
|
3212
|
+
id: uuidv712(),
|
|
3213
|
+
orderId: order.id,
|
|
3214
|
+
fromStatus: order.status,
|
|
3215
|
+
toStatus: order.status,
|
|
3216
|
+
actor: FINALIZE_ACTOR,
|
|
3217
|
+
note: `captured payment not applied: ${reason}${detail === void 0 ? "" : ` (${detail})`}`,
|
|
3218
|
+
timestamp: /* @__PURE__ */ new Date()
|
|
3219
|
+
});
|
|
3220
|
+
}
|
|
3221
|
+
logger.warn({ paymentIntentId, orderId: order?.id, reason }, "captured payment not applied");
|
|
3222
|
+
return { orderNumber: order?.orderNumber ?? null, finalized: false, reason };
|
|
3223
|
+
}
|
|
3224
|
+
async function reservationFor(tx, order, reservationId, index) {
|
|
3225
|
+
const held = await repos.inventoryReservation.findById(tx, reservationId);
|
|
3226
|
+
if (held !== null) return reservationId;
|
|
3227
|
+
const line = order.lineItems[index];
|
|
3228
|
+
if (line === void 0) {
|
|
3229
|
+
throw new CheckoutError2(
|
|
3230
|
+
"finalize_failed",
|
|
3231
|
+
`Order ${order.id} has no line for reservation ${reservationId}`
|
|
3232
|
+
);
|
|
3233
|
+
}
|
|
3234
|
+
const retaken = await inventory.tryReserveStock(line.variantId, line.qty, order.id).catch((err) => {
|
|
3235
|
+
if (err instanceof NotFoundError10) return null;
|
|
3236
|
+
throw err;
|
|
3237
|
+
});
|
|
3238
|
+
if (retaken === null) throw new StockUnavailable(line.variantId);
|
|
3239
|
+
return retaken.reservationId;
|
|
3240
|
+
}
|
|
3241
|
+
async function refundCapture(paymentIntentId, paid, currency2, key, context2) {
|
|
3242
|
+
try {
|
|
3243
|
+
const answer = await payments.refund(
|
|
3244
|
+
paymentIntentId,
|
|
3245
|
+
paid.amountMinor,
|
|
3246
|
+
PROVIDER_REFUND_REASON,
|
|
3247
|
+
{
|
|
3248
|
+
idempotencyKey: key,
|
|
3249
|
+
currency: currency2
|
|
3250
|
+
}
|
|
3251
|
+
);
|
|
3252
|
+
const settlement = settlementOf(answer, { amountMinor: paid.amountMinor, currency: currency2 });
|
|
3253
|
+
if (settlement.mismatch) {
|
|
3254
|
+
logger.error(
|
|
3255
|
+
{ ...context2, answer: { amountMinor: answer.amountMinor, currency: answer.currency } },
|
|
3256
|
+
"provider refund answer differs from the capture; left pending"
|
|
3257
|
+
);
|
|
3258
|
+
}
|
|
3259
|
+
return settlement;
|
|
3260
|
+
} catch (err) {
|
|
3261
|
+
if (err instanceof PaymentError2 && err.code === "payment.refund_rejected") {
|
|
3262
|
+
logger.error({ ...context2, err }, "provider refused the refund of a capture");
|
|
3263
|
+
return { status: "failed", providerRefundId: null, mismatch: false };
|
|
3264
|
+
}
|
|
3265
|
+
logger.error(
|
|
3266
|
+
{ ...context2, err },
|
|
3267
|
+
"capture refund outcome unknown; left pending until reconciled"
|
|
3268
|
+
);
|
|
3269
|
+
return { status: "pending", providerRefundId: null, mismatch: false };
|
|
3270
|
+
}
|
|
3271
|
+
}
|
|
3272
|
+
async function refundCancelledCapture(paymentIntentId, paid, order) {
|
|
3273
|
+
const refundId = uuidv5(`cancelled-capture:${paymentIntentId}`, CAPTURE_REFUND_NAMESPACE);
|
|
3274
|
+
const held = await store.transaction(async (tx) => {
|
|
3275
|
+
audit.note("payment.refundCapture", [{ type: "order", id: order.id }]);
|
|
3276
|
+
const locked = await repos.order.lock(tx, order.id);
|
|
3277
|
+
if (locked === null || locked.capturedMinor > 0) return false;
|
|
3278
|
+
const now = /* @__PURE__ */ new Date();
|
|
3279
|
+
await repos.order.recordCapture(tx, order.id, {
|
|
3280
|
+
amountMinor: paid.amountMinor,
|
|
3281
|
+
method: "provider",
|
|
3282
|
+
at: now
|
|
3283
|
+
});
|
|
3284
|
+
await repos.orderRefund.insert(tx, {
|
|
3285
|
+
id: refundId,
|
|
3286
|
+
orderId: order.id,
|
|
3287
|
+
amountMinor: paid.amountMinor,
|
|
3288
|
+
currency: order.currency,
|
|
3289
|
+
providerRefundId: null,
|
|
3290
|
+
status: "pending",
|
|
3291
|
+
reason: "captured for a cancelled order",
|
|
3292
|
+
actor: "system:checkout",
|
|
3293
|
+
createdAt: now
|
|
3294
|
+
});
|
|
3295
|
+
await publisher.publish(EVT_PAYMENT_CAPTURED, {
|
|
3296
|
+
paymentId: paymentIntentId,
|
|
3297
|
+
orderId: order.id,
|
|
3298
|
+
amountMinor: paid.amountMinor,
|
|
3299
|
+
currency: order.currency
|
|
3300
|
+
});
|
|
3301
|
+
return true;
|
|
3302
|
+
});
|
|
3303
|
+
if (!held) return;
|
|
3304
|
+
const settlement = await refundCapture(paymentIntentId, paid, order.currency, refundId, {
|
|
3305
|
+
orderId: order.id,
|
|
3306
|
+
refundId
|
|
3307
|
+
});
|
|
3308
|
+
if (settlement.status === "pending") return;
|
|
3309
|
+
await store.transaction(async (tx) => {
|
|
3310
|
+
await repos.order.lock(tx, order.id);
|
|
3311
|
+
await repos.orderRefund.settle(tx, refundId, {
|
|
3312
|
+
status: settlement.status,
|
|
3313
|
+
providerRefundId: settlement.providerRefundId
|
|
3314
|
+
});
|
|
3315
|
+
await refreshRefunded(repos, tx, order.id, /* @__PURE__ */ new Date());
|
|
3316
|
+
if (settlement.status === "succeeded") {
|
|
3317
|
+
await publisher.publish(EVT_PAYMENT_REFUNDED2, {
|
|
3318
|
+
paymentId: paymentIntentId,
|
|
3319
|
+
orderId: order.id,
|
|
3320
|
+
refundId,
|
|
3321
|
+
amountMinor: paid.amountMinor,
|
|
3322
|
+
currency: order.currency
|
|
3323
|
+
});
|
|
3324
|
+
}
|
|
3325
|
+
});
|
|
3326
|
+
}
|
|
3327
|
+
async function refundDuplicateCapture(tx, paymentIntentId, paid, order) {
|
|
3328
|
+
if (await repos.processedEvent.seen(tx, DUPLICATE_CAPTURE_HANDLER, paymentIntentId)) {
|
|
3329
|
+
return { orderNumber: order.orderNumber, finalized: false, reason: DUPLICATE_CAPTURE };
|
|
3330
|
+
}
|
|
3331
|
+
const key = uuidv5(`duplicate-capture:${paymentIntentId}`, CAPTURE_REFUND_NAMESPACE);
|
|
3332
|
+
const settlement = await refundCapture(
|
|
3333
|
+
paymentIntentId,
|
|
3334
|
+
paid,
|
|
3335
|
+
paid.currency.toUpperCase(),
|
|
3336
|
+
key,
|
|
3337
|
+
{
|
|
3338
|
+
orderId: order.id,
|
|
3339
|
+
idempotencyKey: key
|
|
3340
|
+
}
|
|
3341
|
+
);
|
|
3342
|
+
if (settlement.status === "pending" && !settlement.mismatch) {
|
|
3343
|
+
throw new CheckoutError2(
|
|
3344
|
+
"finalize_failed",
|
|
3345
|
+
`The refund of a second capture of order ${order.orderNumber} has no known outcome`,
|
|
3346
|
+
{ context: { orderNumber: order.orderNumber } }
|
|
3347
|
+
);
|
|
3348
|
+
}
|
|
3349
|
+
await repos.processedEvent.markProcessed(
|
|
3350
|
+
tx,
|
|
3351
|
+
DUPLICATE_CAPTURE_HANDLER,
|
|
3352
|
+
paymentIntentId,
|
|
3353
|
+
/* @__PURE__ */ new Date()
|
|
3354
|
+
);
|
|
3355
|
+
const reason = settlement.status === "succeeded" ? DUPLICATE_CAPTURE : `duplicate_capture_refund_${settlement.status}`;
|
|
3356
|
+
return recordOutcome(
|
|
3357
|
+
tx,
|
|
3358
|
+
paymentIntentId,
|
|
3359
|
+
order,
|
|
3360
|
+
reason,
|
|
3361
|
+
`capture of ${formatMoney(paid.amountMinor, paid.currency)}`
|
|
3362
|
+
);
|
|
3363
|
+
}
|
|
3364
|
+
async function confirm(tx, paymentIntentId, paid, order, capture) {
|
|
3365
|
+
const metadata = order.metadata;
|
|
3366
|
+
const reservationIds = Array.isArray(metadata.reservationIds) ? metadata.reservationIds : [];
|
|
3367
|
+
audit.note("order.confirm", [{ type: "order", id: order.id }]);
|
|
3368
|
+
for (const [index, reservationId] of reservationIds.entries()) {
|
|
3369
|
+
const reservation = await reservationFor(tx, order, reservationId, index);
|
|
3370
|
+
await inventory.commitReservation(reservation, FINALIZE_ACTOR);
|
|
3371
|
+
}
|
|
3372
|
+
const now = /* @__PURE__ */ new Date();
|
|
3373
|
+
if (!await repos.order.setStatusIf(tx, order.id, "pending", "confirmed", now)) {
|
|
3374
|
+
throw new NoLongerPending();
|
|
3375
|
+
}
|
|
3376
|
+
await repos.order.recordCapture(tx, order.id, {
|
|
3377
|
+
amountMinor: paid.amountMinor,
|
|
3378
|
+
method: capture.method,
|
|
3379
|
+
at: now
|
|
3380
|
+
});
|
|
3381
|
+
await repos.orderHistory.append(tx, {
|
|
3382
|
+
id: uuidv712(),
|
|
3383
|
+
orderId: order.id,
|
|
3384
|
+
fromStatus: "pending",
|
|
3385
|
+
toStatus: "confirmed",
|
|
3386
|
+
actor: capture.actor,
|
|
3387
|
+
note: capture.note,
|
|
3388
|
+
timestamp: now
|
|
3389
|
+
});
|
|
3390
|
+
if (order.customerId) {
|
|
3391
|
+
await repos.customer.incrementStats(tx, order.customerId, 1, paid.amountMinor, now);
|
|
3392
|
+
}
|
|
3393
|
+
await publisher.publish(EVT_PAYMENT_CAPTURED, {
|
|
3394
|
+
paymentId: paymentIntentId,
|
|
3395
|
+
orderId: order.id,
|
|
3396
|
+
amountMinor: paid.amountMinor,
|
|
3397
|
+
currency: order.currency
|
|
3398
|
+
});
|
|
3399
|
+
await publisher.publish(EVT_ORDER_PAID, {
|
|
3400
|
+
orderId: order.id,
|
|
3401
|
+
paymentIntentId,
|
|
3402
|
+
amountMinor: paid.amountMinor,
|
|
3403
|
+
currency: order.currency
|
|
3404
|
+
});
|
|
3405
|
+
const cartToken = metadata.cartToken;
|
|
3406
|
+
if (cartToken) {
|
|
3407
|
+
if (await repos.cart.clearIfLive(tx, cartToken, now)) {
|
|
3408
|
+
await publisher.publish(EVT_CART_UPDATED2, {
|
|
3409
|
+
cartId: cartToken,
|
|
3410
|
+
itemCount: 0,
|
|
3411
|
+
totalMinor: 0
|
|
3412
|
+
});
|
|
3413
|
+
}
|
|
3414
|
+
await publisher.publish(EVT_CART_CONVERTED, {
|
|
3415
|
+
cartId: cartToken,
|
|
3416
|
+
orderId: order.id
|
|
3417
|
+
});
|
|
3418
|
+
}
|
|
3419
|
+
logger.info({ orderId: order.id, orderNumber: order.orderNumber }, "checkout finalized");
|
|
3420
|
+
return { orderNumber: order.orderNumber, finalized: true };
|
|
3421
|
+
}
|
|
3422
|
+
async function cancelDraft(orderId, reason) {
|
|
3423
|
+
await store.transaction(async (tx) => {
|
|
3424
|
+
const order = await repos.order.findById(tx, orderId);
|
|
3425
|
+
if (!order) throw new NotFoundError10("order", orderId);
|
|
3426
|
+
const metadata = order.metadata;
|
|
3427
|
+
const reservationIds = Array.isArray(metadata.reservationIds) ? metadata.reservationIds : [];
|
|
3428
|
+
for (const rid of reservationIds) {
|
|
3429
|
+
await inventory.releaseReservation(rid, "cancelled");
|
|
3430
|
+
}
|
|
3431
|
+
await orders.cancel(orderId, reason, CANCEL_ACTOR);
|
|
3432
|
+
});
|
|
3433
|
+
}
|
|
3434
|
+
async function checkStock(tx, cartDoc) {
|
|
3435
|
+
for (const item of cartDoc.items) {
|
|
3436
|
+
const v = await repos.variant.findById(tx, item.variantId);
|
|
3437
|
+
if (!v) {
|
|
3438
|
+
throw new CheckoutError2("variant_missing", `Variant missing: ${item.variantId}`);
|
|
3439
|
+
}
|
|
3440
|
+
if (v.stock < item.qty) {
|
|
3441
|
+
throw new CheckoutError2(
|
|
3442
|
+
"out_of_stock",
|
|
3443
|
+
`Insufficient stock for ${item.variantName}: available ${v.stock}, requested ${item.qty}`
|
|
3444
|
+
);
|
|
3445
|
+
}
|
|
3446
|
+
}
|
|
3447
|
+
}
|
|
3448
|
+
async function place(tx, input, closed) {
|
|
3449
|
+
const cartDoc = await repos.cart.lock(tx, input.cartToken);
|
|
3450
|
+
if (cartDoc === null) throw new NotFoundError10("cart", input.cartToken);
|
|
3451
|
+
if (!cartDoc.items.length) throw await cartEmpty(input.cartToken);
|
|
3452
|
+
const pending = await repos.order.findPendingByCartToken(tx, input.cartToken);
|
|
3453
|
+
if (pending !== null) {
|
|
3454
|
+
const { paymentIntentId } = pending;
|
|
3455
|
+
if (paymentIntentId === null) {
|
|
3456
|
+
if (Date.now() - Date.parse(pending.createdAt) <= ABANDON_AFTER_MS) {
|
|
3457
|
+
throw new CheckoutError2("in_progress", "A checkout for this cart is already in progress");
|
|
3458
|
+
}
|
|
3459
|
+
await cancelDraft(pending.id, "abandoned: no payment intent");
|
|
3460
|
+
} else {
|
|
3461
|
+
const reason = closed.get(paymentIntentId);
|
|
3462
|
+
if (reason === void 0) {
|
|
3463
|
+
if (sameLines(pending, cartDoc)) {
|
|
3464
|
+
const orderKey = await mintKey(tx, pending.id);
|
|
3465
|
+
return { kind: "existing", order: { ...pending, paymentIntentId }, orderKey };
|
|
3466
|
+
}
|
|
3467
|
+
return { kind: "cancel-first", order: { ...pending, paymentIntentId } };
|
|
3468
|
+
}
|
|
3469
|
+
await cancelDraft(pending.id, reason);
|
|
3470
|
+
}
|
|
3471
|
+
}
|
|
3472
|
+
await checkStock(tx, cartDoc);
|
|
3473
|
+
const lineItems = cartDoc.items.map((item) => ({
|
|
3474
|
+
variantId: item.variantId,
|
|
3475
|
+
productId: item.productId,
|
|
3476
|
+
productName: item.productName,
|
|
3477
|
+
variantName: item.variantName,
|
|
3478
|
+
sku: "",
|
|
3479
|
+
qty: item.qty,
|
|
3480
|
+
unitPriceMinor: item.priceMinor,
|
|
3481
|
+
lineSubtotalMinor: item.priceMinor * item.qty,
|
|
3482
|
+
lineTaxMinor: 0,
|
|
3483
|
+
lineTotalMinor: item.priceMinor * item.qty,
|
|
3484
|
+
imageUrl: item.imageUrl
|
|
3485
|
+
}));
|
|
3486
|
+
const orderId = uuidv712();
|
|
3487
|
+
audit.note("checkout.place", [{ type: "order", id: orderId }]);
|
|
3488
|
+
const correlationId = currentCorrelationId();
|
|
3489
|
+
const reservationIds = [];
|
|
3490
|
+
for (const item of cartDoc.items) {
|
|
3491
|
+
try {
|
|
3492
|
+
const r = await inventory.reserveStock(item.variantId, item.qty, orderId);
|
|
3493
|
+
reservationIds.push(r.reservationId);
|
|
3494
|
+
} catch (err) {
|
|
3495
|
+
if (err instanceof CheckoutError2) throw err;
|
|
3496
|
+
throw new CheckoutError2("reservation_failed", "Inventory reservation failed", {
|
|
3497
|
+
cause: err
|
|
3498
|
+
});
|
|
3499
|
+
}
|
|
3500
|
+
}
|
|
3501
|
+
const order = await orders.createFromCheckout({
|
|
3502
|
+
orderId,
|
|
3503
|
+
customerId: input.customerId ?? null,
|
|
3504
|
+
email: input.email,
|
|
3505
|
+
billingAddress: input.billingAddress,
|
|
3506
|
+
shippingAddress: input.shippingAddress,
|
|
3507
|
+
lineItems,
|
|
3508
|
+
subtotalMinor: cartDoc.subtotalMinor,
|
|
3509
|
+
taxTotalMinor: 0,
|
|
3510
|
+
shippingTotalMinor: 0,
|
|
3511
|
+
discountTotalMinor: 0,
|
|
3512
|
+
totalMinor: cartDoc.subtotalMinor,
|
|
3513
|
+
currency: cartDoc.currency,
|
|
3514
|
+
...input.notes !== void 0 && { notes: input.notes },
|
|
3515
|
+
metadata: {
|
|
3516
|
+
cartToken: cartDoc.token,
|
|
3517
|
+
reservationIds,
|
|
3518
|
+
...correlationId !== void 0 && { correlationId }
|
|
3519
|
+
},
|
|
3520
|
+
cartToken: cartDoc.token
|
|
3521
|
+
});
|
|
3522
|
+
return { kind: "placed", order, orderKey: await mintKey(tx, order.id) };
|
|
3523
|
+
}
|
|
3524
|
+
async function answerExisting(order) {
|
|
3525
|
+
const paymentIntent = await payments.getPaymentIntent(order.paymentIntentId);
|
|
3526
|
+
if (outcomeOf(paymentIntent.status) === "failed") {
|
|
3527
|
+
return { closed: `payment_${paymentIntent.status}` };
|
|
3528
|
+
}
|
|
3529
|
+
return {
|
|
3530
|
+
orderId: order.id,
|
|
3531
|
+
orderNumber: order.orderNumber,
|
|
3532
|
+
paymentIntent,
|
|
3533
|
+
currency: order.currency,
|
|
3534
|
+
totalMinor: order.totalMinor,
|
|
3535
|
+
orderStatus: order.status,
|
|
3536
|
+
payment: { status: "requires_action" }
|
|
3537
|
+
};
|
|
3538
|
+
}
|
|
3539
|
+
async function cancelIntent(order) {
|
|
3540
|
+
try {
|
|
3541
|
+
await payments.cancelPaymentIntent(order.paymentIntentId);
|
|
3542
|
+
} catch (err) {
|
|
3543
|
+
if (!(err instanceof PaymentError2 && err.code === "payment.cancel_refused")) throw err;
|
|
3544
|
+
throw new CheckoutError2(
|
|
3545
|
+
"payment_in_progress",
|
|
3546
|
+
`The payment for order ${order.orderNumber} is already under way`,
|
|
3547
|
+
{ cause: err, context: { orderNumber: order.orderNumber } }
|
|
3548
|
+
);
|
|
3549
|
+
}
|
|
3550
|
+
}
|
|
3551
|
+
async function pay(input, order) {
|
|
3552
|
+
const params = {
|
|
3553
|
+
amountMinor: order.totalMinor,
|
|
3554
|
+
currency: order.currency,
|
|
3555
|
+
orderRef: order.id,
|
|
3556
|
+
receiptEmail: input.email,
|
|
3557
|
+
metadata: { orderId: order.id, orderNumber: order.orderNumber }
|
|
3558
|
+
};
|
|
3559
|
+
if (input.customerId != null) params.customerId = input.customerId;
|
|
3560
|
+
let intent;
|
|
3561
|
+
try {
|
|
3562
|
+
intent = await payments.createPaymentIntent(params);
|
|
3563
|
+
} catch (err) {
|
|
3564
|
+
await cancelDraft(order.id, "payment intent not created");
|
|
3565
|
+
throw err;
|
|
3566
|
+
}
|
|
3567
|
+
let unconfirmed = null;
|
|
3568
|
+
const answer = await store.transaction(async (tx) => {
|
|
3569
|
+
await repos.cart.lock(tx, input.cartToken);
|
|
3570
|
+
await repos.order.setPaymentIntent(tx, order.id, intent.id, /* @__PURE__ */ new Date());
|
|
3571
|
+
await publisher.publish(EVT_PAYMENT_INTENT_CREATED, {
|
|
3572
|
+
paymentId: intent.id,
|
|
3573
|
+
orderId: order.id
|
|
3574
|
+
});
|
|
3575
|
+
let payment;
|
|
3576
|
+
const outcome = outcomeOf(intent.status);
|
|
3577
|
+
if (outcome === "succeeded") {
|
|
3578
|
+
const done = await finalize(intent.id, {
|
|
3579
|
+
amountMinor: intent.amountMinor,
|
|
3580
|
+
currency: intent.currency
|
|
3581
|
+
});
|
|
3582
|
+
if (!done.finalized) unconfirmed = done.reason ?? "not_confirmed";
|
|
3583
|
+
payment = unconfirmed === null ? { status: "succeeded" } : { status: "failed", reason: unconfirmed };
|
|
3584
|
+
} else if (outcome === "failed") {
|
|
3585
|
+
const reason = `payment_${intent.status}`;
|
|
3586
|
+
await cancelDraft(order.id, reason);
|
|
3587
|
+
await publisher.publish(EVT_PAYMENT_FAILED, {
|
|
3588
|
+
paymentId: intent.id,
|
|
3589
|
+
orderId: order.id,
|
|
3590
|
+
reason
|
|
3591
|
+
});
|
|
3592
|
+
payment = { status: "failed", reason };
|
|
3593
|
+
} else {
|
|
3594
|
+
payment = { status: "requires_action" };
|
|
3595
|
+
}
|
|
3596
|
+
const current = await repos.order.findById(tx, order.id);
|
|
3597
|
+
logger.info(
|
|
3598
|
+
{ orderId: order.id, orderNumber: order.orderNumber, payment: payment.status },
|
|
3599
|
+
"checkout started"
|
|
3600
|
+
);
|
|
3601
|
+
return {
|
|
3602
|
+
orderId: order.id,
|
|
3603
|
+
orderNumber: order.orderNumber,
|
|
3604
|
+
paymentIntent: intent,
|
|
3605
|
+
currency: order.currency,
|
|
3606
|
+
totalMinor: order.totalMinor,
|
|
3607
|
+
orderStatus: current?.status ?? order.status,
|
|
3608
|
+
payment
|
|
3609
|
+
};
|
|
3610
|
+
});
|
|
3611
|
+
if (unconfirmed !== null && answer.orderStatus === "pending") {
|
|
3612
|
+
await cancelDraft(order.id, unconfirmed);
|
|
3613
|
+
await refundCancelledCapture(
|
|
3614
|
+
intent.id,
|
|
3615
|
+
{ amountMinor: intent.amountMinor, currency: intent.currency },
|
|
3616
|
+
order
|
|
3617
|
+
);
|
|
3618
|
+
return { ...answer, orderStatus: "cancelled" };
|
|
3619
|
+
}
|
|
3620
|
+
return answer;
|
|
3621
|
+
}
|
|
3622
|
+
async function finalize(paymentIntentId, paid) {
|
|
3623
|
+
return store.transaction(async (tx) => {
|
|
3624
|
+
const order = await repos.order.findByPaymentIntentId(tx, paymentIntentId);
|
|
3625
|
+
return inOrderScope(order, () => finalizeLoaded(tx, paymentIntentId, paid, order));
|
|
3626
|
+
});
|
|
3627
|
+
}
|
|
3628
|
+
async function finalizeLoaded(tx, paymentIntentId, paid, order) {
|
|
3629
|
+
const outcome = (order2, reason) => recordOutcome(tx, paymentIntentId, order2, reason);
|
|
3630
|
+
if (order === null || order.status !== "pending") {
|
|
3631
|
+
return settled(tx, paymentIntentId, order, paid);
|
|
3632
|
+
}
|
|
3633
|
+
if (paid.amountMinor !== order.totalMinor || paid.currency.toUpperCase() !== order.currency.toUpperCase()) {
|
|
3634
|
+
return outcome(
|
|
3635
|
+
order,
|
|
3636
|
+
`amount_mismatch: paid ${paid.amountMinor} ${paid.currency.toUpperCase()}, due ${order.totalMinor} ${order.currency.toUpperCase()}`
|
|
3637
|
+
);
|
|
3638
|
+
}
|
|
3639
|
+
try {
|
|
3640
|
+
return await store.savepoint(
|
|
3641
|
+
() => confirm(tx, paymentIntentId, paid, order, PROVIDER_CAPTURE)
|
|
3642
|
+
);
|
|
3643
|
+
} catch (err) {
|
|
3644
|
+
if (err instanceof StockUnavailable) {
|
|
3645
|
+
const current = await repos.order.findById(tx, order.id);
|
|
3646
|
+
if (current?.status !== "pending") return settled(tx, paymentIntentId, current, paid);
|
|
3647
|
+
return outcome(current, `stock_unavailable: ${err.variantId}`);
|
|
3648
|
+
}
|
|
3649
|
+
if (!(err instanceof NoLongerPending)) throw err;
|
|
3650
|
+
}
|
|
3651
|
+
return settled(tx, paymentIntentId, await repos.order.findById(tx, order.id), paid);
|
|
3652
|
+
}
|
|
3653
|
+
return {
|
|
3654
|
+
async beginCheckout(input) {
|
|
3655
|
+
audit.note("checkout.place");
|
|
3656
|
+
try {
|
|
3657
|
+
await loadValidCart(input.cartToken);
|
|
3658
|
+
const closed = /* @__PURE__ */ new Map();
|
|
3659
|
+
for (let attempt = 0; ; attempt += 1) {
|
|
3660
|
+
const placement = await store.transaction((tx) => place(tx, input, closed));
|
|
3661
|
+
if (placement.kind === "placed") {
|
|
3662
|
+
return { ...await pay(input, placement.order), orderKey: placement.orderKey };
|
|
3663
|
+
}
|
|
3664
|
+
if (placement.kind === "existing") {
|
|
3665
|
+
const answer = await answerExisting(placement.order);
|
|
3666
|
+
if (!("closed" in answer)) return { ...answer, orderKey: placement.orderKey };
|
|
3667
|
+
closed.set(placement.order.paymentIntentId, answer.closed);
|
|
3668
|
+
continue;
|
|
3669
|
+
}
|
|
3670
|
+
if (attempt === SUPERSEDE_ATTEMPTS) {
|
|
3671
|
+
throw new CheckoutError2(
|
|
3672
|
+
"in_progress",
|
|
3673
|
+
"A checkout for this cart is already in progress"
|
|
3674
|
+
);
|
|
3675
|
+
}
|
|
3676
|
+
await cancelIntent(placement.order);
|
|
3677
|
+
closed.set(placement.order.paymentIntentId, "superseded: the cart changed");
|
|
3678
|
+
}
|
|
3679
|
+
} catch (err) {
|
|
3680
|
+
throw await withOrderKey(err);
|
|
3681
|
+
}
|
|
3682
|
+
},
|
|
3683
|
+
finalize,
|
|
3684
|
+
async cancel(orderId, reason) {
|
|
3685
|
+
await cancelDraft(orderId, reason);
|
|
3686
|
+
},
|
|
3687
|
+
async markPaid(orderId, actor, note) {
|
|
3688
|
+
audit.note("order.markPaid", [{ type: "order", id: orderId }]);
|
|
3689
|
+
const found = await store.read((tx) => repos.order.findById(tx, orderId));
|
|
3690
|
+
if (!found) throw new NotFoundError10("order", orderId);
|
|
3691
|
+
if (found.status !== "pending") {
|
|
3692
|
+
throw new StatusTransitionError4("order", found.status, "confirmed");
|
|
3693
|
+
}
|
|
3694
|
+
if (found.paymentIntentId) {
|
|
3695
|
+
try {
|
|
3696
|
+
await payments.cancelPaymentIntent(found.paymentIntentId);
|
|
3697
|
+
} catch (err) {
|
|
3698
|
+
if (!(err instanceof PaymentError2 && err.code === "payment.cancel_refused")) throw err;
|
|
3699
|
+
throw new OrderConflictError4(
|
|
3700
|
+
"order.payment_in_progress",
|
|
3701
|
+
`The payment for order ${found.orderNumber} is under way with the provider`,
|
|
3702
|
+
{ cause: err, context: { orderNumber: found.orderNumber } }
|
|
3703
|
+
);
|
|
3704
|
+
}
|
|
3705
|
+
}
|
|
3706
|
+
return store.transaction(async (tx) => {
|
|
3707
|
+
const order = await repos.order.lock(tx, orderId);
|
|
3708
|
+
if (!order) throw new NotFoundError10("order", orderId);
|
|
3709
|
+
if (order.status !== "pending") {
|
|
3710
|
+
throw new StatusTransitionError4("order", order.status, "confirmed");
|
|
3711
|
+
}
|
|
3712
|
+
const capture = {
|
|
3713
|
+
method: "manual",
|
|
3714
|
+
actor,
|
|
3715
|
+
note: note ? `payment recorded manually: ${note}` : "payment recorded manually"
|
|
3716
|
+
};
|
|
3717
|
+
const paid = { amountMinor: order.totalMinor, currency: order.currency };
|
|
3718
|
+
try {
|
|
3719
|
+
await inOrderScope(order, () => confirm(tx, "", paid, order, capture));
|
|
3720
|
+
} catch (err) {
|
|
3721
|
+
if (!(err instanceof StockUnavailable)) throw err;
|
|
3722
|
+
throw new OrderConflictError4(
|
|
3723
|
+
"order.stock_unavailable",
|
|
3724
|
+
`The stock order ${order.orderNumber} held has gone to another order`,
|
|
3725
|
+
{ context: { variantId: err.variantId } }
|
|
3726
|
+
);
|
|
3727
|
+
}
|
|
3728
|
+
return await repos.order.findById(tx, order.id);
|
|
3729
|
+
});
|
|
3730
|
+
}
|
|
3731
|
+
};
|
|
3732
|
+
}
|
|
3733
|
+
|
|
3734
|
+
// src/services/search-service.ts
|
|
3735
|
+
function createSearchService(deps) {
|
|
3736
|
+
return {
|
|
3737
|
+
async products(query, params) {
|
|
3738
|
+
return deps.adapter.search(query, params);
|
|
3739
|
+
}
|
|
3740
|
+
};
|
|
3741
|
+
}
|
|
3742
|
+
|
|
3743
|
+
// src/services/recently-viewed-service.ts
|
|
3744
|
+
import {
|
|
3745
|
+
EVT_PRODUCT_VIEWED as EVT_PRODUCT_VIEWED2,
|
|
3746
|
+
EVT_VISITOR_MERGED as EVT_VISITOR_MERGED2
|
|
3747
|
+
} from "@nymbalhq/types";
|
|
3748
|
+
function createRecentlyViewedService(deps) {
|
|
3749
|
+
const { store, repos, publisher, logger } = deps;
|
|
3750
|
+
const now = deps.now ?? (() => /* @__PURE__ */ new Date());
|
|
3751
|
+
return {
|
|
3752
|
+
async record(viewer, productId) {
|
|
3753
|
+
const product = await store.read((tx) => repos.product.findById(tx, productId));
|
|
3754
|
+
if (product?.status !== "active") return false;
|
|
3755
|
+
await publisher.publish(EVT_PRODUCT_VIEWED2, { productId, viewer }, { timestamp: now() });
|
|
3756
|
+
logger.debug({ productId, viewer: viewer.kind }, "product view recorded");
|
|
3757
|
+
return true;
|
|
3758
|
+
},
|
|
3759
|
+
async fold(visitorId, customerId) {
|
|
3760
|
+
await publisher.publish(
|
|
3761
|
+
EVT_VISITOR_MERGED2,
|
|
3762
|
+
{ visitorId, customerId },
|
|
3763
|
+
{ timestamp: now() }
|
|
3764
|
+
);
|
|
3765
|
+
logger.debug({ customerId }, "visitor views folded into the customer");
|
|
3766
|
+
}
|
|
3767
|
+
};
|
|
3768
|
+
}
|
|
3769
|
+
|
|
3770
|
+
// src/services/alert-service.ts
|
|
3771
|
+
import { v7 as uuidv713 } from "uuid";
|
|
3772
|
+
import {
|
|
3773
|
+
EVT_ALERT_CONFIRMED,
|
|
3774
|
+
EVT_ALERT_REQUESTED,
|
|
3775
|
+
EVT_ALERT_SENT,
|
|
3776
|
+
EVT_ALERT_UNSUBSCRIBED,
|
|
3777
|
+
HttpError as HttpError3
|
|
3778
|
+
} from "@nymbalhq/types";
|
|
3779
|
+
|
|
3780
|
+
// src/services/alert-token.ts
|
|
3781
|
+
import { randomBytes as randomBytes2 } from "crypto";
|
|
3782
|
+
function newAlertToken() {
|
|
3783
|
+
return randomBytes2(32).toString("base64url");
|
|
3784
|
+
}
|
|
3785
|
+
|
|
3786
|
+
// src/services/alert-service.ts
|
|
3787
|
+
var CONFIRMABLE = ["pending", "active"];
|
|
3788
|
+
var UNSUBSCRIBABLE = ["pending", "active", "fired"];
|
|
3789
|
+
function linkInvalid() {
|
|
3790
|
+
return new HttpError3(404, "This link is not valid or no longer applies", {
|
|
3791
|
+
code: "alerts.link_invalid"
|
|
3792
|
+
});
|
|
3793
|
+
}
|
|
3794
|
+
function createAlertService(deps) {
|
|
3795
|
+
const { store, repos, publisher } = deps;
|
|
3796
|
+
const origins = new Set(deps.allowedOrigins.filter((origin) => origin !== "*"));
|
|
3797
|
+
return {
|
|
3798
|
+
async subscribe({ email, variantId, kind, origin }) {
|
|
3799
|
+
return store.transaction(async (tx) => {
|
|
3800
|
+
audit.note("alert.subscribe", [{ type: "variant", id: variantId }]);
|
|
3801
|
+
if (!deps.delivers()) {
|
|
3802
|
+
throw new HttpError3(409, "This store does not send email alerts", {
|
|
3803
|
+
code: "alerts.unavailable"
|
|
3804
|
+
});
|
|
3805
|
+
}
|
|
3806
|
+
if (origin === void 0 || !origins.has(origin)) {
|
|
3807
|
+
throw new HttpError3(
|
|
3808
|
+
400,
|
|
3809
|
+
"The request does not come from one of the store\u2019s storefronts",
|
|
3810
|
+
{
|
|
3811
|
+
code: "alerts.origin_not_allowed"
|
|
3812
|
+
}
|
|
3813
|
+
);
|
|
3814
|
+
}
|
|
3815
|
+
const variant = await repos.variant.findById(tx, variantId);
|
|
3816
|
+
if (variant === null) {
|
|
3817
|
+
throw new HttpError3(404, `Variant ${variantId} not found`, {
|
|
3818
|
+
code: "alerts.variant_not_found"
|
|
3819
|
+
});
|
|
3820
|
+
}
|
|
3821
|
+
const row = await repos.alertSubscription.upsertPending(tx, {
|
|
3822
|
+
id: uuidv713(),
|
|
3823
|
+
email: email.trim().toLowerCase(),
|
|
3824
|
+
kind,
|
|
3825
|
+
variantId,
|
|
3826
|
+
productId: variant.productId,
|
|
3827
|
+
confirmToken: newAlertToken(),
|
|
3828
|
+
unsubscribeToken: newAlertToken(),
|
|
3829
|
+
origin,
|
|
3830
|
+
baselinePriceMinor: kind === "price_drop" ? variant.priceMinor : null,
|
|
3831
|
+
at: /* @__PURE__ */ new Date()
|
|
3832
|
+
});
|
|
3833
|
+
if (row.status === "pending") {
|
|
3834
|
+
await publisher.publish(EVT_ALERT_REQUESTED, {
|
|
3835
|
+
subscriptionId: row.id,
|
|
3836
|
+
kind,
|
|
3837
|
+
variantId,
|
|
3838
|
+
productId: variant.productId
|
|
3839
|
+
});
|
|
3840
|
+
}
|
|
3841
|
+
return { status: "pending" };
|
|
3842
|
+
});
|
|
3843
|
+
},
|
|
3844
|
+
async confirm(token) {
|
|
3845
|
+
return store.transaction(async (tx) => {
|
|
3846
|
+
audit.note("alert.confirm");
|
|
3847
|
+
const row = await repos.alertSubscription.findByConfirmToken(tx, token);
|
|
3848
|
+
const product = row === null ? null : await repos.product.findById(tx, row.productId);
|
|
3849
|
+
if (row === null || product === null || !CONFIRMABLE.includes(row.status)) {
|
|
3850
|
+
throw linkInvalid();
|
|
3851
|
+
}
|
|
3852
|
+
audit.note("alert.confirm", [{ type: "alert", id: row.id }]);
|
|
3853
|
+
if (row.status === "pending") {
|
|
3854
|
+
const now = /* @__PURE__ */ new Date();
|
|
3855
|
+
await repos.alertSubscription.update(
|
|
3856
|
+
tx,
|
|
3857
|
+
row.id,
|
|
3858
|
+
{ status: "active", updatedAt: now, confirmedAt: now },
|
|
3859
|
+
["pending"]
|
|
3860
|
+
);
|
|
3861
|
+
await publisher.publish(EVT_ALERT_CONFIRMED, { subscriptionId: row.id });
|
|
3862
|
+
}
|
|
3863
|
+
return {
|
|
3864
|
+
status: "active",
|
|
3865
|
+
kind: row.kind,
|
|
3866
|
+
product: { name: product.name, slug: product.slug }
|
|
3867
|
+
};
|
|
3868
|
+
});
|
|
3869
|
+
},
|
|
3870
|
+
async unsubscribe(token) {
|
|
3871
|
+
return store.transaction(async (tx) => {
|
|
3872
|
+
audit.note("alert.unsubscribe");
|
|
3873
|
+
const row = await repos.alertSubscription.findByUnsubscribeToken(tx, token);
|
|
3874
|
+
if (row === null) throw linkInvalid();
|
|
3875
|
+
audit.note("alert.unsubscribe", [{ type: "alert", id: row.id }]);
|
|
3876
|
+
if (row.status !== "unsubscribed") {
|
|
3877
|
+
await repos.alertSubscription.update(
|
|
3878
|
+
tx,
|
|
3879
|
+
row.id,
|
|
3880
|
+
{ status: "unsubscribed", updatedAt: /* @__PURE__ */ new Date() },
|
|
3881
|
+
UNSUBSCRIBABLE
|
|
3882
|
+
);
|
|
3883
|
+
await publisher.publish(EVT_ALERT_UNSUBSCRIBED, { subscriptionId: row.id });
|
|
3884
|
+
}
|
|
3885
|
+
return { status: "unsubscribed" };
|
|
3886
|
+
});
|
|
3887
|
+
},
|
|
3888
|
+
async recordSent(tx, subscription, trigger) {
|
|
3889
|
+
const updatedAt = /* @__PURE__ */ new Date();
|
|
3890
|
+
await repos.alertSubscription.update(
|
|
3891
|
+
tx,
|
|
3892
|
+
subscription.id,
|
|
3893
|
+
subscription.kind === "price_drop" ? {
|
|
3894
|
+
status: "active",
|
|
3895
|
+
baselinePriceMinor: trigger.payload.priceMinor,
|
|
3896
|
+
updatedAt
|
|
3897
|
+
} : { status: "fired", updatedAt },
|
|
3898
|
+
["active"]
|
|
3899
|
+
);
|
|
3900
|
+
await publisher.publish(EVT_ALERT_SENT, {
|
|
3901
|
+
subscriptionId: subscription.id,
|
|
3902
|
+
kind: subscription.kind,
|
|
3903
|
+
triggerEventId: trigger.id
|
|
3904
|
+
});
|
|
3905
|
+
}
|
|
3906
|
+
};
|
|
3907
|
+
}
|
|
3908
|
+
|
|
3909
|
+
// src/services/index.ts
|
|
3910
|
+
function emailDelivers(email) {
|
|
3911
|
+
return email.providerName !== "native";
|
|
3912
|
+
}
|
|
3913
|
+
function buildServices(deps) {
|
|
3914
|
+
const { config, store, repos, publisher, logger, payments, searchAdapter, email } = deps;
|
|
3915
|
+
const inventory = createInventoryService({
|
|
3916
|
+
store,
|
|
3917
|
+
repos,
|
|
3918
|
+
publisher,
|
|
3919
|
+
logger: logger.child({ service: "inventory" })
|
|
3920
|
+
});
|
|
3921
|
+
const orders = createOrderService({
|
|
3922
|
+
store,
|
|
3923
|
+
repos,
|
|
3924
|
+
publisher,
|
|
3925
|
+
logger: logger.child({ service: "order" }),
|
|
3926
|
+
orderNumberPrefix: config.commerce.orders.numberPrefix,
|
|
3927
|
+
orderNumberStart: config.commerce.orders.numberStart
|
|
3928
|
+
});
|
|
3929
|
+
const cart = createCartService({
|
|
3930
|
+
store,
|
|
3931
|
+
carts: repos.cart,
|
|
3932
|
+
publisher,
|
|
3933
|
+
logger: logger.child({ service: "cart" }),
|
|
3934
|
+
currency: config.store.currency
|
|
3935
|
+
});
|
|
3936
|
+
const checkout = createCheckoutService({
|
|
3937
|
+
store,
|
|
3938
|
+
repos,
|
|
3939
|
+
publisher,
|
|
3940
|
+
logger: logger.child({ service: "checkout" }),
|
|
3941
|
+
cart,
|
|
3942
|
+
orders,
|
|
3943
|
+
inventory,
|
|
3944
|
+
payments,
|
|
3945
|
+
currency: config.store.currency
|
|
3946
|
+
});
|
|
3947
|
+
return {
|
|
3948
|
+
product: createProductService({
|
|
3949
|
+
store,
|
|
3950
|
+
repos,
|
|
3951
|
+
publisher,
|
|
3952
|
+
logger: logger.child({ service: "product" }),
|
|
3953
|
+
currency: config.store.currency
|
|
3954
|
+
}),
|
|
3955
|
+
category: createCategoryService({
|
|
3956
|
+
repos,
|
|
3957
|
+
publisher,
|
|
3958
|
+
logger: logger.child({ service: "category" })
|
|
3959
|
+
}),
|
|
3960
|
+
cart,
|
|
3961
|
+
customer: createCustomerService({
|
|
3962
|
+
repos,
|
|
3963
|
+
publisher,
|
|
3964
|
+
logger: logger.child({ service: "customer" })
|
|
3965
|
+
}),
|
|
3966
|
+
auth: createAuthService({
|
|
3967
|
+
repos,
|
|
3968
|
+
publisher,
|
|
3969
|
+
logger: logger.child({ service: "auth" }),
|
|
3970
|
+
jwtSecret: config.security.auth.jwtSecret,
|
|
3971
|
+
accessTtl: config.security.auth.accessTtl,
|
|
3972
|
+
refreshTtl: config.security.auth.refreshTtl
|
|
3973
|
+
}),
|
|
3974
|
+
order: orders,
|
|
3975
|
+
inventory,
|
|
3976
|
+
checkout,
|
|
3977
|
+
refund: createRefundService({
|
|
3978
|
+
store,
|
|
3979
|
+
repos,
|
|
3980
|
+
publisher,
|
|
3981
|
+
logger: logger.child({ service: "refund" }),
|
|
3982
|
+
payments
|
|
3983
|
+
}),
|
|
3984
|
+
search: createSearchService({
|
|
3985
|
+
adapter: searchAdapter,
|
|
3986
|
+
logger: logger.child({ service: "search" })
|
|
3987
|
+
}),
|
|
3988
|
+
recentlyViewed: createRecentlyViewedService({
|
|
3989
|
+
store,
|
|
3990
|
+
repos,
|
|
3991
|
+
publisher,
|
|
3992
|
+
logger: logger.child({ service: "recently-viewed" })
|
|
3993
|
+
}),
|
|
3994
|
+
alert: createAlertService({
|
|
3995
|
+
store,
|
|
3996
|
+
repos,
|
|
3997
|
+
publisher,
|
|
3998
|
+
allowedOrigins: config.http.cors.allowedOrigins,
|
|
3999
|
+
delivers: () => emailDelivers(email)
|
|
4000
|
+
})
|
|
4001
|
+
};
|
|
4002
|
+
}
|
|
4003
|
+
|
|
4004
|
+
// src/routes/capabilities.ts
|
|
4005
|
+
function storeCapabilities(adapters) {
|
|
4006
|
+
const client = adapters.payments.client?.() ?? null;
|
|
4007
|
+
return {
|
|
4008
|
+
payments: {
|
|
4009
|
+
capabilities: [...adapters.payments.capabilities()],
|
|
4010
|
+
client: client === null ? null : { driver: client.driver, options: { ...client.options } }
|
|
4011
|
+
},
|
|
4012
|
+
search: { capabilities: [...adapters.search.capabilities()] },
|
|
4013
|
+
// The document store runs the listing's sort, so these are the catalogue's keys, not the search adapter's.
|
|
4014
|
+
catalog: { sortKeys: [...PRODUCT_SORT_KEYS], defaultSort: DEFAULT_PRODUCT_SORT2 },
|
|
4015
|
+
email: { delivers: emailDelivers(adapters.email) }
|
|
4016
|
+
};
|
|
4017
|
+
}
|
|
4018
|
+
function registerCapabilitiesRoute(adapter, adapters) {
|
|
4019
|
+
adapter.registerRoute("GET", "/api/capabilities", async () => {
|
|
4020
|
+
try {
|
|
4021
|
+
return ok(storeCapabilities(adapters));
|
|
4022
|
+
} catch (err) {
|
|
4023
|
+
return renderError(err);
|
|
4024
|
+
}
|
|
4025
|
+
});
|
|
4026
|
+
}
|
|
4027
|
+
|
|
4028
|
+
// src/routes/categories.ts
|
|
4029
|
+
function registerCategoryRoutes(adapter, documentStore, storeName) {
|
|
4030
|
+
adapter.registerRoute("GET", "/api/categories", async () => {
|
|
4031
|
+
try {
|
|
4032
|
+
const result = await documentStore.query(
|
|
4033
|
+
"categories",
|
|
4034
|
+
{ partitionKey: { field: "storeId", value: storeName }, limit: 500 }
|
|
4035
|
+
);
|
|
4036
|
+
const sorted = result.items.slice().sort((a, b) => (a.position ?? 0) - (b.position ?? 0));
|
|
4037
|
+
return ok(sorted);
|
|
4038
|
+
} catch (err) {
|
|
4039
|
+
return renderError(err);
|
|
4040
|
+
}
|
|
4041
|
+
});
|
|
4042
|
+
}
|
|
4043
|
+
|
|
4044
|
+
// src/routes/cart.ts
|
|
4045
|
+
import "@nymbalhq/types";
|
|
4046
|
+
var CART_COOKIE = "nymbal.cart";
|
|
4047
|
+
function cookie(token) {
|
|
4048
|
+
return [
|
|
4049
|
+
{
|
|
4050
|
+
name: CART_COOKIE,
|
|
4051
|
+
value: token,
|
|
4052
|
+
path: "/",
|
|
4053
|
+
httpOnly: true,
|
|
4054
|
+
sameSite: "lax",
|
|
4055
|
+
secure: process.env.NODE_ENV === "production",
|
|
4056
|
+
maxAge: 60 * 60 * 24 * 30
|
|
4057
|
+
}
|
|
4058
|
+
];
|
|
4059
|
+
}
|
|
4060
|
+
function registerCartRoutes(adapter, deps) {
|
|
4061
|
+
const { cart, productRepo, variantRepo } = deps;
|
|
4062
|
+
adapter.registerRoute("GET", "/api/cart", async (ctx) => {
|
|
4063
|
+
try {
|
|
4064
|
+
const token = ctx.cookies[CART_COOKIE];
|
|
4065
|
+
const existing = token ? await cart.get(token) : null;
|
|
4066
|
+
if (existing) return ok(existing);
|
|
4067
|
+
const fresh = await cart.getOrCreate();
|
|
4068
|
+
const env = ok(fresh);
|
|
4069
|
+
env.cookies = cookie(fresh.token);
|
|
4070
|
+
return env;
|
|
4071
|
+
} catch (err) {
|
|
4072
|
+
return renderError(err);
|
|
4073
|
+
}
|
|
4074
|
+
});
|
|
4075
|
+
adapter.registerRoute("POST", "/api/cart/items", async (ctx) => {
|
|
4076
|
+
try {
|
|
4077
|
+
const body = ctx.body;
|
|
4078
|
+
if (!body?.variantId) return fail("cart.invalid", "variantId required", 400);
|
|
4079
|
+
const qty = body.qty ?? 1;
|
|
4080
|
+
const { variantId } = body;
|
|
4081
|
+
const variant = await variantRepo.store.read((tx) => variantRepo.findById(tx, variantId));
|
|
4082
|
+
if (!variant) return fail("cart.variant_missing", "variant not found", 404);
|
|
4083
|
+
if (variant.stock < qty) {
|
|
4084
|
+
return fail("cart.out_of_stock", "insufficient stock", 409, {
|
|
4085
|
+
variantId: variant.id,
|
|
4086
|
+
available: variant.stock
|
|
4087
|
+
});
|
|
4088
|
+
}
|
|
4089
|
+
const product = await productRepo.store.read(
|
|
4090
|
+
(tx) => productRepo.findById(tx, variant.productId)
|
|
4091
|
+
);
|
|
4092
|
+
if (!product) return fail("cart.product_missing", "product not found", 404);
|
|
4093
|
+
const token = ctx.cookies[CART_COOKIE] ?? (await cart.getOrCreate()).token;
|
|
4094
|
+
const updated = await cart.addItem(token, {
|
|
4095
|
+
variantId: variant.id,
|
|
4096
|
+
productId: product.id,
|
|
4097
|
+
productName: product.name,
|
|
4098
|
+
variantName: variant.name,
|
|
4099
|
+
priceMinor: variant.priceMinor,
|
|
4100
|
+
qty,
|
|
4101
|
+
imageUrl: product.media[0]?.url ?? ""
|
|
4102
|
+
});
|
|
4103
|
+
const env = ok(updated);
|
|
4104
|
+
env.cookies = cookie(token);
|
|
4105
|
+
return env;
|
|
4106
|
+
} catch (err) {
|
|
4107
|
+
return renderError(err);
|
|
4108
|
+
}
|
|
4109
|
+
});
|
|
4110
|
+
adapter.registerRoute("PATCH", "/api/cart/items/:variantId", async (ctx) => {
|
|
4111
|
+
try {
|
|
4112
|
+
const token = ctx.cookies[CART_COOKIE];
|
|
4113
|
+
if (!token) return fail("cart.missing", "no active cart", 404);
|
|
4114
|
+
const variantId = ctx.params.variantId;
|
|
4115
|
+
if (!variantId) return fail("cart.variant_required", "variantId param required", 400);
|
|
4116
|
+
const qty = ctx.body?.qty ?? 0;
|
|
4117
|
+
const updated = await cart.updateItemQuantity(token, variantId, qty);
|
|
4118
|
+
return ok(updated);
|
|
4119
|
+
} catch (err) {
|
|
4120
|
+
return renderError(err);
|
|
4121
|
+
}
|
|
4122
|
+
});
|
|
4123
|
+
adapter.registerRoute("DELETE", "/api/cart/items/:variantId", async (ctx) => {
|
|
4124
|
+
try {
|
|
4125
|
+
const token = ctx.cookies[CART_COOKIE];
|
|
4126
|
+
if (!token) return fail("cart.missing", "no active cart", 404);
|
|
4127
|
+
const variantId = ctx.params.variantId;
|
|
4128
|
+
if (!variantId) return fail("cart.variant_required", "variantId param required", 400);
|
|
4129
|
+
const updated = await cart.removeItem(token, variantId);
|
|
4130
|
+
return ok(updated);
|
|
4131
|
+
} catch (err) {
|
|
4132
|
+
return renderError(err);
|
|
4133
|
+
}
|
|
4134
|
+
});
|
|
4135
|
+
adapter.registerRoute("DELETE", "/api/cart", async (ctx) => {
|
|
4136
|
+
try {
|
|
4137
|
+
const token = ctx.cookies[CART_COOKIE];
|
|
4138
|
+
if (!token) return fail("cart.missing", "no active cart", 404);
|
|
4139
|
+
const cleared = await cart.clear(token);
|
|
4140
|
+
return ok(cleared);
|
|
4141
|
+
} catch (err) {
|
|
4142
|
+
return renderError(err);
|
|
4143
|
+
}
|
|
4144
|
+
});
|
|
4145
|
+
}
|
|
4146
|
+
|
|
4147
|
+
// src/routes/checkout.ts
|
|
4148
|
+
import "@nymbalhq/types";
|
|
4149
|
+
var CART_COOKIE2 = "nymbal.cart";
|
|
4150
|
+
function registerCheckoutRoutes(adapter, checkout) {
|
|
4151
|
+
adapter.registerRoute("POST", "/api/checkout", async (ctx) => {
|
|
4152
|
+
try {
|
|
4153
|
+
const body = ctx.body;
|
|
4154
|
+
const cartToken = ctx.cookies[CART_COOKIE2];
|
|
4155
|
+
if (!cartToken) return fail("checkout.no_cart", "No active cart", 400);
|
|
4156
|
+
if (!body?.email || !body.billingAddress || !body.shippingAddress) {
|
|
4157
|
+
return fail("checkout.invalid", "email, billingAddress, shippingAddress are required", 400);
|
|
4158
|
+
}
|
|
4159
|
+
const result = await checkout.beginCheckout({
|
|
4160
|
+
cartToken,
|
|
4161
|
+
...ctx.auth?.userId !== void 0 && { customerId: ctx.auth.userId },
|
|
4162
|
+
email: body.email,
|
|
4163
|
+
billingAddress: body.billingAddress,
|
|
4164
|
+
shippingAddress: body.shippingAddress,
|
|
4165
|
+
...body.notes !== void 0 && { notes: body.notes }
|
|
4166
|
+
});
|
|
4167
|
+
return ok({
|
|
4168
|
+
orderId: result.orderId,
|
|
4169
|
+
orderNumber: result.orderNumber,
|
|
4170
|
+
paymentIntent: result.paymentIntent,
|
|
4171
|
+
currency: result.currency,
|
|
4172
|
+
totalMinor: result.totalMinor,
|
|
4173
|
+
orderStatus: result.orderStatus,
|
|
4174
|
+
payment: result.payment,
|
|
4175
|
+
orderKey: result.orderKey
|
|
4176
|
+
});
|
|
4177
|
+
} catch (err) {
|
|
4178
|
+
return renderError(err);
|
|
4179
|
+
}
|
|
4180
|
+
});
|
|
4181
|
+
}
|
|
4182
|
+
|
|
4183
|
+
// src/routes/orders.ts
|
|
4184
|
+
import {
|
|
4185
|
+
NotFoundError as NotFoundError11,
|
|
4186
|
+
ORDER_KEY_HEADER
|
|
4187
|
+
} from "@nymbalhq/types";
|
|
4188
|
+
|
|
4189
|
+
// src/routes/role-middleware.ts
|
|
4190
|
+
import { AuthError as AuthError4 } from "@nymbalhq/types";
|
|
4191
|
+
function requireAuth(handler) {
|
|
4192
|
+
return (ctx) => {
|
|
4193
|
+
if (!ctx.auth?.userId) {
|
|
4194
|
+
return fail("auth.unauthorized", "Authentication required", 401);
|
|
4195
|
+
}
|
|
4196
|
+
return handler(ctx);
|
|
4197
|
+
};
|
|
4198
|
+
}
|
|
4199
|
+
function requireRole(role, handler) {
|
|
4200
|
+
return (ctx) => {
|
|
4201
|
+
if (!ctx.auth?.userId) {
|
|
4202
|
+
return fail("auth.unauthorized", "Authentication required", 401);
|
|
4203
|
+
}
|
|
4204
|
+
if (!ctx.auth.roles?.includes(role)) {
|
|
4205
|
+
return fail("auth.forbidden", `Role required: ${role}`, 403);
|
|
4206
|
+
}
|
|
4207
|
+
return handler(ctx);
|
|
4208
|
+
};
|
|
4209
|
+
}
|
|
4210
|
+
|
|
4211
|
+
// src/routes/orders.ts
|
|
4212
|
+
function shopperOrder(doc) {
|
|
4213
|
+
const { partitionKey: _partitionKey, sortKey: _sortKey, history: _history, ...order } = doc;
|
|
4214
|
+
return { ...order, metadata: {}, notes: "", paymentIntentId: null };
|
|
4215
|
+
}
|
|
4216
|
+
function registerOrderRoutes(adapter, orders, documentStore) {
|
|
4217
|
+
adapter.registerRoute(
|
|
4218
|
+
"GET",
|
|
4219
|
+
"/api/orders",
|
|
4220
|
+
requireAuth(async (ctx) => {
|
|
4221
|
+
try {
|
|
4222
|
+
const customerId = ctx.auth.userId;
|
|
4223
|
+
const result = await documentStore.query("orders-by-customer", {
|
|
4224
|
+
partitionKey: { field: "partitionKey", value: `customer:${customerId}` },
|
|
4225
|
+
limit: 50
|
|
4226
|
+
});
|
|
4227
|
+
return ok(result.items.map(shopperOrder), { nextCursor: result.nextCursor });
|
|
4228
|
+
} catch (err) {
|
|
4229
|
+
return renderError(err);
|
|
4230
|
+
}
|
|
4231
|
+
})
|
|
4232
|
+
);
|
|
4233
|
+
async function readOrder(ctx) {
|
|
4234
|
+
try {
|
|
4235
|
+
const orderNumber = ctx.params.orderNumber;
|
|
4236
|
+
if (!orderNumber) return fail("orders.invalid", "orderNumber required", 400);
|
|
4237
|
+
const doc = await documentStore.get("orders", orderNumber);
|
|
4238
|
+
if (!doc) throw new NotFoundError11("order", orderNumber);
|
|
4239
|
+
const userId = ctx.auth?.userId;
|
|
4240
|
+
const owner = doc.customerId !== null && userId !== void 0 && doc.customerId === userId;
|
|
4241
|
+
const key = ctx.headers[ORDER_KEY_HEADER];
|
|
4242
|
+
if (!owner && !(typeof key === "string" && await orders.keyOpens(doc.id, key))) {
|
|
4243
|
+
throw new NotFoundError11("order", orderNumber);
|
|
4244
|
+
}
|
|
4245
|
+
return ok(shopperOrder(doc));
|
|
4246
|
+
} catch (err) {
|
|
4247
|
+
return renderError(err);
|
|
4248
|
+
}
|
|
4249
|
+
}
|
|
4250
|
+
adapter.registerRoute("GET", "/api/orders/:orderNumber", async (ctx) => ({
|
|
4251
|
+
...await readOrder(ctx),
|
|
4252
|
+
headers: { "Cache-Control": "no-store" }
|
|
4253
|
+
}));
|
|
4254
|
+
}
|
|
4255
|
+
|
|
4256
|
+
// src/routes/customers.ts
|
|
4257
|
+
import "@nymbalhq/types";
|
|
4258
|
+
function registerCustomerRoutes(adapter, customers) {
|
|
4259
|
+
adapter.registerRoute(
|
|
4260
|
+
"GET",
|
|
4261
|
+
"/api/customers/me",
|
|
4262
|
+
requireAuth(async (ctx) => {
|
|
4263
|
+
try {
|
|
4264
|
+
return ok(await customers.getProfile(ctx.auth.userId));
|
|
4265
|
+
} catch (err) {
|
|
4266
|
+
return renderError(err);
|
|
4267
|
+
}
|
|
4268
|
+
})
|
|
4269
|
+
);
|
|
4270
|
+
adapter.registerRoute(
|
|
4271
|
+
"PATCH",
|
|
4272
|
+
"/api/customers/me",
|
|
4273
|
+
requireAuth(async (ctx) => {
|
|
4274
|
+
try {
|
|
4275
|
+
const patch = ctx.body;
|
|
4276
|
+
const profile = await customers.updateProfile(ctx.auth.userId, {
|
|
4277
|
+
...typeof patch.firstName === "string" && { firstName: patch.firstName },
|
|
4278
|
+
...typeof patch.lastName === "string" && { lastName: patch.lastName },
|
|
4279
|
+
...typeof patch.phone === "string" && { phone: patch.phone }
|
|
4280
|
+
});
|
|
4281
|
+
return ok(profile);
|
|
4282
|
+
} catch (err) {
|
|
4283
|
+
return renderError(err);
|
|
4284
|
+
}
|
|
4285
|
+
})
|
|
4286
|
+
);
|
|
4287
|
+
adapter.registerRoute(
|
|
4288
|
+
"GET",
|
|
4289
|
+
"/api/customers/me/addresses",
|
|
4290
|
+
requireAuth(async (ctx) => {
|
|
4291
|
+
try {
|
|
4292
|
+
return ok(await customers.listAddresses(ctx.auth.userId));
|
|
4293
|
+
} catch (err) {
|
|
4294
|
+
return renderError(err);
|
|
4295
|
+
}
|
|
4296
|
+
})
|
|
4297
|
+
);
|
|
4298
|
+
adapter.registerRoute(
|
|
4299
|
+
"POST",
|
|
4300
|
+
"/api/customers/me/addresses",
|
|
4301
|
+
requireAuth(async (ctx) => {
|
|
4302
|
+
try {
|
|
4303
|
+
const body = ctx.body;
|
|
4304
|
+
if (!body || !body.addressLine1) return fail("address.invalid", "address invalid", 400);
|
|
4305
|
+
const addr = await customers.addAddress(ctx.auth.userId, {
|
|
4306
|
+
firstName: body.firstName,
|
|
4307
|
+
lastName: body.lastName,
|
|
4308
|
+
addressLine1: body.addressLine1,
|
|
4309
|
+
city: body.city,
|
|
4310
|
+
region: body.region,
|
|
4311
|
+
postalCode: body.postalCode,
|
|
4312
|
+
country: body.country,
|
|
4313
|
+
isDefaultBilling: body.isDefaultBilling ?? false,
|
|
4314
|
+
isDefaultShipping: body.isDefaultShipping ?? false,
|
|
4315
|
+
...body.addressLine2 !== void 0 && { addressLine2: body.addressLine2 },
|
|
4316
|
+
...body.company !== void 0 && { company: body.company },
|
|
4317
|
+
...body.phone !== void 0 && { phone: body.phone }
|
|
4318
|
+
});
|
|
4319
|
+
return ok(addr, void 0, 201);
|
|
4320
|
+
} catch (err) {
|
|
4321
|
+
return renderError(err);
|
|
4322
|
+
}
|
|
4323
|
+
})
|
|
4324
|
+
);
|
|
4325
|
+
adapter.registerRoute(
|
|
4326
|
+
"DELETE",
|
|
4327
|
+
"/api/customers/me/addresses/:id",
|
|
4328
|
+
requireAuth(async (ctx) => {
|
|
4329
|
+
try {
|
|
4330
|
+
const id2 = ctx.params.id;
|
|
4331
|
+
if (!id2) return fail("address.invalid", "id required", 400);
|
|
4332
|
+
await customers.deleteAddress(ctx.auth.userId, id2);
|
|
4333
|
+
return ok({ ok: true });
|
|
4334
|
+
} catch (err) {
|
|
4335
|
+
return renderError(err);
|
|
4336
|
+
}
|
|
4337
|
+
})
|
|
4338
|
+
);
|
|
4339
|
+
}
|
|
4340
|
+
|
|
4341
|
+
// src/routes/admin-me.ts
|
|
4342
|
+
function registerAdminMeRoute(adapter, deps) {
|
|
4343
|
+
const { config } = deps;
|
|
4344
|
+
adapter.registerRoute(
|
|
4345
|
+
"GET",
|
|
4346
|
+
"/api/admin/me",
|
|
4347
|
+
requireRole("admin", async (ctx) => {
|
|
4348
|
+
try {
|
|
4349
|
+
return ok({
|
|
4350
|
+
userId: ctx.auth.userId,
|
|
4351
|
+
roles: ctx.auth.roles,
|
|
4352
|
+
storeName: config.store.name,
|
|
4353
|
+
environment: process.env["NODE_ENV"] ?? "development"
|
|
4354
|
+
});
|
|
4355
|
+
} catch (err) {
|
|
4356
|
+
return renderError(err);
|
|
4357
|
+
}
|
|
4358
|
+
})
|
|
4359
|
+
);
|
|
4360
|
+
}
|
|
4361
|
+
|
|
4362
|
+
// src/routes/admin-dashboard.ts
|
|
4363
|
+
function registerAdminDashboardRoute(adapter, deps) {
|
|
4364
|
+
const { repos } = deps;
|
|
4365
|
+
const { store } = repos.order;
|
|
4366
|
+
adapter.registerRoute(
|
|
4367
|
+
"GET",
|
|
4368
|
+
"/api/admin/dashboard",
|
|
4369
|
+
requireRole("admin", async () => {
|
|
4370
|
+
try {
|
|
4371
|
+
const startOfToday = new Date((/* @__PURE__ */ new Date()).setHours(0, 0, 0, 0));
|
|
4372
|
+
const allOrders = await store.read((tx) => repos.order.list(tx, { limit: 200 }));
|
|
4373
|
+
const todayOrders = allOrders.filter((o) => new Date(o.createdAt) >= startOfToday);
|
|
4374
|
+
const shippedStatuses = /* @__PURE__ */ new Set(["shipped", "delivered"]);
|
|
4375
|
+
const todayOrderCount = todayOrders.length;
|
|
4376
|
+
const todayRevenueMinor = todayOrders.reduce(
|
|
4377
|
+
(sum, o) => sum + o.capturedMinor - o.refundedMinor,
|
|
4378
|
+
0
|
|
4379
|
+
);
|
|
4380
|
+
const todayItemsShipped = todayOrders.filter((o) => shippedStatuses.has(o.status)).length;
|
|
4381
|
+
const recentOrders = allOrders.slice(0, 10);
|
|
4382
|
+
const productVariants = await store.read(async (tx) => {
|
|
4383
|
+
const products = await repos.product.list(tx, { limit: 1e3 });
|
|
4384
|
+
const out = [];
|
|
4385
|
+
for (const product of products) {
|
|
4386
|
+
out.push({ product, variants: await repos.variant.findByProduct(tx, product.id) });
|
|
4387
|
+
}
|
|
4388
|
+
return out;
|
|
4389
|
+
});
|
|
4390
|
+
const lowStock = [];
|
|
4391
|
+
for (const { product, variants } of productVariants) {
|
|
4392
|
+
for (const variant of variants) {
|
|
4393
|
+
if (variant.stock <= variant.lowStockThreshold) {
|
|
4394
|
+
lowStock.push({
|
|
4395
|
+
variantId: variant.id,
|
|
4396
|
+
productId: product.id,
|
|
4397
|
+
productName: product.name,
|
|
4398
|
+
sku: variant.sku,
|
|
4399
|
+
stock: variant.stock,
|
|
4400
|
+
threshold: variant.lowStockThreshold,
|
|
4401
|
+
status: variant.stock <= 0 ? "out_of_stock" : "low_stock"
|
|
4402
|
+
});
|
|
4403
|
+
}
|
|
4404
|
+
}
|
|
4405
|
+
}
|
|
4406
|
+
return ok({
|
|
4407
|
+
today: {
|
|
4408
|
+
orderCount: todayOrderCount,
|
|
4409
|
+
revenueMinor: todayRevenueMinor,
|
|
4410
|
+
itemsShipped: todayItemsShipped
|
|
4411
|
+
},
|
|
4412
|
+
recentOrders,
|
|
4413
|
+
lowStock
|
|
4414
|
+
});
|
|
4415
|
+
} catch (err) {
|
|
4416
|
+
return renderError(err);
|
|
4417
|
+
}
|
|
4418
|
+
})
|
|
4419
|
+
);
|
|
1828
4420
|
}
|
|
1829
4421
|
|
|
4422
|
+
// src/routes/admin-orders.ts
|
|
4423
|
+
import {
|
|
4424
|
+
OrderConflictError as OrderConflictError5,
|
|
4425
|
+
canTransitionOrder as canTransitionOrder2
|
|
4426
|
+
} from "@nymbalhq/types";
|
|
4427
|
+
|
|
1830
4428
|
// src/history/http.ts
|
|
1831
4429
|
var DEFAULT_LIMIT = 50;
|
|
1832
4430
|
var MAX_LIMIT = 200;
|
|
@@ -1838,7 +4436,7 @@ function one(ctx, name) {
|
|
|
1838
4436
|
function atOf(ctx) {
|
|
1839
4437
|
return one(ctx, "at");
|
|
1840
4438
|
}
|
|
1841
|
-
async function answerAsOf(reader, at, resolve2,
|
|
4439
|
+
async function answerAsOf(reader, at, resolve2, notFound3) {
|
|
1842
4440
|
try {
|
|
1843
4441
|
const instant = new Date(at);
|
|
1844
4442
|
if (!ISO_INSTANT.test(at) || Number.isNaN(instant.getTime())) {
|
|
@@ -1849,7 +4447,7 @@ async function answerAsOf(reader, at, resolve2, notFound2) {
|
|
|
1849
4447
|
case "record":
|
|
1850
4448
|
return ok(outcome.read);
|
|
1851
4449
|
case "not_found":
|
|
1852
|
-
return
|
|
4450
|
+
return notFound3();
|
|
1853
4451
|
case "deleted":
|
|
1854
4452
|
return fail("history.deleted", `Deleted at ${outcome.deletedAt}`, 410, {
|
|
1855
4453
|
deletedAt: outcome.deletedAt
|
|
@@ -1866,7 +4464,7 @@ async function answerAsOf(reader, at, resolve2, notFound2) {
|
|
|
1866
4464
|
return renderError(err);
|
|
1867
4465
|
}
|
|
1868
4466
|
}
|
|
1869
|
-
async function answerHistory(reader, ctx, resolve2,
|
|
4467
|
+
async function answerHistory(reader, ctx, resolve2, notFound3) {
|
|
1870
4468
|
try {
|
|
1871
4469
|
const limitRaw = one(ctx, "limit");
|
|
1872
4470
|
const limit = limitRaw === void 0 || limitRaw === "" ? DEFAULT_LIMIT : Number(limitRaw);
|
|
@@ -1881,7 +4479,7 @@ async function answerHistory(reader, ctx, resolve2, notFound2) {
|
|
|
1881
4479
|
limit: Math.min(limit, MAX_LIMIT),
|
|
1882
4480
|
...cursor !== void 0 && cursor !== "" && { beforeSeq: Number(cursor) }
|
|
1883
4481
|
});
|
|
1884
|
-
return page === null ?
|
|
4482
|
+
return page === null ? notFound3() : ok(page);
|
|
1885
4483
|
} catch (err) {
|
|
1886
4484
|
return renderError(err);
|
|
1887
4485
|
}
|
|
@@ -1919,7 +4517,7 @@ function registerAdminOrdersRoutes(adapter, deps) {
|
|
|
1919
4517
|
const found = await store.read((tx) => findOrder(tx, idOrNumber));
|
|
1920
4518
|
return { kind: "order", id: found?.id ?? idOrNumber, live: found !== null };
|
|
1921
4519
|
}
|
|
1922
|
-
const
|
|
4520
|
+
const notFound3 = (idOrNumber) => () => fail("orders.not_found", `Order not found: ${idOrNumber}`, 404);
|
|
1923
4521
|
adapter.registerRoute(
|
|
1924
4522
|
"GET",
|
|
1925
4523
|
"/api/admin/orders",
|
|
@@ -1978,7 +4576,7 @@ function registerAdminOrdersRoutes(adapter, deps) {
|
|
|
1978
4576
|
if (!orderNumber) return fail("admin.invalid", "orderNumber required", 400);
|
|
1979
4577
|
const at = atOf(ctx);
|
|
1980
4578
|
if (at !== void 0) {
|
|
1981
|
-
return answerAsOf(history, at, () => historySubject(orderNumber),
|
|
4579
|
+
return answerAsOf(history, at, () => historySubject(orderNumber), notFound3(orderNumber));
|
|
1982
4580
|
}
|
|
1983
4581
|
const detail = await store.read(async (tx) => {
|
|
1984
4582
|
const found = await repos.order.findByOrderNumber(tx, orderNumber);
|
|
@@ -2002,7 +4600,7 @@ function registerAdminOrdersRoutes(adapter, deps) {
|
|
|
2002
4600
|
if (!id2) return fail("admin.invalid", "id required", 400);
|
|
2003
4601
|
const current = await order.getById(id2);
|
|
2004
4602
|
if (canTransitionOrder2(current.status, "confirmed") && current.capturedMinor === 0) {
|
|
2005
|
-
throw new
|
|
4603
|
+
throw new OrderConflictError5(
|
|
2006
4604
|
"order.unpaid",
|
|
2007
4605
|
`Order ${current.orderNumber} is unpaid: record its payment to confirm it`
|
|
2008
4606
|
);
|
|
@@ -2125,7 +4723,7 @@ function registerAdminOrdersRoutes(adapter, deps) {
|
|
|
2125
4723
|
requireRole("admin", async (ctx) => {
|
|
2126
4724
|
const id2 = ctx.params.id;
|
|
2127
4725
|
if (!id2) return fail("admin.invalid", "id required", 400);
|
|
2128
|
-
return answerHistory(history, ctx, () => historySubject(id2),
|
|
4726
|
+
return answerHistory(history, ctx, () => historySubject(id2), notFound3(id2));
|
|
2129
4727
|
})
|
|
2130
4728
|
);
|
|
2131
4729
|
adapter.registerRoute(
|
|
@@ -2200,7 +4798,8 @@ function registerAdminOrdersRoutes(adapter, deps) {
|
|
|
2200
4798
|
try {
|
|
2201
4799
|
const id2 = ctx.params.id;
|
|
2202
4800
|
if (!id2) return fail("admin.invalid", "id required", 400);
|
|
2203
|
-
|
|
4801
|
+
const queued = await order.resendConfirmation(id2);
|
|
4802
|
+
return ok({ orderId: queued.id, orderNumber: queued.orderNumber, email: queued.email });
|
|
2204
4803
|
} catch (err) {
|
|
2205
4804
|
return renderError(err);
|
|
2206
4805
|
}
|
|
@@ -2210,13 +4809,13 @@ function registerAdminOrdersRoutes(adapter, deps) {
|
|
|
2210
4809
|
|
|
2211
4810
|
// src/routes/admin-products.ts
|
|
2212
4811
|
import {
|
|
2213
|
-
NotFoundError as
|
|
4812
|
+
NotFoundError as NotFoundError12
|
|
2214
4813
|
} from "@nymbalhq/types";
|
|
2215
4814
|
async function orNull(found) {
|
|
2216
4815
|
try {
|
|
2217
4816
|
return await found;
|
|
2218
4817
|
} catch (err) {
|
|
2219
|
-
if (err instanceof
|
|
4818
|
+
if (err instanceof NotFoundError12) return null;
|
|
2220
4819
|
throw err;
|
|
2221
4820
|
}
|
|
2222
4821
|
}
|
|
@@ -2229,7 +4828,7 @@ function registerAdminProductsRoutes(adapter, deps) {
|
|
|
2229
4828
|
const live = await findProduct(idOrSlug);
|
|
2230
4829
|
return { kind: "product", id: live?.id ?? idOrSlug, live: live !== null };
|
|
2231
4830
|
}
|
|
2232
|
-
const
|
|
4831
|
+
const notFound3 = (idOrSlug) => () => fail("not_found", `product not found: ${idOrSlug}`, 404);
|
|
2233
4832
|
adapter.registerRoute(
|
|
2234
4833
|
"GET",
|
|
2235
4834
|
"/api/admin/products",
|
|
@@ -2280,10 +4879,10 @@ function registerAdminProductsRoutes(adapter, deps) {
|
|
|
2280
4879
|
if (!idOrSlug) return fail("admin.invalid", "id required", 400);
|
|
2281
4880
|
const at = atOf(ctx);
|
|
2282
4881
|
if (at !== void 0) {
|
|
2283
|
-
return answerAsOf(history, at, () => historySubject(idOrSlug),
|
|
4882
|
+
return answerAsOf(history, at, () => historySubject(idOrSlug), notFound3(idOrSlug));
|
|
2284
4883
|
}
|
|
2285
4884
|
const found = await findProduct(idOrSlug);
|
|
2286
|
-
return found === null ?
|
|
4885
|
+
return found === null ? notFound3(idOrSlug)() : ok(found);
|
|
2287
4886
|
} catch (err) {
|
|
2288
4887
|
return renderError(err);
|
|
2289
4888
|
}
|
|
@@ -2295,7 +4894,7 @@ function registerAdminProductsRoutes(adapter, deps) {
|
|
|
2295
4894
|
requireRole("admin", async (ctx) => {
|
|
2296
4895
|
const idOrSlug = ctx.params.id;
|
|
2297
4896
|
if (!idOrSlug) return fail("admin.invalid", "id required", 400);
|
|
2298
|
-
return answerHistory(history, ctx, () => historySubject(idOrSlug),
|
|
4897
|
+
return answerHistory(history, ctx, () => historySubject(idOrSlug), notFound3(idOrSlug));
|
|
2299
4898
|
})
|
|
2300
4899
|
);
|
|
2301
4900
|
adapter.registerRoute(
|
|
@@ -2591,7 +5190,7 @@ function registerAdminCustomersRoutes(adapter, deps) {
|
|
|
2591
5190
|
const found = await store.read((tx) => repos.customer.findById(tx, id2));
|
|
2592
5191
|
return { kind: "customer", id: id2, live: found !== null };
|
|
2593
5192
|
}
|
|
2594
|
-
const
|
|
5193
|
+
const notFound3 = (id2) => () => fail("customers.not_found", `Customer not found: ${id2}`, 404);
|
|
2595
5194
|
adapter.registerRoute(
|
|
2596
5195
|
"GET",
|
|
2597
5196
|
"/api/admin/customers",
|
|
@@ -2643,7 +5242,7 @@ function registerAdminCustomersRoutes(adapter, deps) {
|
|
|
2643
5242
|
const id2 = ctx.params.id;
|
|
2644
5243
|
if (!id2) return fail("admin.invalid", "id required", 400);
|
|
2645
5244
|
const at = atOf(ctx);
|
|
2646
|
-
if (at !== void 0) return answerAsOf(history, at, () => historySubject(id2),
|
|
5245
|
+
if (at !== void 0) return answerAsOf(history, at, () => historySubject(id2), notFound3(id2));
|
|
2647
5246
|
const found = await store.read(async (tx) => {
|
|
2648
5247
|
const raw = await repos.customer.findById(tx, id2);
|
|
2649
5248
|
return raw ? { raw, orders: await repos.order.listByCustomer(tx, id2) } : null;
|
|
@@ -2664,7 +5263,7 @@ function registerAdminCustomersRoutes(adapter, deps) {
|
|
|
2664
5263
|
requireRole("admin", async (ctx) => {
|
|
2665
5264
|
const id2 = ctx.params.id;
|
|
2666
5265
|
if (!id2) return fail("admin.invalid", "id required", 400);
|
|
2667
|
-
return answerHistory(history, ctx, () => historySubject(id2),
|
|
5266
|
+
return answerHistory(history, ctx, () => historySubject(id2), notFound3(id2));
|
|
2668
5267
|
})
|
|
2669
5268
|
);
|
|
2670
5269
|
adapter.registerRoute(
|
|
@@ -2815,7 +5414,7 @@ import {
|
|
|
2815
5414
|
} from "@nymbalhq/types";
|
|
2816
5415
|
|
|
2817
5416
|
// src/settings/crypto.ts
|
|
2818
|
-
import { createCipheriv, createDecipheriv, createHash as
|
|
5417
|
+
import { createCipheriv, createDecipheriv, createHash as createHash4, randomBytes as randomBytes3 } from "crypto";
|
|
2819
5418
|
var ALGORITHM = "aes-256-gcm";
|
|
2820
5419
|
var IV_BYTES = 12;
|
|
2821
5420
|
var TAG_BYTES = 16;
|
|
@@ -2823,7 +5422,7 @@ var KEY_BYTES = 32;
|
|
|
2823
5422
|
var SECRETS_KEY_ENV = "NYMBAL_SECRETS_KEY";
|
|
2824
5423
|
var SECRETS_KEY_OLD_ENV = "NYMBAL_SECRETS_KEY_OLD";
|
|
2825
5424
|
function encrypt(key, aad, plaintext) {
|
|
2826
|
-
const iv =
|
|
5425
|
+
const iv = randomBytes3(IV_BYTES);
|
|
2827
5426
|
const cipher = createCipheriv(ALGORITHM, key, iv, { authTagLength: TAG_BYTES });
|
|
2828
5427
|
cipher.setAAD(Buffer.from(aad, "utf8"));
|
|
2829
5428
|
const ciphertext = Buffer.concat([cipher.update(plaintext, "utf8"), cipher.final()]);
|
|
@@ -2843,7 +5442,7 @@ function decrypt(key, aad, row) {
|
|
|
2843
5442
|
);
|
|
2844
5443
|
}
|
|
2845
5444
|
function keyId(key) {
|
|
2846
|
-
return
|
|
5445
|
+
return createHash4("sha256").update(key).digest("hex").slice(0, 8);
|
|
2847
5446
|
}
|
|
2848
5447
|
var BASE64_32 = /^[A-Za-z0-9+/]{43}=?$/;
|
|
2849
5448
|
function readSecretsKey(env, name = SECRETS_KEY_ENV) {
|
|
@@ -3013,16 +5612,16 @@ function createMiddlewareSecurityAdapter(deps) {
|
|
|
3013
5612
|
}
|
|
3014
5613
|
|
|
3015
5614
|
// src/adapters/payments/native-stub.ts
|
|
3016
|
-
import { v7 as
|
|
5615
|
+
import { v7 as uuidv714 } from "uuid";
|
|
3017
5616
|
import {
|
|
3018
|
-
EVT_PAYMENT_CAPTURED,
|
|
3019
|
-
EVT_PAYMENT_FAILED,
|
|
3020
|
-
EVT_PAYMENT_REFUNDED as
|
|
3021
|
-
PaymentError as
|
|
5617
|
+
EVT_PAYMENT_CAPTURED as EVT_PAYMENT_CAPTURED2,
|
|
5618
|
+
EVT_PAYMENT_FAILED as EVT_PAYMENT_FAILED2,
|
|
5619
|
+
EVT_PAYMENT_REFUNDED as EVT_PAYMENT_REFUNDED3,
|
|
5620
|
+
PaymentError as PaymentError3
|
|
3022
5621
|
} from "@nymbalhq/types";
|
|
3023
5622
|
var STUB_ID_PREFIX = "pi_stub_";
|
|
3024
5623
|
function rejected(message) {
|
|
3025
|
-
return new
|
|
5624
|
+
return new PaymentError3("refund_rejected", message);
|
|
3026
5625
|
}
|
|
3027
5626
|
function statusFor(receiptEmail) {
|
|
3028
5627
|
const address2 = receiptEmail ?? "";
|
|
@@ -3052,12 +5651,12 @@ function createNativeStubPaymentsAdapter(deps) {
|
|
|
3052
5651
|
capabilities: () => ["intent", "capture", "refund"],
|
|
3053
5652
|
// Nothing to collect: the receipt email decides the outcome.
|
|
3054
5653
|
client: () => ({ driver: "test-mode", options: {} }),
|
|
3055
|
-
producesEvents: [
|
|
5654
|
+
producesEvents: [EVT_PAYMENT_CAPTURED2, EVT_PAYMENT_FAILED2, EVT_PAYMENT_REFUNDED3],
|
|
3056
5655
|
consumesEvents: [],
|
|
3057
5656
|
initialize: noopInitialize,
|
|
3058
5657
|
healthCheck: () => okHealth("stub \u2014 always healthy"),
|
|
3059
5658
|
async createPaymentIntent(params) {
|
|
3060
|
-
const id2 = `${STUB_ID_PREFIX}${
|
|
5659
|
+
const id2 = `${STUB_ID_PREFIX}${uuidv714()}`;
|
|
3061
5660
|
const intent = {
|
|
3062
5661
|
id: id2,
|
|
3063
5662
|
amountMinor: params.amountMinor,
|
|
@@ -3072,7 +5671,7 @@ function createNativeStubPaymentsAdapter(deps) {
|
|
|
3072
5671
|
},
|
|
3073
5672
|
async capturePayment(intentId) {
|
|
3074
5673
|
const intent = intents.get(intentId);
|
|
3075
|
-
if (!intent) throw new
|
|
5674
|
+
if (!intent) throw new PaymentError3("capture_failed", `unknown intent ${intentId}`);
|
|
3076
5675
|
intent.status = "succeeded";
|
|
3077
5676
|
return {
|
|
3078
5677
|
paymentId: intent.id,
|
|
@@ -3091,7 +5690,7 @@ function createNativeStubPaymentsAdapter(deps) {
|
|
|
3091
5690
|
if (!paymentId.startsWith(STUB_ID_PREFIX)) throw rejected(`${paymentId} is not a stub intent`);
|
|
3092
5691
|
const answer = (amount2, currency) => {
|
|
3093
5692
|
const refund = {
|
|
3094
|
-
refundId: `re_stub_${
|
|
5693
|
+
refundId: `re_stub_${uuidv714()}`,
|
|
3095
5694
|
paymentId,
|
|
3096
5695
|
amountMinor: amount2,
|
|
3097
5696
|
currency,
|
|
@@ -3122,14 +5721,14 @@ function createNativeStubPaymentsAdapter(deps) {
|
|
|
3122
5721
|
},
|
|
3123
5722
|
async getPaymentIntent(intentId) {
|
|
3124
5723
|
const intent = intents.get(intentId);
|
|
3125
|
-
if (!intent) throw new
|
|
5724
|
+
if (!intent) throw new PaymentError3("intent_failed", `unknown intent ${intentId}`);
|
|
3126
5725
|
return toIntent(intent);
|
|
3127
5726
|
},
|
|
3128
5727
|
async cancelPaymentIntent(intentId) {
|
|
3129
5728
|
const intent = intents.get(intentId);
|
|
3130
5729
|
if (!intent) return;
|
|
3131
5730
|
if (intent.status === "succeeded") {
|
|
3132
|
-
throw new
|
|
5731
|
+
throw new PaymentError3("cancel_refused", `intent ${intentId} is already captured`);
|
|
3133
5732
|
}
|
|
3134
5733
|
intent.status = "cancelled";
|
|
3135
5734
|
},
|
|
@@ -3141,14 +5740,14 @@ function createNativeStubPaymentsAdapter(deps) {
|
|
|
3141
5740
|
if (held !== void 0 && event.kind === "payment.captured") held.status = "succeeded";
|
|
3142
5741
|
return {
|
|
3143
5742
|
verified: true,
|
|
3144
|
-
eventId: event.id ?? `evt_stub_${
|
|
5743
|
+
eventId: event.id ?? `evt_stub_${uuidv714()}`,
|
|
3145
5744
|
kind: event.kind ?? "ignored",
|
|
3146
5745
|
...event.paymentIntentId !== void 0 && { paymentIntentId: event.paymentIntentId },
|
|
3147
5746
|
...event.amountMinor !== void 0 && { amountMinor: event.amountMinor },
|
|
3148
5747
|
...event.currency !== void 0 && { currency: event.currency }
|
|
3149
5748
|
};
|
|
3150
5749
|
} catch (err) {
|
|
3151
|
-
throw new
|
|
5750
|
+
throw new PaymentError3("webhook_invalid", "stub webhook body not JSON", { cause: err });
|
|
3152
5751
|
}
|
|
3153
5752
|
}
|
|
3154
5753
|
};
|
|
@@ -3157,9 +5756,9 @@ function createNativeStubPaymentsAdapter(deps) {
|
|
|
3157
5756
|
// src/adapters/email/native-email-adapter.ts
|
|
3158
5757
|
import {
|
|
3159
5758
|
EVT_CART_ABANDONED,
|
|
3160
|
-
EVT_CUSTOMER_CREATED,
|
|
3161
|
-
EVT_ORDER_PLACED,
|
|
3162
|
-
EVT_ORDER_SHIPPED,
|
|
5759
|
+
EVT_CUSTOMER_CREATED as EVT_CUSTOMER_CREATED2,
|
|
5760
|
+
EVT_ORDER_PLACED as EVT_ORDER_PLACED2,
|
|
5761
|
+
EVT_ORDER_SHIPPED as EVT_ORDER_SHIPPED2,
|
|
3163
5762
|
renderEmailTemplate
|
|
3164
5763
|
} from "@nymbalhq/types";
|
|
3165
5764
|
function createNativeEmailAdapter(deps) {
|
|
@@ -3169,7 +5768,7 @@ function createNativeEmailAdapter(deps) {
|
|
|
3169
5768
|
providerName: "native",
|
|
3170
5769
|
capabilities: () => ["transactional", "list-sync"],
|
|
3171
5770
|
producesEvents: [],
|
|
3172
|
-
consumesEvents: [
|
|
5771
|
+
consumesEvents: [EVT_ORDER_PLACED2, EVT_ORDER_SHIPPED2, EVT_CUSTOMER_CREATED2, EVT_CART_ABANDONED],
|
|
3173
5772
|
async initialize() {
|
|
3174
5773
|
},
|
|
3175
5774
|
healthCheck: () => okHealth("console transport"),
|
|
@@ -3193,10 +5792,10 @@ function createNativeEmailAdapter(deps) {
|
|
|
3193
5792
|
|
|
3194
5793
|
// src/adapters/search/native-adapter.ts
|
|
3195
5794
|
import {
|
|
3196
|
-
EVT_PRODUCT_CREATED,
|
|
3197
|
-
EVT_PRODUCT_DELETED,
|
|
3198
|
-
EVT_PRODUCT_UPDATED,
|
|
3199
|
-
ValidationError as
|
|
5795
|
+
EVT_PRODUCT_CREATED as EVT_PRODUCT_CREATED2,
|
|
5796
|
+
EVT_PRODUCT_DELETED as EVT_PRODUCT_DELETED2,
|
|
5797
|
+
EVT_PRODUCT_UPDATED as EVT_PRODUCT_UPDATED2,
|
|
5798
|
+
ValidationError as ValidationError10
|
|
3200
5799
|
} from "@nymbalhq/types";
|
|
3201
5800
|
|
|
3202
5801
|
// src/adapters/search/terms.ts
|
|
@@ -3480,7 +6079,7 @@ function decodeSearchCursor(cursor) {
|
|
|
3480
6079
|
const text = Buffer.from(cursor, "base64url").toString("utf8");
|
|
3481
6080
|
const offset = Number(text);
|
|
3482
6081
|
if (!/^\d+$/.test(text) || !Number.isSafeInteger(offset) || encodeSearchCursor(offset) !== cursor) {
|
|
3483
|
-
throw new
|
|
6082
|
+
throw new ValidationError10("malformed search cursor");
|
|
3484
6083
|
}
|
|
3485
6084
|
return offset;
|
|
3486
6085
|
}
|
|
@@ -3505,7 +6104,7 @@ function createNativeSearchAdapter(deps) {
|
|
|
3505
6104
|
providerName: "native",
|
|
3506
6105
|
capabilities: () => ["index", "search", "facet"],
|
|
3507
6106
|
producesEvents: [],
|
|
3508
|
-
consumesEvents: [
|
|
6107
|
+
consumesEvents: [EVT_PRODUCT_CREATED2, EVT_PRODUCT_UPDATED2, EVT_PRODUCT_DELETED2],
|
|
3509
6108
|
initialize: noopInitialize,
|
|
3510
6109
|
healthCheck: () => okHealth(),
|
|
3511
6110
|
async index(documents) {
|
|
@@ -3554,10 +6153,10 @@ function createNativeSearchAdapter(deps) {
|
|
|
3554
6153
|
}
|
|
3555
6154
|
|
|
3556
6155
|
// src/adapters/reviews/native-adapter.ts
|
|
3557
|
-
import { v7 as
|
|
6156
|
+
import { v7 as uuidv715 } from "uuid";
|
|
3558
6157
|
import {
|
|
3559
|
-
EVT_ORDER_DELIVERED,
|
|
3560
|
-
ValidationError as
|
|
6158
|
+
EVT_ORDER_DELIVERED as EVT_ORDER_DELIVERED2,
|
|
6159
|
+
ValidationError as ValidationError11
|
|
3561
6160
|
} from "@nymbalhq/types";
|
|
3562
6161
|
function encodeReviewCursor(review) {
|
|
3563
6162
|
return Buffer.from(JSON.stringify([review.submittedAt, review.id]), "utf8").toString("base64url");
|
|
@@ -3567,10 +6166,10 @@ function decodeReviewCursor(cursor) {
|
|
|
3567
6166
|
try {
|
|
3568
6167
|
key = JSON.parse(Buffer.from(cursor, "base64url").toString("utf8"));
|
|
3569
6168
|
} catch (err) {
|
|
3570
|
-
throw new
|
|
6169
|
+
throw new ValidationError11("malformed reviews cursor", { cause: err });
|
|
3571
6170
|
}
|
|
3572
6171
|
if (!Array.isArray(key) || key.length !== 2 || typeof key[0] !== "string" || typeof key[1] !== "string" || Number.isNaN(Date.parse(key[0])) || Buffer.from(JSON.stringify(key), "utf8").toString("base64url") !== cursor) {
|
|
3573
|
-
throw new
|
|
6172
|
+
throw new ValidationError11("malformed reviews cursor");
|
|
3574
6173
|
}
|
|
3575
6174
|
return { submittedAt: key[0], id: key[1] };
|
|
3576
6175
|
}
|
|
@@ -3581,7 +6180,7 @@ function createNativeReviewsAdapter(deps) {
|
|
|
3581
6180
|
providerName: "native",
|
|
3582
6181
|
capabilities: () => ["submit", "moderate", "aggregate"],
|
|
3583
6182
|
producesEvents: [],
|
|
3584
|
-
consumesEvents: [
|
|
6183
|
+
consumesEvents: [EVT_ORDER_DELIVERED2],
|
|
3585
6184
|
initialize: noopInitialize,
|
|
3586
6185
|
healthCheck: () => okHealth(),
|
|
3587
6186
|
async getProductReviews(productId, params) {
|
|
@@ -3602,7 +6201,7 @@ function createNativeReviewsAdapter(deps) {
|
|
|
3602
6201
|
return { productId, ...agg };
|
|
3603
6202
|
},
|
|
3604
6203
|
async submitReview(submission) {
|
|
3605
|
-
const id2 =
|
|
6204
|
+
const id2 = uuidv715();
|
|
3606
6205
|
const now = /* @__PURE__ */ new Date();
|
|
3607
6206
|
const review = await repos.review.store.transaction(async (tx) => {
|
|
3608
6207
|
await repos.review.insert(tx, {
|
|
@@ -3709,7 +6308,7 @@ function createNativeTaxAdapter(logger, defaultRate = 0) {
|
|
|
3709
6308
|
}
|
|
3710
6309
|
|
|
3711
6310
|
// src/adapters/not-configured.ts
|
|
3712
|
-
import { AdapterError as
|
|
6311
|
+
import { AdapterError as AdapterError3 } from "@nymbalhq/types";
|
|
3713
6312
|
function createNotConfiguredAdapter(slot, provider, missing) {
|
|
3714
6313
|
const fields = missing.map((path) => `${slot}.${path}`).join(", ");
|
|
3715
6314
|
const detail = `${provider} is not configured: ${fields} not set (in the config, the environment or the admin's Settings)`;
|
|
@@ -3727,7 +6326,7 @@ function createNotConfiguredAdapter(slot, provider, missing) {
|
|
|
3727
6326
|
...slot === "payments" && { client: () => ({ driver: provider, options: {} }) }
|
|
3728
6327
|
};
|
|
3729
6328
|
const refuse = async () => {
|
|
3730
|
-
throw new
|
|
6329
|
+
throw new AdapterError3("not_configured", detail, { context: { slot, provider, missing } });
|
|
3731
6330
|
};
|
|
3732
6331
|
return new Proxy(base, {
|
|
3733
6332
|
get(target, property, receiver) {
|
|
@@ -4242,52 +6841,6 @@ import {
|
|
|
4242
6841
|
canTransitionOrder as canTransitionOrder3,
|
|
4243
6842
|
paymentState as paymentState3
|
|
4244
6843
|
} from "@nymbalhq/types";
|
|
4245
|
-
|
|
4246
|
-
// src/history/views.ts
|
|
4247
|
-
import {
|
|
4248
|
-
paymentState as paymentState2
|
|
4249
|
-
} from "@nymbalhq/types";
|
|
4250
|
-
function orderViewOf(order) {
|
|
4251
|
-
const {
|
|
4252
|
-
notes: _notes,
|
|
4253
|
-
metadata: _metadata,
|
|
4254
|
-
updatedAt: _updatedAt,
|
|
4255
|
-
capturedAt: _capturedAt,
|
|
4256
|
-
captureMethod: _captureMethod,
|
|
4257
|
-
...rest
|
|
4258
|
-
} = order;
|
|
4259
|
-
const { payment: _payment, history: _history, ...view } = rest;
|
|
4260
|
-
return {
|
|
4261
|
-
...view,
|
|
4262
|
-
payment: {
|
|
4263
|
-
state: paymentState2(order),
|
|
4264
|
-
capturedMinor: order.capturedMinor,
|
|
4265
|
-
refundedMinor: order.refundedMinor,
|
|
4266
|
-
currency: order.currency
|
|
4267
|
-
}
|
|
4268
|
-
};
|
|
4269
|
-
}
|
|
4270
|
-
function toProductAsOf(snapshot) {
|
|
4271
|
-
return {
|
|
4272
|
-
...snapshot,
|
|
4273
|
-
variants: snapshot.variants.map(({ updatedAt: _updatedAt, ...variant }) => variant),
|
|
4274
|
-
// A set: product.created keeps the order it was sent in, a read the repository's.
|
|
4275
|
-
categoryIds: [...snapshot.categoryIds].sort()
|
|
4276
|
-
};
|
|
4277
|
-
}
|
|
4278
|
-
function toCustomerSnapshot(customer) {
|
|
4279
|
-
return {
|
|
4280
|
-
id: customer.id,
|
|
4281
|
-
email: customer.email,
|
|
4282
|
-
firstName: customer.firstName,
|
|
4283
|
-
lastName: customer.lastName,
|
|
4284
|
-
phone: customer.phone,
|
|
4285
|
-
addresses: customer.addresses,
|
|
4286
|
-
createdAt: customer.createdAt
|
|
4287
|
-
};
|
|
4288
|
-
}
|
|
4289
|
-
|
|
4290
|
-
// src/history/fold.ts
|
|
4291
6844
|
function eventName(type) {
|
|
4292
6845
|
return type.replace(/\.v\d+$/, "");
|
|
4293
6846
|
}
|
|
@@ -4712,7 +7265,7 @@ function registerAdminStaticRoute(adapter, root) {
|
|
|
4712
7265
|
}
|
|
4713
7266
|
|
|
4714
7267
|
// src/routes/events-sse.ts
|
|
4715
|
-
import { createHmac, randomBytes as
|
|
7268
|
+
import { createHmac, randomBytes as randomBytes4 } from "crypto";
|
|
4716
7269
|
import "@nymbalhq/types";
|
|
4717
7270
|
var TICKET_TTL_SECONDS = 60;
|
|
4718
7271
|
var NONCE_COLLECTION = "sse-ticket-nonces";
|
|
@@ -4739,7 +7292,7 @@ function registerEventsSseRoute(adapter, deps) {
|
|
|
4739
7292
|
"/api/admin/events/ticket",
|
|
4740
7293
|
requireRole("admin", (ctx) => {
|
|
4741
7294
|
try {
|
|
4742
|
-
const nonce =
|
|
7295
|
+
const nonce = randomBytes4(12).toString("base64url");
|
|
4743
7296
|
const payload = {
|
|
4744
7297
|
uid: ctx.auth.userId,
|
|
4745
7298
|
roles: ctx.auth.roles ?? ["admin"],
|
|
@@ -4808,35 +7361,68 @@ function registerEventsSseRoute(adapter, deps) {
|
|
|
4808
7361
|
void fail;
|
|
4809
7362
|
}
|
|
4810
7363
|
|
|
4811
|
-
// src/routes/webhooks-
|
|
7364
|
+
// src/routes/webhooks-inbound.ts
|
|
4812
7365
|
import {
|
|
4813
|
-
|
|
4814
|
-
|
|
7366
|
+
ConfigError as ConfigError5,
|
|
7367
|
+
EVT_PAYMENT_FAILED as EVT_PAYMENT_FAILED3,
|
|
7368
|
+
webhookDeliveryProblem
|
|
4815
7369
|
} from "@nymbalhq/types";
|
|
4816
|
-
|
|
4817
|
-
|
|
4818
|
-
|
|
4819
|
-
|
|
4820
|
-
|
|
4821
|
-
|
|
4822
|
-
|
|
4823
|
-
|
|
4824
|
-
|
|
4825
|
-
|
|
4826
|
-
|
|
4827
|
-
|
|
7370
|
+
var PAYMENTS_ALIAS = "stripe";
|
|
7371
|
+
function isHooked(adapter) {
|
|
7372
|
+
return "receiveWebhook" in adapter && typeof adapter.receiveWebhook === "function";
|
|
7373
|
+
}
|
|
7374
|
+
function webhookTargets(adapters) {
|
|
7375
|
+
const bySlot = /* @__PURE__ */ new Map();
|
|
7376
|
+
const hookless = /* @__PURE__ */ new Map();
|
|
7377
|
+
const add = (name, target) => {
|
|
7378
|
+
const slots = bySlot.get(name) ?? /* @__PURE__ */ new Map();
|
|
7379
|
+
slots.set(target.slot, target);
|
|
7380
|
+
bySlot.set(name, slots);
|
|
7381
|
+
};
|
|
7382
|
+
const payments = { kind: "payments", slot: "payments", adapter: adapters.payments };
|
|
7383
|
+
add(PAYMENTS_ALIAS, payments);
|
|
7384
|
+
add(adapters.payments.providerName, payments);
|
|
7385
|
+
for (const slot of COMMERCE_SLOTS) {
|
|
7386
|
+
const adapter = adapters[slot];
|
|
7387
|
+
if (slot === "payments" || adapter === null) continue;
|
|
7388
|
+
if (isHooked(adapter)) add(adapter.providerName, { kind: "hooked", slot, adapter });
|
|
7389
|
+
else hookless.set(adapter.providerName, [...hookless.get(adapter.providerName) ?? [], slot]);
|
|
7390
|
+
}
|
|
7391
|
+
const hooked = /* @__PURE__ */ new Map();
|
|
7392
|
+
for (const [name, slots] of bySlot) {
|
|
7393
|
+
if (slots.size > 1) {
|
|
7394
|
+
const names = [...slots.keys()];
|
|
7395
|
+
throw new ConfigError5(
|
|
7396
|
+
`webhook provider '${name}' is taken by more than one slot that receives webhooks: ${names.join(" and ")}`,
|
|
7397
|
+
{ code: "config.webhook_provider_ambiguous", context: { name, slots: names } }
|
|
7398
|
+
);
|
|
7399
|
+
}
|
|
7400
|
+
hooked.set(name, [...slots.values()][0]);
|
|
7401
|
+
}
|
|
7402
|
+
return { hooked, hookless };
|
|
7403
|
+
}
|
|
7404
|
+
function isWebhookInvalid(err) {
|
|
7405
|
+
const code = err?.code;
|
|
7406
|
+
return typeof code === "string" && code.endsWith("webhook_invalid");
|
|
7407
|
+
}
|
|
7408
|
+
var invalid = () => fail("webhook.invalid", "signature verification failed", 400);
|
|
7409
|
+
var notFound2 = () => fail("webhook.not_found", "no webhook is received under this name", 404);
|
|
7410
|
+
var noRawBody = () => fail("webhook.raw_body_missing", "the HTTP adapter kept no raw request body", 500);
|
|
7411
|
+
function registerInboundWebhookRoute(adapter, deps) {
|
|
7412
|
+
const { checkout, publisher, store, processedEvents, orders } = deps;
|
|
7413
|
+
const targets = webhookTargets(deps.adapters);
|
|
4828
7414
|
async function publishFailed(tx, paymentIntentId, reason) {
|
|
4829
7415
|
const order = paymentIntentId ? await orders.findByPaymentIntentId(tx, paymentIntentId) : null;
|
|
4830
7416
|
await inOrderScope(
|
|
4831
7417
|
order,
|
|
4832
|
-
() => publisher.publish(
|
|
7418
|
+
() => publisher.publish(EVT_PAYMENT_FAILED3, {
|
|
4833
7419
|
paymentId: paymentIntentId,
|
|
4834
7420
|
orderId: order?.id ?? "",
|
|
4835
7421
|
reason
|
|
4836
7422
|
})
|
|
4837
7423
|
);
|
|
4838
7424
|
}
|
|
4839
|
-
async function
|
|
7425
|
+
async function handlePayment(tx, result) {
|
|
4840
7426
|
if (result.kind === "payment.captured") {
|
|
4841
7427
|
const paymentIntentId = result.paymentIntentId ?? "";
|
|
4842
7428
|
if (paymentIntentId === "" || typeof result.amountMinor !== "number" || typeof result.currency !== "string" || result.currency === "") {
|
|
@@ -4855,49 +7441,101 @@ function registerStripeWebhookRoute(adapter, deps) {
|
|
|
4855
7441
|
}
|
|
4856
7442
|
return ok({ ignored: true });
|
|
4857
7443
|
}
|
|
7444
|
+
async function receivePayment(ctx, name, payments) {
|
|
7445
|
+
const rawSig = ctx.headers["stripe-signature"];
|
|
7446
|
+
const sig = Array.isArray(rawSig) ? rawSig[0] : rawSig;
|
|
7447
|
+
if (!sig) return fail("webhook.signature_missing", "stripe-signature header missing", 400);
|
|
7448
|
+
if (ctx.rawBody === void 0) return noRawBody();
|
|
7449
|
+
let result;
|
|
7450
|
+
try {
|
|
7451
|
+
result = await payments.parseWebhook(ctx.rawBody, sig);
|
|
7452
|
+
} catch (err) {
|
|
7453
|
+
if (isWebhookInvalid(err)) return invalid();
|
|
7454
|
+
throw err;
|
|
7455
|
+
}
|
|
7456
|
+
if (!result.verified) return invalid();
|
|
7457
|
+
return store.transaction(async (tx) => {
|
|
7458
|
+
if (!await processedEvents.claim(tx, `webhook:${name}`, result.eventId, /* @__PURE__ */ new Date())) {
|
|
7459
|
+
return ok({ deduped: true });
|
|
7460
|
+
}
|
|
7461
|
+
return handlePayment(tx, result);
|
|
7462
|
+
});
|
|
7463
|
+
}
|
|
7464
|
+
async function receiveHooked(ctx, name, target) {
|
|
7465
|
+
if (ctx.rawBody === void 0) return noRawBody();
|
|
7466
|
+
let delivery;
|
|
7467
|
+
try {
|
|
7468
|
+
delivery = await target.adapter.receiveWebhook(ctx.rawBody, ctx.headers);
|
|
7469
|
+
} catch (err) {
|
|
7470
|
+
if (isWebhookInvalid(err)) return invalid();
|
|
7471
|
+
throw err;
|
|
7472
|
+
}
|
|
7473
|
+
if (!delivery.verified) return invalid();
|
|
7474
|
+
const problem = webhookDeliveryProblem(
|
|
7475
|
+
target.adapter.providerName,
|
|
7476
|
+
target.adapter.producesEvents,
|
|
7477
|
+
delivery
|
|
7478
|
+
);
|
|
7479
|
+
if (problem !== null) {
|
|
7480
|
+
ctx.logger.warn(
|
|
7481
|
+
{ webhook: name, slot: target.slot, type: problem.type, reason: problem.reason },
|
|
7482
|
+
"a webhook delivery was refused: its events break the adapter event rule"
|
|
7483
|
+
);
|
|
7484
|
+
return fail(
|
|
7485
|
+
"webhook.event_invalid",
|
|
7486
|
+
`the delivery's events are refused: ${problem.reason}`,
|
|
7487
|
+
500
|
|
7488
|
+
);
|
|
7489
|
+
}
|
|
7490
|
+
const handler = `webhook:${name}`;
|
|
7491
|
+
return store.transaction(async (tx) => {
|
|
7492
|
+
if (!await processedEvents.claim(tx, handler, delivery.deliveryId, /* @__PURE__ */ new Date())) {
|
|
7493
|
+
return ok({ deduped: true });
|
|
7494
|
+
}
|
|
7495
|
+
audit.note("webhook.receive", [{ type: "webhook", id: `${name}:${delivery.deliveryId}` }]);
|
|
7496
|
+
await publisher.publishUntyped(
|
|
7497
|
+
delivery.events.map(({ type, payload }) => ({ type, payload })),
|
|
7498
|
+
{ source: handler }
|
|
7499
|
+
);
|
|
7500
|
+
return ok({ received: true, events: delivery.events.length });
|
|
7501
|
+
});
|
|
7502
|
+
}
|
|
4858
7503
|
adapter.registerRoute(
|
|
4859
7504
|
"POST",
|
|
4860
|
-
"/api/webhooks
|
|
4861
|
-
|
|
4862
|
-
|
|
4863
|
-
|
|
4864
|
-
|
|
4865
|
-
|
|
4866
|
-
|
|
4867
|
-
|
|
4868
|
-
|
|
4869
|
-
|
|
4870
|
-
|
|
4871
|
-
);
|
|
4872
|
-
}
|
|
4873
|
-
let result;
|
|
4874
|
-
try {
|
|
4875
|
-
result = await payments.parseWebhook(ctx.rawBody, sig);
|
|
4876
|
-
} catch (err) {
|
|
4877
|
-
if (err instanceof PaymentError3 && err.code === "payment.webhook_invalid") {
|
|
4878
|
-
return fail("webhook.invalid", "signature verification failed", 400);
|
|
4879
|
-
}
|
|
4880
|
-
throw err;
|
|
4881
|
-
}
|
|
4882
|
-
if (!result.verified) return fail("webhook.invalid", "signature verification failed", 400);
|
|
4883
|
-
return await store.transaction(async (tx) => {
|
|
4884
|
-
if (await processedEvents.seen(tx, HANDLER, result.eventId))
|
|
4885
|
-
return ok({ deduped: true });
|
|
4886
|
-
const answer = await handle(tx, result);
|
|
4887
|
-
await processedEvents.markProcessed(tx, HANDLER, result.eventId, /* @__PURE__ */ new Date());
|
|
4888
|
-
return answer;
|
|
4889
|
-
});
|
|
4890
|
-
} catch (err) {
|
|
4891
|
-
return renderError(err);
|
|
7505
|
+
"/api/webhooks/:adapter",
|
|
7506
|
+
async (ctx) => {
|
|
7507
|
+
const name = ctx.params["adapter"] ?? "";
|
|
7508
|
+
const target = targets.hooked.get(name);
|
|
7509
|
+
if (target === void 0) {
|
|
7510
|
+
const slots = targets.hookless.get(name);
|
|
7511
|
+
ctx.logger.warn(
|
|
7512
|
+
{ webhook: name, ...slots !== void 0 && { slots } },
|
|
7513
|
+
slots === void 0 ? "a webhook delivery named no provider of this store" : "a webhook delivery named a provider whose adapter takes no webhooks"
|
|
7514
|
+
);
|
|
7515
|
+
return notFound2();
|
|
4892
7516
|
}
|
|
4893
|
-
|
|
7517
|
+
return runAsActor(
|
|
7518
|
+
{ kind: "system", id: `${name}-webhook` },
|
|
7519
|
+
() => auditedRoute(
|
|
7520
|
+
store,
|
|
7521
|
+
target.kind === "payments" ? "payment.finalize" : "webhook.receive",
|
|
7522
|
+
async () => {
|
|
7523
|
+
try {
|
|
7524
|
+
return target.kind === "payments" ? await receivePayment(ctx, name, target.adapter) : await receiveHooked(ctx, name, target);
|
|
7525
|
+
} catch (err) {
|
|
7526
|
+
return renderError(err);
|
|
7527
|
+
}
|
|
7528
|
+
}
|
|
7529
|
+
)
|
|
7530
|
+
);
|
|
7531
|
+
},
|
|
4894
7532
|
{ csrf: false, rawBody: true }
|
|
4895
7533
|
);
|
|
4896
7534
|
}
|
|
4897
7535
|
|
|
4898
7536
|
// src/routes/validated-adapter.ts
|
|
4899
7537
|
import {
|
|
4900
|
-
ConfigError as
|
|
7538
|
+
ConfigError as ConfigError6
|
|
4901
7539
|
} from "@nymbalhq/types";
|
|
4902
7540
|
|
|
4903
7541
|
// src/routes/schemas.ts
|
|
@@ -4946,6 +7584,11 @@ var productVariant = z.object({
|
|
|
4946
7584
|
options: z.array(z.object({ name: z.string(), value: z.string() })),
|
|
4947
7585
|
status: z.enum(["active", "inactive"]).optional()
|
|
4948
7586
|
});
|
|
7587
|
+
var variantPrices = z.object({
|
|
7588
|
+
id,
|
|
7589
|
+
priceMinor: money.min(0),
|
|
7590
|
+
compareAtPriceMinor: money.min(0).nullable().optional()
|
|
7591
|
+
});
|
|
4949
7592
|
var productFields = {
|
|
4950
7593
|
description: z.string().optional(),
|
|
4951
7594
|
shortDescription: z.string().optional(),
|
|
@@ -4994,7 +7637,7 @@ var routeSchemas = {
|
|
|
4994
7637
|
// Store
|
|
4995
7638
|
"GET /api/capabilities": {
|
|
4996
7639
|
name: "capabilities.get",
|
|
4997
|
-
description: "What the store can do, for a storefront: payments client half, search capabilities and
|
|
7640
|
+
description: "What the store can do, for a storefront: payments client half, search capabilities, sort keys and whether email delivers."
|
|
4998
7641
|
},
|
|
4999
7642
|
// Catalogue
|
|
5000
7643
|
"GET /api/categories": {
|
|
@@ -5027,6 +7670,29 @@ var routeSchemas = {
|
|
|
5027
7670
|
params: idParams,
|
|
5028
7671
|
query: z.object({ limit: queryValue, cursor: queryValue })
|
|
5029
7672
|
},
|
|
7673
|
+
// Back-in-stock and price-drop alerts
|
|
7674
|
+
"POST /api/alerts/subscribe": {
|
|
7675
|
+
name: "alerts.subscribe",
|
|
7676
|
+
command: "alert.subscribe",
|
|
7677
|
+
description: "Ask to be emailed when a variant is back in stock (`back_in_stock`) or when its price drops (`price_drop`); a confirmation email is sent first.",
|
|
7678
|
+
body: z.object({
|
|
7679
|
+
email: z.string().trim().max(254).email(),
|
|
7680
|
+
variantId: id,
|
|
7681
|
+
kind: z.enum(["back_in_stock", "price_drop"])
|
|
7682
|
+
})
|
|
7683
|
+
},
|
|
7684
|
+
"POST /api/alerts/confirm": {
|
|
7685
|
+
name: "alerts.confirm",
|
|
7686
|
+
command: "alert.confirm",
|
|
7687
|
+
description: "Confirm an alert subscription with the token from its confirmation email.",
|
|
7688
|
+
body: z.object({ token: z.string().min(1) })
|
|
7689
|
+
},
|
|
7690
|
+
"POST /api/alerts/unsubscribe": {
|
|
7691
|
+
name: "alerts.unsubscribe",
|
|
7692
|
+
command: "alert.unsubscribe",
|
|
7693
|
+
description: "Stop an alert with the unsubscribe token from any of its emails.",
|
|
7694
|
+
body: z.object({ token: z.string().min(1) })
|
|
7695
|
+
},
|
|
5030
7696
|
// Cart
|
|
5031
7697
|
"GET /api/cart": {
|
|
5032
7698
|
name: "cart.get",
|
|
@@ -5074,9 +7740,20 @@ var routeSchemas = {
|
|
|
5074
7740
|
},
|
|
5075
7741
|
"GET /api/orders/:orderNumber": {
|
|
5076
7742
|
name: "orders.get",
|
|
5077
|
-
description: "Get one order by its number.",
|
|
7743
|
+
description: "Get one order by its number, with a key that opens it in the x-nymbal-order-key header or as the order's signed-in customer.",
|
|
5078
7744
|
params: orderNumberParams
|
|
5079
7745
|
},
|
|
7746
|
+
// Recently viewed: the viewer is the bearer's customer or the visitor cookie's, never one the request names.
|
|
7747
|
+
"POST /api/recently-viewed": {
|
|
7748
|
+
name: "recentlyViewed.record",
|
|
7749
|
+
command: null,
|
|
7750
|
+
description: "Record that the shopper viewed a product.",
|
|
7751
|
+
body: z.object({ productId: id })
|
|
7752
|
+
},
|
|
7753
|
+
"GET /api/recently-viewed": {
|
|
7754
|
+
name: "recentlyViewed.list",
|
|
7755
|
+
description: "List the shopper's recently viewed products, newest first."
|
|
7756
|
+
},
|
|
5080
7757
|
// Customer account
|
|
5081
7758
|
"GET /api/customers/me": {
|
|
5082
7759
|
name: "customers.me",
|
|
@@ -5238,7 +7915,7 @@ var routeSchemas = {
|
|
|
5238
7915
|
},
|
|
5239
7916
|
"POST /api/admin/orders/:id/resend-confirmation": {
|
|
5240
7917
|
name: "admin.orders.resendConfirmation",
|
|
5241
|
-
command:
|
|
7918
|
+
command: "order.resendConfirmation",
|
|
5242
7919
|
description: "Resend an order's confirmation email.",
|
|
5243
7920
|
params: orderIdParams
|
|
5244
7921
|
},
|
|
@@ -5274,9 +7951,13 @@ var routeSchemas = {
|
|
|
5274
7951
|
"PATCH /api/admin/products/:id": {
|
|
5275
7952
|
name: "admin.products.update",
|
|
5276
7953
|
command: "product.update",
|
|
5277
|
-
description: "Update a product's fields.",
|
|
7954
|
+
description: "Update a product's fields and its variants' prices; a variant left out keeps its prices, and stock moves only through inventory.",
|
|
5278
7955
|
params: idParams,
|
|
5279
|
-
body: z.object({
|
|
7956
|
+
body: z.object({
|
|
7957
|
+
name: z.string().optional(),
|
|
7958
|
+
...productFields,
|
|
7959
|
+
variants: z.array(variantPrices).optional()
|
|
7960
|
+
})
|
|
5280
7961
|
},
|
|
5281
7962
|
"DELETE /api/admin/products/:id": {
|
|
5282
7963
|
name: "admin.products.delete",
|
|
@@ -5421,10 +8102,12 @@ var routeSchemas = {
|
|
|
5421
8102
|
query: z.object({ since: queryValue, until: queryValue, correlation: queryValue })
|
|
5422
8103
|
},
|
|
5423
8104
|
// Webhooks
|
|
5424
|
-
"POST /api/webhooks
|
|
5425
|
-
name: "webhooks.
|
|
5426
|
-
command:
|
|
5427
|
-
|
|
8105
|
+
"POST /api/webhooks/:adapter": {
|
|
8106
|
+
name: "webhooks.receive",
|
|
8107
|
+
// The route opens its own audit command: payment.finalize for a payments delivery, webhook.receive otherwise.
|
|
8108
|
+
command: null,
|
|
8109
|
+
description: "Receive a signed delivery from a provider, by its name (stripe always names the payments provider).",
|
|
8110
|
+
params: z.object({ adapter: id }),
|
|
5428
8111
|
// The signature covers the raw bytes, and a malformed event is answered by the handler itself.
|
|
5429
8112
|
body: z.unknown()
|
|
5430
8113
|
},
|
|
@@ -5450,7 +8133,7 @@ function schemaFor(method, path) {
|
|
|
5450
8133
|
const key = `${method} ${path}`;
|
|
5451
8134
|
const schema = routeSchemas[key];
|
|
5452
8135
|
if (!schema) {
|
|
5453
|
-
throw new
|
|
8136
|
+
throw new ConfigError6(`route ${key} has no entry in routeSchemas`, {
|
|
5454
8137
|
code: "config.route_schema_missing",
|
|
5455
8138
|
context: { method, path }
|
|
5456
8139
|
});
|
|
@@ -5486,7 +8169,7 @@ function parseInput(schema, ctx) {
|
|
|
5486
8169
|
}
|
|
5487
8170
|
};
|
|
5488
8171
|
}
|
|
5489
|
-
function
|
|
8172
|
+
function invalid2(issues) {
|
|
5490
8173
|
return fail("validation.failed", "The request input is invalid", 400, { issues });
|
|
5491
8174
|
}
|
|
5492
8175
|
function validatedAdapter(adapter) {
|
|
@@ -5498,7 +8181,7 @@ function validatedAdapter(adapter) {
|
|
|
5498
8181
|
path,
|
|
5499
8182
|
async (ctx) => {
|
|
5500
8183
|
const input = parseInput(schema, ctx);
|
|
5501
|
-
return input.ok ? handler(input.ctx) :
|
|
8184
|
+
return input.ok ? handler(input.ctx) : invalid2(input.issues);
|
|
5502
8185
|
},
|
|
5503
8186
|
options
|
|
5504
8187
|
);
|
|
@@ -5648,6 +8331,47 @@ function registerAdminActivityRoutes(adapter, deps) {
|
|
|
5648
8331
|
);
|
|
5649
8332
|
}
|
|
5650
8333
|
|
|
8334
|
+
// src/routes/alerts.ts
|
|
8335
|
+
function originOf(header) {
|
|
8336
|
+
return Array.isArray(header) ? void 0 : header;
|
|
8337
|
+
}
|
|
8338
|
+
function registerAlertRoutes(adapter, deps) {
|
|
8339
|
+
const { alerts } = deps;
|
|
8340
|
+
adapter.registerRoute("POST", "/api/alerts/subscribe", async (ctx) => {
|
|
8341
|
+
try {
|
|
8342
|
+
const body = ctx.body;
|
|
8343
|
+
const answer = await alerts.subscribe({ ...body, origin: originOf(ctx.headers["origin"]) });
|
|
8344
|
+
return ok(answer, void 0, 202);
|
|
8345
|
+
} catch (err) {
|
|
8346
|
+
return renderError(err);
|
|
8347
|
+
}
|
|
8348
|
+
});
|
|
8349
|
+
adapter.registerRoute(
|
|
8350
|
+
"POST",
|
|
8351
|
+
"/api/alerts/confirm",
|
|
8352
|
+
async (ctx) => {
|
|
8353
|
+
try {
|
|
8354
|
+
return ok(await alerts.confirm(ctx.body.token));
|
|
8355
|
+
} catch (err) {
|
|
8356
|
+
return renderError(err);
|
|
8357
|
+
}
|
|
8358
|
+
},
|
|
8359
|
+
{ csrf: false }
|
|
8360
|
+
);
|
|
8361
|
+
adapter.registerRoute(
|
|
8362
|
+
"POST",
|
|
8363
|
+
"/api/alerts/unsubscribe",
|
|
8364
|
+
async (ctx) => {
|
|
8365
|
+
try {
|
|
8366
|
+
return ok(await alerts.unsubscribe(ctx.body.token));
|
|
8367
|
+
} catch (err) {
|
|
8368
|
+
return renderError(err);
|
|
8369
|
+
}
|
|
8370
|
+
},
|
|
8371
|
+
{ csrf: false }
|
|
8372
|
+
);
|
|
8373
|
+
}
|
|
8374
|
+
|
|
5651
8375
|
// src/routes/register.ts
|
|
5652
8376
|
function correlatedAdapter(adapter) {
|
|
5653
8377
|
return {
|
|
@@ -5678,7 +8402,7 @@ function commandOf(method, path) {
|
|
|
5678
8402
|
if (method === "GET" || schema === void 0) return void 0;
|
|
5679
8403
|
const { command } = schema;
|
|
5680
8404
|
if (command === void 0) {
|
|
5681
|
-
throw new
|
|
8405
|
+
throw new ConfigError7(`route ${method} ${path} declares no audit command in routeSchemas`, {
|
|
5682
8406
|
code: "config.route_command_missing",
|
|
5683
8407
|
context: { method, path }
|
|
5684
8408
|
});
|
|
@@ -5734,7 +8458,8 @@ function registerAllRoutes(deps) {
|
|
|
5734
8458
|
repos.auditEntry.store
|
|
5735
8459
|
);
|
|
5736
8460
|
adapter.registerMiddleware(createAuthMiddleware(services.auth));
|
|
5737
|
-
|
|
8461
|
+
const afterSignIn = [foldViewsOnSignIn(services.recentlyViewed)];
|
|
8462
|
+
registerAuthRoutes(adapter, services.auth, config.security.auth.refreshTtl, afterSignIn);
|
|
5738
8463
|
registerCapabilitiesRoute(adapter, adapters);
|
|
5739
8464
|
registerCategoryRoutes(adapter, documentStore, config.store.name);
|
|
5740
8465
|
registerProductRoutes(
|
|
@@ -5751,7 +8476,14 @@ function registerAllRoutes(deps) {
|
|
|
5751
8476
|
productRepo: repos.product,
|
|
5752
8477
|
variantRepo: repos.variant
|
|
5753
8478
|
});
|
|
8479
|
+
registerRecentlyViewedRoutes(adapter, {
|
|
8480
|
+
recentlyViewed: services.recentlyViewed,
|
|
8481
|
+
documentStore,
|
|
8482
|
+
productRepo: repos.product,
|
|
8483
|
+
retentionDays: config.events.retentionDays
|
|
8484
|
+
});
|
|
5754
8485
|
registerCheckoutRoutes(adapter, services.checkout);
|
|
8486
|
+
registerAlertRoutes(adapter, { alerts: services.alert });
|
|
5755
8487
|
registerOrderRoutes(adapter, services.order, documentStore);
|
|
5756
8488
|
registerCustomerRoutes(adapter, services.customer);
|
|
5757
8489
|
registerAdminRoutes(adapter, {
|
|
@@ -5768,8 +8500,8 @@ function registerAllRoutes(deps) {
|
|
|
5768
8500
|
documentStore,
|
|
5769
8501
|
ticketSecret: config.security.auth.jwtSecret
|
|
5770
8502
|
});
|
|
5771
|
-
|
|
5772
|
-
|
|
8503
|
+
registerInboundWebhookRoute(adapter, {
|
|
8504
|
+
adapters,
|
|
5773
8505
|
checkout: services.checkout,
|
|
5774
8506
|
publisher,
|
|
5775
8507
|
store: repos.processedEvent.store,
|
|
@@ -5811,12 +8543,46 @@ export {
|
|
|
5811
8543
|
outsideCommand,
|
|
5812
8544
|
audit,
|
|
5813
8545
|
auditedCommand,
|
|
8546
|
+
CATEGORIES,
|
|
8547
|
+
PRODUCTS,
|
|
8548
|
+
PRODUCTS_BY_CATEGORY,
|
|
8549
|
+
ORDERS,
|
|
8550
|
+
ORDERS_BY_CUSTOMER,
|
|
8551
|
+
CUSTOMER_PROFILES,
|
|
8552
|
+
buildCategoryDoc,
|
|
8553
|
+
buildProductDoc,
|
|
8554
|
+
productByCategoryKey,
|
|
8555
|
+
productWrites,
|
|
8556
|
+
buildOrderDoc,
|
|
8557
|
+
orderWrites,
|
|
8558
|
+
buildCustomerProfile,
|
|
8559
|
+
KEY_OF,
|
|
8560
|
+
buildSearchDoc,
|
|
8561
|
+
subscribeDerived,
|
|
8562
|
+
recentlyViewed,
|
|
8563
|
+
registerRecentlyViewedProjection,
|
|
5814
8564
|
formatMoney,
|
|
8565
|
+
mintOrderKey,
|
|
8566
|
+
parseDurationToMs,
|
|
8567
|
+
createAuthService,
|
|
8568
|
+
createProductService,
|
|
8569
|
+
createCategoryService,
|
|
8570
|
+
createCartService,
|
|
8571
|
+
createCustomerService,
|
|
8572
|
+
createOrderService,
|
|
8573
|
+
createInventoryService,
|
|
5815
8574
|
PROVIDER_REFUND_REASON,
|
|
5816
8575
|
orderPayment,
|
|
5817
8576
|
settlementOf,
|
|
5818
8577
|
refreshRefunded,
|
|
5819
8578
|
createRefundService,
|
|
8579
|
+
createCheckoutService,
|
|
8580
|
+
createSearchService,
|
|
8581
|
+
createRecentlyViewedService,
|
|
8582
|
+
newAlertToken,
|
|
8583
|
+
createAlertService,
|
|
8584
|
+
emailDelivers,
|
|
8585
|
+
buildServices,
|
|
5820
8586
|
SECRETS_KEY_ENV,
|
|
5821
8587
|
SECRETS_KEY_OLD_ENV,
|
|
5822
8588
|
encrypt,
|
|
@@ -5828,8 +8594,6 @@ export {
|
|
|
5828
8594
|
CSRF_COOKIE,
|
|
5829
8595
|
CSRF_HEADER,
|
|
5830
8596
|
buildSecurityHeaders,
|
|
5831
|
-
noopInitialize,
|
|
5832
|
-
okHealth,
|
|
5833
8597
|
createMiddlewareSecurityAdapter,
|
|
5834
8598
|
createNativeStubPaymentsAdapter,
|
|
5835
8599
|
createNativeEmailAdapter,
|
|
@@ -5852,10 +8616,9 @@ export {
|
|
|
5852
8616
|
listStoredSettings,
|
|
5853
8617
|
settingValues,
|
|
5854
8618
|
loadBootSettings,
|
|
5855
|
-
toCustomerSnapshot,
|
|
5856
8619
|
registerAdminStaticRoute,
|
|
5857
|
-
inOrderScope,
|
|
5858
8620
|
routeSchemas,
|
|
8621
|
+
registerAlertRoutes,
|
|
5859
8622
|
registerAllRoutes
|
|
5860
8623
|
};
|
|
5861
|
-
//# sourceMappingURL=chunk-
|
|
8624
|
+
//# sourceMappingURL=chunk-GMV3B3SC.js.map
|