(function(){
'use strict';
const esc=v=>String(v==null?'':v).replace(/[&<>"']/g,c=>({'&':'&','<':'<','>':'>','"':'"',"'":'''}[c]));
const money=v=>Number(v||0).toFixed(2);
const state={page:1,size:100,rows:[]};
function pushStatusHtml(value){const status=String(value||'pending').trim().toLowerCase();const labels={pending:'待推送',success:'推送成功',failed:'推送失败',pushing:'推送中',running:'推送中',error:'推送失败'};const tone=status==='success'?'success':(['failed','error'].includes(status)?'failed':'pending');return ''+esc(labels[status]||value||'待推送')+'';}
function pushMessageHtml(message){const full=String(message||'').trim();if(!full)return '-';const tooltip=full.replace(/\s+/g,' ');return '';}
window.copyFitOrderMessage=async function(button){const message=button?.dataset?.message||'';if(!message)return;try{if(!navigator.clipboard?.writeText)throw new Error('clipboard unavailable');await navigator.clipboard.writeText(message);}catch(e){const textarea=document.createElement('textarea');textarea.value=message;textarea.style.position='fixed';textarea.style.opacity='0';document.body.appendChild(textarea);textarea.select();document.execCommand('copy');textarea.remove();}toast('完整推送信息已复制');};
function nav(){return document.getElementById('navFitSub');}
function install(){
const sub=nav(),main=document.querySelector('main'); if(!sub||!main)return false;
if(!sub.querySelector('[data-s="fit-order-import"]')){const n=document.createElement('div');n.className='nav navchild';n.dataset.s='fit-order-import';n.dataset.resource='fit.order_import';n.textContent='积加订单导入';n.onclick=()=>open('fit-order-import');sub.insertBefore(n,sub.children[1]||null);}
if(!sub.querySelector('[data-s="fit-order-import-map"]')){const n=document.createElement('div');n.className='nav navchild';n.dataset.s='fit-order-import-map';n.dataset.resource='fit.order_import_mapping';n.textContent='积加订单字段映射';n.onclick=()=>open('fit-order-import-map');sub.insertBefore(n,sub.querySelector('[data-s="fit-shop-filter"]')||null);}
if(!document.getElementById('fit-order-import')){main.insertAdjacentHTML('beforeend',`积加订单导入
NTE.COM 销售订单导入与积加单据创建。
请选择 NTE.COM 原始订单文件。
共 0 个文件
`);}
if(!document.getElementById('fit-order-import-map')){main.insertAdjacentHTML('beforeend',`积加订单字段映射
按客户维护 Excel 来源字段到积加订单创建请求字段的关系。
每个客户分别保存一套映射;可以选择已有客户,也可以直接输入新客户。新增客户会使用同一字段模板,并把店铺名称默认设为客户名称,不会覆盖其他客户数据。自发货订单新增 V2 必须维护 shopId(积加店铺 ID)、regionId(积加区域 ID)和 marketId(积加站点 ID)的固定值。NTE.COM 已按现有多平台订单识别站点值 1000004;Lowes/TSC 的原映射不会在此修改。
| 积加请求字段 | 字段名称 | 层级 | 取值方式 | 来源列/固定值 | 启用 | 操作 |
|---|
`);}
const apiNote=document.querySelector('#fit-api .section-title p');if(apiNote)apiNote.textContent='统一使用 ERP 对账管理中的积加认证;本页同时维护 FIT 与 NTE 订单接口配置。';
return true;
}
function open(id){document.querySelectorAll('.section').forEach(x=>x.classList.remove('active'));const el=document.getElementById(id);if(el){el.style.display='';el.classList.add('active');}document.querySelectorAll('.nav,.navchild,.navgrandchild').forEach(x=>x.classList.remove('active'));document.querySelector('[data-s="'+id+'"]')?.classList.add('active');if(window.title){title.innerText=id==='fit-order-import-map'?'积加订单字段映射':'积加订单导入';desc.innerText='FIT';}if(id==='fit-order-import-map')fitOrderImportOpenMappings();else fitOrderImportLoad();}
function fitMappingRow(m={}){return `
| | | | | | |
`;}
function mappingCustomer(){return String(document.getElementById('fitOiMapCustomer')?.value||'').trim();}
window.fitOrderImportLoadMappingCustomers=async function(){const input=document.getElementById('fitOiMapCustomer'),options=document.getElementById('fitOiMapCustomerOptions');if(!input||!options)return;const current=mappingCustomer()||'NTE.COM';const d=await apiGet('/api/fit/order-import/mapping-customers');options.innerHTML=(d.customers||[]).map(customer=>'').join('');input.value=current;};
window.fitOrderImportOpenMappings=async function(){try{await fitOrderImportLoadMappingCustomers();await fitOrderImportLoadMappings();}catch(e){toast('加载积加字段映射失败:'+e.message)}};
window.fitOrderImportLoadMappings=async function(){const customer=mappingCustomer();if(!customer)return toast('请先选择或输入客户');try{const d=await apiGet('/api/fit/order-import/mappings?customer='+encodeURIComponent(customer));const input=document.getElementById('fitOiMapCustomer'),tb=document.getElementById('fitOiMapTb');if(input)input.value=d.customer||customer;if(!tb)return;tb.innerHTML=(d.mappings||[]).map(fitMappingRow).join('')||'暂无字段规则 |
';}catch(e){toast('加载积加字段映射失败:'+e.message)}};
window.fitOrderImportAddMapping=function(){const tb=document.getElementById('fitOiMapTb');if(!tb)return;if(tb.querySelector('.empty'))tb.innerHTML='';tb.insertAdjacentHTML('beforeend',fitMappingRow({field_scope:'entry',value_type:'source',enabled:1}));};
window.fitOrderImportSaveMappings=async function(){const customer=mappingCustomer();if(!customer)return toast('请先选择或输入客户');const mappings=[...document.querySelectorAll('#fitOiMapTb tr')].map(tr=>{const type=tr.querySelector('[data-fit-map-type]')?.value||'source';const value=tr.querySelector('[data-fit-map-value]')?.value.trim()||'';return{target_key:tr.querySelector('[data-fit-map-key]')?.value.trim()||'',target_name:tr.querySelector('[data-fit-map-name]')?.value.trim()||'',field_scope:tr.querySelector('[data-fit-map-scope]')?.value||'entry',value_type:type,source_col:type==='source'?value:'',const_value:type==='const'?value:'',enabled:tr.querySelector('[data-fit-map-enabled]')?.checked?1:0};}).filter(x=>x.target_key);try{const r=await apiPost('/api/fit/order-import/mappings',{customer,mappings});toast((r.customer||customer)+' 的积加订单字段映射已保存,共 '+(r.saved||0)+' 条');await fitOrderImportLoadMappingCustomers();await fitOrderImportLoadMappings();}catch(e){toast('保存积加字段映射失败:'+e.message)}};
function init(){if(!install()){setTimeout(init,300);return;}const y=document.getElementById('fitOiYear'),m=document.getElementById('fitOiMonth'),now=new Date(),currentYear=now.getFullYear(),currentMonth=now.getMonth()+1;if(y&&!y.options.length){y.insertAdjacentHTML('beforeend','');for(let i=currentYear-3;i<=currentYear+1;i++)y.insertAdjacentHTML('beforeend',``);y.value=String(currentYear);}if(m&&!m.options.length){m.insertAdjacentHTML('beforeend','');for(let i=1;i<=12;i++)m.insertAdjacentHTML('beforeend',``);m.value=String(currentMonth);}if(window.applyNavPermissions&&!window._fitOiPermissionWrapped){const old=window.applyNavPermissions;window.applyNavPermissions=function(){old();const importVisible=typeof hasResource!=='function'||hasResource('fit.order_import');const mappingVisible=typeof hasResource!=='function'||hasResource('fit.order_import_mapping');const n=document.querySelector('[data-s="fit-order-import"]');const map=document.querySelector('[data-s="fit-order-import-map"]');if(n)n.style.display=importVisible?'':'none';if(map)map.style.display=mappingVisible?'':'none';const s=document.getElementById('fit-order-import');const ms=document.getElementById('fit-order-import-map');if(s&&!importVisible)s.classList.remove('active');if(ms&&!mappingVisible)ms.classList.remove('active');document.querySelectorAll('#fit-order-import [data-resource-action],#fit-order-import-map [data-resource-action]').forEach(b=>{b.style.display=typeof hasOperateResource!=='function'||hasOperateResource(b.dataset.resourceAction)?'':'none';});};window._fitOiPermissionWrapped=true;window.applyNavPermissions();}}
function readFile(file){return new Promise((resolve,reject)=>{const rd=new FileReader();rd.onload=e=>{try{const wb=XLSX.read(new Uint8Array(e.target.result),{type:'array',cellDates:false});let best=[];for(const name of wb.SheetNames){const matrix=XLSX.utils.sheet_to_json(wb.Sheets[name],{header:1,defval:''});let hi=matrix.findIndex(r=>r.some(v=>String(v).trim()==='PO Number'));if(hi<0)hi=0;const headers=(matrix[hi]||[]).map(v=>String(v).trim());const rows=matrix.slice(hi+1).map(arr=>{const o={};headers.forEach((h,i)=>{if(h)o[h]=arr[i]??''});return o}).filter(o=>Object.values(o).some(v=>String(v).trim()!==''));if(rows.length>best.length)best=rows;}resolve(best)}catch(err){reject(err)}};rd.onerror=()=>reject(new Error('文件读取失败'));rd.readAsArrayBuffer(file)})}
window.fitOrderImportFileHint=function(){const e=document.getElementById('fitOiFiles'),h=document.getElementById('fitOiFileHint');if(h)h.textContent=e?.files?.length?'已选择 '+e.files.length+' 个文件,请点击导入订单。':'选择后不会自动导入,请点击导入订单。';};
window.fitOrderImportFiles=async function(){const input=document.getElementById('fitOiFiles'),files=[...(input?.files||[])];if(!files.length)return toast('请选择 Excel 文件');for(const file of files){let rows;try{rows=await readFile(file);if(!rows.length)throw new Error('文件没有有效行');const payload={filename:file.name,year:Number(document.getElementById('fitOiYear').value),month:Number(document.getElementById('fitOiMonth').value),rows};try{const result=await apiPost('/api/fit/order-import/import',payload);toast(file.name+' 导入成功:'+(result.order_count||1)+' 张订单,'+(result.imported||0)+' 条明细')}catch(first){if(String(first.message).includes('已存在')||String(first.message).includes('覆盖')||String(first.message).includes('already exists')){payload.overwrite_confirmed=true;const result=await apiPost('/api/fit/order-import/import',payload);toast(file.name+' 已覆盖导入:'+(result.order_count||1)+' 张订单')}else throw first}}catch(e){toast('导入失败:'+e.message)}}input.value='';fitOrderImportFileHint();fitOrderImportLoad();};
window.fitOrderImportLoad=async function(){try{const year=document.getElementById('fitOiYear')?.value||'',month=document.getElementById('fitOiMonth')?.value||'',status=document.getElementById('fitOiStatus')?.value||'all',params={push_status:status,page:state.page,page_size:state.size};if(year)params.year=year;if(month)params.month=month;const d=await apiGet('/api/fit/order-import/files?'+new URLSearchParams(params));state.rows=d.rows||[];const tb=document.getElementById('fitOiTb');if(!tb)return;tb.innerHTML=state.rows.map(r=>` | ${esc(r.customer)} | ${esc(r.po_date)} | ${esc(r.po_number)} | ${Number(r.record_count||0)} | ${Number(r.total_qty||0)} | ${money(r.total_amount)} | ${pushStatusHtml(r.push_status)} | ${esc(r.kingdee_bill_no||'')} | ${pushMessageHtml(r.push_message)} | |
`).join('')||'暂无积加订单,请先导入 |
';document.getElementById('fitOiCheckAll').checked=false;document.getElementById('fitOiPageInfo').textContent='共 '+d.total+' 个文件';if(window.applyNavPermissions)window.applyNavPermissions();}catch(e){toast('加载积加订单失败:'+e.message)}};
window.fitOrderImportRefresh=async function(){const failedIds=state.rows.filter(row=>['failed','error'].includes(String(row.push_status||'').toLowerCase())).map(row=>Number(row.id)).filter(Boolean);try{let cleared=0;if(failedIds.length){const result=await apiPost('/api/fit/order-import/clear-failed-push-messages',{ids:failedIds});cleared=Number(result.cleared||0);}await fitOrderImportLoad();toast(cleared?'列表已刷新,已清除 '+cleared+' 条失败推送信息并恢复为待推送':'列表已刷新,当前没有失败信息');}catch(e){toast('刷新列表失败:'+e.message)}};
window.fitOrderImportToggleAll=function(){const checked=document.getElementById('fitOiCheckAll')?.checked;document.querySelectorAll('.fitOiCb:not(:disabled)').forEach(x=>x.checked=checked)};
function ids(){return [...document.querySelectorAll('.fitOiCb:checked')].map(x=>Number(x.value))}
window.fitOrderImportPush=async function(){const selected=ids();if(!selected.length)return toast('请先勾选待推送订单');try{const r=await apiPost('/api/fit/order-import/push',{ids:selected});toast('推送完成:成功 '+(r.success||0)+',失败 '+(r.failed||0));fitOrderImportLoad()}catch(e){toast('推送失败:'+e.message)}};
window.fitOrderImportPushOne=async function(id){try{const r=await apiPost('/api/fit/order-import/push',{ids:[Number(id)]});const detail=(r.details||[])[0]||{};toast(detail.message||('推送完成:成功 '+(r.success||0)+',失败 '+(r.failed||0)));fitOrderImportLoad()}catch(e){toast('推送失败:'+e.message)}};
window.fitOrderImportDelete=async function(){const selected=ids();if(!selected.length)return toast('请先勾选订单');try{await apiDelete('/api/fit/order-import/files',{ids:selected});toast('已删除');fitOrderImportLoad()}catch(e){toast('删除失败:'+e.message)}};
window.fitOrderImportDetail=async function(id){try{const d=await apiGet('/api/fit/order-import/records?file_id='+id+'&page_size=500');const cols=[['PO Number','订单编号'],['PO Date','订单日期'],['Qty Ordered','销售数量'],['Unit Price','商品单价'],['Vendor Style','MSKU'],['Product/Item Description','商品标题'],['Ship To Name','收件人姓名'],['Ship To Address 1','收件人(详细地址)'],['Ship To City','收件人(城市)'],['Ship To State','*收件人(省/州)'],['Ship to Zip','收件人邮编'],['Ship To Contact','收件电话'],['PO Total Amount','商品总额']];const body=(d.rows||[]).map(r=>''+cols.map(c=>'| '+esc(r[c[0]]??'')+' | ').join('')+'
').join('')||'| 暂无明细 |
';const html=''+cols.map(c=>'| '+esc(c[1])+' | ').join('')+'
'+body+'
';if(window.openSimpleModal)openSimpleModal('积加订单明细',html,'');else alert('明细已加载');}catch(e){toast('加载明细失败:'+e.message)}};
const oldEnsure=window.ensureFitUi;if(oldEnsure&&!window._fitOiEnsureWrapped){window.ensureFitUi=function(){const r=oldEnsure.apply(this,arguments);install();return r};window._fitOiEnsureWrapped=true;}const oldOpen=window.openFitSection;if(oldOpen&&!window._fitOiOpenWrapped){window.openFitSection=function(id){if(id==='fit-order-import'||id==='fit-order-import-map'){open(id);return}return oldOpen.apply(this,arguments)};window._fitOiOpenWrapped=true;}init();
})();