TPlusServerService.php 151 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096209720982099210021012102210321042105210621072108210921102111211221132114211521162117211821192120212121222123212421252126212721282129213021312132213321342135213621372138213921402141214221432144214521462147214821492150215121522153215421552156215721582159216021612162216321642165216621672168216921702171217221732174217521762177217821792180218121822183218421852186218721882189219021912192219321942195219621972198219922002201220222032204220522062207220822092210221122122213221422152216221722182219222022212222222322242225222622272228222922302231223222332234223522362237223822392240224122422243224422452246224722482249225022512252225322542255225622572258225922602261226222632264226522662267226822692270227122722273227422752276227722782279228022812282228322842285228622872288228922902291229222932294229522962297229822992300230123022303230423052306230723082309231023112312231323142315231623172318231923202321232223232324232523262327232823292330233123322333233423352336233723382339234023412342234323442345234623472348234923502351235223532354235523562357235823592360236123622363236423652366236723682369237023712372237323742375237623772378237923802381238223832384238523862387238823892390239123922393239423952396239723982399240024012402240324042405240624072408240924102411241224132414241524162417241824192420242124222423242424252426242724282429243024312432243324342435243624372438243924402441244224432444244524462447244824492450245124522453245424552456245724582459246024612462246324642465246624672468246924702471247224732474247524762477247824792480248124822483248424852486248724882489249024912492249324942495249624972498249925002501250225032504250525062507250825092510251125122513251425152516251725182519252025212522252325242525252625272528252925302531253225332534253525362537253825392540254125422543254425452546254725482549255025512552255325542555255625572558255925602561256225632564256525662567256825692570257125722573257425752576257725782579258025812582258325842585258625872588258925902591259225932594259525962597259825992600260126022603260426052606260726082609261026112612261326142615261626172618261926202621262226232624262526262627262826292630263126322633263426352636263726382639264026412642264326442645264626472648264926502651265226532654265526562657265826592660266126622663266426652666266726682669267026712672267326742675267626772678267926802681268226832684268526862687268826892690269126922693269426952696269726982699270027012702270327042705270627072708270927102711271227132714271527162717271827192720272127222723272427252726272727282729273027312732273327342735273627372738273927402741274227432744274527462747274827492750275127522753275427552756275727582759276027612762276327642765276627672768276927702771277227732774277527762777277827792780278127822783278427852786278727882789279027912792279327942795279627972798279928002801280228032804280528062807280828092810281128122813281428152816281728182819282028212822282328242825282628272828282928302831283228332834283528362837283828392840284128422843284428452846284728482849285028512852285328542855285628572858285928602861286228632864286528662867286828692870287128722873287428752876287728782879288028812882288328842885288628872888288928902891289228932894289528962897289828992900290129022903290429052906290729082909291029112912291329142915291629172918291929202921292229232924292529262927292829292930293129322933293429352936293729382939294029412942294329442945294629472948294929502951295229532954295529562957295829592960296129622963296429652966296729682969297029712972297329742975297629772978297929802981298229832984298529862987298829892990299129922993299429952996299729982999300030013002300330043005300630073008300930103011301230133014301530163017301830193020302130223023302430253026302730283029303030313032303330343035303630373038303930403041304230433044304530463047304830493050305130523053305430553056305730583059306030613062306330643065306630673068
  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 as rp')
  1394. // // 使用 leftJoin 确保主表始终存在
  1395. // ->leftJoin('ARAP_ReceivePayment_b as rp_b', 'rp.ID', '=', 'rp_b.idArapReceivePaymentDTO')
  1396. // // 发票子表等关联逻辑保持不变
  1397. // ->leftJoin('SA_SaleInvoice_b as si_b', function ($join) {
  1398. // $join->on('rp_b.voucherDetailID', '=', 'si_b.ID')
  1399. // ->where('rp_b.idvouchertype', '=', 20);
  1400. // })
  1401. // ->leftJoin('SA_SaleInvoice as si', function ($join) {
  1402. // $join->on('si_b.idSaleInvoiceDTO', '=', 'si.ID')
  1403. // ->where('rp_b.idvouchertype', '=', 20);
  1404. // })
  1405. // ->leftJoin('SA_SaleDelivery_b as sd_b', function ($join) {
  1406. // $join->on('si_b.sourceVoucherDetailId', '=', 'sd_b.ID')
  1407. // ->where('rp_b.idvouchertype', '=', 20);
  1408. // })
  1409. // ->leftJoin('SA_SaleDelivery as sd', function ($join) {
  1410. // $join->on('sd_b.idSaleDeliveryDTO', '=', 'sd.ID')
  1411. // ->where('rp_b.idvouchertype', '=', 20);
  1412. // })
  1413. // ->leftJoin('AA_Inventory as it', 'sd_b.idinventory', '=', 'it.ID')
  1414. // ->leftJoin('AA_Partner as pn', 'rp.idpartner', '=', 'pn.ID')
  1415. // ->leftJoin('AA_Person as ps', 'rp.idperson', '=', 'ps.ID')
  1416. // ->leftJoin('AA_Person as ps2', 'pn.idsaleman', '=', 'ps2.ID')
  1417. // ->where('rp.voucherdate', '>=', $data['start_time'])
  1418. // ->where('rp.voucherdate', '<=', $data['end_time'])
  1419. // ->where('rp.isReceiveFlag', '=', 1)
  1420. // // 核心修改:按主表 ID 进行分页过滤
  1421. // ->where('rp.ID', '>', $lastId)
  1422. // ->orderBy('rp.ID', 'asc')
  1423. // ->limit($limit)
  1424. // ->selectRaw("
  1425. // COALESCE(rp.ID, 0) as order_id,
  1426. // COALESCE(rp.code, '') as order_number,
  1427. // rp.voucherdate as order_time,
  1428. // rp.voucherstate as order_state,
  1429. // COALESCE(rp.pubuserdefnvc11, '') as channel_finance,
  1430. // COALESCE(rp.pubuserdefnvc12, '') as channel_details,
  1431. // COALESCE(si.pubuserdefnvc12, '') as channel_details_fp,
  1432. // COALESCE(pn.code, '') as customer_code,
  1433. // COALESCE(pn.name, '') as customer_title,
  1434. // CASE WHEN rp_b.idvouchertype = 20 THEN COALESCE(it.code, '') ELSE '' END as product_code,
  1435. // CASE WHEN rp_b.idvouchertype = 20 THEN COALESCE(it.name, '') ELSE '' END as product_title,
  1436. // COALESCE(rp.idperson, 0) as employee_id_1,
  1437. // COALESCE(ps.name, '') as employee_id_1_title,
  1438. // COALESCE(pn.idsaleman, 0) as employee_id_2,
  1439. // COALESCE(ps2.name, '') as employee_id_2_title,
  1440. // CASE WHEN rp_b.idvouchertype = 20 THEN COALESCE(si_b.quantity, 0) ELSE 0 END as quantity,
  1441. // CASE WHEN rp_b.idvouchertype = 20 THEN COALESCE(si_b.taxPrice, 0) ELSE 0 END as price_1,
  1442. // CASE WHEN rp_b.idvouchertype = 20 THEN COALESCE(si_b.taxAmount, 0) ELSE 0 END as price_1_total,
  1443. // COALESCE(rp_b.origCurrentAmount, 0) as payment_amount,
  1444. // COALESCE(rp_b.ID, 0) as id_detail,
  1445. // COALESCE(rp_b.voucherDetailID, 0) as id_detail_upstream,
  1446. // COALESCE(rp_b.voucherCode, '') as order_number_upstream,
  1447. // COALESCE(rp_b.idvouchertype, 0) as voucher_type,
  1448. // CASE WHEN rp_b.idvouchertype = 20 THEN COALESCE(sd.priuserdefnvc4, '') ELSE '' END as is_kh
  1449. // ")
  1450. // ->get();
  1451. //
  1452. // if ($rows->isEmpty()) break;
  1453. //
  1454. // $dataArray = $rows->map(function ($item) {
  1455. // return (array)$item;
  1456. // })->toArray();
  1457. //
  1458. // // 存货档案业务成本
  1459. // $product_codes = array_filter(array_unique(array_column($dataArray, 'product_code')));
  1460. // $product_map = [];
  1461. // if (!empty($product_codes)) {
  1462. // $product_map = Product::where('del_time', 0)
  1463. // ->whereIn('code', $product_codes)
  1464. // ->pluck('business_cost', 'code')
  1465. // ->all();
  1466. // }
  1467. //
  1468. // foreach ($dataArray as $key => $value) {
  1469. // $p_tmp = $product_map[$value['product_code']] ?? 0;
  1470. // $dataArray[$key]['order_type'] = RevenueCost::ORDER_THREE;
  1471. // // 注意:如果 order_time 是字符串格式,strtotime 是必须的
  1472. // $dataArray[$key]['order_time'] = is_numeric($value['order_time']) ? $value['order_time'] : strtotime($value['order_time']);
  1473. //
  1474. // $business_cost = (float)$p_tmp;
  1475. // $dataArray[$key]['price_4'] = $business_cost;
  1476. // $dataArray[$key]['price_4_total'] = bcmul((string)$business_cost, (string)$value['quantity'], 2);
  1477. // }
  1478. //
  1479. // DB::table($table)->insert($dataArray);
  1480. //
  1481. // // 更新 lastId 为当前批次最后一条数据的【主表ID】
  1482. // $lastId = end($dataArray)['order_id'];
  1483. //
  1484. // } while (count($rows) === $limit);
  1485. $rows = $this->databaseService->table('ARAP_ReceivePayment_b as rp_b')
  1486. ->join('ARAP_ReceivePayment as rp', 'rp_b.idArapReceivePaymentDTO', '=', 'rp.ID')
  1487. // 发票子表关联(仅限 idvouchertype = 20)
  1488. ->leftJoin('SA_SaleInvoice_b as si_b', function ($join) {
  1489. $join->on('rp_b.voucherDetailID', '=', 'si_b.ID')
  1490. ->where('rp_b.idvouchertype', '=', 20);
  1491. })
  1492. ->leftJoin('SA_SaleInvoice as si', function ($join) {
  1493. $join->on('si_b.idSaleInvoiceDTO', '=', 'si.ID')
  1494. ->where('rp_b.idvouchertype', '=', 20);
  1495. })
  1496. ->leftJoin('SA_SaleDelivery_b as sd_b', function ($join) {
  1497. $join->on('si_b.sourceVoucherDetailId', '=', 'sd_b.ID')
  1498. ->where('rp_b.idvouchertype', '=', 20);
  1499. })
  1500. ->leftJoin('SA_SaleDelivery as sd', function ($join) {
  1501. $join->on('sd_b.idSaleDeliveryDTO', '=', 'sd.ID')
  1502. ->where('rp_b.idvouchertype', '=', 20);
  1503. })
  1504. ->leftJoin('AA_Inventory as it', 'sd_b.idinventory', '=', 'it.ID')
  1505. ->leftJoin('AA_Partner as pn', 'rp.idpartner', '=', 'pn.ID') //结算客户
  1506. ->leftJoin('AA_Person as ps', 'rp.idperson', '=', 'ps.ID')
  1507. ->leftJoin('AA_Person as ps2', 'pn.idsaleman', '=', 'ps2.ID') // 结算客户的上级管理人员
  1508. ->where('rp.voucherdate','>=',$data['start_time'])
  1509. ->where('rp.voucherdate','<=',$data['end_time'])
  1510. ->where('rp.isReceiveFlag','=', 1)
  1511. ->where('rp_b.ID', '>', $lastId)
  1512. ->orderBy('rp_b.ID')
  1513. ->limit($limit)
  1514. ->selectRaw("
  1515. COALESCE(rp.ID, 0) as order_id,
  1516. COALESCE(rp.code, '') as order_number,
  1517. rp.voucherdate as order_time,
  1518. rp.voucherstate as order_state,
  1519. COALESCE(rp.pubuserdefnvc11, '') as channel_finance,
  1520. COALESCE(rp.pubuserdefnvc12, '') as channel_details,
  1521. COALESCE(si.pubuserdefnvc12, '') as channel_details_fp,
  1522. COALESCE(pn.code, '') as customer_code,
  1523. COALESCE(pn.name, '') as customer_title,
  1524. CASE WHEN rp_b.idvouchertype = 20 THEN COALESCE(it.code, '') ELSE '' END as product_code,
  1525. CASE WHEN rp_b.idvouchertype = 20 THEN COALESCE(it.name, '') ELSE '' END as product_title,
  1526. COALESCE(rp.idperson, 0) as employee_id_1,
  1527. COALESCE(ps.name, '') as employee_id_1_title,
  1528. COALESCE(pn.idsaleman, 0) as employee_id_2,
  1529. COALESCE(ps2.name, '') as employee_id_2_title,
  1530. CASE WHEN rp_b.idvouchertype = 20 THEN COALESCE(si_b.quantity, 0) ELSE 0 END as quantity,
  1531. CASE WHEN rp_b.idvouchertype = 20 THEN COALESCE(si_b.taxPrice, 0) ELSE 0 END as price_1,
  1532. CASE WHEN rp_b.idvouchertype = 20 THEN COALESCE(si_b.taxAmount, 0) ELSE 0 END as price_1_total,
  1533. COALESCE(rp_b.origCurrentAmount, 0) as payment_amount,
  1534. COALESCE(rp_b.ID, 0) as id_detail,
  1535. COALESCE(rp_b.voucherDetailID, 0) as id_detail_upstream,
  1536. COALESCE(rp_b.voucherCode, '') as order_number_upstream,
  1537. rp_b.idvouchertype as voucher_type,
  1538. CASE WHEN rp_b.idvouchertype = 20 THEN COALESCE(sd.priuserdefnvc4, '') ELSE '' END as is_kh
  1539. ")
  1540. ->get();
  1541. if ($rows->isEmpty()) break;
  1542. $dataArray = Collect($rows)->map(function ($object) {
  1543. return (array)$object;
  1544. })->toArray();
  1545. //存货档案业务成本
  1546. $product_map = Product::where('del_time',0)
  1547. ->whereIn('code', array_unique(array_column($dataArray,'product_code')))
  1548. ->pluck('business_cost','code')
  1549. ->all();
  1550. //组织数据
  1551. foreach ($dataArray as $key => $value){
  1552. $p_tmp = $product_map[$value['product_code']] ?? 0;
  1553. $dataArray[$key]['order_type'] = RevenueCost::ORDER_THREE;
  1554. $dataArray[$key]['order_time'] = strtotime($value['order_time']);
  1555. //业务成本单价和金额
  1556. $business_cost = $p_tmp ?? 0;
  1557. $dataArray[$key]['price_4'] = $business_cost;
  1558. $price_4_total = bcmul($business_cost, $value['quantity'],2);
  1559. $dataArray[$key]['price_4_total'] = $price_4_total;
  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 synSaleCost($data, $user){
  1571. //创建临时表 如果不存在
  1572. $this->createTmpTable5();
  1573. //清理临时表 如果内容不为空
  1574. // $this->clearTmpTable(5);
  1575. try{
  1576. $table = $this->table_5;
  1577. $limit = 500;
  1578. $lastId = 0;
  1579. do {
  1580. $rows = $this->databaseService->table('CS_ExpenseVoucher_b as cs_b')
  1581. ->join('CS_ExpenseVoucher as cs', 'cs_b.idExpenseVoucherDTO', '=', 'cs.ID')
  1582. ->leftJoin('AA_ExpenseItem as ae', 'ae.id', '=', 'cs_b.idexpenseitem')
  1583. ->leftJoin('AA_Person as ps', 'cs.idclerk', '=', 'ps.ID')
  1584. ->where('cs.voucherdate','>=',$data['start_time'])
  1585. ->where('cs.voucherdate','<=',$data['end_time'])
  1586. ->where('cs_b.ID', '>', $lastId)
  1587. ->orderBy('cs_b.ID')
  1588. ->limit($limit)
  1589. ->selectRaw("
  1590. 1 as order_type,
  1591. COALESCE(cs.ID, 0) as order_id,
  1592. COALESCE(cs.code, '') as order_number,
  1593. cs.voucherdate as order_time,
  1594. cs.idclerk as employee_id_1,
  1595. COALESCE(ps.name, '') as employee_id_1_title,
  1596. COALESCE(cs.pubuserdefnvc12, '') as channel_details,
  1597. COALESCE(cs.pubuserdefnvc11, '') as channel_finance,
  1598. COALESCE(ae.code, '') as fy_code,
  1599. COALESCE(cs_b.taxamount, 0) as taxamount,
  1600. COALESCE(cs_b.ID, 0) as id_detail
  1601. ")
  1602. ->get();
  1603. if ($rows->isEmpty()) break;
  1604. $dataArray = Collect($rows)->map(function ($object) {
  1605. return (array)$object;
  1606. })->toArray();
  1607. foreach ($dataArray as $key => $value){
  1608. $dataArray[$key]['order_time'] = strtotime($value['order_time']);
  1609. }
  1610. DB::table($table)->insert($dataArray);
  1611. // 更新 lastId 继续下一批
  1612. $lastId = end($dataArray)['id_detail'] ?? $lastId;
  1613. } while (count($rows) === $limit);
  1614. }catch (\Throwable $exception){
  1615. return [false, "费用同步异常" . $exception->getMessage() . "|" . $exception->getLine() . "|" . $exception->getFile()];
  1616. }
  1617. try{
  1618. $table = $this->table_5;
  1619. $limit = 500;
  1620. $lastId = 0;
  1621. do {
  1622. $rows = $this->databaseService->table('ST_RDRecord_b as st_b')
  1623. ->join('ST_RDRecord as st', 'st_b.idRDRecordDTO', '=', 'st.ID')
  1624. ->leftJoin('AA_Person as ps', 'st.idclerk', '=', 'ps.ID')
  1625. ->where('st.voucherdate','>=',$data['start_time'])
  1626. ->where('st.voucherdate','<=',$data['end_time'])
  1627. ->where('st.idvouchertype', 30)
  1628. // ->whereIn('st.idbusitype',[20048,60,20049]) //20049 客情出库 60 赠品出库 20048 员工福利
  1629. ->where('st_b.ID', '>', $lastId)
  1630. ->orderBy('st_b.ID')
  1631. ->limit($limit)
  1632. ->selectRaw("
  1633. 2 as order_type,
  1634. COALESCE(st.ID, 0) as order_id,
  1635. COALESCE(st.code, '') as order_number,
  1636. st.voucherdate as order_time,
  1637. st.idclerk as employee_id_1,
  1638. COALESCE(ps.name, '') as employee_id_1_title,
  1639. COALESCE(st.pubuserdefnvc12, '') as channel_details,
  1640. COALESCE(st.pubuserdefnvc11, '') as channel_finance,
  1641. COALESCE(st_b.amount, 0) as taxamount,
  1642. COALESCE(st_b.ID, 0) as id_detail,
  1643. st.idbusitype as ck_type
  1644. ")->get();
  1645. if ($rows->isEmpty()) break;
  1646. $dataArray = Collect($rows)->map(function ($object) {
  1647. return (array)$object;
  1648. })->toArray();
  1649. foreach ($dataArray as $key => $value){
  1650. $dataArray[$key]['order_time'] = strtotime($value['order_time']);
  1651. }
  1652. DB::table($table)->insert($dataArray);
  1653. // 更新 lastId 继续下一批
  1654. $lastId = end($dataArray)['id_detail'] ?? $lastId;
  1655. } while (count($rows) === $limit);
  1656. }catch (\Throwable $exception){
  1657. return [false, "其他出库同步异常" . $exception->getMessage() . "|" . $exception->getLine() . "|" . $exception->getFile()];
  1658. }
  1659. return [true, ''];
  1660. }
  1661. private function saveResultold($data, $user){
  1662. // 初始化汇总数组------报表一
  1663. $paymentSummary = [];
  1664. $costSummary = [];
  1665. $costSummary2 = [];
  1666. //报表二
  1667. $paymentSummary_road = [];
  1668. $costSummary_road = [];
  1669. $costSummary2_road = [];
  1670. $map = [
  1671. 2 => [
  1672. 'type' => 1,
  1673. 'channel_details' => ['通路'],
  1674. ],
  1675. 3 => [
  1676. 'type' => 2,
  1677. 'channel_details' => ['通路'],
  1678. ],
  1679. 23 => [
  1680. 'type' => 3,
  1681. 'channel_details' => ['通路'],
  1682. ],
  1683. 7 => [
  1684. 'type' => 4,
  1685. 'channel_details' => ['通路','大卖场'],
  1686. ],
  1687. 8 => [
  1688. 'type' => 4,
  1689. 'channel_details' => ['通路','大卖场'],
  1690. ],
  1691. 48 => [
  1692. 'type' => 4,
  1693. 'channel_details' => ['通路','大卖场'],
  1694. ],
  1695. ];
  1696. try{
  1697. $limit = 500;
  1698. $lastId = 0;
  1699. do {
  1700. // 分批查询:只查 is_kh 不为空的数据
  1701. $rows = DB::table('tmp_item_road')
  1702. ->where('id', '>', $lastId)
  1703. ->orderBy('id')
  1704. ->limit($limit)
  1705. ->select([
  1706. 'id',
  1707. 'order_time',
  1708. 'channel_details',
  1709. 'payment_amount',
  1710. 'price_4_total',
  1711. 'is_kh',
  1712. 'employee_id_2'
  1713. ])
  1714. ->get();
  1715. if ($rows->isEmpty()) {
  1716. break;
  1717. }
  1718. // 聚合到汇总数组
  1719. foreach ($rows as $row) {
  1720. $order_time = $row->order_time;
  1721. $month = strtotime(date("Y-m-01", $order_time));
  1722. $channel = $row->channel_details ?? '';
  1723. $t = $map[$row->employee_id_2] ?? [];
  1724. //收款销售收入
  1725. if (! $row->is_kh) {
  1726. if (!isset($paymentSummary[$month][$channel])) {
  1727. $paymentSummary[$month][$channel] = $row->payment_amount;
  1728. }else{
  1729. $paymentSummary[$month][$channel] = bcadd(
  1730. $paymentSummary[$month][$channel],
  1731. $row->payment_amount,
  1732. 3
  1733. );
  1734. }
  1735. if(! empty($t)){
  1736. $type = $t['type'];
  1737. $c_t = $t['channel_details'];
  1738. if(in_array($channel, $c_t)){
  1739. if (!isset($paymentSummary_road[$month][$type])) {
  1740. $paymentSummary_road[$month][$type] = $row->payment_amount;
  1741. }else{
  1742. $paymentSummary_road[$month][$type] = bcadd(
  1743. $paymentSummary_road[$month][$type],
  1744. $row->payment_amount,
  1745. 3
  1746. );
  1747. }
  1748. }
  1749. }
  1750. }
  1751. //成本
  1752. if (!isset($costSummary[$month][$channel])) {
  1753. $costSummary[$month][$channel] = $row->price_4_total;
  1754. }else{
  1755. $costSummary[$month][$channel] = bcadd(
  1756. $costSummary[$month][$channel],
  1757. $row->price_4_total,
  1758. 3
  1759. );
  1760. }
  1761. if(! empty($t)){
  1762. $type = $t['type'];
  1763. $c_t = $t['channel_details'];
  1764. if(in_array($channel, $c_t)){
  1765. if (!isset($costSummary_road[$month][$type])) {
  1766. $costSummary_road[$month][$type] = $row->price_4_total;
  1767. }else{
  1768. $costSummary_road[$month][$type] = bcadd(
  1769. $costSummary_road[$month][$type],
  1770. $row->price_4_total,
  1771. 3
  1772. );
  1773. }
  1774. }
  1775. }
  1776. }
  1777. // 更新 lastId
  1778. $lastId = $rows->last()->id;
  1779. } while ($rows->count() === $limit);
  1780. $limit = 500;
  1781. $lastId = 0;
  1782. do {
  1783. $rows = DB::table('tmp_item_cost')
  1784. ->where('id', '>', $lastId)
  1785. ->orderBy('id')
  1786. ->limit($limit)
  1787. ->select([
  1788. 'id',
  1789. 'order_time',
  1790. 'channel_details',
  1791. 'ck_type',
  1792. 'fy_code',
  1793. 'taxamount',
  1794. 'employee_id_1'
  1795. ])
  1796. ->get();
  1797. if ($rows->isEmpty()) {
  1798. break;
  1799. }
  1800. foreach ($rows as $row) {
  1801. $order_time = $row->order_time;
  1802. $month = strtotime(date("Y-m-01", $order_time));
  1803. $channel = $row->channel_details ?? '';
  1804. $amount = $row->taxamount;
  1805. $t = $map[$row->employee_id_1] ?? [];
  1806. if($row->fy_code == 7004){
  1807. if (! isset($costSummary2[$month][$channel]['settle_amount'])) {
  1808. $costSummary2[$month][$channel]['settle_amount'] = $amount;
  1809. }else{
  1810. $costSummary2[$month][$channel]['settle_amount'] = bcadd(
  1811. $costSummary2[$month][$channel]['settle_amount'],
  1812. $amount,
  1813. 3
  1814. );
  1815. }
  1816. if(! empty($t)){
  1817. $type = $t['type'];
  1818. $c_t = $t['channel_details'];
  1819. if(in_array($channel, $c_t)){
  1820. if (!isset($costSummary2_road[$month][$type])) {
  1821. $costSummary2_road[$month][$type]['settle_amount'] = $amount;
  1822. }else{
  1823. $costSummary2_road[$month][$type]['settle_amount'] = bcadd(
  1824. $costSummary2_road[$month][$type]['settle_amount'],
  1825. $amount,
  1826. 3
  1827. );
  1828. }
  1829. }
  1830. }
  1831. }
  1832. $gl_amount = bcmul($amount, 0.05,3);
  1833. if (! isset($costSummary2[$month][$channel]['gl_amount'])) {
  1834. $costSummary2[$month][$channel]['gl_amount'] = $gl_amount;
  1835. }else{
  1836. $costSummary2[$month][$channel]['gl_amount'] = bcadd(
  1837. $costSummary2[$month][$channel]['gl_amount'],
  1838. $gl_amount,
  1839. 3
  1840. );
  1841. }
  1842. if(! empty($t)){
  1843. $type = $t['type'];
  1844. $c_t = $t['channel_details'];
  1845. if(in_array($channel, $c_t)){
  1846. if (!isset($costSummary2_road[$month][$type]['gl_amount'])) {
  1847. $costSummary2_road[$month][$type]['gl_amount'] = $amount;
  1848. }else{
  1849. $costSummary2_road[$month][$type]['gl_amount'] = bcadd(
  1850. $costSummary2_road[$month][$type]['gl_amount'],
  1851. $amount,
  1852. 3
  1853. );
  1854. }
  1855. }
  1856. }
  1857. $wl_amount = bcmul($amount, 2.3,3);
  1858. if (! isset($costSummary2[$month][$channel]['wl_amount'])) {
  1859. $costSummary2[$month][$channel]['wl_amount'] = $wl_amount;
  1860. }else{
  1861. $costSummary2[$month][$channel]['wl_amount'] = bcadd(
  1862. $costSummary2[$month][$channel]['wl_amount'],
  1863. $wl_amount,
  1864. 3
  1865. );
  1866. }
  1867. if(! empty($t)){
  1868. $type = $t['type'];
  1869. $c_t = $t['channel_details'];
  1870. if(in_array($channel, $c_t)){
  1871. if (!isset($costSummary2_road[$month][$type]['wl_amount'])) {
  1872. $costSummary2_road[$month][$type]['wl_amount'] = $amount;
  1873. }else{
  1874. $costSummary2_road[$month][$type]['wl_amount'] = bcadd(
  1875. $costSummary2_road[$month][$type]['wl_amount'],
  1876. $amount,
  1877. 3
  1878. );
  1879. }
  1880. }
  1881. }
  1882. if($row->fy_code == 7005){
  1883. if (! isset($costSummary2[$month][$channel]['ht_amount'])) {
  1884. $costSummary2[$month][$channel]['ht_amount'] = $amount;
  1885. }else{
  1886. $costSummary2[$month][$channel]['ht_amount'] = bcadd(
  1887. $costSummary2[$month][$channel]['ht_amount'],
  1888. $amount,
  1889. 3
  1890. );
  1891. }
  1892. if(! empty($t)){
  1893. $type = $t['type'];
  1894. $c_t = $t['channel_details'];
  1895. if(in_array($channel, $c_t)){
  1896. if (!isset($costSummary2_road[$month][$type]['ht_amount'])) {
  1897. $costSummary2_road[$month][$type]['ht_amount'] = $amount;
  1898. }else{
  1899. $costSummary2_road[$month][$type]['ht_amount'] = bcadd(
  1900. $costSummary2_road[$month][$type]['ht_amount'],
  1901. $amount,
  1902. 3
  1903. );
  1904. }
  1905. }
  1906. }
  1907. }
  1908. if($row->fy_code == 7006){
  1909. if (! isset($costSummary2[$month][$channel]['zk_amount'])) {
  1910. $costSummary2[$month][$channel]['zk_amount'] = $amount;
  1911. }else{
  1912. $costSummary2[$month][$channel]['zk_amount'] = bcadd(
  1913. $costSummary2[$month][$channel]['zk_amount'],
  1914. $amount,
  1915. 3
  1916. );
  1917. }
  1918. if(! empty($t)){
  1919. $type = $t['type'];
  1920. $c_t = $t['channel_details'];
  1921. if(in_array($channel, $c_t)){
  1922. if (!isset($costSummary2_road[$month][$type]['zk_amount'])) {
  1923. $costSummary2_road[$month][$type]['zk_amount'] = $amount;
  1924. }else{
  1925. $costSummary2_road[$month][$type]['zk_amount'] = bcadd(
  1926. $costSummary2_road[$month][$type]['zk_amount'],
  1927. $amount,
  1928. 3
  1929. );
  1930. }
  1931. }
  1932. }
  1933. }
  1934. if($row->fy_code == 7007){
  1935. if (! isset($costSummary2[$month][$channel]['cx_amount'])) {
  1936. $costSummary2[$month][$channel]['cx_amount'] = $amount;
  1937. }else{
  1938. $costSummary2[$month][$channel]['cx_amount'] = bcadd(
  1939. $costSummary2[$month][$channel]['cx_amount'],
  1940. $amount,
  1941. 3
  1942. );
  1943. }
  1944. if(! empty($t)){
  1945. $type = $t['type'];
  1946. $c_t = $t['channel_details'];
  1947. if(in_array($channel, $c_t)){
  1948. if (!isset($costSummary2_road[$month][$type]['cx_amount'])) {
  1949. $costSummary2_road[$month][$type]['cx_amount'] = $amount;
  1950. }else{
  1951. $costSummary2_road[$month][$type]['cx_amount'] = bcadd(
  1952. $costSummary2_road[$month][$type]['cx_amount'],
  1953. $amount,
  1954. 3
  1955. );
  1956. }
  1957. }
  1958. }
  1959. }
  1960. if($row->fy_code == 7013){
  1961. if (! isset($costSummary2[$month][$channel]['tg_amount'])) {
  1962. $costSummary2[$month][$channel]['tg_amount'] = $amount;
  1963. }else{
  1964. $costSummary2[$month][$channel]['tg_amount'] = bcadd(
  1965. $costSummary2[$month][$channel]['tg_amount'],
  1966. $amount,
  1967. 3
  1968. );
  1969. }
  1970. if(! empty($t)){
  1971. $type = $t['type'];
  1972. $c_t = $t['channel_details'];
  1973. if(in_array($channel, $c_t)){
  1974. if (!isset($costSummary2_road[$month][$type]['tg_amount'])) {
  1975. $costSummary2_road[$month][$type]['tg_amount'] = $amount;
  1976. }else{
  1977. $costSummary2_road[$month][$type]['tg_amount'] = bcadd(
  1978. $costSummary2_road[$month][$type]['tg_amount'],
  1979. $amount,
  1980. 3
  1981. );
  1982. }
  1983. }
  1984. }
  1985. }
  1986. if($row->fy_code == 7012){
  1987. if (! isset($costSummary2[$month][$channel]['cl_amount'])) {
  1988. $costSummary2[$month][$channel]['cl_amount'] = $amount;
  1989. }else{
  1990. $costSummary2[$month][$channel]['cl_amount'] = bcadd(
  1991. $costSummary2[$month][$channel]['cl_amount'],
  1992. $amount,
  1993. 3
  1994. );
  1995. }
  1996. if(! empty($t)){
  1997. $type = $t['type'];
  1998. $c_t = $t['channel_details'];
  1999. if(in_array($channel, $c_t)){
  2000. if (!isset($costSummary2_road[$month][$type]['cl_amount'])) {
  2001. $costSummary2_road[$month][$type]['cl_amount'] = $amount;
  2002. }else{
  2003. $costSummary2_road[$month][$type]['cl_amount'] = bcadd(
  2004. $costSummary2_road[$month][$type]['cl_amount'],
  2005. $amount,
  2006. 3
  2007. );
  2008. }
  2009. }
  2010. }
  2011. }
  2012. //20049 客情出库 60 赠品出库 20048 员工福利
  2013. if($row->fy_code == 7008 || $row->ck_type == 20049){
  2014. if (! isset($costSummary2[$month][$channel]['kq_amount'])) {
  2015. $costSummary2[$month][$channel]['kq_amount'] = $amount;
  2016. }else{
  2017. $costSummary2[$month][$channel]['kq_amount'] = bcadd(
  2018. $costSummary2[$month][$channel]['kq_amount'],
  2019. $amount,
  2020. 3
  2021. );
  2022. }
  2023. if(! empty($t)){
  2024. $type = $t['type'];
  2025. $c_t = $t['channel_details'];
  2026. if(in_array($channel, $c_t)){
  2027. if (!isset($costSummary2_road[$month][$type]['kq_amount'])) {
  2028. $costSummary2_road[$month][$type]['kq_amount'] = $amount;
  2029. }else{
  2030. $costSummary2_road[$month][$type]['kq_amount'] = bcadd(
  2031. $costSummary2_road[$month][$type]['kq_amount'],
  2032. $amount,
  2033. 3
  2034. );
  2035. }
  2036. }
  2037. }
  2038. }
  2039. if($row->fy_code == 7009 || $row->ck_type == 60){
  2040. if (! isset($costSummary2[$month][$channel]['zp_amount'])) {
  2041. $costSummary2[$month][$channel]['zp_amount'] = $amount;
  2042. }else{
  2043. $costSummary2[$month][$channel]['zp_amount'] = bcadd(
  2044. $costSummary2[$month][$channel]['zp_amount'],
  2045. $amount,
  2046. 3
  2047. );
  2048. }
  2049. if(! empty($t)){
  2050. $type = $t['type'];
  2051. $c_t = $t['channel_details'];
  2052. if(in_array($channel, $c_t)){
  2053. if (!isset($costSummary2_road[$month][$type]['zp_amount'])) {
  2054. $costSummary2_road[$month][$type]['zp_amount'] = $amount;
  2055. }else{
  2056. $costSummary2_road[$month][$type]['zp_amount'] = bcadd(
  2057. $costSummary2_road[$month][$type]['zp_amount'],
  2058. $amount,
  2059. 3
  2060. );
  2061. }
  2062. }
  2063. }
  2064. }
  2065. if($row->fy_code == 7010){
  2066. if (! isset($costSummary2[$month][$channel]['gg_amount'])) {
  2067. $costSummary2[$month][$channel]['gg_amount'] = $amount;
  2068. }else{
  2069. $costSummary2[$month][$channel]['gg_amount'] = bcadd(
  2070. $costSummary2[$month][$channel]['gg_amount'],
  2071. $amount,
  2072. 3
  2073. );
  2074. }
  2075. if(! empty($t)){
  2076. $type = $t['type'];
  2077. $c_t = $t['channel_details'];
  2078. if(in_array($channel, $c_t)){
  2079. if (!isset($costSummary2_road[$month][$type]['gg_amount'])) {
  2080. $costSummary2_road[$month][$type]['gg_amount'] = $amount;
  2081. }else{
  2082. $costSummary2_road[$month][$type]['gg_amount'] = bcadd(
  2083. $costSummary2_road[$month][$type]['gg_amount'],
  2084. $amount,
  2085. 3
  2086. );
  2087. }
  2088. }
  2089. }
  2090. }
  2091. if($row->fy_code == 7011){
  2092. if (! isset($costSummary2[$month][$channel]['kd_amount'])) {
  2093. $costSummary2[$month][$channel]['kd_amount'] = $amount;
  2094. }else{
  2095. $costSummary2[$month][$channel]['kd_amount'] = bcadd(
  2096. $costSummary2[$month][$channel]['kd_amount'],
  2097. $amount,
  2098. 3
  2099. );
  2100. }
  2101. if(! empty($t)){
  2102. $type = $t['type'];
  2103. $c_t = $t['channel_details'];
  2104. if(in_array($channel, $c_t)){
  2105. if (!isset($costSummary2_road[$month][$type]['kd_amount'])) {
  2106. $costSummary2_road[$month][$type]['kd_amount'] = $amount;
  2107. }else{
  2108. $costSummary2_road[$month][$type]['kd_amount'] = bcadd(
  2109. $costSummary2_road[$month][$type]['kd_amount'],
  2110. $amount,
  2111. 3
  2112. );
  2113. }
  2114. }
  2115. }
  2116. }
  2117. if($row->fy_code == 7001){
  2118. if (! isset($costSummary2[$month][$channel]['xsqt_amount'])) {
  2119. $costSummary2[$month][$channel]['xsqt_amount'] = $amount;
  2120. }else{
  2121. $costSummary2[$month][$channel]['xsqt_amount'] = bcadd(
  2122. $costSummary2[$month][$channel]['xsqt_amount'],
  2123. $amount,
  2124. 3
  2125. );
  2126. }
  2127. if(! empty($t)){
  2128. $type = $t['type'];
  2129. $c_t = $t['channel_details'];
  2130. if(in_array($channel, $c_t)){
  2131. if (!isset($costSummary2_road[$month][$type]['xsqt_amount'])) {
  2132. $costSummary2_road[$month][$type]['xsqt_amount'] = $amount;
  2133. }else{
  2134. $costSummary2_road[$month][$type]['xsqt_amount'] = bcadd(
  2135. $costSummary2_road[$month][$type]['xsqt_amount'],
  2136. $amount,
  2137. 3
  2138. );
  2139. }
  2140. }
  2141. }
  2142. }
  2143. if($row->fy_code == 7003){
  2144. if (! isset($costSummary2[$month][$channel]['ry_amount'])) {
  2145. $costSummary2[$month][$channel]['ry_amount'] = $amount;
  2146. }else{
  2147. $costSummary2[$month][$channel]['ry_amount'] = bcadd(
  2148. $costSummary2[$month][$channel]['ry_amount'],
  2149. $amount,
  2150. 3
  2151. );
  2152. }
  2153. if(! empty($t)){
  2154. $type = $t['type'];
  2155. $c_t = $t['channel_details'];
  2156. if(in_array($channel, $c_t)){
  2157. if (!isset($costSummary2_road[$month][$type]['ry_amount'])) {
  2158. $costSummary2_road[$month][$type]['ry_amount'] = $amount;
  2159. }else{
  2160. $costSummary2_road[$month][$type]['ry_amount'] = bcadd(
  2161. $costSummary2_road[$month][$type]['ry_amount'],
  2162. $amount,
  2163. 3
  2164. );
  2165. }
  2166. }
  2167. }
  2168. }
  2169. if($row->fy_code == 7019 || $row->ck_type == 20048){
  2170. if (! isset($costSummary2[$month][$channel]['sb_amount'])) {
  2171. $costSummary2[$month][$channel]['sb_amount'] = $amount;
  2172. }else{
  2173. $costSummary2[$month][$channel]['sb_amount'] = bcadd(
  2174. $costSummary2[$month][$channel]['sb_amount'],
  2175. $amount,
  2176. 3
  2177. );
  2178. }
  2179. if(! empty($t)){
  2180. $type = $t['type'];
  2181. $c_t = $t['channel_details'];
  2182. if(in_array($channel, $c_t)){
  2183. if (!isset($costSummary2_road[$month][$type]['sb_amount'])) {
  2184. $costSummary2_road[$month][$type]['sb_amount'] = $amount;
  2185. }else{
  2186. $costSummary2_road[$month][$type]['sb_amount'] = bcadd(
  2187. $costSummary2_road[$month][$type]['sb_amount'],
  2188. $amount,
  2189. 3
  2190. );
  2191. }
  2192. }
  2193. }
  2194. }
  2195. $sj_amount = bcmul($amount,0.01,3);
  2196. if (! isset($costSummary2[$month][$channel]['sj_amount'])) {
  2197. $costSummary2[$month][$channel]['sj_amount'] = $sj_amount;
  2198. }else{
  2199. $costSummary2[$month][$channel]['sj_amount'] = bcadd(
  2200. $costSummary2[$month][$channel]['sj_amount'],
  2201. $sj_amount,
  2202. 3
  2203. );
  2204. }
  2205. if(! empty($t)){
  2206. $type = $t['type'];
  2207. $c_t = $t['channel_details'];
  2208. if(in_array($channel, $c_t)){
  2209. if (!isset($costSummary2_road[$month][$type]['sj_amount'])) {
  2210. $costSummary2_road[$month][$type]['sj_amount'] = $amount;
  2211. }else{
  2212. $costSummary2_road[$month][$type]['sj_amount'] = bcadd(
  2213. $costSummary2_road[$month][$type]['sj_amount'],
  2214. $amount,
  2215. 3
  2216. );
  2217. }
  2218. }
  2219. }
  2220. }
  2221. // 更新 lastId
  2222. $lastId = $rows->last()->id;
  2223. } while ($rows->count() === $limit);
  2224. }catch (\Throwable $exception){
  2225. return [false, "初步汇总异常" . $exception->getMessage() . "|" . $exception->getLine() . "|" . $exception->getFile()];
  2226. }
  2227. try {
  2228. $start_timeStamp = $data['start_timeStamp'];
  2229. $end_timeStamp = $data['end_timeStamp'];
  2230. $result = $this->sumRes($paymentSummary,$costSummary,$costSummary2);
  2231. $result2 = $this->sumRes2($paymentSummary_road, $costSummary_road, $costSummary2_road);
  2232. DB::transaction(function () use ($start_timeStamp, $end_timeStamp, $result, $result2) {
  2233. // 1. 先删除旧数据
  2234. ItemReport::where('time', '>=', $start_timeStamp)
  2235. ->where('time', '<=', $end_timeStamp)
  2236. ->delete();
  2237. ItemReportRoad::where('time', '>=', $start_timeStamp)
  2238. ->where('time', '<=', $end_timeStamp)
  2239. ->delete();
  2240. // 2. 插入新数据
  2241. ItemReport::insert($result);
  2242. ItemReportRoad::insert($result2);
  2243. });
  2244. }catch (\Throwable $exception){
  2245. return [false, "结果异常" . $exception->getMessage() . "|" . $exception->getLine() . "|" . $exception->getFile()];
  2246. }
  2247. return [true, ''];
  2248. }
  2249. private function saveResult($data, $user){
  2250. // 初始化汇总数组------报表一
  2251. $paymentSummary = [];
  2252. //回款里的原商品调整99001+经销补差99002+返利99003+串码误差调整99004+运费99005+货款预收99006,渠道明细大卖场
  2253. $product_map = [
  2254. '99001' => 0,
  2255. '99002' => 0,
  2256. '99003' => 0,
  2257. '99004' => 0,
  2258. '99005' => 0,
  2259. '99006' => 0,
  2260. ];
  2261. // 初始化汇总数组------报表二 (业务员报表)
  2262. $manSummary = [];
  2263. try{
  2264. $limit = 500;
  2265. $lastId = 0;
  2266. do {
  2267. //收入
  2268. $rows = DB::table('tmp_item_road')
  2269. ->where('id', '>', $lastId)
  2270. ->orderBy('id')
  2271. ->limit($limit)
  2272. ->select([
  2273. 'id',
  2274. 'order_time',
  2275. 'channel_details',
  2276. 'channel_finance',
  2277. 'payment_amount',
  2278. 'price_4_total',
  2279. 'price_1_total',
  2280. 'product_code',
  2281. 'is_kh',
  2282. 'employee_id_1',
  2283. 'employee_id_1_title',
  2284. 'employee_id_2'
  2285. ])
  2286. ->get();
  2287. if ($rows->isEmpty()) {
  2288. break;
  2289. }
  2290. foreach ($rows as $row) {
  2291. $order_time = $row->order_time;
  2292. $month = strtotime(date("Y-m-01", $order_time));
  2293. $channel = $row->channel_details ?? '';
  2294. $finance = $row->channel_finance ?? '';
  2295. $empId = $row->employee_id_1 ?? 0;
  2296. $empName = $row->employee_id_1_title ?? '';
  2297. // --- 报表一逻辑 ---
  2298. $key_1 = "{$month}_{$channel}";
  2299. if (!isset($paymentSummary[$key_1])) {
  2300. $paymentSummary[$key_1] = [
  2301. 'time' => $month,
  2302. 'channel_details' => $channel,
  2303. 'receipt_amount' => 0,
  2304. 'receipt_not_amount' => 0,
  2305. 'pk_amount' => 0,
  2306. 'cost' => 0,
  2307. 'profit' => 0,
  2308. 'profit_not' => 0,
  2309. 'settle_amount' => 0,
  2310. 'gl_amount' => 0,
  2311. 'gl_not_amount' => 0,
  2312. 'wl_amount' => 0,
  2313. 'wl_not_amount' => 0,
  2314. 'ht_amount' => 0,
  2315. 'zk_amount' => 0,
  2316. 'cx_amount' => 0,
  2317. 'tg_amount' => 0,
  2318. 'cl_amount' => 0,
  2319. 'kq_amount' => 0,
  2320. 'zp_amount' => 0,
  2321. 'gg_amount' => 0,
  2322. 'kd_amount' => 0,
  2323. 'xsqt_amount' => 0,
  2324. 'ry_amount' => 0,
  2325. 'sb_amount' => 0,
  2326. 'sj_amount' => 0,
  2327. 'sj_not_amount' => 0,
  2328. 'sx_amount' => 0,
  2329. 'sx_not_amount' => 0,
  2330. 'cg_amount' => 0,
  2331. 'other_ck_amount' => 0,
  2332. ];
  2333. }
  2334. // 收款总额 (所有)
  2335. $paymentSummary[$key_1]['receipt_amount'] = bcadd($paymentSummary[$key_1]['receipt_amount'], $row->payment_amount, 3);
  2336. // 收款 (不含不计考勤 is_kh == 0)
  2337. if (!$row->is_kh) {
  2338. $paymentSummary[$key_1]['receipt_not_amount'] = bcadd($paymentSummary[$key_1]['receipt_not_amount'], $row->payment_amount, 3);
  2339. }
  2340. //票扣费用
  2341. if($row->product_code && isset($product_map[$row->product_code])) {
  2342. $paymentSummary[$key_1]['pk_amount'] = bcadd($paymentSummary[$key_1]['pk_amount'], $row->price_1_total, 3);
  2343. }
  2344. // 业务成本
  2345. $paymentSummary[$key_1]['cost'] = bcadd($paymentSummary[$key_1]['cost'], $row->price_4_total, 3);
  2346. // --- 新报表二逻辑 (业务员维度) ---
  2347. $key = "{$month}_{$finance}_{$empId}";
  2348. if (!isset($manSummary[$key])) {
  2349. $manSummary[$key] = [
  2350. 'time' => $month,
  2351. 'channel_finance' => $finance,
  2352. 'employee_id_1' => $empId,
  2353. 'employee_id_1_title' => $empName,
  2354. 'receipt_amount' => 0,
  2355. 'receipt_not_amount' => 0,
  2356. 'cost' => 0,
  2357. 'profit' => 0,
  2358. 'profit_not' => 0,
  2359. 'settle_amount' => 0,
  2360. 'gl_amount' => 0,
  2361. 'gl_not_amount' => 0,
  2362. 'wl_amount' => 0,
  2363. 'wl_not_amount' => 0,
  2364. 'ht_amount' => 0,
  2365. 'zk_amount' => 0,
  2366. 'cx_amount' => 0,
  2367. 'tg_amount' => 0,
  2368. 'cl_amount' => 0,
  2369. 'kq_amount' => 0,
  2370. 'zp_amount' => 0,
  2371. 'gg_amount' => 0,
  2372. 'kd_amount' => 0,
  2373. 'xsqt_amount' => 0,
  2374. 'ry_amount' => 0,
  2375. 'sb_amount' => 0,
  2376. 'sj_amount' => 0,
  2377. 'sj_not_amount' => 0,
  2378. 'sx_amount' => 0,
  2379. 'sx_not_amount' => 0,
  2380. 'cg_amount' => 0,
  2381. 'other_ck_amount' => 0,
  2382. ];
  2383. }
  2384. // 收款总额 (所有)
  2385. $manSummary[$key]['receipt_amount'] = bcadd($manSummary[$key]['receipt_amount'], $row->payment_amount, 3);
  2386. // 收款 (不含不计考勤 is_kh == 0)
  2387. if (!$row->is_kh) {
  2388. $manSummary[$key]['receipt_not_amount'] = bcadd($manSummary[$key]['receipt_not_amount'], $row->payment_amount, 3);
  2389. }
  2390. // 业务成本
  2391. $manSummary[$key]['cost'] = bcadd($manSummary[$key]['cost'], $row->price_4_total, 3);
  2392. }
  2393. $lastId = $rows->last()->id;
  2394. } while ($rows->count() === $limit);
  2395. $limit = 500;
  2396. $lastId = 0;
  2397. do {
  2398. //指出
  2399. $rows = DB::table('tmp_item_cost')
  2400. ->where('id', '>', $lastId)
  2401. ->orderBy('id')
  2402. ->limit($limit)
  2403. ->select([
  2404. 'id', 'order_time', 'channel_details', 'ck_type', 'fy_code', 'taxamount', 'employee_id_1', 'channel_finance', 'order_type' , 'employee_id_1_title'
  2405. ])
  2406. ->get();
  2407. if ($rows->isEmpty()) {
  2408. break;
  2409. }
  2410. foreach ($rows as $row) {
  2411. $order_time = $row->order_time;
  2412. $month = strtotime(date("Y-m-01", $order_time));
  2413. $channel = $row->channel_details ?? '';
  2414. $finance = $row->channel_finance ?? '';
  2415. $empId = $row->employee_id_1 ?? 0;
  2416. $empName = $row->employee_id_1_title ?? '';
  2417. $amount = $row->taxamount;
  2418. //表一-------------------------------------------------------
  2419. $key = "{$month}_{$channel}";
  2420. if (!isset($paymentSummary[$key])) {
  2421. $paymentSummary[$key] = [
  2422. 'time' => $month,
  2423. 'channel_details' => $channel,
  2424. 'receipt_amount' => 0,
  2425. 'receipt_not_amount' => 0,
  2426. 'pk_amount' => 0,
  2427. 'cost' => 0,
  2428. 'profit' => 0,
  2429. 'profit_not' => 0,
  2430. 'settle_amount' => 0,
  2431. 'gl_amount' => 0,
  2432. 'gl_not_amount' => 0,
  2433. 'wl_amount' => 0,
  2434. 'wl_not_amount' => 0,
  2435. 'ht_amount' => 0,
  2436. 'zk_amount' => 0,
  2437. 'cx_amount' => 0,
  2438. 'tg_amount' => 0,
  2439. 'cl_amount' => 0,
  2440. 'kq_amount' => 0,
  2441. 'zp_amount' => 0,
  2442. 'gg_amount' => 0,
  2443. 'kd_amount' => 0,
  2444. 'xsqt_amount' => 0,
  2445. 'ry_amount' => 0,
  2446. 'sb_amount' => 0,
  2447. 'sj_amount' => 0,
  2448. 'sj_not_amount' => 0,
  2449. 'sx_amount' => 0,
  2450. 'sx_not_amount' => 0,
  2451. 'cg_amount' => 0,
  2452. 'other_ck_amount' => 0,
  2453. ];
  2454. }
  2455. if ($row->order_type == 2) {
  2456. // 1. 判断是否为其他出库
  2457. $paymentSummary[$key]['other_ck_amount'] = bcadd($paymentSummary[$key]['other_ck_amount'] ?? 0, $amount, 3);
  2458. } else {
  2459. // 结算费用
  2460. if($row->fy_code == 7004) $paymentSummary[$key]['settle_amount'] = bcadd($paymentSummary[$key]['settle_amount'] ?? 0, $amount, 3);
  2461. if($row->fy_code == 7005) $paymentSummary[$key]['ht_amount'] = bcadd($paymentSummary[$key]['ht_amount'] ?? 0, $amount, 3);
  2462. if($row->fy_code == 7006) $paymentSummary[$key]['zk_amount'] = bcadd($paymentSummary[$key]['zk_amount'] ?? 0, $amount, 3);
  2463. if($row->fy_code == 7007) $paymentSummary[$key]['cx_amount'] = bcadd($paymentSummary[$key]['cx_amount'] ?? 0, $amount, 3);
  2464. if($row->fy_code == 7013) $paymentSummary[$key]['tg_amount'] = bcadd($paymentSummary[$key]['tg_amount'] ?? 0, $amount, 3);
  2465. if($row->fy_code == 7012) $paymentSummary[$key]['cl_amount'] = bcadd($paymentSummary[$key]['cl_amount'] ?? 0, $amount, 3);
  2466. if($row->fy_code == 7008) $paymentSummary[$key]['kq_amount'] = bcadd($paymentSummary[$key]['kq_amount'] ?? 0, $amount, 3);
  2467. if($row->fy_code == 7009) $paymentSummary[$key]['zp_amount'] = bcadd($paymentSummary[$key]['zp_amount'] ?? 0, $amount, 3);
  2468. if($row->fy_code == 7010) $paymentSummary[$key]['gg_amount'] = bcadd($paymentSummary[$key]['gg_amount'] ?? 0, $amount, 3);
  2469. if($row->fy_code == 7011) $paymentSummary[$key]['kd_amount'] = bcadd($paymentSummary[$key]['kd_amount'] ?? 0, $amount, 3);
  2470. if($row->fy_code == 7001) $paymentSummary[$key]['xsqt_amount'] = bcadd($paymentSummary[$key]['xsqt_amount'] ?? 0, $amount, 3);
  2471. if($row->fy_code == 7003) $paymentSummary[$key]['ry_amount'] = bcadd($paymentSummary[$key]['ry_amount'] ?? 0, $amount, 3);
  2472. if($row->fy_code == 7019) $paymentSummary[$key]['sb_amount'] = bcadd($paymentSummary[$key]['sb_amount'] ?? 0, $amount, 3);
  2473. if($row->fy_code == 7023) $paymentSummary[$key]['cg_amount'] = bcadd($paymentSummary[$key]['cg_amount'] ?? 0, $amount, 3);
  2474. }
  2475. // 表二----------------------------------------------------------------------
  2476. $key = "{$month}_{$finance}_{$empId}";
  2477. if (!isset($manSummary[$key])) {
  2478. $manSummary[$key] = [
  2479. 'time' => $month,
  2480. 'channel_finance' => $finance,
  2481. 'employee_id_1' => $empId,
  2482. 'employee_id_1_title' => $empName,
  2483. 'receipt_amount' => 0,
  2484. 'receipt_not_amount' => 0,
  2485. 'cost' => 0,
  2486. 'profit' => 0,
  2487. 'profit_not' => 0,
  2488. 'settle_amount' => 0,
  2489. 'gl_amount' => 0,
  2490. 'gl_not_amount' => 0,
  2491. 'wl_amount' => 0,
  2492. 'wl_not_amount' => 0,
  2493. 'ht_amount' => 0,
  2494. 'zk_amount' => 0,
  2495. 'cx_amount' => 0,
  2496. 'tg_amount' => 0,
  2497. 'cl_amount' => 0,
  2498. 'kq_amount' => 0,
  2499. 'zp_amount' => 0,
  2500. 'gg_amount' => 0,
  2501. 'kd_amount' => 0,
  2502. 'xsqt_amount' => 0,
  2503. 'ry_amount' => 0,
  2504. 'sb_amount' => 0,
  2505. 'sj_amount' => 0,
  2506. 'sj_not_amount' => 0,
  2507. 'sx_amount' => 0,
  2508. 'sx_not_amount' => 0,
  2509. 'cg_amount' => 0,
  2510. 'other_ck_amount' => 0,
  2511. ];
  2512. }
  2513. if ($row->order_type == 2) {
  2514. // 1. 判断是否为其他出库
  2515. $manSummary[$key]['other_ck_amount'] = bcadd($manSummary[$key]['other_ck_amount'] ?? 0, $amount, 3);
  2516. } else {
  2517. // 2. 正常费用代码归类
  2518. if($row->fy_code == 7004) $manSummary[$key]['settle_amount'] = bcadd($manSummary[$key]['settle_amount'] ?? 0, $amount, 3);
  2519. if($row->fy_code == 7005) $manSummary[$key]['ht_amount'] = bcadd($manSummary[$key]['ht_amount'] ?? 0, $amount, 3);
  2520. if($row->fy_code == 7006) $manSummary[$key]['zk_amount'] = bcadd($manSummary[$key]['zk_amount'] ?? 0, $amount, 3);
  2521. if($row->fy_code == 7007) $manSummary[$key]['cx_amount'] = bcadd($manSummary[$key]['cx_amount'] ?? 0, $amount, 3);
  2522. if($row->fy_code == 7013) $manSummary[$key]['tg_amount'] = bcadd($manSummary[$key]['tg_amount'] ?? 0, $amount, 3);
  2523. if($row->fy_code == 7012) $manSummary[$key]['cl_amount'] = bcadd($manSummary[$key]['cl_amount'] ?? 0, $amount, 3);
  2524. if($row->fy_code == 7008) $manSummary[$key]['kq_amount'] = bcadd($manSummary[$key]['kq_amount'] ?? 0, $amount, 3);
  2525. if($row->fy_code == 7009) $manSummary[$key]['zp_amount'] = bcadd($manSummary[$key]['zp_amount'] ?? 0, $amount, 3);
  2526. if($row->fy_code == 7010) $manSummary[$key]['gg_amount'] = bcadd($manSummary[$key]['gg_amount'] ?? 0, $amount, 3);
  2527. if($row->fy_code == 7011) $manSummary[$key]['kd_amount'] = bcadd($manSummary[$key]['kd_amount'] ?? 0, $amount, 3);
  2528. if($row->fy_code == 7001) $manSummary[$key]['xsqt_amount'] = bcadd($manSummary[$key]['xsqt_amount'] ?? 0, $amount, 3);
  2529. if($row->fy_code == 7003) $manSummary[$key]['ry_amount'] = bcadd($manSummary[$key]['ry_amount'] ?? 0, $amount, 3);
  2530. if($row->fy_code == 7019) $manSummary[$key]['sb_amount'] = bcadd($manSummary[$key]['sb_amount'] ?? 0, $amount, 3);
  2531. if($row->fy_code == 7023) $manSummary[$key]['cg_amount'] = bcadd($manSummary[$key]['cg_amount'] ?? 0, $amount, 3);
  2532. }
  2533. }
  2534. $lastId = $rows->last()->id;
  2535. } while ($rows->count() === $limit);
  2536. } catch (\Throwable $exception){
  2537. return [false, "初步汇总异常" . $exception->getMessage() . "|" . $exception->getLine()];
  2538. }
  2539. foreach ($paymentSummary as $key => $item) {
  2540. $r_amount = $item['receipt_amount'];
  2541. $r_not_amount = $item['receipt_not_amount'];
  2542. // 1. 计算总毛利:总收款 - 总成本 - 票扣费用
  2543. $tmp = bcsub(
  2544. $r_amount,
  2545. $item['cost'],
  2546. 3
  2547. );
  2548. $paymentSummary[$key]['profit'] = bcsub(
  2549. $tmp,
  2550. $item['pk_amount'],
  2551. 3
  2552. );
  2553. // 2. 计算不含不计考勤毛利:考核收款 - 总成本 - 票扣费用
  2554. $tmp = bcsub(
  2555. $r_not_amount,
  2556. $item['cost'],
  2557. 3
  2558. );
  2559. $paymentSummary[$key]['profit_not'] = bcsub(
  2560. $tmp,
  2561. $item['pk_amount'],
  2562. 3
  2563. );
  2564. // 2. 统一计算比例费用(此时 $r_amount 是汇总后的总额,只算一次,绝对准确)
  2565. $paymentSummary[$key]['gl_amount'] = bcmul($r_amount, 0.05, 3);
  2566. $paymentSummary[$key]['gl_not_amount'] = bcmul($r_not_amount, 0.05, 3);
  2567. $paymentSummary[$key]['wl_amount'] = bcmul($r_amount, 0.023, 3);
  2568. $paymentSummary[$key]['wl_not_amount'] = bcmul($r_not_amount, 0.023, 3);
  2569. $paymentSummary[$key]['sj_amount'] = bcmul($r_amount, 0.01, 3);
  2570. $paymentSummary[$key]['sj_not_amount'] = bcmul($r_not_amount, 0.01, 3);
  2571. $paymentSummary[$key]['sx_amount'] = bcmul($r_amount, 0.01, 3);
  2572. $paymentSummary[$key]['sx_not_amount'] = bcmul($r_not_amount, 0.01, 3);
  2573. }
  2574. foreach ($manSummary as $key => $item) {
  2575. $r_amount = $item['receipt_amount'];
  2576. $r_not_amount = $item['receipt_not_amount'];
  2577. // 1. 计算毛利
  2578. $manSummary[$key]['profit'] = bcsub($r_amount, $item['cost'], 3);
  2579. $manSummary[$key]['profit_not'] = bcsub($r_not_amount, $item['cost'], 3);
  2580. // 2. 统一计算比例费用(此时 $r_amount 是汇总后的总额,只算一次,绝对准确)
  2581. $manSummary[$key]['gl_amount'] = bcmul($r_amount, 0.05, 3);
  2582. $manSummary[$key]['gl_not_amount'] = bcmul($r_not_amount, 0.05, 3);
  2583. $manSummary[$key]['wl_amount'] = bcmul($r_amount, 0.023, 3);
  2584. $manSummary[$key]['wl_not_amount'] = bcmul($r_not_amount, 0.023, 3);
  2585. $manSummary[$key]['sj_amount'] = bcmul($r_amount, 0.01, 3);
  2586. $manSummary[$key]['sj_not_amount'] = bcmul($r_not_amount, 0.01, 3);
  2587. $manSummary[$key]['sx_amount'] = bcmul($r_amount, 0.01, 3);
  2588. $manSummary[$key]['sx_not_amount'] = bcmul($r_not_amount, 0.01, 3);
  2589. }
  2590. try {
  2591. $start_timeStamp = $data['start_timeStamp'];
  2592. $end_timeStamp = $data['end_timeStamp'];
  2593. $paymentSummary = array_values($paymentSummary);
  2594. $manSummary = array_values($manSummary);
  2595. DB::transaction(function () use ($start_timeStamp, $end_timeStamp, $paymentSummary, $manSummary) {
  2596. ItemReport::where('time', '>=', $start_timeStamp)
  2597. ->where('time', '<=', $end_timeStamp)
  2598. ->delete();
  2599. ItemReport::insert($paymentSummary);
  2600. ItemReportMan::where('time', '>=', $start_timeStamp)
  2601. ->where('time', '<=', $end_timeStamp)
  2602. ->delete();
  2603. ItemReportMan::insert($manSummary);
  2604. });
  2605. } catch (\Throwable $exception){
  2606. return [false, "结果异常" . $exception->getMessage() . "|" . $exception->getLine()];
  2607. }
  2608. return [true, ''];
  2609. }
  2610. private function sumRes($paymentSummary, $costSummary, $costSummary2){
  2611. // 合并三个汇总数组为最终结果
  2612. $result = [];
  2613. // 获取所有唯一的时间+渠道组合
  2614. $keys = [];
  2615. foreach (array_keys($paymentSummary) as $month) {
  2616. foreach (array_keys($paymentSummary[$month]) as $channel) {
  2617. $keys["$month|$channel"] = ['month' => $month, 'channel' => $channel];
  2618. }
  2619. }
  2620. foreach (array_keys($costSummary) as $month) {
  2621. foreach (array_keys($costSummary[$month]) as $channel) {
  2622. $keys["$month|$channel"] = ['month' => $month, 'channel' => $channel];
  2623. }
  2624. }
  2625. foreach (array_keys($costSummary2) as $month) {
  2626. foreach (array_keys($costSummary2[$month]) as $channel) {
  2627. $keys["$month|$channel"] = ['month' => $month, 'channel' => $channel];
  2628. }
  2629. }
  2630. // 遍历所有组合,构建最终数据
  2631. foreach ($keys as $key => $info) {
  2632. $month = $info['month'];
  2633. $channel = $info['channel'];
  2634. // 收款销售收入(注意:原逻辑中 is_kh == false 才计入)
  2635. $receipt_amount = isset($paymentSummary[$month][$channel])
  2636. ? $paymentSummary[$month][$channel]
  2637. : '0.000';
  2638. // 业务成本(来自 tmp_item_road 的 price_4_total)
  2639. $cost = isset($costSummary[$month][$channel])
  2640. ? $costSummary[$month][$channel]
  2641. : '0.000';
  2642. // 利润 = 收入 - 成本
  2643. $profit = bcsub($receipt_amount, $cost, 3);
  2644. // 从 costSummary2 提取各项费用(默认为 0.000)
  2645. $cs2 = $costSummary2[$month][$channel] ?? [];
  2646. $settle_amount = $cs2['settle_amount'] ?? '0.000';
  2647. $gl_amount = $cs2['gl_amount'] ?? '0.000';
  2648. $wl_amount = $cs2['wl_amount'] ?? '0.000';
  2649. $ht_amount = $cs2['ht_amount'] ?? '0.000';
  2650. $zk_amount = $cs2['zk_amount'] ?? '0.000';
  2651. $cx_amount = $cs2['cx_amount'] ?? '0.000';
  2652. $tg_amount = $cs2['tg_amount'] ?? '0.000';
  2653. $cl_amount = $cs2['cl_amount'] ?? '0.000';
  2654. $kq_amount = $cs2['kq_amount'] ?? '0.000';
  2655. $zp_amount = $cs2['zp_amount'] ?? '0.000';
  2656. $gg_amount = $cs2['gg_amount'] ?? '0.000';
  2657. $kd_amount = $cs2['kd_amount'] ?? '0.000';
  2658. $xsqt_amount = $cs2['xsqt_amount'] ?? '0.000';
  2659. $ry_amount = $cs2['ry_amount'] ?? '0.000';
  2660. $sb_amount = $cs2['sb_amount'] ?? '0.000';
  2661. $sj_amount = $cs2['sj_amount'] ?? '0.000';
  2662. $result[] = [
  2663. 'time' => $month,
  2664. 'channel_details'=> $channel,
  2665. 'receipt_amount' => $receipt_amount,
  2666. 'cost' => $cost,
  2667. 'profit' => $profit,
  2668. 'settle_amount' => $settle_amount,
  2669. 'gl_amount' => $gl_amount,
  2670. 'wl_amount' => $wl_amount,
  2671. 'ht_amount' => $ht_amount,
  2672. 'zk_amount' => $zk_amount,
  2673. 'cx_amount' => $cx_amount,
  2674. 'tg_amount' => $tg_amount,
  2675. 'cl_amount' => $cl_amount,
  2676. 'kq_amount' => $kq_amount,
  2677. 'zp_amount' => $zp_amount,
  2678. 'gg_amount' => $gg_amount,
  2679. 'kd_amount' => $kd_amount,
  2680. 'xsqt_amount' => $xsqt_amount,
  2681. 'ry_amount' => $ry_amount,
  2682. 'sb_amount' => $sb_amount,
  2683. 'sj_amount' => $sj_amount,
  2684. ];
  2685. }
  2686. return $result;
  2687. }
  2688. private function sumRes2($paymentSummary, $costSummary, $costSummary2){
  2689. // 合并三个汇总数组为最终结果
  2690. $result = [];
  2691. // 获取所有唯一的时间+渠道组合
  2692. $keys = [];
  2693. foreach (array_keys($paymentSummary) as $month) {
  2694. foreach (array_keys($paymentSummary[$month]) as $channel) {
  2695. $keys["$month|$channel"] = ['month' => $month, 'channel' => $channel];
  2696. }
  2697. }
  2698. foreach (array_keys($costSummary) as $month) {
  2699. foreach (array_keys($costSummary[$month]) as $channel) {
  2700. $keys["$month|$channel"] = ['month' => $month, 'channel' => $channel];
  2701. }
  2702. }
  2703. foreach (array_keys($costSummary2) as $month) {
  2704. foreach (array_keys($costSummary2[$month]) as $channel) {
  2705. $keys["$month|$channel"] = ['month' => $month, 'channel' => $channel];
  2706. }
  2707. }
  2708. // 遍历所有组合,构建最终数据
  2709. foreach ($keys as $key => $info) {
  2710. $month = $info['month'];
  2711. $channel = $info['channel'];
  2712. // 收款销售收入
  2713. $receipt_amount = isset($paymentSummary[$month][$channel])
  2714. ? $paymentSummary[$month][$channel]
  2715. : '0.000';
  2716. // 业务成本(来自 tmp_item_road 的 price_4_total)
  2717. $cost = isset($costSummary[$month][$channel])
  2718. ? $costSummary[$month][$channel]
  2719. : '0.000';
  2720. // 利润 = 收入 - 成本
  2721. $profit = bcsub($receipt_amount, $cost, 3);
  2722. // 从 costSummary2 提取各项费用(默认为 0.000)
  2723. $cs2 = $costSummary2[$month][$channel] ?? [];
  2724. $settle_amount = $cs2['settle_amount'] ?? '0.000';
  2725. $gl_amount = $cs2['gl_amount'] ?? '0.000';
  2726. $wl_amount = $cs2['wl_amount'] ?? '0.000';
  2727. $ht_amount = $cs2['ht_amount'] ?? '0.000';
  2728. $zk_amount = $cs2['zk_amount'] ?? '0.000';
  2729. $cx_amount = $cs2['cx_amount'] ?? '0.000';
  2730. $tg_amount = $cs2['tg_amount'] ?? '0.000';
  2731. $cl_amount = $cs2['cl_amount'] ?? '0.000';
  2732. $kq_amount = $cs2['kq_amount'] ?? '0.000';
  2733. $zp_amount = $cs2['zp_amount'] ?? '0.000';
  2734. $gg_amount = $cs2['gg_amount'] ?? '0.000';
  2735. $kd_amount = $cs2['kd_amount'] ?? '0.000';
  2736. $xsqt_amount = $cs2['xsqt_amount'] ?? '0.000';
  2737. $ry_amount = $cs2['ry_amount'] ?? '0.000';
  2738. $sb_amount = $cs2['sb_amount'] ?? '0.000';
  2739. $sj_amount = $cs2['sj_amount'] ?? '0.000';
  2740. $result[] = [
  2741. 'time' => $month,
  2742. 'receipt_amount' => $receipt_amount,
  2743. 'cost' => $cost,
  2744. 'profit' => $profit,
  2745. 'settle_amount' => $settle_amount,
  2746. 'gl_amount' => $gl_amount,
  2747. 'wl_amount' => $wl_amount,
  2748. 'ht_amount' => $ht_amount,
  2749. 'zk_amount' => $zk_amount,
  2750. 'cx_amount' => $cx_amount,
  2751. 'tg_amount' => $tg_amount,
  2752. 'cl_amount' => $cl_amount,
  2753. 'kq_amount' => $kq_amount,
  2754. 'zp_amount' => $zp_amount,
  2755. 'gg_amount' => $gg_amount,
  2756. 'kd_amount' => $kd_amount,
  2757. 'xsqt_amount' => $xsqt_amount,
  2758. 'ry_amount' => $ry_amount,
  2759. 'sb_amount' => $sb_amount,
  2760. 'sj_amount' => $sj_amount,
  2761. 'employee_title_type' => $channel
  2762. ];
  2763. }
  2764. return $result;
  2765. }
  2766. }