U8ThirdPartyService.php 54 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297
  1. <?php
  2. namespace App\Service;
  3. use Illuminate\Support\Facades\Cache;
  4. use Illuminate\Support\Facades\Log;
  5. class U8ThirdPartyService extends Service
  6. {
  7. const one = 1;
  8. const two = 2;
  9. const three = 3;
  10. const four = 4;
  11. const five = 5;
  12. const six = 6;
  13. const seven = 7;
  14. const eight = 8;
  15. const type_all = [
  16. self::one => '采购入库',
  17. self::two => '采购退货',
  18. self::three => '材料出库',
  19. self::four => '销售出库',
  20. self::five => '产成品入库',
  21. self::six => '销售退货',
  22. self::seven => '其他入',
  23. self::eight => '其他出',
  24. ];
  25. public function settleU8Data($data){
  26. if(empty($data['type'])) return [false, 'type类型不能为空'];
  27. if(! isset(self::type_all[$data['type']])) return [false, 'type类型错误'];
  28. $type = $data['type'];
  29. list($status, $msg) = $this->getToken();
  30. if(! $status) return [false, $msg];
  31. $data['u8_data'] = $msg;
  32. if($type == self::one){
  33. list($status, $msg) = $this->purchaseIn($data);
  34. }elseif ($type == self::two){
  35. list($status, $msg) = $this->purchaseReturn($data);
  36. }elseif ($type == self::three){
  37. list($status, $msg) = $this->materialOut($data);
  38. }elseif ($type == self::four){
  39. list($status, $msg) = $this->saleOut($data);
  40. }elseif ($type == self::five){
  41. list($status, $msg) = $this->productIn($data);
  42. }elseif ($type == self::six){
  43. list($status, $msg) = $this->saleReturn($data);
  44. }elseif ($type == self::seven){
  45. list($status, $msg) = $this->otherIn($data);
  46. }elseif ($type == self::eight){
  47. list($status, $msg) = $this->otherOut($data);
  48. }
  49. return [$status, $msg];
  50. }
  51. public function getToken(){
  52. $key = "drb_u8_api" . env('SQLSRV_DATABASE');
  53. $config = config('wms.drb');
  54. // 1. 自检网络通畅
  55. list($bool, $msg) = $this->checkNetworkStatus($config['api_host'], $config['api_port']);
  56. if (!$bool) return [false, "网络连接失败: " . $msg];
  57. $host = $config['api_host'] . ":" . $config['api_port'];
  58. // 2. 尝试从缓存获取
  59. $token = Cache::get($key);
  60. if (! $token) {
  61. // 3. 缓存失效,请求新 Token
  62. $url = $host . "/api/System/GetToken";
  63. $date = date("Y-m-d");
  64. $json = [
  65. "U8DbName" => $config['database'],
  66. "sUserId" => $config['user_id'],
  67. "sPassword" => $config['user_password'],
  68. "LoginDateTime" => $date,
  69. "bPersist" => true
  70. ];
  71. $header = ['Content-Type:application/json'];
  72. // 调用你的 POST 辅助函数
  73. list($status, $result) = $this->post_helper1($url, json_encode($json), $header);
  74. if (!$status) return [false, "用友token获取失败: " . $result];
  75. if (!isset($result['code'])) return [false, '获取用友登录信息失败: 响应格式异常'];
  76. if ($result['code'] != 0) return [false, "U8错误: " . ($result['msg'] ?? '未知错误')];
  77. $token = $result['data']['Token'] ?? "";
  78. if (empty($token)) return [false, "接口返回的 Token 为空"];
  79. // 30分钟 = 1800秒
  80. Cache::put($key, $token, now()->addMinutes(30));
  81. }
  82. return [true, ['host' => $host, 'token' => $token]];
  83. }
  84. /**
  85. * 采购到货单拆行/更新处理
  86. */
  87. public function purchaseIn($data)
  88. {
  89. if (empty($data['orderId'])) return [false, '采购到货单ID不能为空'];
  90. if (empty($data['orderNo'])) return [false, '采购到货单单号不能为空'];
  91. if (empty($data['detail'])) return [false, '表体信息detail不能为空'];
  92. // 1. 获取到货单明细
  93. $service = new U8ThirtyPartyDatabaseServerService();
  94. list($status, $result) = $service->getCGDHDetails($data['orderId']);
  95. if (! $status) return [false, $result];
  96. // 取出第一行作为模板,保留 ID, cCode 等主表关联信息
  97. $templateRow = reset($result);
  98. $mainId = $templateRow['ID'];
  99. // 2. 存货管控校验(批次/保质期)
  100. // list($status, $msg) = $service->checkInventoryControl(array_column($data['detail'], 'materialCode'));
  101. // if (!$status) return [false, $msg];
  102. $insertData = [];
  103. $rowNo = 1;
  104. foreach ($data['detail'] as $value) {
  105. if (!isset($result[$value['materialCode']])) continue;
  106. $map = $result[$value['materialCode']]; // 获取原始行信息(单价、税率等)
  107. // 计算单价
  108. $oldQty = (float)($map['iQuantity'] ?? 0);
  109. if ($oldQty <= 0) continue;
  110. $unitPrice = (float)$map['iOriSum'] / $oldQty;
  111. $unitMoney = (float)$map['iOriMoney'] / $oldQty;
  112. $unitLocalSum = (float)$map['iSum'] / $oldQty;
  113. $unitLocalMoney = (float)$map['iMoney'] / $oldQty;
  114. $newQty = (float)$value['iQuantity'];
  115. // 组织新行数据
  116. $newRow = $map;
  117. // 清理旧行主键和业务累积状态(关键!)
  118. unset($newRow['Autoid']);
  119. $newRow['fInspectQuantity'] = 0; // 已报检量清零
  120. $newRow['fValidQuantity'] = 0; // 合格量清零
  121. $newRow['iQuantity'] = $newQty;
  122. $newRow['ivouchrowno'] = $rowNo++; // 重新排序行号
  123. // 填充计算后的金额和批次日期
  124. $newRow['iOriMoney'] = round($unitMoney * $newQty, 2);
  125. $newRow['iOriSum'] = round($unitPrice * $newQty, 2);
  126. $newRow['iOriTaxPrice'] = round(($unitPrice - $unitMoney) * $newQty, 2);
  127. $newRow['iMoney'] = round($unitLocalMoney * $newQty, 2);
  128. $newRow['iSum'] = round($unitLocalSum * $newQty, 2);
  129. $newRow['iTaxPrice'] = round(($unitLocalSum - $unitLocalMoney) * $newQty, 2);
  130. $newRow['cBatch'] = $value['lot'] ?? null;
  131. $newRow['dPDate'] = !empty($value['productDate']) ? $this->formatAndValidateDate($value['productDate']) : null;
  132. $newRow['dVDate'] = !empty($value['failureDate']) ? $this->formatAndValidateDate($value['failureDate']) : null;
  133. $insertData[] = $newRow;
  134. }
  135. // 3. 执行数据库操作:先删后插
  136. list($status, $msg) = $service->rebuildDhDetails($mainId, $insertData);
  137. if (!$status) return [false, $msg];
  138. //查询采购到货单
  139. list($status, $order) = $service->getCgOrder($data['orderId']);
  140. if(! $status) return [false, $order];
  141. //生成来料报检单
  142. $inspect = [
  143. "Inum" => "ArrInspect",
  144. "Data" => [
  145. "iHead" => [
  146. // 注意:这里使用的是主表的 ID
  147. "CSOURCEID" => $order['ID'],
  148. "CDEPCODE" => $order['cDepCode'],
  149. "DDATE" => date("Y-m-d"),
  150. "CCHECKTYPECODE" => 'ARR',
  151. ],
  152. "iBody" => []
  153. ]
  154. ];
  155. foreach ($order['details'] as $item) {
  156. $qty = (float)($item['iQuantity'] ?? 0);
  157. if ($qty <= 0) continue;
  158. $inspect["Data"]["iBody"][] = [
  159. "SOURCEAUTOID" => $item['Autoid'],
  160. "ITESTSTYLE" => 0,
  161. "CINVCODE" => $item['cInvCode'],
  162. "FCHANGRATE" => (float)($item['iInvExchRate'] ?? 0),
  163. "FQUANTITY" => $qty,
  164. "CBATCH" => $item['cBatch'],
  165. 'DPRODATE' => $item['dPDate'],
  166. 'DVDATE' => $item['dVDate'],
  167. 'cFree1' => $item['cFree1'],
  168. 'cFree2' => $item['cFree2'],
  169. ];
  170. }
  171. // 4. 封装成数组返回
  172. $final_data = [$inspect];
  173. //调用所需
  174. $host = $data['u8_data']['host'];
  175. $token = $data['u8_data']['token'];
  176. //报检单
  177. $header = ["Authorization: {$token}",'Content-Type:application/json'];
  178. $url = $host . "/api/QmArr/ArrInspectAdd";
  179. $json = json_encode($final_data);
  180. list($status, $result) = $this->post_helper1($url,$json, $header, 30);
  181. if(! $status) return [false, $result];
  182. if(! isset($result['code'])) return [false, '报检单生成失败'];
  183. if($result['code'] != 0) return [false, $result['msg']];
  184. return [true, ''];
  185. }
  186. public function materialOut($data)
  187. {
  188. if (empty($data['orderId'])) return [false, '领料申请单ID不能为空'];
  189. if (empty($data['orderNo'])) return [false, '领料申请单单号不能为空'];
  190. if (empty($data['warehouseCode'])) return [false, '仓库不能为空'];
  191. if (empty($data['detail'])) return [false, '表体信息detail不能为空'];
  192. // 1. 获取领料申请单明细
  193. $service = new U8ThirtyPartyDatabaseServerService();
  194. list($status, $result) = $service->getLlSQDetails($data['orderId']);
  195. if (! $status) return [false, $result];
  196. if(empty($result)) return [false, '领料申请单不存在'];
  197. // 取出第一行作为模板,获取主表 ID
  198. $templateRow = reset($result);
  199. $mainId = $templateRow['ID'];
  200. // 2. 存货管控校验(批次/保质期)
  201. // list($status, $msg) = $service->checkInventoryControl(array_column($data['detail'], 'materialCode'));
  202. // if (!$status) return [false, $msg];
  203. $insertData = [];
  204. $rowNo = 1;
  205. foreach ($data['detail'] as $value) {
  206. if (!isset($result[$value['materialCode']])) continue;
  207. // 获取原始行(保留生产订单关联 morderdid、仓库 cwhcode 等信息)
  208. $map = $result[$value['materialCode']];
  209. $newQty = (float)$value['iQuantity'];
  210. // 组织新行数据
  211. $newRow = $map;
  212. // 清理主键
  213. unset($newRow['AutoID']);
  214. $newRow['iQuantity'] = $newQty; // 申请数量
  215. $newRow['irowno'] = $rowNo++; // 重新排序行号
  216. $newRow['cBatch'] = $value['lot'] ?? null; // 批号
  217. // 生产日期与失效日期 (U8 领料申请单通常字段名为 dMadeDate 和 dVDate 或 dmadedate)
  218. $newRow['dMadeDate'] = !empty($value['productDate']) ? $this->formatAndValidateDate($value['productDate']) : null;
  219. $newRow['dVDate'] = !empty($value['failureDate']) ? $this->formatAndValidateDate($value['failureDate']) : null;
  220. $insertData[] = $newRow;
  221. }
  222. // 3. 执行数据库操作:先删后插
  223. list($status, $msg) = $service->rebuildLLDetails($mainId, $insertData);
  224. if (!$status) return [false, $msg];
  225. //查询领料申请单
  226. list($status, $order) = $service->getLLOrder($data['orderId']);
  227. if(!$status) return [false, '领料单不存在'];
  228. //仓库区分出入库类别
  229. if($data['warehouseCode'] == "01"){
  230. $cRdCode = "0201";
  231. }else{
  232. $cRdCode = "0203";
  233. }
  234. $materialOut = [
  235. "Inum" => "MaterialOut",
  236. "Data" => [
  237. "iHead" => [
  238. "IsVerify" => true,
  239. "cWhCode" => $data['warehouseCode'], // 仓库
  240. "cVouchType" => "11",
  241. "cRdCode" => $cRdCode, // 出入库类别
  242. "cDepCode" => $order['cDepCode'], // 领用部门
  243. "cSource" => "领料申请单",
  244. "cBusCode" => $order['cCode'], // 领料申请单单号
  245. "cBusType" => "领料",
  246. "cMemo" => "接口生成",
  247. "dDate" => date("Y-m-d"),
  248. ],
  249. "iBody" => []
  250. ]
  251. ];
  252. foreach ($order['details'] as $index => $item) {
  253. // 这里的数量取值要对应你 getLLOrder 查出来的字段名,通常是 fQty
  254. $qty = $item['iQuantity'];
  255. if ($qty <= 0) continue;
  256. $materialOut["Data"]["iBody"][] = [
  257. "iRowNo" => $index + 1,
  258. "cInvCode" => $item['cInvCode'],
  259. "cBatch" => $item['cBatch'] ?? null, // 批号
  260. "iQuantity" => $qty, // 实际出库数量
  261. "iNQuantity" => $qty, // 实收数量
  262. "iinvexchrate" => (float)($item['iinvexchrate'] ?? 1),
  263. "iMaIDs" => $item['AutoID'],
  264. "dMadeDate" => $item['dMadeDate'] ?? null, // 生产日期
  265. "dVDate" => $item['dVDate'] ?? null, // 失效日期
  266. 'cFree1' => $item['cFree1'],
  267. 'cFree2' => $item['cFree2'],
  268. ];
  269. }
  270. // 封装成数组返回
  271. $final_data = [$materialOut];
  272. //调用所需
  273. $host = $data['u8_data']['host'];
  274. $token = $data['u8_data']['token'];
  275. //材料出库单
  276. $header = ["Authorization: {$token}",'Content-Type:application/json'];
  277. $url = $host . "/api/MaterialOut/Add";
  278. $json = json_encode($final_data);
  279. list($status, $result) = $this->post_helper1($url,$json, $header, 30);
  280. if(! $status) return [false, $result];
  281. if(! isset($result['code'])) return [false, '材料出库单生成失败'];
  282. if($result['code'] != 0) return [false, $result['msg']];
  283. return [true, ''];
  284. }
  285. public function purchaseReturn($data){
  286. if(empty($data['orderId'])) return [false, '采购退货单ID不能为空'];
  287. // 1. 获取到货单(退货单)及明细
  288. $service = new U8ThirtyPartyDatabaseServerService();
  289. list($status, $order) = $service->getArrivalVouchById($data['orderId']);
  290. if(! $status) return [false, $order];
  291. // 获取 Token 相关信息
  292. $host = $data['u8_data']['host'] ?? "";
  293. $token = $data['u8_data']['token'] ?? "";
  294. // 2. 组织单一仓库的红字采购入库单
  295. $iBody = [];
  296. foreach ($order['details'] as $index => $item) {
  297. // 强制转为负数,生成红字入库单
  298. $qty = abs((float)$item['iQuantity']) * -1;
  299. $iBody[] = [
  300. "iRowNo" => $index + 1,
  301. "cInvCode" => $item['cInvCode'],
  302. "cBatch" => $item['cBatch'] ?? '',
  303. "iinvexchrate" => (float)($item['iinvexchrate'] ?? 1),
  304. "iQuantity" => $qty, // 负数
  305. "iNQuantity" => $qty, // 负数
  306. "iArrsId" => $item['iArrsId'],
  307. "dMadeDate" => $item['dPDate'],
  308. "dVDate" => $item['dVDate'],
  309. "iTaxRate" => $item['iTaxRate'] ?? 0,
  310. "iTaxUnitPrice"=> $item['iOriTaxCost'] ?? 0,
  311. 'cFree1' => $item['cFree1'],
  312. 'cFree2' => $item['cFree2'],
  313. ];
  314. }
  315. if(empty($iBody)) return [false, '表体明细为空'];
  316. $final_data = [
  317. [
  318. "Inum" => "PurchaseIn",
  319. "Data" => [
  320. "iHead" => [
  321. "IsVerify" => true,
  322. "bIsRedVouch" => true, // 必须为红字
  323. "bCalPrice" => true, // 自动计算金额
  324. "cWhCode" => "01",
  325. "cRdCode" => $order['rd_code'],
  326. "cDepCode" => $order['depart_code'],
  327. "cARVCode" => $order['no'], // 关联来源单号
  328. "cSource" => "采购到货单", // 即使是退货单,参照来源也写这个
  329. "cBusType" => "普通采购",
  330. "cMemo" => "接口生成",
  331. "dDate" => date("Y-m-d"),
  332. "iExchRate"=> 1,
  333. ],
  334. "iBody" => $iBody
  335. ]
  336. ]
  337. ];
  338. // 3. 调用 API
  339. $header = ["Authorization: {$token}", 'Content-Type:application/json'];
  340. $url = $host . "/api/PurchaseIn/Add";
  341. $json = json_encode($final_data);
  342. list($status, $result) = $this->post_helper1($url, $json, $header, 30);
  343. if(! $status) return [false, $result];
  344. if(! isset($result['code'])) return [false, '红字采购入库单生成失败'];
  345. if($result['code'] != 0) return [false, $result['msg']];
  346. return [true, ''];
  347. }
  348. public function productIn($data){
  349. if(empty($data['orderId'])) return [false, '产品报检单ID不能为空'];
  350. if(empty($data['orderNo'])) return [false, '产品报检单单号不能为空'];
  351. if(empty($data['detail'])) return [false, '表体信息detail不能为空'];
  352. // 1. 获取报检单明细 (建议 getBjOrder 返回以 cInvCode 为 key 的数组)
  353. $service = new U8ThirtyPartyDatabaseServerService();
  354. list($status,$result) = $service->getBjOrder($data['orderId']);
  355. if (! $status) return [false, $result];
  356. // 取出第一行作为模板,获取主表 ID
  357. $templateRow = reset($result);
  358. $mainId = $templateRow['ID'];
  359. // 2. 存货管控校验(批次/保质期)
  360. // list($status, $msg) = $service->checkInventoryControl(array_column($data['detail'], 'materialCode'));
  361. // if (!$status) return [false, $msg];
  362. $insertData = [];
  363. $rowNo = 1;
  364. foreach ($data['detail'] as $value) {
  365. if (!isset($result[$value['materialCode']])) continue;
  366. // 获取原始行(保留来源单据关联,如采购到货单行 AutoID 等)
  367. $map = $result[$value['materialCode']];
  368. $newQty = (float)$value['iQuantity'];
  369. // 组织新行数据
  370. $newRow = $map;
  371. // 清理子表主键
  372. unset($newRow['AUTOID']);
  373. // --- 核心字段修正 (报检单子表字段通常为大写) ---
  374. $newRow['FQUANTITY'] = $newQty; // 报检数量
  375. $newRow['CBATCH'] = $value['lot'] ?? null; // 批号
  376. // 报检单的日期字段通常是 DPRODATE (生产日期) 和 DVDATE (失效日期)
  377. $newRow['DPRODATE'] = !empty($value['productDate']) ? $this->formatAndValidateDate($value['productDate']) : null;
  378. $newRow['DVDATE'] = !empty($value['failureDate']) ? $this->formatAndValidateDate($value['failureDate']) : null;
  379. $insertData[] = $newRow;
  380. }
  381. // 3. 执行数据库操作:先删后插
  382. list($status, $msg) = $service->rebuildBjDetails($mainId, $insertData);
  383. if (!$status) return [false, $msg];
  384. // $service = new U8ThirtyPartyDatabaseServerService();
  385. // $result = $service->getBjOrder($data['orderId']);
  386. //
  387. // $tmp = $update = $insert = [];
  388. // foreach ($data['detail'] as $key => $value) {
  389. // if(empty($value['lineNum'])) return [false, '行号不能为空'];
  390. // if(! is_numeric($value['lineNum'])) return [false, '行号错误'];
  391. // if(empty($value['materialCode'])) return [false, '存货编码不能为空'];
  392. // if(empty($value['productDate'])) return [false, '生产日期不能为空'];
  393. // $return = $this->formatAndValidateDate($value['productDate']);
  394. // if(! $return) return [false, '生产日期格式错误'];
  395. // $productDate = $return;
  396. // if(empty($value['failureDate'])) return [false, '失效日期不能为空'];
  397. // $return = $this->formatAndValidateDate($value['failureDate']);
  398. // if(! $return) return [false, '生产日期格式错误'];
  399. // $failureDate= $return;
  400. // if(empty($value['lot'])) return [false, '批号不能为空'];
  401. // if(empty($value['iQuantity']) || ! is_numeric($value['iQuantity'])) return [false, '存货数量错误'];
  402. //
  403. // if(isset($result[$value['materialCode']])){
  404. // $map = $result[$value['materialCode']];
  405. // $update_detail = [
  406. // 'CBATCH' => $value['lot'],
  407. // 'FQUANTITY' => $value['iQuantity'],
  408. // 'DPRODATE' => $productDate,
  409. // 'DVDATE' => $failureDate,
  410. // ];
  411. // if(! isset($tmp[$value['materialCode']])){
  412. // $update[$map['AUTOID']] = $update_detail;
  413. // $tmp[$value['materialCode']] = $value['materialCode'];
  414. // }else{
  415. // $map['AUTOID'] = null;
  416. // $insert[] = array_merge($map, $update_detail);
  417. // }
  418. // }
  419. // }
  420. //
  421. // list($status,$msg) = $service->checkInventoryControl(array_values(array_column($data['detail'],'materialCode')));
  422. // if(! $status) return [false, $msg];
  423. //
  424. // list($status, $msg) = $service->updateBjOrder($update, $insert);
  425. // if(! $status) return [false, $msg];
  426. return [true, ''];
  427. }
  428. public function saleOut($data){
  429. if(empty($data['orderId'])) return [false, '销售订单ID不能为空'];
  430. if(empty($data['orderNo'])) return [false, '销售订单号不能为空'];
  431. if(empty($data['detail'])) return [false, '表体信息detail不能为空'];
  432. //获取销售订单信息
  433. $service = new U8ThirtyPartyDatabaseServerService();
  434. list($status,$order) = $service->getXsOrder($data['orderId']);
  435. if(! $status) return [false, $order];
  436. $detail_map = [];
  437. foreach ($data['detail'] as $key => $value) {
  438. if(empty($value['lineNum'])) return [false, '行号不能为空'];
  439. if(! is_numeric($value['lineNum'])) return [false, '行号错误'];
  440. if(empty($value['materialCode'])) return [false, '存货编码不能为空'];
  441. // if(empty($value['productDate'])) return [false, '生产日期不能为空'];
  442. // $return = $this->formatAndValidateDate($value['productDate']);
  443. // if(! $return) return [false, '生产日期格式错误'];
  444. // $productDate = $return;
  445. if(! empty($value['failureDate'])) {
  446. $return = $this->formatAndValidateDate($value['failureDate']);
  447. if(! $return) return [false, '失效日期格式错误'];
  448. $failureDate= $return;
  449. }
  450. // if(empty($value['lot'])) return [false, '批号不能为空'];
  451. if(empty($value['iQuantity']) || ! is_numeric($value['iQuantity'])) return [false, '存货数量错误'];
  452. $detail_map[$value['materialCode']][] = [
  453. // 'productDate' => $productDate,
  454. 'failureDate' => $failureDate ?? null,
  455. 'lot' => $value['lot'] ?? null,
  456. 'iQuantity' => $value['iQuantity'],
  457. ];
  458. }
  459. // 2. 组织发货单 (DispatchList) 结构
  460. $tmp = [
  461. "Inum" => "DispatchList",
  462. "Data" => [
  463. "iHead" => [
  464. "cVouchType" => "05",
  465. "cSTCode" => (string)($order['cSTCode'] ?? "02"), // 示例中是02
  466. "cDepCode" => (string)($order['cDepCode'] ?? "01"),
  467. "IsVerify" => true,
  468. "cMemo" => "接口生成",
  469. "dDate" => date("Y-m-d"),
  470. "cSoCode" => (string)$order['cSOCode'],
  471. "ccuscode" => (string)$order['cCusCode'],
  472. "cexch_name" => (string)($order['cexch_name'] ?? "人民币"),
  473. "iexchrate" => (float)($order['iExchRate'] ?? 1.0), // 强制转浮点,去掉引号
  474. "iTaxRate" => (float)($order['iTaxRate'] ?? 13.0), // 强制转浮点
  475. ],
  476. "iBody" => []
  477. ]
  478. ];
  479. // 3. 遍历销售订单明细组织表体
  480. $key = 0;
  481. foreach ($order['details'] as $item) {
  482. $p_t = $detail_map[$item['cInvCode']] ?? [];
  483. if (empty($p_t)) continue;
  484. foreach ($p_t as $value) {
  485. $key++;
  486. $qty = (float)$value['iQuantity'];
  487. $taxRate = (float)($item['iTaxRate'] ?? 13.0);
  488. $taxUnitPrice = (float)$item['iTaxUnitPrice']; // 含税单价 (如 100)
  489. // 价税合计 (iSum)
  490. $iSum = round($qty * $taxUnitPrice, 2);
  491. // 无税金额 (imoney) = 价税合计 / (1 + 税率/100)
  492. $iMoney = round($iSum / (1 + ($taxRate / 100)), 2);
  493. // 税额 (itax)
  494. $iTax = round($iSum - $iMoney, 2);
  495. // 无税单价 (iunitprice)
  496. $iUnitPrice = round($taxUnitPrice / (1 + ($taxRate / 100)), 10);
  497. $tmp["Data"]["iBody"][] = [
  498. "iRowNo" => (int)$key, // 强制转整型
  499. "cInvCode" => (string)$item['cInvCode'],
  500. "iTaxRate" => (float)$taxRate,
  501. "cGroupCode" => (string)($item['cGroupCode'] ?? "01"),
  502. "iGroupType" => "0",
  503. "cUnitID" => (string)($item['cUnitID'] ?? "003"),
  504. "cWhCode" => "06",
  505. "iQuantity" => (float)$qty,
  506. "iNum" => 0, // 辅计量数量
  507. "iSum" => (float)$iSum,
  508. "iInvExchRate" => 1.0, // 换算率,必填
  509. "imoney" => (float)$iMoney,
  510. "itax" => (float)$iTax,
  511. "idiscount" => 0,
  512. "inatmoney" => (float)$iMoney,
  513. "inattax" => (float)$iTax,
  514. "inatdiscount" => 0,
  515. "inatsum" => (float)$iSum,
  516. "itaxunitprice" => (float)$taxUnitPrice,
  517. "iunitprice" => (float)$iUnitPrice,
  518. "inatunitprice" => (float)$iUnitPrice,
  519. "dvDate" => $value['failureDate'], // 示例中只需失效日期
  520. // "dMDate" => (string)$value['productDate'],
  521. "iSOsID" => (int)$item['iSOsID'], // 强制转整型,去掉引号
  522. "cBatch" => $value['lot'],
  523. 'cFree1' => $item['cFree1'],
  524. 'cFree2' => $item['cFree2'],
  525. ];
  526. }
  527. }
  528. $final_data = [$tmp];
  529. //调用所需
  530. $host = $data['u8_data']['host'];
  531. $token = $data['u8_data']['token'];
  532. //销售发货单
  533. $header = ["Authorization: {$token}",'Content-Type:application/json'];
  534. $url = $host . "/api/Dispatch/Add";
  535. $json = json_encode($final_data);
  536. list($status, $result) = $this->post_helper1($url,$json, $header, 30);
  537. if(! $status) return [false, $result];
  538. if(! isset($result['code'])) return [false, '销售发货单生成失败'];
  539. if($result['code'] != 0) return [false, $result['msg']];
  540. $first = $result['data'][0];
  541. $id = $first['VouchId'];
  542. // $id = 1000000882;
  543. list($status, $fhOrder) = $service->getFhOrder($id);
  544. if(! $status) return [false, $fhOrder];
  545. // 2. 初始化销售出库单结构
  546. $saleOut = [
  547. "Inum" => "SaleOut",
  548. "Data" => [
  549. "iHead" => [
  550. "IsVerify" => true, // 自动审核
  551. "cWhCode" => "06", // 仓库编码
  552. "cRdCode" => "0299", // 出入库类别编码
  553. "cVouchType" => "32", // 单据类型编码
  554. "cMemo" => "接口生成",
  555. "cSource" => "发货单",
  556. "cSTCode" => $fhOrder['cSTCode'], // 销售类型
  557. "DLCode" => $fhOrder['cDLCode'], // 关联的发货单号
  558. "cDepCode" => $fhOrder['cDepCode'], // 部门
  559. "dDate" => date("Y-m-d"), // 出库日期
  560. ],
  561. "iBody" => []
  562. ]
  563. ];
  564. // 3. 遍历发货单明细组织表体
  565. foreach ($fhOrder['details'] as $index => $item) {
  566. // 计算待出库数量 (总发货数 - 已出库数)
  567. $qty = (float)($item['iQuantity'] ?? 0);
  568. $outQty = (float)($item['fOutQuantity'] ?? 0);
  569. $pendingQty = $qty - $outQty;
  570. // 如果该行已全部出库,则跳过(可选逻辑)
  571. if ($pendingQty <= 0) continue;
  572. $saleOut["Data"]["iBody"][] = [
  573. "iRowNo" => $index + 1,
  574. "cInvCode" => $item['cInvCode'] ?? "",
  575. "cPosition" => $item['cPosition'] ?? "", // 货位
  576. "cBatch" => $item['cBatch'] ?? "", // 批号
  577. "iinvexchrate" => (float)($item['iExchRate'] ?? 1), // 换算率
  578. "iQuantity" => $pendingQty, // 本次出库数量
  579. "iNQuantity" => $pendingQty, // 对应实收数量
  580. "iDLsID" => $item['iDLsID'], // 核心:发货单子表ID
  581. "dMadeDate" => $item['dMDate'], // 生产
  582. "dVDate" => $item['dvDate'], // 失效
  583. 'cFree1' => $item['cFree1'],
  584. 'cFree2' => $item['cFree2'],
  585. // "iUnitCost" => (float)($item['iUnitPrice'] ?? 0), // 无税单价
  586. // "iPrice" => round((float)($item['iUnitPrice'] ?? 0) * $pendingQty, 2), // 无税金额
  587. ];
  588. }
  589. // 4. 封装成数组
  590. $final_data = [$saleOut];
  591. $header = ["Authorization: {$token}",'Content-Type:application/json'];
  592. $url = $host . "/api/SaleOut/Add";
  593. $json = json_encode($final_data);
  594. list($status, $result) = $this->post_helper1($url,$json, $header, 30);
  595. if(! $status) return [false, $result];
  596. if(! isset($result['code'])) return [false, '销售出库单生成失败'];
  597. if($result['code'] != 0) return [false, $result['msg']];
  598. return [true, ''];
  599. }
  600. public function otherIn($data) {return [false, '其他入功能关闭'];
  601. // 1. 基础校验
  602. if (empty($data['warehouseCode'])) return [false, '仓库编码不能为空'];
  603. if (empty($data['detail'])) return [false, '明细数据不能为空'];
  604. $iBody = [];
  605. foreach ($data['detail'] as $key => $value) {
  606. if(empty($value['lineNum'])) return [false, '行号不能为空'];
  607. if(! is_numeric($value['lineNum'])) return [false, '行号错误'];
  608. if(empty($value['materialCode'])) return [false, '存货编码不能为空'];
  609. if(empty($value['productDate'])) return [false, '生产日期不能为空'];
  610. $return = $this->formatAndValidateDate($value['productDate']);
  611. if(! $return) return [false, '生产日期格式错误'];
  612. $productDate = $return;
  613. if(empty($value['failureDate'])) return [false, '失效日期不能为空'];
  614. $return = $this->formatAndValidateDate($value['failureDate']);
  615. if(! $return) return [false, '生产日期格式错误'];
  616. $failureDate= $return;
  617. if(empty($value['lot'])) return [false, '批号不能为空'];
  618. if(empty($value['iQuantity']) || ! is_numeric($value['iQuantity'])) return [false, '存货数量错误'];
  619. $iBody[] = [
  620. "iRowNo" => $key + 1,
  621. "cInvCode" => $value['materialCode'], // 存货编码
  622. "cBatch" => $value['lot'] ?? "", // 批号
  623. "iQuantity" => $value['iQuantity'],
  624. "iinvexchrate" => 0,
  625. "iNum" => 0,
  626. "dMadeDate" => $productDate, // 生产日期
  627. "dVDate" => $failureDate, // 失效日期
  628. 'cFree1' => $value['param_one'] ?? null,
  629. 'cFree2' => $value['param_two'] ?? null,
  630. ];
  631. }
  632. // 2. 组织表头 (iHead)
  633. $iHead = [
  634. "cWhCode" => $data['warehouseCode'], // 仓库编码
  635. "cRdCode" => "0109", // 收发类别 其他入
  636. "cDepCode" => "", // 部门
  637. "IsVerify" => ! isset($data['IsVerify']) ?? false, // 是否自动审核
  638. "cMemo" => "接口生成",
  639. "dDate" => $data['dDate'] ?? date("Y-m-d"), // 单据日期
  640. ];
  641. // 4. 封装成要求的数组结构
  642. $final_data = [
  643. [
  644. "Inum" => "OtherIn",
  645. "Data" => [
  646. "iHead" => $iHead,
  647. "iBody" => $iBody
  648. ]
  649. ]
  650. ];
  651. // 5. 准备发送请求
  652. $host = $data['u8_data']['host'] ?? "";
  653. $token = $data['u8_data']['token'] ?? "";
  654. $url = $host . "/api/OtherIn/Add";
  655. $header = ["Authorization: {$token}", 'Content-Type:application/json'];
  656. // 执行提交 (假设你已经定义了 post_helper1)
  657. $json = json_encode($final_data);
  658. list($status, $result) = $this->post_helper1($url, $json, $header, 30);
  659. if(! $status) return [false, $result];
  660. if(! isset($result['code'])) return [false, '其他入库单生成失败'];
  661. if($result['code'] != 0) return [false, $result['msg']];
  662. return [true, $result];
  663. }
  664. public function otherOut($data) {return [false, '其他出功能关闭'];
  665. // 1. 基础校验
  666. if (empty($data['warehouseCode'])) return [false, '仓库编码不能为空'];
  667. if (empty($data['detail'])) return [false, '明细数据不能为空'];
  668. $iBody = [];
  669. foreach ($data['detail'] as $key => $value) {
  670. if(empty($value['materialCode'])) return [false, '存货编码不能为空'];
  671. // 格式化生产日期
  672. $productDate = null;
  673. if(!empty($value['productDate'])){
  674. $productDate = $this->formatAndValidateDate($value['productDate']);
  675. if(!$productDate) return [false, '生产日期格式错误'];
  676. }
  677. // 格式化失效日期
  678. $failureDate = null;
  679. if(!empty($value['failureDate'])){
  680. $failureDate = $this->formatAndValidateDate($value['failureDate']);
  681. if(!$failureDate) return [false, '失效日期格式错误'];
  682. }
  683. if(empty($value['iQuantity']) || !is_numeric($value['iQuantity'])) return [false, '存货数量错误'];
  684. $iBody[] = [
  685. "iRowNo" => $key + 1,
  686. "cInvCode" => $value['materialCode'], // 存货编码
  687. "cBatch" => $value['lot'] ?? "", // 批号
  688. "iQuantity" => $value['iQuantity'],
  689. "iinvexchrate" => 0,
  690. "dMadeDate" => $productDate, // 生产日期
  691. "dVDate" => $failureDate, // 失效日期
  692. 'cFree1' => $value['param_one'] ?? null,
  693. 'cFree2' => $value['param_two'] ?? null,
  694. ];
  695. }
  696. // 2. 组织表头 (iHead)
  697. $iHead = [
  698. "cWhCode" => $data['warehouseCode'], // 仓库编码
  699. "cRdCode" => "0209", // 收发类别:其他出库
  700. "cDepCode" => "", // 部门
  701. "IsVerify" => isset($data['IsVerify']) ?? false, // 是否自动审核
  702. "cMemo" => "接口生成",
  703. "dDate" => $data['dDate'] ?? date("Y-m-d"), // 单据日期
  704. ];
  705. // 4. 封装成要求的数组结构 - Inum 改为 OtherOut
  706. $final_data = [
  707. [
  708. "Inum" => "OtherOut",
  709. "Data" => [
  710. "iHead" => $iHead,
  711. "iBody" => $iBody
  712. ]
  713. ]
  714. ];
  715. // 5. 准备发送请求
  716. $host = $data['u8_data']['host'] ?? "";
  717. $token = $data['u8_data']['token'] ?? "";
  718. // 地址改为 OtherOut
  719. $url = $host . "/api/OtherOut/Add";
  720. $header = ["Authorization: {$token}", 'Content-Type:application/json'];
  721. // 执行提交
  722. $json = json_encode($final_data);
  723. list($status, $result) = $this->post_helper1($url, $json, $header, 30);
  724. if(! $status) return [false, "网络请求失败: " . $result];
  725. if(! isset($result['code'])) return [false, '其他出库单生成失败'];
  726. if($result['code'] != 0) return [false, "U8错误: " . $result['msg']];
  727. return [true, $result];
  728. }
  729. public function saleReturn($data) {
  730. if(empty($data['orderId'])) return [false, '销售退货单ID不能为空'];
  731. // 1. 获取销售退货单信息 (DispatchList & DispatchLists)
  732. $service = new U8ThirtyPartyDatabaseServerService();
  733. list($status, $order) = $service->getXsThOrder($data['orderId']);
  734. if(! $status) return [false, $order];
  735. // --- 核心修改:按仓库分组 ---
  736. $groupDetails = [];
  737. foreach ($order['details'] as $item) {
  738. $whCode = $item['cWhCode'] ?? $order['cWhCode']; // 优先取明细里的仓库,没有则取主表的
  739. $groupDetails[$whCode][] = $item;
  740. }
  741. $final_data = [];
  742. // 2. 遍历每个仓库分组,生成各自的单据
  743. foreach ($groupDetails as $whCode => $details) {
  744. $iBody = [];
  745. foreach ($details as $index => $value) {
  746. $qty = (float)($value['iQuantity'] ?? 0);
  747. $redQty = $qty > 0 ? -$qty : $qty; // 强制红字
  748. $iBody[] = [
  749. "iRowNo" => $index + 1,
  750. "cInvCode" => $value['cInvCode'],
  751. "cPosition" => $value['cPosition'] ?? "",
  752. "cBatch" => $value['cBatch'] ?? "",
  753. "iinvexchrate" => (float)($value['iinvexchrate'] ?? 1),
  754. "iQuantity" => $redQty,
  755. "iNQuantity" => $redQty,
  756. "iNum" => (float)($value['iNum'] ?? 0),
  757. "iNNum" => (float)($value['iNum'] ?? 0),
  758. "iDLsID" => $value['iDLsID'] ?? 0, // 关键:关联发货单行ID
  759. "dMadeDate" => $value['dMDate'] ?? null,
  760. "dVDate" => $value['dvDate'] ?? null,
  761. 'cFree1' => $details['cFree1'] ?? null,
  762. 'cFree2' => $details['cFree2'] ?? null,
  763. ];
  764. }
  765. // 组织该单据的表头
  766. $iHead = [
  767. "IsVerify" => true,
  768. "bIsRedVouch" => true,
  769. "cWhCode" => $whCode, // 当前分组的仓库
  770. "cRdCode" => "0204",
  771. "cMemo" => "接口生成",
  772. "cSource" => "发货单",
  773. "cSTCode" => $order['cSTCode'],
  774. "DLCode" => $order['cDLCode'] ?? "",
  775. "dDate" => date("Y-m-d"),
  776. ];
  777. // 放入大数组
  778. $final_data[] = [
  779. "Inum" => "SaleOut",
  780. "Data" => [
  781. "iHead" => $iHead,
  782. "iBody" => $iBody
  783. ]
  784. ];
  785. }
  786. // 3. 发送请求
  787. $host = $data['u8_data']['host'] ?? "";
  788. $token = $data['u8_data']['token'] ?? "";
  789. $url = $host . "/api/SaleOut/Add";
  790. $header = ["Authorization: {$token}", 'Content-Type:application/json'];
  791. $json = json_encode($final_data);
  792. list($status, $result) = $this->post_helper1($url, $json, $header, 30);
  793. if(!$status) return [false, $result];
  794. if(!isset($result['code'])) return [false, '红字销售出库单生成失败'];
  795. if($result['code'] != 0) return [false, $result['msg']];
  796. return [true, $result];
  797. }
  798. //检验单生成产成品入库单
  799. public function productInByZj($data){
  800. $record = $data['record'];
  801. $payload = $data['payload'];
  802. $id = $record['u8_id'];
  803. $type = $data['type'];
  804. // 数量逻辑判断
  805. $num = ($type == 1) ? (float)$payload['hg_quantity'] : (float)$payload['rb_quantity'];
  806. // 获取单据 产品检验单
  807. $service = new U8ThirtyPartyDatabaseServerService();
  808. list($status, $order) = $service->getJyOrder($id);
  809. if(! $status) return [false, $order];
  810. // 获取单据 生产订单子表 (用于获取生产订单累计数量 iNQuantity)
  811. list($status, $product_detail) = $service->getScDetails($order['SOURCEID']);
  812. if(! $status) return [false, $product_detail];
  813. // u8 token 获取
  814. list($status, $msg) = $this->getToken();
  815. if(! $status) return [false, $msg];
  816. // 组织 ProductIn 结构
  817. $tmp = [
  818. "Inum" => "ProductIn",
  819. "Data" => [
  820. "iHead" => [
  821. "cWhCode" => (string)($order['cWhCode'] ?? "06"), // 产成品库
  822. "cRdCode" => "0103", // 入库类别
  823. "cDepCode" => $order['CINSPECTDEPCODE'],
  824. "cMemo" => "接口生成",
  825. "cSource" => "产品检验单",
  826. "cBusType" => "成品入库",
  827. "cMPoCode" => (string)$order['SOURCECODE'], // 生产订单号
  828. "cChkCode" => (string)$order['CCHECKCODE'], // 检验单号
  829. "dDate" => date("Y-m-d"),
  830. "IsVerify" => true,
  831. ],
  832. "iBody" => []
  833. ]
  834. ];
  835. // 组织表体
  836. $tmp["Data"]["iBody"][] = [
  837. "iRowNo" => 1,
  838. "cInvCode" => (string)($order['CINVCODE'] ?? ''),
  839. "iinvexchrate" => (float)($order['FCHANGRATE'] ?? 0), // 换算率转为数字
  840. "iQuantity" => (float)$num, // 本次入库数量
  841. "iNQuantity" => (float)($product_detail['Qty'] ?? 0), // 生产订单总数量
  842. "iNum" => 0, // 辅计数量
  843. "iNNum" => 0, // 生产订单辅计总数量
  844. "iMPoIds" => (int)($order['SOURCEAUTOID'] ?? 0), // 生产订单子表ID,必须是整型
  845. "cBatch" => (string)($order['CBATCH'] ?? ''),
  846. "dMadeDate" => (string)($order['DPRODATE'] ?? ''),
  847. "dVDate" => (string)($order['DVDATE'] ?? ''),
  848. 'cFree1' => $order['CFREE1'] ?? null,
  849. 'cFree2' => $order['CFREE2'] ?? null,
  850. ];
  851. $final_data = [$tmp];
  852. // 调用参数
  853. $host = $msg['host'] ?? "";
  854. $token = $msg['token'] ?? "";
  855. $url = $host . "/api/ProductIn/Add";
  856. $header = ["Authorization: {$token}", 'Content-Type:application/json'];
  857. $json = json_encode($final_data);
  858. list($status, $result) = $this->post_helper1($url, $json, $header, 30);
  859. if(! $status) return [false, $result];
  860. if(! isset($result['code'])) return [false, '产成品入库单生成失败'];
  861. if($result['code'] != 0) return [false, $result['msg']];
  862. return [true, ''];
  863. }
  864. //检验单生成其他入库单
  865. public function otherInByZj($data){
  866. $record = $data['record'];
  867. $payload = $data['payload'];
  868. $id = $record['u8_id'];
  869. $num = $payload['hg_not_quantity'];
  870. //获取单据 检验单
  871. $service = new U8ThirtyPartyDatabaseServerService();
  872. list($status, $order) = $service->getJyOrder($id);
  873. if(! $status) return [false, $order];
  874. //u8 token
  875. list($status, $msg) = $this->getToken();
  876. if(! $status) return [false, $msg];
  877. $tmp = [
  878. "Inum" => "OtherIn",
  879. "Data" => [
  880. "iHead" => [
  881. "IsVerify" => true,
  882. "cWhCode" => "53", // 成品不良品库
  883. "cRdCode" => '0109', // 入库类别 其他入库
  884. "cDepCode" => '', // 部门
  885. "cMemo" => "接口生成",
  886. "dDate" => date("Y-m-d"),
  887. ],
  888. "iBody" => []
  889. ]
  890. ];
  891. //一个检验单只有一行
  892. $tmp["Data"]["iBody"][] = [
  893. "iRowNo" => 1,
  894. "cInvCode" => $order['CINVCODE'] ?? '',
  895. "cAssUnit" => $order['CUNITID'] ?? '',
  896. "cPosition" => $order['cPosition'] ?? '',
  897. "cBatch" => $order['CBATCH'] ?? '',
  898. "iinvexchrate" => $order['FCHANGRATE'] ?? 0,
  899. "iQuantity" => $num, // 数量
  900. "dMadeDate" => $order['DPRODATE'] ?? '', // 生产日期
  901. "dVDate" => $order['DVDATE'] ?? '',
  902. 'cFree1' => $order['CFREE1'] ?? null,
  903. 'cFree2' => $order['CFREE2'] ?? null,
  904. ];
  905. $final_data = [$tmp];
  906. //调用所需
  907. $host = $msg['host'] ?? "";
  908. $token = $msg['token'] ?? "";
  909. //产成品入库单生成
  910. $header = ["Authorization: {$token}",'Content-Type:application/json'];
  911. $url = $host . "/api/OtherIn/Add";
  912. $json = json_encode($final_data);
  913. list($status, $result) = $this->post_helper1($url, $json, $header, 30);
  914. if(! $status) return [false, $result];
  915. if(! isset($result['code'])) return [false, '其他入库单生成并审核失败'];
  916. if($result['code'] != 0) return [false, $result['msg']];
  917. return [true, ''];
  918. }
  919. public function purchaseInByZj($data)
  920. {
  921. $record = $data['record'];
  922. $payload = $data['payload'];
  923. $type = $data['type'];
  924. // 确定入库数量
  925. $num = ($type == 1) ? (float)$payload['hg_quantity'] : (float)$payload['rb_quantity'];
  926. // 1. 获取基础数据 (检验单信息)
  927. $service = new U8ThirtyPartyDatabaseServerService();
  928. list($status, $order) = $service->getJyOrder2($record['u8_id']);
  929. if(! $status || empty($order)) return [false, '检验单不存在'];
  930. // 2. 获取 U8 Token
  931. list($status, $msg) = $this->getToken();
  932. if(! $status) return [false, $msg];
  933. // --- 核心金额计算逻辑 ---
  934. $qty = (float)$num;
  935. $taxRate = (float)($order['iTaxRate'] ?? 13.0); // 税率
  936. $taxUnitPrice = (float)($order['iOriTaxCost'] ?? 0); // 原币含税单价
  937. // 1. 价税合计 (iSum)
  938. $iSum = round($qty * $taxUnitPrice, 2);
  939. // 2. 原币无税金额 (imoney) = 价税合计 / (1 + 税率/100)
  940. $iMoney = round($iSum / (1 + ($taxRate / 100)), 2);
  941. // 3. 税额 (itax)
  942. $iTax = round($iSum - $iMoney, 2);
  943. // 4. 原币无税单价 (iunitprice)
  944. $iUnitPrice = round($taxUnitPrice / (1 + ($taxRate / 100)), 6);
  945. // 3. 组织采购入库单
  946. $tmp = [
  947. "Inum" => "PurchaseIn",
  948. "Data" => [
  949. "iHead" => [
  950. "IsVerify" => true,
  951. "bCalPrice" => true, // 开启自动计算
  952. "PriceCalKey" => "iOriTaxCost", // 以含税单价为准
  953. "cWhCode" => (string)($order['CWHCODE'] ?? "01"),
  954. "cDepCode" => (string)($order['CDEPCODE']),
  955. "cVenCode" => (string)$order['CVENCODE'],
  956. "cRdCode" => "0101",
  957. "iExchRate" => (float)($order['IEXCHRATE'] ?? 1.0),
  958. "iTaxRate" => (float)$taxRate,
  959. "cExch_Name" => "人民币",
  960. "cSource" => "来料检验单",
  961. "cBusType" => "普通采购",
  962. "cMemo" => "接口生成",
  963. "dDate" => date("Y-m-d"),
  964. "cChkCode" => (string)$order['CCHECKCODE']
  965. ],
  966. "iBody" => [
  967. [
  968. "iRowNo" => 1,
  969. "cInvCode" => (string)$order['CINVCODE'],
  970. "iQuantity" => (float)$qty,
  971. "iNum" => 0,
  972. "iNQuantity" => (float)($order['IQUANTITY'] ?? $qty),
  973. "iNNum" => 0,
  974. "iArrsId" => (int)$order['SOURCEAUTOID'], // 强制转 int,关联到货单子表
  975. // --- 新增价格字段 ---
  976. "iOriTaxCost" => (float)$taxUnitPrice, // 原币含税单价
  977. "iOriCost" => (float)$iUnitPrice, // 原币无税单价
  978. "iOriMoney" => (float)$iMoney, // 原币无税金额
  979. "iOriTaxPrice" => (float)$iTax, // 原币税额
  980. "iOriSum" => (float)$iSum, // 原币价税合计
  981. "iTaxRate" => (float)$taxRate, // 税率
  982. // 本币字段 (inat...) 建议也加上,防止 U8 换算误差
  983. "fNatMoney" => (float)$iMoney, // 本币无税金额
  984. "fNatTax" => (float)$iTax, // 本币税额
  985. "fNatSum" => (float)$iSum, // 本币价税合计
  986. "cBatch" => (string)($order['CBATCH'] ?? ''),
  987. "dMadeDate" => (string)($order['DPRODATE'] ?? ''),
  988. "dVDate" => (string)($order['DVDATE'] ?? ''),
  989. 'cFree1' => $order['CFREE1'] ?? null,
  990. 'cFree2' => $order['CFREE2'] ?? null,
  991. ]
  992. ]
  993. ]
  994. ];
  995. // 3. 组织采购入库单 (参照来料检验单模式)
  996. // $tmp = [
  997. // "Inum" => "PurchaseIn",
  998. // "Data" => [
  999. // "iHead" => [
  1000. // "IsVerify" => true, // 示例中为 false
  1001. // "cWhCode" => (string)($order['CWHCODE'] ?? "01"),
  1002. // "cDepCode" => (string)($order['CDEPCODE']),
  1003. // "cVenCode" => (string)$order['CVENCODE'],
  1004. // "cRdCode" => "0101",
  1005. // "iExchRate" => (float)($order['IEXCHRATE'] ?? 1.0),
  1006. // "iTaxRate" => (float)($order['ITAXRATE'] ?? 13.0),
  1007. // "cExch_Name" => "人民币",
  1008. // "cSource" => "来料检验单", // 匹配示例中的来源
  1009. // "cBusType" => "普通采购",
  1010. // "cMemo" => "接口生成",
  1011. // "dDate" => date("Y-m-d"),
  1012. // "cChkCode" => (string)$order['CCHECKCODE'] // 检验单号
  1013. // ],
  1014. // "iBody" => [
  1015. // [
  1016. // "iRowNo" => 1,
  1017. // "cInvCode" => (string)$order['CINVCODE'],
  1018. // "iQuantity" => (float)$num, // 本次入库实收数量
  1019. // "iNum" => 0,
  1020. // "iNQuantity" => (float)($order['IQUANTITY'] ?? $num), // 检验单关联数量
  1021. // "iNNum" => 0,
  1022. //// "iCheckIdBaks" => (int)$order['ICHECKIDBAKS'],
  1023. // "iArrsId" => $order['SOURCEAUTOID'], // 子表id
  1024. // "cBatch" => (string)($order['CBATCH'] ?? ''),
  1025. // "dMadeDate" => (string)($order['DPRODATE'] ?? ''),
  1026. // "dVDate" => (string)($order['DVDATE'] ?? ''),
  1027. // ]
  1028. // ]
  1029. // ]
  1030. // ];
  1031. $final_data = [$tmp];
  1032. // 4. 调用 API
  1033. $host = $msg['host'] ?? "";
  1034. $token = $msg['token'] ?? "";
  1035. $header = ["Authorization: {$token}", 'Content-Type:application/json'];
  1036. $url = $host . "/api/PurchaseIn/Add";
  1037. $json = json_encode($final_data);
  1038. list($status, $result) = $this->post_helper1($url, $json, $header, 30);
  1039. if(! $status) return [false, $result];
  1040. if(! isset($result['code'])) return [false, '采购入库单生成失败'];
  1041. if($result['code'] != 0) return [false, $result['msg']];
  1042. return [true, ''];
  1043. }
  1044. public function post_helper1($url, $data, $header = [], $timeout = 20){
  1045. Log::channel('apiLog')->info('POST', ["api" => $url , "param" => json_decode($data,true) ,"header" => $header]);
  1046. $ch = curl_init();
  1047. curl_setopt($ch, CURLOPT_URL, $url);
  1048. curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
  1049. curl_setopt($ch, CURLOPT_ENCODING, '');
  1050. curl_setopt($ch, CURLOPT_POST, 1);
  1051. curl_setopt($ch, CURLOPT_CUSTOMREQUEST, 'POST');
  1052. curl_setopt($ch, CURLOPT_HTTPHEADER, $header);
  1053. curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
  1054. curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, false);
  1055. curl_setopt($ch, CURLOPT_TIMEOUT, $timeout);
  1056. curl_setopt($ch, CURLOPT_CONNECTTIMEOUT, 10);
  1057. if(!is_null($data)) curl_setopt($ch, CURLOPT_POSTFIELDS, $data);
  1058. $r = curl_exec($ch);
  1059. if ($r === false) {
  1060. // 获取错误号
  1061. $errorNumber = curl_errno($ch);
  1062. // 获取错误信息
  1063. $errorMessage = curl_error($ch);
  1064. $message = "cURL Error #{$errorNumber}: {$errorMessage}";
  1065. Log::channel('apiLog')->info('POST结果', ["message" => $message ]);
  1066. return [false, $message];
  1067. }
  1068. curl_close($ch);
  1069. $return = json_decode($r, true);
  1070. unset($r);
  1071. Log::channel('apiLog')->info('POST结果', ["message" => $return ]);
  1072. return [true, $return];
  1073. }
  1074. function validateProductDate($dateStr) {
  1075. // SQL Server 常用的 datetime 格式包含 .v (毫秒)
  1076. // 注意:这里的格式必须严格对应 " 2025-12-13 00:00:00.000"
  1077. // 如果字符串开头有空格,格式字符串里也要留空格
  1078. $format = 'Y-m-d H:i:s.v';
  1079. $d = \DateTime::createFromFormat($format, $dateStr);
  1080. // 检查是否转换成功,并且转换后的格式与原字符串完全一致
  1081. return $d && $d->format($format) === $dateStr;
  1082. }
  1083. /**
  1084. * 校验并格式化日期
  1085. * 如果日期合法,返回格式化后的字符串;如果不合法,返回 false
  1086. */
  1087. public function formatAndValidateDate($dateStr) {
  1088. try {
  1089. // DateTime 构造函数会自动识别多种日期格式
  1090. // trim($dateStr) 用于去除可能存在的首尾空格
  1091. $d = new \DateTime(trim($dateStr));
  1092. // 统一转换为 SQL Server 喜欢的格式: 2026-03-11 00:00:00.000
  1093. return $d->format('Y-m-d H:i:s.v');
  1094. } catch (\Exception $e) {
  1095. // 如果传入的字符串无法解析为日期,会抛出异常
  1096. return false;
  1097. }
  1098. }
  1099. }