BuyService.php 37.1 KB
Newer Older
D
v1.2.0  
devil_gong 已提交
1 2 3 4
<?php
// +----------------------------------------------------------------------
// | ShopXO 国内领先企业级B2C免费开源电商系统
// +----------------------------------------------------------------------
D
devil_gong 已提交
5
// | Copyright (c) 2011~2019 http://shopxo.net All rights reserved.
D
v1.2.0  
devil_gong 已提交
6 7 8 9 10 11 12 13
// +----------------------------------------------------------------------
// | Licensed ( http://www.apache.org/licenses/LICENSE-2.0 )
// +----------------------------------------------------------------------
// | Author: Devil
// +----------------------------------------------------------------------
namespace app\service;

use think\Db;
D
devil_gong 已提交
14
use think\facade\Hook;
15 16 17
use app\service\GoodsService;
use app\service\UserService;
use app\service\ResourcesService;
D
v1.2.0  
devil_gong 已提交
18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36

/**
 * 购买服务层
 * @author   Devil
 * @blog     http://gong.gg/
 * @version  0.0.1
 * @datetime 2016-12-01T21:51:08+0800
 */
class BuyService
{
    /**
     * 购物车添加
     * @author   Devil
     * @blog    http://gong.gg/
     * @version 1.0.0
     * @date    2018-08-29
     * @desc    description
     * @param   [array]          $params [输入参数]
     */
37
    public static function CartAdd($params = [])
D
v1.2.0  
devil_gong 已提交
38 39 40 41 42 43 44 45 46 47 48 49 50
    {
        // 请求参数
        $p = [
            [
                'checked_type'      => 'empty',
                'key_name'          => 'goods_id',
                'error_msg'         => '商品id有误',
            ],
            [
                'checked_type'      => 'empty',
                'key_name'          => 'stock',
                'error_msg'         => '购买数量有误',
            ],
D
devil_gong 已提交
51 52 53 54 55 56
            [
                'checked_type'      => 'min',
                'key_name'          => 'stock',
                'checked_data'      => 1,
                'error_msg'         => '购买数量有误',
            ],
D
v1.2.0  
devil_gong 已提交
57 58 59 60 61 62 63 64 65 66 67 68
            [
                'checked_type'      => 'empty',
                'key_name'          => 'user',
                'error_msg'         => '用户信息有误',
            ],
        ];
        $ret = ParamsChecked($params, $p);
        if($ret !== true)
        {
            return DataReturn($ret, -1);
        }

69 70 71 72 73 74 75
        // 查询用户状态是否正常
        $ret = UserService::UserStatusCheck('id', $params['user']['id']);
        if($ret['code'] != 0)
        {
            return $ret;
        }

D
v1.2.0  
devil_gong 已提交
76 77 78 79 80 81 82 83 84
        // 获取商品
        $goods_id = intval($params['goods_id']);
        $goods = Db::name('Goods')->where(['id'=>$goods_id, 'is_shelves'=>1, 'is_delete_time'=>0])->find();
        if(empty($goods))
        {
            return DataReturn('商品不存在或已删除', -2);
        }

        // 规格处理
85
        $spec = self::GoodsSpecificationsHandle($params);
D
v1.2.0  
devil_gong 已提交
86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113

        // 获取商品基础信息
        $goods_base = GoodsService::GoodsSpecDetail(['id'=>$goods_id, 'spec'=>$spec]);
        if($goods_base['code'] != 0)
        {
            return $goods_base;
        }

        // 添加购物车
        $data = [
            'user_id'       => $params['user']['id'],
            'goods_id'      => $goods_id,
            'title'         => $goods['title'],
            'images'        => $goods['images'],
            'original_price'=> $goods_base['data']['original_price'],
            'price'         => $goods_base['data']['price'],
            'stock'         => intval($params['stock']),
            'spec'          => empty($spec) ? '' : json_encode($spec),
        ];

        // 存在则更新
        $where = ['user_id'=>$data['user_id'], 'goods_id'=>$data['goods_id'], 'spec'=>$data['spec']];
        $temp = Db::name('Cart')->where($where)->find();
        if(empty($temp))
        {
            $data['add_time'] = time();
            if(Db::name('Cart')->insertGetId($data) > 0)
            {
114
                return DataReturn('加入成功', 0, self::UserCartTotal($params));
D
v1.2.0  
devil_gong 已提交
115 116 117 118 119 120 121 122 123 124
            }
        } else {
            $data['upd_time'] = time();
            $data['stock'] += $temp['stock'];
            if($data['stock'] > $goods['inventory'])
            {
                $data['stock'] = $goods['inventory'];
            }
            if(Db::name('Cart')->where($where)->update($data))
            {
125
                return DataReturn('加入成功', 0, self::UserCartTotal($params));
D
v1.2.0  
devil_gong 已提交
126 127 128 129 130 131 132 133 134 135 136 137 138 139 140
            }
        }
        
        return DataReturn('加入失败', -100);
    }

