StoreOrder.php 104 KB

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