OwnerService.php 25 KB

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