    /**
     * 商品规格解析
     * @author   Devil
     * @blog    http://gong.gg/
     * @version 1.0.0
     * @date    2018-09-21
     * @desc    description
     * @param   [array]          $params [输入参数]
     */
141
    private static function GoodsSpecificationsHandle($params = [])
D
v1.2.0  
devil_gong 已提交
142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164
    {
        $spec = '';
        if(!empty($params['spec']))
        {
            if(!is_array($params['spec']))
            {
                $spec = json_decode($params['spec'], true);
            } else {
                $spec = $params['spec'];
            }
        }
        return empty($spec) ? '' : $spec;
    }

    /**
     * 获取购物车列表
     * @author   Devil
     * @blog    http://gong.gg/
     * @version 1.0.0
     * @date    2018-08-29
     * @desc    description
     * @param   [array]          $params [输入参数]
     */
165
    public static function CartList($params = [])
D
v1.2.0  
devil_gong 已提交
166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200
    {
        // 请求参数
        $p = [
            [
                'checked_type'      => 'empty',
                'key_name'          => 'user',
                'error_msg'         => '用户信息有误',
            ],
        ];
        $ret = ParamsChecked($params, $p);
        if($ret !== true)
        {
            return DataReturn($ret, -1);
        }

        $where = (!empty($params['where']) && is_array($params['where'])) ? $params['where'] : [];
        $where['c.user_id'] = $params['user']['id'];

        $field = 'c.*, g.title, g.images, g.inventory_unit, g.is_shelves, g.is_delete_time, g.buy_min_number, g.buy_max_number';
        $data = Db::name('Cart')->alias('c')->join(['__GOODS__'=>'g'], 'g.id=c.goods_id')->where($where)->field($field)->select();


        // 数据处理
        if(!empty($data))
        {
            foreach($data as &$v)
            {
                // 规格
                $v['spec'] = empty($v['spec']) ? null : json_decode($v['spec'], true);

                // 获取商品基础信息
                $goods_base = GoodsService::GoodsSpecDetail(['id'=>$v['goods_id'], 'spec'=>$v['spec']]);
                if($goods_base['code'] == 0)
                {
                    $v['inventory'] = $goods_base['data']['inventory'];
201
                    $v['price'] = (float) $goods_base['data']['price'];
202
                    $v['original_price'] = (float) $goods_base['data']['original_price'];
203 204 205
                    $v['spec_weight'] = $goods_base['data']['weight'];
                    $v['spec_coding'] = $goods_base['data']['coding'];
                    $v['spec_barcode'] = $goods_base['data']['barcode'];
D
v1.2.0  
devil_gong 已提交
206 207 208 209 210 211 212
                } else {
                    return $goods_base;
                }

                // 基础信息
                $v['goods_url'] = MyUrl('index/goods/index', ['id'=>$v['goods_id']]);
                $v['images_old'] = $v['images'];
213
                $v['images'] = ResourcesService::AttachmentPathViewHandle($v['images']);
214
                $v['total_price'] = $v['stock']* ((float) $v['price']);
D
v1.2.0  
devil_gong 已提交
215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230
                $v['buy_max_number'] = ($v['buy_max_number'] <= 0) ? $v['inventory']: $v['buy_max_number'];
            }
        }

        return DataReturn('操作成功', 0, $data);
    }

    /**
     * 购物车删除
     * @author   Devil
     * @blog    http://gong.gg/
     * @version 1.0.0
     * @date    2018-09-14
     * @desc    description
     * @param   [array]          $params [输入参数]
     */
231
    public static function CartDelete($params = [])
D
v1.2.0  
devil_gong 已提交
232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251
    {
        // 请求参数
        $p = [
            [
                'checked_type'      => 'empty',
                'key_name'          => 'id',
                'error_msg'         => '删除数据id有误',
            ],
            [
                'checked_type'      => 'empty',
                'key_name'          => 'user',
                'error_msg'         => '用户信息有误',
            ],
        ];
        $ret = ParamsChecked($params, $p);
        if($ret !== true)
        {
            return DataReturn($ret, -1);
        }

252 253 254 255 256 257 258
        // 查询用户状态是否正常
        $ret = UserService::UserStatusCheck('id', $params['user']['id']);
        if($ret['code'] != 0)
        {
            return $ret;
        }

D
v1.2.0  
devil_gong 已提交
259 260 261 262 263 264 265
        // 删除
        $where = [
            'id'        => explode(',', $params['id']),
            'user_id'   => $params['user']['id']
        ];
        if(Db::name('Cart')->where($where)->delete())
        {
266
            return DataReturn('删除成功', 0, self::UserCartTotal($params));
D
v1.2.0  
devil_gong 已提交
267 268 269 270 271 272 273 274 275 276 277 278 279
        }
        return DataReturn('删除失败或资源不存在', -100);
    }

