@new-vintage-labs/commission-dashboard 0.1.0 → 0.1.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/README.md CHANGED
@@ -4,7 +4,7 @@ The New Vintage sales commission dashboard as one script. Claude loads it in an
4
4
 
5
5
  ```html
6
6
  <div id="app"></div>
7
- <script src="https://cdn.jsdelivr.net/npm/@new-vintage-labs/commission-dashboard@0.1.0/dist/commission-dashboard.js"></script>
7
+ <script src="https://cdn.jsdelivr.net/npm/@new-vintage-labs/commission-dashboard@0.1.1/dist/commission-dashboard.js"></script>
8
8
  <script>
9
9
  NVCommissionDashboard.mount("#app", { tenantId, wineryName, guideVersion, settings, plan, snapshot, customize, cards })
10
10
  </script>
@@ -22,7 +22,7 @@ The New Vintage sales commission dashboard as one script. Claude loads it in an
22
22
  ## Releasing
23
23
 
24
24
  1. Raise `version` in `package.json` and `src/version.ts`, and the pinned URL in the spec. The library test fails until all three match.
25
- 2. Merge, then push the tag `commission-dashboard-v<version>`. `.github/workflows/publish-commission-dashboard.yml` tests and publishes it through npm trusted publishing, so no npm token is stored anywhere.
25
+ 2. Merge, then push the tag `commission-dashboard-v<version>`. `.github/workflows/publish-commission-dashboard.yml` tests it and stages the release through npm trusted publishing, so no npm token is stored anywhere. A maintainer then approves it with 2FA, on the package's page on npmjs.com or with `npm stage approve <stage-id>` (`npm stage list` shows the id).
26
26
  3. Merge the spec change after the version is on npm, so the guide never points at a version that isn't there.
27
27
 
28
28
  A published version can't be changed. Existing pages keep the version they were built with until Claude updates them.
@@ -1,7 +1,7 @@
1
- var NVCommissionDashboard=(function(Q){"use strict";function S(e){const n=typeof e=="number"?e:Number(e);return Number.isFinite(n)?n:0}const ot=new Intl.NumberFormat("en-US",{style:"currency",currency:"USD",minimumFractionDigits:2,maximumFractionDigits:2}),rt=new Intl.NumberFormat("en-US",{style:"currency",currency:"USD",maximumFractionDigits:0}),xn=new Intl.NumberFormat("en-US",{maximumFractionDigits:1});function h(e){const n=S(e);return Number.isInteger(Math.round(n*100)/100)?rt.format(n):ot.format(n)}function H(e){return ot.format(S(e))}function se(e){const n=S(e),t=Math.abs(n);if(t<1e3)return rt.format(n);const[s,o]=t>=1e6?[1e6,"M"]:[1e3,"K"],a=Math.round(n/s*10)/10;return(n<0?"-$":"$")+String(Math.abs(a)).replace(/\.0$/,"")+o}function C(e){return xn.format(S(e))}function ke(e){return e instanceof Date?e.toISOString().slice(0,10):String(e!=null?e:"").slice(0,10)}function V(e){return ke(e).slice(0,7)}const _n=["Jan","Feb","Mar","Apr","May","Jun","Jul","Aug","Sep","Oct","Nov","Dec"],kn=["January","February","March","April","May","June","July","August","September","October","November","December"];function D(e,n=!1){var s;const t=Number(e.slice(5,7))-1;return(s=(n?kn:_n)[t])!=null?s:e}function Sn(e){return`${D(e,!0)} ${e.slice(0,4)}`}function pe(e){return`${D(e.slice(0,7))} ${Number(e.slice(8,10))}`}function O(e,n){if(!e)return"";const t=String(e);if(/^\d{4}-\d{2}-\d{2}$/.test(t))return pe(t);const s=new Date(t);return Number.isNaN(s.getTime())?t:new Intl.DateTimeFormat("en-US",{timeZone:n,month:"short",day:"numeric"}).format(s)}function oe(e,n){if(!e)return"";const t=e instanceof Date?e:new Date(String(e));return Number.isNaN(t.getTime())?String(e):new Intl.DateTimeFormat("en-US",{timeZone:n,month:"short",day:"numeric",hour:"numeric",minute:"2-digit"}).format(t)}function $n(e,n){return new Intl.DateTimeFormat("en-CA",{timeZone:n,year:"numeric",month:"2-digit",day:"2-digit"}).format(e)}function at(e,n){const t=S(n);return e==="percent"?`${C(t)}%`:e==="amount_per_unit"?`${h(t)}/unit`:e==="amount_per_line"?`${h(t)}/line`:""}const it=["America/Los_Angeles","America/Denver","America/Phoenix","America/Chicago","America/New_York","America/Anchorage","Pacific/Honolulu"],We=/^\d{4}-\d{2}-\d{2}$/,Cn=/^\d{4}-\d{2}$/;function Y(e){throw new Error("fillCommissionQuery: "+e)}function re(e){return e==null?"null::text":((typeof e!="string"||e.length>200)&&Y("bad text value"),"'"+e.replace(/'/g,"''")+"'::text")}function Se(e,n){return e==null?"null::text":((typeof e!="string"||n.indexOf(e)<0)&&Y("unexpected value "+String(e)),"'"+e+"'::text")}function $e(e,n){return e==null?"null::"+n:((typeof e!="number"||!isFinite(e))&&Y("bad number"),String(e)+"::"+n)}function lt(e){return e==null?"null::date":((typeof e!="string"||!We.test(e))&&Y("bad date "+String(e)),"'"+e+"'::date")}function ct(e){return(typeof e!="string"||!Cn.test(e))&&Y("bad month "+String(e)),"'"+e+"'::text"}function ae(e,n,t,s){const o=new RegExp("((?:with |\\n)"+n+" as \\([\\s\\S]*?\\bvalues\\b)([\\s\\S]*?)(\\)\\s*"+t+" \\()");if(!o.test(e))return e;s.length||Y(n+" needs at least one row");const a=`
2
- `+s.map(c=>" ("+c.join(", ")+")").join(`,
1
+ var NVCommissionDashboard=(function(ie){"use strict";function $(e){const n=typeof e=="number"?e:Number(e);return Number.isFinite(n)?n:0}const gt=new Intl.NumberFormat("en-US",{style:"currency",currency:"USD",minimumFractionDigits:2,maximumFractionDigits:2}),ht=new Intl.NumberFormat("en-US",{style:"currency",currency:"USD",maximumFractionDigits:0}),An=new Intl.NumberFormat("en-US",{maximumFractionDigits:1});function h(e){const n=$(e);return Number.isInteger(Math.round(n*100)/100)?ht.format(n):gt.format(n)}function Z(e){return gt.format($(e))}function le(e){const n=$(e),t=Math.abs(n);if(t<1e3)return ht.format(n);const[s,r]=t>=1e6?[1e6,"M"]:[1e3,"K"],a=Math.round(n/s*10)/10;return(n<0?"-$":"$")+String(Math.abs(a)).replace(/\.0$/,"")+r}function C(e){return An.format($(e))}function Ne(e){return e instanceof Date?e.toISOString().slice(0,10):String(e!=null?e:"").slice(0,10)}function q(e){return Ne(e).slice(0,7)}const Mn=["Jan","Feb","Mar","Apr","May","Jun","Jul","Aug","Sep","Oct","Nov","Dec"],En=["January","February","March","April","May","June","July","August","September","October","November","December"];function z(e,n=!1){var s;const t=Number(e.slice(5,7))-1;return(s=(n?En:Mn)[t])!=null?s:e}function bt(e){return`${z(e,!0)} ${e.slice(0,4)}`}function J(e){return`${z(e.slice(0,7))} ${Number(e.slice(8,10))}`}function F(e,n){if(!e)return"";const t=String(e);if(/^\d{4}-\d{2}-\d{2}$/.test(t))return J(t);const s=new Date(t);return Number.isNaN(s.getTime())?t:new Intl.DateTimeFormat("en-US",{timeZone:n,month:"short",day:"numeric"}).format(s)}function Q(e,n){if(!e)return"";const t=e instanceof Date?e:new Date(String(e));return Number.isNaN(t.getTime())?String(e):new Intl.DateTimeFormat("en-US",{timeZone:n,month:"short",day:"numeric",hour:"numeric",minute:"2-digit"}).format(t)}function Gn(e,n){return new Intl.DateTimeFormat("en-CA",{timeZone:n,year:"numeric",month:"2-digit",day:"2-digit"}).format(e)}function yt(e,n){const t=$(n);return e==="percent"?`${C(t)}%`:e==="amount_per_unit"?`${h(t)}/unit`:e==="amount_per_line"?`${h(t)}/line`:""}const vt=["America/Los_Angeles","America/Denver","America/Phoenix","America/Chicago","America/New_York","America/Anchorage","Pacific/Honolulu"],Xe=/^\d{4}-\d{2}-\d{2}$/,Ln=/^\d{4}-\d{2}$/;function X(e){throw new Error("fillCommissionQuery: "+e)}function pe(e){return e==null?"null::text":((typeof e!="string"||e.length>200)&&X("bad text value"),"'"+e.replace(/'/g,"''")+"'::text")}function Ae(e,n){return e==null?"null::text":((typeof e!="string"||n.indexOf(e)<0)&&X("unexpected value "+String(e)),"'"+e+"'::text")}function Me(e,n){return e==null?"null::"+n:((typeof e!="number"||!isFinite(e))&&X("bad number"),String(e)+"::"+n)}function wt(e){return e==null?"null::date":((typeof e!="string"||!Xe.test(e))&&X("bad date "+String(e)),"'"+e+"'::date")}function xt(e){return(typeof e!="string"||!Ln.test(e))&&X("bad month "+String(e)),"'"+e+"'::text"}function fe(e,n,t,s){const r=new RegExp("((?:with |\\n)"+n+" as \\([\\s\\S]*?\\bvalues\\b)([\\s\\S]*?)(\\)\\s*"+t+" \\()");if(!r.test(e))return e;s.length||X(n+" needs at least one row");const a=`
2
+ `+s.map(u=>" ("+u.join(", ")+")").join(`,
3
3
  `)+`
4
- `;return e.replace(o,(c,i,l,m)=>i+a+m)}function dt(e,n){const t=n||{};it.indexOf(t.timeZone)<0&&Y("unsupported time zone"),(!We.test(t.windowStart||"")||!We.test(t.windowEnd||""))&&Y("window dates must be YYYY-MM-DD");let s=String(e);return s=s.replace(/>= timestamptz '[^']*'/g,">= timestamptz '"+t.windowStart+" 00:00:00 "+t.timeZone+"'"),s=s.replace(/< timestamptz '[^']*'/g,"< timestamptz '"+t.windowEnd+" 00:00:00 "+t.timeZone+"'"),s=s.replace(/at time zone '[^']*'/g,"at time zone '"+t.timeZone+"'"),s=ae(s,"rules","rule_rows",(t.rules||[]).map((o,a)=>[$e(a+1,"integer"),re(o.associateAccountId),re(o.associateName),Se(o.productKind,["wine","sku","product_id","title","item_type"]),re(o.productValue),Se(o.rateKind,["percent","amount_per_unit","amount_per_line"]),$e(o.rate,"numeric")])),s=ae(s,"statuses","status_rows",(t.statuses||[]).map(o=>[Se(o.kind,["fulfillment_earns","payment_earns","fulfillment_never","payment_never"]),re(o.value)])),t.payPeriod&&(s=ae(s,"pay_period","pay_period_rows",[[Se(t.payPeriod.kind,["weekly","biweekly","semimonthly","monthly","days"]),lt(t.payPeriod.anchorDate),$e(t.payPeriod.days===void 0?null:t.payPeriod.days,"integer")]])),t.returnWindowDays!==void 0&&(s=ae(s,"return_window","return_window_rows",[[$e(t.returnWindowDays,"integer")]])),t.reportMonths&&(s=ae(s,"report_months","report_rows",[[ct(t.reportMonths.first),ct(t.reportMonths.last)]])),t.focus&&(s=ae(s,"focus","focus_rows",[[re(t.focus.associateAccountId),re(t.focus.associateName),lt(t.focus.periodStart)]])),s}const Be=864e5;function ge(e){return Date.UTC(Number(e.slice(0,4)),Number(e.slice(5,7))-1,Number(e.slice(8,10)))}function Tn(e){return new Date(e).toISOString().slice(0,10)}function ie(e,n){return Tn(ge(e)+n*Be)}function q(e,n){const t=Number(e.slice(0,4))*12+Number(e.slice(5,7))-1+n;return`${Math.floor(t/12)}-${String(t%12+1).padStart(2,"0")}`}function X(e){return`${e}-01`}function Nn(e){return(ge(X(q(e,1)))-ge(X(e)))/Be}function An(e){return e.kind==="weekly"?7:e.kind==="biweekly"?14:e.kind==="days"&&e.days&&e.days>0?e.days:null}function Ce(e,n){const t=e.slice(0,7);if(n.kind==="semimonthly")return Number(e.slice(8,10))<16?{start:X(t),end:`${t}-16`}:{start:`${t}-16`,end:X(q(t,1))};const s=An(n);if(s&&n.anchorDate){const o=Math.floor((ge(e)-ge(n.anchorDate))/Be/s),a=ie(n.anchorDate,o*s);return{start:a,end:ie(a,s)}}return{start:X(t),end:X(q(t,1))}}function Mn(e,n){return Ce(ie(e.start,-1),n)}function En(e,n){return Ce(e.end,n)}function ee(e){return ie(e.end,-1)}function Te(e){return ee(e).slice(0,7)}function le(e){return e.start.endsWith("-01")&&e.end===X(q(e.start.slice(0,7),1))}function F(e){if(le(e))return Sn(e.start.slice(0,7));const n=ee(e);return n.slice(0,7)===e.start.slice(0,7)?`${pe(e.start)}–${Number(n.slice(8,10))}`:`${pe(e.start)}–${pe(n)}`}function Gn(e){return le(e)?F(e).split(" ")[0].slice(0,3):F(e)}function Ln(e){return{windowStart:`${ee(e).slice(0,4)}-01-01`,windowEnd:e.end}}const zn="sales-commission-dashboard",ce={summary:"sales-associate-commission-summary",lines:"sales-associate-commission-lines",performance:"sales-associate-monthly-performance",sources:"team-sales-sources-monthly"};class U extends Error{constructor(n){super(n.kind==="tool"?n.message:n.kind),this.failure=n}}async function Dn(e){const n=globalThis.claude;if(!n||typeof n.use!="function")return null;try{const t=await Promise.race([n.use("mcp"),new Promise(s=>setTimeout(()=>s(null),1e4))]);return!t||typeof t.callTool!="function"?null:(s,o)=>t.callTool(e,s,o)}catch{return null}}function On(e){const n=e.content;if(!Array.isArray(n))return;const t=n.find(s=>s&&typeof s=="object"&&s.type==="text");if(typeof(t==null?void 0:t.text)=="string")try{return JSON.parse(t.text)}catch{return t.text}}function ut(e){var s,o,a;if(!e||typeof e!="object")throw new U({kind:"tool",message:"The connector returned nothing."});const n=e,t=(a=(o=(s=n.payload)!=null?s:n.structuredContent)!=null?o:On(n))!=null?a:n;if(n.isError===!0||t&&typeof t=="object"&&t.ok===!1){const c=t.error,i=typeof(c==null?void 0:c.message)=="string"?c.message:typeof t=="string"?t:"The New Vintage tool returned an error.";throw new U({kind:"tool",message:i})}if(!t||typeof t!="object")throw new U({kind:"tool",message:String(t)});return t}function Ne(e){var s,o,a;if(e instanceof U)return e.failure;const n=String((s=e==null?void 0:e.code)!=null?s:""),t=String((a=(o=e==null?void 0:e.message)!=null?o:e)!=null?a:"");return/not_granted|consent|permission|denied/i.test(n)?{kind:"approval"}:/server_not_connected|unauthori[sz]ed|auth|reconnect/i.test(n+" "+t)?{kind:"reconnect"}:(e==null?void 0:e.retryable)===!0||/timeout|unavailable|rate_limited|network|5\d\d/i.test(n+" "+t)?{kind:"temporary"}:/cannot access|not in this session|tenant/i.test(t)?{kind:"unavailable"}:{kind:"tool",message:t||"The New Vintage tool returned an error."}}function Rn(e,n){return{call:async(t,s)=>{const o=t==="get_analysis_guide"?s:{tenantId:n,...s};try{return ut(await e(t,o))}catch(a){if(Ne(a).kind!=="temporary")throw a;return await new Promise(c=>setTimeout(c,2e3)),ut(await e(t,o))}}}}async function In(e,n){var a,c;const t=await e.call("get_analysis_guide",{context:"Refreshing the sales commission dashboard with the latest commission queries.",slug:zn,includeReferenceQueries:!0,...n?{pageSetup:n}:{}}),s=(a=t.item)!=null?a:t,o={};for(const i of(c=s.referenceQueries)!=null?c:[])typeof i.slug=="string"&&typeof i.sqlText=="string"&&(o[i.slug]=i.sqlText);for(const i of Object.values(ce))if(!o[i])throw new U({kind:"tool",message:`The guide is missing the ${i} query.`});return{version:S(s.version),queries:o}}async function de(e,n,t){const s=await e.call("safe_tenant_sql",{context:t,sqlText:n});return{rows:Array.isArray(s.rows)?s.rows:[],complete:s.resultMode!=="sampled_preview"}}function he(e,n,t){try{return dt(e.queries[n],t)}catch{throw new U({kind:"needs_update"})}}function mt(e,n){const t=[];for(let s=e;s<=n;s=q(s,3)){const o=q(s,2);t.push({first:s,last:o<n?o:n})}return t}async function Pn(e,n,t){const s="Loading each associate's commission by pay period and month for the dashboard.",o=await de(e,he(n,ce.summary,t),s);if(o.complete)return o.rows;const a=[];for(const i of mt(t.reportMonths.first,t.reportMonths.last)){const l=await de(e,he(n,ce.summary,{...t,reportMonths:i}),s);if(!l.complete)throw new U({kind:"tool",message:"The commission summary is too large to load in one quarter."});a.push(...l.rows)}const c=new Set;return a.filter(i=>{const l=[i.grain,i.associate_account_id,i.associate_name,i.period_start].join("|");return c.has(l)?!1:(c.add(l),!0)})}async function ft(e,n,t,s){const o="Loading monthly sales performance for the commission dashboard.",a=await de(e,he(n,t,s),o);if(a.complete)return a.rows;const c=[],i=s.windowStart.slice(0,7),l=ie(s.windowEnd,-1).slice(0,7);for(const m of mt(i,l)){const d=`${q(m.last,1)}-01`,u=await de(e,he(n,t,{...s,windowStart:`${m.first}-01`,windowEnd:d<s.windowEnd?d:s.windowEnd}),o);if(!u.complete)throw new U({kind:"tool",message:"Monthly performance is too large to load in one quarter."});c.push(...u.rows)}return c}async function Vn(e,n,t){const s=await de(e,he(n,ce.lines,t),"Loading one associate's commission lines for the pay period on screen.");if(!s.complete)throw new U({kind:"tool",message:"This associate's lines are too many to load at once."});return s.rows}function qn(e,n){var s;const t=new Map;for(const o of e){const a=V(o.month);t.set(a,((s=t.get(a))!=null?s:0)+S(o.credited_sales))}return n.every(o=>{var a;return Math.abs(((a=t.get(V(o.month)))!=null?a:0)-S(o.associate_credited_sales))<=5})}function Ae(e){var t;const n=e.associate_account_id;return typeof n=="string"&&n?n:String((t=e.associate_name)!=null?t:"")}function Fn(e){var n,t;return String((t=(n=e.associate_name)!=null?n:e.associate_account_id)!=null?t:"Unnamed")}const pt=["eligible_sales","eligible_commission","eligible_lines","pending_sales","pending_commission","pending_lines","excluded_sales","excluded_commission","unpriced_lines","refunds","refund_lines","refunds_after_window","refunded_off_lines"],Un=Object.fromEntries(pt.map(e=>[e,0]));function gt(e){return e?Object.fromEntries(pt.map(n=>[n,S(e[n])])):{...Un}}function j(e,n,t){return gt(e.summary.find(s=>s.grain==="pay_period"&&ke(s.period_start)===t.start&&Ae(s)===n))}function te(e,n,t){return gt(e.summary.find(s=>s.grain==="month"&&V(s.period_start)===t&&Ae(s)===n))}function ht(e,n){return e.summary.some(t=>t.grain==="pay_period"&&ke(t.period_start)===n.start)}const jn=["credited_sales","orders","bottles","club_signups","club_cancellations"];function bt(e,n){for(const t of jn)e[t]+=S(n[t]);return e}const yt=()=>({credited_sales:0,orders:0,bottles:0,club_signups:0,club_cancellations:0});function be(e,n,t){return e.performance.filter(s=>V(s.month)===t&&Ae(s)===n).reduce(bt,yt())}function ye(e,n){return e.performance.filter(t=>V(t.month)===n).reduce(bt,yt())}function Wn(e,n){return e.performance.some(t=>V(t.month)===n)||e.sources.some(t=>V(t.month)===n)}function vt(e,n){return e.sources.find(t=>V(t.month)===n)}function Me(e,n,t){const s=new Map,o=a=>{const c=Ae(a);if(!c||s.has(c))return;const i=a.associate_account_id;s.set(c,{key:c,name:Fn(a),accountId:typeof i=="string"&&i?i:null})};return e.summary.filter(a=>a.grain==="pay_period"&&ke(a.period_start)===n.start).forEach(o),e.performance.filter(a=>V(a.month)===t).forEach(o),[...s.values()].sort((a,c)=>j(e,c.key,n).eligible_commission-j(e,a.key,n).eligible_commission||a.name.localeCompare(c.name))}function Ke(e,n=12){return Array.from({length:n},(t,s)=>q(e,s-n+1))}function Ee(e,n){return n.filter(t=>Wn(e,t))}function wt(e,n){const t=s=>s.associateAccountId===null&&s.associateName===null||s.associateAccountId!==null&&s.associateAccountId===n.accountId||s.associateName!==null&&s.associateName===n.name;return e.filter(s=>t(s)&&s.rate>0)}function Bn(e){return e.productKind==="wine"?"wine":e.productKind&&e.productValue?e.productValue:"everything else"}function Kn(e){if(!e.length||e.some(t=>t.rateKind!=="percent"))return null;const n=e[0].rate;return e.every(t=>t.rate===n)?n:null}function xt(e){const n={eligible:0,pending:0,excluded:0};for(const t of e)t.bucket==="eligible"&&(n.eligible+=S(t.net_dollars)),t.bucket==="pending"&&(n.pending+=S(t.net_dollars)),(t.bucket==="excluded"||t.bucket==="unpriced")&&(n.excluded+=S(t.net_dollars));return{eligible:e.filter(t=>t.bucket==="eligible").sort((t,s)=>S(s.net_dollars)-S(t.net_dollars)),unpriced:e.filter(t=>t.bucket==="unpriced"),refundsListed:e.filter(t=>t.bucket==="refund"&&t.refund_listed===!0),refundsNotListed:e.filter(t=>t.bucket==="refund"&&t.refund_counts===!0&&t.refund_listed!==!0),totals:n}}function Hn(e,n="order_id"){const t=e.tenant_id,s=e[n];return typeof t!="string"||!t||typeof s!="string"&&typeof s!="number"?null:`https://${encodeURIComponent(t)}.pos.platform.commerce7.com/store/order/${encodeURIComponent(String(s))}/summary`}const Yn="commission-dashboard";function Zn(){const e=globalThis.storage;return e&&typeof e.get=="function"&&typeof e.set=="function"?e:null}function Jn(){try{const e=globalThis.localStorage,n="__nv_probe__";return e.setItem(n,"1"),e.removeItem(n),e}catch{return null}}function Qn(e){return typeof e=="string"?e:e&&typeof e=="object"&&typeof e.value=="string"?e.value:null}function Xn(e){if(e)return{adapter:e,mode:"shared"};const n=Zn();if(n)return{mode:"shared",adapter:{get:async(s,o)=>{try{return Qn(await n.get(s,o))}catch{return null}},set:async(s,o,a)=>{await n.set(s,o,a)}}};const t=Jn();return t?{mode:"browser",adapter:{get:async(s,o)=>t.getItem(o?s:`personal:${s}`),set:async(s,o,a)=>t.setItem(a?s:`personal:${s}`,o)}}:{adapter:null,mode:"none"}}function _t(e){var n,t,s,o;return{teamGoal:(n=e.teamGoal)!=null?n:null,teamCommissionGoal:(t=e.teamCommissionGoal)!=null?t:null,associateGoals:{...(s=e.associateGoals)!=null?s:{}},associateCommissionGoals:{...(o=e.associateCommissionGoals)!=null?o:{}}}}function ue(e){return{schemaVersion:1,planRevision:e.planRevision,goalChanges:[],..._t(e)}}function kt(e){return`${Yn}:${e}`}async function es(e,n,t){var s,o,a,c;if(!e)return ue(t);try{const i=await e.get(kt(n),!0);if(!i)return ue(t);const l=JSON.parse(i);return l.schemaVersion!==1||typeof l.planRevision!="number"||l.planRevision<t.planRevision?ue(t):{schemaVersion:1,planRevision:l.planRevision,teamGoal:(s=l.teamGoal)!=null?s:null,teamCommissionGoal:(o=l.teamCommissionGoal)!=null?o:null,associateGoals:{...(a=l.associateGoals)!=null?a:{}},associateCommissionGoals:{...(c=l.associateCommissionGoals)!=null?c:{}},goalChanges:Array.isArray(l.goalChanges)?l.goalChanges:[]}}catch{return ue(t)}}async function ts(e,n,t){if(!e)return!1;try{return await e.set(kt(n),JSON.stringify(t),!0),!0}catch{return!1}}async function ns(e,n){if(!e)return null;try{return await e.get(n,!1)}catch{return null}}async function ss(e,n,t){if(e)try{await e.set(n,t,!1)}catch{}}function os(e,n,t){if(St(e,t)===St(n,t))return null;for(let o=e.goalChanges.length-1;o>=0;o-=1)if(e.goalChanges[o].goal===t)return e.goalChanges[o];return null}function St(e,n){if(n==="team-sales")return e.teamGoal;if(n==="team-commission")return e.teamCommissionGoal;const[t,...s]=n.split(":"),o=s.join(":"),a=t==="sales"?e.associateGoals[o]:e.associateCommissionGoals[o];return a===void 0?null:a}function rs(e,n,t,s,o){const a={...e,associateGoals:{...e.associateGoals},associateCommissionGoals:{...e.associateCommissionGoals},goalChanges:[...e.goalChanges,{goal:n,value:t,at:o,by:s}]};if(n==="team-sales")a.teamGoal=t;else if(n==="team-commission")a.teamCommissionGoal=t;else{const[c,...i]=n.split(":"),l=i.join(":"),m=c==="sales"?a.associateGoals:a.associateCommissionGoals;t===null?delete m[l]:m[l]=t}return a}const $t="0.1.0",Ge=(e,n)=>String(e!=null?e:"").replace(/\s+/g," ").trim().slice(0,n);function Ct(e={},n=[]){var t,s,o,a,c,i;return{packageVersion:$t,hiddenSections:((t=e.hide)!=null?t:[]).slice(0,20).map(l=>Ge(l,40)),reorderedViews:["team","associate"].filter(l=>{var m,d,u;return((u=(d=(m=e.order)==null?void 0:m[l])==null?void 0:d.length)!=null?u:0)>0}),renamedSections:Object.keys((s=e.labels)!=null?s:{}).slice(0,20).map(l=>Ge(l,40)),themeChanged:Object.keys((o=e.theme)!=null?o:{}).length+Object.keys((a=e.themeDark)!=null?a:{}).length>0,fontsChanged:!!((c=e.fonts)!=null&&c.display||(i=e.fonts)!=null&&i.body),titleChanged:!!e.title,customCards:n.slice(0,10).map(l=>({title:Ge(l.title,80),purpose:Ge(l.purpose,160),view:l.view}))}}const as={"surface-base":"#f7f5f1","surface-subtle":"#f2efea","surface-panel":"#ece8e1","surface-raised":"#ffffff","text-primary":"#1a1917","text-secondary":"#4f4a43","text-tertiary":"#6b655d","border-subtle":"#ebe7df","border-default":"#ddd8ce","border-strong":"#8d877f","action-primary-bg":"#0b6623","action-primary-fg":"#ffffff","action-primary-hover":"#155826","focus-ring-color":"#1a6b30","status-success":"#127a45","status-success-bg":"#edf8f1","status-warning":"#9c6110","status-warning-bg":"#fff7e7","status-error":"#b73847","status-error-bg":"#fdf0f2","font-display":"'Newsreader', Georgia, serif","font-body":"'Be Vietnam Pro', system-ui, sans-serif"},is={"surface-base":"#171614","surface-subtle":"#1f1d1b","surface-panel":"#262320","surface-raised":"#34302d","text-primary":"#f5f3ef","text-secondary":"#d0c8bd","text-tertiary":"#b4aba0","border-subtle":"#3b3632","border-default":"#4c4742","border-strong":"#8a8279","action-primary-bg":"#57bd76","action-primary-fg":"#06210d","action-primary-hover":"#7ecb93","focus-ring-color":"#8cd0a0","status-success":"#47d78b","status-success-bg":"rgba(71,215,139,.16)","status-warning":"#f0c36a","status-warning-bg":"rgba(240,195,106,.16)","status-error":"#f28c95","status-error-bg":"rgba(242,140,149,.12)"},ls=/^[a-z][a-z0-9-]{0,40}$/,cs=/^[^;{}<>\\]{1,120}$/;function Tt(e){return Object.entries(e).filter(([n,t])=>ls.test(n)&&cs.test(t)).map(([n,t])=>`--${n}:${t};`).join("")}function ds(e){return`https://fonts.googleapis.com/css2?${e.map(t=>`family=${encodeURIComponent(t).replace(/%20/g,"+")}:wght@300;400;500;600`).join("&")}&display=swap`}function us(e={},n={}){const t=Tt({...as,...e}),s=Tt({...is,...n});return`.nvcd{${t}}@media (prefers-color-scheme: dark){.nvcd{${s}}}`}const ms=`
4
+ `;return e.replace(r,(u,i,l,m)=>i+a+m)}function kt(e,n){const t=n||{};vt.indexOf(t.timeZone)<0&&X("unsupported time zone"),(!Xe.test(t.windowStart||"")||!Xe.test(t.windowEnd||""))&&X("window dates must be YYYY-MM-DD");let s=String(e);return s=s.replace(/>= timestamptz '[^']*'/g,">= timestamptz '"+t.windowStart+" 00:00:00 "+t.timeZone+"'"),s=s.replace(/< timestamptz '[^']*'/g,"< timestamptz '"+t.windowEnd+" 00:00:00 "+t.timeZone+"'"),s=s.replace(/at time zone '[^']*'/g,"at time zone '"+t.timeZone+"'"),s=fe(s,"rules","rule_rows",(t.rules||[]).map((r,a)=>[Me(a+1,"integer"),pe(r.associateAccountId),pe(r.associateName),Ae(r.productKind,["wine","sku","product_id","title","item_type"]),pe(r.productValue),Ae(r.rateKind,["percent","amount_per_unit","amount_per_line"]),Me(r.rate,"numeric")])),s=fe(s,"statuses","status_rows",(t.statuses||[]).map(r=>[Ae(r.kind,["fulfillment_earns","payment_earns","fulfillment_never","payment_never"]),pe(r.value)])),t.payPeriod&&(s=fe(s,"pay_period","pay_period_rows",[[Ae(t.payPeriod.kind,["weekly","biweekly","semimonthly","monthly","days"]),wt(t.payPeriod.anchorDate),Me(t.payPeriod.days===void 0?null:t.payPeriod.days,"integer")]])),t.returnWindowDays!==void 0&&(s=fe(s,"return_window","return_window_rows",[[Me(t.returnWindowDays,"integer")]])),t.reportMonths&&(s=fe(s,"report_months","report_rows",[[xt(t.reportMonths.first),xt(t.reportMonths.last)]])),t.focus&&(s=fe(s,"focus","focus_rows",[[pe(t.focus.associateAccountId),pe(t.focus.associateName),wt(t.focus.periodStart)]])),s}const et=864e5;function xe(e){return Date.UTC(Number(e.slice(0,4)),Number(e.slice(5,7))-1,Number(e.slice(8,10)))}function zn(e){return new Date(e).toISOString().slice(0,10)}function ce(e,n){return zn(xe(e)+n*et)}function U(e,n){const t=Number(e.slice(0,4))*12+Number(e.slice(5,7))-1+n;return`${Math.floor(t/12)}-${String(t%12+1).padStart(2,"0")}`}function de(e){return`${e}-01`}function Dn(e){return(xe(de(U(e,1)))-xe(de(e)))/et}function On(e){return e.kind==="weekly"?7:e.kind==="biweekly"?14:e.kind==="days"&&e.days&&e.days>0?e.days:null}function Ee(e,n){const t=e.slice(0,7);if(n.kind==="semimonthly")return Number(e.slice(8,10))<16?{start:de(t),end:`${t}-16`}:{start:`${t}-16`,end:de(U(t,1))};const s=On(n);if(s&&n.anchorDate){const r=Math.floor((xe(e)-xe(n.anchorDate))/et/s),a=ce(n.anchorDate,r*s);return{start:a,end:ce(a,s)}}return{start:de(t),end:de(U(t,1))}}function Rn(e,n){return Ee(ce(e.start,-1),n)}function In(e,n){return Ee(e.end,n)}function ee(e){return ce(e.end,-1)}function Ge(e){return ee(e).slice(0,7)}function ge(e){return e.start.endsWith("-01")&&e.end===de(U(e.start.slice(0,7),1))}function j(e){if(ge(e))return bt(e.start.slice(0,7));const n=ee(e);return n.slice(0,7)===e.start.slice(0,7)?`${J(e.start)}–${Number(n.slice(8,10))}`:`${J(e.start)}–${J(n)}`}function tt(e,n=!1){if(ge(e)){const s=e.start.slice(0,7);return n?`${z(s)} ${s.slice(0,4)}`:bt(s)}const t=ee(e);return t.slice(0,4)!==e.start.slice(0,4)?`${J(e.start)}, ${e.start.slice(0,4)}–${J(t)}, ${t.slice(0,4)}`:`${j(e)}, ${t.slice(0,4)}`}function Pn(e){return{windowStart:`${ee(e).slice(0,4)}-01-01`,windowEnd:e.end}}const Vn="sales-commission-dashboard",he={summary:"sales-associate-commission-summary",lines:"sales-associate-commission-lines",performance:"sales-associate-monthly-performance",sources:"team-sales-sources-monthly"};class W extends Error{constructor(n){super(n.kind==="tool"?n.message:n.kind),this.failure=n}}async function qn(e){const n=globalThis.claude;if(!n||typeof n.use!="function")return null;try{const t=await Promise.race([n.use("mcp"),new Promise(s=>setTimeout(()=>s(null),1e4))]);return!t||typeof t.callTool!="function"?null:(s,r)=>t.callTool(e,s,r)}catch{return null}}function Fn(e){const n=e.content;if(!Array.isArray(n))return;const t=n.find(s=>s&&typeof s=="object"&&s.type==="text");if(typeof(t==null?void 0:t.text)=="string")try{return JSON.parse(t.text)}catch{return t.text}}function _t(e){var s,r,a;if(!e||typeof e!="object")throw new W({kind:"tool",message:"The connector returned nothing."});const n=e,t=(a=(r=(s=n.payload)!=null?s:n.structuredContent)!=null?r:Fn(n))!=null?a:n;if(n.isError===!0||t&&typeof t=="object"&&t.ok===!1){const u=t.error,i=typeof(u==null?void 0:u.message)=="string"?u.message:typeof t=="string"?t:"The New Vintage tool returned an error.";throw new W({kind:"tool",message:i})}if(!t||typeof t!="object")throw new W({kind:"tool",message:String(t)});return t}function Le(e){var s,r,a;if(e instanceof W)return e.failure;const n=String((s=e==null?void 0:e.code)!=null?s:""),t=String((a=(r=e==null?void 0:e.message)!=null?r:e)!=null?a:"");return/not_granted|consent|permission|denied/i.test(n)?{kind:"approval"}:/server_not_connected|unauthori[sz]ed|auth|reconnect/i.test(n+" "+t)?{kind:"reconnect"}:(e==null?void 0:e.retryable)===!0||/timeout|unavailable|rate_limited|network|5\d\d/i.test(n+" "+t)?{kind:"temporary"}:/cannot access|not in this session|tenant/i.test(t)?{kind:"unavailable"}:{kind:"tool",message:t||"The New Vintage tool returned an error."}}function Un(e,n){return{call:async(t,s)=>{const r=t==="get_analysis_guide"?s:{tenantId:n,...s};try{return _t(await e(t,r))}catch(a){if(Le(a).kind!=="temporary")throw a;return await new Promise(u=>setTimeout(u,2e3)),_t(await e(t,r))}}}}async function jn(e,n){var a,u;const t=await e.call("get_analysis_guide",{context:"Refreshing the sales commission dashboard with the latest commission queries.",slug:Vn,includeReferenceQueries:!0,...n?{pageSetup:n}:{}}),s=(a=t.item)!=null?a:t,r={};for(const i of(u=s.referenceQueries)!=null?u:[])typeof i.slug=="string"&&typeof i.sqlText=="string"&&(r[i.slug]=i.sqlText);for(const i of Object.values(he))if(!r[i])throw new W({kind:"tool",message:`The guide is missing the ${i} query.`});return{version:$(s.version),queries:r}}async function be(e,n,t){const s=await e.call("safe_tenant_sql",{context:t,sqlText:n});return{rows:Array.isArray(s.rows)?s.rows:[],complete:s.resultMode!=="sampled_preview"}}function ke(e,n,t){try{return kt(e.queries[n],t)}catch{throw new W({kind:"needs_update"})}}function $t(e,n){const t=[];for(let s=e;s<=n;s=U(s,3)){const r=U(s,2);t.push({first:s,last:r<n?r:n})}return t}async function Wn(e,n,t){const s="Loading each associate's commission by pay period and month for the dashboard.",r=await be(e,ke(n,he.summary,t),s);if(r.complete)return r.rows;const a=[];for(const i of $t(t.reportMonths.first,t.reportMonths.last)){const l=await be(e,ke(n,he.summary,{...t,reportMonths:i}),s);if(!l.complete)throw new W({kind:"tool",message:"The commission summary is too large to load in one quarter."});a.push(...l.rows)}const u=new Set;return a.filter(i=>{const l=[i.grain,i.associate_account_id,i.associate_name,i.period_start].join("|");return u.has(l)?!1:(u.add(l),!0)})}async function St(e,n,t,s){const r="Loading monthly sales performance for the commission dashboard.",a=await be(e,ke(n,t,s),r);if(a.complete)return a.rows;const u=[],i=s.windowStart.slice(0,7),l=ce(s.windowEnd,-1).slice(0,7);for(const m of $t(i,l)){const c=`${U(m.last,1)}-01`,d=await be(e,ke(n,t,{...s,windowStart:`${m.first}-01`,windowEnd:c<s.windowEnd?c:s.windowEnd}),r);if(!d.complete)throw new W({kind:"tool",message:"Monthly performance is too large to load in one quarter."});u.push(...d.rows)}return u}async function Bn(e,n,t){const s=await be(e,ke(n,he.lines,t),"Loading one associate's commission lines for the pay period on screen.");if(!s.complete)throw new W({kind:"tool",message:"This associate's lines are too many to load at once."});return s.rows}function Kn(e,n){var s;const t=new Map;for(const r of e){const a=q(r.month);t.set(a,((s=t.get(a))!=null?s:0)+$(r.credited_sales))}return n.every(r=>{var a;return Math.abs(((a=t.get(q(r.month)))!=null?a:0)-$(r.associate_credited_sales))<=5})}function ze(e){var t;const n=e.associate_account_id;return typeof n=="string"&&n?n:String((t=e.associate_name)!=null?t:"")}function Hn(e){var n,t;return String((t=(n=e.associate_name)!=null?n:e.associate_account_id)!=null?t:"Unnamed")}const Ct=["eligible_sales","eligible_commission","eligible_lines","pending_sales","pending_commission","pending_lines","excluded_sales","excluded_commission","unpriced_lines","refunds","refund_lines","refunds_after_window","refunded_off_lines"],Yn=Object.fromEntries(Ct.map(e=>[e,0]));function Tt(e){return e?Object.fromEntries(Ct.map(n=>[n,$(e[n])])):{...Yn}}function B(e,n,t){return Tt(e.summary.find(s=>s.grain==="pay_period"&&Ne(s.period_start)===t.start&&ze(s)===n))}function ue(e,n,t){return Tt(e.summary.find(s=>s.grain==="month"&&q(s.period_start)===t&&ze(s)===n))}function nt(e,n){return e.summary.some(t=>t.grain==="pay_period"&&Ne(t.period_start)===n.start)}const Zn=["credited_sales","orders","bottles","club_signups","club_cancellations"];function Nt(e,n){for(const t of Zn)e[t]+=$(n[t]);return e}const At=()=>({credited_sales:0,orders:0,bottles:0,club_signups:0,club_cancellations:0});function _e(e,n,t){return e.performance.filter(s=>q(s.month)===t&&ze(s)===n).reduce(Nt,At())}function $e(e,n){return e.performance.filter(t=>q(t.month)===n).reduce(Nt,At())}function Jn(e,n){return e.performance.some(t=>q(t.month)===n)||e.sources.some(t=>q(t.month)===n)}function Mt(e,n){return e.sources.find(t=>q(t.month)===n)}function De(e,n,t){const s=new Map,r=a=>{const u=ze(a);if(!u||s.has(u))return;const i=a.associate_account_id;s.set(u,{key:u,name:Hn(a),accountId:typeof i=="string"&&i?i:null})};return e.summary.filter(a=>a.grain==="pay_period"&&Ne(a.period_start)===n.start).forEach(r),e.performance.filter(a=>q(a.month)===t).forEach(r),[...s.values()].sort((a,u)=>B(e,u.key,n).eligible_commission-B(e,a.key,n).eligible_commission||a.name.localeCompare(u.name))}function st(e,n=12){return Array.from({length:n},(t,s)=>U(e,s-n+1))}function Oe(e,n){return n.filter(t=>Jn(e,t))}function Et(e,n){const t=s=>s.associateAccountId===null&&s.associateName===null||s.associateAccountId!==null&&s.associateAccountId===n.accountId||s.associateName!==null&&s.associateName===n.name;return e.filter(s=>t(s)&&s.rate>0)}function Qn(e){return e.productKind==="wine"?"wine":e.productKind&&e.productValue?e.productValue:"everything else"}function Xn(e){if(!e.length||e.some(t=>t.rateKind!=="percent"))return null;const n=e[0].rate;return e.every(t=>t.rate===n)?n:null}function Gt(e){const n={eligible:0,pending:0,excluded:0};for(const t of e)t.bucket==="eligible"&&(n.eligible+=$(t.net_dollars)),t.bucket==="pending"&&(n.pending+=$(t.net_dollars)),(t.bucket==="excluded"||t.bucket==="unpriced")&&(n.excluded+=$(t.net_dollars));return{eligible:e.filter(t=>t.bucket==="eligible").sort((t,s)=>$(s.net_dollars)-$(t.net_dollars)),unpriced:e.filter(t=>t.bucket==="unpriced"),refundsListed:e.filter(t=>t.bucket==="refund"&&t.refund_listed===!0),refundsNotListed:e.filter(t=>t.bucket==="refund"&&t.refund_counts===!0&&t.refund_listed!==!0),totals:n}}function es(e,n="order_id"){const t=e.tenant_id,s=e[n];return typeof t!="string"||!t||typeof s!="string"&&typeof s!="number"?null:`https://${encodeURIComponent(t)}.pos.platform.commerce7.com/store/order/${encodeURIComponent(String(s))}/summary`}const ts="commission-dashboard";function ns(){const e=globalThis.storage;return e&&typeof e.get=="function"&&typeof e.set=="function"?e:null}function ss(){try{const e=globalThis.localStorage,n="__nv_probe__";return e.setItem(n,"1"),e.removeItem(n),e}catch{return null}}function os(e){return typeof e=="string"?e:e&&typeof e=="object"&&typeof e.value=="string"?e.value:null}function rs(e){if(e)return{adapter:e,mode:"shared"};const n=ns();if(n)return{mode:"shared",adapter:{get:async(s,r)=>{try{return os(await n.get(s,r))}catch{return null}},set:async(s,r,a)=>{await n.set(s,r,a)}}};const t=ss();return t?{mode:"browser",adapter:{get:async(s,r)=>t.getItem(r?s:`personal:${s}`),set:async(s,r,a)=>t.setItem(a?s:`personal:${s}`,r)}}:{adapter:null,mode:"none"}}function Lt(e){var n,t,s,r;return{teamGoal:(n=e.teamGoal)!=null?n:null,teamCommissionGoal:(t=e.teamCommissionGoal)!=null?t:null,associateGoals:{...(s=e.associateGoals)!=null?s:{}},associateCommissionGoals:{...(r=e.associateCommissionGoals)!=null?r:{}}}}function ye(e){return{schemaVersion:1,planRevision:e.planRevision,goalChanges:[],...Lt(e)}}function zt(e){return`${ts}:${e}`}async function as(e,n,t){var s,r,a,u;if(!e)return ye(t);try{const i=await e.get(zt(n),!0);if(!i)return ye(t);const l=JSON.parse(i);return l.schemaVersion!==1||typeof l.planRevision!="number"||l.planRevision<t.planRevision?ye(t):{schemaVersion:1,planRevision:l.planRevision,teamGoal:(s=l.teamGoal)!=null?s:null,teamCommissionGoal:(r=l.teamCommissionGoal)!=null?r:null,associateGoals:{...(a=l.associateGoals)!=null?a:{}},associateCommissionGoals:{...(u=l.associateCommissionGoals)!=null?u:{}},goalChanges:Array.isArray(l.goalChanges)?l.goalChanges:[]}}catch{return ye(t)}}async function is(e,n,t){if(!e)return!1;try{return await e.set(zt(n),JSON.stringify(t),!0),!0}catch{return!1}}async function ls(e,n){if(!e)return null;try{return await e.get(n,!1)}catch{return null}}async function cs(e,n,t){if(e)try{await e.set(n,t,!1)}catch{}}function ds(e,n,t){if(Dt(e,t)===Dt(n,t))return null;for(let r=e.goalChanges.length-1;r>=0;r-=1)if(e.goalChanges[r].goal===t)return e.goalChanges[r];return null}function Dt(e,n){if(n==="team-sales")return e.teamGoal;if(n==="team-commission")return e.teamCommissionGoal;const[t,...s]=n.split(":"),r=s.join(":"),a=t==="sales"?e.associateGoals[r]:e.associateCommissionGoals[r];return a===void 0?null:a}function us(e,n,t,s,r){const a={...e,associateGoals:{...e.associateGoals},associateCommissionGoals:{...e.associateCommissionGoals},goalChanges:[...e.goalChanges,{goal:n,value:t,at:r,by:s}]};if(n==="team-sales")a.teamGoal=t;else if(n==="team-commission")a.teamCommissionGoal=t;else{const[u,...i]=n.split(":"),l=i.join(":"),m=u==="sales"?a.associateGoals:a.associateCommissionGoals;t===null?delete m[l]:m[l]=t}return a}const Ot="0.1.1",Re=(e,n)=>String(e!=null?e:"").replace(/\s+/g," ").trim().slice(0,n);function Rt(e={},n=[]){var t,s,r,a,u,i;return{packageVersion:Ot,hiddenSections:((t=e.hide)!=null?t:[]).slice(0,20).map(l=>Re(l,40)),reorderedViews:["team","associate"].filter(l=>{var m,c,d;return((d=(c=(m=e.order)==null?void 0:m[l])==null?void 0:c.length)!=null?d:0)>0}),renamedSections:Object.keys((s=e.labels)!=null?s:{}).slice(0,20).map(l=>Re(l,40)),themeChanged:Object.keys((r=e.theme)!=null?r:{}).length+Object.keys((a=e.themeDark)!=null?a:{}).length>0,fontsChanged:!!((u=e.fonts)!=null&&u.display||(i=e.fonts)!=null&&i.body),titleChanged:!!e.title,customCards:n.slice(0,10).map(l=>({title:Re(l.title,80),purpose:Re(l.purpose,160),view:l.view}))}}const ms={"surface-base":"#f7f5f1","surface-subtle":"#f2efea","surface-panel":"#ece8e1","surface-raised":"#ffffff","text-primary":"#1a1917","text-secondary":"#4f4a43","text-tertiary":"#6b655d","border-subtle":"#ebe7df","border-default":"#ddd8ce","border-strong":"#8d877f","action-primary-bg":"#0b6623","action-primary-fg":"#ffffff","action-primary-hover":"#155826","focus-ring-color":"#1a6b30","status-success":"#127a45","status-success-bg":"#edf8f1","status-warning":"#9c6110","status-warning-bg":"#fff7e7","status-error":"#b73847","status-error-bg":"#fdf0f2","chart-bar":"#c3d0e0","chart-bar-hover":"#9fb4ce","chart-bar-selected":"#2b5a8c","chart-series-1":"#2b5a8c","chart-series-2":"#6f95c2","chart-series-3":"#c3d0e0","font-display":"'Newsreader', Georgia, serif","font-body":"'Be Vietnam Pro', system-ui, sans-serif"},ps={"surface-base":"#171614","surface-subtle":"#1f1d1b","surface-panel":"#262320","surface-raised":"#34302d","text-primary":"#f5f3ef","text-secondary":"#d0c8bd","text-tertiary":"#b4aba0","border-subtle":"#3b3632","border-default":"#4c4742","border-strong":"#8a8279","action-primary-bg":"#57bd76","action-primary-fg":"#06210d","action-primary-hover":"#7ecb93","focus-ring-color":"#8cd0a0","status-success":"#47d78b","status-success-bg":"rgba(71,215,139,.16)","status-warning":"#f0c36a","status-warning-bg":"rgba(240,195,106,.16)","status-error":"#f28c95","status-error-bg":"rgba(242,140,149,.12)","chart-bar":"#3a4a5f","chart-bar-hover":"#4d6380","chart-bar-selected":"#8db7e8","chart-series-1":"#8db7e8","chart-series-2":"#557ba6","chart-series-3":"#33445a"},fs=/^[a-z][a-z0-9-]{0,40}$/,gs=/^[^;{}<>\\]{1,120}$/;function It(e){return Object.entries(e).filter(([n,t])=>fs.test(n)&&gs.test(t)).map(([n,t])=>`--${n}:${t};`).join("")}function hs(e){return`https://fonts.googleapis.com/css2?${e.map(t=>`family=${encodeURIComponent(t).replace(/%20/g,"+")}:wght@300;400;500;600`).join("&")}&display=swap`}function bs(e={},n={}){const t=It({...ms,...e}),s=It({...ps,...n});return`.nvcd{${t}}@media (prefers-color-scheme: dark){.nvcd{${s}}}`}const ys=`
5
5
  html,body{margin:0;background:var(--surface-base,#f7f5f1)}
6
6
  .nvcd{background:var(--surface-base);color:var(--text-primary);font:16px/1.5 var(--font-body);-webkit-font-smoothing:antialiased;min-height:100vh}
7
7
  .nvcd *{box-sizing:border-box}
@@ -12,8 +12,32 @@ html,body{margin:0;background:var(--surface-base,#f7f5f1)}
12
12
  .nvcd h1{font:300 32px/1.15 var(--font-display);letter-spacing:-.02em;margin:0}
13
13
  .nvcd h2{font:500 20px/1.3 var(--font-display);margin:0 0 12px}
14
14
  .nvcd .meta{color:var(--text-tertiary);font-size:14px;margin-top:4px}
15
- .nvcd .data-label{display:inline-block;margin-top:8px;font-size:13px;color:var(--text-secondary)}
15
+ .nvcd .data-label{display:inline-flex;align-items:center;gap:8px;margin-top:8px;padding:4px 12px;border-radius:999px;font-size:13px;font-weight:500;color:var(--text-secondary);background:var(--surface-subtle);border:1px solid var(--border-subtle)}
16
+ .nvcd .data-label .dot{width:8px;height:8px;border-radius:50%;background:var(--text-tertiary)}
17
+ .nvcd .data-live .dot{background:var(--status-success)}
18
+ .nvcd .data-busy{color:var(--text-primary);border-color:var(--border-strong)}
19
+ .nvcd .spinner{display:inline-block;width:12px;height:12px;border-radius:50%;border:2px solid var(--border-default);border-top-color:var(--action-primary-bg);animation:nvcd-spin 800ms linear infinite;flex:none}
20
+ .nvcd .progress{position:absolute;left:0;right:0;bottom:-1px;height:3px;overflow:hidden;background:var(--border-subtle)}
21
+ .nvcd .progress::after{content:"";position:absolute;top:0;bottom:0;width:35%;background:var(--action-primary-bg);animation:nvcd-slide 1.2s cubic-bezier(0.2,0,0.2,1) infinite}
22
+ .nvcd .skel{display:block;border-radius:6px;background:linear-gradient(90deg,var(--surface-subtle) 25%,var(--surface-panel) 50%,var(--surface-subtle) 75%);background-size:200% 100%;animation:nvcd-shimmer 1.4s ease-in-out infinite}
23
+ .nvcd .skel-eyebrow{width:40%;height:12px}
24
+ .nvcd .skel-hero{width:55%;height:48px;margin:12px 0}
25
+ .nvcd .skel-line{width:80%;height:14px;margin-top:8px}
26
+ .nvcd .skel-figure{width:50%;height:24px;margin-top:8px}
27
+ .nvcd .skel-cell{height:14px;flex:1}
28
+ .nvcd .skel-wide{height:14px;flex:2.5}
29
+ .nvcd .skeleton-caption{display:flex;align-items:center;gap:8px;font-size:14px;color:var(--text-secondary);margin-bottom:12px}
30
+ .nvcd .skeleton-row{display:flex;gap:16px;padding:12px 0;border-bottom:1px solid var(--border-subtle)}
31
+ .nvcd .skeleton-row:last-child{border-bottom:0}
32
+ @keyframes nvcd-spin{to{transform:rotate(360deg)}}
33
+ @keyframes nvcd-slide{from{left:-35%}to{left:100%}}
34
+ @keyframes nvcd-shimmer{from{background-position:200% 0}to{background-position:-200% 0}}
16
35
  .nvcd .eyebrow{font:600 12px/1.4 var(--font-body);text-transform:uppercase;letter-spacing:.12em;color:var(--text-secondary)}
36
+ .nvcd .eyebrow-row{display:flex;flex-wrap:wrap;align-items:baseline;justify-content:space-between;gap:4px 12px}
37
+ .nvcd .eyebrow-period{font-size:13px;color:var(--text-tertiary)}
38
+ .nvcd .meta{display:flex;flex-wrap:wrap;gap:4px 16px}
39
+ .nvcd .meta-winery{font-weight:500;color:var(--text-secondary)}
40
+ .nvcd .period-open{font-size:12px;font-weight:500;padding:2px 8px;border-radius:999px;border:1px solid var(--border-strong);color:var(--text-secondary)}
17
41
  .nvcd .caption,.nvcd .note{font-size:13px;color:var(--text-secondary);margin:4px 0 0}
18
42
  .nvcd .section{margin-top:32px}
19
43
  .nvcd .card{background:var(--surface-raised);border:1px solid var(--border-default);border-radius:12px;box-shadow:0 6px 18px rgba(26,25,23,.07);padding:24px}
@@ -41,7 +65,7 @@ html,body{margin:0;background:var(--surface-base,#f7f5f1)}
41
65
  .nvcd select,.nvcd input,.nvcd button{font:inherit;font-size:14px;color:var(--text-primary)}
42
66
  .nvcd select,.nvcd input{background:var(--surface-raised);border:1px solid var(--border-strong);border-radius:8px;padding:8px;min-height:36px}
43
67
  .nvcd .view-select{font-weight:600;font-size:16px;min-width:220px}
44
- .nvcd .period{display:flex;align-items:center;gap:8px;font-weight:500;font-variant-numeric:tabular-nums}
68
+ .nvcd .period{display:flex;align-items:center;gap:8px;font-weight:500;font-variant-numeric:tabular-nums;white-space:nowrap}
45
69
  .nvcd .period-short{display:none}
46
70
  .nvcd .icon-button{display:inline-flex;align-items:center;justify-content:center;min-width:36px;min-height:36px;border:1px solid var(--border-strong);border-radius:8px;background:var(--surface-raised);cursor:pointer}
47
71
  .nvcd .icon-button:disabled{opacity:.4;cursor:default}
@@ -70,11 +94,18 @@ html,body{margin:0;background:var(--surface-base,#f7f5f1)}
70
94
  .nvcd .goalbar-zero{position:absolute;top:-2px;width:1px;height:16px;background:var(--border-strong)}
71
95
  .nvcd .chart-title{font-size:14px;font-weight:500}
72
96
  .nvcd .readout{font-size:13px;color:var(--text-secondary);min-height:20px;font-variant-numeric:tabular-nums}
73
- .nvcd .bars{display:flex;align-items:flex-end;gap:4px;height:140px;margin-top:8px}
74
- .nvcd .bar{flex:1;display:flex;flex-direction:column;justify-content:flex-end;align-items:stretch;height:100%;border:0;background:transparent;padding:0;cursor:default;min-width:0}
75
- .nvcd .bar-fill{display:block;background:var(--border-strong);border-radius:3px 3px 0 0}
76
- .nvcd .bar-selected .bar-fill{background:var(--text-secondary)}
77
- .nvcd .bar-label{font-size:12px;color:var(--text-tertiary);text-align:center;margin-top:4px;overflow:hidden;white-space:nowrap}
97
+ .nvcd .charts{grid-template-columns:repeat(auto-fit,minmax(min(100%,440px),1fr))}
98
+ .nvcd .chart{margin:0;container-type:inline-size}
99
+ .nvcd .bars,.nvcd .bar-labels{display:grid;grid-auto-flow:column;grid-auto-columns:minmax(0,1fr);gap:6px}
100
+ .nvcd .bars{align-items:end;height:160px;margin-top:8px;border-bottom:1px solid var(--border-default)}
101
+ .nvcd .bar{display:flex;align-items:flex-end;height:100%;border:0;background:transparent;padding:0;cursor:default;min-width:0}
102
+ .nvcd .bar-fill{display:block;width:100%;background:var(--chart-bar);border-radius:3px 3px 0 0;transition:background 120ms cubic-bezier(0.2,0,0.2,1)}
103
+ .nvcd .bar:hover .bar-fill,.nvcd .bar:focus-visible .bar-fill{background:var(--chart-bar-hover)}
104
+ .nvcd .bar-selected .bar-fill,.nvcd .bar-selected:hover .bar-fill{background:var(--chart-bar-selected)}
105
+ .nvcd .bar-labels{margin-top:6px}
106
+ .nvcd .bar-label{font-size:12px;color:var(--text-tertiary);text-align:center;white-space:nowrap;overflow:visible}
107
+ .nvcd .bar-label-selected{color:var(--text-primary);font-weight:600}
108
+ @container (max-width: 360px){.nvcd .bar-label-minor{visibility:hidden}}
78
109
  .nvcd .stack{display:flex;height:16px;border-radius:8px;overflow:hidden;margin:12px 0}
79
110
  .nvcd .stack span{display:block;height:100%}
80
111
  .nvcd .legend{display:flex;flex-wrap:wrap;gap:16px;font-size:14px}
@@ -113,12 +144,15 @@ html,body{margin:0;background:var(--surface-base,#f7f5f1)}
113
144
  .nvcd .grid-5{grid-template-columns:repeat(2,minmax(0,1fr))}
114
145
  .nvcd .heroes{grid-template-columns:1fr}
115
146
  .nvcd .hero-value{font-size:44px}
116
- .nvcd .controlbar-inner{flex-wrap:nowrap}
117
- .nvcd .view-select{flex:1;min-width:0}
147
+ .nvcd .controlbar-inner{flex-wrap:wrap;gap:8px}
148
+ .nvcd .view-select{flex:1 1 110px;min-width:0;font-size:15px;text-overflow:ellipsis}
149
+ .nvcd .period{flex:0 0 auto;margin-left:auto;white-space:nowrap;gap:4px;font-size:14px}
118
150
  .nvcd .period-long{display:none}
119
151
  .nvcd .period-short{display:inline}
152
+ .nvcd .period-open{display:none}
153
+ .nvcd .eyebrow-row{flex-direction:column;align-items:flex-start;gap:2px}
120
154
  .nvcd .icon-button,.nvcd .button,.nvcd .button-quiet,.nvcd select,.nvcd input{min-height:44px}
121
155
  .nvcd .disclosure summary{min-height:44px}
122
156
  }
123
- @media (prefers-reduced-motion: reduce){.nvcd *{transition-duration:0ms!important}}
124
- `,fs=["teamHeroes","teamTiles","teamCharts","teamSources","teamTable","teamMissing"],ps=["associateSummary","associatePayout","associateCharts","associateMonths","associateLines","associateRefunds"];function W(e,n,t){const s=n==="sales"?e.associateGoals[t]:e.associateCommissionGoals[t];return s!=null?{value:s,custom:!0}:{value:n==="sales"?e.teamGoal:e.teamCommissionGoal,custom:!1}}function Z(e,n,t,s){if(n==null)return"none";if(e>=n)return"met";const o=s.slice(0,7);if(o>t)return"behind";if(o<t)return"on_pace";const a=n*Number(s.slice(8,10))/Nn(t);return e>=a?"on_pace":"behind"}const Nt={met:"Met",on_pace:"On pace",behind:"Behind pace",none:"No goal"};function At(e,n){return n?e==="none"?`No ${n.toLowerCase()}`:`${n} ${Nt[e].toLowerCase()}`:Nt[e]}const Mt={met:0,on_pace:1,behind:2,none:3};function r(e,n=null,...t){const s=document.createElement(e);for(const[o,a]of Object.entries(n!=null?n:{}))a==null||a===!1||(typeof a=="function"?s.addEventListener(o.replace(/^on/,"").toLowerCase(),a):a===!0?s.setAttribute(o,""):s.setAttribute(o,String(a)));return Et(s,t),s}function Et(e,n){for(const t of n)t==null||t===!1||(Array.isArray(t)?Et(e,t):e.append(t instanceof Node?t:String(t)))}const gs="http://www.w3.org/2000/svg";function ve(e,n={},...t){const s=document.createElementNS(gs,e);for(const[o,a]of Object.entries(n))s.setAttribute(o,String(a));return s.append(...t),s}const hs={"chevron-left":"M15 18l-6-6 6-6","chevron-right":"M9 18l6-6-6-6","chevron-down":"M6 9l6 6 6-6","external-link":"M15 3h6v6M10 14L21 3M18 13v6a2 2 0 0 1-2 2H5a2 2 0 0 1-2-2V8a2 2 0 0 1 2-2h6",info:"M12 16v-4M12 8h.01M22 12a10 10 0 1 1-20 0 10 10 0 0 1 20 0z"};function Le(e,n=16){var t;return ve("svg",{width:n,height:n,viewBox:"0 0 24 24",fill:"none",stroke:"currentColor","stroke-width":2,"stroke-linecap":"round","stroke-linejoin":"round","aria-hidden":"true"},ve("path",{d:(t=hs[e])!=null?t:""}))}function J(e,n,t=!1){const s=t&&n?At(e,`Custom ${n.toLowerCase()}`):At(e,n);return r("span",{class:`pill pill-${e}`},s)}function ze(e){return r("div",{class:"eyebrow"},e)}function L(e,n,t){return r("div",{class:"figure card"},r("div",{class:"figure-label"},e),r("div",{class:"figure-value"},n),t?r("div",{class:"caption"},t):null)}function k(e,n="note"){return r("p",{class:n},e)}function bs(e,n,t=!1){return r("span",{class:`tip${t?" tip-end":""}`,tabindex:0,"aria-label":`${e}. ${n}`},e,r("span",{class:"tip-body",role:"tooltip"},n))}function me(e,n,t=se){var i;const s=(i=n.find(l=>l.selected))!=null?i:n[n.length-1],o=r("div",{class:"readout","aria-live":"polite"},s?`${s.label}: ${t(s.value)}`:""),a=Math.max(1,...n.map(l=>Math.abs(l.value))),c=n.map(l=>{const m=`${l.label}: ${t(l.value)}`,d=()=>{o.textContent=m};return r("button",{class:`bar${l.selected?" bar-selected":""}`,type:"button","aria-label":m,title:m,onmouseenter:d,onfocus:d},r("span",{class:"bar-fill",style:`height:${Math.max(2,Math.abs(l.value)/a*100)}%`}),r("span",{class:"bar-label"},l.label))});return r("figure",{class:"chart card"},r("figcaption",{class:"chart-title"},e),o,r("div",{class:"bars"},c))}function ys(e,n){const o=Math.max(1,...e),a=e.length>1?96/(e.length-1):0,c=e.map((l,m)=>`${(m*a).toFixed(1)},${(22-Math.max(0,l)/o*20).toFixed(1)}`),i=[ve("polyline",{points:c.join(" "),fill:"none",stroke:"var(--text-tertiary)","stroke-width":1.5})];if(n>=0&&c[n]){const[l,m]=c[n].split(",");i.push(ve("circle",{cx:l,cy:m,r:2.5,fill:"var(--text-primary)"}))}return ve("svg",{width:96,height:24,viewBox:"0 0 96 24","aria-hidden":"true",class:"sparkline"},...i)}function He(e,n,t={}){const s=[...n],o=e.find(l=>l.key===t.sortKey&&l.sort);if(o!=null&&o.sort){const l=t.sortDir==="asc"?1:-1;s.sort((m,d)=>{const u=o.sort(m),y=o.sort(d);return(u<y?-1:u>y?1:0)*l})}const a=r("tr",null,e.map((l,m)=>{const d=l.tip?bs(l.label,l.tip,m===e.length-1):l.label,u=!!(l.sort&&t.onSort),y=(o==null?void 0:o.key)===l.key;return r("th",{scope:"col",class:l.numeric?"num":null,"aria-sort":y?t.sortDir==="asc"?"ascending":"descending":null},u?r("button",{type:"button",class:"sort",onclick:()=>t.onSort(l.key)},d,y?t.sortDir==="asc"?" ↑":" ↓":""):d)})),c=s.map(l=>r("tr",null,e.map(m=>r("td",{class:m.numeric?"num":null},m.cell(l))))),i=t.footer?r("tfoot",null,r("tr",null,t.footer.map((l,m)=>r("td",{class:m>0?"num":null},l)))):null;return r("div",{class:"table-wrap"},r("table",null,t.caption?r("caption",{class:"sr-only"},t.caption):null,r("thead",null,a),r("tbody",null,c),i))}function Ye(e){for(const n of Array.from(e.querySelectorAll(".table-wrap"))){n.classList.remove("boxed");const t=n.querySelector("table");t&&t.scrollWidth>n.clientWidth+1&&n.classList.add("boxed")}}function Ze(e,n,t,...s){const o=r("details",{class:"disclosure",open:n},r("summary",null,Le("chevron-down",14),e),r("div",{class:"disclosure-body"},s));return o.addEventListener("toggle",()=>t(o.open)),o}const Gt={howTo:"How to read this page",teamHeroes:"",teamTiles:"This month",teamCharts:"Trends",teamSources:"Where sales come from",teamTable:"Associates",teamMissing:"What this page can't show",associateSummary:"",associatePayout:"Upcoming payout",associateCharts:"Months",associateMonths:"By month",associateLines:"Lines",associateRefunds:"Refunds",rulesFooter:"Rules"};function G(e,n){var s,o,a;const t=(a=(o=(s=e.options.customize)==null?void 0:s.labels)==null?void 0:o[n])!=null?a:Gt[n];return t?r("h2",null,t):null}function De(e){const n=e.replace(/[$,\s]/g,"");if(!n)return null;const t=Number(n);return Number.isFinite(t)&&t>=0?Math.round(t*100)/100:null}function Oe(e,n){const t=os(e.saved,e.baseline,n);if(!t)return null;const s=O(t.at,e.options.settings.timeZone);return r("div",{class:"changed"},`Changed on this page ${s}${t.by?` by ${t.by}`:""}`)}function Lt(e){return e.saved.goalChanges.length>0}const T=e=>Te(e.period);function zt(e,n,t){let s=0,o=!1;for(const a of n){const c=W(e.saved,t,a.key).value;c!==null&&(s+=c,o=!0)}return o?s:null}function Dt(e){return e.saved.teamCommissionGoal!==null||Object.values(e.saved.associateCommissionGoals).some(n=>n!=null)}function Ot(e,n){return n?`${(Math.round(e/n*100)/100).toFixed(2)}× the goal`:""}const vs=(e,n)=>{const t=Me(e.data,e.period,T(e)),s=t.reduce((v,N)=>v+j(e.data,N.key,e.period).eligible_commission,0),o=t.reduce((v,N)=>v+j(e.data,N.key,e.period).eligible_sales,0),a=t.reduce((v,N)=>v+te(e.data,N.key,T(e)).eligible_sales,0),c=t.reduce((v,N)=>v+te(e.data,N.key,T(e)).eligible_commission,0),i=zt(e,t,"sales"),l=zt(e,t,"commission"),m=Z(a,i,T(e),e.today),d=Z(c,l,T(e),e.today),u=le(e.period),y=r("div",{class:"card"},ze(`Team eligible commission · ${F(e.period)}`),r("div",{class:"hero-value"},h(s)),l!==null?r("div",{class:"pills"},r("span",{class:"caption"},`Commission goal ${h(l)} · ${Ot(c,l)}`),J(d,"Commission goal")):null),b=r("div",{class:"card"},ze(`Team eligible sales · ${F(e.period)}`),r("div",{class:"hero-value"},h(o)),r("div",{class:"pills"},i!==null?r("span",{class:"caption"},`${u?"":`${D(T(e),!0)} eligible sales ${h(a)} · `}${Ot(a,i)} of ${h(i)}`):null,J(m,"Sales goal"))),p=r("input",{type:"text",inputmode:"decimal",id:"team-sales-goal","data-fid":"team-sales-goal",placeholder:e.saved.teamGoal!==null?`${h(e.saved.teamGoal)} now`:"No sales goal","aria-label":"Team monthly sales goal"}),_=r("input",{type:"text",inputmode:"decimal",id:"team-commission-goal","data-fid":"team-commission-goal",placeholder:e.saved.teamCommissionGoal!==null?`${h(e.saved.teamCommissionGoal)} now`:"No commission goal","aria-label":"Team monthly commission goal"}),z=Ze("Edit team goals",e.openDisclosures.has("team-goals"),v=>n.toggleDisclosure("team-goals",v),k("Team goals are the monthly default for every associate. An associate's custom goal still replaces it."),r("div",{class:"goal-row"},r("label",{for:"team-sales-goal"},"Monthly sales goal"),p,e.saved.teamGoal!==null?r("button",{type:"button",class:"button-quiet",onclick:()=>n.setGoal("team-sales",null)},"Remove"):null),Oe(e,"team-sales"),r("div",{class:"goal-row"},r("label",{for:"team-commission-goal"},"Monthly commission goal"),_,e.saved.teamCommissionGoal!==null?r("button",{type:"button",class:"button-quiet",onclick:()=>n.setGoal("team-commission",null)},"Remove"):null),Oe(e,"team-commission"),r("div",{class:"goal-row"},r("button",{type:"button",class:"button",onclick:()=>{const v=De(p.value),N=De(_.value);v!==null&&n.setGoal("team-sales",v),N!==null&&n.setGoal("team-commission",N)}},"Set"),Lt(e)?r("button",{type:"button",class:"button-quiet",onclick:n.restoreGoals},"Restore goals set in chat"):null));return r("div",null,r("div",{class:"grid grid-2 heroes"},y,b),r("div",{style:"margin-top:12px"},z))};function we(e,n,t){if(n===null)return"No prior month loaded";const s=e-n;return s===0?"Same as last month":`${s>0?"+":"−"}${t(Math.abs(s))} vs last month`}const ws=e=>{var i,l,m;const n=ye(e.data,T(e)),t=q(T(e),-1),o=Ee(e.data,[t]).length>0?ye(e.data,t):null,a=d=>d.orders?d.credited_sales/d.orders:0,c=d=>d.orders?d.bottles/d.orders:0;return r("div",null,G(e,"teamTiles"),r("div",{class:"grid grid-5"},L("Orders",C(n.orders),we(n.orders,(i=o==null?void 0:o.orders)!=null?i:null,C)),L("Average order",se(a(n)),we(a(n),o?a(o):null,se)),L("Bottles per order",C(c(n)),we(c(n),o?c(o):null,C)),L("Club signups",C(n.club_signups),we(n.club_signups,(l=o==null?void 0:o.club_signups)!=null?l:null,C)),L("Club cancellations",C(n.club_cancellations),we(n.club_cancellations,(m=o==null?void 0:o.club_cancellations)!=null?m:null,C))))},xs=e=>{const n=Ee(e.data,Ke(T(e)));if(n.length<2)return r("div",null,G(e,"teamCharts"),k(e.live?"Trends need more than one month of sales.":"Trends need the New Vintage connector."));const t=s=>n.map(o=>({label:D(o),value:s(o),selected:o===T(e)}));return r("div",null,G(e,"teamCharts"),r("div",{class:"grid grid-3"},me("Credited sales",t(s=>ye(e.data,s).credited_sales)),me("Orders",t(s=>ye(e.data,s).orders),C),me("Club signups",t(s=>{var o,a;return S((a=(o=vt(e.data,s))==null?void 0:o.team_club_signups)!=null?a:ye(e.data,s).club_signups)}),C)))},_s=e=>{const n=vt(e.data,T(e));if(!n)return r("div",null,G(e,"teamSources"),k("Sales sources for this month need the New Vintage connector."));const t=S(n.paid_sales),s=[{label:"Associate-credited",value:S(n.associate_credited_sales),color:"var(--text-primary)"},{label:"Club processing",value:S(n.club_processing_sales),color:"var(--text-tertiary)"},{label:"Other",value:S(n.other_sales),color:"var(--border-strong)"}],o=a=>t?Math.round(a/t*100):0;return r("div",null,G(e,"teamSources"),r("div",{class:"card"},ze(`Paid sales · ${D(T(e),!0)}`),r("div",{class:"figure-value"},h(t)),r("div",{class:"stack",role:"img","aria-label":s.map(a=>`${a.label} ${o(a.value)}%`).join(", ")},s.map(a=>r("span",{style:`width:${o(a.value)}%;background:${a.color}`}))),r("div",{class:"legend"},s.map(a=>r("span",null,r("span",{class:"swatch",style:`background:${a.color}`}),`${a.label} ${o(a.value)}% · ${se(a.value)}`))),k(`An associate can be credited with ${o(s[0].value)}% of the winery's paid sales this month; club processing and other sales have no associate.`)))},ks=(e,n)=>{const t=T(e),s=Ke(t),o=Me(e.data,e.period,t).map(i=>{const l=j(e.data,i.key,e.period),m=te(e.data,i.key,t),d=be(e.data,i.key,t);return{associate:i,commission:l.eligible_commission,eligible:l.eligible_sales,monthEligible:m.eligible_sales,monthCommission:m.eligible_commission,salesStatus:Z(m.eligible_sales,W(e.saved,"sales",i.key).value,t,e.today),commissionStatus:Z(m.eligible_commission,W(e.saved,"commission",i.key).value,t,e.today),credited:d.credited_sales,orders:d.orders,bottles:d.bottles,signups:d.club_signups,refunds:l.refunds,trend:s.map(u=>be(e.data,i.key,u).credited_sales)}}),a=o.filter(i=>i.trend.some(l=>l!==0)).length,c=[{key:"associate",label:"Associate",cell:i=>r("button",{type:"button",class:"name-link","data-fid":`pick-${i.associate.key}`,onclick:()=>n.selectAssociate(i.associate.key)},i.associate.name),sort:i=>i.associate.name.toLowerCase()},{key:"commission",label:"Commission",numeric:!0,cell:i=>h(i.commission),sort:i=>i.commission},{key:"eligible",label:"Eligible sales",numeric:!0,cell:i=>h(i.eligible),sort:i=>i.eligible}];return le(e.period)||c.push({key:"monthEligible",label:"Month eligible sales",numeric:!0,cell:i=>h(i.monthEligible),sort:i=>i.monthEligible}),c.push({key:"salesGoal",label:"Sales goal",tip:`Eligible sales for ${D(t,!0)} against the monthly sales goal.`,cell:i=>J(i.salesStatus),sort:i=>Mt[i.salesStatus]}),Dt(e)&&c.push({key:"commissionGoal",label:"Commission goal",tip:`Eligible commission for ${D(t,!0)} against the monthly commission goal.`,cell:i=>J(i.commissionStatus),sort:i=>Mt[i.commissionStatus]}),c.push({key:"credited",label:"Credited sales",numeric:!0,cell:i=>h(i.credited),sort:i=>i.credited},{key:"orders",label:"Orders",numeric:!0,cell:i=>C(i.orders),sort:i=>i.orders},{key:"aov",label:"Average order",numeric:!0,cell:i=>i.orders?h(i.credited/i.orders):"",sort:i=>i.orders?i.credited/i.orders:0},{key:"bottles",label:"Bottles",numeric:!0,cell:i=>C(i.bottles),sort:i=>i.bottles},{key:"signups",label:"Signups",numeric:!0,cell:i=>C(i.signups),sort:i=>i.signups},{key:"refunds",label:"Refunds",numeric:!0,cell:i=>i.refunds?h(i.refunds):"",sort:i=>i.refunds},{key:"trend",label:"Trend",tip:`Trend lines are scaled to each associate's own best month, so compare shape, not height. ${a} ${a===1?"associate":"associates"} had activity.`,cell:i=>ys(i.trend,s.indexOf(t))}),o.length?r("div",null,G(e,"teamTable"),r("div",{class:"card",style:"padding:0"},He(c,o,{sortKey:e.teamSort.key,sortDir:e.teamSort.dir,onSort:n.sortTeam,caption:"Associates"}))):r("div",null,G(e,"teamTable"),k("No associate has credited sales or commission lines in this pay period."))},Ss=e=>{const n=e.data.sources.length>0&&e.data.sources.every(t=>S(t.visits)===0);return r("div",null,G(e,"teamMissing"),n?k("No visits, guests or conversion: this winery has no reservations synced."):null,k("Hours worked aren't in Commerce7, so the page can't show sales per hour."))};function $s(e,n,t,s){const o=W(e.saved,"sales",n.key);if(o.value===null)return null;const a=o.value,c=Math.max(0,-t),i=Math.max(a,Math.max(0,t))+c||1,l=c/i*100,m=Math.abs(t)/i*100,d=t<0?l-m:l,u=l+a/i*100,y=a>=t,b=o.custom?"Custom sales goal":le(e.period)?"Sales goal":`${D(T(e),!0)} sales goal`,p=`${b} ${se(a)}`,_=s==="met"?"status-met":s==="behind"?"status-behind":"";return r("div",{class:"goalbar",title:`${b}: eligible sales for ${D(T(e),!0)} (${h(t)}) against the ${h(a)} sales goal.`},r("div",{class:"goalbar-track"},c?r("span",{class:"goalbar-zero",style:`left:${l}%`}):null,r("span",{class:`goalbar-fill ${_}`,style:`left:${d}%;width:${m}%`}),y?null:r("span",{class:"goalbar-tick",style:`left:${u}%`})),r("span",{class:`goalbar-label${y?" end":""}`,style:y?"":`left:${u}%`},p),t<0?r("div",{class:"caption"},`${h(t)} after refunds`):null)}function Cs(e,n,t){const s=e.saved.associateGoals[t.key],o=e.saved.associateCommissionGoals[t.key],a=(s!=null?s:null)!==null||(o!=null?o:null)!==null,c=(m,d)=>m!=null?`${h(m)} custom`:d!==null?`${h(d)} team`:"No team goal",i=r("input",{type:"text",inputmode:"decimal",id:"associate-sales-goal","data-fid":"associate-sales-goal",placeholder:c(s,e.saved.teamGoal),"aria-label":"Monthly sales goal"}),l=r("input",{type:"text",inputmode:"decimal",id:"associate-commission-goal","data-fid":"associate-commission-goal",placeholder:c(o,e.saved.teamCommissionGoal),"aria-label":"Monthly commission goal"});return Ze(a?"Custom goal · Edit":"Edit goal",e.openDisclosures.has(`goal-${t.key}`),m=>n.toggleDisclosure(`goal-${t.key}`,m),k(`Custom goals apply to ${t.name} only.`),r("div",{class:"goal-row"},r("label",{for:"associate-sales-goal"},"Monthly sales goal"),i,(s!=null?s:null)!==null?r("button",{type:"button",class:"button-quiet",onclick:()=>n.setGoal(`sales:${t.key}`,null)},"Use team goal"):null),Oe(e,`sales:${t.key}`),r("div",{class:"goal-row"},r("label",{for:"associate-commission-goal"},"Monthly commission goal"),l,(o!=null?o:null)!==null?r("button",{type:"button",class:"button-quiet",onclick:()=>n.setGoal(`commission:${t.key}`,null)},"Use team goal"):null),Oe(e,`commission:${t.key}`),r("div",{class:"goal-row"},r("button",{type:"button",class:"button",onclick:()=>{const m=De(i.value),d=De(l.value);m!==null&&n.setGoal(`sales:${t.key}`,m),d!==null&&n.setGoal(`commission:${t.key}`,d)}},"Set"),Lt(e)?r("button",{type:"button",class:"button-quiet",onclick:n.restoreGoals},"Restore goals set in chat"):null))}const Ts=(e,n)=>{const t=e.associate;if(!t)return null;const s=j(e.data,t.key,e.period),o=te(e.data,t.key,T(e)),a=be(e.data,t.key,T(e)),c=W(e.saved,"sales",t.key),i=W(e.saved,"commission",t.key),l=Z(o.eligible_sales,c.value,T(e),e.today),m=Z(o.eligible_commission,i.value,T(e),e.today),d=le(e.period),u=s.eligible_lines===0&&s.eligible_sales===0,y=d&&l==="met"?" status-met":d&&l==="behind"?" status-behind":"",b=wt(e.options.settings.rules,t),p=b.length?b.map(v=>`${at(v.rateKind,v.rate)} on ${Bn(v)}`).join(", "):"No rate earns",_=r("div",{class:"card"},ze(`Eligible sales · ${F(e.period)}`),u?r("p",{class:"verdict"},`${t.name}'s first commissionable sale in ${F(e.period)} will show here.`):[r("div",{class:`hero-value${y}`},h(s.eligible_sales)),r("p",{class:"verdict"},"Eligible commission is ",r("span",{class:"amount"},h(s.eligible_commission)),".")],r("div",{class:"pills"},J(l,"Sales goal"),i.value!==null?J(m,"Commission goal",i.custom):null),$s(e,t,o.eligible_sales,l),r("div",{style:"margin-top:8px"},Cs(e,n,t))),z=[L("Total attributed sales",h(a.credited_sales),d?void 0:`Credited sales in ${D(T(e),!0)}`),L("Pending sales",h(s.pending_sales)),L("Pending commission",h(s.pending_commission)),L("Excluded",h(s.excluded_sales)),(()=>{var N;const v=L("Rate",p);return(N=v.querySelector(".figure-value"))==null||N.classList.add("figure-text"),v})(),s.refunds?L("Refunds",h(s.refunds)):null];return r("div",null,_,r("div",{class:"grid grid-3",style:"margin-top:12px"},z))},Ns=e=>{const n=e.associate;if(!n)return null;const t=j(e.data,n.key,e.period),s=e.period.end.slice(0,4),o=Array.from({length:Number(T(e).slice(5,7))},(l,m)=>`${s}-${String(m+1).padStart(2,"0")}`),a=o.every(l=>e.data.summary.some(m=>m.grain==="month"&&String(m.period_start).startsWith(l))),c=o.reduce((l,m)=>l+te(e.data,n.key,m).pending_commission,0),i=ie(e.period.end,e.options.settings.returnWindowDays);return r("div",null,G(e,"associatePayout"),r("div",{class:"card"},r("div",{class:"grid grid-2"},L("Eligible so far",h(t.eligible_commission)),L("Could still be added",h(t.pending_commission),"When pending lines pass the sale rules"),L("Most this pay period could reach",h(t.eligible_commission+t.pending_commission)),L("Pending across the year",a?h(c):"—",a?void 0:"Needs the New Vintage connector")),k(`Payout timing: ${e.options.plan.payoutTiming}. No pay date is set.`),e.today<i?k(`Refunds before ${pe(i)} can still lower this.`):null))},As=e=>{const n=e.associate;if(!n)return null;const t=T(e).slice(0,4),s=Ke(T(e)).filter(a=>e.data.summary.some(c=>c.grain==="month"&&String(c.period_start).startsWith(a))||Ee(e.data,[a]).length);if(s.length<2)return r("div",null,G(e,"associateCharts"),k(e.live?"Trends need more than one month.":"Trends need the New Vintage connector."));const o=a=>s.map(c=>({label:D(c)+(c.startsWith(t)?"":` ${c.slice(2,4)}`),value:a(c),selected:c===T(e)}));return r("div",null,G(e,"associateCharts"),r("div",{class:"grid grid-2"},me("Eligible sales",o(a=>te(e.data,n.key,a).eligible_sales)),me("Credited sales",o(a=>be(e.data,n.key,a).credited_sales))))},Ms=e=>{const n=e.associate;if(!n)return null;const t=T(e),s=t.slice(0,4),a=Array.from({length:Number(t.slice(5,7))},(u,y)=>`${s}-${String(y+1).padStart(2,"0")}`).filter(u=>e.data.summary.some(y=>y.grain==="month"&&String(y.period_start).startsWith(u))||Ee(e.data,[u]).length).map(u=>{const y=te(e.data,n.key,u),b=be(e.data,n.key,u);return{month:u,commission:y.eligible_commission,eligible:y.eligible_sales,sales:Z(y.eligible_sales,W(e.saved,"sales",n.key).value,u,e.today),commissionStatus:Z(y.eligible_commission,W(e.saved,"commission",n.key).value,u,e.today),credited:b.credited_sales,orders:b.orders,bottles:b.bottles,signups:b.club_signups,cancellations:b.club_cancellations}}),c=Dt(e),i=[{key:"month",label:"Month",cell:u=>D(u.month,!0)},{key:"commission",label:"Eligible commission",numeric:!0,cell:u=>h(u.commission)},{key:"eligible",label:"Eligible sales",numeric:!0,cell:u=>h(u.eligible)},{key:"sales",label:"Sales goal",tip:"Eligible sales for the month against the monthly sales goal.",cell:u=>J(u.sales)}];c&&i.push({key:"commissionGoal",label:"Commission goal",tip:"Eligible commission for the month against the monthly commission goal.",cell:u=>J(u.commissionStatus)}),i.push({key:"credited",label:"Credited sales",numeric:!0,cell:u=>h(u.credited)},{key:"orders",label:"Orders",numeric:!0,cell:u=>C(u.orders)},{key:"aov",label:"Average order",numeric:!0,cell:u=>u.orders?h(u.credited/u.orders):""},{key:"bottles",label:"Bottles",numeric:!0,cell:u=>C(u.bottles)},{key:"signups",label:"Signups",numeric:!0,cell:u=>C(u.signups)},{key:"cancellations",label:"Cancellations",numeric:!0,cell:u=>C(u.cancellations)});const l=u=>a.reduce((y,b)=>y+u(b),0),m=l(u=>u.orders),d=["Year to date",h(l(u=>u.commission)),h(l(u=>u.eligible)),"",...c?[""]:[],h(l(u=>u.credited)),C(m),m?h(l(u=>u.credited)/m):"",C(l(u=>u.bottles)),C(l(u=>u.signups)),C(l(u=>u.cancellations))];return a.length?r("div",null,G(e,"associateMonths"),r("div",{class:"card",style:"padding:0"},He(i,a,{footer:d,caption:"By month"})),a.length<Number(t.slice(5,7))&&!e.live?k("Earlier months need the New Vintage connector."):null):r("div",null,G(e,"associateMonths"),k("No months are loaded for this associate."))};function xe(e,n,t){var a,c;const s=Hn(e,n),o=String((c=(a=e[t])!=null?a:e[n])!=null?c:"");return s?r("a",{href:s,target:"_blank",rel:"noopener noreferrer"},o," ",Le("external-link",12)):o}function Rt(e){return r("dl",{class:"trace-grid"},e.filter(([,n])=>n!=null&&n!=="").map(([n,t])=>r("div",null,r("dt",null,n),r("dd",null,t instanceof Node?t:String(t)))))}function It(e,n,t,s,o,a,c){var l;const i=[];for(const m of s){const d=`${t}-${String((l=m.line_id)!=null?l:m.order_id)}`,u=e.openRows.has(d),y=()=>n.toggleRow(d);i.push(r("tr",{class:"line",tabindex:0,"data-fid":d,"aria-expanded":u?"true":"false",onclick:b=>{b.target.closest("a")||y()},onkeydown:b=>{const p=b.key;(p==="Enter"||p===" ")&&(b.preventDefault(),y())}},o(m).map((b,p)=>r("td",{class:p>=3?"num":null},b)))),u&&i.push(r("tr",{class:"trace"},r("td",{colspan:7},a(m))))}return i}function Pt(e,n){return r("div",{class:"table-wrap"},r("table",null,r("thead",null,r("tr",null,e.map((t,s)=>r("th",{scope:"col",class:s>=3?"num":null},t)))),r("tbody",null,n)))}function Es(e,n){var t;return e.lines.status==="loading"?`${n}'s lines are loading.`:e.lines.status==="offline"?"Line detail needs the New Vintage connector.":e.lines.status==="error"?(t=e.lines.message)!=null?t:"Line detail couldn't load.":null}const Gs=(e,n)=>{const t=e.associate;if(!t)return null;const s=Es(e,t.name);if(s)return r("div",null,G(e,"associateLines"),k(s));const o=e.options.settings.timeZone,a=xt(e.lines.rows),c=e.showAllLines?a.eligible:a.eligible.slice(0,10),i=c.reduce((p,_)=>p+S(_.net_dollars),0),l=a.eligible.slice(c.length),m=l.reduce((p,_)=>p+S(_.net_dollars),0),d=j(e.data,t.key,e.period).eligible_sales,u=[...c,...a.unpriced],y=It(e,n,"line",u,p=>{var _,z,v,N,M;return[O(p.order_date,o),xe(p,"order_id","order_number"),p.bucket==="unpriced"?r("span",null,String((z=(_=p.product)!=null?_:p.product_title)!=null?z:"")," ",r("span",{class:"unpriced"},"Could not price")):String((N=(v=p.product)!=null?v:p.product_title)!=null?N:""),C((M=p.net_quantity)!=null?M:p.quantity),h(p.net_dollars),at(p.rate_kind,p.rate),h(p.rule_commission)]},p=>Rt([["Order id",p.order_id],["Order",xe(p,"order_id","order_number")],["Order date",O(p.order_date,o)],["Fulfilled",O(p.fulfilled_date,o)],["Delivery",p.delivery_method],["SKU",p.sku],["Product id",p.product_id],["Item type",p.item_type],["Dollar amount",H(p.dollar_amount)],["Taken off by refunds",S(p.dollars_taken)?H(p.dollars_taken):null],["Fulfillment status",p.fulfillment_status],["Payment status",p.payment_status],["Purchase type",p.purchase_type],["Rule",p.rule_label],["Commission",H(p.rule_commission)]])),b=i+m;return r("div",null,G(e,"associateLines"),a.eligible.length||a.unpriced.length?r("div",{class:"card",style:"padding:0"},Pt(["Date","Order","Product","Qty","Sales","Rate","Commission"],y)):k(`No eligible lines for ${t.name} in ${F(e.period)}.`),!e.showAllLines&&l.length?r("button",{type:"button",class:"button-quiet",style:"margin-top:12px",onclick:n.showAllLines},`Show all ${a.eligible.length} lines`):null,k(l.length?`Listed lines ${h(i)} plus ${l.length} other eligible lines ${h(m)} equal eligible sales ${h(b)}.`:`Listed lines equal eligible sales ${h(b)}.`,"status-line"),Math.abs(b-d)>.05?k(`These lines don't match the summary's eligible sales of ${h(d)}. The data may have changed since the summary loaded.`,"status-line problem"):null)},Ls=(e,n)=>{const t=e.associate;if(!t||e.lines.status!=="ready")return null;const s=e.options.settings.timeZone,o=xt(e.lines.rows),a=o.refundsListed.reduce((d,u)=>d+S(u.dollar_amount),0),c=o.refundsListed.reduce((d,u)=>d+(u.original_line_loaded===!0&&u.refund_in_window===!0?Math.abs(S(u.dollar_amount)):0),0),i=o.refundsNotListed.reduce((d,u)=>d+S(u.dollar_amount),0),l=j(e.data,t.key,e.period).refunds,m=It(e,n,"refund",o.refundsListed,d=>{var u,y;return[O(d.order_date,s),O(d.original_order_date,s),xe(d,"linked_order_id","linked_order_number"),String((y=(u=d.product)!=null?u:d.product_title)!=null?y:""),h(d.dollar_amount)]},d=>{var u;return Rt([["Refund order",xe(d,"order_id","order_number")],["Refund date",O(d.order_date,s)],["Original order",xe(d,"linked_order_id","linked_order_number")],["Original order date",O(d.original_order_date,s)],["Delivery",d.original_delivery_method],["Original fulfilled",O(d.original_fulfilled_date,s)],["Item",(u=d.product)!=null?u:d.product_title],["Item type",d.item_type],["Quantity refunded",C(Math.abs(S(d.quantity)))],["Refund",H(d.dollar_amount)],["Original line amount",d.original_line_loaded===!0?H(d.original_line_dollars):"Before this year's lines"],["Taken off",d.original_line_loaded===!0?H(d.original_line_taken):H(0)],["Left on the line",d.original_line_loaded===!0?H(d.original_line_left):null]])});return r("div",null,G(e,"associateRefunds"),k(`A refund within the ${e.options.settings.returnWindowDays}-day return window lowers the commission of the pay period its original sale is in. A later refund changes nothing already paid. This list is for reconciling payouts.`),o.refundsListed.length?r("div",{class:"card",style:"padding:0;margin-top:12px"},Pt(["Refund date","Order date","Original order","Product","Refunds"],m)):k(`No refunds are listed for ${t.name} in this pay period.`),k([`Listed refunds ${h(a)}, of which ${h(c)} came off original lines.`,o.refundsNotListed.length?`${o.refundsNotListed.length} refund lines (${h(i)}) are on orders not credited to ${t.name} and aren't listed.`:"",`Refunds figure: ${h(l)}.`].filter(Boolean).join(" "),"status-line"))};function zs(e,n){var l,m;const t=e.options.plan,s=(l=t.assumed)!=null?l:[],o=e.associate,a=o?wt(e.options.settings.rules,o):e.options.settings.rules.filter(d=>d.rate>0&&d.associateAccountId===null&&d.associateName===null),c=Kn(a),i=o?W(e.saved,"sales",o.key).value:e.saved.teamGoal;return r("footer",{class:"section"},G(e,"rulesFooter"),s.length?r("button",{type:"button",class:"assumed","data-fid":"assumed",onclick:n.toggleAssumed},`${s.length} ${s.length===1?"item is":"items are"} assumed — not confirmed.`):null,r("ul",null,t.rules.map(d=>r("li",{class:s.includes(d)&&e.highlightAssumed?"highlight":null},d)),s.filter(d=>!t.rules.includes(d)).map(d=>r("li",{class:e.highlightAssumed?"highlight":null},`Assumed — not confirmed: ${d}`)),((m=t.notCalculated)!=null?m:[]).map(d=>r("li",null,`Not calculated: ${d}.`))),k(`Payout timing: ${t.payoutTiming}. No pay date is set.`),i!==null?k(c!==null?`Goal payout: at the ${h(i)} sales goal, ${C(c)}% pays ${h(i*c/100)}.`:"Goal payout: the mix of rules decides it, so it isn't shown."):null,t.policyFile?k(`Rules from ${t.policyFile}.`):null,e.syncedAt?k(`New Vintage last received orders ${e.syncedAt}.`):null,e.mathUpdated!==null?k(`Commission math updated to version ${e.mathUpdated}.`):null,e.needsUpdate?k("This dashboard needs an update. Ask Claude in this chat to update it.","status-line problem"):null,e.storageNote?k(e.storageNote):null,k("Rule, pay period, sale-counting and return-window changes change the queries: ask Claude in this chat."))}function Ds(e,n){var t,s,o;return Ze((o=(s=(t=e.options.customize)==null?void 0:t.labels)==null?void 0:s.howTo)!=null?o:Gt.howTo,e.openDisclosures.has("howto"),a=>n.toggleDisclosure("howto",a),r("ul",null,r("li",null,"Credited sales are paid orders with an associate on them. Eligible sales are the lines that passed the sale rules and earn a rate above zero; commission is paid on those."),r("li",null,"Pending lines haven't passed the fulfillment or payment rule yet. Excluded lines never earn, including lines that pay 0 percent, so they aren't in eligible sales."),r("li",null,`Refunds are listed so a payout can be reconciled. A refund lowers a pay period's commission only when its original sale is in that period and it comes within the ${e.options.settings.returnWindowDays}-day return window.`),r("li",null,"The rate is applied to each line after refunds are taken off it."),r("li",null,"Goals are monthly. The sales goal is measured on eligible sales, and the commission goal, when one is set, on eligible commission.")))}const Os={teamHeroes:vs,teamTiles:ws,teamCharts:xs,teamSources:_s,teamTable:ks,teamMissing:Ss,associateSummary:Ts,associatePayout:Ns,associateCharts:As,associateMonths:Ms,associateLines:Gs,associateRefunds:Ls},Rs=900*1e3,Vt="dash-howto";function qt(e,n){if(!e)return"";switch(e.kind){case"unavailable":return"Live numbers need the New Vintage connector with access to this winery.";case"approval":return"Live numbers need your permission to use the New Vintage connector.";case"reconnect":return"Reconnect New Vintage in claude.ai Settings → Connectors.";case"temporary":return`Couldn't refresh · showing ${n}`;case"needs_update":return"This dashboard needs an update. Ask Claude in this chat to update it.";case"not_reconciled":return`The refresh did not reconcile, so the page kept the data from ${n}.`;case"tool":return e.message}}function Is(e,n){var i,l,m,d,u,y;const t=n==="team"?[...fs]:[...ps],s=((i=e.cards)!=null?i:[]).filter(b=>b.view===n||b.view==="both");for(const b of s){const p=b.after?t.indexOf(b.after):-1;p>=0?t.splice(p+1,0,b.id):t.push(b.id)}const a=((d=(m=(l=e.customize)==null?void 0:l.order)==null?void 0:m[n])!=null?d:[]).filter(b=>t.includes(b));for(const b of t)a.includes(b)||a.push(b);const c=new Set((y=(u=e.customize)==null?void 0:u.hide)!=null?y:[]);return a.filter(b=>!c.has(b))}function Ps(e,n){var Xt,en,tn,nn,sn,on,rn,an,ln,cn,dn,un,mn,fn;const t=(Xt=n.now)!=null?Xt:(()=>new Date),s=n.settings.timeZone,o=n.settings.payPeriod,a=()=>$n(t(),s),c=()=>Ce(a(),o),i=`${Number(a().slice(0,4))-1}-01-01`,l=Ct(n.customize,n.cards),m=Xn(n.storage),d=m.mode,u=_t(n.plan);let y={summary:n.snapshot.summary,performance:n.snapshot.performance,sources:n.snapshot.sources},b="team",p=null,_=c(),z=ue(n.plan),v={mode:"snapshot",refreshedAt:null,failure:null},N=n.snapshot.lastSyncedAt,M=null,P=null,Ft=!1,Ut=null,Je=!1,jt=null,Re=!1,Qe=!1,Ie={key:"commission",dir:"desc"};const Pe=new Set,Ve=new Set,R=new Map;let Xe=null,qe=!1;e.innerHTML="";const qs=[(nn=(tn=(en=n.customize)==null?void 0:en.fonts)==null?void 0:tn.display)!=null?nn:"Newsreader",(rn=(on=(sn=n.customize)==null?void 0:sn.fonts)==null?void 0:on.body)!=null?rn:"Be Vietnam Pro"],Wt=r("link",{rel:"stylesheet",href:ds(qs.filter(f=>/^[A-Za-z0-9 ]{1,40}$/.test(f)))}),et={};(ln=(an=n.customize)==null?void 0:an.fonts)!=null&&ln.display&&(et["font-display"]=`'${n.customize.fonts.display}', Georgia, serif`),(dn=(cn=n.customize)==null?void 0:cn.fonts)!=null&&dn.body&&(et["font-body"]=`'${n.customize.fonts.body}', system-ui, sans-serif`);const Bt=r("style",null,us({...et,...(mn=(un=n.customize)==null?void 0:un.theme)!=null?mn:{}},(fn=n.customize)==null?void 0:fn.themeDark)+ms);document.head.append(Wt,Bt);const B=r("div",{class:"nvcd"});e.append(B);const K=typeof ResizeObserver=="function"?new ResizeObserver(()=>tt()):null,Kt=()=>{tt(),Ye(B)};window.addEventListener("resize",Kt);function tt(){const f=B.querySelector(".controlbar");f&&B.style.setProperty("--bar-h",`${f.offsetHeight}px`)}function Ht(){return p?`${p}|${_.start}`:null}function nt(){if(!p)return null;const f=Me(y,_,Te(_)).find(g=>g.key===p);return f!=null?f:{key:p,name:p,accountId:null}}function Yt(){const f=Ht(),g=f&&R.get(f)||{status:M?"loading":"offline",rows:[]};return{options:n,data:y,period:_,today:a(),live:v.mode==="live",saved:z,baseline:u,associate:nt(),lines:g,openRows:Pe,openDisclosures:Ve,showAllLines:Re,teamSort:Ie,highlightAssumed:Qe,storageNote:d==="browser"?"Goals are saved only in this browser.":d==="none"?"Changes won't be saved.":null,mathUpdated:Ut,needsUpdate:Je,syncedAt:N?oe(N,s):null}}const Fe={selectAssociate:f=>{var g;b=f?"associate":"team",p=f,Re=!1,E(),(g=window.scrollTo)==null||g.call(window,0,0),st()},setGoal:(f,g)=>{var w;z=rs(z,f,g,(w=n.viewerName)!=null?w:null,t().toISOString()),E(),Zt()},restoreGoals:()=>{z={...ue(n.plan),planRevision:z.planRevision},E(),Zt()},sortTeam:f=>{Ie=Ie.key===f?{key:f,dir:Ie.dir==="desc"?"asc":"desc"}:{key:f,dir:f==="associate"||f==="salesGoal"||f==="commissionGoal"?"asc":"desc"},E()},toggleRow:f=>{Pe.has(f)?Pe.delete(f):Pe.add(f),E()},toggleDisclosure:(f,g)=>{g?Ve.add(f):Ve.delete(f),f==="howto"&&ss(m.adapter,Vt,g?"open":"closed")},showAllLines:()=>{Re=!0,E()},toggleAssumed:()=>{Qe=!Qe,E()}};async function Zt(){await ts(m.adapter,n.tenantId,z)}function Fs(){var $,x,A;const f=v.refreshedAt?oe(v.refreshedAt,s):oe(n.snapshot.loadedAt,s),g=v.mode==="live"&&v.refreshedAt?`Live · refreshed ${oe(v.refreshedAt,s)}`:v.mode==="loading"?`Snapshot from ${O(n.snapshot.loadedAt,s)} · refreshing`:`Snapshot from ${O(n.snapshot.loadedAt,s)}`,w=qt(v.failure,f);return r("header",null,r("h1",null,(x=($=n.customize)==null?void 0:$.title)!=null?x:"Sales Commission Dashboard"),r("div",{class:"meta"},`${n.wineryName} · Source: New Vintage orders${N?` · Last synced ${oe(N,s)}`:""}`),r("span",{class:"data-label"},g),w?r("p",{class:"status-line problem"},w):null,((A=v.failure)==null?void 0:A.kind)==="approval"?r("button",{type:"button",class:"button",style:"margin-top:8px",onclick:()=>void je()},"Allow live data"):null)}function Us(){var I,ne;const f=Me(y,_,Te(_)),g=r("select",{class:"view-select","aria-label":"View","data-fid":"view-select"},r("option",{value:""},"Whole team"),f.length?r("optgroup",{label:"Associates, by commission"},f.map(_e=>r("option",{value:_e.key},_e.name))):null);g.value=b==="associate"&&p?p:"",b==="associate"&&p&&g.value!==p&&(g.append(r("option",{value:p},(ne=(I=nt())==null?void 0:I.name)!=null?ne:p)),g.value=p),g.addEventListener("change",()=>Fe.selectAssociate(g.value||null));const w=Mn(_,o),$=w.start>=i&&(ht(y,w)||M!==null),x=_.start===c().start,A=a()<_.end;return r("div",{class:"controlbar"},r("div",{class:"controlbar-inner"},g,r("div",{class:"period"},r("button",{type:"button",class:"icon-button","aria-label":"Previous pay period","data-fid":"prev",disabled:!$,onclick:()=>Qt(w)},Le("chevron-left")),r("span",{class:"period-long"},F(_),A?" · open":""),r("span",{class:"period-short"},Gn(_),A?" · open":""),r("button",{type:"button",class:"icon-button","aria-label":"Next pay period","data-fid":"next",disabled:x,onclick:()=>Qt(En(_,o))},Le("chevron-right")))))}function js(f){const g=Yt();return{view:f,period:{start:_.start,end:_.end,label:F(_),goalMonth:Te(_),open:g.today<_.end},associate:g.associate?{key:g.associate.key,name:g.associate.name}:null,timeZone:s,live:v.mode==="live",data:{summary:y.summary,performance:y.performance,sources:y.sources,lines:g.lines.status==="ready"?g.lines.rows:null},ui:{h:r,money:h,moneyShort:se,number:C,figure:L,note:w=>k(w),barChart:me,table:(w,$)=>He(w.map(x=>({key:x.key,label:x.label,numeric:x.money,cell:A=>{var I;return x.money?h(A[x.key]):String((I=A[x.key])!=null?I:"")}})),$)},runSql:async w=>{if(!M)throw new Error("This card needs the New Vintage connector.");return(await de(M,w,"Loading a custom card on the commission dashboard.")).rows}}}function Ws(f,g){const w=r("div",null,k("Loading…")),$=r("section",{class:"section custom-card","data-card":f.id},r("h2",null,f.title),r("p",{class:"card-purpose"},f.purpose),r("div",{class:"card"},w));return Promise.resolve().then(()=>f.render(js(g))).then(x=>{w.replaceChildren(x==null?k("Nothing to show yet."):typeof x=="string"?k(x):x),Ye($)}).catch(x=>w.replaceChildren(k(`This card couldn't load: ${x instanceof Error?x.message:String(x)}`,"status-line problem"))),$}function E(){var ne,_e,pn,gn,hn,bn;if(qe)return;const f=(_e=(ne=document.activeElement)==null?void 0:ne.getAttribute)==null?void 0:_e.call(ne,"data-fid"),g=Yt(),w=r("main",{class:"page page-head"},Fs(),r("div",{class:"howto"},Ds(g,Fe))),$=r("div",{class:"page"}),x=b,A=new Map(((pn=n.cards)!=null?pn:[]).map(fe=>[fe.id,fe]));for(const fe of Is(n,x)){const yn=A.get(fe);if(yn){$.append(Ws(yn,x));continue}const vn=Os[fe],wn=vn?vn(g,Fe):null;wn&&$.append(r("section",{class:"section","data-section":fe},wn))}(hn=(gn=n.customize)==null?void 0:gn.hide)!=null&&hn.includes("rulesFooter")||$.append(zs(g,Fe)),B.replaceChildren(w,Us(),$),f&&((bn=B.querySelector(`[data-fid="${CSS.escape(f)}"]`))==null||bn.focus()),K==null||K.disconnect();const I=B.querySelector(".controlbar");I&&(K==null||K.observe(I)),tt(),Ye(B)}function Ue(f){return{...n.settings,...f}}function Bs(f){const g=ee(f).slice(0,4),w=c(),$=ee(w).slice(0,4)===g?w.end:Ce(`${g}-12-31`,o).end;return{windowStart:`${g}-01-01`,windowEnd:$,year:g}}async function Jt(f){if(!M||!P)return;const g=Bs(f),w=ee({start:g.windowStart,end:g.windowEnd}).slice(0,7),$=await Pn(M,P,{...Ue(g),reportMonths:{first:`${g.year}-01`,last:w}}),x={windowStart:`${Number(g.year)-1}-01-01`,windowEnd:g.windowEnd},A=await ft(M,P,ce.performance,Ue(x)),I=await ft(M,P,ce.sources,Ue(x));if(!qn(A,I))throw new Error("not_reconciled");y={summary:$,performance:A,sources:I},jt=g.year}async function je(){var f,g;if(!qe){v={...v,mode:v.mode==="live"?"live":"loading",failure:null},E();try{if(!M){const w=(g=n.callTool)!=null?g:await Dn((f=n.connectorName)!=null?f:"New Vintage");if(!w){v={mode:"snapshot",refreshedAt:null,failure:{kind:"unavailable"}};for(const[$,x]of R)x.status==="loading"&&R.set($,{status:"offline",rows:[]});E();return}M=Rn(w,n.tenantId)}P=await In(M,Ft?null:l),Ft=!0,Ut=P.version>n.guideVersion?P.version:null;try{const w=await M.call("discover_tenant_data_sources",{context:"Checking when New Vintage last synced this winery's orders for the commission dashboard."}),x=(Array.isArray(w.connectedSources)?w.connectedSources:[]).map(A=>A.lastSyncAt).filter(A=>typeof A=="string").sort();x.length&&(N=x[x.length-1])}catch{}await Jt(_),R.clear(),Je=!1,v={mode:"live",refreshedAt:t().toISOString(),failure:null},E(),st()}catch(w){const $=w instanceof Error&&w.message==="not_reconciled"?{kind:"not_reconciled"}:Ne(w);if(Je=$.kind==="needs_update",v={mode:v.refreshedAt?"live":"snapshot",refreshedAt:v.refreshedAt,failure:$},!M)for(const[x,A]of R)A.status==="loading"&&R.set(x,{status:"offline",rows:[]});E()}}}async function st(){var w,$;const f=Ht(),g=nt();if(!(!f||!g||((w=R.get(f))==null?void 0:w.status)==="ready")){if(!M||!P){v.mode!=="loading"&&R.set(f,{status:"offline",rows:[]}),E();return}R.set(f,{status:"loading",rows:[]}),E();try{const x=await Vn(M,P,{...Ue(Ln(_)),focus:{associateAccountId:g.accountId,associateName:g.accountId?null:g.name,periodStart:_.start}});R.set(f,{status:"ready",rows:x})}catch(x){const A=Ne(x);R.set(f,{status:"error",rows:[],message:qt(A,oe(($=v.refreshedAt)!=null?$:n.snapshot.loadedAt,s))})}E()}}function Qt(f){_=f,Re=!1,E(),M&&P&&!ht(y,f)&&ee(f).slice(0,4)!==jt&&Jt(f).then(()=>E()).catch(g=>{v={...v,failure:Ne(g)},E()}),st()}return E(),(async()=>(z=await es(m.adapter,n.tenantId,n.plan),await ns(m.adapter,Vt)==="open"&&Ve.add("howto"),E(),await je(),qe||(Xe=setInterval(()=>void je(),Rs))))(),{refresh:je,destroy:()=>{qe=!0,Xe&&clearInterval(Xe),K==null||K.disconnect(),window.removeEventListener("resize",Kt),Bt.remove(),Wt.remove(),B.remove()},state:()=>({view:b,associate:p,period:_,live:v.mode})}}function Vs(e,n){const t=typeof e=="string"?document.querySelector(e):e;if(!t)throw new Error(`NVCommissionDashboard: no element matches ${String(e)}`);return Ps(t,n)}return Q.SUPPORTED_TIME_ZONES=it,Q.VERSION=$t,Q.fillCommissionQuery=dt,Q.mount=Vs,Q.pageSetup=Ct,Object.defineProperty(Q,Symbol.toStringTag,{value:"Module"}),Q})({});
157
+ @media (prefers-reduced-motion: reduce){.nvcd *{transition-duration:0ms!important;animation:none!important}.nvcd .progress::after{left:0;width:100%;opacity:.5}}
158
+ `,vs=["teamHeroes","teamTiles","teamCharts","teamSources","teamTable","teamMissing"],ws=["associateSummary","associatePayout","associateCharts","associateMonths","associateLines","associateRefunds"];function K(e,n,t){const s=n==="sales"?e.associateGoals[t]:e.associateCommissionGoals[t];return s!=null?{value:s,custom:!0}:{value:n==="sales"?e.teamGoal:e.teamCommissionGoal,custom:!1}}function te(e,n,t,s){if(n==null)return"none";if(e>=n)return"met";const r=s.slice(0,7);if(r>t)return"behind";if(r<t)return"on_pace";const a=n*Number(s.slice(8,10))/Dn(t);return e>=a?"on_pace":"behind"}const Pt={met:"Met",on_pace:"On pace",behind:"Behind pace",none:"No goal"};function Vt(e,n){return n?e==="none"?`No ${n.toLowerCase()}`:`${n} ${Pt[e].toLowerCase()}`:Pt[e]}const qt={met:0,on_pace:1,behind:2,none:3};function o(e,n=null,...t){const s=document.createElement(e);for(const[r,a]of Object.entries(n!=null?n:{}))a==null||a===!1||(typeof a=="function"?s.addEventListener(r.replace(/^on/,"").toLowerCase(),a):a===!0?s.setAttribute(r,""):s.setAttribute(r,String(a)));return Ft(s,t),s}function Ft(e,n){for(const t of n)t==null||t===!1||(Array.isArray(t)?Ft(e,t):e.append(t instanceof Node?t:String(t)))}const xs="http://www.w3.org/2000/svg";function Se(e,n={},...t){const s=document.createElementNS(xs,e);for(const[r,a]of Object.entries(n))s.setAttribute(r,String(a));return s.append(...t),s}const ks={"chevron-left":"M15 18l-6-6 6-6","chevron-right":"M9 18l6-6-6-6","chevron-down":"M6 9l6 6 6-6","external-link":"M15 3h6v6M10 14L21 3M18 13v6a2 2 0 0 1-2 2H5a2 2 0 0 1-2-2V8a2 2 0 0 1 2-2h6",info:"M12 16v-4M12 8h.01M22 12a10 10 0 1 1-20 0 10 10 0 0 1 20 0z"};function Ie(e,n=16){var t;return Se("svg",{width:n,height:n,viewBox:"0 0 24 24",fill:"none",stroke:"currentColor","stroke-width":2,"stroke-linecap":"round","stroke-linejoin":"round","aria-hidden":"true"},Se("path",{d:(t=ks[e])!=null?t:""}))}function ne(e,n,t=!1){const s=t&&n?Vt(e,`Custom ${n.toLowerCase()}`):Vt(e,n);return o("span",{class:`pill pill-${e}`},s)}function Pe(e,n){return n?o("div",{class:"eyebrow-row"},o("span",{class:"eyebrow"},e),o("span",{class:"eyebrow-period"},n)):o("div",{class:"eyebrow"},e)}function L(e,n,t){return o("div",{class:"figure card"},o("div",{class:"figure-label"},e),o("div",{class:"figure-value"},n),t?o("div",{class:"caption"},t):null)}function _(e,n="note"){return o("p",{class:n},e)}function _s(e,n,t=!1){return o("span",{class:`tip${t?" tip-end":""}`,tabindex:0,"aria-label":`${e}. ${n}`},e,o("span",{class:"tip-body",role:"tooltip"},n))}function ve(e,n,t=le){var m;const s=(m=n.find(c=>c.selected))!=null?m:n[n.length-1],r=o("div",{class:"readout","aria-live":"polite"},s?`${s.label}: ${t(s.value)}`:""),a=Math.max(1,...n.map(c=>Math.abs(c.value))),u=n.map(c=>{const d=`${c.label}: ${t(c.value)}`,b=()=>{r.textContent=d};return o("button",{class:`bar${c.selected?" bar-selected":""}`,type:"button","aria-label":d,title:d,onmouseenter:b,onfocus:b},o("span",{class:"bar-fill",style:`height:${Math.max(2,Math.abs(c.value)/a*100)}%`}))}),i=Math.max(0,n.findIndex(c=>c.selected)),l=n.map((c,d)=>o("span",{class:`bar-label${c.selected?" bar-label-selected":""}${Math.abs(d-i)%2===1?" bar-label-minor":""}`,"aria-hidden":"true"},c.label));return o("figure",{class:"chart card"},o("figcaption",{class:"chart-title"},e),r,o("div",{class:"bars"},u),o("div",{class:"bar-labels"},l))}function $s(e,n){const r=Math.max(1,...e),a=e.length>1?96/(e.length-1):0,u=e.map((l,m)=>`${(m*a).toFixed(1)},${(22-Math.max(0,l)/r*20).toFixed(1)}`),i=[Se("polyline",{points:u.join(" "),fill:"none",stroke:"var(--chart-series-2)","stroke-width":1.5})];if(n>=0&&u[n]){const[l,m]=u[n].split(",");i.push(Se("circle",{cx:l,cy:m,r:2.5,fill:"var(--chart-bar-selected)"}))}return Se("svg",{width:96,height:24,viewBox:"0 0 96 24","aria-hidden":"true",class:"sparkline"},...i)}function ot(e,n,t={}){const s=[...n],r=e.find(l=>l.key===t.sortKey&&l.sort);if(r!=null&&r.sort){const l=t.sortDir==="asc"?1:-1;s.sort((m,c)=>{const d=r.sort(m),b=r.sort(c);return(d<b?-1:d>b?1:0)*l})}const a=o("tr",null,e.map((l,m)=>{const c=l.tip?_s(l.label,l.tip,m===e.length-1):l.label,d=!!(l.sort&&t.onSort),b=(r==null?void 0:r.key)===l.key;return o("th",{scope:"col",class:l.numeric?"num":null,"aria-sort":b?t.sortDir==="asc"?"ascending":"descending":null},d?o("button",{type:"button",class:"sort",onclick:()=>t.onSort(l.key)},c,b?t.sortDir==="asc"?" ↑":" ↓":""):c)})),u=s.map(l=>o("tr",null,e.map(m=>o("td",{class:m.numeric?"num":null},m.cell(l))))),i=t.footer?o("tfoot",null,o("tr",null,t.footer.map((l,m)=>o("td",{class:m>0?"num":null},l)))):null;return o("div",{class:"table-wrap"},o("table",null,t.caption?o("caption",{class:"sr-only"},t.caption):null,o("thead",null,a),o("tbody",null,u),i))}function rt(e){for(const n of Array.from(e.querySelectorAll(".table-wrap"))){n.classList.remove("boxed");const t=n.querySelector("table");t&&t.scrollWidth>n.clientWidth+1&&n.classList.add("boxed")}}function at(e,n,t,...s){const r=o("details",{class:"disclosure",open:n},o("summary",null,Ie("chevron-down",14),e),o("div",{class:"disclosure-body"},s));return r.addEventListener("toggle",()=>t(r.open)),r}const Ut={howTo:"How to read this page",teamHeroes:"",teamTiles:"This month",teamCharts:"Trends",teamSources:"Where sales come from",teamTable:"Associates",teamMissing:"What this page can't show",associateSummary:"",associatePayout:"Upcoming payout",associateCharts:"Months",associateMonths:"By month",associateLines:"Lines",associateRefunds:"Refunds",rulesFooter:"Rules"};function G(e,n){var s,r,a;const t=(a=(r=(s=e.options.customize)==null?void 0:s.labels)==null?void 0:r[n])!=null?a:Ut[n];return t?o("h2",null,t):null}function Ve(e){const n=e.replace(/[$,\s]/g,"");if(!n)return null;const t=Number(n);return Number.isFinite(t)&&t>=0?Math.round(t*100)/100:null}function qe(e,n){const t=ds(e.saved,e.baseline,n);if(!t)return null;const s=F(t.at,e.options.settings.timeZone);return o("div",{class:"changed"},`Changed on this page ${s}${t.by?` by ${t.by}`:""}`)}function jt(e){return e.saved.goalChanges.length>0}const T=e=>Ge(e.period);function Wt(e,n,t){let s=0,r=!1;for(const a of n){const u=K(e.saved,t,a.key).value;u!==null&&(s+=u,r=!0)}return r?s:null}function Bt(e){return e.saved.teamCommissionGoal!==null||Object.values(e.saved.associateCommissionGoals).some(n=>n!=null)}function it(e,n,t){return`${n?Math.round(e/n*100):0}% of the ${le(n)} ${t}`}function Kt(e){const n=e.options.plan.payoutTiming.trim().replace(/\.+$/,""),t=e.options.settings.returnWindowDays;if(/return window/i.test(n)){const s=J(ce(e.period.end,t));return`Commission for ${j(e.period)} is final on ${s}, when the ${t}-day return window closes. Your payroll date isn't tracked here.`}return`Payout timing: ${n}. Your payroll date isn't tracked here.`}const Ss=(e,n)=>{const t=De(e.data,e.period,T(e)),s=t.reduce((y,N)=>y+B(e.data,N.key,e.period).eligible_commission,0),r=t.reduce((y,N)=>y+B(e.data,N.key,e.period).eligible_sales,0),a=t.reduce((y,N)=>y+ue(e.data,N.key,T(e)).eligible_sales,0),u=t.reduce((y,N)=>y+ue(e.data,N.key,T(e)).eligible_commission,0),i=Wt(e,t,"sales"),l=Wt(e,t,"commission"),m=te(a,i,T(e),e.today),c=te(u,l,T(e),e.today),d=ge(e.period),b=o("div",{class:"card"},Pe("Team eligible commission",j(e.period)),o("div",{class:"hero-value"},h(s)),l!==null?o("div",{class:"pills"},o("span",{class:"caption"},`${d?"":`${z(T(e),!0)}: `}${it(u,l,"commission goal")}`),ne(c,"Commission goal")):null),v=o("div",{class:"card"},Pe("Team eligible sales",j(e.period)),o("div",{class:"hero-value"},h(r)),o("div",{class:"pills"},i!==null?o("span",{class:"caption"},d?it(a,i,"sales goal"):`${z(T(e),!0)} eligible sales of ${h(a)} are ${it(a,i,"sales goal")}`):null,ne(m,"Sales goal"))),f=o("input",{type:"text",inputmode:"decimal",id:"team-sales-goal","data-fid":"team-sales-goal",placeholder:e.saved.teamGoal!==null?`${h(e.saved.teamGoal)} now`:"No sales goal","aria-label":"Team monthly sales goal"}),x=o("input",{type:"text",inputmode:"decimal",id:"team-commission-goal","data-fid":"team-commission-goal",placeholder:e.saved.teamCommissionGoal!==null?`${h(e.saved.teamCommissionGoal)} now`:"No commission goal","aria-label":"Team monthly commission goal"}),D=at("Edit team goals",e.openDisclosures.has("team-goals"),y=>n.toggleDisclosure("team-goals",y),_("Team goals are the monthly default for every associate. An associate's custom goal still replaces it."),o("div",{class:"goal-row"},o("label",{for:"team-sales-goal"},"Monthly sales goal"),f,e.saved.teamGoal!==null?o("button",{type:"button",class:"button-quiet",onclick:()=>n.setGoal("team-sales",null)},"Remove"):null),qe(e,"team-sales"),o("div",{class:"goal-row"},o("label",{for:"team-commission-goal"},"Monthly commission goal"),x,e.saved.teamCommissionGoal!==null?o("button",{type:"button",class:"button-quiet",onclick:()=>n.setGoal("team-commission",null)},"Remove"):null),qe(e,"team-commission"),o("div",{class:"goal-row"},o("button",{type:"button",class:"button",onclick:()=>{const y=Ve(f.value),N=Ve(x.value);y!==null&&n.setGoal("team-sales",y),N!==null&&n.setGoal("team-commission",N)}},"Set"),jt(e)?o("button",{type:"button",class:"button-quiet",onclick:n.restoreGoals},"Restore goals set in chat"):null));return o("div",null,o("div",{class:"grid grid-2 heroes"},b,v),o("div",{style:"margin-top:12px"},D))};function Ce(e,n,t){if(n===null)return"No prior month loaded";const s=e-n;return s===0?"Same as last month":`${s>0?"+":"−"}${t(Math.abs(s))} vs last month`}const Cs=e=>{var i,l,m;const n=$e(e.data,T(e)),t=U(T(e),-1),r=Oe(e.data,[t]).length>0?$e(e.data,t):null,a=c=>c.orders?c.credited_sales/c.orders:0,u=c=>c.orders?c.bottles/c.orders:0;return o("div",null,G(e,"teamTiles"),o("div",{class:"grid grid-5"},L("Orders",C(n.orders),Ce(n.orders,(i=r==null?void 0:r.orders)!=null?i:null,C)),L("Average order",le(a(n)),Ce(a(n),r?a(r):null,le)),L("Bottles per order",C(u(n)),Ce(u(n),r?u(r):null,C)),L("Club signups",C(n.club_signups),Ce(n.club_signups,(l=r==null?void 0:r.club_signups)!=null?l:null,C)),L("Club cancellations",C(n.club_cancellations),Ce(n.club_cancellations,(m=r==null?void 0:r.club_cancellations)!=null?m:null,C))))},Ts=e=>{const n=Oe(e.data,st(T(e)));if(n.length<2)return o("div",null,G(e,"teamCharts"),_(e.live?"Trends need more than one month of sales.":"Trends need the New Vintage connector."));const t=s=>n.map(r=>({label:z(r),value:s(r),selected:r===T(e)}));return o("div",null,G(e,"teamCharts"),o("div",{class:"grid charts"},ve("Credited sales",t(s=>$e(e.data,s).credited_sales)),ve("Orders",t(s=>$e(e.data,s).orders),C),ve("Club signups",t(s=>{var r,a;return $((a=(r=Mt(e.data,s))==null?void 0:r.team_club_signups)!=null?a:$e(e.data,s).club_signups)}),C)))},Ns=e=>{const n=Mt(e.data,T(e));if(!n)return o("div",null,G(e,"teamSources"),_("Sales sources for this month need the New Vintage connector."));const t=$(n.paid_sales),s=[{label:"Associate-credited",value:$(n.associate_credited_sales),color:"var(--chart-series-1)"},{label:"Club processing",value:$(n.club_processing_sales),color:"var(--chart-series-2)"},{label:"Other",value:$(n.other_sales),color:"var(--chart-series-3)"}],r=a=>t?Math.round(a/t*100):0;return o("div",null,G(e,"teamSources"),o("div",{class:"card"},Pe("Paid sales",z(T(e),!0)),o("div",{class:"figure-value"},h(t)),o("div",{class:"stack",role:"img","aria-label":s.map(a=>`${a.label} ${r(a.value)}%`).join(", ")},s.map(a=>o("span",{style:`width:${r(a.value)}%;background:${a.color}`}))),o("div",{class:"legend"},s.map(a=>o("span",null,o("span",{class:"swatch",style:`background:${a.color}`}),`${a.label} ${r(a.value)}% (${le(a.value)})`))),_(`An associate can be credited with ${r(s[0].value)}% of the winery's paid sales this month; club processing and other sales have no associate.`)))},As=(e,n)=>{const t=T(e),s=st(t),r=De(e.data,e.period,t).map(i=>{const l=B(e.data,i.key,e.period),m=ue(e.data,i.key,t),c=_e(e.data,i.key,t);return{associate:i,commission:l.eligible_commission,eligible:l.eligible_sales,monthEligible:m.eligible_sales,monthCommission:m.eligible_commission,salesStatus:te(m.eligible_sales,K(e.saved,"sales",i.key).value,t,e.today),commissionStatus:te(m.eligible_commission,K(e.saved,"commission",i.key).value,t,e.today),credited:c.credited_sales,orders:c.orders,bottles:c.bottles,signups:c.club_signups,refunds:l.refunds,trend:s.map(d=>_e(e.data,i.key,d).credited_sales)}}),a=r.filter(i=>i.trend.some(l=>l!==0)).length,u=[{key:"associate",label:"Associate",cell:i=>o("button",{type:"button",class:"name-link","data-fid":`pick-${i.associate.key}`,onclick:()=>n.selectAssociate(i.associate.key)},i.associate.name),sort:i=>i.associate.name.toLowerCase()},{key:"commission",label:"Commission",numeric:!0,cell:i=>h(i.commission),sort:i=>i.commission},{key:"eligible",label:"Eligible sales",numeric:!0,cell:i=>h(i.eligible),sort:i=>i.eligible}];return ge(e.period)||u.push({key:"monthEligible",label:"Month eligible sales",numeric:!0,cell:i=>h(i.monthEligible),sort:i=>i.monthEligible}),u.push({key:"salesGoal",label:"Sales goal",tip:`Eligible sales for ${z(t,!0)} against the monthly sales goal.`,cell:i=>ne(i.salesStatus),sort:i=>qt[i.salesStatus]}),Bt(e)&&u.push({key:"commissionGoal",label:"Commission goal",tip:`Eligible commission for ${z(t,!0)} against the monthly commission goal.`,cell:i=>ne(i.commissionStatus),sort:i=>qt[i.commissionStatus]}),u.push({key:"credited",label:"Credited sales",numeric:!0,cell:i=>h(i.credited),sort:i=>i.credited},{key:"orders",label:"Orders",numeric:!0,cell:i=>C(i.orders),sort:i=>i.orders},{key:"aov",label:"Average order",numeric:!0,cell:i=>i.orders?h(i.credited/i.orders):"",sort:i=>i.orders?i.credited/i.orders:0},{key:"bottles",label:"Bottles",numeric:!0,cell:i=>C(i.bottles),sort:i=>i.bottles},{key:"signups",label:"Signups",numeric:!0,cell:i=>C(i.signups),sort:i=>i.signups},{key:"refunds",label:"Refunds",numeric:!0,cell:i=>i.refunds?h(i.refunds):"",sort:i=>i.refunds},{key:"trend",label:"Trend",tip:`Trend lines are scaled to each associate's own best month, so compare shape, not height. ${a} ${a===1?"associate":"associates"} had activity.`,cell:i=>$s(i.trend,s.indexOf(t))}),r.length?o("div",null,G(e,"teamTable"),o("div",{class:"card",style:"padding:0"},ot(u,r,{sortKey:e.teamSort.key,sortDir:e.teamSort.dir,onSort:n.sortTeam,caption:"Associates"}))):o("div",null,G(e,"teamTable"),_("No associate has credited sales or commission lines in this pay period."))},Ms=e=>{const n=e.data.sources.length>0&&e.data.sources.every(t=>$(t.visits)===0);return o("div",null,G(e,"teamMissing"),n?_("No visits, guests or conversion: this winery has no reservations synced."):null,_("Hours worked aren't in Commerce7, so the page can't show sales per hour."))};function Es(e,n,t,s){const r=K(e.saved,"sales",n.key);if(r.value===null)return null;const a=r.value,u=Math.max(0,-t),i=Math.max(a,Math.max(0,t))+u||1,l=u/i*100,m=Math.abs(t)/i*100,c=t<0?l-m:l,d=l+a/i*100,b=a>=t,v=r.custom?"Custom sales goal":ge(e.period)?"Sales goal":`${z(T(e),!0)} sales goal`,f=`${v} ${le(a)}`,x=s==="met"?"status-met":s==="behind"?"status-behind":"";return o("div",{class:"goalbar",title:`${v}: eligible sales for ${z(T(e),!0)} (${h(t)}) against the ${h(a)} sales goal.`},o("div",{class:"goalbar-track"},u?o("span",{class:"goalbar-zero",style:`left:${l}%`}):null,o("span",{class:`goalbar-fill ${x}`,style:`left:${c}%;width:${m}%`}),b?null:o("span",{class:"goalbar-tick",style:`left:${d}%`})),o("span",{class:`goalbar-label${b?" end":""}`,style:b?"":`left:${d}%`},f),t<0?o("div",{class:"caption"},`${h(t)} after refunds`):null)}function Gs(e,n,t){const s=e.saved.associateGoals[t.key],r=e.saved.associateCommissionGoals[t.key],a=(s!=null?s:null)!==null||(r!=null?r:null)!==null,u=(m,c)=>m!=null?`${h(m)} custom`:c!==null?`${h(c)} team`:"No team goal",i=o("input",{type:"text",inputmode:"decimal",id:"associate-sales-goal","data-fid":"associate-sales-goal",placeholder:u(s,e.saved.teamGoal),"aria-label":"Monthly sales goal"}),l=o("input",{type:"text",inputmode:"decimal",id:"associate-commission-goal","data-fid":"associate-commission-goal",placeholder:u(r,e.saved.teamCommissionGoal),"aria-label":"Monthly commission goal"});return at(a?"Edit custom goal":"Edit goal",e.openDisclosures.has(`goal-${t.key}`),m=>n.toggleDisclosure(`goal-${t.key}`,m),_(`Custom goals apply to ${t.name} only.`),o("div",{class:"goal-row"},o("label",{for:"associate-sales-goal"},"Monthly sales goal"),i,(s!=null?s:null)!==null?o("button",{type:"button",class:"button-quiet",onclick:()=>n.setGoal(`sales:${t.key}`,null)},"Use team goal"):null),qe(e,`sales:${t.key}`),o("div",{class:"goal-row"},o("label",{for:"associate-commission-goal"},"Monthly commission goal"),l,(r!=null?r:null)!==null?o("button",{type:"button",class:"button-quiet",onclick:()=>n.setGoal(`commission:${t.key}`,null)},"Use team goal"):null),qe(e,`commission:${t.key}`),o("div",{class:"goal-row"},o("button",{type:"button",class:"button",onclick:()=>{const m=Ve(i.value),c=Ve(l.value);m!==null&&n.setGoal(`sales:${t.key}`,m),c!==null&&n.setGoal(`commission:${t.key}`,c)}},"Set"),jt(e)?o("button",{type:"button",class:"button-quiet",onclick:n.restoreGoals},"Restore goals set in chat"):null))}const Ls=(e,n)=>{const t=e.associate;if(!t)return null;const s=B(e.data,t.key,e.period),r=ue(e.data,t.key,T(e)),a=_e(e.data,t.key,T(e)),u=K(e.saved,"sales",t.key),i=K(e.saved,"commission",t.key),l=te(r.eligible_sales,u.value,T(e),e.today),m=te(r.eligible_commission,i.value,T(e),e.today),c=ge(e.period),d=s.eligible_lines===0&&s.eligible_sales===0,b=c&&l==="met"?" status-met":c&&l==="behind"?" status-behind":"",v=Et(e.options.settings.rules,t),f=v.length?v.map(y=>`${yt(y.rateKind,y.rate)} on ${Qn(y)}`).join(", "):"No rate earns",x=o("div",{class:"card"},Pe("Eligible sales",j(e.period)),d?o("p",{class:"verdict"},`${t.name}'s first commissionable sale in ${j(e.period)} will show here.`):[o("div",{class:`hero-value${b}`},h(s.eligible_sales)),o("p",{class:"verdict"},"Eligible commission is ",o("span",{class:"amount"},h(s.eligible_commission)),".")],o("div",{class:"pills"},ne(l,"Sales goal"),i.value!==null?ne(m,"Commission goal",i.custom):null),Es(e,t,r.eligible_sales,l),o("div",{style:"margin-top:8px"},Gs(e,n,t))),D=[L("Total attributed sales",h(a.credited_sales),c?void 0:`Credited sales in ${z(T(e),!0)}`),L("Pending sales",h(s.pending_sales)),L("Pending commission",h(s.pending_commission)),L("Excluded",h(s.excluded_sales)),(()=>{var N;const y=L("Rate",f);return(N=y.querySelector(".figure-value"))==null||N.classList.add("figure-text"),y})(),s.refunds?L("Refunds",h(s.refunds)):null];return o("div",null,x,o("div",{class:"grid grid-3",style:"margin-top:12px"},D))},zs=e=>{const n=e.associate;if(!n)return null;const t=B(e.data,n.key,e.period),s=e.period.end.slice(0,4),r=Array.from({length:Number(T(e).slice(5,7))},(l,m)=>`${s}-${String(m+1).padStart(2,"0")}`),a=r.every(l=>e.data.summary.some(m=>m.grain==="month"&&String(m.period_start).startsWith(l))),u=r.reduce((l,m)=>l+ue(e.data,n.key,m).pending_commission,0),i=ce(e.period.end,e.options.settings.returnWindowDays);return o("div",null,G(e,"associatePayout"),o("div",{class:"card"},o("div",{class:"grid grid-2"},L("Eligible so far",h(t.eligible_commission)),L("Could still be added",h(t.pending_commission),"When pending lines pass the sale rules"),L("Most this pay period could reach",h(t.eligible_commission+t.pending_commission)),L("Pending across the year",a?h(u):"—",a?void 0:"Needs the New Vintage connector")),_(Kt(e)),e.today<i?_(`Refunds before ${J(i)} can still lower this.`):null))},Ds=e=>{const n=e.associate;if(!n)return null;const t=T(e).slice(0,4),s=st(T(e)).filter(a=>e.data.summary.some(u=>u.grain==="month"&&String(u.period_start).startsWith(a))||Oe(e.data,[a]).length);if(s.length<2)return o("div",null,G(e,"associateCharts"),_(e.live?"Trends need more than one month.":"Trends need the New Vintage connector."));const r=a=>s.map(u=>({label:z(u)+(u.startsWith(t)?"":` ${u.slice(2,4)}`),value:a(u),selected:u===T(e)}));return o("div",null,G(e,"associateCharts"),o("div",{class:"grid charts"},ve("Eligible sales",r(a=>ue(e.data,n.key,a).eligible_sales)),ve("Credited sales",r(a=>_e(e.data,n.key,a).credited_sales))))},Os=e=>{const n=e.associate;if(!n)return null;const t=T(e),s=t.slice(0,4),a=Array.from({length:Number(t.slice(5,7))},(d,b)=>`${s}-${String(b+1).padStart(2,"0")}`).filter(d=>e.data.summary.some(b=>b.grain==="month"&&String(b.period_start).startsWith(d))||Oe(e.data,[d]).length).map(d=>{const b=ue(e.data,n.key,d),v=_e(e.data,n.key,d);return{month:d,commission:b.eligible_commission,eligible:b.eligible_sales,sales:te(b.eligible_sales,K(e.saved,"sales",n.key).value,d,e.today),commissionStatus:te(b.eligible_commission,K(e.saved,"commission",n.key).value,d,e.today),credited:v.credited_sales,orders:v.orders,bottles:v.bottles,signups:v.club_signups,cancellations:v.club_cancellations}}),u=Bt(e),i=[{key:"month",label:"Month",cell:d=>z(d.month,!0)},{key:"commission",label:"Eligible commission",numeric:!0,cell:d=>h(d.commission)},{key:"eligible",label:"Eligible sales",numeric:!0,cell:d=>h(d.eligible)},{key:"sales",label:"Sales goal",tip:"Eligible sales for the month against the monthly sales goal.",cell:d=>ne(d.sales)}];u&&i.push({key:"commissionGoal",label:"Commission goal",tip:"Eligible commission for the month against the monthly commission goal.",cell:d=>ne(d.commissionStatus)}),i.push({key:"credited",label:"Credited sales",numeric:!0,cell:d=>h(d.credited)},{key:"orders",label:"Orders",numeric:!0,cell:d=>C(d.orders)},{key:"aov",label:"Average order",numeric:!0,cell:d=>d.orders?h(d.credited/d.orders):""},{key:"bottles",label:"Bottles",numeric:!0,cell:d=>C(d.bottles)},{key:"signups",label:"Signups",numeric:!0,cell:d=>C(d.signups)},{key:"cancellations",label:"Cancellations",numeric:!0,cell:d=>C(d.cancellations)});const l=d=>a.reduce((b,v)=>b+d(v),0),m=l(d=>d.orders),c=["Year to date",h(l(d=>d.commission)),h(l(d=>d.eligible)),"",...u?[""]:[],h(l(d=>d.credited)),C(m),m?h(l(d=>d.credited)/m):"",C(l(d=>d.bottles)),C(l(d=>d.signups)),C(l(d=>d.cancellations))];return a.length?o("div",null,G(e,"associateMonths"),o("div",{class:"card",style:"padding:0"},ot(i,a,{footer:c,caption:"By month"})),a.length<Number(t.slice(5,7))&&!e.live?_("Earlier months need the New Vintage connector."):null):o("div",null,G(e,"associateMonths"),_("No months are loaded for this associate."))};function Te(e,n,t){var a,u;const s=es(e,n),r=String((u=(a=e[t])!=null?a:e[n])!=null?u:"");return s?o("a",{href:s,target:"_blank",rel:"noopener noreferrer"},r," ",Ie("external-link",12)):r}function Ht(e){return o("dl",{class:"trace-grid"},e.filter(([,n])=>n!=null&&n!=="").map(([n,t])=>o("div",null,o("dt",null,n),o("dd",null,t instanceof Node?t:String(t)))))}function Yt(e,n,t,s,r,a,u){var l;const i=[];for(const m of s){const c=`${t}-${String((l=m.line_id)!=null?l:m.order_id)}`,d=e.openRows.has(c),b=()=>n.toggleRow(c);i.push(o("tr",{class:"line",tabindex:0,"data-fid":c,"aria-expanded":d?"true":"false",onclick:v=>{v.target.closest("a")||b()},onkeydown:v=>{const f=v.key;(f==="Enter"||f===" ")&&(v.preventDefault(),b())}},r(m).map((v,f)=>o("td",{class:f>=3?"num":null},v)))),d&&i.push(o("tr",{class:"trace"},o("td",{colspan:7},a(m))))}return i}function Zt(e,n){return o("div",{class:"table-wrap"},o("table",null,o("thead",null,o("tr",null,e.map((t,s)=>o("th",{scope:"col",class:s>=3?"num":null},t)))),o("tbody",null,n)))}function H(e){return o("span",{class:`skel ${e}`,"aria-hidden":"true"})}function Jt(e,n=5,t=7){return o("div",{class:"card skeleton-table",role:"status","aria-live":"polite"},o("span",{class:"sr-only"},e),o("div",{class:"skeleton-caption"},o("span",{class:"spinner","aria-hidden":"true"}),e),Array.from({length:n},()=>o("div",{class:"skeleton-row"},Array.from({length:t},(s,r)=>H(r===2?"skel-wide":"skel-cell")))))}function Rs(e,n){const t=()=>o("div",{class:"card"},H("skel-eyebrow"),H("skel-hero"),H("skel-line"));return o("div",{class:"skeleton-view"},o("section",{class:"section"},o("div",{class:"grid grid-2 heroes"},t(),e==="team"?t():o("div",{class:"card"},H("skel-line"),H("skel-line"),H("skel-line")))),o("section",{class:"section"},o("div",{class:"grid grid-5"},Array.from({length:5},()=>o("div",{class:"card figure"},H("skel-line"),H("skel-figure"))))),o("section",{class:"section"},Jt(`Loading ${n}…`)))}function Is(e,n){var t;return e.lines.status==="offline"?"Line detail needs the New Vintage connector.":e.lines.status==="error"?(t=e.lines.message)!=null?t:"Line detail couldn't load.":null}const Ps=(e,n)=>{const t=e.associate;if(!t)return null;if(e.lines.status==="loading")return o("div",null,G(e,"associateLines"),Jt(`Loading ${t.name}'s lines…`));const s=Is(e,t.name);if(s)return o("div",null,G(e,"associateLines"),_(s));const r=e.options.settings.timeZone,a=Gt(e.lines.rows),u=e.showAllLines?a.eligible:a.eligible.slice(0,10),i=u.reduce((f,x)=>f+$(x.net_dollars),0),l=a.eligible.slice(u.length),m=l.reduce((f,x)=>f+$(x.net_dollars),0),c=B(e.data,t.key,e.period).eligible_sales,d=[...u,...a.unpriced],b=Yt(e,n,"line",d,f=>{var x,D,y,N,M;return[F(f.order_date,r),Te(f,"order_id","order_number"),f.bucket==="unpriced"?o("span",null,String((D=(x=f.product)!=null?x:f.product_title)!=null?D:"")," ",o("span",{class:"unpriced"},"Could not price")):String((N=(y=f.product)!=null?y:f.product_title)!=null?N:""),C((M=f.net_quantity)!=null?M:f.quantity),h(f.net_dollars),yt(f.rate_kind,f.rate),h(f.rule_commission)]},f=>Ht([["Order id",f.order_id],["Order",Te(f,"order_id","order_number")],["Order date",F(f.order_date,r)],["Fulfilled",F(f.fulfilled_date,r)],["Delivery",f.delivery_method],["SKU",f.sku],["Product id",f.product_id],["Item type",f.item_type],["Dollar amount",Z(f.dollar_amount)],["Taken off by refunds",$(f.dollars_taken)?Z(f.dollars_taken):null],["Fulfillment status",f.fulfillment_status],["Payment status",f.payment_status],["Purchase type",f.purchase_type],["Rule",f.rule_label],["Commission",Z(f.rule_commission)]])),v=i+m;return o("div",null,G(e,"associateLines"),a.eligible.length||a.unpriced.length?o("div",{class:"card",style:"padding:0"},Zt(["Date","Order","Product","Qty","Sales","Rate","Commission"],b)):_(`No eligible lines for ${t.name} in ${j(e.period)}.`),!e.showAllLines&&l.length?o("button",{type:"button",class:"button-quiet",style:"margin-top:12px",onclick:n.showAllLines},`Show all ${a.eligible.length} lines`):null,_(l.length?`Listed lines ${h(i)} plus ${l.length} other eligible lines ${h(m)} equal eligible sales ${h(v)}.`:`Listed lines equal eligible sales ${h(v)}.`,"status-line"),Math.abs(v-c)>.05?_(`These lines don't match the summary's eligible sales of ${h(c)}. The data may have changed since the summary loaded.`,"status-line problem"):null)},Vs=(e,n)=>{const t=e.associate;if(!t||e.lines.status!=="ready")return null;const s=e.options.settings.timeZone,r=Gt(e.lines.rows),a=r.refundsListed.reduce((c,d)=>c+$(d.dollar_amount),0),u=r.refundsListed.reduce((c,d)=>c+(d.original_line_loaded===!0&&d.refund_in_window===!0?Math.abs($(d.dollar_amount)):0),0),i=r.refundsNotListed.reduce((c,d)=>c+$(d.dollar_amount),0),l=B(e.data,t.key,e.period).refunds,m=Yt(e,n,"refund",r.refundsListed,c=>{var d,b;return[F(c.order_date,s),F(c.original_order_date,s),Te(c,"linked_order_id","linked_order_number"),String((b=(d=c.product)!=null?d:c.product_title)!=null?b:""),h(c.dollar_amount)]},c=>{var d;return Ht([["Refund order",Te(c,"order_id","order_number")],["Refund date",F(c.order_date,s)],["Original order",Te(c,"linked_order_id","linked_order_number")],["Original order date",F(c.original_order_date,s)],["Delivery",c.original_delivery_method],["Original fulfilled",F(c.original_fulfilled_date,s)],["Item",(d=c.product)!=null?d:c.product_title],["Item type",c.item_type],["Quantity refunded",C(Math.abs($(c.quantity)))],["Refund",Z(c.dollar_amount)],["Original line amount",c.original_line_loaded===!0?Z(c.original_line_dollars):"Before this year's lines"],["Taken off",c.original_line_loaded===!0?Z(c.original_line_taken):Z(0)],["Left on the line",c.original_line_loaded===!0?Z(c.original_line_left):null]])});return o("div",null,G(e,"associateRefunds"),_(`A refund within the ${e.options.settings.returnWindowDays}-day return window lowers the commission of the pay period its original sale is in. A later refund changes nothing already paid. This list is for reconciling payouts.`),r.refundsListed.length?o("div",{class:"card",style:"padding:0;margin-top:12px"},Zt(["Refund date","Order date","Original order","Product","Refunds"],m)):_(`No refunds are listed for ${t.name} in this pay period.`),_([`Listed refunds ${h(a)}, of which ${h(u)} came off original lines.`,r.refundsNotListed.length?`${r.refundsNotListed.length} refund lines (${h(i)}) are on orders not credited to ${t.name} and aren't listed.`:"",`Refunds figure: ${h(l)}.`].filter(Boolean).join(" "),"status-line"))};function qs(e,n){var l,m;const t=e.options.plan,s=(l=t.assumed)!=null?l:[],r=e.associate,a=r?Et(e.options.settings.rules,r):e.options.settings.rules.filter(c=>c.rate>0&&c.associateAccountId===null&&c.associateName===null),u=Xn(a),i=r?K(e.saved,"sales",r.key).value:e.saved.teamGoal;return o("footer",{class:"section"},G(e,"rulesFooter"),s.length?o("button",{type:"button",class:"assumed","data-fid":"assumed",onclick:n.toggleAssumed},`${s.length} ${s.length===1?"item is":"items are"} assumed — not confirmed.`):null,o("ul",null,t.rules.map(c=>o("li",{class:s.includes(c)&&e.highlightAssumed?"highlight":null},c)),s.filter(c=>!t.rules.includes(c)).map(c=>o("li",{class:e.highlightAssumed?"highlight":null},`Assumed — not confirmed: ${c}`)),((m=t.notCalculated)!=null?m:[]).map(c=>o("li",null,`Not calculated: ${c}.`))),_(Kt(e)),i!==null?_(u!==null?`Goal payout: at the ${h(i)} sales goal, ${C(u)}% pays ${h(i*u/100)}.`:"Goal payout: the mix of rules decides it, so it isn't shown."):null,t.policyFile?_(`Rules from ${t.policyFile}.`):null,e.mathUpdated!==null?_(`Commission math updated to version ${e.mathUpdated}.`):null,e.needsUpdate?_("This dashboard needs an update. Ask Claude in this chat to update it.","status-line problem"):null,e.storageNote?_(e.storageNote):null,_("Rule, pay period, sale-counting and return-window changes change the queries: ask Claude in this chat."))}function Fs(e,n){var t,s,r;return at((r=(s=(t=e.options.customize)==null?void 0:t.labels)==null?void 0:s.howTo)!=null?r:Ut.howTo,e.openDisclosures.has("howto"),a=>n.toggleDisclosure("howto",a),o("ul",null,o("li",null,"Credited sales are paid orders with an associate on them. Eligible sales are the lines that passed the sale rules and earn a rate above zero; commission is paid on those."),o("li",null,"Pending lines haven't passed the fulfillment or payment rule yet. Excluded lines never earn, including lines that pay 0 percent, so they aren't in eligible sales."),o("li",null,`Refunds are listed so a payout can be reconciled. A refund lowers a pay period's commission only when its original sale is in that period and it comes within the ${e.options.settings.returnWindowDays}-day return window.`),o("li",null,"The rate is applied to each line after refunds are taken off it."),o("li",null,"Goals are monthly. The sales goal is measured on eligible sales, and the commission goal, when one is set, on eligible commission.")))}const Us={teamHeroes:Ss,teamTiles:Cs,teamCharts:Ts,teamSources:Ns,teamTable:As,teamMissing:Ms,associateSummary:Ls,associatePayout:zs,associateCharts:Ds,associateMonths:Os,associateLines:Ps,associateRefunds:Vs},js=900*1e3,Qt="dash-howto";function Xt(e,n){if(!e)return"";switch(e.kind){case"unavailable":return"Live numbers need the New Vintage connector with access to this winery.";case"approval":return"Live numbers need your permission to use the New Vintage connector.";case"reconnect":return"Reconnect New Vintage in claude.ai Settings → Connectors.";case"temporary":return`Couldn't refresh. Showing data from ${n}.`;case"needs_update":return"This dashboard needs an update. Ask Claude in this chat to update it.";case"not_reconciled":return`The refresh did not reconcile, so the page kept the data from ${n}.`;case"tool":return e.message}}function Ws(e,n){var i,l,m,c,d,b;const t=n==="team"?[...vs]:[...ws],s=((i=e.cards)!=null?i:[]).filter(v=>v.view===n||v.view==="both");for(const v of s){const f=v.after?t.indexOf(v.after):-1;f>=0?t.splice(f+1,0,v.id):t.push(v.id)}const a=((c=(m=(l=e.customize)==null?void 0:l.order)==null?void 0:m[n])!=null?c:[]).filter(v=>t.includes(v));for(const v of t)a.includes(v)||a.push(v);const u=new Set((b=(d=e.customize)==null?void 0:d.hide)!=null?b:[]);return a.filter(v=>!u.has(v))}function Bs(e,n){var mn,pn,fn,gn,hn,bn,yn,vn,wn,xn,kn,_n,$n,Sn;const t=(mn=n.now)!=null?mn:(()=>new Date),s=n.settings.timeZone,r=n.settings.payPeriod,a=()=>Gn(t(),s),u=()=>Ee(a(),r),i=`${Number(a().slice(0,4))-1}-01-01`,l=Rt(n.customize,n.cards),m=rs(n.storage),c=m.mode,d=Lt(n.plan);let b={summary:n.snapshot.summary,performance:n.snapshot.performance,sources:n.snapshot.sources},v="team",f=null,x=u(),D=ye(n.plan),y={mode:"snapshot",refreshedAt:null,failure:null},N=n.snapshot.lastSyncedAt,M=null,I=null,en=!1,tn=null,lt=!1,nn=null,me=!1,Fe=!1,Ue=!1,ct=!1,je={key:"commission",dir:"desc"};const We=new Set,Be=new Set,R=new Map;let dt=null,Ke=!1;e.innerHTML="";const Hs=[(gn=(fn=(pn=n.customize)==null?void 0:pn.fonts)==null?void 0:fn.display)!=null?gn:"Newsreader",(yn=(bn=(hn=n.customize)==null?void 0:hn.fonts)==null?void 0:bn.body)!=null?yn:"Be Vietnam Pro"],sn=o("link",{rel:"stylesheet",href:hs(Hs.filter(p=>/^[A-Za-z0-9 ]{1,40}$/.test(p)))}),ut={};(wn=(vn=n.customize)==null?void 0:vn.fonts)!=null&&wn.display&&(ut["font-display"]=`'${n.customize.fonts.display}', Georgia, serif`),(kn=(xn=n.customize)==null?void 0:xn.fonts)!=null&&kn.body&&(ut["font-body"]=`'${n.customize.fonts.body}', system-ui, sans-serif`);const on=o("style",null,bs({...ut,...($n=(_n=n.customize)==null?void 0:_n.theme)!=null?$n:{}},(Sn=n.customize)==null?void 0:Sn.themeDark)+ys);document.head.append(sn,on);const P=o("div",{class:"nvcd"});e.append(P);const Y=typeof ResizeObserver=="function"?new ResizeObserver(()=>He()):null,rn=()=>{He(),rt(P)};window.addEventListener("resize",rn);function He(){const p=P.querySelector(".controlbar");p&&P.style.setProperty("--bar-h",`${p.offsetHeight}px`)}function mt(){return f?`${f}|${x.start}`:null}function pt(){if(!f)return null;const p=De(b,x,Ge(x)).find(g=>g.key===f);return p!=null?p:{key:f,name:f,accountId:null}}function an(){const p=mt(),g=p&&R.get(p)||{status:M?"loading":"offline",rows:[]};return{options:n,data:b,period:x,today:a(),live:y.mode==="live",saved:D,baseline:d,associate:pt(),lines:g,openRows:We,openDisclosures:Be,showAllLines:Ue,teamSort:je,highlightAssumed:ct,storageNote:c==="browser"?"Goals are saved only in this browser.":c==="none"?"Changes won't be saved.":null,mathUpdated:tn,needsUpdate:lt,syncedAt:N?Q(N,s):null}}const Ye={selectAssociate:p=>{var g;v=p?"associate":"team",f=p,Ue=!1,E(),(g=window.scrollTo)==null||g.call(window,0,0),ft()},setGoal:(p,g)=>{var w;D=us(D,p,g,(w=n.viewerName)!=null?w:null,t().toISOString()),E(),ln()},restoreGoals:()=>{D={...ye(n.plan),planRevision:D.planRevision},E(),ln()},sortTeam:p=>{je=je.key===p?{key:p,dir:je.dir==="desc"?"asc":"desc"}:{key:p,dir:p==="associate"||p==="salesGoal"||p==="commissionGoal"?"asc":"desc"},E()},toggleRow:p=>{We.has(p)?We.delete(p):We.add(p),E()},toggleDisclosure:(p,g)=>{g?Be.add(p):Be.delete(p),p==="howto"&&cs(m.adapter,Qt,g?"open":"closed")},showAllLines:()=>{Ue=!0,E()},toggleAssumed:()=>{ct=!ct,E()}};async function ln(){await is(m.adapter,n.tenantId,D)}function Ys(){var V,se,oe,re,ae;const p=y.refreshedAt?Q(y.refreshedAt,s):Q(n.snapshot.loadedAt,s),g=(V=n.snapshot.lastSyncedAt)!=null?V:n.snapshot.loadedAt,w=Qe=>`orders through ${Q(Qe,s)}`,S=me?y.mode==="live"?"Checking for new orders…":`Loading live data. Showing the snapshot with ${w(g)}`:y.mode==="live"?`Live, ${w((se=N!=null?N:y.refreshedAt)!=null?se:g)}`:`Snapshot, ${w(g)}`,k=y.mode==="live"&&y.refreshedAt?`New Vintage last received orders from Commerce7 at ${Q(N!=null?N:y.refreshedAt,s)}. This page last checked for new orders at ${Q(y.refreshedAt,s)} and checks again every 15 minutes.`:`These figures were saved when the dashboard was built, from orders New Vintage had received by ${Q(g,s)}.`,A=me?"busy":y.mode==="live"?"live":"snapshot",O=Xt(y.failure,p);return o("header",null,o("h1",null,(re=(oe=n.customize)==null?void 0:oe.title)!=null?re:"Sales Commission Dashboard"),o("div",{class:"meta"},o("span",{class:"meta-winery"},n.wineryName),o("span",null,"Source: New Vintage orders")),o("span",{class:`data-label data-${A}`,role:"status","aria-live":"polite",title:k},A==="busy"?o("span",{class:"spinner","aria-hidden":"true"}):o("span",{class:"dot","aria-hidden":"true"}),S),O?o("p",{class:"status-line problem"},O):null,((ae=y.failure)==null?void 0:ae.kind)==="approval"?o("button",{type:"button",class:"button",style:"margin-top:8px",onclick:()=>void Je()},"Allow live data"):null)}function cn(){var se,oe,re;const p=De(b,x,Ge(x)),g=o("select",{class:"view-select","aria-label":"View","data-fid":"view-select"},o("option",{value:""},"Whole team"),p.length?o("optgroup",{label:"Associates, by commission"},p.map(ae=>o("option",{value:ae.key},ae.name))):null);g.value=v==="associate"&&f?f:"",v==="associate"&&f&&g.value!==f&&(g.append(o("option",{value:f},(oe=(se=pt())==null?void 0:se.name)!=null?oe:f)),g.value=f),g.addEventListener("change",()=>Ye.selectAssociate(g.value||null));const w=Rn(x,r),S=w.start>=i&&(nt(b,w)||M!==null),k=x.start===u().start,A=a()<x.end,O=mt(),V=me||Fe||O!==null&&((re=R.get(O))==null?void 0:re.status)==="loading";return o("div",{class:"controlbar","aria-busy":V?"true":"false"},o("div",{class:"controlbar-inner"},g,o("div",{class:"period"},o("button",{type:"button",class:"icon-button","aria-label":"Previous pay period","data-fid":"prev",disabled:!S,onclick:()=>un(w)},Ie("chevron-left")),o("span",{class:"period-long"},tt(x)),A?o("span",{class:"period-open"},"Open"):null,o("span",{class:"period-short","aria-label":`${tt(x)}${A?", open":""}`},tt(x,!0)),o("button",{type:"button",class:"icon-button","aria-label":"Next pay period","data-fid":"next",disabled:k,onclick:()=>un(In(x,r))},Ie("chevron-right")))),V?o("div",{class:"progress","aria-hidden":"true"}):null)}function Zs(p){const g=an();return{view:p,period:{start:x.start,end:x.end,label:j(x),goalMonth:Ge(x),open:g.today<x.end},associate:g.associate?{key:g.associate.key,name:g.associate.name}:null,timeZone:s,live:y.mode==="live",data:{summary:b.summary,performance:b.performance,sources:b.sources,lines:g.lines.status==="ready"?g.lines.rows:null},ui:{h:o,money:h,moneyShort:le,number:C,figure:L,note:w=>_(w),barChart:ve,table:(w,S)=>ot(w.map(k=>({key:k.key,label:k.label,numeric:k.money,cell:A=>{var O;return k.money?h(A[k.key]):String((O=A[k.key])!=null?O:"")}})),S)},runSql:async w=>{if(!M)throw new Error("This card needs the New Vintage connector.");return(await be(M,w,"Loading a custom card on the commission dashboard.")).rows}}}function Js(p,g){const w=o("div",null,_("Loading…")),S=o("section",{class:"section custom-card","data-card":p.id},o("h2",null,p.title),o("p",{class:"card-purpose"},p.purpose),o("div",{class:"card"},w));return Promise.resolve().then(()=>p.render(Zs(g))).then(k=>{w.replaceChildren(k==null?_("Nothing to show yet."):typeof k=="string"?_(k):k),rt(S)}).catch(k=>w.replaceChildren(_(`This card couldn't load: ${k instanceof Error?k.message:String(k)}`,"status-line problem"))),S}function E(){var V,se,oe,re,ae,Qe;if(Ke)return;const p=(se=(V=document.activeElement)==null?void 0:V.getAttribute)==null?void 0:se.call(V,"data-fid"),g=an(),w=o("main",{class:"page page-head"},Ys(),o("div",{class:"howto"},Fs(g,Ye))),S=o("div",{class:"page"}),k=v;if(Fe&&!nt(b,x)){S.append(Rs(k,j(x))),P.replaceChildren(w,cn(),S),He();return}const A=new Map(((oe=n.cards)!=null?oe:[]).map(we=>[we.id,we]));for(const we of Ws(n,k)){const Cn=A.get(we);if(Cn){S.append(Js(Cn,k));continue}const Tn=Us[we],Nn=Tn?Tn(g,Ye):null;Nn&&S.append(o("section",{class:"section","data-section":we},Nn))}(ae=(re=n.customize)==null?void 0:re.hide)!=null&&ae.includes("rulesFooter")||S.append(qs(g,Ye)),P.replaceChildren(w,cn(),S),p&&((Qe=P.querySelector(`[data-fid="${CSS.escape(p)}"]`))==null||Qe.focus()),Y==null||Y.disconnect();const O=P.querySelector(".controlbar");O&&(Y==null||Y.observe(O)),He(),rt(P)}function Ze(p){return{...n.settings,...p}}function Qs(p){const g=ee(p).slice(0,4),w=u(),S=ee(w).slice(0,4)===g?w.end:Ee(`${g}-12-31`,r).end;return{windowStart:`${g}-01-01`,windowEnd:S,year:g}}async function dn(p){if(!M||!I)return;const g=Qs(p),w=ee({start:g.windowStart,end:g.windowEnd}).slice(0,7),S=await Wn(M,I,{...Ze(g),reportMonths:{first:`${g.year}-01`,last:w}}),k={windowStart:`${Number(g.year)-1}-01-01`,windowEnd:g.windowEnd},A=await St(M,I,he.performance,Ze(k)),O=await St(M,I,he.sources,Ze(k));if(!Kn(A,O))throw new Error("not_reconciled");b={summary:S,performance:A,sources:O},nn=g.year}async function Je(){var p,g;if(!Ke){y={...y,mode:y.mode==="live"?"live":"loading",failure:null},me=!0,E();try{if(!M){const w=(g=n.callTool)!=null?g:await qn((p=n.connectorName)!=null?p:"New Vintage");if(!w){me=!1,y={mode:"snapshot",refreshedAt:null,failure:{kind:"unavailable"}};for(const[S,k]of R)k.status==="loading"&&R.set(S,{status:"offline",rows:[]});E();return}M=Un(w,n.tenantId)}I=await jn(M,en?null:l),en=!0,tn=I.version>n.guideVersion?I.version:null;try{const w=await M.call("discover_tenant_data_sources",{context:"Checking when New Vintage last synced this winery's orders for the commission dashboard."}),k=(Array.isArray(w.connectedSources)?w.connectedSources:[]).map(A=>A.lastSyncAt).filter(A=>typeof A=="string").sort();k.length&&(N=k[k.length-1])}catch{}await dn(x),R.clear(),lt=!1,me=!1,y={mode:"live",refreshedAt:t().toISOString(),failure:null},E(),ft()}catch(w){const S=w instanceof Error&&w.message==="not_reconciled"?{kind:"not_reconciled"}:Le(w);if(lt=S.kind==="needs_update",me=!1,y={mode:y.refreshedAt?"live":"snapshot",refreshedAt:y.refreshedAt,failure:S},!M)for(const[k,A]of R)A.status==="loading"&&R.set(k,{status:"offline",rows:[]});E()}}}async function ft(){var w,S;const p=mt(),g=pt();if(!(!p||!g||((w=R.get(p))==null?void 0:w.status)==="ready")){if(!M||!I){y.mode!=="loading"&&R.set(p,{status:"offline",rows:[]}),E();return}R.set(p,{status:"loading",rows:[]}),E();try{const k=await Bn(M,I,{...Ze(Pn(x)),focus:{associateAccountId:g.accountId,associateName:g.accountId?null:g.name,periodStart:x.start}});R.set(p,{status:"ready",rows:k})}catch(k){const A=Le(k);R.set(p,{status:"error",rows:[],message:Xt(A,Q((S=y.refreshedAt)!=null?S:n.snapshot.loadedAt,s))})}E()}}function un(p){x=p,Ue=!1,E(),M&&I&&!nt(b,p)&&ee(p).slice(0,4)!==nn&&(Fe=!0,E(),dn(p).catch(g=>{y={...y,failure:Le(g)}}).finally(()=>{Fe=!1,E()})),ft()}return E(),(async()=>(D=await as(m.adapter,n.tenantId,n.plan),await ls(m.adapter,Qt)==="open"&&Be.add("howto"),E(),await Je(),Ke||(dt=setInterval(()=>void Je(),js))))(),{refresh:Je,destroy:()=>{Ke=!0,dt&&clearInterval(dt),Y==null||Y.disconnect(),window.removeEventListener("resize",rn),on.remove(),sn.remove(),P.remove()},state:()=>({view:v,associate:f,period:x,live:y.mode})}}function Ks(e,n){const t=typeof e=="string"?document.querySelector(e):e;if(!t)throw new Error(`NVCommissionDashboard: no element matches ${String(e)}`);return Bs(t,n)}return ie.SUPPORTED_TIME_ZONES=vt,ie.VERSION=Ot,ie.fillCommissionQuery=kt,ie.mount=Ks,ie.pageSetup=Rt,Object.defineProperty(ie,Symbol.toStringTag,{value:"Module"}),ie})({});