TPlusServerService.php 141 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065206620672068206920702071207220732074207520762077207820792080208120822083208420852086208720882089209020912092209320942095209620972098209921002101210221032104210521062107210821092110211121122113211421152116211721182119212021212122212321242125212621272128212921302131213221332134213521362137213821392140214121422143214421452146214721482149215021512152215321542155215621572158215921602161216221632164216521662167216821692170217121722173217421752176217721782179218021812182218321842185218621872188218921902191219221932194219521962197219821992200220122022203220422052206220722082209221022112212221322142215221622172218221922202221222222232224222522262227222822292230223122322233223422352236223722382239224022412242224322442245224622472248224922502251225222532254225522562257225822592260226122622263226422652266226722682269227022712272227322742275227622772278227922802281228222832284228522862287228822892290229122922293229422952296229722982299230023012302230323042305230623072308230923102311231223132314231523162317231823192320232123222323232423252326232723282329233023312332233323342335233623372338233923402341234223432344234523462347234823492350235123522353235423552356235723582359236023612362236323642365236623672368236923702371237223732374237523762377237823792380238123822383238423852386238723882389239023912392239323942395239623972398239924002401240224032404240524062407240824092410241124122413241424152416241724182419242024212422242324242425242624272428242924302431243224332434243524362437243824392440244124422443244424452446244724482449245024512452245324542455245624572458245924602461246224632464246524662467246824692470247124722473247424752476247724782479248024812482248324842485248624872488248924902491249224932494249524962497249824992500250125022503250425052506250725082509251025112512251325142515251625172518251925202521252225232524252525262527252825292530253125322533253425352536253725382539254025412542254325442545254625472548254925502551255225532554255525562557255825592560256125622563256425652566256725682569257025712572257325742575257625772578257925802581258225832584258525862587258825892590259125922593259425952596259725982599260026012602260326042605260626072608260926102611261226132614261526162617261826192620262126222623262426252626262726282629263026312632263326342635263626372638263926402641264226432644264526462647264826492650265126522653265426552656265726582659266026612662266326642665266626672668266926702671267226732674267526762677267826792680268126822683268426852686268726882689269026912692269326942695269626972698269927002701270227032704270527062707270827092710271127122713271427152716271727182719272027212722272327242725272627272728272927302731273227332734273527362737273827392740274127422743274427452746274727482749275027512752275327542755275627572758275927602761276227632764276527662767276827692770277127722773277427752776277727782779278027812782278327842785278627872788278927902791279227932794279527962797279827992800280128022803280428052806280728082809281028112812281328142815281628172818281928202821282228232824282528262827282828292830283128322833283428352836283728382839284028412842284328442845284628472848284928502851285228532854285528562857285828592860286128622863286428652866286728682869287028712872287328742875
  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\ItemReport;
  11. use App\Model\ItemReportMan;
  12. use App\Model\ItemReportRoad;
  13. use App\Model\Product;
  14. use App\Model\RevenueCost;
  15. use App\Model\RevenueCostTotal;
  16. use App\Model\SalaryEmployee;
  17. use Illuminate\Database\Schema\Blueprint;
  18. use Illuminate\Support\Facades\DB;
  19. use Illuminate\Support\Facades\Schema;
  20. class TPlusServerService extends Service
  21. {
  22. /**
  23. * @var TPlusDatabaseServerService
  24. */
  25. protected $databaseService;
  26. /**
  27. * @var string|null
  28. */
  29. protected $error;
  30. /**
  31. * TPlusServerService constructor.
  32. */
  33. public function __construct()
  34. {
  35. $service = new TPlusDatabaseServerService();
  36. $this->databaseService = $service->db;
  37. $this->error = $service->error;
  38. }
  39. /**
  40. * 获取错误信息
  41. *
  42. * @return string|null
  43. */
  44. public function getError()
  45. {
  46. return $this->error;
  47. }
  48. private $table = "tmp_revenue_cost_data";
  49. private $table_2 = "tmp_salary_employee";
  50. private $table_3 = "tmp_freight_fee";
  51. private $table_4 = "tmp_item_road";
  52. private $table_5 = "tmp_item_cost";
  53. /**
  54. * 同步人员部门
  55. *
  56. * @param array $data
  57. * @param array $user
  58. * @return array
  59. */
  60. public function synPersonDepart($data, $user)
  61. {
  62. try {
  63. $this->databaseService->table('AA_Department')
  64. ->select('id','idparent as parent_id','name as title','code','disabled as is_use')
  65. ->chunkById(100, function ($data) {
  66. DB::transaction(function () use ($data) {
  67. $dataArray = Collect($data)->map(function ($object) {
  68. return (array)$object;
  69. })->toArray();
  70. $d_id = Depart::whereIn('id', array_column($dataArray,'id'))
  71. ->pluck('id')
  72. ->toArray();
  73. $insert = $update = [];
  74. foreach ($dataArray as $value){
  75. $is_use = $value['is_use'] ? 0 : 1;
  76. if(in_array($value['id'], $d_id)){
  77. $update[] = [
  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. }else{
  85. $insert[] = [
  86. 'id' => $value['id'],
  87. 'parent_id' => $value['parent_id'],
  88. 'title' => $value['title'],
  89. 'code' => $value['code'],
  90. 'is_use' => $is_use
  91. ];
  92. }
  93. }
  94. if(! empty($insert)) Depart::insert($insert);
  95. if(! empty($update)) {
  96. foreach ($update as $value){
  97. Depart::where('id', $value['id'])
  98. ->update($value);
  99. }
  100. }
  101. });
  102. });
  103. $this->databaseService->table('AA_Person')
  104. ->select('id','code as number','name as emp_name','mobilePhoneNo as mobile','iddepartment as depart_id','disabled as state')
  105. ->chunkById(100, function ($data) {
  106. DB::transaction(function () use ($data) {
  107. $dataArray = Collect($data)->map(function ($object) {
  108. return (array)$object;
  109. })->toArray();
  110. $employee_id = Employee::whereIn('id', array_column($dataArray,'id'))
  111. ->pluck('id')
  112. ->toArray();
  113. $insert = $update = $depart_update = [];
  114. foreach ($dataArray as $value){
  115. $state = $value['state'] ? Employee::NOT_USE : Employee::USE;
  116. if(in_array($value['id'], $employee_id)){
  117. $update[] = [
  118. 'id' => $value['id'],
  119. 'number' => $value['number'],
  120. 'emp_name' => $value['emp_name'],
  121. 'mobile' => $value['mobile'],
  122. 'state' => $state
  123. ];
  124. }else{
  125. $insert[] = [
  126. 'id' => $value['id'],
  127. 'number' => $value['number'],
  128. 'emp_name' => $value['emp_name'],
  129. 'mobile' => $value['mobile'],
  130. 'state' => $state
  131. ];
  132. }
  133. $depart_update[] = [
  134. 'employee_id' => $value['id'],
  135. 'depart_id' => $value['depart_id']
  136. ];
  137. }
  138. if(! empty($insert)) Employee::insert($insert);
  139. if(! empty($update)) {
  140. foreach ($update as $value){
  141. Employee::where('id', $value['id'])
  142. ->update($value);
  143. }
  144. }
  145. if(! empty($depart_update)){
  146. EmployeeDepartPermission::whereIn('employee_id',array_column($depart_update,'employee_id'))->delete();
  147. EmployeeDepartPermission::insert($depart_update);
  148. }
  149. });
  150. });
  151. } catch (\Throwable $e) {
  152. return [false, $e->getMessage()];
  153. }
  154. return [true, ''];
  155. }
  156. /**
  157. * 收入成本统计同步
  158. *
  159. * @param array $data
  160. * @param array $user
  161. * @return array
  162. */
  163. public function synRevenueCost($data, $user){
  164. if(empty($data['crt_time'][0]) || empty($data['crt_time'][1])) return [false, '同步时间不能为空'];
  165. list($start_time, $end_time) = $this->changeDateToTimeStampAboutRange($data['crt_time'],false);
  166. if ($start_time === null || $end_time === null || $start_time > $end_time) return [false, "同步时间:时间区间无效"];
  167. list($bool, $bool_msg) = $this->isWithinMonths($start_time, $end_time);
  168. if(! $bool) return [false, $bool_msg];
  169. $data['start_timeStamp'] = $start_time;
  170. $data['end_timeStamp'] = $end_time;
  171. $start = date('Y-m-d H:i:s.000', $start_time);
  172. $end = date('Y-m-d H:i:s.000', $end_time);
  173. $data['start_time'] = $start;
  174. $data['end_time'] = $end;
  175. $data['operation_time'] = time();
  176. if(empty($data['type'])) return [false, '同步类型不能为空'];
  177. if(in_array($data['type'],[1,2,3,4])){
  178. list($status,$msg) = $this->limitingSendRequest($this->table);
  179. if(! $status) return [false, '收入成本相关信息同步正在后台运行,请稍后'];
  180. // //同步
  181. // list($status, $msg) = $this->synRevenueCostFromTPlus($data, $user);
  182. // if(! $status) {
  183. // return [false, $msg];
  184. // }
  185. //队列
  186. ProcessDataJob::dispatch($data, $user)->onQueue(RevenueCost::job);
  187. }else{
  188. return [false, '同步类型错误'];
  189. }
  190. return [true, '收入成本相关信息同步已进入后台任务'];
  191. }
  192. public function synRevenueCostFromTPlus($data, $user){
  193. //创建临时表 如果不存在
  194. $this->createTmpTable();
  195. //清理临时表 如果内容不为空
  196. $this->clearTmpTable();
  197. $type = $data['type'];
  198. //写入临时数据
  199. if($type == 1){
  200. list($status, $msg) = $this->xhdTPlus($data, $user);
  201. if(! $status) return [false, $msg];
  202. list($status, $msg) = $this->xsfpTPlus($data, $user);
  203. if(! $status) return [false, $msg];
  204. list($status, $msg) = $this->hkdTPlus($data, $user);
  205. if(! $status) return [false, $msg];
  206. }elseif ($type == 2){
  207. list($status, $msg) = $this->xhdTPlus($data, $user);
  208. if(! $status) return [false, $msg];
  209. }elseif ($type == 3){
  210. list($status, $msg) = $this->xsfpTPlus($data, $user);
  211. if(! $status) return [false, $msg];
  212. }elseif ($type == 4){
  213. list($status, $msg) = $this->hkdTPlus($data, $user);
  214. if(! $status) return [false, $msg];
  215. }
  216. //更新数据
  217. list($status,$msg) = $this->updateRevenueCost($data);
  218. if(! $status) return [false, $msg];
  219. // //更新主表数据
  220. // list($status,$msg) = $this->updateRevenueCostTotal($data);
  221. // if(! $status) return [false, $msg];
  222. //都成功后 清理临时表
  223. $this->clearTmpTable();
  224. //释放redis
  225. $this->delTableKey();
  226. return [true, '同步成功'];
  227. }
  228. private function xhdTPlus($data, $user){
  229. try {
  230. $table = $this->table;
  231. $limit = 500;
  232. $lastId = 0;
  233. do {
  234. $rows = $this->databaseService->table('SA_SaleDelivery_b as sd_b')
  235. ->join('SA_SaleDelivery as sd', 'sd_b.idSaleDeliveryDTO', '=', 'sd.ID')
  236. ->leftJoin('AA_Partner as pn', 'sd.idsettlecustomer', '=', 'pn.ID')
  237. ->leftJoin('AA_Person as ps', 'sd.idclerk', '=', 'ps.ID')
  238. ->leftJoin('AA_Person as ps2', 'pn.idsaleman', '=', 'ps2.ID')
  239. ->leftJoin('AA_Inventory as it', 'sd_b.idinventory', '=', 'it.ID')
  240. ->leftJoin('AA_Unit as ui', 'sd_b.idbaseunit', '=', 'ui.ID')
  241. ->where('sd.voucherdate', '>=', $data['start_time'])
  242. ->where('sd.voucherdate', '<=', $data['end_time'])
  243. ->where('sd_b.ID', '>', $lastId) // 用真实字段
  244. ->orderBy('sd_b.ID')
  245. ->limit($limit)
  246. ->selectRaw("
  247. COALESCE(sd.ID, 0) as order_id,
  248. COALESCE(sd.code, '') as order_number,
  249. sd.voucherdate as order_time,
  250. sd.voucherState as order_state,
  251. COALESCE(ps.name, '') as employee_id_1_title,
  252. COALESCE(sd.idclerk, 0) as employee_id_1,
  253. COALESCE(ps2.name, '') as employee_id_2_title,
  254. COALESCE(pn.idsaleman, 0) as employee_id_2,
  255. COALESCE(pn.code, '') as customer_code,
  256. COALESCE(pn.name, '') as customer_title,
  257. COALESCE(pn.priuserdefnvc14, '') as customer_profit_rate,
  258. COALESCE(sd.pubuserdefnvc11, '') as channel_finance,
  259. COALESCE(sd.pubuserdefnvc12, '') as channel_details,
  260. COALESCE(it.code, '') as product_code,
  261. COALESCE(it.name, '') as product_title,
  262. COALESCE(it.specification, '') as product_size,
  263. COALESCE(ui.name, '') as unit,
  264. COALESCE(sd_b.quantity, 0) as quantity,
  265. COALESCE(sd_b.taxPrice, 0) as price_3,
  266. COALESCE(sd_b.taxAmount, 0) as price_3_total,
  267. COALESCE(sd_b.ID, 0) as id_detail,
  268. COALESCE(sd_b.pubuserdefdecm9, 0) as is_activity
  269. ")
  270. ->get();
  271. if ($rows->isEmpty()) break;
  272. $dataArray = Collect($rows)->map(function ($object) {
  273. return (array)$object;
  274. })->toArray();
  275. //存货档案
  276. $product = Product::where('del_time', 0)
  277. ->whereIn('code', array_unique(array_column($dataArray, 'product_code')))
  278. ->select('code', 'write_off_price', 'freight_price', 'business_cost')
  279. ->get()->toArray();
  280. $product_map = array_column($product, null, 'code');
  281. //组织数据
  282. foreach ($dataArray as $key => $value) {
  283. $customer_profit_rate = rtrim($value['customer_profit_rate'],'%');
  284. if(is_numeric($customer_profit_rate)){
  285. $customer_profit_rate = bcdiv($customer_profit_rate,100,3);
  286. }else{
  287. $customer_profit_rate = 0;
  288. }
  289. $dataArray[$key]['customer_profit_rate'] = $customer_profit_rate;
  290. $p_tmp = $product_map[$value['product_code']] ?? [];
  291. $dataArray[$key]['order_type'] = RevenueCost::ORDER_ONE;
  292. $dataArray[$key]['order_time'] = strtotime($value['order_time']);
  293. $write_off_price = $p_tmp['write_off_price'] ?? 0;
  294. $dataArray[$key]['price_1'] = $write_off_price;
  295. $dataArray[$key]['price_1_total'] = bcmul($write_off_price, $value['quantity'], 2);
  296. $freight_price = $p_tmp['freight_price'] ?? 0;
  297. $dataArray[$key]['price_2'] = $freight_price;
  298. $dataArray[$key]['price_2_total'] = bcmul($freight_price, $value['quantity'], 2);
  299. $business_cost = $p_tmp['business_cost'] ?? 0;
  300. $dataArray[$key]['price_4'] = $business_cost;
  301. $price_4_total = bcmul($business_cost, $value['quantity'], 2);
  302. $dataArray[$key]['price_4_total'] = bcmul($business_cost, $value['quantity'], 2);
  303. $profit = bcsub($value['price_3_total'], $price_4_total, 2);
  304. $dataArray[$key]['profit'] = $profit;
  305. $dataArray[$key]['profit_rate'] = $value['price_3_total'] > 0 ? bcdiv($profit, $value['price_3_total'], 2) : 0;
  306. }
  307. DB::table($table)->insert($dataArray);
  308. // 更新 lastId 继续下一批
  309. $lastId = end($dataArray)['id_detail'] ?? $lastId;
  310. } while (count($rows) === $limit);
  311. }catch (\Throwable $exception){
  312. return [false, "销货单同步异常" . $exception->getMessage() . "|" . $exception->getLine() . "|" . $exception->getFile()];
  313. }
  314. return [true, ''];
  315. }
  316. private function xsfpTPlus($data, $user){
  317. try {
  318. $table = $this->table;
  319. $limit = 500;
  320. $lastId = 0;
  321. do {
  322. $rows = $this->databaseService->table('SA_SaleInvoice_b as si_b')
  323. ->join('SA_SaleInvoice as si', 'si_b.idSaleInvoiceDTO', '=', 'si.ID')
  324. ->leftJoin('SA_SaleDelivery_b as sd_b', 'si_b.sourceVoucherDetailId', '=', 'sd_b.ID')
  325. ->leftJoin('AA_Partner as pn', 'si.idsettlecustomer', '=', 'pn.ID')
  326. ->leftJoin('AA_Person as ps', 'si.idclerk', '=', 'ps.ID')
  327. ->leftJoin('AA_Person as ps2', 'pn.idsaleman', '=', 'ps2.ID')
  328. ->leftJoin('AA_Inventory as it', 'si_b.idinventory', '=', 'it.ID')
  329. ->leftJoin('AA_Unit as ui', 'si_b.idbaseunit', '=', 'ui.ID')
  330. ->where('si.voucherdate','>=',$data['start_time'])
  331. ->where('si.voucherdate','<=',$data['end_time'])
  332. ->where('si_b.ID', '>', $lastId) // 用真实字段
  333. ->orderBy('si_b.ID')
  334. ->limit($limit)
  335. ->selectRaw("
  336. COALESCE(si.ID, 0) as order_id,
  337. COALESCE(si.code, '') as order_number,
  338. si.voucherdate as order_time,
  339. si.voucherState as order_state,
  340. COALESCE(pn.code, '') as customer_code,
  341. COALESCE(pn.name, '') as customer_title,
  342. COALESCE(pn.priuserdefnvc14, '') as customer_profit_rate,
  343. COALESCE(si.idclerk, 0) as employee_id_1,
  344. COALESCE(ps.name, '') as employee_id_1_title,
  345. COALESCE(pn.idsaleman, 0) as employee_id_2,
  346. COALESCE(ps2.name, '') as employee_id_2_title,
  347. COALESCE(it.code, '') as product_code,
  348. COALESCE(it.name, '') as product_title,
  349. COALESCE(it.specification, '') as product_size,
  350. COALESCE(ui.name, '') as unit,
  351. COALESCE(si_b.quantity, 0) as quantity,
  352. COALESCE(si_b.taxPrice, 0) as price_1,
  353. COALESCE(si_b.taxAmount, 0) as price_1_total,
  354. COALESCE(si_b.ID, 0) as id_detail,
  355. COALESCE(si_b.sourceVoucherDetailId, 0) as id_detail_upstream,
  356. COALESCE(si_b.sourceVoucherCode, '') as order_number_upstream,
  357. COALESCE(sd_b.pubuserdefdecm9, 0) as is_activity
  358. ")
  359. ->get();
  360. if ($rows->isEmpty()) break;
  361. $dataArray = Collect($rows)->map(function ($object) {
  362. return (array)$object;
  363. })->toArray();
  364. //存货档案
  365. $product = Product::where('del_time',0)
  366. ->whereIn('code', array_unique(array_column($dataArray,'product_code')))
  367. ->select('code','business_cost')
  368. ->get()->toArray();
  369. $product_map = array_column($product,null,'code');
  370. //组织数据
  371. foreach ($dataArray as $key => $value){
  372. $customer_profit_rate = rtrim($value['customer_profit_rate'],'%');
  373. if(is_numeric($customer_profit_rate)){
  374. $customer_profit_rate = bcdiv($customer_profit_rate,100,3);
  375. }else{
  376. $customer_profit_rate = 0;
  377. }
  378. $dataArray[$key]['customer_profit_rate'] = $customer_profit_rate;
  379. $p_tmp = $product_map[$value['product_code']] ?? [];
  380. $dataArray[$key]['order_type'] = RevenueCost::ORDER_TWO;
  381. $dataArray[$key]['order_time'] = strtotime($value['order_time']);
  382. $business_cost = $p_tmp['business_cost'] ?? 0;
  383. $dataArray[$key]['price_4'] = $business_cost;
  384. $price_4_total = bcmul($business_cost, $value['quantity'],2);
  385. $dataArray[$key]['price_4_total'] = bcmul($business_cost, $value['quantity'],2);
  386. $profit = bcsub($value['price_1_total'], $price_4_total,2);
  387. $dataArray[$key]['profit'] = $profit;
  388. $dataArray[$key]['profit_rate'] = $value['price_1_total'] > 0 ? bcdiv($profit, $value['price_1_total'],2) : 0;
  389. }
  390. DB::table($table)->insert($dataArray);
  391. // 更新 lastId 继续下一批
  392. $lastId = end($dataArray)['id_detail'] ?? $lastId;
  393. } while (count($rows) === $limit);
  394. }catch (\Throwable $exception){
  395. return [false, "销售发票同步异常" . $exception->getMessage() . "|" . $exception->getLine() . "|" . $exception->getFile()];
  396. }
  397. return [true, ''];
  398. }
  399. private function hkdTPlus($data, $user){
  400. try{
  401. $table = $this->table;
  402. $limit = 500;
  403. $lastId = 0;
  404. do {
  405. $rows = $this->databaseService->table('ARAP_ReceivePayment_b as rp_b')
  406. ->join('ARAP_ReceivePayment as rp', 'rp_b.idArapReceivePaymentDTO', '=', 'rp.ID')
  407. // ->leftJoin('SA_SaleInvoice_b as si_b', 'rp_b.voucherDetailID', '=', 'si_b.ID')
  408. // ->leftJoin('SA_SaleInvoice as si', 'si_b.idSaleInvoiceDTO', '=', 'si.ID')
  409. // ->leftJoin('SA_SaleDelivery_b as sd_b', 'si_b.sourceVoucherDetailId', '=', 'sd_b.ID')
  410. // 发票子表关联(仅限 idvouchertype = 20)
  411. ->leftJoin('SA_SaleInvoice_b as si_b', function ($join) {
  412. $join->on('rp_b.voucherDetailID', '=', 'si_b.ID')
  413. ->where('rp_b.idvouchertype', '=', 20);
  414. })
  415. ->leftJoin('SA_SaleInvoice as si', function ($join) {
  416. $join->on('si_b.idSaleInvoiceDTO', '=', 'si.ID')
  417. ->where('rp_b.idvouchertype', '=', 20);
  418. })
  419. ->leftJoin('SA_SaleDelivery_b as sd_b', function ($join) {
  420. $join->on('si_b.sourceVoucherDetailId', '=', 'sd_b.ID')
  421. ->where('rp_b.idvouchertype', '=', 20);
  422. })
  423. ->leftJoin('AA_Partner as pn', 'si.idsettlecustomer', '=', 'pn.ID')
  424. ->leftJoin('AA_Person as ps', 'rp.idperson', '=', 'ps.ID')
  425. ->leftJoin('AA_Person as ps2', 'pn.idsaleman', '=', 'ps2.ID')
  426. ->leftJoin('AA_Inventory as it', 'si_b.idinventory', '=', 'it.ID')
  427. ->leftJoin('AA_Unit as ui', 'si_b.idbaseunit', '=', 'ui.ID')
  428. ->where('rp.voucherdate','>=',$data['start_time'])
  429. ->where('rp.voucherdate','<=',$data['end_time'])
  430. // ->where('rp_b.idvouchertype','=', 20) // 销售发票
  431. ->where('rp.isReceiveFlag','=', 1)
  432. ->where('rp_b.ID', '>', $lastId)
  433. ->orderBy('rp_b.ID')
  434. ->limit($limit)
  435. // ->selectRaw("
  436. // COALESCE(rp.ID, 0) as order_id,
  437. // COALESCE(rp.code, '') as order_number,
  438. // rp.voucherdate as order_time,
  439. // COALESCE(pn.code, '') as customer_code,
  440. // COALESCE(pn.name, '') as customer_title,
  441. // COALESCE(pn.priuserdefnvc14, '') as customer_profit_rate,
  442. // COALESCE(it.code, '') as product_code,
  443. // COALESCE(it.name, '') as product_title,
  444. // COALESCE(rp.idperson, 0) as employee_id_1,
  445. // COALESCE(ps.name, '') as employee_id_1_title,
  446. // COALESCE(pn.idsaleman, 0) as employee_id_2,
  447. // COALESCE(ps2.name, '') as employee_id_2_title,
  448. // COALESCE(it.specification, '') as product_size,
  449. // COALESCE(ui.name, '') as unit,
  450. // COALESCE(si_b.quantity, 0) as quantity,
  451. // COALESCE(si_b.taxPrice, 0) as price_1,
  452. // COALESCE(si_b.taxAmount, 0) as price_1_total,
  453. // COALESCE(rp_b.amount, 0) as payment_amount,
  454. // COALESCE(rp_b.ID, 0) as id_detail,
  455. // COALESCE(rp_b.voucherDetailID, 0) as id_detail_upstream,
  456. // COALESCE(rp_b.voucherCode, '') as order_number_upstream,
  457. // COALESCE(sd_b.pubuserdefdecm9, 0) as is_activity
  458. // ")
  459. ->selectRaw("
  460. COALESCE(rp.ID, 0) as order_id,
  461. COALESCE(rp.code, '') as order_number,
  462. rp.voucherdate as order_time,
  463. rp.voucherstate as order_state,
  464. COALESCE(rp.pubuserdefnvc11, '') as channel_finance,
  465. COALESCE(rp.pubuserdefnvc12, '') as channel_details,
  466. COALESCE(pn.code, '') as customer_code,
  467. COALESCE(pn.name, '') as customer_title,
  468. COALESCE(pn.priuserdefnvc14, '') as customer_profit_rate,
  469. CASE WHEN rp_b.idvouchertype = 20 THEN COALESCE(it.code, '') ELSE '' END as product_code,
  470. CASE WHEN rp_b.idvouchertype = 20 THEN COALESCE(it.name, '') ELSE '' END as product_title,
  471. COALESCE(rp.idperson, 0) as employee_id_1,
  472. COALESCE(ps.name, '') as employee_id_1_title,
  473. COALESCE(pn.idsaleman, 0) as employee_id_2,
  474. COALESCE(ps2.name, '') as employee_id_2_title,
  475. CASE WHEN rp_b.idvouchertype = 20 THEN COALESCE(it.specification, '') ELSE '' END as product_size,
  476. CASE WHEN rp_b.idvouchertype = 20 THEN COALESCE(ui.name, '') ELSE '' END as unit,
  477. CASE WHEN rp_b.idvouchertype = 20 THEN COALESCE(si_b.quantity, 0) ELSE 0 END as quantity,
  478. CASE WHEN rp_b.idvouchertype = 20 THEN COALESCE(si_b.taxPrice, 0) ELSE 0 END as price_1,
  479. CASE WHEN rp_b.idvouchertype = 20 THEN COALESCE(si_b.taxAmount, 0) ELSE 0 END as price_1_total,
  480. COALESCE(rp_b.origCurrentAmount, 0) as payment_amount,
  481. COALESCE(rp_b.ID, 0) as id_detail,
  482. COALESCE(rp_b.voucherDetailID, 0) as id_detail_upstream,
  483. COALESCE(rp_b.voucherCode, '') as order_number_upstream,
  484. CASE WHEN rp_b.idvouchertype = 20 THEN COALESCE(sd_b.pubuserdefdecm9, 0) ELSE 0 END as is_activity,
  485. rp_b.idvouchertype as voucher_type
  486. ")
  487. ->get();
  488. // COALESCE(rp_b.amount, 0) as payment_amount,
  489. if ($rows->isEmpty()) break;
  490. $dataArray = Collect($rows)->map(function ($object) {
  491. return (array)$object;
  492. })->toArray();
  493. //存货档案
  494. $product = Product::where('del_time',0)
  495. ->whereIn('code', array_unique(array_column($dataArray,'product_code')))
  496. ->select('code','business_cost')
  497. ->get()->toArray();
  498. $product_map = array_column($product,null,'code');
  499. //组织数据
  500. foreach ($dataArray as $key => $value){
  501. $customer_profit_rate = rtrim($value['customer_profit_rate'],'%');
  502. if(is_numeric($customer_profit_rate)){
  503. $customer_profit_rate = bcdiv($customer_profit_rate,100,3);
  504. }else{
  505. $customer_profit_rate = 0;
  506. }
  507. $dataArray[$key]['customer_profit_rate'] = $customer_profit_rate;
  508. $p_tmp = $product_map[$value['product_code']] ?? [];
  509. $dataArray[$key]['order_type'] = RevenueCost::ORDER_THREE;
  510. $dataArray[$key]['order_time'] = strtotime($value['order_time']);
  511. $business_cost = $p_tmp['business_cost'] ?? 0;
  512. $dataArray[$key]['price_4'] = $business_cost;
  513. $price_4_total = bcmul($business_cost, $value['quantity'],2);
  514. $dataArray[$key]['price_4_total'] = $price_4_total;
  515. $profit = bcsub($value['price_1_total'], $price_4_total,2);
  516. $dataArray[$key]['profit'] = $profit;
  517. $dataArray[$key]['profit_rate'] = $value['price_1_total'] > 0 ? bcdiv($profit, $value['price_1_total'],2) : 0;
  518. }
  519. DB::table($table)->insert($dataArray);
  520. // 更新 lastId 继续下一批
  521. $lastId = end($dataArray)['id_detail'] ?? $lastId;
  522. } while (count($rows) === $limit);
  523. }catch (\Throwable $exception){
  524. return [false, "回款单同步异常" . $exception->getMessage() . "|" . $exception->getLine() . "|" . $exception->getFile()];
  525. }
  526. return [true, ''];
  527. }
  528. private function updateRevenueCost($data){
  529. try {
  530. $start_timeStamp = $data['start_timeStamp'];
  531. $end_timeStamp = $data['end_timeStamp'];
  532. $tmpTable = $this->table;
  533. $time = time();
  534. $ergs = $data;
  535. DB::transaction(function () use ($start_timeStamp, $end_timeStamp, $tmpTable,$time, $ergs) {
  536. // 1. 先软删除旧数据(你已有)
  537. RevenueCost::where('del_time', 0)
  538. ->where('order_time', '>=', $start_timeStamp)
  539. ->where('order_time', '<=', $end_timeStamp)
  540. ->update(['del_time' => $time]);
  541. // 2. 分批从临时表插入新数据
  542. $batchSize = 500;
  543. $lastId = 0;
  544. do {
  545. $chunk = DB::table($tmpTable)
  546. ->where('id', '>', $lastId)
  547. ->orderBy('id')
  548. ->limit($batchSize)
  549. ->get();
  550. if ($chunk->isEmpty()) {
  551. break;
  552. }
  553. $data = $chunk->map(function ($item) use($time){
  554. return [
  555. 'order_id' => $item->order_id,
  556. 'order_number' => $item->order_number,
  557. 'order_time' => $item->order_time,
  558. 'order_state' => $item->order_state,
  559. 'employee_id_1_title' => $item->employee_id_1_title,
  560. 'employee_id_1' => $item->employee_id_1 ?? 0,
  561. 'employee_id_2' => $item->employee_id_2 ?? 0,
  562. 'employee_id_2_title' => $item->employee_id_2_title ?? "",
  563. 'customer_code' => $item->customer_code,
  564. 'customer_title' => $item->customer_title,
  565. 'channel_finance' => $item->channel_finance,
  566. 'channel_details' => $item->channel_details,
  567. 'product_code' => $item->product_code,
  568. 'product_title' => $item->product_title,
  569. 'product_size' => $item->product_size,
  570. 'unit' => $item->unit,
  571. 'quantity' => $item->quantity,
  572. 'price_1' => $item->price_1,
  573. 'price_1_total' => $item->price_1_total,
  574. 'price_2' => $item->price_2,
  575. 'price_2_total' => $item->price_2_total,
  576. 'price_3' => $item->price_3,
  577. 'price_3_total' => $item->price_3_total,
  578. 'price_4' => $item->price_4,
  579. 'price_4_total' => $item->price_4_total,
  580. 'profit' => $item->profit,
  581. 'profit_rate' => $item->profit_rate,
  582. 'id_detail' => $item->id_detail,
  583. 'order_type' => $item->order_type,
  584. 'payment_amount' => $item->payment_amount ?? 0,
  585. 'id_detail_upstream' => $item->id_detail_upstream?? 0,
  586. 'order_number_upstream' => $item->order_number_upstream ?? "",
  587. 'is_activity' => $item->is_activity ?? 0,
  588. 'customer_profit_rate' => $item->customer_profit_rate ?? '',
  589. 'voucher_type' => $item->voucher_type ?? 0,
  590. 'crt_time' => $time,
  591. ];
  592. })->toArray();
  593. // 每批单独插入(可选:加小事务)
  594. RevenueCost::insert($data);
  595. // 更新 lastId
  596. $lastId = $chunk->last()->id;
  597. } while ($chunk->count() == $batchSize);
  598. // 3. 更新主表
  599. list($status, $msg) = $this->updateRevenueCostTotal($ergs);
  600. if (! $status) {
  601. throw new \Exception($msg);
  602. }
  603. });
  604. }catch (\Throwable $exception){
  605. return [false, "单据明细同步异常" . $exception->getMessage() . "|" . $exception->getLine() . "|" . $exception->getFile()];
  606. }
  607. return [true, ''];
  608. }
  609. private function updateRevenueCostTotal($data){
  610. try {
  611. $start_timeStamp = $data['start_timeStamp'];
  612. $end_timeStamp = $data['end_timeStamp'];
  613. $time = time();
  614. //组织写入数据
  615. $return = [];
  616. $update_stamp = [];
  617. DB::table('revenue_cost')
  618. ->where('del_time',0)
  619. ->where('order_time', '>=', $start_timeStamp)
  620. ->where('order_time', '<=', $end_timeStamp)
  621. ->select(RevenueCost::$field)
  622. ->chunkById(100, function ($data) use(&$return,&$update_stamp){
  623. $dataArray = Collect($data)->map(function ($object){
  624. return (array)$object;
  625. })->toArray();
  626. foreach ($dataArray as $value){
  627. //变成每个月第一天的时间戳
  628. $time = date("Y-m-01", $value['order_time']);
  629. $stamp = strtotime($time);
  630. if(! in_array($stamp, $update_stamp)) $update_stamp[] = $stamp;
  631. if($value['order_type'] == RevenueCost::ORDER_ONE){
  632. $income = $value['price_3_total'];
  633. }elseif ($value['order_type'] == RevenueCost::ORDER_TWO){
  634. $income = $value['price_1_total'];
  635. }else{
  636. $income = $value['payment_amount'];
  637. }
  638. $adjust = $income < 0 ? $income : 0;
  639. $business = $value['price_4_total'];
  640. if(isset($return[$stamp][$value['order_type']][$value['employee_id_1']])){
  641. $income_total = bcadd($return[$stamp][$value['order_type']][$value['employee_id_1']]['income'], $income,2);
  642. $adjust_total = bcadd($return[$stamp][$value['order_type']][$value['employee_id_1']]['adjust'], $adjust,2);
  643. $business_total = bcadd($return[$stamp][$value['order_type']][$value['employee_id_1']]['business'], $business,2);
  644. $return[$stamp][$value['order_type']][$value['employee_id_1']]['income'] = $income_total;
  645. $return[$stamp][$value['order_type']][$value['employee_id_1']]['adjust'] = $adjust_total;
  646. $return[$stamp][$value['order_type']][$value['employee_id_1']]['business'] = $business_total;
  647. }else{
  648. $return[$stamp][$value['order_type']][$value['employee_id_1']] = [
  649. 'income' => $income,
  650. 'adjust' => $adjust,
  651. 'business' => $business,
  652. 'order_time' => $stamp,
  653. 'employee_id_1_title' => $value['employee_id_1_title'],
  654. ];
  655. }
  656. }
  657. });
  658. $insert = [];
  659. foreach ($return as $value){
  660. foreach ($value as $order_type => $val){
  661. foreach ($val as $employee_id => $v){
  662. $profit = bcsub($v['income'], $v['business'],2);
  663. $profit_rate = $v['income'] > 0 ? bcdiv($profit, $v['income'],2) : 0;
  664. $v['profit'] = $profit;
  665. $v['profit_rate'] = $profit_rate;
  666. $v['order_type'] = $order_type;
  667. $v['employee_id_1'] = $employee_id;
  668. $v['crt_time'] = $time;
  669. $insert[] = $v;
  670. }
  671. }
  672. }
  673. RevenueCostTotal::where('del_time', 0)
  674. ->whereIn('order_time', $update_stamp)
  675. ->update(['del_time' => $time]);
  676. RevenueCostTotal::insert($insert);
  677. }catch (\Throwable $exception){
  678. return [false, "主表同步异常" . $exception->getMessage() . "|" . $exception->getLine() . "|" . $exception->getFile()];
  679. }
  680. return [true, ''];
  681. }
  682. private function createTmpTable(){
  683. $table = $this->table;
  684. if (! Schema::hasTable($table)) {
  685. // 可以通过 migration 创建,或程序启动时检查
  686. Schema::create($table, function (Blueprint $table) {
  687. $table->bigIncrements('id'); // BIGINT UNSIGNED AUTO_INCREMENT PRIMARY KEY
  688. $table->integer('order_type')->default(0);
  689. $table->bigInteger('order_id')->default(0);
  690. $table->string('order_number', 50)->default('');
  691. $table->integer('order_time')->nullable();
  692. $table->integer('order_state')->default(0);
  693. $table->string('employee_id_1_title', 100)->default('');
  694. $table->bigInteger('employee_id_1')->default(0);
  695. $table->bigInteger('employee_id_2')->default(0);
  696. $table->string('employee_id_2_title', 100)->default('');
  697. $table->string('customer_code', 50)->default('');
  698. $table->string('customer_title', 100)->default('');
  699. $table->string('channel_finance', 50)->nullable();
  700. $table->string('channel_details', 50)->nullable();
  701. $table->string('product_code', 50)->default('');
  702. $table->string('product_title', 100)->default('');
  703. $table->string('product_size', 100)->nullable();
  704. $table->string('unit', 20)->nullable();
  705. $table->decimal('quantity', 12, 2)->default(0);
  706. $table->decimal('price_1', 12, 2)->default(0); // 销项成本
  707. $table->decimal('price_1_total', 12, 2)->default(0);
  708. $table->decimal('price_2', 12, 2)->default(0); // 运费
  709. $table->decimal('price_2_total', 12, 2)->default(0);
  710. $table->decimal('price_3', 12, 2)->default(0); // 含税单价
  711. $table->decimal('price_3_total', 12, 2)->default(0); // 含税金额
  712. $table->decimal('price_4', 12, 2)->default(0); // 业务成本
  713. $table->decimal('price_4_total', 12, 2)->default(0);
  714. $table->decimal('profit', 12, 2)->default(0);
  715. $table->decimal('payment_amount', 12, 2)->default(0);
  716. $table->decimal('profit_rate', 10, 3)->default(0);
  717. $table->bigInteger('id_detail')->default(0);
  718. $table->bigInteger('id_detail_upstream')->default(0);
  719. $table->string('order_number_upstream', 100)->nullable();
  720. $table->decimal('is_activity', 2, 0)->default(0);
  721. $table->string('customer_profit_rate', 20)->default('');
  722. $table->bigInteger('voucher_type')->default(0);
  723. });
  724. }
  725. }
  726. public function clearTmpTable($type = 1){
  727. if($type == 1){
  728. if (Schema::hasTable($this->table)) DB::table($this->table)->truncate();
  729. }elseif ($type == 2){
  730. if (Schema::hasTable($this->table_2)) DB::table($this->table_2)->truncate();
  731. }elseif ($type == 3){
  732. if (Schema::hasTable($this->table_3)) DB::table($this->table_3)->truncate();
  733. }elseif ($type == 4){
  734. if (Schema::hasTable($this->table_4)) DB::table($this->table_4)->truncate();
  735. if (Schema::hasTable($this->table_5)) DB::table($this->table_5)->truncate();
  736. }
  737. // elseif ($type == 5){
  738. // if (Schema::hasTable($this->table_5)) DB::table($this->table_5)->truncate();
  739. // }
  740. }
  741. public function delTableKey($type = 1){
  742. $key = $this->table;
  743. if($type == 2) $key = $this->table_2;
  744. if($type == 3) $key = $this->table_3;
  745. if($type == 4) $key = $this->table_4;
  746. $this->dellimitingSendRequest($key);
  747. }
  748. public function synSalaryEmployee($data, $user){
  749. if(empty($data['crt_time'][0]) || empty($data['crt_time'][1])) return [false, '同步时间不能为空'];
  750. list($start_time, $end_time) = $this->changeDateToTimeStampAboutRange($data['crt_time'],false);
  751. if ($start_time === null || $end_time === null || $start_time > $end_time) return [false, "同步时间:时间区间无效"];
  752. list($bool, $bool_msg) = $this->isWithinMonths($start_time, $end_time);
  753. if(! $bool) return [false, $bool_msg];
  754. $data['start_timeStamp'] = $start_time;
  755. $data['end_timeStamp'] = $end_time;
  756. $data['start_time'] = strtotime(date("Y-m-01",$data['start_timeStamp']));
  757. $data['end_time'] = strtotime(date("Y-m-01"),$data['end_timeStamp']);
  758. $data['operation_time'] = time();
  759. $data['type'] = 5;
  760. list($status,$msg) = $this->limitingSendRequest($this->table_2);
  761. if(! $status) return [false, '业务员工资同步正在后台运行,请稍后'];
  762. //同步
  763. // list($status, $msg) = $this->synSalaryEmployeeFromMine($data, $user);
  764. // if(! $status) {
  765. // $this->dellimitingSendRequest($this->table_2);
  766. // return [false, $msg];
  767. // }
  768. //队列
  769. ProcessDataJob::dispatch($data, $user, 2)->onQueue(RevenueCost::job2);
  770. return [true, '业务员工资相关信息同步已进入后台任务'];
  771. }
  772. public function synSalaryEmployeeFromMine($data, $user){
  773. //创建临时表 如果不存在
  774. $this->createTmpTable2();
  775. //清理临时表 如果内容不为空
  776. $this->clearTmpTable(2);
  777. //写入临时表
  778. DB::table('revenue_cost')
  779. ->where('del_time', 0)
  780. ->where('order_type', RevenueCost::ORDER_THREE)
  781. ->where('order_time','>=',$data['start_timeStamp'])
  782. ->where('order_time','<=',$data['end_timeStamp'])
  783. ->select([
  784. 'employee_id_1',
  785. 'employee_id_1_title',
  786. 'order_time as time',
  787. DB::raw("DATE_FORMAT(FROM_UNIXTIME(order_time), '%Y-%m-01') as order_time"),
  788. DB::raw("SUM(payment_amount) as payment_amount"),
  789. DB::raw("SUM(CASE WHEN is_activity = 0 THEN payment_amount ELSE 0 END) as payment_amount_not_include_activity"),
  790. DB::raw("SUM(CASE WHEN is_activity = 1 THEN payment_amount ELSE 0 END) as payment_amount_activity"),
  791. 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"),
  792. 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"),
  793. DB::raw("SUM(CASE WHEN profit_rate >= customer_profit_rate and is_activity = 0 THEN price_4_total ELSE 0 END) as business"),
  794. DB::raw("ROW_NUMBER() OVER (ORDER BY MIN(id)) as fake_id")
  795. ])
  796. ->groupBy('employee_id_1', DB::raw("DATE_FORMAT(FROM_UNIXTIME(order_time), '%Y-%m-01')"))
  797. ->orderBy('order_time', 'desc')
  798. ->chunkById(500, function ($data){
  799. $dataArray = Collect($data)->map(function ($object){
  800. return (array)$object;
  801. })->toArray();
  802. $indexes = $this->getEmployeeIndex($dataArray);
  803. foreach ($dataArray as $key => $value){
  804. $value['index_' . EmployeeIndex::TYPE_ONE] = 0;
  805. $value['index_' . EmployeeIndex::TYPE_SIX] = 0;
  806. $value['index_' . EmployeeIndex::TYPE_EIGHT] = 0;
  807. $this->findIndex($indexes, $value);
  808. $dataArray[$key]['order_type'] = RevenueCost::ORDER_THREE;
  809. $dataArray[$key]['order_time'] = strtotime($value['order_time']);
  810. $dataArray[$key]['sale_bonus'] = $value['index_' . EmployeeIndex::TYPE_EIGHT];
  811. $dataArray[$key]['index_' . EmployeeIndex::TYPE_ONE] = $value['index_' . EmployeeIndex::TYPE_ONE];
  812. $rate = bcdiv($value['index_' . EmployeeIndex::TYPE_ONE],100,2);
  813. $pay_in_advance = bcmul($rate, $value['payment_amount_greater_than_rate'],2);
  814. $dataArray[$key]['pay_in_advance'] = $pay_in_advance;
  815. $dataArray[$key]['basic_salary'] = $value['index_' . EmployeeIndex::TYPE_SIX];
  816. $dataArray[$key]['should_pay'] = bcadd(bcadd($value['index_' . EmployeeIndex::TYPE_EIGHT], $pay_in_advance,2),$value['index_' . EmployeeIndex::TYPE_SIX],2);
  817. unset($dataArray[$key]['fake_id']);
  818. unset($dataArray[$key]['time']);
  819. }
  820. DB::table($this->table_2)->insert($dataArray);
  821. }, 'fake_id');
  822. //更新数据
  823. list($status,$msg) = $this->updateSalaryEmployee($data);
  824. if(! $status) return [false, $msg];
  825. //清理临时表 如果内容不为空
  826. $this->clearTmpTable(2);
  827. //释放redis
  828. $this->delTableKey(2);
  829. return [true, '同步成功'];
  830. }
  831. private function getEmployeeIndex($existingData)
  832. {
  833. if (empty($existingData)) {
  834. return collect();
  835. }
  836. // 取出所有涉及的 employee_id 和时间区间
  837. $employeeIds = array_column($existingData, 'employee_id_1');
  838. $time = array_column($existingData, 'time');
  839. $minStart = ! empty($time) ? min($time) : 0;
  840. $maxEnd = ! empty($time) ? max($time) : 0;
  841. // 一次性查出这些员工在最大区间范围内的所有指标
  842. $results = EmployeeIndex::where('del_time', 0)
  843. ->whereIn('type', [EmployeeIndex::TYPE_ONE, EmployeeIndex::TYPE_EIGHT, EmployeeIndex::TYPE_SIX])
  844. ->whereIn('employee_id', $employeeIds)
  845. ->where('start_time', '<=', $maxEnd)
  846. ->where('end_time', '>=', $minStart)
  847. ->select('start_time','end_time','employee_id','index','type')
  848. ->get();
  849. return $results;
  850. }
  851. private function findIndex($indexes, &$value){
  852. // 找到所有符合条件的 index(可能多个 type)
  853. $matchedIndexes = $indexes->filter(function ($item) use ($value) {
  854. return $item['employee_id'] == $value['employee_id_1']
  855. && $item['start_time'] <= $value['time']
  856. && $item['end_time'] >= $value['time'];
  857. });
  858. // 按 type 去重,只保留第一次出现的
  859. $uniqueByType = [];
  860. foreach ($matchedIndexes as $item) {
  861. $index = "index_" . $item['type'];
  862. if (! isset($uniqueByType[$index])) {
  863. $uniqueByType[$index] = $item['index'];
  864. }
  865. }
  866. $value = array_merge($value, $uniqueByType);
  867. }
  868. private function createTmpTable2(){
  869. $table = $this->table_2;
  870. if (! Schema::hasTable($table)) {
  871. // 可以通过 migration 创建,或程序启动时检查
  872. Schema::create($table, function (Blueprint $table) {
  873. $table->bigIncrements('id'); // BIGINT UNSIGNED AUTO_INCREMENT PRIMARY KEY
  874. $table->integer('order_type')->default(0);
  875. $table->integer('order_time')->default(0);
  876. $table->string('employee_id_1_title', 100)->default('');
  877. $table->bigInteger('employee_id_1')->default(0);
  878. $table->decimal('payment_amount', 12, 2)->default(0);
  879. $table->decimal('payment_amount_not_include_activity', 12, 2)->default(0);
  880. $table->decimal('payment_amount_activity', 12, 2)->default(0);
  881. $table->decimal('payment_amount_lower_than_rate', 12, 2)->default(0);
  882. $table->decimal('payment_amount_greater_than_rate', 12, 2)->default(0);
  883. $table->decimal('business', 12, 2)->default(0);
  884. $table->decimal('sale_bonus', 12, 2)->default(0);
  885. $table->decimal('index_1', 10, 2)->default(0);
  886. $table->decimal('pay_in_advance', 12, 2)->default(0);
  887. $table->decimal('basic_salary', 12, 2)->default(0);
  888. $table->decimal('should_pay', 12, 2)->default(0);
  889. });
  890. }
  891. }
  892. private function updateSalaryEmployee($data){
  893. try {
  894. $start_timeStamp = $data['start_time'];
  895. $end_timeStamp = $data['end_time'];
  896. $tmpTable = $this->table_2;
  897. $time = time();
  898. $ergs = $data;
  899. DB::transaction(function () use ($start_timeStamp, $end_timeStamp, $tmpTable,$time, $ergs) {
  900. // 1. 先软删除旧数据(你已有)
  901. SalaryEmployee::where('del_time', 0)
  902. ->where('order_time', '>=', $start_timeStamp)
  903. ->where('order_time', '<=', $end_timeStamp)
  904. ->update(['del_time' => $time]);
  905. // 2. 分批从临时表插入新数据
  906. $batchSize = 500;
  907. $lastId = 0;
  908. do {
  909. $chunk = DB::table($tmpTable)
  910. ->where('id', '>', $lastId)
  911. ->orderBy('id')
  912. ->limit($batchSize)
  913. ->get();
  914. if ($chunk->isEmpty()) {
  915. break;
  916. }
  917. $data = $chunk->map(function ($item) use($time){
  918. return [
  919. 'order_type' => $item->order_type,
  920. 'order_time' => $item->order_time,
  921. 'employee_id_1_title' => $item->employee_id_1_title,
  922. 'employee_id_1' => $item->employee_id_1 ?? 0,
  923. 'payment_amount' => $item->payment_amount,
  924. 'payment_amount_not_include_activity' => $item->payment_amount_not_include_activity,
  925. 'payment_amount_activity' => $item->payment_amount_activity,
  926. 'payment_amount_lower_than_rate' => $item->payment_amount_lower_than_rate,
  927. 'payment_amount_greater_than_rate' => $item->payment_amount_greater_than_rate,
  928. 'business' => $item->business,
  929. 'sale_bonus' => $item->sale_bonus,
  930. 'index_1' => $item->index_1,
  931. 'pay_in_advance' => $item->pay_in_advance,
  932. 'basic_salary' => $item->basic_salary,
  933. 'should_pay' => $item->should_pay,
  934. 'crt_time' => $time,
  935. ];
  936. })->toArray();
  937. // 每批单独插入(可选:加小事务)
  938. SalaryEmployee::insert($data);
  939. // 更新 lastId
  940. $lastId = $chunk->last()->id;
  941. } while ($chunk->count() == $batchSize);
  942. });
  943. }catch (\Throwable $exception){
  944. return [false, "单据明细同步异常" . $exception->getMessage() . "|" . $exception->getLine() . "|" . $exception->getFile()];
  945. }
  946. return [true, ''];
  947. }
  948. public function synFreightFee($data, $user){
  949. if(empty($data['crt_time'][0]) || empty($data['crt_time'][1])) return [false, '同步时间不能为空'];
  950. list($start_time, $end_time) = $this->changeDateToTimeStampAboutRange($data['crt_time'],false);
  951. if ($start_time === null || $end_time === null || $start_time > $end_time) return [false, "同步时间:时间区间无效"];
  952. list($bool, $bool_msg) = $this->isWithinMonths($start_time, $end_time);
  953. if(! $bool) return [false, $bool_msg];
  954. $data['start_timeStamp'] = $start_time;
  955. $data['end_timeStamp'] = $end_time;
  956. $start = date('Y-m-d H:i:s.000', $start_time);
  957. $end = date('Y-m-d H:i:s.000', $end_time);
  958. $data['start_time'] = $start;
  959. $data['end_time'] = $end;
  960. $data['operation_time'] = time();
  961. $data['type'] = 6;
  962. // list($status, $msg) = $this->synFreightFeeFromMine($data, $user);dd($status, $msg);
  963. list($status,$msg) = $this->limitingSendRequest($this->table_3);
  964. if(! $status) return [false, '运费统计同步正在后台运行,请稍后'];
  965. //同步
  966. // list($status, $msg) = $this->synFreightFeeFromMine($data, $user);
  967. // if(! $status) {
  968. // $this->dellimitingSendRequest($this->table_3);
  969. // return [false, $msg];
  970. // }
  971. //队列
  972. ProcessDataJob::dispatch($data, $user, 3)->onQueue(RevenueCost::job3);
  973. return [true, '运费统计同步已进入后台任务'];
  974. }
  975. public function synFreightFeeFromMine($data, $user){
  976. //创建临时表 如果不存在
  977. $this->createTmpTable3();
  978. //清理临时表 如果内容不为空
  979. $this->clearTmpTable(3);
  980. //生成临时数据
  981. list($status, $msg) = $this->getFreightData($data);
  982. if(! $status) return [false, $msg];
  983. //写入
  984. list($status, $msg) = $this->updateFreightFeeFromMine($data);
  985. if(! $status) return [false, $msg];
  986. //清理临时表 如果内容不为空
  987. $this->clearTmpTable(3);
  988. //释放redis
  989. $this->delTableKey(3);
  990. return [true, '同步成功'];
  991. }
  992. private function createTmpTable3(){
  993. $table = $this->table_3;
  994. if (! Schema::hasTable($table)) {
  995. // 可以通过 migration 创建,或程序启动时检查
  996. Schema::create($table, function (Blueprint $table) {
  997. // 主键
  998. $table->bigIncrements('id');
  999. // 原始字段
  1000. $table->bigInteger('order_id')->default(0)->comment('订单ID');
  1001. $table->string('order_number')->default('')->comment('订单编号');
  1002. $table->dateTime('order_time')->nullable()->comment('订单时间');
  1003. $table->integer('order_state')->default(0)->comment('订单状态');
  1004. $table->string('employee_id_1_title')->default('')->comment('业务员1名称');
  1005. $table->bigInteger('employee_id_1')->default(0)->comment('业务员1 ID');
  1006. $table->string('employee_id_2_title')->default('')->comment('上级管理人员名称');
  1007. $table->bigInteger('employee_id_2')->default(0)->comment('上级管理人员ID');
  1008. $table->string('customer_code')->default('')->comment('客户编码');
  1009. $table->string('customer_title')->default('')->comment('客户名称');
  1010. $table->decimal('customer_store_price', 10, 2)->default(0)->comment('客户卸货费单价');
  1011. $table->string('product_code')->default('')->comment('产品编码');
  1012. $table->string('product_title')->default('')->comment('产品名称');
  1013. $table->string('product_size')->default('')->comment('产品规格');
  1014. $table->decimal('product_box_size', 10, 2)->default(0)->comment('装箱数');
  1015. $table->decimal('product_weight', 10, 3)->default(0)->comment('单件重量(kg)');
  1016. $table->decimal('product_store_price', 10, 2)->default(0)->comment('门店卸货费单价');
  1017. $table->decimal('product_store_price2', 10, 2)->default(0)->comment('到货装卸费单价');
  1018. $table->string('product_category')->default('')->comment('货类');
  1019. $table->string('unit')->default('')->comment('单位');
  1020. $table->decimal('quantity', 12, 3)->default(0)->comment('数量');
  1021. $table->decimal('price_3', 12, 2)->default(0)->comment('含税单价');
  1022. $table->decimal('price_3_total', 14, 2)->default(0)->comment('含税金额');
  1023. $table->bigInteger('id_detail')->default(0)->comment('明细ID');
  1024. $table->boolean('is_present')->default(false)->comment('是否赠品');
  1025. $table->string('mark')->default('')->comment('订单备注');
  1026. $table->string('item_mark')->default('')->comment('明细备注');
  1027. $table->bigInteger('warehouse_id')->default(0)->comment('仓库ID');
  1028. $table->string('warehouse_name')->default('')->comment('仓库名称');
  1029. $table->bigInteger('business_type_id')->default(0)->comment('业务类型ID');
  1030. $table->string('business_type_title')->default('')->comment('业务类型名称');
  1031. $table->string('address')->default('')->comment('送货地址');
  1032. $table->string('area_hs')->default('')->comment('区域');
  1033. $table->string('delivery_mode')->default('')->comment('配送方式');
  1034. $table->decimal('sl_fee', 10, 2)->default(0)->comment('上楼费');
  1035. // 新增的计算字段
  1036. $table->integer('xs')->default(0)->comment('箱数');
  1037. $table->decimal('weight', 12, 4)->default(0)->comment('总重量(kg)');
  1038. $table->tinyInteger('area_range')->default(1)->comment('运价区间 (1: <5kg, 2: >=5kg)');
  1039. $table->decimal('freight_unit_price', 10, 2)->default(0)->comment('配送费单价');
  1040. $table->decimal('freight_amount', 12, 4)->default(0)->comment('配送费金额');
  1041. $table->decimal('js_single_amount', 12, 4)->default(0)->comment('结算金额');
  1042. $table->decimal('min_freight_amount', 12, 2)->default(0)->comment('地区最低运价');
  1043. $table->decimal('customer_store_zx_fee', 12, 4)->default(0)->comment('门店卸货费');
  1044. $table->decimal('dh_fee', 12, 4)->default(0)->comment('到货装卸费');
  1045. });
  1046. }
  1047. }
  1048. private function getFreightData($data){
  1049. //写入临时表
  1050. try {
  1051. $table = $this->table_3;
  1052. $limit = 500;
  1053. $lastId = 0;
  1054. do {
  1055. $rows = $this->databaseService->table('SA_SaleDelivery_b as sd_b')
  1056. ->join('SA_SaleDelivery as sd', 'sd_b.idSaleDeliveryDTO', '=', 'sd.ID')
  1057. ->leftJoin('AA_Partner as pn', 'sd.idcustomer', '=', 'pn.ID') // 客户
  1058. ->leftJoin('AA_Person as ps', 'sd.idclerk', '=', 'ps.ID') // 业务员
  1059. ->leftJoin('AA_Person as ps2', 'pn.idsaleman', '=', 'ps2.ID')
  1060. ->leftJoin('AA_Inventory as it', 'sd_b.idinventory', '=', 'it.ID')
  1061. ->leftJoin('AA_Unit as ui', 'sd_b.idbaseunit', '=', 'ui.ID')
  1062. ->leftJoin('AA_Warehouse as wa', 'sd_b.idwarehouse', '=', 'wa.id')
  1063. ->leftJoin('AA_Busitype as bs', 'sd.idbusinesstype', '=', 'bs.id')
  1064. ->where('sd.voucherdate', '>=', $data['start_time'])
  1065. ->where('sd.voucherdate', '<=', $data['end_time'])
  1066. ->where('sd.voucherState', '=', 189) //181 未审核 189 已审核
  1067. ->where('sd_b.ID', '>', $lastId) // 用真实字段
  1068. ->orderBy('sd_b.ID')
  1069. ->limit($limit)
  1070. ->selectRaw("
  1071. COALESCE(sd.ID, 0) as order_id,
  1072. COALESCE(sd.code, '') as order_number,
  1073. sd.voucherdate as order_time,
  1074. sd.voucherState as order_state,
  1075. COALESCE(ps.name, '') as employee_id_1_title,
  1076. COALESCE(sd.idclerk, 0) as employee_id_1,
  1077. COALESCE(ps2.name, '') as employee_id_2_title,
  1078. COALESCE(pn.idsaleman, 0) as employee_id_2,
  1079. COALESCE(pn.code, '') as customer_code,
  1080. COALESCE(pn.name, '') as customer_title,
  1081. COALESCE(pn.priuserdefdecm3, 0) as customer_store_price,
  1082. COALESCE(it.code, '') as product_code,
  1083. COALESCE(it.name, '') as product_title,
  1084. COALESCE(it.specification, '') as product_size,
  1085. COALESCE(it.priuserdefdecm1, 0) as product_box_size,
  1086. COALESCE(it.priuserdefdecm3, 0) as product_weight,
  1087. COALESCE(it.priuserdefdecm10, 0) as product_store_price,
  1088. COALESCE(it.priuserdefdecm11, 0) as product_store_price2,
  1089. COALESCE(it.priuserdefnvc5, '') as product_category,
  1090. COALESCE(ui.name, '') as unit,
  1091. COALESCE(sd_b.quantity, 0) as quantity,
  1092. COALESCE(sd_b.taxPrice, 0) as price_3,
  1093. COALESCE(sd_b.taxAmount, 0) as price_3_total,
  1094. COALESCE(sd_b.ID, 0) as id_detail,
  1095. COALESCE(sd_b.isPresent, 0) as is_present,
  1096. COALESCE(sd_b.DetailMemo, '') as item_mark,
  1097. COALESCE(sd.memo, '') as mark,
  1098. sd_b.idwarehouse as warehouse_id,
  1099. COALESCE(wa.name, '') as warehouse_name,
  1100. sd.idbusinesstype as business_type_id,
  1101. COALESCE(bs.name , '') as business_type_title,
  1102. COALESCE(sd.address , '') as address,
  1103. COALESCE(sd.priuserdefnvc2 , '') as area_hs,
  1104. COALESCE(sd.deliveryMode , 0) as delivery_mode,
  1105. COALESCE(sd.priuserdefdecm5 , 0) as sl_fee
  1106. ")
  1107. ->get();
  1108. if ($rows->isEmpty()) break;
  1109. $dataArray = Collect($rows)->map(function ($object) {
  1110. return (array)$object;
  1111. })->toArray();
  1112. $freight = Freight::where('del_time',0)
  1113. ->whereIn('region',array_column($dataArray,'area_hs'))
  1114. ->select('region','one_and_five','greater_than_five','min_freight_fee')
  1115. ->get()->toArray();
  1116. $freight_map = array_column($freight,null,'region');
  1117. //组织数据
  1118. foreach ($dataArray as $key => $value) {
  1119. $quantity = abs($value['quantity']);
  1120. //箱数
  1121. $xs = 0;
  1122. if(! empty($value['product_box_size']) && is_numeric($value['product_box_size']) && $value['product_box_size'] > 0) $xs = ceil($quantity / $value['product_box_size']);
  1123. $dataArray[$key]['xs'] = $xs;
  1124. //总重量
  1125. $weight = 0;
  1126. if(! empty($value['product_weight']) && is_numeric($value['product_weight']) && $value['product_weight'] > 0) $weight = bcdiv(bcmul($xs, $value['product_weight']),1000,4);
  1127. $dataArray[$key]['weight'] = $weight;
  1128. //运价区间
  1129. $area_range = 1;
  1130. if($weight >= 5) $area_range = 2;
  1131. $dataArray[$key]['area_range'] = $area_range;
  1132. //配送费单价
  1133. $freight = $min_freight = 0;
  1134. if(isset($freight_map[$value['area_hs']])) {
  1135. $tmp = $freight_map[$value['area_hs']];
  1136. if($area_range == 1){
  1137. $freight = $tmp['one_and_five'];
  1138. }else{
  1139. $freight = $tmp['greater_than_five'];
  1140. }
  1141. $min_freight = $tmp['min_freight_fee'];
  1142. }
  1143. $dataArray[$key]['freight_unit_price'] = $freight;
  1144. //地区最低运价
  1145. $dataArray[$key]['min_freight_amount'] = $min_freight;
  1146. //纯自提不计算-------------------------------------------------------
  1147. if($value['delivery_mode'] == FreightFee::deliveryModeNormal){
  1148. //配送费金额
  1149. $dataArray[$key]['freight_amount'] = 0;
  1150. //结算金额 记录的是每一条的
  1151. $dataArray[$key]['js_single_amount'] = 0;
  1152. //门店卸货费
  1153. $dataArray[$key]['customer_store_zx_fee'] = 0;
  1154. //到货装卸费
  1155. $dataArray[$key]['dh_fee'] = 0;
  1156. }else{
  1157. //配送费金额
  1158. $freight_amount = bcmul($weight, $freight,4);
  1159. $dataArray[$key]['freight_amount'] = $freight_amount;
  1160. //结算金额 记录的是每一条的
  1161. $dataArray[$key]['js_single_amount'] = $freight_amount;
  1162. //门店卸货费
  1163. $customer_store_price = 0;
  1164. if(! empty($value['customer_store_price']) && is_numeric($value['customer_store_price']) && $value['customer_store_price'] > 0){
  1165. $customer_store_price = bcmul($value['customer_store_price'], $xs,4);
  1166. }else{
  1167. if(! empty($value['product_store_price']) && is_numeric($value['product_store_price']) && $value['product_store_price'] > 0){
  1168. $customer_store_price = bcmul($value['product_store_price'], $xs,4);
  1169. }
  1170. }
  1171. $dataArray[$key]['customer_store_zx_fee'] = $customer_store_price;
  1172. //到货装卸费
  1173. $product_store_price2 = 0;
  1174. if(! empty($value['product_store_price2']) && is_numeric($value['product_store_price2'])) $product_store_price2 = $value['product_store_price2'];
  1175. if(! empty($value['product_category']) && $value['product_category'] == "礼盒"){
  1176. $dh_fee = bcmul($xs, $product_store_price2,4);
  1177. }else{
  1178. $dh_fee = bcmul($weight, $product_store_price2,4);
  1179. }
  1180. if($value['business_type_id'] == FreightFee::businessTypeReturn) $dh_fee = bcmul($dh_fee,2,4);
  1181. $dataArray[$key]['dh_fee'] = $dh_fee;
  1182. }
  1183. }
  1184. DB::table($table)->insert($dataArray);
  1185. // 更新 lastId 继续下一批
  1186. $lastId = end($dataArray)['id_detail'] ?? $lastId;
  1187. } while (count($rows) === $limit);
  1188. }catch (\Throwable $exception){
  1189. return [false, "运费获取销货单数据异常" . $exception->getMessage() . "|" . $exception->getLine() . "|" . $exception->getFile()];
  1190. }
  1191. return [true, ''];
  1192. }
  1193. private function updateFreightFeeFromMine($data){
  1194. try {
  1195. $start_timeStamp = $data['start_timeStamp'];
  1196. $end_timeStamp = $data['end_timeStamp'];
  1197. $tmpTable = $this->table_3;
  1198. $time = time();
  1199. $ergs = $data;
  1200. DB::transaction(function () use ($start_timeStamp, $end_timeStamp, $tmpTable,$time, $ergs) {
  1201. // 1. 先软删除旧数据(你已有)
  1202. FreightFee::where('del_time', 0)
  1203. ->where('order_time', '>=', $start_timeStamp)
  1204. ->where('order_time', '<=', $end_timeStamp)
  1205. ->update(['del_time' => $time]);
  1206. // 2. 分批从临时表插入新数据
  1207. $batchSize = 500;
  1208. $lastId = 0;
  1209. do {
  1210. $chunk = DB::table($tmpTable)
  1211. ->where('id', '>', $lastId)
  1212. ->orderBy('id')
  1213. ->limit($batchSize)
  1214. ->get();
  1215. if ($chunk->isEmpty()) {
  1216. break;
  1217. }
  1218. $data = $chunk->map(function ($item) use($time){
  1219. return [
  1220. // 基础字段(按你给的顺序)
  1221. 'order_id' => $item->order_id ?? 0,
  1222. 'order_number' => $item->order_number ?? '',
  1223. 'order_time' => $item->order_time ? strtotime($item->order_time) : 0,
  1224. 'order_state' => $item->order_state ?? 0,
  1225. 'employee_id_1_title' => $item->employee_id_1_title ?? '',
  1226. 'employee_id_1' => $item->employee_id_1 ?? 0,
  1227. 'employee_id_2_title' => $item->employee_id_2_title ?? '',
  1228. 'employee_id_2' => $item->employee_id_2 ?? 0,
  1229. 'customer_code' => $item->customer_code ?? '',
  1230. 'customer_title' => $item->customer_title ?? '',
  1231. 'customer_store_price' => $item->customer_store_price ?? 0,
  1232. 'product_code' => $item->product_code ?? '',
  1233. 'product_title' => $item->product_title ?? '',
  1234. 'product_size' => $item->product_size ?? '',
  1235. 'product_box_size' => $item->product_box_size ?? 0,
  1236. 'product_weight' => $item->product_weight ?? 0,
  1237. 'product_store_price' => $item->product_store_price ?? 0,
  1238. 'product_store_price2' => $item->product_store_price2 ?? 0,
  1239. 'product_category' => $item->product_category ?? '',
  1240. 'unit' => $item->unit ?? '',
  1241. 'quantity' => $item->quantity ?? 0,
  1242. 'price_3' => $item->price_3 ?? 0,
  1243. 'price_3_total' => $item->price_3_total ?? 0,
  1244. 'id_detail' => $item->id_detail ?? 0,
  1245. 'is_present' => $item->is_present ?? '',
  1246. 'mark' => $item->mark ?? '',
  1247. 'item_mark' => $item->item_mark ?? '',
  1248. 'warehouse_id' => $item->warehouse_id ?? 0,
  1249. 'warehouse_name' => $item->warehouse_name ?? '',
  1250. 'business_type_id' => $item->business_type_id ?? 0,
  1251. 'business_type_title' => $item->business_type_title ?? '',
  1252. 'address' => $item->address ?? '',
  1253. 'area_hs' => $item->area_hs ?? '',
  1254. 'delivery_mode' => $item->delivery_mode ?? 0,
  1255. 'sl_fee' => $item->sl_fee ?? 0,
  1256. 'xs' => $item->xs,
  1257. 'weight' => $item->weight ?? 0,
  1258. 'area_range' => $item->area_range ?? 0,
  1259. 'freight_unit_price' => $item->freight_unit_price ?? 0,
  1260. 'freight_amount' => $item->freight_amount ?? 0,
  1261. 'js_single_amount' => $item->js_single_amount ?? 0,
  1262. 'min_freight_amount' => $item->min_freight_amount ?? 0,
  1263. 'customer_store_zx_fee' => $item->customer_store_zx_fee ?? 0,
  1264. 'dh_fee' => $item->dh_fee ?? 0,
  1265. 'crt_time' => $time,
  1266. ];
  1267. })->toArray();
  1268. // 每批单独插入(可选:加小事务)
  1269. FreightFee::insert($data);
  1270. // 更新 lastId
  1271. $lastId = $chunk->last()->id;
  1272. } while ($chunk->count() == $batchSize);
  1273. });
  1274. }catch (\Throwable $exception){
  1275. return [false, "单据明细同步异常" . $exception->getMessage() . "|" . $exception->getLine() . "|" . $exception->getFile()];
  1276. }
  1277. return [true, ''];
  1278. }
  1279. public function synItemRoad($data, $user){
  1280. if(empty($data['crt_time'][0]) || empty($data['crt_time'][1])) return [false, '同步时间不能为空'];
  1281. $start_time = $data['crt_time'][0] / 1000;
  1282. $end_time = $data['crt_time'][1] / 1000;
  1283. list($bool, $bool_msg) = $this->isWithinMonths($start_time, $end_time);
  1284. if(! $bool) return [false, $bool_msg];
  1285. $data['start_timeStamp'] = $start_time;
  1286. $data['end_timeStamp'] = $end_time;
  1287. $start = date('Y-m-d H:i:s.000', $start_time);
  1288. $end = date('Y-m-d H:i:s.000', $end_time);
  1289. $data['start_time'] = $start;
  1290. $data['end_time'] = $end;
  1291. $data['operation_time'] = time();
  1292. $data['type'] = 7;
  1293. // list($status, $msg) = $this->synItemRoadMy($data, $user);dd($status, $msg);
  1294. list($status,$msg) = $this->limitingSendRequest($this->table_4);
  1295. if(! $status) return [false, '统计同步正在后台运行,请稍后'];
  1296. //队列
  1297. ProcessDataJob::dispatch($data, $user, 4)->onQueue(RevenueCost::job4);
  1298. return [true, '统计同步已进入后台任务'];
  1299. }
  1300. private function createTmpTable4(){
  1301. $table = $this->table_4;
  1302. if (! Schema::hasTable($table)) {
  1303. Schema::create($table, function (Blueprint $table) {
  1304. $table->bigIncrements('id');
  1305. // 订单基础信息
  1306. $table->bigInteger('order_id')->default(0)->comment('收款单ID(rp.ID)');
  1307. $table->string('order_number')->default('')->comment('收款单编号(rp.code)');
  1308. $table->integer('order_time')->default(0)->comment('单据时间(时间戳)');
  1309. $table->integer('order_state')->default(0)->comment('订单状态');
  1310. $table->integer('order_type')->default(0)->comment('订单分类标识');
  1311. // 渠道/分销相关
  1312. $table->string('channel_finance')->default('')->comment('渠道财务(rp.pubuserdefnvc11)');
  1313. $table->string('channel_details')->default('')->comment('渠道明细(rp.pubuserdefnvc12)');
  1314. $table->string('channel_details_fp')->default('')->comment('发票渠道明细(si.pubuserdefnvc12)');
  1315. // 客户信息
  1316. $table->string('customer_code')->default('')->comment('结算客户编码');
  1317. $table->string('customer_title')->default('')->comment('结算客户名称');
  1318. // 人员信息
  1319. $table->bigInteger('employee_id_1')->default(0)->comment('业务员ID');
  1320. $table->string('employee_id_1_title')->default('')->comment('业务员名称');
  1321. $table->bigInteger('employee_id_2')->default(0)->comment('上级管理人员ID');
  1322. $table->string('employee_id_2_title')->default('')->comment('上级管理人员名称');
  1323. // 产品信息 (仅限 idvouchertype = 20)
  1324. $table->string('product_code')->default('')->comment('产品编码');
  1325. $table->string('product_title')->default('')->comment('产品名称');
  1326. $table->decimal('quantity', 14, 3)->default(0)->comment('发票数量');
  1327. // 收入/价格相关
  1328. $table->decimal('price_1', 14, 4)->default(0)->comment('含税单价(taxPrice)');
  1329. $table->decimal('price_1_total', 14, 2)->default(0)->comment('含税金额(taxAmount)');
  1330. $table->decimal('payment_amount', 14, 2)->default(0)->comment('明细行的收款金额');
  1331. // 成本相关 (计算得出)
  1332. $table->decimal('price_4', 14, 4)->default(0)->comment('业务成本单价');
  1333. $table->decimal('price_4_total', 14, 2)->default(0)->comment('业务成本总额');
  1334. // 关联追溯字段
  1335. $table->bigInteger('id_detail')->default(0)->comment('收款明细ID(rp_b.ID)');
  1336. $table->bigInteger('id_detail_upstream')->default(0)->comment('上游单据明细ID(voucherDetailID)');
  1337. $table->string('order_number_upstream')->default('')->comment('上游单据编号(voucherCode)');
  1338. $table->integer('voucher_type')->default(0)->comment('单据类型(idvouchertype)');
  1339. $table->string('is_kh')->default('0')->comment('是否计入考核(sd.priuserdefnvc4)');
  1340. });
  1341. }
  1342. }
  1343. private function createTmpTable5(){
  1344. $table = $this->table_5;
  1345. if (! Schema::hasTable($table)) {
  1346. Schema::create($table, function (Blueprint $table) {
  1347. $table->bigIncrements('id');
  1348. // 基础信息
  1349. $table->bigInteger('order_id')->default(0)->comment('费用单ID(cs.ID)');
  1350. $table->string('order_number')->default('')->comment('费用单编号(cs.code)');
  1351. $table->integer('order_time')->default(0)->comment('单据时间(时间戳)');
  1352. $table->integer('order_type')->default(0)->comment('订单分类标识(1 费用单 2 其他出库单)');
  1353. $table->string('ck_type')->default("")->comment('出库单出库类别');
  1354. $table->integer('employee_id_1')->default(0)->comment('业务员id');
  1355. $table->string('employee_id_1_title')->default('')->comment('业务员名称');
  1356. // 维度信息
  1357. $table->string('channel_finance')->default('')->comment('渠道财务(cs.pubuserdefnvc11)');
  1358. $table->string('channel_details')->default('')->comment('渠道明细(cs.pubuserdefnvc12)');
  1359. $table->string('fy_code')->default('')->comment('费用项目编码(ae.code)');
  1360. // 金额信息
  1361. $table->decimal('taxamount', 14, 2)->default(0)->comment('含税金额(cs_b.taxamount)');
  1362. // 追溯信息
  1363. $table->bigInteger('id_detail')->default(0)->comment('费用明细行ID(cs_b.ID)');
  1364. });
  1365. }
  1366. }
  1367. public function synItemRoadMy($data, $user){
  1368. //收入
  1369. list($status, $msg) = $this->synReceipt($data,$user);
  1370. if(! $status) return [false, $msg];
  1371. //成本
  1372. list($status, $msg) = $this->synSaleCost($data,$user);
  1373. if(! $status) return [false, $msg];
  1374. //汇总项目报表
  1375. list($status, $msg) = $this->saveResult($data,$user);
  1376. if(! $status) return [false, $msg];
  1377. //清理临时表 如果内容不为空
  1378. $this->clearTmpTable(4);
  1379. //释放redis
  1380. $this->delTableKey(4);
  1381. return [true, ''];
  1382. }
  1383. private function synReceipt($data, $user){
  1384. //创建临时表 如果不存在
  1385. $this->createTmpTable4();
  1386. //清理临时表 如果内容不为空
  1387. $this->clearTmpTable(4);
  1388. try{
  1389. $table = $this->table_4;
  1390. $limit = 500;
  1391. $lastId = 0;
  1392. do {
  1393. $rows = $this->databaseService->table('ARAP_ReceivePayment_b as rp_b')
  1394. ->join('ARAP_ReceivePayment as rp', 'rp_b.idArapReceivePaymentDTO', '=', 'rp.ID')
  1395. // 发票子表关联(仅限 idvouchertype = 20)
  1396. ->leftJoin('SA_SaleInvoice_b as si_b', function ($join) {
  1397. $join->on('rp_b.voucherDetailID', '=', 'si_b.ID')
  1398. ->where('rp_b.idvouchertype', '=', 20);
  1399. })
  1400. ->leftJoin('SA_SaleInvoice as si', function ($join) {
  1401. $join->on('si_b.idSaleInvoiceDTO', '=', 'si.ID')
  1402. ->where('rp_b.idvouchertype', '=', 20);
  1403. })
  1404. ->leftJoin('SA_SaleDelivery_b as sd_b', function ($join) {
  1405. $join->on('si_b.sourceVoucherDetailId', '=', 'sd_b.ID')
  1406. ->where('rp_b.idvouchertype', '=', 20);
  1407. })
  1408. ->leftJoin('SA_SaleDelivery as sd', function ($join) {
  1409. $join->on('sd_b.idSaleDeliveryDTO', '=', 'sd.ID')
  1410. ->where('rp_b.idvouchertype', '=', 20);
  1411. })
  1412. ->leftJoin('AA_Inventory as it', 'sd_b.idinventory', '=', 'it.ID')
  1413. ->leftJoin('AA_Partner as pn', 'si.idsettlecustomer', '=', 'pn.ID') //结算客户
  1414. ->leftJoin('AA_Person as ps', 'rp.idperson', '=', 'ps.ID')
  1415. ->leftJoin('AA_Person as ps2', 'pn.idsaleman', '=', 'ps2.ID') // 结算客户的上级管理人员
  1416. ->where('rp.voucherdate','>=',$data['start_time'])
  1417. ->where('rp.voucherdate','<=',$data['end_time'])
  1418. // ->where('priuserdefnvc4','=', 1) //.. 不计入考核 todo
  1419. ->where('rp.isReceiveFlag','=', 1)
  1420. ->where('rp_b.ID', '>', $lastId)
  1421. ->orderBy('rp_b.ID')
  1422. ->limit($limit)
  1423. ->selectRaw("
  1424. COALESCE(rp.ID, 0) as order_id,
  1425. COALESCE(rp.code, '') as order_number,
  1426. rp.voucherdate as order_time,
  1427. rp.voucherstate as order_state,
  1428. COALESCE(rp.pubuserdefnvc11, '') as channel_finance,
  1429. COALESCE(rp.pubuserdefnvc12, '') as channel_details,
  1430. COALESCE(si.pubuserdefnvc12, '') as channel_details_fp,
  1431. COALESCE(pn.code, '') as customer_code,
  1432. COALESCE(pn.name, '') as customer_title,
  1433. CASE WHEN rp_b.idvouchertype = 20 THEN COALESCE(it.code, '') ELSE '' END as product_code,
  1434. CASE WHEN rp_b.idvouchertype = 20 THEN COALESCE(it.name, '') ELSE '' END as product_title,
  1435. COALESCE(rp.idperson, 0) as employee_id_1,
  1436. COALESCE(ps.name, '') as employee_id_1_title,
  1437. COALESCE(pn.idsaleman, 0) as employee_id_2,
  1438. COALESCE(ps2.name, '') as employee_id_2_title,
  1439. CASE WHEN rp_b.idvouchertype = 20 THEN COALESCE(si_b.quantity, 0) ELSE 0 END as quantity,
  1440. CASE WHEN rp_b.idvouchertype = 20 THEN COALESCE(si_b.taxPrice, 0) ELSE 0 END as price_1,
  1441. CASE WHEN rp_b.idvouchertype = 20 THEN COALESCE(si_b.taxAmount, 0) ELSE 0 END as price_1_total,
  1442. COALESCE(rp_b.origCurrentAmount, 0) as payment_amount,
  1443. COALESCE(rp_b.ID, 0) as id_detail,
  1444. COALESCE(rp_b.voucherDetailID, 0) as id_detail_upstream,
  1445. COALESCE(rp_b.voucherCode, '') as order_number_upstream,
  1446. rp_b.idvouchertype as voucher_type,
  1447. CASE WHEN rp_b.idvouchertype = 20 THEN COALESCE(sd.priuserdefnvc4, '') ELSE '' END as is_kh
  1448. ")
  1449. ->get();
  1450. if ($rows->isEmpty()) break;
  1451. $dataArray = Collect($rows)->map(function ($object) {
  1452. return (array)$object;
  1453. })->toArray();
  1454. //存货档案业务成本
  1455. $product_map = Product::where('del_time',0)
  1456. ->whereIn('code', array_unique(array_column($dataArray,'product_code')))
  1457. ->pluck('business_cost','code')
  1458. ->all();
  1459. //组织数据
  1460. foreach ($dataArray as $key => $value){
  1461. $p_tmp = $product_map[$value['product_code']] ?? 0;
  1462. $dataArray[$key]['order_type'] = RevenueCost::ORDER_THREE;
  1463. $dataArray[$key]['order_time'] = strtotime($value['order_time']);
  1464. //业务成本单价和金额
  1465. $business_cost = $p_tmp ?? 0;
  1466. $dataArray[$key]['price_4'] = $business_cost;
  1467. $price_4_total = bcmul($business_cost, $value['quantity'],2);
  1468. $dataArray[$key]['price_4_total'] = $price_4_total;
  1469. }
  1470. DB::table($table)->insert($dataArray);
  1471. // 更新 lastId 继续下一批
  1472. $lastId = end($dataArray)['id_detail'] ?? $lastId;
  1473. } while (count($rows) === $limit);
  1474. }catch (\Throwable $exception){
  1475. return [false, "收入同步异常" . $exception->getMessage() . "|" . $exception->getLine() . "|" . $exception->getFile()];
  1476. }
  1477. return [true, ''];
  1478. }
  1479. private function synSaleCost($data, $user){
  1480. //创建临时表 如果不存在
  1481. $this->createTmpTable5();
  1482. //清理临时表 如果内容不为空
  1483. // $this->clearTmpTable(5);
  1484. try{
  1485. $table = $this->table_5;
  1486. $limit = 500;
  1487. $lastId = 0;
  1488. do {
  1489. $rows = $this->databaseService->table('CS_ExpenseVoucher_b as cs_b')
  1490. ->join('CS_ExpenseVoucher as cs', 'cs_b.idExpenseVoucherDTO', '=', 'cs.ID')
  1491. ->leftJoin('AA_ExpenseItem as ae', 'ae.id', '=', 'cs_b.idexpenseitem')
  1492. ->leftJoin('AA_Person as ps', 'cs.idclerk', '=', 'ps.ID')
  1493. ->where('cs.voucherdate','>=',$data['start_time'])
  1494. ->where('cs.voucherdate','<=',$data['end_time'])
  1495. ->where('cs_b.ID', '>', $lastId)
  1496. ->orderBy('cs_b.ID')
  1497. ->limit($limit)
  1498. ->selectRaw("
  1499. 1 as order_type,
  1500. COALESCE(cs.ID, 0) as order_id,
  1501. COALESCE(cs.code, '') as order_number,
  1502. cs.voucherdate as order_time,
  1503. cs.idclerk as employee_id_1,
  1504. COALESCE(ps.name, '') as employee_id_1_title,
  1505. COALESCE(cs.pubuserdefnvc12, '') as channel_details,
  1506. COALESCE(cs.pubuserdefnvc11, '') as channel_finance,
  1507. COALESCE(ae.code, '') as fy_code,
  1508. COALESCE(cs_b.taxamount, 0) as taxamount,
  1509. COALESCE(cs_b.ID, 0) as id_detail
  1510. ")
  1511. ->get();
  1512. if ($rows->isEmpty()) break;
  1513. $dataArray = Collect($rows)->map(function ($object) {
  1514. return (array)$object;
  1515. })->toArray();
  1516. foreach ($dataArray as $key => $value){
  1517. $dataArray[$key]['order_time'] = strtotime($value['order_time']);
  1518. }
  1519. DB::table($table)->insert($dataArray);
  1520. // 更新 lastId 继续下一批
  1521. $lastId = end($dataArray)['id_detail'] ?? $lastId;
  1522. } while (count($rows) === $limit);
  1523. }catch (\Throwable $exception){
  1524. return [false, "费用同步异常" . $exception->getMessage() . "|" . $exception->getLine() . "|" . $exception->getFile()];
  1525. }
  1526. try{
  1527. $table = $this->table_5;
  1528. $limit = 500;
  1529. $lastId = 0;
  1530. do {
  1531. $rows = $this->databaseService->table('ST_RDRecord_b as st_b')
  1532. ->join('ST_RDRecord as st', 'st_b.idRDRecordDTO', '=', 'st.ID')
  1533. ->leftJoin('AA_Person as ps', 'st.idclerk', '=', 'ps.ID')
  1534. ->where('st.voucherdate','>=',$data['start_time'])
  1535. ->where('st.voucherdate','<=',$data['end_time'])
  1536. ->where('st.idvouchertype', 30)
  1537. // ->whereIn('st.idbusitype',[20048,60,20049]) //20049 客情出库 60 赠品出库 20048 员工福利
  1538. ->where('st_b.ID', '>', $lastId)
  1539. ->orderBy('st_b.ID')
  1540. ->limit($limit)
  1541. ->selectRaw("
  1542. 2 as order_type,
  1543. COALESCE(st.ID, 0) as order_id,
  1544. COALESCE(st.code, '') as order_number,
  1545. st.voucherdate as order_time,
  1546. st.idclerk as employee_id_1,
  1547. COALESCE(ps.name, '') as employee_id_1_title,
  1548. COALESCE(st.pubuserdefnvc12, '') as channel_details,
  1549. COALESCE(st.pubuserdefnvc11, '') as channel_finance,
  1550. COALESCE(st_b.amount, 0) as taxamount,
  1551. COALESCE(st_b.ID, 0) as id_detail,
  1552. st.idbusitype as ck_type
  1553. ")->get();
  1554. if ($rows->isEmpty()) break;
  1555. $dataArray = Collect($rows)->map(function ($object) {
  1556. return (array)$object;
  1557. })->toArray();
  1558. foreach ($dataArray as $key => $value){
  1559. $dataArray[$key]['order_time'] = strtotime($value['order_time']);
  1560. }
  1561. DB::table($table)->insert($dataArray);
  1562. // 更新 lastId 继续下一批
  1563. $lastId = end($dataArray)['id_detail'] ?? $lastId;
  1564. } while (count($rows) === $limit);
  1565. }catch (\Throwable $exception){
  1566. return [false, "其他出库同步异常" . $exception->getMessage() . "|" . $exception->getLine() . "|" . $exception->getFile()];
  1567. }
  1568. return [true, ''];
  1569. }
  1570. private function saveResultold($data, $user){
  1571. // 初始化汇总数组------报表一
  1572. $paymentSummary = [];
  1573. $costSummary = [];
  1574. $costSummary2 = [];
  1575. //报表二
  1576. $paymentSummary_road = [];
  1577. $costSummary_road = [];
  1578. $costSummary2_road = [];
  1579. $map = [
  1580. 2 => [
  1581. 'type' => 1,
  1582. 'channel_details' => ['通路'],
  1583. ],
  1584. 3 => [
  1585. 'type' => 2,
  1586. 'channel_details' => ['通路'],
  1587. ],
  1588. 23 => [
  1589. 'type' => 3,
  1590. 'channel_details' => ['通路'],
  1591. ],
  1592. 7 => [
  1593. 'type' => 4,
  1594. 'channel_details' => ['通路','大卖场'],
  1595. ],
  1596. 8 => [
  1597. 'type' => 4,
  1598. 'channel_details' => ['通路','大卖场'],
  1599. ],
  1600. 48 => [
  1601. 'type' => 4,
  1602. 'channel_details' => ['通路','大卖场'],
  1603. ],
  1604. ];
  1605. try{
  1606. $limit = 500;
  1607. $lastId = 0;
  1608. do {
  1609. // 分批查询:只查 is_kh 不为空的数据
  1610. $rows = DB::table('tmp_item_road')
  1611. ->where('id', '>', $lastId)
  1612. ->orderBy('id')
  1613. ->limit($limit)
  1614. ->select([
  1615. 'id',
  1616. 'order_time',
  1617. 'channel_details',
  1618. 'payment_amount',
  1619. 'price_4_total',
  1620. 'is_kh',
  1621. 'employee_id_2'
  1622. ])
  1623. ->get();
  1624. if ($rows->isEmpty()) {
  1625. break;
  1626. }
  1627. // 聚合到汇总数组
  1628. foreach ($rows as $row) {
  1629. $order_time = $row->order_time;
  1630. $month = strtotime(date("Y-m-01", $order_time));
  1631. $channel = $row->channel_details ?? '';
  1632. $t = $map[$row->employee_id_2] ?? [];
  1633. //收款销售收入
  1634. if (! $row->is_kh) {
  1635. if (!isset($paymentSummary[$month][$channel])) {
  1636. $paymentSummary[$month][$channel] = $row->payment_amount;
  1637. }else{
  1638. $paymentSummary[$month][$channel] = bcadd(
  1639. $paymentSummary[$month][$channel],
  1640. $row->payment_amount,
  1641. 3
  1642. );
  1643. }
  1644. if(! empty($t)){
  1645. $type = $t['type'];
  1646. $c_t = $t['channel_details'];
  1647. if(in_array($channel, $c_t)){
  1648. if (!isset($paymentSummary_road[$month][$type])) {
  1649. $paymentSummary_road[$month][$type] = $row->payment_amount;
  1650. }else{
  1651. $paymentSummary_road[$month][$type] = bcadd(
  1652. $paymentSummary_road[$month][$type],
  1653. $row->payment_amount,
  1654. 3
  1655. );
  1656. }
  1657. }
  1658. }
  1659. }
  1660. //成本
  1661. if (!isset($costSummary[$month][$channel])) {
  1662. $costSummary[$month][$channel] = $row->price_4_total;
  1663. }else{
  1664. $costSummary[$month][$channel] = bcadd(
  1665. $costSummary[$month][$channel],
  1666. $row->price_4_total,
  1667. 3
  1668. );
  1669. }
  1670. if(! empty($t)){
  1671. $type = $t['type'];
  1672. $c_t = $t['channel_details'];
  1673. if(in_array($channel, $c_t)){
  1674. if (!isset($costSummary_road[$month][$type])) {
  1675. $costSummary_road[$month][$type] = $row->price_4_total;
  1676. }else{
  1677. $costSummary_road[$month][$type] = bcadd(
  1678. $costSummary_road[$month][$type],
  1679. $row->price_4_total,
  1680. 3
  1681. );
  1682. }
  1683. }
  1684. }
  1685. }
  1686. // 更新 lastId
  1687. $lastId = $rows->last()->id;
  1688. } while ($rows->count() === $limit);
  1689. $limit = 500;
  1690. $lastId = 0;
  1691. do {
  1692. $rows = DB::table('tmp_item_cost')
  1693. ->where('id', '>', $lastId)
  1694. ->orderBy('id')
  1695. ->limit($limit)
  1696. ->select([
  1697. 'id',
  1698. 'order_time',
  1699. 'channel_details',
  1700. 'ck_type',
  1701. 'fy_code',
  1702. 'taxamount',
  1703. 'employee_id_1'
  1704. ])
  1705. ->get();
  1706. if ($rows->isEmpty()) {
  1707. break;
  1708. }
  1709. foreach ($rows as $row) {
  1710. $order_time = $row->order_time;
  1711. $month = strtotime(date("Y-m-01", $order_time));
  1712. $channel = $row->channel_details ?? '';
  1713. $amount = $row->taxamount;
  1714. $t = $map[$row->employee_id_1] ?? [];
  1715. if($row->fy_code == 7004){
  1716. if (! isset($costSummary2[$month][$channel]['settle_amount'])) {
  1717. $costSummary2[$month][$channel]['settle_amount'] = $amount;
  1718. }else{
  1719. $costSummary2[$month][$channel]['settle_amount'] = bcadd(
  1720. $costSummary2[$month][$channel]['settle_amount'],
  1721. $amount,
  1722. 3
  1723. );
  1724. }
  1725. if(! empty($t)){
  1726. $type = $t['type'];
  1727. $c_t = $t['channel_details'];
  1728. if(in_array($channel, $c_t)){
  1729. if (!isset($costSummary2_road[$month][$type])) {
  1730. $costSummary2_road[$month][$type]['settle_amount'] = $amount;
  1731. }else{
  1732. $costSummary2_road[$month][$type]['settle_amount'] = bcadd(
  1733. $costSummary2_road[$month][$type]['settle_amount'],
  1734. $amount,
  1735. 3
  1736. );
  1737. }
  1738. }
  1739. }
  1740. }
  1741. $gl_amount = bcmul($amount, 0.05,3);
  1742. if (! isset($costSummary2[$month][$channel]['gl_amount'])) {
  1743. $costSummary2[$month][$channel]['gl_amount'] = $gl_amount;
  1744. }else{
  1745. $costSummary2[$month][$channel]['gl_amount'] = bcadd(
  1746. $costSummary2[$month][$channel]['gl_amount'],
  1747. $gl_amount,
  1748. 3
  1749. );
  1750. }
  1751. if(! empty($t)){
  1752. $type = $t['type'];
  1753. $c_t = $t['channel_details'];
  1754. if(in_array($channel, $c_t)){
  1755. if (!isset($costSummary2_road[$month][$type]['gl_amount'])) {
  1756. $costSummary2_road[$month][$type]['gl_amount'] = $amount;
  1757. }else{
  1758. $costSummary2_road[$month][$type]['gl_amount'] = bcadd(
  1759. $costSummary2_road[$month][$type]['gl_amount'],
  1760. $amount,
  1761. 3
  1762. );
  1763. }
  1764. }
  1765. }
  1766. $wl_amount = bcmul($amount, 2.3,3);
  1767. if (! isset($costSummary2[$month][$channel]['wl_amount'])) {
  1768. $costSummary2[$month][$channel]['wl_amount'] = $wl_amount;
  1769. }else{
  1770. $costSummary2[$month][$channel]['wl_amount'] = bcadd(
  1771. $costSummary2[$month][$channel]['wl_amount'],
  1772. $wl_amount,
  1773. 3
  1774. );
  1775. }
  1776. if(! empty($t)){
  1777. $type = $t['type'];
  1778. $c_t = $t['channel_details'];
  1779. if(in_array($channel, $c_t)){
  1780. if (!isset($costSummary2_road[$month][$type]['wl_amount'])) {
  1781. $costSummary2_road[$month][$type]['wl_amount'] = $amount;
  1782. }else{
  1783. $costSummary2_road[$month][$type]['wl_amount'] = bcadd(
  1784. $costSummary2_road[$month][$type]['wl_amount'],
  1785. $amount,
  1786. 3
  1787. );
  1788. }
  1789. }
  1790. }
  1791. if($row->fy_code == 7005){
  1792. if (! isset($costSummary2[$month][$channel]['ht_amount'])) {
  1793. $costSummary2[$month][$channel]['ht_amount'] = $amount;
  1794. }else{
  1795. $costSummary2[$month][$channel]['ht_amount'] = bcadd(
  1796. $costSummary2[$month][$channel]['ht_amount'],
  1797. $amount,
  1798. 3
  1799. );
  1800. }
  1801. if(! empty($t)){
  1802. $type = $t['type'];
  1803. $c_t = $t['channel_details'];
  1804. if(in_array($channel, $c_t)){
  1805. if (!isset($costSummary2_road[$month][$type]['ht_amount'])) {
  1806. $costSummary2_road[$month][$type]['ht_amount'] = $amount;
  1807. }else{
  1808. $costSummary2_road[$month][$type]['ht_amount'] = bcadd(
  1809. $costSummary2_road[$month][$type]['ht_amount'],
  1810. $amount,
  1811. 3
  1812. );
  1813. }
  1814. }
  1815. }
  1816. }
  1817. if($row->fy_code == 7006){
  1818. if (! isset($costSummary2[$month][$channel]['zk_amount'])) {
  1819. $costSummary2[$month][$channel]['zk_amount'] = $amount;
  1820. }else{
  1821. $costSummary2[$month][$channel]['zk_amount'] = bcadd(
  1822. $costSummary2[$month][$channel]['zk_amount'],
  1823. $amount,
  1824. 3
  1825. );
  1826. }
  1827. if(! empty($t)){
  1828. $type = $t['type'];
  1829. $c_t = $t['channel_details'];
  1830. if(in_array($channel, $c_t)){
  1831. if (!isset($costSummary2_road[$month][$type]['zk_amount'])) {
  1832. $costSummary2_road[$month][$type]['zk_amount'] = $amount;
  1833. }else{
  1834. $costSummary2_road[$month][$type]['zk_amount'] = bcadd(
  1835. $costSummary2_road[$month][$type]['zk_amount'],
  1836. $amount,
  1837. 3
  1838. );
  1839. }
  1840. }
  1841. }
  1842. }
  1843. if($row->fy_code == 7007){
  1844. if (! isset($costSummary2[$month][$channel]['cx_amount'])) {
  1845. $costSummary2[$month][$channel]['cx_amount'] = $amount;
  1846. }else{
  1847. $costSummary2[$month][$channel]['cx_amount'] = bcadd(
  1848. $costSummary2[$month][$channel]['cx_amount'],
  1849. $amount,
  1850. 3
  1851. );
  1852. }
  1853. if(! empty($t)){
  1854. $type = $t['type'];
  1855. $c_t = $t['channel_details'];
  1856. if(in_array($channel, $c_t)){
  1857. if (!isset($costSummary2_road[$month][$type]['cx_amount'])) {
  1858. $costSummary2_road[$month][$type]['cx_amount'] = $amount;
  1859. }else{
  1860. $costSummary2_road[$month][$type]['cx_amount'] = bcadd(
  1861. $costSummary2_road[$month][$type]['cx_amount'],
  1862. $amount,
  1863. 3
  1864. );
  1865. }
  1866. }
  1867. }
  1868. }
  1869. if($row->fy_code == 7013){
  1870. if (! isset($costSummary2[$month][$channel]['tg_amount'])) {
  1871. $costSummary2[$month][$channel]['tg_amount'] = $amount;
  1872. }else{
  1873. $costSummary2[$month][$channel]['tg_amount'] = bcadd(
  1874. $costSummary2[$month][$channel]['tg_amount'],
  1875. $amount,
  1876. 3
  1877. );
  1878. }
  1879. if(! empty($t)){
  1880. $type = $t['type'];
  1881. $c_t = $t['channel_details'];
  1882. if(in_array($channel, $c_t)){
  1883. if (!isset($costSummary2_road[$month][$type]['tg_amount'])) {
  1884. $costSummary2_road[$month][$type]['tg_amount'] = $amount;
  1885. }else{
  1886. $costSummary2_road[$month][$type]['tg_amount'] = bcadd(
  1887. $costSummary2_road[$month][$type]['tg_amount'],
  1888. $amount,
  1889. 3
  1890. );
  1891. }
  1892. }
  1893. }
  1894. }
  1895. if($row->fy_code == 7012){
  1896. if (! isset($costSummary2[$month][$channel]['cl_amount'])) {
  1897. $costSummary2[$month][$channel]['cl_amount'] = $amount;
  1898. }else{
  1899. $costSummary2[$month][$channel]['cl_amount'] = bcadd(
  1900. $costSummary2[$month][$channel]['cl_amount'],
  1901. $amount,
  1902. 3
  1903. );
  1904. }
  1905. if(! empty($t)){
  1906. $type = $t['type'];
  1907. $c_t = $t['channel_details'];
  1908. if(in_array($channel, $c_t)){
  1909. if (!isset($costSummary2_road[$month][$type]['cl_amount'])) {
  1910. $costSummary2_road[$month][$type]['cl_amount'] = $amount;
  1911. }else{
  1912. $costSummary2_road[$month][$type]['cl_amount'] = bcadd(
  1913. $costSummary2_road[$month][$type]['cl_amount'],
  1914. $amount,
  1915. 3
  1916. );
  1917. }
  1918. }
  1919. }
  1920. }
  1921. //20049 客情出库 60 赠品出库 20048 员工福利
  1922. if($row->fy_code == 7008 || $row->ck_type == 20049){
  1923. if (! isset($costSummary2[$month][$channel]['kq_amount'])) {
  1924. $costSummary2[$month][$channel]['kq_amount'] = $amount;
  1925. }else{
  1926. $costSummary2[$month][$channel]['kq_amount'] = bcadd(
  1927. $costSummary2[$month][$channel]['kq_amount'],
  1928. $amount,
  1929. 3
  1930. );
  1931. }
  1932. if(! empty($t)){
  1933. $type = $t['type'];
  1934. $c_t = $t['channel_details'];
  1935. if(in_array($channel, $c_t)){
  1936. if (!isset($costSummary2_road[$month][$type]['kq_amount'])) {
  1937. $costSummary2_road[$month][$type]['kq_amount'] = $amount;
  1938. }else{
  1939. $costSummary2_road[$month][$type]['kq_amount'] = bcadd(
  1940. $costSummary2_road[$month][$type]['kq_amount'],
  1941. $amount,
  1942. 3
  1943. );
  1944. }
  1945. }
  1946. }
  1947. }
  1948. if($row->fy_code == 7009 || $row->ck_type == 60){
  1949. if (! isset($costSummary2[$month][$channel]['zp_amount'])) {
  1950. $costSummary2[$month][$channel]['zp_amount'] = $amount;
  1951. }else{
  1952. $costSummary2[$month][$channel]['zp_amount'] = bcadd(
  1953. $costSummary2[$month][$channel]['zp_amount'],
  1954. $amount,
  1955. 3
  1956. );
  1957. }
  1958. if(! empty($t)){
  1959. $type = $t['type'];
  1960. $c_t = $t['channel_details'];
  1961. if(in_array($channel, $c_t)){
  1962. if (!isset($costSummary2_road[$month][$type]['zp_amount'])) {
  1963. $costSummary2_road[$month][$type]['zp_amount'] = $amount;
  1964. }else{
  1965. $costSummary2_road[$month][$type]['zp_amount'] = bcadd(
  1966. $costSummary2_road[$month][$type]['zp_amount'],
  1967. $amount,
  1968. 3
  1969. );
  1970. }
  1971. }
  1972. }
  1973. }
  1974. if($row->fy_code == 7010){
  1975. if (! isset($costSummary2[$month][$channel]['gg_amount'])) {
  1976. $costSummary2[$month][$channel]['gg_amount'] = $amount;
  1977. }else{
  1978. $costSummary2[$month][$channel]['gg_amount'] = bcadd(
  1979. $costSummary2[$month][$channel]['gg_amount'],
  1980. $amount,
  1981. 3
  1982. );
  1983. }
  1984. if(! empty($t)){
  1985. $type = $t['type'];
  1986. $c_t = $t['channel_details'];
  1987. if(in_array($channel, $c_t)){
  1988. if (!isset($costSummary2_road[$month][$type]['gg_amount'])) {
  1989. $costSummary2_road[$month][$type]['gg_amount'] = $amount;
  1990. }else{
  1991. $costSummary2_road[$month][$type]['gg_amount'] = bcadd(
  1992. $costSummary2_road[$month][$type]['gg_amount'],
  1993. $amount,
  1994. 3
  1995. );
  1996. }
  1997. }
  1998. }
  1999. }
  2000. if($row->fy_code == 7011){
  2001. if (! isset($costSummary2[$month][$channel]['kd_amount'])) {
  2002. $costSummary2[$month][$channel]['kd_amount'] = $amount;
  2003. }else{
  2004. $costSummary2[$month][$channel]['kd_amount'] = bcadd(
  2005. $costSummary2[$month][$channel]['kd_amount'],
  2006. $amount,
  2007. 3
  2008. );
  2009. }
  2010. if(! empty($t)){
  2011. $type = $t['type'];
  2012. $c_t = $t['channel_details'];
  2013. if(in_array($channel, $c_t)){
  2014. if (!isset($costSummary2_road[$month][$type]['kd_amount'])) {
  2015. $costSummary2_road[$month][$type]['kd_amount'] = $amount;
  2016. }else{
  2017. $costSummary2_road[$month][$type]['kd_amount'] = bcadd(
  2018. $costSummary2_road[$month][$type]['kd_amount'],
  2019. $amount,
  2020. 3
  2021. );
  2022. }
  2023. }
  2024. }
  2025. }
  2026. if($row->fy_code == 7001){
  2027. if (! isset($costSummary2[$month][$channel]['xsqt_amount'])) {
  2028. $costSummary2[$month][$channel]['xsqt_amount'] = $amount;
  2029. }else{
  2030. $costSummary2[$month][$channel]['xsqt_amount'] = bcadd(
  2031. $costSummary2[$month][$channel]['xsqt_amount'],
  2032. $amount,
  2033. 3
  2034. );
  2035. }
  2036. if(! empty($t)){
  2037. $type = $t['type'];
  2038. $c_t = $t['channel_details'];
  2039. if(in_array($channel, $c_t)){
  2040. if (!isset($costSummary2_road[$month][$type]['xsqt_amount'])) {
  2041. $costSummary2_road[$month][$type]['xsqt_amount'] = $amount;
  2042. }else{
  2043. $costSummary2_road[$month][$type]['xsqt_amount'] = bcadd(
  2044. $costSummary2_road[$month][$type]['xsqt_amount'],
  2045. $amount,
  2046. 3
  2047. );
  2048. }
  2049. }
  2050. }
  2051. }
  2052. if($row->fy_code == 7003){
  2053. if (! isset($costSummary2[$month][$channel]['ry_amount'])) {
  2054. $costSummary2[$month][$channel]['ry_amount'] = $amount;
  2055. }else{
  2056. $costSummary2[$month][$channel]['ry_amount'] = bcadd(
  2057. $costSummary2[$month][$channel]['ry_amount'],
  2058. $amount,
  2059. 3
  2060. );
  2061. }
  2062. if(! empty($t)){
  2063. $type = $t['type'];
  2064. $c_t = $t['channel_details'];
  2065. if(in_array($channel, $c_t)){
  2066. if (!isset($costSummary2_road[$month][$type]['ry_amount'])) {
  2067. $costSummary2_road[$month][$type]['ry_amount'] = $amount;
  2068. }else{
  2069. $costSummary2_road[$month][$type]['ry_amount'] = bcadd(
  2070. $costSummary2_road[$month][$type]['ry_amount'],
  2071. $amount,
  2072. 3
  2073. );
  2074. }
  2075. }
  2076. }
  2077. }
  2078. if($row->fy_code == 7019 || $row->ck_type == 20048){
  2079. if (! isset($costSummary2[$month][$channel]['sb_amount'])) {
  2080. $costSummary2[$month][$channel]['sb_amount'] = $amount;
  2081. }else{
  2082. $costSummary2[$month][$channel]['sb_amount'] = bcadd(
  2083. $costSummary2[$month][$channel]['sb_amount'],
  2084. $amount,
  2085. 3
  2086. );
  2087. }
  2088. if(! empty($t)){
  2089. $type = $t['type'];
  2090. $c_t = $t['channel_details'];
  2091. if(in_array($channel, $c_t)){
  2092. if (!isset($costSummary2_road[$month][$type]['sb_amount'])) {
  2093. $costSummary2_road[$month][$type]['sb_amount'] = $amount;
  2094. }else{
  2095. $costSummary2_road[$month][$type]['sb_amount'] = bcadd(
  2096. $costSummary2_road[$month][$type]['sb_amount'],
  2097. $amount,
  2098. 3
  2099. );
  2100. }
  2101. }
  2102. }
  2103. }
  2104. $sj_amount = bcmul($amount,0.01,3);
  2105. if (! isset($costSummary2[$month][$channel]['sj_amount'])) {
  2106. $costSummary2[$month][$channel]['sj_amount'] = $sj_amount;
  2107. }else{
  2108. $costSummary2[$month][$channel]['sj_amount'] = bcadd(
  2109. $costSummary2[$month][$channel]['sj_amount'],
  2110. $sj_amount,
  2111. 3
  2112. );
  2113. }
  2114. if(! empty($t)){
  2115. $type = $t['type'];
  2116. $c_t = $t['channel_details'];
  2117. if(in_array($channel, $c_t)){
  2118. if (!isset($costSummary2_road[$month][$type]['sj_amount'])) {
  2119. $costSummary2_road[$month][$type]['sj_amount'] = $amount;
  2120. }else{
  2121. $costSummary2_road[$month][$type]['sj_amount'] = bcadd(
  2122. $costSummary2_road[$month][$type]['sj_amount'],
  2123. $amount,
  2124. 3
  2125. );
  2126. }
  2127. }
  2128. }
  2129. }
  2130. // 更新 lastId
  2131. $lastId = $rows->last()->id;
  2132. } while ($rows->count() === $limit);
  2133. }catch (\Throwable $exception){
  2134. return [false, "初步汇总异常" . $exception->getMessage() . "|" . $exception->getLine() . "|" . $exception->getFile()];
  2135. }
  2136. try {
  2137. $start_timeStamp = $data['start_timeStamp'];
  2138. $end_timeStamp = $data['end_timeStamp'];
  2139. $result = $this->sumRes($paymentSummary,$costSummary,$costSummary2);
  2140. $result2 = $this->sumRes2($paymentSummary_road, $costSummary_road, $costSummary2_road);
  2141. DB::transaction(function () use ($start_timeStamp, $end_timeStamp, $result, $result2) {
  2142. // 1. 先删除旧数据
  2143. ItemReport::where('time', '>=', $start_timeStamp)
  2144. ->where('time', '<=', $end_timeStamp)
  2145. ->delete();
  2146. ItemReportRoad::where('time', '>=', $start_timeStamp)
  2147. ->where('time', '<=', $end_timeStamp)
  2148. ->delete();
  2149. // 2. 插入新数据
  2150. ItemReport::insert($result);
  2151. ItemReportRoad::insert($result2);
  2152. });
  2153. }catch (\Throwable $exception){
  2154. return [false, "结果异常" . $exception->getMessage() . "|" . $exception->getLine() . "|" . $exception->getFile()];
  2155. }
  2156. return [true, ''];
  2157. }
  2158. private function saveResult($data, $user){
  2159. // 初始化汇总数组------报表一
  2160. $paymentSummary = [];
  2161. $costSummary = [];
  2162. $costSummary2 = [];
  2163. // 初始化汇总数组------报表二 (业务员报表)
  2164. $manSummary = [];
  2165. try{
  2166. $limit = 500;
  2167. $lastId = 0;
  2168. do {
  2169. //收入
  2170. $rows = DB::table('tmp_item_road')
  2171. ->where('id', '>', $lastId)
  2172. ->orderBy('id')
  2173. ->limit($limit)
  2174. ->select([
  2175. 'id',
  2176. 'order_time',
  2177. 'channel_details',
  2178. 'channel_finance',
  2179. 'payment_amount',
  2180. 'price_4_total',
  2181. 'is_kh',
  2182. 'employee_id_1',
  2183. 'employee_id_1_title',
  2184. 'employee_id_2'
  2185. ])
  2186. ->get();
  2187. if ($rows->isEmpty()) {
  2188. break;
  2189. }
  2190. foreach ($rows as $row) {
  2191. $order_time = $row->order_time;
  2192. $month = strtotime(date("Y-m-01", $order_time));
  2193. $channel = $row->channel_details ?? '';
  2194. $finance = $row->channel_finance ?? '';
  2195. $empId = $row->employee_id_1 ?? 0;
  2196. $empName = $row->employee_id_1_title ?? '';
  2197. // --- 原报表一逻辑 (不改动) ---
  2198. if (! $row->is_kh) {
  2199. $paymentSummary[$month][$channel] = bcadd($paymentSummary[$month][$channel] ?? 0, $row->payment_amount, 3);
  2200. }
  2201. $costSummary[$month][$channel] = bcadd($costSummary[$month][$channel] ?? 0, $row->price_4_total, 3);
  2202. // --- 新报表二逻辑 (业务员维度) ---
  2203. $key = "{$month}_{$finance}_{$empId}";
  2204. if (!isset($manSummary[$key])) {
  2205. $manSummary[$key] = [
  2206. 'time' => $month,
  2207. 'channel_finance' => $finance,
  2208. 'employee_id_1' => $empId,
  2209. 'employee_id_1_title' => $empName,
  2210. 'receipt_amount' => 0,
  2211. 'receipt_not_amount' => 0,
  2212. 'cost' => 0,
  2213. 'profit' => 0,
  2214. 'profit_not' => 0,
  2215. 'settle_amount' => 0,
  2216. 'gl_amount' => 0,
  2217. 'gl_not_amount' => 0,
  2218. 'wl_amount' => 0,
  2219. 'wl_not_amount' => 0,
  2220. 'ht_amount' => 0,
  2221. 'zk_amount' => 0,
  2222. 'cx_amount' => 0,
  2223. 'tg_amount' => 0,
  2224. 'cl_amount' => 0,
  2225. 'kq_amount' => 0,
  2226. 'zp_amount' => 0,
  2227. 'gg_amount' => 0,
  2228. 'kd_amount' => 0,
  2229. 'xsqt_amount' => 0,
  2230. 'ry_amount' => 0,
  2231. 'sb_amount' => 0,
  2232. 'sj_amount' => 0,
  2233. 'sj_not_amount' => 0,
  2234. 'sx_amount' => 0,
  2235. 'sx_not_amount' => 0,
  2236. 'cg_amount' => 0,
  2237. 'other_ck_amount' => 0,
  2238. ];
  2239. }
  2240. // 收款总额 (所有)
  2241. $manSummary[$key]['receipt_amount'] = bcadd($manSummary[$key]['receipt_amount'], $row->payment_amount, 3);
  2242. // 收款 (不含不计考勤 is_kh == 0)
  2243. if (!$row->is_kh) {
  2244. $manSummary[$key]['receipt_not_amount'] = bcadd($manSummary[$key]['receipt_not_amount'], $row->payment_amount, 3);
  2245. }
  2246. // 业务成本
  2247. $manSummary[$key]['cost'] = bcadd($manSummary[$key]['cost'], $row->price_4_total, 3);
  2248. }
  2249. $lastId = $rows->last()->id;
  2250. } while ($rows->count() === $limit);
  2251. // 计算毛利
  2252. foreach ($manSummary as $key => $val) {
  2253. // 1. 计算总毛利:总收款 - 总成本
  2254. $manSummary[$key]['profit'] = bcsub(
  2255. $val['receipt_amount'],
  2256. $val['cost'],
  2257. 3
  2258. );
  2259. // 2. 计算不含不计考勤毛利:考核收款 - 总成本
  2260. $manSummary[$key]['profit_not'] = bcsub(
  2261. $val['receipt_not_amount'],
  2262. $val['cost'],
  2263. 3
  2264. );
  2265. }
  2266. $limit = 500;
  2267. $lastId = 0;
  2268. do {
  2269. //指出
  2270. $rows = DB::table('tmp_item_cost')
  2271. ->where('id', '>', $lastId)
  2272. ->orderBy('id')
  2273. ->limit($limit)
  2274. ->select([
  2275. 'id', 'order_time', 'channel_details', 'ck_type', 'fy_code', 'taxamount', 'employee_id_1', 'channel_finance', 'order_type' , 'employee_id_1_title'
  2276. ])
  2277. ->get();
  2278. if ($rows->isEmpty()) {
  2279. break;
  2280. }
  2281. foreach ($rows as $row) {
  2282. $order_time = $row->order_time;
  2283. $month = strtotime(date("Y-m-01", $order_time));
  2284. $channel = $row->channel_details ?? '';
  2285. $finance = $row->channel_finance ?? '';
  2286. $empId = $row->employee_id_1 ?? 0;
  2287. $empName = $row->employee_id_1_title ?? '';
  2288. $amount = $row->taxamount;
  2289. //表一-------------------------------------------------------
  2290. // 结算费用
  2291. if($row->fy_code == 7004){
  2292. $costSummary2[$month][$channel]['settle_amount'] = bcadd($costSummary2[$month][$channel]['settle_amount'] ?? 0, $amount, 3);
  2293. }
  2294. // 管理费 (5%)
  2295. $gl_amount = bcmul($amount, 0.05, 3);
  2296. $costSummary2[$month][$channel]['gl_amount'] = bcadd($costSummary2[$month][$channel]['gl_amount'] ?? 0, $gl_amount, 3);
  2297. // 物流费 (2.3%)
  2298. $wl_amount = bcmul($amount, 0.023, 3);
  2299. $costSummary2[$month][$channel]['wl_amount'] = bcadd($costSummary2[$month][$channel]['wl_amount'] ?? 0, $wl_amount, 3);
  2300. if($row->fy_code == 7005) $costSummary2[$month][$channel]['ht_amount'] = bcadd($costSummary2[$month][$channel]['ht_amount'] ?? 0, $amount, 3);
  2301. if($row->fy_code == 7006) $costSummary2[$month][$channel]['zk_amount'] = bcadd($costSummary2[$month][$channel]['zk_amount'] ?? 0, $amount, 3);
  2302. if($row->fy_code == 7007) $costSummary2[$month][$channel]['cx_amount'] = bcadd($costSummary2[$month][$channel]['cx_amount'] ?? 0, $amount, 3);
  2303. if($row->fy_code == 7013) $costSummary2[$month][$channel]['tg_amount'] = bcadd($costSummary2[$month][$channel]['tg_amount'] ?? 0, $amount, 3);
  2304. if($row->fy_code == 7012) $costSummary2[$month][$channel]['cl_amount'] = bcadd($costSummary2[$month][$channel]['cl_amount'] ?? 0, $amount, 3);
  2305. // 客情出库
  2306. if($row->fy_code == 7008 || $row->ck_type == 20049) {
  2307. $costSummary2[$month][$channel]['kq_amount'] = bcadd($costSummary2[$month][$channel]['kq_amount'] ?? 0, $amount, 3);
  2308. }
  2309. // 赠品出库
  2310. if($row->fy_code == 7009 || $row->ck_type == 60) {
  2311. $costSummary2[$month][$channel]['zp_amount'] = bcadd($costSummary2[$month][$channel]['zp_amount'] ?? 0, $amount, 3);
  2312. }
  2313. if($row->fy_code == 7010) $costSummary2[$month][$channel]['gg_amount'] = bcadd($costSummary2[$month][$channel]['gg_amount'] ?? 0, $amount, 3);
  2314. if($row->fy_code == 7011) $costSummary2[$month][$channel]['kd_amount'] = bcadd($costSummary2[$month][$channel]['kd_amount'] ?? 0, $amount, 3);
  2315. if($row->fy_code == 7001) $costSummary2[$month][$channel]['xsqt_amount'] = bcadd($costSummary2[$month][$channel]['xsqt_amount'] ?? 0, $amount, 3);
  2316. if($row->fy_code == 7003) $costSummary2[$month][$channel]['ry_amount'] = bcadd($costSummary2[$month][$channel]['ry_amount'] ?? 0, $amount, 3);
  2317. // 社保/福利
  2318. if($row->fy_code == 7019 || $row->ck_type == 20048) {
  2319. $costSummary2[$month][$channel]['sb_amount'] = bcadd($costSummary2[$month][$channel]['sb_amount'] ?? 0, $amount, 3);
  2320. }
  2321. // 税金 (1%)
  2322. $sj_amount = bcmul($amount, 0.01, 3);
  2323. $costSummary2[$month][$channel]['sj_amount'] = bcadd($costSummary2[$month][$channel]['sj_amount'] ?? 0, $sj_amount, 3);
  2324. // 表二----------------------------------------------------------------------
  2325. $key = "{$month}_{$finance}_{$empId}";
  2326. if (!isset($manSummary[$key])) {
  2327. $manSummary[$key] = [
  2328. 'time' => $month,
  2329. 'channel_finance' => $finance,
  2330. 'employee_id_1' => $empId,
  2331. 'employee_id_1_title' => $empName,
  2332. 'receipt_amount' => 0,
  2333. 'receipt_not_amount' => 0,
  2334. 'cost' => 0,
  2335. 'profit' => 0,
  2336. 'profit_not' => 0,
  2337. 'settle_amount' => 0,
  2338. 'gl_amount' => 0,
  2339. 'gl_not_amount' => 0,
  2340. 'wl_amount' => 0,
  2341. 'wl_not_amount' => 0,
  2342. 'ht_amount' => 0,
  2343. 'zk_amount' => 0,
  2344. 'cx_amount' => 0,
  2345. 'tg_amount' => 0,
  2346. 'cl_amount' => 0,
  2347. 'kq_amount' => 0,
  2348. 'zp_amount' => 0,
  2349. 'gg_amount' => 0,
  2350. 'kd_amount' => 0,
  2351. 'xsqt_amount' => 0,
  2352. 'ry_amount' => 0,
  2353. 'sb_amount' => 0,
  2354. 'sj_amount' => 0,
  2355. 'sj_not_amount' => 0,
  2356. 'sx_amount' => 0,
  2357. 'sx_not_amount' => 0,
  2358. 'cg_amount' => 0,
  2359. 'other_ck_amount' => 0,
  2360. ];
  2361. }
  2362. if ($row->order_type == 2) {
  2363. // 1. 判断是否为其他出库
  2364. $manSummary[$key]['other_ck_amount'] = bcadd($manSummary[$key]['other_ck_amount'] ?? 0, $amount, 3);
  2365. } else {
  2366. // 2. 正常费用代码归类
  2367. if($row->fy_code == 7004) $manSummary[$key]['settle_amount'] = bcadd($manSummary[$key]['settle_amount'] ?? 0, $amount, 3);
  2368. if($row->fy_code == 7005) $manSummary[$key]['ht_amount'] = bcadd($manSummary[$key]['ht_amount'] ?? 0, $amount, 3);
  2369. if($row->fy_code == 7006) $manSummary[$key]['zk_amount'] = bcadd($manSummary[$key]['zk_amount'] ?? 0, $amount, 3);
  2370. if($row->fy_code == 7007) $manSummary[$key]['cx_amount'] = bcadd($manSummary[$key]['cx_amount'] ?? 0, $amount, 3);
  2371. if($row->fy_code == 7013) $manSummary[$key]['tg_amount'] = bcadd($manSummary[$key]['tg_amount'] ?? 0, $amount, 3);
  2372. if($row->fy_code == 7012) $manSummary[$key]['cl_amount'] = bcadd($manSummary[$key]['cl_amount'] ?? 0, $amount, 3);
  2373. if($row->fy_code == 7008) $manSummary[$key]['kq_amount'] = bcadd($manSummary[$key]['kq_amount'] ?? 0, $amount, 3);
  2374. if($row->fy_code == 7009) $manSummary[$key]['zp_amount'] = bcadd($manSummary[$key]['zp_amount'] ?? 0, $amount, 3);
  2375. if($row->fy_code == 7010) $manSummary[$key]['gg_amount'] = bcadd($manSummary[$key]['gg_amount'] ?? 0, $amount, 3);
  2376. if($row->fy_code == 7011) $manSummary[$key]['kd_amount'] = bcadd($manSummary[$key]['kd_amount'] ?? 0, $amount, 3);
  2377. if($row->fy_code == 7001) $manSummary[$key]['xsqt_amount'] = bcadd($manSummary[$key]['xsqt_amount'] ?? 0, $amount, 3);
  2378. if($row->fy_code == 7003) $manSummary[$key]['ry_amount'] = bcadd($manSummary[$key]['ry_amount'] ?? 0, $amount, 3);
  2379. if($row->fy_code == 7019) $manSummary[$key]['sb_amount'] = bcadd($manSummary[$key]['sb_amount'] ?? 0, $amount, 3);
  2380. if($row->fy_code == 7023) $manSummary[$key]['cg_amount'] = bcadd($manSummary[$key]['cg_amount'] ?? 0, $amount, 3);
  2381. }
  2382. }
  2383. $lastId = $rows->last()->id;
  2384. } while ($rows->count() === $limit);
  2385. } catch (\Throwable $exception){
  2386. return [false, "初步汇总异常" . $exception->getMessage() . "|" . $exception->getLine()];
  2387. }
  2388. foreach ($manSummary as $key => $item) {
  2389. $r_amount = $item['receipt_amount'];
  2390. $r_not_amount = $item['receipt_not_amount'];
  2391. // 1. 计算毛利
  2392. $manSummary[$key]['profit'] = bcsub($r_amount, $item['cost'], 3);
  2393. $manSummary[$key]['profit_not'] = bcsub($r_not_amount, $item['cost'], 3);
  2394. // 2. 统一计算比例费用(此时 $r_amount 是汇总后的总额,只算一次,绝对准确)
  2395. $manSummary[$key]['gl_amount'] = bcmul($r_amount, 0.05, 3);
  2396. $manSummary[$key]['gl_not_amount'] = bcmul($r_not_amount, 0.05, 3);
  2397. $manSummary[$key]['wl_amount'] = bcmul($r_amount, 0.023, 3);
  2398. $manSummary[$key]['wl_not_amount'] = bcmul($r_not_amount, 0.023, 3);
  2399. $manSummary[$key]['sj_amount'] = bcmul($r_amount, 0.01, 3);
  2400. $manSummary[$key]['sj_not_amount'] = bcmul($r_not_amount, 0.01, 3);
  2401. // 补齐字段,防止 DB 报错
  2402. $manSummary[$key]['sx_amount'] = bcmul($r_amount, 0.01, 3);
  2403. $manSummary[$key]['sx_not_amount'] = bcmul($r_not_amount, 0.01, 3);
  2404. }
  2405. try {
  2406. $start_timeStamp = $data['start_timeStamp'];
  2407. $end_timeStamp = $data['end_timeStamp'];
  2408. $result = $this->sumRes($paymentSummary, $costSummary, $costSummary2);
  2409. $manSummary = array_values($manSummary);
  2410. DB::transaction(function () use ($start_timeStamp, $end_timeStamp, $result, $manSummary) {
  2411. ItemReport::where('time', '>=', $start_timeStamp)
  2412. ->where('time', '<=', $end_timeStamp)
  2413. ->delete();
  2414. ItemReport::insert($result);
  2415. ItemReportMan::where('time', '>=', $start_timeStamp)
  2416. ->where('time', '<=', $end_timeStamp)
  2417. ->delete();
  2418. ItemReportMan::insert($manSummary);
  2419. });
  2420. } catch (\Throwable $exception){
  2421. return [false, "结果异常" . $exception->getMessage() . "|" . $exception->getLine()];
  2422. }
  2423. return [true, ''];
  2424. }
  2425. private function sumRes($paymentSummary, $costSummary, $costSummary2){
  2426. // 合并三个汇总数组为最终结果
  2427. $result = [];
  2428. // 获取所有唯一的时间+渠道组合
  2429. $keys = [];
  2430. foreach (array_keys($paymentSummary) as $month) {
  2431. foreach (array_keys($paymentSummary[$month]) as $channel) {
  2432. $keys["$month|$channel"] = ['month' => $month, 'channel' => $channel];
  2433. }
  2434. }
  2435. foreach (array_keys($costSummary) as $month) {
  2436. foreach (array_keys($costSummary[$month]) as $channel) {
  2437. $keys["$month|$channel"] = ['month' => $month, 'channel' => $channel];
  2438. }
  2439. }
  2440. foreach (array_keys($costSummary2) as $month) {
  2441. foreach (array_keys($costSummary2[$month]) as $channel) {
  2442. $keys["$month|$channel"] = ['month' => $month, 'channel' => $channel];
  2443. }
  2444. }
  2445. // 遍历所有组合,构建最终数据
  2446. foreach ($keys as $key => $info) {
  2447. $month = $info['month'];
  2448. $channel = $info['channel'];
  2449. // 收款销售收入(注意:原逻辑中 is_kh == false 才计入)
  2450. $receipt_amount = isset($paymentSummary[$month][$channel])
  2451. ? $paymentSummary[$month][$channel]
  2452. : '0.000';
  2453. // 业务成本(来自 tmp_item_road 的 price_4_total)
  2454. $cost = isset($costSummary[$month][$channel])
  2455. ? $costSummary[$month][$channel]
  2456. : '0.000';
  2457. // 利润 = 收入 - 成本
  2458. $profit = bcsub($receipt_amount, $cost, 3);
  2459. // 从 costSummary2 提取各项费用(默认为 0.000)
  2460. $cs2 = $costSummary2[$month][$channel] ?? [];
  2461. $settle_amount = $cs2['settle_amount'] ?? '0.000';
  2462. $gl_amount = $cs2['gl_amount'] ?? '0.000';
  2463. $wl_amount = $cs2['wl_amount'] ?? '0.000';
  2464. $ht_amount = $cs2['ht_amount'] ?? '0.000';
  2465. $zk_amount = $cs2['zk_amount'] ?? '0.000';
  2466. $cx_amount = $cs2['cx_amount'] ?? '0.000';
  2467. $tg_amount = $cs2['tg_amount'] ?? '0.000';
  2468. $cl_amount = $cs2['cl_amount'] ?? '0.000';
  2469. $kq_amount = $cs2['kq_amount'] ?? '0.000';
  2470. $zp_amount = $cs2['zp_amount'] ?? '0.000';
  2471. $gg_amount = $cs2['gg_amount'] ?? '0.000';
  2472. $kd_amount = $cs2['kd_amount'] ?? '0.000';
  2473. $xsqt_amount = $cs2['xsqt_amount'] ?? '0.000';
  2474. $ry_amount = $cs2['ry_amount'] ?? '0.000';
  2475. $sb_amount = $cs2['sb_amount'] ?? '0.000';
  2476. $sj_amount = $cs2['sj_amount'] ?? '0.000';
  2477. $result[] = [
  2478. 'time' => $month,
  2479. 'channel_details'=> $channel,
  2480. 'receipt_amount' => $receipt_amount,
  2481. 'cost' => $cost,
  2482. 'profit' => $profit,
  2483. 'settle_amount' => $settle_amount,
  2484. 'gl_amount' => $gl_amount,
  2485. 'wl_amount' => $wl_amount,
  2486. 'ht_amount' => $ht_amount,
  2487. 'zk_amount' => $zk_amount,
  2488. 'cx_amount' => $cx_amount,
  2489. 'tg_amount' => $tg_amount,
  2490. 'cl_amount' => $cl_amount,
  2491. 'kq_amount' => $kq_amount,
  2492. 'zp_amount' => $zp_amount,
  2493. 'gg_amount' => $gg_amount,
  2494. 'kd_amount' => $kd_amount,
  2495. 'xsqt_amount' => $xsqt_amount,
  2496. 'ry_amount' => $ry_amount,
  2497. 'sb_amount' => $sb_amount,
  2498. 'sj_amount' => $sj_amount,
  2499. ];
  2500. }
  2501. return $result;
  2502. }
  2503. private function sumRes2($paymentSummary, $costSummary, $costSummary2){
  2504. // 合并三个汇总数组为最终结果
  2505. $result = [];
  2506. // 获取所有唯一的时间+渠道组合
  2507. $keys = [];
  2508. foreach (array_keys($paymentSummary) as $month) {
  2509. foreach (array_keys($paymentSummary[$month]) as $channel) {
  2510. $keys["$month|$channel"] = ['month' => $month, 'channel' => $channel];
  2511. }
  2512. }
  2513. foreach (array_keys($costSummary) as $month) {
  2514. foreach (array_keys($costSummary[$month]) as $channel) {
  2515. $keys["$month|$channel"] = ['month' => $month, 'channel' => $channel];
  2516. }
  2517. }
  2518. foreach (array_keys($costSummary2) as $month) {
  2519. foreach (array_keys($costSummary2[$month]) as $channel) {
  2520. $keys["$month|$channel"] = ['month' => $month, 'channel' => $channel];
  2521. }
  2522. }
  2523. // 遍历所有组合,构建最终数据
  2524. foreach ($keys as $key => $info) {
  2525. $month = $info['month'];
  2526. $channel = $info['channel'];
  2527. // 收款销售收入
  2528. $receipt_amount = isset($paymentSummary[$month][$channel])
  2529. ? $paymentSummary[$month][$channel]
  2530. : '0.000';
  2531. // 业务成本(来自 tmp_item_road 的 price_4_total)
  2532. $cost = isset($costSummary[$month][$channel])
  2533. ? $costSummary[$month][$channel]
  2534. : '0.000';
  2535. // 利润 = 收入 - 成本
  2536. $profit = bcsub($receipt_amount, $cost, 3);
  2537. // 从 costSummary2 提取各项费用(默认为 0.000)
  2538. $cs2 = $costSummary2[$month][$channel] ?? [];
  2539. $settle_amount = $cs2['settle_amount'] ?? '0.000';
  2540. $gl_amount = $cs2['gl_amount'] ?? '0.000';
  2541. $wl_amount = $cs2['wl_amount'] ?? '0.000';
  2542. $ht_amount = $cs2['ht_amount'] ?? '0.000';
  2543. $zk_amount = $cs2['zk_amount'] ?? '0.000';
  2544. $cx_amount = $cs2['cx_amount'] ?? '0.000';
  2545. $tg_amount = $cs2['tg_amount'] ?? '0.000';
  2546. $cl_amount = $cs2['cl_amount'] ?? '0.000';
  2547. $kq_amount = $cs2['kq_amount'] ?? '0.000';
  2548. $zp_amount = $cs2['zp_amount'] ?? '0.000';
  2549. $gg_amount = $cs2['gg_amount'] ?? '0.000';
  2550. $kd_amount = $cs2['kd_amount'] ?? '0.000';
  2551. $xsqt_amount = $cs2['xsqt_amount'] ?? '0.000';
  2552. $ry_amount = $cs2['ry_amount'] ?? '0.000';
  2553. $sb_amount = $cs2['sb_amount'] ?? '0.000';
  2554. $sj_amount = $cs2['sj_amount'] ?? '0.000';
  2555. $result[] = [
  2556. 'time' => $month,
  2557. 'receipt_amount' => $receipt_amount,
  2558. 'cost' => $cost,
  2559. 'profit' => $profit,
  2560. 'settle_amount' => $settle_amount,
  2561. 'gl_amount' => $gl_amount,
  2562. 'wl_amount' => $wl_amount,
  2563. 'ht_amount' => $ht_amount,
  2564. 'zk_amount' => $zk_amount,
  2565. 'cx_amount' => $cx_amount,
  2566. 'tg_amount' => $tg_amount,
  2567. 'cl_amount' => $cl_amount,
  2568. 'kq_amount' => $kq_amount,
  2569. 'zp_amount' => $zp_amount,
  2570. 'gg_amount' => $gg_amount,
  2571. 'kd_amount' => $kd_amount,
  2572. 'xsqt_amount' => $xsqt_amount,
  2573. 'ry_amount' => $ry_amount,
  2574. 'sb_amount' => $sb_amount,
  2575. 'sj_amount' => $sj_amount,
  2576. 'employee_title_type' => $channel
  2577. ];
  2578. }
  2579. return $result;
  2580. }
  2581. }