TPlusServerService.php 70 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383
  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\Freight;
  9. use App\Model\FreightFee;
  10. use App\Model\Product;
  11. use App\Model\RevenueCost;
  12. use App\Model\RevenueCostTotal;
  13. use App\Model\SalaryEmployee;
  14. use Illuminate\Database\Schema\Blueprint;
  15. use Illuminate\Support\Facades\DB;
  16. use Illuminate\Support\Facades\Schema;
  17. class TPlusServerService extends Service
  18. {
  19. /**
  20. * @var TPlusDatabaseServerService
  21. */
  22. protected $databaseService;
  23. /**
  24. * @var string|null
  25. */
  26. protected $error;
  27. /**
  28. * TPlusServerService constructor.
  29. */
  30. public function __construct()
  31. {
  32. $service = new TPlusDatabaseServerService();
  33. $this->databaseService = $service->db;
  34. $this->error = $service->error;
  35. }
  36. /**
  37. * 获取错误信息
  38. *
  39. * @return string|null
  40. */
  41. public function getError()
  42. {
  43. return $this->error;
  44. }
  45. private $table = "tmp_revenue_cost_data";
  46. private $table_2 = "tmp_salary_employee";
  47. private $table_3 = "tmp_freight_fee";
  48. /**
  49. * 同步人员部门
  50. *
  51. * @param array $data
  52. * @param array $user
  53. * @return array
  54. */
  55. public function synPersonDepart($data, $user)
  56. {
  57. try {
  58. $this->databaseService->table('AA_Department')
  59. ->select('id','idparent as parent_id','name as title','code','disabled as is_use')
  60. ->chunkById(100, function ($data) {
  61. DB::transaction(function () use ($data) {
  62. $dataArray = Collect($data)->map(function ($object) {
  63. return (array)$object;
  64. })->toArray();
  65. $d_id = Depart::whereIn('id', array_column($dataArray,'id'))
  66. ->pluck('id')
  67. ->toArray();
  68. $insert = $update = [];
  69. foreach ($dataArray as $value){
  70. $is_use = $value['is_use'] ? 0 : 1;
  71. if(in_array($value['id'], $d_id)){
  72. $update[] = [
  73. 'id' => $value['id'],
  74. 'parent_id' => $value['parent_id'],
  75. 'title' => $value['title'],
  76. 'code' => $value['code'],
  77. 'is_use' => $is_use
  78. ];
  79. }else{
  80. $insert[] = [
  81. 'id' => $value['id'],
  82. 'parent_id' => $value['parent_id'],
  83. 'title' => $value['title'],
  84. 'code' => $value['code'],
  85. 'is_use' => $is_use
  86. ];
  87. }
  88. }
  89. if(! empty($insert)) Depart::insert($insert);
  90. if(! empty($update)) {
  91. foreach ($update as $value){
  92. Depart::where('id', $value['id'])
  93. ->update($value);
  94. }
  95. }
  96. });
  97. });
  98. $this->databaseService->table('AA_Person')
  99. ->select('id','code as number','name as emp_name','mobilePhoneNo as mobile','iddepartment as depart_id','disabled as state')
  100. ->chunkById(100, function ($data) {
  101. DB::transaction(function () use ($data) {
  102. $dataArray = Collect($data)->map(function ($object) {
  103. return (array)$object;
  104. })->toArray();
  105. $employee_id = Employee::whereIn('id', array_column($dataArray,'id'))
  106. ->pluck('id')
  107. ->toArray();
  108. $insert = $update = $depart_update = [];
  109. foreach ($dataArray as $value){
  110. $state = $value['state'] ? Employee::NOT_USE : Employee::USE;
  111. if(in_array($value['id'], $employee_id)){
  112. $update[] = [
  113. 'id' => $value['id'],
  114. 'number' => $value['number'],
  115. 'emp_name' => $value['emp_name'],
  116. 'mobile' => $value['mobile'],
  117. 'state' => $state
  118. ];
  119. }else{
  120. $insert[] = [
  121. 'id' => $value['id'],
  122. 'number' => $value['number'],
  123. 'emp_name' => $value['emp_name'],
  124. 'mobile' => $value['mobile'],
  125. 'state' => $state
  126. ];
  127. }
  128. $depart_update[] = [
  129. 'employee_id' => $value['id'],
  130. 'depart_id' => $value['depart_id']
  131. ];
  132. }
  133. if(! empty($insert)) Employee::insert($insert);
  134. if(! empty($update)) {
  135. foreach ($update as $value){
  136. Employee::where('id', $value['id'])
  137. ->update($value);
  138. }
  139. }
  140. if(! empty($depart_update)){
  141. EmployeeDepartPermission::whereIn('employee_id',array_column($depart_update,'employee_id'))->delete();
  142. EmployeeDepartPermission::insert($depart_update);
  143. }
  144. });
  145. });
  146. } catch (\Throwable $e) {
  147. return [false, $e->getMessage()];
  148. }
  149. return [true, ''];
  150. }
  151. /**
  152. * 收入成本统计同步
  153. *
  154. * @param array $data
  155. * @param array $user
  156. * @return array
  157. */
  158. public function synRevenueCost($data, $user){
  159. if(empty($data['crt_time'][0]) || empty($data['crt_time'][1])) return [false, '同步时间不能为空'];
  160. list($start_time, $end_time) = $this->changeDateToTimeStampAboutRange($data['crt_time'],false);
  161. if ($start_time === null || $end_time === null || $start_time > $end_time) return [false, "同步时间:时间区间无效"];
  162. list($bool, $bool_msg) = $this->isOverThreeMonths($start_time, $end_time);
  163. if(! $bool) return [false, $bool_msg];
  164. $data['start_timeStamp'] = $start_time;
  165. $data['end_timeStamp'] = $end_time;
  166. $start = date('Y-m-d H:i:s.000', $start_time);
  167. $end = date('Y-m-d H:i:s.000', $end_time);
  168. $data['start_time'] = $start;
  169. $data['end_time'] = $end;
  170. $data['operation_time'] = time();
  171. if(empty($data['type'])) return [false, '同步类型不能为空'];
  172. if(in_array($data['type'],[1,2,3,4])){
  173. list($status,$msg) = $this->limitingSendRequest($this->table);
  174. if(! $status) return [false, '收入成本相关信息同步正在后台运行,请稍后'];
  175. // //同步
  176. // list($status, $msg) = $this->synRevenueCostFromTPlus($data, $user);
  177. // if(! $status) {
  178. // return [false, $msg];
  179. // }
  180. //队列
  181. ProcessDataJob::dispatch($data, $user)->onQueue(RevenueCost::job);
  182. }else{
  183. return [false, '同步类型错误'];
  184. }
  185. return [true, '收入成本相关信息同步已进入后台任务'];
  186. }
  187. public function synRevenueCostFromTPlus($data, $user){
  188. //创建临时表 如果不存在
  189. $this->createTmpTable();
  190. //清理临时表 如果内容不为空
  191. $this->clearTmpTable();
  192. $type = $data['type'];
  193. //写入临时数据
  194. if($type == 1){
  195. list($status, $msg) = $this->xhdTPlus($data, $user);
  196. if(! $status) return [false, $msg];
  197. list($status, $msg) = $this->xsfpTPlus($data, $user);
  198. if(! $status) return [false, $msg];
  199. list($status, $msg) = $this->hkdTPlus($data, $user);
  200. if(! $status) return [false, $msg];
  201. }elseif ($type == 2){
  202. list($status, $msg) = $this->xhdTPlus($data, $user);
  203. if(! $status) return [false, $msg];
  204. }elseif ($type == 3){
  205. list($status, $msg) = $this->xsfpTPlus($data, $user);
  206. if(! $status) return [false, $msg];
  207. }elseif ($type == 4){
  208. list($status, $msg) = $this->hkdTPlus($data, $user);
  209. if(! $status) return [false, $msg];
  210. }
  211. //更新数据
  212. list($status,$msg) = $this->updateRevenueCost($data);
  213. if(! $status) return [false, $msg];
  214. // //更新主表数据
  215. // list($status,$msg) = $this->updateRevenueCostTotal($data);
  216. // if(! $status) return [false, $msg];
  217. //都成功后 清理临时表
  218. $this->clearTmpTable();
  219. //释放redis
  220. $this->delTableKey();
  221. return [true, '同步成功'];
  222. }
  223. private function xhdTPlus($data, $user){
  224. try {
  225. $table = $this->table;
  226. $limit = 500;
  227. $lastId = 0;
  228. do {
  229. $rows = $this->databaseService->table('SA_SaleDelivery_b as sd_b')
  230. ->join('SA_SaleDelivery as sd', 'sd_b.idSaleDeliveryDTO', '=', 'sd.ID')
  231. ->leftJoin('AA_Partner as pn', 'sd.idsettlecustomer', '=', 'pn.ID')
  232. ->leftJoin('AA_Person as ps', 'sd.idclerk', '=', 'ps.ID')
  233. ->leftJoin('AA_Person as ps2', 'pn.idsaleman', '=', 'ps2.ID')
  234. ->leftJoin('AA_Inventory as it', 'sd_b.idinventory', '=', 'it.ID')
  235. ->leftJoin('AA_Unit as ui', 'sd_b.idbaseunit', '=', 'ui.ID')
  236. ->where('sd.voucherdate', '>=', $data['start_time'])
  237. ->where('sd.voucherdate', '<=', $data['end_time'])
  238. ->where('sd_b.ID', '>', $lastId) // 用真实字段
  239. ->orderBy('sd_b.ID')
  240. ->limit($limit)
  241. ->selectRaw("
  242. COALESCE(sd.ID, 0) as order_id,
  243. COALESCE(sd.code, '') as order_number,
  244. sd.voucherdate as order_time,
  245. sd.voucherState as order_state,
  246. COALESCE(ps.name, '') as employee_id_1_title,
  247. COALESCE(sd.idclerk, 0) as employee_id_1,
  248. COALESCE(ps2.name, '') as employee_id_2_title,
  249. COALESCE(pn.idsaleman, 0) as employee_id_2,
  250. COALESCE(pn.code, '') as customer_code,
  251. COALESCE(pn.name, '') as customer_title,
  252. COALESCE(pn.priuserdefnvc14, '') as customer_profit_rate,
  253. COALESCE(sd.pubuserdefnvc11, '') as channel_finance,
  254. COALESCE(sd.pubuserdefnvc12, '') as channel_details,
  255. COALESCE(it.code, '') as product_code,
  256. COALESCE(it.name, '') as product_title,
  257. COALESCE(it.specification, '') as product_size,
  258. COALESCE(ui.name, '') as unit,
  259. COALESCE(sd_b.quantity, 0) as quantity,
  260. COALESCE(sd_b.taxPrice, 0) as price_3,
  261. COALESCE(sd_b.taxAmount, 0) as price_3_total,
  262. COALESCE(sd_b.ID, 0) as id_detail,
  263. COALESCE(sd_b.pubuserdefdecm9, 0) as is_activity
  264. ")
  265. ->get();
  266. if ($rows->isEmpty()) break;
  267. $dataArray = Collect($rows)->map(function ($object) {
  268. return (array)$object;
  269. })->toArray();
  270. //存货档案
  271. $product = Product::where('del_time', 0)
  272. ->whereIn('code', array_unique(array_column($dataArray, 'product_code')))
  273. ->select('code', 'write_off_price', 'freight_price', 'business_cost')
  274. ->get()->toArray();
  275. $product_map = array_column($product, null, 'code');
  276. //组织数据
  277. foreach ($dataArray as $key => $value) {
  278. $customer_profit_rate = rtrim($value['customer_profit_rate'],'%');
  279. if(is_numeric($customer_profit_rate)){
  280. $customer_profit_rate = bcdiv($customer_profit_rate,100,3);
  281. }else{
  282. $customer_profit_rate = 0;
  283. }
  284. $dataArray[$key]['customer_profit_rate'] = $customer_profit_rate;
  285. $p_tmp = $product_map[$value['product_code']] ?? [];
  286. $dataArray[$key]['order_type'] = RevenueCost::ORDER_ONE;
  287. $dataArray[$key]['order_time'] = strtotime($value['order_time']);
  288. $write_off_price = $p_tmp['write_off_price'] ?? 0;
  289. $dataArray[$key]['price_1'] = $write_off_price;
  290. $dataArray[$key]['price_1_total'] = bcmul($write_off_price, $value['quantity'], 2);
  291. $freight_price = $p_tmp['freight_price'] ?? 0;
  292. $dataArray[$key]['price_2'] = $freight_price;
  293. $dataArray[$key]['price_2_total'] = bcmul($freight_price, $value['quantity'], 2);
  294. $business_cost = $p_tmp['business_cost'] ?? 0;
  295. $dataArray[$key]['price_4'] = $business_cost;
  296. $price_4_total = bcmul($business_cost, $value['quantity'], 2);
  297. $dataArray[$key]['price_4_total'] = bcmul($business_cost, $value['quantity'], 2);
  298. $profit = bcsub($value['price_3_total'], $price_4_total, 2);
  299. $dataArray[$key]['profit'] = $profit;
  300. $dataArray[$key]['profit_rate'] = $value['price_3_total'] > 0 ? bcdiv($profit, $value['price_3_total'], 2) : 0;
  301. }
  302. DB::table($table)->insert($dataArray);
  303. // 更新 lastId 继续下一批
  304. $lastId = end($dataArray)['id_detail'] ?? $lastId;
  305. } while (count($rows) === $limit);
  306. }catch (\Throwable $exception){
  307. return [false, "销货单同步异常" . $exception->getMessage() . "|" . $exception->getLine() . "|" . $exception->getFile()];
  308. }
  309. return [true, ''];
  310. }
  311. private function xsfpTPlus($data, $user){
  312. try {
  313. $table = $this->table;
  314. $limit = 500;
  315. $lastId = 0;
  316. do {
  317. $rows = $this->databaseService->table('SA_SaleInvoice_b as si_b')
  318. ->join('SA_SaleInvoice as si', 'si_b.idSaleInvoiceDTO', '=', 'si.ID')
  319. ->leftJoin('SA_SaleDelivery_b as sd_b', 'si_b.sourceVoucherDetailId', '=', 'sd_b.ID')
  320. ->leftJoin('AA_Partner as pn', 'si.idsettlecustomer', '=', 'pn.ID')
  321. ->leftJoin('AA_Person as ps', 'si.idclerk', '=', 'ps.ID')
  322. ->leftJoin('AA_Person as ps2', 'pn.idsaleman', '=', 'ps2.ID')
  323. ->leftJoin('AA_Inventory as it', 'si_b.idinventory', '=', 'it.ID')
  324. ->leftJoin('AA_Unit as ui', 'si_b.idbaseunit', '=', 'ui.ID')
  325. ->where('si.voucherdate','>=',$data['start_time'])
  326. ->where('si.voucherdate','<=',$data['end_time'])
  327. ->where('si_b.ID', '>', $lastId) // 用真实字段
  328. ->orderBy('si_b.ID')
  329. ->limit($limit)
  330. ->selectRaw("
  331. COALESCE(si.ID, 0) as order_id,
  332. COALESCE(si.code, '') as order_number,
  333. si.voucherdate as order_time,
  334. si.voucherState as order_state,
  335. COALESCE(pn.code, '') as customer_code,
  336. COALESCE(pn.name, '') as customer_title,
  337. COALESCE(pn.priuserdefnvc14, '') as customer_profit_rate,
  338. COALESCE(si.idclerk, 0) as employee_id_1,
  339. COALESCE(ps.name, '') as employee_id_1_title,
  340. COALESCE(pn.idsaleman, 0) as employee_id_2,
  341. COALESCE(ps2.name, '') as employee_id_2_title,
  342. COALESCE(it.code, '') as product_code,
  343. COALESCE(it.name, '') as product_title,
  344. COALESCE(it.specification, '') as product_size,
  345. COALESCE(ui.name, '') as unit,
  346. COALESCE(si_b.quantity, 0) as quantity,
  347. COALESCE(si_b.taxPrice, 0) as price_1,
  348. COALESCE(si_b.taxAmount, 0) as price_1_total,
  349. COALESCE(si_b.ID, 0) as id_detail,
  350. COALESCE(si_b.sourceVoucherDetailId, 0) as id_detail_upstream,
  351. COALESCE(si_b.sourceVoucherCode, '') as order_number_upstream,
  352. COALESCE(sd_b.pubuserdefdecm9, 0) as is_activity
  353. ")
  354. ->get();
  355. if ($rows->isEmpty()) break;
  356. $dataArray = Collect($rows)->map(function ($object) {
  357. return (array)$object;
  358. })->toArray();
  359. //存货档案
  360. $product = Product::where('del_time',0)
  361. ->whereIn('code', array_unique(array_column($dataArray,'product_code')))
  362. ->select('code','business_cost')
  363. ->get()->toArray();
  364. $product_map = array_column($product,null,'code');
  365. //组织数据
  366. foreach ($dataArray as $key => $value){
  367. $customer_profit_rate = rtrim($value['customer_profit_rate'],'%');
  368. if(is_numeric($customer_profit_rate)){
  369. $customer_profit_rate = bcdiv($customer_profit_rate,100,3);
  370. }else{
  371. $customer_profit_rate = 0;
  372. }
  373. $dataArray[$key]['customer_profit_rate'] = $customer_profit_rate;
  374. $p_tmp = $product_map[$value['product_code']] ?? [];
  375. $dataArray[$key]['order_type'] = RevenueCost::ORDER_TWO;
  376. $dataArray[$key]['order_time'] = strtotime($value['order_time']);
  377. $business_cost = $p_tmp['business_cost'] ?? 0;
  378. $dataArray[$key]['price_4'] = $business_cost;
  379. $price_4_total = bcmul($business_cost, $value['quantity'],2);
  380. $dataArray[$key]['price_4_total'] = bcmul($business_cost, $value['quantity'],2);
  381. $profit = bcsub($value['price_1_total'], $price_4_total,2);
  382. $dataArray[$key]['profit'] = $profit;
  383. $dataArray[$key]['profit_rate'] = $value['price_1_total'] > 0 ? bcdiv($profit, $value['price_1_total'],2) : 0;
  384. }
  385. DB::table($table)->insert($dataArray);
  386. // 更新 lastId 继续下一批
  387. $lastId = end($dataArray)['id_detail'] ?? $lastId;
  388. } while (count($rows) === $limit);
  389. }catch (\Throwable $exception){
  390. return [false, "销售发票同步异常" . $exception->getMessage() . "|" . $exception->getLine() . "|" . $exception->getFile()];
  391. }
  392. return [true, ''];
  393. }
  394. private function hkdTPlus($data, $user){
  395. try{
  396. $table = $this->table;
  397. $limit = 500;
  398. $lastId = 0;
  399. do {
  400. $rows = $this->databaseService->table('ARAP_ReceivePayment_b as rp_b')
  401. ->join('ARAP_ReceivePayment as rp', 'rp_b.idArapReceivePaymentDTO', '=', 'rp.ID')
  402. // ->leftJoin('SA_SaleInvoice_b as si_b', 'rp_b.voucherDetailID', '=', 'si_b.ID')
  403. // ->leftJoin('SA_SaleInvoice as si', 'si_b.idSaleInvoiceDTO', '=', 'si.ID')
  404. // ->leftJoin('SA_SaleDelivery_b as sd_b', 'si_b.sourceVoucherDetailId', '=', 'sd_b.ID')
  405. // 发票子表关联(仅限 idvouchertype = 20)
  406. ->leftJoin('SA_SaleInvoice_b as si_b', function ($join) {
  407. $join->on('rp_b.voucherDetailID', '=', 'si_b.ID')
  408. ->where('rp_b.idvouchertype', '=', 20);
  409. })
  410. ->leftJoin('SA_SaleInvoice as si', function ($join) {
  411. $join->on('si_b.idSaleInvoiceDTO', '=', 'si.ID')
  412. ->where('rp_b.idvouchertype', '=', 20);
  413. })
  414. ->leftJoin('SA_SaleDelivery_b as sd_b', function ($join) {
  415. $join->on('si_b.sourceVoucherDetailId', '=', 'sd_b.ID')
  416. ->where('rp_b.idvouchertype', '=', 20);
  417. })
  418. ->leftJoin('AA_Partner as pn', 'si.idsettlecustomer', '=', 'pn.ID')
  419. ->leftJoin('AA_Person as ps', 'rp.idperson', '=', 'ps.ID')
  420. ->leftJoin('AA_Person as ps2', 'pn.idsaleman', '=', 'ps2.ID')
  421. ->leftJoin('AA_Inventory as it', 'si_b.idinventory', '=', 'it.ID')
  422. ->leftJoin('AA_Unit as ui', 'si_b.idbaseunit', '=', 'ui.ID')
  423. ->where('rp.voucherdate','>=',$data['start_time'])
  424. ->where('rp.voucherdate','<=',$data['end_time'])
  425. // ->where('rp_b.idvouchertype','=', 20) // 销售发票
  426. ->where('rp.isReceiveFlag','=', 1)
  427. ->where('rp_b.ID', '>', $lastId)
  428. ->orderBy('rp_b.ID')
  429. ->limit($limit)
  430. // ->selectRaw("
  431. // COALESCE(rp.ID, 0) as order_id,
  432. // COALESCE(rp.code, '') as order_number,
  433. // rp.voucherdate as order_time,
  434. // COALESCE(pn.code, '') as customer_code,
  435. // COALESCE(pn.name, '') as customer_title,
  436. // COALESCE(pn.priuserdefnvc14, '') as customer_profit_rate,
  437. // COALESCE(it.code, '') as product_code,
  438. // COALESCE(it.name, '') as product_title,
  439. // COALESCE(rp.idperson, 0) as employee_id_1,
  440. // COALESCE(ps.name, '') as employee_id_1_title,
  441. // COALESCE(pn.idsaleman, 0) as employee_id_2,
  442. // COALESCE(ps2.name, '') as employee_id_2_title,
  443. // COALESCE(it.specification, '') as product_size,
  444. // COALESCE(ui.name, '') as unit,
  445. // COALESCE(si_b.quantity, 0) as quantity,
  446. // COALESCE(si_b.taxPrice, 0) as price_1,
  447. // COALESCE(si_b.taxAmount, 0) as price_1_total,
  448. // COALESCE(rp_b.amount, 0) as payment_amount,
  449. // COALESCE(rp_b.ID, 0) as id_detail,
  450. // COALESCE(rp_b.voucherDetailID, 0) as id_detail_upstream,
  451. // COALESCE(rp_b.voucherCode, '') as order_number_upstream,
  452. // COALESCE(sd_b.pubuserdefdecm9, 0) as is_activity
  453. // ")
  454. ->selectRaw("
  455. COALESCE(rp.ID, 0) as order_id,
  456. COALESCE(rp.code, '') as order_number,
  457. rp.voucherdate as order_time,
  458. rp.voucherstate as order_state,
  459. COALESCE(rp.pubuserdefnvc11, '') as channel_finance,
  460. COALESCE(rp.pubuserdefnvc12, '') as channel_details,
  461. COALESCE(pn.code, '') as customer_code,
  462. COALESCE(pn.name, '') as customer_title,
  463. COALESCE(pn.priuserdefnvc14, '') as customer_profit_rate,
  464. CASE WHEN rp_b.idvouchertype = 20 THEN COALESCE(it.code, '') ELSE '' END as product_code,
  465. CASE WHEN rp_b.idvouchertype = 20 THEN COALESCE(it.name, '') ELSE '' END as product_title,
  466. COALESCE(rp.idperson, 0) as employee_id_1,
  467. COALESCE(ps.name, '') as employee_id_1_title,
  468. COALESCE(pn.idsaleman, 0) as employee_id_2,
  469. COALESCE(ps2.name, '') as employee_id_2_title,
  470. CASE WHEN rp_b.idvouchertype = 20 THEN COALESCE(it.specification, '') ELSE '' END as product_size,
  471. CASE WHEN rp_b.idvouchertype = 20 THEN COALESCE(ui.name, '') ELSE '' END as unit,
  472. CASE WHEN rp_b.idvouchertype = 20 THEN COALESCE(si_b.quantity, 0) ELSE 0 END as quantity,
  473. CASE WHEN rp_b.idvouchertype = 20 THEN COALESCE(si_b.taxPrice, 0) ELSE 0 END as price_1,
  474. CASE WHEN rp_b.idvouchertype = 20 THEN COALESCE(si_b.taxAmount, 0) ELSE 0 END as price_1_total,
  475. COALESCE(rp_b.amount, 0) as payment_amount,
  476. COALESCE(rp_b.ID, 0) as id_detail,
  477. COALESCE(rp_b.voucherDetailID, 0) as id_detail_upstream,
  478. COALESCE(rp_b.voucherCode, '') as order_number_upstream,
  479. CASE WHEN rp_b.idvouchertype = 20 THEN COALESCE(sd_b.pubuserdefdecm9, 0) ELSE 0 END as is_activity,
  480. rp_b.idvouchertype as voucher_type
  481. ")
  482. ->get();
  483. if ($rows->isEmpty()) break;
  484. $dataArray = Collect($rows)->map(function ($object) {
  485. return (array)$object;
  486. })->toArray();
  487. //存货档案
  488. $product = Product::where('del_time',0)
  489. ->whereIn('code', array_unique(array_column($dataArray,'product_code')))
  490. ->select('code','business_cost')
  491. ->get()->toArray();
  492. $product_map = array_column($product,null,'code');
  493. //组织数据
  494. foreach ($dataArray as $key => $value){
  495. $customer_profit_rate = rtrim($value['customer_profit_rate'],'%');
  496. if(is_numeric($customer_profit_rate)){
  497. $customer_profit_rate = bcdiv($customer_profit_rate,100,3);
  498. }else{
  499. $customer_profit_rate = 0;
  500. }
  501. $dataArray[$key]['customer_profit_rate'] = $customer_profit_rate;
  502. $p_tmp = $product_map[$value['product_code']] ?? [];
  503. $dataArray[$key]['order_type'] = RevenueCost::ORDER_THREE;
  504. $dataArray[$key]['order_time'] = strtotime($value['order_time']);
  505. $business_cost = $p_tmp['business_cost'] ?? 0;
  506. $dataArray[$key]['price_4'] = $business_cost;
  507. $price_4_total = bcmul($business_cost, $value['quantity'],2);
  508. $dataArray[$key]['price_4_total'] = $price_4_total;
  509. $profit = bcsub($value['price_1_total'], $price_4_total,2);
  510. $dataArray[$key]['profit'] = $profit;
  511. $dataArray[$key]['profit_rate'] = $value['price_1_total'] > 0 ? bcdiv($profit, $value['price_1_total'],2) : 0;
  512. }
  513. DB::table($table)->insert($dataArray);
  514. // 更新 lastId 继续下一批
  515. $lastId = end($dataArray)['id_detail'] ?? $lastId;
  516. } while (count($rows) === $limit);
  517. }catch (\Throwable $exception){
  518. return [false, "回款单同步异常" . $exception->getMessage() . "|" . $exception->getLine() . "|" . $exception->getFile()];
  519. }
  520. return [true, ''];
  521. }
  522. private function updateRevenueCost($data){
  523. try {
  524. $start_timeStamp = $data['start_timeStamp'];
  525. $end_timeStamp = $data['end_timeStamp'];
  526. $tmpTable = $this->table;
  527. $time = time();
  528. $ergs = $data;
  529. DB::transaction(function () use ($start_timeStamp, $end_timeStamp, $tmpTable,$time, $ergs) {
  530. // 1. 先软删除旧数据(你已有)
  531. RevenueCost::where('del_time', 0)
  532. ->where('order_time', '>=', $start_timeStamp)
  533. ->where('order_time', '<=', $end_timeStamp)
  534. ->update(['del_time' => $time]);
  535. // 2. 分批从临时表插入新数据
  536. $batchSize = 500;
  537. $lastId = 0;
  538. do {
  539. $chunk = DB::table($tmpTable)
  540. ->where('id', '>', $lastId)
  541. ->orderBy('id')
  542. ->limit($batchSize)
  543. ->get();
  544. if ($chunk->isEmpty()) {
  545. break;
  546. }
  547. $data = $chunk->map(function ($item) use($time){
  548. return [
  549. 'order_id' => $item->order_id,
  550. 'order_number' => $item->order_number,
  551. 'order_time' => $item->order_time,
  552. 'order_state' => $item->order_state,
  553. 'employee_id_1_title' => $item->employee_id_1_title,
  554. 'employee_id_1' => $item->employee_id_1 ?? 0,
  555. 'employee_id_2' => $item->employee_id_2 ?? 0,
  556. 'employee_id_2_title' => $item->employee_id_2_title ?? "",
  557. 'customer_code' => $item->customer_code,
  558. 'customer_title' => $item->customer_title,
  559. 'channel_finance' => $item->channel_finance,
  560. 'channel_details' => $item->channel_details,
  561. 'product_code' => $item->product_code,
  562. 'product_title' => $item->product_title,
  563. 'product_size' => $item->product_size,
  564. 'unit' => $item->unit,
  565. 'quantity' => $item->quantity,
  566. 'price_1' => $item->price_1,
  567. 'price_1_total' => $item->price_1_total,
  568. 'price_2' => $item->price_2,
  569. 'price_2_total' => $item->price_2_total,
  570. 'price_3' => $item->price_3,
  571. 'price_3_total' => $item->price_3_total,
  572. 'price_4' => $item->price_4,
  573. 'price_4_total' => $item->price_4_total,
  574. 'profit' => $item->profit,
  575. 'profit_rate' => $item->profit_rate,
  576. 'id_detail' => $item->id_detail,
  577. 'order_type' => $item->order_type,
  578. 'payment_amount' => $item->payment_amount ?? 0,
  579. 'id_detail_upstream' => $item->id_detail_upstream?? 0,
  580. 'order_number_upstream' => $item->order_number_upstream ?? "",
  581. 'is_activity' => $item->is_activity ?? 0,
  582. 'customer_profit_rate' => $item->customer_profit_rate ?? '',
  583. 'voucher_type' => $item->voucher_type ?? 0,
  584. 'crt_time' => $time,
  585. ];
  586. })->toArray();
  587. // 每批单独插入(可选:加小事务)
  588. RevenueCost::insert($data);
  589. // 更新 lastId
  590. $lastId = $chunk->last()->id;
  591. } while ($chunk->count() == $batchSize);
  592. // 3. 更新主表
  593. list($status, $msg) = $this->updateRevenueCostTotal($ergs);
  594. if (! $status) {
  595. throw new \Exception($msg);
  596. }
  597. });
  598. }catch (\Throwable $exception){
  599. return [false, "单据明细同步异常" . $exception->getMessage() . "|" . $exception->getLine() . "|" . $exception->getFile()];
  600. }
  601. return [true, ''];
  602. }
  603. private function updateRevenueCostTotal($data){
  604. try {
  605. $start_timeStamp = $data['start_timeStamp'];
  606. $end_timeStamp = $data['end_timeStamp'];
  607. $time = time();
  608. //组织写入数据
  609. $return = [];
  610. $update_stamp = [];
  611. DB::table('revenue_cost')
  612. ->where('del_time',0)
  613. ->where('order_time', '>=', $start_timeStamp)
  614. ->where('order_time', '<=', $end_timeStamp)
  615. ->select(RevenueCost::$field)
  616. ->chunkById(100, function ($data) use(&$return,&$update_stamp){
  617. $dataArray = Collect($data)->map(function ($object){
  618. return (array)$object;
  619. })->toArray();
  620. foreach ($dataArray as $value){
  621. //变成每个月第一天的时间戳
  622. $time = date("Y-m-01", $value['order_time']);
  623. $stamp = strtotime($time);
  624. if(! in_array($stamp, $update_stamp)) $update_stamp[] = $stamp;
  625. if($value['order_type'] == RevenueCost::ORDER_ONE){
  626. $income = $value['price_3_total'];
  627. }elseif ($value['order_type'] == RevenueCost::ORDER_TWO){
  628. $income = $value['price_1_total'];
  629. }else{
  630. $income = $value['payment_amount'];
  631. }
  632. $adjust = $income < 0 ? $income : 0;
  633. $business = $value['price_4_total'];
  634. if(isset($return[$stamp][$value['order_type']][$value['employee_id_1']])){
  635. $income_total = bcadd($return[$stamp][$value['order_type']][$value['employee_id_1']]['income'], $income,2);
  636. $adjust_total = bcadd($return[$stamp][$value['order_type']][$value['employee_id_1']]['adjust'], $adjust,2);
  637. $business_total = bcadd($return[$stamp][$value['order_type']][$value['employee_id_1']]['business'], $business,2);
  638. $return[$stamp][$value['order_type']][$value['employee_id_1']]['income'] = $income_total;
  639. $return[$stamp][$value['order_type']][$value['employee_id_1']]['adjust'] = $adjust_total;
  640. $return[$stamp][$value['order_type']][$value['employee_id_1']]['business'] = $business_total;
  641. }else{
  642. $return[$stamp][$value['order_type']][$value['employee_id_1']] = [
  643. 'income' => $income,
  644. 'adjust' => $adjust,
  645. 'business' => $business,
  646. 'order_time' => $stamp,
  647. 'employee_id_1_title' => $value['employee_id_1_title'],
  648. ];
  649. }
  650. }
  651. });
  652. $insert = [];
  653. foreach ($return as $value){
  654. foreach ($value as $order_type => $val){
  655. foreach ($val as $employee_id => $v){
  656. $profit = bcsub($v['income'], $v['business'],2);
  657. $profit_rate = $v['income'] > 0 ? bcdiv($profit, $v['income'],2) : 0;
  658. $v['profit'] = $profit;
  659. $v['profit_rate'] = $profit_rate;
  660. $v['order_type'] = $order_type;
  661. $v['employee_id_1'] = $employee_id;
  662. $v['crt_time'] = $time;
  663. $insert[] = $v;
  664. }
  665. }
  666. }
  667. RevenueCostTotal::where('del_time', 0)
  668. ->whereIn('order_time', $update_stamp)
  669. ->update(['del_time' => $time]);
  670. RevenueCostTotal::insert($insert);
  671. }catch (\Throwable $exception){
  672. return [false, "主表同步异常" . $exception->getMessage() . "|" . $exception->getLine() . "|" . $exception->getFile()];
  673. }
  674. return [true, ''];
  675. }
  676. private function createTmpTable(){
  677. $table = $this->table;
  678. if (! Schema::hasTable($table)) {
  679. // 可以通过 migration 创建,或程序启动时检查
  680. Schema::create($table, function (Blueprint $table) {
  681. $table->bigIncrements('id'); // BIGINT UNSIGNED AUTO_INCREMENT PRIMARY KEY
  682. $table->integer('order_type')->default(0);
  683. $table->bigInteger('order_id')->default(0);
  684. $table->string('order_number', 50)->default('');
  685. $table->integer('order_time')->nullable();
  686. $table->integer('order_state')->default(0);
  687. $table->string('employee_id_1_title', 100)->default('');
  688. $table->bigInteger('employee_id_1')->default(0);
  689. $table->bigInteger('employee_id_2')->default(0);
  690. $table->string('employee_id_2_title', 100)->default('');
  691. $table->string('customer_code', 50)->default('');
  692. $table->string('customer_title', 100)->default('');
  693. $table->string('channel_finance', 50)->nullable();
  694. $table->string('channel_details', 50)->nullable();
  695. $table->string('product_code', 50)->default('');
  696. $table->string('product_title', 100)->default('');
  697. $table->string('product_size', 100)->nullable();
  698. $table->string('unit', 20)->nullable();
  699. $table->decimal('quantity', 12, 2)->default(0);
  700. $table->decimal('price_1', 12, 2)->default(0); // 销项成本
  701. $table->decimal('price_1_total', 12, 2)->default(0);
  702. $table->decimal('price_2', 12, 2)->default(0); // 运费
  703. $table->decimal('price_2_total', 12, 2)->default(0);
  704. $table->decimal('price_3', 12, 2)->default(0); // 含税单价
  705. $table->decimal('price_3_total', 12, 2)->default(0); // 含税金额
  706. $table->decimal('price_4', 12, 2)->default(0); // 业务成本
  707. $table->decimal('price_4_total', 12, 2)->default(0);
  708. $table->decimal('profit', 12, 2)->default(0);
  709. $table->decimal('payment_amount', 12, 2)->default(0);
  710. $table->decimal('profit_rate', 10, 3)->default(0);
  711. $table->bigInteger('id_detail')->default(0);
  712. $table->bigInteger('id_detail_upstream')->default(0);
  713. $table->string('order_number_upstream', 100)->nullable();
  714. $table->decimal('is_activity', 2, 0)->default(0);
  715. $table->string('customer_profit_rate', 20)->default('');
  716. $table->bigInteger('voucher_type')->default(0);
  717. });
  718. }
  719. }
  720. public function clearTmpTable($type = 1){
  721. if($type == 1){
  722. if (Schema::hasTable($this->table)) DB::table($this->table)->truncate();
  723. }elseif ($type == 2){
  724. if (Schema::hasTable($this->table_2)) DB::table($this->table_2)->truncate();
  725. }elseif ($type == 3){
  726. if (Schema::hasTable($this->table_3)) DB::table($this->table_3)->truncate();
  727. }
  728. }
  729. public function delTableKey($type = 1){
  730. $key = $this->table;
  731. if($type == 2) $key = $this->table_2;
  732. if($type == 3) $key = $this->table_3;
  733. $this->dellimitingSendRequest($key);
  734. }
  735. public function synSalaryEmployee($data, $user){
  736. if(empty($data['crt_time'][0]) || empty($data['crt_time'][1])) return [false, '同步时间不能为空'];
  737. list($start_time, $end_time) = $this->changeDateToTimeStampAboutRange($data['crt_time'],false);
  738. if ($start_time === null || $end_time === null || $start_time > $end_time) return [false, "同步时间:时间区间无效"];
  739. list($bool, $bool_msg) = $this->isOverThreeMonths($start_time, $end_time);
  740. if(! $bool) return [false, $bool_msg];
  741. $data['start_timeStamp'] = $start_time;
  742. $data['end_timeStamp'] = $end_time;
  743. $data['start_time'] = strtotime(date("Y-m-01",$data['start_timeStamp']));
  744. $data['end_time'] = strtotime(date("Y-m-01"),$data['end_timeStamp']);
  745. $data['operation_time'] = time();
  746. list($status,$msg) = $this->limitingSendRequest($this->table_2);
  747. if(! $status) return [false, '业务员工资同步正在后台运行,请稍后'];
  748. //同步
  749. // list($status, $msg) = $this->synSalaryEmployeeFromMine($data, $user);
  750. // if(! $status) {
  751. // $this->dellimitingSendRequest($this->table_2);
  752. // return [false, $msg];
  753. // }
  754. //队列
  755. ProcessDataJob::dispatch($data, $user, 2)->onQueue(RevenueCost::job2);
  756. return [true, '业务员工资相关信息同步已进入后台任务'];
  757. }
  758. public function synSalaryEmployeeFromMine($data, $user){
  759. //创建临时表 如果不存在
  760. $this->createTmpTable2();
  761. //清理临时表 如果内容不为空
  762. $this->clearTmpTable(2);
  763. //写入临时表
  764. DB::table('revenue_cost')
  765. ->where('del_time', 0)
  766. ->where('order_type', RevenueCost::ORDER_THREE)
  767. ->where('order_time','>=',$data['start_timeStamp'])
  768. ->where('order_time','<=',$data['end_timeStamp'])
  769. ->select([
  770. 'employee_id_1',
  771. 'employee_id_1_title',
  772. 'order_time as time',
  773. DB::raw("DATE_FORMAT(FROM_UNIXTIME(order_time), '%Y-%m-01') as order_time"),
  774. DB::raw("SUM(payment_amount) as payment_amount"),
  775. DB::raw("SUM(CASE WHEN is_activity = 0 THEN payment_amount ELSE 0 END) as payment_amount_not_include_activity"),
  776. DB::raw("SUM(CASE WHEN is_activity = 1 THEN payment_amount ELSE 0 END) as payment_amount_activity"),
  777. 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"),
  778. 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"),
  779. DB::raw("SUM(CASE WHEN profit_rate >= customer_profit_rate and is_activity = 0 THEN price_4_total ELSE 0 END) as business"),
  780. DB::raw("ROW_NUMBER() OVER (ORDER BY MIN(id)) as fake_id")
  781. ])
  782. ->groupBy('employee_id_1', DB::raw("DATE_FORMAT(FROM_UNIXTIME(order_time), '%Y-%m-01')"))
  783. ->orderBy('order_time', 'desc')
  784. ->chunkById(500, function ($data){
  785. $dataArray = Collect($data)->map(function ($object){
  786. return (array)$object;
  787. })->toArray();
  788. $indexes = $this->getEmployeeIndex($dataArray);
  789. foreach ($dataArray as $key => $value){
  790. $value['index_' . EmployeeIndex::TYPE_ONE] = 0;
  791. $value['index_' . EmployeeIndex::TYPE_SIX] = 0;
  792. $value['index_' . EmployeeIndex::TYPE_EIGHT] = 0;
  793. $this->findIndex($indexes, $value);
  794. $dataArray[$key]['order_type'] = RevenueCost::ORDER_THREE;
  795. $dataArray[$key]['order_time'] = strtotime($value['order_time']);
  796. $dataArray[$key]['sale_bonus'] = $value['index_' . EmployeeIndex::TYPE_EIGHT];
  797. $dataArray[$key]['index_' . EmployeeIndex::TYPE_ONE] = $value['index_' . EmployeeIndex::TYPE_ONE];
  798. $rate = bcdiv($value['index_' . EmployeeIndex::TYPE_ONE],100,2);
  799. $pay_in_advance = bcmul($rate, $value['payment_amount_greater_than_rate'],2);
  800. $dataArray[$key]['pay_in_advance'] = $pay_in_advance;
  801. $dataArray[$key]['basic_salary'] = $value['index_' . EmployeeIndex::TYPE_SIX];
  802. $dataArray[$key]['should_pay'] = bcadd(bcadd($value['index_' . EmployeeIndex::TYPE_EIGHT], $pay_in_advance,2),$value['index_' . EmployeeIndex::TYPE_SIX],2);
  803. unset($dataArray[$key]['fake_id']);
  804. unset($dataArray[$key]['time']);
  805. }
  806. DB::table($this->table_2)->insert($dataArray);
  807. }, 'fake_id');
  808. //更新数据
  809. list($status,$msg) = $this->updateSalaryEmployee($data);
  810. if(! $status) return [false, $msg];
  811. //清理临时表 如果内容不为空
  812. $this->clearTmpTable(2);
  813. //释放redis
  814. $this->delTableKey(2);
  815. return [true, '同步成功'];
  816. }
  817. private function getEmployeeIndex($existingData)
  818. {
  819. if (empty($existingData)) {
  820. return collect();
  821. }
  822. // 取出所有涉及的 employee_id 和时间区间
  823. $employeeIds = array_column($existingData, 'employee_id_1');
  824. $time = array_column($existingData, 'time');
  825. $minStart = ! empty($time) ? min($time) : 0;
  826. $maxEnd = ! empty($time) ? max($time) : 0;
  827. // 一次性查出这些员工在最大区间范围内的所有指标
  828. $results = EmployeeIndex::where('del_time', 0)
  829. ->whereIn('type', [EmployeeIndex::TYPE_ONE, EmployeeIndex::TYPE_EIGHT, EmployeeIndex::TYPE_SIX])
  830. ->whereIn('employee_id', $employeeIds)
  831. ->where('start_time', '<=', $maxEnd)
  832. ->where('end_time', '>=', $minStart)
  833. ->select('start_time','end_time','employee_id','index','type')
  834. ->get();
  835. return $results;
  836. }
  837. private function findIndex($indexes, &$value){
  838. // 找到所有符合条件的 index(可能多个 type)
  839. $matchedIndexes = $indexes->filter(function ($item) use ($value) {
  840. return $item['employee_id'] == $value['employee_id_1']
  841. && $item['start_time'] <= $value['time']
  842. && $item['end_time'] >= $value['time'];
  843. });
  844. // 按 type 去重,只保留第一次出现的
  845. $uniqueByType = [];
  846. foreach ($matchedIndexes as $item) {
  847. $index = "index_" . $item['type'];
  848. if (! isset($uniqueByType[$index])) {
  849. $uniqueByType[$index] = $item['index'];
  850. }
  851. }
  852. $value = array_merge($value, $uniqueByType);
  853. }
  854. private function createTmpTable2(){
  855. $table = $this->table_2;
  856. if (! Schema::hasTable($table)) {
  857. // 可以通过 migration 创建,或程序启动时检查
  858. Schema::create($table, function (Blueprint $table) {
  859. $table->bigIncrements('id'); // BIGINT UNSIGNED AUTO_INCREMENT PRIMARY KEY
  860. $table->integer('order_type')->default(0);
  861. $table->integer('order_time')->default(0);
  862. $table->string('employee_id_1_title', 100)->default('');
  863. $table->bigInteger('employee_id_1')->default(0);
  864. $table->decimal('payment_amount', 12, 2)->default(0);
  865. $table->decimal('payment_amount_not_include_activity', 12, 2)->default(0);
  866. $table->decimal('payment_amount_activity', 12, 2)->default(0);
  867. $table->decimal('payment_amount_lower_than_rate', 12, 2)->default(0);
  868. $table->decimal('payment_amount_greater_than_rate', 12, 2)->default(0);
  869. $table->decimal('business', 12, 2)->default(0);
  870. $table->decimal('sale_bonus', 12, 2)->default(0);
  871. $table->decimal('index_1', 10, 2)->default(0);
  872. $table->decimal('pay_in_advance', 12, 2)->default(0);
  873. $table->decimal('basic_salary', 12, 2)->default(0);
  874. $table->decimal('should_pay', 12, 2)->default(0);
  875. });
  876. }
  877. }
  878. private function updateSalaryEmployee($data){
  879. try {
  880. $start_timeStamp = $data['start_time'];
  881. $end_timeStamp = $data['end_time'];
  882. $tmpTable = $this->table_2;
  883. $time = time();
  884. $ergs = $data;
  885. DB::transaction(function () use ($start_timeStamp, $end_timeStamp, $tmpTable,$time, $ergs) {
  886. // 1. 先软删除旧数据(你已有)
  887. SalaryEmployee::where('del_time', 0)
  888. ->where('order_time', '>=', $start_timeStamp)
  889. ->where('order_time', '<=', $end_timeStamp)
  890. ->update(['del_time' => $time]);
  891. // 2. 分批从临时表插入新数据
  892. $batchSize = 500;
  893. $lastId = 0;
  894. do {
  895. $chunk = DB::table($tmpTable)
  896. ->where('id', '>', $lastId)
  897. ->orderBy('id')
  898. ->limit($batchSize)
  899. ->get();
  900. if ($chunk->isEmpty()) {
  901. break;
  902. }
  903. $data = $chunk->map(function ($item) use($time){
  904. return [
  905. 'order_type' => $item->order_type,
  906. 'order_time' => $item->order_time,
  907. 'employee_id_1_title' => $item->employee_id_1_title,
  908. 'employee_id_1' => $item->employee_id_1 ?? 0,
  909. 'payment_amount' => $item->payment_amount,
  910. 'payment_amount_not_include_activity' => $item->payment_amount_not_include_activity,
  911. 'payment_amount_activity' => $item->payment_amount_activity,
  912. 'payment_amount_lower_than_rate' => $item->payment_amount_lower_than_rate,
  913. 'payment_amount_greater_than_rate' => $item->payment_amount_greater_than_rate,
  914. 'business' => $item->business,
  915. 'sale_bonus' => $item->sale_bonus,
  916. 'index_1' => $item->index_1,
  917. 'pay_in_advance' => $item->pay_in_advance,
  918. 'basic_salary' => $item->basic_salary,
  919. 'should_pay' => $item->should_pay,
  920. 'crt_time' => $time,
  921. ];
  922. })->toArray();
  923. // 每批单独插入(可选:加小事务)
  924. SalaryEmployee::insert($data);
  925. // 更新 lastId
  926. $lastId = $chunk->last()->id;
  927. } while ($chunk->count() == $batchSize);
  928. });
  929. }catch (\Throwable $exception){
  930. return [false, "单据明细同步异常" . $exception->getMessage() . "|" . $exception->getLine() . "|" . $exception->getFile()];
  931. }
  932. return [true, ''];
  933. }
  934. public function synFreightFee($data, $user){
  935. if(empty($data['crt_time'][0]) || empty($data['crt_time'][1])) return [false, '同步时间不能为空'];
  936. list($start_time, $end_time) = $this->changeDateToTimeStampAboutRange($data['crt_time'],false);
  937. if ($start_time === null || $end_time === null || $start_time > $end_time) return [false, "同步时间:时间区间无效"];
  938. list($bool, $bool_msg) = $this->isOverThreeMonths($start_time, $end_time);
  939. if(! $bool) return [false, $bool_msg];
  940. $data['start_timeStamp'] = $start_time;
  941. $data['end_timeStamp'] = $end_time;
  942. $start = date('Y-m-d H:i:s.000', $start_time);
  943. $end = date('Y-m-d H:i:s.000', $end_time);
  944. $data['start_time'] = $start;
  945. $data['end_time'] = $end;
  946. $data['operation_time'] = time();
  947. // list($status, $msg) = $this->synFreightFeeFromMine($data, $user);dd(333);
  948. list($status,$msg) = $this->limitingSendRequest($this->table_3);
  949. if(! $status) return [false, '运费统计同步正在后台运行,请稍后'];
  950. //同步
  951. // list($status, $msg) = $this->synFreightFeeFromMine($data, $user);
  952. // if(! $status) {
  953. // $this->dellimitingSendRequest($this->table_3);
  954. // return [false, $msg];
  955. // }
  956. //队列
  957. ProcessDataJob::dispatch($data, $user, 3)->onQueue(RevenueCost::job3);
  958. return [true, '运费统计同步已进入后台任务'];
  959. }
  960. public function synFreightFeeFromMine($data, $user){
  961. //创建临时表 如果不存在
  962. $this->createTmpTable3();
  963. //清理临时表 如果内容不为空
  964. $this->clearTmpTable(3);
  965. //生成临时数据
  966. list($status, $msg) = $this->getFreightData($data);
  967. if(! $status) return [false, $msg];
  968. //写入
  969. list($status, $msg) = $this->updateFreightFeeFromMine($data);
  970. if(! $status) return [false, $msg];
  971. //清理临时表 如果内容不为空
  972. $this->clearTmpTable(3);
  973. //释放redis
  974. $this->delTableKey(3);
  975. return [true, '同步成功'];
  976. }
  977. private function createTmpTable3(){
  978. $table = $this->table_3;
  979. if (! Schema::hasTable($table)) {
  980. // 可以通过 migration 创建,或程序启动时检查
  981. Schema::create($table, function (Blueprint $table) {
  982. // 主键
  983. $table->bigIncrements('id');
  984. // 原始字段
  985. $table->bigInteger('order_id')->default(0)->comment('订单ID');
  986. $table->string('order_number')->default('')->comment('订单编号');
  987. $table->dateTime('order_time')->nullable()->comment('订单时间');
  988. $table->integer('order_state')->default(0)->comment('订单状态');
  989. $table->string('employee_id_1_title')->default('')->comment('业务员1名称');
  990. $table->bigInteger('employee_id_1')->default(0)->comment('业务员1 ID');
  991. $table->string('employee_id_2_title')->default('')->comment('上级管理人员名称');
  992. $table->bigInteger('employee_id_2')->default(0)->comment('上级管理人员ID');
  993. $table->string('customer_code')->default('')->comment('客户编码');
  994. $table->string('customer_title')->default('')->comment('客户名称');
  995. $table->decimal('customer_store_price', 10, 2)->default(0)->comment('客户卸货费单价');
  996. $table->string('product_code')->default('')->comment('产品编码');
  997. $table->string('product_title')->default('')->comment('产品名称');
  998. $table->string('product_size')->default('')->comment('产品规格');
  999. $table->decimal('product_box_size', 10, 2)->default(0)->comment('装箱数');
  1000. $table->decimal('product_weight', 10, 3)->default(0)->comment('单件重量(kg)');
  1001. $table->decimal('product_store_price', 10, 2)->default(0)->comment('门店卸货费单价');
  1002. $table->decimal('product_store_price2', 10, 2)->default(0)->comment('到货装卸费单价');
  1003. $table->string('product_category')->default('')->comment('货类');
  1004. $table->string('unit')->default('')->comment('单位');
  1005. $table->decimal('quantity', 12, 3)->default(0)->comment('数量');
  1006. $table->decimal('price_3', 12, 2)->default(0)->comment('含税单价');
  1007. $table->decimal('price_3_total', 14, 2)->default(0)->comment('含税金额');
  1008. $table->bigInteger('id_detail')->default(0)->comment('明细ID');
  1009. $table->boolean('is_present')->default(false)->comment('是否赠品');
  1010. $table->string('mark')->default('')->comment('订单备注');
  1011. $table->string('item_mark')->default('')->comment('明细备注');
  1012. $table->bigInteger('warehouse_id')->default(0)->comment('仓库ID');
  1013. $table->string('warehouse_name')->default('')->comment('仓库名称');
  1014. $table->bigInteger('business_type_id')->default(0)->comment('业务类型ID');
  1015. $table->string('business_type_title')->default('')->comment('业务类型名称');
  1016. $table->string('address')->default('')->comment('送货地址');
  1017. $table->string('area_hs')->default('')->comment('区域');
  1018. $table->string('delivery_mode')->default('')->comment('配送方式');
  1019. $table->decimal('sl_fee', 10, 2)->default(0)->comment('其它费用');
  1020. // 新增的计算字段
  1021. $table->integer('xs')->default(0)->comment('箱数');
  1022. $table->decimal('weight', 12, 3)->default(0)->comment('总重量(kg)');
  1023. $table->tinyInteger('area_range')->default(1)->comment('运价区间 (1: <5kg, 2: >=5kg)');
  1024. $table->decimal('freight_unit_price', 10, 2)->default(0)->comment('配送费单价');
  1025. $table->decimal('freight_amount', 12, 2)->default(0)->comment('配送费金额');
  1026. $table->decimal('js_single_amount', 12, 2)->default(0)->comment('结算金额');
  1027. $table->decimal('min_freight_amount', 12, 2)->default(0)->comment('地区最低运价');
  1028. $table->decimal('customer_store_zx_fee', 12, 2)->default(0)->comment('门店卸货费');
  1029. $table->decimal('dh_fee', 12, 2)->default(0)->comment('到货装卸费');
  1030. });
  1031. }
  1032. }
  1033. private function getFreightData($data){
  1034. //写入临时表
  1035. try {
  1036. $table = $this->table_3;
  1037. $limit = 500;
  1038. $lastId = 0;
  1039. do {
  1040. $rows = $this->databaseService->table('SA_SaleDelivery_b as sd_b')
  1041. ->join('SA_SaleDelivery as sd', 'sd_b.idSaleDeliveryDTO', '=', 'sd.ID')
  1042. ->leftJoin('AA_Partner as pn', 'sd.idsettlecustomer', '=', 'pn.ID') // 结算客户
  1043. ->leftJoin('AA_Person as ps', 'sd.idclerk', '=', 'ps.ID') // 业务员
  1044. ->leftJoin('AA_Person as ps2', 'pn.idsaleman', '=', 'ps2.ID')
  1045. ->leftJoin('AA_Inventory as it', 'sd_b.idinventory', '=', 'it.ID')
  1046. ->leftJoin('AA_Unit as ui', 'sd_b.idbaseunit', '=', 'ui.ID')
  1047. ->leftJoin('AA_Warehouse as wa', 'sd_b.idwarehouse', '=', 'wa.id')
  1048. ->leftJoin('AA_Busitype as bs', 'sd.idbusinesstype', '=', 'bs.id')
  1049. ->where('sd.voucherdate', '>=', $data['start_time'])
  1050. ->where('sd.voucherdate', '<=', $data['end_time'])
  1051. ->where('sd.voucherState', '=', 189) //181 未审核 189 已审核
  1052. ->where('sd_b.ID', '>', $lastId) // 用真实字段
  1053. ->orderBy('sd_b.ID')
  1054. ->limit($limit)
  1055. ->selectRaw("
  1056. COALESCE(sd.ID, 0) as order_id,
  1057. COALESCE(sd.code, '') as order_number,
  1058. sd.voucherdate as order_time,
  1059. sd.voucherState as order_state,
  1060. COALESCE(ps.name, '') as employee_id_1_title,
  1061. COALESCE(sd.idclerk, 0) as employee_id_1,
  1062. COALESCE(ps2.name, '') as employee_id_2_title,
  1063. COALESCE(pn.idsaleman, 0) as employee_id_2,
  1064. COALESCE(pn.code, '') as customer_code,
  1065. COALESCE(pn.name, '') as customer_title,
  1066. COALESCE(pn.priuserdefdecm3, 0) as customer_store_price,
  1067. COALESCE(it.code, '') as product_code,
  1068. COALESCE(it.name, '') as product_title,
  1069. COALESCE(it.specification, '') as product_size,
  1070. COALESCE(it.priuserdefdecm1, 0) as product_box_size,
  1071. COALESCE(it.priuserdefdecm3, 0) as product_weight,
  1072. COALESCE(it.priuserdefdecm10, 0) as product_store_price,
  1073. COALESCE(it.priuserdefdecm9, 0) as product_store_price2,
  1074. COALESCE(it.priuserdefnvc5, '') as product_category,
  1075. COALESCE(ui.name, '') as unit,
  1076. COALESCE(sd_b.quantity, 0) as quantity,
  1077. COALESCE(sd_b.taxPrice, 0) as price_3,
  1078. COALESCE(sd_b.taxAmount, 0) as price_3_total,
  1079. COALESCE(sd_b.ID, 0) as id_detail,
  1080. COALESCE(sd_b.isPresent, 0) as is_present,
  1081. COALESCE(sd_b.DetailMemo, '') as item_mark,
  1082. COALESCE(sd.memo, '') as mark,
  1083. sd_b.idwarehouse as warehouse_id,
  1084. COALESCE(wa.name, '') as warehouse_name,
  1085. sd.idbusinesstype as business_type_id,
  1086. COALESCE(bs.name , '') as business_type_title,
  1087. COALESCE(sd.address , '') as address,
  1088. COALESCE(sd.priuserdefnvc2 , '') as area_hs,
  1089. COALESCE(sd.deliveryMode , 0) as delivery_mode,
  1090. COALESCE(sd.priuserdefdecm5 , 0) as sl_fee
  1091. ")
  1092. ->get();
  1093. if ($rows->isEmpty()) break;
  1094. $dataArray = Collect($rows)->map(function ($object) {
  1095. return (array)$object;
  1096. })->toArray();
  1097. $freight = Freight::where('del_time',0)
  1098. ->whereIn('region',array_column($dataArray,'area_hs'))
  1099. ->select('region','one_and_five','greater_than_five','min_freight_fee')
  1100. ->get()->toArray();
  1101. $freight_map = array_column($freight,null,'region');
  1102. //组织数据
  1103. foreach ($dataArray as $key => $value) {
  1104. $quantity = abs($value['quantity']);
  1105. //箱数
  1106. $xs = 0;
  1107. if(! empty($value['product_box_size']) && is_numeric($value['product_box_size']) && $value['product_box_size'] > 0) $xs = ceil($quantity / $value['product_box_size']);
  1108. $dataArray[$key]['xs'] = $xs;
  1109. //总重量
  1110. $weight = 0;
  1111. if(! empty($value['product_weight']) && is_numeric($value['product_weight']) && $value['product_weight'] > 0) $weight = bcdiv(bcmul($xs, $value['product_weight']),1000,3);
  1112. $dataArray[$key]['weight'] = $weight;
  1113. //运价区间
  1114. $area_range = 1;
  1115. if($weight >= 5) $area_range = 2;
  1116. $dataArray[$key]['area_range'] = $area_range;
  1117. //配送费单价
  1118. $freight = $min_freight = 0;
  1119. if(isset($freight_map[$value['area_hs']])) {
  1120. $tmp = $freight_map[$value['area_hs']];
  1121. if($area_range == 1){
  1122. $freight = $tmp['one_and_five'];
  1123. }else{
  1124. $freight = $tmp['greater_than_five'];
  1125. }
  1126. $min_freight = $tmp['min_freight_fee'];
  1127. }
  1128. $dataArray[$key]['freight_unit_price'] = $freight;
  1129. //配送费金额
  1130. $freight_amount = bcmul($weight, $freight,2);
  1131. $dataArray[$key]['freight_amount'] = $freight_amount;
  1132. //结算金额 记录的是每一条的
  1133. $dataArray[$key]['js_single_amount'] = $freight_amount;
  1134. //地区最低运价
  1135. $dataArray[$key]['min_freight_amount'] = $min_freight;
  1136. //门店卸货费
  1137. $customer_store_price = 0;
  1138. if(! empty($value['customer_store_price']) && is_numeric($value['customer_store_price']) && $value['customer_store_price'] > 0){
  1139. $customer_store_price = bcmul($value['customer_store_price'], $xs,2);
  1140. }else{
  1141. if(! empty($value['product_store_price']) && is_numeric($value['product_store_price']) && $value['product_store_price'] > 0){
  1142. $customer_store_price = bcmul($value['product_store_price'], $xs,2);
  1143. }
  1144. }
  1145. $dataArray[$key]['customer_store_zx_fee'] = $customer_store_price;
  1146. //到货装卸费
  1147. $product_store_price2 = 0;
  1148. if(! empty($value['product_store_price2']) && is_numeric($value['product_store_price2'])) $product_store_price2 = $value['product_store_price2'];
  1149. if(! empty($value['product_category']) && $value['product_category'] == "礼盒"){
  1150. $dh_fee = bcmul($xs, $product_store_price2,2);
  1151. }else{
  1152. $dh_fee = bcmul($weight, $product_store_price2,2);
  1153. }
  1154. if($value['business_type_id'] == FreightFee::businessTypeReturn) $dh_fee = bcmul($dh_fee,2,2);
  1155. $dataArray[$key]['dh_fee'] = $dh_fee;
  1156. }
  1157. DB::table($table)->insert($dataArray);
  1158. // 更新 lastId 继续下一批
  1159. $lastId = end($dataArray)['id_detail'] ?? $lastId;
  1160. } while (count($rows) === $limit);
  1161. }catch (\Throwable $exception){
  1162. return [false, "运费获取销货单数据异常" . $exception->getMessage() . "|" . $exception->getLine() . "|" . $exception->getFile()];
  1163. }
  1164. return [true, ''];
  1165. }
  1166. private function updateFreightFeeFromMine($data){
  1167. try {
  1168. $start_timeStamp = $data['start_time'];
  1169. $end_timeStamp = $data['end_time'];
  1170. $tmpTable = $this->table_3;
  1171. $time = time();
  1172. $ergs = $data;
  1173. DB::transaction(function () use ($start_timeStamp, $end_timeStamp, $tmpTable,$time, $ergs) {
  1174. // 1. 先软删除旧数据(你已有)
  1175. FreightFee::where('del_time', 0)
  1176. ->where('order_time', '>=', $start_timeStamp)
  1177. ->where('order_time', '<=', $end_timeStamp)
  1178. ->update(['del_time' => $time]);
  1179. // 2. 分批从临时表插入新数据
  1180. $batchSize = 500;
  1181. $lastId = 0;
  1182. do {
  1183. $chunk = DB::table($tmpTable)
  1184. ->where('id', '>', $lastId)
  1185. ->orderBy('id')
  1186. ->limit($batchSize)
  1187. ->get();
  1188. if ($chunk->isEmpty()) {
  1189. break;
  1190. }
  1191. $data = $chunk->map(function ($item) use($time){
  1192. return [
  1193. // 基础字段(按你给的顺序)
  1194. 'order_id' => $item->order_id ?? 0,
  1195. 'order_number' => $item->order_number ?? '',
  1196. 'order_time' => $item->order_time ? strtotime($item->order_time) : 0,
  1197. 'order_state' => $item->order_state ?? 0,
  1198. 'employee_id_1_title' => $item->employee_id_1_title ?? '',
  1199. 'employee_id_1' => $item->employee_id_1 ?? 0,
  1200. 'employee_id_2_title' => $item->employee_id_2_title ?? '',
  1201. 'employee_id_2' => $item->employee_id_2 ?? 0,
  1202. 'customer_code' => $item->customer_code ?? '',
  1203. 'customer_title' => $item->customer_title ?? '',
  1204. 'customer_store_price' => $item->customer_store_price ?? 0,
  1205. 'product_code' => $item->product_code ?? '',
  1206. 'product_title' => $item->product_title ?? '',
  1207. 'product_size' => $item->product_size ?? '',
  1208. 'product_box_size' => $item->product_box_size ?? 0,
  1209. 'product_weight' => $item->product_weight ?? 0,
  1210. 'product_store_price' => $item->product_store_price ?? 0,
  1211. 'product_store_price2' => $item->product_store_price2 ?? 0,
  1212. 'product_category' => $item->product_category ?? '',
  1213. 'unit' => $item->unit ?? '',
  1214. 'quantity' => $item->quantity ?? 0,
  1215. 'price_3' => $item->price_3 ?? 0,
  1216. 'price_3_total' => $item->price_3_total ?? 0,
  1217. 'id_detail' => $item->id_detail ?? 0,
  1218. 'is_present' => $item->is_present ?? '',
  1219. 'mark' => $item->mark ?? '',
  1220. 'item_mark' => $item->item_mark ?? '',
  1221. 'warehouse_id' => $item->warehouse_id ?? 0,
  1222. 'warehouse_name' => $item->warehouse_name ?? '',
  1223. 'business_type_id' => $item->business_type_id ?? 0,
  1224. 'business_type_title' => $item->business_type_title ?? '',
  1225. 'address' => $item->address ?? '',
  1226. 'area_hs' => $item->area_hs ?? '',
  1227. 'delivery_mode' => $item->delivery_mode ?? 0,
  1228. 'sl_fee' => $item->sl_fee ?? 0,
  1229. 'xs' => $item->xs,
  1230. 'weight' => $item->weight ?? 0,
  1231. 'area_range' => $item->area_range ?? 0,
  1232. 'freight_unit_price' => $item->freight_unit_price ?? 0,
  1233. 'freight_amount' => $item->freight_amount ?? 0,
  1234. 'js_single_amount' => $item->js_single_amount ?? 0,
  1235. 'min_freight_amount' => $item->min_freight_amount ?? 0,
  1236. 'customer_store_zx_fee' => $item->customer_store_zx_fee ?? 0,
  1237. 'dh_fee' => $item->dh_fee ?? 0,
  1238. 'crt_time' => $time,
  1239. ];
  1240. })->toArray();
  1241. // 每批单独插入(可选:加小事务)
  1242. FreightFee::insert($data);
  1243. // 更新 lastId
  1244. $lastId = $chunk->last()->id;
  1245. } while ($chunk->count() == $batchSize);
  1246. });
  1247. }catch (\Throwable $exception){
  1248. return [false, "单据明细同步异常" . $exception->getMessage() . "|" . $exception->getLine() . "|" . $exception->getFile()];
  1249. }
  1250. return [true, ''];
  1251. }
  1252. }