OwnerService.php 24 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627
  1. <?php
  2. namespace App\Services;
  3. use App\Authority;
  4. use App\Interfaces\UserFilter;
  5. use App\OracleBasCustomer;
  6. use App\Owner;
  7. use App\OwnerPriceDirectLogistic;
  8. use App\OwnerPriceExpress;
  9. use App\OwnerPriceLogistic;
  10. use App\OwnerPriceOperation;
  11. use App\OwnerPriceSystem;
  12. use App\OwnerStoragePriceModel;
  13. use App\Services\common\BatchUpdateService;
  14. use App\User;
  15. use Carbon\Carbon;
  16. use Doctrine\DBAL\Exception\DatabaseObjectExistsException;
  17. use Illuminate\Database\Eloquent\Builder;
  18. use Illuminate\Database\Eloquent\Model;
  19. use Illuminate\Support\Collection;
  20. use Illuminate\Support\Facades\Auth;
  21. use Illuminate\Support\Facades\Cache;
  22. use Illuminate\Support\Facades\DB;
  23. use App\Traits\ServiceAppAop;
  24. class OwnerService implements UserFilter
  25. {
  26. use ServiceAppAop;
  27. protected $modelClass=Owner::class;
  28. /** @var CacheService $cacheService */
  29. private $cacheService;
  30. function __construct(){
  31. $this->instant($this->cacheService,'CacheService');
  32. }
  33. /*
  34. * array | string $column
  35. * 默认一些select字段,可传递string 或 array来指定select字段
  36. */
  37. public function getIntersectPermitting(array $column = ['id', 'name'])
  38. {
  39. $ownerIds=app('OwnerService')->getIdArr();
  40. return $this->cacheService->getOrExecute('OwnersAll_IdName'.md5(json_encode($column).json_encode($ownerIds)),function()use($column,$ownerIds){
  41. if(empty($ownerIds))return new Collection();
  42. return Owner::query()->select($column)->whereIn('id', $ownerIds)->whereNull('deleted_at')->get();
  43. },config('cache.expirations.owners'));
  44. }
  45. public function getSelection($column = ['id'])
  46. {
  47. return $this->cacheService->getOrExecute('OwnersAll_'.md5(json_encode($column)),function()use($column){
  48. return Owner::filterAuthorities()->select($column)->get();
  49. },config('cache.expirations.owners'));
  50. }
  51. /**
  52. *同步WMS全部货主至WAS
  53. */
  54. public function syncOwnersData()
  55. {
  56. $basCustomers = OracleBasCustomer::query()
  57. ->select('CUSTOMERID', 'DESCR_C')
  58. ->where('DESCR_C', 'not like', '%换ERP%')
  59. ->where('DESCR_C', 'not like', '%退仓%')
  60. ->where('CUSTOMER_TYPE', 'OW')
  61. ->get();
  62. $ownerCount = Owner::query()->count();
  63. if (count($basCustomers) == $ownerCount) return null;
  64. foreach ($basCustomers as $basCustomer) {
  65. $owner = Owner::query()->where('code', $basCustomer['customerid'])->first();
  66. if (!isset($owner)){
  67. Owner::query()->create([
  68. 'code' => $basCustomer['customerid'],
  69. 'name' => $basCustomer['descr_c'],
  70. 'created_at' => Carbon::now()->format('Y-m-d H:i:s'),
  71. ]);
  72. continue;
  73. }
  74. if ($owner['name']!=$basCustomer['descr_c']){
  75. $owner->update([
  76. 'code' => $basCustomer['customerid'],
  77. 'name' => $basCustomer['descr_c'],
  78. ]);
  79. }
  80. }
  81. $owners = Owner::query()->select('id', 'name')->get();
  82. return $owners;
  83. }
  84. public function first(array $params, array $rules =[]){
  85. return $this->cacheService->getOrExecute('OwnersFirst'.md5(json_encode($params),json_encode($rules)),function()use($params,$rules){
  86. $owner = Owner::query();
  87. foreach ($params as $column => $value){
  88. if (!isset($rules[$column]))$owner->where($column, $value);
  89. else{
  90. switch ($rules[$column]){
  91. case "or":
  92. $owner->orWhere($column, $value);
  93. break;
  94. }
  95. }
  96. }
  97. return $owner->first();
  98. },config('cache.expirations.rarelyChange'));
  99. }
  100. public function find($id, $with = [])
  101. {
  102. return Owner::query()->with($with)->find($id);
  103. }
  104. public function update(Owner $owner, array $values, array $related = [])
  105. {
  106. if ($related["ownerStoragePriceModels"] ?? false)$owner->ownerStoragePriceModels()->sync($related["ownerStoragePriceModels"]);
  107. return $owner->update($values);
  108. }
  109. public function create(array $params, array $related = []){
  110. /** @var Owner $owner */
  111. $owner = Owner::query()->create($params);
  112. if ($related["ownerStoragePriceModels"] ?? false)$owner->ownerStoragePriceModels()->syncWithoutDetaching($related["ownerStoragePriceModels"]);
  113. return $owner;
  114. }
  115. public function firstOrCreate(array $params, array $values = null){
  116. if (!$values) return Owner::query()->whereNull("deleted_at")->firstOrCreate($params);
  117. return Owner::query()->whereNull("deleted_at")->firstOrCreate($params,$values);
  118. }
  119. public function 获取订单跟踪的货主(){
  120. return Owner::query()->with('orderTrackingOwner')->whereHas('orderTrackingOwner',function($query){
  121. $query->where('status','启用');
  122. })->get();
  123. }
  124. public function getByWmsOrders($orderHeaders){
  125. $customerIds = array_unique(data_get($orderHeaders,'*.customerid'));
  126. $customerIds = array_diff($customerIds,[null,'','*']);
  127. $owners = Owner::query()->whereIn('code',$customerIds)->get();
  128. if($owners->count() < count($customerIds)){
  129. $customerIds = array_diff($customerIds,data_get($owners,'*.code'));
  130. $owner_list = $this->createByWmsCustomerIds($customerIds);
  131. $owners=$owners->concat($owner_list);
  132. }
  133. return $owners;
  134. }
  135. public function createByWmsCustomerIds($codes){
  136. if(!$codes) {return [];}
  137. $basCustomer = OracleBasCustomer::query()
  138. ->where('Customer_Type','OW')
  139. ->whereIn('CustomerID', $codes)
  140. ->get();
  141. $insert_params = [];
  142. $created_at = Carbon::now()->format('Y-m-d H:i:s');
  143. foreach ($basCustomer as $item) {
  144. $insert_params[] = [
  145. 'code' => $item->customerid,
  146. 'name' => $item->descr_c,
  147. 'created_at' => $created_at,
  148. ];
  149. }
  150. try {
  151. if (count($insert_params) > 0) {
  152. $this->insert($insert_params);
  153. app('LogService')->log(__METHOD__, __FUNCTION__, '批量创建 owner ' . count($insert_params) . json_encode($insert_params) );
  154. }
  155. } catch (\Exception $e) {
  156. app('LogService')->log(__METHOD__, __FUNCTION__, '批量创建 owner error' . json_encode($insert_params) . '||' . $e->getMessage() . '||' . $e->getTraceAsString());
  157. } finally {
  158. return Owner::query()->whereIn('code', $codes)->get();
  159. }
  160. }
  161. public function insert($fillables){
  162. return Owner::query()->insert($fillables);
  163. }
  164. public function getAuthorizedOwners(){
  165. return Owner::query()->whereIn('id',app("OwnerService")->getQuery())->get();
  166. }
  167. public function get(array $params, array $withs = null, bool $authority = true, bool $notShowSoftDelete = false, $user = null)
  168. {
  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){
  173. $query = $this->query($this->getQueryConstructor($withs, $authority, $notShowSoftDelete),$params);
  174. return $query->get();
  175. });
  176. }
  177. private function getQueryConstructor(array $withs, bool $authority, bool $notShowSoftDelete) :Builder
  178. {
  179. $query = Owner::query();
  180. if ($withs)$query->with($withs);
  181. if ($authority){
  182. $ids = $this->getIdArr();
  183. if (count($ids) > 0){
  184. $query->whereIn("id", $ids);
  185. } else {
  186. $query->where("id", 0);
  187. }
  188. }
  189. if ($notShowSoftDelete) $query->whereNull('deleted_at');
  190. return $query;
  191. }
  192. public function paginate(array $params, array $withs = null, bool $authority = true, bool $notShowSoftDelete = false)
  193. {
  194. $query = $this->query($this->getQueryConstructor($withs, $authority, $notShowSoftDelete),$params)->
  195. 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 ($column == 'user_work_group'){
  248. // $builder->where("user_workgroup_id",$param);
  249. // continue;
  250. // }
  251. if ($column == 'kcGroup'){
  252. $builder->whereHas("departmentObligationOwner",function($query)use($param){
  253. $query->where('obligation_code','kc')->where('department_id',$param);
  254. });
  255. continue;
  256. }
  257. if ($column == 'jgGroup'){
  258. $builder->whereHas("departmentObligationOwner",function($query)use($param){
  259. $query->where('obligation_code','jg')->where('department_id',$param);
  260. });
  261. continue;
  262. }
  263. if ($column == 'fhGroup'){
  264. $builder->whereHas("departmentObligationOwner",function($query)use($param){
  265. $query->where('obligation_code','fh')->where('department_id',$param);
  266. });
  267. continue;
  268. }
  269. if ($column == 'thGroup'){
  270. $builder->whereHas("departmentObligationOwner",function($query)use($param){
  271. $query->where('obligation_code','th')->where('department_id',$param);
  272. });
  273. continue;
  274. }
  275. if ($column == 'shGroup'){
  276. $builder->whereHas("departmentObligationOwner",function($query)use($param){
  277. $query->where('obligation_code','sh')->where('department_id',$param);
  278. });
  279. continue;
  280. }
  281. if (is_array($param))$builder->whereIn($column,$param);
  282. else $builder->where($column,$param);
  283. }
  284. return $builder;
  285. }
  286. public function getOwnerByCodes($codes)
  287. {
  288. $collect = collect();
  289. if(count($codes) == 0)return $collect;
  290. foreach ($codes as $code) {
  291. $collect = $collect->push($this->getOwnerByCode($code));
  292. }
  293. return $collect;
  294. }
  295. public function getOwnerByCode($code){
  296. return Cache::remember("getOwnerByCode_{$code}", config('cache.expirations.owners'), function ()use($code){
  297. $owner = Owner::query()->where('code',$code)->first();
  298. if($owner) return $owner;
  299. $basCustomer = app('OracleBasCustomerService')->first(['Customer_Type'=>'OW','CustomerID'=>$code]);
  300. if(!$basCustomer)return null;
  301. if($basCustomer && $basCustomer['active_flag']=='Y') return Owner::query()
  302. ->create(['name'=>$basCustomer['descr_c'],'code'=>$basCustomer['customerid']]);
  303. $deleted_at=Carbon::now()->toDateTimeString();
  304. if($basCustomer && $basCustomer['active_flag']=='N') return Owner::query()
  305. ->create(['name'=>$basCustomer['descr_c'],'code'=>$basCustomer['customerid'],'deleted_at'=>$deleted_at]);
  306. });
  307. }
  308. public function codeGetOwner($code)
  309. {
  310. return app(CacheService::class)->getOrExecute("owner_".$code,function ()use($code){
  311. return Owner::query()->firstOrCreate(["code"=>$code],["code"=>$code,"name"=>$code]);
  312. });
  313. }
  314. /**
  315. * 向FLUX同步推送WAS本地录入信息
  316. *
  317. * @param array|Owner|integer $owner
  318. * @return bool
  319. */
  320. public function syncPush($owner)
  321. {
  322. if (is_array($owner)){
  323. $owner = new Owner();
  324. foreach ($owner as $column=>$value){
  325. $owner[$column] = $value;
  326. }
  327. }
  328. if (is_numeric($owner)){
  329. $owner = Owner::query()->find($owner);
  330. if (!$owner)return false;
  331. }
  332. $wms = DB::connection("oracle")->selectOne(DB::raw("SELECT CUSTOMERID FROM BAS_CUSTOMER WHERE CUSTOMER_TYPE = ? AND CUSTOMERID = ?"),["OW",$owner->code]);
  333. if (!$wms && $owner->code){
  334. $query = DB::raw(<<<sql
  335. INSERT INTO BAS_CUSTOMER(CUSTOMERID,CUSTOMER_TYPE,DESCR_C,ADDTIME,EDITTIME,ADDWHO)
  336. VALUES(?,?,?,TO_DATE(?,'yyyy-mm-dd hh24:mi:ss'),TO_DATE(?,'yyyy-mm-dd hh24:mi:ss'),?)
  337. sql
  338. );
  339. $date = date('Y-m-d H:i:s');
  340. DB::connection("oracle")->insert($query,[$owner->code,'OW',$owner->name,$date,$date,'WAS-'.(Auth::user() ? Auth::user()['name'] : 'SYSTEM')]);
  341. }
  342. return true;
  343. }
  344. public function syncUpdate($owner)
  345. {
  346. if (is_array($owner)){
  347. $owner = new Owner();
  348. foreach ($owner as $column=>$value){
  349. $owner[$column] = $value;
  350. }
  351. }
  352. if (is_numeric($owner)){
  353. $owner = Owner::query()->find($owner);
  354. if (!$owner)return false;
  355. }
  356. $sql = DB::raw(<<<sql
  357. update BAS_CUSTOMER set ACTIVE_FLAG = ?,EDITTIME = TO_DATE(?,'yyyy-mm-dd hh24:mi:ss'),EDITWHO = ? where CUSTOMERID = ? and CUSTOMER_TYPE = ?
  358. sql
  359. );
  360. $date = date('Y-m-d H:i:s');
  361. if ($owner && $owner->deleted_at){
  362. DB::connection("oracle")->update($sql,['N',$date,'WAS-'.(Auth::user() ? Auth::user()['name'] : 'SYSTEM'),$owner->code,'OW']);
  363. }
  364. if ($owner && $owner->deleted_at==null) {
  365. DB::connection("oracle")->update($sql,['Y',$date,'WAS-'.(Auth::user() ? Auth::user()['name'] : 'SYSTEM'),$owner->code,'OW']);
  366. }
  367. return true;
  368. }
  369. /**
  370. * 同步货主时创建权限
  371. *
  372. * @param array|Owner $owner
  373. */
  374. public function createAuthority($owner)
  375. {
  376. Authority::query()->create([
  377. 'name' => "_{$owner['id']}",
  378. 'alias_name' => "(货主:{$owner['name']})",
  379. 'remark' => "(key: _{$owner['id']})",
  380. ]);
  381. }
  382. /**
  383. * 停用货主时删除权限
  384. *
  385. * @param array|Owner $owner
  386. */
  387. public function deleteAuthority($owner)
  388. {
  389. $authorities = Authority::query()->where('name',"_{$owner['id']}")
  390. ->where("alias_name","like","(货主%")
  391. ->get(["id"]);
  392. $ids = array_column($authorities->toArray(),"id");
  393. DB::table("authority_role")->whereIn("id_authority",$ids)->delete();
  394. Authority::destroy($ids);
  395. }
  396. /**
  397. * 计费模型变动时更新货主中关联属性
  398. *
  399. * @param integer $ownerId
  400. *
  401. */
  402. public function refreshRelevance($ownerId)
  403. {
  404. $relevance = [];
  405. $sql = <<<sql
  406. SELECT 1 FROM owner_storage_price_models a
  407. LEFT JOIN owner_storage_price_model_owner b ON a.id = b.owner_storage_price_model_id
  408. LEFT JOIN owners c ON b.owner_id = c.id
  409. WHERE (a.operation IS NULL OR a.operation = '') AND c.id = ? LIMIT 1
  410. sql;
  411. if (DB::selectOne(DB::raw($sql),[$ownerId]))$relevance[] = 0;
  412. $sql = <<<sql
  413. SELECT 1 FROM owner_price_operations a
  414. LEFT JOIN owner_price_operation_owner b ON a.id = b.owner_price_operation_id
  415. LEFT JOIN owners c ON b.owner_id = c.id
  416. WHERE (a.operation IS NULL OR a.operation = '') AND c.id = ? LIMIT 1
  417. sql;
  418. if (DB::selectOne(DB::raw($sql),[$ownerId]))$relevance[] = 1;
  419. $sql = <<<sql
  420. SELECT 1 FROM owner_price_expresses a
  421. LEFT JOIN owner_price_express_owner b ON a.id = b.owner_price_express_id
  422. LEFT JOIN owners c ON b.owner_id = c.id
  423. WHERE (a.operation IS NULL OR a.operation = '') AND c.id = ? LIMIT 1
  424. sql;
  425. if (DB::selectOne(DB::raw($sql),[$ownerId]))$relevance[] = 2;
  426. $sql = <<<sql
  427. SELECT 1 FROM owner_price_logistics a
  428. LEFT JOIN owner_price_logistic_owner b ON a.id = b.owner_price_logistic_id
  429. LEFT JOIN owners c ON b.owner_id = c.id
  430. WHERE (a.operation IS NULL OR a.operation = '') AND c.id = ? LIMIT 1
  431. sql;
  432. if (DB::selectOne(DB::raw($sql),[$ownerId]))$relevance[] = 3;
  433. $sql = <<<sql
  434. SELECT 1 FROM owner_price_direct_logistics a
  435. LEFT JOIN owner_price_direct_logistic_owner b ON a.id = b.owner_price_direct_logistic_id
  436. LEFT JOIN owners c ON b.owner_id = c.id
  437. WHERE (a.operation IS NULL OR a.operation = '') AND c.id = ? LIMIT 1
  438. sql;
  439. if (DB::selectOne(DB::raw($sql),[$ownerId]))$relevance[] = 4;
  440. $sql = <<<sql
  441. SELECT 1 FROM owner_price_systems a LEFT JOIN owners b ON a.owner_id = b.id
  442. WHERE b.id = ? LIMIT 1
  443. sql;
  444. if (DB::selectOne(DB::raw($sql),[$ownerId]))$relevance[] = 5;
  445. Owner::query()->where("id",$ownerId)->update(["relevance"=>$relevance]);
  446. }
  447. /**
  448. * 税率变更时附加税率
  449. *
  450. * @param Owner|\stdClass $owner
  451. */
  452. public function attachTaxRate(Owner $owner)
  453. {
  454. OwnerStoragePriceModel::query()->whereHas("owners",function (Builder $query)use($owner){
  455. $query->where("id",$owner->id);
  456. })->whereNull("tax_rate_id")->update(["tax_rate_id"=>$owner->tax_rate_id]);
  457. OwnerPriceOperation::query()->whereHas("owners",function (Builder $query)use($owner){
  458. $query->where("id",$owner->id);
  459. })->whereNull("tax_rate_id")->update(["tax_rate_id"=>$owner->tax_rate_id]);
  460. OwnerPriceExpress::query()->whereHas("owners",function (Builder $query)use($owner){
  461. $query->where("id",$owner->id);
  462. })->whereNull("tax_rate_id")->update(["tax_rate_id"=>$owner->tax_rate_id]);
  463. OwnerPriceLogistic::query()->whereHas("owners",function (Builder $query)use($owner){
  464. $query->where("id",$owner->id);
  465. })->whereNull("tax_rate_id")->update(["tax_rate_id"=>$owner->tax_rate_id]);
  466. OwnerPriceDirectLogistic::query()->whereHas("owners",function (Builder $query)use($owner){
  467. $query->where("id",$owner->id);
  468. })->whereNull("tax_rate_id")->update(["tax_rate_id"=>$owner->tax_rate_id]);
  469. OwnerPriceSystem::query()->where("owner_id",$owner->id)->whereNull("tax_rate_id")
  470. ->update(["tax_rate_id"=>$owner->tax_rate_id]);
  471. }
  472. /**
  473. * 税率变更时取消税率
  474. *
  475. * @param Owner|\stdClass $owner
  476. */
  477. public function removeTaxRate(Owner $owner)
  478. {
  479. OwnerStoragePriceModel::query()->whereHas("owners",function (Builder $query)use($owner){
  480. $query->where("id",$owner->id);
  481. })->update(["tax_rate_id"=>null]);
  482. OwnerPriceOperation::query()->whereHas("owners",function (Builder $query)use($owner){
  483. $query->where("id",$owner->id);
  484. })->update(["tax_rate_id"=>null]);
  485. OwnerPriceExpress::query()->whereHas("owners",function (Builder $query)use($owner){
  486. $query->where("id",$owner->id);
  487. })->update(["tax_rate_id"=>null]);
  488. OwnerPriceLogistic::query()->whereHas("owners",function (Builder $query)use($owner){
  489. $query->where("id",$owner->id);
  490. })->update(["tax_rate_id"=>null]);
  491. OwnerPriceDirectLogistic::query()->whereHas("owners",function (Builder $query)use($owner){
  492. $query->where("id",$owner->id);
  493. })->update(["tax_rate_id"=>null]);
  494. OwnerPriceSystem::query()->where("owner_id",$owner->id)
  495. ->update(["tax_rate_id"=>null]);
  496. }
  497. /**
  498. * 获取税率 或 税费
  499. *
  500. * @param Model|\stdClass $model
  501. * @param int $ownerId
  502. * @param float|null $money
  503. *
  504. * @return float|null
  505. */
  506. public function getTaxRateFee(Model $model, int $ownerId, ?float $money = null):?float
  507. {
  508. $taxRate = null;
  509. if ($model->tax_rate_id){
  510. $model->loadMissing("taxRate");
  511. $taxRate = $model->taxRate;
  512. }
  513. if (!$taxRate){
  514. /** @var Model|\stdClass $owner */
  515. $owner = new Owner();
  516. $owner->id = $ownerId;
  517. $owner->load("taxRate");
  518. $taxRate = $owner->taxRate;
  519. }
  520. if (!$taxRate)return null;
  521. if ($money===null)return $taxRate->value;
  522. return $money*($taxRate->value/100);
  523. }
  524. public function changeManualBackStatus($id,$isManual)
  525. {
  526. $owner=Owner::query()->find($id);
  527. if ($isManual==0)$owner->update(['is_manual_back'=>1]);
  528. else $owner->update(['is_manual_back'=>0]);
  529. return $owner;
  530. }
  531. public function changeIntervalTime($id,$intervalTime)
  532. {
  533. $owner=Owner::query()->find($id);
  534. $owner->update(['interval_time'=>$intervalTime]);
  535. return $owner;
  536. }
  537. function getIdArr(?int $userId = null): array
  538. {
  539. if (!$userId)$userId = Auth::id();
  540. return $this->cacheService->getOrExecute("USER.{$userId}.OWNER.ID",function()use($userId){
  541. return array_column($this->getQuery($userId)->get()->toArray(),"id");
  542. });
  543. }
  544. function getCodeArr(?int $userId): array
  545. {
  546. $column = "code";
  547. if (!$userId)$userId = Auth::id();
  548. return $this->cacheService->getOrExecute("USER.{$userId}.OWNER.CODE",function()use($userId, $column){
  549. return array_column($this->getQuery($userId, $column)->get()->toArray(),$column);
  550. });
  551. }
  552. function getQuery(?int $userId = null, $column = "id"): Builder
  553. {
  554. if (!$userId)$userId = Auth::id();
  555. $query = Owner::query()->select("owners.".$column);
  556. if (!app("UserService")->checkAdminIdentity($userId) && !app("AuthorityService")->checkAllOwner($userId)){
  557. //$query->whereHas("roles",function ($query)use($userId){
  558. $query->whereHas("users",function ($query)use($userId){
  559. $query->where("users.id",$userId);
  560. });
  561. //});
  562. }
  563. return $query->whereNull("deleted_at");
  564. }
  565. public function combineOwners($owners)
  566. {
  567. foreach ($owners as $owner){
  568. $departmentObligationOwner=$owner->departmentObligationOwner??false;
  569. if (!$departmentObligationOwner)continue;
  570. foreach ($departmentObligationOwner as $item){
  571. if ($item->obligation_code=='kc'){
  572. $owner->kc=$item->department_id;$owner->kcGroup=$item->department?$item->department->name:'';
  573. }
  574. if ($item->obligation_code=='jg'){
  575. $owner->jg=$item->department_id;$owner->jgGroup=$item->department?$item->department->name:'';
  576. }
  577. if ($item->obligation_code=='th'){
  578. $owner->th=$item->department_id;$owner->thGroup=$item->department?$item->department->name:'';
  579. }
  580. if ($item->obligation_code=='sh'){
  581. $owner->sh=$item->department_id;$owner->shGroup=$item->department?$item->department->name:'';
  582. }
  583. if ($item->obligation_code=='fh'){
  584. $owner->fh=$item->department_id;$owner->fhGroup=$item->department?$item->department->name:'';
  585. }
  586. }
  587. }
  588. return $owners;
  589. }
  590. }