@nymbalhq/platform 1.3.0 → 1.5.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-QN56IB4G.js → chunk-NNDIAIT6.js} +187 -5
- package/dist/chunk-NNDIAIT6.js.map +1 -0
- package/dist/{chunk-2PLYK5RU.js → chunk-TRLERRUI.js} +3559 -509
- package/dist/chunk-TRLERRUI.js.map +1 -0
- package/dist/db/schema/index.d.ts +5276 -3224
- package/dist/db/schema/index.js +1 -1
- package/dist/index.d.ts +428 -81
- package/dist/index.js +1200 -2254
- package/dist/index.js.map +1 -1
- package/dist/register-SBGUI2L5.js +8 -0
- package/migrations/postgres/0013_order_access_keys.sql +11 -0
- package/migrations/postgres/0014_alert_subscriptions.sql +22 -0
- package/migrations/postgres/0015_events_retry_at.sql +1 -0
- package/migrations/postgres/0016_email_suppressions.sql +7 -0
- package/migrations/postgres/0017_order_shipments.sql +14 -0
- package/migrations/postgres/0018_order_key_expiry.sql +8 -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/0016_snapshot.json +2233 -0
- package/migrations/postgres/meta/0017_snapshot.json +2300 -0
- package/migrations/postgres/meta/0018_snapshot.json +2306 -0
- package/migrations/postgres/meta/_journal.json +42 -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/0016_email_suppressions.sql +7 -0
- package/migrations/sqlite/0017_order_shipments.sql +9 -0
- package/migrations/sqlite/0018_order_key_expiry.sql +25 -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/0016_snapshot.json +1981 -0
- package/migrations/sqlite/meta/0017_snapshot.json +2041 -0
- package/migrations/sqlite/meta/0018_snapshot.json +2048 -0
- package/migrations/sqlite/meta/_journal.json +42 -0
- package/package.json +17 -47
- package/dist/chunk-2PLYK5RU.js.map +0 -1
- package/dist/chunk-QN56IB4G.js.map +0 -1
- package/dist/register-UUQ64HZP.js +0 -8
- /package/dist/{register-UUQ64HZP.js.map → register-SBGUI2L5.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-NNDIAIT6.js";
|
|
9
9
|
|
|
10
10
|
// src/routes/register.ts
|
|
11
11
|
import {
|
|
12
|
-
ConfigError as
|
|
12
|
+
ConfigError as ConfigError7
|
|
13
13
|
} from "@nymbalhq/types";
|
|
14
14
|
|
|
15
15
|
// src/events/correlation.ts
|
|
@@ -951,8 +951,659 @@ function createAuthMiddleware(auth) {
|
|
|
951
951
|
|
|
952
952
|
// src/routes/auth.ts
|
|
953
953
|
import {
|
|
954
|
-
AuthError
|
|
954
|
+
AuthError as AuthError3
|
|
955
|
+
} from "@nymbalhq/types";
|
|
956
|
+
|
|
957
|
+
// src/services/auth-service.ts
|
|
958
|
+
import { v7 as uuidv73 } from "uuid";
|
|
959
|
+
import bcrypt from "bcryptjs";
|
|
960
|
+
import { SignJWT, jwtVerify } from "jose";
|
|
961
|
+
import { createHash as createHash2 } from "crypto";
|
|
962
|
+
import {
|
|
963
|
+
AuthError,
|
|
964
|
+
EVT_CUSTOMER_CREATED,
|
|
965
|
+
ValidationError as ValidationError2
|
|
966
|
+
} from "@nymbalhq/types";
|
|
967
|
+
|
|
968
|
+
// src/history/views.ts
|
|
969
|
+
import {
|
|
970
|
+
paymentState
|
|
971
|
+
} from "@nymbalhq/types";
|
|
972
|
+
function orderViewOf(order) {
|
|
973
|
+
const {
|
|
974
|
+
notes: _notes,
|
|
975
|
+
metadata: _metadata,
|
|
976
|
+
updatedAt: _updatedAt,
|
|
977
|
+
capturedAt: _capturedAt,
|
|
978
|
+
captureMethod: _captureMethod,
|
|
979
|
+
...rest
|
|
980
|
+
} = order;
|
|
981
|
+
const { payment: _payment, history: _history, ...view } = rest;
|
|
982
|
+
return {
|
|
983
|
+
...view,
|
|
984
|
+
payment: {
|
|
985
|
+
state: paymentState(order),
|
|
986
|
+
capturedMinor: order.capturedMinor,
|
|
987
|
+
refundedMinor: order.refundedMinor,
|
|
988
|
+
currency: order.currency
|
|
989
|
+
}
|
|
990
|
+
};
|
|
991
|
+
}
|
|
992
|
+
function toProductAsOf(snapshot2) {
|
|
993
|
+
return {
|
|
994
|
+
...snapshot2,
|
|
995
|
+
variants: snapshot2.variants.map(({ updatedAt: _updatedAt, ...variant }) => variant),
|
|
996
|
+
// A set: product.created keeps the order it was sent in, a read the repository's.
|
|
997
|
+
categoryIds: [...snapshot2.categoryIds].sort()
|
|
998
|
+
};
|
|
999
|
+
}
|
|
1000
|
+
function toCustomerSnapshot(customer) {
|
|
1001
|
+
return {
|
|
1002
|
+
id: customer.id,
|
|
1003
|
+
email: customer.email,
|
|
1004
|
+
firstName: customer.firstName,
|
|
1005
|
+
lastName: customer.lastName,
|
|
1006
|
+
phone: customer.phone,
|
|
1007
|
+
addresses: customer.addresses,
|
|
1008
|
+
createdAt: customer.createdAt
|
|
1009
|
+
};
|
|
1010
|
+
}
|
|
1011
|
+
|
|
1012
|
+
// src/services/auth-service.ts
|
|
1013
|
+
var { hash: bcryptHash, compare: bcryptCompare } = bcrypt;
|
|
1014
|
+
function parseDurationToMs(s) {
|
|
1015
|
+
const match = /^(\d+)(ms|s|m|h|d)$/.exec(s);
|
|
1016
|
+
if (!match) throw new ValidationError2(`invalid duration: ${s}`);
|
|
1017
|
+
const qty = Number(match[1]);
|
|
1018
|
+
switch (match[2]) {
|
|
1019
|
+
case "ms":
|
|
1020
|
+
return qty;
|
|
1021
|
+
case "s":
|
|
1022
|
+
return qty * 1e3;
|
|
1023
|
+
case "m":
|
|
1024
|
+
return qty * 60 * 1e3;
|
|
1025
|
+
case "h":
|
|
1026
|
+
return qty * 60 * 60 * 1e3;
|
|
1027
|
+
case "d":
|
|
1028
|
+
return qty * 24 * 60 * 60 * 1e3;
|
|
1029
|
+
/* c8 ignore next 2 -- regex above only matches ms|s|m|h|d, making this unreachable */
|
|
1030
|
+
default:
|
|
1031
|
+
throw new ValidationError2(`invalid duration unit: ${match[2]}`);
|
|
1032
|
+
}
|
|
1033
|
+
}
|
|
1034
|
+
function hashRefresh(token) {
|
|
1035
|
+
return createHash2("sha256").update(token).digest("hex");
|
|
1036
|
+
}
|
|
1037
|
+
function stripPassword(c) {
|
|
1038
|
+
const { passwordHash: _pw, ...rest } = c;
|
|
1039
|
+
return rest;
|
|
1040
|
+
}
|
|
1041
|
+
function createAuthService(deps) {
|
|
1042
|
+
const { repos, publisher, logger, jwtSecret, accessTtl, refreshTtl } = deps;
|
|
1043
|
+
const { store } = repos.customer;
|
|
1044
|
+
const issuer = deps.issuer ?? "nymbal";
|
|
1045
|
+
const secretKey = new TextEncoder().encode(jwtSecret);
|
|
1046
|
+
const accessTtlMs = parseDurationToMs(accessTtl);
|
|
1047
|
+
const refreshTtlMs = parseDurationToMs(refreshTtl);
|
|
1048
|
+
async function mintAccess(customer) {
|
|
1049
|
+
return new SignJWT({
|
|
1050
|
+
sub: customer.id,
|
|
1051
|
+
email: customer.email,
|
|
1052
|
+
roles: customer.roles,
|
|
1053
|
+
type: "access"
|
|
1054
|
+
}).setProtectedHeader({ alg: "HS256" }).setIssuedAt().setIssuer(issuer).setExpirationTime(new Date(Date.now() + accessTtlMs)).sign(secretKey);
|
|
1055
|
+
}
|
|
1056
|
+
async function mintRefresh(customer, jti) {
|
|
1057
|
+
return new SignJWT({
|
|
1058
|
+
sub: customer.id,
|
|
1059
|
+
email: customer.email,
|
|
1060
|
+
roles: ["customer"],
|
|
1061
|
+
type: "refresh",
|
|
1062
|
+
jti
|
|
1063
|
+
}).setProtectedHeader({ alg: "HS256" }).setIssuedAt().setJti(jti).setIssuer(issuer).setExpirationTime(new Date(Date.now() + refreshTtlMs)).sign(secretKey);
|
|
1064
|
+
}
|
|
1065
|
+
async function issueTokens(customer) {
|
|
1066
|
+
const jti = uuidv73();
|
|
1067
|
+
const refreshToken = await mintRefresh(customer, jti);
|
|
1068
|
+
await store.transaction(
|
|
1069
|
+
(tx) => repos.refreshToken.insert(tx, {
|
|
1070
|
+
id: jti,
|
|
1071
|
+
customerId: customer.id,
|
|
1072
|
+
tokenHash: hashRefresh(refreshToken),
|
|
1073
|
+
expiresAt: new Date(Date.now() + refreshTtlMs),
|
|
1074
|
+
createdAt: /* @__PURE__ */ new Date()
|
|
1075
|
+
})
|
|
1076
|
+
);
|
|
1077
|
+
const accessToken = await mintAccess(customer);
|
|
1078
|
+
return {
|
|
1079
|
+
accessToken,
|
|
1080
|
+
refreshToken,
|
|
1081
|
+
expiresIn: Math.floor(accessTtlMs / 1e3)
|
|
1082
|
+
};
|
|
1083
|
+
}
|
|
1084
|
+
return {
|
|
1085
|
+
async register(input) {
|
|
1086
|
+
audit.note("customer.register");
|
|
1087
|
+
if (!input.email.includes("@")) throw new ValidationError2("invalid email");
|
|
1088
|
+
if (input.password.length < 8) throw new ValidationError2("password must be \u2265 8 characters");
|
|
1089
|
+
const email = input.email.toLowerCase();
|
|
1090
|
+
const existing = await store.read((tx) => repos.customer.findByEmail(tx, email));
|
|
1091
|
+
if (existing) {
|
|
1092
|
+
throw new AuthError("invalid_credentials", "An account with this email already exists");
|
|
1093
|
+
}
|
|
1094
|
+
const id2 = uuidv73();
|
|
1095
|
+
const passwordHash = await bcryptHash(input.password, 10);
|
|
1096
|
+
const now = /* @__PURE__ */ new Date();
|
|
1097
|
+
const customer = await store.transaction(async (tx) => {
|
|
1098
|
+
audit.note("customer.register", [{ type: "customer", id: id2 }]);
|
|
1099
|
+
await repos.customer.insert(tx, {
|
|
1100
|
+
id: id2,
|
|
1101
|
+
email,
|
|
1102
|
+
passwordHash,
|
|
1103
|
+
...input.firstName !== void 0 && { firstName: input.firstName },
|
|
1104
|
+
...input.lastName !== void 0 && { lastName: input.lastName },
|
|
1105
|
+
...input.phone !== void 0 && { phone: input.phone },
|
|
1106
|
+
createdAt: now,
|
|
1107
|
+
updatedAt: now
|
|
1108
|
+
});
|
|
1109
|
+
const inserted = await repos.customer.findById(tx, id2);
|
|
1110
|
+
if (!inserted) throw new Error("customer disappeared after insert");
|
|
1111
|
+
await publisher.publish(EVT_CUSTOMER_CREATED, {
|
|
1112
|
+
customerId: id2,
|
|
1113
|
+
email,
|
|
1114
|
+
customer: toCustomerSnapshot(inserted)
|
|
1115
|
+
});
|
|
1116
|
+
return inserted;
|
|
1117
|
+
});
|
|
1118
|
+
const tokens = await issueTokens(customer);
|
|
1119
|
+
logger.info({ customerId: id2 }, "customer registered");
|
|
1120
|
+
return { customer: stripPassword(customer), tokens };
|
|
1121
|
+
},
|
|
1122
|
+
async login(email, password) {
|
|
1123
|
+
const customer = await store.read((tx) => repos.customer.findByEmail(tx, email.toLowerCase()));
|
|
1124
|
+
if (!customer) throw new AuthError("invalid_credentials", "Invalid email or password");
|
|
1125
|
+
const ok2 = await bcryptCompare(password, customer.passwordHash);
|
|
1126
|
+
if (!ok2) throw new AuthError("invalid_credentials", "Invalid email or password");
|
|
1127
|
+
const tokens = await issueTokens(customer);
|
|
1128
|
+
logger.info({ customerId: customer.id }, "customer login");
|
|
1129
|
+
return { customer: stripPassword(customer), tokens };
|
|
1130
|
+
},
|
|
1131
|
+
async refresh(refreshToken) {
|
|
1132
|
+
let verified;
|
|
1133
|
+
try {
|
|
1134
|
+
verified = await jwtVerify(refreshToken, secretKey, { issuer });
|
|
1135
|
+
} catch {
|
|
1136
|
+
throw new AuthError("token_invalid", "refresh token invalid");
|
|
1137
|
+
}
|
|
1138
|
+
const payload = verified.payload;
|
|
1139
|
+
if (payload.type !== "refresh" || !payload.jti || !payload.sub) {
|
|
1140
|
+
throw new AuthError("token_invalid", "not a refresh token");
|
|
1141
|
+
}
|
|
1142
|
+
const jti = payload.jti;
|
|
1143
|
+
const customerId = payload.sub;
|
|
1144
|
+
const record2 = await store.read((tx) => repos.refreshToken.findById(tx, jti));
|
|
1145
|
+
if (!record2) throw new AuthError("token_invalid", "refresh token unknown");
|
|
1146
|
+
if (record2.revokedAt) throw new AuthError("token_invalid", "refresh token revoked");
|
|
1147
|
+
if (record2.tokenHash !== hashRefresh(refreshToken)) {
|
|
1148
|
+
await store.transaction((tx) => repos.refreshToken.revokeAllForCustomer(tx, customerId));
|
|
1149
|
+
throw new AuthError("token_invalid", "refresh token mismatch; revoking chain");
|
|
1150
|
+
}
|
|
1151
|
+
const customer = await store.read((tx) => repos.customer.findById(tx, customerId));
|
|
1152
|
+
if (!customer) throw new AuthError("token_invalid", "customer missing");
|
|
1153
|
+
const nextJti = uuidv73();
|
|
1154
|
+
const nextRefresh = await mintRefresh(customer, nextJti);
|
|
1155
|
+
await store.transaction(
|
|
1156
|
+
(tx) => repos.refreshToken.rotate(tx, jti, {
|
|
1157
|
+
id: nextJti,
|
|
1158
|
+
customerId: customer.id,
|
|
1159
|
+
tokenHash: hashRefresh(nextRefresh),
|
|
1160
|
+
expiresAt: new Date(Date.now() + refreshTtlMs),
|
|
1161
|
+
createdAt: /* @__PURE__ */ new Date()
|
|
1162
|
+
})
|
|
1163
|
+
);
|
|
1164
|
+
const accessToken = await mintAccess(customer);
|
|
1165
|
+
return {
|
|
1166
|
+
accessToken,
|
|
1167
|
+
refreshToken: nextRefresh,
|
|
1168
|
+
expiresIn: Math.floor(accessTtlMs / 1e3)
|
|
1169
|
+
};
|
|
1170
|
+
},
|
|
1171
|
+
async logout(refreshToken) {
|
|
1172
|
+
try {
|
|
1173
|
+
const verified = await jwtVerify(refreshToken, secretKey, { issuer });
|
|
1174
|
+
const payload = verified.payload;
|
|
1175
|
+
const { jti } = payload;
|
|
1176
|
+
if (jti) await store.transaction((tx) => repos.refreshToken.revoke(tx, jti));
|
|
1177
|
+
} catch {
|
|
1178
|
+
}
|
|
1179
|
+
},
|
|
1180
|
+
async verifyAccessToken(token) {
|
|
1181
|
+
try {
|
|
1182
|
+
const verified = await jwtVerify(token, secretKey, { issuer });
|
|
1183
|
+
const payload = verified.payload;
|
|
1184
|
+
if (payload.type !== "access") throw new AuthError("token_invalid", "not an access token");
|
|
1185
|
+
return payload;
|
|
1186
|
+
} catch (err) {
|
|
1187
|
+
if (err instanceof AuthError) throw err;
|
|
1188
|
+
throw new AuthError("token_invalid", "access token invalid", { cause: err });
|
|
1189
|
+
}
|
|
1190
|
+
},
|
|
1191
|
+
async importCustomer(input) {
|
|
1192
|
+
if (!input.email.includes("@")) throw new ValidationError2("invalid email");
|
|
1193
|
+
const email = input.email.toLowerCase();
|
|
1194
|
+
const customer = await store.transaction(async (tx) => {
|
|
1195
|
+
const existing = await repos.customer.findByEmail(tx, email);
|
|
1196
|
+
if (existing) return existing;
|
|
1197
|
+
const id2 = uuidv73();
|
|
1198
|
+
audit.note("customer.import", [{ type: "customer", id: id2 }]);
|
|
1199
|
+
const now = /* @__PURE__ */ new Date();
|
|
1200
|
+
await repos.customer.insert(tx, {
|
|
1201
|
+
id: id2,
|
|
1202
|
+
email,
|
|
1203
|
+
passwordHash: "IMPORTED_NO_PASSWORD",
|
|
1204
|
+
requiresPasswordReset: true,
|
|
1205
|
+
...input.firstName !== void 0 && { firstName: input.firstName },
|
|
1206
|
+
...input.lastName !== void 0 && { lastName: input.lastName },
|
|
1207
|
+
...input.phone !== void 0 && { phone: input.phone },
|
|
1208
|
+
...input.addresses !== void 0 && { addresses: input.addresses },
|
|
1209
|
+
...input.metadata !== void 0 && { metadata: input.metadata },
|
|
1210
|
+
roles: ["customer"],
|
|
1211
|
+
createdAt: now,
|
|
1212
|
+
updatedAt: now
|
|
1213
|
+
});
|
|
1214
|
+
const inserted = await repos.customer.findById(tx, id2);
|
|
1215
|
+
if (!inserted) throw new Error("customer disappeared after insert");
|
|
1216
|
+
await publisher.publish(EVT_CUSTOMER_CREATED, {
|
|
1217
|
+
customerId: id2,
|
|
1218
|
+
email,
|
|
1219
|
+
customer: toCustomerSnapshot(inserted)
|
|
1220
|
+
});
|
|
1221
|
+
logger.info({ customerId: id2 }, "customer imported");
|
|
1222
|
+
return inserted;
|
|
1223
|
+
});
|
|
1224
|
+
return stripPassword(customer);
|
|
1225
|
+
}
|
|
1226
|
+
};
|
|
1227
|
+
}
|
|
1228
|
+
|
|
1229
|
+
// src/routes/recently-viewed.ts
|
|
1230
|
+
import { v7 as uuidv74 } from "uuid";
|
|
1231
|
+
import {
|
|
1232
|
+
AuthError as AuthError2
|
|
1233
|
+
} from "@nymbalhq/types";
|
|
1234
|
+
|
|
1235
|
+
// src/read-models/recently-viewed.ts
|
|
1236
|
+
import {
|
|
1237
|
+
EVT_CUSTOMER_DELETED,
|
|
1238
|
+
EVT_PRODUCT_VIEWED,
|
|
1239
|
+
EVT_VISITOR_MERGED
|
|
955
1240
|
} from "@nymbalhq/types";
|
|
1241
|
+
|
|
1242
|
+
// src/handlers/derived.ts
|
|
1243
|
+
async function subscribeDerived(eventBus, handlers) {
|
|
1244
|
+
for (const h of handlers) {
|
|
1245
|
+
const pattern = h.types.length === 1 ? h.types[0] : [...h.types];
|
|
1246
|
+
await eventBus.subscribe(pattern, h.handle, { name: h.name, derived: true });
|
|
1247
|
+
}
|
|
1248
|
+
}
|
|
1249
|
+
|
|
1250
|
+
// src/handlers/projections/recently-viewed-projection.ts
|
|
1251
|
+
function recentlyViewedProjection(deps) {
|
|
1252
|
+
const { documentStore, logger } = deps;
|
|
1253
|
+
const docs = {
|
|
1254
|
+
get: (key) => documentStore.get(RECENTLY_VIEWED, key),
|
|
1255
|
+
put: (key, doc) => documentStore.put(RECENTLY_VIEWED, key, doc),
|
|
1256
|
+
delete: (key) => documentStore.delete(RECENTLY_VIEWED, key)
|
|
1257
|
+
};
|
|
1258
|
+
const handle = async (event) => {
|
|
1259
|
+
await foldEvent(docs, event);
|
|
1260
|
+
logger.debug({ type: event.type }, "recently viewed projected");
|
|
1261
|
+
};
|
|
1262
|
+
return [{ name: "recently-viewed-projection", types: RECENTLY_VIEWED_TYPES, handle }];
|
|
1263
|
+
}
|
|
1264
|
+
async function registerRecentlyViewedProjection(deps) {
|
|
1265
|
+
await subscribeDerived(deps.eventBus, recentlyViewedProjection(deps));
|
|
1266
|
+
}
|
|
1267
|
+
|
|
1268
|
+
// src/order-history-notes.ts
|
|
1269
|
+
var REFUND_NOTE_PREFIX = "refund of ";
|
|
1270
|
+
|
|
1271
|
+
// src/read-models/order-timeline.ts
|
|
1272
|
+
var MOVES = {
|
|
1273
|
+
shipped: "shipped",
|
|
1274
|
+
delivered: "delivered",
|
|
1275
|
+
cancelled: "cancelled",
|
|
1276
|
+
refunded: "refunded",
|
|
1277
|
+
partially_refunded: "partially_refunded"
|
|
1278
|
+
};
|
|
1279
|
+
function kindOf(row) {
|
|
1280
|
+
const { fromStatus: from, toStatus: to } = row;
|
|
1281
|
+
if (from === null) return to === "pending" ? "placed" : null;
|
|
1282
|
+
if (from === to) {
|
|
1283
|
+
return to === "partially_refunded" && row.note.startsWith(REFUND_NOTE_PREFIX) ? "partially_refunded" : null;
|
|
1284
|
+
}
|
|
1285
|
+
if (from === "pending" && to === "confirmed") return "paid";
|
|
1286
|
+
return MOVES[to] ?? null;
|
|
1287
|
+
}
|
|
1288
|
+
function orderTimeline(history) {
|
|
1289
|
+
const entries = [];
|
|
1290
|
+
for (const row of history) {
|
|
1291
|
+
const kind = kindOf(row);
|
|
1292
|
+
if (kind !== null) entries.push({ kind, at: row.timestamp });
|
|
1293
|
+
}
|
|
1294
|
+
return entries;
|
|
1295
|
+
}
|
|
1296
|
+
|
|
1297
|
+
// src/read-models/builders.ts
|
|
1298
|
+
var CATEGORIES = "categories";
|
|
1299
|
+
var PRODUCTS = "products";
|
|
1300
|
+
var PRODUCTS_BY_CATEGORY = "products-by-category";
|
|
1301
|
+
var ORDERS = "orders";
|
|
1302
|
+
var ORDERS_BY_CUSTOMER = "orders-by-customer";
|
|
1303
|
+
var CUSTOMER_PROFILES = "customer-profiles";
|
|
1304
|
+
var RECENTLY_VIEWED = "recently-viewed";
|
|
1305
|
+
function buildCategoryDoc(category, storeId) {
|
|
1306
|
+
return {
|
|
1307
|
+
id: category.id,
|
|
1308
|
+
storeId,
|
|
1309
|
+
parentId: category.parentId,
|
|
1310
|
+
slug: category.slug,
|
|
1311
|
+
name: category.name,
|
|
1312
|
+
description: category.description,
|
|
1313
|
+
position: category.position,
|
|
1314
|
+
createdAt: category.createdAt
|
|
1315
|
+
};
|
|
1316
|
+
}
|
|
1317
|
+
var isVariantOption = (o) => typeof o === "object" && o !== null && typeof o.name === "string" && typeof o.value === "string";
|
|
1318
|
+
function variantOptions(raw, sku, logger) {
|
|
1319
|
+
let value = raw;
|
|
1320
|
+
if (typeof raw === "string") {
|
|
1321
|
+
try {
|
|
1322
|
+
value = JSON.parse(raw);
|
|
1323
|
+
} catch (err) {
|
|
1324
|
+
logger?.warn({ sku, err }, "variant options are not JSON; projected as none");
|
|
1325
|
+
return [];
|
|
1326
|
+
}
|
|
1327
|
+
}
|
|
1328
|
+
if (!Array.isArray(value)) return [];
|
|
1329
|
+
return value.filter(isVariantOption).map((o) => ({ name: o.name, value: o.value }));
|
|
1330
|
+
}
|
|
1331
|
+
function buildProductDoc(p, categories, ctx) {
|
|
1332
|
+
const prices = p.variants.map((v) => v.priceMinor);
|
|
1333
|
+
return {
|
|
1334
|
+
id: p.id,
|
|
1335
|
+
storeId: ctx.storeId,
|
|
1336
|
+
slug: p.slug,
|
|
1337
|
+
name: p.name,
|
|
1338
|
+
description: p.description,
|
|
1339
|
+
shortDescription: p.shortDescription,
|
|
1340
|
+
status: p.status,
|
|
1341
|
+
type: p.type,
|
|
1342
|
+
media: p.media,
|
|
1343
|
+
variantCount: p.variants.length,
|
|
1344
|
+
inStock: p.variants.some((v) => v.stock > 0),
|
|
1345
|
+
priceRange: prices.length ? { minMinor: Math.min(...prices), maxMinor: Math.max(...prices) } : null,
|
|
1346
|
+
currency: ctx.currency,
|
|
1347
|
+
priceMinor: prices[0] ?? null,
|
|
1348
|
+
variants: p.variants.map((v) => ({
|
|
1349
|
+
id: v.id,
|
|
1350
|
+
sku: v.sku,
|
|
1351
|
+
name: v.name,
|
|
1352
|
+
priceMinor: v.priceMinor,
|
|
1353
|
+
stock: v.stock,
|
|
1354
|
+
options: variantOptions(v.options, v.sku, ctx.logger)
|
|
1355
|
+
})),
|
|
1356
|
+
categoryIds: p.categoryIds,
|
|
1357
|
+
categories: p.categoryIds.flatMap((id2) => {
|
|
1358
|
+
const c = categories.get(id2);
|
|
1359
|
+
return c ? [{ id: c.id, name: c.name, slug: c.slug }] : [];
|
|
1360
|
+
}),
|
|
1361
|
+
createdAt: p.createdAt,
|
|
1362
|
+
updatedAt: p.updatedAt
|
|
1363
|
+
};
|
|
1364
|
+
}
|
|
1365
|
+
var productByCategoryKey = (categorySlug, productSlug) => `category:${categorySlug}#product:${productSlug}`;
|
|
1366
|
+
function productWrites(doc) {
|
|
1367
|
+
return [
|
|
1368
|
+
{ collection: PRODUCTS, key: doc.slug, doc },
|
|
1369
|
+
...doc.categories.map((c) => ({
|
|
1370
|
+
collection: PRODUCTS_BY_CATEGORY,
|
|
1371
|
+
key: productByCategoryKey(c.slug, doc.slug),
|
|
1372
|
+
doc: { ...doc, partitionKey: `category:${c.slug}`, sortKey: `product:${doc.slug}` }
|
|
1373
|
+
}))
|
|
1374
|
+
];
|
|
1375
|
+
}
|
|
1376
|
+
function customerSortKey(o) {
|
|
1377
|
+
return `order:${String(Number.MAX_SAFE_INTEGER - new Date(String(o.createdAt)).getTime()).padStart(16, "0")}:${o.orderNumber}`;
|
|
1378
|
+
}
|
|
1379
|
+
function buildOrderDoc(order, history) {
|
|
1380
|
+
const rows = history.map((h) => ({
|
|
1381
|
+
fromStatus: h.fromStatus,
|
|
1382
|
+
toStatus: h.toStatus,
|
|
1383
|
+
actor: h.actor,
|
|
1384
|
+
note: h.note,
|
|
1385
|
+
timestamp: String(h.timestamp)
|
|
1386
|
+
}));
|
|
1387
|
+
return { ...order, history: rows, timeline: orderTimeline(rows) };
|
|
1388
|
+
}
|
|
1389
|
+
function orderWrites(doc) {
|
|
1390
|
+
const writes = [{ collection: ORDERS, key: doc.orderNumber, doc }];
|
|
1391
|
+
if (doc.customerId) {
|
|
1392
|
+
const sortKey = customerSortKey(doc);
|
|
1393
|
+
writes.push({
|
|
1394
|
+
collection: ORDERS_BY_CUSTOMER,
|
|
1395
|
+
key: `customer:${doc.customerId}#${sortKey}`,
|
|
1396
|
+
doc: { ...doc, partitionKey: `customer:${doc.customerId}`, sortKey }
|
|
1397
|
+
});
|
|
1398
|
+
}
|
|
1399
|
+
return writes;
|
|
1400
|
+
}
|
|
1401
|
+
function buildCustomerProfile(c) {
|
|
1402
|
+
const { orderCount, totalSpentMinor } = c;
|
|
1403
|
+
return {
|
|
1404
|
+
customerId: c.id,
|
|
1405
|
+
orderCount,
|
|
1406
|
+
totalSpentMinor,
|
|
1407
|
+
segment: totalSpentMinor > 1e5 ? "vip" : orderCount > 3 ? "returning" : orderCount > 0 ? "active" : "new",
|
|
1408
|
+
createdAt: String(c.createdAt)
|
|
1409
|
+
};
|
|
1410
|
+
}
|
|
1411
|
+
var partitioned = (doc) => {
|
|
1412
|
+
const { partitionKey, sortKey } = doc;
|
|
1413
|
+
return `${String(partitionKey)}#${String(sortKey)}`;
|
|
1414
|
+
};
|
|
1415
|
+
var KEY_OF = {
|
|
1416
|
+
[CATEGORIES]: (doc) => String(doc.slug),
|
|
1417
|
+
[PRODUCTS]: (doc) => String(doc.slug),
|
|
1418
|
+
[PRODUCTS_BY_CATEGORY]: partitioned,
|
|
1419
|
+
[ORDERS]: (doc) => String(doc.orderNumber),
|
|
1420
|
+
[ORDERS_BY_CUSTOMER]: partitioned,
|
|
1421
|
+
[CUSTOMER_PROFILES]: (doc) => String(doc.customerId),
|
|
1422
|
+
[RECENTLY_VIEWED]: (doc) => String(doc.viewer)
|
|
1423
|
+
};
|
|
1424
|
+
function buildSearchDoc(p) {
|
|
1425
|
+
return {
|
|
1426
|
+
id: p.id,
|
|
1427
|
+
type: "product",
|
|
1428
|
+
fields: {
|
|
1429
|
+
slug: p.slug,
|
|
1430
|
+
name: p.name,
|
|
1431
|
+
description: p.description,
|
|
1432
|
+
status: p.status,
|
|
1433
|
+
categoryIds: p.categoryIds,
|
|
1434
|
+
variants: p.variants.map((v) => ({ sku: v.sku, name: v.name, priceMinor: v.priceMinor }))
|
|
1435
|
+
}
|
|
1436
|
+
};
|
|
1437
|
+
}
|
|
1438
|
+
|
|
1439
|
+
// src/read-models/recently-viewed.ts
|
|
1440
|
+
var RECENT_VIEWS_KEPT = 12;
|
|
1441
|
+
var RECENT_VIEWS_WINDOW_DAYS = 30;
|
|
1442
|
+
var RECENTLY_VIEWED_TYPES = [
|
|
1443
|
+
EVT_PRODUCT_VIEWED,
|
|
1444
|
+
EVT_VISITOR_MERGED,
|
|
1445
|
+
EVT_CUSTOMER_DELETED
|
|
1446
|
+
];
|
|
1447
|
+
function viewerKey(v) {
|
|
1448
|
+
return `${v.kind}:${v.id}`;
|
|
1449
|
+
}
|
|
1450
|
+
var newestFirst = (a, b) => a.viewedAt === b.viewedAt ? a.productId < b.productId ? -1 : a.productId > b.productId ? 1 : 0 : a.viewedAt < b.viewedAt ? 1 : -1;
|
|
1451
|
+
function ranked(items) {
|
|
1452
|
+
const newest = /* @__PURE__ */ new Map();
|
|
1453
|
+
for (const { productId, viewedAt } of items) {
|
|
1454
|
+
const held = newest.get(productId);
|
|
1455
|
+
if (held === void 0 || viewedAt > held) newest.set(productId, viewedAt);
|
|
1456
|
+
}
|
|
1457
|
+
return [...newest].map(([productId, viewedAt]) => ({ productId, viewedAt })).sort(newestFirst).slice(0, RECENT_VIEWS_KEPT);
|
|
1458
|
+
}
|
|
1459
|
+
function withView(doc, viewer, productId, viewedAt) {
|
|
1460
|
+
return { viewer, items: ranked([...doc?.items ?? [], { productId, viewedAt }]) };
|
|
1461
|
+
}
|
|
1462
|
+
function merged(visitor, customer, customerKey) {
|
|
1463
|
+
if (visitor === null) return customer;
|
|
1464
|
+
if (customer === null) return { viewer: customerKey, items: visitor.items };
|
|
1465
|
+
return { viewer: customerKey, items: ranked([...customer.items, ...visitor.items]) };
|
|
1466
|
+
}
|
|
1467
|
+
async function foldEvent(docs, event) {
|
|
1468
|
+
if (event.type === EVT_PRODUCT_VIEWED) {
|
|
1469
|
+
const { productId, viewer } = event.payload;
|
|
1470
|
+
const key = viewerKey(viewer);
|
|
1471
|
+
await docs.put(key, withView(await docs.get(key), key, productId, event.timestamp));
|
|
1472
|
+
} else if (event.type === EVT_VISITOR_MERGED) {
|
|
1473
|
+
const { visitorId, customerId } = event.payload;
|
|
1474
|
+
const visitorKey = viewerKey({ kind: "visitor", id: visitorId });
|
|
1475
|
+
const customerKey = viewerKey({ kind: "customer", id: customerId });
|
|
1476
|
+
const next = merged(await docs.get(visitorKey), await docs.get(customerKey), customerKey);
|
|
1477
|
+
if (next !== null) await docs.put(customerKey, next);
|
|
1478
|
+
await docs.delete(visitorKey);
|
|
1479
|
+
} else if (event.type === EVT_CUSTOMER_DELETED) {
|
|
1480
|
+
const { customerId } = event.payload;
|
|
1481
|
+
await docs.delete(viewerKey({ kind: "customer", id: customerId }));
|
|
1482
|
+
}
|
|
1483
|
+
}
|
|
1484
|
+
async function readRecentlyViewed(deps, viewer) {
|
|
1485
|
+
if (viewer === null) return [];
|
|
1486
|
+
const doc = await deps.documentStore.get(RECENTLY_VIEWED, viewer);
|
|
1487
|
+
if (doc === null) return [];
|
|
1488
|
+
const days = Math.min(RECENT_VIEWS_WINDOW_DAYS, deps.retentionDays);
|
|
1489
|
+
const since = new Date(deps.now().getTime() - days * 864e5).toISOString();
|
|
1490
|
+
const recent = doc.items.filter((i) => i.viewedAt >= since);
|
|
1491
|
+
const { product } = deps.repos;
|
|
1492
|
+
const slugs = await product.store.read(async (tx) => {
|
|
1493
|
+
const out = [];
|
|
1494
|
+
for (const { productId } of recent) {
|
|
1495
|
+
const row = await product.findById(tx, productId);
|
|
1496
|
+
if (row?.status === "active") out.push(row.slug);
|
|
1497
|
+
}
|
|
1498
|
+
return out;
|
|
1499
|
+
});
|
|
1500
|
+
const docs = await deps.documentStore.batchGet(PRODUCTS, slugs);
|
|
1501
|
+
return slugs.flatMap((slug) => {
|
|
1502
|
+
const found = docs.get(slug);
|
|
1503
|
+
return found === void 0 ? [] : [found];
|
|
1504
|
+
});
|
|
1505
|
+
}
|
|
1506
|
+
var recentlyViewed = {
|
|
1507
|
+
name: "recently-viewed",
|
|
1508
|
+
target: "documents",
|
|
1509
|
+
collections: [RECENTLY_VIEWED],
|
|
1510
|
+
async *rebuild(ctx) {
|
|
1511
|
+
const held = /* @__PURE__ */ new Map();
|
|
1512
|
+
const docs = {
|
|
1513
|
+
get: async (key) => held.get(key) ?? null,
|
|
1514
|
+
put: async (key, doc) => {
|
|
1515
|
+
held.set(key, doc);
|
|
1516
|
+
},
|
|
1517
|
+
delete: async (key) => {
|
|
1518
|
+
held.delete(key);
|
|
1519
|
+
}
|
|
1520
|
+
};
|
|
1521
|
+
for await (const page of ctx.events(RECENTLY_VIEWED_TYPES)) {
|
|
1522
|
+
for (const { event } of page) await foldEvent(docs, event);
|
|
1523
|
+
}
|
|
1524
|
+
for (const [key, doc] of held) yield { collection: RECENTLY_VIEWED, key, doc };
|
|
1525
|
+
},
|
|
1526
|
+
handlers({ documentStore, logger }) {
|
|
1527
|
+
return recentlyViewedProjection({ documentStore, logger });
|
|
1528
|
+
}
|
|
1529
|
+
};
|
|
1530
|
+
|
|
1531
|
+
// src/routes/recently-viewed.ts
|
|
1532
|
+
var VISITOR_COOKIE = "nymbal.visitor";
|
|
1533
|
+
var UUID = /^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i;
|
|
1534
|
+
var BOT = /bot|crawl|spider|slurp/i;
|
|
1535
|
+
var NOT_STORED = { "Cache-Control": "private, no-store" };
|
|
1536
|
+
function visitorCookie(id2) {
|
|
1537
|
+
return {
|
|
1538
|
+
name: VISITOR_COOKIE,
|
|
1539
|
+
value: id2,
|
|
1540
|
+
path: "/",
|
|
1541
|
+
httpOnly: true,
|
|
1542
|
+
sameSite: "lax",
|
|
1543
|
+
secure: process.env.NODE_ENV === "production",
|
|
1544
|
+
maxAge: RECENT_VIEWS_WINDOW_DAYS * 86400
|
|
1545
|
+
};
|
|
1546
|
+
}
|
|
1547
|
+
function expiredVisitorCookie() {
|
|
1548
|
+
return { name: VISITOR_COOKIE, value: "", path: "/", maxAge: 0, httpOnly: true };
|
|
1549
|
+
}
|
|
1550
|
+
function visitorOf(ctx) {
|
|
1551
|
+
const id2 = ctx.cookies[VISITOR_COOKIE];
|
|
1552
|
+
return id2 !== void 0 && UUID.test(id2) ? id2 : void 0;
|
|
1553
|
+
}
|
|
1554
|
+
function lapsedBearer(ctx) {
|
|
1555
|
+
if (ctx.headers.authorization === void 0 || ctx.auth?.userId !== void 0) return void 0;
|
|
1556
|
+
return renderError(new AuthError2("token_invalid", "the access token is not valid"));
|
|
1557
|
+
}
|
|
1558
|
+
function foldViewsOnSignIn(recentlyViewed2) {
|
|
1559
|
+
return async (ctx, customerId) => {
|
|
1560
|
+
const visitorId = visitorOf(ctx);
|
|
1561
|
+
if (visitorId === void 0) return [];
|
|
1562
|
+
await recentlyViewed2.fold(visitorId, customerId);
|
|
1563
|
+
return [expiredVisitorCookie()];
|
|
1564
|
+
};
|
|
1565
|
+
}
|
|
1566
|
+
function registerRecentlyViewedRoutes(adapter, deps) {
|
|
1567
|
+
const { recentlyViewed: recentlyViewed2, documentStore, productRepo, retentionDays } = deps;
|
|
1568
|
+
const now = deps.now ?? (() => /* @__PURE__ */ new Date());
|
|
1569
|
+
adapter.registerRoute("POST", "/api/recently-viewed", async (ctx) => {
|
|
1570
|
+
try {
|
|
1571
|
+
const refused2 = lapsedBearer(ctx);
|
|
1572
|
+
if (refused2 !== void 0) return refused2;
|
|
1573
|
+
const agent = ctx.headers["user-agent"];
|
|
1574
|
+
if (typeof agent === "string" && BOT.test(agent)) return { status: 204 };
|
|
1575
|
+
const { productId } = ctx.body;
|
|
1576
|
+
const customerId = ctx.auth?.userId;
|
|
1577
|
+
if (customerId !== void 0) {
|
|
1578
|
+
await recentlyViewed2.record({ kind: "customer", id: customerId }, productId);
|
|
1579
|
+
return { status: 204 };
|
|
1580
|
+
}
|
|
1581
|
+
const visitorId = visitorOf(ctx) ?? uuidv74();
|
|
1582
|
+
const recorded = await recentlyViewed2.record({ kind: "visitor", id: visitorId }, productId);
|
|
1583
|
+
return recorded ? { status: 204, cookies: [visitorCookie(visitorId)] } : { status: 204 };
|
|
1584
|
+
} catch (err) {
|
|
1585
|
+
return renderError(err);
|
|
1586
|
+
}
|
|
1587
|
+
});
|
|
1588
|
+
adapter.registerRoute("GET", "/api/recently-viewed", async (ctx) => {
|
|
1589
|
+
try {
|
|
1590
|
+
const refused2 = lapsedBearer(ctx);
|
|
1591
|
+
if (refused2 !== void 0) return refused2;
|
|
1592
|
+
const visitorId = visitorOf(ctx);
|
|
1593
|
+
const customerId = ctx.auth?.userId;
|
|
1594
|
+
const viewer = customerId !== void 0 ? viewerKey({ kind: "customer", id: customerId }) : visitorId !== void 0 ? viewerKey({ kind: "visitor", id: visitorId }) : null;
|
|
1595
|
+
const items = await readRecentlyViewed(
|
|
1596
|
+
{ documentStore, repos: { product: productRepo }, retentionDays, now },
|
|
1597
|
+
viewer
|
|
1598
|
+
);
|
|
1599
|
+
return { ...ok({ items }), headers: NOT_STORED };
|
|
1600
|
+
} catch (err) {
|
|
1601
|
+
return renderError(err);
|
|
1602
|
+
}
|
|
1603
|
+
});
|
|
1604
|
+
}
|
|
1605
|
+
|
|
1606
|
+
// src/routes/auth.ts
|
|
956
1607
|
var REFRESH_COOKIE = "nymbal.refresh";
|
|
957
1608
|
function refreshCookies(token, maxAgeSeconds) {
|
|
958
1609
|
return [
|
|
@@ -968,9 +1619,24 @@ function refreshCookies(token, maxAgeSeconds) {
|
|
|
968
1619
|
];
|
|
969
1620
|
}
|
|
970
1621
|
function expiredCookies() {
|
|
971
|
-
return [
|
|
1622
|
+
return [
|
|
1623
|
+
{ name: REFRESH_COOKIE, value: "", path: "/", maxAge: 0, httpOnly: true },
|
|
1624
|
+
expiredVisitorCookie()
|
|
1625
|
+
];
|
|
972
1626
|
}
|
|
973
|
-
function
|
|
1627
|
+
async function runAfterSignIn(hooks2, ctx, customerId) {
|
|
1628
|
+
const cookies = [];
|
|
1629
|
+
for (const hook of hooks2) {
|
|
1630
|
+
try {
|
|
1631
|
+
cookies.push(...await hook(ctx, customerId));
|
|
1632
|
+
} catch (err) {
|
|
1633
|
+
ctx.logger.warn({ err, customerId }, "an after-sign-in hook failed; the sign-in stands");
|
|
1634
|
+
}
|
|
1635
|
+
}
|
|
1636
|
+
return cookies;
|
|
1637
|
+
}
|
|
1638
|
+
function registerAuthRoutes(adapter, auth, refreshTtl, afterSignIn = []) {
|
|
1639
|
+
const refreshMaxAge = Math.floor(parseDurationToMs(refreshTtl) / 1e3);
|
|
974
1640
|
adapter.registerRoute("POST", "/api/auth/register", async (ctx) => {
|
|
975
1641
|
try {
|
|
976
1642
|
const body = ctx.body;
|
|
@@ -986,11 +1652,18 @@ function registerAuthRoutes(adapter, auth) {
|
|
|
986
1652
|
};
|
|
987
1653
|
const result = await auth.register(registerInput);
|
|
988
1654
|
const envelope = ok(
|
|
989
|
-
{
|
|
1655
|
+
{
|
|
1656
|
+
customer: result.customer,
|
|
1657
|
+
accessToken: result.tokens.accessToken,
|
|
1658
|
+
expiresIn: result.tokens.expiresIn
|
|
1659
|
+
},
|
|
990
1660
|
void 0,
|
|
991
1661
|
201
|
|
992
1662
|
);
|
|
993
|
-
envelope.cookies =
|
|
1663
|
+
envelope.cookies = [
|
|
1664
|
+
...refreshCookies(result.tokens.refreshToken, refreshMaxAge),
|
|
1665
|
+
...await runAfterSignIn(afterSignIn, ctx, result.customer.id)
|
|
1666
|
+
];
|
|
994
1667
|
return envelope;
|
|
995
1668
|
} catch (err) {
|
|
996
1669
|
return renderError(err);
|
|
@@ -1008,7 +1681,10 @@ function registerAuthRoutes(adapter, auth) {
|
|
|
1008
1681
|
accessToken: result.tokens.accessToken,
|
|
1009
1682
|
expiresIn: result.tokens.expiresIn
|
|
1010
1683
|
});
|
|
1011
|
-
envelope.cookies =
|
|
1684
|
+
envelope.cookies = [
|
|
1685
|
+
...refreshCookies(result.tokens.refreshToken, refreshMaxAge),
|
|
1686
|
+
...await runAfterSignIn(afterSignIn, ctx, result.customer.id)
|
|
1687
|
+
];
|
|
1012
1688
|
return envelope;
|
|
1013
1689
|
} catch (err) {
|
|
1014
1690
|
return renderError(err);
|
|
@@ -1018,10 +1694,10 @@ function registerAuthRoutes(adapter, auth) {
|
|
|
1018
1694
|
try {
|
|
1019
1695
|
const body = ctx.body;
|
|
1020
1696
|
const refreshToken = body?.refreshToken ?? ctx.cookies[REFRESH_COOKIE];
|
|
1021
|
-
if (!refreshToken) throw new
|
|
1697
|
+
if (!refreshToken) throw new AuthError3("token_invalid", "refresh token missing");
|
|
1022
1698
|
const tokens = await auth.refresh(refreshToken);
|
|
1023
1699
|
const envelope = ok({ accessToken: tokens.accessToken, expiresIn: tokens.expiresIn });
|
|
1024
|
-
envelope.cookies = refreshCookies(tokens.refreshToken,
|
|
1700
|
+
envelope.cookies = refreshCookies(tokens.refreshToken, refreshMaxAge);
|
|
1025
1701
|
return envelope;
|
|
1026
1702
|
} catch (err) {
|
|
1027
1703
|
return renderError(err);
|
|
@@ -1210,26 +1886,2206 @@ 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
|
-
|
|
1231
|
-
|
|
1232
|
-
|
|
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
|
+
});
|
|
2175
|
+
}
|
|
2176
|
+
};
|
|
2177
|
+
}
|
|
2178
|
+
|
|
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
|
+
async addNote(customerId, note) {
|
|
2425
|
+
await store.transaction(async (tx) => {
|
|
2426
|
+
const customer = await loadOrThrow(tx, customerId);
|
|
2427
|
+
audit.note("customer.addNote", [{ type: "customer", id: customerId }]);
|
|
2428
|
+
const notes = customer.metadata.adminNotes ?? [];
|
|
2429
|
+
await repos.customer.update(tx, customerId, {
|
|
2430
|
+
metadata: { ...customer.metadata, adminNotes: [...notes, note] },
|
|
2431
|
+
updatedAt: /* @__PURE__ */ new Date()
|
|
2432
|
+
});
|
|
2433
|
+
await publishUpdated(tx, customerId);
|
|
2434
|
+
});
|
|
2435
|
+
}
|
|
2436
|
+
};
|
|
2437
|
+
}
|
|
2438
|
+
|
|
2439
|
+
// src/services/order-service.ts
|
|
2440
|
+
import { v7 as uuidv79 } from "uuid";
|
|
2441
|
+
import {
|
|
2442
|
+
EVT_ORDER_CANCELLED,
|
|
2443
|
+
EVT_ORDER_CONFIRMATION_RESEND_REQUESTED,
|
|
2444
|
+
EVT_ORDER_DELIVERED,
|
|
2445
|
+
EVT_ORDER_PLACED,
|
|
2446
|
+
EVT_ORDER_SHIPPED,
|
|
2447
|
+
EVT_ORDER_STATUS_CHANGED,
|
|
2448
|
+
NotFoundError as NotFoundError7,
|
|
2449
|
+
OrderConflictError as OrderConflictError2,
|
|
2450
|
+
StatusTransitionError as StatusTransitionError2,
|
|
2451
|
+
ValidationError as ValidationError7,
|
|
2452
|
+
assertOrderTransition
|
|
2453
|
+
} from "@nymbalhq/types";
|
|
2454
|
+
|
|
2455
|
+
// src/order-access-key.ts
|
|
2456
|
+
import { createHash as createHash3, randomBytes } from "crypto";
|
|
2457
|
+
var ORDER_KEY = /^[A-Za-z0-9_-]{43}$/;
|
|
2458
|
+
function mintOrderKey() {
|
|
2459
|
+
const key = randomBytes(32).toString("base64url");
|
|
2460
|
+
return { key, hash: hashOrderKey(key) };
|
|
2461
|
+
}
|
|
2462
|
+
function hashOrderKey(key) {
|
|
2463
|
+
return createHash3("sha256").update(key).digest("hex");
|
|
2464
|
+
}
|
|
2465
|
+
function isOrderKey(value) {
|
|
2466
|
+
return typeof value === "string" && ORDER_KEY.test(value);
|
|
2467
|
+
}
|
|
2468
|
+
function orderEmailMatches(orderEmail, given) {
|
|
2469
|
+
return orderEmail.trim().toLowerCase() === given.trim().toLowerCase();
|
|
2470
|
+
}
|
|
2471
|
+
|
|
2472
|
+
// src/services/order-service.ts
|
|
2473
|
+
var NO_CONFIRMATION_DUE = /* @__PURE__ */ new Set(["pending", "cancelled"]);
|
|
2474
|
+
function createOrderService(deps) {
|
|
2475
|
+
const { store, repos, publisher } = deps;
|
|
2476
|
+
async function keyState(orderId, key, now) {
|
|
2477
|
+
if (!isOrderKey(key)) return "none";
|
|
2478
|
+
return store.read((tx) => repos.orderAccessKey.opens(tx, orderId, hashOrderKey(key), now));
|
|
2479
|
+
}
|
|
2480
|
+
async function requireOrder(tx, id2) {
|
|
2481
|
+
const order = await repos.order.findById(tx, id2);
|
|
2482
|
+
if (!order) throw new NotFoundError7("order", id2);
|
|
2483
|
+
return order;
|
|
2484
|
+
}
|
|
2485
|
+
async function lockOrder(tx, id2) {
|
|
2486
|
+
const order = await repos.order.lock(tx, id2);
|
|
2487
|
+
if (!order) throw new NotFoundError7("order", id2);
|
|
2488
|
+
return order;
|
|
2489
|
+
}
|
|
2490
|
+
async function doTransition(tx, order, toStatus, actor, note) {
|
|
2491
|
+
assertOrderTransition(order.status, toStatus);
|
|
2492
|
+
const now = /* @__PURE__ */ new Date();
|
|
2493
|
+
await repos.order.setStatus(tx, order.id, toStatus, now);
|
|
2494
|
+
await repos.orderHistory.append(tx, {
|
|
2495
|
+
id: uuidv79(),
|
|
2496
|
+
orderId: order.id,
|
|
2497
|
+
fromStatus: order.status,
|
|
2498
|
+
toStatus,
|
|
2499
|
+
actor,
|
|
2500
|
+
note,
|
|
2501
|
+
timestamp: now
|
|
2502
|
+
});
|
|
2503
|
+
return requireOrder(tx, order.id);
|
|
2504
|
+
}
|
|
2505
|
+
return {
|
|
2506
|
+
async createFromCheckout(input) {
|
|
2507
|
+
return store.transaction(async (tx) => {
|
|
2508
|
+
audit.note("order.place", [{ type: "order", id: input.orderId }]);
|
|
2509
|
+
const sequence = await repos.orderSequence.nextSequence(tx, deps.orderNumberStart);
|
|
2510
|
+
const orderNumber = `${deps.orderNumberPrefix}-${sequence + 1}`;
|
|
2511
|
+
const now = /* @__PURE__ */ new Date();
|
|
2512
|
+
await repos.order.insert(tx, {
|
|
2513
|
+
id: input.orderId,
|
|
2514
|
+
orderNumber,
|
|
2515
|
+
sequence,
|
|
2516
|
+
customerId: input.customerId,
|
|
2517
|
+
status: "pending",
|
|
2518
|
+
email: input.email,
|
|
2519
|
+
billingAddress: input.billingAddress,
|
|
2520
|
+
shippingAddress: input.shippingAddress,
|
|
2521
|
+
lineItems: input.lineItems,
|
|
2522
|
+
subtotalMinor: input.subtotalMinor,
|
|
2523
|
+
taxTotalMinor: input.taxTotalMinor,
|
|
2524
|
+
shippingTotalMinor: input.shippingTotalMinor,
|
|
2525
|
+
discountTotalMinor: input.discountTotalMinor,
|
|
2526
|
+
totalMinor: input.totalMinor,
|
|
2527
|
+
currency: input.currency,
|
|
2528
|
+
notes: input.notes ?? "",
|
|
2529
|
+
metadata: input.metadata ?? {},
|
|
2530
|
+
paymentIntentId: input.paymentIntentId ?? null,
|
|
2531
|
+
cartToken: input.cartToken ?? null,
|
|
2532
|
+
createdAt: now,
|
|
2533
|
+
updatedAt: now
|
|
2534
|
+
});
|
|
2535
|
+
await repos.orderHistory.append(tx, {
|
|
2536
|
+
id: uuidv79(),
|
|
2537
|
+
orderId: input.orderId,
|
|
2538
|
+
fromStatus: null,
|
|
2539
|
+
toStatus: "pending",
|
|
2540
|
+
actor: "system:checkout",
|
|
2541
|
+
note: "order draft created",
|
|
2542
|
+
timestamp: now
|
|
2543
|
+
});
|
|
2544
|
+
const fresh = await requireOrder(tx, input.orderId);
|
|
2545
|
+
await publisher.publish(EVT_ORDER_PLACED, { order: fresh });
|
|
2546
|
+
return fresh;
|
|
2547
|
+
});
|
|
2548
|
+
},
|
|
2549
|
+
async getById(id2) {
|
|
2550
|
+
return store.read((tx) => requireOrder(tx, id2));
|
|
2551
|
+
},
|
|
2552
|
+
async getByOrderNumber(orderNumber) {
|
|
2553
|
+
const order = await store.read((tx) => repos.order.findByOrderNumber(tx, orderNumber));
|
|
2554
|
+
if (!order) throw new NotFoundError7("order", orderNumber);
|
|
2555
|
+
return order;
|
|
2556
|
+
},
|
|
2557
|
+
async listByCustomer(customerId) {
|
|
2558
|
+
return store.read((tx) => repos.order.listByCustomer(tx, customerId));
|
|
2559
|
+
},
|
|
2560
|
+
async keyOpens(orderId, key) {
|
|
2561
|
+
return await keyState(orderId, key, /* @__PURE__ */ new Date()) === "open";
|
|
2562
|
+
},
|
|
2563
|
+
keyState(orderId, key, now = /* @__PURE__ */ new Date()) {
|
|
2564
|
+
return keyState(orderId, key, now);
|
|
2565
|
+
},
|
|
2566
|
+
async requestLink(orderNumber, email) {
|
|
2567
|
+
const order = await store.read((tx) => repos.order.findByOrderNumber(tx, orderNumber));
|
|
2568
|
+
if (order === null || NO_CONFIRMATION_DUE.has(order.status)) return;
|
|
2569
|
+
if (!orderEmailMatches(order.email, email)) return;
|
|
2570
|
+
await store.transaction(async () => {
|
|
2571
|
+
audit.note("order.requestLink", [{ type: "order", id: order.id }]);
|
|
2572
|
+
await publisher.publish(EVT_ORDER_CONFIRMATION_RESEND_REQUESTED, { orderId: order.id });
|
|
2573
|
+
});
|
|
2574
|
+
},
|
|
2575
|
+
async updateStatus(id2, toStatus, actor, note = "") {
|
|
2576
|
+
return store.transaction(async (tx) => {
|
|
2577
|
+
audit.note("order.updateStatus", [{ type: "order", id: id2 }]);
|
|
2578
|
+
const order = await requireOrder(tx, id2);
|
|
2579
|
+
const fresh = await doTransition(tx, order, toStatus, actor, note);
|
|
2580
|
+
await publisher.publish(EVT_ORDER_STATUS_CHANGED, {
|
|
2581
|
+
orderId: fresh.id,
|
|
2582
|
+
from: order.status,
|
|
2583
|
+
to: fresh.status
|
|
2584
|
+
});
|
|
2585
|
+
return fresh;
|
|
2586
|
+
});
|
|
2587
|
+
},
|
|
2588
|
+
async markShipped(id2, trackingNumber, carrier, actor) {
|
|
2589
|
+
return store.transaction(async (tx) => {
|
|
2590
|
+
audit.note("order.ship", [{ type: "order", id: id2 }]);
|
|
2591
|
+
const order = await lockOrder(tx, id2);
|
|
2592
|
+
const fresh = await doTransition(
|
|
2593
|
+
tx,
|
|
2594
|
+
order,
|
|
2595
|
+
"shipped",
|
|
2596
|
+
actor,
|
|
2597
|
+
`Shipped via ${carrier}: ${trackingNumber}`
|
|
2598
|
+
);
|
|
2599
|
+
await repos.orderShipment.record(tx, {
|
|
2600
|
+
orderId: fresh.id,
|
|
2601
|
+
carrier,
|
|
2602
|
+
trackingNumber,
|
|
2603
|
+
at: /* @__PURE__ */ new Date()
|
|
2604
|
+
});
|
|
2605
|
+
await publisher.publish(EVT_ORDER_SHIPPED, {
|
|
2606
|
+
orderId: fresh.id,
|
|
2607
|
+
trackingNumber,
|
|
2608
|
+
carrier
|
|
2609
|
+
});
|
|
2610
|
+
return fresh;
|
|
2611
|
+
});
|
|
2612
|
+
},
|
|
2613
|
+
async markDelivered(id2, actor) {
|
|
2614
|
+
return store.transaction(async (tx) => {
|
|
2615
|
+
audit.note("order.markDelivered", [{ type: "order", id: id2 }]);
|
|
2616
|
+
const order = await lockOrder(tx, id2);
|
|
2617
|
+
const fresh = await doTransition(tx, order, "delivered", actor, "Delivered");
|
|
2618
|
+
await publisher.publish(EVT_ORDER_DELIVERED, { orderId: fresh.id });
|
|
2619
|
+
return fresh;
|
|
2620
|
+
});
|
|
2621
|
+
},
|
|
2622
|
+
async cancel(id2, reason, actor) {
|
|
2623
|
+
return store.transaction(async (tx) => {
|
|
2624
|
+
audit.note("order.cancel", [{ type: "order", id: id2 }]);
|
|
2625
|
+
const order = await repos.order.lock(tx, id2);
|
|
2626
|
+
if (!order) throw new NotFoundError7("order", id2);
|
|
2627
|
+
if (order.capturedMinor > 0) {
|
|
2628
|
+
throw new OrderConflictError2(
|
|
2629
|
+
"order.paid",
|
|
2630
|
+
`Order ${order.orderNumber} is paid: refund it instead of cancelling`
|
|
2631
|
+
);
|
|
2632
|
+
}
|
|
2633
|
+
assertOrderTransition(order.status, "cancelled");
|
|
2634
|
+
const now = /* @__PURE__ */ new Date();
|
|
2635
|
+
if (!await repos.order.setStatusIf(tx, order.id, order.status, "cancelled", now)) {
|
|
2636
|
+
const current = await requireOrder(tx, order.id);
|
|
2637
|
+
throw new StatusTransitionError2("order", current.status, "cancelled");
|
|
2638
|
+
}
|
|
2639
|
+
await repos.orderHistory.append(tx, {
|
|
2640
|
+
id: uuidv79(),
|
|
2641
|
+
orderId: order.id,
|
|
2642
|
+
fromStatus: order.status,
|
|
2643
|
+
toStatus: "cancelled",
|
|
2644
|
+
actor,
|
|
2645
|
+
note: reason,
|
|
2646
|
+
timestamp: now
|
|
2647
|
+
});
|
|
2648
|
+
const fresh = await requireOrder(tx, order.id);
|
|
2649
|
+
await publisher.publish(EVT_ORDER_CANCELLED, { orderId: fresh.id, reason });
|
|
2650
|
+
return fresh;
|
|
2651
|
+
});
|
|
2652
|
+
},
|
|
2653
|
+
async resendConfirmation(id2) {
|
|
2654
|
+
return store.transaction(async (tx) => {
|
|
2655
|
+
audit.note("order.resendConfirmation", [{ type: "order", id: id2 }]);
|
|
2656
|
+
const order = await requireOrder(tx, id2);
|
|
2657
|
+
if (NO_CONFIRMATION_DUE.has(order.status)) {
|
|
2658
|
+
throw new OrderConflictError2(
|
|
2659
|
+
"order.unpaid",
|
|
2660
|
+
`Order ${order.orderNumber} is ${order.status}: no confirmation is due`,
|
|
2661
|
+
{ context: { status: order.status } }
|
|
2662
|
+
);
|
|
2663
|
+
}
|
|
2664
|
+
await publisher.publish(EVT_ORDER_CONFIRMATION_RESEND_REQUESTED, { orderId: order.id });
|
|
2665
|
+
return order;
|
|
2666
|
+
});
|
|
2667
|
+
},
|
|
2668
|
+
async importOrder(input) {
|
|
2669
|
+
const capturedMinor = input.capturedMinor ?? 0;
|
|
2670
|
+
const refundedMinor = input.refundedMinor ?? 0;
|
|
2671
|
+
if (!(0 <= refundedMinor && refundedMinor <= capturedMinor && capturedMinor <= input.totalMinor) || capturedMinor > 0 !== (input.captureMethod != null)) {
|
|
2672
|
+
throw new ValidationError7("imported payment amounts are inconsistent", {
|
|
2673
|
+
context: { capturedMinor, refundedMinor, totalMinor: input.totalMinor }
|
|
2674
|
+
});
|
|
2675
|
+
}
|
|
2676
|
+
return store.transaction(async (tx) => {
|
|
2677
|
+
audit.note("order.import", [{ type: "order", id: input.orderId }]);
|
|
2678
|
+
const sequence = await repos.orderSequence.nextSequence(tx, deps.orderNumberStart);
|
|
2679
|
+
await repos.order.insert(tx, {
|
|
2680
|
+
id: input.orderId,
|
|
2681
|
+
orderNumber: input.orderNumber,
|
|
2682
|
+
sequence,
|
|
2683
|
+
customerId: input.customerId,
|
|
2684
|
+
status: input.status,
|
|
2685
|
+
email: input.email,
|
|
2686
|
+
billingAddress: input.billingAddress,
|
|
2687
|
+
shippingAddress: input.shippingAddress,
|
|
2688
|
+
lineItems: input.lineItems,
|
|
2689
|
+
subtotalMinor: input.subtotalMinor,
|
|
2690
|
+
taxTotalMinor: input.taxTotalMinor,
|
|
2691
|
+
shippingTotalMinor: input.shippingTotalMinor,
|
|
2692
|
+
discountTotalMinor: input.discountTotalMinor,
|
|
2693
|
+
totalMinor: input.totalMinor,
|
|
2694
|
+
currency: input.currency,
|
|
2695
|
+
notes: input.notes ?? "",
|
|
2696
|
+
metadata: input.metadata ?? {},
|
|
2697
|
+
paymentIntentId: input.paymentIntentId ?? null,
|
|
2698
|
+
...input.captureMethod != null && {
|
|
2699
|
+
capture: {
|
|
2700
|
+
amountMinor: capturedMinor,
|
|
2701
|
+
method: input.captureMethod,
|
|
2702
|
+
at: input.createdAt,
|
|
2703
|
+
refundedMinor
|
|
2704
|
+
}
|
|
2705
|
+
},
|
|
2706
|
+
createdAt: input.createdAt,
|
|
2707
|
+
updatedAt: input.createdAt
|
|
2708
|
+
});
|
|
2709
|
+
const fresh = await requireOrder(tx, input.orderId);
|
|
2710
|
+
await publisher.publish(EVT_ORDER_PLACED, { order: fresh });
|
|
2711
|
+
return fresh;
|
|
2712
|
+
});
|
|
2713
|
+
}
|
|
2714
|
+
};
|
|
2715
|
+
}
|
|
2716
|
+
|
|
2717
|
+
// src/services/inventory-service.ts
|
|
2718
|
+
import { v7 as uuidv710 } from "uuid";
|
|
2719
|
+
import {
|
|
2720
|
+
AdapterError as AdapterError2,
|
|
2721
|
+
NotFoundError as NotFoundError8,
|
|
2722
|
+
ValidationError as ValidationError8,
|
|
2723
|
+
EVT_INVENTORY_CHANGED,
|
|
2724
|
+
EVT_INVENTORY_RESERVED,
|
|
2725
|
+
EVT_INVENTORY_RELEASED,
|
|
2726
|
+
EVT_INVENTORY_LOW_STOCK,
|
|
2727
|
+
EVT_INVENTORY_OUT_OF_STOCK,
|
|
2728
|
+
EVT_PRODUCT_RESTOCKED
|
|
2729
|
+
} from "@nymbalhq/types";
|
|
2730
|
+
function classifyStock(stock, threshold) {
|
|
2731
|
+
if (stock <= 0) return "out_of_stock";
|
|
2732
|
+
if (stock <= threshold) return "low_stock";
|
|
2733
|
+
return "in_stock";
|
|
2734
|
+
}
|
|
2735
|
+
function createInventoryService(deps) {
|
|
2736
|
+
const { store, repos, publisher, logger } = deps;
|
|
2737
|
+
const defaultTtl = deps.defaultReservationTtlSeconds ?? 15 * 60;
|
|
2738
|
+
async function emitThresholdEvents(variantId, newQty, threshold) {
|
|
2739
|
+
if (newQty <= 0) {
|
|
2740
|
+
await publisher.publish(EVT_INVENTORY_OUT_OF_STOCK, { variantId });
|
|
2741
|
+
} else if (newQty <= threshold) {
|
|
2742
|
+
await publisher.publish(EVT_INVENTORY_LOW_STOCK, {
|
|
2743
|
+
variantId,
|
|
2744
|
+
currentQty: newQty,
|
|
2745
|
+
threshold
|
|
2746
|
+
});
|
|
2747
|
+
}
|
|
2748
|
+
}
|
|
2749
|
+
async function emitRestocked(variantId, previousQty, newQty, productIdOf) {
|
|
2750
|
+
if (previousQty <= 0 && newQty > 0) {
|
|
2751
|
+
const productId = await productIdOf();
|
|
2752
|
+
await publisher.publish(EVT_PRODUCT_RESTOCKED, { productId, variantId, previousQty, newQty });
|
|
2753
|
+
}
|
|
2754
|
+
}
|
|
2755
|
+
async function take(variantId, qty, orderRef, ttlSeconds) {
|
|
2756
|
+
if (qty <= 0) throw new ValidationError8(`Reservation qty must be positive, got ${qty}`);
|
|
2757
|
+
return store.transaction(async (tx) => {
|
|
2758
|
+
audit.note("inventory.reserve", [{ type: "variant", id: variantId }]);
|
|
2759
|
+
const variant = await repos.variant.findById(tx, variantId);
|
|
2760
|
+
if (!variant) throw new NotFoundError8("variant", variantId);
|
|
2761
|
+
const now = /* @__PURE__ */ new Date();
|
|
2762
|
+
const remaining = await repos.variant.decrementStock(tx, variant.id, qty, now);
|
|
2763
|
+
if (remaining === null) return { available: variant.stock };
|
|
2764
|
+
const expiresAt = new Date(now.getTime() + (ttlSeconds ?? defaultTtl) * 1e3);
|
|
2765
|
+
const reservationId = uuidv710();
|
|
2766
|
+
await repos.inventoryReservation.insert(tx, {
|
|
2767
|
+
reservationId,
|
|
2768
|
+
variantId: variant.id,
|
|
2769
|
+
qty,
|
|
2770
|
+
orderRef,
|
|
2771
|
+
expiresAt,
|
|
2772
|
+
createdAt: now
|
|
2773
|
+
});
|
|
2774
|
+
await publisher.publish(EVT_INVENTORY_RESERVED, {
|
|
2775
|
+
variantId: variant.id,
|
|
2776
|
+
qty,
|
|
2777
|
+
reservationId,
|
|
2778
|
+
expiresAt: expiresAt.toISOString()
|
|
2779
|
+
});
|
|
2780
|
+
await publisher.publish(EVT_INVENTORY_CHANGED, {
|
|
2781
|
+
variantId: variant.id,
|
|
2782
|
+
previousQty: remaining + qty,
|
|
2783
|
+
newQty: remaining,
|
|
2784
|
+
reason: "manual"
|
|
2785
|
+
});
|
|
2786
|
+
await emitThresholdEvents(variant.id, remaining, variant.lowStockThreshold);
|
|
2787
|
+
return { reservationId, expiresAt: expiresAt.toISOString() };
|
|
2788
|
+
});
|
|
2789
|
+
}
|
|
2790
|
+
return {
|
|
2791
|
+
async adjustStock(variantId, delta, reason, actor) {
|
|
2792
|
+
return store.transaction(async (tx) => {
|
|
2793
|
+
audit.note("inventory.adjust", [{ type: "variant", id: variantId }]);
|
|
2794
|
+
const variant = await repos.variant.findById(tx, variantId);
|
|
2795
|
+
if (!variant) throw new NotFoundError8("variant", variantId);
|
|
2796
|
+
const now = /* @__PURE__ */ new Date();
|
|
2797
|
+
const newQty = delta < 0 ? await repos.variant.decrementStock(tx, variant.id, -delta, now) : await repos.variant.incrementStock(tx, variant.id, delta, now);
|
|
2798
|
+
if (newQty === null) {
|
|
2799
|
+
throw new ValidationError8(`Cannot reduce stock below zero (variant ${variantId})`, {
|
|
2800
|
+
context: { variantId, stock: variant.stock, delta }
|
|
2801
|
+
});
|
|
2802
|
+
}
|
|
2803
|
+
const previousQty = newQty - delta;
|
|
2804
|
+
await repos.stockAdjustment.append(tx, {
|
|
2805
|
+
id: uuidv710(),
|
|
2806
|
+
variantId: variant.id,
|
|
2807
|
+
adjustment: delta,
|
|
2808
|
+
reason,
|
|
2809
|
+
actor,
|
|
2810
|
+
previousQty,
|
|
2811
|
+
newQty,
|
|
2812
|
+
timestamp: now
|
|
2813
|
+
});
|
|
2814
|
+
await publisher.publish(EVT_INVENTORY_CHANGED, {
|
|
2815
|
+
variantId: variant.id,
|
|
2816
|
+
previousQty,
|
|
2817
|
+
newQty,
|
|
2818
|
+
reason
|
|
2819
|
+
});
|
|
2820
|
+
await emitRestocked(variant.id, previousQty, newQty, async () => variant.productId);
|
|
2821
|
+
await emitThresholdEvents(variant.id, newQty, variant.lowStockThreshold);
|
|
2822
|
+
logger.debug({ variantId, delta, newQty, reason }, "stock adjusted");
|
|
2823
|
+
return { newQty };
|
|
2824
|
+
});
|
|
2825
|
+
},
|
|
2826
|
+
async reserveStock(variantId, qty, orderRef = null, ttlSeconds) {
|
|
2827
|
+
const taken = await take(variantId, qty, orderRef, ttlSeconds);
|
|
2828
|
+
if ("available" in taken) {
|
|
2829
|
+
throw new AdapterError2(
|
|
2830
|
+
"inventory.insufficient",
|
|
2831
|
+
`Insufficient stock for variant ${variantId}`,
|
|
2832
|
+
{
|
|
2833
|
+
context: { variantId, requested: qty, available: taken.available }
|
|
2834
|
+
}
|
|
2835
|
+
);
|
|
2836
|
+
}
|
|
2837
|
+
return taken;
|
|
2838
|
+
},
|
|
2839
|
+
async tryReserveStock(variantId, qty, orderRef = null, ttlSeconds) {
|
|
2840
|
+
const taken = await take(variantId, qty, orderRef, ttlSeconds);
|
|
2841
|
+
return "available" in taken ? null : taken;
|
|
2842
|
+
},
|
|
2843
|
+
async releaseReservation(reservationId, reason) {
|
|
2844
|
+
await store.transaction(async (tx) => {
|
|
2845
|
+
const reservation = await repos.inventoryReservation.deleteById(tx, reservationId);
|
|
2846
|
+
if (!reservation) {
|
|
2847
|
+
logger.debug(
|
|
2848
|
+
{ reservationId },
|
|
2849
|
+
"reservation already released, committed or never existed"
|
|
2850
|
+
);
|
|
2851
|
+
return;
|
|
2852
|
+
}
|
|
2853
|
+
audit.note("inventory.release", [{ type: "variant", id: reservation.variantId }]);
|
|
2854
|
+
const now = /* @__PURE__ */ new Date();
|
|
2855
|
+
const newQty = await repos.variant.incrementStock(
|
|
2856
|
+
tx,
|
|
2857
|
+
reservation.variantId,
|
|
2858
|
+
reservation.qty,
|
|
2859
|
+
now
|
|
2860
|
+
);
|
|
2861
|
+
if (newQty !== null) {
|
|
2862
|
+
const previousQty = newQty - reservation.qty;
|
|
2863
|
+
await repos.stockAdjustment.append(tx, {
|
|
2864
|
+
id: uuidv710(),
|
|
2865
|
+
variantId: reservation.variantId,
|
|
2866
|
+
adjustment: reservation.qty,
|
|
2867
|
+
reason: "reservation-release",
|
|
2868
|
+
actor: `system:release:${reason}`,
|
|
2869
|
+
previousQty,
|
|
2870
|
+
newQty,
|
|
2871
|
+
timestamp: now
|
|
2872
|
+
});
|
|
2873
|
+
await publisher.publish(EVT_INVENTORY_CHANGED, {
|
|
2874
|
+
variantId: reservation.variantId,
|
|
2875
|
+
previousQty,
|
|
2876
|
+
newQty,
|
|
2877
|
+
reason: "reservation-release"
|
|
2878
|
+
});
|
|
2879
|
+
await emitRestocked(reservation.variantId, previousQty, newQty, async () => {
|
|
2880
|
+
const variant = await repos.variant.findById(tx, reservation.variantId);
|
|
2881
|
+
return variant.productId;
|
|
2882
|
+
});
|
|
2883
|
+
}
|
|
2884
|
+
await publisher.publish(EVT_INVENTORY_RELEASED, {
|
|
2885
|
+
variantId: reservation.variantId,
|
|
2886
|
+
qty: reservation.qty,
|
|
2887
|
+
reservationId: reservation.reservationId,
|
|
2888
|
+
reason
|
|
2889
|
+
});
|
|
2890
|
+
});
|
|
2891
|
+
},
|
|
2892
|
+
async commitReservation(reservationId, actor) {
|
|
2893
|
+
await store.transaction(async (tx) => {
|
|
2894
|
+
const reservation = await repos.inventoryReservation.deleteById(tx, reservationId);
|
|
2895
|
+
if (!reservation) throw new NotFoundError8("reservation", reservationId);
|
|
2896
|
+
audit.note("inventory.commit", [{ type: "variant", id: reservation.variantId }]);
|
|
2897
|
+
const variant = await repos.variant.findById(tx, reservation.variantId);
|
|
2898
|
+
if (!variant) throw new NotFoundError8("variant", reservation.variantId);
|
|
2899
|
+
await repos.stockAdjustment.append(tx, {
|
|
2900
|
+
id: uuidv710(),
|
|
2901
|
+
variantId: variant.id,
|
|
2902
|
+
adjustment: -reservation.qty,
|
|
2903
|
+
reason: "reservation-commit",
|
|
2904
|
+
actor,
|
|
2905
|
+
previousQty: variant.stock + reservation.qty,
|
|
2906
|
+
newQty: variant.stock,
|
|
2907
|
+
timestamp: /* @__PURE__ */ new Date()
|
|
2908
|
+
});
|
|
2909
|
+
await publisher.publish(EVT_INVENTORY_RELEASED, {
|
|
2910
|
+
variantId: reservation.variantId,
|
|
2911
|
+
qty: reservation.qty,
|
|
2912
|
+
reservationId: reservation.reservationId,
|
|
2913
|
+
reason: "committed"
|
|
2914
|
+
});
|
|
2915
|
+
});
|
|
2916
|
+
},
|
|
2917
|
+
async getStockStatus(variantId) {
|
|
2918
|
+
const variant = await store.read((tx) => repos.variant.findById(tx, variantId));
|
|
2919
|
+
if (!variant) throw new NotFoundError8("variant", variantId);
|
|
2920
|
+
return {
|
|
2921
|
+
stock: variant.stock,
|
|
2922
|
+
threshold: variant.lowStockThreshold,
|
|
2923
|
+
status: classifyStock(variant.stock, variant.lowStockThreshold)
|
|
2924
|
+
};
|
|
2925
|
+
}
|
|
2926
|
+
};
|
|
2927
|
+
}
|
|
2928
|
+
|
|
2929
|
+
// src/services/checkout-service.ts
|
|
2930
|
+
import { v5 as uuidv5, v7 as uuidv712 } from "uuid";
|
|
2931
|
+
import {
|
|
2932
|
+
CheckoutError as CheckoutError2,
|
|
2933
|
+
EVT_CART_CONVERTED,
|
|
2934
|
+
EVT_CART_UPDATED as EVT_CART_UPDATED2,
|
|
2935
|
+
EVT_ORDER_PAID,
|
|
2936
|
+
EVT_PAYMENT_CAPTURED,
|
|
2937
|
+
EVT_PAYMENT_FAILED,
|
|
2938
|
+
EVT_PAYMENT_INTENT_CREATED,
|
|
2939
|
+
EVT_PAYMENT_REFUNDED as EVT_PAYMENT_REFUNDED2,
|
|
2940
|
+
NotFoundError as NotFoundError10,
|
|
2941
|
+
OrderConflictError as OrderConflictError4,
|
|
2942
|
+
PaymentError as PaymentError2,
|
|
2943
|
+
StatusTransitionError as StatusTransitionError4
|
|
2944
|
+
} from "@nymbalhq/types";
|
|
2945
|
+
|
|
2946
|
+
// src/money.ts
|
|
2947
|
+
function formatMoney(amountMinor, currency) {
|
|
2948
|
+
const code = currency.toUpperCase();
|
|
2949
|
+
const format = new Intl.NumberFormat("en-GB", { style: "currency", currency: code });
|
|
2950
|
+
const digits = format.resolvedOptions().maximumFractionDigits ?? 2;
|
|
2951
|
+
return format.format(amountMinor / 10 ** digits);
|
|
2952
|
+
}
|
|
2953
|
+
|
|
2954
|
+
// src/services/order-correlation.ts
|
|
2955
|
+
function inOrderScope(order, fn) {
|
|
2956
|
+
const id2 = order?.metadata?.correlationId;
|
|
2957
|
+
return typeof id2 === "string" ? runWithCorrelation(id2, fn) : fn();
|
|
2958
|
+
}
|
|
2959
|
+
|
|
2960
|
+
// src/services/refund-service.ts
|
|
2961
|
+
import { v7 as uuidv711 } from "uuid";
|
|
2962
|
+
import {
|
|
2963
|
+
EVT_ORDER_PARTIALLY_REFUNDED,
|
|
2964
|
+
EVT_ORDER_REFUNDED,
|
|
2965
|
+
EVT_PAYMENT_REFUNDED,
|
|
2966
|
+
NotFoundError as NotFoundError9,
|
|
2967
|
+
OrderConflictError as OrderConflictError3,
|
|
2968
|
+
PaymentError,
|
|
2969
|
+
StatusTransitionError as StatusTransitionError3,
|
|
2970
|
+
ValidationError as ValidationError9,
|
|
2971
|
+
canTransitionOrder,
|
|
2972
|
+
paymentState as paymentState2,
|
|
2973
|
+
refundableMinor
|
|
2974
|
+
} from "@nymbalhq/types";
|
|
2975
|
+
var PROVIDER_REFUND_REASON = "requested_by_customer";
|
|
2976
|
+
function orderPayment(order, refunds) {
|
|
2977
|
+
return {
|
|
2978
|
+
state: paymentState2(order),
|
|
2979
|
+
capturedMinor: order.capturedMinor,
|
|
2980
|
+
refundedMinor: order.refundedMinor,
|
|
2981
|
+
refundableMinor: refundableMinor(order, refunds),
|
|
2982
|
+
currency: order.currency,
|
|
2983
|
+
refunds
|
|
2984
|
+
};
|
|
2985
|
+
}
|
|
2986
|
+
function settlementOf(answer, row) {
|
|
2987
|
+
const matches = answer.amountMinor === row.amountMinor && answer.currency.toUpperCase() === row.currency.toUpperCase();
|
|
2988
|
+
const providerRefundId = answer.refundId;
|
|
2989
|
+
if (answer.status === "failed") return { status: "failed", providerRefundId, mismatch: false };
|
|
2990
|
+
if (!matches) return { status: "pending", providerRefundId, mismatch: true };
|
|
2991
|
+
return { status: answer.status, providerRefundId, mismatch: false };
|
|
2992
|
+
}
|
|
2993
|
+
async function refreshRefunded(repos, tx, orderId, at) {
|
|
2994
|
+
const refunds = await repos.orderRefund.listByOrder(tx, orderId);
|
|
2995
|
+
const refundedMinor = refunds.filter((r) => r.status === "succeeded").reduce((sum, r) => sum + r.amountMinor, 0);
|
|
2996
|
+
const current = await repos.order.findById(tx, orderId);
|
|
2997
|
+
if (current.refundedMinor !== refundedMinor) {
|
|
2998
|
+
await repos.order.setRefunded(tx, orderId, refundedMinor, at);
|
|
2999
|
+
}
|
|
3000
|
+
return { refunds, refundedMinor };
|
|
3001
|
+
}
|
|
3002
|
+
function createRefundService(deps) {
|
|
3003
|
+
const { store, repos, publisher, logger, payments } = deps;
|
|
3004
|
+
async function hold2(tx, input) {
|
|
3005
|
+
audit.note("order.refund", [{ type: "order", id: input.orderId }]);
|
|
3006
|
+
const order = await repos.order.lock(tx, input.orderId);
|
|
3007
|
+
if (!order) throw new NotFoundError9("order", input.orderId);
|
|
3008
|
+
if (input.requestId !== void 0) {
|
|
3009
|
+
const earlier = await repos.orderRefund.findByRequestId(tx, order.id, input.requestId);
|
|
3010
|
+
if (earlier !== null) {
|
|
3011
|
+
if (earlier.amountMinor !== input.amountMinor) {
|
|
3012
|
+
throw new OrderConflictError3(
|
|
3013
|
+
"refund.request_reused",
|
|
3014
|
+
`Request ${input.requestId} already refunded ${formatMoney(earlier.amountMinor, earlier.currency)} on order ${order.orderNumber}`,
|
|
3015
|
+
{
|
|
3016
|
+
context: { amountMinor: input.amountMinor, earlierAmountMinor: earlier.amountMinor }
|
|
3017
|
+
}
|
|
3018
|
+
);
|
|
3019
|
+
}
|
|
3020
|
+
const refunds = await repos.orderRefund.listByOrder(tx, order.id);
|
|
3021
|
+
return { repeat: { order, payment: orderPayment(order, refunds), refund: earlier } };
|
|
3022
|
+
}
|
|
3023
|
+
}
|
|
3024
|
+
if (order.capturedMinor <= 0 || order.captureMethod === "provider" && !order.paymentIntentId) {
|
|
3025
|
+
throw new OrderConflictError3(
|
|
3026
|
+
"refund.not_captured",
|
|
3027
|
+
`Order ${order.orderNumber} has no captured payment to refund`
|
|
3028
|
+
);
|
|
3029
|
+
}
|
|
3030
|
+
const refundable = refundableMinor(order, await repos.orderRefund.listByOrder(tx, order.id));
|
|
3031
|
+
if (input.amountMinor > refundable) {
|
|
3032
|
+
throw new OrderConflictError3(
|
|
3033
|
+
"refund.exceeds_captured",
|
|
3034
|
+
`Refund of ${formatMoney(input.amountMinor, order.currency)} exceeds the ${formatMoney(refundable, order.currency)} refundable on order ${order.orderNumber}`,
|
|
3035
|
+
{ context: { amountMinor: input.amountMinor, refundableMinor: refundable } }
|
|
3036
|
+
);
|
|
3037
|
+
}
|
|
3038
|
+
if (!canTransitionOrder(order.status, "refunded")) {
|
|
3039
|
+
throw new StatusTransitionError3("order", order.status, "refunded");
|
|
3040
|
+
}
|
|
3041
|
+
const row = {
|
|
3042
|
+
id: uuidv711(),
|
|
3043
|
+
orderId: order.id,
|
|
3044
|
+
amountMinor: input.amountMinor,
|
|
3045
|
+
currency: order.currency,
|
|
3046
|
+
providerRefundId: null,
|
|
3047
|
+
status: "pending",
|
|
3048
|
+
reason: input.reason ?? null,
|
|
3049
|
+
actor: input.actor,
|
|
3050
|
+
createdAt: /* @__PURE__ */ new Date(),
|
|
3051
|
+
requestId: input.requestId ?? null
|
|
3052
|
+
};
|
|
3053
|
+
await repos.orderRefund.insert(tx, row);
|
|
3054
|
+
return { order, row };
|
|
3055
|
+
}
|
|
3056
|
+
async function moveMoney(order, row) {
|
|
3057
|
+
if (order.captureMethod !== "provider") {
|
|
3058
|
+
return { status: "succeeded", providerRefundId: null, mismatch: false };
|
|
3059
|
+
}
|
|
3060
|
+
const context2 = { orderId: order.id, refundId: row.id, amountMinor: row.amountMinor };
|
|
3061
|
+
try {
|
|
3062
|
+
const answer = await payments.refund(
|
|
3063
|
+
order.paymentIntentId,
|
|
3064
|
+
row.amountMinor,
|
|
3065
|
+
PROVIDER_REFUND_REASON,
|
|
3066
|
+
{ idempotencyKey: row.id, currency: order.currency }
|
|
3067
|
+
);
|
|
3068
|
+
const settlement = settlementOf(answer, row);
|
|
3069
|
+
if (settlement.mismatch) {
|
|
3070
|
+
logger.error(
|
|
3071
|
+
{ ...context2, answer: { amountMinor: answer.amountMinor, currency: answer.currency } },
|
|
3072
|
+
"provider refund answer differs from the refund; left pending"
|
|
3073
|
+
);
|
|
3074
|
+
}
|
|
3075
|
+
return settlement;
|
|
3076
|
+
} catch (err) {
|
|
3077
|
+
if (err instanceof PaymentError && err.code === "payment.refund_rejected") {
|
|
3078
|
+
logger.warn({ ...context2, err }, "provider refused the refund");
|
|
3079
|
+
return { status: "failed", providerRefundId: null, mismatch: false };
|
|
3080
|
+
}
|
|
3081
|
+
logger.error({ ...context2, err }, "refund outcome unknown; left pending until reconciled");
|
|
3082
|
+
return { status: "pending", providerRefundId: null, mismatch: false };
|
|
3083
|
+
}
|
|
3084
|
+
}
|
|
3085
|
+
async function settle(tx, orderId, row, settlement) {
|
|
3086
|
+
const order = await repos.order.lock(tx, orderId);
|
|
3087
|
+
if (!order) throw new NotFoundError9("order", orderId);
|
|
3088
|
+
await repos.orderRefund.settle(tx, row.id, {
|
|
3089
|
+
status: settlement.status,
|
|
3090
|
+
providerRefundId: settlement.providerRefundId
|
|
3091
|
+
});
|
|
3092
|
+
const now = /* @__PURE__ */ new Date();
|
|
3093
|
+
const { refunds, refundedMinor } = await refreshRefunded(repos, tx, order.id, now);
|
|
3094
|
+
const refund = refunds.find((r) => r.id === row.id);
|
|
3095
|
+
if (refund.status === "succeeded") await recordSucceeded(tx, order, refundedMinor, refund, now);
|
|
3096
|
+
const fresh = await repos.order.findById(tx, order.id);
|
|
3097
|
+
return { order: fresh, payment: orderPayment(fresh, refunds), refund };
|
|
3098
|
+
}
|
|
3099
|
+
async function recordSucceeded(tx, order, refundedMinor, refund, now) {
|
|
3100
|
+
const full = refundedMinor >= order.capturedMinor;
|
|
3101
|
+
const target = full ? "refunded" : "partially_refunded";
|
|
3102
|
+
const note = `${REFUND_NOTE_PREFIX}${formatMoney(refund.amountMinor, refund.currency)}${refund.reason ? `: ${refund.reason}` : ""}`;
|
|
3103
|
+
let toStatus = order.status;
|
|
3104
|
+
if (order.status !== target && canTransitionOrder(order.status, target)) {
|
|
3105
|
+
await repos.order.setStatus(tx, order.id, target, now);
|
|
3106
|
+
toStatus = target;
|
|
3107
|
+
} else if (order.status !== target) {
|
|
3108
|
+
logger.warn(
|
|
3109
|
+
{ orderId: order.id, refundId: refund.id, status: order.status, wanted: target },
|
|
3110
|
+
"refund settled; the order status no longer allows the move and is kept"
|
|
3111
|
+
);
|
|
3112
|
+
}
|
|
3113
|
+
await repos.orderHistory.append(tx, {
|
|
3114
|
+
id: uuidv711(),
|
|
3115
|
+
orderId: order.id,
|
|
3116
|
+
fromStatus: order.status,
|
|
3117
|
+
toStatus,
|
|
3118
|
+
actor: refund.actor,
|
|
3119
|
+
note,
|
|
3120
|
+
timestamp: now
|
|
3121
|
+
});
|
|
3122
|
+
if (order.customerId) {
|
|
3123
|
+
await repos.customer.incrementStats(tx, order.customerId, 0, -refund.amountMinor, now);
|
|
3124
|
+
}
|
|
3125
|
+
const payload = {
|
|
3126
|
+
orderId: order.id,
|
|
3127
|
+
refundId: refund.id,
|
|
3128
|
+
amountMinor: refund.amountMinor,
|
|
3129
|
+
currency: refund.currency,
|
|
3130
|
+
reason: refund.reason ?? ""
|
|
3131
|
+
};
|
|
3132
|
+
await publisher.publish(full ? EVT_ORDER_REFUNDED : EVT_ORDER_PARTIALLY_REFUNDED, payload);
|
|
3133
|
+
await publisher.publish(EVT_PAYMENT_REFUNDED, {
|
|
3134
|
+
paymentId: order.captureMethod === "provider" ? order.paymentIntentId ?? "" : "",
|
|
3135
|
+
orderId: order.id,
|
|
3136
|
+
refundId: refund.id,
|
|
3137
|
+
amountMinor: refund.amountMinor,
|
|
3138
|
+
currency: refund.currency
|
|
3139
|
+
});
|
|
3140
|
+
}
|
|
3141
|
+
return {
|
|
3142
|
+
async refund(input) {
|
|
3143
|
+
audit.note("order.refund", [{ type: "order", id: input.orderId }]);
|
|
3144
|
+
if (!Number.isInteger(input.amountMinor) || input.amountMinor <= 0) {
|
|
3145
|
+
throw new ValidationError9("amountMinor must be a positive whole number of minor units", {
|
|
3146
|
+
context: { amountMinor: input.amountMinor }
|
|
3147
|
+
});
|
|
3148
|
+
}
|
|
3149
|
+
const held = await store.transaction((tx) => hold2(tx, input));
|
|
3150
|
+
if ("repeat" in held) return held.repeat;
|
|
3151
|
+
const { order, row } = held;
|
|
3152
|
+
const settlement = await moveMoney(order, row);
|
|
3153
|
+
return store.transaction((tx) => settle(tx, order.id, row, settlement));
|
|
3154
|
+
}
|
|
3155
|
+
};
|
|
3156
|
+
}
|
|
3157
|
+
|
|
3158
|
+
// src/services/checkout-service.ts
|
|
3159
|
+
var CHECKOUT_KEYS_KEPT = 5;
|
|
3160
|
+
var DEFAULT_CHECKOUT_KEY_LIFETIME_MS = 48 * 36e5;
|
|
3161
|
+
var StockUnavailable = class extends Error {
|
|
3162
|
+
constructor(variantId) {
|
|
3163
|
+
super(`stock unavailable for variant ${variantId}`);
|
|
3164
|
+
this.variantId = variantId;
|
|
3165
|
+
}
|
|
3166
|
+
variantId;
|
|
3167
|
+
};
|
|
3168
|
+
var NoLongerPending = class extends Error {
|
|
3169
|
+
};
|
|
3170
|
+
var PROVIDER_CAPTURE = {
|
|
3171
|
+
method: "provider",
|
|
3172
|
+
actor: "system:checkout",
|
|
3173
|
+
note: "payment captured"
|
|
3174
|
+
};
|
|
3175
|
+
var FINALIZE_ACTOR = "system:checkout-finalize";
|
|
3176
|
+
var CANCEL_ACTOR = "system:checkout-cancel";
|
|
3177
|
+
var DUPLICATE_CAPTURE = "duplicate_capture_refunded";
|
|
3178
|
+
var DUPLICATE_CAPTURE_HANDLER = "checkout:duplicate-capture";
|
|
3179
|
+
var CAPTURE_REFUND_NAMESPACE = "49e623d3-5784-4331-80e9-6f951d97f7c0";
|
|
3180
|
+
var SUPERSEDE_ATTEMPTS = 3;
|
|
3181
|
+
var ABANDON_AFTER_MS = 12e4;
|
|
3182
|
+
function outcomeOf(status) {
|
|
3183
|
+
if (status === "succeeded") return "succeeded";
|
|
3184
|
+
if (status === "failed" || status === "cancelled") return "failed";
|
|
3185
|
+
return "requires_action";
|
|
3186
|
+
}
|
|
3187
|
+
function sameLines(order, cart) {
|
|
3188
|
+
if (order.totalMinor !== cart.subtotalMinor || order.currency !== cart.currency) return false;
|
|
3189
|
+
if (order.lineItems.length !== cart.items.length) return false;
|
|
3190
|
+
return cart.items.every((item, i) => {
|
|
3191
|
+
const line = order.lineItems[i];
|
|
3192
|
+
return line?.variantId === item.variantId && line.qty === item.qty && line.unitPriceMinor === item.priceMinor;
|
|
3193
|
+
});
|
|
3194
|
+
}
|
|
3195
|
+
function createCheckoutService(deps) {
|
|
3196
|
+
const { store, repos, publisher, logger, cart, orders, inventory, payments, currency } = deps;
|
|
3197
|
+
const keyLifetimeMs = deps.keyLifetimeMs ?? DEFAULT_CHECKOUT_KEY_LIFETIME_MS;
|
|
3198
|
+
async function mintKey(tx, order) {
|
|
3199
|
+
if (order.customerId !== null) return void 0;
|
|
3200
|
+
const { key, hash } = mintOrderKey();
|
|
3201
|
+
const createdAt = /* @__PURE__ */ new Date();
|
|
3202
|
+
await repos.orderAccessKey.insert(tx, {
|
|
3203
|
+
id: uuidv712(),
|
|
3204
|
+
orderId: order.id,
|
|
3205
|
+
keyHash: hash,
|
|
3206
|
+
purpose: "checkout",
|
|
3207
|
+
createdAt,
|
|
3208
|
+
expiresAt: new Date(createdAt.getTime() + keyLifetimeMs)
|
|
3209
|
+
});
|
|
3210
|
+
await repos.orderAccessKey.keepNewest(tx, order.id, "checkout", CHECKOUT_KEYS_KEPT);
|
|
3211
|
+
return key;
|
|
3212
|
+
}
|
|
3213
|
+
function withKey(answer, orderKey) {
|
|
3214
|
+
return orderKey === void 0 ? answer : { ...answer, orderKey };
|
|
3215
|
+
}
|
|
3216
|
+
async function withOrderKey(err) {
|
|
3217
|
+
if (!(err instanceof CheckoutError2)) return err;
|
|
3218
|
+
const orderNumber = err.context["orderNumber"];
|
|
3219
|
+
if (typeof orderNumber !== "string") return err;
|
|
3220
|
+
const order = await store.read((tx) => repos.order.findByOrderNumber(tx, orderNumber));
|
|
3221
|
+
if (order === null) return err;
|
|
3222
|
+
const orderKey = await store.transaction((tx) => mintKey(tx, order));
|
|
3223
|
+
if (orderKey !== void 0) err.context["orderKey"] = orderKey;
|
|
3224
|
+
return err;
|
|
3225
|
+
}
|
|
3226
|
+
async function cartEmpty(token) {
|
|
3227
|
+
const converted = await store.read((tx) => repos.order.findLastConvertedByCartToken(tx, token));
|
|
3228
|
+
return new CheckoutError2(
|
|
3229
|
+
"cart_empty",
|
|
3230
|
+
"Cart has no items",
|
|
3231
|
+
converted ? { context: { orderNumber: converted.orderNumber } } : {}
|
|
3232
|
+
);
|
|
3233
|
+
}
|
|
3234
|
+
async function loadValidCart(token) {
|
|
3235
|
+
const c = await cart.get(token);
|
|
3236
|
+
if (!c) throw new NotFoundError10("cart", token);
|
|
3237
|
+
if (!c.items.length) throw await cartEmpty(token);
|
|
3238
|
+
if (c.currency !== currency) {
|
|
3239
|
+
throw new CheckoutError2(
|
|
3240
|
+
"cart_empty",
|
|
3241
|
+
`Cart currency ${c.currency} does not match store currency ${currency}`
|
|
3242
|
+
);
|
|
3243
|
+
}
|
|
3244
|
+
return c;
|
|
3245
|
+
}
|
|
3246
|
+
async function settled(tx, paymentIntentId, order, paid) {
|
|
3247
|
+
if (order === null) return recordOutcome(tx, paymentIntentId, null, "no_order");
|
|
3248
|
+
if (order.captureMethod === "manual" || order.captureMethod === "import") {
|
|
3249
|
+
return refundDuplicateCapture(tx, paymentIntentId, paid, order);
|
|
3250
|
+
}
|
|
3251
|
+
if (order.status === "confirmed") return { orderNumber: order.orderNumber, finalized: true };
|
|
3252
|
+
if (order.status === "cancelled") {
|
|
3253
|
+
if (order.capturedMinor === 0) await refundCancelledCapture(paymentIntentId, paid, order);
|
|
3254
|
+
return recordOutcome(tx, paymentIntentId, order, "order_cancelled_refunded");
|
|
3255
|
+
}
|
|
3256
|
+
return recordOutcome(tx, paymentIntentId, order, `order_not_pending: ${order.status}`);
|
|
3257
|
+
}
|
|
3258
|
+
async function recordOutcome(tx, paymentIntentId, order, reason, detail) {
|
|
3259
|
+
await publisher.publish(EVT_PAYMENT_FAILED, {
|
|
3260
|
+
paymentId: paymentIntentId,
|
|
3261
|
+
orderId: order?.id ?? "",
|
|
3262
|
+
reason
|
|
3263
|
+
});
|
|
3264
|
+
if (order !== null) {
|
|
3265
|
+
audit.note("payment.recordOutcome", [{ type: "order", id: order.id }]);
|
|
3266
|
+
await repos.orderHistory.append(tx, {
|
|
3267
|
+
id: uuidv712(),
|
|
3268
|
+
orderId: order.id,
|
|
3269
|
+
fromStatus: order.status,
|
|
3270
|
+
toStatus: order.status,
|
|
3271
|
+
actor: FINALIZE_ACTOR,
|
|
3272
|
+
note: `captured payment not applied: ${reason}${detail === void 0 ? "" : ` (${detail})`}`,
|
|
3273
|
+
timestamp: /* @__PURE__ */ new Date()
|
|
3274
|
+
});
|
|
3275
|
+
}
|
|
3276
|
+
logger.warn({ paymentIntentId, orderId: order?.id, reason }, "captured payment not applied");
|
|
3277
|
+
return { orderNumber: order?.orderNumber ?? null, finalized: false, reason };
|
|
3278
|
+
}
|
|
3279
|
+
async function reservationFor(tx, order, reservationId, index) {
|
|
3280
|
+
const held = await repos.inventoryReservation.findById(tx, reservationId);
|
|
3281
|
+
if (held !== null) return reservationId;
|
|
3282
|
+
const line = order.lineItems[index];
|
|
3283
|
+
if (line === void 0) {
|
|
3284
|
+
throw new CheckoutError2(
|
|
3285
|
+
"finalize_failed",
|
|
3286
|
+
`Order ${order.id} has no line for reservation ${reservationId}`
|
|
3287
|
+
);
|
|
3288
|
+
}
|
|
3289
|
+
const retaken = await inventory.tryReserveStock(line.variantId, line.qty, order.id).catch((err) => {
|
|
3290
|
+
if (err instanceof NotFoundError10) return null;
|
|
3291
|
+
throw err;
|
|
3292
|
+
});
|
|
3293
|
+
if (retaken === null) throw new StockUnavailable(line.variantId);
|
|
3294
|
+
return retaken.reservationId;
|
|
3295
|
+
}
|
|
3296
|
+
async function refundCapture(paymentIntentId, paid, currency2, key, context2) {
|
|
3297
|
+
try {
|
|
3298
|
+
const answer = await payments.refund(
|
|
3299
|
+
paymentIntentId,
|
|
3300
|
+
paid.amountMinor,
|
|
3301
|
+
PROVIDER_REFUND_REASON,
|
|
3302
|
+
{
|
|
3303
|
+
idempotencyKey: key,
|
|
3304
|
+
currency: currency2
|
|
3305
|
+
}
|
|
3306
|
+
);
|
|
3307
|
+
const settlement = settlementOf(answer, { amountMinor: paid.amountMinor, currency: currency2 });
|
|
3308
|
+
if (settlement.mismatch) {
|
|
3309
|
+
logger.error(
|
|
3310
|
+
{ ...context2, answer: { amountMinor: answer.amountMinor, currency: answer.currency } },
|
|
3311
|
+
"provider refund answer differs from the capture; left pending"
|
|
3312
|
+
);
|
|
3313
|
+
}
|
|
3314
|
+
return settlement;
|
|
3315
|
+
} catch (err) {
|
|
3316
|
+
if (err instanceof PaymentError2 && err.code === "payment.refund_rejected") {
|
|
3317
|
+
logger.error({ ...context2, err }, "provider refused the refund of a capture");
|
|
3318
|
+
return { status: "failed", providerRefundId: null, mismatch: false };
|
|
3319
|
+
}
|
|
3320
|
+
logger.error(
|
|
3321
|
+
{ ...context2, err },
|
|
3322
|
+
"capture refund outcome unknown; left pending until reconciled"
|
|
3323
|
+
);
|
|
3324
|
+
return { status: "pending", providerRefundId: null, mismatch: false };
|
|
3325
|
+
}
|
|
3326
|
+
}
|
|
3327
|
+
async function refundCancelledCapture(paymentIntentId, paid, order) {
|
|
3328
|
+
const refundId = uuidv5(`cancelled-capture:${paymentIntentId}`, CAPTURE_REFUND_NAMESPACE);
|
|
3329
|
+
const held = await store.transaction(async (tx) => {
|
|
3330
|
+
audit.note("payment.refundCapture", [{ type: "order", id: order.id }]);
|
|
3331
|
+
const locked = await repos.order.lock(tx, order.id);
|
|
3332
|
+
if (locked === null || locked.capturedMinor > 0) return false;
|
|
3333
|
+
const now = /* @__PURE__ */ new Date();
|
|
3334
|
+
await repos.order.recordCapture(tx, order.id, {
|
|
3335
|
+
amountMinor: paid.amountMinor,
|
|
3336
|
+
method: "provider",
|
|
3337
|
+
at: now
|
|
3338
|
+
});
|
|
3339
|
+
await repos.orderRefund.insert(tx, {
|
|
3340
|
+
id: refundId,
|
|
3341
|
+
orderId: order.id,
|
|
3342
|
+
amountMinor: paid.amountMinor,
|
|
3343
|
+
currency: order.currency,
|
|
3344
|
+
providerRefundId: null,
|
|
3345
|
+
status: "pending",
|
|
3346
|
+
reason: "captured for a cancelled order",
|
|
3347
|
+
actor: "system:checkout",
|
|
3348
|
+
createdAt: now
|
|
3349
|
+
});
|
|
3350
|
+
await publisher.publish(EVT_PAYMENT_CAPTURED, {
|
|
3351
|
+
paymentId: paymentIntentId,
|
|
3352
|
+
orderId: order.id,
|
|
3353
|
+
amountMinor: paid.amountMinor,
|
|
3354
|
+
currency: order.currency
|
|
3355
|
+
});
|
|
3356
|
+
return true;
|
|
3357
|
+
});
|
|
3358
|
+
if (!held) return;
|
|
3359
|
+
const settlement = await refundCapture(paymentIntentId, paid, order.currency, refundId, {
|
|
3360
|
+
orderId: order.id,
|
|
3361
|
+
refundId
|
|
3362
|
+
});
|
|
3363
|
+
if (settlement.status === "pending") return;
|
|
3364
|
+
await store.transaction(async (tx) => {
|
|
3365
|
+
await repos.order.lock(tx, order.id);
|
|
3366
|
+
await repos.orderRefund.settle(tx, refundId, {
|
|
3367
|
+
status: settlement.status,
|
|
3368
|
+
providerRefundId: settlement.providerRefundId
|
|
3369
|
+
});
|
|
3370
|
+
await refreshRefunded(repos, tx, order.id, /* @__PURE__ */ new Date());
|
|
3371
|
+
if (settlement.status === "succeeded") {
|
|
3372
|
+
await publisher.publish(EVT_PAYMENT_REFUNDED2, {
|
|
3373
|
+
paymentId: paymentIntentId,
|
|
3374
|
+
orderId: order.id,
|
|
3375
|
+
refundId,
|
|
3376
|
+
amountMinor: paid.amountMinor,
|
|
3377
|
+
currency: order.currency
|
|
3378
|
+
});
|
|
3379
|
+
}
|
|
3380
|
+
});
|
|
3381
|
+
}
|
|
3382
|
+
async function refundDuplicateCapture(tx, paymentIntentId, paid, order) {
|
|
3383
|
+
if (await repos.processedEvent.seen(tx, DUPLICATE_CAPTURE_HANDLER, paymentIntentId)) {
|
|
3384
|
+
return { orderNumber: order.orderNumber, finalized: false, reason: DUPLICATE_CAPTURE };
|
|
3385
|
+
}
|
|
3386
|
+
const key = uuidv5(`duplicate-capture:${paymentIntentId}`, CAPTURE_REFUND_NAMESPACE);
|
|
3387
|
+
const settlement = await refundCapture(
|
|
3388
|
+
paymentIntentId,
|
|
3389
|
+
paid,
|
|
3390
|
+
paid.currency.toUpperCase(),
|
|
3391
|
+
key,
|
|
3392
|
+
{
|
|
3393
|
+
orderId: order.id,
|
|
3394
|
+
idempotencyKey: key
|
|
3395
|
+
}
|
|
3396
|
+
);
|
|
3397
|
+
if (settlement.status === "pending" && !settlement.mismatch) {
|
|
3398
|
+
throw new CheckoutError2(
|
|
3399
|
+
"finalize_failed",
|
|
3400
|
+
`The refund of a second capture of order ${order.orderNumber} has no known outcome`,
|
|
3401
|
+
{ context: { orderNumber: order.orderNumber } }
|
|
3402
|
+
);
|
|
3403
|
+
}
|
|
3404
|
+
await repos.processedEvent.markProcessed(
|
|
3405
|
+
tx,
|
|
3406
|
+
DUPLICATE_CAPTURE_HANDLER,
|
|
3407
|
+
paymentIntentId,
|
|
3408
|
+
/* @__PURE__ */ new Date()
|
|
3409
|
+
);
|
|
3410
|
+
const reason = settlement.status === "succeeded" ? DUPLICATE_CAPTURE : `duplicate_capture_refund_${settlement.status}`;
|
|
3411
|
+
return recordOutcome(
|
|
3412
|
+
tx,
|
|
3413
|
+
paymentIntentId,
|
|
3414
|
+
order,
|
|
3415
|
+
reason,
|
|
3416
|
+
`capture of ${formatMoney(paid.amountMinor, paid.currency)}`
|
|
3417
|
+
);
|
|
3418
|
+
}
|
|
3419
|
+
async function confirm(tx, paymentIntentId, paid, order, capture) {
|
|
3420
|
+
const metadata = order.metadata;
|
|
3421
|
+
const reservationIds = Array.isArray(metadata.reservationIds) ? metadata.reservationIds : [];
|
|
3422
|
+
audit.note("order.confirm", [{ type: "order", id: order.id }]);
|
|
3423
|
+
for (const [index, reservationId] of reservationIds.entries()) {
|
|
3424
|
+
const reservation = await reservationFor(tx, order, reservationId, index);
|
|
3425
|
+
await inventory.commitReservation(reservation, FINALIZE_ACTOR);
|
|
3426
|
+
}
|
|
3427
|
+
const now = /* @__PURE__ */ new Date();
|
|
3428
|
+
if (!await repos.order.setStatusIf(tx, order.id, "pending", "confirmed", now)) {
|
|
3429
|
+
throw new NoLongerPending();
|
|
3430
|
+
}
|
|
3431
|
+
await repos.order.recordCapture(tx, order.id, {
|
|
3432
|
+
amountMinor: paid.amountMinor,
|
|
3433
|
+
method: capture.method,
|
|
3434
|
+
at: now
|
|
3435
|
+
});
|
|
3436
|
+
await repos.orderHistory.append(tx, {
|
|
3437
|
+
id: uuidv712(),
|
|
3438
|
+
orderId: order.id,
|
|
3439
|
+
fromStatus: "pending",
|
|
3440
|
+
toStatus: "confirmed",
|
|
3441
|
+
actor: capture.actor,
|
|
3442
|
+
note: capture.note,
|
|
3443
|
+
timestamp: now
|
|
3444
|
+
});
|
|
3445
|
+
if (order.customerId) {
|
|
3446
|
+
await repos.customer.incrementStats(tx, order.customerId, 1, paid.amountMinor, now);
|
|
3447
|
+
}
|
|
3448
|
+
await publisher.publish(EVT_PAYMENT_CAPTURED, {
|
|
3449
|
+
paymentId: paymentIntentId,
|
|
3450
|
+
orderId: order.id,
|
|
3451
|
+
amountMinor: paid.amountMinor,
|
|
3452
|
+
currency: order.currency
|
|
3453
|
+
});
|
|
3454
|
+
await publisher.publish(EVT_ORDER_PAID, {
|
|
3455
|
+
orderId: order.id,
|
|
3456
|
+
paymentIntentId,
|
|
3457
|
+
amountMinor: paid.amountMinor,
|
|
3458
|
+
currency: order.currency
|
|
3459
|
+
});
|
|
3460
|
+
const cartToken = metadata.cartToken;
|
|
3461
|
+
if (cartToken) {
|
|
3462
|
+
if (await repos.cart.clearIfLive(tx, cartToken, now)) {
|
|
3463
|
+
await publisher.publish(EVT_CART_UPDATED2, {
|
|
3464
|
+
cartId: cartToken,
|
|
3465
|
+
itemCount: 0,
|
|
3466
|
+
totalMinor: 0
|
|
3467
|
+
});
|
|
3468
|
+
}
|
|
3469
|
+
await publisher.publish(EVT_CART_CONVERTED, {
|
|
3470
|
+
cartId: cartToken,
|
|
3471
|
+
orderId: order.id
|
|
3472
|
+
});
|
|
3473
|
+
}
|
|
3474
|
+
logger.info({ orderId: order.id, orderNumber: order.orderNumber }, "checkout finalized");
|
|
3475
|
+
return { orderNumber: order.orderNumber, finalized: true };
|
|
3476
|
+
}
|
|
3477
|
+
async function cancelDraft(orderId, reason) {
|
|
3478
|
+
await store.transaction(async (tx) => {
|
|
3479
|
+
const order = await repos.order.findById(tx, orderId);
|
|
3480
|
+
if (!order) throw new NotFoundError10("order", orderId);
|
|
3481
|
+
const metadata = order.metadata;
|
|
3482
|
+
const reservationIds = Array.isArray(metadata.reservationIds) ? metadata.reservationIds : [];
|
|
3483
|
+
for (const rid of reservationIds) {
|
|
3484
|
+
await inventory.releaseReservation(rid, "cancelled");
|
|
3485
|
+
}
|
|
3486
|
+
await orders.cancel(orderId, reason, CANCEL_ACTOR);
|
|
3487
|
+
});
|
|
3488
|
+
}
|
|
3489
|
+
async function checkStock(tx, cartDoc) {
|
|
3490
|
+
for (const item of cartDoc.items) {
|
|
3491
|
+
const v = await repos.variant.findById(tx, item.variantId);
|
|
3492
|
+
if (!v) {
|
|
3493
|
+
throw new CheckoutError2("variant_missing", `Variant missing: ${item.variantId}`);
|
|
3494
|
+
}
|
|
3495
|
+
if (v.stock < item.qty) {
|
|
3496
|
+
throw new CheckoutError2(
|
|
3497
|
+
"out_of_stock",
|
|
3498
|
+
`Insufficient stock for ${item.variantName}: available ${v.stock}, requested ${item.qty}`
|
|
3499
|
+
);
|
|
3500
|
+
}
|
|
3501
|
+
}
|
|
3502
|
+
}
|
|
3503
|
+
async function place(tx, input, closed) {
|
|
3504
|
+
const cartDoc = await repos.cart.lock(tx, input.cartToken);
|
|
3505
|
+
if (cartDoc === null) throw new NotFoundError10("cart", input.cartToken);
|
|
3506
|
+
if (!cartDoc.items.length) throw await cartEmpty(input.cartToken);
|
|
3507
|
+
const pending = await repos.order.findPendingByCartToken(tx, input.cartToken);
|
|
3508
|
+
if (pending !== null) {
|
|
3509
|
+
const { paymentIntentId } = pending;
|
|
3510
|
+
if (paymentIntentId === null) {
|
|
3511
|
+
if (Date.now() - Date.parse(pending.createdAt) <= ABANDON_AFTER_MS) {
|
|
3512
|
+
throw new CheckoutError2("in_progress", "A checkout for this cart is already in progress");
|
|
3513
|
+
}
|
|
3514
|
+
await cancelDraft(pending.id, "abandoned: no payment intent");
|
|
3515
|
+
} else {
|
|
3516
|
+
const reason = closed.get(paymentIntentId);
|
|
3517
|
+
if (reason === void 0) {
|
|
3518
|
+
if (sameLines(pending, cartDoc)) {
|
|
3519
|
+
const orderKey = await mintKey(tx, pending);
|
|
3520
|
+
return { kind: "existing", order: { ...pending, paymentIntentId }, orderKey };
|
|
3521
|
+
}
|
|
3522
|
+
return { kind: "cancel-first", order: { ...pending, paymentIntentId } };
|
|
3523
|
+
}
|
|
3524
|
+
await cancelDraft(pending.id, reason);
|
|
3525
|
+
}
|
|
3526
|
+
}
|
|
3527
|
+
await checkStock(tx, cartDoc);
|
|
3528
|
+
const lineItems = cartDoc.items.map((item) => ({
|
|
3529
|
+
variantId: item.variantId,
|
|
3530
|
+
productId: item.productId,
|
|
3531
|
+
productName: item.productName,
|
|
3532
|
+
variantName: item.variantName,
|
|
3533
|
+
sku: "",
|
|
3534
|
+
qty: item.qty,
|
|
3535
|
+
unitPriceMinor: item.priceMinor,
|
|
3536
|
+
lineSubtotalMinor: item.priceMinor * item.qty,
|
|
3537
|
+
lineTaxMinor: 0,
|
|
3538
|
+
lineTotalMinor: item.priceMinor * item.qty,
|
|
3539
|
+
imageUrl: item.imageUrl
|
|
3540
|
+
}));
|
|
3541
|
+
const orderId = uuidv712();
|
|
3542
|
+
audit.note("checkout.place", [{ type: "order", id: orderId }]);
|
|
3543
|
+
const correlationId = currentCorrelationId();
|
|
3544
|
+
const reservationIds = [];
|
|
3545
|
+
for (const item of cartDoc.items) {
|
|
3546
|
+
try {
|
|
3547
|
+
const r = await inventory.reserveStock(item.variantId, item.qty, orderId);
|
|
3548
|
+
reservationIds.push(r.reservationId);
|
|
3549
|
+
} catch (err) {
|
|
3550
|
+
if (err instanceof CheckoutError2) throw err;
|
|
3551
|
+
throw new CheckoutError2("reservation_failed", "Inventory reservation failed", {
|
|
3552
|
+
cause: err
|
|
3553
|
+
});
|
|
3554
|
+
}
|
|
3555
|
+
}
|
|
3556
|
+
const order = await orders.createFromCheckout({
|
|
3557
|
+
orderId,
|
|
3558
|
+
customerId: input.customerId ?? null,
|
|
3559
|
+
email: input.email,
|
|
3560
|
+
billingAddress: input.billingAddress,
|
|
3561
|
+
shippingAddress: input.shippingAddress,
|
|
3562
|
+
lineItems,
|
|
3563
|
+
subtotalMinor: cartDoc.subtotalMinor,
|
|
3564
|
+
taxTotalMinor: 0,
|
|
3565
|
+
shippingTotalMinor: 0,
|
|
3566
|
+
discountTotalMinor: 0,
|
|
3567
|
+
totalMinor: cartDoc.subtotalMinor,
|
|
3568
|
+
currency: cartDoc.currency,
|
|
3569
|
+
...input.notes !== void 0 && { notes: input.notes },
|
|
3570
|
+
metadata: {
|
|
3571
|
+
cartToken: cartDoc.token,
|
|
3572
|
+
reservationIds,
|
|
3573
|
+
...correlationId !== void 0 && { correlationId }
|
|
3574
|
+
},
|
|
3575
|
+
cartToken: cartDoc.token
|
|
3576
|
+
});
|
|
3577
|
+
return { kind: "placed", order, orderKey: await mintKey(tx, order) };
|
|
3578
|
+
}
|
|
3579
|
+
async function answerExisting(order) {
|
|
3580
|
+
const paymentIntent = await payments.getPaymentIntent(order.paymentIntentId);
|
|
3581
|
+
if (outcomeOf(paymentIntent.status) === "failed") {
|
|
3582
|
+
return { closed: `payment_${paymentIntent.status}` };
|
|
3583
|
+
}
|
|
3584
|
+
return {
|
|
3585
|
+
orderId: order.id,
|
|
3586
|
+
orderNumber: order.orderNumber,
|
|
3587
|
+
paymentIntent,
|
|
3588
|
+
currency: order.currency,
|
|
3589
|
+
totalMinor: order.totalMinor,
|
|
3590
|
+
orderStatus: order.status,
|
|
3591
|
+
payment: { status: "requires_action" }
|
|
3592
|
+
};
|
|
3593
|
+
}
|
|
3594
|
+
async function cancelIntent(order) {
|
|
3595
|
+
try {
|
|
3596
|
+
await payments.cancelPaymentIntent(order.paymentIntentId);
|
|
3597
|
+
} catch (err) {
|
|
3598
|
+
if (!(err instanceof PaymentError2 && err.code === "payment.cancel_refused")) throw err;
|
|
3599
|
+
throw new CheckoutError2(
|
|
3600
|
+
"payment_in_progress",
|
|
3601
|
+
`The payment for order ${order.orderNumber} is already under way`,
|
|
3602
|
+
{ cause: err, context: { orderNumber: order.orderNumber } }
|
|
3603
|
+
);
|
|
3604
|
+
}
|
|
3605
|
+
}
|
|
3606
|
+
async function pay(input, order) {
|
|
3607
|
+
const params = {
|
|
3608
|
+
amountMinor: order.totalMinor,
|
|
3609
|
+
currency: order.currency,
|
|
3610
|
+
orderRef: order.id,
|
|
3611
|
+
receiptEmail: input.email,
|
|
3612
|
+
metadata: { orderId: order.id, orderNumber: order.orderNumber }
|
|
3613
|
+
};
|
|
3614
|
+
if (input.customerId != null) params.customerId = input.customerId;
|
|
3615
|
+
let intent;
|
|
3616
|
+
try {
|
|
3617
|
+
intent = await payments.createPaymentIntent(params);
|
|
3618
|
+
} catch (err) {
|
|
3619
|
+
await cancelDraft(order.id, "payment intent not created");
|
|
3620
|
+
throw err;
|
|
3621
|
+
}
|
|
3622
|
+
let unconfirmed = null;
|
|
3623
|
+
const answer = await store.transaction(async (tx) => {
|
|
3624
|
+
await repos.cart.lock(tx, input.cartToken);
|
|
3625
|
+
await repos.order.setPaymentIntent(tx, order.id, intent.id, /* @__PURE__ */ new Date());
|
|
3626
|
+
await publisher.publish(EVT_PAYMENT_INTENT_CREATED, {
|
|
3627
|
+
paymentId: intent.id,
|
|
3628
|
+
orderId: order.id
|
|
3629
|
+
});
|
|
3630
|
+
let payment;
|
|
3631
|
+
const outcome = outcomeOf(intent.status);
|
|
3632
|
+
if (outcome === "succeeded") {
|
|
3633
|
+
const done = await finalize(intent.id, {
|
|
3634
|
+
amountMinor: intent.amountMinor,
|
|
3635
|
+
currency: intent.currency
|
|
3636
|
+
});
|
|
3637
|
+
if (!done.finalized) unconfirmed = done.reason ?? "not_confirmed";
|
|
3638
|
+
payment = unconfirmed === null ? { status: "succeeded" } : { status: "failed", reason: unconfirmed };
|
|
3639
|
+
} else if (outcome === "failed") {
|
|
3640
|
+
const reason = `payment_${intent.status}`;
|
|
3641
|
+
await cancelDraft(order.id, reason);
|
|
3642
|
+
await publisher.publish(EVT_PAYMENT_FAILED, {
|
|
3643
|
+
paymentId: intent.id,
|
|
3644
|
+
orderId: order.id,
|
|
3645
|
+
reason
|
|
3646
|
+
});
|
|
3647
|
+
payment = { status: "failed", reason };
|
|
3648
|
+
} else {
|
|
3649
|
+
payment = { status: "requires_action" };
|
|
3650
|
+
}
|
|
3651
|
+
const current = await repos.order.findById(tx, order.id);
|
|
3652
|
+
logger.info(
|
|
3653
|
+
{ orderId: order.id, orderNumber: order.orderNumber, payment: payment.status },
|
|
3654
|
+
"checkout started"
|
|
3655
|
+
);
|
|
3656
|
+
return {
|
|
3657
|
+
orderId: order.id,
|
|
3658
|
+
orderNumber: order.orderNumber,
|
|
3659
|
+
paymentIntent: intent,
|
|
3660
|
+
currency: order.currency,
|
|
3661
|
+
totalMinor: order.totalMinor,
|
|
3662
|
+
orderStatus: current?.status ?? order.status,
|
|
3663
|
+
payment
|
|
3664
|
+
};
|
|
3665
|
+
});
|
|
3666
|
+
if (unconfirmed !== null && answer.orderStatus === "pending") {
|
|
3667
|
+
await cancelDraft(order.id, unconfirmed);
|
|
3668
|
+
await refundCancelledCapture(
|
|
3669
|
+
intent.id,
|
|
3670
|
+
{ amountMinor: intent.amountMinor, currency: intent.currency },
|
|
3671
|
+
order
|
|
3672
|
+
);
|
|
3673
|
+
return { ...answer, orderStatus: "cancelled" };
|
|
3674
|
+
}
|
|
3675
|
+
return answer;
|
|
3676
|
+
}
|
|
3677
|
+
async function finalize(paymentIntentId, paid) {
|
|
3678
|
+
return store.transaction(async (tx) => {
|
|
3679
|
+
const order = await repos.order.findByPaymentIntentId(tx, paymentIntentId);
|
|
3680
|
+
return inOrderScope(order, () => finalizeLoaded(tx, paymentIntentId, paid, order));
|
|
3681
|
+
});
|
|
3682
|
+
}
|
|
3683
|
+
async function finalizeLoaded(tx, paymentIntentId, paid, order) {
|
|
3684
|
+
const outcome = (order2, reason) => recordOutcome(tx, paymentIntentId, order2, reason);
|
|
3685
|
+
if (order === null || order.status !== "pending") {
|
|
3686
|
+
return settled(tx, paymentIntentId, order, paid);
|
|
3687
|
+
}
|
|
3688
|
+
if (paid.amountMinor !== order.totalMinor || paid.currency.toUpperCase() !== order.currency.toUpperCase()) {
|
|
3689
|
+
return outcome(
|
|
3690
|
+
order,
|
|
3691
|
+
`amount_mismatch: paid ${paid.amountMinor} ${paid.currency.toUpperCase()}, due ${order.totalMinor} ${order.currency.toUpperCase()}`
|
|
3692
|
+
);
|
|
3693
|
+
}
|
|
3694
|
+
try {
|
|
3695
|
+
return await store.savepoint(
|
|
3696
|
+
() => confirm(tx, paymentIntentId, paid, order, PROVIDER_CAPTURE)
|
|
3697
|
+
);
|
|
3698
|
+
} catch (err) {
|
|
3699
|
+
if (err instanceof StockUnavailable) {
|
|
3700
|
+
const current = await repos.order.findById(tx, order.id);
|
|
3701
|
+
if (current?.status !== "pending") return settled(tx, paymentIntentId, current, paid);
|
|
3702
|
+
return outcome(current, `stock_unavailable: ${err.variantId}`);
|
|
3703
|
+
}
|
|
3704
|
+
if (!(err instanceof NoLongerPending)) throw err;
|
|
3705
|
+
}
|
|
3706
|
+
return settled(tx, paymentIntentId, await repos.order.findById(tx, order.id), paid);
|
|
3707
|
+
}
|
|
3708
|
+
return {
|
|
3709
|
+
async beginCheckout(input) {
|
|
3710
|
+
audit.note("checkout.place");
|
|
3711
|
+
try {
|
|
3712
|
+
await loadValidCart(input.cartToken);
|
|
3713
|
+
const closed = /* @__PURE__ */ new Map();
|
|
3714
|
+
for (let attempt = 0; ; attempt += 1) {
|
|
3715
|
+
const placement = await store.transaction((tx) => place(tx, input, closed));
|
|
3716
|
+
if (placement.kind === "placed") {
|
|
3717
|
+
return withKey(await pay(input, placement.order), placement.orderKey);
|
|
3718
|
+
}
|
|
3719
|
+
if (placement.kind === "existing") {
|
|
3720
|
+
const answer = await answerExisting(placement.order);
|
|
3721
|
+
if (!("closed" in answer)) return withKey(answer, placement.orderKey);
|
|
3722
|
+
closed.set(placement.order.paymentIntentId, answer.closed);
|
|
3723
|
+
continue;
|
|
3724
|
+
}
|
|
3725
|
+
if (attempt === SUPERSEDE_ATTEMPTS) {
|
|
3726
|
+
throw new CheckoutError2(
|
|
3727
|
+
"in_progress",
|
|
3728
|
+
"A checkout for this cart is already in progress"
|
|
3729
|
+
);
|
|
3730
|
+
}
|
|
3731
|
+
await cancelIntent(placement.order);
|
|
3732
|
+
closed.set(placement.order.paymentIntentId, "superseded: the cart changed");
|
|
3733
|
+
}
|
|
3734
|
+
} catch (err) {
|
|
3735
|
+
throw await withOrderKey(err);
|
|
3736
|
+
}
|
|
3737
|
+
},
|
|
3738
|
+
finalize,
|
|
3739
|
+
async cancel(orderId, reason) {
|
|
3740
|
+
await cancelDraft(orderId, reason);
|
|
3741
|
+
},
|
|
3742
|
+
async markPaid(orderId, actor, note) {
|
|
3743
|
+
audit.note("order.markPaid", [{ type: "order", id: orderId }]);
|
|
3744
|
+
const found = await store.read((tx) => repos.order.findById(tx, orderId));
|
|
3745
|
+
if (!found) throw new NotFoundError10("order", orderId);
|
|
3746
|
+
if (found.status !== "pending") {
|
|
3747
|
+
throw new StatusTransitionError4("order", found.status, "confirmed");
|
|
3748
|
+
}
|
|
3749
|
+
if (found.paymentIntentId) {
|
|
3750
|
+
try {
|
|
3751
|
+
await payments.cancelPaymentIntent(found.paymentIntentId);
|
|
3752
|
+
} catch (err) {
|
|
3753
|
+
if (!(err instanceof PaymentError2 && err.code === "payment.cancel_refused")) throw err;
|
|
3754
|
+
throw new OrderConflictError4(
|
|
3755
|
+
"order.payment_in_progress",
|
|
3756
|
+
`The payment for order ${found.orderNumber} is under way with the provider`,
|
|
3757
|
+
{ cause: err, context: { orderNumber: found.orderNumber } }
|
|
3758
|
+
);
|
|
3759
|
+
}
|
|
3760
|
+
}
|
|
3761
|
+
return store.transaction(async (tx) => {
|
|
3762
|
+
const order = await repos.order.lock(tx, orderId);
|
|
3763
|
+
if (!order) throw new NotFoundError10("order", orderId);
|
|
3764
|
+
if (order.status !== "pending") {
|
|
3765
|
+
throw new StatusTransitionError4("order", order.status, "confirmed");
|
|
3766
|
+
}
|
|
3767
|
+
const capture = {
|
|
3768
|
+
method: "manual",
|
|
3769
|
+
actor,
|
|
3770
|
+
note: note ? `payment recorded manually: ${note}` : "payment recorded manually"
|
|
3771
|
+
};
|
|
3772
|
+
const paid = { amountMinor: order.totalMinor, currency: order.currency };
|
|
3773
|
+
try {
|
|
3774
|
+
await inOrderScope(order, () => confirm(tx, "", paid, order, capture));
|
|
3775
|
+
} catch (err) {
|
|
3776
|
+
if (!(err instanceof StockUnavailable)) throw err;
|
|
3777
|
+
throw new OrderConflictError4(
|
|
3778
|
+
"order.stock_unavailable",
|
|
3779
|
+
`The stock order ${order.orderNumber} held has gone to another order`,
|
|
3780
|
+
{ context: { variantId: err.variantId } }
|
|
3781
|
+
);
|
|
3782
|
+
}
|
|
3783
|
+
return await repos.order.findById(tx, order.id);
|
|
3784
|
+
});
|
|
3785
|
+
}
|
|
3786
|
+
};
|
|
3787
|
+
}
|
|
3788
|
+
|
|
3789
|
+
// src/services/search-service.ts
|
|
3790
|
+
function createSearchService(deps) {
|
|
3791
|
+
return {
|
|
3792
|
+
async products(query, params) {
|
|
3793
|
+
return deps.adapter.search(query, params);
|
|
3794
|
+
}
|
|
3795
|
+
};
|
|
3796
|
+
}
|
|
3797
|
+
|
|
3798
|
+
// src/services/recently-viewed-service.ts
|
|
3799
|
+
import {
|
|
3800
|
+
EVT_PRODUCT_VIEWED as EVT_PRODUCT_VIEWED2,
|
|
3801
|
+
EVT_VISITOR_MERGED as EVT_VISITOR_MERGED2
|
|
3802
|
+
} from "@nymbalhq/types";
|
|
3803
|
+
function createRecentlyViewedService(deps) {
|
|
3804
|
+
const { store, repos, publisher, logger } = deps;
|
|
3805
|
+
const now = deps.now ?? (() => /* @__PURE__ */ new Date());
|
|
3806
|
+
return {
|
|
3807
|
+
async record(viewer, productId) {
|
|
3808
|
+
const product = await store.read((tx) => repos.product.findById(tx, productId));
|
|
3809
|
+
if (product?.status !== "active") return false;
|
|
3810
|
+
await publisher.publish(EVT_PRODUCT_VIEWED2, { productId, viewer }, { timestamp: now() });
|
|
3811
|
+
logger.debug({ productId, viewer: viewer.kind }, "product view recorded");
|
|
3812
|
+
return true;
|
|
3813
|
+
},
|
|
3814
|
+
async fold(visitorId, customerId) {
|
|
3815
|
+
await publisher.publish(
|
|
3816
|
+
EVT_VISITOR_MERGED2,
|
|
3817
|
+
{ visitorId, customerId },
|
|
3818
|
+
{ timestamp: now() }
|
|
3819
|
+
);
|
|
3820
|
+
logger.debug({ customerId }, "visitor views folded into the customer");
|
|
3821
|
+
}
|
|
3822
|
+
};
|
|
3823
|
+
}
|
|
3824
|
+
|
|
3825
|
+
// src/services/alert-service.ts
|
|
3826
|
+
import { v7 as uuidv713 } from "uuid";
|
|
3827
|
+
import {
|
|
3828
|
+
EVT_ALERT_CONFIRMED,
|
|
3829
|
+
EVT_ALERT_REPEATED,
|
|
3830
|
+
EVT_ALERT_REQUESTED,
|
|
3831
|
+
EVT_ALERT_SENT,
|
|
3832
|
+
EVT_ALERT_UNSUBSCRIBED,
|
|
3833
|
+
HttpError as HttpError3
|
|
3834
|
+
} from "@nymbalhq/types";
|
|
3835
|
+
|
|
3836
|
+
// src/email-address.ts
|
|
3837
|
+
function normaliseEmail(value) {
|
|
3838
|
+
return value.trim().toLowerCase();
|
|
3839
|
+
}
|
|
3840
|
+
|
|
3841
|
+
// src/services/alert-token.ts
|
|
3842
|
+
import { randomBytes as randomBytes2 } from "crypto";
|
|
3843
|
+
function newAlertToken() {
|
|
3844
|
+
return randomBytes2(32).toString("base64url");
|
|
3845
|
+
}
|
|
3846
|
+
|
|
3847
|
+
// src/services/alert-service.ts
|
|
3848
|
+
var CONFIRMABLE = ["pending", "active"];
|
|
3849
|
+
var UNSUBSCRIBABLE = ["pending", "active", "fired"];
|
|
3850
|
+
function linkInvalid() {
|
|
3851
|
+
return new HttpError3(404, "This link is not valid or no longer applies", {
|
|
3852
|
+
code: "alerts.link_invalid"
|
|
3853
|
+
});
|
|
3854
|
+
}
|
|
3855
|
+
function createAlertService(deps) {
|
|
3856
|
+
const { store, repos, publisher } = deps;
|
|
3857
|
+
const origins = new Set(deps.allowedOrigins.filter((origin) => origin !== "*"));
|
|
3858
|
+
return {
|
|
3859
|
+
async subscribe({ email, variantId, kind, origin }) {
|
|
3860
|
+
return store.transaction(async (tx) => {
|
|
3861
|
+
audit.note("alert.subscribe", [{ type: "variant", id: variantId }]);
|
|
3862
|
+
if (!deps.delivers()) {
|
|
3863
|
+
throw new HttpError3(409, "This store does not send email alerts", {
|
|
3864
|
+
code: "alerts.unavailable"
|
|
3865
|
+
});
|
|
3866
|
+
}
|
|
3867
|
+
if (origin === void 0 || !origins.has(origin)) {
|
|
3868
|
+
throw new HttpError3(
|
|
3869
|
+
400,
|
|
3870
|
+
"The request does not come from one of the store\u2019s storefronts",
|
|
3871
|
+
{
|
|
3872
|
+
code: "alerts.origin_not_allowed"
|
|
3873
|
+
}
|
|
3874
|
+
);
|
|
3875
|
+
}
|
|
3876
|
+
const variant = await repos.variant.findById(tx, variantId);
|
|
3877
|
+
if (variant === null) {
|
|
3878
|
+
throw new HttpError3(404, `Variant ${variantId} not found`, {
|
|
3879
|
+
code: "alerts.variant_not_found"
|
|
3880
|
+
});
|
|
3881
|
+
}
|
|
3882
|
+
const row = await repos.alertSubscription.upsertPending(tx, {
|
|
3883
|
+
id: uuidv713(),
|
|
3884
|
+
email: normaliseEmail(email),
|
|
3885
|
+
kind,
|
|
3886
|
+
variantId,
|
|
3887
|
+
productId: variant.productId,
|
|
3888
|
+
confirmToken: newAlertToken(),
|
|
3889
|
+
unsubscribeToken: newAlertToken(),
|
|
3890
|
+
origin,
|
|
3891
|
+
baselinePriceMinor: kind === "price_drop" ? variant.priceMinor : null,
|
|
3892
|
+
at: /* @__PURE__ */ new Date()
|
|
3893
|
+
});
|
|
3894
|
+
await publisher.publish(
|
|
3895
|
+
row.status === "pending" ? EVT_ALERT_REQUESTED : EVT_ALERT_REPEATED,
|
|
3896
|
+
{
|
|
3897
|
+
subscriptionId: row.id,
|
|
3898
|
+
kind,
|
|
3899
|
+
variantId,
|
|
3900
|
+
productId: variant.productId
|
|
3901
|
+
}
|
|
3902
|
+
);
|
|
3903
|
+
return { status: "pending" };
|
|
3904
|
+
});
|
|
3905
|
+
},
|
|
3906
|
+
async confirm(token) {
|
|
3907
|
+
return store.transaction(async (tx) => {
|
|
3908
|
+
audit.note("alert.confirm");
|
|
3909
|
+
const row = await repos.alertSubscription.findByConfirmToken(tx, token);
|
|
3910
|
+
const product = row === null ? null : await repos.product.findById(tx, row.productId);
|
|
3911
|
+
if (row === null || product === null || !CONFIRMABLE.includes(row.status)) {
|
|
3912
|
+
throw linkInvalid();
|
|
3913
|
+
}
|
|
3914
|
+
audit.note("alert.confirm", [{ type: "alert", id: row.id }]);
|
|
3915
|
+
if (row.status === "pending") {
|
|
3916
|
+
const now = /* @__PURE__ */ new Date();
|
|
3917
|
+
await repos.alertSubscription.update(
|
|
3918
|
+
tx,
|
|
3919
|
+
row.id,
|
|
3920
|
+
{ status: "active", updatedAt: now, confirmedAt: now },
|
|
3921
|
+
["pending"]
|
|
3922
|
+
);
|
|
3923
|
+
await publisher.publish(EVT_ALERT_CONFIRMED, { subscriptionId: row.id });
|
|
3924
|
+
}
|
|
3925
|
+
return {
|
|
3926
|
+
status: "active",
|
|
3927
|
+
kind: row.kind,
|
|
3928
|
+
product: { name: product.name, slug: product.slug }
|
|
3929
|
+
};
|
|
3930
|
+
});
|
|
3931
|
+
},
|
|
3932
|
+
async unsubscribe(token) {
|
|
3933
|
+
return store.transaction(async (tx) => {
|
|
3934
|
+
audit.note("alert.unsubscribe");
|
|
3935
|
+
const row = await repos.alertSubscription.findByUnsubscribeToken(tx, token);
|
|
3936
|
+
if (row === null) throw linkInvalid();
|
|
3937
|
+
audit.note("alert.unsubscribe", [{ type: "alert", id: row.id }]);
|
|
3938
|
+
if (row.status !== "unsubscribed") {
|
|
3939
|
+
await repos.alertSubscription.update(
|
|
3940
|
+
tx,
|
|
3941
|
+
row.id,
|
|
3942
|
+
{ status: "unsubscribed", updatedAt: /* @__PURE__ */ new Date() },
|
|
3943
|
+
UNSUBSCRIBABLE
|
|
3944
|
+
);
|
|
3945
|
+
await publisher.publish(EVT_ALERT_UNSUBSCRIBED, { subscriptionId: row.id });
|
|
3946
|
+
}
|
|
3947
|
+
return { status: "unsubscribed" };
|
|
3948
|
+
});
|
|
3949
|
+
},
|
|
3950
|
+
async recordSent(tx, subscription, trigger) {
|
|
3951
|
+
const updatedAt = /* @__PURE__ */ new Date();
|
|
3952
|
+
await repos.alertSubscription.update(
|
|
3953
|
+
tx,
|
|
3954
|
+
subscription.id,
|
|
3955
|
+
subscription.kind === "price_drop" ? {
|
|
3956
|
+
status: "active",
|
|
3957
|
+
baselinePriceMinor: trigger.payload.priceMinor,
|
|
3958
|
+
updatedAt
|
|
3959
|
+
} : { status: "fired", updatedAt },
|
|
3960
|
+
["active"]
|
|
3961
|
+
);
|
|
3962
|
+
await publisher.publish(EVT_ALERT_SENT, {
|
|
3963
|
+
subscriptionId: subscription.id,
|
|
3964
|
+
kind: subscription.kind,
|
|
3965
|
+
triggerEventId: trigger.id
|
|
3966
|
+
});
|
|
3967
|
+
}
|
|
3968
|
+
};
|
|
3969
|
+
}
|
|
3970
|
+
|
|
3971
|
+
// src/services/index.ts
|
|
3972
|
+
function emailDelivers(email) {
|
|
3973
|
+
return email.providerName !== "native";
|
|
3974
|
+
}
|
|
3975
|
+
function buildServices(deps) {
|
|
3976
|
+
const { config, store, repos, publisher, logger, payments, searchAdapter, email, jwtSecret } = deps;
|
|
3977
|
+
const inventory = createInventoryService({
|
|
3978
|
+
store,
|
|
3979
|
+
repos,
|
|
3980
|
+
publisher,
|
|
3981
|
+
logger: logger.child({ service: "inventory" })
|
|
3982
|
+
});
|
|
3983
|
+
const orders = createOrderService({
|
|
3984
|
+
store,
|
|
3985
|
+
repos,
|
|
3986
|
+
publisher,
|
|
3987
|
+
logger: logger.child({ service: "order" }),
|
|
3988
|
+
orderNumberPrefix: config.commerce.orders.numberPrefix,
|
|
3989
|
+
orderNumberStart: config.commerce.orders.numberStart
|
|
3990
|
+
});
|
|
3991
|
+
const cart = createCartService({
|
|
3992
|
+
store,
|
|
3993
|
+
carts: repos.cart,
|
|
3994
|
+
publisher,
|
|
3995
|
+
logger: logger.child({ service: "cart" }),
|
|
3996
|
+
currency: config.store.currency
|
|
3997
|
+
});
|
|
3998
|
+
const checkout = createCheckoutService({
|
|
3999
|
+
store,
|
|
4000
|
+
repos,
|
|
4001
|
+
publisher,
|
|
4002
|
+
logger: logger.child({ service: "checkout" }),
|
|
4003
|
+
cart,
|
|
4004
|
+
orders,
|
|
4005
|
+
inventory,
|
|
4006
|
+
payments,
|
|
4007
|
+
currency: config.store.currency,
|
|
4008
|
+
keyLifetimeMs: parseDurationToMs(config.commerce.orders.keyLifetime.checkout)
|
|
4009
|
+
});
|
|
4010
|
+
return {
|
|
4011
|
+
product: createProductService({
|
|
4012
|
+
store,
|
|
4013
|
+
repos,
|
|
4014
|
+
publisher,
|
|
4015
|
+
logger: logger.child({ service: "product" }),
|
|
4016
|
+
currency: config.store.currency
|
|
4017
|
+
}),
|
|
4018
|
+
category: createCategoryService({
|
|
4019
|
+
repos,
|
|
4020
|
+
publisher,
|
|
4021
|
+
logger: logger.child({ service: "category" })
|
|
4022
|
+
}),
|
|
4023
|
+
cart,
|
|
4024
|
+
customer: createCustomerService({
|
|
4025
|
+
repos,
|
|
4026
|
+
publisher,
|
|
4027
|
+
logger: logger.child({ service: "customer" })
|
|
4028
|
+
}),
|
|
4029
|
+
auth: createAuthService({
|
|
4030
|
+
repos,
|
|
4031
|
+
publisher,
|
|
4032
|
+
logger: logger.child({ service: "auth" }),
|
|
4033
|
+
jwtSecret,
|
|
4034
|
+
accessTtl: config.security.auth.accessTtl,
|
|
4035
|
+
refreshTtl: config.security.auth.refreshTtl
|
|
4036
|
+
}),
|
|
4037
|
+
order: orders,
|
|
4038
|
+
inventory,
|
|
4039
|
+
checkout,
|
|
4040
|
+
refund: createRefundService({
|
|
4041
|
+
store,
|
|
4042
|
+
repos,
|
|
4043
|
+
publisher,
|
|
4044
|
+
logger: logger.child({ service: "refund" }),
|
|
4045
|
+
payments
|
|
4046
|
+
}),
|
|
4047
|
+
search: createSearchService({
|
|
4048
|
+
adapter: searchAdapter,
|
|
4049
|
+
logger: logger.child({ service: "search" })
|
|
4050
|
+
}),
|
|
4051
|
+
recentlyViewed: createRecentlyViewedService({
|
|
4052
|
+
store,
|
|
4053
|
+
repos,
|
|
4054
|
+
publisher,
|
|
4055
|
+
logger: logger.child({ service: "recently-viewed" })
|
|
4056
|
+
}),
|
|
4057
|
+
alert: createAlertService({
|
|
4058
|
+
store,
|
|
4059
|
+
repos,
|
|
4060
|
+
publisher,
|
|
4061
|
+
allowedOrigins: config.http.cors.allowedOrigins,
|
|
4062
|
+
delivers: () => emailDelivers(email)
|
|
4063
|
+
})
|
|
4064
|
+
};
|
|
4065
|
+
}
|
|
4066
|
+
|
|
4067
|
+
// src/routes/capabilities.ts
|
|
4068
|
+
function storeCapabilities(adapters) {
|
|
4069
|
+
const client = adapters.payments.client?.() ?? null;
|
|
4070
|
+
return {
|
|
4071
|
+
payments: {
|
|
4072
|
+
capabilities: [...adapters.payments.capabilities()],
|
|
4073
|
+
client: client === null ? null : { driver: client.driver, options: { ...client.options } }
|
|
4074
|
+
},
|
|
4075
|
+
search: { capabilities: [...adapters.search.capabilities()] },
|
|
4076
|
+
// The document store runs the listing's sort, so these are the catalogue's keys, not the search adapter's.
|
|
4077
|
+
catalog: { sortKeys: [...PRODUCT_SORT_KEYS], defaultSort: DEFAULT_PRODUCT_SORT2 },
|
|
4078
|
+
email: { delivers: emailDelivers(adapters.email) }
|
|
4079
|
+
};
|
|
4080
|
+
}
|
|
4081
|
+
function registerCapabilitiesRoute(adapter, adapters) {
|
|
4082
|
+
adapter.registerRoute("GET", "/api/capabilities", async () => {
|
|
4083
|
+
try {
|
|
4084
|
+
return ok(storeCapabilities(adapters));
|
|
4085
|
+
} catch (err) {
|
|
4086
|
+
return renderError(err);
|
|
4087
|
+
}
|
|
4088
|
+
});
|
|
1233
4089
|
}
|
|
1234
4090
|
|
|
1235
4091
|
// src/routes/categories.ts
|
|
@@ -1378,7 +4234,8 @@ function registerCheckoutRoutes(adapter, checkout) {
|
|
|
1378
4234
|
currency: result.currency,
|
|
1379
4235
|
totalMinor: result.totalMinor,
|
|
1380
4236
|
orderStatus: result.orderStatus,
|
|
1381
|
-
payment: result.payment
|
|
4237
|
+
payment: result.payment,
|
|
4238
|
+
...result.orderKey !== void 0 && { orderKey: result.orderKey }
|
|
1382
4239
|
});
|
|
1383
4240
|
} catch (err) {
|
|
1384
4241
|
return renderError(err);
|
|
@@ -1388,11 +4245,13 @@ function registerCheckoutRoutes(adapter, checkout) {
|
|
|
1388
4245
|
|
|
1389
4246
|
// src/routes/orders.ts
|
|
1390
4247
|
import {
|
|
1391
|
-
NotFoundError as
|
|
4248
|
+
NotFoundError as NotFoundError11,
|
|
4249
|
+
ORDER_EMAIL_HEADER,
|
|
4250
|
+
ORDER_KEY_HEADER
|
|
1392
4251
|
} from "@nymbalhq/types";
|
|
1393
4252
|
|
|
1394
4253
|
// src/routes/role-middleware.ts
|
|
1395
|
-
import { AuthError as
|
|
4254
|
+
import { AuthError as AuthError4 } from "@nymbalhq/types";
|
|
1396
4255
|
function requireAuth(handler) {
|
|
1397
4256
|
return (ctx) => {
|
|
1398
4257
|
if (!ctx.auth?.userId) {
|
|
@@ -1414,6 +4273,45 @@ function requireRole(role, handler) {
|
|
|
1414
4273
|
}
|
|
1415
4274
|
|
|
1416
4275
|
// src/routes/orders.ts
|
|
4276
|
+
function keyedOrder(doc) {
|
|
4277
|
+
const { phone: _phone, company: _company, ...shippingAddress } = doc.shippingAddress;
|
|
4278
|
+
return {
|
|
4279
|
+
orderNumber: doc.orderNumber,
|
|
4280
|
+
status: doc.status,
|
|
4281
|
+
timeline: doc.timeline,
|
|
4282
|
+
lineItems: doc.lineItems,
|
|
4283
|
+
subtotalMinor: doc.subtotalMinor,
|
|
4284
|
+
taxTotalMinor: doc.taxTotalMinor,
|
|
4285
|
+
shippingTotalMinor: doc.shippingTotalMinor,
|
|
4286
|
+
discountTotalMinor: doc.discountTotalMinor,
|
|
4287
|
+
totalMinor: doc.totalMinor,
|
|
4288
|
+
currency: doc.currency,
|
|
4289
|
+
createdAt: doc.createdAt,
|
|
4290
|
+
shippingAddress
|
|
4291
|
+
};
|
|
4292
|
+
}
|
|
4293
|
+
function ownerOrder(doc) {
|
|
4294
|
+
return {
|
|
4295
|
+
id: doc.id,
|
|
4296
|
+
orderNumber: doc.orderNumber,
|
|
4297
|
+
status: doc.status,
|
|
4298
|
+
timeline: doc.timeline,
|
|
4299
|
+
lineItems: doc.lineItems,
|
|
4300
|
+
subtotalMinor: doc.subtotalMinor,
|
|
4301
|
+
taxTotalMinor: doc.taxTotalMinor,
|
|
4302
|
+
shippingTotalMinor: doc.shippingTotalMinor,
|
|
4303
|
+
discountTotalMinor: doc.discountTotalMinor,
|
|
4304
|
+
totalMinor: doc.totalMinor,
|
|
4305
|
+
refundedMinor: doc.refundedMinor,
|
|
4306
|
+
currency: doc.currency,
|
|
4307
|
+
email: doc.email,
|
|
4308
|
+
billingAddress: doc.billingAddress,
|
|
4309
|
+
shippingAddress: doc.shippingAddress,
|
|
4310
|
+
createdAt: doc.createdAt,
|
|
4311
|
+
updatedAt: doc.updatedAt
|
|
4312
|
+
};
|
|
4313
|
+
}
|
|
4314
|
+
var LINK_ANSWER = { sent: "if-matched" };
|
|
1417
4315
|
function registerOrderRoutes(adapter, orders, documentStore) {
|
|
1418
4316
|
adapter.registerRoute(
|
|
1419
4317
|
"GET",
|
|
@@ -1425,25 +4323,52 @@ function registerOrderRoutes(adapter, orders, documentStore) {
|
|
|
1425
4323
|
partitionKey: { field: "partitionKey", value: `customer:${customerId}` },
|
|
1426
4324
|
limit: 50
|
|
1427
4325
|
});
|
|
1428
|
-
return ok(result.items, { nextCursor: result.nextCursor });
|
|
4326
|
+
return ok(result.items.map(ownerOrder), { nextCursor: result.nextCursor });
|
|
1429
4327
|
} catch (err) {
|
|
1430
4328
|
return renderError(err);
|
|
1431
4329
|
}
|
|
1432
4330
|
})
|
|
1433
4331
|
);
|
|
1434
|
-
|
|
4332
|
+
async function readOrder(ctx) {
|
|
1435
4333
|
try {
|
|
1436
4334
|
const orderNumber = ctx.params.orderNumber;
|
|
1437
4335
|
if (!orderNumber) return fail("orders.invalid", "orderNumber required", 400);
|
|
1438
4336
|
const doc = await documentStore.get("orders", orderNumber);
|
|
1439
|
-
if (!doc) throw new
|
|
1440
|
-
|
|
1441
|
-
|
|
1442
|
-
|
|
1443
|
-
|
|
4337
|
+
if (!doc) throw new NotFoundError11("order", orderNumber);
|
|
4338
|
+
const userId = ctx.auth?.userId;
|
|
4339
|
+
if (doc.customerId !== null && userId !== void 0 && doc.customerId === userId) {
|
|
4340
|
+
return ok(ownerOrder(doc));
|
|
4341
|
+
}
|
|
4342
|
+
const key = ctx.headers[ORDER_KEY_HEADER];
|
|
4343
|
+
const state = typeof key === "string" ? await orders.keyState(doc.id, key) : "none";
|
|
4344
|
+
if (state === "open") return ok(keyedOrder(doc));
|
|
4345
|
+
if (state === "expired") {
|
|
4346
|
+
const email = ctx.headers[ORDER_EMAIL_HEADER];
|
|
4347
|
+
if (email === void 0) {
|
|
4348
|
+
return fail(
|
|
4349
|
+
"orders.key_expired",
|
|
4350
|
+
"This order link has expired: give the order's email to open it",
|
|
4351
|
+
404
|
|
4352
|
+
);
|
|
4353
|
+
}
|
|
4354
|
+
if (typeof email === "string" && orderEmailMatches(doc.email, email)) {
|
|
4355
|
+
return ok(keyedOrder(doc));
|
|
1444
4356
|
}
|
|
1445
4357
|
}
|
|
1446
|
-
|
|
4358
|
+
throw new NotFoundError11("order", orderNumber);
|
|
4359
|
+
} catch (err) {
|
|
4360
|
+
return renderError(err);
|
|
4361
|
+
}
|
|
4362
|
+
}
|
|
4363
|
+
adapter.registerRoute("GET", "/api/orders/:orderNumber", async (ctx) => ({
|
|
4364
|
+
...await readOrder(ctx),
|
|
4365
|
+
headers: { "Cache-Control": "no-store" }
|
|
4366
|
+
}));
|
|
4367
|
+
adapter.registerRoute("POST", "/api/orders/link", async (ctx) => {
|
|
4368
|
+
try {
|
|
4369
|
+
const { orderNumber, email } = ctx.body;
|
|
4370
|
+
await orders.requestLink(orderNumber, email);
|
|
4371
|
+
return ok(LINK_ANSWER, void 0, 202);
|
|
1447
4372
|
} catch (err) {
|
|
1448
4373
|
return renderError(err);
|
|
1449
4374
|
}
|
|
@@ -1618,214 +4543,9 @@ function registerAdminDashboardRoute(adapter, deps) {
|
|
|
1618
4543
|
|
|
1619
4544
|
// src/routes/admin-orders.ts
|
|
1620
4545
|
import {
|
|
1621
|
-
OrderConflictError as
|
|
4546
|
+
OrderConflictError as OrderConflictError5,
|
|
1622
4547
|
canTransitionOrder as canTransitionOrder2
|
|
1623
|
-
} from "@nymbalhq/types";
|
|
1624
|
-
|
|
1625
|
-
// src/services/refund-service.ts
|
|
1626
|
-
import { v7 as uuidv73 } from "uuid";
|
|
1627
|
-
import {
|
|
1628
|
-
EVT_ORDER_PARTIALLY_REFUNDED,
|
|
1629
|
-
EVT_ORDER_REFUNDED,
|
|
1630
|
-
EVT_PAYMENT_REFUNDED,
|
|
1631
|
-
NotFoundError as NotFoundError4,
|
|
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 };
|
|
1667
|
-
}
|
|
1668
|
-
async function refreshRefunded(repos, tx, orderId, at) {
|
|
1669
|
-
const refunds = await repos.orderRefund.listByOrder(tx, orderId);
|
|
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 };
|
|
1673
|
-
}
|
|
1674
|
-
function createRefundService(deps) {
|
|
1675
|
-
const { store, repos, publisher, logger, payments } = deps;
|
|
1676
|
-
async function hold2(tx, input) {
|
|
1677
|
-
audit.note("order.refund", [{ type: "order", id: input.orderId }]);
|
|
1678
|
-
const order = await repos.order.lock(tx, input.orderId);
|
|
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 };
|
|
1731
|
-
}
|
|
1732
|
-
const context2 = { orderId: order.id, refundId: row.id, amountMinor: row.amountMinor };
|
|
1733
|
-
try {
|
|
1734
|
-
const answer = await payments.refund(
|
|
1735
|
-
order.paymentIntentId,
|
|
1736
|
-
row.amountMinor,
|
|
1737
|
-
PROVIDER_REFUND_REASON,
|
|
1738
|
-
{ idempotencyKey: row.id, currency: order.currency }
|
|
1739
|
-
);
|
|
1740
|
-
const settlement = settlementOf(answer, row);
|
|
1741
|
-
if (settlement.mismatch) {
|
|
1742
|
-
logger.error(
|
|
1743
|
-
{ ...context2, answer: { amountMinor: answer.amountMinor, currency: answer.currency } },
|
|
1744
|
-
"provider refund answer differs from the refund; left pending"
|
|
1745
|
-
);
|
|
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
|
-
}
|
|
1756
|
-
}
|
|
1757
|
-
async function settle(tx, orderId, row, settlement) {
|
|
1758
|
-
const order = await repos.order.lock(tx, orderId);
|
|
1759
|
-
if (!order) throw new NotFoundError4("order", orderId);
|
|
1760
|
-
await repos.orderRefund.settle(tx, row.id, {
|
|
1761
|
-
status: settlement.status,
|
|
1762
|
-
providerRefundId: settlement.providerRefundId
|
|
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
|
-
);
|
|
1784
|
-
}
|
|
1785
|
-
await repos.orderHistory.append(tx, {
|
|
1786
|
-
id: uuidv73(),
|
|
1787
|
-
orderId: order.id,
|
|
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);
|
|
1796
|
-
}
|
|
1797
|
-
const payload = {
|
|
1798
|
-
orderId: order.id,
|
|
1799
|
-
refundId: refund.id,
|
|
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
|
|
1811
|
-
});
|
|
1812
|
-
}
|
|
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
|
-
}
|
|
4548
|
+
} from "@nymbalhq/types";
|
|
1829
4549
|
|
|
1830
4550
|
// src/history/http.ts
|
|
1831
4551
|
var DEFAULT_LIMIT = 50;
|
|
@@ -1838,7 +4558,7 @@ function one(ctx, name) {
|
|
|
1838
4558
|
function atOf(ctx) {
|
|
1839
4559
|
return one(ctx, "at");
|
|
1840
4560
|
}
|
|
1841
|
-
async function answerAsOf(reader, at, resolve2,
|
|
4561
|
+
async function answerAsOf(reader, at, resolve2, notFound3) {
|
|
1842
4562
|
try {
|
|
1843
4563
|
const instant = new Date(at);
|
|
1844
4564
|
if (!ISO_INSTANT.test(at) || Number.isNaN(instant.getTime())) {
|
|
@@ -1849,7 +4569,7 @@ async function answerAsOf(reader, at, resolve2, notFound2) {
|
|
|
1849
4569
|
case "record":
|
|
1850
4570
|
return ok(outcome.read);
|
|
1851
4571
|
case "not_found":
|
|
1852
|
-
return
|
|
4572
|
+
return notFound3();
|
|
1853
4573
|
case "deleted":
|
|
1854
4574
|
return fail("history.deleted", `Deleted at ${outcome.deletedAt}`, 410, {
|
|
1855
4575
|
deletedAt: outcome.deletedAt
|
|
@@ -1866,7 +4586,7 @@ async function answerAsOf(reader, at, resolve2, notFound2) {
|
|
|
1866
4586
|
return renderError(err);
|
|
1867
4587
|
}
|
|
1868
4588
|
}
|
|
1869
|
-
async function answerHistory(reader, ctx, resolve2,
|
|
4589
|
+
async function answerHistory(reader, ctx, resolve2, notFound3) {
|
|
1870
4590
|
try {
|
|
1871
4591
|
const limitRaw = one(ctx, "limit");
|
|
1872
4592
|
const limit = limitRaw === void 0 || limitRaw === "" ? DEFAULT_LIMIT : Number(limitRaw);
|
|
@@ -1881,7 +4601,7 @@ async function answerHistory(reader, ctx, resolve2, notFound2) {
|
|
|
1881
4601
|
limit: Math.min(limit, MAX_LIMIT),
|
|
1882
4602
|
...cursor !== void 0 && cursor !== "" && { beforeSeq: Number(cursor) }
|
|
1883
4603
|
});
|
|
1884
|
-
return page === null ?
|
|
4604
|
+
return page === null ? notFound3() : ok(page);
|
|
1885
4605
|
} catch (err) {
|
|
1886
4606
|
return renderError(err);
|
|
1887
4607
|
}
|
|
@@ -1919,7 +4639,7 @@ function registerAdminOrdersRoutes(adapter, deps) {
|
|
|
1919
4639
|
const found = await store.read((tx) => findOrder(tx, idOrNumber));
|
|
1920
4640
|
return { kind: "order", id: found?.id ?? idOrNumber, live: found !== null };
|
|
1921
4641
|
}
|
|
1922
|
-
const
|
|
4642
|
+
const notFound3 = (idOrNumber) => () => fail("orders.not_found", `Order not found: ${idOrNumber}`, 404);
|
|
1923
4643
|
adapter.registerRoute(
|
|
1924
4644
|
"GET",
|
|
1925
4645
|
"/api/admin/orders",
|
|
@@ -1978,7 +4698,7 @@ function registerAdminOrdersRoutes(adapter, deps) {
|
|
|
1978
4698
|
if (!orderNumber) return fail("admin.invalid", "orderNumber required", 400);
|
|
1979
4699
|
const at = atOf(ctx);
|
|
1980
4700
|
if (at !== void 0) {
|
|
1981
|
-
return answerAsOf(history, at, () => historySubject(orderNumber),
|
|
4701
|
+
return answerAsOf(history, at, () => historySubject(orderNumber), notFound3(orderNumber));
|
|
1982
4702
|
}
|
|
1983
4703
|
const detail = await store.read(async (tx) => {
|
|
1984
4704
|
const found = await repos.order.findByOrderNumber(tx, orderNumber);
|
|
@@ -2002,7 +4722,7 @@ function registerAdminOrdersRoutes(adapter, deps) {
|
|
|
2002
4722
|
if (!id2) return fail("admin.invalid", "id required", 400);
|
|
2003
4723
|
const current = await order.getById(id2);
|
|
2004
4724
|
if (canTransitionOrder2(current.status, "confirmed") && current.capturedMinor === 0) {
|
|
2005
|
-
throw new
|
|
4725
|
+
throw new OrderConflictError5(
|
|
2006
4726
|
"order.unpaid",
|
|
2007
4727
|
`Order ${current.orderNumber} is unpaid: record its payment to confirm it`
|
|
2008
4728
|
);
|
|
@@ -2125,7 +4845,7 @@ function registerAdminOrdersRoutes(adapter, deps) {
|
|
|
2125
4845
|
requireRole("admin", async (ctx) => {
|
|
2126
4846
|
const id2 = ctx.params.id;
|
|
2127
4847
|
if (!id2) return fail("admin.invalid", "id required", 400);
|
|
2128
|
-
return answerHistory(history, ctx, () => historySubject(id2),
|
|
4848
|
+
return answerHistory(history, ctx, () => historySubject(id2), notFound3(id2));
|
|
2129
4849
|
})
|
|
2130
4850
|
);
|
|
2131
4851
|
adapter.registerRoute(
|
|
@@ -2200,7 +4920,8 @@ function registerAdminOrdersRoutes(adapter, deps) {
|
|
|
2200
4920
|
try {
|
|
2201
4921
|
const id2 = ctx.params.id;
|
|
2202
4922
|
if (!id2) return fail("admin.invalid", "id required", 400);
|
|
2203
|
-
|
|
4923
|
+
const queued = await order.resendConfirmation(id2);
|
|
4924
|
+
return ok({ orderId: queued.id, orderNumber: queued.orderNumber, email: queued.email });
|
|
2204
4925
|
} catch (err) {
|
|
2205
4926
|
return renderError(err);
|
|
2206
4927
|
}
|
|
@@ -2210,13 +4931,13 @@ function registerAdminOrdersRoutes(adapter, deps) {
|
|
|
2210
4931
|
|
|
2211
4932
|
// src/routes/admin-products.ts
|
|
2212
4933
|
import {
|
|
2213
|
-
NotFoundError as
|
|
4934
|
+
NotFoundError as NotFoundError12
|
|
2214
4935
|
} from "@nymbalhq/types";
|
|
2215
4936
|
async function orNull(found) {
|
|
2216
4937
|
try {
|
|
2217
4938
|
return await found;
|
|
2218
4939
|
} catch (err) {
|
|
2219
|
-
if (err instanceof
|
|
4940
|
+
if (err instanceof NotFoundError12) return null;
|
|
2220
4941
|
throw err;
|
|
2221
4942
|
}
|
|
2222
4943
|
}
|
|
@@ -2229,7 +4950,7 @@ function registerAdminProductsRoutes(adapter, deps) {
|
|
|
2229
4950
|
const live = await findProduct(idOrSlug);
|
|
2230
4951
|
return { kind: "product", id: live?.id ?? idOrSlug, live: live !== null };
|
|
2231
4952
|
}
|
|
2232
|
-
const
|
|
4953
|
+
const notFound3 = (idOrSlug) => () => fail("not_found", `product not found: ${idOrSlug}`, 404);
|
|
2233
4954
|
adapter.registerRoute(
|
|
2234
4955
|
"GET",
|
|
2235
4956
|
"/api/admin/products",
|
|
@@ -2280,10 +5001,10 @@ function registerAdminProductsRoutes(adapter, deps) {
|
|
|
2280
5001
|
if (!idOrSlug) return fail("admin.invalid", "id required", 400);
|
|
2281
5002
|
const at = atOf(ctx);
|
|
2282
5003
|
if (at !== void 0) {
|
|
2283
|
-
return answerAsOf(history, at, () => historySubject(idOrSlug),
|
|
5004
|
+
return answerAsOf(history, at, () => historySubject(idOrSlug), notFound3(idOrSlug));
|
|
2284
5005
|
}
|
|
2285
5006
|
const found = await findProduct(idOrSlug);
|
|
2286
|
-
return found === null ?
|
|
5007
|
+
return found === null ? notFound3(idOrSlug)() : ok(found);
|
|
2287
5008
|
} catch (err) {
|
|
2288
5009
|
return renderError(err);
|
|
2289
5010
|
}
|
|
@@ -2295,7 +5016,7 @@ function registerAdminProductsRoutes(adapter, deps) {
|
|
|
2295
5016
|
requireRole("admin", async (ctx) => {
|
|
2296
5017
|
const idOrSlug = ctx.params.id;
|
|
2297
5018
|
if (!idOrSlug) return fail("admin.invalid", "id required", 400);
|
|
2298
|
-
return answerHistory(history, ctx, () => historySubject(idOrSlug),
|
|
5019
|
+
return answerHistory(history, ctx, () => historySubject(idOrSlug), notFound3(idOrSlug));
|
|
2299
5020
|
})
|
|
2300
5021
|
);
|
|
2301
5022
|
adapter.registerRoute(
|
|
@@ -2555,6 +5276,7 @@ function registerAdminInventoryRoutes(adapter, deps) {
|
|
|
2555
5276
|
}
|
|
2556
5277
|
|
|
2557
5278
|
// src/routes/admin-customers.ts
|
|
5279
|
+
import { NotFoundError as NotFoundError13 } from "@nymbalhq/types";
|
|
2558
5280
|
function computeStats(orders) {
|
|
2559
5281
|
if (orders.length === 0) {
|
|
2560
5282
|
return {
|
|
@@ -2591,7 +5313,7 @@ function registerAdminCustomersRoutes(adapter, deps) {
|
|
|
2591
5313
|
const found = await store.read((tx) => repos.customer.findById(tx, id2));
|
|
2592
5314
|
return { kind: "customer", id: id2, live: found !== null };
|
|
2593
5315
|
}
|
|
2594
|
-
const
|
|
5316
|
+
const notFound3 = (id2) => () => fail("customers.not_found", `Customer not found: ${id2}`, 404);
|
|
2595
5317
|
adapter.registerRoute(
|
|
2596
5318
|
"GET",
|
|
2597
5319
|
"/api/admin/customers",
|
|
@@ -2643,7 +5365,7 @@ function registerAdminCustomersRoutes(adapter, deps) {
|
|
|
2643
5365
|
const id2 = ctx.params.id;
|
|
2644
5366
|
if (!id2) return fail("admin.invalid", "id required", 400);
|
|
2645
5367
|
const at = atOf(ctx);
|
|
2646
|
-
if (at !== void 0) return answerAsOf(history, at, () => historySubject(id2),
|
|
5368
|
+
if (at !== void 0) return answerAsOf(history, at, () => historySubject(id2), notFound3(id2));
|
|
2647
5369
|
const found = await store.read(async (tx) => {
|
|
2648
5370
|
const raw = await repos.customer.findById(tx, id2);
|
|
2649
5371
|
return raw ? { raw, orders: await repos.order.listByCustomer(tx, id2) } : null;
|
|
@@ -2664,7 +5386,7 @@ function registerAdminCustomersRoutes(adapter, deps) {
|
|
|
2664
5386
|
requireRole("admin", async (ctx) => {
|
|
2665
5387
|
const id2 = ctx.params.id;
|
|
2666
5388
|
if (!id2) return fail("admin.invalid", "id required", 400);
|
|
2667
|
-
return answerHistory(history, ctx, () => historySubject(id2),
|
|
5389
|
+
return answerHistory(history, ctx, () => historySubject(id2), notFound3(id2));
|
|
2668
5390
|
})
|
|
2669
5391
|
);
|
|
2670
5392
|
adapter.registerRoute(
|
|
@@ -2697,22 +5419,12 @@ function registerAdminCustomersRoutes(adapter, deps) {
|
|
|
2697
5419
|
actor: `admin:${ctx.auth.userId}`,
|
|
2698
5420
|
at: (/* @__PURE__ */ new Date()).toISOString()
|
|
2699
5421
|
};
|
|
2700
|
-
|
|
2701
|
-
|
|
2702
|
-
|
|
2703
|
-
|
|
2704
|
-
|
|
2705
|
-
|
|
2706
|
-
...raw.metadata,
|
|
2707
|
-
adminNotes: [...existingNotes, newNote]
|
|
2708
|
-
};
|
|
2709
|
-
await repos.customer.update(tx, id2, {
|
|
2710
|
-
metadata: updatedMeta,
|
|
2711
|
-
updatedAt: /* @__PURE__ */ new Date()
|
|
2712
|
-
});
|
|
2713
|
-
return true;
|
|
2714
|
-
});
|
|
2715
|
-
if (!noted) return fail("customers.not_found", `Customer not found: ${id2}`, 404);
|
|
5422
|
+
try {
|
|
5423
|
+
await deps.customer.addNote(id2, newNote);
|
|
5424
|
+
} catch (err) {
|
|
5425
|
+
if (err instanceof NotFoundError13) return notFound3(id2)();
|
|
5426
|
+
throw err;
|
|
5427
|
+
}
|
|
2716
5428
|
return ok({ note: newNote });
|
|
2717
5429
|
} catch (err) {
|
|
2718
5430
|
return renderError(err);
|
|
@@ -2815,7 +5527,7 @@ import {
|
|
|
2815
5527
|
} from "@nymbalhq/types";
|
|
2816
5528
|
|
|
2817
5529
|
// src/settings/crypto.ts
|
|
2818
|
-
import { createCipheriv, createDecipheriv, createHash as
|
|
5530
|
+
import { createCipheriv, createDecipheriv, createHash as createHash4, randomBytes as randomBytes3 } from "crypto";
|
|
2819
5531
|
var ALGORITHM = "aes-256-gcm";
|
|
2820
5532
|
var IV_BYTES = 12;
|
|
2821
5533
|
var TAG_BYTES = 16;
|
|
@@ -2823,7 +5535,7 @@ var KEY_BYTES = 32;
|
|
|
2823
5535
|
var SECRETS_KEY_ENV = "NYMBAL_SECRETS_KEY";
|
|
2824
5536
|
var SECRETS_KEY_OLD_ENV = "NYMBAL_SECRETS_KEY_OLD";
|
|
2825
5537
|
function encrypt(key, aad, plaintext) {
|
|
2826
|
-
const iv =
|
|
5538
|
+
const iv = randomBytes3(IV_BYTES);
|
|
2827
5539
|
const cipher = createCipheriv(ALGORITHM, key, iv, { authTagLength: TAG_BYTES });
|
|
2828
5540
|
cipher.setAAD(Buffer.from(aad, "utf8"));
|
|
2829
5541
|
const ciphertext = Buffer.concat([cipher.update(plaintext, "utf8"), cipher.final()]);
|
|
@@ -2843,7 +5555,7 @@ function decrypt(key, aad, row) {
|
|
|
2843
5555
|
);
|
|
2844
5556
|
}
|
|
2845
5557
|
function keyId(key) {
|
|
2846
|
-
return
|
|
5558
|
+
return createHash4("sha256").update(key).digest("hex").slice(0, 8);
|
|
2847
5559
|
}
|
|
2848
5560
|
var BASE64_32 = /^[A-Za-z0-9+/]{43}=?$/;
|
|
2849
5561
|
function readSecretsKey(env, name = SECRETS_KEY_ENV) {
|
|
@@ -2864,26 +5576,39 @@ function settingAad(slot, path) {
|
|
|
2864
5576
|
// src/settings/load.ts
|
|
2865
5577
|
import { ConfigError as ConfigError4 } from "@nymbalhq/types";
|
|
2866
5578
|
|
|
2867
|
-
// src/adapters/
|
|
2868
|
-
import { existsSync } from "fs";
|
|
2869
|
-
import { join as join2 } from "path";
|
|
5579
|
+
// src/adapters/resolve.ts
|
|
5580
|
+
import { existsSync, readFileSync, realpathSync } from "fs";
|
|
5581
|
+
import { dirname, join as join2 } from "path";
|
|
5582
|
+
import { fileURLToPath, pathToFileURL } from "url";
|
|
5583
|
+
import {
|
|
5584
|
+
ADAPTER_CATALOGUE,
|
|
5585
|
+
BUILT_IN,
|
|
5586
|
+
conventionPackage,
|
|
5587
|
+
slotFolder,
|
|
5588
|
+
suggestProvider
|
|
5589
|
+
} from "@nymbalhq/config";
|
|
2870
5590
|
import {
|
|
2871
5591
|
ConfigError as ConfigError2
|
|
2872
5592
|
} from "@nymbalhq/types";
|
|
2873
|
-
|
|
2874
|
-
|
|
2875
|
-
|
|
2876
|
-
|
|
2877
|
-
|
|
2878
|
-
|
|
2879
|
-
|
|
2880
|
-
}
|
|
2881
|
-
|
|
2882
|
-
|
|
2883
|
-
}
|
|
2884
|
-
|
|
2885
|
-
|
|
2886
|
-
|
|
5593
|
+
import { resolve as resolveFrom } from "import-meta-resolve";
|
|
5594
|
+
function catalogued(slot, provider) {
|
|
5595
|
+
const entries = ADAPTER_CATALOGUE[slot];
|
|
5596
|
+
return Object.hasOwn(entries, provider) ? entries[provider] : void 0;
|
|
5597
|
+
}
|
|
5598
|
+
function resolveChoice(slot, choice) {
|
|
5599
|
+
if (choice.provider === "custom") return { kind: "custom" };
|
|
5600
|
+
if (BUILT_IN[slot].includes(choice.provider)) return { kind: "built-in" };
|
|
5601
|
+
if (choice.package !== void 0) {
|
|
5602
|
+
return { kind: "package", package: choice.package, named: "package" };
|
|
5603
|
+
}
|
|
5604
|
+
const sdk = catalogued(slot, choice.provider)?.sdk;
|
|
5605
|
+
return {
|
|
5606
|
+
kind: "package",
|
|
5607
|
+
package: conventionPackage(slot, choice.provider),
|
|
5608
|
+
named: "convention",
|
|
5609
|
+
...sdk !== void 0 && { sdk }
|
|
5610
|
+
};
|
|
5611
|
+
}
|
|
2887
5612
|
var INFRASTRUCTURE_SLOTS = /* @__PURE__ */ new Set(["documentStore", "eventBus", "media"]);
|
|
2888
5613
|
function choiceOf(slot, provider) {
|
|
2889
5614
|
if (slot === "security") return `security.adapter '${provider}'`;
|
|
@@ -2913,6 +5638,14 @@ function packageManager(env, cwd) {
|
|
|
2913
5638
|
function installLine(packages, env, cwd) {
|
|
2914
5639
|
return [INSTALL_VERBS[packageManager(env, cwd)], ...packages].join(" ");
|
|
2915
5640
|
}
|
|
5641
|
+
var DEDUPE_LINES = {
|
|
5642
|
+
npm: "npm dedupe",
|
|
5643
|
+
pnpm: "pnpm dedupe",
|
|
5644
|
+
yarn: "yarn dedupe",
|
|
5645
|
+
bun: "bun install --force"
|
|
5646
|
+
};
|
|
5647
|
+
var TYPES = "@nymbalhq/types";
|
|
5648
|
+
var TYPES_DUPLICATE = "adapter.types_duplicate";
|
|
2916
5649
|
function packageOf(specifier) {
|
|
2917
5650
|
const parts = specifier.split("/");
|
|
2918
5651
|
return specifier.startsWith("@") ? parts.slice(0, 2).join("/") : parts[0];
|
|
@@ -2920,48 +5653,164 @@ function packageOf(specifier) {
|
|
|
2920
5653
|
function missingPackage(error) {
|
|
2921
5654
|
if (error?.code !== "ERR_MODULE_NOT_FOUND") return null;
|
|
2922
5655
|
const match = /Cannot find (?:package|module) '([^']+)'/.exec(String(error.message));
|
|
2923
|
-
|
|
5656
|
+
const specifier = match?.[1];
|
|
5657
|
+
if (specifier === void 0 || /^(?:[/.]|file:)/.test(specifier)) return null;
|
|
5658
|
+
return packageOf(specifier);
|
|
2924
5659
|
}
|
|
2925
5660
|
function isSetting(value) {
|
|
2926
5661
|
const s = value;
|
|
2927
5662
|
return typeof s === "object" && s !== null && typeof s.path === "string" && s.path !== "" && typeof s.label === "string" && typeof s.secret === "boolean" && (s.env === void 0 || typeof s.env === "string");
|
|
2928
5663
|
}
|
|
2929
|
-
|
|
2930
|
-
|
|
2931
|
-
|
|
2932
|
-
|
|
5664
|
+
var shown = (value) => typeof value === "string" ? `'${value}'` : value === void 0 ? "missing" : String(value);
|
|
5665
|
+
function checkAdapterModule(mod, slot, provider, pkg) {
|
|
5666
|
+
const m = typeof mod === "object" && mod !== null ? mod : {};
|
|
5667
|
+
const context2 = { slot, provider, package: pkg };
|
|
5668
|
+
if (typeof m["createAdapter"] !== "function") {
|
|
5669
|
+
throw new ConfigError2(
|
|
5670
|
+
`${pkg} exports no createAdapter(ctx) function (its createAdapter export is ${typeof m["createAdapter"]})`,
|
|
5671
|
+
{ code: "adapter.package_invalid", context: { ...context2, export: "createAdapter" } }
|
|
5672
|
+
);
|
|
5673
|
+
}
|
|
5674
|
+
if (m["slot"] !== slot) {
|
|
5675
|
+
throw new ConfigError2(
|
|
5676
|
+
`${pkg} is loaded for the '${slot}' slot, but its slot export is ${shown(m["slot"])}: it must export slot = '${slot}'`,
|
|
5677
|
+
{
|
|
5678
|
+
code: "adapter.wrong_slot",
|
|
5679
|
+
context: { ...context2, export: "slot", expected: slot, actual: m["slot"] }
|
|
5680
|
+
}
|
|
5681
|
+
);
|
|
5682
|
+
}
|
|
5683
|
+
if (provider !== "custom" && m["provider"] !== provider) {
|
|
5684
|
+
throw new ConfigError2(
|
|
5685
|
+
`${pkg} is loaded for ${choiceOf(slot, provider)}, but its provider export is ${shown(m["provider"])}: it must export provider = '${provider}'`,
|
|
5686
|
+
{
|
|
5687
|
+
code: "adapter.package_invalid",
|
|
5688
|
+
context: { ...context2, export: "provider", expected: provider, actual: m["provider"] }
|
|
5689
|
+
}
|
|
5690
|
+
);
|
|
5691
|
+
}
|
|
5692
|
+
const settings3 = m["settings"];
|
|
5693
|
+
if (settings3 !== void 0 && !(Array.isArray(settings3) && settings3.every(isSetting))) {
|
|
5694
|
+
throw new ConfigError2(
|
|
5695
|
+
`${pkg} exports \`settings\` that is not an array of { path, label, secret, env? }`,
|
|
5696
|
+
{ code: "adapter.package_invalid", context: { ...context2, export: "settings" } }
|
|
5697
|
+
);
|
|
5698
|
+
}
|
|
5699
|
+
return m;
|
|
5700
|
+
}
|
|
5701
|
+
function importFailure(slot, provider, resolution, error, env) {
|
|
5702
|
+
if (error instanceof ConfigError2 && error.code === TYPES_DUPLICATE) {
|
|
5703
|
+
return typesDuplicate(slot, provider, resolution.package, error, env);
|
|
5704
|
+
}
|
|
5705
|
+
const missing = missingPackage(error);
|
|
5706
|
+
if (missing === null) return error;
|
|
5707
|
+
const pkg = resolution.package;
|
|
5708
|
+
const context2 = { slot, provider, package: pkg };
|
|
5709
|
+
if (resolution.named === "convention" && missing === pkg && catalogued(slot, provider) === void 0) {
|
|
5710
|
+
const suggestion = suggestProvider(slot, provider);
|
|
5711
|
+
const unknown = `unknown ${slot === "security" ? "security adapter" : `${slotFolder(slot)} provider`} '${provider}'`;
|
|
5712
|
+
return new ConfigError2(
|
|
5713
|
+
suggestion === void 0 ? `${unknown}: no first-party adapter is named that; a third-party adapter is named with \`package:\`` : `${unknown}; did you mean '${suggestion}'?`,
|
|
5714
|
+
{
|
|
5715
|
+
code: "adapter.provider_unknown",
|
|
5716
|
+
cause: error,
|
|
5717
|
+
context: { ...context2, ...suggestion !== void 0 && { suggestion } }
|
|
5718
|
+
}
|
|
5719
|
+
);
|
|
5720
|
+
}
|
|
5721
|
+
const own = missing === pkg || missing === resolution.sdk;
|
|
5722
|
+
const packages = own ? [pkg, ...resolution.sdk === void 0 ? [] : [resolution.sdk]] : [missing];
|
|
5723
|
+
const install = installLine(packages, env, process.cwd());
|
|
5724
|
+
return new ConfigError2(
|
|
5725
|
+
own ? `${choiceOf(slot, provider)} needs ${pkg}: ${install}` : `${choiceOf(slot, provider)} needs ${missing}, which ${pkg} imports: ${install}`,
|
|
5726
|
+
{ code: "adapter.package_missing", cause: error, context: { ...context2, missing, install } }
|
|
5727
|
+
);
|
|
5728
|
+
}
|
|
5729
|
+
function typesCopyAt(entryUrl) {
|
|
5730
|
+
const entry = realpathSync(fileURLToPath(entryUrl));
|
|
5731
|
+
for (let dir = dirname(entry); dirname(dir) !== dir; dir = dirname(dir)) {
|
|
5732
|
+
const path = join2(dir, "package.json");
|
|
5733
|
+
if (!existsSync(path)) continue;
|
|
5734
|
+
const manifest = JSON.parse(readFileSync(path, "utf8"));
|
|
5735
|
+
if (manifest.name === TYPES) return { dir, version: String(manifest.version) };
|
|
5736
|
+
}
|
|
5737
|
+
throw new Error(`${entry} lies in no ${TYPES} package`);
|
|
5738
|
+
}
|
|
5739
|
+
var kernelCopies = /* @__PURE__ */ new Map();
|
|
5740
|
+
function sameTypesCopy(adapterUrl, kernelUrl) {
|
|
5741
|
+
let kernel = kernelCopies.get(kernelUrl);
|
|
5742
|
+
if (kernel === void 0) {
|
|
5743
|
+
kernel = typesCopyAt(resolveFrom(TYPES, kernelUrl));
|
|
5744
|
+
kernelCopies.set(kernelUrl, kernel);
|
|
5745
|
+
}
|
|
5746
|
+
let adapter;
|
|
2933
5747
|
try {
|
|
2934
|
-
|
|
5748
|
+
adapter = typesCopyAt(resolveFrom(TYPES, adapterUrl));
|
|
2935
5749
|
} catch (error) {
|
|
2936
|
-
const
|
|
2937
|
-
if (
|
|
2938
|
-
|
|
2939
|
-
const install = installLine(packages, env, process.cwd());
|
|
2940
|
-
throw new ConfigError2(`${choiceOf(slot, provider)} needs ${entry.package}: ${install}`, {
|
|
2941
|
-
code: "adapter.package_missing",
|
|
2942
|
-
cause: error,
|
|
2943
|
-
context: { slot, provider, missing, install }
|
|
2944
|
-
});
|
|
5750
|
+
const code = error?.code;
|
|
5751
|
+
if (code !== "ERR_MODULE_NOT_FOUND" && code !== "ENOENT") throw error;
|
|
5752
|
+
adapter = null;
|
|
2945
5753
|
}
|
|
2946
|
-
|
|
2947
|
-
|
|
2948
|
-
|
|
2949
|
-
|
|
2950
|
-
|
|
5754
|
+
return {
|
|
5755
|
+
adapterTypes: adapter?.dir ?? null,
|
|
5756
|
+
kernelTypes: kernel.dir,
|
|
5757
|
+
adapterVersion: adapter?.version ?? null,
|
|
5758
|
+
kernelVersion: kernel.version
|
|
5759
|
+
};
|
|
5760
|
+
}
|
|
5761
|
+
function compareVersions(a, b) {
|
|
5762
|
+
const parse = (v) => {
|
|
5763
|
+
const core = v.split(/[-+]/, 1)[0] ?? "";
|
|
5764
|
+
const parts = core.split(".").map((n) => Number.parseInt(n, 10) || 0);
|
|
5765
|
+
return { parts, pre: /^[^+]*-/.test(v) };
|
|
5766
|
+
};
|
|
5767
|
+
const x = parse(a);
|
|
5768
|
+
const y = parse(b);
|
|
5769
|
+
for (let i = 0; i < 3; i++) {
|
|
5770
|
+
const diff = (x.parts[i] ?? 0) - (y.parts[i] ?? 0);
|
|
5771
|
+
if (diff !== 0) return diff;
|
|
2951
5772
|
}
|
|
2952
|
-
|
|
5773
|
+
return Number(y.pre) - Number(x.pre);
|
|
5774
|
+
}
|
|
5775
|
+
function typesDuplicate(slot, provider, pkg, error, env) {
|
|
5776
|
+
const { adapterVersion, kernelVersion } = error.context;
|
|
5777
|
+
const cwd = process.cwd();
|
|
5778
|
+
const dedupe = adapterVersion === kernelVersion;
|
|
5779
|
+
const install = dedupe ? DEDUPE_LINES[packageManager(env, cwd)] : installLine([pkg], env, cwd);
|
|
5780
|
+
const adapterAt = `${pkg} at a version whose ${TYPES} peer range includes ${String(kernelVersion)}`;
|
|
5781
|
+
const remedy = dedupe ? `Run ${install} so both load one copy.` : compareVersions(String(adapterVersion), String(kernelVersion)) < 0 ? `Install ${adapterAt}.` : `Update Nymbal's core (nymbal, @nymbalhq/platform) to a release whose ${TYPES} is at least ${String(adapterVersion)}, or install ${adapterAt}.`;
|
|
5782
|
+
return new ConfigError2(`${error.message} ${remedy}`, {
|
|
5783
|
+
code: TYPES_DUPLICATE,
|
|
5784
|
+
context: { slot, provider, ...error.context, install }
|
|
5785
|
+
});
|
|
5786
|
+
}
|
|
5787
|
+
var projectImport = async (specifier) => {
|
|
5788
|
+
const url = resolveFrom(specifier, pathToFileURL(join2(process.cwd(), "package.json")).href);
|
|
5789
|
+
const copies = sameTypesCopy(url, import.meta.url);
|
|
5790
|
+
if (copies.adapterTypes !== null && copies.adapterTypes !== copies.kernelTypes) {
|
|
2953
5791
|
throw new ConfigError2(
|
|
2954
|
-
`${
|
|
2955
|
-
{ code:
|
|
5792
|
+
`${specifier} loads ${TYPES} ${copies.adapterVersion} from ${copies.adapterTypes}, but the kernel loads ${copies.kernelVersion} from ${copies.kernelTypes}: two copies make errors the adapter throws unrecognisable.`,
|
|
5793
|
+
{ code: TYPES_DUPLICATE, context: { package: specifier, ...copies } }
|
|
2956
5794
|
);
|
|
2957
5795
|
}
|
|
2958
|
-
return
|
|
5796
|
+
return import(url);
|
|
5797
|
+
};
|
|
5798
|
+
async function importAdapterModule(slot, choice, env, importer = projectImport) {
|
|
5799
|
+
const resolution = resolveChoice(slot, choice);
|
|
5800
|
+
if (resolution.kind !== "package") return void 0;
|
|
5801
|
+
let mod;
|
|
5802
|
+
try {
|
|
5803
|
+
mod = await importer(resolution.package);
|
|
5804
|
+
} catch (error) {
|
|
5805
|
+
throw importFailure(slot, choice.provider, resolution, error, env);
|
|
5806
|
+
}
|
|
5807
|
+
return checkAdapterModule(mod, slot, choice.provider, resolution.package);
|
|
2959
5808
|
}
|
|
2960
5809
|
function declaredSettings(mod) {
|
|
2961
5810
|
return mod?.settings ?? [];
|
|
2962
5811
|
}
|
|
2963
|
-
async function loadProviderAdapter(slot,
|
|
2964
|
-
const mod = await
|
|
5812
|
+
async function loadProviderAdapter(slot, choice, ctx) {
|
|
5813
|
+
const mod = await importAdapterModule(slot, choice, ctx.env);
|
|
2965
5814
|
if (mod === void 0) return void 0;
|
|
2966
5815
|
return await mod.createAdapter({ ...ctx, slot });
|
|
2967
5816
|
}
|
|
@@ -3013,16 +5862,16 @@ function createMiddlewareSecurityAdapter(deps) {
|
|
|
3013
5862
|
}
|
|
3014
5863
|
|
|
3015
5864
|
// src/adapters/payments/native-stub.ts
|
|
3016
|
-
import { v7 as
|
|
5865
|
+
import { v7 as uuidv714 } from "uuid";
|
|
3017
5866
|
import {
|
|
3018
|
-
EVT_PAYMENT_CAPTURED,
|
|
3019
|
-
EVT_PAYMENT_FAILED,
|
|
3020
|
-
EVT_PAYMENT_REFUNDED as
|
|
3021
|
-
PaymentError as
|
|
5867
|
+
EVT_PAYMENT_CAPTURED as EVT_PAYMENT_CAPTURED2,
|
|
5868
|
+
EVT_PAYMENT_FAILED as EVT_PAYMENT_FAILED2,
|
|
5869
|
+
EVT_PAYMENT_REFUNDED as EVT_PAYMENT_REFUNDED3,
|
|
5870
|
+
PaymentError as PaymentError3
|
|
3022
5871
|
} from "@nymbalhq/types";
|
|
3023
5872
|
var STUB_ID_PREFIX = "pi_stub_";
|
|
3024
5873
|
function rejected(message) {
|
|
3025
|
-
return new
|
|
5874
|
+
return new PaymentError3("refund_rejected", message);
|
|
3026
5875
|
}
|
|
3027
5876
|
function statusFor(receiptEmail) {
|
|
3028
5877
|
const address2 = receiptEmail ?? "";
|
|
@@ -3052,12 +5901,12 @@ function createNativeStubPaymentsAdapter(deps) {
|
|
|
3052
5901
|
capabilities: () => ["intent", "capture", "refund"],
|
|
3053
5902
|
// Nothing to collect: the receipt email decides the outcome.
|
|
3054
5903
|
client: () => ({ driver: "test-mode", options: {} }),
|
|
3055
|
-
producesEvents: [
|
|
5904
|
+
producesEvents: [EVT_PAYMENT_CAPTURED2, EVT_PAYMENT_FAILED2, EVT_PAYMENT_REFUNDED3],
|
|
3056
5905
|
consumesEvents: [],
|
|
3057
5906
|
initialize: noopInitialize,
|
|
3058
5907
|
healthCheck: () => okHealth("stub \u2014 always healthy"),
|
|
3059
5908
|
async createPaymentIntent(params) {
|
|
3060
|
-
const id2 = `${STUB_ID_PREFIX}${
|
|
5909
|
+
const id2 = `${STUB_ID_PREFIX}${uuidv714()}`;
|
|
3061
5910
|
const intent = {
|
|
3062
5911
|
id: id2,
|
|
3063
5912
|
amountMinor: params.amountMinor,
|
|
@@ -3072,7 +5921,7 @@ function createNativeStubPaymentsAdapter(deps) {
|
|
|
3072
5921
|
},
|
|
3073
5922
|
async capturePayment(intentId) {
|
|
3074
5923
|
const intent = intents.get(intentId);
|
|
3075
|
-
if (!intent) throw new
|
|
5924
|
+
if (!intent) throw new PaymentError3("capture_failed", `unknown intent ${intentId}`);
|
|
3076
5925
|
intent.status = "succeeded";
|
|
3077
5926
|
return {
|
|
3078
5927
|
paymentId: intent.id,
|
|
@@ -3091,7 +5940,7 @@ function createNativeStubPaymentsAdapter(deps) {
|
|
|
3091
5940
|
if (!paymentId.startsWith(STUB_ID_PREFIX)) throw rejected(`${paymentId} is not a stub intent`);
|
|
3092
5941
|
const answer = (amount2, currency) => {
|
|
3093
5942
|
const refund = {
|
|
3094
|
-
refundId: `re_stub_${
|
|
5943
|
+
refundId: `re_stub_${uuidv714()}`,
|
|
3095
5944
|
paymentId,
|
|
3096
5945
|
amountMinor: amount2,
|
|
3097
5946
|
currency,
|
|
@@ -3122,14 +5971,14 @@ function createNativeStubPaymentsAdapter(deps) {
|
|
|
3122
5971
|
},
|
|
3123
5972
|
async getPaymentIntent(intentId) {
|
|
3124
5973
|
const intent = intents.get(intentId);
|
|
3125
|
-
if (!intent) throw new
|
|
5974
|
+
if (!intent) throw new PaymentError3("intent_failed", `unknown intent ${intentId}`);
|
|
3126
5975
|
return toIntent(intent);
|
|
3127
5976
|
},
|
|
3128
5977
|
async cancelPaymentIntent(intentId) {
|
|
3129
5978
|
const intent = intents.get(intentId);
|
|
3130
5979
|
if (!intent) return;
|
|
3131
5980
|
if (intent.status === "succeeded") {
|
|
3132
|
-
throw new
|
|
5981
|
+
throw new PaymentError3("cancel_refused", `intent ${intentId} is already captured`);
|
|
3133
5982
|
}
|
|
3134
5983
|
intent.status = "cancelled";
|
|
3135
5984
|
},
|
|
@@ -3141,14 +5990,14 @@ function createNativeStubPaymentsAdapter(deps) {
|
|
|
3141
5990
|
if (held !== void 0 && event.kind === "payment.captured") held.status = "succeeded";
|
|
3142
5991
|
return {
|
|
3143
5992
|
verified: true,
|
|
3144
|
-
eventId: event.id ?? `evt_stub_${
|
|
5993
|
+
eventId: event.id ?? `evt_stub_${uuidv714()}`,
|
|
3145
5994
|
kind: event.kind ?? "ignored",
|
|
3146
5995
|
...event.paymentIntentId !== void 0 && { paymentIntentId: event.paymentIntentId },
|
|
3147
5996
|
...event.amountMinor !== void 0 && { amountMinor: event.amountMinor },
|
|
3148
5997
|
...event.currency !== void 0 && { currency: event.currency }
|
|
3149
5998
|
};
|
|
3150
5999
|
} catch (err) {
|
|
3151
|
-
throw new
|
|
6000
|
+
throw new PaymentError3("webhook_invalid", "stub webhook body not JSON", { cause: err });
|
|
3152
6001
|
}
|
|
3153
6002
|
}
|
|
3154
6003
|
};
|
|
@@ -3157,9 +6006,9 @@ function createNativeStubPaymentsAdapter(deps) {
|
|
|
3157
6006
|
// src/adapters/email/native-email-adapter.ts
|
|
3158
6007
|
import {
|
|
3159
6008
|
EVT_CART_ABANDONED,
|
|
3160
|
-
EVT_CUSTOMER_CREATED,
|
|
3161
|
-
EVT_ORDER_PLACED,
|
|
3162
|
-
EVT_ORDER_SHIPPED,
|
|
6009
|
+
EVT_CUSTOMER_CREATED as EVT_CUSTOMER_CREATED2,
|
|
6010
|
+
EVT_ORDER_PLACED as EVT_ORDER_PLACED2,
|
|
6011
|
+
EVT_ORDER_SHIPPED as EVT_ORDER_SHIPPED2,
|
|
3163
6012
|
renderEmailTemplate
|
|
3164
6013
|
} from "@nymbalhq/types";
|
|
3165
6014
|
function createNativeEmailAdapter(deps) {
|
|
@@ -3169,7 +6018,7 @@ function createNativeEmailAdapter(deps) {
|
|
|
3169
6018
|
providerName: "native",
|
|
3170
6019
|
capabilities: () => ["transactional", "list-sync"],
|
|
3171
6020
|
producesEvents: [],
|
|
3172
|
-
consumesEvents: [
|
|
6021
|
+
consumesEvents: [EVT_ORDER_PLACED2, EVT_ORDER_SHIPPED2, EVT_CUSTOMER_CREATED2, EVT_CART_ABANDONED],
|
|
3173
6022
|
async initialize() {
|
|
3174
6023
|
},
|
|
3175
6024
|
healthCheck: () => okHealth("console transport"),
|
|
@@ -3193,10 +6042,10 @@ function createNativeEmailAdapter(deps) {
|
|
|
3193
6042
|
|
|
3194
6043
|
// src/adapters/search/native-adapter.ts
|
|
3195
6044
|
import {
|
|
3196
|
-
EVT_PRODUCT_CREATED,
|
|
3197
|
-
EVT_PRODUCT_DELETED,
|
|
3198
|
-
EVT_PRODUCT_UPDATED,
|
|
3199
|
-
ValidationError as
|
|
6045
|
+
EVT_PRODUCT_CREATED as EVT_PRODUCT_CREATED2,
|
|
6046
|
+
EVT_PRODUCT_DELETED as EVT_PRODUCT_DELETED2,
|
|
6047
|
+
EVT_PRODUCT_UPDATED as EVT_PRODUCT_UPDATED2,
|
|
6048
|
+
ValidationError as ValidationError10
|
|
3200
6049
|
} from "@nymbalhq/types";
|
|
3201
6050
|
|
|
3202
6051
|
// src/adapters/search/terms.ts
|
|
@@ -3480,7 +6329,7 @@ function decodeSearchCursor(cursor) {
|
|
|
3480
6329
|
const text = Buffer.from(cursor, "base64url").toString("utf8");
|
|
3481
6330
|
const offset = Number(text);
|
|
3482
6331
|
if (!/^\d+$/.test(text) || !Number.isSafeInteger(offset) || encodeSearchCursor(offset) !== cursor) {
|
|
3483
|
-
throw new
|
|
6332
|
+
throw new ValidationError10("malformed search cursor");
|
|
3484
6333
|
}
|
|
3485
6334
|
return offset;
|
|
3486
6335
|
}
|
|
@@ -3505,7 +6354,7 @@ function createNativeSearchAdapter(deps) {
|
|
|
3505
6354
|
providerName: "native",
|
|
3506
6355
|
capabilities: () => ["index", "search", "facet"],
|
|
3507
6356
|
producesEvents: [],
|
|
3508
|
-
consumesEvents: [
|
|
6357
|
+
consumesEvents: [EVT_PRODUCT_CREATED2, EVT_PRODUCT_UPDATED2, EVT_PRODUCT_DELETED2],
|
|
3509
6358
|
initialize: noopInitialize,
|
|
3510
6359
|
healthCheck: () => okHealth(),
|
|
3511
6360
|
async index(documents) {
|
|
@@ -3554,10 +6403,10 @@ function createNativeSearchAdapter(deps) {
|
|
|
3554
6403
|
}
|
|
3555
6404
|
|
|
3556
6405
|
// src/adapters/reviews/native-adapter.ts
|
|
3557
|
-
import { v7 as
|
|
6406
|
+
import { v7 as uuidv715 } from "uuid";
|
|
3558
6407
|
import {
|
|
3559
|
-
EVT_ORDER_DELIVERED,
|
|
3560
|
-
ValidationError as
|
|
6408
|
+
EVT_ORDER_DELIVERED as EVT_ORDER_DELIVERED2,
|
|
6409
|
+
ValidationError as ValidationError11
|
|
3561
6410
|
} from "@nymbalhq/types";
|
|
3562
6411
|
function encodeReviewCursor(review) {
|
|
3563
6412
|
return Buffer.from(JSON.stringify([review.submittedAt, review.id]), "utf8").toString("base64url");
|
|
@@ -3567,10 +6416,10 @@ function decodeReviewCursor(cursor) {
|
|
|
3567
6416
|
try {
|
|
3568
6417
|
key = JSON.parse(Buffer.from(cursor, "base64url").toString("utf8"));
|
|
3569
6418
|
} catch (err) {
|
|
3570
|
-
throw new
|
|
6419
|
+
throw new ValidationError11("malformed reviews cursor", { cause: err });
|
|
3571
6420
|
}
|
|
3572
6421
|
if (!Array.isArray(key) || key.length !== 2 || typeof key[0] !== "string" || typeof key[1] !== "string" || Number.isNaN(Date.parse(key[0])) || Buffer.from(JSON.stringify(key), "utf8").toString("base64url") !== cursor) {
|
|
3573
|
-
throw new
|
|
6422
|
+
throw new ValidationError11("malformed reviews cursor");
|
|
3574
6423
|
}
|
|
3575
6424
|
return { submittedAt: key[0], id: key[1] };
|
|
3576
6425
|
}
|
|
@@ -3581,7 +6430,7 @@ function createNativeReviewsAdapter(deps) {
|
|
|
3581
6430
|
providerName: "native",
|
|
3582
6431
|
capabilities: () => ["submit", "moderate", "aggregate"],
|
|
3583
6432
|
producesEvents: [],
|
|
3584
|
-
consumesEvents: [
|
|
6433
|
+
consumesEvents: [EVT_ORDER_DELIVERED2],
|
|
3585
6434
|
initialize: noopInitialize,
|
|
3586
6435
|
healthCheck: () => okHealth(),
|
|
3587
6436
|
async getProductReviews(productId, params) {
|
|
@@ -3602,7 +6451,7 @@ function createNativeReviewsAdapter(deps) {
|
|
|
3602
6451
|
return { productId, ...agg };
|
|
3603
6452
|
},
|
|
3604
6453
|
async submitReview(submission) {
|
|
3605
|
-
const id2 =
|
|
6454
|
+
const id2 = uuidv715();
|
|
3606
6455
|
const now = /* @__PURE__ */ new Date();
|
|
3607
6456
|
const review = await repos.review.store.transaction(async (tx) => {
|
|
3608
6457
|
await repos.review.insert(tx, {
|
|
@@ -3709,11 +6558,16 @@ function createNativeTaxAdapter(logger, defaultRate = 0) {
|
|
|
3709
6558
|
}
|
|
3710
6559
|
|
|
3711
6560
|
// src/adapters/not-configured.ts
|
|
3712
|
-
import { AdapterError as
|
|
6561
|
+
import { AdapterError as AdapterError3 } from "@nymbalhq/types";
|
|
6562
|
+
var NOT_CONFIGURED = /* @__PURE__ */ Symbol.for("nymbal.adapter.notConfigured");
|
|
6563
|
+
function isNotConfigured(subject) {
|
|
6564
|
+
return typeof subject === "object" && subject !== null && subject[NOT_CONFIGURED] === true;
|
|
6565
|
+
}
|
|
3713
6566
|
function createNotConfiguredAdapter(slot, provider, missing) {
|
|
3714
6567
|
const fields = missing.map((path) => `${slot}.${path}`).join(", ");
|
|
3715
6568
|
const detail = `${provider} is not configured: ${fields} not set (in the config, the environment or the admin's Settings)`;
|
|
3716
6569
|
const base = {
|
|
6570
|
+
[NOT_CONFIGURED]: true,
|
|
3717
6571
|
kind: slot,
|
|
3718
6572
|
providerName: provider,
|
|
3719
6573
|
capabilities: () => [],
|
|
@@ -3727,7 +6581,7 @@ function createNotConfiguredAdapter(slot, provider, missing) {
|
|
|
3727
6581
|
...slot === "payments" && { client: () => ({ driver: provider, options: {} }) }
|
|
3728
6582
|
};
|
|
3729
6583
|
const refuse = async () => {
|
|
3730
|
-
throw new
|
|
6584
|
+
throw new AdapterError3("not_configured", detail, { context: { slot, provider, missing } });
|
|
3731
6585
|
};
|
|
3732
6586
|
return new Proxy(base, {
|
|
3733
6587
|
get(target, property, receiver) {
|
|
@@ -3816,7 +6670,7 @@ async function resolveSlot(slot, config, logger, injected, builtIns, settings3)
|
|
|
3816
6670
|
if (block.provider === "custom") {
|
|
3817
6671
|
adapter = injected[slot];
|
|
3818
6672
|
} else {
|
|
3819
|
-
const mod = await
|
|
6673
|
+
const mod = await importAdapterModule(slot, block, process.env);
|
|
3820
6674
|
if (mod !== void 0) {
|
|
3821
6675
|
const declared = declaredSettings(mod);
|
|
3822
6676
|
blockConfig = fillFromSettings(slot, blockConfig, declared, settings3, process.env);
|
|
@@ -3851,22 +6705,26 @@ function resolvePaymentsAdapter(config, logger, injected = {}, settings3 = []) {
|
|
|
3851
6705
|
settings3
|
|
3852
6706
|
);
|
|
3853
6707
|
}
|
|
6708
|
+
function securityChoice(config) {
|
|
6709
|
+
const { adapter, package: pkg } = config.security;
|
|
6710
|
+
return { provider: adapter, ...pkg !== void 0 && { package: pkg } };
|
|
6711
|
+
}
|
|
3854
6712
|
async function resolveSecurityAdapter(config, logger, env = process.env) {
|
|
3855
|
-
const choice = config
|
|
6713
|
+
const choice = securityChoice(config);
|
|
3856
6714
|
const slotLogger = logger.child({ adapter: "security" });
|
|
3857
|
-
if (choice === "
|
|
3858
|
-
|
|
6715
|
+
if (resolveChoice("security", choice).kind === "built-in") {
|
|
6716
|
+
return createMiddlewareSecurityAdapter({ logger: slotLogger });
|
|
6717
|
+
}
|
|
6718
|
+
const blockConfig = choice.provider === "cloudflare" ? { ...config.security.cloudflare } : { ...config.security.config };
|
|
3859
6719
|
const adapter = await loadProviderAdapter("security", choice, {
|
|
3860
6720
|
config: blockConfig,
|
|
3861
6721
|
logger: slotLogger,
|
|
3862
6722
|
env
|
|
3863
6723
|
});
|
|
3864
6724
|
if (adapter === void 0) {
|
|
3865
|
-
|
|
3866
|
-
|
|
3867
|
-
|
|
3868
|
-
{ code: "config.security_adapter_unknown", context: { adapter: choice, known } }
|
|
3869
|
-
);
|
|
6725
|
+
throw new ConfigError3(`security.adapter '${choice.provider}' has no adapter`, {
|
|
6726
|
+
context: { slot: "security", provider: choice.provider }
|
|
6727
|
+
});
|
|
3870
6728
|
}
|
|
3871
6729
|
await adapter.initialize(blockConfig);
|
|
3872
6730
|
return adapter;
|
|
@@ -3980,9 +6838,10 @@ function createSettingsRepository(store) {
|
|
|
3980
6838
|
async function declaredSlots(config, env) {
|
|
3981
6839
|
const out = [];
|
|
3982
6840
|
for (const slot of COMMERCE_SLOTS) {
|
|
3983
|
-
const
|
|
6841
|
+
const block = config.commerce[slot];
|
|
6842
|
+
const provider = block.provider;
|
|
3984
6843
|
if (provider === "custom") continue;
|
|
3985
|
-
const declared = declaredSettings(await
|
|
6844
|
+
const declared = declaredSettings(await importAdapterModule(slot, block, env));
|
|
3986
6845
|
if (declared.length > 0) out.push({ slot, provider, declared });
|
|
3987
6846
|
}
|
|
3988
6847
|
return out;
|
|
@@ -4242,52 +7101,6 @@ import {
|
|
|
4242
7101
|
canTransitionOrder as canTransitionOrder3,
|
|
4243
7102
|
paymentState as paymentState3
|
|
4244
7103
|
} from "@nymbalhq/types";
|
|
4245
|
-
|
|
4246
|
-
// src/history/views.ts
|
|
4247
|
-
import {
|
|
4248
|
-
paymentState as paymentState2
|
|
4249
|
-
} from "@nymbalhq/types";
|
|
4250
|
-
function orderViewOf(order) {
|
|
4251
|
-
const {
|
|
4252
|
-
notes: _notes,
|
|
4253
|
-
metadata: _metadata,
|
|
4254
|
-
updatedAt: _updatedAt,
|
|
4255
|
-
capturedAt: _capturedAt,
|
|
4256
|
-
captureMethod: _captureMethod,
|
|
4257
|
-
...rest
|
|
4258
|
-
} = order;
|
|
4259
|
-
const { payment: _payment, history: _history, ...view } = rest;
|
|
4260
|
-
return {
|
|
4261
|
-
...view,
|
|
4262
|
-
payment: {
|
|
4263
|
-
state: paymentState2(order),
|
|
4264
|
-
capturedMinor: order.capturedMinor,
|
|
4265
|
-
refundedMinor: order.refundedMinor,
|
|
4266
|
-
currency: order.currency
|
|
4267
|
-
}
|
|
4268
|
-
};
|
|
4269
|
-
}
|
|
4270
|
-
function toProductAsOf(snapshot) {
|
|
4271
|
-
return {
|
|
4272
|
-
...snapshot,
|
|
4273
|
-
variants: snapshot.variants.map(({ updatedAt: _updatedAt, ...variant }) => variant),
|
|
4274
|
-
// A set: product.created keeps the order it was sent in, a read the repository's.
|
|
4275
|
-
categoryIds: [...snapshot.categoryIds].sort()
|
|
4276
|
-
};
|
|
4277
|
-
}
|
|
4278
|
-
function toCustomerSnapshot(customer) {
|
|
4279
|
-
return {
|
|
4280
|
-
id: customer.id,
|
|
4281
|
-
email: customer.email,
|
|
4282
|
-
firstName: customer.firstName,
|
|
4283
|
-
lastName: customer.lastName,
|
|
4284
|
-
phone: customer.phone,
|
|
4285
|
-
addresses: customer.addresses,
|
|
4286
|
-
createdAt: customer.createdAt
|
|
4287
|
-
};
|
|
4288
|
-
}
|
|
4289
|
-
|
|
4290
|
-
// src/history/fold.ts
|
|
4291
7104
|
function eventName(type) {
|
|
4292
7105
|
return type.replace(/\.v\d+$/, "");
|
|
4293
7106
|
}
|
|
@@ -4576,14 +7389,14 @@ function createHistoryReader(deps) {
|
|
|
4576
7389
|
});
|
|
4577
7390
|
}
|
|
4578
7391
|
const newest = entries.reverse().filter((e) => page.beforeSeq === void 0 || e.seq < page.beforeSeq);
|
|
4579
|
-
const
|
|
4580
|
-
await actorsOf(tx,
|
|
4581
|
-
const last =
|
|
7392
|
+
const shown2 = newest.slice(0, page.limit);
|
|
7393
|
+
await actorsOf(tx, shown2);
|
|
7394
|
+
const last = shown2[shown2.length - 1];
|
|
4582
7395
|
return {
|
|
4583
7396
|
historyStartsAt: rows[start].createdAt.toISOString(),
|
|
4584
7397
|
retentionDays,
|
|
4585
|
-
entries:
|
|
4586
|
-
nextCursor: newest.length >
|
|
7398
|
+
entries: shown2,
|
|
7399
|
+
nextCursor: newest.length > shown2.length && last !== void 0 ? String(last.seq) : null
|
|
4587
7400
|
};
|
|
4588
7401
|
});
|
|
4589
7402
|
}
|
|
@@ -4617,7 +7430,12 @@ function registerAdminRoutes(adapter, deps) {
|
|
|
4617
7430
|
product: services.product,
|
|
4618
7431
|
repos
|
|
4619
7432
|
});
|
|
4620
|
-
registerAdminCustomersRoutes(adapter, {
|
|
7433
|
+
registerAdminCustomersRoutes(adapter, {
|
|
7434
|
+
order: services.order,
|
|
7435
|
+
customer: services.customer,
|
|
7436
|
+
repos,
|
|
7437
|
+
history
|
|
7438
|
+
});
|
|
4621
7439
|
registerAdminSearchRoute(adapter, {
|
|
4622
7440
|
order: services.order,
|
|
4623
7441
|
product: services.product,
|
|
@@ -4712,7 +7530,7 @@ function registerAdminStaticRoute(adapter, root) {
|
|
|
4712
7530
|
}
|
|
4713
7531
|
|
|
4714
7532
|
// src/routes/events-sse.ts
|
|
4715
|
-
import { createHmac, randomBytes as
|
|
7533
|
+
import { createHmac, randomBytes as randomBytes4 } from "crypto";
|
|
4716
7534
|
import "@nymbalhq/types";
|
|
4717
7535
|
var TICKET_TTL_SECONDS = 60;
|
|
4718
7536
|
var NONCE_COLLECTION = "sse-ticket-nonces";
|
|
@@ -4739,7 +7557,7 @@ function registerEventsSseRoute(adapter, deps) {
|
|
|
4739
7557
|
"/api/admin/events/ticket",
|
|
4740
7558
|
requireRole("admin", (ctx) => {
|
|
4741
7559
|
try {
|
|
4742
|
-
const nonce =
|
|
7560
|
+
const nonce = randomBytes4(12).toString("base64url");
|
|
4743
7561
|
const payload = {
|
|
4744
7562
|
uid: ctx.auth.userId,
|
|
4745
7563
|
roles: ctx.auth.roles ?? ["admin"],
|
|
@@ -4808,35 +7626,74 @@ function registerEventsSseRoute(adapter, deps) {
|
|
|
4808
7626
|
void fail;
|
|
4809
7627
|
}
|
|
4810
7628
|
|
|
4811
|
-
// src/routes/webhooks-
|
|
7629
|
+
// src/routes/webhooks-inbound.ts
|
|
4812
7630
|
import {
|
|
4813
|
-
|
|
4814
|
-
|
|
7631
|
+
ConfigError as ConfigError5,
|
|
7632
|
+
EVT_PAYMENT_FAILED as EVT_PAYMENT_FAILED3,
|
|
7633
|
+
emailFeedbackProblem,
|
|
7634
|
+
shippingTrackingProblem,
|
|
7635
|
+
webhookDeliveryProblem
|
|
4815
7636
|
} from "@nymbalhq/types";
|
|
4816
|
-
|
|
4817
|
-
|
|
4818
|
-
|
|
4819
|
-
const id2 = order?.metadata?.correlationId;
|
|
4820
|
-
return typeof id2 === "string" ? runWithCorrelation(id2, fn) : fn();
|
|
7637
|
+
var PAYMENTS_ALIAS = "stripe";
|
|
7638
|
+
function isHooked(adapter) {
|
|
7639
|
+
return "receiveWebhook" in adapter && typeof adapter.receiveWebhook === "function";
|
|
4821
7640
|
}
|
|
4822
|
-
|
|
4823
|
-
|
|
4824
|
-
|
|
4825
|
-
|
|
4826
|
-
function
|
|
4827
|
-
const
|
|
7641
|
+
var SLOT_WEBHOOK_RULES = {
|
|
7642
|
+
email: emailFeedbackProblem,
|
|
7643
|
+
shipping: shippingTrackingProblem
|
|
7644
|
+
};
|
|
7645
|
+
function webhookTargets(adapters) {
|
|
7646
|
+
const bySlot = /* @__PURE__ */ new Map();
|
|
7647
|
+
const hookless = /* @__PURE__ */ new Map();
|
|
7648
|
+
const add = (name, target) => {
|
|
7649
|
+
const slots = bySlot.get(name) ?? /* @__PURE__ */ new Map();
|
|
7650
|
+
slots.set(target.slot, target);
|
|
7651
|
+
bySlot.set(name, slots);
|
|
7652
|
+
};
|
|
7653
|
+
const payments = { kind: "payments", slot: "payments", adapter: adapters.payments };
|
|
7654
|
+
add(PAYMENTS_ALIAS, payments);
|
|
7655
|
+
add(adapters.payments.providerName, payments);
|
|
7656
|
+
for (const slot of COMMERCE_SLOTS) {
|
|
7657
|
+
const adapter = adapters[slot];
|
|
7658
|
+
if (slot === "payments" || adapter === null) continue;
|
|
7659
|
+
if (isHooked(adapter)) add(adapter.providerName, { kind: "hooked", slot, adapter });
|
|
7660
|
+
else hookless.set(adapter.providerName, [...hookless.get(adapter.providerName) ?? [], slot]);
|
|
7661
|
+
}
|
|
7662
|
+
const hooked = /* @__PURE__ */ new Map();
|
|
7663
|
+
for (const [name, slots] of bySlot) {
|
|
7664
|
+
if (slots.size > 1) {
|
|
7665
|
+
const names = [...slots.keys()];
|
|
7666
|
+
throw new ConfigError5(
|
|
7667
|
+
`webhook provider '${name}' is taken by more than one slot that receives webhooks: ${names.join(" and ")}`,
|
|
7668
|
+
{ code: "config.webhook_provider_ambiguous", context: { name, slots: names } }
|
|
7669
|
+
);
|
|
7670
|
+
}
|
|
7671
|
+
hooked.set(name, [...slots.values()][0]);
|
|
7672
|
+
}
|
|
7673
|
+
return { hooked, hookless };
|
|
7674
|
+
}
|
|
7675
|
+
function isWebhookInvalid(err) {
|
|
7676
|
+
const code = err?.code;
|
|
7677
|
+
return typeof code === "string" && code.endsWith("webhook_invalid");
|
|
7678
|
+
}
|
|
7679
|
+
var invalid = () => fail("webhook.invalid", "signature verification failed", 400);
|
|
7680
|
+
var notFound2 = () => fail("webhook.not_found", "no webhook is received under this name", 404);
|
|
7681
|
+
var noRawBody = () => fail("webhook.raw_body_missing", "the HTTP adapter kept no raw request body", 500);
|
|
7682
|
+
function registerInboundWebhookRoute(adapter, deps) {
|
|
7683
|
+
const { checkout, publisher, store, processedEvents, orders } = deps;
|
|
7684
|
+
const targets = webhookTargets(deps.adapters);
|
|
4828
7685
|
async function publishFailed(tx, paymentIntentId, reason) {
|
|
4829
7686
|
const order = paymentIntentId ? await orders.findByPaymentIntentId(tx, paymentIntentId) : null;
|
|
4830
7687
|
await inOrderScope(
|
|
4831
7688
|
order,
|
|
4832
|
-
() => publisher.publish(
|
|
7689
|
+
() => publisher.publish(EVT_PAYMENT_FAILED3, {
|
|
4833
7690
|
paymentId: paymentIntentId,
|
|
4834
7691
|
orderId: order?.id ?? "",
|
|
4835
7692
|
reason
|
|
4836
7693
|
})
|
|
4837
7694
|
);
|
|
4838
7695
|
}
|
|
4839
|
-
async function
|
|
7696
|
+
async function handlePayment(tx, result) {
|
|
4840
7697
|
if (result.kind === "payment.captured") {
|
|
4841
7698
|
const paymentIntentId = result.paymentIntentId ?? "";
|
|
4842
7699
|
if (paymentIntentId === "" || typeof result.amountMinor !== "number" || typeof result.currency !== "string" || result.currency === "") {
|
|
@@ -4855,49 +7712,101 @@ function registerStripeWebhookRoute(adapter, deps) {
|
|
|
4855
7712
|
}
|
|
4856
7713
|
return ok({ ignored: true });
|
|
4857
7714
|
}
|
|
7715
|
+
async function receivePayment(ctx, name, payments) {
|
|
7716
|
+
const rawSig = ctx.headers["stripe-signature"];
|
|
7717
|
+
const sig = Array.isArray(rawSig) ? rawSig[0] : rawSig;
|
|
7718
|
+
if (!sig) return fail("webhook.signature_missing", "stripe-signature header missing", 400);
|
|
7719
|
+
if (ctx.rawBody === void 0) return noRawBody();
|
|
7720
|
+
let result;
|
|
7721
|
+
try {
|
|
7722
|
+
result = await payments.parseWebhook(ctx.rawBody, sig);
|
|
7723
|
+
} catch (err) {
|
|
7724
|
+
if (isWebhookInvalid(err)) return invalid();
|
|
7725
|
+
throw err;
|
|
7726
|
+
}
|
|
7727
|
+
if (!result.verified) return invalid();
|
|
7728
|
+
return store.transaction(async (tx) => {
|
|
7729
|
+
if (!await processedEvents.claim(tx, `webhook:${name}`, result.eventId, /* @__PURE__ */ new Date())) {
|
|
7730
|
+
return ok({ deduped: true });
|
|
7731
|
+
}
|
|
7732
|
+
return handlePayment(tx, result);
|
|
7733
|
+
});
|
|
7734
|
+
}
|
|
7735
|
+
async function receiveHooked(ctx, name, target) {
|
|
7736
|
+
if (ctx.rawBody === void 0) return noRawBody();
|
|
7737
|
+
let delivery;
|
|
7738
|
+
try {
|
|
7739
|
+
delivery = await target.adapter.receiveWebhook(ctx.rawBody, ctx.headers);
|
|
7740
|
+
} catch (err) {
|
|
7741
|
+
if (isWebhookInvalid(err)) return invalid();
|
|
7742
|
+
throw err;
|
|
7743
|
+
}
|
|
7744
|
+
if (!delivery.verified) return invalid();
|
|
7745
|
+
const problem = webhookDeliveryProblem(
|
|
7746
|
+
target.adapter.providerName,
|
|
7747
|
+
target.adapter.producesEvents,
|
|
7748
|
+
delivery
|
|
7749
|
+
) ?? SLOT_WEBHOOK_RULES[target.slot]?.(target.adapter.providerName, delivery) ?? null;
|
|
7750
|
+
if (problem !== null) {
|
|
7751
|
+
ctx.logger.warn(
|
|
7752
|
+
{ webhook: name, slot: target.slot, type: problem.type, reason: problem.reason },
|
|
7753
|
+
"a webhook delivery was refused: its events break the adapter event rule"
|
|
7754
|
+
);
|
|
7755
|
+
return fail(
|
|
7756
|
+
"webhook.event_invalid",
|
|
7757
|
+
`the delivery's events are refused: ${problem.reason}`,
|
|
7758
|
+
500
|
|
7759
|
+
);
|
|
7760
|
+
}
|
|
7761
|
+
const handler = `webhook:${name}`;
|
|
7762
|
+
return store.transaction(async (tx) => {
|
|
7763
|
+
if (!await processedEvents.claim(tx, handler, delivery.deliveryId, /* @__PURE__ */ new Date())) {
|
|
7764
|
+
return ok({ deduped: true });
|
|
7765
|
+
}
|
|
7766
|
+
audit.note("webhook.receive", [{ type: "webhook", id: `${name}:${delivery.deliveryId}` }]);
|
|
7767
|
+
await publisher.publishUntyped(
|
|
7768
|
+
delivery.events.map(({ type, payload }) => ({ type, payload })),
|
|
7769
|
+
{ source: handler }
|
|
7770
|
+
);
|
|
7771
|
+
return ok({ received: true, events: delivery.events.length });
|
|
7772
|
+
});
|
|
7773
|
+
}
|
|
4858
7774
|
adapter.registerRoute(
|
|
4859
7775
|
"POST",
|
|
4860
|
-
"/api/webhooks
|
|
4861
|
-
|
|
4862
|
-
|
|
4863
|
-
|
|
4864
|
-
|
|
4865
|
-
|
|
4866
|
-
|
|
4867
|
-
|
|
4868
|
-
|
|
4869
|
-
|
|
4870
|
-
|
|
4871
|
-
);
|
|
4872
|
-
}
|
|
4873
|
-
let result;
|
|
4874
|
-
try {
|
|
4875
|
-
result = await payments.parseWebhook(ctx.rawBody, sig);
|
|
4876
|
-
} catch (err) {
|
|
4877
|
-
if (err instanceof PaymentError3 && err.code === "payment.webhook_invalid") {
|
|
4878
|
-
return fail("webhook.invalid", "signature verification failed", 400);
|
|
4879
|
-
}
|
|
4880
|
-
throw err;
|
|
4881
|
-
}
|
|
4882
|
-
if (!result.verified) return fail("webhook.invalid", "signature verification failed", 400);
|
|
4883
|
-
return await store.transaction(async (tx) => {
|
|
4884
|
-
if (await processedEvents.seen(tx, HANDLER, result.eventId))
|
|
4885
|
-
return ok({ deduped: true });
|
|
4886
|
-
const answer = await handle(tx, result);
|
|
4887
|
-
await processedEvents.markProcessed(tx, HANDLER, result.eventId, /* @__PURE__ */ new Date());
|
|
4888
|
-
return answer;
|
|
4889
|
-
});
|
|
4890
|
-
} catch (err) {
|
|
4891
|
-
return renderError(err);
|
|
7776
|
+
"/api/webhooks/:adapter",
|
|
7777
|
+
async (ctx) => {
|
|
7778
|
+
const name = ctx.params["adapter"] ?? "";
|
|
7779
|
+
const target = targets.hooked.get(name);
|
|
7780
|
+
if (target === void 0) {
|
|
7781
|
+
const slots = targets.hookless.get(name);
|
|
7782
|
+
ctx.logger.warn(
|
|
7783
|
+
{ webhook: name, ...slots !== void 0 && { slots } },
|
|
7784
|
+
slots === void 0 ? "a webhook delivery named no provider of this store" : "a webhook delivery named a provider whose adapter takes no webhooks"
|
|
7785
|
+
);
|
|
7786
|
+
return notFound2();
|
|
4892
7787
|
}
|
|
4893
|
-
|
|
7788
|
+
return runAsActor(
|
|
7789
|
+
{ kind: "system", id: `${name}-webhook` },
|
|
7790
|
+
() => auditedRoute(
|
|
7791
|
+
store,
|
|
7792
|
+
target.kind === "payments" ? "payment.finalize" : "webhook.receive",
|
|
7793
|
+
async () => {
|
|
7794
|
+
try {
|
|
7795
|
+
return target.kind === "payments" ? await receivePayment(ctx, name, target.adapter) : await receiveHooked(ctx, name, target);
|
|
7796
|
+
} catch (err) {
|
|
7797
|
+
return renderError(err);
|
|
7798
|
+
}
|
|
7799
|
+
}
|
|
7800
|
+
)
|
|
7801
|
+
);
|
|
7802
|
+
},
|
|
4894
7803
|
{ csrf: false, rawBody: true }
|
|
4895
7804
|
);
|
|
4896
7805
|
}
|
|
4897
7806
|
|
|
4898
7807
|
// src/routes/validated-adapter.ts
|
|
4899
7808
|
import {
|
|
4900
|
-
ConfigError as
|
|
7809
|
+
ConfigError as ConfigError6
|
|
4901
7810
|
} from "@nymbalhq/types";
|
|
4902
7811
|
|
|
4903
7812
|
// src/routes/schemas.ts
|
|
@@ -4946,6 +7855,11 @@ var productVariant = z.object({
|
|
|
4946
7855
|
options: z.array(z.object({ name: z.string(), value: z.string() })),
|
|
4947
7856
|
status: z.enum(["active", "inactive"]).optional()
|
|
4948
7857
|
});
|
|
7858
|
+
var variantPrices = z.object({
|
|
7859
|
+
id,
|
|
7860
|
+
priceMinor: money.min(0),
|
|
7861
|
+
compareAtPriceMinor: money.min(0).nullable().optional()
|
|
7862
|
+
});
|
|
4949
7863
|
var productFields = {
|
|
4950
7864
|
description: z.string().optional(),
|
|
4951
7865
|
shortDescription: z.string().optional(),
|
|
@@ -4994,7 +7908,7 @@ var routeSchemas = {
|
|
|
4994
7908
|
// Store
|
|
4995
7909
|
"GET /api/capabilities": {
|
|
4996
7910
|
name: "capabilities.get",
|
|
4997
|
-
description: "What the store can do, for a storefront: payments client half, search capabilities and
|
|
7911
|
+
description: "What the store can do, for a storefront: payments client half, search capabilities, sort keys and whether email delivers."
|
|
4998
7912
|
},
|
|
4999
7913
|
// Catalogue
|
|
5000
7914
|
"GET /api/categories": {
|
|
@@ -5027,6 +7941,29 @@ var routeSchemas = {
|
|
|
5027
7941
|
params: idParams,
|
|
5028
7942
|
query: z.object({ limit: queryValue, cursor: queryValue })
|
|
5029
7943
|
},
|
|
7944
|
+
// Back-in-stock and price-drop alerts
|
|
7945
|
+
"POST /api/alerts/subscribe": {
|
|
7946
|
+
name: "alerts.subscribe",
|
|
7947
|
+
command: "alert.subscribe",
|
|
7948
|
+
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.",
|
|
7949
|
+
body: z.object({
|
|
7950
|
+
email: z.string().trim().max(254).email(),
|
|
7951
|
+
variantId: id,
|
|
7952
|
+
kind: z.enum(["back_in_stock", "price_drop"])
|
|
7953
|
+
})
|
|
7954
|
+
},
|
|
7955
|
+
"POST /api/alerts/confirm": {
|
|
7956
|
+
name: "alerts.confirm",
|
|
7957
|
+
command: "alert.confirm",
|
|
7958
|
+
description: "Confirm an alert subscription with the token from its confirmation email.",
|
|
7959
|
+
body: z.object({ token: z.string().min(1) })
|
|
7960
|
+
},
|
|
7961
|
+
"POST /api/alerts/unsubscribe": {
|
|
7962
|
+
name: "alerts.unsubscribe",
|
|
7963
|
+
command: "alert.unsubscribe",
|
|
7964
|
+
description: "Stop an alert with the unsubscribe token from any of its emails.",
|
|
7965
|
+
body: z.object({ token: z.string().min(1) })
|
|
7966
|
+
},
|
|
5030
7967
|
// Cart
|
|
5031
7968
|
"GET /api/cart": {
|
|
5032
7969
|
name: "cart.get",
|
|
@@ -5074,9 +8011,29 @@ var routeSchemas = {
|
|
|
5074
8011
|
},
|
|
5075
8012
|
"GET /api/orders/:orderNumber": {
|
|
5076
8013
|
name: "orders.get",
|
|
5077
|
-
description: "Get one order by its number.",
|
|
8014
|
+
description: "Get one order by its number, with a key that opens it in the x-nymbal-order-key header (an expired key with the order's email in x-nymbal-order-email) or as the order's signed-in customer.",
|
|
5078
8015
|
params: orderNumberParams
|
|
5079
8016
|
},
|
|
8017
|
+
"POST /api/orders/link": {
|
|
8018
|
+
name: "orders.requestLink",
|
|
8019
|
+
command: "order.requestLink",
|
|
8020
|
+
description: "Email the order's link again to the order's own email; the answer is the same whether or not the number and email matched an order.",
|
|
8021
|
+
body: z.object({
|
|
8022
|
+
orderNumber: z.string().trim().min(1).max(64),
|
|
8023
|
+
email: z.string().trim().min(1).max(254)
|
|
8024
|
+
})
|
|
8025
|
+
},
|
|
8026
|
+
// Recently viewed: the viewer is the bearer's customer or the visitor cookie's, never one the request names.
|
|
8027
|
+
"POST /api/recently-viewed": {
|
|
8028
|
+
name: "recentlyViewed.record",
|
|
8029
|
+
command: null,
|
|
8030
|
+
description: "Record that the shopper viewed a product.",
|
|
8031
|
+
body: z.object({ productId: id })
|
|
8032
|
+
},
|
|
8033
|
+
"GET /api/recently-viewed": {
|
|
8034
|
+
name: "recentlyViewed.list",
|
|
8035
|
+
description: "List the shopper's recently viewed products, newest first."
|
|
8036
|
+
},
|
|
5080
8037
|
// Customer account
|
|
5081
8038
|
"GET /api/customers/me": {
|
|
5082
8039
|
name: "customers.me",
|
|
@@ -5238,7 +8195,7 @@ var routeSchemas = {
|
|
|
5238
8195
|
},
|
|
5239
8196
|
"POST /api/admin/orders/:id/resend-confirmation": {
|
|
5240
8197
|
name: "admin.orders.resendConfirmation",
|
|
5241
|
-
command:
|
|
8198
|
+
command: "order.resendConfirmation",
|
|
5242
8199
|
description: "Resend an order's confirmation email.",
|
|
5243
8200
|
params: orderIdParams
|
|
5244
8201
|
},
|
|
@@ -5274,9 +8231,13 @@ var routeSchemas = {
|
|
|
5274
8231
|
"PATCH /api/admin/products/:id": {
|
|
5275
8232
|
name: "admin.products.update",
|
|
5276
8233
|
command: "product.update",
|
|
5277
|
-
description: "Update a product's fields.",
|
|
8234
|
+
description: "Update a product's fields and its variants' prices; a variant left out keeps its prices, and stock moves only through inventory.",
|
|
5278
8235
|
params: idParams,
|
|
5279
|
-
body: z.object({
|
|
8236
|
+
body: z.object({
|
|
8237
|
+
name: z.string().optional(),
|
|
8238
|
+
...productFields,
|
|
8239
|
+
variants: z.array(variantPrices).optional()
|
|
8240
|
+
})
|
|
5280
8241
|
},
|
|
5281
8242
|
"DELETE /api/admin/products/:id": {
|
|
5282
8243
|
name: "admin.products.delete",
|
|
@@ -5421,10 +8382,12 @@ var routeSchemas = {
|
|
|
5421
8382
|
query: z.object({ since: queryValue, until: queryValue, correlation: queryValue })
|
|
5422
8383
|
},
|
|
5423
8384
|
// Webhooks
|
|
5424
|
-
"POST /api/webhooks
|
|
5425
|
-
name: "webhooks.
|
|
5426
|
-
command:
|
|
5427
|
-
|
|
8385
|
+
"POST /api/webhooks/:adapter": {
|
|
8386
|
+
name: "webhooks.receive",
|
|
8387
|
+
// The route opens its own audit command: payment.finalize for a payments delivery, webhook.receive otherwise.
|
|
8388
|
+
command: null,
|
|
8389
|
+
description: "Receive a signed delivery from a provider, by its name (stripe always names the payments provider).",
|
|
8390
|
+
params: z.object({ adapter: id }),
|
|
5428
8391
|
// The signature covers the raw bytes, and a malformed event is answered by the handler itself.
|
|
5429
8392
|
body: z.unknown()
|
|
5430
8393
|
},
|
|
@@ -5450,7 +8413,7 @@ function schemaFor(method, path) {
|
|
|
5450
8413
|
const key = `${method} ${path}`;
|
|
5451
8414
|
const schema = routeSchemas[key];
|
|
5452
8415
|
if (!schema) {
|
|
5453
|
-
throw new
|
|
8416
|
+
throw new ConfigError6(`route ${key} has no entry in routeSchemas`, {
|
|
5454
8417
|
code: "config.route_schema_missing",
|
|
5455
8418
|
context: { method, path }
|
|
5456
8419
|
});
|
|
@@ -5486,7 +8449,7 @@ function parseInput(schema, ctx) {
|
|
|
5486
8449
|
}
|
|
5487
8450
|
};
|
|
5488
8451
|
}
|
|
5489
|
-
function
|
|
8452
|
+
function invalid2(issues) {
|
|
5490
8453
|
return fail("validation.failed", "The request input is invalid", 400, { issues });
|
|
5491
8454
|
}
|
|
5492
8455
|
function validatedAdapter(adapter) {
|
|
@@ -5498,7 +8461,7 @@ function validatedAdapter(adapter) {
|
|
|
5498
8461
|
path,
|
|
5499
8462
|
async (ctx) => {
|
|
5500
8463
|
const input = parseInput(schema, ctx);
|
|
5501
|
-
return input.ok ? handler(input.ctx) :
|
|
8464
|
+
return input.ok ? handler(input.ctx) : invalid2(input.issues);
|
|
5502
8465
|
},
|
|
5503
8466
|
options
|
|
5504
8467
|
);
|
|
@@ -5648,6 +8611,47 @@ function registerAdminActivityRoutes(adapter, deps) {
|
|
|
5648
8611
|
);
|
|
5649
8612
|
}
|
|
5650
8613
|
|
|
8614
|
+
// src/routes/alerts.ts
|
|
8615
|
+
function originOf(header) {
|
|
8616
|
+
return Array.isArray(header) ? void 0 : header;
|
|
8617
|
+
}
|
|
8618
|
+
function registerAlertRoutes(adapter, deps) {
|
|
8619
|
+
const { alerts } = deps;
|
|
8620
|
+
adapter.registerRoute("POST", "/api/alerts/subscribe", async (ctx) => {
|
|
8621
|
+
try {
|
|
8622
|
+
const body = ctx.body;
|
|
8623
|
+
const answer = await alerts.subscribe({ ...body, origin: originOf(ctx.headers["origin"]) });
|
|
8624
|
+
return ok(answer, void 0, 202);
|
|
8625
|
+
} catch (err) {
|
|
8626
|
+
return renderError(err);
|
|
8627
|
+
}
|
|
8628
|
+
});
|
|
8629
|
+
adapter.registerRoute(
|
|
8630
|
+
"POST",
|
|
8631
|
+
"/api/alerts/confirm",
|
|
8632
|
+
async (ctx) => {
|
|
8633
|
+
try {
|
|
8634
|
+
return ok(await alerts.confirm(ctx.body.token));
|
|
8635
|
+
} catch (err) {
|
|
8636
|
+
return renderError(err);
|
|
8637
|
+
}
|
|
8638
|
+
},
|
|
8639
|
+
{ csrf: false }
|
|
8640
|
+
);
|
|
8641
|
+
adapter.registerRoute(
|
|
8642
|
+
"POST",
|
|
8643
|
+
"/api/alerts/unsubscribe",
|
|
8644
|
+
async (ctx) => {
|
|
8645
|
+
try {
|
|
8646
|
+
return ok(await alerts.unsubscribe(ctx.body.token));
|
|
8647
|
+
} catch (err) {
|
|
8648
|
+
return renderError(err);
|
|
8649
|
+
}
|
|
8650
|
+
},
|
|
8651
|
+
{ csrf: false }
|
|
8652
|
+
);
|
|
8653
|
+
}
|
|
8654
|
+
|
|
5651
8655
|
// src/routes/register.ts
|
|
5652
8656
|
function correlatedAdapter(adapter) {
|
|
5653
8657
|
return {
|
|
@@ -5678,7 +8682,7 @@ function commandOf(method, path) {
|
|
|
5678
8682
|
if (method === "GET" || schema === void 0) return void 0;
|
|
5679
8683
|
const { command } = schema;
|
|
5680
8684
|
if (command === void 0) {
|
|
5681
|
-
throw new
|
|
8685
|
+
throw new ConfigError7(`route ${method} ${path} declares no audit command in routeSchemas`, {
|
|
5682
8686
|
code: "config.route_command_missing",
|
|
5683
8687
|
context: { method, path }
|
|
5684
8688
|
});
|
|
@@ -5734,7 +8738,8 @@ function registerAllRoutes(deps) {
|
|
|
5734
8738
|
repos.auditEntry.store
|
|
5735
8739
|
);
|
|
5736
8740
|
adapter.registerMiddleware(createAuthMiddleware(services.auth));
|
|
5737
|
-
|
|
8741
|
+
const afterSignIn = [foldViewsOnSignIn(services.recentlyViewed)];
|
|
8742
|
+
registerAuthRoutes(adapter, services.auth, config.security.auth.refreshTtl, afterSignIn);
|
|
5738
8743
|
registerCapabilitiesRoute(adapter, adapters);
|
|
5739
8744
|
registerCategoryRoutes(adapter, documentStore, config.store.name);
|
|
5740
8745
|
registerProductRoutes(
|
|
@@ -5751,7 +8756,14 @@ function registerAllRoutes(deps) {
|
|
|
5751
8756
|
productRepo: repos.product,
|
|
5752
8757
|
variantRepo: repos.variant
|
|
5753
8758
|
});
|
|
8759
|
+
registerRecentlyViewedRoutes(adapter, {
|
|
8760
|
+
recentlyViewed: services.recentlyViewed,
|
|
8761
|
+
documentStore,
|
|
8762
|
+
productRepo: repos.product,
|
|
8763
|
+
retentionDays: config.events.retentionDays
|
|
8764
|
+
});
|
|
5754
8765
|
registerCheckoutRoutes(adapter, services.checkout);
|
|
8766
|
+
registerAlertRoutes(adapter, { alerts: services.alert });
|
|
5755
8767
|
registerOrderRoutes(adapter, services.order, documentStore);
|
|
5756
8768
|
registerCustomerRoutes(adapter, services.customer);
|
|
5757
8769
|
registerAdminRoutes(adapter, {
|
|
@@ -5766,10 +8778,10 @@ function registerAllRoutes(deps) {
|
|
|
5766
8778
|
registerEventsSseRoute(adapter, {
|
|
5767
8779
|
eventBus,
|
|
5768
8780
|
documentStore,
|
|
5769
|
-
ticketSecret:
|
|
8781
|
+
ticketSecret: deps.jwtSecret
|
|
5770
8782
|
});
|
|
5771
|
-
|
|
5772
|
-
|
|
8783
|
+
registerInboundWebhookRoute(adapter, {
|
|
8784
|
+
adapters,
|
|
5773
8785
|
checkout: services.checkout,
|
|
5774
8786
|
publisher,
|
|
5775
8787
|
store: repos.processedEvent.store,
|
|
@@ -5780,9 +8792,11 @@ function registerAllRoutes(deps) {
|
|
|
5780
8792
|
}
|
|
5781
8793
|
|
|
5782
8794
|
export {
|
|
5783
|
-
|
|
8795
|
+
resolveChoice,
|
|
5784
8796
|
installLine,
|
|
5785
|
-
|
|
8797
|
+
missingPackage,
|
|
8798
|
+
checkAdapterModule,
|
|
8799
|
+
importAdapterModule,
|
|
5786
8800
|
declaredSettings,
|
|
5787
8801
|
loadProviderAdapter,
|
|
5788
8802
|
sqliteDb,
|
|
@@ -5797,6 +8811,7 @@ export {
|
|
|
5797
8811
|
listAuditEntries,
|
|
5798
8812
|
auditEntriesInOrder,
|
|
5799
8813
|
createAuditEntryRepository,
|
|
8814
|
+
normaliseEmail,
|
|
5800
8815
|
runWithCorrelation,
|
|
5801
8816
|
currentCorrelationId,
|
|
5802
8817
|
newCorrelationId,
|
|
@@ -5806,30 +8821,37 @@ export {
|
|
|
5806
8821
|
currentActor,
|
|
5807
8822
|
outsideActor,
|
|
5808
8823
|
actorOf,
|
|
8824
|
+
addSecret,
|
|
5809
8825
|
scrub,
|
|
5810
8826
|
scrubbingLogger,
|
|
5811
8827
|
outsideCommand,
|
|
5812
8828
|
audit,
|
|
5813
8829
|
auditedCommand,
|
|
8830
|
+
parseDurationToMs,
|
|
8831
|
+
createAuthService,
|
|
8832
|
+
CATEGORIES,
|
|
8833
|
+
PRODUCTS,
|
|
8834
|
+
PRODUCTS_BY_CATEGORY,
|
|
8835
|
+
ORDERS,
|
|
8836
|
+
ORDERS_BY_CUSTOMER,
|
|
8837
|
+
CUSTOMER_PROFILES,
|
|
8838
|
+
buildCategoryDoc,
|
|
8839
|
+
buildProductDoc,
|
|
8840
|
+
productByCategoryKey,
|
|
8841
|
+
productWrites,
|
|
8842
|
+
buildOrderDoc,
|
|
8843
|
+
orderWrites,
|
|
8844
|
+
buildCustomerProfile,
|
|
8845
|
+
KEY_OF,
|
|
8846
|
+
buildSearchDoc,
|
|
8847
|
+
subscribeDerived,
|
|
8848
|
+
recentlyViewed,
|
|
8849
|
+
registerRecentlyViewedProjection,
|
|
5814
8850
|
formatMoney,
|
|
5815
|
-
|
|
5816
|
-
orderPayment,
|
|
5817
|
-
settlementOf,
|
|
5818
|
-
refreshRefunded,
|
|
5819
|
-
createRefundService,
|
|
5820
|
-
SECRETS_KEY_ENV,
|
|
5821
|
-
SECRETS_KEY_OLD_ENV,
|
|
5822
|
-
encrypt,
|
|
5823
|
-
decrypt,
|
|
5824
|
-
keyId,
|
|
5825
|
-
readSecretsKey,
|
|
5826
|
-
keyProblem,
|
|
5827
|
-
settingAad,
|
|
8851
|
+
mintOrderKey,
|
|
5828
8852
|
CSRF_COOKIE,
|
|
5829
8853
|
CSRF_HEADER,
|
|
5830
8854
|
buildSecurityHeaders,
|
|
5831
|
-
noopInitialize,
|
|
5832
|
-
okHealth,
|
|
5833
8855
|
createMiddlewareSecurityAdapter,
|
|
5834
8856
|
createNativeStubPaymentsAdapter,
|
|
5835
8857
|
createNativeEmailAdapter,
|
|
@@ -5840,22 +8862,50 @@ export {
|
|
|
5840
8862
|
createNativeAnalyticsAdapter,
|
|
5841
8863
|
createNativeShippingAdapter,
|
|
5842
8864
|
createNativeTaxAdapter,
|
|
8865
|
+
isNotConfigured,
|
|
5843
8866
|
fillFromSettings,
|
|
5844
8867
|
COMMERCE_SLOTS,
|
|
5845
8868
|
checkInjectedAdapters,
|
|
5846
8869
|
checkInjectedSlot,
|
|
5847
8870
|
resolvePaymentsAdapter,
|
|
8871
|
+
securityChoice,
|
|
5848
8872
|
resolveSecurityAdapter,
|
|
5849
8873
|
slotBuilders,
|
|
5850
8874
|
buildAdapters,
|
|
8875
|
+
isHooked,
|
|
8876
|
+
createProductService,
|
|
8877
|
+
createCategoryService,
|
|
8878
|
+
createCartService,
|
|
8879
|
+
createCustomerService,
|
|
8880
|
+
createOrderService,
|
|
8881
|
+
createInventoryService,
|
|
8882
|
+
PROVIDER_REFUND_REASON,
|
|
8883
|
+
orderPayment,
|
|
8884
|
+
settlementOf,
|
|
8885
|
+
refreshRefunded,
|
|
8886
|
+
createRefundService,
|
|
8887
|
+
createCheckoutService,
|
|
8888
|
+
createSearchService,
|
|
8889
|
+
createRecentlyViewedService,
|
|
8890
|
+
newAlertToken,
|
|
8891
|
+
createAlertService,
|
|
8892
|
+
emailDelivers,
|
|
8893
|
+
buildServices,
|
|
8894
|
+
SECRETS_KEY_ENV,
|
|
8895
|
+
SECRETS_KEY_OLD_ENV,
|
|
8896
|
+
encrypt,
|
|
8897
|
+
decrypt,
|
|
8898
|
+
keyId,
|
|
8899
|
+
readSecretsKey,
|
|
8900
|
+
keyProblem,
|
|
8901
|
+
settingAad,
|
|
5851
8902
|
isMissingSettingsTable,
|
|
5852
8903
|
listStoredSettings,
|
|
5853
8904
|
settingValues,
|
|
5854
8905
|
loadBootSettings,
|
|
5855
|
-
toCustomerSnapshot,
|
|
5856
8906
|
registerAdminStaticRoute,
|
|
5857
|
-
inOrderScope,
|
|
5858
8907
|
routeSchemas,
|
|
8908
|
+
registerAlertRoutes,
|
|
5859
8909
|
registerAllRoutes
|
|
5860
8910
|
};
|
|
5861
|
-
//# sourceMappingURL=chunk-
|
|
8911
|
+
//# sourceMappingURL=chunk-TRLERRUI.js.map
|