TPlusServerService.php 34 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726
  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'][0]) || empty($data['crt_time'][1])) 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_Person as ps2', 'pn.idsaleman', '=', 'ps2.ID')
  230. ->leftJoin('AA_Inventory as it', 'sd_b.idinventory', '=', 'it.ID')
  231. ->leftJoin('AA_Unit as ui', 'sd_b.idbaseunit', '=', 'ui.ID')
  232. ->where('sd.voucherdate', '>=', $data['start_time'])
  233. ->where('sd.voucherdate', '<=', $data['end_time'])
  234. ->where('sd_b.ID', '>', $lastId) // 用真实字段
  235. ->orderBy('sd_b.ID')
  236. ->limit($limit)
  237. ->selectRaw("
  238. COALESCE(sd.ID, 0) as order_id,
  239. COALESCE(sd.code, '') as order_number,
  240. sd.voucherdate as order_time,
  241. COALESCE(ps.name, '') as employee_id_1_title,
  242. COALESCE(sd.idclerk, 0) as employee_id_1,
  243. COALESCE(ps2.name, '') as employee_id_2_title,
  244. COALESCE(pn.idsaleman, 0) as employee_id_2,
  245. COALESCE(pn.code, '') as customer_code,
  246. COALESCE(pn.name, '') as customer_title,
  247. COALESCE(pn.priuserdefnvc14, '') as customer_profit_rate,
  248. COALESCE(sd.pubuserdefnvc11, '') as channel_finance,
  249. COALESCE(sd.pubuserdefnvc12, '') as channel_details,
  250. COALESCE(it.code, '') as product_code,
  251. COALESCE(it.name, '') as product_title,
  252. COALESCE(it.specification, '') as product_size,
  253. COALESCE(ui.name, '') as unit,
  254. COALESCE(sd_b.quantity, 0) as quantity,
  255. COALESCE(sd_b.taxPrice, 0) as price_3,
  256. COALESCE(sd_b.taxAmount, 0) as price_3_total,
  257. COALESCE(sd_b.ID, 0) as id_detail,
  258. COALESCE(sd_b.pubuserdefdecm9, 0) as is_activity
  259. ")
  260. ->get();
  261. if ($rows->isEmpty()) break;
  262. $dataArray = Collect($rows)->map(function ($object) {
  263. return (array)$object;
  264. })->toArray();
  265. //存货档案
  266. $product = Product::where('del_time', 0)
  267. ->whereIn('code', array_unique(array_column($dataArray, 'product_code')))
  268. ->select('code', 'write_off_price', 'freight_price', 'business_cost')
  269. ->get()->toArray();
  270. $product_map = array_column($product, null, 'code');
  271. //组织数据
  272. foreach ($dataArray as $key => $value) {
  273. $p_tmp = $product_map[$value['product_code']] ?? [];
  274. $dataArray[$key]['order_type'] = RevenueCost::ORDER_ONE;
  275. $dataArray[$key]['order_time'] = strtotime($value['order_time']);
  276. $write_off_price = $p_tmp['write_off_price'] ?? 0;
  277. $dataArray[$key]['price_1'] = $write_off_price;
  278. $dataArray[$key]['price_1_total'] = bcmul($write_off_price, $value['quantity'], 2);
  279. $freight_price = $p_tmp['freight_price'] ?? 0;
  280. $dataArray[$key]['price_2'] = $freight_price;
  281. $dataArray[$key]['price_2_total'] = bcmul($freight_price, $value['quantity'], 2);
  282. $business_cost = $p_tmp['business_cost'] ?? 0;
  283. $dataArray[$key]['price_4'] = $business_cost;
  284. $price_4_total = bcmul($business_cost, $value['quantity'], 2);
  285. $dataArray[$key]['price_4_total'] = bcmul($business_cost, $value['quantity'], 2);
  286. $profit = bcsub($value['price_3_total'], $price_4_total, 2);
  287. $dataArray[$key]['profit'] = $profit;
  288. $dataArray[$key]['profit_rate'] = $value['price_3_total'] > 0 ? bcdiv($profit, $value['price_3_total'], 2) : 0;
  289. }
  290. DB::table($table)->insert($dataArray);
  291. // 更新 lastId 继续下一批
  292. $lastId = end($dataArray)['id_detail'] ?? $lastId;
  293. } while (count($rows) === $limit);
  294. }catch (\Throwable $exception){
  295. return [false, "销货单同步异常" . $exception->getMessage() . "|" . $exception->getLine() . "|" . $exception->getFile()];
  296. }
  297. return [true, ''];
  298. }
  299. private function xsfpTPlus($data, $user){
  300. try {
  301. $table = $this->table;
  302. $limit = 500;
  303. $lastId = 0;
  304. do {
  305. $rows = $this->databaseService->table('SA_SaleInvoice_b as si_b')
  306. ->join('SA_SaleInvoice as si', 'si_b.idSaleInvoiceDTO', '=', 'si.ID')
  307. ->leftJoin('SA_SaleDelivery_b as sd_b', 'si_b.sourceVoucherDetailId', '=', 'sd_b.ID')
  308. ->leftJoin('AA_Partner as pn', 'si.idsettlecustomer', '=', 'pn.ID')
  309. ->leftJoin('AA_Person as ps', 'si.idclerk', '=', 'ps.ID')
  310. ->leftJoin('AA_Person as ps2', 'pn.idsaleman', '=', 'ps2.ID')
  311. ->leftJoin('AA_Inventory as it', 'si_b.idinventory', '=', 'it.ID')
  312. ->leftJoin('AA_Unit as ui', 'si_b.idbaseunit', '=', 'ui.ID')
  313. ->where('si.voucherdate','>=',$data['start_time'])
  314. ->where('si.voucherdate','<=',$data['end_time'])
  315. ->where('si_b.ID', '>', $lastId) // 用真实字段
  316. ->orderBy('si_b.ID')
  317. ->limit($limit)
  318. ->selectRaw("
  319. COALESCE(si.ID, 0) as order_id,
  320. COALESCE(si.code, '') as order_number,
  321. si.voucherdate as order_time,
  322. COALESCE(pn.code, '') as customer_code,
  323. COALESCE(pn.name, '') as customer_title,
  324. COALESCE(pn.priuserdefnvc14, '') as customer_profit_rate,
  325. COALESCE(si.idclerk, 0) as employee_id_1,
  326. COALESCE(ps.name, '') as employee_id_1_title,
  327. COALESCE(pn.idsaleman, 0) as employee_id_2,
  328. COALESCE(ps2.name, '') as employee_id_2_title,
  329. COALESCE(it.code, '') as product_code,
  330. COALESCE(it.name, '') as product_title,
  331. COALESCE(it.specification, '') as product_size,
  332. COALESCE(ui.name, '') as unit,
  333. COALESCE(si_b.quantity, 0) as quantity,
  334. COALESCE(si_b.taxPrice, 0) as price_1,
  335. COALESCE(si_b.taxAmount, 0) as price_1_total,
  336. COALESCE(si_b.ID, 0) as id_detail,
  337. COALESCE(si_b.sourceVoucherDetailId, 0) as id_detail_upstream,
  338. COALESCE(si_b.sourceVoucherCode, '') as order_number_upstream,
  339. COALESCE(sd_b.pubuserdefdecm9, 0) as is_activity
  340. ")
  341. ->get();
  342. if ($rows->isEmpty()) break;
  343. $dataArray = Collect($rows)->map(function ($object) {
  344. return (array)$object;
  345. })->toArray();
  346. //存货档案
  347. $product = Product::where('del_time',0)
  348. ->whereIn('code', array_unique(array_column($dataArray,'product_code')))
  349. ->select('code','business_cost')
  350. ->get()->toArray();
  351. $product_map = array_column($product,null,'code');
  352. //组织数据
  353. foreach ($dataArray as $key => $value){
  354. $p_tmp = $product_map[$value['product_code']] ?? [];
  355. $dataArray[$key]['order_type'] = RevenueCost::ORDER_TWO;
  356. $dataArray[$key]['order_time'] = strtotime($value['order_time']);
  357. $business_cost = $p_tmp['business_cost'] ?? 0;
  358. $dataArray[$key]['price_4'] = $business_cost;
  359. $price_4_total = bcmul($business_cost, $value['quantity'],2);
  360. $dataArray[$key]['price_4_total'] = bcmul($business_cost, $value['quantity'],2);
  361. $profit = bcsub($value['price_1_total'], $price_4_total,2);
  362. $dataArray[$key]['profit'] = $profit;
  363. $dataArray[$key]['profit_rate'] = $value['price_1_total'] > 0 ? bcdiv($profit, $value['price_1_total'],2) : 0;
  364. }
  365. DB::table($table)->insert($dataArray);
  366. // 更新 lastId 继续下一批
  367. $lastId = end($dataArray)['id_detail'] ?? $lastId;
  368. } while (count($rows) === $limit);
  369. }catch (\Throwable $exception){
  370. return [false, "销售发票同步异常" . $exception->getMessage() . "|" . $exception->getLine() . "|" . $exception->getFile()];
  371. }
  372. return [true, ''];
  373. }
  374. private function hkdTPlus($data, $user){
  375. try{
  376. $table = $this->table;
  377. $limit = 500;
  378. $lastId = 0;
  379. do {
  380. $rows = $this->databaseService->table('ARAP_ReceivePayment_b as rp_b')
  381. ->join('ARAP_ReceivePayment as rp', 'rp_b.idArapReceivePaymentDTO', '=', 'rp.ID')
  382. ->leftJoin('SA_SaleInvoice_b as si_b', 'rp_b.voucherDetailID', '=', 'si_b.ID')
  383. ->leftJoin('SA_SaleInvoice as si', 'si_b.idSaleInvoiceDTO', '=', 'si.ID')
  384. ->leftJoin('SA_SaleDelivery_b as sd_b', 'si_b.sourceVoucherDetailId', '=', 'sd_b.ID')
  385. ->leftJoin('AA_Partner as pn', 'si.idsettlecustomer', '=', 'pn.ID')
  386. ->leftJoin('AA_Person as ps', 'rp.idperson', '=', 'ps.ID')
  387. ->leftJoin('AA_Person as ps2', 'pn.idsaleman', '=', 'ps2.ID')
  388. ->leftJoin('AA_Inventory as it', 'si_b.idinventory', '=', 'it.ID')
  389. ->leftJoin('AA_Unit as ui', 'si_b.idbaseunit', '=', 'ui.ID')
  390. ->where('rp.voucherdate','>=',$data['start_time'])
  391. ->where('rp.voucherdate','<=',$data['end_time'])
  392. ->where('rp_b.idvouchertype','=', 20) // 销售发票
  393. ->where('rp.isReceiveFlag','=', 1)
  394. ->where('rp_b.ID', '>', $lastId)
  395. ->orderBy('rp_b.ID')
  396. ->limit($limit)
  397. ->selectRaw("
  398. COALESCE(rp.ID, 0) as order_id,
  399. COALESCE(rp.code, '') as order_number,
  400. rp.voucherdate as order_time,
  401. COALESCE(pn.code, '') as customer_code,
  402. COALESCE(pn.name, '') as customer_title,
  403. COALESCE(pn.priuserdefnvc14, '') as customer_profit_rate,
  404. COALESCE(it.code, '') as product_code,
  405. COALESCE(it.name, '') as product_title,
  406. COALESCE(rp.idperson, 0) as employee_id_1,
  407. COALESCE(ps.name, '') as employee_id_1_title,
  408. COALESCE(pn.idsaleman, 0) as employee_id_2,
  409. COALESCE(ps2.name, '') as employee_id_2_title,
  410. COALESCE(it.specification, '') as product_size,
  411. COALESCE(ui.name, '') as unit,
  412. COALESCE(si_b.quantity, 0) as quantity,
  413. COALESCE(si_b.taxPrice, 0) as price_1,
  414. COALESCE(si_b.taxAmount, 0) as price_1_total,
  415. COALESCE(rp_b.amount, 0) as payment_amount,
  416. COALESCE(rp_b.ID, 0) as id_detail,
  417. COALESCE(rp_b.voucherDetailID, 0) as id_detail_upstream,
  418. COALESCE(rp_b.voucherCode, '') as order_number_upstream,
  419. COALESCE(sd_b.pubuserdefdecm9, 0) as is_activity
  420. ")
  421. ->get();
  422. if ($rows->isEmpty()) break;
  423. $dataArray = Collect($rows)->map(function ($object) {
  424. return (array)$object;
  425. })->toArray();
  426. //存货档案
  427. $product = Product::where('del_time',0)
  428. ->whereIn('code', array_unique(array_column($dataArray,'product_code')))
  429. ->select('code','business_cost')
  430. ->get()->toArray();
  431. $product_map = array_column($product,null,'code');
  432. //组织数据
  433. foreach ($dataArray as $key => $value){
  434. $p_tmp = $product_map[$value['product_code']] ?? [];
  435. $dataArray[$key]['order_type'] = RevenueCost::ORDER_THREE;
  436. $dataArray[$key]['order_time'] = strtotime($value['order_time']);
  437. $business_cost = $p_tmp['business_cost'] ?? 0;
  438. $dataArray[$key]['price_4'] = $business_cost;
  439. $price_4_total = bcmul($business_cost, $value['quantity'],2);
  440. $dataArray[$key]['price_4_total'] = $price_4_total;
  441. $profit = bcsub($value['price_1_total'], $price_4_total,2);
  442. $dataArray[$key]['profit'] = $profit;
  443. $dataArray[$key]['profit_rate'] = $value['price_1_total'] > 0 ? bcdiv($profit, $value['price_1_total'],2) : 0;
  444. }
  445. DB::table($table)->insert($dataArray);
  446. // 更新 lastId 继续下一批
  447. $lastId = end($dataArray)['id_detail'] ?? $lastId;
  448. } while (count($rows) === $limit);
  449. }catch (\Throwable $exception){
  450. return [false, "回款单同步异常" . $exception->getMessage() . "|" . $exception->getLine() . "|" . $exception->getFile()];
  451. }
  452. return [true, ''];
  453. }
  454. private function updateRevenueCost($data){
  455. try {
  456. $start_timeStamp = $data['start_timeStamp'];
  457. $end_timeStamp = $data['end_timeStamp'];
  458. $tmpTable = $this->table;
  459. $time = time();
  460. $ergs = $data;
  461. DB::transaction(function () use ($start_timeStamp, $end_timeStamp, $tmpTable,$time, $ergs) {
  462. // 1. 先软删除旧数据(你已有)
  463. RevenueCost::where('del_time', 0)
  464. ->where('order_time', '>=', $start_timeStamp)
  465. ->where('order_time', '<=', $end_timeStamp)
  466. ->update(['del_time' => $time]);
  467. // 2. 分批从临时表插入新数据
  468. $batchSize = 500;
  469. $lastId = 0;
  470. do {
  471. $chunk = DB::table($tmpTable)
  472. ->where('id', '>', $lastId)
  473. ->orderBy('id')
  474. ->limit($batchSize)
  475. ->get();
  476. if ($chunk->isEmpty()) {
  477. break;
  478. }
  479. $data = $chunk->map(function ($item) use($time){
  480. return [
  481. 'order_id' => $item->order_id,
  482. 'order_number' => $item->order_number,
  483. 'order_time' => $item->order_time,
  484. 'employee_id_1_title' => $item->employee_id_1_title,
  485. 'employee_id_1' => $item->employee_id_1 ?? 0,
  486. 'employee_id_2' => $item->employee_id_2 ?? 0,
  487. 'employee_id_2_title' => $item->employee_id_2_title ?? "",
  488. 'customer_code' => $item->customer_code,
  489. 'customer_title' => $item->customer_title,
  490. 'channel_finance' => $item->channel_finance,
  491. 'channel_details' => $item->channel_details,
  492. 'product_code' => $item->product_code,
  493. 'product_title' => $item->product_title,
  494. 'product_size' => $item->product_size,
  495. 'unit' => $item->unit,
  496. 'quantity' => $item->quantity,
  497. 'price_1' => $item->price_1,
  498. 'price_1_total' => $item->price_1_total,
  499. 'price_2' => $item->price_2,
  500. 'price_2_total' => $item->price_2_total,
  501. 'price_3' => $item->price_3,
  502. 'price_3_total' => $item->price_3_total,
  503. 'price_4' => $item->price_4,
  504. 'price_4_total' => $item->price_4_total,
  505. 'profit' => $item->profit,
  506. 'profit_rate' => $item->profit_rate,
  507. 'id_detail' => $item->id_detail,
  508. 'order_type' => $item->order_type,
  509. 'payment_amount' => $item->payment_amount ?? 0,
  510. 'id_detail_upstream' => $item->id_detail_upstream?? 0,
  511. 'order_number_upstream' => $item->order_number_upstream ?? "",
  512. 'is_activity' => $item->is_activity ?? 0,
  513. 'customer_profit_rate' => $item->customer_profit_rate ?? '',
  514. 'crt_time' => $time,
  515. ];
  516. })->toArray();
  517. // 每批单独插入(可选:加小事务)
  518. RevenueCost::insert($data);
  519. // 更新 lastId
  520. $lastId = $chunk->last()->id;
  521. } while ($chunk->count() == $batchSize);
  522. // 3. 更新主表
  523. list($status, $msg) = $this->updateRevenueCostTotal($ergs);
  524. if (! $status) {
  525. throw new \Exception($msg);
  526. }
  527. });
  528. }catch (\Throwable $exception){
  529. return [false, "单据明细同步异常" . $exception->getMessage() . "|" . $exception->getLine() . "|" . $exception->getFile()];
  530. }
  531. return [true, ''];
  532. }
  533. private function updateRevenueCostTotal($data){
  534. try {
  535. $start_timeStamp = $data['start_timeStamp'];
  536. $end_timeStamp = $data['end_timeStamp'];
  537. $time = time();
  538. //组织写入数据
  539. $return = [];
  540. $update_stamp = [];
  541. DB::table('revenue_cost')
  542. ->where('del_time',0)
  543. ->where('order_time', '>=', $start_timeStamp)
  544. ->where('order_time', '<=', $end_timeStamp)
  545. ->select(RevenueCost::$field)
  546. ->chunkById(100, function ($data) use(&$return,&$update_stamp){
  547. $dataArray = Collect($data)->map(function ($object){
  548. return (array)$object;
  549. })->toArray();
  550. foreach ($dataArray as $value){
  551. //变成每个月第一天的时间戳
  552. $time = date("Y-m-01", $value['order_time']);
  553. $stamp = strtotime($time);
  554. if(! in_array($stamp, $update_stamp)) $update_stamp[] = $stamp;
  555. if($value['order_type'] == RevenueCost::ORDER_ONE){
  556. $income = $value['price_3_total'];
  557. }elseif ($value['order_type'] == RevenueCost::ORDER_TWO){
  558. $income = $value['price_1_total'];
  559. }else{
  560. $income = $value['payment_amount'];
  561. }
  562. $adjust = $income < 0 ? $income : 0;
  563. $business = $value['price_4_total'];
  564. if(isset($return[$stamp][$value['order_type']][$value['employee_id_1']])){
  565. $income_total = bcadd($return[$stamp][$value['order_type']][$value['employee_id_1']]['income'], $income,2);
  566. $adjust_total = bcadd($return[$stamp][$value['order_type']][$value['employee_id_1']]['adjust'], $adjust,2);
  567. $business_total = bcadd($return[$stamp][$value['order_type']][$value['employee_id_1']]['business'], $business,2);
  568. $return[$stamp][$value['order_type']][$value['employee_id_1']]['income'] = $income_total;
  569. $return[$stamp][$value['order_type']][$value['employee_id_1']]['adjust'] = $adjust_total;
  570. $return[$stamp][$value['order_type']][$value['employee_id_1']]['business'] = $business_total;
  571. }else{
  572. $return[$stamp][$value['order_type']][$value['employee_id_1']] = [
  573. 'income' => $income,
  574. 'adjust' => $adjust,
  575. 'business' => $business,
  576. 'order_time' => $stamp,
  577. 'employee_id_1_title' => $value['employee_id_1_title'],
  578. ];
  579. }
  580. }
  581. });
  582. $insert = [];
  583. foreach ($return as $value){
  584. foreach ($value as $order_type => $val){
  585. foreach ($val as $employee_id => $v){
  586. $profit = bcsub($v['income'], $v['business'],2);
  587. $profit_rate = $v['income'] > 0 ? bcdiv($profit, $v['income'],2) : 0;
  588. $v['profit'] = $profit;
  589. $v['profit_rate'] = $profit_rate;
  590. $v['order_type'] = $order_type;
  591. $v['employee_id_1'] = $employee_id;
  592. $v['crt_time'] = $time;
  593. $insert[] = $v;
  594. }
  595. }
  596. }
  597. RevenueCostTotal::where('del_time', 0)
  598. ->whereIn('order_time', $update_stamp)
  599. ->update(['del_time' => $time]);
  600. RevenueCostTotal::insert($insert);
  601. }catch (\Throwable $exception){
  602. return [false, "主表同步异常" . $exception->getMessage() . "|" . $exception->getLine() . "|" . $exception->getFile()];
  603. }
  604. return [true, ''];
  605. }
  606. private function createTmpTable(){
  607. $table = $this->table;
  608. if (! Schema::hasTable($table)) {
  609. // 可以通过 migration 创建,或程序启动时检查
  610. Schema::create($table, function (Blueprint $table) {
  611. $table->bigIncrements('id'); // BIGINT UNSIGNED AUTO_INCREMENT PRIMARY KEY
  612. $table->integer('order_type')->default(0);
  613. $table->bigInteger('order_id')->default(0);
  614. $table->string('order_number', 50)->default('');
  615. $table->integer('order_time')->nullable();
  616. $table->string('employee_id_1_title', 100)->default('');
  617. $table->bigInteger('employee_id_1')->default(0);
  618. $table->bigInteger('employee_id_2')->default(0);
  619. $table->string('employee_id_2_title', 100)->default('');
  620. $table->string('customer_code', 50)->default('');
  621. $table->string('customer_title', 100)->default('');
  622. $table->string('channel_finance', 50)->nullable();
  623. $table->string('channel_details', 50)->nullable();
  624. $table->string('product_code', 50)->default('');
  625. $table->string('product_title', 100)->default('');
  626. $table->string('product_size', 100)->nullable();
  627. $table->string('unit', 20)->nullable();
  628. $table->decimal('quantity', 12, 2)->default(0);
  629. $table->decimal('price_1', 12, 2)->default(0); // 销项成本
  630. $table->decimal('price_1_total', 12, 2)->default(0);
  631. $table->decimal('price_2', 12, 2)->default(0); // 运费
  632. $table->decimal('price_2_total', 12, 2)->default(0);
  633. $table->decimal('price_3', 12, 2)->default(0); // 含税单价
  634. $table->decimal('price_3_total', 12, 2)->default(0); // 含税金额
  635. $table->decimal('price_4', 12, 2)->default(0); // 业务成本
  636. $table->decimal('price_4_total', 12, 2)->default(0);
  637. $table->decimal('profit', 12, 2)->default(0);
  638. $table->decimal('payment_amount', 12, 2)->default(0);
  639. $table->decimal('profit_rate', 10, 3)->default(0);
  640. $table->bigInteger('id_detail')->default(0);
  641. $table->bigInteger('id_detail_upstream')->default(0);
  642. $table->string('order_number_upstream', 100)->nullable();
  643. $table->decimal('is_activity', 2, 0)->default(0);
  644. $table->string('customer_profit_rate', 20)->default('');
  645. });
  646. }
  647. }
  648. public function clearTmpTable(){
  649. if (Schema::hasTable($this->table)) DB::table($this->table)->truncate();
  650. }
  651. public function delTableKey(){
  652. $this->dellimitingSendRequest($this->table);
  653. }
  654. }