diff --git a/README.md b/README.md index 3e65223..6f951a0 100644 --- a/README.md +++ b/README.md @@ -1,6 +1,6 @@ # 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-1406%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-97-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-1479%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-97-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) @@ -76,7 +76,7 @@ rebate from the supplier: | **Profit** | **₹168.00** | ₹750.00 − ₹582.00 | | GP % | 22.40% | 168 ÷ 750 | | Margin % | 28.87% | 168 ÷ 582 | -| Break-even SP | ₹686.76 | incl GST — below this you lose money | +| Break-even SP (incl GST) | ₹686.76 | incl GST — below this you lose money | Without the two incentives the same deal shows ₹150.00 profit and 20.00% GP. That 3% off-invoice is a fifth of the profit, and it is exactly the part that is @@ -145,7 +145,7 @@ sw.js service worker manifest.json PWA manifest _headers response headers for the host tests/ test suite (dev-only) -docs/ screenshots for this README +docs/ screenshots for this README (npm run screenshots) robots.txt · sitemap.xml indexing ``` @@ -410,8 +410,8 @@ Shown in the **Profit card**, beside the profit they are measured against: | Row | Meaning | |---|---| -| **Break-even SP** | Price at which profit reaches zero | -| **SP at GP floor** | Price at which GP % hits your Settings floor | +| **Break-even SP (incl GST)** | Price at which profit reaches zero | +| **SP at GP floor (incl GST)** | Price at which GP % hits your Settings floor | Both are stated *before* SP incentives — those reduce what you actually receive, so the quotable price is grossed back up accordingly. @@ -449,6 +449,26 @@ takes its own SP input (discount % or manual ₹) and shows SP, Profit ₹, GP % Margin %. The highest-GP scenario is highlighted automatically, and everything updates live. +### GP % / markup % converter + +Two ways of quoting the same profit, over different denominators — which is why +a supplier offering "25%" and a customer expecting "25%" can mean different +money. **GP ⇄ Markup** in the header takes either and returns the other: + +| GP % | Markup % | +|---:|---:| +| 20.00 | 25.00 | +| 25.00 | 33.33 | +| 50.00 | 100.00 | + +`markup = GP ÷ (100 − GP)` and `GP = markup ÷ (100 + markup)`. It shows the +result as money as well — *buy at ₹100.00, sell at ₹125.00* — because a +percentage on its own is easy to nod along to. **Use this calculation** seeds it +from whatever is on screen, and the two ends with no finite answer (100% GP, +−100% markup) say so rather than blanking. + +Markup % is what this app calls **Margin %** elsewhere. + ### Quote builder A multi-line quoting tool — press `M`, or use **Quote** in the header / menu. @@ -505,12 +525,23 @@ CSV · Clear all. ### Undo / redo -Every state-changing action is undoable: adding, deleting, renaming or retyping -an incentive, changing rounding, resetting, editing the quote, and all history -operations. +Every state-changing action is undoable — **including typed values**. Correcting +an MRP, a discount, a quantity, a landed cost or an incentive rate is a step you +can walk back, as are the chips, toggles and dropdowns. + +One field edit is one step, not one per keystroke: the state is captured when +you enter the field and recorded when you leave it, so `⌘/Ctrl + Z` takes back +the whole number rather than the last digit. Entering a field and leaving it +untouched records nothing. + +Anything that does not change what the app saves — opening a dialog, switching a +Settings tab, searching history — stays out of the stack, so undo never burns a +step on a no-op. - **Undo / Redo** buttons in the header (Undo also in the mobile menu) -- `⌘/Ctrl + Z` and `⌘/Ctrl + ⇧ + Z` — these work even while typing in a field +- `⌘/Ctrl + Z` and `⌘/Ctrl + ⇧ + Z` — these work even while typing in a field, + and take the edit in progress with them +- The toast names what it reverted: *Undid: cost discount* - Destructive actions show a toast with an inline **Undo** - Up to **40 steps** retained @@ -562,6 +593,7 @@ and it disappears from the screen: | | | |---|---| | **Presets** | the header button, menu entry and the manager | +| **GP / markup converter** | the header button | | **Quote builder** | the header button, menu item and bottom-nav tab | | **What-if scenarios** | the button on the summary | | **Landed costs** | both fields in the MRP bar | @@ -743,7 +775,7 @@ Every number here is reproducible from the repo — none is hand-written. | Metric | Value | Reproduce with | |---|---|---| -| Tests | 1406 passing, 7 suites | `npm test` | +| Tests | 1479 passing, 7 suites | `npm test` | | Statement coverage | **82.7%** (app.js 86.3%, app-extra.js 72.3%) | `npm run coverage` | | Lighthouse Performance | **97** | `npm i -D lighthouse && npm run lighthouse` | | Lighthouse Accessibility | **100** | ” | @@ -780,7 +812,7 @@ commands after significant changes. ## Tests -1406 assertions across seven suites. They load the real `index.html`, +1479 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.** @@ -791,13 +823,13 @@ npm test | Suite | Assertions | Covers | |---|---|---| -| `features` | 979 | GST, incentives, quantity, landed costs, rounding, undo/redo, quote maths, history | +| `features` | 1041 | GST, incentives, quantity, landed costs, rounding, undo/redo of typed values and controls, 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 | | `modes` | 85 | solve modes, price input modes, what-if, comparison, Quick mode, wizard, share-link round trip, theming, auto-save | -| `a11y` | 103 | contrast ratios, structure, names, keyboard operability, focus trap, live regions, reduced motion, axe-core | -| `browser` | 78 | real Chromium over HTTP: asset loading, CSS cascade, `defer` timing, clicks, dialogs, mobile viewport, axe with layout | +| `a11y` | 104 | contrast ratios, structure, names, keyboard operability, focus trap, live regions, reduced motion, axe-core | +| `browser` | 88 | real Chromium over HTTP: asset loading, CSS cascade, `defer` timing, clicks, dialogs, control-bar spacing, mobile viewport, axe with layout | Individual suites: `npm run test:features`, `test:errors`, `test:mobile`, `test:fab`, `test:modes`, `test:a11y`, `test:browser`. Full assertion output: diff --git a/assets/app-extra.js b/assets/app-extra.js index 0f36159..031a980 100644 --- a/assets/app-extra.js +++ b/assets/app-extra.js @@ -272,7 +272,10 @@ function fcBuildCards(){ function fcMkField(symTxt,inputId,placeholder,extraStyle,sufId){ var isRupee=(symTxt!=='%'); var wrap=document.createElement('div');wrap.className='fc-input-wrap';if(extraStyle)wrap.style.cssText=extraStyle; - var sym=document.createElement('span');sym.className='fc-input-sym';sym.textContent=symTxt; + var sym=document.createElement('span'); + // A word rather than a currency glyph needs the smaller treatment, or it + // eats half the field on a phone. + sym.className='fc-input-sym'+(symTxt.length>2?' word':'');sym.textContent=symTxt; var inp=document.createElement('input');inp.className='fc-input';inp.inputMode='decimal';inp.autocomplete='off'; inp.id=inputId;inp.placeholder=placeholder; if(isRupee){ @@ -326,7 +329,7 @@ function fcBuildCPCard(){ // disc input var discWrap=document.createElement('div');discWrap.id='fc-cp-disc-wrap'; discWrap.style.display=FC_CM==='manual'?'none':''; - discWrap.appendChild(fcMkField('Disc','fc-cpd','e.g. 34',null,'fc-cpd-suf')); + discWrap.appendChild(fcMkField('Discount','fc-cpd','e.g. 34',null,'fc-cpd-suf')); card.appendChild(discWrap); // manual input @@ -383,7 +386,7 @@ function fcBuildSPCard(){ var discWrap=document.createElement('div');discWrap.id='fc-sp-disc-wrap'; discWrap.style.display=FC_SM==='manual'?'none':''; - discWrap.appendChild(fcMkField('Disc','fc-spd','e.g. 20',null,'fc-spd-suf')); + discWrap.appendChild(fcMkField('Discount','fc-spd','e.g. 20',null,'fc-spd-suf')); card.appendChild(discWrap); var manWrap=document.createElement('div');manWrap.id='fc-sp-manual-wrap';manWrap.style.cssText='display:'+(FC_SM==='manual'?'flex':'none')+';flex-direction:column;gap:8px'; @@ -942,7 +945,6 @@ function qtField(i,field,val,opts){ +(opts.step?' step="'+opts.step+'"':'') +(opts.style?' style="'+opts.style+'"':'') +(opts.label?' aria-label="'+opts.label+'"':'') - +' data-focus="undoQuote"' +' data-input="qtSet" data-p="'+i+'" data-q="'+field+'" autocomplete="off">'; } @@ -1496,7 +1498,7 @@ function _renderWhatIfImpl(cp){ } else { // disc % input — oninput stores + updateWiResults() only var fld=document.createElement('div');fld.className='field'; - var sym=document.createElement('span');sym.className='sym';sym.textContent='Disc %'; + var sym=document.createElement('span');sym.className='sym';sym.textContent='Discount %'; var inp=document.createElement('input');inp.type='number';inp.inputMode='decimal';inp.placeholder='e.g. 20'; inp.min='0';inp.max='100';inp.step='0.01';inp.value=sc.spDisc;inp.autocomplete='off'; inp.oninput=(function(idx){return function(){ diff --git a/assets/app.js b/assets/app.js index 606beff..62b4b0c 100644 --- a/assets/app.js +++ b/assets/app.js @@ -266,19 +266,73 @@ ACT.obAction = function(){ var s=OB_STEPS[OB_STEP]; if(s&&s.action==='example')o * @param {boolean} [capture] use capture — required for focus/blur, which do not bubble */ function delegate(evt, capture){ + var records = evt === 'click' || evt === 'change'; document.addEventListener(evt, function(e){ var node = e.target && e.target.closest ? e.target.closest('[data-' + evt + ']') : null; if(!node) return; var fn = ACT[node.getAttribute('data-' + evt)]; if(!fn){ logWarn('no handler registered for data-' + evt + '="' + node.getAttribute('data-' + evt) + '"'); return; } + // Snapshot around the handler so any state it changes becomes undoable + // without the handler having to know about undo. See autoUndo. Guarded + // separately from the handler: undo bookkeeping must never stop a click + // from working. + var before = null; + if(records) guard('undo snapshot', function(){ before = undoBefore(e.target) }); + // Read after the snapshot, not before: undoBefore may have committed a + // pending typed edit, and that bump must not be mistaken for this handler + // recording its own entry. + var seq = _undoSeq; guard('handler ' + node.getAttribute('data-' + evt), function(){ fn(node, e); }); + if(before) guard('undo record', function(){ + autoUndo(before, seq, (e.target && e.target.id) ? e.target : node); + }); }, !!capture); } +/** + * The 'before' snapshot for a click or change. If the target is the field + * currently being typed into, its focus-time snapshot is the true before — + * taking a fresh one would swallow the keystrokes. Any *other* pending edit is + * an earlier action, so it is committed first to keep the stack in order. + * @param {Element} target + * @returns {Object} + */ +function undoBefore(target){ + if(_fieldSnap){ + if(_fieldSnap.node===target){ var s=_fieldSnap; _fieldSnap=null; return s.state } + commitFieldUndo(); + } + /* A checkbox has already flipped by the time `change` fires, and clicking one + does not reliably focus it, so there may be no snapshot from focusin either. + Put it back for the length of a single capture. Radios are left alone: this + would not restore whichever sibling was checked before. */ + if(target && target.tagName === 'INPUT' && target.type === 'checkbox'){ + target.checked = !target.checked; + var st = captureState(); + target.checked = !target.checked; + return st; + } + return captureState(); +} ['click','change','input','keydown'].forEach(function(evt){ delegate(evt); }); // focus/blur do not bubble, so they are delegated in the capture phase. delegate('focus', true); delegate('blur', true); +/* Typed values are recorded from focus to blur rather than per action, so this + is bound directly rather than through ACT — every field is covered, including + the incentive rows that are built as HTML at runtime. focusin/focusout bubble; + focus/blur do not. */ +document.addEventListener('focusin', function(e){ + var t = e.target; + // Selects and checkboxes are in here too: their `change` event fires after the + // value has already moved, so the snapshot has to predate the focus. + if(t && (t.tagName === 'INPUT' || t.tagName === 'SELECT' || t.tagName === 'TEXTAREA')) + guard('undo snapshot', function(){ startFieldUndo(t) }); +}); +document.addEventListener('focusout', function(){ + guard('undo record', function(){ commitFieldUndo() }); +}); + /* ── Parameterised delegated actions ──────────────────────────────────────── Rows, cards and dialogs are built as HTML strings, so their handlers were @@ -304,8 +358,6 @@ ACT.histTagEdit = function(self){ startTagEdit(+self.getAttribute('data-p')); }; ACT.histTagSave = function(self){ commitTag(+self.getAttribute('data-p'), self.value); }; ACT.qtDelLine = function(self){ qtDelLine(+self.getAttribute('data-p')); }; ACT.qtSet = function(self){ qtSet(+self.getAttribute('data-p'), self.getAttribute('data-q'), self.value); }; -ACT.undoQuote = function(){ pushUndo('edit quote line'); }; -ACT.undoRename = function(){ pushUndo('rename incentive'); }; ACT.histMore = function(){ histShowMore(); }; ACT.obGoto = function(self){ OB_STEP=+self.getAttribute('data-p'); obRender(); }; ACT.fcNext = function(){ fcNext(); }; @@ -402,6 +454,17 @@ function parseMRP(){ * mid-entry (so typing "100." doesn't get rewritten to "100"). * @param {HTMLInputElement} inp */ +/** + * Re-apply thousands grouping to the MRP box after a programmatic write. + * A restored value went in as a plain number, so without this an undo left + * "1000" in a box that reads "1,000" the moment it is typed into. + */ +function fmtMrpField(){ + var inp=el('mrp'); + if(!inp)return; + var n=parseFloat(String(inp.value).replace(/,/g,'')); + if(!isNaN(n)&&String(inp.value).trim()!=='')inp.value=fmtINDIAN(n); +} function onMrpInput(inp){ var raw=inp.value.replace(/[^0-9.]/g,''); // Allow only one decimal point @@ -1139,7 +1202,7 @@ function closeModal(id){ * @param {string} id overlay suffix */ function overlayClick(e,id){if(e.target===el('overlay-'+id))closeModal(id)} -document.addEventListener('keydown',function(e){if(e.key==='Escape'){closeModal('settings');closeModal('whatif');closeModal('quote');closeModal('presets');closeConfirm();closePrompt();closeFab()}}); +document.addEventListener('keydown',function(e){if(e.key==='Escape'){closeModal('settings');closeModal('whatif');closeModal('quote');closeModal('presets');closeConfirm();closePrompt();closeConvert();closeFab()}}); /** * Handler for the custom GST box. Rejects anything outside 0–100 and says so, @@ -1174,7 +1237,7 @@ 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,landed:true,solver:true,inccp:true,incsp:true}; +var FEATURES={presets:true,convert: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 } @@ -1185,6 +1248,11 @@ var FEATURE_DEFS=[ values:function(){ var n=Object.keys(PRESETS).length; return n?[n+' saved preset'+(n===1?'':'s')]:[] }, clear:function(){ PRESETS={}; savePresets(); renderPresetList(); renderPresetManager(); }}, + {k:'convert',name:'GP / markup converter',hint:'Translate between the two ways of quoting a margin.', + els:['hbtn-convert'], + values:function(){ return [] }, + clear:function(){ closeConvert(); }}, + {k:'quote',name:'Quote builder',hint:'Multi-line quotes with blended GP.', els:['hbtn-quote','hmenu-quote','bnav-quote'], values:function(){ return QUOTE.length?[QUOTE.length+' quote line'+(QUOTE.length===1?'':'s')]:[] }, @@ -1305,6 +1373,100 @@ function factoryReset(){ } ACT.factoryReset = function(){ factoryReset() }; +/* ── GP % / markup % converter ────────────────────────────────────────────── + The same profit over two different denominators, which is why a supplier + offering "25%" and a customer expecting "25%" can mean different money. + GP = profit / selling price + markup = profit / cost price (what this app calls Margin %) + so markup = GP / (100 - GP) and GP = markup / (100 + markup). + ─────────────────────────────────────────────────────────────────────────── */ +/** + * @param {number} gp gross profit percentage + * @returns {number|null} markup %, or null where it has no finite answer + */ +function gpToMarkup(gp){ + if(isNaN(gp)||gp>=100)return null; // at 100% GP the cost is zero + return (gp/(100-gp))*100; +} +/** + * @param {number} mk markup percentage + * @returns {number|null} GP %, or null where it has no finite answer + */ +function markupToGp(mk){ + if(isNaN(mk)||mk<=-100)return null; // at -100% markup the sale is zero + return (mk/(100+mk))*100; +} +/** + * Recompute the other field and the worked line beneath. + * @param {'gp'|'mk'} from which field the user is typing in + */ +function renderConvert(from){ + var gpEl=el('cv-gp'), mkEl=el('cv-mk'), out=el('cv-out'); + if(!gpEl||!mkEl||!out)return; + var raw=(from==='gp'?gpEl:mkEl).value; + if(String(raw).trim()===''){ + (from==='gp'?mkEl:gpEl).value=''; + out.textContent='';out.className='cv-out'; + return; + } + var v=parseFloat(raw); + var other=(from==='gp')?gpToMarkup(v):markupToGp(v); + if(other===null){ + (from==='gp'?mkEl:gpEl).value=''; + out.textContent=(from==='gp') + ? 'A GP of 100% or more would mean the goods cost nothing — there is no markup that matches.' + : 'A markup of −100% or less would mean selling for nothing — there is no GP that matches.'; + out.className='cv-out bad'; + return; + } + (from==='gp'?mkEl:gpEl).value=String(+other.toFixed(4)); + // Ground it in money: percentages either way are easy to nod along to. + var gp=(from==='gp')?v:other; + var cost=100, sale=(gp>=100)?null:(cost/(1-gp/100)); + if(sale===null||!isFinite(sale)){ out.textContent='';out.className='cv-out'; return } + out.textContent='Buy at '+INR_RS(cost)+', sell at '+INR_RS(sale)+' — profit '+ + INR_RS(sale-cost)+', which is '+PCT(gp)+' of the sale and '+ + PCT((from==='gp')?other:v)+' of the cost.'; + out.className='cv-out'; +} +/** Open the converter, seeded from the calculation on screen when there is one. */ +function openConvert(){ + if(!featOn('convert'))return; + var o=el('overlay-convert'); + if(!o)return; + _lastFocused=document.activeElement; + o.classList.add('open'); + document.body.style.overflow='hidden'; + pushOverlay(o); + var use=el('cv-use'); + if(use)use.style.display=(LAST_CP&&LAST_SP)?'':'none'; + setTimeout(function(){ var f=el('cv-gp'); if(f){f.focus();if(f.select)f.select()} },30); +} +/** Close it. */ +function closeConvert(){ + var o=el('overlay-convert'); + if(o&&o.classList.contains('open')){ + o.classList.remove('open'); + popOverlay(o); + if(_lastFocused&&_lastFocused.focus)_lastFocused.focus(); + } +} +/** Pull the GP the calculator is currently showing into the converter. */ +function convertUseCurrent(){ + if(!LAST_CP||!LAST_SP)return; + var effSP=effectiveSP(LAST_SP), effCP=effectiveCP(LAST_CP); + if(!effSP||effSP<=0)return; + var gp=((effSP-effCP)/effSP)*100; + var f=el('cv-gp'); + if(f){ f.value=String(+gp.toFixed(4)); renderConvert('gp'); } +} +ACT.openConvert = function(){ openConvert() }; +ACT.convertClose = function(){ closeConvert() }; +ACT.convertOverlay = function(self,event){ if(event.target===el('overlay-convert'))closeConvert() }; +ACT.convertFromGp = function(){ renderConvert('gp') }; +ACT.convertFromMk = function(){ renderConvert('mk') }; +ACT.convertUseCurrent = function(){ convertUseCurrent() }; + /* ── 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 @@ -1743,6 +1905,10 @@ function runConfirm(){ Snapshots the whole mutable app state. Cheap enough at this size, and it means any new action gets undo for free by calling pushUndo() before it mutates. */ var UNDO=[],REDO=[],MAX_UNDO=40,_undoBusy=false; +/* Bumped whenever either stack moves. The automatic recorder (autoUndo) uses it + to tell "this action recorded its own undo entry" from "this action changed + state silently", and so avoids recording undo itself as an undoable action. */ +var _undoSeq=0; /** * Deep-copy every piece of mutable app state into a plain object. * This is what makes undo generic: a new feature becomes undoable simply by @@ -1777,6 +1943,9 @@ function captureState(){ function restoreState(s){ if(!s)return; _undoBusy=true; + // Whatever edit was in flight is about to be overwritten; its snapshot would + // describe a state that no longer exists. + _fieldSnap=null; try{ INC_KEYS=s.incKeys.slice(); SP_INC_KEYS=s.spIncKeys.slice(); @@ -1802,6 +1971,10 @@ function restoreState(s){ logError('undo/redo could not fully restore the previous state',e); } _undoBusy=false; + // The field the user is in now holds a restored value; re-arm from that so a + // further edit is measured against what is on screen. + var a=document.activeElement; + if(a&&(a.tagName==='INPUT'||a.tagName==='SELECT'||a.tagName==='TEXTAREA'))startFieldUndo(a); } /** * Record the current state so the next action can be undone. Clears the redo @@ -1810,9 +1983,23 @@ function restoreState(s){ */ function pushUndo(label){ if(_undoBusy)return; - UNDO.push({label:label,state:captureState()}); + // A half-typed value is an older change than this one; record it first so the + // stack stays in the order the user made them. + commitFieldUndo(); + pushUndoState(label,captureState()); +} +/** + * Push a snapshot that was taken earlier. pushUndo captures the state as it is + * now; a typed edit has to record the state from before the first keystroke, + * which only this form allows. + * @param {string} label + * @param {Object} state snapshot from captureState + */ +function pushUndoState(label,state){ + UNDO.push({label:label,state:state}); if(UNDO.length>MAX_UNDO)UNDO.shift(); REDO=[]; + _undoSeq++; updateUndoBtns(); } /** @@ -1829,9 +2016,13 @@ function updateUndoBtns(){ * Step back one action, moving the current state onto the redo stack. */ function undo(){ + // Ctrl+Z can be pressed without leaving the field, so the edit in progress has + // not been recorded yet. Record it first, then it is what undo steps back to. + commitFieldUndo(); if(UNDO.length===0){toast('Nothing to undo');return} var entry=UNDO.pop(); REDO.push({label:entry.label,state:captureState()}); + _undoSeq++; restoreState(entry.state); updateUndoBtns(); hideToast(); @@ -1842,15 +2033,124 @@ function undo(){ * Re-apply the most recently undone action. */ function redo(){ + commitFieldUndo(); if(REDO.length===0){toast('Nothing to redo');return} var entry=REDO.pop(); UNDO.push({label:entry.label,state:captureState()}); + _undoSeq++; restoreState(entry.state); updateUndoBtns(); haptic('light'); toast('Redid: '+entry.label); } +/* ── Automatic undo ── + Buttons used to be undoable only if their handler remembered to call + pushUndo, and typing was never undoable at all. Both are now recorded here + instead, from the one place every interaction already passes through: + delegate() snapshots the state, runs the handler, and compares. + + Comparing serialised snapshots rather than watching individual fields is what + makes this safe to apply to *every* control. Anything the app persists is in + the snapshot, so it is covered automatically; anything that is not — opening a + dialog, the history search box, switching a settings tab — produces an + identical snapshot and records nothing. */ + +/** A field's pre-edit snapshot, held between focus and blur. */ +var _fieldSnap=null; + +/** Human name for the undo toast. Curated where the aria-label is a sentence. */ +var UNDO_FIELD_NAMES={ + mrp:'MRP', cpd:'cost discount', cpv:'cost price', + spd:'sale discount', spv:'selling price', pri:'target profit', + qty:'quantity', landed:'inbound landed cost', 'sp-landed':'outbound landed cost', + 'floor-gp':'GP floor', 'floor-mg':'margin floor', 'gst-custom':'GST rate', + 'rnd-custom':'rounding step', 'fx-manual':'exchange rate', + 'ccy-select':'display currency', 'fx-scope':'currency scope' +}; +/** + * Name an element for the 'Undid: …' toast: the curated name, else the + * accessible name, else the visible text, trimmed to what a toast can hold. + * @param {Element} node + * @returns {string} + */ +function undoLabelFor(node){ + if(!node)return'change'; + if(UNDO_FIELD_NAMES[node.id])return UNDO_FIELD_NAMES[node.id]; + // Incentive rows are built at runtime, so their names live in INC_LABELS. + var m=/^s?(?:iv|it|lbl-(?:cp|sp))-(.+)$/.exec(node.id||''); + if(m&&INC_LABELS[m[1]])return INC_LABELS[m[1]]; + // aria-label first: it is what a symbol-only control (+, −, ×) actually means. + var t=node.getAttribute('aria-label')||node.getAttribute('title')||undoNodeText(node); + t=t.replace(/\s+/g,' ').trim(); + if(t.length>32)t=t.slice(0,32).replace(/\s\S*$/,'')+'…'; + return t||'change'; +} +/** + * Visible text of a control, with line breaks read as spaces — the two-line + * chips would otherwise come out as "NettDiscount %". + * @param {Element} node + * @returns {string} + */ +function undoNodeText(node){ + if(node.tagName==='INPUT'||!node.cloneNode)return''; + // A select's textContent is every option run together. + if(node.tagName==='SELECT'){ + var o=node.options&&node.options[node.selectedIndex]; + return o?(o.text||''):''; + } + var c=node.cloneNode(true),brs=c.querySelectorAll?c.querySelectorAll('br'):[]; + for(var i=0;i−':''; var labelHtml=editMode - ?'' + ?'' :''+lbl+''; var unitId=(k==='sc')?' id="'+(isCP?'sc':'ssc')+'-unit"':(custom?' id="unit-'+panel+'-'+k+'"':''); @@ -4584,6 +4884,10 @@ function pickEnum(v, allowed, fallback){ /** A numeric string safe to drop into an input's value. */ function numStr(v, max){ if(v === undefined || v === null) return undefined; + /* An empty box is a real state, not a missing field. Collapsing the two meant + a restore could put a value *into* a box but never take one back out, so + undoing the first entry into a blank field left the number sitting there. */ + if(String(v).trim() === '') return ''; var n = parseFloat(String(v).replace(/,/g, '')); if(isNaN(n) || !isFinite(n)) return undefined; if(max !== undefined && Math.abs(n) > max) return undefined; @@ -4613,11 +4917,11 @@ function validateShareState(raw){ if(raw.lc !== undefined){ var lc = numStr(raw.lc, 1e9); - if(lc !== undefined && parseFloat(lc) >= 0) s.lc = lc; + if(lc === '' || (lc !== undefined && parseFloat(lc) >= 0)) s.lc = lc; } if(raw.slc !== undefined){ var slc = numStr(raw.slc, 1e9); - if(slc !== undefined && parseFloat(slc) >= 0) s.slc = slc; + if(slc === '' || (slc !== undefined && parseFloat(slc) >= 0)) s.slc = slc; } var qty = parseInt(raw.qty, 10); @@ -4720,7 +5024,7 @@ function applyShareState(raw){ if(s.lc!==undefined&&el('landed'))el('landed').value=s.lc; if(s.slc!==undefined&&el('sp-landed'))el('sp-landed').value=s.slc; if(s.g)setGST(parseFloat(s.g)); - if(s.m)el('mrp').value=s.m; + if(s.m!==undefined){el('mrp').value=s.m;fmtMrpField()} if(s.cm)setCM(s.cm); if(s.cpms)setCPManual(s.cpms); if(s.cpd!==undefined)el('cpd').value=s.cpd; diff --git a/assets/styles.css b/assets/styles.css index 74beb23..596b421 100644 --- a/assets/styles.css +++ b/assets/styles.css @@ -97,11 +97,13 @@ body{font-family:var(--font-body);background:var(--bg);color:var(--text);min-hei .page{max-width:1100px;margin:0 auto;padding:clamp(1.25rem,3vw,2.5rem) clamp(1rem,3vw,2rem)} /* ── CONTROL BAR ── */ -.control-bar{display:flex;flex-wrap:wrap;gap:10px;align-items:center;margin-bottom:1.25rem;background:var(--surface);border:1px solid var(--border);border-radius:var(--radius);padding:12px 16px;box-shadow:var(--shadow)} -.ctrl-group{display:flex;align-items:center;gap:8px} +.control-bar{display:flex;flex-wrap:wrap;gap:14px;align-items:center;margin-bottom:1.25rem;background:var(--surface);border:1px solid var(--border);border-radius:var(--radius);padding:12px 16px;box-shadow:var(--shadow)} +.ctrl-group{display:flex;align-items:center;gap:11px} .ctrl-label{font-size:11px;font-weight:500;color:var(--text3);letter-spacing:.08em;text-transform:uppercase;white-space:nowrap} -.pill-group{display:flex;gap:3px} -.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} +/* 3px here left the pills all but touching, so the row read as one blurred + block rather than three separate choices. */ +.pill-group{display:flex;flex-wrap:wrap;gap:7px} +.pill{padding:6px 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;white-space:nowrap;min-height:28px} .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)} @@ -235,7 +237,9 @@ body{font-family:var(--font-body);background:var(--bg);color:var(--text);min-hei .inc-label-edit{font-size:12px;font-weight:500;font-family:var(--font-body);border:none;border-bottom:1px solid var(--accent);background:transparent;color:var(--text2);padding:0 0 1px;width:0;min-width:0;flex:1;outline:none} .inc-add-btn{width:100%;margin-top:6px;padding:8px;border:1.5px dashed var(--border-ctrl);border-radius:8px;background:transparent;color:var(--text2);font-size:12px;cursor:pointer;font-family:var(--font-body);display:none} .inc-add-btn:hover{border-color:var(--accent-ink);color:var(--accent-ink)} -.gst-custom-wrap{display:inline-flex;align-items:center;gap:1px;border:1.5px solid var(--border-ctrl);border-radius:20px;padding:1px 6px 1px 2px;background:var(--surface);transition:border-color .15s} +/* Sits in the same pill row, so it has to match .pill's box or the row looks + ragged. min-height keeps the two aligned as the pill padding changes. */ +.gst-custom-wrap{display:inline-flex;align-items:center;gap:1px;border:1.5px solid var(--border-ctrl);border-radius:20px;padding:1px 7px 1px 3px;min-height:28px;background:var(--surface);transition:border-color .15s} .gst-custom-wrap:focus-within{border-color:var(--accent)} .gst-custom-wrap input{border:none;background:transparent;width:38px;font-size:12px;font-family:var(--font-body);text-align:center;outline:none;color:var(--text);padding:2px;-moz-appearance:textfield} .gst-custom-wrap input::-webkit-outer-spin-button,.gst-custom-wrap input::-webkit-inner-spin-button{-webkit-appearance:none;margin:0} @@ -545,6 +549,12 @@ html[data-theme="dark"] .fc-dot.cur{background:var(--text)} .fc-input-wrap:focus-within{border-color:var(--accent)} .fc-input-sym{padding:0 14px;font-family:var(--font-heading);font-size:20px;font-weight:700;color:var(--text3);border-right:1px solid var(--border);height:56px;display:flex;align-items:center} .fc-input{border:none;outline:none;background:transparent;padding:0 16px;height:56px;font-size:26px;font-family:var(--font-mono);font-weight:500;color:var(--text);width:100%;min-width:0;user-select:text;-webkit-user-select:text} +/* The hint is not the data. At the input's own 26px a placeholder like + "e.g. 34" is wider than the box it has to fit on a phone. */ +.fc-input::placeholder{font-family:var(--font-body);font-size:17px;font-weight:400} +/* Set in fcMkField when the prefix is a word ("Discount") rather than a ₹ or + % glyph — at 20px heading weight it would crowd out the number. */ +.fc-input-sym.word{font-family:var(--font-body);font-size:13px;font-weight:500;padding:0 12px} .fc-input-suf{padding:0 12px;font-size:13px;font-weight:500;color:var(--text3);border-left:1px solid var(--border);height:56px;display:flex;align-items:center;white-space:nowrap;flex-shrink:0;font-family:var(--font-body)} .fc-mode-tabs{display:flex;gap:6px;flex-wrap:wrap} @@ -856,6 +866,20 @@ html[data-theme="dark"] .lbl-field:focus-within{box-shadow:0 0 0 3px rgba(240,23 /* The last section in a pane has nothing under it to separate from. */ .settings-pane .modal-section:last-child{border-bottom:none;margin-bottom:0;padding-bottom:0} +/* ── GP / markup converter ── */ +.cv-intro{font-size:12px;color:var(--text2);line-height:1.55;margin:0 0 16px} +.cv-pair{display:flex;align-items:flex-start;gap:12px} +.cv-field{flex:1;min-width:0;display:flex;flex-direction:column;gap:5px;cursor:text} +.cv-lbl{font-size:10px;letter-spacing:.09em;text-transform:uppercase;color:var(--text3);font-weight:600} +.cv-input{display:flex;align-items:center;border:1.5px solid var(--border-ctrl);border-radius:var(--radius-sm);background:var(--surface2);padding:0 10px} +.cv-input:focus-within{border-color:var(--text2)} +.cv-input input{flex:1;min-width:0;border:none;background:transparent;outline:none;padding:10px 0;font-family:var(--font-mono);font-size:17px;font-weight:600;color:var(--text);-moz-appearance:textfield} +.cv-input input::-webkit-outer-spin-button,.cv-input input::-webkit-inner-spin-button{-webkit-appearance:none;margin:0} +.cv-input::after{content:'%';font-size:12px;color:var(--text3);margin-left:4px} +.cv-hint{font-size:10.5px;color:var(--text3);line-height:1.4} +.cv-swap{align-self:center;margin-top:14px;font-size:16px;color:var(--text3);flex-shrink:0} +.cv-out{font-size:11.5px;line-height:1.55;color:var(--text2);min-height:34px;margin:14px 0 0} +.cv-out.bad{color:var(--amber)} .feat-intro{font-size:12px;color:var(--text2);line-height:1.55;margin:0 0 12px} .feat-grid{display:grid;grid-template-columns:1fr 1fr;gap:8px} .feat-chip{display:flex;flex-direction:column;gap:2px;text-align:left;padding:10px 12px;border-radius:var(--radius-sm);border:1px solid var(--border-ctrl);background:transparent;cursor:pointer;font-family:var(--font-body);transition:all .15s;min-height:44px} @@ -949,6 +973,16 @@ 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} + /* Three Calculate chips will not fit one line on a phone. Let them wrap and + keep the group label level with the first of them, rather than floating it + in the middle of a two-line block. The divider between groups only made + sense while they sat side by side. */ + .control-bar .ctrl-group{align-items:flex-start} + .control-bar .ctrl-label{padding-top:9px} + .control-bar .divider{display:none} + .cv-pair{flex-direction:column;gap:14px} + .cv-swap{align-self:flex-start;margin-top:0;transform:rotate(90deg)} + .cv-input input{min-height:44px} .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} diff --git a/docs/screenshot-mobile.png b/docs/screenshot-mobile.png index ad3391b..1255b74 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 6d35d19..8f0feae 100644 Binary files a/docs/screenshot.png and b/docs/screenshot.png differ diff --git a/index.html b/index.html index 9bce152..499ee5b 100644 --- a/index.html +++ b/index.html @@ -106,6 +106,10 @@

Price Calc

Presets +
- Disc + Discount % + 18% GST
- Disc + Discount % + 18% GST

Profit = Eff. SP excl GST − Eff. CP excl GST (after all incentives).

@@ -539,7 +543,7 @@

History

- Disc + Discount % + 18% GST
@@ -969,6 +973,42 @@
+ + +