Jelajahi Sumber

feat: [AE-会员端] 添加订单详情页面

bill 3 minggu lalu
induk
melakukan
5df9592787

+ 14 - 0
src/api/shop.js

@@ -13,6 +13,20 @@ export function createGuestOrder(data) {
   return request({ url: '/v1/shop/no-login-reconsume-sure-order', method: 'post', data })
 }
 
+export function fetchGuestOrderDetail(query) {
+  return request({ url: '/v1/shop/no-login-order-detail', method: 'get', params: query })
+}
+
+export function downloadGuestOrder(orderSn) {
+  return request({
+    url: `/v1/shop/no-login-order-export/${encodeURIComponent(orderSn)}`,
+    method: 'get',
+    params: {},
+    // 匿名导出失败留给页面提示,避免触发会员拦截器清缓存并跳转登录。
+    validateStatus: status => (status >= 200 && status < 300) || status === 401
+  })
+}
+
 // 商品列表
 export function fetchProductList(query) {
   return request({

+ 8 - 1
src/ui-refactor/index.vue

@@ -1,6 +1,6 @@
 <template>
   <el-container direction="vertical" class="ng-public-layout" lang="en">
-    <public-header v-if="layout.showHeader !== false" :login-route="loginRoute" />
+    <public-header v-if="showHeader" :login-route="loginRoute" />
     <el-main class="ng-public-main">
       <page-hero v-if="layout.hero" :hero="layout.hero" />
       <div class="ng-public-container ng-public-content">
@@ -16,6 +16,7 @@ import './styles/theme.scss'
 import PublicHeader from './layouts/PublicHeader.vue'
 import PageHero from './layouts/PageHero.vue'
 import PublicFooter from './layouts/PublicFooter.vue'
+import usersInfo from '@/utils/usersInfo'
 
 export default {
   name: 'PublicLayout',
@@ -25,6 +26,12 @@ export default {
       // 仅使用当前叶子路由的展示配置,不参与权限或认证判断。
       return this.$route.meta.publicLayout || {}
     },
+    showHeader() {
+      // 会话有效性沿用路由守卫;这里只读取现有登录状态来控制展示。
+      return this.layout.showHeader === 'authenticated'
+        ? Boolean(usersInfo.accessToken())
+        : this.layout.showHeader !== false
+    },
     loginRoute() {
       // 返回登录时保留 redirect 和来源等查询参数。
       return { path: '/login', query: this.$route.query }

+ 40 - 14
src/ui-refactor/layouts/PublicFooter.vue

@@ -12,8 +12,16 @@
         <el-col v-for="group in groups" :key="group.title" :xs="24" :sm="12" :lg="group.span">
           <h2 class="ng-public-footer-title">{{ group.title }}</h2>
           <ul class="ng-public-footer-list">
-            <li v-for="label in group.items" :key="label" class="ng-public-footer-item">
-              {{ label }}
+            <li v-for="item in group.items" :key="item.label" class="ng-public-footer-item">
+              <a
+                :href="item.href"
+                :underline="false"
+                target="_blank"
+                rel="noopener noreferrer"
+                class="ng-public-footer-link"
+              >
+                {{ item.label }}
+              </a>
             </li>
           </ul>
         </el-col>
@@ -29,13 +37,13 @@
             Utako, Abuja.
             <br>
             Tel :
-            <el-link href="tel:+2349131178401" class="ng-public-footer-contact">
+            <a href="tel:+2349131178401" class="ng-public-footer-contact">
               +234 913 117 8401
-            </el-link>
+            </a>
             <br>
-            <el-link href="mailto:contact@elkenafrica.com" class="ng-public-footer-contact">
+            <a href="mailto:contact@elkenafrica.com" class="ng-public-footer-contact">
               contact@elkenafrica.com
-            </el-link>
+            </a>
           </address>
         </el-col>
       </el-row>
@@ -82,20 +90,31 @@ export default {
   name: 'PublicFooter',
   data() {
     return {
-      // 尚无对应站内路由,仅展示栏目文字,避免生成无效链接。
       groups: [
         {
           title: 'Who We Are',
           span: 5,
           items: [
-            'About Elken Nigeria',
-            'Our Global Strength',
-            'Leadership',
-            'Our Journey',
-            'Community'
+            { label: 'About Elken Nigeria', href: 'https://staging.elkenafrica.com/about/' },
+            {
+              label: 'Our Global Strength',
+              href: 'https://staging.elkenafrica.com/about/global-strength/'
+            },
+            { label: 'Leadership', href: 'https://staging.elkenafrica.com/about/leadership/' },
+            { label: 'Our Journey', href: 'https://staging.elkenafrica.com/about/journey/' },
+            { label: 'Community', href: 'https://staging.elkenafrica.com/about/community/' }
           ]
         },
-        { title: 'Products', span: 4, items: ['Health', 'Wellness', 'Water', 'Beauty'] }
+        {
+          title: 'Products',
+          span: 4,
+          items: [
+            { label: 'Health', href: 'https://staging.elkenafrica.com/products/health/' },
+            { label: 'Wellness', href: 'https://staging.elkenafrica.com/products/wellness/' },
+            { label: 'Water', href: 'https://staging.elkenafrica.com/products/water-filters/' },
+            { label: 'Beauty', href: 'https://staging.elkenafrica.com/products/beauty/' }
+          ]
+        }
       ],
       policies: ['Privacy', 'Terms Of Use', 'Policies', 'Support'],
       socials: [
@@ -169,6 +188,12 @@ export default {
   content: '';
 }
 
+.ng-public-layout .ng-public-footer-link {
+  color: inherit;
+  font-size: inherit;
+  font-weight: inherit;
+}
+
 .ng-public-layout .ng-public-footer-address {
   color: #d7dcdf;
   font-size: 14px;
@@ -190,7 +215,8 @@ export default {
   text-decoration: underline;
 }
 
-.ng-public-layout .ng-public-footer-contact:hover {
+.ng-public-layout .ng-public-footer-contact:hover,
+.ng-public-layout .ng-public-footer-link:hover {
   color: #f287b7;
 }
 

+ 18 - 1
src/ui-refactor/views/account/__tests__/AccountOrders.spec.js

@@ -1,6 +1,7 @@
 /* eslint-env jest */
 import Vue from 'vue'
 import ElementUI from 'element-ui'
+import VueRouter from 'vue-router'
 import fs from 'fs'
 import path from 'path'
 import { transformSync } from '@babel/core'
@@ -14,6 +15,7 @@ jest.mock('@/api/shop', () => ({ fetchOrderList: jest.fn(), downloadOrder: jest.
 jest.mock('@/api/user', () => ({ fetchOrderList: jest.fn(), downloadOrder: jest.fn() }))
 jest.mock('@/utils/usersInfo', () => ({}))
 Vue.use(ElementUI)
+Vue.use(VueRouter)
 Vue.prototype.$t = key => key
 
 // 沿用现有测试的真实 SFC 编译方式,并支持只加载旧脚本。
@@ -58,7 +60,8 @@ const order = {
 }
 const instances = []
 function instance() {
-  const vm = new Vue(AccountOrders).$mount()
+  const router = new VueRouter({ mode: 'abstract', routes: [{ path: '/guest-order', component: { render: h => h('div') }}] })
+  const vm = new Vue({ ...AccountOrders, router }).$mount()
   document.body.appendChild(vm.$el)
   instances.push(vm)
   return vm
@@ -89,6 +92,20 @@ afterEach(() => {
   jest.restoreAllMocks()
 })
 
+it.each([['self', 0, 'OWN-1'], ['self', 1, 'OWN-2'], ['member', 0, 'MEMBER-1']])('opens the selected %s order reference in the shared detail page', async(category, index, sn) => {
+  const vm = instance()
+  vm.category = category
+  await settle()
+  const link = vm.$el.querySelectorAll('.ng-order-number a')[index]
+  expect(link).toBeTruthy()
+  expect(link.textContent).toBe(sn)
+  expect(link.getAttribute('href')).toBe('/guest-order?order=' + sn)
+  link.click()
+  await settle()
+  expect(vm.$route.path).toBe('/guest-order')
+  expect(vm.$route.query).toEqual({ order: sn })
+})
+
 it('inherits each old page without replacing its state, requests, downloads or amount filters', () => {
   for (const [name, file] of [['OwnOrders', 'shop/order-list.vue'], ['MemberOrders', 'user/member-order.vue']]) {
     const options = AccountOrders.components[name]

+ 11 - 1
src/ui-refactor/views/account/components/order/AccountOrderCards.vue

@@ -28,7 +28,12 @@
     >
       <div class="ng-order-header">
         <div class="ng-order-heading">
-          <h3 class="ng-order-number">{{ order.SN }}</h3>
+          <h3 class="ng-order-number">
+            <router-link
+              class="ng-order-link"
+              :to="{ path: '/guest-order', query: { order: order.SN }}"
+            >{{ order.SN }}</router-link>
+          </h3>
           <span>{{ order.ORDER_TYPE }}</span>
           <el-tag :type="order.STATUS | statusFilter" size="small">{{ order.STATUS }}</el-tag>
         </div>
@@ -185,6 +190,11 @@ export default {
   gap: 12px;
 }
 
+.ng-order-link {
+  text-decoration: underline;
+  text-underline-offset: 3px;
+}
+
 .ng-order-header {
   justify-content: space-between;
 }

+ 288 - 0
src/ui-refactor/views/guest-shop/GuestOrderDetails.vue

@@ -0,0 +1,288 @@
+<script>
+import UiSectionCard from '@/components/ui/UiSectionCard.vue'
+import tool from '@/utils/tool'
+import { amountFilter } from '@/filters'
+
+const numeric = value =>
+  (typeof value === 'number' || (typeof value === 'string' && value.trim() !== '')) &&
+  Number.isFinite(Number(value)) &&
+  Number(value) >= 0
+
+export default {
+  name: 'GuestOrderDetails',
+  components: { UiSectionCard },
+  props: { order: { type: Object, required: true }, items: { type: Array, default: () => [] }},
+  computed: {
+    currency() {
+      const code = this.order.CURRENCY
+      return typeof code === 'string' && /^[A-Z]{3}$/.test(code) ? code : ''
+    },
+    total() {
+      return this.order.PAY_AMOUNT != null ? this.order.PAY_AMOUNT : this.order.ORDER_AMOUNT
+    },
+    shipping() {
+      return this.order.PAY_FREIGHT != null ? this.order.PAY_FREIGHT : this.order.FREIGHT
+    },
+    tax() {
+      if (
+        !this.items.length ||
+        this.items.some(item => ![item.REAL_PRICE, item.BUY_NUMS, item.TAX_RATE].every(numeric))
+      ) { return null }
+      return (
+        this.items.reduce(
+          (sum, item) =>
+            sum +
+            Math.round(
+              tool.calculateTax(
+                Number(item.REAL_PRICE),
+                Number(item.TAX_RATE),
+                Number(item.BUY_NUMS)
+              ) * 100
+            ),
+          0
+        ) / 100
+      )
+    },
+    status() {
+      const value = this.order.STATUS
+      if (typeof value === 'string' && value.trim() && !numeric(value)) return value
+      // 数字状态的业务含义未经约定,不把下单响应中的 1 推断为已付款。
+      return numeric(value) ? 'Status: ' + value : 'Status unavailable'
+    },
+    statusType() {
+      return /^paid$/i.test(this.status)
+        ? 'success'
+        : /^unpaid$/i.test(this.status)
+          ? 'warning'
+          : 'info'
+    },
+    placedAt() {
+      const value = this.order.CREATED_AT
+      return numeric(value) && Number(value) > 0
+        ? tool.formatDate(value)
+        : typeof value === 'string' && !numeric(value)
+          ? value
+          : '—'
+    },
+    paymentMethod() {
+      return this.order.PAY_TYPE === 'pay_stack' ? 'Paystack' : this.order.PAY_TYPE || '—'
+    },
+    address() {
+      return (
+        this.order.FULL_ADDRESS ||
+        [this.order.ADDRESS, this.order.LGA_NAME, this.order.CITY_NAME]
+          .filter(Boolean)
+          .join(', ') ||
+        '—'
+      )
+    }
+  },
+  methods: {
+    money(value) {
+      return numeric(value)
+        ? (this.currency ? this.currency + ' ' : '') +
+            amountFilter(Math.round(Number(value) * 100) / 100)
+        : '—'
+    },
+    lineTotal(item) {
+      return [item.REAL_PRICE, item.BUY_NUMS].every(numeric)
+        ? Number(item.REAL_PRICE) * Number(item.BUY_NUMS)
+        : null
+    },
+    image(item) {
+      return tool.getArImage(item.COVER, '/files/')
+    }
+  }
+}
+</script>
+
+<template>
+  <div class="ng-guest-order-details">
+    <ui-section-card class="ng-guest-order-overview">
+      <div class="ng-guest-order-heading">
+        <div>
+          <el-tag :type="statusType" size="small">{{ status }}</el-tag>
+          <h2>Order {{ order.SN }}</h2>
+          <p>
+            Placed {{ placedAt }} · {{ items.length }} {{ items.length === 1 ? 'item' : 'items' }}
+          </p>
+        </div>
+        <div class="ng-guest-order-grand-total">
+          <span>Order total</span><strong>{{ money(total) }}</strong>
+        </div>
+      </div>
+    </ui-section-card>
+    <el-row :gutter="24">
+      <el-col :xs="24" :md="16">
+        <ui-section-card :title="'Items (' + items.length + ')'">
+          <div v-for="(item, index) in items" :key="index" class="ng-guest-order-item">
+            <el-image
+              v-if="item.COVER"
+              :src="image(item)"
+              :alt="item.GOODS_TITLE || 'Product'"
+              fit="contain"
+              class="ng-guest-order-image"
+            ><span slot="error">—</span></el-image>
+            <div class="ng-guest-order-item-name">
+              <strong>{{ item.GOODS_TITLE || '—' }}</strong>
+              <p>{{ item.SKU_CODE || '—' }} · {{ money(item.REAL_PRICE) }} each</p>
+            </div>
+            <div class="ng-guest-order-item-amount">
+              <span>×{{ item.BUY_NUMS == null ? '—' : item.BUY_NUMS }}</span><strong>{{ money(lineTotal(item)) }}</strong>
+            </div>
+          </div>
+          <p v-if="!items.length">Item details are unavailable.</p>
+          <dl class="ng-guest-order-totals">
+            <div>
+              <dt>Subtotal</dt>
+              <dd>{{ money(order.ORDER_AMOUNT) }}</dd>
+            </div>
+            <div>
+              <dt>Shipping</dt>
+              <dd>{{ money(shipping) }}</dd>
+            </div>
+            <div>
+              <dt>Tax (included)</dt>
+              <dd>{{ money(tax) }}</dd>
+            </div>
+            <div class="ng-guest-order-total">
+              <dt>Total</dt>
+              <dd>{{ money(total) }}</dd>
+            </div>
+          </dl>
+          <p v-if="!currency">Currency information is unavailable.</p>
+        </ui-section-card>
+        <ui-section-card title="Delivery">
+          <strong>{{ order.CONSIGNEE || '—' }}</strong>
+          <p class="ng-guest-order-address">
+            {{ order.MOBILE || '—' }}<br>{{ address }}<br>{{ order.COUNTRY || '—' }}
+          </p>
+        </ui-section-card>
+        <ui-section-card title="Payment">
+          <div class="ng-guest-order-payment">
+            <strong>{{ paymentMethod }}</strong><el-tag :type="statusType" size="small">{{ status }}</el-tag>
+          </div>
+          <p>
+            Order reference <strong>{{ order.SN }}</strong>
+          </p>
+        </ui-section-card>
+      </el-col>
+      <el-col :xs="24" :md="8"><slot name="sidebar" /></el-col>
+    </el-row>
+  </div>
+</template>
+
+<style lang="scss" scoped>
+.ng-guest-order-heading,
+.ng-guest-order-item,
+.ng-guest-order-payment {
+  display: flex;
+  align-items: center;
+  justify-content: space-between;
+  gap: 16px;
+  min-width: 0;
+}
+.ng-guest-order-heading {
+  flex-wrap: wrap;
+  margin-bottom: 20px;
+}
+.ng-guest-order-heading h2 {
+  margin: 12px 0;
+  font-size: 24px;
+}
+.ng-guest-order-details p {
+  margin: 12px 0 20px;
+  color: #606266;
+  line-height: 1.6;
+}
+.ng-guest-order-heading p {
+  margin-bottom: 0;
+}
+.ng-guest-order-grand-total {
+  display: grid;
+  gap: 12px;
+  text-align: right;
+}
+.ng-guest-order-grand-total span {
+  font-size: 13px;
+  color: #606266;
+  text-transform: uppercase;
+}
+.ng-guest-order-grand-total strong {
+  font-size: 24px;
+}
+.ng-guest-order-item {
+  justify-content: flex-start;
+  padding: 0 0 20px;
+}
+.ng-guest-order-image {
+  flex: 0 0 56px;
+  width: 56px;
+  height: 56px;
+  border-radius: 4px;
+}
+.ng-guest-order-item-name {
+  flex: 1;
+  min-width: 0;
+}
+.ng-guest-order-item-name p {
+  margin: 8px 0 0;
+  font-size: 13px;
+}
+.ng-guest-order-item-amount {
+  display: flex;
+  align-items: center;
+  gap: 16px;
+  text-align: right;
+}
+.ng-guest-order-item-amount span {
+  font-size: 13px;
+  color: #606266;
+}
+.ng-guest-order-totals {
+  border-top: 1px solid #dfe4eb;
+  padding-top: 12px;
+  margin: 0 0 20px;
+}
+.ng-guest-order-totals > div {
+  display: flex;
+  justify-content: space-between;
+  gap: 16px;
+  padding: 8px 0;
+}
+.ng-guest-order-totals dt {
+  color: #606266;
+}
+.ng-guest-order-totals dd {
+  margin: 0;
+  text-align: right;
+}
+.ng-guest-order-totals .ng-guest-order-total {
+  margin-top: 8px;
+  border-top: 1px solid #dfe4eb;
+  padding-top: 16px;
+  font-weight: 700;
+}
+.ng-guest-order-total dt {
+  color: inherit;
+}
+.ng-guest-order-address {
+  white-space: pre-line;
+}
+@media (max-width: 767px) {
+  .ng-guest-order-heading h2 {
+    font-size: 20px;
+  }
+  .ng-guest-order-grand-total {
+    text-align: left;
+  }
+  .ng-guest-order-item {
+    flex-wrap: wrap;
+    gap: 12px;
+  }
+  .ng-guest-order-item-amount {
+    flex-basis: 100%;
+    justify-content: space-between;
+  }
+}
+</style>

+ 165 - 47
src/ui-refactor/views/guest-shop/GuestOrderPage.vue

@@ -1,71 +1,189 @@
-<template>
-  <section class="ng-guest-order">
-    <el-breadcrumb
-      separator="/"
-    ><el-breadcrumb-item :to="{ path: '/login' }">Home</el-breadcrumb-item><el-breadcrumb-item>Order details</el-breadcrumb-item></el-breadcrumb>
-    <h1>Order details</h1>
-    <el-card shadow="never">
-      <h2>{{ order ? 'Order ' + order : 'Order reference unavailable' }}</h2>
-      <el-alert
-        title="Order details are not available yet. Please keep your order number and contact customer service if you need assistance."
-        type="info"
-        :closable="false"
-        show-icon
-      />
-    </el-card>
-    <el-row :gutter="24" class="ng-guest-order-sections">
-      <el-col
-        v-for="section in sections"
-        :key="section"
-        :xs="24"
-        :md="section === 'Items' ? 16 : 8"
-      >
-        <el-card
-          shadow="never"
-        ><h2>{{ section }}</h2>
-          <p>—</p></el-card>
-      </el-col>
-    </el-row>
-    <el-button type="primary" @click="$router.push('/login')">Back to sign in</el-button>
-  </section>
-</template>
-
 <script>
+import { fetchGuestOrderDetail, downloadGuestOrder, downloadOrder } from '@/api/shop'
+import handleClipboard from '@/utils/clipboard'
+import usersInfo from '@/utils/usersInfo'
+import UiSectionCard from '@/components/ui/UiSectionCard.vue'
+import GuestOrderDetails from './GuestOrderDetails.vue'
+
 export default {
   name: 'GuestOrderPage',
+  components: { UiSectionCard, GuestOrderDetails },
   data() {
-    return { sections: ['Items', 'Order total', 'Delivery', 'Payment'] }
+    return { detail: null, loading: false, failed: false, downloading: false, receiptError: '' }
   },
   computed: {
     order() {
-      return typeof this.$route.query.order === 'string' ? this.$route.query.order : ''
+      return typeof this.$route.query.order === 'string' ? this.$route.query.order.trim() : ''
+    },
+    orderLink() {
+      const { href } = this.$router.resolve({ path: '/guest-order', query: { order: this.order }})
+      return new URL(href, window.location.href).href
+    }
+  },
+  watch: { order: { immediate: true, handler: 'loadOrder' }},
+  beforeDestroy() {
+    this.requestVersion++
+  },
+  methods: {
+    async loadOrder() {
+      const version = (this.requestVersion = (this.requestVersion || 0) + 1)
+      this.detail = null
+      this.failed = false
+      this.receiptError = ''
+      this.downloading = false
+      this.loading = Boolean(this.order)
+      if (!this.order) return
+      try {
+        const { data } = await fetchGuestOrderDetail({ orderSn: this.order })
+        if (version !== this.requestVersion) return
+        if (!data || !data.order || data.order.SN !== this.order) { throw new Error('Unexpected order reference') }
+        this.detail = { order: data.order, goods: Array.isArray(data.goods) ? data.goods : [] }
+      } catch (error) {
+        if (version === this.requestVersion) this.failed = true
+      } finally {
+        if (version === this.requestVersion) this.loading = false
+      }
+    },
+    copyLink(event) {
+      handleClipboard(this.orderLink, event)
+    },
+    async downloadReceipt() {
+      if (!this.detail || this.downloading) return
+      const version = this.requestVersion
+      this.downloading = true
+      this.receiptError = ''
+      try {
+        const download = usersInfo.accessToken() ? downloadOrder : downloadGuestOrder
+        const { data } = await download(this.detail.order.SN)
+        if (version !== this.requestVersion) return
+        if (!data || typeof data.fileUrl !== 'string' || !data.fileUrl.trim()) { throw new Error('Receipt unavailable') }
+        const base = process.env.VUE_APP_BASE_DO_API || window.location.origin
+        const url = new URL(data.fileUrl, base.replace(/\/$/, '') + '/')
+        if (!['https:', 'http:'].includes(url.protocol)) throw new Error('Invalid receipt URL')
+        const link = document.createElement('a')
+        link.href = url.href
+        link.target = '_blank'
+        link.rel = 'noopener noreferrer'
+        link.download = data.targetName || this.detail.order.SN + '.pdf'
+        link.click()
+      } catch (error) {
+        if (version === this.requestVersion) {
+          this.receiptError =
+            'Receipt download is unavailable. Please try again or contact customer service with your order number.'
+        }
+      } finally {
+        if (version === this.requestVersion) this.downloading = false
+      }
     }
   }
 }
 </script>
 
+<template>
+  <section class="ng-guest-order" :aria-busy="loading">
+    <el-breadcrumb separator="/">
+      <el-breadcrumb-item :to="{ path: '/login' }">Home</el-breadcrumb-item>
+      <el-breadcrumb-item>Order details</el-breadcrumb-item>
+    </el-breadcrumb>
+    <h1>Order details</h1>
+    <p class="ng-guest-order-intro">
+      Reference for your Elken purchase. Shareable via the link below.
+    </p>
+    <ui-section-card v-if="loading" aria-live="polite">
+      <p><i class="el-icon-loading" aria-hidden="true" /> Loading order details…</p>
+    </ui-section-card>
+    <ui-section-card v-else-if="!detail" aria-live="polite">
+      <h2>{{ order ? 'Order ' + order : 'Order reference unavailable' }}</h2>
+      <el-alert
+        :title="
+          failed
+            ? 'Unable to load this order. Please check the link or try again.'
+            : 'Open the order link provided after checkout to view your order.'
+        "
+        type="info"
+        :closable="false"
+        show-icon
+      />
+      <el-button
+        v-if="failed"
+        class="ng-guest-order-retry"
+        native-type="button"
+        @click="loadOrder"
+      >Retry</el-button>
+    </ui-section-card>
+    <guest-order-details v-else :order="detail.order" :items="detail.goods">
+      <template slot="sidebar">
+        <ui-section-card title="Receipt">
+          <p>Download a copy of your order receipt for your records.</p>
+          <el-button
+            class="ng-guest-order-action"
+            type="primary"
+            icon="el-icon-download"
+            aria-label="Download receipt"
+            :loading="downloading"
+            native-type="button"
+            @click="downloadReceipt"
+          >Download receipt</el-button>
+          <p v-if="receiptError" class="ng-guest-order-error" role="alert">{{ receiptError }}</p>
+        </ui-section-card>
+        <ui-section-card title="Order details link">
+          <el-input
+            :value="orderLink"
+            readonly
+            aria-label="Order details link"
+            @focus="$event.target.select()"
+          />
+          <el-button
+            class="ng-guest-order-action"
+            native-type="button"
+            icon="el-icon-document-copy"
+            aria-label="Copy"
+            @click="copyLink"
+          >Copy</el-button>
+          <p>This link is stored in your browser, so it only opens on this device. Send it to your email to keep a copy — your email app opens with the message pre-filled. (Static demo: no server-side email is sent.)</p>
+        </ui-section-card>
+      </template>
+    </guest-order-details>
+    <el-button
+      type="text"
+      native-type="button"
+      icon="el-icon-back"
+      @click="$router.push('/login')"
+    >Back to home</el-button>
+  </section>
+</template>
+
 <style lang="scss" scoped>
+.ng-guest-order {
+  min-width: 0;
+  padding: 8px 0 32px;
+  color: #202259;
+  overflow-wrap: anywhere;
+}
 .ng-guest-order h1 {
-  margin: 32px 0;
+  margin: 28px 0 12px;
   font-size: 32px;
+  line-height: 1.2;
 }
 .ng-guest-order h2 {
+  font-size: 20px;
+}
+.ng-guest-order p {
   margin: 0 0 20px;
-  font-size: 18px;
-  overflow-wrap: anywhere;
+  color: #606266;
+  line-height: 1.6;
 }
-.ng-guest-order .el-card {
-  margin-bottom: 24px;
-  border-radius: 10px;
+.ng-guest-order .ng-guest-order-intro {
+  margin-bottom: 28px;
 }
-.ng-guest-order-sections {
-  display: flex;
-  flex-wrap: wrap;
+.ng-guest-order .ng-guest-order-error {
+  color: #f56c6c;
 }
-.ng-guest-order-sections .el-card {
-  min-height: 140px;
+.ng-guest-order-action {
+  width: 100%;
+  margin: 16px 0 20px;
 }
-.ng-guest-order-sections p {
-  color: #909399;
+.ng-guest-order-retry {
+  margin: 20px 0;
 }
 </style>

+ 15 - 7
src/ui-refactor/views/guest-shop/README.md

@@ -6,24 +6,26 @@
 
 - 登录页 Shop now 打开 `MarketDialog`,固定 Nigeria(`620699181539139625`)与 UAE(`620699181539139643`),不改变注册页选项。支持键盘 Enter / Space 打开、Escape 关闭与焦点恢复。
 - `GuestShopPage` 负责路由与离开保护;`GuestPurchaseFlow` 组合既有购买展示,`guestPurchase.js` 负责匿名请求与本次访问的业务状态。会员和游客的购物车列表统一使用 `purchase/CartItems.vue`,`GuestCart` 只转发属性与事件。收货地址统一由既有 `purchase/CheckoutFields.vue` 渲染,`GuestCheckoutFields` 只保留游客必填校验与表单封装;`guest` 展示参数隐藏会员信息并对应匿名地址字段。商品卡片、详情、订单摘要通过 `showBv=false` 隐藏游客 BV;会员默认行为保持。
-- `/guest-shop/ng`、`/guest-shop/ae` 各有 `/cart`、`/checkout`。六条购物路由与 `/guest-order` 精确加入匿名白名单,隐藏 header,保留原 footer;仅商品页展示国家 Hero。会员路径仍受保护。
+- `/guest-shop/ng`、`/guest-shop/ae` 各有 `/cart`、`/checkout`。六条购物路由与 `/guest-order` 精确加入匿名白名单,保留原 footer;购物路由隐藏 header,订单详情通过 `showHeader: 'authenticated'` 在已登录时显示原 header、游客访问时隐藏。仅商品页展示国家 Hero。会话校验仍由原路由守卫负责,会员路径仍受保护。
 - 购物车跨分页和购物步骤保留;切换国家重建状态,刷新不恢复购物车。游客邮箱、地址、未付单不写入 LocalStorage、SessionStorage、Vuex 或会员缓存。
 
 ## API 与支付约定
 
-三个方法追加到 `src/api/shop.js`:
+游客方法在 `src/api/shop.js` 中维护:
 
 | 方法 | 请求 |
 | --- | --- |
 | fetchGuestProducts | GET `/v1/shop/no-login-reconsume`,countryId / categoryType / page / limit |
 | fetchGuestCart | GET `/v1/shop/no-login-show-cart`,countryId / categoryType |
 | createGuestOrder | POST `/v1/shop/no-login-reconsume-sure-order` |
+| fetchGuestOrderDetail | GET `/v1/shop/no-login-order-detail`,orderSn |
+| downloadGuestOrder | GET `/v1/shop/no-login-order-export/{orderSn}`,游客收据下载 |
 
 列表沿用 `list / totalCount`,结算沿用 `sellType / freight / freeShipping / coin`。支付选项及顺序取分类 1 的 `sell_type`,默认第一项;无可用结算配置时阻止提交并提供重试。游客地区通过 `src/api/config.js` 的 `getGuestRegionList({countryId})` 请求 `GET /v1/config/no-login-region-list`,Nigeria / UAE 均传对应字符串国家 ID;会员仍使用原 `getRegionList` 与 `/v1/config/region-list`,不写死地区数据。
 
 下单只发送 `countryId / goodsId / goodsNum / email / payType / consignee / acceptMobile / province / lgaName / cityName / detailaddress`。手机号区号跟随国家显示,`acceptMobile` 仍传用户输入值,`province` 保留地区路径数组。不发送会员编号、报单中心、支付密码或会员地址 ID。
 
-游客商品卡片、购物车单价/行金额、结账汇总与税额统一使用接口 `MARKET_PRICE`,不套用会员销售价或折扣;保留原含税算法及免运费阈值,税不再叠加到应付金额。游客和注册详情隐藏 Sales Price,登录后的展示与计价保持原样。商品、购物车和结账展示优先使用商品 `COIN`,结算配置的 `coin` 只作兜底;两个 GET 的返回顺序不影响商品币种。Place order 先验证地址,再确认邮箱,最后下单。非 Paystack 以匿名下单成功返回的 SN 进入公开详情骨架。
+游客商品卡片、购物车单价/行金额、结账汇总与税额统一使用接口 `MARKET_PRICE`,不套用会员销售价或折扣;保留原含税算法及免运费阈值,税不再叠加到应付金额。游客和注册详情隐藏 Sales Price,登录后的展示与计价保持原样。商品、购物车和结账展示优先使用商品 `COIN`,结算配置的 `coin` 只作兜底;两个 GET 的返回顺序不影响商品币种。Place order 先验证地址,再确认邮箱,最后下单。非 Paystack 以匿名下单成功返回的 SN 进入公开详情页。
 
 匿名下单实际可返回订单记录 `SN / PAY_AMOUNT / ORDER_AMOUNT / COUNTRY_ID / CURRENCY_ID`:金额优先取 `PAY_AMOUNT`,缺失时取 `ORDER_AMOUNT`,不使用 `_STANDARD` 字段或 `EXCHANGE_RATE` 换算。订单未返回 ISO 币种代码时,必须先核对 `COUNTRY_ID` 和当前国家,再用 `CURRENCY_ID` 匹配所选商品的 `LOCAL_CURRENCY_ID`,使用该商品的 `COIN`;无法匹配时保留订单并阻止支付。继续兼容原 `SN / amount / currency`,显式返回的 `amount / currency` 优先。返回 `EMAIL` 为空时仍使用表单内已确认的邮箱。
 
@@ -31,7 +33,11 @@
 
 请求期间防止重复提交。关闭支付保留 SN,重开只恢复支付,不重复 POST,也不调用会员取消接口;未付单存在时锁定商品、地址、邮箱和支付方式。异步响应和 SDK 回调受组件生命周期与本次支付序号约束。
 
-`/guest-order?order=<SN>` 仅显示真实订单号和待接入提示,商品、金额、配送和支付为骨架。无详情请求、物流、下载、分享或本地收据;前端回调不作为服务端付款确认。
+`/guest-order?order=<SN>` 在进入、刷新和订单参数变化时调用匿名详情接口,传 `orderSn`,响应为 `{ order, goods }`。订单号必须与请求一致;加载中清除旧明细,失败可重试,离开页面或更换订单后忽略旧响应。`GuestOrderPage` 管理请求、下载与复制,`GuestOrderDetails` 负责展示;卡片复用 `UiSectionCard`,图片、按钮和状态使用 Element UI。
+
+详情以 `order.CURRENCY / PAY_AMOUNT / ORDER_AMOUNT / PAY_FREIGHT / FREIGHT / STATUS / CREATED_AT / PAY_TYPE / CONSIGNEE / MOBILE / FULL_ADDRESS / COUNTRY` 展示,配送地址缺失时使用已有 `ADDRESS / LGA_NAME / CITY_NAME`,不把 `PROVINCE` 地区 ID 当名称。`goods` 沿用会员订单商品的 `GOODS_TITLE / SKU_CODE / COVER / REAL_PRICE / BUY_NUMS / TAX_RATE`。商品为空显示暂无明细;缺失金额和地址显示 `—`,不会补成零。税额按原含税算法展示,不再次加到接口金额;总额优先 `PAY_AMOUNT`。支付状态只取详情接口,数字状态不推断为 Paid,前端支付回调和 URL 参数均不能改变状态;不显示会员身份、PV 或 BV。
+
+复制链接使用当前访问地址和 Vue Router 解析后的路径,自动适配测试/生产域名、部署目录与 Hash 路由;复用既有 clipboard 工具。下载根据现有登录状态选择接口:游客使用 `GET /v1/shop/no-login-order-export/{orderSn}`,已登录使用原 `downloadOrder` 与 `/v1/shop/order-export/{orderSn}`;两者沿用 `fileUrl / targetName` 返回字段。游客调用中的 HTTP 401 留给页面处理,避免会员请求拦截器清缓存并跳回登录;不修改全局拦截器或会员导出方法。下载支持失败重试、阻止重复请求并忽略离开后的响应。不缓存本地订单,不提供邮件发送、物流查询或前端生成收据。
 
 ## 验证
 
@@ -44,7 +50,7 @@ $env:NODE_PATH='C:\Users\Administrator\.cache\codex-runtimes\codex-primary-runti
 & 'C:\Users\Administrator\.cache\codex-runtimes\codex-primary-runtime\dependencies\node\bin\node.exe' src/ui-refactor/views/guest-shop/__tests__/verify.cjs "$env:TEMP/ng-guest-shop-final"
 ```
 
-浏览器只访问临时构建,所有商品、地区、订单和 SDK 都是显式隔离样例,未配置请求一律阻止。检查 320 / 375 / 768 / 1024 / 1440px 和短视口,共 66 组布局,并覆盖键盘、空购物车刷新、会员守卫、邮箱、支付金额变化、取消重开和成功跳转。
+浏览器只访问临时构建,所有商品、地区、订单和 SDK 都是显式隔离样例,未配置请求一律阻止。检查 320 / 375 / 768 / 1024 / 1440px 和短视口,并覆盖键盘、空购物车刷新、会员守卫、邮箱、支付金额变化、取消重开和成功跳转。订单详情检查包含刷新查询、服务端状态、空商品、失败重试、缺失订单号、环境链接复制和收据成功/401 两条路径。
 
 实施前基线:305 项,293 通过、12 项既有失败。新增游客检查为 53 项;既有失败包含四项 Tax 展示、订单地址/分页、资料开关、网络深度、余额 Reset、主题约束和团队支持按钮断言。原断言未放宽;登录回归只新增 MarketDialog 的依赖隔离,不改变登录行为断言。
 
@@ -74,8 +80,10 @@ $env:NODE_PATH='C:\Users\Administrator\.cache\codex-runtimes\codex-primary-runti
 
 ## 交付限制
 
+2026-10-23 订单详情接入:匿名 GET 已用用户提供的订单号确认返回 `{ order, goods }`、`STATUS=Paid`、`CURRENCY=NGN`,该订单实际 `goods=[]`。未保存真实收件人、电话或地址作为测试资料。详情和收据新增 23 项回归;游客相关 109 项通过,全量 UI 414 项通过、与修改前完全相同的 12 项既有失败,无新增加载错误。定向 lint、生产构建、108 组隔离浏览器布局与交互检查通过;6/6 详情保护故障注入在临时副本被捕获。未执行真实下单或 Paystack 扣款。当时原会员导出接口匿名实测返回 401;后续已按用户提供的匿名导出接口接入,见上方最新接口约定。
+
 2026-10-23 未登录计价修正验证:新增 25 项回归通过;全量 UI 回归 391 项通过、相同 12 项既有失败。定向 lint、生产构建、90 组隔离浏览器布局检查通过,覆盖 Nigeria/UAE 与注册的市场价卡片、详情和游客购物步骤;会员原价格及 Sales Price 展示有独立回归。6/6 价格与展示故障注入被捕获,使用临时源码副本,没有修改运行中的源码。未执行真实注册、下单或支付。
 
-- 未进行真实后端、真实订单、实际 Paystack 扣款或服务端付款确认。匿名 API、地区访问权限、可用支付方式、支付币种与 SN / amount / currency 响应仍须在授权测试环境联调。
-- 没有匿名详情或订单状态接口,刷新后不能恢复未付单,无法查询网络中断时的下单结果;接口须负责最终计价、库存与订单幂等,前端不宣称提供服务端幂等保证。
+- 除本轮匿名详情 GET 与导出权限检查外,未进行真实下单、实际 Paystack 扣款或支付确认。可用支付方式、支付币种与服务端最终计价仍须在授权测试环境联调。
+- 详情支持通过订单号刷新查询,但不能恢复购物步骤中的未付单支付上下文;没有收到订单号时,无法查询网络中断时的下单结果。接口须负责最终计价、库存与订单幂等,前端不宣称提供服务端幂等保证。
 - 本轮核对 469 个既有文件(包含未跟踪文件和根环境/lockfile);只改动登录入口、shop API、路由、白名单、四个共用展示组件、商品卡片和登录测试依赖设置,未删除文件。未提交、推送或部署。

+ 96 - 3
src/ui-refactor/views/guest-shop/__tests__/verifyBrowser.cjs

@@ -16,6 +16,11 @@ const checks = []
 const errors = []
 const unknown = []
 const orders = []
+const detailRequests = []
+const receiptRequests = []
+let receiptUnauthorized = true
+let detailMode = 'items'
+const expectedHttpErrors = new Set()
 const ids = { ng: '620699181539139625', ae: '620699181539139643' }
 const art = '<svg xmlns="http://www.w3.org/2000/svg" width="160" height="160"><rect width="160" height="160" fill="#f4f6f8"/><rect x="55" y="18" width="50" height="125" rx="8" fill="#e9f4f8"/><rect x="60" y="65" width="40" height="45" fill="#202259"/></svg>'
 
@@ -49,6 +54,29 @@ async function main() {
             allGoods: [{ ID: 'P1', GOODS_NAME: 'Sample registration product', GOODS_NO: 'SKU1', COVER: 'guest-fixture.png', SELL_PRICE: 100, MARKET_PRICE: 120, PRICE_PV: 20, STORE_NUMS: 5, TAX_RATE: 7.5, CODE: 'NGN' }],
             allOpenBank: [], region: [], decLevel: [], isDec: '0', payList: [{ label: 'pay_stack', name: 'Paystack' }]
           }
+        } else if (api === '/v1/shop/no-login-order-detail') {
+          assert.equal(request.method(), 'GET')
+          const sn = url.searchParams.get('orderSn')
+          assert(sn && sn.startsWith('SAMPLE-ORDER-'))
+          detailRequests.push(sn)
+          if (detailMode === 'error') return route.fulfill({ contentType: 'application/json', body: JSON.stringify({ success: false, message: 'Sample query failure' }) })
+          data = {
+            order: { SN: sn, STATUS: 'Unpaid', CURRENCY: 'NGN', CREATED_AT: 1792000000, ORDER_AMOUNT: '120.00', PAY_AMOUNT: '130.00', PAY_FREIGHT: '10.00', CONSIGNEE: 'Sample recipient', MOBILE: '+234123456789', FULL_ADDRESS: 'Sample street, Lagos', COUNTRY: 'Nigeria', PAY_TYPE: 'Paystack', USER_NAME: 'PRIVATE-MEMBER', SHOW_BV: true },
+            goods: [{ GOODS_TITLE: 'Sample ordered product', SKU_CODE: 'SAMPLE-SKU', COVER: 'guest-fixture.png', REAL_PRICE: '120.00', BUY_NUMS: 1, TAX_RATE: 7.5 }]
+          }
+          if (detailMode === 'empty') {
+            data.goods = []
+            Object.assign(data.order, { STATUS: 'Paid', ORDER_AMOUNT: '2999000.00', PAY_AMOUNT: '2999000.00', FULL_ADDRESS: '', CONSIGNEE: '', MOBILE: '' })
+          }
+        } else if (api.startsWith('/v1/shop/no-login-order-export/') || api.startsWith('/v1/shop/order-export/')) {
+          assert.equal(request.method(), 'GET')
+          receiptRequests.push(api)
+          assert.equal(Boolean(request.headers().authorization), api.startsWith('/v1/shop/order-export/'), 'Receipt endpoint must follow the current session')
+          if (receiptUnauthorized) {
+            expectedHttpErrors.add(url.href)
+            return route.fulfill({ status: 401, contentType: 'application/json', body: JSON.stringify({ status: 401, code: 0, message: 'Unauthorized' }) })
+          }
+          data = { fileUrl: origin + '/sample-receipt.pdf', targetName: 'sample-receipt.pdf' }
         } else if (api === '/v1/shop/no-login-reconsume-sure-order') {
           assert.equal(request.method(), 'POST')
           const params = request.postDataJSON()
@@ -62,6 +90,7 @@ async function main() {
         return route.fulfill({ contentType: 'application/json', body: JSON.stringify({ success: true, data: { data }}) })
       }
       if (request.resourceType() === 'image' && url.origin !== origin) return route.fulfill({ contentType: 'image/svg+xml', body: art })
+      if (url.href === origin + '/sample-receipt.pdf') return route.fulfill({ contentType: 'application/pdf', headers: { 'Content-Disposition': 'attachment; filename="sample-receipt.pdf"' }, body: '%PDF-1.4\n%%EOF' })
       if (url.origin === origin) return route.continue()
       unknown.push(url.origin + url.pathname)
       return route.abort()
@@ -69,7 +98,7 @@ async function main() {
     const page = await context.newPage()
     page.setDefaultTimeout(10000)
     page.on('pageerror', error => errors.push(error.message))
-    page.on('console', message => { if (message.type() === 'error') errors.push(message.text()) })
+    page.on('console', message => { if (message.type() === 'error' && !expectedHttpErrors.has(message.location().url)) errors.push(message.text()) })
     const layouts = async(label, dialog = false) => {
       for (const [width, height] of viewports) {
         await page.setViewportSize({ width, height })
@@ -79,7 +108,7 @@ async function main() {
           const box = await page.locator('.el-dialog:visible').boundingBox()
           assert(box && box.x >= 0 && box.x + box.width <= width + 1, label + ' dialog overflow')
         }
-        if (width === 375 && height === 812 && /checkout|email|market/.test(label)) await page.screenshot({ path: path.join(output, label + '-mobile.png'), fullPage: true, animations: 'disabled' })
+        if (width === 375 && height === 812 && /checkout|email|market|order/.test(label)) await page.screenshot({ path: path.join(output, label + '-mobile.png'), fullPage: true, animations: 'disabled' })
         checks.push({ label, width, height })
       }
       await page.setViewportSize({ width: 1440, height: 900 })
@@ -160,9 +189,48 @@ async function main() {
       assert.equal(orders.length, before, 'Resuming payment must not create another order')
       await page.evaluate(() => window.samplePayment.callback({ reference: window.samplePayment.ref }))
       await page.waitForURL(/guest-order\?order=SAMPLE-ORDER-/)
-      assert((await page.locator('.ng-guest-order').textContent()).includes('Order details are not available yet'))
+      await page.getByText('Sample ordered product', { exact: true }).waitFor()
+      const orderText = await page.locator('.ng-guest-order').textContent()
+      assert(orderText.includes('NGN 130.00') && orderText.includes('Unpaid'), 'SDK success must not replace server payment status')
+      assert(!orderText.includes('PRIVATE-MEMBER') && !orderText.includes('BV'))
+      assert.equal(await page.locator('.ng-public-header').count(), 0)
       await layouts(market + '-order')
+      const detailCount = detailRequests.length
+      await page.reload()
+      await page.getByText('Sample ordered product', { exact: true }).waitFor()
+      assert.equal(detailRequests.length, detailCount + 1, 'Refresh must load the order from the API')
+      await context.grantPermissions(['clipboard-read', 'clipboard-write'], { origin })
+      await page.getByRole('button', { name: 'Copy', exact: true }).focus()
+      await page.keyboard.press('Enter')
+      assert.equal(await page.evaluate(() => navigator.clipboard.readText()), page.url(), 'Copied link must follow the current environment')
+      await page.getByRole('button', { name: 'Download receipt', exact: true }).click()
+      await page.getByRole('alert').filter({ hasText: 'Receipt download is unavailable' }).waitFor()
+      assert(page.url().includes('/guest-order?order='), 'Receipt 401 must not redirect to login')
+      receiptUnauthorized = false
+      const downloadPromise = page.waitForEvent('download')
+      await page.getByRole('button', { name: 'Download receipt', exact: true }).click()
+      assert.equal((await downloadPromise).suggestedFilename(), 'sample-receipt.pdf')
+      receiptUnauthorized = true
     }
+    detailMode = 'empty'
+    await page.goto(origin + '/#/guest-order?order=SAMPLE-ORDER-EMPTY')
+    await page.getByText('Item details are unavailable.', { exact: true }).waitFor()
+    assert((await page.locator('.ng-guest-order-grand-total').textContent()).includes('NGN 2,999,000.00'))
+    assert.equal(await page.locator('.ng-guest-order-overview .el-tag--success').count(), 1)
+    await layouts('empty-order')
+    detailMode = 'error'
+    await page.goto(origin + '/#/guest-order?order=SAMPLE-ORDER-ERROR')
+    await page.getByRole('button', { name: 'Retry', exact: true }).waitFor()
+    assert.equal(await page.locator('.ng-guest-order-details').count(), 0)
+    await layouts('failed-order')
+    detailMode = 'items'
+    await page.getByRole('button', { name: 'Retry', exact: true }).click()
+    await page.getByText('Sample ordered product', { exact: true }).waitFor()
+    const requestCount = detailRequests.length
+    await page.goto(origin + '/#/guest-order')
+    await page.getByText('Order reference unavailable', { exact: true }).waitFor()
+    assert.equal(detailRequests.length, requestCount)
+    await layouts('missing-order')
     await page.goto(origin + '/#/signup')
     await page.locator('#ng-signup-SignupPagevue-0').click()
     await page.getByText('Nigeria', { exact: true }).click()
@@ -182,6 +250,31 @@ async function main() {
     await page.goto(origin + '/#/dashboard/repeat-purchase')
     await page.waitForURL(/#\/login/)
     assert.equal(await page.evaluate(() => localStorage.getItem('accessToken')), null)
+    // 仅隔离浏览器里的样例会话;外网仍由上面的请求白名单完全拦截。
+    await page.evaluate(() => {
+      const now = String(Math.floor(Date.now() / 1000))
+      localStorage.setItem('accessToken', 'sample-session')
+      localStorage.setItem('accessTokenExpiresIn', '86400')
+      localStorage.setItem('accessTokenUpdateAt', now)
+      localStorage.setItem('refreshToken', 'sample-refresh')
+      localStorage.setItem('refreshTokenExpiresIn', '86400')
+      localStorage.setItem('refreshTokenUpdateAt', now)
+    })
+    await page.goto(origin + '/#/guest-order?order=SAMPLE-ORDER-SIGNED-IN')
+    await page.getByText('Sample ordered product', { exact: true }).waitFor()
+    assert.equal(await page.locator('.ng-public-header').count(), 1, 'Signed-in order details must retain the header')
+    await layouts('signed-in-order')
+    receiptUnauthorized = false
+    const memberReceipt = page.waitForEvent('download')
+    await page.getByRole('button', { name: 'Download receipt', exact: true }).click()
+    assert.equal((await memberReceipt).suggestedFilename(), 'sample-receipt.pdf')
+    assert.equal(receiptRequests[receiptRequests.length - 1], '/v1/shop/order-export/SAMPLE-ORDER-SIGNED-IN')
+    await page.evaluate(() => {
+      for (const key of ['accessToken', 'accessTokenExpiresIn', 'accessTokenUpdateAt', 'refreshToken', 'refreshTokenExpiresIn', 'refreshTokenUpdateAt']) localStorage.removeItem(key)
+    })
+    await page.reload()
+    await page.getByText('Sample ordered product', { exact: true }).waitFor()
+    assert.equal(await page.locator('.ng-public-header').count(), 0, 'Anonymous order details must keep the header hidden')
     assert.deepEqual(unknown, [])
     assert.deepEqual(errors, [])
     fs.writeFileSync(path.join(output, 'results.json'), JSON.stringify({ checks, orders: orders.length, errors, unknown }, null, 2))

+ 1 - 1
src/ui-refactor/views/guest-shop/routes.js

@@ -37,7 +37,7 @@ guestRoutes.push({
   path: '/guest-order',
   name: 'GuestOrder',
   component: () => import('./GuestOrderPage.vue'),
-  meta: { title: 'Order details', publicLayout: { showHeader: false }}
+  meta: { title: 'Order details', publicLayout: { showHeader: 'authenticated' }}
 })
 
 export const guestPaths = guestRoutes.map(route => route.path)

+ 18 - 1
tests/unit/ui-refactor/guestShopApi.spec.js

@@ -1,6 +1,6 @@
 /* eslint-env jest */
 import request from '@/utils/request'
-import { fetchGuestProducts, fetchGuestCart, createGuestOrder } from '@/api/shop'
+import { fetchGuestProducts, fetchGuestCart, createGuestOrder, fetchGuestOrderDetail, downloadGuestOrder, downloadOrder } from '@/api/shop'
 import { getGuestRegionList, getRegionList } from '@/api/config'
 jest.mock('@/utils/request', () => jest.fn())
 it.each([[fetchGuestProducts, '/v1/shop/no-login-reconsume'], [fetchGuestCart, '/v1/shop/no-login-show-cart']])('calls the anonymous GET endpoint without modifying the country ID', (api, url) => {
@@ -23,3 +23,20 @@ it('keeps member region queries on the original endpoint', () => {
   getRegionList(params)
   expect(request).toHaveBeenLastCalledWith({ url: '/v1/config/region-list', method: 'get', params })
 })
+it('queries anonymous order details using orderSn', () => {
+  const params = { orderSn: 'SAMPLE-ORDER' }
+  fetchGuestOrderDetail(params)
+  expect(request).toHaveBeenLastCalledWith({ url: '/v1/shop/no-login-order-detail', method: 'get', params })
+})
+it('uses anonymous receipt export while handling an anonymous 401 on the page', () => {
+  downloadGuestOrder('SAMPLE/ORDER')
+  const config = request.mock.calls[request.mock.calls.length - 1][0]
+  expect(config).toMatchObject({ url: '/v1/shop/no-login-order-export/SAMPLE%2FORDER', method: 'get', params: {}})
+  expect(config.validateStatus(200)).toBe(true)
+  expect(config.validateStatus(401)).toBe(true)
+  expect(config.validateStatus(500)).toBe(false)
+})
+it('keeps signed-in receipt export on its original endpoint', () => {
+  downloadOrder('SAMPLE-ORDER')
+  expect(request).toHaveBeenLastCalledWith({ url: '/v1/shop/order-export/SAMPLE-ORDER', method: 'get', params: {}})
+})

+ 314 - 0
tests/unit/ui-refactor/guestShopOrder.spec.js

@@ -0,0 +1,314 @@
+/* eslint-env jest */
+import Vue from 'vue'
+import ElementUI from 'element-ui'
+import path from 'path'
+import { load } from './loadGuestComponent'
+import { fetchGuestOrderDetail, downloadGuestOrder, downloadOrder } from '@/api/shop'
+import handleClipboard from '@/utils/clipboard'
+import usersInfo from '@/utils/usersInfo'
+
+jest.mock('@/api/shop', () => ({ fetchGuestOrderDetail: jest.fn(), downloadGuestOrder: jest.fn(), downloadOrder: jest.fn() }))
+jest.mock('@/utils/clipboard', () => jest.fn())
+jest.mock('@/utils/usersInfo', () => ({ accessToken: jest.fn() }))
+jest.mock('@/router', () => ({ push: jest.fn(), replace: jest.fn() }))
+Vue.use(ElementUI)
+const Order = load(path.resolve('src/ui-refactor/views/guest-shop/GuestOrderPage.vue'))
+const sample = {
+  SN: 'SAMPLE-ORDER',
+  STATUS: 'Unpaid',
+  CREATED_AT: 1792000000,
+  CURRENCY: 'NGN',
+  ORDER_AMOUNT: 38000,
+  PAY_AMOUNT: 38100,
+  PAY_FREIGHT: 100,
+  CONSIGNEE: 'Sample recipient',
+  MOBILE: '+234123456789',
+  FULL_ADDRESS: 'Sample street, Lagos',
+  COUNTRY: 'Nigeria',
+  PAY_TYPE: 'pay_stack',
+  hasChildren: [
+    {
+      GOODS_TITLE: 'Sample product',
+      SKU_CODE: 'SKU-1',
+      COVER: 'sample.png',
+      REAL_PRICE: 19000,
+      BUY_NUMS: 2,
+      TAX_RATE: 7.5
+    }
+  ]
+}
+const response = (order = sample) => ({ data: { order, goods: order.hasChildren || [] }})
+const instances = []
+const errors = []
+Vue.config.errorHandler = error => errors.push(error)
+async function settle() {
+  for (let i = 0; i < 12; i++) {
+    await Promise.resolve()
+    await Vue.nextTick()
+  }
+}
+function mount(order = 'SAMPLE-ORDER') {
+  const route = Vue.observable({ query: { order }})
+  const router = {
+    push: jest.fn(),
+    resolve: jest.fn(() => ({ href: '/app/#/guest-order?order=' + encodeURIComponent(order) }))
+  }
+  const vm = new (Vue.extend(Order))({
+    beforeCreate() {
+      this.$route = route
+      this.$router = router
+    }
+  }).$mount()
+  document.body.appendChild(vm.$el)
+  instances.push(vm)
+  return vm
+}
+beforeEach(() => {
+  jest.clearAllMocks()
+  errors.length = 0
+  usersInfo.accessToken.mockReturnValue('')
+  process.env.VUE_APP_BASE_DO_API = 'https://api.example.test'
+  fetchGuestOrderDetail.mockResolvedValue(response())
+  downloadGuestOrder.mockResolvedValue({
+    data: { fileUrl: 'receipts/sample.pdf', targetName: 'sample.pdf' }
+  })
+  downloadOrder.mockResolvedValue({ data: { fileUrl: 'receipts/member.pdf', targetName: 'member.pdf' }})
+})
+afterEach(() => {
+  instances.splice(0).forEach(vm => {
+    vm.$destroy()
+    vm.$el.remove()
+  })
+  jest.restoreAllMocks()
+  expect(errors).toEqual([])
+})
+it('requests the anonymous detail by the URL reference and renders server data without adding tax', async() => {
+  const vm = mount()
+  await settle()
+  expect(fetchGuestOrderDetail).toHaveBeenCalledWith({ orderSn: 'SAMPLE-ORDER' })
+  const text = vm.$el.textContent
+  for (const value of [
+    'Order SAMPLE-ORDER',
+    'Sample product',
+    'SKU-1',
+    'Sample recipient',
+    '+234123456789',
+    'Sample street, Lagos',
+    'NGN 38,100',
+    'Unpaid',
+    'Paystack'
+  ]) { expect(text).toContain(value) }
+  expect(text).not.toContain('40,950')
+  expect(text).not.toContain('BV')
+})
+it('does not request a missing reference', async() => {
+  const vm = mount('')
+  await settle()
+  expect(fetchGuestOrderDetail).not.toHaveBeenCalled()
+  expect(vm.$el.textContent).toContain('Order reference unavailable')
+})
+it('supports a direct link and a fresh mount without saved receipts', async() => {
+  const storage = jest.spyOn(Storage.prototype, 'setItem')
+  mount()
+  await settle()
+  mount()
+  await settle()
+  expect(fetchGuestOrderDetail).toHaveBeenCalledTimes(2)
+  expect(storage).not.toHaveBeenCalled()
+})
+it('clears old details while querying another order and ignores the older response', async() => {
+  let oldResponse
+  fetchGuestOrderDetail.mockImplementationOnce(
+    () =>
+      new Promise(resolve => {
+        oldResponse = resolve
+      })
+  )
+  const vm = mount()
+  vm.$route.query = { order: 'SECOND-ORDER' }
+  fetchGuestOrderDetail.mockResolvedValue(
+    response({ ...sample, SN: 'SECOND-ORDER', CONSIGNEE: 'New recipient' })
+  )
+  await settle()
+  oldResponse(response())
+  await settle()
+  expect(vm.$el.textContent).toContain('Order SECOND-ORDER')
+  expect(vm.$el.textContent).toContain('New recipient')
+  expect(vm.$el.textContent).not.toContain('Sample recipient')
+})
+it('ignores a response after the page is destroyed', async() => {
+  let finish
+  fetchGuestOrderDetail.mockImplementationOnce(
+    () =>
+      new Promise(resolve => {
+        finish = resolve
+      })
+  )
+  const vm = mount()
+  vm.$destroy()
+  finish(response())
+  await settle()
+  expect(vm.detail).toBeNull()
+})
+it('shows an error with retry and recovers from a failed query', async() => {
+  fetchGuestOrderDetail.mockRejectedValueOnce(new Error('not found'))
+  const vm = mount()
+  await settle()
+  expect(vm.$el.textContent).toContain('Unable to load this order')
+  const retry = [...vm.$el.querySelectorAll('button')].find(button =>
+    button.textContent.includes('Retry')
+  )
+  retry.click()
+  await settle()
+  expect(vm.$el.textContent).toContain('Sample product')
+})
+it('rejects an unexpected order returned for this reference', async() => {
+  fetchGuestOrderDetail.mockResolvedValue(response({ ...sample, SN: 'ANOTHER-ORDER' }))
+  const vm = mount()
+  await settle()
+  expect(vm.$el.textContent).toContain('Unable to load this order')
+  expect(vm.$el.textContent).not.toContain('Sample recipient')
+})
+it('uses the router and current origin for copy links, excluding personal data', async() => {
+  const vm = mount()
+  await settle()
+  const button = [...vm.$el.querySelectorAll('button')].find(
+    button => button.textContent.trim() === 'Copy'
+  )
+  button.click()
+  expect(handleClipboard.mock.calls[0][0]).toBe(
+    window.location.origin + '/app/#/guest-order?order=SAMPLE-ORDER'
+  )
+  expect(vm.$router.resolve).toHaveBeenCalledWith({
+    path: '/guest-order',
+    query: { order: 'SAMPLE-ORDER' }
+  })
+})
+it('downloads through the anonymous receipt endpoint and prevents double clicks', async() => {
+  let complete
+  downloadGuestOrder.mockImplementationOnce(
+    () =>
+      new Promise(resolve => {
+        complete = resolve
+      })
+  )
+  const click = jest.spyOn(HTMLAnchorElement.prototype, 'click').mockImplementation(() => {})
+  const vm = mount()
+  await settle()
+  vm.downloadReceipt()
+  vm.downloadReceipt()
+  expect(downloadGuestOrder).toHaveBeenCalledTimes(1)
+  expect(downloadGuestOrder).toHaveBeenCalledWith('SAMPLE-ORDER')
+  expect(downloadOrder).not.toHaveBeenCalled()
+  complete({ data: { fileUrl: 'receipts/sample.pdf', targetName: 'sample.pdf' }})
+  await settle()
+  expect(click.mock.instances[0].href).toBe('https://api.example.test/receipts/sample.pdf')
+  expect(click.mock.instances[0].rel).toContain('noopener')
+  expect(vm.downloading).toBe(false)
+})
+it('uses the original receipt method for a signed-in visitor', async() => {
+  usersInfo.accessToken.mockReturnValue('sample-session')
+  jest.spyOn(HTMLAnchorElement.prototype, 'click').mockImplementation(() => {})
+  const vm = mount()
+  await settle()
+  await vm.downloadReceipt()
+  expect(downloadOrder).toHaveBeenCalledWith('SAMPLE-ORDER')
+  expect(downloadGuestOrder).not.toHaveBeenCalled()
+})
+it.each([
+  () => Promise.reject(new Error('Unavailable')),
+  () => Promise.resolve({ data: { status: 401, message: 'Unauthorized' }}),
+  () => Promise.resolve({ data: { fileUrl: 'javascript:alert(1)' }})
+])('recovers from receipt errors without navigating away', async response => {
+  downloadGuestOrder.mockImplementation(response)
+  const vm = mount()
+  await settle()
+  await vm.downloadReceipt()
+  expect(vm.$el.textContent).toContain('Receipt download is unavailable')
+  expect(vm.downloading).toBe(false)
+  expect(vm.$router.push).not.toHaveBeenCalled()
+})
+it('does not download or show a stale receipt after switching references', async() => {
+  let complete
+  const click = jest.spyOn(HTMLAnchorElement.prototype, 'click').mockImplementation(() => {})
+  downloadGuestOrder.mockImplementationOnce(
+    () =>
+      new Promise(resolve => {
+        complete = resolve
+      })
+  )
+  const vm = mount()
+  await settle()
+  vm.downloadReceipt()
+  vm.$route.query = { order: 'SECOND-ORDER' }
+  await settle()
+  complete({ data: { fileUrl: 'receipts/sample.pdf' }})
+  await settle()
+  expect(click).not.toHaveBeenCalled()
+})
+it('renders the confirmed order/goods response with an empty goods list and missing address', async() => {
+  fetchGuestOrderDetail.mockResolvedValue({
+    data: {
+      order: {
+        ...sample,
+        ORDER_AMOUNT: '2999000.00',
+        PAY_AMOUNT: '2999000.00',
+        STATUS: 'Paid',
+        FULL_ADDRESS: '',
+        PROVINCE: '1',
+        SHOW_BV: true,
+        USER_NAME: 'PRIVATE-MEMBER'
+      },
+      goods: []
+    }
+  })
+  const vm = mount()
+  await settle()
+  expect(vm.$el.textContent).toContain('NGN 2,999,000')
+  expect(vm.$el.textContent).toContain('Item details are unavailable')
+  expect(vm.$el.textContent).toContain('Paid')
+  expect(vm.$el.textContent).not.toContain('PRIVATE-MEMBER')
+  expect(vm.$el.textContent).not.toContain('BV')
+  expect(vm.$el.querySelector('.ng-guest-order-address').textContent).toContain('—')
+})
+it.each(['Paid', 'Unpaid', 'Cancelled', 1, null])(
+  'uses the server status %s rather than a payment callback or URL flag',
+  async status => {
+    fetchGuestOrderDetail.mockResolvedValue(response({ ...sample, STATUS: status }))
+    const vm = mount()
+    vm.$route.query = { order: 'SAMPLE-ORDER', paid: 'true' }
+    await settle()
+    const tag = vm.$el.querySelector('.el-tag')
+    expect(tag.textContent).toBe(
+      status == null ? 'Status unavailable' : status === 1 ? 'Status: 1' : status
+    )
+    expect(tag.classList.contains('el-tag--success')).toBe(status === 'Paid')
+  }
+)
+it('keeps zero amounts and missing amounts distinct without inventing a currency', async() => {
+  fetchGuestOrderDetail.mockResolvedValue({
+    data: { order: { SN: sample.SN, PAY_AMOUNT: 0, PAY_FREIGHT: 0 }, goods: [] }
+  })
+  const vm = mount()
+  await settle()
+  expect(vm.$el.querySelector('.ng-guest-order-grand-total strong').textContent).toBe('0.00')
+  expect(vm.$el.querySelector('.ng-guest-order-totals dd').textContent).toBe('—')
+  expect(vm.$el.textContent).toContain('Currency information is unavailable')
+  expect(vm.$el.textContent).not.toContain('NGN')
+})
+it('uses the response currency and final amount without exchange or another tax charge', async() => {
+  fetchGuestOrderDetail.mockResolvedValue(
+    response({
+      ...sample,
+      CURRENCY: 'AED',
+      PAY_AMOUNT: '41000.50',
+      PAY_AMOUNT_STANDARD: 10,
+      EXCHANGE_RATE: 1200
+    })
+  )
+  const vm = mount()
+  await settle()
+  expect(vm.$el.querySelector('.ng-guest-order-grand-total strong').textContent).toBe(
+    'AED 41,000.50'
+  )
+})

+ 3 - 2
tests/unit/ui-refactor/guestShopRoutes.spec.js

@@ -22,9 +22,10 @@ it.each(['/dashboard/cart', '/dashboard/checkout', '/shop/member-order', '/guest
   await guard({ path, meta: {}}, {}, next)
   expect(next).toHaveBeenCalledWith('/login?redirect=' + path)
 })
-it('hides the header on every guest route and sets country-specific catalog heroes only', () => {
+it('hides shopping headers, uses the existing session for order details and sets catalog heroes only', () => {
   expect(guestPaths).toHaveLength(7)
-  guestRoutes.forEach(route => expect(route.meta.publicLayout.showHeader).toBe(false))
+  guestRoutes.filter(route => route.path !== '/guest-order').forEach(route => expect(route.meta.publicLayout.showHeader).toBe(false))
+  expect(guestRoutes.find(route => route.path === '/guest-order').meta.publicLayout.showHeader).toBe('authenticated')
   const hero = guestRoutes.find(route => route.path === '/guest-shop/ae').meta.publicLayout.hero
   expect(hero.titleParts.map(part => part.text).join('')).toBe('Shop Elken UAE.')
   expect(guestRoutes.find(route => route.path.endsWith('/cart')).meta.publicLayout.hero).toBeUndefined()

+ 7 - 4
tests/unit/ui-refactor/guestShopUi.spec.js

@@ -7,7 +7,7 @@ import * as shop from '@/api/shop'
 import { getGuestRegionList } from '@/api/config'
 import { toThousandFilter } from '@/filters'
 
-jest.mock('@/api/shop', () => ({ fetchGuestProducts: jest.fn(), fetchGuestCart: jest.fn(), createGuestOrder: jest.fn() }))
+jest.mock('@/api/shop', () => ({ fetchGuestProducts: jest.fn(), fetchGuestCart: jest.fn(), createGuestOrder: jest.fn(), fetchGuestOrderDetail: jest.fn(), downloadGuestOrder: jest.fn(), downloadOrder: jest.fn() }))
 jest.mock('@/api/config', () => ({ getGuestRegionList: jest.fn() }))
 jest.mock('@/router', () => ({ push: jest.fn(), replace: jest.fn() }))
 jest.mock('vue-paystack', () => ({
@@ -169,12 +169,15 @@ it('does not turn a backend guest Cash option into a member balance', async() =>
   expect(vm.$el.querySelector('.ng-payment-methods').textContent).not.toContain('Account Balance')
   expect(vm.$el.textContent).not.toContain('Available balance')
 })
-it('shows only the supplied order reference, without fabricating receipt or paid data', async() => {
+it('loads the supplied order reference without fabricating paid data', async() => {
   Vue.prototype.$route = { query: { order: 'REAL-ORDER' }}
+  Vue.prototype.$router.resolve = () => ({ href: '/#/guest-order?order=REAL-ORDER' })
+  shop.fetchGuestOrderDetail.mockResolvedValue({ data: { order: { SN: 'REAL-ORDER', STATUS: 'Unpaid', CURRENCY: 'NGN' }, goods: [] }})
   const vm = mount(Order)
   await settle()
   expect(vm.$el.textContent).toContain('Order REAL-ORDER')
-  expect(vm.$el.textContent).toContain('Order details are not available yet')
-  expect(vm.$el.textContent).not.toContain('PAID')
+  expect(vm.$el.textContent).toContain('Item details are unavailable')
+  expect(vm.$el.textContent).toContain('Unpaid')
+  expect(shop.fetchGuestOrderDetail).toHaveBeenCalledWith({ orderSn: 'REAL-ORDER' })
   expect(shop.fetchGuestProducts).not.toHaveBeenCalled()
 })

+ 60 - 0
tests/unit/ui-refactor/publicLayout.spec.js

@@ -0,0 +1,60 @@
+/* eslint-env jest */
+import Vue from 'vue'
+import ElementUI from 'element-ui'
+import fs from 'fs'
+import path from 'path'
+import { transformSync } from '@babel/core'
+import { parseComponent, compileTemplate } from 'vue/compiler-sfc'
+import usersInfo from '@/utils/usersInfo'
+import { guestRoutes } from '@/ui-refactor/views/guest-shop/routes'
+
+jest.mock('@/utils/usersInfo', () => ({ accessToken: jest.fn() }))
+Vue.use(ElementUI)
+const filename = path.resolve('src/ui-refactor/index.vue')
+const { script, template } = parseComponent(fs.readFileSync(filename, 'utf8'))
+const code = transformSync(script.content, { babelrc: false, configFile: false, plugins: [require.resolve('@babel/plugin-transform-modules-commonjs')] }).code
+const module = { exports: {}}
+new Function('require', 'module', 'exports', code)(id => {
+  if (id === '@/utils/usersInfo') return require(id)
+  if (id.endsWith('PublicHeader.vue')) return { render: h => h('header', { class: 'sample-header' }) }
+  return { render: h => h('div') }
+}, module, module.exports)
+const compiled = compileTemplate({ source: template.content, filename })
+if (compiled.errors.length) throw new Error(compiled.errors.join('\n'))
+const Layout = { ...module.exports.default, ...new Function(compiled.code + '; return { render, staticRenderFns }')(), components: { ...module.exports.default.components, RouterView: { render: h => h('div') }}}
+const instances = []
+function mount(route) {
+  const state = Vue.observable({ route })
+  const vm = new (Vue.extend(Layout))({ beforeCreate() {
+    Object.defineProperty(this, '$route', { get: () => state.route, set: value => { state.route = value } })
+  } }).$mount()
+  instances.push(vm)
+  return vm
+}
+afterEach(() => { instances.splice(0).forEach(vm => vm.$destroy()); jest.clearAllMocks() })
+it.each([true, false])('shows the order detail header only for a signed-in visitor (%s)', loggedIn => {
+  usersInfo.accessToken.mockReturnValue(loggedIn ? 'sample-session' : '')
+  const route = guestRoutes.find(item => item.path === '/guest-order')
+  const vm = mount({ path: route.path, meta: route.meta, query: { order: 'SAMPLE-ORDER' }})
+  expect(Boolean(vm.$el.querySelector('.sample-header'))).toBe(loggedIn)
+})
+it.each([true, false])('preserves hidden shop headers and ordinary page headers (%s)', loggedIn => {
+  usersInfo.accessToken.mockReturnValue(loggedIn ? 'sample-session' : '')
+  for (const route of guestRoutes.filter(item => item.path !== '/guest-order')) {
+    const vm = mount({ path: route.path, meta: route.meta, query: {}})
+    expect(vm.$el.querySelector('.sample-header')).toBeNull()
+  }
+  expect(mount({ path: '/dashboard/index', meta: {}, query: {}}).$el.querySelector('.sample-header')).not.toBeNull()
+})
+it('updates the header when navigating between an account page and public order details', async() => {
+  usersInfo.accessToken.mockReturnValue('sample-session')
+  const vm = mount({ path: '/dashboard/index', meta: {}, query: {}})
+  const route = guestRoutes.find(item => item.path === '/guest-order')
+  vm.$route = Vue.observable({ path: route.path, meta: route.meta, query: { order: 'SAMPLE-ORDER' }})
+  await Vue.nextTick()
+  expect(vm.$el.querySelector('.sample-header')).not.toBeNull()
+  usersInfo.accessToken.mockReturnValue('')
+  vm.$route = { path: route.path, meta: route.meta, query: { order: 'ANOTHER-ORDER' }}
+  await Vue.nextTick()
+  expect(vm.$el.querySelector('.sample-header')).toBeNull()
+})