ScoreImportLogic.php 8.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231
  1. <?php
  2. namespace addons\ScoreExpansion\backend\logic;
  3. use addons\ScoreExpansion\common\enums\ScoreExpansionEnum;
  4. use addons\ScoreExpansion\common\models\ScoreExpansionWallet;
  5. use common\enums\RabbitMqEnum;
  6. use common\enums\StatusEnum;
  7. use common\helpers\FormatHelper;
  8. use common\models\common\ImportFailLog;
  9. use common\models\common\ImportLog;
  10. use common\models\user\User;
  11. use common\traits\ErrorTrait;
  12. use Exception;
  13. use RuntimeException;
  14. use Yii;
  15. class ScoreImportLogic
  16. {
  17. use ErrorTrait;
  18. /**
  19. * @param $params
  20. *
  21. * @return false|int[]
  22. */
  23. public static function importSync($params)
  24. {
  25. $t = Yii::$app->db->beginTransaction();
  26. try {
  27. $basePath = \Yii::$app->basePath;
  28. if (empty($_FILES) || !isset($_FILES['file'])) throw new Exception('请上传csv文件');
  29. $fileName = $_FILES['file']['name'];
  30. $tmpName = $_FILES['file']['tmp_name'];
  31. $basePath = $basePath . '/web/uploads/addons/ScoreExpansion/';
  32. if (!is_dir($basePath)) mkdir($basePath, 0775, true);
  33. $ext = strtolower(pathinfo($fileName, PATHINFO_EXTENSION));
  34. if ($ext != 'csv') throw new Exception('请上传csv文件');
  35. $uploadFile = $basePath . 'ScoreExpansion-' . date('Y-m-d His') . '.' . $ext;
  36. //上传
  37. move_uploaded_file($tmpName, $uploadFile);
  38. $success_counts = $fail_counts = 0;
  39. $counts = 0;
  40. $param['counts'] = $counts;
  41. $param['success_counts'] = $success_counts;
  42. $param['fail_counts'] = $fail_counts;
  43. $param['upload_file'] = $uploadFile;
  44. $param['mall_id'] = $params['mall_id'];
  45. $param['source'] = ScoreExpansionWallet::class;
  46. $import_log_model = ImportLog::setData($param);
  47. if (!$import_log_model) throw new Exception(ImportLog::getStaticError());
  48. $t->commit();
  49. $params = ['id' => $import_log_model['id']];
  50. Yii::$app->services->rabbitMq->push(RabbitMqEnum::EXCHANGE_LONG_DURATION, RabbitMqEnum::LONG_DURATION_QUEUE, $params, self::class, 'syncImport');
  51. return ['counts' => $counts, 'success_counts' => $success_counts, 'fail_counts' => $fail_counts];
  52. } catch (Exception $e) {
  53. self::setError($e->getMessage());
  54. $t->rollBack();
  55. return false;
  56. }
  57. }
  58. public static function handleImportData($params, $data, $sync = 1)
  59. {
  60. $success_counts = $fail_counts = 0;
  61. $counts = count($data);
  62. $fail_arr = [];
  63. $userMap = User::find()
  64. ->where([
  65. 'status' => StatusEnum::ENABLED,
  66. 'mobile' => array_column($data, 'mobile'),
  67. 'mall_id' => $params['mall_id']
  68. ])
  69. ->select('id, mobile')
  70. ->indexBy('mobile')
  71. ->asArray()
  72. ->all();
  73. foreach ($data as $val) {
  74. array_walk($val, function (&$v) {
  75. $v = trim($v);
  76. });
  77. $val['mall_id'] = $params['mall_id'];
  78. $val['source_table'] = ImportLog::tableName();
  79. $val['source_table_id'] = $params['import_log_id'];
  80. if (empty($val['mobile'])) {
  81. $val['reason'] = '用户手机号为空';
  82. [$fail_arr, $fail_counts] = ImportFailLog::packFailArr($val, $fail_arr, $fail_counts);
  83. continue;
  84. }
  85. if (!isset($userMap[$val['mobile']])) {
  86. $val['reason'] = '手机号错误,未查询到该用户';
  87. [$fail_arr, $fail_counts] = ImportFailLog::packFailArr($val, $fail_arr, $fail_counts);
  88. continue;
  89. }
  90. $val['user_id'] = $userMap[$val['mobile']]['id'];
  91. if (!isset($val['integral']) || !is_numeric($val['integral'])) {
  92. $val['integral'] = 0;
  93. }
  94. if (!isset($val['frozen_integral']) || !is_numeric($val['frozen_integral'])) {
  95. $val['frozen_integral'] = 0;
  96. }
  97. if (self::handleScore($val)) {
  98. $success_counts += 1;
  99. } else {
  100. $val['reason'] = self::getStaticError();
  101. [$fail_arr, $fail_counts] = ImportFailLog::packFailArr($val, $fail_arr, $fail_counts);
  102. }
  103. }
  104. $param['counts'] = $counts;
  105. $param['success_counts'] = $success_counts;
  106. $param['fail_counts'] = $fail_counts;
  107. $param['source'] = ScoreExpansionWallet::class;
  108. $param['mall_id'] = $params['mall_id'];
  109. if ($sync == 0) {
  110. $param['fail_arr'] = $fail_arr;
  111. // 异步返回数据
  112. return $param;
  113. }
  114. $import_log_model = ImportLog::setData($param);
  115. if (!$import_log_model) throw new Exception(ImportLog::getStaticError());
  116. if (!empty($fail_arr)) {
  117. $res = ImportFailLog::setData($fail_arr, $import_log_model->id);
  118. if (!$res) throw new Exception(ImportFailLog::getStaticError());
  119. }
  120. }
  121. /**
  122. * @param $params
  123. *
  124. * @return void
  125. */
  126. public static function syncImport($params)
  127. {
  128. try {
  129. if (empty($params['id'])) throw new Exception('缺少参数id');
  130. $model = ImportLog::findOne(['id' => $params['id']]);
  131. if (empty($model['upload_file'])) throw new Exception('缺少参数upload_file');
  132. $upload_file = $model['upload_file'];
  133. $mall_id = $model['mall_id'];
  134. $cvsFile = fopen($upload_file, 'r'); //开始读取csv文件数据
  135. $i = 0;
  136. $rows = [];
  137. while ($fileData = fgetcsv($cvsFile)) {
  138. $i++;
  139. if ($i == 1) continue; //过滤表头
  140. $temp_row = [];
  141. foreach ($fileData as $k => $val) {
  142. $val = mb_convert_encoding(trim($val), "UTF-8", "GBK");
  143. if ($k == 0) {
  144. $temp_row['mobile'] = $val;
  145. } else if ($k == 1) {
  146. $temp_row['integral'] = $val;
  147. } else if ($k == 2) {
  148. $temp_row['frozen_integral'] = $val;
  149. }
  150. }
  151. $rows[] = $temp_row;
  152. }
  153. $result = self::handleImportData(['mall_id' => $mall_id, 'import_log_id' => $params['id']], $rows, 0);
  154. $model->counts = $result['counts'];
  155. $model->success_counts = $result['success_counts'];
  156. $model->fail_counts = $result['fail_counts'];
  157. if (!$model->save()) throw new RuntimeException($model->getErrorMessage());
  158. $fail_arr = $result['fail_arr'] ?? [];
  159. if (!empty($fail_arr)) {
  160. $res = ImportFailLog::setData($fail_arr, $model->id);
  161. if (!$res) throw new RuntimeException(ImportFailLog::getStaticError());
  162. }
  163. } catch (Exception $e) {
  164. Yii::$app->custom->logs(FormatHelper::exception($e, '【积分拓客】充值积分失败'));
  165. }
  166. }
  167. /**
  168. * @param array $params
  169. *
  170. * @return bool
  171. */
  172. private static function handleScore(array $params): bool
  173. {
  174. $integralFrozenText = ScoreExpansionEnum::getRedpackText(ScoreExpansionEnum::WALLET_INTEGRAL_FROZEN, $params['mall_id']);
  175. $integralText = ScoreExpansionEnum::getRedpackText(ScoreExpansionEnum::WALLET_INTEGRAL, $params['mall_id']);
  176. $t = Yii::$app->db->beginTransaction();
  177. try {
  178. // 加激活积分
  179. if ($params['integral']) {
  180. $res = ScoreExpansionWallet::setData([
  181. 'mall_id' => $params['mall_id'],
  182. 'user_id' => $params['user_id'],
  183. 'is_frozen' => false,
  184. 'is_deduct' => true,
  185. 'integral' => $params['integral'],
  186. 'from_type' => ScoreExpansionEnum::FROM_IMPORT,
  187. 'desc' => '手动导入' . $integralText,
  188. ]);
  189. if ($res === false) throw new RuntimeException(ScoreExpansionWallet::getStaticError());
  190. }
  191. // 加冻结积分
  192. if ($params['frozen_integral']) {
  193. $res = ScoreExpansionWallet::setData([
  194. 'mall_id' => $params['mall_id'],
  195. 'user_id' => $params['user_id'],
  196. 'is_frozen' => true,
  197. 'is_deduct' => true,
  198. 'integral' => $params['frozen_integral'],
  199. 'from_type' => ScoreExpansionEnum::FROM_IMPORT,
  200. 'desc' => '手动导入' . $integralFrozenText,
  201. ]);
  202. if ($res === false) throw new RuntimeException(ScoreExpansionWallet::getStaticError());
  203. }
  204. $t->commit();
  205. } catch (Exception $e) {
  206. $t->rollBack();
  207. self::setStaticError(FormatHelper::exception($e, '【积分拓客】充值积分失败'));
  208. return false;
  209. }
  210. return true;
  211. }
  212. }