StoreOrder.php 102 KB

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