| 123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172217321742175217621772178217921802181218221832184218521862187218821892190219121922193219421952196219721982199220022012202220322042205220622072208220922102211221222132214221522162217221822192220222122222223222422252226222722282229223022312232223322342235223622372238223922402241224222432244224522462247224822492250225122522253225422552256225722582259226022612262226322642265226622672268226922702271227222732274227522762277227822792280228122822283228422852286228722882289229022912292229322942295229622972298229923002301230223032304230523062307230823092310231123122313231423152316231723182319232023212322232323242325232623272328232923302331233223332334233523362337233823392340234123422343234423452346234723482349235023512352235323542355235623572358235923602361236223632364236523662367236823692370237123722373237423752376237723782379238023812382238323842385238623872388238923902391239223932394239523962397239823992400240124022403240424052406240724082409241024112412241324142415241624172418241924202421242224232424242524262427242824292430243124322433243424352436243724382439244024412442244324442445244624472448244924502451245224532454245524562457245824592460246124622463246424652466246724682469247024712472247324742475247624772478247924802481248224832484248524862487248824892490249124922493249424952496249724982499 |
- <?php
- /**
- * 重庆赤晓店信息科技有限公司
- * https://www.chixiaodian.com
- * Copyright (c) 2023 赤店商城 All rights reserved.
- */
- namespace app\modules\client\models\v1\order;
- use app\constants\OptionSetting;
- use app\models\Address;
- use app\models\AgentFrontBind;
- use app\models\AgentFrontErpInventory;
- use app\models\Cart;
- use app\models\common\CommonOrder;
- use app\models\DeliveryInfo;
- use app\models\District;
- use app\models\FoodCart;
- use app\models\FoodFlag;
- use app\models\Goods;
- use app\models\GoodsBook;
- use app\models\GoodsChainLevel;
- use app\models\IntegralAppreciationGoods;
- use app\models\IntegralAppreciationUser;
- use app\models\IntegralAppreciationUserIntegralLog;
- use app\models\Level;
- use app\models\LevelOrder;
- use app\models\Md;
- use app\models\MdGoods;
- use app\models\MdProfit;
- use app\models\Order;
- use app\models\OrderDetail;
- use app\models\OrderTransit;
- use app\models\QueueLog;
- use app\models\Register;
- use app\models\SaaSLeaguePriceLog;
- use app\models\SaasUser;
- use app\models\SeckillActivity;
- use app\models\SeckillActivityGoods;
- use app\models\SeckillActivityOrderLog;
- use app\models\ShareHolderLevel;
- use app\models\ShareHolderProfitGoodsLog;
- use app\models\Store;
- use app\models\Supplier;
- use app\models\User;
- use app\models\UserCoupon;
- use app\models\Option;
- use app\models\AccountLog;
- use app\models\LocalDeliveryFreight;
- use app\models\OfferPrice;
- use app\models\VerifyCard;
- use app\models\VerifyCardSale;
- use app\models\VerifyCardLog;
- use app\models\VideoGoods;
- use app\models\VideoGoodsList;
- use app\models\VideoGoodsSetting;
- use app\models\VideoGoodsShare;
- use app\models\WorkerOrderExt;
- use app\models\WorkerSetting;
- use app\modules\admin\models\MerchantForm;
- use app\plugins\adopt\models\AdoptGoods;
- use app\plugins\adopt\models\AdoptOrderInfo;
- use app\utils\CloudPrint;
- use app\utils\Delivery\Delivery;
- use app\utils\Delivery\Alipay\ADelivery;
- use app\utils\Delivery\WechatNewDelivery;
- use app\utils\Notice\NoticeSend;
- use app\utils\OrderNo;
- use app\utils\PrintOrder;
- use app\utils\Tools;
- use yii\helpers\ArrayHelper;
- use yii\helpers\Json;
- use app\modules\admin\models\ActivityCutPriceForm;
- use app\modules\admin\models\givingGifts\GivingGiftsForm;
- use yii\db\Expression;
- use app\modules\admin\models\mochat\MochatForm;
- use app\modules\admin\models\maiyatian\MaiyatianForm;
- use app\modules\admin\models\keloop\KeloopForm;
- class OrderSubmitForm extends OrderForm
- {
- public $user;
- public $payment;
- public $use_integral;
- public $buy_level_id;
- public $adopt_name;
- public $adopt_mobile;
- public $worker_time;
- public $is_fugou = 0;
- public function rules()
- {
- $rules = [
- [['payment', 'use_integral', 'buy_level_id', 'is_fugou'], 'integer'],
- [['adopt_name', 'adopt_mobile', 'worker_time'], 'string']
- ];
- return array_merge(parent::rules(), $rules);
- }
- public function preOrder()
- {
- if (!$this->validate())
- return [
- 'code' => 1,
- 'msg' => $this->getErrorSummary(false)[0],
- ];
- try {
- if (!$this->address['id']) {
- return [
- 'code' => 0,
- 'data' => [
- 'fee' => 0,
- 'resultcode' => 0
- ]
- ];
- // return [
- // 'code' => 1,
- // 'msg' => '请先选择收货地址',
- // ];
- }
- if (isset($this->pre_order_data)) {
- $this->mch_list = json_decode($this->pre_order_data, true);
- }
- $mch_list = $this->getMchListData(true);
- if (isset($mch_list['code']) && $mch_list['code'] == 1) {
- return $mch_list;
- }
- $goods_list = [];
- $fee = 0;
- foreach ($mch_list as $mch) {
- $is_front_delivery = 0;//做表里面的标识使用
- foreach ($mch['goods_list'] as $goods) {
- $goods_list[] = [
- 'name' => $goods['goods_name'],
- 'price' => $goods['price'],
- 'pic' => $goods['goods_pic'],
- 'num' => $goods['num'],
- 'weight' => $goods['weight'],
- ];
- }
- $delivery_time = $mch['delivery_time'];//送出时间
- if($this->order_no){
- $existOrder = Order::findOne(['order_no' => $this->order_no]);
- if($existOrder){
- return [
- 'code' => 1,
- 'msg' => '单号错误0,请后退到商品页重新下单',
- ];
- }
- $order_no = $this->order_no;
- }else{
- $order_no = OrderNo::getOrderNo(OrderNo::ORDER_ALIPAY_FOOD);
- $goods_id = array_column($mch['goods_list'], 'goods_id');
- sort($goods_id);
- $goods_id = implode(',', $goods_id);
- $goods_id = md5($goods_id);
- $order_no = cache()->get('delivery_order_no_' . $goods_id . '_' . get_user_id());
- }
- if (!$order_no) {
- throw new \Exception('同城配送暂不可用' . 'delivery_order_no_' . $goods_id . '_' . get_user_id());
- }
- $local_type = Option::get(OptionSetting::STORE_LOCAL_TYPE, $this->store_id, 'store')['value'];
- $local_type = Option::get(OptionSetting::STORE_LOCAL_TYPE, $this->store_id, 'pay', $local_type);
- foreach ($mch['goods_list'] as $goods) {
- if (intval($goods['is_front_delivery'])) {
- $is_front_delivery = 1;
- $local_type['value'] = "self";
- break;
- }
- }
- if($local_type['value'] == 'keloop') {//快跑者配送
- if(KeloopForm::isSaasOpen()){
- $preAddOrder = KeloopForm::preAddOrder($this->store_id, $order_no, $this->address['longitude'], $this->address['latitude']);
- if ($preAddOrder['code']) {
- return $preAddOrder;
- }
- $fee = bcadd($fee, (float)$preAddOrder['data']['fee'], 2);
- // return [
- // 'code' => 0,
- // 'msg' => 'ok',
- // 'data' => [
- // "resultcode" => 0,
- // 'fee' => (float)$preAddOrder['data']['fee'],
- // 'fee_data' => $preAddOrder['data']['fee_data'],
- // ],
- // 'order_no' => $order_no,
- // ];
- } else {
- return [
- 'code' => 1,
- 'msg' => '快跑者配送没有配置',
- ];
- }
- }
- if($local_type['value'] == 'maiyatian') {//麦芽田
- if(MaiyatianForm::isopen($this->store_id)){
- $getFreight = LocalDeliveryFreight::getFreight($this->store_id, $this->address, $delivery_time, LocalDeliveryFreight::TYPE_MAIYATIAN, $goods_list);
- if($getFreight['code'] != 0){
- return $getFreight;
- }
- $freight = $getFreight['data'];
- $preAddOrder = MaiyatianForm::preAddOrder($this->store_id, $order_no, $freight);
- $fee = bcadd($fee, (float)$freight, 2);
- // return [
- // 'code' => 0,
- // 'msg' => 'ok',
- // 'data' => [
- // "resultcode" => 0,
- //// 'fee' => (float)MaiyatianForm::getConf($this->store_id, 'cyy_delivery_fee'),
- // 'fee' => (float)$freight,
- // ],
- // 'order_no' => $order_no,
- // ];
- // return $preAddOrder;
- } else {
- return [
- 'code' => 1,
- 'msg' => '麦芽田没有配置',
- ];
- }
- } elseif($local_type['value'] == 'aggregate') {//聚合配送
- if(is_alipay_platform()){
- $this->address_id || $this->address_id = 220;
- $res = ADelivery::createOrder(1, $this->store_id, get_mini_id(), get_saas_user()->ali_user_id, $goods_list, $order_no, $this->address_id);;
- return array_merge($res, ['order_no' => $order_no]);
- }
- $store = Store::findOne($this->store_id);
- if (intval($store->wechat_delivery_type) === 0) {
- return array_merge(Delivery::preAddOrder($goods_list, $order_no), ['order_no' => $order_no]);
- } else {
- $form = new WechatNewDelivery();
- $result = $form->preAddOrder([
- 'address' => ArrayHelper::toArray($this->address),
- 'goods_list' => $goods_list,
- 'store_id' => $this->store_id,
- 'md_id' => get_md_id()
- ]);
- if ($result['code'] === 0) {
- DeliveryInfo::deleteAll(['order_no' => $order_no, 'store_id' => get_store_id(), 'status' => 0]);
- // 存预下单表
- $delivery_info = new DeliveryInfo();
- $delivery_info->store_id = get_store_id();
- $delivery_info->order_no = $order_no;
- $delivery_info->fee = bcdiv($result['data']['fee'], 100, 2);;
- $delivery_info->delivery_type = 0;
- $delivery_info->created_at = time();
- $delivery_info->is_local = DeliveryInfo::IS_LOCAL_NO;
- $serial_num = DeliveryInfo::find()->where(['>','created_at',strtotime(date('Y-m-d'))])->orderBy('serial_num desc')->asArray()->one()['serial_num'];
- $delivery_info->serial_num = $serial_num > 0 ? $serial_num + 1 : 1;
- $delivery_info->md_id = get_md_id();
- $delivery_info->wechat_delivery_type = 1;
- $delivery_info->save();
- // return array_merge($result, ['order_no' => $order_no]);
- $fee = bcadd($fee, (float)$result['data']['fee'], 2);
- } else {
- return $result;
- }
- // return array_merge($form->preAddOrder([
- // 'address' => ArrayHelper::toArray($this->address),
- // 'goods_list' => $goods_list,
- // 'store_id' => $this->store_id,
- // 'md_id' => 0
- // ]), ['order_no' => $order_no]);
- }
- } elseif(in_array($local_type['value'], ['self', 'self_store'])) {//平台自配
- // return Delivery::preAddOrder($goods_list, $order_no);
- /* 配送费搞一下 id891 WPing 2023年7月3日19:47:30 */
- if(!$this->address['id']){
- return [
- 'code' => 1,
- 'msg' => '请先选择收货地址',
- ];
- }
- $type = LocalDeliveryFreight::TYPE_LOCAL;
- if ($local_type['value'] === 'self_store') {
- $type = LocalDeliveryFreight::TYPE_STORE_LOCAL;
- }
- $getFreight = LocalDeliveryFreight::getFreight($this->store_id, $this->address, $delivery_time, $type, $goods_list);
- if($getFreight['code'] != 0){
- return $getFreight;
- }
- $freight = $getFreight['data'];
- DeliveryInfo::deleteAll(['order_no' => $order_no, 'store_id' => get_store_id(), 'status' => 0]);
- // 存预下单表
- $delivery_info = new DeliveryInfo();
- $delivery_info->store_id = get_store_id();
- $delivery_info->order_no = $order_no;
- $delivery_info->fee = $freight;
- $delivery_info->delivery_type = 0;
- $delivery_info->created_at = time();
- $delivery_info->is_local = DeliveryInfo::IS_LOCAL_YSE;
- $delivery_info->is_store_delivery_type = intval($local_type['value'] === 'self_store');
- $delivery_info->is_front_delivery = $is_front_delivery;//是否是仓库配送订单
- $serial_num = DeliveryInfo::find()->where(['>','created_at',strtotime(date('Y-m-d'))])->orderBy('serial_num desc')->asArray()->one()['serial_num'];
- $delivery_info->serial_num = $serial_num > 0 ? $serial_num + 1 : 1;
- $delivery_info->save();
- $fee = bcadd($fee, (float)$freight, 2);
- // return [
- // 'code' => 0,
- // 'msg' => 'success',
- // 'order_no' => $order_no,
- // 'data' => $getFreight['info'],
- // ];
- /* end */
- // return [
- // 'code' => 0,
- // 'data' => [
- // 'goods_list' => $goods_list,
- // 'order_no' => $order_no,
- // 'test' => [
- // 'address' => $address,
- // 'store' => $store,
- // 'distance' => $distance,
- // 'delivery_time' => $delivery_time,
- // 'delivery_time_stamp' => $delivery_time_stamp,
- // 'LocalDeliveryFreight' => $data,
- // 'freight_detail' => $freight_detail,
- // 'freight' => $freight,
- // ]
- // ],
- // 'msg' => '平台自配'
- // ];
- }
- }
- return [
- 'code' => 0,
- 'data' => [
- 'fee' => floatval($fee),
- 'resultcode' => 0
- ]
- ];
- } catch (\Exception $e) {
- return [
- 'code' => 1,
- 'msg1' => $e->getTraceAsString(),
- 'msg' => $e->getMessage()
- ];
- }
- }
- public function save()
- {
- if (!$this->validate())
- return [
- 'code' => 1,
- 'msg' => $this->getErrorSummary(false)[0],
- ];
- try {
- $mchListData = $this->getMchListData(true);
- if (isset($mchListData['code']) && $mchListData['code'] == 1) {
- return $mchListData;
- }
- if(count($mchListData) > 1){
- foreach($mchListData as $mch){
- if($mch['mch_id'] > 0 && $mch['send'] == 'shop'){
- throw new \Exception('(' . $mch['name'] . ')店铺需要单独提交订单');
- }
- }
- }
- } catch (\Exception $e) {
- return [
- 'code' => 1,
- 'msg' => $e->getMessage()
- ];
- }
- $order_id_list = [];
- $level = $this->level;
- $md_select = 0;
- /**
- * @var $address Address
- */
- $order_type_ext = 0;
- $address = (object)($this->address);
- $t = \Yii::$app->db->beginTransaction();
- if ($this->is_worker) {
- $start_time = strtotime($this->worker_time);
- $end_time = $start_time + 1800;
- $order_ext = WorkerOrderExt::find()->where(['worker_id' => $this->worker_id, 'user_revoke' => 0])
- ->andWhere(['AND', ['>=', 'time_start_service', $start_time], ['<', 'time_start_service', $end_time]])
- ->select('time_start_service, time_end_service')->one();
- if ($order_ext) {
- return [
- 'code' => 1,
- 'msg' => '当前时间不可预约'
- ];
- }
- }
- foreach ($mchListData as &$mch) {
- if(get_md_id() > 0 && $mch['mch_id'] > 0){
- return [
- 'code' => 1,
- 'msg' => '(' . $mch['name'] . ')店铺下单,需要取消门店选择',
- ];
- }
- // 门店营业时间判断
- if (get_md_id() && get_md_id() > 0 && $mch['send'] == 'shop') {
- $md = Md::findOne(['id' => get_md_id(), 'is_delete' => 0]);
- if ($md->open_status == 0) {
- return [
- 'code' => 1,
- 'msg' => '门店已打烊'
- ];
- }
- if ($md->is_time_forbid == 0 && !$this->checkTimeBeginEnd($md->start_time, $md->end_time) && $md->shop_time_type == 1) {
- return [
- 'code' => 1,
- 'msg' => '非营业时间禁止下单'
- ];
- }
- }
- if (isset($mch['use_integral']) && !$mch['use_integral']) {
- $mch['integral'] = ['forehead' => 0, 'forehead_integral' => 0];
- $mch['give'] = 0;
- }
- $mch_goods = $mch['goods_list'];
- if ($mch_goods) {
- $checkMchData = $this->checkMchData($mch);
- if ($checkMchData['code'] == 1) {
- $t->rollBack();
- return $checkMchData;
- }
- $level_price = 0;
- $total_price = 0;
- $is_have_express = false;
- $is_have_shop = false;
- $order_type = 0;
- $is_have_delivery = 0;
- $total_integral = 0;
- if ($mch['send'] == 'express') {
- $is_have_express = true;
- }
- if ($mch['send'] == 'shop') {// || get_md_id()
- $is_have_shop = true;
- if (!empty($mch['shop']) && !empty($mch['shop']['id'])) {
- $md_select = $mch['shop']['id'];
- }
- }
- $is_delivery = OfferPrice::findOne([
- 'store_id' => get_store_id(),
- 'is_delete' => 0
- ]);
- $store_data = Store::findOne(get_store_id());
- $delivery_rules = [];
- if ($mch['send'] == 'delivery') {
- $local_type = Option::get(OptionSetting::STORE_LOCAL_TYPE, get_store_id(), 'store')['value'];
- $local_type = Option::get(OptionSetting::STORE_LOCAL_TYPE, get_store_id(), 'pay', $local_type);
- $is_have_express = true;
- $delivery_rules = json_decode($is_delivery->delivery_rules, true);
- if ($is_delivery->delivery_type == 1 && !empty($delivery_rules)) {
- $conf = [
- 'shop_tag' => $store_data->coordinate,
- 'deliveryRules' => $delivery_rules
- ];
- $deliveryRules = $this->canDeliver($address, $conf);
- if (!$deliveryRules['can_deliver']) {
- return [
- 'code' => 1,
- 'msg' => '当前订单超出配送距离'
- ];
- }
- }
- if ($local_type['value'] == 'keloop') { //快跑者配送
- if (!KeloopForm::isSaasOpen()) {
- $t->rollBack();
- return [
- 'code' => 1,
- 'msg' => '商城未设置有效配送方式'
- ];
- }
- }
- if($local_type['value'] == 'maiyatian') {//麦芽田
- $maiyatian = MaiyatianForm::isopen($this->store_id);
- if (!$maiyatian) {
- $t->rollBack();
- return [
- 'code' => 1,
- 'msg' => '商城未设置有效配送方式'
- ];
- }
- } elseif($local_type['value'] == 'aggregate') {//聚合配送
- $store = Store::findOne($this->store_id);
- if (intval($store->wechat_delivery_type) === 0) {
- if ($store->delivery_type == 0) {
- $t->rollBack();
- return [
- 'code' => 1,
- 'msg' => '商城未设置有效配送方式'
- ];
- }
- $res = Delivery::getBindAccount();
- // 下单时判断是否可以同城配送
- if (empty($res['data']['shop_list'])) {
- $t->rollBack();
- return [
- 'code' => 1,
- 'msg' => '当前未绑定运力账号,暂不能保存选择同城配送方式'
- ];
- }
- $shop_list = $res['data']['shop_list'];
- $delivery_arr = array_column($shop_list, 'delivery_id');
- $delivery_arr[] = 'TEST';
- $delivery_arr_id = array_column($shop_list, null, 'delivery_id');
- if (!in_array(Delivery::$deliveryIdArr[$store->delivery_type], $delivery_arr) || $delivery_arr_id[Delivery::$deliveryIdArr[$store->delivery_type]]['audit_result'] != 0) {
- $t->rollBack();
- return [
- 'code' => 1,
- 'msg' => '当前账号未在微信后台绑定或者并未审核通过'
- ];
- }
- }
- } elseif(in_array($local_type['value'], ['self', 'self_store'])) {//平台自配
- if(empty($mch['delivery_time'])){
- $store_id = $local_type['value'] === 'self_store' ? $this->store_id : 0;
- $setting = json_decode(Option::get(OptionSetting::LOCAL_DELIVERY_SETTING, $store_id, '', '{}')['value'], true);
- $mch['delivery_time'] = date('Y-m-d H:i:s', time() + 90 * 60);
- if(!empty($setting['default_time']) && !empty($setting['default_time']['value'])){
- $mch['delivery_time'] = date('Y-m-d H:i:s', time() + ($setting['default_time']['value'] * 60));
- }
- }
- }
- $is_have_delivery = true;
- }
- $take_price = 0;
- $send_price = 0;
- foreach ($mch_goods as $v) {
- if ($v['product_type'] == 1) {
- $order_type = 1;
- }
- if ($v['product_type'] == 2) {
- $order_type = 2;
- }
- if ($v['product_type'] == 3) {
- $order_type = 4;
- }
- if ($v['product_type'] == Goods::GOODS_TYPE_ADOPT) {
- $order_type = 5;
- }
- if ($v['product_type'] == Goods::GOODS_TYPE_WORKER) {
- $order_type = 6;
- }
- if ($v['product_type'] == Goods::GOODS_TYPE_INTEGRAL) {
- $order_type = 7;
- $total_integral += isset($v['integral_price']) ? $v['integral_price'] : 0;
- }
- //普通商品没选择门店禁止选择自提方式
- if ($v['product_type'] == 0 && $is_have_shop && !$v['mch_id']) {
- if (empty(input_params('flag_id')) && empty(input_params('table_num'))) {
- $md_id = get_md_id();
- if ($md_id > 0 || ($mch['shop'] && $mch['shop']['id'])) {
- $md_info = Md::findOne($md_id > 0 ? $md_id : $mch['shop']['id']);
- if (!$md_info) {
- return [
- 'code' => 1,
- 'result_code' => 'select_md',
- 'msg' => '自提订单请选择门店'
- ];
- }
- } else {
- return [
- 'code' => 1,
- 'result_code' => 'select_md',
- 'msg' => '自提订单请选择门店'
- ];
- }
- }
- }
- // if ($v['send'] == 'shop' && empty($v['shop_id']) && empty($v['shop'])) {
- // return [
- // 'code' => 1,
- // 'msg' => '自提商品请选择自提点'
- // ];
- // }
- if ($this->buy_level_id && $order_type !== 6) {
- $level_price += $v['next_level_price'];
- } else {
- if ($v['payment_type']) {
- $level_price += $v['pre_price'];
- } else {
- $level_price += $v['level_price'];
- }
- }
- if ($v['payment_type']) {
- $order_type_ext = 1;
- $total_price += $v['pre_price'];
- } else {
- $total_price += isset($v['total_price']) ? $v['total_price'] : $v['price'];
- }
- $take_price += $v['take_price'] ?? 0;
- $send_price += $v['send_price'] ?? 0;
- }
- $mch['level_price'] = $level_price;
- $mch['level_diff_price'] = sprintf('%.2f',$mch['next_level']['diff_price']);
- $mch['total_price'] = $total_price;
- $mch['total_integral'] = $total_integral; //积分兑换
- // 是否开启配送范围设置
- if ($is_have_delivery) {
- if (get_md_id() > 0) {
- $md_info = Md::findOne(get_md_id());
- $lat = $md_info->latitude;
- $long = $md_info->longitude;
- $is_set_distance = $md_info->is_set_distance;
- $distance = $md_info->distance;
- } else {
- $store_info = Store::findOne(get_store_id());
- $is_set_distance = $store_info->is_set_distance;
- $distance = $store_info->distance;
- $coordinate = explode(',', $store_info->coordinate);
- $lat = $coordinate[0];
- $long = $coordinate[1];
- }
- if ($is_set_distance) {
- $distance_str = Tools::getDistance($lat, $long, $address->latitude, $address->longitude);
- if ($distance_str != '未知距离') {
- if (false !== strpos($distance_str, 'km')) {
- if (floatval($distance_str) > $distance) {
- $t->rollBack();
- return [
- 'code' => 1,
- 'msg' => '当前订单超出配送距离'
- ];
- }
- } else {
- if (floatval($distance_str) > $distance * 1000) {
- $t->rollBack();
- return [
- 'code' => 1,
- 'msg' => '当前订单超出配送距离'
- ];
- }
- }
- }
- }
- }
- //判断服务范围
- if ($this->is_worker) {
- $result = $this->travel;
- $setting = WorkerSetting::getByStoreId(get_store_id());
- if ($result['distance'] > ($setting->order_range / 1000)) {
- return [
- 'code' => 1,
- 'msg' => '超出服务范围,请选择附近下单'
- ];
- }
- }
- // 开启使用积分抵扣
- if (isset($mch['use_integral']) && $mch['use_integral'] == 1) {
- if (get_user()->integralPrice < $mch['integral']['forehead'] || get_user()->integral < $mch['total_integral']) {
- return [
- 'code' => 1,
- 'msg' => '积分可抵扣支付数量不足'
- ];
- }
- }
- if ($order_type == 1) {
- $bookCount = count($mch_goods[0]['book']);
- $mch['level_price'] *= $bookCount;
- $mch['total_price'] *= $bookCount;
- }
- $mch['level_price'] = $this->getBookPrice($mch['level_price'], $mch_goods);
- $payPrice = $this->getPayPrice($mch);
- if ($is_have_express && $is_delivery->delivery_type == 1 && !empty($delivery_rules)) {
- if ($payPrice < $deliveryRules['delivery_price']) {
- return [
- 'code' => 1,
- 'msg' => '同城配送订单满 ¥' . $deliveryRules['delivery_price'] . ' 起送'
- ];
- }
- }
- $order = new Order();
- // $verifylog = new VerifyCardLog();
- // $verifycardsale = new VerifyCardSale();
- if($mch['delivery_time']){
- $order->delivery_time = strtotime($mch['delivery_time']);
- }
- // 订单来源
- if (is_h5()) {
- $order->order_origin = Order::ORDER_SOURCE_WEB;
- }
- if (is_app_platform()) {
- $order->order_origin = Order::ORDER_SOURCE_APP;
- }
- $order->total_price = $mch['total_price'];
- $order->level_diff_price = $mch['level_diff_price'];
- $order->store_id = $this->store_id;
- $order->user_id = $this->user_id;
- // 兼容手机端自提订单 核销订单展示部分 start 修改为使用user表数据
- $order->name = get_user()->nickname;
- $order->mobile = get_user()->binding;
- // end
- $order->buy_level_id = $this->buy_level_id ?: 0;
- $order->level_price_json = json_encode($mch['level_price_arr']);
- if (!empty($this->verify_card_id)) {
- $vcs = VerifyCardSale::findOne($this->verify_card_id);
- if($vcs->status == 1){
- return [
- 'code' => 1,
- 'msg' => '卡券已被使用过'
- ];
- }
- $order->type = 1;
- }
- if ($is_have_delivery) {
- if($this->order_no){
- $order->order_no = $this->order_no;
- }else{
- $goods_id = array_column($mch['goods_list'], 'goods_id');
- sort($goods_id);
- $goods_id = implode(',', $goods_id);
- $goods_id = md5($goods_id);
- $order->order_no = cache()->get('delivery_order_no_' . $goods_id . '_' . get_user_id());
- }
- $existOrder = Order::findOne(['order_no' => $order->order_no]);
- if($existOrder){
- $t->rollBack();
- return [
- 'code' => 1,
- 'msg' => '单号错误1,请后退到商品页重新下单' . $order->order_no . 'aa',
- ];
- }
- } else {
- $order->order_no = OrderNo::getOrderNo(OrderNo::ORDER_MALL);
- }
- $order->pay_price = !empty($this->verify_card_id) ? 0 : $payPrice;
-
- if ($mch['rand_discount_price'] > 0) {
- if ($order->pay_price <= 0) {
- $order->rand_discount = 0;
- } else {
- $order->pay_price -= $mch['rand_discount_price'];
- $order->rand_discount = $mch['rand_discount_price'];
- }
- }
- if ($mch['integral_appreciation_price'] > 0) {
- if ($order->pay_price <= 0) {
- $order->rand_discount = 0;
- } else {
- if ($order->pay_price > $mch['integral_appreciation_price']) {
- $order->pay_price -= $mch['integral_appreciation_price'];
- } else {
- $mch['integral_appreciation_price'] = $order->pay_price;
- $order->pay_price = 0;
- }
- $order->integral_appreciation_price = $mch['integral_appreciation_price'];
- }
- }
- if (isset($mch['picker_coupon']) && !empty($mch['picker_coupon'])) {
- $order->user_coupon_id = $mch['picker_coupon']['user_coupon_id'];
- $order->coupon_sub_price = $mch['picker_coupon']['sub_price'];
- // 查找优惠券优惠的商品
- $this->pickerGoods($mch);
- }
- // 订单类型
- $order->order_type = $order_type;
- // 积分兑换商品
- if (isset($mch['total_integral']) && $mch['total_integral'] > 0 ) {
- if (get_user()->integral < $mch['total_integral']) {
- //获取商城积分抵扣规则 x积分 = 1元
- $integral_rule = Option::find()->where(['store_id'=>get_store_id(),'name'=>'integral'])->select('value')->asArray()->one();
- $difference_price = sprintf("%.2f", ($mch['total_integral'] - get_user()->integral ) / $integral_rule['value'] );
- $order->pay_price += $difference_price;
- $order->total_price += $difference_price;
- $order->integral_price = get_user()->integral ?? 0;
- $order->integral_difference_price = $difference_price;
- $mch['integral_type'] = 2; //积分不足
- $mch['integral_difference_price'] = $difference_price; //补的差额
- }else{
- $order->integral_price = $mch['total_integral'] ?? 0;
- $order->integral_difference_price = 0;
- $mch['integral_type'] = 1; //全部使用积分
- $mch['integral_difference_price'] = 0; //补的差额
- }
- //当用户有积分时
- // if(get_user()->integral > 0){
- // $upIntegral = get_user()->integral - $order->integral_price;
- // //减用户积分
- // if(! User::updateAll(['integral'=>$upIntegral],['id'=> get_user_id()]) ){
- // $t->rollBack();
- // return [
- // 'code' => 1,
- // 'msg' => '积分抵扣失败,稍后重试!'
- // ];
- // }
- // }
- }
- // 是否是平台小程序订单
- if (is_platform()) {
- $order->is_platform = 1;
- }
- if (get_md_id()) {
- $order->md_id = get_md_id();
- }
- if($md_select > 0){
- $order->md_id = $md_select;
- }
- $order->is_fugou = $this->is_fugou;
- // if($this->send_price){
- // $order->send_price = $this->send_price;
- // }
- // if($this->take_price){
- // $order->take_price = $this->take_price;
- // }
- $order->take_price = $take_price;
- if ($order->pay_price > 0) {
- if($order->take_price > 0) {
- $order->pay_price -= $order->take_price;
- $order->total_price -= $order->take_price;
- }
- } else {
- if($order->take_price > 0) {
- $order->take_price = 0;
- $order->send_price = 0;
- }
- }
- $order->send_price = $send_price;
- $order->created_at = time();
- $order->first_price = 0;
- $order->second_price = 0;
- $order->third_price = 0;
- $order->content = isset($mch['content']) ? $mch['content'] : '';
- $order->is_offline = $is_have_shop ? 1 : 0;
- $order->is_delivery = $is_have_delivery ? 1 : 0;
- // TODO 商品余额抵扣
- if (isset($mch['use_balance']) && $mch['use_balance'] == 1) {
- $totalBalance = array_sum(array_column($mch['goods_list'], 'balance'));
- $order->balance = $totalBalance ? $totalBalance : 0;
- $order->pay_price -= $totalBalance;
- }
- if (isset($mch['use_integral']) && $mch['use_integral'] == 1) {
- $order->integral = json_encode($mch['integral'], JSON_UNESCAPED_UNICODE);
- $order->integral_difference_price = sprintf('%.2f', $mch['integral']['forehead']);
- $integral_price = $mch['integral']['forehead_integral'];
- if ($mch['total_integral']) {
- $integral_price = $mch['total_integral'];
- }
- $order->integral_price = $integral_price? $integral_price : 0;
- } else {
- $order->integral = json_encode(['forehead' => 0, 'forehead_integral' => 0], JSON_UNESCAPED_UNICODE);
- $order->integral_difference_price = 0;
- }
- $order->version = cyy_version();
- $order->mch_id = $mch['mch_id'] ?? 0;
- $order->discount = isset($level['discount']) ? $level['discount'] : 10;
- $order->remark = $mch['remark'] ?? '';
- if ($this->payment == 2) {
- $order->pay_type = 2;
- $order->is_pay = 0;
- }
- if ($this->payment == 3) {
- $order->pay_type = 3;
- $order->is_pay = 0;
- }
- // 线下支付
- if ($this->payment == 6) {
- $order->pay_type = 6;
- $order->is_pay = 0;
- }
- if ((!empty(input_params('flag_id')) || !empty(input_params('table_num')))) {
- if (get_md_id() < 0) {
- if (\Yii::$app->prod_is_dandianpu() || \Yii::$app->prod_is_shangmeng() || \Yii::$app->prod_is_shangmengduli()) {
- $store = Store::findOne(get_store_id());
- if ($store->open_status == 0) {
- $t->rollBack();
- return [
- 'code' => 1,
- 'msg' => '已打烊'
- ];
- }
- if ($store->is_time_forbid == 0 && !$this->checkTimeBeginEnd($store->s_time, $store->e_time) && $store->shop_time_type == 1) {
- $t->rollBack();
- return [
- 'code' => 1,
- 'msg' => '非营业时间禁止下单'
- ];
- }
- }
- }
- if (!empty(input_params('flag_id'))) {
- $order->food_flag_id = input_params('flag_id');
- } else {
- $order->food_flag_id = FoodFlag::findOne(['store_id' => get_store_id(), 'md_id' => get_md_id(), 'status' => 0, 'table_num' => input_params('table_num')])->id;
- }
- $order->order_type = 3;
- $order->food_book_ext = $mch['food_book_ext'];
- }
- if ($is_have_express || get_md_id()) {
- $order->address = $address->province . $address->city . $address->district . $address->town . $address->village . $address->detail;
- $order->mobile = $address->mobile ?: get_user()->binding;
- $order->name = $address->name ?: get_user()->nickname;
- if ($is_have_express) {
- if (!preg_match('/^1[1-9]\d{9}$/', $order->mobile) || empty($order->name)) {
- return [
- 'code' => 1,
- 'msg' => '请前往收货地址填写收货人以及手机号信息'
- ];
- }
- }
- if ($is_have_express) {
- $order->province_id = $address->province_id;
- $order->city_id = $address->city_id;
- $order->district_id = $address->district_id;
- $order->town_id = $address->town_id ? : 0;
- $order->village_id = $address->village_id ? : 0;
- }
- $order->address_data = json_encode([
- 'province' => trim($address->province),
- 'city' => trim($address->city),
- 'district' => trim($address->district),
- 'detail' => trim($address->detail),
- 'town' => $address->town_id ? trim($address->town) : '',
- 'village' => $address->village_id ? trim($address->village) : '',
- 'latitude' => $address->latitude,
- 'longitude' => $address->longitude,
- ], JSON_UNESCAPED_UNICODE);
- if ($is_have_delivery) {
- $order->total_price = !empty($this->verify_card_id) ? 0 : $mch['total_price'];
- } else {
- if (intval($order->order_type) === 6) {
- $order->book_info = json_encode(['worker_id' => $this->worker_id, 'worker_time' => $this->worker_time]);
- $order->express_price = $mch['travel_price'];
- $order->total_price = !empty($this->verify_card_id) ? 0 : $mch['total_price'] + $mch['travel_price'];
- if ($order_type_ext) {
- $order->order_type_ext = 601;
- }
- } else {
- $order->express_price = $mch['express_price'] ?? 0;
- ///
- $order->total_price = !empty($this->verify_card_id) ? 0 : $mch['total_price'] + ($mch['express_price'] ?? 0);
- }
- }
- }
- if ($is_have_shop) {
- $order->total_price = !empty($this->verify_card_id) ? 0 : $mch['total_price'];
- $order->express_price = 0;
- if (get_md_id()) {
- $md_info = Md::findOne(get_md_id());
- $order->province_id = $md_info->province;
- $order->city_id = $md_info->city;
- $order->district_id = $md_info->district;
- $order->town_id = 0;
- $order->village_id = 0;
- $md_address_province = District::findOne($md_info->province)->name ?: '';
- $md_address_city = District::findOne($md_info->city)->name ?: '';
- $md_address_district = District::findOne($md_info->district)->name ?: '';
- $order->address_data = json_encode([
- 'province' => trim($md_address_province),
- 'city' => trim($md_address_city),
- 'district' => trim($md_address_district),
- 'detail' => trim($md_info->address),
- 'town' => '',
- 'village' => '',
- 'latitude' => $md_info->latitude,
- 'longitude' => $md_info->longitude,
- ], JSON_UNESCAPED_UNICODE);
- $order->address = $md_address_province . $md_address_city . $md_address_district . $md_info->address;
- }
- }
- if ($order->order_type == 1 || $order->order_type == 2) {
- $order->book_info = Json::encode($mch['book_info']);
- }
- if ($order->order_type == 2) {
- $order->total_price = $payPrice;
- }
- if ($order->order_type == 1) {
- $order->total_price = $mch['total_price'];
- }
- // 礼品卡订单
- if (!empty(post_params('verify_card_id'))) {
- $order->verify_card_id = post_params('verify_card_id');
- }
- //获取代理配置信息
- $store = Store::findOne($this->store_id);
- //支付金额 * 店铺让利比例 * 代理商分润比例
- // $admin_profit = Option::get('admin_profit', 0, 'saas', 0)['value'];
- if (!empty($store->transfer_profit)) {
- $order->ag_rebate = $payPrice * ($store->transfer_profit / 100);
- }
- // 配送订单预存数据
- if ($is_have_delivery) {
- // $delivery_info = new DeliveryInfo();
- // $delivery_info->store_id = get_store_id();
- // $delivery_info->order_no = $order->order_no;
- // $delivery_info->status = 0;
- // $delivery_info->created_at = time();
- // $delivery_info->updated_at = time();
- // $delivery_info->save();
- }
- $order->saas_id = 0;
- $order->integral_difference_price = 0;
- if($this->activity_cut_price_order_id){
- $order->activity_cut_price_order_id = $this->activity_cut_price_order_id;
- }
- if($this->activity_wechat_room_id){
- $order->activity_wechat_room_id = $this->activity_wechat_room_id;
- }
-
- if ($is_have_delivery) {
- $cacheK = 'is_have_delivery_' . $order->order_no;
- $cacheV = cache()->get($cacheK);
- $deliveryInfo = DeliveryInfo::find()->where(['order_no' => $order->order_no])->one();
- if(!$deliveryInfo){
- $t->rollBack();
- if($cacheV){
- return [
- 'code' => 1,
- 'msg' => '配送单不存在,请返回商品详情页重新下单。' . $cacheV . $cacheK
- ];
- }
- cache()->set($cacheK, 1, 180);
- $this->order_no = $order->order_no;
- $preOrder = $this->preOrder();
- if($preOrder['code'] != 0){
- return $preOrder;
- }else{
- $this->order_no = '';
- return $this->save();
- }
- } else {
- if (intval($deliveryInfo->wechat_delivery_type) === 1) {
- $goods_list = [];
- //foreach ($mch as $mch_item) {
-
- foreach ($mch['goods_list'] as $goods) {
- $goods_list[] = [
- 'name' => $goods['goods_name'],
- 'price' => $goods['price'],
- 'pic' => $goods['goods_pic'],
- 'num' => $goods['num'],
- 'weight' => $goods['weight'],
- ];
- }
- //}
- $form = new WechatNewDelivery();
- $result = $form->preAddOrder([
- 'address' => ArrayHelper::toArray($this->address),
- 'goods_list' => $goods_list,
- 'store_id' => $this->store_id,
- 'md_id' => get_md_id()
- ]);
- // $result = $form->addOrder([
- // 'address' => ArrayHelper::toArray($this->address),
- // 'goods_list' => $goods_list,
- // 'store_id' => $order->store_id,
- // 'md_id' => $order->md_id ?: 0,
- // 'order_no' => $order->order_no,
- // 'store_user' => ArrayHelper::toArray(get_user()),
- // 'order_seq' => $deliveryInfo->serial_num,
- // 'order_detail_path' => '/order/order-detail/order-detail?id=' . $order->id,
- // ]);
- if ($result['code'] === 0) {
- $deliveryInfo = DeliveryInfo::findOne(['order_no' => $order->order_no]);
- if (floatval($deliveryInfo->fee) !== floatval(bcdiv($result['data']['fee'], 100, 2))) {
- $t->rollBack();
- return [
- 'code' => 1,
- 'msg' => '配送费错误,请重新下单'
- ];
- }
- } else {
- $t->rollBack();
- return $result;
- }
- }
- }
- $order->total_price += $deliveryInfo->fee;
- $order->pay_price += $deliveryInfo->fee;
- }
- if($this->invoiceConf){
- $order->tax_price += $mch['tax_price'];
- $order->total_price += $mch['tax_price'];
- $order->pay_price += $mch['tax_price'];
- }
- // 添加到货时间 已经根据到货时间进行过拆单 取第一个商品的到货规则进行存储即可
- $order->arrival_time = $mch['goods_list'][0]['delivery_rules'] ? $mch['goods_list'][0]['delivery_rules']['arrival_time'] : 0;
- // 增加订单对应的门店团购轰动ID
- $order->md_group_activities_id = $mch['goods_list'][0]['md_group_activities_id'] ?? 0;
- if($this->is_wastore){
- $order->is_wastore = 1;
- }
- if($order->pay_price < 0){
- $t->rollBack();
- return [
- 'code' => 1,
- 'msg' => '订单金额错误,请检查优惠信息' . $order->pay_price,
- 'mch' => [$mch, $order],
- ];
- }
- if ($order->save()) {
- if($this->is_giving_gifts){
- $giving_gifts = GivingGiftsForm::orderSubmit($order, $this->giving_gifts_data);
- if($giving_gifts['code']){
- $t->rollBack();
- return $giving_gifts;
- }
- }
- //如果客户没有设置默认地址,当客户下单一次后,自动将该地址设置为 默认地址
- if ($this->address) {
- $check_address = Address::find()->where([
- 'user_id' => get_saas_user_id(),
- 'is_default' => 1,
- 'is_delete' => 0,
- ])->limit(1)->one();
- if (empty($check_address)) {
- $edit_address = Address::findOne($this->address['id']);
- if ($edit_address) {
- $edit_address->is_default = 1;
- $edit_address->save();
- }
- }
- }
- if($this->is_wastore && $this->traceId){
- cache()->set('wastoreShopOrderAdd' . $order->id, [
- 'traceId' => $this->traceId,
- ], 86400 * 30);
- }
- //砍价订单
- if($this->activity_cut_price_order_id){
- $orderUsed = ActivityCutPriceForm::orderUsed($this->activity_cut_price_order_id, $order);
- if ($orderUsed['code'] != 0) {
- $t->rollBack();
- return $orderUsed;
- }
- }
- //开发票
- if($this->invoiceConf){
- $orderInvoiceSave = \app\modules\admin\models\InvoiceForm::orderInvoiceSave($order->id, $this->invoiceConf);
- if ($orderInvoiceSave['code'] != 0) {
- $t->rollBack();
- return $orderInvoiceSave;
- }
- }
- // //如果是余额支付
- // if($order->order_type == 7){
- // $log = new AccountLog();
- // $log->store_id = get_store_id();
- // $log->user_id = get_user_id();
- // $log->type = AccountLog::TYPE_INTEGRAL;
- // $log->log_type = AccountLog::LOG_TYPE_EXPEND;
- // $log->amount = $order->integral_price;
- // $log->desc = "订单积分抵扣支付,订单号为:{$order->order_no}。";
- // $log->before = get_user()->integral;
- // $log->after = get_user()->integral - $order->integral_price;
- // $log->operator = '';
- // $log->operator_id = 0;
- // $log->operator_type = AccountLog::TYPE_OPERATOR_NORMAL;
- // $log->created_at = time();
- // $log->order_id = $order->id;
- // $log->order_type = AccountLog::TYPE_PLATFORM_ORDER;
- // if(!$log->save()){
- // $t->rollBack();
- // return [
- // 'code' => 1,
- // 'msg' => '记录积分消耗失败,请稍后再试',
- // 'error' => $log->errors[0]
- // ];
- // }
- // }
- //
- // try {
- // $res = $this->reduceIntegral($order);
- // if ($res['code'] !== 0) {
- // throw new \Exception($res['msg']);
- // }
- // } catch (\Exception $e) {
- // $t->rollBack();
- // return [
- // 'code' => 1,
- // 'msg' => '积分抵扣失败,请稍后再试',
- // ];
- // }
- // 绑定上下级
- $user = User::findOne($this->user_id);
- if ($user && $user->parent_user_id) {
- CommonOrder::saveParentId($user->parent_user_id);
- }
- // VerifyCard::updateAll(['send_times' => $send_times], 'id='.$VerifyCardSale['verify_card_id']);
- // VerifyCardSale::updateAll(['left_num' => $left_num, 'status' => 1],'id='.$this->verify_card_id);
- // $verifylog->save();
- // 更改点餐flag_id状态
- if (!empty(input_params('flag_id'))) {
- FoodCart::updateAll(['is_delete' => 1], ['flag_id' => input_params('flag_id')]);
- FoodFlag::updateAll(['status' => 1], ['id' => input_params('flag_id'), 'status' => 0]);
- }
- // 处理订单生成之后其他相关数据
- $orderRes = $this->insertData($mch, $order);
- if ($orderRes['code'] == 1) {
- $t->rollBack();
- return $orderRes;
- }
- $printer_order = new PrintOrder($order->store_id, $order->id, 'order', 0, $order->md_id, 0, $order['mch_id']);
- $printer_order->print_order();
- // 订单提交完成发送消息
- $order_type = 0;
- if ($order->order_type === 6) {
- $order_type = 6;
- }
- $mch_name = '';
- if($order['mch_id']){
- $mch_name = '[' . $mch['name'] . ']';
- }
- NoticeSend::OrderSubmit($this->user_id, $order->mobile, $order->order_no, $order->pay_price, $mch_name . $mch_goods[0]['goods_name'], $order_type, $order->store_id);
- $order_id_list[] = $order->id;
- } else {
- $t->rollBack();
- return [
- 'code' => 0,
- 'msg' => implode(';', array_values($order->firstErrors)),
- '$order' => $order->getErrors(),
- '$order1' => $order->attributes,
- ];
- }
- }
- }
- if (count($order_id_list) > 0) {
- $t->commit();
- $store = Store::findOne($this->store_id);
- if (count($order_id_list) > 1) {//多个订单合并
- return [
- 'code' => 0,
- 'msg' => '订单提交成功',
- 'data' => (object)[
- 'order_id_list' => $order_id_list,
- 'add_time' => $order->created_at,
- 'douyin_url' => $store->douyin_url,
- ],
- ];
- } else {//单个订单
- $order_id = $order_id_list[0];
- // if ($order->pay_price > 0) {
- // if($order->take_price > 0) {
- // $order->pay_price -= $order->take_price;
- // $order->total_price -= $order->take_price;
- // }
- // } else {
- // if($order->take_price > 0) {
- // $order->take_price = 0;
- // $order->send_price = 0;
- // }
- // }
- // $order->save();
- $returnData = [
- 'order_id' => $order_id_list[0],
- 'add_time' => $order->created_at,
- 'order_price'=> $order->pay_price,
- 'douyin_url' => $store->douyin_url,
- ];
-
- // if ($mch['rand_discount_price'] > 0) {
- // $randDiscountCache = cache()->get('rand_discount_cache2_' . $this->user_id);
- // if ($randDiscountCache && $randDiscountCache['rand'] != $mch['rand_discount_price']) {
- // return [
- // 'code' => 1,
- // 'msg' => '非法请求!',
- // ];
- // }
- // $returnData['old_price'] = $order->pay_price;
- // if ($order->pay_price <= 0) {
- // $order->rand_discount = 0;
- // $order->save();
- // } else {
- // $order->pay_price -= $mch['rand_discount_price'];
- // $order->rand_discount = $mch['rand_discount_price'];
- // $order->save();
- // }
- //
- // $returnData['order_price'] = $order->pay_price;
- // $returnData['rand_discount_price'] = $mch['rand_discount_price'];
- // }
- CloudPrint::doPrint($order_id, 0, $this->store_id);
- return [
- 'code' => 0,
- 'msg' => '订单提交成功',
- 'data' => (object)$returnData,
- ];
- }
- } else {
- $t->rollBack();
- return [
- 'order_list' => $order_id_list,
- 'order_price'=> $order->pay_price
- ];
- }
- }
- /**
- * 判断是否可以配送并计算费用
- */
- private function canDeliver($address, $conf)
- {
- // 解析商家地址的经纬度
- list($shopLon, $shopLat) = explode(',', $conf['shop_tag']);
- // 计算距离
- $distance = Tools::getDistance((float)$shopLat, (float)$shopLon, $address->latitude ?: $address['latitude'], $address->longitude ?: $address['longitude']);
- if (strpos($distance, 'km') !== false) {
- $distance = floatval(explode('km', $distance)[0]);
- } elseif (strpos($distance, 'm') !== false) {
- $distance = floatval(explode('m', $distance)[0]) / 1000;
- }
- foreach ($conf['deliveryRules'] as $rule) {
- if ($rule['start'] <= $distance && $distance <= $rule['end']) {
- return [
- 'can_deliver' => true,
- 'distance' => $distance,
- 'delivery_price' => $rule['price'],
- 'delivery_range' => [$rule['start'], $rule['end']]
- ];
- }
- }
- return ['can_deliver' => false, 'distance' => $distance, 'delivery_price' => null, 'delivery_range' => null];
- }
- private function reduceIntegral($order)
- {
- try {
- $integral = Json::decode($order->integral);
- // 减去当前用户账户积分
- if ($integral['forehead_integral'] > 0) {
- $user = User::findOne($order->user_id);
- $before = $user->integral;
- if ($before < $integral['forehead_integral']) {
- throw new \Exception('积分不足,抵扣失败');
- }
- $user->integral -= $integral['forehead_integral'];
- if ($user->save()) {
- $log = new AccountLog();
- $log->store_id = $order->store_id;
- $log->user_id = $user->id;
- $log->type = AccountLog::TYPE_INTEGRAL;
- $log->log_type = AccountLog::LOG_TYPE_EXPEND;
- $log->amount = $integral['forehead_integral'];
- $log->desc = "订单积分抵扣支付,订单号为:{$order->order_no}。";
- $log->before = $before;
- $log->after = $user->integral;
- $log->operator = '';
- $log->operator_id = 0;
- $log->operator_type = AccountLog::TYPE_OPERATOR_NORMAL;
- $log->created_at = time();
- $log->order_id = $order->id;
- $log->order_type = AccountLog::TYPE_PLATFORM_ORDER;
- $log->save();
- }
- }
- return [
- 'code' => 0,
- 'msg' => 'success'
- ];
- } catch (\Exception $e) {
- return [
- 'code' => 1,
- 'msg' => $e->getMessage()
- ];
- }
- }
- public function getNo($attrStr, $searchAttrIds)
- {
- $attr = json_decode($attrStr, true);
- foreach ($attr as $item) {
- $attrIds = array_column($item['attr_list'], 'attr_id');
- if ($attrIds == $searchAttrIds) {
- return $item['no'];
- }
- }
- }
- // 获得实际支付金额
- private function getPayPrice($mch)
- {
- $goods_list = $mch['goods_list'];
- $payPrice = $mch['level_price'];
- if (isset($mch['use_integral']) && $mch['use_integral']) {
- $payPrice -= $mch['integral']['forehead'];
- }
- if (isset($mch['picker_coupon'])) {
- $pickerCoupon = $mch['picker_coupon'];
- if ($pickerCoupon['sub_price'] > 0) {
- $coupon_price = 0;
- if ($pickerCoupon['appoint_type'] == 1 && $pickerCoupon['cat_id_list'] != null) {
- foreach ($goods_list as $goods) {
- foreach ($goods['cat_id'] as $v1) {
- if (in_array($v1, $pickerCoupon['cat_id_list'])) {
- $coupon_price += floatval($goods['level_price']);
- break;
- };
- };
- }
- } else if ($pickerCoupon['appoint_type'] == 2 && $pickerCoupon['goods_id_list'] != null) {
- foreach ($goods_list as $goods) {
- if (in_array($goods['goods_id'], $pickerCoupon['goods_id_list'])) {
- $coupon_price += floatval($goods['level_price']);
- };
- }
- };
- if ($pickerCoupon['sub_price'] > $coupon_price && $coupon_price > 0) {
- $payPrice -= $coupon_price;
- } else {
- $payPrice -= $pickerCoupon['sub_price'];
- }
- }
- }
- // Todo 此处有待确认算法是否正确 by Syan
- // $payPrice = $payPrice > 0 ? $payPrice : 0.01;
- if ($mch['express_price'] > 0) {
- if (isset($mch['send']) && $mch['send'] == 'express') {
- $payPrice += $mch['express_price'];
- } else {
- foreach ($goods_list as $goods) {
- if (isset($goods['send']) && $goods['send'] == 'express') {
- $payPrice += $mch['express_price'];
- break;
- }
- }
- }
- }
- if ($mch['travel_price'] > 0) {
- $payPrice += $mch['travel_price'];
- }
- if ($this->buy_level_id) {
- $level = Level::findOne($this->buy_level_id);
- $payPrice += ($level->price * 1);
- }
- return $payPrice > 0 ? $payPrice : 0;
- }
- // 检查数据
- private function checkMchData($mch)
- {
- if (empty($mch['goods_list'])) {
- return [
- 'code' => 1,
- 'msg' => '商品不存在或已删除'
- ];
- }
- $checkFormData = $this->checkFormData($mch);
- if ($checkFormData['code'] == 1) {
- return $checkFormData;
- }
- $checkSendType = $this->checkSendType($mch);
- if ($checkSendType['code'] == 1) {
- return $checkSendType;
- }
- $checkCoupon = $this->checkCoupon($mch);
- if ($checkCoupon['code'] == 1) {
- return $checkCoupon;
- }
- $checkGoods = $this->checkGoods($mch);
- if ($checkGoods['code'] == 1) {
- return $checkGoods;
- }
- $checkStbzOrder = $this->checkCloudOrder($mch);
- if ($checkStbzOrder['code'] == 1) {
- return $checkStbzOrder;
- }
- $checkMdFrontBind = $this->checkMdFrontBind($mch);
- if ($checkMdFrontBind['code'] == 1) {
- return $checkMdFrontBind;
- }
- return ['code' => 0, 'msg' => 'success'];
- }
- public function checkCloudOrder($mch)
- {
- try {
- $address = (object)($this->address);
- //胜天半子订单预下单
- $spu = [];
- foreach ($mch['goods_list'] as $arr) {
- if ((int)$arr['cloud_goods_id'] > 0) {
- $goods = Goods::findOne($arr['goods_id']);
- $cloud_url = "/goods/getGoodsInfo";
- $cloud_data = [];
- $cloud_data['goods_id'] = $arr['cloud_goods_id'];
- $domain = (new OptionSetting)->getCloudDomainName();
- $cloud_info = cloud_post($domain . $cloud_url, $cloud_data);
- $cloud_info = json_decode($cloud_info, true);
- if($cloud_info['code'] != 0){
- return $cloud_info;
- }else{
- $cloud_goods = $cloud_info['data']['goods'];
- //获取云仓产品
- if (intval($cloud_goods['stbz_goods_id']) !== 0) {
- $attr_list = $arr['attr_list'];
- $attr_id = array_column($attr_list, 'attr_id');
- sort($attr_id);
- $attr = json_decode($goods->attr, true);
- foreach ($attr as $item) {
- $attr_id_ = array_column($item['attr_list'], 'attr_id');
- sort($attr_id_);
- if (!array_diff($attr_id_, $attr_id)) {
- $spu[] = [
- 'number' => $arr['num'],
- 'sku' => $item['no'],
- ];
- }
- }
- } else {
- //检测其他类型商品
- if (in_array($cloud_goods['send_type'], [5, 6])) {
- //获取商城供货商
- $supplier = Supplier::findOne(['cloud_supplier_id' => $cloud_goods['supplier_id'], 'is_delete' => 0]);
- $supplierAgentFrontBind = AgentFrontBind::find()->where([
- 'is_delete' => 0,
- 'status' => 1,
- 'type' => AgentFrontBind::TYPE_SUPPLIER,
- 'type_id' => $supplier->id
- ])->select('front_agent_admin_id')->column();
- $md_id = get_md_id();
- if ($md_id <= 0 || $mch['send'] == 'express') {
- $mdAgentFrontBind = AgentFrontBind::find()->where([
- 'type' => AgentFrontBind::TYPE_STORE,
- 'type_id' => get_store_id(),
- 'is_delete' => 0,
- 'status' => 1,
- 'front_agent_admin_id' => $supplierAgentFrontBind,
- 'is_cloud_delivery' => AgentFrontBind::IS_CLOUD_DELIVERY_TRUE
- ])->select('md_id, front_agent_admin_id')
- ->orderBy('md_id ASC')->asArray()->one();
- if (!$mdAgentFrontBind) {
- $mdAgentFrontBind = AgentFrontBind::find()->where([
- 'type' => AgentFrontBind::TYPE_STORE,
- 'type_id' => get_store_id(),
- 'is_delete' => 0,
- 'status' => 1,
- 'front_agent_admin_id' => $supplierAgentFrontBind
- ])->select('md_id, front_agent_admin_id')
- ->orderBy('md_id ASC')->asArray()->one();
- }
- } else {
- $mdAgentFrontBind = AgentFrontBind::find()->where([
- 'md_id' => $md_id,
- 'is_delete' => 0,
- 'status' => 1,
- 'front_agent_admin_id' => $supplierAgentFrontBind
- ])->select('md_id, front_agent_admin_id')
- ->orderBy('md_id ASC')->asArray()->one();
- }
- if (!$mdAgentFrontBind) {
- return ['code' => 1, 'msg' => '云仓商品类型绑定参数错误 请联系客服进行处理'];
- }
- $erpInventoryArray = AgentFrontErpInventory::find()->where(['goods_id' => $arr['cloud_goods_id'], 'front_agent_admin_id' => $mdAgentFrontBind['front_agent_admin_id']])
- ->asArray()->one();
- if (empty($erpInventoryArray)) {
- return ['code' => 1, 'msg' => '云仓商品绑定参数错误 请联系客服进行处理'];
- }
- }
- }
- }
- }
- }
- //胜天半子下单前检测
- if ($spu) {
- $params = [
- 'spu' => $spu,
- 'address' => [
- 'consignee' => $address->name,
- 'phone' => $address->mobile,
- 'province' => trim($address->province),
- 'city' => trim($address->city),
- 'area' => trim($address->district),
- 'street' => '',
- 'description' => trim($address->detail),
- ]
- ];
- debug_log('胜天半子商品信息' . json_encode($params));
- $checkData = \stbz_client()->getApiResponse('post', '/v2/order/beforeCheck', $params);
- $checkData = \json_decode($checkData, true);
- debug_log('胜天半子下单检测' . json_encode($checkData));
- if ($checkData['code'] != 1) {
- throw new \Exception($checkData['msg']);
- }
- }
- return [
- 'code' => 0,
- 'msg' => '下单检测成功'
- ];
- } catch (\Exception $e) {
- return [
- 'code' => 1,
- 'msg' => $e->getMessage()
- ];
- }
- }
- //如果下单的产品的供货商绑定的仓库和门店是否绑定
- private function checkMdFrontBind($mch)
- {
- $md_id = get_md_id();
- return OrderTransit::checkMdFrontBind($mch, $md_id);
- }
- // 检测优惠券是否可使用
- private function checkCoupon($mch)
- {
- if (empty($mch['picker_coupon'])) {
- return [
- 'code' => 0,
- 'msg' => ''
- ];
- }
- $ok = false;
- foreach ($mch['coupon_list'] as $item) {
- if ($item['user_coupon_id'] == $mch['picker_coupon']['user_coupon_id']) {
- $ok = true;
- }
- }
- if (!$ok) {
- return [
- 'code' => 1,
- 'msg' => '该优惠券已过期'
- ];
- } else {
- return [
- 'code' => 0,
- 'msg' => ''
- ];
- }
- }
- // 检测发货方式
- private function checkSendType($mch)
- {
- if ($mch['mch_id'] == 0) {
- if (isset($mch['is_offline']) && $mch['is_offline'] == 1) {
- if (isset($mch['shop']) == false) {
- return [
- 'code' => 1,
- 'msg' => '请选择自提门店'
- ];
- }
- if (!(isset($mch['offline_name']) && $mch['offline_name']) || !(isset($mch['offline_mobile']) && $mch['offline_mobile'])) {
- return [
- 'code' => 1,
- 'msg' => '请输入自提信息'
- ];
- }
- if (!preg_match("/^1\d{10}$/", $mch['offline_mobile'])) {
- return [
- 'code' => 1,
- 'msg' => '请输入正确的手机号'
- ];
- }
- } else {
- if (!$this->address) {
- return [
- 'coe' => 1,
- 'msg' => '收货地址不存在'
- ];
- }
- if ($mch['offer_rule'] && $mch['offer_rule']['is_allowed'] == 1 && $mch['send'] != 'delivery') {
- return [
- 'code' => 1,
- 'msg' => $mch['offer_rule']['msg']
- ];
- }
- if ($mch['is_area'] == 1 && $mch['send'] == 'express') {
- return [
- 'code' => 1,
- 'msg' => '所选地区自营商品暂时无货'
- ];
- }
- }
- } else {
- if (!$this->address) {
- return [
- 'coe' => 1,
- 'msg' => '收货地址不存在'
- ];
- }
- }
- return ['code' => 0, 'msg' => ''];
- }
- // 检测自定义表单
- private function checkFormData($mch)
- {
- foreach ($mch['goods_list'] as $goods) {
- if (isset($goods['form']['code'])) {
- return $goods['form'];
- }
- if (!isset($goods['form'])) {
- continue;
- }
- $form = $goods['form'];
- if ($form['is_form'] == 1) {
- $form_list = $form['list'];
- foreach ($form_list as $index => $value) {
- if ($value['required'] == 1) {
- if (in_array($value['type'], ['radio', 'checkbox'])) {
- $is_true = false;
- foreach ($value['default_list'] as $k => $v) {
- if ($v['checked'] == true) {
- $is_true = true;
- }
- }
- if (!$is_true) {
- return [
- 'code' => 1,
- 'msg' => '请填写' . $form['name'] . ',加“*”为必填项',
- 'name' => $value['name']
- ];
- }
- } else {
- if (empty($value['default']) && strlen($value['default']) == 0) {
- return [
- 'code' => 1,
- 'msg' => '请填写' . $form['name'] . ',加“*”为必填项',
- 'name' => $value['name']
- ];
- }
- }
- }
- }
- }
- }
- return [
- 'code' => 0,
- 'msg' => ''
- ];
- }
- // 检测商品相关
- private function checkGoods($mch)
- {
- \Yii::warning($mch);
- foreach ($mch['goods_list'] as $goods) {
- $attr_id_list = [];
- foreach ($goods['attr_list'] as $item) {
- array_push($attr_id_list, $item['attr_id']);
- }
- $_goods = Goods::find()->where('id = ' . $goods['goods_id'] . ' for update')->one();
- if($_goods->product_type == Goods::GOODS_TYPE_WORKER){
- return [
- 'code' => 0
- ];
- }
- if (get_md_id() && empty(input_params('flag_id'))) {
- $md = Md::findOne(get_md_id());
- if ($md->is_single) {
- $md_goods = MdGoods::findOne(['goods_id' => $_goods->id, 'md_id' => get_md_id()]);
- if (!$md_goods) {
- return [
- 'code' => 1,
- 'msg' => '订单提交失败,商品“' . $_goods->name . '”在当前门店无售卖权限',
- ];
- }
- }
- }
- //2砍价商品6当面付
- if ($_goods->type != 2 && $_goods->type != 6 && $_goods->product_type == Goods::GOODS_TYPE_NORMAL || $_goods->product_type == Goods::GOODS_TYPE_ADOPT) {
- if (!$_goods->numSub($attr_id_list, $goods['num'])) {
- return [
- 'code' => 1,
- 'msg' => '订单提交失败,商品“' . $_goods->name . '”库存不足',
- 'attr_id_list' => $attr_id_list,
- 'attr_list' => $goods['attr_list'],
- ];
- }
- }
- if($_goods->product_type == Goods::GOODS_TYPE_DATE){
- $num = Goods::getGoodsNum($_goods)['data'];
- $attr = $goods['book'];
- foreach ($attr as $iattr) {
- $idate = $iattr['date'];
- foreach ($num as $inum) {
- $indate = $inum['date'];
- if(($idate == $indate) && ($inum['num'] < $goods['num'])){
- return ['code' => 1, 'msg' => $idate.'库存不足'];
- }
- }
- }
- }
- //加价保护start
- $riskResult = Goods::getRiskStatus($goods['goods_id']);
- if (!$riskResult) {
- return ['code' => 1,'msg' => '商品状态异常 请尝试重新下单'];
- }
- $form = new MerchantForm();
- $is_install = $form->goodsIsInstall($goods['goods_id']);
- if ($is_install !== 2) {
- $store = Store::findOne(get_store_id());
- $store_address = [
- 'province_id' => $store->province_id,
- 'city_id' => $store->city_id,
- 'district_id' => $store->district_id,
- ];
- if ($is_install !== 1) {
- $md_id = get_md_id();
- $md = Md::findOne($md_id);
- $store_address = [
- 'province_id' => $md->province,
- 'city_id' => $md->city,
- 'district_id' => $md->district,
- ];
- }
- $address = $is_install === 1 ? $this->address : $store_address;
- $result = $this->goodsIsGoodsAgent($address, $goods['goods_id']);
- if ($result['code'] !== 0) {
- return $result;
- }
- }
- }
- return ['code' => 0, 'msg' => ''];
- }
- public function getOrderNo()
- {
- $order_no = null;
- while (true) {
- $order_no = date('YmdHis') . mt_rand(100000, 999999);
- $exist_order_no = Order::find()->where(['order_no' => $order_no])->exists();
- if (!$exist_order_no) {
- break;
- }
- }
- return $order_no;
- }
- // 优惠券可优惠的商品总额计算
- private function pickerGoods(&$mch)
- {
- $totalPrice = 0;
- $pickerCoupon = $mch['picker_coupon'];
- if (empty($pickerCoupon)) {
- return;
- }
- foreach ($mch['goods_list'] as $item) {
- if ($pickerCoupon['appoint_type'] == 1) {
- if (!empty($pickerCoupon['cat_id_list'])) {
- $catIdList = $pickerCoupon['cat_id_list'];
- if (array_intersect($item['cat_id'], $catIdList)) {
- $totalPrice += $item['price'];
- $mch['picker_coupon']['goods_id'][] = $item['goods_id'];
- }
- } else {
- $totalPrice += $item['price'];
- $mch['picker_coupon']['goods_id'][] = $item['goods_id'];
- }
- } else if ($pickerCoupon['appoint_type'] == 2) {
- if (!empty($pickerCoupon['goods_id_list'])) {
- $goodsIdList = $pickerCoupon['goods_id_list'];
- if (in_array($item['goods_id'], $goodsIdList)) {
- $totalPrice += $item['price'];
- $mch['picker_coupon']['goods_id'][] = $item['goods_id'];
- }
- } else {
- $totalPrice += $item['price'];
- $mch['picker_coupon']['goods_id'][] = $item['goods_id'];
- }
- } else {
- $totalPrice += $item['price'];
- $mch['picker_coupon']['goods_id'][] = $item['goods_id'];
- }
- }
- $mch['picker_coupon']['total_price'] = $totalPrice;
- }
- /**
- * @param $mch
- * @param $order Order
- * @return array
- */
- private function insertData($mch, $order)
- {
- // 计算商品相关
- $goods_list = $mch['goods_list'];
- $goodsPrice = 0;
- // 计算商品分润
- $goods_profit = 0;
- $chain_goods_profit = 0;
- $chainGoodsList = [];
- foreach ($goods_list as $goods) {
- $i++ || MochatForm::sendMsg(1, get_store_id(), MochatForm::MSG_TYPE_SUBMIT_ORDER, get_saas_user_id(), ['goods_id' => $goods['id']]);
- if ($goods['product_type'] == Goods::GOODS_TYPE_ADOPT) {
- $adopt_order_info = new AdoptOrderInfo();
- $adopt_order_info->name = $this->adopt_name;
- $adopt_order_info->mobile = $this->adopt_mobile;
- $adopt_order_info->order_id = $order->id;
- $adopt_order_info->store_id = $this->store_id;
- $adopt_goods = AdoptGoods::find()->where(['goods_id' => $goods['id']])->one();
- $adopt_order_info->mature_time = time() + $adopt_goods->growth_cycle * 86400;
- if (!$adopt_order_info->save()) {
- return [
- 'code' => 1,
- 'msg' => '订单提交失败,请稍后再重试',
- 'error' => $adopt_order_info->errors
- ];
- }
- }
- // 存入下单表单
- if ($goods['form'] && $goods['form']['is_form'] == 1) {
- foreach ($goods['form']['list'] as $index => $value) {
- $order_form = new \app\models\OrderForm();
- $order_form->store_id = $this->store_id;
- $order_form->order_id = $order->id;
- $order_form->goods_id = $goods['id'];
- $order_form->key = $value['name'];
- $order_form->value = $value['default'];
- $order_form->type = $value['type'];
- $order_form->is_delete = 0;
- $order_form->save();
- }
- }
- // 删除购物车
- if (isset($goods['cart_id'])) {
- Cart::updateAll(['is_delete' => 1], ['id' => $goods['cart_id']]);
- }
- Goods::updateAll(['updated_at' => time()], ['id' => $goods['goods_id']]);
- $order_detail = new OrderDetail();
- $order_detail->order_id = $order->id;
- $order_detail->goods_id = $goods['goods_id'];
- $order_detail->num = $goods['num'];
- if (isset($goods['cost_price'])) {
- $order_detail->cost_price = $goods['cost_price'];
- }
- // if ($goods['is_level'] && $goods['is_level'] == 1) {
- // $order_detail->is_level = (int)$goods['is_level'];
- // } else {
- $order_detail->is_level = 1;
- // }
- if ($this->buy_level_id) {
- $payPrice = $goods['next_level_price'];
- } else {
- $payPrice = $goods['level_price'];
- if ($goods['payment_type']) {
- $order_detail->pre_price = $goods['pre_price'];
- }
- }
- //使用优惠券
- if (isset($mch['picker_coupon']) && $mch['picker_coupon'] && !empty($mch['picker_coupon'])) {
- if (is_string($mch['picker_coupon']['goods_id_list'])) {
- $mch['picker_coupon']['goods_id_list'] = json_decode($mch['picker_coupon']['goods_id_list'], true);
- }
- // 这里要考虑优惠券不设置指定商品或者指定商品分类的情况
- // 三种情况 1.优惠券未指定商品分类 同时 也没有指定商品
- // 2.优惠券指定了商品分类 且 商品所属分类在指定的分类中
- // 3.优惠券指定了商品 且购买商品在指定商品中
- if(((empty($mch['picker_coupon']['goods_id_list']) && empty($mch['picker_coupon']['cat_id_list'])) || (!empty($mch['picker_coupon']['goods_id_list']) && in_array($goods['goods_id'], $mch['picker_coupon']['goods_id_list'])) || (!empty($mch['picker_coupon']['cat_id_list'] && array_intersect($goods['cat_id'], $mch['picker_coupon']['cat_id_list'])))) && $mch['picker_coupon']['total_price'] > 0){
- $pickerCouponSubPrice = doubleval($mch['picker_coupon']['sub_price'] * doubleval($goods['price']) / $mch['picker_coupon']['total_price']);
- $payPrice -= $pickerCouponSubPrice;
- }
- // 删除优惠券
- UserCoupon::updateAll(['is_use' => 1], ['id' => $mch['picker_coupon']['user_coupon_id']]);
- }
- //使用积分
- if (isset($mch['use_integral']) && $mch['use_integral']) {
- if ($goods['resIntegral'] && $goods['resIntegral']['forehead'] > 0) {
- $payPrice -= $goods['resIntegral']['forehead'];
- }
- }
- //使用联盟券抵扣
- if ($goods['take_price'] > 0) {
- $payPrice -= $goods['take_price'];
- }
- //使用余额抵扣
- if ($goods['balance'] > 0) {
- $payPrice -= $goods['balance'];
- }
- //随机立减
- if ($goods['rand_discount_price'] > 0) {
- $payPrice -= $goods['rand_discount_price'];
- }
- //增值积分
- if ($goods['integral_appreciation_price'] > 0) {
- if ($payPrice > $goods['integral_appreciation_price']) {
- $payPrice -= $goods['integral_appreciation_price'];
- } else {
- $goods['integral_appreciation_price'] = $payPrice;
- $payPrice = 0;
- }
- }
- $payPrice = $payPrice >= 0 ? sprintf('%.2f', $payPrice) : 0;
- $goodsPrice += $payPrice;
- $orderPrice = floatval($order->pay_price) - floatval($order->express_price);
- if ($goodsPrice > $orderPrice) {
- $payPrice = $payPrice - ($goodsPrice - $orderPrice);
- $goodsPrice = $orderPrice;
- }
- $payPrice = $this->getBookPrice($payPrice, $goods_list);
- // $order_detail->supplier_price = $goods['supplier_price'];
- if ($goods['payment_type']) {
- $payPrice = $goods['level_price'];
- }
- $order_detail->total_price = $payPrice;
- $order_detail->integral_appreciation_price = $goods['integral_appreciation_price'] ?: '0.00';
- $order_detail->integral_appreciation_amount = $goods['integral_appreciation_amount'] ?: '0.00';
- // 计算单个商品可分红金额
- $profit = $goods['rate_type'] == 0 ? floatval($payPrice * $goods['rate'] / 100) : floatval($goods['rate']) * $goods['num'];
- $goods_profit += $profit;
- $order_detail->profit = $profit;
- // 链动
- $chain_profit = $goods['chain_rate_type'] == 0 ? floatval($payPrice * $goods['chain_rate'] / 100) : floatval($goods['chain_rate']) * $goods['num'];
- $chain_goods_profit += $chain_profit;
- $order_detail->chain_profit = $chain_profit;
- $order_detail->is_delete = 0;
- $chainGoodsList[] = [
- 'id' => $goods['id'],
- 'num' => $goods['num'],
- 'pay_price' => $payPrice,
- ];
- $shareHolderRepeatProfitSwitch = (int)Option::get('shareHolderRepeatProfitSwitch', $order->store_id, 'bonus_pool', 0)['value'];
- //判断是否是升级产品
- $open = false;
- $shareHolderLevelList = ShareHolderLevel::find()->where(['store_id' => $order->store_id, 'status' => 1, 'is_delete' => 0])->select('condition, id, level, member_level')->asArray()->all();
- foreach ($shareHolderLevelList as $item) {
- $condition = json_decode($item['condition'], true);
- if ((int)$condition['goods']['is_open'] === 1 && !empty($condition['goods']['value']['id']) && in_array($goods['id'], $condition['goods']['value']['id'])) {
- $open = true;
- break;
- }
- }
- //如果是分红产品或者是升级产品则添加记录
- if (floatval(sprintf("%.2f", ($profit / $goods['num']))) > 0 || $open) {
- if ($shareHolderRepeatProfitSwitch) {
- $profitGoodsLog = new ShareHolderProfitGoodsLog();
- $profitGoodsLog->user_id = get_user_id();
- $profitGoodsLog->goods_id = $goods['id'];
- $profitGoodsLog->order_id = $order->id;
- $profitGoodsLog->goods_price = floatval(sprintf("%.2f", ($payPrice / $goods['num'])));
- $profitGoodsLog->goods_profit = floatval(sprintf("%.2f", ($profit / $goods['num'])));
- $profitGoodsLog->is_switch = intval($shareHolderRepeatProfitSwitch);
- if (!$profitGoodsLog->save()) {
- return [
- 'code' => 1,
- 'msg' => implode(';', array_values($profitGoodsLog->firstErrors))
- ];
- };
- // }
- }
- }
- //
- if ($goods['product_type'] == 1) {
- $order_detail->attr = json_encode($goods['book'], JSON_UNESCAPED_UNICODE);
- } elseif ($goods['product_type'] == 2) {
- //$order_detail->attr = json_encode($goods['service'], JSON_UNESCAPED_UNICODE);
- $service = $goods['service'];
- $time = explode('-', $service['time']);
- $order_detail->attr = json_encode([
- 'start_date' => $service['date'] . ' ' . $time[0],
- 'end_date' => $service['date'] . ' ' . $time[1],
- 'time' => $service['time'],
- 'date' => $service['date'],
- 'price' => $service['price'],
- ], JSON_UNESCAPED_UNICODE);
- } else {
- $order_detail->attr = json_encode($goods['attr_list'], JSON_UNESCAPED_UNICODE);
- $order_detail->food_ext_goods = json_encode($goods['food_ext_goods'], JSON_UNESCAPED_UNICODE);
- }
- $goods_info = Goods::findOne($goods['goods_id']);
- $order_detail->pic = $goods['goods_pic'] ? $goods['goods_pic'] : $goods_info->cover_pic;
- $order_detail->goods_name = $goods_info ? $goods_info->name : $goods['goods_name'];
- if (!empty($goods_info)) {
- //在添加下单商品信息时增加链动等级记录 为了实现小推大功能
- $goods_info = $goods_info->toArray();
- $goods_info['goods_chain_level'] = GoodsChainLevel::find()->where(['goods_id' => $goods_info['id']])->asArray()->one();
- }
- $order_detail->goods_info = $goods_info ? Json::encode($goods_info) : Json::encode([]);
- $order_detail->delivery_type = $mch['send'] == 'express' ? OrderDetail::GOODS_DELIVERY_EXPRESS : ($mch['send'] == 'delivery' ? OrderDetail::GOODS_DELIVERY_IM : OrderDetail::GOODS_DELIVERY_SHOP);
- if ($mch['send'] == 'shop' && empty(input_params('flag_id'))) {
- if(isset($goods['shop_id']) && $goods['shop_id'] > 0){
- $order_detail->shop_id = $goods['shop_id'];
- }else{
- $order_detail->shop_id = 0;
- }
- }
- if ($goods['give'] > 0) {
- $order_detail->integral = $goods['give'];
- } else {
- $order_detail->integral = 0;
- }
- $attr_id_list = [];
- foreach ($goods['attr_list'] as $item) {
- array_push($attr_id_list, $item['attr_id']);
- }
- $order_detail->batch_price_tips = $goods['current_batch_price_tips'];
- // 存入点餐的user_id
- if (!empty($goods['user_id'])) {
- $order_detail->user_id = $goods['user_id'];
- }
- // 积分兑换商品 1次只能兑换1个
- if ($order->order_type == 7){
- $order_detail->total_price = $order->total_price;
- $order_detail->integral_price = $order->integral_price;
- $order_detail->integral_difference_price = $order->integral_difference_price;
- }
- //增值积分下单扣减用户积分
- $integralAppreciationGoods = IntegralAppreciationGoods::findOne(['goods_id' => $goods['id'], 'is_delete' => 0]);
- if ($integralAppreciationGoods && $integralAppreciationGoods->integral_amount > 0) {
- $integral_appreciation_setting = Option::get('integral_appreciation_setting', $order->store_id, 'integral_appreciation')['value'];
- $integral_appreciation_setting = json_decode($integral_appreciation_setting ?? '', true);
- $integral_custom_name = $integral_appreciation_setting['integral_custom_name'] ?: '增值积分';
- $integralAppreciationUser = IntegralAppreciationUser::findOne(['user_id' => $this->user_id]);
- if (!$integralAppreciationUser) {
- return [
- 'code' => 1,
- 'msg' => "用户{$integral_custom_name}数量不足"
- ];
- }
- $integral_amount = bcmul($integralAppreciationGoods->integral_amount, $goods['num'], 2);
- if ($integral_amount > $integralAppreciationUser->integral) {
- return [
- 'code' => 1,
- 'msg' => "用户{$integral_custom_name}数量不足"
- ];
- }
- $integralAppreciationUser->integral = bcsub($integralAppreciationUser->integral, $integral_amount, 2);
- $integralAppreciationUser->save();
- $result = IntegralAppreciationUserIntegralLog::saveIntegralLog(
- $integralAppreciationUser->id,
- $integral_amount,
- IntegralAppreciationUserIntegralLog::TYPE_EXPEND,
- IntegralAppreciationUserIntegralLog::SOURCE_TYPE_BUY_GOODS, "购买商品 订单号{$order->order_no}",
- $order->id);
- if ($result['code']) {
- return $result;
- }
- }
- if (!$order_detail->save()) {
- return [
- 'code' => 1,
- 'msg' => '订单提交失败,请稍后再重试',
- 'error' => $order_detail->errors[0]
- ];
- }
- if ($this->is_seckill) {
- $seckill_activity_goods = SeckillActivityGoods::find()->alias('sag')->where(['sag.goods_id' => $goods['goods_id']])
- ->leftJoin(['sg' => SeckillActivity::tableName()], 'sg.id = sag.activity_id')
- ->andWhere(['AND', ['>', 'sg.end_time', time()], ['<', 'sg.start_time', time()], ['sg.is_delete' => 0, 'sag.is_delete' => 0, 'sg.store_id' => get_store_id()]])
- ->select('sag.id sag_id, sg.id, sg.end_time, sag.attr, sag.use_attr, sag.seckill_num, sag.seckill_price, sag.sale_num, sg.order_limit_num, sg.self_limit_num')->asArray()->one();
- if ($seckill_activity_goods) {
- $activity_order_log = new SeckillActivityOrderLog();
- $activity_order_log->order_id = $order->id;
- $activity_order_log->order_detail_id = $order_detail->id;
- $activity_order_log->user_id = get_user_id();
- $activity_order_log->sale_price = $goods['level_price'];
- $activity_order_log->activity_id = $seckill_activity_goods['id'];
- $activity_order_log->activity_goods_id = $seckill_activity_goods['sag_id'];
- $activity_order_log->goods_id = $goods['goods_id'];
- $activity_order_log->num = $goods['num'];
- $activity_order_log->store_id = get_store_id();
- if (!$activity_order_log->save()) {
- debug_log("秒杀信息保存" . json_encode($activity_order_log->errors));
- }
- $order->seckill_order_id = $activity_order_log->id;
- }
- }
- if (!empty($goods['videoId'])) {
- //获取抖品信息
- $video_goods = VideoGoodsList::findOne($goods['videoId']);
- //获取抖品配置信息
- $setting = VideoGoodsSetting::findOne(['store_id' => get_store_id()]);
- //获取商品配置信息
- $goods_info = Goods::findOne($goods['goods_id']);
- $profit = ($setting->profit / 100);
- if ($profit > 0 && $video_goods && $goods_info) {
- $video_share = new VideoGoodsShare();
- $video_share->order_id = $order->id;
- $video_share->goods_id = $goods['goods_id'];
- $video_share->num = $goods['num'];
- $video_share->order_detail = $order_detail->id;
- $video_share->video_goods_id = $goods['videoId'];
- $video_share->store_id = get_store_id();
- $video_share->author_user_id = $video_goods->user_id;
- $video_share->created_at = time();
- $video_share->profit = $setting->profit;
- $video_share->proportion = ($goods['level_price'] * $profit);
- if (!$video_share->save()) {
- return [
- 'code' => 1,
- 'msg' => implode(';', array_values($video_share->firstErrors))
- ];
- }
- }
- }
- }
- if ($this->buy_level_id) {
- $level = Level::findOne($this->buy_level_id);
- $orderLevel = new LevelOrder();
- $orderLevel->store_id = get_store_id();
- $orderLevel->user_id = get_user_id();
- $orderLevel->current_level = get_user()->level;
- $orderLevel->after_level = $level->level;
- $orderLevel->order_no = OrderNo::getOrderNo(OrderNo::ORDER_LEVEL);
- $orderLevel->is_pay = 0;
- $orderLevel->is_delete = 0;
- $orderLevel->created_at = time();
- $orderLevel->pay_price = $level->price;
- if ($orderLevel->save()) {
- $order->level_order_id = $orderLevel->id;
- }
- }
- // goods_profit 计算之后存入订单表中
- $order->profit = $goods_profit;
- $order->chain_profit = $chain_goods_profit;
- $orderChainLevelProfit = \app\utils\Share\BonusPool::getOrderLevelProfit(get_store_id(), $chainGoodsList);
- $order->chain_level_value = json_encode($orderChainLevelProfit);
- $order->save();
- // 计算门店收益
- if (get_md_id() > 0 && !in_array($order->order_type, [1, 2])) {
- $result = OrderForm::findPrice($order->id);
- MdProfit::handleProfit($order->id, $result['original_price'], $result['md_price'], $order->md_id);
- }else{
- if ($order->is_offline || in_array($order->order_type, [1, 2])) {
- MdProfit::handleProfit($order->id, $order->total_price, $order->total_price, $order->md_id);
- }
- }
- if (!empty($this->worker)) {
- $order_ext = WorkerOrderExt::findOne(['order_id' => $order->id]);
- $order_ext->worker_id = $this->worker['id'];
- if (!empty($this->travel)) {
- $order_ext->dis = $this->travel['distance'];
- }
- $order_ext->save();
- }
-
- $order->afterOtherDataSave();
- return [
- 'code' => 0,
- 'msg' => ''
- ];
- }
- public function getBookPrice($payPrice, $mch_goods)
- {
- $price = $payPrice;
- foreach ($mch_goods as $goods) {
- if ($goods['product_type'] == 1) {
- $price = 0;
- $goods_id = $goods['goods_id'];
- $goodsInfoObj = Goods::findOne($goods_id);
- if ($goodsInfoObj) {
- $service_book_desc = json_decode($goodsInfoObj->service_book_desc ?: '', true);
- }
- if (!empty($service_book_desc)) {
- if (empty($goods['book'])) {
- return [
- 'code' => 1,
- 'msg' => '预约日期数据为空'
- ];
- }
- foreach ($goods['book'] as $value) {
- $book_date = strtotime($value['date']);
- foreach ($service_book_desc as $service_book_item) {
- $service_book_date = strtotime($service_book_item['date']);
- if ($book_date === $service_book_date) {
- $price += $service_book_item['price'];
- }
- }
- }
- $price = $price * $goods['num'];
- }
- }
- if ($goods['product_type'] == 2) {
- $price = 0;
- $goods_book = GoodsBook::findOne(['goods_id' => $goods['id']]);
- $service_book = Json::decode($goods_book->service_book);
- //$service_book = $service_book['data'];
- $date_data = $this->getDateByInterval(7);
- $new_arr = [
- 'data' => []
- ];
- foreach ($date_data as $index => $datum) {
- $new_arr['data'][$index]['date'] = $datum;
- $new_arr['data'][$index]['time'] = $service_book['data'][0]['time'];
- }
- if (!$new_arr) {
- return [
- 'code' => 1,
- 'msg' => '数据异常'
- ];
- }
- $price = 0;
- $service_book = $new_arr['data'];
- $service_book_date = array_column($service_book, NULL, 'date');
- $service_book_time = $service_book_date[$goods['service']['date']]['time'];
- foreach ($service_book_time as $m) {
- foreach ($m['times'] as $n) {
- if ($n['time'] == $goods['service']['time']) {
- $price = $goods['service']['price'] * $goods['num'];
- break;
- }
- }
- if ($price > 0) {
- break;
- }
- }
- }
- }
- \Yii::error($price);
- return $price;
- }
- /**
- * 检查当前时间是否为指定时间范围内
- * @param $begin 20:00:00
- * @param $end 08:00:00
- * @param $date
- * @return bool true 时间范围内
- */
- private function checkTimeBeginEnd ($begin, $end, $date = null)
- {
- if (empty($begin) && empty($end)) {
- return true;//
- }
- $date = is_null ($date) ? date ('H:i:s') : $date;
- $curTime = strtotime ($date); // 当前时分
- $assignTime1 = strtotime ($begin); // 获得指定分钟时间戳,00:00
- $assignTime2 = strtotime ($end); // 获得指定分钟时间戳,01:00
- $result = false;
- if ($assignTime1 > $assignTime2) {
- //跨24点
- if ($curTime > $assignTime1 || $curTime < $assignTime2) {
- $result = true;
- }
- }
- if ($curTime > $assignTime1 && $curTime < $assignTime2) {
- $result = true;
- }
- if ($assignTime1 == $assignTime2) {
- $result = true;
- }
- return $result;
- }
-
- public function giftsReceivedAddr($param) {
- $orderId = $param['order_id'];
- try{
- $order = Order::findOne($orderId);
- if(GivingGiftsForm::isReceivedTimeout($order) > 0){
- throw new \Exception('超出礼物领取时效');
- }
- if($order->giving_gifts_received_user_id > 0){
- throw new \Exception('礼物已领取');
- }
- $order->giving_gifts_received_user_id = $this->user_id;
- $address = (object)($this->getAddressData());
- $order->address = $address->province . $address->city . $address->district . $address->town . $address->village . $address->detail;
- $order->mobile = $address->mobile ?: get_user()->binding;
- $order->name = $address->name ?: get_user()->nickname;
- $order->province_id = $address->province_id;
- $order->city_id = $address->city_id;
- $order->district_id = $address->district_id;
- $order->town_id = $address->town_id ? : 0;
- $order->village_id = $address->village_id ? : 0;
- $order->address_data = json_encode([
- 'province' => trim($address->province),
- 'city' => trim($address->city),
- 'district' => trim($address->district),
- 'detail' => trim($address->detail),
- 'town' => $address->town_id ? trim($address->town) : '',
- 'village' => $address->village_id ? trim($address->village) : '',
- 'latitude' => $address->latitude,
- 'longitude' => $address->longitude,
- ], JSON_UNESCAPED_UNICODE);
- if (!$order->save()) {
- throw new \Exception(array_shift($order->getFirstErrors()));
- }
- } catch (\Exception $ex) {
- \Yii::error($ex);
- debug_log([__METHOD__, __LINE__, $orderId, $this->address, $ex->getMessage()], __CLASS__ . '.log');
- return [
- 'code' => 1,
- 'msg' => $ex->getMessage(),
- ];
- }
- return [
- 'code' => 0,
- 'msg' => 'ok',
- ];
- }
- }
|