import{api as u}from"./common-DEIQtiPI.js";import"./index-DOFLUERq.js";async function m(a){if(!a)return"CNY";try{return(await u.call("jingrow.client.get_value",{pagetype:"Company",filters:{name:a},fieldname:"default_currency"}))?.message?.default_currency||"CNY"}catch{return"CNY"}}function d(a){async function p(e,r){const t=e[a.priceListField];if(!t)return;const s=e.items&&e.items.length>0,l={items:s?e.items.map(n=>({pagetype:n.pagetype,name:n.name,item_code:n.item_code,item_group:n.item_group,brand:n.brand,qty:n.qty||1,uom:n.uom,warehouse:n.warehouse,conversion_factor:n.conversion_factor||1})):[],customer:e.customer,supplier:e.supplier,currency:e.currency,conversion_rate:e.conversion_rate,price_list:t,price_list_currency:e.price_list_currency,plc_conversion_rate:e.plc_conversion_rate,company:e.company,transaction_date:e.transaction_date||e.posting_date,pagetype:r,name:e.name};try{const n=await u.call("jerp.stock.get_item_details.apply_price_list",{args:l,pg:e});if(n?.message){const c=n.message.parent;c&&(c.price_list_currency&&(e.price_list_currency=c.price_list_currency),c.plc_conversion_rate&&(e.plc_conversion_rate=c.plc_conversion_rate));const o=n.message.children;o&&s&&o.forEach((i,y)=>{if(e.items[y]&&i){const _=e.items[y];i.price_list_rate!==void 0&&(_.price_list_rate=i.price_list_rate),i.discount_percentage!==void 0&&(_.discount_percentage=i.discount_percentage),i.rate!==void 0&&(_.rate=i.rate),i.amount!==void 0&&(_.amount=i.amount)}})}}catch(n){console.error("[priceList plugin] apply_price_list failed:",n)}}async function g(e){const{value:r,record:t,pagetype:s}=e;if(!r)return;const l=t.transaction_date||t.posting_date,n=await m(t.company);if(r===n){t.conversion_rate=1,t.price_list_currency===r&&(t.plc_conversion_rate=1),await p(t,s);return}try{const c=await u.call("jerp.setup.utils.get_exchange_rate",{transaction_date:l,from_currency:r,to_currency:n,args:a.exchangeArgs||"for_selling"}),o=Number(c?.message)||1;t.conversion_rate=o,t.price_list_currency===r&&(t.plc_conversion_rate=o),await p(t,s)}catch(c){console.error("[priceList plugin] Failed to fetch exchange rate:",c)}}async function f(e){const{record:r,pagetype:t}=e;r.plc_conversion_rate=null,await p(r,t)}return[{fieldname:"currency",handler:g},{fieldname:a.priceListField,handler:f}]}export{d as createPriceListPlugin};