    /**
     * 购物车数量保存
     * @author   Devil
     * @blog    http://gong.gg/
     * @version 1.0.0
     * @date    2018-09-14
     * @desc    description
     * @param   [array]          $params [输入参数]
     */
280
    public static function CartStock($params = [])
D
v1.2.0  
devil_gong 已提交
281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298
    {
        // 请求参数
        $p = [
            [
                'checked_type'      => 'empty',
                'key_name'          => 'id',
                'error_msg'         => '数据id有误',
            ],
            [
                'checked_type'      => 'empty',
                'key_name'          => 'goods_id',
                'error_msg'         => '商品id有误',
            ],
            [
                'checked_type'      => 'empty',
                'key_name'          => 'stock',
                'error_msg'         => '购买数量有误',
            ],
D
devil_gong 已提交
299 300 301 302 303 304
            [
                'checked_type'      => 'min',
                'key_name'          => 'stock',
                'checked_data'      => 1,
                'error_msg'         => '购买数量有误',
            ],
D
v1.2.0  
devil_gong 已提交
305 306 307 308 309 310 311 312 313 314 315 316
            [
                'checked_type'      => 'empty',
                'key_name'          => 'user',
                'error_msg'         => '用户信息有误',
            ],
        ];
        $ret = ParamsChecked($params, $p);
        if($ret !== true)
        {
            return DataReturn($ret, -1);
        }

317 318 319 320 321 322 323
        // 查询用户状态是否正常
        $ret = UserService::UserStatusCheck('id', $params['user']['id']);
        if($ret['code'] != 0)
        {
            return $ret;
        }

D
v1.2.0  
devil_gong 已提交
324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349
        // 更新
        $where = [
            'id'        => intval($params['id']),
            'goods_id'  => intval($params['goods_id']),
            'user_id'   => intval($params['user']['id']),
        ];
        $data = [
            'stock'     => intval($params['stock']),
            'upd_time'  => time(),
        ];
        if(Db::name('Cart')->where($where)->update($data))
        {
            return DataReturn('更新成功', 0);
        }
        return DataReturn('更新失败', -100);
    }

    /**
     * 下订单 - 正常购买
     * @author   Devil
     * @blog    http://gong.gg/
     * @version 1.0.0
     * @date    2018-09-21
     * @desc    description
     * @param   [array]          $params [输入参数]
     */
350
    public static function BuyGoods($params = [])
D
v1.2.0  
devil_gong 已提交
351 352 353 354 355 356 357 358
    {
        // 请求参数
        $p = [
            [
                'checked_type'      => 'empty',
                'key_name'          => 'stock',
                'error_msg'         => '购买数量有误',
            ],
D
devil_gong 已提交
359 360 361 362 363 364
            [
                'checked_type'      => 'min',
                'key_name'          => 'stock',
                'checked_data'      => 1,
                'error_msg'         => '购买数量有误',
            ],
D
v1.2.0  
devil_gong 已提交
365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395
            [
                'checked_type'      => 'empty',
                'key_name'          => 'goods_id',
                'error_msg'         => '商品id有误',
            ],
            [
                'checked_type'      => 'isset',
                'key_name'          => 'spec',
                'error_msg'         => '规格参数有误',
            ],
            [
                'checked_type'      => 'empty',
                'key_name'          => 'user',
                'error_msg'         => '用户信息有误',
            ],
        ];
        $ret = ParamsChecked($params, $p);
        if($ret !== true)
        {
            return DataReturn($ret, -1);
        }

        // 获取商品
        $p = [
            'where' => [
                'id'                => intval($params['goods_id']),
                'is_delete_time'    => 0,
                'is_shelves'        => 1,
            ],
            'field' => 'id, id AS goods_id, title, images, inventory_unit, buy_min_number, buy_max_number',
        ];
396 397
        $ret = GoodsService::GoodsList($p);
        if(empty($ret['data'][0]))
D
v1.2.0  
devil_gong 已提交
398 399 400 401 402
        {
            return DataReturn('资源不存在或已被删除', -10);
        }

        // 规格
403
        $ret['data'][0]['spec'] = self::GoodsSpecificationsHandle($params);
D
v1.2.0  
devil_gong 已提交
404 405

        // 获取商品基础信息
406
        $goods_base = GoodsService::GoodsSpecDetail(['id'=>$ret['data'][0]['goods_id'], 'spec'=>$ret['data'][0]['spec']]);
D
v1.2.0  
devil_gong 已提交
407 408
        if($goods_base['code'] == 0)
        {
409
            $ret['data'][0]['inventory'] = $goods_base['data']['inventory'];
410 411
            $ret['data'][0]['price'] = (float) $goods_base['data']['price'];
            $ret['data'][0]['original_price'] = (float) $goods_base['data']['original_price'];
412 413 414
            $ret['data'][0]['spec_weight'] = $goods_base['data']['weight'];
            $ret['data'][0]['spec_coding'] = $goods_base['data']['coding'];
            $ret['data'][0]['spec_barcode'] = $goods_base['data']['barcode'];
D
v1.2.0  
devil_gong 已提交
415 416 417 418 419
        } else {
            return $goods_base;
        }

        // 数量/小计
420
        $ret['data'][0]['stock'] = $params['stock'];
421
        $ret['data'][0]['total_price'] = $params['stock']* ((float) $ret['data'][0]['price']);
D
v1.2.0  
devil_gong 已提交
422

D
devil_gong 已提交
423
        return DataReturn('操作成功', 0, $ret['data']);
D
v1.2.0  
devil_gong 已提交
424 425 426 427 428 429 430 431 432 433 434
    }

