TestController.php 35 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803
  1. <?php
  2. namespace App\Http\Controllers;
  3. use App\Authority;
  4. use App\Commodity;
  5. use App\CommodityBarcode;
  6. use App\Customer;
  7. use App\Feature;
  8. use App\Log;
  9. use App\Logistic;
  10. use App\OracleActAllocationDetails;
  11. use App\OracleDOCOrderHeader;
  12. use App\OracleDocOrderPackingSummary;
  13. use App\OracleDOCWaveDetails;
  14. use App\Order;
  15. use App\OrderIssue;
  16. use App\OrderPackage;
  17. use App\Owner;
  18. use App\OwnerAreaReport;
  19. use App\Package;
  20. use App\Process;
  21. use App\ProcessDaily;
  22. use App\ProcessStatistic;
  23. use App\RejectedBill;
  24. use App\RejectedBillItem;
  25. use App\Services\CacheService;
  26. use App\Services\common\DataHandlerService;
  27. use App\Services\FeatureService;
  28. use App\Services\InventoryCompareService;
  29. use App\Services\OracleDOCOrderHeaderService;
  30. use App\Services\OrderPackageService;
  31. use App\Services\OrderService;
  32. use App\Services\OrderTrackingOwnerService;
  33. use App\Services\OrderTrackingService;
  34. use App\Services\OwnerPriceOperationService;
  35. use App\Unit;
  36. use App\User;
  37. use App\Warehouse;
  38. use Carbon\Carbon;
  39. use Illuminate\Database\Eloquent\Builder;
  40. use Illuminate\Support\Facades\Auth;
  41. use Illuminate\Support\Facades\Cache;
  42. use Illuminate\Http\Request;
  43. use Illuminate\Support\Facades\DB;
  44. use Illuminate\Support\Facades\Hash;
  45. use Illuminate\Support\Str;
  46. use Ramsey\Collection\Collection;
  47. use Ramsey\Uuid\Uuid;
  48. use Zttp\Zttp;
  49. class TestController extends Controller
  50. {
  51. const ASNREFERENCE_2 = 'ASNREFERENCE2';
  52. private $data = [];
  53. public function __construct()
  54. {
  55. $this->data["active_test"] = "active";
  56. }
  57. public function method(Request $request, $method)
  58. {
  59. return call_user_func([$this, $method], $request);
  60. }
  61. public function test4(){
  62. $a = new FeatureService();
  63. dd($a->matchFeature("1&2&3",[],[]));
  64. }
  65. public function test2(){
  66. $b = Logistic::query()->first();
  67. $a = OrderPackage::query()->with("order")->first();
  68. $a->bulk = 521;
  69. $a->save();
  70. if (!$a->order) $a->order = new Order();
  71. dd($a);
  72. if (!$a->order->logistic)$a->order->logistic = $b;
  73. dd($a->order->logistic);
  74. dd($a);
  75. $a->save();
  76. dd($a);
  77. }
  78. function packageFromLog(Request $request)
  79. { //x $packagesBatch=Package::where('batch_number',$batch_number)->first();
  80. ini_set('max_execution_time', 2500);
  81. ini_set('memory_limit', '1526M');
  82. $uploaded = 0;
  83. $count = DB::table('logs')->where('operation', 'like', "%PackageController::new_%")
  84. ->where('created_at', '>', "2020-06-08 15:46:00")
  85. ->where('created_at', '<', "2020-06-08 15:47:00")
  86. ->where('type', "request_new_")
  87. ->count();
  88. $requests = DB::table('logs')->where('operation', 'like', "%PackageController::new_%")
  89. ->where('created_at', '>', "2020-06-08 15:46:00")
  90. ->where('created_at', '<', "2020-06-08 15:47:00")
  91. ->where('type', "request_new_")
  92. ->get();
  93. $requests->each(function ($request) use (&$uploaded) {
  94. $requestJson = json_decode($request->description, true);
  95. $response = Zttp::withHeaders(['content-type' => 'application/json',
  96. ])->post('https://was.baoshi56.com/api/thirdPart/flux/package/new',
  97. $requestJson
  98. );
  99. if ($response->json() && $response->json()['response'] && $response->json()['response']['flag'] == 'Y')
  100. $uploaded += 1;
  101. });
  102. dd($uploaded . '/' . $count);
  103. }
  104. function wmsSql()
  105. {
  106. $owner=Owner::first();
  107. // $owner['phone_number'] ?? $owner['phone_number'] = '31115';
  108. // $owner->update();
  109. dd($owner);
  110. }
  111. function issues()
  112. {
  113. /** @var OrderPackageService $orderPackageService */
  114. $orderPackageService = app('OrderPackageService');
  115. $ids = [741, 739, 738, 736, 735, 733, 732, 731, 730, 729, 728, 725, 724, 723, 721, 720, 719, 718, 717, 715, 714, 713, 712, 711, 710, 705, 703, 702, 701, 700, 699, 698, 696, 694, 693, 692, 691, 690];
  116. $orderIssues = OrderIssue::query()->whereIn('id', $ids)->get();
  117. $order_ids = data_get($orderIssues, '*.order_id');
  118. $orders = Order::query()->whereIn('id', $order_ids)->get();
  119. foreach ($orders as $item) {
  120. $orderPackageService->createdByOrder($item);
  121. }
  122. }
  123. function t2(Request $request)
  124. { //x $packagesBatch=Package::where('batch_number',$batch_number)->first();
  125. $inventoryCompareService = new InventoryCompareService();
  126. echo ($inventoryCompareService)->getCreatingMissionCode('安桥主品');
  127. echo ($inventoryCompareService)->getCreatingMissionCode('安桥主品');
  128. echo ($inventoryCompareService)->getCreatingMissionCode('安桥主品');
  129. echo ($inventoryCompareService)->getCreatingMissionCode('安桥主品');
  130. }
  131. function tlog(Request $request)
  132. {
  133. app('LogService')->log(__METHOD__,'cczdelme'.__FUNCTION__,json_encode($request->all()),null);
  134. }
  135. function setCache(Request $request)
  136. {
  137. $today = now();
  138. Cache::put('storedTest', $today);
  139. return "cacheing:'$today'<script>localStorage.setItem('storedTest','{$today}')</script>";
  140. }
  141. function getCache(Request $request)
  142. {
  143. $cache = Cache::get('storedTest');
  144. return "cacheing get:'$cache'<script>document.write('<br>localStorage:'+localStorage.getItem('storedTest'))</script>";
  145. }
  146. function t1(Request $request)
  147. {
  148. {
  149. $username = config('database.connections.oracle.username');
  150. $password = config('database.connections.oracle.password');
  151. $host = config('database.connections.oracle.host');
  152. $service_name = config('database.connections.oracle.service_name');
  153. $conn = oci_connect($username, $password, $host . '/' . $service_name); //连接oracle数据库
  154. $IN_WarehouseID = '';
  155. $IN_TraceID = '';
  156. $IN_WavenNo = '';
  157. $IN_UserID = '';
  158. $IN_Language = '';
  159. $OUT_Return_Code = '';
  160. $sql_sp = "begin SPCUS_EDI_WCS001(:IN_WarehouseID,:IN_Process_Action_C,:IN_Process_By_C,
  161. :IN_WaveNO_C,:IN_OrderNO_C,:IN_OrderLineNO_C,:IN_AllocationDetailsID,:IN_Language,:IN_UserID,:OUT_Return_Code); end;";
  162. $stmt = oci_parse($conn, $sql_sp);
  163. oci_bind_by_name($stmt, ':IN_Warehouse', $IN_WarehouseID);
  164. oci_bind_by_name($stmt, ':IN_TraceID', $IN_TraceID);
  165. oci_bind_by_name($stmt, ':IN_WavenNo', $IN_WavenNo);
  166. oci_bind_by_name($stmt, ':IN_Language', $IN_Language);
  167. oci_bind_by_name($stmt, ':IN_UserID', $IN_UserID);
  168. oci_bind_by_name($stmt, ':OUT_Return_Code', $OUT_Return_Code);
  169. return oci_execute($stmt);
  170. }
  171. }
  172. function packageT(Request $request)
  173. {
  174. $package = Package::where('created_at', '<', '2020-07-08')->whereNotNull('logistic_number')->first();
  175. $package->fetchLogistic();
  176. }
  177. function injectJS(Request $request)
  178. {
  179. $items = RejectedBillItem::whereHas('rejectedBill', function ($query) {
  180. return $query->where('id_owner', 2);
  181. })->where('created_at', '>', '2019-12-23 18:11:00')->where('created_at', '<', '2019-12-24 11:25:00')->get();
  182. (new RejectedBillItemController())->collectionsToPackConfirm($items);
  183. }
  184. public function tj2(Request $request)
  185. {
  186. $numbersesOfBatch = OracleDOCWaveDetails::select('picktotraceid as logistic_number', 'act_allocation_details.orderno')->where('doc_wave_details.waveno', 'W190630000042')
  187. ->leftJoin('act_allocation_details', 'doc_wave_details.orderno', 'act_allocation_details.orderno')->get();
  188. $oneIdxAsrsReceive = OracleDocOrderPackingSummary::where('traceid', $numbersesOfBatch[0]['logistic_number'])->first();
  189. if (!$oneIdxAsrsReceive) {
  190. $inserts = '';
  191. $values = [];
  192. foreach ($numbersesOfBatch as $numbers) {
  193. $inserts .= " into doc_order_packing_summary (traceid,orderno,grossweight,addwho,addtime,editwho,edittime)values(?,?,?,?,?,?,?) ";
  194. $values[] = $numbers['logistic_number'] ?? '';
  195. $values[] = $numbers['orderno'] ?? '';
  196. $values[] = 12;
  197. $values[] = 'WAS';
  198. $values[] = Carbon::now();
  199. $values[] = 'WAS';
  200. $values[] = Carbon::now();
  201. }
  202. DB::connection('oracle')->insert("insert all {$inserts} select * from dual", $values);
  203. } else {
  204. $logisticNumbers = $numbersesOfBatch->map(function ($numbers) {
  205. return $numbers['logistic_number'];
  206. });
  207. OracleDocOrderPackingSummary::whereIn('traceid', $logisticNumbers)->update(['grossweight' => 32]);
  208. }
  209. }
  210. public function delme()
  211. {
  212. $fields = [
  213. 'doc_order_header.userdefine1',
  214. 'doc_order_header.userdefine2',
  215. 'doc_order_header.SOReference5',
  216. 'doc_order_header.waveno',
  217. 'doc_order_header.orderno',
  218. 'doc_order_header.customerid',
  219. 'doc_order_header.Consigneename'
  220. ];
  221. if ('') {
  222. $resultOracleObj = OracleDOCOrderHeader::select($fields)->where('orderno', 'SO200603004708');
  223. } else {
  224. $resultOracleObj = OracleActAllocationDetails::select($fields);
  225. $resultOracleObj->where('picktotraceid', '546152742096');
  226. $resultOracleObj->leftJoin('DOC_Order_Header', 'act_allocation_details.orderno', 'doc_order_header.orderno');
  227. }
  228. $_temOracleInfo = $resultOracleObj->first();
  229. dd($_temOracleInfo);
  230. }
  231. public function mergerPackageData()
  232. {
  233. ini_set('max_execution_time', 36000);
  234. ini_set('memory_limit', '1526M');
  235. $number = 3000;
  236. $start_at = 1;
  237. $sum = Package::query()->where('id', '>', $start_at)->count();
  238. $len = ceil($sum / $number);
  239. $id = $start_at;
  240. for ($i = 1; $i <= $len; $i++) {
  241. $packages = Package::query()->orderBy('id')->where('id', '>', $id)->limit($number)->get();
  242. $error = [];
  243. foreach ($packages as $package) {
  244. /** @var $service OrderPackageService */
  245. $service = app('OrderPackageService');
  246. $orderPackage = $service->firstOrCreate($package->logistic_number,
  247. ['batch_number' => $package->batch_number,
  248. 'batch_rule' => $package->batch_rule,
  249. 'bulk' => $package->bulk,
  250. 'weight' => $package->weight,
  251. 'length' => $package->length,
  252. 'width' => $package->width,
  253. 'height' => $package->height,
  254. 'paper_box_id' => $package->paper_box_id,
  255. 'measuring_machine_id' => $package->measuring_machine_id,
  256. 'weighed_at' => $package->weighed_at,
  257. 'status' => $package->status]);
  258. if (!$orderPackage) array_push($error, $package->id);
  259. }
  260. app('LogService')->log(__METHOD__, "同步时WMS中未找到这些订单", json_encode($error));
  261. $id = $packages[count($packages) - 1]->id;
  262. echo $number . ' a bunch done at:' . now()->toFormattedDateString() . '<br>';
  263. }
  264. }
  265. public function excelIt()
  266. {
  267. $excel = new ExcelController();
  268. return $excel->makeExcel();
  269. }
  270. public function featureIt()
  271. {
  272. LogisticNumberFeatureController::loadRecentRejectedsToFeatures(5, 2500);
  273. }
  274. public function newSku()
  275. {
  276. $url = 'http://bswcs/api/sorting/flux/newSku';
  277. $response = Zttp::post($url, [
  278. 'request' => [
  279. [
  280. "SKU" => "1234567890",
  281. "NAME" => "瑞士莲**巧克力",
  282. "Alternate_SKU1" => "1122334455",
  283. "GrossWeight" => "1.2",
  284. "Cube" => "0.75",
  285. "SKULength" => "0.25",
  286. "SKUWidth" => "0.15",
  287. "SKUHigh" => "0.05"
  288. ],
  289. [
  290. "SKU" => "1234567892",
  291. "NAME" => "跳跳饼",
  292. "Alternate_SKU1" => "",
  293. "GrossWeight" => "1.3",
  294. "Cube" => "0.75",
  295. "SKULength" => "0.25",
  296. "SKUWidth" => "0.15",
  297. "SKUHigh" => "0.25"
  298. ],
  299. ]
  300. ]);
  301. return $response->json();
  302. }
  303. public function changePackage()
  304. {
  305. $packages = Package::where('delivery_number', '<>', null)->where('logistic_id', null)->get();
  306. $packages = Package::whereRaw('delivery_number IS NOT NULL AND logistic_id IS NULL')->get();
  307. $logistics = Logistic::get();
  308. $packages->each(function ($package) use ($logistics) {
  309. $logistics->each(function ($logistic) use ($package) {
  310. if ($package->WMSReflectPackage->CarrierID == $logistic->code) {
  311. $package->logistic_id = $logistic->id;
  312. return;
  313. }
  314. });
  315. });
  316. return "OK";
  317. }
  318. public function tNull()
  319. {
  320. User::query()->get()->toArray();
  321. User::query()->get()->toJson();
  322. }
  323. public function deletePackageAuthority()
  324. {
  325. $authorities = Authority::where('name', 'like', '%包裹信息%')->get();
  326. $authorities->each(function ($authority) {
  327. $authority->delete();
  328. });
  329. }
  330. function test()
  331. {
  332. $ids = [];
  333. $logs = Log::query()->select('description')->where('type', '同步时WMS中未找到这些订单')->get();
  334. foreach ($logs as $log) {
  335. $arr = [];
  336. eval("\$arr = " . $log->description . '; ');
  337. if (count($arr) < 1) continue;
  338. $ids = array_merge($ids, $arr);
  339. }
  340. $ids = array_unique($ids);
  341. $error = [];
  342. foreach ($ids as $id) {
  343. $package = Package::query()->find($id);
  344. /** @var OrderPackageService */
  345. $orderPackage = app('OrderPackageService')->firstOrCreate($package->logistic_number,
  346. ['batch_number' => $package->batch_number,
  347. 'batch_rule' => $package->batch_rule,
  348. 'bulk' => $package->bulk,
  349. 'weight' => $package->weight,
  350. 'length' => $package->length,
  351. 'width' => $package->width,
  352. 'height' => $package->height,
  353. 'paper_box_id' => $package->paper_box_id,
  354. 'measuring_machine_id' => $package->measuring_machine_id,
  355. 'weighed_at' => $package->weighed_at,
  356. 'status' => $package->status]);
  357. if (!$orderPackage) array_push($error, $package->id);
  358. }
  359. if (count($error) > 0) app('LogService')->log(__METHOD__, "同步时WMS中未找到这些订单_two", json_encode($error));
  360. }
  361. function test1()
  362. {
  363. $statistics = ProcessStatistic::query()->whereNull('revenue')->get();
  364. $id = array_column($statistics->toArray(), 'process_id');
  365. $processes = Process::query()->where(function (Builder $query) {
  366. $query->where('status', '待交接')->orWhere('status', '交接完成');
  367. })->whereIn('id', $id)->get();
  368. $sign_end = true;
  369. foreach ($processes as $process) {
  370. if (count($process->processDailies) > 0) {
  371. $completed_amount = 0;
  372. foreach ($process->processDailies as $processDaily) {
  373. $completed_amount = $completed_amount + ($processDaily->output);
  374. }
  375. $process->completed_amount = $completed_amount;
  376. }
  377. //统计:
  378. $revenue = ($process->unit_price) * ($process->completed_amount); //收入合计
  379. $processDailies = ProcessDaily::with('processDailyParticipants')->where('process_id', $process->id)->where('output', '>', 0)->get();
  380. $duration_days = count($processDailies); //完成天数
  381. $duration_man_hours = 0; //总工时
  382. $total_cost = 0; //合计成本
  383. foreach ($processDailies as $processDailyOne) {
  384. foreach ($processDailyOne->processDailyParticipants as $processDailyParticipant) {
  385. if (!$processDailyParticipant->unit_price && !$processDailyParticipant->hour_price) continue;
  386. $duration_man_hours += $processDailyParticipant->hour_count;
  387. if ($processDailyParticipant->unit_count) {
  388. $total_cost += ($processDailyParticipant->unit_count) * ($processDailyParticipant->unit_price);
  389. continue;
  390. }
  391. $total_cost += ($processDailyParticipant->hour_count) * ($processDailyParticipant->hour_price);
  392. }
  393. };
  394. $processStatistic = ProcessStatistic::query()->find($process->id);
  395. $processStatistic->revenue = $revenue;
  396. $processStatistic->duration_days = $duration_days;
  397. $processStatistic->duration_man_hours = $duration_man_hours;
  398. if ($sign_end) $processStatistic->ended_at = date('Y-m-d H:i:s');
  399. if (!$revenue || !$total_cost) {
  400. $processStatistic->update();
  401. continue;
  402. }
  403. $gross_profit = $revenue - $total_cost; //毛利润
  404. if ($gross_profit != 0) $gross_profit_rate = $gross_profit / $revenue; //毛利率;
  405. else $gross_profit_rate = 0;
  406. $processStatistic->total_cost = $total_cost;
  407. $processStatistic->gross_profit = $gross_profit;
  408. $processStatistic->gross_profit_rate = $gross_profit_rate;
  409. $processStatistic->update();
  410. app('LogService')->log(__METHOD__, "修改二次加工单统计单_" . __FUNCTION__, json_encode($processStatistic), Auth::user()['id']);
  411. }
  412. }
  413. public function test5(){
  414. ini_set('max_execution_time',2500);
  415. ini_set('memory_limit','1526M');
  416. //清理冗余条码
  417. // $this->cleanBarcode();
  418. while(true){
  419. $toDay = Carbon::now();
  420. $skus = DB::select(DB::raw('select sku from commodities group by sku,owner_id having count(*)>1 limit 500 '));
  421. $skus = array_column($skus,'sku');
  422. $commodities = Commodity::query()->with('barcodes')->whereNotNull('owner_id')->whereIn('sku',$skus)->get();
  423. if (count($commodities) < 1)return "SUCCESS";
  424. $commodityMap = [];
  425. $commodityDel = [];
  426. $commodityTag = [];
  427. $commodityBar = [];
  428. $createBarcodes = [];
  429. $logs = [];
  430. foreach ($commodities as $commodity){
  431. if ($commodityMap[$commodity->sku.'_'.$commodity->owner_id] ?? false){
  432. $codes = $commodity->barcodes ? array_column($commodity->barcodes->toArray(),'code') : [];
  433. $logs[] = [
  434. 'id' => $commodity->id,
  435. 'sku' => $commodity->sku,
  436. 'owner_id'=>$commodity->owner_id,
  437. 'code'=>$codes,
  438. ];
  439. $commodityDel[] = $commodity->id;
  440. $commodityTag[$commodity->id] = $commodityMap[$commodity->sku.'_'.$commodity->owner_id];
  441. $arr = array_diff($codes,$commodityBar[$commodity->sku.'_'.$commodity->owner_id]);
  442. foreach ($arr as $code){
  443. if (!$code)continue;
  444. $createBarcodes[] = [
  445. 'code' => $code,
  446. 'commodity_id' => $commodityMap[$commodity->sku.'_'.$commodity->owner_id],
  447. 'created_at' => $toDay,
  448. ];
  449. }
  450. }else{
  451. $commodityMap[$commodity->sku.'_'.$commodity->owner_id] = $commodity->id;
  452. $commodityBar[$commodity->sku.'_'.$commodity->owner_id] = $commodity->barcodes ? array_column($commodity->barcodes->toArray(),'code') : [];
  453. }
  454. }
  455. dd($commodityMap,$commodityDel,$commodityTag);
  456. app('LogService')->log(__METHOD__,'清理商品',json_encode($logs,JSON_UNESCAPED_UNICODE));
  457. app('LogService')->log(__METHOD__,'重新分配商品',json_encode($commodityTag,JSON_UNESCAPED_UNICODE));
  458. app('InventoryAccountMissionService')->batchUpdateItself('commodity_id', $commodityTag);//批量更新库存盘点任务
  459. app('InventoryCompareService')->batchUpdateItself('commodity_id', $commodityTag);//批量更新库存对比
  460. app('InventoryDailyLogService')->batchUpdateItself('commodity_id', $commodityTag);//批量更新库存每日记录
  461. app('ProcessesContentService')->batchUpdateItself('commodity_id', $commodityTag);//批量更新二次加工内容单
  462. app('StoreCheckingReceiveItemService')->batchUpdateItself('commodity_id', $commodityTag);//批量更新入库盘收一体
  463. app('OrderPackageCommoditiesService')->batchUpdateItself('commodity_id', $commodityTag);//批量更新订单商品
  464. app('LogService')->log(__METHOD__,'删除商品与对应条码',json_encode($commodityDel,JSON_UNESCAPED_UNICODE));
  465. CommodityBarcode::query()->whereIn('commodity_id',$commodityDel)->delete();
  466. Commodity::destroy($commodityDel);
  467. }
  468. }
  469. private function cleanBarcode(){
  470. $logCommodityBarcodes = CommodityBarcode::query()->where('code', "")->get();
  471. if (count($logCommodityBarcodes) > 0) app('LogService')->log(__METHOD__, "纠正商品-删除空条码", json_encode($logCommodityBarcodes, JSON_UNESCAPED_UNICODE));
  472. CommodityBarcode::query()->where('code', "")->delete();
  473. $barcodes = DB::select(DB::raw('select * from commodity_barcodes c
  474. where (c.code,c.commodity_id) in (select code,commodity_id from commodity_barcodes group by code,commodity_id having count(*) > 1) order by commodity_id'));
  475. $barcodeMap = [];
  476. $barcodeDelete = [];
  477. foreach ($barcodes as $barcode) {
  478. if (isset($barcodeMap[$barcode->code . '_' . $barcode->commodity_id])) $barcodeDelete[] = $barcode->id;
  479. else $barcodeMap[$barcode->code . '_' . $barcode->commodity_id] = $barcode->id;
  480. }
  481. $logCommodityBarcodes = CommodityBarcode::query()->whereIn('id', $barcodeDelete)->get();
  482. if (count($logCommodityBarcodes) > 0) app('LogService')->log(__METHOD__, "纠正商品-删除重复条码", json_encode($logCommodityBarcodes, JSON_UNESCAPED_UNICODE));
  483. CommodityBarcode::destroy($barcodeDelete);
  484. }
  485. public function correctCommodity()
  486. {
  487. ini_set('max_execution_time', 2500);
  488. ini_set('memory_limit', '1526M');
  489. //清理冗余条码
  490. //$this->cleanBarcode();
  491. //获取重复条码
  492. $commodities = DB::select(DB::raw('select commodities.name,commodities.sku,commodities.owner_id,commodity_barcodes.id as barcode_id,commodity_barcodes.code as barcode_code,commodity_barcodes.commodity_id from commodities LEFT JOIN commodity_barcodes on commodities.id = commodity_barcodes.commodity_id
  493. where (commodities.owner_id,commodity_barcodes.code) in (select commodities.owner_id,commodity_barcodes.code from commodities LEFT JOIN commodity_barcodes on commodities.id = commodity_barcodes.commodity_id group by commodities.owner_id,commodity_barcodes.code having count(*) > 1) order by commodities.owner_id,commodity_barcodes.code'));
  494. //对比map池
  495. $commodityMap = [];
  496. //需要删除项
  497. $commodityDelete = [];
  498. foreach ($commodities as $index => $commodity) {
  499. $commodity->barcode_code = strtolower(trim($commodity->barcode_code));
  500. //货主+条码 为唯一key值 设想正常数据下同货主不应该有同条码
  501. $key = $commodity->owner_id . '_' . $commodity->barcode_code;
  502. //使用map池对比为重复数据
  503. if (isset($commodityMap[$key])) {
  504. //获取下标指针指向的源数据
  505. $c = $commodities[$commodityMap[$key]];
  506. //源数据不符合规范,当前数据替换掉它
  507. if (($c->sku == null || $c->sku == "") && ($commodity->sku != null && $commodity->sku != "")) {
  508. $commodityDelete[] = $commodityMap[$key];
  509. $commodityMap[$key] = $index;
  510. } else {
  511. //当前数据比源数据更符合预期,替换掉
  512. if (($c->sku == $commodity->sku) && (strlen($c->name) < strlen($commodity->name))) {
  513. $commodityDelete[] = $commodityMap[$key];
  514. $commodityMap[$key] = $index;
  515. } else {
  516. //扔进处理池
  517. $commodityDelete[] = $index;
  518. }
  519. }
  520. //第一次出现的新数据,val为下标,当作指针指向源数据
  521. } else $commodityMap[$key] = $index;
  522. }
  523. $createBarcodes = []; //批量生成条码
  524. $deleteCommodities = []; //批量删除商品及商品条码
  525. $updateCommodities = [];
  526. foreach ($commodityDelete as $index) {
  527. //获取到被处理数据 与 目标数据
  528. $del = $commodities[$index];
  529. $target = $commodities[$commodityMap[$del->owner_id . '_' . $del->barcode_code]];
  530. //记录ID删除商品与条码
  531. $deleteCommodities[] = $del->commodity_id;
  532. //有效条码合并
  533. $barcodes = DB::select(DB::raw("select * from
  534. (select * from commodity_barcodes where commodity_id = " . $del->commodity_id . ")a
  535. where (select count(1) as num from commodity_barcodes b
  536. where commodity_id = " . $target->commodity_id . " and b.code = a.code) = 0"));
  537. if (count($barcodes) > 0) {
  538. foreach ($barcodes as $barcode) {
  539. $createBarcodes[] = ['code' => $barcode->code, 'commodity_id' => $target->commodity_id];
  540. }
  541. }
  542. $updateCommodities[$del->commodity_id] = $target->commodity_id;
  543. }
  544. if (count($updateCommodities) > 0){
  545. app('InventoryAccountMissionService')->batchUpdateItself('commodity_id', $updateCommodities);//批量更新库存盘点任务
  546. app('InventoryCompareService')->batchUpdateItself('commodity_id', $updateCommodities);//批量更新库存对比
  547. app('InventoryDailyLogService')->batchUpdateItself('commodity_id', $updateCommodities);//批量更新库存每日记录
  548. app('ProcessesContentService')->batchUpdateItself('commodity_id', $updateCommodities);//批量更新二次加工内容单
  549. app('StoreCheckingReceiveItemService')->batchUpdateItself('commodity_id', $updateCommodities);//批量更新入库盘收一体
  550. app('OrderPackageCommoditiesService')->batchUpdateItself('commodity_id', $updateCommodities);//批量更新订单商品
  551. }
  552. if (count($createBarcodes) > 0) app('LogService')->log(__METHOD__, "纠正商品-录入合并条码", json_encode(data_get($createBarcodes, '*.id'), JSON_UNESCAPED_UNICODE));
  553. CommodityBarcode::query()->insert($createBarcodes);
  554. $logCommodityBarcodes = CommodityBarcode::query()->whereIn('commodity_id', $deleteCommodities)->get();
  555. if (count($logCommodityBarcodes) > 0) app('LogService')->log(__METHOD__, "纠正商品-删除无用商品条码", json_encode(data_get($logCommodityBarcodes, '*.id'), JSON_UNESCAPED_UNICODE));
  556. CommodityBarcode::query()->whereIn('commodity_id', $deleteCommodities)->delete();
  557. // $logCommodities = Commodity::query()->whereIn('id',$deleteCommodities)->get();
  558. if (count($deleteCommodities) > 0) app('LogService')->log(__METHOD__, "纠正商品-删除无用商品", json_encode($deleteCommodities, JSON_UNESCAPED_UNICODE));
  559. Commodity::destroy($deleteCommodities);
  560. }
  561. /*1*/
  562. function socket(Request $request)
  563. {/**/
  564. $a = microtime(true);
  565. error_reporting(E_ALL);
  566. set_time_limit(0);
  567. echo "<h2>TCP/IP Connection</h2>\n";
  568. $port = 8091;
  569. $ip = "127.0.0.1";
  570. /*
  571. +-------------------------------
  572. * @socket连接整个过程
  573. +-------------------------------
  574. * @socket_create
  575. * @socket_connect
  576. * @socket_write
  577. * @socket_read
  578. * @socket_close
  579. +--------------------------------
  580. */
  581. $socket = socket_create(AF_INET, SOCK_STREAM, SOL_TCP);
  582. if ($socket < 0) {
  583. echo "socket_create() failed: reason: " . socket_strerror($socket) . "\n";
  584. } else {
  585. echo "OK.\n";
  586. }
  587. echo "试图连接 '$ip' 端口 '$port'...\n";
  588. $result = socket_connect($socket, $ip, $port);
  589. if ($result < 0) {
  590. echo "socket_connect() failed.\nReason: ($result) " . socket_strerror($result) . "\n";
  591. } else {
  592. echo "连接OK\n";
  593. }
  594. $b = microtime(true);
  595. echo "连接耗时:" . ($b - $a) . "\n";
  596. $content = Commodity::query()->limit(200)->get();
  597. $c = microtime(true);
  598. echo "查询数据耗时:" . ($c - $b) . "\n";
  599. $content->toArray();
  600. /*$chunks=$content->chunk(100);
  601. foreach ($chunks as $chunk){
  602. $chunk->toJson();
  603. var_dump(mb_strlen($chunk->toJson()));
  604. //socket_write($socket, $chunk->toJson(), mb_strlen($chunk->toJson()));
  605. }*/
  606. $d = microtime(true);
  607. echo "发送数据耗时:" . ($d - $c) . "\n";
  608. socket_close($socket);
  609. $e = microtime(true);
  610. echo "共耗时:" . ($e - $a) . "\n";
  611. }
  612. public function test3()
  613. {
  614. /** @var OrderTrackingService $orderTrackingService */
  615. $orderTrackingService = app('OrderTrackingService');
  616. /** @var OrderService $orderService */
  617. $orderService = app(OrderService::class);
  618. $owners = app(OrderTrackingOwnerService::class)->getTrackingOrderOwner();
  619. $startDate = \Illuminate\Support\Carbon::parse('2020-10-28 00:00:00')->toDateTimeString();
  620. $orderHeaders = OracleDOCOrderHeader::query()->with(['oracleDOCOrderDetails', 'actAllocationDetails', 'oracleBASCode'])
  621. ->where('addTime', '>=', $startDate)
  622. ->whereIn('customerID', data_get($owners, '*.code'))
  623. ->get();
  624. $orderService->updateByWmsOrders($orderHeaders);
  625. $orderTrackingService->updateByWmsOrderHeaders($orderHeaders);
  626. }
  627. public function test11()
  628. {
  629. $rejectedBills = RejectedBill::query()
  630. ->where('created_at','>=','2020-11-10 18:00:22')
  631. ->where('created_at','<=','2020-11-11 00:00:00')
  632. ->get();
  633. $update = [['id','logistic_number']];
  634. $rejectedBills->each(function ($rejectedBill)use(&$update){
  635. if($rejectedBill->logistic_number == '原单退回'){
  636. $details = OracleActAllocationDetails::query()->with('oracleDocOrderHeader')->whereHas('oracleDocOrderHeader',function($query)use($rejectedBill){
  637. $query->where('SOReference1',$rejectedBill->order_number);
  638. })->get()->groupBy('picktotraceid');
  639. if($details->count() == 1){
  640. $update[] = ['id'=> $rejectedBill->id ,'logistic_number'=>$rejectedBill->logistic_number_return];
  641. }
  642. }
  643. });
  644. app('RejectedBillService')->batchUpdate($update);
  645. }
  646. public function output()
  647. {
  648. /** @var CacheService $cacheService */
  649. $cacheService = app('CacheService');
  650. $authorities=$cacheService->getOrExecute('userxx',function (){
  651. return Authority::with('roles')->get();
  652. });
  653. dd($authorities);
  654. }
  655. public function output2()
  656. {
  657. dump(Cache::get('aa'));
  658. Cache::put('aa', '2223', 5);
  659. }
  660. public function usage()
  661. {
  662. dd(Request::all());
  663. }
  664. public function relating()
  665. {
  666. dd(OrderIssue::query()->where('id',182)->paginate()->total());
  667. }
  668. public function updateOrdersWarehouse()
  669. {
  670. /**
  671. * @var DataHandlerService $dataHandlerService
  672. * @var OrderService $orderService
  673. */
  674. $dataHandlerService = app(DataHandlerService::class);
  675. $orderService = app(OrderService::class);
  676. $page = 500;
  677. $count = Order::query()->count();
  678. $warehouse = Warehouse::query()->get();
  679. $warehouse_map = $dataHandlerService->dataHeader(['code'], $warehouse);
  680. for ($i = 0; $i < $count; $i += $page) {
  681. $min = $i;$max = $i + $page;
  682. $orders = Order::query()->where('id', '>=', $min)->where('id', '<=', $max)->get();
  683. $orderNos = array_diff(array_unique(data_get($orders, '*.code')), ['', ' ', '*', null]);
  684. if (count($orderNos)==0) continue;
  685. /** @var Collection $orderHeaders */
  686. $orderHeaders = OracleDOCOrderHeader::query()->whereIn('orderno', $orderNos)->get();
  687. if ($orderHeaders->count() == 0) continue;
  688. $orderHeader_map = $dataHandlerService->dataHeader(['orderno'], $orderHeaders);
  689. $update_params = [];
  690. $update_params[] = ['id', 'warehouse_id'];
  691. foreach ($orders as $order) {
  692. $orderHeader = $dataHandlerService->getKeyValue(['orderno' => $order->code], $orderHeader_map);
  693. if ($orderHeader == null) continue;
  694. $warehouse = $dataHandlerService->getKeyValue(['code' => $orderHeader->warehouseid], $warehouse_map);
  695. if ($warehouse == null) continue;
  696. $update_params[] = [
  697. 'id' => $order->id,
  698. 'warehouse_id' => $warehouse->id
  699. ];
  700. }
  701. $orderService->batchUpdate($update_params);
  702. unset($orders, $orderHeaders, $update_params);
  703. }
  704. unset($warehouse);
  705. }
  706. public function syncSendOrder()
  707. {
  708. $order_issues = OrderIssue::query()->whereNotNull('second_client_no')->get();
  709. $client_nos = data_get($order_issues,'*.second_client_no');
  710. $orderHeaders = OracleDOCOrderHeader::query()->selectRaw(implode(',',OracleDOCOrderHeaderService::$columns))
  711. ->whereIn('SOReference1',$client_nos)
  712. ->with(['oracleBASCustomer'=>function($query){
  713. $query->selectRaw('BAS_CUSTOMER.CustomerID,BAS_CUSTOMER.Customer_Type,BAS_CUSTOMER.Descr_C,BAS_CUSTOMER.Active_Flag');
  714. },'oracleDOCOrderDetails'=>function($query){
  715. $query->selectRaw('doc_order_details.orderNo,doc_order_details.customerid,doc_order_details.sku,doc_order_details.QtyOrdered');
  716. }, 'actAllocationDetails'=>function($query){
  717. $query->selectRaw('ACT_Allocation_Details.AllocationDetailsID,ACT_Allocation_Details.OrderNo,ACT_Allocation_Details.Qty_Each,ACT_Allocation_Details.PickToTraceID,ACT_Allocation_Details.CustomerID');
  718. },'oracleBASCode'=>function($query){
  719. $query->selectRaw('BAS_Codes.CodeID,BAS_Codes.CodeName_C,BAS_Codes.Code');
  720. }])
  721. ->get();
  722. $service = app('OrderIssueService');
  723. $service->updateByWmsOrders($orderHeaders);
  724. }
  725. public function changeOrderIssue()
  726. {
  727. // $ids = [5419,5404,5402,5401,5400,5398,5397,5395,5388,5387,5383,5382,5379,5373,5370,5353,5329,5327];
  728. // OrderIssue::query()->whereIn('id',$ids)->update(['is_new_rejecting'=>'无','rejecting_status'=>'未退回']);
  729. }
  730. }