StoreOrder.php 108 KB

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