    /**
     * 下订单 - 购物车
     * @author   Devil
     * @blog    http://gong.gg/
     * @version 1.0.0
     * @date    2018-09-21
     * @desc    description
     * @param   [array]          $params [输入参数]
     */
435
    public static function BuyCart($params = [])
D
v1.2.0  
devil_gong 已提交
436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461
    {
        // 请求参数
        $p = [
            [
                'checked_type'      => 'empty',
                'key_name'          => 'ids',
                'error_msg'         => '购物车id有误',
            ],
            [
                'checked_type'      => 'empty',
                'key_name'          => 'user',
                'error_msg'         => '用户信息有误',
            ],
        ];
        $ret = ParamsChecked($params, $p);
        if($ret !== true)
        {
            return DataReturn($ret, -1);
        }

        // 获取购物车数据
        $params['where'] = [
            'g.is_delete_time'  => 0,
            'g.is_shelves'      => 1,
            'c.id'              => explode(',', $params['ids']),
        ];
462
        return self::CartList($params);
D
v1.2.0  
devil_gong 已提交
463 464 465 466 467 468 469 470 471 472
    }

    /**
     * 下订单购物车删除
     * @author   Devil
     * @blog     http://gong.gg/
     * @version  1.0.0
     * @datetime 2018-10-12T00:42:49+0800
     * @param   [array]          $params [输入参数]
     */
473
    public static function BuyCartDelete($params = [])
D
v1.2.0  
devil_gong 已提交
474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489
    {
        if(isset($params['buy_type']) && $params['buy_type'] == 'cart' && !empty($params['ids']))
        {
            Db::name('Cart')->where(['id'=>explode(',', $params['ids'])])->delete();
        }
    }

    /**
     * 根据购买类型获取商品列表
     * @author   Devil
     * @blog    http://gong.gg/
     * @version 1.0.0
     * @date    2018-09-26
     * @desc    description
     * @param   [array]          $params [输入参数]
     */
490
    public static function BuyTypeGoodsList($params = [])
D
v1.2.0  
devil_gong 已提交
491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512
    {
        if(isset($params['buy_type']))
        {
            switch($params['buy_type'])
            {
                // 正常购买
                case 'goods' :
                    $ret = BuyService::BuyGoods($params);
                    break;

                // 购物车
                case 'cart' :
                    $ret = BuyService::BuyCart($params);
                    break;

                // 默认
                default :
                    $ret = DataReturn('参数有误', -1);
            }
        } else {
            $ret = DataReturn('参数有误', -1);
        }
D
devil_gong 已提交
513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532

        // 数据组装
        if($ret['code'] == 0)
        {
            // 商品数据
            $goods = $ret['data'];

            // 用户默认地址
            $address_params = [
                'user'  => $params['user'],
            ];
            if(!empty($params['address_id']))
            {
                $address_params['where'] = ['id' => $params['address_id']];
            }
            $address = UserService::UserDefaultAddress($address_params);

            // 商品/基础信息
            $total_price = empty($goods) ? 0 : array_sum(array_column($goods, 'total_price'));
            $base = [
D
devil_gong 已提交
533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555
                // 总价
                'total_price'           => $total_price,

                // 订单实际支付金额(已减去优惠金额, 已加上增加金额)
                'actual_price'          => $total_price,

                // 优惠金额
                'preferential_price'    => 0.00,

                // 增加金额
                'increase_price'        => 0.00,

                // 商品数量
                'goods_count'           => count($goods),

                // 规格重量总计
                'spec_weight_total'     => empty($goods) ? 0 : array_sum(array_map(function($v) {return $v['spec_weight']*$v['stock'];}, $goods)),

                // 购买总数
                'buy_count'             => empty($goods) ? 0 : array_sum(array_column($goods, 'stock')),

                // 默认地址
                'address'               => empty($address['data']) ? null : $address['data'],
D
devil_gong 已提交
556 557 558 559 560 561 562 563
            ];

            // 扩展展示数据
            // name 名称
            // price 金额
            // type 类型(0减少, 1增加)
            // tips 提示信息
            $extension_data = [
D
devil_gong 已提交
564 565 566 567 568 569
                // [
                //     'name'  => '感恩节9折',
                //     'price' => 23,
                //     'type'  => 0,
                //     'tips'  => '-¥23元'
                // ],
D
devil_gong 已提交
570 571 572 573 574 575 576 577
            ];

            // 返回数据
            $result = [
                'goods'             => $goods,
                'base'              => $base,
                'extension_data'    => $extension_data,
            ];
D
devil_gong 已提交
578 579 580 581 582 583 584 585 586 587 588 589 590 591

            // 生成订单数据处理钩子
            $hook_name = 'plugins_service_buy_handle';
            $ret = Hook::listen($hook_name, [
                'hook_name'     => $hook_name,
                'is_backend'    => true,
                'params'        => &$params,
                'data'          => &$result,
            ]);
            if(isset($ret['code']) && $ret['code'] != 0)
            {
                return $ret;
            }

D
devil_gong 已提交
592 593 594
            return DataReturn('操作成功', 0, $result);
        }

D
v1.2.0  
devil_gong 已提交
595 596 597 598 599 600 601 602 603 604 605 606
        return $ret;
    }

