@mohsinonxrm/pptb-dataverse-request-studio 1.4.0-beta.3 → 1.5.0-beta.1
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/CHANGELOG.md +375 -0
- package/README.md +81 -11
- package/SECURITY.md +8 -1
- package/dist/assets/AssociateMode-mu2ai0TV.js +1 -0
- package/dist/assets/AssociateTargetsEditor-BoH9Qxe8.js +1 -0
- package/dist/assets/BatchMode-BVAfFgPy.js +11 -0
- package/dist/assets/BinaryColumnPickers-DYpKoRIO.js +1 -0
- package/dist/assets/BulkDeleteMode-Df-XirlR.js +1 -0
- package/dist/assets/BulkWriteMode-UXREEvbe.js +6 -0
- package/dist/assets/DisassociateMode-CKBL5nUo.js +2 -0
- package/dist/assets/ExecuteWorkflowMode-4EWco-ze.js +1 -0
- package/dist/assets/ManageFileMode-BFNwxuEY.js +1 -0
- package/dist/assets/ManageImageMode-DX0AdPN1.js +1 -0
- package/dist/assets/MergeMode-BzyXLu1b.js +1 -0
- package/dist/assets/PredefinedQueryMode-BT-HdZHF.js +1 -0
- package/dist/assets/RetrieveNextLinkMode-QBuIwdgS.js +1 -0
- package/dist/assets/{cssMode-B4BP9f3X.js → cssMode-DRNC4UuD.js} +1 -1
- package/dist/assets/{freemarker2-DFKOu_2v.js → freemarker2-BITb8GyO.js} +1 -1
- package/dist/assets/{handlebars-cWHtgvCj.js → handlebars-BbDVduNH.js} +1 -1
- package/dist/assets/{html-DSPQITYl.js → html-Ru2Cy2VS.js} +1 -1
- package/dist/assets/{htmlMode-Cr-uAXsT.js → htmlMode-DeMh8vPt.js} +1 -1
- package/dist/assets/index-XmEQbXiX.js +703 -0
- package/dist/assets/{javascript-B3oRul8j.js → javascript-DLj2yjBO.js} +1 -1
- package/dist/assets/{jsonMode-_zXsQ367.js → jsonMode-DOHFeg2H.js} +1 -1
- package/dist/assets/{liquid-Cib5dNaW.js → liquid-udbJGOUP.js} +1 -1
- package/dist/assets/{mdx-8A_8JwPK.js → mdx-B6ABiFDH.js} +1 -1
- package/dist/assets/{monacoSetup-DObeMDBe.js → monacoSetup-CEhMjQNN.js} +3 -3
- package/dist/assets/{python-DsudPCj1.js → python-DDgBOsRh.js} +1 -1
- package/dist/assets/{razor-CrmV2uj7.js → razor-DGf0KCTP.js} +1 -1
- package/dist/assets/{tsMode-BnycW89y.js → tsMode-D4ZDTisA.js} +1 -1
- package/dist/assets/{typescript-Bs6iTDav.js → typescript-CJFgy1iR.js} +1 -1
- package/dist/assets/{xml-DuKZPRNV.js → xml-BXhJpCm5.js} +1 -1
- package/dist/assets/{yaml-DDDa6myK.js → yaml-B7iGwJkY.js} +1 -1
- package/dist/index.html +1 -1
- package/package.json +10 -3
- package/dist/assets/AssociateMode-Bs_R9XbQ.js +0 -1
- package/dist/assets/AssociateTargetsEditor-CVWE3tbv.js +0 -1
- package/dist/assets/BatchMode-XGXMc2XF.js +0 -11
- package/dist/assets/BinaryColumnPickers-mrnLqk3Z.js +0 -1
- package/dist/assets/BulkDeleteMode-DowWcbnA.js +0 -1
- package/dist/assets/BulkWriteMode-Dt3M0dGV.js +0 -6
- package/dist/assets/DisassociateMode-qIc2CUpE.js +0 -2
- package/dist/assets/ExecuteWorkflowMode-Ce6sKYci.js +0 -1
- package/dist/assets/ManageFileMode-CcNSQkJf.js +0 -1
- package/dist/assets/ManageImageMode-Dn4P4D6H.js +0 -1
- package/dist/assets/MergeMode-DzPQq2Ao.js +0 -1
- package/dist/assets/PredefinedQueryMode-CaQqp2lm.js +0 -1
- package/dist/assets/RetrieveNextLinkMode-BNbknSwe.js +0 -1
- package/dist/assets/index-D0g0tm7R.js +0 -702
|
@@ -0,0 +1,11 @@
|
|
|
1
|
+
import{aq as Dt,cE as Ft,e as Ue,bH as ze,f as lt,c6 as _t,c7 as Lt,c8 as Ht,cF as Ut,cG as zt,cH as Wt,cI as Gt,cJ as Vt,b$ as Jt,c1 as Kt,bZ as We,bQ as Qt,bT as Xt,bF as Yt,bI as Zt,bJ as es,cK as ts,cL as ss,cM as ns,cN as os,cO as rs,cP as as,cQ as is,cR as ls,cS as cs,cT as ds,an as us,ba as hs,bb as ps,cU as ms,cV as fs,cW as gs,cX as bs,cY as xs,ar as ys,I as vs,aU as $s,cZ as ct,c_ as js,c$ as ws,d0 as re,n as dt,l as w,u as Ss,b3 as ks,d1 as Es,c2 as Ts,A as t,ah as ue,cl as ut,aL as je,Y as C,d2 as ht,d3 as pt,aH as we,N as J,O as K,ad as H,b4 as ge,b5 as be,ae as W,a2 as j,al as mt,a3 as M,_ as Se,aJ as ce,d4 as ae,d5 as Ie,d6 as Ce,bl as Rs,bm as Ge,d7 as Oe,aA as Is,V as ne,d8 as Cs,d9 as Os,da as qs,db as Bs,dc as Ms,dd as Ps,W as ke,aW as As,cm as Ns,$ as Ds,a0 as Fs,de as _s,df as Ls,dg as Hs,dh as Us,a5 as zs,a6 as Ws,a7 as Gs,a8 as Vs,a9 as Js,bx as Ks,ac as Qs,k as Ee,af as Xs,b9 as Ys,di as Zs,dj as en,dk as Ve,E as Je,dl as tn,dm as sn,dn as nn,ch as xe,au as on,dp as rn,be as an,p as ye,q as Ke,t as ln,dq as cn,dr as dn,ds as un,dt as hn,ck as pn,du as Qe,J as mn,K as fn,U as gn,S as bn}from"./index-XmEQbXiX.js";const ve=e=>e.status>=400;function xn(e,s){const o=new Map,n=[];for(const p of s)p.contentId&&!o.has(p.contentId)?o.set(p.contentId,p):n.push(p);o.size===0&&n.length===e.items.length&&(e.items.forEach((p,x)=>o.set(p.contentId,n[x])),n.length=0);const a=s.some(ve),i=e.transaction&&a,r=e.items.map(p=>{const x=o.get(p.contentId);return x?{itemId:p.item.id,contentId:p.contentId,outcome:i&&!ve(x)?"rolled-back":"done",status:x.status,statusText:x.statusText,headers:x.headers,body:x.body}:{itemId:p.item.id,contentId:p.contentId,outcome:i?"rolled-back":"not-run"}}),b=n.find(ve);return{items:r,segment:{transaction:e.transaction,contentIds:e.items.map(p=>p.contentId),ms:0,ok:!a&&r.every(p=>p.outcome==="done"),changesetError:b}}}function yn(e){const s=e.segments.some(x=>!x.skipped&&(!x.error||x.requestFailed)),o=e.items.length;let n=0,a=0,i=0,r=0,b=0;for(const x of e.items)x.outcome==="done"?(x.status??0)>=400?a++:n++:x.outcome==="rolled-back"?i++:x.outcome==="not-run"?r++:b++;const p=[`${o} request${o===1?"":"s"}`];return a&&p.push(`${a} failed`),i&&p.push(`${i} rolled back`),r&&p.push(`${r} not run`),b&&p.push(`${b} no result`),o>0&&n===o&&p.push("all succeeded"),{status:s?200:0,summary:p.join(" · "),succeeded:n}}const vn=/additional headers were rejected|header consent/i,ft=/invalid content id correlation|missing operation results/i,$n=/invalid content id correlation/i;function jn(e){return e.replace(/^\s*Error invoking remote method '[^']*':\s*/i,"").replace(/^(?:\w*Error:\s*)+/,"").trim()}function wn(e,s){const o=jn(e);return vn.test(o)?`Power Platform ToolBox didn’t send this batch because its request headers weren’t approved, so nothing reached Dataverse. Send again and allow the headers when ToolBox asks, or remove them. Host message: ${o}`:!s.transaction&&s.continueOnError&&$n.test(o)?`A request in this batch failed, and Power Platform ToolBox couldn’t read the continue-on-error response because more requests followed the failed one (a known ToolBox batch-parser bug). Dataverse still ran every request: the ones that succeeded were applied. To see each result, put requests that might fail last in the batch, or send them on their own. Host message: ${o}`:!s.transaction&&!s.continueOnError&&ft.test(o)?`A request failed and Dataverse stopped the batch there. Requests before it were applied; the rest didn’t run. This version of Power Platform ToolBox can’t return partial results without continue-on-error — turn on Continue on error to see each request’s result. Host message: ${o}`:o}async function Sn(e,s){const o=performance.now(),n=[],a=[];let i=!1;for(const r of e){const b=r.items.map(h=>h.contentId);if(i){a.push({transaction:r.transaction,contentIds:b,ms:0,ok:!1,skipped:!0});for(const h of r.items)n.push({itemId:h.item.id,contentId:h.contentId,outcome:"not-run"});continue}const p=r.items.map(gt),x=!r.transaction&&s.continueOnError?{Prefer:"odata.continue-on-error"}:void 0,m=performance.now();try{const h=r.transaction?await Ue.executeTransaction(p,x):await Ue.executeBatch(p,x),c=xn(r,h);c.segment.ms=Math.round(performance.now()-m),a.push(c.segment),n.push(...c.items),!c.segment.ok&&!s.continueOnError&&(i=!0)}catch(h){const c=h instanceof Error?h.message:String(h);x||p.some(g=>g.headers&&Object.keys(g.headers).length),a.push({transaction:r.transaction,contentIds:b,ms:Math.round(performance.now()-m),ok:!1,requestFailed:ft.test(c),error:wn(c,{transaction:r.transaction,continueOnError:s.continueOnError})});for(const g of r.items)n.push({itemId:g.item.id,contentId:g.contentId,outcome:r.transaction?"rolled-back":"unknown"});s.continueOnError||(i=!0)}}return{ms:Math.round(performance.now()-o),ok:a.every(r=>r.ok),items:n,segments:a}}function gt(e){const s=e.wire,o={method:s.method,url:s.path,contentId:e.contentId};return Object.keys(s.headers).length>0&&(o.headers={...s.headers}),s.body!==void 0&&(o.body=s.body),o}function kn(){return Dt()?Ft()?null:"Sending a $batch requires Power Platform ToolBox 1.2.7 or later.":"Run Dataverse Request Studio inside Power Platform ToolBox to send a batch."}const En=new Set(["retrieve-multiple","retrieve-single","predefined-query","create","update","upsert","delete","merge","associate","disassociate","exec-action","exec-function","exec-workflow"]),Tn=new Set(["authorization","accept","content-type","content-length","odata-version","odata-maxversion"]);function Xe(e,s){return{id:`__batch__${e}`,name:e,value:s,enabled:!0,builtin:!0}}function L(e){let s=(e.headers??[]).map(a=>a.name==="MSCRM.SuppressDuplicateDetection"&&e.duplicateDetection!==void 0?{...a,enabled:e.duplicateDetection,value:"false"}:a);const o=e.concurrency?xs(e.concurrency):null;if(o&&s.push(Xe(o.name,o.value)),e.suppressDuplicateDetection&&s.push(Xe("MSCRM.SuppressDuplicateDetection","true")),e.bypass){const a=e.bypassCustomPlugins&&e.bypass.businessLogic==="none"?{...e.bypass,businessLogic:"sync",useLegacyHeader:!0}:e.bypass;s=ys(s,a)}const n=vs(s,e.prefer?$s(e.prefer):null);return Object.fromEntries(Object.entries(n).filter(([a])=>!Tn.has(a.toLowerCase())))}function $e(e,s,o,n,a,i){return ct("custom",{label:e,source:s,method:o,url:ws(n),body:i&&Object.keys(i).length>0?js(i):i?"{}":"",headers:Object.entries(a).map(([r,b])=>({name:r,value:b,enabled:!0}))})}function Rn(e){const{name:s}=e,o=(n,a,i,r)=>a?{ok:!0,items:[$e(s,s,n,a,i,r)]}:{ok:!1,reason:"its table isn’t available on this connection"};try{switch(e.modeId){case"retrieve-multiple":{const n=gs(e.state);return o("GET",bs(n).relativeUrl,L(n))}case"retrieve-single":{const n=ms(e.state);return o("GET",fs(n).relativeUrl,L(n))}case"predefined-query":{const n=hs(e.state);return o("GET",ps(n).relativeUrl,L(n))}case"create":{const n=cs(e.state);return o("POST",ds(n).relativeUrl,L(n),us(n))}case"update":{const n=as(e.state);return o(n.method,is(n).relativeUrl,L(n),ls(n))}case"upsert":{const n=ns(e.state);return o("PATCH",os(n).relativeUrl,L(n),rs(n))}case"delete":{const n=ts(e.state);return o("DELETE",ss(n).relativeUrl,L(n))}case"merge":{const n=Yt(e.state);return o("POST",Zt(n).relativeUrl,L(n),es(n))}case"associate":{const n=Qt(e.state),a=L(n),i=Xt(n);return i.length===0?{ok:!1,reason:"the request is incomplete"}:{ok:!0,items:i.map(r=>$e(`${s} → ${r.targetId}`,s,r.method,r.relativeUrl,We(r.method,a),r.body))}}case"disassociate":{const n=Jt(e.state),a=L(n),i=Kt(n);return i.length===0?{ok:!1,reason:"the request is incomplete"}:{ok:!0,items:i.map(r=>$e(r.targetId?`${s} × ${r.targetId}`:s,s,r.method,r.relativeUrl,We(r.method,a),r.body))}}case"exec-action":{const n=Wt(e.state);return o("POST",Gt(n).relativeUrl,L(n),Vt(n))}case"exec-function":{const n=Ut(e.state);return o("GET",zt(n).relativeUrl,L(n))}case"exec-workflow":{const n=_t(e.state);return o("POST",Lt(n).relativeUrl,L(n),Ht(n))}default:return{ok:!1,reason:"file, image and attachment requests can’t be sent in a batch"}}}catch(n){return{ok:!1,reason:n instanceof Error?n.message:String(n)}}}function In(e){if(e&&typeof e=="object"&&"table"in e){const s=e.table;if(typeof s=="string")return s}return""}async function Cn(e){const s=In(e.state);s&&await ze.getTable(s).catch(()=>{});const o=e.state?.navProperty;if(s&&typeof o=="string"&&o){const n=lt(s)?.navigationProperties.find(a=>a.name===o)?.targetEntity;n&&await ze.getTable(n).catch(()=>{})}return Rn(e)}const U=`\r
|
|
2
|
+
`;function On(e){return/^\$\d+/.test(e)?e:`${re}/${e}`}function qn(e,s){const o=s.toLowerCase();return Object.keys(e).some(n=>n.toLowerCase()===o)}function Te({contentId:e,wire:s}){const o=["Content-Type: application/http","Content-Transfer-Encoding: binary",`Content-ID: ${e}`,"",`${s.method} ${On(s.path)} HTTP/1.1`];for(const[n,a]of Object.entries(s.headers))o.push(`${n}: ${a}`);return s.body!==void 0&&!qn(s.headers,"Content-Type")&&o.push("Content-Type: application/json; type=entry"),o.push("",s.body??""),o.join(U)}let Ye=0;function de(e){Ye+=1;const s=typeof crypto<"u"&&"randomUUID"in crypto?crypto.randomUUID():`${Date.now().toString(16)}-${Ye.toString(16)}-${Math.random().toString(16).slice(2)}`;return`${e}_${s}`}function bt(e,s={}){const o=s.batch??de("batch");let n=0,a="";for(const i of e)if(i.parts.length!==0)if(i.atomic){const r=s.changeset?.(n)??de("changeset");n+=1,a+=`--${o}${U}Content-Type: multipart/mixed; boundary=${r}${U}${U}`;for(const b of i.parts)a+=`--${r}${U}${Te(b)}${U}`;a+=`--${r}--${U}`}else for(const r of i.parts)a+=`--${o}${U}${Te(r)}${U}`;return a+=`--${o}--${U}`,{boundary:o,contentType:`multipart/mixed; boundary=${o}`,body:a}}const xt=/boundary=(?:"([^"]+)"|([^;\s]+))/i;function Bn(e,s){const o=xt.exec(e);if(o)return o[1]||o[2];const n=/^\s*--([^\r\n]+)/.exec(s);return n?n[1].trim():null}function Ze(e){const s={};for(const o of e.split(/\r?\n/)){const n=o.indexOf(":");if(n<=0)continue;const a=o.slice(0,n).trim().toLowerCase(),i=o.slice(n+1).trim();s[a]=s[a]?`${s[a]}, ${i}`:i}return s}function Mn(e,s){const o=`--${s}`,n=[];let a=e.indexOf(o);if(a<0)throw new Error(`Response boundary "${s}" not found.`);for(;a>=0;){if(a+=o.length,e.startsWith("--",a))return n;const i=e.indexOf(o,a);if(i<0)throw new Error("Response is missing its closing boundary.");n.push(e.slice(a,i).replace(/^\r?\n/,"").replace(/\r?\n$/,"")),a=i}return n}function et(e){const s=/\r?\n\r?\n/.exec(e);return s?[e.slice(0,s.index),e.slice(s.index+s[0].length)]:[e,""]}function Pn(e,s=""){const o=Bn(s,e);if(!o)throw new Error("No multipart boundary in the Content-Type or the body.");let n=0;const a=(i,r,b)=>Mn(i,r).flatMap(p=>{const[x,m]=et(p),h=Ze(x),c=xt.exec(h["content-type"]??"");if(c){const V=n++;return a(m,c[1]||c[2],V)}const g=m.search(/HTTP\/1\.[01]\s+\d{3}/i);if(g<0)throw new Error("A response part has no HTTP status line.");const[k,O]=et(m.slice(g)),[D,...A]=k.split(/\r?\n/),G=/^HTTP\/1\.[01]\s+(\d{3})(?:\s+(.*))?$/i.exec(D.trim());if(!G)throw new Error(`Malformed status line: ${D}`);const I=O.trim();let P;if(I)try{P=JSON.parse(I)}catch{P=I}const q={status:Number(G[1]),statusText:G[2]?.trim()||void 0,headers:Ze(A.join(`
|
|
3
|
+
`))};return h["content-id"]&&(q.contentId=h["content-id"]),P!==void 0&&(q.body=P),b!==void 0&&(q.changeset=b),[q]});return a(e,o)}const yt={http:"HTTP ($batch)",fetch:"fetch (JavaScript)",pptb:"PPTB dataverseAPI"};function vt(e){const s=[];let o=null;for(const n of e)n.wire&&(n.group!==o&&s.push({atomic:n.group.atomic,parts:[]}),s[s.length-1].parts.push({contentId:n.contentId,wire:n.wire}),o=n.group);return s}function tt(e,s){return["OData-MaxVersion: 4.0","OData-Version: 4.0","If-None-Match: null","Accept: application/json",`Content-Type: ${e}`,...s?["Prefer: odata.continue-on-error"]:[]]}const An=e=>e.replace(/\r\n/g,`
|
|
4
|
+
`);function Nn(e,s){const o=s.orgUrl||"[Organization URI]",n=bt(vt(s.items),s.boundaries);switch(e){case"http":return An([`POST ${o}${re}/$batch HTTP/1.1`,...tt(n.contentType,s.continueOnError),"",n.body].join(U));case"fetch":{const a=n.body.split(U);a[a.length-1]===""&&a.pop();const i=tt(n.contentType,s.continueOnError).filter(r=>!r.startsWith("If-None-Match")).map(r=>{const b=r.indexOf(":");return` ${JSON.stringify(r.slice(0,b))}: ${JSON.stringify(r.slice(b+1).trim())},`});return["// Dataverse $batch — every line of the body must end in CRLF.","const body = [",...a.map(r=>` ${JSON.stringify(r)},`),"].join('\\r\\n') + '\\r\\n';","",`const res = await fetch(${JSON.stringify(`${o}${re}/$batch`)}, {`," method: 'POST',"," headers: {"," Authorization: `Bearer ${accessToken}`,",...i," },"," body,","});","","// The response is multipart/mixed too: one part per request, change sets nested.","console.log(res.status, res.headers.get('Content-Type'));","console.log(await res.text());"].join(`
|
|
5
|
+
`)}case"pptb":{if(s.plan.length===0)return"// Add a request to see the host calls.";const a=["// What Dataverse Request Studio sends through Power Platform ToolBox (1.2.7+).","// The host writes the multipart body; each change set is its own call."];return s.plan.length>1&&a.push(`// ${s.plan.length} calls, in order.${s.continueOnError?"":" A failed call stops the rest."}`),s.plan.forEach((i,r)=>{const b=i.items.filter(m=>m.wire).map(gt),p=i.transaction?"executeTransaction":"executeBatch",x=!i.transaction&&s.continueOnError?", undefined, { Prefer: 'odata.continue-on-error' }":"";a.push("",`const results${r+1} = await dataverseAPI.${p}(${JSON.stringify(b,null,2)}${x});`)}),a.push("","// Each result: { contentId, status, statusText, headers, body }"),a.join(`
|
|
6
|
+
`).replace(/\\r\\n/g,"\\n")}}}const Dn=/^\{?[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}\}?$/i,B=e=>JSON.stringify(e),Y=e=>`new Guid(${B(e.replace(/[{}]/g,""))})`;function Z(e,s){return s.logicalOf(e)??e.replace(/s$/,"")}function Fn(e){const s=/^([A-Za-z_][\w]*)\(([^)]+)\)$/.exec(e.trim());return s?{set:s[1],id:s[2]}:null}function _n(e,s,o,n,a){if(o===null)return"null";const i=n.attrType(e,s);switch(i){case"Picklist":case"State":case"Status":return`new OptionSetValue(${Number(o)})`;case"MultiSelectPicklist":return`new OptionSetValueCollection { ${String(o).split(",").filter(Boolean).map(r=>`new OptionSetValue(${Number(r)})`).join(", ")} }`;case"Money":return`new Money(${Number(o)}m)`;case"Decimal":return`${Number(o)}m`;case"BigInt":return`${Number(o)}L`;case"DateTime":return`DateTime.Parse(${B(String(o))})`;case"Uniqueidentifier":return Y(String(o))}return typeof o=="string"?B(o):typeof o=="boolean"?String(o):typeof o=="number"?(i||a.push(`${s}: confirm the type (int / OptionSetValue / Money / decimal)`),String(o)):(a.push(`${s}: nested value not converted`),null)}function Ln(e,s,o,n){const a=[];for(const[i,r]of Object.entries(s)){if(i.endsWith("@odata.bind")){let p=i.slice(0,-11);if(!o.attrType(e,p)&&p.includes("_")){const m=p.slice(0,p.lastIndexOf("_"));o.attrType(e,m)&&(p=m)}const x=typeof r=="string"?Fn(r.replace(/^.*\/api\/data\/v[\d.]+\//,"")):null;typeof r=="string"&&/^\$\d+$/.test(r)?n.push(`${p}: ${r} referenced an earlier request — ExecuteMultiple has no Content-ID references; set the id returned by that request`):x?a.push(`[${B(p)}] = new EntityReference(${B(Z(x.set,o))}, ${Y(x.id)}),`):n.push(`${p}: couldn't convert the @odata.bind value`);continue}if(i.includes("@"))continue;const b=_n(e,i,r,o,n);b!==null&&a.push(`[${B(i)}] = ${b},`)}return a}function st(e){if(!e)return{};try{const s=JSON.parse(e);return s&&typeof s=="object"&&!Array.isArray(s)?s:{}}catch{return{}}}const Hn=(e,s)=>e.map(o=>" ".repeat(s)+o);function nt(e){return e?`new ColumnSet(${e.split(",").map(s=>B(s.trim().replace(/^_(.+)_value$/,"$1"))).join(", ")})`:"new ColumnSet(true)"}function Un(e,s){const o=e.wire;if(!o)return[`// $${e.contentId}: has errors — fix it in the Builder.`];const n=[],a=[],i=e.item,r=`// $${e.contentId} ${o.method} ${o.path}`,b=m=>(a.push(r,...n.map(h=>`// TODO ${h}`),...m),a),p=Dn.test(i.recordId.trim());if(i.op==="create"||i.op==="update"){const m=Z(i.entitySet,s);i.op==="update"&&!p&&n.push(`record id ${i.recordId} isn't a GUID — use new Entity(logicalName, keyAttributes) for an alternate key`);const h=i.op==="update"&&p?`new Entity(${B(m)}, ${Y(i.recordId.trim())})`:`new Entity(${B(m)})`,c=Ln(m,st(o.body),s,n);return b([`requests.Add(new ${i.op==="create"?"CreateRequest":"UpdateRequest"}`,"{",` Target = ${h}`," {",...Hn(c,8)," },","});"])}if(i.op==="delete"){const m=Z(i.entitySet,s);return p||n.push(`record id ${i.recordId} isn't a GUID`),b([`requests.Add(new DeleteRequest { Target = new EntityReference(${B(m)}, ${Y(i.recordId.trim())}) });`])}if(i.op==="retrieve"){const m=Z(i.entitySet,s),h=new URLSearchParams(i.query.trim().replace(/^\?/,"")),c=h.get("$select");if(i.recordId.trim())return b(["requests.Add(new RetrieveRequest","{",` Target = new EntityReference(${B(m)}, ${Y(i.recordId.trim())}),`,` ColumnSet = ${nt(c)},`,"});"]);const g=h.get("$top");for(const k of["$filter","$orderby","$expand","$apply","fetchXml"])h.get(k)&&n.push(`translate ${k} into the QueryExpression (or use FetchExpression)`);return b(["requests.Add(new RetrieveMultipleRequest","{",` Query = new QueryExpression(${B(m)})`," {",` ColumnSet = ${nt(c)},`,...g?[` TopCount = ${Number(g)},`]:[]," },","});"])}if(i.op==="associate"){const m=Z(i.entitySet,s),h=Z(i.targetSet,s);return n.push("Relationship takes the relationship schema name — usually the navigation property name"),b(["requests.Add(new AssociateRequest","{",` Target = new EntityReference(${B(m)}, ${Y(i.recordId.trim())}),`,` Relationship = new Relationship(${B(i.navProperty.trim())}),`,` RelatedEntities = new EntityReferenceCollection { new EntityReference(${B(h)}, ${Y(i.targetId.trim())}) },`,"});"])}const x=/^(?:Microsoft\.Dynamics\.CRM\.)?([A-Za-z_][\w]*)$/.exec(o.path);if(o.method==="POST"&&x&&!s.logicalOf(x[1])){const m=Object.entries(st(o.body)).filter(([h])=>!h.includes("@"));return b([`requests.Add(new OrganizationRequest(${B(x[1])})`,"{"," Parameters ="," {",...m.map(([h,c])=>typeof c=="object"&&c!==null?` // TODO ${h}: convert ${JSON.stringify(c)}`:` [${B(h)}] = ${typeof c=="string"?B(c):String(c)},`)," },","});"])}return[r,"// No SDK request generated for this Web API call — add the matching OrganizationRequest."]}function zn(e,s,o){return["// ExecuteMultiple (SDK for .NET). Microsoft.Xrm.Sdk + Microsoft.Xrm.Sdk.Messages + Microsoft.Xrm.Sdk.Query.","// Max 1000 requests per call; ExecuteMultiple is not transactional — use ExecuteTransactionRequest for all-or-nothing.","var requests = new OrganizationRequestCollection();","",...e.flatMap(a=>[...Un(a,o),""]),"var executeMultiple = new ExecuteMultipleRequest","{"," Settings = new ExecuteMultipleSettings"," {",` ContinueOnError = ${s.continueOnError},`,` ReturnResponses = ${s.returnResponses},`," },"," Requests = requests,","};","","var response = (ExecuteMultipleResponse)service.Execute(executeMultiple);","","// With ReturnResponses = false only faults come back. RequestIndex is 0-based.","foreach (var item in response.Responses)","{"," if (item.Fault != null)",' Console.WriteLine($"Request {item.RequestIndex} failed: {item.Fault.Message}");'," else if (item.Response != null)",' Console.WriteLine($"Request {item.RequestIndex}: {item.Response.ResponseName}");',"}",'Console.WriteLine($"IsFaulted: {response.IsFaulted}");'].join(`
|
|
7
|
+
`)}const ot=[{id:"create",label:"Create (POST)"},{id:"update",label:"Update (PATCH)"},{id:"delete",label:"Delete (DELETE)"},{id:"retrieve",label:"Retrieve (GET)"},{id:"associate",label:"Associate (POST $ref)"},{id:"custom",label:"Custom request"}],Wn=["GET","POST","PATCH","PUT","DELETE"],Gn=[{name:"Prefer",value:"return=representation"},{name:"If-Match",value:"*"},{name:"MSCRM.SuppressDuplicateDetection",value:"false"}],z={fontFamily:j.fontFamilyMonospace,fontSize:12};function Vn({item:e,contentId:s,group:o,groups:n,wire:a,issues:i,onChange:r,onRemove:b,onMove:p,onMoveToGroup:x}){const{entities:m,allEntities:h}=dt(),c=w.useMemo(()=>h.find(f=>f.entitySetName===e.entitySet.trim())?.logicalName??null,[h,e.entitySet]),{table:g}=Ss(e.op==="associate"?c:null),k=ks(),O=w.useMemo(()=>Es(g?.navigationProperties??[],k).filter(Ts),[g,k]),D=`drs-batch-sets-${e.id}`,A=`drs-batch-navs-${e.id}`,G=e.op!=="custom",I=e.op==="update"||e.op==="delete"||e.op==="associate",P=e.op==="create"||e.op==="update"||e.op==="custom",q=n.indexOf(o),V=(f,$)=>r({headers:e.headers.map((F,N)=>N===f?{...F,...$}:F)});return t.jsxs("div",{style:{maxWidth:860},children:[t.jsxs(ue,{icon:ut,title:`Request $${s}`,sub:o.atomic?`In change set ${q+1} — rolls back with the rest of the change set if any request fails.`:`In group ${q+1} — independent; runs on its own.`,group:"batch",children:[t.jsx(je,{content:"Move up",relationship:"label",children:t.jsx(C,{icon:t.jsx(ht,{}),appearance:"subtle",onClick:()=>p(-1)})}),t.jsx(je,{content:"Move down",relationship:"label",children:t.jsx(C,{icon:t.jsx(pt,{}),appearance:"subtle",onClick:()=>p(1)})}),t.jsx(C,{icon:t.jsx(we,{}),appearance:"subtle",onClick:b,children:"Remove"})]}),i.length>0&&t.jsx(J,{intent:i.some(f=>f.severity==="error")?"error":"warning",layout:"multiline",style:{marginBottom:12},children:t.jsx(K,{children:i.map((f,$)=>t.jsx("div",{children:f.message},$))})}),t.jsxs("div",{style:{display:"grid",gridTemplateColumns:"repeat(auto-fit, minmax(220px, 1fr))",gap:12},children:[t.jsx(H,{label:"Operation",children:t.jsx(ge,{value:ot.find(f=>f.id===e.op)?.label??"",selectedOptions:[e.op],onOptionSelect:(f,$)=>{const F=$.optionValue,N={op:F};(F==="create"||F==="update")&&!e.body.trim()&&(N.body=`{
|
|
8
|
+
|
|
9
|
+
}`),r(N)},children:ot.map(f=>t.jsx(be,{value:f.id,children:f.label},f.id))})}),n.length>1&&t.jsx(H,{label:"Group",children:t.jsx(ge,{value:`${o.atomic?"Change set":"Independent"} ${q+1}`,selectedOptions:[o.id],onOptionSelect:(f,$)=>$.optionValue&&x($.optionValue),children:n.map((f,$)=>t.jsx(be,{value:f.id,children:`${f.atomic?"Change set":"Independent"} ${$+1}`},f.id))})}),t.jsx(H,{label:"Label (optional)",children:t.jsx(W,{value:e.label,onChange:(f,$)=>r({label:$.value})})})]}),t.jsxs("div",{style:{display:"grid",gridTemplateColumns:"repeat(auto-fit, minmax(220px, 1fr))",gap:12,marginTop:12},children:[e.op==="custom"&&t.jsxs(t.Fragment,{children:[t.jsx(H,{label:"Method",children:t.jsx(ge,{value:e.method,selectedOptions:[e.method],onOptionSelect:(f,$)=>r({method:$.optionValue}),children:Wn.map(f=>t.jsx(be,{value:f,children:f},f))})}),t.jsx(H,{label:"URL (relative to /api/data/v9.2/)",hint:"e.g. WhoAmI, accounts?$top=5, $1/primarycontactid/$ref",style:{gridColumn:"span 2"},children:t.jsx(W,{value:e.url,onChange:(f,$)=>r({url:$.value}),input:{style:z}})})]}),G&&t.jsx(H,{label:e.op==="associate"?"Source table (entity set)":"Table (entity set)",children:t.jsx(W,{value:e.entitySet,onChange:(f,$)=>r({entitySet:$.value}),placeholder:"accounts",input:{list:D,style:z}})}),(I||e.op==="retrieve")&&t.jsx(H,{label:e.op==="retrieve"?"Record id (optional)":"Record id",hint:e.op==="retrieve"?void 0:"GUID, alternate key, or $n for a record created earlier in this change set",children:t.jsx(W,{value:e.recordId,onChange:(f,$)=>r({recordId:$.value}),placeholder:"00000000-0000-0000-0000-000000000000",input:{style:z}})}),e.op==="retrieve"&&t.jsx(H,{label:"Query options",hint:"Without the leading ?",children:t.jsx(W,{value:e.query,onChange:(f,$)=>r({query:$.value}),placeholder:"$select=name&$top=10",input:{style:z}})}),e.op==="associate"&&t.jsxs(t.Fragment,{children:[t.jsx(H,{label:"Navigation property (collection-valued)",children:t.jsx(W,{value:e.navProperty,onChange:(f,$)=>r({navProperty:$.value}),placeholder:"contact_customer_accounts",input:{list:A,style:z}})}),t.jsx(H,{label:"Target table (entity set)",children:t.jsx(W,{value:e.targetSet,onChange:(f,$)=>r({targetSet:$.value}),placeholder:"contacts",input:{list:D,style:z}})}),t.jsx(H,{label:"Target record id",hint:"GUID or $n",children:t.jsx(W,{value:e.targetId,onChange:(f,$)=>r({targetId:$.value}),input:{style:z}})})]})]}),t.jsx("datalist",{id:D,children:m.map(f=>t.jsx("option",{value:f.entitySetName,children:f.displayName},f.logicalName))}),t.jsx("datalist",{id:A,children:O.map(f=>t.jsx("option",{value:f.name,children:f.targetEntity},f.name))}),P&&t.jsx(H,{label:"Body (JSON)",hint:o.atomic?'Reference a record created earlier in this change set with "$n", e.g. "primarycontactid@odata.bind": "$1".':void 0,style:{marginTop:12},children:t.jsx(mt,{value:e.body,onChange:(f,$)=>r({body:$.value}),resize:"vertical",rows:8,textarea:{style:z,spellCheck:!1}})}),t.jsxs("div",{style:{marginTop:16},children:[t.jsxs("div",{style:{display:"flex",alignItems:"center",gap:8,marginBottom:6,flexWrap:"wrap"},children:[t.jsx("strong",{style:{fontSize:13},children:"Request headers"}),t.jsx(M,{style:{color:j.colorNeutralForeground3},children:"Sent inside this part. Power Platform ToolBox asks you to approve them the first time."})]}),e.headers.map((f,$)=>t.jsxs("div",{style:{display:"flex",gap:8,marginBottom:6,alignItems:"center"},children:[t.jsx(Se,{checked:f.enabled,onChange:(F,N)=>V($,{enabled:N.checked}),"aria-label":`Send ${f.name||"header"}`}),t.jsx(W,{value:f.name,onChange:(F,N)=>V($,{name:N.value}),placeholder:"Name","aria-label":"Header name",input:{style:z},style:{flex:"1 1 0",minWidth:0}}),t.jsx(W,{value:f.value,onChange:(F,N)=>V($,{value:N.value}),placeholder:"Value","aria-label":"Header value",input:{style:z},style:{flex:"2 1 0",minWidth:0}}),t.jsx(C,{icon:t.jsx(we,{}),appearance:"subtle","aria-label":"Remove header",onClick:()=>r({headers:e.headers.filter((F,N)=>N!==$)})})]},$)),t.jsxs("div",{style:{display:"flex",gap:6,flexWrap:"wrap"},children:[t.jsx(C,{size:"small",icon:t.jsx(ce,{}),onClick:()=>r({headers:[...e.headers,{name:"",value:"",enabled:!0}]}),children:"Header"}),Gn.filter(f=>!e.headers.some($=>$.name.toLowerCase()===f.name.toLowerCase())).map(f=>t.jsxs(C,{size:"small",appearance:"subtle",onClick:()=>r({headers:[...e.headers,{...f,enabled:!0}]}),children:["+ ",f.name,": ",f.value]},f.name))]})]}),a&&t.jsxs("div",{style:{marginTop:16},children:[t.jsx("strong",{style:{fontSize:13},children:"Part preview"}),t.jsx("pre",{style:{...z,background:j.colorNeutralBackground1,border:`1px solid ${j.colorNeutralStroke2}`,borderRadius:4,padding:10,marginTop:6,whiteSpace:"pre-wrap",wordBreak:"break-all"},children:Te({contentId:s,wire:a}).replace(/\r\n/g,`
|
|
10
|
+
`)})]}),e.source&&t.jsxs(M,{style:{color:j.colorNeutralForeground3},children:["From: ",e.source]})]})}const Jn=[{id:"create",label:"Create"},{id:"update",label:"Update"},{id:"delete",label:"Delete"},{id:"retrieve",label:"Retrieve"},{id:"associate",label:"Associate"},{id:"custom",label:"Custom request"}];function Kn({onAdd:e,label:s="Add request",disabledGet:o}){return t.jsxs(Os,{children:[t.jsx(qs,{disableButtonEnhancement:!0,children:t.jsx(C,{icon:t.jsx(ce,{}),children:s})}),t.jsx(Bs,{children:t.jsx(Ms,{children:Jn.filter(n=>!(o&&n.id==="retrieve")).map(n=>t.jsx(Ps,{onClick:()=>e(n.id),children:n.label},n.id))})})]})}function Qn({groups:e,continueOnError:s,setContinueOnError:o,plan:n,unavailable:a,needsConsent:i,orgUrl:r,onAddGroup:b,onOpenSaved:p,onAddLast:x,lastLabel:m,onSelect:h,notice:c,variant:g="batch",returnResponses:k=!0,setReturnResponses:O}){const D=e.reduce((I,P)=>I+P.items.length,0),A=g==="execute-multiple";let G=0;return t.jsxs("div",{style:{maxWidth:860},children:[t.jsx(ue,{icon:Is,title:A?"ExecuteMultiple":"$batch request",sub:A?"Up to 1,000 independent requests in one call, with the SDK’s ContinueOnError and ReturnResponses settings.":"Up to 1,000 requests in one POST to /$batch. Requests in a change set succeed or roll back together.",group:"batch"}),A&&t.jsx(J,{intent:"info",layout:"multiline",style:{marginBottom:12},children:t.jsxs(K,{children:[t.jsx(ne,{children:"Sent as a Web API $batch"}),"ExecuteMultiple is an SDK for .NET (Organization service) message; the Web API has no ExecuteMultiple action. Its Web API equivalent is a ",t.jsx("code",{children:"$batch"})," of independent requests, which is what DRS sends. ContinueOnError maps to"," ",t.jsx("code",{children:"Prefer: odata.continue-on-error"}),"; ReturnResponses = false shows only the faults, as ExecuteMultipleResponse does. The Code tab has the ExecuteMultipleRequest (C#). For all-or-nothing, use the $batch Request mode’s change sets (ExecuteTransaction)."]})}),a&&t.jsx(J,{intent:"warning",layout:"multiline",style:{marginBottom:12},children:t.jsxs(K,{children:[t.jsx(ne,{children:"Can’t send from here"}),a," You can still compose the batch and copy it from the Code tab."]})}),c&&t.jsx(J,{intent:"info",layout:"multiline",style:{marginBottom:12},children:t.jsx(K,{children:c})}),t.jsxs("div",{style:{display:"flex",gap:8,flexWrap:"wrap",marginBottom:16},children:[A?e[0]&&t.jsx(C,{icon:t.jsx(ce,{}),onClick:()=>h(`group:${e[0].id}`),children:"Add request"}):t.jsxs(t.Fragment,{children:[t.jsx(C,{icon:t.jsx(Ie,{}),onClick:()=>b(!0),children:"Add change set"}),t.jsx(C,{icon:t.jsx(Ce,{}),onClick:()=>b(!1),children:"Add independent group"})]}),t.jsx(C,{icon:t.jsx(ce,{}),onClick:p,children:"Add from Saved…"}),t.jsx(C,{icon:t.jsx(Cs,{}),onClick:x,disabled:!m,children:m?`Add last request (${m})`:"Add last request"})]}),t.jsxs("div",{style:{display:"flex",gap:12,alignItems:"flex-start",padding:12,border:`1px solid ${j.colorNeutralStroke2}`,borderRadius:6,background:j.colorNeutralBackground1,marginBottom:16},children:[t.jsx(Se,{checked:s,onChange:(I,P)=>o(P.checked),"aria-label":"Continue on error"}),t.jsxs("div",{children:[t.jsx("strong",{children:A?"ContinueOnError":"Continue on error"})," ",t.jsx("code",{style:{fontSize:12},children:"Prefer: odata.continue-on-error"}),t.jsx(M,{block:!0,style:{color:j.colorNeutralForeground3},children:A?"False: processing stops at the first fault; the rest don’t run. True: every request runs and each fault is reported. Requests that already ran aren’t undone either way.":"Off: Dataverse stops at the first failed request or change set. On: it runs the rest and returns every result. A change set is all-or-nothing either way."})]})]}),A&&O&&t.jsxs("div",{style:{display:"flex",gap:12,alignItems:"flex-start",padding:12,border:`1px solid ${j.colorNeutralStroke2}`,borderRadius:6,background:j.colorNeutralBackground1,marginBottom:16},children:[t.jsx(Se,{checked:k,onChange:(I,P)=>O(P.checked),"aria-label":"ReturnResponses"}),t.jsxs("div",{children:[t.jsx("strong",{children:"ReturnResponses"}),t.jsx(M,{block:!0,style:{color:j.colorNeutralForeground3},children:"True: a response for every request. False: only the faults, which is what you want for bulk loads. A $batch always returns every response; DRS filters the Results the same way and sets it in the C#."})]})]}),i&&t.jsx(J,{intent:"info",layout:"multiline",style:{marginBottom:12},children:t.jsxs(K,{children:[t.jsx(ne,{children:"Headers need your approval in Power Platform ToolBox"}),"This batch sends request headers (per-request headers or continue-on-error). If you haven’t approved additional request headers for this tool yet, ToolBox asks first; if you reject, nothing is sent."]})}),n.length>1&&t.jsx(J,{intent:"info",layout:"multiline",style:{marginBottom:12},children:t.jsxs(K,{children:[t.jsxs(ne,{children:["Sent as ",n.length," host calls"]}),"Power Platform ToolBox sends one change set or one run of independent requests per call, so this batch goes out as ",n.length," $batch requests in order (",n.map(I=>I.transaction?"change set":"independent").join(" → "),"). Each change set is still atomic.",s?"":" A failed call stops the ones after it."," The Code tab shows the single-envelope form for other clients."]})}),t.jsxs("div",{style:{fontSize:13,marginBottom:8},children:[t.jsxs("strong",{children:[D," request",D===1?"":"s"]})," ","in ",e.length," group",e.length===1?"":"s"]}),e.map((I,P)=>t.jsxs("div",{style:{border:`1px solid ${j.colorNeutralStroke2}`,borderLeft:`3px solid ${I.atomic?"var(--color-request-batch)":j.colorNeutralStroke1}`,borderRadius:6,padding:"8px 12px",marginBottom:8,background:j.colorNeutralBackground1},children:[t.jsx(C,{appearance:"transparent",onClick:()=>h(`group:${I.id}`),style:{padding:0},children:t.jsx("strong",{children:A?"Requests":I.atomic?`Change set ${P+1}`:`Independent group ${P+1}`})}),I.items.length===0&&t.jsx(M,{block:!0,style:{color:j.colorNeutralForeground3},children:"Empty — skipped when sent."}),I.items.map(q=>{G+=1;const V=ae(q,r);return t.jsxs("div",{role:"button",tabIndex:0,onClick:()=>h(`item:${q.id}`),onKeyDown:f=>(f.key==="Enter"||f.key===" ")&&h(`item:${q.id}`),style:{display:"flex",gap:8,alignItems:"center",padding:"3px 0",cursor:"pointer"},children:[t.jsxs("code",{style:{width:36,color:j.colorNeutralForeground3},children:["$",G]}),t.jsx(Oe,{method:V.method,size:"sm"}),t.jsx("code",{style:{overflow:"hidden",textOverflow:"ellipsis",whiteSpace:"nowrap"},children:V.path||"—"}),q.label&&t.jsx(M,{style:{color:j.colorNeutralForeground3},children:q.label})]},q.id)})]},I.id))]})}function Xn({group:e,index:s,count:o,contentIdOf:n,orgUrl:a,onSetAtomic:i,onAdd:r,onRemoveGroup:b,onMoveGroup:p,onSelect:x,variant:m="batch"}){const h=e.items.some(g=>ae(g,a).method==="GET"),c=m==="execute-multiple";return t.jsxs("div",{style:{maxWidth:860},children:[t.jsx(ue,{icon:e.atomic?Ie:Ce,title:c?"Requests":e.atomic?`Change set ${s+1}`:`Independent group ${s+1}`,sub:c?"ExecuteMultiple runs each request on its own, in order. It isn’t transactional.":e.atomic?"Atomic: if any request fails, Dataverse rolls back the whole change set. GET isn’t allowed here.":"Each request runs on its own; a failure doesn’t undo the others.",group:"batch",children:!c&&t.jsxs(t.Fragment,{children:[t.jsx(C,{icon:t.jsx(ht,{}),appearance:"subtle","aria-label":"Move group up",disabled:s===0,onClick:()=>p(-1)}),t.jsx(C,{icon:t.jsx(pt,{}),appearance:"subtle","aria-label":"Move group down",disabled:s===o-1,onClick:()=>p(1)}),t.jsx(C,{icon:t.jsx(we,{}),appearance:"subtle",onClick:b,children:"Remove group"})]})}),t.jsxs("div",{style:{display:"flex",gap:12,alignItems:"center",marginBottom:16,flexWrap:"wrap"},children:[!c&&t.jsxs(Rs,{ariaLabel:"Group kind",children:[t.jsx(Ge,{checked:e.atomic,onClick:()=>i(!0),children:"Change set (atomic)"}),t.jsx(Ge,{checked:!e.atomic,onClick:()=>i(!1),children:"Independent"})]}),t.jsx(Kn,{onAdd:r,disabledGet:e.atomic})]}),e.atomic&&h&&t.jsx(J,{intent:"error",style:{marginBottom:12},children:t.jsx(K,{children:"This change set holds a GET request. Move it to an independent group."})}),e.items.length===0&&t.jsx(M,{style:{color:j.colorNeutralForeground3},children:"No requests yet."}),e.items.map(g=>{const k=ae(g,a);return t.jsxs("div",{role:"button",tabIndex:0,onClick:()=>x(`item:${g.id}`),onKeyDown:O=>(O.key==="Enter"||O.key===" ")&&x(`item:${g.id}`),style:{display:"flex",gap:8,alignItems:"center",padding:"6px 8px",borderBottom:`1px solid ${j.colorNeutralStroke3}`,cursor:"pointer"},children:[t.jsxs("code",{style:{width:36,color:j.colorNeutralForeground3},children:["$",n(g.id)]}),t.jsx(Oe,{method:k.method,size:"sm"}),t.jsx("code",{style:{overflow:"hidden",textOverflow:"ellipsis",whiteSpace:"nowrap"},children:k.path||"—"}),g.label&&t.jsx(M,{style:{color:j.colorNeutralForeground3},children:g.label})]},g.id)})]})}const oe={fontFamily:j.fontFamilyMonospace,fontSize:12};function rt(e){return e.outcome!=="done"?e.outcome==="rolled-back"?"warning":"info":e.status===void 0?"info":e.status>=400?"danger":"success"}function Re(e){if(e&&typeof e=="object"&&"error"in e){const s=e.error;if(s?.message)return s.code?`${s.code}: ${s.message}`:s.message}return null}function at({r:e}){const s=Re(e.body),o=e.headers?.["odata-entityid"]??e.headers?.["OData-EntityId"],n=e.outcome==="rolled-back"?"Rolled back":e.outcome==="not-run"?"Not run":e.outcome==="unknown"?"No result":null;return t.jsxs("details",{style:{borderBottom:`1px solid ${j.colorNeutralStroke3}`,padding:"6px 4px"},children:[t.jsxs("summary",{style:{display:"flex",gap:8,alignItems:"center",cursor:"pointer",listStyle:"none"},children:[t.jsxs("code",{style:{width:40,color:j.colorNeutralForeground3},children:["$",e.contentId]}),e.method&&t.jsx(Oe,{method:e.method,size:"sm"}),t.jsxs("code",{style:{flex:1,minWidth:0,overflow:"hidden",textOverflow:"ellipsis",whiteSpace:"nowrap"},children:[e.label?`${e.label} — `:"",e.path??""]}),n&&e.status===void 0?t.jsx(ke,{status:rt(e),code:n}):t.jsx(ke,{status:rt(e),code:e.status!==void 0&&e.status<300?e.status:`${e.status??"—"}${e.statusText&&(e.status??0)>=300?` ${e.statusText}`:""}`}),n&&e.status!==void 0&&t.jsx(M,{children:n})]}),t.jsxs("div",{style:{padding:"8px 0 4px 48px"},children:[s&&t.jsx(J,{intent:"error",layout:"multiline",style:{marginBottom:8},children:t.jsx(K,{children:s})}),o&&t.jsxs("div",{style:{...oe,marginBottom:6},children:["OData-EntityId: ",t.jsx("code",{children:o})]}),e.headers&&Object.keys(e.headers).length>0&&t.jsx("pre",{style:{...oe,margin:"0 0 8px",whiteSpace:"pre-wrap"},children:Object.entries(e.headers).map(([a,i])=>`${a}: ${i}`).join(`
|
|
11
|
+
`)}),e.body!==void 0&&t.jsx("pre",{style:{...oe,margin:0,whiteSpace:"pre-wrap",wordBreak:"break-all",background:j.colorNeutralBackground1,border:`1px solid ${j.colorNeutralStroke2}`,borderRadius:4,padding:8,maxHeight:360,overflow:"auto"},children:typeof e.body=="string"?e.body:JSON.stringify(e.body,null,2)}),e.body===void 0&&e.outcome==="done"&&t.jsx(M,{style:{color:j.colorNeutralForeground3},children:"No response body."}),e.outcome==="rolled-back"&&t.jsx(M,{block:!0,style:{color:j.colorNeutralForeground3},children:"The change set failed, so Dataverse undid this request with the rest of it."}),e.outcome==="unknown"&&t.jsx(M,{block:!0,style:{color:j.colorNeutralForeground3},children:"The host call failed as a whole (see the message above), so there’s no result for this request."}),e.outcome==="not-run"&&t.jsx(M,{block:!0,style:{color:j.colorNeutralForeground3},children:"An earlier failure stopped the batch before this request ran."})]})]})}function Yn({run:e,rows:s,extraTitle:o}){const[n,a]=w.useState(""),[i,r]=w.useState(null),[b,p]=w.useState(null),x=()=>{try{r(Pn(n)),p(null)}catch(c){r(null),p(c instanceof Error?c.message:String(c))}},m=(e?.items??[]).reduce((c,g)=>(g.outcome==="done"&&g.status!==void 0&&g.status<400?c.ok+=1:g.outcome==="done"?c.failed+=1:g.outcome==="unknown"?c.noResult+=1:c.other+=1,c),{ok:0,failed:0,other:0,noResult:0}),h=c=>!!c.requestFailed&&c.contentIds.every(g=>s.find(k=>k.contentId===g)?.outcome==="unknown");if(e){const c=new Map(s.map(g=>[g.contentId,g]));for(const g of e.segments){if(!g.changesetError&&!g.requestFailed)continue;!g.contentIds.some(O=>{const D=c.get(O);return D?.outcome==="done"&&(D.status??0)>=400})&&m.other>0&&(m.failed+=1,m.other-=1)}}return t.jsxs("div",{style:{maxWidth:1e3},children:[e?t.jsxs(t.Fragment,{children:[t.jsxs("div",{style:{display:"flex",gap:10,alignItems:"center",marginBottom:12,flexWrap:"wrap"},children:[t.jsx(ke,{status:e.ok?"success":"danger",code:e.ok?200:"Failed",ms:e.ms}),t.jsxs("span",{style:{fontSize:13},children:[m.ok," succeeded · ",m.failed," failed",m.other?` · ${m.other} rolled back or not run`:"",m.noResult?` · ${m.noResult} no result`:"",e.segments.length>1?` · ${e.segments.length} host calls`:""]}),o&&t.jsx(M,{children:o})]}),e.segments.map((c,g)=>c.error||c.changesetError?t.jsx(J,{intent:"error",layout:"multiline",style:{marginBottom:8},children:t.jsxs(K,{children:[t.jsxs(ne,{children:[h(c)?"No results for ":"",c.transaction?"Change set":"Requests"," $",c.contentIds[0],c.contentIds.length>1?`–$${c.contentIds[c.contentIds.length-1]}`:"",h(c)?"":" failed"]}),c.error??`${c.changesetError.status} ${c.changesetError.statusText??""} — ${Re(c.changesetError.body)??"see the response body below"}`,c.changesetError?.body!==void 0&&!Re(c.changesetError.body)&&t.jsx("pre",{style:{...oe,whiteSpace:"pre-wrap"},children:JSON.stringify(c.changesetError.body,null,2)})]})},g):null),t.jsx("div",{style:{background:j.colorNeutralBackground1,border:`1px solid ${j.colorNeutralStroke2}`,borderRadius:6,padding:"0 8px"},children:s.map(c=>t.jsx(at,{r:c},c.key))})]}):t.jsx(M,{block:!0,style:{color:j.colorNeutralForeground3,marginBottom:16},children:"Send the batch to see each request’s status, headers and body here."}),t.jsxs("details",{style:{marginTop:24},children:[t.jsxs("summary",{style:{cursor:"pointer",fontSize:13},children:[t.jsx(As,{style:{verticalAlign:"middle",marginRight:6}}),"Inspect a raw $batch response from another client"]}),t.jsxs("div",{style:{marginTop:8},children:[t.jsx(mt,{value:n,onChange:(c,g)=>a(g.value),placeholder:"--batchresponse_…",rows:8,resize:"vertical",textarea:{style:oe,spellCheck:!1},style:{width:"100%"},"aria-label":"Raw $batch response"}),t.jsx(C,{style:{marginTop:8},onClick:x,disabled:!n.trim(),children:"Parse response"}),b&&t.jsx(J,{intent:"error",style:{marginTop:8},children:t.jsx(K,{children:b})}),i&&t.jsx("div",{style:{marginTop:8},children:i.map((c,g)=>t.jsx(at,{r:{key:String(g),contentId:c.contentId??String(g+1),label:c.changeset!==void 0?`change set ${c.changeset+1}`:void 0,outcome:"done",status:c.status,statusText:c.statusText,headers:c.headers,body:c.body}},g))})]})]})]})}function it({formats:e,labels:s,generate:o,note:n,crlfFormats:a=["http"]}){const[i,r]=w.useState(e[0]),[b,p]=w.useState(!1),x=o(i);return t.jsxs("div",{children:[t.jsx(ue,{icon:Ns,title:"Code",sub:n,group:"batch",children:t.jsx(je,{content:"Copy",relationship:"label",children:t.jsx(C,{icon:t.jsx(Fs,{}),appearance:"subtle",onClick:()=>{Ds(x,"the code",{toastOnSuccess:!1}).then(m=>{m&&(p(!0),setTimeout(()=>p(!1),1500))})},children:b?"Copied":"Copy"})})}),t.jsx(_s,{selectedValue:i,onTabSelect:(m,h)=>r(h.value),size:"small",children:e.map(m=>t.jsx(Ls,{value:m,children:s[m]},m))}),t.jsx("pre",{style:{fontFamily:j.fontFamilyMonospace,fontSize:12,lineHeight:1.5,background:j.colorNeutralBackground1,border:`1px solid ${j.colorNeutralStroke2}`,borderRadius:6,padding:12,marginTop:8,whiteSpace:"pre",overflow:"auto",maxHeight:"calc(100vh - 260px)"},children:x}),a.includes(i)&&t.jsx(M,{style:{color:j.colorNeutralForeground3},children:"Line breaks in a $batch body are CRLF on the wire."})]})}function Zn({open:e,onClose:s,onAdd:o}){const{saved:n}=Hs(),[a,i]=w.useState(new Set),[r,b]=w.useState(""),p=Us(),x=w.useMemo(()=>n.filter(h=>En.has(h.modeId)&&(!h.orgScope||h.orgScope===p)).filter(h=>!r.trim()||h.name.toLowerCase().includes(r.trim().toLowerCase())).sort((h,c)=>c.savedAt-h.savedAt),[n,p,r]),m=()=>{i(new Set),b(""),s()};return t.jsx(zs,{open:e,onOpenChange:(h,c)=>!c.open&&m(),children:t.jsx(Ws,{style:{maxWidth:640},children:t.jsxs(Gs,{children:[t.jsx(Vs,{children:"Add saved requests to the batch"}),t.jsxs(Js,{children:[t.jsx(W,{value:r,onChange:(h,c)=>b(c.value),placeholder:"Filter by name",contentBefore:t.jsx(Ks,{}),style:{width:"100%",marginBottom:8},"aria-label":"Filter saved requests"}),x.length===0&&t.jsx(M,{block:!0,style:{color:j.colorNeutralForeground3,padding:"12px 0"},children:"No saved requests on this connection that can go in a batch. Save a request from a Read, Write, Relate or Execute mode first."}),t.jsx("div",{style:{maxHeight:360,overflowY:"auto"},children:x.map(h=>t.jsx("div",{style:{display:"flex",alignItems:"center",gap:4},children:t.jsx(Qs,{checked:a.has(h.id),onChange:(c,g)=>i(k=>{const O=new Set(k);return g.checked?O.add(h.id):O.delete(h.id),O}),label:t.jsxs("span",{children:[h.name," ",t.jsx(M,{style:{color:j.colorNeutralForeground3},children:Ee(h.modeId).name})]})})},h.id))})]}),t.jsxs(Xs,{children:[t.jsx(C,{appearance:"secondary",onClick:m,children:"Cancel"}),t.jsxs(C,{appearance:"primary",disabled:a.size===0,onClick:()=>{o(x.filter(h=>a.has(h.id))),m()},children:["Add ",a.size||""]})]})]})})})}const eo=["http","fetch","pptb"],to=["csharp","http","pptb"],so={...yt,csharp:"ExecuteMultipleRequest (C#)",http:"Web API equivalent ($batch)"},no=new Set(["bulk-delete","bulk-write","batch","execute-multiple"]);function ro({themeMode:e,variant:s="batch"}){const o=s==="execute-multiple",n=o?"execute-multiple":"batch",a=Ee(n),i=Ys(n,Ve,o?Zs:en),[r,b]=w.useState(i.state),p=r.returnResponses??!0,{allEntities:x}=dt(),[m,h]=w.useState("overview"),[c,g]=w.useState("builder"),[k,O]=w.useState(null),[D,A]=w.useState(!1),[G,I]=w.useState([]),[P,q]=w.useState(!1),[V,f]=w.useState(null),[$,F]=w.useState(i.lastSavedId),[N,qe]=w.useState(i.lastSavedHash),X=Je.host?`https://${Je.host}`:"",T=w.useMemo(()=>tn(r.groups,X),[r.groups,X]),ie=w.useMemo(()=>sn(T.items),[T]),Be=kn(),$t=w.useMemo(()=>{const l=T.items.length,d=T.items.filter(u=>u.wire&&u.wire.method!=="GET").length;return d===0?null:{operation:a.name,scope:{kind:"text",text:`${l} request${l===1?"":"s"}, ${d} of them change${d===1?"s":""} data`,count:d},highImpact:!0,confirmWord:a.id==="execute-multiple"?"ExecuteMultiple":"batch"}},[T,a.id,a.name]),he=(l,d)=>{const u=new Set(l.dirty);return u.add(d),{...l,dirty:u}},Q=w.useCallback((l,d="batch")=>b(u=>he({...u,groups:l(u.groups)},d)),[]),jt=(l,d)=>Q(u=>u.map(y=>({...y,items:y.items.map(v=>v.id===l?{...v,...d}:v)})),`item:${l}`),Me=(l,d,u=!0)=>{d.length!==0&&(Q(y=>{let v=y.find(R=>R.id===l);const S=d.some(R=>ae(R,X).method==="GET");if((!v||v.atomic&&S)&&(v=[...y].reverse().find(R=>S?!R.atomic:!0)),!v){const R=Qe(!S,d);return[...y,R]}const E=v.id;return y.map(R=>R.id===E?{...R,items:[...R.items,...d]}:R)}),u&&(h(`item:${d[0].id}`),g("builder")))},wt=l=>{for(const d of r.groups){const u=d.items.find(y=>y.id===l);if(u)return{group:d,item:u}}return null},St=(l,d)=>Q(u=>{const y=u.findIndex(_=>_.items.some(Nt=>Nt.id===l));if(y<0)return u;const v=u[y].items,S=v.findIndex(_=>_.id===l),E=u.map(_=>({..._,items:[..._.items]})),R=S+d;if(R>=0&&R<v.length)[E[y].items[S],E[y].items[R]]=[E[y].items[R],E[y].items[S]];else if(u[y+d]){const[_]=E[y].items.splice(S,1);d<0?E[y-1].items.push(_):E[y+1].items.unshift(_)}return E}),kt=(l,d)=>Q(u=>{const y=u.flatMap(v=>v.items).find(v=>v.id===l);return y?u.map(v=>{const S=v.items.filter(E=>E.id!==l);return v.id===d?{...v,items:[...S,y]}:{...v,items:S}}):u}),pe=nn(),ee=pe&&!no.has(pe.modeId)?pe:null,Pe=ee?Ee(ee.modeId).name:null,Ae=async l=>{const d=[],u=[];for(const v of l){const S=await Cn(v);S.ok?d.push(...S.items):u.push(`“${v.name}” (${S.reason})`)}const y=m.startsWith("group:")?m.slice(6):null;Me(y,d,!1),f([d.length?`Added ${d.length} request${d.length===1?"":"s"}.`:"",u.length?`Skipped ${u.join(", ")}.`:""].filter(Boolean).join(" ")||null)},Ne=w.useMemo(()=>{const l=T.issues.map((u,y)=>{const v=u.target?u.target.startsWith("g")?`group:${u.target}`:`item:${u.target}`:"overview",S=T.items.find(R=>R.item.id===u.target),E=S?`$${S.contentId}: ${u.message}`:u.message;return u.severity==="error"?xe.err(`batch-${y}`,"validation",E,void 0,v):xe.warn(`batch-${y}`,"validation",E,void 0,v)}),d=T.items.filter(u=>u.wire?.method==="DELETE").length;return d>0&&l.push(xe.warn("batch-deletes","validation",`This batch deletes ${d} record${d===1?"":"s"}`,"The batch’s confirmation counts writes, not the records each delete removes, and there’s no typed record name as in the Delete mode. Check the ids first.","overview")),l},[T]),Et=Be??on(Ne),Tt=T.items.some(l=>l.wire&&Object.keys(l.wire.headers).length>0)||r.continueOnError&&ie.some(l=>!l.transaction),Rt=async()=>{A(!0);try{const l=await Sn(ie,{continueOnError:r.continueOnError});O(l);const{status:d,summary:u,succeeded:y}=yn(l);I(v=>[{id:`r-${Date.now()}`,modeId:n,url:`${re}/$batch`,method:"BATCH",ts:Date.now(),status:d,ms:l.ms,rowCount:y,summary:u},...v].slice(0,8)),b(v=>({...v,dirty:new Set}))}finally{A(!1),g("results")}},It=w.useMemo(()=>k?(o&&!p?k.items.filter(d=>d.outcome!=="done"||(d.status??0)>=400):k.items).map(d=>{const u=T.items.find(y=>y.item.id===d.itemId);return{key:d.itemId,contentId:d.contentId,method:u?.wire?.method,path:u?.wire?.path,label:u?.item.label,outcome:d.outcome,status:d.status,statusText:d.statusText,headers:d.headers,body:d.body}}):[],[k,T,o,p]),De=w.useRef({batch:de("batch"),cs:[]}),me=w.useMemo(()=>({batch:De.current.batch,changeset:l=>{var d;return(d=De.current.cs)[l]??(d[l]=de("changeset"))}}),[]),Ct=w.useMemo(()=>new TextEncoder().encode(bt(vt(T.items),me).body).length,[T,me]),Fe=l=>Nn(l,{items:T.items,plan:ie,continueOnError:r.continueOnError,orgUrl:X,boundaries:me}),Ot=l=>l==="csharp"?zn(T.items,{continueOnError:r.continueOnError,returnResponses:p},{logicalOf:d=>x.find(u=>u.entitySetName===d)?.logicalName??null,attrType:(d,u)=>lt(d)?.columns.find(y=>y.logicalName===u)?.attributeType??null}):Fe(l),te=w.useMemo(()=>rn(r),[r]);an(n,te,$,N);const qt=w.useMemo(()=>ye(te),[te]),_e=N===null?!0:qt!==N,le=T.items.length,Bt=l=>{F(l.id),qe(ye(l.state))},Mt=l=>{if(l.modeId!==n)return;const d=l.state;b(Ve(d)),F(l.id),qe(ye(d)),O(null),h("overview")},Le=Ke(Bt),He=Ke(Mt);ln(w.useMemo(()=>({state:te,modeId:n,dirty:_e,lastSavedId:$,onSaved:Le,onLoadSaved:He}),[te,n,_e,$,Le,He]));const fe=l=>T.issues.filter(d=>d.target===l),Pt=l=>k?.items.find(d=>d.itemId===l),At=[{id:"batch",label:o?"ExecuteMultiple":"Batch",meta:`${le} request${le===1?"":"s"}`,items:[{id:"overview",icon:dn,iconFilled:cn,label:o?"Settings & add":"Options & add",badge:r.continueOnError?"continue":null,badgeAppearance:"tint",dirty:r.dirty.has("overview")}]},...r.groups.map((l,d)=>({id:l.id,label:o?"Requests":l.atomic?`Change set ${d+1}`:`Independent ${d+1}`,meta:`${l.items.length}`,items:[{id:`group:${l.id}`,icon:l.atomic?Ie:Ce,iconFilled:l.atomic?un:hn,label:o?"Add request":l.atomic?"Atomic group":"Independent requests",badge:fe(l.id).length||null,badgeColor:"danger"},...l.items.map(u=>{const y=T.items.find(_=>_.item.id===u.id),v=ae(u,X),S=fe(u.id).filter(_=>_.severity==="error").length,E=Pt(u.id),R=S?`${S} issue${S===1?"":"s"}`:E?E.status!==void 0?E.status:E.outcome==="rolled-back"?"rolled back":E.outcome==="unknown"?"no result":"not run":null;return{id:`item:${u.id}`,icon:ut,iconFilled:pn,label:`$${y?.contentId??"?"} ${v.method} ${u.label||v.path||"…"}`,code:!0,badge:R,badgeAppearance:"tint",badgeColor:S||E&&(E.outcome!=="done"||(E.status??0)>=400)?"danger":"success",dirty:r.dirty.has(`item:${u.id}`)}})]}))];let se=null;if(m.startsWith("item:")){const l=wt(m.slice(5)),d=l&&T.items.find(u=>u.item.id===l.item.id);l&&d&&(se=t.jsx(Vn,{item:l.item,contentId:d.contentId,group:l.group,groups:r.groups,wire:d.wire,issues:fe(l.item.id),onChange:u=>jt(l.item.id,u),onRemove:()=>{Q(u=>u.map(y=>({...y,items:y.items.filter(v=>v.id!==l.item.id)}))),h(`group:${l.group.id}`)},onMove:u=>St(l.item.id,u),onMoveToGroup:u=>kt(l.item.id,u)},l.item.id))}else if(m.startsWith("group:")){const l=r.groups.findIndex(u=>u.id===m.slice(6)),d=r.groups[l];d&&(se=t.jsx(Xn,{group:d,index:l,count:r.groups.length,variant:s,orgUrl:X,contentIdOf:u=>T.items.find(y=>y.item.id===u)?.contentId??"?",onSetAtomic:u=>Q(y=>y.map(v=>v.id===d.id?{...v,atomic:u}:v)),onAdd:u=>Me(d.id,[ct(u)]),onRemoveGroup:()=>{Q(u=>u.filter(y=>y.id!==d.id)),h("overview")},onMoveGroup:u=>Q(y=>{const v=[...y],S=l+u;return S<0||S>=v.length?y:([v[l],v[S]]=[v[S],v[l]],v)}),onSelect:h}))}return se||(se=t.jsx(Qn,{variant:s,returnResponses:p,setReturnResponses:l=>b(d=>he({...d,returnResponses:l},"overview")),groups:r.groups,continueOnError:r.continueOnError,setContinueOnError:l=>b(d=>he({...d,continueOnError:l},"overview")),plan:ie,unavailable:Be,needsConsent:Tt,orgUrl:X,onAddGroup:l=>{const d=Qe(l);Q(u=>[...u,d]),h(`group:${d.id}`)},onOpenSaved:()=>q(!0),onAddLast:()=>{ee&&Ae([{...ee,name:Pe??ee.modeId}])},lastLabel:Pe,onSelect:h,notice:V})),t.jsxs(mn,{sidebar:t.jsx(bn,{type:a,urlPreview:`/$batch · ${le} request${le===1?"":"s"}${o?" · ExecuteMultiple":""}`,sections:At,activeNode:m,onSelect:l=>{h(l),g("builder")},recents:G}),urlBar:t.jsx(gn,{method:"BATCH",url:`${re}/$batch`,bytes:Ct,executeVerb:a.executeVerb,writeConfirm:$t,disabledReason:Et,loading:D,onExecute:Rt,advisories:Ne,onAdvisoryFocus:l=>{h(l),g("builder")}}),children:[t.jsxs(fn,{tab:c,onTabChange:g,resultCount:k?k.items.length:null,children:[c==="builder"&&se,c==="code"&&o&&t.jsx(it,{formats:to,labels:so,generate:Ot,note:"DRS sends these requests as a Web API $batch; the C# is the SDK form."}),c==="code"&&!o&&t.jsx(it,{formats:eo,labels:yt,generate:Fe,note:T.issues.some(l=>l.severity==="error")?"Requests with errors are left out until they’re fixed.":void 0}),c==="results"&&t.jsx(Yn,{run:k,rows:It,extraTitle:o&&!p&&k?"ReturnResponses = false: only faults are listed.":void 0})]}),t.jsx(Zn,{open:P,onClose:()=>q(!1),onAdd:l=>{Ae(l.map(d=>({modeId:d.modeId,state:d.state,name:d.name})))}})]})}export{ro as BatchMode};
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
import{f,l as F,A as e,N as u,O as p,ah as x,cA as h,ad as N,bn as b,b5 as I,ck as j,a2 as n,bq as i,cn as g,a3 as m,cC as z,cD as S}from"./index-XmEQbXiX.js";function P({table:l,value:r,onChange:t,group:d="binary"}){const o=f(l),c=F.useMemo(()=>(o?.columns??[]).filter(a=>a.attributeType==="File"),[o]),s=c.find(a=>a.logicalName===r);return o?c.length===0?e.jsxs("div",{children:[e.jsx(x,{icon:j,title:"File column",group:d}),e.jsx(u,{layout:"multiline",intent:"warning",style:{maxWidth:720},children:e.jsxs(p,{children:[e.jsx("strong",{children:o.displayName})," has no File-typed columns. Add one via the maker portal or pick a different table."]})})]}):e.jsxs("div",{children:[e.jsx(x,{icon:j,title:"File column",sub:"Pick the File-typed column to operate on. Max size + target are sourced from the column metadata.",group:d}),e.jsxs("div",{style:{maxWidth:720},children:[e.jsx(N,{label:"Column",children:e.jsx(b,{value:s?.displayName??s?.logicalName??"",selectedOptions:r?[r]:[],onOptionSelect:(a,y)=>t(y.optionValue??null),placeholder:"Pick a file column…",children:c.map(a=>e.jsx(I,{value:a.logicalName,text:a.displayName,children:e.jsx(v,{col:a})},a.logicalName))})}),s&&e.jsx("div",{style:{marginTop:16},children:e.jsx(C,{col:s})})]})]}):e.jsx(u,{layout:"multiline",intent:"error",children:e.jsxs(p,{children:["Unknown table ",e.jsx("code",{children:l}),"."]})})}function v({col:l}){return e.jsxs("div",{style:{display:"flex",flexDirection:"column",minWidth:0},children:[e.jsxs("div",{style:{display:"flex",alignItems:"center",gap:6},children:[e.jsx("span",{style:{fontFamily:n.fontFamilyMonospace,fontWeight:600},children:l.logicalName}),e.jsx(i,{appearance:"ghost",size:"small",children:"File"}),e.jsxs(i,{appearance:"ghost",size:"small",style:{marginLeft:"auto"},children:["max ",g((l.maxSizeInKB??32768)*1024)]})]}),e.jsxs(m,{style:{color:n.colorNeutralForeground3},children:[l.displayName,l.binaryTarget&&l.binaryTarget!=="file"&&e.jsxs(e.Fragment,{children:[" · ",l.binaryTarget," body"]})]})]})}function C({col:l}){const r=(l.maxSizeInKB??32768)*1024;return e.jsxs("div",{style:{border:`1px solid ${n.colorNeutralStroke2}`,borderRadius:n.borderRadiusMedium,padding:12,background:n.colorNeutralBackground1},children:[e.jsxs("div",{style:{display:"flex",alignItems:"center",gap:8,marginBottom:8},children:[e.jsx(j,{style:{color:n.colorBrandForeground1}}),e.jsx("strong",{style:{fontFamily:n.fontFamilyMonospace,fontSize:13},children:l.logicalName}),e.jsx(i,{appearance:"tint",color:"brand",children:"File"}),e.jsx("span",{style:{flexGrow:1}}),e.jsx(m,{style:{color:n.colorNeutralForeground3,fontFamily:n.fontFamilyMonospace},children:l.displayName})]}),e.jsxs("div",{style:{display:"grid",gridTemplateColumns:"160px 1fr",rowGap:4,fontSize:11},children:[e.jsx("span",{style:{color:n.colorNeutralForeground3},children:"Max file size"}),e.jsxs("span",{children:[g(r)," ",e.jsxs(m,{style:{color:n.colorNeutralForeground3,marginLeft:4},children:["· ",(l.maxSizeInKB??32768).toLocaleString()," KB"]})]}),e.jsx("span",{style:{color:n.colorNeutralForeground3},children:"Companion column"}),e.jsxs("span",{style:{fontFamily:n.fontFamilyMonospace},children:[S(l.logicalName)," ",e.jsx(m,{style:{color:n.colorNeutralForeground3,marginLeft:4,fontFamily:n.fontFamilyBase},children:"· read-only string — $select to get the filename without downloading bytes"})]}),e.jsx("span",{style:{color:n.colorNeutralForeground3},children:"Retrieve returns"}),e.jsx("span",{children:"file id (Guid). Pass to DeleteFile or compose download URL."}),e.jsx("span",{style:{color:n.colorNeutralForeground3},children:"Binary target"}),e.jsx("span",{children:e.jsx(i,{appearance:"ghost",children:l.binaryTarget??"file"})})]})]})}function T({table:l,value:r,onChange:t,group:d="binary"}){const o=f(l),c=F.useMemo(()=>(o?.columns??[]).filter(a=>a.attributeType==="Image"),[o]),s=c.find(a=>a.logicalName===r);return o?c.length===0?e.jsxs("div",{children:[e.jsx(x,{icon:h,title:"Image column",group:d}),e.jsx(u,{layout:"multiline",intent:"warning",style:{maxWidth:720},children:e.jsxs(p,{children:[e.jsx("strong",{children:o.displayName})," has no Image-typed columns. Tables get one when their primary image is configured; custom image columns are created via solution explorer."]})})]}):e.jsxs("div",{children:[e.jsx(x,{icon:h,title:"Image column",sub:"Pick the Image-typed column. Primary image (entityimage) is thumbnail-only; custom image columns can store full size when configured.",group:d}),e.jsxs("div",{style:{maxWidth:720},children:[e.jsx(N,{label:"Column",children:e.jsx(b,{value:s?.displayName??s?.logicalName??"",selectedOptions:r?[r]:[],onOptionSelect:(a,y)=>t(y.optionValue??null),placeholder:"Pick an image column…",children:c.map(a=>e.jsx(I,{value:a.logicalName,text:a.displayName,children:e.jsx(B,{col:a})},a.logicalName))})}),s&&e.jsx("div",{style:{marginTop:16},children:e.jsx(k,{col:s})})]})]}):e.jsx(u,{layout:"multiline",intent:"error",children:e.jsxs(p,{children:["Unknown table ",e.jsx("code",{children:l}),"."]})})}function B({col:l}){return e.jsxs("div",{style:{display:"flex",flexDirection:"column",minWidth:0},children:[e.jsxs("div",{style:{display:"flex",alignItems:"center",gap:6},children:[e.jsx("span",{style:{fontFamily:n.fontFamilyMonospace,fontWeight:600},children:l.logicalName}),e.jsx(i,{appearance:"ghost",size:"small",children:"Image"}),l.isPrimaryImage&&e.jsx(i,{appearance:"tint",color:"brand",size:"small",children:"primary"}),l.canStoreFullImage&&e.jsx(i,{appearance:"tint",color:"success",size:"small",children:"full-size"}),e.jsx(i,{appearance:"ghost",size:"small",style:{marginLeft:"auto"},children:l.isPrimaryImage?"144×144":`max ${g((l.maxSizeInKB??10240)*1024)}`})]}),e.jsx(m,{style:{color:n.colorNeutralForeground3},children:l.displayName})]})}function k({col:l}){const r=(l.maxSizeInKB??10240)*1024;return e.jsxs("div",{style:{border:`1px solid ${n.colorNeutralStroke2}`,borderRadius:n.borderRadiusMedium,padding:12,background:n.colorNeutralBackground1},children:[e.jsxs("div",{style:{display:"flex",alignItems:"center",gap:8,marginBottom:8},children:[e.jsx(h,{style:{color:n.colorBrandForeground1}}),e.jsx("strong",{style:{fontFamily:n.fontFamilyMonospace,fontSize:13},children:l.logicalName}),e.jsx(i,{appearance:"tint",color:"brand",children:"Image"}),l.isPrimaryImage&&e.jsx(i,{appearance:"tint",color:"brand",children:"primary"}),l.canStoreFullImage?e.jsx(i,{appearance:"tint",color:"success",children:"full-size enabled"}):e.jsx(i,{appearance:"tint",color:"subtle",children:"thumbnail only"})]}),e.jsxs("div",{style:{display:"grid",gridTemplateColumns:"180px 1fr",rowGap:4,fontSize:11},children:[e.jsx("span",{style:{color:n.colorNeutralForeground3},children:"Display name"}),e.jsx("span",{children:l.displayName}),e.jsx("span",{style:{color:n.colorNeutralForeground3},children:"Thumbnail size"}),e.jsx("span",{children:"144 × 144 (auto-cropped center)"}),e.jsx("span",{style:{color:n.colorNeutralForeground3},children:"Full-size"}),e.jsx("span",{children:l.canStoreFullImage?`Up to ${g(r)}`:e.jsx("em",{style:{color:n.colorNeutralForeground3},children:"not stored — thumbnail only"})}),e.jsx("span",{style:{color:n.colorNeutralForeground3},children:"Companion columns"}),e.jsx("span",{style:{fontFamily:n.fontFamilyMonospace,fontSize:10},children:(()=>{const t=z(l.logicalName);return`${t.id} · ${t.timestamp} · ${t.url}`})()}),e.jsx("span",{style:{color:n.colorNeutralForeground3},children:"Set on Create?"}),e.jsx("span",{children:l.isPrimaryImage?"Yes — primary image only":"No — Update or PATCH only"}),e.jsx("span",{style:{color:n.colorNeutralForeground3},children:"File types"}),e.jsx("span",{children:"image/gif · image/jpeg · image/png · image/bmp · image/tiff"})]})]})}export{P as F,T as I};
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
import{f as U,E as V,c as We,a as Xe,g as Ye,b as ce,d as ue,s as Ve,e as I,m as de,r as Je,h as Qe,i as ze,j as Ge,k as Ke,l as u,u as Ze,n as et,o as tt,p as X,q as pe,t as at,T as st,v as nt,F as rt,w as lt,C as Ne,x as ot,M as De,y as it,L as ct,z as ut,A as t,H as dt,B as pt,D as mt,G as Te,I as me,J as ht,K as yt,N as L,O,P as ft,R as bt,U as gt,S as xt,Q as jt,V as J,W as he,X as Q,Y as F,Z as St,_ as G,$ as vt,a0 as kt,a1 as wt,a2 as D,a3 as T,a4 as Nt,a5 as Dt,a6 as Tt,a7 as Ct,a8 as Et,a9 as $t,aa as Rt,ab as Lt,ac as Ot,ad as C,ae as z,af as Ft,ag as At,ah as Ce,ai as It,aj as ye,ak as Pt,al as fe,am as Mt}from"./index-XmEQbXiX.js";const be={eq:"Equal",ne:"NotEqual",gt:"GreaterThan",ge:"GreaterEqual",lt:"LessThan",le:"LessEqual"},Bt=new Set(["On","OnOrAfter","OnOrBefore","Today","Tomorrow","Yesterday","Last7Days","Next7Days","LastWeek","ThisWeek","NextWeek","LastMonth","ThisMonth","NextMonth","LastYear","ThisYear","NextYear","LastXHours","LastXDays","LastXWeeks","LastXMonths","LastXYears","NextXHours","NextXDays","NextXWeeks","NextXMonths","NextXYears","OlderThanXMinutes","OlderThanXHours","OlderThanXDays","OlderThanXWeeks","OlderThanXMonths","OlderThanXYears","ThisFiscalPeriod","ThisFiscalYear","LastFiscalPeriod","LastFiscalYear","NextFiscalPeriod","NextFiscalYear","LastXFiscalPeriods","LastXFiscalYears","NextXFiscalPeriods","NextXFiscalYears","InFiscalPeriod","InFiscalYear","InFiscalPeriodAndYear","InOrAfterFiscalPeriodAndYear","InOrBeforeFiscalPeriodAndYear","Between","NotBetween","In","NotIn","ContainValues","DoesNotContainValues","Above","AboveOrEqual","Under","UnderOrEqual","NotUnder","EqualUserId","NotEqualUserId","EqualBusinessId","NotEqualBusinessId","EqualRoleBusinessId","EqualUserLanguage","EqualUserTeams","EqualUserOrUserTeams","EqualUserOrUserHierarchy","EqualUserOrUserHierarchyAndTeams"]);function ge(e){switch(e?.attributeType){case"Integer":case"Picklist":case"State":case"Status":case"MultiSelectPicklist":case"EntityName":return"System.Int32";case"BigInt":return"System.Int64";case"Decimal":case"Money":return"System.Decimal";case"Double":return"System.Double";case"Boolean":return"System.Boolean";case"DateTime":return"System.DateTime";case"Uniqueidentifier":case"Lookup":case"Customer":case"Owner":return"System.Guid";default:return"System.String"}}const qt=e=>e.replace(/[[%_]/g,s=>`[${s}]`);function Ut(e,s){const a=[],l=n=>{if(n.type==="rule"){if(n.col.includes("/"))return a.push(`"${n.col}" filters on a related table — not supported in a bulk delete query.`),null;if(n.valKind==="column")return a.push(`"${n.col}" compares two columns — not supported in a bulk delete query.`),null;const c=ce(n.op),p=ue(e,n.col),y=n.val??"";if(c?.kind==="null-check")return{AttributeName:n.col,Operator:n.op==="is-null"?"Null":"NotNull",Values:[]};if(c?.kind==="comparison"&&be[n.op])return{AttributeName:n.col,Operator:be[n.op],Values:[{Type:ge(p),Value:y}]};if(c?.kind==="odata-fn"){const{value:f}=Ve(y),h=qt(f),d=n.op==="contains"?`%${h}%`:n.op==="startswith"?`${h}%`:`%${h}`;return{AttributeName:n.col,Operator:n.negated?"NotLike":"Like",Values:[{Type:"System.String",Value:d}]}}return a.push(`Operator "${n.op}" on "${n.col}" has no QueryExpression mapping.`),null}if(n.type==="function"){const c=ce(n.op);if(!c||!Bt.has(n.op))return a.push(`Query function "${n.op}" has no QueryExpression mapping.`),null;if(n.negated)return a.push(`"not ${n.op}" can't be expressed in a bulk delete query.`),null;if(n.col.includes("/"))return a.push(`"${n.col}" filters on a related table — not supported in a bulk delete query.`),null;const p=c.category==="hierarchy"?e.primaryKey:n.col,y=ue(e,n.col),f=c.kind==="dv-fn-array"?n.values??[]:c.kind==="dv-fn-2"?n.vals??["",""]:c.kind==="dv-fn-0"?[]:[n.val??""],h=c.kind==="dv-fn-1-int"||c.kind==="dv-fn-2"?"System.Int32":c.kind==="dv-fn-guid"?"System.Guid":ge(y);return{AttributeName:p,Operator:n.op,Values:f.map(d=>({Type:h,Value:d}))}}return null},r=n=>{n.negated&&a.push('Negated groups ("not (…)") can’t be expressed in a bulk delete query.');const c={FilterOperator:n.combinator==="or"?"Or":"And",Conditions:[],Filters:[]};for(const p of n.rules)if(p.type==="group")c.Filters.push(r(p));else if(p.type==="lambda")a.push(`"${p.nav}/${p.lambda}(…)" filters on related records — not supported in a bulk delete query.`);else{const y=l(p);y&&c.Conditions.push(y)}return c},i=r(s);for(const n of We(s,e))a.push(`"${n.col}" needs ${n.expected}, not ${JSON.stringify(n.value)}.`);return a.push(...Xe(s)),{query:a.length?null:{EntityName:e.logicalName,Criteria:i},problems:a}}const _t=/^\{?[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}\}?$/i;function xe(e){const s=e.split(/[\s,;]+/).map(r=>r.trim()).filter(Boolean),a=[],l=[];for(const r of s)_t.test(r)?a.push(r.replace(/^\{|\}$/g,"").toLowerCase()):l.push(r);return{ids:[...new Set(a)],invalid:l}}const je=e=>({"@odata.type":"Microsoft.Dynamics.CRM.activityparty",activitypartyid:e});function Ee(e){return e&&e>0?`FREQ=DAILY;INTERVAL=${Math.floor(e)}`:""}function Ht(e,s){if(e.startMode==="at"&&e.startAt){const a=new Date(e.startAt);if(!Number.isNaN(a.getTime()))return a.toISOString()}return s.toISOString()}function Wt(e){const s=a=>String(a).padStart(2,"0");return`${e.getFullYear()}-${s(e.getMonth()+1)}-${s(e.getDate())} ${s(e.getHours())}:${s(e.getMinutes())}`}function $e(e,s){return`DRS bulk delete · ${e||"table"} · ${Wt(s)}`}function Re(e,s){const a=U(e.table);if(!a)return{body:null,problems:["Pick a target table first."],deletesAll:!1};const{query:l,problems:r}=Ut(a,e.filter),i=xe(e.toRecipients),n=xe(e.ccRecipients),c=[...r];e.jobName.trim()||c.push("Give the job a name."),(i.invalid.length||n.invalid.length)&&c.push(`Not a systemuser id: ${[...i.invalid,...n.invalid].join(", ")}`),e.sendEmail&&i.ids.length===0&&c.push("Email notification needs at least one To recipient (systemuser id)."),e.startMode==="at"&&Number.isNaN(new Date(e.startAt).getTime())&&c.push("Pick a valid start date and time."),e.recurrenceDays!==null&&!(e.recurrenceDays>=1)&&c.push("Recurrence must be every 1 day or more.");const p=!!l&&Le(l.Criteria);return{body:l?{QuerySet:[l],JobName:e.jobName.trim(),SendEmailNotification:e.sendEmail,ToRecipients:e.sendEmail?i.ids.map(je):[],CCRecipients:e.sendEmail?n.ids.map(je):[],RecurrencePattern:Ee(e.recurrenceDays),StartDateTime:Ht(e,s)}:null,problems:c,deletesAll:p}}function Le(e){return e.Conditions.length===0&&e.Filters.every(Le)}function Xt(e){const s=U(e.table),a="/BulkDelete",l=`${V.apiBase}${a}`;return{relativeUrl:l,relativeNoBase:a,bytes:l.length,queryParts:[],entitySet:s?.entitySetName??"",entityLogical:s?.logicalName??""}}function Yt(e){const s=U(e.table);if(!s)return null;const a=Ye(e.filter,s),l=r=>encodeURIComponent(r).replace(/%2F/g,"/").replace(/%2C/g,",").replace(/%3D/g,"=").replace(/%24/g,"$").replace(/%28/g,"(").replace(/%29/g,")").replace(/%20/g," ").replace(/%27/g,"'").replace(/%3A/g,":");return`${s.entitySetName}?$select=${s.primaryKey}&$count=true&$top=1`+(a?`&$filter=${l(a)}`:"")}const Oe=5e3,Vt={0:"Ready",1:"Suspended",2:"Locked",3:"Completed"},Se={0:"Waiting for resources",10:"Waiting",20:"In progress",21:"Pausing",22:"Canceling",30:"Succeeded",31:"Failed",32:"Canceled"};function Jt(e){return`asyncoperations(${e})?$select=name,statecode,statuscode,message,friendlymessage,createdon,startedon,completedon,postponeuntil,recurrencepattern`}function Qt(e){return`bulkdeleteoperations?$select=successcount,failurecount,statecode,statuscode,isrecurring&$filter=_asyncoperationid_value eq ${e}`}function zt(e){const{dirty:s,...a}=e;return a}function Gt(e,s){return{...s,...e,dirty:new Set}}const Fe=e=>{const s=typeof e=="object"&&e!==null?e:{};return s.message??s.innererror?.message??String(e)};async function Kt(e){const s=Yt(e);if(!s)return{ok:!1,error:"Table metadata not loaded."};try{const l=(await I.queryData(s))["@odata.count"];return typeof l!="number"?{ok:!1,error:"The response had no @odata.count."}:{ok:!0,count:l,capped:l>=Oe}}catch(a){return{ok:!1,error:Fe(a)}}}async function Zt(e,s){const{body:a,problems:l}=Re(e,new Date);if(!a||l.length)return de({statusCode:400,message:l[0]??"Request incomplete."},0);const r=Je(s);if(r)return r;const i=Qe(ze("impersonation",s)),n=performance.now();try{const c=await I.execute({operationName:"BulkDelete",operationType:"action",parameters:a},i);return{status:200,statusText:"OK",ms:Math.round(performance.now()-n),bytes:Ge(c??{}),ok:!0,outcome:"ok",body:c??{},headers:{"OData-Version":"4.0"}}}catch(c){return de(c,Math.round(performance.now()-n),i)}}function ea(e){if(!e||typeof e!="object")return null;const s=e.JobId;return typeof s=="string"?s:null}async function ta(){const s=(await I.execute({operationName:"WhoAmI",operationType:"function"})).UserId;if(typeof s!="string")throw new Error("WhoAmI returned no UserId.");return s.toLowerCase()}async function aa(e){try{const s=await I.queryData(Jt(e)),a=Array.isArray(s?.value)?s.value[0]??null:s??null;let l=null;try{l=(await I.queryData(Qt(e)))?.value?.[0]??null}catch{}return{job:a,operation:l}}catch(s){return{job:null,operation:null,error:Fe(s)}}}const q="bulk-delete",R="bulk",ve=5e3,Y=120,ke=()=>({table:"",filter:Te(),jobName:"",sendEmail:!1,toRecipients:"",ccRecipients:"",startMode:"now",startAt:"",recurrenceDays:null,headers:jt()});function ca({themeMode:e}){const s=Ke(q),[a,l]=u.useState(()=>({...ke(),dirty:new Set})),{table:r}=Ze(a.table||null),{allEntities:i}=et(),[n,c]=u.useState("target"),[p,y]=u.useState("builder"),[f,h]=u.useState(null),[d,S]=u.useState(null),[v,N]=u.useState(!1),[E,g]=u.useState(!1),[x,j]=u.useState([]),[k,K]=u.useState(null),[Z,ee]=u.useState(void 0),[te,ae]=u.useState(null),[_,Ae]=u.useState(()=>new Date);u.useEffect(()=>{const o=window.setInterval(()=>Ae(new Date),6e4);return()=>window.clearInterval(o)},[]);const w=U(a.table),A=u.useMemo(()=>Xt(a),[a,r]),{body:Ie,problems:H,deletesAll:P}=u.useMemo(()=>Re(a,_),[a,r,_]),M=u.useMemo(()=>tt(a.filter),[a.filter]),se=(o,m,W)=>l(oe=>{const ie=new Set(oe.dirty);return ie.add(W),{...oe,[o]:m,dirty:ie}}),Pe=a.table?w?H.length>0?H[0]:a.headers.some(o=>o.enabled&&!o.name)?"Fix empty header name.":null:"Loading table metadata…":"Pick a target table first.",Me=async()=>{g(!1),N(!0);const o=await Zt(a,me(a.headers,null));h(o),S(o.ok?ea(o.body):null),N(!1),y("results"),j(m=>[{id:`r-${Date.now()}`,modeId:q,url:A.relativeUrl,method:"POST",ts:Date.now(),status:o.status,ms:o.ms},...m].slice(0,8)),l(m=>({...m,dirty:new Set}))},B=u.useMemo(()=>zt(a),[a]),Be=u.useMemo(()=>X(B),[B]),ne=te===null?!0:Be!==te,qe=o=>{ee(o.id),ae(X(o.state))},Ue=o=>{if(o.modeId!==q)return;const m=o.state;if(i.length>0&&!i.some(W=>W.logicalName===m.table)){K(`Can't load "${o.name}": table '${m.table}' isn't available in this environment.`);return}K(null),l(Gt(m,ke())),ee(o.id),ae(X(m)),h(null),S(null),c("filter")},re=pe(qe),le=pe(Ue);at(u.useMemo(()=>a.table?{state:B,modeId:q,dirty:ne,lastSavedId:Z,onSaved:re,onLoadSaved:le}:null,[B,ne,Z,a.table,re,le]));const _e=[{id:"target",label:"Target",meta:w?`${w.displayName} · ${w.entitySetName}`:"Pick a table",items:[{id:"target",icon:nt,iconFilled:st,label:w?.displayName??"Pick a table",dirty:a.dirty.has("target")}]},{id:"query",label:"Query",meta:M?`${M} condition${M===1?"":"s"}`:"all rows",items:[{id:"filter",icon:lt,iconFilled:rt,label:"Criteria",code:!0,badge:P?"ALL":M||null,badgeAppearance:"tint",badgeColor:P?"danger":"brand",dirty:a.dirty.has("filter")}]},{id:"job",label:"Job",meta:a.recurrenceDays?`every ${a.recurrenceDays} d`:"run once",items:[{id:"job",icon:ot,iconFilled:Ne,label:"Name & schedule",badge:a.startMode==="at"?"scheduled":null,dirty:a.dirty.has("job")},{id:"notify",icon:it,iconFilled:De,label:"Email notification",badge:a.sendEmail?"on":null,dirty:a.dirty.has("notify")}]},{id:"headers",label:"Headers",meta:`${a.headers.filter(o=>o.enabled).length} active`,items:[{id:"headers",icon:ut,iconFilled:ct,label:"HTTP headers",badge:a.headers.filter(o=>o.enabled).length||null,dirty:a.dirty.has("headers")}]}];let $=null;switch(n){case"target":$=t.jsx(mt,{table:a.table,onTableChange:o=>{l(m=>({...m,table:o,filter:Te(),jobName:m.jobName&&!m.jobName.startsWith("DRS bulk delete")?m.jobName:o?$e(o,new Date):"",dirty:new Set(["target","filter"])})),h(null),S(null)},group:R,sub:"Rows of this table that match the query are deleted by an asynchronous system job. Switching the target clears the query."});break;case"filter":$=t.jsxs("div",{children:[t.jsx(sa,{deletesAll:P,problems:H,tbl:w}),t.jsx(pt,{table:a.table,tree:a.filter,setTree:o=>se("filter",o,"filter"),group:R})]});break;case"job":$=t.jsx(na,{state:a,now:_,onChange:o=>l(m=>({...m,...o,dirty:new Set([...m.dirty,"job"])}))});break;case"notify":$=t.jsx(ra,{state:a,onChange:o=>l(m=>({...m,...o,dirty:new Set([...m.dirty,"notify"])}))});break;case"headers":$=t.jsx(dt,{policy:"impersonation",items:a.headers,setItems:o=>se("headers",o,"headers"),group:R});break}const He={method:"POST",built:A,headers:me(a.headers,null),body:Ie??{},entityLogical:A.entityLogical};return t.jsxs(ht,{sidebar:t.jsx(xt,{type:s,urlPreview:A.relativeNoBase,sections:_e,activeNode:n,onSelect:o=>{c(o),y("builder")},recents:x}),urlBar:t.jsx(gt,{method:"POST",url:A.relativeUrl,executeVerb:s.executeVerb,disabledReason:Pe,loading:v,onExecute:async()=>g(!0)}),children:[t.jsxs(yt,{tab:p,onTabChange:y,resultCount:null,children:[p==="builder"&&t.jsxs(t.Fragment,{children:[k&&t.jsx(L,{intent:"error",style:{marginBottom:12},children:t.jsx(O,{children:k})}),$]}),p==="code"&&t.jsx(ft,{themeMode:e,inputs:He,group:R}),p==="results"&&(f?.ok&&d?t.jsx(oa,{jobId:d,result:f}):t.jsx(bt,{result:f,mode:"single",table:a.table}))]}),E&&w&&t.jsx(la,{state:a,tbl:w,deletesAll:P,onCancel:()=>g(!1),onConfirm:Me})]})}function sa({deletesAll:e,problems:s,tbl:a}){if(!a)return null;const l=s.filter(r=>/bulk delete query|mapping/.test(r));return t.jsxs("div",{style:{display:"flex",flexDirection:"column",gap:8,marginBottom:12},children:[e&&t.jsx(L,{intent:"error",layout:"multiline",children:t.jsxs(O,{children:[t.jsxs(J,{children:["No conditions — every ",a.displayName," row matches"]}),"Add at least one condition unless you really mean to empty the table."]})}),l.length>0&&t.jsx(L,{intent:"error",layout:"multiline",children:t.jsxs(O,{children:[t.jsx(J,{children:"Can't convert to a QueryExpression"}),t.jsx("ul",{style:{margin:"4px 0 0",paddingLeft:18},children:l.map(r=>t.jsx("li",{children:r},r))})]})}),t.jsx(L,{intent:"info",layout:"multiline",children:t.jsxs(O,{children:["BulkDelete takes a ",t.jsx("code",{children:"QueryExpression"}),", so this $filter is converted: comparisons, null checks, contains / starts / ends with (as ",t.jsx("code",{children:"Like"}),"), and the Dataverse query functions map 1:1. Related-table paths, any/all, column-to-column comparisons and negated groups or functions aren't supported. The confirmation counts matches with the same $filter before anything is submitted."]})})]})}function na({state:e,now:s,onChange:a}){return t.jsxs("div",{style:{maxWidth:640,display:"flex",flexDirection:"column",gap:14},children:[t.jsx(Ce,{icon:Ne,title:"Job",sub:"The bulk delete runs as a system job; it only deletes rows created before it starts.",group:R}),t.jsx(C,{label:"Job name",required:!0,children:t.jsx(z,{value:e.jobName,placeholder:$e(e.table,s),onChange:(l,r)=>a({jobName:r.value})})}),t.jsx(C,{label:"Start",children:t.jsxs(It,{value:e.startMode,onChange:(l,r)=>a({startMode:r.value}),children:[t.jsx(ye,{value:"now",label:"Immediately (StartDateTime = when you send)"}),t.jsx(ye,{value:"at",label:"At a specific time"})]})}),e.startMode==="at"&&t.jsx(C,{label:"Start date and time (your local time)",children:t.jsx(z,{type:"datetime-local",value:e.startAt,onChange:(l,r)=>a({startAt:r.value})})}),t.jsx(G,{checked:e.recurrenceDays!==null,onChange:(l,r)=>a({recurrenceDays:r.checked?7:null}),label:"Repeat the job"}),e.recurrenceDays!==null&&t.jsx(C,{label:"Every N days",hint:t.jsxs(t.Fragment,{children:["RecurrencePattern ",t.jsx("code",{children:Ee(e.recurrenceDays)||"—"}),". A recurring job keeps deleting new matching rows until you cancel it in System Jobs."]}),children:t.jsx(Pt,{min:1,max:365,value:e.recurrenceDays,onChange:(l,r)=>{const i=r.value??Number(r.displayValue);Number.isFinite(i)&&a({recurrenceDays:Math.max(1,Math.floor(i))})}})})]})}function ra({state:e,onChange:s}){const[a,l]=u.useState(null),r=async()=>{try{const i=await ta();e.toRecipients.toLowerCase().includes(i)||s({toRecipients:[e.toRecipients.trim(),i].filter(Boolean).join(", ")}),l(null)}catch(i){l(i instanceof Error?i.message:String(i))}};return t.jsxs("div",{style:{maxWidth:640,display:"flex",flexDirection:"column",gap:14},children:[t.jsx(Ce,{icon:De,title:"Email notification",sub:"Email users when the job finishes. Recipients are systemuser ids with a valid email address.",group:R}),t.jsx(G,{checked:e.sendEmail,onChange:(i,n)=>s({sendEmail:n.checked}),label:"Send an email when the job completes"}),e.sendEmail&&t.jsxs(t.Fragment,{children:[t.jsx(C,{label:"To (systemuser ids)",required:!0,hint:"Comma, space or new-line separated.",children:t.jsx(fe,{value:e.toRecipients,onChange:(i,n)=>s({toRecipients:n.value}),rows:2})}),t.jsxs("div",{children:[t.jsx(F,{icon:t.jsx(Mt,{}),onClick:()=>{r()},children:"Add me"}),a&&t.jsx(T,{style:{color:D.colorPaletteRedForeground1,marginLeft:8},children:a})]}),t.jsx(C,{label:"Cc (systemuser ids)",children:t.jsx(fe,{value:e.ccRecipients,onChange:(i,n)=>s({ccRecipients:n.value}),rows:2})})]})]})}function la({state:e,tbl:s,deletesAll:a,onCancel:l,onConfirm:r}){const[i,n]=u.useState(null),[c,p]=u.useState(""),[y,f]=u.useState(!1),h=Nt(),d=h.environmentUrl.replace(/^https?:\/\//,"").replace(/\/.*$/,"");u.useEffect(()=>{let g=!1;return Kt(e).then(x=>{g||n(x)}),()=>{g=!0}},[]);const S=c.trim()===s.logicalName,v=i?.ok&&i.count===0,N=S&&i!==null&&(!a||y)&&!(v&&!e.recurrenceDays),E=e.startMode==="at"&&e.startAt?new Date(e.startAt).toLocaleString():"as soon as the system job runs";return t.jsx(Dt,{open:!0,modalType:"alert",onOpenChange:(g,x)=>!x.open&&l(),children:t.jsx(Tt,{style:{maxWidth:560},children:t.jsxs(Ct,{children:[t.jsxs(Et,{children:["Delete ",s.displayName," rows in bulk?"]}),t.jsxs($t,{style:{display:"flex",flexDirection:"column",gap:10},children:[t.jsx(L,{intent:"error",layout:"multiline",children:t.jsxs(O,{children:[t.jsx(J,{children:"This permanently deletes data"}),"Deleted rows can't be restored, related rows follow the table's cascade rules, plug-ins and flows on Delete run for every row, and a failed job doesn't roll back what it already deleted."]})}),h.connected&&t.jsxs("div",{style:{display:"flex",flexWrap:"wrap",alignItems:"center",gap:8},children:[t.jsx(T,{style:{color:D.colorNeutralForeground3},children:"Environment"}),t.jsx(Q,{weight:"semibold",children:h.connectionName||d||"(no connection)"}),t.jsx(Rt,{environment:h.environment}),h.connectionName&&d&&t.jsx(T,{style:{color:D.colorNeutralForeground3,wordBreak:"break-all"},children:d})]}),t.jsx("div",{children:i===null?t.jsx(Lt,{size:"tiny",label:"Counting matching rows…",labelPosition:"after"}):i.ok?t.jsxs(Q,{weight:"semibold",size:400,children:[i.capped?`${Oe.toLocaleString()} or more`:i.count.toLocaleString()," ",s.displayName," row",i.count===1?"":"s"," match right now."]}):t.jsxs(T,{style:{color:D.colorPaletteRedForeground1},children:["Couldn't count matching rows: ",i.error]})}),v&&!e.recurrenceDays&&t.jsx(T,{children:"Nothing matches, so there's nothing to delete."}),t.jsxs(T,{children:["Job ",t.jsx("strong",{children:e.jobName||"(unnamed)"})," starts ",E,e.recurrenceDays?` and repeats every ${e.recurrenceDays} day${e.recurrenceDays===1?"":"s"}, deleting rows that match at each run`:"","."]}),a&&t.jsx(Ot,{checked:y,onChange:(g,x)=>f(!!x.checked),label:`The query has no conditions — delete every ${s.displayName} row.`}),t.jsx(C,{label:t.jsxs(t.Fragment,{children:["Type the table name ",t.jsx("code",{children:s.logicalName})," to confirm"]}),children:t.jsx(z,{value:c,onChange:(g,x)=>p(x.value),autoComplete:"off","aria-label":"Table logical name"})})]}),t.jsxs(Ft,{children:[t.jsx(F,{appearance:"secondary",onClick:l,children:"Cancel"}),t.jsx(F,{appearance:"primary",icon:t.jsx(At,{}),disabled:!N,onClick:r,style:N?{backgroundColor:D.colorPaletteRedBackground3,color:D.colorNeutralForegroundOnBrand}:void 0,children:"Submit bulk delete job"})]})]})})})}function we(e){return typeof e=="number"?e:void 0}function b(e,s,a){if(!e)return"—";const l=e[`${s}@OData.Community.Display.V1.FormattedValue`];if(typeof l=="string")return l;const r=e[s];return a&&typeof r=="number"?a[r]??String(r):r==null||r===""?"—":String(r)}function oa({jobId:e,result:s}){const[a,l]=u.useState(null),[r,i]=u.useState(0),[n,c]=u.useState(!0),[p,y]=u.useState(!1),f=we(a?.job?.statecode)===3,h=async()=>{const j=await aa(e);l(j),i(k=>k+1)};u.useEffect(()=>{h()},[e]),u.useEffect(()=>{if(!n||f||r>=Y)return;const j=window.setTimeout(()=>{h()},ve);return()=>window.clearTimeout(j)},[n,f,r]);const d=a?.job??null,S=a?.operation??null,v=we(d?.statuscode),N=v===30?"success":v===31||v===32?"danger":"info",E=V.host?`https://${V.host}/main.aspx?pagetype=entityrecord&etn=asyncoperation&id=${e}`:"",g={padding:"4px 12px 4px 0",verticalAlign:"top"},x=[["Job id",t.jsx("code",{children:e},"id")],["Name",b(d,"name")],["State",b(d,"statecode",Vt)],["Status",b(d,"statuscode",Se)],["Deleted",S?b(S,"successcount"):"—"],["Failed",S?b(S,"failurecount"):"—"],["Created",b(d,"createdon")],["Started",b(d,"startedon")],["Completed",b(d,"completedon")],["Recurrence",b(d,"recurrencepattern")],["Message",b(d,"friendlymessage")!=="—"?b(d,"friendlymessage"):b(d,"message")]];return t.jsxs("div",{style:{display:"flex",flexDirection:"column",gap:12,maxWidth:760},children:[t.jsxs("div",{style:{display:"flex",alignItems:"center",gap:10,flexWrap:"wrap"},children:[t.jsx(he,{status:"success",code:s.status,ms:s.ms}),t.jsx(Q,{weight:"semibold",children:"Bulk delete job submitted"}),a&&t.jsx(he,{status:N,code:b(d,"statuscode",Se)})]}),t.jsxs("div",{style:{display:"flex",gap:8,flexWrap:"wrap",alignItems:"center"},children:[t.jsx(F,{icon:t.jsx(St,{}),onClick:()=>{h()},children:"Refresh"}),t.jsx(G,{checked:n&&!f&&r<Y,disabled:f||r>=Y,onChange:(j,k)=>c(k.checked),label:f?"Job completed":`Auto-refresh every ${ve/1e3} s`}),t.jsx(F,{icon:t.jsx(kt,{}),onClick:()=>{vt(e,"the job ID",{toastOnSuccess:!1}).then(j=>j&&y(!0))},children:p?"Copied":"Copy job id"}),E&&t.jsx(F,{as:"a",href:E,target:"_blank",rel:"noreferrer",icon:t.jsx(wt,{}),appearance:"subtle",children:"Open system job"})]}),a?.error&&t.jsx(L,{intent:"warning",children:t.jsxs(O,{children:["Couldn't read the job: ",a.error]})}),t.jsx("table",{style:{borderCollapse:"collapse",fontSize:13},children:t.jsx("tbody",{children:x.map(([j,k])=>t.jsxs("tr",{children:[t.jsx("td",{style:{...g,color:D.colorNeutralForeground3},children:j}),t.jsx("td",{style:g,children:k})]},j))})}),t.jsxs(T,{children:["Status comes from ",t.jsxs("code",{children:["asyncoperations(",e,")"]}),"; deleted / failed counts from the matching ",t.jsx("code",{children:"bulkdeleteoperations"})," row once the job has run."]})]})}export{ca as BulkDeleteMode};
|
|
@@ -0,0 +1,6 @@
|
|
|
1
|
+
import{f as P,E as Ye,an as Xe,ao as et,ap as ve,d as tt,e as Se,r as st,m as be,h as at,j as rt,k as nt,l as y,u as it,n as ot,aq as lt,ar as dt,as as ct,at as ut,au as pt,p as X,q as we,t as ht,av as Ce,aw as mt,T as yt,v as gt,ax as $e,ay as ft,az as Re,aA as bt,L as wt,z as xt,aB as xe,aC as jt,A as t,a3 as M,aD as kt,H as vt,D as St,I as je,J as Ct,K as $t,N as $,O as R,P as Rt,R as Mt,U as It,S as Dt,ah as ae,Y as k,aE as Ft,aF as Me,aG as Ie,a0 as re,aH as te,ad as Nt,ae as De,aI as Bt,aJ as Lt,aK as At,V as Fe,a2 as E,aL as ee,aM as Ut,ai as Ot,aj as Tt,ab as Et,W as Pt,X as qt,$ as Vt,a5 as _t,a6 as Kt,a7 as zt,a8 as Gt,a9 as Wt,al as Ht,ac as Jt,af as Zt,aN as Qt,Q as Yt,aO as Xt}from"./index-XmEQbXiX.js";const Ne=["CreateMultiple","UpdateMultiple","UpsertMultiple","DeleteMultiple"],es=1e3,ts=100,ss=/^\{?[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}\}?$/i,Be=s=>ss.test(s.trim()),Le=s=>s.trim().replace(/^\{|\}$/g,"").toLowerCase();let as=1;function G(s){return{id:typeof crypto<"u"&&typeof crypto.randomUUID=="function"?`row_${crypto.randomUUID()}`:`row_${Date.now().toString(36)}_${(as++).toString(36)}`,key:s?.key??"",fieldValues:s?.fieldValues??{},nullFields:s?.nullFields??[]}}function rs(s){return G({key:"",fieldValues:ns(s.fieldValues),nullFields:[...s.nullFields]})}function ns(s){return JSON.parse(JSON.stringify(s))}const q={CreateMultiple:{label:"Create multiple",description:"Creates every row in one request and returns the new ids.",keyRequired:!1,allowsAlternateKey:!1,usesFields:!0,fieldPurpose:"create",successStatus:200},UpdateMultiple:{label:"Update multiple",description:"Updates rows addressed by their primary key (GUID). Send only changed columns.",keyRequired:!0,allowsAlternateKey:!1,usesFields:!0,fieldPurpose:"update",successStatus:204},UpsertMultiple:{label:"Upsert multiple",description:"Creates or updates each row, addressed by primary key or an alternate key. Needs a table that supports both CreateMultiple and UpdateMultiple.",keyRequired:!0,allowsAlternateKey:!0,usesFields:!0,fieldPurpose:"upsert",successStatus:204},DeleteMultiple:{label:"Delete multiple",description:"Deletes rows by primary key. Elastic tables only — for standard tables use Bulk Delete.",keyRequired:!0,allowsAlternateKey:!1,usesFields:!0,fieldPurpose:"update",successStatus:204}};function is(s,a){return Xe({table:s,fieldValues:a.fieldValues,nullFields:a.nullFields})}function os(s,a,e){const r=q[s.operation],i={"@odata.type":`Microsoft.Dynamics.CRM.${a.logicalName}`},o=r.usesFields?is(s.table,e):{};Object.assign(i,o);const u=e.key.trim();let l;if(u?Be(u)?i[a.primaryKey]=Le(u):r.allowsAlternateKey?i["@odata.id"]=`${a.entitySetName}(${u})`:l=s.operation==="UpdateMultiple"?"Key must be a GUID — UpdateMultiple in the Web API does not accept alternate keys.":"Key must be a GUID.":r.keyRequired&&(l=s.operation==="UpsertMultiple"?"Missing key — a GUID or an alternate key such as name='value'.":"Missing primary key (GUID)."),!l&&s.operation!=="DeleteMultiple"&&Object.keys(o).length===0&&(l="No column values set."),!l&&s.operation==="CreateMultiple"){const d=ls(a,e);d.length>0&&(l=`Required column${d.length===1?"":"s"} unset: ${d.slice(0,3).join(", ")}${d.length>3?"…":""}`)}return{target:i,issue:l}}function ls(s,a){return s.columns.filter(e=>et(e)).filter(e=>{const r=a.fieldValues[e.logicalName];return r==null||r===""?!0:Array.isArray(r)?r.length===0:ve(e)?!r?.id:!1}).map(e=>e.logicalName)}function Ae(s){const a=P(s.table);if(!a)return{body:{Targets:[]},issues:[]};const e=[],r=new Map;return{body:{Targets:s.rows.map((o,u)=>{const{target:l,issue:d}=os(s,a,o);d&&e.push({rowIndex:u,rowId:o.id,message:d});const p=o.key.trim().toLowerCase();if(p){const m=r.get(p);m!==void 0?e.push({rowIndex:u,rowId:o.id,message:s.operation==="UpdateMultiple"?`Same key as row ${m+1} — UpdateMultiple applies only the first of them.`:`Same key as row ${m+1} — duplicate keys fail the request.`}):r.set(p,u)}return l})},issues:e}}function ds(s){const a=P(s.table);if(!a)return{relativeUrl:"",relativeNoBase:"",bytes:0,queryParts:[],entitySet:"",entityLogical:""};const e=`/${a.entitySetName}/Microsoft.Dynamics.CRM.${s.operation}`,r=`${Ye.apiBase}${e}`;return{relativeUrl:r,relativeNoBase:e,bytes:r.length,queryParts:[],entitySet:a.entitySetName,entityLogical:a.logicalName}}function cs(s){return s==="UpsertMultiple"?["CreateMultiple","UpdateMultiple"]:[s]}function us(s,a){const e=r=>`'${r.replace(/'/g,"''")}'`;return`sdkmessagefilters?$select=sdkmessagefilterid&$filter=sdkmessageid/name eq ${e(s)} and primaryobjecttypecode eq ${e(a)}`}function ps(s,a,e){const r=P(s.table);if(!s.table)return"Pick a target table first.";if(!r)return"Loading table metadata…";if(e.state==="unsupported")return e.message;if(s.rows.length===0)return"Add at least one row.";if(a.length>0){const i=a[0];return`Row ${i.rowIndex+1}: ${i.message}${a.length>1?` (+${a.length-1} more)`:""}`}return s.headers.some(i=>i.enabled&&!i.name)?"Fix empty header name.":null}function hs(s,a,e){return s==="DeleteMultiple"?`DeleteMultiple isn't available for '${a}'. It's supported on elastic tables only — use the Bulk Delete mode (an asynchronous job) for standard tables.`:s==="UpsertMultiple"?`UpsertMultiple needs both CreateMultiple and UpdateMultiple, and '${a}' doesn't support ${e.join(" or ")}.`:`'${a}' doesn't support ${s} (no sdkmessagefilter for this table).`}const ms=new Set(["@key","key","id","@odata.id"]);function ys(s,a){const e=s.trim();if(!e)return{rows:[],skippedColumns:[],errors:[]};let r;if(e.startsWith("[")||e.startsWith("{")){let l;try{l=JSON.parse(e)}catch(p){return{rows:[],skippedColumns:[],errors:[`Invalid JSON: ${p instanceof Error?p.message:String(p)}`]}}const d=Array.isArray(l)?l:l&&typeof l=="object"?l.Targets??l.value:void 0;if(!Array.isArray(d))return{rows:[],skippedColumns:[],errors:['JSON must be an array of objects (or { "Targets": [ … ] }).']};r=d.filter(p=>!!p&&typeof p=="object")}else{const l=js(e);if(l.length<2)return{rows:[],skippedColumns:[],errors:["CSV needs a header row and at least one data row."]};const[d,...p]=l;r=p.filter(m=>m.some(g=>g.trim()!=="")).map(m=>{const g={};return d.forEach((j,S)=>{const b=m[S];b!==void 0&&b!==""&&(g[j.trim()]=b)}),g})}const i=new Set,o=[];return{rows:r.map((l,d)=>{const p=G();for(const[m,g]of Object.entries(l)){const j=m.trim();if(j==="@odata.type"||j==="@odata.etag"||g===void 0)continue;if(ms.has(j.toLowerCase())||j.toLowerCase()===a.primaryKey){p.key=gs(String(g??""),a);continue}const S=/^(.+)@odata\.bind$/i.exec(j),b=fs(a,S?S[1]:j);if(!b){i.add(j);continue}if(g===null){p.nullFields.push(b.logicalName);continue}const w=bs(b,g);"error"in w?o.push(`Row ${d+1}, ${j}: ${w.error}`):p.fieldValues[b.logicalName]=w.value}return p}),skippedColumns:[...i],errors:o}}function gs(s,a){const e=/^\/?([A-Za-z0-9_]+)\((.*)\)$/.exec(s.trim());return e&&e[1]===a.entitySetName?e[2]:s.trim()}function fs(s,a){const e=a.toLowerCase(),r=tt(s,e);if(r)return r;const i=s.columns.find(o=>ve(o)&&e.startsWith(`${o.logicalName}_`));return i||s.columns.find(o=>o.displayName.toLowerCase()===e)}function ke(s,a){if(typeof a=="number")return a;const e=String(a).trim();return/^-?\d+$/.test(e)?Number(e):s.find(r=>r.label.toLowerCase()===e.toLowerCase())?.value}function bs(s,a){const e=typeof a=="string"?a.trim():a;switch(s.attributeType){case"Integer":case"BigInt":case"Decimal":case"Double":case"Money":{const r=typeof e=="number"?e:Number(String(e).replace(/,/g,""));return Number.isFinite(r)?(s.attributeType==="Integer"||s.attributeType==="BigInt")&&!Number.isInteger(r)?{error:`"${String(a)}" is not a whole number`}:{value:r}:{error:`"${String(a)}" is not a number`}}case"Boolean":{if(typeof e=="boolean")return{value:e};const r=String(e).toLowerCase();return["true","1","yes","y"].includes(r)?{value:!0}:["false","0","no","n"].includes(r)?{value:!1}:r===s.trueOption.label.toLowerCase()?{value:!0}:r===s.falseOption.label.toLowerCase()?{value:!1}:{error:`"${String(a)}" is not a yes/no value`}}case"Picklist":case"State":case"Status":case"EntityName":{const r=ke(s.options,e);return r===void 0?{error:`unknown choice "${String(a)}"`}:{value:r}}case"MultiSelectPicklist":{const r=Array.isArray(e)?e:String(e).split(/[,;]/).map(o=>o.trim()).filter(Boolean),i=[];for(const o of r){const u=ke(s.options,o);if(u===void 0)return{error:`unknown choice "${String(o)}"`};i.push(u)}return{value:i}}case"Lookup":case"Customer":case"Owner":{const r=String(e),i=/^\/?([A-Za-z0-9_]+)\(\{?([0-9a-fA-F-]{36})\}?\)$/.exec(r);if(i){const d=s.targets.find(p=>P(p)?.entitySetName===i[1]);return d?{value:{id:i[2].toLowerCase(),targetEntity:d}}:{error:`"${i[1]}" is not a target of ${s.logicalName}`}}const o=/^([A-Za-z0-9_]+):\s*(.+)$/.exec(r),u=o?o[1].toLowerCase():s.targets[0],l=o?o[2]:r;return Be(l)?s.targets.includes(u)?{value:{id:Le(l),targetEntity:u}}:{error:`"${u}" is not a target of ${s.logicalName}`}:{error:`"${r}" is not a GUID`}}case"File":case"Image":return{error:"file and image columns can’t be set in a bulk write"};default:return{value:typeof e=="string"?e:String(e)}}}function ws(s){const{dirty:a,...e}=s;return e}function xs(s,a){return{...a,...s,operation:Ne.includes(s.operation)?s.operation:"CreateMultiple",rows:(s.rows??[]).map(e=>({id:e.id||G().id,key:e.key??"",fieldValues:e.fieldValues??{},nullFields:e.nullFields??[]})),dirty:new Set}}function js(s){const a=s.split(/\r?\n/,1)[0],e=a.includes(" ")&&!a.includes(",")?" ":",",r=[];let i=[],o="",u=!1;for(let l=0;l<s.length;l++){const d=s[l];if(u){d==='"'?s[l+1]==='"'?(o+='"',l++):u=!1:o+=d;continue}d==='"'&&o===""?u=!0:d===e?(i.push(o),o=""):d===`
|
|
2
|
+
`||d==="\r"?(d==="\r"&&s[l+1]===`
|
|
3
|
+
`&&l++,i.push(o),r.push(i),i=[],o=""):o+=d}return i.push(o),r.push(i),r}async function ks(s,a){try{const e=[];for(const r of cs(a))(await Se.queryData(us(r,s)))?.value?.length||e.push(r);return e.length===0?{state:"supported"}:{state:"unsupported",message:hs(a,s,e)}}catch(e){return{state:"unknown",message:`Couldn't check ${a} availability: ${e instanceof Error?e.message:String(e)}`}}}async function vs(s,a){const e=st(a);if(e)return e;const{body:r,issues:i}=Ae(s);if(i.length>0)return be({statusCode:400,message:`Row ${i[0].rowIndex+1}: ${i[0].message}`},0);const o=at(a),u=performance.now();try{const l=await Se.execute({operationName:s.operation,operationType:"action",entityName:s.table,parameters:r},o),d=Math.round(performance.now()-u),p=l&&Object.keys(l).length>0?l:null;return{status:p?200:204,statusText:p?"OK":"No Content",ms:d,bytes:rt(p),ok:!0,outcome:"ok",body:p,headers:{"OData-Version":"4.0"}}}catch(l){return be(l,Math.round(performance.now()-u),o)}}function se(s){if(!s||typeof s!="object")return[];const a=s.Ids;return Array.isArray(a)?a.filter(e=>typeof e=="string"):[]}const z="bulk-write",D="bulk",L=100,Ss=25,Ue=()=>({table:"",operation:"CreateMultiple",rows:[],headers:Yt(),bypass:Qt()}),Cs=()=>({...Ue(),dirty:new Set}),T=s=>`row:${s}`;function Bs({themeMode:s}){const a=nt(z),[e,r]=y.useState(Cs),{table:i}=it(e.table||null),{allEntities:o}=ot(),[u,l]=y.useState("target"),[d,p]=y.useState("builder"),[m,g]=y.useState(null),[j,S]=y.useState("CreateMultiple"),[b,w]=y.useState(!1),[W,H]=y.useState([]),[x,v]=y.useState({state:"idle"}),[J,F]=y.useState(!1),[I,A]=y.useState(null),[Z,V]=y.useState(void 0),[ne,ie]=y.useState(null),C=P(e.table),U=y.useMemo(()=>ds(e),[e,i]),{body:Oe,issues:O}=y.useMemo(()=>Ae(e),[e,i]),Te=q[e.operation];y.useEffect(()=>{if(!e.table){v({state:"idle"});return}if(!lt()){v({state:"unknown",message:"Not connected to Power Platform ToolBox — availability not checked."});return}let n=!1;return v({state:"checking"}),ks(e.table,e.operation).then(c=>{n||v(c)}),()=>{n=!0}},[e.table,e.operation]);const oe=(n,c)=>{const h=new Set(n.dirty);return h.add(c),h},Q=(n,c,h)=>r(f=>({...f,[n]:c,dirty:oe(f,h)})),B=n=>r(c=>({...c,rows:n(c.rows),dirty:oe(c,"rows")})),le=(n,c)=>B(h=>h.map(f=>f.id===n?{...f,...c}:f)),Ee=()=>G({fieldValues:C&&e.operation==="CreateMultiple"?Xt(C):{}}),Pe=n=>{const c=Ee();B(h=>[...h,c])},de=n=>{const c=e.rows.find(f=>f.id===n);if(!c)return;const h=rs(c);B(f=>{const Ze=f.findIndex(Qe=>Qe.id===n),fe=[...f];return fe.splice(Ze+1,0,h),fe})},ce=n=>{B(c=>c.filter(h=>h.id!==n)),u===T(n)&&l("rows")},_=y.useMemo(()=>dt(e.headers,e.bypass),[e.headers,e.bypass]),ue=y.useMemo(()=>[...ct(e.bypass,"bypass"),...ut({op:"create",bypass:e.bypass})],[e.bypass]),qe=pt(ue),Ve=ps(e,O,x)??(x.state==="checking"?`Checking ${e.operation} availability…`:null),_e=async()=>{w(!0);const n=e.operation,c=await vs(e,je(_,null));g(c),S(n),w(!1),p("results");const h=se(c.body);H(f=>[{id:`r-${Date.now()}`,modeId:z,url:U.relativeUrl,method:"POST",ts:Date.now(),status:c.status,ms:c.ms,rowCount:c.ok?h.length||e.rows.length:0,summary:c.ok?`${h.length||e.rows.length} ${(h.length||e.rows.length)===1?"row":"rows"} written`:void 0},...f].slice(0,8)),r(f=>({...f,dirty:new Set}))},K=y.useMemo(()=>ws(e),[e]),Ke=y.useMemo(()=>X(K),[K]),pe=ne===null?!0:Ke!==ne,ze=n=>{V(n.id),ie(X(n.state))},Ge=n=>{if(n.modeId!==z)return;const c=n.state;if(o.length>0&&!o.some(h=>h.logicalName===c.table)){A(`Can't load "${n.name}": table '${c.table}' isn't available in this environment.`);return}A(null),r(xs(c,Ue())),V(n.id),ie(X(c)),g(null),l("rows")},he=we(ze),me=we(Ge);ht(y.useMemo(()=>e.table?{state:K,modeId:z,dirty:pe,lastSavedId:Z,onSaved:he,onLoadSaved:me}:null,[K,pe,Z,e.table,he,me]));const Y=y.useMemo(()=>{const n=new Map;for(const c of O)n.has(c.rowId)||n.set(c.rowId,c.message);return n},[O]),ye=(n,c)=>{const h=C?n.fieldValues[C.primaryName]:void 0,f=n.key||typeof h=="string"&&h||"";return f?`#${c+1} · ${f}`:`#${c+1}`},We=e.rows.slice(0,Ss).map((n,c)=>{const h=Y.get(n.id),f=Object.keys(n.fieldValues).length+n.nullFields.length;return{id:T(n.id),icon:mt,iconFilled:Ce,label:ye(n,c),badge:h?"!":f||null,badgeAppearance:"tint",badgeColor:h?"danger":"success"}}),ge=x.state==="supported"?{badge:"supported",color:"success"}:x.state==="unsupported"?{badge:"unsupported",color:"danger"}:x.state==="checking"?{badge:"…",color:"subtle"}:x.state==="unknown"?{badge:"?",color:"warning"}:{badge:null,color:"subtle"},He=[{id:"target",label:"Target",meta:C?`${C.displayName} · ${C.entitySetName}`:"Pick a table",items:[{id:"target",icon:gt,iconFilled:yt,label:C?.displayName??"Pick a table",dirty:e.dirty.has("target")}]},{id:"operation",label:"Operation",meta:e.operation,items:[{id:"operation",icon:ft,iconFilled:$e,label:Te.label,badge:ge.badge,badgeAppearance:"tint",badgeColor:ge.color,dirty:e.dirty.has("operation")}]},{id:"rows",label:"Rows",meta:`${e.rows.length} row${e.rows.length===1?"":"s"}`,items:[{id:"rows",icon:bt,iconFilled:Re,label:"All rows",badge:O.length||null,badgeAppearance:"tint",badgeColor:"danger",dirty:e.dirty.has("rows"),children:We}]},{id:"headers",label:"Headers",meta:`${_.filter(n=>n.enabled).length} active`,items:[{id:"headers",icon:xt,iconFilled:wt,label:"HTTP headers",badge:_.filter(n=>n.enabled).length||null,dirty:e.dirty.has("headers")},{id:"bypass",icon:xe,iconFilled:xe,label:"Bypass logic",badge:jt(e.bypass),badgeAppearance:e.bypass.businessLogic!=="none"||e.bypass.suppressFlows?"tint":"ghost",badgeColor:e.bypass.businessLogic!=="none"||e.bypass.suppressFlows?"warning":"subtle",dirty:e.dirty.has("bypass")}]}];let N=null;if(u.startsWith("row:")){const n=e.rows.findIndex(h=>T(h.id)===u),c=e.rows[n];N=c?t.jsx(Is,{row:c,index:n,count:e.rows.length,table:e.table,tbl:C,operation:e.operation,issue:Y.get(c.id),themeMode:s,onPatch:h=>le(c.id,h),onNavigate:h=>l(T(e.rows[h].id)),onBack:()=>l("rows"),onDuplicate:()=>de(c.id),onRemove:()=>ce(c.id)},c.id):t.jsx(M,{children:"That row was removed."})}else switch(u){case"target":N=t.jsx(St,{table:e.table,onTableChange:n=>{r(c=>({...c,table:n,rows:[],dirty:new Set(["target","rows"])})),g(null)},group:D,sub:"Every row in a bulk request targets the same table. Switching the target clears the rows."});break;case"operation":N=t.jsx($s,{operation:e.operation,setOperation:n=>Q("operation",n,"operation"),support:x,table:e.table});break;case"rows":N=t.jsx(Ms,{state:e,tbl:C,issueByRow:Y,issueCount:O.length,rowLabel:ye,onAdd:()=>Pe(),onImport:()=>F(!0),onClear:()=>B(()=>[]),onEdit:n=>l(T(n)),onDuplicate:de,onRemove:ce,onKeyChange:(n,c)=>le(n,{key:c})});break;case"headers":N=t.jsx(vt,{items:e.headers,setItems:n=>Q("headers",n,"headers"),group:D,sendsHeaders:!0});break;case"bypass":N=t.jsx(kt,{value:e.bypass,onChange:n=>Q("bypass",n,"bypass"),group:D});break}const Je={method:"POST",built:U,headers:je(_,null),body:Oe,entityLogical:U.entityLogical};return t.jsxs(Ct,{sidebar:t.jsx(Dt,{type:a,urlPreview:U.relativeNoBase,sections:He,activeNode:u,onSelect:n=>{l(n),p("builder")},recents:W}),urlBar:t.jsx(It,{method:"POST",url:U.relativeUrl,executeVerb:a.executeVerb,writeConfirm:{operation:`Bulk Write · ${e.operation}`,table:e.table,scope:{kind:"records",count:e.rows.length},highImpact:!0},disabledReason:Ve??qe,loading:b,onExecute:_e,advisories:ue,onAdvisoryFocus:l}),children:[t.jsxs($t,{tab:d,onTabChange:p,resultCount:m?.ok&&se(m.body).length||null,children:[d==="builder"&&t.jsxs(t.Fragment,{children:[I&&t.jsx($,{intent:"error",style:{marginBottom:12},children:t.jsx(R,{children:I})}),N]}),d==="code"&&t.jsx(Rt,{themeMode:s,inputs:Je,group:D}),d==="results"&&(m&&m.ok?t.jsx(Fs,{result:m,operation:j}):t.jsx(Mt,{result:m,mode:"single",table:e.table}))]}),t.jsx(Ds,{open:J,tbl:C,onClose:()=>F(!1),onImport:(n,c)=>{B(h=>c?n:[...h,...n]),F(!1),l("rows")}})]})}function $s({operation:s,setOperation:a,support:e,table:r}){return t.jsxs("div",{style:{maxWidth:760},children:[t.jsx(ae,{icon:$e,title:"Operation",sub:"One request, many rows of the same table. On standard tables the whole request rolls back if any row fails.",group:D}),t.jsx(Ot,{value:s,onChange:(i,o)=>a(o.value),"aria-label":"Bulk operation",children:Ne.map(i=>t.jsx(Tt,{value:i,label:t.jsxs("span",{children:[t.jsx("code",{children:i}),t.jsx("br",{}),t.jsx(M,{children:q[i].description})]})},i))}),t.jsxs("div",{style:{marginTop:16,display:"flex",flexDirection:"column",gap:8},children:[r?e.state==="checking"?t.jsx(Et,{size:"tiny",label:`Checking ${s} availability for ${r}…`}):e.state==="supported"?t.jsx($,{intent:"success",children:t.jsxs(R,{children:[t.jsx("code",{children:r})," supports ",s,"."]})}):e.state==="unsupported"?t.jsx($,{intent:"error",layout:"multiline",children:t.jsxs(R,{children:[t.jsx(Fe,{children:"Not available"}),e.message]})}):e.state==="unknown"?t.jsx($,{intent:"warning",layout:"multiline",children:t.jsx(R,{children:e.message})}):null:t.jsx($,{intent:"info",children:t.jsxs(R,{children:["Pick a table to check whether it supports ",s,"."]})}),t.jsx($,{intent:"info",layout:"multiline",children:t.jsxs(R,{children:["Availability comes from the table's ",t.jsx("code",{children:"sdkmessagefilters"}),"."," ",t.jsx("code",{children:"UpsertMultiple"})," has no filter of its own — it's available where both"," ",t.jsx("code",{children:"CreateMultiple"})," and ",t.jsx("code",{children:"UpdateMultiple"})," are. Send 100–1,000 rows per request on standard tables (",ts," on elastic tables); there's no fixed cap, but large payloads hit size and time limits."," ",t.jsx("a",{href:"https://learn.microsoft.com/en-us/power-apps/developer/data-platform/bulk-operations",target:"_blank",rel:"noreferrer",children:"Use bulk operation messages"})]})})]})]})}function Rs(s,a){const e=a?.primaryKey??"primary key";switch(s){case"CreateMultiple":return`optional ${e} GUID`;case"UpsertMultiple":return`${e} GUID or key='value'`;default:return`${e} GUID`}}function Ms({state:s,tbl:a,issueByRow:e,issueCount:r,rowLabel:i,onAdd:o,onImport:u,onClear:l,onEdit:d,onDuplicate:p,onRemove:m,onKeyChange:g}){const[j,S]=y.useState(0),b=Math.max(1,Math.ceil(s.rows.length/L)),w=Math.min(j,b-1),W=s.rows.slice(w*L,(w+1)*L),H=q[s.operation],x={padding:"4px 8px",borderBottom:`1px solid ${E.colorNeutralStroke2}`};return t.jsxs("div",{children:[t.jsxs(ae,{icon:Re,title:"Rows",sub:`Each row becomes one item in Targets. ${H.keyRequired?"Every row needs a key.":"A key is optional."}`,group:D,children:[t.jsx(k,{icon:t.jsx(Lt,{}),onClick:o,disabled:!a,children:"Add row"}),t.jsx(k,{icon:t.jsx(At,{}),onClick:u,disabled:!a,children:"Import CSV / JSON…"}),t.jsx(k,{icon:t.jsx(te,{}),appearance:"subtle",onClick:l,disabled:s.rows.length===0,children:"Clear"})]}),!a&&t.jsx($,{intent:"info",children:t.jsx(R,{children:"Pick a target table first."})}),s.rows.length>es&&t.jsx($,{intent:"warning",layout:"multiline",style:{marginBottom:8},children:t.jsxs(R,{children:[t.jsxs(Fe,{children:[s.rows.length.toLocaleString()," rows"]}),"Microsoft recommends 100–1,000 rows per request. Larger requests are more likely to hit message-size or time limits, and on standard tables a failure rolls back every row. Consider splitting the rows into several requests."]})}),r>0&&t.jsx($,{intent:"error",style:{marginBottom:8},children:t.jsxs(R,{children:[r," row issue",r===1?"":"s"," — fix them before sending."]})}),a&&s.rows.length===0&&t.jsx(M,{children:"No rows yet. Add rows one by one, or import them from CSV (header row of column names — Excel copy-paste works) or a JSON array of objects."}),s.rows.length>0&&t.jsxs("table",{style:{borderCollapse:"collapse",width:"100%",fontSize:13},children:[t.jsx("thead",{children:t.jsxs("tr",{style:{textAlign:"left"},children:[t.jsx("th",{style:x,children:"#"}),t.jsx("th",{style:x,children:"Key"}),t.jsx("th",{style:x,children:"Columns"}),t.jsx("th",{style:x,children:"Status"}),t.jsx("th",{style:x,"aria-label":"Actions"})]})}),t.jsx("tbody",{children:W.map((v,J)=>{const F=w*L+J,I=[...Object.keys(v.fieldValues),...v.nullFields],A=e.get(v.id);return t.jsxs("tr",{children:[t.jsx("td",{style:x,children:F+1}),t.jsx("td",{style:{...x,minWidth:220},children:t.jsx(De,{size:"small",value:v.key,placeholder:Rs(s.operation,a),onChange:(Z,V)=>g(v.id,V.value),"aria-label":`Row ${F+1} key`,style:{width:"100%"}})}),t.jsx("td",{style:x,children:t.jsx(M,{title:I.join(", "),children:I.length===0?"—":`${I.length}: ${I.slice(0,3).join(", ")}${I.length>3?"…":""}`})}),t.jsx("td",{style:x,children:A?t.jsx(M,{style:{color:E.colorPaletteRedForeground1},children:A}):t.jsx(M,{style:{color:E.colorPaletteGreenForeground1},children:"Ready"})}),t.jsxs("td",{style:{...x,whiteSpace:"nowrap"},children:[t.jsx(ee,{content:`Edit ${i(v,F)}`,relationship:"label",children:t.jsx(k,{size:"small",appearance:"subtle",icon:t.jsx(Ut,{}),onClick:()=>d(v.id)})}),t.jsx(ee,{content:"Duplicate row",relationship:"label",children:t.jsx(k,{size:"small",appearance:"subtle",icon:t.jsx(re,{}),onClick:()=>p(v.id)})}),t.jsx(ee,{content:"Remove row",relationship:"label",children:t.jsx(k,{size:"small",appearance:"subtle",icon:t.jsx(te,{}),onClick:()=>m(v.id)})})]})]},v.id)})})]}),b>1&&t.jsxs("div",{style:{display:"flex",alignItems:"center",gap:8,marginTop:8},children:[t.jsx(k,{size:"small",icon:t.jsx(Me,{}),disabled:w===0,onClick:()=>S(w-1),"aria-label":"Previous page"}),t.jsxs(M,{children:["Rows ",w*L+1,"–",Math.min((w+1)*L,s.rows.length)," of"," ",s.rows.length]}),t.jsx(k,{size:"small",icon:t.jsx(Ie,{}),disabled:w>=b-1,onClick:()=>S(w+1),"aria-label":"Next page"})]})]})}function Is({row:s,index:a,count:e,table:r,tbl:i,operation:o,issue:u,themeMode:l,onPatch:d,onNavigate:p,onBack:m,onDuplicate:g,onRemove:j}){const S=q[o];return t.jsxs("div",{children:[t.jsxs(ae,{icon:Ce,title:`Row ${a+1} of ${e}`,sub:o==="DeleteMultiple"?"Only the key (and partitionid on partitioned elastic tables) is needed.":void 0,group:D,children:[t.jsx(k,{icon:t.jsx(Ft,{}),appearance:"subtle",onClick:m,children:"All rows"}),t.jsx(k,{icon:t.jsx(Me,{}),disabled:a===0,onClick:()=>p(a-1),"aria-label":"Previous row"}),t.jsx(k,{icon:t.jsx(Ie,{}),disabled:a>=e-1,onClick:()=>p(a+1),"aria-label":"Next row"}),t.jsx(k,{icon:t.jsx(re,{}),onClick:g,children:"Duplicate"}),t.jsx(k,{icon:t.jsx(te,{}),appearance:"subtle",onClick:j,children:"Remove"})]}),t.jsx(Nt,{label:S.keyRequired?"Key (required)":"Key (optional)",hint:o==="UpsertMultiple"?`A ${i?.primaryKey??"primary key"} GUID, or an alternate key segment such as name='Contoso' — sent as @odata.id.`:o==="CreateMultiple"?`Leave empty to let Dataverse assign the id, or set a ${i?.primaryKey??"primary key"} GUID.`:`The ${i?.primaryKey??"primary key"} GUID of the row.`,validationState:u?"error":"none",validationMessage:u,style:{maxWidth:520,marginBottom:12},children:t.jsx(De,{value:s.key,onChange:(b,w)=>d({key:w.value})})}),S.usesFields&&t.jsx(Bt,{table:r,values:s.fieldValues,setValues:b=>d({fieldValues:b}),nullFields:s.nullFields,setNullFields:b=>d({nullFields:b}),group:D,themeMode:l,purpose:S.fieldPurpose})]})}function Ds({open:s,tbl:a,onClose:e,onImport:r}){const[i,o]=y.useState(""),[u,l]=y.useState(!1),d=y.useMemo(()=>a?ys(i,a):{rows:[],skippedColumns:[],errors:[]},[i,a]),p=async m=>{m&&o(await m.text())};return t.jsx(_t,{open:s,onOpenChange:(m,g)=>!g.open&&e(),children:t.jsx(Kt,{style:{maxWidth:760},children:t.jsxs(zt,{children:[t.jsxs(Gt,{children:["Import rows",a?` into ${a.displayName}`:""]}),t.jsxs(Wt,{style:{display:"flex",flexDirection:"column",gap:10},children:[t.jsxs(M,{children:["Paste CSV / tab-separated text with a header row of column logical (or display) names, or a JSON array of objects. A ",t.jsx("code",{children:a?.primaryKey??"primary key"}),","," ",t.jsx("code",{children:"id"})," or ",t.jsx("code",{children:"@key"})," column fills the row key. Lookups take a GUID (first target) or ",t.jsx("code",{children:"table:guid"}),"; choices take the value or the label."]}),t.jsx(Ht,{value:i,onChange:(m,g)=>o(g.value),rows:12,"aria-label":"Rows to import",placeholder:`name,numberofemployees
|
|
4
|
+
Contoso,10
|
|
5
|
+
Fabrikam,25`,textarea:{style:{fontFamily:E.fontFamilyMonospace,fontSize:12}}}),t.jsxs("div",{style:{display:"flex",alignItems:"center",gap:12,flexWrap:"wrap"},children:[t.jsx("input",{type:"file",accept:".csv,.tsv,.txt,.json","aria-label":"Load rows from a file",onChange:m=>{p(m.target.files?.[0])}}),t.jsx(Jt,{checked:u,onChange:(m,g)=>l(!!g.checked),label:"Replace existing rows"})]}),i.trim()&&t.jsx($,{intent:d.errors.length?"warning":d.rows.length?"success":"info",layout:"multiline",children:t.jsxs(R,{children:[d.rows.length," row",d.rows.length===1?"":"s"," parsed.",d.skippedColumns.length>0&&t.jsxs(t.Fragment,{children:[" Skipped columns (not on this table): ",d.skippedColumns.join(", "),"."]}),d.errors.length>0&&t.jsxs("ul",{style:{margin:"4px 0 0",paddingLeft:18},children:[d.errors.slice(0,6).map(m=>t.jsx("li",{children:m},m)),d.errors.length>6&&t.jsxs("li",{children:["…and ",d.errors.length-6," more"]})]})]})})]}),t.jsxs(Zt,{children:[t.jsx(k,{appearance:"secondary",onClick:e,children:"Cancel"}),t.jsxs(k,{appearance:"primary",disabled:d.rows.length===0,onClick:()=>{r(d.rows,u),o("")},children:["Import ",d.rows.length||""," row",d.rows.length===1?"":"s"]})]})]})})})}function Fs({result:s,operation:a}){const e=se(s.body),[r,i]=y.useState(!1);return t.jsxs("div",{style:{display:"flex",flexDirection:"column",gap:12,maxWidth:760},children:[t.jsxs("div",{style:{display:"flex",alignItems:"center",gap:10},children:[t.jsx(Pt,{status:"success",code:s.status,ms:s.ms}),t.jsxs(qt,{weight:"semibold",children:[a," ",e.length>0?`created ${e.length} row${e.length===1?"":"s"}`:"completed"]})]}),e.length>0?t.jsxs(t.Fragment,{children:[t.jsx("div",{children:t.jsx(k,{icon:t.jsx(re,{}),onClick:()=>{Vt(e.join(`
|
|
6
|
+
`),"the IDs",{toastOnSuccess:!1,shown:!1}).then(o=>o&&i(!0))},children:r?"Copied":"Copy ids"})}),t.jsx("ol",{style:{margin:0,paddingLeft:32,fontFamily:E.fontFamilyMonospace,fontSize:12,maxHeight:480,overflow:"auto"},children:e.map(o=>t.jsx("li",{children:o},o))})]}):t.jsxs(M,{children:[a," returns 204 No Content — Dataverse doesn't report per-row results for it. Every row in the request succeeded (a failure would have rolled back the request on a standard table)."]})]})}export{Bs as BulkWriteMode};
|
|
@@ -0,0 +1,2 @@
|
|
|
1
|
+
import{k as Ee,b9 as De,b$ as re,l as n,u as Re,n as Me,c0 as $e,c1 as Fe,f as H,c2 as Le,bU as Q,bc as Ae,c3 as Be,be as He,p as W,q as ne,t as ze,T as qe,v as Ue,bW as Ve,bX as We,bL as J,bM as Oe,L as _e,z as Ke,A as e,H as Je,D as Qe,bZ as Xe,I as oe,J as Ze,K as Ge,P as Ye,R as et,b_ as O,U as tt,S as at,Q as st,b0 as rt,ah as le,N as _,O as K,V as ie,aB as nt,a2 as d,a3 as C,ab as ot,c4 as lt,b8 as it,br as dt,b1 as ct,bs as ut,bq as gt}from"./index-XmEQbXiX.js";import{t as ue,N as ht,A as mt}from"./AssociateTargetsEditor-BoH9Qxe8.js";const pt=()=>({table:"",sourceId:null,navProperty:null,targetIds:[],targetNames:{},headers:st(),dirty:new Set});function St({themeMode:l}){const m=Ee("disassociate"),g=De("disassociate",re,pt),[t,o]=n.useState(g.state),{table:S}=Re(t.table||null),{allEntities:j}=Me(),[w,c]=n.useState("source"),[b,E]=n.useState("builder"),[D,z]=n.useState(null),[ge,X]=n.useState(!1),[he,me]=n.useState([]),[R,M]=n.useState(g.lastSavedId),[$,F]=n.useState(g.lastSavedHash),[Z,q]=n.useState(""),[p,f]=n.useState(null),[G,k]=n.useState(!1),[U,L]=n.useState(null),T=n.useMemo(()=>$e(t),[t,S]),v=n.useMemo(()=>Fe(t),[t,S]),y=H(t.table),r=t.navProperty?y?.navigationProperties.find(a=>a.name===t.navProperty):void 0,pe=r?Le(r):!1,h=r?Q(r):!1,I=h?"PATCH":"DELETE";n.useEffect(()=>{let a=!1;if(L(null),!h||!t.sourceId||!y||!r){f(null),k(!1);return}if(typeof window>"u"||!window.dataverseAPI?.queryData){f(null),k(!1),L("The PPTB host is not available, so the current value cannot be read.");return}f(null),k(!0);const s=`_${r.referencingAttribute||r.name}_value`,u=`/${y.entitySetName}(${t.sourceId})?$select=${s}`;return window.dataverseAPI.queryData(u).then(i=>{if(a)return;const N=i?.value,B=Array.isArray(N)?N[0]??null:N&&typeof N=="object"?N:i&&typeof i=="object"&&(s in i||y.primaryKey in i)?i:null;if(!B)L("Dataverse returned no row for the source record.");else{const se=String(B[s]??""),Ce=String(B[`${s}@OData.Community.Display.V1.FormattedValue`]??""),we=String(B[`${s}@Microsoft.Dynamics.CRM.lookuplogicalname`]??"");f(se?{id:se,name:Ce||null,entity:we||null}:null)}k(!1)}).catch(i=>{a||(f(null),k(!1),L(i instanceof Error?i.message:String(i)))}),()=>{a=!0}},[h,t.sourceId,t.navProperty,y,r]);const V=a=>o(s=>{const u=new Set(s.dirty);return u.add(a),{...s,dirty:u}}),A=(a,s,u)=>{o(i=>({...i,[a]:s})),u&&V(u)},ye=Ae([["Source record id",t.sourceId],...t.targetIds.map(a=>["Target record id",a])],[["Navigation property",t.navProperty]]),be=y?t.sourceId?t.navProperty?pe&&t.targetIds.length===0?"Pick at least one target record to disassociate.":h&&p===null&&!G&&!U?"Source's lookup is already empty — nothing to disassociate.":t.headers.some(a=>a.enabled&&!a.name)?"Fix empty header name.":ye:"Pick a navigation property.":"Pick a source record.":"Pick a source table first.",ve=async()=>{X(!0);const a=await ct.disassociate(t,oe(t.headers,null));z(a),X(!1),E("results"),me(s=>[{id:`r-${Date.now()}`,snapshot:x,modeId:"disassociate",url:T.relativeUrl,method:I,ts:Date.now(),status:a.status,ms:a.ms,rowCount:O(a,v.length)??0,summary:`${O(a,v.length)??0} of ${v.length} unlinked`},...s].slice(0,8)),o(s=>({...s,dirty:new Set}))},x=n.useMemo(()=>Be(t),[t]);He("disassociate",x,R,$);const fe=n.useMemo(()=>W(x),[x]),Y=$===null?!0:fe!==$,xe=a=>{M(a.id),F(W(a.state))},ee=a=>{if(a.modeId!=="disassociate")return;const s=a.state;if(j.length>0&&!j.some(u=>u.logicalName===s.table)){rt(`Can't load "${a.name}": entity \`${s.table}\` isn't available in this environment. The solution may have been removed or you may be connected to a different org.`);return}o(re(s)),M(a.id),F(W(s)),z(null),q(""),c("source")},Se=a=>{const s=ut(a,"disassociate");if(!s)return;const u=R,i=$;ee(s),M(u),F(i)},te=ne(xe),ae=ne(ee);ze(n.useMemo(()=>t.table?{state:x,modeId:"disassociate",dirty:Y,lastSavedId:R,onSaved:te,onLoadSaved:ae}:null,[x,Y,R,t.table,te,ae]));const je=[{id:"source",label:"Target",meta:y?.displayName??"Pick a table",items:[{id:"source",icon:Ue,iconFilled:qe,label:t.sourceId?Z||`${y?.displayName??""} (selected)`:"Pick a record",badge:r?I:null,badgeAppearance:"tint",badgeColor:"brand",dirty:t.dirty.has("source")}]},{id:"relationship",label:"Relationship",meta:r?ce(r.cardinality):"pick one",items:[{id:"nav",icon:We,iconFilled:Ve,label:r?r.name:"Navigation property",code:!!r,badge:r?ce(r.cardinality):null,badgeAppearance:"ghost",dirty:t.dirty.has("nav")}]},{id:"target",label:"Related",meta:h?p?`clear: ${p.name??p.id.slice(0,8)}…`:U?"value unknown":"lookup empty":t.targetIds.length?`${t.targetIds.length} target${t.targetIds.length===1?"":"s"}`:"none",items:[{id:"target",icon:Oe,iconFilled:J,label:h?"Target — implicit":ue(!1,t.targetIds.length),badge:h?"∅":t.targetIds.length||null,badgeAppearance:"tint",badgeColor:t.targetIds.length>0?"success":"subtle",dirty:t.dirty.has("target")}]},{id:"headers",label:"Headers",meta:`${t.headers.filter(a=>a.enabled).length} active`,items:[{id:"headers",icon:Ke,iconFilled:_e,label:"HTTP headers",badge:t.headers.filter(a=>a.enabled).length||null,dirty:t.dirty.has("headers")}]}];let P;switch(w){case"source":P=e.jsx(Qe,{table:t.table,onTableChange:a=>{o(s=>({...s,table:a,sourceId:null,navProperty:null,targetIds:[],targetNames:{},dirty:new Set(["source","nav","target"])})),q(""),f(null),z(null),M(void 0),F(null)},recordId:t.sourceId,onRecordChange:(a,s)=>{A("sourceId",a,"source"),q(s??"")},group:"relate",sub:"Pick the source record holding the relationship link to remove."});break;case"nav":P=e.jsx("div",{children:e.jsx(ht,{table:t.table,value:t.navProperty,onChange:a=>{o(s=>({...s,navProperty:a,targetIds:[],targetNames:{}})),V("nav"),V("target")},group:"relate",forOperation:"disassociate",footer:r&&e.jsx(bt,{nav:r})})});break;case"target":P=e.jsx(yt,{state:t,setTargetIds:a=>A("targetIds",a,"target"),targetNames:t.targetNames,setTargetNames:a=>A("targetNames",a),currentLookup:p,currentLookupLoading:G,currentLookupError:U});break;case"headers":P=e.jsx(Je,{policy:"relate",items:t.headers,setItems:a=>A("headers",a,"headers"),group:"relate"});break}const ke=Xe(I,oe(t.headers,null)),Te=v[0],Ie={method:I,built:T,headers:ke,body:Te?.body,entityLogical:T.entityLogical,multiRequests:v.length>1?v.map(a=>({method:a.method,relativeUrl:a.relativeUrl,body:a.body,description:a.targetId?`target ${a.targetId}`:"clear lookup (null)"})):void 0},Pe=h?p?.name?[p.name]:[]:t.targetIds.map(a=>t.targetNames[a]).filter(a=>!!a),Ne=h?p?1:0:t.targetIds.length;return e.jsx(Ze,{sidebar:e.jsx(at,{type:m,urlPreview:T.relativeNoBase,sections:je,activeNode:w,onSelect:a=>{c(a),E("builder")},recents:he,onRecentClick:Se}),urlBar:e.jsx(tt,{method:I,url:T.relativeUrl,executeVerb:m.executeVerb,writeConfirm:{operation:r?`Disassociate (${r.name})`:"Disassociate",table:t.table,scope:{kind:"records",count:Math.max(1,t.targetIds.length)},highImpact:t.targetIds.length>1},disabledReason:be,loading:ge,onExecute:ve}),children:e.jsxs(Ge,{tab:b,onTabChange:E,resultCount:O(D,v.length),children:[b==="builder"&&P,b==="code"&&e.jsx(Ye,{themeMode:l,inputs:Ie}),b==="results"&&e.jsx(et,{result:D,mode:"single",table:t.table,writeContext:{operation:"disassociate",table:t.table,recordId:t.sourceId,recordName:Z||null,navProperty:t.navProperty??void 0,targetCount:Ne,targetNames:Pe,targetNameById:t.targetNames}})]})})}function yt({state:l,setTargetIds:m,targetNames:g,setTargetNames:t,currentLookup:o,currentLookupLoading:S,currentLookupError:j}){const w=H(l.table),c=l.navProperty?w?.navigationProperties.find(D=>D.name===l.navProperty):void 0;if(!c)return e.jsxs("div",{children:[e.jsx(le,{icon:J,title:ue(!1,l.targetIds.length),sub:"Pick a navigation property first.",group:"relate"}),e.jsx(_,{layout:"multiline",intent:"info",style:{maxWidth:720},children:e.jsxs(K,{children:["Switch to the ",e.jsx("strong",{children:"Relationship"})," pane and pick a navigation property."]})})]});const b=H(c.targetEntity);return Q(c)?e.jsxs("div",{children:[e.jsx(le,{icon:J,title:"Target — implicit (single-valued)",sub:e.jsxs(e.Fragment,{children:["Single-valued nav props don't take a target id. The ",e.jsx("code",{children:"PATCH"})," body"," ",e.jsx("code",{children:`{ "${c.name}@odata.bind": null }`})," clears the lookup on the source row."]}),group:"relate"}),e.jsx(_,{layout:"multiline",intent:"warning",icon:e.jsx(nt,{}),style:{maxWidth:880,marginBottom:14},children:e.jsxs(K,{children:[e.jsx(ie,{children:"This clears the lookup."}),e.jsx("code",{children:c.name})," on the source row becomes ",e.jsx("code",{children:"null"}),". The related row is"," ",e.jsx("strong",{children:"not"})," deleted — only the link is removed."]})}),e.jsxs("div",{style:{border:`1px solid ${d.colorNeutralStroke2}`,borderRadius:d.borderRadiusMedium,padding:12,maxWidth:560},children:[e.jsxs(C,{style:{color:d.colorNeutralForeground3,display:"block",marginBottom:8},children:["Current lookup value",S?" (loading…)":""]}),S?e.jsxs("div",{style:{display:"flex",alignItems:"center",gap:8},children:[e.jsx(ot,{size:"tiny"}),e.jsx(C,{children:"Fetching the lookup's current value from Dataverse…"})]}):o?e.jsxs(e.Fragment,{children:[e.jsxs("div",{style:{display:"flex",alignItems:"center",gap:10},children:[e.jsx(lt,{size:28,name:o.name??void 0,color:"colorful"}),e.jsxs("div",{style:{flex:1,minWidth:0},children:[e.jsx("div",{style:{fontSize:12,fontWeight:600},children:o.name??"(name not available)"}),e.jsxs("div",{style:{fontFamily:d.fontFamilyMonospace,fontSize:10,color:d.colorNeutralForeground3},children:["/",(o.entity&&H(o.entity)?.entitySetName)??b?.entitySetName??c.targetEntity,"(",o.id,")"]})]})]}),o.entity&&o.entity!==c.targetEntity&&e.jsxs(C,{style:{display:"block",marginTop:8,color:d.colorNeutralForeground3},children:["The lookup currently references a ",e.jsx("code",{children:o.entity})," row, not"," ",e.jsx("code",{children:c.targetEntity}),"."]})]}):j?e.jsx(_,{layout:"multiline",intent:"warning",children:e.jsxs(K,{children:[e.jsx(ie,{children:"Couldn't read the current value."}),"Execute still sends the ",e.jsx("code",{children:"PATCH"}),"; if the lookup is already empty it changes nothing. ",e.jsx("code",{children:j})]})}):e.jsx(C,{style:{color:d.colorNeutralForeground3,fontStyle:"italic"},children:"Source's lookup is already empty — the PATCH would be a no-op."})]})]}):e.jsx(mt,{table:l.table,navProperty:l.navProperty,targets:l.targetIds,setTargets:m,targetNames:g,setTargetNames:t,group:"relate",resolvedMethod:null,verb:"DELETE",sub:e.jsxs(e.Fragment,{children:["Pick one or more ",e.jsx("code",{children:b?.logicalName})," rows to remove from the collection. Each fires a separate DELETE request per docs — the target rows are ",e.jsx("strong",{children:"not"})," ","deleted, only the links."]})})}function bt({nav:l}){const m=it(),g=Q(l);return e.jsxs("div",{className:dt(m.inlineCard),style:{padding:12},children:[e.jsx("strong",{style:{fontSize:12,display:"block",marginBottom:8},children:"URL shape per cardinality"}),e.jsxs("div",{style:{display:"grid",gridTemplateColumns:"repeat(2, 1fr)",gap:10},children:[e.jsx(de,{label:"Collection-valued (1:N / N:N)",syntax:"DELETE /<set>(<id>)/<nav>(<related-id>)/$ref",note:"One DELETE per target id.",active:!g}),e.jsx(de,{label:"Single-valued (N:1)",syntax:`PATCH /<set>(<id>)
|
|
2
|
+
{ "<nav>@odata.bind": null }`,note:"Clears the lookup — docs-preferred over DELETE/$ref (and the only path PPTB exposes).",active:g})]})]})}function de({label:l,syntax:m,note:g,active:t}){return e.jsxs("div",{style:{padding:10,border:`1px solid ${t?d.colorBrandStroke1:d.colorNeutralStroke2}`,background:t?d.colorBrandBackground2:"transparent",borderRadius:d.borderRadiusMedium,opacity:t?1:.55},children:[e.jsxs("div",{style:{display:"flex",alignItems:"center",gap:6,marginBottom:4},children:[e.jsx("strong",{style:{fontSize:11},children:l}),t&&e.jsx(gt,{appearance:"tint",color:"brand",size:"small",style:{marginLeft:"auto",fontWeight:700},children:"ACTIVE"})]}),e.jsx("code",{style:{fontFamily:d.fontFamilyMonospace,fontSize:11,wordBreak:"break-all",display:"block",whiteSpace:"pre-wrap"},children:m}),e.jsx(C,{style:{display:"block",marginTop:4,color:d.colorNeutralForeground3},children:g})]})}function ce(l){switch(l){case"OneToMany":return"1:N";case"ManyToOne":return"N:1";case"ManyToMany":return"N:N"}}export{St as DisassociateMode};
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
import{b8 as re,A as e,br as je,a2 as w,l as o,a3 as v,ab as se,N as L,O as C,V as z,bq as b,k as Se,b9 as ve,c6 as Q,c7 as Ee,c8 as Ie,u as Ne,f as Pe,n as Te,bc as Le,c9 as Ce,be as Re,p as O,q as X,t as qe,ca as R,cb as Ae,T as Z,v as We,L as Me,z as $e,H as Be,ah as ne,ad as ae,b6 as Fe,I as ee,J as De,K as He,P as Oe,R as ze,U as Ve,S as Ue,cc as _e,Y as Ge,Z as Ke,bn as Ye,b5 as te,Q as Je,b0 as Qe,b1 as Xe,bs as Ze}from"./index-XmEQbXiX.js";function et({rows:i,keyWidth:s,className:c}){const t=re(),n=s!=null?{gridTemplateColumns:`${typeof s=="number"?`${s}px`:s} 1fr`}:void 0;return e.jsx("div",{className:je(t.kvGrid,c),style:n,children:i.map((u,l)=>e.jsx(tt,{k:u.k,v:u.v,mono:u.mono},l))})}function tt({k:i,v:s,mono:c}){const t=re();return e.jsxs(e.Fragment,{children:[e.jsx("span",{className:t.kvKey,children:i}),e.jsx("span",{className:c?t.kvValMono:t.kvVal,children:s==null||s===""?e.jsx("em",{style:{color:w.colorNeutralForeground4},children:"—"}):s})]})}const rt="http://schemas.microsoft.com/winfx/2006/xaml",st=new Set(["InputEntities","CreatedEntities"]);function nt(i){if(!i||typeof DOMParser>"u")return[];let s;try{s=new DOMParser().parseFromString(i,"application/xml")}catch{return[]}if(s.getElementsByTagName("parsererror").length>0)return[];const c=[],t=s.getElementsByTagNameNS(rt,"Property");for(const n of Array.from(t)){const u=n.getAttribute("Name"),l=/^(In|InOut)Argument\((.*)\)$/.exec((n.getAttribute("Type")??"").trim());if(!u||!l||st.has(u))continue;let y=!1,h=null;for(const g of Array.from(n.getElementsByTagName("*"))){const a=g.getAttribute("Value");g.localName==="ArgumentRequiredAttribute"&&(y=a?.toLowerCase()==="true"),g.localName==="ArgumentDescriptionAttribute"&&a&&(h=a)}c.push({name:u,direction:l[1],type:l[2].trim(),required:y,description:h})}return c}function at(i){return i.replace(/\b[a-z]+:/g,"")}function ot({workflowId:i}){const[s,c]=o.useState({status:"loading"});o.useEffect(()=>{if(typeof window>"u"||!window.dataverseAPI?.queryData){c({status:"ready",args:[]});return}let n=!1;return c({status:"loading"}),window.dataverseAPI.queryData(`workflows?$select=xaml&$filter=workflowid eq ${i}`).then(u=>{if(n)return;const l=u?.value?.[0],y=typeof l?.xaml=="string"?l.xaml:null;c({status:"ready",args:nt(y)})}).catch(u=>{n||c({status:"error",message:u instanceof Error?u.message:String(u)})}),()=>{n=!0}},[i]);const t={color:w.colorNeutralForeground3,display:"block",marginTop:10};return s.status==="loading"?e.jsxs(v,{style:{...t,display:"flex",alignItems:"center",gap:6},children:[e.jsx(se,{size:"extra-tiny"})," Reading the workflow's input arguments…"]}):s.status==="error"?e.jsxs(v,{style:t,children:["Couldn't read the workflow definition to check for input arguments: ",s.message]}):s.args.length===0?e.jsxs(v,{style:t,children:["No input arguments declared — ",e.jsx("code",{children:"EntityId"})," is the whole request body."]}):e.jsx(L,{layout:"multiline",intent:"warning",style:{marginTop:12},children:e.jsxs(C,{children:[e.jsxs(z,{children:["This workflow declares ",s.args.length," input argument",s.args.length===1?"":"s"]}),"The Web API ",e.jsx("code",{children:"ExecuteWorkflow"})," action only takes ",e.jsx("code",{children:"EntityId"}),", so these can't be set from here; the workflow runs with their default values.",e.jsx("ul",{style:{margin:"6px 0 0",paddingLeft:18},children:s.args.map(n=>e.jsxs("li",{children:[e.jsx("code",{children:n.name})," ",e.jsx(b,{appearance:"outline",size:"small",children:at(n.type)}),n.direction==="InOut"&&e.jsx(b,{appearance:"tint",size:"small",style:{marginLeft:4},children:"in/out"}),n.required&&e.jsx(b,{appearance:"tint",color:"danger",size:"small",style:{marginLeft:4},children:"required"}),n.description&&e.jsxs("span",{style:{color:w.colorNeutralForeground3},children:[" — ",n.description]})]},n.name))})]})})}const it=()=>({workflowId:null,entityId:null,headers:Je(),dirty:new Set});function ut({themeMode:i}){const s=Se("exec-workflow"),c=ve("exec-workflow",Q,it),[t,n]=o.useState(c.state),[u,l]=o.useState("pick"),[y,h]=o.useState("builder"),[g,a]=o.useState(null),[p,j]=o.useState(!1),[q,A]=o.useState([]),E=o.useMemo(()=>Ee(t),[t]),oe=o.useMemo(()=>Ie(t),[t]),[W,V]=o.useState([]),[ie,M]=o.useState(!1),[le,$]=o.useState(null),[de,ce]=o.useState(0),ue=typeof window<"u"&&!!window.dataverseAPI?.queryData;o.useEffect(()=>{let r=!1;if(typeof window>"u"||!window.dataverseAPI?.queryData){V([]),$("Workflows can only be loaded from a live Dataverse connection (PPTB).");return}return M(!0),$(null),window.dataverseAPI.queryData("workflows?$select=workflowid,name,uniquename,primaryentity,description&$filter=(statecode eq 1 and type eq 1 and ondemand eq true and category eq 0)&$orderby=name asc").then(f=>{if(r)return;const x=f?.value??[];V(x.map(k=>({id:String(k.workflowid??""),name:String(k.name??"(unnamed)"),uniqueName:k.uniquename!=null?String(k.uniquename):null,primaryEntity:String(k.primaryentity??""),description:k.description!=null?String(k.description):null}))),M(!1)}).catch(f=>{r||($(f instanceof Error?f.message:String(f)),M(!1))}),()=>{r=!0}},[de]);const d=t.workflowId?W.find(r=>r.id===t.workflowId):void 0;Ne(d?.primaryEntity??null);const I=d?Pe(d.primaryEntity):void 0,{allEntities:U}=Te(),[N,B]=o.useState(c.lastSavedId),[P,F]=o.useState(c.lastSavedHash),[me,D]=o.useState(""),H=r=>n(m=>{const f=new Set(m.dirty);return f.add(r),{...m,dirty:f}}),_=(r,m,f)=>{n(x=>({...x,[r]:m})),f&&H(f)},fe=Le([["Workflow id",t.workflowId],["Record id",t.entityId]]),ye=d?t.entityId?t.headers.some(r=>r.enabled&&!r.name)?"Fix empty header name.":fe:`Pick a ${d.primaryEntity} record to run the workflow on.`:"Pick a workflow.",he=async()=>{j(!0);const r=await Xe.workflow(t,ee(t.headers,null));a(r),j(!1),h("results"),A(m=>[{id:`r-${Date.now()}`,snapshot:S,modeId:"exec-workflow",url:E.relativeUrl,method:"POST",ts:Date.now(),status:r.status,ms:r.ms,rowCount:r.ok?1:0},...m].slice(0,8)),n(m=>({...m,dirty:new Set}))},S=o.useMemo(()=>Ce(t),[t]);Re("exec-workflow",S,N,P);const pe=o.useMemo(()=>O(S),[S]),G=P===null?!0:pe!==P,we=r=>{B(r.id),F(O(r.state))},K=r=>{if(r.modeId!=="exec-workflow")return;const m=r.state,f=W.find(x=>x.id===m.workflowId);if(f&&U.length>0&&!U.some(x=>x.logicalName===f.primaryEntity)){Qe(`Can't load "${r.name}": workflow's primary entity \`${f.primaryEntity}\` isn't available in this environment.`);return}n(Q(m)),B(r.id),F(O(m)),a(null),D(""),l("pick")},ge=r=>{const m=Ze(r,"exec-workflow");if(!m)return;const f=N,x=P;K(m),B(f),F(x)},Y=X(we),J=X(K);qe(o.useMemo(()=>t.workflowId?{state:S,modeId:"exec-workflow",dirty:G,lastSavedId:N,onSaved:Y,onLoadSaved:J}:null,[S,G,N,t.workflowId,Y,J]));const xe=[{id:"workflow",label:"Target",meta:d?.name??"pick one",items:[{id:"pick",icon:Ae,iconFilled:R,label:d?.name??"Pick on-demand workflow",dirty:t.dirty.has("pick")}]},{id:"target",label:"Bound to",meta:d?`${I?.displayName??d.primaryEntity} record`:"—",items:[{id:"target",icon:We,iconFilled:Z,label:t.entityId?`${I?.displayName??""} (selected)`:"Pick a record",badge:t.entityId?"✓":null,badgeAppearance:"ghost",dirty:t.dirty.has("target")}]},{id:"headers",label:"Headers",meta:`${t.headers.filter(r=>r.enabled).length} active`,items:[{id:"headers",icon:$e,iconFilled:Me,label:"HTTP headers",badge:t.headers.filter(r=>r.enabled).length||null,dirty:t.dirty.has("headers")}]}];let T;switch(u){case"pick":T=e.jsx(lt,{workflows:W,loading:ie,error:le,onRetry:ue?()=>ce(r=>r+1):void 0,workflowId:t.workflowId,setWorkflowId:r=>{n(m=>({...m,workflowId:r,entityId:null})),D(""),H("pick"),H("target")}});break;case"target":T=d?e.jsxs("div",{children:[e.jsx(ne,{icon:Z,title:"Target record",sub:`The ${I?.displayName??d.primaryEntity} record the workflow operates on. Slots into the request body as "EntityId".`,group:"execute"}),e.jsxs("div",{style:{maxWidth:480},children:[e.jsx(ae,{label:`${I?.displayName??d.primaryEntity} record`,children:e.jsx(Fe,{table:d.primaryEntity,selectedId:t.entityId,onPick:r=>{_("entityId",r?.id??null,"target"),D(r?.primary??"")},placeholder:`Search ${I?.displayName??d.primaryEntity} records…`})}),e.jsx(ot,{workflowId:d.id})]})]}):e.jsx(L,{layout:"multiline",intent:"info",children:e.jsx(C,{children:"Pick a workflow first."})});break;case"headers":T=e.jsx(Be,{items:t.headers,setItems:r=>_("headers",r,"headers"),group:"execute",sendsHeaders:!0});break}const ke=ee(t.headers,null),be={method:"POST",built:E,headers:ke,body:oe,entityLogical:E.entityLogical};return e.jsx(De,{sidebar:e.jsx(Ue,{type:s,urlPreview:E.relativeNoBase,sections:xe,activeNode:u,onSelect:r=>{l(r),h("builder")},recents:q,onRecentClick:ge}),urlBar:e.jsx(Ve,{method:"POST",url:E.relativeUrl,executeVerb:s.executeVerb,writeConfirm:d?{operation:`Execute Workflow "${d.name}"`,table:d.primaryEntity||void 0,scope:{kind:"records",count:1},highImpact:!0}:null,executeIcon:R,disabledReason:ye,loading:p,onExecute:he}),children:e.jsxs(He,{tab:y,onTabChange:h,resultCount:g?.ok?1:null,children:[y==="builder"&&T,y==="code"&&e.jsx(Oe,{themeMode:i,inputs:be}),y==="results"&&e.jsx(ze,{result:g,mode:"single",table:d?.primaryEntity??"",writeContext:{operation:"workflow",table:d?.primaryEntity??"",recordId:t.entityId,recordName:me||null,operationName:d?.name??void 0}})]})})}function lt({workflows:i,loading:s,error:c,onRetry:t,workflowId:n,setWorkflowId:u}){const l=n?i.find(a=>a.id===n):void 0,[y,h]=o.useState("");o.useEffect(()=>{h(l?.name??"")},[l?.name]);const g=o.useMemo(()=>{const a=y.trim().toLowerCase();return!a||a===(l?.name??"").toLowerCase()?i:i.filter(p=>p.name.toLowerCase().includes(a)||(p.uniqueName?.toLowerCase().includes(a)??!1)||p.primaryEntity.toLowerCase().includes(a)||(p.description?.toLowerCase().includes(a)??!1))},[i,y,l]);return e.jsxs("div",{children:[e.jsx(ne,{icon:R,title:"On-demand workflow",sub:"Pick an activated workflow (type=Definition, category=Workflow). The workflow's primary entity drives the Target picker.",group:"execute",children:s?e.jsx(b,{appearance:"ghost",icon:e.jsx(se,{size:"extra-tiny"}),children:"loading…"}):c?null:e.jsxs(b,{appearance:"ghost",children:[i.length," workflow",i.length===1?"":"s"]})}),c&&!s&&e.jsxs(L,{intent:"error",layout:"multiline",style:{marginBottom:12,maxWidth:760},children:[e.jsxs(C,{children:[e.jsx(z,{children:"Couldn't load workflows"}),c]}),t&&e.jsx(_e,{containerAction:e.jsx(Ge,{appearance:"primary",size:"small",icon:e.jsx(Ke,{}),onClick:t,children:"Retry"})})]}),e.jsxs("div",{style:{maxWidth:760},children:[e.jsx(ae,{label:"Workflow",children:e.jsxs(Ye,{freeform:!0,clearable:!0,value:y,selectedOptions:n?[n]:[],onChange:a=>{const p=a.target.value;h(p),p===""&&n&&u(null)},onOptionSelect:(a,p)=>{const j=p.optionValue??null;if(u(j),j){const q=i.find(A=>A.id===j);h(q?.name??"")}else h("")},placeholder:s?"Loading workflows…":c?"Workflows didn’t load":i.length===0?"No activated workflows in this environment":"Search workflows…",disabled:s||i.length===0,listbox:{style:{maxHeight:420}},children:[g.length===0&&y.trim()&&e.jsx(te,{value:"__none",text:"",disabled:!0,children:e.jsxs(v,{style:{color:w.colorNeutralForeground3},children:['No workflows match "',y.trim(),'"']})}),g.map(a=>e.jsx(te,{value:a.id,text:a.name,children:e.jsxs("div",{style:{display:"flex",flexDirection:"column"},children:[e.jsx("span",{children:a.name}),e.jsxs(v,{style:{color:w.colorNeutralForeground3},children:["Primary entity:"," ",e.jsx("span",{style:{fontFamily:w.fontFamilyMonospace},children:a.primaryEntity}),a.description?` · ${a.description}`:""]})]})},a.id))]})}),l&&e.jsxs("div",{style:{marginTop:16,padding:12,border:`1px solid ${w.colorNeutralStroke2}`,borderRadius:w.borderRadiusMedium,background:w.colorNeutralBackground1},children:[e.jsxs("div",{style:{display:"flex",alignItems:"center",gap:8,marginBottom:8},children:[e.jsx(R,{style:{color:w.colorBrandForeground1}}),e.jsx("strong",{style:{fontSize:13},children:l.name}),e.jsx(b,{appearance:"ghost",children:l.primaryEntity}),e.jsx("span",{style:{flexGrow:1}}),e.jsx(b,{appearance:"filled",color:"success",style:{fontWeight:700},children:"POST"})]}),e.jsx(v,{style:{color:w.colorNeutralForeground2,display:"block",marginBottom:8},children:l.description}),e.jsx(et,{keyWidth:120,rows:[{k:"Workflow id",v:l.id,mono:!0},{k:"Primary entity",v:l.primaryEntity,mono:!0},{k:"URL shape",v:`POST /workflows(${l.id})/Microsoft.Dynamics.CRM.ExecuteWorkflow`,mono:!0},{k:"Body shape",v:'{ "EntityId": "<target-guid>" }',mono:!0},{k:"Response",v:"204 No Content — workflow runs async"}]}),e.jsx(L,{layout:"multiline",intent:"info",style:{marginTop:12},children:e.jsxs(C,{children:[e.jsx(z,{children:"Workflow runs are asynchronous."}),"The 204 only confirms the request was accepted. Check the ",e.jsx("code",{children:"workflowlogs"})," ","/ ",e.jsx("code",{children:"asyncoperations"})," tables for completion + result."]})})]})]})]})}export{ut as ExecuteWorkflowMode,lt as WorkflowPickerPane};
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
import{k as xe,b9 as ke,cd as Q,l as r,u as Se,ce as je,cf as ve,f as Fe,bc as we,n as Ce,cg as Te,be as Be,p as E,q as X,t as ze,aq as Me,ch as Pe,A as e,ci as ae,cj as Ae,T as Ne,v as Re,ck as Z,cl as ee,aS as H,aT as De,bY as Ie,cm as Ue,L as Le,z as Ee,cn as A,H as He,co as qe,cp as Oe,cq as $e,D as Ge,I as Ve,cr as We,J as _e,K as Ke,P as Ye,R as Je,U as Qe,cs as Xe,ct as Ze,cu as ea,S as aa,Q as la,b0 as sa,N as z,O as M,V as P,ah as q,ad as g,ai as le,aj as b,a2 as o,a3 as u,ak as v,b8 as oa,cv as ta,br as na,b1 as ia,bs as ra}from"./index-XmEQbXiX.js";import{F as da}from"./BinaryColumnPickers-DYpKoRIO.js";const ca=()=>({table:"",recordId:null,fileColumn:"",operation:"upload",uploadMethod:{kind:"chunked-patch",chunkSize:2*1024*1024},downloadMethod:{kind:"single-request"},source:{kind:"file"},fileName:"",fileSize:0,mimeType:"application/octet-stream",bodyBase64:"",bodyUrl:"",headers:la(),dirty:new Set});function ya({themeMode:s}){const n=xe("manage-file"),d=ke("manage-file",Q,ca),[a,i]=r.useState(d.state),{table:f}=Se(a.table||null),[O,N]=r.useState("pipeline"),[F,R]=r.useState("builder"),[$,D]=r.useState(null),[se,G]=r.useState(!1),[oe,te]=r.useState([]),x=r.useMemo(()=>je(a),[a,f]),p=r.useMemo(()=>ve(a),[a,f]),k=Fe(a.table),S=r.useMemo(()=>(k?.columns??[]).find(l=>l.attributeType==="File"&&l.logicalName===a.fileColumn),[k,a.fileColumn]),ne=l=>i(t=>{const h=new Set(t.dirty);return h.add(l),{...t,dirty:h}}),c=(l,t,h)=>{i(L=>({...L,[l]:t})),h&&ne(h)},I=p[0]?.method??"PATCH",ie=we([["Record id",a.recordId]],[["File column",a.fileColumn]]),re=k?a.recordId?a.fileColumn?a.operation==="upload"&&a.source.kind==="file"&&!a.bodyBase64&&a.source.kind==="file"&&!a.fileName?"Choose a file to upload.":a.headers.some(l=>l.enabled&&!l.name)?"Fix empty header name.":ie:"Pick a file column.":"Pick a source record.":"Pick a target table first.",[de,V]=r.useState(""),ce=async()=>{G(!0);const l=await ia.manageFile(a);D(l),G(!1),R("results"),te(t=>[{id:`r-${Date.now()}`,snapshot:y,modeId:"manage-file",url:x.relativeUrl,method:I,ts:Date.now(),status:l.status,ms:l.ms,rowCount:l.ok?1:0},...t].slice(0,8)),i(t=>({...t,dirty:new Set}))},{allEntities:W}=Ce(),[w,C]=r.useState(d.lastSavedId),[T,B]=r.useState(d.lastSavedHash),y=r.useMemo(()=>Te(a),[a]);Be("manage-file",y,w,T);const ue=r.useMemo(()=>E(y),[y]),_=T===null?!0:ue!==T,he=l=>{C(l.id),B(E(l.state))},K=l=>{if(l.modeId!=="manage-file")return;const t=l.state;if(W.length>0&&t.table&&!W.some(h=>h.logicalName===t.table)){sa(`Can't load "${l.name}": entity \`${t.table}\` isn't available in this environment.`);return}i(Q(t)),C(l.id),B(E(t)),D(null),V(""),N("pipeline")},pe=l=>{const t=ra(l,"manage-file");if(!t)return;const h=w,L=T;K(t),C(h),B(L)},Y=X(he),J=X(K);ze(r.useMemo(()=>a.table?{state:y,modeId:"manage-file",dirty:_,lastSavedId:w,onSaved:Y,onLoadSaved:J}:null,[y,_,w,a.table,Y,J]));const me=r.useMemo(()=>Me()?[Pe.warn("binary-host-unsupported","header","File operations run externally",e.jsxs("span",{children:["PPTB's ",e.jsx("code",{children:"dataverseAPI"})," doesn't expose file column endpoints. Build the request here, then copy a snippet from the ",e.jsx("strong",{children:"Code"})," tab (fetch / curl / C# / PowerShell) and run it from there. Execute will return ",e.jsx("code",{children:"501 Not Implemented"}),"."]}),"pipeline","https://learn.microsoft.com/en-us/power-apps/developer/data-platform/file-column-data")]:[],[]),j=a.operation==="upload"?"UPLOAD":a.operation==="download"?"DOWNLOAD":"DELETE",ge=a.operation==="delete"?"danger":"brand",U=a.operation==="upload"?a.uploadMethod.kind:a.operation==="download"?a.downloadMethod.kind:"simple",be=[{id:"operation",label:"Operation",meta:j.toLowerCase(),items:[{id:"operation",icon:Ae,iconFilled:ae,label:j.charAt(0)+j.slice(1).toLowerCase(),badge:j,badgeAppearance:"tint",badgeColor:ge,dirty:a.dirty.has("operation")}]},{id:"target",label:"Target",meta:k?.displayName??"?",items:[{id:"target",icon:Re,iconFilled:Ne,label:a.recordId?`${k?.displayName??""} (selected)`:"Pick a record",badge:a.recordId?"✓":null,badgeAppearance:"ghost",dirty:a.dirty.has("target")},{id:"column",icon:ee,iconFilled:Z,label:a.fileColumn||"Pick a file column",code:!!a.fileColumn,badge:S?A((S.maxSizeInKB??32768)*1024):null,badgeAppearance:"ghost",dirty:a.dirty.has("column")}]},...a.operation!=="delete"?[{id:"method",label:"Method",meta:U,items:[{id:"method",icon:De,iconFilled:H,label:a.operation==="upload"?"Upload method":"Download method",badge:U,badgeAppearance:"ghost",dirty:a.dirty.has("method")}]}]:[],...a.operation==="upload"?[{id:"payload",label:"Payload",meta:a.fileName||"—",items:[{id:"source",icon:ee,iconFilled:Z,label:"Source",badge:a.source.kind,badgeAppearance:"ghost",dirty:a.dirty.has("source")}]}]:[],{id:"pipe",label:"Pipeline",meta:`${p.length} request${p.length===1?"":"s"}`,items:[{id:"pipeline",icon:Ue,iconFilled:Ie,label:"Generated requests",badge:p.length||null,badgeAppearance:"tint",badgeColor:"brand",dirty:a.dirty.has("pipeline")}]},{id:"headers",label:"Headers",meta:`${a.headers.filter(l=>l.enabled).length} active`,items:[{id:"headers",icon:Ee,iconFilled:Le,label:"HTTP headers",badge:a.headers.filter(l=>l.enabled).length||null,dirty:a.dirty.has("headers")}]}];let m;switch(O){case"operation":m=e.jsx(ua,{value:a.operation,onChange:l=>c("operation",l,"operation")});break;case"target":m=e.jsx(Ge,{table:a.table,onTableChange:l=>{i(t=>({...t,table:l,recordId:null,fileColumn:null,dirty:new Set(["target","column"])})),D(null),C(void 0),B(null)},recordId:a.recordId,onRecordChange:(l,t)=>{c("recordId",l,"target"),V(t??"")},group:"binary",sub:"Pick the entity + record that holds the file column."});break;case"column":m=e.jsx(da,{table:a.table,value:a.fileColumn,onChange:l=>c("fileColumn",l,"column")});break;case"method":m=a.operation==="upload"?e.jsx(ha,{value:a.uploadMethod,onChange:l=>c("uploadMethod",l,"method")}):e.jsx(pa,{value:a.downloadMethod,onChange:l=>c("downloadMethod",l,"method")});break;case"source":m=e.jsx($e,{source:a.source,setSource:l=>c("source",l,"source"),fileName:a.fileName,setFileName:l=>c("fileName",l,"source"),fileSize:a.fileSize,setFileSize:l=>c("fileSize",l,"source"),mimeType:a.mimeType,setMimeType:l=>c("mimeType",l,"source"),bodyBase64:a.bodyBase64,setBodyBase64:l=>c("bodyBase64",l,"source"),bodyUrl:a.bodyUrl,setBodyUrl:l=>c("bodyUrl",l,"source"),group:"binary"});break;case"pipeline":m=e.jsxs("div",{style:{display:"flex",flexDirection:"column",gap:14},children:[e.jsx(ma,{state:a,fileCol:S}),e.jsx(qe,{steps:p,title:`${j} pipeline — ${U}`,sub:p.length>1?"Each request fires sequentially.":void 0,sizeAdvisory:a.operation==="upload"?Oe(a.fileSize,S?.maxSizeInKB?S.maxSizeInKB*1024:void 0,"file"):null})]});break;case"headers":m=e.jsx(He,{items:a.headers,setItems:l=>c("headers",l,"headers"),group:"binary"});break}const fe=Ve(a.headers,null),ye={method:I,built:x,...We(p,fe),entityLogical:x.entityLogical};return e.jsx(_e,{sidebar:e.jsx(aa,{type:n,urlPreview:x.relativeNoBase,sections:be,activeNode:O,onSelect:l=>{N(l),R("builder")},recents:oe,onRecentClick:pe}),urlBar:e.jsx(Qe,{method:I,url:x.relativeUrl,executeVerb:a.operation==="upload"?"Upload":a.operation==="download"?"Download":"Delete",executeIcon:a.operation==="upload"?Xe:a.operation==="download"?Ze:ea,disabledReason:re,loading:se,onExecute:ce,advisories:me,onAdvisoryFocus:N}),children:e.jsxs(Ke,{tab:F,onTabChange:R,resultCount:$?.ok?p.length:null,children:[F==="builder"&&m,F==="code"&&e.jsx(Ye,{themeMode:s,inputs:ye}),F==="results"&&e.jsx(Je,{result:$,mode:"single",table:a.table,writeContext:{operation:"manage-file",table:a.table,recordId:a.recordId,recordName:de||null,fileOperation:a.operation,columnName:a.fileColumn??void 0,fileName:a.fileName||void 0}})]})})}function ua({value:s,onChange:n}){const d=oa(),a=[{id:"upload",label:"Upload",sub:"PATCH or message-based upload pipeline.",tone:"brand"},{id:"download",label:"Download",sub:"GET /$value, ranged GET, message pipeline, or SAS URL.",tone:"brand"},{id:"delete",label:"Delete",sub:"DELETE /<set>(<id>)/<col> · clears the column value.",tone:"danger"}];return e.jsxs("div",{children:[e.jsx(q,{icon:ae,title:"Operation",sub:"What to do with the file column — drives the URL bar method + pipeline shape.",group:"binary"}),e.jsx("div",{style:{display:"grid",gridTemplateColumns:"repeat(3, 1fr)",gap:12,maxWidth:960},children:a.map(i=>{const f=s===i.id;return e.jsxs("button",{type:"button",onClick:()=>n(i.id),className:na(d.inlineCard),style:{textAlign:"left",padding:14,cursor:"pointer",background:f?i.tone==="danger"?o.colorPaletteRedBackground2:o.colorBrandBackground2:o.colorNeutralBackground1,border:`1px solid ${f?i.tone==="danger"?o.colorPaletteRedBorderActive:o.colorBrandStroke1:o.colorNeutralStroke2}`,borderRadius:o.borderRadiusMedium},children:[e.jsxs("div",{style:{display:"flex",alignItems:"center",gap:8},children:[e.jsx("strong",{style:{fontSize:13},children:i.label}),f&&e.jsx(ta,{style:{marginLeft:"auto",color:i.tone==="danger"?o.colorPaletteRedForeground1:o.colorBrandForeground1},"aria-label":"Selected"})]}),e.jsx(u,{style:{color:o.colorNeutralForeground2,lineHeight:1.4,marginTop:6,display:"block"},children:i.sub})]},i.id)})})]})}function ha({value:s,onChange:n}){return e.jsxs("div",{children:[e.jsx(q,{icon:H,title:"Upload method",sub:"Per file-column-data — three supported approaches.",group:"binary"}),e.jsxs("div",{style:{maxWidth:760,display:"flex",flexDirection:"column",gap:14},children:[e.jsx(g,{label:"Approach",children:e.jsxs(le,{value:s.kind,onChange:(d,a)=>{switch(a.value){case"single-request":n({kind:"single-request"});break;case"chunked-patch":n({kind:"chunked-patch",chunkSize:s.kind==="chunked-patch"?s.chunkSize:2*1024*1024});break;case"dataverse-messages":n({kind:"dataverse-messages",blockSize:s.kind==="dataverse-messages"?s.blockSize:4*1024*1024});break}},children:[e.jsx(b,{value:"single-request",label:e.jsxs("span",{children:[e.jsx("strong",{children:"Single-request PATCH"})," ",e.jsx("code",{style:{fontFamily:o.fontFamilyMonospace,fontSize:11},children:"PATCH /(set)(id)/col"}),e.jsx(u,{style:{display:"block",color:o.colorNeutralForeground3,marginTop:2},children:"Fastest for files up to ~128 MB. Body = raw bytes; x-ms-file-name header. No init/commit ceremony."})]})}),e.jsx(b,{value:"chunked-patch",label:e.jsxs("span",{children:[e.jsx("strong",{children:"Chunked PATCH"})," ",e.jsx("code",{style:{fontFamily:o.fontFamilyMonospace,fontSize:11},children:"x-ms-transfer-mode: chunked"}),e.jsx(u,{style:{display:"block",color:o.colorNeutralForeground3,marginTop:2},children:"Init PATCH returns Location + x-ms-chunk-size. Each chunk = PATCH with Content-Range. Server commits on final chunk."})]})}),e.jsx(b,{value:"dataverse-messages",label:e.jsxs("span",{children:[e.jsx("strong",{children:"Dataverse messages"})," ",e.jsx("code",{style:{fontFamily:o.fontFamilyMonospace,fontSize:11},children:"InitializeFileBlocksUpload / UploadBlock / CommitFileBlocksUpload"}),e.jsx(u,{style:{display:"block",color:o.colorNeutralForeground3,marginTop:2},children:"Three OData actions. Up to 10 GB. Returns FileId on commit. Use for files > 128 MB or when you need parallel block uploads."})]})})]})}),s.kind==="chunked-patch"&&e.jsxs(g,{label:"Chunk size (bytes)",hint:"Defaults to 2 MB. Server may suggest a different size via x-ms-chunk-size on init.",children:[e.jsx(v,{value:s.chunkSize,min:64*1024,max:64*1024*1024,step:1024*1024,onChange:(d,a)=>n({kind:"chunked-patch",chunkSize:Number(a.value??a.displayValue??s.chunkSize)})}),e.jsxs(u,{style:{marginTop:4,display:"block",color:o.colorNeutralForeground3},children:["≈ ",A(s.chunkSize)," per chunk."]})]}),s.kind==="dataverse-messages"&&e.jsxs(g,{label:"Block size (bytes)",hint:"Default = 4 MB. The docs cap each UploadBlock at 4 MB; smaller is fine.",children:[e.jsx(v,{value:s.blockSize,min:64*1024,max:4*1024*1024,step:1024*1024,onChange:(d,a)=>n({kind:"dataverse-messages",blockSize:Number(a.value??a.displayValue??s.blockSize)})}),e.jsxs(u,{style:{marginTop:4,display:"block",color:o.colorNeutralForeground3},children:["≈ ",A(s.blockSize)," per block."]})]})]})]})}function pa({value:s,onChange:n}){return e.jsxs("div",{children:[e.jsx(q,{icon:H,title:"Download method",sub:"Per file-column-data + getfilesasurl — four supported approaches.",group:"binary"}),e.jsxs("div",{style:{maxWidth:760,display:"flex",flexDirection:"column",gap:14},children:[e.jsx(g,{label:"Approach",children:e.jsxs(le,{value:s.kind,onChange:(d,a)=>{switch(a.value){case"single-request":n({kind:"single-request"});break;case"ranged":n({kind:"ranged",rangeStart:0,rangeEnd:4*1024*1024-1});break;case"dataverse-messages":n({kind:"dataverse-messages",blockSize:4*1024*1024});break;case"sas-url":n({kind:"sas-url"});break}},children:[e.jsx(b,{value:"single-request",label:e.jsxs("span",{children:[e.jsx("strong",{children:"GET /$value"}),e.jsx(u,{style:{display:"block",color:o.colorNeutralForeground3,marginTop:2},children:"Stream the entire file in one request. Returns raw bytes. Easy but not great for huge files."})]})}),e.jsx(b,{value:"ranged",label:e.jsxs("span",{children:[e.jsx("strong",{children:"Ranged GET"})," ",e.jsx("code",{style:{fontFamily:o.fontFamilyMonospace,fontSize:11},children:"Range: bytes=A-B"}),e.jsx(u,{style:{display:"block",color:o.colorNeutralForeground3,marginTop:2},children:"Partial content — server returns 206. Use for resume / parallel download."})]})}),e.jsx(b,{value:"dataverse-messages",label:e.jsxs("span",{children:[e.jsx("strong",{children:"Dataverse messages"})," ",e.jsx("code",{style:{fontFamily:o.fontFamilyMonospace,fontSize:11},children:"InitializeFileBlocksDownload + DownloadBlock"}),e.jsx(u,{style:{display:"block",color:o.colorNeutralForeground3,marginTop:2},children:"Block-by-block download. Returns FileName + FileSizeInBytes + FileContinuationToken from init."})]})}),e.jsx(b,{value:"sas-url",label:e.jsxs("span",{children:[e.jsx("strong",{children:"GetFileSasUrl"})," ",e.jsx("code",{style:{fontFamily:o.fontFamilyMonospace,fontSize:11},children:"GET /GetFileSasUrl(…)"}),e.jsx(u,{style:{display:"block",color:o.colorNeutralForeground3,marginTop:2},children:"Returns a 1-hour SAS URL that anyone can use to download directly from Azure Storage. Skips Web API roundtrip on the actual download."})]})})]})}),s.kind==="ranged"&&e.jsxs("div",{style:{display:"flex",gap:10,maxWidth:480},children:[e.jsx(g,{label:"Range start (bytes)",children:e.jsx(v,{value:s.rangeStart,min:0,onChange:(d,a)=>n({kind:"ranged",rangeStart:Number(a.value??a.displayValue??0),rangeEnd:s.rangeEnd})})}),e.jsx(g,{label:"Range end (bytes)",children:e.jsx(v,{value:s.rangeEnd,min:0,onChange:(d,a)=>n({kind:"ranged",rangeStart:s.rangeStart,rangeEnd:Number(a.value??a.displayValue??0)})})})]}),s.kind==="dataverse-messages"&&e.jsx(g,{label:"Block size (bytes)",children:e.jsx(v,{value:s.blockSize,min:64*1024,max:4*1024*1024,step:1024*1024,onChange:(d,a)=>n({kind:"dataverse-messages",blockSize:Number(a.value??a.displayValue??s.blockSize)})})}),s.kind==="sas-url"&&e.jsx(z,{layout:"multiline",intent:"info",children:e.jsxs(M,{children:[e.jsx(P,{children:"SAS URL caveats"}),e.jsxs("ul",{style:{margin:"4px 0 0",paddingLeft:18,lineHeight:1.6},children:[e.jsx("li",{children:"Only works for image columns that support full-size images."}),e.jsx("li",{children:"SAS URL valid for 1 hour from generation."}),e.jsx("li",{children:"Does NOT work for environments using BYOK encryption — migrate to CMK first."}),e.jsx("li",{children:"Caller must have access to the record; the resulting URL grants anonymous access for 1 hour."})]})]})})]})]})}function ma({state:s,fileCol:n}){const d=(n?.maxSizeInKB??32768)*1024;if(s.operation==="upload"){const a=s.fileSize>4194304,i=s.fileSize>128*1024*1024;return e.jsx(z,{layout:"multiline",intent:i?"warning":"info",children:e.jsxs(M,{children:[e.jsx(P,{children:"Upload"}),i?e.jsxs(e.Fragment,{children:["File is over ",e.jsx("strong",{children:"128 MB"})," — single-request PATCH won't work. Use the Dataverse messages path which supports up to 10 GB."]}):a?e.jsxs(e.Fragment,{children:["File is over ",e.jsx("strong",{children:"4 MB"})," — chunked PATCH (or Dataverse messages) is recommended; single-request still works up to 128 MB."]}):e.jsxs(e.Fragment,{children:["Small enough for single-request PATCH. Column max: ",A(d),"."]})]})})}return s.operation==="download"?e.jsx(z,{layout:"multiline",intent:"info",children:e.jsxs(M,{children:[e.jsx(P,{children:"Download"}),"Retrieving a file column returns the ",e.jsx("strong",{children:"file id"})," (not bytes) — use the operations below to fetch actual content. GET /$value is the simplest; SAS URL skips the Web API roundtrip when an anonymous browser-side download is fine."]})}):e.jsx(z,{layout:"multiline",intent:"warning",children:e.jsxs(M,{children:[e.jsx(P,{children:"Delete"}),"Clears the file column value + the ",e.jsx("code",{children:"_name"})," companion. The underlying file is removed by Dataverse. Alternative equivalent paths: PATCH the column to null, or call the"," ",e.jsx("code",{children:"DeleteFile"})," action with the column's current FileId."]})})}export{ya as ManageFileMode};
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
import{k as ze,b9 as ke,cw as X,l as t,u as Be,cx as Ne,cy as Pe,f as Ce,bc as Re,n as Me,cz as Le,be as Ue,p as H,q as Z,t as Ae,aq as De,ch as Ee,A as e,ci as ie,cj as He,T as $e,v as Oe,cA as q,cB as I,aS as ne,aT as qe,bY as We,cm as _e,L as Ke,z as Ve,H as Ge,co as ee,cp as ae,cq as re,D as Ye,I as Je,cr as Qe,J as Xe,K as Ze,P as ea,R as aa,U as oa,cs as la,ct as ia,cu as na,S as ra,Q as ta,b0 as sa,N as C,O as R,V as $,b8 as te,a2 as i,bq as O,a3 as T,br as se,ah as de,ad as da,ai as ca,aj as oe,b1 as ua,bs as ma}from"./index-XmEQbXiX.js";import{I as pa}from"./BinaryColumnPickers-DYpKoRIO.js";const ga=5*1024*1024;function le(l){if(!l)return 0;const n=l.endsWith("==")?2:l.endsWith("=")?1:0;return Math.max(0,Math.floor(l.length*3/4)-n)}const ba=()=>({table:"",recordId:null,imageColumn:"",operation:"upload",downloadSize:"thumbnail",source:{kind:"file"},fileName:"",fileSize:0,bodyBase64:"",bodyUrl:"",mimeType:"image/png",headers:ta(),dirty:new Set});function wa({themeMode:l}){const n=ze("manage-image"),u=ke("manage-image",X,ba),[a,s]=t.useState(u.state),[b,M]=t.useState(null),m=t.useRef(null),j=t.useCallback(o=>{m.current&&URL.revokeObjectURL(m.current),m.current=o&&o.type.startsWith("image/")&&o.size<=ga?URL.createObjectURL(o):null,M(m.current&&o?{url:m.current,name:o.name}:null)},[]),L=b&&b.name===a.fileName?b.url:null;t.useEffect(()=>()=>{m.current&&URL.revokeObjectURL(m.current)},[]);const{table:z}=Be(a.table||null),[h,v]=t.useState("preview"),[f,U]=t.useState("builder"),[W,A]=t.useState(null),[ce,_]=t.useState(!1),[ue,me]=t.useState([]),w=t.useMemo(()=>Ne(a),[a,z]),y=t.useMemo(()=>Pe(a),[a,z]),F=Ce(a.table),c=t.useMemo(()=>(F?.columns??[]).find(o=>o.attributeType==="Image"&&o.logicalName===a.imageColumn),[F,a.imageColumn]),pe=o=>s(r=>{const g=new Set(r.dirty);return g.add(o),{...r,dirty:g}}),d=(o,r,g)=>{s(E=>({...E,[o]:r})),g&&pe(g)},D=y[0]?.method??"PATCH",ge=Re([["Record id",a.recordId]],[["Image column",a.imageColumn]]),be=F?a.recordId?a.imageColumn?a.operation==="upload"&&a.source.kind==="file"&&!a.fileName?"Pick an image file.":a.operation==="download"&&a.downloadSize==="full"&&!c?.canStoreFullImage?`${a.imageColumn} doesn't store full-size images (canStoreFullImage = false).`:a.headers.some(o=>o.enabled&&!o.name)?"Fix empty header name.":ge:"Pick an image column.":"Pick a source record.":"Pick a target table first.",[he,K]=t.useState(""),ye=async()=>{_(!0);const o=await ua.manageImage(a);A(o),_(!1),U("results"),me(r=>[{id:`r-${Date.now()}`,snapshot:x,modeId:"manage-image",url:w.relativeUrl,method:D,ts:Date.now(),status:o.status,ms:o.ms,rowCount:o.ok?1:0},...r].slice(0,8)),s(r=>({...r,dirty:new Set}))},{allEntities:V}=Me(),[k,B]=t.useState(u.lastSavedId),[N,P]=t.useState(u.lastSavedHash),x=t.useMemo(()=>Le(a),[a]);Ue("manage-image",x,k,N);const fe=t.useMemo(()=>H(x),[x]),G=N===null?!0:fe!==N,xe=o=>{B(o.id),P(H(o.state))},Y=o=>{if(o.modeId!=="manage-image")return;const r=o.state;if(V.length>0&&r.table&&!V.some(g=>g.logicalName===r.table)){sa(`Can't load "${o.name}": entity \`${r.table}\` isn't available in this environment.`);return}s(X(r)),j(null),B(o.id),P(H(r)),A(null),K(""),v("preview")},Se=o=>{const r=ma(o,"manage-image");if(!r)return;const g=k,E=N;Y(r),B(g),P(E)},J=Z(xe),Q=Z(Y);Ae(t.useMemo(()=>a.table?{state:x,modeId:"manage-image",dirty:G,lastSavedId:k,onSaved:J,onLoadSaved:Q}:null,[x,G,k,a.table,J,Q]));const je=t.useMemo(()=>De()?[Ee.warn("binary-host-unsupported","header","Image operations run externally",e.jsxs("span",{children:["PPTB's ",e.jsx("code",{children:"dataverseAPI"})," doesn't expose image column endpoints. Build the request here, then copy a snippet from the ",e.jsx("strong",{children:"Code"})," tab (fetch / curl / C# / PowerShell) and run it from there. Execute will return ",e.jsx("code",{children:"501 Not Implemented"}),"."]}),"preview","https://learn.microsoft.com/en-us/power-apps/developer/data-platform/image-column-data")]:[],[]),S=a.operation==="upload"?"UPLOAD":a.operation==="download"?"DOWNLOAD":"DELETE",ve=a.operation==="delete"?"danger":"brand",we="?",Fe=[{id:"operation",label:"Operation",meta:S.toLowerCase(),items:[{id:"operation",icon:He,iconFilled:ie,label:S.charAt(0)+S.slice(1).toLowerCase(),badge:S,badgeAppearance:"tint",badgeColor:ve,dirty:a.dirty.has("operation")}]},{id:"target",label:"Target",meta:F?.displayName??"?",items:[{id:"target",icon:Oe,iconFilled:$e,label:a.recordId?`${F?.displayName??""} (selected)`:"Pick a record",badge:a.recordId?"✓":null,badgeAppearance:"ghost",dirty:a.dirty.has("target")},{id:"column",icon:I,iconFilled:q,label:a.imageColumn||"Pick an image column",code:!!a.imageColumn,badge:c?.isPrimaryImage?"primary":c?.canStoreFullImage?"full":"thumb",badgeAppearance:"tint",badgeColor:c?.canStoreFullImage?"success":"brand",dirty:a.dirty.has("column")}]},...c?[{id:"deriv",label:"Derivatives",meta:"3 companion columns",items:[{id:"d1",icon:I,label:`${c.logicalName}id`,code:!0,badge:"guid",badgeAppearance:"ghost"},{id:"d2",icon:I,label:`${c.logicalName}_Timestamp`,code:!0,badge:"bigint",badgeAppearance:"ghost"},{id:"d3",icon:I,label:`${c.logicalName}_URL`,code:!0,badge:"url",badgeAppearance:"ghost"}]}]:[],...a.operation==="upload"?[{id:"payload",label:"Payload",meta:a.fileName||"—",items:[{id:"source",icon:I,iconFilled:q,label:"Source",badge:a.source.kind,badgeAppearance:"ghost",dirty:a.dirty.has("source")}]}]:[],...a.operation==="download"?[{id:"options",label:"Options",meta:a.downloadSize,items:[{id:"options",icon:qe,iconFilled:ne,label:"Download size",badge:a.downloadSize,badgeAppearance:"tint",badgeColor:"brand",dirty:a.dirty.has("options")}]}]:[],{id:"pipe",label:"Pipeline",meta:`${y.length} request${y.length===1?"":"s"}`,items:[{id:"pipeline",icon:_e,iconFilled:We,label:"Generated requests",badge:y.length||null,badgeAppearance:"tint",badgeColor:"brand",dirty:a.dirty.has("pipeline")}]},{id:"headers",label:"Headers",meta:`${a.headers.filter(o=>o.enabled).length} active`,items:[{id:"headers",icon:Ve,iconFilled:Ke,label:"HTTP headers",badge:a.headers.filter(o=>o.enabled).length||null,dirty:a.dirty.has("headers")}]}];let p;switch(h){case"operation":p=e.jsx(ya,{value:a.operation,onChange:o=>d("operation",o,"operation")});break;case"target":p=e.jsx(Ye,{table:a.table,onTableChange:o=>{s(r=>({...r,table:o,recordId:null,imageColumn:null,dirty:new Set(["target","column"])})),A(null),B(void 0),P(null)},recordId:a.recordId,onRecordChange:(o,r)=>{d("recordId",o,"target"),K(r??"")},group:"binary",sub:"Pick the entity + record that holds the image column."});break;case"column":p=e.jsx(pa,{table:a.table,value:a.imageColumn,onChange:o=>d("imageColumn",o,"column")});break;case"source":p=e.jsx(re,{source:a.source,setSource:o=>d("source",o,"source"),fileName:a.fileName,setFileName:o=>d("fileName",o,"source"),fileSize:a.fileSize??0,setFileSize:o=>d("fileSize",o,"source"),mimeType:a.mimeType,setMimeType:o=>d("mimeType",o,"source"),bodyBase64:a.bodyBase64,setBodyBase64:o=>d("bodyBase64",o,"source"),bodyUrl:a.bodyUrl,setBodyUrl:o=>d("bodyUrl",o,"source"),accept:"image/png,image/jpeg,image/gif,image/bmp,image/tiff",group:"binary",onFile:j});break;case"options":p=e.jsx(fa,{downloadSize:a.downloadSize,setDownloadSize:o=>d("downloadSize",o,"options"),canStoreFullImage:c?.canStoreFullImage??!1});break;case"preview":p=e.jsxs("div",{style:{display:"flex",flexDirection:"column",gap:14},children:[e.jsx(xa,{state:a,imageCol:c}),e.jsx(ha,{state:a,imageCol:c,initials:we,setSource:o=>d("source",o,"source"),setBodyBase64:o=>d("bodyBase64",o,"source"),setFileName:o=>d("fileName",o,"source"),setFileSize:o=>d("fileSize",o,"source"),setMimeType:o=>d("mimeType",o,"source"),previewUrl:L,onFile:j}),e.jsx(ee,{steps:y,title:`${S} pipeline`,sizeAdvisory:a.operation==="upload"?ae(a.fileSize||le(a.bodyBase64),c?.maxSizeInKB?c.maxSizeInKB*1024:void 0,"image"):null})]});break;case"pipeline":p=e.jsx(ee,{steps:y,title:`${S} pipeline`,sizeAdvisory:a.operation==="upload"?ae(a.fileSize||le(a.bodyBase64),c?.maxSizeInKB?c.maxSizeInKB*1024:void 0,"image"):null});break;case"headers":p=e.jsx(Ge,{items:a.headers,setItems:o=>d("headers",o,"headers"),group:"binary"});break}const Ie=Je(a.headers,null),Te={method:D,built:w,...Qe(y,Ie),entityLogical:w.entityLogical};return e.jsx(Xe,{sidebar:e.jsx(ra,{type:n,urlPreview:w.relativeNoBase,sections:Fe,activeNode:h,onSelect:o=>{v(o),U("builder")},recents:ue,onRecentClick:Se}),urlBar:e.jsx(oa,{method:D,url:w.relativeUrl,executeVerb:a.operation==="upload"?"Upload":a.operation==="download"?"Download":"Delete",executeIcon:a.operation==="upload"?la:a.operation==="download"?ia:na,disabledReason:be,loading:ce,onExecute:ye,advisories:je,onAdvisoryFocus:v}),children:e.jsxs(Ze,{tab:f,onTabChange:U,resultCount:W?.ok?1:null,children:[f==="builder"&&p,f==="code"&&e.jsx(ea,{themeMode:l,inputs:Te}),f==="results"&&e.jsx(aa,{result:W,mode:"single",table:a.table,writeContext:{operation:"manage-image",table:a.table,recordId:a.recordId,recordName:he||null,fileOperation:a.operation,columnName:a.imageColumn??void 0,fileName:a.fileName||void 0}})]})})}function ha({state:l,imageCol:n,initials:u,setSource:a,setBodyBase64:s,setFileName:b,setFileSize:M,setMimeType:m,previewUrl:j,onFile:L}){const z=te(),h=l.source.kind==="file"?j:l.source.kind==="base64"&&l.bodyBase64?`data:${l.mimeType};base64,${l.bodyBase64}`:null,v=n?.isPrimaryImage&&!n?.canStoreFullImage;return e.jsxs("div",{className:se(z.inlineCard),style:{padding:14,maxWidth:880},children:[e.jsxs("div",{style:{display:"flex",alignItems:"center",gap:8,marginBottom:12},children:[e.jsx(q,{style:{color:i.colorBrandForeground1}}),e.jsx("strong",{style:{fontSize:13},children:"Preview · Source"}),e.jsx(O,{appearance:"tint",color:"brand",children:n?.isPrimaryImage?"primary image":"custom image column"}),v&&e.jsx(O,{appearance:"ghost",children:"144×144 only"}),n?.canStoreFullImage&&e.jsx(O,{appearance:"tint",color:"success",children:"full-size enabled"})]}),e.jsxs("div",{style:{display:"flex",gap:20,alignItems:"flex-start"},children:[e.jsxs("div",{children:[e.jsxs(T,{style:{color:i.colorNeutralForeground3,display:"block",marginBottom:4},children:[l.operation==="upload"?"Preview":l.downloadSize==="full"?"Full-size":"Thumbnail"," ","· 144×144"]}),e.jsx("div",{style:{width:144,height:144,background:h?`url("${h}") center/cover`:i.colorNeutralBackground3,borderRadius:i.borderRadiusMedium,display:"flex",alignItems:"center",justifyContent:"center",color:h?"#fff":i.colorNeutralForeground3,fontWeight:700,fontSize:40,border:`1px solid ${i.colorNeutralStroke2}`},children:!h&&u}),(h||l.source.kind==="file"&&l.fileName)&&e.jsxs(T,{style:{color:i.colorNeutralForeground3,display:"block",marginTop:4},children:[l.fileName," · ",l.mimeType]})]}),l.operation==="upload"&&e.jsx("div",{style:{flex:1},children:e.jsx(re,{source:l.source,setSource:a,fileName:l.fileName,setFileName:b,fileSize:l.fileSize??0,setFileSize:M,mimeType:l.mimeType,setMimeType:f=>m(f),bodyBase64:l.bodyBase64,setBodyBase64:s,bodyUrl:l.bodyUrl,setBodyUrl:()=>{},accept:"image/png,image/jpeg,image/gif,image/bmp,image/tiff",group:"binary",onFile:L})}),l.operation!=="upload"&&e.jsxs("div",{style:{flex:1,fontSize:11,color:i.colorNeutralForeground3,lineHeight:1.6},children:[l.operation==="download"&&e.jsxs(e.Fragment,{children:[e.jsx("strong",{style:{color:i.colorNeutralForeground2},children:"Download:"})," server returns the"," ",l.downloadSize==="full"?"original full-size":"auto-cropped 144×144 thumbnail"," ","as raw bytes. The Content-Type matches the stored image's MIME type (one of image/png · image/jpeg · image/gif · image/bmp · image/tiff)."]}),l.operation==="delete"&&e.jsxs(e.Fragment,{children:[e.jsx("strong",{style:{color:i.colorNeutralForeground2},children:"Delete:"})," clears the image data + companion columns (",e.jsxs("code",{style:{fontFamily:i.fontFamilyMonospace},children:[n?.logicalName,"id"]}),", ",e.jsx("code",{style:{fontFamily:i.fontFamilyMonospace},children:"_Timestamp"}),","," ",e.jsx("code",{style:{fontFamily:i.fontFamilyMonospace},children:"_URL"}),"). Equivalent forms: PATCH set null, PUT /col with body ",e.jsx("code",{children:'{"value":null}'}),", or DELETE /col (shown)."]})]})]})]})}function ya({value:l,onChange:n}){const u=te(),a=[{id:"upload",label:"Upload",sub:"PATCH /<set>(<id>) with body {col: <base64>}.",tone:"brand"},{id:"download",label:"Download",sub:"GET /<set>(<id>)/<col>/$value (?size=full for full).",tone:"brand"},{id:"delete",label:"Delete",sub:"DELETE / PATCH null / PUT /col body=null — three equivalents.",tone:"danger"}];return e.jsxs("div",{children:[e.jsx(de,{icon:ie,title:"Operation",group:"binary"}),e.jsx("div",{style:{display:"grid",gridTemplateColumns:"repeat(3, 1fr)",gap:12,maxWidth:960},children:a.map(s=>{const b=l===s.id;return e.jsxs("button",{type:"button",onClick:()=>n(s.id),className:se(u.inlineCard),style:{textAlign:"left",padding:14,cursor:"pointer",background:b?s.tone==="danger"?i.colorPaletteRedBackground2:i.colorBrandBackground2:i.colorNeutralBackground1,border:`1px solid ${b?s.tone==="danger"?i.colorPaletteRedBorderActive:i.colorBrandStroke1:i.colorNeutralStroke2}`,borderRadius:i.borderRadiusMedium},children:[e.jsx("strong",{style:{fontSize:13,display:"block"},children:s.label}),e.jsx(T,{style:{color:i.colorNeutralForeground2,lineHeight:1.4,marginTop:6,display:"block"},children:s.sub})]},s.id)})})]})}function fa({downloadSize:l,setDownloadSize:n,canStoreFullImage:u}){return e.jsxs("div",{children:[e.jsx(de,{icon:ne,title:"Download options",sub:"Image columns can store both thumbnail + full-size when CanStoreFullImage is true.",group:"binary"}),e.jsx("div",{style:{maxWidth:720},children:e.jsx(da,{label:"Size",children:e.jsxs(ca,{value:l,onChange:(a,s)=>n(s.value),children:[e.jsx(oe,{value:"thumbnail",label:e.jsxs("span",{children:[e.jsx("strong",{children:"Thumbnail (144×144)"}),e.jsx(T,{style:{display:"block",color:i.colorNeutralForeground3,marginTop:2},children:"Default for all image columns. Center-cropped square."})]})}),e.jsx(oe,{value:"full",disabled:!u,label:e.jsxs("span",{children:[e.jsx("strong",{children:"Full-size"})," ",e.jsx("code",{style:{fontFamily:i.fontFamilyMonospace,fontSize:11},children:"?size=full"}),e.jsxs(T,{style:{display:"block",color:i.colorNeutralForeground3,marginTop:2},children:["Only available when the column has CanStoreFullImage = true. Server returns 204 if not configured.",!u&&e.jsxs(e.Fragment,{children:[" ","·"," ",e.jsx("span",{style:{color:i.colorPaletteRedForeground1},children:"this column doesn't support full-size"})]})]})]})})]})})})]})}function xa({state:l,imageCol:n}){return n?l.operation==="upload"?e.jsx(C,{layout:"multiline",intent:"info",children:e.jsxs(R,{children:[e.jsx($,{children:n.isPrimaryImage?"Primary image — thumbnail only":"Custom image column"}),n.isPrimaryImage?e.jsxs(e.Fragment,{children:[e.jsx("code",{children:n.logicalName})," is the table's primary image (auto-cropped 144×144). Full-size data is discarded. To store full-resolution images, create a custom image column with ",e.jsx("code",{children:"CanStoreFullImage = true"}),"."]}):n.canStoreFullImage?e.jsxs(e.Fragment,{children:[e.jsx("code",{children:n.logicalName})," supports full-size (max"," ",((n.maxSizeInKB??10240)/1024).toFixed(0)," MB). Upload via PATCH; for files > 4 MB use the file-column chunked upload path on the underlying file storage."]}):e.jsxs(e.Fragment,{children:[e.jsx("code",{children:n.logicalName})," stores thumbnail only (CanStoreFullImage = false). Full-size won't be retained."]})]})}):l.operation==="download"?e.jsx(C,{layout:"multiline",intent:"info",children:e.jsxs(R,{children:[e.jsx($,{children:"Download"}),"GET /$value returns the"," ",l.downloadSize==="full"?"full-size original":"144×144 thumbnail",". Image companion columns (",e.jsxs("code",{children:[n.logicalName,"_URL"]})," etc.) let you compose a download URL for browser-side use."]})}):e.jsx(C,{layout:"multiline",intent:"warning",children:e.jsxs(R,{children:[e.jsx($,{children:"Delete"}),"Clears ",e.jsx("code",{children:n.logicalName})," + its companion columns (id / _Timestamp / _URL). Three equivalent paths per docs: DELETE /col (shown), PATCH set null, or PUT /col with body"," ",e.jsx("code",{children:'{"value":null}'}),"."]})}):e.jsx(C,{layout:"multiline",intent:"info",children:e.jsx(R,{children:"Pick an image column on the left to see operation-specific guidance."})})}export{wa as ManageImageMode};
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
import{f as P,l as b,bt as et,bu as xe,ap as ce,bv as tt,A as e,N as E,O as $,ah as G,bw as J,ae,bx as rt,aL as Fe,Y as at,by as st,bz as it,bq as Q,a2 as n,b8 as Ce,a3 as M,ai as nt,aj as te,aE as Ie,br as ot,bA as lt,bB as se,bn as ie,b5 as ne,bC as dt,_ as oe,ak as ct,al as ut,bD as pt,bE as gt,k as bt,b9 as ht,bF as je,u as ft,n as De,bG as mt,bH as yt,bI as xt,bJ as jt,ar as St,as as vt,at as kt,au as Tt,bK as Nt,be as wt,p as re,q as Se,t as Ft,bL as Pe,bM as Ct,bN as ve,aS as Me,aT as It,L as Dt,z as Pt,aB as le,aC as Mt,aD as Lt,H as Rt,I as ke,J as Bt,K as At,P as Ot,R as zt,U as Et,S as $t,Q as Vt,aN as Ut,bO as Ht,b0 as _t,V as Le,ad as Re,b6 as Gt,T as Wt,b1 as qt,bs as Kt,bP as Jt}from"./index-XmEQbXiX.js";const Qt=new Set(["createdon","modifiedon","createdby","modifiedby","createdonbehalfby","modifiedonbehalfby","versionnumber","importsequencenumber","overriddencreatedon","utcconversiontimezonecode","timezoneruleversionnumber","statecode","statuscode"]),Xt=s=>Qt.has(s.logicalName)||s.attributeType==="File"||s.attributeType==="Image"||s.attributeType==="Uniqueidentifier"&&s.isPrimaryKey===!0;function Yt(s){const{table:a,target:i,sub:t,fieldChoices:d,customValues:c,setFieldChoice:p,setCustomValue:o}=s,u=P(a),[h,S]=b.useState(""),[k,C]=b.useState(!0),T=b.useMemo(()=>!u||!i||!t?[]:u.columns.filter(x=>!Xt(x)&&x.isValidForUpdate!==!1&&!et(x)).map(x=>{const v=xe(i,x),N=xe(t,x),V=v==null||v==="",I=N==null||N==="";let F;return V&&I?F="both-empty":V&&!I?F="auto-fill":!V&&I?F="sub-empty":ce(x)?F=tt(v,N)?"same":"differs":F=String(v)===String(N)?"same":"differs",{col:x,targetVal:v,subVal:N,state:F}}),[u,i,t]),L=b.useMemo(()=>{let m=T;if(k&&(m=m.filter(y=>y.state==="differs"||y.state==="auto-fill")),h){const y=h.toLowerCase();m=m.filter(x=>x.col.displayName.toLowerCase().includes(y)||x.col.logicalName.toLowerCase().includes(y))}return m},[T,k,h]),w=b.useMemo(()=>{const m=Object.values(d).filter(v=>v!=="target").length,y=T.filter(v=>v.state==="differs").length,x=T.filter(v=>v.state==="auto-fill").length;return{overrides:m,differs:y,autoFill:x}},[d,T]);return u?!i||!t?e.jsxs("div",{children:[e.jsx(G,{icon:J,title:"Field comparison",sub:"Pick both Target and Subordinate to see a side-by-side diff.",group:"write"}),e.jsx(E,{layout:"multiline",intent:"info",style:{maxWidth:720},children:e.jsx($,{children:!i&&!t?"Pick a Target (the record that survives) and a Subordinate (the duplicate to merge away) to start.":i?"Pick a Subordinate record on the left rail.":"Pick a Target record on the left rail."})})]}):e.jsxs("div",{children:[e.jsxs(G,{icon:J,title:"Field comparison",sub:e.jsxs("span",{children:["For each differing field, pick what the merged row should carry — the Target's value, the Subordinate's value, or your own."," ",e.jsx("strong",{children:"Empty Target fields get auto-filled"})," from the Subordinate by the server."]}),group:"write",children:[e.jsx(ae,{contentBefore:e.jsx(rt,{}),"aria-label":"Filter fields",placeholder:"Filter fields…",value:h,onChange:(m,y)=>S(y.value),size:"small",style:{width:220}}),e.jsx(Fe,{content:k?"Showing only differing / auto-fill rows":"Showing every column",relationship:"description",children:e.jsx(at,{size:"small",appearance:k?"primary":"outline",icon:k?e.jsx(st,{}):e.jsx(it,{}),onClick:()=>C(m=>!m),children:k?"Diff only":"All fields"})}),e.jsxs(Q,{appearance:"tint",color:w.overrides>0?"brand":"subtle",children:[w.overrides," override",w.overrides===1?"":"s"]}),e.jsxs(Q,{appearance:"ghost",children:[w.differs," differ · ",w.autoFill," auto-fill"]})]}),e.jsx("div",{style:{maxWidth:1200,overflowX:"auto"},children:e.jsxs("table",{style:{width:"100%",borderCollapse:"separate",borderSpacing:0},children:[e.jsx("thead",{children:e.jsxs("tr",{children:[e.jsx(q,{style:{width:"20%"},children:"Field"}),e.jsx(q,{tone:"target",children:"Target (survives)"}),e.jsx(q,{tone:"sub",children:"Subordinate"}),e.jsx(q,{style:{width:"34%"},children:"Final value"})]})}),e.jsxs("tbody",{children:[L.length===0&&e.jsx("tr",{children:e.jsx("td",{colSpan:4,style:{padding:"24px 8px",textAlign:"center",color:n.colorNeutralForeground3,fontStyle:"italic"},children:k?'No differing fields. Toggle "All fields" to see the full row.':"No fields match the search."})}),L.map(m=>e.jsx(Zt,{tbl:u,row:m,choice:d[m.col.logicalName]??"target",customValue:c[m.col.logicalName],onChoice:y=>p(m.col.logicalName,y),onCustom:y=>o(m.col.logicalName,y)},m.col.logicalName))]})]})})]}):e.jsx(E,{layout:"multiline",intent:"error",children:e.jsxs($,{children:["Unknown table ",e.jsx("code",{children:a}),"."]})})}function Zt({tbl:s,row:a,choice:i,customValue:t,onChoice:d,onCustom:c}){const p=Ce(),{col:o,targetVal:u,subVal:h,state:S}=a,k=S==="differs",C=S==="auto-fill",T=!(h==null||h==="");return e.jsxs("tr",{children:[e.jsx(K,{children:e.jsxs("div",{style:{display:"flex",flexDirection:"column",gap:2},children:[e.jsx("span",{style:{fontWeight:500,color:n.colorNeutralForeground1,fontSize:12},children:o.displayName}),e.jsxs(M,{style:{color:n.colorNeutralForeground3,fontFamily:n.fontFamilyMonospace,fontSize:10},children:[o.logicalName," ·"," ",e.jsx("span",{style:{color:n.colorBrandForeground2},children:o.attributeType})]}),C&&e.jsx(Fe,{content:"Target is empty — server will auto-fill from Subordinate. No override needed.",relationship:"description",children:e.jsx(Q,{appearance:"tint",color:"success",size:"small",style:{alignSelf:"flex-start"},children:"auto-fill"})})]})}),e.jsx(K,{tone:"target",children:e.jsx(Te,{col:o,value:u,tbl:s})}),e.jsx(K,{tone:"sub",children:e.jsx(Te,{col:o,value:h,tbl:s})}),e.jsx(K,{children:e.jsxs("div",{className:ot(p.inlineCard),style:{padding:"6px 8px"},children:[e.jsxs(nt,{layout:"horizontal",value:i,onChange:(L,w)=>d(w.value),children:[e.jsx(te,{value:"target",label:e.jsxs("span",{style:{fontSize:11},children:["Target",!k&&!C&&e.jsx("span",{style:{color:n.colorNeutralForeground3},children:" · default"})]})}),e.jsx(te,{value:"subordinate",disabled:!T,label:e.jsxs("span",{style:{fontSize:11},children:["Subordinate",!T&&e.jsx("span",{style:{color:n.colorNeutralForeground3},children:" · empty"})]})}),e.jsx(te,{value:"custom",label:e.jsx("span",{style:{fontSize:11},children:"Custom"})})]}),i==="custom"&&e.jsx("div",{style:{marginTop:6},children:e.jsx(er,{col:o,value:t,onChange:c,fallback:typeof u=="object"?"":String(u??""),parentTable:s.logicalName})}),i==="subordinate"&&e.jsxs("div",{style:{marginTop:6,display:"flex",alignItems:"center",gap:6},children:[e.jsx(Ie,{style:{width:14,height:14,color:n.colorBrandForeground1}}),e.jsxs(M,{style:{color:n.colorBrandForeground2,fontWeight:500},children:["Will overwrite Target with: ",e.jsx("strong",{children:Be(o,h)})]})]})]})})]})}function q({children:s,style:a,tone:i}){const t=i==="target"?{background:"rgba(31,127,56,.08)",color:n.colorPaletteGreenForeground1}:i==="sub"?{background:"rgba(242,176,80,.08)",color:n.colorPaletteDarkOrangeForeground1}:{};return e.jsx("th",{style:{textAlign:"left",padding:"8px 10px",fontSize:11,fontWeight:600,color:n.colorNeutralForeground2,borderBottom:`2px solid ${n.colorNeutralStroke2}`,whiteSpace:"nowrap",...t,...a},children:s})}function K({children:s,tone:a}){const i=a==="target"?{background:"rgba(31,127,56,.025)",borderLeft:`2px solid ${n.colorPaletteGreenBorderActive}`}:a==="sub"?{background:"rgba(242,176,80,.025)",borderLeft:`2px solid ${n.colorPaletteDarkOrangeBorderActive}`}:{};return e.jsx("td",{style:{padding:"8px 10px",verticalAlign:"top",borderBottom:`1px solid ${n.colorNeutralStroke3}`,fontSize:12,...i},children:s})}function Te({col:s,value:a,tbl:i}){if(a==null||a==="")return e.jsx("span",{style:{color:n.colorNeutralForeground3,fontStyle:"italic",fontSize:11},children:"(empty)"});const t=Be(s,a);return e.jsx("span",{style:{fontFamily:s.attributeType==="Uniqueidentifier"||ce(s)&&!a.name?n.fontFamilyMonospace:n.fontFamilyBase,fontSize:12,color:n.colorNeutralForeground1,wordBreak:"break-word"},children:t})}function Be(s,a){if(a==null||a==="")return"(empty)";if(s.attributeType==="Boolean")return a===!0||a==="1"||a===1?s.trueOption.label:s.falseOption.label;if(ce(s)&&typeof a=="object"&&"id"in a)return pt(a);const i=se(s);if(i){const t=Number(a);if(Number.isFinite(t)){const d=i.find(c=>c.value===t);if(d)return`${d.label} · ${t}`}if(s.attributeType==="MultiSelectPicklist"&&typeof a=="string")return a.split(",").map(d=>{const c=i.find(p=>String(p.value)===d);return c?c.label:d}).join(", ")}if(s.attributeType==="Money"){const t=Number(a);if(Number.isFinite(t))return t.toLocaleString(void 0,{style:"currency",currency:"USD"})}return s.attributeType==="DateTime"&&typeof a=="string"?gt(a,s):String(a)}function er({col:s,value:a,onChange:i,fallback:t,parentTable:d}){switch(lt(d,s.logicalName),s.attributeType){case"Memo":return e.jsx(ut,{"aria-label":`${s.displayName} (custom value)`,rows:2,size:"small",value:a??t,onChange:(c,p)=>i(p.value),style:{fontFamily:n.fontFamilyMonospace,fontSize:12}});case"Integer":case"BigInt":case"Decimal":case"Double":case"Money":return e.jsx(ct,{"aria-label":`${s.displayName} (custom value)`,size:"small",value:Number(a??0),onChange:(c,p)=>{const o=p.value??Number(p.displayValue??0);Number.isFinite(o)&&i(o)}});case"Boolean":return e.jsx(oe,{checked:a===!0,onChange:(c,p)=>i(p.checked),label:a===!0?s.trueOption.label:s.falseOption.label});case"Picklist":case"State":case"Status":case"EntityName":{const c=se(s)??[],p=c.find(o=>o.value===a);return e.jsx(ie,{"aria-label":`${s.displayName} (custom value)`,size:"small",value:p?.label??(a!=null?String(a):""),selectedOptions:a!=null?[String(a)]:[],onOptionSelect:(o,u)=>u.optionValue&&i(Number(u.optionValue)),placeholder:"Pick a value…",children:c.map(o=>e.jsx(ne,{value:String(o.value),text:o.label,children:o.label},o.value))})}case"Lookup":case"Customer":case"Owner":return e.jsx(dt,{col:s,value:a,onChange:i});case"MultiSelectPicklist":{const c=se(s)??[],p=Array.isArray(a)?a:typeof a=="string"&&a?a.split(",").map(o=>Number(o.trim())).filter(o=>Number.isFinite(o)):[];return e.jsx(ie,{"aria-label":`${s.displayName} (custom value)`,size:"small",multiselect:!0,value:p.map(o=>c.find(u=>u.value===o)?.label??String(o)).join(", "),selectedOptions:p.map(String),onOptionSelect:(o,u)=>{const h=(u.selectedOptions??[]).map(S=>Number(S)).filter(S=>Number.isFinite(S));i(h)},placeholder:"Pick one or more…",children:c.map(o=>e.jsx(ne,{value:String(o.value),text:o.label,children:o.label},o.value))})}case"DateTime":return e.jsx(ae,{"aria-label":`${s.displayName} (custom value)`,size:"small",type:s.format==="DateOnly"?"date":"datetime-local",value:typeof a=="string"?a.slice(0,16):"",onChange:(c,p)=>i(p.value),style:{fontFamily:n.fontFamilyMonospace,fontSize:12}});default:return e.jsx(ae,{"aria-label":`${s.displayName} (custom value)`,size:"small",value:a??t,onChange:(c,p)=>i(p.value)})}}const de=["account","contact","lead","incident"],Ae="account, contact, lead, and incident",tr=s=>de.includes(s),rr=()=>({table:"",targetId:null,subordinateId:null,fieldChoices:{},customValues:{},performParentingChecks:!0,suppressDuplicateDetection:!1,bypass:Ut(),headers:Vt(),dirty:new Set,targetSnapshot:null,subordinateSnapshot:null}),z=Ht;function dr({themeMode:s}){const a=bt("merge"),i=ht("merge",je,rr),[t,d]=b.useState(i.state),{table:c}=ft(t.table||null),{allEntities:p}=De(),[o,u]=b.useState("target"),[h,S]=b.useState("builder"),[k,C]=b.useState(null),[T,L]=b.useState(!1),[w,m]=b.useState([]),[y,x]=b.useState(i.lastSavedId),[v,N]=b.useState(i.lastSavedHash),[V,I]=b.useState(!1),[F,X]=b.useState(!1),j=P(t.table),Y=b.useMemo(()=>{const r=t.subordinateSnapshot;if(!j||!r)return[];const g=new Set;for(const[l,f]of Object.entries(t.fieldChoices)){if(f!=="subordinate")continue;const A=j.columns.find(Ze=>Ze.logicalName===l),O=A&&mt(r,A)?.targetEntity;O&&g.add(O)}return[...g].sort()},[j,t.subordinateSnapshot,t.fieldChoices]),Oe=Y.join("|"),[ze,Ee]=b.useState([]);b.useEffect(()=>{for(const r of Y)P(r)||yt.getTable(r).catch(()=>{}).then(g=>{g||Ee(l=>l.includes(r)?l:[...l,r])})},[Oe]);const W=Y.filter(r=>!P(r)),ue=W.filter(r=>ze.includes(r)),U=b.useMemo(()=>xt(t),[t,c]),$e=W.join("|"),Ve=b.useMemo(()=>jt(t),[t,c,$e]);b.useEffect(()=>{let r=!1;if(!t.table||!t.targetId||!j||!z(t.targetId)){d(l=>({...l,targetSnapshot:null}));return}if(typeof window>"u"||!window.dataverseAPI?.queryData)return;I(!0);const g=`/${j.entitySetName}(${t.targetId})`;return window.dataverseAPI.queryData(g).then(l=>{if(r)return;const f=l?.value,A=Array.isArray(f)?f[0]??null:f&&typeof f=="object"?f:l&&typeof l=="object"&&j.primaryKey in l?l:null;d(O=>({...O,targetSnapshot:A})),I(!1)}).catch(()=>{r||(d(l=>({...l,targetSnapshot:null})),I(!1))}),()=>{r=!0}},[t.table,t.targetId,j]),b.useEffect(()=>{let r=!1;if(!t.table||!t.subordinateId||!j||!z(t.subordinateId)){d(l=>({...l,subordinateSnapshot:null}));return}if(typeof window>"u"||!window.dataverseAPI?.queryData)return;X(!0);const g=`/${j.entitySetName}(${t.subordinateId})`;return window.dataverseAPI.queryData(g).then(l=>{if(r)return;const f=l?.value,A=Array.isArray(f)?f[0]??null:f&&typeof f=="object"?f:l&&typeof l=="object"&&j.primaryKey in l?l:null;d(O=>({...O,subordinateSnapshot:A})),X(!1)}).catch(()=>{r||(d(l=>({...l,subordinateSnapshot:null})),X(!1))}),()=>{r=!0}},[t.table,t.subordinateId,j]);const pe=r=>d(g=>{const l=new Set(g.dirty);return l.add(r),{...g,dirty:l}}),R=(r,g,l)=>{d(f=>({...f,[r]:g})),l&&pe(l)},Ue=(r,g)=>{d(l=>{const f={...l.fieldChoices};return g==="target"?delete f[r]:f[r]=g,{...l,fieldChoices:f,dirty:new Set(l.dirty).add("fielddiff")}})},He=(r,g)=>{d(l=>({...l,customValues:{...l.customValues,[r]:g},dirty:new Set(l.dirty).add("fielddiff")}))},Z=t.targetSnapshot,ee=t.subordinateSnapshot,H=Object.values(t.fieldChoices).filter(r=>r!=="target").length,_e=j?tr(j.logicalName)?t.targetId?z(t.targetId)?t.subordinateId?z(t.subordinateId)?t.targetId===t.subordinateId?"Target and Subordinate must be different records.":t.headers.some(r=>r.enabled&&!r.name)?"Fix empty header name.":ue.length>0?`Couldn't load metadata for ${ue.join(", ")}, so a lookup kept from the Subordinate can’t be bound. Pick Target or Custom for it instead.`:W.length>0?`Loading metadata for ${W.join(", ")} to bind the lookups kept from the Subordinate…`:null:"Subordinate record id is not a valid GUID.":"Pick a Subordinate record (the loser).":"Target record id is not a valid GUID.":"Pick a Target record (the winner).":`Merge is only supported for ${Ae}.`:"Pick a target table first.",Ge=async()=>{L(!0);const r=await qt.merge(t,ke(ge,null));C(r),L(!1),S("results"),m(g=>[{id:`r-${Date.now()}`,snapshot:B,modeId:"merge",url:U.relativeUrl,method:"POST",ts:Date.now(),status:r.status,ms:r.ms,rowCount:r.ok?1:0},...g].slice(0,8)),d(g=>({...g,dirty:new Set}))},ge=b.useMemo(()=>{let r=[...t.headers];return t.suppressDuplicateDetection&&r.push({id:"__sup-dupe",name:"MSCRM.SuppressDuplicateDetection",value:"true",enabled:!0,builtin:!0,hint:"Skips duplicate detection rules when applying UpdateContent overrides."}),r=St(r,t.bypass),r},[t.headers,t.suppressDuplicateDetection,t.bypass]),be=b.useMemo(()=>{const r=[...vt(t.bypass,"bypass"),...kt({op:"merge",bypass:t.bypass})];return t.targetId&&!z(t.targetId)&&r.push({id:"merge-bad-target-guid",severity:"error",source:"validation",focusNode:"target",title:"Invalid Target record id",body:`"${t.targetId}" isn't a valid GUID. The merge will fail at the wire.`}),t.subordinateId&&!z(t.subordinateId)&&r.push({id:"merge-bad-sub-guid",severity:"error",source:"validation",focusNode:"subordinate",title:"Invalid Subordinate record id",body:`"${t.subordinateId}" isn't a valid GUID. The merge will fail at the wire.`}),r},[t.bypass,t.targetId,t.subordinateId]),We=Tt(be),B=b.useMemo(()=>Nt(t),[t]);wt("merge",B,y,v);const qe=b.useMemo(()=>re(B),[B]),he=v===null?!0:qe!==v,Ke=r=>{x(r.id),N(re(r.state))},fe=r=>{if(r.modeId!=="merge")return;const g=r.state;if(p.length>0&&!p.some(l=>l.logicalName===g.table)){_t(`Can't load "${r.name}": entity \`${g.table}\` isn't available in this environment. The solution may have been removed or you may be connected to a different org.`);return}d(je(g)),x(r.id),N(re(g)),C(null),u("target")},Je=r=>{const g=Kt(r,"merge");if(!g)return;const l=y,f=v;fe(g),x(l),N(f)},me=Se(Ke),ye=Se(fe);Ft(b.useMemo(()=>t.table?{state:B,modeId:"merge",dirty:he,lastSavedId:y,onSaved:me,onLoadSaved:ye}:null,[B,he,y,t.table,me,ye]));const Qe=[{id:"target",label:"Target",meta:j?.displayName??"Pick a table",items:[{id:"target",icon:Ct,iconFilled:Pe,label:"Master (survives)",badge:t.targetId?"✓":null,badgeAppearance:"ghost",dirty:t.dirty.has("target")||t.dirty.has("entity")}]},{id:"subordinate-section",label:"Subordinate",meta:t.subordinateId?"will be deactivated":"pick a record",items:[{id:"subordinate",icon:ve,iconFilled:J,label:"Subordinate record",badge:t.subordinateId?"✓":null,badgeAppearance:"ghost",dirty:t.dirty.has("subordinate")}]},{id:"override",label:"Override fields",meta:`${H} override${H===1?"":"s"}`,items:[{id:"fielddiff",icon:ve,iconFilled:J,label:"Field comparison",badge:H||null,badgeAppearance:"tint",badgeColor:H>0?"brand":"subtle",dirty:t.dirty.has("fielddiff")}]},{id:"settings",label:"Settings",meta:(t.performParentingChecks?1:0)+(t.suppressDuplicateDetection?1:0)==0?"defaults":`${(t.performParentingChecks?1:0)+(t.suppressDuplicateDetection?1:0)} set`,items:[{id:"options",icon:It,iconFilled:Me,label:"Merge options",badge:(t.performParentingChecks?1:0)+(t.suppressDuplicateDetection?1:0)||null,badgeAppearance:"ghost",dirty:t.dirty.has("options")}]},{id:"headers",label:"Headers",meta:`${t.headers.filter(r=>r.enabled).length} active`,items:[{id:"headers",icon:Pt,iconFilled:Dt,label:"HTTP headers",badge:t.headers.filter(r=>r.enabled).length||null,dirty:t.dirty.has("headers")},{id:"bypass",icon:le,iconFilled:le,label:"Bypass logic",badge:Mt(t.bypass),badgeAppearance:t.bypass.businessLogic!=="none"||t.bypass.suppressFlows?"tint":"ghost",badgeColor:t.bypass.businessLogic!=="none"||t.bypass.suppressFlows?"warning":"subtle",dirty:t.dirty.has("bypass")}]}];let D;switch(o){case"target":D=e.jsxs("div",{style:{display:"flex",flexDirection:"column",gap:14},children:[e.jsx(ir,{state:t,setState:d,markDirty:pe,onEntityChange:()=>{x(void 0),N(null)}}),e.jsx(we,{title:"Master record",sub:"The record that keeps its identity. Subordinate is merged into it.",table:t.table,selectedId:t.targetId,onPick:r=>R("targetId",r,"target")})]});break;case"subordinate":D=e.jsx(we,{title:"Subordinate (deactivated)",sub:"The duplicate to merge away. Its relationships re-parent to the Target; the row gets statecode=Inactive.",table:t.table,selectedId:t.subordinateId,onPick:r=>R("subordinateId",r,"subordinate"),conflictWith:t.targetId});break;case"fielddiff":D=e.jsxs("div",{children:[e.jsx(ar,{overrideCount:H,subordinateName:_(j,ee??void 0)}),e.jsx(sr,{table:t.table,target:Z??void 0,subordinate:ee??void 0,targetLoading:V,subordinateLoading:F}),e.jsx(Yt,{table:t.table,target:t.targetSnapshot??null,sub:t.subordinateSnapshot??null,fieldChoices:t.fieldChoices,customValues:t.customValues,setFieldChoice:Ue,setCustomValue:He})]});break;case"options":D=e.jsx(nr,{performParentingChecks:t.performParentingChecks,setPerformParentingChecks:r=>R("performParentingChecks",r,"options"),suppressDuplicateDetection:t.suppressDuplicateDetection,setSuppressDuplicateDetection:r=>R("suppressDuplicateDetection",r,"options")});break;case"headers":D=e.jsx(Rt,{items:t.headers,setItems:r=>R("headers",r,"headers"),group:"write"});break;case"bypass":D=e.jsx(Lt,{value:t.bypass,onChange:r=>R("bypass",r,"bypass"),group:"write"});break}const Xe=ke(ge,null),Ye={method:"POST",built:U,headers:Xe,body:Ve,entityLogical:U.entityLogical};return e.jsx(Bt,{sidebar:e.jsx($t,{type:a,urlPreview:U.relativeNoBase,sections:Qe,activeNode:o,onSelect:r=>{u(r),S("builder")},recents:w,onRecentClick:Je}),urlBar:e.jsx(Et,{method:"POST",url:U.relativeUrl,executeVerb:a.executeVerb,writeConfirm:{operation:"Merge Records",table:t.table,scope:{kind:"text",text:"2 records: the subordinate merges into the master and is deactivated"},highImpact:!0},disabledReason:_e??We,loading:T,onExecute:Ge,advisories:be,onAdvisoryFocus:u}),children:e.jsxs(At,{tab:h,onTabChange:S,resultCount:k?.ok?1:null,children:[h==="builder"&&D,h==="code"&&e.jsx(Ot,{themeMode:s,inputs:Ye}),h==="results"&&e.jsx(zt,{result:k,mode:"single",table:t.table,writeContext:{operation:"merge",table:t.table,recordId:t.targetId,recordName:_(j,Z??void 0),targetName:_(j,Z??void 0),subordinateName:_(j,ee??void 0)}})]})})}function ar({overrideCount:s,subordinateName:a}){return e.jsx(E,{layout:"multiline",intent:"warning",icon:e.jsx(le,{}),style:{marginBottom:14},children:e.jsxs($,{children:[e.jsx(Le,{children:"Merge is irreversible."}),a?e.jsxs(e.Fragment,{children:[e.jsx("strong",{children:a})," will be deactivated,"," "]}):"The subordinate will be deactivated, ","its related records re-parent to the Target, and ",e.jsx("strong",{children:s})," field",s===1?"":"s"," on the Target will be overwritten by your overrides. The server also auto-fills any empty Target fields from the Subordinate."]})})}function sr({table:s,target:a,subordinate:i,targetLoading:t,subordinateLoading:d}){const c=Ce(),p=P(s);return p?e.jsxs("div",{className:c.inlineCard,style:{padding:14,marginBottom:14,display:"grid",gridTemplateColumns:"1fr 44px 1fr",gap:10,alignItems:"stretch"},children:[e.jsx(Ne,{tone:"target",chip:"TARGET",chipDescription:"survives the merge",row:a,tbl:p,emptyHint:t?"Loading Target record…":"Pick a Target record."}),e.jsx("div",{style:{display:"flex",alignItems:"center",justifyContent:"center",color:n.colorNeutralForeground3},children:e.jsx(Ie,{style:{width:28,height:28}})}),e.jsx(Ne,{tone:"sub",chip:"SUBORDINATE",chipDescription:"will be deactivated",row:i,tbl:p,emptyHint:d?"Loading Subordinate record…":"Pick a Subordinate record."})]}):null}function Ne({tone:s,chip:a,chipDescription:i,row:t,tbl:d,emptyHint:c}){const p=s==="target"?{border:`1px solid ${n.colorPaletteGreenBorderActive}`,background:n.colorPaletteGreenBackground1}:{border:`1px solid ${n.colorPaletteDarkOrangeBorderActive}`,background:n.colorPaletteDarkOrangeBackground1},o=s==="target"?n.colorPaletteGreenForeground1:n.colorPaletteDarkOrangeForeground1,u=_(d,t),h=t?String(t[d.primaryKey]??""):null,S=t?.createdon?String(t.createdon):null,k=S?new Date(S).toLocaleDateString(void 0,{year:"numeric",month:"short"}):null;return e.jsxs("div",{style:{...p,borderRadius:n.borderRadiusMedium,padding:12},children:[e.jsxs("div",{style:{display:"flex",alignItems:"center",gap:8,marginBottom:8},children:[e.jsx(Q,{appearance:"filled",style:{background:o,color:n.colorNeutralForegroundOnBrand,fontWeight:700,letterSpacing:.4},children:a}),e.jsx(M,{style:{color:n.colorNeutralForeground3},children:i})]}),t?e.jsxs(e.Fragment,{children:[e.jsxs("div",{style:{display:"flex",alignItems:"center",gap:10,marginBottom:8},children:[e.jsx(Jt,{size:"small",name:u??"?",avatar:{color:"colorful"}}),e.jsxs("div",{style:{flex:1,minWidth:0},children:[e.jsx("div",{style:{fontSize:13,fontWeight:600},children:u??"(no name)"}),e.jsx("div",{style:{fontFamily:n.fontFamilyMonospace,fontSize:10,color:n.colorNeutralForeground3},children:h??""})]})]}),e.jsxs("div",{style:{display:"flex",flexDirection:"column",gap:2,fontSize:11,color:n.colorNeutralForeground3},children:[k&&e.jsxs("div",{children:["Created:"," ",e.jsx("strong",{style:{color:n.colorNeutralForeground2},children:k})]}),t.accountnumber!=null&&e.jsxs("div",{children:["Account #:"," ",e.jsx("strong",{style:{color:n.colorNeutralForeground2,fontFamily:n.fontFamilyMonospace},children:String(t.accountnumber)})]}),t.revenue!=null&&e.jsxs("div",{children:["Revenue:"," ",e.jsx("strong",{style:{color:n.colorNeutralForeground2},children:Number(t.revenue).toLocaleString(void 0,{style:"currency",currency:"USD",maximumFractionDigits:0})})]}),t.emailaddress1!=null&&e.jsxs("div",{children:["Email:"," ",e.jsx("strong",{style:{color:n.colorNeutralForeground2},children:String(t.emailaddress1)})]})]})]}):e.jsx("div",{style:{padding:"20px 4px",color:n.colorNeutralForeground3,fontSize:12,fontStyle:"italic",textAlign:"center"},children:c})]})}function ir({state:s,setState:a,markDirty:i,onEntityChange:t}){const d=P(s.table),{allEntities:c,allLoading:p}=De(),o=b.useMemo(()=>de.map(u=>c.find(h=>h.logicalName===u)).filter(u=>!!u),[c]);return e.jsxs("div",{children:[e.jsx(G,{icon:Wt,title:"Merge entity type",sub:`Pick the table to merge. The Merge action is restricted to ${Ae}.`,group:"write"}),e.jsxs("div",{style:{maxWidth:560},children:[e.jsx(Re,{label:"Entity",hint:p?"Loading tables…":o.length===0?`No Merge-supported table (${de.join(", ")}) was found in this environment.`:void 0,children:e.jsx(ie,{value:d?.displayName??"",selectedOptions:[s.table],onOptionSelect:(u,h)=>{h.optionValue&&(a(S=>({...S,table:h.optionValue,targetId:null,subordinateId:null,fieldChoices:{},customValues:{},targetSnapshot:null,subordinateSnapshot:null})),i("entity"),i("target"),i("subordinate"),i("fielddiff"),t())},children:o.map(u=>e.jsx(ne,{value:u.logicalName,text:u.displayName,children:e.jsxs("div",{style:{display:"flex",flexDirection:"column"},children:[e.jsx("span",{children:u.displayName}),e.jsxs(M,{style:{color:n.colorNeutralForeground3},children:[u.entitySetName," · supports Merge"]})]})},u.logicalName))})}),e.jsx(E,{layout:"multiline",intent:"info",style:{marginTop:14},children:e.jsxs($,{children:["Merge requires both records be the ",e.jsx("strong",{children:"same entity type"}),"."," ",e.jsx("code",{children:"incident"})," behaves differently — per docs, the ",e.jsx("code",{children:"UpdateContent"})," ","parameter is ",e.jsx("strong",{children:"ignored"})," for incident, and the merge runs in the user's security context (not system)."]})})]})]})}function we({title:s,sub:a,table:i,selectedId:t,onPick:d,conflictWith:c}){const p=P(i),o=c&&t&&c===t;return e.jsxs("div",{children:[e.jsx(G,{icon:Pe,title:s,sub:a,group:"write"}),e.jsxs("div",{style:{maxWidth:480},children:[e.jsx(Re,{label:"Record",children:e.jsx(Gt,{table:i,selectedId:t,onPick:u=>d(u?.id??null),placeholder:`Search ${p?.displayName??""} records…`})}),o&&e.jsx(E,{layout:"multiline",intent:"error",style:{marginTop:14},children:e.jsx($,{children:"Target and Subordinate must be different records."})}),!t&&e.jsx(M,{style:{display:"block",marginTop:8,color:n.colorNeutralForeground3},children:"Tip: use the search box to filter by primary name (e.g. account name, contact full name)."})]})]})}function nr({performParentingChecks:s,setPerformParentingChecks:a,suppressDuplicateDetection:i,setSuppressDuplicateDetection:t}){return e.jsxs("div",{children:[e.jsx(G,{icon:Me,title:"Merge options",sub:"Controls applied during the merge operation.",group:"write"}),e.jsxs("div",{style:{maxWidth:720,display:"flex",flexDirection:"column",gap:16},children:[e.jsx("div",{style:{padding:12,border:`1px solid ${n.colorNeutralStroke2}`,borderRadius:n.borderRadiusMedium},children:e.jsx(oe,{checked:s,onChange:(d,c)=>a(c.checked),label:e.jsxs("span",{children:[e.jsx("strong",{children:"PerformParentingChecks"}),e.jsx(M,{style:{display:"block",color:n.colorNeutralForeground3,marginTop:2},children:"When enabled, the merge fails if the Target and Subordinate have different parent records. Useful for child entities (e.g. contacts under different accounts)."})]})})}),e.jsx("div",{style:{padding:12,border:`1px solid ${n.colorNeutralStroke2}`,borderRadius:n.borderRadiusMedium},children:e.jsx(oe,{checked:i,onChange:(d,c)=>t(c.checked),label:e.jsxs("span",{children:[e.jsx("strong",{children:"MSCRM.SuppressDuplicateDetection"})," ",e.jsx("code",{style:{fontFamily:n.fontFamilyMonospace,fontSize:11},children:"= true"}),e.jsxs(M,{style:{display:"block",color:n.colorNeutralForeground3,marginTop:2},children:["Skip duplicate detection rules when applying ",e.jsx("code",{children:"UpdateContent"})," to the Target. Adds the ",e.jsx("code",{children:"MSCRM.SuppressDuplicateDetection: true"})," request header."]})]})})}),e.jsx(E,{layout:"multiline",intent:"warning",children:e.jsxs($,{children:[e.jsx(Le,{children:"Merge is destructive."}),"The Subordinate is deactivated (",e.jsx("code",{children:"statecode=Inactive"}),") and most of its relationships re-parent to the Target. Some Target fields take Subordinate's value only when the Target's value is empty. Use ",e.jsx("strong",{children:"UpdateContent"})," (the Field comparison pane) to override that."]})})]})]})}function _(s,a){if(!s||!a)return null;const i=a[s.primaryName];return i!=null?String(i):null}export{dr as MergeMode};
|