OwnerService.php 25 KB

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