    /**
     * 购买商品校验
     * @author   Devil
     * @blog    http://gong.gg/
     * @version 1.0.0
     * @date    2018-09-26
     * @desc    description
     * @param   [array]          $params [输入参数]
     */
607
    public static function BuyGoodsCheck($params = [])
D
v1.2.0  
devil_gong 已提交
608 609 610 611 612 613 614 615 616 617 618 619 620 621 622 623 624 625 626 627 628 629 630 631 632 633 634 635 636 637 638 639 640 641 642 643 644 645 646 647 648 649 650 651 652 653 654 655 656 657 658 659 660 661
    {
        // 请求参数
        $p = [
            [
                'checked_type'      => 'empty',
                'key_name'          => 'goods',
                'error_msg'         => '商品信息有误',
            ]
        ];
        $ret = ParamsChecked($params, $p);
        if($ret !== true)
        {
            return DataReturn($ret, -1);
        }

        // 数据校验
        foreach($params['goods'] as $v)
        {
            // 获取商品信息
            $goods = Db::name('Goods')->find($v['goods_id']);

            // 规格
            $goods_base = GoodsService::GoodsSpecDetail(['id'=>$v['goods_id'], 'spec'=>isset($v['spec']) ? $v['spec'] : []]);
            if($goods_base['code'] == 0)
            {
                $goods['price'] = $goods_base['data']['price'];
                $goods['inventory'] = $goods_base['data']['inventory'];
            } else {
                return $goods_base;
            }

            // 基础判断
            if(empty($goods))
            {
                return DataReturn('['.$v['goods_id'].']商品不存在', -1);
            }
            if($goods['is_shelves'] != 1)
            {
                return DataReturn('['.$v['goods_id'].']商品已下架', -1);
            }
            if($v['stock'] > $goods['inventory'])
            {
                return DataReturn('['.$v['goods_id'].']购买数量超过商品库存数量['.$v['stock'].'>'.$goods['inventory'].']', -1);
            }
            if($goods['buy_min_number'] > 1 && $v['stock'] < $goods['buy_min_number'])
            {
                return DataReturn('['.$v['goods_id'].']低于商品起购数量['.$v['stock'].'<'.$goods['buy_min_number'].']', -1);
            }
            if($goods['buy_max_number'] > 1 && $v['stock'] > $goods['buy_max_number'])
            {
                return DataReturn('['.$v['goods_id'].']超过商品限购数量['.$v['stock'].'>'.$goods['buy_max_number'].']', -1);
            }
        }

D
devil_gong 已提交
662
        return DataReturn('操作成功', 0);
D
v1.2.0  
devil_gong 已提交
663 664 665 666 667 668 669 670 671 672 673
    }

