TPlusServerService.php 47 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984
  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\EmployeeIndex;
  8. use App\Model\Product;
  9. use App\Model\RevenueCost;
  10. use App\Model\RevenueCostTotal;
  11. use App\Model\SalaryEmployee;
  12. use Illuminate\Database\Schema\Blueprint;
  13. use Illuminate\Support\Facades\DB;
  14. use Illuminate\Support\Facades\Schema;
  15. class TPlusServerService extends Service
  16. {
  17. /**
  18. * @var TPlusDatabaseServerService
  19. */
  20. protected $databaseService;
  21. /**
  22. * @var string|null
  23. */
  24. protected $error;
  25. /**
  26. * TPlusServerService constructor.
  27. */
  28. public function __construct()
  29. {
  30. $service = new TPlusDatabaseServerService();
  31. $this->databaseService = $service->db;
  32. $this->error = $service->error;
  33. }
  34. /**
  35. * 获取错误信息
  36. *
  37. * @return string|null
  38. */
  39. public function getError()
  40. {
  41. return $this->error;
  42. }
  43. private $table = "tmp_revenue_cost_data";
  44. private $table_2 = "tmp_salary_employee";
  45. /**
  46. * 同步人员部门
  47. *
  48. * @param array $data
  49. * @param array $user
  50. * @return array
  51. */
  52. public function synPersonDepart($data, $user)
  53. {
  54. try {
  55. $this->databaseService->table('AA_Department')
  56. ->select('id','idparent as parent_id','name as title','code','disabled as is_use')
  57. ->chunkById(100, function ($data) {
  58. DB::transaction(function () use ($data) {
  59. $dataArray = Collect($data)->map(function ($object) {
  60. return (array)$object;
  61. })->toArray();
  62. $d_id = Depart::whereIn('id', array_column($dataArray,'id'))
  63. ->pluck('id')
  64. ->toArray();
  65. $insert = $update = [];
  66. foreach ($dataArray as $value){
  67. $is_use = $value['is_use'] ? 0 : 1;
  68. if(in_array($value['id'], $d_id)){
  69. $update[] = [
  70. 'id' => $value['id'],
  71. 'parent_id' => $value['parent_id'],
  72. 'title' => $value['title'],
  73. 'code' => $value['code'],
  74. 'is_use' => $is_use
  75. ];
  76. }else{
  77. $insert[] = [
  78. 'id' => $value['id'],
  79. 'parent_id' => $value['parent_id'],
  80. 'title' => $value['title'],
  81. 'code' => $value['code'],
  82. 'is_use' => $is_use
  83. ];
  84. }
  85. }
  86. if(! empty($insert)) Depart::insert($insert);
  87. if(! empty($update)) {
  88. foreach ($update as $value){
  89. Depart::where('id', $value['id'])
  90. ->update($value);
  91. }
  92. }
  93. });
  94. });
  95. $this->databaseService->table('AA_Person')
  96. ->select('id','code as number','name as emp_name','mobilePhoneNo as mobile','iddepartment as depart_id','disabled as state')
  97. ->chunkById(100, function ($data) {
  98. DB::transaction(function () use ($data) {
  99. $dataArray = Collect($data)->map(function ($object) {
  100. return (array)$object;
  101. })->toArray();
  102. $employee_id = Employee::whereIn('id', array_column($dataArray,'id'))
  103. ->pluck('id')
  104. ->toArray();
  105. $insert = $update = $depart_update = [];
  106. foreach ($dataArray as $value){
  107. $state = $value['state'] ? Employee::NOT_USE : Employee::USE;
  108. if(in_array($value['id'], $employee_id)){
  109. $update[] = [
  110. 'id' => $value['id'],
  111. 'number' => $value['number'],
  112. 'emp_name' => $value['emp_name'],
  113. 'mobile' => $value['mobile'],
  114. 'state' => $state
  115. ];
  116. }else{
  117. $insert[] = [
  118. 'id' => $value['id'],
  119. 'number' => $value['number'],
  120. 'emp_name' => $value['emp_name'],
  121. 'mobile' => $value['mobile'],
  122. 'state' => $state
  123. ];
  124. }
  125. $depart_update[] = [
  126. 'employee_id' => $value['id'],
  127. 'depart_id' => $value['depart_id']
  128. ];
  129. }
  130. if(! empty($insert)) Employee::insert($insert);
  131. if(! empty($update)) {
  132. foreach ($update as $value){
  133. Employee::where('id', $value['id'])
  134. ->update($value);
  135. }
  136. }
  137. if(! empty($depart_update)){
  138. EmployeeDepartPermission::whereIn('employee_id',array_column($depart_update,'employee_id'))->delete();
  139. EmployeeDepartPermission::insert($depart_update);
  140. }
  141. });
  142. });
  143. } catch (\Throwable $e) {
  144. return [false, $e->getMessage()];
  145. }
  146. return [true, ''];
  147. }
  148. /**
  149. * 收入成本统计同步
  150. *
  151. * @param array $data
  152. * @param array $user
  153. * @return array
  154. */
  155. public function synRevenueCost($data, $user){
  156. if(empty($data['crt_time'][0]) || empty($data['crt_time'][1])) return [false, '同步时间不能为空'];
  157. list($start_time, $end_time) = $this->changeDateToTimeStampAboutRange($data['crt_time'],false);
  158. if ($start_time === null || $end_time === null || $start_time > $end_time) return [false, "同步时间:时间区间无效"];
  159. list($bool, $bool_msg) = $this->isOverThreeMonths($start_time, $end_time);
  160. if(! $bool) return [false, $bool_msg];
  161. $data['start_timeStamp'] = $start_time;
  162. $data['end_timeStamp'] = $end_time;
  163. $start = date('Y-m-d H:i:s.000', $start_time);
  164. $end = date('Y-m-d H:i:s.000', $end_time);
  165. $data['start_time'] = $start;
  166. $data['end_time'] = $end;
  167. $data['operation_time'] = time();
  168. if(empty($data['type'])) return [false, '同步类型不能为空'];
  169. if(in_array($data['type'],[1,2,3,4])){
  170. list($status,$msg) = $this->limitingSendRequest($this->table);
  171. if(! $status) return [false, '收入成本相关信息同步正在后台运行,请稍后'];
  172. // //同步
  173. // list($status, $msg) = $this->synRevenueCostFromTPlus($data, $user);
  174. // if(! $status) {
  175. // $this->clearTmpTable();
  176. // $this->dellimitingSendRequest($this->table);
  177. // return [false, $msg];
  178. // }
  179. //队列
  180. ProcessDataJob::dispatch($data, $user)->onQueue(RevenueCost::job);
  181. }else{
  182. return [false, '同步类型错误'];
  183. }
  184. return [true, '收入成本相关信息同步已进入后台任务'];
  185. }
  186. public function synRevenueCostFromTPlus($data, $user){
  187. //创建临时表 如果不存在
  188. $this->createTmpTable();
  189. //清理临时表 如果内容不为空
  190. $this->clearTmpTable();
  191. $type = $data['type'];
  192. //写入临时数据
  193. if($type == 1){
  194. list($status, $msg) = $this->xhdTPlus($data, $user);
  195. if(! $status) return [false, $msg];
  196. list($status, $msg) = $this->xsfpTPlus($data, $user);
  197. if(! $status) return [false, $msg];
  198. list($status, $msg) = $this->hkdTPlus($data, $user);
  199. if(! $status) return [false, $msg];
  200. }elseif ($type == 2){
  201. list($status, $msg) = $this->xhdTPlus($data, $user);
  202. if(! $status) return [false, $msg];
  203. }elseif ($type == 3){
  204. list($status, $msg) = $this->xsfpTPlus($data, $user);
  205. if(! $status) return [false, $msg];
  206. }elseif ($type == 4){
  207. list($status, $msg) = $this->hkdTPlus($data, $user);
  208. if(! $status) return [false, $msg];
  209. }
  210. //更新数据
  211. list($status,$msg) = $this->updateRevenueCost($data);
  212. if(! $status) return [false, $msg];
  213. // //更新主表数据
  214. // list($status,$msg) = $this->updateRevenueCostTotal($data);
  215. // if(! $status) return [false, $msg];
  216. //都成功后 清理临时表
  217. $this->clearTmpTable();
  218. //释放redis
  219. $this->delTableKey();
  220. return [true, '同步成功'];
  221. }
  222. private function xhdTPlus($data, $user){
  223. try {
  224. $table = $this->table;
  225. $limit = 500;
  226. $lastId = 0;
  227. do {
  228. $rows = $this->databaseService->table('SA_SaleDelivery_b as sd_b')
  229. ->join('SA_SaleDelivery as sd', 'sd_b.idSaleDeliveryDTO', '=', 'sd.ID')
  230. ->leftJoin('AA_Partner as pn', 'sd.idsettlecustomer', '=', 'pn.ID')
  231. ->leftJoin('AA_Person as ps', 'sd.idclerk', '=', 'ps.ID')
  232. ->leftJoin('AA_Person as ps2', 'pn.idsaleman', '=', 'ps2.ID')
  233. ->leftJoin('AA_Inventory as it', 'sd_b.idinventory', '=', 'it.ID')
  234. ->leftJoin('AA_Unit as ui', 'sd_b.idbaseunit', '=', 'ui.ID')
  235. ->where('sd.voucherdate', '>=', $data['start_time'])
  236. ->where('sd.voucherdate', '<=', $data['end_time'])
  237. ->where('sd_b.ID', '>', $lastId) // 用真实字段
  238. ->orderBy('sd_b.ID')
  239. ->limit($limit)
  240. ->selectRaw("
  241. COALESCE(sd.ID, 0) as order_id,
  242. COALESCE(sd.code, '') as order_number,
  243. sd.voucherdate as order_time,
  244. COALESCE(ps.name, '') as employee_id_1_title,
  245. COALESCE(sd.idclerk, 0) as employee_id_1,
  246. COALESCE(ps2.name, '') as employee_id_2_title,
  247. COALESCE(pn.idsaleman, 0) as employee_id_2,
  248. COALESCE(pn.code, '') as customer_code,
  249. COALESCE(pn.name, '') as customer_title,
  250. COALESCE(pn.priuserdefnvc14, '') as customer_profit_rate,
  251. COALESCE(sd.pubuserdefnvc11, '') as channel_finance,
  252. COALESCE(sd.pubuserdefnvc12, '') as channel_details,
  253. COALESCE(it.code, '') as product_code,
  254. COALESCE(it.name, '') as product_title,
  255. COALESCE(it.specification, '') as product_size,
  256. COALESCE(ui.name, '') as unit,
  257. COALESCE(sd_b.quantity, 0) as quantity,
  258. COALESCE(sd_b.taxPrice, 0) as price_3,
  259. COALESCE(sd_b.taxAmount, 0) as price_3_total,
  260. COALESCE(sd_b.ID, 0) as id_detail,
  261. COALESCE(sd_b.pubuserdefdecm9, 0) as is_activity
  262. ")
  263. ->get();
  264. if ($rows->isEmpty()) break;
  265. $dataArray = Collect($rows)->map(function ($object) {
  266. return (array)$object;
  267. })->toArray();
  268. //存货档案
  269. $product = Product::where('del_time', 0)
  270. ->whereIn('code', array_unique(array_column($dataArray, 'product_code')))
  271. ->select('code', 'write_off_price', 'freight_price', 'business_cost')
  272. ->get()->toArray();
  273. $product_map = array_column($product, null, 'code');
  274. //组织数据
  275. foreach ($dataArray as $key => $value) {
  276. $customer_profit_rate = rtrim($value['customer_profit_rate'],'%');
  277. if(is_numeric($customer_profit_rate)){
  278. $customer_profit_rate = bcdiv($customer_profit_rate,100,3);
  279. }else{
  280. $customer_profit_rate = 0;
  281. }
  282. $dataArray[$key]['customer_profit_rate'] = $customer_profit_rate;
  283. $p_tmp = $product_map[$value['product_code']] ?? [];
  284. $dataArray[$key]['order_type'] = RevenueCost::ORDER_ONE;
  285. $dataArray[$key]['order_time'] = strtotime($value['order_time']);
  286. $write_off_price = $p_tmp['write_off_price'] ?? 0;
  287. $dataArray[$key]['price_1'] = $write_off_price;
  288. $dataArray[$key]['price_1_total'] = bcmul($write_off_price, $value['quantity'], 2);
  289. $freight_price = $p_tmp['freight_price'] ?? 0;
  290. $dataArray[$key]['price_2'] = $freight_price;
  291. $dataArray[$key]['price_2_total'] = bcmul($freight_price, $value['quantity'], 2);
  292. $business_cost = $p_tmp['business_cost'] ?? 0;
  293. $dataArray[$key]['price_4'] = $business_cost;
  294. $price_4_total = bcmul($business_cost, $value['quantity'], 2);
  295. $dataArray[$key]['price_4_total'] = bcmul($business_cost, $value['quantity'], 2);
  296. $profit = bcsub($value['price_3_total'], $price_4_total, 2);
  297. $dataArray[$key]['profit'] = $profit;
  298. $dataArray[$key]['profit_rate'] = $value['price_3_total'] > 0 ? bcdiv($profit, $value['price_3_total'], 2) : 0;
  299. }
  300. DB::table($table)->insert($dataArray);
  301. // 更新 lastId 继续下一批
  302. $lastId = end($dataArray)['id_detail'] ?? $lastId;
  303. } while (count($rows) === $limit);
  304. }catch (\Throwable $exception){
  305. return [false, "销货单同步异常" . $exception->getMessage() . "|" . $exception->getLine() . "|" . $exception->getFile()];
  306. }
  307. return [true, ''];
  308. }
  309. private function xsfpTPlus($data, $user){
  310. try {
  311. $table = $this->table;
  312. $limit = 500;
  313. $lastId = 0;
  314. do {
  315. $rows = $this->databaseService->table('SA_SaleInvoice_b as si_b')
  316. ->join('SA_SaleInvoice as si', 'si_b.idSaleInvoiceDTO', '=', 'si.ID')
  317. ->leftJoin('SA_SaleDelivery_b as sd_b', 'si_b.sourceVoucherDetailId', '=', 'sd_b.ID')
  318. ->leftJoin('AA_Partner as pn', 'si.idsettlecustomer', '=', 'pn.ID')
  319. ->leftJoin('AA_Person as ps', 'si.idclerk', '=', 'ps.ID')
  320. ->leftJoin('AA_Person as ps2', 'pn.idsaleman', '=', 'ps2.ID')
  321. ->leftJoin('AA_Inventory as it', 'si_b.idinventory', '=', 'it.ID')
  322. ->leftJoin('AA_Unit as ui', 'si_b.idbaseunit', '=', 'ui.ID')
  323. ->where('si.voucherdate','>=',$data['start_time'])
  324. ->where('si.voucherdate','<=',$data['end_time'])
  325. ->where('si_b.ID', '>', $lastId) // 用真实字段
  326. ->orderBy('si_b.ID')
  327. ->limit($limit)
  328. ->selectRaw("
  329. COALESCE(si.ID, 0) as order_id,
  330. COALESCE(si.code, '') as order_number,
  331. si.voucherdate as order_time,
  332. COALESCE(pn.code, '') as customer_code,
  333. COALESCE(pn.name, '') as customer_title,
  334. COALESCE(pn.priuserdefnvc14, '') as customer_profit_rate,
  335. COALESCE(si.idclerk, 0) as employee_id_1,
  336. COALESCE(ps.name, '') as employee_id_1_title,
  337. COALESCE(pn.idsaleman, 0) as employee_id_2,
  338. COALESCE(ps2.name, '') as employee_id_2_title,
  339. COALESCE(it.code, '') as product_code,
  340. COALESCE(it.name, '') as product_title,
  341. COALESCE(it.specification, '') as product_size,
  342. COALESCE(ui.name, '') as unit,
  343. COALESCE(si_b.quantity, 0) as quantity,
  344. COALESCE(si_b.taxPrice, 0) as price_1,
  345. COALESCE(si_b.taxAmount, 0) as price_1_total,
  346. COALESCE(si_b.ID, 0) as id_detail,
  347. COALESCE(si_b.sourceVoucherDetailId, 0) as id_detail_upstream,
  348. COALESCE(si_b.sourceVoucherCode, '') as order_number_upstream,
  349. COALESCE(sd_b.pubuserdefdecm9, 0) as is_activity
  350. ")
  351. ->get();
  352. if ($rows->isEmpty()) break;
  353. $dataArray = Collect($rows)->map(function ($object) {
  354. return (array)$object;
  355. })->toArray();
  356. //存货档案
  357. $product = Product::where('del_time',0)
  358. ->whereIn('code', array_unique(array_column($dataArray,'product_code')))
  359. ->select('code','business_cost')
  360. ->get()->toArray();
  361. $product_map = array_column($product,null,'code');
  362. //组织数据
  363. foreach ($dataArray as $key => $value){
  364. $customer_profit_rate = rtrim($value['customer_profit_rate'],'%');
  365. if(is_numeric($customer_profit_rate)){
  366. $customer_profit_rate = bcdiv($customer_profit_rate,100,3);
  367. }else{
  368. $customer_profit_rate = 0;
  369. }
  370. $dataArray[$key]['customer_profit_rate'] = $customer_profit_rate;
  371. $p_tmp = $product_map[$value['product_code']] ?? [];
  372. $dataArray[$key]['order_type'] = RevenueCost::ORDER_TWO;
  373. $dataArray[$key]['order_time'] = strtotime($value['order_time']);
  374. $business_cost = $p_tmp['business_cost'] ?? 0;
  375. $dataArray[$key]['price_4'] = $business_cost;
  376. $price_4_total = bcmul($business_cost, $value['quantity'],2);
  377. $dataArray[$key]['price_4_total'] = bcmul($business_cost, $value['quantity'],2);
  378. $profit = bcsub($value['price_1_total'], $price_4_total,2);
  379. $dataArray[$key]['profit'] = $profit;
  380. $dataArray[$key]['profit_rate'] = $value['price_1_total'] > 0 ? bcdiv($profit, $value['price_1_total'],2) : 0;
  381. }
  382. DB::table($table)->insert($dataArray);
  383. // 更新 lastId 继续下一批
  384. $lastId = end($dataArray)['id_detail'] ?? $lastId;
  385. } while (count($rows) === $limit);
  386. }catch (\Throwable $exception){
  387. return [false, "销售发票同步异常" . $exception->getMessage() . "|" . $exception->getLine() . "|" . $exception->getFile()];
  388. }
  389. return [true, ''];
  390. }
  391. private function hkdTPlus($data, $user){
  392. try{
  393. $table = $this->table;
  394. $limit = 500;
  395. $lastId = 0;
  396. do {
  397. $rows = $this->databaseService->table('ARAP_ReceivePayment_b as rp_b')
  398. ->join('ARAP_ReceivePayment as rp', 'rp_b.idArapReceivePaymentDTO', '=', 'rp.ID')
  399. ->leftJoin('SA_SaleInvoice_b as si_b', 'rp_b.voucherDetailID', '=', 'si_b.ID')
  400. ->leftJoin('SA_SaleInvoice as si', 'si_b.idSaleInvoiceDTO', '=', 'si.ID')
  401. ->leftJoin('SA_SaleDelivery_b as sd_b', 'si_b.sourceVoucherDetailId', '=', 'sd_b.ID')
  402. ->leftJoin('AA_Partner as pn', 'si.idsettlecustomer', '=', 'pn.ID')
  403. ->leftJoin('AA_Person as ps', 'rp.idperson', '=', 'ps.ID')
  404. ->leftJoin('AA_Person as ps2', 'pn.idsaleman', '=', 'ps2.ID')
  405. ->leftJoin('AA_Inventory as it', 'si_b.idinventory', '=', 'it.ID')
  406. ->leftJoin('AA_Unit as ui', 'si_b.idbaseunit', '=', 'ui.ID')
  407. ->where('rp.voucherdate','>=',$data['start_time'])
  408. ->where('rp.voucherdate','<=',$data['end_time'])
  409. ->where('rp_b.idvouchertype','=', 20) // 销售发票
  410. ->where('rp.isReceiveFlag','=', 1)
  411. ->where('rp_b.ID', '>', $lastId)
  412. ->orderBy('rp_b.ID')
  413. ->limit($limit)
  414. ->selectRaw("
  415. COALESCE(rp.ID, 0) as order_id,
  416. COALESCE(rp.code, '') as order_number,
  417. rp.voucherdate as order_time,
  418. COALESCE(pn.code, '') as customer_code,
  419. COALESCE(pn.name, '') as customer_title,
  420. COALESCE(pn.priuserdefnvc14, '') as customer_profit_rate,
  421. COALESCE(it.code, '') as product_code,
  422. COALESCE(it.name, '') as product_title,
  423. COALESCE(rp.idperson, 0) as employee_id_1,
  424. COALESCE(ps.name, '') as employee_id_1_title,
  425. COALESCE(pn.idsaleman, 0) as employee_id_2,
  426. COALESCE(ps2.name, '') as employee_id_2_title,
  427. COALESCE(it.specification, '') as product_size,
  428. COALESCE(ui.name, '') as unit,
  429. COALESCE(si_b.quantity, 0) as quantity,
  430. COALESCE(si_b.taxPrice, 0) as price_1,
  431. COALESCE(si_b.taxAmount, 0) as price_1_total,
  432. COALESCE(rp_b.amount, 0) as payment_amount,
  433. COALESCE(rp_b.ID, 0) as id_detail,
  434. COALESCE(rp_b.voucherDetailID, 0) as id_detail_upstream,
  435. COALESCE(rp_b.voucherCode, '') as order_number_upstream,
  436. COALESCE(sd_b.pubuserdefdecm9, 0) as is_activity
  437. ")
  438. ->get();
  439. if ($rows->isEmpty()) break;
  440. $dataArray = Collect($rows)->map(function ($object) {
  441. return (array)$object;
  442. })->toArray();
  443. //存货档案
  444. $product = Product::where('del_time',0)
  445. ->whereIn('code', array_unique(array_column($dataArray,'product_code')))
  446. ->select('code','business_cost')
  447. ->get()->toArray();
  448. $product_map = array_column($product,null,'code');
  449. //组织数据
  450. foreach ($dataArray as $key => $value){
  451. $customer_profit_rate = rtrim($value['customer_profit_rate'],'%');
  452. if(is_numeric($customer_profit_rate)){
  453. $customer_profit_rate = bcdiv($customer_profit_rate,100,3);
  454. }else{
  455. $customer_profit_rate = 0;
  456. }
  457. $dataArray[$key]['customer_profit_rate'] = $customer_profit_rate;
  458. $p_tmp = $product_map[$value['product_code']] ?? [];
  459. $dataArray[$key]['order_type'] = RevenueCost::ORDER_THREE;
  460. $dataArray[$key]['order_time'] = strtotime($value['order_time']);
  461. $business_cost = $p_tmp['business_cost'] ?? 0;
  462. $dataArray[$key]['price_4'] = $business_cost;
  463. $price_4_total = bcmul($business_cost, $value['quantity'],2);
  464. $dataArray[$key]['price_4_total'] = $price_4_total;
  465. $profit = bcsub($value['price_1_total'], $price_4_total,2);
  466. $dataArray[$key]['profit'] = $profit;
  467. $dataArray[$key]['profit_rate'] = $value['price_1_total'] > 0 ? bcdiv($profit, $value['price_1_total'],2) : 0;
  468. }
  469. DB::table($table)->insert($dataArray);
  470. // 更新 lastId 继续下一批
  471. $lastId = end($dataArray)['id_detail'] ?? $lastId;
  472. } while (count($rows) === $limit);
  473. }catch (\Throwable $exception){
  474. return [false, "回款单同步异常" . $exception->getMessage() . "|" . $exception->getLine() . "|" . $exception->getFile()];
  475. }
  476. return [true, ''];
  477. }
  478. private function updateRevenueCost($data){
  479. try {
  480. $start_timeStamp = $data['start_timeStamp'];
  481. $end_timeStamp = $data['end_timeStamp'];
  482. $tmpTable = $this->table;
  483. $time = time();
  484. $ergs = $data;
  485. DB::transaction(function () use ($start_timeStamp, $end_timeStamp, $tmpTable,$time, $ergs) {
  486. // 1. 先软删除旧数据(你已有)
  487. RevenueCost::where('del_time', 0)
  488. ->where('order_time', '>=', $start_timeStamp)
  489. ->where('order_time', '<=', $end_timeStamp)
  490. ->update(['del_time' => $time]);
  491. // 2. 分批从临时表插入新数据
  492. $batchSize = 500;
  493. $lastId = 0;
  494. do {
  495. $chunk = DB::table($tmpTable)
  496. ->where('id', '>', $lastId)
  497. ->orderBy('id')
  498. ->limit($batchSize)
  499. ->get();
  500. if ($chunk->isEmpty()) {
  501. break;
  502. }
  503. $data = $chunk->map(function ($item) use($time){
  504. return [
  505. 'order_id' => $item->order_id,
  506. 'order_number' => $item->order_number,
  507. 'order_time' => $item->order_time,
  508. 'employee_id_1_title' => $item->employee_id_1_title,
  509. 'employee_id_1' => $item->employee_id_1 ?? 0,
  510. 'employee_id_2' => $item->employee_id_2 ?? 0,
  511. 'employee_id_2_title' => $item->employee_id_2_title ?? "",
  512. 'customer_code' => $item->customer_code,
  513. 'customer_title' => $item->customer_title,
  514. 'channel_finance' => $item->channel_finance,
  515. 'channel_details' => $item->channel_details,
  516. 'product_code' => $item->product_code,
  517. 'product_title' => $item->product_title,
  518. 'product_size' => $item->product_size,
  519. 'unit' => $item->unit,
  520. 'quantity' => $item->quantity,
  521. 'price_1' => $item->price_1,
  522. 'price_1_total' => $item->price_1_total,
  523. 'price_2' => $item->price_2,
  524. 'price_2_total' => $item->price_2_total,
  525. 'price_3' => $item->price_3,
  526. 'price_3_total' => $item->price_3_total,
  527. 'price_4' => $item->price_4,
  528. 'price_4_total' => $item->price_4_total,
  529. 'profit' => $item->profit,
  530. 'profit_rate' => $item->profit_rate,
  531. 'id_detail' => $item->id_detail,
  532. 'order_type' => $item->order_type,
  533. 'payment_amount' => $item->payment_amount ?? 0,
  534. 'id_detail_upstream' => $item->id_detail_upstream?? 0,
  535. 'order_number_upstream' => $item->order_number_upstream ?? "",
  536. 'is_activity' => $item->is_activity ?? 0,
  537. 'customer_profit_rate' => $item->customer_profit_rate ?? '',
  538. 'crt_time' => $time,
  539. ];
  540. })->toArray();
  541. // 每批单独插入(可选:加小事务)
  542. RevenueCost::insert($data);
  543. // 更新 lastId
  544. $lastId = $chunk->last()->id;
  545. } while ($chunk->count() == $batchSize);
  546. // 3. 更新主表
  547. list($status, $msg) = $this->updateRevenueCostTotal($ergs);
  548. if (! $status) {
  549. throw new \Exception($msg);
  550. }
  551. });
  552. }catch (\Throwable $exception){
  553. return [false, "单据明细同步异常" . $exception->getMessage() . "|" . $exception->getLine() . "|" . $exception->getFile()];
  554. }
  555. return [true, ''];
  556. }
  557. private function updateRevenueCostTotal($data){
  558. try {
  559. $start_timeStamp = $data['start_timeStamp'];
  560. $end_timeStamp = $data['end_timeStamp'];
  561. $time = time();
  562. //组织写入数据
  563. $return = [];
  564. $update_stamp = [];
  565. DB::table('revenue_cost')
  566. ->where('del_time',0)
  567. ->where('order_time', '>=', $start_timeStamp)
  568. ->where('order_time', '<=', $end_timeStamp)
  569. ->select(RevenueCost::$field)
  570. ->chunkById(100, function ($data) use(&$return,&$update_stamp){
  571. $dataArray = Collect($data)->map(function ($object){
  572. return (array)$object;
  573. })->toArray();
  574. foreach ($dataArray as $value){
  575. //变成每个月第一天的时间戳
  576. $time = date("Y-m-01", $value['order_time']);
  577. $stamp = strtotime($time);
  578. if(! in_array($stamp, $update_stamp)) $update_stamp[] = $stamp;
  579. if($value['order_type'] == RevenueCost::ORDER_ONE){
  580. $income = $value['price_3_total'];
  581. }elseif ($value['order_type'] == RevenueCost::ORDER_TWO){
  582. $income = $value['price_1_total'];
  583. }else{
  584. $income = $value['payment_amount'];
  585. }
  586. $adjust = $income < 0 ? $income : 0;
  587. $business = $value['price_4_total'];
  588. if(isset($return[$stamp][$value['order_type']][$value['employee_id_1']])){
  589. $income_total = bcadd($return[$stamp][$value['order_type']][$value['employee_id_1']]['income'], $income,2);
  590. $adjust_total = bcadd($return[$stamp][$value['order_type']][$value['employee_id_1']]['adjust'], $adjust,2);
  591. $business_total = bcadd($return[$stamp][$value['order_type']][$value['employee_id_1']]['business'], $business,2);
  592. $return[$stamp][$value['order_type']][$value['employee_id_1']]['income'] = $income_total;
  593. $return[$stamp][$value['order_type']][$value['employee_id_1']]['adjust'] = $adjust_total;
  594. $return[$stamp][$value['order_type']][$value['employee_id_1']]['business'] = $business_total;
  595. }else{
  596. $return[$stamp][$value['order_type']][$value['employee_id_1']] = [
  597. 'income' => $income,
  598. 'adjust' => $adjust,
  599. 'business' => $business,
  600. 'order_time' => $stamp,
  601. 'employee_id_1_title' => $value['employee_id_1_title'],
  602. ];
  603. }
  604. }
  605. });
  606. $insert = [];
  607. foreach ($return as $value){
  608. foreach ($value as $order_type => $val){
  609. foreach ($val as $employee_id => $v){
  610. $profit = bcsub($v['income'], $v['business'],2);
  611. $profit_rate = $v['income'] > 0 ? bcdiv($profit, $v['income'],2) : 0;
  612. $v['profit'] = $profit;
  613. $v['profit_rate'] = $profit_rate;
  614. $v['order_type'] = $order_type;
  615. $v['employee_id_1'] = $employee_id;
  616. $v['crt_time'] = $time;
  617. $insert[] = $v;
  618. }
  619. }
  620. }
  621. RevenueCostTotal::where('del_time', 0)
  622. ->whereIn('order_time', $update_stamp)
  623. ->update(['del_time' => $time]);
  624. RevenueCostTotal::insert($insert);
  625. }catch (\Throwable $exception){
  626. return [false, "主表同步异常" . $exception->getMessage() . "|" . $exception->getLine() . "|" . $exception->getFile()];
  627. }
  628. return [true, ''];
  629. }
  630. private function createTmpTable(){
  631. $table = $this->table;
  632. if (! Schema::hasTable($table)) {
  633. // 可以通过 migration 创建,或程序启动时检查
  634. Schema::create($table, function (Blueprint $table) {
  635. $table->bigIncrements('id'); // BIGINT UNSIGNED AUTO_INCREMENT PRIMARY KEY
  636. $table->integer('order_type')->default(0);
  637. $table->bigInteger('order_id')->default(0);
  638. $table->string('order_number', 50)->default('');
  639. $table->integer('order_time')->nullable();
  640. $table->string('employee_id_1_title', 100)->default('');
  641. $table->bigInteger('employee_id_1')->default(0);
  642. $table->bigInteger('employee_id_2')->default(0);
  643. $table->string('employee_id_2_title', 100)->default('');
  644. $table->string('customer_code', 50)->default('');
  645. $table->string('customer_title', 100)->default('');
  646. $table->string('channel_finance', 50)->nullable();
  647. $table->string('channel_details', 50)->nullable();
  648. $table->string('product_code', 50)->default('');
  649. $table->string('product_title', 100)->default('');
  650. $table->string('product_size', 100)->nullable();
  651. $table->string('unit', 20)->nullable();
  652. $table->decimal('quantity', 12, 2)->default(0);
  653. $table->decimal('price_1', 12, 2)->default(0); // 销项成本
  654. $table->decimal('price_1_total', 12, 2)->default(0);
  655. $table->decimal('price_2', 12, 2)->default(0); // 运费
  656. $table->decimal('price_2_total', 12, 2)->default(0);
  657. $table->decimal('price_3', 12, 2)->default(0); // 含税单价
  658. $table->decimal('price_3_total', 12, 2)->default(0); // 含税金额
  659. $table->decimal('price_4', 12, 2)->default(0); // 业务成本
  660. $table->decimal('price_4_total', 12, 2)->default(0);
  661. $table->decimal('profit', 12, 2)->default(0);
  662. $table->decimal('payment_amount', 12, 2)->default(0);
  663. $table->decimal('profit_rate', 10, 3)->default(0);
  664. $table->bigInteger('id_detail')->default(0);
  665. $table->bigInteger('id_detail_upstream')->default(0);
  666. $table->string('order_number_upstream', 100)->nullable();
  667. $table->decimal('is_activity', 2, 0)->default(0);
  668. $table->string('customer_profit_rate', 20)->default('');
  669. });
  670. }
  671. }
  672. public function clearTmpTable(){
  673. if (Schema::hasTable($this->table)) DB::table($this->table)->truncate();
  674. }
  675. public function delTableKey($type = 1){
  676. $key = $this->table;
  677. if($type == 2) $key = $this->table_2;
  678. $this->dellimitingSendRequest($key);
  679. }
  680. public function synSalaryEmployee($data, $user){
  681. if(empty($data['crt_time'][0]) || empty($data['crt_time'][1])) return [false, '同步时间不能为空'];
  682. list($start_time, $end_time) = $this->changeDateToTimeStampAboutRange($data['crt_time'],false);
  683. if ($start_time === null || $end_time === null || $start_time > $end_time) return [false, "同步时间:时间区间无效"];
  684. list($bool, $bool_msg) = $this->isOverThreeMonths($start_time, $end_time);
  685. if(! $bool) return [false, $bool_msg];
  686. $data['start_timeStamp'] = $start_time;
  687. $data['end_timeStamp'] = $end_time;
  688. $data['start_time'] = strtotime(date("Y-m-01",$data['start_timeStamp']));
  689. $data['end_time'] = strtotime(date("Y-m-01"),$data['end_timeStamp']);
  690. $data['operation_time'] = time();
  691. list($status,$msg) = $this->limitingSendRequest($this->table_2);
  692. if(! $status) return [false, '业务员工资同步正在后台运行,请稍后'];
  693. //同步
  694. // list($status, $msg) = $this->synSalaryEmployeeFromMine($data, $user);
  695. // if(! $status) {
  696. // $this->dellimitingSendRequest($this->table_2);
  697. // return [false, $msg];
  698. // }
  699. //队列
  700. ProcessDataJob::dispatch($data, $user, 2)->onQueue(RevenueCost::job2);
  701. return [true, '业务员工资相关信息同步已进入后台任务'];
  702. }
  703. public function synSalaryEmployeeFromMine($data, $user){
  704. //创建临时表 如果不存在
  705. $this->createTmpTable2();
  706. //清理临时表 如果内容不为空
  707. $this->clearTmpTable2();
  708. //写入临时表
  709. DB::table('revenue_cost')
  710. ->where('del_time', 0)
  711. ->where('order_type', RevenueCost::ORDER_THREE)
  712. ->where('order_time','>=',$data['start_timeStamp'])
  713. ->where('order_time','<=',$data['end_timeStamp'])
  714. ->select([
  715. 'employee_id_1',
  716. 'employee_id_1_title',
  717. 'order_time as time',
  718. DB::raw("DATE_FORMAT(FROM_UNIXTIME(order_time), '%Y-%m-01') as order_time"),
  719. DB::raw("SUM(payment_amount) as payment_amount"),
  720. DB::raw("SUM(CASE WHEN is_activity = 0 THEN payment_amount ELSE 0 END) as payment_amount_not_include_activity"),
  721. DB::raw("SUM(CASE WHEN is_activity = 1 THEN payment_amount ELSE 0 END) as payment_amount_activity"),
  722. DB::raw("SUM(CASE WHEN profit_rate < customer_profit_rate and is_activity = 0 THEN payment_amount ELSE 0 END) as payment_amount_lower_than_rate"),
  723. DB::raw("SUM(CASE WHEN profit_rate >= customer_profit_rate and is_activity = 0 THEN payment_amount ELSE 0 END) as payment_amount_greater_than_rate"),
  724. DB::raw("SUM(CASE WHEN profit_rate >= customer_profit_rate and is_activity = 0 THEN price_4_total ELSE 0 END) as business"),
  725. DB::raw("ROW_NUMBER() OVER (ORDER BY MIN(id)) as fake_id")
  726. ])
  727. ->groupBy('employee_id_1', DB::raw("DATE_FORMAT(FROM_UNIXTIME(order_time), '%Y-%m-01')"))
  728. ->orderBy('order_time', 'desc')
  729. ->chunkById(500, function ($data){
  730. $dataArray = Collect($data)->map(function ($object){
  731. return (array)$object;
  732. })->toArray();
  733. $indexes = $this->getEmployeeIndex($dataArray);
  734. foreach ($dataArray as $key => $value){
  735. $value['index_' . EmployeeIndex::TYPE_ONE] = 0;
  736. $value['index_' . EmployeeIndex::TYPE_SIX] = 0;
  737. $value['index_' . EmployeeIndex::TYPE_EIGHT] = 0;
  738. $this->findIndex($indexes, $value);
  739. $dataArray[$key]['order_type'] = RevenueCost::ORDER_THREE;
  740. $dataArray[$key]['order_time'] = strtotime($value['order_time']);
  741. $dataArray[$key]['sale_bonus'] = $value['index_' . EmployeeIndex::TYPE_EIGHT];
  742. $dataArray[$key]['index_' . EmployeeIndex::TYPE_ONE] = $value['index_' . EmployeeIndex::TYPE_ONE];
  743. $rate = bcdiv($value['index_' . EmployeeIndex::TYPE_ONE],100,2);
  744. $pay_in_advance = bcmul($rate, $value['payment_amount_greater_than_rate'],2);
  745. $dataArray[$key]['pay_in_advance'] = $pay_in_advance;
  746. $dataArray[$key]['basic_salary'] = $value['index_' . EmployeeIndex::TYPE_SIX];
  747. $dataArray[$key]['should_pay'] = bcadd(bcadd($value['index_' . EmployeeIndex::TYPE_EIGHT], $pay_in_advance,2),$value['index_' . EmployeeIndex::TYPE_SIX],2);
  748. unset($dataArray[$key]['fake_id']);
  749. unset($dataArray[$key]['time']);
  750. }
  751. DB::table($this->table_2)->insert($dataArray);
  752. }, 'fake_id');
  753. //更新数据
  754. list($status,$msg) = $this->updateSalaryEmployee($data);
  755. if(! $status) return [false, $msg];
  756. //清理临时表 如果内容不为空
  757. $this->clearTmpTable2();
  758. //释放redis
  759. $this->delTableKey(2);
  760. return [true, '同步成功'];
  761. }
  762. private function getEmployeeIndex($existingData)
  763. {
  764. if (empty($existingData)) {
  765. return collect();
  766. }
  767. // 取出所有涉及的 employee_id 和时间区间
  768. $employeeIds = array_column($existingData, 'employee_id_1');
  769. $time = array_column($existingData, 'time');
  770. $minStart = ! empty($time) ? min($time) : 0;
  771. $maxEnd = ! empty($time) ? max($time) : 0;
  772. // 一次性查出这些员工在最大区间范围内的所有指标
  773. $results = EmployeeIndex::where('del_time', 0)
  774. ->whereIn('type', [EmployeeIndex::TYPE_ONE, EmployeeIndex::TYPE_EIGHT, EmployeeIndex::TYPE_SIX])
  775. ->whereIn('employee_id', $employeeIds)
  776. ->where('start_time', '<=', $maxEnd)
  777. ->where('end_time', '>=', $minStart)
  778. ->select('start_time','end_time','employee_id','index','type')
  779. ->get();
  780. return $results;
  781. }
  782. private function findIndex($indexes, &$value){
  783. // 找到所有符合条件的 index(可能多个 type)
  784. $matchedIndexes = $indexes->filter(function ($item) use ($value) {
  785. return $item['employee_id'] == $value['employee_id_1']
  786. && $item['start_time'] <= $value['time']
  787. && $item['end_time'] >= $value['time'];
  788. });
  789. // 按 type 去重,只保留第一次出现的
  790. $uniqueByType = [];
  791. foreach ($matchedIndexes as $item) {
  792. $index = "index_" . $item['type'];
  793. if (! isset($uniqueByType[$index])) {
  794. $uniqueByType[$index] = $item['index'];
  795. }
  796. }
  797. $value = array_merge($value, $uniqueByType);
  798. }
  799. private function createTmpTable2(){
  800. $table = $this->table_2;
  801. if (! Schema::hasTable($table)) {
  802. // 可以通过 migration 创建,或程序启动时检查
  803. Schema::create($table, function (Blueprint $table) {
  804. $table->bigIncrements('id'); // BIGINT UNSIGNED AUTO_INCREMENT PRIMARY KEY
  805. $table->integer('order_type')->default(0);
  806. $table->integer('order_time')->default(0);
  807. $table->string('employee_id_1_title', 100)->default('');
  808. $table->bigInteger('employee_id_1')->default(0);
  809. $table->decimal('payment_amount', 12, 2)->default(0);
  810. $table->decimal('payment_amount_not_include_activity', 12, 2)->default(0);
  811. $table->decimal('payment_amount_activity', 12, 2)->default(0);
  812. $table->decimal('payment_amount_lower_than_rate', 12, 2)->default(0);
  813. $table->decimal('payment_amount_greater_than_rate', 12, 2)->default(0);
  814. $table->decimal('business', 12, 2)->default(0);
  815. $table->decimal('sale_bonus', 12, 2)->default(0);
  816. $table->decimal('index_1', 10, 2)->default(0);
  817. $table->decimal('pay_in_advance', 12, 2)->default(0);
  818. $table->decimal('basic_salary', 12, 2)->default(0);
  819. $table->decimal('should_pay', 12, 2)->default(0);
  820. });
  821. }
  822. }
  823. public function clearTmpTable2(){
  824. if (Schema::hasTable($this->table_2)) DB::table($this->table_2)->truncate();
  825. }
  826. private function updateSalaryEmployee($data){
  827. try {
  828. $start_timeStamp = $data['start_time'];
  829. $end_timeStamp = $data['end_time'];
  830. $tmpTable = $this->table_2;
  831. $time = time();
  832. $ergs = $data;
  833. DB::transaction(function () use ($start_timeStamp, $end_timeStamp, $tmpTable,$time, $ergs) {
  834. // 1. 先软删除旧数据(你已有)
  835. SalaryEmployee::where('del_time', 0)
  836. ->where('order_time', '>=', $start_timeStamp)
  837. ->where('order_time', '<=', $end_timeStamp)
  838. ->update(['del_time' => $time]);
  839. // 2. 分批从临时表插入新数据
  840. $batchSize = 500;
  841. $lastId = 0;
  842. do {
  843. $chunk = DB::table($tmpTable)
  844. ->where('id', '>', $lastId)
  845. ->orderBy('id')
  846. ->limit($batchSize)
  847. ->get();
  848. if ($chunk->isEmpty()) {
  849. break;
  850. }
  851. $data = $chunk->map(function ($item) use($time){
  852. return [
  853. 'order_type' => $item->order_type,
  854. 'order_time' => $item->order_time,
  855. 'employee_id_1_title' => $item->employee_id_1_title,
  856. 'employee_id_1' => $item->employee_id_1 ?? 0,
  857. 'payment_amount' => $item->payment_amount,
  858. 'payment_amount_not_include_activity' => $item->payment_amount_not_include_activity,
  859. 'payment_amount_activity' => $item->payment_amount_activity,
  860. 'payment_amount_lower_than_rate' => $item->payment_amount_lower_than_rate,
  861. 'payment_amount_greater_than_rate' => $item->payment_amount_greater_than_rate,
  862. 'business' => $item->business,
  863. 'sale_bonus' => $item->sale_bonus,
  864. 'index_1' => $item->index_1,
  865. 'pay_in_advance' => $item->pay_in_advance,
  866. 'basic_salary' => $item->basic_salary,
  867. 'should_pay' => $item->should_pay,
  868. 'crt_time' => $time,
  869. ];
  870. })->toArray();
  871. // 每批单独插入(可选:加小事务)
  872. SalaryEmployee::insert($data);
  873. // 更新 lastId
  874. $lastId = $chunk->last()->id;
  875. } while ($chunk->count() == $batchSize);
  876. });
  877. }catch (\Throwable $exception){
  878. return [false, "单据明细同步异常" . $exception->getMessage() . "|" . $exception->getLine() . "|" . $exception->getFile()];
  879. }
  880. return [true, ''];
  881. }
  882. }