diff --git a/README.md b/README.md index c8bab9b..34879b9 100644 --- a/README.md +++ b/README.md @@ -1,13 +1,19 @@ # Pricing Calculator -[![Tests](https://github.com/sterlingspares/calc/actions/workflows/tests.yml/badge.svg)](https://github.com/sterlingspares/calc/actions/workflows/tests.yml) ![Tests](https://img.shields.io/badge/tests-1352%20passing-brightgreen?style=flat-square) ![Coverage](https://img.shields.io/badge/coverage-80%25-green?style=flat-square) ![Lighthouse Performance](https://img.shields.io/badge/Lighthouse%20Perf-98-brightgreen?style=flat-square&logo=lighthouse) ![Lighthouse Accessibility](https://img.shields.io/badge/Lighthouse%20A11y-100-brightgreen?style=flat-square&logo=lighthouse) ![Lighthouse Best Practices](https://img.shields.io/badge/Best%20Practices-100-brightgreen?style=flat-square&logo=lighthouse) ![a11y](https://img.shields.io/badge/WCAG%202.1-AA-brightgreen?style=flat-square) ![PWA](https://img.shields.io/badge/PWA-offline--ready-brightgreen?style=flat-square&logo=pwa) ![License](https://img.shields.io/badge/license-MIT-blue?style=flat-square) ![PRs Welcome](https://img.shields.io/badge/PRs-welcome-brightgreen.svg) +[![Tests](https://github.com/sterlingspares/calc/actions/workflows/tests.yml/badge.svg)](https://github.com/sterlingspares/calc/actions/workflows/tests.yml) ![Tests](https://img.shields.io/badge/tests-1380%20passing-brightgreen?style=flat-square) ![Coverage](https://img.shields.io/badge/coverage-80%25-green?style=flat-square) ![Lighthouse Performance](https://img.shields.io/badge/Lighthouse%20Perf-98-brightgreen?style=flat-square&logo=lighthouse) ![Lighthouse Accessibility](https://img.shields.io/badge/Lighthouse%20A11y-100-brightgreen?style=flat-square&logo=lighthouse) ![Lighthouse Best Practices](https://img.shields.io/badge/Best%20Practices-100-brightgreen?style=flat-square&logo=lighthouse) ![a11y](https://img.shields.io/badge/WCAG%202.1-AA-brightgreen?style=flat-square) ![PWA](https://img.shields.io/badge/PWA-offline--ready-brightgreen?style=flat-square&logo=pwa) ![License](https://img.shields.io/badge/license-MIT-blue?style=flat-square) ![PRs Welcome](https://img.shields.io/badge/PRs-welcome-brightgreen.svg) **Live app:** [calc.sterlingspares.com](https://calc.sterlingspares.com) -An offline-first web app for MRP-based pricing and profit calculations in -automotive parts distribution. You enter a Maximum Retail Price, describe how -cost and selling price are discounted off it, layer on the incentives your -supplier and your customer actually give you, and it tells you what you make. +An offline-first web app for list-price trading margins. You enter the printed +price, describe how cost and selling price are discounted off it, layer on the +rebates your supplier and your customer actually give you, and it tells you what +you make. + +Built for automotive parts distribution, but the arithmetic is the same in any +trade that buys at a discount off a list price and sells at a smaller one — FMCG, +electronics, pharma, hardware, stationery. If you have ever worked out a quote +by subtracting one percentage from another and then remembered the quarterly +rebate, this is that sum. No build step, no framework, no runtime dependencies. @@ -17,23 +23,43 @@ No build step, no framework, no runtime dependencies. ## What problem it solves -In Indian distribution, the **MRP** printed on the pack is a legal ceiling — no -one in the chain may sell above it. So price is not built up from cost; it is -discounted *down* from the MRP. A distributor buys at, say, 40% off MRP and -sells at 25% off. The gap is the business. +Distribution prices downwards. There is a printed price on the pack — MRP in +India, where it is a legal ceiling nobody in the chain may exceed; RRP or list +price elsewhere — and everyone buys at a discount off it. A distributor buys at, +say, 40% off and sells at 25% off. The gap is the business. + +That shape is not specific to any one trade. Whether the box holds a brake pad, +a shampoo sachet or a laptop, the sum is the same. What makes that hard to hold in your head is that the invoice discount is not the real one. On top of it sit **incentives** — cash discount for paying promptly, early-bird for ordering in a window, quarterly and annual volume rebates, seasonal schemes. None appear on the invoice line, all change what the stock actually cost you. Some of them you receive; others you pass on to your -own customer. Meanwhile every figure has to be tracked both **excl GST** (what -profit is computed from, since the tax is passed through) and **incl GST** (what -you actually quote and negotiate). +own customer. Meanwhile every figure has to be tracked both **excl tax** (what +profit is computed from, since the tax is passed through) and **incl tax** (what +you actually quote and negotiate). The app calls that tax GST, and the rate is +yours to set — 18% and 5% are one tap because they are India's common slabs, but +any rate from 0 to 100% works, so VAT at 20% or GST at 10% behaves identically. This app does that arithmetic, live, so a quote can be checked before it is given rather than regretted after. +### Who it fits + +| | | +|---|---| +| **Any list-price trade** | Auto parts, FMCG, electronics, pharma, hardware — anywhere you buy and sell at discounts off a printed price, with rebates that never touch the invoice | +| **Import and export** | The cost side and the sale side can be shown in different currencies, so buying in one and selling in another is a supported case rather than a workaround. Landed costs are per-unit, inbound and outbound | +| **Outside India** | Set **Show** to *Cost & Sale* in your own currency and nothing on the calculator is in rupees — the list price included. The maths is all ratios and one tax rate, so the unit is yours to choose | + +Rupees remain the internal unit everything is stored in, but that is an +implementation detail rather than something you see: under *Cost & Sale* every +field and figure, MRP among them, is entered and shown in the currency you pick. +Under a one-sided scope the printed price deliberately stays in rupees — an +exporter quoting in dollars still buys against a rupee MRP, and a rate update +must not restate a figure fixed by law. + ### A worked example The screenshot above, step by step. A part with an MRP of ₹1,000 at 18% GST, @@ -60,10 +86,10 @@ easy to forget. | Term | Means | |---|---| -| **MRP** | Maximum Retail Price — the ceiling printed on the pack. Every price is a discount off it | +| **MRP** | Maximum Retail Price — the price printed on the pack, and a legal ceiling in India. Read it as RRP or list price elsewhere; every price is a discount off it | | **CP** | Cost Price — what you pay your supplier | | **SP** | Selling Price — what you charge your customer | -| **GST** | Goods and Services Tax. Auto parts are usually 18%, some 5% | +| **GST** | The pass-through sales tax. 18% and 5% are one tap (India's common slabs); any rate 0–100% works, so VAT behaves the same | | **Incentive** | An off-invoice discount — cash discount, rebate, scheme — that changes real cost without changing the invoice line | | **Effective CP / SP** | The price after incentives and landed costs. Profit is computed from these, not from the invoice figures | | **Landed cost** | Per-unit freight, insurance or handling — added to CP inbound, deducted from SP outbound | @@ -127,8 +153,8 @@ docs/ screenshots for this README ## Pricing The control bar carries only what changes per calculation: **GST**, what to -**Calculate**, and **Reset**. Presets live in the header menu (or `E`), and the -currency control in Settings → Pricing → Currency — neither changes from one +**Calculate**, and **Reset**. Presets have their own header button (or `E`), and the +currency control lives in Settings → Pricing → Currency — neither changes from one quote to the next. ### MRP and GST @@ -228,9 +254,11 @@ currency — twenty are available: | **Cost & Sale** | both of the above | Profit follows the **sale** side, because that is the currency the money arrives -in. **MRP is never converted** under any scope: it is a rupee price fixed by law, -and converting it would let a rate update restate the one figure in the deal that -cannot move. +in. **MRP follows *Cost & Sale* only.** Under a one-sided scope it stays in +rupees — an exporter quoting abroad still buys against a rupee MRP, and a rate +update must not restate a figure fixed by law. Under *Cost & Sale* the whole deal +has been declared to be in another currency, so the printed price is too, which +is how a trader outside India works entirely in theirs. Fields on a converted side are **entered in that currency too** — a box showing `$` holds dollars. Switching currency re-expresses what you typed, so a ₹50 @@ -340,8 +368,8 @@ Incentive setups repeat — one supplier's terms, one dealer's scheme. A preset snapshots both panels entirely: the rows, their names, their % / ₹ modes, which are switched on, the values in them, and the CD/Scheme base selectors. -Everything lives in one manager, reached from the header menu, **Settings → -Features → Saved presets**, or `E`: +Everything lives in one manager, reached from the **Presets** button in the +header, **Settings → Features → Saved presets**, or `E`: | Action | Where | What it does | |---|---|---| @@ -389,7 +417,7 @@ so the quotable price is grossed back up accordingly. ### Target-margin solver -Below the break-even rows, enter a **Target GP %** and it answers the question +In the summary, beside Margin %, enter a **Target GP %** and it answers the question directly rather than making you converge on it by trial and error. What it says depends on which side of the target you are on: @@ -512,6 +540,7 @@ switched off hides rather than leading nowhere. | **Exchange rates** | Update now, and set a manual rate | | **App tour** | Restart the onboarding walkthrough | | **Keyboard shortcuts** | View all shortcuts | +| **Reset everything** | Clear every saved key and start as if the app were new | Floor limits, auto-save preference and theme persist across sessions. @@ -523,10 +552,9 @@ and it disappears from the screen: | | | |---|---| -| **Presets** | the control-bar picker and the manager | +| **Presets** | the header button, menu entry and the manager | | **Quote builder** | the header button, menu item and bottom-nav tab | | **What-if scenarios** | the button on the summary | -| **Currency conversion** | the Show control; the display returns to rupees | | **Landed costs** | both fields in the MRP bar | | **Target GP solver** | the row under break-even | | **Incentives on CP** · **Incentives on SP** | the whole panel; the Incentives tab goes when both are off | @@ -628,7 +656,11 @@ taken by Solve-for-Profit and Settings, so presets use `E`. | `pc-theme` | Dark / light preference | | `ob-done` | Onboarding completion flag | -A URL share (`?s=…`) encodes calculator state as base64 JSON and takes +A **Settings → Help → Reset everything** clears exactly these keys — not +`localStorage.clear()`, since the origin may hold something that is not ours — +and reloads, so the app comes up the way a new visitor sees it. + +URL share (`?s=…`) encodes calculator state as base64 JSON and takes **priority over localStorage** on load. Every field is allow-listed on the way in — an unrecognised or malformed payload is discarded, not partially applied. @@ -702,7 +734,7 @@ Every number here is reproducible from the repo — none is hand-written. | Metric | Value | Reproduce with | |---|---|---| -| Tests | 1352 passing, 7 suites | `npm test` | +| Tests | 1380 passing, 7 suites | `npm test` | | Statement coverage | **82.6%** (app.js 86.3%, app-extra.js 68.5%) | `npm run coverage` | | Lighthouse Performance | **98** | `npm i -D lighthouse && npm run lighthouse` | | Lighthouse Accessibility | **100** | ” | @@ -730,7 +762,7 @@ commands after significant changes. ## Tests -1352 assertions across seven suites. They load the real `index.html`, +1380 assertions across seven suites. They load the real `index.html`, `assets/styles.css` and both script bundles, and drive the actual application functions — no application code is mocked. **Node 22 or newer.** @@ -741,7 +773,7 @@ npm test | Suite | Assertions | Covers | |---|---|---| -| `features` | 925 | GST, incentives, quantity, landed costs, rounding, undo/redo, quote maths, history | +| `features` | 953 | GST, incentives, quantity, landed costs, rounding, undo/redo, quote maths, history | | `errors` | 33 | every failure path logs; a clean run stays silent; storage and payload recovery | | `mobile` | 78 | modal layering, touch targets, sticky result bar, responsive quote layouts | | `fab` | 50 | floating action button behaviour and z-index ordering | diff --git a/assets/app.js b/assets/app.js index 6cf4eac..063ff9c 100644 --- a/assets/app.js +++ b/assets/app.js @@ -670,7 +670,7 @@ var SYM_SIDES={ }; /** Fields whose typed value is an amount, and the side it is quoted in. */ var MONEY_FIELDS=[ - {id:'cpv',side:'cost'},{id:'spv',side:'sale'}, + {id:'mrp',side:'base'},{id:'cpv',side:'cost'},{id:'spv',side:'sale'}, {id:'pri',side:'sale'},{id:'landed',side:'cost'},{id:'sp-landed',side:'sale'} ]; /** @@ -826,7 +826,6 @@ function renderFxNote(){ * @param {string} c currency code */ function setDisplayCcy(c,scope){ - if(!featOn('forex')&&c!=='INR')return; if(CCY_CODES.indexOf(c)===-1){ logWarn('ignoring unknown currency '+JSON.stringify(c)); c='INR'; @@ -883,11 +882,13 @@ var FX_SCOPES=['cost','sale','both']; */ function ccyFor(side){ if(DISPLAY_CCY==='INR')return'INR'; - // MRP is a rupee price printed on the pack by law — there is no dollar MRP — - // so it and the figures derived straight from it stay in rupees under every - // scope. Converting it would also mean a rate update silently restating the - // one number in the deal that cannot move. - if(side==='base')return'INR'; + // MRP follows 'both' and nothing else. Under a one-sided scope it stays in + // rupees, because an exporter quoting in dollars still buys against a rupee + // MRP and a rate update must not restate the one figure fixed by law. Under + // 'both' the whole deal has been declared to be in another currency — which + // is how a trader outside India works in theirs — so the printed price is in + // that currency too, and there is no rupee left on screen. + if(side==='base')return FX_SCOPE==='both'?DISPLAY_CCY:'INR'; if(side==='cost')return(FX_SCOPE==='cost'||FX_SCOPE==='both')?DISPLAY_CCY:'INR'; return(FX_SCOPE==='sale'||FX_SCOPE==='both')?DISPLAY_CCY:'INR'; } @@ -1030,7 +1031,27 @@ var FOCUSABLE='a[href],button:not([disabled]),input:not([disabled]),select:not([ /** Element that had focus before the current dialog opened, restored on close. */ var _lastFocused=null; /** The open dialog's overlay, or null. Used by the Tab handler. */ +/* Dialogs can stack: the preset manager opens the naming dialog, which opens a + confirmation. Tracking only the newest one left the focus trap pointing at + nothing once the top dialog closed, so Tab escaped into the page behind. */ +var _overlayStack=[]; var _openOverlay=null; +/** Push a dialog onto the stack and give it the focus trap. */ +function pushOverlay(o){ + if(!o)return; + var i=_overlayStack.indexOf(o); + if(i!==-1)_overlayStack.splice(i,1); + _overlayStack.push(o); + _openOverlay=o; +} +/** Remove a dialog and hand the trap back to whatever is still open. */ +function popOverlay(o){ + var i=_overlayStack.indexOf(o); + if(i!==-1)_overlayStack.splice(i,1); + _openOverlay=_overlayStack.length?_overlayStack[_overlayStack.length-1]:null; + // Only release the scroll lock once nothing is left open. + if(!_overlayStack.length)document.body.style.overflow=''; +} /** * Visible focusable descendants of an element. @@ -1083,7 +1104,7 @@ function openModal(id){ _lastFocused=document.activeElement; o.classList.add('open'); document.body.style.overflow='hidden'; - _openOverlay=o; + pushOverlay(o); } if(id==='whatif')renderWhatIf(LAST_CP); if(id==='quote')withExtras(function(){qtRender()}); @@ -1103,7 +1124,7 @@ function closeModal(id){ if(!o||!o.classList.contains('open'))return; o.classList.remove('open'); document.body.style.overflow=''; - if(_openOverlay===o)_openOverlay=null; + popOverlay(o); // Return focus to whatever opened the dialog, so keyboard users are not // dumped back at the top of the document. if(_lastFocused&&typeof _lastFocused.focus==='function'){ @@ -1152,14 +1173,14 @@ function onCustomGST(inp){ adding a feature is one entry rather than edits in four places, and the tests can walk the registry rather than naming elements by hand. ─────────────────────────────────────────────────────────────────────────── */ -var FEATURES={presets:true,quote:true,whatif:true,forex:true,landed:true,solver:true,inccp:true,incsp:true}; +var FEATURES={presets:true,quote:true,whatif:true,landed:true,solver:true,inccp:true,incsp:true}; /** True when the named feature is switched on. Unknown keys read as on. */ function featOn(k){ return FEATURES[k]!==false } var FEATURE_DEFS=[ {k:'presets',name:'Presets',hint:'Save and reuse incentive setups.', - els:['hmenu-presets','sec-set-presets'], + els:['hbtn-presets','hmenu-presets','sec-set-presets'], values:function(){ var n=Object.keys(PRESETS).length; return n?[n+' saved preset'+(n===1?'':'s')]:[] }, clear:function(){ PRESETS={}; savePresets(); renderPresetList(); renderPresetManager(); }}, @@ -1180,16 +1201,6 @@ var FEATURE_DEFS=[ closeModal('whatif'); }}, - {k:'forex',name:'Currency conversion',hint:'Show either side of the deal in another currency.', - els:['sec-set-forex'], - values:function(){ - var out=[]; - if(DISPLAY_CCY!=='INR')out.push('showing '+DISPLAY_CCY); - var m=Object.keys(FX.manual||{}).filter(function(c){return FX.manual[c]>0}); - if(m.length)out.push(m.length+' manual rate'+(m.length===1?'':'s')); - return out; - }, - clear:function(){ FX.manual={}; saveFx(); setDisplayCcy('INR','both'); }}, {k:'landed',name:'Landed costs',hint:'Per-unit freight in and out.', els:['stat-landed-cp','stat-landed-sp'], @@ -1260,6 +1271,39 @@ function applyFeatureVisibility(){ if(nInc)nInc.style.display=(featOn('inccp')||featOn('incsp'))?'':'none'; } +/** + * Put the app back to how it ships. + * + * Every key this app writes, not localStorage.clear() — the origin may hold + * something that is not ours, and wiping a neighbour's data would be a rude + * way to reset a calculator. The list is the same one documented in the README. + */ +var STORAGE_KEYS=['pc-state','pc-history','pc-labels','pc-presets','pc-qstate', + 'pc-quote','pc-theme','pc-fx','pc-features','ob-done']; +function factoryReset(){ + var held=[]; + if(HISTORY.length)held.push(HISTORY.length+' history entr'+(HISTORY.length===1?'y':'ies')); + var np=Object.keys(PRESETS).length; + if(np)held.push(np+' preset'+(np===1?'':'s')); + if(QUOTE.length)held.push(QUOTE.length+' quote line'+(QUOTE.length===1?'':'s')); + var off=FEATURE_DEFS.filter(function(f){return !featOn(f.k)}).length; + if(off)held.push(off+' switched-off feature'+(off===1?'':'s')); + askConfirm('Reset the app', + held.length?('This will clear '+held.join(', ')+', along with every setting.') + :'This will clear every saved setting and start fresh.', + 'It cannot be undone — undo history goes too.','Reset everything',function(){ + STORAGE_KEYS.forEach(function(k){ + try{ localStorage.removeItem(k) }catch(e){ logError('could not clear '+k,e) } + }); + // Reload rather than unpick the state by hand: every module reads its own + // storage on boot, so a fresh load is the one path guaranteed to agree + // with what a new visitor sees. + try{ location.replace(location.pathname) } + catch(e){ logError('could not reload after reset',e); location.reload() } + }); +} +ACT.factoryReset = function(){ factoryReset() }; + /* ── Settings tabs ────────────────────────────────────────────────────────── Eight stacked sections became a long scroll that was hard to find anything in. They are grouped into four panes behind a nav rail, which becomes a @@ -1555,7 +1599,7 @@ function askConfirm(title,msg,sub,btnLabel,fn){ _lastFocused=document.activeElement; o.classList.add('open'); document.body.style.overflow='hidden'; - _openOverlay=o; + pushOverlay(o); // Focus Cancel, not the destructive button — a stray Enter should not delete. setTimeout(function(){ var cancel=o.querySelector('.confirm-btn:not(.danger)'); @@ -1618,7 +1662,7 @@ function askPrompt(o){ _lastFocused=document.activeElement; ov.classList.add('open'); document.body.style.overflow='hidden'; - _openOverlay=ov; + pushOverlay(ov); // Select the text so typing replaces it, which is what prompt() did. setTimeout(function(){if(inp){inp.focus();if(inp.select)inp.select()}},30); } @@ -1656,7 +1700,7 @@ function closePrompt(){ if(ov&&ov.classList.contains('open')){ ov.classList.remove('open'); document.body.style.overflow=''; - if(_openOverlay===ov)_openOverlay=null; + popOverlay(ov); if(_lastFocused&&_lastFocused.focus)_lastFocused.focus(); } } @@ -1677,7 +1721,7 @@ function closeConfirm(){ if(o&&o.classList.contains('open')){ o.classList.remove('open'); document.body.style.overflow=''; - if(_openOverlay===o)_openOverlay=null; + popOverlay(o); if(_lastFocused&&typeof _lastFocused.focus==='function'){ try{_lastFocused.focus()}catch(e){logWarn('could not restore focus after closing confirm',e)} } diff --git a/assets/styles.css b/assets/styles.css index 5274497..39fdc44 100644 --- a/assets/styles.css +++ b/assets/styles.css @@ -104,6 +104,8 @@ body{font-family:var(--font-body);background:var(--bg);color:var(--text);min-hei .pill{padding:5px 13px;border-radius:20px;border:1px solid var(--border-ctrl);background:transparent;font-size:12px;font-weight:500;color:var(--text2);cursor:pointer;font-family:var(--font-body);transition:all .15s;white-space:nowrap} .pill:hover{border-color:var(--border2);color:var(--text)} .pill.on{background:var(--accent);color:#fff;border-color:var(--accent)} +.pill.danger-pill{border-color:var(--red);color:var(--red)} +.pill.danger-pill:hover{background:var(--red);color:#fff} .divider{width:1px;height:24px;background:var(--border);flex-shrink:0} .sep{flex:1;min-width:8px} .btn-reset{display:flex;align-items:center;gap:6px;padding:5px 14px;border-radius:20px;border:1px solid var(--border-ctrl);background:transparent;font-size:12px;font-weight:500;color:var(--text2);cursor:pointer;font-family:var(--font-body);transition:all .15s} @@ -278,7 +280,10 @@ body{font-family:var(--font-body);background:var(--bg);color:var(--text);min-hei .preset-btn.danger:hover:not(:disabled){border-color:var(--red);color:var(--red)} /* Inside the summary card, so it inherits the dark treatment */ -.solver{margin-top:14px;padding-top:12px;border-top:1px solid rgba(255,255,255,0.16);display:flex;align-items:center;gap:10px;flex-wrap:wrap} +/* A grid item now, not a row of its own. Margin % used to sit alone on the + second line with five empty columns beside it while the solver took a + whole extra row under a divider; it fills that gap instead. */ +.solver{grid-column:span 3;display:flex;align-items:center;gap:10px;flex-wrap:wrap;align-self:start} .solver-lbl{font-size:10px;letter-spacing:.09em;text-transform:uppercase;color:rgba(255,255,255,0.55);font-weight:600;white-space:nowrap} .solver-input{display:inline-flex;align-items:center;border:1px solid rgba(255,255,255,0.42);border-radius:20px;padding:1px 9px;background:rgba(255,255,255,0.08)} .solver-input:focus-within{border-color:#fff;background:rgba(255,255,255,0.14)} @@ -286,7 +291,7 @@ body{font-family:var(--font-body);background:var(--bg);color:var(--text);min-hei .solver-input input::-webkit-outer-spin-button,.solver-input input::-webkit-inner-spin-button{-webkit-appearance:none;margin:0} .solver-input input::placeholder{color:rgba(255,255,255,0.55)} .solver-input::after{content:'%';font-size:11px;color:rgba(255,255,255,0.55);margin-left:3px} -.solver-out{flex:1;min-width:220px;font-size:11.5px;line-height:1.5;color:rgba(255,255,255,0.75)} +.solver-out{flex:1;min-width:180px;font-size:11.5px;line-height:1.5;color:rgba(255,255,255,0.75)} .solver-out.ok{color:#8fe3b0} .solver-out.bad{color:#ffb4ab} @media(max-width:800px){ @@ -388,6 +393,12 @@ html[data-theme="dark"] .hist-del-btn:hover{background:rgba(239,68,68,0.15);bord /* z-index must beat .bottom-nav (500), or the nav renders over the dialog on mobile and can obstruct its buttons. */ .modal-overlay{display:none;position:fixed;inset:0;background:rgba(10,10,8,0.55);z-index:600;align-items:flex-start;justify-content:center;padding:clamp(1rem,3vw,2rem);overflow-y:auto;backdrop-filter:blur(2px)} +/* The naming and confirmation dialogs are always secondary — raised from the + preset manager, from Settings, from a history row. At the shared z-index + they were ordered by position in the markup, so the prompt raised from + the preset manager painted behind it. */ +#overlay-prompt,#overlay-confirm{z-index:640} + .modal-overlay.open{display:flex} .modal{background:var(--surface);border-radius:var(--radius);box-shadow:var(--shadow-modal);width:100%;max-width:720px;margin:auto;animation:modalIn var(--dur-slow) var(--ease-spring)} @keyframes modalIn{0%{opacity:0;transform:translateY(-14px) scale(.97)}60%{opacity:1}100%{opacity:1;transform:none}} @@ -936,6 +947,7 @@ html[data-theme="dark"] .qt-del:hover{background:rgba(239,68,68,0.15)} sits before the base rules they override — so .pm-btn kept its 30px height and .fx-note kept nowrap. Same specificity, later wins. */ .inc-pair{grid-template-columns:1fr;gap:10px} + .solver{grid-column:1/-1;padding-top:10px;border-top:1px solid rgba(255,255,255,0.16)} .fx-note{white-space:normal;width:100%} .fx-manual-wrap input{min-height:44px} .pm-row{flex-direction:column;align-items:stretch;gap:8px} diff --git a/docs/screenshot-mobile.png b/docs/screenshot-mobile.png index d516c9f..ad3391b 100644 Binary files a/docs/screenshot-mobile.png and b/docs/screenshot-mobile.png differ diff --git a/docs/screenshot.png b/docs/screenshot.png index 6ff8ede..6d35d19 100644 Binary files a/docs/screenshot.png and b/docs/screenshot.png differ diff --git a/index.html b/index.html index fb5befa..0f408be 100644 --- a/index.html +++ b/index.html @@ -96,6 +96,10 @@

