| 123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490 |
- <?php
- namespace addons\CloudStock\common\models;
- use addons\CloudStock\common\enums\CloudStockEnum;
- use addons\CloudStock\common\events\order\CloudStockChangeEvent;
- use common\enums\StatusEnum;
- use common\models\base\BaseActiveRecord;
- use common\models\goods\Goods;
- use common\helpers\csv\CsvImportForm;
- use common\enums\RabbitMqEnum;
- use common\models\user\User;
- use Yii;
- use yii\db\Exception;
- /**
- * This is the model class for table "{{%addons_cloud_stock_agent_goods".
- *
- * @property int $id
- * @property int $mall_id 商城id
- * @property int $user_id 用户id
- * @property int $goods_id 商品id
- * @property int $num 库存数量
- * @property int $status 状态[-1:删除;0:禁用;1启用]
- * @property int $created_at
- * @property int $updated_at
- */
- class CloudStockAgentGoods extends BaseActiveRecord
- {
- /**
- * {@inheritdoc}
- */
- public static function tableName()
- {
- return '{{%addons_cloud_stock_agent_goods}}';
- }
- /**
- * {@inheritdoc}
- */
- public function rules()
- {
- return [
- [['mall_id', 'user_id', 'goods_id', 'num', 'status', 'created_at', 'updated_at'], 'integer'],
- [['goods_id'], 'required'],
- ];
- }
- /**
- * {@inheritdoc}
- */
- public function attributeLabels()
- {
- return [
- 'id' => 'ID',
- 'mall_id' => '商城id',
- 'user_id' => '用户id',
- 'goods_id' => '商品id',
- 'num' => '库存数量',
- 'status' => '状态[-1:删除;0:禁用;1启用]',
- 'created_at' => 'Created At',
- 'updated_at' => 'Updated At',
- ];
- }
- public static $head_list = [
- '0' => [
- 'field' => 'serial_number',
- 'field_name' => '序号',
- ],
- '1' => [
- 'field' => 'user_id',
- 'field_name' => '用户id',
- ],
- '2' => [
- 'field' => 'goods_id',
- 'field_name' => '商品id',
- ],
- '3' => [
- 'field' => 'num',
- 'field_name' => '数量',
- ]
- ];
- public static $max_count = 5000;
- public static $column_num = 4;
- public function getGoods()
- {
- return $this->hasOne(Goods::class, ['id' => 'goods_id'])->select(['id', 'goods_name', 'cover_pic']);
- }
- public static function setData(int $mall_id, array $data)
- {
- if (!empty($data['id'])) {
- $model = self::findOne(['mall_id' => $mall_id, 'status' => StatusEnum::ENABLED, 'id' => $data['id']]);
- } else {
- $model = new self();
- $model->loadDefaultValues();
- $model->mall_id = $mall_id;
- }
- foreach ($data as $key => $val) {
- $model->$key = $val;
- }
- // dd($model);
- if (!$model->save()) {
- self::$static_error = '保存数据失败:' . $model->getErrorMessage();
- return false;
- }
- return $model;
- }
- public static function addData(array $params, &$increase_detail)
- {
- try {
- if (!empty($params['mall_id']) && !empty($params['user_id']) && !empty($params['goods_id'])) {
- $model = self::findOne(['mall_id' => $params['mall_id'], 'user_id' => $params['user_id'], 'goods_id' => $params['goods_id'], 'status' => [StatusEnum::ENABLED, StatusEnum::DISABLED]]);
- if (empty($model)) {
- $model = new self();
- $model->loadDefaultValues();
- if (!$model->load($params, '')) throw new \Exception($model->getErrorMessage());
- } else {
- var_dump('加之前user_id' . $params['user_id'] . ':num:' . $model->num);
- var_dump('加多少user_id' . $params['user_id'] . ':num:' . $params['num']);
- $model->num += $params['num'];
- }
- } else {
- $model = new self();
- $model->loadDefaultValues();
- if (!$model->load($params, '')) throw new \Exception($model->getErrorMessage());
- }
- if (!$model->save()) throw new \Exception($model->getErrorMessage());
- var_dump('加之后user_id' . $params['user_id'] . ':num:' . $model->num);
- $param = [
- 'mall_id' => $params['mall_id'],
- 'goods_id' => $params['goods_id'],
- 'user_id' => $params['user_id'],
- 'changes_dir' => $params['changes_dir'],
- 'order_id' => $params['order_id'],
- 'num' => $params['num'],
- 'order_type' => $params['order_type'],
- 'changes_type' => $params['changes_type'],
- ];
- $stock_log = CloudStockGoodsStockLog::setData($param['mall_id'], $param);
- if ($stock_log == false) throw new Exception(CloudStockGoodsStockLog::getStaticError());
- $param = [
- 'stock_log_id' => $stock_log->id,
- 'user_id' => $params['user_id'],
- 'num' => $params['num'],
- 'changes_type' => $params['changes_type'],
- 'goods_id' => $params['goods_id'],
- 'mall_id' => $params['mall_id'],
- 'order_id' => $params['order_id'],
- ];
- $increase_detail = CloudStockIncreaseDetail::setData($param);
- if ($increase_detail == false) throw new Exception(CloudStockIncreaseDetail::getStaticError());
- //触发库存变动事件
- $event = new CloudStockChangeEvent($params['mall_id']);
- $event_data = [
- 'id' => $increase_detail->id,
- 'type' => CloudStockEnum::STOCK_CHANGE_ADD,
- 'mall_id' => $params['mall_id'],
- ];
- \Yii::$app->services->events->dispatch($event, $event_data, $event->listeners);
- return $model;
- } catch (\Exception $e) {
- self::$static_error = $e->getMessage();
- return false;
- }
- }
- public static function subData(array $params)
- {
- try {
- if (!empty($params['mall_id']) && !empty($params['user_id']) && !empty($params['goods_id'])) {
- $model = self::findOne(['mall_id' => $params['mall_id'], 'user_id' => $params['user_id'], 'goods_id' => $params['goods_id'], 'status' => [StatusEnum::ENABLED, StatusEnum::DISABLED]]);
- if (empty($model)) {
- $model = new self();
- $model->loadDefaultValues();
- if (!$model->load($params, '')) throw new \Exception($model->getErrorMessage());
- } else {
- $model->num -= $params['num'];
- }
- } else {
- $model = new self();
- $model->loadDefaultValues();
- if (!$model->load($params, '')) throw new \Exception($model->getErrorMessage());
- }
- if (!$model->save()) throw new \Exception($model->getErrorMessage());
- $params = [
- 'stock_log_id' => isset($params['stock_log_id']) ? $params['stock_log_id'] : 0,
- 'user_id' => $params['user_id'],
- 'num' => $params['num'],
- 'not_yet_num' => 0,
- 'changes_type' => $params['changes_type'],
- 'order_id' => $params['order_id'],
- 'goods_id' => $params['goods_id'],
- 'mall_id' => $params['mall_id'],
- ];
- $res = CloudStockDeductionDetail::setData($params);
- if (!$res) throw new \Exception(CloudStockAgentGoods::getStaticError());
- //触发库存变动事件
- $event = new CloudStockChangeEvent($params['mall_id']);
- $event_data = [
- 'id' => $res->id,
- 'type' => CloudStockEnum::STOCK_CHANGE_SUB,
- 'mall_id' => $params['mall_id'],
- ];
- \Yii::$app->services->events->dispatch($event, $event_data, $event->listeners);
- return $model;
- } catch (\Exception $e) {
- self::$static_error = $e->getMessage();
- return false;
- }
- }
- //获取指定等级库存商品价格
- public static function getGoodsAgentPrice($agent_price, $level)
- {
- if (isset($agent_price['agent_price'])) {
- $agent_price = \Qiniu\json_decode($agent_price['agent_price'], true);
- foreach ($agent_price as $value) {
- if ($value['level'] == $level) {
- return $value['price'];
- }
- }
- }
- return 0;
- }
- /**
- * 批量导入代理库存
- * @param $params
- * @return array|bool
- */
- public static function importStock($params)
- {
- $t = \Yii::$app->db->beginTransaction();
- try {
- self::isCanImport($params['mall_id']);
- $csvImport = new CsvImportForm();
- $data = $csvImport->setDataForm($params)
- ->setMaxCount(self::$max_count)
- ->setImportFieldConfig(self::$head_list)
- ->setColumnNum(self::$column_num)
- ->readCsvData();
- if (!$data) throw new \Exception(CsvImportForm::getStaticError());
- $success_counts = $fail_counts = 0;
- $counts = count($data);
- $fail_arr = [];
- $success_user_id_arr = [];
- $merge_arr = [];
- foreach ($data as $item) {
- $param = $item;
- $merge_arr[] = $param;
- }
- self::batchUpdateStock($params['mall_id'], $merge_arr, $success_counts, $fail_arr, $fail_counts, $success_user_id_arr);
- $param['counts'] = $counts;
- $param['success_counts'] = $success_counts;
- $param['fail_counts'] = $fail_counts;
- $param['status'] = 1;
- $param['mall_id'] = $params['mall_id'];
- $import_log_model = CloudStockImportStockLog::setData($param);
- if (!$import_log_model) throw new \Exception(CloudStockImportStockLog::getStaticError());
- if (!empty($fail_arr)) {
- $res = CloudStockImportStockFailLog::setData($fail_arr, $import_log_model->id);
- if (!$res) throw new \Exception(CloudStockImportStockFailLog::getStaticError());
- }
- $t->commit();
- return ['counts' => $counts, 'success_counts' => $success_counts, 'fail_counts' => $fail_counts];
- } catch (\Exception $e) {
- var_dump($e->getMessage() . $e->getFile());
- self::$static_error = $e->getMessage();
- $t->rollBack();
- return false;
- }
- }
- public static function importStockSync($params)
- {
- $t = \Yii::$app->db->beginTransaction();
- try {
- self::isCanImport($params['mall_id']);
- $basePath = \Yii::$app->basePath;
- if (empty($_FILES) || !isset($_FILES['file'])) throw new \Exception('请上传csv文件');
- $fileName = $_FILES['file']['name'];
- $tmpName = $_FILES['file']['tmp_name'];
- $basePath = $basePath . '/web/uploads/';
- if (!is_dir($basePath)) mkdir($basePath, 0775, true);
- $ext = strtolower(pathinfo($fileName, PATHINFO_EXTENSION));
- if ($ext != 'csv') throw new \Exception('请上传csv文件');
- $uploadFile = $basePath . 'ADMIN-' . date('Y-m-d His') . '.' . $ext;
- //上传
- move_uploaded_file($tmpName, $uploadFile);
- $success_counts = $fail_counts = 0;
- $counts = 0;
- $param['counts'] = $counts;
- $param['success_counts'] = $success_counts;
- $param['fail_counts'] = $fail_counts;
- $param['upload_file'] = $uploadFile;
- $param['mall_id'] = $params['mall_id'];
- $user_import_log_model = CloudStockImportStockLog::setData($param);
- if (!$user_import_log_model) throw new \Exception(CloudStockImportStockLog::getStaticError());
- $t->commit();
- $params = ['id' => $user_import_log_model['id']];
- \Yii::$app->services->rabbitMq->push(RabbitMqEnum::TASK_QUEUE, RabbitMqEnum::TASK_QUEUE, $params, self::class, 'syncImportStock');
- return ['counts' => $counts, 'success_counts' => $success_counts, 'fail_counts' => $fail_counts];
- } catch (\Exception $e) {
- self::$static_error = $e->getMessage();
- var_dump($e->getMessage());
- $t->rollBack();
- return false;
- }
- }
- public static function isCanImport($mall_id)
- {
- $time = strtotime('2024-04-28 23:59:59');
- $res = CloudStockImportStockLog::find()->where(['mall_id' => $mall_id, 'status' => 3])->andWhere(['>=', 'created_at', $time])->one();
- if (!empty($res)) throw new \Exception('等上一次导入执行完再导入');
- }
- //异步执行
- public static function syncImportStock($params)
- {
- if (empty($params['id'])) return false;
- $model = CloudStockImportStockLog::findOne(['id' => $params['id']]);
- if (!empty($model['upload_file'])) {
- $upload_file = $model['upload_file'];
- $mall_id = $model['mall_id'];
- $cvsFile = fopen($upload_file, 'r'); //开始读取csv文件数据
- $fail_arr = [];
- $success_counts = $fail_counts = $counts = $i = 0;
- $counts = 0;
- $success_user_id_arr = [];
- $data = []; // 初始化数据
- while ($fileData = fgetcsv($cvsFile)) {
- $i++;
- if ($i == 1) continue; //过滤表头
- $counts++;
- $user_id = 0;
- $goods_id = 0;
- $num = 0;
- foreach ($fileData as $k => &$val) {
- $val = mb_convert_encoding(trim($val), "UTF-8", "GBK");
- switch ($k) {
- case 1:
- $user_id = !empty($val) ? $val : '';
- break;
- case 2:
- $goods_id = !empty($val) ? trim($val) : 0;
- break;
- case 2:
- $num = !empty($val) ? trim($val) : 0;
- break;
- }
- }
- $param['user_id'] = $user_id;
- $param['goods_id'] = $goods_id;
- $param['num'] = $num;
- $data[] = $param;
- }
- self::batchUpdateStock($mall_id, $data, $success_counts, $fail_arr, $fail_counts);
- $model->counts = $counts;
- $model->success_counts = $success_counts;
- $model->fail_counts = $fail_counts;
- $model->status = 1;
- if (!$model->save()) throw new \Exception($model->getErrorMessage());
- if (!empty($fail_arr)) {
- $res = CloudStockImportStockFailLog::setData($fail_arr, $model->id);
- if (!$res) throw new \Exception(CloudStockImportStockFailLog::getStaticError());
- }
- }
- }
- /**
- * 批量更新等级
- * @Author: zfh
- * @DateTime: 2024/4/28 0003 15:16
- * @Copyright: copyright (c) 2021 广东七件事集团
- * @param $mall_id
- * @param $data
- * @param int $success_counts
- * @param array $fail_arr
- * @param int $fail_counts
- * @throws Exception
- */
- public static function batchUpdateStock($mall_id, $data, &$success_counts = 0, &$fail_arr = [], &$fail_counts = 0, &$success_user_id_arr = [])
- {
- foreach ($data as $item) {
- $fail_params = $item;
- $fail_params['maill_id'] = $mall_id;
- $where = [];
- $where[] = ['mall_id' => $mall_id];
- $where[] = ['id' => $item['user_id']];
- if (empty(User::getUser($where))) {
- $fail_params['reason'] = '用户不存在';
- list($fail_arr, $fail_counts) = CloudStockImportStockFailLog::packFailArr($fail_params, $fail_arr, $fail_counts);
- } else if (empty(Goods::getOne([['id' => $item['goods_id'],'mall_id'=>$mall_id]]))) {
- $fail_params['reason'] = '商品不存在';
- list($fail_arr, $fail_counts) = CloudStockImportStockFailLog::packFailArr($fail_params, $fail_arr, $fail_counts);
- } else if (empty(CloudStockAgent::getOne([['user_id' => $item['user_id'],'mall_id'=>$mall_id]]))) {
- $fail_params['reason'] = '代理商不存在';
- list($fail_arr, $fail_counts) = CloudStockImportStockFailLog::packFailArr($fail_params, $fail_arr, $fail_counts);
- } else {
- $saveData=[];
- $saveData['num']=$item['num'];
- $saveData['user_id']=$item['user_id'];
- $saveData['goods_id']=$item['goods_id'];
- $stock = CloudStockAgentGoods::getOne([['user_id' => $item['user_id'], 'goods_id' => $item['goods_id'], 'status' => 1,'mall_id'=>$mall_id]]);
- if ($stock) {
- $saveData['id'] = $stock['id'];
- $saveData['num'] += $stock['num'];
- if ($saveData['num'] < 0) {
- $saveData['num'] = 0;
- }
- }
- $item['mall_id'] = $mall_id;
- try {
- $res = CloudStockAgentGoods::setData($mall_id, $saveData);
- $param = [
- 'mall_id' => $mall_id,
- 'goods_id' => $item['goods_id'],
- 'user_id' => $item['user_id'],
- 'changes_dir' => $item['num'] > 0 ? 1 : 2,
- 'order_id' => 0,
- 'num' => abs($item['num']),
- 'order_type' => 0,
- 'changes_type' => $item['num'] > 0 ? CloudStockEnum::CHANGE_TYPE_INCREASE_PLATFORM:CloudStockEnum::CHANGE_TYPE_DEDUTION_PLATFORM,
- ];
- $stock_log = CloudStockGoodsStockLog::setData($param['mall_id'], $param);
- if ($stock_log == false) throw new Exception(CloudStockGoodsStockLog::getStaticError());
- $param = [
- 'stock_log_id' => $stock_log->id,
- 'user_id' => $item['user_id'],
- 'num' => $item['num'],
- 'changes_type' => $item['num'] > 0 ? CloudStockEnum::CHANGE_TYPE_INCREASE_PLATFORM:CloudStockEnum::CHANGE_TYPE_DEDUTION_PLATFORM,
- 'goods_id' => $item['goods_id'],
- 'mall_id' => $mall_id,
- 'order_id' => 0,
- ];
- $increase_detail = null;
- if ($item['num'] > 0) {
- $increase_detail=CloudStockIncreaseDetail::setData($param);
- if ($increase_detail == false) throw new Exception(
- CloudStockIncreaseDetail::getStaticError()
- );
- } else {
- $param['num']=abs($item['num']);
- $increase_detail= CloudStockDeductionDetail::setData($param);
- if ($increase_detail == false) throw new Exception(
- CloudStockDeductionDetail::getStaticError()
- );
- }
-
-
- CloudStockAgent::fixStock($mall_id,$item['user_id']);
- //触发库存变动事件
- $event = new CloudStockChangeEvent($mall_id);
- $event_data = [
- 'id' => $increase_detail->id,
- 'type' => $item['num'] > 0 ? CloudStockEnum::STOCK_CHANGE_ADD : CloudStockEnum::STOCK_CHANGE_SUB,
- 'mall_id' => $mall_id,
- ];
- \Yii::$app->services->events->dispatch($event, $event_data, $event->listeners);
- if ($res) {
- $success_user_id_arr[] = $res['id'];
- $success_counts++;
- } else {
- $fail_params['reason'] = CloudStockAgentGoods::getStaticError();
- list($fail_arr, $fail_counts) = CloudStockImportStockFailLog::packFailArr($fail_params, $fail_arr, $fail_counts);
- }
- } catch (\Exception $e) {
- self::$static_error = $e->getMessage();
- $fail_params['reason'] = '系统错误';
- list($fail_arr, $fail_counts) = CloudStockImportStockFailLog::packFailArr($fail_params, $fail_arr, $fail_counts);
- }
- }
- }
- }
- }
|