var f=Object.defineProperty;var E=(c,e,t)=>e in c?f(c,e,{enumerable:!0,configurable:!0,writable:!0,value:t}):c[e]=t;var l=(c,e,t)=>E(c,typeof e!="symbol"?e+"":e,t);new KintoneRestAPIClient;const h=["RECORD_NUMBER","CREATOR","CREATED_TIME","MODIFIER","UPDATED_TIME","CATEGORY","STATUS","STATUS_ASSIGNEE","SINGLE_LINE_TEXT","NUMBER","CALC","MULTI_LINE_TEXT","RICH_TEXT","LINK","CHECK_BOX","RADIO_BUTTON","DROP_DOWN","MULTI_SELECT","FILE","DATE","TIME","DATETIME","USER_SELECT","ORGANIZATION_SELECT","GROUP_SELECT","GROUP","REFERENCE_TABLE","SUBTABLE"];h.reduce((c,e)=>(c[e]=e,c),{});function C(c){return e=>(e==null?void 0:e.type)===c}const u=Object.fromEntries(h.map(c=>[c,C(c)]));class T{constructor(e,t){l(this,"config");l(this,"currentApp");l(this,"handleButtonClick",async()=>{const e=this.showSpinner();try{console.log("データ収集開始..."),await this.execDataFectch(),e.close(),location.reload()}catch(t){e.close();const r=`データ収集中処理中例外発生しました。${t instanceof Error?`
詳細:`+t.message:""}`;console.error(r,t),window.alert(r)}});l(this,"execDataFectch",async()=>{const e=this.config.joinTables[0];let n=(await this.fetchDataFromApp(e)).map(i=>{const o={};return e.fieldsMapping.forEach(s=>{o[this.fieldCode(s.rightField)]=i[this.fieldCode(s.leftField)]}),o});const r=this.config.joinTables.filter((i,o)=>o>0);for(const i of r){const o=await this.fetchDataFromApp(i);n=this.leftJoin(n,o,i)}await this.deleteCurrentRecords(),await this.saveDataToCurrentApp(n)});l(this,"fetchDataFromApp",async e=>{const t=this.getWhereCondition(e.whereConditions),n=e.fieldsMapping.map(s=>this.fieldCode(s.leftField));e.table&&n.push(e.table),e.onConditions.map(s=>this.fieldCode(s.leftField)).forEach(s=>{n.includes(s)||n.push(s)});const o=await new KintoneRestAPIClient().record.getAllRecords({app:e.app,fields:n,condition:t});return this.convertToFlatDatas(o,e.table)});this.config=e,this.currentApp=t}init(){this.addButtonToView()}addButtonToView(){const e=kintone.app.getHeaderMenuSpaceElement();if(!e)throw new Error("このページではヘッダー要素が利用できません。");if(document.getElementById("btn-data-fetch"))return;const t=Kucs["1.18.0"],n=new t.Button({text:this.config.buttonName,type:"submit",id:"btn-data-fetch"});n.addEventListener("click",()=>this.handleButtonClick()),e.appendChild(n)}showSpinner(){const e=Kucs["1.18.0"],t=new e.Spinner({text:"データ収集中",container:document.body});return t.open(),t}getWhereCondition(e){return e.filter(r=>this.fieldCode(r.field)!=="").map(r=>{let i=r.condition;"subField"in r.field&&r.field.subField&&(i=this.mapConditionForSubField(r.condition));const o=this.getConditionValue(r.field,i,r.data);return`${this.fieldCode(r.field)} ${i} ${o}`}).join(" and ")}mapConditionForSubField(e){switch(e){case"=":return"in";case"!=":return"not in";default:return e}}getConditionValue(e,t,n){return n?u.NUMBER(e)||u.RECORD_NUMBER(e)?n:u.DATE(e)?/^\d{4}-\d{2}-\d{2}$/.test(n)||n.match(/^\w+\(.*\)$/)?`"${n}"`:`"${new Date(n).toISOString().split("T")[0]}"`:u.DATETIME(e)||u.CREATED_TIME(e)||u.UPDATED_TIME(e)?n.match(/^\w+\(.*\)$/)?`"${n}"`:`"${new Date(n).toISOString()}"`:t==="in"||t==="not in"?n.includes(",")?`(${n.split(",").map(i=>`"${i.trim()}"`).join(",")})`:`("${n}")`:`"${n}"`:""}fieldCode(e){return e?typeof e=="string"&&e?e:typeof e=="object"&&"code"in e?e.code:"":""}convertToFlatDatas(e,t){if(!t)return e;const n=[];return e.forEach(r=>{var i;if(((i=r[t])==null?void 0:i.type)==="SUBTABLE"&&r[t].value.length>0)r[t].value.forEach(o=>{const s={...r};Object.entries(o.value).forEach(([d,a])=>{s[d]={value:a.value,type:a.type}}),delete s[t],n.push(s)});else{const o={...r};delete o[t],n.push(o)}}),n}leftJoin(e,t,n){const r=[];return e.forEach(i=>{const o=t.filter(s=>n.onConditions.every(d=>{var a,p;return((a=i[this.fieldCode(d.rightField)])==null?void 0:a.value)===((p=s[this.fieldCode(d.leftField)])==null?void 0:p.value)}));o?o.forEach(s=>{const d={...i};n.fieldsMapping.forEach(a=>{d[this.fieldCode(a.rightField)]=s[this.fieldCode(a.leftField)]}),r.push(d)}):r.push(i)}),r}async deleteCurrentRecords(){const e=new KintoneRestAPIClient,n=(await e.record.getAllRecords({app:this.currentApp,fields:["$id"]})).map(r=>({id:r.$id.value}));await e.record.deleteAllRecords({app:this.currentApp,records:n}),e.record.addAllRecords}async saveDataToCurrentApp(e){try{const n=await new KintoneRestAPIClient().record.addAllRecords({app:this.currentApp,records:this.convertForUpdate(e)})}catch(t){throw console.error("データ作成時エラーが発生しました:",t),t}}convertForUpdate(e){return e.map(t=>Object.fromEntries(Object.entries(t).map(([n,{value:r}])=>[n,{value:r}])))}}(function(c){kintone.events.on("app.record.index.show",t=>{var n;try{const r=kintone.plugin.app.getConfig(c),i=e(r),o=(n=kintone.app.getId())==null?void 0:n.toString();if(!o)return;new T(i,o).init()}catch(r){const o=`データ収集中処理中例外発生しました。${r instanceof Error?`
詳細:`+r.message:""}`;t.error=o}return t});function e(t){return{buttonName:t.buttonName,joinTables:JSON.parse(t.joinTables)}}})(kintone.$PLUGIN_ID);
