TPlusServerService.php 33 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705
  1. <?php
  2. namespace App\Service;
  3. use App\Jobs\ProcessDataJob;
  4. use App\Model\Depart;
  5. use App\Model\Employee;
  6. use App\Model\EmployeeDepartPermission;
  7. use App\Model\Product;
  8. use App\Model\RevenueCost;
  9. use App\Model\RevenueCostTotal;
  10. use Illuminate\Database\Schema\Blueprint;
  11. use Illuminate\Support\Facades\DB;
  12. use Illuminate\Support\Facades\Schema;
  13. class TPlusServerService extends Service
  14. {
  15. /**
  16. * @var TPlusDatabaseServerService
  17. */
  18. protected $databaseService;
  19. /**
  20. * @var string|null
  21. */
  22. protected $error;
  23. /**
  24. * TPlusServerService constructor.
  25. */
  26. public function __construct()
  27. {
  28. $service = new TPlusDatabaseServerService();
  29. $this->databaseService = $service->db;
  30. $this->error = $service->error;
  31. }
  32. /**
  33. * 获取错误信息
  34. *
  35. * @return string|null
  36. */
  37. public function getError()
  38. {
  39. return $this->error;
  40. }
  41. private $table = "tmp_revenue_cost_data";
  42. /**
  43. * 同步人员部门
  44. *
  45. * @param array $data
  46. * @param array $user
  47. * @return array
  48. */
  49. public function synPersonDepart($data, $user)
  50. {
  51. try {
  52. $this->databaseService->table('AA_Department')
  53. ->select('id','idparent as parent_id','name as title','code','disabled as is_use')
  54. ->chunkById(100, function ($data) {
  55. DB::transaction(function () use ($data) {
  56. $dataArray = Collect($data)->map(function ($object) {
  57. return (array)$object;
  58. })->toArray();
  59. $d_id = Depart::whereIn('id', array_column($dataArray,'id'))
  60. ->pluck('id')
  61. ->toArray();
  62. $insert = $update = [];
  63. foreach ($dataArray as $value){
  64. $is_use = $value['is_use'] ? 0 : 1;
  65. if(in_array($value['id'], $d_id)){
  66. $update[] = [
  67. 'id' => $value['id'],
  68. 'parent_id' => $value['parent_id'],
  69. 'title' => $value['title'],
  70. 'code' => $value['code'],
  71. 'is_use' => $is_use
  72. ];
  73. }else{
  74. $insert[] = [
  75. 'id' => $value['id'],
  76. 'parent_id' => $value['parent_id'],
  77. 'title' => $value['title'],
  78. 'code' => $value['code'],
  79. 'is_use' => $is_use
  80. ];
  81. }
  82. }
  83. if(! empty($insert)) Depart::insert($insert);
  84. if(! empty($update)) {
  85. foreach ($update as $value){
  86. Depart::where('id', $value['id'])
  87. ->update($value);
  88. }
  89. }
  90. });
  91. });
  92. $this->databaseService->table('AA_Person')
  93. ->select('id','code as number','name as emp_name','mobilePhoneNo as mobile','iddepartment as depart_id','disabled as state')
  94. ->chunkById(100, function ($data) {
  95. DB::transaction(function () use ($data) {
  96. $dataArray = Collect($data)->map(function ($object) {
  97. return (array)$object;
  98. })->toArray();
  99. $employee_id = Employee::whereIn('id', array_column($dataArray,'id'))
  100. ->pluck('id')
  101. ->toArray();
  102. $insert = $update = $depart_update = [];
  103. foreach ($dataArray as $value){
  104. $state = $value['state'] ? Employee::NOT_USE : Employee::USE;
  105. if(in_array($value['id'], $employee_id)){
  106. $update[] = [
  107. 'id' => $value['id'],
  108. 'number' => $value['number'],
  109. 'emp_name' => $value['emp_name'],
  110. 'mobile' => $value['mobile'],
  111. 'state' => $state
  112. ];
  113. }else{
  114. $insert[] = [
  115. 'id' => $value['id'],
  116. 'number' => $value['number'],
  117. 'emp_name' => $value['emp_name'],
  118. 'mobile' => $value['mobile'],
  119. 'state' => $state
  120. ];
  121. }
  122. $depart_update[] = [
  123. 'employee_id' => $value['id'],
  124. 'depart_id' => $value['depart_id']
  125. ];
  126. }
  127. if(! empty($insert)) Employee::insert($insert);
  128. if(! empty($update)) {
  129. foreach ($update as $value){
  130. Employee::where('id', $value['id'])
  131. ->update($value);
  132. }
  133. }
  134. if(! empty($depart_update)){
  135. EmployeeDepartPermission::whereIn('employee_id',array_column($depart_update,'employee_id'))->delete();
  136. EmployeeDepartPermission::insert($depart_update);
  137. }
  138. });
  139. });
  140. } catch (\Throwable $e) {
  141. return [false, $e->getMessage()];
  142. }
  143. return [true, ''];
  144. }
  145. /**
  146. * 收入成本统计同步
  147. *
  148. * @param array $data
  149. * @param array $user
  150. * @return array
  151. */
  152. public function synRevenueCost($data, $user){
  153. if(empty($data['crt_time']) || ! is_array($data['crt_time'])) return [false, '同步时间不能为空'];
  154. list($start_time, $end_time) = $this->changeDateToTimeStampAboutRange($data['crt_time'],false);
  155. if ($start_time === null || $end_time === null || $start_time > $end_time) return [false, "同步时间:时间区间无效"];
  156. list($bool, $bool_msg) = $this->isOverThreeMonths($start_time, $end_time);
  157. if(! $bool) return [false, $bool_msg];
  158. $data['start_timeStamp'] = $start_time;
  159. $data['end_timeStamp'] = $end_time;
  160. $start = date('Y-m-d H:i:s.000', $start_time);
  161. $end = date('Y-m-d H:i:s.000', $end_time);
  162. $data['start_time'] = $start;
  163. $data['end_time'] = $end;
  164. $data['operation_time'] = time();
  165. if(empty($data['type'])) return [false, '同步类型不能为空'];
  166. if(in_array($data['type'],[1,2,3,4])){
  167. list($status,$msg) = $this->limitingSendRequest($this->table);
  168. if(! $status) return [false, '收入成本相关信息同步正在后台运行,请稍后'];
  169. // //同步
  170. // list($status, $msg) = $this->synRevenueCostFromTPlus($data, $user);
  171. // if(! $status) {
  172. // $this->clearTmpTable();
  173. // $this->dellimitingSendRequest($this->table);
  174. // return [false, $msg];
  175. // }
  176. //队列
  177. ProcessDataJob::dispatch($data, $user)->onQueue(RevenueCost::job);
  178. }else{
  179. return [false, '同步类型错误'];
  180. }
  181. return [true, '收入成本相关信息同步已进入后台任务'];
  182. }
  183. public function synRevenueCostFromTPlus($data, $user){
  184. //创建临时表 如果不存在
  185. $this->createTmpTable();
  186. //清理临时表 如果内容不为空
  187. $this->clearTmpTable();
  188. $type = $data['type'];
  189. //写入临时数据
  190. if($type == 1){
  191. list($status, $msg) = $this->xhdTPlus($data, $user);
  192. if(! $status) return [false, $msg];
  193. list($status, $msg) = $this->xsfpTPlus($data, $user);
  194. if(! $status) return [false, $msg];
  195. list($status, $msg) = $this->hkdTPlus($data, $user);
  196. if(! $status) return [false, $msg];
  197. }elseif ($type == 2){
  198. list($status, $msg) = $this->xhdTPlus($data, $user);
  199. if(! $status) return [false, $msg];
  200. }elseif ($type == 3){
  201. list($status, $msg) = $this->xsfpTPlus($data, $user);
  202. if(! $status) return [false, $msg];
  203. }elseif ($type == 4){
  204. list($status, $msg) = $this->hkdTPlus($data, $user);
  205. if(! $status) return [false, $msg];
  206. }
  207. //更新数据
  208. list($status,$msg) = $this->updateRevenueCost($data);
  209. if(! $status) return [false, $msg];
  210. // //更新主表数据
  211. // list($status,$msg) = $this->updateRevenueCostTotal($data);
  212. // if(! $status) return [false, $msg];
  213. //都成功后 清理临时表
  214. $this->clearTmpTable();
  215. //释放redis
  216. $this->delTableKey();
  217. return [true, '同步成功'];
  218. }
  219. private function xhdTPlus($data, $user){
  220. try {
  221. $table = $this->table;
  222. $limit = 500;
  223. $lastId = 0;
  224. do {
  225. $rows = $this->databaseService->table('SA_SaleDelivery_b as sd_b')
  226. ->join('SA_SaleDelivery as sd', 'sd_b.idSaleDeliveryDTO', '=', 'sd.ID')
  227. ->leftJoin('AA_Partner as pn', 'sd.idsettlecustomer', '=', 'pn.ID')
  228. ->leftJoin('AA_Person as ps', 'sd.idclerk', '=', 'ps.ID')
  229. ->leftJoin('AA_Inventory as it', 'sd_b.idinventory', '=', 'it.ID')
  230. ->leftJoin('AA_Unit as ui', 'sd_b.idbaseunit', '=', 'ui.ID')
  231. ->where('sd.voucherdate', '>=', $data['start_time'])
  232. ->where('sd.voucherdate', '<=', $data['end_time'])
  233. ->where('sd_b.ID', '>', $lastId) // 用真实字段
  234. ->orderBy('sd_b.ID')
  235. ->limit($limit)
  236. ->selectRaw("
  237. COALESCE(sd.ID, 0) as order_id,
  238. COALESCE(sd.code, '') as order_number,
  239. sd.voucherdate as order_time,
  240. COALESCE(ps.name, '') as employee_id_1_title,
  241. COALESCE(sd.idclerk, 0) as employee_id_1,
  242. COALESCE(pn.priuserdefnvc15, '') as employee_id_2_title,
  243. COALESCE(pn.code, '') as customer_code,
  244. COALESCE(pn.name, '') as customer_title,
  245. COALESCE(sd.pubuserdefnvc11, '') as channel_finance,
  246. COALESCE(sd.pubuserdefnvc12, '') as channel_details,
  247. COALESCE(it.code, '') as product_code,
  248. COALESCE(it.name, '') as product_title,
  249. COALESCE(it.specification, '') as product_size,
  250. COALESCE(ui.name, '') as unit,
  251. COALESCE(sd_b.quantity, 0) as quantity,
  252. COALESCE(sd_b.taxPrice, 0) as price_3,
  253. COALESCE(sd_b.taxAmount, 0) as price_3_total,
  254. COALESCE(sd_b.ID, 0) as id_detail
  255. ")
  256. ->get();
  257. if ($rows->isEmpty()) break;
  258. $dataArray = Collect($rows)->map(function ($object) {
  259. return (array)$object;
  260. })->toArray();
  261. //存货档案
  262. $product = Product::where('del_time', 0)
  263. ->whereIn('code', array_unique(array_column($dataArray, 'product_code')))
  264. ->select('code', 'write_off_price', 'freight_price', 'business_cost')
  265. ->get()->toArray();
  266. $product_map = array_column($product, null, 'code');
  267. //组织数据
  268. foreach ($dataArray as $key => $value) {
  269. $p_tmp = $product_map[$value['product_code']] ?? [];
  270. $dataArray[$key]['order_type'] = RevenueCost::ORDER_ONE;
  271. $dataArray[$key]['order_time'] = strtotime($value['order_time']);
  272. $write_off_price = $p_tmp['write_off_price'] ?? 0;
  273. $dataArray[$key]['price_1'] = $write_off_price;
  274. $dataArray[$key]['price_1_total'] = bcmul($write_off_price, $value['quantity'], 2);
  275. $freight_price = $p_tmp['freight_price'] ?? 0;
  276. $dataArray[$key]['price_2'] = $freight_price;
  277. $dataArray[$key]['price_2_total'] = bcmul($freight_price, $value['quantity'], 2);
  278. $business_cost = $p_tmp['business_cost'] ?? 0;
  279. $dataArray[$key]['price_4'] = $business_cost;
  280. $price_4_total = bcmul($business_cost, $value['quantity'], 2);
  281. $dataArray[$key]['price_4_total'] = bcmul($business_cost, $value['quantity'], 2);
  282. $profit = bcsub($value['price_3_total'], $price_4_total, 2);
  283. $dataArray[$key]['profit'] = $profit;
  284. $dataArray[$key]['profit_rate'] = $value['price_3_total'] > 0 ? bcdiv($profit, $value['price_3_total'], 2) : 0;
  285. }
  286. DB::table($table)->insert($dataArray);
  287. // 更新 lastId 继续下一批
  288. $lastId = end($dataArray)['id_detail'] ?? $lastId;
  289. } while (count($rows) === $limit);
  290. }catch (\Throwable $exception){
  291. return [false, "销货单同步异常" . $exception->getMessage() . "|" . $exception->getLine() . "|" . $exception->getFile()];
  292. }
  293. return [true, ''];
  294. }
  295. private function xsfpTPlus($data, $user){
  296. try {
  297. $table = $this->table;
  298. $limit = 500;
  299. $lastId = 0;
  300. do {
  301. $rows = $this->databaseService->table('SA_SaleInvoice_b as si_b')
  302. ->join('SA_SaleInvoice as si', 'si_b.idSaleInvoiceDTO', '=', 'si.ID')
  303. ->leftJoin('AA_Partner as pn', 'si.idsettlecustomer', '=', 'pn.ID')
  304. ->leftJoin('AA_Person as ps', 'si.idclerk', '=', 'ps.ID')
  305. ->leftJoin('AA_Inventory as it', 'si_b.idinventory', '=', 'it.ID')
  306. ->leftJoin('AA_Unit as ui', 'si_b.idbaseunit', '=', 'ui.ID')
  307. ->where('si.voucherdate','>=',$data['start_time'])
  308. ->where('si.voucherdate','<=',$data['end_time'])
  309. ->where('si_b.ID', '>', $lastId) // 用真实字段
  310. ->orderBy('si_b.ID')
  311. ->limit($limit)
  312. ->selectRaw("
  313. COALESCE(si.ID, 0) as order_id,
  314. COALESCE(si.code, '') as order_number,
  315. si.voucherdate as order_time,
  316. COALESCE(pn.code, '') as customer_code,
  317. COALESCE(pn.name, '') as customer_title,
  318. COALESCE(si.idclerk, 0) as employee_id_1,
  319. COALESCE(ps.name, '') as employee_id_1_title,
  320. COALESCE(pn.priuserdefnvc15, '') as employee_id_2_title,
  321. COALESCE(it.code, '') as product_code,
  322. COALESCE(it.name, '') as product_title,
  323. COALESCE(it.specification, '') as product_size,
  324. COALESCE(ui.name, '') as unit,
  325. COALESCE(si_b.quantity, 0) as quantity,
  326. COALESCE(si_b.taxPrice, 0) as price_1,
  327. COALESCE(si_b.taxAmount, 0) as price_1_total,
  328. COALESCE(si_b.ID, 0) as id_detail,
  329. COALESCE(si_b.sourceVoucherDetailId, 0) as id_detail_upstream,
  330. COALESCE(si_b.sourceVoucherCode, '') as order_number_upstream
  331. ")
  332. ->get();
  333. if ($rows->isEmpty()) break;
  334. $dataArray = Collect($rows)->map(function ($object) {
  335. return (array)$object;
  336. })->toArray();
  337. //存货档案
  338. $product = Product::where('del_time',0)
  339. ->whereIn('code', array_unique(array_column($dataArray,'product_code')))
  340. ->select('code','business_cost')
  341. ->get()->toArray();
  342. $product_map = array_column($product,null,'code');
  343. //组织数据
  344. foreach ($dataArray as $key => $value){
  345. $p_tmp = $product_map[$value['product_code']] ?? [];
  346. $dataArray[$key]['order_type'] = RevenueCost::ORDER_TWO;
  347. $dataArray[$key]['order_time'] = strtotime($value['order_time']);
  348. $business_cost = $p_tmp['business_cost'] ?? 0;
  349. $dataArray[$key]['price_4'] = $business_cost;
  350. $price_4_total = bcmul($business_cost, $value['quantity'],2);
  351. $dataArray[$key]['price_4_total'] = bcmul($business_cost, $value['quantity'],2);
  352. $profit = bcsub($value['price_1_total'], $price_4_total,2);
  353. $dataArray[$key]['profit'] = $profit;
  354. $dataArray[$key]['profit_rate'] = $value['price_1_total'] > 0 ? bcdiv($profit, $value['price_1_total'],2) : 0;
  355. }
  356. DB::table($table)->insert($dataArray);
  357. // 更新 lastId 继续下一批
  358. $lastId = end($dataArray)['id_detail'] ?? $lastId;
  359. } while (count($rows) === $limit);
  360. }catch (\Throwable $exception){
  361. return [false, "销售发票同步异常" . $exception->getMessage() . "|" . $exception->getLine() . "|" . $exception->getFile()];
  362. }
  363. return [true, ''];
  364. }
  365. private function hkdTPlus($data, $user){
  366. try{
  367. $table = $this->table;
  368. $limit = 500;
  369. $lastId = 0;
  370. do {
  371. $rows = $this->databaseService->table('ARAP_ReceivePayment_b as rp_b')
  372. ->join('ARAP_ReceivePayment as rp', 'rp_b.idArapReceivePaymentDTO', '=', 'rp.ID')
  373. ->leftJoin('SA_SaleInvoice_b as si_b', 'rp_b.voucherDetailID', '=', 'si_b.ID')
  374. ->leftJoin('SA_SaleInvoice as si', 'si_b.idSaleInvoiceDTO', '=', 'si.ID')
  375. ->leftJoin('AA_Partner as pn', 'si.idsettlecustomer', '=', 'pn.ID')
  376. ->leftJoin('AA_Person as ps', 'rp.idperson', '=', 'ps.ID')
  377. ->leftJoin('AA_Inventory as it', 'si_b.idinventory', '=', 'it.ID')
  378. ->leftJoin('AA_Unit as ui', 'si_b.idbaseunit', '=', 'ui.ID')
  379. ->where('rp.voucherdate','>=',$data['start_time'])
  380. ->where('rp.voucherdate','<=',$data['end_time'])
  381. ->where('rp.isReceiveFlag','=', 1)
  382. ->where('rp_b.ID', '>', $lastId) // 用真实字段
  383. ->orderBy('rp_b.ID')
  384. ->limit($limit)
  385. ->selectRaw("
  386. COALESCE(rp.ID, 0) as order_id,
  387. COALESCE(rp.code, '') as order_number,
  388. rp.voucherdate as order_time,
  389. COALESCE(pn.code, '') as customer_code,
  390. COALESCE(pn.name, '') as customer_title,
  391. COALESCE(it.code, '') as product_code,
  392. COALESCE(it.name, '') as product_title,
  393. COALESCE(rp.idperson, 0) as employee_id_1,
  394. COALESCE(ps.name, '') as employee_id_1_title,
  395. COALESCE(pn.priuserdefnvc15, '') as employee_id_2_title,
  396. COALESCE(it.specification, '') as product_size,
  397. COALESCE(ui.name, '') as unit,
  398. COALESCE(si_b.quantity, 0) as quantity,
  399. COALESCE(si_b.taxPrice, 0) as price_1,
  400. COALESCE(si_b.taxAmount, 0) as price_1_total,
  401. COALESCE(rp_b.amount, 0) as payment_amount,
  402. COALESCE(rp_b.ID, 0) as id_detail,
  403. COALESCE(rp_b.voucherDetailID, 0) as id_detail_upstream,
  404. COALESCE(rp_b.voucherCode, '') as order_number_upstream
  405. ")
  406. ->get();
  407. if ($rows->isEmpty()) break;
  408. $dataArray = Collect($rows)->map(function ($object) {
  409. return (array)$object;
  410. })->toArray();
  411. //存货档案
  412. $product = Product::where('del_time',0)
  413. ->whereIn('code', array_unique(array_column($dataArray,'product_code')))
  414. ->select('code','business_cost')
  415. ->get()->toArray();
  416. $product_map = array_column($product,null,'code');
  417. //组织数据
  418. foreach ($dataArray as $key => $value){
  419. $p_tmp = $product_map[$value['product_code']] ?? [];
  420. $dataArray[$key]['order_type'] = RevenueCost::ORDER_THREE;
  421. $dataArray[$key]['order_time'] = strtotime($value['order_time']);
  422. $business_cost = $p_tmp['business_cost'] ?? 0;
  423. $dataArray[$key]['price_4'] = $business_cost;
  424. $price_4_total = bcmul($business_cost, $value['quantity'],2);
  425. $dataArray[$key]['price_4_total'] = $price_4_total;
  426. $profit = bcsub($value['price_1_total'], $price_4_total,2);
  427. $dataArray[$key]['profit'] = $profit;
  428. $dataArray[$key]['profit_rate'] = $value['price_1_total'] > 0 ? bcdiv($profit, $value['price_1_total'],2) : 0;
  429. }
  430. DB::table($table)->insert($dataArray);
  431. // 更新 lastId 继续下一批
  432. $lastId = end($dataArray)['id_detail'] ?? $lastId;
  433. } while (count($rows) === $limit);
  434. }catch (\Throwable $exception){
  435. return [false, "回款单同步异常" . $exception->getMessage() . "|" . $exception->getLine() . "|" . $exception->getFile()];
  436. }
  437. return [true, ''];
  438. }
  439. private function updateRevenueCost($data){
  440. try {
  441. $start_timeStamp = $data['start_timeStamp'];
  442. $end_timeStamp = $data['end_timeStamp'];
  443. $tmpTable = $this->table;
  444. $time = time();
  445. $ergs = $data;
  446. DB::transaction(function () use ($start_timeStamp, $end_timeStamp, $tmpTable,$time, $ergs) {
  447. // 1. 先软删除旧数据(你已有)
  448. RevenueCost::where('del_time', 0)
  449. ->where('order_time', '>=', $start_timeStamp)
  450. ->where('order_time', '<=', $end_timeStamp)
  451. ->update(['del_time' => $time]);
  452. // 2. 分批从临时表插入新数据
  453. $batchSize = 500;
  454. $lastId = 0;
  455. do {
  456. $chunk = DB::table($tmpTable)
  457. ->where('id', '>', $lastId)
  458. ->orderBy('id')
  459. ->limit($batchSize)
  460. ->get();
  461. if ($chunk->isEmpty()) {
  462. break;
  463. }
  464. $data = $chunk->map(function ($item) use($time){
  465. return [
  466. 'order_id' => $item->order_id,
  467. 'order_number' => $item->order_number,
  468. 'order_time' => $item->order_time,
  469. 'employee_id_1_title' => $item->employee_id_1_title,
  470. 'employee_id_1' => $item->employee_id_1,
  471. 'employee_id_2_title' => $item->employee_id_2_title ?? "",
  472. 'customer_code' => $item->customer_code,
  473. 'customer_title' => $item->customer_title,
  474. 'channel_finance' => $item->channel_finance,
  475. 'channel_details' => $item->channel_details,
  476. 'product_code' => $item->product_code,
  477. 'product_title' => $item->product_title,
  478. 'product_size' => $item->product_size,
  479. 'unit' => $item->unit,
  480. 'quantity' => $item->quantity,
  481. 'price_1' => $item->price_1,
  482. 'price_1_total' => $item->price_1_total,
  483. 'price_2' => $item->price_2,
  484. 'price_2_total' => $item->price_2_total,
  485. 'price_3' => $item->price_3,
  486. 'price_3_total' => $item->price_3_total,
  487. 'price_4' => $item->price_4,
  488. 'price_4_total' => $item->price_4_total,
  489. 'profit' => $item->profit,
  490. 'profit_rate' => $item->profit_rate,
  491. 'id_detail' => $item->id_detail,
  492. 'order_type' => $item->order_type,
  493. 'payment_amount' => $item->payment_amount ?? 0,
  494. 'id_detail_upstream' => $item->id_detail_upstream?? 0,
  495. 'order_number_upstream' => $item->order_number_upstream ?? "",
  496. 'crt_time' => $time,
  497. ];
  498. })->toArray();
  499. // 每批单独插入(可选:加小事务)
  500. RevenueCost::insert($data);
  501. // 更新 lastId
  502. $lastId = $chunk->last()->id;
  503. } while ($chunk->count() == $batchSize);
  504. // 3. 更新主表
  505. list($status, $msg) = $this->updateRevenueCostTotal($ergs);
  506. if (! $status) {
  507. throw new \Exception($msg);
  508. }
  509. });
  510. }catch (\Throwable $exception){
  511. return [false, "单据明细同步异常" . $exception->getMessage() . "|" . $exception->getLine() . "|" . $exception->getFile()];
  512. }
  513. return [true, ''];
  514. }
  515. private function updateRevenueCostTotal($data){
  516. try {
  517. $start_timeStamp = $data['start_timeStamp'];
  518. $end_timeStamp = $data['end_timeStamp'];
  519. $time = time();
  520. //组织写入数据
  521. $return = [];
  522. $update_stamp = [];
  523. DB::table('revenue_cost')
  524. ->where('del_time',0)
  525. ->where('order_time', '>=', $start_timeStamp)
  526. ->where('order_time', '<=', $end_timeStamp)
  527. ->select(RevenueCost::$field)
  528. ->chunkById(100, function ($data) use(&$return,&$update_stamp){
  529. $dataArray = Collect($data)->map(function ($object){
  530. return (array)$object;
  531. })->toArray();
  532. foreach ($dataArray as $value){
  533. //变成每个月第一天的时间戳
  534. $time = date("Y-m-01", $value['order_time']);
  535. $stamp = strtotime($time);
  536. if(! in_array($stamp, $update_stamp)) $update_stamp[] = $stamp;
  537. if($value['order_type'] == RevenueCost::ORDER_ONE){
  538. $income = $value['price_3_total'];
  539. }elseif ($value['order_type'] == RevenueCost::ORDER_TWO){
  540. $income = $value['price_1_total'];
  541. }else{
  542. $income = $value['payment_amount'];
  543. }
  544. $adjust = $income < 0 ? $income : 0;
  545. $business = $value['price_4_total'];
  546. if(isset($return[$stamp][$value['order_type']][$value['employee_id_1']])){
  547. $income_total = bcadd($return[$stamp][$value['order_type']][$value['employee_id_1']]['income'], $income,2);
  548. $adjust_total = bcadd($return[$stamp][$value['order_type']][$value['employee_id_1']]['adjust'], $adjust,2);
  549. $business_total = bcadd($return[$stamp][$value['order_type']][$value['employee_id_1']]['business'], $business,2);
  550. $return[$stamp][$value['order_type']][$value['employee_id_1']]['income'] = $income_total;
  551. $return[$stamp][$value['order_type']][$value['employee_id_1']]['adjust'] = $adjust_total;
  552. $return[$stamp][$value['order_type']][$value['employee_id_1']]['business'] = $business_total;
  553. }else{
  554. $return[$stamp][$value['order_type']][$value['employee_id_1']] = [
  555. 'income' => $income,
  556. 'adjust' => $adjust,
  557. 'business' => $business,
  558. 'order_time' => $stamp,
  559. 'employee_id_1_title' => $value['employee_id_1_title'],
  560. ];
  561. }
  562. }
  563. });
  564. $insert = [];
  565. foreach ($return as $value){
  566. foreach ($value as $order_type => $val){
  567. foreach ($val as $employee_id => $v){
  568. $profit = bcsub($v['income'], $v['business'],2);
  569. $profit_rate = $v['income'] > 0 ? bcdiv($profit, $v['income'],2) : 0;
  570. $v['profit'] = $profit;
  571. $v['profit_rate'] = $profit_rate;
  572. $v['order_type'] = $order_type;
  573. $v['employee_id_1'] = $employee_id;
  574. $v['crt_time'] = $time;
  575. $insert[] = $v;
  576. }
  577. }
  578. }
  579. RevenueCostTotal::where('del_time', 0)
  580. ->whereIn('order_time', $update_stamp)
  581. ->update(['del_time' => $time]);
  582. RevenueCostTotal::insert($insert);
  583. }catch (\Throwable $exception){
  584. return [false, "主表同步异常" . $exception->getMessage() . "|" . $exception->getLine() . "|" . $exception->getFile()];
  585. }
  586. return [true, ''];
  587. }
  588. private function createTmpTable(){
  589. $table = $this->table;
  590. if (! Schema::hasTable($table)) {
  591. // 可以通过 migration 创建,或程序启动时检查
  592. Schema::create($table, function (Blueprint $table) {
  593. $table->bigIncrements('id'); // BIGINT UNSIGNED AUTO_INCREMENT PRIMARY KEY
  594. $table->integer('order_type')->default(0);
  595. $table->bigInteger('order_id')->default(0);
  596. $table->string('order_number', 50)->default('');
  597. $table->integer('order_time')->nullable();
  598. $table->string('employee_id_1_title', 100)->default('');
  599. $table->bigInteger('employee_id_1')->default(0);
  600. $table->string('employee_id_2_title', 100)->default('');
  601. $table->string('customer_code', 50)->default('');
  602. $table->string('customer_title', 100)->default('');
  603. $table->string('channel_finance', 50)->nullable();
  604. $table->string('channel_details', 50)->nullable();
  605. $table->string('product_code', 50)->default('');
  606. $table->string('product_title', 100)->default('');
  607. $table->string('product_size', 100)->nullable();
  608. $table->string('unit', 20)->nullable();
  609. $table->decimal('quantity', 12, 2)->default(0);
  610. $table->decimal('price_1', 12, 2)->default(0); // 销项成本
  611. $table->decimal('price_1_total', 12, 2)->default(0);
  612. $table->decimal('price_2', 12, 2)->default(0); // 运费
  613. $table->decimal('price_2_total', 12, 2)->default(0);
  614. $table->decimal('price_3', 12, 2)->default(0); // 含税单价
  615. $table->decimal('price_3_total', 12, 2)->default(0); // 含税金额
  616. $table->decimal('price_4', 12, 2)->default(0); // 业务成本
  617. $table->decimal('price_4_total', 12, 2)->default(0);
  618. $table->decimal('profit', 12, 2)->default(0);
  619. $table->decimal('payment_amount', 12, 2)->default(0);
  620. $table->decimal('profit_rate', 10, 3)->default(0);
  621. $table->bigInteger('id_detail')->default(0);
  622. $table->bigInteger('id_detail_upstream')->default(0);
  623. $table->string('order_number_upstream', 100)->nullable();
  624. });
  625. }
  626. }
  627. public function clearTmpTable(){
  628. if (Schema::hasTable($this->table)) DB::table($this->table)->truncate();
  629. }
  630. public function delTableKey(){
  631. $this->dellimitingSendRequest($this->table);
  632. }
  633. }