diff --git a/README.md b/README.md index c8bab9b..34879b9 100644 --- a/README.md +++ b/README.md @@ -1,13 +1,19 @@ # Pricing Calculator -[](https://github.com/sterlingspares/calc/actions/workflows/tests.yml)          +[](https://github.com/sterlingspares/calc/actions/workflows/tests.yml)          **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 @@