CloudStockAgentGoods.php 20 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490
  1. <?php
  2. namespace addons\CloudStock\common\models;
  3. use addons\CloudStock\common\enums\CloudStockEnum;
  4. use addons\CloudStock\common\events\order\CloudStockChangeEvent;
  5. use common\enums\StatusEnum;
  6. use common\models\base\BaseActiveRecord;
  7. use common\models\goods\Goods;
  8. use common\helpers\csv\CsvImportForm;
  9. use common\enums\RabbitMqEnum;
  10. use common\models\user\User;
  11. use Yii;
  12. use yii\db\Exception;
  13. /**
  14. * This is the model class for table "{{%addons_cloud_stock_agent_goods".
  15. *
  16. * @property int $id
  17. * @property int $mall_id 商城id
  18. * @property int $user_id 用户id
  19. * @property int $goods_id 商品id
  20. * @property int $num 库存数量
  21. * @property int $status 状态[-1:删除;0:禁用;1启用]
  22. * @property int $created_at
  23. * @property int $updated_at
  24. */
  25. class CloudStockAgentGoods extends BaseActiveRecord
  26. {
  27. /**
  28. * {@inheritdoc}
  29. */
  30. public static function tableName()
  31. {
  32. return '{{%addons_cloud_stock_agent_goods}}';
  33. }
  34. /**
  35. * {@inheritdoc}
  36. */
  37. public function rules()
  38. {
  39. return [
  40. [['mall_id', 'user_id', 'goods_id', 'num', 'status', 'created_at', 'updated_at'], 'integer'],
  41. [['goods_id'], 'required'],
  42. ];
  43. }
  44. /**
  45. * {@inheritdoc}
  46. */
  47. public function attributeLabels()
  48. {
  49. return [
  50. 'id' => 'ID',
  51. 'mall_id' => '商城id',
  52. 'user_id' => '用户id',
  53. 'goods_id' => '商品id',
  54. 'num' => '库存数量',
  55. 'status' => '状态[-1:删除;0:禁用;1启用]',
  56. 'created_at' => 'Created At',
  57. 'updated_at' => 'Updated At',
  58. ];
  59. }
  60. public static $head_list = [
  61. '0' => [
  62. 'field' => 'serial_number',
  63. 'field_name' => '序号',
  64. ],
  65. '1' => [
  66. 'field' => 'user_id',
  67. 'field_name' => '用户id',
  68. ],
  69. '2' => [
  70. 'field' => 'goods_id',
  71. 'field_name' => '商品id',
  72. ],
  73. '3' => [
  74. 'field' => 'num',
  75. 'field_name' => '数量',
  76. ]
  77. ];
  78. public static $max_count = 5000;
  79. public static $column_num = 4;
  80. public function getGoods()
  81. {
  82. return $this->hasOne(Goods::class, ['id' => 'goods_id'])->select(['id', 'goods_name', 'cover_pic']);
  83. }
  84. public static function setData(int $mall_id, array $data)
  85. {
  86. if (!empty($data['id'])) {
  87. $model = self::findOne(['mall_id' => $mall_id, 'status' => StatusEnum::ENABLED, 'id' => $data['id']]);
  88. } else {
  89. $model = new self();
  90. $model->loadDefaultValues();
  91. $model->mall_id = $mall_id;
  92. }
  93. foreach ($data as $key => $val) {
  94. $model->$key = $val;
  95. }
  96. // dd($model);
  97. if (!$model->save()) {
  98. self::$static_error = '保存数据失败:' . $model->getErrorMessage();
  99. return false;
  100. }
  101. return $model;
  102. }
  103. public static function addData(array $params, &$increase_detail)
  104. {
  105. try {
  106. if (!empty($params['mall_id']) && !empty($params['user_id']) && !empty($params['goods_id'])) {
  107. $model = self::findOne(['mall_id' => $params['mall_id'], 'user_id' => $params['user_id'], 'goods_id' => $params['goods_id'], 'status' => [StatusEnum::ENABLED, StatusEnum::DISABLED]]);
  108. if (empty($model)) {
  109. $model = new self();
  110. $model->loadDefaultValues();
  111. if (!$model->load($params, '')) throw new \Exception($model->getErrorMessage());
  112. } else {
  113. var_dump('加之前user_id' . $params['user_id'] . ':num:' . $model->num);
  114. var_dump('加多少user_id' . $params['user_id'] . ':num:' . $params['num']);
  115. $model->num += $params['num'];
  116. }
  117. } else {
  118. $model = new self();
  119. $model->loadDefaultValues();
  120. if (!$model->load($params, '')) throw new \Exception($model->getErrorMessage());
  121. }
  122. if (!$model->save()) throw new \Exception($model->getErrorMessage());
  123. var_dump('加之后user_id' . $params['user_id'] . ':num:' . $model->num);
  124. $param = [
  125. 'mall_id' => $params['mall_id'],
  126. 'goods_id' => $params['goods_id'],
  127. 'user_id' => $params['user_id'],
  128. 'changes_dir' => $params['changes_dir'],
  129. 'order_id' => $params['order_id'],
  130. 'num' => $params['num'],
  131. 'order_type' => $params['order_type'],
  132. 'changes_type' => $params['changes_type'],
  133. ];
  134. $stock_log = CloudStockGoodsStockLog::setData($param['mall_id'], $param);
  135. if ($stock_log == false) throw new Exception(CloudStockGoodsStockLog::getStaticError());
  136. $param = [
  137. 'stock_log_id' => $stock_log->id,
  138. 'user_id' => $params['user_id'],
  139. 'num' => $params['num'],
  140. 'changes_type' => $params['changes_type'],
  141. 'goods_id' => $params['goods_id'],
  142. 'mall_id' => $params['mall_id'],
  143. 'order_id' => $params['order_id'],
  144. ];
  145. $increase_detail = CloudStockIncreaseDetail::setData($param);
  146. if ($increase_detail == false) throw new Exception(CloudStockIncreaseDetail::getStaticError());
  147. //触发库存变动事件
  148. $event = new CloudStockChangeEvent($params['mall_id']);
  149. $event_data = [
  150. 'id' => $increase_detail->id,
  151. 'type' => CloudStockEnum::STOCK_CHANGE_ADD,
  152. 'mall_id' => $params['mall_id'],
  153. ];
  154. \Yii::$app->services->events->dispatch($event, $event_data, $event->listeners);
  155. return $model;
  156. } catch (\Exception $e) {
  157. self::$static_error = $e->getMessage();
  158. return false;
  159. }
  160. }
  161. public static function subData(array $params)
  162. {
  163. try {
  164. if (!empty($params['mall_id']) && !empty($params['user_id']) && !empty($params['goods_id'])) {
  165. $model = self::findOne(['mall_id' => $params['mall_id'], 'user_id' => $params['user_id'], 'goods_id' => $params['goods_id'], 'status' => [StatusEnum::ENABLED, StatusEnum::DISABLED]]);
  166. if (empty($model)) {
  167. $model = new self();
  168. $model->loadDefaultValues();
  169. if (!$model->load($params, '')) throw new \Exception($model->getErrorMessage());
  170. } else {
  171. $model->num -= $params['num'];
  172. }
  173. } else {
  174. $model = new self();
  175. $model->loadDefaultValues();
  176. if (!$model->load($params, '')) throw new \Exception($model->getErrorMessage());
  177. }
  178. if (!$model->save()) throw new \Exception($model->getErrorMessage());
  179. $params = [
  180. 'stock_log_id' => isset($params['stock_log_id']) ? $params['stock_log_id'] : 0,
  181. 'user_id' => $params['user_id'],
  182. 'num' => $params['num'],
  183. 'not_yet_num' => 0,
  184. 'changes_type' => $params['changes_type'],
  185. 'order_id' => $params['order_id'],
  186. 'goods_id' => $params['goods_id'],
  187. 'mall_id' => $params['mall_id'],
  188. ];
  189. $res = CloudStockDeductionDetail::setData($params);
  190. if (!$res) throw new \Exception(CloudStockAgentGoods::getStaticError());
  191. //触发库存变动事件
  192. $event = new CloudStockChangeEvent($params['mall_id']);
  193. $event_data = [
  194. 'id' => $res->id,
  195. 'type' => CloudStockEnum::STOCK_CHANGE_SUB,
  196. 'mall_id' => $params['mall_id'],
  197. ];
  198. \Yii::$app->services->events->dispatch($event, $event_data, $event->listeners);
  199. return $model;
  200. } catch (\Exception $e) {
  201. self::$static_error = $e->getMessage();
  202. return false;
  203. }
  204. }
  205. //获取指定等级库存商品价格
  206. public static function getGoodsAgentPrice($agent_price, $level)
  207. {
  208. if (isset($agent_price['agent_price'])) {
  209. $agent_price = \Qiniu\json_decode($agent_price['agent_price'], true);
  210. foreach ($agent_price as $value) {
  211. if ($value['level'] == $level) {
  212. return $value['price'];
  213. }
  214. }
  215. }
  216. return 0;
  217. }
  218. /**
  219. * 批量导入代理库存
  220. * @param $params
  221. * @return array|bool
  222. */
  223. public static function importStock($params)
  224. {
  225. $t = \Yii::$app->db->beginTransaction();
  226. try {
  227. self::isCanImport($params['mall_id']);
  228. $csvImport = new CsvImportForm();
  229. $data = $csvImport->setDataForm($params)
  230. ->setMaxCount(self::$max_count)
  231. ->setImportFieldConfig(self::$head_list)
  232. ->setColumnNum(self::$column_num)
  233. ->readCsvData();
  234. if (!$data) throw new \Exception(CsvImportForm::getStaticError());
  235. $success_counts = $fail_counts = 0;
  236. $counts = count($data);
  237. $fail_arr = [];
  238. $success_user_id_arr = [];
  239. $merge_arr = [];
  240. foreach ($data as $item) {
  241. $param = $item;
  242. $merge_arr[] = $param;
  243. }
  244. self::batchUpdateStock($params['mall_id'], $merge_arr, $success_counts, $fail_arr, $fail_counts, $success_user_id_arr);
  245. $param['counts'] = $counts;
  246. $param['success_counts'] = $success_counts;
  247. $param['fail_counts'] = $fail_counts;
  248. $param['status'] = 1;
  249. $param['mall_id'] = $params['mall_id'];
  250. $import_log_model = CloudStockImportStockLog::setData($param);
  251. if (!$import_log_model) throw new \Exception(CloudStockImportStockLog::getStaticError());
  252. if (!empty($fail_arr)) {
  253. $res = CloudStockImportStockFailLog::setData($fail_arr, $import_log_model->id);
  254. if (!$res) throw new \Exception(CloudStockImportStockFailLog::getStaticError());
  255. }
  256. $t->commit();
  257. return ['counts' => $counts, 'success_counts' => $success_counts, 'fail_counts' => $fail_counts];
  258. } catch (\Exception $e) {
  259. var_dump($e->getMessage() . $e->getFile());
  260. self::$static_error = $e->getMessage();
  261. $t->rollBack();
  262. return false;
  263. }
  264. }
  265. public static function importStockSync($params)
  266. {
  267. $t = \Yii::$app->db->beginTransaction();
  268. try {
  269. self::isCanImport($params['mall_id']);
  270. $basePath = \Yii::$app->basePath;
  271. if (empty($_FILES) || !isset($_FILES['file'])) throw new \Exception('请上传csv文件');
  272. $fileName = $_FILES['file']['name'];
  273. $tmpName = $_FILES['file']['tmp_name'];
  274. $basePath = $basePath . '/web/uploads/';
  275. if (!is_dir($basePath)) mkdir($basePath, 0775, true);
  276. $ext = strtolower(pathinfo($fileName, PATHINFO_EXTENSION));
  277. if ($ext != 'csv') throw new \Exception('请上传csv文件');
  278. $uploadFile = $basePath . 'ADMIN-' . date('Y-m-d His') . '.' . $ext;
  279. //上传
  280. move_uploaded_file($tmpName, $uploadFile);
  281. $success_counts = $fail_counts = 0;
  282. $counts = 0;
  283. $param['counts'] = $counts;
  284. $param['success_counts'] = $success_counts;
  285. $param['fail_counts'] = $fail_counts;
  286. $param['upload_file'] = $uploadFile;
  287. $param['mall_id'] = $params['mall_id'];
  288. $user_import_log_model = CloudStockImportStockLog::setData($param);
  289. if (!$user_import_log_model) throw new \Exception(CloudStockImportStockLog::getStaticError());
  290. $t->commit();
  291. $params = ['id' => $user_import_log_model['id']];
  292. \Yii::$app->services->rabbitMq->push(RabbitMqEnum::TASK_QUEUE, RabbitMqEnum::TASK_QUEUE, $params, self::class, 'syncImportStock');
  293. return ['counts' => $counts, 'success_counts' => $success_counts, 'fail_counts' => $fail_counts];
  294. } catch (\Exception $e) {
  295. self::$static_error = $e->getMessage();
  296. var_dump($e->getMessage());
  297. $t->rollBack();
  298. return false;
  299. }
  300. }
  301. public static function isCanImport($mall_id)
  302. {
  303. $time = strtotime('2024-04-28 23:59:59');
  304. $res = CloudStockImportStockLog::find()->where(['mall_id' => $mall_id, 'status' => 3])->andWhere(['>=', 'created_at', $time])->one();
  305. if (!empty($res)) throw new \Exception('等上一次导入执行完再导入');
  306. }
  307. //异步执行
  308. public static function syncImportStock($params)
  309. {
  310. if (empty($params['id'])) return false;
  311. $model = CloudStockImportStockLog::findOne(['id' => $params['id']]);
  312. if (!empty($model['upload_file'])) {
  313. $upload_file = $model['upload_file'];
  314. $mall_id = $model['mall_id'];
  315. $cvsFile = fopen($upload_file, 'r'); //开始读取csv文件数据
  316. $fail_arr = [];
  317. $success_counts = $fail_counts = $counts = $i = 0;
  318. $counts = 0;
  319. $success_user_id_arr = [];
  320. $data = []; // 初始化数据
  321. while ($fileData = fgetcsv($cvsFile)) {
  322. $i++;
  323. if ($i == 1) continue; //过滤表头
  324. $counts++;
  325. $user_id = 0;
  326. $goods_id = 0;
  327. $num = 0;
  328. foreach ($fileData as $k => &$val) {
  329. $val = mb_convert_encoding(trim($val), "UTF-8", "GBK");
  330. switch ($k) {
  331. case 1:
  332. $user_id = !empty($val) ? $val : '';
  333. break;
  334. case 2:
  335. $goods_id = !empty($val) ? trim($val) : 0;
  336. break;
  337. case 2:
  338. $num = !empty($val) ? trim($val) : 0;
  339. break;
  340. }
  341. }
  342. $param['user_id'] = $user_id;
  343. $param['goods_id'] = $goods_id;
  344. $param['num'] = $num;
  345. $data[] = $param;
  346. }
  347. self::batchUpdateStock($mall_id, $data, $success_counts, $fail_arr, $fail_counts);
  348. $model->counts = $counts;
  349. $model->success_counts = $success_counts;
  350. $model->fail_counts = $fail_counts;
  351. $model->status = 1;
  352. if (!$model->save()) throw new \Exception($model->getErrorMessage());
  353. if (!empty($fail_arr)) {
  354. $res = CloudStockImportStockFailLog::setData($fail_arr, $model->id);
  355. if (!$res) throw new \Exception(CloudStockImportStockFailLog::getStaticError());
  356. }
  357. }
  358. }
  359. /**
  360. * 批量更新等级
  361. * @Author: zfh
  362. * @DateTime: 2024/4/28 0003 15:16
  363. * @Copyright: copyright (c) 2021 广东七件事集团
  364. * @param $mall_id
  365. * @param $data
  366. * @param int $success_counts
  367. * @param array $fail_arr
  368. * @param int $fail_counts
  369. * @throws Exception
  370. */
  371. public static function batchUpdateStock($mall_id, $data, &$success_counts = 0, &$fail_arr = [], &$fail_counts = 0, &$success_user_id_arr = [])
  372. {
  373. foreach ($data as $item) {
  374. $fail_params = $item;
  375. $fail_params['maill_id'] = $mall_id;
  376. $where = [];
  377. $where[] = ['mall_id' => $mall_id];
  378. $where[] = ['id' => $item['user_id']];
  379. if (empty(User::getUser($where))) {
  380. $fail_params['reason'] = '用户不存在';
  381. list($fail_arr, $fail_counts) = CloudStockImportStockFailLog::packFailArr($fail_params, $fail_arr, $fail_counts);
  382. } else if (empty(Goods::getOne([['id' => $item['goods_id'],'mall_id'=>$mall_id]]))) {
  383. $fail_params['reason'] = '商品不存在';
  384. list($fail_arr, $fail_counts) = CloudStockImportStockFailLog::packFailArr($fail_params, $fail_arr, $fail_counts);
  385. } else if (empty(CloudStockAgent::getOne([['user_id' => $item['user_id'],'mall_id'=>$mall_id]]))) {
  386. $fail_params['reason'] = '代理商不存在';
  387. list($fail_arr, $fail_counts) = CloudStockImportStockFailLog::packFailArr($fail_params, $fail_arr, $fail_counts);
  388. } else {
  389. $saveData=[];
  390. $saveData['num']=$item['num'];
  391. $saveData['user_id']=$item['user_id'];
  392. $saveData['goods_id']=$item['goods_id'];
  393. $stock = CloudStockAgentGoods::getOne([['user_id' => $item['user_id'], 'goods_id' => $item['goods_id'], 'status' => 1,'mall_id'=>$mall_id]]);
  394. if ($stock) {
  395. $saveData['id'] = $stock['id'];
  396. $saveData['num'] += $stock['num'];
  397. if ($saveData['num'] < 0) {
  398. $saveData['num'] = 0;
  399. }
  400. }
  401. $item['mall_id'] = $mall_id;
  402. try {
  403. $res = CloudStockAgentGoods::setData($mall_id, $saveData);
  404. $param = [
  405. 'mall_id' => $mall_id,
  406. 'goods_id' => $item['goods_id'],
  407. 'user_id' => $item['user_id'],
  408. 'changes_dir' => $item['num'] > 0 ? 1 : 2,
  409. 'order_id' => 0,
  410. 'num' => abs($item['num']),
  411. 'order_type' => 0,
  412. 'changes_type' => $item['num'] > 0 ? CloudStockEnum::CHANGE_TYPE_INCREASE_PLATFORM:CloudStockEnum::CHANGE_TYPE_DEDUTION_PLATFORM,
  413. ];
  414. $stock_log = CloudStockGoodsStockLog::setData($param['mall_id'], $param);
  415. if ($stock_log == false) throw new Exception(CloudStockGoodsStockLog::getStaticError());
  416. $param = [
  417. 'stock_log_id' => $stock_log->id,
  418. 'user_id' => $item['user_id'],
  419. 'num' => $item['num'],
  420. 'changes_type' => $item['num'] > 0 ? CloudStockEnum::CHANGE_TYPE_INCREASE_PLATFORM:CloudStockEnum::CHANGE_TYPE_DEDUTION_PLATFORM,
  421. 'goods_id' => $item['goods_id'],
  422. 'mall_id' => $mall_id,
  423. 'order_id' => 0,
  424. ];
  425. $increase_detail = null;
  426. if ($item['num'] > 0) {
  427. $increase_detail=CloudStockIncreaseDetail::setData($param);
  428. if ($increase_detail == false) throw new Exception(
  429. CloudStockIncreaseDetail::getStaticError()
  430. );
  431. } else {
  432. $param['num']=abs($item['num']);
  433. $increase_detail= CloudStockDeductionDetail::setData($param);
  434. if ($increase_detail == false) throw new Exception(
  435. CloudStockDeductionDetail::getStaticError()
  436. );
  437. }
  438. CloudStockAgent::fixStock($mall_id,$item['user_id']);
  439. //触发库存变动事件
  440. $event = new CloudStockChangeEvent($mall_id);
  441. $event_data = [
  442. 'id' => $increase_detail->id,
  443. 'type' => $item['num'] > 0 ? CloudStockEnum::STOCK_CHANGE_ADD : CloudStockEnum::STOCK_CHANGE_SUB,
  444. 'mall_id' => $mall_id,
  445. ];
  446. \Yii::$app->services->events->dispatch($event, $event_data, $event->listeners);
  447. if ($res) {
  448. $success_user_id_arr[] = $res['id'];
  449. $success_counts++;
  450. } else {
  451. $fail_params['reason'] = CloudStockAgentGoods::getStaticError();
  452. list($fail_arr, $fail_counts) = CloudStockImportStockFailLog::packFailArr($fail_params, $fail_arr, $fail_counts);
  453. }
  454. } catch (\Exception $e) {
  455. self::$static_error = $e->getMessage();
  456. $fail_params['reason'] = '系统错误';
  457. list($fail_arr, $fail_counts) = CloudStockImportStockFailLog::packFailArr($fail_params, $fail_arr, $fail_counts);
  458. }
  459. }
  460. }
  461. }
  462. }