OwnerService.php 13 KB

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