| 123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914 |
- <?php
- namespace app\common\model;
- use app\common\model\ShopGoodsModel as Goods;
- use app\common\model\UserModel as User;
- use app\common\model\UserMoneyModel as UserMoney;
- use app\api\services\ExpressServices;
- use jobs\ShopOrderJob;
- use mysql_xdevapi\Result;
- use services\CacheServices;
- use think\db\concern\ResultOperation;
- use think\Exception;
- use think\facade\Db;
- use think\Model;
- use app\common\model\ShopOrderGoodsModel as OrderGoods;
- use app\common\model\ShopOrderShippingModel as OrderShipping;
- use jobs\ShopBonusJob;
- use utils\Json;
- use utils\Queue;
- class ShopOrderModel extends Model
- {
- protected $name = 'shop_order';
- const waitPay = 0; //待支付
- const waitDelivery = 1; //待发货
- const doneDelivery = 2; //已发货
- const doneOrder = 3; //交易完成
- const cancelOrder = 4; //已取消
- /**
- * @return \think\model\relation\HasMany
- * 关联订单商品
- */
- public function withOrderGoods ()
- {
- return self::hasMany(OrderGoods::class, 'order_id', 'order_id')->field('goods_name,goods_id,goods_img,num,price,total_fee,spec_text,goods_spec_id');
- }
- /**
- * @return \think\model\relation\HasOne
- * 关联订单配送
- */
- public function withOrderShipping ()
- {
- return self::hasOne(OrderShipping::class, 'order_id', 'order_id')->field('sp_name,sp_mobile,sp_province,sp_city,sp_county,sp_remark,sp_mergename');
- }
- /**
- * 订单列表
- */
- public static function list (array $map = [], array $paginate = [], $userId, ?string $field = '*')
- {
- $map['user_id'] = $userId;
- $field = 'order_id,status,order_sn,order_type,coupon_number,created_time,order_remark,payment,ship_postfee,rebate_score,ship_name,ship_code,ship_number,expires_time,rebate_lock_score';
- foreach ($map as $k => $v) {
- if (empty($v) && $v != '0') {
- unset($map[$k]);
- }
- }
- if (isset($map['status'])) {
- if ($map['status'] == -1) {
- $map['status'] = ['0','1','2', '4', '5', '6'];
- }
- }
- // if (isset($map['order_type'])) {
- // if ($map['order_type'] == -1) {
- // $map['order_type'] = ['1','2','3', '4', '5'];
- // }
- // }
- $data = self::where($map)->where('status', '<>', 3)->relation(['withOrderGoods'])->field($field)->order('order_id desc')->paginate($paginate['limit'])->toArray();
- foreach ($data['data'] as $k=>&$v){
- foreach ($v['withOrderGoods'] as $key=>$val){
- $goods_sn = Db::name('shop_goods')->where('goods_id', $val['goods_id'])->value('goods_sn');
- // sr_log($goods_sn);
- // $val['goods_sn'] = $goods_sn;
- $data['data'][$k]['withOrderGoods'][$key]['goods_sn'] = $goods_sn;
- // $data['data'][$k]['withOrderGoods'][$key]['goods_name'] = '云德商品购买';
- }
- $v['withOrderShipping'] = Db::name('shop_order_shipping')->where('order_id', $v['order_id'])->find();
- }
- $cur_xzmoney = Db::name('system_config')->where('name', 'xz_cur_money')->where('group', 'xzconfig')->value('value');
- foreach ($data['data'] as $k => &$v) {
- $v['withOrderExpress'] = [];
- // if (in_array($v['status'], [1, 2])) {
- $v['withOrderExpress'] = ExpressServices::instance()->orderId($v['order_id'])->code($v['ship_code'])->number($v['ship_number'])->find() ?: [];
- if (intval($v['status']) == 2){
- $v['express_url'] = "https://m.kuaidi100.com/result.jsp?nu=".$v['ship_number'];
- }else{
- $v['express_url'] = "";
- }
- // }
- if ($v['status'] == 1){
- if ($v['order_type'] == 1){
- $v['can_hg'] = 1;
- }
- }else{
- $v['can_hg'] = 2;
- }
- // if ($v['status'] == 4){
- // $v['yg_goodsid'] = Db::name('yg_order')->where('order_sn', $v['order_sn'])->max('id');
- // }else{
- // $v['yg_goodsid'] = 0;
- //
- // }
- switch ($v['status']){
- case 0:
- $v['status_title'] = '待付款';
- break;
- case 1:
- $v['status_title'] = '待发货';
- break;
- case 2:
- $v['status_title'] = '已发货';
- break;
- case 3:
- $v['status_title'] = '已过期';
- break;
- case 4:
- $v['status_title'] = '已完成';
- break;
- case 5:
- $v['status_title'] = '已完成';
- break;
- case 6:
- $v['status_title'] = '已完成';
- break;
- }
- // if ($v['expires_time']){
- // $v['expires_time']=strtotime($v['expires_time']);
- // }
- // 建议竞拍价格
- // $back_redscore = number_format($v['rebate_lock_score']*env('app.YP_APPLY_HUIGOU_SCALE')/100, '2', '.', '');
- // $cur_xzmoney = Db::name('system_config')->where('name', 'xz_cur_money')->where('group', 'xzconfig')->value('value');
- // $xz_price = getXzPirceWithPrice($cur_xzmoney, $back_redscore);
- // $v['jy_buyprice'] = number_format($xz_price + 1, '0', '.', '');
- // if ($xz_price < 1){
- // $v['jy_jpprice'] = 0.1;
- // }
- //
- // if ($xz_price > 1){
- // $v['jy_jpprice'] = 1;
- // }
- //
- // if ($xz_price > 4){
- // $v['jy_jpprice'] = number_format($xz_price-2, '0', '.', '');
- // }
- // if ($xz_price > 5){
- // $v['jy_jpprice'] = number_format($xz_price-3, '0', '.', '');
- // }
- // if ($v['order_type'] == 5){
- // foreach ($v['withOrderGoods'] as $k1=>&$v1){
- // $v1['price'] = getXzPirceWithPrice($cur_xzmoney ,$v1['price']);
- // }
- //
- // $v['payment'] = getXzPirceWithPrice($cur_xzmoney, $v['payment']);
- // }
- }
- return $data['data'];
- }
- /**
- * 订单详情
- */
- public static function details (array $map, $userId, ?string $field = '*'): array
- {
- $field = 'order_type,order_id,status,order_sn,created_time,coupon_number,order_remark,total_price,ship_postfee,payment,rebate_score,ship_code,ship_name,ship_number,expires_time,rebate_lock_score';
- $cur_xzmoney = Db::name('system_config')->where('name', 'xz_cur_money')->where('group', 'xzconfig')->value('value');
- $map['user_id'] = $userId;
- $details = self::where($map)->relation(['withOrderGoods', 'withOrderShipping'])->field($field)->findOrEmpty()->toArray();
- if (empty($details))
- throw new Exception('订单不存在');
- $details['withOrderExpress'] = [];
- if (in_array($details['status'], [1, 2])) {
- $details['withOrderExpress'] = ExpressServices::instance()->orderId($details['order_id'])->code($details['ship_code'])->number($details['ship_number'])->find() ?: [];
- if (intval($details['status']) == 2){
- $details['express_url'] = "https://m.kuaidi100.com/result.jsp?nu=".$details['ship_number'];
- }else{
- $details['express_url'] = "";
- }
- }
- if ($details['order_type'] == 5){
- $details['total_price'] = getXzPirceWithPrice($cur_xzmoney, $details['total_price']);
- }
- switch ($details['status']){
- case 0:
- $details['status_title'] = '待付款';
- break;
- case 1:
- $details['status_title'] = '待发货';
- break;
- case 2:
- $details['status_title'] = '已发货';
- break;
- case 3:
- $details['status_title'] = '取消订单';
- break;
- case 4:
- $details['status_title'] = '待发货(正在竞拍)';
- break;
- case 5:
- $details['status_title'] = '待发货(竞拍完成)';
- break;
- case 6:
- $details['status_title'] = '已发货(竞拍已发货)';
- break;
- }
- // if ($details['expires_time']){
- // $details['expires_time']=strtotime($details['expires_time']);
- // }
- // foreach ($details['data'] as $k=>$v){
- foreach ($details['withOrderGoods'] as $key=>$val){
- $goods_sn = Db::name('shop_goods')->where('goods_id', $val['goods_id'])->value('goods_sn');
- // sr_log($goods_sn);
- // $val['goods_sn'] = $goods_sn;
- //
- $details['withOrderGoods'][$key]['goods_sn'] = $goods_sn;
- // $details['withOrderGoods'][$key]['goods_name'] = '云德商品购买';
- $details['withOrderGoods'][$key]['price'] = getXzPirceWithPrice($cur_xzmoney, $details['withOrderGoods'][$key]['price']);
- }
- // }
- return $details;
- }
- /**
- * 下单详情,获取商品信息
- */
- public static function buyDetails (array $data, array $address = [])
- {
- $result = [];
- foreach ($data as $key => $value) {
- $result[$value['goods_sn'] . '_' . $value['spec_id']][] = $value;
- }
- $details = [];
- try {
- array_walk($result, function ($value, $key) use (&$details, &$flag) {
- $key_arrkass = explode('_', $key);
- $goodsBase = Db::name('shop_goods')->where(['goods_sn' => $key_arrkass[0]])->find();
- $num = array_sum(array_column($value, 'num'));
- $goodsSpec = Db::name('shop_goods_spec')->where(['goods_id' => $goodsBase['goods_id'], 'spec_ids' => $value[0]['spec_id']])->find();
- if (empty($goodsSpec) || empty($goodsBase)) {
- throw new Exception('操作失败,所选商品含有失效商品');
- }
- $superlizer = Db::name('shop_supplier')->where('id', $goodsBase['supplier'])->find();
- $details[] = [
- 'goods_sn' => $goodsBase['goods_sn'],
- 'goods_id' => $goodsBase['goods_id'],
- 'goods_type' => $goodsBase['goods_type'],
- 'goods_name' => $goodsBase['goods_name'],
- 'picture' => $goodsSpec['picture'] ?: $goodsBase['goods_img'],
- 'num' => $num, //数量
- 'price' => $goodsSpec['price'],//单价
- 'weight' => $goodsSpec['weight'], //重量
- 'total_fee' => bcmul($num, $goodsSpec['price'], 2), //总价
- 'rebate_score' => $goodsSpec['rebate_score'],//单个返利积分
- 'total_items_rebate_score' => bcmul($num, $goodsSpec['rebate_score'], 2),//总返利积分
- 'spec_ids' => $goodsSpec['spec_ids'],
- 'spec_text' => $goodsSpec['spec_text'],
- 'post_template_id' => $goodsBase['post_template_id'], //是否包邮,否就是运费模板ID
- 'stock' => $goodsSpec['stock'],
- 'supplier_name'=>$superlizer['name']
- ];
- });
- //组合数据
- $details_arr = [];
- foreach ($details as $k => $v) {
- $details_arr[$v['goods_sn']]['goods'][] = $v;
- $total_rebate_score = multi_array_sum($details_arr[$v['goods_sn']]['goods'], 'total_items_rebate_score');
- $total_num = multi_array_sum($details_arr[$v['goods_sn']]['goods'], 'num');
- $total_weight = multi_array_sum($details_arr[$v['goods_sn']]['goods'], 'weight');
- $total_price = multi_array_sum($details_arr[$v['goods_sn']]['goods'], 'total_fee');
- $details_arr[$v['goods_sn']]['total_rebate_score'] = $total_rebate_score; //总返利积分
- $details_arr[$v['goods_sn']]['total_num'] = $total_num; //总数量
- $details_arr[$v['goods_sn']]['total_price'] = $total_price; //总金额
- $details_arr[$v['goods_sn']]['total_weight'] = $total_weight; //总重量
- $details_arr[$v['goods_sn']]['post_fee'] = '0.00';
- $details_arr[$v['goods_sn']]['payment'] = bcadd($details_arr[$v['goods_sn']]['total_price'], $details_arr[$v['goods_sn']]['post_fee'], 2);
- $details_arr[$v['goods_sn']]['supplier_name'] = $details[$key]['supplier_name'];
- }
- $total = [
- 'count_payment' => sprintf("%.2f", multi_array_sum($details_arr, 'payment')),
- 'count_rebate_score' => (string)multi_array_sum($details_arr, 'total_rebate_score'),
- 'count_num' => multi_array_sum($details_arr, 'total_num'),
- ];
- $details_arr = array_values($details_arr);
- return ['details' => $details_arr, 'total' => $total];
- } catch (\Exception $e) {
- throw new Exception($e->getMessage());
- }
- }
- /**
- * 生成订单
- */
- public static function createOrder (array $data, int $userId, $user, $buyData, $cart_id)
- {
- Db::startTrans();
- try {
- //-----组装商品数据,不同商品将拆分------
- $result = $data['order'];
- $results = [];
- $specStock = [];
- // $m_id = createdMachineID();
- // if ($data['order_type'] == 3){
- // // 生成矿机兑换券
- // $m_machine->insertGetId([
- // 'number'=>$m_id,
- // 'create_time'=>sr_getcurtime(time())
- // ]);
- // }
- array_walk($result, function ($value, $key) use (&$results, &$specStock) {
- $key_arrkass = explode('_', $key);
- $goodsBase = Db::name('shop_goods')->where(['goods_sn' => $key_arrkass[0]])->find();
- $results[$key_arrkass[0]]['goods'] = $goodsBase;
- $goodsSpec = Db::name('shop_goods_spec')->where(['goods_id' => $goodsBase['goods_id'], 'spec_ids' => $value[0]['spec_id']])->find();
- $num = array_sum(array_column($value, 'num'));
- $results[$key_arrkass[0]]['spec'][$key_arrkass[1]] = $specStock[] = [
- 'num' => $num, //数量
- 'total_fee' => bcmul($num, $goodsSpec['price'], 3), //总价
- 'total_weight' => bcmul($num, $goodsSpec['weight'], 3), //总重量
- 'spec_id' => $value[0]['spec_id'], //规格ids
- 'spec_data' => $goodsSpec, //规格数据
- 'total_rebate_score' => bcmul($num, $goodsBase['rebate_score'], 3),//总返积分
- // 'total_rebate_lock_score' => bcmul($num, $goodsBase['rebate_score_lock'], 3)//返利积分锁定
- ];
- });
- //------减库存--------
- $num = 0;
- foreach ($specStock as $k => $v) {
- Db::name('shop_goods_spec')->where(['goods_spec_id' => $v['spec_data']['goods_spec_id']])->dec('stock', $v['num'])->update();
- $spec_info = Db::name('shop_goods_spec')->where(['goods_spec_id' => $v['spec_data']['goods_spec_id']])->find();
- Db::name('shop_goods')->where(['goods_id' => $spec_info['goods_id']])->dec('inventory', $v['num'])->update();
- // CacheServices::clear(md5('goodsDetail_' . $v['goods_sn']));
- CacheServices::set(md5('goodsDetail_' . $spec_info['goods_sn']), false);
- }
- //-------生成订单商品,返回订单号--------
- $createOrder = [];
- $i = -1;
- $total_rebate_score = 0;
- // $total_rebate_lock_score = 0;
- array_walk($results, function ($value, $key) use ($userId, $data, &$createOrder, &$i, &$total_rebate_score) {
- $nowTime = date('Y-m-d H:i:s', time());
- $nums = multi_array_sum($value['spec'], 'num');
- $total_price = multi_array_sum($value['spec'], 'total_fee');
- $total_weight = multi_array_sum($value['spec'], 'total_weight');
- $total_rebate_score = multi_array_sum($value['spec'], 'total_rebate_score');
- // $total_rebate_score = $value['goods']['rebate_score_most']*
- // $total_rebate_lock_score = multi_array_sum($value['spec'], 'total_rebate_lock_score');
- //运费
- $post_fee = self::postFee(
- $data['address']['city'],
- [
- 'goods_sn' => $value['goods']['goods_sn'],
- 'num' => $nums,
- 'total_price' => $total_price,
- 'total_weight' => $total_weight
- ],
- $value['goods']['post_template_id']
- );
- $post_fee = 0;
- $give_vip = 0;
- if ($data['cls'] == 1 && $value['goods']['give_vip']) {
- $give_vip = $value['goods']['give_vip'];
- }
- $i++;
- // //写入订单
- $status = 0;
- $payment = bcadd($total_price, $post_fee, 3);
- $order = self::create([
- 'order_sn' => createdOrderSn(),
- 'total_price' => $total_price,
- 'payment' => $payment,
- 'user_id' => $userId,
- 'num' => $nums,
- 'status'=>$status,
- 'ship_postfee' => $post_fee,
- 'rebate_score' => $total_rebate_score, //总返利积分
- 'created_time' => $nowTime, 'updated_time' => $nowTime,
- 'give_vip' => $give_vip,
- 'order_remark' => isset($data['order_remark']) ? $data['order_remark'] : '',
- 'pay_type'=>$data['pay_type'],
- 'order_type'=>$data['order_type'],
- 'coupon_number'=>'',
- 'expires_time'=>sr_getcurtime(time()+intval(env('common.ORDER_EXPIRES_TIME'))),
- 'supplier_name'=>$data['supplier_name']
- ]);
- // sr_log('ccccc'.$data['order_type']);
- //写入订单商品详情
- $orderGoods = [];
- foreach ($value['spec'] as $specKey => $specValue) {
- $orderGoods[] = [
- 'order_id' => $order->id, 'goods_id' => $value['goods']['goods_id'],
- 'goods_name' => $value['goods']['goods_name'], 'goods_category' => $value['goods']['category'],
- 'goods_img' => $specValue['spec_data']['picture'] ?: $value['goods']['goods_img'],
- 'num' => $specValue['num'],
- 'price' => $specValue['spec_data']['price'],
- 'total_fee' => $specValue['total_fee'],
- 'goods_spec_id' => $specValue['spec_data']['goods_spec_id'],
- 'spec_ids' => $specValue['spec_data']['spec_ids'],
- 'spec_text' => $specValue['spec_data']['spec_text'],
- 'rebate_score' => $specValue['spec_data']['rebate_score'],
- 'total_rebate_score' => $specValue['total_rebate_score'],
- 'order_type'=>$data['order_type'],
- 'uid'=>$userId
- ];
- }
- (new OrderGoods())->saveAll($orderGoods);
- //写入订单配送
- OrderShipping::create(OrderShipping::packageAddressShipPing($data['address'], $order->id));
- $createOrder[] = ['order_sn' => $order->order_sn, 'order_data' => $value['spec']];
- });
- if ($data['cart_ids']) {
- Db::name('shop_cart')->where('id', 'in', $data['cart_ids'])->where(['user_id' => $userId])->delete();
- }
- // 购买商品
- if (in_array($data['order_type'], [1, 3])){
- $ex_time = intval(env('common.ORDER_EXPIRES_TIME', 60*60));
- $order_sn = $createOrder[0]['order_sn'];
- Queue::instance()->log('订单过期执行成功')->job(ShopOrderJob::class)->do('ShopOrderExpired')->secs($ex_time)->push([$order_sn]);
- }
- // 增加销量
- if (in_array($data['order_type'], [2,4,5])){
- foreach ($createOrder as $key=>$val){
- $order_id = Db::name('shop_order')->where('order_sn', $val['order_sn'])->value('order_id');
- $orderGoods = OrderGoods::where(['order_id' => $order_id])->select()->toArray();
- foreach ($orderGoods as $k => $v) {
- ShopGoodsModel::where(['goods_id' => $v['goods_id']])->inc('sales_volume', $v['num'])->inc('real_sales_volume', $v['num'])->update();
- }
- }
- }
- if (intval($cart_id) > 0){
- Db::name('shop_cart')->where('id', $cart_id)->delete();
- }
- Db::commit();
- return ['flag' => 200, 'data' => array_column($createOrder, 'order_sn')];
- } catch (\Exception $e) {
- Db::rollback();
- if (strpos($e->getMessage(), 'SQLSTATE[22003]') !== false) {
- throw new Exception('所选商品含有库存不足');
- }
- throw new Exception($e->getMessage());
- }
- }
- /**
- * 校验库存
- */
- public static function checkStock (array $data)
- {
- $results = [];
- array_walk($data, function ($value, $key) use (&$results) {
- $num = array_sum(array_column($value, 'num'));
- $results[] = ['spec_id' => $value[0]['spec_id'], 'goods_sn' => $value[0]['goods_sn'], 'num' => $num];
- });
- foreach ($results as $k => $v) {
- $stock = Db::name('shop_goods_spec')->where(['goods_sn' => $v['goods_sn'], 'spec_ids' => $v['spec_id']])->value('stock') ?: 0;
- sr_log($stock);
- if ($v['num'] > $stock) {
- return false;
- }
- }
- return true;
- }
- /**
- * 支付前校验订单
- */
- public static function checkingOrder ($order_sn, $userPayMoney, $userId)
- {
- $orderSnArr = $order_sn? explode(',', $order_sn) : [];
- if(empty($orderSnArr)){
- return ['flag' => 110, 'msg' => '订单参数错误'];
- }
- $field = 'order_id,payment,order_sn,total_price,ship_postfee,user_id,pay_type,order_type,rebate_score,status';
- $order = self::where(['order_sn' => $orderSnArr,'user_id'=>$userId])->field($field)->select()->toArray();
- if (empty($order)) {
- return ['flag' => 110, 'msg' => '校验订单失败'];
- }
- if(count($order) != count($orderSnArr)){
- return ['flag' => 110, 'msg' => '存在无效的订单'];
- }
- $orderPayment = multi_array_sum($order, 'payment');
- return ['flag' => 200, 'msg' => '成功', 'orderPayment' => $orderPayment, 'order' => $order];
- }
- /**
- * 支付订单回调
- */
- public static function payDoneOrderCallback ($order, $payType, $userId)
- {
- $nowTime = date('Y-m-d H:i:s', time());
- self::where(['order_sn' => array_column($order, 'order_sn')])
- ->update(['pay_type' => $payType, 'status' => self::waitDelivery, 'updated_time' => $nowTime]);
- //根据订单商品 生成分红
- $orderId = array_column($order, 'order_id');
- $orderGoods = OrderGoods::where(['order_id' => $orderId])->select()->toArray();
- foreach ($orderGoods as $k => $v) {
- ShopGoodsModel::where(['goods_id' => $v['goods_id']])->inc('sales_volume', $v['num'])->inc('real_sales_volume', $v['num'])->update();
- }
- //赠送送会员
- if ($order[0]['give_vip']) {
- $vip = $order[0]['give_vip'] == 2 ? 'year_card' : 'monthly_card';
- $user = Db::name('user')->where('id', $userId)->field('vip,vip_expire_time')->find();
- $vip_config = get_vip_config($vip);
- $date = new \DateTime($user['vip_expire_time']);
- $date->add(new \DateInterval(get_vip_datetime_string($vip_config['type'])['time']));
- $vip_expire_time = $date->format('Y-m-d H:i:s'); // vip到期时间
- //更新用户vip信息
- Db::name('User')->where('id', $userId)->update(['vip' => get_vip_datetime_string($vip_config['type'])['vip_type'], 'vip_expire_time' => $vip_expire_time]);
- Db::name('vip_log')->insert(['uid' => $userId, 'type' => 2, 'pay_price' => 0, 'vip_expire_time' => $vip_expire_time, 'vip_type' => $vip]);
- }
- Queue::instance()->log('执行成功')->job(ShopBonusJob::class)->do('shopBonusJob')->push([$userId, $orderGoods]);
- }
- /**
- * 取消订单
- */
- public static function cancelOrder ($data, $userId)
- {
- $nowTime = date('Y-m-d H:i:s', time());
- $data = self::where(['order_sn' => $data['order_sn'], 'user_id' => $userId])->relation(['withOrderGoods'])->findOrEmpty()->toArray();
- if (empty($data)) {
- throw new Exception('参数错误');
- }
- if ($data['status'] != 0) {
- throw new Exception('订单状态错误');
- }
- self::where(['order_sn' => $data['order_sn']])->save(['status' => 3, 'updated_time' => $nowTime]);
- foreach ($data['withOrderGoods'] as $kk => $vv) {
- Db::name('shop_goods_spec')->where(['goods_spec_id' => $vv['goods_spec_id']])->inc('stock', $vv['num'])->update();
- }
- }
- /**
- * 确定订单
- */
- public static function receiveOrder ($data, $userId)
- {
- $nowTime = date('Y-m-d H:i:s', time());
- $data = self::where(['order_sn' => $data['order_sn'], 'user_id' => $userId])->relation(['withOrderGoods'])->findOrEmpty()->toArray();
- if (empty($data)) {
- throw new Exception('参数错误');
- }
- if ($data['status'] != 2) {
- throw new Exception('订单状态错误');
- }
- self::where(['order_sn' => $data['order_sn']])->save(['status' => 4, 'updated_time' => $nowTime]);
- }
- /**
- * @param $address 用户地址
- * @param $data 商品数据
- * @param $express_template_id 模板ID
- * 获取运费
- */
- public static function postFee ($address, $data, $express_template_id)
- {
- //获取运费模板
- $expressDelivery = Db::name('express_delivery')->where(['id' => $express_template_id])->findOrEmpty();
- //获取运费模板列表
- $expressDeliveryItems = Db::name('express_shipping_method')->where(['template_id' => $expressDelivery['id']])->select()->toArray();
- $price_method_field = '';
- switch ($expressDelivery['price_method']) {
- case 1:
- $price_method_field = $data['total_price']; //按金额
- break;
- case 2:
- $price_method_field = $data['num']; //按件数
- break;
- case 3:
- $price_method_field = $data['total_weight']; //按重量
- break;
- default:
- break;
- }
- if ($expressDelivery['price_method'] == 1) {
- //计算默认运费 【配送区域、免运费金额、达标时运费、未达标时运费;】
- if ($price_method_field < $expressDelivery['default_free_price']) {
- $default_postfee = $expressDelivery['default_fastandard_price'];
- } else {
- //达标时运费
- $default_postfee = $expressDelivery['default_price'];
- }
- if (empty($expressDeliveryItems)) {
- return $default_postfee;
- }
- //按指定地区计算邮费
- foreach ($expressDeliveryItems as $k => $node) {
- if (in_array($address, explode(',', $node['address_items_ids']))) {
- //未达标运费
- if ($price_method_field < $node['free_price']) {
- return $node['fastandard_price'];
- } else {
- //达标时运费
- return $node['price'];
- }
- } else {
- return $default_postfee;
- }
- }
- } else {
- //按件数 重量计费 【配送区域、首件、达标时运费、续件、未达标时运费】
- //计算默认运费
- if ($price_method_field <= $expressDelivery['default_pieces']) {
- $default_postfee = $expressDelivery['default_price'];
- } else {
- //达到续件条件时的运费
- if ($expressDelivery['add_pieces']) {
- //配置过续件费用
- //续件数 = (下单件数 - 首件) /续件数
- //总运费 = 首件运费 + (续件数 * 续件费用)
- $add_pieces = bcdiv(($price_method_field - $expressDelivery['default_pieces']), $expressDelivery['add_pieces'], 2);
- $default_postfee = bcadd($expressDelivery['default_price'], bcmul($add_pieces, $expressDelivery['add_price'], 2), 2);
- } else {
- //未配置过续件,按首件价格
- $default_postfee = $expressDelivery['default_price'];
- }
- }
- if (empty($expressDeliveryItems)) {
- return $default_postfee;
- }
- //按指定地区计算邮费
- foreach ($expressDeliveryItems as $k => $node) {
- if (in_array($address, explode(',', $node['address_items_ids']))) {
- //未达到续件条件时的运费
- if ($price_method_field <= $node['pieces']) {
- return $node['price'];
- } else {
- //达到续件条件时的运费
- if ($node['add_pieces']) {
- //配置过续件费用
- //续件数 = (下单件数 - 首件) /续件数
- //总运费 = 首件运费 + (续件数 * 续件费用)
- $add_pieces = bcdiv(($price_method_field - $node['pieces']), $node['add_pieces'], 2);
- return bcadd($node['price'], bcmul($add_pieces, $node['add_price'], 2), 2);
- } else {
- //未配置过续件,按首件价格
- return $node['price'];
- }
- }
- } else {
- return $default_postfee;
- }
- }
- }
- }
- /**
- * 一键发货
- * @param $uid 用户ID
- * @param $params
- * @throws Exception
- * @throws \think\db\exception\DataNotFoundException
- * @throws \think\db\exception\DbException
- * @throws \think\db\exception\ModelNotFoundException
- */
- public function boxGoodsSurePost($uid, $params){
- $hand_ids = $params['hand_ids'];
- $address_id = $params['address_id'];
- $total_ids = explode(',', $hand_ids);
- $model_hands = new BoxHandleModel();
- $list = $model_hands->where('id', 'in', $hand_ids)->where('status', 1)->where('uid', $uid)->select();
- if (count($list) != count($total_ids)){
- sr_throw('参数错误');
- }
- $address_info = Db::name('user_address')->where('id', $address_id)->where('uid', $uid)->find();
- if (!$address_info){
- sr_throw('地址错误');
- }
- $cur_time = sr_getcurtime(time());
- foreach ($total_ids as $key=>$val){
- $hand_info = Db::name('box_handle')->where('id', $val)->find();
- $goods_info = Db::name('shop_goods')->where('goods_id', $hand_info['goods_id'])->find();
- $supplier_info = Db::name('shop_supplier')->where('id', $goods_info['supplier'])->find();
- $order_id = Db::name('shop_order')->insertGetId([
- 'order_sn'=>createdFDOrderSn(),
- 'payment'=>0,
- 'ship_postfee'=>0,
- 'user_id'=>$uid,
- 'status'=>1,
- 'num'=>1,
- 'order_type'=>5,
- 'order_source'=> '福袋单号:'.$hand_info['h_sn'],
- 'supplier_name'=>$supplier_info['name'],
- 'total_price'=>0,
- 'created_time'=>$cur_time,
- 'rebate_score'=>0,
- ]);
- Db::name('shop_order_goods')->insertGetId([
- 'order_id'=>$order_id,
- 'goods_id'=>$goods_info['goods_id'],
- 'goods_name'=>$goods_info['goods_name'],
- 'goods_category'=>$goods_info['category'],
- 'goods_img'=>$goods_info['goods_img'],
- 'num'=>1,
- 'price'=>$goods_info['price'],
- 'total_fee'=>$goods_info['price'],
- 'spec_ids'=>1,
- 'spec_text'=>$goods_info['spec_name'],
- 'uid'=>$uid,
- 'rebate_score'=>0,
- 'total_rebate_score'=>0
- ]);
- $pname = Db::name('area')->where('id', $address_info['province'])->value('name');
- $cname = Db::name('area')->where('id', $address_info['city'])->value('name');
- $countyname = Db::name('area')->where('id', $address_info['county'])->value('name');
- Db::name('shop_order_shipping')->insert([
- 'order_id'=>$order_id,
- 'sp_name'=>$address_info['name'],
- 'sp_mobile'=>$address_info['mobile'],
- 'sp_province'=>$pname,
- 'sp_city'=>$cname,
- 'sp_county'=>$countyname,
- 'sp_remark'=>$address_info['remark'],
- 'sp_mergename'=> $pname.' '.$cname.' '.$countyname.' '.$address_info['remark'],
- 'created_time'=>$cur_time
- ]);
- Db::name('box_handle')->where('id', $val)->save([
- 'status'=>2,
- 'handle_type'=>1
- ]);
- }
- }
- // 一件回收
- public function boxGoodsReBuy($uid, $params, $user_info){
- $hand_ids = $params['hand_ids'];
- $total_ids = explode(',', $hand_ids);
- $model_hands = new BoxHandleModel();
- $total_goodsnum = count($total_ids);
- $list = $model_hands->where('id', 'in', $total_ids)->where('status', 1)->where('uid', $uid)->select();
- if (count($list) != $total_goodsnum){
- sr_throw('参数或状态错误');
- }
- if ($model_hands->where('box_type', 10)->where('id', 'in', $hand_ids)->find()){
- sr_throw('普通商品只能发货,不能回收');
- }
- $cur_time = sr_getcurtime(time());
- // 待处理的总金额
- $total_money = Db::name('box_handle')->where('id', 'in', $hand_ids)->sum('goods_price');
- // 最终金额 总共商品金额减去 每个商品 10快
- $end_money = $total_money - $total_goodsnum* env('boxsetting.RECYCLE_ONBOX_PRICE');
- if ($end_money < 0){
- sr_throw('错误,请联系客服');
- }
- if ($params['action'] == 'apply'){
- return [
- 'total_count'=>count($list),
- 'end_money'=>$end_money,
- 'total_money'=>$total_money
- ];
- }
- if ($params['action'] == 'surerecycle'){
- $user_info = Db::name('user')->where(['id'=> $uid])->field('id,score,money,recycle_count')->find();
- // 回收卡扣除
- if ($user_info['recycle_count'] < $total_goodsnum){
- sr_throw('回收卡不足'.$total_goodsnum.'个');
- }
- // 扣除回收卡
- edit_user_recyclecard(3, $uid, $total_goodsnum, 0, $hand_ids);
- // 288的原价
- $oring_price = count($total_ids) * env('boxsetting.ONE_BOX_PRICE');
- edit_user_money(2, $uid, $oring_price);
-
- // 备注利润是否可以为负 by wes
- if ($total_money > $end_money){
- // 待结算利润
- Db::name('user')->where('id', $uid)->inc('profit_money',max(0,$end_money-$oring_price))->update();
- // 添加用户利润记录
- Db::name('user_unmoney')->insert([
- 'uid'=>$uid,
- 'money'=>$end_money-$oring_price,
- 'ids'=>$hand_ids,
- 'create_time'=>sr_getcurtime(time())
- ]);
- }
- // 改变用户处理状态
- Db::name('box_handle')->where('id', 'in', $hand_ids)->save([
- 'status'=>2,
- 'handle_type'=>2
- ]);
- }
- }
- }
|