OwnerService.php 24 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620
  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('UserService')->getPermittingOwnerIds(Auth::user());
  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. $user = Auth::user();
  166. return Owner::query()->whereIn('id',app('UserService')->getPermittingOwnerIds($user)??[])->get();
  167. }
  168. public function get(array $params, array $withs = null, bool $authority = true, bool $notShowSoftDelete = false, $user = null)
  169. {
  170. /** @var User $user */
  171. if ($user==null)$user = Auth::user();
  172. return Cache::remember(
  173. 'owner_'.md5(json_encode($params).json_encode($withs).$authority.$notShowSoftDelete.json_encode($user))
  174. ,config('cache.expirations.rarelyChange')
  175. ,function()use($params,$withs,$authority,$notShowSoftDelete,$user){
  176. $query = Owner::query();
  177. if ($withs)$query->with($withs);
  178. if ($authority&&$user){
  179. $ids = $user->getPermittingOwnerIdsAttribute();
  180. $query->whereIn("id",$ids);
  181. }
  182. if ($notShowSoftDelete) $query->whereNull('deleted_at');
  183. $query = $this->query($query,$params);
  184. return $query->get();
  185. });
  186. }
  187. public function paginate(array $params, array $withs = null, bool $authority = true, bool $notShowSoftDelete = false)
  188. {
  189. /** @var User $user */
  190. $user = Auth::user();
  191. $query = Owner::query();
  192. if ($withs)$query->with($withs);
  193. if ($authority){
  194. $ids = $user->getPermittingOwnerIdsAttribute();
  195. $query->whereIn("id",$ids);
  196. }
  197. if ($notShowSoftDelete) $query->whereNull('deleted_at');
  198. $query = $this->query($query,$params)->orderByDesc("id");
  199. return $query->paginate($params["paginate"] ?? 50);
  200. }
  201. private function query(Builder $builder, array $params)
  202. {
  203. foreach ($params as $column => $param){
  204. if ($column == 'paginate' || $column == 'page' || !$param)continue;
  205. if ($param === true){
  206. $builder->whereNotNull($column);
  207. continue;
  208. }
  209. if ($param === false){
  210. $builder->whereNull($column);
  211. continue;
  212. }
  213. if ($column == 'created_at_start'){
  214. $builder->where("created_at",">=",$param.":00");
  215. continue;
  216. }
  217. if ($column == 'created_at_end'){
  218. $builder->where("created_at","<=",$param.":59");
  219. continue;
  220. }
  221. if ($column == 'contract_number'){
  222. $builder->whereHas("contracts",function ($query)use($param){
  223. /** @var Builder $query */
  224. $query->where("contract_number","like",$param."%");
  225. });
  226. continue;
  227. }
  228. if ($column == 'using_type'){
  229. $builder->whereHas("ownerStoragePriceModels",function ($query)use($param){
  230. /** @var Builder $query */
  231. $query->where("using_type",$param);
  232. });
  233. continue;
  234. }
  235. if ($column == 'customers'){
  236. if (is_array($param))$builder->whereIn('customer_id',$param);
  237. else $builder->where('customer_id',$param);
  238. continue;
  239. }
  240. if ($column == 'ids'){
  241. if (is_array($param))$builder->whereIn('id',$param);
  242. else $builder->where('id',$param);
  243. continue;
  244. }
  245. if ($column == 'owners'){
  246. if (is_array($param))$builder->whereIn('owner_id',$param);
  247. else $builder->where('owner_id',$param);
  248. continue;
  249. }
  250. // if ($column == 'user_work_group'){
  251. // $builder->where("user_workgroup_id",$param);
  252. // continue;
  253. // }
  254. if ($column == 'kcGroup'){
  255. $builder->whereHas("departmentObligationOwner",function($query)use($param){
  256. $query->where('obligation_code','kc')->where('department_id',$param);
  257. });
  258. continue;
  259. }
  260. if ($column == 'jgGroup'){
  261. $builder->whereHas("departmentObligationOwner",function($query)use($param){
  262. $query->where('obligation_code','jg')->where('department_id',$param);
  263. });
  264. continue;
  265. }
  266. if ($column == 'fhGroup'){
  267. $builder->whereHas("departmentObligationOwner",function($query)use($param){
  268. $query->where('obligation_code','fh')->where('department_id',$param);
  269. });
  270. continue;
  271. }
  272. if ($column == 'thGroup'){
  273. $builder->whereHas("departmentObligationOwner",function($query)use($param){
  274. $query->where('obligation_code','th')->where('department_id',$param);
  275. });
  276. continue;
  277. }
  278. if ($column == 'shGroup'){
  279. $builder->whereHas("departmentObligationOwner",function($query)use($param){
  280. $query->where('obligation_code','sh')->where('department_id',$param);
  281. });
  282. continue;
  283. }
  284. if (is_array($param))$builder->whereIn($column,$param);
  285. else $builder->where($column,$param);
  286. }
  287. return $builder;
  288. }
  289. public function getOwnerByCodes($codes)
  290. {
  291. $collect = collect();
  292. if(count($codes) == 0)return $collect;
  293. foreach ($codes as $code) {
  294. $collect = $collect->push($this->getOwnerByCode($code));
  295. }
  296. return $collect;
  297. }
  298. public function getOwnerByCode($code){
  299. return Cache::remember("getOwnerByCode_{$code}", config('cache.expirations.owners'), function ()use($code){
  300. $owner = Owner::query()->where('code',$code)->first();
  301. if($owner) return $owner;
  302. $basCustomer = app('OracleBasCustomerService')->first(['Customer_Type'=>'OW','CustomerID'=>$code]);
  303. if(!$basCustomer)return null;
  304. if($basCustomer && $basCustomer['active_flag']=='Y') return Owner::query()
  305. ->create(['name'=>$basCustomer['descr_c'],'code'=>$basCustomer['customerid']]);
  306. $deleted_at=Carbon::now()->toDateTimeString();
  307. if($basCustomer && $basCustomer['active_flag']=='N') return Owner::query()
  308. ->create(['name'=>$basCustomer['descr_c'],'code'=>$basCustomer['customerid'],'deleted_at'=>$deleted_at]);
  309. });
  310. }
  311. public function codeGetOwner($code)
  312. {
  313. return app(CacheService::class)->getOrExecute("owner_".$code,function ()use($code){
  314. return Owner::query()->firstOrCreate(["code"=>$code],["code"=>$code,"name"=>$code]);
  315. });
  316. }
  317. /**
  318. * 向FLUX同步推送WAS本地录入信息
  319. *
  320. * @param array|Owner|integer $owner
  321. * @return bool
  322. */
  323. public function syncPush($owner)
  324. {
  325. if (is_array($owner)){
  326. $owner = new Owner();
  327. foreach ($owner as $column=>$value){
  328. $owner[$column] = $value;
  329. }
  330. }
  331. if (is_numeric($owner)){
  332. $owner = Owner::query()->find($owner);
  333. if (!$owner)return false;
  334. }
  335. $wms = DB::connection("oracle")->selectOne(DB::raw("SELECT CUSTOMERID FROM BAS_CUSTOMER WHERE CUSTOMER_TYPE = ? AND CUSTOMERID = ?"),["OW",$owner->code]);
  336. if (!$wms && $owner->code){
  337. $query = DB::raw(<<<sql
  338. INSERT INTO BAS_CUSTOMER(CUSTOMERID,CUSTOMER_TYPE,DESCR_C,ADDTIME,EDITTIME,ADDWHO)
  339. VALUES(?,?,?,TO_DATE(?,'yyyy-mm-dd hh24:mi:ss'),TO_DATE(?,'yyyy-mm-dd hh24:mi:ss'),?)
  340. sql
  341. );
  342. $date = date('Y-m-d H:i:s');
  343. DB::connection("oracle")->insert($query,[$owner->code,'OW',$owner->name,$date,$date,'WAS-'.(Auth::user() ? Auth::user()['name'] : 'SYSTEM')]);
  344. }
  345. return true;
  346. }
  347. public function syncUpdate($owner)
  348. {
  349. if (is_array($owner)){
  350. $owner = new Owner();
  351. foreach ($owner as $column=>$value){
  352. $owner[$column] = $value;
  353. }
  354. }
  355. if (is_numeric($owner)){
  356. $owner = Owner::query()->find($owner);
  357. if (!$owner)return false;
  358. }
  359. $sql = DB::raw(<<<sql
  360. update BAS_CUSTOMER set ACTIVE_FLAG = ?,EDITTIME = TO_DATE(?,'yyyy-mm-dd hh24:mi:ss'),EDITWHO = ? where CUSTOMERID = ? and CUSTOMER_TYPE = ?
  361. sql
  362. );
  363. $date = date('Y-m-d H:i:s');
  364. if ($owner && $owner->deleted_at){
  365. DB::connection("oracle")->update($sql,['N',$date,'WAS-'.(Auth::user() ? Auth::user()['name'] : 'SYSTEM'),$owner->code,'OW']);
  366. }
  367. if ($owner && $owner->deleted_at==null) {
  368. DB::connection("oracle")->update($sql,['Y',$date,'WAS-'.(Auth::user() ? Auth::user()['name'] : 'SYSTEM'),$owner->code,'OW']);
  369. }
  370. return true;
  371. }
  372. /**
  373. * 同步货主时创建权限
  374. *
  375. * @param array|Owner $owner
  376. */
  377. public function createAuthority($owner)
  378. {
  379. Authority::query()->create([
  380. 'name' => "_{$owner['id']}",
  381. 'alias_name' => "(货主:{$owner['name']})",
  382. 'remark' => "(key: _{$owner['id']})",
  383. ]);
  384. }
  385. /**
  386. * 停用货主时删除权限
  387. *
  388. * @param array|Owner $owner
  389. */
  390. public function deleteAuthority($owner)
  391. {
  392. $authorities = Authority::query()->where('name',"_{$owner['id']}")
  393. ->where("alias_name","like","(货主%")
  394. ->get(["id"]);
  395. $ids = array_column($authorities->toArray(),"id");
  396. DB::table("authority_role")->whereIn("id_authority",$ids)->delete();
  397. Authority::destroy($ids);
  398. }
  399. /**
  400. * 计费模型变动时更新货主中关联属性
  401. *
  402. * @param integer $ownerId
  403. *
  404. */
  405. public function refreshRelevance($ownerId)
  406. {
  407. $relevance = [];
  408. $sql = <<<sql
  409. SELECT 1 FROM owner_storage_price_models a
  410. LEFT JOIN owner_storage_price_model_owner b ON a.id = b.owner_storage_price_model_id
  411. LEFT JOIN owners c ON b.owner_id = c.id
  412. WHERE (a.operation IS NULL OR a.operation = '') AND c.id = ? LIMIT 1
  413. sql;
  414. if (DB::selectOne(DB::raw($sql),[$ownerId]))$relevance[] = 0;
  415. $sql = <<<sql
  416. SELECT 1 FROM owner_price_operations a
  417. LEFT JOIN owner_price_operation_owner b ON a.id = b.owner_price_operation_id
  418. LEFT JOIN owners c ON b.owner_id = c.id
  419. WHERE (a.operation IS NULL OR a.operation = '') AND c.id = ? LIMIT 1
  420. sql;
  421. if (DB::selectOne(DB::raw($sql),[$ownerId]))$relevance[] = 1;
  422. $sql = <<<sql
  423. SELECT 1 FROM owner_price_expresses a
  424. LEFT JOIN owner_price_express_owner b ON a.id = b.owner_price_express_id
  425. LEFT JOIN owners c ON b.owner_id = c.id
  426. WHERE (a.operation IS NULL OR a.operation = '') AND c.id = ? LIMIT 1
  427. sql;
  428. if (DB::selectOne(DB::raw($sql),[$ownerId]))$relevance[] = 2;
  429. $sql = <<<sql
  430. SELECT 1 FROM owner_price_logistics a
  431. LEFT JOIN owner_price_logistic_owner b ON a.id = b.owner_price_logistic_id
  432. LEFT JOIN owners c ON b.owner_id = c.id
  433. WHERE (a.operation IS NULL OR a.operation = '') AND c.id = ? LIMIT 1
  434. sql;
  435. if (DB::selectOne(DB::raw($sql),[$ownerId]))$relevance[] = 3;
  436. $sql = <<<sql
  437. SELECT 1 FROM owner_price_direct_logistics a
  438. LEFT JOIN owner_price_direct_logistic_owner b ON a.id = b.owner_price_direct_logistic_id
  439. LEFT JOIN owners c ON b.owner_id = c.id
  440. WHERE (a.operation IS NULL OR a.operation = '') AND c.id = ? LIMIT 1
  441. sql;
  442. if (DB::selectOne(DB::raw($sql),[$ownerId]))$relevance[] = 4;
  443. $sql = <<<sql
  444. SELECT 1 FROM owner_price_systems a LEFT JOIN owners b ON a.owner_id = b.id
  445. WHERE b.id = ? LIMIT 1
  446. sql;
  447. if (DB::selectOne(DB::raw($sql),[$ownerId]))$relevance[] = 5;
  448. Owner::query()->where("id",$ownerId)->update(["relevance"=>$relevance]);
  449. }
  450. /**
  451. * 税率变更时附加税率
  452. *
  453. * @param Owner|\stdClass $owner
  454. */
  455. public function attachTaxRate(Owner $owner)
  456. {
  457. OwnerStoragePriceModel::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. OwnerPriceOperation::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. OwnerPriceExpress::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. OwnerPriceLogistic::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. OwnerPriceDirectLogistic::query()->whereHas("owners",function (Builder $query)use($owner){
  470. $query->where("id",$owner->id);
  471. })->whereNull("tax_rate_id")->update(["tax_rate_id"=>$owner->tax_rate_id]);
  472. OwnerPriceSystem::query()->where("owner_id",$owner->id)->whereNull("tax_rate_id")
  473. ->update(["tax_rate_id"=>$owner->tax_rate_id]);
  474. }
  475. /**
  476. * 税率变更时取消税率
  477. *
  478. * @param Owner|\stdClass $owner
  479. */
  480. public function removeTaxRate(Owner $owner)
  481. {
  482. OwnerStoragePriceModel::query()->whereHas("owners",function (Builder $query)use($owner){
  483. $query->where("id",$owner->id);
  484. })->update(["tax_rate_id"=>null]);
  485. OwnerPriceOperation::query()->whereHas("owners",function (Builder $query)use($owner){
  486. $query->where("id",$owner->id);
  487. })->update(["tax_rate_id"=>null]);
  488. OwnerPriceExpress::query()->whereHas("owners",function (Builder $query)use($owner){
  489. $query->where("id",$owner->id);
  490. })->update(["tax_rate_id"=>null]);
  491. OwnerPriceLogistic::query()->whereHas("owners",function (Builder $query)use($owner){
  492. $query->where("id",$owner->id);
  493. })->update(["tax_rate_id"=>null]);
  494. OwnerPriceDirectLogistic::query()->whereHas("owners",function (Builder $query)use($owner){
  495. $query->where("id",$owner->id);
  496. })->update(["tax_rate_id"=>null]);
  497. OwnerPriceSystem::query()->where("owner_id",$owner->id)
  498. ->update(["tax_rate_id"=>null]);
  499. }
  500. /**
  501. * 获取税率 或 税费
  502. *
  503. * @param Model|\stdClass $model
  504. * @param int $ownerId
  505. * @param float|null $money
  506. *
  507. * @return float|null
  508. */
  509. public function getTaxRateFee(Model $model, int $ownerId, ?float $money = null):?float
  510. {
  511. $taxRate = null;
  512. if ($model->tax_rate_id){
  513. $model->loadMissing("taxRate");
  514. $taxRate = $model->taxRate;
  515. }
  516. if (!$taxRate){
  517. /** @var Model|\stdClass $owner */
  518. $owner = new Owner();
  519. $owner->id = $ownerId;
  520. $owner->load("taxRate");
  521. $taxRate = $owner->taxRate;
  522. }
  523. if (!$taxRate)return null;
  524. if ($money===null)return $taxRate->value;
  525. return $money*($taxRate->value/100);
  526. }
  527. public function changeManualBackStatus($id,$isManual)
  528. {
  529. $owner=Owner::query()->find($id);
  530. if ($isManual==0)$owner->update(['is_manual_back'=>1]);
  531. else $owner->update(['is_manual_back'=>0]);
  532. return $owner;
  533. }
  534. public function changeIntervalTime($id,$intervalTime)
  535. {
  536. $owner=Owner::query()->find($id);
  537. $owner->update(['interval_time'=>$intervalTime]);
  538. return $owner;
  539. }
  540. function getIdArr(?int $userId = null): array
  541. {
  542. if (!$userId)$userId = Auth::id();
  543. return array_column($this->getQuery($userId)->get()->toArray(),"id");
  544. }
  545. function getQuery(?int $userId = null): Builder
  546. {
  547. if (!$userId)$userId = Auth::id();
  548. $query = Owner::query()->select("owners.id");
  549. if (!app("UserService")->checkAdminIdentity($userId) && !app("AuthorityService")->checkAllOwner()){
  550. $query->whereHas("roles",function ($query)use($userId){
  551. $query->whereHas("users",function ($query)use($userId){
  552. $query->where("users.id",$userId);
  553. });
  554. });
  555. }
  556. return $query->whereNull("deleted_at");
  557. }
  558. public function combineOwners($owners)
  559. {
  560. foreach ($owners as $owner){
  561. $departmentObligationOwner=$owner->departmentObligationOwner??false;
  562. if (!$departmentObligationOwner)continue;
  563. foreach ($departmentObligationOwner as $item){
  564. if ($item->obligation_code=='kc'){
  565. $owner->kc=$item->department_id;$owner->kcGroup=$item->department?$item->department->name:'';
  566. }
  567. if ($item->obligation_code=='jg'){
  568. $owner->jg=$item->department_id;$owner->jgGroup=$item->department?$item->department->name:'';
  569. }
  570. if ($item->obligation_code=='th'){
  571. $owner->th=$item->department_id;$owner->thGroup=$item->department?$item->department->name:'';
  572. }
  573. if ($item->obligation_code=='sh'){
  574. $owner->sh=$item->department_id;$owner->shGroup=$item->department?$item->department->name:'';
  575. }
  576. if ($item->obligation_code=='fh'){
  577. $owner->fh=$item->department_id;$owner->fhGroup=$item->department?$item->department->name:'';
  578. }
  579. }
  580. }
  581. return $owners;
  582. }
  583. }