U8ThirdPartyService.php 54 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296
  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']; // 批号
  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'])) return [false, '失效日期不能为空'];
  446. $return = $this->formatAndValidateDate($value['failureDate']);
  447. if(! $return) return [false, '生产日期格式错误'];
  448. $failureDate= $return;
  449. if(empty($value['lot'])) return [false, '批号不能为空'];
  450. if(empty($value['iQuantity']) || ! is_numeric($value['iQuantity'])) return [false, '存货数量错误'];
  451. $detail_map[$value['materialCode']][] = [
  452. 'productDate' => $productDate,
  453. 'failureDate' => $failureDate,
  454. 'lot' => $value['lot'],
  455. 'iQuantity' => $value['iQuantity'],
  456. ];
  457. }
  458. // 2. 组织发货单 (DispatchList) 结构
  459. $tmp = [
  460. "Inum" => "DispatchList",
  461. "Data" => [
  462. "iHead" => [
  463. "cVouchType" => "05",
  464. "cSTCode" => (string)($order['cSTCode'] ?? "02"), // 示例中是02
  465. "cDepCode" => (string)($order['cDepCode'] ?? "01"),
  466. "IsVerify" => true,
  467. "cMemo" => "接口生成",
  468. "dDate" => date("Y-m-d"),
  469. "cSoCode" => (string)$order['cSOCode'],
  470. "ccuscode" => (string)$order['cCusCode'],
  471. "cexch_name" => (string)($order['cexch_name'] ?? "人民币"),
  472. "iexchrate" => (float)($order['iExchRate'] ?? 1.0), // 强制转浮点,去掉引号
  473. "iTaxRate" => (float)($order['iTaxRate'] ?? 13.0), // 强制转浮点
  474. ],
  475. "iBody" => []
  476. ]
  477. ];
  478. // 3. 遍历销售订单明细组织表体
  479. $key = 0;
  480. foreach ($order['details'] as $item) {
  481. $p_t = $detail_map[$item['cInvCode']] ?? [];
  482. if (empty($p_t)) continue;
  483. foreach ($p_t as $value) {
  484. $key++;
  485. $qty = (float)$value['iQuantity'];
  486. $taxRate = (float)($item['iTaxRate'] ?? 13.0);
  487. $taxUnitPrice = (float)$item['iTaxUnitPrice']; // 含税单价 (如 100)
  488. // 价税合计 (iSum)
  489. $iSum = round($qty * $taxUnitPrice, 2);
  490. // 无税金额 (imoney) = 价税合计 / (1 + 税率/100)
  491. $iMoney = round($iSum / (1 + ($taxRate / 100)), 2);
  492. // 税额 (itax)
  493. $iTax = round($iSum - $iMoney, 2);
  494. // 无税单价 (iunitprice)
  495. $iUnitPrice = round($taxUnitPrice / (1 + ($taxRate / 100)), 10);
  496. $tmp["Data"]["iBody"][] = [
  497. "iRowNo" => (int)$key, // 强制转整型
  498. "cInvCode" => (string)$item['cInvCode'],
  499. "iTaxRate" => (float)$taxRate,
  500. "cGroupCode" => (string)($item['cGroupCode'] ?? "01"),
  501. "iGroupType" => "0",
  502. "cUnitID" => (string)($item['cUnitID'] ?? "003"),
  503. "cWhCode" => "06",
  504. "iQuantity" => (float)$qty,
  505. "iNum" => 0, // 辅计量数量
  506. "iSum" => (float)$iSum,
  507. "iInvExchRate" => 1.0, // 换算率,必填
  508. "imoney" => (float)$iMoney,
  509. "itax" => (float)$iTax,
  510. "idiscount" => 0,
  511. "inatmoney" => (float)$iMoney,
  512. "inattax" => (float)$iTax,
  513. "inatdiscount" => 0,
  514. "inatsum" => (float)$iSum,
  515. "itaxunitprice" => (float)$taxUnitPrice,
  516. "iunitprice" => (float)$iUnitPrice,
  517. "inatunitprice" => (float)$iUnitPrice,
  518. "dvDate" => (string)$value['failureDate'], // 示例中只需失效日期
  519. // "dMDate" => (string)$value['productDate'], // todo
  520. "iSOsID" => (int)$item['iSOsID'], // 强制转整型,去掉引号
  521. "cBatch" => (string)$value['lot'],
  522. 'cFree1' => $item['cFree1'],
  523. 'cFree2' => $item['cFree2'],
  524. ];
  525. }
  526. }
  527. $final_data = [$tmp];
  528. //调用所需
  529. $host = $data['u8_data']['host'];
  530. $token = $data['u8_data']['token'];
  531. //销售发货单
  532. $header = ["Authorization: {$token}",'Content-Type:application/json'];
  533. $url = $host . "/api/Dispatch/Add";
  534. $json = json_encode($final_data);
  535. list($status, $result) = $this->post_helper1($url,$json, $header, 30);
  536. if(! $status) return [false, $result];
  537. if(! isset($result['code'])) return [false, '销售发货单生成失败'];
  538. if($result['code'] != 0) return [false, $result['msg']];
  539. $first = $result['data'][0];
  540. $id = $first['VouchId'];
  541. // $id = 1000000882;
  542. list($status, $fhOrder) = $service->getFhOrder($id);
  543. if(! $status) return [false, $fhOrder];
  544. // 2. 初始化销售出库单结构
  545. $saleOut = [
  546. "Inum" => "SaleOut",
  547. "Data" => [
  548. "iHead" => [
  549. "IsVerify" => true, // 自动审核
  550. "cWhCode" => "06", // 仓库编码
  551. "cRdCode" => "0299", // 出入库类别编码
  552. "cVouchType" => "32", // 单据类型编码
  553. "cMemo" => "接口生成",
  554. "cSource" => "发货单",
  555. "cSTCode" => $fhOrder['cSTCode'], // 销售类型
  556. "DLCode" => $fhOrder['cDLCode'], // 关联的发货单号
  557. "cDepCode" => $fhOrder['cDepCode'], // 部门
  558. "dDate" => date("Y-m-d"), // 出库日期
  559. ],
  560. "iBody" => []
  561. ]
  562. ];
  563. // 3. 遍历发货单明细组织表体
  564. foreach ($fhOrder['details'] as $index => $item) {
  565. // 计算待出库数量 (总发货数 - 已出库数)
  566. $qty = (float)($item['iQuantity'] ?? 0);
  567. $outQty = (float)($item['fOutQuantity'] ?? 0);
  568. $pendingQty = $qty - $outQty;
  569. // 如果该行已全部出库,则跳过(可选逻辑)
  570. if ($pendingQty <= 0) continue;
  571. $saleOut["Data"]["iBody"][] = [
  572. "iRowNo" => $index + 1,
  573. "cInvCode" => $item['cInvCode'] ?? "",
  574. "cPosition" => $item['cPosition'] ?? "", // 货位
  575. "cBatch" => $item['cBatch'] ?? "", // 批号
  576. "iinvexchrate" => (float)($item['iExchRate'] ?? 1), // 换算率
  577. "iQuantity" => $pendingQty, // 本次出库数量
  578. "iNQuantity" => $pendingQty, // 对应实收数量
  579. "iDLsID" => $item['iDLsID'], // 核心:发货单子表ID
  580. "dMadeDate" => $item['dMDate'], // 生产
  581. "dVDate" => $item['dvDate'], // 失效
  582. 'cFree1' => $item['cFree1'],
  583. 'cFree2' => $item['cFree2'],
  584. // "iUnitCost" => (float)($item['iUnitPrice'] ?? 0), // 无税单价
  585. // "iPrice" => round((float)($item['iUnitPrice'] ?? 0) * $pendingQty, 2), // 无税金额
  586. ];
  587. }
  588. // 4. 封装成数组
  589. $final_data = [$saleOut];
  590. $header = ["Authorization: {$token}",'Content-Type:application/json'];
  591. $url = $host . "/api/SaleOut/Add";
  592. $json = json_encode($final_data);
  593. list($status, $result) = $this->post_helper1($url,$json, $header, 30);
  594. if(! $status) return [false, $result];
  595. if(! isset($result['code'])) return [false, '销售出库单生成失败'];
  596. if($result['code'] != 0) return [false, $result['msg']];
  597. return [true, ''];
  598. }
  599. public function otherIn($data) {
  600. // 1. 基础校验
  601. if (empty($data['warehouseCode'])) return [false, '仓库编码不能为空'];
  602. if (empty($data['detail'])) return [false, '明细数据不能为空'];
  603. $iBody = [];
  604. foreach ($data['detail'] as $key => $value) {
  605. if(empty($value['lineNum'])) return [false, '行号不能为空'];
  606. if(! is_numeric($value['lineNum'])) return [false, '行号错误'];
  607. if(empty($value['materialCode'])) return [false, '存货编码不能为空'];
  608. if(empty($value['productDate'])) return [false, '生产日期不能为空'];
  609. $return = $this->formatAndValidateDate($value['productDate']);
  610. if(! $return) return [false, '生产日期格式错误'];
  611. $productDate = $return;
  612. if(empty($value['failureDate'])) return [false, '失效日期不能为空'];
  613. $return = $this->formatAndValidateDate($value['failureDate']);
  614. if(! $return) return [false, '生产日期格式错误'];
  615. $failureDate= $return;
  616. if(empty($value['lot'])) return [false, '批号不能为空'];
  617. if(empty($value['iQuantity']) || ! is_numeric($value['iQuantity'])) return [false, '存货数量错误'];
  618. $iBody[] = [
  619. "iRowNo" => $key + 1,
  620. "cInvCode" => $value['materialCode'], // 存货编码
  621. "cBatch" => $value['lot'] ?? "", // 批号
  622. "iQuantity" => $value['iQuantity'],
  623. "iinvexchrate" => 0,
  624. "iNum" => 0,
  625. "dMadeDate" => $productDate, // 生产日期
  626. "dVDate" => $failureDate, // 失效日期
  627. 'cFree1' => $value['param_one'] ?? null,
  628. 'cFree2' => $value['param_two'] ?? null,
  629. ];
  630. }
  631. // 2. 组织表头 (iHead)
  632. $iHead = [
  633. "cWhCode" => $data['warehouseCode'], // 仓库编码
  634. "cRdCode" => "0109", // 收发类别 其他入
  635. "cDepCode" => "", // 部门
  636. "IsVerify" => ! isset($data['IsVerify']) ?? false, // 是否自动审核
  637. "cMemo" => "接口生成",
  638. "dDate" => $data['dDate'] ?? date("Y-m-d"), // 单据日期
  639. ];
  640. // 4. 封装成要求的数组结构
  641. $final_data = [
  642. [
  643. "Inum" => "OtherIn",
  644. "Data" => [
  645. "iHead" => $iHead,
  646. "iBody" => $iBody
  647. ]
  648. ]
  649. ];
  650. // 5. 准备发送请求
  651. $host = $data['u8_data']['host'] ?? "";
  652. $token = $data['u8_data']['token'] ?? "";
  653. $url = $host . "/api/OtherIn/Add";
  654. $header = ["Authorization: {$token}", 'Content-Type:application/json'];
  655. // 执行提交 (假设你已经定义了 post_helper1)
  656. $json = json_encode($final_data);
  657. list($status, $result) = $this->post_helper1($url, $json, $header, 30);
  658. if(! $status) return [false, $result];
  659. if(! isset($result['code'])) return [false, '其他入库单生成失败'];
  660. if($result['code'] != 0) return [false, $result['msg']];
  661. return [true, $result];
  662. }
  663. public function otherOut($data) {
  664. // 1. 基础校验
  665. if (empty($data['warehouseCode'])) return [false, '仓库编码不能为空'];
  666. if (empty($data['detail'])) return [false, '明细数据不能为空'];
  667. $iBody = [];
  668. foreach ($data['detail'] as $key => $value) {
  669. if(empty($value['materialCode'])) return [false, '存货编码不能为空'];
  670. // 格式化生产日期
  671. $productDate = null;
  672. if(!empty($value['productDate'])){
  673. $productDate = $this->formatAndValidateDate($value['productDate']);
  674. if(!$productDate) return [false, '生产日期格式错误'];
  675. }
  676. // 格式化失效日期
  677. $failureDate = null;
  678. if(!empty($value['failureDate'])){
  679. $failureDate = $this->formatAndValidateDate($value['failureDate']);
  680. if(!$failureDate) return [false, '失效日期格式错误'];
  681. }
  682. if(empty($value['iQuantity']) || !is_numeric($value['iQuantity'])) return [false, '存货数量错误'];
  683. $iBody[] = [
  684. "iRowNo" => $key + 1,
  685. "cInvCode" => $value['materialCode'], // 存货编码
  686. "cBatch" => $value['lot'] ?? "", // 批号
  687. "iQuantity" => $value['iQuantity'],
  688. "iinvexchrate" => 0,
  689. "dMadeDate" => $productDate, // 生产日期
  690. "dVDate" => $failureDate, // 失效日期
  691. 'cFree1' => $value['param_one'] ?? null,
  692. 'cFree2' => $value['param_two'] ?? null,
  693. ];
  694. }
  695. // 2. 组织表头 (iHead)
  696. $iHead = [
  697. "cWhCode" => $data['warehouseCode'], // 仓库编码
  698. "cRdCode" => "0209", // 收发类别:其他出库
  699. "cDepCode" => "", // 部门
  700. "IsVerify" => isset($data['IsVerify']) ?? false, // 是否自动审核
  701. "cMemo" => "接口生成",
  702. "dDate" => $data['dDate'] ?? date("Y-m-d"), // 单据日期
  703. ];
  704. // 4. 封装成要求的数组结构 - Inum 改为 OtherOut
  705. $final_data = [
  706. [
  707. "Inum" => "OtherOut",
  708. "Data" => [
  709. "iHead" => $iHead,
  710. "iBody" => $iBody
  711. ]
  712. ]
  713. ];
  714. // 5. 准备发送请求
  715. $host = $data['u8_data']['host'] ?? "";
  716. $token = $data['u8_data']['token'] ?? "";
  717. // 地址改为 OtherOut
  718. $url = $host . "/api/OtherOut/Add";
  719. $header = ["Authorization: {$token}", 'Content-Type:application/json'];
  720. // 执行提交
  721. $json = json_encode($final_data);
  722. list($status, $result) = $this->post_helper1($url, $json, $header, 30);
  723. if(! $status) return [false, "网络请求失败: " . $result];
  724. if(! isset($result['code'])) return [false, '其他出库单生成失败'];
  725. if($result['code'] != 0) return [false, "U8错误: " . $result['msg']];
  726. return [true, $result];
  727. }
  728. public function saleReturn($data) {
  729. if(empty($data['orderId'])) return [false, '销售退货单ID不能为空'];
  730. // 1. 获取销售退货单信息 (DispatchList & DispatchLists)
  731. $service = new U8ThirtyPartyDatabaseServerService();
  732. list($status, $order) = $service->getXsThOrder($data['orderId']);
  733. if(! $status) return [false, $order];
  734. // --- 核心修改:按仓库分组 ---
  735. $groupDetails = [];
  736. foreach ($order['details'] as $item) {
  737. $whCode = $item['cWhCode'] ?? $order['cWhCode']; // 优先取明细里的仓库,没有则取主表的
  738. $groupDetails[$whCode][] = $item;
  739. }
  740. $final_data = [];
  741. // 2. 遍历每个仓库分组,生成各自的单据
  742. foreach ($groupDetails as $whCode => $details) {
  743. $iBody = [];
  744. foreach ($details as $index => $value) {
  745. $qty = (float)($value['iQuantity'] ?? 0);
  746. $redQty = $qty > 0 ? -$qty : $qty; // 强制红字
  747. $iBody[] = [
  748. "iRowNo" => $index + 1,
  749. "cInvCode" => $value['cInvCode'],
  750. "cPosition" => $value['cPosition'] ?? "",
  751. "cBatch" => $value['cBatch'] ?? "",
  752. "iinvexchrate" => (float)($value['iinvexchrate'] ?? 1),
  753. "iQuantity" => $redQty,
  754. "iNQuantity" => $redQty,
  755. "iNum" => (float)($value['iNum'] ?? 0),
  756. "iNNum" => (float)($value['iNum'] ?? 0),
  757. "iDLsID" => $value['iDLsID'] ?? 0, // 关键:关联发货单行ID
  758. "dMadeDate" => $value['dMDate'] ?? null,
  759. "dVDate" => $value['dvDate'] ?? null,
  760. 'cFree1' => $details['cFree1'] ?? null,
  761. 'cFree2' => $details['cFree2'] ?? null,
  762. ];
  763. }
  764. // 组织该单据的表头
  765. $iHead = [
  766. "IsVerify" => true,
  767. "bIsRedVouch" => true,
  768. "cWhCode" => $whCode, // 当前分组的仓库
  769. "cRdCode" => "0204",
  770. "cMemo" => "接口生成",
  771. "cSource" => "发货单",
  772. "cSTCode" => $order['cSTCode'],
  773. "DLCode" => $order['cDLCode'] ?? "",
  774. "dDate" => date("Y-m-d"),
  775. ];
  776. // 放入大数组
  777. $final_data[] = [
  778. "Inum" => "SaleOut",
  779. "Data" => [
  780. "iHead" => $iHead,
  781. "iBody" => $iBody
  782. ]
  783. ];
  784. }
  785. // 3. 发送请求
  786. $host = $data['u8_data']['host'] ?? "";
  787. $token = $data['u8_data']['token'] ?? "";
  788. $url = $host . "/api/SaleOut/Add";
  789. $header = ["Authorization: {$token}", 'Content-Type:application/json'];
  790. $json = json_encode($final_data);
  791. list($status, $result) = $this->post_helper1($url, $json, $header, 30);
  792. if(!$status) return [false, $result];
  793. if(!isset($result['code'])) return [false, '红字销售出库单生成失败'];
  794. if($result['code'] != 0) return [false, $result['msg']];
  795. return [true, $result];
  796. }
  797. //检验单生成产成品入库单
  798. public function productInByZj($data){
  799. $record = $data['record'];
  800. $payload = $data['payload'];
  801. $id = $record['u8_id'];
  802. $type = $data['type'];
  803. // 数量逻辑判断
  804. $num = ($type == 1) ? (float)$payload['hg_quantity'] : (float)$payload['rb_quantity'];
  805. // 获取单据 产品检验单
  806. $service = new U8ThirtyPartyDatabaseServerService();
  807. list($status, $order) = $service->getJyOrder($id);
  808. if(! $status) return [false, $order];
  809. // 获取单据 生产订单子表 (用于获取生产订单累计数量 iNQuantity)
  810. list($status, $product_detail) = $service->getScDetails($order['SOURCEID']);
  811. if(! $status) return [false, $product_detail];
  812. // u8 token 获取
  813. list($status, $msg) = $this->getToken();
  814. if(! $status) return [false, $msg];
  815. // 组织 ProductIn 结构
  816. $tmp = [
  817. "Inum" => "ProductIn",
  818. "Data" => [
  819. "iHead" => [
  820. "cWhCode" => (string)($order['cWhCode'] ?? "06"), // 产成品库
  821. "cRdCode" => "0103", // 入库类别
  822. "cDepCode" => $order['CINSPECTDEPCODE'],
  823. "cMemo" => "接口生成",
  824. "cSource" => "产品检验单",
  825. "cBusType" => "成品入库",
  826. "cMPoCode" => (string)$order['SOURCECODE'], // 生产订单号
  827. "cChkCode" => (string)$order['CCHECKCODE'], // 检验单号
  828. "dDate" => date("Y-m-d"),
  829. "IsVerify" => true,
  830. ],
  831. "iBody" => []
  832. ]
  833. ];
  834. // 组织表体
  835. $tmp["Data"]["iBody"][] = [
  836. "iRowNo" => 1,
  837. "cInvCode" => (string)($order['CINVCODE'] ?? ''),
  838. "iinvexchrate" => (float)($order['FCHANGRATE'] ?? 0), // 换算率转为数字
  839. "iQuantity" => (float)$num, // 本次入库数量
  840. "iNQuantity" => (float)($product_detail['Qty'] ?? 0), // 生产订单总数量
  841. "iNum" => 0, // 辅计数量
  842. "iNNum" => 0, // 生产订单辅计总数量
  843. "iMPoIds" => (int)($order['SOURCEAUTOID'] ?? 0), // 生产订单子表ID,必须是整型
  844. "cBatch" => (string)($order['CBATCH'] ?? ''),
  845. "dMadeDate" => (string)($order['DPRODATE'] ?? ''),
  846. "dVDate" => (string)($order['DVDATE'] ?? ''),
  847. 'cFree1' => $order['CFREE1'] ?? null,
  848. 'cFree2' => $order['CFREE2'] ?? null,
  849. ];
  850. $final_data = [$tmp];
  851. // 调用参数
  852. $host = $msg['host'] ?? "";
  853. $token = $msg['token'] ?? "";
  854. $url = $host . "/api/ProductIn/Add";
  855. $header = ["Authorization: {$token}", 'Content-Type:application/json'];
  856. $json = json_encode($final_data);
  857. list($status, $result) = $this->post_helper1($url, $json, $header, 30);
  858. if(! $status) return [false, $result];
  859. if(! isset($result['code'])) return [false, '产成品入库单生成失败'];
  860. if($result['code'] != 0) return [false, $result['msg']];
  861. return [true, ''];
  862. }
  863. //检验单生成其他入库单
  864. public function otherInByZj($data){
  865. $record = $data['record'];
  866. $payload = $data['payload'];
  867. $id = $record['u8_id'];
  868. $num = $payload['hg_not_quantity'];
  869. //获取单据 检验单
  870. $service = new U8ThirtyPartyDatabaseServerService();
  871. list($status, $order) = $service->getJyOrder($id);
  872. if(! $status) return [false, $order];
  873. //u8 token
  874. list($status, $msg) = $this->getToken();
  875. if(! $status) return [false, $msg];
  876. $tmp = [
  877. "Inum" => "OtherIn",
  878. "Data" => [
  879. "iHead" => [
  880. "IsVerify" => true,
  881. "cWhCode" => "53", // 成品不良品库
  882. "cRdCode" => '0109', // 入库类别 其他入库
  883. "cDepCode" => '', // 部门
  884. "cMemo" => "接口生成",
  885. "dDate" => date("Y-m-d"),
  886. ],
  887. "iBody" => []
  888. ]
  889. ];
  890. //一个检验单只有一行
  891. $tmp["Data"]["iBody"][] = [
  892. "iRowNo" => 1,
  893. "cInvCode" => $order['CINVCODE'] ?? '',
  894. "cAssUnit" => $order['CUNITID'] ?? '',
  895. "cPosition" => $order['cPosition'] ?? '',
  896. "cBatch" => $order['CBATCH'] ?? '',
  897. "iinvexchrate" => $order['FCHANGRATE'] ?? 0,
  898. "iQuantity" => $num, // 数量
  899. "dMadeDate" => $order['DPRODATE'] ?? '', // 生产日期
  900. "dVDate" => $order['DVDATE'] ?? '',
  901. 'cFree1' => $order['CFREE1'] ?? null,
  902. 'cFree2' => $order['CFREE2'] ?? null,
  903. ];
  904. $final_data = [$tmp];
  905. //调用所需
  906. $host = $msg['host'] ?? "";
  907. $token = $msg['token'] ?? "";
  908. //产成品入库单生成
  909. $header = ["Authorization: {$token}",'Content-Type:application/json'];
  910. $url = $host . "/api/OtherIn/Add";
  911. $json = json_encode($final_data);
  912. list($status, $result) = $this->post_helper1($url, $json, $header, 30);
  913. if(! $status) return [false, $result];
  914. if(! isset($result['code'])) return [false, '其他入库单生成并审核失败'];
  915. if($result['code'] != 0) return [false, $result['msg']];
  916. return [true, ''];
  917. }
  918. public function purchaseInByZj($data)
  919. {
  920. $record = $data['record'];
  921. $payload = $data['payload'];
  922. $type = $data['type'];
  923. // 确定入库数量
  924. $num = ($type == 1) ? (float)$payload['hg_quantity'] : (float)$payload['rb_quantity'];
  925. // 1. 获取基础数据 (检验单信息)
  926. $service = new U8ThirtyPartyDatabaseServerService();
  927. list($status, $order) = $service->getJyOrder2($record['u8_id']);
  928. if(! $status || empty($order)) return [false, '检验单不存在'];
  929. // 2. 获取 U8 Token
  930. list($status, $msg) = $this->getToken();
  931. if(! $status) return [false, $msg];
  932. // --- 核心金额计算逻辑 ---
  933. $qty = (float)$num;
  934. $taxRate = (float)($order['iTaxRate'] ?? 13.0); // 税率
  935. $taxUnitPrice = (float)($order['iOriTaxCost'] ?? 0); // 原币含税单价
  936. // 1. 价税合计 (iSum)
  937. $iSum = round($qty * $taxUnitPrice, 2);
  938. // 2. 原币无税金额 (imoney) = 价税合计 / (1 + 税率/100)
  939. $iMoney = round($iSum / (1 + ($taxRate / 100)), 2);
  940. // 3. 税额 (itax)
  941. $iTax = round($iSum - $iMoney, 2);
  942. // 4. 原币无税单价 (iunitprice)
  943. $iUnitPrice = round($taxUnitPrice / (1 + ($taxRate / 100)), 6);
  944. // 3. 组织采购入库单
  945. $tmp = [
  946. "Inum" => "PurchaseIn",
  947. "Data" => [
  948. "iHead" => [
  949. "IsVerify" => true,
  950. "bCalPrice" => true, // 开启自动计算
  951. "PriceCalKey" => "iOriTaxCost", // 以含税单价为准
  952. "cWhCode" => (string)($order['CWHCODE'] ?? "01"),
  953. "cDepCode" => (string)($order['CDEPCODE']),
  954. "cVenCode" => (string)$order['CVENCODE'],
  955. "cRdCode" => "0101",
  956. "iExchRate" => (float)($order['IEXCHRATE'] ?? 1.0),
  957. "iTaxRate" => (float)$taxRate,
  958. "cExch_Name" => "人民币",
  959. "cSource" => "来料检验单",
  960. "cBusType" => "普通采购",
  961. "cMemo" => "接口生成",
  962. "dDate" => date("Y-m-d"),
  963. "cChkCode" => (string)$order['CCHECKCODE']
  964. ],
  965. "iBody" => [
  966. [
  967. "iRowNo" => 1,
  968. "cInvCode" => (string)$order['CINVCODE'],
  969. "iQuantity" => (float)$qty,
  970. "iNum" => 0,
  971. "iNQuantity" => (float)($order['IQUANTITY'] ?? $qty),
  972. "iNNum" => 0,
  973. "iArrsId" => (int)$order['SOURCEAUTOID'], // 强制转 int,关联到货单子表
  974. // --- 新增价格字段 ---
  975. "iOriTaxCost" => (float)$taxUnitPrice, // 原币含税单价
  976. "iOriCost" => (float)$iUnitPrice, // 原币无税单价
  977. "iOriMoney" => (float)$iMoney, // 原币无税金额
  978. "iOriTaxPrice" => (float)$iTax, // 原币税额
  979. "iOriSum" => (float)$iSum, // 原币价税合计
  980. "iTaxRate" => (float)$taxRate, // 税率
  981. // 本币字段 (inat...) 建议也加上,防止 U8 换算误差
  982. "fNatMoney" => (float)$iMoney, // 本币无税金额
  983. "fNatTax" => (float)$iTax, // 本币税额
  984. "fNatSum" => (float)$iSum, // 本币价税合计
  985. "cBatch" => (string)($order['CBATCH'] ?? ''),
  986. "dMadeDate" => (string)($order['DPRODATE'] ?? ''),
  987. "dVDate" => (string)($order['DVDATE'] ?? ''),
  988. 'cFree1' => $order['CFREE1'] ?? null,
  989. 'cFree2' => $order['CFREE2'] ?? null,
  990. ]
  991. ]
  992. ]
  993. ];
  994. // 3. 组织采购入库单 (参照来料检验单模式)
  995. // $tmp = [
  996. // "Inum" => "PurchaseIn",
  997. // "Data" => [
  998. // "iHead" => [
  999. // "IsVerify" => true, // 示例中为 false
  1000. // "cWhCode" => (string)($order['CWHCODE'] ?? "01"),
  1001. // "cDepCode" => (string)($order['CDEPCODE']),
  1002. // "cVenCode" => (string)$order['CVENCODE'],
  1003. // "cRdCode" => "0101",
  1004. // "iExchRate" => (float)($order['IEXCHRATE'] ?? 1.0),
  1005. // "iTaxRate" => (float)($order['ITAXRATE'] ?? 13.0),
  1006. // "cExch_Name" => "人民币",
  1007. // "cSource" => "来料检验单", // 匹配示例中的来源
  1008. // "cBusType" => "普通采购",
  1009. // "cMemo" => "接口生成",
  1010. // "dDate" => date("Y-m-d"),
  1011. // "cChkCode" => (string)$order['CCHECKCODE'] // 检验单号
  1012. // ],
  1013. // "iBody" => [
  1014. // [
  1015. // "iRowNo" => 1,
  1016. // "cInvCode" => (string)$order['CINVCODE'],
  1017. // "iQuantity" => (float)$num, // 本次入库实收数量
  1018. // "iNum" => 0,
  1019. // "iNQuantity" => (float)($order['IQUANTITY'] ?? $num), // 检验单关联数量
  1020. // "iNNum" => 0,
  1021. //// "iCheckIdBaks" => (int)$order['ICHECKIDBAKS'],
  1022. // "iArrsId" => $order['SOURCEAUTOID'], // 子表id
  1023. // "cBatch" => (string)($order['CBATCH'] ?? ''),
  1024. // "dMadeDate" => (string)($order['DPRODATE'] ?? ''),
  1025. // "dVDate" => (string)($order['DVDATE'] ?? ''),
  1026. // ]
  1027. // ]
  1028. // ]
  1029. // ];
  1030. $final_data = [$tmp];
  1031. // 4. 调用 API
  1032. $host = $msg['host'] ?? "";
  1033. $token = $msg['token'] ?? "";
  1034. $header = ["Authorization: {$token}", 'Content-Type:application/json'];
  1035. $url = $host . "/api/PurchaseIn/Add";
  1036. $json = json_encode($final_data);
  1037. list($status, $result) = $this->post_helper1($url, $json, $header, 30);
  1038. if(! $status) return [false, $result];
  1039. if(! isset($result['code'])) return [false, '采购入库单生成失败'];
  1040. if($result['code'] != 0) return [false, $result['msg']];
  1041. return [true, ''];
  1042. }
  1043. public function post_helper1($url, $data, $header = [], $timeout = 20){
  1044. Log::channel('apiLog')->info('POST', ["api" => $url , "param" => json_decode($data,true) ,"header" => $header]);
  1045. $ch = curl_init();
  1046. curl_setopt($ch, CURLOPT_URL, $url);
  1047. curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
  1048. curl_setopt($ch, CURLOPT_ENCODING, '');
  1049. curl_setopt($ch, CURLOPT_POST, 1);
  1050. curl_setopt($ch, CURLOPT_CUSTOMREQUEST, 'POST');
  1051. curl_setopt($ch, CURLOPT_HTTPHEADER, $header);
  1052. curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
  1053. curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, false);
  1054. curl_setopt($ch, CURLOPT_TIMEOUT, $timeout);
  1055. curl_setopt($ch, CURLOPT_CONNECTTIMEOUT, 10);
  1056. if(!is_null($data)) curl_setopt($ch, CURLOPT_POSTFIELDS, $data);
  1057. $r = curl_exec($ch);
  1058. if ($r === false) {
  1059. // 获取错误号
  1060. $errorNumber = curl_errno($ch);
  1061. // 获取错误信息
  1062. $errorMessage = curl_error($ch);
  1063. $message = "cURL Error #{$errorNumber}: {$errorMessage}";
  1064. Log::channel('apiLog')->info('POST结果', ["message" => $message ]);
  1065. return [false, $message];
  1066. }
  1067. curl_close($ch);
  1068. $return = json_decode($r, true);
  1069. unset($r);
  1070. Log::channel('apiLog')->info('POST结果', ["message" => $return ]);
  1071. return [true, $return];
  1072. }
  1073. function validateProductDate($dateStr) {
  1074. // SQL Server 常用的 datetime 格式包含 .v (毫秒)
  1075. // 注意:这里的格式必须严格对应 " 2025-12-13 00:00:00.000"
  1076. // 如果字符串开头有空格,格式字符串里也要留空格
  1077. $format = 'Y-m-d H:i:s.v';
  1078. $d = \DateTime::createFromFormat($format, $dateStr);
  1079. // 检查是否转换成功,并且转换后的格式与原字符串完全一致
  1080. return $d && $d->format($format) === $dateStr;
  1081. }
  1082. /**
  1083. * 校验并格式化日期
  1084. * 如果日期合法,返回格式化后的字符串;如果不合法,返回 false
  1085. */
  1086. public function formatAndValidateDate($dateStr) {
  1087. try {
  1088. // DateTime 构造函数会自动识别多种日期格式
  1089. // trim($dateStr) 用于去除可能存在的首尾空格
  1090. $d = new \DateTime(trim($dateStr));
  1091. // 统一转换为 SQL Server 喜欢的格式: 2026-03-11 00:00:00.000
  1092. return $d->format('Y-m-d H:i:s.v');
  1093. } catch (\Exception $e) {
  1094. // 如果传入的字符串无法解析为日期,会抛出异常
  1095. return false;
  1096. }
  1097. }
  1098. }