Price Calc

PDF + +
+
+ Reset everything + Clear every saved setting, preset, quote and history entry, and start as if the app were new. +
+
+ +
+
Keyboard shortcuts diff --git a/tests/README.md b/tests/README.md index 10a1335..aa16c86 100644 --- a/tests/README.md +++ b/tests/README.md @@ -1,6 +1,6 @@ # Tests -1352 assertions across seven suites. They load the real `index.html`, +1380 assertions across seven suites. They load the real `index.html`, `assets/styles.css` and `assets/app.js` into [jsdom](https://github.com/jsdom/jsdom) and drive the actual application functions — no application code is mocked. @@ -33,7 +33,7 @@ The runner exits non-zero if anything fails, so CI catches it. | File | Assertions | Covers | |---|---|---| -| `features.test.js` | 925 | GST (presets, custom, decimal), incentive edit mode, add/delete/rename, %/₹ modes, quantity and order totals, rounding, undo/redo, quote maths, history search/filter/tags, share-state round trips | +| `features.test.js` | 953 | GST (presets, custom, decimal), incentive edit mode, add/delete/rename, %/₹ modes, quantity and order totals, rounding, undo/redo, quote maths, history search/filter/tags, share-state round trips | | `errors.test.js` | 33 | every failure path logs; a clean run logs nothing; storage-quota and corrupt-payload recovery; global handlers | | `mobile.test.js` | 78 | modal layering vs the bottom nav, touch-target sizes, viewport zoom policy, type scale, sticky result bar states, quote table vs card layouts | | `fab.test.js` | 50 | FAB visibility rules, open/close and dismissal, ARIA state, deferred dispatch, error containment, z-index ordering | diff --git a/tests/features.test.js b/tests/features.test.js index 69ed083..4bf5760 100644 --- a/tests/features.test.js +++ b/tests/features.test.js @@ -2119,8 +2119,9 @@ w.setDisplayCcy('USD'); ok('a foreign currency groups in thousands, not lakhs', w.SINR(987654321.55) === '$987,654,321.55', w.SINR(987654321.55)); ok('and at a million exactly', w.SINR(1000000) === '$1,000,000.00', w.SINR(1000000)); -// MRP is never converted, so the base formatter stays in rupees throughout. -ok('MRP stays in rupees even so', w.INR(1000000) === '₹10,00,000.00', w.INR(1000000)); +// MRP follows the 'both' scope only; the block above is in 'both', so it +// converts here and groups in thousands like any other foreign amount. +ok('MRP converts under the both scope', w.INR(1000000) === '$1,000,000.00', w.INR(1000000)); w.setDisplayCcy('EUR'); ok('same for the euro', w.SINR(1234567.891) === '€1,234,567.89', w.SINR(1234567.891)); w.setDisplayCcy('AED'); @@ -2402,14 +2403,22 @@ runFetchCases().then(() => { ['cve', 's-ecp', 's-inc', 'sve', 's-esp', 's-pr', 's-be'].every(i => startsUsd(cell(i))), ['cve', 's-ecp', 's-inc', 'sve', 's-esp', 's-pr', 's-be'].map(i => cell(i)).join(' ')); - // ── MRP is never converted ────────────────────────────────────────────── - // There is no dollar MRP: it is a rupee price fixed by law, and converting it - // would let a rate update restate the one figure that cannot move. - ['cost', 'sale', 'both'].forEach(scope => { + // ── MRP follows 'both' and nothing else ───────────────────────────────── + // Under a one-sided scope an exporter still buys against a rupee MRP, and a + // rate update must not restate a figure fixed by law. Under 'both' the whole + // deal has been declared to be in another currency, which is how a trader + // outside India works entirely in theirs. + ['cost', 'sale'].forEach(scope => { w.setDisplayCcy('USD', scope); ok(scope + ': MRP stays in rupees', startsRs(cell('mx')), cell('mx')); ok(scope + ': and so does its input prefix', sym('sym-mrp') === '₹', sym('sym-mrp')); }); + w.setDisplayCcy('USD', 'both'); + ok('both: MRP converts with everything else', startsUsd(cell('mx')), cell('mx')); + ok('both: and its input prefix follows', sym('sym-mrp') === '$', sym('sym-mrp')); + ok('both: leaving no rupee sign anywhere on the calculator', + ['mx', 's-ecp', 's-esp', 's-pr'].every(i => !startsRs(cell(i))), + ['mx', 's-ecp', 's-esp', 's-pr'].map(i => cell(i)).join(' ')); // ── Rounding follows the sticker price, i.e. the sale side ────────────── w.setDisplayCcy('USD', 'sale'); @@ -2692,6 +2701,24 @@ ok('break-even moved into the profit card', ok('and left the summary', !sumLabels.some(l => l.indexOf('Break-even') === 0), sumLabels.join(' · ')); +// The solver shares the summary grid rather than taking a row of its own: +// Margin % was sitting alone on the second line with five empty columns beside +// it while the solver sat under a divider below. +ok('the target-GP solver is part of the summary grid', + d.getElementById('solver').parentElement.className.indexOf('summary-grid') !== -1, + d.getElementById('solver').parentElement.className); +ok('it spans several columns rather than one', + /\.solver\{[^}]*grid-column:span \d/.test(readAsset('assets/styles.css')), + 'no column span'); +// Anchored to the start of a line: the mobile override is indented and does +// keep a divider, since it goes full width there. +ok('and no longer draws its own divider on desktop', + !/^\.solver\{[^}]*border-top/m.test(readAsset('assets/styles.css')), + 'still has a border-top'); +ok('but goes full width on a phone', + /grid-column:1\/-1/.test(mobileRule(readAsset('assets/styles.css'), '.solver')), + mobileRule(readAsset('assets/styles.css'), '.solver')); + // The two incentive panels sit side by side rather than stacked. ok('the incentive panels are paired', d.querySelector('.inc-pair') !== null && @@ -2818,6 +2845,94 @@ R.section('\n=== 31. Settings is grouped into tabs ==='); w.SETTINGS_TAB); w.closeModal('settings'); + R.section('\n=== 31b. Stacked dialogs, header presets, factory reset ==='); + + // ── A dialog raised from a dialog must paint above it ─────────────────── + // Saving a preset from the manager opened the naming dialog behind it: both + // are .modal-overlay, and at the same z-index the one later in the markup + // wins. It also left the focus trap pointing at the closed dialog. + // The raised rule is a grouped selector, so the name may not start the line. + const zFor = sel => { + const m = readAsset('assets/styles.css').match( + new RegExp('(^|,)' + sel.replace(/[#.]/g, '\\$&') + '[^{]*\\{[^}]*z-index:(\\d+)', 'm')); + return m ? +m[2] : null; + }; + ok('the naming dialog outranks an ordinary one', + zFor('#overlay-prompt') > zFor('.modal-overlay'), + zFor('#overlay-prompt') + ' vs ' + zFor('.modal-overlay')); + ok('so does the confirmation', zFor('#overlay-confirm') > zFor('.modal-overlay')); + + w.PRESETS = {}; + w.openModal('settings'); + ok('the trap starts on Settings', w._openOverlay.id === 'overlay-settings', w._openOverlay.id); + w.ACT.settingsPresets(); + ok('Manage closes Settings and opens the manager', + !overlayOpen('settings') && overlayOpen('presets')); + w.savePresetAs(); + ok('the naming dialog opens over the manager', + overlayOpen('prompt') && overlayOpen('presets')); + ok('and takes the focus trap', w._openOverlay.id === 'overlay-prompt', w._openOverlay.id); + d.getElementById('prompt-input').value = 'Bosch'; + w.validatePrompt(); w.runPrompt(); + ok('saving closes only the top dialog', + !overlayOpen('prompt') && overlayOpen('presets')); + ok('and the trap goes back to the manager', + w._openOverlay.id === 'overlay-presets', w._openOverlay && w._openOverlay.id); + w.deletePreset('Bosch'); + ok('a confirmation stacks too', overlayOpen('confirm') && overlayOpen('presets')); + ok('and the trap follows it', w._openOverlay.id === 'overlay-confirm'); + w.closeConfirm(); + ok('cancelling hands the trap back', w._openOverlay.id === 'overlay-presets'); + w.closeModal('presets'); + ok('with everything closed there is no trap', w._openOverlay === null); + ok('and the scroll lock is released', d.body.style.overflow === ''); + + // ── Presets is reachable from the header ──────────────────────────────── + ok('there is a Presets button in the header', d.getElementById('hbtn-presets') !== null); + ok('beside Quote', d.getElementById('hbtn-presets').nextElementSibling.id === 'hbtn-quote', + d.getElementById('hbtn-presets').nextElementSibling.id); + ok('and it opens the manager', (() => { + w.PRESETS = {}; + w.ACT.presetManage(); + const open = overlayOpen('presets'); + w.closeModal('presets'); + return open; + })()); + ok('the switch hides it along with the menu entry', + w.featureDef('presets').els.indexOf('hbtn-presets') !== -1, + w.featureDef('presets').els.join(',')); + + // ── Factory reset ─────────────────────────────────────────────────────── + w.HISTORY.push({ mrp: 900, cpE: 1, spE: 2, pr: 1, gp: 1, mg: 1, gst: 18, time: w.nowMs() }); + w.PRESETS = { A: w.capturePreset() }; + w.QUOTE.push({ mrp: '1000', cpd: '40', spd: '25', qty: '1' }); + w.factoryReset(); + ok('reset asks before wiping anything', overlayOpen('confirm')); + ok('and says what is held', + d.getElementById('confirm-msg').textContent.indexOf('1 history entry') !== -1 && + d.getElementById('confirm-msg').textContent.indexOf('1 preset') !== -1 && + d.getElementById('confirm-msg').textContent.indexOf('1 quote line') !== -1, + d.getElementById('confirm-msg').textContent); + ok('and warns it is final', + d.getElementById('confirm-sub').textContent.indexOf('cannot be undone') !== -1, + d.getElementById('confirm-sub').textContent); + w.closeConfirm(); + ok('cancelling changes nothing', + w.HISTORY.length === 1 && Object.keys(w.PRESETS).length === 1 && w.QUOTE.length === 1); + + // It clears the app's own keys rather than the whole origin. + ok('it names every key the app writes', + ['pc-state', 'pc-history', 'pc-labels', 'pc-presets', 'pc-qstate', 'pc-quote', + 'pc-theme', 'pc-fx', 'pc-features', 'ob-done'].every(k => w.STORAGE_KEYS.indexOf(k) !== -1), + w.STORAGE_KEYS.join(',')); + // Comments stripped first: the reason for not using it is written next to the + // key list, and matching prose would fail on the explanation itself. + ok('and does not reach for localStorage.clear()', + !/localStorage\.clear\(\)/.test( + readAsset('assets/app.js').replace(/\/\*[\s\S]*?\*\//g, '').replace(/^\s*\/\/.*$/gm, '')), + 'wipes the whole origin'); + w.HISTORY.length = 0; w.QUOTE.length = 0; w.PRESETS = {}; + R.section('\n=== 32. Turning features off ==='); // Walk the registry rather than naming elements here: a feature added later @@ -2825,12 +2940,18 @@ R.section('\n=== 31. Settings is grouped into tabs ==='); freshCalc(1000, 40, 25); w.setDisplayCcy('INR', 'both'); w.openModal('settings'); - ok('a switch per feature', d.querySelectorAll('#feat-grid .feat-chip').length === 8, + ok('a switch per feature', d.querySelectorAll('#feat-grid .feat-chip').length === 7, 'got ' + d.querySelectorAll('#feat-grid .feat-chip').length); - ok('all eight are named', - ['presets', 'quote', 'whatif', 'forex', 'landed', 'solver', 'inccp', 'incsp'] + ok('all seven are named', + ['presets', 'quote', 'whatif', 'landed', 'solver', 'inccp', 'incsp'] .every(k => w.FEATURE_DEFS.some(f => f.k === k)), w.FEATURE_DEFS.map(f => f.k).join(',')); + // Currency is configured in Settings → Pricing, so a switch for it here was a + // second place to look for the same setting. + ok('currency is not among them', !w.FEATURE_DEFS.some(f => f.k === 'forex'), + w.FEATURE_DEFS.map(f => f.k).join(',')); + ok('but its settings section is still there', + d.getElementById('sec-set-forex') !== null); ok('each switch reports its state to assistive tech', [...d.querySelectorAll('#feat-grid .feat-chip')] .every(b => b.getAttribute('role') === 'switch' && b.getAttribute('aria-checked') === 'true')); @@ -2921,12 +3042,6 @@ R.section('\n=== 31. Settings is grouped into tabs ==='); d.getElementById('bnav-inc').style.display === 'none', d.getElementById('bnav-inc').style.display); - // Turning off the currency feature returns the display to rupees. - w.toggleFeature('forex'); w.runConfirm(); - ok('turning off currency goes back to rupees', w.DISPLAY_CCY === 'INR', w.DISPLAY_CCY); - w.setDisplayCcy('USD', 'sale'); - ok('and it cannot be set again while off', w.DISPLAY_CCY === 'INR', w.DISPLAY_CCY); - w.toggleFeature('whatif'); w.runConfirm(); ok('every feature is now off', w.FEATURE_DEFS.every(f => !w.featOn(f.k)), w.FEATURE_DEFS.filter(f => w.featOn(f.k)).map(f => f.k).join(',')); @@ -2934,7 +3049,13 @@ R.section('\n=== 31. Settings is grouped into tabs ==='); w.FEATURE_DEFS.every(f => f.els.every(id => { const e = d.getElementById(id); return !e || e.style.display === 'none'; }))); - // The calculator itself still works with everything switched off. + // The calculator itself still works with everything switched off. Back to + // rupees and re-enter the price first: MRP follows the 'both' scope, so the + // 1000 typed earlier while dollars were showing genuinely meant $1,000 — + // switching back re-expresses it as ₹100,000, which is right but is not what + // this block is asserting. + w.setDisplayCcy('INR', 'both'); + d.getElementById('mrp').value = '1000'; w.calc(); ok('the core calculation survives with everything off', Math.abs(w.LAST_CP.e - 600) < 0.01 && Math.abs(w.LAST_SP.e - 750) < 0.01,