Press n or j to go to the next uncovered block, b, p or k for the previous block.
| 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609 610 611 612 613 614 615 616 617 618 619 620 621 | 5x 5x 5x 1x 1x 57x 18x 26x 26x 13x 13x 13x 13x 13x 13x 3x 25x 25x 5x 1x 1x 5x 19x 19x 19x 19x 19x 19x 19x 19x 19x 19x 19x 19x 19x 19x 19x 19x 19x 19x 19x 19x 19x 19x 19x 19x 19x 19x 19x 19x 19x 19x 13x 13x 13x 13x 13x 13x 13x 13x 13x 13x 13x 13x 13x 13x 13x 13x 13x 13x 13x 13x 13x 13x 13x 13x 13x 19x 19x 67x 17x 19x 16x 1x 20x 14x 7x 14x 7x 7x 14x 5x 5x 5x 5x 5x 3x 2x 3x 3x 3x 2x 3x 3x 8x 8x 8x 8x 8x 8x 1x 7x 4x 6x 6x 6x 6x 8x 1x 6x 1x 1x 1x 8x 7x 4x 4x 10x 10x 10x 10x 10x 10x 10x 10x 10x 1x 1x 10x 10x 10x 7x 7x 4x 4x 4x 4x 1x 1x 3x 3x 3x 4x 4x 4x 4x 1x 4x 5x 5x 5x 1x 4x 4x 4x 4x 4x 4x 4x 4x 4x 4x 4x 4x 4x 4x 4x 1x 1x 4x 4x 4x 4x 4x 4x 1x 1x 1x 1x 3x 3x 3x 3x 1x 2x 2x 2x 3x 4x 4x 3x 3x 3x 3x 3x 3x 3x 3x 3x 3x 3x 3x 3x 3x 3x 3x 3x 1x 3x 3x 3x 3x 3x 3x 3x 1x 1x 1x 1x 1x 3x 2x 2x 2x 2x 1x 1x 1x 1x 1x 1x 2x 3x 3x 19x | import { computed, ref } from "vue";
import { defineStore } from "pinia";
import {
ApiError,
createApiClient,
createTradeApi,
secureRandomUUID,
type AfterSale,
type BusinessId,
type TradeApi,
} from "@plain-journal/foundation";
const apiBaseUrl = import.meta.env.VITE_API_BASE_URL?.trim() ?? "";
const LEGACY_PENDING_AFTER_SALE_KEY = "plain-journal:pending-after-sale:v1";
const PENDING_AFTER_SALE_KEY_PREFIX = "plain-journal:pending-after-sale:v2:";
export interface AfterSaleAccessContext {
authenticated: boolean;
ownerId: BusinessId | null;
accessToken: string | null;
}
interface ActiveAfterSaleAccess {
ownerId: BusinessId;
accessToken: string;
revision: number;
}
export interface PendingAfterSaleApplication {
key: string;
userId: BusinessId;
orderNo: string;
reason: string;
createdAt: string;
}
class AfterSaleResponseMismatchError extends Error {
constructor() {
super("Trade 已响应,但返回的售后事实与本次账户或请求不一致。");
this.name = "AfterSaleResponseMismatchError";
}
}
function isActiveContext(context: AfterSaleAccessContext): context is {
authenticated: true;
ownerId: BusinessId;
accessToken: string;
} {
return context.authenticated
&& typeof context.ownerId === "string"
&& context.ownerId.length > 0
&& typeof context.accessToken === "string"
&& context.accessToken.length > 0;
}
function pendingKey(ownerId: BusinessId): string {
return `${PENDING_AFTER_SALE_KEY_PREFIX}${ownerId}`;
}
function parsePending(
raw: string | null,
ownerId: BusinessId,
): PendingAfterSaleApplication | null {
Eif (!raw) {
return null;
}
try {
const value: unknown = JSON.parse(raw);
if (
!value
|| typeof value !== "object"
|| !("key" in value)
|| !("userId" in value)
|| !("orderNo" in value)
|| !("reason" in value)
|| !("createdAt" in value)
|| typeof value.key !== "string"
|| value.userId !== ownerId
|| typeof value.orderNo !== "string"
|| value.orderNo.length === 0
|| typeof value.reason !== "string"
|| typeof value.createdAt !== "string"
) {
return null;
}
return value as PendingAfterSaleApplication;
} catch {
return null;
}
}
function loadPending(ownerId: BusinessId): PendingAfterSaleApplication | null {
Iif (typeof localStorage === "undefined") {
return null;
}
const scoped = parsePending(localStorage.getItem(pendingKey(ownerId)), ownerId);
Iif (scoped) {
return scoped;
}
const legacy = parsePending(localStorage.getItem(LEGACY_PENDING_AFTER_SALE_KEY), ownerId);
Iif (legacy) {
localStorage.setItem(pendingKey(ownerId), JSON.stringify(legacy));
localStorage.removeItem(LEGACY_PENDING_AFTER_SALE_KEY);
}
return legacy;
}
function applicationKey(): string {
return `after-sale:${secureRandomUUID()}`;
}
function tradeApi(accessToken: string): TradeApi {
return createTradeApi(createApiClient({
baseUrl: apiBaseUrl,
timeoutMs: 8000,
tokenProvider: () => accessToken,
}));
}
function isUncertain(cause: unknown): boolean {
return cause instanceof ApiError && (
cause.kind === "network"
|| cause.kind === "timeout"
|| cause.kind === "invalid-response"
|| (cause.kind === "http" && (cause.status ?? 500) >= 500)
);
}
function readError(cause: unknown, fallback: string): string {
Iif (cause instanceof ApiError && cause.status === 404) {
return "售后记录不存在,或不属于当前账户。";
}
return cause instanceof Error ? cause.message : fallback;
}
export const useAfterSalesStore = defineStore("customer-after-sales", () => {
const afterSales = ref<AfterSale[]>([]);
const loading = ref(false);
const loadingNo = ref<string | null>(null);
const applyingOrderNo = ref<string | null>(null);
const cancelingNo = ref<string | null>(null);
const error = ref<string | null>(null);
const applicationUnknown = ref(false);
const applicationError = ref<string | null>(null);
const cancellationUnknown = ref(false);
const cancellationError = ref<string | null>(null);
const pendingApplication = ref<PendingAfterSaleApplication | null>(null);
const activeOwnerId = ref<BusinessId | null>(null);
let activeAccessToken: string | null = null;
let accessRevision = 0;
let listRevision = 0;
let detailRevision = 0;
let applicationRevision = 0;
let cancellationRevision = 0;
let activeApplicationPromise: Promise<AfterSale | null> | null = null;
let activeApplicationOrderNo: string | null = null;
let activeApplicationAccessRevision = -1;
let activeCancellationPromise: Promise<AfterSale | null> | null = null;
let activeCancellationNo: string | null = null;
let activeCancellationAccessRevision = -1;
const currentPending = computed(() => pendingApplication.value);
function synchronizeAccess(context: AfterSaleAccessContext): ActiveAfterSaleAccess | null {
const nextOwnerId = isActiveContext(context) ? context.ownerId : null;
const nextAccessToken = isActiveContext(context) ? context.accessToken : null;
const ownerChanged = activeOwnerId.value !== nextOwnerId;
const tokenChanged = activeAccessToken !== nextAccessToken;
if (ownerChanged || tokenChanged) {
activeOwnerId.value = nextOwnerId;
activeAccessToken = nextAccessToken;
accessRevision += 1;
listRevision += 1;
detailRevision += 1;
applicationRevision += 1;
cancellationRevision += 1;
activeApplicationPromise = null;
activeApplicationOrderNo = null;
activeApplicationAccessRevision = -1;
activeCancellationPromise = null;
activeCancellationNo = null;
activeCancellationAccessRevision = -1;
loading.value = false;
loadingNo.value = null;
applyingOrderNo.value = null;
cancelingNo.value = null;
error.value = null;
applicationError.value = null;
cancellationError.value = null;
if (ownerChanged) {
afterSales.value = [];
pendingApplication.value = nextOwnerId ? loadPending(nextOwnerId) : null;
applicationUnknown.value = Boolean(pendingApplication.value);
cancellationUnknown.value = false;
} else Eif (pendingApplication.value) {
applicationUnknown.value = true;
applicationError.value = "会话凭据已经更新,原申请键仍按当前账户保留;请重新查询 Trade 事实。";
}
}
Iif (!isActiveContext(context)) {
afterSales.value = [];
pendingApplication.value = null;
return null;
}
return {
ownerId: context.ownerId,
accessToken: context.accessToken,
revision: accessRevision,
};
}
function accessIsCurrent(access: ActiveAfterSaleAccess): boolean {
return access.revision === accessRevision
&& access.ownerId === activeOwnerId.value
&& access.accessToken === activeAccessToken;
}
function find(afterSaleNo: string): AfterSale | null {
return afterSales.value.find((value) => value.afterSaleNo === afterSaleNo) ?? null;
}
function forOrder(orderNo: string): AfterSale | null {
return afterSales.value.find((value) => value.orderNo === orderNo) ?? null;
}
function verifyFact(
access: ActiveAfterSaleAccess,
value: AfterSale,
expected?: { afterSaleNo?: string; orderNo?: string },
) {
if (
value.userId !== access.ownerId
|| (expected?.afterSaleNo && value.afterSaleNo !== expected.afterSaleNo)
|| (expected?.orderNo && value.orderNo !== expected.orderNo)
) {
throw new AfterSaleResponseMismatchError();
}
}
function sortFacts() {
afterSales.value.sort((left, right) => Date.parse(right.createdAt) - Date.parse(left.createdAt));
}
function upsert(value: AfterSale) {
const index = afterSales.value.findIndex((candidate) =>
candidate.afterSaleNo === value.afterSaleNo || candidate.orderNo === value.orderNo);
if (index >= 0) {
afterSales.value[index] = value;
} else {
afterSales.value.push(value);
}
sortFacts();
}
function persistPending(
access: ActiveAfterSaleAccess,
value: PendingAfterSaleApplication | null,
) {
Iif (!accessIsCurrent(access)) {
return;
}
pendingApplication.value = value;
Iif (typeof localStorage === "undefined") {
return;
}
const key = pendingKey(access.ownerId);
if (value) {
localStorage.setItem(key, JSON.stringify(value));
} else {
localStorage.removeItem(key);
}
}
function completeApplication(access: ActiveAfterSaleAccess, value: AfterSale) {
Iif (!accessIsCurrent(access)) {
return;
}
upsert(value);
if (pendingApplication.value?.orderNo === value.orderNo) {
persistPending(access, null);
}
applicationUnknown.value = false;
applicationError.value = null;
}
async function loadForAccess(access: ActiveAfterSaleAccess): Promise<AfterSale[]> {
const requestRevision = ++listRevision;
loading.value = true;
error.value = null;
try {
const values = await tradeApi(access.accessToken).afterSales();
if (!accessIsCurrent(access) || requestRevision !== listRevision) {
return afterSales.value;
}
for (const value of values) {
verifyFact(access, value);
}
afterSales.value = values;
sortFacts();
const pending = pendingApplication.value;
const recovered = pending ? forOrder(pending.orderNo) : null;
if (recovered) {
completeApplication(access, recovered);
}
return afterSales.value;
} catch (cause) {
Eif (accessIsCurrent(access) && requestRevision === listRevision) {
error.value = readError(cause, "售后列表暂时无法读取。");
}
return afterSales.value;
} finally {
if (accessIsCurrent(access) && requestRevision === listRevision) {
loading.value = false;
}
}
}
async function load(context: AfterSaleAccessContext): Promise<AfterSale[]> {
const access = synchronizeAccess(context);
return access ? loadForAccess(access) : [];
}
async function loadOneForAccess(
access: ActiveAfterSaleAccess,
afterSaleNo: string,
): Promise<AfterSale | null> {
const requestRevision = ++detailRevision;
loadingNo.value = afterSaleNo;
error.value = null;
try {
const value = await tradeApi(access.accessToken).afterSale(afterSaleNo);
Iif (!accessIsCurrent(access) || requestRevision !== detailRevision) {
return null;
}
verifyFact(access, value, { afterSaleNo });
upsert(value);
if (value.status === "CANCELED") {
cancellationUnknown.value = false;
cancellationError.value = null;
}
return value;
} catch (cause) {
if (accessIsCurrent(access) && requestRevision === detailRevision) {
error.value = readError(cause, "售后事实暂时无法读取。");
}
return null;
} finally {
Eif (accessIsCurrent(access) && requestRevision === detailRevision) {
loadingNo.value = null;
}
}
}
async function loadOne(
context: AfterSaleAccessContext,
afterSaleNo: string,
): Promise<AfterSale | null> {
const access = synchronizeAccess(context);
return access ? loadOneForAccess(access, afterSaleNo) : null;
}
function prepare(
access: ActiveAfterSaleAccess,
orderNo: string,
reason: string,
): PendingAfterSaleApplication | null {
const trimmedReason = reason.trim();
Iif (!trimmedReason) {
applicationError.value = "请说明申请整单退货退款的真实原因。";
return null;
}
const existing = pendingApplication.value;
if (existing) {
Iif (existing.orderNo !== orderNo) {
applicationUnknown.value = true;
applicationError.value = "当前账户已有另一笔售后申请结果尚未确认,请先处理原订单。";
return null;
}
return existing;
}
const value: PendingAfterSaleApplication = {
key: applicationKey(),
userId: access.ownerId,
orderNo,
reason: trimmedReason,
createdAt: new Date().toISOString(),
};
persistPending(access, value);
return value;
}
async function recoverApplicationForAccess(
access: ActiveAfterSaleAccess,
orderNo: string,
): Promise<AfterSale | null> {
await loadForAccess(access);
Iif (!accessIsCurrent(access)) {
return null;
}
const recovered = forOrder(orderNo);
if (recovered) {
completeApplication(access, recovered);
}
return recovered;
}
function apply(
context: AfterSaleAccessContext,
orderNo: string,
reason: string,
): Promise<AfterSale | null> {
const access = synchronizeAccess(context);
Iif (!access) {
applicationError.value = "当前会话没有可用于申请售后的顾客事实。";
return Promise.resolve(null);
}
if (
activeApplicationPromise
&& activeApplicationOrderNo === orderNo
&& activeApplicationAccessRevision === access.revision
) {
return activeApplicationPromise;
}
const request = applyForAccess(access, orderNo, reason);
activeApplicationPromise = request;
activeApplicationOrderNo = orderNo;
activeApplicationAccessRevision = access.revision;
const cleanup = () => {
Eif (activeApplicationPromise === request) {
activeApplicationPromise = null;
activeApplicationOrderNo = null;
activeApplicationAccessRevision = -1;
}
};
void request.then(cleanup, cleanup);
return request;
}
async function applyForAccess(
access: ActiveAfterSaleAccess,
orderNo: string,
reason: string,
): Promise<AfterSale | null> {
applicationError.value = null;
const known = forOrder(orderNo);
Iif (known) {
return known;
}
if (pendingApplication.value) {
const recovered = await recoverApplicationForAccess(access, orderNo);
Iif (!accessIsCurrent(access) || recovered) {
return recovered;
}
}
const pending = prepare(access, orderNo, reason);
Iif (!pending) {
return null;
}
const requestRevision = ++applicationRevision;
applyingOrderNo.value = orderNo;
try {
const value = await tradeApi(access.accessToken).applyAfterSale(
pending.orderNo,
pending.reason,
pending.key,
);
Iif (!accessIsCurrent(access) || requestRevision !== applicationRevision) {
return null;
}
verifyFact(access, value, { orderNo });
completeApplication(access, value);
return value;
} catch (cause) {
Iif (!accessIsCurrent(access) || requestRevision !== applicationRevision) {
return null;
}
Eif (isUncertain(cause)) {
const recovered = await recoverApplicationForAccess(access, orderNo);
if (recovered) {
return recovered;
}
applicationUnknown.value = true;
applicationError.value = "售后申请结果尚未确认。原申请键已按当前账户保留,请查询或安全重试。";
return null;
}
if (cause instanceof AfterSaleResponseMismatchError) {
applicationUnknown.value = true;
applicationError.value = cause.message;
return null;
}
persistPending(access, null);
applicationUnknown.value = false;
applicationError.value = cause instanceof Error ? cause.message : "售后申请未完成。";
return null;
} finally {
Eif (accessIsCurrent(access) && requestRevision === applicationRevision) {
applyingOrderNo.value = null;
}
}
}
function cancel(
context: AfterSaleAccessContext,
afterSaleNo: string,
): Promise<AfterSale | null> {
const access = synchronizeAccess(context);
Iif (!access) {
cancellationError.value = "当前会话没有可用于取消售后的顾客事实。";
return Promise.resolve(null);
}
Iif (
activeCancellationPromise
&& activeCancellationNo === afterSaleNo
&& activeCancellationAccessRevision === access.revision
) {
return activeCancellationPromise;
}
const request = cancelForAccess(access, afterSaleNo);
activeCancellationPromise = request;
activeCancellationNo = afterSaleNo;
activeCancellationAccessRevision = access.revision;
const cleanup = () => {
Eif (activeCancellationPromise === request) {
activeCancellationPromise = null;
activeCancellationNo = null;
activeCancellationAccessRevision = -1;
}
};
void request.then(cleanup, cleanup);
return request;
}
async function cancelForAccess(
access: ActiveAfterSaleAccess,
afterSaleNo: string,
): Promise<AfterSale | null> {
cancellationError.value = null;
let current = find(afterSaleNo);
if (!current) {
current = await loadOneForAccess(access, afterSaleNo);
}
Iif (!accessIsCurrent(access) || !current) {
return null;
}
Iif (current.status === "CANCELED") {
cancellationUnknown.value = false;
return current;
}
Iif (current.status !== "APPLIED") {
cancellationUnknown.value = false;
cancellationError.value = `售后当前为 ${current.status},不能取消已经推进的退货或退款。`;
return current;
}
const requestRevision = ++cancellationRevision;
cancelingNo.value = afterSaleNo;
try {
const value = await tradeApi(access.accessToken).cancelAfterSale(afterSaleNo);
Iif (!accessIsCurrent(access) || requestRevision !== cancellationRevision) {
return null;
}
verifyFact(access, value, { afterSaleNo });
upsert(value);
cancellationUnknown.value = value.status !== "CANCELED";
cancellationError.value = value.status === "CANCELED"
? null
: "取消接口已响应,但 Trade 尚未返回 CANCELED;请继续查询售后事实。";
return value;
} catch (cause) {
Iif (!accessIsCurrent(access) || requestRevision !== cancellationRevision) {
return null;
}
Eif (isUncertain(cause)) {
const recovered = await loadOneForAccess(access, afterSaleNo);
if (recovered?.status === "CANCELED") {
cancellationUnknown.value = false;
cancellationError.value = null;
return recovered;
}
cancellationUnknown.value = true;
cancellationError.value = "取消售后结果尚未确认,请查询 Trade 事实后再决定是否重试。";
return recovered;
}
cancellationUnknown.value = false;
cancellationError.value = cause instanceof Error ? cause.message : "取消售后未完成。";
return null;
} finally {
Eif (accessIsCurrent(access) && requestRevision === cancellationRevision) {
cancelingNo.value = null;
}
}
}
return {
afterSales,
loading,
loadingNo,
applyingOrderNo,
cancelingNo,
error,
applicationUnknown,
applicationError,
cancellationUnknown,
cancellationError,
pendingApplication,
currentPending,
activeOwnerId,
synchronizeAccess,
find,
forOrder,
load,
loadOne,
apply,
cancel,
};
});
|