OwnerService.php 13 KB

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