OwnerService.php 15 KB

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