VideoShopOrderForm.php 45 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929
  1. <?php
  2. namespace app\modules\admin\models;
  3. use app\models\Attr;
  4. use app\models\AttrGroup;
  5. use app\models\common\CommonGoods;
  6. use app\models\Goods;
  7. use app\models\GoodsPic;
  8. use app\models\Option;
  9. use app\models\Order;
  10. use app\models\OrderDetail;
  11. use app\models\OrderRefund;
  12. use app\models\SaasUser;
  13. use app\models\Share;
  14. use app\models\ShareLevel;
  15. use app\models\StoreMini;
  16. use app\models\User;
  17. use app\models\VideoShopGoodsExt;
  18. use app\models\VideoShopOrderExt;
  19. use app\models\VideoShopSharer;
  20. use app\models\VideoShopUser;
  21. use app\modules\client\models\v1\ShareMoneyForm;
  22. use app\utils\OrderNo;
  23. use EasyWeChat\Kernel\BaseClient;
  24. use yii\base\Model;
  25. use yii\helpers\Json;
  26. use app\models\District;
  27. class VideoShopOrderForm extends Model
  28. {
  29. public $params;
  30. public $store_id;
  31. public $mini_id;
  32. public $miniProgram;
  33. public $ids;
  34. public $start_time;
  35. public $end_time;
  36. public $sharer_id;
  37. public $order_no;
  38. public $status;
  39. public function rules()
  40. {
  41. return [
  42. [['ids', 'start_time', 'end_time', 'order_no'], 'string'],
  43. [['sharer_id', 'status', 'mini_id'], 'integer'],
  44. [['params'], 'safe']
  45. ];
  46. }
  47. // 获取商品id列表
  48. public function syncOrderList($next_key = '', $page_size = 10) {
  49. try {
  50. if (!$this->miniProgram) {
  51. throw new \Exception('请检查小店状态');
  52. }
  53. $mini_id = $this->mini_id;
  54. //获取两天内
  55. //如果没有两天就不执行操作
  56. //..
  57. // if (cache()->get('sync_wechat_sharer_order' . $mini_id)) {
  58. // return false;
  59. // }
  60. $end_time = $this->end_time;//60 * 60 * 24 * 2; //两天
  61. // cache()->set('sync_wechat_sharer_order' . $mini_id, true, $diff_time);
  62. $start_time = $this->start_time;//time() - $diff_time;
  63. $data = [
  64. 'next_key' => $next_key,
  65. 'page_size' => $page_size,
  66. 'create_time_range' => [
  67. 'start_time' => $start_time,
  68. 'end_time' => $end_time
  69. ]
  70. ];
  71. $client = new BaseClient($this->miniProgram);
  72. $res = $client->httpPostJson('channels/ec/order/list/get', $data);
  73. if (!$res['errcode'] && !empty($res)) {
  74. //根据商品id同步商品
  75. // ....
  76. if ($res['order_id_list']) {
  77. $result = $this->syncOrderInfo($res['order_id_list']);
  78. //下一页
  79. if (count($res['order_id_list']) >= $page_size) {
  80. $this->syncOrderList($res['next_key']);
  81. }
  82. }
  83. } else {
  84. throw new \Exception($res['errmsg'], $res['errcode']);
  85. }
  86. return [
  87. 'code' => 0,
  88. 'msg' => '同步成功'
  89. ];
  90. } catch (\Exception $e) {
  91. return [
  92. 'code' => $e->getCode() ?: 1,
  93. 'msg' => $e->getMessage()
  94. ];
  95. }
  96. }
  97. public function _orderInfo($store_id, $mini_id, $order_id, $cache_order_info = null, $refresh = 0) {
  98. $cache_order_info = $cache_order_info ? json_decode($cache_order_info, true) : null;
  99. if(!$refresh && $cache_order_info){
  100. if(($cache_order_info['update_time'] < time() - 86400 * 30) || $cache_order_info['status'] >= 100 || ($cache_order_info['aftersale_detail']['aftersale_order_list'] && !$cache_order_info['aftersale_detail']['on_aftersale_order_cnt'])){
  101. return $cache_order_info;
  102. }
  103. }
  104. $orderInfo = null;
  105. $data = [
  106. 'order_id' => $order_id
  107. ];
  108. $miniProgram = \app\utils\Wechat\WechatMini::getWechatConfig($store_id, $mini_id, 1);
  109. $client = new BaseClient($miniProgram);
  110. $res = $client->httpPostJson('channels/ec/order/get', $data);
  111. if (!$res['errcode'] && !empty($res)) {
  112. $orderInfo = $res['order'];
  113. VideoShopOrderExt::updateAll(['order_info' => json_encode($orderInfo, JSON_UNESCAPED_UNICODE)], ['out_order_id' => $order_id]);
  114. }
  115. return $orderInfo;
  116. }
  117. //根据订单id同步订单
  118. public function syncOrderInfo($order_id_list = []) {
  119. if (!$order_id_list) {
  120. throw new \Exception('缺少order_id');
  121. }
  122. $store_id = $this->store_id;
  123. $mini_id = $this->mini_id;
  124. foreach ($order_id_list as $item) {
  125. $t = \Yii::$app->db->beginTransaction();
  126. try {
  127. $data = [
  128. 'order_id' => $item
  129. ];
  130. $client = new BaseClient($this->miniProgram);
  131. $res = $client->httpPostJson('channels/ec/order/get', $data);
  132. if (!$res['errcode'] && !empty($res)) {
  133. $orderInfo = $res['order'];
  134. $video_shop_order = VideoShopOrderExt::findOne(['store_id' => $store_id, 'out_order_id' => $item]);
  135. //增加用户
  136. //根据地址中的手机号判断是否存在用户
  137. $address_info = [];
  138. if ($orderInfo['order_detail']['delivery_info']['address_info']) {
  139. $address_info = $orderInfo['order_detail']['delivery_info']['address_info'];
  140. }
  141. //关联系统用户
  142. $tel_number = $address_info['tel_number'];
  143. $nick_name = substr_replace($tel_number, '******', 3, 6);
  144. $unionid = $orderInfo['unionid'];
  145. if(!$unionid){
  146. debug_log(['缺少unionid', $store_id, $item, $unionid], __CLASS__);
  147. // throw new \Exception('缺少unionid');
  148. }
  149. $open_id = $orderInfo['openid'];
  150. $shop_user = VideoShopUser::findOne(['unionid' => $unionid]);
  151. $saas_id = 0;
  152. if ($shop_user) {
  153. // $saas_id = $shop_user->saas_id;
  154. }
  155. $user_id = 0;
  156. if($unionid){
  157. $user = User::findOne(['store_id' => $store_id, 'wechat_union_id' => $unionid]);
  158. debug_log(['$user', $store_id, $item, $unionid, $user['id']], __CLASS__);
  159. if($user){
  160. $user_id = $user->id;
  161. $saasUser = SaasUser::findOne(['mobile' => $user->binding]);
  162. $saas_id = (int)$saasUser['id'];
  163. }
  164. }
  165. if(!$saas_id){
  166. debug_log(['非商城用户,unionid', $store_id, $item, $unionid], __CLASS__);
  167. }
  168. $saas_user = SaasUser::findOne(['id' => $saas_id, 'is_delete' => 0]);
  169. if (!$saas_user) {
  170. // $saas_user = SaasUser::findOne(['mobile' => $tel_number, 'is_delete' => 0]);
  171. // if (!$saas_user) {
  172. // $saas_user = new SaasUser();
  173. // $saas_user->access_token = \Yii::$app->security->generateRandomString();
  174. // $saas_user->avatar = '';
  175. // $saas_user->mobile = $tel_number ?: '';
  176. // $saas_user->name = $nick_name;
  177. // $saas_user->store_id = $store_id;
  178. // if (!$saas_user->save()) {
  179. // throw new \Exception(json_encode($saas_user->errors, JSON_UNESCAPED_UNICODE));
  180. // }
  181. // }
  182. }
  183. if (!$shop_user) {
  184. $shop_user = new VideoShopUser();
  185. $shop_user->unionid = $unionid;
  186. $shop_user->open_id = $open_id;
  187. $shop_user->store_id = $store_id;
  188. $shop_user->mini_id = $mini_id;
  189. $shop_user->saas_id = (int)$saas_id;
  190. if (!$shop_user->save()) {
  191. throw new \Exception(json_encode($shop_user->errors, JSON_UNESCAPED_UNICODE));
  192. }
  193. }
  194. // $user = User::findOne(['binding' => $saas_user->mobile, 'is_delete' => 0, 'store_id' => $store_id]);
  195. if (!$user) {
  196. // $user = new User();
  197. // $user->access_token = \Yii::$app->security->generateRandomString();
  198. // $user->binding = $saas_user->mobile;
  199. // $user->type = User::USER_TYPE_NORMAL;
  200. // $user->nickname = substr_replace($saas_user->mobile, '******', 3, 6);
  201. // $user->avatar_url = '';
  202. // $user->username = \Yii::$app->security->generateRandomString();
  203. // $user->password = \Yii::$app->security->generatePasswordHash(\Yii::$app->security->generateRandomString(), 5);
  204. // $user->auth_key = \Yii::$app->security->generateRandomString();
  205. // $user->is_delete = User::USER_NOT_DELETE;
  206. // $user->store_id = $store_id;
  207. // $user->platform = User::USER_FROM_WECHAT; // 微信
  208. // $user->wechat_open_id = $open_id;
  209. // if (!$user->save()) {
  210. // throw new \Exception(json_encode($user->errors, JSON_UNESCAPED_UNICODE));
  211. // }
  212. }
  213. $order = null;
  214. if ($video_shop_order && $video_shop_order->order_id) {
  215. $order = Order::findOne($video_shop_order->order_id);
  216. debug_log([$video_shop_order->order_id, $order->id, $order->is_sale], __CLASS__);
  217. if (intval($order->is_sale) === 1) {
  218. continue;
  219. }
  220. }
  221. if (!$order) {
  222. $order = new Order();
  223. $order->order_no = OrderNo::getOrderNo(OrderNo::ORDER_MALL);
  224. $order->profit = self::getOrderProfit($store_id, $orderInfo['order_detail']['product_infos']);
  225. }
  226. self::setOrderAddr($order, $orderInfo['order_detail']['delivery_info']['address_info']);
  227. $order->created_at = $orderInfo['create_time'];
  228. $order->is_pay = Order::IS_PAY_TRUE;
  229. $order->user_id = $user_id;
  230. $order->store_id = $store_id;
  231. $order->first_price = 0;
  232. $order->second_price = 0;
  233. $order->third_price = 0;
  234. //支付信息
  235. if ($orderInfo['order_detail']['pay_info']) {
  236. //支付时间
  237. if ($orderInfo['order_detail']['pay_info']['pay_time']) {
  238. $order->pay_time = $orderInfo['order_detail']['pay_info']['pay_time'];
  239. }
  240. //支付方式 微信支付
  241. if ($orderInfo['order_detail']['pay_info']['payment_method']) {
  242. $order->pay_type = Order::PAY_TYPE_WECHAT;
  243. }
  244. //微信支付id
  245. if ($orderInfo['order_detail']['pay_info']['transaction_id']) {
  246. $order->transaction_id = $orderInfo['order_detail']['pay_info']['transaction_id'];
  247. }
  248. }
  249. //订单金额信息
  250. if ($orderInfo['order_detail']['price_info']) {
  251. //订单金额
  252. if ($orderInfo['order_detail']['price_info']['order_price']) {
  253. $order->pay_price = $order->total_price = ($orderInfo['order_detail']['price_info']['order_price'] * 0.01);
  254. }
  255. //随机立减
  256. if ($orderInfo['order_detail']['price_info']['discounted_price']) {
  257. $order->rand_discount = ($orderInfo['order_detail']['price_info']['discounted_price'] * 0.01);
  258. }
  259. //运费
  260. if ($orderInfo['order_detail']['price_info']['freight']) {
  261. $order->express_price = ($orderInfo['order_detail']['price_info']['freight'] * 0.01);
  262. }
  263. //改价后的运费
  264. if ($orderInfo['order_detail']['price_info']['change_freight']) {
  265. $order->express_price = ($orderInfo['order_detail']['price_info']['change_freight'] * 0.01);
  266. }
  267. }
  268. // 发货信息
  269. if ($orderInfo['order_detail']['delivery_info']['delivery_product_info']) {
  270. $delivery_product_info = $orderInfo['order_detail']['delivery_info']['delivery_product_info'];
  271. //快递单号
  272. if ($delivery_product_info['waybill_id']) {
  273. $order->express_no = $delivery_product_info['waybill_id'];
  274. }
  275. //快递公司名称
  276. if ($delivery_product_info['delivery_name']) {
  277. $order->express = $delivery_product_info['delivery_name'];
  278. }
  279. //发货时间
  280. if ($delivery_product_info['delivery_time']) {
  281. $order->send_time = $delivery_product_info['delivery_time'];
  282. }
  283. }
  284. switch ($orderInfo['status']) {
  285. case 10: //待付款
  286. $order->trade_status = Order::ORDER_FLOW_DEFAULT;
  287. $order->is_pay = Order::IS_PAY_FALSE;
  288. break;
  289. case 21: //发货 / 部分发货
  290. case 20:
  291. $order->trade_status = Order::ORDER_FLOW_NO_SEND;
  292. break;
  293. case 30: //待收货
  294. $order->trade_status = Order::ORDER_FLOW_SEND;
  295. break;
  296. case 100: //已收货
  297. $order->trade_status = Order::ORDER_FLOW_CONFIRM;
  298. $order->confirm_time = $orderInfo['update_time'];
  299. break;
  300. case 200: //已售后完成,订单取消
  301. if(empty($order->express_no)){
  302. $order->trade_status = Order::ORDER_FLOW_CANCEL;
  303. }
  304. case 250: //超时未支付
  305. $order->trade_status = Order::ORDER_FLOW_CANCEL;
  306. $order->is_pay = Order::IS_PAY_FALSE;
  307. break;
  308. }
  309. if ($address_info) {
  310. $order->name = $address_info['user_name'];
  311. $order->mobile = $tel_number;
  312. $order->address = $address_info['province_name'] .
  313. $address_info['city_name'] .
  314. $address_info['county_name'] .
  315. $address_info['detail_info'];
  316. $order->address_data = json_encode([
  317. 'province' => $address_info['province_name'],
  318. 'city' => $address_info['city_name'],
  319. 'district' => $address_info['county_name'],
  320. 'detail' => $address_info['detail_info'],
  321. 'latitude' => '',
  322. 'longitude' => ''
  323. ], JSON_UNESCAPED_UNICODE);
  324. }
  325. $order->discount = 10;
  326. $order->integral = json_encode([
  327. 'forehead' => 0,
  328. 'forehead_integral' => 0
  329. ]);
  330. $order->version = cyy_version();
  331. $order->updated_at = $orderInfo['update_time'];
  332. $sharer_id = 0;
  333. if ($orderInfo['order_detail']['sharer_info']) {
  334. $sharer_info = $orderInfo['order_detail']['sharer_info'];
  335. $sharer = VideoShopSharer::findOne(['openid' => $sharer_info['sharer_openid'], 'action_id' => $mini_id, 'is_delete' => 0]);
  336. $sharer_id = $sharer->id ?: 0;
  337. //
  338. if ($sharer->user_id) {
  339. if ($video_shop_order) {
  340. $video_shop_order->old_parent_id = $sharer->user_id;
  341. }
  342. if($user){
  343. if ($user->parent_id <= 0 && $user->old_parent_id <= 0) {
  344. $user->parent_id = $user->old_parent_id = $order->old_parent_id;
  345. }
  346. if (!$user->save()) {
  347. throw new \Exception(json_encode($user->errors, JSON_UNESCAPED_UNICODE));
  348. }
  349. }
  350. }
  351. $order->rebate = 0;
  352. }
  353. if (!$order->save()) {
  354. throw new \Exception(json_encode($order->errors, JSON_UNESCAPED_UNICODE));
  355. }
  356. $promoter_id = [];
  357. if ($orderInfo['order_detail']['source_infos']) {
  358. $source_infos = $orderInfo['order_detail']['source_infos'];
  359. foreach((array)$source_infos as $source_info){
  360. $promoter_id[] = $source_info['account_id'];
  361. break;
  362. }
  363. }
  364. if (!$video_shop_order) {
  365. $video_shop_order = new VideoShopOrderExt();
  366. $video_shop_order->out_order_id = $item;
  367. $video_shop_order->store_id = $store_id;
  368. $video_shop_order->mini_id = $mini_id;
  369. }
  370. $video_shop_order->order_id = $order->id;
  371. $video_shop_order->sharer_id = $sharer_id;
  372. $video_shop_order->promoter_id = implode(',', $promoter_id);
  373. $orderInfo['order_detail']['commission_infos'] && $video_shop_order->commission_status = $orderInfo['order_detail']['commission_infos'][0]['status'];
  374. $video_shop_order->order_info = json_encode($orderInfo, JSON_UNESCAPED_UNICODE);
  375. if (!$video_shop_order->save()) {
  376. throw new \Exception(json_encode($video_shop_order->errors, JSON_UNESCAPED_UNICODE));
  377. }
  378. //保存售后 订单详情
  379. $order_d = [];
  380. if ($orderInfo['order_detail']['product_infos']) {
  381. $product_infos = $orderInfo['order_detail']['product_infos'];
  382. $order_detail = OrderDetail::findOne(['order_id' => $order->id]);
  383. if(!$order_detail){
  384. foreach ($product_infos as $product_info) {
  385. $shop_goods = VideoShopGoodsExt::findOne(['product_id' => (string)$product_info['product_id'],
  386. 'is_delete' => 0, 'mini_id' => $mini_id]);
  387. if ($shop_goods) {
  388. $goods = Goods::findOne($shop_goods->goods_id);
  389. if ($goods) {
  390. // 获取规格
  391. $attr = $goods->attr;
  392. $attr = json_decode($attr, true);
  393. $buy_attr = [];
  394. foreach ($attr as $attr_item) {
  395. if ($attr_item['sku_id'] === $product_info['sku_id']) {
  396. foreach ($attr_item['attr_list'] as &$attr_item_) {
  397. $attr_model = Attr::findOne($attr_item_['attr_id']);
  398. if ($attr_model) {
  399. $attr_group_model = AttrGroup::findOne($attr_model->attr_group_id);
  400. if ($attr_group_model) {
  401. $attr_item_ = array_merge($attr_item_, [
  402. 'attr_group_id' => $attr_group_model->id,
  403. 'attr_group_name' => $attr_group_model->attr_group_name
  404. ]);
  405. }
  406. }
  407. }
  408. $buy_attr = $attr_item['attr_list'];
  409. }
  410. }
  411. $order_detail = new OrderDetail();
  412. $order_detail->order_id = $order->id;
  413. $order_detail->goods_id = $shop_goods->goods_id;
  414. $order_detail->goods_name = $goods->name;
  415. $order_detail->num = $product_info['sku_cnt'] ?: 1;
  416. $order_detail->total_price = ($product_info['real_price'] * 0.01);
  417. $order_detail->created_at = $order->created_at;
  418. $order_detail->attr = json_encode($buy_attr, JSON_UNESCAPED_UNICODE);
  419. $order_detail->pic = $product_info['thumb_img'] ?: $goods->cover_pic;
  420. $order_detail->goods_info = json_encode($goods->toArray(), JSON_UNESCAPED_UNICODE);
  421. if (intval($orderInfo['status']) === 200) {
  422. $order_detail->is_refund = 1;
  423. }
  424. if (!$order_detail->save()) {
  425. throw new \Exception(json_encode($order_detail->errors, JSON_UNESCAPED_UNICODE));
  426. }
  427. array_push($order_d, $order_detail->id);
  428. }
  429. }
  430. }
  431. }
  432. }
  433. if (empty($order_detail)) {
  434. throw new \Exception('商品未找到');
  435. }
  436. $order_detail = $this->getOrderDetail($order);
  437. if ($video_shop_order->first_price <= 0) {
  438. $video_shop_order->first_price = $this->getShareCommissionMoney($order, $order_detail, $video_shop_order->old_parent_id, 1) ?: 0.00;
  439. }
  440. if (!$order->save()) {
  441. throw new \Exception(json_encode($order->errors, JSON_UNESCAPED_UNICODE));
  442. }
  443. if (intval($orderInfo['status']) === 200 && !empty($order->express_no)) {
  444. $order_refund = OrderRefund::findOne(['order_id' => $order->id]);
  445. if (!$order_refund) {
  446. $order_refund = new OrderRefund();
  447. $order_refund->store_id = $store_id;
  448. $order_refund->order_id = $order->id;
  449. $order_refund->user_id = $user_id;
  450. $order_refund->order_refund_no = $this->getOrderRefundNo();
  451. $order_refund->refund_price = $order->pay_price;
  452. $order_refund->type = 1;
  453. $order_refund->status = 1;
  454. $order_refund->is_agree = 1;
  455. $order_refund->is_user_send = 1;
  456. }
  457. $order_refund->order_detail_id = json_encode($order_d);
  458. $order_refund->pic_list = json_encode([]);
  459. if (!$order_refund->save()) {
  460. throw new \Exception(json_encode($order_refund->errors, JSON_UNESCAPED_UNICODE));
  461. }
  462. }
  463. }
  464. $t->commit();
  465. } catch (\Exception $e) {
  466. $t->rollBack();
  467. \Yii::error($e);
  468. debug_log([$store_id, $item, $order_id_list, $e->getMessage()], __CLASS__);
  469. // return [
  470. // 'code' => $e->getCode() ?: 1,
  471. // 'msg' => $e->getMessage() . $e->getLine() . $e->getFile()
  472. // ];
  473. }
  474. }
  475. return [
  476. 'code' => 0,
  477. 'msg' => '操作成功'
  478. ];
  479. }
  480. public static function setOrderAddr(Order $order, $address_info = []){
  481. $province = District::find()->where(['like', 'name', $address_info['province_name']])->one();
  482. $city = District::find()->where(['like', 'name', $address_info['city_name']])->one();
  483. $county = District::find()->where(['like', 'name', $address_info['county_name']])->one();
  484. $order->province_id = (int)$province['id'];
  485. $order->city_id = (int)$city['id'];
  486. $order->district_id = (int)$county['id'];
  487. }
  488. public static function getOrderProfit($store_id, $product_infos = []){
  489. $orderProfit = 0;
  490. foreach($product_infos as $product_info){
  491. $payPrice = $product_info['real_price'] / 100;
  492. $goodsExt = VideoShopGoodsExt::findOne(['store_id' => $store_id, 'product_id' => (string)$product_info['product_id']]);
  493. $goods = Goods::findOne($goodsExt['goods_id']);
  494. // 计算单个商品可分红金额
  495. $profit = $goods['rate_type'] == 0 ? floatval($payPrice * $goods['rate'] / 100) : floatval($goods['rate']) * $product_info['sku_cnt'];
  496. $orderProfit += $profit;
  497. }
  498. return $orderProfit > 0 ? $orderProfit : 0;
  499. }
  500. private function getOrderRefundNo()
  501. {
  502. $order_refund_no = null;
  503. while (true) {
  504. $order_refund_no = date('YmdHis') . mt_rand(100000, 999999);
  505. $exist_order_refund_no = OrderRefund::find()->where(['order_refund_no' => $order_refund_no])->exists();
  506. if (!$exist_order_refund_no) {
  507. break;
  508. }
  509. }
  510. return $order_refund_no;
  511. }
  512. public function getShareCommissionMoney($order, $orderDetail, $user_id, $type = 1) {
  513. $setting = Option::get('share_money_setting', $order->store_id);
  514. $setting = $setting ? Json::decode($setting['value']) : [];
  515. if (!$setting) {
  516. \Yii::warning('未开启分销设置1');
  517. return false;
  518. }
  519. // if (!is_array($setting['commission_type']) || empty($setting['commission_type'])) {
  520. // \Yii::warning('未开启分销设置2');
  521. // return false;
  522. // }
  523. $share_send_type = 0;
  524. // 获取到当前到订单佣金发放类型 1: 佣金 2:积分, 3:余额
  525. if (!empty($setting['giveType'])) {
  526. $share_send_type = $setting['giveType'];
  527. }
  528. $integral = Option::get('integral', $order->store_id, 'store')['value'];
  529. if (!$integral && $share_send_type == 2) {
  530. \Yii::warning('发放积分佣金类型比例未设置');
  531. return false;
  532. }
  533. $order->share_send_type = $share_send_type;
  534. $share = Share::findOne(['user_id' => $user_id, 'status' => Share::SHARE_AUDIT_PASS, 'is_delete' => Share::SHARE_NOT_DELETE]);
  535. $share_commission_money = 0;
  536. if ($share) {
  537. $share_level_id = $share->level;
  538. $share_level = ShareLevel::findOne(['level' => $share_level_id, 'store_id' => $order->store_id, 'is_delete' => ShareLevel::SHARE_NOT_DELETE,
  539. 'status' => ShareLevel::STATUS_ON]);
  540. foreach ($orderDetail as $item) {
  541. // TODO: 价格
  542. $item_price = doubleval($item['price']);
  543. // $item_price = doubleval($orderShare->pay_price);
  544. $rate_first = 0;
  545. if ($item['individual_share'] == 1) {
  546. if ($type === 1) {
  547. $rate_first = $item['share_commission_new_first']['share_commission_level_' . $share_level_id];
  548. } elseif ($type === 2) {
  549. $rate_first = $item['share_commission_new_second']['share_commission_level_' . $share_level_id];
  550. } elseif ($type === 3) {
  551. $rate_first = $item['share_commission_new_third']['share_commission_level_' . $share_level_id];
  552. }
  553. $shareType = $item['share_type'];
  554. } else {
  555. $setting_shara = Option::get('share_money_setting', $order->store_id, 'share');
  556. $setting_shara = $setting_shara ? Json::decode($setting_shara['value']) : [];
  557. if ($type === 1) {
  558. $rate_first = $share_level->first_profit ?? ($setting_shara['level_one']['value'] ?? 0);
  559. } elseif ($type === 2) {
  560. $rate_first = $share_level->second_profit ?? ($setting_shara['level_two']['value'] ?? 0);
  561. } elseif ($type === 3) {
  562. $rate_first = $share_level->third_profit ?? ($setting_shara['level_three']['value'] ?? 0);
  563. }
  564. if ($share_level) {
  565. $shareType = intval($share_level->profit_type);
  566. } else {
  567. $shareType = 0;
  568. }
  569. }
  570. if ($shareType == 1) { // 金钱
  571. if ($share_send_type == 2) {
  572. // 兑换比例
  573. $share_commission_money += round($rate_first * $integral) * $item['num'];
  574. } else {
  575. $share_commission_money += $rate_first * $item['num'];
  576. }
  577. } else { // 比例
  578. if ($share_send_type == 2) {
  579. $share_commission_money += round($item_price * ($rate_first / 100) * $integral);
  580. } else {
  581. $share_commission_money += $item_price * $rate_first / 100;
  582. }
  583. }
  584. }
  585. return sprintf("%.2f", $share_commission_money < 0.01 ? 0 : $share_commission_money);
  586. }
  587. return 0;
  588. }
  589. private function getOrderDetail($order)
  590. {
  591. $list = OrderDetail::find()->where(['is_delete' => 0, 'order_id' => $order->id])->all();
  592. $newList = [];
  593. foreach ($list as $value) {
  594. $goods = $value->goods;
  595. $buyAttrList = Json::decode($value['attr']);
  596. if ($goods['attr_setting_type'] === 1) {
  597. $attrIdArr2 = [];
  598. foreach ($buyAttrList as $attrListItem2) {
  599. $attrIdArr2[] = $attrListItem2['attr_id'];
  600. }
  601. $goodsData = [
  602. 'attr' => $goods['attr'],
  603. 'price' => $goods['price'],
  604. 'is_level' => $goods['is_level'],
  605. ];
  606. $res = CommonGoods::currentGoodsAttr($goodsData, $attrIdArr2, [], 1, $order->user_id, $order->store_id);
  607. $newItem = [
  608. 'individual_share' => $goods['individual_share'],
  609. 'share_commission_new_first' => $res['share_commission_new_first'],
  610. 'share_commission_new_second' => $res['share_commission_new_second'],
  611. 'share_commission_new_third' => $res['share_commission_new_third'],
  612. 'share_type' => $goods['share_type'],
  613. 'num' => $value['num'],
  614. 'price' => $value['total_price'],
  615. 'mch_id' => $goods['mch_id']
  616. ];
  617. } else {
  618. $newItem = [
  619. 'individual_share' => $goods['individual_share'],
  620. 'share_commission_new_first' => $goods['share_commission_new_first'] ? json_decode($goods['share_commission_new_first'], true) : [],
  621. 'share_commission_new_second' => $goods['share_commission_new_second'] ? json_decode($goods['share_commission_new_second'], true) : [],
  622. 'share_commission_new_third' => $goods['share_commission_new_third'] ? json_decode($goods['share_commission_new_third'], true) : [],
  623. 'share_type' => $goods['share_type'],
  624. 'num' => $value['num'],
  625. 'price' => $value['total_price'],
  626. 'mch_id' => $goods['mch_id']
  627. ];
  628. }
  629. array_push($newList, $newItem);
  630. }
  631. return $newList;
  632. }
  633. public function getSharerOrderList($params = []) {
  634. try {
  635. $sharer_id = $this->sharer_id;
  636. $store_id = $this->store_id;
  637. $mini_id = $this->mini_id;
  638. $order_no = $this->order_no;
  639. $status = $this->status;
  640. $start_time = $this->start_time;
  641. $end_time = $this->end_time;
  642. $query = Order::find()->alias('o')->where(['o.store_id' => $store_id, 'o.is_delete' => 0, 's.is_cancle' => 0])
  643. ->leftJoin(['oe' => VideoShopOrderExt::tableName()], 'o.id = oe.order_id')->andWhere(['IS NOT', 'oe.id', NULL])
  644. ->leftJoin(['s' => StoreMini::tableName()], 'oe.mini_id = s.id');
  645. if ($params['order_id']) {
  646. $query->andWhere(['o.id' => $params['order_id']]);
  647. }
  648. if ($params['promoter_id']) {
  649. $query->andWhere(['oe.promoter_id' => $params['promoter_id']]);
  650. }
  651. if (isset($params['commission_status']) && $params['commission_status'] > -1) {
  652. $query->andWhere(['oe.commission_status' => $params['commission_status']]);
  653. }
  654. if ($sharer_id) {
  655. $query->andWhere(['oe.sharer_id' => $sharer_id]);
  656. }
  657. if ($mini_id) {
  658. $query->andWhere(['oe.mini_id' => $mini_id]);
  659. }
  660. if ($order_no) {
  661. $query->andWhere(['OR', ['LIKE', 'o.order_no', $order_no], ['LIKE', 'oe.out_order_id', $order_no]]);
  662. }
  663. if ($start_time) {
  664. $query->andWhere(['>=', 'o.created_at', strtotime($start_time)]);
  665. }
  666. if ($end_time) {
  667. $query->andWhere(['<=', 'o.created_at', strtotime($end_time)]);
  668. }
  669. if ($status !== '' && in_array($status, [-1, 0, 1, 2, 3, 4])) {//待支付 待发货 已取消 待收货 已收货 有售后
  670. if ($status === 4) {
  671. $query->leftJoin(['or' => OrderRefund::tableName()], 'or.order_id = o.id')->andWhere(['IS NOT', 'or.id', NULL]);
  672. } else {
  673. $query->andWhere(['o.trade_status' => $status]);
  674. }
  675. }
  676. $query->select('o.*, oe.mini_id, oe.sharer_id, oe.promoter_id, oe.order_info, oe.commission_status, oe.out_order_id')->orderBy('o.created_at desc');
  677. $pagination = pagination_make($query);
  678. $store_mini_ = StoreMini::find()->where(['store_id' => $store_id, 'fuwu_type' => 1, 'is_cancle' => 0])
  679. ->select('id, mini_nickname')->asArray()->all();
  680. $sharer_list = VideoShopSharer::find()->where(['store_id' => $store_id, 'is_delete' => 0, 'is_use' => 1])
  681. ->select('id, nickname')->asArray()->all();
  682. foreach ($pagination['list'] as &$item) {
  683. $item['created_at'] = date('Y-m-d H:i:s', $item['created_at']);
  684. $item['trade_status'] = (string)$item['trade_status'];
  685. $order_refund = OrderRefund::findOne(['order_id' => $item['id']]);
  686. if ($order_refund) {
  687. $item['trade_status'] = '4';
  688. }
  689. $item['user'] = User::findOne($item['user_id']);
  690. $item['saas_user'] = SaasUser::findOne(['mobile' => $item['user']['binding']]);
  691. $sharer = VideoShopSharer::findOne($item['sharer_id']);
  692. $item['sharer_name'] = '-';
  693. $item['share_level'] = '-';
  694. $item['first_profit'] = '0.00';
  695. if ($sharer) {
  696. $item['sharer_name'] = $sharer->nickname ?: '分享员';
  697. $share_level = ShareLevel::findOne(['store_id' => $store_id, 'level' => $sharer->share_level, 'is_delete' => 0]);
  698. $item['share_level'] = $share_level['name'] ?: '默认等级';
  699. $item['first_profit'] = $share_level['first_profit'] ?: '0.00';
  700. }
  701. $store_mini = StoreMini::findOne($item['mini_id']);
  702. $item['store_mini_name'] = '-';
  703. if ($store_mini) {
  704. $item['store_mini_name'] = $store_mini->mini_nickname;
  705. }
  706. $item['goods_list'] = OrderDetail::find()->where(['order_id' => $item['id']])->select('goods_name name, pic, total_price, num, attr')->asArray()->all();
  707. foreach ($item['goods_list'] as &$goods_item) {
  708. $goods_item['attr'] = json_decode($goods_item['attr'], true);
  709. }
  710. $item['order_info'] = $this->_orderInfo($item['store_id'], $item['mini_id'], $item['out_order_id'], $item['order_info']);
  711. $item['promoterList'] = publicRanking\PublicRankingForm::promoterList($store_id, ['promoter_id' => explode(',', $item['promoter_id'])]);
  712. }
  713. return [
  714. 'code' => 0,
  715. 'msg' => 'success',
  716. 'data' => [
  717. 'q' => $query->createCommand()->getRawSql(),
  718. 'data' => $pagination['list'],
  719. 'pageNo' => $pagination['pageNo'],
  720. 'totalCount' => $pagination['totalCount'],
  721. 'store_mini' => $store_mini_,
  722. 'sharer_list' => $sharer_list
  723. ]
  724. ];
  725. } catch (\Exception $e) {
  726. return [
  727. 'code' => $e->getCode() ?: 1,
  728. 'msg' => $e->getMessage()
  729. ];
  730. }
  731. }
  732. public function getSharerOrderNum() {
  733. try {
  734. $store_id = $this->store_id;
  735. $query = Order::find()->alias('o')->where(['o.store_id' => $store_id, 'o.is_delete' => 0, 's.is_cancle' => 0])
  736. ->leftJoin(['oe' => VideoShopOrderExt::tableName()], 'o.id = oe.order_id')->andWhere(['IS NOT', 'oe.id', NULL])
  737. ->leftJoin(['s' => StoreMini::tableName()], 'oe.mini_id = s.id')
  738. ->leftJoin(['vss' => VideoShopSharer::tableName()], 'vss.id = oe.sharer_id');
  739. $query->andWhere(['>' ,'oe.sharer_id', 0]);
  740. $query->andWhere(['o.is_pay' => 1]);
  741. $query->select('oe.sharer_id, count(o.id) order_num, sum(o.total_price) order_sum, vss.nickname, vss.invite_image, vss.username, vss.openid, vss.user_id');
  742. $query->groupBy('oe.sharer_id');
  743. $query->orderBy('order_sum DESC');
  744. $list = pagination_make($query);
  745. foreach ($list['list'] as &$item) {
  746. $item['avatar'] = '';
  747. if($item['user_id']){
  748. $user = User::find()->alias('u')->leftJoin(['su' => SaasUser::tableName()], 'su.mobile = u.binding')->select('su.avatar')->where(['u.id' => $item['user_id']])->asArray()->one();
  749. $item['avatar'] = $user['avatar'];
  750. }
  751. $first = (new ShareListForm(['store_id' => $store_id]))->getTeam($item['user_id'], 1);
  752. $item['first'] = $first;
  753. $item['first_count'] = count($first['data']);
  754. }
  755. return [
  756. 'code' => 0,
  757. 'msg' => 'success',
  758. 'data' => $list,
  759. ];
  760. } catch (\Exception $e) {
  761. return [
  762. 'code' => $e->getCode() ?: 1,
  763. 'msg' => $e->getMessage()
  764. ];
  765. }
  766. }
  767. /*订单发货*/
  768. public function orderSend($order_id, $express_no, &$msg = []) {
  769. try {
  770. if (!$order_id) {
  771. return false;
  772. }
  773. $videoShopOrder = VideoShopOrderExt::findOne(['order_id' => $order_id, 'is_delete' => 0]);
  774. if (!$videoShopOrder) {
  775. return false;
  776. }
  777. $order_detail = OrderDetail::find()->where(['order_id' => $order_id, 'is_delete' => 0])->asArray()->all();
  778. $product_infos = [];
  779. if ($order_detail) {
  780. foreach ($order_detail as $goods_item) {
  781. $arr = [];
  782. $attr_id = json_decode($goods_item['attr'], true);
  783. $attr_id = array_column($attr_id, 'attr_id');
  784. sort($attr_id);
  785. $videoShopGoods = VideoShopGoodsExt::findOne(['goods_id' => $goods_item['goods_id']]);
  786. if ($videoShopGoods) {
  787. $arr['product_cnt'] = (int)$goods_item['num'];
  788. $arr['product_id'] = $videoShopGoods->product_id;
  789. $goods = Goods::findOne($goods_item['goods_id']);
  790. if ($goods) {
  791. $attr_ = json_decode($goods->attr, true);
  792. foreach ($attr_ as $attr_item) {
  793. $attr_id_ = array_column($attr_item['attr_list'], 'attr_id');
  794. sort($attr_id_);
  795. if (!array_diff($attr_id_, $attr_id)) {
  796. $arr['sku_id'] = $attr_item['sku_id'];
  797. }
  798. }
  799. }
  800. }
  801. if (!$arr['product_cnt'] && !$arr['product_id'] && !$arr['sku_id']) {
  802. continue;
  803. }
  804. $product_infos[] = $arr;
  805. }
  806. }
  807. if (!$express_no) {
  808. throw new \Exception('请填写快递单号');
  809. }
  810. $data = [
  811. 'order_id' => $videoShopOrder->out_order_id,
  812. 'delivery_list' => [
  813. [
  814. 'delivery_id' => 'OTHER',
  815. 'deliver_type' => 1,
  816. 'waybill_id' => $express_no,
  817. 'product_infos' => $product_infos
  818. ]
  819. ]
  820. ];
  821. $client = new BaseClient($this->miniProgram);
  822. $res = $client->httpPostJson('channels/ec/order/delivery/send', $data);
  823. if (!$res['errcode'] && !empty($res)) {
  824. $msg = [
  825. 'code' => 0,
  826. 'msg' => $res['errmsg']
  827. ];
  828. } else {
  829. throw new \Exception($res['errmsg'], $res['errcode']);
  830. }
  831. return true;
  832. } catch (\Exception $e) {
  833. $msg = [
  834. 'code' => $e->getCode() ?: 1,
  835. 'msg' => $e->getMessage()
  836. ];
  837. return true;
  838. }
  839. }
  840. }