StoreOrder.php 102 KB

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