StoreOrder.php 101 KB

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