TPlusServerService.php 36 KB

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