    /**
     * 订单添加
     * @author   Devil
     * @blog    http://gong.gg/
     * @version 1.0.0
     * @date    2018-09-26
     * @desc    description
     * @param   [array]          $params [输入参数]
     */
674
    public static function OrderAdd($params = [])
D
v1.2.0  
devil_gong 已提交
675 676 677 678 679 680 681 682 683 684 685 686 687 688 689 690 691 692 693 694 695 696 697 698 699 700 701 702
    {
        // 请求参数
        $p = [
            [
                'checked_type'      => 'empty',
                'key_name'          => 'user',
                'error_msg'         => '用户信息有误',
            ],
            [
                'checked_type'      => 'empty',
                'key_name'          => 'address_id',
                'error_msg'         => '地址有误',
            ],
        ];
        if(MyC('common_order_is_booking', 0) != 1)
        {
            $p[] = [
                'checked_type'      => 'empty',
                'key_name'          => 'payment_id',
                'error_msg'         => '支付方式有误',
            ];
        }
        $ret = ParamsChecked($params, $p);
        if($ret !== true)
        {
            return DataReturn($ret, -1);
        }

703 704 705 706 707 708 709
        // 查询用户状态是否正常
        $ret = UserService::UserStatusCheck('id', $params['user']['id']);
        if($ret['code'] != 0)
        {
            return $ret;
        }

D
v1.2.0  
devil_gong 已提交
710
        // 清单商品
D
devil_gong 已提交
711
        $params['is_order_submit'] = 1;
D
devil_gong 已提交
712 713
        $buy = self::BuyTypeGoodsList($params);
        if(!isset($buy['code']) || $buy['code'] != 0)
D
v1.2.0  
devil_gong 已提交
714
        {
D
devil_gong 已提交
715
            return $buy;
D
v1.2.0  
devil_gong 已提交
716
        }
D
devil_gong 已提交
717
        $check = self::BuyGoodsCheck(['goods'=>$buy['data']['goods']]);
D
v1.2.0  
devil_gong 已提交
718 719 720 721 722
        if(!isset($check['code']) || $check['code'] != 0)
        {
            return $check;
        }

D
devil_gong 已提交
723 724
        // 收货地址
        if(empty($buy['data']['base']['address']))
D
v1.2.0  
devil_gong 已提交
725
        {
D
devil_gong 已提交
726 727 728
            return DataReturn('收货地址有误', -1);
        } else {
            $address = $buy['data']['base']['address'];
D
v1.2.0  
devil_gong 已提交
729 730 731 732 733 734 735 736 737 738
        }

        // 店铺
        $shop_id = 0;

        // 订单写入
        $order = [
            'order_no'              => date('YmdHis').GetNumberCode(6),
            'user_id'               => $params['user']['id'],
            'shop_id'               => $shop_id,
D
devil_gong 已提交
739 740 741 742 743 744 745
            'receive_address_id'    => $address['id'],
            'receive_name'          => $address['name'],
            'receive_tel'           => $address['tel'],
            'receive_province'      => $address['province'],
            'receive_city'          => $address['city'],
            'receive_county'        => $address['county'],
            'receive_address'       => $address['address'],
D
v1.2.0  
devil_gong 已提交
746 747
            'user_note'             => isset($params['user_note']) ? htmlentities($params['user_note']) : '',
            'status'                => (intval(MyC('common_order_is_booking', 0)) == 1) ? 0 : 1,
D
devil_gong 已提交
748 749 750 751 752
            'preferential_price'    => $buy['data']['base']['preferential_price'],
            'increase_price'        => $buy['data']['base']['increase_price'],
            'price'                 => $buy['data']['base']['total_price'],
            'total_price'           => $buy['data']['base']['actual_price'],
            'extension_data'        => empty($buy['data']['extension_data']) ? '' : json_encode($buy['data']['extension_data']),
D
v1.2.0  
devil_gong 已提交
753 754 755 756 757 758 759 760 761 762 763 764 765 766 767
            'payment_id'            => isset($params['payment_id']) ? intval($params['payment_id']) : 0,
            'add_time'              => time(),
        ];
        if($order['status'] == 1)
        {
            $order['confirm_time'] = time();
        }

        // 开始事务
        Db::startTrans();

        // 订单添加
        $order_id = Db::name('Order')->insertGetId($order);
        if($order_id > 0)
        {
D
devil_gong 已提交
768
            foreach($buy['data']['goods'] as $v)
D
v1.2.0  
devil_gong 已提交
769 770 771 772 773 774 775 776 777 778 779
            {
                $detail = [
                    'order_id'          => $order_id,
                    'user_id'           => $params['user']['id'],
                    'shop_id'           => $shop_id,
                    'goods_id'          => $v['goods_id'],
                    'title'             => $v['title'],
                    'images'            => $v['images_old'],
                    'original_price'    => $v['original_price'],
                    'price'             => $v['price'],
                    'spec'              => empty($v['spec']) ? '' : json_encode($v['spec']),
780 781 782
                    'spec_weight'       => $v['spec_weight'],
                    'spec_coding'       => $v['spec_coding'],
                    'spec_barcode'      => $v['spec_barcode'],
D
v1.2.0  
devil_gong 已提交
783 784 785 786 787 788 789 790 791 792 793 794 795 796 797 798 799
                    'buy_number'        => $v['stock'],
                    'add_time'          => time(),
                ];
                if(Db::name('OrderDetail')->insertGetId($detail) <= 0)
                {
                    Db::rollback();
                    return DataReturn('订单详情添加失败', -1);
                }
            }
        } else {
            Db::rollback();
            return DataReturn('订单添加失败', -1);
        }

        // 库存扣除
        if($order['status'] == 1)
        {
800
            $ret = self::OrderInventoryDeduct(['order_id'=>$order_id, 'order_data'=>$order]);
D
v1.2.0  
devil_gong 已提交
801 802 803 804 805 806 807 808 809 810 811 812 813
            if($ret['code'] != 0)
            {
                // 事务回滚
                Db::rollback();
                return DataReturn($ret['msg'], -10);
            }
        }
        

        // 订单提交成功
        Db::commit();

        // 删除购物车
814
        self::BuyCartDelete($params);
D
v1.2.0  
devil_gong 已提交
815 816 817 818 819 820 821 822 823 824 825 826 827 828 829 830 831 832 833 834 835 836 837 838 839 840 841 842 843 844 845 846 847 848 849 850 851 852 853

        // 返回信息
        $result = [
            'order'     => Db::name('Order')->find($order_id),
            'jump_url'  => MyUrl('index/order/index'),
        ];


        // 获取订单信息
        switch($order['status'])
        {
            // 预约成功
            case 0 :
                $msg = '预约成功';
                break;

            // 提交成功
            case 1 :
                $msg = '提交成功';
                $result['jump_url'] = MyUrl('index/order/pay', ['id'=>$order_id]);
                break;

            // 默认操作成功
            default :
                $msg = '操作成功';
        }

        return DataReturn($msg, 0, $result);
    }

