/* Chandrahasa — account dashboard: orders w/ timeline, wishlist, profile, invoice */
'use strict';
const $ = (s, c = document) => c.querySelector(s);
const $$ = (s, c = document) => [...c.querySelectorAll(s)];
const fmt = CH.money;
const STATUS_STEPS = ['pending', 'confirmed', 'shipped', 'out_for_delivery', 'delivered'];
const STEP_LABEL = { pending: 'Placed', confirmed: 'Confirmed', shipped: 'Shipped', out_for_delivery: 'Out for delivery', delivered: 'Delivered' };
function timelineHTML(status) {
if (['cancelled', 'returned'].includes(status)) return `
${status.replace('_', ' ')}
`;
const idx = STATUS_STEPS.indexOf(status);
return '' + STATUS_STEPS.map((s, i) =>
`
${STEP_LABEL[s]}
`).join('') + '
';
}
(async function boot() {
const me = await CH.api('/api/auth/me').catch(() => null);
if (!me || !me.user) { window.location.href = '/login?next=/account'; return; }
const user = me.user;
$('#acctName').textContent = user.name.split(' ')[0];
$('#pfName').value = user.name; $('#pfPhone').value = user.phone || ''; $('#pfEmail').value = user.email;
/* tabs */
$$('.acct-tab[data-tab]').forEach(tab => tab.addEventListener('click', () => {
$$('.acct-tab[data-tab]').forEach(t => t.classList.toggle('active', t === tab));
$$('.acct-panel').forEach(p => p.classList.toggle('hidden', p.id !== 'tab-' + tab.dataset.tab));
}));
/* orders */
const list = $('#ordersList');
try {
const { orders } = await CH.api('/api/orders/mine');
if (!orders.length) {
list.innerHTML = '';
} else {
list.innerHTML = orders.map(o => `
Order #${o.id}
${new Date(o.created_at + 'Z').toLocaleDateString('en-IN', { day: 'numeric', month: 'long', year: 'numeric' })}
${o.status.replace(/_/g, ' ')}
Total
${fmt(o.total)}
${o.items.map(i => `
${i.name} × ${i.qty}
HUID ${i.huid || '—'}`).join('')}
${timelineHTML(o.status)}
`).join('');
list.addEventListener('click', (e) => {
const btn = e.target.closest('[data-invoice]'); if (!btn) return;
printInvoice(orders.find(o => o.id === Number(btn.dataset.invoice)));
});
}
} catch { list.innerHTML = 'Could not load your orders. Please refresh.
'; }
/* seller inquiries and replies */
try { const data=await CH.api('/api/customer/seller-inquiries'); if((data.inquiries||[]).length){const box=document.createElement('section');box.className='feature-panel';box.style.marginTop='20px';const h=document.createElement('h2');h.textContent='Seller messages';box.append(h);data.inquiries.forEach(q=>{const item=document.createElement('article');item.className='order-card';const title=document.createElement('b');title.textContent=q.seller_name+' · '+q.subject;const body=document.createElement('p');body.textContent=q.message;item.append(title,body);if(q.response_message){const reply=document.createElement('p');reply.textContent='Seller reply: '+q.response_message;item.append(reply);}else{const waiting=document.createElement('small');waiting.textContent='Awaiting seller response';item.append(waiting);}box.append(item);});list.parentElement.append(box);} } catch { /* seller messaging is optional */ }
/* wishlist */
try {
const { items } = await CH.api('/api/wishlist');
const grid = $('#wishlistGrid');
grid.innerHTML = items.length ? items.map(CH.productCardHTML).join('') : 'Your wishlist is quiet — tap the heart on pieces you love.
';
} catch { /* non-fatal */ }
/* profile save */
$('#profileForm').addEventListener('submit', async (e) => {
e.preventDefault();
try {
const d = await CH.api('/api/auth/me', { method: 'PATCH', body: { name: $('#pfName').value.trim(), phone: $('#pfPhone').value.trim() } });
$('#acctName').textContent = (d.user.name || 'friend').split(' ')[0];
CH.toast('Saved — your details are up to date ✦');
} catch (err) { CH.toast(err.message); }
});
})();
/* ── invoice: render a clean GST-style invoice and print it ── */
function printInvoice(order) {
if (!order) return;
const date = new Date(order.created_at + 'Z').toLocaleDateString('en-IN', { day: 'numeric', month: 'long', year: 'numeric' });
const addr = order.address || {};
const rows = order.items.map((i, n) => `| ${n + 1} | ${i.name}${i.huid ? ' HUID ' + i.huid + '' : ''} | ${i.qty} | ${fmt(i.price)} | ${fmt(i.price * i.qty)} |
`).join('');
const html = `
Chandrahasa
Sterling Silver Collection
ORDER RECEIPT
Order #${String(order.id).padStart(5, '0')}
${date}
Store
Chandrahasa
Bill to
${addr.name || order.email}
${[addr.line1, addr.line2, addr.city, addr.state, addr.pincode].filter(Boolean).join(', ')}
${order.email}
${order.phone}
| # | Item | Qty | Rate | Amount |
${rows}
Subtotal: ${fmt(order.subtotal)}
Discount: –${fmt(order.discount)} ${order.coupon_code ? '(' + order.coupon_code + ')' : ''}
Shipping: ${order.shipping ? fmt(order.shipping) : 'FREE'}${order.address && order.address.giftCharge ? ' · Gift wrap ' + fmt(order.address.giftCharge) : ''}
Total: ${fmt(order.total)} ${order.payment_status === 'paid' ? '— PAID' : '— COD'}
This is an order receipt, not a tax invoice. For a GST tax invoice, seller legal name, registered address, GSTIN and tax breakup must be confirmed by the store before issue.
`;
const box = $('#invoice-print');
box.innerHTML = html;
box.style.display = 'block';
window.print();
setTimeout(() => { box.style.display = 'none'; box.innerHTML = ''; }, 800);
}