StoreOrderServices.php 125 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065206620672068206920702071207220732074207520762077207820792080208120822083208420852086208720882089209020912092209320942095209620972098209921002101210221032104210521062107210821092110211121122113211421152116211721182119212021212122212321242125212621272128212921302131213221332134213521362137213821392140214121422143214421452146214721482149215021512152215321542155215621572158215921602161216221632164216521662167216821692170217121722173217421752176217721782179218021812182218321842185218621872188218921902191219221932194219521962197219821992200220122022203220422052206220722082209221022112212221322142215221622172218221922202221222222232224222522262227222822292230223122322233223422352236223722382239224022412242224322442245224622472248224922502251225222532254225522562257225822592260226122622263226422652266226722682269227022712272227322742275227622772278227922802281228222832284228522862287228822892290229122922293229422952296229722982299230023012302230323042305230623072308230923102311231223132314231523162317231823192320232123222323232423252326232723282329233023312332233323342335233623372338233923402341234223432344234523462347234823492350235123522353235423552356235723582359236023612362236323642365236623672368236923702371237223732374237523762377237823792380238123822383238423852386238723882389239023912392239323942395239623972398239924002401240224032404240524062407240824092410241124122413241424152416241724182419242024212422242324242425242624272428242924302431243224332434243524362437243824392440244124422443244424452446244724482449245024512452245324542455245624572458245924602461246224632464246524662467246824692470247124722473247424752476247724782479248024812482248324842485248624872488248924902491249224932494249524962497249824992500250125022503250425052506250725082509251025112512251325142515251625172518251925202521252225232524252525262527252825292530253125322533253425352536253725382539254025412542254325442545254625472548254925502551255225532554255525562557255825592560256125622563256425652566256725682569257025712572257325742575257625772578257925802581258225832584258525862587258825892590259125922593259425952596259725982599260026012602260326042605260626072608260926102611261226132614261526162617261826192620262126222623262426252626262726282629263026312632263326342635263626372638263926402641264226432644264526462647264826492650265126522653265426552656265726582659266026612662266326642665266626672668266926702671267226732674267526762677267826792680268126822683268426852686268726882689269026912692269326942695269626972698269927002701270227032704270527062707270827092710271127122713271427152716271727182719272027212722272327242725272627272728272927302731273227332734273527362737273827392740274127422743274427452746274727482749275027512752
  1. <?php
  2. // +----------------------------------------------------------------------
  3. // | CRMEB [ CRMEB赋能开发者,助力企业发展 ]
  4. // +----------------------------------------------------------------------
  5. // | Copyright (c) 2016~2020 https://www.crmeb.com All rights reserved.
  6. // +----------------------------------------------------------------------
  7. // | Licensed CRMEB并不是自由软件,未经许可不能去掉CRMEB相关版权
  8. // +----------------------------------------------------------------------
  9. // | Author: CRMEB Team <admin@crmeb.com>
  10. // +----------------------------------------------------------------------
  11. namespace app\services\order;
  12. use app\dao\order\StoreOrderDao;
  13. use app\jobs\BatchHandleJob;
  14. use app\jobs\order\AutoOrderUnpaidCancelJob;
  15. use app\jobs\order\SpliteStoreOrderJob;
  16. use app\services\activity\combination\StorePinkServices;
  17. use app\services\activity\coupon\StoreCouponIssueServices;
  18. use app\services\BaseServices;
  19. use app\services\product\branch\StoreBranchProductServices;
  20. use app\services\other\queue\QueueAuxiliaryServices;
  21. use app\services\other\queue\QueueServices;
  22. use app\services\pay\PayServices;
  23. use app\services\product\product\StoreProductLogServices;
  24. use app\services\product\product\StoreProductServices;
  25. use app\services\product\sku\StoreProductAttrValueServices;
  26. use app\services\store\finance\StoreFinanceFlowServices;
  27. use app\services\store\SystemStoreServices;
  28. use app\services\system\config\ConfigServices;
  29. use app\services\system\form\SystemFormServices;
  30. use app\services\user\UserAwardIntegralServices;
  31. use app\services\user\UserInvoiceServices;
  32. use app\services\user\UserServices;
  33. use app\services\product\product\StoreProductReplyServices;
  34. use app\services\user\UserAddressServices;
  35. use app\services\user\level\UserLevelServices;
  36. use crmeb\exceptions\AdminException;
  37. use crmeb\services\CacheService;
  38. use crmeb\services\FileService;
  39. use crmeb\services\FormBuilder as Form;
  40. use crmeb\services\printer\Printer;
  41. use crmeb\services\SystemConfigService;
  42. use crmeb\traits\ServicesTrait;
  43. use crmeb\utils\Arr;
  44. use think\exception\ValidateException;
  45. use think\facade\Log;
  46. /**
  47. * Class StoreOrderServices
  48. * @package app\services\order
  49. * @mixin StoreOrderDao
  50. */
  51. class StoreOrderServices extends BaseServices
  52. {
  53. use ServicesTrait;
  54. /**
  55. * 订单类型
  56. * @var string[]
  57. */
  58. protected $type = [
  59. 0 => '普通',
  60. 1 => '秒杀',
  61. 2 => '砍价',
  62. 3 => '拼团',
  63. 4 => '积分',
  64. 5 => '套餐',
  65. 6 => '预售',
  66. 7 => '新人礼',
  67. 8 => '抽奖',
  68. 9 => '拼单',
  69. 10 => '桌码'
  70. ];
  71. /**
  72. * 发货类型
  73. * @var string[]
  74. */
  75. public $deliveryType = ['send' => '商家配送', 'express' => '快递配送', 'fictitious' => '虚拟发货', 'delivery_part_split' => '拆分部分发货', 'delivery_split' => '拆分发货完成'];
  76. /**
  77. * StoreOrderProductServices constructor.
  78. * @param StoreOrderDao $dao
  79. */
  80. public function __construct(StoreOrderDao $dao)
  81. {
  82. $this->dao = $dao;
  83. }
  84. /**
  85. * 从缓存中获取购买商品个数
  86. * @param int $uid
  87. * @param int $type
  88. * @param int $id
  89. * @return int
  90. * @author 等风来
  91. * @email 136327134@qq.com
  92. * @date 2022/11/3
  93. */
  94. public function getBuyCountCache(int $uid, int $type, int $id)
  95. {
  96. $key = md5($uid . $type . $id);
  97. $res = $this->dao->cacheInfoById($key);
  98. if (null !== $res) {
  99. $num = $this->dao->getBuyCount($uid, $type, $id);
  100. $this->dao->cacheUpdate(['type' => $type, 'uid' => $uid, 'product_id' => $id, 'totalNum' => $num ?: 0], $key);
  101. } else {
  102. $num = $res['totalNum'] ?? 0;
  103. }
  104. return (int)$num;
  105. }
  106. /**
  107. * 获取门店订单统计
  108. * @param int $storeId
  109. * @return array
  110. */
  111. public function getStoreOrderHeader(int $storeId)
  112. {
  113. return [
  114. 'cashier' => $this->dao->count(['pid' => 0, 'type' => 6, 'is_system_del' => 0, 'store_id' => $storeId]),
  115. 'delivery' => $this->dao->count(['pid' => 0, 'type' => 7, 'is_system_del' => 0, 'store_id' => $storeId]),
  116. 'writeoff' => $this->dao->count(['pid' => 0, 'type' => 5, 'is_system_del' => 0, 'store_id' => $storeId]),
  117. ];
  118. }
  119. /**
  120. * 获取列表
  121. * @param array $where
  122. * @param array $field
  123. * @param array $with
  124. * @param bool $abridge
  125. * @param string $order
  126. * @return array
  127. * @throws \think\db\exception\DataNotFoundException
  128. * @throws \think\db\exception\DbException
  129. * @throws \think\db\exception\ModelNotFoundException
  130. */
  131. public function getOrderList(array $where, array $field = ['*'], array $with = [], bool $abridge = false, string $order = 'add_time DESC,id DESC')
  132. {
  133. [$page, $limit] = $this->getPageValue();
  134. $data = $this->dao->getOrderList($where, $field, $page, $limit, $with, $order);
  135. $count = $this->dao->count($where);
  136. $stat = [];
  137. $batch_url = "file/upload/1";
  138. if ($data) {
  139. $data = $this->tidyOrderList($data, true, $abridge);
  140. foreach ($data as &$item) {
  141. $refund_num = array_sum(array_column($item['refund'], 'refund_num'));
  142. $cart_num = 0;
  143. foreach ($item['_info'] as &$items) {
  144. if (isset($items['cart_info']['is_gift']) && $items['cart_info']['is_gift']) continue;
  145. $cart_num += $items['cart_info']['cart_num'];
  146. $cart_ids = [];
  147. $cart_ids[] = ['cart_id' => $items['cart_info']['id'], 'cart_num' => $items['cart_info']['cart_num']];
  148. /** @var StoreOrderSplitServices $storeOrderSpliteServices */
  149. $storeOrderSpliteServices = app()->make(StoreOrderSplitServices::class);
  150. $cartInfos = $storeOrderSpliteServices->getSplitOrderCartInfo($item['id'], $cart_ids, $item);
  151. $total_price = $pay_postage = 0;
  152. foreach ($cartInfos as $cart) {
  153. $_info = is_string($cart['cart_info']) ? json_decode($cart['cart_info'], true) : $cart['cart_info'];
  154. $total_price = bcadd((string)$total_price, bcmul((string)($_info['truePrice'] ?? 0), (string)$cart['cart_num'], 4), 2);
  155. if (!in_array($item['shipping_type'], [2, 4])) {
  156. $pay_postage = bcadd((string)$pay_postage, (string)($_info['postage_price'] ?? 0), 2);
  157. }
  158. }
  159. //实际退款金额
  160. $refund_pay_price = bcadd((string)$total_price, (string)$pay_postage, 2);
  161. if (isset($item['change_price']) && (float)$item['change_price']) {//有改价 且是拆分
  162. //订单原实际支付金额
  163. $order_pay_price = bcadd((string)$item['change_price'], (string)$item['pay_price'], 2);
  164. $refund_price = bcmul((string)bcdiv((string)$item['pay_price'], (string)$order_pay_price, 4), (string)$refund_pay_price, 2);
  165. } else {
  166. $refund_price = $refund_pay_price;
  167. }
  168. $items['cart_info']['refund_price'] = $refund_price;
  169. }
  170. $item['is_all_refund'] = $refund_num == $cart_num;
  171. }
  172. }
  173. return compact('data', 'count', 'stat', 'batch_url');
  174. }
  175. /**获取单个订单信息
  176. * @param string $key
  177. * @param int $uid
  178. * @param array $with
  179. * @return array|\think\Model|null
  180. * @throws \think\db\exception\DataNotFoundException
  181. * @throws \think\db\exception\DbException
  182. * @throws \think\db\exception\ModelNotFoundException
  183. */
  184. public function getOneOrderList(string $key, int $uid, array $with = [])
  185. {
  186. return $this->dao->getUserOrderDetail($key, $uid, array_merge(['user', 'spread', 'refund'], $with));
  187. }
  188. /**
  189. * 获取列表
  190. * @param array $where
  191. * @return array
  192. * @throws \think\db\exception\DataNotFoundException
  193. * @throws \think\db\exception\DbException
  194. * @throws \think\db\exception\ModelNotFoundException
  195. */
  196. public function getSplitOrderList(array $where, array $field = ['*'], array $with = [])
  197. {
  198. $data = $this->dao->getOrderList($where, $field, 0, 0, $with);
  199. if ($data) {
  200. $data = $this->tidyOrderList($data);
  201. /** @var StoreOrderStatusServices $statusServices */
  202. $statusServices = app()->make(StoreOrderStatusServices::class);
  203. foreach ($data as &$item) {
  204. $log = $statusServices->getColumn(['oid' => $item['id']], 'change_time', 'change_type');
  205. if (isset($log['delivery'])) {
  206. $delivery = date('Y-m-d H:i:s', $log['delivery']);
  207. } elseif (isset($log['delivery_goods'])) {
  208. $delivery = date('Y-m-d H:i:s', $log['delivery_goods']);
  209. } elseif (isset($log['delivery_fictitious'])) {
  210. $delivery = date('Y-m-d H:i:s', $log['delivery_fictitious']);
  211. } else {
  212. $delivery = '';
  213. }
  214. $item['delivery_time'] = $delivery;
  215. }
  216. }
  217. return $data;
  218. }
  219. /**
  220. * 前端订单列表
  221. * @param array $where
  222. * @param array|string[] $field
  223. * @param array $with
  224. * @return array
  225. * @throws \think\db\exception\DataNotFoundException
  226. * @throws \think\db\exception\DbException
  227. * @throws \think\db\exception\ModelNotFoundException
  228. */
  229. public function getOrderApiList(array $where, array $field = ['*'], array $with = [])
  230. {
  231. [$page, $limit] = $this->getPageValue();
  232. if (isset($where['status']) && $where['status'] === '') {
  233. $data = $this->dao->getOrderList($where, $field, $page, $limit, $with, 'id DESC');
  234. } else {
  235. $data = $this->dao->getOrderList($where, $field, $page, $limit, $with);
  236. }
  237. foreach ($data as &$item) {
  238. $item = $this->tidyOrder($item, true);
  239. $cart_num = 0;
  240. foreach ($item['cartInfo'] ?: [] as $key => $product) {
  241. if (isset($item['_status']['_type']) && $item['_status']['_type'] == 3) {
  242. $item['cartInfo'][$key]['add_time'] = isset($product['add_time']) ? date('Y-m-d H:i', (int)$product['add_time']) : '时间错误';
  243. }
  244. $item['cartInfo'][$key]['productInfo']['price'] = $product['truePrice'] ?? 0;
  245. if (isset($product['is_gift']) && $product['is_gift']) continue;
  246. $cart_num += $product['cart_num'];
  247. }
  248. if (count($item['refund'])) {
  249. $refund_num = array_sum(array_column($item['refund'], 'refund_num'));
  250. $item['is_all_refund'] = $refund_num == $cart_num;
  251. } else {
  252. $item['is_all_refund'] = false;
  253. }
  254. }
  255. return $data;
  256. }
  257. /**
  258. * 获取订单数量
  259. * @param int $uid
  260. * @param int $store_id
  261. * @param int $plat_type
  262. * @return array
  263. */
  264. public function getOrderData(int $uid = 0, int $store_id = -1, int $plat_type = -1)
  265. {
  266. $where = ['pid' => 0, 'uid' => $uid, 'is_del' => 0, 'is_system_del' => 0, 'plat_type' => $plat_type];
  267. $countWhere = [];
  268. if ($store_id != -1) {
  269. $where['store_id'] = $store_id;
  270. $countWhere['store_id'] = $store_id;
  271. }
  272. $data['order_count'] = (string)$this->dao->count($where);
  273. $where = $where + ['paid' => 1];
  274. $data['sum_price'] = (string)$this->dao->sum($where, 'pay_price', true);
  275. // $countWhere = $store_id != -1 ? ['pid' => 0, 'store_id' => $store_id] : ['pid' => 0];
  276. if ($uid) {
  277. $countWhere['uid'] = $uid;
  278. }
  279. if ($plat_type != -1) {
  280. $countWhere['plat_type'] = $plat_type;
  281. }
  282. $pid_where = ['pid' => 0];
  283. $not_pid_where = ['not_pid' => 1];
  284. $data['unpaid_count'] = (string)$this->dao->count(['status' => 0] + $countWhere + $pid_where);
  285. $data['unshipped_count'] = (string)$this->dao->count(['status' => 1] + $countWhere + $pid_where);
  286. $data['received_count'] = (string)$this->dao->count(['status' => 2] + $countWhere + $pid_where);
  287. $data['evaluated_count'] = (string)$this->dao->count(['status' => 3] + $countWhere + $pid_where);
  288. $data['unwritoff_count'] = (string)$this->dao->count(['status' => 5] + $countWhere);
  289. $data['complete_count'] = (string)$this->dao->count(['status' => 4] + $countWhere + $pid_where);
  290. /** @var StoreOrderRefundServices $storeOrderRefundServices */
  291. $storeOrderRefundServices = app()->make(StoreOrderRefundServices::class);
  292. $refund_where = ['is_cancel' => 0];
  293. if ($uid) $refund_where['uid'] = $uid;
  294. if ($store_id != -1) $refund_where['store_id'] = $store_id;
  295. $data['refunding_count'] = (string)$storeOrderRefundServices->count($refund_where + ['refund_type' => [1, 2, 4, 5]]);
  296. $data['refunded_count'] = (string)$storeOrderRefundServices->count($refund_where + ['refund_type' => [3, 6]]);
  297. $data['refund_count'] = (string)bcadd($data['refunding_count'], $data['refunded_count'], 0);
  298. $data['yue_pay_status'] = (int)sys_config('balance_func_status') && (int)sys_config('yue_pay_status') == 1 ? (int)1 : (int)2;//余额支付 1 开启 2 关闭
  299. $data['pay_weixin_open'] = (int)sys_config('pay_weixin_open') ?? 0;//微信支付 1 开启 0 关闭
  300. $data['ali_pay_status'] = (bool)sys_config('ali_pay_status');//支付包支付 1 开启 0 关闭
  301. return $data;
  302. }
  303. /**
  304. * 订单详情数据格式化
  305. * @param $order
  306. * @param bool $detail 是否需要订单商品详情
  307. * @param bool $isPic 是否需要订单状态图片
  308. * @return mixed
  309. */
  310. public function tidyOrder($order, bool $detail = false, bool $isPic = false)
  311. {
  312. if ($detail == true && isset($order['id'])) {
  313. /** @var StoreOrderCartInfoServices $cartServices */
  314. $cartServices = app()->make(StoreOrderCartInfoServices::class);
  315. $cartInfos = $cartServices->getCartColunm(['oid' => $order['id']], 'cart_num,is_writeoff,surplus_num,cart_info,refund_num,product_type,is_support_refund,is_gift,promotions_id,type,relation_id,write_times,write_surplus_times,write_start,write_end', 'unique');
  316. $info = [];
  317. /** @var StoreProductReplyServices $replyServices */
  318. $replyServices = app()->make(StoreProductReplyServices::class);
  319. foreach ($cartInfos as $k => $cartInfo) {
  320. $cart = json_decode($cartInfo['cart_info'], true);
  321. $cart['cart_num'] = $cartInfo['cart_num'];
  322. $cart['is_writeoff'] = $cartInfo['is_writeoff'];
  323. $cart['surplus_num'] = $cartInfo['write_surplus_times'];
  324. $cart['refund_num'] = $cartInfo['refund_num'];
  325. $cart['write_times'] = $cartInfo['write_times'];
  326. $cart['write_surplus_times'] = $cartInfo['write_surplus_times'];
  327. $cart['write_start'] = $cartInfo['write_start'];
  328. $cart['write_end'] = $cartInfo['write_end'];
  329. $cart['write_off'] = max(bcsub((string)$cart['write_times'], (string)$cart['write_surplus_times'], 0), 0);
  330. $cart['product_type'] = $cartInfo['product_type'];
  331. $cart['supplier_id'] = $cart['store_id'] = 0;
  332. if ($cartInfo['type'] == 1) {
  333. $cart['store_id'] = $cartInfo['relation_id'] ?? 0;
  334. } elseif ($cartInfo['type'] == 2) {
  335. $cart['supplier_id'] = $cartInfo['relation_id'] ?? 0;
  336. }
  337. $cart['is_support_refund'] = $cartInfo['is_support_refund'];
  338. $cart['is_gift'] = $cartInfo['is_gift'];
  339. $cart['promotions_id'] = $cartInfo['promotions_id'];
  340. $cart['unique'] = $k;
  341. //新增是否评价字段
  342. $cart['is_reply'] = $replyServices->count(['unique' => $k]);
  343. if (isset($cart['productInfo']['attrInfo'])) {
  344. $cart['productInfo']['attrInfo'] = get_thumb_water($cart['productInfo']['attrInfo']);
  345. }
  346. $cart['productInfo'] = get_thumb_water($cart['productInfo']);
  347. //一种商品买多件 计算总优惠
  348. $cart['vip_sum_truePrice'] = bcmul($cart['vip_truePrice'], $cart['cart_num'] ? $cart['cart_num'] : 1, 2);
  349. $cart['is_valid'] = 1;
  350. array_push($info, $cart);
  351. unset($cart);
  352. }
  353. $order['cartInfo'] = $info;
  354. }
  355. /** @var StoreOrderStatusServices $statusServices */
  356. $statusServices = app()->make(StoreOrderStatusServices::class);
  357. $status = [];
  358. $storeInfo = [];
  359. if ($order['store_id']) {
  360. $storeServices = app()->make(SystemStoreServices::class);
  361. $storeInfo = $storeServices->get((int)$order['store_id']);
  362. }
  363. //系统预设取消订单时间段
  364. $keyValue = ['order_cancel_time', 'order_activity_time', 'order_bargain_time', 'order_seckill_time', 'order_pink_time'];
  365. //获取配置
  366. $systemValue = SystemConfigService::more($keyValue);
  367. //格式化数据
  368. $systemValue = Arr::setValeTime($keyValue, is_array($systemValue) ? $systemValue : []);
  369. switch ($order['type'] ?? 0) {
  370. case 1://秒杀
  371. $secs = $systemValue['order_seckill_time'] ? $systemValue['order_seckill_time'] : $systemValue['order_activity_time'];
  372. break;
  373. case 2://砍价
  374. $secs = $systemValue['order_bargain_time'] ? $systemValue['order_bargain_time'] : $systemValue['order_activity_time'];
  375. break;
  376. case 3://拼团
  377. $secs = $systemValue['order_pink_time'] ? $systemValue['order_pink_time'] : $systemValue['order_activity_time'];
  378. break;
  379. default:
  380. $secs = $systemValue['order_cancel_time'];
  381. break;
  382. }
  383. $order['stop_time'] = $secs * 3600 + $order['add_time'];
  384. if (!$order['paid'] && $order['pay_type'] == 'offline' && !$order['status'] >= 2) {
  385. $status['_type'] = 9;
  386. $status['_title'] = '线下付款,未支付';
  387. $status['_msg'] = '等待商家处理,请耐心等待';
  388. $status['_class'] = 'nobuy';
  389. } else if (!$order['paid']) {
  390. $status['_type'] = 0;
  391. $status['_title'] = '未支付';
  392. $status['_msg'] = '请在' . date('m-d H:i:s', $order['stop_time']) . '前完成支付!';
  393. $status['_class'] = 'nobuy';
  394. } else if ($order['refund_status'] == 2) {
  395. $status['_type'] = -2;
  396. $status['_title'] = '已退款';
  397. $status['_msg'] = '已为您退款,感谢您的支持';
  398. $status['_class'] = 'state-sqtk';
  399. } else if ($order['status'] == 4) {
  400. if ($order['delivery_type'] == 'send') {// 送货
  401. $status['_type'] = 2;
  402. $status['_title'] = '待收货';
  403. $status['_msg'] = date('m月d日H时i分', $statusServices->value(['oid' => $order['id'], 'change_type' => 'delivery'], 'change_time')) . '服务商已送货';
  404. $status['_class'] = 'state-ysh';
  405. } elseif ($order['delivery_type'] == 'express') {// 发货
  406. $status['_type'] = 2;
  407. $status['_title'] = '待收货';
  408. $status['_msg'] = date('m月d日H时i分', $statusServices->value(['oid' => $order['id'], 'change_type' => 'delivery_goods'], 'change_time')) . '服务商已发货';
  409. $status['_class'] = 'state-ysh';
  410. } elseif ($order['delivery_type'] == 'split') {//拆分发货
  411. $status['_type'] = 2;
  412. $status['_title'] = '待收货';
  413. $status['_msg'] = date('m月d日H时i分', $statusServices->value(['oid' => $order['id'], 'change_type' => 'delivery_part_split'], 'change_time')) . '服务商已拆分多个包裹发货';
  414. $status['_class'] = 'state-ysh';
  415. } else {
  416. $status['_type'] = 2;
  417. $status['_title'] = '待收货';
  418. $status['_msg'] = date('m月d日H时i分', $statusServices->value(['oid' => $order['id'], 'change_type' => 'delivery_fictitious'], 'change_time')) . '服务商已虚拟发货';
  419. $status['_class'] = 'state-ysh';
  420. }
  421. } elseif ($order['status'] == 5) {
  422. if ($order['shipping_type'] == 2) {
  423. $status['_type'] = 5;
  424. $status['_title'] = '部分核销';
  425. $status['_msg'] = '部分核销,请继续进行核销';
  426. $status['_class'] = 'state-nfh';
  427. } else {
  428. $status['_type'] = 2;
  429. $status['_title'] = '待收货';
  430. $status['_msg'] = '部分核销收货,请继续进行核销';
  431. $status['_class'] = 'state-ysh';
  432. }
  433. } else if ($order['refund_status'] == 1) {
  434. if (in_array($order['refund_type'], [0, 1, 2])) {
  435. $status['_type'] = -1;
  436. $status['_title'] = '申请退款中';
  437. $status['_msg'] = '商家审核中,请耐心等待';
  438. $status['_class'] = 'state-sqtk';
  439. } elseif ($order['refund_type'] == 4) {
  440. $status['_type'] = -1;
  441. $status['_title'] = '申请退款中';
  442. $status['_msg'] = '商家同意退款,请填写退货订单号';
  443. $status['_class'] = 'state-sqtk';
  444. if ($order['shipping_type'] == 1 || !$storeInfo) {//平台
  445. $status['refund_name'] = sys_config('refund_name', '');
  446. $status['refund_phone'] = sys_config('refund_phone', '');
  447. $status['refund_address'] = sys_config('refund_address', '');
  448. } else {
  449. $status['refund_name'] = $storeInfo['name'];
  450. $status['refund_phone'] = $storeInfo['phone'];
  451. $status['refund_address'] = $storeInfo['detailed_address'];
  452. }
  453. } elseif ($order['refund_type'] == 5) {
  454. $status['_type'] = -1;
  455. $status['_title'] = '申请退款中';
  456. $status['_msg'] = '等待商家收货';
  457. $status['_class'] = 'state-sqtk';
  458. if ($order['shipping_type'] == 1 || !$storeInfo) {//平台
  459. $status['refund_name'] = sys_config('refund_name', '');
  460. $status['refund_phone'] = sys_config('refund_phone', '');
  461. $status['refund_address'] = sys_config('refund_address', '');
  462. } else {
  463. $status['refund_name'] = $storeInfo['name'];
  464. $status['refund_phone'] = $storeInfo['phone'];
  465. $status['refund_address'] = $storeInfo['detailed_address'];
  466. }
  467. }
  468. } else if ($order['refund_status'] == 3) {
  469. $status['_type'] = -1;
  470. $status['_title'] = '部分退款(子订单)';
  471. $status['_msg'] = '拆分发货,部分退款';
  472. $status['_class'] = 'state-sqtk';
  473. } else if ($order['refund_status'] == 4) {
  474. $status['_type'] = -1;
  475. $status['_title'] = '子订单已全部申请退款中';
  476. $status['_msg'] = '拆分发货,全部退款';
  477. $status['_class'] = 'state-sqtk';
  478. } else if (!$order['status']) {
  479. if ($order['pink_id']) {
  480. /** @var StorePinkServices $pinkServices */
  481. $pinkServices = app()->make(StorePinkServices::class);
  482. if ($pinkServices->getCount(['id' => $order['pink_id'], 'status' => 1])) {
  483. $status['_type'] = 1;
  484. $status['_title'] = '拼团中';
  485. $status['_msg'] = '等待其他人参加拼团';
  486. $status['_class'] = 'state-nfh';
  487. } else if (in_array($order['shipping_type'], [1, 3])) {
  488. $status['_type'] = 1;
  489. $status['_title'] = '未发货';
  490. $status['_msg'] = '商家未发货,请耐心等待';
  491. $status['_class'] = 'state-nfh';
  492. } else {
  493. $status['_type'] = 5;
  494. $status['_title'] = '待核销';
  495. $status['_msg'] = '待核销,请到核销点进行核销';
  496. $status['_class'] = 'state-nfh';
  497. }
  498. } else {
  499. if (in_array($order['shipping_type'], [1, 3])) {
  500. $status['_type'] = 1;
  501. $status['_title'] = '未发货';
  502. $status['_msg'] = '商家未发货,请耐心等待';
  503. $status['_class'] = 'state-nfh';
  504. } else {
  505. $status['_type'] = 5;
  506. $status['_title'] = '待核销';
  507. $status['_msg'] = '待核销,请到核销点进行核销';
  508. $status['_class'] = 'state-nfh';
  509. }
  510. }
  511. } else if ($order['status'] == 1) {
  512. if ($order['delivery_type'] == 'send') {// 配送
  513. $status['_type'] = 2;
  514. $status['_title'] = '待收货';
  515. $status['_msg'] = date('m月d日H时i分', $statusServices->value(['oid' => $order['id'], 'change_type' => 'delivery'], 'change_time')) . '服务商已发货';
  516. $status['_class'] = 'state-ysh';
  517. } elseif ($order['delivery_type'] == 'express') {// 发货
  518. $status['_type'] = 2;
  519. $status['_title'] = '待收货';
  520. $status['_msg'] = date('m月d日H时i分', $statusServices->value(['oid' => $order['id'], 'change_type' => 'delivery_goods'], 'change_time')) . '服务商已发货';
  521. $status['_class'] = 'state-ysh';
  522. } elseif ($order['delivery_type'] == 'split') {//拆分发货
  523. $status['_type'] = 2;
  524. $status['_title'] = '待收货';
  525. $status['_msg'] = date('m月d日H时i分', $statusServices->value(['oid' => $order['id'], 'change_type' => 'delivery_split'], 'change_time')) . '服务商已拆分多个包裹发货';
  526. $status['_class'] = 'state-ysh';
  527. } else {
  528. $status['_type'] = 2;
  529. $status['_title'] = '待收货';
  530. $status['_msg'] = date('m月d日H时i分', $statusServices->value(['oid' => $order['id'], 'change_type' => 'delivery_fictitious'], 'change_time')) . '服务商已虚拟发货';
  531. $status['_class'] = 'state-ysh';
  532. }
  533. } else if ($order['status'] == 2) {
  534. $status['_type'] = 3;
  535. $status['_title'] = '待评价';
  536. $status['_msg'] = '已收货,快去评价一下吧';
  537. $status['_class'] = 'state-ypj';
  538. } else if ($order['status'] == 3) {
  539. $status['_type'] = 4;
  540. $status['_title'] = '交易完成';
  541. $status['_msg'] = '交易完成,感谢您的支持';
  542. $status['_class'] = 'state-ytk';
  543. }
  544. if (isset($order['pay_type']))
  545. $status['_payType'] = ($status['_type'] ?? 0) == 0 ? '' : PayServices::PAY_TYPE[$order['pay_type']] ?? '其他方式';
  546. if (isset($order['delivery_type']))
  547. $status['_deliveryType'] = isset($this->deliveryType[$order['delivery_type']]) ? $this->deliveryType[$order['delivery_type']] : '其他方式';
  548. $order['_status'] = $status;
  549. $order['_pay_time'] = isset($order['pay_time']) && $order['pay_time'] != null ? date('Y-m-d H:i:s', $order['pay_time']) : '';
  550. $order['_add_time'] = isset($order['add_time']) ? (strstr((string)$order['add_time'], '-') === false ? date('Y-m-d H:i:s', $order['add_time']) : $order['add_time']) : '';
  551. $order['status_pic'] = '';
  552. //获取商品状态图片
  553. if ($isPic) {
  554. try {
  555. $order_details_images = sys_data('order_details_images') ?: [];
  556. $order_details_images = array_combine(array_column($order_details_images, 'order_status'), $order_details_images);
  557. $_type = $order['_status']['_type'] == 5 ? 2 : $order['_status']['_type'];
  558. $order['status_pic'] = $order_details_images[$_type]['pic'] ?? '';
  559. } catch (\Throwable $e) {
  560. }
  561. }
  562. $order['offlinePayStatus'] = (int)sys_config('offline_pay_status') ?? 2;
  563. //自购返佣
  564. if ($order['uid'] == $order['spread_uid']) {
  565. $order['spread_nickname'] = isset($order['spread_nickname']) ? $order['spread_nickname'] . '(自购)' : '';
  566. }
  567. $order['longitude'] = $order['latitude'] = '';
  568. //处理地址定位
  569. if (isset($order['user_location']) && $order['user_location']) {
  570. [$longitude, $latitude] = explode(' ', $order['user_location']);
  571. $order['longitude'] = $longitude;
  572. $order['latitude'] = $latitude;
  573. }
  574. return $order;
  575. }
  576. /**
  577. * 整理订单类型
  578. * @param $order
  579. * @param bool $abridge
  580. * @return string[]
  581. */
  582. public function tidyOrderType($order, bool $abridge = false)
  583. {
  584. $pink_name = $color = '';
  585. if ($order && isset($order['type'])) {
  586. switch ($order['type']) {
  587. case 0://普通订单
  588. if ($order['shipping_type'] == 1) {
  589. $pink_name = $abridge ? '普通' : '[普通订单]';
  590. $color = '#895612';
  591. } else if ($order['shipping_type'] == 2) {
  592. $pink_name = $abridge ? '核销' : '[核销订单]';
  593. $color = '#8956E8';
  594. } else if ($order['shipping_type'] == 3) {
  595. $pink_name = $abridge ? '分配' : '[分配订单]';
  596. $color = '#FFA21B';
  597. } else if ($order['shipping_type'] == 4) {
  598. $pink_name = $abridge ? '收银' : '[收银订单]';
  599. $color = '#2EC479';
  600. }
  601. break;
  602. case 1://秒杀
  603. $pink_name = $abridge ? '秒杀' : '[秒杀订单]';
  604. $color = '#32c5e9';
  605. break;
  606. case 2://砍价
  607. $pink_name = $abridge ? '砍价' : '[砍价订单]';
  608. $color = '#12c5e9';
  609. break;
  610. case 3://拼团
  611. if (isset($order['pinkStatus'])) {
  612. switch ($order['pinkStatus']) {
  613. case 1:
  614. $pink_name = $abridge ? '拼团' : '[拼团订单]正在进行中';
  615. $color = '#f00';
  616. break;
  617. case 2:
  618. $pink_name = $abridge ? '拼团' : '[拼团订单]已完成';
  619. $color = '#00f';
  620. break;
  621. case 3:
  622. $pink_name = $abridge ? '拼团' : '[拼团订单]未完成';
  623. $color = '#f0f';
  624. break;
  625. default:
  626. $pink_name = $abridge ? '拼团' : '[拼团订单]历史订单';
  627. $color = '#457856';
  628. break;
  629. }
  630. } else {
  631. $pink_name = $abridge ? '拼团' : '[拼团订单]历史订单';
  632. $color = '#457856';
  633. }
  634. break;
  635. case 4://积分
  636. $pink_name = $abridge ? '积分' : '[积分订单]';
  637. $color = '#12c5e9';
  638. break;
  639. case 5://套餐
  640. $pink_name = $abridge ? '优惠' : '[优惠套餐]';
  641. $color = '#12c5e9';
  642. break;
  643. case 6://预售
  644. $pink_name = $abridge ? '预售' : '[预售订单]';
  645. $color = '#12c5e9';
  646. break;
  647. case 7://新人礼
  648. $pink_name = $abridge ? '新人礼' : '[新人专享]';
  649. $color = '#12c5e9';
  650. break;
  651. case 8://抽奖
  652. $pink_name = $abridge ? '抽奖' : '[抽奖订单]';
  653. $color = '#12c5e9';
  654. break;
  655. case 9://拼单
  656. $pink_name = $abridge ? '拼单' : '[拼单订单]';
  657. $color = '#12c5e9';
  658. break;
  659. case 10://桌码
  660. $pink_name = $abridge ? '桌码' : '[桌码订单]';
  661. $color = '#F5222D';
  662. break;
  663. }
  664. }
  665. return [$pink_name, $color];
  666. }
  667. /**
  668. * 数据转换
  669. * @param array $data
  670. * @param bool $is_cart_info
  671. * @return array|null
  672. */
  673. public function tidyOrderList(array $data, bool $is_cart_info = true, bool $abridge = false)
  674. {
  675. if (!$data) {
  676. return $data;
  677. }
  678. /** @var StoreOrderCartInfoServices $services */
  679. $services = app()->make(StoreOrderCartInfoServices::class);
  680. foreach ($data as &$item) {
  681. if ($is_cart_info) $item['_info'] = $services->getOrderCartInfo((int)$item['id']);
  682. $item['add_time'] = date('Y-m-d H:i:s', $item['add_time']);
  683. $item['_refund_time'] = isset($item['refund_reason_time']) && $item['refund_reason_time'] ? date('Y-m-d H:i:s', $item['refund_reason_time']) : '';
  684. $item['_pay_time'] = isset($item['pay_time']) && $item['pay_time'] ? date('Y-m-d H:i:s', $item['pay_time']) : '';
  685. [$pink_name, $color] = $this->tidyOrderType($item, $abridge);
  686. $item['pink_name'] = $pink_name;
  687. $item['color'] = $color;
  688. if ($item['paid'] == 1) {
  689. switch ($item['pay_type']) {
  690. case PayServices::WEIXIN_PAY:
  691. $item['pay_type_name'] = '微信支付';
  692. break;
  693. case PayServices::YUE_PAY:
  694. $item['pay_type_name'] = '余额支付';
  695. break;
  696. case PayServices::OFFLINE_PAY:
  697. $item['pay_type_name'] = '线下支付';
  698. break;
  699. case PayServices::ALIAPY_PAY:
  700. $item['pay_type_name'] = '支付宝支付';
  701. break;
  702. case PayServices::CASH_PAY:
  703. $item['pay_type_name'] = '现金支付';
  704. break;
  705. default:
  706. $item['pay_type_name'] = '其他支付';
  707. break;
  708. }
  709. } else {
  710. switch ($item['pay_type']) {
  711. default:
  712. $item['pay_type_name'] = '未支付';
  713. break;
  714. case 'offline':
  715. $item['pay_type_name'] = '线下支付';
  716. $item['pay_type_info'] = 1;
  717. break;
  718. }
  719. }
  720. $status_name = ['status_name' => '', 'pics' => []];
  721. if ($item['is_del'] || $item['is_system_del']) {
  722. $status_name['status_name'] = '已删除';
  723. $item['_status'] = -1;
  724. } else if ($item['paid'] == 0 && $item['status'] == 0) {
  725. $status_name['status_name'] = '未支付';
  726. $item['_status'] = 1;//未支付
  727. } else if ($item['paid'] == 1 && $item['status'] == 4 && in_array($item['shipping_type'], [1, 3]) && $item['refund_status'] == 0) {
  728. $status_name['status_name'] = '部分发货';
  729. $item['_status'] = 8;//已支付 部分发货
  730. } else if ($item['paid'] == 1 && $item['refund_status'] == 2) {
  731. $status_name['status_name'] = '已退款';
  732. $item['_status'] = 7;//已支付 已退款
  733. } else if ($item['paid'] == 1 && $item['status'] == 5 && $item['refund_status'] == 0) {
  734. $status_name['status_name'] = $item['shipping_type'] == 2 ? '部分核销' : '部分收货';
  735. $item['_status'] = 12;//已支付 部分核销
  736. } else if ($item['paid'] == 1 && $item['refund_status'] == 1) {
  737. $item['_status'] = 3;//已支付 申请退款中
  738. $refundReasonTime = $item['refund_reason_time'] ? date('Y-m-d H:i', $item['refund_reason_time']) : '';
  739. $refundReasonWapImg = json_decode($item['refund_reason_wap_img'], true);
  740. $refundReasonWapImg = $refundReasonWapImg ? $refundReasonWapImg : [];
  741. $img = [];
  742. if (count($refundReasonWapImg)) {
  743. foreach ($refundReasonWapImg as $itemImg) {
  744. if (strlen(trim($itemImg)))
  745. $img[] = $itemImg;
  746. }
  747. }
  748. $status_name['status_name'] = <<<HTML
  749. <b style="color:#f124c7">申请退款</b><br/>
  750. <span>退款原因:{$item['refund_reason_wap']}</span><br/>
  751. <span>备注说明:{$item['refund_reason_wap_explain']}</span><br/>
  752. <span>退款时间:{$refundReasonTime}</span><br/>
  753. <span>退款凭证:</span>
  754. HTML;
  755. $status_name['pics'] = $img;
  756. } else if ($item['paid'] == 1 && $item['refund_status'] == 4) {
  757. $item['_status'] = 10;//拆单发货 已全部申请退款
  758. $status_name['status_name'] = '退款中';
  759. } else if ($item['paid'] == 1 && $item['status'] == 0 && in_array($item['shipping_type'], [1, 3, 4]) && $item['refund_status'] == 0) {
  760. $status_name['status_name'] = '未发货';
  761. $item['_status'] = 2;//已支付 未发货
  762. } else if ($item['paid'] == 1 && in_array($item['status'], [0, 1]) && $item['shipping_type'] == 2 && $item['refund_status'] == 0) {
  763. $status_name['status_name'] = '未核销';
  764. $item['_status'] = 11;//已支付 待核销
  765. } else if ($item['paid'] == 1 && in_array($item['status'], [1, 5]) && in_array($item['shipping_type'], [1, 3, 4]) && $item['refund_status'] == 0) {
  766. $status_name['status_name'] = '待收货';
  767. $item['_status'] = 4;//已支付 待收货
  768. } else if ($item['paid'] == 1 && $item['status'] == 2 && $item['refund_status'] == 0) {
  769. $status_name['status_name'] = '待评价';
  770. $item['_status'] = 5;//已支付 待评价
  771. } else if ($item['paid'] == 1 && $item['status'] == 3 && $item['refund_status'] == 0) {
  772. $status_name['status_name'] = '已完成';
  773. $item['_status'] = 6;//已支付 已完成
  774. } else if ($item['paid'] == 1 && $item['refund_status'] == 3) {
  775. $item['_status'] = 9;//拆单发货 部分申请退款
  776. $status_name['status_name'] = '部分退款';
  777. }
  778. $item['status_name'] = $status_name;
  779. if ($item['store_id'] == 0 && $item['clerk_id'] == 0 && !isset($item['clerk_name'])) {
  780. $item['clerk_name'] = '总平台';
  781. }
  782. //根据核销员更改store_name
  783. if ($item['clerk_id'] && isset($item['staff_store_id']) && $item['staff_store_id']) {
  784. /** @var SystemStoreServices $store */
  785. $store = app()->make(SystemStoreServices::class);
  786. $storeOne = $store->value(['id' => $item['staff_store_id']], 'name');
  787. if ($storeOne) $item['store_name'] = $storeOne;
  788. }
  789. //自购返佣
  790. if ($item['uid'] == $item['spread_uid']) {
  791. $item['spread_nickname'] = isset($item['spread_nickname']) ? $item['spread_nickname'] . '(自购)' : '';
  792. }
  793. }
  794. return $data;
  795. }
  796. /**
  797. * 处理订单金额
  798. * @param $where
  799. * @return array
  800. */
  801. public function getOrderPrice($where)
  802. {
  803. // $where['pid'] = 0;//子订单不统计
  804. $whereData = [];
  805. $price['today_count_sum'] = 0; //今日订单总数
  806. $price['count_sum'] = 0; //订单总数
  807. $price['pay_price'] = 0;//支付金额
  808. $price['today_pay_price'] = 0;//今日支付金额
  809. if ($where['status'] == '') {
  810. $whereData['paid'] = 1;
  811. $whereData['refund_status'] = [0, 3];
  812. }
  813. $not_pid = $where;
  814. unset($not_pid['pid']);
  815. $not_pid['not_pid'] = 1;
  816. $sumNumber = $this->dao->search($where + $whereData)->field([
  817. 'count(id) as count_sum',
  818. ])->find();
  819. $price['count_sum'] = $sumNumber && $sumNumber['count_sum'] ? $sumNumber['count_sum'] : 0;
  820. $sumNumber = $this->dao->search($whereData + $where)->field([
  821. 'sum(pay_price) as sum_pay_price',
  822. ])->find();
  823. $price['pay_price'] = $sumNumber && $sumNumber['sum_pay_price'] ? $sumNumber['sum_pay_price'] : 0;
  824. $where['time'] = 'today';
  825. $not_pid['time'] = 'today';
  826. $sumNumber = $this->dao->search($where + $whereData)->field([
  827. 'count(id) as today_count_sum',
  828. ])->find();
  829. $price['today_count_sum'] = $sumNumber && $sumNumber['today_count_sum'] ? $sumNumber['today_count_sum'] : 0;
  830. $sumNumber = $this->dao->search($whereData + $where + ['paid' => 1])->field([
  831. 'sum(pay_price) as today_pay_price',
  832. ])->find();
  833. $price['today_pay_price'] = $sumNumber && $sumNumber['today_pay_price'] ? $sumNumber['today_pay_price'] : 0;
  834. return $price;
  835. }
  836. /**
  837. * 获取订单列表页面统计数据
  838. * @param $where
  839. * @return array
  840. */
  841. public function getBadge($where)
  842. {
  843. $price = $this->getOrderPrice($where);
  844. return [
  845. [
  846. 'name' => '订单数量',
  847. 'field' => '件',
  848. 'count' => $price['count_sum'],
  849. 'className' => 'md-basket',
  850. 'col' => 6
  851. ],
  852. [
  853. 'name' => '订单金额',
  854. 'field' => '元',
  855. 'count' => $price['pay_price'],
  856. 'className' => 'md-pricetags',
  857. 'col' => 6
  858. ],
  859. [
  860. 'name' => '今日订单数量',
  861. 'field' => '件',
  862. 'count' => $price['today_count_sum'],
  863. 'className' => 'ios-chatbubbles',
  864. 'col' => 6
  865. ],
  866. [
  867. 'name' => '今日支付金额',
  868. 'field' => '元',
  869. 'count' => $price['today_pay_price'],
  870. 'className' => 'ios-cash',
  871. 'col' => 6
  872. ],
  873. ];
  874. }
  875. /**
  876. *
  877. * @param array $where
  878. * @return mixed
  879. */
  880. public function orderStoreCount(array $where)
  881. {
  882. $defaultWhere = ['time' => $where['time'], 'store_id' => $where['store_id'] ?? 0, 'is_system_del' => 0];
  883. if (isset($where['store_id'])) {
  884. $defaultWhere['store_id'] = $where['store_id'];
  885. }
  886. //全部订单
  887. $data['all'] = (string)$this->dao->count(['pid' => 0] + $defaultWhere);
  888. //普通订单
  889. $data['general'] = (string)$this->dao->count(['pid' => 0, 'type' => 0] + $defaultWhere);
  890. //拼团订单
  891. $data['pink'] = (string)$this->dao->count(['pid' => 0, 'type' => 3] + $defaultWhere);
  892. //秒杀订单
  893. $data['seckill'] = (string)$this->dao->count(['pid' => 0, 'type' => 1] + $defaultWhere);
  894. //砍价订单
  895. $data['bargain'] = (string)$this->dao->count(['pid' => 0, 'type' => 2] + $defaultWhere);
  896. //收银订单
  897. $data['cashier'] = (string)$this->dao->count(['pid' => 0, 'type' => 6] + $defaultWhere);
  898. $data['write_off'] = (string)$this->dao->count(['pid' => 0, 'type' => 5] + $defaultWhere);
  899. $data['delivery'] = (string)$this->dao->count(['pid' => 0, 'type' => 7] + $defaultWhere);
  900. //预售订单
  901. $data['presale'] = (string)$this->dao->count(['pid' => 0, 'type' => 8] + $defaultWhere);
  902. switch ($where['type']) {
  903. case 0:
  904. $data['statusAll'] = $data['general'];
  905. break;
  906. case 1:
  907. $data['statusAll'] = $data['seckill'];
  908. break;
  909. case 2:
  910. $data['statusAll'] = $data['bargain'];
  911. break;
  912. case 3:
  913. $data['statusAll'] = $data['pink'];
  914. break;
  915. case 4:
  916. break;
  917. case 5:
  918. $data['statusAll'] = $data['write_off'];
  919. break;
  920. case 6:
  921. $data['statusAll'] = $data['cashier'];
  922. break;
  923. case 7:
  924. $data['statusAll'] = $data['delivery'];
  925. break;
  926. case 8:
  927. $data['statusAll'] = $data['presale'];
  928. break;
  929. default:
  930. $data['statusAll'] = $data['all'];
  931. }
  932. $count_where = ['pid' => 0, 'type' => $where['type']] + $defaultWhere;
  933. //未支付
  934. $data['unpaid'] = (string)$this->dao->count($count_where + ['status' => 0]);
  935. //未发货
  936. $data['unshipped'] = (string)$this->dao->count($count_where + ['status' => 1]);
  937. //部分发货
  938. $data['partshipped'] = (string)$this->dao->count($count_where + ['status' => 7]);
  939. //待收货
  940. $data['untake'] = (string)$this->dao->count($count_where + ['status' => 2]);
  941. //待核销
  942. $data['write_off'] = (string)$this->dao->count($count_where + ['status' => 5]);
  943. //已核销
  944. $data['write_offed'] = (string)$this->dao->count($count_where + ['status' => 6]);
  945. //待评价
  946. $data['unevaluate'] = (string)$this->dao->count($count_where + ['status' => 3]);
  947. //交易完成
  948. $data['complete'] = (string)$this->dao->count($count_where + ['status' => 4]);
  949. //退款中
  950. // $data['refunding'] = (string)$this->dao->count(['status' => -1, 'time' => $where['time'], 'is_system_del' => 0, 'type' => $where['type']]);
  951. //已退款
  952. // $data['refund'] = (string)$this->dao->count(['status' => -2, 'time' => $where['time'], 'is_system_del' => 0, 'type' => $where['type']]);
  953. //删除订单
  954. $data['del'] = (string)$this->dao->count($count_where + ['status' => -4]);
  955. return $data;
  956. }
  957. /**
  958. *
  959. * @param array $where
  960. * @return mixed
  961. */
  962. public function orderCount(array $where)
  963. {
  964. $default_where = [
  965. 'pid' => [0, -1],
  966. 'time' => $where['time'],
  967. 'status' => $where['status'],
  968. 'pay_type' => $where['pay_type'],
  969. 'field_key' => $where['field_key'],
  970. 'real_name' => $where['real_name'],
  971. 'is_system_del' => 0
  972. ];
  973. $count_where = ['type' => $where['type'] ?? 0, 'store_id' => $where['store_id'] ?? 0, 'supplier_id' => $where['supplier_id'] ?? 0];
  974. // if ($count_where['store_id'] || $count_where['supplier_id'] || (isset($where['plat_type']) && in_array($where['plat_type'], [1, 2]))) {
  975. // $default_where['pid'] = 0;
  976. // }
  977. //全部订单
  978. $data['all'] = (string)$this->dao->count($default_where + $count_where);
  979. //普通订单
  980. $data['general'] = (string)$this->dao->count(['type' => 0] + $default_where + $count_where);
  981. //平台订单
  982. $data['plat'] = (string)$this->dao->count(['plat_type' => 0, 'pid' => 0] + $default_where + $count_where);
  983. //门店订单
  984. $data['store'] = (string)$this->dao->count(['plat_type' => 1, 'pid' => 0] + $default_where + $count_where);
  985. //供应商订单
  986. $data['supplier'] = (string)$this->dao->count(['plat_type' => 2, 'pid' => 0] + $default_where + $count_where);
  987. //拼团订单
  988. $data['pink'] = (string)$this->dao->count(['type' => 3] + $default_where);
  989. //秒杀订单
  990. $data['seckill'] = (string)$this->dao->count(['type' => 1] + $default_where);
  991. //砍价订单
  992. $data['bargain'] = (string)$this->dao->count(['type' => 2] + $default_where);
  993. //预售订单
  994. $data['presale'] = (string)$this->dao->count(['type' => 8] + $default_where);
  995. $data['statusAll'] = $data['all'];
  996. if (trim($where['type'], ' ') !== '') {
  997. switch ($where['type']) {
  998. case 0:
  999. $data['statusAll'] = $data['general'];
  1000. break;
  1001. case 1:
  1002. $data['statusAll'] = $data['seckill'];
  1003. break;
  1004. case 2:
  1005. $data['statusAll'] = $data['bargain'];
  1006. break;
  1007. case 3:
  1008. $data['statusAll'] = $data['pink'];
  1009. break;
  1010. case 4:
  1011. break;
  1012. case 8:
  1013. $data['statusAll'] = $data['presale'];
  1014. break;
  1015. default:
  1016. $data['statusAll'] = $data['all'];
  1017. }
  1018. }
  1019. $count_where = ['type' => $where['type']] + $default_where;
  1020. //未支付
  1021. $data['unpaid'] = (string)$this->dao->count($count_where + ['status' => 0]);
  1022. //未发货
  1023. $data['unshipped'] = (string)$this->dao->count($count_where + ['status' => 1, 'shipping_type' => 1]);
  1024. //部分发货
  1025. $data['partshipped'] = (string)$this->dao->count($count_where + ['status' => 7, 'shipping_type' => 1]);
  1026. //待收货
  1027. $data['untake'] = (string)$this->dao->count($count_where + ['status' => 2, 'shipping_type' => 1]);
  1028. //待核销
  1029. $data['write_off'] = (string)$this->dao->count($count_where + ['status' => 5]);
  1030. //已核销
  1031. $data['write_offed'] = (string)$this->dao->count($count_where + ['status' => 6]);
  1032. //待评价
  1033. $data['unevaluate'] = (string)$this->dao->count($count_where + ['status' => 3]);
  1034. //交易完成
  1035. $data['complete'] = (string)$this->dao->count($count_where + ['status' => 4]);
  1036. //退款中
  1037. // $data['refunding'] = (string)$this->dao->count(['status' => -1, 'time' => $where['time'], 'is_system_del' => 0, 'type' => $where['type']]);
  1038. //已退款
  1039. // $data['refund'] = (string)$this->dao->count(['status' => -2, 'time' => $where['time'], 'is_system_del' => 0, 'type' => $where['type']]);
  1040. //删除订单
  1041. $data['del'] = (string)$this->dao->count($count_where + ['status' => -4]);
  1042. return $data;
  1043. }
  1044. /**
  1045. * 创建修改订单表单
  1046. * @param int $id
  1047. * @return array
  1048. * @throws \FormBuilder\Exception\FormBuilderException
  1049. */
  1050. public function updateForm(int $id)
  1051. {
  1052. $product = $this->dao->get($id);
  1053. if (!$product) {
  1054. throw new ValidateException('Data does not exist!');
  1055. }
  1056. $f = [];
  1057. $f[] = Form::input('order_id', '订单编号', $product->getData('order_id'))->disabled(true);
  1058. $f[] = Form::number('total_price', '商品总价', (float)$product->getData('total_price'))->min(0)->disabled(true);
  1059. $f[] = Form::number('total_postage', '原始邮费', (float)$product->getData('total_postage'))->min(0)->disabled(true);
  1060. $f[] = Form::number('pay_postage', '实际支付邮费', (float)$product->getData('pay_postage') ?: 0)->disabled(true);
  1061. $f[] = Form::number('pay_price', '实际支付金额', (float)$product->getData('pay_price'))->min(0);
  1062. $f[] = Form::number('gain_integral', '赠送积分', (float)$product->getData('gain_integral') ?: 0)->precision(0);
  1063. return create_form('修改订单', $f, $this->url('/order/update/' . $id), 'PUT');
  1064. }
  1065. /**
  1066. * 修改订单
  1067. * @param int $id
  1068. * @param array $data
  1069. * @return mixed
  1070. * @throws \Exception
  1071. */
  1072. public function updateOrder(int $id, array $data)
  1073. {
  1074. $order = $this->dao->getOne(['id' => $id, 'is_del' => 0]);
  1075. if (!$order) {
  1076. throw new ValidateException('订单不存在或已删除');
  1077. }
  1078. if ($order['paid']) {
  1079. throw new ValidateException('订单已支付');
  1080. }
  1081. //限制改价金额两位小数
  1082. $data['pay_price'] = sprintf("%.2f", $data['pay_price']);
  1083. $pay_price = $order['pay_price'];
  1084. if ($order['change_price']) {//已经改过一次价
  1085. $pay_price = bcadd((string)$pay_price, (string)$order['change_price'], 2);
  1086. }
  1087. //记录改价优惠金额
  1088. $data['change_price'] = (float)bcsub((string)$pay_price, (string)($data['pay_price'] ?? 0), 2);
  1089. /** @var StoreOrderStatusServices $services */
  1090. $services = app()->make(StoreOrderStatusServices::class);
  1091. $this->transaction(function () use ($id, $order, $data, $services) {
  1092. $res = $this->dao->update($id, $data);
  1093. $res = $res && $services->save([
  1094. 'oid' => $id,
  1095. 'change_type' => 'order_edit',
  1096. 'change_time' => time(),
  1097. 'change_message' => '商品总价为:' . $order['pay_price'] . ' 修改实际支付金额为:' . $data['pay_price']
  1098. ]);
  1099. if ($res) {
  1100. return true;
  1101. } else {
  1102. throw new ValidateException('Modification failed');
  1103. }
  1104. });
  1105. //新订单号
  1106. // $order['order_id'] = $data['order_id'];
  1107. //改价提醒
  1108. event('order.price', [$order, $data['pay_price']]);
  1109. return true;
  1110. }
  1111. /**
  1112. * 订单图表
  1113. * @param $cycle
  1114. * @return array
  1115. */
  1116. public function orderCharts($cycle)
  1117. {
  1118. $datalist = [];
  1119. $where = [];
  1120. $series1 = ['normal' => ['color' => [
  1121. 'x' => 0, 'y' => 0, 'x2' => 0, 'y2' => 1,
  1122. 'colorStops' => [
  1123. [
  1124. 'offset' => 0,
  1125. 'color' => '#69cdff'
  1126. ],
  1127. [
  1128. 'offset' => 0.5,
  1129. 'color' => '#3eb3f7'
  1130. ],
  1131. [
  1132. 'offset' => 1,
  1133. 'color' => '#1495eb'
  1134. ]
  1135. ]
  1136. ]]
  1137. ];
  1138. $series2 = ['normal' => ['color' => [
  1139. 'x' => 0, 'y' => 0, 'x2' => 0, 'y2' => 1,
  1140. 'colorStops' => [
  1141. [
  1142. 'offset' => 0,
  1143. 'color' => '#6fdeab'
  1144. ],
  1145. [
  1146. 'offset' => 0.5,
  1147. 'color' => '#44d693'
  1148. ],
  1149. [
  1150. 'offset' => 1,
  1151. 'color' => '#2cc981'
  1152. ]
  1153. ]
  1154. ]]
  1155. ];
  1156. $chartdata = [];
  1157. $data = [];//临时
  1158. $chartdata['yAxis']['maxnum'] = 0;//最大值数量
  1159. $chartdata['yAxis']['maxprice'] = 0;//最大值金额
  1160. switch ($cycle) {
  1161. case 'thirtyday':
  1162. //上期
  1163. $datebefor = date('Y-m-d 00:00:00', strtotime('-59 day'));
  1164. $dateafter = date('Y-m-d 23:59:59', strtotime('-29 day'));
  1165. //当前
  1166. $now_datebefor = date('Y-m-d 00:00:00', strtotime('-29 day'));
  1167. $now_dateafter = date('Y-m-d 23:59:59');
  1168. for ($i = -29; $i <= 0; $i++) {
  1169. $datalist[date('Y-m-d', strtotime($i . ' day'))] = date('Y-m-d', strtotime($i . ' day'));
  1170. }
  1171. $order_list = $this->dao->orderAddTimeList($where, [$now_datebefor, $now_dateafter], 'day');
  1172. if (empty($order_list)) return ['yAxis' => [], 'legend' => [], 'xAxis' => [], 'serise' => [], 'pre_cycle' => [], 'cycle' => []];
  1173. $order_list = array_combine(array_column($order_list, 'day'), $order_list);
  1174. $cycle_list = [];
  1175. foreach ($datalist as $dk => $dd) {
  1176. if (isset($order_list[$dk]) && !empty($order_list[$dd])) {
  1177. $cycle_list[$dd] = $order_list[$dd];
  1178. } else {
  1179. $cycle_list[$dd] = ['count' => 0, 'day' => $dd, 'price' => ''];
  1180. }
  1181. }
  1182. foreach ($cycle_list as $k => $v) {
  1183. $data['day'][] = $v['day'];
  1184. $data['count'][] = $v['count'];
  1185. $data['price'][] = round($v['price'], 2);
  1186. if ($chartdata['yAxis']['maxnum'] < $v['count'])
  1187. $chartdata['yAxis']['maxnum'] = $v['count'];//日最大订单数
  1188. if ($chartdata['yAxis']['maxprice'] < $v['price'])
  1189. $chartdata['yAxis']['maxprice'] = $v['price'];//日最大金额
  1190. }
  1191. $chartdata['legend'] = ['订单金额', '订单数'];//分类
  1192. $chartdata['xAxis'] = $data['day'];//X轴值
  1193. $chartdata['series'][] = ['name' => $chartdata['legend'][0], 'type' => 'bar', 'itemStyle' => $series1, 'data' => $data['price']];//分类1值
  1194. $chartdata['series'][] = ['name' => $chartdata['legend'][1], 'type' => 'line', 'itemStyle' => $series2, 'data' => $data['count'], 'yAxisIndex' => 1];//分类2值
  1195. break;
  1196. case 'week':
  1197. $weekarray = [['周日'], ['周一'], ['周二'], ['周三'], ['周四'], ['周五'], ['周六']];
  1198. $datebefor = date('Y-m-d 00:00:00', strtotime('-1 week Monday'));
  1199. $dateafter = date('Y-m-d 23:59:59', strtotime('-1 week Sunday'));
  1200. $order_list = $this->dao->orderAddTimeList($where, [$datebefor, $dateafter], 'week');
  1201. //数据查询重新处理
  1202. $new_order_list = array_combine(array_column($order_list, 'day'), $order_list);
  1203. $now_datebefor = date('Y-m-d 00:00:00', (time() - ((date('w') == 0 ? 7 : date('w')) - 1) * 24 * 3600));
  1204. $now_dateafter = date('Y-m-d 23:59:59', strtotime("+1 day"));
  1205. $now_order_list = $this->dao->orderAddTimeList($where, [$now_datebefor, $now_dateafter], 'week');
  1206. //数据查询重新处理 key 变为当前值
  1207. $new_now_order_list = array_combine(array_column($now_order_list, 'day'), $now_order_list);
  1208. foreach ($weekarray as $dk => $dd) {
  1209. if (isset($new_order_list[$dk]) && !empty($new_order_list[$dk])) {
  1210. $weekarray[$dk]['pre'] = $new_order_list[$dk];
  1211. } else {
  1212. $weekarray[$dk]['pre'] = ['count' => 0, 'day' => $weekarray[$dk][0], 'price' => '0'];
  1213. }
  1214. if (isset($new_now_order_list[$dk]) && !empty($new_now_order_list[$dk])) {
  1215. $weekarray[$dk]['now'] = $new_now_order_list[$dk];
  1216. } else {
  1217. $weekarray[$dk]['now'] = ['count' => 0, 'day' => $weekarray[$dk][0], 'price' => '0'];
  1218. }
  1219. }
  1220. foreach ($weekarray as $k => $v) {
  1221. $data['day'][] = $v[0];
  1222. $data['pre']['count'][] = $v['pre']['count'];
  1223. $data['pre']['price'][] = round($v['pre']['price'], 2);
  1224. $data['now']['count'][] = $v['now']['count'];
  1225. $data['now']['price'][] = round($v['now']['price'], 2);
  1226. if ($chartdata['yAxis']['maxnum'] < $v['pre']['count'] || $chartdata['yAxis']['maxnum'] < $v['now']['count']) {
  1227. $chartdata['yAxis']['maxnum'] = $v['pre']['count'] > $v['now']['count'] ? $v['pre']['count'] : $v['now']['count'];//日最大订单数
  1228. }
  1229. if ($chartdata['yAxis']['maxprice'] < $v['pre']['price'] || $chartdata['yAxis']['maxprice'] < $v['now']['price']) {
  1230. $chartdata['yAxis']['maxprice'] = $v['pre']['price'] > $v['now']['price'] ? $v['pre']['price'] : $v['now']['price'];//日最大金额
  1231. }
  1232. }
  1233. $chartdata['legend'] = ['上周金额', '本周金额', '上周订单数', '本周订单数'];//分类
  1234. $chartdata['xAxis'] = $data['day'];//X轴值
  1235. $chartdata['series'][] = ['name' => $chartdata['legend'][0], 'type' => 'bar', 'itemStyle' => $series1, 'data' => $data['pre']['price']];//分类1值
  1236. $chartdata['series'][] = ['name' => $chartdata['legend'][1], 'type' => 'bar', 'itemStyle' => $series1, 'data' => $data['now']['price']];//分类1值
  1237. $chartdata['series'][] = ['name' => $chartdata['legend'][2], 'type' => 'line', 'itemStyle' => $series2, 'data' => $data['pre']['count'], 'yAxisIndex' => 1];//分类2值
  1238. $chartdata['series'][] = ['name' => $chartdata['legend'][3], 'type' => 'line', 'itemStyle' => $series2, 'data' => $data['now']['count'], 'yAxisIndex' => 1];//分类2值
  1239. break;
  1240. case 'month':
  1241. $weekarray = ['01' => ['1'], '02' => ['2'], '03' => ['3'], '04' => ['4'], '05' => ['5'], '06' => ['6'], '07' => ['7'], '08' => ['8'], '09' => ['9'], '10' => ['10'], '11' => ['11'], '12' => ['12'], '13' => ['13'], '14' => ['14'], '15' => ['15'], '16' => ['16'], '17' => ['17'], '18' => ['18'], '19' => ['19'], '20' => ['20'], '21' => ['21'], '22' => ['22'], '23' => ['23'], '24' => ['24'], '25' => ['25'], '26' => ['26'], '27' => ['27'], '28' => ['28'], '29' => ['29'], '30' => ['30'], '31' => ['31']];
  1242. $datebefor = date('Y-m-01 00:00:00', strtotime('-1 month'));
  1243. $dateafter = date('Y-m-d 23:59:59', strtotime(date('Y-m-01')));
  1244. $order_list = $this->dao->orderAddTimeList($where, [$datebefor, $dateafter], "month");
  1245. //数据查询重新处理
  1246. $new_order_list = array_combine(array_column($order_list, 'day'), $order_list);
  1247. $now_datebefor = date('Y-m-01 00:00:00');
  1248. $now_dateafter = date('Y-m-d', strtotime("+1 day"));
  1249. $now_order_list = $this->dao->orderAddTimeList($where, [$now_datebefor, $now_dateafter], "month");
  1250. //数据查询重新处理 key 变为当前值
  1251. $new_now_order_list = array_combine(array_column($now_order_list, 'day'), $now_order_list);
  1252. foreach ($weekarray as $dk => $dd) {
  1253. if (isset($new_order_list[$dk]) && !empty($new_order_list[$dk])) {
  1254. $weekarray[$dk]['pre'] = $new_order_list[$dk];
  1255. } else {
  1256. $weekarray[$dk]['pre'] = ['count' => 0, 'day' => $weekarray[$dk][0], 'price' => '0'];
  1257. }
  1258. if (isset($new_now_order_list[$dk]) && !empty($new_now_order_list[$dk])) {
  1259. $weekarray[$dk]['now'] = $new_now_order_list[$dk];
  1260. } else {
  1261. $weekarray[$dk]['now'] = ['count' => 0, 'day' => $weekarray[$dk][0], 'price' => '0'];
  1262. }
  1263. }
  1264. foreach ($weekarray as $k => $v) {
  1265. $data['day'][] = $v[0];
  1266. $data['pre']['count'][] = $v['pre']['count'];
  1267. $data['pre']['price'][] = round($v['pre']['price'], 2);
  1268. $data['now']['count'][] = $v['now']['count'];
  1269. $data['now']['price'][] = round($v['now']['price'], 2);
  1270. if ($chartdata['yAxis']['maxnum'] < $v['pre']['count'] || $chartdata['yAxis']['maxnum'] < $v['now']['count']) {
  1271. $chartdata['yAxis']['maxnum'] = $v['pre']['count'] > $v['now']['count'] ? $v['pre']['count'] : $v['now']['count'];//日最大订单数
  1272. }
  1273. if ($chartdata['yAxis']['maxprice'] < $v['pre']['price'] || $chartdata['yAxis']['maxprice'] < $v['now']['price']) {
  1274. $chartdata['yAxis']['maxprice'] = $v['pre']['price'] > $v['now']['price'] ? $v['pre']['price'] : $v['now']['price'];//日最大金额
  1275. }
  1276. }
  1277. $chartdata['legend'] = ['上月金额', '本月金额', '上月订单数', '本月订单数'];//分类
  1278. $chartdata['xAxis'] = $data['day'];//X轴值
  1279. $chartdata['series'][] = ['name' => $chartdata['legend'][0], 'type' => 'bar', 'itemStyle' => $series1, 'data' => $data['pre']['price']];//分类1值
  1280. $chartdata['series'][] = ['name' => $chartdata['legend'][1], 'type' => 'bar', 'itemStyle' => $series1, 'data' => $data['now']['price']];//分类1值
  1281. $chartdata['series'][] = ['name' => $chartdata['legend'][2], 'type' => 'line', 'itemStyle' => $series2, 'data' => $data['pre']['count'], 'yAxisIndex' => 1];//分类2值
  1282. $chartdata['series'][] = ['name' => $chartdata['legend'][3], 'type' => 'line', 'itemStyle' => $series2, 'data' => $data['now']['count'], 'yAxisIndex' => 1];//分类2值
  1283. break;
  1284. case 'year':
  1285. $weekarray = ['01' => ['一月'], '02' => ['二月'], '03' => ['三月'], '04' => ['四月'], '05' => ['五月'], '06' => ['六月'], '07' => ['七月'], '08' => ['八月'], '09' => ['九月'], '10' => ['十月'], '11' => ['十一月'], '12' => ['十二月']];
  1286. $datebefor = date('Y-01-01 00:00:00', strtotime('-1 year'));
  1287. $dateafter = date('Y-12-31 23:59:59', strtotime('-1 year'));
  1288. $order_list = $this->dao->orderAddTimeList($where, [$datebefor, $dateafter], 'year');
  1289. //数据查询重新处理
  1290. $new_order_list = array_combine(array_column($order_list, 'day'), $order_list);
  1291. $now_datebefor = date('Y-01-01 00:00:00');
  1292. $now_dateafter = date('Y-12-31 23:59:59');
  1293. $now_order_list = $this->dao->orderAddTimeList($where, [$now_datebefor, $now_dateafter], 'year');
  1294. //数据查询重新处理 key 变为当前值
  1295. $new_now_order_list = array_combine(array_column($now_order_list, 'day'), $now_order_list);
  1296. $y = date('Y');
  1297. foreach ($weekarray as $dk => $dd) {
  1298. $order_dk = $y . '-' . $dk;
  1299. if (isset($new_order_list[$order_dk]) && !empty($new_order_list[$order_dk])) {
  1300. $weekarray[$dk]['pre'] = $new_order_list[$order_dk];
  1301. } else {
  1302. $weekarray[$dk]['pre'] = ['count' => 0, 'day' => $weekarray[$dk][0], 'price' => '0'];
  1303. }
  1304. if (isset($new_now_order_list[$order_dk]) && !empty($new_now_order_list[$order_dk])) {
  1305. $weekarray[$dk]['now'] = $new_now_order_list[$order_dk];
  1306. } else {
  1307. $weekarray[$dk]['now'] = ['count' => 0, 'day' => $weekarray[$dk][0], 'price' => '0'];
  1308. }
  1309. }
  1310. foreach ($weekarray as $k => $v) {
  1311. $data['day'][] = $v[0];
  1312. $data['pre']['count'][] = $v['pre']['count'];
  1313. $data['pre']['price'][] = round($v['pre']['price'], 2);
  1314. $data['now']['count'][] = $v['now']['count'];
  1315. $data['now']['price'][] = round($v['now']['price'], 2);
  1316. if ($chartdata['yAxis']['maxnum'] < $v['pre']['count'] || $chartdata['yAxis']['maxnum'] < $v['now']['count']) {
  1317. $chartdata['yAxis']['maxnum'] = $v['pre']['count'] > $v['now']['count'] ? $v['pre']['count'] : $v['now']['count'];//日最大订单数
  1318. }
  1319. if ($chartdata['yAxis']['maxprice'] < $v['pre']['price'] || $chartdata['yAxis']['maxprice'] < $v['now']['price']) {
  1320. $chartdata['yAxis']['maxprice'] = $v['pre']['price'] > $v['now']['price'] ? $v['pre']['price'] : $v['now']['price'];//日最大金额
  1321. }
  1322. }
  1323. $chartdata['legend'] = ['去年金额', '今年金额', '去年订单数', '今年订单数'];//分类
  1324. $chartdata['xAxis'] = $data['day'];//X轴值
  1325. $chartdata['series'][] = ['name' => $chartdata['legend'][0], 'type' => 'bar', 'itemStyle' => $series1, 'data' => $data['pre']['price']];//分类1值
  1326. $chartdata['series'][] = ['name' => $chartdata['legend'][1], 'type' => 'bar', 'itemStyle' => $series1, 'data' => $data['now']['price']];//分类1值
  1327. $chartdata['series'][] = ['name' => $chartdata['legend'][2], 'type' => 'line', 'itemStyle' => $series2, 'data' => $data['pre']['count'], 'yAxisIndex' => 1];//分类2值
  1328. $chartdata['series'][] = ['name' => $chartdata['legend'][3], 'type' => 'line', 'itemStyle' => $series2, 'data' => $data['now']['count'], 'yAxisIndex' => 1];//分类2值
  1329. break;
  1330. default:
  1331. break;
  1332. }
  1333. //统计总数上期
  1334. $pre_total = $this->dao->preTotalFind($where, [$datebefor, $dateafter]);
  1335. if ($pre_total) {
  1336. $chartdata['pre_cycle']['count'] = [
  1337. 'data' => $pre_total['count'] ?: 0
  1338. ];
  1339. $chartdata['pre_cycle']['price'] = [
  1340. 'data' => $pre_total['price'] ?: 0
  1341. ];
  1342. }
  1343. //统计总数
  1344. $total = $this->dao->preTotalFind($where, [$now_datebefor, $now_dateafter]);
  1345. if ($total) {
  1346. $cha_count = intval($pre_total['count']) - intval($total['count']);
  1347. $pre_total['count'] = $pre_total['count'] == 0 ? 1 : $pre_total['count'];
  1348. $chartdata['cycle']['count'] = [
  1349. 'data' => $total['count'] ?: 0,
  1350. 'percent' => round((abs($cha_count) / intval($pre_total['count']) * 100), 2),
  1351. 'is_plus' => $cha_count > 0 ? -1 : ($cha_count == 0 ? 0 : 1)
  1352. ];
  1353. $cha_price = round($pre_total['price'], 2) - round($total['price'], 2);
  1354. $pre_total['price'] = $pre_total['price'] == 0 ? 1 : $pre_total['price'];
  1355. $chartdata['cycle']['price'] = [
  1356. 'data' => $total['price'] ?: 0,
  1357. 'percent' => round(abs($cha_price) / $pre_total['price'] * 100, 2),
  1358. 'is_plus' => $cha_price > 0 ? -1 : ($cha_price == 0 ? 0 : 1)
  1359. ];
  1360. }
  1361. return $chartdata;
  1362. }
  1363. /**
  1364. * 获取订单数量
  1365. * @param int $store_id
  1366. * @param int $type
  1367. * @param string $field
  1368. * @return int
  1369. */
  1370. public function storeOrderCount(int $store_id = 0, int $type = -1, string $field = 'store_id')
  1371. {
  1372. return $this->dao->storeOrderCount($store_id, $type, $field);
  1373. }
  1374. /**
  1375. * 首页头部统计
  1376. * @return array
  1377. */
  1378. public function homeStatics()
  1379. {
  1380. /** @var UserServices $uSercice */
  1381. $uSercice = app()->make(UserServices::class);
  1382. /** @var StoreProductLogServices $productLogServices */
  1383. $productLogServices = app()->make(StoreProductLogServices::class);
  1384. // 销售额
  1385. //今日销售额
  1386. $today_sales = $this->dao->totalSales('today');
  1387. //昨日销售额
  1388. $yesterday_sales = $this->dao->totalSales('yesterday');
  1389. //日同比
  1390. $sales_today_ratio = $this->countRate($today_sales, $yesterday_sales);
  1391. //周销售额
  1392. // //本周
  1393. // $this_week_sales = $this->dao->totalSales('week');
  1394. // //上周
  1395. // $last_week_sales = $this->dao->totalSales('last week');
  1396. // //周同比
  1397. // $sales_week_ratio = $this->countRate($this_week_sales, $last_week_sales);
  1398. //总销售额
  1399. $total_sales = $this->dao->totalSales('month');
  1400. $sales = [
  1401. 'today' => $today_sales,
  1402. 'yesterday' => $yesterday_sales,
  1403. 'today_ratio' => $sales_today_ratio,
  1404. // 'week' => $this_week_sales,
  1405. // 'last_week' => $last_week_sales,
  1406. // 'week_ratio' => $sales_week_ratio,
  1407. 'total' => $total_sales . '元',
  1408. 'date' => '今日'
  1409. ];
  1410. //用户访问量
  1411. //今日访问量
  1412. $today_visits = $productLogServices->count(['time' => 'today', 'type' => 'visit']);
  1413. //昨日访问量
  1414. $yesterday_visits = $productLogServices->count(['time' => 'yesterday', 'type' => 'visit']);
  1415. //日同比
  1416. $visits_today_ratio = $this->countRate($today_visits, $yesterday_visits);
  1417. // //本周访问量
  1418. // $this_week_visits = $productLogServices->count(['time' => 'week', 'type' => 'visit']);
  1419. // //上周访问量
  1420. // $last_week_visits = $productLogServices->count(['time' => 'last week', 'type' => 'visit']);
  1421. // //周同比
  1422. // $visits_week_ratio = $this->countRate($this_week_visits, $last_week_visits);
  1423. //总访问量
  1424. $total_visits = $productLogServices->count(['time' => 'month', 'type' => 'visit']);
  1425. $visits = [
  1426. 'today' => $today_visits,
  1427. 'yesterday' => $yesterday_visits,
  1428. 'today_ratio' => $visits_today_ratio,
  1429. // 'week' => $this_week_visits,
  1430. // 'last_week' => $last_week_visits,
  1431. // 'week_ratio' => $visits_week_ratio,
  1432. 'total' => $total_visits . 'Pv',
  1433. 'date' => '今日'
  1434. ];
  1435. // 订单量
  1436. //今日订单量
  1437. $today_order = $this->dao->totalOrderCount('today');
  1438. //昨日订单量
  1439. $yesterday_order = $this->dao->totalOrderCount('yesterday');
  1440. //订单日同比
  1441. $order_today_ratio = $this->countRate($today_order, $yesterday_order);
  1442. // //本周订单量
  1443. // $this_week_order = $this->dao->totalOrderCount('week');
  1444. // //上周订单量
  1445. // $last_week_order = $this->dao->totalOrderCount('last week');
  1446. // //订单周同比
  1447. // $order_week_ratio = $this->countRate($this_week_order, $last_week_order);
  1448. //总订单量
  1449. $total_order = $this->dao->totalOrderCount('month');
  1450. $order = [
  1451. 'today' => $today_order,
  1452. 'yesterday' => $yesterday_order,
  1453. 'today_ratio' => $order_today_ratio,
  1454. // 'week' => $this_week_order,
  1455. // 'last_week' => $last_week_order,
  1456. // 'week_ratio' => $order_week_ratio,
  1457. 'total' => $total_order . '单',
  1458. 'date' => '今日'
  1459. ];
  1460. // 用户
  1461. //今日新增用户
  1462. $today_user = $uSercice->totalUserCount('today');
  1463. //昨日新增用户
  1464. $yesterday_user = $uSercice->totalUserCount('yesterday');
  1465. //新增用户日同比
  1466. $user_today_ratio = $this->countRate($today_user, $yesterday_user);
  1467. // //本周新增用户
  1468. // $this_week_user = $uSercice->totalUserCount('week');
  1469. // //上周新增用户
  1470. // $last_week_user = $uSercice->totalUserCount('last week');
  1471. // //新增用户周同比
  1472. // $user_week_ratio = $this->countRate($this_week_user, $last_week_user);
  1473. //本月新增用户
  1474. $total_user = $uSercice->totalUserCount('month');
  1475. $user = [
  1476. 'today' => $today_user,
  1477. 'yesterday' => $yesterday_user,
  1478. 'today_ratio' => $user_today_ratio,
  1479. // 'week' => $this_week_user,
  1480. // 'last_week' => $last_week_user,
  1481. // 'week_ratio' => $user_week_ratio,
  1482. 'total' => $total_user . '人',
  1483. 'date' => '今日'
  1484. ];
  1485. $integralService = app()->make(UserAwardIntegralServices::class);
  1486. $integral['active'] = $integralService->getIntegralSum(['status' => 0, 'type' => 1]);
  1487. $integral['static'] = $integralService->getIntegralSum(['status' => 0, 'type' => 0]);
  1488. $info = array_values(compact('sales', 'visits', 'order', 'user', 'integral'));
  1489. $info[0]['title'] = '销售额';
  1490. $info[1]['title'] = '用户访问量';
  1491. $info[2]['title'] = '订单量';
  1492. $info[3]['title'] = '新增用户';
  1493. $info[0]['total_name'] = '本月销售额';
  1494. $info[1]['total_name'] = '本月访问量';
  1495. $info[2]['total_name'] = '本月订单量';
  1496. $info[3]['total_name'] = '本月新增用户';
  1497. return $info;
  1498. }
  1499. /**
  1500. * 打印订单
  1501. * @param int $id
  1502. * @param bool $isTable
  1503. * @return bool
  1504. */
  1505. public function orderPrint(int $id, int $type = -1, int $relation_id = -1, bool $isTable = false)
  1506. {
  1507. $order = $this->dao->get($id);
  1508. if (!$order) {
  1509. throw new ValidateException('订单信息不存在!');
  1510. }
  1511. $order = $order->toArray();
  1512. /** @var StoreOrderCartInfoServices $cartServices */
  1513. $cartServices = app()->make(StoreOrderCartInfoServices::class);
  1514. $product = $cartServices->getCartInfoPrintProduct((int)$order['id']);
  1515. if (!$product) {
  1516. throw new ValidateException('订单商品获取失败,无法打印!');
  1517. }
  1518. if ($type == -1 && $relation_id == -1) {//取订单属于那一端
  1519. $type = $relation_id = 0;
  1520. if (isset($order['store_id']) && $order['store_id']) {
  1521. $store_id = (int)$order['store_id'];
  1522. if ($isTable) {
  1523. if (isset($order['type']) && $order['type'] == 10) {
  1524. $print = store_config($store_id, 'store_printing_timing');
  1525. if (!$print || !is_array($print) || !in_array(2, $print)) {
  1526. return true;
  1527. }
  1528. }
  1529. }
  1530. $type = 1;
  1531. $relation_id = $store_id;
  1532. } elseif (isset($order['supplier_id']) && $order['supplier_id']) {
  1533. $supplier_id = (int)$order['supplier_id'];
  1534. $type = 2;
  1535. $relation_id = $supplier_id;
  1536. }
  1537. }
  1538. /** @var ConfigServices $configServices */
  1539. $configServices = app()->make(ConfigServices::class);
  1540. [$switch, $name, $configData] = $configServices->getPrintingConfig($type, $relation_id);
  1541. if (!$switch) {
  1542. throw new ValidateException('请先开启小票打印');
  1543. }
  1544. foreach ($configData as $value) {
  1545. if (!$value) {
  1546. throw new ValidateException('请先配置小票打印开发者');
  1547. }
  1548. }
  1549. $printer = new Printer($name, $configData);
  1550. $printer->setPrinterContent([
  1551. 'name' => sys_config('site_name'),
  1552. 'orderInfo' => is_object($order) ? $order->toArray() : $order,
  1553. 'product' => $product
  1554. ])->startPrinter();
  1555. return true;
  1556. }
  1557. /**
  1558. * 获取订单确认数据
  1559. * @param array $user
  1560. * @param $cartId
  1561. * @param bool $new
  1562. * @param int $addressId
  1563. * @param int $shipping_type
  1564. * @param int $store_id
  1565. * @param int $coupon_id
  1566. * @return array
  1567. * @throws \Psr\SimpleCache\InvalidArgumentException
  1568. * @throws \think\db\exception\DataNotFoundException
  1569. * @throws \think\db\exception\DbException
  1570. * @throws \think\db\exception\ModelNotFoundException
  1571. */
  1572. public function getOrderConfirmData(array $user, $cartId, bool $new, int $addressId, int $shipping_type = 1, int $store_id = 0, int $coupon_id = 0)
  1573. {
  1574. $addr = $data = [];
  1575. $uid = (int)$user['uid'];
  1576. /** @var UserAddressServices $addressServices */
  1577. $addressServices = app()->make(UserAddressServices::class);
  1578. if ($addressId) {
  1579. $addr = $addressServices->getAdderssCache($addressId);
  1580. }
  1581. //没传地址id或地址已删除未找到 ||获取默认地址
  1582. if (!$addr) {
  1583. $addr = $addressServices->getUserDefaultAddressCache($uid);
  1584. }
  1585. $data['upgrade_addr'] = 0;
  1586. if ($addr) {
  1587. $addr = is_object($addr) ? $addr->toArray() : $addr;
  1588. if (isset($addr['upgrade']) && $addr['upgrade'] == 0) {
  1589. $data['upgrade_addr'] = 1;
  1590. }
  1591. } else {
  1592. $addr = [];
  1593. }
  1594. if ($store_id) {
  1595. /** @var SystemStoreServices $storeServices */
  1596. $storeServices = app()->make(SystemStoreServices::class);
  1597. $storeServices->getStoreInfo($store_id);
  1598. }
  1599. /** @var StoreCartServices $cartServices */
  1600. $cartServices = app()->make(StoreCartServices::class);
  1601. //获取购物车信息
  1602. $cartGroup = $cartServices->getUserProductCartListV1($uid, $cartId, $new, $addr, $shipping_type, $store_id, $coupon_id);
  1603. $storeFreePostage = floatval(sys_config('store_free_postage')) ?: 0;//满额包邮金额
  1604. $data['storeFreePostage'] = $storeFreePostage;
  1605. $validCartInfo = $cartGroup['valid'];
  1606. $giveCartList = $cartGroup['giveCartList'] ?? [];
  1607. /** @var StoreOrderComputedServices $computedServices */
  1608. $computedServices = app()->make(StoreOrderComputedServices::class);
  1609. $priceGroup = $computedServices->getOrderPriceGroup($validCartInfo, $addr, $user, $storeFreePostage);
  1610. $priceGroup['couponPrice'] = $cartGroup['couponPrice'] ?? 0;
  1611. $priceGroup['firstOrderPrice'] = $cartGroup['firstOrderPrice'] ?? 0;
  1612. $validCartInfo = array_merge($priceGroup['cartInfo'] ?? $validCartInfo, $giveCartList);
  1613. $other = [
  1614. 'offlinePostage' => sys_config('offline_postage'),
  1615. 'integralRatio' => sys_config('integral_ratio'),
  1616. 'give_integral' => $cartGroup['giveIntegral'] ?? 0,
  1617. 'give_coupon' => $cartGroup['giveCoupon'] ?? [],
  1618. 'give_product' => $cartGroup['giveProduct'],
  1619. 'promotions' => $cartGroup['promotions']
  1620. ];
  1621. $deduction = $cartGroup['deduction'];
  1622. $data['product_type'] = $deduction['product_type'] ?? 0;
  1623. $data['valid_count'] = count($validCartInfo);
  1624. $data['addressInfo'] = $addr;
  1625. $data['type'] = $deduction['type'] ?? 0;
  1626. $data['activity_id'] = $deduction['activity_id'] ?? 0;
  1627. $data['seckill_id'] = $deduction['type'] == 1 ? $deduction['activity_id'] : 0;
  1628. $data['bargain_id'] = $deduction['type'] == 2 ? $deduction['activity_id'] : 0;
  1629. $data['combination_id'] = $deduction['type'] == 3 ? $deduction['activity_id'] : 0;
  1630. $data['luck_record_id'] = $deduction['type'] == 8 ? $deduction['activity_id'] : 0;
  1631. $data['collate_code_id'] = $deduction['type'] == 9 || $deduction['type'] == 10 ? $deduction['collate_code_id'] : 0;
  1632. $data['discount_id'] = $deduction['type'] == 5 ? $deduction['activity_id'] : 0;
  1633. $data['newcomer_id'] = $deduction['type'] == 7 ? $deduction['activity_id'] : 0;
  1634. $data['deduction'] = in_array($deduction['product_type'], [1, 2]) || $deduction['activity_id'] > 0;
  1635. $data['cartInfo'] = array_merge($cartGroup['cartInfo'], $giveCartList);
  1636. // $data['giveCartInfo'] = $giveCartList;
  1637. $data['custom_form'] = [];
  1638. if (isset($cartGroup['cartInfo'][0]['productInfo']['system_form_id']) && $cartGroup['cartInfo'][0]['productInfo']['system_form_id']) {
  1639. /** @var SystemFormServices $systemFormServices */
  1640. $systemFormServices = app()->make(SystemFormServices::class);
  1641. $formInfo = $systemFormServices->value(['id' => $cartGroup['cartInfo'][0]['productInfo']['system_form_id']], 'value');
  1642. if ($formInfo) {
  1643. $data['custom_form'] = is_string($formInfo) ? json_decode($formInfo, true) : $formInfo;
  1644. }
  1645. }
  1646. $data['give_integral'] = $other['give_integral'];
  1647. $data['give_coupon'] = [];
  1648. if ($other['give_coupon']) {
  1649. /** @var StoreCouponIssueServices $couponIssueService */
  1650. $couponIssueService = app()->make(StoreCouponIssueServices::class);
  1651. $data['give_coupon'] = $couponIssueService->getColumn([['id', 'IN', $other['give_coupon']]], 'id,coupon_title');
  1652. }
  1653. $data['priceGroup'] = $priceGroup;
  1654. $data['orderKey'] = $this->cacheOrderInfo($uid, $validCartInfo, $priceGroup, $other, $addr, $cartGroup['invalid'] ?? [], $deduction);
  1655. $data['offlinePostage'] = $other['offlinePostage'];
  1656. if (isset($user['pwd'])) unset($user['pwd']);
  1657. $user['vip'] = isset($priceGroup['vipPrice']) && $priceGroup['vipPrice'] > 0;
  1658. $user['vip_id'] = 0;
  1659. $user['discount'] = 0;
  1660. //用户等级是否开启
  1661. if (sys_config('member_func_status', 1)) {
  1662. /** @var UserLevelServices $levelServices */
  1663. $levelServices = app()->make(UserLevelServices::class);
  1664. $userLevel = $levelServices->getUerLevelInfoByUid($uid);
  1665. if ($user['vip'] || $userLevel) {
  1666. $user['vip'] = true;
  1667. $user['vip_id'] = $userLevel['id'] ?? 0;
  1668. $user['discount'] = $userLevel['discount'] ?? 0;
  1669. }
  1670. }
  1671. $user['record_pone'] = !isset($user['record_pone']) || !$user['record_pone'] ? '' : $user['record_pone'];
  1672. $data['userInfo'] = $user;
  1673. $data['integralRatio'] = $other['integralRatio'];
  1674. $data['offline_pay_status'] = (int)sys_config('offline_pay_status') ?? (int)2;
  1675. $data['yue_pay_status'] = (int)sys_config('balance_func_status') && (int)sys_config('yue_pay_status') == 1 ? (int)1 : (int)2;//余额支付 1 开启 2 关闭
  1676. $data['pay_weixin_open'] = (int)sys_config('pay_weixin_open') ?? 0;//微信支付 1 开启 0 关闭
  1677. $data['store_func_status'] = (int)(sys_config('store_func_status', 1));//门店是否开启
  1678. $data['store_self_mention'] = false;//门店自提
  1679. $data['store_delivery_status'] = false;//门店配送
  1680. if ($data['store_func_status']) {
  1681. //门店自提是否开启
  1682. /** @var SystemStoreServices $systemStoreServices */
  1683. $systemStoreServices = app()->make(SystemStoreServices::class);
  1684. $data['store_self_mention'] = sys_config('store_self_mention') && $systemStoreServices->count(['type' => 0, 'is_store' => 1]);
  1685. $data['store_delivery_status'] = !!$systemStoreServices->count(['type' => 0]);
  1686. }
  1687. $data['store_func_status'] = $data['store_func_status'] && ($data['store_self_mention'] || $data['store_delivery_status']);
  1688. $data['ali_pay_status'] = (bool)sys_config('ali_pay_status');//支付包支付 1 开启 0 关闭
  1689. $data['system_store'] = [];//门店信息
  1690. /** @var UserInvoiceServices $userInvoice */
  1691. $userInvoice = app()->make(UserInvoiceServices::class);
  1692. $invoice_func = $userInvoice->invoiceFuncStatus();
  1693. $data['invoice_func'] = $invoice_func['invoice_func'];
  1694. $data['special_invoice'] = $invoice_func['special_invoice'];
  1695. $data['integral_ratio_status'] = (int)sys_config('integral_ratio_status', 1);
  1696. return $data;
  1697. }
  1698. /**
  1699. * 缓存订单信息
  1700. * @param int $uid
  1701. * @param array $cartInfo
  1702. * @param array $priceGroup
  1703. * @param array $other
  1704. * @param array $addr
  1705. * @param array $invalidCartInfo
  1706. * @param array $deduction
  1707. * @param int $cacheTime
  1708. * @return string
  1709. * @throws \Psr\SimpleCache\InvalidArgumentException
  1710. */
  1711. public function cacheOrderInfo(int $uid, array $cartInfo, array $priceGroup, array $other = [], array $addr = [], array $invalidCartInfo = [], array $deduction = [], int $cacheTime = 600)
  1712. {
  1713. /** @var StoreOrderCreateServices $storeOrderCreateService */
  1714. $storeOrderCreateService = app()->make(StoreOrderCreateServices::class);
  1715. $key = md5($storeOrderCreateService->getNewOrderId((string)$uid) . substr(implode(NULL, array_map('ord', str_split(substr(uniqid(), 7, 13), 1))), 0, 8));
  1716. CacheService::redisHandler()->set('user_order_' . $uid . $key, compact('cartInfo', 'priceGroup', 'other', 'addr', 'invalidCartInfo', 'deduction'), $cacheTime);
  1717. return $key;
  1718. }
  1719. /**
  1720. * 获取订单缓存信息
  1721. * @param int $uid
  1722. * @param string $key
  1723. * @return |null
  1724. */
  1725. public function getCacheOrderInfo(int $uid, string $key)
  1726. {
  1727. $cacheName = 'user_order_' . $uid . $key;
  1728. if (!CacheService::redisHandler()->has($cacheName)) return null;
  1729. return CacheService::redisHandler()->get($cacheName);
  1730. }
  1731. /**
  1732. * 获取用户购买活动产品的次数
  1733. * @param $uid
  1734. * @param $seckill_id
  1735. * @return int
  1736. */
  1737. public function activityProductCount(array $where)
  1738. {
  1739. return $this->dao->count($where);
  1740. }
  1741. /**
  1742. * 获取拼团的订单id
  1743. * @param int $pid
  1744. * @param int $uid
  1745. * @return mixed
  1746. */
  1747. public function getStoreIdPink(int $pid, int $uid)
  1748. {
  1749. return $this->dao->value(['uid' => $uid, 'pink_id' => $pid, 'is_del' => 0], 'order_id');
  1750. }
  1751. /**
  1752. * 判断当前订单中是否有拼团
  1753. * @param int $pid
  1754. * @param int $uid
  1755. * @return int
  1756. */
  1757. public function getIsOrderPink($pid = 0, $uid = 0)
  1758. {
  1759. return $this->dao->count(['uid' => $uid, 'pink_id' => $pid, 'refund_status' => 0, 'is_del' => 0]);
  1760. }
  1761. /**
  1762. * 判断支付方式是否开启
  1763. * @param $payType
  1764. * @return bool
  1765. */
  1766. public function checkPaytype(string $payType)
  1767. {
  1768. $res = false;
  1769. switch ($payType) {
  1770. case PayServices::WEIXIN_PAY:
  1771. $res = (bool)sys_config('pay_weixin_open');
  1772. break;
  1773. case PayServices::YUE_PAY:
  1774. $res = sys_config('balance_func_status') && sys_config('yue_pay_status') == 1;
  1775. break;
  1776. case 'offline':
  1777. $res = sys_config('offline_pay_status') == 1;
  1778. break;
  1779. case PayServices::ALIAPY_PAY:
  1780. $res = sys_config('ali_pay_status') == 1;
  1781. break;
  1782. }
  1783. return $res;
  1784. }
  1785. /**
  1786. * 修改支付方式为线下支付
  1787. * @param string $orderId
  1788. * @return bool
  1789. */
  1790. public function setOrderTypePayOffline(string $orderId)
  1791. {
  1792. return $this->dao->update($orderId, ['pay_type' => 'offline'], 'order_id');
  1793. }
  1794. /**
  1795. * 删除订单
  1796. * @param $uni
  1797. * @param $uid
  1798. * @return bool
  1799. */
  1800. public function removeOrder(string $uni, int $uid)
  1801. {
  1802. $order = $this->getUserOrderDetail($uni, $uid);
  1803. if (!$order) {
  1804. throw new ValidateException('订单不存在!');
  1805. }
  1806. $order = $this->tidyOrder($order);
  1807. if ($order['_status']['_type'] != 0 && $order['_status']['_type'] != -2 && $order['_status']['_type'] != 4)
  1808. throw new ValidateException('该订单无法删除!');
  1809. $order->is_del = 1;
  1810. /** @var StoreOrderStatusServices $statusService */
  1811. $statusService = app()->make(StoreOrderStatusServices::class);
  1812. $res = $statusService->save([
  1813. 'oid' => $order['id'],
  1814. 'change_type' => 'remove_order',
  1815. 'change_message' => '删除订单',
  1816. 'change_time' => time()
  1817. ]);
  1818. if ($order->save() && $res) {
  1819. //未支付和已退款的状态下才可以退积分退库存退优惠券
  1820. if ($order['_status']['_type'] == 0 || $order['_status']['_type'] == -2) {
  1821. /** @var StoreOrderRefundServices $refundServices */
  1822. $refundServices = app()->make(StoreOrderRefundServices::class);
  1823. $this->transaction(function () use ($order, $refundServices) {
  1824. //回退积分和优惠卷
  1825. $res = $refundServices->integralAndCouponBack($order);
  1826. //回退库存
  1827. $res = $res && $refundServices->regressionStock($order);
  1828. if (!$res) {
  1829. throw new ValidateException('取消订单失败!');
  1830. }
  1831. });
  1832. }
  1833. return true;
  1834. } else
  1835. throw new ValidateException('订单删除失败!');
  1836. }
  1837. /**
  1838. * 取消订单
  1839. * @param $order_id
  1840. * @param int $uid
  1841. * @return bool
  1842. * @throws \think\db\exception\DataNotFoundException
  1843. * @throws \think\db\exception\DbException
  1844. * @throws \think\db\exception\ModelNotFoundException
  1845. */
  1846. public function cancelOrder($order_id, int $uid)
  1847. {
  1848. $order = $this->dao->getOne(['order_id' => $order_id, 'uid' => $uid, 'is_del' => 0]);
  1849. if (!$order) {
  1850. throw new ValidateException('没有查到此订单');
  1851. }
  1852. if ($order->paid) {
  1853. throw new ValidateException('订单已经支付无法取消');
  1854. }
  1855. /** @var StoreOrderRefundServices $refundServices */
  1856. $refundServices = app()->make(StoreOrderRefundServices::class);
  1857. $this->transaction(function () use ($refundServices, $order) {
  1858. //回退积分和优惠卷
  1859. $res = $refundServices->integralAndCouponBack($order);
  1860. //回退库存和销量
  1861. $res = $res && $refundServices->regressionStock($order);
  1862. $order->is_del = 1;
  1863. if (!($res && $order->save())) {
  1864. throw new ValidateException('取消订单失败');
  1865. }
  1866. });
  1867. //订单取消事件
  1868. event('order.cancel', [$order]);
  1869. return true;
  1870. }
  1871. /**
  1872. * 判断订单完成
  1873. * @param StoreProductReplyServices $replyServices
  1874. * @param array $uniqueList
  1875. * @param $oid
  1876. * @return mixed
  1877. */
  1878. public function checkOrderOver($replyServices, array $uniqueList, $oid)
  1879. {
  1880. //订单商品全部评价完成
  1881. $replyServices->count(['unique' => $uniqueList, 'oid' => $oid]);
  1882. if ($replyServices->count(['unique' => $uniqueList, 'oid' => $oid]) == count($uniqueList)) {
  1883. $res = $this->dao->update($oid, ['status' => '3']);
  1884. if (!$res) throw new ValidateException('评价后置操作失败!');
  1885. /** @var StoreOrderStatusServices $statusService */
  1886. $statusService = app()->make(StoreOrderStatusServices::class);
  1887. $statusService->save([
  1888. 'oid' => $oid,
  1889. 'change_type' => 'check_order_over',
  1890. 'change_message' => '用户评价',
  1891. 'change_time' => time()
  1892. ]);
  1893. }
  1894. }
  1895. /**
  1896. * 某个用户订单
  1897. * @param int $uid
  1898. * @param UserServices $userServices
  1899. * @return array
  1900. * @throws \think\db\exception\DataNotFoundException
  1901. * @throws \think\db\exception\DbException
  1902. * @throws \think\db\exception\ModelNotFoundException
  1903. */
  1904. public function getUserOrderList(int $uid)
  1905. {
  1906. /** @var UserServices $userServices */
  1907. $userServices = app()->make(UserServices::class);
  1908. $user = $userServices->getUserWithTrashedInfo($uid);
  1909. if (!$user) {
  1910. throw new ValidateException('数据不存在');
  1911. }
  1912. [$page, $limit] = $this->getPageValue();
  1913. $where = ['uid' => $uid, 'pid' => [0, -1], 'paid' => 1, 'is_del' => 0, 'is_system_del' => 0];
  1914. $list = $this->dao->getStairOrderList($where, 'order_id,real_name,total_num,total_price,pay_price,FROM_UNIXTIME(pay_time,"%Y-%m-%d") as pay_time,paid,pay_type,type,activity_id,activity_append', $page, $limit);
  1915. $count = $this->dao->count($where);
  1916. return compact('list', 'count');
  1917. }
  1918. /**
  1919. * 获取推广订单列表
  1920. * @param int $uid
  1921. * @param $where
  1922. * @return array
  1923. * @throws \think\db\exception\DataNotFoundException
  1924. * @throws \think\db\exception\DbException
  1925. * @throws \think\db\exception\ModelNotFoundException
  1926. */
  1927. public function getUserStairOrderList(int $uid, $where)
  1928. {
  1929. $where_data = [];
  1930. if (isset($where['type'])) {
  1931. switch ((int)$where['type']) {
  1932. case 1:
  1933. $where_data['spread_uid'] = $uid;
  1934. break;
  1935. case 2:
  1936. $where_data['spread_two_uid'] = $uid;
  1937. break;
  1938. default:
  1939. $where_data['spread_or_uid'] = $uid;
  1940. break;
  1941. }
  1942. }
  1943. if (isset($where['data']) && $where['data']) {
  1944. $where_data['time'] = $where['data'];
  1945. }
  1946. if (isset($where['order_id']) && $where['order_id']) {
  1947. $where_data['order_id'] = $where['order_id'];
  1948. }
  1949. if (isset($where['nickname']) && $where['nickname']) {
  1950. $where_data['real_name'] = $where['nickname'];
  1951. }
  1952. //推广订单只显示支付过并且未退款的订单
  1953. $where_data['pid'] = 0;
  1954. $where_data['paid'] = 1;
  1955. $where_data['refund_status'] = 0;
  1956. [$page, $limit] = $this->getPageValue();
  1957. $list = $this->dao->getStairOrderList($where_data, '*', $page, $limit);
  1958. $count = $this->dao->count($where_data);
  1959. return compact('list', 'count');
  1960. }
  1961. /**
  1962. * 订单导出
  1963. * @param array $where
  1964. * @return array
  1965. * @throws \think\db\exception\DataNotFoundException
  1966. * @throws \think\db\exception\DbException
  1967. * @throws \think\db\exception\ModelNotFoundException
  1968. */
  1969. public function getExportList(array $where, array $with = [], int $limit = 0)
  1970. {
  1971. if ($limit) {
  1972. [$page] = $this->getPageValue();
  1973. } else {
  1974. [$page, $limit] = $this->getPageValue();
  1975. }
  1976. $list = $this->dao->search($where)->with($with)->page($page, $limit)->order('id asc')->select()->toArray();
  1977. if ($list) {
  1978. /** @var $userServices */
  1979. $userServices = app()->make(UserServices::class);
  1980. $userSex = $userServices->getColumn([['uid', 'IN', array_unique(array_column($list, 'uid'))]], 'uid,sex', 'uid');
  1981. foreach ($list as &$item) {
  1982. /** @var StoreOrderCartInfoServices $orderCart */
  1983. $orderCart = app()->make(StoreOrderCartInfoServices::class);
  1984. $_info = $orderCart->getCartColunm(['oid' => $item['id']], 'cart_info', 'unique');
  1985. foreach ($_info as $k => $v) {
  1986. $cart_info = is_string($v) ? json_decode($v, true) : $v;
  1987. if (!isset($cart_info['productInfo'])) $cart_info['productInfo'] = [];
  1988. $_info[$k] = $cart_info;
  1989. unset($cart_info);
  1990. }
  1991. $item['_info'] = $_info;
  1992. $item['sex'] = $userSex[$item['uid']]['sex'] ?? '';
  1993. [$pink_name, $color] = $this->tidyOrderType($item);
  1994. $item['pink_name'] = $pink_name;
  1995. $item['color'] = $color;
  1996. }
  1997. }
  1998. return $list;
  1999. }
  2000. /**
  2001. * 自动取消订单
  2002. * @return bool
  2003. * @throws \think\db\exception\DataNotFoundException
  2004. * @throws \think\db\exception\DbException
  2005. * @throws \think\db\exception\ModelNotFoundException
  2006. */
  2007. public function runOrderUnpaidCancel(int $page = 0, int $limit = 0)
  2008. {
  2009. $list = $this->dao->getOrderUnPaid(0, $page, $limit)->field(['*'])->select();
  2010. if (!$list) {
  2011. return true;
  2012. }
  2013. //系统预设取消订单时间段
  2014. $keyValue = ['order_cancel_time', 'order_activity_time', 'order_bargain_time', 'order_seckill_time', 'order_pink_time'];
  2015. //获取配置
  2016. $systemValue = SystemConfigService::more($keyValue);
  2017. //格式化数据
  2018. $systemValue = Arr::setValeTime($keyValue, is_array($systemValue) ? $systemValue : []);
  2019. $secsArr = [];
  2020. //秒杀
  2021. $secsArr[1] = $systemValue['order_seckill_time'] ? $systemValue['order_seckill_time'] : $systemValue['order_activity_time'];
  2022. //砍价
  2023. $secsArr[2] = $systemValue['order_bargain_time'] ? $systemValue['order_bargain_time'] : $systemValue['order_activity_time'];
  2024. //拼团
  2025. $secsArr[3] = $systemValue['order_pink_time'] ? $systemValue['order_pink_time'] : $systemValue['order_activity_time'];
  2026. //默认
  2027. $secsArr[0] = $systemValue['order_cancel_time'];
  2028. /** @var StoreOrderRefundServices $refundServices */
  2029. $refundServices = app()->make(StoreOrderRefundServices::class);
  2030. foreach ($list as $order) {
  2031. $type = $order['type'];
  2032. $secs = $secsArr[$type] ?? $secsArr[0];
  2033. if ($secs == 0) continue;
  2034. if (($order['add_time'] + bcmul($secs, '3600', 0)) < time()) {
  2035. try {
  2036. $this->transaction(function () use ($order, $refundServices) {
  2037. //回退积分和优惠卷
  2038. $res = $refundServices->integralAndCouponBack($order);
  2039. //回退库存和销量
  2040. $res = $res && $refundServices->regressionStock($order);
  2041. //修改订单状态
  2042. $res = $res && $this->dao->update($order['id'], ['is_del' => 1, 'mark' => '订单未支付已超过系统预设时间']);
  2043. if (!$res) {
  2044. throw new ValidateException('订单号' . $order['order_id'] . '自动取消订单失败');
  2045. }
  2046. return true;
  2047. });
  2048. //订单取消事件
  2049. event('order.cancel', [$order]);
  2050. } catch (\Throwable $e) {
  2051. Log::error('自动取消订单失败,失败原因:' . $e->getMessage(), $e->getTrace());
  2052. }
  2053. }
  2054. }
  2055. return true;
  2056. }
  2057. /**
  2058. * 批量加入对接
  2059. * @param int $count
  2060. * @param int $limit
  2061. */
  2062. public function batchJoinJob(int $count, int $limit)
  2063. {
  2064. $pages = ceil($limit / $count);
  2065. for ($i = 1; $i <= $pages; $i++) {
  2066. AutoOrderUnpaidCancelJob::dispatch([$i, $limit]);
  2067. }
  2068. return true;
  2069. }
  2070. /**
  2071. * 自动取消订单
  2072. * @return bool
  2073. * @throws \think\db\exception\DataNotFoundException
  2074. * @throws \think\db\exception\DbException
  2075. * @throws \think\db\exception\ModelNotFoundException
  2076. */
  2077. public function orderUnpaidCancel()
  2078. {
  2079. $count = $this->dao->getOrderUnPaid()->count();
  2080. $maxLimit = 100;
  2081. if ($count > $maxLimit) {
  2082. return $this->batchJoinJob($count, $maxLimit);
  2083. }
  2084. return $this->runOrderUnpaidCancel();
  2085. }
  2086. /**
  2087. * 根据时间获取当天或昨天订单营业额
  2088. * @param array $where
  2089. * @return float|int
  2090. */
  2091. public function getOrderMoneyByWhere(array $where, string $sum_field, string $selectType, string $group = "")
  2092. {
  2093. switch ($selectType) {
  2094. case "sum" :
  2095. return $this->dao->getDayTotalMoney($where, $sum_field);
  2096. case "group" :
  2097. return $this->dao->getDayGroupMoney($where, $sum_field, $group);
  2098. }
  2099. }
  2100. /**
  2101. * 统计时间段订单数
  2102. * @param array $where
  2103. * @param string $sum_field
  2104. */
  2105. public function getOrderCountByWhere(array $where)
  2106. {
  2107. return $this->dao->getDayOrderCount($where);
  2108. }
  2109. /**
  2110. * 分组统计时间段订单数
  2111. * @param $where
  2112. * @return mixed
  2113. */
  2114. public function getOrderGroupCountByWhere($where)
  2115. {
  2116. return $this->dao->getOrderGroupCount($where);
  2117. }
  2118. /**
  2119. * 时间段支付订单人数
  2120. * @param $where
  2121. * @return mixed
  2122. */
  2123. public function getPayOrderPeopleByWhere($where)
  2124. {
  2125. return $this->dao->getPayOrderPeople($where);
  2126. }
  2127. /**
  2128. * 时间段分组统计支付订单人数
  2129. * @param $where
  2130. * @return mixed
  2131. */
  2132. public function getPayOrderGroupPeopleByWhere($where)
  2133. {
  2134. return $this->dao->getPayOrderGroupPeople($where);
  2135. }
  2136. /**
  2137. * 批量更新数据
  2138. * @param array $ids
  2139. * @param array $data
  2140. * @param string|null $key
  2141. * @return BaseModel
  2142. */
  2143. public function orderDel(array $ids, $redisKey, $queueId)
  2144. {
  2145. /** @var QueueServices $queueService */
  2146. $queueService = app()->make(QueueServices::class);
  2147. $res = $this->dao->batchUpdateOrder($ids, ['is_system_del' => 1]);
  2148. if ($res) {
  2149. $queueService->doSuccessSremRedis($ids, $redisKey, $queueId['type']);
  2150. } else {
  2151. $queueService->addQueueFail($queueId['id'], $redisKey);
  2152. throw new AdminException('删除失败');
  2153. }
  2154. }
  2155. /**获取发货excel文件数据
  2156. * @param string $file
  2157. * @param $row
  2158. * @return array
  2159. * @throws \PhpOffice\PhpSpreadsheet\Reader\Exception
  2160. */
  2161. public function readExpreExcel(string $file, $row = 2)
  2162. {
  2163. if (!$file) throw new AdminException('请上传发货数据表');
  2164. /** @var FileService $readExcelService */
  2165. $readExcelService = app()->make(FileService::class);
  2166. $exprData = $readExcelService->readExcel($file, $row);
  2167. if (!$exprData) throw new AdminException('发货数据为空');
  2168. return $exprData;
  2169. }
  2170. /**
  2171. * 队列发货
  2172. * @return bool
  2173. * @throws \think\db\exception\DataNotFoundException
  2174. * @throws \think\db\exception\DbException
  2175. * @throws \think\db\exception\ModelNotFoundException
  2176. */
  2177. public function adminQueueOrderDo(array $data, bool $is_again = false)
  2178. {
  2179. if (!$data) return false;
  2180. /** @var QueueServices $queueService */
  2181. $queueService = app()->make(QueueServices::class);
  2182. /** @var QueueAuxiliaryServices $auxiliaryService */
  2183. $auxiliaryService = app()->make(QueueAuxiliaryServices::class);
  2184. $queueWhere['type'] = $data['queueType'];
  2185. $queueWhere['status'] = 0;
  2186. if (isset($data['queueId']) && $data['queueId']) $queueWhere['id'] = $data['queueId'];
  2187. $queueInfo = $queueService->getQueueOne($queueWhere);
  2188. $ids = $auxiliaryService->getCacheOidList($queueInfo['id'], $data['cacheType']);
  2189. $data['ids'] = array_column($ids, 'relation_id');
  2190. $data['queueId'] = $queueInfo['id'];
  2191. //if ($queueInfo['status'] == 2) throw new ValidateException('任务已完成');
  2192. //把队列需要执行的入参数据存起来,以便队列执行失败后接着执行,同时队列状态改为正在执行状态。
  2193. $queueService->setQueueDoing($data, $queueInfo['id'], $is_again);
  2194. $oids = $auxiliaryService->getOrderExpreList(['binding_id' => $queueInfo['id'], 'type' => $data['cacheType'], 'status' => [0, 2]]);
  2195. $oids = $oids ? array_column($oids, 'relation_id') : [];
  2196. // $chunkPids = array_chunk($oids, 1000, true);
  2197. $data['queueId'] = $queueInfo['id'];
  2198. foreach ($oids as $v) {
  2199. //加入队列
  2200. BatchHandleJob::dispatch([$v, $data['queueType'], $data]);
  2201. }
  2202. return true;
  2203. }
  2204. /**
  2205. * 对外接口获取订单状态
  2206. * @param int $oid
  2207. */
  2208. public function outGetStatus(string $oid)
  2209. {
  2210. $order = $this->dao->getOne(['order_id' => $oid]);
  2211. if (!$order['paid'] && $order['pay_type'] == 'offline' && !$order['status'] >= 2) {
  2212. $status_name = '线下支付';
  2213. } else if (!$order['paid']) {
  2214. $status_name = '未支付';
  2215. } else if ($order['status'] == 0 && $order['refund_status'] == 0) {
  2216. $status_name = '待发货';
  2217. } else if ($order['refund_status'] == 1) {
  2218. $status_name = '申请退款中';
  2219. } else if ($order['refund_status'] == 2) {
  2220. $status_name = '已退款';
  2221. } else if ($order['refund_status'] == 3) {
  2222. $status_name = '部分退款(子订单)';
  2223. } else if ($order['refund_status'] == 4) {
  2224. $status_name = '子订单已全部申请退款中';
  2225. } else if (!$order['status']) {
  2226. $status_name = '未发货';
  2227. } else if ($order['status'] == 1) {
  2228. $status_name = '待收货';
  2229. } else if ($order['status'] == 2) {
  2230. $status_name = '待评价';
  2231. } else if ($order['status'] == 3) {
  2232. $status_name = '交易完成';
  2233. }
  2234. $data = [];
  2235. $data['status_name'] = $status_name;
  2236. $data['status'] = $order['status'];
  2237. $data['paid'] = $order['paid'];
  2238. $data['pay_type'] = $order['pay_type'];
  2239. $data['refund_status'] = $order['refund_status'];
  2240. return $data;
  2241. }
  2242. /**
  2243. * 对外接口根据订单id查询收货方式
  2244. * @param string $oid
  2245. * @return array
  2246. */
  2247. public function outGetShippingType(string $oid)
  2248. {
  2249. $shipping_type = $this->dao->value(['order_id' => $oid], 'shipping_type');
  2250. $shipping_type = $shipping_type == 1 ? '商家配送' : '到店自提';
  2251. return compact('shipping_type');
  2252. }
  2253. /**
  2254. * 对外接口根据订单id查询配送信息
  2255. * @param string $oid
  2256. * @return array|\think\Model|null
  2257. * @throws \think\db\exception\DataNotFoundException
  2258. * @throws \think\db\exception\DbException
  2259. * @throws \think\db\exception\ModelNotFoundException
  2260. */
  2261. public function OutDeliveryType(string $oid)
  2262. {
  2263. $info = $this->dao->getOne(['order_id' => $oid], 'order_id,delivery_type,delivery_name,delivery_id');
  2264. return $info ? $info->toArray() : [];
  2265. }
  2266. /**
  2267. * 对外接口获取运费
  2268. * @param int $cartId
  2269. * @param int $uid
  2270. * @param int $addressId
  2271. * @return array
  2272. * @throws \Psr\SimpleCache\InvalidArgumentException
  2273. */
  2274. public function outGetPostage($cartId, int $uid, int $addressId, int $couponId = 0)
  2275. {
  2276. $addr = [];
  2277. /** @var UserAddressServices $addressServices */
  2278. $addressServices = app()->make(UserAddressServices::class);
  2279. /** @var UserServices $userServices */
  2280. $userServices = app()->make(UserServices::class);
  2281. $user = $userServices->get($uid);
  2282. if ($addressId) {
  2283. $addr = $addressServices->getAdderssCache($addressId);
  2284. }
  2285. //没传地址id或地址已删除未找到 ||获取默认地址
  2286. if (!$addr) {
  2287. $addr = $addressServices->getUserDefaultAddressCache($uid);
  2288. }
  2289. /** @var StoreCartServices $cartServices */
  2290. $cartServices = app()->make(StoreCartServices::class);
  2291. $cartGroup = $cartServices->getUserProductCartListV1($uid, $cartId, true, $addr);
  2292. $storeFreePostage = floatval(sys_config('store_free_postage')) ?: 0;//满额包邮金额
  2293. $validCartInfo = $cartGroup['valid'];
  2294. /** @var StoreOrderComputedServices $computedServices */
  2295. $computedServices = app()->make(StoreOrderComputedServices::class);
  2296. $priceGroup = $computedServices->getOrderPriceGroup($validCartInfo, $addr, $user, $storeFreePostage);
  2297. $postage = $priceGroup['storePostage'] ?? 0;
  2298. return compact('postage');
  2299. }
  2300. /**
  2301. * 获取配送员订单统计列表
  2302. * @param array $where
  2303. * @return array
  2304. * @throws \think\db\exception\DataNotFoundException
  2305. * @throws \think\db\exception\DbException
  2306. * @throws \think\db\exception\ModelNotFoundException
  2307. */
  2308. public function getDeliveryStatistics(array $where)
  2309. {
  2310. [$page, $limit] = $this->getPageValue();
  2311. $where['is_del'] = 0;
  2312. $where['paid'] = 1;
  2313. $where['is_system_del'] = 0;
  2314. $where['delivery_type'] = 'send';
  2315. $where['refund_status'] = [0, 3];
  2316. $list = $this->dao->getList((array)$where, ['*'], (int)$page, (int)$limit, ['user']);
  2317. if ($list) {
  2318. $list = $this->tidyOrderList($list, false);
  2319. }
  2320. $count = $this->dao->count($where);
  2321. return compact('list', 'count');
  2322. }
  2323. /**
  2324. * 配送员订单统计
  2325. * @param $store_id
  2326. * @param $delivery_uid
  2327. * @param $time
  2328. * @return array
  2329. * @throws \think\db\exception\DataNotFoundException
  2330. * @throws \think\db\exception\DbException
  2331. * @throws \think\db\exception\ModelNotFoundException
  2332. */
  2333. public function getStatisticsHeader($store_id, $delivery_uid, $time)
  2334. {
  2335. $where['is_del'] = 0;
  2336. $where['paid'] = 1;
  2337. $where['is_system_del'] = 0;
  2338. $where['delivery_type'] = 'send';
  2339. $where['store_id'] = $store_id;
  2340. $where['refund_status'] = [0, 3];
  2341. if ($delivery_uid) {
  2342. $where['delivery_uid'] = $delivery_uid;
  2343. }
  2344. [$start, $end, $timeType, $xAxis] = $time;
  2345. $order = $this->dao->orderAddTimeList($where, [$start, $end], $timeType, false);
  2346. $price = array_column($order, 'price', 'day');
  2347. $count = array_column($order, 'count', 'day');
  2348. $data = $series = [];
  2349. foreach ($xAxis as $key) {
  2350. $data['配送订单金额'][] = isset($price[$key]) ? floatval($price[$key]) : 0;
  2351. $data['配送单数'][] = isset($count[$key]) ? floatval($count[$key]) : 0;
  2352. }
  2353. foreach ($data as $key => $item) {
  2354. $series[] = [
  2355. 'name' => $key,
  2356. 'data' => $item,
  2357. 'type' => 'line',
  2358. 'smooth' => 'true',
  2359. 'yAxisIndex' => 1,
  2360. ];
  2361. }
  2362. return compact('xAxis', 'series');
  2363. }
  2364. /**
  2365. * 门店线上支付订单详情
  2366. * @param int $store
  2367. * @param int $uid
  2368. * @return mixed
  2369. * @throws \think\db\exception\DataNotFoundException
  2370. * @throws \think\db\exception\DbException
  2371. * @throws \think\db\exception\ModelNotFoundException
  2372. */
  2373. public function payCashierOrder(int $store, int $uid)
  2374. {
  2375. $order = $this->dao->payCashierOrder($store, $uid);
  2376. if (!$order) throw new ValidateException('订单不存在');
  2377. $order = $order->toArray();
  2378. $order = $this->tidyOrder($order, true);
  2379. $order['yue_pay_status'] = (int)sys_config('balance_func_status') && (int)sys_config('yue_pay_status') == 1 ? (int)1 : (int)2;//余额支付 1 开启 2 关闭
  2380. $order['pay_weixin_open'] = (int)sys_config('pay_weixin_open') ?? 0;//微信支付 1 开启 0 关闭
  2381. $order['ali_pay_status'] = (bool)sys_config('ali_pay_status');//支付包支付 1 开启 0 关闭
  2382. return $order;
  2383. }
  2384. /**
  2385. * 订单分配|重新分配给你门店
  2386. * @param int $id
  2387. * @param int $store_id
  2388. * @return mixed
  2389. * @throws \think\db\exception\DataNotFoundException
  2390. * @throws \think\db\exception\DbException
  2391. * @throws \think\db\exception\ModelNotFoundException
  2392. */
  2393. public function shareOrder(int $id, int $store_id)
  2394. {
  2395. $orderInfo = $this->dao->get((int)$id);
  2396. if (!$orderInfo) {
  2397. throw new ValidateException('订单不存在');
  2398. }
  2399. //卡密商品
  2400. if ($orderInfo['product_type'] == 1) {
  2401. throw new ValidateException('订单中卡密商品门店暂不支持');
  2402. }
  2403. /** @var SystemStoreServices $storeServices */
  2404. $storeServices = app()->make(SystemStoreServices::class);
  2405. $storeInfo = $storeServices->getStoreInfo($store_id);
  2406. if ($orderInfo['status'] != 0) {
  2407. throw new ValidateException('订单已发货');
  2408. }
  2409. /** @var StoreOrderCartInfoServices $storeOrderCartInfoServices */
  2410. $storeOrderCartInfoServices = app()->make(StoreOrderCartInfoServices::class);
  2411. $cart_info = $storeOrderCartInfoServices->getSplitCartList($id, 'cart_info');
  2412. if (!$cart_info) {
  2413. throw new ValidateException('订单已发货');
  2414. }
  2415. /** @var StoreOrderRefundServices $storeOrderRefundServices */
  2416. $storeOrderRefundServices = app()->make(StoreOrderRefundServices::class);
  2417. if ($storeOrderRefundServices->count(['store_order_id' => $id, 'refund_type' => [1, 2, 4, 5, 6], 'is_cancel' => 0, 'is_del' => 0])) {
  2418. throw new ValidateException('订单有售后申请请先处理');
  2419. }
  2420. $platProductIds = [];
  2421. $platStoreProductIds = [];
  2422. $storeProductIds = [];
  2423. foreach ($cart_info as $cart) {
  2424. $productInfo = $cart['productInfo'] ?? [];
  2425. if (isset($productInfo['store_delivery']) && !$productInfo['store_delivery']) {//有商品不支持门店配送
  2426. return [[], $cart_info];
  2427. }
  2428. switch ($productInfo['type'] ?? 0) {
  2429. case 0://平台
  2430. case 2://供应商
  2431. $platProductIds[] = $cart['product_id'];
  2432. break;
  2433. case 1://门店
  2434. if ($productInfo['pid']) {//门店自有商品
  2435. $storeProductIds[] = $cart['product_id'];
  2436. } else {
  2437. $platStoreProductIds[] = $cart['product_id'];
  2438. }
  2439. break;
  2440. }
  2441. }
  2442. if ($storeProductIds && $store_id != $orderInfo['store_id']) {
  2443. throw new ValidateException('该门店商品未上架或未设置库存');
  2444. }
  2445. /** @var StoreBranchProductServices $branchProductServics */
  2446. $branchProductServics = app()->make(StoreBranchProductServices::class);
  2447. //转换成平台商品
  2448. if ($platStoreProductIds) {
  2449. $ids = $branchProductServics->getStoreProductIds($platStoreProductIds);
  2450. $platProductIds = array_merge($platProductIds, $ids);
  2451. }
  2452. $productCount = count($platProductIds);
  2453. //商品没下架 && 库存足够
  2454. if ($productCount != $branchProductServics->count(['pid' => $platProductIds, 'is_show' => 1, 'is_del' => 0, 'type' => 1, 'relation_id' => $store_id])) {
  2455. throw new ValidateException('该门店商品未上架或未设置库存');
  2456. }
  2457. /** @var StoreProductAttrValueServices $skuValueServices */
  2458. $skuValueServices = app()->make(StoreProductAttrValueServices::class);
  2459. foreach ($cart_info as $cart) {
  2460. if (isset($cart['productInfo']['store_delivery']) && !$cart['productInfo']['store_delivery']) {//有商品不支持门店配送
  2461. throw new ValidateException('有商品不支持门店配送');
  2462. }
  2463. switch ($cart['type']) {
  2464. case 0:
  2465. case 6:
  2466. case 8:
  2467. $suk = $skuValueServices->value(['unique' => $cart['product_attr_unique'], 'product_id' => $cart['product_id'], 'type' => 0], 'suk');
  2468. break;
  2469. case 1:
  2470. case 2:
  2471. case 3:
  2472. case 5:
  2473. case 7:
  2474. $suk = $skuValueServices->value(['unique' => $cart['product_attr_unique'], 'product_id' => $cart['activity_id'], 'type' => $cart['type']], 'suk');
  2475. break;
  2476. }
  2477. $branchProductInfo = $branchProductServics->isValidStoreProduct((int)$cart['product_id'], $store_id);
  2478. if (!$branchProductInfo) {
  2479. throw new ValidateException('该门店商品库存不足');
  2480. }
  2481. $attrValue = $skuValueServices->get(['suk' => $suk, 'product_id' => $branchProductInfo['id'], 'type' => 0]);
  2482. if (!$attrValue) {
  2483. throw new ValidateException('该门店商品库存不足');
  2484. }
  2485. }
  2486. $res = $this->transaction(function () use ($id, $store_id, $orderInfo, $storeInfo, $cart_info, $branchProductServics) {
  2487. if ($orderInfo['store_id'] > 0) {//重新分配门店
  2488. //返还原来门店库存
  2489. $res = $branchProductServics->regressionBranchProductStock($orderInfo, $cart_info, -1, 0);
  2490. } else {
  2491. //返还平台库存
  2492. $res = $branchProductServics->regressionBranchProductStock($orderInfo, $cart_info, 0, -1);
  2493. }
  2494. //扣门店库存
  2495. $res = $branchProductServics->regressionBranchProductStock($orderInfo, $cart_info, -1, 1, $store_id);
  2496. $res = $res && $this->dao->update($id, ['store_id' => $storeInfo['id'], 'shipping_type' => $orderInfo['shipping_type'] == 1 ? 3 : $orderInfo['shipping_type']]);
  2497. return $res;
  2498. });
  2499. $orderInfo['store_id'] = $storeInfo['id'];
  2500. //删除之前的账单记录
  2501. /** @var StoreFinanceFlowServices $storeFinanceFlowServices */
  2502. $storeFinanceFlowServices = app()->make(StoreFinanceFlowServices::class);
  2503. $storeFinanceFlowServices->update(['link_id' => $orderInfo['order_id']], ['is_del' => 1]);
  2504. //分配后置方法
  2505. SpliteStoreOrderJob::dispatchDo('splitAfter', [$orderInfo, true]);
  2506. return $res;
  2507. }
  2508. /**
  2509. * 获取退货商品列表
  2510. * @param array $cart_ids
  2511. * @param int $id
  2512. * @return array
  2513. * @throws \think\db\exception\DataNotFoundException
  2514. * @throws \think\db\exception\DbException
  2515. * @throws \think\db\exception\ModelNotFoundException
  2516. */
  2517. public function refundCartInfoList(array $cart_ids = [], int $id = 0)
  2518. {
  2519. $orderInfo = $this->dao->get($id);
  2520. if (!$orderInfo) {
  2521. throw new ValidateException('订单不存在');
  2522. }
  2523. $orderInfo = $this->tidyOrder($orderInfo, true);
  2524. $cartInfo = $orderInfo['cartInfo'] ?? [];
  2525. $data = [];
  2526. if ($cart_ids) {
  2527. foreach ($cart_ids as $cart) {
  2528. if (!isset($cart['cart_id']) || !$cart['cart_id']) {
  2529. throw new ValidateException('请重新选择退款商品,或件数');
  2530. }
  2531. }
  2532. $cart_ids = array_combine(array_column($cart_ids, 'cart_id'), $cart_ids);
  2533. $i = 0;
  2534. foreach ($cartInfo as $item) {
  2535. if (isset($cart_ids[$item['id']])) {
  2536. $data['cartInfo'][$i] = $item;
  2537. if (isset($cart_ids[$item['id']]['cart_num'])) $data['cartInfo'][$i]['cart_num'] = $cart_ids[$item['id']]['cart_num'];
  2538. $i++;
  2539. }
  2540. }
  2541. }
  2542. $data['_status'] = $orderInfo['_status'] ?? [];
  2543. $data['cartInfo'] = $data['cartInfo'] ?? $cartInfo;
  2544. return $data;
  2545. }
  2546. /**
  2547. * 拆单的发货订单数量
  2548. * @param int $id
  2549. * @param $order
  2550. * @return int
  2551. * @throws \think\db\exception\DataNotFoundException
  2552. * @throws \think\db\exception\DbException
  2553. * @throws \think\db\exception\ModelNotFoundException
  2554. */
  2555. public function getDeliverNum(int $id, $order): int
  2556. {
  2557. if (!$order) {
  2558. $order = $this->get($id);
  2559. }
  2560. $ids = $id;
  2561. $pid = (int)$order['pid'];
  2562. if ($pid > 0) {
  2563. $ids = $this->Value([['pid', '=', $pid], ['status', '=', 1]], 'GROUP_CONCAT(id)');
  2564. if (!empty($ids)) {
  2565. $ids = array_map('intval', array_filter(explode(',', $ids)));
  2566. }
  2567. }
  2568. return $this->getCount(['id' => $ids, 'status' => 1]);
  2569. }
  2570. /**
  2571. * 获取确认订单页面是否展示快递配送和到店自提
  2572. * @param $uid
  2573. * @param $cartIds
  2574. * @param $new
  2575. * @return array
  2576. * @throws \Psr\SimpleCache\InvalidArgumentException
  2577. */
  2578. public function checkShipping($uid, $cartIds, $new)
  2579. {
  2580. if ($new) {
  2581. $cartIds = explode(',', $cartIds);
  2582. $cartInfo = [];
  2583. $redis = CacheService::redisHandler();
  2584. foreach ($cartIds as $key) {
  2585. $info = $redis->get($key);
  2586. if ($info) {
  2587. $cartInfo[] = $info;
  2588. }
  2589. }
  2590. } else {
  2591. /** @var StoreCartServices $cartServices */
  2592. $cartServices = app()->make(StoreCartServices::class);
  2593. $cartInfo = $cartServices->getCartList(['uid' => $uid, 'status' => 1, 'id' => $cartIds], 0, 0, ['productInfo', 'attrInfo']);
  2594. }
  2595. if (!$cartInfo) {
  2596. throw new ValidateException('获取购物车信息失败');
  2597. }
  2598. $arr = [];
  2599. $store_id = [];
  2600. //delivery_type :1、快递,2、到店自提,3、门店配送
  2601. foreach ($cartInfo as $item) {
  2602. $delivery_type = is_string($item['productInfo']['delivery_type']) ? explode(',', $item['productInfo']['delivery_type']) : $item['productInfo']['delivery_type'];
  2603. if (in_array(1, $delivery_type)) {//支持平台配送 验证平台该商品
  2604. $productInfo = $item['productInfo'] ?? [];
  2605. if ($productInfo && isset($productInfo['type']) && $productInfo['type'] == 1 && isset($productInfo['pid']) && $productInfo['pid']) {
  2606. /** @var StoreProductServices $productServices */
  2607. $productServices = app()->make(StoreProductServices::class);
  2608. $platInfo = $productServices->getCacheProductInfo((int)$productInfo['pid']);
  2609. if (!$platInfo || $platInfo['stock'] <= 0) {
  2610. unset($delivery_type[array_search('1', $delivery_type)]);
  2611. }
  2612. }
  2613. }
  2614. $arr = array_merge($arr, $delivery_type);
  2615. if (isset($item['productInfo']['type']) && isset($item['productInfo']['relation_id']) && $item['productInfo']['type'] == 1 && $item['productInfo']['relation_id']) {
  2616. $store_id[] = $item['productInfo']['relation_id'];
  2617. }
  2618. }
  2619. $count = count($arr);
  2620. if (!$count) {
  2621. $arr = [1, 2, 3];
  2622. }
  2623. // 门店总开关
  2624. if (!sys_config('store_func_status', 1)) {
  2625. if (in_array(2, $arr)) unset($arr[array_search(2, $arr)]);
  2626. if (in_array(3, $arr)) unset($arr[array_search(3, $arr)]);
  2627. } elseif (sys_config('store_self_mention', 1)) {
  2628. //判断有没有满足自提的店铺
  2629. $where['id'] = $store_id;
  2630. $where['is_store'] = 1;
  2631. $where['is_show'] = 1;
  2632. $where['is_del'] = 0;
  2633. /** @var SystemStoreServices $SystemStoreServe */
  2634. $SystemStoreServe = app()->make(SystemStoreServices::class);
  2635. $store_list = $SystemStoreServe->count($where);
  2636. if (!$store_list) {
  2637. if (in_array(2, $arr)) unset($arr[array_search(2, $arr)]);
  2638. }
  2639. } else {
  2640. if (in_array(2, $arr)) unset($arr[array_search(2, $arr)]);
  2641. }
  2642. $arr = array_merge(array_unique($arr));
  2643. return ['type' => $arr];
  2644. }
  2645. /**
  2646. * @param int $pid
  2647. * @param int $order_id
  2648. * @return bool
  2649. * @throws \think\db\exception\DbException
  2650. */
  2651. public function checkSubOrderNotSend(int $pid, int $order_id)
  2652. {
  2653. $order_count = $this->dao->getSubOrderNotSend($pid, $order_id);
  2654. if ($order_count > 0) {
  2655. return false;
  2656. } else {
  2657. return true;
  2658. }
  2659. }
  2660. /**
  2661. * @param int $pid
  2662. * @param int $order_id
  2663. * @return bool
  2664. * @throws \think\db\exception\DbException
  2665. */
  2666. public function checkSubOrderNotTake(int $pid, int $order_id)
  2667. {
  2668. $order_count = $this->dao->getSubOrderNotTake($pid, $order_id);
  2669. if ($order_count > 0) {
  2670. return false;
  2671. } else {
  2672. return true;
  2673. }
  2674. }
  2675. }