@nymbalhq/platform 1.2.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-UBEGSSFI.js → chunk-GMV3B3SC.js} +3681 -389
- package/dist/chunk-GMV3B3SC.js.map +1 -0
- package/dist/{chunk-XVUH34US.js → chunk-SNNK2OX3.js} +129 -7
- package/dist/chunk-SNNK2OX3.js.map +1 -0
- package/dist/db/schema/index.d.ts +1821 -323
- package/dist/db/schema/index.js +1 -1
- package/dist/index.d.ts +239 -10
- package/dist/index.js +734 -2169
- package/dist/index.js.map +1 -1
- package/dist/register-N2XGSFUF.js +8 -0
- package/migrations/postgres/0012_event_subject.sql +27 -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/0012_snapshot.json +1926 -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 +28 -0
- package/migrations/sqlite/0012_event_subject.sql +27 -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/0012_snapshot.json +1728 -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 +28 -0
- package/package.json +19 -19
- package/dist/chunk-UBEGSSFI.js.map +0 -1
- package/dist/chunk-XVUH34US.js.map +0 -1
- package/dist/register-NHG3TIRQ.js +0 -8
- /package/dist/{register-NHG3TIRQ.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
|
|
955
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
|
|
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
|
+
];
|
|
1626
|
+
}
|
|
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;
|
|
972
1637
|
}
|
|
973
|
-
function registerAuthRoutes(adapter, auth) {
|
|
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,38 +1886,2155 @@ 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
|
-
|
|
1226
|
-
|
|
1227
|
-
|
|
1228
|
-
|
|
1229
|
-
|
|
1230
|
-
|
|
2102
|
+
|
|
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
|
+
});
|
|
1231
2175
|
}
|
|
1232
|
-
}
|
|
2176
|
+
};
|
|
1233
2177
|
}
|
|
1234
2178
|
|
|
1235
|
-
// src/
|
|
1236
|
-
|
|
1237
|
-
|
|
1238
|
-
|
|
1239
|
-
|
|
1240
|
-
|
|
1241
|
-
|
|
1242
|
-
|
|
1243
|
-
|
|
1244
|
-
|
|
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()
|
|
2243
|
+
});
|
|
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;
|
|
2340
|
+
});
|
|
2341
|
+
}
|
|
2342
|
+
};
|
|
2343
|
+
}
|
|
2344
|
+
|
|
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);
|
|
2383
|
+
});
|
|
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);
|
|
2422
|
+
});
|
|
2423
|
+
}
|
|
2424
|
+
};
|
|
2425
|
+
}
|
|
2426
|
+
|
|
2427
|
+
// src/services/order-service.ts
|
|
2428
|
+
import { v7 as uuidv79 } from "uuid";
|
|
2429
|
+
import {
|
|
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
|
|
2441
|
+
} from "@nymbalhq/types";
|
|
2442
|
+
|
|
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) };
|
|
2449
|
+
}
|
|
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);
|
|
2455
|
+
}
|
|
2456
|
+
|
|
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
|
|
2510
|
+
});
|
|
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
|
|
2519
|
+
});
|
|
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
|
|
2549
|
+
});
|
|
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}`
|
|
2563
|
+
);
|
|
2564
|
+
await publisher.publish(EVT_ORDER_SHIPPED, {
|
|
2565
|
+
orderId: fresh.id,
|
|
2566
|
+
trackingNumber,
|
|
2567
|
+
carrier
|
|
2568
|
+
});
|
|
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
|
+
);
|
|
2591
|
+
}
|
|
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 }
|
|
2633
|
+
});
|
|
2634
|
+
}
|
|
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
|
+
};
|
|
2674
|
+
}
|
|
2675
|
+
|
|
2676
|
+
// src/services/inventory-service.ts
|
|
2677
|
+
import { v7 as uuidv710 } from "uuid";
|
|
2678
|
+
import {
|
|
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
|
|
2688
|
+
} from "@nymbalhq/types";
|
|
2689
|
+
function classifyStock(stock, threshold) {
|
|
2690
|
+
if (stock <= 0) return "out_of_stock";
|
|
2691
|
+
if (stock <= threshold) return "low_stock";
|
|
2692
|
+
return "in_stock";
|
|
2693
|
+
}
|
|
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
|
+
}
|
|
2749
|
+
return {
|
|
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,
|
|
2940
|
+
refundableMinor: refundableMinor(order, refunds),
|
|
2941
|
+
currency: order.currency,
|
|
2942
|
+
refunds
|
|
2943
|
+
};
|
|
2944
|
+
}
|
|
2945
|
+
function settlementOf(answer, row) {
|
|
2946
|
+
const matches = answer.amountMinor === row.amountMinor && answer.currency.toUpperCase() === row.currency.toUpperCase();
|
|
2947
|
+
const providerRefundId = answer.refundId;
|
|
2948
|
+
if (answer.status === "failed") return { status: "failed", providerRefundId, mismatch: false };
|
|
2949
|
+
if (!matches) return { status: "pending", providerRefundId, mismatch: true };
|
|
2950
|
+
return { status: answer.status, providerRefundId, mismatch: false };
|
|
2951
|
+
}
|
|
2952
|
+
async function refreshRefunded(repos, tx, orderId, at) {
|
|
2953
|
+
const refunds = await repos.orderRefund.listByOrder(tx, orderId);
|
|
2954
|
+
const refundedMinor = refunds.filter((r) => r.status === "succeeded").reduce((sum, r) => sum + r.amountMinor, 0);
|
|
2955
|
+
await repos.order.setRefunded(tx, orderId, refundedMinor, at);
|
|
2956
|
+
return { refunds, refundedMinor };
|
|
2957
|
+
}
|
|
2958
|
+
function createRefundService(deps) {
|
|
2959
|
+
const { store, repos, publisher, logger, payments } = deps;
|
|
2960
|
+
async function hold2(tx, input) {
|
|
2961
|
+
audit.note("order.refund", [{ type: "order", id: input.orderId }]);
|
|
2962
|
+
const order = await repos.order.lock(tx, input.orderId);
|
|
2963
|
+
if (!order) throw new NotFoundError9("order", input.orderId);
|
|
2964
|
+
if (input.requestId !== void 0) {
|
|
2965
|
+
const earlier = await repos.orderRefund.findByRequestId(tx, order.id, input.requestId);
|
|
2966
|
+
if (earlier !== null) {
|
|
2967
|
+
if (earlier.amountMinor !== input.amountMinor) {
|
|
2968
|
+
throw new OrderConflictError3(
|
|
2969
|
+
"refund.request_reused",
|
|
2970
|
+
`Request ${input.requestId} already refunded ${formatMoney(earlier.amountMinor, earlier.currency)} on order ${order.orderNumber}`,
|
|
2971
|
+
{
|
|
2972
|
+
context: { amountMinor: input.amountMinor, earlierAmountMinor: earlier.amountMinor }
|
|
2973
|
+
}
|
|
2974
|
+
);
|
|
2975
|
+
}
|
|
2976
|
+
const refunds = await repos.orderRefund.listByOrder(tx, order.id);
|
|
2977
|
+
return { repeat: { order, payment: orderPayment(order, refunds), refund: earlier } };
|
|
2978
|
+
}
|
|
2979
|
+
}
|
|
2980
|
+
if (order.capturedMinor <= 0 || order.captureMethod === "provider" && !order.paymentIntentId) {
|
|
2981
|
+
throw new OrderConflictError3(
|
|
2982
|
+
"refund.not_captured",
|
|
2983
|
+
`Order ${order.orderNumber} has no captured payment to refund`
|
|
2984
|
+
);
|
|
2985
|
+
}
|
|
2986
|
+
const refundable = refundableMinor(order, await repos.orderRefund.listByOrder(tx, order.id));
|
|
2987
|
+
if (input.amountMinor > refundable) {
|
|
2988
|
+
throw new OrderConflictError3(
|
|
2989
|
+
"refund.exceeds_captured",
|
|
2990
|
+
`Refund of ${formatMoney(input.amountMinor, order.currency)} exceeds the ${formatMoney(refundable, order.currency)} refundable on order ${order.orderNumber}`,
|
|
2991
|
+
{ context: { amountMinor: input.amountMinor, refundableMinor: refundable } }
|
|
2992
|
+
);
|
|
2993
|
+
}
|
|
2994
|
+
if (!canTransitionOrder(order.status, "refunded")) {
|
|
2995
|
+
throw new StatusTransitionError3("order", order.status, "refunded");
|
|
2996
|
+
}
|
|
2997
|
+
const row = {
|
|
2998
|
+
id: uuidv711(),
|
|
2999
|
+
orderId: order.id,
|
|
3000
|
+
amountMinor: input.amountMinor,
|
|
3001
|
+
currency: order.currency,
|
|
3002
|
+
providerRefundId: null,
|
|
3003
|
+
status: "pending",
|
|
3004
|
+
reason: input.reason ?? null,
|
|
3005
|
+
actor: input.actor,
|
|
3006
|
+
createdAt: /* @__PURE__ */ new Date(),
|
|
3007
|
+
requestId: input.requestId ?? null
|
|
3008
|
+
};
|
|
3009
|
+
await repos.orderRefund.insert(tx, row);
|
|
3010
|
+
return { order, row };
|
|
3011
|
+
}
|
|
3012
|
+
async function moveMoney(order, row) {
|
|
3013
|
+
if (order.captureMethod !== "provider") {
|
|
3014
|
+
return { status: "succeeded", providerRefundId: null, mismatch: false };
|
|
3015
|
+
}
|
|
3016
|
+
const context2 = { orderId: order.id, refundId: row.id, amountMinor: row.amountMinor };
|
|
3017
|
+
try {
|
|
3018
|
+
const answer = await payments.refund(
|
|
3019
|
+
order.paymentIntentId,
|
|
3020
|
+
row.amountMinor,
|
|
3021
|
+
PROVIDER_REFUND_REASON,
|
|
3022
|
+
{ idempotencyKey: row.id, currency: order.currency }
|
|
3023
|
+
);
|
|
3024
|
+
const settlement = settlementOf(answer, row);
|
|
3025
|
+
if (settlement.mismatch) {
|
|
3026
|
+
logger.error(
|
|
3027
|
+
{ ...context2, answer: { amountMinor: answer.amountMinor, currency: answer.currency } },
|
|
3028
|
+
"provider refund answer differs from the refund; left pending"
|
|
3029
|
+
);
|
|
3030
|
+
}
|
|
3031
|
+
return settlement;
|
|
3032
|
+
} catch (err) {
|
|
3033
|
+
if (err instanceof PaymentError && err.code === "payment.refund_rejected") {
|
|
3034
|
+
logger.warn({ ...context2, err }, "provider refused the refund");
|
|
3035
|
+
return { status: "failed", providerRefundId: null, mismatch: false };
|
|
3036
|
+
}
|
|
3037
|
+
logger.error({ ...context2, err }, "refund outcome unknown; left pending until reconciled");
|
|
3038
|
+
return { status: "pending", providerRefundId: null, mismatch: false };
|
|
3039
|
+
}
|
|
3040
|
+
}
|
|
3041
|
+
async function settle(tx, orderId, row, settlement) {
|
|
3042
|
+
const order = await repos.order.lock(tx, orderId);
|
|
3043
|
+
if (!order) throw new NotFoundError9("order", orderId);
|
|
3044
|
+
await repos.orderRefund.settle(tx, row.id, {
|
|
3045
|
+
status: settlement.status,
|
|
3046
|
+
providerRefundId: settlement.providerRefundId
|
|
3047
|
+
});
|
|
3048
|
+
const now = /* @__PURE__ */ new Date();
|
|
3049
|
+
const { refunds, refundedMinor } = await refreshRefunded(repos, tx, order.id, now);
|
|
3050
|
+
const refund = refunds.find((r) => r.id === row.id);
|
|
3051
|
+
if (refund.status === "succeeded") await recordSucceeded(tx, order, refundedMinor, refund, now);
|
|
3052
|
+
const fresh = await repos.order.findById(tx, order.id);
|
|
3053
|
+
return { order: fresh, payment: orderPayment(fresh, refunds), refund };
|
|
3054
|
+
}
|
|
3055
|
+
async function recordSucceeded(tx, order, refundedMinor, refund, now) {
|
|
3056
|
+
const full = refundedMinor >= order.capturedMinor;
|
|
3057
|
+
const target = full ? "refunded" : "partially_refunded";
|
|
3058
|
+
const note = `${REFUND_NOTE_PREFIX}${formatMoney(refund.amountMinor, refund.currency)}${refund.reason ? `: ${refund.reason}` : ""}`;
|
|
3059
|
+
let toStatus = order.status;
|
|
3060
|
+
if (order.status !== target && canTransitionOrder(order.status, target)) {
|
|
3061
|
+
await repos.order.setStatus(tx, order.id, target, now);
|
|
3062
|
+
toStatus = target;
|
|
3063
|
+
} else if (order.status !== target) {
|
|
3064
|
+
logger.warn(
|
|
3065
|
+
{ orderId: order.id, refundId: refund.id, status: order.status, wanted: target },
|
|
3066
|
+
"refund settled; the order status no longer allows the move and is kept"
|
|
3067
|
+
);
|
|
3068
|
+
}
|
|
3069
|
+
await repos.orderHistory.append(tx, {
|
|
3070
|
+
id: uuidv711(),
|
|
3071
|
+
orderId: order.id,
|
|
3072
|
+
fromStatus: order.status,
|
|
3073
|
+
toStatus,
|
|
3074
|
+
actor: refund.actor,
|
|
3075
|
+
note,
|
|
3076
|
+
timestamp: now
|
|
3077
|
+
});
|
|
3078
|
+
if (order.customerId) {
|
|
3079
|
+
await repos.customer.incrementStats(tx, order.customerId, 0, -refund.amountMinor, now);
|
|
3080
|
+
}
|
|
3081
|
+
const payload = {
|
|
3082
|
+
orderId: order.id,
|
|
3083
|
+
refundId: refund.id,
|
|
3084
|
+
amountMinor: refund.amountMinor,
|
|
3085
|
+
currency: refund.currency,
|
|
3086
|
+
reason: refund.reason ?? ""
|
|
3087
|
+
};
|
|
3088
|
+
await publisher.publish(full ? EVT_ORDER_REFUNDED : EVT_ORDER_PARTIALLY_REFUNDED, payload);
|
|
3089
|
+
await publisher.publish(EVT_PAYMENT_REFUNDED, {
|
|
3090
|
+
paymentId: order.captureMethod === "provider" ? order.paymentIntentId ?? "" : "",
|
|
3091
|
+
orderId: order.id,
|
|
3092
|
+
refundId: refund.id,
|
|
3093
|
+
amountMinor: refund.amountMinor,
|
|
3094
|
+
currency: refund.currency
|
|
3095
|
+
});
|
|
3096
|
+
}
|
|
3097
|
+
return {
|
|
3098
|
+
async refund(input) {
|
|
3099
|
+
audit.note("order.refund", [{ type: "order", id: input.orderId }]);
|
|
3100
|
+
if (!Number.isInteger(input.amountMinor) || input.amountMinor <= 0) {
|
|
3101
|
+
throw new ValidationError9("amountMinor must be a positive whole number of minor units", {
|
|
3102
|
+
context: { amountMinor: input.amountMinor }
|
|
3103
|
+
});
|
|
3104
|
+
}
|
|
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);
|
|
1245
4038
|
} catch (err) {
|
|
1246
4039
|
return renderError(err);
|
|
1247
4040
|
}
|
|
@@ -1378,7 +4171,8 @@ function registerCheckoutRoutes(adapter, checkout) {
|
|
|
1378
4171
|
currency: result.currency,
|
|
1379
4172
|
totalMinor: result.totalMinor,
|
|
1380
4173
|
orderStatus: result.orderStatus,
|
|
1381
|
-
payment: result.payment
|
|
4174
|
+
payment: result.payment,
|
|
4175
|
+
orderKey: result.orderKey
|
|
1382
4176
|
});
|
|
1383
4177
|
} catch (err) {
|
|
1384
4178
|
return renderError(err);
|
|
@@ -1388,11 +4182,12 @@ function registerCheckoutRoutes(adapter, checkout) {
|
|
|
1388
4182
|
|
|
1389
4183
|
// src/routes/orders.ts
|
|
1390
4184
|
import {
|
|
1391
|
-
NotFoundError as
|
|
4185
|
+
NotFoundError as NotFoundError11,
|
|
4186
|
+
ORDER_KEY_HEADER
|
|
1392
4187
|
} from "@nymbalhq/types";
|
|
1393
4188
|
|
|
1394
4189
|
// src/routes/role-middleware.ts
|
|
1395
|
-
import { AuthError as
|
|
4190
|
+
import { AuthError as AuthError4 } from "@nymbalhq/types";
|
|
1396
4191
|
function requireAuth(handler) {
|
|
1397
4192
|
return (ctx) => {
|
|
1398
4193
|
if (!ctx.auth?.userId) {
|
|
@@ -1414,6 +4209,10 @@ function requireRole(role, handler) {
|
|
|
1414
4209
|
}
|
|
1415
4210
|
|
|
1416
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
|
+
}
|
|
1417
4216
|
function registerOrderRoutes(adapter, orders, documentStore) {
|
|
1418
4217
|
adapter.registerRoute(
|
|
1419
4218
|
"GET",
|
|
@@ -1425,29 +4224,33 @@ function registerOrderRoutes(adapter, orders, documentStore) {
|
|
|
1425
4224
|
partitionKey: { field: "partitionKey", value: `customer:${customerId}` },
|
|
1426
4225
|
limit: 50
|
|
1427
4226
|
});
|
|
1428
|
-
return ok(result.items, { nextCursor: result.nextCursor });
|
|
4227
|
+
return ok(result.items.map(shopperOrder), { nextCursor: result.nextCursor });
|
|
1429
4228
|
} catch (err) {
|
|
1430
4229
|
return renderError(err);
|
|
1431
4230
|
}
|
|
1432
4231
|
})
|
|
1433
4232
|
);
|
|
1434
|
-
|
|
4233
|
+
async function readOrder(ctx) {
|
|
1435
4234
|
try {
|
|
1436
4235
|
const orderNumber = ctx.params.orderNumber;
|
|
1437
4236
|
if (!orderNumber) return fail("orders.invalid", "orderNumber required", 400);
|
|
1438
4237
|
const doc = await documentStore.get("orders", orderNumber);
|
|
1439
|
-
if (!doc) throw new
|
|
1440
|
-
|
|
1441
|
-
|
|
1442
|
-
|
|
1443
|
-
|
|
1444
|
-
|
|
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);
|
|
1445
4244
|
}
|
|
1446
|
-
return ok(doc);
|
|
4245
|
+
return ok(shopperOrder(doc));
|
|
1447
4246
|
} catch (err) {
|
|
1448
4247
|
return renderError(err);
|
|
1449
4248
|
}
|
|
1450
|
-
}
|
|
4249
|
+
}
|
|
4250
|
+
adapter.registerRoute("GET", "/api/orders/:orderNumber", async (ctx) => ({
|
|
4251
|
+
...await readOrder(ctx),
|
|
4252
|
+
headers: { "Cache-Control": "no-store" }
|
|
4253
|
+
}));
|
|
1451
4254
|
}
|
|
1452
4255
|
|
|
1453
4256
|
// src/routes/customers.ts
|
|
@@ -1618,213 +4421,68 @@ function registerAdminDashboardRoute(adapter, deps) {
|
|
|
1618
4421
|
|
|
1619
4422
|
// src/routes/admin-orders.ts
|
|
1620
4423
|
import {
|
|
1621
|
-
OrderConflictError as
|
|
4424
|
+
OrderConflictError as OrderConflictError5,
|
|
1622
4425
|
canTransitionOrder as canTransitionOrder2
|
|
1623
4426
|
} from "@nymbalhq/types";
|
|
1624
4427
|
|
|
1625
|
-
// src/
|
|
1626
|
-
|
|
1627
|
-
|
|
1628
|
-
|
|
1629
|
-
|
|
1630
|
-
|
|
1631
|
-
|
|
1632
|
-
OrderConflictError as OrderConflictError2,
|
|
1633
|
-
PaymentError,
|
|
1634
|
-
StatusTransitionError as StatusTransitionError2,
|
|
1635
|
-
ValidationError as ValidationError2,
|
|
1636
|
-
canTransitionOrder,
|
|
1637
|
-
paymentState,
|
|
1638
|
-
refundableMinor
|
|
1639
|
-
} from "@nymbalhq/types";
|
|
1640
|
-
|
|
1641
|
-
// src/money.ts
|
|
1642
|
-
function formatMoney(amountMinor, currency) {
|
|
1643
|
-
const code = currency.toUpperCase();
|
|
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);
|
|
1647
|
-
}
|
|
1648
|
-
|
|
1649
|
-
// src/services/refund-service.ts
|
|
1650
|
-
var PROVIDER_REFUND_REASON = "requested_by_customer";
|
|
1651
|
-
function orderPayment(order, refunds) {
|
|
1652
|
-
return {
|
|
1653
|
-
state: paymentState(order),
|
|
1654
|
-
capturedMinor: order.capturedMinor,
|
|
1655
|
-
refundedMinor: order.refundedMinor,
|
|
1656
|
-
refundableMinor: refundableMinor(order, refunds),
|
|
1657
|
-
currency: order.currency,
|
|
1658
|
-
refunds
|
|
1659
|
-
};
|
|
1660
|
-
}
|
|
1661
|
-
function settlementOf(answer, row) {
|
|
1662
|
-
const matches = answer.amountMinor === row.amountMinor && answer.currency.toUpperCase() === row.currency.toUpperCase();
|
|
1663
|
-
const providerRefundId = answer.refundId;
|
|
1664
|
-
if (answer.status === "failed") return { status: "failed", providerRefundId, mismatch: false };
|
|
1665
|
-
if (!matches) return { status: "pending", providerRefundId, mismatch: true };
|
|
1666
|
-
return { status: answer.status, providerRefundId, mismatch: false };
|
|
4428
|
+
// src/history/http.ts
|
|
4429
|
+
var DEFAULT_LIMIT = 50;
|
|
4430
|
+
var MAX_LIMIT = 200;
|
|
4431
|
+
var ISO_INSTANT = /^\d{4}-\d{2}-\d{2}T\d{2}:\d{2}(:\d{2}(\.\d{1,9})?)?(Z|[+-]\d{2}:\d{2})$/i;
|
|
4432
|
+
function one(ctx, name) {
|
|
4433
|
+
const value = ctx.query[name];
|
|
4434
|
+
return Array.isArray(value) ? value[0] : value;
|
|
1667
4435
|
}
|
|
1668
|
-
|
|
1669
|
-
|
|
1670
|
-
const refundedMinor = refunds.filter((r) => r.status === "succeeded").reduce((sum, r) => sum + r.amountMinor, 0);
|
|
1671
|
-
await repos.order.setRefunded(tx, orderId, refundedMinor, at);
|
|
1672
|
-
return { refunds, refundedMinor };
|
|
4436
|
+
function atOf(ctx) {
|
|
4437
|
+
return one(ctx, "at");
|
|
1673
4438
|
}
|
|
1674
|
-
function
|
|
1675
|
-
|
|
1676
|
-
|
|
1677
|
-
|
|
1678
|
-
|
|
1679
|
-
if (!order) throw new NotFoundError4("order", input.orderId);
|
|
1680
|
-
if (input.requestId !== void 0) {
|
|
1681
|
-
const earlier = await repos.orderRefund.findByRequestId(tx, order.id, input.requestId);
|
|
1682
|
-
if (earlier !== null) {
|
|
1683
|
-
if (earlier.amountMinor !== input.amountMinor) {
|
|
1684
|
-
throw new OrderConflictError2(
|
|
1685
|
-
"refund.request_reused",
|
|
1686
|
-
`Request ${input.requestId} already refunded ${formatMoney(earlier.amountMinor, earlier.currency)} on order ${order.orderNumber}`,
|
|
1687
|
-
{
|
|
1688
|
-
context: { amountMinor: input.amountMinor, earlierAmountMinor: earlier.amountMinor }
|
|
1689
|
-
}
|
|
1690
|
-
);
|
|
1691
|
-
}
|
|
1692
|
-
const refunds = await repos.orderRefund.listByOrder(tx, order.id);
|
|
1693
|
-
return { repeat: { order, payment: orderPayment(order, refunds), refund: earlier } };
|
|
1694
|
-
}
|
|
1695
|
-
}
|
|
1696
|
-
if (order.capturedMinor <= 0 || order.captureMethod === "provider" && !order.paymentIntentId) {
|
|
1697
|
-
throw new OrderConflictError2(
|
|
1698
|
-
"refund.not_captured",
|
|
1699
|
-
`Order ${order.orderNumber} has no captured payment to refund`
|
|
1700
|
-
);
|
|
1701
|
-
}
|
|
1702
|
-
const refundable = refundableMinor(order, await repos.orderRefund.listByOrder(tx, order.id));
|
|
1703
|
-
if (input.amountMinor > refundable) {
|
|
1704
|
-
throw new OrderConflictError2(
|
|
1705
|
-
"refund.exceeds_captured",
|
|
1706
|
-
`Refund of ${formatMoney(input.amountMinor, order.currency)} exceeds the ${formatMoney(refundable, order.currency)} refundable on order ${order.orderNumber}`,
|
|
1707
|
-
{ context: { amountMinor: input.amountMinor, refundableMinor: refundable } }
|
|
1708
|
-
);
|
|
1709
|
-
}
|
|
1710
|
-
if (!canTransitionOrder(order.status, "refunded")) {
|
|
1711
|
-
throw new StatusTransitionError2("order", order.status, "refunded");
|
|
1712
|
-
}
|
|
1713
|
-
const row = {
|
|
1714
|
-
id: uuidv73(),
|
|
1715
|
-
orderId: order.id,
|
|
1716
|
-
amountMinor: input.amountMinor,
|
|
1717
|
-
currency: order.currency,
|
|
1718
|
-
providerRefundId: null,
|
|
1719
|
-
status: "pending",
|
|
1720
|
-
reason: input.reason ?? null,
|
|
1721
|
-
actor: input.actor,
|
|
1722
|
-
createdAt: /* @__PURE__ */ new Date(),
|
|
1723
|
-
requestId: input.requestId ?? null
|
|
1724
|
-
};
|
|
1725
|
-
await repos.orderRefund.insert(tx, row);
|
|
1726
|
-
return { order, row };
|
|
1727
|
-
}
|
|
1728
|
-
async function moveMoney(order, row) {
|
|
1729
|
-
if (order.captureMethod !== "provider") {
|
|
1730
|
-
return { status: "succeeded", providerRefundId: null, mismatch: false };
|
|
4439
|
+
async function answerAsOf(reader, at, resolve2, notFound3) {
|
|
4440
|
+
try {
|
|
4441
|
+
const instant = new Date(at);
|
|
4442
|
+
if (!ISO_INSTANT.test(at) || Number.isNaN(instant.getTime())) {
|
|
4443
|
+
return fail("history.invalid_at", "at must be an ISO 8601 date-time with a zone", 400, { at });
|
|
1731
4444
|
}
|
|
1732
|
-
const
|
|
1733
|
-
|
|
1734
|
-
|
|
1735
|
-
|
|
1736
|
-
|
|
1737
|
-
|
|
1738
|
-
|
|
1739
|
-
|
|
1740
|
-
|
|
1741
|
-
|
|
1742
|
-
|
|
1743
|
-
|
|
1744
|
-
"
|
|
4445
|
+
const outcome = await reader.asOf(await resolve2(), instant);
|
|
4446
|
+
switch (outcome.kind) {
|
|
4447
|
+
case "record":
|
|
4448
|
+
return ok(outcome.read);
|
|
4449
|
+
case "not_found":
|
|
4450
|
+
return notFound3();
|
|
4451
|
+
case "deleted":
|
|
4452
|
+
return fail("history.deleted", `Deleted at ${outcome.deletedAt}`, 410, {
|
|
4453
|
+
deletedAt: outcome.deletedAt
|
|
4454
|
+
});
|
|
4455
|
+
case "before_start":
|
|
4456
|
+
return fail(
|
|
4457
|
+
"history.before_start",
|
|
4458
|
+
outcome.historyStartsAt === null ? "The record predates the event log\u2019s window (events.retentionDays)" : `The event log holds this record from ${outcome.historyStartsAt}`,
|
|
4459
|
+
409,
|
|
4460
|
+
{ historyStartsAt: outcome.historyStartsAt }
|
|
1745
4461
|
);
|
|
1746
|
-
}
|
|
1747
|
-
return settlement;
|
|
1748
|
-
} catch (err) {
|
|
1749
|
-
if (err instanceof PaymentError && err.code === "payment.refund_rejected") {
|
|
1750
|
-
logger.warn({ ...context2, err }, "provider refused the refund");
|
|
1751
|
-
return { status: "failed", providerRefundId: null, mismatch: false };
|
|
1752
|
-
}
|
|
1753
|
-
logger.error({ ...context2, err }, "refund outcome unknown; left pending until reconciled");
|
|
1754
|
-
return { status: "pending", providerRefundId: null, mismatch: false };
|
|
1755
4462
|
}
|
|
4463
|
+
} catch (err) {
|
|
4464
|
+
return renderError(err);
|
|
1756
4465
|
}
|
|
1757
|
-
|
|
1758
|
-
|
|
1759
|
-
|
|
1760
|
-
|
|
1761
|
-
|
|
1762
|
-
|
|
1763
|
-
|
|
1764
|
-
const now = /* @__PURE__ */ new Date();
|
|
1765
|
-
const { refunds, refundedMinor } = await refreshRefunded(repos, tx, order.id, now);
|
|
1766
|
-
const refund = refunds.find((r) => r.id === row.id);
|
|
1767
|
-
if (refund.status === "succeeded") await recordSucceeded(tx, order, refundedMinor, refund, now);
|
|
1768
|
-
const fresh = await repos.order.findById(tx, order.id);
|
|
1769
|
-
return { order: fresh, payment: orderPayment(fresh, refunds), refund };
|
|
1770
|
-
}
|
|
1771
|
-
async function recordSucceeded(tx, order, refundedMinor, refund, now) {
|
|
1772
|
-
const full = refundedMinor >= order.capturedMinor;
|
|
1773
|
-
const target = full ? "refunded" : "partially_refunded";
|
|
1774
|
-
const note = `refund of ${formatMoney(refund.amountMinor, refund.currency)}${refund.reason ? `: ${refund.reason}` : ""}`;
|
|
1775
|
-
let toStatus = order.status;
|
|
1776
|
-
if (order.status !== target && canTransitionOrder(order.status, target)) {
|
|
1777
|
-
await repos.order.setStatus(tx, order.id, target, now);
|
|
1778
|
-
toStatus = target;
|
|
1779
|
-
} else if (order.status !== target) {
|
|
1780
|
-
logger.warn(
|
|
1781
|
-
{ orderId: order.id, refundId: refund.id, status: order.status, wanted: target },
|
|
1782
|
-
"refund settled; the order status no longer allows the move and is kept"
|
|
1783
|
-
);
|
|
4466
|
+
}
|
|
4467
|
+
async function answerHistory(reader, ctx, resolve2, notFound3) {
|
|
4468
|
+
try {
|
|
4469
|
+
const limitRaw = one(ctx, "limit");
|
|
4470
|
+
const limit = limitRaw === void 0 || limitRaw === "" ? DEFAULT_LIMIT : Number(limitRaw);
|
|
4471
|
+
if (!Number.isInteger(limit) || limit < 1) {
|
|
4472
|
+
return fail("history.invalid", "limit must be a whole number of at least 1", 400);
|
|
1784
4473
|
}
|
|
1785
|
-
|
|
1786
|
-
|
|
1787
|
-
|
|
1788
|
-
fromStatus: order.status,
|
|
1789
|
-
toStatus,
|
|
1790
|
-
actor: refund.actor,
|
|
1791
|
-
note,
|
|
1792
|
-
timestamp: now
|
|
1793
|
-
});
|
|
1794
|
-
if (order.customerId) {
|
|
1795
|
-
await repos.customer.incrementStats(tx, order.customerId, 0, -refund.amountMinor, now);
|
|
4474
|
+
const cursor = one(ctx, "cursor");
|
|
4475
|
+
if (cursor !== void 0 && cursor !== "" && !/^\d+$/.test(cursor)) {
|
|
4476
|
+
return fail("history.invalid", "cursor is not one this API issued", 400);
|
|
1796
4477
|
}
|
|
1797
|
-
const
|
|
1798
|
-
|
|
1799
|
-
|
|
1800
|
-
amountMinor: refund.amountMinor,
|
|
1801
|
-
currency: refund.currency,
|
|
1802
|
-
reason: refund.reason ?? ""
|
|
1803
|
-
};
|
|
1804
|
-
await publisher.publish(full ? EVT_ORDER_REFUNDED : EVT_ORDER_PARTIALLY_REFUNDED, payload);
|
|
1805
|
-
await publisher.publish(EVT_PAYMENT_REFUNDED, {
|
|
1806
|
-
paymentId: order.captureMethod === "provider" ? order.paymentIntentId ?? "" : "",
|
|
1807
|
-
orderId: order.id,
|
|
1808
|
-
refundId: refund.id,
|
|
1809
|
-
amountMinor: refund.amountMinor,
|
|
1810
|
-
currency: refund.currency
|
|
4478
|
+
const page = await reader.list(await resolve2(), {
|
|
4479
|
+
limit: Math.min(limit, MAX_LIMIT),
|
|
4480
|
+
...cursor !== void 0 && cursor !== "" && { beforeSeq: Number(cursor) }
|
|
1811
4481
|
});
|
|
4482
|
+
return page === null ? notFound3() : ok(page);
|
|
4483
|
+
} catch (err) {
|
|
4484
|
+
return renderError(err);
|
|
1812
4485
|
}
|
|
1813
|
-
return {
|
|
1814
|
-
async refund(input) {
|
|
1815
|
-
audit.note("order.refund", [{ type: "order", id: input.orderId }]);
|
|
1816
|
-
if (!Number.isInteger(input.amountMinor) || input.amountMinor <= 0) {
|
|
1817
|
-
throw new ValidationError2("amountMinor must be a positive whole number of minor units", {
|
|
1818
|
-
context: { amountMinor: input.amountMinor }
|
|
1819
|
-
});
|
|
1820
|
-
}
|
|
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
|
-
};
|
|
1828
4486
|
}
|
|
1829
4487
|
|
|
1830
4488
|
// src/routes/admin-orders.ts
|
|
@@ -1839,7 +4497,7 @@ function parseNotes(rawNotes, createdAt) {
|
|
|
1839
4497
|
}
|
|
1840
4498
|
}
|
|
1841
4499
|
function registerAdminOrdersRoutes(adapter, deps) {
|
|
1842
|
-
const { order, checkout, refund, repos } = deps;
|
|
4500
|
+
const { order, checkout, refund, repos, history } = deps;
|
|
1843
4501
|
const { store } = repos.order;
|
|
1844
4502
|
async function withPayments(tx, orders) {
|
|
1845
4503
|
const refunds = await repos.orderRefund.listByOrders(
|
|
@@ -1855,6 +4513,11 @@ function registerAdminOrdersRoutes(adapter, deps) {
|
|
|
1855
4513
|
async function findOrder(tx, idOrNumber) {
|
|
1856
4514
|
return await repos.order.findById(tx, idOrNumber) ?? await repos.order.findByOrderNumber(tx, idOrNumber);
|
|
1857
4515
|
}
|
|
4516
|
+
async function historySubject(idOrNumber) {
|
|
4517
|
+
const found = await store.read((tx) => findOrder(tx, idOrNumber));
|
|
4518
|
+
return { kind: "order", id: found?.id ?? idOrNumber, live: found !== null };
|
|
4519
|
+
}
|
|
4520
|
+
const notFound3 = (idOrNumber) => () => fail("orders.not_found", `Order not found: ${idOrNumber}`, 404);
|
|
1858
4521
|
adapter.registerRoute(
|
|
1859
4522
|
"GET",
|
|
1860
4523
|
"/api/admin/orders",
|
|
@@ -1911,6 +4574,10 @@ function registerAdminOrdersRoutes(adapter, deps) {
|
|
|
1911
4574
|
try {
|
|
1912
4575
|
const orderNumber = ctx.params.orderNumber;
|
|
1913
4576
|
if (!orderNumber) return fail("admin.invalid", "orderNumber required", 400);
|
|
4577
|
+
const at = atOf(ctx);
|
|
4578
|
+
if (at !== void 0) {
|
|
4579
|
+
return answerAsOf(history, at, () => historySubject(orderNumber), notFound3(orderNumber));
|
|
4580
|
+
}
|
|
1914
4581
|
const detail = await store.read(async (tx) => {
|
|
1915
4582
|
const found = await repos.order.findByOrderNumber(tx, orderNumber);
|
|
1916
4583
|
if (!found) return null;
|
|
@@ -1933,7 +4600,7 @@ function registerAdminOrdersRoutes(adapter, deps) {
|
|
|
1933
4600
|
if (!id2) return fail("admin.invalid", "id required", 400);
|
|
1934
4601
|
const current = await order.getById(id2);
|
|
1935
4602
|
if (canTransitionOrder2(current.status, "confirmed") && current.capturedMinor === 0) {
|
|
1936
|
-
throw new
|
|
4603
|
+
throw new OrderConflictError5(
|
|
1937
4604
|
"order.unpaid",
|
|
1938
4605
|
`Order ${current.orderNumber} is unpaid: record its payment to confirm it`
|
|
1939
4606
|
);
|
|
@@ -2035,8 +4702,8 @@ function registerAdminOrdersRoutes(adapter, deps) {
|
|
|
2035
4702
|
const id2 = ctx.params.id;
|
|
2036
4703
|
if (!id2) return fail("admin.invalid", "id required", 400);
|
|
2037
4704
|
const body = ctx.body;
|
|
2038
|
-
const
|
|
2039
|
-
const requestId = body.requestId ?? ("key" in
|
|
4705
|
+
const keyed2 = idempotencyKeyOf(ctx);
|
|
4706
|
+
const requestId = body.requestId ?? ("key" in keyed2 ? keyed2.key : void 0);
|
|
2040
4707
|
const result = await refund.refund({
|
|
2041
4708
|
orderId: id2,
|
|
2042
4709
|
amountMinor: body.amountMinor,
|
|
@@ -2050,6 +4717,15 @@ function registerAdminOrdersRoutes(adapter, deps) {
|
|
|
2050
4717
|
}
|
|
2051
4718
|
})
|
|
2052
4719
|
);
|
|
4720
|
+
adapter.registerRoute(
|
|
4721
|
+
"GET",
|
|
4722
|
+
"/api/admin/orders/:id/history",
|
|
4723
|
+
requireRole("admin", async (ctx) => {
|
|
4724
|
+
const id2 = ctx.params.id;
|
|
4725
|
+
if (!id2) return fail("admin.invalid", "id required", 400);
|
|
4726
|
+
return answerHistory(history, ctx, () => historySubject(id2), notFound3(id2));
|
|
4727
|
+
})
|
|
4728
|
+
);
|
|
2053
4729
|
adapter.registerRoute(
|
|
2054
4730
|
"GET",
|
|
2055
4731
|
"/api/admin/orders/:id/timeline",
|
|
@@ -2057,12 +4733,12 @@ function registerAdminOrdersRoutes(adapter, deps) {
|
|
|
2057
4733
|
try {
|
|
2058
4734
|
const id2 = ctx.params.id;
|
|
2059
4735
|
if (!id2) return fail("admin.invalid", "id required", 400);
|
|
2060
|
-
const
|
|
4736
|
+
const history2 = await store.read(async (tx) => {
|
|
2061
4737
|
const found = await findOrder(tx, id2);
|
|
2062
4738
|
return found ? repos.orderHistory.listByOrder(tx, found.id) : null;
|
|
2063
4739
|
});
|
|
2064
|
-
if (!
|
|
2065
|
-
return ok(
|
|
4740
|
+
if (!history2) return fail("orders.not_found", `Order not found: ${id2}`, 404);
|
|
4741
|
+
return ok(history2);
|
|
2066
4742
|
} catch (err) {
|
|
2067
4743
|
return renderError(err);
|
|
2068
4744
|
}
|
|
@@ -2122,7 +4798,8 @@ function registerAdminOrdersRoutes(adapter, deps) {
|
|
|
2122
4798
|
try {
|
|
2123
4799
|
const id2 = ctx.params.id;
|
|
2124
4800
|
if (!id2) return fail("admin.invalid", "id required", 400);
|
|
2125
|
-
|
|
4801
|
+
const queued = await order.resendConfirmation(id2);
|
|
4802
|
+
return ok({ orderId: queued.id, orderNumber: queued.orderNumber, email: queued.email });
|
|
2126
4803
|
} catch (err) {
|
|
2127
4804
|
return renderError(err);
|
|
2128
4805
|
}
|
|
@@ -2131,8 +4808,27 @@ function registerAdminOrdersRoutes(adapter, deps) {
|
|
|
2131
4808
|
}
|
|
2132
4809
|
|
|
2133
4810
|
// src/routes/admin-products.ts
|
|
4811
|
+
import {
|
|
4812
|
+
NotFoundError as NotFoundError12
|
|
4813
|
+
} from "@nymbalhq/types";
|
|
4814
|
+
async function orNull(found) {
|
|
4815
|
+
try {
|
|
4816
|
+
return await found;
|
|
4817
|
+
} catch (err) {
|
|
4818
|
+
if (err instanceof NotFoundError12) return null;
|
|
4819
|
+
throw err;
|
|
4820
|
+
}
|
|
4821
|
+
}
|
|
2134
4822
|
function registerAdminProductsRoutes(adapter, deps) {
|
|
2135
|
-
const { product } = deps;
|
|
4823
|
+
const { product, history } = deps;
|
|
4824
|
+
async function findProduct(idOrSlug) {
|
|
4825
|
+
return await orNull(product.getById(idOrSlug)) ?? await orNull(product.getBySlug(idOrSlug));
|
|
4826
|
+
}
|
|
4827
|
+
async function historySubject(idOrSlug) {
|
|
4828
|
+
const live = await findProduct(idOrSlug);
|
|
4829
|
+
return { kind: "product", id: live?.id ?? idOrSlug, live: live !== null };
|
|
4830
|
+
}
|
|
4831
|
+
const notFound3 = (idOrSlug) => () => fail("not_found", `product not found: ${idOrSlug}`, 404);
|
|
2136
4832
|
adapter.registerRoute(
|
|
2137
4833
|
"GET",
|
|
2138
4834
|
"/api/admin/products",
|
|
@@ -2174,6 +4870,33 @@ function registerAdminProductsRoutes(adapter, deps) {
|
|
|
2174
4870
|
}
|
|
2175
4871
|
})
|
|
2176
4872
|
);
|
|
4873
|
+
adapter.registerRoute(
|
|
4874
|
+
"GET",
|
|
4875
|
+
"/api/admin/products/:id",
|
|
4876
|
+
requireRole("admin", async (ctx) => {
|
|
4877
|
+
try {
|
|
4878
|
+
const idOrSlug = ctx.params.id;
|
|
4879
|
+
if (!idOrSlug) return fail("admin.invalid", "id required", 400);
|
|
4880
|
+
const at = atOf(ctx);
|
|
4881
|
+
if (at !== void 0) {
|
|
4882
|
+
return answerAsOf(history, at, () => historySubject(idOrSlug), notFound3(idOrSlug));
|
|
4883
|
+
}
|
|
4884
|
+
const found = await findProduct(idOrSlug);
|
|
4885
|
+
return found === null ? notFound3(idOrSlug)() : ok(found);
|
|
4886
|
+
} catch (err) {
|
|
4887
|
+
return renderError(err);
|
|
4888
|
+
}
|
|
4889
|
+
})
|
|
4890
|
+
);
|
|
4891
|
+
adapter.registerRoute(
|
|
4892
|
+
"GET",
|
|
4893
|
+
"/api/admin/products/:id/history",
|
|
4894
|
+
requireRole("admin", async (ctx) => {
|
|
4895
|
+
const idOrSlug = ctx.params.id;
|
|
4896
|
+
if (!idOrSlug) return fail("admin.invalid", "id required", 400);
|
|
4897
|
+
return answerHistory(history, ctx, () => historySubject(idOrSlug), notFound3(idOrSlug));
|
|
4898
|
+
})
|
|
4899
|
+
);
|
|
2177
4900
|
adapter.registerRoute(
|
|
2178
4901
|
"PATCH",
|
|
2179
4902
|
"/api/admin/products/:id",
|
|
@@ -2181,10 +4904,7 @@ function registerAdminProductsRoutes(adapter, deps) {
|
|
|
2181
4904
|
try {
|
|
2182
4905
|
const id2 = ctx.params.id;
|
|
2183
4906
|
if (!id2) return fail("admin.invalid", "id required", 400);
|
|
2184
|
-
const snap = await product.update(
|
|
2185
|
-
id2,
|
|
2186
|
-
ctx.body
|
|
2187
|
-
);
|
|
4907
|
+
const snap = await product.update(id2, ctx.body);
|
|
2188
4908
|
return ok(snap);
|
|
2189
4909
|
} catch (err) {
|
|
2190
4910
|
return renderError(err);
|
|
@@ -2464,8 +5184,13 @@ function computeStats(orders) {
|
|
|
2464
5184
|
};
|
|
2465
5185
|
}
|
|
2466
5186
|
function registerAdminCustomersRoutes(adapter, deps) {
|
|
2467
|
-
const { repos } = deps;
|
|
5187
|
+
const { repos, history } = deps;
|
|
2468
5188
|
const { store } = repos.customer;
|
|
5189
|
+
async function historySubject(id2) {
|
|
5190
|
+
const found = await store.read((tx) => repos.customer.findById(tx, id2));
|
|
5191
|
+
return { kind: "customer", id: id2, live: found !== null };
|
|
5192
|
+
}
|
|
5193
|
+
const notFound3 = (id2) => () => fail("customers.not_found", `Customer not found: ${id2}`, 404);
|
|
2469
5194
|
adapter.registerRoute(
|
|
2470
5195
|
"GET",
|
|
2471
5196
|
"/api/admin/customers",
|
|
@@ -2516,6 +5241,8 @@ function registerAdminCustomersRoutes(adapter, deps) {
|
|
|
2516
5241
|
try {
|
|
2517
5242
|
const id2 = ctx.params.id;
|
|
2518
5243
|
if (!id2) return fail("admin.invalid", "id required", 400);
|
|
5244
|
+
const at = atOf(ctx);
|
|
5245
|
+
if (at !== void 0) return answerAsOf(history, at, () => historySubject(id2), notFound3(id2));
|
|
2519
5246
|
const found = await store.read(async (tx) => {
|
|
2520
5247
|
const raw = await repos.customer.findById(tx, id2);
|
|
2521
5248
|
return raw ? { raw, orders: await repos.order.listByCustomer(tx, id2) } : null;
|
|
@@ -2530,6 +5257,15 @@ function registerAdminCustomersRoutes(adapter, deps) {
|
|
|
2530
5257
|
}
|
|
2531
5258
|
})
|
|
2532
5259
|
);
|
|
5260
|
+
adapter.registerRoute(
|
|
5261
|
+
"GET",
|
|
5262
|
+
"/api/admin/customers/:id/history",
|
|
5263
|
+
requireRole("admin", async (ctx) => {
|
|
5264
|
+
const id2 = ctx.params.id;
|
|
5265
|
+
if (!id2) return fail("admin.invalid", "id required", 400);
|
|
5266
|
+
return answerHistory(history, ctx, () => historySubject(id2), notFound3(id2));
|
|
5267
|
+
})
|
|
5268
|
+
);
|
|
2533
5269
|
adapter.registerRoute(
|
|
2534
5270
|
"GET",
|
|
2535
5271
|
"/api/admin/customers/:id/orders",
|
|
@@ -2678,7 +5414,7 @@ import {
|
|
|
2678
5414
|
} from "@nymbalhq/types";
|
|
2679
5415
|
|
|
2680
5416
|
// src/settings/crypto.ts
|
|
2681
|
-
import { createCipheriv, createDecipheriv, createHash as
|
|
5417
|
+
import { createCipheriv, createDecipheriv, createHash as createHash4, randomBytes as randomBytes3 } from "crypto";
|
|
2682
5418
|
var ALGORITHM = "aes-256-gcm";
|
|
2683
5419
|
var IV_BYTES = 12;
|
|
2684
5420
|
var TAG_BYTES = 16;
|
|
@@ -2686,7 +5422,7 @@ var KEY_BYTES = 32;
|
|
|
2686
5422
|
var SECRETS_KEY_ENV = "NYMBAL_SECRETS_KEY";
|
|
2687
5423
|
var SECRETS_KEY_OLD_ENV = "NYMBAL_SECRETS_KEY_OLD";
|
|
2688
5424
|
function encrypt(key, aad, plaintext) {
|
|
2689
|
-
const iv =
|
|
5425
|
+
const iv = randomBytes3(IV_BYTES);
|
|
2690
5426
|
const cipher = createCipheriv(ALGORITHM, key, iv, { authTagLength: TAG_BYTES });
|
|
2691
5427
|
cipher.setAAD(Buffer.from(aad, "utf8"));
|
|
2692
5428
|
const ciphertext = Buffer.concat([cipher.update(plaintext, "utf8"), cipher.final()]);
|
|
@@ -2706,7 +5442,7 @@ function decrypt(key, aad, row) {
|
|
|
2706
5442
|
);
|
|
2707
5443
|
}
|
|
2708
5444
|
function keyId(key) {
|
|
2709
|
-
return
|
|
5445
|
+
return createHash4("sha256").update(key).digest("hex").slice(0, 8);
|
|
2710
5446
|
}
|
|
2711
5447
|
var BASE64_32 = /^[A-Za-z0-9+/]{43}=?$/;
|
|
2712
5448
|
function readSecretsKey(env, name = SECRETS_KEY_ENV) {
|
|
@@ -2876,16 +5612,16 @@ function createMiddlewareSecurityAdapter(deps) {
|
|
|
2876
5612
|
}
|
|
2877
5613
|
|
|
2878
5614
|
// src/adapters/payments/native-stub.ts
|
|
2879
|
-
import { v7 as
|
|
5615
|
+
import { v7 as uuidv714 } from "uuid";
|
|
2880
5616
|
import {
|
|
2881
|
-
EVT_PAYMENT_CAPTURED,
|
|
2882
|
-
EVT_PAYMENT_FAILED,
|
|
2883
|
-
EVT_PAYMENT_REFUNDED as
|
|
2884
|
-
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
|
|
2885
5621
|
} from "@nymbalhq/types";
|
|
2886
5622
|
var STUB_ID_PREFIX = "pi_stub_";
|
|
2887
5623
|
function rejected(message) {
|
|
2888
|
-
return new
|
|
5624
|
+
return new PaymentError3("refund_rejected", message);
|
|
2889
5625
|
}
|
|
2890
5626
|
function statusFor(receiptEmail) {
|
|
2891
5627
|
const address2 = receiptEmail ?? "";
|
|
@@ -2915,12 +5651,12 @@ function createNativeStubPaymentsAdapter(deps) {
|
|
|
2915
5651
|
capabilities: () => ["intent", "capture", "refund"],
|
|
2916
5652
|
// Nothing to collect: the receipt email decides the outcome.
|
|
2917
5653
|
client: () => ({ driver: "test-mode", options: {} }),
|
|
2918
|
-
producesEvents: [
|
|
5654
|
+
producesEvents: [EVT_PAYMENT_CAPTURED2, EVT_PAYMENT_FAILED2, EVT_PAYMENT_REFUNDED3],
|
|
2919
5655
|
consumesEvents: [],
|
|
2920
5656
|
initialize: noopInitialize,
|
|
2921
5657
|
healthCheck: () => okHealth("stub \u2014 always healthy"),
|
|
2922
5658
|
async createPaymentIntent(params) {
|
|
2923
|
-
const id2 = `${STUB_ID_PREFIX}${
|
|
5659
|
+
const id2 = `${STUB_ID_PREFIX}${uuidv714()}`;
|
|
2924
5660
|
const intent = {
|
|
2925
5661
|
id: id2,
|
|
2926
5662
|
amountMinor: params.amountMinor,
|
|
@@ -2935,7 +5671,7 @@ function createNativeStubPaymentsAdapter(deps) {
|
|
|
2935
5671
|
},
|
|
2936
5672
|
async capturePayment(intentId) {
|
|
2937
5673
|
const intent = intents.get(intentId);
|
|
2938
|
-
if (!intent) throw new
|
|
5674
|
+
if (!intent) throw new PaymentError3("capture_failed", `unknown intent ${intentId}`);
|
|
2939
5675
|
intent.status = "succeeded";
|
|
2940
5676
|
return {
|
|
2941
5677
|
paymentId: intent.id,
|
|
@@ -2954,7 +5690,7 @@ function createNativeStubPaymentsAdapter(deps) {
|
|
|
2954
5690
|
if (!paymentId.startsWith(STUB_ID_PREFIX)) throw rejected(`${paymentId} is not a stub intent`);
|
|
2955
5691
|
const answer = (amount2, currency) => {
|
|
2956
5692
|
const refund = {
|
|
2957
|
-
refundId: `re_stub_${
|
|
5693
|
+
refundId: `re_stub_${uuidv714()}`,
|
|
2958
5694
|
paymentId,
|
|
2959
5695
|
amountMinor: amount2,
|
|
2960
5696
|
currency,
|
|
@@ -2985,14 +5721,14 @@ function createNativeStubPaymentsAdapter(deps) {
|
|
|
2985
5721
|
},
|
|
2986
5722
|
async getPaymentIntent(intentId) {
|
|
2987
5723
|
const intent = intents.get(intentId);
|
|
2988
|
-
if (!intent) throw new
|
|
5724
|
+
if (!intent) throw new PaymentError3("intent_failed", `unknown intent ${intentId}`);
|
|
2989
5725
|
return toIntent(intent);
|
|
2990
5726
|
},
|
|
2991
5727
|
async cancelPaymentIntent(intentId) {
|
|
2992
5728
|
const intent = intents.get(intentId);
|
|
2993
5729
|
if (!intent) return;
|
|
2994
5730
|
if (intent.status === "succeeded") {
|
|
2995
|
-
throw new
|
|
5731
|
+
throw new PaymentError3("cancel_refused", `intent ${intentId} is already captured`);
|
|
2996
5732
|
}
|
|
2997
5733
|
intent.status = "cancelled";
|
|
2998
5734
|
},
|
|
@@ -3004,14 +5740,14 @@ function createNativeStubPaymentsAdapter(deps) {
|
|
|
3004
5740
|
if (held !== void 0 && event.kind === "payment.captured") held.status = "succeeded";
|
|
3005
5741
|
return {
|
|
3006
5742
|
verified: true,
|
|
3007
|
-
eventId: event.id ?? `evt_stub_${
|
|
5743
|
+
eventId: event.id ?? `evt_stub_${uuidv714()}`,
|
|
3008
5744
|
kind: event.kind ?? "ignored",
|
|
3009
5745
|
...event.paymentIntentId !== void 0 && { paymentIntentId: event.paymentIntentId },
|
|
3010
5746
|
...event.amountMinor !== void 0 && { amountMinor: event.amountMinor },
|
|
3011
5747
|
...event.currency !== void 0 && { currency: event.currency }
|
|
3012
5748
|
};
|
|
3013
5749
|
} catch (err) {
|
|
3014
|
-
throw new
|
|
5750
|
+
throw new PaymentError3("webhook_invalid", "stub webhook body not JSON", { cause: err });
|
|
3015
5751
|
}
|
|
3016
5752
|
}
|
|
3017
5753
|
};
|
|
@@ -3020,9 +5756,9 @@ function createNativeStubPaymentsAdapter(deps) {
|
|
|
3020
5756
|
// src/adapters/email/native-email-adapter.ts
|
|
3021
5757
|
import {
|
|
3022
5758
|
EVT_CART_ABANDONED,
|
|
3023
|
-
EVT_CUSTOMER_CREATED,
|
|
3024
|
-
EVT_ORDER_PLACED,
|
|
3025
|
-
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,
|
|
3026
5762
|
renderEmailTemplate
|
|
3027
5763
|
} from "@nymbalhq/types";
|
|
3028
5764
|
function createNativeEmailAdapter(deps) {
|
|
@@ -3032,7 +5768,7 @@ function createNativeEmailAdapter(deps) {
|
|
|
3032
5768
|
providerName: "native",
|
|
3033
5769
|
capabilities: () => ["transactional", "list-sync"],
|
|
3034
5770
|
producesEvents: [],
|
|
3035
|
-
consumesEvents: [
|
|
5771
|
+
consumesEvents: [EVT_ORDER_PLACED2, EVT_ORDER_SHIPPED2, EVT_CUSTOMER_CREATED2, EVT_CART_ABANDONED],
|
|
3036
5772
|
async initialize() {
|
|
3037
5773
|
},
|
|
3038
5774
|
healthCheck: () => okHealth("console transport"),
|
|
@@ -3056,10 +5792,10 @@ function createNativeEmailAdapter(deps) {
|
|
|
3056
5792
|
|
|
3057
5793
|
// src/adapters/search/native-adapter.ts
|
|
3058
5794
|
import {
|
|
3059
|
-
EVT_PRODUCT_CREATED,
|
|
3060
|
-
EVT_PRODUCT_DELETED,
|
|
3061
|
-
EVT_PRODUCT_UPDATED,
|
|
3062
|
-
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
|
|
3063
5799
|
} from "@nymbalhq/types";
|
|
3064
5800
|
|
|
3065
5801
|
// src/adapters/search/terms.ts
|
|
@@ -3335,7 +6071,7 @@ function createSqliteSearchIndex(raw) {
|
|
|
3335
6071
|
}
|
|
3336
6072
|
|
|
3337
6073
|
// src/adapters/search/native-adapter.ts
|
|
3338
|
-
var
|
|
6074
|
+
var DEFAULT_LIMIT2 = 20;
|
|
3339
6075
|
function encodeSearchCursor(offset) {
|
|
3340
6076
|
return Buffer.from(String(offset), "utf8").toString("base64url");
|
|
3341
6077
|
}
|
|
@@ -3343,7 +6079,7 @@ function decodeSearchCursor(cursor) {
|
|
|
3343
6079
|
const text = Buffer.from(cursor, "base64url").toString("utf8");
|
|
3344
6080
|
const offset = Number(text);
|
|
3345
6081
|
if (!/^\d+$/.test(text) || !Number.isSafeInteger(offset) || encodeSearchCursor(offset) !== cursor) {
|
|
3346
|
-
throw new
|
|
6082
|
+
throw new ValidationError10("malformed search cursor");
|
|
3347
6083
|
}
|
|
3348
6084
|
return offset;
|
|
3349
6085
|
}
|
|
@@ -3368,7 +6104,7 @@ function createNativeSearchAdapter(deps) {
|
|
|
3368
6104
|
providerName: "native",
|
|
3369
6105
|
capabilities: () => ["index", "search", "facet"],
|
|
3370
6106
|
producesEvents: [],
|
|
3371
|
-
consumesEvents: [
|
|
6107
|
+
consumesEvents: [EVT_PRODUCT_CREATED2, EVT_PRODUCT_UPDATED2, EVT_PRODUCT_DELETED2],
|
|
3372
6108
|
initialize: noopInitialize,
|
|
3373
6109
|
healthCheck: () => okHealth(),
|
|
3374
6110
|
async index(documents) {
|
|
@@ -3387,8 +6123,8 @@ function createNativeSearchAdapter(deps) {
|
|
|
3387
6123
|
},
|
|
3388
6124
|
async search(query, params) {
|
|
3389
6125
|
const offset = params?.cursor === void 0 ? 0 : decodeSearchCursor(params.cursor);
|
|
3390
|
-
const requested = params?.limit ??
|
|
3391
|
-
const limit = Number.isFinite(requested) ? Math.max(1, Math.floor(requested)) :
|
|
6126
|
+
const requested = params?.limit ?? DEFAULT_LIMIT2;
|
|
6127
|
+
const limit = Number.isFinite(requested) ? Math.max(1, Math.floor(requested)) : DEFAULT_LIMIT2;
|
|
3392
6128
|
const terms = uniqueTerms(query);
|
|
3393
6129
|
if (terms.length === 0) return { items: [], total: 0, nextCursor: null };
|
|
3394
6130
|
const categories = categoryFilter(params?.filters);
|
|
@@ -3417,10 +6153,10 @@ function createNativeSearchAdapter(deps) {
|
|
|
3417
6153
|
}
|
|
3418
6154
|
|
|
3419
6155
|
// src/adapters/reviews/native-adapter.ts
|
|
3420
|
-
import { v7 as
|
|
6156
|
+
import { v7 as uuidv715 } from "uuid";
|
|
3421
6157
|
import {
|
|
3422
|
-
EVT_ORDER_DELIVERED,
|
|
3423
|
-
ValidationError as
|
|
6158
|
+
EVT_ORDER_DELIVERED as EVT_ORDER_DELIVERED2,
|
|
6159
|
+
ValidationError as ValidationError11
|
|
3424
6160
|
} from "@nymbalhq/types";
|
|
3425
6161
|
function encodeReviewCursor(review) {
|
|
3426
6162
|
return Buffer.from(JSON.stringify([review.submittedAt, review.id]), "utf8").toString("base64url");
|
|
@@ -3430,10 +6166,10 @@ function decodeReviewCursor(cursor) {
|
|
|
3430
6166
|
try {
|
|
3431
6167
|
key = JSON.parse(Buffer.from(cursor, "base64url").toString("utf8"));
|
|
3432
6168
|
} catch (err) {
|
|
3433
|
-
throw new
|
|
6169
|
+
throw new ValidationError11("malformed reviews cursor", { cause: err });
|
|
3434
6170
|
}
|
|
3435
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) {
|
|
3436
|
-
throw new
|
|
6172
|
+
throw new ValidationError11("malformed reviews cursor");
|
|
3437
6173
|
}
|
|
3438
6174
|
return { submittedAt: key[0], id: key[1] };
|
|
3439
6175
|
}
|
|
@@ -3444,7 +6180,7 @@ function createNativeReviewsAdapter(deps) {
|
|
|
3444
6180
|
providerName: "native",
|
|
3445
6181
|
capabilities: () => ["submit", "moderate", "aggregate"],
|
|
3446
6182
|
producesEvents: [],
|
|
3447
|
-
consumesEvents: [
|
|
6183
|
+
consumesEvents: [EVT_ORDER_DELIVERED2],
|
|
3448
6184
|
initialize: noopInitialize,
|
|
3449
6185
|
healthCheck: () => okHealth(),
|
|
3450
6186
|
async getProductReviews(productId, params) {
|
|
@@ -3465,7 +6201,7 @@ function createNativeReviewsAdapter(deps) {
|
|
|
3465
6201
|
return { productId, ...agg };
|
|
3466
6202
|
},
|
|
3467
6203
|
async submitReview(submission) {
|
|
3468
|
-
const id2 =
|
|
6204
|
+
const id2 = uuidv715();
|
|
3469
6205
|
const now = /* @__PURE__ */ new Date();
|
|
3470
6206
|
const review = await repos.review.store.transaction(async (tx) => {
|
|
3471
6207
|
await repos.review.insert(tx, {
|
|
@@ -3572,7 +6308,7 @@ function createNativeTaxAdapter(logger, defaultRate = 0) {
|
|
|
3572
6308
|
}
|
|
3573
6309
|
|
|
3574
6310
|
// src/adapters/not-configured.ts
|
|
3575
|
-
import { AdapterError as
|
|
6311
|
+
import { AdapterError as AdapterError3 } from "@nymbalhq/types";
|
|
3576
6312
|
function createNotConfiguredAdapter(slot, provider, missing) {
|
|
3577
6313
|
const fields = missing.map((path) => `${slot}.${path}`).join(", ");
|
|
3578
6314
|
const detail = `${provider} is not configured: ${fields} not set (in the config, the environment or the admin's Settings)`;
|
|
@@ -3590,7 +6326,7 @@ function createNotConfiguredAdapter(slot, provider, missing) {
|
|
|
3590
6326
|
...slot === "payments" && { client: () => ({ driver: provider, options: {} }) }
|
|
3591
6327
|
};
|
|
3592
6328
|
const refuse = async () => {
|
|
3593
|
-
throw new
|
|
6329
|
+
throw new AdapterError3("not_configured", detail, { context: { slot, provider, missing } });
|
|
3594
6330
|
};
|
|
3595
6331
|
return new Proxy(base, {
|
|
3596
6332
|
get(target, property, receiver) {
|
|
@@ -4100,24 +6836,341 @@ function registerAdminSettingsRoutes(adapter, deps) {
|
|
|
4100
6836
|
);
|
|
4101
6837
|
}
|
|
4102
6838
|
|
|
6839
|
+
// src/history/fold.ts
|
|
6840
|
+
import {
|
|
6841
|
+
canTransitionOrder as canTransitionOrder3,
|
|
6842
|
+
paymentState as paymentState3
|
|
6843
|
+
} from "@nymbalhq/types";
|
|
6844
|
+
function eventName(type) {
|
|
6845
|
+
return type.replace(/\.v\d+$/, "");
|
|
6846
|
+
}
|
|
6847
|
+
function payloadOf(row) {
|
|
6848
|
+
const payload = row.event.payload;
|
|
6849
|
+
return payload !== null && typeof payload === "object" ? payload : {};
|
|
6850
|
+
}
|
|
6851
|
+
function objectAt(payload, key) {
|
|
6852
|
+
const value = payload[key];
|
|
6853
|
+
return value !== null && typeof value === "object" ? value : null;
|
|
6854
|
+
}
|
|
6855
|
+
var BASE_EVENTS = {
|
|
6856
|
+
product: { names: ["product.created", "product.updated"], snapshot: "product" },
|
|
6857
|
+
order: { names: ["order.placed"], snapshot: "order" },
|
|
6858
|
+
customer: { names: ["customer.created", "customer.updated"], snapshot: "customer" }
|
|
6859
|
+
};
|
|
6860
|
+
function isBaseEvent(kind, row) {
|
|
6861
|
+
const base = BASE_EVENTS[kind];
|
|
6862
|
+
return base.names.includes(eventName(row.event.type)) && objectAt(payloadOf(row), base.snapshot) !== null;
|
|
6863
|
+
}
|
|
6864
|
+
function isDeleted(view) {
|
|
6865
|
+
return view !== null && view.deleted === true;
|
|
6866
|
+
}
|
|
6867
|
+
function applyProduct(view, row) {
|
|
6868
|
+
if (isDeleted(view)) return view;
|
|
6869
|
+
const name = eventName(row.event.type);
|
|
6870
|
+
const payload = payloadOf(row);
|
|
6871
|
+
if (isBaseEvent("product", row)) return toProductAsOf(payload["product"]);
|
|
6872
|
+
if (name === "product.deleted") return { deleted: true, deletedAt: row.createdAt.toISOString() };
|
|
6873
|
+
if (view === null || name !== "inventory.changed") return view;
|
|
6874
|
+
const product = view;
|
|
6875
|
+
const variantId = payload["variantId"];
|
|
6876
|
+
const newQty = payload["newQty"];
|
|
6877
|
+
if (typeof newQty !== "number" || !product.variants.some((v) => v.id === variantId)) return view;
|
|
6878
|
+
return {
|
|
6879
|
+
...product,
|
|
6880
|
+
variants: product.variants.map((v) => v.id === variantId ? { ...v, stock: newQty } : v)
|
|
6881
|
+
};
|
|
6882
|
+
}
|
|
6883
|
+
function refundedStatus(status, target) {
|
|
6884
|
+
return status !== target && canTransitionOrder3(status, target) ? target : status;
|
|
6885
|
+
}
|
|
6886
|
+
function applyOrder(view, row, context2) {
|
|
6887
|
+
const name = eventName(row.event.type);
|
|
6888
|
+
const payload = payloadOf(row);
|
|
6889
|
+
if (isBaseEvent("order", row)) return orderViewOf(payload["order"]);
|
|
6890
|
+
if (view === null || isDeleted(view)) return view;
|
|
6891
|
+
const order = view;
|
|
6892
|
+
let next;
|
|
6893
|
+
switch (name) {
|
|
6894
|
+
case "order.status_changed":
|
|
6895
|
+
next = { ...order, status: payload["to"] };
|
|
6896
|
+
break;
|
|
6897
|
+
case "order.shipped":
|
|
6898
|
+
next = { ...order, status: "shipped" };
|
|
6899
|
+
break;
|
|
6900
|
+
case "order.delivered":
|
|
6901
|
+
next = { ...order, status: "delivered" };
|
|
6902
|
+
break;
|
|
6903
|
+
case "order.cancelled":
|
|
6904
|
+
next = { ...order, status: "cancelled" };
|
|
6905
|
+
break;
|
|
6906
|
+
case "payment.intent_created":
|
|
6907
|
+
next = { ...order, paymentIntentId: payload["paymentId"] };
|
|
6908
|
+
break;
|
|
6909
|
+
case "payment.captured":
|
|
6910
|
+
next = { ...order, capturedMinor: payload["amountMinor"] };
|
|
6911
|
+
break;
|
|
6912
|
+
case "order.paid":
|
|
6913
|
+
next = {
|
|
6914
|
+
...order,
|
|
6915
|
+
capturedMinor: payload["amountMinor"],
|
|
6916
|
+
status: order.status === "pending" ? "confirmed" : order.status
|
|
6917
|
+
};
|
|
6918
|
+
break;
|
|
6919
|
+
case "payment.refunded": {
|
|
6920
|
+
const refundId = payload["refundId"];
|
|
6921
|
+
if (context2.countedRefunds.has(refundId)) return view;
|
|
6922
|
+
context2.countedRefunds.add(refundId);
|
|
6923
|
+
next = { ...order, refundedMinor: order.refundedMinor + payload["amountMinor"] };
|
|
6924
|
+
break;
|
|
6925
|
+
}
|
|
6926
|
+
case "order.refunded":
|
|
6927
|
+
case "order.partially_refunded":
|
|
6928
|
+
context2.countedRefunds.add(payload["refundId"]);
|
|
6929
|
+
next = {
|
|
6930
|
+
...order,
|
|
6931
|
+
refundedMinor: order.refundedMinor + payload["amountMinor"],
|
|
6932
|
+
status: refundedStatus(
|
|
6933
|
+
order.status,
|
|
6934
|
+
name === "order.refunded" ? "refunded" : "partially_refunded"
|
|
6935
|
+
)
|
|
6936
|
+
};
|
|
6937
|
+
break;
|
|
6938
|
+
default:
|
|
6939
|
+
return view;
|
|
6940
|
+
}
|
|
6941
|
+
return {
|
|
6942
|
+
...next,
|
|
6943
|
+
payment: {
|
|
6944
|
+
...next.payment,
|
|
6945
|
+
state: paymentState3(next),
|
|
6946
|
+
capturedMinor: next.capturedMinor,
|
|
6947
|
+
refundedMinor: next.refundedMinor
|
|
6948
|
+
}
|
|
6949
|
+
};
|
|
6950
|
+
}
|
|
6951
|
+
function applyCustomer(view, row) {
|
|
6952
|
+
if (!isBaseEvent("customer", row)) return view;
|
|
6953
|
+
return toCustomerSnapshot(payloadOf(row)["customer"]);
|
|
6954
|
+
}
|
|
6955
|
+
function startFold(kind) {
|
|
6956
|
+
let view = null;
|
|
6957
|
+
const context2 = { countedRefunds: /* @__PURE__ */ new Set() };
|
|
6958
|
+
return {
|
|
6959
|
+
apply(row) {
|
|
6960
|
+
if (kind === "order") view = applyOrder(view, row, context2);
|
|
6961
|
+
else if (kind === "product") view = applyProduct(view, row);
|
|
6962
|
+
else view = applyCustomer(view, row);
|
|
6963
|
+
return view;
|
|
6964
|
+
}
|
|
6965
|
+
};
|
|
6966
|
+
}
|
|
6967
|
+
|
|
6968
|
+
// src/history/diff.ts
|
|
6969
|
+
function isPlain(value) {
|
|
6970
|
+
return value !== null && typeof value === "object" && !Array.isArray(value);
|
|
6971
|
+
}
|
|
6972
|
+
function equal(a, b) {
|
|
6973
|
+
if (a === b) return true;
|
|
6974
|
+
if (Array.isArray(a) && Array.isArray(b)) {
|
|
6975
|
+
return a.length === b.length && a.every((item, i) => equal(item, b[i]));
|
|
6976
|
+
}
|
|
6977
|
+
if (isPlain(a) && isPlain(b)) {
|
|
6978
|
+
const keys = /* @__PURE__ */ new Set([...Object.keys(a), ...Object.keys(b)]);
|
|
6979
|
+
return [...keys].every((key) => equal(a[key], b[key]));
|
|
6980
|
+
}
|
|
6981
|
+
return false;
|
|
6982
|
+
}
|
|
6983
|
+
var join3 = (path, key) => path === "" ? key : `${path}.${key}`;
|
|
6984
|
+
function keyed(items) {
|
|
6985
|
+
const byId = /* @__PURE__ */ new Map();
|
|
6986
|
+
for (const item of items) {
|
|
6987
|
+
const id2 = isPlain(item) ? item["id"] : void 0;
|
|
6988
|
+
if (typeof id2 !== "string" || byId.has(id2)) return null;
|
|
6989
|
+
byId.set(id2, item);
|
|
6990
|
+
}
|
|
6991
|
+
return byId;
|
|
6992
|
+
}
|
|
6993
|
+
function entriesOf(a, b) {
|
|
6994
|
+
const ka = keyed(a);
|
|
6995
|
+
const kb = keyed(b);
|
|
6996
|
+
if (ka !== null && kb !== null) return [ka, kb];
|
|
6997
|
+
const byIndex = (items) => new Map(items.map((item, i) => [String(i), item]));
|
|
6998
|
+
return [byIndex(a), byIndex(b)];
|
|
6999
|
+
}
|
|
7000
|
+
function diffMaps(path, a, b, out) {
|
|
7001
|
+
for (const key of /* @__PURE__ */ new Set([...a.keys(), ...b.keys()])) {
|
|
7002
|
+
const from = a.get(key);
|
|
7003
|
+
const to = b.get(key);
|
|
7004
|
+
if (from !== void 0 && to !== void 0) diffValue(join3(path, key), from, to, out);
|
|
7005
|
+
else if (!equal(from ?? null, to ?? null)) {
|
|
7006
|
+
out.push({ path: join3(path, key), from: from ?? null, to: to ?? null });
|
|
7007
|
+
}
|
|
7008
|
+
}
|
|
7009
|
+
}
|
|
7010
|
+
function diffValue(path, a, b, out) {
|
|
7011
|
+
if (isPlain(a) && isPlain(b)) {
|
|
7012
|
+
diffMaps(path, new Map(Object.entries(a)), new Map(Object.entries(b)), out);
|
|
7013
|
+
} else if (Array.isArray(a) && Array.isArray(b)) {
|
|
7014
|
+
diffMaps(path, ...entriesOf(a, b), out);
|
|
7015
|
+
} else if (!equal(a, b)) {
|
|
7016
|
+
out.push({ path, from: a ?? null, to: b ?? null });
|
|
7017
|
+
}
|
|
7018
|
+
}
|
|
7019
|
+
function diffViews(before, after) {
|
|
7020
|
+
if (before === null || after === null || isDeleted(before)) return [];
|
|
7021
|
+
if (isDeleted(after)) return [{ path: "deletedAt", from: null, to: after.deletedAt }];
|
|
7022
|
+
const out = [];
|
|
7023
|
+
diffValue("", before, after, out);
|
|
7024
|
+
return out;
|
|
7025
|
+
}
|
|
7026
|
+
|
|
7027
|
+
// src/history/read.ts
|
|
7028
|
+
var DAY_MS = 24 * 60 * 60 * 1e3;
|
|
7029
|
+
var READ_PAGE = 1e3;
|
|
7030
|
+
function createHistoryReader(deps) {
|
|
7031
|
+
const { eventLog, auditEntries: auditEntries3, retentionDays } = deps;
|
|
7032
|
+
const { store } = eventLog;
|
|
7033
|
+
async function readAll(tx, subjects) {
|
|
7034
|
+
const rows = [];
|
|
7035
|
+
for (; ; ) {
|
|
7036
|
+
const last = rows[rows.length - 1];
|
|
7037
|
+
const page = await eventLog.listBySubjects(tx, subjects, {
|
|
7038
|
+
limit: READ_PAGE,
|
|
7039
|
+
...last !== void 0 && { afterSeq: last.seq }
|
|
7040
|
+
});
|
|
7041
|
+
rows.push(...page);
|
|
7042
|
+
if (page.length < READ_PAGE) return rows;
|
|
7043
|
+
}
|
|
7044
|
+
}
|
|
7045
|
+
async function rowsOf(tx, kind, id2) {
|
|
7046
|
+
const own = await readAll(tx, [{ type: kind, id: id2 }]);
|
|
7047
|
+
if (kind !== "product") return own;
|
|
7048
|
+
const variantIds = /* @__PURE__ */ new Set();
|
|
7049
|
+
for (const row of own) {
|
|
7050
|
+
if (!isBaseEvent("product", row)) continue;
|
|
7051
|
+
const product = row.event.payload.product;
|
|
7052
|
+
for (const variant of product.variants ?? []) {
|
|
7053
|
+
if (typeof variant.id === "string") variantIds.add(variant.id);
|
|
7054
|
+
}
|
|
7055
|
+
}
|
|
7056
|
+
if (variantIds.size === 0) return own;
|
|
7057
|
+
return readAll(tx, [
|
|
7058
|
+
{ type: "product", id: id2 },
|
|
7059
|
+
...[...variantIds].map((variantId) => ({ type: "variant", id: variantId }))
|
|
7060
|
+
]);
|
|
7061
|
+
}
|
|
7062
|
+
function startOf(kind, rows) {
|
|
7063
|
+
const horizon = Date.now() - retentionDays * DAY_MS;
|
|
7064
|
+
return rows.findIndex((row) => isBaseEvent(kind, row) && row.createdAt.getTime() >= horizon);
|
|
7065
|
+
}
|
|
7066
|
+
async function actorsOf(tx, entries) {
|
|
7067
|
+
const byCorrelation = /* @__PURE__ */ new Map();
|
|
7068
|
+
for (const correlation of new Set(entries.map((e) => e.correlationId))) {
|
|
7069
|
+
const [applied] = await auditEntries3.list(tx, {
|
|
7070
|
+
correlation,
|
|
7071
|
+
outcome: "applied",
|
|
7072
|
+
order: "asc",
|
|
7073
|
+
limit: 1
|
|
7074
|
+
});
|
|
7075
|
+
byCorrelation.set(
|
|
7076
|
+
correlation,
|
|
7077
|
+
applied === void 0 ? { actor: null, command: null } : { actor: applied.actor, command: applied.command }
|
|
7078
|
+
);
|
|
7079
|
+
}
|
|
7080
|
+
for (const entry of entries) Object.assign(entry, byCorrelation.get(entry.correlationId));
|
|
7081
|
+
}
|
|
7082
|
+
return {
|
|
7083
|
+
asOf(subject, at) {
|
|
7084
|
+
return store.read(async (tx) => {
|
|
7085
|
+
const rows = await rowsOf(tx, subject.kind, subject.id);
|
|
7086
|
+
if (rows.length === 0 && !subject.live) return { kind: "not_found" };
|
|
7087
|
+
const start = startOf(subject.kind, rows);
|
|
7088
|
+
if (start < 0) return { kind: "before_start", historyStartsAt: null };
|
|
7089
|
+
const startsAt = rows[start].createdAt;
|
|
7090
|
+
if (at.getTime() < startsAt.getTime()) {
|
|
7091
|
+
return { kind: "before_start", historyStartsAt: startsAt.toISOString() };
|
|
7092
|
+
}
|
|
7093
|
+
const fold = startFold(subject.kind);
|
|
7094
|
+
let view = null;
|
|
7095
|
+
for (const row of rows.slice(start)) {
|
|
7096
|
+
if (row.createdAt.getTime() <= at.getTime()) view = fold.apply(row);
|
|
7097
|
+
}
|
|
7098
|
+
if (isDeleted(view)) return { kind: "deleted", deletedAt: view.deletedAt };
|
|
7099
|
+
return {
|
|
7100
|
+
kind: "record",
|
|
7101
|
+
read: { asOf: at.toISOString(), historyStartsAt: startsAt.toISOString(), record: view }
|
|
7102
|
+
};
|
|
7103
|
+
});
|
|
7104
|
+
},
|
|
7105
|
+
list(subject, page) {
|
|
7106
|
+
return store.read(async (tx) => {
|
|
7107
|
+
const rows = await rowsOf(tx, subject.kind, subject.id);
|
|
7108
|
+
if (rows.length === 0 && !subject.live) return null;
|
|
7109
|
+
const start = startOf(subject.kind, rows);
|
|
7110
|
+
if (start < 0)
|
|
7111
|
+
return { historyStartsAt: null, retentionDays, entries: [], nextCursor: null };
|
|
7112
|
+
const entries = [];
|
|
7113
|
+
const fold = startFold(subject.kind);
|
|
7114
|
+
let view = null;
|
|
7115
|
+
for (const [i, row] of rows.slice(start).entries()) {
|
|
7116
|
+
const before = view;
|
|
7117
|
+
view = fold.apply(row);
|
|
7118
|
+
const changes = diffViews(before, view);
|
|
7119
|
+
if (i > 0 && changes.length === 0) continue;
|
|
7120
|
+
entries.push({
|
|
7121
|
+
seq: row.seq,
|
|
7122
|
+
at: row.createdAt.toISOString(),
|
|
7123
|
+
type: row.event.type,
|
|
7124
|
+
correlationId: row.event.correlationId,
|
|
7125
|
+
actor: null,
|
|
7126
|
+
command: null,
|
|
7127
|
+
base: i === 0,
|
|
7128
|
+
changes
|
|
7129
|
+
});
|
|
7130
|
+
}
|
|
7131
|
+
const newest = entries.reverse().filter((e) => page.beforeSeq === void 0 || e.seq < page.beforeSeq);
|
|
7132
|
+
const shown = newest.slice(0, page.limit);
|
|
7133
|
+
await actorsOf(tx, shown);
|
|
7134
|
+
const last = shown[shown.length - 1];
|
|
7135
|
+
return {
|
|
7136
|
+
historyStartsAt: rows[start].createdAt.toISOString(),
|
|
7137
|
+
retentionDays,
|
|
7138
|
+
entries: shown,
|
|
7139
|
+
nextCursor: newest.length > shown.length && last !== void 0 ? String(last.seq) : null
|
|
7140
|
+
};
|
|
7141
|
+
});
|
|
7142
|
+
}
|
|
7143
|
+
};
|
|
7144
|
+
}
|
|
7145
|
+
|
|
4103
7146
|
// src/routes/admin.ts
|
|
4104
7147
|
function registerAdminRoutes(adapter, deps) {
|
|
4105
7148
|
const { config, services, repos, adapters } = deps;
|
|
7149
|
+
const history = createHistoryReader({
|
|
7150
|
+
eventLog: repos.eventLog,
|
|
7151
|
+
auditEntries: repos.auditEntry,
|
|
7152
|
+
retentionDays: config.events.retentionDays
|
|
7153
|
+
});
|
|
4106
7154
|
registerAdminMeRoute(adapter, { config });
|
|
4107
7155
|
registerAdminDashboardRoute(adapter, { repos, config });
|
|
4108
7156
|
registerAdminOrdersRoutes(adapter, {
|
|
4109
7157
|
order: services.order,
|
|
4110
7158
|
checkout: services.checkout,
|
|
4111
7159
|
refund: services.refund,
|
|
4112
|
-
repos
|
|
7160
|
+
repos,
|
|
7161
|
+
history
|
|
7162
|
+
});
|
|
7163
|
+
registerAdminProductsRoutes(adapter, {
|
|
7164
|
+
product: services.product,
|
|
7165
|
+
ai: adapters.ai,
|
|
7166
|
+
history
|
|
4113
7167
|
});
|
|
4114
|
-
registerAdminProductsRoutes(adapter, { product: services.product, ai: adapters.ai });
|
|
4115
7168
|
registerAdminInventoryRoutes(adapter, {
|
|
4116
7169
|
inventory: services.inventory,
|
|
4117
7170
|
product: services.product,
|
|
4118
7171
|
repos
|
|
4119
7172
|
});
|
|
4120
|
-
registerAdminCustomersRoutes(adapter, { order: services.order, repos });
|
|
7173
|
+
registerAdminCustomersRoutes(adapter, { order: services.order, repos, history });
|
|
4121
7174
|
registerAdminSearchRoute(adapter, {
|
|
4122
7175
|
order: services.order,
|
|
4123
7176
|
product: services.product,
|
|
@@ -4212,7 +7265,7 @@ function registerAdminStaticRoute(adapter, root) {
|
|
|
4212
7265
|
}
|
|
4213
7266
|
|
|
4214
7267
|
// src/routes/events-sse.ts
|
|
4215
|
-
import { createHmac, randomBytes as
|
|
7268
|
+
import { createHmac, randomBytes as randomBytes4 } from "crypto";
|
|
4216
7269
|
import "@nymbalhq/types";
|
|
4217
7270
|
var TICKET_TTL_SECONDS = 60;
|
|
4218
7271
|
var NONCE_COLLECTION = "sse-ticket-nonces";
|
|
@@ -4239,7 +7292,7 @@ function registerEventsSseRoute(adapter, deps) {
|
|
|
4239
7292
|
"/api/admin/events/ticket",
|
|
4240
7293
|
requireRole("admin", (ctx) => {
|
|
4241
7294
|
try {
|
|
4242
|
-
const nonce =
|
|
7295
|
+
const nonce = randomBytes4(12).toString("base64url");
|
|
4243
7296
|
const payload = {
|
|
4244
7297
|
uid: ctx.auth.userId,
|
|
4245
7298
|
roles: ctx.auth.roles ?? ["admin"],
|
|
@@ -4308,35 +7361,68 @@ function registerEventsSseRoute(adapter, deps) {
|
|
|
4308
7361
|
void fail;
|
|
4309
7362
|
}
|
|
4310
7363
|
|
|
4311
|
-
// src/routes/webhooks-
|
|
7364
|
+
// src/routes/webhooks-inbound.ts
|
|
4312
7365
|
import {
|
|
4313
|
-
|
|
4314
|
-
|
|
7366
|
+
ConfigError as ConfigError5,
|
|
7367
|
+
EVT_PAYMENT_FAILED as EVT_PAYMENT_FAILED3,
|
|
7368
|
+
webhookDeliveryProblem
|
|
4315
7369
|
} from "@nymbalhq/types";
|
|
4316
|
-
|
|
4317
|
-
|
|
4318
|
-
|
|
4319
|
-
|
|
4320
|
-
|
|
4321
|
-
|
|
4322
|
-
|
|
4323
|
-
|
|
4324
|
-
|
|
4325
|
-
|
|
4326
|
-
|
|
4327
|
-
|
|
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);
|
|
4328
7414
|
async function publishFailed(tx, paymentIntentId, reason) {
|
|
4329
7415
|
const order = paymentIntentId ? await orders.findByPaymentIntentId(tx, paymentIntentId) : null;
|
|
4330
7416
|
await inOrderScope(
|
|
4331
7417
|
order,
|
|
4332
|
-
() => publisher.publish(
|
|
7418
|
+
() => publisher.publish(EVT_PAYMENT_FAILED3, {
|
|
4333
7419
|
paymentId: paymentIntentId,
|
|
4334
7420
|
orderId: order?.id ?? "",
|
|
4335
7421
|
reason
|
|
4336
7422
|
})
|
|
4337
7423
|
);
|
|
4338
7424
|
}
|
|
4339
|
-
async function
|
|
7425
|
+
async function handlePayment(tx, result) {
|
|
4340
7426
|
if (result.kind === "payment.captured") {
|
|
4341
7427
|
const paymentIntentId = result.paymentIntentId ?? "";
|
|
4342
7428
|
if (paymentIntentId === "" || typeof result.amountMinor !== "number" || typeof result.currency !== "string" || result.currency === "") {
|
|
@@ -4355,49 +7441,101 @@ function registerStripeWebhookRoute(adapter, deps) {
|
|
|
4355
7441
|
}
|
|
4356
7442
|
return ok({ ignored: true });
|
|
4357
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
|
+
}
|
|
4358
7503
|
adapter.registerRoute(
|
|
4359
7504
|
"POST",
|
|
4360
|
-
"/api/webhooks
|
|
4361
|
-
|
|
4362
|
-
|
|
4363
|
-
|
|
4364
|
-
|
|
4365
|
-
|
|
4366
|
-
|
|
4367
|
-
|
|
4368
|
-
|
|
4369
|
-
|
|
4370
|
-
|
|
4371
|
-
);
|
|
4372
|
-
}
|
|
4373
|
-
let result;
|
|
4374
|
-
try {
|
|
4375
|
-
result = await payments.parseWebhook(ctx.rawBody, sig);
|
|
4376
|
-
} catch (err) {
|
|
4377
|
-
if (err instanceof PaymentError3 && err.code === "payment.webhook_invalid") {
|
|
4378
|
-
return fail("webhook.invalid", "signature verification failed", 400);
|
|
4379
|
-
}
|
|
4380
|
-
throw err;
|
|
4381
|
-
}
|
|
4382
|
-
if (!result.verified) return fail("webhook.invalid", "signature verification failed", 400);
|
|
4383
|
-
return await store.transaction(async (tx) => {
|
|
4384
|
-
if (await processedEvents.seen(tx, HANDLER, result.eventId))
|
|
4385
|
-
return ok({ deduped: true });
|
|
4386
|
-
const answer = await handle(tx, result);
|
|
4387
|
-
await processedEvents.markProcessed(tx, HANDLER, result.eventId, /* @__PURE__ */ new Date());
|
|
4388
|
-
return answer;
|
|
4389
|
-
});
|
|
4390
|
-
} catch (err) {
|
|
4391
|
-
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();
|
|
4392
7516
|
}
|
|
4393
|
-
|
|
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
|
+
},
|
|
4394
7532
|
{ csrf: false, rawBody: true }
|
|
4395
7533
|
);
|
|
4396
7534
|
}
|
|
4397
7535
|
|
|
4398
7536
|
// src/routes/validated-adapter.ts
|
|
4399
7537
|
import {
|
|
4400
|
-
ConfigError as
|
|
7538
|
+
ConfigError as ConfigError6
|
|
4401
7539
|
} from "@nymbalhq/types";
|
|
4402
7540
|
|
|
4403
7541
|
// src/routes/schemas.ts
|
|
@@ -4406,6 +7544,8 @@ import { PRODUCT_SORT_KEYS as PRODUCT_SORT_KEYS2 } from "@nymbalhq/types";
|
|
|
4406
7544
|
var id = z.string().min(1);
|
|
4407
7545
|
var queryValue = z.union([z.string(), z.array(z.string())]).optional();
|
|
4408
7546
|
var paging = { limit: queryValue, offset: queryValue };
|
|
7547
|
+
var asOfQuery = z.object({ at: queryValue });
|
|
7548
|
+
var historyQuery = z.object({ cursor: queryValue, limit: queryValue });
|
|
4409
7549
|
var idParams = z.object({ id });
|
|
4410
7550
|
var orderIdParams = idParams;
|
|
4411
7551
|
var variantIdParams = z.object({ variantId: id });
|
|
@@ -4444,6 +7584,11 @@ var productVariant = z.object({
|
|
|
4444
7584
|
options: z.array(z.object({ name: z.string(), value: z.string() })),
|
|
4445
7585
|
status: z.enum(["active", "inactive"]).optional()
|
|
4446
7586
|
});
|
|
7587
|
+
var variantPrices = z.object({
|
|
7588
|
+
id,
|
|
7589
|
+
priceMinor: money.min(0),
|
|
7590
|
+
compareAtPriceMinor: money.min(0).nullable().optional()
|
|
7591
|
+
});
|
|
4447
7592
|
var productFields = {
|
|
4448
7593
|
description: z.string().optional(),
|
|
4449
7594
|
shortDescription: z.string().optional(),
|
|
@@ -4492,7 +7637,7 @@ var routeSchemas = {
|
|
|
4492
7637
|
// Store
|
|
4493
7638
|
"GET /api/capabilities": {
|
|
4494
7639
|
name: "capabilities.get",
|
|
4495
|
-
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."
|
|
4496
7641
|
},
|
|
4497
7642
|
// Catalogue
|
|
4498
7643
|
"GET /api/categories": {
|
|
@@ -4525,6 +7670,29 @@ var routeSchemas = {
|
|
|
4525
7670
|
params: idParams,
|
|
4526
7671
|
query: z.object({ limit: queryValue, cursor: queryValue })
|
|
4527
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
|
+
},
|
|
4528
7696
|
// Cart
|
|
4529
7697
|
"GET /api/cart": {
|
|
4530
7698
|
name: "cart.get",
|
|
@@ -4572,9 +7740,20 @@ var routeSchemas = {
|
|
|
4572
7740
|
},
|
|
4573
7741
|
"GET /api/orders/:orderNumber": {
|
|
4574
7742
|
name: "orders.get",
|
|
4575
|
-
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.",
|
|
4576
7744
|
params: orderNumberParams
|
|
4577
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
|
+
},
|
|
4578
7757
|
// Customer account
|
|
4579
7758
|
"GET /api/customers/me": {
|
|
4580
7759
|
name: "customers.me",
|
|
@@ -4655,8 +7834,15 @@ var routeSchemas = {
|
|
|
4655
7834
|
},
|
|
4656
7835
|
"GET /api/admin/orders/:orderNumber": {
|
|
4657
7836
|
name: "admin.orders.get",
|
|
4658
|
-
description: "Get one order with its status history.",
|
|
4659
|
-
params: orderNumberParams
|
|
7837
|
+
description: "Get one order with its status history; with `at`, the order as the event log folds it at that time.",
|
|
7838
|
+
params: orderNumberParams,
|
|
7839
|
+
query: asOfQuery
|
|
7840
|
+
},
|
|
7841
|
+
"GET /api/admin/orders/:id/history": {
|
|
7842
|
+
name: "admin.orders.history",
|
|
7843
|
+
description: "List an order's changes from the event log, newest first.",
|
|
7844
|
+
params: orderIdParams,
|
|
7845
|
+
query: historyQuery
|
|
4660
7846
|
},
|
|
4661
7847
|
"POST /api/admin/orders/:id/confirm": {
|
|
4662
7848
|
name: "admin.orders.confirm",
|
|
@@ -4729,7 +7915,7 @@ var routeSchemas = {
|
|
|
4729
7915
|
},
|
|
4730
7916
|
"POST /api/admin/orders/:id/resend-confirmation": {
|
|
4731
7917
|
name: "admin.orders.resendConfirmation",
|
|
4732
|
-
command:
|
|
7918
|
+
command: "order.resendConfirmation",
|
|
4733
7919
|
description: "Resend an order's confirmation email.",
|
|
4734
7920
|
params: orderIdParams
|
|
4735
7921
|
},
|
|
@@ -4750,12 +7936,28 @@ var routeSchemas = {
|
|
|
4750
7936
|
variants: z.array(productVariant).optional()
|
|
4751
7937
|
})
|
|
4752
7938
|
},
|
|
7939
|
+
"GET /api/admin/products/:id": {
|
|
7940
|
+
name: "admin.products.get",
|
|
7941
|
+
description: "Get one product by id or slug; with `at`, the product as the event log folds it at that time.",
|
|
7942
|
+
params: idParams,
|
|
7943
|
+
query: asOfQuery
|
|
7944
|
+
},
|
|
7945
|
+
"GET /api/admin/products/:id/history": {
|
|
7946
|
+
name: "admin.products.history",
|
|
7947
|
+
description: "List a product's changes from the event log, newest first.",
|
|
7948
|
+
params: idParams,
|
|
7949
|
+
query: historyQuery
|
|
7950
|
+
},
|
|
4753
7951
|
"PATCH /api/admin/products/:id": {
|
|
4754
7952
|
name: "admin.products.update",
|
|
4755
7953
|
command: "product.update",
|
|
4756
|
-
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.",
|
|
4757
7955
|
params: idParams,
|
|
4758
|
-
body: z.object({
|
|
7956
|
+
body: z.object({
|
|
7957
|
+
name: z.string().optional(),
|
|
7958
|
+
...productFields,
|
|
7959
|
+
variants: z.array(variantPrices).optional()
|
|
7960
|
+
})
|
|
4759
7961
|
},
|
|
4760
7962
|
"DELETE /api/admin/products/:id": {
|
|
4761
7963
|
name: "admin.products.delete",
|
|
@@ -4833,8 +8035,15 @@ var routeSchemas = {
|
|
|
4833
8035
|
},
|
|
4834
8036
|
"GET /api/admin/customers/:id": {
|
|
4835
8037
|
name: "admin.customers.get",
|
|
4836
|
-
description: "Get one customer with order statistics.",
|
|
4837
|
-
params: idParams
|
|
8038
|
+
description: "Get one customer with order statistics; with `at`, the customer as the event log folds it at that time.",
|
|
8039
|
+
params: idParams,
|
|
8040
|
+
query: asOfQuery
|
|
8041
|
+
},
|
|
8042
|
+
"GET /api/admin/customers/:id/history": {
|
|
8043
|
+
name: "admin.customers.history",
|
|
8044
|
+
description: "List a customer's changes from the event log, newest first.",
|
|
8045
|
+
params: idParams,
|
|
8046
|
+
query: historyQuery
|
|
4838
8047
|
},
|
|
4839
8048
|
"GET /api/admin/customers/:id/orders": {
|
|
4840
8049
|
name: "admin.customers.orders",
|
|
@@ -4893,10 +8102,12 @@ var routeSchemas = {
|
|
|
4893
8102
|
query: z.object({ since: queryValue, until: queryValue, correlation: queryValue })
|
|
4894
8103
|
},
|
|
4895
8104
|
// Webhooks
|
|
4896
|
-
"POST /api/webhooks
|
|
4897
|
-
name: "webhooks.
|
|
4898
|
-
command:
|
|
4899
|
-
|
|
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 }),
|
|
4900
8111
|
// The signature covers the raw bytes, and a malformed event is answered by the handler itself.
|
|
4901
8112
|
body: z.unknown()
|
|
4902
8113
|
},
|
|
@@ -4922,7 +8133,7 @@ function schemaFor(method, path) {
|
|
|
4922
8133
|
const key = `${method} ${path}`;
|
|
4923
8134
|
const schema = routeSchemas[key];
|
|
4924
8135
|
if (!schema) {
|
|
4925
|
-
throw new
|
|
8136
|
+
throw new ConfigError6(`route ${key} has no entry in routeSchemas`, {
|
|
4926
8137
|
code: "config.route_schema_missing",
|
|
4927
8138
|
context: { method, path }
|
|
4928
8139
|
});
|
|
@@ -4958,7 +8169,7 @@ function parseInput(schema, ctx) {
|
|
|
4958
8169
|
}
|
|
4959
8170
|
};
|
|
4960
8171
|
}
|
|
4961
|
-
function
|
|
8172
|
+
function invalid2(issues) {
|
|
4962
8173
|
return fail("validation.failed", "The request input is invalid", 400, { issues });
|
|
4963
8174
|
}
|
|
4964
8175
|
function validatedAdapter(adapter) {
|
|
@@ -4970,7 +8181,7 @@ function validatedAdapter(adapter) {
|
|
|
4970
8181
|
path,
|
|
4971
8182
|
async (ctx) => {
|
|
4972
8183
|
const input = parseInput(schema, ctx);
|
|
4973
|
-
return input.ok ? handler(input.ctx) :
|
|
8184
|
+
return input.ok ? handler(input.ctx) : invalid2(input.issues);
|
|
4974
8185
|
},
|
|
4975
8186
|
options
|
|
4976
8187
|
);
|
|
@@ -5007,17 +8218,17 @@ function validatedAdapter(adapter) {
|
|
|
5007
8218
|
// src/routes/admin-activity.ts
|
|
5008
8219
|
import { Readable } from "stream";
|
|
5009
8220
|
var OUTCOMES = /* @__PURE__ */ new Set(["applied", "refused", "replayed"]);
|
|
5010
|
-
var
|
|
5011
|
-
var
|
|
8221
|
+
var DEFAULT_LIMIT3 = 50;
|
|
8222
|
+
var MAX_LIMIT2 = 200;
|
|
5012
8223
|
var QueryError = class extends Error {
|
|
5013
8224
|
};
|
|
5014
|
-
function
|
|
8225
|
+
function one2(ctx, name) {
|
|
5015
8226
|
const value = ctx.query[name];
|
|
5016
8227
|
const first = Array.isArray(value) ? value[0] : value;
|
|
5017
8228
|
return first === void 0 || first === "" ? void 0 : first;
|
|
5018
8229
|
}
|
|
5019
8230
|
function time(ctx, name) {
|
|
5020
|
-
const value =
|
|
8231
|
+
const value = one2(ctx, name);
|
|
5021
8232
|
if (value === void 0) return void 0;
|
|
5022
8233
|
const at = new Date(value);
|
|
5023
8234
|
if (Number.isNaN(at.getTime())) throw new QueryError(`${name} must be an ISO 8601 time`);
|
|
@@ -5026,10 +8237,10 @@ function time(ctx, name) {
|
|
|
5026
8237
|
function filterOf(ctx, names) {
|
|
5027
8238
|
const filter = {};
|
|
5028
8239
|
for (const name of ["actor", "command", "subject", "correlation"]) {
|
|
5029
|
-
const value = names.includes(name) ?
|
|
8240
|
+
const value = names.includes(name) ? one2(ctx, name) : void 0;
|
|
5030
8241
|
if (value !== void 0) filter[name] = value;
|
|
5031
8242
|
}
|
|
5032
|
-
const outcome = names.includes("outcome") ?
|
|
8243
|
+
const outcome = names.includes("outcome") ? one2(ctx, "outcome") : void 0;
|
|
5033
8244
|
if (outcome !== void 0) {
|
|
5034
8245
|
if (!OUTCOMES.has(outcome)) throw new QueryError("outcome must be applied, refused or replayed");
|
|
5035
8246
|
filter.outcome = outcome;
|
|
@@ -5055,12 +8266,12 @@ function decodeCursor(value) {
|
|
|
5055
8266
|
throw new QueryError("cursor is not one this API issued");
|
|
5056
8267
|
}
|
|
5057
8268
|
function limitOf(ctx) {
|
|
5058
|
-
const value =
|
|
5059
|
-
if (value === void 0) return
|
|
8269
|
+
const value = one2(ctx, "limit");
|
|
8270
|
+
if (value === void 0) return DEFAULT_LIMIT3;
|
|
5060
8271
|
const n = Number(value);
|
|
5061
8272
|
if (!Number.isInteger(n) || n < 1)
|
|
5062
8273
|
throw new QueryError("limit must be a whole number of at least 1");
|
|
5063
|
-
return Math.min(n,
|
|
8274
|
+
return Math.min(n, MAX_LIMIT2);
|
|
5064
8275
|
}
|
|
5065
8276
|
function answerError(err) {
|
|
5066
8277
|
return err instanceof QueryError ? fail("activity.invalid", err.message, 400) : renderError(err);
|
|
@@ -5075,7 +8286,7 @@ function registerAdminActivityRoutes(adapter, deps) {
|
|
|
5075
8286
|
try {
|
|
5076
8287
|
const filter = filterOf(ctx, ["actor", "command", "subject", "correlation", "outcome"]);
|
|
5077
8288
|
const limit = limitOf(ctx);
|
|
5078
|
-
const cursor = decodeCursor(
|
|
8289
|
+
const cursor = decodeCursor(one2(ctx, "cursor"));
|
|
5079
8290
|
const rows = await store.read(
|
|
5080
8291
|
(tx) => auditEntries3.list(tx, {
|
|
5081
8292
|
...filter,
|
|
@@ -5120,6 +8331,47 @@ function registerAdminActivityRoutes(adapter, deps) {
|
|
|
5120
8331
|
);
|
|
5121
8332
|
}
|
|
5122
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
|
+
|
|
5123
8375
|
// src/routes/register.ts
|
|
5124
8376
|
function correlatedAdapter(adapter) {
|
|
5125
8377
|
return {
|
|
@@ -5150,7 +8402,7 @@ function commandOf(method, path) {
|
|
|
5150
8402
|
if (method === "GET" || schema === void 0) return void 0;
|
|
5151
8403
|
const { command } = schema;
|
|
5152
8404
|
if (command === void 0) {
|
|
5153
|
-
throw new
|
|
8405
|
+
throw new ConfigError7(`route ${method} ${path} declares no audit command in routeSchemas`, {
|
|
5154
8406
|
code: "config.route_command_missing",
|
|
5155
8407
|
context: { method, path }
|
|
5156
8408
|
});
|
|
@@ -5169,15 +8421,15 @@ function auditedAdapter(adapter, store) {
|
|
|
5169
8421
|
(ctx) => {
|
|
5170
8422
|
const actor = actorOf(ctx.auth);
|
|
5171
8423
|
return runAsActor(actor, async () => {
|
|
5172
|
-
const
|
|
5173
|
-
if ("malformed" in
|
|
8424
|
+
const keyed2 = adminWrite ? idempotencyKeyOf(ctx) : { key: void 0 };
|
|
8425
|
+
if ("malformed" in keyed2) return malformedKey();
|
|
5174
8426
|
if (!command) return handler(ctx);
|
|
5175
8427
|
const run = async () => handler(ctx);
|
|
5176
|
-
if (
|
|
8428
|
+
if (keyed2.key === void 0) return auditedRoute(store, command, run);
|
|
5177
8429
|
return idempotentCommand(
|
|
5178
8430
|
store,
|
|
5179
8431
|
command,
|
|
5180
|
-
{ actor, key:
|
|
8432
|
+
{ actor, key: keyed2.key, hash: requestHash(ctx), provider },
|
|
5181
8433
|
run
|
|
5182
8434
|
);
|
|
5183
8435
|
});
|
|
@@ -5206,7 +8458,8 @@ function registerAllRoutes(deps) {
|
|
|
5206
8458
|
repos.auditEntry.store
|
|
5207
8459
|
);
|
|
5208
8460
|
adapter.registerMiddleware(createAuthMiddleware(services.auth));
|
|
5209
|
-
|
|
8461
|
+
const afterSignIn = [foldViewsOnSignIn(services.recentlyViewed)];
|
|
8462
|
+
registerAuthRoutes(adapter, services.auth, config.security.auth.refreshTtl, afterSignIn);
|
|
5210
8463
|
registerCapabilitiesRoute(adapter, adapters);
|
|
5211
8464
|
registerCategoryRoutes(adapter, documentStore, config.store.name);
|
|
5212
8465
|
registerProductRoutes(
|
|
@@ -5223,7 +8476,14 @@ function registerAllRoutes(deps) {
|
|
|
5223
8476
|
productRepo: repos.product,
|
|
5224
8477
|
variantRepo: repos.variant
|
|
5225
8478
|
});
|
|
8479
|
+
registerRecentlyViewedRoutes(adapter, {
|
|
8480
|
+
recentlyViewed: services.recentlyViewed,
|
|
8481
|
+
documentStore,
|
|
8482
|
+
productRepo: repos.product,
|
|
8483
|
+
retentionDays: config.events.retentionDays
|
|
8484
|
+
});
|
|
5226
8485
|
registerCheckoutRoutes(adapter, services.checkout);
|
|
8486
|
+
registerAlertRoutes(adapter, { alerts: services.alert });
|
|
5227
8487
|
registerOrderRoutes(adapter, services.order, documentStore);
|
|
5228
8488
|
registerCustomerRoutes(adapter, services.customer);
|
|
5229
8489
|
registerAdminRoutes(adapter, {
|
|
@@ -5240,8 +8500,8 @@ function registerAllRoutes(deps) {
|
|
|
5240
8500
|
documentStore,
|
|
5241
8501
|
ticketSecret: config.security.auth.jwtSecret
|
|
5242
8502
|
});
|
|
5243
|
-
|
|
5244
|
-
|
|
8503
|
+
registerInboundWebhookRoute(adapter, {
|
|
8504
|
+
adapters,
|
|
5245
8505
|
checkout: services.checkout,
|
|
5246
8506
|
publisher,
|
|
5247
8507
|
store: repos.processedEvent.store,
|
|
@@ -5283,12 +8543,46 @@ export {
|
|
|
5283
8543
|
outsideCommand,
|
|
5284
8544
|
audit,
|
|
5285
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,
|
|
5286
8564
|
formatMoney,
|
|
8565
|
+
mintOrderKey,
|
|
8566
|
+
parseDurationToMs,
|
|
8567
|
+
createAuthService,
|
|
8568
|
+
createProductService,
|
|
8569
|
+
createCategoryService,
|
|
8570
|
+
createCartService,
|
|
8571
|
+
createCustomerService,
|
|
8572
|
+
createOrderService,
|
|
8573
|
+
createInventoryService,
|
|
5287
8574
|
PROVIDER_REFUND_REASON,
|
|
5288
8575
|
orderPayment,
|
|
5289
8576
|
settlementOf,
|
|
5290
8577
|
refreshRefunded,
|
|
5291
8578
|
createRefundService,
|
|
8579
|
+
createCheckoutService,
|
|
8580
|
+
createSearchService,
|
|
8581
|
+
createRecentlyViewedService,
|
|
8582
|
+
newAlertToken,
|
|
8583
|
+
createAlertService,
|
|
8584
|
+
emailDelivers,
|
|
8585
|
+
buildServices,
|
|
5292
8586
|
SECRETS_KEY_ENV,
|
|
5293
8587
|
SECRETS_KEY_OLD_ENV,
|
|
5294
8588
|
encrypt,
|
|
@@ -5300,8 +8594,6 @@ export {
|
|
|
5300
8594
|
CSRF_COOKIE,
|
|
5301
8595
|
CSRF_HEADER,
|
|
5302
8596
|
buildSecurityHeaders,
|
|
5303
|
-
noopInitialize,
|
|
5304
|
-
okHealth,
|
|
5305
8597
|
createMiddlewareSecurityAdapter,
|
|
5306
8598
|
createNativeStubPaymentsAdapter,
|
|
5307
8599
|
createNativeEmailAdapter,
|
|
@@ -5325,8 +8617,8 @@ export {
|
|
|
5325
8617
|
settingValues,
|
|
5326
8618
|
loadBootSettings,
|
|
5327
8619
|
registerAdminStaticRoute,
|
|
5328
|
-
inOrderScope,
|
|
5329
8620
|
routeSchemas,
|
|
8621
|
+
registerAlertRoutes,
|
|
5330
8622
|
registerAllRoutes
|
|
5331
8623
|
};
|
|
5332
|
-
//# sourceMappingURL=chunk-
|
|
8624
|
+
//# sourceMappingURL=chunk-GMV3B3SC.js.map
|