MchCommission.php 19 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497
  1. <?php
  2. namespace addons\Mch\common\models;
  3. use common\components\export\CsvTool;
  4. use common\enums\DownloadEnum;
  5. use common\enums\StatusEnum;
  6. use common\models\base\BaseActiveRecord;
  7. use common\models\common\Download;
  8. use common\models\user\User;
  9. use Yii;
  10. /**
  11. * This is the model class for table "qimall_addons_mch_commission".
  12. *
  13. * @property int $id
  14. * @property int $mall_id 商城id
  15. * @property int $mch_id 多商户id
  16. * @property int $user_id 会员id
  17. * @property string $order_no 订单编号
  18. * @property float $order_money 订单金额
  19. * @property float $pay_money 支付金额
  20. * @property float $discount_money 优惠金额
  21. * @property float $addons_bonus 插件分红
  22. * @property float $service_charge 服务费
  23. * @property float $amount_received 到账金额
  24. * @property int $is_settlement 结算状态 0:待结算;1:已结算
  25. * @property int $type 类型:1:o2o订单;2:o2o收银台订单
  26. * @property int $created_at
  27. * @property int $updated_at
  28. * @property int|null $status 状态[-1:删除;0:禁用;1启用]
  29. */
  30. class MchCommission extends BaseActiveRecord
  31. {
  32. /**
  33. * {@inheritdoc}
  34. */
  35. public static function tableName()
  36. {
  37. return '{{%addons_mch_commission}}';
  38. }
  39. /**
  40. * {@inheritdoc}
  41. */
  42. public function rules()
  43. {
  44. return [
  45. [['mall_id', 'mch_id', 'user_id', 'is_settlement', 'type', 'created_at', 'updated_at', 'status'], 'integer'],
  46. [['order_money', 'pay_money', 'discount_money', 'addons_bonus', 'service_charge', 'amount_received'], 'number'],
  47. [['order_no'], 'string', 'max' => 100],
  48. ];
  49. }
  50. /**
  51. * {@inheritdoc}
  52. */
  53. public function attributeLabels()
  54. {
  55. return [
  56. 'id' => 'ID',
  57. 'mall_id' => '商城id',
  58. 'mch_id' => '多商户id',
  59. 'user_id' => '会员id',
  60. 'order_no' => '订单编号',
  61. 'order_money' => '订单金额',
  62. 'pay_money' => '支付金额',
  63. 'discount_money' => '优惠金额',
  64. 'addons_bonus' => '插件分红',
  65. 'service_charge' => '服务费',
  66. 'amount_received' => '到账金额',
  67. 'is_settlement' => '结算状态 0:待结算;1:已结算',
  68. 'type' => '类型:1:o2o订单;2:o2o收银台订单',
  69. 'created_at' => 'Created At',
  70. 'updated_at' => 'Updated At',
  71. 'status' => '状态[-1:删除;0:禁用;1启用]',
  72. ];
  73. }
  74. public function getUser()
  75. {
  76. return $this->hasOne(User::class, ['id' => 'user_id']);
  77. }
  78. public function getMch()
  79. {
  80. return $this->hasOne(Mch::class, ['id' => 'mch_id'])->select('id, store_name, logo_img, shop_mobile');
  81. }
  82. public static function setData(array $params)
  83. {
  84. try {
  85. $model = new self();
  86. $model->loadDefaultValues();
  87. if (!$model->load($params, '') || !$model->save()) {
  88. throw new \Exception($model->getErrorMessage());
  89. }
  90. return $model;
  91. } catch (\Exception $e) {
  92. self::$static_error = $e->getMessage() . $e->getLine() . $e->getFile();
  93. return false;
  94. }
  95. }
  96. /**
  97. * @name:
  98. * @msg: 数据导出处理器
  99. * @param {*} $data
  100. * @return {*}
  101. */
  102. public static function exportHandle(array $data = null)
  103. {
  104. try {
  105. $download_id = $data['download_id'] ?? 0;
  106. $download = Download::findOne(['id' => $download_id]);
  107. $params = json_decode($download->params, true);
  108. $have_select_field_arr = [];
  109. $all_fields = self::fieldsList();
  110. $fields = $params['fields'] ?? [];
  111. if (!empty($fields)) {
  112. foreach ($fields as $field) {
  113. $have_select_field_arr[] = $all_fields[$field];
  114. }
  115. } else {
  116. $have_select_field_arr = $all_fields;
  117. }
  118. $csv = new CsvTool();
  119. $csv->filename = $download->name;
  120. $csv->file_dirname = DownloadEnum::getTypeStorageDirMap($download->type);
  121. $csv->export_mode = CsvTool::EXPORT_MODE_ASYNC;
  122. $csv->header = $have_select_field_arr;
  123. $list_query = self::find()->where(['mall_id' => $params['mall_id'], 'status' => StatusEnum::ENABLED]);
  124. if (!empty($min_amount)) {
  125. $list_query->andWhere(['>=', 'pay_money', $min_amount]);
  126. }
  127. if (!empty($max_amount)) {
  128. $list_query->andWhere(['<=', 'pay_money', $max_amount]);
  129. }
  130. if (!empty($start_time)) {
  131. $list_query->andWhere(['>=', 'created_at', $start_time]);
  132. }
  133. if (!empty($end_time)) {
  134. $list_query->andWhere(['<=', 'created_at', $end_time]);
  135. }
  136. if (!empty($store_name)) {
  137. $stores = Mch::find()
  138. ->select('id,store_name,logo_img')
  139. ->where(['mall_id' => $params['mall_id'], 'status' => StatusEnum::ENABLED])
  140. ->andWhere(['like', 'store_name', $store_name])
  141. ->asArray()
  142. ->indexBy('id')
  143. ->all();
  144. $store_ids = array_column($stores, 'id');
  145. $list_query->andWhere(['store_id' => $store_ids]);
  146. }
  147. if (!empty($user_id)) {
  148. $list_query->andWhere(['user_id' => $user_id]);
  149. }
  150. $user_wheres = [];
  151. $users = [];
  152. if (!empty($nickname)) {
  153. $user_wheres[] = ['like', 'nickname', $nickname];
  154. }
  155. if (!empty($mobile)) {
  156. $user_wheres[] = ['like', 'mobile', $mobile];
  157. }
  158. if (!empty($user_wheres)) {
  159. $user_wheres[] = ['mall_id' => $params['mall_id'], 'status' => StatusEnum::ENABLED];
  160. $query = User::find()->select('id,nickname,mobile,avatar_url');
  161. foreach ($user_wheres as $where) {
  162. $query->andWhere($where);
  163. }
  164. $users = $query->asArray()->indexBy('id')->all();
  165. $user_ids = array_column($users, 'id');
  166. $list_query->andWhere(['user_id' => $user_ids]);
  167. }
  168. $rows = [];
  169. foreach ($list_query->asArray()->batch(200) as $lists) {
  170. // dd($lists);
  171. if (empty($users)) {
  172. $user_ids = array_column($lists, 'user_id');
  173. $users = User::find()
  174. ->select('id,nickname,mobile,avatar_url')
  175. ->where(['mall_id' => $params['mall_id'], 'status' => StatusEnum::ENABLED, 'id' => $user_ids])
  176. ->asArray()
  177. ->indexBy('id')
  178. ->all();
  179. }
  180. if (empty($stores)) {
  181. $store_ids = array_column($lists, 'store_id');
  182. $stores = Mch::find()
  183. ->select('id,store_name,logo_img')
  184. ->where(['mall_id' => $params['mall_id'], 'status' => StatusEnum::ENABLED, 'id' => $store_ids])
  185. ->asArray()
  186. ->indexBy('id')
  187. ->all();
  188. }
  189. foreach ($lists as $list) {
  190. $user = $users[$list['user_id']] ?? '';
  191. $store = $stores[$list['store_id']] ?? '';
  192. $list['nickname'] = $user['nickname'] ?? '';
  193. $list['mobile'] = $user['mobile'] ?? '';
  194. $list['store_name'] = $store['store_name'] ?? '';
  195. // dd($list);
  196. $arr = [];
  197. foreach ($fields as $field) {
  198. if (!empty($list[$field])) {
  199. if ('created_at' == $field) {
  200. $list[$field] = date('Y-m-d H:i:s', $list[$field]);
  201. }
  202. if ('mobile' == $field) {
  203. $list[$field] = (string)$list[$field];
  204. }
  205. } else {
  206. $list[$field] = '';
  207. }
  208. $arr[] = $list[$field];
  209. }
  210. $rows[] = $arr;
  211. }
  212. }
  213. $csv->data = $rows;
  214. $csv->export();
  215. $csv->updateDown($download, $params['mall_id']);
  216. return true;
  217. } catch (\Exception $e) {
  218. $download->status = 3;
  219. $res = $download->save();
  220. self::setStaticError($e->getMessage());
  221. return $e->getMessage();
  222. }
  223. }
  224. /** 订单明细导出
  225. * @param array $data
  226. * @return string|true
  227. */
  228. public static function orderDetailExportHandle(array $data)
  229. {
  230. $download_id = $data['download_id'] ?? 0;
  231. $download = Download::findOne(['id' => $download_id]);
  232. $transaction = \Yii::$app->db->beginTransaction();
  233. try {
  234. $params = json_decode($download->params, true);
  235. $fileName = $download->name;
  236. $storeModel = self::find()->where(['mall_id' => $params['mall_id'], 'status' => StatusEnum::ENABLED, 'type' => 1]);
  237. if (!empty($params['store_name'])) {
  238. $store_ids = Mch::find()
  239. ->select('id')
  240. ->where(['mall_id' => $params['mall_id'], 'status' => StatusEnum::ENABLED])
  241. ->andWhere(['like', 'store_name', $params['store_name']])
  242. ->asArray()
  243. ->indexBy('id')
  244. ->column();
  245. $storeModel->andWhere(['store_id' => $store_ids]);
  246. }
  247. $user_ids = [];
  248. if (!empty($params['user_id'])) {
  249. $user_ids[] = $params['user_id'];
  250. }
  251. if (!empty($params['nickname'])) {
  252. $user_ids = array_merge($user_ids, self::getUserIdsByParams($params, 'nickname'));
  253. }
  254. if (!empty($params['mobile'])) {
  255. $user_ids = array_merge($user_ids, self::getUserIdsByParams($params, 'mobile'));
  256. }
  257. if (!empty($user_ids)) {
  258. $storeModel->andWhere(['user_id' => $user_ids]);
  259. }
  260. if (!empty($params['order_no'])) {
  261. $storeModel->andWhere(['like', 'order_no', $params['order_no']]);
  262. }
  263. if (!empty($params['order_status'])) {
  264. switch ($params['order_status']) {
  265. case 1:
  266. $storeModel->andWhere(['is_settlement' => 0]);
  267. break;
  268. case 2:
  269. $storeModel->andWhere(['is_settlement' => 1]);
  270. break;
  271. default:
  272. $storeModel->andWhere(['!=', 'status', StatusEnum::ENABLED]);
  273. }
  274. }
  275. if (!empty($params['order_ids'])) {
  276. $storeModel->andWhere(['id' => $params['order_ids']]);
  277. }
  278. $batchSize = 10000;
  279. $totalRecords = $storeModel->count() ?? 0;
  280. $is_model_page = bcdiv($totalRecords, $batchSize);
  281. $oldFields = $params['fields'] ?? [];
  282. $exportHeader = [];
  283. $fields = [];
  284. $orderDetailFieldsList = self::orderDetailFieldsList();
  285. foreach ($orderDetailFieldsList as $field => $fieldName)
  286. {
  287. if (in_array($field, $oldFields)) {
  288. $fields[] = $field;
  289. $exportHeader[] = $fieldName;
  290. }
  291. }
  292. $whereWith = ['mch', 'user' => function ($query) {
  293. $query->select('id, nickname, mobile, avatar_url');
  294. }];
  295. $i = 0;
  296. foreach ($storeModel->with($whereWith)->orderBy('id desc')->asArray()->batch($batchSize) as $stores) {
  297. $exportList = [];
  298. foreach ($stores as $store) {
  299. $exportItem = self::buildExportItem($store, $fields);
  300. $exportList[] = $exportItem;
  301. }
  302. if (!empty($exportList)) {
  303. $csv = new CsvTool();
  304. $csv->header = $exportHeader;
  305. $csv->file_dirname = DownloadEnum::getTypeStorageDirMap($download->type);
  306. $csv->export_mode = CsvTool::EXPORT_MODE_ASYNC;
  307. $csv->data = $exportList;
  308. $csv->filename = $is_model_page ? $fileName . '_1' : $fileName;
  309. if ($is_model_page && $i == 0) { // 因为订单页需要分页,所以需要设置文件名
  310. $download->name = $fileName . '_1';
  311. $download->save();
  312. }
  313. if ($i >= 1) {
  314. $newFileName = $fileName . '_' . ($i + 1);
  315. $csv->filename = $newFileName;
  316. $downloadData = [
  317. 'mall_id' => $download->mall_id,
  318. 'mch_id' => $download->mch_id,
  319. 'store_id' => $download->store_id,
  320. 'name' => $newFileName,
  321. 'type' => $download->type,
  322. 'handler_class' => $download->handler_class,
  323. 'method' => $download->method,
  324. 'params' => $download->params,
  325. 'data' => $exportList
  326. ];
  327. $downloadModel = Download::setData($downloadData);
  328. if ($downloadModel === false) {
  329. Yii::$app->custom->logs('创建下载任务失败:' . $downloadData['name'], Download::getStaticError());
  330. throw new \Exception('创建新下载任务失败');
  331. };
  332. $download = $downloadModel;
  333. }
  334. $csv->export();
  335. $csv->updateDown($download, $params['mall_id']);
  336. $i++;
  337. }
  338. unset($exportList);
  339. }
  340. $transaction->commit();// 事务完成
  341. return true;
  342. } catch (\Exception $e) {
  343. $transaction->rollBack();
  344. $download->status = 3;
  345. $res = $download->save();
  346. self::setStaticError($e->getMessage());
  347. return $e->getMessage();
  348. }
  349. }
  350. /**
  351. * 构建导出数据
  352. * @param $store
  353. * @param $fields
  354. * @return array
  355. */
  356. public static function buildExportItem($store, $fields): array
  357. {
  358. $exportItem = [];
  359. foreach ($fields as $field) {
  360. switch ($field) {
  361. case 'store_name':
  362. $exportItem[$field] = $store['mch']['store_name'] ?? '';
  363. break;
  364. case 'user_id':
  365. $exportItem[$field] = $store['user_id'] ?? '';
  366. break;
  367. case 'nickname':
  368. $exportItem[$field] = $store['user']['nickname'] ?? '';
  369. break;
  370. case 'mobile':
  371. $exportItem[$field] = $store['user']['mobile'] ?? '';
  372. break;
  373. case 'order_no':
  374. $exportItem[$field] = $store['order_no'] ?? '';
  375. break;
  376. case 'order_money':
  377. $exportItem[$field] = $store['order_money'] ?? '';
  378. break;
  379. case 'discount_money':
  380. $exportItem[$field] = $store['discount_money'] ?? '';
  381. break;
  382. case 'pay_money':
  383. $exportItem[$field] = $store['pay_money'] ?? '';
  384. break;
  385. case 'addons_bonus':
  386. $exportItem[$field] = $store['addons_bonus'] ?? '';
  387. break;
  388. case 'service_charge':
  389. $exportItem[$field] = $store['service_charge'] ?? '';
  390. break;
  391. case 'amount_received':
  392. $exportItem[$field] = $store['amount_received'] ?? '';
  393. break;
  394. case 'is_settlement':
  395. $exportItem[$field] = $store['is_settlement'] == 1 ? '已结算' : '未结算';
  396. break;
  397. case 'created_at':
  398. $exportItem[$field] = date('Y-m-d H:i:s', $store['created_at']);
  399. break;
  400. }
  401. }
  402. return $exportItem;
  403. }
  404. /**
  405. * 根据查询条件获取用户ID
  406. * @param $params
  407. * @param $field
  408. * @return array
  409. */
  410. public static function getUserIdsByParams($params, $field): array
  411. {
  412. if (empty($params[$field])) {
  413. return [];
  414. }
  415. try {
  416. return User::find()
  417. ->select('id')
  418. ->where(['mall_id' => $params['mall_id'], 'status' => StatusEnum::ENABLED])
  419. ->andWhere(['like', $field, $params[$field]])
  420. ->asArray()
  421. ->column();
  422. } catch (\Exception $e) {
  423. // 记录异常日志
  424. \Yii::error("Failed to query user IDs by $field: " . $e->getMessage());
  425. return [];
  426. }
  427. }
  428. public static function fieldsList(array $fields = []): array
  429. {
  430. $field_list = [
  431. 'store_name' => '多商户名称',
  432. 'nickname' => '会员昵称',
  433. 'mobile' => '会员手机号',
  434. 'order_no' => '订单编号',
  435. 'order_money' => '应付金额',
  436. 'pay_money' => '实付金额',
  437. 'discount_money' => '优惠金额',
  438. 'amount_received' => '实收金额',
  439. 'created_at' => '下单时间',
  440. ];
  441. if (empty($fields)) {
  442. return $field_list;
  443. } else {
  444. $new_list = [];
  445. foreach ($fields as $val) {
  446. if (!empty($field_list[$val])) {
  447. $new_list[$val] = $fields[$val];
  448. }
  449. }
  450. return $new_list;
  451. }
  452. }
  453. /**
  454. * 资产管理-订单明细导出
  455. * @param array $fields
  456. * @return array
  457. */
  458. public static function orderDetailFieldsList(array $fields = []): array
  459. {
  460. return [
  461. 'store_name' => '商户名称',
  462. 'user_id' => '用户ID',
  463. 'nickname' => '用户昵称',
  464. 'mobile' => '用户手机号',
  465. 'order_no' => '订单编号',
  466. 'order_money' => '订单金额',
  467. 'discount_money' => '优惠金额',
  468. 'pay_money' => '实付金额',
  469. 'addons_bonus' => '插件分红',
  470. 'service_charge' => '服务费',
  471. 'amount_received' => '到账金额',
  472. 'is_settlement' => '状态',
  473. 'created_at' => '创建时间',
  474. ];
  475. }
  476. }