@easy-cms/plugin-ecommerce 0.0.0-stage → 0.45.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/LICENSE +21 -0
- package/README.md +48 -2
- package/dist/admin.js +62 -0
- package/dist/chunk-KON3VWC6.js +302 -0
- package/dist/chunk-RRF3IDUV.js +1937 -0
- package/dist/client.d.ts +250 -0
- package/dist/client.js +18 -0
- package/dist/index.d.ts +530 -0
- package/dist/index.js +44 -0
- package/dist/payments-tPD3bTTW.d.ts +213 -0
- package/dist/react.d.ts +95 -0
- package/dist/react.js +170 -0
- package/dist/stripe.d.ts +58 -0
- package/dist/stripe.js +90 -0
- package/dist/vue.d.ts +119 -0
- package/dist/vue.js +179 -0
- package/package.json +84 -4
package/LICENSE
ADDED
|
@@ -0,0 +1,21 @@
|
|
|
1
|
+
MIT License
|
|
2
|
+
|
|
3
|
+
Copyright (c) 2026 Kanawoot K.
|
|
4
|
+
|
|
5
|
+
Permission is hereby granted, free of charge, to any person obtaining a copy
|
|
6
|
+
of this software and associated documentation files (the "Software"), to deal
|
|
7
|
+
in the Software without restriction, including without limitation the rights
|
|
8
|
+
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
|
|
9
|
+
copies of the Software, and to permit persons to whom the Software is
|
|
10
|
+
furnished to do so, subject to the following conditions:
|
|
11
|
+
|
|
12
|
+
The above copyright notice and this permission notice shall be included in all
|
|
13
|
+
copies or substantial portions of the Software.
|
|
14
|
+
|
|
15
|
+
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
|
|
16
|
+
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
|
|
17
|
+
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
|
|
18
|
+
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
|
|
19
|
+
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
|
|
20
|
+
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
|
|
21
|
+
SOFTWARE.
|
package/README.md
CHANGED
|
@@ -1,3 +1,49 @@
|
|
|
1
|
-
#
|
|
1
|
+
# @easy-cms/plugin-ecommerce
|
|
2
2
|
|
|
3
|
-
|
|
3
|
+
A shop for Easy CMS: products with variants and prices in several currencies, carts that guests keep too, checkout with Stripe (card, PromptPay) or bank transfer, orders made exactly once, stock, customer accounts, order emails and events, and a client for pages with React hooks and Vue composables. Part of [Easy CMS](https://github.com/maritonx/easy-cms), the embedded, code-first headless CMS for Nuxt and Next.js.
|
|
4
|
+
|
|
5
|
+
## Install
|
|
6
|
+
|
|
7
|
+
```bash
|
|
8
|
+
npm install @easy-cms/plugin-ecommerce
|
|
9
|
+
```
|
|
10
|
+
|
|
11
|
+
Or `pnpm add`, `yarn add` or `bun add`. For Stripe, also install `stripe`.
|
|
12
|
+
|
|
13
|
+
## Usage
|
|
14
|
+
|
|
15
|
+
```ts
|
|
16
|
+
import { ecommercePlugin, manualAdapter } from '@easy-cms/plugin-ecommerce'
|
|
17
|
+
import { stripeAdapter } from '@easy-cms/plugin-ecommerce/stripe'
|
|
18
|
+
|
|
19
|
+
export default defineConfig({
|
|
20
|
+
// …
|
|
21
|
+
plugins: [
|
|
22
|
+
ecommercePlugin({
|
|
23
|
+
currencies: { supported: ['THB', 'USD'] },
|
|
24
|
+
payments: {
|
|
25
|
+
methods: [
|
|
26
|
+
stripeAdapter({ secretKey: process.env.STRIPE_SECRET_KEY!, publishableKey: process.env.STRIPE_PUBLISHABLE_KEY! }),
|
|
27
|
+
manualAdapter({ instructions: 'Transfer to Kasikorn Bank 123-4-56789-0' }),
|
|
28
|
+
],
|
|
29
|
+
},
|
|
30
|
+
}),
|
|
31
|
+
],
|
|
32
|
+
})
|
|
33
|
+
```
|
|
34
|
+
|
|
35
|
+
```tsx
|
|
36
|
+
'use client'
|
|
37
|
+
import { ShopProvider, useCart } from '@easy-cms/plugin-ecommerce/react'
|
|
38
|
+
|
|
39
|
+
function AddToCart({ product }: { product: number }) {
|
|
40
|
+
const { addItem } = useCart()
|
|
41
|
+
return <button onClick={() => addItem(product)}>Add to cart</button>
|
|
42
|
+
}
|
|
43
|
+
```
|
|
44
|
+
|
|
45
|
+
## Links
|
|
46
|
+
|
|
47
|
+
[Shop guide](https://maritonx.github.io/easy-cms/guide/ecommerce) · [Documentation](https://maritonx.github.io/easy-cms/) ([ภาษาไทย](https://maritonx.github.io/easy-cms/th/)) · [GitHub](https://github.com/maritonx/easy-cms)
|
|
48
|
+
|
|
49
|
+
MIT License
|
package/dist/admin.js
ADDED
|
@@ -0,0 +1,62 @@
|
|
|
1
|
+
var x={en:{amount:"Amount",status:"Status",paid:"Payment received",fulfilled:"Mark as sent",cancelled:"Cancel order",refunded:"Refund",confirmPaid:"Mark this order as paid? The customer gets an email.",confirmFulfilled:"Mark this order as sent?",confirmCancelled:"Cancel this order? Its items go back in stock.",confirmRefunded:"Refund this order? The money goes back to the customer.",failed:"Could not change the order: {message}",unsaved:"Orders are made at checkout.",short:"Stock ran out while this order was paid: check before sending.",widget:"Shop",today:"Today",month:"Last 30 days",orders:"{n} orders",pending:"Awaiting payment",toFulfil:"To send",none:"No sales yet.",loading:"Loading\u2026",loadFailed:"Could not load the numbers.",statuses:{pending:"Awaiting payment",paid:"Paid",fulfilled:"Sent",cancelled:"Cancelled",refunded:"Refunded"}},th:{amount:"\u0E08\u0E33\u0E19\u0E27\u0E19\u0E40\u0E07\u0E34\u0E19",status:"\u0E2A\u0E16\u0E32\u0E19\u0E30",paid:"\u0E44\u0E14\u0E49\u0E23\u0E31\u0E1A\u0E40\u0E07\u0E34\u0E19\u0E41\u0E25\u0E49\u0E27",fulfilled:"\u0E08\u0E31\u0E14\u0E2A\u0E48\u0E07\u0E41\u0E25\u0E49\u0E27",cancelled:"\u0E22\u0E01\u0E40\u0E25\u0E34\u0E01\u0E04\u0E33\u0E2A\u0E31\u0E48\u0E07\u0E0B\u0E37\u0E49\u0E2D",refunded:"\u0E04\u0E37\u0E19\u0E40\u0E07\u0E34\u0E19",confirmPaid:"\u0E22\u0E37\u0E19\u0E22\u0E31\u0E19\u0E27\u0E48\u0E32\u0E44\u0E14\u0E49\u0E23\u0E31\u0E1A\u0E40\u0E07\u0E34\u0E19\u0E2A\u0E33\u0E2B\u0E23\u0E31\u0E1A\u0E04\u0E33\u0E2A\u0E31\u0E48\u0E07\u0E0B\u0E37\u0E49\u0E2D\u0E19\u0E35\u0E49\u0E41\u0E25\u0E49\u0E27? \u0E25\u0E39\u0E01\u0E04\u0E49\u0E32\u0E08\u0E30\u0E44\u0E14\u0E49\u0E23\u0E31\u0E1A\u0E2D\u0E35\u0E40\u0E21\u0E25",confirmFulfilled:"\u0E22\u0E37\u0E19\u0E22\u0E31\u0E19\u0E27\u0E48\u0E32\u0E08\u0E31\u0E14\u0E2A\u0E48\u0E07\u0E04\u0E33\u0E2A\u0E31\u0E48\u0E07\u0E0B\u0E37\u0E49\u0E2D\u0E19\u0E35\u0E49\u0E41\u0E25\u0E49\u0E27?",confirmCancelled:"\u0E22\u0E01\u0E40\u0E25\u0E34\u0E01\u0E04\u0E33\u0E2A\u0E31\u0E48\u0E07\u0E0B\u0E37\u0E49\u0E2D\u0E19\u0E35\u0E49? \u0E2A\u0E34\u0E19\u0E04\u0E49\u0E32\u0E08\u0E30\u0E01\u0E25\u0E31\u0E1A\u0E40\u0E02\u0E49\u0E32\u0E2A\u0E15\u0E47\u0E2D\u0E01",confirmRefunded:"\u0E04\u0E37\u0E19\u0E40\u0E07\u0E34\u0E19\u0E04\u0E33\u0E2A\u0E31\u0E48\u0E07\u0E0B\u0E37\u0E49\u0E2D\u0E19\u0E35\u0E49? \u0E40\u0E07\u0E34\u0E19\u0E08\u0E30\u0E01\u0E25\u0E31\u0E1A\u0E44\u0E1B\u0E22\u0E31\u0E07\u0E25\u0E39\u0E01\u0E04\u0E49\u0E32",failed:"\u0E40\u0E1B\u0E25\u0E35\u0E48\u0E22\u0E19\u0E2A\u0E16\u0E32\u0E19\u0E30\u0E44\u0E21\u0E48\u0E2A\u0E33\u0E40\u0E23\u0E47\u0E08: {message}",unsaved:"\u0E04\u0E33\u0E2A\u0E31\u0E48\u0E07\u0E0B\u0E37\u0E49\u0E2D\u0E2A\u0E23\u0E49\u0E32\u0E07\u0E15\u0E2D\u0E19\u0E25\u0E39\u0E01\u0E04\u0E49\u0E32\u0E0A\u0E33\u0E23\u0E30\u0E40\u0E07\u0E34\u0E19",short:"\u0E2A\u0E15\u0E47\u0E2D\u0E01\u0E2B\u0E21\u0E14\u0E23\u0E30\u0E2B\u0E27\u0E48\u0E32\u0E07\u0E17\u0E35\u0E48\u0E25\u0E39\u0E01\u0E04\u0E49\u0E32\u0E0A\u0E33\u0E23\u0E30\u0E40\u0E07\u0E34\u0E19 \u0E15\u0E23\u0E27\u0E08\u0E2A\u0E2D\u0E1A\u0E01\u0E48\u0E2D\u0E19\u0E08\u0E31\u0E14\u0E2A\u0E48\u0E07",widget:"\u0E23\u0E49\u0E32\u0E19\u0E04\u0E49\u0E32",today:"\u0E27\u0E31\u0E19\u0E19\u0E35\u0E49",month:"30 \u0E27\u0E31\u0E19\u0E25\u0E48\u0E32\u0E2A\u0E38\u0E14",orders:"{n} \u0E04\u0E33\u0E2A\u0E31\u0E48\u0E07\u0E0B\u0E37\u0E49\u0E2D",pending:"\u0E23\u0E2D\u0E0A\u0E33\u0E23\u0E30\u0E40\u0E07\u0E34\u0E19",toFulfil:"\u0E23\u0E2D\u0E08\u0E31\u0E14\u0E2A\u0E48\u0E07",none:"\u0E22\u0E31\u0E07\u0E44\u0E21\u0E48\u0E21\u0E35\u0E22\u0E2D\u0E14\u0E02\u0E32\u0E22",loading:"\u0E01\u0E33\u0E25\u0E31\u0E07\u0E42\u0E2B\u0E25\u0E14\u2026",loadFailed:"\u0E42\u0E2B\u0E25\u0E14\u0E15\u0E31\u0E27\u0E40\u0E25\u0E02\u0E44\u0E21\u0E48\u0E2A\u0E33\u0E40\u0E23\u0E47\u0E08",statuses:{pending:"\u0E23\u0E2D\u0E0A\u0E33\u0E23\u0E30\u0E40\u0E07\u0E34\u0E19",paid:"\u0E0A\u0E33\u0E23\u0E30\u0E41\u0E25\u0E49\u0E27",fulfilled:"\u0E08\u0E31\u0E14\u0E2A\u0E48\u0E07\u0E41\u0E25\u0E49\u0E27",cancelled:"\u0E22\u0E01\u0E40\u0E25\u0E34\u0E01",refunded:"\u0E04\u0E37\u0E19\u0E40\u0E07\u0E34\u0E19\u0E41\u0E25\u0E49\u0E27"}}},i=o=>o.replace(/[&<>"']/g,t=>({"&":"&","<":"<",">":">",'"':""","'":"'"})[t]),v=`
|
|
2
|
+
:host { display: block; font: inherit; color: var(--text); }
|
|
3
|
+
[hidden] { display: none !important; }
|
|
4
|
+
.muted { color: var(--text-muted); }
|
|
5
|
+
button:focus-visible, input:focus-visible, a:focus-visible { outline: 2px solid var(--focus); outline-offset: 2px; }
|
|
6
|
+
`;function u(o,t){for(let e of t)Object.defineProperty(o.prototype,e,{get(){return this.props[e]},set(n){this.props[e]=n,this.update()}})}var p=["value","options","readOnly","uiLocale","label","field","doc","id","api","collection","path","global","locale","apiVersion","user"],c=class extends HTMLElement{props={};constructor(){super(),this.attachShadow({mode:"open"})}connectedCallback(){this.update()}get uiLang(){return this.props.uiLocale==="th"?"th":"en"}t(t,e={}){return x[this.uiLang][t].replace(/\{(\w+)\}/g,(n,r)=>String(e[r]??""))}status(t){return x[this.uiLang].statuses[t]??t}money(t,e,n=2){try{return new Intl.NumberFormat(this.uiLang==="th"?"th-TH":"en",{style:"currency",currency:e,minimumFractionDigits:n,maximumFractionDigits:n}).format(t/10**n)}catch{return`${(t/10**n).toFixed(n)} ${e}`}}},S=`
|
|
7
|
+
${v}
|
|
8
|
+
.row { display: flex; align-items: stretch; max-inline-size: 16rem; }
|
|
9
|
+
.unit {
|
|
10
|
+
display: inline-flex; align-items: center; padding: 0 0.6rem; border: 1px solid var(--border-strong);
|
|
11
|
+
border-right: 0; border-radius: var(--radius-sm, 8px) 0 0 var(--radius-sm, 8px);
|
|
12
|
+
background: var(--surface-2); color: var(--text-muted); font-size: 0.875rem;
|
|
13
|
+
}
|
|
14
|
+
input {
|
|
15
|
+
flex: 1; min-inline-size: 0; min-block-size: 2.25rem; padding: 0 0.6rem; border: 1px solid var(--border-strong);
|
|
16
|
+
border-radius: 0 var(--radius-sm, 8px) var(--radius-sm, 8px) 0; background: var(--surface); color: var(--text);
|
|
17
|
+
font: inherit; font-variant-numeric: tabular-nums; text-align: right;
|
|
18
|
+
}
|
|
19
|
+
input[aria-invalid='true'] { border-color: var(--danger, #c0392b); }
|
|
20
|
+
input:read-only { background: var(--surface-2); }
|
|
21
|
+
`;function $(o,t){let e=o.replace(/[\s,_]/g,"");if(e==="")return null;if(!(t>0?new RegExp(`^\\d+(\\.\\d{0,${t}})?$`):/^\d+$/).test(e))return;let[r="0",s=""]=e.split(".");return Number(r)*10**t+Number(s.padEnd(t,"0")||"0")}function h(o,t){return typeof o!="number"||!Number.isFinite(o)?"":(o/10**t).toFixed(t)}var f=class o extends c{#t=document.createElement("input");#e=document.createElement("span");static{u(o,p)}constructor(){super(),this.#t.inputMode="decimal",this.#t.autocomplete="off",this.#e.className="unit",this.#e.setAttribute("aria-hidden","true"),this.#t.addEventListener("input",()=>{let n=$(this.#t.value,this.#r);this.#t.setAttribute("aria-invalid",String(n===void 0)),n!==void 0&&this.dispatchEvent(new CustomEvent("change",{detail:n}))}),this.#t.addEventListener("blur",()=>{let n=$(this.#t.value,this.#r);n!==void 0&&(this.#t.value=h(n,this.#r))});let t=document.createElement("div");t.className="row",t.append(this.#e,this.#t);let e=document.createElement("style");e.textContent=S,this.shadowRoot?.append(e,t)}get#n(){return this.props.options??{}}get#r(){let t=this.#n.decimals;return typeof t=="number"?t:2}update(){let t=this.props.doc??{},e=this.#n.currency??(typeof t.currency=="string"?t.currency:""),{symbol:n}=this.#n;this.#e.textContent=n??e,this.#t.readOnly=this.props.readOnly===!0;let r=typeof this.props.label=="string"?this.props.label:this.t("amount");this.#t.setAttribute("aria-label",`${r} (${e})`),this.#t.placeholder=h(0,this.#r),this.shadowRoot?.activeElement!==this.#t&&(this.#t.value=h(this.props.value,this.#r))}},g=class o extends c{static{u(o,p)}update(){let t=this.shadowRoot;if(!t)return;let{currency:e,decimals:n=2}=this.props.options??{},r=this.props.value,s=this.props.doc??{},a=e??(typeof s.currency=="string"?s.currency:"");t.innerHTML=`<style>:host{font-variant-numeric:tabular-nums}</style>${i(typeof r=="number"&&a?this.money(r,a,n):typeof r=="number"?String(r):"\u2014")}`}},R=`
|
|
22
|
+
${v}
|
|
23
|
+
h3 { margin: 0 0 0.5rem; font-size: 0.8rem; font-weight: 600; text-transform: uppercase; letter-spacing: 0.02em; color: var(--text-muted); }
|
|
24
|
+
.badge {
|
|
25
|
+
display: inline-flex; align-items: center; min-height: 1.6rem; padding: 0 0.6rem; border-radius: 999px;
|
|
26
|
+
background: var(--surface-2); font-size: 0.8rem; font-weight: 600; margin-bottom: 0.75rem;
|
|
27
|
+
}
|
|
28
|
+
.badge.paid, .badge.fulfilled { background: color-mix(in srgb, var(--success, #1a7f37) 15%, transparent); color: var(--success, #1a7f37); }
|
|
29
|
+
.badge.pending { background: color-mix(in srgb, var(--warning, #9a6700) 15%, transparent); color: var(--warning, #9a6700); }
|
|
30
|
+
.actions { display: flex; flex-wrap: wrap; gap: 0.5rem; }
|
|
31
|
+
button {
|
|
32
|
+
min-height: 2rem; padding: 0 0.75rem; border: 1px solid var(--border-strong); border-radius: var(--radius-sm, 8px);
|
|
33
|
+
background: var(--surface); color: var(--text); font: inherit; font-size: 0.85rem; font-weight: 500; cursor: pointer;
|
|
34
|
+
}
|
|
35
|
+
button.primary { background: var(--accent); border-color: var(--accent); color: var(--accent-contrast, #fff); }
|
|
36
|
+
button.danger { color: var(--danger, #c0392b); }
|
|
37
|
+
button:disabled { opacity: 0.6; cursor: progress; }
|
|
38
|
+
p { margin: 0 0 0.6rem; font-size: 0.85rem; }
|
|
39
|
+
.warn { color: var(--warning, #9a6700); }
|
|
40
|
+
.error { color: var(--danger, #c0392b); }
|
|
41
|
+
`,L={pending:[{action:"paid",style:"primary"},{action:"cancelled",style:"danger"}],paid:[{action:"fulfilled",style:"primary"},{action:"refunded",style:"danger"}],fulfilled:[{action:"refunded",style:"danger"}]},T={paid:"confirmPaid",fulfilled:"confirmFulfilled",cancelled:"confirmCancelled",refunded:"confirmRefunded"},b=class o extends c{#t=!1;#e="";static{u(o,p)}async#n(t){let e=this.props.api,n=this.props.id;if(!(!e||n===void 0||n===null)&&window.confirm(this.t(T[t]))){this.#t=!0,this.#e="",this.update();try{await e("POST",`/shop/orders/${encodeURIComponent(String(n))}/${t}`,{}),window.location.reload()}catch(r){this.#t=!1,this.#e=this.t("failed",{message:r.message}),this.update()}}}update(){let t=this.shadowRoot;if(!t)return;let e=this.props.doc??{},n=this.props.id,r;if(n==null)r=`<p class="muted">${i(this.t("unsaved"))}</p>`;else{let s=String(e.status??""),a=(L[s]??[]).map(({action:d,style:l})=>`<button type="button" data-action="${d}" class="${l??""}" ${this.#t?"disabled":""}>${i(this.t(d))}</button>`).join("");r=`
|
|
42
|
+
<span class="badge ${i(s)}">${i(this.status(s))}</span>
|
|
43
|
+
${e.stockShort===!0?`<p class="warn">${i(this.t("short"))}</p>`:""}
|
|
44
|
+
${typeof e.total=="number"&&typeof e.currency=="string"?`<p>${i(this.money(e.total,e.currency))}</p>`:""}
|
|
45
|
+
${a?`<div class="actions">${a}</div>`:""}
|
|
46
|
+
${this.#e?`<p class="error" role="alert">${i(this.#e)}</p>`:""}`}t.innerHTML=`<style>${R}</style><section aria-label="${i(this.t("status"))}"><h3>${i(this.t("status"))}</h3>${r}</section>`;for(let s of t.querySelectorAll("button[data-action]"))s.addEventListener("click",()=>{this.#n(s.dataset.action)})}},F=`
|
|
47
|
+
${v}
|
|
48
|
+
h2 { margin: 0 0 0.75rem; font-size: 1rem; font-weight: 600; }
|
|
49
|
+
.grid { display: grid; grid-template-columns: repeat(auto-fit, minmax(9rem, 1fr)); gap: 0.75rem; }
|
|
50
|
+
.stat { padding: 0.75rem; border: 1px solid var(--border); border-radius: var(--radius-sm, 8px); }
|
|
51
|
+
.stat span { display: block; font-size: 0.8rem; color: var(--text-muted); }
|
|
52
|
+
.stat strong { display: block; margin-top: 0.2rem; font-size: 1.25rem; font-variant-numeric: tabular-nums; }
|
|
53
|
+
.stat small { color: var(--text-muted); }
|
|
54
|
+
a { color: inherit; text-decoration: none; }
|
|
55
|
+
a.stat:hover { border-color: var(--border-strong); background: var(--surface-2); }
|
|
56
|
+
p { margin: 0; font-size: 0.875rem; }
|
|
57
|
+
`,y=class o extends c{#t=null;#e=!1;#n=!1;static{u(o,p)}async#r(){let t=this.props.api;if(!(!t||this.#n)){this.#n=!0;try{this.#t=await t("GET","/shop/overview")}catch{this.#e=!0}this.update()}}#s(t,e){let n=Object.entries(t);if(n.length===0)return{total:"\u2014",orders:this.t("orders",{n:0})};let r=s=>e.currencies.find(a=>a.code===s)?.decimals??2;return{total:n.map(([s,a])=>this.money(a.total,s,r(s))).join(" \xB7 "),orders:this.t("orders",{n:n.reduce((s,[,a])=>s+a.orders,0)})}}update(){let t=this.shadowRoot;if(!t)return;this.#r();let n=(this.props.options??{}).adminPath??"/admin",r=this.#t,s;if(this.#e)s=`<p class="muted">${i(this.t("loadFailed"))}</p>`;else if(!r)s=`<p class="muted">${i(this.t("loading"))}</p>`;else{let a=this.#s(r.today,r),d=this.#s(r.month,r),l=(w,k,E)=>`<a class="stat" href="${i(n+w)}" data-to="${i(w)}"><span>${i(k)}</span><strong>${E}</strong></a>`;s=`<div class="grid">
|
|
58
|
+
<div class="stat"><span>${i(this.t("today"))}</span><strong>${i(a.total)}</strong><small>${i(a.orders)}</small></div>
|
|
59
|
+
<div class="stat"><span>${i(this.t("month"))}</span><strong>${i(d.total)}</strong><small>${i(d.orders)}</small></div>
|
|
60
|
+
${l("/collections/orders?f_status=pending",this.t("pending"),r.pending)}
|
|
61
|
+
${l("/collections/orders?f_status=paid",this.t("toFulfil"),r.toFulfil)}
|
|
62
|
+
</div>`}t.innerHTML=`<style>${F}</style><section aria-labelledby="title"><h2 id="title">${i(this.t("widget"))}</h2>${s}</section>`;for(let a of t.querySelectorAll("a[data-to]"))a.addEventListener("click",d=>{d.metaKey||d.ctrlKey||d.shiftKey||d.altKey||d.button!==0||(d.preventDefault(),this.dispatchEvent(new CustomEvent("navigate",{detail:a.dataset.to??"/"})))})}},m=(o,t)=>{customElements.get(o)||customElements.define(o,t)};m("ecms-price-field",f);m("ecms-price-cell",g);m("ecms-order-actions",b);m("ecms-shop-overview",y);export{$ as parseMoney,h as showMoney};
|
|
@@ -0,0 +1,302 @@
|
|
|
1
|
+
// src/shared.ts
|
|
2
|
+
var CURRENCIES = {
|
|
3
|
+
THB: { code: "THB", symbol: "\u0E3F", label: "Thai baht", decimals: 2 },
|
|
4
|
+
USD: { code: "USD", symbol: "$", label: "US dollar", decimals: 2 },
|
|
5
|
+
EUR: { code: "EUR", symbol: "\u20AC", label: "Euro", decimals: 2 },
|
|
6
|
+
GBP: { code: "GBP", symbol: "\xA3", label: "Pound sterling", decimals: 2 },
|
|
7
|
+
JPY: { code: "JPY", symbol: "\xA5", label: "Japanese yen", decimals: 0 }
|
|
8
|
+
};
|
|
9
|
+
var priceField = (code) => `priceIn${code.toUpperCase()}`;
|
|
10
|
+
function formatPrice(amount, currency, locale = "en") {
|
|
11
|
+
const value = amount / 10 ** currency.decimals;
|
|
12
|
+
try {
|
|
13
|
+
return new Intl.NumberFormat(locale, {
|
|
14
|
+
style: "currency",
|
|
15
|
+
currency: currency.code,
|
|
16
|
+
minimumFractionDigits: currency.decimals,
|
|
17
|
+
maximumFractionDigits: currency.decimals
|
|
18
|
+
}).format(value);
|
|
19
|
+
} catch {
|
|
20
|
+
return `${currency.symbol}${value.toFixed(currency.decimals)}`;
|
|
21
|
+
}
|
|
22
|
+
}
|
|
23
|
+
var ORDER_STATUSES = ["pending", "paid", "fulfilled", "cancelled", "refunded"];
|
|
24
|
+
var TRANSACTION_STATUSES = [
|
|
25
|
+
"pending",
|
|
26
|
+
"processing",
|
|
27
|
+
"succeeded",
|
|
28
|
+
"failed",
|
|
29
|
+
"refunded"
|
|
30
|
+
];
|
|
31
|
+
|
|
32
|
+
// src/client.ts
|
|
33
|
+
var ShopError = class extends Error {
|
|
34
|
+
constructor(message, status, errors = []) {
|
|
35
|
+
super(message);
|
|
36
|
+
this.status = status;
|
|
37
|
+
this.errors = errors;
|
|
38
|
+
this.name = "ShopError";
|
|
39
|
+
}
|
|
40
|
+
status;
|
|
41
|
+
errors;
|
|
42
|
+
};
|
|
43
|
+
var defaultStorage = () => {
|
|
44
|
+
try {
|
|
45
|
+
return typeof localStorage === "undefined" ? null : localStorage;
|
|
46
|
+
} catch {
|
|
47
|
+
return null;
|
|
48
|
+
}
|
|
49
|
+
};
|
|
50
|
+
function createShopClient(options = {}) {
|
|
51
|
+
const api = (options.api ?? "/api/cms").replace(/\/+$/, "");
|
|
52
|
+
const storage = options.storage === void 0 ? defaultStorage() : options.storage;
|
|
53
|
+
const key = options.storageKey ?? "easy-cms-cart";
|
|
54
|
+
const locale = options.locale ?? "en";
|
|
55
|
+
const doFetch = options.fetch ?? ((...args) => fetch(...args));
|
|
56
|
+
let state = { settings: null, user: null, cart: null, loading: true, busy: false };
|
|
57
|
+
const listeners = /* @__PURE__ */ new Set();
|
|
58
|
+
const set = (patch) => {
|
|
59
|
+
state = { ...state, ...patch };
|
|
60
|
+
for (const listener of listeners) listener(state);
|
|
61
|
+
};
|
|
62
|
+
let csrf;
|
|
63
|
+
let signupToken;
|
|
64
|
+
const remembered = () => {
|
|
65
|
+
try {
|
|
66
|
+
const raw = storage?.getItem(key);
|
|
67
|
+
if (!raw) return null;
|
|
68
|
+
const parsed = JSON.parse(raw);
|
|
69
|
+
return parsed && typeof parsed.secret === "string" ? parsed : null;
|
|
70
|
+
} catch {
|
|
71
|
+
return null;
|
|
72
|
+
}
|
|
73
|
+
};
|
|
74
|
+
const remember = (cart) => {
|
|
75
|
+
try {
|
|
76
|
+
if (cart) storage?.setItem(key, JSON.stringify(cart));
|
|
77
|
+
else storage?.removeItem(key);
|
|
78
|
+
} catch {
|
|
79
|
+
}
|
|
80
|
+
};
|
|
81
|
+
async function call(method, path, body) {
|
|
82
|
+
const headers = { accept: "application/json" };
|
|
83
|
+
if (body !== void 0) headers["content-type"] = "application/json";
|
|
84
|
+
if (method !== "GET" && csrf) headers["x-csrf-token"] = csrf;
|
|
85
|
+
const response = await doFetch(`${api}${path}`, {
|
|
86
|
+
method,
|
|
87
|
+
headers,
|
|
88
|
+
credentials: "include",
|
|
89
|
+
...body !== void 0 ? { body: JSON.stringify(body) } : {}
|
|
90
|
+
});
|
|
91
|
+
const text = await response.text();
|
|
92
|
+
const json = text ? JSON.parse(text) : {};
|
|
93
|
+
if (!response.ok)
|
|
94
|
+
throw new ShopError(
|
|
95
|
+
typeof json.message === "string" ? json.message : response.statusText,
|
|
96
|
+
response.status,
|
|
97
|
+
Array.isArray(json.errors) ? json.errors : []
|
|
98
|
+
);
|
|
99
|
+
return json;
|
|
100
|
+
}
|
|
101
|
+
const withCart = (body = {}) => {
|
|
102
|
+
const cart = state.user ? null : remembered();
|
|
103
|
+
return cart ? { ...body, cart } : body;
|
|
104
|
+
};
|
|
105
|
+
async function busy(run) {
|
|
106
|
+
set({ busy: true });
|
|
107
|
+
try {
|
|
108
|
+
return await run();
|
|
109
|
+
} finally {
|
|
110
|
+
set({ busy: false });
|
|
111
|
+
}
|
|
112
|
+
}
|
|
113
|
+
async function me() {
|
|
114
|
+
const result = await call("GET", "/users/me");
|
|
115
|
+
csrf = result.csrfToken;
|
|
116
|
+
return result.user;
|
|
117
|
+
}
|
|
118
|
+
const cartCall = (path, body) => busy(async () => {
|
|
119
|
+
const result = await call(
|
|
120
|
+
"POST",
|
|
121
|
+
`/shop/cart${path}`,
|
|
122
|
+
withCart(body)
|
|
123
|
+
);
|
|
124
|
+
if (result.secret && result.cart) remember({ id: result.cart.id, secret: result.secret });
|
|
125
|
+
set({ cart: result.cart });
|
|
126
|
+
return result.cart;
|
|
127
|
+
});
|
|
128
|
+
async function signedIn(user) {
|
|
129
|
+
const guest = remembered();
|
|
130
|
+
remember(null);
|
|
131
|
+
set({ user });
|
|
132
|
+
const result = await call(
|
|
133
|
+
"POST",
|
|
134
|
+
"/shop/cart/merge",
|
|
135
|
+
guest ? { cart: guest } : {}
|
|
136
|
+
);
|
|
137
|
+
set({ cart: result.cart });
|
|
138
|
+
return user;
|
|
139
|
+
}
|
|
140
|
+
const lineQuantity = (line) => state.cart?.lines.find((l) => l.id === line)?.quantity ?? 0;
|
|
141
|
+
const client = {
|
|
142
|
+
getState: () => state,
|
|
143
|
+
subscribe(listener) {
|
|
144
|
+
listeners.add(listener);
|
|
145
|
+
return () => listeners.delete(listener);
|
|
146
|
+
},
|
|
147
|
+
async load() {
|
|
148
|
+
try {
|
|
149
|
+
const [settings, user] = await Promise.all([
|
|
150
|
+
call("GET", "/shop/config"),
|
|
151
|
+
me().catch(() => null)
|
|
152
|
+
]);
|
|
153
|
+
set({ settings, user });
|
|
154
|
+
await client.refreshCart();
|
|
155
|
+
} finally {
|
|
156
|
+
set({ loading: false });
|
|
157
|
+
}
|
|
158
|
+
},
|
|
159
|
+
async refreshCart() {
|
|
160
|
+
const result = await call("POST", "/shop/cart", withCart());
|
|
161
|
+
if (!result.cart && !state.user) remember(null);
|
|
162
|
+
set({ cart: result.cart });
|
|
163
|
+
return result.cart;
|
|
164
|
+
},
|
|
165
|
+
addItem: (product, opts = {}) => cartCall("/add", {
|
|
166
|
+
product,
|
|
167
|
+
...opts.variant !== void 0 && opts.variant !== null ? { variant: opts.variant } : {},
|
|
168
|
+
quantity: opts.quantity ?? 1,
|
|
169
|
+
...state.cart ? {} : { currency: state.settings?.defaultCurrency }
|
|
170
|
+
}),
|
|
171
|
+
updateItem: (line, quantity) => cartCall("/update", { line, quantity }),
|
|
172
|
+
incrementItem: (line) => cartCall("/update", { line, quantity: lineQuantity(line) + 1 }),
|
|
173
|
+
decrementItem: (line) => cartCall("/update", { line, quantity: Math.max(0, lineQuantity(line) - 1) }),
|
|
174
|
+
removeItem: (line) => cartCall("/remove", { line }),
|
|
175
|
+
async clearCart() {
|
|
176
|
+
if (!state.cart) return null;
|
|
177
|
+
return cartCall("/clear");
|
|
178
|
+
},
|
|
179
|
+
setCurrency: (code) => cartCall("/currency", { currency: code }),
|
|
180
|
+
currency() {
|
|
181
|
+
const code = state.cart?.currency ?? state.settings?.defaultCurrency;
|
|
182
|
+
return state.settings?.currencies.find((c) => c.code === code) ?? null;
|
|
183
|
+
},
|
|
184
|
+
formatPrice(amount, code) {
|
|
185
|
+
const wanted = code ?? state.cart?.currency ?? state.settings?.defaultCurrency;
|
|
186
|
+
const currency = state.settings?.currencies.find((c) => c.code === wanted);
|
|
187
|
+
if (!currency) return String(amount);
|
|
188
|
+
return formatPrice(amount, currency, locale === "th" ? "th-TH" : locale);
|
|
189
|
+
},
|
|
190
|
+
async login(email, password) {
|
|
191
|
+
return busy(async () => {
|
|
192
|
+
const result = await call("POST", "/users/login", {
|
|
193
|
+
email,
|
|
194
|
+
password
|
|
195
|
+
});
|
|
196
|
+
csrf = result.csrfToken;
|
|
197
|
+
return signedIn(result.user);
|
|
198
|
+
});
|
|
199
|
+
},
|
|
200
|
+
async logout() {
|
|
201
|
+
await call("POST", "/users/logout").catch(() => {
|
|
202
|
+
});
|
|
203
|
+
csrf = void 0;
|
|
204
|
+
set({ user: null, cart: null });
|
|
205
|
+
},
|
|
206
|
+
async signup(data) {
|
|
207
|
+
return busy(async () => {
|
|
208
|
+
if (!signupToken || Date.now() - signupToken.at > 12 * 36e5) {
|
|
209
|
+
const form = await call("GET", "/users/signup");
|
|
210
|
+
signupToken = { token: form.token, at: Date.now() };
|
|
211
|
+
await new Promise((resolve) => setTimeout(resolve, 2100));
|
|
212
|
+
}
|
|
213
|
+
const result = await call(
|
|
214
|
+
"POST",
|
|
215
|
+
"/users/signup",
|
|
216
|
+
{ ...data, token: signupToken.token, locale }
|
|
217
|
+
);
|
|
218
|
+
if (result.verify) return { verify: true };
|
|
219
|
+
csrf = result.csrfToken;
|
|
220
|
+
if (result.user) await signedIn(result.user);
|
|
221
|
+
return { verify: false };
|
|
222
|
+
});
|
|
223
|
+
},
|
|
224
|
+
async verifyEmail(token) {
|
|
225
|
+
const result = await call(
|
|
226
|
+
"POST",
|
|
227
|
+
"/users/verify-email",
|
|
228
|
+
{ token }
|
|
229
|
+
);
|
|
230
|
+
csrf = result.csrfToken;
|
|
231
|
+
return signedIn(result.user);
|
|
232
|
+
},
|
|
233
|
+
async forgotPassword(email) {
|
|
234
|
+
await call("POST", "/users/forgot-password", { email, locale });
|
|
235
|
+
},
|
|
236
|
+
async resetPassword(token, password) {
|
|
237
|
+
const result = await call(
|
|
238
|
+
"POST",
|
|
239
|
+
"/users/reset-password",
|
|
240
|
+
{ token, password, locale }
|
|
241
|
+
);
|
|
242
|
+
csrf = result.csrfToken;
|
|
243
|
+
return signedIn(result.user);
|
|
244
|
+
},
|
|
245
|
+
async checkout(input) {
|
|
246
|
+
return busy(async () => {
|
|
247
|
+
const result = await call(
|
|
248
|
+
"POST",
|
|
249
|
+
"/shop/checkout",
|
|
250
|
+
withCart({ ...input, locale })
|
|
251
|
+
);
|
|
252
|
+
if (result.order) {
|
|
253
|
+
remember(null);
|
|
254
|
+
set({ cart: null });
|
|
255
|
+
}
|
|
256
|
+
return result;
|
|
257
|
+
});
|
|
258
|
+
},
|
|
259
|
+
async confirm(transaction, input = {}) {
|
|
260
|
+
return busy(async () => {
|
|
261
|
+
const result = await call("POST", "/shop/confirm", { ...input, transaction });
|
|
262
|
+
if (result.order) {
|
|
263
|
+
remember(null);
|
|
264
|
+
set({ cart: null });
|
|
265
|
+
}
|
|
266
|
+
return result;
|
|
267
|
+
});
|
|
268
|
+
},
|
|
269
|
+
async addresses() {
|
|
270
|
+
const result = await call(
|
|
271
|
+
"GET",
|
|
272
|
+
"/addresses?limit=100&sort=-updatedAt"
|
|
273
|
+
);
|
|
274
|
+
return result.docs;
|
|
275
|
+
},
|
|
276
|
+
createAddress: (address) => call("POST", "/addresses", address),
|
|
277
|
+
updateAddress: (id, address) => call("PATCH", `/addresses/${encodeURIComponent(String(id))}`, address),
|
|
278
|
+
async deleteAddress(id) {
|
|
279
|
+
await call("DELETE", `/addresses/${encodeURIComponent(String(id))}`);
|
|
280
|
+
},
|
|
281
|
+
async orders(opts = {}) {
|
|
282
|
+
const query = new URLSearchParams({
|
|
283
|
+
sort: "-createdAt",
|
|
284
|
+
limit: String(opts.limit ?? 20),
|
|
285
|
+
page: String(opts.page ?? 1),
|
|
286
|
+
depth: "0"
|
|
287
|
+
});
|
|
288
|
+
return call("GET", `/orders?${query}`);
|
|
289
|
+
}
|
|
290
|
+
};
|
|
291
|
+
return client;
|
|
292
|
+
}
|
|
293
|
+
|
|
294
|
+
export {
|
|
295
|
+
CURRENCIES,
|
|
296
|
+
priceField,
|
|
297
|
+
formatPrice,
|
|
298
|
+
ORDER_STATUSES,
|
|
299
|
+
TRANSACTION_STATUSES,
|
|
300
|
+
ShopError,
|
|
301
|
+
createShopClient
|
|
302
|
+
};
|