OwnerService.php 19 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490
  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. }
  236. if ($column == 'ids'){
  237. if (is_array($param))$builder->whereIn('id',$param);
  238. else $builder->where('id',$param);
  239. }
  240. if (is_array($param))$builder->whereIn($column,$param);
  241. else $builder->where($column,$param);
  242. }
  243. return $builder;
  244. }
  245. public function getOwnerByCodes($codes)
  246. {
  247. $collect = collect();
  248. if(count($codes) == 0)return $collect;
  249. foreach ($codes as $code) {
  250. $collect = $collect->push($this->getOwnerByCode($code));
  251. }
  252. return $collect;
  253. }
  254. public function getOwnerByCode($code){
  255. return Cache::remember("getOwnerByCode_{$code}", config('cache.expirations.owners'), function ()use($code){
  256. $owner = Owner::query()->where('code',$code)->first();
  257. if($owner) return $owner;
  258. $basCustomer = app('OracleBasCustomerService')->first(['Customer_Type'=>'OW','CustomerID'=>$code]);
  259. if(!$basCustomer)return null;
  260. if($basCustomer && $basCustomer['active_flag']=='Y') return Owner::query()
  261. ->create(['name'=>$basCustomer['descr_c'],'code'=>$basCustomer['customerid']]);
  262. $deleted_at=Carbon::now()->toDateTimeString();
  263. if($basCustomer && $basCustomer['active_flag']=='N') return Owner::query()
  264. ->create(['name'=>$basCustomer['descr_c'],'code'=>$basCustomer['customerid'],'deleted_at'=>$deleted_at]);
  265. });
  266. }
  267. public function codeGetOwner($code)
  268. {
  269. return app(CacheService::class)->getOrExecute("owner_".$code,function ()use($code){
  270. return Owner::query()->firstOrCreate(["code"=>$code],["code"=>$code,"name"=>$code]);
  271. });
  272. }
  273. /**
  274. * 向FLUX同步推送WAS本地录入信息
  275. *
  276. * @param array|Owner|integer $owner
  277. * @return bool
  278. */
  279. public function syncPush($owner)
  280. {
  281. if (is_array($owner)){
  282. $owner = new Owner();
  283. foreach ($owner as $column=>$value){
  284. $owner[$column] = $value;
  285. }
  286. }
  287. if (is_numeric($owner)){
  288. $owner = Owner::query()->find($owner);
  289. if (!$owner)return false;
  290. }
  291. $wms = DB::connection("oracle")->selectOne(DB::raw("SELECT CUSTOMERID FROM BAS_CUSTOMER WHERE CUSTOMER_TYPE = ? AND CUSTOMERID = ?"),["OW",$owner->code]);
  292. if (!$wms && $owner->code){
  293. $query = DB::raw(<<<sql
  294. INSERT INTO BAS_CUSTOMER(CUSTOMERID,CUSTOMER_TYPE,DESCR_C,ADDTIME,EDITTIME,ADDWHO)
  295. VALUES(?,?,?,TO_DATE(?,'yyyy-mm-dd hh24:mi:ss'),TO_DATE(?,'yyyy-mm-dd hh24:mi:ss'),?)
  296. sql
  297. );
  298. $date = date('Y-m-d H:i:s');
  299. DB::connection("oracle")->insert($query,[$owner->code,'OW',$owner->name,$date,$date,'WAS-'.(Auth::user() ? Auth::user()['name'] : 'SYSTEM')]);
  300. }
  301. return true;
  302. }
  303. public function syncUpdate($owner)
  304. {
  305. if (is_array($owner)){
  306. $owner = new Owner();
  307. foreach ($owner as $column=>$value){
  308. $owner[$column] = $value;
  309. }
  310. }
  311. if (is_numeric($owner)){
  312. $owner = Owner::query()->find($owner);
  313. if (!$owner)return false;
  314. }
  315. $sql = DB::raw(<<<sql
  316. update BAS_CUSTOMER set ACTIVE_FLAG = ?,EDITTIME = TO_DATE(?,'yyyy-mm-dd hh24:mi:ss'),EDITWHO = ? where CUSTOMERID = ? and CUSTOMER_TYPE = ?
  317. sql
  318. );
  319. $date = date('Y-m-d H:i:s');
  320. if ($owner && $owner->deleted_at){
  321. DB::connection("oracle")->update($sql,['N',$date,'WAS-'.(Auth::user() ? Auth::user()['name'] : 'SYSTEM'),$owner->code,'OW']);
  322. }
  323. if ($owner && $owner->deleted_at==null) {
  324. DB::connection("oracle")->update($sql,['Y',$date,'WAS-'.(Auth::user() ? Auth::user()['name'] : 'SYSTEM'),$owner->code,'OW']);
  325. }
  326. return true;
  327. }
  328. /**
  329. * 同步货主时创建权限
  330. *
  331. * @param array|Owner $owner
  332. */
  333. public function createAuthority($owner)
  334. {
  335. Authority::query()->create([
  336. 'name' => "_{$owner['id']}",
  337. 'alias_name' => "(货主:{$owner['name']})",
  338. 'remark' => "(key: _{$owner['id']})",
  339. ]);
  340. }
  341. /**
  342. * 停用货主时删除权限
  343. *
  344. * @param array|Owner $owner
  345. */
  346. public function deleteAuthority($owner)
  347. {
  348. $authorities = Authority::query()->where('name',"_{$owner['id']}")
  349. ->where("alias_name","like","(货主%")
  350. ->get(["id"]);
  351. $ids = array_column($authorities->toArray(),"id");
  352. DB::table("authority_role")->whereIn("id_authority",$ids)->delete();
  353. Authority::destroy($ids);
  354. }
  355. /**
  356. * 计费模型变动时更新货主中关联属性
  357. *
  358. * @param integer $ownerId
  359. *
  360. */
  361. public function refreshRelevance($ownerId)
  362. {
  363. $relevance = [];
  364. $sql = <<<sql
  365. SELECT 1 FROM owner_storage_price_models a
  366. LEFT JOIN owner_storage_price_model_owner b ON a.id = b.owner_storage_price_model_id
  367. LEFT JOIN owners c ON b.owner_id = c.id
  368. WHERE (a.operation IS NULL OR a.operation = '') AND c.id = ? LIMIT 1
  369. sql;
  370. if (DB::selectOne(DB::raw($sql),[$ownerId]))$relevance[] = 0;
  371. $sql = <<<sql
  372. SELECT 1 FROM owner_price_operations a
  373. LEFT JOIN owner_price_operation_owner b ON a.id = b.owner_price_operation_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[] = 1;
  378. $sql = <<<sql
  379. SELECT 1 FROM owner_price_expresses a
  380. LEFT JOIN owner_price_express_owner b ON a.id = b.owner_price_express_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[] = 2;
  385. $sql = <<<sql
  386. SELECT 1 FROM owner_price_logistics a
  387. LEFT JOIN owner_price_logistic_owner b ON a.id = b.owner_price_logistic_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[] = 3;
  392. $sql = <<<sql
  393. SELECT 1 FROM owner_price_direct_logistics a
  394. LEFT JOIN owner_price_direct_logistic_owner b ON a.id = b.owner_price_direct_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[] = 4;
  399. $sql = <<<sql
  400. SELECT 1 FROM owner_price_systems a LEFT JOIN owners b ON a.owner_id = b.id
  401. WHERE b.id = ? LIMIT 1
  402. sql;
  403. if (DB::selectOne(DB::raw($sql),[$ownerId]))$relevance[] = 5;
  404. Owner::query()->where("id",$ownerId)->update(["relevance"=>$relevance]);
  405. }
  406. /**
  407. * 税率变更时附加税率
  408. *
  409. * @param Owner|\stdClass $owner
  410. */
  411. public function attachTaxRate(Owner $owner)
  412. {
  413. OwnerStoragePriceModel::query()->whereHas("owners",function (Builder $query)use($owner){
  414. $query->where("id",$owner->id);
  415. })->whereNull("tax_rate_id")->update(["tax_rate_id"=>$owner->tax_rate_id]);
  416. OwnerPriceOperation::query()->whereHas("owners",function (Builder $query)use($owner){
  417. $query->where("id",$owner->id);
  418. })->whereNull("tax_rate_id")->update(["tax_rate_id"=>$owner->tax_rate_id]);
  419. OwnerPriceExpress::query()->whereHas("owners",function (Builder $query)use($owner){
  420. $query->where("id",$owner->id);
  421. })->whereNull("tax_rate_id")->update(["tax_rate_id"=>$owner->tax_rate_id]);
  422. OwnerPriceLogistic::query()->whereHas("owners",function (Builder $query)use($owner){
  423. $query->where("id",$owner->id);
  424. })->whereNull("tax_rate_id")->update(["tax_rate_id"=>$owner->tax_rate_id]);
  425. OwnerPriceDirectLogistic::query()->whereHas("owners",function (Builder $query)use($owner){
  426. $query->where("id",$owner->id);
  427. })->whereNull("tax_rate_id")->update(["tax_rate_id"=>$owner->tax_rate_id]);
  428. OwnerPriceSystem::query()->where("owner_id",$owner->id)->whereNull("tax_rate_id")
  429. ->update(["tax_rate_id"=>$owner->tax_rate_id]);
  430. }
  431. /**
  432. * 税率变更时取消税率
  433. *
  434. * @param Owner|\stdClass $owner
  435. */
  436. public function removeTaxRate(Owner $owner)
  437. {
  438. OwnerStoragePriceModel::query()->whereHas("owners",function (Builder $query)use($owner){
  439. $query->where("id",$owner->id);
  440. })->update(["tax_rate_id"=>null]);
  441. OwnerPriceOperation::query()->whereHas("owners",function (Builder $query)use($owner){
  442. $query->where("id",$owner->id);
  443. })->update(["tax_rate_id"=>null]);
  444. OwnerPriceExpress::query()->whereHas("owners",function (Builder $query)use($owner){
  445. $query->where("id",$owner->id);
  446. })->update(["tax_rate_id"=>null]);
  447. OwnerPriceLogistic::query()->whereHas("owners",function (Builder $query)use($owner){
  448. $query->where("id",$owner->id);
  449. })->update(["tax_rate_id"=>null]);
  450. OwnerPriceDirectLogistic::query()->whereHas("owners",function (Builder $query)use($owner){
  451. $query->where("id",$owner->id);
  452. })->update(["tax_rate_id"=>null]);
  453. OwnerPriceSystem::query()->where("owner_id",$owner->id)
  454. ->update(["tax_rate_id"=>null]);
  455. }
  456. }