    /**
     * 购物车总数
     * @author   Devil
     * @blog    http://gong.gg/
     * @version 1.0.0
     * @date    2018-09-29
     * @desc    description
     * @param   [array]          $where [条件]
     */
854
    public static function CartTotal($where = [])
D
v1.2.0  
devil_gong 已提交
855 856 857 858 859 860 861 862 863 864 865 866 867
    {
        return (int) Db::name('Cart')->where($where)->count();
    }

    /**
     * 用户购物车总数
     * @author   Devil
     * @blog    http://gong.gg/
     * @version 1.0.0
     * @date    2018-09-29
     * @desc    description
     * @param   [array]          $params [输入参数]
     */
868
    public static function UserCartTotal($params = [])
D
v1.2.0  
devil_gong 已提交
869 870 871 872 873 874 875 876 877 878 879 880 881 882
    {
        // 请求参数
        $p = [
            [
                'checked_type'      => 'empty',
                'key_name'          => 'user',
                'error_msg'         => '用户信息有误',
            ],
        ];
        $ret = ParamsChecked($params, $p);
        if($ret !== true)
        {
            return 0;
        }
883
        return self::CartTotal(['user_id'=>$params['user']['id']]);
D
v1.2.0  
devil_gong 已提交
884 885 886 887 888 889 890 891 892 893 894
    }

    /**
     * 库存扣除
     * @author   Devil
     * @blog    http://gong.gg/
     * @version 1.0.0
     * @date    2018-11-09
     * @desc    description
     * @param   [array]          $params [输入参数]
     */
895
    public static function OrderInventoryDeduct($params = [])
D
v1.2.0  
devil_gong 已提交
896 897 898 899 900 901 902 903 904 905 906 907 908 909 910 911 912 913 914 915 916 917 918 919 920 921 922 923 924 925 926 927 928 929 930 931 932 933 934 935 936 937 938 939 940 941 942 943 944 945 946 947 948 949 950 951 952 953 954 955 956 957 958 959 960 961 962 963 964 965 966 967 968 969 970 971 972 973 974 975 976 977 978 979 980 981 982 983 984 985 986 987 988 989 990 991 992 993 994 995 996 997 998 999 1000 1001 1002 1003 1004 1005 1006 1007 1008 1009 1010 1011 1012 1013 1014 1015 1016 1017 1018 1019
    {
        // 请求参数
        $p = [
            [
                'checked_type'      => 'empty',
                'key_name'          => 'order_id',
                'error_msg'         => '订单id有误',
            ],
            [
                'checked_type'      => 'empty',
                'key_name'          => 'order_data',
                'error_msg'         => '订单更新数据不能为空',
            ],
            [
                'checked_type'      => 'is_array',
                'key_name'          => 'order_data',
                'error_msg'         => '订单更新数据有误',
            ]
        ];
        $ret = ParamsChecked($params, $p);
        if($ret !== true)
        {
            return DataReturn($ret, -1);
        }

        // 是否扣除库存
        $common_is_deduction_inventory = MyC('common_is_deduction_inventory', 0);
        if($common_is_deduction_inventory != 1)
        {
            return DataReturn('未开启扣除库存', 0);
        }

        // 扣除库存规则
        $common_deduction_inventory_rules = MyC('common_deduction_inventory_rules', 1);
        switch($common_deduction_inventory_rules)
        {
            // 订单确认成功
            case 0 :
                if($params['order_data']['status'] != 1)
                {
                    return DataReturn('当前订单状态未操作确认-不扣除库存['.$params['order_id'].']', 0);
                }
                break;

            // 订单支付成功
            case 1 :
                if($params['order_data']['status'] != 2)
                {
                    return DataReturn('当前订单状态未操作支付-不扣除库存['.$params['order_id'].']', 0);
                }
                break;

            // 订单发货
            case 2 :
                if($params['order_data']['status'] != 3)
                {
                    return DataReturn('当前订单状态未操作发货-不扣除库存['.$params['order_id'].']', 0);
                }
                break;
        }

        // 获取订单商品
        $order_detail = Db::name('OrderDetail')->field('goods_id,buy_number,spec')->where(['order_id'=>$params['order_id']])->select();
        if(!empty($order_detail))
        {
            foreach($order_detail as $v)
            {
                // 查看是否已扣除过库存,避免更改模式导致重复扣除
                $temp = Db::name('OrderGoodsInventoryLog')->where(['order_id'=>$params['order_id'], 'goods_id'=>$v['goods_id']])->find();
                if(empty($temp))
                {
                    $goods = Db::name('Goods')->field('is_deduction_inventory,inventory')->find($v['goods_id']);
                    if(isset($goods['is_deduction_inventory']) && $goods['is_deduction_inventory'] == 1)
                    {
                        // 扣除操作
                        if(!Db::name('Goods')->where(['id'=>$v['goods_id']])->setDec('inventory', $v['buy_number']))
                        {
                            return DataReturn('商品库存扣减失败['.$params['order_id'].'-'.$v['goods_id'].'('.$goods['inventory'].'-'.$v['buy_number'].')]', -10);
                        }

                        // 扣除规格库存
                        $spec = empty($v['spec']) ? '' : json_decode($v['spec'], true);
                        $base = GoodsService::GoodsSpecDetail(['id'=>$v['goods_id'], 'spec'=>$spec]);
                        if($base['code'] == 0)
                        {
                            // 扣除规格操作
                            if(!Db::name('GoodsSpecBase')->where(['id'=>$base['data']['id'], 'goods_id'=>$v['goods_id']])->setDec('inventory', $v['buy_number']))
                            {
                                return DataReturn('规格库存扣减失败['.$params['order_id'].'-'.$v['goods_id'].'('.$goods['inventory'].'-'.$v['buy_number'].')]', -10);
                            }
                        } else {
                            return $base;
                        }

                        // 扣除日志添加
                        $log_data = [
                            'order_id'              => $params['order_id'],
                            'goods_id'              => $v['goods_id'],
                            'order_status'          => $params['order_data']['status'],
                            'original_inventory'    => $goods['inventory'],
                            'new_inventory'         => Db::name('Goods')->where(['id'=>$v['goods_id']])->value('inventory'),
                            'add_time'              => time(),
                        ];
                        if(Db::name('OrderGoodsInventoryLog')->insertGetId($log_data) <= 0)
                        {
                            return DataReturn('库存扣减日志添加失败['.$params['order_id'].'-'.$v['goods_id'].']', -100);
                        }
                    }
                }
            }
            return DataReturn('操作成功', 0);
        }
        return DataReturn('没有需要扣除库存的数据', 0);
    }

