randmarcomps 1.322.0 → 1.323.0
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/dist/randmarcomps.js +13 -16
- package/dist/randmarcomps.umd.cjs +3 -3
- package/package.json +1 -1
package/dist/randmarcomps.js
CHANGED
|
@@ -60274,7 +60274,7 @@ function createDOMPurify() {
|
|
|
60274
60274
|
}
|
|
60275
60275
|
var purify = createDOMPurify();
|
|
60276
60276
|
function markdownToSafeHTML(t) {
|
|
60277
|
-
|
|
60277
|
+
const e = marked(t, { async: !1 });
|
|
60278
60278
|
return purify.sanitize(e, {
|
|
60279
60279
|
ALLOWED_TAGS: [
|
|
60280
60280
|
// ======== Headings ========
|
|
@@ -60698,10 +60698,9 @@ const DebugMessageDisplay = ({ debugMessages: t }) => {
|
|
|
60698
60698
|
if (useEffect(() => {
|
|
60699
60699
|
if (je === null) return;
|
|
60700
60700
|
const pt = Oe.find((Kt) => Kt.conversationID === je[0]);
|
|
60701
|
-
if (pt
|
|
60702
|
-
|
|
60703
|
-
|
|
60704
|
-
}
|
|
60701
|
+
if (!pt || (pt.pending && se("pending"), $e([pt.partner1, pt.partner2]), je[0] === -1 && !F) || je[0] !== -1 && !He) return;
|
|
60702
|
+
const Zt = je[1];
|
|
60703
|
+
ze(null), Zt && Ke(Zt);
|
|
60705
60704
|
}, [je, Oe, se, $e, F, He]), useImperativeHandle(f, () => ({
|
|
60706
60705
|
setActiveChatAndSendMessage: it
|
|
60707
60706
|
})), !F)
|
|
@@ -64857,7 +64856,7 @@ function SalesChart({
|
|
|
64857
64856
|
const z = String(q.Day ?? 0);
|
|
64858
64857
|
if (z.length !== 8) return;
|
|
64859
64858
|
const Q = `${z.substring(0, 4)}-${z.substring(4, 6)}`;
|
|
64860
|
-
O
|
|
64859
|
+
O[Q] && (O[Q].price += q.ExtendedPrice ?? 0, O[Q].quantity += q.Quantity ?? 0);
|
|
64861
64860
|
}), _ = I.map((q) => {
|
|
64862
64861
|
const z = O[q], [Q, j] = q.split("-").map(Number);
|
|
64863
64862
|
return {
|
|
@@ -93274,9 +93273,7 @@ const Treemap = React.forwardRef(
|
|
|
93274
93273
|
const b = React.useRef(null), [S, _] = React.useState(null);
|
|
93275
93274
|
React.useEffect(() => {
|
|
93276
93275
|
if (!b.current) return;
|
|
93277
|
-
const R = b.current
|
|
93278
|
-
let A;
|
|
93279
|
-
const M = () => {
|
|
93276
|
+
const R = b.current, A = () => {
|
|
93280
93277
|
const q = getComputedStyle(R).getPropertyValue("--primary").trim();
|
|
93281
93278
|
if (q) {
|
|
93282
93279
|
const z = parseHsl(q);
|
|
@@ -93292,14 +93289,14 @@ const Treemap = React.forwardRef(
|
|
|
93292
93289
|
}
|
|
93293
93290
|
return !1;
|
|
93294
93291
|
};
|
|
93295
|
-
if (
|
|
93292
|
+
if (A())
|
|
93296
93293
|
return;
|
|
93297
|
-
let
|
|
93298
|
-
const O =
|
|
93299
|
-
|
|
93300
|
-
|
|
93301
|
-
|
|
93302
|
-
|
|
93294
|
+
let M = 0;
|
|
93295
|
+
const I = 20, O = setInterval(() => {
|
|
93296
|
+
(A() || M >= I) && clearInterval(O), M++;
|
|
93297
|
+
}, 100);
|
|
93298
|
+
return () => {
|
|
93299
|
+
O && clearInterval(O);
|
|
93303
93300
|
};
|
|
93304
93301
|
}, []);
|
|
93305
93302
|
const C = React.useMemo(() => {
|
|
@@ -1060,7 +1060,7 @@ ${t}</tr>
|
|
|
1060
1060
|
`}strong({tokens:t}){return`<strong>${this.parser.parseInline(t)}</strong>`}em({tokens:t}){return`<em>${this.parser.parseInline(t)}</em>`}codespan({text:t}){return`<code>${escape2(t,!0)}</code>`}br(t){return"<br>"}del({tokens:t}){return`<del>${this.parser.parseInline(t)}</del>`}link({href:t,title:e,tokens:n}){const o=this.parser.parseInline(n),l=cleanUrl(t);if(l===null)return o;t=l;let d='<a href="'+t+'"';return e&&(d+=' title="'+escape2(e)+'"'),d+=">"+o+"</a>",d}image({href:t,title:e,text:n,tokens:o}){o&&(n=this.parser.parseInline(o,this.parser.textRenderer));const l=cleanUrl(t);if(l===null)return escape2(n);t=l;let d=`<img src="${t}" alt="${n}"`;return e&&(d+=` title="${escape2(e)}"`),d+=">",d}text(t){return"tokens"in t&&t.tokens?this.parser.parseInline(t.tokens):"escaped"in t&&t.escaped?t.text:escape2(t.text)}},_TextRenderer=class{strong({text:t}){return t}em({text:t}){return t}codespan({text:t}){return t}del({text:t}){return t}html({text:t}){return t}text({text:t}){return t}link({text:t}){return""+t}image({text:t}){return""+t}br(){return""}},_Parser=class vn{constructor(e){Qt(this,"options");Qt(this,"renderer");Qt(this,"textRenderer");this.options=e||_defaults,this.options.renderer=this.options.renderer||new _Renderer,this.renderer=this.options.renderer,this.renderer.options=this.options,this.renderer.parser=this,this.textRenderer=new _TextRenderer}static parse(e,n){return new vn(n).parse(e)}static parseInline(e,n){return new vn(n).parseInline(e)}parse(e,n=!0){var l,d;let o="";for(let f=0;f<e.length;f++){const g=e[f];if((d=(l=this.options.extensions)==null?void 0:l.renderers)!=null&&d[g.type]){const _=g,S=this.options.extensions.renderers[_.type].call({parser:this},_);if(S!==!1||!["space","hr","heading","code","table","blockquote","list","html","paragraph","text"].includes(_.type)){o+=S||"";continue}}const b=g;switch(b.type){case"space":{o+=this.renderer.space(b);continue}case"hr":{o+=this.renderer.hr(b);continue}case"heading":{o+=this.renderer.heading(b);continue}case"code":{o+=this.renderer.code(b);continue}case"table":{o+=this.renderer.table(b);continue}case"blockquote":{o+=this.renderer.blockquote(b);continue}case"list":{o+=this.renderer.list(b);continue}case"html":{o+=this.renderer.html(b);continue}case"paragraph":{o+=this.renderer.paragraph(b);continue}case"text":{let _=b,S=this.renderer.text(_);for(;f+1<e.length&&e[f+1].type==="text";)_=e[++f],S+=`
|
|
1061
1061
|
`+this.renderer.text(_);n?o+=this.renderer.paragraph({type:"paragraph",raw:S,text:S,tokens:[{type:"text",raw:S,text:S,escaped:!0}]}):o+=S;continue}default:{const _='Token with "'+b.type+'" type was not found.';if(this.options.silent)return console.error(_),"";throw new Error(_)}}}return o}parseInline(e,n=this.renderer){var l,d;let o="";for(let f=0;f<e.length;f++){const g=e[f];if((d=(l=this.options.extensions)==null?void 0:l.renderers)!=null&&d[g.type]){const _=this.options.extensions.renderers[g.type].call({parser:this},g);if(_!==!1||!["escape","html","link","image","strong","em","codespan","br","del","text"].includes(g.type)){o+=_||"";continue}}const b=g;switch(b.type){case"escape":{o+=n.text(b);break}case"html":{o+=n.html(b);break}case"link":{o+=n.link(b);break}case"image":{o+=n.image(b);break}case"strong":{o+=n.strong(b);break}case"em":{o+=n.em(b);break}case"codespan":{o+=n.codespan(b);break}case"br":{o+=n.br(b);break}case"del":{o+=n.del(b);break}case"text":{o+=n.text(b);break}default:{const _='Token with "'+b.type+'" type was not found.';if(this.options.silent)return console.error(_),"";throw new Error(_)}}}return o}},_Hooks=(ar=class{constructor(t){Qt(this,"options");Qt(this,"block");this.options=t||_defaults}preprocess(t){return t}postprocess(t){return t}processAllTokens(t){return t}provideLexer(){return this.block?_Lexer.lex:_Lexer.lexInline}provideParser(){return this.block?_Parser.parse:_Parser.parseInline}},Qt(ar,"passThroughHooks",new Set(["preprocess","postprocess","processAllTokens"])),ar),Marked=class{constructor(...t){Qt(this,"defaults",_getDefaults());Qt(this,"options",this.setOptions);Qt(this,"parse",this.parseMarkdown(!0));Qt(this,"parseInline",this.parseMarkdown(!1));Qt(this,"Parser",_Parser);Qt(this,"Renderer",_Renderer);Qt(this,"TextRenderer",_TextRenderer);Qt(this,"Lexer",_Lexer);Qt(this,"Tokenizer",_Tokenizer);Qt(this,"Hooks",_Hooks);this.use(...t)}walkTokens(t,e){var o,l;let n=[];for(const d of t)switch(n=n.concat(e.call(this,d)),d.type){case"table":{const f=d;for(const g of f.header)n=n.concat(this.walkTokens(g.tokens,e));for(const g of f.rows)for(const b of g)n=n.concat(this.walkTokens(b.tokens,e));break}case"list":{const f=d;n=n.concat(this.walkTokens(f.items,e));break}default:{const f=d;(l=(o=this.defaults.extensions)==null?void 0:o.childTokens)!=null&&l[f.type]?this.defaults.extensions.childTokens[f.type].forEach(g=>{const b=f[g].flat(1/0);n=n.concat(this.walkTokens(b,e))}):f.tokens&&(n=n.concat(this.walkTokens(f.tokens,e)))}}return n}use(...t){const e=this.defaults.extensions||{renderers:{},childTokens:{}};return t.forEach(n=>{const o={...n};if(o.async=this.defaults.async||o.async||!1,n.extensions&&(n.extensions.forEach(l=>{if(!l.name)throw new Error("extension name required");if("renderer"in l){const d=e.renderers[l.name];d?e.renderers[l.name]=function(...f){let g=l.renderer.apply(this,f);return g===!1&&(g=d.apply(this,f)),g}:e.renderers[l.name]=l.renderer}if("tokenizer"in l){if(!l.level||l.level!=="block"&&l.level!=="inline")throw new Error("extension level must be 'block' or 'inline'");const d=e[l.level];d?d.unshift(l.tokenizer):e[l.level]=[l.tokenizer],l.start&&(l.level==="block"?e.startBlock?e.startBlock.push(l.start):e.startBlock=[l.start]:l.level==="inline"&&(e.startInline?e.startInline.push(l.start):e.startInline=[l.start]))}"childTokens"in l&&l.childTokens&&(e.childTokens[l.name]=l.childTokens)}),o.extensions=e),n.renderer){const l=this.defaults.renderer||new _Renderer(this.defaults);for(const d in n.renderer){if(!(d in l))throw new Error(`renderer '${d}' does not exist`);if(["options","parser"].includes(d))continue;const f=d,g=n.renderer[f],b=l[f];l[f]=(..._)=>{let S=g.apply(l,_);return S===!1&&(S=b.apply(l,_)),S||""}}o.renderer=l}if(n.tokenizer){const l=this.defaults.tokenizer||new _Tokenizer(this.defaults);for(const d in n.tokenizer){if(!(d in l))throw new Error(`tokenizer '${d}' does not exist`);if(["options","rules","lexer"].includes(d))continue;const f=d,g=n.tokenizer[f],b=l[f];l[f]=(..._)=>{let S=g.apply(l,_);return S===!1&&(S=b.apply(l,_)),S}}o.tokenizer=l}if(n.hooks){const l=this.defaults.hooks||new _Hooks;for(const d in n.hooks){if(!(d in l))throw new Error(`hook '${d}' does not exist`);if(["options","block"].includes(d))continue;const f=d,g=n.hooks[f],b=l[f];_Hooks.passThroughHooks.has(d)?l[f]=_=>{if(this.defaults.async)return Promise.resolve(g.call(l,_)).then(R=>b.call(l,R));const S=g.call(l,_);return b.call(l,S)}:l[f]=(..._)=>{let S=g.apply(l,_);return S===!1&&(S=b.apply(l,_)),S}}o.hooks=l}if(n.walkTokens){const l=this.defaults.walkTokens,d=n.walkTokens;o.walkTokens=function(f){let g=[];return g.push(d.call(this,f)),l&&(g=g.concat(l.call(this,f))),g}}this.defaults={...this.defaults,...o}}),this}setOptions(t){return this.defaults={...this.defaults,...t},this}lexer(t,e){return _Lexer.lex(t,e??this.defaults)}parser(t,e){return _Parser.parse(t,e??this.defaults)}parseMarkdown(t){return(n,o)=>{const l={...o},d={...this.defaults,...l},f=this.onError(!!d.silent,!!d.async);if(this.defaults.async===!0&&l.async===!1)return f(new Error("marked(): The async option was set to true by an extension. Remove async: false from the parse options object to return a Promise."));if(typeof n>"u"||n===null)return f(new Error("marked(): input parameter is undefined or null"));if(typeof n!="string")return f(new Error("marked(): input parameter is of type "+Object.prototype.toString.call(n)+", string expected"));d.hooks&&(d.hooks.options=d,d.hooks.block=t);const g=d.hooks?d.hooks.provideLexer():t?_Lexer.lex:_Lexer.lexInline,b=d.hooks?d.hooks.provideParser():t?_Parser.parse:_Parser.parseInline;if(d.async)return Promise.resolve(d.hooks?d.hooks.preprocess(n):n).then(_=>g(_,d)).then(_=>d.hooks?d.hooks.processAllTokens(_):_).then(_=>d.walkTokens?Promise.all(this.walkTokens(_,d.walkTokens)).then(()=>_):_).then(_=>b(_,d)).then(_=>d.hooks?d.hooks.postprocess(_):_).catch(f);try{d.hooks&&(n=d.hooks.preprocess(n));let _=g(n,d);d.hooks&&(_=d.hooks.processAllTokens(_)),d.walkTokens&&this.walkTokens(_,d.walkTokens);let S=b(_,d);return d.hooks&&(S=d.hooks.postprocess(S)),S}catch(_){return f(_)}}}onError(t,e){return n=>{if(n.message+=`
|
|
1062
1062
|
Please report this to https://github.com/markedjs/marked.`,t){const o="<p>An error occurred:</p><pre>"+escape2(n.message+"",!0)+"</pre>";return e?Promise.resolve(o):o}if(e)return Promise.reject(n);throw n}}},markedInstance=new Marked;function marked(t,e){return markedInstance.parse(t,e)}marked.options=marked.setOptions=function(t){return markedInstance.setOptions(t),marked.defaults=markedInstance.defaults,changeDefaults(marked.defaults),marked},marked.getDefaults=_getDefaults,marked.defaults=_defaults,marked.use=function(...t){return markedInstance.use(...t),marked.defaults=markedInstance.defaults,changeDefaults(marked.defaults),marked},marked.walkTokens=function(t,e){return markedInstance.walkTokens(t,e)},marked.parseInline=markedInstance.parseInline,marked.Parser=_Parser,marked.parser=_Parser.parse,marked.Renderer=_Renderer,marked.TextRenderer=_TextRenderer,marked.Lexer=_Lexer,marked.lexer=_Lexer.lex,marked.Tokenizer=_Tokenizer,marked.Hooks=_Hooks,marked.parse=marked,marked.options,marked.setOptions,marked.use,marked.walkTokens,marked.parseInline,_Parser.parse,_Lexer.lex;/*! @license DOMPurify 3.2.6 | (c) Cure53 and other contributors | Released under the Apache license 2.0 and Mozilla Public License 2.0 | github.com/cure53/DOMPurify/blob/3.2.6/LICENSE */const{entries,setPrototypeOf,isFrozen,getPrototypeOf,getOwnPropertyDescriptor}=Object;let{freeze,seal,create}=Object,{apply:apply$1,construct}=typeof Reflect<"u"&&Reflect;freeze||(freeze=function(e){return e}),seal||(seal=function(e){return e}),apply$1||(apply$1=function(e,n,o){return e.apply(n,o)}),construct||(construct=function(e,n){return new e(...n)});const arrayForEach=unapply(Array.prototype.forEach),arrayLastIndexOf=unapply(Array.prototype.lastIndexOf),arrayPop=unapply(Array.prototype.pop),arrayPush=unapply(Array.prototype.push),arraySplice=unapply(Array.prototype.splice),stringToLowerCase=unapply(String.prototype.toLowerCase),stringToString=unapply(String.prototype.toString),stringMatch=unapply(String.prototype.match),stringReplace=unapply(String.prototype.replace),stringIndexOf=unapply(String.prototype.indexOf),stringTrim=unapply(String.prototype.trim),objectHasOwnProperty=unapply(Object.prototype.hasOwnProperty),regExpTest=unapply(RegExp.prototype.test),typeErrorCreate=unconstruct(TypeError);function unapply(t){return function(e){e instanceof RegExp&&(e.lastIndex=0);for(var n=arguments.length,o=new Array(n>1?n-1:0),l=1;l<n;l++)o[l-1]=arguments[l];return apply$1(t,e,o)}}function unconstruct(t){return function(){for(var e=arguments.length,n=new Array(e),o=0;o<e;o++)n[o]=arguments[o];return construct(t,n)}}function addToSet(t,e){let n=arguments.length>2&&arguments[2]!==void 0?arguments[2]:stringToLowerCase;setPrototypeOf&&setPrototypeOf(t,null);let o=e.length;for(;o--;){let l=e[o];if(typeof l=="string"){const d=n(l);d!==l&&(isFrozen(e)||(e[o]=d),l=d)}t[l]=!0}return t}function cleanArray(t){for(let e=0;e<t.length;e++)objectHasOwnProperty(t,e)||(t[e]=null);return t}function clone(t){const e=create(null);for(const[n,o]of entries(t))objectHasOwnProperty(t,n)&&(Array.isArray(o)?e[n]=cleanArray(o):o&&typeof o=="object"&&o.constructor===Object?e[n]=clone(o):e[n]=o);return e}function lookupGetter(t,e){for(;t!==null;){const o=getOwnPropertyDescriptor(t,e);if(o){if(o.get)return unapply(o.get);if(typeof o.value=="function")return unapply(o.value)}t=getPrototypeOf(t)}function n(){return null}return n}const html$1=freeze(["a","abbr","acronym","address","area","article","aside","audio","b","bdi","bdo","big","blink","blockquote","body","br","button","canvas","caption","center","cite","code","col","colgroup","content","data","datalist","dd","decorator","del","details","dfn","dialog","dir","div","dl","dt","element","em","fieldset","figcaption","figure","font","footer","form","h1","h2","h3","h4","h5","h6","head","header","hgroup","hr","html","i","img","input","ins","kbd","label","legend","li","main","map","mark","marquee","menu","menuitem","meter","nav","nobr","ol","optgroup","option","output","p","picture","pre","progress","q","rp","rt","ruby","s","samp","section","select","shadow","small","source","spacer","span","strike","strong","style","sub","summary","sup","table","tbody","td","template","textarea","tfoot","th","thead","time","tr","track","tt","u","ul","var","video","wbr"]),svg$1=freeze(["svg","a","altglyph","altglyphdef","altglyphitem","animatecolor","animatemotion","animatetransform","circle","clippath","defs","desc","ellipse","filter","font","g","glyph","glyphref","hkern","image","line","lineargradient","marker","mask","metadata","mpath","path","pattern","polygon","polyline","radialgradient","rect","stop","style","switch","symbol","text","textpath","title","tref","tspan","view","vkern"]),svgFilters=freeze(["feBlend","feColorMatrix","feComponentTransfer","feComposite","feConvolveMatrix","feDiffuseLighting","feDisplacementMap","feDistantLight","feDropShadow","feFlood","feFuncA","feFuncB","feFuncG","feFuncR","feGaussianBlur","feImage","feMerge","feMergeNode","feMorphology","feOffset","fePointLight","feSpecularLighting","feSpotLight","feTile","feTurbulence"]),svgDisallowed=freeze(["animate","color-profile","cursor","discard","font-face","font-face-format","font-face-name","font-face-src","font-face-uri","foreignobject","hatch","hatchpath","mesh","meshgradient","meshpatch","meshrow","missing-glyph","script","set","solidcolor","unknown","use"]),mathMl$1=freeze(["math","menclose","merror","mfenced","mfrac","mglyph","mi","mlabeledtr","mmultiscripts","mn","mo","mover","mpadded","mphantom","mroot","mrow","ms","mspace","msqrt","mstyle","msub","msup","msubsup","mtable","mtd","mtext","mtr","munder","munderover","mprescripts"]),mathMlDisallowed=freeze(["maction","maligngroup","malignmark","mlongdiv","mscarries","mscarry","msgroup","mstack","msline","msrow","semantics","annotation","annotation-xml","mprescripts","none"]),text$1=freeze(["#text"]),html=freeze(["accept","action","align","alt","autocapitalize","autocomplete","autopictureinpicture","autoplay","background","bgcolor","border","capture","cellpadding","cellspacing","checked","cite","class","clear","color","cols","colspan","controls","controlslist","coords","crossorigin","datetime","decoding","default","dir","disabled","disablepictureinpicture","disableremoteplayback","download","draggable","enctype","enterkeyhint","face","for","headers","height","hidden","high","href","hreflang","id","inputmode","integrity","ismap","kind","label","lang","list","loading","loop","low","max","maxlength","media","method","min","minlength","multiple","muted","name","nonce","noshade","novalidate","nowrap","open","optimum","pattern","placeholder","playsinline","popover","popovertarget","popovertargetaction","poster","preload","pubdate","radiogroup","readonly","rel","required","rev","reversed","role","rows","rowspan","spellcheck","scope","selected","shape","size","sizes","span","srclang","start","src","srcset","step","style","summary","tabindex","title","translate","type","usemap","valign","value","width","wrap","xmlns","slot"]),svg=freeze(["accent-height","accumulate","additive","alignment-baseline","amplitude","ascent","attributename","attributetype","azimuth","basefrequency","baseline-shift","begin","bias","by","class","clip","clippathunits","clip-path","clip-rule","color","color-interpolation","color-interpolation-filters","color-profile","color-rendering","cx","cy","d","dx","dy","diffuseconstant","direction","display","divisor","dur","edgemode","elevation","end","exponent","fill","fill-opacity","fill-rule","filter","filterunits","flood-color","flood-opacity","font-family","font-size","font-size-adjust","font-stretch","font-style","font-variant","font-weight","fx","fy","g1","g2","glyph-name","glyphref","gradientunits","gradienttransform","height","href","id","image-rendering","in","in2","intercept","k","k1","k2","k3","k4","kerning","keypoints","keysplines","keytimes","lang","lengthadjust","letter-spacing","kernelmatrix","kernelunitlength","lighting-color","local","marker-end","marker-mid","marker-start","markerheight","markerunits","markerwidth","maskcontentunits","maskunits","max","mask","media","method","mode","min","name","numoctaves","offset","operator","opacity","order","orient","orientation","origin","overflow","paint-order","path","pathlength","patterncontentunits","patterntransform","patternunits","points","preservealpha","preserveaspectratio","primitiveunits","r","rx","ry","radius","refx","refy","repeatcount","repeatdur","restart","result","rotate","scale","seed","shape-rendering","slope","specularconstant","specularexponent","spreadmethod","startoffset","stddeviation","stitchtiles","stop-color","stop-opacity","stroke-dasharray","stroke-dashoffset","stroke-linecap","stroke-linejoin","stroke-miterlimit","stroke-opacity","stroke","stroke-width","style","surfacescale","systemlanguage","tabindex","tablevalues","targetx","targety","transform","transform-origin","text-anchor","text-decoration","text-rendering","textlength","type","u1","u2","unicode","values","viewbox","visibility","version","vert-adv-y","vert-origin-x","vert-origin-y","width","word-spacing","wrap","writing-mode","xchannelselector","ychannelselector","x","x1","x2","xmlns","y","y1","y2","z","zoomandpan"]),mathMl=freeze(["accent","accentunder","align","bevelled","close","columnsalign","columnlines","columnspan","denomalign","depth","dir","display","displaystyle","encoding","fence","frame","height","href","id","largeop","length","linethickness","lspace","lquote","mathbackground","mathcolor","mathsize","mathvariant","maxsize","minsize","movablelimits","notation","numalign","open","rowalign","rowlines","rowspacing","rowspan","rspace","rquote","scriptlevel","scriptminsize","scriptsizemultiplier","selection","separator","separators","stretchy","subscriptshift","supscriptshift","symmetric","voffset","width","xmlns"]),xml=freeze(["xlink:href","xml:id","xlink:title","xml:space","xmlns:xlink"]),MUSTACHE_EXPR=seal(/\{\{[\w\W]*|[\w\W]*\}\}/gm),ERB_EXPR=seal(/<%[\w\W]*|[\w\W]*%>/gm),TMPLIT_EXPR=seal(/\$\{[\w\W]*/gm),DATA_ATTR=seal(/^data-[\-\w.\u00B7-\uFFFF]+$/),ARIA_ATTR=seal(/^aria-[\-\w]+$/),IS_ALLOWED_URI=seal(/^(?:(?:(?:f|ht)tps?|mailto|tel|callto|sms|cid|xmpp|matrix):|[^a-z]|[a-z+.\-]+(?:[^a-z+.\-:]|$))/i),IS_SCRIPT_OR_DATA=seal(/^(?:\w+script|data):/i),ATTR_WHITESPACE=seal(/[\u0000-\u0020\u00A0\u1680\u180E\u2000-\u2029\u205F\u3000]/g),DOCTYPE_NAME=seal(/^html$/i),CUSTOM_ELEMENT=seal(/^[a-z][.\w]*(-[.\w]+)+$/i);var EXPRESSIONS=Object.freeze({__proto__:null,ARIA_ATTR,ATTR_WHITESPACE,CUSTOM_ELEMENT,DATA_ATTR,DOCTYPE_NAME,ERB_EXPR,IS_ALLOWED_URI,IS_SCRIPT_OR_DATA,MUSTACHE_EXPR,TMPLIT_EXPR});const NODE_TYPE={element:1,text:3,progressingInstruction:7,comment:8,document:9},getGlobal=function t(){return typeof window>"u"?null:window},_createTrustedTypesPolicy=function t(e,n){if(typeof e!="object"||typeof e.createPolicy!="function")return null;let o=null;const l="data-tt-policy-suffix";n&&n.hasAttribute(l)&&(o=n.getAttribute(l));const d="dompurify"+(o?"#"+o:"");try{return e.createPolicy(d,{createHTML(f){return f},createScriptURL(f){return f}})}catch{return console.warn("TrustedTypes policy "+d+" could not be created."),null}},_createHooksMap=function t(){return{afterSanitizeAttributes:[],afterSanitizeElements:[],afterSanitizeShadowDOM:[],beforeSanitizeAttributes:[],beforeSanitizeElements:[],beforeSanitizeShadowDOM:[],uponSanitizeAttribute:[],uponSanitizeElement:[],uponSanitizeShadowNode:[]}};function createDOMPurify(){let t=arguments.length>0&&arguments[0]!==void 0?arguments[0]:getGlobal();const e=Wt=>createDOMPurify(Wt);if(e.version="3.2.6",e.removed=[],!t||!t.document||t.document.nodeType!==NODE_TYPE.document||!t.Element)return e.isSupported=!1,e;let{document:n}=t;const o=n,l=o.currentScript,{DocumentFragment:d,HTMLTemplateElement:f,Node:g,Element:b,NodeFilter:_,NamedNodeMap:S=t.NamedNodeMap||t.MozNamedAttrMap,HTMLFormElement:R,DOMParser:C,trustedTypes:E}=t,A=b.prototype,M=lookupGetter(A,"cloneNode"),I=lookupGetter(A,"remove"),j=lookupGetter(A,"nextSibling"),q=lookupGetter(A,"childNodes"),z=lookupGetter(A,"parentNode");if(typeof f=="function"){const Wt=n.createElement("template");Wt.content&&Wt.content.ownerDocument&&(n=Wt.content.ownerDocument)}let Q,F="";const{implementation:V,createNodeIterator:te,createDocumentFragment:ne,getElementsByTagName:se}=n,{importNode:ge}=o;let oe=_createHooksMap();e.isSupported=typeof entries=="function"&&typeof z=="function"&&V&&V.createHTMLDocument!==void 0;const{MUSTACHE_EXPR:Ae,ERB_EXPR:je,TMPLIT_EXPR:Ne,DATA_ATTR:Oe,ARIA_ATTR:Fe,IS_SCRIPT_OR_DATA:ze,ATTR_WHITESPACE:$e,CUSTOM_ELEMENT:Be}=EXPRESSIONS;let{IS_ALLOWED_URI:qe}=EXPRESSIONS,Ge=null;const He=addToSet({},[...html$1,...svg$1,...svgFilters,...mathMl$1,...text$1]);let Ze=null;const tt=addToSet({},[...html,...svg,...mathMl,...xml]);let Ye=Object.seal(create(null,{tagNameCheck:{writable:!0,configurable:!1,enumerable:!0,value:null},attributeNameCheck:{writable:!0,configurable:!1,enumerable:!0,value:null},allowCustomizedBuiltInElements:{writable:!0,configurable:!1,enumerable:!0,value:!1}})),Qe=null,Xe=null,st=!0,rt=!0,at=!1,ot=!0,Ue=!1,Ct=!0,Je=!1,yt=!1,Mt=!1,qt=!1,Ht=!1,Ft=!1,Ke=!0,it=!1;const et="user-content-";let ct=!0,ft=!1,dt={},Rt=null;const zt=addToSet({},["annotation-xml","audio","colgroup","desc","foreignobject","head","iframe","math","mi","mn","mo","ms","mtext","noembed","noframes","noscript","plaintext","script","style","svg","template","thead","title","video","xmp"]);let Yt=null;const sr=addToSet({},["audio","video","img","source","image","track"]);let dr=null;const mt=addToSet({},["alt","class","for","id","label","name","pattern","placeholder","role","summary","title","value","style","xmlns"]),Sr="http://www.w3.org/1998/Math/MathML",pt="http://www.w3.org/2000/svg",Zt="http://www.w3.org/1999/xhtml";let Kt=Zt,ur=!1,or=null;const Rr=addToSet({},[Sr,pt,Zt],stringToString);let Er=addToSet({},["mi","mo","mn","ms","mtext"]),gr=addToSet({},["annotation-xml"]);const xr=addToSet({},["title","style","font","a","script"]);let tr=null;const $r=["application/xhtml+xml","text/html"],Xt="text/html";let mr=null,jr=null;const gn=n.createElement("form"),Lr=function(nt){return nt instanceof RegExp||nt instanceof Function},Ar=function(){let nt=arguments.length>0&&arguments[0]!==void 0?arguments[0]:{};if(!(jr&&jr===nt)){if((!nt||typeof nt!="object")&&(nt={}),nt=clone(nt),tr=$r.indexOf(nt.PARSER_MEDIA_TYPE)===-1?Xt:nt.PARSER_MEDIA_TYPE,mr=tr==="application/xhtml+xml"?stringToString:stringToLowerCase,Ge=objectHasOwnProperty(nt,"ALLOWED_TAGS")?addToSet({},nt.ALLOWED_TAGS,mr):He,Ze=objectHasOwnProperty(nt,"ALLOWED_ATTR")?addToSet({},nt.ALLOWED_ATTR,mr):tt,or=objectHasOwnProperty(nt,"ALLOWED_NAMESPACES")?addToSet({},nt.ALLOWED_NAMESPACES,stringToString):Rr,dr=objectHasOwnProperty(nt,"ADD_URI_SAFE_ATTR")?addToSet(clone(mt),nt.ADD_URI_SAFE_ATTR,mr):mt,Yt=objectHasOwnProperty(nt,"ADD_DATA_URI_TAGS")?addToSet(clone(sr),nt.ADD_DATA_URI_TAGS,mr):sr,Rt=objectHasOwnProperty(nt,"FORBID_CONTENTS")?addToSet({},nt.FORBID_CONTENTS,mr):zt,Qe=objectHasOwnProperty(nt,"FORBID_TAGS")?addToSet({},nt.FORBID_TAGS,mr):clone({}),Xe=objectHasOwnProperty(nt,"FORBID_ATTR")?addToSet({},nt.FORBID_ATTR,mr):clone({}),dt=objectHasOwnProperty(nt,"USE_PROFILES")?nt.USE_PROFILES:!1,st=nt.ALLOW_ARIA_ATTR!==!1,rt=nt.ALLOW_DATA_ATTR!==!1,at=nt.ALLOW_UNKNOWN_PROTOCOLS||!1,ot=nt.ALLOW_SELF_CLOSE_IN_ATTR!==!1,Ue=nt.SAFE_FOR_TEMPLATES||!1,Ct=nt.SAFE_FOR_XML!==!1,Je=nt.WHOLE_DOCUMENT||!1,qt=nt.RETURN_DOM||!1,Ht=nt.RETURN_DOM_FRAGMENT||!1,Ft=nt.RETURN_TRUSTED_TYPE||!1,Mt=nt.FORCE_BODY||!1,Ke=nt.SANITIZE_DOM!==!1,it=nt.SANITIZE_NAMED_PROPS||!1,ct=nt.KEEP_CONTENT!==!1,ft=nt.IN_PLACE||!1,qe=nt.ALLOWED_URI_REGEXP||IS_ALLOWED_URI,Kt=nt.NAMESPACE||Zt,Er=nt.MATHML_TEXT_INTEGRATION_POINTS||Er,gr=nt.HTML_INTEGRATION_POINTS||gr,Ye=nt.CUSTOM_ELEMENT_HANDLING||{},nt.CUSTOM_ELEMENT_HANDLING&&Lr(nt.CUSTOM_ELEMENT_HANDLING.tagNameCheck)&&(Ye.tagNameCheck=nt.CUSTOM_ELEMENT_HANDLING.tagNameCheck),nt.CUSTOM_ELEMENT_HANDLING&&Lr(nt.CUSTOM_ELEMENT_HANDLING.attributeNameCheck)&&(Ye.attributeNameCheck=nt.CUSTOM_ELEMENT_HANDLING.attributeNameCheck),nt.CUSTOM_ELEMENT_HANDLING&&typeof nt.CUSTOM_ELEMENT_HANDLING.allowCustomizedBuiltInElements=="boolean"&&(Ye.allowCustomizedBuiltInElements=nt.CUSTOM_ELEMENT_HANDLING.allowCustomizedBuiltInElements),Ue&&(rt=!1),Ht&&(qt=!0),dt&&(Ge=addToSet({},text$1),Ze=[],dt.html===!0&&(addToSet(Ge,html$1),addToSet(Ze,html)),dt.svg===!0&&(addToSet(Ge,svg$1),addToSet(Ze,svg),addToSet(Ze,xml)),dt.svgFilters===!0&&(addToSet(Ge,svgFilters),addToSet(Ze,svg),addToSet(Ze,xml)),dt.mathMl===!0&&(addToSet(Ge,mathMl$1),addToSet(Ze,mathMl),addToSet(Ze,xml))),nt.ADD_TAGS&&(Ge===He&&(Ge=clone(Ge)),addToSet(Ge,nt.ADD_TAGS,mr)),nt.ADD_ATTR&&(Ze===tt&&(Ze=clone(Ze)),addToSet(Ze,nt.ADD_ATTR,mr)),nt.ADD_URI_SAFE_ATTR&&addToSet(dr,nt.ADD_URI_SAFE_ATTR,mr),nt.FORBID_CONTENTS&&(Rt===zt&&(Rt=clone(Rt)),addToSet(Rt,nt.FORBID_CONTENTS,mr)),ct&&(Ge["#text"]=!0),Je&&addToSet(Ge,["html","head","body"]),Ge.table&&(addToSet(Ge,["tbody"]),delete Qe.tbody),nt.TRUSTED_TYPES_POLICY){if(typeof nt.TRUSTED_TYPES_POLICY.createHTML!="function")throw typeErrorCreate('TRUSTED_TYPES_POLICY configuration option must provide a "createHTML" hook.');if(typeof nt.TRUSTED_TYPES_POLICY.createScriptURL!="function")throw typeErrorCreate('TRUSTED_TYPES_POLICY configuration option must provide a "createScriptURL" hook.');Q=nt.TRUSTED_TYPES_POLICY,F=Q.createHTML("")}else Q===void 0&&(Q=_createTrustedTypesPolicy(E,l)),Q!==null&&typeof F=="string"&&(F=Q.createHTML(""));freeze&&freeze(nt),jr=nt}},sn=addToSet({},[...svg$1,...svgFilters,...svgDisallowed]),Dr=addToSet({},[...mathMl$1,...mathMlDisallowed]),Fr=function(nt){let It=z(nt);(!It||!It.tagName)&&(It={namespaceURI:Kt,tagName:"template"});const Ut=stringToLowerCase(nt.tagName),cr=stringToLowerCase(It.tagName);return or[nt.namespaceURI]?nt.namespaceURI===pt?It.namespaceURI===Zt?Ut==="svg":It.namespaceURI===Sr?Ut==="svg"&&(cr==="annotation-xml"||Er[cr]):!!sn[Ut]:nt.namespaceURI===Sr?It.namespaceURI===Zt?Ut==="math":It.namespaceURI===pt?Ut==="math"&&gr[cr]:!!Dr[Ut]:nt.namespaceURI===Zt?It.namespaceURI===pt&&!gr[cr]||It.namespaceURI===Sr&&!Er[cr]?!1:!Dr[Ut]&&(xr[Ut]||!sn[Ut]):!!(tr==="application/xhtml+xml"&&or[nt.namespaceURI]):!1},Pr=function(nt){arrayPush(e.removed,{element:nt});try{z(nt).removeChild(nt)}catch{I(nt)}},Or=function(nt,It){try{arrayPush(e.removed,{attribute:It.getAttributeNode(nt),from:It})}catch{arrayPush(e.removed,{attribute:null,from:It})}if(It.removeAttribute(nt),nt==="is")if(qt||Ht)try{Pr(It)}catch{}else try{It.setAttribute(nt,"")}catch{}},Xr=function(nt){let It=null,Ut=null;if(Mt)nt="<remove></remove>"+nt;else{const pr=stringMatch(nt,/^[\r\n\t ]+/);Ut=pr&&pr[0]}tr==="application/xhtml+xml"&&Kt===Zt&&(nt='<html xmlns="http://www.w3.org/1999/xhtml"><head></head><body>'+nt+"</body></html>");const cr=Q?Q.createHTML(nt):nt;if(Kt===Zt)try{It=new C().parseFromString(cr,tr)}catch{}if(!It||!It.documentElement){It=V.createDocument(Kt,"template",null);try{It.documentElement.innerHTML=ur?F:cr}catch{}}const vr=It.body||It.documentElement;return nt&&Ut&&vr.insertBefore(n.createTextNode(Ut),vr.childNodes[0]||null),Kt===Zt?se.call(It,Je?"html":"body")[0]:Je?It.documentElement:vr},Jr=function(nt){return te.call(nt.ownerDocument||nt,nt,_.SHOW_ELEMENT|_.SHOW_COMMENT|_.SHOW_TEXT|_.SHOW_PROCESSING_INSTRUCTION|_.SHOW_CDATA_SECTION,null)},Gr=function(nt){return nt instanceof R&&(typeof nt.nodeName!="string"||typeof nt.textContent!="string"||typeof nt.removeChild!="function"||!(nt.attributes instanceof S)||typeof nt.removeAttribute!="function"||typeof nt.setAttribute!="function"||typeof nt.namespaceURI!="string"||typeof nt.insertBefore!="function"||typeof nt.hasChildNodes!="function")},Qr=function(nt){return typeof g=="function"&&nt instanceof g};function Nr(Wt,nt,It){arrayForEach(Wt,Ut=>{Ut.call(e,nt,It,jr)})}const on=function(nt){let It=null;if(Nr(oe.beforeSanitizeElements,nt,null),Gr(nt))return Pr(nt),!0;const Ut=mr(nt.nodeName);if(Nr(oe.uponSanitizeElement,nt,{tagName:Ut,allowedTags:Ge}),Ct&&nt.hasChildNodes()&&!Qr(nt.firstElementChild)&®ExpTest(/<[/\w!]/g,nt.innerHTML)&®ExpTest(/<[/\w!]/g,nt.textContent)||nt.nodeType===NODE_TYPE.progressingInstruction||Ct&&nt.nodeType===NODE_TYPE.comment&®ExpTest(/<[/\w]/g,nt.data))return Pr(nt),!0;if(!Ge[Ut]||Qe[Ut]){if(!Qe[Ut]&&dn(Ut)&&(Ye.tagNameCheck instanceof RegExp&®ExpTest(Ye.tagNameCheck,Ut)||Ye.tagNameCheck instanceof Function&&Ye.tagNameCheck(Ut)))return!1;if(ct&&!Rt[Ut]){const cr=z(nt)||nt.parentNode,vr=q(nt)||nt.childNodes;if(vr&&cr){const pr=vr.length;for(let _r=pr-1;_r>=0;--_r){const Cr=M(vr[_r],!0);Cr.__removalCount=(nt.__removalCount||0)+1,cr.insertBefore(Cr,j(nt))}}}return Pr(nt),!0}return nt instanceof b&&!Fr(nt)||(Ut==="noscript"||Ut==="noembed"||Ut==="noframes")&®ExpTest(/<\/no(script|embed|frames)/i,nt.innerHTML)?(Pr(nt),!0):(Ue&&nt.nodeType===NODE_TYPE.text&&(It=nt.textContent,arrayForEach([Ae,je,Ne],cr=>{It=stringReplace(It,cr," ")}),nt.textContent!==It&&(arrayPush(e.removed,{element:nt.cloneNode()}),nt.textContent=It)),Nr(oe.afterSanitizeElements,nt,null),!1)},un=function(nt,It,Ut){if(Ke&&(It==="id"||It==="name")&&(Ut in n||Ut in gn))return!1;if(!(rt&&!Xe[It]&®ExpTest(Oe,It))){if(!(st&®ExpTest(Fe,It))){if(!Ze[It]||Xe[It]){if(!(dn(nt)&&(Ye.tagNameCheck instanceof RegExp&®ExpTest(Ye.tagNameCheck,nt)||Ye.tagNameCheck instanceof Function&&Ye.tagNameCheck(nt))&&(Ye.attributeNameCheck instanceof RegExp&®ExpTest(Ye.attributeNameCheck,It)||Ye.attributeNameCheck instanceof Function&&Ye.attributeNameCheck(It))||It==="is"&&Ye.allowCustomizedBuiltInElements&&(Ye.tagNameCheck instanceof RegExp&®ExpTest(Ye.tagNameCheck,Ut)||Ye.tagNameCheck instanceof Function&&Ye.tagNameCheck(Ut))))return!1}else if(!dr[It]){if(!regExpTest(qe,stringReplace(Ut,$e,""))){if(!((It==="src"||It==="xlink:href"||It==="href")&&nt!=="script"&&stringIndexOf(Ut,"data:")===0&&Yt[nt])){if(!(at&&!regExpTest(ze,stringReplace(Ut,$e,"")))){if(Ut)return!1}}}}}}return!0},dn=function(nt){return nt!=="annotation-xml"&&stringMatch(nt,Be)},en=function(nt){Nr(oe.beforeSanitizeAttributes,nt,null);const{attributes:It}=nt;if(!It||Gr(nt))return;const Ut={attrName:"",attrValue:"",keepAttr:!0,allowedAttributes:Ze,forceKeepAttr:void 0};let cr=It.length;for(;cr--;){const vr=It[cr],{name:pr,namespaceURI:_r,value:Cr}=vr,Br=mr(pr),tn=Cr;let Vt=pr==="value"?tn:stringTrim(tn);if(Ut.attrName=Br,Ut.attrValue=Vt,Ut.keepAttr=!0,Ut.forceKeepAttr=void 0,Nr(oe.uponSanitizeAttribute,nt,Ut),Vt=Ut.attrValue,it&&(Br==="id"||Br==="name")&&(Or(pr,nt),Vt=et+Vt),Ct&®ExpTest(/((--!?|])>)|<\/(style|title)/i,Vt)){Or(pr,nt);continue}if(Ut.forceKeepAttr)continue;if(!Ut.keepAttr){Or(pr,nt);continue}if(!ot&®ExpTest(/\/>/i,Vt)){Or(pr,nt);continue}Ue&&arrayForEach([Ae,je,Ne],Tr=>{Vt=stringReplace(Vt,Tr," ")});const qr=mr(nt.nodeName);if(!un(qr,Br,Vt)){Or(pr,nt);continue}if(Q&&typeof E=="object"&&typeof E.getAttributeType=="function"&&!_r)switch(E.getAttributeType(qr,Br)){case"TrustedHTML":{Vt=Q.createHTML(Vt);break}case"TrustedScriptURL":{Vt=Q.createScriptURL(Vt);break}}if(Vt!==tn)try{_r?nt.setAttributeNS(_r,pr,Vt):nt.setAttribute(pr,Vt),Gr(nt)?Pr(nt):arrayPop(e.removed)}catch{Or(pr,nt)}}Nr(oe.afterSanitizeAttributes,nt,null)},fn=function Wt(nt){let It=null;const Ut=Jr(nt);for(Nr(oe.beforeSanitizeShadowDOM,nt,null);It=Ut.nextNode();)Nr(oe.uponSanitizeShadowNode,It,null),on(It),en(It),It.content instanceof d&&Wt(It.content);Nr(oe.afterSanitizeShadowDOM,nt,null)};return e.sanitize=function(Wt){let nt=arguments.length>1&&arguments[1]!==void 0?arguments[1]:{},It=null,Ut=null,cr=null,vr=null;if(ur=!Wt,ur&&(Wt="<!-->"),typeof Wt!="string"&&!Qr(Wt))if(typeof Wt.toString=="function"){if(Wt=Wt.toString(),typeof Wt!="string")throw typeErrorCreate("dirty is not a string, aborting")}else throw typeErrorCreate("toString is not a function");if(!e.isSupported)return Wt;if(yt||Ar(nt),e.removed=[],typeof Wt=="string"&&(ft=!1),ft){if(Wt.nodeName){const Cr=mr(Wt.nodeName);if(!Ge[Cr]||Qe[Cr])throw typeErrorCreate("root node is forbidden and cannot be sanitized in-place")}}else if(Wt instanceof g)It=Xr("<!---->"),Ut=It.ownerDocument.importNode(Wt,!0),Ut.nodeType===NODE_TYPE.element&&Ut.nodeName==="BODY"||Ut.nodeName==="HTML"?It=Ut:It.appendChild(Ut);else{if(!qt&&!Ue&&!Je&&Wt.indexOf("<")===-1)return Q&&Ft?Q.createHTML(Wt):Wt;if(It=Xr(Wt),!It)return qt?null:Ft?F:""}It&&Mt&&Pr(It.firstChild);const pr=Jr(ft?Wt:It);for(;cr=pr.nextNode();)on(cr),en(cr),cr.content instanceof d&&fn(cr.content);if(ft)return Wt;if(qt){if(Ht)for(vr=ne.call(It.ownerDocument);It.firstChild;)vr.appendChild(It.firstChild);else vr=It;return(Ze.shadowroot||Ze.shadowrootmode)&&(vr=ge.call(o,vr,!0)),vr}let _r=Je?It.outerHTML:It.innerHTML;return Je&&Ge["!doctype"]&&It.ownerDocument&&It.ownerDocument.doctype&&It.ownerDocument.doctype.name&®ExpTest(DOCTYPE_NAME,It.ownerDocument.doctype.name)&&(_r="<!DOCTYPE "+It.ownerDocument.doctype.name+`>
|
|
1063
|
-
`+_r),Ue&&arrayForEach([Ae,je,Ne],Cr=>{_r=stringReplace(_r,Cr," ")}),Q&&Ft?Q.createHTML(_r):_r},e.setConfig=function(){let Wt=arguments.length>0&&arguments[0]!==void 0?arguments[0]:{};Ar(Wt),yt=!0},e.clearConfig=function(){jr=null,yt=!1},e.isValidAttribute=function(Wt,nt,It){jr||Ar({});const Ut=mr(Wt),cr=mr(nt);return un(Ut,cr,It)},e.addHook=function(Wt,nt){typeof nt=="function"&&arrayPush(oe[Wt],nt)},e.removeHook=function(Wt,nt){if(nt!==void 0){const It=arrayLastIndexOf(oe[Wt],nt);return It===-1?void 0:arraySplice(oe[Wt],It,1)[0]}return arrayPop(oe[Wt])},e.removeHooks=function(Wt){oe[Wt]=[]},e.removeAllHooks=function(){oe=_createHooksMap()},e}var purify=createDOMPurify();function markdownToSafeHTML(t){var e=marked(t,{async:!1});return purify.sanitize(e,{ALLOWED_TAGS:["h1","h2","h3","h4","h5","h6","b","strong","i","em","u","s","sub","sup","mark","code","pre","blockquote","q","ul","ol","li","dl","dt","dd","p","div","span","br","hr","table","thead","tbody","tfoot","tr","th","td"]})}function SkeletonMessage({botStatus:t}){return jsxRuntime.jsxs("div",{className:"flex items-start gap-2",children:[jsxRuntime.jsx("div",{className:"h-8 w-8 mt-1 rounded-full bg-gray-300 animate-pulse flex-shrink-0"}),jsxRuntime.jsxs("div",{className:"flex flex-col max-w-[70%]",children:[jsxRuntime.jsxs("p",{className:"mb-1",children:["Assistant",jsxRuntime.jsx("span",{className:"text-xs text-muted-foreground mt-1 ml-3",children:new Date().toLocaleTimeString([],{hour:"numeric",minute:"2-digit",hour12:!0})})]}),jsxRuntime.jsx("div",{className:"rounded-md p-3 break-words bg-white border rounded-tl-none",children:jsxRuntime.jsxs("div",{className:"flex items-center space-x-2",children:[jsxRuntime.jsx("div",{className:"h-2 w-2 rounded-full bg-primary animate-pulse"}),jsxRuntime.jsx("div",{className:"h-2 w-2 rounded-full bg-primary animate-pulse delay-150"}),jsxRuntime.jsx("div",{className:"h-2 w-2 rounded-full bg-primary animate-pulse delay-300"}),jsxRuntime.jsx("span",{className:"text-xs text-muted-foreground ml-1",children:t})]})})]})]})}function ChatMessages({messages:t,currentUserId:e,botStatus:n,isAssistantChat:o}){return jsxRuntime.jsxs("div",{children:[t.map(l=>{const d=l.fromPartnerID===e;return jsxRuntime.jsxs("div",{className:cn("flex items-start gap-2 mt-2 mb-2",d&&"flex-row-reverse"),children:[jsxRuntime.jsx(Avatar,{className:"h-8 w-8 mt-1",children:jsxRuntime.jsx(AvatarImage,{src:`https://api.dicebear.com/9.x/thumbs/svg?seed=${md5(l.senderName+l.fromPartnerID)}&flip=${d}`})}),jsxRuntime.jsxs("div",{className:"flex flex-col max-w-[70%]",children:[jsxRuntime.jsxs("p",{className:"mb-1",children:[l.senderName,jsxRuntime.jsx("span",{className:"text-xs text-muted-foreground mt-1 ml-3",children:(()=>{const f=new Date(l.timestamp);return isToday(f)?f.toLocaleTimeString([],{hour:"numeric",minute:"2-digit",hour12:!0}):isYesterday(f)?`Yesterday, ${f.toLocaleTimeString([],{hour:"numeric",minute:"2-digit",hour12:!0})}`:`${f.toLocaleDateString([],{month:"short",day:"numeric"})} ${f.toLocaleTimeString([],{hour:"numeric",minute:"2-digit",hour12:!0})}`})()})]}),jsxRuntime.jsx("div",{className:cn("rounded-md p-3 break-words [&_li]:ml-6 [&_li]:list-disc [&_h1]:text-lg [&_h1]:font-bold [&_h1]:mt-4 [&_h2]:font-bold [&_h2]:mt-4 [&_h3]:mt-4 ",d?"bg-primary text-white rounded-tr-none":"bg-white border rounded-tl-none"),children:parser(markdownToSafeHTML(l.content))})]})]},l.id)}),n!==""&&jsxRuntime.jsx(SkeletonMessage,{botStatus:n}),t.length===0&&!o&&jsxRuntime.jsx("div",{className:"text-center text-muted-foreground py-8",children:"No messages yet"}),t.length===0&&n===""&&o&&jsxRuntime.jsxs("div",{className:"text-center py-8",children:[jsxRuntime.jsx("p",{children:"The Randmar Assistant is ready to help you. Ask anything about products, orders, carts, shipments and tracking numbers."}),jsxRuntime.jsx("p",{children:jsxRuntime.jsx("strong",{children:'Try it now, type "my open orders"!'})})]})]})}var SWITCH_NAME="Switch",[createSwitchContext,createSwitchScope]=createContextScope(SWITCH_NAME),[SwitchProvider,useSwitchContext]=createSwitchContext(SWITCH_NAME),Switch$1=React__namespace.forwardRef((t,e)=>{const{__scopeSwitch:n,name:o,checked:l,defaultChecked:d,required:f,disabled:g,value:b="on",onCheckedChange:_,form:S,...R}=t,[C,E]=React__namespace.useState(null),A=useComposedRefs(e,z=>E(z)),M=React__namespace.useRef(!1),I=C?S||!!C.closest("form"):!0,[j,q]=useControllableState({prop:l,defaultProp:d??!1,onChange:_,caller:SWITCH_NAME});return jsxRuntime.jsxs(SwitchProvider,{scope:n,checked:j,disabled:g,children:[jsxRuntime.jsx(Primitive.button,{type:"button",role:"switch","aria-checked":j,"aria-required":f,"data-state":getState$2(j),"data-disabled":g?"":void 0,disabled:g,value:b,...R,ref:A,onClick:composeEventHandlers(t.onClick,z=>{q(Q=>!Q),I&&(M.current=z.isPropagationStopped(),M.current||z.stopPropagation())})}),I&&jsxRuntime.jsx(SwitchBubbleInput,{control:C,bubbles:!M.current,name:o,value:b,checked:j,required:f,disabled:g,form:S,style:{transform:"translateX(-100%)"}})]})});Switch$1.displayName=SWITCH_NAME;var THUMB_NAME="SwitchThumb",SwitchThumb=React__namespace.forwardRef((t,e)=>{const{__scopeSwitch:n,...o}=t,l=useSwitchContext(THUMB_NAME,n);return jsxRuntime.jsx(Primitive.span,{"data-state":getState$2(l.checked),"data-disabled":l.disabled?"":void 0,...o,ref:e})});SwitchThumb.displayName=THUMB_NAME;var BUBBLE_INPUT_NAME$2="SwitchBubbleInput",SwitchBubbleInput=React__namespace.forwardRef(({__scopeSwitch:t,control:e,checked:n,bubbles:o=!0,...l},d)=>{const f=React__namespace.useRef(null),g=useComposedRefs(f,d),b=usePrevious(n),_=useSize(e);return React__namespace.useEffect(()=>{const S=f.current;if(!S)return;const R=window.HTMLInputElement.prototype,E=Object.getOwnPropertyDescriptor(R,"checked").set;if(b!==n&&E){const A=new Event("click",{bubbles:o});E.call(S,n),S.dispatchEvent(A)}},[b,n,o]),jsxRuntime.jsx("input",{type:"checkbox","aria-hidden":!0,defaultChecked:n,...l,tabIndex:-1,ref:g,style:{...l.style,..._,position:"absolute",pointerEvents:"none",opacity:0,margin:0}})});SwitchBubbleInput.displayName=BUBBLE_INPUT_NAME$2;function getState$2(t){return t?"checked":"unchecked"}var Root$1=Switch$1,Thumb=SwitchThumb;const Switch=React__namespace.forwardRef(({className:t,...e},n)=>jsxRuntime.jsx(Root$1,{className:cn("peer inline-flex h-5 w-9 shrink-0 cursor-pointer items-center rounded-full border-2 border-transparent shadow-sm transition-colors focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-ring focus-visible:ring-offset-2 focus-visible:ring-offset-background disabled:cursor-not-allowed disabled:opacity-50 data-[state=checked]:bg-primary data-[state=unchecked]:bg-input",t),...e,ref:n,children:jsxRuntime.jsx(Thumb,{className:cn("pointer-events-none block h-4 w-4 rounded-full bg-background shadow-lg ring-0 transition-transform data-[state=checked]:translate-x-4 data-[state=unchecked]:translate-x-0")})}));Switch.displayName=Root$1.displayName;const DebugMessageDisplay=({debugMessages:t})=>{const[e,n]=React.useState({}),o=l=>{n(d=>({...d,[l]:!d[l]}))};return jsxRuntime.jsx("div",{children:t.map((l,d)=>{if(typeof l=="string")return jsxRuntime.jsx("p",{className:"text-slate-600",children:l},d);{const f=e[d];return jsxRuntime.jsxs("div",{className:"cursor-pointer",onClick:()=>o(d),children:[jsxRuntime.jsxs("div",{className:"flex items-center",children:[jsxRuntime.jsx("p",{className:"text-slate-600 mr-2",children:l[0]}),jsxRuntime.jsx("span",{className:"text-slate-500 text-xs",children:f?"▲":"▼"})]}),f&&jsxRuntime.jsx("p",{className:"text-slate-400 pl-4",children:l[1]})]},d)}})})},ASSISTANT_ID="RandmarAIChatAssistant",sortChats=(t,e)=>t.unread>0&&e.unread===0?-1:e.unread>0&&t.unread===0?1:t.name.localeCompare(e.name),ChatLayout=React.forwardRef(({userId:t,userName:e,inputRef:n,assistantOnly:o,className:l,initialPrompt:d},f)=>{const{data:g,refetch:b}=useGetV4PartnerByRouteApplicationIdBusinessDevelopmentConversationsQuery({routeApplicationId:t},{skip:o===!0}),[_]=usePostV4PartnerByApplicationIdAccountDebugFeedbackMutation(),[S,{isLoading:R}]=usePostV4PartnerByRouteApplicationIdBusinessDevelopmentConversationPartnerAndPartnerIdMutation(),[C,E]=React.useState(!1),A=React.useRef(null),M=React.useRef(!1),[I]=usePostV4PartnerByRouteApplicationIdBusinessDevelopmentConversationPartnerAndPartnerIdMutation(),[j]=usePostV4PartnerByRouteApplicationIdBusinessDevelopmentConversationAndConversationIdReadMutation(),[q]=useLazyGetV4PartnerByRouteApplicationIdBusinessDevelopmentConversationAndConversationIdMessagesQuery(),{handleSubmitToBot:z,botMessages:Q,clearBotMessages:F,botReady:V,debugMessages:te,botStatus:ne,reset:se}=useAIAssistant({userId:t,smartAndSlow:C});React.useEffect(()=>{const pt={partner1:t,partner2:ASSISTANT_ID,name:"Randmar Assistant",unread:0,pending:!1,messages:[],conversationID:-1};if(o===!0){Be([pt]);return}if(!g)return;(async()=>{const Kt=g.map(async or=>{var Er,gr,xr;const Rr=await q({routeApplicationId:t,conversationId:or.ConversationId});return{partner1:or.Participant1,partner2:or.Participant2,name:((Er=or.Participant)==null?void 0:Er.PublicName)??"missing public name",unread:((gr=Rr.data)==null?void 0:gr.filter(tr=>!tr.Read&&tr.SenderId!=t).length)??0,pending:or.Status!=="Approved",messages:((xr=Rr.data)==null?void 0:xr.map(tr=>({id:"history"+tr.MessageId,fromPartnerID:tr.SenderId,toPartnerID:tr.SenderId==or.Participant1?or.Participant2:or.Participant1,senderName:tr.SenderName??"missing name",timestamp:new Date(tr.SentDate+"Z").getTime(),content:tr.Content??"no content"})))??[],conversationID:or.ConversationId}}),ur=await Promise.all(Kt);ur.sort(sortChats),Be([pt,...ur]),setTimeout(()=>{var or;return(or=Ue.current)==null?void 0:or.focus()},50)})()},[g,o,t]);const[ge,oe]=React.useState("approved"),[Ae,je]=React.useState([t,ASSISTANT_ID]),[Ne,Oe]=React.useState(""),[Fe,ze]=React.useState(null),[$e,Be]=React.useState([]),[qe,Ge]=React.useState(""),[He,Ze]=React.useState(null),tt=React.useRef(null),Ye=React.useRef(null),[Qe,Xe]=React.useState(null),[st,rt]=React.useState([]),[at,ot]=React.useState([]),Ue=n||Ye,Ct=React.useRef(null),{toast:Je}=useToast(),yt=()=>$e.find(pt=>pt.partner1===(Ae==null?void 0:Ae[0])&&pt.partner2===(Ae==null?void 0:Ae[1])),Mt=()=>(Ae==null?void 0:Ae[0])===ASSISTANT_ID||(Ae==null?void 0:Ae[1])===ASSISTANT_ID;function qt(){const pt=yt();pt&&(Mt()||j({routeApplicationId:t,conversationId:pt.conversationID}))}React.useEffect(()=>{d&&V&&(M.current||Mt()&&(M.current=!0,Ke(d)))},[d,V,Ae,M]);const Ht=React.useMemo(()=>$e.filter(pt=>{if(pt.partner1===ASSISTANT_ID||pt.partner2===ASSISTANT_ID)return!0;const Kt=pt.name.toLowerCase().includes(qe.toLowerCase());return ge==="approved"?Kt&&!pt.pending:ge==="pending"?Kt&&pt.pending:Kt}),[$e,qe,ge]);React.useEffect(()=>{var pt;Qe!==null&&(Je({title:"File attached",description:"Add your instruction before sending.",variant:"success"}),(pt=Ue.current)==null||pt.focus())},[Qe]),React.useEffect(()=>{Q.length!==0&&(Q.forEach(pt=>{if(!pt||pt.isComponent)return;const Zt={id:pt.timestamp.toString(),fromPartnerID:ASSISTANT_ID,toPartnerID:t,senderName:"Assistant",timestamp:pt.timestamp.getTime(),content:pt.content};Ft(Zt)}),F())},[Q]);const Ft=pt=>ot(Zt=>[...Zt,pt]);React.useEffect(()=>{at.length!=0&&(at.forEach(pt=>{Be(Zt=>Zt.map(Kt=>{let ur=Kt.partner1===pt.fromPartnerID&&Kt.partner2===pt.toPartnerID;if(ur||(ur=Kt.partner1===pt.toPartnerID&&Kt.partner2===pt.fromPartnerID),!ur||Kt.messages.some(Rr=>Rr.id===pt.id))return Kt;let or=1;return(Ae==null?void 0:Ae[0])==Kt.partner1&&Ae[1]==Kt.partner2&&(or=0,qt(),setTimeout(()=>{var Rr;return(Rr=tt.current)==null?void 0:Rr.scrollIntoView({behavior:"smooth"})},50),Kt.pending&&oe("approved")),{...Kt,pending:!1,unread:Kt.unread+or,messages:[...Kt.messages,pt]}}).sort(sortChats))}),ot([]))},[at,ot,Be,je,Ae]),React.useEffect(()=>{if(o===!0)return;const pt=new HubConnectionBuilder().withUrl("https://api.randmar.io/hub",{accessTokenFactory:()=>localStorage.getItem("access_token"),headers:{"X-Impersonated-Id":t}}).configureLogging(LogLevel.Information).withAutomaticReconnect().withHubProtocol(new JsonHubProtocol).build();return pt.on("ReceiveMessage",Ft),pt.start().catch(Zt=>console.error("Error connecting to SignalR hub:",Zt)),Ze(pt),()=>{pt&&pt.stop()}},[t,o]),React.useEffect(()=>{var Zt;if(!Ae)return;const pt=yt();pt&&((Zt=Ue.current)==null||Zt.focus(),pt.unread>0&&(qt(),Be(Kt=>Kt.map(ur=>ur.partner1===Ae[0]&&ur.partner2===Ae[1]?{...ur,unread:0}:ur))),setTimeout(()=>{var Kt;return(Kt=tt.current)==null?void 0:Kt.scrollIntoView({behavior:"smooth"})},50))},[$e,Ae]);const Ke=pt=>{if(!Ae)return;const Zt={id:crypto.randomUUID(),senderName:e,fromPartnerID:t,toPartnerID:Ae[0]===t?Ae[1]:Ae[0],content:pt+(Qe?` (${Qe==null?void 0:Qe.name} attached)`:""),timestamp:Date.now()};Ft(Zt),Zt.toPartnerID==ASSISTANT_ID?(z(Zt.content,Qe??void 0),Qe&&rt(Kt=>[...Kt,Qe.name])):He.invoke("NewMessage",Zt).catch(Kt=>console.error("Error sending message:",Kt)),Oe(""),Xe(null),Ct.current&&(Ct.current.value="")},it=(pt,Zt)=>ze([pt,Zt]);if(React.useEffect(()=>{if(Fe===null)return;const pt=$e.find(Kt=>Kt.conversationID===Fe[0]);if(pt&&(pt.pending&&oe("pending"),je([pt.partner1,pt.partner2]),!(Fe[0]===-1&&!V)&&!(Fe[0]!==-1&&!He))){var Zt=Fe[1];ze(null),Zt&&Ke(Zt)}},[Fe,$e,oe,je,V,He]),React.useImperativeHandle(f,()=>({setActiveChatAndSendMessage:it})),!V)return jsxRuntime.jsx(jsxRuntime.Fragment,{children:jsxRuntime.jsx("div",{className:"flex items-center justify-center p-8",children:jsxRuntime.jsxs("div",{className:"text-center",children:[jsxRuntime.jsx("div",{className:"animate-spin rounded-full h-12 w-12 border-b-2 border-primary mx-auto mb-4"}),jsxRuntime.jsx("p",{children:"Loading API functions..."})]})})});const et=pt=>{var Kt;if(!Mt())return;const Zt=(Kt=pt.clipboardData)==null?void 0:Kt.items;if(Zt){for(let ur=0;ur<Zt.length;ur++)if(Zt[ur].type.indexOf("image")!==-1){const or=Zt[ur].getAsFile();if(or){Xe(or);return}}}},ct=()=>{!Ne.trim()||!Ae||o!==!0&&!He||Ke(Ne)},ft=pt=>{pt.target.files&&pt.target.files[0]?Xe(pt.target.files[0]):Xe(null)},dt=()=>{var pt;(pt=Ct.current)==null||pt.click()},Rt=()=>{var pt;Xe(null),Je({title:"File removed",description:"No file will be sent to the assistant.",variant:"secondary"}),(pt=Ue.current)==null||pt.focus()},zt=()=>{const Zt={messages:$e.find(Kt=>Kt.partner1===ASSISTANT_ID||Kt.partner2===ASSISTANT_ID),debug:te};_({applicationId:t,emailAddress:e,body:Zt})},Yt=async()=>{A.current&&(A.current.disabled=!0),await I({routeApplicationId:t,partnerId:"2"}),await b()},sr=()=>{Be(pt=>pt.map(Kt=>Kt.partner1!==ASSISTANT_ID&&Kt.partner2!==ASSISTANT_ID?Kt:{...Kt,messages:[]})),rt([]),se()},dr=()=>{Ae&&S({routeApplicationId:t,partnerId:Ae[0]==t?Ae[1]:Ae[0]}).then(()=>{oe("approved")})},mt=yt(),Sr=$e.filter(pt=>pt.pending).length;return jsxRuntime.jsxs("div",{className:cn("flex overflow-hidden",l),children:[o!==!0&&jsxRuntime.jsx(jsxRuntime.Fragment,{children:jsxRuntime.jsxs("div",{className:"w-[260px] p-4 pt-3 flex flex-col border-r",children:[jsxRuntime.jsx("div",{className:"p-4 font-semibold border-b",children:"Communications"}),$e.length>1&&jsxRuntime.jsxs(jsxRuntime.Fragment,{children:[jsxRuntime.jsx("div",{className:"p-2",children:jsxRuntime.jsxs("div",{className:"relative",children:[jsxRuntime.jsx(Search,{className:"absolute left-2 top-1/2 transform -translate-y-1/2 h-4 w-4 text-muted-foreground"}),jsxRuntime.jsx(Input,{placeholder:"Search chats...",className:"pl-8 h-9",value:qe,onChange:pt=>Ge(pt.target.value)})]})}),jsxRuntime.jsx(Tabs,{value:ge,onValueChange:oe,className:"w-full mb-1",children:jsxRuntime.jsxs(TabsList,{className:"grid grid-cols-6 h-9 mx-2",children:[jsxRuntime.jsx(TabsTrigger,{value:"approved",className:"text-xs col-span-3",children:"Approved"}),jsxRuntime.jsxs(TabsTrigger,{value:"pending",className:"text-xs col-span-3",children:["Pending ",Sr>0&&`(${Sr})`]})]})})]}),jsxRuntime.jsx("div",{className:"mt-1 mb-1",children:$e.findIndex(pt=>pt.partner1==="2"||pt.partner2==="2")<0?jsxRuntime.jsx(Button,{className:"w-full",ref:A,onClick:()=>Yt(),children:"Chat with Randmar"},"b1"):ge==="approved"&&$e.length>=5?null:jsxRuntime.jsx(reactRouterDom.Link,{to:`${window.location.hostname==="dashboard.randmar.io"?"":"https://dashboard.randmar.io"}/${t}/ExploreManufacturers`,target:window.location.hostname==="dashboard.randmar.io"?"_self":"_blank",children:jsxRuntime.jsx(Button,{className:"w-full",children:"Explore Manufacturers"},"b2")})}),jsxRuntime.jsx(ScrollArea,{className:"flex-1",children:$e.length>0&&jsxRuntime.jsx(ChatList,{userId:t,chats:Ht.filter(pt=>pt.partner1!==ASSISTANT_ID&&pt.partner2!==ASSISTANT_ID),activeChat:mt??null,onSelectChat:je})}),jsxRuntime.jsx(Separator$1,{className:"mt-auto"}),jsxRuntime.jsx("div",{className:"pt-1",children:$e.find(pt=>pt.partner1===ASSISTANT_ID||pt.partner2===ASSISTANT_ID)&&jsxRuntime.jsx(ChatList,{userId:t,chats:Ht.filter(pt=>pt.partner1===ASSISTANT_ID||pt.partner2===ASSISTANT_ID),activeChat:mt??null,onSelectChat:je,assistantStickyMode:!0})})]})}),jsxRuntime.jsx("div",{className:"flex-5 flex flex-col",children:Ae?jsxRuntime.jsxs(jsxRuntime.Fragment,{children:[jsxRuntime.jsx("div",{className:"flex items-center p-4 border-b",children:Ae[0]==ASSISTANT_ID||Ae[1]==ASSISTANT_ID?jsxRuntime.jsxs(jsxRuntime.Fragment,{children:[jsxRuntime.jsx(Avatar,{className:"h-8 w-8 flex-shrink-0 rounded-none",children:jsxRuntime.jsx(Bot,{className:"text-primary fill-white min-h-full"})}),jsxRuntime.jsx("div",{className:"ml-3 font-medium",children:"Randmar Assistant"}),jsxRuntime.jsxs("div",{className:"flex items-center space-x-2 ml-auto",children:[jsxRuntime.jsx(Switch,{id:"smartSwitch",disabled:!!ne,checked:C,onCheckedChange:pt=>{sr(),setTimeout(()=>E(pt),20)}}),jsxRuntime.jsx(Label$2,{htmlFor:"smartSwitch",children:"Think harder"})]}),jsxRuntime.jsx(Button,{variant:"ghost",size:"icon",className:"ml-1",onClick:()=>sr(),children:jsxRuntime.jsx(MessageCircleX,{className:"h-5 w-5"})}),jsxRuntime.jsx(Button,{variant:"ghost",size:"icon",className:"ml-1",confirmationDialog:{title:"Report Issue",content:"This action will send a copy of your chat to Randmar. Send it?",onConfirm:()=>zt()},children:jsxRuntime.jsx(MessageSquareShare,{className:"h-5 w-5"})})]}):jsxRuntime.jsxs(jsxRuntime.Fragment,{children:[jsxRuntime.jsx(Avatar,{className:"h-8 w-8 flex-shrink-0 rounded-none",children:jsxRuntime.jsx(PartnerLogo,{id:Ae[0]===t?Ae[1]:Ae[0],width:72,height:72})}),jsxRuntime.jsx("div",{className:"ml-3 font-medium",children:mt==null?void 0:mt.name}),jsxRuntime.jsx("div",{className:"flex items-center space-x-2 ml-auto",children:jsxRuntime.jsx(reactRouterDom.Link,{to:`${window.location.hostname==="dashboard.randmar.io"?"":"https://dashboard.randmar.io"}/${t}/Partner/${Ae[0]===t?Ae[1]:Ae[0]}`,target:window.location.hostname==="dashboard.randmar.io"?"_self":"_blank",children:jsxRuntime.jsx(Button,{children:"View Partner"})})})]})}),mt!=null&&mt.pending&&mt.partner1==t?jsxRuntime.jsx("p",{className:"mt-8 p-2 mx-auto",children:"This conversation is awaiting approval by the other party — please check back later."}):jsxRuntime.jsxs(jsxRuntime.Fragment,{children:[jsxRuntime.jsxs(ScrollArea,{className:"flex-1 pl-2 pr-2 bg-slate-50",children:[jsxRuntime.jsx(ChatMessages,{messages:(mt==null?void 0:mt.messages)??[],currentUserId:t,isAssistantChat:Mt(),botStatus:Mt()?ne:""}),jsxRuntime.jsx("div",{ref:tt})]}),jsxRuntime.jsxs("div",{className:"p-4 border-t border-r flex",children:[(mt==null?void 0:mt.pending)&&jsxRuntime.jsxs(jsxRuntime.Fragment,{children:[jsxRuntime.jsxs(Button,{disabled:R,onClick:()=>dr(),children:[jsxRuntime.jsx(Handshake,{}),"Accept Conversation Request"]}),jsxRuntime.jsxs(Button,{disabled:!0,className:"ml-2",children:[jsxRuntime.jsx(ThumbsDown,{}),"Block Partner"]})]}),jsxRuntime.jsx(Textarea,{ref:Ue,placeholder:"Type a message...",value:Ne,onPaste:et,onChange:pt=>Oe(pt.target.value),onKeyDown:pt=>{pt.key!=="Enter"||pt.shiftKey||(pt.preventDefault(),ct())},className:mt!=null&&mt.pending?"collapse":"flex-1 resize-none"}),jsxRuntime.jsxs("div",{className:"flex items-center",children:[jsxRuntime.jsx(Button,{size:"icon",variant:"default",className:mt!=null&&mt.pending?"collapse":"ml-2 h-8 w-8",disabled:!!ne||(mt==null?void 0:mt.pending),onClick:ct,children:jsxRuntime.jsx(Send,{className:"h-6 w-6"})}),Mt()&&jsxRuntime.jsxs(jsxRuntime.Fragment,{children:[jsxRuntime.jsx(Input,{type:"file",onChange:ft,className:"hidden",ref:Ct}),jsxRuntime.jsx(Button,{size:"icon",variant:"default",onClick:dt,className:mt!=null&&mt.pending?"collapse":"ml-2 h-8 w-8",disabled:ne!==""||(mt==null?void 0:mt.pending)||!!Qe,children:jsxRuntime.jsx(Paperclip,{className:"h-5 w-5"})}),jsxRuntime.jsx(Button,{size:"icon",variant:"default",onClick:Rt,className:mt!=null&&mt.pending?"collapse":"ml-2 h-8 w-8",disabled:ne!==""||(mt==null?void 0:mt.pending)||!Qe,children:jsxRuntime.jsx(Trash,{className:"h-5 w-5"})})]})]})]})]})]}):jsxRuntime.jsx("div",{className:"flex-1 flex items-center justify-center text-muted-foreground",children:"Select a chat to start messaging"})}),jsxRuntime.jsx("div",{"data-thin":Mt(),className:"w-[480px] flex flex-col border-l flex-4 data-[thin=true]:flex-2",children:Mt()?jsxRuntime.jsxs(jsxRuntime.Fragment,{children:[jsxRuntime.jsx("div",{className:"flex items-center p-4 border-b",children:jsxRuntime.jsx("p",{className:"h-9 text-base/9",children:"Sources and System Info"})}),jsxRuntime.jsx(ScrollArea,{className:"flex-1 pl-2 pr-2 bg-slate-50",children:jsxRuntime.jsxs("div",{className:"space-y-2",children:[Qe?jsxRuntime.jsx(jsxRuntime.Fragment,{children:jsxRuntime.jsxs("div",{className:"flex",children:[jsxRuntime.jsx(File,{})," ",Qe.name," (pending send...)"]})}):st.length?jsxRuntime.jsx(jsxRuntime.Fragment,{}):jsxRuntime.jsx("p",{children:"No files attached to this conversation yet."}),st.slice().reverse().map(pt=>jsxRuntime.jsx(jsxRuntime.Fragment,{children:jsxRuntime.jsxs("div",{className:"flex",children:[jsxRuntime.jsx(File,{})," ",pt]})}))]})}),jsxRuntime.jsx(ScrollArea,{className:"flex-4 border-t pl-2 pr-2 bg-slate-50",children:jsxRuntime.jsx("div",{className:"space-y-2",children:jsxRuntime.jsx(DebugMessageDisplay,{debugMessages:te})})})]}):jsxRuntime.jsxs(jsxRuntime.Fragment,{children:[jsxRuntime.jsx("div",{className:"flex items-center p-4 border-b",children:jsxRuntime.jsx("p",{className:"h-9 text-base/9",children:"Partner Overview"})}),jsxRuntime.jsx(ScrollArea,{className:"flex-1 pl-2 pr-2 bg-slate-50",children:jsxRuntime.jsx("div",{className:"mt-1",children:jsxRuntime.jsx(PartnerRelationshipPage,{applicationId:t,partnerId:((Ae==null?void 0:Ae[0])===t?Ae[1]:Ae==null?void 0:Ae[0])??t,userEmail:e,shopifyHostName:void 0,isSuperAdmin:!1})})})]})})]})});function UnsavedChangesDialog({isOpen:t,onClose:e,onConfirm:n,title:o,description:l,confirmText:d="Confirm",cancelText:f="Cancel"}){return jsxRuntime.jsx(Dialog,{open:t,onOpenChange:e,children:jsxRuntime.jsxs(DialogContent,{className:"sm:max-w-[425px]",children:[jsxRuntime.jsxs(DialogHeader,{children:[jsxRuntime.jsx(DialogTitle,{children:o}),jsxRuntime.jsx(DialogDescription,{children:l})]}),jsxRuntime.jsxs(DialogFooter,{children:[jsxRuntime.jsx(Button,{variant:"outline",onClick:e,children:f}),jsxRuntime.jsx(Button,{onClick:n,children:d})]})]})})}function useRouterNavigationGuard(t){const[e,n]=React.useState(!1),o=reactRouterDom.useBlocker(React.useCallback(({currentLocation:g,nextLocation:b})=>{const _=g.pathname!==b.pathname||g.search!==b.search||g.hash!==b.hash;return t()&&_},[t]));React.useEffect(()=>{o.state==="blocked"&&n(!0)},[o]),React.useEffect(()=>{const g=b=>{if(t())return b.preventDefault(),"You have unsaved changes. Are you sure you want to leave?"};return window.addEventListener("beforeunload",g),()=>{window.removeEventListener("beforeunload",g)}},[t]);const l=React.useCallback(()=>{n(!1),o.state==="blocked"&&o.proceed()},[o]),d=React.useCallback(()=>{n(!1),o.state==="blocked"&&o.reset()},[o]),f=React.useCallback(()=>jsxRuntime.jsx(UnsavedChangesDialog,{isOpen:e,onClose:d,onConfirm:l,title:"Unsaved Changes",description:"You have unsaved changes. Are you sure you want to leave? Your changes will be lost.",confirmText:"Discard Changes",cancelText:"Stay on Page"}),[e,d,l]);return{showDialog:e,handleConfirm:l,handleCancel:d,NavigationGuardDialog:f}}var isCheckBoxInput=t=>t.type==="checkbox",isDateObject=t=>t instanceof Date,isNullOrUndefined=t=>t==null;const isObjectType=t=>typeof t=="object";var isObject=t=>!isNullOrUndefined(t)&&!Array.isArray(t)&&isObjectType(t)&&!isDateObject(t),getEventValue=t=>isObject(t)&&t.target?isCheckBoxInput(t.target)?t.target.checked:t.target.value:t,getNodeParentName=t=>t.substring(0,t.search(/\.\d+(\.|$)/))||t,isNameInFieldArray=(t,e)=>t.has(getNodeParentName(e)),isPlainObject$1=t=>{const e=t.constructor&&t.constructor.prototype;return isObject(e)&&e.hasOwnProperty("isPrototypeOf")},isWeb=typeof window<"u"&&typeof window.HTMLElement<"u"&&typeof document<"u";function cloneObject(t){let e;const n=Array.isArray(t),o=typeof FileList<"u"?t instanceof FileList:!1;if(t instanceof Date)e=new Date(t);else if(t instanceof Set)e=new Set(t);else if(!(isWeb&&(t instanceof Blob||o))&&(n||isObject(t)))if(e=n?[]:{},!n&&!isPlainObject$1(t))e=t;else for(const l in t)t.hasOwnProperty(l)&&(e[l]=cloneObject(t[l]));else return t;return e}var compact=t=>Array.isArray(t)?t.filter(Boolean):[],isUndefined=t=>t===void 0,get=(t,e,n)=>{if(!e||!isObject(t))return n;const o=compact(e.split(/[,[\].]+?/)).reduce((l,d)=>isNullOrUndefined(l)?l:l[d],t);return isUndefined(o)||o===t?isUndefined(t[e])?n:t[e]:o},isBoolean=t=>typeof t=="boolean",isKey=t=>/^\w*$/.test(t),stringToPath=t=>compact(t.replace(/["|']|\]/g,"").split(/\.|\[/)),set=(t,e,n)=>{let o=-1;const l=isKey(e)?[e]:stringToPath(e),d=l.length,f=d-1;for(;++o<d;){const g=l[o];let b=n;if(o!==f){const _=t[g];b=isObject(_)||Array.isArray(_)?_:isNaN(+l[o+1])?{}:[]}if(g==="__proto__"||g==="constructor"||g==="prototype")return;t[g]=b,t=t[g]}};const EVENTS={BLUR:"blur",FOCUS_OUT:"focusout"},VALIDATION_MODE={onBlur:"onBlur",onChange:"onChange",onSubmit:"onSubmit",onTouched:"onTouched",all:"all"},INPUT_VALIDATION_RULES={max:"max",min:"min",maxLength:"maxLength",minLength:"minLength",pattern:"pattern",required:"required",validate:"validate"};React.createContext(null);var getProxyFormState=(t,e,n,o=!0)=>{const l={defaultValues:e._defaultValues};for(const d in t)Object.defineProperty(l,d,{get:()=>{const f=d;return e._proxyFormState[f]!==VALIDATION_MODE.all&&(e._proxyFormState[f]=!o||VALIDATION_MODE.all),t[f]}});return l};const useIsomorphicLayoutEffect$1=typeof window<"u"?React__namespace.useLayoutEffect:React__namespace.useEffect;var isString=t=>typeof t=="string",generateWatchOutput=(t,e,n,o,l)=>isString(t)?(o&&e.watch.add(t),get(n,t,l)):Array.isArray(t)?t.map(d=>(o&&e.watch.add(d),get(n,d))):(o&&(e.watchAll=!0),n),appendErrors=(t,e,n,o,l)=>e?{...n[t],types:{...n[t]&&n[t].types?n[t].types:{},[o]:l||!0}}:{},convertToArrayPayload=t=>Array.isArray(t)?t:[t],createSubject=()=>{let t=[];return{get observers(){return t},next:l=>{for(const d of t)d.next&&d.next(l)},subscribe:l=>(t.push(l),{unsubscribe:()=>{t=t.filter(d=>d!==l)}}),unsubscribe:()=>{t=[]}}},isPrimitive=t=>isNullOrUndefined(t)||!isObjectType(t);function deepEqual$1(t,e){if(isPrimitive(t)||isPrimitive(e))return t===e;if(isDateObject(t)&&isDateObject(e))return t.getTime()===e.getTime();const n=Object.keys(t),o=Object.keys(e);if(n.length!==o.length)return!1;for(const l of n){const d=t[l];if(!o.includes(l))return!1;if(l!=="ref"){const f=e[l];if(isDateObject(d)&&isDateObject(f)||isObject(d)&&isObject(f)||Array.isArray(d)&&Array.isArray(f)?!deepEqual$1(d,f):d!==f)return!1}}return!0}var isEmptyObject$1=t=>isObject(t)&&!Object.keys(t).length,isFileInput=t=>t.type==="file",isFunction$3=t=>typeof t=="function",isHTMLElement=t=>{if(!isWeb)return!1;const e=t?t.ownerDocument:0;return t instanceof(e&&e.defaultView?e.defaultView.HTMLElement:HTMLElement)},isMultipleSelect=t=>t.type==="select-multiple",isRadioInput=t=>t.type==="radio",isRadioOrCheckbox=t=>isRadioInput(t)||isCheckBoxInput(t),live=t=>isHTMLElement(t)&&t.isConnected;function baseGet(t,e){const n=e.slice(0,-1).length;let o=0;for(;o<n;)t=isUndefined(t)?o++:t[e[o++]];return t}function isEmptyArray(t){for(const e in t)if(t.hasOwnProperty(e)&&!isUndefined(t[e]))return!1;return!0}function unset(t,e){const n=Array.isArray(e)?e:isKey(e)?[e]:stringToPath(e),o=n.length===1?t:baseGet(t,n),l=n.length-1,d=n[l];return o&&delete o[d],l!==0&&(isObject(o)&&isEmptyObject$1(o)||Array.isArray(o)&&isEmptyArray(o))&&unset(t,n.slice(0,-1)),t}var objectHasFunction=t=>{for(const e in t)if(isFunction$3(t[e]))return!0;return!1};function markFieldsDirty(t,e={}){const n=Array.isArray(t);if(isObject(t)||n)for(const o in t)Array.isArray(t[o])||isObject(t[o])&&!objectHasFunction(t[o])?(e[o]=Array.isArray(t[o])?[]:{},markFieldsDirty(t[o],e[o])):isNullOrUndefined(t[o])||(e[o]=!0);return e}function getDirtyFieldsFromDefaultValues(t,e,n){const o=Array.isArray(t);if(isObject(t)||o)for(const l in t)Array.isArray(t[l])||isObject(t[l])&&!objectHasFunction(t[l])?isUndefined(e)||isPrimitive(n[l])?n[l]=Array.isArray(t[l])?markFieldsDirty(t[l],[]):{...markFieldsDirty(t[l])}:getDirtyFieldsFromDefaultValues(t[l],isNullOrUndefined(e)?{}:e[l],n[l]):n[l]=!deepEqual$1(t[l],e[l]);return n}var getDirtyFields=(t,e)=>getDirtyFieldsFromDefaultValues(t,e,markFieldsDirty(e));const defaultResult={value:!1,isValid:!1},validResult={value:!0,isValid:!0};var getCheckboxValue=t=>{if(Array.isArray(t)){if(t.length>1){const e=t.filter(n=>n&&n.checked&&!n.disabled).map(n=>n.value);return{value:e,isValid:!!e.length}}return t[0].checked&&!t[0].disabled?t[0].attributes&&!isUndefined(t[0].attributes.value)?isUndefined(t[0].value)||t[0].value===""?validResult:{value:t[0].value,isValid:!0}:validResult:defaultResult}return defaultResult},getFieldValueAs=(t,{valueAsNumber:e,valueAsDate:n,setValueAs:o})=>isUndefined(t)?t:e?t===""?NaN:t&&+t:n&&isString(t)?new Date(t):o?o(t):t;const defaultReturn={isValid:!1,value:null};var getRadioValue=t=>Array.isArray(t)?t.reduce((e,n)=>n&&n.checked&&!n.disabled?{isValid:!0,value:n.value}:e,defaultReturn):defaultReturn;function getFieldValue(t){const e=t.ref;return isFileInput(e)?e.files:isRadioInput(e)?getRadioValue(t.refs).value:isMultipleSelect(e)?[...e.selectedOptions].map(({value:n})=>n):isCheckBoxInput(e)?getCheckboxValue(t.refs).value:getFieldValueAs(isUndefined(e.value)?t.ref.value:e.value,t)}var getResolverOptions=(t,e,n,o)=>{const l={};for(const d of t){const f=get(e,d);f&&set(l,d,f._f)}return{criteriaMode:n,names:[...t],fields:l,shouldUseNativeValidation:o}},isRegex=t=>t instanceof RegExp,getRuleValue=t=>isUndefined(t)?t:isRegex(t)?t.source:isObject(t)?isRegex(t.value)?t.value.source:t.value:t,getValidationModes=t=>({isOnSubmit:!t||t===VALIDATION_MODE.onSubmit,isOnBlur:t===VALIDATION_MODE.onBlur,isOnChange:t===VALIDATION_MODE.onChange,isOnAll:t===VALIDATION_MODE.all,isOnTouch:t===VALIDATION_MODE.onTouched});const ASYNC_FUNCTION="AsyncFunction";var hasPromiseValidation=t=>!!t&&!!t.validate&&!!(isFunction$3(t.validate)&&t.validate.constructor.name===ASYNC_FUNCTION||isObject(t.validate)&&Object.values(t.validate).find(e=>e.constructor.name===ASYNC_FUNCTION)),hasValidation=t=>t.mount&&(t.required||t.min||t.max||t.maxLength||t.minLength||t.pattern||t.validate),isWatched=(t,e,n)=>!n&&(e.watchAll||e.watch.has(t)||[...e.watch].some(o=>t.startsWith(o)&&/^\.\w+/.test(t.slice(o.length))));const iterateFieldsByAction=(t,e,n,o)=>{for(const l of n||Object.keys(t)){const d=get(t,l);if(d){const{_f:f,...g}=d;if(f){if(f.refs&&f.refs[0]&&e(f.refs[0],l)&&!o)return!0;if(f.ref&&e(f.ref,f.name)&&!o)return!0;if(iterateFieldsByAction(g,e))break}else if(isObject(g)&&iterateFieldsByAction(g,e))break}}};function schemaErrorLookup(t,e,n){const o=get(t,n);if(o||isKey(n))return{error:o,name:n};const l=n.split(".");for(;l.length;){const d=l.join("."),f=get(e,d),g=get(t,d);if(f&&!Array.isArray(f)&&n!==d)return{name:n};if(g&&g.type)return{name:d,error:g};if(g&&g.root&&g.root.type)return{name:`${d}.root`,error:g.root};l.pop()}return{name:n}}var shouldRenderFormState=(t,e,n,o)=>{n(t);const{name:l,...d}=t;return isEmptyObject$1(d)||Object.keys(d).length>=Object.keys(e).length||Object.keys(d).find(f=>e[f]===(!o||VALIDATION_MODE.all))},shouldSubscribeByName=(t,e,n)=>!t||!e||t===e||convertToArrayPayload(t).some(o=>o&&(n?o===e:o.startsWith(e)||e.startsWith(o))),skipValidation=(t,e,n,o,l)=>l.isOnAll?!1:!n&&l.isOnTouch?!(e||t):(n?o.isOnBlur:l.isOnBlur)?!t:(n?o.isOnChange:l.isOnChange)?t:!0,unsetEmptyArray=(t,e)=>!compact(get(t,e)).length&&unset(t,e),updateFieldArrayRootError=(t,e,n)=>{const o=convertToArrayPayload(get(t,n));return set(o,"root",e[n]),set(t,n,o),t},isMessage=t=>isString(t);function getValidateError(t,e,n="validate"){if(isMessage(t)||Array.isArray(t)&&t.every(isMessage)||isBoolean(t)&&!t)return{type:n,message:isMessage(t)?t:"",ref:e}}var getValueAndMessage=t=>isObject(t)&&!isRegex(t)?t:{value:t,message:""},validateField=async(t,e,n,o,l,d)=>{const{ref:f,refs:g,required:b,maxLength:_,minLength:S,min:R,max:C,pattern:E,validate:A,name:M,valueAsNumber:I,mount:j}=t._f,q=get(n,M);if(!j||e.has(M))return{};const z=g?g[0]:f,Q=Ae=>{l&&z.reportValidity&&(z.setCustomValidity(isBoolean(Ae)?"":Ae||""),z.reportValidity())},F={},V=isRadioInput(f),te=isCheckBoxInput(f),ne=V||te,se=(I||isFileInput(f))&&isUndefined(f.value)&&isUndefined(q)||isHTMLElement(f)&&f.value===""||q===""||Array.isArray(q)&&!q.length,ge=appendErrors.bind(null,M,o,F),oe=(Ae,je,Ne,Oe=INPUT_VALIDATION_RULES.maxLength,Fe=INPUT_VALIDATION_RULES.minLength)=>{const ze=Ae?je:Ne;F[M]={type:Ae?Oe:Fe,message:ze,ref:f,...ge(Ae?Oe:Fe,ze)}};if(d?!Array.isArray(q)||!q.length:b&&(!ne&&(se||isNullOrUndefined(q))||isBoolean(q)&&!q||te&&!getCheckboxValue(g).isValid||V&&!getRadioValue(g).isValid)){const{value:Ae,message:je}=isMessage(b)?{value:!!b,message:b}:getValueAndMessage(b);if(Ae&&(F[M]={type:INPUT_VALIDATION_RULES.required,message:je,ref:z,...ge(INPUT_VALIDATION_RULES.required,je)},!o))return Q(je),F}if(!se&&(!isNullOrUndefined(R)||!isNullOrUndefined(C))){let Ae,je;const Ne=getValueAndMessage(C),Oe=getValueAndMessage(R);if(!isNullOrUndefined(q)&&!isNaN(q)){const Fe=f.valueAsNumber||q&&+q;isNullOrUndefined(Ne.value)||(Ae=Fe>Ne.value),isNullOrUndefined(Oe.value)||(je=Fe<Oe.value)}else{const Fe=f.valueAsDate||new Date(q),ze=qe=>new Date(new Date().toDateString()+" "+qe),$e=f.type=="time",Be=f.type=="week";isString(Ne.value)&&q&&(Ae=$e?ze(q)>ze(Ne.value):Be?q>Ne.value:Fe>new Date(Ne.value)),isString(Oe.value)&&q&&(je=$e?ze(q)<ze(Oe.value):Be?q<Oe.value:Fe<new Date(Oe.value))}if((Ae||je)&&(oe(!!Ae,Ne.message,Oe.message,INPUT_VALIDATION_RULES.max,INPUT_VALIDATION_RULES.min),!o))return Q(F[M].message),F}if((_||S)&&!se&&(isString(q)||d&&Array.isArray(q))){const Ae=getValueAndMessage(_),je=getValueAndMessage(S),Ne=!isNullOrUndefined(Ae.value)&&q.length>+Ae.value,Oe=!isNullOrUndefined(je.value)&&q.length<+je.value;if((Ne||Oe)&&(oe(Ne,Ae.message,je.message),!o))return Q(F[M].message),F}if(E&&!se&&isString(q)){const{value:Ae,message:je}=getValueAndMessage(E);if(isRegex(Ae)&&!q.match(Ae)&&(F[M]={type:INPUT_VALIDATION_RULES.pattern,message:je,ref:f,...ge(INPUT_VALIDATION_RULES.pattern,je)},!o))return Q(je),F}if(A){if(isFunction$3(A)){const Ae=await A(q,n),je=getValidateError(Ae,z);if(je&&(F[M]={...je,...ge(INPUT_VALIDATION_RULES.validate,je.message)},!o))return Q(je.message),F}else if(isObject(A)){let Ae={};for(const je in A){if(!isEmptyObject$1(Ae)&&!o)break;const Ne=getValidateError(await A[je](q,n),z,je);Ne&&(Ae={...Ne,...ge(je,Ne.message)},Q(Ne.message),o&&(F[M]=Ae))}if(!isEmptyObject$1(Ae)&&(F[M]={ref:z,...Ae},!o))return F}}return Q(!0),F};const defaultOptions$1={mode:VALIDATION_MODE.onSubmit,reValidateMode:VALIDATION_MODE.onChange,shouldFocusError:!0};function createFormControl(t={}){let e={...defaultOptions$1,...t},n={submitCount:0,isDirty:!1,isReady:!1,isLoading:isFunction$3(e.defaultValues),isValidating:!1,isSubmitted:!1,isSubmitting:!1,isSubmitSuccessful:!1,isValid:!1,touchedFields:{},dirtyFields:{},validatingFields:{},errors:e.errors||{},disabled:e.disabled||!1};const o={};let l=isObject(e.defaultValues)||isObject(e.values)?cloneObject(e.defaultValues||e.values)||{}:{},d=e.shouldUnregister?{}:cloneObject(l),f={action:!1,mount:!1,watch:!1},g={mount:new Set,disabled:new Set,unMount:new Set,array:new Set,watch:new Set},b,_=0;const S={isDirty:!1,dirtyFields:!1,validatingFields:!1,touchedFields:!1,isValidating:!1,isValid:!1,errors:!1};let R={...S};const C={array:createSubject(),state:createSubject()},E=e.criteriaMode===VALIDATION_MODE.all,A=Ke=>it=>{clearTimeout(_),_=setTimeout(Ke,it)},M=async Ke=>{if(!e.disabled&&(S.isValid||R.isValid||Ke)){const it=e.resolver?isEmptyObject$1((await te()).errors):await se(o,!0);it!==n.isValid&&C.state.next({isValid:it})}},I=(Ke,it)=>{!e.disabled&&(S.isValidating||S.validatingFields||R.isValidating||R.validatingFields)&&((Ke||Array.from(g.mount)).forEach(et=>{et&&(it?set(n.validatingFields,et,it):unset(n.validatingFields,et))}),C.state.next({validatingFields:n.validatingFields,isValidating:!isEmptyObject$1(n.validatingFields)}))},j=(Ke,it=[],et,ct,ft=!0,dt=!0)=>{if(ct&&et&&!e.disabled){if(f.action=!0,dt&&Array.isArray(get(o,Ke))){const Rt=et(get(o,Ke),ct.argA,ct.argB);ft&&set(o,Ke,Rt)}if(dt&&Array.isArray(get(n.errors,Ke))){const Rt=et(get(n.errors,Ke),ct.argA,ct.argB);ft&&set(n.errors,Ke,Rt),unsetEmptyArray(n.errors,Ke)}if((S.touchedFields||R.touchedFields)&&dt&&Array.isArray(get(n.touchedFields,Ke))){const Rt=et(get(n.touchedFields,Ke),ct.argA,ct.argB);ft&&set(n.touchedFields,Ke,Rt)}(S.dirtyFields||R.dirtyFields)&&(n.dirtyFields=getDirtyFields(l,d)),C.state.next({name:Ke,isDirty:oe(Ke,it),dirtyFields:n.dirtyFields,errors:n.errors,isValid:n.isValid})}else set(d,Ke,it)},q=(Ke,it)=>{set(n.errors,Ke,it),C.state.next({errors:n.errors})},z=Ke=>{n.errors=Ke,C.state.next({errors:n.errors,isValid:!1})},Q=(Ke,it,et,ct)=>{const ft=get(o,Ke);if(ft){const dt=get(d,Ke,isUndefined(et)?get(l,Ke):et);isUndefined(dt)||ct&&ct.defaultChecked||it?set(d,Ke,it?dt:getFieldValue(ft._f)):Ne(Ke,dt),f.mount&&M()}},F=(Ke,it,et,ct,ft)=>{let dt=!1,Rt=!1;const zt={name:Ke};if(!e.disabled){if(!et||ct){(S.isDirty||R.isDirty)&&(Rt=n.isDirty,n.isDirty=zt.isDirty=oe(),dt=Rt!==zt.isDirty);const Yt=deepEqual$1(get(l,Ke),it);Rt=!!get(n.dirtyFields,Ke),Yt?unset(n.dirtyFields,Ke):set(n.dirtyFields,Ke,!0),zt.dirtyFields=n.dirtyFields,dt=dt||(S.dirtyFields||R.dirtyFields)&&Rt!==!Yt}if(et){const Yt=get(n.touchedFields,Ke);Yt||(set(n.touchedFields,Ke,et),zt.touchedFields=n.touchedFields,dt=dt||(S.touchedFields||R.touchedFields)&&Yt!==et)}dt&&ft&&C.state.next(zt)}return dt?zt:{}},V=(Ke,it,et,ct)=>{const ft=get(n.errors,Ke),dt=(S.isValid||R.isValid)&&isBoolean(it)&&n.isValid!==it;if(e.delayError&&et?(b=A(()=>q(Ke,et)),b(e.delayError)):(clearTimeout(_),b=null,et?set(n.errors,Ke,et):unset(n.errors,Ke)),(et?!deepEqual$1(ft,et):ft)||!isEmptyObject$1(ct)||dt){const Rt={...ct,...dt&&isBoolean(it)?{isValid:it}:{},errors:n.errors,name:Ke};n={...n,...Rt},C.state.next(Rt)}},te=async Ke=>{I(Ke,!0);const it=await e.resolver(d,e.context,getResolverOptions(Ke||g.mount,o,e.criteriaMode,e.shouldUseNativeValidation));return I(Ke),it},ne=async Ke=>{const{errors:it}=await te(Ke);if(Ke)for(const et of Ke){const ct=get(it,et);ct?set(n.errors,et,ct):unset(n.errors,et)}else n.errors=it;return it},se=async(Ke,it,et={valid:!0})=>{for(const ct in Ke){const ft=Ke[ct];if(ft){const{_f:dt,...Rt}=ft;if(dt){const zt=g.array.has(dt.name),Yt=ft._f&&hasPromiseValidation(ft._f);Yt&&S.validatingFields&&I([ct],!0);const sr=await validateField(ft,g.disabled,d,E,e.shouldUseNativeValidation&&!it,zt);if(Yt&&S.validatingFields&&I([ct]),sr[dt.name]&&(et.valid=!1,it))break;!it&&(get(sr,dt.name)?zt?updateFieldArrayRootError(n.errors,sr,dt.name):set(n.errors,dt.name,sr[dt.name]):unset(n.errors,dt.name))}!isEmptyObject$1(Rt)&&await se(Rt,it,et)}}return et.valid},ge=()=>{for(const Ke of g.unMount){const it=get(o,Ke);it&&(it._f.refs?it._f.refs.every(et=>!live(et)):!live(it._f.ref))&&Xe(Ke)}g.unMount=new Set},oe=(Ke,it)=>!e.disabled&&(Ke&&it&&set(d,Ke,it),!deepEqual$1(qe(),l)),Ae=(Ke,it,et)=>generateWatchOutput(Ke,g,{...f.mount?d:isUndefined(it)?l:isString(Ke)?{[Ke]:it}:it},et,it),je=Ke=>compact(get(f.mount?d:l,Ke,e.shouldUnregister?get(l,Ke,[]):[])),Ne=(Ke,it,et={})=>{const ct=get(o,Ke);let ft=it;if(ct){const dt=ct._f;dt&&(!dt.disabled&&set(d,Ke,getFieldValueAs(it,dt)),ft=isHTMLElement(dt.ref)&&isNullOrUndefined(it)?"":it,isMultipleSelect(dt.ref)?[...dt.ref.options].forEach(Rt=>Rt.selected=ft.includes(Rt.value)):dt.refs?isCheckBoxInput(dt.ref)?dt.refs.forEach(Rt=>{(!Rt.defaultChecked||!Rt.disabled)&&(Array.isArray(ft)?Rt.checked=!!ft.find(zt=>zt===Rt.value):Rt.checked=ft===Rt.value||!!ft)}):dt.refs.forEach(Rt=>Rt.checked=Rt.value===ft):isFileInput(dt.ref)?dt.ref.value="":(dt.ref.value=ft,dt.ref.type||C.state.next({name:Ke,values:cloneObject(d)})))}(et.shouldDirty||et.shouldTouch)&&F(Ke,ft,et.shouldTouch,et.shouldDirty,!0),et.shouldValidate&&Be(Ke)},Oe=(Ke,it,et)=>{for(const ct in it){if(!it.hasOwnProperty(ct))return;const ft=it[ct],dt=Ke+"."+ct,Rt=get(o,dt);(g.array.has(Ke)||isObject(ft)||Rt&&!Rt._f)&&!isDateObject(ft)?Oe(dt,ft,et):Ne(dt,ft,et)}},Fe=(Ke,it,et={})=>{const ct=get(o,Ke),ft=g.array.has(Ke),dt=cloneObject(it);set(d,Ke,dt),ft?(C.array.next({name:Ke,values:cloneObject(d)}),(S.isDirty||S.dirtyFields||R.isDirty||R.dirtyFields)&&et.shouldDirty&&C.state.next({name:Ke,dirtyFields:getDirtyFields(l,d),isDirty:oe(Ke,dt)})):ct&&!ct._f&&!isNullOrUndefined(dt)?Oe(Ke,dt,et):Ne(Ke,dt,et),isWatched(Ke,g)&&C.state.next({...n}),C.state.next({name:f.mount?Ke:void 0,values:cloneObject(d)})},ze=async Ke=>{f.mount=!0;const it=Ke.target;let et=it.name,ct=!0;const ft=get(o,et),dt=Yt=>{ct=Number.isNaN(Yt)||isDateObject(Yt)&&isNaN(Yt.getTime())||deepEqual$1(Yt,get(d,et,Yt))},Rt=getValidationModes(e.mode),zt=getValidationModes(e.reValidateMode);if(ft){let Yt,sr;const dr=it.type?getFieldValue(ft._f):getEventValue(Ke),mt=Ke.type===EVENTS.BLUR||Ke.type===EVENTS.FOCUS_OUT,Sr=!hasValidation(ft._f)&&!e.resolver&&!get(n.errors,et)&&!ft._f.deps||skipValidation(mt,get(n.touchedFields,et),n.isSubmitted,zt,Rt),pt=isWatched(et,g,mt);set(d,et,dr),mt?(ft._f.onBlur&&ft._f.onBlur(Ke),b&&b(0)):ft._f.onChange&&ft._f.onChange(Ke);const Zt=F(et,dr,mt),Kt=!isEmptyObject$1(Zt)||pt;if(!mt&&C.state.next({name:et,type:Ke.type,values:cloneObject(d)}),Sr)return(S.isValid||R.isValid)&&(e.mode==="onBlur"?mt&&M():mt||M()),Kt&&C.state.next({name:et,...pt?{}:Zt});if(!mt&&pt&&C.state.next({...n}),e.resolver){const{errors:ur}=await te([et]);if(dt(dr),ct){const or=schemaErrorLookup(n.errors,o,et),Rr=schemaErrorLookup(ur,o,or.name||et);Yt=Rr.error,et=Rr.name,sr=isEmptyObject$1(ur)}}else I([et],!0),Yt=(await validateField(ft,g.disabled,d,E,e.shouldUseNativeValidation))[et],I([et]),dt(dr),ct&&(Yt?sr=!1:(S.isValid||R.isValid)&&(sr=await se(o,!0)));ct&&(ft._f.deps&&Be(ft._f.deps),V(et,sr,Yt,Zt))}},$e=(Ke,it)=>{if(get(n.errors,it)&&Ke.focus)return Ke.focus(),1},Be=async(Ke,it={})=>{let et,ct;const ft=convertToArrayPayload(Ke);if(e.resolver){const dt=await ne(isUndefined(Ke)?Ke:ft);et=isEmptyObject$1(dt),ct=Ke?!ft.some(Rt=>get(dt,Rt)):et}else Ke?(ct=(await Promise.all(ft.map(async dt=>{const Rt=get(o,dt);return await se(Rt&&Rt._f?{[dt]:Rt}:Rt)}))).every(Boolean),!(!ct&&!n.isValid)&&M()):ct=et=await se(o);return C.state.next({...!isString(Ke)||(S.isValid||R.isValid)&&et!==n.isValid?{}:{name:Ke},...e.resolver||!Ke?{isValid:et}:{},errors:n.errors}),it.shouldFocus&&!ct&&iterateFieldsByAction(o,$e,Ke?ft:g.mount),ct},qe=Ke=>{const it={...f.mount?d:l};return isUndefined(Ke)?it:isString(Ke)?get(it,Ke):Ke.map(et=>get(it,et))},Ge=(Ke,it)=>({invalid:!!get((it||n).errors,Ke),isDirty:!!get((it||n).dirtyFields,Ke),error:get((it||n).errors,Ke),isValidating:!!get(n.validatingFields,Ke),isTouched:!!get((it||n).touchedFields,Ke)}),He=Ke=>{Ke&&convertToArrayPayload(Ke).forEach(it=>unset(n.errors,it)),C.state.next({errors:Ke?n.errors:{}})},Ze=(Ke,it,et)=>{const ct=(get(o,Ke,{_f:{}})._f||{}).ref,ft=get(n.errors,Ke)||{},{ref:dt,message:Rt,type:zt,...Yt}=ft;set(n.errors,Ke,{...Yt,...it,ref:ct}),C.state.next({name:Ke,errors:n.errors,isValid:!1}),et&&et.shouldFocus&&ct&&ct.focus&&ct.focus()},tt=(Ke,it)=>isFunction$3(Ke)?C.state.subscribe({next:et=>Ke(Ae(void 0,it),et)}):Ae(Ke,it,!0),Ye=Ke=>C.state.subscribe({next:it=>{shouldSubscribeByName(Ke.name,it.name,Ke.exact)&&shouldRenderFormState(it,Ke.formState||S,qt,Ke.reRenderRoot)&&Ke.callback({values:{...d},...n,...it})}}).unsubscribe,Qe=Ke=>(f.mount=!0,R={...R,...Ke.formState},Ye({...Ke,formState:R})),Xe=(Ke,it={})=>{for(const et of Ke?convertToArrayPayload(Ke):g.mount)g.mount.delete(et),g.array.delete(et),it.keepValue||(unset(o,et),unset(d,et)),!it.keepError&&unset(n.errors,et),!it.keepDirty&&unset(n.dirtyFields,et),!it.keepTouched&&unset(n.touchedFields,et),!it.keepIsValidating&&unset(n.validatingFields,et),!e.shouldUnregister&&!it.keepDefaultValue&&unset(l,et);C.state.next({values:cloneObject(d)}),C.state.next({...n,...it.keepDirty?{isDirty:oe()}:{}}),!it.keepIsValid&&M()},st=({disabled:Ke,name:it})=>{(isBoolean(Ke)&&f.mount||Ke||g.disabled.has(it))&&(Ke?g.disabled.add(it):g.disabled.delete(it))},rt=(Ke,it={})=>{let et=get(o,Ke);const ct=isBoolean(it.disabled)||isBoolean(e.disabled);return set(o,Ke,{...et||{},_f:{...et&&et._f?et._f:{ref:{name:Ke}},name:Ke,mount:!0,...it}}),g.mount.add(Ke),et?st({disabled:isBoolean(it.disabled)?it.disabled:e.disabled,name:Ke}):Q(Ke,!0,it.value),{...ct?{disabled:it.disabled||e.disabled}:{},...e.progressive?{required:!!it.required,min:getRuleValue(it.min),max:getRuleValue(it.max),minLength:getRuleValue(it.minLength),maxLength:getRuleValue(it.maxLength),pattern:getRuleValue(it.pattern)}:{},name:Ke,onChange:ze,onBlur:ze,ref:ft=>{if(ft){rt(Ke,it),et=get(o,Ke);const dt=isUndefined(ft.value)&&ft.querySelectorAll&&ft.querySelectorAll("input,select,textarea")[0]||ft,Rt=isRadioOrCheckbox(dt),zt=et._f.refs||[];if(Rt?zt.find(Yt=>Yt===dt):dt===et._f.ref)return;set(o,Ke,{_f:{...et._f,...Rt?{refs:[...zt.filter(live),dt,...Array.isArray(get(l,Ke))?[{}]:[]],ref:{type:dt.type,name:Ke}}:{ref:dt}}}),Q(Ke,!1,void 0,dt)}else et=get(o,Ke,{}),et._f&&(et._f.mount=!1),(e.shouldUnregister||it.shouldUnregister)&&!(isNameInFieldArray(g.array,Ke)&&f.action)&&g.unMount.add(Ke)}}},at=()=>e.shouldFocusError&&iterateFieldsByAction(o,$e,g.mount),ot=Ke=>{isBoolean(Ke)&&(C.state.next({disabled:Ke}),iterateFieldsByAction(o,(it,et)=>{const ct=get(o,et);ct&&(it.disabled=ct._f.disabled||Ke,Array.isArray(ct._f.refs)&&ct._f.refs.forEach(ft=>{ft.disabled=ct._f.disabled||Ke}))},0,!1))},Ue=(Ke,it)=>async et=>{let ct;et&&(et.preventDefault&&et.preventDefault(),et.persist&&et.persist());let ft=cloneObject(d);if(C.state.next({isSubmitting:!0}),e.resolver){const{errors:dt,values:Rt}=await te();n.errors=dt,ft=Rt}else await se(o);if(g.disabled.size)for(const dt of g.disabled)set(ft,dt,void 0);if(unset(n.errors,"root"),isEmptyObject$1(n.errors)){C.state.next({errors:{}});try{await Ke(ft,et)}catch(dt){ct=dt}}else it&&await it({...n.errors},et),at(),setTimeout(at);if(C.state.next({isSubmitted:!0,isSubmitting:!1,isSubmitSuccessful:isEmptyObject$1(n.errors)&&!ct,submitCount:n.submitCount+1,errors:n.errors}),ct)throw ct},Ct=(Ke,it={})=>{get(o,Ke)&&(isUndefined(it.defaultValue)?Fe(Ke,cloneObject(get(l,Ke))):(Fe(Ke,it.defaultValue),set(l,Ke,cloneObject(it.defaultValue))),it.keepTouched||unset(n.touchedFields,Ke),it.keepDirty||(unset(n.dirtyFields,Ke),n.isDirty=it.defaultValue?oe(Ke,cloneObject(get(l,Ke))):oe()),it.keepError||(unset(n.errors,Ke),S.isValid&&M()),C.state.next({...n}))},Je=(Ke,it={})=>{const et=Ke?cloneObject(Ke):l,ct=cloneObject(et),ft=isEmptyObject$1(Ke),dt=ft?l:ct;if(it.keepDefaultValues||(l=et),!it.keepValues){if(it.keepDirtyValues){const Rt=new Set([...g.mount,...Object.keys(getDirtyFields(l,d))]);for(const zt of Array.from(Rt))get(n.dirtyFields,zt)?set(dt,zt,get(d,zt)):Fe(zt,get(dt,zt))}else{if(isWeb&&isUndefined(Ke))for(const Rt of g.mount){const zt=get(o,Rt);if(zt&&zt._f){const Yt=Array.isArray(zt._f.refs)?zt._f.refs[0]:zt._f.ref;if(isHTMLElement(Yt)){const sr=Yt.closest("form");if(sr){sr.reset();break}}}}for(const Rt of g.mount)Fe(Rt,get(dt,Rt))}d=cloneObject(dt),C.array.next({values:{...dt}}),C.state.next({values:{...dt}})}g={mount:it.keepDirtyValues?g.mount:new Set,unMount:new Set,array:new Set,disabled:new Set,watch:new Set,watchAll:!1,focus:""},f.mount=!S.isValid||!!it.keepIsValid||!!it.keepDirtyValues,f.watch=!!e.shouldUnregister,C.state.next({submitCount:it.keepSubmitCount?n.submitCount:0,isDirty:ft?!1:it.keepDirty?n.isDirty:!!(it.keepDefaultValues&&!deepEqual$1(Ke,l)),isSubmitted:it.keepIsSubmitted?n.isSubmitted:!1,dirtyFields:ft?{}:it.keepDirtyValues?it.keepDefaultValues&&d?getDirtyFields(l,d):n.dirtyFields:it.keepDefaultValues&&Ke?getDirtyFields(l,Ke):it.keepDirty?n.dirtyFields:{},touchedFields:it.keepTouched?n.touchedFields:{},errors:it.keepErrors?n.errors:{},isSubmitSuccessful:it.keepIsSubmitSuccessful?n.isSubmitSuccessful:!1,isSubmitting:!1})},yt=(Ke,it)=>Je(isFunction$3(Ke)?Ke(d):Ke,it),Mt=(Ke,it={})=>{const et=get(o,Ke),ct=et&&et._f;if(ct){const ft=ct.refs?ct.refs[0]:ct.ref;ft.focus&&(ft.focus(),it.shouldSelect&&isFunction$3(ft.select)&&ft.select())}},qt=Ke=>{n={...n,...Ke}},Ft={control:{register:rt,unregister:Xe,getFieldState:Ge,handleSubmit:Ue,setError:Ze,_subscribe:Ye,_runSchema:te,_focusError:at,_getWatch:Ae,_getDirty:oe,_setValid:M,_setFieldArray:j,_setDisabledField:st,_setErrors:z,_getFieldArray:je,_reset:Je,_resetDefaultValues:()=>isFunction$3(e.defaultValues)&&e.defaultValues().then(Ke=>{yt(Ke,e.resetOptions),C.state.next({isLoading:!1})}),_removeUnmounted:ge,_disableForm:ot,_subjects:C,_proxyFormState:S,get _fields(){return o},get _formValues(){return d},get _state(){return f},set _state(Ke){f=Ke},get _defaultValues(){return l},get _names(){return g},set _names(Ke){g=Ke},get _formState(){return n},get _options(){return e},set _options(Ke){e={...e,...Ke}}},subscribe:Qe,trigger:Be,register:rt,handleSubmit:Ue,watch:tt,setValue:Fe,getValues:qe,reset:yt,resetField:Ct,clearErrors:He,unregister:Xe,setError:Ze,setFocus:Mt,getFieldState:Ge};return{...Ft,formControl:Ft}}function useForm(t={}){const e=React.useRef(void 0),n=React.useRef(void 0),[o,l]=React.useState({isDirty:!1,isValidating:!1,isLoading:isFunction$3(t.defaultValues),isSubmitted:!1,isSubmitting:!1,isSubmitSuccessful:!1,isValid:!1,submitCount:0,dirtyFields:{},touchedFields:{},validatingFields:{},errors:t.errors||{},disabled:t.disabled||!1,isReady:!1,defaultValues:isFunction$3(t.defaultValues)?void 0:t.defaultValues});e.current||(e.current={...t.formControl?t.formControl:createFormControl(t),formState:o},t.formControl&&t.defaultValues&&!isFunction$3(t.defaultValues)&&t.formControl.reset(t.defaultValues,t.resetOptions));const d=e.current.control;return d._options=t,useIsomorphicLayoutEffect$1(()=>{const f=d._subscribe({formState:d._proxyFormState,callback:()=>l({...d._formState}),reRenderRoot:!0});return l(g=>({...g,isReady:!0})),d._formState.isReady=!0,f},[d]),React.useEffect(()=>d._disableForm(t.disabled),[d,t.disabled]),React.useEffect(()=>{t.mode&&(d._options.mode=t.mode),t.reValidateMode&&(d._options.reValidateMode=t.reValidateMode)},[d,t.mode,t.reValidateMode]),React.useEffect(()=>{t.errors&&(d._setErrors(t.errors),d._focusError())},[d,t.errors]),React.useEffect(()=>{t.shouldUnregister&&d._subjects.state.next({values:d._getWatch()})},[d,t.shouldUnregister]),React.useEffect(()=>{if(d._proxyFormState.isDirty){const f=d._getDirty();f!==o.isDirty&&d._subjects.state.next({isDirty:f})}},[d,o.isDirty]),React.useEffect(()=>{t.values&&!deepEqual$1(t.values,n.current)?(d._reset(t.values,d._options.resetOptions),n.current=t.values,l(f=>({...f}))):d._resetDefaultValues()},[d,t.values]),React.useEffect(()=>{d._state.mount||(d._setValid(),d._state.mount=!0),d._state.watch&&(d._state.watch=!1,d._subjects.state.next({...d._formState})),d._removeUnmounted()}),e.current.formState=getProxyFormState(o,d),e.current}var defaultErrorHandler=function(t){process.env.NODE_ENV!=="production"&&console.error(t)},defaultWarnHandler=function(t){process.env.NODE_ENV!=="production"&&console.warn(t)},DEFAULT_INTL_CONFIG={formats:{},messages:{},timeZone:void 0,defaultLocale:"en",defaultFormats:{},fallbackOnEmptyString:!0,onError:defaultErrorHandler,onWarn:defaultWarnHandler};function invariant(t,e,n){if(n===void 0&&(n=Error),!t)throw new n(e)}function invariantIntlContext(t){invariant(t,"[React Intl] Could not find required `intl` object. <IntlProvider> needs to exist in the component ancestry.")}__assign$1(__assign$1({},DEFAULT_INTL_CONFIG),{textComponent:React__namespace.Fragment});var reactIs={exports:{}},reactIs_production_min={};/** @license React v16.13.1
|
|
1063
|
+
`+_r),Ue&&arrayForEach([Ae,je,Ne],Cr=>{_r=stringReplace(_r,Cr," ")}),Q&&Ft?Q.createHTML(_r):_r},e.setConfig=function(){let Wt=arguments.length>0&&arguments[0]!==void 0?arguments[0]:{};Ar(Wt),yt=!0},e.clearConfig=function(){jr=null,yt=!1},e.isValidAttribute=function(Wt,nt,It){jr||Ar({});const Ut=mr(Wt),cr=mr(nt);return un(Ut,cr,It)},e.addHook=function(Wt,nt){typeof nt=="function"&&arrayPush(oe[Wt],nt)},e.removeHook=function(Wt,nt){if(nt!==void 0){const It=arrayLastIndexOf(oe[Wt],nt);return It===-1?void 0:arraySplice(oe[Wt],It,1)[0]}return arrayPop(oe[Wt])},e.removeHooks=function(Wt){oe[Wt]=[]},e.removeAllHooks=function(){oe=_createHooksMap()},e}var purify=createDOMPurify();function markdownToSafeHTML(t){const e=marked(t,{async:!1});return purify.sanitize(e,{ALLOWED_TAGS:["h1","h2","h3","h4","h5","h6","b","strong","i","em","u","s","sub","sup","mark","code","pre","blockquote","q","ul","ol","li","dl","dt","dd","p","div","span","br","hr","table","thead","tbody","tfoot","tr","th","td"]})}function SkeletonMessage({botStatus:t}){return jsxRuntime.jsxs("div",{className:"flex items-start gap-2",children:[jsxRuntime.jsx("div",{className:"h-8 w-8 mt-1 rounded-full bg-gray-300 animate-pulse flex-shrink-0"}),jsxRuntime.jsxs("div",{className:"flex flex-col max-w-[70%]",children:[jsxRuntime.jsxs("p",{className:"mb-1",children:["Assistant",jsxRuntime.jsx("span",{className:"text-xs text-muted-foreground mt-1 ml-3",children:new Date().toLocaleTimeString([],{hour:"numeric",minute:"2-digit",hour12:!0})})]}),jsxRuntime.jsx("div",{className:"rounded-md p-3 break-words bg-white border rounded-tl-none",children:jsxRuntime.jsxs("div",{className:"flex items-center space-x-2",children:[jsxRuntime.jsx("div",{className:"h-2 w-2 rounded-full bg-primary animate-pulse"}),jsxRuntime.jsx("div",{className:"h-2 w-2 rounded-full bg-primary animate-pulse delay-150"}),jsxRuntime.jsx("div",{className:"h-2 w-2 rounded-full bg-primary animate-pulse delay-300"}),jsxRuntime.jsx("span",{className:"text-xs text-muted-foreground ml-1",children:t})]})})]})]})}function ChatMessages({messages:t,currentUserId:e,botStatus:n,isAssistantChat:o}){return jsxRuntime.jsxs("div",{children:[t.map(l=>{const d=l.fromPartnerID===e;return jsxRuntime.jsxs("div",{className:cn("flex items-start gap-2 mt-2 mb-2",d&&"flex-row-reverse"),children:[jsxRuntime.jsx(Avatar,{className:"h-8 w-8 mt-1",children:jsxRuntime.jsx(AvatarImage,{src:`https://api.dicebear.com/9.x/thumbs/svg?seed=${md5(l.senderName+l.fromPartnerID)}&flip=${d}`})}),jsxRuntime.jsxs("div",{className:"flex flex-col max-w-[70%]",children:[jsxRuntime.jsxs("p",{className:"mb-1",children:[l.senderName,jsxRuntime.jsx("span",{className:"text-xs text-muted-foreground mt-1 ml-3",children:(()=>{const f=new Date(l.timestamp);return isToday(f)?f.toLocaleTimeString([],{hour:"numeric",minute:"2-digit",hour12:!0}):isYesterday(f)?`Yesterday, ${f.toLocaleTimeString([],{hour:"numeric",minute:"2-digit",hour12:!0})}`:`${f.toLocaleDateString([],{month:"short",day:"numeric"})} ${f.toLocaleTimeString([],{hour:"numeric",minute:"2-digit",hour12:!0})}`})()})]}),jsxRuntime.jsx("div",{className:cn("rounded-md p-3 break-words [&_li]:ml-6 [&_li]:list-disc [&_h1]:text-lg [&_h1]:font-bold [&_h1]:mt-4 [&_h2]:font-bold [&_h2]:mt-4 [&_h3]:mt-4 ",d?"bg-primary text-white rounded-tr-none":"bg-white border rounded-tl-none"),children:parser(markdownToSafeHTML(l.content))})]})]},l.id)}),n!==""&&jsxRuntime.jsx(SkeletonMessage,{botStatus:n}),t.length===0&&!o&&jsxRuntime.jsx("div",{className:"text-center text-muted-foreground py-8",children:"No messages yet"}),t.length===0&&n===""&&o&&jsxRuntime.jsxs("div",{className:"text-center py-8",children:[jsxRuntime.jsx("p",{children:"The Randmar Assistant is ready to help you. Ask anything about products, orders, carts, shipments and tracking numbers."}),jsxRuntime.jsx("p",{children:jsxRuntime.jsx("strong",{children:'Try it now, type "my open orders"!'})})]})]})}var SWITCH_NAME="Switch",[createSwitchContext,createSwitchScope]=createContextScope(SWITCH_NAME),[SwitchProvider,useSwitchContext]=createSwitchContext(SWITCH_NAME),Switch$1=React__namespace.forwardRef((t,e)=>{const{__scopeSwitch:n,name:o,checked:l,defaultChecked:d,required:f,disabled:g,value:b="on",onCheckedChange:_,form:S,...R}=t,[C,E]=React__namespace.useState(null),A=useComposedRefs(e,z=>E(z)),M=React__namespace.useRef(!1),I=C?S||!!C.closest("form"):!0,[j,q]=useControllableState({prop:l,defaultProp:d??!1,onChange:_,caller:SWITCH_NAME});return jsxRuntime.jsxs(SwitchProvider,{scope:n,checked:j,disabled:g,children:[jsxRuntime.jsx(Primitive.button,{type:"button",role:"switch","aria-checked":j,"aria-required":f,"data-state":getState$2(j),"data-disabled":g?"":void 0,disabled:g,value:b,...R,ref:A,onClick:composeEventHandlers(t.onClick,z=>{q(Q=>!Q),I&&(M.current=z.isPropagationStopped(),M.current||z.stopPropagation())})}),I&&jsxRuntime.jsx(SwitchBubbleInput,{control:C,bubbles:!M.current,name:o,value:b,checked:j,required:f,disabled:g,form:S,style:{transform:"translateX(-100%)"}})]})});Switch$1.displayName=SWITCH_NAME;var THUMB_NAME="SwitchThumb",SwitchThumb=React__namespace.forwardRef((t,e)=>{const{__scopeSwitch:n,...o}=t,l=useSwitchContext(THUMB_NAME,n);return jsxRuntime.jsx(Primitive.span,{"data-state":getState$2(l.checked),"data-disabled":l.disabled?"":void 0,...o,ref:e})});SwitchThumb.displayName=THUMB_NAME;var BUBBLE_INPUT_NAME$2="SwitchBubbleInput",SwitchBubbleInput=React__namespace.forwardRef(({__scopeSwitch:t,control:e,checked:n,bubbles:o=!0,...l},d)=>{const f=React__namespace.useRef(null),g=useComposedRefs(f,d),b=usePrevious(n),_=useSize(e);return React__namespace.useEffect(()=>{const S=f.current;if(!S)return;const R=window.HTMLInputElement.prototype,E=Object.getOwnPropertyDescriptor(R,"checked").set;if(b!==n&&E){const A=new Event("click",{bubbles:o});E.call(S,n),S.dispatchEvent(A)}},[b,n,o]),jsxRuntime.jsx("input",{type:"checkbox","aria-hidden":!0,defaultChecked:n,...l,tabIndex:-1,ref:g,style:{...l.style,..._,position:"absolute",pointerEvents:"none",opacity:0,margin:0}})});SwitchBubbleInput.displayName=BUBBLE_INPUT_NAME$2;function getState$2(t){return t?"checked":"unchecked"}var Root$1=Switch$1,Thumb=SwitchThumb;const Switch=React__namespace.forwardRef(({className:t,...e},n)=>jsxRuntime.jsx(Root$1,{className:cn("peer inline-flex h-5 w-9 shrink-0 cursor-pointer items-center rounded-full border-2 border-transparent shadow-sm transition-colors focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-ring focus-visible:ring-offset-2 focus-visible:ring-offset-background disabled:cursor-not-allowed disabled:opacity-50 data-[state=checked]:bg-primary data-[state=unchecked]:bg-input",t),...e,ref:n,children:jsxRuntime.jsx(Thumb,{className:cn("pointer-events-none block h-4 w-4 rounded-full bg-background shadow-lg ring-0 transition-transform data-[state=checked]:translate-x-4 data-[state=unchecked]:translate-x-0")})}));Switch.displayName=Root$1.displayName;const DebugMessageDisplay=({debugMessages:t})=>{const[e,n]=React.useState({}),o=l=>{n(d=>({...d,[l]:!d[l]}))};return jsxRuntime.jsx("div",{children:t.map((l,d)=>{if(typeof l=="string")return jsxRuntime.jsx("p",{className:"text-slate-600",children:l},d);{const f=e[d];return jsxRuntime.jsxs("div",{className:"cursor-pointer",onClick:()=>o(d),children:[jsxRuntime.jsxs("div",{className:"flex items-center",children:[jsxRuntime.jsx("p",{className:"text-slate-600 mr-2",children:l[0]}),jsxRuntime.jsx("span",{className:"text-slate-500 text-xs",children:f?"▲":"▼"})]}),f&&jsxRuntime.jsx("p",{className:"text-slate-400 pl-4",children:l[1]})]},d)}})})},ASSISTANT_ID="RandmarAIChatAssistant",sortChats=(t,e)=>t.unread>0&&e.unread===0?-1:e.unread>0&&t.unread===0?1:t.name.localeCompare(e.name),ChatLayout=React.forwardRef(({userId:t,userName:e,inputRef:n,assistantOnly:o,className:l,initialPrompt:d},f)=>{const{data:g,refetch:b}=useGetV4PartnerByRouteApplicationIdBusinessDevelopmentConversationsQuery({routeApplicationId:t},{skip:o===!0}),[_]=usePostV4PartnerByApplicationIdAccountDebugFeedbackMutation(),[S,{isLoading:R}]=usePostV4PartnerByRouteApplicationIdBusinessDevelopmentConversationPartnerAndPartnerIdMutation(),[C,E]=React.useState(!1),A=React.useRef(null),M=React.useRef(!1),[I]=usePostV4PartnerByRouteApplicationIdBusinessDevelopmentConversationPartnerAndPartnerIdMutation(),[j]=usePostV4PartnerByRouteApplicationIdBusinessDevelopmentConversationAndConversationIdReadMutation(),[q]=useLazyGetV4PartnerByRouteApplicationIdBusinessDevelopmentConversationAndConversationIdMessagesQuery(),{handleSubmitToBot:z,botMessages:Q,clearBotMessages:F,botReady:V,debugMessages:te,botStatus:ne,reset:se}=useAIAssistant({userId:t,smartAndSlow:C});React.useEffect(()=>{const pt={partner1:t,partner2:ASSISTANT_ID,name:"Randmar Assistant",unread:0,pending:!1,messages:[],conversationID:-1};if(o===!0){Be([pt]);return}if(!g)return;(async()=>{const Kt=g.map(async or=>{var Er,gr,xr;const Rr=await q({routeApplicationId:t,conversationId:or.ConversationId});return{partner1:or.Participant1,partner2:or.Participant2,name:((Er=or.Participant)==null?void 0:Er.PublicName)??"missing public name",unread:((gr=Rr.data)==null?void 0:gr.filter(tr=>!tr.Read&&tr.SenderId!=t).length)??0,pending:or.Status!=="Approved",messages:((xr=Rr.data)==null?void 0:xr.map(tr=>({id:"history"+tr.MessageId,fromPartnerID:tr.SenderId,toPartnerID:tr.SenderId==or.Participant1?or.Participant2:or.Participant1,senderName:tr.SenderName??"missing name",timestamp:new Date(tr.SentDate+"Z").getTime(),content:tr.Content??"no content"})))??[],conversationID:or.ConversationId}}),ur=await Promise.all(Kt);ur.sort(sortChats),Be([pt,...ur]),setTimeout(()=>{var or;return(or=Ue.current)==null?void 0:or.focus()},50)})()},[g,o,t]);const[ge,oe]=React.useState("approved"),[Ae,je]=React.useState([t,ASSISTANT_ID]),[Ne,Oe]=React.useState(""),[Fe,ze]=React.useState(null),[$e,Be]=React.useState([]),[qe,Ge]=React.useState(""),[He,Ze]=React.useState(null),tt=React.useRef(null),Ye=React.useRef(null),[Qe,Xe]=React.useState(null),[st,rt]=React.useState([]),[at,ot]=React.useState([]),Ue=n||Ye,Ct=React.useRef(null),{toast:Je}=useToast(),yt=()=>$e.find(pt=>pt.partner1===(Ae==null?void 0:Ae[0])&&pt.partner2===(Ae==null?void 0:Ae[1])),Mt=()=>(Ae==null?void 0:Ae[0])===ASSISTANT_ID||(Ae==null?void 0:Ae[1])===ASSISTANT_ID;function qt(){const pt=yt();pt&&(Mt()||j({routeApplicationId:t,conversationId:pt.conversationID}))}React.useEffect(()=>{d&&V&&(M.current||Mt()&&(M.current=!0,Ke(d)))},[d,V,Ae,M]);const Ht=React.useMemo(()=>$e.filter(pt=>{if(pt.partner1===ASSISTANT_ID||pt.partner2===ASSISTANT_ID)return!0;const Kt=pt.name.toLowerCase().includes(qe.toLowerCase());return ge==="approved"?Kt&&!pt.pending:ge==="pending"?Kt&&pt.pending:Kt}),[$e,qe,ge]);React.useEffect(()=>{var pt;Qe!==null&&(Je({title:"File attached",description:"Add your instruction before sending.",variant:"success"}),(pt=Ue.current)==null||pt.focus())},[Qe]),React.useEffect(()=>{Q.length!==0&&(Q.forEach(pt=>{if(!pt||pt.isComponent)return;const Zt={id:pt.timestamp.toString(),fromPartnerID:ASSISTANT_ID,toPartnerID:t,senderName:"Assistant",timestamp:pt.timestamp.getTime(),content:pt.content};Ft(Zt)}),F())},[Q]);const Ft=pt=>ot(Zt=>[...Zt,pt]);React.useEffect(()=>{at.length!=0&&(at.forEach(pt=>{Be(Zt=>Zt.map(Kt=>{let ur=Kt.partner1===pt.fromPartnerID&&Kt.partner2===pt.toPartnerID;if(ur||(ur=Kt.partner1===pt.toPartnerID&&Kt.partner2===pt.fromPartnerID),!ur||Kt.messages.some(Rr=>Rr.id===pt.id))return Kt;let or=1;return(Ae==null?void 0:Ae[0])==Kt.partner1&&Ae[1]==Kt.partner2&&(or=0,qt(),setTimeout(()=>{var Rr;return(Rr=tt.current)==null?void 0:Rr.scrollIntoView({behavior:"smooth"})},50),Kt.pending&&oe("approved")),{...Kt,pending:!1,unread:Kt.unread+or,messages:[...Kt.messages,pt]}}).sort(sortChats))}),ot([]))},[at,ot,Be,je,Ae]),React.useEffect(()=>{if(o===!0)return;const pt=new HubConnectionBuilder().withUrl("https://api.randmar.io/hub",{accessTokenFactory:()=>localStorage.getItem("access_token"),headers:{"X-Impersonated-Id":t}}).configureLogging(LogLevel.Information).withAutomaticReconnect().withHubProtocol(new JsonHubProtocol).build();return pt.on("ReceiveMessage",Ft),pt.start().catch(Zt=>console.error("Error connecting to SignalR hub:",Zt)),Ze(pt),()=>{pt&&pt.stop()}},[t,o]),React.useEffect(()=>{var Zt;if(!Ae)return;const pt=yt();pt&&((Zt=Ue.current)==null||Zt.focus(),pt.unread>0&&(qt(),Be(Kt=>Kt.map(ur=>ur.partner1===Ae[0]&&ur.partner2===Ae[1]?{...ur,unread:0}:ur))),setTimeout(()=>{var Kt;return(Kt=tt.current)==null?void 0:Kt.scrollIntoView({behavior:"smooth"})},50))},[$e,Ae]);const Ke=pt=>{if(!Ae)return;const Zt={id:crypto.randomUUID(),senderName:e,fromPartnerID:t,toPartnerID:Ae[0]===t?Ae[1]:Ae[0],content:pt+(Qe?` (${Qe==null?void 0:Qe.name} attached)`:""),timestamp:Date.now()};Ft(Zt),Zt.toPartnerID==ASSISTANT_ID?(z(Zt.content,Qe??void 0),Qe&&rt(Kt=>[...Kt,Qe.name])):He.invoke("NewMessage",Zt).catch(Kt=>console.error("Error sending message:",Kt)),Oe(""),Xe(null),Ct.current&&(Ct.current.value="")},it=(pt,Zt)=>ze([pt,Zt]);if(React.useEffect(()=>{if(Fe===null)return;const pt=$e.find(Kt=>Kt.conversationID===Fe[0]);if(!pt||(pt.pending&&oe("pending"),je([pt.partner1,pt.partner2]),Fe[0]===-1&&!V)||Fe[0]!==-1&&!He)return;const Zt=Fe[1];ze(null),Zt&&Ke(Zt)},[Fe,$e,oe,je,V,He]),React.useImperativeHandle(f,()=>({setActiveChatAndSendMessage:it})),!V)return jsxRuntime.jsx(jsxRuntime.Fragment,{children:jsxRuntime.jsx("div",{className:"flex items-center justify-center p-8",children:jsxRuntime.jsxs("div",{className:"text-center",children:[jsxRuntime.jsx("div",{className:"animate-spin rounded-full h-12 w-12 border-b-2 border-primary mx-auto mb-4"}),jsxRuntime.jsx("p",{children:"Loading API functions..."})]})})});const et=pt=>{var Kt;if(!Mt())return;const Zt=(Kt=pt.clipboardData)==null?void 0:Kt.items;if(Zt){for(let ur=0;ur<Zt.length;ur++)if(Zt[ur].type.indexOf("image")!==-1){const or=Zt[ur].getAsFile();if(or){Xe(or);return}}}},ct=()=>{!Ne.trim()||!Ae||o!==!0&&!He||Ke(Ne)},ft=pt=>{pt.target.files&&pt.target.files[0]?Xe(pt.target.files[0]):Xe(null)},dt=()=>{var pt;(pt=Ct.current)==null||pt.click()},Rt=()=>{var pt;Xe(null),Je({title:"File removed",description:"No file will be sent to the assistant.",variant:"secondary"}),(pt=Ue.current)==null||pt.focus()},zt=()=>{const Zt={messages:$e.find(Kt=>Kt.partner1===ASSISTANT_ID||Kt.partner2===ASSISTANT_ID),debug:te};_({applicationId:t,emailAddress:e,body:Zt})},Yt=async()=>{A.current&&(A.current.disabled=!0),await I({routeApplicationId:t,partnerId:"2"}),await b()},sr=()=>{Be(pt=>pt.map(Kt=>Kt.partner1!==ASSISTANT_ID&&Kt.partner2!==ASSISTANT_ID?Kt:{...Kt,messages:[]})),rt([]),se()},dr=()=>{Ae&&S({routeApplicationId:t,partnerId:Ae[0]==t?Ae[1]:Ae[0]}).then(()=>{oe("approved")})},mt=yt(),Sr=$e.filter(pt=>pt.pending).length;return jsxRuntime.jsxs("div",{className:cn("flex overflow-hidden",l),children:[o!==!0&&jsxRuntime.jsx(jsxRuntime.Fragment,{children:jsxRuntime.jsxs("div",{className:"w-[260px] p-4 pt-3 flex flex-col border-r",children:[jsxRuntime.jsx("div",{className:"p-4 font-semibold border-b",children:"Communications"}),$e.length>1&&jsxRuntime.jsxs(jsxRuntime.Fragment,{children:[jsxRuntime.jsx("div",{className:"p-2",children:jsxRuntime.jsxs("div",{className:"relative",children:[jsxRuntime.jsx(Search,{className:"absolute left-2 top-1/2 transform -translate-y-1/2 h-4 w-4 text-muted-foreground"}),jsxRuntime.jsx(Input,{placeholder:"Search chats...",className:"pl-8 h-9",value:qe,onChange:pt=>Ge(pt.target.value)})]})}),jsxRuntime.jsx(Tabs,{value:ge,onValueChange:oe,className:"w-full mb-1",children:jsxRuntime.jsxs(TabsList,{className:"grid grid-cols-6 h-9 mx-2",children:[jsxRuntime.jsx(TabsTrigger,{value:"approved",className:"text-xs col-span-3",children:"Approved"}),jsxRuntime.jsxs(TabsTrigger,{value:"pending",className:"text-xs col-span-3",children:["Pending ",Sr>0&&`(${Sr})`]})]})})]}),jsxRuntime.jsx("div",{className:"mt-1 mb-1",children:$e.findIndex(pt=>pt.partner1==="2"||pt.partner2==="2")<0?jsxRuntime.jsx(Button,{className:"w-full",ref:A,onClick:()=>Yt(),children:"Chat with Randmar"},"b1"):ge==="approved"&&$e.length>=5?null:jsxRuntime.jsx(reactRouterDom.Link,{to:`${window.location.hostname==="dashboard.randmar.io"?"":"https://dashboard.randmar.io"}/${t}/ExploreManufacturers`,target:window.location.hostname==="dashboard.randmar.io"?"_self":"_blank",children:jsxRuntime.jsx(Button,{className:"w-full",children:"Explore Manufacturers"},"b2")})}),jsxRuntime.jsx(ScrollArea,{className:"flex-1",children:$e.length>0&&jsxRuntime.jsx(ChatList,{userId:t,chats:Ht.filter(pt=>pt.partner1!==ASSISTANT_ID&&pt.partner2!==ASSISTANT_ID),activeChat:mt??null,onSelectChat:je})}),jsxRuntime.jsx(Separator$1,{className:"mt-auto"}),jsxRuntime.jsx("div",{className:"pt-1",children:$e.find(pt=>pt.partner1===ASSISTANT_ID||pt.partner2===ASSISTANT_ID)&&jsxRuntime.jsx(ChatList,{userId:t,chats:Ht.filter(pt=>pt.partner1===ASSISTANT_ID||pt.partner2===ASSISTANT_ID),activeChat:mt??null,onSelectChat:je,assistantStickyMode:!0})})]})}),jsxRuntime.jsx("div",{className:"flex-5 flex flex-col",children:Ae?jsxRuntime.jsxs(jsxRuntime.Fragment,{children:[jsxRuntime.jsx("div",{className:"flex items-center p-4 border-b",children:Ae[0]==ASSISTANT_ID||Ae[1]==ASSISTANT_ID?jsxRuntime.jsxs(jsxRuntime.Fragment,{children:[jsxRuntime.jsx(Avatar,{className:"h-8 w-8 flex-shrink-0 rounded-none",children:jsxRuntime.jsx(Bot,{className:"text-primary fill-white min-h-full"})}),jsxRuntime.jsx("div",{className:"ml-3 font-medium",children:"Randmar Assistant"}),jsxRuntime.jsxs("div",{className:"flex items-center space-x-2 ml-auto",children:[jsxRuntime.jsx(Switch,{id:"smartSwitch",disabled:!!ne,checked:C,onCheckedChange:pt=>{sr(),setTimeout(()=>E(pt),20)}}),jsxRuntime.jsx(Label$2,{htmlFor:"smartSwitch",children:"Think harder"})]}),jsxRuntime.jsx(Button,{variant:"ghost",size:"icon",className:"ml-1",onClick:()=>sr(),children:jsxRuntime.jsx(MessageCircleX,{className:"h-5 w-5"})}),jsxRuntime.jsx(Button,{variant:"ghost",size:"icon",className:"ml-1",confirmationDialog:{title:"Report Issue",content:"This action will send a copy of your chat to Randmar. Send it?",onConfirm:()=>zt()},children:jsxRuntime.jsx(MessageSquareShare,{className:"h-5 w-5"})})]}):jsxRuntime.jsxs(jsxRuntime.Fragment,{children:[jsxRuntime.jsx(Avatar,{className:"h-8 w-8 flex-shrink-0 rounded-none",children:jsxRuntime.jsx(PartnerLogo,{id:Ae[0]===t?Ae[1]:Ae[0],width:72,height:72})}),jsxRuntime.jsx("div",{className:"ml-3 font-medium",children:mt==null?void 0:mt.name}),jsxRuntime.jsx("div",{className:"flex items-center space-x-2 ml-auto",children:jsxRuntime.jsx(reactRouterDom.Link,{to:`${window.location.hostname==="dashboard.randmar.io"?"":"https://dashboard.randmar.io"}/${t}/Partner/${Ae[0]===t?Ae[1]:Ae[0]}`,target:window.location.hostname==="dashboard.randmar.io"?"_self":"_blank",children:jsxRuntime.jsx(Button,{children:"View Partner"})})})]})}),mt!=null&&mt.pending&&mt.partner1==t?jsxRuntime.jsx("p",{className:"mt-8 p-2 mx-auto",children:"This conversation is awaiting approval by the other party — please check back later."}):jsxRuntime.jsxs(jsxRuntime.Fragment,{children:[jsxRuntime.jsxs(ScrollArea,{className:"flex-1 pl-2 pr-2 bg-slate-50",children:[jsxRuntime.jsx(ChatMessages,{messages:(mt==null?void 0:mt.messages)??[],currentUserId:t,isAssistantChat:Mt(),botStatus:Mt()?ne:""}),jsxRuntime.jsx("div",{ref:tt})]}),jsxRuntime.jsxs("div",{className:"p-4 border-t border-r flex",children:[(mt==null?void 0:mt.pending)&&jsxRuntime.jsxs(jsxRuntime.Fragment,{children:[jsxRuntime.jsxs(Button,{disabled:R,onClick:()=>dr(),children:[jsxRuntime.jsx(Handshake,{}),"Accept Conversation Request"]}),jsxRuntime.jsxs(Button,{disabled:!0,className:"ml-2",children:[jsxRuntime.jsx(ThumbsDown,{}),"Block Partner"]})]}),jsxRuntime.jsx(Textarea,{ref:Ue,placeholder:"Type a message...",value:Ne,onPaste:et,onChange:pt=>Oe(pt.target.value),onKeyDown:pt=>{pt.key!=="Enter"||pt.shiftKey||(pt.preventDefault(),ct())},className:mt!=null&&mt.pending?"collapse":"flex-1 resize-none"}),jsxRuntime.jsxs("div",{className:"flex items-center",children:[jsxRuntime.jsx(Button,{size:"icon",variant:"default",className:mt!=null&&mt.pending?"collapse":"ml-2 h-8 w-8",disabled:!!ne||(mt==null?void 0:mt.pending),onClick:ct,children:jsxRuntime.jsx(Send,{className:"h-6 w-6"})}),Mt()&&jsxRuntime.jsxs(jsxRuntime.Fragment,{children:[jsxRuntime.jsx(Input,{type:"file",onChange:ft,className:"hidden",ref:Ct}),jsxRuntime.jsx(Button,{size:"icon",variant:"default",onClick:dt,className:mt!=null&&mt.pending?"collapse":"ml-2 h-8 w-8",disabled:ne!==""||(mt==null?void 0:mt.pending)||!!Qe,children:jsxRuntime.jsx(Paperclip,{className:"h-5 w-5"})}),jsxRuntime.jsx(Button,{size:"icon",variant:"default",onClick:Rt,className:mt!=null&&mt.pending?"collapse":"ml-2 h-8 w-8",disabled:ne!==""||(mt==null?void 0:mt.pending)||!Qe,children:jsxRuntime.jsx(Trash,{className:"h-5 w-5"})})]})]})]})]})]}):jsxRuntime.jsx("div",{className:"flex-1 flex items-center justify-center text-muted-foreground",children:"Select a chat to start messaging"})}),jsxRuntime.jsx("div",{"data-thin":Mt(),className:"w-[480px] flex flex-col border-l flex-4 data-[thin=true]:flex-2",children:Mt()?jsxRuntime.jsxs(jsxRuntime.Fragment,{children:[jsxRuntime.jsx("div",{className:"flex items-center p-4 border-b",children:jsxRuntime.jsx("p",{className:"h-9 text-base/9",children:"Sources and System Info"})}),jsxRuntime.jsx(ScrollArea,{className:"flex-1 pl-2 pr-2 bg-slate-50",children:jsxRuntime.jsxs("div",{className:"space-y-2",children:[Qe?jsxRuntime.jsx(jsxRuntime.Fragment,{children:jsxRuntime.jsxs("div",{className:"flex",children:[jsxRuntime.jsx(File,{})," ",Qe.name," (pending send...)"]})}):st.length?jsxRuntime.jsx(jsxRuntime.Fragment,{}):jsxRuntime.jsx("p",{children:"No files attached to this conversation yet."}),st.slice().reverse().map(pt=>jsxRuntime.jsx(jsxRuntime.Fragment,{children:jsxRuntime.jsxs("div",{className:"flex",children:[jsxRuntime.jsx(File,{})," ",pt]})}))]})}),jsxRuntime.jsx(ScrollArea,{className:"flex-4 border-t pl-2 pr-2 bg-slate-50",children:jsxRuntime.jsx("div",{className:"space-y-2",children:jsxRuntime.jsx(DebugMessageDisplay,{debugMessages:te})})})]}):jsxRuntime.jsxs(jsxRuntime.Fragment,{children:[jsxRuntime.jsx("div",{className:"flex items-center p-4 border-b",children:jsxRuntime.jsx("p",{className:"h-9 text-base/9",children:"Partner Overview"})}),jsxRuntime.jsx(ScrollArea,{className:"flex-1 pl-2 pr-2 bg-slate-50",children:jsxRuntime.jsx("div",{className:"mt-1",children:jsxRuntime.jsx(PartnerRelationshipPage,{applicationId:t,partnerId:((Ae==null?void 0:Ae[0])===t?Ae[1]:Ae==null?void 0:Ae[0])??t,userEmail:e,shopifyHostName:void 0,isSuperAdmin:!1})})})]})})]})});function UnsavedChangesDialog({isOpen:t,onClose:e,onConfirm:n,title:o,description:l,confirmText:d="Confirm",cancelText:f="Cancel"}){return jsxRuntime.jsx(Dialog,{open:t,onOpenChange:e,children:jsxRuntime.jsxs(DialogContent,{className:"sm:max-w-[425px]",children:[jsxRuntime.jsxs(DialogHeader,{children:[jsxRuntime.jsx(DialogTitle,{children:o}),jsxRuntime.jsx(DialogDescription,{children:l})]}),jsxRuntime.jsxs(DialogFooter,{children:[jsxRuntime.jsx(Button,{variant:"outline",onClick:e,children:f}),jsxRuntime.jsx(Button,{onClick:n,children:d})]})]})})}function useRouterNavigationGuard(t){const[e,n]=React.useState(!1),o=reactRouterDom.useBlocker(React.useCallback(({currentLocation:g,nextLocation:b})=>{const _=g.pathname!==b.pathname||g.search!==b.search||g.hash!==b.hash;return t()&&_},[t]));React.useEffect(()=>{o.state==="blocked"&&n(!0)},[o]),React.useEffect(()=>{const g=b=>{if(t())return b.preventDefault(),"You have unsaved changes. Are you sure you want to leave?"};return window.addEventListener("beforeunload",g),()=>{window.removeEventListener("beforeunload",g)}},[t]);const l=React.useCallback(()=>{n(!1),o.state==="blocked"&&o.proceed()},[o]),d=React.useCallback(()=>{n(!1),o.state==="blocked"&&o.reset()},[o]),f=React.useCallback(()=>jsxRuntime.jsx(UnsavedChangesDialog,{isOpen:e,onClose:d,onConfirm:l,title:"Unsaved Changes",description:"You have unsaved changes. Are you sure you want to leave? Your changes will be lost.",confirmText:"Discard Changes",cancelText:"Stay on Page"}),[e,d,l]);return{showDialog:e,handleConfirm:l,handleCancel:d,NavigationGuardDialog:f}}var isCheckBoxInput=t=>t.type==="checkbox",isDateObject=t=>t instanceof Date,isNullOrUndefined=t=>t==null;const isObjectType=t=>typeof t=="object";var isObject=t=>!isNullOrUndefined(t)&&!Array.isArray(t)&&isObjectType(t)&&!isDateObject(t),getEventValue=t=>isObject(t)&&t.target?isCheckBoxInput(t.target)?t.target.checked:t.target.value:t,getNodeParentName=t=>t.substring(0,t.search(/\.\d+(\.|$)/))||t,isNameInFieldArray=(t,e)=>t.has(getNodeParentName(e)),isPlainObject$1=t=>{const e=t.constructor&&t.constructor.prototype;return isObject(e)&&e.hasOwnProperty("isPrototypeOf")},isWeb=typeof window<"u"&&typeof window.HTMLElement<"u"&&typeof document<"u";function cloneObject(t){let e;const n=Array.isArray(t),o=typeof FileList<"u"?t instanceof FileList:!1;if(t instanceof Date)e=new Date(t);else if(t instanceof Set)e=new Set(t);else if(!(isWeb&&(t instanceof Blob||o))&&(n||isObject(t)))if(e=n?[]:{},!n&&!isPlainObject$1(t))e=t;else for(const l in t)t.hasOwnProperty(l)&&(e[l]=cloneObject(t[l]));else return t;return e}var compact=t=>Array.isArray(t)?t.filter(Boolean):[],isUndefined=t=>t===void 0,get=(t,e,n)=>{if(!e||!isObject(t))return n;const o=compact(e.split(/[,[\].]+?/)).reduce((l,d)=>isNullOrUndefined(l)?l:l[d],t);return isUndefined(o)||o===t?isUndefined(t[e])?n:t[e]:o},isBoolean=t=>typeof t=="boolean",isKey=t=>/^\w*$/.test(t),stringToPath=t=>compact(t.replace(/["|']|\]/g,"").split(/\.|\[/)),set=(t,e,n)=>{let o=-1;const l=isKey(e)?[e]:stringToPath(e),d=l.length,f=d-1;for(;++o<d;){const g=l[o];let b=n;if(o!==f){const _=t[g];b=isObject(_)||Array.isArray(_)?_:isNaN(+l[o+1])?{}:[]}if(g==="__proto__"||g==="constructor"||g==="prototype")return;t[g]=b,t=t[g]}};const EVENTS={BLUR:"blur",FOCUS_OUT:"focusout"},VALIDATION_MODE={onBlur:"onBlur",onChange:"onChange",onSubmit:"onSubmit",onTouched:"onTouched",all:"all"},INPUT_VALIDATION_RULES={max:"max",min:"min",maxLength:"maxLength",minLength:"minLength",pattern:"pattern",required:"required",validate:"validate"};React.createContext(null);var getProxyFormState=(t,e,n,o=!0)=>{const l={defaultValues:e._defaultValues};for(const d in t)Object.defineProperty(l,d,{get:()=>{const f=d;return e._proxyFormState[f]!==VALIDATION_MODE.all&&(e._proxyFormState[f]=!o||VALIDATION_MODE.all),t[f]}});return l};const useIsomorphicLayoutEffect$1=typeof window<"u"?React__namespace.useLayoutEffect:React__namespace.useEffect;var isString=t=>typeof t=="string",generateWatchOutput=(t,e,n,o,l)=>isString(t)?(o&&e.watch.add(t),get(n,t,l)):Array.isArray(t)?t.map(d=>(o&&e.watch.add(d),get(n,d))):(o&&(e.watchAll=!0),n),appendErrors=(t,e,n,o,l)=>e?{...n[t],types:{...n[t]&&n[t].types?n[t].types:{},[o]:l||!0}}:{},convertToArrayPayload=t=>Array.isArray(t)?t:[t],createSubject=()=>{let t=[];return{get observers(){return t},next:l=>{for(const d of t)d.next&&d.next(l)},subscribe:l=>(t.push(l),{unsubscribe:()=>{t=t.filter(d=>d!==l)}}),unsubscribe:()=>{t=[]}}},isPrimitive=t=>isNullOrUndefined(t)||!isObjectType(t);function deepEqual$1(t,e){if(isPrimitive(t)||isPrimitive(e))return t===e;if(isDateObject(t)&&isDateObject(e))return t.getTime()===e.getTime();const n=Object.keys(t),o=Object.keys(e);if(n.length!==o.length)return!1;for(const l of n){const d=t[l];if(!o.includes(l))return!1;if(l!=="ref"){const f=e[l];if(isDateObject(d)&&isDateObject(f)||isObject(d)&&isObject(f)||Array.isArray(d)&&Array.isArray(f)?!deepEqual$1(d,f):d!==f)return!1}}return!0}var isEmptyObject$1=t=>isObject(t)&&!Object.keys(t).length,isFileInput=t=>t.type==="file",isFunction$3=t=>typeof t=="function",isHTMLElement=t=>{if(!isWeb)return!1;const e=t?t.ownerDocument:0;return t instanceof(e&&e.defaultView?e.defaultView.HTMLElement:HTMLElement)},isMultipleSelect=t=>t.type==="select-multiple",isRadioInput=t=>t.type==="radio",isRadioOrCheckbox=t=>isRadioInput(t)||isCheckBoxInput(t),live=t=>isHTMLElement(t)&&t.isConnected;function baseGet(t,e){const n=e.slice(0,-1).length;let o=0;for(;o<n;)t=isUndefined(t)?o++:t[e[o++]];return t}function isEmptyArray(t){for(const e in t)if(t.hasOwnProperty(e)&&!isUndefined(t[e]))return!1;return!0}function unset(t,e){const n=Array.isArray(e)?e:isKey(e)?[e]:stringToPath(e),o=n.length===1?t:baseGet(t,n),l=n.length-1,d=n[l];return o&&delete o[d],l!==0&&(isObject(o)&&isEmptyObject$1(o)||Array.isArray(o)&&isEmptyArray(o))&&unset(t,n.slice(0,-1)),t}var objectHasFunction=t=>{for(const e in t)if(isFunction$3(t[e]))return!0;return!1};function markFieldsDirty(t,e={}){const n=Array.isArray(t);if(isObject(t)||n)for(const o in t)Array.isArray(t[o])||isObject(t[o])&&!objectHasFunction(t[o])?(e[o]=Array.isArray(t[o])?[]:{},markFieldsDirty(t[o],e[o])):isNullOrUndefined(t[o])||(e[o]=!0);return e}function getDirtyFieldsFromDefaultValues(t,e,n){const o=Array.isArray(t);if(isObject(t)||o)for(const l in t)Array.isArray(t[l])||isObject(t[l])&&!objectHasFunction(t[l])?isUndefined(e)||isPrimitive(n[l])?n[l]=Array.isArray(t[l])?markFieldsDirty(t[l],[]):{...markFieldsDirty(t[l])}:getDirtyFieldsFromDefaultValues(t[l],isNullOrUndefined(e)?{}:e[l],n[l]):n[l]=!deepEqual$1(t[l],e[l]);return n}var getDirtyFields=(t,e)=>getDirtyFieldsFromDefaultValues(t,e,markFieldsDirty(e));const defaultResult={value:!1,isValid:!1},validResult={value:!0,isValid:!0};var getCheckboxValue=t=>{if(Array.isArray(t)){if(t.length>1){const e=t.filter(n=>n&&n.checked&&!n.disabled).map(n=>n.value);return{value:e,isValid:!!e.length}}return t[0].checked&&!t[0].disabled?t[0].attributes&&!isUndefined(t[0].attributes.value)?isUndefined(t[0].value)||t[0].value===""?validResult:{value:t[0].value,isValid:!0}:validResult:defaultResult}return defaultResult},getFieldValueAs=(t,{valueAsNumber:e,valueAsDate:n,setValueAs:o})=>isUndefined(t)?t:e?t===""?NaN:t&&+t:n&&isString(t)?new Date(t):o?o(t):t;const defaultReturn={isValid:!1,value:null};var getRadioValue=t=>Array.isArray(t)?t.reduce((e,n)=>n&&n.checked&&!n.disabled?{isValid:!0,value:n.value}:e,defaultReturn):defaultReturn;function getFieldValue(t){const e=t.ref;return isFileInput(e)?e.files:isRadioInput(e)?getRadioValue(t.refs).value:isMultipleSelect(e)?[...e.selectedOptions].map(({value:n})=>n):isCheckBoxInput(e)?getCheckboxValue(t.refs).value:getFieldValueAs(isUndefined(e.value)?t.ref.value:e.value,t)}var getResolverOptions=(t,e,n,o)=>{const l={};for(const d of t){const f=get(e,d);f&&set(l,d,f._f)}return{criteriaMode:n,names:[...t],fields:l,shouldUseNativeValidation:o}},isRegex=t=>t instanceof RegExp,getRuleValue=t=>isUndefined(t)?t:isRegex(t)?t.source:isObject(t)?isRegex(t.value)?t.value.source:t.value:t,getValidationModes=t=>({isOnSubmit:!t||t===VALIDATION_MODE.onSubmit,isOnBlur:t===VALIDATION_MODE.onBlur,isOnChange:t===VALIDATION_MODE.onChange,isOnAll:t===VALIDATION_MODE.all,isOnTouch:t===VALIDATION_MODE.onTouched});const ASYNC_FUNCTION="AsyncFunction";var hasPromiseValidation=t=>!!t&&!!t.validate&&!!(isFunction$3(t.validate)&&t.validate.constructor.name===ASYNC_FUNCTION||isObject(t.validate)&&Object.values(t.validate).find(e=>e.constructor.name===ASYNC_FUNCTION)),hasValidation=t=>t.mount&&(t.required||t.min||t.max||t.maxLength||t.minLength||t.pattern||t.validate),isWatched=(t,e,n)=>!n&&(e.watchAll||e.watch.has(t)||[...e.watch].some(o=>t.startsWith(o)&&/^\.\w+/.test(t.slice(o.length))));const iterateFieldsByAction=(t,e,n,o)=>{for(const l of n||Object.keys(t)){const d=get(t,l);if(d){const{_f:f,...g}=d;if(f){if(f.refs&&f.refs[0]&&e(f.refs[0],l)&&!o)return!0;if(f.ref&&e(f.ref,f.name)&&!o)return!0;if(iterateFieldsByAction(g,e))break}else if(isObject(g)&&iterateFieldsByAction(g,e))break}}};function schemaErrorLookup(t,e,n){const o=get(t,n);if(o||isKey(n))return{error:o,name:n};const l=n.split(".");for(;l.length;){const d=l.join("."),f=get(e,d),g=get(t,d);if(f&&!Array.isArray(f)&&n!==d)return{name:n};if(g&&g.type)return{name:d,error:g};if(g&&g.root&&g.root.type)return{name:`${d}.root`,error:g.root};l.pop()}return{name:n}}var shouldRenderFormState=(t,e,n,o)=>{n(t);const{name:l,...d}=t;return isEmptyObject$1(d)||Object.keys(d).length>=Object.keys(e).length||Object.keys(d).find(f=>e[f]===(!o||VALIDATION_MODE.all))},shouldSubscribeByName=(t,e,n)=>!t||!e||t===e||convertToArrayPayload(t).some(o=>o&&(n?o===e:o.startsWith(e)||e.startsWith(o))),skipValidation=(t,e,n,o,l)=>l.isOnAll?!1:!n&&l.isOnTouch?!(e||t):(n?o.isOnBlur:l.isOnBlur)?!t:(n?o.isOnChange:l.isOnChange)?t:!0,unsetEmptyArray=(t,e)=>!compact(get(t,e)).length&&unset(t,e),updateFieldArrayRootError=(t,e,n)=>{const o=convertToArrayPayload(get(t,n));return set(o,"root",e[n]),set(t,n,o),t},isMessage=t=>isString(t);function getValidateError(t,e,n="validate"){if(isMessage(t)||Array.isArray(t)&&t.every(isMessage)||isBoolean(t)&&!t)return{type:n,message:isMessage(t)?t:"",ref:e}}var getValueAndMessage=t=>isObject(t)&&!isRegex(t)?t:{value:t,message:""},validateField=async(t,e,n,o,l,d)=>{const{ref:f,refs:g,required:b,maxLength:_,minLength:S,min:R,max:C,pattern:E,validate:A,name:M,valueAsNumber:I,mount:j}=t._f,q=get(n,M);if(!j||e.has(M))return{};const z=g?g[0]:f,Q=Ae=>{l&&z.reportValidity&&(z.setCustomValidity(isBoolean(Ae)?"":Ae||""),z.reportValidity())},F={},V=isRadioInput(f),te=isCheckBoxInput(f),ne=V||te,se=(I||isFileInput(f))&&isUndefined(f.value)&&isUndefined(q)||isHTMLElement(f)&&f.value===""||q===""||Array.isArray(q)&&!q.length,ge=appendErrors.bind(null,M,o,F),oe=(Ae,je,Ne,Oe=INPUT_VALIDATION_RULES.maxLength,Fe=INPUT_VALIDATION_RULES.minLength)=>{const ze=Ae?je:Ne;F[M]={type:Ae?Oe:Fe,message:ze,ref:f,...ge(Ae?Oe:Fe,ze)}};if(d?!Array.isArray(q)||!q.length:b&&(!ne&&(se||isNullOrUndefined(q))||isBoolean(q)&&!q||te&&!getCheckboxValue(g).isValid||V&&!getRadioValue(g).isValid)){const{value:Ae,message:je}=isMessage(b)?{value:!!b,message:b}:getValueAndMessage(b);if(Ae&&(F[M]={type:INPUT_VALIDATION_RULES.required,message:je,ref:z,...ge(INPUT_VALIDATION_RULES.required,je)},!o))return Q(je),F}if(!se&&(!isNullOrUndefined(R)||!isNullOrUndefined(C))){let Ae,je;const Ne=getValueAndMessage(C),Oe=getValueAndMessage(R);if(!isNullOrUndefined(q)&&!isNaN(q)){const Fe=f.valueAsNumber||q&&+q;isNullOrUndefined(Ne.value)||(Ae=Fe>Ne.value),isNullOrUndefined(Oe.value)||(je=Fe<Oe.value)}else{const Fe=f.valueAsDate||new Date(q),ze=qe=>new Date(new Date().toDateString()+" "+qe),$e=f.type=="time",Be=f.type=="week";isString(Ne.value)&&q&&(Ae=$e?ze(q)>ze(Ne.value):Be?q>Ne.value:Fe>new Date(Ne.value)),isString(Oe.value)&&q&&(je=$e?ze(q)<ze(Oe.value):Be?q<Oe.value:Fe<new Date(Oe.value))}if((Ae||je)&&(oe(!!Ae,Ne.message,Oe.message,INPUT_VALIDATION_RULES.max,INPUT_VALIDATION_RULES.min),!o))return Q(F[M].message),F}if((_||S)&&!se&&(isString(q)||d&&Array.isArray(q))){const Ae=getValueAndMessage(_),je=getValueAndMessage(S),Ne=!isNullOrUndefined(Ae.value)&&q.length>+Ae.value,Oe=!isNullOrUndefined(je.value)&&q.length<+je.value;if((Ne||Oe)&&(oe(Ne,Ae.message,je.message),!o))return Q(F[M].message),F}if(E&&!se&&isString(q)){const{value:Ae,message:je}=getValueAndMessage(E);if(isRegex(Ae)&&!q.match(Ae)&&(F[M]={type:INPUT_VALIDATION_RULES.pattern,message:je,ref:f,...ge(INPUT_VALIDATION_RULES.pattern,je)},!o))return Q(je),F}if(A){if(isFunction$3(A)){const Ae=await A(q,n),je=getValidateError(Ae,z);if(je&&(F[M]={...je,...ge(INPUT_VALIDATION_RULES.validate,je.message)},!o))return Q(je.message),F}else if(isObject(A)){let Ae={};for(const je in A){if(!isEmptyObject$1(Ae)&&!o)break;const Ne=getValidateError(await A[je](q,n),z,je);Ne&&(Ae={...Ne,...ge(je,Ne.message)},Q(Ne.message),o&&(F[M]=Ae))}if(!isEmptyObject$1(Ae)&&(F[M]={ref:z,...Ae},!o))return F}}return Q(!0),F};const defaultOptions$1={mode:VALIDATION_MODE.onSubmit,reValidateMode:VALIDATION_MODE.onChange,shouldFocusError:!0};function createFormControl(t={}){let e={...defaultOptions$1,...t},n={submitCount:0,isDirty:!1,isReady:!1,isLoading:isFunction$3(e.defaultValues),isValidating:!1,isSubmitted:!1,isSubmitting:!1,isSubmitSuccessful:!1,isValid:!1,touchedFields:{},dirtyFields:{},validatingFields:{},errors:e.errors||{},disabled:e.disabled||!1};const o={};let l=isObject(e.defaultValues)||isObject(e.values)?cloneObject(e.defaultValues||e.values)||{}:{},d=e.shouldUnregister?{}:cloneObject(l),f={action:!1,mount:!1,watch:!1},g={mount:new Set,disabled:new Set,unMount:new Set,array:new Set,watch:new Set},b,_=0;const S={isDirty:!1,dirtyFields:!1,validatingFields:!1,touchedFields:!1,isValidating:!1,isValid:!1,errors:!1};let R={...S};const C={array:createSubject(),state:createSubject()},E=e.criteriaMode===VALIDATION_MODE.all,A=Ke=>it=>{clearTimeout(_),_=setTimeout(Ke,it)},M=async Ke=>{if(!e.disabled&&(S.isValid||R.isValid||Ke)){const it=e.resolver?isEmptyObject$1((await te()).errors):await se(o,!0);it!==n.isValid&&C.state.next({isValid:it})}},I=(Ke,it)=>{!e.disabled&&(S.isValidating||S.validatingFields||R.isValidating||R.validatingFields)&&((Ke||Array.from(g.mount)).forEach(et=>{et&&(it?set(n.validatingFields,et,it):unset(n.validatingFields,et))}),C.state.next({validatingFields:n.validatingFields,isValidating:!isEmptyObject$1(n.validatingFields)}))},j=(Ke,it=[],et,ct,ft=!0,dt=!0)=>{if(ct&&et&&!e.disabled){if(f.action=!0,dt&&Array.isArray(get(o,Ke))){const Rt=et(get(o,Ke),ct.argA,ct.argB);ft&&set(o,Ke,Rt)}if(dt&&Array.isArray(get(n.errors,Ke))){const Rt=et(get(n.errors,Ke),ct.argA,ct.argB);ft&&set(n.errors,Ke,Rt),unsetEmptyArray(n.errors,Ke)}if((S.touchedFields||R.touchedFields)&&dt&&Array.isArray(get(n.touchedFields,Ke))){const Rt=et(get(n.touchedFields,Ke),ct.argA,ct.argB);ft&&set(n.touchedFields,Ke,Rt)}(S.dirtyFields||R.dirtyFields)&&(n.dirtyFields=getDirtyFields(l,d)),C.state.next({name:Ke,isDirty:oe(Ke,it),dirtyFields:n.dirtyFields,errors:n.errors,isValid:n.isValid})}else set(d,Ke,it)},q=(Ke,it)=>{set(n.errors,Ke,it),C.state.next({errors:n.errors})},z=Ke=>{n.errors=Ke,C.state.next({errors:n.errors,isValid:!1})},Q=(Ke,it,et,ct)=>{const ft=get(o,Ke);if(ft){const dt=get(d,Ke,isUndefined(et)?get(l,Ke):et);isUndefined(dt)||ct&&ct.defaultChecked||it?set(d,Ke,it?dt:getFieldValue(ft._f)):Ne(Ke,dt),f.mount&&M()}},F=(Ke,it,et,ct,ft)=>{let dt=!1,Rt=!1;const zt={name:Ke};if(!e.disabled){if(!et||ct){(S.isDirty||R.isDirty)&&(Rt=n.isDirty,n.isDirty=zt.isDirty=oe(),dt=Rt!==zt.isDirty);const Yt=deepEqual$1(get(l,Ke),it);Rt=!!get(n.dirtyFields,Ke),Yt?unset(n.dirtyFields,Ke):set(n.dirtyFields,Ke,!0),zt.dirtyFields=n.dirtyFields,dt=dt||(S.dirtyFields||R.dirtyFields)&&Rt!==!Yt}if(et){const Yt=get(n.touchedFields,Ke);Yt||(set(n.touchedFields,Ke,et),zt.touchedFields=n.touchedFields,dt=dt||(S.touchedFields||R.touchedFields)&&Yt!==et)}dt&&ft&&C.state.next(zt)}return dt?zt:{}},V=(Ke,it,et,ct)=>{const ft=get(n.errors,Ke),dt=(S.isValid||R.isValid)&&isBoolean(it)&&n.isValid!==it;if(e.delayError&&et?(b=A(()=>q(Ke,et)),b(e.delayError)):(clearTimeout(_),b=null,et?set(n.errors,Ke,et):unset(n.errors,Ke)),(et?!deepEqual$1(ft,et):ft)||!isEmptyObject$1(ct)||dt){const Rt={...ct,...dt&&isBoolean(it)?{isValid:it}:{},errors:n.errors,name:Ke};n={...n,...Rt},C.state.next(Rt)}},te=async Ke=>{I(Ke,!0);const it=await e.resolver(d,e.context,getResolverOptions(Ke||g.mount,o,e.criteriaMode,e.shouldUseNativeValidation));return I(Ke),it},ne=async Ke=>{const{errors:it}=await te(Ke);if(Ke)for(const et of Ke){const ct=get(it,et);ct?set(n.errors,et,ct):unset(n.errors,et)}else n.errors=it;return it},se=async(Ke,it,et={valid:!0})=>{for(const ct in Ke){const ft=Ke[ct];if(ft){const{_f:dt,...Rt}=ft;if(dt){const zt=g.array.has(dt.name),Yt=ft._f&&hasPromiseValidation(ft._f);Yt&&S.validatingFields&&I([ct],!0);const sr=await validateField(ft,g.disabled,d,E,e.shouldUseNativeValidation&&!it,zt);if(Yt&&S.validatingFields&&I([ct]),sr[dt.name]&&(et.valid=!1,it))break;!it&&(get(sr,dt.name)?zt?updateFieldArrayRootError(n.errors,sr,dt.name):set(n.errors,dt.name,sr[dt.name]):unset(n.errors,dt.name))}!isEmptyObject$1(Rt)&&await se(Rt,it,et)}}return et.valid},ge=()=>{for(const Ke of g.unMount){const it=get(o,Ke);it&&(it._f.refs?it._f.refs.every(et=>!live(et)):!live(it._f.ref))&&Xe(Ke)}g.unMount=new Set},oe=(Ke,it)=>!e.disabled&&(Ke&&it&&set(d,Ke,it),!deepEqual$1(qe(),l)),Ae=(Ke,it,et)=>generateWatchOutput(Ke,g,{...f.mount?d:isUndefined(it)?l:isString(Ke)?{[Ke]:it}:it},et,it),je=Ke=>compact(get(f.mount?d:l,Ke,e.shouldUnregister?get(l,Ke,[]):[])),Ne=(Ke,it,et={})=>{const ct=get(o,Ke);let ft=it;if(ct){const dt=ct._f;dt&&(!dt.disabled&&set(d,Ke,getFieldValueAs(it,dt)),ft=isHTMLElement(dt.ref)&&isNullOrUndefined(it)?"":it,isMultipleSelect(dt.ref)?[...dt.ref.options].forEach(Rt=>Rt.selected=ft.includes(Rt.value)):dt.refs?isCheckBoxInput(dt.ref)?dt.refs.forEach(Rt=>{(!Rt.defaultChecked||!Rt.disabled)&&(Array.isArray(ft)?Rt.checked=!!ft.find(zt=>zt===Rt.value):Rt.checked=ft===Rt.value||!!ft)}):dt.refs.forEach(Rt=>Rt.checked=Rt.value===ft):isFileInput(dt.ref)?dt.ref.value="":(dt.ref.value=ft,dt.ref.type||C.state.next({name:Ke,values:cloneObject(d)})))}(et.shouldDirty||et.shouldTouch)&&F(Ke,ft,et.shouldTouch,et.shouldDirty,!0),et.shouldValidate&&Be(Ke)},Oe=(Ke,it,et)=>{for(const ct in it){if(!it.hasOwnProperty(ct))return;const ft=it[ct],dt=Ke+"."+ct,Rt=get(o,dt);(g.array.has(Ke)||isObject(ft)||Rt&&!Rt._f)&&!isDateObject(ft)?Oe(dt,ft,et):Ne(dt,ft,et)}},Fe=(Ke,it,et={})=>{const ct=get(o,Ke),ft=g.array.has(Ke),dt=cloneObject(it);set(d,Ke,dt),ft?(C.array.next({name:Ke,values:cloneObject(d)}),(S.isDirty||S.dirtyFields||R.isDirty||R.dirtyFields)&&et.shouldDirty&&C.state.next({name:Ke,dirtyFields:getDirtyFields(l,d),isDirty:oe(Ke,dt)})):ct&&!ct._f&&!isNullOrUndefined(dt)?Oe(Ke,dt,et):Ne(Ke,dt,et),isWatched(Ke,g)&&C.state.next({...n}),C.state.next({name:f.mount?Ke:void 0,values:cloneObject(d)})},ze=async Ke=>{f.mount=!0;const it=Ke.target;let et=it.name,ct=!0;const ft=get(o,et),dt=Yt=>{ct=Number.isNaN(Yt)||isDateObject(Yt)&&isNaN(Yt.getTime())||deepEqual$1(Yt,get(d,et,Yt))},Rt=getValidationModes(e.mode),zt=getValidationModes(e.reValidateMode);if(ft){let Yt,sr;const dr=it.type?getFieldValue(ft._f):getEventValue(Ke),mt=Ke.type===EVENTS.BLUR||Ke.type===EVENTS.FOCUS_OUT,Sr=!hasValidation(ft._f)&&!e.resolver&&!get(n.errors,et)&&!ft._f.deps||skipValidation(mt,get(n.touchedFields,et),n.isSubmitted,zt,Rt),pt=isWatched(et,g,mt);set(d,et,dr),mt?(ft._f.onBlur&&ft._f.onBlur(Ke),b&&b(0)):ft._f.onChange&&ft._f.onChange(Ke);const Zt=F(et,dr,mt),Kt=!isEmptyObject$1(Zt)||pt;if(!mt&&C.state.next({name:et,type:Ke.type,values:cloneObject(d)}),Sr)return(S.isValid||R.isValid)&&(e.mode==="onBlur"?mt&&M():mt||M()),Kt&&C.state.next({name:et,...pt?{}:Zt});if(!mt&&pt&&C.state.next({...n}),e.resolver){const{errors:ur}=await te([et]);if(dt(dr),ct){const or=schemaErrorLookup(n.errors,o,et),Rr=schemaErrorLookup(ur,o,or.name||et);Yt=Rr.error,et=Rr.name,sr=isEmptyObject$1(ur)}}else I([et],!0),Yt=(await validateField(ft,g.disabled,d,E,e.shouldUseNativeValidation))[et],I([et]),dt(dr),ct&&(Yt?sr=!1:(S.isValid||R.isValid)&&(sr=await se(o,!0)));ct&&(ft._f.deps&&Be(ft._f.deps),V(et,sr,Yt,Zt))}},$e=(Ke,it)=>{if(get(n.errors,it)&&Ke.focus)return Ke.focus(),1},Be=async(Ke,it={})=>{let et,ct;const ft=convertToArrayPayload(Ke);if(e.resolver){const dt=await ne(isUndefined(Ke)?Ke:ft);et=isEmptyObject$1(dt),ct=Ke?!ft.some(Rt=>get(dt,Rt)):et}else Ke?(ct=(await Promise.all(ft.map(async dt=>{const Rt=get(o,dt);return await se(Rt&&Rt._f?{[dt]:Rt}:Rt)}))).every(Boolean),!(!ct&&!n.isValid)&&M()):ct=et=await se(o);return C.state.next({...!isString(Ke)||(S.isValid||R.isValid)&&et!==n.isValid?{}:{name:Ke},...e.resolver||!Ke?{isValid:et}:{},errors:n.errors}),it.shouldFocus&&!ct&&iterateFieldsByAction(o,$e,Ke?ft:g.mount),ct},qe=Ke=>{const it={...f.mount?d:l};return isUndefined(Ke)?it:isString(Ke)?get(it,Ke):Ke.map(et=>get(it,et))},Ge=(Ke,it)=>({invalid:!!get((it||n).errors,Ke),isDirty:!!get((it||n).dirtyFields,Ke),error:get((it||n).errors,Ke),isValidating:!!get(n.validatingFields,Ke),isTouched:!!get((it||n).touchedFields,Ke)}),He=Ke=>{Ke&&convertToArrayPayload(Ke).forEach(it=>unset(n.errors,it)),C.state.next({errors:Ke?n.errors:{}})},Ze=(Ke,it,et)=>{const ct=(get(o,Ke,{_f:{}})._f||{}).ref,ft=get(n.errors,Ke)||{},{ref:dt,message:Rt,type:zt,...Yt}=ft;set(n.errors,Ke,{...Yt,...it,ref:ct}),C.state.next({name:Ke,errors:n.errors,isValid:!1}),et&&et.shouldFocus&&ct&&ct.focus&&ct.focus()},tt=(Ke,it)=>isFunction$3(Ke)?C.state.subscribe({next:et=>Ke(Ae(void 0,it),et)}):Ae(Ke,it,!0),Ye=Ke=>C.state.subscribe({next:it=>{shouldSubscribeByName(Ke.name,it.name,Ke.exact)&&shouldRenderFormState(it,Ke.formState||S,qt,Ke.reRenderRoot)&&Ke.callback({values:{...d},...n,...it})}}).unsubscribe,Qe=Ke=>(f.mount=!0,R={...R,...Ke.formState},Ye({...Ke,formState:R})),Xe=(Ke,it={})=>{for(const et of Ke?convertToArrayPayload(Ke):g.mount)g.mount.delete(et),g.array.delete(et),it.keepValue||(unset(o,et),unset(d,et)),!it.keepError&&unset(n.errors,et),!it.keepDirty&&unset(n.dirtyFields,et),!it.keepTouched&&unset(n.touchedFields,et),!it.keepIsValidating&&unset(n.validatingFields,et),!e.shouldUnregister&&!it.keepDefaultValue&&unset(l,et);C.state.next({values:cloneObject(d)}),C.state.next({...n,...it.keepDirty?{isDirty:oe()}:{}}),!it.keepIsValid&&M()},st=({disabled:Ke,name:it})=>{(isBoolean(Ke)&&f.mount||Ke||g.disabled.has(it))&&(Ke?g.disabled.add(it):g.disabled.delete(it))},rt=(Ke,it={})=>{let et=get(o,Ke);const ct=isBoolean(it.disabled)||isBoolean(e.disabled);return set(o,Ke,{...et||{},_f:{...et&&et._f?et._f:{ref:{name:Ke}},name:Ke,mount:!0,...it}}),g.mount.add(Ke),et?st({disabled:isBoolean(it.disabled)?it.disabled:e.disabled,name:Ke}):Q(Ke,!0,it.value),{...ct?{disabled:it.disabled||e.disabled}:{},...e.progressive?{required:!!it.required,min:getRuleValue(it.min),max:getRuleValue(it.max),minLength:getRuleValue(it.minLength),maxLength:getRuleValue(it.maxLength),pattern:getRuleValue(it.pattern)}:{},name:Ke,onChange:ze,onBlur:ze,ref:ft=>{if(ft){rt(Ke,it),et=get(o,Ke);const dt=isUndefined(ft.value)&&ft.querySelectorAll&&ft.querySelectorAll("input,select,textarea")[0]||ft,Rt=isRadioOrCheckbox(dt),zt=et._f.refs||[];if(Rt?zt.find(Yt=>Yt===dt):dt===et._f.ref)return;set(o,Ke,{_f:{...et._f,...Rt?{refs:[...zt.filter(live),dt,...Array.isArray(get(l,Ke))?[{}]:[]],ref:{type:dt.type,name:Ke}}:{ref:dt}}}),Q(Ke,!1,void 0,dt)}else et=get(o,Ke,{}),et._f&&(et._f.mount=!1),(e.shouldUnregister||it.shouldUnregister)&&!(isNameInFieldArray(g.array,Ke)&&f.action)&&g.unMount.add(Ke)}}},at=()=>e.shouldFocusError&&iterateFieldsByAction(o,$e,g.mount),ot=Ke=>{isBoolean(Ke)&&(C.state.next({disabled:Ke}),iterateFieldsByAction(o,(it,et)=>{const ct=get(o,et);ct&&(it.disabled=ct._f.disabled||Ke,Array.isArray(ct._f.refs)&&ct._f.refs.forEach(ft=>{ft.disabled=ct._f.disabled||Ke}))},0,!1))},Ue=(Ke,it)=>async et=>{let ct;et&&(et.preventDefault&&et.preventDefault(),et.persist&&et.persist());let ft=cloneObject(d);if(C.state.next({isSubmitting:!0}),e.resolver){const{errors:dt,values:Rt}=await te();n.errors=dt,ft=Rt}else await se(o);if(g.disabled.size)for(const dt of g.disabled)set(ft,dt,void 0);if(unset(n.errors,"root"),isEmptyObject$1(n.errors)){C.state.next({errors:{}});try{await Ke(ft,et)}catch(dt){ct=dt}}else it&&await it({...n.errors},et),at(),setTimeout(at);if(C.state.next({isSubmitted:!0,isSubmitting:!1,isSubmitSuccessful:isEmptyObject$1(n.errors)&&!ct,submitCount:n.submitCount+1,errors:n.errors}),ct)throw ct},Ct=(Ke,it={})=>{get(o,Ke)&&(isUndefined(it.defaultValue)?Fe(Ke,cloneObject(get(l,Ke))):(Fe(Ke,it.defaultValue),set(l,Ke,cloneObject(it.defaultValue))),it.keepTouched||unset(n.touchedFields,Ke),it.keepDirty||(unset(n.dirtyFields,Ke),n.isDirty=it.defaultValue?oe(Ke,cloneObject(get(l,Ke))):oe()),it.keepError||(unset(n.errors,Ke),S.isValid&&M()),C.state.next({...n}))},Je=(Ke,it={})=>{const et=Ke?cloneObject(Ke):l,ct=cloneObject(et),ft=isEmptyObject$1(Ke),dt=ft?l:ct;if(it.keepDefaultValues||(l=et),!it.keepValues){if(it.keepDirtyValues){const Rt=new Set([...g.mount,...Object.keys(getDirtyFields(l,d))]);for(const zt of Array.from(Rt))get(n.dirtyFields,zt)?set(dt,zt,get(d,zt)):Fe(zt,get(dt,zt))}else{if(isWeb&&isUndefined(Ke))for(const Rt of g.mount){const zt=get(o,Rt);if(zt&&zt._f){const Yt=Array.isArray(zt._f.refs)?zt._f.refs[0]:zt._f.ref;if(isHTMLElement(Yt)){const sr=Yt.closest("form");if(sr){sr.reset();break}}}}for(const Rt of g.mount)Fe(Rt,get(dt,Rt))}d=cloneObject(dt),C.array.next({values:{...dt}}),C.state.next({values:{...dt}})}g={mount:it.keepDirtyValues?g.mount:new Set,unMount:new Set,array:new Set,disabled:new Set,watch:new Set,watchAll:!1,focus:""},f.mount=!S.isValid||!!it.keepIsValid||!!it.keepDirtyValues,f.watch=!!e.shouldUnregister,C.state.next({submitCount:it.keepSubmitCount?n.submitCount:0,isDirty:ft?!1:it.keepDirty?n.isDirty:!!(it.keepDefaultValues&&!deepEqual$1(Ke,l)),isSubmitted:it.keepIsSubmitted?n.isSubmitted:!1,dirtyFields:ft?{}:it.keepDirtyValues?it.keepDefaultValues&&d?getDirtyFields(l,d):n.dirtyFields:it.keepDefaultValues&&Ke?getDirtyFields(l,Ke):it.keepDirty?n.dirtyFields:{},touchedFields:it.keepTouched?n.touchedFields:{},errors:it.keepErrors?n.errors:{},isSubmitSuccessful:it.keepIsSubmitSuccessful?n.isSubmitSuccessful:!1,isSubmitting:!1})},yt=(Ke,it)=>Je(isFunction$3(Ke)?Ke(d):Ke,it),Mt=(Ke,it={})=>{const et=get(o,Ke),ct=et&&et._f;if(ct){const ft=ct.refs?ct.refs[0]:ct.ref;ft.focus&&(ft.focus(),it.shouldSelect&&isFunction$3(ft.select)&&ft.select())}},qt=Ke=>{n={...n,...Ke}},Ft={control:{register:rt,unregister:Xe,getFieldState:Ge,handleSubmit:Ue,setError:Ze,_subscribe:Ye,_runSchema:te,_focusError:at,_getWatch:Ae,_getDirty:oe,_setValid:M,_setFieldArray:j,_setDisabledField:st,_setErrors:z,_getFieldArray:je,_reset:Je,_resetDefaultValues:()=>isFunction$3(e.defaultValues)&&e.defaultValues().then(Ke=>{yt(Ke,e.resetOptions),C.state.next({isLoading:!1})}),_removeUnmounted:ge,_disableForm:ot,_subjects:C,_proxyFormState:S,get _fields(){return o},get _formValues(){return d},get _state(){return f},set _state(Ke){f=Ke},get _defaultValues(){return l},get _names(){return g},set _names(Ke){g=Ke},get _formState(){return n},get _options(){return e},set _options(Ke){e={...e,...Ke}}},subscribe:Qe,trigger:Be,register:rt,handleSubmit:Ue,watch:tt,setValue:Fe,getValues:qe,reset:yt,resetField:Ct,clearErrors:He,unregister:Xe,setError:Ze,setFocus:Mt,getFieldState:Ge};return{...Ft,formControl:Ft}}function useForm(t={}){const e=React.useRef(void 0),n=React.useRef(void 0),[o,l]=React.useState({isDirty:!1,isValidating:!1,isLoading:isFunction$3(t.defaultValues),isSubmitted:!1,isSubmitting:!1,isSubmitSuccessful:!1,isValid:!1,submitCount:0,dirtyFields:{},touchedFields:{},validatingFields:{},errors:t.errors||{},disabled:t.disabled||!1,isReady:!1,defaultValues:isFunction$3(t.defaultValues)?void 0:t.defaultValues});e.current||(e.current={...t.formControl?t.formControl:createFormControl(t),formState:o},t.formControl&&t.defaultValues&&!isFunction$3(t.defaultValues)&&t.formControl.reset(t.defaultValues,t.resetOptions));const d=e.current.control;return d._options=t,useIsomorphicLayoutEffect$1(()=>{const f=d._subscribe({formState:d._proxyFormState,callback:()=>l({...d._formState}),reRenderRoot:!0});return l(g=>({...g,isReady:!0})),d._formState.isReady=!0,f},[d]),React.useEffect(()=>d._disableForm(t.disabled),[d,t.disabled]),React.useEffect(()=>{t.mode&&(d._options.mode=t.mode),t.reValidateMode&&(d._options.reValidateMode=t.reValidateMode)},[d,t.mode,t.reValidateMode]),React.useEffect(()=>{t.errors&&(d._setErrors(t.errors),d._focusError())},[d,t.errors]),React.useEffect(()=>{t.shouldUnregister&&d._subjects.state.next({values:d._getWatch()})},[d,t.shouldUnregister]),React.useEffect(()=>{if(d._proxyFormState.isDirty){const f=d._getDirty();f!==o.isDirty&&d._subjects.state.next({isDirty:f})}},[d,o.isDirty]),React.useEffect(()=>{t.values&&!deepEqual$1(t.values,n.current)?(d._reset(t.values,d._options.resetOptions),n.current=t.values,l(f=>({...f}))):d._resetDefaultValues()},[d,t.values]),React.useEffect(()=>{d._state.mount||(d._setValid(),d._state.mount=!0),d._state.watch&&(d._state.watch=!1,d._subjects.state.next({...d._formState})),d._removeUnmounted()}),e.current.formState=getProxyFormState(o,d),e.current}var defaultErrorHandler=function(t){process.env.NODE_ENV!=="production"&&console.error(t)},defaultWarnHandler=function(t){process.env.NODE_ENV!=="production"&&console.warn(t)},DEFAULT_INTL_CONFIG={formats:{},messages:{},timeZone:void 0,defaultLocale:"en",defaultFormats:{},fallbackOnEmptyString:!0,onError:defaultErrorHandler,onWarn:defaultWarnHandler};function invariant(t,e,n){if(n===void 0&&(n=Error),!t)throw new n(e)}function invariantIntlContext(t){invariant(t,"[React Intl] Could not find required `intl` object. <IntlProvider> needs to exist in the component ancestry.")}__assign$1(__assign$1({},DEFAULT_INTL_CONFIG),{textComponent:React__namespace.Fragment});var reactIs={exports:{}},reactIs_production_min={};/** @license React v16.13.1
|
|
1064
1064
|
* react-is.production.min.js
|
|
1065
1065
|
*
|
|
1066
1066
|
* Copyright (c) Facebook, Inc. and its affiliates.
|
|
@@ -1081,7 +1081,7 @@ Please report this to https://github.com/markedjs/marked.`,t){const o="<p>An err
|
|
|
1081
1081
|
|
|
1082
1082
|
Defaulting to \`null\`.`}var Root=Progress$1,Indicator=ProgressIndicator;const Progress=React__namespace.forwardRef(({className:t,value:e,...n},o)=>jsxRuntime.jsx(Root,{ref:o,className:cn("relative h-2 w-full overflow-hidden rounded-full bg-primary/20",t),...n,children:jsxRuntime.jsx(Indicator,{className:"h-full w-full flex-1 bg-primary transition-all",style:{transform:`translateX(-${100-(e||0)}%)`}})}));Progress.displayName=Root.displayName;function ManufacturerInventoryFinanceCard({manufacturer:t,isLoading:e}){const{data:n,isLoading:o,isFetching:l}=useGetV4ManufacturerByRouteManufacturerIdInventoryValueQuery({routeManufacturerId:(t==null?void 0:t.ManufacturerId)??""},{skip:!(t!=null&&t.ManufacturerId)}),d=(t==null?void 0:t.DefaultMaxInventoryValue)??0,f=(n||[]).reduce((_,S)=>_+(S.InventoryValue||0),0),g=d-f,b=Math.round(f/d*100);return e||o||l?jsxRuntime.jsxs(Card,{children:[jsxRuntime.jsxs(CardHeader,{children:[jsxRuntime.jsx(Skeleton,{className:"h-7 w-3/4"}),jsxRuntime.jsx(Skeleton,{className:"h-5 w-1/2 mt-2"})]}),jsxRuntime.jsxs(CardContent,{className:"space-y-6",children:[jsxRuntime.jsxs("div",{className:"space-y-4",children:[jsxRuntime.jsxs("div",{className:"flex items-center justify-between",children:[jsxRuntime.jsx(Skeleton,{className:"h-5 w-1/3"}),jsxRuntime.jsx(Skeleton,{className:"h-5 w-1/4"})]}),jsxRuntime.jsxs("div",{className:"flex items-center justify-between",children:[jsxRuntime.jsx(Skeleton,{className:"h-5 w-1/3"}),jsxRuntime.jsx(Skeleton,{className:"h-5 w-1/4"})]}),jsxRuntime.jsxs("div",{className:"flex items-center justify-between",children:[jsxRuntime.jsx(Skeleton,{className:"h-5 w-1/3"}),jsxRuntime.jsx(Skeleton,{className:"h-5 w-1/4"})]})]}),jsxRuntime.jsxs("div",{className:"space-y-2",children:[jsxRuntime.jsxs("div",{className:"flex items-center justify-between",children:[jsxRuntime.jsx(Skeleton,{className:"h-5 w-1/3"}),jsxRuntime.jsx(Skeleton,{className:"h-5 w-16"})]}),jsxRuntime.jsx(Skeleton,{className:"h-2 w-full"})]})]})]}):jsxRuntime.jsxs(Card,{children:[jsxRuntime.jsxs(CardHeader,{children:[jsxRuntime.jsxs(CardTitle,{className:"flex items-center gap-2",children:[jsxRuntime.jsx(DollarSign,{className:"h-5 w-5 text-muted-foreground"}),"Inventory Finance"]}),jsxRuntime.jsx(CardDescription,{children:"Current inventory financial status"})]}),jsxRuntime.jsxs(CardContent,{className:"space-y-6",children:[jsxRuntime.jsxs("div",{className:"space-y-2",children:[jsxRuntime.jsxs("div",{className:"flex items-center justify-between",children:[jsxRuntime.jsx("span",{className:"text-sm font-medium",children:"Max Allowance"}),jsxRuntime.jsx("span",{className:"font-bold",children:formatMoney(d)})]}),jsxRuntime.jsxs("div",{className:"flex items-center justify-between",children:[jsxRuntime.jsx("span",{className:"text-sm font-medium",children:"Current Funds"}),jsxRuntime.jsx("span",{className:"font-bold",children:formatMoney(f)})]}),jsxRuntime.jsxs("div",{className:"flex items-center justify-between",children:[jsxRuntime.jsx("span",{className:"text-sm font-medium",children:"Available Funds"}),jsxRuntime.jsx("span",{className:`font-bold ${g>=0?"text-emerald-600 dark:text-emerald-500":"text-red-600 dark:text-red-500"}`,children:formatMoney(g)})]})]}),jsxRuntime.jsxs("div",{className:"space-y-2",children:[jsxRuntime.jsxs("div",{className:"flex items-center justify-between",children:[jsxRuntime.jsx("span",{className:"text-sm font-medium",children:"Budget Usage"}),jsxRuntime.jsx(TooltipProvider,{children:jsxRuntime.jsxs(Tooltip$1,{children:[jsxRuntime.jsx(TooltipTrigger,{asChild:!0,children:jsxRuntime.jsxs("div",{className:"flex items-center gap-1",children:[jsxRuntime.jsxs("span",{className:"text-sm font-medium",children:[b,"%"]}),b>80&&jsxRuntime.jsx(CircleAlert,{className:"h-4 w-4 text-amber-500"})]})}),jsxRuntime.jsx(TooltipContent,{children:jsxRuntime.jsx("p",{children:b>80?"High usage alert":"Budget usage"})})]})})]}),jsxRuntime.jsx(Progress,{value:b,className:"h-2"})]})]})]})}function ManufacturerCreditFinanceCard({manufacturer:t,isLoading:e}){const n=(t==null?void 0:t.CreditLimit)??0,o=(t==null?void 0:t.OutstandingBalance)??0,l=n-o,d=Math.round(o/n*100);return e?jsxRuntime.jsxs(Card,{children:[jsxRuntime.jsxs(CardHeader,{children:[jsxRuntime.jsx(Skeleton,{className:"h-7 w-3/4"}),jsxRuntime.jsx(Skeleton,{className:"h-5 w-1/2 mt-2"})]}),jsxRuntime.jsxs(CardContent,{className:"space-y-6",children:[jsxRuntime.jsxs("div",{className:"space-y-4",children:[jsxRuntime.jsxs("div",{className:"flex items-center justify-between",children:[jsxRuntime.jsx(Skeleton,{className:"h-5 w-1/3"}),jsxRuntime.jsx(Skeleton,{className:"h-5 w-1/4"})]}),jsxRuntime.jsxs("div",{className:"flex items-center justify-between",children:[jsxRuntime.jsx(Skeleton,{className:"h-5 w-1/3"}),jsxRuntime.jsx(Skeleton,{className:"h-5 w-1/4"})]}),jsxRuntime.jsxs("div",{className:"flex items-center justify-between",children:[jsxRuntime.jsx(Skeleton,{className:"h-5 w-1/3"}),jsxRuntime.jsx(Skeleton,{className:"h-5 w-1/4"})]})]}),jsxRuntime.jsxs("div",{className:"space-y-2",children:[jsxRuntime.jsxs("div",{className:"flex items-center justify-between",children:[jsxRuntime.jsx(Skeleton,{className:"h-5 w-1/3"}),jsxRuntime.jsx(Skeleton,{className:"h-5 w-16"})]}),jsxRuntime.jsx(Skeleton,{className:"h-2 w-full"})]})]})]}):jsxRuntime.jsxs(Card,{children:[jsxRuntime.jsxs(CardHeader,{children:[jsxRuntime.jsxs(CardTitle,{className:"flex items-center gap-2",children:[jsxRuntime.jsx(CreditCard,{className:"h-5 w-5 text-muted-foreground"}),"Credit Finance"]}),jsxRuntime.jsx(CardDescription,{children:"Current credit financial status"})]}),jsxRuntime.jsxs(CardContent,{className:"space-y-6",children:[jsxRuntime.jsxs("div",{className:"space-y-2",children:[jsxRuntime.jsxs("div",{className:"flex items-center justify-between",children:[jsxRuntime.jsx("span",{className:"text-sm font-medium",children:"Credit Limit"}),jsxRuntime.jsx("span",{className:"font-bold",children:formatMoney(n)})]}),jsxRuntime.jsxs("div",{className:"flex items-center justify-between",children:[jsxRuntime.jsx("span",{className:"text-sm font-medium",children:"Outstanding Balance"}),jsxRuntime.jsx("span",{className:"font-bold",children:formatMoney(o)})]}),jsxRuntime.jsxs("div",{className:"flex items-center justify-between",children:[jsxRuntime.jsx("span",{className:"text-sm font-medium",children:"Available Credit"}),jsxRuntime.jsx("span",{className:`font-bold ${l>=0?"text-emerald-600 dark:text-emerald-500":"text-red-600 dark:text-red-500"}`,children:formatMoney(l)})]})]}),jsxRuntime.jsxs("div",{className:"space-y-2",children:[jsxRuntime.jsxs("div",{className:"flex items-center justify-between",children:[jsxRuntime.jsx("span",{className:"text-sm font-medium",children:"Credit Usage"}),jsxRuntime.jsx(TooltipProvider,{children:jsxRuntime.jsxs(Tooltip$1,{children:[jsxRuntime.jsx(TooltipTrigger,{asChild:!0,children:jsxRuntime.jsxs("div",{className:"flex items-center gap-1",children:[jsxRuntime.jsxs("span",{className:"text-sm font-medium",children:[d,"%"]}),d>80&&jsxRuntime.jsx(CircleAlert,{className:"h-4 w-4 text-amber-500"})]})}),jsxRuntime.jsx(TooltipContent,{children:jsxRuntime.jsx("p",{children:d>80?"High credit usage alert":"Credit usage"})})]})})]}),jsxRuntime.jsx(Progress,{value:d,className:"h-2"})]})]})]})}function SalesChartCard({statistics:t,loading:e=!1,mode:n="month",chartHeight:o=300,className:l,size:d="default"}){return e?jsxRuntime.jsxs(Card,{className:cn("w-full",l),children:[jsxRuntime.jsx(CardHeader,{children:jsxRuntime.jsx(Skeleton,{className:"h-7 w-48 rounded-md"})}),jsxRuntime.jsxs(CardContent,{children:[jsxRuntime.jsx("div",{style:{height:o},children:jsxRuntime.jsx(Skeleton,{className:"h-full w-full rounded-md"})}),d==="default"&&n==="month"&&jsxRuntime.jsxs("div",{className:"mt-4 flex items-center space-x-2",children:[jsxRuntime.jsx(Skeleton,{className:"h-5 w-10 rounded-full"}),jsxRuntime.jsx(Skeleton,{className:"h-4 w-40 rounded-md"})]})]})]}):jsxRuntime.jsxs(Card,{className:cn("w-full",l),children:[jsxRuntime.jsx(CardHeader,{children:jsxRuntime.jsx(CardTitle,{children:n==="week"?"Weekly Sales Performance":"Monthly Sales Performance"})}),jsxRuntime.jsx(CardContent,{children:jsxRuntime.jsx(SalesChart,{statistics:t,mode:n,chartHeight:o,size:d})})]})}function ManufacturerOverviewPage({applicationId:t,readonly:e,withReports:n,manufacturer:o,userEmail:l}){const{data:d,isLoading:f,isError:g}=useGetV4PartnerByApplicationIdAccountManufacturerQuery({applicationId:t,withSpecification:!0},{skip:!!o}),[b,_]=React.useState({publicInfo:{hasUnsavedChanges:!1},qualifications:{hasUnsavedChanges:!1},billingInfo:{hasUnsavedChanges:!1}}),S=React.useCallback(()=>e?!1:b.publicInfo.hasUnsavedChanges||b.qualifications.hasUnsavedChanges||b.billingInfo.hasUnsavedChanges,[e,b]),R=React.useCallback((A,M)=>{_(I=>{var j;return((j=I[A])==null?void 0:j.hasUnsavedChanges)!==M.hasUnsavedChanges?(console.log(`Updating form state for ${A}:`,M.hasUnsavedChanges),{...I,[A]:M}):I})},[]),{NavigationGuardDialog:C}=useRouterNavigationGuard(S),E=o??d;return jsxRuntime.jsxs("div",{className:"@container",children:[g?jsxRuntime.jsx(Card,{className:"p-6",children:jsxRuntime.jsxs(Alert,{variant:"destructive",children:[jsxRuntime.jsx(CircleAlert,{className:"h-4 w-4"}),jsxRuntime.jsx(AlertTitle,{children:"Error"}),jsxRuntime.jsx(AlertDescription,{children:"There was an error loading your manufacturer information. Please try again later."})]})}):jsxRuntime.jsxs("div",{className:"space-y-6 mb-6",children:[jsxRuntime.jsx(SalesSummary,{fiscalYearMonthStart:E==null?void 0:E.FiscalYearMonthStart,salesData:E==null?void 0:E.SalesData,isLoading:f}),jsxRuntime.jsxs("div",{className:"grid @2xl:grid-cols-2 gap-6",children:[jsxRuntime.jsx(SalesChartCard,{statistics:(E==null?void 0:E.SalesStatistics)??[],loading:f}),jsxRuntime.jsx(ManufacturerResellerOrdersSection,{manufacturerId:(E==null?void 0:E.ManufacturerId)??"",activeOrders:(E==null?void 0:E.ActiveOrderDetails)??void 0,isLoading:f}),n&&jsxRuntime.jsx(ManufacturerInventoryFinanceCard,{manufacturer:E,isLoading:f}),n&&jsxRuntime.jsx(ManufacturerCreditFinanceCard,{manufacturer:E,isLoading:f}),n&&jsxRuntime.jsx(ManufacturerReorderingCard,{manufacturer:E??{},onSave:()=>{},loading:f,readonly:e}),n&&jsxRuntime.jsx(ManufacturerPublicInfoSection,{manufacturer:E,readonly:e,isLoading:f,onUnsavedChanges:A=>R("publicInfo",{hasUnsavedChanges:A})}),n&&jsxRuntime.jsx(OpenToWorkSection,{manufacturer:E,readonly:e,isLoading:f}),n&&jsxRuntime.jsx(ManufacturerBillingInfoSection,{manufacturer:E,readonly:e,isLoading:f,onUnsavedChanges:A=>R("billingInfo",{hasUnsavedChanges:A})}),n&&jsxRuntime.jsx(ManufacturerQualificationsSection,{manufacturer:E,readonly:e,isLoading:f,onUnsavedChanges:A=>R("qualifications",{hasUnsavedChanges:A})})]}),n&&jsxRuntime.jsx(ManufacturerReportsSection,{manufacturerId:(E==null?void 0:E.ManufacturerId)??"",userEmail:l,isLoading:f})]}),jsxRuntime.jsx(C,{})]})}function ManufacturerCategories({categories:t,activeCategory:e,onSelectCategory:n}){return jsxRuntime.jsx("div",{className:"grid",children:jsxRuntime.jsx("div",{className:"flex overflow-x-auto small-scrollbar pb-4",children:jsxRuntime.jsx("div",{className:"flex gap-2",children:t.map(o=>jsxRuntime.jsxs(Button,{onClick:()=>n(o.CategoryCode??""),variant:e===o.CategoryCode?"default":"outline",size:"sm",className:"px-3 py-1.5 text-xs whitespace-nowrap rounded-full",children:[o.CategoryName??"Undefined",o.QualificationRequired&&jsxRuntime.jsx(ShieldCheck,{className:`ml-1 w-5 h-5 ${e!==o.CategoryCode?"text-red-500":""}`})]},o.CategoryCode))})})})}function ManufacturerProducts({applicationId:t,manufacturer:e,shopifyHostName:n}){var I,j,q,z;const[o]=usePostV4ResellerByRouteResellerIdManufacturerAndManufacturerIdCategoryCodeShopifyMutation(),[l,d]=React.useState(((j=(I=e.Categories)==null?void 0:I[0])==null?void 0:j.CategoryCode)||""),[f,g]=React.useState(!1),[b,_]=React.useState(!1),{toast:S}=useToast(),{data:R,isLoading:C,isFetching:E}=useGetV4ResellerByRouteResellerIdManufacturerAndManufacturerIdCategoryCodeQuery({routeResellerId:t,manufacturerId:e.ManufacturerId,categoryCode:l??""},{skip:!e.ManufacturerId||!l}),A=async()=>{try{g(!0),_(!1),await o({routeResellerId:t,manufacturerId:e.ManufacturerId??"",categoryCode:l,shopifyHostName:n}).unwrap()&&S({title:"Success",description:"Category synced to Shopify successfully",variant:"success"})}catch(Q){console.error("Error syncing to Shopify:",Q),S({title:"Error",description:"Error syncing category to Shopify.",variant:"destructive"})}finally{g(!1)}},M=()=>{var Q,F;return((F=(Q=e.Categories)==null?void 0:Q.find(V=>V.CategoryCode===l))==null?void 0:F.CategoryName)||l};return jsxRuntime.jsxs(jsxRuntime.Fragment,{children:[jsxRuntime.jsxs("div",{children:[jsxRuntime.jsx(ManufacturerCategories,{categories:e.Categories||[],activeCategory:l,onSelectCategory:d}),n&&((q=e.Categories)==null?void 0:q.findIndex(Q=>Q.AvailableToBuy))!==-1&&jsxRuntime.jsxs(Dialog,{open:b,onOpenChange:_,children:[jsxRuntime.jsx(DialogTrigger,{asChild:!0,children:jsxRuntime.jsx(Button,{className:"bg-green-600 hover:bg-green-700 mb-4",disabled:f,children:f?jsxRuntime.jsxs(jsxRuntime.Fragment,{children:[jsxRuntime.jsx(LoaderCircle,{className:"mr-2 h-4 w-4 animate-spin"}),"Syncing..."]}):jsxRuntime.jsxs(jsxRuntime.Fragment,{children:[jsxRuntime.jsx(ShoppingCart,{className:"mr-2 h-4 w-4"}),"Sync Category to Shopify"]})})}),jsxRuntime.jsxs(DialogContent,{children:[jsxRuntime.jsxs(DialogHeader,{children:[jsxRuntime.jsx(DialogTitle,{children:"Confirm Sync to Shopify"}),jsxRuntime.jsxs(DialogDescription,{children:['Are you sure you want to sync the category "',M(),'" to Shopify? This will add all products in this category to your Shopify store.']})]}),jsxRuntime.jsxs(DialogFooter,{children:[jsxRuntime.jsx(Button,{variant:"outline",onClick:()=>_(!1),children:"Cancel"}),jsxRuntime.jsx(Button,{className:"bg-green-600 hover:bg-green-700",onClick:A,disabled:f,children:f?jsxRuntime.jsxs(jsxRuntime.Fragment,{children:[jsxRuntime.jsx(LoaderCircle,{className:"mr-2 h-4 w-4 animate-spin"}),"Syncing..."]}):"Confirm Sync"})]})]})]})]}),jsxRuntime.jsx("div",{className:"grid grid-cols-1 @md:grid-cols-2 gap-4 mb-4",children:C||E?Array.from({length:4}).map((Q,F)=>jsxRuntime.jsx(ProductCard,{},F)):R!=null&&R.Products&&(R==null?void 0:R.Products.length)>0?(z=[...R.Products].sort((Q,F)=>{const V=Q.OverallPercentileRank??0;return(F.OverallPercentileRank??0)-V}))==null?void 0:z.map(Q=>jsxRuntime.jsx(ProductCard,{applicationId:t,product:Q,viewProductLink:`/${t}/Product/${Q.RandmarSKU}`,shopifyHostname:n},Q.RandmarSKU)):jsxRuntime.jsxs(Alert,{variant:"warning",className:"col-span-1 @md:col-span-2",children:[jsxRuntime.jsx(CircleAlert,{className:"h-4 w-4"}),jsxRuntime.jsx(AlertTitle,{children:"Warning"}),jsxRuntime.jsx(AlertDescription,{children:"No products found for this manufacturer category."})]})})]})}function PartnerRelationshipPage({applicationId:t,partnerId:e,userEmail:n,shopifyHostName:o,isSuperAdmin:l}){var j,q,z;const{data:d,isLoading:f,isFetching:g}=useGetV4PartnerByRouteApplicationIdPartnerAndPartnerIdQuery({routeApplicationId:t,partnerId:e,withSpecification:!0}),b=f||g,{toast:_}=useToast(),[S]=usePostV4ResellerByRouteResellerIdManufacturerAndManufacturerIdShopifyMutation(),[R,C]=React.useState(!1),[E,A]=React.useState(!1),M=async()=>{try{C(!0),A(!1),await S({routeResellerId:t??"",manufacturerId:e??"",shopifyHostName:o}).unwrap()&&_({title:"Success",description:"Manufacturer synced to Shopify successfully",variant:"success"})}catch(Q){console.error("Error syncing to Shopify:",Q),_({title:"Error",description:"Error syncing manufacturer to Shopify.",variant:"destructive"})}finally{C(!1)}},I=()=>d!=null&&d.Reseller?"reseller-overview":d!=null&&d.Manufacturer?"manufacturer-overview":"";return jsxRuntime.jsxs("div",{className:"@container",children:[jsxRuntime.jsxs("div",{className:"grid gap-4 @2xl:grid-cols-2",children:[jsxRuntime.jsx(PartnerCard,{account:d,loading:b,withAbout:!0,withVoice:!1,action:" "}),jsxRuntime.jsxs("div",{className:"grid gap-4",children:[((d==null?void 0:d.Manufacturer)||b)&&jsxRuntime.jsx(ManufacturerCard,{manufacturer:d==null?void 0:d.Manufacturer,loading:b,mainAction:jsxRuntime.jsxs(jsxRuntime.Fragment,{children:[(d==null?void 0:d.Manufacturer)&&jsxRuntime.jsx(ManufacturerGetStartedButton,{applicationId:t,manufacturer:d==null?void 0:d.Manufacturer}),o&&((q=(j=d==null?void 0:d.Manufacturer)==null?void 0:j.Categories)==null?void 0:q.findIndex(Q=>Q.AvailableToBuy))!==-1&&jsxRuntime.jsxs(Dialog,{open:E,onOpenChange:A,children:[jsxRuntime.jsx(DialogTrigger,{asChild:!0,children:jsxRuntime.jsx(Button,{className:"bg-green-600 hover:bg-green-700 ml-2",disabled:R,children:R?jsxRuntime.jsxs(jsxRuntime.Fragment,{children:[jsxRuntime.jsx(LoaderCircle,{className:"mr-2 h-4 w-4 animate-spin"}),"Syncing..."]}):jsxRuntime.jsxs(jsxRuntime.Fragment,{children:[jsxRuntime.jsx(ShoppingCart,{className:"mr-2 h-4 w-4"}),"Sync Manufacturer to Shopify"]})})}),jsxRuntime.jsxs(DialogContent,{children:[jsxRuntime.jsxs(DialogHeader,{children:[jsxRuntime.jsx(DialogTitle,{children:"Confirm Sync to Shopify"}),jsxRuntime.jsxs(DialogDescription,{children:['Are you sure you want to sync the manufacturer "',(z=d==null?void 0:d.Manufacturer)==null?void 0:z.PublicName,'" to Shopify? This will add all products from this manufacturer to your Shopify store.']})]}),jsxRuntime.jsxs(DialogFooter,{children:[jsxRuntime.jsx(Button,{variant:"outline",onClick:()=>A(!1),children:"Cancel"}),jsxRuntime.jsx(Button,{className:"bg-green-600 hover:bg-green-700",onClick:M,disabled:R,children:R?jsxRuntime.jsxs(jsxRuntime.Fragment,{children:[jsxRuntime.jsx(LoaderCircle,{className:"mr-2 h-4 w-4 animate-spin"}),"Syncing..."]}):"Confirm Sync"})]})]})]})]})}),(d==null?void 0:d.Reseller)&&jsxRuntime.jsx(ResellerCard,{reseller:d==null?void 0:d.Reseller,loading:b})]})]}),((d==null?void 0:d.Reseller)||(d==null?void 0:d.Manufacturer))&&!b&&jsxRuntime.jsx("div",{className:"max-w-6xl mx-auto p-4",children:jsxRuntime.jsxs(Tabs,{defaultValue:I(),className:"w-full",children:[jsxRuntime.jsxs(TabsList,{className:"inline-flex h-auto items-center justify-center rounded-none border-b bg-transparent p-0",children:[(d==null?void 0:d.Reseller)&&jsxRuntime.jsx(TabsTrigger,{value:"reseller-overview",className:"reseller-theme relative h-12 rounded-none border-b-2 border-b-transparent bg-transparent px-4 pb-3 pt-2 text-sm font-medium text-muted-foreground shadow-none transition-none hover:text-foreground data-[state=active]:border-b-primary data-[state=active]:text-foreground data-[state=active]:shadow-none cursor-pointer",children:"Reseller Overview"}),(d==null?void 0:d.Manufacturer)&&jsxRuntime.jsx(TabsTrigger,{value:"manufacturer-overview",className:"manufacturer-theme relative h-12 rounded-none border-b-2 border-b-transparent bg-transparent px-4 pb-3 pt-2 text-sm font-medium text-muted-foreground shadow-none transition-none hover:text-foreground data-[state=active]:border-b-primary data-[state=active]:text-foreground data-[state=active]:shadow-none cursor-pointer",children:"Manufacturer Overview"}),(d==null?void 0:d.Manufacturer)&&jsxRuntime.jsx(TabsTrigger,{value:"products",className:"relative h-12 rounded-none border-b-2 border-b-transparent bg-transparent px-4 pb-3 pt-2 text-sm font-medium text-muted-foreground shadow-none transition-none hover:text-foreground data-[state=active]:border-b-primary data-[state=active]:text-foreground data-[state=active]:shadow-none cursor-pointer",children:"Products"})]}),(d==null?void 0:d.Reseller)&&jsxRuntime.jsx(TabsContent,{value:"reseller-overview",children:jsxRuntime.jsx("div",{className:"mt-4",children:jsxRuntime.jsx(ResellerOverview,{readonly:!0,appID:d.ApplicationId||"",reseller:d==null?void 0:d.Reseller,userEmail:n,isSuperAdmin:l,withoutReports:!0})})}),(d==null?void 0:d.Manufacturer)&&jsxRuntime.jsx(TabsContent,{value:"manufacturer-overview",children:jsxRuntime.jsx("div",{className:"mt-4",children:jsxRuntime.jsx(ManufacturerOverviewPage,{readonly:!0,manufacturer:d==null?void 0:d.Manufacturer,applicationId:t,userEmail:n})})}),(d==null?void 0:d.Manufacturer)&&jsxRuntime.jsx(TabsContent,{value:"products",children:jsxRuntime.jsx("div",{className:"mt-4",children:jsxRuntime.jsx(ManufacturerProducts,{applicationId:t,manufacturer:d.Manufacturer,shopifyHostName:o})})})]})}),b&&jsxRuntime.jsx("div",{className:"max-w-6xl mx-auto p-4 mt-4 flex justify-center items-center h-32",children:jsxRuntime.jsx(LoaderCircle,{className:"h-8 w-8 animate-spin text-primary"})})]})}const PublicInfo=({reseller:t,appID:e,isLoading:n,readonly:o,onUnsavedChanges:l})=>{const{toast:d}=useToast(),[f]=usePostV4PartnerByApplicationIdAccountResellerAndFieldNameMutation(),[g,b]=React.useState({}),_=React.useMemo(()=>({publicEmail:t.PublicEmail??"",contactName:t.ContactName??"",phone:t.Phone??"",website:t.Website??""}),[t]),{register:S,handleSubmit:R,reset:C,watch:E,formState:{errors:A,isSubmitting:M}}=useForm({defaultValues:_}),I=E(),j=React.useCallback(()=>g?JSON.stringify(I)!==JSON.stringify(g):!1,[I,g]);React.useEffect(()=>{l&&l(j())},[j,l]),React.useEffect(()=>{t&&Object.keys(t).length>0&&(C(_),b(_))},[t,C,_]);const q=async Q=>{let F=!0,V=!1;const te=Object.keys(Q).map(ne=>({key:ne,keyApi:ne.charAt(0).toUpperCase()+ne.slice(1)}));for(const ne of te){const se=Q[ne.key],ge=t[ne.keyApi];if(se!==ge&&se!==void 0){V=!0;try{await f({applicationId:e,fieldName:ne.keyApi,newValue:String(se)}).unwrap()||(F=!1)}catch(oe){console.error(`Error updating ${ne.keyApi}:`,oe),F=!1}}}F&&V?(d({title:"Public info",description:"Information updated successfully",variant:"success"}),b({...Q}),l&&l(!1)):F||d({title:"Updation error",description:"Failed to update",variant:"destructive"})},z=Q=>!Q||Q.trim()==="";return n?jsxRuntime.jsxs(Card,{children:[jsxRuntime.jsx(CardHeader,{children:jsxRuntime.jsx(CardTitle,{children:"Public Information"})}),jsxRuntime.jsx(CardContent,{children:jsxRuntime.jsxs("div",{className:"space-y-4",children:[jsxRuntime.jsxs("div",{className:"grid grid-cols-1 @md:grid-cols-2 gap-4",children:[jsxRuntime.jsxs("div",{className:"space-y-2",children:[jsxRuntime.jsx(Skeleton,{className:"h-4 w-32"}),jsxRuntime.jsx(Skeleton,{className:"h-10 w-full"})]}),jsxRuntime.jsxs("div",{className:"space-y-2",children:[jsxRuntime.jsx(Skeleton,{className:"h-4 w-24"}),jsxRuntime.jsx(Skeleton,{className:"h-10 w-full"})]})]}),jsxRuntime.jsxs("div",{className:"space-y-2",children:[jsxRuntime.jsx(Skeleton,{className:"h-4 w-20"}),jsxRuntime.jsx(Skeleton,{className:"h-10 w-full"})]}),jsxRuntime.jsxs("div",{className:"space-y-2",children:[jsxRuntime.jsx(Skeleton,{className:"h-4 w-28"}),jsxRuntime.jsx(Skeleton,{className:"h-10 w-full"})]}),jsxRuntime.jsx("div",{className:"flex justify-end",children:jsxRuntime.jsx(Skeleton,{className:"h-10 w-20"})})]})})]}):jsxRuntime.jsxs(Card,{children:[jsxRuntime.jsx(CardHeader,{children:jsxRuntime.jsxs(CardTitle,{className:"text-1xl font-bold",children:["Public Information ",o?"(read only)":""]})}),jsxRuntime.jsxs(CardContent,{children:[(z(E("contactName"))||z(E("publicEmail"))||z(E("website"))||z(E("phone")))&&jsxRuntime.jsxs(Alert,{variant:"destructive",className:"mb-6",children:[jsxRuntime.jsx(CircleAlert,{className:"h-4 w-4"}),jsxRuntime.jsx(AlertTitle,{children:"Missing information"}),jsxRuntime.jsx(AlertDescription,{children:"All fields are required to get started at working with Manufacturers."})]}),jsxRuntime.jsxs("form",{onSubmit:R(q),className:"space-y-4",children:[jsxRuntime.jsxs("div",{className:"grid grid-cols-1 @md:grid-cols-2 gap-4",children:[jsxRuntime.jsxs("div",{className:"space-y-2",children:[jsxRuntime.jsx("label",{className:"text-sm font-medium leading-none",htmlFor:"contactName",children:"Main Representative *"}),jsxRuntime.jsx(Input,{id:"contactName",placeholder:"John Doe",readOnly:o,...S("contactName",{}),className:A.contactName||z(E("contactName"))?"input-error-indicator":""}),A.contactName&&jsxRuntime.jsx("p",{className:"text-red-500 text-sm",children:A.contactName.message})]}),jsxRuntime.jsxs("div",{className:"space-y-2",children:[jsxRuntime.jsx("label",{className:"text-sm font-medium leading-none",htmlFor:"publicEmail",children:"Public Email *"}),jsxRuntime.jsx(Input,{id:"publicEmail",placeholder:"contact@company.com",readOnly:o,...S("publicEmail",{pattern:{value:/^[A-Z0-9._%+-]+@[A-Z0-9.-]+\.[A-Z]{2,}$/i,message:"Invalid email address"}}),className:A.publicEmail||z(E("publicEmail"))?"input-error-indicator":""}),A.publicEmail&&jsxRuntime.jsx("p",{className:"text-red-500 text-sm",children:A.publicEmail.message})]})]}),jsxRuntime.jsxs("div",{className:"space-y-2",children:[jsxRuntime.jsx("label",{className:"text-sm font-medium leading-none",htmlFor:"website",children:"Website *"}),jsxRuntime.jsx(Input,{id:"website",placeholder:"https://company.com",readOnly:o,...S("website",{pattern:{value:/^.{7,}$/,message:"Must be at least 7 characters"}}),className:A.website||z(E("website"))?"input-error-indicator":""}),A.website&&jsxRuntime.jsx("p",{className:"text-red-500 text-sm",children:A.website.message})]}),jsxRuntime.jsxs("div",{className:"space-y-2",children:[jsxRuntime.jsx("label",{className:"text-sm font-medium leading-none",htmlFor:"phone",children:"Phone Number *"}),jsxRuntime.jsx(Input,{id:"phone",placeholder:"+1 (555) 123-4567",readOnly:o,...S("phone",{pattern:{value:/^.{7,}$/,message:"Must be at least 7 characters"}}),className:A.phone||z(E("phone"))?"input-error-indicator":""}),A.phone&&jsxRuntime.jsx("p",{className:"text-red-500 text-sm",children:A.phone.message})]}),jsxRuntime.jsx("div",{className:"flex justify-end",children:jsxRuntime.jsx(Button,{type:"submit",disabled:M||o,className:o?"hidden":"",children:M?"Saving...":"Save"})})]})]})]})};function BillingCard({appID:t,reseller:e,isLoading:n,withoutReports:o,userEmail:l}){const{toast:d}=useToast(),{Statement:f,CreditLimit:g}=e,[b,_]=React.useState(!1),[S,R]=React.useState(!1),[C,E]=React.useState(!1),[A,M]=React.useState(!1),[I,j]=React.useState(!1),[q,z]=React.useState(l||""),Q=[{label:"0 - 30 Days",value:jsxRuntime.jsx(FormattedNumber,{value:(f==null?void 0:f.Over0)||0,style:"currency",currency:"CAD",currencyDisplay:"symbol"}),icon:Calendar},{label:"31 - 45 Days",value:jsxRuntime.jsx(FormattedNumber,{value:(f==null?void 0:f.Over30)||0,style:"currency",currency:"CAD",currencyDisplay:"symbol"}),icon:CalendarDays},{label:"45+ Days",value:jsxRuntime.jsx(FormattedNumber,{value:(f==null?void 0:f.Over45)||0,style:"currency",currency:"CAD",currencyDisplay:"symbol"}),icon:CalendarRange},{label:"Total",value:jsxRuntime.jsx(FormattedNumber,{value:(f==null?void 0:f.Total)||0,style:"currency",currency:"CAD",currencyDisplay:"symbol"}),icon:DollarSign},{label:"Credit Limit",value:jsxRuntime.jsx(FormattedNumber,{value:g||0,style:"currency",currency:"CAD",currencyDisplay:"symbol"}),icon:CreditCard}],[F]=useLazyGetV4ResellerByRouteResellerIdDocumentAndDocumentNumberPdfQuery(),V=async ge=>{_(!1),ge?R(!0):E(!0);let oe="";try{const je=(await F({routeResellerId:t,documentNumber:`ST${t}`})).data;if(!je.url||!je.filename)throw new Error("No data received for download.");if(oe=je.url,ge)window.open(oe);else{const Ne=document.createElement("a");Ne.href=oe,Ne.download=je.filename,document.body.appendChild(Ne),Ne.click(),Ne.remove()}d({title:"Success",description:"Statement downloaded successfully.",variant:"success"})}catch(Ae){console.error("Download Error:",Ae),d({title:"Error",description:"An error occurred while downloading the statement. Please try again.",variant:"destructive"})}finally{ge?R(!1):E(!1),oe&&setTimeout(()=>{window.URL.revokeObjectURL(oe)},1e3)}},[te]=usePostV4ResellerByRouteResellerIdDocumentStatementEmailMutation(),ne=async()=>{if(!q||!/^[^\s@]+@[^\s@]+\.[^\s@]+$/.test(q)){d({title:"Invalid Email",description:"Please enter a valid email address.",variant:"destructive"});return}M(!0);try{await te({routeResellerId:t,emailAddress:q}).unwrap(),d({title:"Success",description:`Statement sent to ${q} successfully.`,variant:"success"}),j(!1)}catch(oe){console.error("Send Email Error:",oe),d({title:"Error",description:"An error occurred while sending the statement. Please try again.",variant:"destructive"})}finally{M(!1)}};if(n)return jsxRuntime.jsxs(Card,{className:"w-full",children:[jsxRuntime.jsx(CardHeader,{className:"border-b p-6 md:p-5",children:jsxRuntime.jsx(Skeleton,{className:"h-6 w-36"})}),jsxRuntime.jsxs(CardContent,{className:"p-6 md:p-5",children:[jsxRuntime.jsxs("div",{className:"grid sm:grid-cols-2 sm:divide-x divide-border",children:[jsxRuntime.jsx("div",{className:"space-y-6 sm:pe-4",children:[1,2,3].map(ge=>jsxRuntime.jsxs("div",{className:"flex items-center flex-wrap gap-1.5",children:[jsxRuntime.jsxs("div",{className:"flex items-center gap-2",children:[jsxRuntime.jsx(Skeleton,{className:"h-4 w-4"}),jsxRuntime.jsx(Skeleton,{className:"h-4 w-24"})]}),jsxRuntime.jsx(Skeleton,{className:"h-5 w-20 ms-auto"})]},ge))}),jsxRuntime.jsx("div",{className:"space-y-6 sm:ps-4 pt-6 sm:pt-0 mt-6 sm:mt-0 border-t sm:border-t-0 border-border",children:[1,2].map(ge=>jsxRuntime.jsx("div",{className:ge===2?"pt-6 mt-6 border-t border-border":"",children:jsxRuntime.jsxs("div",{className:"flex items-center flex-wrap gap-1.5",children:[jsxRuntime.jsxs("div",{className:"flex items-center gap-2",children:[jsxRuntime.jsx(Skeleton,{className:"h-4 w-4"}),jsxRuntime.jsx(Skeleton,{className:"h-4 w-24"})]}),jsxRuntime.jsx(Skeleton,{className:"h-5 w-20 ms-auto"})]})},ge))})]}),jsxRuntime.jsxs("div",{className:"flex justify-end mt-6 gap-2",children:[jsxRuntime.jsx(Skeleton,{className:"h-10 w-32"}),jsxRuntime.jsx(Skeleton,{className:"h-10 w-28"})]})]})]});const se=!o;return jsxRuntime.jsxs(jsxRuntime.Fragment,{children:[jsxRuntime.jsxs(Card,{className:"w-full",children:[jsxRuntime.jsx(CardHeader,{className:"border-b p-6 md:p-5",children:jsxRuntime.jsx(CardTitle,{className:"text-1xl font-bold",children:"Billing Overview"})}),jsxRuntime.jsxs(CardContent,{className:"p-6 md:p-5",children:[jsxRuntime.jsxs("div",{className:"grid sm:grid-cols-2 sm:divide-x divide-border",children:[jsxRuntime.jsx("div",{className:"space-y-6 sm:pe-4",children:Q.slice(0,3).map((ge,oe)=>jsxRuntime.jsx(BillingItem,{icon:ge.icon,label:ge.label,value:ge.value},oe))}),jsxRuntime.jsx("div",{className:"space-y-6 sm:ps-4 pt-6 sm:pt-0 mt-6 sm:mt-0 border-t sm:border-t-0 border-border",children:Q.slice(3).map((ge,oe)=>jsxRuntime.jsx("div",{className:oe===1?"pt-6 mt-6 border-t border-border":"",children:jsxRuntime.jsx(BillingItem,{icon:ge.icon,label:ge.label,value:ge.value})},oe))})]}),se&&jsxRuntime.jsxs("div",{className:"flex justify-end mt-6 gap-2",children:[jsxRuntime.jsxs(DropdownMenu,{open:b,onOpenChange:_,children:[jsxRuntime.jsx(DropdownMenuTrigger,{asChild:!0,children:jsxRuntime.jsx(Button,{variant:"outline",disabled:S||C,children:S?jsxRuntime.jsxs(jsxRuntime.Fragment,{children:[jsxRuntime.jsx(LoaderCircle,{className:"mr-2 h-4 w-4 animate-spin"}),"Printing..."]}):C?jsxRuntime.jsxs(jsxRuntime.Fragment,{children:[jsxRuntime.jsx(LoaderCircle,{className:"mr-2 h-4 w-4 animate-spin"}),"Downloading..."]}):jsxRuntime.jsxs(jsxRuntime.Fragment,{children:[jsxRuntime.jsx(FileText,{className:"mr-2 h-4 w-4"}),"Statement",jsxRuntime.jsx(ChevronDown,{className:"ml-2 h-4 w-4"})]})})}),jsxRuntime.jsxs(DropdownMenuContent,{align:"end",children:[jsxRuntime.jsxs(DropdownMenuItem,{onClick:()=>V(!0),disabled:S,children:[jsxRuntime.jsx(Printer,{className:"mr-2 h-4 w-4"}),jsxRuntime.jsx("span",{children:"Print"})]}),jsxRuntime.jsx(DropdownMenuSeparator,{}),jsxRuntime.jsxs(DropdownMenuItem,{onClick:()=>V(!1),disabled:C,children:[jsxRuntime.jsx(Download,{className:"mr-2 h-4 w-4"}),jsxRuntime.jsx("span",{children:"Download"})]}),jsxRuntime.jsx(DropdownMenuSeparator,{}),jsxRuntime.jsxs(DropdownMenuItem,{onSelect:()=>j(!0),children:[jsxRuntime.jsx(Mail,{className:"mr-2 h-4 w-4"}),jsxRuntime.jsx("span",{children:"Send by Email"})]})]})]}),jsxRuntime.jsx(reactRouterDom.Link,{to:`${window.location.hostname==="dashboard.randmar.io"?"":"https://dashboard.randmar.io"}/${t}/PayInvoice`,target:window.location.hostname==="dashboard.randmar.io"?"_self":"_blank",children:jsxRuntime.jsxs(Button,{children:[jsxRuntime.jsx(CreditCard,{className:"mr-2 h-4 w-4"}),"Pay Invoices"]})})]})]})]}),jsxRuntime.jsx(Dialog,{open:I,children:jsxRuntime.jsxs(DialogContent,{className:"sm:max-w-[425px]",children:[jsxRuntime.jsxs(DialogHeader,{children:[jsxRuntime.jsx(DialogTitle,{children:"Send Statement by Email"}),jsxRuntime.jsx(DialogDescription,{children:"Enter the recipient's email address below. The statement will be sent as a PDF attachment."})]}),jsxRuntime.jsx("div",{className:"grid gap-4 py-4",children:jsxRuntime.jsxs("div",{className:"grid grid-cols-4 items-center gap-4",children:[jsxRuntime.jsx(Label$2,{htmlFor:"email",className:"text-right",children:"Email"}),jsxRuntime.jsx(Input,{id:"email",type:"email",value:q,onChange:ge=>z(ge.target.value),className:"col-span-3",placeholder:"recipient@example.com"})]})}),jsxRuntime.jsx(DialogFooter,{children:jsxRuntime.jsx(Button,{type:"submit",onClick:ne,disabled:A||!q,children:A?jsxRuntime.jsxs(jsxRuntime.Fragment,{children:[jsxRuntime.jsx(LoaderCircle,{className:"mr-2 h-4 w-4 animate-spin"}),"Sending..."]}):jsxRuntime.jsxs(jsxRuntime.Fragment,{children:[jsxRuntime.jsx(Send,{className:"mr-2 h-4 w-4"}),"Send"]})})})]})})]})}function BillingItem({icon:t,label:e,value:n}){return jsxRuntime.jsxs("div",{className:"flex items-center flex-wrap gap-1.5",children:[jsxRuntime.jsxs("div",{className:"flex items-center gap-2",children:[jsxRuntime.jsx(t,{className:"size-4 text-muted-foreground"}),jsxRuntime.jsx("span",{className:"text-sm font-medium text-muted-foreground",children:e})]}),jsxRuntime.jsx("span",{className:"text-base font-semibold ms-auto",children:n})]})}function ChangePricingTierModal({open:t,setOpen:e,tier:n,onTierChange:o,isLoading:l}){const d=()=>{e(!1)};return jsxRuntime.jsx(Dialog,{open:t,onOpenChange:e,children:jsxRuntime.jsxs(DialogContent,{className:"sm:max-w-[425px]",children:[jsxRuntime.jsx(DialogHeader,{children:jsxRuntime.jsx(DialogTitle,{children:"Change Pricing Tier"})}),jsxRuntime.jsxs("div",{className:"grid gap-1.5 py-2",children:[jsxRuntime.jsxs("p",{className:"text-lg text-muted-foreground",children:["Requested Pricing Tier: ",jsxRuntime.jsx("span",{className:"font-bold",children:n})]}),jsxRuntime.jsx("p",{className:"text-sm text-muted-foreground",children:"If your account qualifies, your pricing will update immediately."}),jsxRuntime.jsx("p",{className:"text-sm text-muted-foreground",children:"If not, we'll review your request and notify you of the decision."})]}),jsxRuntime.jsxs(DialogFooter,{children:[jsxRuntime.jsx(Button,{variant:"outline",onClick:d,disabled:l,children:"Cancel"}),jsxRuntime.jsx(Button,{onClick:o,disabled:l,children:l?"Loading...":`Apply for ${n}`})]})]})})}const getPricingText=t=>t===1?"The Best":t===2?"Fixed 12.5% GP on all items":t===3?"Advantageous":t===4?"Buying Group":t===5?"Cost":t,getShippingText=t=>t==="A"?"Free or Custom":t==="B"?"Fixed $10 anywhere":t==="C"?`Free shipping on $150+ orders to your location,
|
|
1083
1083
|
$15 for drop shipped orders under $1,500,
|
|
1084
|
-
$10 with opportunities under $1,000`:t==="D"?"$15 under $1,500":t==="E"?"Full shipping charges":t,getTermsText=t=>t==="STRIPE"?"Credit card payment":t==="NET30"?"Net 30 days":t,AccountTier=({isSuperAdmin:t,readonly:e,reseller:n,appID:o,isLoading:l})=>{const{toast:d}=useToast(),[f,g]=React.useState(!1),[b,_]=React.useState(""),[S,{isLoading:R}]=usePostV4PartnerByApplicationIdAccountResellerAndFieldNameMutation(),C=Oe=>Oe&&{Starter:"starter","E-Commerce":"ecommerce",Commercial:"commercial",Basics:"cws",Novexco:"novexco","Jean Coutu":"jeancoutu",Exclusive:"exclusive"}[Oe]||"",E=Oe=>Oe&&{A:"free",B:"fixed",C:"dropshipped",D:"under1500",E:"fullcharges"}[Oe]||"",A=Oe=>Oe&&{1:"exclusive",2:"ecommerce",3:"commercial",4:"buyinggroup",5:"cost"}[Oe]||"",[M,I]=React.useState(C((n==null?void 0:n.Priority)??"")),[j,q]=React.useState(E((n==null?void 0:n.ShippingProfile)??"")),[z,Q]=React.useState(A(n==null?void 0:n.PriceProfile)),F=Oe=>({starter:"Starter",ecommerce:"E-Commerce",commercial:"Commercial",cws:"Basics",novexco:"Novexco",jeancoutu:"Jean Coutu",exclusive:"Exclusive"})[Oe]||Oe,V=Oe=>({free:"A",fixed:"B",dropshipped:"C",under1500:"D",fullcharges:"E"})[Oe]||Oe,te=Oe=>({exclusive:"1",ecommerce:"2",commercial:"3",buyinggroup:"4",cost:"5"})[Oe]||Oe;React.useEffect(()=>{I(C((n==null?void 0:n.Priority)??"")),q(E((n==null?void 0:n.ShippingProfile)??"")),Q(A(n==null?void 0:n.PriceProfile))},[n]);const ne=async(Oe,Fe,ze,$e)=>{try{(await S({applicationId:o,fieldName:Oe,newValue:Fe})).error?d({title:"Error",description:$e,variant:"destructive"}):d({title:"Success",description:ze,variant:"success"})}catch{d({title:"Error",description:"An unexpected error occurred",variant:"destructive"})}},se=async Oe=>{I(Oe);const Fe=F(Oe);ne("Priority",Fe,`Priority updated to ${Fe}`,"Failed to update priority")},ge=async Oe=>{q(Oe);const Fe=V(Oe);ne("ShippingProfile",Fe,`Shipping profile updated to ${Fe}`,"Failed to update shipping profile")},oe=async Oe=>{Q(Oe);const Fe=te(Oe);ne("PriceProfile",Fe,`Pricing profile updated to ${Fe}`,"Failed to update pricing profile")},Ae=async()=>{try{const Oe=await S({applicationId:o,fieldName:"Tier",newValue:b});Oe.error?d({title:"Error",description:"Failed to update reseller",variant:"destructive"}):Oe.data?d({title:"Success",description:`Pricing Tier changed to ${b}`,variant:"success"}):d({title:"Considered",description:"Request being considered",variant:"success"})}catch{d({title:"Error",description:"An unexpected error occurred",variant:"destructive"})}finally{g(!1),_("")}},je=[{name:"Terms",enabled:n.Priority==="Starter"},{name:"E-Commerce",enabled:n.Priority==="Commercial"},{name:"Commercial",enabled:n.Priority==="E-Commerce"},{name:"Exclusive",enabled:t}],Ne=Oe=>{_(Oe),g(!0)};return l?jsxRuntime.jsxs(Card,{className:"w-full",children:[jsxRuntime.jsx(CardHeader,{className:"pb-2",children:jsxRuntime.jsxs("div",{className:"flex items-center justify-between",children:[jsxRuntime.jsx(Skeleton,{className:"h-6 w-28"}),jsxRuntime.jsx(Skeleton,{className:"h-6 w-16 rounded-full"})]})}),jsxRuntime.jsxs(CardContent,{children:[jsxRuntime.jsxs("div",{className:"mb-3",children:[jsxRuntime.jsx(Skeleton,{className:"h-8 w-40 mb-1"}),jsxRuntime.jsx(Skeleton,{className:"h-4 w-56"})]}),jsxRuntime.jsx("div",{className:"grid gap-3",children:[1,2,3].map(Oe=>jsxRuntime.jsxs("div",{className:"flex items-center gap-3",children:[jsxRuntime.jsx(Skeleton,{className:"h-8 w-8 rounded-full shrink-0"}),jsxRuntime.jsxs("div",{className:"flex-1",children:[jsxRuntime.jsx(Skeleton,{className:"h-5 w-20 mb-1"}),jsxRuntime.jsx(Skeleton,{className:"h-4 w-full"})]})]},Oe))}),jsxRuntime.jsxs("div",{className:"flex gap-2 mt-3",children:[jsxRuntime.jsx(Skeleton,{className:"h-10 w-full"}),jsxRuntime.jsx(Skeleton,{className:"h-10 w-full"})]})]})]}):jsxRuntime.jsxs(jsxRuntime.Fragment,{children:[jsxRuntime.jsxs(Card,{className:"w-full",children:[jsxRuntime.jsxs(CardHeader,{className:"pb-2 pt-4 px-4 flex flex-row items-center justify-between",children:[jsxRuntime.jsx(CardTitle,{className:"text-1xl font-bold",children:"Account Tier"}),jsxRuntime.jsx(Badge,{variant:"secondary",className:"bg-green-100 text-green-700 hover:bg-green-200 text-xs",children:"Active"})]}),jsxRuntime.jsxs(CardContent,{className:"pt-2 px-4 pb-4",children:[jsxRuntime.jsxs("div",{className:"flex items-center justify-between mb-3 bg-primary/5 p-4 rounded-lg",children:[jsxRuntime.jsxs("div",{children:[jsxRuntime.jsxs("h3",{className:"text-lg font-bold text-primary",children:[(n==null?void 0:n.Priority)||""," Tier"]}),jsxRuntime.jsx("p",{className:"text-xs text-muted-foreground",children:"Optimized for online retail"})]}),jsxRuntime.jsx(CircleCheck,{className:"h-6 w-6 text-green-600"})]}),jsxRuntime.jsxs("div",{className:"grid grid-cols-1 gap-2 mb-3",children:[jsxRuntime.jsxs("div",{className:"flex items-center gap-2 p-2 rounded-lg border bg-card hover:bg-accent/5 transition-colors",children:[jsxRuntime.jsx("div",{className:"bg-primary/10 p-1.5 rounded-full shrink-0",children:jsxRuntime.jsx(Package2,{className:"h-4 w-4 text-primary"})}),jsxRuntime.jsxs("div",{className:"min-w-0",children:[jsxRuntime.jsx("p",{className:"font-medium text-sm",children:"Pricing"}),jsxRuntime.jsx("p",{className:"text-xs text-muted-foreground truncate",children:getPricingText(n.PriceProfile||0)})]})]}),jsxRuntime.jsxs("div",{className:"flex items-center gap-2 p-2 rounded-lg border bg-card hover:bg-accent/5 transition-colors",children:[jsxRuntime.jsx("div",{className:"bg-primary/10 p-1.5 rounded-full shrink-0",children:jsxRuntime.jsx(Truck,{className:"h-4 w-4 text-primary"})}),jsxRuntime.jsxs("div",{className:"min-w-0",children:[jsxRuntime.jsx("p",{className:"font-medium text-sm",children:"Shipping"}),jsxRuntime.jsx("p",{className:"text-xs text-muted-foreground",children:getShippingText(n.ShippingProfile||"").split(".")[0]})]})]}),jsxRuntime.jsxs("div",{className:"flex items-center gap-2 p-2 rounded-lg border bg-card hover:bg-accent/5 transition-colors",children:[jsxRuntime.jsx("div",{className:"bg-primary/10 p-1.5 rounded-full shrink-0",children:jsxRuntime.jsx(Calendar,{className:"h-4 w-4 text-primary"})}),jsxRuntime.jsxs("div",{className:"min-w-0",children:[jsxRuntime.jsx("p",{className:"font-medium text-sm",children:"Payment terms"}),jsxRuntime.jsx("p",{className:"text-xs text-muted-foreground",children:getTermsText((n==null?void 0:n.Terms)||"")})]})]})]}),jsxRuntime.jsxs("div",{className:"flex gap-2",children:[!e&&jsxRuntime.jsx(Button,{variant:"outline",className:"flex-1",asChild:!0,children:jsxRuntime.jsxs(reactRouterDom.Link,{to:"https://www.randmar.io/docs/overview/pricingTiers",target:"_blank",children:[jsxRuntime.jsx(ExternalLink,{className:"h-4 w-4 mr-1"}),"Pricing Tiers"]})}),jsxRuntime.jsxs(Popover,{children:[jsxRuntime.jsx(PopoverTrigger,{asChild:!0,children:jsxRuntime.jsxs(Button,{disabled:e,className:e?"hidden":"flex-1",children:["Upgrade Tier ",jsxRuntime.jsx(ChevronRight,{className:"h-3 w-3 ml-1"})]})}),jsxRuntime.jsx(PopoverContent,{className:"w-56 p-2",children:jsxRuntime.jsxs("div",{className:"grid gap-1",children:[jsxRuntime.jsx("h4",{className:"font-medium text-xs mb-1",children:"Select a tier"}),je.map(Oe=>jsxRuntime.jsx(Button,{variant:"ghost",size:"sm",className:"w-full justify-start h-8",disabled:!Oe.enabled,onClick:()=>Ne(Oe.name),children:Oe.name},Oe.name))]})})]})]})]})]}),jsxRuntime.jsx(ChangePricingTierModal,{isLoading:R,open:f,setOpen:g,tier:b,onTierChange:Ae}),t&&!e&&jsxRuntime.jsxs(Card,{className:"mt-4",children:[jsxRuntime.jsx(CardHeader,{className:"pb-2 pt-3 px-4",children:jsxRuntime.jsx(CardTitle,{className:"text-1xl font-bold",children:"Admin Configuration"})}),jsxRuntime.jsx(CardContent,{className:"pt-2 px-4 pb-4",children:jsxRuntime.jsxs("div",{className:"space-y-3",children:[jsxRuntime.jsxs("div",{className:"bg-muted/30 p-2 rounded-lg",children:[jsxRuntime.jsx(Label$2,{className:"block mb-1 text-xs font-medium",children:"Priority"}),jsxRuntime.jsx(RadioGroup$1,{value:M,onValueChange:se,className:"grid grid-cols-2 @sm:grid-cols-3 @md:grid-cols-4 gap-1",children:[{value:"starter",label:"Starter"},{value:"ecommerce",label:"E-Commerce"},{value:"commercial",label:"Commercial"},{value:"cws",label:"CWS (Basics)"},{value:"novexco",label:"Novexco"},{value:"jeancoutu",label:"Jean Coutu"},{value:"exclusive",label:"Exclusive"}].map(Oe=>jsxRuntime.jsxs("div",{className:"flex items-center space-x-1",children:[jsxRuntime.jsx(RadioGroupItem,{value:Oe.value,id:`priority-${Oe.value}`,className:"h-6 w-6 scale-50"}),jsxRuntime.jsx(Label$2,{htmlFor:`priority-${Oe.value}`,className:"cursor-pointer text-xs",children:Oe.label})]},Oe.value))})]}),jsxRuntime.jsxs("div",{className:"bg-muted/30 p-2 rounded-lg",children:[jsxRuntime.jsx(Label$2,{className:"block mb-1 text-xs font-medium",children:"Shipping Profile"}),jsxRuntime.jsx(RadioGroup$1,{value:j,onValueChange:ge,className:"grid grid-cols-1 @md:grid-cols-2 gap-1",children:[{value:"free",label:"Free (A)"},{value:"fixed",label:"Fixed $10 Shipping (B)"},{value:"dropshipped",label:"$15 for drop shipped (C)"},{value:"under1500",label:"15$ under 1,500 (D)"},{value:"fullcharges",label:"Full shipping charges (E)"}].map(Oe=>jsxRuntime.jsxs("div",{className:"flex items-center space-x-1",children:[jsxRuntime.jsx(RadioGroupItem,{value:Oe.value,id:`shipping-${Oe.value}`,className:"h-6 w-6 scale-50"}),jsxRuntime.jsx(Label$2,{htmlFor:`shipping-${Oe.value}`,className:"cursor-pointer text-xs",children:Oe.label})]},Oe.value))})]}),jsxRuntime.jsxs("div",{className:"bg-muted/30 p-2 rounded-lg",children:[jsxRuntime.jsx(Label$2,{className:"block mb-1 text-xs font-medium",children:"Pricing Profile"}),jsxRuntime.jsx(RadioGroup$1,{value:z,onValueChange:oe,className:"grid grid-cols-2 @sm:grid-cols-3 gap-1",children:[{value:"exclusive",label:"Exclusive (1)"},{value:"ecommerce",label:"E-Commerce (2)"},{value:"commercial",label:"Commercial (3)"},{value:"buyinggroup",label:"Buying Group (4)"},{value:"cost",label:"Cost (5)"}].map(Oe=>jsxRuntime.jsxs("div",{className:"flex items-center space-x-1",children:[jsxRuntime.jsx(RadioGroupItem,{value:Oe.value,id:`pricing-${Oe.value}`,className:"h-6 w-6 scale-50 antialiased"}),jsxRuntime.jsx(Label$2,{htmlFor:`pricing-${Oe.value}`,className:"cursor-pointer text-xs",children:Oe.label})]},Oe.value))})]})]})})]})]})};function OrderCategories({openOrders:t=[],isLoading:e=!1}){const n=(t==null?void 0:t.filter(M=>M.DocumentType==="Order"))||[],o=(t==null?void 0:t.filter(M=>M.DocumentType==="Shipment"))||[],l=n.filter(M=>M.WarehouseCode!=="3PLE"),d=l.reduce((M,I)=>M+(I.Quantity??0),0),f=l.reduce((M,I)=>M+(I.ExtendedPrice??0),0),g=n.filter(M=>M.WarehouseCode==="3PLE"),b=g.reduce((M,I)=>M+(I.Quantity??0),0),_=g.reduce((M,I)=>M+(I.ExtendedPrice??0),0),S=o.reduce((M,I)=>M+(I.Quantity??0),0),R=o.reduce((M,I)=>M+(I.ExtendedPrice??0),0),C=d+b+S,E=f+_+R,A=[{name:"All",icon:Package,color:"bg-blue-500",orders:C,amount:E},{name:"Processing",icon:RefreshCcw,color:"bg-yellow-500",orders:d,amount:f},{name:"Shipped",icon:Truck,color:"bg-green-500",orders:S,amount:R},{name:"Delayed",icon:CircleAlert,color:"bg-red-500",orders:b,amount:_}];return e?jsxRuntime.jsxs(Card,{className:"w-full @md:col-span-2 @xl:col-span-1",children:[jsxRuntime.jsx(CardHeader,{children:jsxRuntime.jsx(Skeleton,{className:"h-7 w-40"})}),jsxRuntime.jsx(CardContent,{children:jsxRuntime.jsx("div",{className:"grid grid-cols-1 @sm:grid-cols-2 gap-3.5",children:[1,2,3,4].map(M=>jsxRuntime.jsx(Card,{className:"overflow-hidden rounded-md rounded-b-lg border-0 shadow-md",children:jsxRuntime.jsxs(CardContent,{className:"p-0",children:[jsxRuntime.jsx("div",{className:"bg-gray-200 h-[3px]"}),jsxRuntime.jsxs("div",{className:"p-6 border border-t-0",children:[jsxRuntime.jsxs("div",{className:"flex justify-between items-center mb-4",children:[jsxRuntime.jsx(Skeleton,{className:"h-5 w-24"}),jsxRuntime.jsx(Skeleton,{className:"h-8 w-8 rounded-full"})]}),jsxRuntime.jsxs("div",{className:"flex justify-between items-start",children:[jsxRuntime.jsxs("div",{children:[jsxRuntime.jsx(Skeleton,{className:"h-3 w-20 mb-1"}),jsxRuntime.jsx(Skeleton,{className:"h-6 w-12"})]}),jsxRuntime.jsxs("div",{className:"text-end",children:[jsxRuntime.jsx(Skeleton,{className:"h-3 w-20 mb-1"}),jsxRuntime.jsx(Skeleton,{className:"h-5 w-20"})]})]})]})]})},M))})})]}):jsxRuntime.jsxs(Card,{className:"w-full @md:col-span-2 @xl:col-span-1",children:[jsxRuntime.jsx(CardHeader,{children:jsxRuntime.jsx(CardTitle,{className:"text-1xl font-bold",children:"Order Categories"})}),jsxRuntime.jsx(CardContent,{children:jsxRuntime.jsx("div",{className:"grid grid-cols-1 @sm:grid-cols-2 gap-3.5",children:A.map(M=>jsxRuntime.jsx(Card,{className:"overflow-hidden rounded-md rounded-b-lg border-0 shadow-md",children:jsxRuntime.jsxs(CardContent,{className:"p-0",children:[jsxRuntime.jsx("div",{className:`${M.color} bg-opacity-60 h-[3px]`}),jsxRuntime.jsxs("div",{className:"p-6 border border-t-0",children:[jsxRuntime.jsxs("div",{className:"flex justify-between items-center mb-4",children:[jsxRuntime.jsx("h3",{className:"font-semibold text-base",children:M.name}),jsxRuntime.jsx("div",{className:`${M.color} bg-opacity-90 p-2 rounded-full`,children:jsxRuntime.jsx(M.icon,{className:"size-4 shrink-0 text-white"})})]}),jsxRuntime.jsxs("div",{className:"flex justify-between items-start",children:[jsxRuntime.jsxs("div",{children:[jsxRuntime.jsx("p",{className:"text-xs text-muted-foreground",children:"Total Orders"}),jsxRuntime.jsx("p",{className:"text-xl font-bold",children:M.orders})]}),jsxRuntime.jsxs("div",{className:"text-end",children:[jsxRuntime.jsx("p",{className:"text-xs text-muted-foreground",children:"Total Amount"}),jsxRuntime.jsx("p",{className:"text-base font-semibold",children:jsxRuntime.jsx(FormattedNumber,{value:M.amount,style:"currency",currency:"CAD",currencyDisplay:"symbol"})})]})]})]})]})},M.name))})})]})}function ReportsSection({isLoading:t,userEmail:e,appID:n}){const{toast:o}=useToast(),[l,{isLoading:d}]=usePostV4ResellerByRouteResellerIdReportWalmartTrackingFileEmailMutation(),[f,{isLoading:g}]=usePostV4ResellerByRouteResellerIdReportAmazonTrackingFileEmailMutation(),[b,{isLoading:_}]=usePostV4ResellerByRouteResellerIdReportOpenOrdersEmailMutation(),[S,{isLoading:R}]=usePostV4ResellerByRouteResellerIdReportProductsEmailMutation(),[C,{isLoading:E}]=usePostV4ResellerByRouteResellerIdReportInvoicesEmailMutation(),[A,{isLoading:M}]=usePostV4ResellerByRouteResellerIdDocumentStatementEmailMutation(),[I,j]=React.useState(null),[q,z]=React.useState(e),[Q,F]=React.useState(!1),V=[{name:"Products",reports:[{id:"Products",title:"Universal Product List",description:"A comprehensive overview of your product list with detailed specifications and pricing information.",icon:Package}]},{name:"Operation Details",reports:[{id:"OpenOrders",title:"Order Details",description:"A detailed report of all your orders and shipments, including status, tracking information, and delivery estimates.",icon:ShoppingCart},{id:"Invoices",title:"Invoices and Credits Report",description:"Detailed overview of your invoices and credits within a specific date range. It also contains reports about additional charges, serial numbers, and other relevant information.",icon:ScrollText},{id:"Statement",title:"Statement and RMAs Report",description:"A detailed report of all unpaid invoices and active RMAs.",icon:Banknote}]},{name:"Tracking Files",reports:[{id:"AmazonTrackingFile",title:"Amazon Tracking File",description:"Track products sold on Amazon marketplace with detailed sales and inventory information.",icon:ChartNoAxesColumnIncreasing},{id:"WalmartTrackingFile",title:"Walmart Tracking File",description:"Track products sold on Walmart marketplace with detailed sales and inventory information.",icon:ChartNoAxesColumnIncreasing}]}],te=async ge=>{j(ge),F(!0)},ne=async()=>{if(!(!I||!n))try{switch(I.id){case"Products":await S({routeResellerId:n,emailAddress:q}).unwrap();break;case"AmazonTrackingFile":await f({routeResellerId:n,emailAddress:q}).unwrap();break;case"WalmartTrackingFile":await l({routeResellerId:n,emailAddress:q}).unwrap();break;case"OpenOrders":await b({routeResellerId:n,emailAddress:q}).unwrap();break;case"Invoices":await C({routeResellerId:n,emailAddress:q}).unwrap();break;case"Statement":await A({routeResellerId:n,emailAddress:q}).unwrap();break;default:throw new Error("invalid report id")}o({title:"Report requested",description:`The ${I.title} will be sent to ${q} shortly.`,variant:"success"}),F(!1)}catch(ge){console.error("Error requesting report:",ge),o({title:"Error",description:"Failed to request report. Please try again.",variant:"destructive"})}},se=_||R||g||d||M||E;return jsxRuntime.jsxs(Card,{children:[jsxRuntime.jsxs(CardHeader,{children:[jsxRuntime.jsx(CardTitle,{className:"text-1xl font-bold",children:"Reports"}),jsxRuntime.jsx("p",{className:"text-sm text-muted-foreground",children:"Download essential business reports, from your Product List to your Order Details."})]}),jsxRuntime.jsx(CardContent,{className:"space-y-6",children:t?jsxRuntime.jsx(jsxRuntime.Fragment,{children:[1,2,3].map(ge=>jsxRuntime.jsxs("div",{className:"space-y-4",children:[jsxRuntime.jsx(Skeleton,{className:"h-6 w-48"}),[1,2].map(oe=>jsxRuntime.jsxs("div",{className:"flex items-start gap-4 p-4 border rounded-lg",children:[jsxRuntime.jsx(Skeleton,{className:"h-9 w-9 rounded-full"}),jsxRuntime.jsxs("div",{className:"flex-1",children:[jsxRuntime.jsx(Skeleton,{className:"h-5 w-40 mb-2"}),jsxRuntime.jsx(Skeleton,{className:"h-4 w-full"})]}),jsxRuntime.jsx(Skeleton,{className:"h-9 w-24"})]},oe))]},ge))}):jsxRuntime.jsx(jsxRuntime.Fragment,{children:V.map(ge=>jsxRuntime.jsxs("div",{className:"space-y-4",children:[jsxRuntime.jsx("h3",{className:"text-sm font-semibold",children:ge.name}),ge.reports.map(oe=>jsxRuntime.jsxs("div",{className:"flex items-start gap-4 p-4 border rounded-lg hover:bg-gray-100 transition-colors",children:[jsxRuntime.jsx("div",{className:"bg-primary/10 p-2 rounded-full",children:jsxRuntime.jsx(oe.icon,{className:"h-5 w-5 text-primary"})}),jsxRuntime.jsxs("div",{className:"flex-1",children:[jsxRuntime.jsx("h4",{className:"font-semibold text-sm",children:oe.title}),jsxRuntime.jsx("p",{className:"text-sm text-muted-foreground mt-1",children:oe.description})]}),jsxRuntime.jsxs(Button,{variant:"outline",size:"sm",className:"flex items-center gap-1",onClick:()=>te(oe),children:[jsxRuntime.jsx(Download,{className:"h-4 w-4"}),"Request"]})]},oe.id))]},ge.name))})}),jsxRuntime.jsx(Dialog,{open:Q,onOpenChange:F,children:jsxRuntime.jsxs(DialogContent,{children:[jsxRuntime.jsxs(DialogHeader,{children:[jsxRuntime.jsxs(DialogTitle,{children:["Request ",I==null?void 0:I.title]}),jsxRuntime.jsx(DialogDescription,{children:"Enter the email address where you would like to receive the report."})]}),jsxRuntime.jsxs("div",{className:"py-4",children:[jsxRuntime.jsx(Label$2,{htmlFor:"email",children:"Email"}),jsxRuntime.jsx(Input,{id:"email",value:q,onChange:ge=>z(ge.target.value),placeholder:"your@email.com",className:"mt-2"})]}),jsxRuntime.jsx(DialogDescription,{children:"The report will take around 5 minutes to generate."}),jsxRuntime.jsxs(DialogFooter,{children:[jsxRuntime.jsx(Button,{variant:"outline",onClick:()=>F(!1),children:"Cancel"}),jsxRuntime.jsx(Button,{onClick:ne,disabled:!q||se,children:se?jsxRuntime.jsxs(jsxRuntime.Fragment,{children:[jsxRuntime.jsx(LoaderCircle,{className:"mr-2 h-4 w-4 animate-spin"}),"Sending..."]}):"Send Report"})]})]})})]})}const badgeVariants=cva("inline-flex items-center rounded-full px-2.5 py-0.5 text-xs font-semibold transition-colors focus:outline-hidden focus:ring-2 focus:ring-ring focus:ring-offset-2",{variants:{variant:{default:"bg-primary text-primary-foreground hover:bg-primary/80",secondary:"bg-secondary text-secondary-foreground hover:bg-secondary/80",destructive:"bg-destructive text-destructive-foreground hover:bg-destructive/80",outline:"text-foreground border border-input hover:bg-accent hover:text-accent-foreground",success:"bg-green-600 text-white hover:bg-green-700",warning:"bg-yellow-500 text-white hover:bg-yellow-600",info:"bg-blue-500 text-white hover:bg-blue-600",ghost:"bg-background hover:bg-accent hover:text-accent-foreground",randmarRed:"bg-randmar-red text-white hover:bg-randmar-red/80",randmarBlue:"bg-randmar-blue text-white hover:bg-randmar-blue/80",randmarPurple:"bg-randmar-purple text-white hover:bg-randmar-purple/80",randmarGreen:"bg-randmar-green text-black hover:bg-randmar-green/80",randmarBlack:"bg-randmar-black text-white hover:bg-randmar-black/80",randmarYellow:"bg-randmar-yellow text-black hover:bg-randmar-yellow/80"},size:{default:"h-6",sm:"h-5 text-[10px]",lg:"h-7 px-3"}},defaultVariants:{variant:"default",size:"default"}}),Badge=React__namespace.forwardRef(({className:t,variant:e,size:n,icon:o,children:l,...d},f)=>jsxRuntime.jsxs("div",{ref:f,className:cn(badgeVariants({variant:e,size:n}),t),...d,children:[o&&jsxRuntime.jsx("span",{className:"mr-1",children:o}),l]}));Badge.displayName="Badge";function QualificationBadge({qualification:t}){return!t.QualificationId||t.QualificationId==="Suspended"?null:t.QualificationId==="Do Not Sell"?jsxRuntime.jsx(TooltipProvider,{children:jsxRuntime.jsxs(Tooltip$1,{children:[jsxRuntime.jsx(TooltipTrigger,{asChild:!0,children:jsxRuntime.jsxs(Badge,{variant:"destructive",children:[jsxRuntime.jsx(X$1,{className:"h-3 w-3 mr-1"}),"Do Not Sell"]})}),jsxRuntime.jsx(TooltipContent,{children:jsxRuntime.jsx("p",{children:"Qualification"})})]})}):jsxRuntime.jsx(TooltipProvider,{children:jsxRuntime.jsxs(Tooltip$1,{children:[jsxRuntime.jsx(TooltipTrigger,{asChild:!0,children:jsxRuntime.jsxs(Badge,{variant:"info",className:t.DefaultOpportunityNumber?"pr-1":"",children:[jsxRuntime.jsx(BadgeCheck,{className:"h-3 w-3 mr-1"}),t.QualificationId,t.DefaultOpportunityNumber&&jsxRuntime.jsx(Badge,{variant:"secondary",size:"sm",className:"ml-1",children:t.DefaultOpportunityNumber})]})}),jsxRuntime.jsx(TooltipContent,{children:jsxRuntime.jsx("p",{children:"Qualification"})})]})})}function SalesChart({statistics:t,mode:e="month",chartHeight:n,loading:o=!1,size:l="default"}){const[d,f]=React.useState([]),[g,b]=React.useState(!1),_=[{name:"dollarVolume",label:"Dollar Volume",color:"var(--primary)",yAxisId:"left",format:"money"},{name:"unitsSold",label:"Units Sold",color:"#888",units:" units",yAxisId:"right",format:"integer"}];return React.useEffect(()=>{if(o||!t){f([]);return}let S=[];if(e==="week"){const R=new Map;t.forEach(C=>{var A;const E=((A=C.Day)==null?void 0:A.toString())||"";if(E.length===8){const M=parseInt(E.substring(0,4),10),I=parseInt(E.substring(4,6),10)-1,j=parseInt(E.substring(6,8),10),q=new Date(M,I,j),z=new Date(q);z.setDate(q.getDate()-q.getDay());const Q=`${z.getFullYear()}-${String(z.getMonth()+1).padStart(2,"0")}-${String(z.getDate()).padStart(2,"0")}`,F=R.get(Q)||{price:0,quantity:0};F.price+=C.ExtendedPrice||0,F.quantity+=C.Quantity||0,R.set(Q,F)}}),S=Array.from(R).sort(([C],[E])=>C.localeCompare(E)).map(([C,E])=>({date:`${C.substring(5,7)}/${C.substring(8,10)}`,dollarVolume:E.price,unitsSold:E.quantity}))}else{const R=new Date,C=R.getFullYear(),E=R.getMonth(),A=R.getDate(),M=`${C}-${(E+1).toString().padStart(2,"0")}`,I=Array.from({length:12},(q,z)=>{const Q=new Date(C,E-(11-z),1);return`${Q.getFullYear()}-${(Q.getMonth()+1).toString().padStart(2,"0")}`}),j=Object.fromEntries(I.map(q=>[q,{price:0,quantity:0}]));if(t.forEach(q=>{const z=String(q.Day??0);if(z.length!==8)return;const Q=`${z.substring(0,4)}-${z.substring(4,6)}`;j.hasOwnProperty(Q)&&(j[Q].price+=q.ExtendedPrice??0,j[Q].quantity+=q.Quantity??0)}),S=I.map(q=>{const z=j[q],[Q,F]=q.split("-").map(Number);return{date:new Date(Q,F-1).toLocaleString("default",{month:"short",year:"numeric"}),dollarVolume:z.price,unitsSold:z.quantity}}),g){const q=j[M];if(q&&q.price>0&&A>0){const z=new Date(C,E+1,0).getDate();if(A<z){const Q=q.price/A,F=q.quantity/A,V=Q*z,te=F*z,ne=S[S.length-1];ne&&(ne.dollarVolume=V,ne.unitsSold=te)}}}}f(S)},[t,e,g,o]),o?jsxRuntime.jsx("div",{style:{height:n},children:jsxRuntime.jsx(Skeleton,{className:"h-full w-full rounded-md"})}):d.length===0?jsxRuntime.jsx("div",{style:{height:n},className:"flex items-center justify-center text-muted-foreground",children:"No sales data available."}):jsxRuntime.jsxs(jsxRuntime.Fragment,{children:[jsxRuntime.jsx(AreaChart,{data:d,series:_,height:n,size:l}),l==="default"&&e==="month"&&jsxRuntime.jsxs("div",{className:"mt-4",children:[jsxRuntime.jsxs("div",{className:"flex items-center space-x-2",children:[jsxRuntime.jsx(Switch,{checked:g,onCheckedChange:b,id:"extrapolate-switch"}),jsxRuntime.jsx(Label$2,{htmlFor:"extrapolate-switch",children:"Extrapolate Current Month"})]}),g&&jsxRuntime.jsxs("p",{className:"mt-2 text-sm text-muted-foreground",children:["* Values for ",new Date().toLocaleString("default",{month:"long"})," are projected estimates."]})]})]})}function ManufacturerCard({manufacturer:t,link:e,linkNewTab:n=!0,actions:o,mainAction:l,loading:d=!1}){var S,R,C;if(d||!t)return jsxRuntime.jsxs(Card,{className:"flex flex-col h-full",children:[jsxRuntime.jsxs(CardHeader,{className:"flex flex-row items-start justify-between space-y-0 pb-2 pt-4",children:[jsxRuntime.jsxs("div",{className:"flex items-center gap-3",children:[jsxRuntime.jsx(Skeleton,{className:"h-12 w-12 rounded-md"}),jsxRuntime.jsxs("div",{children:[jsxRuntime.jsx(Skeleton,{className:"h-3 w-24 mb-2"}),jsxRuntime.jsx(Skeleton,{className:"h-5 w-40 mb-1"}),jsxRuntime.jsx(Skeleton,{className:"h-4 w-32 mb-1"}),jsxRuntime.jsx(Skeleton,{className:"h-4 w-48"})]})]}),jsxRuntime.jsx(Skeleton,{className:"h-16 w-24"})]}),jsxRuntime.jsx(CardContent,{className:"pb-2 flex-grow",children:jsxRuntime.jsxs("div",{className:"flex flex-col space-y-2",children:[jsxRuntime.jsxs("div",{className:"flex flex-wrap gap-2",children:[jsxRuntime.jsx(Skeleton,{className:"h-5 w-16 rounded-full"}),jsxRuntime.jsx(Skeleton,{className:"h-5 w-20 rounded-full"}),jsxRuntime.jsx(Skeleton,{className:"h-5 w-14 rounded-full"})]}),jsxRuntime.jsxs("div",{className:"space-y-1 pt-2",children:[jsxRuntime.jsxs("div",{className:"flex items-center gap-2",children:[jsxRuntime.jsx(Skeleton,{className:"h-4 w-4"}),jsxRuntime.jsx(Skeleton,{className:"h-4 w-32"})]}),jsxRuntime.jsxs("div",{className:"flex items-center gap-2",children:[jsxRuntime.jsx(Skeleton,{className:"h-4 w-4"}),jsxRuntime.jsx(Skeleton,{className:"h-4 w-40"})]}),jsxRuntime.jsxs("div",{className:"flex items-center gap-2",children:[jsxRuntime.jsx(Skeleton,{className:"h-4 w-4"}),jsxRuntime.jsx(Skeleton,{className:"h-4 w-36"})]})]})]})}),jsxRuntime.jsxs(CardFooter,{className:"flex justify-between pt-2 gap-2 mt-auto",children:[jsxRuntime.jsx(Skeleton,{className:"h-9 w-24"}),jsxRuntime.jsx(Skeleton,{className:"h-9 w-40"})]})]});const f=t.ManufacturerId||"N/A",g=[t.City,t.Province,t.Country].filter(Boolean),b=g.length>0?g.join(", "):"",_=((S=t.Tags)==null?void 0:S.split(",").map(E=>E.trim()).filter(Boolean))||[];return jsxRuntime.jsxs(Card,{className:"manufacturer-theme flex flex-col h-full",children:[jsxRuntime.jsx(reactRouterDom.Link,{to:e??"#",target:e&&n?"_blank":"_self",children:jsxRuntime.jsxs(CardHeader,{className:"flex flex-row items-start justify-between space-y-0 pb-2 pt-4",children:[jsxRuntime.jsxs("div",{className:"flex items-center gap-3",children:[jsxRuntime.jsx("div",{className:"h-12 w-12 overflow-hidden rounded-md",children:jsxRuntime.jsx(PartnerLogo,{id:t.ManufacturerId,width:48,height:48})}),jsxRuntime.jsxs("div",{children:[jsxRuntime.jsxs("div",{className:"flex items-center gap-2",children:[jsxRuntime.jsx("span",{className:"text-xs text-primary",children:"Manufacturer"}),jsxRuntime.jsx("span",{className:"text-xs text-muted-foreground",children:"|"}),jsxRuntime.jsx("span",{className:"text-xs text-muted-foreground",children:f})]}),jsxRuntime.jsx("h3",{className:"font-semibold",children:t.PublicName||"N/A"}),t.Name&&jsxRuntime.jsx("p",{className:"text-sm text-muted-foreground",children:t.Name}),b&&jsxRuntime.jsx("p",{className:"text-sm text-muted-foreground",children:b})]})]}),jsxRuntime.jsx("div",{className:"flex flex-col items-end gap-2",children:t.SalesStatistics&&t.SalesStatistics.length>0&&jsxRuntime.jsx("div",{className:"h-16 w-24",children:jsxRuntime.jsx(SalesChart,{statistics:t.SalesStatistics,size:"mini"})})})]})}),jsxRuntime.jsx(CardContent,{className:"pb-2 flex-grow",children:jsxRuntime.jsxs("div",{className:"flex",children:[jsxRuntime.jsxs("div",{className:"flex flex-col flex-1 space-y-2",children:[(!!((R=t.Qualification)!=null&&R.QualificationId)&&((C=t.Qualification)==null?void 0:C.QualificationId)!=="Suspended"||!!t.OpenToWork||!!t.OnHold&&t.OnHold!==0||_.length>0)&&jsxRuntime.jsxs("div",{className:"flex flex-wrap gap-2",children:[jsxRuntime.jsx(QualificationBadge,{qualification:t.Qualification??{}}),!!t.OpenToWork&&jsxRuntime.jsxs(Badge,{variant:"success",children:[jsxRuntime.jsx(HardHat,{className:"h-3 w-3 mr-1"}),"Open To Work"]}),!!t.OnHold&&t.OnHold!==0&&jsxRuntime.jsx(Badge,{variant:"warning",children:"On Hold"}),_.map((E,A)=>jsxRuntime.jsx(Badge,{variant:"outline",children:E},A))]}),jsxRuntime.jsxs("div",{className:"space-y-1 pt-2",children:[t.Phone&&jsxRuntime.jsxs(reactRouterDom.Link,{to:`tel:${t.Phone}`,target:"_blank",className:"flex items-center gap-2 text-sm text-muted-foreground",children:[jsxRuntime.jsx(Phone,{className:"h-4 w-4"}),jsxRuntime.jsx("span",{children:t.Phone})]}),t.PublicEmail&&jsxRuntime.jsxs(reactRouterDom.Link,{to:`mailto:${t.PublicEmail}`,target:"_blank",className:"flex items-center gap-2 text-sm text-muted-foreground",children:[jsxRuntime.jsx(Mail,{className:"h-4 w-4"}),jsxRuntime.jsx("span",{children:t.PublicEmail})]}),t.Website&&jsxRuntime.jsxs(reactRouterDom.Link,{to:t.Website,target:"_blank",className:"flex items-center gap-2 text-sm text-muted-foreground",children:[jsxRuntime.jsx(Globe,{className:"h-4 w-4"}),jsxRuntime.jsx("span",{children:t.Website})]}),t.CurrencyCode&&jsxRuntime.jsxs("div",{className:"flex items-center gap-2 text-sm text-muted-foreground",children:[jsxRuntime.jsx(DollarSign,{className:"h-4 w-4"}),jsxRuntime.jsx("span",{children:t.CurrencyCode})]})]})]}),t.SalesData&&jsxRuntime.jsxs("div",{className:"border-l pl-2 ml-2 flex flex-col text-sm",children:[jsxRuntime.jsx("strong",{className:"",children:"YTD"}),jsxRuntime.jsx("p",{children:t.SalesData.SalesYearToDay?formatMoney(t.SalesData.SalesYearToDay):"—"}),jsxRuntime.jsx("strong",{className:"mt-2",children:"3 mo."}),jsxRuntime.jsx("p",{children:t.SalesData.SalesLast3Months?formatMoney(t.SalesData.SalesLast3Months):"—"}),jsxRuntime.jsx("strong",{className:"mt-2",children:"30 days"}),jsxRuntime.jsx("p",{children:t.SalesData.SalesLast30Days?formatMoney(t.SalesData.SalesLast30Days):"—"})]})]})}),(o||l||t.PublicResourcesLink)&&jsxRuntime.jsxs(CardFooter,{className:"flex pt-2 gap-2 justify-between mt-auto",children:[jsxRuntime.jsxs("div",{className:"flex items-center gap-2",children:[o&&o,t.PublicResourcesLink&&jsxRuntime.jsx(TooltipProvider,{children:jsxRuntime.jsxs(Tooltip$1,{children:[jsxRuntime.jsx(TooltipTrigger,{asChild:!0,children:jsxRuntime.jsx(reactRouterDom.Link,{to:t.PublicResourcesLink,target:"_blank",children:jsxRuntime.jsx(Button,{size:"icon",children:jsxRuntime.jsx(HardDriveDownload,{className:"h-4 w-4"})})})}),jsxRuntime.jsx(TooltipContent,{children:jsxRuntime.jsx("p",{children:"Public Resources Link"})})]})})]}),l&&jsxRuntime.jsx("div",{children:l})]})]})}function OrdersCard({applicationId:t,orders:e=null,loading:n=!1,title:o="Order Details"}){const l=React.useMemo(()=>[{accessorKey:"DocumentNumber",header:"Document Number",cell:({row:g})=>g.original.DocumentNumber?jsxRuntime.jsx(TooltipProvider,{delayDuration:100,children:jsxRuntime.jsxs(Tooltip$1,{children:[jsxRuntime.jsx(TooltipTrigger,{asChild:!0,children:jsxRuntime.jsx(reactRouterDom.Link,{to:`/${t}/Document/${g.original.DocumentNumber}`,className:"font-medium text-primary hover:underline",children:g.original.DocumentNumber})}),jsxRuntime.jsx(TooltipContent,{children:jsxRuntime.jsxs("p",{children:["View details for order ",g.original.DocumentNumber]})})]})}):"N/A",enableSorting:!0,enableFiltering:!0},{accessorKey:"DocumentDate",header:"Document Date",cell:({row:g})=>formatYYYYMMDDIntToDateString(g.original.DocumentDate),enableSorting:!0,enableFiltering:!1},{accessorKey:"OrderNumber",header:"Order Number",cell:({row:g})=>g.original.OrderNumber??"N/A",enableSorting:!0,enableFiltering:!0},{accessorKey:"PONumber",header:"PO Number",cell:({row:g})=>g.original.PONumber??"N/A",enableSorting:!0,enableFiltering:!0},{accessorKey:"WarehouseCode",header:"Warehouse",cell:({row:g})=>g.original.WarehouseCode??"N/A",enableSorting:!0,enableFiltering:!0},{accessorKey:"Quantity",header:"Quantity",cell:({row:g})=>g.original.Quantity??"N/A",enableSorting:!0,enableFiltering:!1},{accessorKey:"ShipToName",header:"Name",cell:({row:g})=>jsxRuntime.jsx("div",{className:"min-w-[150px]",children:g.original.ShipToName??"N/A"}),enableSorting:!0,enableFiltering:!0},{accessorKey:"UnitPrice",header:"Unit Price",cell:({row:g})=>g.original.UnitPrice?formatMoney(g.original.UnitPrice):"N/A",enableSorting:!0,enableFiltering:!1}],[]),d=React.useMemo(()=>{const g={};if(e){const b=Array.from(new Set(e.map(E=>E.WarehouseCode).filter(E=>E!=null)));g.WarehouseCode=b;const _=Array.from(new Set(e.map(E=>E.ShipToName).filter(E=>E!=null)));g.ShipToName=_;const S=Array.from(new Set(e.map(E=>E.DocumentNumber).filter(E=>E!=null)));g.DocumentNumber=S;const R=Array.from(new Set(e.map(E=>E.OrderNumber).filter(E=>E!=null)));g.OrderNumber=R;const C=Array.from(new Set(e.map(E=>E.PONumber).filter(E=>E!=null)));g.PONumber=C}return g},[e]),f=e||[];return n?jsxRuntime.jsxs(Card,{className:"w-full",children:[jsxRuntime.jsxs(CardHeader,{children:[" ",jsxRuntime.jsx(Skeleton,{className:"h-7 w-48"})," "]}),jsxRuntime.jsxs(CardContent,{className:"space-y-4",children:[jsxRuntime.jsx(Skeleton,{className:"h-12 w-full rounded-md border"}),jsxRuntime.jsx(Skeleton,{className:"h-10 w-full rounded-md border"}),jsxRuntime.jsx(Skeleton,{className:"h-10 w-full rounded-md border"}),jsxRuntime.jsx(Skeleton,{className:"h-10 w-full rounded-md border"}),jsxRuntime.jsxs("div",{className:"flex items-center justify-between pt-4",children:[jsxRuntime.jsx(Skeleton,{className:"h-9 w-[130px]"}),jsxRuntime.jsxs("div",{className:"flex items-center space-x-2",children:[jsxRuntime.jsx(Skeleton,{className:"h-9 w-20"}),jsxRuntime.jsx(Skeleton,{className:"h-9 w-24"}),jsxRuntime.jsx(Skeleton,{className:"h-9 w-9"}),jsxRuntime.jsx(Skeleton,{className:"h-9 w-9"})]})]})]})]}):jsxRuntime.jsxs(Card,{className:"w-full",children:[jsxRuntime.jsxs(CardHeader,{children:[" ",jsxRuntime.jsx(CardTitle,{className:"text-1xl font-bold",children:o})," "]}),jsxRuntime.jsx(CardContent,{children:jsxRuntime.jsx(DataTable,{columns:l,data:f,uniqueValues:d})})]})}function ResellerOverview({appID:t,reseller:e,readonly:n,userEmail:o,isSuperAdmin:l,withoutReports:d=!1}){const{data:f,isLoading:g,isError:b}=useGetV4PartnerByApplicationIdAccountResellerQuery({applicationId:t??"",withSpecification:!0},{skip:!!e}),[_,S]=React.useState({publicInfo:{hasUnsavedChanges:!1}}),R=React.useCallback(()=>n?!1:_.publicInfo.hasUnsavedChanges,[n,_]),C=React.useCallback((q,z)=>{S(Q=>{var F;return((F=Q[q])==null?void 0:F.hasUnsavedChanges)!==z.hasUnsavedChanges?{...Q,[q]:z}:Q})},[]),{NavigationGuardDialog:E}=useRouterNavigationGuard(R),A=e??f,M=!n||!!(A!=null&&A.Statement)&&(A.Statement.Total??0)>0,I=(A==null?void 0:A.QualifiedManufacturers)??[],j=(A==null?void 0:A.Qualifications)??[];return jsxRuntime.jsxs("div",{className:"@container",children:[b?jsxRuntime.jsx(Card,{className:"p-6",children:jsxRuntime.jsxs(Alert,{variant:"destructive",children:[jsxRuntime.jsx(CircleAlert,{className:"h-4 w-4"}),jsxRuntime.jsx(AlertTitle,{children:"Error"}),jsxRuntime.jsx(AlertDescription,{children:"There was an error loading your reseller information. Please try again later."})]})}):jsxRuntime.jsxs("div",{className:"space-y-6 mb-6",children:[jsxRuntime.jsx(SalesSummary,{fiscalYearMonthStart:(A==null?void 0:A.FiscalYearMonthStart)||1,salesData:A==null?void 0:A.SalesData,isLoading:g}),jsxRuntime.jsxs("div",{className:"grid grid-cols-1 @2xl:grid-cols-2 gap-6",children:[jsxRuntime.jsx(SalesChartCard,{statistics:(A==null?void 0:A.SalesStatistics)??[],loading:g}),jsxRuntime.jsx(OrderCategories,{openOrders:(A==null?void 0:A.ActiveOrderDetails)??[],isLoading:g}),M&&jsxRuntime.jsx(BillingCard,{appID:t,reseller:A||{},withoutReports:d,isLoading:g,userEmail:o}),jsxRuntime.jsx(PublicInfo,{reseller:A||{},appID:t??"",isLoading:g,readonly:n,onUnsavedChanges:q=>C("publicInfo",{hasUnsavedChanges:q})}),jsxRuntime.jsx(AccountTier,{isSuperAdmin:l,readonly:n,reseller:A||{},appID:t??"",isLoading:g})]}),g||I.length>0?jsxRuntime.jsxs(Card,{className:"w-full",children:[jsxRuntime.jsx(CardHeader,{children:jsxRuntime.jsx(CardTitle,{children:"Manufacturers you are qualified for"})}),jsxRuntime.jsx(CardContent,{children:jsxRuntime.jsx("div",{className:"grid @2xl:grid-cols-2 gap-4",children:g?Array.from({length:2}).map((q,z)=>jsxRuntime.jsx(ManufacturerCard,{loading:!0},z)):I.map(q=>jsxRuntime.jsx(ManufacturerCard,{manufacturer:q,link:`https://dashboard.randmar.io/${t}/Partner/${q.ManufacturerId}`},q.ManufacturerId))})})]}):jsxRuntime.jsx(ResellerQualificationsCard,{qualifications:j}),jsxRuntime.jsx(OpportunitiesTable,{applicationId:t,opportunities:A==null?void 0:A.Opportunities,loading:g}),jsxRuntime.jsx(OrdersCard,{applicationId:t,title:"Active Orders",orders:A==null?void 0:A.ActiveOrderDetails,loading:g}),jsxRuntime.jsx(OrdersCard,{applicationId:t,title:"Completed Orders",orders:A==null?void 0:A.CompletedOrderDetails,loading:g}),jsxRuntime.jsx(ReturnsTable,{applicationId:t,returns:A==null?void 0:A.Returns,loading:g}),!d&&jsxRuntime.jsx(ReportsSection,{appID:t,userEmail:o,isLoading:g})]}),jsxRuntime.jsx(E,{})]})}const alertVariants=cva("relative w-full rounded-lg border px-4 py-3 text-sm [&>svg+div]:translate-y-[-3px] [&>svg]:absolute [&>svg]:left-4 [&>svg]:top-4 [&>svg]:text-foreground [&>svg~*]:pl-7",{variants:{variant:{default:"bg-background text-foreground",destructive:"border-destructive/50 text-destructive dark:border-destructive [&>svg]:text-destructive",success:"border-green-500/50 bg-green-50 text-green-700 dark:border-green-500 dark:bg-green-950 dark:text-green-400 [&>svg]:text-green-500",warning:"border-yellow-500/50 bg-yellow-50 text-yellow-700 dark:border-yellow-500 dark:bg-yellow-950 dark:text-yellow-400 [&>svg]:text-yellow-500",info:"border-blue-500/50 bg-blue-50 text-blue-700 dark:border-blue-500 dark:bg-blue-950 dark:text-blue-400 [&>svg]:text-blue-500"}},defaultVariants:{variant:"default"}}),Alert=React__namespace.forwardRef(({className:t,variant:e,...n},o)=>jsxRuntime.jsx("div",{ref:o,role:"alert",className:cn(alertVariants({variant:e}),t),...n}));Alert.displayName="Alert";const AlertTitle=React__namespace.forwardRef(({className:t,...e},n)=>jsxRuntime.jsx("h5",{ref:n,className:cn("mb-1 font-medium leading-none tracking-tight",t),...e}));AlertTitle.displayName="AlertTitle";const AlertDescription=React__namespace.forwardRef(({className:t,...e},n)=>jsxRuntime.jsx("div",{ref:n,className:cn("text-sm [&_p]:leading-relaxed",t),...e}));AlertDescription.displayName="AlertDescription";/**
|
|
1084
|
+
$10 with opportunities under $1,000`:t==="D"?"$15 under $1,500":t==="E"?"Full shipping charges":t,getTermsText=t=>t==="STRIPE"?"Credit card payment":t==="NET30"?"Net 30 days":t,AccountTier=({isSuperAdmin:t,readonly:e,reseller:n,appID:o,isLoading:l})=>{const{toast:d}=useToast(),[f,g]=React.useState(!1),[b,_]=React.useState(""),[S,{isLoading:R}]=usePostV4PartnerByApplicationIdAccountResellerAndFieldNameMutation(),C=Oe=>Oe&&{Starter:"starter","E-Commerce":"ecommerce",Commercial:"commercial",Basics:"cws",Novexco:"novexco","Jean Coutu":"jeancoutu",Exclusive:"exclusive"}[Oe]||"",E=Oe=>Oe&&{A:"free",B:"fixed",C:"dropshipped",D:"under1500",E:"fullcharges"}[Oe]||"",A=Oe=>Oe&&{1:"exclusive",2:"ecommerce",3:"commercial",4:"buyinggroup",5:"cost"}[Oe]||"",[M,I]=React.useState(C((n==null?void 0:n.Priority)??"")),[j,q]=React.useState(E((n==null?void 0:n.ShippingProfile)??"")),[z,Q]=React.useState(A(n==null?void 0:n.PriceProfile)),F=Oe=>({starter:"Starter",ecommerce:"E-Commerce",commercial:"Commercial",cws:"Basics",novexco:"Novexco",jeancoutu:"Jean Coutu",exclusive:"Exclusive"})[Oe]||Oe,V=Oe=>({free:"A",fixed:"B",dropshipped:"C",under1500:"D",fullcharges:"E"})[Oe]||Oe,te=Oe=>({exclusive:"1",ecommerce:"2",commercial:"3",buyinggroup:"4",cost:"5"})[Oe]||Oe;React.useEffect(()=>{I(C((n==null?void 0:n.Priority)??"")),q(E((n==null?void 0:n.ShippingProfile)??"")),Q(A(n==null?void 0:n.PriceProfile))},[n]);const ne=async(Oe,Fe,ze,$e)=>{try{(await S({applicationId:o,fieldName:Oe,newValue:Fe})).error?d({title:"Error",description:$e,variant:"destructive"}):d({title:"Success",description:ze,variant:"success"})}catch{d({title:"Error",description:"An unexpected error occurred",variant:"destructive"})}},se=async Oe=>{I(Oe);const Fe=F(Oe);ne("Priority",Fe,`Priority updated to ${Fe}`,"Failed to update priority")},ge=async Oe=>{q(Oe);const Fe=V(Oe);ne("ShippingProfile",Fe,`Shipping profile updated to ${Fe}`,"Failed to update shipping profile")},oe=async Oe=>{Q(Oe);const Fe=te(Oe);ne("PriceProfile",Fe,`Pricing profile updated to ${Fe}`,"Failed to update pricing profile")},Ae=async()=>{try{const Oe=await S({applicationId:o,fieldName:"Tier",newValue:b});Oe.error?d({title:"Error",description:"Failed to update reseller",variant:"destructive"}):Oe.data?d({title:"Success",description:`Pricing Tier changed to ${b}`,variant:"success"}):d({title:"Considered",description:"Request being considered",variant:"success"})}catch{d({title:"Error",description:"An unexpected error occurred",variant:"destructive"})}finally{g(!1),_("")}},je=[{name:"Terms",enabled:n.Priority==="Starter"},{name:"E-Commerce",enabled:n.Priority==="Commercial"},{name:"Commercial",enabled:n.Priority==="E-Commerce"},{name:"Exclusive",enabled:t}],Ne=Oe=>{_(Oe),g(!0)};return l?jsxRuntime.jsxs(Card,{className:"w-full",children:[jsxRuntime.jsx(CardHeader,{className:"pb-2",children:jsxRuntime.jsxs("div",{className:"flex items-center justify-between",children:[jsxRuntime.jsx(Skeleton,{className:"h-6 w-28"}),jsxRuntime.jsx(Skeleton,{className:"h-6 w-16 rounded-full"})]})}),jsxRuntime.jsxs(CardContent,{children:[jsxRuntime.jsxs("div",{className:"mb-3",children:[jsxRuntime.jsx(Skeleton,{className:"h-8 w-40 mb-1"}),jsxRuntime.jsx(Skeleton,{className:"h-4 w-56"})]}),jsxRuntime.jsx("div",{className:"grid gap-3",children:[1,2,3].map(Oe=>jsxRuntime.jsxs("div",{className:"flex items-center gap-3",children:[jsxRuntime.jsx(Skeleton,{className:"h-8 w-8 rounded-full shrink-0"}),jsxRuntime.jsxs("div",{className:"flex-1",children:[jsxRuntime.jsx(Skeleton,{className:"h-5 w-20 mb-1"}),jsxRuntime.jsx(Skeleton,{className:"h-4 w-full"})]})]},Oe))}),jsxRuntime.jsxs("div",{className:"flex gap-2 mt-3",children:[jsxRuntime.jsx(Skeleton,{className:"h-10 w-full"}),jsxRuntime.jsx(Skeleton,{className:"h-10 w-full"})]})]})]}):jsxRuntime.jsxs(jsxRuntime.Fragment,{children:[jsxRuntime.jsxs(Card,{className:"w-full",children:[jsxRuntime.jsxs(CardHeader,{className:"pb-2 pt-4 px-4 flex flex-row items-center justify-between",children:[jsxRuntime.jsx(CardTitle,{className:"text-1xl font-bold",children:"Account Tier"}),jsxRuntime.jsx(Badge,{variant:"secondary",className:"bg-green-100 text-green-700 hover:bg-green-200 text-xs",children:"Active"})]}),jsxRuntime.jsxs(CardContent,{className:"pt-2 px-4 pb-4",children:[jsxRuntime.jsxs("div",{className:"flex items-center justify-between mb-3 bg-primary/5 p-4 rounded-lg",children:[jsxRuntime.jsxs("div",{children:[jsxRuntime.jsxs("h3",{className:"text-lg font-bold text-primary",children:[(n==null?void 0:n.Priority)||""," Tier"]}),jsxRuntime.jsx("p",{className:"text-xs text-muted-foreground",children:"Optimized for online retail"})]}),jsxRuntime.jsx(CircleCheck,{className:"h-6 w-6 text-green-600"})]}),jsxRuntime.jsxs("div",{className:"grid grid-cols-1 gap-2 mb-3",children:[jsxRuntime.jsxs("div",{className:"flex items-center gap-2 p-2 rounded-lg border bg-card hover:bg-accent/5 transition-colors",children:[jsxRuntime.jsx("div",{className:"bg-primary/10 p-1.5 rounded-full shrink-0",children:jsxRuntime.jsx(Package2,{className:"h-4 w-4 text-primary"})}),jsxRuntime.jsxs("div",{className:"min-w-0",children:[jsxRuntime.jsx("p",{className:"font-medium text-sm",children:"Pricing"}),jsxRuntime.jsx("p",{className:"text-xs text-muted-foreground truncate",children:getPricingText(n.PriceProfile||0)})]})]}),jsxRuntime.jsxs("div",{className:"flex items-center gap-2 p-2 rounded-lg border bg-card hover:bg-accent/5 transition-colors",children:[jsxRuntime.jsx("div",{className:"bg-primary/10 p-1.5 rounded-full shrink-0",children:jsxRuntime.jsx(Truck,{className:"h-4 w-4 text-primary"})}),jsxRuntime.jsxs("div",{className:"min-w-0",children:[jsxRuntime.jsx("p",{className:"font-medium text-sm",children:"Shipping"}),jsxRuntime.jsx("p",{className:"text-xs text-muted-foreground",children:getShippingText(n.ShippingProfile||"").split(".")[0]})]})]}),jsxRuntime.jsxs("div",{className:"flex items-center gap-2 p-2 rounded-lg border bg-card hover:bg-accent/5 transition-colors",children:[jsxRuntime.jsx("div",{className:"bg-primary/10 p-1.5 rounded-full shrink-0",children:jsxRuntime.jsx(Calendar,{className:"h-4 w-4 text-primary"})}),jsxRuntime.jsxs("div",{className:"min-w-0",children:[jsxRuntime.jsx("p",{className:"font-medium text-sm",children:"Payment terms"}),jsxRuntime.jsx("p",{className:"text-xs text-muted-foreground",children:getTermsText((n==null?void 0:n.Terms)||"")})]})]})]}),jsxRuntime.jsxs("div",{className:"flex gap-2",children:[!e&&jsxRuntime.jsx(Button,{variant:"outline",className:"flex-1",asChild:!0,children:jsxRuntime.jsxs(reactRouterDom.Link,{to:"https://www.randmar.io/docs/overview/pricingTiers",target:"_blank",children:[jsxRuntime.jsx(ExternalLink,{className:"h-4 w-4 mr-1"}),"Pricing Tiers"]})}),jsxRuntime.jsxs(Popover,{children:[jsxRuntime.jsx(PopoverTrigger,{asChild:!0,children:jsxRuntime.jsxs(Button,{disabled:e,className:e?"hidden":"flex-1",children:["Upgrade Tier ",jsxRuntime.jsx(ChevronRight,{className:"h-3 w-3 ml-1"})]})}),jsxRuntime.jsx(PopoverContent,{className:"w-56 p-2",children:jsxRuntime.jsxs("div",{className:"grid gap-1",children:[jsxRuntime.jsx("h4",{className:"font-medium text-xs mb-1",children:"Select a tier"}),je.map(Oe=>jsxRuntime.jsx(Button,{variant:"ghost",size:"sm",className:"w-full justify-start h-8",disabled:!Oe.enabled,onClick:()=>Ne(Oe.name),children:Oe.name},Oe.name))]})})]})]})]})]}),jsxRuntime.jsx(ChangePricingTierModal,{isLoading:R,open:f,setOpen:g,tier:b,onTierChange:Ae}),t&&!e&&jsxRuntime.jsxs(Card,{className:"mt-4",children:[jsxRuntime.jsx(CardHeader,{className:"pb-2 pt-3 px-4",children:jsxRuntime.jsx(CardTitle,{className:"text-1xl font-bold",children:"Admin Configuration"})}),jsxRuntime.jsx(CardContent,{className:"pt-2 px-4 pb-4",children:jsxRuntime.jsxs("div",{className:"space-y-3",children:[jsxRuntime.jsxs("div",{className:"bg-muted/30 p-2 rounded-lg",children:[jsxRuntime.jsx(Label$2,{className:"block mb-1 text-xs font-medium",children:"Priority"}),jsxRuntime.jsx(RadioGroup$1,{value:M,onValueChange:se,className:"grid grid-cols-2 @sm:grid-cols-3 @md:grid-cols-4 gap-1",children:[{value:"starter",label:"Starter"},{value:"ecommerce",label:"E-Commerce"},{value:"commercial",label:"Commercial"},{value:"cws",label:"CWS (Basics)"},{value:"novexco",label:"Novexco"},{value:"jeancoutu",label:"Jean Coutu"},{value:"exclusive",label:"Exclusive"}].map(Oe=>jsxRuntime.jsxs("div",{className:"flex items-center space-x-1",children:[jsxRuntime.jsx(RadioGroupItem,{value:Oe.value,id:`priority-${Oe.value}`,className:"h-6 w-6 scale-50"}),jsxRuntime.jsx(Label$2,{htmlFor:`priority-${Oe.value}`,className:"cursor-pointer text-xs",children:Oe.label})]},Oe.value))})]}),jsxRuntime.jsxs("div",{className:"bg-muted/30 p-2 rounded-lg",children:[jsxRuntime.jsx(Label$2,{className:"block mb-1 text-xs font-medium",children:"Shipping Profile"}),jsxRuntime.jsx(RadioGroup$1,{value:j,onValueChange:ge,className:"grid grid-cols-1 @md:grid-cols-2 gap-1",children:[{value:"free",label:"Free (A)"},{value:"fixed",label:"Fixed $10 Shipping (B)"},{value:"dropshipped",label:"$15 for drop shipped (C)"},{value:"under1500",label:"15$ under 1,500 (D)"},{value:"fullcharges",label:"Full shipping charges (E)"}].map(Oe=>jsxRuntime.jsxs("div",{className:"flex items-center space-x-1",children:[jsxRuntime.jsx(RadioGroupItem,{value:Oe.value,id:`shipping-${Oe.value}`,className:"h-6 w-6 scale-50"}),jsxRuntime.jsx(Label$2,{htmlFor:`shipping-${Oe.value}`,className:"cursor-pointer text-xs",children:Oe.label})]},Oe.value))})]}),jsxRuntime.jsxs("div",{className:"bg-muted/30 p-2 rounded-lg",children:[jsxRuntime.jsx(Label$2,{className:"block mb-1 text-xs font-medium",children:"Pricing Profile"}),jsxRuntime.jsx(RadioGroup$1,{value:z,onValueChange:oe,className:"grid grid-cols-2 @sm:grid-cols-3 gap-1",children:[{value:"exclusive",label:"Exclusive (1)"},{value:"ecommerce",label:"E-Commerce (2)"},{value:"commercial",label:"Commercial (3)"},{value:"buyinggroup",label:"Buying Group (4)"},{value:"cost",label:"Cost (5)"}].map(Oe=>jsxRuntime.jsxs("div",{className:"flex items-center space-x-1",children:[jsxRuntime.jsx(RadioGroupItem,{value:Oe.value,id:`pricing-${Oe.value}`,className:"h-6 w-6 scale-50 antialiased"}),jsxRuntime.jsx(Label$2,{htmlFor:`pricing-${Oe.value}`,className:"cursor-pointer text-xs",children:Oe.label})]},Oe.value))})]})]})})]})]})};function OrderCategories({openOrders:t=[],isLoading:e=!1}){const n=(t==null?void 0:t.filter(M=>M.DocumentType==="Order"))||[],o=(t==null?void 0:t.filter(M=>M.DocumentType==="Shipment"))||[],l=n.filter(M=>M.WarehouseCode!=="3PLE"),d=l.reduce((M,I)=>M+(I.Quantity??0),0),f=l.reduce((M,I)=>M+(I.ExtendedPrice??0),0),g=n.filter(M=>M.WarehouseCode==="3PLE"),b=g.reduce((M,I)=>M+(I.Quantity??0),0),_=g.reduce((M,I)=>M+(I.ExtendedPrice??0),0),S=o.reduce((M,I)=>M+(I.Quantity??0),0),R=o.reduce((M,I)=>M+(I.ExtendedPrice??0),0),C=d+b+S,E=f+_+R,A=[{name:"All",icon:Package,color:"bg-blue-500",orders:C,amount:E},{name:"Processing",icon:RefreshCcw,color:"bg-yellow-500",orders:d,amount:f},{name:"Shipped",icon:Truck,color:"bg-green-500",orders:S,amount:R},{name:"Delayed",icon:CircleAlert,color:"bg-red-500",orders:b,amount:_}];return e?jsxRuntime.jsxs(Card,{className:"w-full @md:col-span-2 @xl:col-span-1",children:[jsxRuntime.jsx(CardHeader,{children:jsxRuntime.jsx(Skeleton,{className:"h-7 w-40"})}),jsxRuntime.jsx(CardContent,{children:jsxRuntime.jsx("div",{className:"grid grid-cols-1 @sm:grid-cols-2 gap-3.5",children:[1,2,3,4].map(M=>jsxRuntime.jsx(Card,{className:"overflow-hidden rounded-md rounded-b-lg border-0 shadow-md",children:jsxRuntime.jsxs(CardContent,{className:"p-0",children:[jsxRuntime.jsx("div",{className:"bg-gray-200 h-[3px]"}),jsxRuntime.jsxs("div",{className:"p-6 border border-t-0",children:[jsxRuntime.jsxs("div",{className:"flex justify-between items-center mb-4",children:[jsxRuntime.jsx(Skeleton,{className:"h-5 w-24"}),jsxRuntime.jsx(Skeleton,{className:"h-8 w-8 rounded-full"})]}),jsxRuntime.jsxs("div",{className:"flex justify-between items-start",children:[jsxRuntime.jsxs("div",{children:[jsxRuntime.jsx(Skeleton,{className:"h-3 w-20 mb-1"}),jsxRuntime.jsx(Skeleton,{className:"h-6 w-12"})]}),jsxRuntime.jsxs("div",{className:"text-end",children:[jsxRuntime.jsx(Skeleton,{className:"h-3 w-20 mb-1"}),jsxRuntime.jsx(Skeleton,{className:"h-5 w-20"})]})]})]})]})},M))})})]}):jsxRuntime.jsxs(Card,{className:"w-full @md:col-span-2 @xl:col-span-1",children:[jsxRuntime.jsx(CardHeader,{children:jsxRuntime.jsx(CardTitle,{className:"text-1xl font-bold",children:"Order Categories"})}),jsxRuntime.jsx(CardContent,{children:jsxRuntime.jsx("div",{className:"grid grid-cols-1 @sm:grid-cols-2 gap-3.5",children:A.map(M=>jsxRuntime.jsx(Card,{className:"overflow-hidden rounded-md rounded-b-lg border-0 shadow-md",children:jsxRuntime.jsxs(CardContent,{className:"p-0",children:[jsxRuntime.jsx("div",{className:`${M.color} bg-opacity-60 h-[3px]`}),jsxRuntime.jsxs("div",{className:"p-6 border border-t-0",children:[jsxRuntime.jsxs("div",{className:"flex justify-between items-center mb-4",children:[jsxRuntime.jsx("h3",{className:"font-semibold text-base",children:M.name}),jsxRuntime.jsx("div",{className:`${M.color} bg-opacity-90 p-2 rounded-full`,children:jsxRuntime.jsx(M.icon,{className:"size-4 shrink-0 text-white"})})]}),jsxRuntime.jsxs("div",{className:"flex justify-between items-start",children:[jsxRuntime.jsxs("div",{children:[jsxRuntime.jsx("p",{className:"text-xs text-muted-foreground",children:"Total Orders"}),jsxRuntime.jsx("p",{className:"text-xl font-bold",children:M.orders})]}),jsxRuntime.jsxs("div",{className:"text-end",children:[jsxRuntime.jsx("p",{className:"text-xs text-muted-foreground",children:"Total Amount"}),jsxRuntime.jsx("p",{className:"text-base font-semibold",children:jsxRuntime.jsx(FormattedNumber,{value:M.amount,style:"currency",currency:"CAD",currencyDisplay:"symbol"})})]})]})]})]})},M.name))})})]})}function ReportsSection({isLoading:t,userEmail:e,appID:n}){const{toast:o}=useToast(),[l,{isLoading:d}]=usePostV4ResellerByRouteResellerIdReportWalmartTrackingFileEmailMutation(),[f,{isLoading:g}]=usePostV4ResellerByRouteResellerIdReportAmazonTrackingFileEmailMutation(),[b,{isLoading:_}]=usePostV4ResellerByRouteResellerIdReportOpenOrdersEmailMutation(),[S,{isLoading:R}]=usePostV4ResellerByRouteResellerIdReportProductsEmailMutation(),[C,{isLoading:E}]=usePostV4ResellerByRouteResellerIdReportInvoicesEmailMutation(),[A,{isLoading:M}]=usePostV4ResellerByRouteResellerIdDocumentStatementEmailMutation(),[I,j]=React.useState(null),[q,z]=React.useState(e),[Q,F]=React.useState(!1),V=[{name:"Products",reports:[{id:"Products",title:"Universal Product List",description:"A comprehensive overview of your product list with detailed specifications and pricing information.",icon:Package}]},{name:"Operation Details",reports:[{id:"OpenOrders",title:"Order Details",description:"A detailed report of all your orders and shipments, including status, tracking information, and delivery estimates.",icon:ShoppingCart},{id:"Invoices",title:"Invoices and Credits Report",description:"Detailed overview of your invoices and credits within a specific date range. It also contains reports about additional charges, serial numbers, and other relevant information.",icon:ScrollText},{id:"Statement",title:"Statement and RMAs Report",description:"A detailed report of all unpaid invoices and active RMAs.",icon:Banknote}]},{name:"Tracking Files",reports:[{id:"AmazonTrackingFile",title:"Amazon Tracking File",description:"Track products sold on Amazon marketplace with detailed sales and inventory information.",icon:ChartNoAxesColumnIncreasing},{id:"WalmartTrackingFile",title:"Walmart Tracking File",description:"Track products sold on Walmart marketplace with detailed sales and inventory information.",icon:ChartNoAxesColumnIncreasing}]}],te=async ge=>{j(ge),F(!0)},ne=async()=>{if(!(!I||!n))try{switch(I.id){case"Products":await S({routeResellerId:n,emailAddress:q}).unwrap();break;case"AmazonTrackingFile":await f({routeResellerId:n,emailAddress:q}).unwrap();break;case"WalmartTrackingFile":await l({routeResellerId:n,emailAddress:q}).unwrap();break;case"OpenOrders":await b({routeResellerId:n,emailAddress:q}).unwrap();break;case"Invoices":await C({routeResellerId:n,emailAddress:q}).unwrap();break;case"Statement":await A({routeResellerId:n,emailAddress:q}).unwrap();break;default:throw new Error("invalid report id")}o({title:"Report requested",description:`The ${I.title} will be sent to ${q} shortly.`,variant:"success"}),F(!1)}catch(ge){console.error("Error requesting report:",ge),o({title:"Error",description:"Failed to request report. Please try again.",variant:"destructive"})}},se=_||R||g||d||M||E;return jsxRuntime.jsxs(Card,{children:[jsxRuntime.jsxs(CardHeader,{children:[jsxRuntime.jsx(CardTitle,{className:"text-1xl font-bold",children:"Reports"}),jsxRuntime.jsx("p",{className:"text-sm text-muted-foreground",children:"Download essential business reports, from your Product List to your Order Details."})]}),jsxRuntime.jsx(CardContent,{className:"space-y-6",children:t?jsxRuntime.jsx(jsxRuntime.Fragment,{children:[1,2,3].map(ge=>jsxRuntime.jsxs("div",{className:"space-y-4",children:[jsxRuntime.jsx(Skeleton,{className:"h-6 w-48"}),[1,2].map(oe=>jsxRuntime.jsxs("div",{className:"flex items-start gap-4 p-4 border rounded-lg",children:[jsxRuntime.jsx(Skeleton,{className:"h-9 w-9 rounded-full"}),jsxRuntime.jsxs("div",{className:"flex-1",children:[jsxRuntime.jsx(Skeleton,{className:"h-5 w-40 mb-2"}),jsxRuntime.jsx(Skeleton,{className:"h-4 w-full"})]}),jsxRuntime.jsx(Skeleton,{className:"h-9 w-24"})]},oe))]},ge))}):jsxRuntime.jsx(jsxRuntime.Fragment,{children:V.map(ge=>jsxRuntime.jsxs("div",{className:"space-y-4",children:[jsxRuntime.jsx("h3",{className:"text-sm font-semibold",children:ge.name}),ge.reports.map(oe=>jsxRuntime.jsxs("div",{className:"flex items-start gap-4 p-4 border rounded-lg hover:bg-gray-100 transition-colors",children:[jsxRuntime.jsx("div",{className:"bg-primary/10 p-2 rounded-full",children:jsxRuntime.jsx(oe.icon,{className:"h-5 w-5 text-primary"})}),jsxRuntime.jsxs("div",{className:"flex-1",children:[jsxRuntime.jsx("h4",{className:"font-semibold text-sm",children:oe.title}),jsxRuntime.jsx("p",{className:"text-sm text-muted-foreground mt-1",children:oe.description})]}),jsxRuntime.jsxs(Button,{variant:"outline",size:"sm",className:"flex items-center gap-1",onClick:()=>te(oe),children:[jsxRuntime.jsx(Download,{className:"h-4 w-4"}),"Request"]})]},oe.id))]},ge.name))})}),jsxRuntime.jsx(Dialog,{open:Q,onOpenChange:F,children:jsxRuntime.jsxs(DialogContent,{children:[jsxRuntime.jsxs(DialogHeader,{children:[jsxRuntime.jsxs(DialogTitle,{children:["Request ",I==null?void 0:I.title]}),jsxRuntime.jsx(DialogDescription,{children:"Enter the email address where you would like to receive the report."})]}),jsxRuntime.jsxs("div",{className:"py-4",children:[jsxRuntime.jsx(Label$2,{htmlFor:"email",children:"Email"}),jsxRuntime.jsx(Input,{id:"email",value:q,onChange:ge=>z(ge.target.value),placeholder:"your@email.com",className:"mt-2"})]}),jsxRuntime.jsx(DialogDescription,{children:"The report will take around 5 minutes to generate."}),jsxRuntime.jsxs(DialogFooter,{children:[jsxRuntime.jsx(Button,{variant:"outline",onClick:()=>F(!1),children:"Cancel"}),jsxRuntime.jsx(Button,{onClick:ne,disabled:!q||se,children:se?jsxRuntime.jsxs(jsxRuntime.Fragment,{children:[jsxRuntime.jsx(LoaderCircle,{className:"mr-2 h-4 w-4 animate-spin"}),"Sending..."]}):"Send Report"})]})]})})]})}const badgeVariants=cva("inline-flex items-center rounded-full px-2.5 py-0.5 text-xs font-semibold transition-colors focus:outline-hidden focus:ring-2 focus:ring-ring focus:ring-offset-2",{variants:{variant:{default:"bg-primary text-primary-foreground hover:bg-primary/80",secondary:"bg-secondary text-secondary-foreground hover:bg-secondary/80",destructive:"bg-destructive text-destructive-foreground hover:bg-destructive/80",outline:"text-foreground border border-input hover:bg-accent hover:text-accent-foreground",success:"bg-green-600 text-white hover:bg-green-700",warning:"bg-yellow-500 text-white hover:bg-yellow-600",info:"bg-blue-500 text-white hover:bg-blue-600",ghost:"bg-background hover:bg-accent hover:text-accent-foreground",randmarRed:"bg-randmar-red text-white hover:bg-randmar-red/80",randmarBlue:"bg-randmar-blue text-white hover:bg-randmar-blue/80",randmarPurple:"bg-randmar-purple text-white hover:bg-randmar-purple/80",randmarGreen:"bg-randmar-green text-black hover:bg-randmar-green/80",randmarBlack:"bg-randmar-black text-white hover:bg-randmar-black/80",randmarYellow:"bg-randmar-yellow text-black hover:bg-randmar-yellow/80"},size:{default:"h-6",sm:"h-5 text-[10px]",lg:"h-7 px-3"}},defaultVariants:{variant:"default",size:"default"}}),Badge=React__namespace.forwardRef(({className:t,variant:e,size:n,icon:o,children:l,...d},f)=>jsxRuntime.jsxs("div",{ref:f,className:cn(badgeVariants({variant:e,size:n}),t),...d,children:[o&&jsxRuntime.jsx("span",{className:"mr-1",children:o}),l]}));Badge.displayName="Badge";function QualificationBadge({qualification:t}){return!t.QualificationId||t.QualificationId==="Suspended"?null:t.QualificationId==="Do Not Sell"?jsxRuntime.jsx(TooltipProvider,{children:jsxRuntime.jsxs(Tooltip$1,{children:[jsxRuntime.jsx(TooltipTrigger,{asChild:!0,children:jsxRuntime.jsxs(Badge,{variant:"destructive",children:[jsxRuntime.jsx(X$1,{className:"h-3 w-3 mr-1"}),"Do Not Sell"]})}),jsxRuntime.jsx(TooltipContent,{children:jsxRuntime.jsx("p",{children:"Qualification"})})]})}):jsxRuntime.jsx(TooltipProvider,{children:jsxRuntime.jsxs(Tooltip$1,{children:[jsxRuntime.jsx(TooltipTrigger,{asChild:!0,children:jsxRuntime.jsxs(Badge,{variant:"info",className:t.DefaultOpportunityNumber?"pr-1":"",children:[jsxRuntime.jsx(BadgeCheck,{className:"h-3 w-3 mr-1"}),t.QualificationId,t.DefaultOpportunityNumber&&jsxRuntime.jsx(Badge,{variant:"secondary",size:"sm",className:"ml-1",children:t.DefaultOpportunityNumber})]})}),jsxRuntime.jsx(TooltipContent,{children:jsxRuntime.jsx("p",{children:"Qualification"})})]})})}function SalesChart({statistics:t,mode:e="month",chartHeight:n,loading:o=!1,size:l="default"}){const[d,f]=React.useState([]),[g,b]=React.useState(!1),_=[{name:"dollarVolume",label:"Dollar Volume",color:"var(--primary)",yAxisId:"left",format:"money"},{name:"unitsSold",label:"Units Sold",color:"#888",units:" units",yAxisId:"right",format:"integer"}];return React.useEffect(()=>{if(o||!t){f([]);return}let S=[];if(e==="week"){const R=new Map;t.forEach(C=>{var A;const E=((A=C.Day)==null?void 0:A.toString())||"";if(E.length===8){const M=parseInt(E.substring(0,4),10),I=parseInt(E.substring(4,6),10)-1,j=parseInt(E.substring(6,8),10),q=new Date(M,I,j),z=new Date(q);z.setDate(q.getDate()-q.getDay());const Q=`${z.getFullYear()}-${String(z.getMonth()+1).padStart(2,"0")}-${String(z.getDate()).padStart(2,"0")}`,F=R.get(Q)||{price:0,quantity:0};F.price+=C.ExtendedPrice||0,F.quantity+=C.Quantity||0,R.set(Q,F)}}),S=Array.from(R).sort(([C],[E])=>C.localeCompare(E)).map(([C,E])=>({date:`${C.substring(5,7)}/${C.substring(8,10)}`,dollarVolume:E.price,unitsSold:E.quantity}))}else{const R=new Date,C=R.getFullYear(),E=R.getMonth(),A=R.getDate(),M=`${C}-${(E+1).toString().padStart(2,"0")}`,I=Array.from({length:12},(q,z)=>{const Q=new Date(C,E-(11-z),1);return`${Q.getFullYear()}-${(Q.getMonth()+1).toString().padStart(2,"0")}`}),j=Object.fromEntries(I.map(q=>[q,{price:0,quantity:0}]));if(t.forEach(q=>{const z=String(q.Day??0);if(z.length!==8)return;const Q=`${z.substring(0,4)}-${z.substring(4,6)}`;j[Q]&&(j[Q].price+=q.ExtendedPrice??0,j[Q].quantity+=q.Quantity??0)}),S=I.map(q=>{const z=j[q],[Q,F]=q.split("-").map(Number);return{date:new Date(Q,F-1).toLocaleString("default",{month:"short",year:"numeric"}),dollarVolume:z.price,unitsSold:z.quantity}}),g){const q=j[M];if(q&&q.price>0&&A>0){const z=new Date(C,E+1,0).getDate();if(A<z){const Q=q.price/A,F=q.quantity/A,V=Q*z,te=F*z,ne=S[S.length-1];ne&&(ne.dollarVolume=V,ne.unitsSold=te)}}}}f(S)},[t,e,g,o]),o?jsxRuntime.jsx("div",{style:{height:n},children:jsxRuntime.jsx(Skeleton,{className:"h-full w-full rounded-md"})}):d.length===0?jsxRuntime.jsx("div",{style:{height:n},className:"flex items-center justify-center text-muted-foreground",children:"No sales data available."}):jsxRuntime.jsxs(jsxRuntime.Fragment,{children:[jsxRuntime.jsx(AreaChart,{data:d,series:_,height:n,size:l}),l==="default"&&e==="month"&&jsxRuntime.jsxs("div",{className:"mt-4",children:[jsxRuntime.jsxs("div",{className:"flex items-center space-x-2",children:[jsxRuntime.jsx(Switch,{checked:g,onCheckedChange:b,id:"extrapolate-switch"}),jsxRuntime.jsx(Label$2,{htmlFor:"extrapolate-switch",children:"Extrapolate Current Month"})]}),g&&jsxRuntime.jsxs("p",{className:"mt-2 text-sm text-muted-foreground",children:["* Values for ",new Date().toLocaleString("default",{month:"long"})," are projected estimates."]})]})]})}function ManufacturerCard({manufacturer:t,link:e,linkNewTab:n=!0,actions:o,mainAction:l,loading:d=!1}){var S,R,C;if(d||!t)return jsxRuntime.jsxs(Card,{className:"flex flex-col h-full",children:[jsxRuntime.jsxs(CardHeader,{className:"flex flex-row items-start justify-between space-y-0 pb-2 pt-4",children:[jsxRuntime.jsxs("div",{className:"flex items-center gap-3",children:[jsxRuntime.jsx(Skeleton,{className:"h-12 w-12 rounded-md"}),jsxRuntime.jsxs("div",{children:[jsxRuntime.jsx(Skeleton,{className:"h-3 w-24 mb-2"}),jsxRuntime.jsx(Skeleton,{className:"h-5 w-40 mb-1"}),jsxRuntime.jsx(Skeleton,{className:"h-4 w-32 mb-1"}),jsxRuntime.jsx(Skeleton,{className:"h-4 w-48"})]})]}),jsxRuntime.jsx(Skeleton,{className:"h-16 w-24"})]}),jsxRuntime.jsx(CardContent,{className:"pb-2 flex-grow",children:jsxRuntime.jsxs("div",{className:"flex flex-col space-y-2",children:[jsxRuntime.jsxs("div",{className:"flex flex-wrap gap-2",children:[jsxRuntime.jsx(Skeleton,{className:"h-5 w-16 rounded-full"}),jsxRuntime.jsx(Skeleton,{className:"h-5 w-20 rounded-full"}),jsxRuntime.jsx(Skeleton,{className:"h-5 w-14 rounded-full"})]}),jsxRuntime.jsxs("div",{className:"space-y-1 pt-2",children:[jsxRuntime.jsxs("div",{className:"flex items-center gap-2",children:[jsxRuntime.jsx(Skeleton,{className:"h-4 w-4"}),jsxRuntime.jsx(Skeleton,{className:"h-4 w-32"})]}),jsxRuntime.jsxs("div",{className:"flex items-center gap-2",children:[jsxRuntime.jsx(Skeleton,{className:"h-4 w-4"}),jsxRuntime.jsx(Skeleton,{className:"h-4 w-40"})]}),jsxRuntime.jsxs("div",{className:"flex items-center gap-2",children:[jsxRuntime.jsx(Skeleton,{className:"h-4 w-4"}),jsxRuntime.jsx(Skeleton,{className:"h-4 w-36"})]})]})]})}),jsxRuntime.jsxs(CardFooter,{className:"flex justify-between pt-2 gap-2 mt-auto",children:[jsxRuntime.jsx(Skeleton,{className:"h-9 w-24"}),jsxRuntime.jsx(Skeleton,{className:"h-9 w-40"})]})]});const f=t.ManufacturerId||"N/A",g=[t.City,t.Province,t.Country].filter(Boolean),b=g.length>0?g.join(", "):"",_=((S=t.Tags)==null?void 0:S.split(",").map(E=>E.trim()).filter(Boolean))||[];return jsxRuntime.jsxs(Card,{className:"manufacturer-theme flex flex-col h-full",children:[jsxRuntime.jsx(reactRouterDom.Link,{to:e??"#",target:e&&n?"_blank":"_self",children:jsxRuntime.jsxs(CardHeader,{className:"flex flex-row items-start justify-between space-y-0 pb-2 pt-4",children:[jsxRuntime.jsxs("div",{className:"flex items-center gap-3",children:[jsxRuntime.jsx("div",{className:"h-12 w-12 overflow-hidden rounded-md",children:jsxRuntime.jsx(PartnerLogo,{id:t.ManufacturerId,width:48,height:48})}),jsxRuntime.jsxs("div",{children:[jsxRuntime.jsxs("div",{className:"flex items-center gap-2",children:[jsxRuntime.jsx("span",{className:"text-xs text-primary",children:"Manufacturer"}),jsxRuntime.jsx("span",{className:"text-xs text-muted-foreground",children:"|"}),jsxRuntime.jsx("span",{className:"text-xs text-muted-foreground",children:f})]}),jsxRuntime.jsx("h3",{className:"font-semibold",children:t.PublicName||"N/A"}),t.Name&&jsxRuntime.jsx("p",{className:"text-sm text-muted-foreground",children:t.Name}),b&&jsxRuntime.jsx("p",{className:"text-sm text-muted-foreground",children:b})]})]}),jsxRuntime.jsx("div",{className:"flex flex-col items-end gap-2",children:t.SalesStatistics&&t.SalesStatistics.length>0&&jsxRuntime.jsx("div",{className:"h-16 w-24",children:jsxRuntime.jsx(SalesChart,{statistics:t.SalesStatistics,size:"mini"})})})]})}),jsxRuntime.jsx(CardContent,{className:"pb-2 flex-grow",children:jsxRuntime.jsxs("div",{className:"flex",children:[jsxRuntime.jsxs("div",{className:"flex flex-col flex-1 space-y-2",children:[(!!((R=t.Qualification)!=null&&R.QualificationId)&&((C=t.Qualification)==null?void 0:C.QualificationId)!=="Suspended"||!!t.OpenToWork||!!t.OnHold&&t.OnHold!==0||_.length>0)&&jsxRuntime.jsxs("div",{className:"flex flex-wrap gap-2",children:[jsxRuntime.jsx(QualificationBadge,{qualification:t.Qualification??{}}),!!t.OpenToWork&&jsxRuntime.jsxs(Badge,{variant:"success",children:[jsxRuntime.jsx(HardHat,{className:"h-3 w-3 mr-1"}),"Open To Work"]}),!!t.OnHold&&t.OnHold!==0&&jsxRuntime.jsx(Badge,{variant:"warning",children:"On Hold"}),_.map((E,A)=>jsxRuntime.jsx(Badge,{variant:"outline",children:E},A))]}),jsxRuntime.jsxs("div",{className:"space-y-1 pt-2",children:[t.Phone&&jsxRuntime.jsxs(reactRouterDom.Link,{to:`tel:${t.Phone}`,target:"_blank",className:"flex items-center gap-2 text-sm text-muted-foreground",children:[jsxRuntime.jsx(Phone,{className:"h-4 w-4"}),jsxRuntime.jsx("span",{children:t.Phone})]}),t.PublicEmail&&jsxRuntime.jsxs(reactRouterDom.Link,{to:`mailto:${t.PublicEmail}`,target:"_blank",className:"flex items-center gap-2 text-sm text-muted-foreground",children:[jsxRuntime.jsx(Mail,{className:"h-4 w-4"}),jsxRuntime.jsx("span",{children:t.PublicEmail})]}),t.Website&&jsxRuntime.jsxs(reactRouterDom.Link,{to:t.Website,target:"_blank",className:"flex items-center gap-2 text-sm text-muted-foreground",children:[jsxRuntime.jsx(Globe,{className:"h-4 w-4"}),jsxRuntime.jsx("span",{children:t.Website})]}),t.CurrencyCode&&jsxRuntime.jsxs("div",{className:"flex items-center gap-2 text-sm text-muted-foreground",children:[jsxRuntime.jsx(DollarSign,{className:"h-4 w-4"}),jsxRuntime.jsx("span",{children:t.CurrencyCode})]})]})]}),t.SalesData&&jsxRuntime.jsxs("div",{className:"border-l pl-2 ml-2 flex flex-col text-sm",children:[jsxRuntime.jsx("strong",{className:"",children:"YTD"}),jsxRuntime.jsx("p",{children:t.SalesData.SalesYearToDay?formatMoney(t.SalesData.SalesYearToDay):"—"}),jsxRuntime.jsx("strong",{className:"mt-2",children:"3 mo."}),jsxRuntime.jsx("p",{children:t.SalesData.SalesLast3Months?formatMoney(t.SalesData.SalesLast3Months):"—"}),jsxRuntime.jsx("strong",{className:"mt-2",children:"30 days"}),jsxRuntime.jsx("p",{children:t.SalesData.SalesLast30Days?formatMoney(t.SalesData.SalesLast30Days):"—"})]})]})}),(o||l||t.PublicResourcesLink)&&jsxRuntime.jsxs(CardFooter,{className:"flex pt-2 gap-2 justify-between mt-auto",children:[jsxRuntime.jsxs("div",{className:"flex items-center gap-2",children:[o&&o,t.PublicResourcesLink&&jsxRuntime.jsx(TooltipProvider,{children:jsxRuntime.jsxs(Tooltip$1,{children:[jsxRuntime.jsx(TooltipTrigger,{asChild:!0,children:jsxRuntime.jsx(reactRouterDom.Link,{to:t.PublicResourcesLink,target:"_blank",children:jsxRuntime.jsx(Button,{size:"icon",children:jsxRuntime.jsx(HardDriveDownload,{className:"h-4 w-4"})})})}),jsxRuntime.jsx(TooltipContent,{children:jsxRuntime.jsx("p",{children:"Public Resources Link"})})]})})]}),l&&jsxRuntime.jsx("div",{children:l})]})]})}function OrdersCard({applicationId:t,orders:e=null,loading:n=!1,title:o="Order Details"}){const l=React.useMemo(()=>[{accessorKey:"DocumentNumber",header:"Document Number",cell:({row:g})=>g.original.DocumentNumber?jsxRuntime.jsx(TooltipProvider,{delayDuration:100,children:jsxRuntime.jsxs(Tooltip$1,{children:[jsxRuntime.jsx(TooltipTrigger,{asChild:!0,children:jsxRuntime.jsx(reactRouterDom.Link,{to:`/${t}/Document/${g.original.DocumentNumber}`,className:"font-medium text-primary hover:underline",children:g.original.DocumentNumber})}),jsxRuntime.jsx(TooltipContent,{children:jsxRuntime.jsxs("p",{children:["View details for order ",g.original.DocumentNumber]})})]})}):"N/A",enableSorting:!0,enableFiltering:!0},{accessorKey:"DocumentDate",header:"Document Date",cell:({row:g})=>formatYYYYMMDDIntToDateString(g.original.DocumentDate),enableSorting:!0,enableFiltering:!1},{accessorKey:"OrderNumber",header:"Order Number",cell:({row:g})=>g.original.OrderNumber??"N/A",enableSorting:!0,enableFiltering:!0},{accessorKey:"PONumber",header:"PO Number",cell:({row:g})=>g.original.PONumber??"N/A",enableSorting:!0,enableFiltering:!0},{accessorKey:"WarehouseCode",header:"Warehouse",cell:({row:g})=>g.original.WarehouseCode??"N/A",enableSorting:!0,enableFiltering:!0},{accessorKey:"Quantity",header:"Quantity",cell:({row:g})=>g.original.Quantity??"N/A",enableSorting:!0,enableFiltering:!1},{accessorKey:"ShipToName",header:"Name",cell:({row:g})=>jsxRuntime.jsx("div",{className:"min-w-[150px]",children:g.original.ShipToName??"N/A"}),enableSorting:!0,enableFiltering:!0},{accessorKey:"UnitPrice",header:"Unit Price",cell:({row:g})=>g.original.UnitPrice?formatMoney(g.original.UnitPrice):"N/A",enableSorting:!0,enableFiltering:!1}],[]),d=React.useMemo(()=>{const g={};if(e){const b=Array.from(new Set(e.map(E=>E.WarehouseCode).filter(E=>E!=null)));g.WarehouseCode=b;const _=Array.from(new Set(e.map(E=>E.ShipToName).filter(E=>E!=null)));g.ShipToName=_;const S=Array.from(new Set(e.map(E=>E.DocumentNumber).filter(E=>E!=null)));g.DocumentNumber=S;const R=Array.from(new Set(e.map(E=>E.OrderNumber).filter(E=>E!=null)));g.OrderNumber=R;const C=Array.from(new Set(e.map(E=>E.PONumber).filter(E=>E!=null)));g.PONumber=C}return g},[e]),f=e||[];return n?jsxRuntime.jsxs(Card,{className:"w-full",children:[jsxRuntime.jsxs(CardHeader,{children:[" ",jsxRuntime.jsx(Skeleton,{className:"h-7 w-48"})," "]}),jsxRuntime.jsxs(CardContent,{className:"space-y-4",children:[jsxRuntime.jsx(Skeleton,{className:"h-12 w-full rounded-md border"}),jsxRuntime.jsx(Skeleton,{className:"h-10 w-full rounded-md border"}),jsxRuntime.jsx(Skeleton,{className:"h-10 w-full rounded-md border"}),jsxRuntime.jsx(Skeleton,{className:"h-10 w-full rounded-md border"}),jsxRuntime.jsxs("div",{className:"flex items-center justify-between pt-4",children:[jsxRuntime.jsx(Skeleton,{className:"h-9 w-[130px]"}),jsxRuntime.jsxs("div",{className:"flex items-center space-x-2",children:[jsxRuntime.jsx(Skeleton,{className:"h-9 w-20"}),jsxRuntime.jsx(Skeleton,{className:"h-9 w-24"}),jsxRuntime.jsx(Skeleton,{className:"h-9 w-9"}),jsxRuntime.jsx(Skeleton,{className:"h-9 w-9"})]})]})]})]}):jsxRuntime.jsxs(Card,{className:"w-full",children:[jsxRuntime.jsxs(CardHeader,{children:[" ",jsxRuntime.jsx(CardTitle,{className:"text-1xl font-bold",children:o})," "]}),jsxRuntime.jsx(CardContent,{children:jsxRuntime.jsx(DataTable,{columns:l,data:f,uniqueValues:d})})]})}function ResellerOverview({appID:t,reseller:e,readonly:n,userEmail:o,isSuperAdmin:l,withoutReports:d=!1}){const{data:f,isLoading:g,isError:b}=useGetV4PartnerByApplicationIdAccountResellerQuery({applicationId:t??"",withSpecification:!0},{skip:!!e}),[_,S]=React.useState({publicInfo:{hasUnsavedChanges:!1}}),R=React.useCallback(()=>n?!1:_.publicInfo.hasUnsavedChanges,[n,_]),C=React.useCallback((q,z)=>{S(Q=>{var F;return((F=Q[q])==null?void 0:F.hasUnsavedChanges)!==z.hasUnsavedChanges?{...Q,[q]:z}:Q})},[]),{NavigationGuardDialog:E}=useRouterNavigationGuard(R),A=e??f,M=!n||!!(A!=null&&A.Statement)&&(A.Statement.Total??0)>0,I=(A==null?void 0:A.QualifiedManufacturers)??[],j=(A==null?void 0:A.Qualifications)??[];return jsxRuntime.jsxs("div",{className:"@container",children:[b?jsxRuntime.jsx(Card,{className:"p-6",children:jsxRuntime.jsxs(Alert,{variant:"destructive",children:[jsxRuntime.jsx(CircleAlert,{className:"h-4 w-4"}),jsxRuntime.jsx(AlertTitle,{children:"Error"}),jsxRuntime.jsx(AlertDescription,{children:"There was an error loading your reseller information. Please try again later."})]})}):jsxRuntime.jsxs("div",{className:"space-y-6 mb-6",children:[jsxRuntime.jsx(SalesSummary,{fiscalYearMonthStart:(A==null?void 0:A.FiscalYearMonthStart)||1,salesData:A==null?void 0:A.SalesData,isLoading:g}),jsxRuntime.jsxs("div",{className:"grid grid-cols-1 @2xl:grid-cols-2 gap-6",children:[jsxRuntime.jsx(SalesChartCard,{statistics:(A==null?void 0:A.SalesStatistics)??[],loading:g}),jsxRuntime.jsx(OrderCategories,{openOrders:(A==null?void 0:A.ActiveOrderDetails)??[],isLoading:g}),M&&jsxRuntime.jsx(BillingCard,{appID:t,reseller:A||{},withoutReports:d,isLoading:g,userEmail:o}),jsxRuntime.jsx(PublicInfo,{reseller:A||{},appID:t??"",isLoading:g,readonly:n,onUnsavedChanges:q=>C("publicInfo",{hasUnsavedChanges:q})}),jsxRuntime.jsx(AccountTier,{isSuperAdmin:l,readonly:n,reseller:A||{},appID:t??"",isLoading:g})]}),g||I.length>0?jsxRuntime.jsxs(Card,{className:"w-full",children:[jsxRuntime.jsx(CardHeader,{children:jsxRuntime.jsx(CardTitle,{children:"Manufacturers you are qualified for"})}),jsxRuntime.jsx(CardContent,{children:jsxRuntime.jsx("div",{className:"grid @2xl:grid-cols-2 gap-4",children:g?Array.from({length:2}).map((q,z)=>jsxRuntime.jsx(ManufacturerCard,{loading:!0},z)):I.map(q=>jsxRuntime.jsx(ManufacturerCard,{manufacturer:q,link:`https://dashboard.randmar.io/${t}/Partner/${q.ManufacturerId}`},q.ManufacturerId))})})]}):jsxRuntime.jsx(ResellerQualificationsCard,{qualifications:j}),jsxRuntime.jsx(OpportunitiesTable,{applicationId:t,opportunities:A==null?void 0:A.Opportunities,loading:g}),jsxRuntime.jsx(OrdersCard,{applicationId:t,title:"Active Orders",orders:A==null?void 0:A.ActiveOrderDetails,loading:g}),jsxRuntime.jsx(OrdersCard,{applicationId:t,title:"Completed Orders",orders:A==null?void 0:A.CompletedOrderDetails,loading:g}),jsxRuntime.jsx(ReturnsTable,{applicationId:t,returns:A==null?void 0:A.Returns,loading:g}),!d&&jsxRuntime.jsx(ReportsSection,{appID:t,userEmail:o,isLoading:g})]}),jsxRuntime.jsx(E,{})]})}const alertVariants=cva("relative w-full rounded-lg border px-4 py-3 text-sm [&>svg+div]:translate-y-[-3px] [&>svg]:absolute [&>svg]:left-4 [&>svg]:top-4 [&>svg]:text-foreground [&>svg~*]:pl-7",{variants:{variant:{default:"bg-background text-foreground",destructive:"border-destructive/50 text-destructive dark:border-destructive [&>svg]:text-destructive",success:"border-green-500/50 bg-green-50 text-green-700 dark:border-green-500 dark:bg-green-950 dark:text-green-400 [&>svg]:text-green-500",warning:"border-yellow-500/50 bg-yellow-50 text-yellow-700 dark:border-yellow-500 dark:bg-yellow-950 dark:text-yellow-400 [&>svg]:text-yellow-500",info:"border-blue-500/50 bg-blue-50 text-blue-700 dark:border-blue-500 dark:bg-blue-950 dark:text-blue-400 [&>svg]:text-blue-500"}},defaultVariants:{variant:"default"}}),Alert=React__namespace.forwardRef(({className:t,variant:e,...n},o)=>jsxRuntime.jsx("div",{ref:o,role:"alert",className:cn(alertVariants({variant:e}),t),...n}));Alert.displayName="Alert";const AlertTitle=React__namespace.forwardRef(({className:t,...e},n)=>jsxRuntime.jsx("h5",{ref:n,className:cn("mb-1 font-medium leading-none tracking-tight",t),...e}));AlertTitle.displayName="AlertTitle";const AlertDescription=React__namespace.forwardRef(({className:t,...e},n)=>jsxRuntime.jsx("div",{ref:n,className:cn("text-sm [&_p]:leading-relaxed",t),...e}));AlertDescription.displayName="AlertDescription";/**
|
|
1085
1085
|
* table-core
|
|
1086
1086
|
*
|
|
1087
1087
|
* Copyright (c) TanStack
|
|
@@ -1324,6 +1324,6 @@ img.ProseMirror-separator {
|
|
|
1324
1324
|
.ProseMirror p {
|
|
1325
1325
|
margin-bottom: 0.5em;
|
|
1326
1326
|
}
|
|
1327
|
-
`;function RichTextEditor({id:t,name:e,value:n,onChange:o,placeholder:l,className:d,...f}){const[g,b]=React.useState(!1),_=React.useRef(null),S=React.useRef(null),R=useEditor({extensions:[StarterKit,Underline],content:n,editorProps:{attributes:{class:"prose prose-sm sm:prose dark:prose-invert focus:outline-none",id:t??"",name:e??""}},onUpdate:({editor:j})=>{const q=j.getHTML();o({target:{id:t,name:e,value:q}})}});React.useEffect(()=>{R&&n!==R.getHTML()&&R.commands.setContent(n)},[n,R]);const C=React.useCallback(j=>{if(R)if(R.chain().focus(),j==="paragraph")R.chain().setParagraph().run();else{const q=Number.parseInt(j.slice(1));R.chain().setHeading({level:q}).run()}},[R]),E=React.useCallback(j=>{if(R)switch(R.chain().focus(),j){case"bold":R.chain().toggleBold().run();break;case"italic":R.chain().toggleItalic().run();break;case"underline":R.chain().toggleUnderline().run();break;case"strike":R.chain().toggleStrike().run();break;case"bulletList":R.chain().toggleBulletList().run();break;case"orderedList":R.chain().toggleOrderedList().run();break}},[R]),A=React.useCallback(()=>{b(j=>!j)},[]),M=React.useCallback(j=>{const q=j.target.value;R&&R.commands.setContent(q),o({target:{id:t,name:e,value:q}})},[o,R,t,e]),I=React.useCallback(()=>{!g&&R&&R.commands.focus()},[g,R]);return R?jsxRuntime.jsxs("div",{ref:S,className:cn("border border-input rounded-md overflow-hidden focus-within:outline-hidden focus-within:ring-1 focus-within:ring-ring",d),onClick:I,...f,children:[jsxRuntime.jsx("style",{children:editorStyles}),jsxRuntime.jsxs("div",{className:"flex flex-wrap items-center p-2 border-b border-input gap-2 bg-background",children:[jsxRuntime.jsxs(Select,{onValueChange:C,disabled:g,children:[jsxRuntime.jsx(SelectTrigger,{className:"w-[160px]",children:jsxRuntime.jsx(SelectValue,{placeholder:"Format"})}),jsxRuntime.jsx(SelectContent,{children:formatOptions.map(j=>jsxRuntime.jsx(SelectItem,{value:j.value,children:j.label},j.value))})]}),["bold","italic","underline","strike","bulletList","orderedList"].map(j=>jsxRuntime.jsxs(Button,{type:"button",variant:"ghost",size:"sm",onClick:()=>E(j),className:R.isActive(j)?"bg-muted":"",disabled:g,children:[j==="bold"&&jsxRuntime.jsx(Bold$1,{className:"h-4 w-4"}),j==="italic"&&jsxRuntime.jsx(Italic$1,{className:"h-4 w-4"}),j==="underline"&&jsxRuntime.jsx(Underline$1,{className:"h-4 w-4"}),j==="strike"&&jsxRuntime.jsx(Strikethrough,{className:"h-4 w-4"}),j==="bulletList"&&jsxRuntime.jsx(List$1,{className:"h-4 w-4"}),j==="orderedList"&&jsxRuntime.jsx(ListOrdered,{className:"h-4 w-4"})]},j)),jsxRuntime.jsx(Button,{type:"button",variant:"ghost",size:"sm",onClick:A,className:g?"bg-muted":"",children:jsxRuntime.jsx(Code$1,{className:"h-4 w-4"})})]}),jsxRuntime.jsx("div",{className:"p-3",children:g?jsxRuntime.jsx(Textarea,{ref:_,id:t,name:e,value:R.getHTML(),onChange:M,className:cn("min-h-[150px] font-mono text-sm resize-none border-0 focus-visible:ring-0 focus-visible:ring-offset-0",d),placeholder:l}):jsxRuntime.jsx(EditorContent,{editor:R})})]}):null}function ReceiptsTable({receipts:t=null,loading:e=!1}){const n=React.useMemo(()=>[{accessorKey:"Location",header:"Location",cell:({row:d})=>jsxRuntime.jsx("div",{className:"min-w-[150px]",children:d.original.Location??"N/A"}),enableSorting:!0,enableFiltering:!0},{accessorKey:"ReceiptDate",header:"Date",cell:({row:d})=>formatYYYYMMDDIntToDateString(d.original.ReceiptDate),enableSorting:!0,enableFiltering:!0},{accessorKey:"Quantity",header:"Quantity",cell:({row:d})=>d.original.Quantity??"N/A",enableSorting:!0,enableFiltering:!0}],[]),o=React.useMemo(()=>{const d={};if(t){const f=Array.from(new Set(t.map(b=>b.Location).filter(b=>b!=null)));d.Location=f;const g=Array.from(new Set(t.map(b=>formatYYYYMMDDIntToDateString(b.ReceiptDate)).filter(b=>b!=="N/A"&&b!=="Invalid Date"))).sort((b,_)=>new Date(_).getTime()-new Date(b).getTime());d.ReceiptDate=g}return d},[t]),l=t||[];return jsxRuntime.jsx(DataTable,{columns:n,data:l,uniqueValues:o,loading:e,tableClass:"bg-card text-card-foreground"})}const formatDate$1=t=>{if(!t)return"N/A";try{const e=new Date(t);return isNaN(e.getTime())?"Invalid Date":e.toLocaleDateString(void 0,{year:"numeric",month:"short",day:"numeric"})}catch{return"Invalid Date"}},getStatusVariant=t=>{const e=(t==null?void 0:t.toLowerCase())||"";return e.includes("accepted")?"success":e.includes("error")||e.includes("rejected")?"destructive":"neutral"};function ReturnsTable({applicationId:t,returns:e=null,loading:n=!1}){const o=React.useMemo(()=>[{accessorKey:"ReturnNumber1",header:"RMA Number",cell:({row:f})=>{const g=f.original.ReturnNumber1||f.original.ReturnNumber;return g?jsxRuntime.jsx(TooltipProvider,{delayDuration:100,children:jsxRuntime.jsxs(Tooltip$1,{children:[jsxRuntime.jsx(TooltipTrigger,{asChild:!0,children:jsxRuntime.jsx(reactRouterDom.Link,{to:`/${t}/Return/${g}`,className:"font-medium text-primary hover:underline",children:g})}),jsxRuntime.jsx(TooltipContent,{children:jsxRuntime.jsxs("p",{children:["View details for return ",g]})})]})}):"N/A"},enableSorting:!0,enableFiltering:!0},{accessorKey:"RequestDate",header:"Request Date",cell:({row:f})=>formatDate$1(f.original.RequestDate),enableSorting:!0},{accessorKey:"InvoiceNumber",header:"Invoice Number",cell:({row:f})=>{const g=f.original.InvoiceNumber;return g?jsxRuntime.jsx(TooltipProvider,{delayDuration:100,children:jsxRuntime.jsxs(Tooltip$1,{children:[jsxRuntime.jsx(TooltipTrigger,{asChild:!0,children:jsxRuntime.jsx(reactRouterDom.Link,{to:`/${t}/Document/${g}`,className:"text-blue-600 hover:underline dark:text-blue-400",children:g})}),jsxRuntime.jsx(TooltipContent,{children:jsxRuntime.jsxs("p",{children:["View details for invoice ",g]})})]})}):"N/A"},enableSorting:!0,enableFiltering:!0},{accessorKey:"Quantity",header:"Quantity",cell:({row:f})=>f.original.Quantity??"0",enableSorting:!0},{accessorKey:"ReasonForReturn",header:"Return Reason",cell:({row:f})=>jsxRuntime.jsx("div",{className:"min-w-[150px]",children:f.original.ReasonForReturn??"—"}),enableSorting:!0,enableFiltering:!0},{accessorKey:"Status",header:"Status",cell:({row:f})=>{const g=f.original.Status,b=getStatusVariant(g);let _="border-gray-400 bg-gray-100 text-gray-600 dark:border-gray-600 dark:bg-gray-800/50 dark:text-gray-400";return b==="success"?_="border-green-500 bg-green-100 text-green-700 dark:border-green-600 dark:bg-green-900/50 dark:text-green-400":b==="destructive"&&(_="border-red-500 bg-red-100 text-red-700 dark:border-red-600 dark:bg-red-900/50 dark:text-red-400"),g?jsxRuntime.jsx(Badge,{variant:"outline",className:`${_} font-medium`,children:g}):"—"},enableSorting:!0,enableFiltering:!0},{accessorKey:"WarehouseLocation",header:"Warehouse",cell:({row:f})=>f.original.WarehouseLocation??"—",enableSorting:!0,enableFiltering:!0},{accessorKey:"LastUpdatedDate",header:"Last Update",cell:({row:f})=>formatDate$1(f.original.LastUpdatedDate)!=="N/A"?formatDate$1(f.original.LastUpdatedDate):"—",enableSorting:!0}],[t]),l=React.useMemo(()=>{const f={};if(e){const g=Array.from(new Set(e.map(S=>S.Status).filter(Boolean)));f.Status=g;const b=Array.from(new Set(e.map(S=>S.ReasonForReturn).filter(Boolean)));f.ReasonForReturn=b;const _=Array.from(new Set(e.map(S=>S.WarehouseLocation).filter(Boolean)));f.WarehouseLocation=_}return f},[e]),d=React.useMemo(()=>e?[...e].sort((g,b)=>(b.ReturnNumber1||b.ReturnNumber||"").localeCompare(g.ReturnNumber1||g.ReturnNumber||"")):[],[e]);return n?jsxRuntime.jsxs(Card,{className:"w-full",children:[jsxRuntime.jsx(CardHeader,{children:jsxRuntime.jsx(Skeleton,{className:"h-7 w-48"})}),jsxRuntime.jsxs(CardContent,{className:"space-y-4",children:[jsxRuntime.jsx(Skeleton,{className:"h-12 w-full rounded-md border"}),jsxRuntime.jsx(Skeleton,{className:"h-48 w-full rounded-md border"}),jsxRuntime.jsxs("div",{className:"flex items-center justify-between pt-4",children:[jsxRuntime.jsx(Skeleton,{className:"h-9 w-[130px]"}),jsxRuntime.jsxs("div",{className:"flex items-center space-x-2",children:[jsxRuntime.jsx(Skeleton,{className:"h-9 w-20"}),jsxRuntime.jsx(Skeleton,{className:"h-9 w-24"}),jsxRuntime.jsx(Skeleton,{className:"h-9 w-9"}),jsxRuntime.jsx(Skeleton,{className:"h-9 w-9"})]})]})]})]}):jsxRuntime.jsxs(Card,{className:"w-full",children:[jsxRuntime.jsx(CardHeader,{children:jsxRuntime.jsx(CardTitle,{className:"text-1xl font-bold",children:"Returns"})}),jsxRuntime.jsx(CardContent,{children:jsxRuntime.jsx(DataTable,{columns:o,data:d,uniqueValues:l})})]})}function InvoicesTable({applicationId:t,invoices:e=null,loading:n=!1}){const o=React.useMemo(()=>[{accessorKey:"InvoiceNumber",header:"Number",cell:({row:f})=>f.original.InvoiceNumber?jsxRuntime.jsx(TooltipProvider,{delayDuration:100,children:jsxRuntime.jsxs(Tooltip$1,{children:[jsxRuntime.jsx(TooltipTrigger,{asChild:!0,children:jsxRuntime.jsx(reactRouterDom.Link,{to:`/${t}/Document/${f.original.InvoiceNumber}`,className:"font-medium text-primary hover:underline",children:f.original.InvoiceNumber})}),jsxRuntime.jsx(TooltipContent,{children:jsxRuntime.jsxs("p",{children:["View details for invoice ",f.original.InvoiceNumber]})})]})}):"—",enableSorting:!0,enableFiltering:!0},{accessorKey:"InvoiceDate",header:"Date",cell:({row:f})=>formatYYYYMMDDIntToDateString(f.original.InvoiceDate),enableSorting:!0,enableFiltering:!0},{accessorKey:"OrderNumber",header:"Order Number",cell:({row:f})=>f.original.OrderNumber?jsxRuntime.jsx(TooltipProvider,{delayDuration:100,children:jsxRuntime.jsxs(Tooltip$1,{children:[jsxRuntime.jsx(TooltipTrigger,{asChild:!0,children:jsxRuntime.jsx(reactRouterDom.Link,{to:`/${t}/GeneralDocument/${f.original.OrderNumber}`,className:"font-medium text-primary hover:underline",children:f.original.OrderNumber})}),jsxRuntime.jsx(TooltipContent,{children:jsxRuntime.jsxs("p",{children:["View details for order ",f.original.OrderNumber]})})]})}):"—",enableSorting:!0,enableFiltering:!0},{accessorKey:"PONumber",header:"PO Number",cell:({row:f})=>f.original.PONumber&&f.original.PONumber.trim().length>0?f.original.PONumber:"—",enableSorting:!0,enableFiltering:!0},{accessorKey:"ShipToName",header:"Ship To Name",cell:({row:f})=>f.original.ShipToName??"—",enableSorting:!0,enableFiltering:!0},{accessorKey:"QuantityOrdered",header:"Quantity Ordered",cell:({row:f})=>f.original.QuantityOrdered??0,enableSorting:!0,enableFiltering:!0},{accessorKey:"UnitPrice",header:"Unit Price",cell:({row:f})=>formatMoney(f.original.UnitPrice??0),enableSorting:!0,enableFiltering:!0},{accessorKey:"Location",header:"Location",cell:({row:f})=>f.original.Location??"—",enableSorting:!0,enableFiltering:!0}],[t]),l=React.useMemo(()=>{const f={};if(e){const g=Array.from(new Set(e.map(C=>C.ShipToName).filter(C=>C!=null)));f.ShipToName=g;const b=Array.from(new Set(e.map(C=>C.InvoiceNumber).filter(C=>C!=null)));f.InvoiceNumber=b;const _=Array.from(new Set(e.map(C=>C.OrderNumber).filter(C=>C!=null)));f.OrderNumber=_;const S=Array.from(new Set(e.map(C=>C.PONumber).filter(C=>C!=null)));f.PONumber=S;const R=Array.from(new Set(e.map(C=>C.Location).filter(C=>C!=null)));f.Location=R}return f},[e]),d=e||[];return jsxRuntime.jsx(DataTable,{columns:o,data:d,uniqueValues:l,loading:n,tableClass:"bg-card text-card-foreground"})}function ProductOverviewPage({applicationId:t,sku:e,productDefaultOpportunityNumber:n="",productOnAddToCart:o,productAddingToCart:l=!1,productShopifyHostname:d,productCustomAction:f=jsxRuntime.jsx(jsxRuntime.Fragment,{})}){var I,j,q,z,Q,F,V,te,ne,se,ge,oe;const{data:g,isLoading:b}=useGetV4PartnerByRouteApplicationIdProductAndRandmarSkuQuery({routeApplicationId:t,randmarSku:e,withSpecification:!1},{skip:!t||!e}),{data:_,isLoading:S}=useGetV4PartnerByRouteApplicationIdProductAndRandmarSkuQuery({routeApplicationId:t,randmarSku:e,withSpecification:!0},{skip:!g}),[R,C]=React.useState("stats"),[E,A]=React.useState(!1);React.useEffect(()=>{var Ne,Oe,Fe,ze,$e,Be,qe,Ge;if(S||!_){A(!1);return}const Ae={stats:(((Ne=_==null?void 0:_.SalesStatistics)==null?void 0:Ne.length)??0)<=0,inventory:(((Fe=(Oe=_==null?void 0:_.Distribution)==null?void 0:Oe.Inventory)==null?void 0:Fe.length)??0)<=0,opportunities:(((ze=_==null?void 0:_.Opportunities)==null?void 0:ze.length)??0)<=0,orders:((($e=_==null?void 0:_.ActiveOrderDetails)==null?void 0:$e.length)??0)<=0&&(((Be=_==null?void 0:_.Returns)==null?void 0:Be.length)??0)<=0,invoices:(((qe=_==null?void 0:_.CompletedOrderDetails)==null?void 0:qe.length)??0)<=0,warehouse:(((Ge=_==null?void 0:_.Receipts)==null?void 0:Ge.length)??0)<=0},je=Object.values(Ae).some(He=>!He);if(A(je),je&&Ae[R]){const He=Object.keys(Ae).find(Ze=>!Ae[Ze]);He&&C(He)}},[S,_,R]);const M=(g==null?void 0:g.ManufacturerId)!==t;return console.log("readonly",M),jsxRuntime.jsxs("div",{className:"@container",children:[jsxRuntime.jsxs("div",{className:"grid gap-4 grid-cols-1 @sm:grid-cols-2 @md:grid-cols-3",children:[jsxRuntime.jsx("div",{className:"@md:col-span-2",children:jsxRuntime.jsx(ProductCard,{applicationId:t,product:_||g,defaultOpportunityNumber:n,onAddToCart:o,addingToCart:l,shopifyHostname:d,customAction:f})}),jsxRuntime.jsxs(Card,{className:"flex flex-col",children:[jsxRuntime.jsx(CardHeader,{children:jsxRuntime.jsxs(CardTitle,{children:[jsxRuntime.jsx(Info,{className:"h-5 w-5 inline mr-2"})," Additionnal information"]})}),jsxRuntime.jsx(CardContent,{className:"basis-0 mb-6 grow overflow-y-auto",children:b?jsxRuntime.jsxs(jsxRuntime.Fragment,{children:[jsxRuntime.jsxs("div",{className:"flex justify-between",children:[jsxRuntime.jsx(Skeleton,{className:"h-5 w-32"}),jsxRuntime.jsx(Skeleton,{className:"h-5 w-24"})]}),jsxRuntime.jsxs("div",{className:"flex justify-between mt-2",children:[jsxRuntime.jsx(Skeleton,{className:"h-5 w-32"}),jsxRuntime.jsx(Skeleton,{className:"h-5 w-24"})]}),jsxRuntime.jsxs("div",{className:"flex justify-between mt-2",children:[jsxRuntime.jsx(Skeleton,{className:"h-5 w-32"}),jsxRuntime.jsx(Skeleton,{className:"h-5 w-24"})]}),jsxRuntime.jsxs("div",{className:"flex justify-between mt-2",children:[jsxRuntime.jsx(Skeleton,{className:"h-5 w-32"}),jsxRuntime.jsx(Skeleton,{className:"h-5 w-24"})]}),jsxRuntime.jsx(Skeleton,{className:"h-1 w-full my-6"}),jsxRuntime.jsx(Skeleton,{className:"h-5 w-24"}),jsxRuntime.jsx(Skeleton,{className:"h-4 w-full mt-2"}),jsxRuntime.jsx(Skeleton,{className:"h-4 w-full mt-1"})]}):jsxRuntime.jsxs(jsxRuntime.Fragment,{children:[jsxRuntime.jsxs("div",{className:"flex justify-between",children:[jsxRuntime.jsx("span",{className:"text-muted-foreground",children:"Cateory Name"}),jsxRuntime.jsx("span",{className:"font-medium",children:(g==null?void 0:g.ProductType)||"N/A"})]}),jsxRuntime.jsxs("div",{className:"flex justify-between mt-2",children:[jsxRuntime.jsx("span",{className:"text-muted-foreground",children:"Master Carton"}),jsxRuntime.jsx("span",{className:"font-medium",children:(g==null?void 0:g.MasterCarton)||"N/A"})]}),jsxRuntime.jsxs("div",{className:"flex justify-between mt-2",children:[jsxRuntime.jsx("span",{className:"text-muted-foreground",children:"Skid Quantity"}),jsxRuntime.jsx("span",{className:"font-medium",children:(g==null?void 0:g.SkidQuantity)||"N/A"})]}),jsxRuntime.jsxs("div",{className:"flex justify-between mt-2",children:[jsxRuntime.jsx("span",{className:"text-muted-foreground",children:"Automatic Reorder"}),jsxRuntime.jsx("span",{className:"font-medium",children:g!=null&&g.AutoUpdate?"Yes":"No"})]}),((g==null?void 0:g.VoiceoverCaption)||(g==null?void 0:g.BodyHTML))&&jsxRuntime.jsxs(jsxRuntime.Fragment,{children:[jsxRuntime.jsx("hr",{className:"my-6"}),jsxRuntime.jsx("div",{className:"text-muted-foreground mb-2",children:"Description"}),(g==null?void 0:g.VoiceoverCaption)&&jsxRuntime.jsx("div",{children:g==null?void 0:g.VoiceoverCaption}),(g==null?void 0:g.BodyHTML)&&jsxRuntime.jsx("div",{className:"prose prose-sm max-w-none",dangerouslySetInnerHTML:{__html:(g==null?void 0:g.BodyHTML)??""}})]})]})})]})]}),jsxRuntime.jsx("div",{className:"my-4",children:b||S?jsxRuntime.jsx("div",{className:"mx-auto flex justify-center items-center h-32",children:jsxRuntime.jsx(LoaderCircle,{className:"h-8 w-8 animate-spin text-primary"})}):E&&jsxRuntime.jsxs(Tabs,{value:R,onValueChange:C,children:[jsxRuntime.jsxs(TabsList,{className:"inline-flex h-auto items-center justify-center rounded-none border-b bg-transparent p-0",children:[jsxRuntime.jsx(TabsTrigger,{value:"stats",className:"relative h-12 rounded-none border-b-2 border-b-transparent bg-transparent px-4 pb-3 pt-2 text-sm font-medium text-muted-foreground shadow-none transition-none hover:text-foreground data-[state=active]:border-b-primary data-[state=active]:text-foreground data-[state=active]:shadow-none cursor-pointer",disabled:(((I=_==null?void 0:_.SalesStatistics)==null?void 0:I.length)??0)<=0,children:"Statistics"}),jsxRuntime.jsx(TabsTrigger,{value:"inventory",className:"relative h-12 rounded-none border-b-2 border-b-transparent bg-transparent px-4 pb-3 pt-2 text-sm font-medium text-muted-foreground shadow-none transition-none hover:text-foreground data-[state=active]:border-b-primary data-[state=active]:text-foreground data-[state=active]:shadow-none cursor-pointer",disabled:(((q=(j=_==null?void 0:_.Distribution)==null?void 0:j.Inventory)==null?void 0:q.length)??0)<=0,children:"Inventory"}),jsxRuntime.jsx(TabsTrigger,{value:"opportunities",className:"relative h-12 rounded-none border-b-2 border-b-transparent bg-transparent px-4 pb-3 pt-2 text-sm font-medium text-muted-foreground shadow-none transition-none hover:text-foreground data-[state=active]:border-b-primary data-[state=active]:text-foreground data-[state=active]:shadow-none cursor-pointer",disabled:(((z=_==null?void 0:_.Opportunities)==null?void 0:z.length)??0)<=0,children:"Opportunities"}),jsxRuntime.jsx(TabsTrigger,{value:"orders",className:"relative h-12 rounded-none border-b-2 border-b-transparent bg-transparent px-4 pb-3 pt-2 text-sm font-medium text-muted-foreground shadow-none transition-none hover:text-foreground data-[state=active]:border-b-primary data-[state=active]:text-foreground data-[state=active]:shadow-none cursor-pointer",disabled:(((Q=_==null?void 0:_.ActiveOrderDetails)==null?void 0:Q.length)??0)<=0&&(((F=_==null?void 0:_.Returns)==null?void 0:F.length)??0)<=0,children:"Orders"}),jsxRuntime.jsx(TabsTrigger,{value:"invoices",className:"relative h-12 rounded-none border-b-2 border-b-transparent bg-transparent px-4 pb-3 pt-2 text-sm font-medium text-muted-foreground shadow-none transition-none hover:text-foreground data-[state=active]:border-b-primary data-[state=active]:text-foreground data-[state=active]:shadow-none cursor-pointer",disabled:(((V=_==null?void 0:_.Invoices)==null?void 0:V.length)??0)<=0,children:"Invoices"}),jsxRuntime.jsx(TabsTrigger,{value:"warehouse",className:"relative h-12 rounded-none border-b-2 border-b-transparent bg-transparent px-4 pb-3 pt-2 text-sm font-medium text-muted-foreground shadow-none transition-none hover:text-foreground data-[state=active]:border-b-primary data-[state=active]:text-foreground data-[state=active]:shadow-none cursor-pointer",disabled:(((te=_==null?void 0:_.Receipts)==null?void 0:te.length)??0)<=0,children:"Latest Warehouse Receiving"})]}),jsxRuntime.jsx(TabsContent,{value:"stats",children:jsxRuntime.jsx("div",{className:"mt-4",children:jsxRuntime.jsx(SalesChartCard,{statistics:(_==null?void 0:_.SalesStatistics)??[],loading:S})})}),jsxRuntime.jsx(TabsContent,{value:"inventory",children:jsxRuntime.jsx("div",{className:"mt-4",children:jsxRuntime.jsx(ProductInventoryGrid,{inventory:((ne=_==null?void 0:_.Distribution)==null?void 0:ne.Inventory)??[],className:"bg-card text-card-foreground"})})}),jsxRuntime.jsx(TabsContent,{value:"opportunities",children:jsxRuntime.jsx("div",{className:"mt-4",children:jsxRuntime.jsx(OpportunitiesTable,{applicationId:t,opportunities:g==null?void 0:g.Opportunities,loading:b})})}),jsxRuntime.jsxs(TabsContent,{value:"orders",children:[(((se=_==null?void 0:_.ActiveOrderDetails)==null?void 0:se.length)??0)>0&&jsxRuntime.jsx("div",{className:"mt-4",children:jsxRuntime.jsx(OrdersCard,{applicationId:t,title:"Open Orders",orders:_==null?void 0:_.ActiveOrderDetails,loading:S})}),(((ge=_==null?void 0:_.Returns)==null?void 0:ge.length)??0)>0&&jsxRuntime.jsx("div",{className:"mt-4",children:jsxRuntime.jsx(ReturnsTable,{applicationId:t,returns:_==null?void 0:_.Returns,loading:S})})]}),jsxRuntime.jsx(TabsContent,{value:"invoices",children:(((oe=_==null?void 0:_.Invoices)==null?void 0:oe.length)??0)>0&&jsxRuntime.jsx("div",{className:"mt-4",children:jsxRuntime.jsx(InvoicesTable,{applicationId:t,invoices:_==null?void 0:_.Invoices,loading:S})})}),jsxRuntime.jsx(TabsContent,{value:"warehouse",children:jsxRuntime.jsx("div",{className:"mt-4",children:jsxRuntime.jsx(ReceiptsTable,{receipts:_==null?void 0:_.Receipts,loading:S})})})]})})]})}function AssistantChat(t){return jsxRuntime.jsx(Card,{className:"max-w-6xl",children:jsxRuntime.jsx(ChatLayout,{className:"h-[40em]",userId:t.userId,userName:t.userName,assistantOnly:!0,initialPrompt:t.initialPrompt})})}function getEndDateStatus(t){if(!t)return{text:"No End Date",variant:"neutral",daysRemaining:null};const e=new Date(t);if(isNaN(e.getTime()))return{text:"Invalid Date",variant:"neutral",daysRemaining:null};const n=new Date,o=new Date(e.getFullYear(),e.getMonth(),e.getDate()),l=new Date(n.getFullYear(),n.getMonth(),n.getDate()),d=o.getTime()-l.getTime(),f=Math.ceil(d/(1e3*60*60*24));return f<0?{text:`Ended ${Math.abs(f)}d ago`,variant:"destructive",daysRemaining:f}:f===0?{text:"Ends today",variant:"destructive",daysRemaining:f}:f<=7?{text:`Ends in ${f}d`,variant:"destructive",daysRemaining:f}:f<=30?{text:`Ends in ${f}d`,variant:"warning",daysRemaining:f}:{text:`Ends in ${f}d`,variant:"neutral",daysRemaining:f}}const formatDate=t=>{if(!t)return"N/A";try{const e=new Date(t);return isNaN(e.getTime())?"Invalid Date":e.toLocaleDateString(void 0,{year:"numeric",month:"short",day:"numeric"})}catch{return"Invalid Date"}};function OpportunitiesTable({applicationId:t,opportunities:e=null,loading:n=!1}){var te;const{toast:o}=useToast(),[l,d]=React.useState({}),[f,g]=React.useState(!1),[b,_]=React.useState(""),[S,R]=React.useState(null),{data:C}=useGetV4PartnerByApplicationIdAccountQuery({applicationId:t},{skip:!t}),E=React.useCallback((ne,se,ge)=>{d(oe=>({...oe,[ne]:{...oe[ne],[se]:ge}}))},[]),[A]=usePutV4ResellerByRouteResellerIdOpportunityAndManufacturerIdDefaultMutation(),M=React.useCallback(async ne=>{if(!(C!=null&&C.IsReseller))return;if(!ne.BidNumber){o({title:"Error",description:"Bid Number is missing, cannot set default.",variant:"destructive"});return}const se=ne.BidNumber;E(se,"isSettingDefault",!0),A({routeResellerId:t,manufacturerId:ne.ManufacturerId??"",opportunityNumber:se}).unwrap().then(()=>{o({title:"Success",description:`Opportunity "${ne.OpportunityName||ne.Opportunity||se}" was successfully set as default.`,variant:"success"})}).catch(ge=>{var oe;console.error("Set as default error:",ge),o({title:"Error",description:((oe=ge.data)==null?void 0:oe.message)||ge.message||"An error occurred while setting this opportunity as default.",variant:"destructive"})}).finally(()=>{E(se,"isSettingDefault",!1)})},[t,A,o,E]),[I]=usePostV4ResellerByRouteResellerIdOpportunityAndManufacturerIdBidNumberEmailMutation(),j=React.useCallback(ne=>{if(C!=null&&C.IsReseller){if(!ne.BidNumber){o({title:"Error",description:"Bid Number is missing, cannot prepare report.",variant:"destructive"});return}R(ne),_(""),g(!0)}},[o]),q=React.useCallback(async()=>{if(!(C!=null&&C.IsReseller))return;if(!S||!S.BidNumber){o({title:"Error",description:"No opportunity selected or Bid Number is missing.",variant:"destructive"});return}if(!b.trim()||!/\S+@\S+\.\S+/.test(b)){o({title:"Validation Error",description:"Please enter a valid email address.",variant:"destructive"});return}const ne=S.BidNumber;E(ne,"isSendingReport",!0),I({routeResellerId:t,manufacturerId:S.ManufacturerId??"",bidNumber:ne,emailAddress:b}).unwrap().then(()=>{o({title:"Success",description:`A report for "${S.OpportunityName||S.Opportunity||ne}" was successfully sent to ${b}.`,variant:"success"}),g(!1)}).catch(se=>{var ge;console.error("Send report by email error:",se),o({title:"Error",description:((ge=se.data)==null?void 0:ge.message)||se.message||"An error occurred while sending the report by email.",variant:"destructive"})}).finally(()=>{E(ne,"isSendingReport",!1),f||(R(null),_(""))})},[S,b,t,I,o,E,g]),z=React.useMemo(()=>[{accessorKey:"ManufacturerId",header:"Manuf.",cell:({row:ne})=>jsxRuntime.jsx("div",{className:"w-20 h-8",children:jsxRuntime.jsx(PartnerLogo,{id:ne.original.ManufacturerId,width:80,height:32})}),enableSorting:!0,enableFiltering:!0},{id:"opportunityDisplay",accessorFn:ne=>ne.OpportunityName||ne.Opportunity,header:"Opportunity",cell:({getValue:ne})=>jsxRuntime.jsx("div",{className:"min-w-[150px]",children:ne()??"N/A"}),enableSorting:!0,enableFiltering:!0},{accessorKey:"BidNumber",header:"Bid Number",cell:({row:ne})=>ne.original.BidNumber??"N/A",enableSorting:!0,enableFiltering:!0},{id:"statusInfo",header:"Status",cell:({row:ne})=>{const se=ne.original,ge=se.Active===!0,oe=getEndDateStatus(se.EndDate);let Ae="border-gray-400 bg-gray-100 text-gray-600 dark:border-gray-600 dark:bg-gray-800/50 dark:text-gray-400";return oe.variant==="destructive"?Ae="border-red-500 bg-red-100 text-red-700 dark:border-red-600 dark:bg-red-900/50 dark:text-red-400":oe.variant==="warning"&&(Ae="border-yellow-500 bg-yellow-100 text-yellow-700 dark:border-yellow-600 dark:bg-yellow-900/50 dark:text-yellow-400"),jsxRuntime.jsxs("div",{className:"flex items-center space-x-2 min-w-[200px]",children:[jsxRuntime.jsx(Badge,{variant:"outline",className:ge?"border-green-500 bg-green-100 text-green-700 dark:border-green-600 dark:bg-green-900/50 dark:text-green-400 font-medium":"border-gray-400 bg-gray-100 text-gray-600 dark:border-gray-600 dark:bg-gray-800/50 dark:text-gray-400 font-medium",children:ge?"Active":"Inactive"}),se.EndDate&&jsxRuntime.jsx(Badge,{variant:"outline",className:`${Ae} font-medium`,children:oe.text}),jsxRuntime.jsx(TooltipProvider,{delayDuration:100,children:jsxRuntime.jsxs(Tooltip$1,{children:[jsxRuntime.jsx(TooltipTrigger,{asChild:!0,children:jsxRuntime.jsx(Button,{variant:"ghost",size:"icon",className:"h-6 w-6 p-0 data-[state=delayed-open]:bg-accent data-[state=instant-open]:bg-accent",children:jsxRuntime.jsx(Info,{className:"h-4 w-4 text-muted-foreground"})})}),jsxRuntime.jsx(TooltipContent,{side:"top",align:"center",className:"bg-popover text-popover-foreground p-2 rounded shadow-lg",children:jsxRuntime.jsxs("div",{className:"text-sm space-y-1",children:[jsxRuntime.jsxs("p",{children:[jsxRuntime.jsx("strong",{children:"Start:"})," ",formatDate(se.StartDate)]}),jsxRuntime.jsxs("p",{children:[jsxRuntime.jsx("strong",{children:"End:"})," ",formatDate(se.EndDate)]}),jsxRuntime.jsxs("p",{children:[jsxRuntime.jsx("strong",{children:"Updated:"})," ",formatDate(se.LastUpdate)]})]})})]})})]})},enableFiltering:!1},{id:"actions",header:"Actions",cell:({row:ne})=>{var Oe,Fe;const se=ne.original;if(!se.BidNumber)return jsxRuntime.jsx("span",{className:"text-xs text-muted-foreground",children:"Actions unavailable"});const ge=se.BidNumber,oe=(Oe=l[ge])==null?void 0:Oe.isSettingDefault,Ae=(S==null?void 0:S.BidNumber)===ge&&((Fe=l[ge])==null?void 0:Fe.isSendingReport),je=oe||Ae,Ne=se.CanBeSetAsDefault===!0;return jsxRuntime.jsxs("div",{className:"flex space-x-2",children:[jsxRuntime.jsx(reactRouterDom.Link,{to:`/${t}/Opportunity/${se.ManufacturerId}/${se.BidNumber}`,children:jsxRuntime.jsxs(Button,{variant:"outline",size:"sm",className:"flex items-center",children:[jsxRuntime.jsx(Star,{className:"mr-2 h-4 w-4"})," View"]})}),(C==null?void 0:C.IsReseller)&&jsxRuntime.jsxs(jsxRuntime.Fragment,{children:[jsxRuntime.jsxs(Button,{variant:"outline",size:"sm",onClick:()=>M(se),disabled:je||!Ne,title:Ne?"Set as default":"This opportunity cannot be set as default",className:"flex items-center",children:[oe?jsxRuntime.jsx(LoaderCircle,{className:"mr-2 h-4 w-4 animate-spin"}):jsxRuntime.jsx(Star,{className:"mr-2 h-4 w-4"})," Set Default"]}),jsxRuntime.jsxs(Button,{variant:"outline",size:"sm",onClick:()=>j(se),disabled:je,title:"Send report by email",className:"flex items-center",children:[Ae?jsxRuntime.jsx(LoaderCircle,{className:"mr-2 h-4 w-4 animate-spin"}):jsxRuntime.jsx(Send,{className:"mr-2 h-4 w-4"})," Send Report"]})]})]})}}],[l,M,j,S]),Q=React.useMemo(()=>{const ne={};if(e){const se=Array.from(new Set(e.map(oe=>oe.ManufacturerId).filter(oe=>oe!=null)));ne.ManufacturerId=se;const ge=Array.from(new Set(e.map(oe=>oe.OpportunityName||oe.Opportunity).filter(oe=>oe!=null)));ne.opportunityDisplay=ge}return ne},[e]),F=e||[],V=S!=null&&S.BidNumber?(te=l[S.BidNumber])==null?void 0:te.isSendingReport:!1;return n?jsxRuntime.jsxs(Card,{className:"w-full",children:[jsxRuntime.jsxs(CardHeader,{children:[" ",jsxRuntime.jsx(Skeleton,{className:"h-7 w-48"})," "]}),jsxRuntime.jsxs(CardContent,{className:"space-y-4",children:[jsxRuntime.jsx(Skeleton,{className:"h-12 w-full rounded-md border"}),jsxRuntime.jsx(Skeleton,{className:"h-48 w-full rounded-md border"}),jsxRuntime.jsxs("div",{className:"flex items-center justify-between pt-4",children:[jsxRuntime.jsx(Skeleton,{className:"h-9 w-[130px]"}),jsxRuntime.jsxs("div",{className:"flex items-center space-x-2",children:[jsxRuntime.jsx(Skeleton,{className:"h-9 w-20"})," ",jsxRuntime.jsx(Skeleton,{className:"h-9 w-24"})," ",jsxRuntime.jsx(Skeleton,{className:"h-9 w-9"})," ",jsxRuntime.jsx(Skeleton,{className:"h-9 w-9"})]})]})]})]}):jsxRuntime.jsxs(jsxRuntime.Fragment,{children:[jsxRuntime.jsxs(Card,{className:"w-full",children:[jsxRuntime.jsxs(CardHeader,{children:[" ",jsxRuntime.jsx(CardTitle,{className:"text-1xl font-bold",children:"Opportunities"})," "]}),jsxRuntime.jsx(CardContent,{children:jsxRuntime.jsx(DataTable,{columns:z,data:F,uniqueValues:Q})})]}),jsxRuntime.jsx(Dialog,{open:f,onOpenChange:ne=>{g(ne),ne||(R(null),_(""))},children:jsxRuntime.jsxs(DialogContent,{className:"@sm:max-w-[425px]",children:[jsxRuntime.jsxs(DialogHeader,{children:[jsxRuntime.jsx(DialogTitle,{children:"Send Opportunity Report"}),jsxRuntime.jsxs(DialogDescription,{children:["Enter the email address to send the report for opportunity: ",jsxRuntime.jsx("br",{}),jsxRuntime.jsx("span",{className:"font-semibold",children:(S==null?void 0:S.OpportunityName)||(S==null?void 0:S.Opportunity)||"N/A"}),(S==null?void 0:S.BidNumber)&&jsxRuntime.jsxs("span",{className:"block text-sm text-muted-foreground",children:["Bid Number: ",S.BidNumber]})]})]}),jsxRuntime.jsx("div",{className:"grid gap-4 py-4",children:jsxRuntime.jsxs("div",{className:"grid grid-cols-4 items-center gap-4",children:[jsxRuntime.jsx(Label$2,{htmlFor:"email",className:"text-right",children:"Email"}),jsxRuntime.jsx(Input,{id:"email",type:"email",value:b,onChange:ne=>_(ne.target.value),placeholder:"recipient@example.com",className:"col-span-3",disabled:V})]})}),jsxRuntime.jsxs(DialogFooter,{children:[jsxRuntime.jsx(Button,{variant:"outline",onClick:()=>g(!1),disabled:V,children:"Cancel"}),jsxRuntime.jsxs(Button,{type:"submit",onClick:q,disabled:V,children:[V&&jsxRuntime.jsx(LoaderCircle,{className:"mr-2 h-4 w-4 animate-spin"})," Send Report"]})]})]})})]})}function useLoadScript(t){const[e,n]=React.useState(!0),[o,l]=React.useState(null),[d,f]=React.useState(!1),g=()=>{n(!1),f(!0)};return React.useEffect(()=>{if(!document){const R=new Error(`[ScriptLoadingError] document not defined when attempting to load ${t}`);l(R);return}const b=document.querySelector(`script[src="${t}"]`);if(b!=null&&b.dataset.loaded){g();return}const _=b||document.createElement("script");b||(_.src=t);const S=()=>{_.dataset.loaded="1",g()};_.addEventListener("load",S),_.addEventListener("error",R=>{console.error("Failed to load script:",t,R);const C=new Error(`[ScriptLoadingError] Failed to load script: ${t}`);l(C)}),b||document.head.append(_)},[]),{isLoading:e,error:o,isSuccess:d}}const isGoogleReady=t=>t&&t.charts,isGoogleChartsReady=(t,e)=>{const{controls:n,toolbarItems:o,getChartEditor:l}=t;return e&&e.charts&&e.visualization&&e.visualization.ChartWrapper&&e.visualization.Dashboard&&(!n||e.visualization.ChartWrapper)&&(!l||e.visualization.ChartEditor)&&(!o||e.visualization.drawToolbar)},getGoogleInstanceFromWindow=t=>window.google;function useLoadGoogleCharts(t){const{chartVersion:e="current",chartPackages:n=["corechart","controls"],chartLanguage:o="en",mapsApiKey:l}=t,[d,f]=React.useState(null),[g,b]=React.useState(null),[_,S]=React.useState(null),{isLoading:R,error:C,isSuccess:E}=useLoadScript(t.chartLoaderScriptUrl||"https://www.gstatic.com/charts/loader.js");return React.useEffect(()=>{if(!E)return;const A=getGoogleInstanceFromWindow();if(!isGoogleReady(A)){const M=new Error("[ScriptInitializationError] Script loaded but Google not attached to window.");b(M);return}if(isGoogleChartsReady(t,A)){f(A);return}A.charts.load(e,{packages:n,language:o,mapsApiKey:l}),A.charts.setOnLoadCallback(()=>{if(!isGoogleChartsReady(t,A)){const M=new Error("[GoogleChartsInitializationError] Google Charts not ready after load callback.");console.error(M),S(M);return}f(A)})},[E]),{error:C||g||_,isLoading:R,google:d}}const chartDefaultProps={legend_toggle:!1,options:{},legendToggle:!1,getChartWrapper:()=>{},spreadSheetQueryParameters:{headers:1,gid:1},rootProps:{},chartWrapperParams:{},chartLoaderScriptUrl:"https://www.gstatic.com/charts/loader.js"},GoogleChartControls=t=>{const{isReady:e,chartControls:n,filter:o}=t;return!e||!n||!(n!=null&&n.length)?null:React.createElement(React.Fragment,null,n.filter(l=>{let{controlProp:d,control:f}=l;return o?o({control:f,controlProp:d}):!0}).map(l=>{let{control:d}=l;return React.createElement("div",{key:d.getContainerId(),id:d.getContainerId()})}))};let uniqueID=0;const generateUniqueID=()=>(uniqueID+=1,`reactgooglegraph-${uniqueID}`),Mr=class Mr{};Qt(Mr,"initializeControls",e=>{for(let n=0;n<e.length;n+=1){const{controlType:o,options:l,controlWrapperParams:d}=e[n].controlProp;d&&"state"in d&&e[n].control.setState(d.state),e[n].control.setOptions(l),e[n].control.setControlType(o)}}),Qt(Mr,"listenToControlEvents",(e,n)=>{const{google:o}=n;return e.flatMap(l=>{const{control:d,controlProp:f}=l,{controlEvents:g=[]}=f;return g.map(b=>{const{callback:_,eventName:S}=b;return o.visualization.events.addListener(d,S,function(){for(var R=arguments.length,C=new Array(R),E=0;E<R;E++)C[E]=arguments[E];_({chartWrapper:null,controlWrapper:d,props:n,google:o,eventArgs:C})})})})}),Qt(Mr,"createControlId",e=>{let n;return typeof e>"u"?n=`googlechart-control-${generateUniqueID()}`:n=e,n}),Qt(Mr,"createChartControls",e=>{const{controls:n,google:o}=e;return n?n.map((l,d)=>{const{controlID:f,controlType:g,options:b,controlWrapperParams:_}=l,S=Mr.createControlId(f);return{controlProp:l,control:new o.visualization.ControlWrapper({containerId:S,controlType:g,options:b,..._})}}):null}),Qt(Mr,"addControls",e=>{const{chartWrapper:n,chartDashboard:o}=e,l=Mr.createChartControls(e);return!l||!o||!n?null:(o.bind(l.map(d=>{let{control:f}=d;return f}),n),Mr.initializeControls(l),l)});let GoogleChartControlsInternal=Mr;const useCreateChartControls=t=>{const[e,n]=React__namespace.useState(null);return[React__namespace.useMemo(()=>!e||!t?null:t.map((l,d)=>{const f=e[d];return f?{controlProp:l,control:f}:void 0}).flatMap(l=>l?[l]:[]),[e,t]),n]},useListenToControlEvents=(t,e)=>{React__namespace.useEffect(()=>{const n=GoogleChartControlsInternal.listenToControlEvents(t??[],e);return()=>{n.forEach(o=>{e.google.visualization.events.removeListener(o)})}},[t,e])},useChartControls=t=>{const[e,n]=useCreateChartControls(t.controls);return useListenToControlEvents(e??[],t),{addControls:l=>{const d=GoogleChartControlsInternal.addControls(l);n((d==null?void 0:d.map(f=>f.control))??null)},renderControl:l=>{const{chartWrapper:d,chartDashboard:f}=t;return React__namespace.createElement(GoogleChartControls,{...t,isReady:!!(d&&f),chartControls:e,filter:l})}}},useChartId=t=>{const e=React__namespace.useRef(null);return{chartId:(()=>{const{graphID:l,graph_id:d}=t,f=l||d;let g;return f?g=f:g=e.current||generateUniqueID(),e.current=g,e.current})()}},DEFAULT_CHART_COLORS=["#3366CC","#DC3912","#FF9900","#109618","#990099","#3B3EAC","#0099C6","#DD4477","#66AA00","#B82E2E","#316395","#994499","#22AA99","#AAAA11","#6633CC","#E67300","#8B0707","#329262","#5574A6","#3B3EAC"],loadDataTableFromSpreadSheet=async function(t,e){let n=arguments.length>2&&arguments[2]!==void 0?arguments[2]:{};return new Promise((o,l)=>{const d=`${n.headers?`headers=${n.headers}`:"headers=0"}`,f=`${n.query?`&tq=${encodeURIComponent(n.query)}`:""}`,g=`${n.gid?`&gid=${n.gid}`:""}`,b=`${n.sheet?`&sheet=${n.sheet}`:""}`,_=`${n.access_token?`&access_token=${n.access_token}`:""}`,S=`${d}${g}${b}${f}${_}`,R=`${e}/gviz/tq?${S}`;new t.visualization.Query(R).send(E=>{E.isError()?l(`Error in query: ${E.getMessage()} ${E.getDetailedMessage()}`):o(E.getDataTable())})})},GRAY_COLOR="#CCCCCC",wr=class wr{};Qt(wr,"grayOutHiddenColumnsLabel",(e,n)=>{const{googleChartWrapper:o,options:l}=e;if(!o){console.error("googleChartWrapper is not defined");return}const d=o.getDataTable();if(!d)return;const f=d.getNumberOfColumns();if(n.length>0===!1)return;const b=Array.from({length:f-1}).map((_,S)=>{const R=wr.getColumnId(d,S+1);return n.includes(R)?GRAY_COLOR:l&&l.colors?l.colors[S]:DEFAULT_CHART_COLORS[S]});o.setOptions({...l,colors:b}),o.draw()}),Qt(wr,"listenToLegendToggle",(e,n)=>{const[o,l]=n,{google:d,googleChartWrapper:f}=e;if(!f){console.error("googleChartWrapper is not defined");return}return d.visualization.events.addListener(f,"select",()=>{const b=f.getChart().getSelection(),_=f.getDataTable();if(b.length===0||b[0].row!==null||!_)return;const S=b[0].column,R=wr.getColumnId(_,S);o!=null&&o.includes(R)?l(C=>[...C.filter(E=>E!==R)]):l(C=>[...C,R])})}),Qt(wr,"draw",async e=>{const{data:n,diffdata:o,rows:l,columns:d,options:f,chartType:g,formatters:b,spreadSheetUrl:_,spreadSheetQueryParameters:S,googleChartDashboard:R,googleChartWrapper:C,google:E,hiddenColumns:A,legendToggle:M,legend_toggle:I}=e;if(!C){console.error("draw was called with googleChartWrapper = null");return}let j,q=null;if(o){const te=E.visualization.arrayToDataTable(o.old),ne=E.visualization.arrayToDataTable(o.new);q=E.visualization[g].prototype.computeDiff(te,ne)}n?n instanceof E.visualization.DataTable?j=n:Array.isArray(n)?j=E.visualization.arrayToDataTable(n):j=new E.visualization.DataTable(n):l&&d?j=E.visualization.arrayToDataTable([d,...l]):_?j=await loadDataTableFromSpreadSheet(E,_,S):j=E.visualization.arrayToDataTable([]);const z=j.getNumberOfColumns(),Q=Array(z).fill(0).map((te,ne)=>{const se=wr.getColumnId(j,ne);return A.includes(se)?{label:j.getColumnLabel(ne),type:j.getColumnType(ne),calc:()=>null}:ne}),F=C.getChart();C.getChartType()==="Timeline"&&F&&F.clearChart(),C.setChartType(g),C.setOptions(f||{});const V=new E.visualization.DataView(j);V.setColumns(Q),C.setDataTable(V),C.draw(),R&&R.draw(j),q&&(C.setDataTable(q),C.draw()),b&&(wr.applyFormatters({dataTable:j,formatters:b,google:E}),C.setDataTable(j),C.draw()),(M===!0||I===!0)&&wr.grayOutHiddenColumnsLabel(e,A)}),Qt(wr,"getColumnId",(e,n)=>e.getColumnId(n)||e.getColumnLabel(n)),Qt(wr,"applyFormatters",e=>{let{dataTable:n,formatters:o,google:l}=e;for(let d of o)switch(d.type){case"ArrowFormat":{new l.visualization.ArrowFormat(d.options).format(n,d.column);return}case"BarFormat":{new l.visualization.BarFormat(d.options).format(n,d.column);return}case"ColorFormat":{const f=new l.visualization.ColorFormat(d.options),{ranges:g}=d;if(g)for(let b of g)f.addRange(...b);f.format(n,d.column);return}case"DateFormat":{new l.visualization.DateFormat(d.options).format(n,d.column);return}case"NumberFormat":{new l.visualization.NumberFormat(d.options).format(n,d.column);return}case"PatternFormat":{new l.visualization.PatternFormat(d.options).format(n,d.column);return}default:{console.warn(`Unknown formatter type: ${d.type}`);return}}});let GoogleChartInternal=wr;const useGoogleChartDataTable=t=>{const{google:e,googleChartWrapper:n,googleChartDashboard:o}=t,[l,d]=React__namespace.useState([]);React__namespace.useEffect(()=>{n&&GoogleChartInternal.draw({...t,hiddenColumns:l,googleChartWrapper:n,googleChartDashboard:o,google:e})},[l,t.data,t.rows,t.columns,t.options,t.chartLoaderScriptUrl,t.chartType,t.formatters,t.spreadSheetUrl,t.spreadSheetQueryParameters,t.legendToggle,t.legend_toggle]);const f=()=>{const{googleChartWrapper:_}=t;_&&_.draw()},g=_=>{const S=[],{legendToggle:R,legend_toggle:C}=t;if(GoogleChartInternal.draw({...t,hiddenColumns:l,googleChartWrapper:_,googleChartDashboard:o,google:e}),window.addEventListener("resize",f),C||R){const E=GoogleChartInternal.listenToLegendToggle(t,[l,d]);E&&S.push(E)}return S},b=(_,S)=>{window.removeEventListener("resize",f),S.forEach(R=>{e.visualization.events.removeListener(R)}),_.getChartType()==="Timeline"&&_.getChart()&&_.getChart().clearChart()};React__namespace.useEffect(()=>{if(!n)return;const _=g(n);return()=>{b(n,_)}},[n,g,b])},listenToEvents=t=>{const{chartEvents:e,google:n,googleChartWrapper:o}=t;if(e){if(!o){console.warn("listenToEvents was called before chart wrapper ready.");return}return e.map(l=>{let{eventName:d,callback:f}=l;return n.visualization.events.addListener(o,d,function(){for(var g=arguments.length,b=new Array(g),_=0;_<g;_++)b[_]=arguments[_];f({chartWrapper:o,props:t,google:n,eventArgs:b})})})}},useGoogleChartEvents=t=>{React.useEffect(()=>{if(!t.googleChartWrapper)return;const e=listenToEvents(t);return()=>{e==null||e.forEach(n=>{t.google.visualization.events.removeListener(n)})}},[t])},GoogleChart=t=>{const[e,n]=React__namespace.useState(null),[o,l]=React__namespace.useState(null),{addControls:d,renderControl:f}=useChartControls({...t,chartDashboard:o,chartWrapper:e});useGoogleChartEvents({...t,googleChartWrapper:e});const{chartId:g}=useChartId(t),b=React__namespace.useRef(null),_=React__namespace.useRef(null);React__namespace.useEffect(()=>{const{options:j,google:q,chartType:z,chartWrapperParams:Q,toolbarItems:F,getChartEditor:V,getChartWrapper:te,onLoad:ne}=t,se={chartType:z,options:j,containerId:g,...Q},ge=new q.visualization.ChartWrapper(se);ge.setOptions(j||{}),te==null||te(ge,q);const oe=new q.visualization.Dashboard(b.current);F&&q.visualization.drawToolbar(_.current,F);let Ae=null;V&&(Ae=new q.visualization.ChartEditor,V({chartEditor:Ae,chartWrapper:ge,google:q})),d({...t,chartDashboard:oe,chartWrapper:ge}),n(ge),l(oe),ne==null||ne(q,{google:q,chartWrapper:ge,chartEditor:Ae,chartDashboard:oe})},[]),useGoogleChartDataTable({...t,googleChartWrapper:e,googleChartDashboard:o});const S=()=>{const{width:j,height:q,options:z,style:Q,className:F,rootProps:V,google:te}=t,ne={height:q||z&&z.height,width:j||z&&z.width,...Q};return React__namespace.createElement("div",{id:g,style:ne,className:F,...V})},R=()=>t.toolbarItems?React__namespace.createElement("div",{ref:_}):null,{width:C,height:E,options:A,style:M}=t,I={height:E||A&&A.height,width:C||A&&A.width,...M};return t.render?React__namespace.createElement("div",{ref:b,style:I},React__namespace.createElement("div",{ref:_,id:"toolbar"}),t.render({renderChart:S,renderControl:f,renderToolbar:R})):React__namespace.createElement("div",{ref:b,style:I},f(j=>{let{controlProp:q}=j;return q.controlPosition!=="bottom"}),S(),f(j=>{let{controlProp:q}=j;return q.controlPosition==="bottom"}),R())},ChartContext=React__namespace.createContext(chartDefaultProps),ContextProvider=t=>{let{children:e,value:n}=t;return React__namespace.createElement(ChartContext.Provider,{value:n},e)},ChartView=t=>{const{google:e,isLoading:n,error:o}=useLoadGoogleCharts(t);return n?t.loader??null:o?t.errorElement??null:e?React.createElement(GoogleChart,{google:e,...t}):null},Chart=t=>{const e={...chartDefaultProps,...t};return React.createElement(ContextProvider,{value:e},React.createElement(ChartView,e))};var GoogleDataTableColumnRoleType;(function(t){t.annotation="annotation",t.annotationText="annotationText",t.certainty="certainty",t.emphasis="emphasis",t.interval="interval",t.scope="scope",t.style="style",t.tooltip="tooltip",t.domain="domain"})(GoogleDataTableColumnRoleType||(GoogleDataTableColumnRoleType={}));function parseHsl(t){const e=t.match(/(\d+\.?\d*)\s*(\d+\.?\d*)%\s*(\d+\.?\d*)%/);return e?{h:parseFloat(e[1]),s:parseFloat(e[2]),l:parseFloat(e[3])}:null}function hslToHex(t,e,n){n/=100;const o=e*Math.min(n,1-n)/100,l=d=>{const f=(d+t/30)%12,g=n-o*Math.max(Math.min(f-3,9-f,1),-1);return Math.round(255*g).toString(16).padStart(2,"0")};return`#${l(0)}${l(8)}${l(4)}`}const Treemap=React__namespace.forwardRef(({data:t,options:e,height:n="500px",className:o,loading:l,disableClick:d=!0,...f},g)=>{const b=React__namespace.useRef(null),[_,S]=React__namespace.useState(null);React__namespace.useEffect(()=>{if(!b.current)return;const E=b.current;let A;const M=()=>{const q=getComputedStyle(E).getPropertyValue("--primary").trim();if(q){const z=parseHsl(q);if(z){const{h:Q,s:F,l:V}=z;S({minColor:hslToHex(Q,F,Math.min(100,V+50)),midColor:hslToHex(Q,F,Math.min(100,V+35)),maxColor:hslToHex(Q,F,Math.min(100,V+20))})}return!0}return!1};if(M())return;let I=0;const j=20;return A=setInterval(()=>{(M()||I>=j)&&clearInterval(A),I++},100),()=>{A&&clearInterval(A)}},[]);const R=React__namespace.useMemo(()=>{const E={headerHeight:0,fontSize:14,showScale:!1,isHtml:!0,generateTooltip:(A,M)=>{var q;const I=(q=t[A+1])==null?void 0:q[0];if(!I)return"";const j=formatMoney(M);return`<div class="p-2 bg-background text-foreground border rounded-md shadow-lg">
|
|
1327
|
+
`;function RichTextEditor({id:t,name:e,value:n,onChange:o,placeholder:l,className:d,...f}){const[g,b]=React.useState(!1),_=React.useRef(null),S=React.useRef(null),R=useEditor({extensions:[StarterKit,Underline],content:n,editorProps:{attributes:{class:"prose prose-sm sm:prose dark:prose-invert focus:outline-none",id:t??"",name:e??""}},onUpdate:({editor:j})=>{const q=j.getHTML();o({target:{id:t,name:e,value:q}})}});React.useEffect(()=>{R&&n!==R.getHTML()&&R.commands.setContent(n)},[n,R]);const C=React.useCallback(j=>{if(R)if(R.chain().focus(),j==="paragraph")R.chain().setParagraph().run();else{const q=Number.parseInt(j.slice(1));R.chain().setHeading({level:q}).run()}},[R]),E=React.useCallback(j=>{if(R)switch(R.chain().focus(),j){case"bold":R.chain().toggleBold().run();break;case"italic":R.chain().toggleItalic().run();break;case"underline":R.chain().toggleUnderline().run();break;case"strike":R.chain().toggleStrike().run();break;case"bulletList":R.chain().toggleBulletList().run();break;case"orderedList":R.chain().toggleOrderedList().run();break}},[R]),A=React.useCallback(()=>{b(j=>!j)},[]),M=React.useCallback(j=>{const q=j.target.value;R&&R.commands.setContent(q),o({target:{id:t,name:e,value:q}})},[o,R,t,e]),I=React.useCallback(()=>{!g&&R&&R.commands.focus()},[g,R]);return R?jsxRuntime.jsxs("div",{ref:S,className:cn("border border-input rounded-md overflow-hidden focus-within:outline-hidden focus-within:ring-1 focus-within:ring-ring",d),onClick:I,...f,children:[jsxRuntime.jsx("style",{children:editorStyles}),jsxRuntime.jsxs("div",{className:"flex flex-wrap items-center p-2 border-b border-input gap-2 bg-background",children:[jsxRuntime.jsxs(Select,{onValueChange:C,disabled:g,children:[jsxRuntime.jsx(SelectTrigger,{className:"w-[160px]",children:jsxRuntime.jsx(SelectValue,{placeholder:"Format"})}),jsxRuntime.jsx(SelectContent,{children:formatOptions.map(j=>jsxRuntime.jsx(SelectItem,{value:j.value,children:j.label},j.value))})]}),["bold","italic","underline","strike","bulletList","orderedList"].map(j=>jsxRuntime.jsxs(Button,{type:"button",variant:"ghost",size:"sm",onClick:()=>E(j),className:R.isActive(j)?"bg-muted":"",disabled:g,children:[j==="bold"&&jsxRuntime.jsx(Bold$1,{className:"h-4 w-4"}),j==="italic"&&jsxRuntime.jsx(Italic$1,{className:"h-4 w-4"}),j==="underline"&&jsxRuntime.jsx(Underline$1,{className:"h-4 w-4"}),j==="strike"&&jsxRuntime.jsx(Strikethrough,{className:"h-4 w-4"}),j==="bulletList"&&jsxRuntime.jsx(List$1,{className:"h-4 w-4"}),j==="orderedList"&&jsxRuntime.jsx(ListOrdered,{className:"h-4 w-4"})]},j)),jsxRuntime.jsx(Button,{type:"button",variant:"ghost",size:"sm",onClick:A,className:g?"bg-muted":"",children:jsxRuntime.jsx(Code$1,{className:"h-4 w-4"})})]}),jsxRuntime.jsx("div",{className:"p-3",children:g?jsxRuntime.jsx(Textarea,{ref:_,id:t,name:e,value:R.getHTML(),onChange:M,className:cn("min-h-[150px] font-mono text-sm resize-none border-0 focus-visible:ring-0 focus-visible:ring-offset-0",d),placeholder:l}):jsxRuntime.jsx(EditorContent,{editor:R})})]}):null}function ReceiptsTable({receipts:t=null,loading:e=!1}){const n=React.useMemo(()=>[{accessorKey:"Location",header:"Location",cell:({row:d})=>jsxRuntime.jsx("div",{className:"min-w-[150px]",children:d.original.Location??"N/A"}),enableSorting:!0,enableFiltering:!0},{accessorKey:"ReceiptDate",header:"Date",cell:({row:d})=>formatYYYYMMDDIntToDateString(d.original.ReceiptDate),enableSorting:!0,enableFiltering:!0},{accessorKey:"Quantity",header:"Quantity",cell:({row:d})=>d.original.Quantity??"N/A",enableSorting:!0,enableFiltering:!0}],[]),o=React.useMemo(()=>{const d={};if(t){const f=Array.from(new Set(t.map(b=>b.Location).filter(b=>b!=null)));d.Location=f;const g=Array.from(new Set(t.map(b=>formatYYYYMMDDIntToDateString(b.ReceiptDate)).filter(b=>b!=="N/A"&&b!=="Invalid Date"))).sort((b,_)=>new Date(_).getTime()-new Date(b).getTime());d.ReceiptDate=g}return d},[t]),l=t||[];return jsxRuntime.jsx(DataTable,{columns:n,data:l,uniqueValues:o,loading:e,tableClass:"bg-card text-card-foreground"})}const formatDate$1=t=>{if(!t)return"N/A";try{const e=new Date(t);return isNaN(e.getTime())?"Invalid Date":e.toLocaleDateString(void 0,{year:"numeric",month:"short",day:"numeric"})}catch{return"Invalid Date"}},getStatusVariant=t=>{const e=(t==null?void 0:t.toLowerCase())||"";return e.includes("accepted")?"success":e.includes("error")||e.includes("rejected")?"destructive":"neutral"};function ReturnsTable({applicationId:t,returns:e=null,loading:n=!1}){const o=React.useMemo(()=>[{accessorKey:"ReturnNumber1",header:"RMA Number",cell:({row:f})=>{const g=f.original.ReturnNumber1||f.original.ReturnNumber;return g?jsxRuntime.jsx(TooltipProvider,{delayDuration:100,children:jsxRuntime.jsxs(Tooltip$1,{children:[jsxRuntime.jsx(TooltipTrigger,{asChild:!0,children:jsxRuntime.jsx(reactRouterDom.Link,{to:`/${t}/Return/${g}`,className:"font-medium text-primary hover:underline",children:g})}),jsxRuntime.jsx(TooltipContent,{children:jsxRuntime.jsxs("p",{children:["View details for return ",g]})})]})}):"N/A"},enableSorting:!0,enableFiltering:!0},{accessorKey:"RequestDate",header:"Request Date",cell:({row:f})=>formatDate$1(f.original.RequestDate),enableSorting:!0},{accessorKey:"InvoiceNumber",header:"Invoice Number",cell:({row:f})=>{const g=f.original.InvoiceNumber;return g?jsxRuntime.jsx(TooltipProvider,{delayDuration:100,children:jsxRuntime.jsxs(Tooltip$1,{children:[jsxRuntime.jsx(TooltipTrigger,{asChild:!0,children:jsxRuntime.jsx(reactRouterDom.Link,{to:`/${t}/Document/${g}`,className:"text-blue-600 hover:underline dark:text-blue-400",children:g})}),jsxRuntime.jsx(TooltipContent,{children:jsxRuntime.jsxs("p",{children:["View details for invoice ",g]})})]})}):"N/A"},enableSorting:!0,enableFiltering:!0},{accessorKey:"Quantity",header:"Quantity",cell:({row:f})=>f.original.Quantity??"0",enableSorting:!0},{accessorKey:"ReasonForReturn",header:"Return Reason",cell:({row:f})=>jsxRuntime.jsx("div",{className:"min-w-[150px]",children:f.original.ReasonForReturn??"—"}),enableSorting:!0,enableFiltering:!0},{accessorKey:"Status",header:"Status",cell:({row:f})=>{const g=f.original.Status,b=getStatusVariant(g);let _="border-gray-400 bg-gray-100 text-gray-600 dark:border-gray-600 dark:bg-gray-800/50 dark:text-gray-400";return b==="success"?_="border-green-500 bg-green-100 text-green-700 dark:border-green-600 dark:bg-green-900/50 dark:text-green-400":b==="destructive"&&(_="border-red-500 bg-red-100 text-red-700 dark:border-red-600 dark:bg-red-900/50 dark:text-red-400"),g?jsxRuntime.jsx(Badge,{variant:"outline",className:`${_} font-medium`,children:g}):"—"},enableSorting:!0,enableFiltering:!0},{accessorKey:"WarehouseLocation",header:"Warehouse",cell:({row:f})=>f.original.WarehouseLocation??"—",enableSorting:!0,enableFiltering:!0},{accessorKey:"LastUpdatedDate",header:"Last Update",cell:({row:f})=>formatDate$1(f.original.LastUpdatedDate)!=="N/A"?formatDate$1(f.original.LastUpdatedDate):"—",enableSorting:!0}],[t]),l=React.useMemo(()=>{const f={};if(e){const g=Array.from(new Set(e.map(S=>S.Status).filter(Boolean)));f.Status=g;const b=Array.from(new Set(e.map(S=>S.ReasonForReturn).filter(Boolean)));f.ReasonForReturn=b;const _=Array.from(new Set(e.map(S=>S.WarehouseLocation).filter(Boolean)));f.WarehouseLocation=_}return f},[e]),d=React.useMemo(()=>e?[...e].sort((g,b)=>(b.ReturnNumber1||b.ReturnNumber||"").localeCompare(g.ReturnNumber1||g.ReturnNumber||"")):[],[e]);return n?jsxRuntime.jsxs(Card,{className:"w-full",children:[jsxRuntime.jsx(CardHeader,{children:jsxRuntime.jsx(Skeleton,{className:"h-7 w-48"})}),jsxRuntime.jsxs(CardContent,{className:"space-y-4",children:[jsxRuntime.jsx(Skeleton,{className:"h-12 w-full rounded-md border"}),jsxRuntime.jsx(Skeleton,{className:"h-48 w-full rounded-md border"}),jsxRuntime.jsxs("div",{className:"flex items-center justify-between pt-4",children:[jsxRuntime.jsx(Skeleton,{className:"h-9 w-[130px]"}),jsxRuntime.jsxs("div",{className:"flex items-center space-x-2",children:[jsxRuntime.jsx(Skeleton,{className:"h-9 w-20"}),jsxRuntime.jsx(Skeleton,{className:"h-9 w-24"}),jsxRuntime.jsx(Skeleton,{className:"h-9 w-9"}),jsxRuntime.jsx(Skeleton,{className:"h-9 w-9"})]})]})]})]}):jsxRuntime.jsxs(Card,{className:"w-full",children:[jsxRuntime.jsx(CardHeader,{children:jsxRuntime.jsx(CardTitle,{className:"text-1xl font-bold",children:"Returns"})}),jsxRuntime.jsx(CardContent,{children:jsxRuntime.jsx(DataTable,{columns:o,data:d,uniqueValues:l})})]})}function InvoicesTable({applicationId:t,invoices:e=null,loading:n=!1}){const o=React.useMemo(()=>[{accessorKey:"InvoiceNumber",header:"Number",cell:({row:f})=>f.original.InvoiceNumber?jsxRuntime.jsx(TooltipProvider,{delayDuration:100,children:jsxRuntime.jsxs(Tooltip$1,{children:[jsxRuntime.jsx(TooltipTrigger,{asChild:!0,children:jsxRuntime.jsx(reactRouterDom.Link,{to:`/${t}/Document/${f.original.InvoiceNumber}`,className:"font-medium text-primary hover:underline",children:f.original.InvoiceNumber})}),jsxRuntime.jsx(TooltipContent,{children:jsxRuntime.jsxs("p",{children:["View details for invoice ",f.original.InvoiceNumber]})})]})}):"—",enableSorting:!0,enableFiltering:!0},{accessorKey:"InvoiceDate",header:"Date",cell:({row:f})=>formatYYYYMMDDIntToDateString(f.original.InvoiceDate),enableSorting:!0,enableFiltering:!0},{accessorKey:"OrderNumber",header:"Order Number",cell:({row:f})=>f.original.OrderNumber?jsxRuntime.jsx(TooltipProvider,{delayDuration:100,children:jsxRuntime.jsxs(Tooltip$1,{children:[jsxRuntime.jsx(TooltipTrigger,{asChild:!0,children:jsxRuntime.jsx(reactRouterDom.Link,{to:`/${t}/GeneralDocument/${f.original.OrderNumber}`,className:"font-medium text-primary hover:underline",children:f.original.OrderNumber})}),jsxRuntime.jsx(TooltipContent,{children:jsxRuntime.jsxs("p",{children:["View details for order ",f.original.OrderNumber]})})]})}):"—",enableSorting:!0,enableFiltering:!0},{accessorKey:"PONumber",header:"PO Number",cell:({row:f})=>f.original.PONumber&&f.original.PONumber.trim().length>0?f.original.PONumber:"—",enableSorting:!0,enableFiltering:!0},{accessorKey:"ShipToName",header:"Ship To Name",cell:({row:f})=>f.original.ShipToName??"—",enableSorting:!0,enableFiltering:!0},{accessorKey:"QuantityOrdered",header:"Quantity Ordered",cell:({row:f})=>f.original.QuantityOrdered??0,enableSorting:!0,enableFiltering:!0},{accessorKey:"UnitPrice",header:"Unit Price",cell:({row:f})=>formatMoney(f.original.UnitPrice??0),enableSorting:!0,enableFiltering:!0},{accessorKey:"Location",header:"Location",cell:({row:f})=>f.original.Location??"—",enableSorting:!0,enableFiltering:!0}],[t]),l=React.useMemo(()=>{const f={};if(e){const g=Array.from(new Set(e.map(C=>C.ShipToName).filter(C=>C!=null)));f.ShipToName=g;const b=Array.from(new Set(e.map(C=>C.InvoiceNumber).filter(C=>C!=null)));f.InvoiceNumber=b;const _=Array.from(new Set(e.map(C=>C.OrderNumber).filter(C=>C!=null)));f.OrderNumber=_;const S=Array.from(new Set(e.map(C=>C.PONumber).filter(C=>C!=null)));f.PONumber=S;const R=Array.from(new Set(e.map(C=>C.Location).filter(C=>C!=null)));f.Location=R}return f},[e]),d=e||[];return jsxRuntime.jsx(DataTable,{columns:o,data:d,uniqueValues:l,loading:n,tableClass:"bg-card text-card-foreground"})}function ProductOverviewPage({applicationId:t,sku:e,productDefaultOpportunityNumber:n="",productOnAddToCart:o,productAddingToCart:l=!1,productShopifyHostname:d,productCustomAction:f=jsxRuntime.jsx(jsxRuntime.Fragment,{})}){var I,j,q,z,Q,F,V,te,ne,se,ge,oe;const{data:g,isLoading:b}=useGetV4PartnerByRouteApplicationIdProductAndRandmarSkuQuery({routeApplicationId:t,randmarSku:e,withSpecification:!1},{skip:!t||!e}),{data:_,isLoading:S}=useGetV4PartnerByRouteApplicationIdProductAndRandmarSkuQuery({routeApplicationId:t,randmarSku:e,withSpecification:!0},{skip:!g}),[R,C]=React.useState("stats"),[E,A]=React.useState(!1);React.useEffect(()=>{var Ne,Oe,Fe,ze,$e,Be,qe,Ge;if(S||!_){A(!1);return}const Ae={stats:(((Ne=_==null?void 0:_.SalesStatistics)==null?void 0:Ne.length)??0)<=0,inventory:(((Fe=(Oe=_==null?void 0:_.Distribution)==null?void 0:Oe.Inventory)==null?void 0:Fe.length)??0)<=0,opportunities:(((ze=_==null?void 0:_.Opportunities)==null?void 0:ze.length)??0)<=0,orders:((($e=_==null?void 0:_.ActiveOrderDetails)==null?void 0:$e.length)??0)<=0&&(((Be=_==null?void 0:_.Returns)==null?void 0:Be.length)??0)<=0,invoices:(((qe=_==null?void 0:_.CompletedOrderDetails)==null?void 0:qe.length)??0)<=0,warehouse:(((Ge=_==null?void 0:_.Receipts)==null?void 0:Ge.length)??0)<=0},je=Object.values(Ae).some(He=>!He);if(A(je),je&&Ae[R]){const He=Object.keys(Ae).find(Ze=>!Ae[Ze]);He&&C(He)}},[S,_,R]);const M=(g==null?void 0:g.ManufacturerId)!==t;return console.log("readonly",M),jsxRuntime.jsxs("div",{className:"@container",children:[jsxRuntime.jsxs("div",{className:"grid gap-4 grid-cols-1 @sm:grid-cols-2 @md:grid-cols-3",children:[jsxRuntime.jsx("div",{className:"@md:col-span-2",children:jsxRuntime.jsx(ProductCard,{applicationId:t,product:_||g,defaultOpportunityNumber:n,onAddToCart:o,addingToCart:l,shopifyHostname:d,customAction:f})}),jsxRuntime.jsxs(Card,{className:"flex flex-col",children:[jsxRuntime.jsx(CardHeader,{children:jsxRuntime.jsxs(CardTitle,{children:[jsxRuntime.jsx(Info,{className:"h-5 w-5 inline mr-2"})," Additionnal information"]})}),jsxRuntime.jsx(CardContent,{className:"basis-0 mb-6 grow overflow-y-auto",children:b?jsxRuntime.jsxs(jsxRuntime.Fragment,{children:[jsxRuntime.jsxs("div",{className:"flex justify-between",children:[jsxRuntime.jsx(Skeleton,{className:"h-5 w-32"}),jsxRuntime.jsx(Skeleton,{className:"h-5 w-24"})]}),jsxRuntime.jsxs("div",{className:"flex justify-between mt-2",children:[jsxRuntime.jsx(Skeleton,{className:"h-5 w-32"}),jsxRuntime.jsx(Skeleton,{className:"h-5 w-24"})]}),jsxRuntime.jsxs("div",{className:"flex justify-between mt-2",children:[jsxRuntime.jsx(Skeleton,{className:"h-5 w-32"}),jsxRuntime.jsx(Skeleton,{className:"h-5 w-24"})]}),jsxRuntime.jsxs("div",{className:"flex justify-between mt-2",children:[jsxRuntime.jsx(Skeleton,{className:"h-5 w-32"}),jsxRuntime.jsx(Skeleton,{className:"h-5 w-24"})]}),jsxRuntime.jsx(Skeleton,{className:"h-1 w-full my-6"}),jsxRuntime.jsx(Skeleton,{className:"h-5 w-24"}),jsxRuntime.jsx(Skeleton,{className:"h-4 w-full mt-2"}),jsxRuntime.jsx(Skeleton,{className:"h-4 w-full mt-1"})]}):jsxRuntime.jsxs(jsxRuntime.Fragment,{children:[jsxRuntime.jsxs("div",{className:"flex justify-between",children:[jsxRuntime.jsx("span",{className:"text-muted-foreground",children:"Cateory Name"}),jsxRuntime.jsx("span",{className:"font-medium",children:(g==null?void 0:g.ProductType)||"N/A"})]}),jsxRuntime.jsxs("div",{className:"flex justify-between mt-2",children:[jsxRuntime.jsx("span",{className:"text-muted-foreground",children:"Master Carton"}),jsxRuntime.jsx("span",{className:"font-medium",children:(g==null?void 0:g.MasterCarton)||"N/A"})]}),jsxRuntime.jsxs("div",{className:"flex justify-between mt-2",children:[jsxRuntime.jsx("span",{className:"text-muted-foreground",children:"Skid Quantity"}),jsxRuntime.jsx("span",{className:"font-medium",children:(g==null?void 0:g.SkidQuantity)||"N/A"})]}),jsxRuntime.jsxs("div",{className:"flex justify-between mt-2",children:[jsxRuntime.jsx("span",{className:"text-muted-foreground",children:"Automatic Reorder"}),jsxRuntime.jsx("span",{className:"font-medium",children:g!=null&&g.AutoUpdate?"Yes":"No"})]}),((g==null?void 0:g.VoiceoverCaption)||(g==null?void 0:g.BodyHTML))&&jsxRuntime.jsxs(jsxRuntime.Fragment,{children:[jsxRuntime.jsx("hr",{className:"my-6"}),jsxRuntime.jsx("div",{className:"text-muted-foreground mb-2",children:"Description"}),(g==null?void 0:g.VoiceoverCaption)&&jsxRuntime.jsx("div",{children:g==null?void 0:g.VoiceoverCaption}),(g==null?void 0:g.BodyHTML)&&jsxRuntime.jsx("div",{className:"prose prose-sm max-w-none",dangerouslySetInnerHTML:{__html:(g==null?void 0:g.BodyHTML)??""}})]})]})})]})]}),jsxRuntime.jsx("div",{className:"my-4",children:b||S?jsxRuntime.jsx("div",{className:"mx-auto flex justify-center items-center h-32",children:jsxRuntime.jsx(LoaderCircle,{className:"h-8 w-8 animate-spin text-primary"})}):E&&jsxRuntime.jsxs(Tabs,{value:R,onValueChange:C,children:[jsxRuntime.jsxs(TabsList,{className:"inline-flex h-auto items-center justify-center rounded-none border-b bg-transparent p-0",children:[jsxRuntime.jsx(TabsTrigger,{value:"stats",className:"relative h-12 rounded-none border-b-2 border-b-transparent bg-transparent px-4 pb-3 pt-2 text-sm font-medium text-muted-foreground shadow-none transition-none hover:text-foreground data-[state=active]:border-b-primary data-[state=active]:text-foreground data-[state=active]:shadow-none cursor-pointer",disabled:(((I=_==null?void 0:_.SalesStatistics)==null?void 0:I.length)??0)<=0,children:"Statistics"}),jsxRuntime.jsx(TabsTrigger,{value:"inventory",className:"relative h-12 rounded-none border-b-2 border-b-transparent bg-transparent px-4 pb-3 pt-2 text-sm font-medium text-muted-foreground shadow-none transition-none hover:text-foreground data-[state=active]:border-b-primary data-[state=active]:text-foreground data-[state=active]:shadow-none cursor-pointer",disabled:(((q=(j=_==null?void 0:_.Distribution)==null?void 0:j.Inventory)==null?void 0:q.length)??0)<=0,children:"Inventory"}),jsxRuntime.jsx(TabsTrigger,{value:"opportunities",className:"relative h-12 rounded-none border-b-2 border-b-transparent bg-transparent px-4 pb-3 pt-2 text-sm font-medium text-muted-foreground shadow-none transition-none hover:text-foreground data-[state=active]:border-b-primary data-[state=active]:text-foreground data-[state=active]:shadow-none cursor-pointer",disabled:(((z=_==null?void 0:_.Opportunities)==null?void 0:z.length)??0)<=0,children:"Opportunities"}),jsxRuntime.jsx(TabsTrigger,{value:"orders",className:"relative h-12 rounded-none border-b-2 border-b-transparent bg-transparent px-4 pb-3 pt-2 text-sm font-medium text-muted-foreground shadow-none transition-none hover:text-foreground data-[state=active]:border-b-primary data-[state=active]:text-foreground data-[state=active]:shadow-none cursor-pointer",disabled:(((Q=_==null?void 0:_.ActiveOrderDetails)==null?void 0:Q.length)??0)<=0&&(((F=_==null?void 0:_.Returns)==null?void 0:F.length)??0)<=0,children:"Orders"}),jsxRuntime.jsx(TabsTrigger,{value:"invoices",className:"relative h-12 rounded-none border-b-2 border-b-transparent bg-transparent px-4 pb-3 pt-2 text-sm font-medium text-muted-foreground shadow-none transition-none hover:text-foreground data-[state=active]:border-b-primary data-[state=active]:text-foreground data-[state=active]:shadow-none cursor-pointer",disabled:(((V=_==null?void 0:_.Invoices)==null?void 0:V.length)??0)<=0,children:"Invoices"}),jsxRuntime.jsx(TabsTrigger,{value:"warehouse",className:"relative h-12 rounded-none border-b-2 border-b-transparent bg-transparent px-4 pb-3 pt-2 text-sm font-medium text-muted-foreground shadow-none transition-none hover:text-foreground data-[state=active]:border-b-primary data-[state=active]:text-foreground data-[state=active]:shadow-none cursor-pointer",disabled:(((te=_==null?void 0:_.Receipts)==null?void 0:te.length)??0)<=0,children:"Latest Warehouse Receiving"})]}),jsxRuntime.jsx(TabsContent,{value:"stats",children:jsxRuntime.jsx("div",{className:"mt-4",children:jsxRuntime.jsx(SalesChartCard,{statistics:(_==null?void 0:_.SalesStatistics)??[],loading:S})})}),jsxRuntime.jsx(TabsContent,{value:"inventory",children:jsxRuntime.jsx("div",{className:"mt-4",children:jsxRuntime.jsx(ProductInventoryGrid,{inventory:((ne=_==null?void 0:_.Distribution)==null?void 0:ne.Inventory)??[],className:"bg-card text-card-foreground"})})}),jsxRuntime.jsx(TabsContent,{value:"opportunities",children:jsxRuntime.jsx("div",{className:"mt-4",children:jsxRuntime.jsx(OpportunitiesTable,{applicationId:t,opportunities:g==null?void 0:g.Opportunities,loading:b})})}),jsxRuntime.jsxs(TabsContent,{value:"orders",children:[(((se=_==null?void 0:_.ActiveOrderDetails)==null?void 0:se.length)??0)>0&&jsxRuntime.jsx("div",{className:"mt-4",children:jsxRuntime.jsx(OrdersCard,{applicationId:t,title:"Open Orders",orders:_==null?void 0:_.ActiveOrderDetails,loading:S})}),(((ge=_==null?void 0:_.Returns)==null?void 0:ge.length)??0)>0&&jsxRuntime.jsx("div",{className:"mt-4",children:jsxRuntime.jsx(ReturnsTable,{applicationId:t,returns:_==null?void 0:_.Returns,loading:S})})]}),jsxRuntime.jsx(TabsContent,{value:"invoices",children:(((oe=_==null?void 0:_.Invoices)==null?void 0:oe.length)??0)>0&&jsxRuntime.jsx("div",{className:"mt-4",children:jsxRuntime.jsx(InvoicesTable,{applicationId:t,invoices:_==null?void 0:_.Invoices,loading:S})})}),jsxRuntime.jsx(TabsContent,{value:"warehouse",children:jsxRuntime.jsx("div",{className:"mt-4",children:jsxRuntime.jsx(ReceiptsTable,{receipts:_==null?void 0:_.Receipts,loading:S})})})]})})]})}function AssistantChat(t){return jsxRuntime.jsx(Card,{className:"max-w-6xl",children:jsxRuntime.jsx(ChatLayout,{className:"h-[40em]",userId:t.userId,userName:t.userName,assistantOnly:!0,initialPrompt:t.initialPrompt})})}function getEndDateStatus(t){if(!t)return{text:"No End Date",variant:"neutral",daysRemaining:null};const e=new Date(t);if(isNaN(e.getTime()))return{text:"Invalid Date",variant:"neutral",daysRemaining:null};const n=new Date,o=new Date(e.getFullYear(),e.getMonth(),e.getDate()),l=new Date(n.getFullYear(),n.getMonth(),n.getDate()),d=o.getTime()-l.getTime(),f=Math.ceil(d/(1e3*60*60*24));return f<0?{text:`Ended ${Math.abs(f)}d ago`,variant:"destructive",daysRemaining:f}:f===0?{text:"Ends today",variant:"destructive",daysRemaining:f}:f<=7?{text:`Ends in ${f}d`,variant:"destructive",daysRemaining:f}:f<=30?{text:`Ends in ${f}d`,variant:"warning",daysRemaining:f}:{text:`Ends in ${f}d`,variant:"neutral",daysRemaining:f}}const formatDate=t=>{if(!t)return"N/A";try{const e=new Date(t);return isNaN(e.getTime())?"Invalid Date":e.toLocaleDateString(void 0,{year:"numeric",month:"short",day:"numeric"})}catch{return"Invalid Date"}};function OpportunitiesTable({applicationId:t,opportunities:e=null,loading:n=!1}){var te;const{toast:o}=useToast(),[l,d]=React.useState({}),[f,g]=React.useState(!1),[b,_]=React.useState(""),[S,R]=React.useState(null),{data:C}=useGetV4PartnerByApplicationIdAccountQuery({applicationId:t},{skip:!t}),E=React.useCallback((ne,se,ge)=>{d(oe=>({...oe,[ne]:{...oe[ne],[se]:ge}}))},[]),[A]=usePutV4ResellerByRouteResellerIdOpportunityAndManufacturerIdDefaultMutation(),M=React.useCallback(async ne=>{if(!(C!=null&&C.IsReseller))return;if(!ne.BidNumber){o({title:"Error",description:"Bid Number is missing, cannot set default.",variant:"destructive"});return}const se=ne.BidNumber;E(se,"isSettingDefault",!0),A({routeResellerId:t,manufacturerId:ne.ManufacturerId??"",opportunityNumber:se}).unwrap().then(()=>{o({title:"Success",description:`Opportunity "${ne.OpportunityName||ne.Opportunity||se}" was successfully set as default.`,variant:"success"})}).catch(ge=>{var oe;console.error("Set as default error:",ge),o({title:"Error",description:((oe=ge.data)==null?void 0:oe.message)||ge.message||"An error occurred while setting this opportunity as default.",variant:"destructive"})}).finally(()=>{E(se,"isSettingDefault",!1)})},[t,A,o,E]),[I]=usePostV4ResellerByRouteResellerIdOpportunityAndManufacturerIdBidNumberEmailMutation(),j=React.useCallback(ne=>{if(C!=null&&C.IsReseller){if(!ne.BidNumber){o({title:"Error",description:"Bid Number is missing, cannot prepare report.",variant:"destructive"});return}R(ne),_(""),g(!0)}},[o]),q=React.useCallback(async()=>{if(!(C!=null&&C.IsReseller))return;if(!S||!S.BidNumber){o({title:"Error",description:"No opportunity selected or Bid Number is missing.",variant:"destructive"});return}if(!b.trim()||!/\S+@\S+\.\S+/.test(b)){o({title:"Validation Error",description:"Please enter a valid email address.",variant:"destructive"});return}const ne=S.BidNumber;E(ne,"isSendingReport",!0),I({routeResellerId:t,manufacturerId:S.ManufacturerId??"",bidNumber:ne,emailAddress:b}).unwrap().then(()=>{o({title:"Success",description:`A report for "${S.OpportunityName||S.Opportunity||ne}" was successfully sent to ${b}.`,variant:"success"}),g(!1)}).catch(se=>{var ge;console.error("Send report by email error:",se),o({title:"Error",description:((ge=se.data)==null?void 0:ge.message)||se.message||"An error occurred while sending the report by email.",variant:"destructive"})}).finally(()=>{E(ne,"isSendingReport",!1),f||(R(null),_(""))})},[S,b,t,I,o,E,g]),z=React.useMemo(()=>[{accessorKey:"ManufacturerId",header:"Manuf.",cell:({row:ne})=>jsxRuntime.jsx("div",{className:"w-20 h-8",children:jsxRuntime.jsx(PartnerLogo,{id:ne.original.ManufacturerId,width:80,height:32})}),enableSorting:!0,enableFiltering:!0},{id:"opportunityDisplay",accessorFn:ne=>ne.OpportunityName||ne.Opportunity,header:"Opportunity",cell:({getValue:ne})=>jsxRuntime.jsx("div",{className:"min-w-[150px]",children:ne()??"N/A"}),enableSorting:!0,enableFiltering:!0},{accessorKey:"BidNumber",header:"Bid Number",cell:({row:ne})=>ne.original.BidNumber??"N/A",enableSorting:!0,enableFiltering:!0},{id:"statusInfo",header:"Status",cell:({row:ne})=>{const se=ne.original,ge=se.Active===!0,oe=getEndDateStatus(se.EndDate);let Ae="border-gray-400 bg-gray-100 text-gray-600 dark:border-gray-600 dark:bg-gray-800/50 dark:text-gray-400";return oe.variant==="destructive"?Ae="border-red-500 bg-red-100 text-red-700 dark:border-red-600 dark:bg-red-900/50 dark:text-red-400":oe.variant==="warning"&&(Ae="border-yellow-500 bg-yellow-100 text-yellow-700 dark:border-yellow-600 dark:bg-yellow-900/50 dark:text-yellow-400"),jsxRuntime.jsxs("div",{className:"flex items-center space-x-2 min-w-[200px]",children:[jsxRuntime.jsx(Badge,{variant:"outline",className:ge?"border-green-500 bg-green-100 text-green-700 dark:border-green-600 dark:bg-green-900/50 dark:text-green-400 font-medium":"border-gray-400 bg-gray-100 text-gray-600 dark:border-gray-600 dark:bg-gray-800/50 dark:text-gray-400 font-medium",children:ge?"Active":"Inactive"}),se.EndDate&&jsxRuntime.jsx(Badge,{variant:"outline",className:`${Ae} font-medium`,children:oe.text}),jsxRuntime.jsx(TooltipProvider,{delayDuration:100,children:jsxRuntime.jsxs(Tooltip$1,{children:[jsxRuntime.jsx(TooltipTrigger,{asChild:!0,children:jsxRuntime.jsx(Button,{variant:"ghost",size:"icon",className:"h-6 w-6 p-0 data-[state=delayed-open]:bg-accent data-[state=instant-open]:bg-accent",children:jsxRuntime.jsx(Info,{className:"h-4 w-4 text-muted-foreground"})})}),jsxRuntime.jsx(TooltipContent,{side:"top",align:"center",className:"bg-popover text-popover-foreground p-2 rounded shadow-lg",children:jsxRuntime.jsxs("div",{className:"text-sm space-y-1",children:[jsxRuntime.jsxs("p",{children:[jsxRuntime.jsx("strong",{children:"Start:"})," ",formatDate(se.StartDate)]}),jsxRuntime.jsxs("p",{children:[jsxRuntime.jsx("strong",{children:"End:"})," ",formatDate(se.EndDate)]}),jsxRuntime.jsxs("p",{children:[jsxRuntime.jsx("strong",{children:"Updated:"})," ",formatDate(se.LastUpdate)]})]})})]})})]})},enableFiltering:!1},{id:"actions",header:"Actions",cell:({row:ne})=>{var Oe,Fe;const se=ne.original;if(!se.BidNumber)return jsxRuntime.jsx("span",{className:"text-xs text-muted-foreground",children:"Actions unavailable"});const ge=se.BidNumber,oe=(Oe=l[ge])==null?void 0:Oe.isSettingDefault,Ae=(S==null?void 0:S.BidNumber)===ge&&((Fe=l[ge])==null?void 0:Fe.isSendingReport),je=oe||Ae,Ne=se.CanBeSetAsDefault===!0;return jsxRuntime.jsxs("div",{className:"flex space-x-2",children:[jsxRuntime.jsx(reactRouterDom.Link,{to:`/${t}/Opportunity/${se.ManufacturerId}/${se.BidNumber}`,children:jsxRuntime.jsxs(Button,{variant:"outline",size:"sm",className:"flex items-center",children:[jsxRuntime.jsx(Star,{className:"mr-2 h-4 w-4"})," View"]})}),(C==null?void 0:C.IsReseller)&&jsxRuntime.jsxs(jsxRuntime.Fragment,{children:[jsxRuntime.jsxs(Button,{variant:"outline",size:"sm",onClick:()=>M(se),disabled:je||!Ne,title:Ne?"Set as default":"This opportunity cannot be set as default",className:"flex items-center",children:[oe?jsxRuntime.jsx(LoaderCircle,{className:"mr-2 h-4 w-4 animate-spin"}):jsxRuntime.jsx(Star,{className:"mr-2 h-4 w-4"})," Set Default"]}),jsxRuntime.jsxs(Button,{variant:"outline",size:"sm",onClick:()=>j(se),disabled:je,title:"Send report by email",className:"flex items-center",children:[Ae?jsxRuntime.jsx(LoaderCircle,{className:"mr-2 h-4 w-4 animate-spin"}):jsxRuntime.jsx(Send,{className:"mr-2 h-4 w-4"})," Send Report"]})]})]})}}],[l,M,j,S]),Q=React.useMemo(()=>{const ne={};if(e){const se=Array.from(new Set(e.map(oe=>oe.ManufacturerId).filter(oe=>oe!=null)));ne.ManufacturerId=se;const ge=Array.from(new Set(e.map(oe=>oe.OpportunityName||oe.Opportunity).filter(oe=>oe!=null)));ne.opportunityDisplay=ge}return ne},[e]),F=e||[],V=S!=null&&S.BidNumber?(te=l[S.BidNumber])==null?void 0:te.isSendingReport:!1;return n?jsxRuntime.jsxs(Card,{className:"w-full",children:[jsxRuntime.jsxs(CardHeader,{children:[" ",jsxRuntime.jsx(Skeleton,{className:"h-7 w-48"})," "]}),jsxRuntime.jsxs(CardContent,{className:"space-y-4",children:[jsxRuntime.jsx(Skeleton,{className:"h-12 w-full rounded-md border"}),jsxRuntime.jsx(Skeleton,{className:"h-48 w-full rounded-md border"}),jsxRuntime.jsxs("div",{className:"flex items-center justify-between pt-4",children:[jsxRuntime.jsx(Skeleton,{className:"h-9 w-[130px]"}),jsxRuntime.jsxs("div",{className:"flex items-center space-x-2",children:[jsxRuntime.jsx(Skeleton,{className:"h-9 w-20"})," ",jsxRuntime.jsx(Skeleton,{className:"h-9 w-24"})," ",jsxRuntime.jsx(Skeleton,{className:"h-9 w-9"})," ",jsxRuntime.jsx(Skeleton,{className:"h-9 w-9"})]})]})]})]}):jsxRuntime.jsxs(jsxRuntime.Fragment,{children:[jsxRuntime.jsxs(Card,{className:"w-full",children:[jsxRuntime.jsxs(CardHeader,{children:[" ",jsxRuntime.jsx(CardTitle,{className:"text-1xl font-bold",children:"Opportunities"})," "]}),jsxRuntime.jsx(CardContent,{children:jsxRuntime.jsx(DataTable,{columns:z,data:F,uniqueValues:Q})})]}),jsxRuntime.jsx(Dialog,{open:f,onOpenChange:ne=>{g(ne),ne||(R(null),_(""))},children:jsxRuntime.jsxs(DialogContent,{className:"@sm:max-w-[425px]",children:[jsxRuntime.jsxs(DialogHeader,{children:[jsxRuntime.jsx(DialogTitle,{children:"Send Opportunity Report"}),jsxRuntime.jsxs(DialogDescription,{children:["Enter the email address to send the report for opportunity: ",jsxRuntime.jsx("br",{}),jsxRuntime.jsx("span",{className:"font-semibold",children:(S==null?void 0:S.OpportunityName)||(S==null?void 0:S.Opportunity)||"N/A"}),(S==null?void 0:S.BidNumber)&&jsxRuntime.jsxs("span",{className:"block text-sm text-muted-foreground",children:["Bid Number: ",S.BidNumber]})]})]}),jsxRuntime.jsx("div",{className:"grid gap-4 py-4",children:jsxRuntime.jsxs("div",{className:"grid grid-cols-4 items-center gap-4",children:[jsxRuntime.jsx(Label$2,{htmlFor:"email",className:"text-right",children:"Email"}),jsxRuntime.jsx(Input,{id:"email",type:"email",value:b,onChange:ne=>_(ne.target.value),placeholder:"recipient@example.com",className:"col-span-3",disabled:V})]})}),jsxRuntime.jsxs(DialogFooter,{children:[jsxRuntime.jsx(Button,{variant:"outline",onClick:()=>g(!1),disabled:V,children:"Cancel"}),jsxRuntime.jsxs(Button,{type:"submit",onClick:q,disabled:V,children:[V&&jsxRuntime.jsx(LoaderCircle,{className:"mr-2 h-4 w-4 animate-spin"})," Send Report"]})]})]})})]})}function useLoadScript(t){const[e,n]=React.useState(!0),[o,l]=React.useState(null),[d,f]=React.useState(!1),g=()=>{n(!1),f(!0)};return React.useEffect(()=>{if(!document){const R=new Error(`[ScriptLoadingError] document not defined when attempting to load ${t}`);l(R);return}const b=document.querySelector(`script[src="${t}"]`);if(b!=null&&b.dataset.loaded){g();return}const _=b||document.createElement("script");b||(_.src=t);const S=()=>{_.dataset.loaded="1",g()};_.addEventListener("load",S),_.addEventListener("error",R=>{console.error("Failed to load script:",t,R);const C=new Error(`[ScriptLoadingError] Failed to load script: ${t}`);l(C)}),b||document.head.append(_)},[]),{isLoading:e,error:o,isSuccess:d}}const isGoogleReady=t=>t&&t.charts,isGoogleChartsReady=(t,e)=>{const{controls:n,toolbarItems:o,getChartEditor:l}=t;return e&&e.charts&&e.visualization&&e.visualization.ChartWrapper&&e.visualization.Dashboard&&(!n||e.visualization.ChartWrapper)&&(!l||e.visualization.ChartEditor)&&(!o||e.visualization.drawToolbar)},getGoogleInstanceFromWindow=t=>window.google;function useLoadGoogleCharts(t){const{chartVersion:e="current",chartPackages:n=["corechart","controls"],chartLanguage:o="en",mapsApiKey:l}=t,[d,f]=React.useState(null),[g,b]=React.useState(null),[_,S]=React.useState(null),{isLoading:R,error:C,isSuccess:E}=useLoadScript(t.chartLoaderScriptUrl||"https://www.gstatic.com/charts/loader.js");return React.useEffect(()=>{if(!E)return;const A=getGoogleInstanceFromWindow();if(!isGoogleReady(A)){const M=new Error("[ScriptInitializationError] Script loaded but Google not attached to window.");b(M);return}if(isGoogleChartsReady(t,A)){f(A);return}A.charts.load(e,{packages:n,language:o,mapsApiKey:l}),A.charts.setOnLoadCallback(()=>{if(!isGoogleChartsReady(t,A)){const M=new Error("[GoogleChartsInitializationError] Google Charts not ready after load callback.");console.error(M),S(M);return}f(A)})},[E]),{error:C||g||_,isLoading:R,google:d}}const chartDefaultProps={legend_toggle:!1,options:{},legendToggle:!1,getChartWrapper:()=>{},spreadSheetQueryParameters:{headers:1,gid:1},rootProps:{},chartWrapperParams:{},chartLoaderScriptUrl:"https://www.gstatic.com/charts/loader.js"},GoogleChartControls=t=>{const{isReady:e,chartControls:n,filter:o}=t;return!e||!n||!(n!=null&&n.length)?null:React.createElement(React.Fragment,null,n.filter(l=>{let{controlProp:d,control:f}=l;return o?o({control:f,controlProp:d}):!0}).map(l=>{let{control:d}=l;return React.createElement("div",{key:d.getContainerId(),id:d.getContainerId()})}))};let uniqueID=0;const generateUniqueID=()=>(uniqueID+=1,`reactgooglegraph-${uniqueID}`),Mr=class Mr{};Qt(Mr,"initializeControls",e=>{for(let n=0;n<e.length;n+=1){const{controlType:o,options:l,controlWrapperParams:d}=e[n].controlProp;d&&"state"in d&&e[n].control.setState(d.state),e[n].control.setOptions(l),e[n].control.setControlType(o)}}),Qt(Mr,"listenToControlEvents",(e,n)=>{const{google:o}=n;return e.flatMap(l=>{const{control:d,controlProp:f}=l,{controlEvents:g=[]}=f;return g.map(b=>{const{callback:_,eventName:S}=b;return o.visualization.events.addListener(d,S,function(){for(var R=arguments.length,C=new Array(R),E=0;E<R;E++)C[E]=arguments[E];_({chartWrapper:null,controlWrapper:d,props:n,google:o,eventArgs:C})})})})}),Qt(Mr,"createControlId",e=>{let n;return typeof e>"u"?n=`googlechart-control-${generateUniqueID()}`:n=e,n}),Qt(Mr,"createChartControls",e=>{const{controls:n,google:o}=e;return n?n.map((l,d)=>{const{controlID:f,controlType:g,options:b,controlWrapperParams:_}=l,S=Mr.createControlId(f);return{controlProp:l,control:new o.visualization.ControlWrapper({containerId:S,controlType:g,options:b,..._})}}):null}),Qt(Mr,"addControls",e=>{const{chartWrapper:n,chartDashboard:o}=e,l=Mr.createChartControls(e);return!l||!o||!n?null:(o.bind(l.map(d=>{let{control:f}=d;return f}),n),Mr.initializeControls(l),l)});let GoogleChartControlsInternal=Mr;const useCreateChartControls=t=>{const[e,n]=React__namespace.useState(null);return[React__namespace.useMemo(()=>!e||!t?null:t.map((l,d)=>{const f=e[d];return f?{controlProp:l,control:f}:void 0}).flatMap(l=>l?[l]:[]),[e,t]),n]},useListenToControlEvents=(t,e)=>{React__namespace.useEffect(()=>{const n=GoogleChartControlsInternal.listenToControlEvents(t??[],e);return()=>{n.forEach(o=>{e.google.visualization.events.removeListener(o)})}},[t,e])},useChartControls=t=>{const[e,n]=useCreateChartControls(t.controls);return useListenToControlEvents(e??[],t),{addControls:l=>{const d=GoogleChartControlsInternal.addControls(l);n((d==null?void 0:d.map(f=>f.control))??null)},renderControl:l=>{const{chartWrapper:d,chartDashboard:f}=t;return React__namespace.createElement(GoogleChartControls,{...t,isReady:!!(d&&f),chartControls:e,filter:l})}}},useChartId=t=>{const e=React__namespace.useRef(null);return{chartId:(()=>{const{graphID:l,graph_id:d}=t,f=l||d;let g;return f?g=f:g=e.current||generateUniqueID(),e.current=g,e.current})()}},DEFAULT_CHART_COLORS=["#3366CC","#DC3912","#FF9900","#109618","#990099","#3B3EAC","#0099C6","#DD4477","#66AA00","#B82E2E","#316395","#994499","#22AA99","#AAAA11","#6633CC","#E67300","#8B0707","#329262","#5574A6","#3B3EAC"],loadDataTableFromSpreadSheet=async function(t,e){let n=arguments.length>2&&arguments[2]!==void 0?arguments[2]:{};return new Promise((o,l)=>{const d=`${n.headers?`headers=${n.headers}`:"headers=0"}`,f=`${n.query?`&tq=${encodeURIComponent(n.query)}`:""}`,g=`${n.gid?`&gid=${n.gid}`:""}`,b=`${n.sheet?`&sheet=${n.sheet}`:""}`,_=`${n.access_token?`&access_token=${n.access_token}`:""}`,S=`${d}${g}${b}${f}${_}`,R=`${e}/gviz/tq?${S}`;new t.visualization.Query(R).send(E=>{E.isError()?l(`Error in query: ${E.getMessage()} ${E.getDetailedMessage()}`):o(E.getDataTable())})})},GRAY_COLOR="#CCCCCC",wr=class wr{};Qt(wr,"grayOutHiddenColumnsLabel",(e,n)=>{const{googleChartWrapper:o,options:l}=e;if(!o){console.error("googleChartWrapper is not defined");return}const d=o.getDataTable();if(!d)return;const f=d.getNumberOfColumns();if(n.length>0===!1)return;const b=Array.from({length:f-1}).map((_,S)=>{const R=wr.getColumnId(d,S+1);return n.includes(R)?GRAY_COLOR:l&&l.colors?l.colors[S]:DEFAULT_CHART_COLORS[S]});o.setOptions({...l,colors:b}),o.draw()}),Qt(wr,"listenToLegendToggle",(e,n)=>{const[o,l]=n,{google:d,googleChartWrapper:f}=e;if(!f){console.error("googleChartWrapper is not defined");return}return d.visualization.events.addListener(f,"select",()=>{const b=f.getChart().getSelection(),_=f.getDataTable();if(b.length===0||b[0].row!==null||!_)return;const S=b[0].column,R=wr.getColumnId(_,S);o!=null&&o.includes(R)?l(C=>[...C.filter(E=>E!==R)]):l(C=>[...C,R])})}),Qt(wr,"draw",async e=>{const{data:n,diffdata:o,rows:l,columns:d,options:f,chartType:g,formatters:b,spreadSheetUrl:_,spreadSheetQueryParameters:S,googleChartDashboard:R,googleChartWrapper:C,google:E,hiddenColumns:A,legendToggle:M,legend_toggle:I}=e;if(!C){console.error("draw was called with googleChartWrapper = null");return}let j,q=null;if(o){const te=E.visualization.arrayToDataTable(o.old),ne=E.visualization.arrayToDataTable(o.new);q=E.visualization[g].prototype.computeDiff(te,ne)}n?n instanceof E.visualization.DataTable?j=n:Array.isArray(n)?j=E.visualization.arrayToDataTable(n):j=new E.visualization.DataTable(n):l&&d?j=E.visualization.arrayToDataTable([d,...l]):_?j=await loadDataTableFromSpreadSheet(E,_,S):j=E.visualization.arrayToDataTable([]);const z=j.getNumberOfColumns(),Q=Array(z).fill(0).map((te,ne)=>{const se=wr.getColumnId(j,ne);return A.includes(se)?{label:j.getColumnLabel(ne),type:j.getColumnType(ne),calc:()=>null}:ne}),F=C.getChart();C.getChartType()==="Timeline"&&F&&F.clearChart(),C.setChartType(g),C.setOptions(f||{});const V=new E.visualization.DataView(j);V.setColumns(Q),C.setDataTable(V),C.draw(),R&&R.draw(j),q&&(C.setDataTable(q),C.draw()),b&&(wr.applyFormatters({dataTable:j,formatters:b,google:E}),C.setDataTable(j),C.draw()),(M===!0||I===!0)&&wr.grayOutHiddenColumnsLabel(e,A)}),Qt(wr,"getColumnId",(e,n)=>e.getColumnId(n)||e.getColumnLabel(n)),Qt(wr,"applyFormatters",e=>{let{dataTable:n,formatters:o,google:l}=e;for(let d of o)switch(d.type){case"ArrowFormat":{new l.visualization.ArrowFormat(d.options).format(n,d.column);return}case"BarFormat":{new l.visualization.BarFormat(d.options).format(n,d.column);return}case"ColorFormat":{const f=new l.visualization.ColorFormat(d.options),{ranges:g}=d;if(g)for(let b of g)f.addRange(...b);f.format(n,d.column);return}case"DateFormat":{new l.visualization.DateFormat(d.options).format(n,d.column);return}case"NumberFormat":{new l.visualization.NumberFormat(d.options).format(n,d.column);return}case"PatternFormat":{new l.visualization.PatternFormat(d.options).format(n,d.column);return}default:{console.warn(`Unknown formatter type: ${d.type}`);return}}});let GoogleChartInternal=wr;const useGoogleChartDataTable=t=>{const{google:e,googleChartWrapper:n,googleChartDashboard:o}=t,[l,d]=React__namespace.useState([]);React__namespace.useEffect(()=>{n&&GoogleChartInternal.draw({...t,hiddenColumns:l,googleChartWrapper:n,googleChartDashboard:o,google:e})},[l,t.data,t.rows,t.columns,t.options,t.chartLoaderScriptUrl,t.chartType,t.formatters,t.spreadSheetUrl,t.spreadSheetQueryParameters,t.legendToggle,t.legend_toggle]);const f=()=>{const{googleChartWrapper:_}=t;_&&_.draw()},g=_=>{const S=[],{legendToggle:R,legend_toggle:C}=t;if(GoogleChartInternal.draw({...t,hiddenColumns:l,googleChartWrapper:_,googleChartDashboard:o,google:e}),window.addEventListener("resize",f),C||R){const E=GoogleChartInternal.listenToLegendToggle(t,[l,d]);E&&S.push(E)}return S},b=(_,S)=>{window.removeEventListener("resize",f),S.forEach(R=>{e.visualization.events.removeListener(R)}),_.getChartType()==="Timeline"&&_.getChart()&&_.getChart().clearChart()};React__namespace.useEffect(()=>{if(!n)return;const _=g(n);return()=>{b(n,_)}},[n,g,b])},listenToEvents=t=>{const{chartEvents:e,google:n,googleChartWrapper:o}=t;if(e){if(!o){console.warn("listenToEvents was called before chart wrapper ready.");return}return e.map(l=>{let{eventName:d,callback:f}=l;return n.visualization.events.addListener(o,d,function(){for(var g=arguments.length,b=new Array(g),_=0;_<g;_++)b[_]=arguments[_];f({chartWrapper:o,props:t,google:n,eventArgs:b})})})}},useGoogleChartEvents=t=>{React.useEffect(()=>{if(!t.googleChartWrapper)return;const e=listenToEvents(t);return()=>{e==null||e.forEach(n=>{t.google.visualization.events.removeListener(n)})}},[t])},GoogleChart=t=>{const[e,n]=React__namespace.useState(null),[o,l]=React__namespace.useState(null),{addControls:d,renderControl:f}=useChartControls({...t,chartDashboard:o,chartWrapper:e});useGoogleChartEvents({...t,googleChartWrapper:e});const{chartId:g}=useChartId(t),b=React__namespace.useRef(null),_=React__namespace.useRef(null);React__namespace.useEffect(()=>{const{options:j,google:q,chartType:z,chartWrapperParams:Q,toolbarItems:F,getChartEditor:V,getChartWrapper:te,onLoad:ne}=t,se={chartType:z,options:j,containerId:g,...Q},ge=new q.visualization.ChartWrapper(se);ge.setOptions(j||{}),te==null||te(ge,q);const oe=new q.visualization.Dashboard(b.current);F&&q.visualization.drawToolbar(_.current,F);let Ae=null;V&&(Ae=new q.visualization.ChartEditor,V({chartEditor:Ae,chartWrapper:ge,google:q})),d({...t,chartDashboard:oe,chartWrapper:ge}),n(ge),l(oe),ne==null||ne(q,{google:q,chartWrapper:ge,chartEditor:Ae,chartDashboard:oe})},[]),useGoogleChartDataTable({...t,googleChartWrapper:e,googleChartDashboard:o});const S=()=>{const{width:j,height:q,options:z,style:Q,className:F,rootProps:V,google:te}=t,ne={height:q||z&&z.height,width:j||z&&z.width,...Q};return React__namespace.createElement("div",{id:g,style:ne,className:F,...V})},R=()=>t.toolbarItems?React__namespace.createElement("div",{ref:_}):null,{width:C,height:E,options:A,style:M}=t,I={height:E||A&&A.height,width:C||A&&A.width,...M};return t.render?React__namespace.createElement("div",{ref:b,style:I},React__namespace.createElement("div",{ref:_,id:"toolbar"}),t.render({renderChart:S,renderControl:f,renderToolbar:R})):React__namespace.createElement("div",{ref:b,style:I},f(j=>{let{controlProp:q}=j;return q.controlPosition!=="bottom"}),S(),f(j=>{let{controlProp:q}=j;return q.controlPosition==="bottom"}),R())},ChartContext=React__namespace.createContext(chartDefaultProps),ContextProvider=t=>{let{children:e,value:n}=t;return React__namespace.createElement(ChartContext.Provider,{value:n},e)},ChartView=t=>{const{google:e,isLoading:n,error:o}=useLoadGoogleCharts(t);return n?t.loader??null:o?t.errorElement??null:e?React.createElement(GoogleChart,{google:e,...t}):null},Chart=t=>{const e={...chartDefaultProps,...t};return React.createElement(ContextProvider,{value:e},React.createElement(ChartView,e))};var GoogleDataTableColumnRoleType;(function(t){t.annotation="annotation",t.annotationText="annotationText",t.certainty="certainty",t.emphasis="emphasis",t.interval="interval",t.scope="scope",t.style="style",t.tooltip="tooltip",t.domain="domain"})(GoogleDataTableColumnRoleType||(GoogleDataTableColumnRoleType={}));function parseHsl(t){const e=t.match(/(\d+\.?\d*)\s*(\d+\.?\d*)%\s*(\d+\.?\d*)%/);return e?{h:parseFloat(e[1]),s:parseFloat(e[2]),l:parseFloat(e[3])}:null}function hslToHex(t,e,n){n/=100;const o=e*Math.min(n,1-n)/100,l=d=>{const f=(d+t/30)%12,g=n-o*Math.max(Math.min(f-3,9-f,1),-1);return Math.round(255*g).toString(16).padStart(2,"0")};return`#${l(0)}${l(8)}${l(4)}`}const Treemap=React__namespace.forwardRef(({data:t,options:e,height:n="500px",className:o,loading:l,disableClick:d=!0,...f},g)=>{const b=React__namespace.useRef(null),[_,S]=React__namespace.useState(null);React__namespace.useEffect(()=>{if(!b.current)return;const E=b.current,A=()=>{const q=getComputedStyle(E).getPropertyValue("--primary").trim();if(q){const z=parseHsl(q);if(z){const{h:Q,s:F,l:V}=z;S({minColor:hslToHex(Q,F,Math.min(100,V+50)),midColor:hslToHex(Q,F,Math.min(100,V+35)),maxColor:hslToHex(Q,F,Math.min(100,V+20))})}return!0}return!1};if(A())return;let M=0;const I=20,j=setInterval(()=>{(A()||M>=I)&&clearInterval(j),M++},100);return()=>{j&&clearInterval(j)}},[]);const R=React__namespace.useMemo(()=>{const E={headerHeight:0,fontSize:14,showScale:!1,isHtml:!0,generateTooltip:(A,M)=>{var q;const I=(q=t[A+1])==null?void 0:q[0];if(!I)return"";const j=formatMoney(M);return`<div class="p-2 bg-background text-foreground border rounded-md shadow-lg">
|
|
1328
1328
|
<strong>${I}</strong><br>Value: ${j}
|
|
1329
1329
|
</div>`}};return _&&(!e||!e.colorAxis)&&(E.minColor=_.minColor,E.midColor=_.midColor,E.maxColor=_.maxColor),{...E,...e}},[t,e,_]),C=React__namespace.useMemo(()=>d?[{eventName:"select",callback:({chartWrapper:A})=>{A.getChart().setSelection(null)}}]:void 0,[d]);return React__namespace.useImperativeHandle(g,()=>b.current,[]),l?jsxRuntime.jsx("div",{ref:b,className:cn("w-full",o),style:{height:n},...f,children:jsxRuntime.jsx(Skeleton,{className:"h-full w-full"})}):!t||t.length<=2?jsxRuntime.jsx("div",{ref:b,className:cn("w-full flex items-center justify-center text-muted-foreground",o),style:{height:n},...f,children:"No data available"}):jsxRuntime.jsx("div",{ref:b,className:cn("w-full",o),style:{height:n},...f,children:jsxRuntime.jsx(Chart,{chartType:"TreeMap",width:"100%",height:"100%",data:t,options:R,chartEvents:C,loader:jsxRuntime.jsx(Skeleton,{className:"h-full w-full"})})})});Treemap.displayName="Treemap";const TopPercentTreemap=({data:t,topPercent:e=80,title:n,loading:o,...l})=>{const d=React__namespace.useMemo(()=>{if(!t||t.length===0)return[["ID","Parent","Value"],["Root",null,0]];const g=[...t].sort((A,M)=>M.value-A.value),_=g.reduce((A,M)=>A+M.value,0)*(e/100),S=[["ID","Parent","Value"],["Root",null,0]],R=[],C=[];let E=0;for(const A of g)E<_?(R.push(A),E+=A.value):C.push(A);if(R.forEach(A=>{S.push([A.name,"Root",A.value])}),C.length>0){const A=`More... (${C.length} items)`;S.push([A,"Root",0]),C.forEach(M=>{S.push([M.name,A,M.value])})}return S},[t,e]),f=React__namespace.useMemo(()=>({title:n,maxDepth:1}),[n]);return jsxRuntime.jsx(Treemap,{data:d,options:f,className:cn("h-full",l.className),loading:o,disableClick:!1,...l})};exports.ActiveOrdersCard=ActiveOrdersCard,exports.AiGeneratedContent=AiGeneratedContent,exports.Alert=Alert,exports.AlertDescription=AlertDescription,exports.AlertDialog=AlertDialog,exports.AlertDialogAction=AlertDialogAction,exports.AlertDialogCancel=AlertDialogCancel,exports.AlertDialogContent=AlertDialogContent,exports.AlertDialogDescription=AlertDialogDescription,exports.AlertDialogFooter=AlertDialogFooter,exports.AlertDialogHeader=AlertDialogHeader,exports.AlertDialogTitle=AlertDialogTitle,exports.AlertDialogTrigger=AlertDialogTrigger,exports.AlertTitle=AlertTitle,exports.AreaChart=AreaChart,exports.AssistantChat=AssistantChat,exports.Avatar=Avatar,exports.AvatarFallback=AvatarFallback,exports.AvatarFooter=AvatarFooter,exports.AvatarImage=AvatarImage,exports.Badge=Badge,exports.Button=Button,exports.Card=Card,exports.CardContent=CardContent,exports.CardDescription=CardDescription,exports.CardFooter=CardFooter,exports.CardHeader=CardHeader,exports.CardTitle=CardTitle,exports.ChatLayout=ChatLayout,exports.ChatProvider=ChatProvider,exports.Checkbox=Checkbox,exports.Command=Command,exports.CommandDialog=CommandDialog,exports.CommandEmpty=CommandEmpty,exports.CommandGroup=CommandGroup,exports.CommandInput=CommandInput,exports.CommandItem=CommandItem,exports.CommandList=CommandList,exports.CommandSeparator=CommandSeparator,exports.CommandShortcut=CommandShortcut,exports.CountryFlag=CountryFlag,exports.DataTable=DataTable,exports.Dialog=Dialog,exports.DialogClose=DialogClose,exports.DialogContent=DialogContent,exports.DialogDescription=DialogDescription,exports.DialogFooter=DialogFooter,exports.DialogHeader=DialogHeader,exports.DialogOverlay=DialogOverlay,exports.DialogPortal=DialogPortal,exports.DialogTitle=DialogTitle,exports.DialogTrigger=DialogTrigger,exports.DropdownMenu=DropdownMenu,exports.DropdownMenuCheckboxItem=DropdownMenuCheckboxItem,exports.DropdownMenuContent=DropdownMenuContent,exports.DropdownMenuGroup=DropdownMenuGroup,exports.DropdownMenuItem=DropdownMenuItem,exports.DropdownMenuLabel=DropdownMenuLabel,exports.DropdownMenuPortal=DropdownMenuPortal,exports.DropdownMenuRadioGroup=DropdownMenuRadioGroup,exports.DropdownMenuRadioItem=DropdownMenuRadioItem,exports.DropdownMenuSeparator=DropdownMenuSeparator,exports.DropdownMenuShortcut=DropdownMenuShortcut,exports.DropdownMenuSub=DropdownMenuSub,exports.DropdownMenuSubContent=DropdownMenuSubContent,exports.DropdownMenuSubTrigger=DropdownMenuSubTrigger,exports.DropdownMenuTrigger=DropdownMenuTrigger,exports.ExploreManufacturers=ExploreManufacturers,exports.GeminiApiKeyProvider=GeminiApiKeyProvider,exports.GeneralDocumentCard=GeneralDocumentCard,exports.Input=Input,exports.InputOTP=InputOTP,exports.InputOTPGroup=InputOTPGroup,exports.InputOTPSeparator=InputOTPSeparator,exports.InputOTPSlot=InputOTPSlot,exports.Label=Label$2,exports.Layout=Layout,exports.ManufacturerCard=ManufacturerCard,exports.ManufacturerGetStartedButton=ManufacturerGetStartedButton,exports.ManufacturerOverviewPage=ManufacturerOverviewPage,exports.ManufacturerReorderingCard=ManufacturerReorderingCard,exports.MultiSelect=MultiSelect,exports.Navbar=Navbar,exports.OpportunitiesTable=OpportunitiesTable,exports.PageHeader=PageHeader,exports.PartnerCard=PartnerCard,exports.PartnerRelationshipPage=PartnerRelationshipPage,exports.Popover=Popover,exports.PopoverAnchor=PopoverAnchor,exports.PopoverContent=PopoverContent,exports.PopoverTrigger=PopoverTrigger,exports.Preloader=Preloader,exports.ProductCard=ProductCard,exports.ProductImage=ProductImage,exports.ProductInventoryGrid=ProductInventoryGrid,exports.ProductOverviewPage=ProductOverviewPage,exports.Progress=Progress,exports.RadioGroup=RadioGroup$1,exports.RadioGroupItem=RadioGroupItem,exports.ResellerBillingOverviewCard=ResellerBillingOverviewCard,exports.ResellerCard=ResellerCard,exports.ResellerOverview=ResellerOverview,exports.ResellerQualificationsCard=ResellerQualificationsCard,exports.ReturnsTable=ReturnsTable,exports.RichTextEditor=RichTextEditor,exports.SalesChart=SalesChart,exports.SalesOverviewCard=SalesOverviewCard,exports.ScrollArea=ScrollArea,exports.ScrollBar=ScrollBar,exports.Select=Select,exports.SelectContent=SelectContent,exports.SelectGroup=SelectGroup,exports.SelectItem=SelectItem,exports.SelectLabel=SelectLabel,exports.SelectScrollDownButton=SelectScrollDownButton,exports.SelectScrollUpButton=SelectScrollUpButton,exports.SelectTrigger=SelectTrigger,exports.SelectValue=SelectValue,exports.Separator=Separator$1,exports.Sheet=Sheet,exports.SheetClose=SheetClose,exports.SheetContent=SheetContent,exports.SheetDescription=SheetDescription,exports.SheetFooter=SheetFooter,exports.SheetHeader=SheetHeader,exports.SheetOverlay=SheetOverlay,exports.SheetPortal=SheetPortal,exports.SheetTitle=SheetTitle,exports.SheetTrigger=SheetTrigger,exports.Sidebar=Sidebar,exports.SidebarContent=SidebarContent,exports.SidebarFooter=SidebarFooter,exports.SidebarGroup=SidebarGroup,exports.SidebarGroupAction=SidebarGroupAction,exports.SidebarGroupContent=SidebarGroupContent,exports.SidebarGroupLabel=SidebarGroupLabel,exports.SidebarHeader=SidebarHeader,exports.SidebarInput=SidebarInput,exports.SidebarInset=SidebarInset,exports.SidebarMenu=SidebarMenu,exports.SidebarMenuAction=SidebarMenuAction,exports.SidebarMenuBadge=SidebarMenuBadge,exports.SidebarMenuButton=SidebarMenuButton,exports.SidebarMenuItem=SidebarMenuItem,exports.SidebarMenuSkeleton=SidebarMenuSkeleton,exports.SidebarMenuSub=SidebarMenuSub,exports.SidebarMenuSubButton=SidebarMenuSubButton,exports.SidebarMenuSubItem=SidebarMenuSubItem,exports.SidebarProvider=SidebarProvider,exports.SidebarRail=SidebarRail,exports.SidebarSeparator=SidebarSeparator,exports.SidebarTrigger=SidebarTrigger,exports.Skeleton=Skeleton,exports.Switch=Switch,exports.Table=Table,exports.TableBody=TableBody,exports.TableCaption=TableCaption,exports.TableCell=TableCell,exports.TableFooter=TableFooter,exports.TableHead=TableHead,exports.TableHeader=TableHeader,exports.TableRow=TableRow,exports.Tabs=Tabs,exports.TabsContent=TabsContent,exports.TabsList=TabsList,exports.TabsTrigger=TabsTrigger,exports.Textarea=Textarea,exports.Toast=Toast,exports.ToastAction=ToastAction,exports.ToastClose=ToastClose,exports.ToastDescription=ToastDescription,exports.ToastProvider=ToastProvider,exports.ToastTitle=ToastTitle,exports.ToastViewport=ToastViewport,exports.Toaster=Toaster,exports.Tooltip=Tooltip$1,exports.TooltipContent=TooltipContent,exports.TooltipProvider=TooltipProvider,exports.TooltipTrigger=TooltipTrigger,exports.TopPercentTreemap=TopPercentTreemap,exports.Topbar=Topbar,exports.Treemap=Treemap,exports.badgeVariants=badgeVariants,exports.buttonVariants=buttonVariants,exports.toast=toast,exports.useChat=useChat,exports.useGeminiApiKey=useGeminiApiKey,exports.useIsMobile=useIsMobile,exports.useSidebar=useSidebar,exports.useToast=useToast,Object.defineProperty(exports,Symbol.toStringTag,{value:"Module"})});
|