Files
vmall/apps/shop-admin/pages/orders/[id].vue
T

280 lines
9.8 KiB
Vue

<script setup lang="ts">
import { t as localized } from "@vmall/shared";
import type { Order, OrderStatus, Shipment, ShipmentItemBody } from "@vmall/shared";
definePageMeta({ middleware: "auth" });
const { $api } = useNuxtApp();
const { locale, t: translate } = useI18n();
const { load: loadMoney, fmt } = useMoney();
const route = useRoute();
const orderId = computed(() => String(route.params.id));
const order = ref<Order | null>(null);
const shipments = ref<Shipment[]>([]);
const quantities = ref<Record<string, number>>({});
const carrier = ref("");
const trackingNo = ref("");
const loading = ref(true);
const busy = ref(false);
const actionId = ref("");
const error = ref("");
function statusClass(value: OrderStatus): "green" | "red" | "orange" | "blue" {
if (value === "completed") return "green";
if (value === "cancelled") return "red";
if (value === "pending_payment") return "orange";
return "blue";
}
function shipmentStatusClass(value: Shipment["status"]): "green" | "blue" | "orange" {
return value === "delivered" ? "green" : value === "shipped" ? "blue" : "orange";
}
function formatDate(value: string): string {
return new Date(value).toLocaleString(locale.value === "zh" ? "zh-CN" : "en-US");
}
function shippedQuantity(itemId: string): number {
return shipments.value
.filter((shipment) => shipment.order_id === orderId.value)
.flatMap((shipment) => shipment.items)
.filter((item) => item.order_item_id === itemId)
.reduce((total, item) => total + item.qty, 0);
}
function unshippedQuantity(itemId: string, total: number): number {
return Math.max(0, total - shippedQuantity(itemId));
}
async function findShopOrder(): Promise<Order> {
let currentPage = 1;
let totalPages = 1;
while (currentPage <= totalPages) {
const result = await $api.shop.listOrders({ page: currentPage });
const found = result.items.find((item) => item.id === orderId.value);
if (found) return found;
totalPages = Math.max(1, Math.ceil(result.total / result.per_page));
currentPage += 1;
}
throw new Error(translate("common.empty"));
}
async function loadOrder(): Promise<void> {
loading.value = true;
error.value = "";
try {
const [loadedOrder, loadedShipments] = await Promise.all([
findShopOrder(),
$api.shop.listShipments(),
]);
order.value = loadedOrder;
shipments.value = loadedShipments.filter((shipment) => shipment.order_id === orderId.value);
const nextQuantities: Record<string, number> = {};
loadedOrder.items.forEach((item) => {
nextQuantities[item.id] = Math.max(
0,
item.qty -
loadedShipments
.filter((shipment) => shipment.order_id === orderId.value)
.flatMap((shipment) => shipment.items)
.filter((shipmentItem) => shipmentItem.order_item_id === item.id)
.reduce((total, shipmentItem) => total + shipmentItem.qty, 0),
);
});
quantities.value = nextQuantities;
} catch (err: unknown) {
error.value = err instanceof Error ? err.message : translate("common.error");
} finally {
loading.value = false;
}
}
async function createShipment(): Promise<void> {
if (!order.value || !carrier.value.trim() || !trackingNo.value.trim()) {
error.value = translate("common.required");
return;
}
const items: ShipmentItemBody[] = order.value.items
.map((item) => ({ order_item_id: item.id, qty: quantities.value[item.id] ?? 0 }))
.filter((item) => item.qty > 0);
if (!items.length) {
error.value = translate("common.required");
return;
}
busy.value = true;
error.value = "";
try {
await $api.shop.createShipment(
order.value.id,
carrier.value.trim(),
trackingNo.value.trim(),
items,
);
carrier.value = "";
trackingNo.value = "";
await loadOrder();
} catch (err: unknown) {
error.value = err instanceof Error ? err.message : translate("common.error");
} finally {
busy.value = false;
}
}
async function markShipped(shipment: Shipment): Promise<void> {
actionId.value = shipment.id;
error.value = "";
try {
await $api.shop.markShipped(shipment.id);
await loadOrder();
} catch (err: unknown) {
error.value = err instanceof Error ? err.message : translate("common.error");
} finally {
actionId.value = "";
}
}
onMounted(() => {
loadMoney();
loadOrder();
});
</script>
<template>
<VPage :title="order ? order.order_no : $t('order.title')">
<template #actions>
<NuxtLink
class="border-border bg-surface text-text hover:bg-bg inline-flex items-center justify-center rounded-md border px-4 py-2 text-sm font-medium"
to="/orders"
>{{ $t("common.back") }}</NuxtLink
>
</template>
<div v-if="error" class="text-danger my-2 text-sm" role="alert">{{ error }}</div>
<p v-if="loading" class="text-muted">{{ $t("common.loading") }}</p>
<template v-else-if="order">
<VCard>
<div class="mb-4 flex items-center justify-between gap-3">
<h2 class="text-lg font-semibold">{{ $t("shop.details") }}</h2>
<VBadge :tone="statusClass(order.status)">{{
$t(`order.status.${order.status}`)
}}</VBadge>
</div>
<div class="mb-5 grid [grid-template-columns:repeat(auto-fit,minmax(180px,1fr))] gap-4">
<div class="grid gap-1.5">
<span class="text-muted text-sm">{{ $t("shop.created") }}</span
><strong>{{ formatDate(order.created_at) }}</strong>
</div>
<div class="grid gap-1.5">
<span class="text-muted text-sm">{{ $t("shop.total") }}</span
><strong>{{ fmt(order.total_minor, order.currency) }}</strong>
</div>
</div>
<h3 class="mb-3 text-base font-semibold">{{ $t("shop.items") }}</h3>
<VTable>
<thead>
<tr>
<th>{{ $t("product.detail") }}</th>
<th>{{ $t("product.skuCode") }}</th>
<th>{{ $t("common.qty") }}</th>
<th>{{ $t("common.price") }}</th>
</tr>
</thead>
<tbody>
<tr v-for="item in order.items" :key="item.id">
<td>{{ localized(item.product_name, locale) }}</td>
<td>{{ item.sku_code }}</td>
<td>{{ item.qty }}</td>
<td>{{ fmt(item.unit_price_minor, order.currency) }}</td>
</tr>
</tbody>
</VTable>
<h3 class="mt-5 mb-2 text-base font-semibold">{{ $t("shop.address") }}</h3>
<address class="leading-7 not-italic">
<div>{{ order.shipping_address.recipient }} · {{ order.shipping_address.phone }}</div>
<div>
{{ order.shipping_address.country }}, {{ order.shipping_address.region }},
{{ order.shipping_address.city }}
</div>
<div>{{ order.shipping_address.line1 }}, {{ order.shipping_address.postal_code }}</div>
</address>
</VCard>
<VCard v-if="order.status === 'paid' || order.status === 'fulfilling'" class="mt-4">
<h2 class="mb-4 text-lg font-semibold">{{ $t("shop.createShipment") }}</h2>
<form @submit.prevent="createShipment">
<div class="grid gap-3 md:grid-cols-2">
<VField :label="$t('shop.carrier')">
<VInput id="carrier" v-model="carrier" required />
</VField>
<VField :label="$t('shop.trackingNo')">
<VInput id="tracking-no" v-model="trackingNo" required />
</VField>
</div>
<h3 class="mb-3 text-base font-semibold">{{ $t("shop.shipmentQuantities") }}</h3>
<div
v-for="item in order.items"
:key="`quantity-${item.id}`"
class="flex items-end gap-3"
>
<div class="min-w-0 flex-[2] pb-3.5">
{{ localized(item.product_name, locale) }} ({{ item.sku_code }})
</div>
<VField
class="flex-1"
:label="`${$t('shop.unshipped')}: ${unshippedQuantity(item.id, item.qty)}`"
>
<VInput
:id="`quantity-${item.id}`"
v-model.number="quantities[item.id]"
type="number"
min="0"
:max="unshippedQuantity(item.id, item.qty)"
step="1"
/>
</VField>
</div>
<VBtn variant="primary" type="submit" :disabled="busy">{{
$t("shop.createShipment")
}}</VBtn>
</form>
</VCard>
<VCard class="mt-4">
<h2 class="mb-4 text-lg font-semibold">{{ $t("shipment.title") }}</h2>
<div v-if="!shipments.length" class="text-muted">{{ $t("common.empty") }}</div>
<VTable v-else>
<thead>
<tr>
<th>{{ $t("shipment.shipmentNo") }}</th>
<th>{{ $t("shop.carrier") }}</th>
<th>{{ $t("shop.trackingNo") }}</th>
<th>{{ $t("common.status") }}</th>
<th>{{ $t("common.actions") }}</th>
</tr>
</thead>
<tbody>
<tr v-for="shipment in shipments" :key="shipment.id">
<td>{{ shipment.shipment_no }}</td>
<td>{{ shipment.carrier }}</td>
<td>{{ shipment.tracking_no }}</td>
<td>
<VBadge :tone="shipmentStatusClass(shipment.status)">{{
$t(`shipment.status.${shipment.status}`)
}}</VBadge>
</td>
<td>
<VBtn
v-if="shipment.status === 'pending'"
size="sm"
:disabled="actionId === shipment.id"
@click="markShipped(shipment)"
>{{ $t("shipment.markShipped") }}</VBtn
>
</td>
</tr>
</tbody>
</VTable>
</VCard>
</template>
</VPage>
</template>