StoreOrder.php 120 KB

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