StoreOrder.php 119 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172217321742175217621772178217921802181218221832184218521862187218821892190219121922193219421952196219721982199220022012202220322042205220622072208220922102211221222132214221522162217221822192220222122222223222422252226222722282229223022312232223322342235223622372238223922402241224222432244224522462247224822492250225122522253225422552256225722582259226022612262226322642265226622672268226922702271227222732274227522762277227822792280228122822283228422852286228722882289229022912292229322942295229622972298229923002301230223032304230523062307230823092310231123122313231423152316231723182319232023212322232323242325232623272328232923302331233223332334233523362337233823392340234123422343234423452346234723482349235023512352235323542355235623572358235923602361236223632364236523662367236823692370237123722373237423752376237723782379238023812382238323842385238623872388238923902391239223932394239523962397239823992400240124022403240424052406240724082409241024112412241324142415241624172418241924202421242224232424242524262427242824292430243124322433243424352436243724382439244024412442244324442445244624472448244924502451245224532454245524562457245824592460246124622463246424652466246724682469247024712472247324742475247624772478247924802481248224832484248524862487248824892490249124922493249424952496249724982499250025012502250325042505250625072508250925102511251225132514
  1. <?php
  2. /**
  3. *
  4. * @author: xaboy<365615158@qq.com>
  5. * @day: 2017/12/20
  6. */
  7. namespace app\models\store;
  8. use app\admin\model\system\ShippingTemplatesFree;
  9. use app\admin\model\system\ShippingTemplatesRegion;
  10. use app\models\system\SystemCity;
  11. use app\models\system\SystemUserLevel;
  12. use crmeb\basic\BaseModel;
  13. use think\Exception;
  14. use think\facade\Cache;
  15. use crmeb\traits\ModelTrait;
  16. use think\facade\Db;
  17. use think\facade\Log;
  18. use app\models\system\SystemStore;
  19. use app\models\order\Line;
  20. use app\models\routine\RoutineTemplate;
  21. use app\models\user\{User, UserAddress, UserBill, UserLevel, WechatUser};
  22. use crmeb\services\{SystemConfigService, UtilService, WechatTemplateService, workerman\ChannelService};
  23. use crmeb\repositories\{
  24. GoodsRepository, PaymentRepositories, OrderRepository, ShortLetterRepositories, UserRepository
  25. };
  26. use app\admin\model\system\ShippingTemplates;
  27. use crmeb\utils\Pink as PinkJob;
  28. use crmeb\utils\Auto as AutoJob;
  29. /**
  30. * TODO 订单Model
  31. * Class StoreOrder
  32. * @package app\models\store
  33. */
  34. class StoreOrder extends BaseModel
  35. {
  36. /**
  37. * 数据表主键
  38. * @var string
  39. */
  40. protected $pk = 'id';
  41. /**
  42. * 模型名称
  43. * @var string
  44. */
  45. protected $name = 'store_order';
  46. use ModelTrait;
  47. protected $insert = ['add_time'];
  48. protected static $payType = ['weixin' => '微信支付', 'yue' => '余额支付', 'offline' => '线下支付', 'integral' => '积分支付', 'wdc' => 'wdc支付'];
  49. protected static $deliveryType = ['send' => '商家配送', 'express' => '快递配送'];
  50. protected function setAddTimeAttr()
  51. {
  52. return time();
  53. }
  54. protected function setCartIdAttr($value)
  55. {
  56. return is_array($value) ? json_encode($value) : $value;
  57. }
  58. protected function getCartIdAttr($value)
  59. {
  60. return json_decode($value, true);
  61. }
  62. /**获取订单组信息
  63. * @param $cartInfo
  64. * @return array
  65. */
  66. public static function getOrderPriceGroup($cartInfo, $addr)
  67. {
  68. $storeFreePostage = floatval(sys_config('store_free_postage')) ?: 0;//满额包邮
  69. $totalPrice = self::getOrderSumPrice($cartInfo, 'truePrice');//获取订单总金额
  70. $costPrice = self::getOrderSumPrice($cartInfo, 'costPrice');//获取订单成本价
  71. $vipPrice = self::getOrderSumPrice($cartInfo, 'vip_truePrice');//获取订单会员优惠金额
  72. //如果满额包邮等于0
  73. if (!$storeFreePostage) {
  74. $storePostage = 0;
  75. } else {
  76. if ($addr) {
  77. $city_id = SystemCity::where('name', $addr['city'])->value('city_id');
  78. //按照运费模板计算每个运费模板下商品的件数/重量/体积以及总金额 按照首重倒序排列
  79. $temp_num = [];
  80. foreach ($cartInfo as $cart) {
  81. $temp = ShippingTemplates::get($cart['productInfo']['temp_id']);
  82. if (!$temp) $temp = ShippingTemplates::get(1);
  83. if ($temp->getData('type') == 1) {
  84. $num = $cart['cart_num'];
  85. } elseif ($temp->getData('type') == 2) {
  86. $num = $cart['cart_num'] * $cart['productInfo']['attrInfo']['weight'];
  87. } else {
  88. $num = $cart['cart_num'] * $cart['productInfo']['attrInfo']['volume'];
  89. }
  90. $region = ShippingTemplatesRegion::where('temp_id', $cart['productInfo']['temp_id'])->where('city_id', $city_id)->find();
  91. if (!$region) $region = ShippingTemplatesRegion::where('temp_id', $cart['productInfo']['temp_id'])->where('city_id', 0)->find();
  92. if (!$region) $region = ShippingTemplatesRegion::where('temp_id', 1)->where('city_id', 0)->find();
  93. if (!$region) {
  94. return self::setErrorInfo('运费模板不存在');
  95. }
  96. if (!isset($temp_num[$cart['productInfo']['temp_id']])) {
  97. $temp_num[$cart['productInfo']['temp_id']]['number'] = $num;
  98. $temp_num[$cart['productInfo']['temp_id']]['price'] = bcmul($cart['cart_num'], $cart['truePrice'], 2);
  99. $temp_num[$cart['productInfo']['temp_id']]['first'] = $region['first'];
  100. $temp_num[$cart['productInfo']['temp_id']]['first_price'] = $region['first_price'];
  101. $temp_num[$cart['productInfo']['temp_id']]['continue'] = $region['continue'];
  102. $temp_num[$cart['productInfo']['temp_id']]['continue_price'] = $region['continue_price'];
  103. $temp_num[$cart['productInfo']['temp_id']]['temp_id'] = $cart['productInfo']['temp_id'];
  104. $temp_num[$cart['productInfo']['temp_id']]['city_id'] = $city_id;
  105. } else {
  106. $temp_num[$cart['productInfo']['temp_id']]['number'] += $num;
  107. $temp_num[$cart['productInfo']['temp_id']]['price'] += bcmul($cart['cart_num'], $cart['truePrice'], 2);
  108. }
  109. }
  110. array_multisort(array_column($temp_num, 'first_price'), SORT_DESC, $temp_num);
  111. $type = $storePostage = 0;
  112. foreach ($temp_num as $k => $v) {
  113. if (ShippingTemplatesFree::where('temp_id', $v['temp_id'])->where('city_id', $v['city_id'])->where('number', '<=', $v['number'])->where('price', '<=', $v['price'])->find()) {
  114. unset($temp_num[$k]);
  115. }
  116. }
  117. foreach ($temp_num as $v) {
  118. if ($type == 0) {
  119. if ($v['number'] <= $v['first']) {
  120. $storePostage = bcadd($storePostage, $v['first_price'], 2);
  121. } else {
  122. if ($v['continue'] <= 0) {
  123. $storePostage = $storePostage;
  124. } else {
  125. $storePostage = bcadd(bcadd($storePostage, $v['first_price'], 2), bcmul(ceil(bcdiv(bcsub($v['number'], $v['first']), $v['continue'] ?? 0, 2)), $v['continue_price']), 2);
  126. }
  127. }
  128. $type = 1;
  129. } else {
  130. if ($v['continue'] <= 0) {
  131. $storePostage = $storePostage;
  132. } else {
  133. $storePostage = bcadd($storePostage, bcmul(ceil(bcdiv($v['number'], $v['continue'] ?? 0, 2)), $v['continue_price']), 2);
  134. }
  135. }
  136. }
  137. } else {
  138. $storePostage = 0;
  139. }
  140. if ($storeFreePostage <= $totalPrice) $storePostage = 0;//如果总价大于等于满额包邮 邮费等于0
  141. }
  142. return compact('storePostage', 'storeFreePostage', 'totalPrice', 'costPrice', 'vipPrice');
  143. }
  144. /**获取某个字段总金额
  145. * @param $cartInfo
  146. * @param $key 键名
  147. * @return int|string
  148. */
  149. public static function getOrderSumPrice($cartInfo, $key = 'truePrice')
  150. {
  151. $SumPrice = 0;
  152. foreach ($cartInfo as $cart) {
  153. $SumPrice = bcadd($SumPrice, bcmul($cart['cart_num'], $cart[$key], 2), 2);
  154. }
  155. return $SumPrice;
  156. }
  157. /**
  158. * 拼团
  159. * @param $cartInfo
  160. * @return array
  161. */
  162. public static function getCombinationOrderPriceGroup($cartInfo)
  163. {
  164. $storePostage = floatval(sys_config('store_postage')) ?: 0;
  165. $storeFreePostage = floatval(sys_config('store_free_postage')) ?: 0;
  166. $totalPrice = self::getCombinationOrderTotalPrice($cartInfo);
  167. $costPrice = self::getCombinationOrderTotalPrice($cartInfo);
  168. if (!$storeFreePostage) {
  169. $storePostage = 0;
  170. } else {
  171. foreach ($cartInfo as $cart) {
  172. if (!StoreCombination::where('id', $cart['combination_id'])->value('is_postage'))
  173. $storePostage = bcadd($storePostage, StoreCombination::where('id', $cart['combination_id'])->value('postage'), 2);
  174. }
  175. if ($storeFreePostage <= $totalPrice) $storePostage = 0;
  176. }
  177. return compact('storePostage', 'storeFreePostage', 'totalPrice', 'costPrice');
  178. }
  179. /**
  180. * 拼团价格
  181. * @param $cartInfo
  182. * @return float
  183. */
  184. public static function getCombinationOrderTotalPrice($cartInfo)
  185. {
  186. $totalPrice = 0;
  187. foreach ($cartInfo as $cart) {
  188. if ($cart['combination_id']) {
  189. $totalPrice = bcadd($totalPrice, bcmul($cart['cart_num'], StoreCombination::where('id', $cart['combination_id'])->value('price'), 2), 2);
  190. }
  191. }
  192. return (float)$totalPrice;
  193. }
  194. /**
  195. * 缓存订单信息
  196. * @param $uid
  197. * @param $cartInfo
  198. * @param $priceGroup
  199. * @param array $other
  200. * @param int $cacheTime
  201. * @return string
  202. * @throws \Psr\SimpleCache\InvalidArgumentException
  203. */
  204. public static function cacheOrderInfo($uid, $cartInfo, $priceGroup, $other = [], $cacheTime = 600)
  205. {
  206. $key = md5(time());
  207. Cache::set('user_order_' . $uid . $key, compact('cartInfo', 'priceGroup', 'other'), $cacheTime);
  208. return $key;
  209. }
  210. /**
  211. * 获取订单缓存信息
  212. * @param $uid
  213. * @param $key
  214. * @return mixed|null
  215. * @throws \Psr\SimpleCache\InvalidArgumentException
  216. */
  217. public static function getCacheOrderInfo($uid, $key)
  218. {
  219. $cacheName = 'user_order_' . $uid . $key;
  220. if (!Cache::has($cacheName)) return null;
  221. return Cache::get($cacheName);
  222. }
  223. /**
  224. * 删除订单缓存
  225. * @param $uid
  226. * @param $key
  227. */
  228. public static function clearCacheOrderInfo($uid, $key)
  229. {
  230. Cache::delete('user_order_' . $uid . $key);
  231. }
  232. /**
  233. * 生成订单
  234. * @param $uid
  235. * @param $key
  236. * @param $addressId
  237. * @param $payType
  238. * @param bool $useIntegral
  239. * @param int $couponId
  240. * @param string $mark
  241. * @param int $combinationId
  242. * @param int $pinkId
  243. * @param int $seckill_id
  244. * @param int $bargain_id
  245. * @param bool $test
  246. * @param int $isChannel
  247. * @param int $shipping_type
  248. * @param string $real_name
  249. * @param string $phone
  250. * @return StoreOrder|bool|\think\Model
  251. * @throws \think\Exception
  252. * @throws \think\db\exception\DataNotFoundException
  253. * @throws \think\db\exception\ModelNotFoundException
  254. * @throws \think\exception\DbException
  255. */
  256. public static function cacheKeyCreateOrder($uid, $key, $addressId, $payType, $useIntegral = false, $couponId = 0, $mark = '', $combinationId = 0, $pinkId = 0, $seckill_id = 0, $bargain_id = 0, $activity_id = 0, $live_id = 0, $test = false, $isChannel = 0, $shipping_type = 1, $real_name = '', $phone = '', $storeId = 0, $use_integral_pink = 0, $isAutoPink = 0,$is_gift=0,$spread=0,$is_num=0,$pink_num=1,$line_id=0,$is_wdc=0)
  257. {
  258. self::beginTrans();
  259. try {
  260. $shipping_type = (int)$shipping_type;
  261. $offlinePayStatus = (int)sys_config('offline_pay_status') ?? (int)2;
  262. if ($offlinePayStatus == 2) unset(self::$payType['offline']);
  263. if (!array_key_exists($payType, self::$payType)) return self::setErrorInfo('选择支付方式有误!', true);
  264. if (self::be(['unique' => $key, 'uid' => $uid])) return self::setErrorInfo('请勿重复提交订单', true);
  265. $userInfo = User::getUserInfo($uid);
  266. if (!$userInfo) return self::setErrorInfo('用户不存在!', true);
  267. $cartGroup = self::getCacheOrderInfo($uid, $key);
  268. if (!$cartGroup) return self::setErrorInfo('订单已过期,请刷新当前页面!', true);
  269. $cartInfo = $cartGroup['cartInfo'];
  270. $priceGroup = $cartGroup['priceGroup'];
  271. $other = $cartGroup['other'];
  272. $payPrice = (float)$priceGroup['totalPrice'];
  273. $addr = UserAddress::where('uid', $uid)->where('id', $addressId)->find();
  274. if ($payType == 'offline' && sys_config('offline_postage') == 1) {
  275. $payPostage = 0;
  276. } else {
  277. $payPostage = self::getOrderPriceGroup($cartInfo, $addr)['storePostage'];
  278. }
  279. if ($shipping_type === 1) {
  280. if (!$test && !$addressId) return self::setErrorInfo('请选择收货地址!', true);
  281. if (!$test && (!UserAddress::be(['uid' => $uid, 'id' => $addressId, 'is_del' => 0]) || !($addressInfo = UserAddress::find($addressId))))
  282. return self::setErrorInfo('地址选择有误!', true);
  283. } else {
  284. if ((!$real_name || !$phone) && !$test) return self::setErrorInfo('请填写姓名和电话', true);
  285. $addressInfo['real_name'] = $real_name;
  286. $addressInfo['phone'] = $phone;
  287. $addressInfo['province'] = '';
  288. $addressInfo['city'] = '';
  289. $addressInfo['district'] = '';
  290. $addressInfo['detail'] = '';
  291. }
  292. $cartIds = [];
  293. $totalNum = 0;
  294. $gainIntegral = 0;
  295. foreach ($cartInfo as $cart) {
  296. $cartIds[] = $cart['id'];
  297. $totalNum += $cart['cart_num'];
  298. if (!$seckill_id) $seckill_id = $cart['seckill_id'];
  299. if (!$bargain_id) $bargain_id = $cart['bargain_id'];
  300. if (!$combinationId) $combinationId = $cart['combination_id'];
  301. if (!$activity_id) $activity_id = $cart['activity_id'];
  302. if (!$live_id) $live_id = $cart['live_id'];
  303. $cartInfoGainIntegral = isset($cart['productInfo']['give_integral']) ? bcmul($cart['cart_num'], $cart['productInfo']['give_integral'], 2) : 0;
  304. $gainIntegral = bcadd($gainIntegral, $cartInfoGainIntegral, 2);
  305. }
  306. $deduction = $seckill_id || $bargain_id || $combinationId || $activity_id || $live_id;
  307. if ($deduction) {
  308. $auto_pink=StoreOrder::where('uid',$uid)->where('combination_id','<>',0)->where('is_del',0)->where('is_ok',0)->find();
  309. if($auto_pink){
  310. return self::setErrorInfo('拼团正在进行!', true);
  311. }
  312. $top_num=sys_config('pink_suceess_num');
  313. $tnum=StoreOrder::where('refund_status', '=', '0')->where('uid', $uid)->where('pink_id','<>',0)->where('pink_num',0)->where('is_ok',1)->whereTime('add_time','today')->count();
  314. if($top_num<=$tnum){
  315. return self::setErrorInfo('今日拼团次数已用尽!', true);
  316. }
  317. $couponId = 0;
  318. $useIntegral = false;
  319. if (!$test) {
  320. unset(self::$payType['offline']);
  321. if (!array_key_exists($payType, self::$payType)) return self::setErrorInfo('营销产品不能使用线下支付!', true);
  322. }
  323. }
  324. //使用优惠劵
  325. $res1 = true;
  326. if ($couponId) {
  327. $couponInfo = StoreCouponUser::validAddressWhere()->where('id', $couponId)->where('uid', $uid)->find();
  328. if (!$couponInfo) return self::setErrorInfo('选择的优惠劵无效!', true);
  329. $coupons = StoreCouponUser::getUsableCouponList($uid, ['valid' => $cartInfo], $payPrice);
  330. $flag = false;
  331. foreach ($coupons as $coupon) {
  332. if ($coupon['id'] == $couponId) {
  333. $flag = true;
  334. continue;
  335. }
  336. }
  337. if (!$flag)
  338. return self::setErrorInfo('不满足优惠劵的使用条件!', true);
  339. $payPrice = (float)bcsub($payPrice, $couponInfo['coupon_price'], 2);
  340. $res1 = StoreCouponUser::useCoupon($couponId);
  341. $couponPrice = $couponInfo['coupon_price'];
  342. } else {
  343. $couponId = 0;
  344. $couponPrice = 0;
  345. }
  346. if (!$res1) return self::setErrorInfo('使用优惠劵失败!', true);
  347. //$shipping_type = 1 快递发货 $shipping_type = 2 门店自提
  348. $store_self_mention = sys_config('store_self_mention') ?? 0;
  349. if (!$store_self_mention) $shipping_type = 1;
  350. if ($shipping_type === 1) {
  351. //是否包邮
  352. if ((isset($other['offlinePostage']) && $other['offlinePostage'] && $payType == 'offline')) $payPostage = 0;
  353. $payPrice = (float)bcadd($payPrice, $payPostage, 2);
  354. } else if ($shipping_type === 2) {
  355. //门店自提没有邮费支付
  356. $priceGroup['storePostage'] = 0;
  357. $payPostage = 0;
  358. if (!$storeId && !$test) {
  359. return self::setErrorInfo('请选择门店', true);
  360. }
  361. }
  362. //积分抵扣
  363. $res2 = true;
  364. $SurplusIntegral = 0;
  365. if ($useIntegral && $userInfo['integral'] > 0) {
  366. $deductionPrice = (float)bcmul($userInfo['integral'], $other['integralRatio'], 2);
  367. if ($deductionPrice < $payPrice) {
  368. $payPrice = bcsub($payPrice, $deductionPrice, 2);
  369. $usedIntegral = $userInfo['integral'];
  370. $SurplusIntegral = 0;
  371. $res2 = false !== User::edit(['integral' => 0], $userInfo['uid'], 'uid');
  372. } else {
  373. $deductionPrice = $payPrice;
  374. $usedIntegral = (float)bcdiv($payPrice, $other['integralRatio'], 2);
  375. $SurplusIntegral = bcsub($userInfo['integral'], $usedIntegral, 2);
  376. $res2 = false !== User::bcDec($userInfo['uid'], 'integral', $usedIntegral, 'uid');
  377. $payPrice = 0;
  378. }
  379. $res2 = $res2 && false != UserBill::expend('积分抵扣', $uid, 'integral', 'deduction', $usedIntegral, $key, $userInfo['integral'], '购买商品使用' . floatval($usedIntegral) . '积分抵扣' . floatval($deductionPrice) . '元');
  380. } else {
  381. $deductionPrice = 0;
  382. $usedIntegral = 0;
  383. }
  384. if (!$res2) return self::setErrorInfo('使用积分抵扣失败!', true);
  385. if ($payPrice <= 0) $payPrice = 0;
  386. if ($test) {
  387. self::rollbackTrans();
  388. return [
  389. 'total_price' => $priceGroup['totalPrice'],
  390. 'pay_price' =>$payPrice,
  391. 'pay_postage' => $payPostage,
  392. 'coupon_price' => $couponPrice,
  393. 'deduction_price' => $deductionPrice,
  394. 'SurplusIntegral' => $SurplusIntegral,
  395. ];
  396. }
  397. if ($combinationId) {
  398. $cost_integral = Db::name('store_combination')->alias('c')->join('store_product p', 'c.product_id=p.id')->where('c.id', '=', $combinationId)->value('cost_integral');
  399. $use_integral_pink += $cost_integral;
  400. }
  401. $orderInfo = [
  402. 'uid' => $uid,
  403. 'order_id' => $test ? 0 : self::getNewOrderId(),
  404. 'real_name' => $addressInfo['real_name'],
  405. 'user_phone' => $addressInfo['phone'],
  406. 'user_address' => $addressInfo['province'] . ' ' . $addressInfo['city'] . ' ' . $addressInfo['district'] . ' ' . $addressInfo['detail'],
  407. 'cart_id' => $cartIds,
  408. 'total_num' => $totalNum,
  409. 'total_price' => $priceGroup['totalPrice'],
  410. 'total_postage' => $priceGroup['storePostage'],
  411. 'coupon_id' => $couponId,
  412. 'coupon_price' => $couponPrice,
  413. 'pay_price' =>$payPrice,
  414. 'pay_postage' => $payPostage,
  415. 'deduction_price' => $deductionPrice,
  416. 'paid' => 0,
  417. 'pay_type' => $payType,
  418. 'use_integral' => $usedIntegral,
  419. 'gain_integral' => $gainIntegral,
  420. 'use_integral_pink' => $use_integral_pink,
  421. 'use_wtc'=>$payPrice,
  422. 'mark' => htmlspecialchars($mark),
  423. 'combination_id' => $combinationId,
  424. 'pink_id' => $pinkId,
  425. 'seckill_id' => $seckill_id,
  426. 'bargain_id' => $bargain_id,
  427. 'activity_id' => $activity_id,
  428. 'live_id' => $live_id,
  429. 'cost' => $priceGroup['costPrice'],
  430. 'is_channel' => $isChannel,
  431. 'add_time' => time(),
  432. 'unique' => $key,
  433. 'shipping_type' => $shipping_type,
  434. 'is_auto_pink' => $isAutoPink,
  435. 'is_gift' =>$is_gift,
  436. 'spread' =>$spread,
  437. 'close_time' => $isAutoPink ? bcadd(time(), 12 * 3600) : 0 , //默认付款12小时后没有成团,自动关闭
  438. 'ok_num'=>0,
  439. 'pink_num'=>$pink_num,
  440. 'line_id'=>$line_id,
  441. 'is_wdc'=>$is_wdc,
  442. ];
  443. if ($shipping_type === 2) {
  444. $orderInfo['verify_code'] = self::getStoreCode();
  445. $orderInfo['store_id'] = SystemStore::getStoreDispose($storeId, 'id');
  446. if (!$orderInfo['store_id']) return self::setErrorInfo('暂无门店无法选择门店自提!', true);
  447. }
  448. $order = self::create($orderInfo);
  449. if (!$order) return self::setErrorInfo('订单生成失败!', true);
  450. $res5 = true;
  451. foreach ($cartInfo as $cart) {
  452. //减库存加销量
  453. if ($combinationId) $res5 = $res5 && StoreCombination::decCombinationStock($cart['cart_num'], $combinationId, isset($cart['productInfo']['attrInfo']) ? $cart['productInfo']['attrInfo']['unique'] : '');
  454. else if ($seckill_id) $res5 = $res5 && StoreSeckill::decSeckillStock($cart['cart_num'], $seckill_id, isset($cart['productInfo']['attrInfo']) ? $cart['productInfo']['attrInfo']['unique'] : '');
  455. else if ($bargain_id) $res5 = $res5 && StoreBargain::decBargainStock($cart['cart_num'], $bargain_id, isset($cart['productInfo']['attrInfo']) ? $cart['productInfo']['attrInfo']['unique'] : '');
  456. else if ($activity_id) $res5 = $res5 && StoreActivityProduct::decCombinationStock($cart['cart_num'], $activity_id, isset($cart['productInfo']['attrInfo']) ? $cart['productInfo']['attrInfo']['unique'] : '');
  457. else if ($live_id) $res5 = $res5 && StoreLiveProduct::decCombinationStock($cart['cart_num'], $live_id, isset($cart['productInfo']['attrInfo']) ? $cart['productInfo']['attrInfo']['unique'] : '');
  458. else $res5 = $res5 && StoreProduct::decProductStock($cart['cart_num'], $cart['productInfo']['id'], isset($cart['productInfo']['attrInfo']) ? $cart['productInfo']['attrInfo']['unique'] : '');
  459. }
  460. //保存购物车商品信息
  461. $res4 = false !== StoreOrderCartInfo::setCartInfo($order['id'], $cartInfo);
  462. //购物车状态修改
  463. $res6 = false !== StoreCart::where('id', 'IN', $cartIds)->update(['is_pay' => 1]);
  464. if (!$res4 || !$res5 || !$res6) return self::setErrorInfo('订单生成失败!', true);
  465. //自动设置默认地址
  466. UserRepository::storeProductOrderCreateEbApi($order, compact('cartInfo', 'addressId'));
  467. self::clearCacheOrderInfo($uid, $key);
  468. self::commitTrans();
  469. StoreOrderStatus::status($order['id'], 'cache_key_create_order', '订单生成');
  470. return $order;
  471. } catch (\PDOException $e) {
  472. self::rollbackTrans();
  473. return self::setErrorInfo('生成订单时SQL执行错误错误原因:' . $e->getMessage());
  474. } catch (\Exception $e) {
  475. self::rollbackTrans();
  476. return self::setErrorInfo('生成订单时系统错误错误原因:' . $e->getMessage());
  477. }
  478. }
  479. /**
  480. * 回退积分
  481. * @param $order 订单信息
  482. * @return bool
  483. */
  484. public static function RegressionIntegral($order)
  485. {
  486. if ($order['paid'] || $order['status'] == -2 || $order['is_del']) return true;
  487. if ($order['use_integral'] <= 0) return true;
  488. if ((int)$order['status'] != -2 && (int)$order['refund_status'] != 2 && $order['back_integral'] >= $order['use_integral']) return true;
  489. $res = User::bcInc($order['uid'], 'integral', $order['use_integral']);
  490. if (!$res) return self::setErrorInfo('回退积分增加失败');
  491. UserBill::income('积分回退', $order['uid'], 'integral', 'deduction', $order['use_integral'], $order['unique'], User::where('uid', $order['uid'])->value('integral'), '购买商品失败,回退积分' . floatval($order['use_integral']));
  492. return false !== self::where('order_id', $order['order_id'])->update(['back_integral' => $order['use_integral']]);
  493. }
  494. /**
  495. * 回退库存和销量
  496. * @param $order 订单信息
  497. * @return bool
  498. * @throws \think\db\exception\DataNotFoundException
  499. * @throws \think\db\exception\ModelNotFoundException
  500. * @throws \think\exception\DbException
  501. */
  502. public static function RegressionStock($order)
  503. {
  504. if ($order['paid'] || $order['status'] == -2 || $order['is_del']) return true;
  505. $combinationId = $order['combination_id'];
  506. $seckill_id = $order['seckill_id'];
  507. $bargain_id = $order['bargain_id'];
  508. $res5 = true;
  509. $cartInfo = StoreOrderCartInfo::where('cart_id', 'in', $order['cart_id'])->select();
  510. foreach ($cartInfo as $cart) {
  511. //增库存减销量
  512. if ($combinationId) $res5 = $res5 && StoreCombination::incCombinationStock($cart['cart_info']['cart_num'], $combinationId);
  513. else if ($seckill_id) $res5 = $res5 && StoreSeckill::incSeckillStock($cart['cart_info']['cart_num'], $seckill_id);
  514. else if ($bargain_id) $res5 = $res5 && StoreBargain::incBargainStock($cart['cart_info']['cart_num'], $bargain_id);
  515. else $res5 = $res5 && StoreProduct::incProductStock($cart['cart_info']['cart_num'], $cart['cart_info']['productInfo']['id'], isset($cart['cart_info']['productInfo']['attrInfo']) ? $cart['cart_info']['productInfo']['attrInfo']['unique'] : '');
  516. }
  517. return $res5;
  518. }
  519. /**
  520. * 回退优惠卷
  521. * @param $order 订单信息
  522. * @return bool
  523. */
  524. public static function RegressionCoupon($order)
  525. {
  526. if ($order['paid'] || $order['status'] == -2 || $order['is_del']) return true;
  527. $res = true;
  528. if ($order['coupon_id'] && StoreCouponUser::be(['id' => $order['coupon_id'], 'uid' => $order['uid'], 'status' => 1])) {
  529. $res = $res && false !== StoreCouponUser::where('id', $order['coupon_id'])->where('uid', $order['uid'])->update(['status' => 0, 'use_time' => 0]);
  530. }
  531. return $res;
  532. }
  533. /**
  534. * 取消订单
  535. * @param string order_id 订单id
  536. * @param $uid
  537. * @return bool
  538. * @throws \think\db\exception\DataNotFoundException
  539. * @throws \think\db\exception\ModelNotFoundException
  540. * @throws \think\exception\DbException
  541. */
  542. public static function cancelOrder($order_id, $uid)
  543. {
  544. $order = self::where('order_id', $order_id)->where('uid', $uid)->find();
  545. if (!$order) return self::setErrorInfo('没有查到此订单');
  546. self::beginTrans();
  547. try {
  548. $res = self::RegressionIntegral($order) && self::RegressionStock($order) && self::RegressionCoupon($order);
  549. $order->is_del = 1;
  550. if ($res && $order->save()) {
  551. self::commitTrans();
  552. return true;
  553. } else
  554. return false;
  555. } catch (\Exception $e) {
  556. self::rollbackTrans();
  557. return self::setErrorInfo(['line' => $e->getLine(), 'message' => $e->getMessage()]);
  558. }
  559. }
  560. /**
  561. * 生成订单唯一id
  562. * @param $uid 用户uid
  563. * @return string
  564. */
  565. public static function getNewOrderId()
  566. {
  567. list($msec, $sec) = explode(' ', microtime());
  568. $msectime = number_format((floatval($msec) + floatval($sec)) * 1000, 0, '', '');
  569. $orderId = 'wx' . $msectime . mt_rand(10000, 99999);
  570. if (self::be(['order_id' => $orderId])) $orderId = 'wx' . $msectime . mt_rand(10000, 99999);
  571. return $orderId;
  572. }
  573. /**
  574. * 修改订单号
  575. * @param $orderId
  576. * @return string
  577. */
  578. public static function changeOrderId($orderId)
  579. {
  580. $ymd = substr($orderId, 2, 8);
  581. $key = substr($orderId, 16);
  582. return 'wx' . $ymd . date('His') . $key;
  583. }
  584. /**
  585. * 查找购物车里的所有产品标题
  586. * @param $cartId 购物车id
  587. * @return bool|string
  588. */
  589. public static function getProductTitle($cartId)
  590. {
  591. $title = '';
  592. try {
  593. $orderCart = StoreOrderCartInfo::where('cart_id', 'in', $cartId)->field('cart_info')->select();
  594. foreach ($orderCart as $item) {
  595. if (isset($item['cart_info']['productInfo']['store_name'])) {
  596. $title .= $item['cart_info']['productInfo']['store_name'] . '|';
  597. }
  598. }
  599. unset($item);
  600. if (!$title) {
  601. $productIds = StoreCart::where('id', 'in', $cartId)->column('product_id');
  602. $productlist = ($productlist = StoreProduct::getProductField($productIds, 'store_name')) ? $productlist->toArray() : [];
  603. foreach ($productlist as $item) {
  604. if (isset($item['store_name'])) $title .= $item['store_name'] . '|';
  605. }
  606. }
  607. if ($title) $title = substr($title, 0, strlen($title) - 1);
  608. unset($item);
  609. } catch (\Exception $e) {
  610. }
  611. return $title;
  612. }
  613. /**
  614. * 获取门店自提唯一核销码
  615. * @return bool|string
  616. */
  617. public static function getStoreCode()
  618. {
  619. list($msec, $sec) = explode(' ', microtime());
  620. $num = bcadd(time(), mt_rand(10, 999999), 0) . '' . substr($msec, 2, 3);//生成随机数
  621. if (strlen($num) < 12)
  622. $num = str_pad((string)$num, 12, 0, STR_PAD_RIGHT);
  623. else
  624. $num = substr($num, 0, 12);
  625. if (self::be(['verify_code' => $num])) return self::getStoreCode();
  626. return $num;
  627. }
  628. /**
  629. * 余额支付
  630. * @param $order_id
  631. * @param $uid
  632. * @param string $formId
  633. * @return bool
  634. * @throws \think\Exception
  635. * @throws \think\db\exception\DataNotFoundException
  636. * @throws \think\db\exception\ModelNotFoundException
  637. * @throws \think\exception\DbException
  638. */
  639. public static function yuePay($order_id, $uid, $formId = '')
  640. {
  641. $orderInfo = self::where('uid', $uid)->where('order_id', $order_id)->where('is_del', 0)->find();
  642. if (!$orderInfo) return self::setErrorInfo('订单不存在!');
  643. if ($orderInfo['paid']) return self::setErrorInfo('该订单已支付!');
  644. // if($orderInfo['pay_type'] != 'yue') return self::setErrorInfo('该订单不能使用余额支付!');
  645. if($orderInfo['pink_id']>0 && !StorePink::isPinkStatus($orderInfo['pink_id'])) self::setErrorInfo('该团已关闭!');
  646. $userInfo = User::getUserInfo($uid);
  647. if ($userInfo['now_money'] < $orderInfo['pay_price'])
  648. return self::setErrorInfo(['status' => 'pay_deficiency', 'msg' => '余额不足' . floatval($orderInfo['pay_price'])]);
  649. self::beginTrans();
  650. $res1 = false !== User::bcDec($uid, 'now_money', $orderInfo['pay_price'], 'uid');
  651. $res2 = UserBill::expend('购买商品', $uid, 'now_money', 'pay_product', $orderInfo['pay_price'], $orderInfo['id'], $userInfo['now_money'], '余额支付' . floatval($orderInfo['pay_price']) . '元购买商品');
  652. // Log::write("a1:".$userInfo['now_money'],'error');
  653. $res3 = self::paySuccess($order_id, 'yue', $formId);//余额支付成功
  654. try {
  655. PaymentRepositories::yuePayProduct($userInfo, $orderInfo);
  656. } catch (\Exception $e) {
  657. self::rollbackTrans();
  658. return self::setErrorInfo($e->getMessage());
  659. }
  660. $res = $res1 && $res2 && $res3;
  661. self::checkTrans($res);
  662. return $res;
  663. }
  664. /**
  665. * 积分支付
  666. * @param $order_id
  667. * @param $uid
  668. * @param string $formId
  669. * @return bool
  670. * @throws \think\Exception
  671. * @throws \think\db\exception\DataNotFoundException
  672. * @throws \think\db\exception\ModelNotFoundException
  673. * @throws \think\exception\DbException
  674. */
  675. public static function integralPay($order_id, $uid, $formId = '')
  676. {
  677. $orderInfo = self::where('uid', $uid)->where('order_id', $order_id)->where('is_del', 0)->find();
  678. @file_put_contents('qq.txt',11);
  679. if (!$orderInfo) return self::setErrorInfo('订单不存在!');
  680. if ($orderInfo['paid']) return self::setErrorInfo('该订单已支付!');
  681. // if($orderInfo['pay_type'] != 'yue') return self::setErrorInfo('该订单不能使用余额支付!');
  682. if($orderInfo['pink_id']>0 && !StorePink::isPinkStatus($orderInfo['pink_id'])) self::setErrorInfo('该团已关闭!');
  683. $userInfo = User::getUserInfo($uid);
  684. if ($userInfo['integral'] < $orderInfo['pay_price'])
  685. return self::setErrorInfo(['status' => 'pay_deficiency', 'msg' => '积分不足' . floatval($orderInfo['pay_price'])]);
  686. @file_put_contents('ww.txt',11);
  687. self::beginTrans();
  688. $res1 = false !== User::bcDec($uid, 'integral', $orderInfo['pay_price'], 'uid');
  689. $res2 = UserBill::expend('购买商品', $uid, 'integral', 'integral_pay_product', $orderInfo['pay_price'], $orderInfo['id'], $userInfo['integral'], '积分支付' . floatval($orderInfo['pay_price']) . '元购买商品');
  690. //Log::write("a1:111111",'error');
  691. $res3 = self::paySuccess($order_id, 'integral', $formId);//积分支付成功
  692. try {
  693. PaymentRepositories::yuePayProduct($userInfo, $orderInfo);
  694. } catch (\Exception $e) {
  695. self::rollbackTrans();
  696. return self::setErrorInfo($e->getMessage());
  697. }
  698. $res = $res1 && $res2 && $res3;
  699. self::checkTrans($res);
  700. return $res;
  701. }
  702. /**
  703. * wdc支付
  704. * @param $order_id
  705. * @param $uid
  706. * @param string $formId
  707. * @return bool
  708. * @throws \think\Exception
  709. * @throws \think\db\exception\DataNotFoundException
  710. * @throws \think\db\exception\ModelNotFoundException
  711. * @throws \think\exception\DbException
  712. */
  713. public static function wdcPay($order_id, $uid, $formId = '')
  714. {
  715. $orderInfo = self::where('uid', $uid)->where('order_id', $order_id)->where('is_del', 0)->find();
  716. if (!$orderInfo) return self::setErrorInfo('订单不存在!');
  717. if ($orderInfo['paid']) return self::setErrorInfo('该订单已支付!');
  718. // if($orderInfo['pay_type'] != 'yue') return self::setErrorInfo('该订单不能使用余额支付!');
  719. if($orderInfo['pink_id']>0 && !StorePink::isPinkStatus($orderInfo['pink_id'])) self::setErrorInfo('该团已关闭!');
  720. if($orderInfo['line_id']){
  721. $res= self::paySuccess($order_id, 'wdc', $formId);//wdc支付成功
  722. return $res;
  723. }
  724. $userInfo = User::getUserInfo($uid);
  725. if ($userInfo['wdc'] < $orderInfo['pay_price'])
  726. return self::setErrorInfo(['status' => 'pay_deficiency', 'msg' => 'wdc不足' . floatval($orderInfo['pay_price'])]);
  727. self::beginTrans();
  728. $res1 = false !== User::bcDec($uid, 'wdc', $orderInfo['pay_price'], 'uid');
  729. $res2 = UserBill::expend('购买商品', $uid, 'wdc', 'wdc_pay_product', $orderInfo['pay_price'], $orderInfo['id'], $userInfo['wdc'], 'wdc支付' . floatval($orderInfo['pay_price']) . '元购买商品');
  730. // Log::write("a1:".$userInfo['now_money'],'error');
  731. $res3 = self::paySuccess($order_id, 'wdc', $formId);//wdc支付成功
  732. try {
  733. PaymentRepositories::yuePayProduct($userInfo, $orderInfo);
  734. } catch (\Exception $e) {
  735. self::rollbackTrans();
  736. return self::setErrorInfo($e->getMessage());
  737. }
  738. $res = $res1 && $res2 && $res3;
  739. self::checkTrans($res);
  740. return $res;
  741. }
  742. /**
  743. * 微信支付 为 0元时
  744. * @param $order_id
  745. * @param $uid
  746. * @param string $formId
  747. * @return bool
  748. * @throws \think\Exception
  749. * @throws \think\db\exception\DataNotFoundException
  750. * @throws \think\db\exception\ModelNotFoundException
  751. * @throws \think\exception\DbException
  752. */
  753. public static function jsPayPrice($order_id, $uid, $formId = '')
  754. {
  755. $orderInfo = self::where('uid', $uid)->where('order_id', $order_id)->where('is_del', 0)->find();
  756. if (!$orderInfo) return self::setErrorInfo('订单不存在!');
  757. if ($orderInfo['paid']) return self::setErrorInfo('该订单已支付!');
  758. if($orderInfo['pink_id']>0 && StorePink::isPinkStatus($orderInfo['pink_id'])) self::setErrorInfo('该团已关闭!');
  759. $userInfo = User::getUserInfo($uid);
  760. self::beginTrans();
  761. $res1 = UserBill::expend('购买商品', $uid, 'now_money', 'pay_product', $orderInfo['pay_price'], $orderInfo['id'], $userInfo['now_money'], '微信支付' . floatval($orderInfo['pay_price']) . '元购买商品');
  762. $res2 = self::paySuccess($order_id, 'weixin', $formId);//微信支付为0时
  763. $res = $res1 && $res2;
  764. self::checkTrans($res);
  765. return $res;
  766. }
  767. /**
  768. * 用户申请退款
  769. * @param $uni
  770. * @param $uid
  771. * @param string $refundReasonWap
  772. * @return bool
  773. */
  774. public static function orderApplyRefund($uni, $uid, $refundReasonWap = '', $refundReasonWapExplain = '', $refundReasonWapImg = [])
  775. {
  776. $order = self::getUserOrderDetail($uid, $uni);
  777. if (!$order) return self::setErrorInfo('支付订单不存在!');
  778. if ($order['refund_status'] == 2) return self::setErrorInfo('订单已退款!');
  779. if ($order['refund_status'] == 1) return self::setErrorInfo('正在申请退款中!');
  780. if ($order['status'] == 1) return self::setErrorInfo('订单当前无法退款!');
  781. self::beginTrans();
  782. $res1 = false !== StoreOrderStatus::status($order['id'], 'apply_refund', '用户申请退款,原因:' . $refundReasonWap);
  783. $res2 = false !== self::edit(['refund_status' => 1, 'refund_reason_time' => time(), 'refund_reason_wap' => $refundReasonWap, 'refund_reason_wap_explain' => $refundReasonWapExplain, 'refund_reason_wap_img' => json_encode($refundReasonWapImg)], $order['id'], 'id');
  784. $res = $res1 && $res2;
  785. self::checkTrans($res);
  786. if (!$res)
  787. return self::setErrorInfo('申请退款失败!');
  788. else {
  789. try {
  790. if (in_array($order['is_channel'], [0, 2])) {
  791. //公众号发送模板消息通知客服
  792. WechatTemplateService::sendAdminNoticeTemplate([
  793. 'first' => "亲,有个订单申请退款 \n订单号:{$order['order_id']}",
  794. 'keyword1' => '退款申请',
  795. 'keyword2' => '已支付',
  796. 'keyword3' => date('Y/m/d H:i', time()),
  797. 'remark' => '请及时处理'
  798. ]);
  799. }
  800. if (in_array($order['is_channel'], [1, 2])) {
  801. //小程序 发送模板消息
  802. RoutineTemplate::sendOrderRefundStatus($order, $refundReasonWap);
  803. }
  804. //通知后台消息提醒
  805. ChannelService::instance()->send('NEW_REFUND_ORDER', ['order_id' => $order['order_id']]);
  806. } catch (\Exception $e) {
  807. }
  808. //发送短信
  809. event('ShortMssageSend', [$order['order_id'], 'AdminRefund']);
  810. return true;
  811. }
  812. }
  813. /**
  814. * //TODO 支付成功后
  815. * @param $orderId
  816. * @param $paytype
  817. * @param $notify
  818. * @return bool
  819. */
  820. public static function paySuccess($orderId, $paytype = 'weixin', $formId = '')
  821. {
  822. //Log::write("pay-OK",'error');
  823. $order = self::where('order_id', $orderId)->find();
  824. @file_put_contents('ee.txt',11);
  825. $resPink = true;
  826. $res1 = self::where('order_id', $orderId)->update(['paid' => 1, 'pay_type' => $paytype,'is_del'=>0, 'pay_time' => time()]);//订单改为支付
  827. @file_put_contents('rr.txt',11);
  828. // Log::write("OK",'error');
  829. if ($order->combination_id && $res1 && !$order->refund_status && !$order->is_auto_pink) $resPink =PinkJob::create($order);//不是自动拼团的,创建拼团
  830. if ($order->combination_id && $res1 && !$order->refund_status && $order->is_auto_pink && !$order->is_ok) $resPink =AutoJob::create($order);//自动拼团
  831. @file_put_contents('rr.txt',11);
  832. if($order->line_id){
  833. Line::where('id',$order['line_id'])->save(['status'=>3]);
  834. }
  835. $oid = self::where('order_id', $orderId)->value('id');
  836. StoreOrderStatus::status($oid, 'pay_success', '用户付款成功');
  837. @file_put_contents('tt.txt',11);
  838. // if ($order->combination_id && $res1) { //拼团商品消耗的积分
  839. // $user = Db::name('user')->where('uid', '=', $order['uid'])->find();
  840. // $cost_integral = Db::name('store_combination')->alias('c')->join('store_product p', 'c.product_id=p.id')->where('c.id', '=', $order->combination_id)->value('cost_integral'); //商品默认积分
  841. // $order['use_integral_pink'] = $user['integral'] - $order['use_integral_pink'] + $cost_integral >= 0 ? $order['use_integral_pink'] - $cost_integral : $user['integral']; //判断用户积分是否足够,要减去商品默认积分
  842. // if ($order['use_integral_pink']) {
  843. // Db::name('user')->where('uid', '=', $user['uid'])->dec('integral', $order['use_integral_pink'])->update();
  844. // $integral = Db::name('user')->where('uid', '=', $user['uid'])->value('integral');
  845. // UserBill::expend('拼团积分消耗', $user['uid'], 'integral', 'deduction', $order['use_integral_pink'], $order['id'], $integral, '拼团消耗积分,助力补贴');
  846. // }
  847. // }
  848. if(!$order->is_wdc && $res1){
  849. User::directWdc($order);
  850. }
  851. if(!$order->is_wdc && $res1 && !$order->combination_id){
  852. self::gainUserIntegral($order);
  853. }
  854. if($order->is_gift && $res1)
  855. {
  856. $product_id = StoreOrderCartInfo::where('oid',$order->id)->value('product_id');
  857. $old_level = StoreProduct::where('id',$product_id)->value('level');
  858. $level=SystemUserLevel::where('id',$old_level)->value('grade');
  859. $old_userlevel = User::where('uid',$order->uid)->value('level');
  860. $userlevel=SystemUserLevel::where('id',$old_userlevel)->value('grade');
  861. if($userlevel<$level)
  862. {
  863. UserLevel::setUserLevel($order->uid,$old_level);
  864. }
  865. }
  866. if(sys_config('spread_look')==1 && $order->spread>0) {
  867. $spread = User::where('uid',$order->uid)->value('spread_uid');
  868. User::setSpreadUid($order->uid,$order->spread);
  869. if(intval($spread)==0) {
  870. WechatUser::spreadSuccessGiveIntegral($order->spread);
  871. }
  872. }
  873. @file_put_contents('yy.txt',11);
  874. //支付成功后
  875. event('OrderPaySuccess', [$order, $formId]);
  876. $res = $res1 && $resPink;
  877. return false !== $res;
  878. }
  879. /*
  880. * 线下支付消息通知
  881. * 待完善
  882. *
  883. * */
  884. public static function createOrderTemplate($order)
  885. {
  886. //$goodsName = StoreOrderCartInfo::getProductNameList($order['id']);
  887. // RoutineTemplateService::sendTemplate(WechatUser::getOpenId($order['uid']),RoutineTemplateService::ORDER_CREATE, [
  888. // 'first'=>'亲,您购买的商品已支付成功',
  889. // 'keyword1'=>date('Y/m/d H:i',$order['add_time']),
  890. // 'keyword2'=>implode(',',$goodsName),
  891. // 'keyword3'=>$order['order_id'],
  892. // 'remark'=>'点击查看订单详情'
  893. // ],Url::build('/wap/My/order',['uni'=>$order['order_id']],true,true));
  894. // RoutineTemplateService::sendAdminNoticeTemplate([
  895. // 'first'=>"亲,您有一个新订单 \n订单号:{$order['order_id']}",
  896. // 'keyword1'=>'新订单',
  897. // 'keyword2'=>'线下支付',
  898. // 'keyword3'=>date('Y/m/d H:i',time()),
  899. // 'remark'=>'请及时处理'
  900. // ]);
  901. }
  902. /**
  903. * 获取订单详情
  904. * @param $uid
  905. * @param $key
  906. * @return array|\think\Model|null
  907. * @throws \think\db\exception\DataNotFoundException
  908. * @throws \think\db\exception\ModelNotFoundException
  909. * @throws \think\exception\DbException
  910. */
  911. public static function getUserOrderDetail($uid, $key)
  912. {
  913. return self::where('order_id|unique', $key)->where('uid', $uid)->where('is_del', 0)->find();
  914. }
  915. /**
  916. * TODO 订单发货
  917. * @param array $postageData 发货信息
  918. * @param string $oid orderID
  919. */
  920. public static function orderPostageAfter($postageData, $oid)
  921. {
  922. $order = self::where('id', $oid)->find();
  923. if ($postageData['delivery_type'] == 'send') {//送货
  924. RoutineTemplate::sendOrderPostage($order);
  925. } else if ($postageData['delivery_type'] == 'express') {//发货
  926. RoutineTemplate::sendOrderPostage($order, 1);
  927. }
  928. }
  929. /** 收货后发送模版消息
  930. * @param $order
  931. */
  932. public static function orderTakeAfter($order)
  933. {
  934. $title = self::getProductTitle($order['cart_id']);
  935. if ($order['is_channel'] == 1) {//小程序
  936. RoutineTemplate::sendOrderTakeOver($order, $title);
  937. } else {
  938. $openid = WechatUser::where('uid', $order['uid'])->value('openid');
  939. \crmeb\services\WechatTemplateService::sendTemplate($openid, \crmeb\services\WechatTemplateService::ORDER_TAKE_SUCCESS, [
  940. 'first' => '亲,您的订单已收货',
  941. 'keyword1' => $order['order_id'],
  942. 'keyword2' => '已收货',
  943. 'keyword3' => date('Y-m-d H:i:s', time()),
  944. 'keyword4' => $title,
  945. 'remark' => '感谢您的光临!'
  946. ]);
  947. }
  948. }
  949. /**
  950. * 删除订单
  951. * @param $uni
  952. * @param $uid
  953. * @return bool
  954. */
  955. public static function removeOrder($uni, $uid)
  956. {
  957. $order = self::getUserOrderDetail($uid, $uni);
  958. if (!$order) return self::setErrorInfo('订单不存在!');
  959. $order = self::tidyOrder($order);
  960. if ($order['_status']['_type'] != 0 && $order['_status']['_type'] != -2 && $order['_status']['_type'] != 4)
  961. return self::setErrorInfo('该订单无法删除!');
  962. if (false !== self::edit(['is_del' => 1], $order['id'], 'id') && false !== StoreOrderStatus::status($order['id'], 'remove_order', '删除订单')) {
  963. //未支付和已退款的状态下才可以退积分退库存退优惠券
  964. if ($order['_status']['_type'] == 0 || $order['_status']['_type'] == -2) {
  965. event('StoreOrderRegressionAllAfter', [$order]);
  966. }
  967. event('UserOrderRemoved', $uni);
  968. return true;
  969. } else
  970. return self::setErrorInfo('订单删除失败!');
  971. }
  972. /**
  973. * //TODO 用户确认收货
  974. * @param $uni
  975. * @param $uid
  976. */
  977. public static function takeOrder($uni, $uid)
  978. {
  979. $order = self::getUserOrderDetail($uid, $uni);
  980. if (!$order) return self::setErrorInfo('订单不存在!');
  981. $order = self::tidyOrder($order);
  982. if ($order['_status']['_type'] != 2) return self::setErrorInfo('订单状态错误!');
  983. self::beginTrans();
  984. if (false !== self::edit(['status' => 2], $order['id'], 'id') &&
  985. false !== StoreOrderStatus::status($order['id'], 'user_take_delivery', '用户已收货')) {
  986. try {
  987. OrderRepository::storeProductOrderUserTakeDelivery($order, $uid);
  988. if ($order['combination_id'] == 0) { //拼团商品外,其他订单的奖励计算
  989. self::computePrize($uni, $uid);
  990. }
  991. } catch (\Exception $e) {
  992. self::rollbackTrans();
  993. return self::setErrorInfo($e->getMessage());
  994. }
  995. self::commitTrans();
  996. event('UserLevelAfter', [User::get($uni)]);
  997. event('UserOrderTake', $uni);
  998. //短信通知
  999. event('ShortMssageSend', [$order['order_id'], ['Receiving', 'AdminConfirmTakeOver']]);
  1000. return true;
  1001. } else {
  1002. self::rollbackTrans();
  1003. return false;
  1004. }
  1005. }
  1006. /**
  1007. * 购物奖励计算发放
  1008. * @param $uni
  1009. * @param $uid
  1010. * @throws \think\db\exception\DataNotFoundException
  1011. * @throws \think\db\exception\DbException
  1012. * @throws \think\db\exception\ModelNotFoundException
  1013. */
  1014. public static function computePrize($uni, $uid)
  1015. {
  1016. BaseModel::beginTrans();
  1017. try {
  1018. Log::write("确认收货-start:" . $uni, 'error');
  1019. Log::write("确认收货1", 'error');
  1020. //获取productId
  1021. $cartId = Db::name('store_order')->where('order_id|unique', $uni)->value('cart_id');
  1022. $cartId = str_replace('[', '', $cartId);
  1023. $cartId = str_replace(']', '', $cartId);
  1024. $cartId = explode(',', $cartId);
  1025. $productId = Db::name('store_cart')->where('id', $cartId[0])->value('product_id');
  1026. $pro = StoreProduct::where('id', $productId)->find();
  1027. $order = StoreOrder::where('order_id|unique', $uni)->find();
  1028. if (!$pro || !$order) {
  1029. return self::setErrorInfo('数据库里找不到数据', true);
  1030. }
  1031. $integral = $pro['give_integral']* $order['total_num'];
  1032. WechatUser::buyProductGiveIntegral($uid, $integral); //购物赠送积分
  1033. $p = $order['pay_price'] - $order['pay_postage'] - $order['cost'];
  1034. $profit = $p > 0 ? $p : 0; //利润
  1035. // $pink_reward_rate = $pro['pink_reward_rate'];
  1036. $level1_reward_rate = $pro['level1_reward_rate'] * $order['total_num'];//极差1奖励
  1037. $level2_reward_rate = $pro['level2_reward_rate'] * $order['total_num'];//极差2奖励
  1038. $level3_reward_rate = $pro['level3_reward_rate'] * $order['total_num'];//极差3奖励
  1039. $samelevel_reward_rate = $pro['samelevel_reward_rate'] * $order['total_num'];//平级奖励
  1040. $pink_zhitui_prize = $pro['pink_zhitui_prize'] * $order['total_num'];//直推奖励
  1041. $samelevelPerson = $pro['samelevel_prise_maxperson'];//平级中奖人数
  1042. if (!$profit) {
  1043. Log::write("确认收货-利润为0", 'error');
  1044. return self::setErrorInfo('利润为0', true);
  1045. }
  1046. Log::write("确认收货2", 'error');
  1047. //直推奖励
  1048. $spread_id = User::where('uid', $uid)->value('spread_uid');
  1049. if ($pink_zhitui_prize > 0 && User::be(['uid' => $spread_id])) {
  1050. User::where('uid', $spread_id)->inc('brokerage_price', bcmul($profit, $pink_zhitui_prize * 0.01, 2))->update();
  1051. $balance = User::where('uid', $spread_id)->value('brokerage_price');
  1052. //Log::write("a1:".$balance,'error');
  1053. UserBill::income('购物直推奖励', $spread_id, 'now_money', 'brokerage', bcmul($profit, $pink_zhitui_prize * 0.01, 2), 0, $balance, '直推奖励', 1);
  1054. }
  1055. Log::write("确认收货3", 'error');
  1056. //计算极差佣金
  1057. $userList = User::select()->toArray();
  1058. $max_prize = max([$level1_reward_rate, $level2_reward_rate, $level3_reward_rate]);
  1059. $levelPrizeLeave = $max_prize;
  1060. $prevUser = null;
  1061. $pids = [];
  1062. UtilService::getparentid($userList, $uid, $pids);
  1063. foreach ($pids as $k => $v) {
  1064. $level = UserLevel::getUserLevel($uid);
  1065. $level_id_origin = 0; //中奖用户等级
  1066. if ($level !== false) {
  1067. $level_id_origin = UserLevel::getUserLevelInfo($level, 'level_id');
  1068. }
  1069. $user = User::where('uid', '=', $v)->find();
  1070. if (!$user)
  1071. continue;
  1072. $level = UserLevel::getUserLevel($v);
  1073. $level_id = 0;
  1074. if ($level !== false) {
  1075. $level_id = UserLevel::getUserLevelInfo($level, 'level_id');
  1076. }
  1077. $user['level_id'] = $level_id;
  1078. if ($prevUser == null) {
  1079. if ($level_id <= $level_id_origin) {
  1080. continue;
  1081. }
  1082. if ($level_id == 1) {
  1083. if ($level1_reward_rate > 0) {
  1084. User::where('uid', $v)->inc('brokerage_price', bcmul($profit, $level1_reward_rate * 0.01, 2))->update();
  1085. $balance = User::where('uid', $v)->value('brokerage_price');
  1086. //Log::write("a5:".$balance,'error');
  1087. UserBill::income('购物极差奖励', $v, 'now_money', 'brokerage', bcmul($profit, $level1_reward_rate * 0.01, 2), 0, $balance, '极差奖励', 1);
  1088. $levelPrizeLeave = $max_prize - $level1_reward_rate;
  1089. $user['prevPrize'] = $level1_reward_rate;
  1090. }
  1091. } else if ($level_id == 2) {
  1092. if ($level2_reward_rate > 0) {
  1093. User::where('uid', $v)->inc('brokerage_price', bcmul($profit, $level2_reward_rate * 0.01, 2))->update();
  1094. $balance = User::where('uid', $v)->value('brokerage_price');
  1095. //Log::write("a6:".$balance,'error');
  1096. UserBill::income('购物极差奖励', $v, 'now_money', 'brokerage', bcmul($profit, $level2_reward_rate * 0.01, 2), 0, $balance, '极差奖励', 1);
  1097. $levelPrizeLeave = $max_prize - $level2_reward_rate;
  1098. $user['prevPrize'] = $level2_reward_rate;
  1099. }
  1100. } else if ($level_id == 3) {
  1101. if ($level3_reward_rate > 0) {
  1102. User::where('uid', $v)->inc('brokerage_price', bcmul($profit, $level3_reward_rate * 0.01, 2))->update();
  1103. $balance = User::where('uid', $v)->value('brokerage_price');
  1104. //Log::write("a7:".$balance,'error');
  1105. UserBill::income('购物极差奖励', $v, 'now_money', 'brokerage', bcmul($profit, $level3_reward_rate * 0.01, 2), 0, $balance, '极差奖励', 1);
  1106. $levelPrizeLeave = $max_prize - $level3_reward_rate;
  1107. $user['prevPrize'] = $level3_reward_rate;
  1108. }
  1109. }
  1110. } else {
  1111. if ($level_id <= $prevUser['level_id']) {
  1112. continue;
  1113. } else {
  1114. if ($level_id == 2) {
  1115. if ($levelPrizeLeave > ($level2_reward_rate - $prevUser['prevPrize'])) {
  1116. if (($level2_reward_rate - $prevUser['prevPrize']) > 0) {
  1117. User::where('uid', $v)->inc('brokerage_price', bcmul($profit, ($level2_reward_rate - $prevUser['prevPrize']) * 0.01, 2))->update();
  1118. $balance = User::where('uid', $v)->value('brokerage_price');
  1119. //Log::write("a10:".$balance,'error');
  1120. UserBill::income('购物极差奖励', $v, 'now_money', 'brokerage', bcmul($profit, ($level2_reward_rate - $prevUser['prevPrize']) * 0.01, 2), 0, $balance, '极差奖励', 1);
  1121. $levelPrizeLeave -= ($level2_reward_rate - $prevUser['prevPrize']);
  1122. $user['prevPrize'] = $level2_reward_rate;
  1123. }
  1124. } else {
  1125. if ($levelPrizeLeave > 0) {
  1126. User::where('uid', $v)->inc('brokerage_price', bcmul($profit, $levelPrizeLeave * 0.01, 2))->update();
  1127. $balance = User::where('uid', $v)->value('brokerage_price');
  1128. //Log::write("a11:".$balance,'error');
  1129. UserBill::income('购物极差奖励', $v, 'now_money', 'brokerage', bcmul($profit, $levelPrizeLeave * 0.01, 2), 0, $balance, '极差奖励', 1);
  1130. $levelPrizeLeave = 0;
  1131. }
  1132. }
  1133. } else if ($level_id == 3) {
  1134. if ($levelPrizeLeave > ($level3_reward_rate - $prevUser['prevPrize'])) {
  1135. if (($level3_reward_rate - $prevUser['prevPrize']) > 0) {
  1136. User::where('uid', $v)->inc('brokerage_price', bcmul($profit, ($level3_reward_rate - $prevUser['prevPrize']) * 0.01, 2))->update();
  1137. $balance = User::where('uid', $v)->value('brokerage_price');
  1138. //Log::write("a12:".$balance,'error');
  1139. UserBill::income('购物极差奖励', $v, 'now_money', 'brokerage', bcmul($profit, ($level3_reward_rate - $prevUser['prevPrize']) * 0.01, 2), 0, $balance, '极差奖励', 1);
  1140. $levelPrizeLeave -= ($level3_reward_rate - $prevUser['prevPrize']);
  1141. $user['prevPrize'] = $level3_reward_rate;
  1142. }
  1143. } else {
  1144. if ($levelPrizeLeave > 0) {
  1145. User::where('uid', $v)->inc('brokerage_price', bcmul($profit, $levelPrizeLeave * 0.01, 2))->update();
  1146. $balance = User::where('uid', $v)->value('brokerage_price');
  1147. //Log::write("a13:".$balance,'error');
  1148. UserBill::income('购物极差奖励', $v, 'now_money', 'brokerage', bcmul($profit, $levelPrizeLeave * 0.01, 2), 0, $balance, '极差奖励', 1);
  1149. $levelPrizeLeave = 0;
  1150. }
  1151. }
  1152. }
  1153. }
  1154. }
  1155. $prevUser = $user;
  1156. if ($levelPrizeLeave <= 0) {//剩余极差为0,结束
  1157. break;
  1158. }
  1159. }
  1160. Log::write("确认收货4", 'error');
  1161. //计算平级佣金
  1162. if ($samelevel_reward_rate) {
  1163. $pids = [];
  1164. UtilService::getparentid($userList, $uid, $pids);
  1165. // $samelevelPerson = sys_config('samelevel_prise_maxperson', 2); //平级奖励人数
  1166. $samelevelArr = [];
  1167. $samelevelPrizeArr = [];
  1168. for ($i = 1; $i <= 3; $i++) {
  1169. $res = Db::name('system_user_level')->where('id', '=', $i)->value('is_samelevel');
  1170. if ($res == 1) {
  1171. $samelevelArr[$i] = 0;
  1172. }
  1173. }
  1174. $level = UserLevel::getUserLevel($uid);
  1175. $level_id_origin = 0; //中奖用户等级
  1176. if ($level !== false) {
  1177. $level_id_origin = UserLevel::getUserLevelInfo($level, 'level_id');
  1178. }
  1179. if (!empty($samelevelArr)) {
  1180. $cur = null; //当前考察的等级
  1181. foreach ($pids as $v) {
  1182. $user = User::where('uid', '=', $v)->find();
  1183. if (!$user)
  1184. continue;
  1185. $level = UserLevel::getUserLevel($v);
  1186. $level_id = 0;
  1187. if ($level !== false) {
  1188. $level_id = UserLevel::getUserLevelInfo($level, 'level_id');
  1189. }
  1190. if ($cur == null) {
  1191. if ($level_id <= $level_id_origin) {
  1192. continue;
  1193. }
  1194. if (array_key_exists($level_id, $samelevelArr)) {
  1195. $cur = $level_id;
  1196. $samelevelArr[$cur] = 1;
  1197. }
  1198. } else {
  1199. if ($level_id == $cur) {
  1200. if ($samelevelArr[$cur] < $samelevelPerson + 1) {
  1201. $samelevelPrizeArr[] = $v;
  1202. $samelevelArr[$cur] += 1;
  1203. }
  1204. } else if ($level_id > $cur && $level_id <= 3) {
  1205. if (array_key_exists($level_id, $samelevelArr)) {
  1206. $cur = $level_id;
  1207. $samelevelArr[$cur] = 1;
  1208. }
  1209. } else if ($level_id > $cur && $level_id > 3) {
  1210. break;
  1211. }
  1212. }
  1213. }
  1214. if (!empty($samelevelPrizeArr) && $samelevel_reward_rate > 0) {
  1215. $samelevelPrize = bcdiv($samelevel_reward_rate, sizeof($samelevelPrizeArr), 2);
  1216. foreach ($samelevelPrizeArr as $v) { //发放平级佣金
  1217. User::where('uid', $v)->inc('brokerage_price', bcmul($profit, $samelevelPrize * 0.01, 2))->update();
  1218. $balance = User::where('uid', $v)->value('brokerage_price');
  1219. //Log::write("a14:".$balance,'error');
  1220. UserBill::income('购物平级奖励', $v, 'now_money', 'brokerage', bcmul($profit, $samelevelPrize * 0.01, 2), 0, $balance, '平级奖励', 1);
  1221. }
  1222. }
  1223. }
  1224. }
  1225. BaseModel::commitTrans();
  1226. Log::write("确认收货-end", 'error');
  1227. } catch (Exception $e) {
  1228. Log::write('数据库异常:' . $e->getMessage() . '||' . $e->getFile() . "||" . $e->getLine(), 'error');
  1229. BaseModel::rollbackTrans();
  1230. }
  1231. }
  1232. /**
  1233. * 获取订单状态购物车等信息
  1234. * @param $order
  1235. * @param bool $detail 是否获取订单购物车详情
  1236. * @param bool $isPic 是否获取订单状态图片
  1237. * @return mixed
  1238. * @throws \think\db\exception\DataNotFoundException
  1239. * @throws \think\db\exception\ModelNotFoundException
  1240. * @throws \think\exception\DbException
  1241. */
  1242. public static function tidyOrder($order, $detail = false, $isPic = false)
  1243. {
  1244. if ($detail == true && isset($order['id'])) {
  1245. $cartInfo = StoreOrderCartInfo::where('oid', $order['id'])->column('cart_info', 'unique') ?: [];
  1246. $info = [];
  1247. foreach ($cartInfo as $k => $cart) {
  1248. $cart = json_decode($cart, true);
  1249. $cart['unique'] = $k;
  1250. //新增是否评价字段
  1251. $cart['is_reply'] = StoreProductReply::where('unique', $k)->count();
  1252. array_push($info, $cart);
  1253. unset($cart);
  1254. }
  1255. $order['cartInfo'] = $info;
  1256. }
  1257. $status = [];
  1258. if (!$order['paid'] && $order['pay_type'] == 'offline' && !$order['status'] >= 2) {
  1259. $status['_type'] = 9;
  1260. $status['_title'] = '线下付款';
  1261. $status['_msg'] = '商家处理中,请耐心等待';
  1262. $status['_class'] = 'nobuy';
  1263. } else if (!$order['paid']) {
  1264. $status['_type'] = 0;
  1265. $status['_title'] = '未支付';
  1266. //系统预设取消订单时间段
  1267. $keyValue = ['order_cancel_time', 'order_activity_time', 'order_bargain_time', 'order_seckill_time', 'order_pink_time'];
  1268. //获取配置
  1269. $systemValue = SystemConfigService::more($keyValue);
  1270. //格式化数据
  1271. $systemValue = self::setValeTime($keyValue, is_array($systemValue) ? $systemValue : []);
  1272. if ($order['pink_id'] || $order['combination_id']) {
  1273. $order_pink_time = $systemValue['order_pink_time'] ? $systemValue['order_pink_time'] : $systemValue['order_activity_time'];
  1274. $time = bcadd($order['add_time'], $order_pink_time * 3600, 0);
  1275. $status['_msg'] = '请在' . date('m-d H:i:s', $time) . '前完成支付!';
  1276. } else if ($order['seckill_id']) {
  1277. $order_seckill_time = $systemValue['order_seckill_time'] ? $systemValue['order_seckill_time'] : $systemValue['order_activity_time'];
  1278. $time = bcadd($order['add_time'], $order_seckill_time * 3600, 0);
  1279. $status['_msg'] = '请在' . date('m-d H:i:s', $time) . '前完成支付!';
  1280. } else if ($order['bargain_id']) {
  1281. $order_bargain_time = $systemValue['order_bargain_time'] ? $systemValue['order_bargain_time'] : $systemValue['order_activity_time'];
  1282. $time = bcadd($order['add_time'], $order_bargain_time * 3600, 0);
  1283. $status['_msg'] = '请在' . date('m-d H:i:s', $time) . '前完成支付!';
  1284. } else {
  1285. $time = bcadd($order['add_time'], $systemValue['order_cancel_time'] * 3600, 0);
  1286. $status['_msg'] = '请在' . date('m-d H:i:s', $time) . '前完成支付!';
  1287. }
  1288. $status['_class'] = 'nobuy';
  1289. } else if ($order['refund_status'] == 1) {
  1290. $status['_type'] = -1;
  1291. $status['_title'] = '申请退款中';
  1292. $status['_msg'] = '商家审核中,请耐心等待';
  1293. $status['_class'] = 'state-sqtk';
  1294. } else if ($order['refund_status'] == 2) {
  1295. $status['_type'] = -2;
  1296. $status['_title'] = '已退款';
  1297. $status['_msg'] = '已为您退款,感谢您的支持';
  1298. $status['_class'] = 'state-sqtk';
  1299. } else if (!$order['status']) {
  1300. if ($order['pink_id']) {
  1301. if (StorePink::where('id', $order['pink_id'])->where('status', 1)->count()) {
  1302. $status['_type'] = 1;
  1303. $status['_title'] = '拼团中';
  1304. $status['_msg'] = '等待其他人参加拼团';
  1305. $status['_class'] = 'state-nfh';
  1306. } else {
  1307. $status['_type'] = 1;
  1308. $status['_title'] = '未发货';
  1309. $status['_msg'] = '商家未发货,请耐心等待';
  1310. $status['_class'] = 'state-nfh';
  1311. }
  1312. } else {
  1313. if ($order['shipping_type'] === 1) {
  1314. $status['_type'] = 1;
  1315. $status['_title'] = '未发货';
  1316. $status['_msg'] = '商家未发货,请耐心等待';
  1317. $status['_class'] = 'state-nfh';
  1318. } else {
  1319. $status['_type'] = 1;
  1320. $status['_title'] = '待核销';
  1321. $status['_msg'] = '待核销,请到核销点进行核销';
  1322. $status['_class'] = 'state-nfh';
  1323. }
  1324. }
  1325. } else if ($order['status'] == 1) {
  1326. if ($order['delivery_type'] == 'send') {//TODO 送货
  1327. $status['_type'] = 2;
  1328. $status['_title'] = '待收货';
  1329. $status['_msg'] = date('m月d日H时i分', StoreOrderStatus::getTime($order['id'], 'delivery')) . '平台已送货';
  1330. $status['_class'] = 'state-ysh';
  1331. } else {//TODO 发货
  1332. $status['_type'] = 2;
  1333. $status['_title'] = '待收货';
  1334. if ($order['delivery_type'] == 'fictitious')
  1335. $_time = StoreOrderStatus::getTime($order['id'], 'delivery_fictitious');
  1336. else
  1337. $_time = StoreOrderStatus::getTime($order['id'], 'delivery_goods');
  1338. $status['_msg'] = date('m月d日H时i分', $_time) . '平台已发货';
  1339. $status['_class'] = 'state-ysh';
  1340. }
  1341. } else if ($order['status'] == 2) {
  1342. $status['_type'] = 3;
  1343. $status['_title'] = '待评价';
  1344. $status['_msg'] = '已收货,快去评价一下吧';
  1345. $status['_class'] = 'state-ypj';
  1346. } else if ($order['status'] == 3) {
  1347. $status['_type'] = 4;
  1348. $status['_title'] = '交易完成';
  1349. $status['_msg'] = '交易完成,感谢您的支持';
  1350. $status['_class'] = 'state-ytk';
  1351. }
  1352. if (isset($order['pay_type']))
  1353. $status['_payType'] = isset(self::$payType[$order['pay_type']]) ? self::$payType[$order['pay_type']] : '其他方式';
  1354. if (isset($order['delivery_type']))
  1355. $status['_deliveryType'] = isset(self::$deliveryType[$order['delivery_type']]) ? self::$deliveryType[$order['delivery_type']] : '其他方式';
  1356. $order['_status'] = $status;
  1357. $order['_pay_time'] = isset($order['pay_time']) && $order['pay_time'] != null ? date('Y-m-d H:i:s', $order['pay_time']) : date('Y-m-d H:i:s', $order['add_time']);
  1358. $order['_add_time'] = isset($order['add_time']) ? (strstr($order['add_time'], '-') === false ? date('Y-m-d H:i:s', $order['add_time']) : $order['add_time']) : '';
  1359. $order['status_pic'] = '';
  1360. //获取产品状态图片
  1361. if ($isPic) {
  1362. $order_details_images = sys_data('order_details_images') ?: [];
  1363. foreach ($order_details_images as $image) {
  1364. if (isset($image['order_status']) && $image['order_status'] == $order['_status']['_type']) {
  1365. $order['status_pic'] = $image['pic'];
  1366. break;
  1367. }
  1368. }
  1369. }
  1370. $order['offlinePayStatus'] = (int)sys_config('offline_pay_status') ?? (int)2;
  1371. return $order;
  1372. }
  1373. /**
  1374. * 设置订单查询状态
  1375. * @param $status
  1376. * @param int $uid
  1377. * @param null $model
  1378. * @return StoreOrder|null
  1379. */
  1380. public static function statusByWhere($status, $uid = 0, $model = null)
  1381. {
  1382. // $orderId = StorePink::where('uid',$uid)->where('status',1)->column('order_id','id');//获取正在拼团的订单编号
  1383. if ($model == null) $model = new self;
  1384. if ('' === $status)
  1385. return $model;
  1386. else if ($status == 0)//未支付
  1387. return $model->where('paid', 0)->where('status', 0)->where('refund_status', 0);
  1388. else if ($status == 1) {//待发货
  1389. // return $model->where('paid', 1)->where('status', 0)->where('refund_status', 0)->whereIn(
  1390. // 'order_id', function ($query) {
  1391. // $query->name('store_pink')->where('status', 2)->field('order_id')->select();
  1392. // }
  1393. // );
  1394. return $model->where('paid', 1)->where('status', 0)->where('refund_status', 0);
  1395. } else if ($status == 2)//待收货
  1396. return $model->where('paid', 1)->where('status', 1)->where('refund_status', 0);
  1397. else if ($status == 3)//待评价
  1398. return $model->where('paid', 1)->where('status', 2)->where('refund_status', 0);
  1399. else if ($status == 4)//已完成
  1400. return $model->where('paid', 1)->where('status', 3)->where('refund_status', 0);
  1401. else if ($status == -1)//退款中
  1402. return $model->where('paid', 1)->where('refund_status', 1);
  1403. else if ($status == -2)//已退款
  1404. return $model->where('paid', 1)->where('refund_status', 2);
  1405. else if ($status == -3)//退款
  1406. return $model->where('paid', 1)->where('refund_status', 'IN', '1,2');
  1407. // else if($status == 11){
  1408. // return $model->where('order_id','IN',implode(',',$orderId));
  1409. // }
  1410. else
  1411. return $model;
  1412. }
  1413. /**
  1414. * 获取订单并分页
  1415. * @param $uid
  1416. * @param string $status
  1417. * @param int $page
  1418. * @param int $limit
  1419. * @return mixed
  1420. * @throws \think\db\exception\DataNotFoundException
  1421. * @throws \think\db\exception\ModelNotFoundException
  1422. * @throws \think\exception\DbException
  1423. */
  1424. public static function getUserOrderList($uid, $status = '', $page = 0, $limit = 8)
  1425. {
  1426. if ($page) $list = self::statusByWhere($status, $uid)->where('is_del', 0)->where('is_show', 0)->where('uid', $uid)
  1427. ->field('add_time,seckill_id,bargain_id,combination_id,id,order_id,pay_price,total_num,total_price,pay_postage,total_postage,paid,status,refund_status,pay_type,coupon_price,deduction_price,pink_id,delivery_type,is_del,shipping_type')
  1428. ->order('add_time DESC')->page((int)$page, (int)$limit)->select()->toArray();
  1429. else $list = self::statusByWhere($status, $uid)->where('is_del', 0)->where('is_show', 0)->where('uid', $uid)
  1430. ->field('add_time,seckill_id,bargain_id,combination_id,id,order_id,pay_price,total_num,total_price,pay_postage,total_postage,paid,status,refund_status,pay_type,coupon_price,deduction_price,pink_id,delivery_type,is_del,shipping_type')
  1431. ->order('add_time DESC')->page((int)$page, (int)$limit)->select()->toArray();
  1432. foreach ($list as $k => $order) {
  1433. $list[$k] = self::tidyOrder($order, true);
  1434. }
  1435. return $list;
  1436. }
  1437. /**
  1438. * 获取推广人地下用户的订单金额
  1439. * @param string $uid
  1440. * @param string $status
  1441. * @return array
  1442. */
  1443. public static function getUserOrderCount($uid = '', $status = '')
  1444. {
  1445. $res = self::statusByWhere($status, $uid)->where('uid', 'IN', $uid)->column('pay_price');
  1446. return $res;
  1447. }
  1448. /**
  1449. * 搜索某个订单详细信息
  1450. * @param $uid
  1451. * @param $order_id
  1452. * @return bool|mixed
  1453. * @throws \think\db\exception\DataNotFoundException
  1454. * @throws \think\db\exception\ModelNotFoundException
  1455. * @throws \think\exception\DbException
  1456. */
  1457. public static function searchUserOrder($uid, $order_id)
  1458. {
  1459. $order = self::where('uid', $uid)->where('order_id', $order_id)->where('is_del', 0)->where('is_show', 0)->field('seckill_id,bargain_id,combination_id,id,order_id,pay_price,total_num,total_price,pay_postage,total_postage,paid,status,refund_status,pay_type,coupon_price,deduction_price,delivery_type,shipping_type')
  1460. ->order('add_time DESC')->find();
  1461. if (!$order)
  1462. return false;
  1463. else
  1464. return self::tidyOrder($order->toArray(), true);
  1465. }
  1466. /**
  1467. * 订单评价信息记录
  1468. * @param $oid
  1469. * @return StoreOrderStatus|\think\Model
  1470. * @throws \Exception
  1471. */
  1472. public static function orderOver($oid)
  1473. {
  1474. $res = self::edit(['status' => '3'], $oid, 'id');
  1475. if (!$res) exception('评价后置操作失败!');
  1476. return StoreOrderStatus::status($oid, 'check_order_over', '用户评价');
  1477. }
  1478. /**
  1479. * 设置订单产品评价完毕事件
  1480. * @param $oid
  1481. * @return StoreOrderStatus|\think\Model
  1482. * @throws \Exception
  1483. */
  1484. public static function checkOrderOver($oid)
  1485. {
  1486. $uniqueList = StoreOrderCartInfo::where('oid', $oid)->column('unique', 'unique');
  1487. //订单产品全部评价完成
  1488. if (StoreProductReply::where('unique', 'IN', $uniqueList)->where('oid', $oid)->count() == count($uniqueList)) {
  1489. event('StoreProductOrderOver', [$oid]);
  1490. return self::orderOver($oid);
  1491. }
  1492. }
  1493. public static function getOrderStatusNum($uid)
  1494. {
  1495. $noBuy = (int)self::where('uid', $uid)->where('paid', 0)->where('is_del', 0)->where('pay_type', '<>', 'offline')->count();
  1496. $noPostageNoPink = (int)self::where('o.uid', $uid)->alias('o')->where('o.paid', 1)->where('o.pink_id', 0)->where('o.is_del', 0)->where('o.status', 0)->where('o.pay_type', '<>', 'offline')->count();
  1497. $noPostageYesPink = (int)self::where('o.uid', $uid)->alias('o')->join('StorePink p', 'o.pink_id = p.id')->where('p.status', 2)->where('o.paid', 1)->where('o.is_del', 0)->where('o.status', 0)->where('o.pay_type', '<>', 'offline')->count();
  1498. $noPostage = (int)bcadd($noPostageNoPink, $noPostageYesPink, 0);
  1499. $noTake = (int)self::where('uid', $uid)->where('paid', 1)->where('is_del', 0)->where('status', 1)->where('pay_type', '<>', 'offline')->count();
  1500. $noReply = (int)self::where('uid', $uid)->where('paid', 1)->where('is_del', 0)->where('status', 2)->count();
  1501. $noPink = (int)self::where('o.uid', $uid)->alias('o')->join('StorePink p', 'o.pink_id = p.id')->where('p.status', 1)->where('o.paid', 1)->where('o.is_del', 0)->where('o.status', 0)->where('o.pay_type', '<>', 'offline')->count();
  1502. $noRefund = (int)self::where('uid', $uid)->where('paid', 1)->where('is_del', 0)->where('refund_status', 'IN', '1,2')->count();
  1503. return compact('noBuy', 'noPostage', 'noTake', 'noReply', 'noPink', 'noRefund');
  1504. }
  1505. /**
  1506. * 购买商品赠送积分
  1507. * @param $order
  1508. * @return bool
  1509. * @throws \think\Exception
  1510. * @throws \think\db\exception\DataNotFoundException
  1511. * @throws \think\db\exception\ModelNotFoundException
  1512. * @throws \think\exception\DbException
  1513. */
  1514. public static function gainUserIntegral($order)
  1515. {
  1516. if ($order['gain_integral'] > 0) {
  1517. $userInfo = User::getUserInfo($order['uid']);
  1518. BaseModel::beginTrans();
  1519. $res1 = false != User::where('uid', $userInfo['uid'])->update(['integral' => bcadd($userInfo['integral'], $order['gain_integral'], 2)]);
  1520. $res2 = false != UserBill::income('购买商品赠送贡献值', $order['uid'], 'integral', 'gain', $order['gain_integral'], $order['id'], $userInfo['integral'], '购买商品赠送' . floatval($order['gain_integral']) . '贡献值');
  1521. $res = $res1 && $res2;
  1522. BaseModel::checkTrans($res);
  1523. return $res;
  1524. }
  1525. return true;
  1526. }
  1527. /**
  1528. * 获取当前订单中有没有拼团存在
  1529. * @param $pid
  1530. * @return int|string
  1531. */
  1532. public static function getIsOrderPink($pid = 0, $uid = 0)
  1533. {
  1534. return self::where('uid', $uid)->where('pink_id', $pid)->where('refund_status', 0)->where('is_del', 0)->count();
  1535. }
  1536. /**
  1537. * 获取order_id
  1538. * @param $pid
  1539. * @return mixed
  1540. */
  1541. public static function getStoreIdPink($pid = 0, $uid = 0)
  1542. {
  1543. return self::where('uid', $uid)->where('pink_id', $pid)->where('is_del', 0)->value('order_id');
  1544. }
  1545. /**
  1546. * 删除当前用户拼团未支付的订单
  1547. */
  1548. public static function delCombination()
  1549. {
  1550. self::where('combination', '>', 0)->where('paid', 0)->where('uid', User::getActiveUid())->delete();
  1551. }
  1552. public static function getUserPrice($uid = 0)
  1553. {
  1554. if (!$uid) return 0;
  1555. $price = self::where('paid', 1)->where('uid', $uid)->where('status', 2)->where('refund_status', 0)->column('pay_price', 'id');
  1556. $count = 0;
  1557. if ($price) {
  1558. foreach ($price as $v) {
  1559. $count = bcadd($count, $v, 2);
  1560. }
  1561. }
  1562. return $count;
  1563. }
  1564. /**
  1565. * 个人中心获取个人订单列表和订单搜索
  1566. * @param int $uid 用户uid
  1567. * @param int | string 查找订单类型
  1568. * @param int $first 分页
  1569. * @param int 每页显示多少条
  1570. * @param string $search 订单号
  1571. * @return array
  1572. * */
  1573. public static function getUserOrderSearchList($uid, $type, $page, $limit, $search)
  1574. {
  1575. if ($search) {
  1576. $order = self::searchUserOrder($uid, $search) ?: [];
  1577. $list = $order == false ? [] : [$order];
  1578. } else {
  1579. $list = self::getUserOrderList($uid, $type, $page, $limit);
  1580. }
  1581. foreach ($list as $k => $order) {
  1582. $list[$k] = self::tidyOrder($order, true);
  1583. if ($list[$k]['_status']['_type'] == 3) {
  1584. foreach ($order['cartInfo'] ?: [] as $key => $product) {
  1585. $list[$k]['cartInfo'][$key]['is_reply'] = StoreProductReply::isReply($product['unique'], 'product');
  1586. $list[$k]['cartInfo'][$key]['add_time'] = isset($product['add_time']) ? date('Y-m-d H:i', $product['add_time']) : '时间错误';
  1587. }
  1588. }
  1589. }
  1590. return $list;
  1591. }
  1592. /**
  1593. * 获取用户下级的订单
  1594. * @param int $xuid 下级用户用户uid
  1595. * @param int $uid 用户uid
  1596. * @param int $type 订单类型
  1597. * @param int $first 截取行数
  1598. * @param int $limit 展示条数
  1599. * @return array
  1600. * */
  1601. public static function getSubordinateOrderlist($xUid, $uid, $type, $first, $limit)
  1602. {
  1603. $list = [];
  1604. if (!$xUid) {
  1605. $arr = User::getOneSpreadUid($uid);
  1606. foreach ($arr as $v) $list = StoreOrder::getUserOrderList($v, $type, $first, $limit);
  1607. } else $list = self::getUserOrderList($xUid, $type, $first, $limit);
  1608. foreach ($list as $k => $order) {
  1609. $list[$k] = self::tidyOrder($order, true);
  1610. if ($list[$k]['_status']['_type'] == 3) {
  1611. foreach ($order['cartInfo'] ?: [] as $key => $product) {
  1612. $list[$k]['cartInfo'][$key]['is_reply'] = StoreProductReply::isReply($product['unique'], 'product');
  1613. }
  1614. }
  1615. }
  1616. return $list;
  1617. }
  1618. /**
  1619. * 获取 今日 昨日 本月 订单金额
  1620. * @return mixed
  1621. */
  1622. public static function getOrderTimeData()
  1623. {
  1624. $to_day = strtotime(date('Y-m-d'));//今日
  1625. $pre_day = strtotime(date('Y-m-d', strtotime('-1 day')));//昨日
  1626. $now_month = strtotime(date('Y-m'));//本月
  1627. //今日成交额
  1628. // $data['todayPrice'] = (float)number_format(self::where('is_del', 0)->where('pay_time', '>=', $to_day)->where('paid', 1)->where('refund_status', 0)->value('sum(pay_price)'), 2) ?? 0;
  1629. $data['todayPrice'] = number_format(self::where('is_del', 0)->where('pay_time', '>=', $to_day)->where('paid', 1)->where('refund_status', 0)->value('sum(pay_price)'), 2) ?? 0;
  1630. //今日订单数
  1631. $data['todayCount'] = self::where('is_del', 0)->where('pay_time', '>=', $to_day)->where('paid', 1)->where('refund_status', 0)->count();
  1632. //昨日成交额
  1633. $data['proPrice'] = number_format(self::where('is_del', 0)->where('pay_time', '<', $to_day)->where('pay_time', '>=', $pre_day)->where('paid', 1)->where('refund_status', 0)->value('sum(pay_price)'), 2) ?? 0;
  1634. //昨日订单数
  1635. $data['proCount'] = self::where('is_del', 0)->where('pay_time', '<', $to_day)->where('pay_time', '>=', $pre_day)->where('paid', 1)->where('refund_status', 0)->count();
  1636. //本月成交额
  1637. $data['monthPrice'] = number_format(self::where('is_del', 0)->where('pay_time', '>=', $now_month)->where('paid', 1)->where('refund_status', 0)->value('sum(pay_price)'), 2) ?? 0;
  1638. //本月订单数
  1639. $data['monthCount'] = self::where('is_del', 0)->where('pay_time', '>=', $now_month)->where('paid', 1)->where('refund_status', 0)->count();
  1640. return $data;
  1641. }
  1642. /**
  1643. * 获取某个用户的订单统计数据
  1644. * @param $uid
  1645. * @return mixed
  1646. */
  1647. public static function getOrderData($uid)
  1648. {
  1649. //订单支付没有退款 数量
  1650. $data['order_count'] = self::where('is_del', 0)->where('paid', 1)->where('uid', $uid)->where('refund_status', 0)->count();
  1651. //订单支付没有退款 支付总金额
  1652. $data['sum_price'] = self::where('is_del', 0)->where('paid', 1)->where('uid', $uid)->where('refund_status', 0)->sum('pay_price');
  1653. //订单待支付 数量
  1654. $data['unpaid_count'] = self::statusByWhere(0, $uid)->where('is_del', 0)->where('uid', $uid)->count();
  1655. //订单待发货 数量
  1656. $data['unshipped_count'] = self::statusByWhere(1, $uid)->where('is_del', 0)->where('uid', $uid)->count();
  1657. //订单待收货 数量
  1658. $data['received_count'] = self::statusByWhere(2, $uid)->where('is_del', 0)->where('uid', $uid)->count();
  1659. //订单待评价 数量
  1660. $data['evaluated_count'] = self::statusByWhere(3, $uid)->where('is_del', 0)->where('uid', $uid)->count();
  1661. //订单已完成 数量
  1662. $data['complete_count'] = self::statusByWhere(4, $uid)->where('is_del', 0)->where('uid', $uid)->count();
  1663. //订单退款
  1664. $data['refund_count'] = self::statusByWhere(-1, $uid)->where('is_del', 0)->where('uid', $uid)->count();
  1665. return $data;
  1666. }
  1667. /**
  1668. * 获取订单统计数据
  1669. * @param $uid
  1670. * @return mixed
  1671. */
  1672. public static function getOrderDataAdmin()
  1673. {
  1674. //订单支付没有退款 数量
  1675. $data['order_count'] = self::where('is_del', 0)->where('paid', 1)->where('refund_status', 0)->count();
  1676. //订单支付没有退款 支付总金额
  1677. $data['sum_price'] = self::where('is_del', 0)->where('paid', 1)->where('refund_status', 0)->sum('pay_price');
  1678. //订单待支付 数量
  1679. $data['unpaid_count'] = self::statusByWhere(0, 0)->where('is_del', 0)->count();
  1680. //订单待发货 数量
  1681. $data['unshipped_count'] = self::statusByWhere(1, 0)->where('is_del', 0)->count();
  1682. //订单待收货 数量
  1683. $data['received_count'] = self::statusByWhere(2, 0)->where('is_del', 0)->count();
  1684. //订单待评价 数量
  1685. $data['evaluated_count'] = self::statusByWhere(3, 0)->where('is_del', 0)->count();
  1686. //订单已完成 数量
  1687. $data['complete_count'] = self::statusByWhere(4, 0)->where('is_del', 0)->count();
  1688. //订单退款 数量
  1689. $data['refund_count'] = self::statusByWhere(-3, 0)->where('is_del', 0)->count();
  1690. return $data;
  1691. }
  1692. /**
  1693. * 累计消费
  1694. * @param $uid
  1695. * @return float
  1696. */
  1697. public static function getOrderStatusSum($uid)
  1698. {
  1699. return self::where('uid', $uid)->where('is_del', 0)->where('paid', 1)->sum('pay_price');
  1700. }
  1701. public static function getPinkOrderId($id)
  1702. {
  1703. return self::where('id', $id)->value('order_id');
  1704. }
  1705. /**
  1706. * 未支付订单自动取消
  1707. * @param int $limit 分页截取条数
  1708. * @param string $prefid 缓存名称
  1709. * @param int $expire 缓存时间
  1710. * @return string|null
  1711. * @throws \Psr\SimpleCache\InvalidArgumentException
  1712. */
  1713. public static function orderUnpaidCancel()
  1714. {
  1715. //系统预设取消订单时间段
  1716. $keyValue = ['order_cancel_time', 'order_activity_time', 'order_bargain_time', 'order_seckill_time', 'order_pink_time'];
  1717. //获取配置
  1718. $systemValue = SystemConfigService::more($keyValue);
  1719. //格式化数据
  1720. $systemValue = self::setValeTime($keyValue, is_array($systemValue) ? $systemValue : []);
  1721. //检查是否有未支付的订单 未支付查询条件
  1722. $unPidCount = self::where('paid', 0)->where('pay_type', '<>', 'offline')->where('is_del', 0)->where('status', 0)->where('refund_status', 0)->count();
  1723. if (!$unPidCount) return null;
  1724. try {
  1725. $res = true;
  1726. // 未支付查询条件
  1727. $orderList = self::where('paid', 0)->where('pay_type', '<>', 'offline')->where('is_del', 0)->where('status', 0)->where('refund_status', 0)->field('add_time,pink_id,order_id,seckill_id,bargain_id,combination_id,status,cart_id,use_integral,refund_status,uid,unique,back_integral,coupon_id,paid,is_del')->select();
  1728. foreach ($orderList as $order) {
  1729. if ($order['seckill_id']) {
  1730. //优先使用单独配置的过期时间
  1731. $order_seckill_time = $systemValue['order_seckill_time'] ? $systemValue['order_seckill_time'] : $systemValue['order_activity_time'];
  1732. $res = $res && self::RegressionAll($order_seckill_time, $order);
  1733. unset($order_seckill_time);
  1734. } else if ($order['bargain_id']) {
  1735. $order_bargain_time = $systemValue['order_bargain_time'] ? $systemValue['order_bargain_time'] : $systemValue['order_activity_time'];
  1736. $res = $res && self::RegressionAll($order_bargain_time, $order);
  1737. unset($order_bargain_time);
  1738. } else if ($order['pink_id'] || $order['combination_id']) {
  1739. $order_pink_time = $systemValue['order_pink_time'] ? $systemValue['order_pink_time'] : $systemValue['order_activity_time'];
  1740. $res = $res && self::RegressionAll($order_pink_time, $order);
  1741. unset($order_pink_time);
  1742. } else {
  1743. $res = $res && self::RegressionAll($systemValue['order_cancel_time'], $order);
  1744. }
  1745. }
  1746. if (!$res) throw new \Exception('更新错误');
  1747. unset($orderList, $res, $pages);
  1748. return null;
  1749. } catch (PDOException $e) {
  1750. Log::error('未支付自动取消时发生数据库查询错误,错误原因为:' . $e->getMessage());
  1751. throw new \Exception($e->getMessage());
  1752. } catch (\think\Exception $e) {
  1753. Log::error('未支付自动取消时发生系统错误,错误原因为:' . $e->getMessage());
  1754. throw new \Exception($e->getMessage());
  1755. }
  1756. }
  1757. /**
  1758. * 未支付订单超过预设时间回退所有,如果不设置未支付过期时间,将不取消订单
  1759. * @param $time 预设时间
  1760. * @param $order 订单详情
  1761. * @return bool
  1762. * @throws \think\db\exception\DataNotFoundException
  1763. * @throws \think\db\exception\ModelNotFoundException
  1764. * @throws \think\exception\DbException
  1765. */
  1766. protected static function RegressionAll($time, $order)
  1767. {
  1768. if ($time == 0) return true;
  1769. if (($order['add_time'] + bcmul($time, 3600, 0)) < time()) {
  1770. $res1 = self::RegressionStock($order);
  1771. $res2 = self::RegressionIntegral($order);
  1772. $res3 = self::RegressionCoupon($order);
  1773. $res = $res1 && $res2 && $res3;
  1774. if ($res) $res = false !== self::where('order_id', $order['order_id'])->update(['is_del' => 1, 'mark' => '订单未支付已超过系统预设时间']);
  1775. unset($res1, $res2, $res3);
  1776. return $res;
  1777. } else
  1778. return true;
  1779. }
  1780. /**
  1781. * 格式化数据
  1782. * @param array $array 原本数据键
  1783. * @param $value 需要格式化的数据
  1784. * @param int $default 默认值
  1785. * @return mixed
  1786. */
  1787. protected static function setValeTime(array $array, $value, $default = 0)
  1788. {
  1789. foreach ($array as $item) {
  1790. if (!isset($value[$item]))
  1791. $value[$item] = $default;
  1792. else if (is_string($value[$item]))
  1793. $value[$item] = (float)$value[$item];
  1794. }
  1795. return $value;
  1796. }
  1797. public static function getOrderTotalPrice($cartInfo)
  1798. {
  1799. $totalPrice = 0;
  1800. foreach ($cartInfo as $cart) {
  1801. $totalPrice = bcadd($totalPrice, bcmul($cart['cart_num'], $cart['truePrice'], 2), 2);
  1802. }
  1803. return $totalPrice;
  1804. }
  1805. public static function getOrderCostPrice($cartInfo)
  1806. {
  1807. $costPrice = 0;
  1808. foreach ($cartInfo as $cart) {
  1809. $costPrice = bcadd($costPrice, bcmul($cart['cart_num'], $cart['costPrice'], 2), 2);
  1810. }
  1811. return $costPrice;
  1812. }
  1813. public static function getCombinationOrderCostPrice($cartInfo)
  1814. {
  1815. $costPrice = 0;
  1816. foreach ($cartInfo as $cart) {
  1817. if ($cart['combination_id']) {
  1818. $costPrice = bcadd($costPrice, bcmul($cart['cart_num'], StoreCombination::where('id', $cart['combination_id'])->value('price'), 2), 2);
  1819. }
  1820. }
  1821. return (float)$costPrice;
  1822. }
  1823. public static function yueRefundAfter($order)
  1824. {
  1825. }
  1826. /**
  1827. * 获取余额支付的金额
  1828. * @param $uid
  1829. * @return float|int
  1830. */
  1831. public static function getOrderStatusYueSum($uid)
  1832. {
  1833. return self::where('uid', $uid)->where('is_del', 0)->where('is_del', 0)->where('pay_type', 'yue')->where('paid', 1)->sum('pay_price');
  1834. }
  1835. /**
  1836. * 砍价支付成功订单数量
  1837. * @param $bargain
  1838. * @return int
  1839. */
  1840. public static function getBargainPayCount($bargain)
  1841. {
  1842. return self::where('bargain_id', $bargain)->where(['paid' => 1, 'refund_status' => 0])->count();
  1843. }
  1844. /**
  1845. * 7天自动收货
  1846. */
  1847. public static function startTakeOrder()
  1848. {
  1849. //7天前时间戳
  1850. $systemDeliveryTime = sys_config('system_delivery_time') ?? 0;
  1851. //0为取消自动收货功能
  1852. if ($systemDeliveryTime == 0) return true;
  1853. $sevenDay = strtotime(date('Y-m-d H:i:s', strtotime('-' . $systemDeliveryTime . ' day')));
  1854. $model = new self;
  1855. $model = $model->alias('o');
  1856. $model = $model->join('StoreOrderStatus s', 's.oid=o.id');
  1857. $model = $model->where('o.paid', 1);
  1858. $model = $model->where('s.change_type', 'delivery_goods');
  1859. $model = $model->where('s.change_time', '<', $sevenDay);
  1860. $model = $model->where('o.status', 1);
  1861. $model = $model->where('o.refund_status', 0);
  1862. $model = $model->where('o.is_del', 0);
  1863. $orderInfo = $model->column('id', 'id');
  1864. if (!count($orderInfo)) return true;
  1865. foreach ($orderInfo as $key => &$item) {
  1866. $order = self::get($item);
  1867. if ($order['status'] == 2) continue;
  1868. if ($order['paid'] == 1 && $order['status'] == 1) $data['status'] = 2;
  1869. else if ($order['pay_type'] == 'offline') $data['status'] = 2;
  1870. else continue;
  1871. if (!self::edit($data, $item, 'id')) continue;
  1872. try {
  1873. OrderRepository::storeProductOrderTakeDeliveryTimer($order);
  1874. } catch (\Exception $e) {
  1875. continue;
  1876. }
  1877. StoreOrderStatus::status($item, 'take_delivery', '已收货[自动收货]');
  1878. }
  1879. }
  1880. /**
  1881. * 获取订单信息
  1882. * @param $id
  1883. * @param string $field
  1884. * @return array|null|\think\Model
  1885. * @throws \think\db\exception\DataNotFoundException
  1886. * @throws \think\db\exception\ModelNotFoundException
  1887. * @throws \think\exception\DbException
  1888. */
  1889. public static function getOrderInfo($id, $field = 'order_id')
  1890. {
  1891. return self::where('id', $id)->field($field)->find();
  1892. }
  1893. /**
  1894. * 订单每月统计数据
  1895. * @param $page
  1896. * @param $limit
  1897. * @return array
  1898. */
  1899. public static function getOrderDataPriceCount($page, $limit, $start, $stop)
  1900. {
  1901. if (!$limit) return [];
  1902. $model = new self;
  1903. if ($start != '' && $stop != '') $model = $model->where('pay_time', '>', $start)->where('pay_time', '<=', $stop);
  1904. $model = $model->field('sum(pay_price) as price,count(id) as count,FROM_UNIXTIME(pay_time, \'%m-%d\') as time');
  1905. $model = $model->where('is_del', 0);
  1906. $model = $model->where('paid', 1);
  1907. $model = $model->where('refund_status', 0);
  1908. $model = $model->group("FROM_UNIXTIME(pay_time, '%Y-%m-%d')");
  1909. $model = $model->order('pay_time DESC');
  1910. if ($page) $model = $model->page($page, $limit);
  1911. return $model->select();
  1912. }
  1913. /**
  1914. * 前台订单管理订单列表获取
  1915. * @param $where
  1916. * @return mixed
  1917. */
  1918. public static function orderList($where)
  1919. {
  1920. $model = self::getOrderWhere($where, self::alias('a')->join('user r', 'r.uid=a.uid', 'LEFT'), 'a.', 'r')->field('a.id,a.order_id,a.add_time,a.status,a.total_num,a.total_price,a.total_postage,a.pay_price,a.pay_postage,a.paid,a.refund_status,a.remark,a.pay_type');
  1921. if ($where['order'] != '') {
  1922. $model = $model->order(self::setOrder($where['order']));
  1923. } else {
  1924. $model = $model->order('a.id desc');
  1925. }
  1926. $data = ($data = $model->page((int)$where['page'], (int)$where['limit'])->select()) && count($data) ? $data->toArray() : [];
  1927. return self::tidyAdminOrder($data);
  1928. }
  1929. /**
  1930. * 前台订单管理 订单信息设置
  1931. * @param $data
  1932. * @param bool $status
  1933. * @return mixed
  1934. * @throws \think\db\exception\DataNotFoundException
  1935. * @throws \think\db\exception\ModelNotFoundException
  1936. * @throws \think\exception\DbException
  1937. */
  1938. public static function tidyAdminOrder($data, $status = false)
  1939. {
  1940. foreach ($data as &$item) {
  1941. $_info = StoreOrderCartInfo::where('oid', $item['id'])->field('cart_info')->select()->toArray();
  1942. foreach ($_info as $k => $v) {
  1943. if (!is_array($v['cart_info']))
  1944. $_info[$k]['cart_info'] = json_decode($v['cart_info'], true);
  1945. }
  1946. foreach ($_info as $k => $v) {
  1947. unset($_info[$k]['cart_info']['type'], $_info[$k]['cart_info']['product_id'], $_info[$k]['cart_info']['combination_id'], $_info[$k]['cart_info']['seckill_id'], $_info[$k]['cart_info']['bargain_id'], $_info[$k]['cart_info']['bargain_id'], $_info[$k]['cart_info']['truePrice'], $_info[$k]['cart_info']['vip_truePrice'], $_info[$k]['cart_info']['trueStock'], $_info[$k]['cart_info']['costPrice'], $_info[$k]['cart_info']['productInfo']['id'], $_info[$k]['cart_info']['productInfo']['vip_price'], $_info[$k]['cart_info']['productInfo']['postage'], $_info[$k]['cart_info']['productInfo']['give_integral'], $_info[$k]['cart_info']['productInfo']['sales'], $_info[$k]['cart_info']['productInfo']['stock'], $_info[$k]['cart_info']['productInfo']['unit_name'], $_info[$k]['cart_info']['productInfo']['is_postage'], $_info[$k]['cart_info']['productInfo']['slider_image'], $_info[$k]['cart_info']['productInfo']['cost'], $_info[$k]['cart_info']['productInfo']['mer_id'], $_info[$k]['cart_info']['productInfo']['cate_id'], $_info[$k]['cart_info']['productInfo']['is_show'], $_info[$k]['cart_info']['productInfo']['store_info'], $_info[$k]['cart_info']['productInfo']['is_del'], $_info[$k]['cart_info']['is_pay'], $_info[$k]['cart_info']['is_del'], $_info[$k]['cart_info']['is_new'], $_info[$k]['cart_info']['add_time'], $_info[$k]['cart_info']['id'], $_info[$k]['cart_info']['uid'], $_info[$k]['cart_info']['product_attr_unique']);
  1948. $_info[$k]['cart_info']['productInfo']['suk'] = '';
  1949. if (isset($v['cart_info']['productInfo']['attrInfo'])) {
  1950. $_info[$k]['cart_info']['productInfo']['image'] = $_info[$k]['cart_info']['productInfo']['attrInfo']['image'];
  1951. $_info[$k]['cart_info']['productInfo']['price'] = $_info[$k]['cart_info']['productInfo']['attrInfo']['price'];
  1952. $_info[$k]['cart_info']['productInfo']['suk'] = $_info[$k]['cart_info']['productInfo']['attrInfo']['suk'];
  1953. unset($_info[$k]['cart_info']['productInfo']['attrInfo']);
  1954. }
  1955. if (!isset($v['cart_info']['productInfo']['ot_price'])) {
  1956. $_info[$k]['cart_info']['productInfo']['ot_price'] = $v['cart_info']['productInfo']['price'];
  1957. }
  1958. }
  1959. $item['_info'] = $_info;
  1960. $item['add_time'] = date('Y-m-d H:i:s', $item['add_time']);
  1961. // if($item['pink_id'] || $item['combination_id']){
  1962. // $pinkStatus = StorePink::where('order_id_key',$item['id'])->value('status');
  1963. // switch ($pinkStatus){
  1964. // case 1:
  1965. // $item['pink_name'] = '[拼团订单]正在进行中';
  1966. // $item['color'] = '#f00';
  1967. // break;
  1968. // case 2:
  1969. // $item['pink_name'] = '[拼团订单]已完成';
  1970. // $item['color'] = '#00f';
  1971. // break;
  1972. // case 3:
  1973. // $item['pink_name'] = '[拼团订单]未完成';
  1974. // $item['color'] = '#f0f';
  1975. // break;
  1976. // default:
  1977. // $item['pink_name'] = '[拼团订单]历史订单';
  1978. // $item['color'] = '#457856';
  1979. // break;
  1980. // }
  1981. // }elseif ($item['seckill_id']){
  1982. // $item['pink_name'] = '[秒杀订单]';
  1983. // $item['color'] = '#32c5e9';
  1984. // }elseif ($item['bargain_id']){
  1985. // $item['pink_name'] = '[砍价订单]';
  1986. // $item['color'] = '#12c5e9';
  1987. // }else{
  1988. // $item['pink_name'] = '[普通订单]';
  1989. // $item['color'] = '#895612';
  1990. // }
  1991. // if($item['paid']==1){
  1992. // switch ($item['pay_type']){
  1993. // case 'weixin':
  1994. // $item['pay_type_name']='微信支付';
  1995. // break;
  1996. // case 'yue':
  1997. // $item['pay_type_name']='余额支付';
  1998. // break;
  1999. // case 'offline':
  2000. // $item['pay_type_name']='线下支付';
  2001. // break;
  2002. // default:
  2003. // $item['pay_type_name']='其他支付';
  2004. // break;
  2005. // }
  2006. // }else{
  2007. // switch ($item['pay_type']){
  2008. // default:
  2009. // $item['pay_type_name']='未支付';
  2010. // break;
  2011. // case 'offline':
  2012. // $item['pay_type_name']='线下支付';
  2013. // $item['pay_type_info']=1;
  2014. // break;
  2015. // }
  2016. // }
  2017. if ($status) {
  2018. $status = [];
  2019. if (!$item['paid'] && $item['pay_type'] == 'offline' && !$item['status'] >= 2) {
  2020. $status['_type'] = 9;
  2021. $status['_title'] = '线下付款';
  2022. $status['_msg'] = '商家处理中,请耐心等待';
  2023. $status['_class'] = 'nobuy';
  2024. } else if (!$item['paid']) {
  2025. $status['_type'] = 0;
  2026. $status['_title'] = '未支付';
  2027. //系统预设取消订单时间段
  2028. $keyValue = ['order_cancel_time', 'order_activity_time', 'order_bargain_time', 'order_seckill_time', 'order_pink_time'];
  2029. //获取配置
  2030. $systemValue = SystemConfigService::more($keyValue);
  2031. //格式化数据
  2032. $systemValue = self::setValeTime($keyValue, is_array($systemValue) ? $systemValue : []);
  2033. if ($item['pink_id'] || $item['combination_id']) {
  2034. $order_pink_time = $systemValue['order_pink_time'] ? $systemValue['order_pink_time'] : $systemValue['order_activity_time'];
  2035. $time = bcadd($item['add_time'], $order_pink_time * 3600, 0);
  2036. $status['_msg'] = '请在' . date('Y-m-d H:i:s', $time) . '前完成支付!';
  2037. } else if ($item['seckill_id']) {
  2038. $order_seckill_time = $systemValue['order_seckill_time'] ? $systemValue['order_seckill_time'] : $systemValue['order_activity_time'];
  2039. $time = bcadd($item['add_time'], $order_seckill_time * 3600, 0);
  2040. $status['_msg'] = '请在' . date('Y-m-d H:i:s', $time) . '前完成支付!';
  2041. } else if ($item['bargain_id']) {
  2042. $order_bargain_time = $systemValue['order_bargain_time'] ? $systemValue['order_bargain_time'] : $systemValue['order_activity_time'];
  2043. $time = bcadd($item['add_time'], $order_bargain_time * 3600, 0);
  2044. $status['_msg'] = '请在' . date('Y-m-d H:i:s', $time) . '前完成支付!';
  2045. } else {
  2046. $time = bcadd($item['add_time'], $systemValue['order_cancel_time'] * 3600, 0);
  2047. $status['_msg'] = '请在' . date('Y-m-d H:i:s', $time) . '前完成支付!';
  2048. }
  2049. $status['_class'] = 'nobuy';
  2050. } else if ($item['refund_status'] == 1) {
  2051. $status['_type'] = -1;
  2052. $status['_title'] = '申请退款中';
  2053. $status['_msg'] = '商家审核中,请耐心等待';
  2054. $status['_class'] = 'state-sqtk';
  2055. } else if ($item['refund_status'] == 2) {
  2056. $status['_type'] = -2;
  2057. $status['_title'] = '已退款';
  2058. $status['_msg'] = '已为您退款,感谢您的支持';
  2059. $status['_class'] = 'state-sqtk';
  2060. } else if (!$item['status']) {
  2061. if ($item['pink_id']) {
  2062. if (StorePink::where('id', $item['pink_id'])->where('status', 1)->count()) {
  2063. $status['_type'] = 11;
  2064. $status['_title'] = '拼团中';
  2065. $status['_msg'] = '等待其他人参加拼团';
  2066. $status['_class'] = 'state-nfh';
  2067. } else {
  2068. $status['_type'] = 1;
  2069. $status['_title'] = '未发货';
  2070. $status['_msg'] = '商家未发货,请耐心等待';
  2071. $status['_class'] = 'state-nfh';
  2072. }
  2073. } else {
  2074. $status['_type'] = 1;
  2075. $status['_title'] = '未发货';
  2076. $status['_msg'] = '商家未发货,请耐心等待';
  2077. $status['_class'] = 'state-nfh';
  2078. }
  2079. } else if ($item['status'] == 1) {
  2080. if ($item['delivery_type'] == 'send') {//TODO 送货
  2081. $status['_type'] = 2;
  2082. $status['_title'] = '待收货';
  2083. $status['_msg'] = date('m月d日H时i分', StoreOrderStatus::getTime($item['id'], 'delivery')) . '平台已送货';
  2084. $status['_class'] = 'state-ysh';
  2085. } else {//TODO 发货
  2086. $status['_type'] = 2;
  2087. $status['_title'] = '待收货';
  2088. $status['_msg'] = date('m月d日H时i分', StoreOrderStatus::getTime($item['id'], 'delivery_goods')) . '平台已发货';
  2089. $status['_class'] = 'state-ysh';
  2090. }
  2091. } else if ($item['status'] == 2) {
  2092. $status['_type'] = 3;
  2093. $status['_title'] = '待评价';
  2094. $status['_msg'] = '已收货,快去评价一下吧';
  2095. $status['_class'] = 'state-ypj';
  2096. } else if ($item['status'] == 3) {
  2097. $status['_type'] = 4;
  2098. $status['_title'] = '交易完成';
  2099. $status['_msg'] = '交易完成,感谢您的支持';
  2100. $status['_class'] = 'state-ytk';
  2101. }
  2102. if (isset($item['pay_type']))
  2103. $status['_payType'] = isset(self::$payType[$item['pay_type']]) ? self::$payType[$item['pay_type']] : '其他方式';
  2104. if (isset($item['delivery_type']))
  2105. $status['_deliveryType'] = isset(self::$deliveryType[$item['delivery_type']]) ? self::$deliveryType[$item['delivery_type']] : '其他方式';
  2106. $item['_status'] = $status;
  2107. } else {
  2108. if ($item['paid'] == 0 && $item['status'] == 0) {
  2109. $item['status_name'] = '未支付';
  2110. } else if ($item['paid'] == 1 && $item['status'] == 0 && $item['refund_status'] == 0) {
  2111. $item['status_name'] = '未发货';
  2112. } else if ($item['paid'] == 1 && $item['status'] == 1 && $item['refund_status'] == 0) {
  2113. $item['status_name'] = '待收货';
  2114. } else if ($item['paid'] == 1 && $item['status'] == 2 && $item['refund_status'] == 0) {
  2115. $item['status_name'] = '待评价';
  2116. } else if ($item['paid'] == 1 && $item['status'] == 3 && $item['refund_status'] == 0) {
  2117. $item['status_name'] = '已完成';
  2118. }
  2119. }
  2120. // unset($item['refund_status']);
  2121. // else if($item['paid']==1 && $item['refund_status']==1){
  2122. // $item['status_name']=<<<HTML
  2123. //<b style="color:#f124c7">申请退款</b><br/>
  2124. //<span>退款原因:{$item['refund_reason_wap']}</span>
  2125. //HTML;
  2126. // }else if($item['paid']==1 && $item['refund_status']==2){
  2127. // $item['status_name']='已退款';
  2128. // }
  2129. // if($item['paid']==0 && $item['status']==0 && $item['refund_status']==0){
  2130. // $item['_status']=1;
  2131. // }else if($item['paid']==1 && $item['status']==0 && $item['refund_status']==0){
  2132. // $item['_status']=2;
  2133. // }else if($item['paid']==1 && $item['refund_status']==1){
  2134. // $item['_status']=3;
  2135. // }else if($item['paid']==1 && $item['status']==1 && $item['refund_status']==0){
  2136. // $item['_status']=4;
  2137. // }else if($item['paid']==1 && $item['status']==2 && $item['refund_status']==0){
  2138. // $item['_status']=5;
  2139. // }else if($item['paid']==1 && $item['status']==3 && $item['refund_status']==0){
  2140. // $item['_status']=6;
  2141. // }else if($item['paid']==1 && $item['refund_status']==2){
  2142. // $item['_status']=7;
  2143. // }
  2144. }
  2145. return $data;
  2146. }
  2147. /**
  2148. * 处理where条件
  2149. * @param $where
  2150. * @param $model
  2151. * @param string $aler
  2152. * @param string $join
  2153. * @return StoreOrder|null
  2154. */
  2155. public static function getOrderWhere($where, $model, $aler = '', $join = '')
  2156. {
  2157. if (isset($where['status']) && $where['status'] != '') $model = self::statusWhere($where['status'], $model, $aler);
  2158. if (isset($where['is_del']) && $where['is_del'] != '' && $where['is_del'] != -1) $model = $model->where($aler . 'is_del', $where['is_del']);
  2159. if (isset($where['combination_id'])) {
  2160. if ($where['combination_id'] == '普通订单') {
  2161. $model = $model->where($aler . 'combination_id', 0)->where($aler . 'seckill_id', 0)->where($aler . 'bargain_id', 0);
  2162. }
  2163. if ($where['combination_id'] == '拼团订单') {
  2164. $model = $model->where($aler . 'combination_id', ">", 0)->where($aler . 'pink_id', ">", 0);
  2165. }
  2166. if ($where['combination_id'] == '秒杀订单') {
  2167. $model = $model->where($aler . 'seckill_id', ">", 0);
  2168. }
  2169. if ($where['combination_id'] == '砍价订单') {
  2170. $model = $model->where($aler . 'bargain_id', ">", 0);
  2171. }
  2172. }
  2173. if (isset($where['type'])) {
  2174. switch ($where['type']) {
  2175. case 1:
  2176. $model = $model->where($aler . 'combination_id', 0)->where($aler . 'seckill_id', 0)->where($aler . 'bargain_id', 0);
  2177. break;
  2178. case 2:
  2179. $model = $model->where($aler . 'combination_id', ">", 0);
  2180. break;
  2181. case 3:
  2182. $model = $model->where($aler . 'seckill_id', ">", 0);
  2183. break;
  2184. case 4:
  2185. $model = $model->where($aler . 'bargain_id', ">", 0);
  2186. break;
  2187. }
  2188. }
  2189. if (isset($where['real_name']) && $where['real_name'] != '')
  2190. $model = $model->where($aler . 'order_id|' . $aler . 'real_name|' . $aler . 'user_phone' . ($join ? '|' . $join . '.nickname|' . $join . '.uid' : ''), 'LIKE', "%$where[real_name]%");
  2191. if (isset($where['data']) && $where['data'] !== '')
  2192. $model = self::getModelTime($where, $model, $aler . 'add_time');
  2193. return $model;
  2194. }
  2195. /**
  2196. * 设置where条件
  2197. * @param $status
  2198. * @param null $model
  2199. * @param string $alert
  2200. * @return StoreOrder|null
  2201. */
  2202. public static function statusWhere($status, $model = null, $alert = '')
  2203. {
  2204. if ($model == null) $model = new self;
  2205. if ('' === $status)
  2206. return $model;
  2207. else if ($status == 0)//未支付
  2208. return $model->where($alert . 'paid', 0)->where($alert . 'status', 0)->where($alert . 'refund_status', 0);
  2209. else if ($status == 1)//已支付 未发货
  2210. return $model->where($alert . 'paid', 1)->where($alert . 'status', 0)->where($alert . 'refund_status', 0);
  2211. else if ($status == 2)//已支付 待收货
  2212. return $model->where($alert . 'paid', 1)->where($alert . 'status', 1)->where($alert . 'refund_status', 0);
  2213. else if ($status == 3)// 已支付 已收货 待评价
  2214. return $model->where($alert . 'paid', 1)->where($alert . 'status', 2)->where($alert . 'refund_status', 0);
  2215. else if ($status == 4)// 交易完成
  2216. return $model->where($alert . 'paid', 1)->where($alert . 'status', 3)->where($alert . 'refund_status', 0);
  2217. else if ($status == -1)//退款中
  2218. return $model->where($alert . 'paid', 1)->where($alert . 'refund_status', 1);
  2219. else if ($status == -2)//已退款
  2220. return $model->where($alert . 'paid', 1)->where($alert . 'refund_status', 2);
  2221. else if ($status == -3)//退款
  2222. return $model->where($alert . 'paid', 1)->where($alert . 'refund_status', 'in', '1,2');
  2223. else
  2224. return $model;
  2225. }
  2226. /**
  2227. * 订单详情 管理员
  2228. * @param $orderId
  2229. * @param string $field
  2230. * @return array|null|\think\Model
  2231. * @throws \think\db\exception\DataNotFoundException
  2232. * @throws \think\db\exception\ModelNotFoundException
  2233. * @throws \think\exception\DbException
  2234. */
  2235. public static function getAdminOrderDetail($orderId, $field = '*')
  2236. {
  2237. return self::where('order_id', $orderId)->field($field)->find();
  2238. }
  2239. /**
  2240. * 获取指定时间区间的支付金额 管理员
  2241. * @param $start
  2242. * @param $stop
  2243. * @return float
  2244. */
  2245. public static function getOrderTimeBusinessVolumePrice($start, $stop)
  2246. {
  2247. return self::where('is_del', 0)->where('paid', 1)->where('refund_status', 0)->where('add_time', '>=', $start)->where('add_time', '<', $stop)->sum('pay_price');
  2248. }
  2249. /**
  2250. * 获取指定时间区间的支付订单数量 管理员
  2251. * @param $start
  2252. * @param $stop
  2253. * @return float
  2254. */
  2255. public static function getOrderTimeBusinessVolumeNumber($start, $stop)
  2256. {
  2257. return self::where('is_del', 0)->where('paid', 1)->where('refund_status', 0)->where('add_time', '>=', $start)->where('add_time', '<', $stop)->count();
  2258. }
  2259. /**
  2260. * 获取当前时间到指定时间的支付金额 管理员
  2261. * @param $start 开始时间
  2262. * @param $stop 结束时间
  2263. * @return mixed
  2264. */
  2265. public static function chartTimePrice($start, $stop)
  2266. {
  2267. $model = new self;
  2268. $model = $model->field('sum(pay_price) as num,FROM_UNIXTIME(add_time, \'%Y-%m-%d\') as time');
  2269. $model = $model->where('is_del', 0);
  2270. $model = $model->where('paid', 1);
  2271. $model = $model->where('refund_status', 0);
  2272. $model = $model->where('add_time', '>=', $start);
  2273. $model = $model->where('add_time', '<', $stop);
  2274. $model = $model->group("FROM_UNIXTIME(add_time, '%Y-%m-%d')");
  2275. $model = $model->order('add_time ASC');
  2276. return $model->select();
  2277. }
  2278. /**
  2279. * 获取当前时间到指定时间的支付订单数 管理员
  2280. * @param $start 开始时间
  2281. * @param $stop 结束时间
  2282. * @return mixed
  2283. */
  2284. public static function chartTimeNumber($start, $stop)
  2285. {
  2286. $model = new self;
  2287. $model = $model->field('count(id) as num,FROM_UNIXTIME(add_time, \'%Y-%m-%d\') as time');
  2288. $model = $model->where('is_del', 0);
  2289. $model = $model->where('paid', 1);
  2290. $model = $model->where('refund_status', 0);
  2291. $model = $model->where('add_time', '>=', $start);
  2292. $model = $model->where('add_time', '<', $stop);
  2293. $model = $model->group("FROM_UNIXTIME(add_time, '%Y-%m-%d')");
  2294. $model = $model->order('add_time ASC');
  2295. return $model->select();
  2296. }
  2297. /**
  2298. * 修改支付方式为线下支付
  2299. * @param $orderId
  2300. * @return bool
  2301. */
  2302. public static function setOrderTypePayOffline($orderId)
  2303. {
  2304. return self::edit(['pay_type' => 'offline'], $orderId, 'order_id');
  2305. }
  2306. /**
  2307. * 线下付款
  2308. * @param $id
  2309. * @return $this
  2310. */
  2311. public static function updateOffline($id)
  2312. {
  2313. $count = self::where('id', $id)->count();
  2314. if (!$count) return self::setErrorInfo('订单不存在');
  2315. $count = self::where('id', $id)->where('paid', 0)->count();
  2316. if (!$count) return self::setErrorInfo('订单已支付');
  2317. $res = self::where('id', $id)->update(['paid' => 1, 'pay_time' => time()]);
  2318. return $res;
  2319. }
  2320. /**
  2321. * 向创建订单10分钟未付款的用户发送短信
  2322. */
  2323. public static function sendTen()
  2324. {
  2325. $list = self::where('paid', 0)->where('is_del', 0)->where('is_system_del', 0)->where('add_time', '>', time() - 900)->where('add_time', '<', time() - 600)->column('user_phone');
  2326. foreach ($list as $phone) {
  2327. ShortLetterRepositories::send(true, $phone, [], 'ORDER_PAY_FALSE');
  2328. }
  2329. }
  2330. public function productInfo()
  2331. {
  2332. return $this->hasMany(StoreProductReply::class, 'oid', 'id');
  2333. }
  2334. public static function setOrderProductReplyWhere($where)
  2335. {
  2336. $model = self::where('status', 3)->order('add_time desc')->whereIn('id', function ($query) {
  2337. $query->name('store_order')->alias('o')->join('store_product_reply a', 'a.oid = o.id')->group('o.id')->field('o.id')->select();
  2338. })->with('productInfo', function ($query) use ($where) {
  2339. $alias = '';
  2340. if (isset($where['title']) && $where['title'] != '')
  2341. $query->where("{$alias}comment", 'LIKE', "%$where[title]%");
  2342. if (isset($where['is_reply']) && $where['is_reply'] != '') {
  2343. if ($where['is_reply'] >= 0) {
  2344. $query->where("{$alias}is_reply", $where['is_reply']);
  2345. } else {
  2346. $query->where("{$alias}is_reply", '>', 0);
  2347. }
  2348. }
  2349. if (isset($where['producr_id']) && $where['producr_id'] != 0)
  2350. $query->where($alias . 'product_id', $where['producr_id']);
  2351. $query->where("{$alias}is_del", 0);
  2352. });
  2353. return $model;
  2354. }
  2355. public static function getOrderProductReplyList($where)
  2356. {
  2357. $list = self::setOrderProductReplyWhere($where)->page((int)$where['message_page'], (int)$where['limit'])->select();
  2358. $list = count($list) ? $list->toArray() : [];
  2359. foreach ($list as $key => $item) {
  2360. if (isset($item['productInfo']) && is_array($item['productInfo']) && count($item['productInfo'])) {
  2361. foreach ($item['productInfo'] as $k => $v) {
  2362. if (!$v['nickname'] && $v['uid']) {
  2363. $v['nickname'] = User::where('uid', $v['uid'])->value('nickname');
  2364. $v['avatar'] = User::where('uid', $v['uid'])->value('avatar');
  2365. }
  2366. $v['image'] = '';
  2367. $v['store_name'] = '';
  2368. if ($v['product_id']) {
  2369. $product = StoreProduct::where('id', $v['product_id'])->field(['image', 'store_name'])->find();
  2370. if ($product) {
  2371. $v['image'] = $product['image'];
  2372. $v['store_name'] = $product['store_name'];
  2373. }
  2374. }
  2375. $list[$key]['productInfo'][$k] = $v;
  2376. }
  2377. }
  2378. }
  2379. $count = self::setOrderProductReplyWhere($where)->count();
  2380. return compact('list', 'count');
  2381. }
  2382. }