    /**
     * 库存回滚
     * @author   Devil
     * @blog    http://gong.gg/
     * @version 1.0.0
     * @date    2018-11-09
     * @desc    description
     * @param   [array]          $params [输入参数]
     */
1020
    public static function OrderInventoryRollback($params = [])
D
v1.2.0  
devil_gong 已提交
1021 1022 1023 1024 1025 1026 1027 1028 1029 1030 1031 1032 1033 1034 1035 1036 1037 1038 1039 1040 1041 1042 1043 1044 1045 1046 1047 1048 1049 1050 1051 1052 1053 1054 1055 1056 1057 1058 1059 1060 1061 1062 1063 1064 1065 1066 1067 1068 1069 1070 1071 1072 1073 1074 1075 1076 1077 1078 1079 1080 1081 1082 1083 1084 1085 1086 1087 1088 1089 1090 1091 1092 1093 1094 1095 1096 1097 1098
    {
        // 请求参数
        $p = [
            [
                'checked_type'      => 'empty',
                'key_name'          => 'order_id',
                'error_msg'         => '订单id有误',
            ],
            [
                'checked_type'      => 'empty',
                'key_name'          => 'order_data',
                'error_msg'         => '订单更新数据不能为空',
            ],
            [
                'checked_type'      => 'is_array',
                'key_name'          => 'order_data',
                'error_msg'         => '订单更新数据有误',
            ]
        ];
        $ret = ParamsChecked($params, $p);
        if($ret !== true)
        {
            return DataReturn($ret, -1);
        }

        // 订单状态
        if(!in_array($params['order_data']['status'], [5,6]))
        {
            return DataReturn('当前订单状态不允许回滚库存['.$params['order_id'].'-'.$params['order_data']['status'].']', 0);
        }

        // 获取订单商品
        $order_detail = Db::name('OrderDetail')->field('goods_id,buy_number,spec')->where(['order_id'=>$params['order_id']])->select();
        if(!empty($order_detail))
        {
            foreach($order_detail as $v)
            {
                // 查看是否已扣除过库存
                $temp = Db::name('OrderGoodsInventoryLog')->where(['order_id'=>$params['order_id'], 'goods_id'=>$v['goods_id'], 'is_rollback'=>0])->find();
                if(!empty($temp))
                {
                    // 回滚操作
                    if(!Db::name('Goods')->where(['id'=>$v['goods_id']])->setInc('inventory', $v['buy_number']))
                    {
                        return DataReturn('商品库存回滚失败['.$params['order_id'].'-'.$v['goods_id'].']', -10);
                    }

                    // 扣除规格库存
                    $spec = empty($v['spec']) ? '' : json_decode($v['spec'], true);
                    $base = GoodsService::GoodsSpecDetail(['id'=>$v['goods_id'], 'spec'=>$spec]);
                    if($base['code'] == 0)
                    {
                        // 扣除规格操作
                        if(!Db::name('GoodsSpecBase')->where(['id'=>$base['data']['id'], 'goods_id'=>$v['goods_id']])->setInc('inventory', $v['buy_number']))
                        {
                            return DataReturn('规格库存回滚失败['.$params['order_id'].'-'.$v['goods_id'].']', -10);
                        }
                    } else {
                        return $base;
                    }

                    // 回滚日志更新
                    $log_data = [
                        'is_rollback'   => 1,
                        'rollback_time' => time(),
                    ];
                    if(!Db::name('OrderGoodsInventoryLog')->where(['id'=>$temp['id']])->update($log_data))
                    {
                        return DataReturn('库存回滚日志更新失败['.$temp['id'].'-'.$params['order_id'].']', -100);
                    }
                }
            }
            return DataReturn('操作成功', 0);
        }
        return DataReturn('没有需要回滚的数据', 0);
    }
}
?>