U8ThirdPartyService.php 54 KB

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