OwnerService.php 19 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497
  1. <?php
  2. namespace App\Services;
  3. use App\Authority;
  4. use App\OracleBasCustomer;
  5. use App\Owner;
  6. use App\OwnerPriceDirectLogistic;
  7. use App\OwnerPriceExpress;
  8. use App\OwnerPriceLogistic;
  9. use App\OwnerPriceOperation;
  10. use App\OwnerPriceSystem;
  11. use App\OwnerStoragePriceModel;
  12. use App\Services\common\BatchUpdateService;
  13. use App\User;
  14. use Carbon\Carbon;
  15. use Illuminate\Database\Eloquent\Builder;
  16. use Illuminate\Support\Collection;
  17. use Illuminate\Support\Facades\Auth;
  18. use Illuminate\Support\Facades\Cache;
  19. use Illuminate\Support\Facades\DB;
  20. use App\Traits\ServiceAppAop;
  21. class OwnerService
  22. {
  23. use ServiceAppAop;
  24. protected $modelClass=Owner::class;
  25. /** @var CacheService $cacheService */
  26. private $cacheService;
  27. function __construct(){
  28. $this->instant($this->cacheService,'CacheService');
  29. }
  30. /*
  31. * array | string $column
  32. * 默认一些select字段,可传递string 或 array来指定select字段
  33. */
  34. public function getIntersectPermitting(array $column = ['id', 'name'])
  35. {
  36. $ownerIds=app('UserService')->getPermittingOwnerIds(Auth::user());
  37. return $this->cacheService->getOrExecute('OwnersAll_IdName'.md5(json_encode($column).json_encode($ownerIds)),function()use($column,$ownerIds){
  38. if(empty($ownerIds))return new Collection();
  39. return Owner::query()->select($column)->whereIn('id', $ownerIds)->whereNull('deleted_at')->get();
  40. },config('cache.expirations.owners'));
  41. }
  42. public function getSelection($column = ['id'])
  43. {
  44. return $this->cacheService->getOrExecute('OwnersAll_'.md5(json_encode($column)),function()use($column){
  45. return Owner::filterAuthorities()->select($column)->get();
  46. },config('cache.expirations.owners'));
  47. }
  48. /**
  49. *同步WMS全部货主至WAS
  50. */
  51. public function syncOwnersData()
  52. {
  53. $basCustomers = OracleBasCustomer::query()
  54. ->select('CUSTOMERID', 'DESCR_C')
  55. ->where('DESCR_C', 'not like', '%换ERP%')
  56. ->where('DESCR_C', 'not like', '%退仓%')
  57. ->where('CUSTOMER_TYPE', 'OW')
  58. ->get();
  59. $ownerCount = Owner::query()->count();
  60. if (count($basCustomers) == $ownerCount) return null;
  61. foreach ($basCustomers as $basCustomer) {
  62. $owner = Owner::query()->where('code', $basCustomer['customerid'])->first();
  63. if (!isset($owner)){
  64. Owner::query()->create([
  65. 'code' => $basCustomer['customerid'],
  66. 'name' => $basCustomer['descr_c'],
  67. 'created_at' => Carbon::now()->format('Y-m-d H:i:s'),
  68. ]);
  69. continue;
  70. }
  71. if ($owner['name']!=$basCustomer['descr_c']){
  72. $owner->update([
  73. 'code' => $basCustomer['customerid'],
  74. 'name' => $basCustomer['descr_c'],
  75. ]);
  76. }
  77. }
  78. $owners = Owner::query()->select('id', 'name')->get();
  79. return $owners;
  80. }
  81. public function first(array $params, array $rules =[]){
  82. return $this->cacheService->getOrExecute('OwnersFirst'.md5(json_encode($params),json_encode($rules)),function()use($params,$rules){
  83. $owner = Owner::query();
  84. foreach ($params as $column => $value){
  85. if (!isset($rules[$column]))$owner->where($column, $value);
  86. else{
  87. switch ($rules[$column]){
  88. case "or":
  89. $owner->orWhere($column, $value);
  90. break;
  91. }
  92. }
  93. }
  94. return $owner->first();
  95. },config('cache.expirations.rarelyChange'));
  96. }
  97. public function find($id, $with = [])
  98. {
  99. return Owner::query()->with($with)->find($id);
  100. }
  101. public function update(Owner $owner, array $values, array $related = [])
  102. {
  103. if ($related["ownerStoragePriceModels"] ?? false)$owner->ownerStoragePriceModels()->sync($related["ownerStoragePriceModels"]);
  104. return $owner->update($values);
  105. }
  106. public function create(array $params, array $related = []){
  107. /** @var Owner $owner */
  108. $owner = Owner::query()->create($params);
  109. if ($related["ownerStoragePriceModels"] ?? false)$owner->ownerStoragePriceModels()->syncWithoutDetaching($related["ownerStoragePriceModels"]);
  110. return $owner;
  111. }
  112. public function firstOrCreate(array $params, array $values = null){
  113. if (!$values) return Owner::query()->firstOrCreate($params);
  114. return Owner::query()->firstOrCreate($params,$values);
  115. }
  116. public function 获取订单跟踪的货主(){
  117. return Owner::query()->with('orderTrackingOwner')->whereHas('orderTrackingOwner',function($query){
  118. $query->where('status','启用');
  119. })->get();
  120. }
  121. public function getByWmsOrders($orderHeaders){
  122. $customerIds = array_unique(data_get($orderHeaders,'*.customerid'));
  123. $customerIds = array_diff($customerIds,[null,'','*']);
  124. $owners = Owner::query()->whereIn('code',$customerIds)->get();
  125. if($owners->count() < count($customerIds)){
  126. $customerIds = array_diff($customerIds,data_get($owners,'*.code'));
  127. $owner_list = $this->createByWmsCustomerIds($customerIds);
  128. $owners=$owners->concat($owner_list);
  129. }
  130. return $owners;
  131. }
  132. public function createByWmsCustomerIds($codes){
  133. if(!$codes) {return [];}
  134. $basCustomer = OracleBasCustomer::query()
  135. ->where('Customer_Type','OW')
  136. ->whereIn('CustomerID', $codes)
  137. ->get();
  138. $insert_params = [];
  139. $created_at = Carbon::now()->format('Y-m-d H:i:s');
  140. foreach ($basCustomer as $item) {
  141. $insert_params[] = [
  142. 'code' => $item->customerid,
  143. 'name' => $item->descr_c,
  144. 'created_at' => $created_at,
  145. ];
  146. }
  147. try {
  148. if (count($insert_params) > 0) {
  149. $this->insert($insert_params);
  150. app('LogService')->log(__METHOD__, __FUNCTION__, '批量创建 owner ' . count($insert_params) . json_encode($insert_params) );
  151. }
  152. } catch (\Exception $e) {
  153. app('LogService')->log(__METHOD__, __FUNCTION__, '批量创建 owner error' . json_encode($insert_params) . '||' . $e->getMessage() . '||' . $e->getTraceAsString());
  154. } finally {
  155. return Owner::query()->whereIn('code', $codes)->get();
  156. }
  157. }
  158. public function insert($fillables){
  159. return Owner::query()->insert($fillables);
  160. }
  161. public function getAuthorizedOwners(){
  162. $user = Auth::user();
  163. return Owner::query()->whereIn('id',app('UserService')->getPermittingOwnerIds($user)??[])->get();
  164. }
  165. public function get(array $params, array $withs = null, bool $authority = true, bool $notShowSoftDelete = false, $user = null)
  166. {
  167. /** @var User $user */
  168. if ($user==null)$user = Auth::user();
  169. return Cache::remember(
  170. 'owner_'.md5(json_encode($params).json_encode($withs).$authority.$notShowSoftDelete.json_encode($user))
  171. ,config('cache.expirations.rarelyChange')
  172. ,function()use($params,$withs,$authority,$notShowSoftDelete,$user){
  173. $query = Owner::query();
  174. if ($withs)$query->with($withs);
  175. if ($authority&&$user){
  176. $ids = $user->getPermittingOwnerIdsAttribute();
  177. $query->whereIn("id",$ids);
  178. }
  179. if ($notShowSoftDelete) $query->whereNull('deleted_at');
  180. $query = $this->query($query,$params);
  181. return $query->get();
  182. });
  183. }
  184. public function paginate(array $params, array $withs = null, bool $authority = true, bool $notShowSoftDelete = false)
  185. {
  186. /** @var User $user */
  187. $user = Auth::user();
  188. $query = Owner::query();
  189. if ($withs)$query->with($withs);
  190. if ($authority){
  191. $ids = $user->getPermittingOwnerIdsAttribute();
  192. $query->whereIn("id",$ids);
  193. }
  194. if ($notShowSoftDelete) $query->whereNull('deleted_at');
  195. $query = $this->query($query,$params)->orderByDesc("id");
  196. return $query->paginate($params["paginate"] ?? 50);
  197. }
  198. private function query(Builder $builder, array $params)
  199. {
  200. foreach ($params as $column => $param){
  201. if ($column == 'paginate' || $column == 'page' || !$param)continue;
  202. if ($param === true){
  203. $builder->whereNotNull($column);
  204. continue;
  205. }
  206. if ($param === false){
  207. $builder->whereNull($column);
  208. continue;
  209. }
  210. if ($column == 'created_at_start'){
  211. $builder->where("created_at",">=",$param.":00");
  212. continue;
  213. }
  214. if ($column == 'created_at_end'){
  215. $builder->where("created_at","<=",$param.":59");
  216. continue;
  217. }
  218. if ($column == 'contract_number'){
  219. $builder->whereHas("contracts",function ($query)use($param){
  220. /** @var Builder $query */
  221. $query->where("contract_number","like",$param."%");
  222. });
  223. continue;
  224. }
  225. if ($column == 'using_type'){
  226. $builder->whereHas("ownerStoragePriceModels",function ($query)use($param){
  227. /** @var Builder $query */
  228. $query->where("using_type",$param);
  229. });
  230. continue;
  231. }
  232. if ($column == 'customers'){
  233. if (is_array($param))$builder->whereIn('customer_id',$param);
  234. else $builder->where('customer_id',$param);
  235. continue;
  236. }
  237. if ($column == 'ids'){
  238. if (is_array($param))$builder->whereIn('id',$param);
  239. else $builder->where('id',$param);
  240. continue;
  241. }
  242. if ($column == 'owners'){
  243. if (is_array($param))$builder->whereIn('owner_id',$param);
  244. else $builder->where('owner_id',$param);
  245. continue;
  246. }
  247. if (is_array($param))$builder->whereIn($column,$param);
  248. else $builder->where($column,$param);
  249. }
  250. return $builder;
  251. }
  252. public function getOwnerByCodes($codes)
  253. {
  254. $collect = collect();
  255. if(count($codes) == 0)return $collect;
  256. foreach ($codes as $code) {
  257. $collect = $collect->push($this->getOwnerByCode($code));
  258. }
  259. return $collect;
  260. }
  261. public function getOwnerByCode($code){
  262. return Cache::remember("getOwnerByCode_{$code}", config('cache.expirations.owners'), function ()use($code){
  263. $owner = Owner::query()->where('code',$code)->first();
  264. if($owner) return $owner;
  265. $basCustomer = app('OracleBasCustomerService')->first(['Customer_Type'=>'OW','CustomerID'=>$code]);
  266. if(!$basCustomer)return null;
  267. if($basCustomer && $basCustomer['active_flag']=='Y') return Owner::query()
  268. ->create(['name'=>$basCustomer['descr_c'],'code'=>$basCustomer['customerid']]);
  269. $deleted_at=Carbon::now()->toDateTimeString();
  270. if($basCustomer && $basCustomer['active_flag']=='N') return Owner::query()
  271. ->create(['name'=>$basCustomer['descr_c'],'code'=>$basCustomer['customerid'],'deleted_at'=>$deleted_at]);
  272. });
  273. }
  274. public function codeGetOwner($code)
  275. {
  276. return app(CacheService::class)->getOrExecute("owner_".$code,function ()use($code){
  277. return Owner::query()->firstOrCreate(["code"=>$code],["code"=>$code,"name"=>$code]);
  278. });
  279. }
  280. /**
  281. * 向FLUX同步推送WAS本地录入信息
  282. *
  283. * @param array|Owner|integer $owner
  284. * @return bool
  285. */
  286. public function syncPush($owner)
  287. {
  288. if (is_array($owner)){
  289. $owner = new Owner();
  290. foreach ($owner as $column=>$value){
  291. $owner[$column] = $value;
  292. }
  293. }
  294. if (is_numeric($owner)){
  295. $owner = Owner::query()->find($owner);
  296. if (!$owner)return false;
  297. }
  298. $wms = DB::connection("oracle")->selectOne(DB::raw("SELECT CUSTOMERID FROM BAS_CUSTOMER WHERE CUSTOMER_TYPE = ? AND CUSTOMERID = ?"),["OW",$owner->code]);
  299. if (!$wms && $owner->code){
  300. $query = DB::raw(<<<sql
  301. INSERT INTO BAS_CUSTOMER(CUSTOMERID,CUSTOMER_TYPE,DESCR_C,ADDTIME,EDITTIME,ADDWHO)
  302. VALUES(?,?,?,TO_DATE(?,'yyyy-mm-dd hh24:mi:ss'),TO_DATE(?,'yyyy-mm-dd hh24:mi:ss'),?)
  303. sql
  304. );
  305. $date = date('Y-m-d H:i:s');
  306. DB::connection("oracle")->insert($query,[$owner->code,'OW',$owner->name,$date,$date,'WAS-'.(Auth::user() ? Auth::user()['name'] : 'SYSTEM')]);
  307. }
  308. return true;
  309. }
  310. public function syncUpdate($owner)
  311. {
  312. if (is_array($owner)){
  313. $owner = new Owner();
  314. foreach ($owner as $column=>$value){
  315. $owner[$column] = $value;
  316. }
  317. }
  318. if (is_numeric($owner)){
  319. $owner = Owner::query()->find($owner);
  320. if (!$owner)return false;
  321. }
  322. $sql = DB::raw(<<<sql
  323. update BAS_CUSTOMER set ACTIVE_FLAG = ?,EDITTIME = TO_DATE(?,'yyyy-mm-dd hh24:mi:ss'),EDITWHO = ? where CUSTOMERID = ? and CUSTOMER_TYPE = ?
  324. sql
  325. );
  326. $date = date('Y-m-d H:i:s');
  327. if ($owner && $owner->deleted_at){
  328. DB::connection("oracle")->update($sql,['N',$date,'WAS-'.(Auth::user() ? Auth::user()['name'] : 'SYSTEM'),$owner->code,'OW']);
  329. }
  330. if ($owner && $owner->deleted_at==null) {
  331. DB::connection("oracle")->update($sql,['Y',$date,'WAS-'.(Auth::user() ? Auth::user()['name'] : 'SYSTEM'),$owner->code,'OW']);
  332. }
  333. return true;
  334. }
  335. /**
  336. * 同步货主时创建权限
  337. *
  338. * @param array|Owner $owner
  339. */
  340. public function createAuthority($owner)
  341. {
  342. Authority::query()->create([
  343. 'name' => "_{$owner['id']}",
  344. 'alias_name' => "(货主:{$owner['name']})",
  345. 'remark' => "(key: _{$owner['id']})",
  346. ]);
  347. }
  348. /**
  349. * 停用货主时删除权限
  350. *
  351. * @param array|Owner $owner
  352. */
  353. public function deleteAuthority($owner)
  354. {
  355. $authorities = Authority::query()->where('name',"_{$owner['id']}")
  356. ->where("alias_name","like","(货主%")
  357. ->get(["id"]);
  358. $ids = array_column($authorities->toArray(),"id");
  359. DB::table("authority_role")->whereIn("id_authority",$ids)->delete();
  360. Authority::destroy($ids);
  361. }
  362. /**
  363. * 计费模型变动时更新货主中关联属性
  364. *
  365. * @param integer $ownerId
  366. *
  367. */
  368. public function refreshRelevance($ownerId)
  369. {
  370. $relevance = [];
  371. $sql = <<<sql
  372. SELECT 1 FROM owner_storage_price_models a
  373. LEFT JOIN owner_storage_price_model_owner b ON a.id = b.owner_storage_price_model_id
  374. LEFT JOIN owners c ON b.owner_id = c.id
  375. WHERE (a.operation IS NULL OR a.operation = '') AND c.id = ? LIMIT 1
  376. sql;
  377. if (DB::selectOne(DB::raw($sql),[$ownerId]))$relevance[] = 0;
  378. $sql = <<<sql
  379. SELECT 1 FROM owner_price_operations a
  380. LEFT JOIN owner_price_operation_owner b ON a.id = b.owner_price_operation_id
  381. LEFT JOIN owners c ON b.owner_id = c.id
  382. WHERE (a.operation IS NULL OR a.operation = '') AND c.id = ? LIMIT 1
  383. sql;
  384. if (DB::selectOne(DB::raw($sql),[$ownerId]))$relevance[] = 1;
  385. $sql = <<<sql
  386. SELECT 1 FROM owner_price_expresses a
  387. LEFT JOIN owner_price_express_owner b ON a.id = b.owner_price_express_id
  388. LEFT JOIN owners c ON b.owner_id = c.id
  389. WHERE (a.operation IS NULL OR a.operation = '') AND c.id = ? LIMIT 1
  390. sql;
  391. if (DB::selectOne(DB::raw($sql),[$ownerId]))$relevance[] = 2;
  392. $sql = <<<sql
  393. SELECT 1 FROM owner_price_logistics a
  394. LEFT JOIN owner_price_logistic_owner b ON a.id = b.owner_price_logistic_id
  395. LEFT JOIN owners c ON b.owner_id = c.id
  396. WHERE (a.operation IS NULL OR a.operation = '') AND c.id = ? LIMIT 1
  397. sql;
  398. if (DB::selectOne(DB::raw($sql),[$ownerId]))$relevance[] = 3;
  399. $sql = <<<sql
  400. SELECT 1 FROM owner_price_direct_logistics a
  401. LEFT JOIN owner_price_direct_logistic_owner b ON a.id = b.owner_price_direct_logistic_id
  402. LEFT JOIN owners c ON b.owner_id = c.id
  403. WHERE (a.operation IS NULL OR a.operation = '') AND c.id = ? LIMIT 1
  404. sql;
  405. if (DB::selectOne(DB::raw($sql),[$ownerId]))$relevance[] = 4;
  406. $sql = <<<sql
  407. SELECT 1 FROM owner_price_systems a LEFT JOIN owners b ON a.owner_id = b.id
  408. WHERE b.id = ? LIMIT 1
  409. sql;
  410. if (DB::selectOne(DB::raw($sql),[$ownerId]))$relevance[] = 5;
  411. Owner::query()->where("id",$ownerId)->update(["relevance"=>$relevance]);
  412. }
  413. /**
  414. * 税率变更时附加税率
  415. *
  416. * @param Owner|\stdClass $owner
  417. */
  418. public function attachTaxRate(Owner $owner)
  419. {
  420. OwnerStoragePriceModel::query()->whereHas("owners",function (Builder $query)use($owner){
  421. $query->where("id",$owner->id);
  422. })->whereNull("tax_rate_id")->update(["tax_rate_id"=>$owner->tax_rate_id]);
  423. OwnerPriceOperation::query()->whereHas("owners",function (Builder $query)use($owner){
  424. $query->where("id",$owner->id);
  425. })->whereNull("tax_rate_id")->update(["tax_rate_id"=>$owner->tax_rate_id]);
  426. OwnerPriceExpress::query()->whereHas("owners",function (Builder $query)use($owner){
  427. $query->where("id",$owner->id);
  428. })->whereNull("tax_rate_id")->update(["tax_rate_id"=>$owner->tax_rate_id]);
  429. OwnerPriceLogistic::query()->whereHas("owners",function (Builder $query)use($owner){
  430. $query->where("id",$owner->id);
  431. })->whereNull("tax_rate_id")->update(["tax_rate_id"=>$owner->tax_rate_id]);
  432. OwnerPriceDirectLogistic::query()->whereHas("owners",function (Builder $query)use($owner){
  433. $query->where("id",$owner->id);
  434. })->whereNull("tax_rate_id")->update(["tax_rate_id"=>$owner->tax_rate_id]);
  435. OwnerPriceSystem::query()->where("owner_id",$owner->id)->whereNull("tax_rate_id")
  436. ->update(["tax_rate_id"=>$owner->tax_rate_id]);
  437. }
  438. /**
  439. * 税率变更时取消税率
  440. *
  441. * @param Owner|\stdClass $owner
  442. */
  443. public function removeTaxRate(Owner $owner)
  444. {
  445. OwnerStoragePriceModel::query()->whereHas("owners",function (Builder $query)use($owner){
  446. $query->where("id",$owner->id);
  447. })->update(["tax_rate_id"=>null]);
  448. OwnerPriceOperation::query()->whereHas("owners",function (Builder $query)use($owner){
  449. $query->where("id",$owner->id);
  450. })->update(["tax_rate_id"=>null]);
  451. OwnerPriceExpress::query()->whereHas("owners",function (Builder $query)use($owner){
  452. $query->where("id",$owner->id);
  453. })->update(["tax_rate_id"=>null]);
  454. OwnerPriceLogistic::query()->whereHas("owners",function (Builder $query)use($owner){
  455. $query->where("id",$owner->id);
  456. })->update(["tax_rate_id"=>null]);
  457. OwnerPriceDirectLogistic::query()->whereHas("owners",function (Builder $query)use($owner){
  458. $query->where("id",$owner->id);
  459. })->update(["tax_rate_id"=>null]);
  460. OwnerPriceSystem::query()->where("owner_id",$owner->id)
  461. ->update(["tax_rate_id"=>null]);
  462. }
  463. }