Files
vmall/apps/shop-admin/pages/coupons.vue
T

279 lines
9.2 KiB
Vue

<script setup lang="ts">
import type { CouponTemplate, CouponTemplateInput, Currency } from "@vmall/shared";
definePageMeta({ middleware: "auth" });
const { $api } = useNuxtApp();
const { locale, t: translate } = useI18n();
const { load: loadMoney, fmt } = useMoney();
const templates = ref<CouponTemplate[]>([]);
const currencies = ref<Currency[]>([]);
const loading = ref(true);
const saving = ref(false);
const actionId = ref("");
const error = ref("");
const message = ref("");
const editingId = ref("");
const form = reactive({
titleEn: "",
titleZh: "",
amountMinor: 0,
thresholdMinor: 0,
currency: "USD",
stock: 0,
enabled: true,
startsAt: "",
endsAt: "",
});
function toLocalInput(iso: string): string {
const d = new Date(iso);
const pad = (n: number) => String(n).padStart(2, "0");
return `${d.getFullYear()}-${pad(d.getMonth() + 1)}-${pad(d.getDate())}T${pad(d.getHours())}:${pad(d.getMinutes())}`;
}
function resetForm(): void {
const now = new Date();
const later = new Date(now.getTime() + 30 * 24 * 3600 * 1000);
editingId.value = "";
form.titleEn = "";
form.titleZh = "";
form.amountMinor = 0;
form.thresholdMinor = 0;
form.currency =
currencies.value.find((c) => c.is_base)?.code ?? currencies.value[0]?.code ?? "USD";
form.stock = 0;
form.enabled = true;
form.startsAt = toLocalInput(now.toISOString());
form.endsAt = toLocalInput(later.toISOString());
}
async function loadTemplates(): Promise<void> {
loading.value = true;
error.value = "";
try {
templates.value = await $api.shop.listCouponTemplates();
} catch (err: unknown) {
error.value = err instanceof Error ? err.message : translate("common.error");
} finally {
loading.value = false;
}
}
async function loadCurrencies(): Promise<void> {
try {
currencies.value = (await $api.listCurrencies()).filter((c) => c.enabled);
} catch {
currencies.value = [];
}
}
function payload(): CouponTemplateInput {
return {
title: { en: form.titleEn.trim(), zh: form.titleZh.trim() },
amount_minor: Number(form.amountMinor),
threshold_minor: Number(form.thresholdMinor),
currency: form.currency,
stock: Number(form.stock),
enabled: form.enabled,
starts_at: new Date(form.startsAt).toISOString(),
ends_at: new Date(form.endsAt).toISOString(),
};
}
async function submit(): Promise<void> {
error.value = "";
message.value = "";
const body = payload();
if (!body.title.en || !body.title.zh) {
error.value = translate("shop.couponTitleRequired");
return;
}
if (!(body.amount_minor > 0)) {
error.value = translate("shop.couponAmountInvalid");
return;
}
if (body.threshold_minor < 0) {
error.value = translate("shop.couponThresholdInvalid");
return;
}
if (body.stock < 0) {
error.value = translate("shop.couponStockInvalid");
return;
}
if (new Date(body.ends_at) < new Date(body.starts_at)) {
error.value = translate("shop.couponWindowInvalid");
return;
}
saving.value = true;
try {
if (editingId.value) await $api.shop.updateCouponTemplate(editingId.value, body);
else await $api.shop.createCouponTemplate(body);
message.value = translate("shop.couponSaved");
resetForm();
await loadTemplates();
} catch (err: unknown) {
error.value = err instanceof Error ? err.message : translate("common.error");
} finally {
saving.value = false;
}
}
function edit(template: CouponTemplate): void {
editingId.value = template.id;
form.titleEn = template.title.en ?? "";
form.titleZh = template.title.zh ?? "";
form.amountMinor = template.amount_minor;
form.thresholdMinor = template.threshold_minor;
form.currency = template.currency;
form.stock = template.stock;
form.enabled = template.enabled;
form.startsAt = toLocalInput(template.starts_at);
form.endsAt = toLocalInput(template.ends_at);
}
async function toggleEnabled(template: CouponTemplate): Promise<void> {
actionId.value = template.id;
error.value = "";
try {
await $api.shop.updateCouponTemplate(template.id, {
title: template.title,
amount_minor: template.amount_minor,
threshold_minor: template.threshold_minor,
currency: template.currency,
stock: template.stock,
enabled: !template.enabled,
starts_at: template.starts_at,
ends_at: template.ends_at,
});
await loadTemplates();
} catch (err: unknown) {
error.value = err instanceof Error ? err.message : translate("common.error");
} finally {
actionId.value = "";
}
}
async function remove(template: CouponTemplate): Promise<void> {
actionId.value = template.id;
error.value = "";
message.value = "";
try {
await $api.shop.deleteCouponTemplate(template.id);
message.value = translate("shop.couponDeleted");
await loadTemplates();
} catch (err: unknown) {
error.value = err instanceof Error ? err.message : translate("common.error");
} finally {
actionId.value = "";
}
}
onMounted(async () => {
loadMoney();
await loadCurrencies();
resetForm();
await loadTemplates();
});
</script>
<template>
<VPage :title="$t('shop.couponList')">
<div v-if="error" class="text-danger my-2 text-sm" role="alert">{{ error }}</div>
<div v-if="message" class="text-muted my-2 text-sm" role="status">{{ message }}</div>
<VCard class="mb-5">
<h2 class="mb-4 text-base font-semibold">
{{ editingId ? $t("shop.editCoupon") : $t("shop.newCoupon") }}
</h2>
<div class="my-3 grid [grid-template-columns:repeat(auto-fit,minmax(220px,1fr))] gap-3">
<VField :label="$t('shop.couponTitleEn')"
><VInput v-model="form.titleEn" type="text"
/></VField>
<VField :label="$t('shop.couponTitleZh')"
><VInput v-model="form.titleZh" type="text"
/></VField>
<VField :label="$t('shop.couponAmount')"
><VInput v-model.number="form.amountMinor" type="number" min="1" step="1"
/></VField>
<VField :label="$t('shop.couponThreshold')"
><VInput v-model.number="form.thresholdMinor" type="number" min="0" step="1"
/></VField>
<VField :label="$t('shop.couponCurrency')">
<select
v-model="form.currency"
class="border-border bg-surface text-text focus:border-primary focus:outline-primary/30 w-full rounded-md border px-3 py-2 text-sm focus:outline-2"
>
<option v-for="c in currencies" :key="c.code" :value="c.code">{{ c.code }}</option>
</select>
</VField>
<VField :label="$t('shop.couponStock')"
><VInput v-model.number="form.stock" type="number" min="0" step="1"
/></VField>
<VField :label="$t('shop.couponStartsAt')"
><VInput v-model="form.startsAt" type="datetime-local"
/></VField>
<VField :label="$t('shop.couponEndsAt')"
><VInput v-model="form.endsAt" type="datetime-local"
/></VField>
<label class="text-text flex items-center gap-2 text-sm font-medium"
><input v-model="form.enabled" type="checkbox" class="accent-primary h-4 w-4" /><span>{{
$t("shop.couponEnabled")
}}</span></label
>
</div>
<div class="flex gap-2">
<VBtn variant="primary" :disabled="saving" @click="submit">{{
editingId ? $t("shop.updateCoupon") : $t("shop.createCoupon")
}}</VBtn>
<VBtn v-if="editingId" type="button" @click="resetForm">{{ $t("common.cancel") }}</VBtn>
</div>
</VCard>
<p v-if="loading" class="text-muted">{{ $t("common.loading") }}</p>
<VCard v-else-if="!templates.length" class="text-muted">{{ $t("common.empty") }}</VCard>
<VTable v-else>
<thead>
<tr>
<th>{{ $t("shop.couponTitleEn") }}</th>
<th>{{ $t("shop.couponAmount") }}</th>
<th>{{ $t("shop.couponThreshold") }}</th>
<th>{{ $t("shop.couponStock") }}</th>
<th>{{ $t("shop.couponStartsAt") }}</th>
<th>{{ $t("shop.couponEndsAt") }}</th>
<th>{{ $t("common.status") }}</th>
<th>{{ $t("common.actions") }}</th>
</tr>
</thead>
<tbody>
<tr v-for="template in templates" :key="template.id">
<td>{{ template.title[locale] ?? template.title.en }}</td>
<td>{{ fmt(template.amount_minor, template.currency) }}</td>
<td>{{ fmt(template.threshold_minor, template.currency) }}</td>
<td>{{ template.stock }}</td>
<td>{{ template.starts_at.slice(0, 10) }}</td>
<td>{{ template.ends_at.slice(0, 10) }}</td>
<td>
<VBadge :tone="template.enabled ? 'green' : 'red'">{{
template.enabled ? $t("shop.enabledOn") : $t("shop.enabledOff")
}}</VBadge>
</td>
<td class="flex flex-wrap gap-1.5">
<VBtn size="sm" :disabled="actionId === template.id" @click="edit(template)">{{
$t("shop.edit")
}}</VBtn>
<VBtn size="sm" :disabled="actionId === template.id" @click="toggleEnabled(template)">{{
template.enabled ? $t("shop.enabledOff") : $t("shop.enabledOn")
}}</VBtn>
<VBtn size="sm" :disabled="actionId === template.id" @click="remove(template)">{{
$t("common.delete")
}}</VBtn>
</td>
</tr>
</tbody>
</VTable>
</VPage>
</template>