Order.php 47 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129
  1. <?php
  2. /*
  3. * FecShop file.
  4. *
  5. * @link http://www.fecmall.com/
  6. * @copyright Copyright (c) 2016 FecShop Software LLC
  7. * @license http://www.fecmall.com/license/
  8. */
  9. namespace fecshop\services;
  10. use Yii;
  11. /**
  12. * Order services.
  13. *
  14. * @property \fecshop\services\order\Item $item
  15. *
  16. * @author Terry Zhao <2358269014@qq.com>
  17. * @since 1.0
  18. */
  19. class Order extends Service
  20. {
  21. public $requiredAddressAttr;
  22. // 必填的订单字段。
  23. // 下面是订单支付状态
  24. // 等待付款状态
  25. public $payment_status_pending = 'payment_pending';
  26. // 付款处理中,(支付处理中,因为信用卡有预售,因此需要等IPN消息来确认是否支付成功)
  27. public $payment_status_processing = 'payment_processing';
  28. // 收款成功(支付状态已确认,代表已经收到钱了)
  29. public $payment_status_confirmed = 'payment_confirmed';
  30. // 欺诈【当paypal的返回金额和网站金额不一致【以及货币类型】的情况,就会判定该状态】
  31. public $payment_status_suspected_fraud = 'payment_suspected_fraud';
  32. // 订单支付已取消【用户进入paypal点击取消订单返回网站,或者payment_pending订单超过xx时间未支付被脚本取消,或者客服后台取消】
  33. public $payment_status_canceled = 'payment_canceled';
  34. // 订单审核中(订单收款成功后,进入erp,需要客服审核,才能开始发货流程,或者可能存在某些问题,被客服暂时挂起)
  35. public $status_holded = 'holded';
  36. // 订单备货处理中,从成功收款进入erp并客服审核成功后,进入备货流程 到 发货前的状态
  37. public $status_processing = 'processing';
  38. // 订单已发货【订单包裹被物流公司收取后】
  39. public $status_dispatched = 'dispatched';
  40. // 订单已退款【已收款订单因为某些原因进行退款,譬如:仓库无货,用户收到货后发现破损退款等】
  41. public $status_refunded = 'refunded';
  42. // 订单已完成,【用户收到货物xx时间后,未发起纠纷争端,订单状态标记为已完成】
  43. public $status_completed = 'completed';
  44. // 订单已取消,【用户付款后,因为纠纷进行取消订单后的状态】
  45. public $status_canceled = 'canceled';
  46. // 订单号格式。
  47. public $increment_id = 1000000000;
  48. public $createdOrder;
  49. // 计算销量的订单时间范围(将最近几个月内的订单中的产品销售个数累加,作为产品的销量值,譬如3代表计算最近3个月的订单产品)
  50. // 0:代表计算订单表中所有的订单。
  51. // 这个值用于console入口(脚本端),通过shell脚本执行,计算产品的销量,将订单中产品个数累加作为产品的销量,然后将这个值更新到产品表字段中,用于产品按照销量排序或者过滤
  52. public $orderProductSaleInMonths = 3;
  53. // 将xx分钟内未支付的pending订单取消掉,并释放产品库存的设置
  54. public $minuteBeforeThatReturnPendingStock = 60;
  55. // 每次处理未支付的pending订单的个数限制。
  56. public $orderCountThatReturnPendingStock = 30;
  57. // 订单备注字符的最大数
  58. public $orderRemarkStrMaxLen = 1500;
  59. // 支付类型,目前只有standard 和 express 两种,express 指的是在购物车点击支付按钮的方式,譬如paypal的express
  60. // standard类型指的是填写完货运地址后生成订单跳转到第三方支付平台的支付类型。
  61. protected $checkout_type;
  62. // 当前的订单信息保存到这个变量中,订单信息是从数据库中取出来订单和产品信息,然后进行了一定的数据处理后,再保存到该变量的。
  63. protected $_currentOrderInfo;
  64. // 支付类型常量
  65. const CHECKOUT_TYPE_STANDARD = 'standard';
  66. const CHECKOUT_TYPE_EXPRESS = 'express';
  67. const CHECKOUT_TYPE_ADMIN_CREATE= 'admin_create';
  68. // 作为保存incrementId到session的key,把当前的order incrementId保存到session的时候,对应的key就是该常量。
  69. const CURRENT_ORDER_INCREAMENT_ID = 'current_order_increament_id';
  70. protected $_orderModelName = '\fecshop\models\mysqldb\Order';
  71. protected $_orderModel;
  72. public function init()
  73. {
  74. parent::init();
  75. list($this->_orderModelName, $this->_orderModel) = \Yii::mapGet($this->_orderModelName);
  76. $this->initParamConfig();
  77. }
  78. public function initParamConfig()
  79. {
  80. $this->increment_id = Yii::$app->store->get('order', 'increment_id');
  81. $requiredAddressAttr = Yii::$app->store->get('order', 'requiredAddressAttr');
  82. $this->requiredAddressAttr = explode(',',$requiredAddressAttr);
  83. $this->orderProductSaleInMonths = Yii::$app->store->get('order', 'orderProductSaleInMonths');
  84. $this->minuteBeforeThatReturnPendingStock = Yii::$app->store->get('order', 'minuteBeforeThatReturnPendingStock');
  85. $this->orderCountThatReturnPendingStock = Yii::$app->store->get('order', 'orderCountThatReturnPendingStock');
  86. $this->orderRemarkStrMaxLen = Yii::$app->store->get('order', 'orderRemarkStrMaxLen');
  87. //$guestOrder = Yii::$app->store->get('order', 'guestOrder');
  88. }
  89. /**
  90. * @return array
  91. * 将订单所有的支付类型,组合成一个数组,进行返回。
  92. */
  93. protected function actionGetCheckoutTypeArr()
  94. {
  95. return [
  96. self::CHECKOUT_TYPE_ADMIN_CREATE => self::CHECKOUT_TYPE_ADMIN_CREATE,
  97. self::CHECKOUT_TYPE_STANDARD => self::CHECKOUT_TYPE_STANDARD,
  98. self::CHECKOUT_TYPE_EXPRESS => self::CHECKOUT_TYPE_EXPRESS,
  99. ];
  100. }
  101. /**
  102. * 付款成功,而且订单付款状态正常的订单状态
  103. *
  104. */
  105. public function getOrderPaymentedStatusArr()
  106. {
  107. return [
  108. $this->payment_status_confirmed,
  109. $this->status_holded,
  110. $this->status_processing,
  111. $this->status_completed,
  112. ];
  113. }
  114. /**
  115. * @return array
  116. * 将订单所有的状态,组合成一个数组,进行返回。
  117. */
  118. protected function actionGetStatusArr()
  119. {
  120. return [
  121. $this->payment_status_pending => $this->payment_status_pending,
  122. $this->payment_status_processing => $this->payment_status_processing,
  123. $this->payment_status_confirmed => $this->payment_status_confirmed,
  124. $this->payment_status_canceled => $this->payment_status_canceled,
  125. $this->payment_status_suspected_fraud => $this->payment_status_suspected_fraud,
  126. $this->status_holded => $this->status_holded,
  127. $this->status_processing => $this->status_processing,
  128. $this->status_dispatched => $this->status_dispatched,
  129. $this->status_refunded => $this->status_refunded,
  130. $this->status_completed => $this->status_completed,
  131. ];
  132. }
  133. /**
  134. * @return array
  135. * 将订单所有的状态,组合成一个数组,进行返回。
  136. */
  137. protected function actionGetSelectStatusArr()
  138. {
  139. return [
  140. $this->payment_status_pending => '等待支付('.$this->payment_status_pending.')',
  141. $this->payment_status_processing => '支付处理中('.$this->payment_status_processing.')',
  142. $this->payment_status_confirmed => '支付成功('.$this->payment_status_confirmed.')',
  143. $this->payment_status_canceled => '支付取消('.$this->payment_status_canceled.')',
  144. $this->payment_status_suspected_fraud => '欺诈订单('.$this->payment_status_suspected_fraud.')',
  145. $this->status_holded => '审核订单('.$this->status_holded.')',
  146. $this->status_processing => '备货中订单('.$this->status_processing.')',
  147. $this->status_dispatched => '已发货订单('.$this->status_dispatched.')',
  148. $this->status_refunded => '已退款订单('.$this->status_refunded.')',
  149. $this->status_completed => '已完成订单('.$this->status_completed.')',
  150. ];
  151. }
  152. /**
  153. * @param $checkout_type | String ,支付类型
  154. * 设置支付类型,其他计算以此设置作为基础,进而获取其他的配置。
  155. */
  156. protected function actionSetCheckoutType($checkout_type)
  157. {
  158. $arr = [self::CHECKOUT_TYPE_STANDARD, self::CHECKOUT_TYPE_EXPRESS];
  159. if (in_array($checkout_type, $arr)) {
  160. $this->checkout_type = $checkout_type;
  161. return true;
  162. }
  163. return false;
  164. }
  165. /**
  166. * 得到支付类型
  167. */
  168. protected function actionGetCheckoutType()
  169. {
  170. return $this->checkout_type;
  171. }
  172. /**
  173. * @param $billing | Array
  174. * @return bool
  175. * 通过$this->requiredAddressAttr,检查地址的必填。
  176. */
  177. protected function actionCheckRequiredAddressAttr($billing)
  178. {
  179. //$this->requiredAddressAttr;
  180. if (is_array($this->requiredAddressAttr) && !empty($this->requiredAddressAttr)) {
  181. foreach ($this->requiredAddressAttr as $attr) {
  182. if (!$attr) {
  183. continue;
  184. }
  185. if (!isset($billing[$attr]) || empty($billing[$attr])) {
  186. Yii::$service->helper->errors->add('{attr} can not empty', ['attr' => $attr]);
  187. return false;
  188. }
  189. }
  190. }
  191. return true;
  192. }
  193. /**
  194. * 得到order 表的id字段。
  195. */
  196. protected function actionGetPrimaryKey()
  197. {
  198. return 'order_id';
  199. }
  200. /**
  201. * @param $primaryKey | Int
  202. * @return Object($this->_orderModel)
  203. * 通过主键值,返回Order Model对象
  204. */
  205. protected function actionGetByPrimaryKey($primaryKey)
  206. {
  207. $one = $this->_orderModel->findOne($primaryKey);
  208. $primaryKey = $this->getPrimaryKey();
  209. if ($one[$primaryKey]) {
  210. return $one;
  211. } else {
  212. return new $this->_orderModelName();
  213. }
  214. }
  215. /**
  216. * @param $increment_id | String , 订单号
  217. * @return object ($this->_orderModel),返回 $this->_orderModel model
  218. * 通过订单号incrementId,得到订单Model对象。
  219. */
  220. protected function actionGetByIncrementId($increment_id)
  221. {
  222. $one = $this->_orderModel->findOne(['increment_id' => $increment_id]);
  223. $primaryKey = $this->getPrimaryKey();
  224. if ($one[$primaryKey]) {
  225. return $one;
  226. } else {
  227. return false;
  228. }
  229. }
  230. protected $_currentOrderIncrementId = '';
  231. public function setCurrentOrderIncrementId($increment_id)
  232. {
  233. $this->_currentOrderIncrementId = $increment_id;
  234. }
  235. public function getCurrentOrderIncrementId()
  236. {
  237. return $this->_currentOrderIncrementId;
  238. }
  239. /**
  240. * @param $reflush | boolean 是否从数据库中重新获取,如果是,则不会使用类变量中计算的值
  241. * 获取当前的订单信息,原理为:
  242. * 通过从session中取出来订单的increment_id,
  243. * 在通过increment_id(订单编号)取出来订单信息。
  244. */
  245. protected function actionGetCurrentOrderInfo($reflush = false)
  246. {
  247. if (!$this->_currentOrderInfo || $reflush) {
  248. if (Yii::$service->store->isAppserver()) {
  249. $increment_id = $this->getCurrentOrderIncrementId();
  250. if (!$increment_id) {
  251. Yii::$service->helper->errors->add('current increment id is empty, you must setCurrentOrderIncrementId');
  252. return null;
  253. }
  254. $this->_currentOrderInfo = Yii::$service->order->getOrderInfoByIncrementId($increment_id);
  255. } else {
  256. $increment_id = Yii::$service->order->getSessionIncrementId();
  257. $this->_currentOrderInfo = Yii::$service->order->getOrderInfoByIncrementId($increment_id);
  258. }
  259. }
  260. return $this->_currentOrderInfo;
  261. }
  262. /**
  263. * @param $increment_id | String 订单编号
  264. * @return array
  265. * 通过increment_id 从数据库中取出来订单数据,
  266. * 然后进行一系列的处理,返回订单数组数据。
  267. */
  268. protected function actionGetOrderInfoByIncrementId($increment_id)
  269. {
  270. $one = $this->getByIncrementId($increment_id);
  271. if (!$one) {
  272. return;
  273. }
  274. $primaryKey = $this->getPrimaryKey();
  275. if (!isset($one[$primaryKey]) || empty($one[$primaryKey])) {
  276. return;
  277. }
  278. $order_info = [];
  279. foreach ($one as $k=>$v) {
  280. $order_info[$k] = $v;
  281. }
  282. $order_info['customer_address_state_name'] = Yii::$service->helper->country->getStateByContryCode($order_info['customer_address_country'], $order_info['customer_address_state']);
  283. $order_info['customer_address_country_name'] = Yii::$service->helper->country->getCountryNameByKey($order_info['customer_address_country']);
  284. $order_info['currency_symbol'] = Yii::$service->page->currency->getSymbol($order_info['order_currency_code']);
  285. $order_info['products'] = Yii::$service->order->item->getByOrderId($one[$primaryKey]);
  286. return $order_info;
  287. }
  288. protected function actionGetorderinfocoll($filter = '')
  289. {
  290. $primaryKey = $this->getPrimaryKey();
  291. $query = $this->_orderModel->find();
  292. $query = Yii::$service->helper->ar->getCollByFilter($query, $filter);
  293. $coll = $query->all();
  294. foreach ($coll as $k => $order_info) {
  295. $coll[$k]['customer_address_state_name'] = Yii::$service->helper->country->getStateByContryCode($order_info['customer_address_country'], $order_info['customer_address_state']);
  296. $coll[$k]['customer_address_country_name'] = Yii::$service->helper->country->getCountryNameByKey($order_info['customer_address_country']);
  297. $coll[$k]['currency_symbol'] = Yii::$service->page->currency->getSymbol($order_info['order_currency_code']);
  298. $coll[$k]['products'] = Yii::$service->order->item->getByOrderId($order_info[$primaryKey]);
  299. }
  300. return [
  301. 'coll' => $coll,
  302. 'count'=> $query->limit(null)->offset(null)->count(),
  303. ];
  304. }
  305. /**
  306. * @param $order_id | Int
  307. * @return array
  308. * 通过order_id 从数据库中取出来订单数据,
  309. * 然后进行一系列的处理,返回订单数组数据。
  310. */
  311. protected function actionGetOrderInfoById($order_id)
  312. {
  313. if (!$order_id) {
  314. return;
  315. }
  316. $one = $this->_orderModel->findOne($order_id);
  317. $primaryKey = $this->getPrimaryKey();
  318. if (!isset($one[$primaryKey]) || empty($one[$primaryKey])) {
  319. return;
  320. }
  321. $order_info = [];
  322. foreach ($one as $k=>$v) {
  323. $order_info[$k] = $v;
  324. }
  325. $order_info['customer_address_state_name'] = Yii::$service->helper->country->getStateByContryCode($order_info['customer_address_country'], $order_info['customer_address_state']);
  326. $order_info['customer_address_country_name']= Yii::$service->helper->country->getCountryNameByKey($order_info['customer_address_country']);
  327. $order_info['currency_symbol'] = Yii::$service->page->currency->getSymbol($order_info['order_currency_code']);
  328. $order_info['products'] = Yii::$service->order->item->getByOrderId($order_id);
  329. return $order_info;
  330. }
  331. /**
  332. * @param $filter|array
  333. * @return Array;
  334. * 通过过滤条件,得到coupon的集合。
  335. * example filter:
  336. * [
  337. * 'numPerPage' => 20,
  338. * 'pageNum' => 1,
  339. * 'orderBy' => ['_id' => SORT_DESC, 'sku' => SORT_ASC ],
  340. * 'where' => [
  341. * ['>','price',1],
  342. * ['<=','price',10]
  343. * ['sku' => 'uk10001'],
  344. * ],
  345. * 'asArray' => true,
  346. * ]
  347. * 根据$filter 搜索参数数组,返回满足条件的订单数据。
  348. */
  349. protected function actionColl($filter = '')
  350. {
  351. $query = $this->_orderModel->find();
  352. $query = Yii::$service->helper->ar->getCollByFilter($query, $filter);
  353. $coll = $query->all();
  354. return [
  355. 'coll' => $coll,
  356. 'count'=> $query->limit(null)->offset(null)->count(),
  357. ];
  358. }
  359. /**
  360. * @param $one|array , save one data .
  361. * @return int 保存order成功后,返回保存的id。
  362. */
  363. protected function actionSave($one)
  364. {
  365. $time = time();
  366. $primaryKey = $this->getPrimaryKey();
  367. $primaryVal = isset($one[$primaryKey]) ? $one[$primaryKey] : '';
  368. if ($primaryVal) {
  369. $model = $this->_orderModel->findOne($primaryVal);
  370. if (!$model) {
  371. Yii::$service->helper->errors->add('order {primaryKey} is not exist', ['primaryKey' => $this->getPrimaryKey()]);
  372. return;
  373. }
  374. } else {
  375. $model = new $this->_orderModelName();
  376. $model->created_at = time();
  377. }
  378. $model->updated_at = time();
  379. $model = Yii::$service->helper->ar->save($model, $one);
  380. $primaryVal = $model[$this->getPrimaryKey()];
  381. return $primaryVal;
  382. }
  383. /**
  384. * @param $ids | Int or Array
  385. * @return bool
  386. * 如果传入的是id数组,则删除多个
  387. * 如果传入的是Int,则删除一个
  388. */
  389. protected function actionRemove($ids)
  390. {
  391. if (!$ids) {
  392. Yii::$service->helper->errors->add('remove id is empty');
  393. return false;
  394. }
  395. if (is_array($ids) && !empty($ids)) {
  396. foreach ($ids as $id) {
  397. $model = $this->_orderModel->findOne($id);
  398. if (isset($model[$this->getPrimaryKey()]) && !empty($model[$this->getPrimaryKey()])) {
  399. $model->delete();
  400. } else {
  401. Yii::$service->helper->errors->add('Order Remove Errors:ID {id} is not exist', ['id' => $id]);
  402. return false;
  403. }
  404. }
  405. } else {
  406. $id = $ids;
  407. $model = $this->_orderModel->findOne($id);
  408. if (isset($model[$this->getPrimaryKey()]) && !empty($model[$this->getPrimaryKey()])) {
  409. $model->delete();
  410. } else {
  411. Yii::$service->helper->errors->add('Coupon Remove Errors:ID:{id} is not exist.', ['id' => $id]);
  412. return false;
  413. }
  414. }
  415. return true;
  416. }
  417. /**
  418. * @param $increment_id | String , 订单号
  419. * @return object ($this->_orderModel),返回 $this->_orderModel model
  420. * 通过订单号,得到订单以及订单产品信息。
  421. */
  422. protected function actionGetInfoByIncrementId($increment_id)
  423. {
  424. $order = $this->getByIncrementId($increment_id);
  425. $orderInfo = [];
  426. if ($order) {
  427. $primaryKey = $this->getPrimaryKey();
  428. $order_id = $order[$primaryKey];
  429. $items = Yii::$service->order->item->getByOrderId($order_id);
  430. foreach ($order as $k=>$v) {
  431. $orderInfo[$k] = $v;
  432. }
  433. $orderInfo['items'] = $items;
  434. return $orderInfo;
  435. } else {
  436. return;
  437. }
  438. }
  439. /**
  440. * @param $token | String , paypal 支付获取的token,订单生成后只有三个字段
  441. * order_id, increment_id , payment_token ,目的就是将token对应到一个increment_id
  442. * 在paypal 点击continue的时候,可以通过token找到对应的订单。
  443. */
  444. protected function actionGeneratePPExpressOrder($token)
  445. {
  446. $myOrder = new $this->_orderModelName();
  447. $myOrder->setGenerateOrderByPaypalToken(true);
  448. $myOrder->payment_token = $token;
  449. $myOrder->save();
  450. $order_id = $myOrder['order_id'];
  451. if ($order_id) {
  452. $increment_id = $this->generateIncrementIdByOrderId($order_id);
  453. $myOrder['increment_id'] = $increment_id;
  454. $myOrder->save();
  455. $this->createdOrder = $myOrder;
  456. if (!Yii::$service->store->isAppserver()) { // appserver入口,没有session机制。
  457. $this->setSessionIncrementId($increment_id);
  458. }
  459. return true;
  460. } else {
  461. Yii::$service->helper->errors->add('generate order fail');
  462. return false;
  463. }
  464. }
  465. /**
  466. * @param $token | String , paypal 支付获取的token,
  467. * 通过token 得到订单 Object
  468. */
  469. protected function actionGetByPaymentToken($token)
  470. {
  471. $one = $this->_orderModel->find()->where(['payment_token' => $token])
  472. ->one();
  473. if (isset($one['order_id']) && $one['order_id']) {
  474. return $one;
  475. } else {
  476. return '';
  477. }
  478. }
  479. /**
  480. * @param $reflush | boolean 是否从数据库中重新获取,如果是,则不会使用类变量中计算的值
  481. * 通过从session中取出来订单的increment_id
  482. * 在通过increment_id(订单编号)取出来订单信息。
  483. */
  484. protected function actionGetInfoByPaymentToken($token)
  485. {
  486. $orderModel = $this->getByPaymentToken($token);
  487. $increment_id = isset($orderModel['increment_id']) ? $orderModel['increment_id'] : '';
  488. return Yii::$service->order->getOrderInfoByIncrementId($increment_id);
  489. }
  490. /**
  491. * @param $address | Array 货运地址
  492. * @param $shipping_method | String 货运快递方式
  493. * @param $payment_method | Array 支付方式、
  494. * @param $clearCartAndDeductStock | boolean 是否清空购物车,并扣除库存,这种情况是先 生成订单,在支付的情况下失败的处理方式。
  495. * @param $token | string 代表 通过payment_token得到order,然后更新order信息的方式生成order,这个是paypal购物车express支付对应的功能
  496. * @param $order_remark | string , 订单备注
  497. * @return bool 通过购物车的数据生成订单是否成功
  498. * 通过购物车中的产品信息,以及传递的货运地址,货运快递方式,支付方式生成订单。
  499. */
  500. protected function actionGenerateOrderByCart($address, $shipping_method, $payment_method, $clearCart = true, $token = '', $order_remark = '')
  501. {
  502. $cart = Yii::$service->cart->quote->getCurrentCart();
  503. if (!$cart) {
  504. Yii::$service->helper->errors->add('current cart is empty');
  505. }
  506. $currency_info = Yii::$service->page->currency->getCurrencyInfo();
  507. $currency_code = $currency_info['code'];
  508. $currency_rate = $currency_info['rate'];
  509. $country = $address['country'];
  510. $state = $address['state'];
  511. $cartInfo = Yii::$service->cart->getCartInfo(true, $shipping_method, $country, $state);
  512. // 检查cartInfo中是否存在产品
  513. if (!is_array($cartInfo) && empty($cartInfo)) {
  514. Yii::$service->helper->errors->add('current cart product is empty');
  515. return false;
  516. }
  517. // 扣除库存。(订单生成后,库存产品库存。)
  518. // 备注)需要另起一个脚本,用来处理半个小时后,还没有支付的订单,将订单取消,然后将订单里面的产品库存返还。
  519. // 如果是无限库存(没有库存就去采购的方式),那么不需要跑这个脚本,将库存设置的非常大即可。
  520. $deductStatus = Yii::$service->product->stock->deduct($cartInfo['products']);
  521. if (!$deductStatus) {
  522. // 库存不足则返回
  523. return false;
  524. }
  525. $beforeEventName = 'event_generate_order_before';
  526. $afterEventName = 'event_generate_order_after';
  527. Yii::$service->event->trigger($beforeEventName, $cartInfo);
  528. if ($token) {
  529. // 有token 代表前面已经生成了order,直接通过token查询出来即可。
  530. $myOrder = $this->getByPaymentToken($token);
  531. if (!$myOrder) {
  532. Yii::$service->helper->errors->add('order increment id is not exist.');
  533. return false;
  534. } else {
  535. $increment_id = $myOrder['increment_id'];
  536. }
  537. } else {
  538. $myOrder = new $this->_orderModelName();
  539. }
  540. $myOrder['order_status'] = $this->payment_status_pending;
  541. $currentStore = Yii::$service->store->currentStore;
  542. $currentStore || $currentStore = $cartInfo['store'];
  543. $myOrder['store'] = $currentStore;
  544. $myOrder['created_at'] = time();
  545. $myOrder['updated_at'] = time();
  546. $myOrder['items_count'] = $cartInfo['items_count'];
  547. $myOrder['total_weight'] = $cartInfo['product_weight'];
  548. $myOrder['order_currency_code'] = $currency_code;
  549. $myOrder['order_to_base_rate'] = $currency_rate;
  550. $myOrder['grand_total'] = $cartInfo['grand_total'];
  551. $myOrder['base_grand_total'] = $cartInfo['base_grand_total'];
  552. $myOrder['subtotal'] = $cartInfo['product_total'];
  553. $myOrder['base_subtotal'] = $cartInfo['base_product_total'];
  554. $myOrder['subtotal_with_discount'] = $cartInfo['coupon_cost'];
  555. $myOrder['base_subtotal_with_discount'] = $cartInfo['base_coupon_cost'];
  556. $myOrder['shipping_total'] = $cartInfo['shipping_cost'];
  557. $myOrder['base_shipping_total'] = $cartInfo['base_shipping_cost'];
  558. $myOrder['checkout_method'] = $this->getCheckoutType();
  559. !$order_remark || $myOrder['order_remark'] = \yii\helpers\Html::encode($order_remark);
  560. if ($address['customer_id']) {
  561. $is_guest = 2;
  562. } else {
  563. $is_guest = 1;
  564. }
  565. if (!Yii::$app->user->isGuest) {
  566. $customer_id = Yii::$app->user->identity->id;
  567. } else {
  568. $customer_id = '';
  569. }
  570. $myOrder['customer_id'] = $customer_id;
  571. $myOrder['customer_email'] = $address['email'];
  572. $myOrder['customer_firstname'] = $address['first_name'];
  573. $myOrder['customer_lastname'] = $address['last_name'];
  574. $myOrder['customer_is_guest'] = $is_guest;
  575. $myOrder['customer_telephone'] = $address['telephone'];
  576. $myOrder['customer_address_country']= $address['country'];
  577. $myOrder['customer_address_state'] = $address['state'];
  578. $myOrder['customer_address_city'] = $address['city'];
  579. $myOrder['customer_address_zip'] = $address['zip'];
  580. $myOrder['customer_address_street1']= $address['street1'];
  581. $myOrder['customer_address_street2']= $address['street2'];
  582. $myOrder['coupon_code'] = $cartInfo['coupon_code'];
  583. $myOrder['payment_method'] = $payment_method;
  584. $myOrder['shipping_method'] = $shipping_method;
  585. // 进行model验证。
  586. if (!$myOrder->validate()) {
  587. $errors = $myOrder->errors;
  588. Yii::$service->helper->errors->addByModelErrors($errors);
  589. return false;
  590. }
  591. // 保存订单
  592. $saveOrderStatus = $myOrder->save();
  593. if (!$saveOrderStatus) {
  594. return false;
  595. }
  596. $order_id = $myOrder['order_id'];
  597. if (!$increment_id) {
  598. $increment_id = $this->generateIncrementIdByOrderId($order_id);
  599. $myOrder['increment_id'] = $increment_id;
  600. // 保存订单
  601. $saveOrderStatus = $myOrder->save();
  602. if (!$saveOrderStatus) {
  603. return false;
  604. }
  605. }
  606. Yii::$service->event->trigger($afterEventName, $myOrder);
  607. if ($myOrder[$this->getPrimaryKey()]) {
  608. // 保存订单产品
  609. $saveItemStatus = Yii::$service->order->item->saveOrderItems($cartInfo['products'], $order_id, $cartInfo['store']);
  610. if (!$saveItemStatus) {
  611. return false;
  612. }
  613. // 订单生成成功,通过api传递数据给trace系统
  614. $this->sendTracePaymentPendingOrder($myOrder, $cartInfo['products']);
  615. // 如果是登录用户,那么,在生成订单后,需要清空购物车中的产品和coupon。
  616. if (!Yii::$app->user->isGuest && $clearCart) {
  617. Yii::$service->cart->clearCartProductAndCoupon();
  618. }
  619. $this->createdOrder = $myOrder;
  620. // 执行成功,则在session中设置increment_id
  621. if (!Yii::$service->store->isAppserver()) { // appserver入口,没有session机制。
  622. $this->setSessionIncrementId($increment_id);
  623. }
  624. return true;
  625. } else {
  626. Yii::$service->helper->errors->add('generate order fail');
  627. return false;
  628. }
  629. }
  630. /**
  631. * @param $order_increment_id | string,订单编号 increment_id
  632. * 订单支付成功后,执行的代码,该代码只会在接收到支付成功信息后,才会执行。
  633. * 在调用该函数前,会对IPN支付成功消息做验证,一次,无论发送多少次ipn消息,该函数只会执行一次。
  634. * 您可以把订单支付成功需要做的事情都在这个函数里面完成。
  635. **/
  636. public function orderPaymentCompleteEvent($order_increment_id)
  637. {
  638. if (!$order_increment_id) {
  639. Yii::$service->helper->errors->add('order increment id is empty');
  640. return false;
  641. }
  642. $orderInfo = Yii::$service->order->getOrderInfoByIncrementId($order_increment_id);
  643. if (!$orderInfo['increment_id']) {
  644. Yii::$service->helper->errors->add('get order by increment_id: {increment_id} fail, order is not exist ', ['increment_id' => $order_increment_id]);
  645. return false;
  646. }
  647. // 追踪信息
  648. Yii::$service->order->sendTracePaymentSuccessOrder($orderInfo);
  649. // 发送订单支付成功邮件
  650. Yii::$service->email->order->sendCreateEmail($orderInfo);
  651. }
  652. /**
  653. * @param $orderInfo | Object, 订单对象
  654. * @param $cartInfo | Object,购物车对象
  655. * 根据传递的参数,得出trace系统的要求的order参数格式数组
  656. * 执行page trace services,将支付完成订单的数据传递给trace系统
  657. */
  658. protected function sendTracePaymentSuccessOrder($orderInfo)
  659. {
  660. \Yii::info('sendTracePaymentSuccessOrder', 'fecshop_debug');
  661. if (Yii::$service->page->trace->traceJsEnable) {
  662. $arr = [];
  663. $arr['invoice'] = (string)$orderInfo['increment_id'];
  664. $arr['order_type'] = $orderInfo['checkout_method'];
  665. $arr['payment_status'] = $orderInfo['order_status'];
  666. $arr['payment_type'] = $orderInfo['payment_method'];
  667. $arr['amount'] = (float)$orderInfo['base_grand_total'];
  668. $arr['shipping'] = (float)$orderInfo['base_shipping_total'];
  669. $arr['discount_amount'] = (float)$orderInfo['base_subtotal_with_discount'];
  670. $arr['coupon'] = $orderInfo['coupon_code'];
  671. $arr['city'] = $orderInfo['customer_address_city'];
  672. $arr['email'] = $orderInfo['customer_email'];
  673. $arr['first_name'] = $orderInfo['customer_firstname'];
  674. $arr['last_name'] = $orderInfo['customer_lastname'];
  675. $arr['zip'] = $orderInfo['customer_address_zip'];
  676. $arr['address1'] = $orderInfo['customer_address_street1'];
  677. $arr['address2'] = $orderInfo['customer_address_street2'];
  678. $arr['created_at'] = $orderInfo['created_at'];
  679. $arr['country_code'] = $orderInfo['customer_address_country'];
  680. $arr['state_code'] = $orderInfo['customer_address_state'];
  681. $arr['state_name'] = Yii::$service->helper->country->getStateByContryCode($orderInfo['customer_address_country'], $orderInfo['customer_address_state']);
  682. $arr['country_name'] = Yii::$service->helper->country->getCountryNameByKey($orderInfo['customer_address_country']);
  683. $product_arr = [];
  684. $products = $orderInfo['products'];
  685. if (is_array($products)) {
  686. foreach ($products as $product) {
  687. $product_arr[] = [
  688. 'sku' => $product['sku'],
  689. 'name' => $product['name'],
  690. 'qty' => (int)$product['qty'],
  691. 'price' => (float)$product['base_product_price'],
  692. ];
  693. }
  694. }
  695. $arr['products'] = $product_arr;
  696. \Yii::info('sendTracePaymentSuccessOrderByApi', 'fecshop_debug');
  697. Yii::$service->page->trace->sendTracePaymentSuccessOrderByApi($arr);
  698. return true;
  699. }
  700. return false;
  701. }
  702. /**
  703. * @param $myOrder | Object, 订单对象
  704. * @param $products | Array,购物车产品数组
  705. * 根据传递的参数,得出trace系统的要求的order参数格式数组,
  706. * 执行page trace services,将等待支付订单(刚刚生成的订单)的数据传递给trace系统
  707. */
  708. protected function sendTracePaymentPendingOrder($myOrder, $products)
  709. {
  710. if (Yii::$service->page->trace->traceJsEnable) {
  711. $arr = [];
  712. $arr['invoice'] = (string)$myOrder['increment_id'];
  713. $arr['order_type'] = $myOrder['checkout_method'];
  714. $arr['payment_status'] = $myOrder['order_status'];
  715. $arr['payment_type'] = $myOrder['payment_method'];
  716. $arr['amount'] = (float)$myOrder['base_grand_total'];
  717. $arr['shipping'] = (float)$myOrder['base_shipping_total'];
  718. $arr['discount_amount'] = (float)$myOrder['base_subtotal_with_discount'];
  719. $arr['coupon'] = $myOrder['coupon_code'];
  720. $arr['city'] = $myOrder['customer_address_city'];
  721. $arr['created_at'] = $myOrder['created_at'];
  722. $arr['email'] = $myOrder['customer_email'];
  723. $arr['first_name'] = $myOrder['customer_firstname'];
  724. $arr['last_name'] = $myOrder['customer_lastname'];
  725. $arr['zip'] = $myOrder['customer_address_zip'];
  726. $arr['address1'] = $myOrder['customer_address_street1'];
  727. $arr['address2'] = $myOrder['customer_address_street2'];
  728. $arr['country_code'] = $myOrder['customer_address_country'];
  729. $arr['state_code'] = $myOrder['customer_address_state'];
  730. $arr['state_name'] = Yii::$service->helper->country->getStateByContryCode($myOrder['customer_address_country'], $myOrder['customer_address_state']);
  731. $arr['country_name'] = Yii::$service->helper->country->getCountryNameByKey($myOrder['customer_address_country']);
  732. $product_arr = [];
  733. // $products = $cartInfo['products'];
  734. if (is_array($products)) {
  735. foreach ($products as $product) {
  736. $product_arr[] = [
  737. 'sku' => $product['sku'],
  738. 'name' => $product['name'],
  739. 'qty' => (int)$product['qty'],
  740. 'price' => (float)$product['base_product_price'],
  741. ];
  742. }
  743. }
  744. $arr['products'] = $product_arr;
  745. Yii::$service->page->trace->sendTracePaymentPendingOrderByApi($arr);
  746. return true;
  747. }
  748. return false;
  749. }
  750. /**
  751. * @param $increment_id | String 每执行一次,version都会+1 (version默认为0)
  752. * 执行完,查看version是否为1,如果不为1,则说明已经执行过了,返回false
  753. */
  754. public function checkOrderVersion($increment_id)
  755. {
  756. // 更新订单版本号,防止被多次执行。
  757. $sql = 'update '.$this->_orderModel->tableName().' set version = version + 1 where increment_id = :increment_id';
  758. $data = [
  759. 'increment_id' => $increment_id,
  760. ];
  761. $result = $this->_orderModel->getDb()->createCommand($sql, $data)->execute();
  762. $myOrder = $this->_orderModel->find()->where([
  763. 'increment_id' => $increment_id,
  764. ])->one();
  765. // 如果版本号不等于1,则回滚
  766. if ($myOrder['version'] > 1) {
  767. Yii::$service->helper->errors->add('Your order has been paid');
  768. return false;
  769. } elseif ($myOrder['version'] < 1) {
  770. Yii::$service->helper->errors->add('Your order is error');
  771. return false;
  772. } else {
  773. return true;
  774. }
  775. }
  776. /**
  777. * @param $increment_id | String ,order订单号
  778. * 将生成的订单号写入session
  779. */
  780. protected function actionSetSessionIncrementId($increment_id)
  781. {
  782. Yii::$service->session->set(self::CURRENT_ORDER_INCREAMENT_ID, $increment_id);
  783. }
  784. /**
  785. * 从session中取出来订单号.
  786. */
  787. protected function actionGetSessionIncrementId()
  788. {
  789. return Yii::$service->session->get(self::CURRENT_ORDER_INCREAMENT_ID);
  790. }
  791. /**
  792. * @param $increment_id | String 订单号
  793. * @param $token | String ,通过api支付的token
  794. * 通过订单号,更新订单的支付token
  795. */
  796. protected function actionUpdateTokenByIncrementId($increment_id, $token)
  797. {
  798. $myOrder = Yii::$service->order->getByIncrementId($increment_id);
  799. if ($myOrder) {
  800. $myOrder->payment_token = $token;
  801. $myOrder->save();
  802. }
  803. }
  804. /**
  805. * 从session中销毁订单号.
  806. */
  807. protected function actionRemoveSessionIncrementId()
  808. {
  809. return Yii::$service->session->remove(self::CURRENT_ORDER_INCREAMENT_ID);
  810. }
  811. /**
  812. * @param int $order_id the order id
  813. * @return int $increment_id
  814. * 通过 order_id 生成订单号。
  815. */
  816. protected function generateIncrementIdByOrderId($order_id)
  817. {
  818. $increment_id = (int) $this->increment_id + (int) $order_id;
  819. return $increment_id;
  820. }
  821. /**
  822. * get order list by customer account id.
  823. * @param int $customer_id
  824. * @deprecated
  825. */
  826. protected function actionGetCustomerOrderList($customer_id)
  827. {
  828. }
  829. /**
  830. * @param int $order_id the order id
  831. * 订单支付成功后,更改订单的状态为支付成功状态。
  832. * @deprecated
  833. */
  834. protected function actionOrderPaySuccess($order_id)
  835. {
  836. }
  837. /**
  838. * @param $increment_id | String
  839. * @return bool
  840. * 取消订单,更新订单的状态为cancel。
  841. * 并且释放库存给产品
  842. */
  843. protected function actionCancel($increment_id = '', $customer_id = '')
  844. {
  845. if (!$increment_id) {
  846. $increment_id = $this->getSessionIncrementId();
  847. }
  848. if ($increment_id) {
  849. $order = $this->getByIncrementId($increment_id);
  850. if ($customer_id && $order['customer_id'] != $customer_id) {
  851. Yii::$service->helper->errors->add('do not have role to cancel this order');
  852. return false;
  853. }
  854. if ($order) {
  855. $order->order_status = $this->status_canceled;
  856. $order->updated_at = time();
  857. $order->save();
  858. // 释放库存
  859. $order_primary_key = $this->getPrimaryKey();
  860. $product_items = Yii::$service->order->item->getByOrderId($order[$order_primary_key], true);
  861. Yii::$service->product->stock->returnQty($product_items);
  862. return true;
  863. }
  864. }
  865. return false;
  866. }
  867. // 用户确认收货
  868. public function delivery($incrementId, $customerId)
  869. {
  870. $updateComules = $this->_orderModel->updateAll(
  871. [
  872. 'order_status' => $this->status_completed,
  873. ],
  874. [
  875. 'increment_id' => $incrementId,
  876. 'order_status' => $this->status_dispatched,
  877. 'customer_id' => $customerId,
  878. ]
  879. );
  880. if (empty($updateComules)) {
  881. Yii::$service->helper->errors->add('customer delivery order fail');
  882. return false;
  883. }
  884. return true;
  885. }
  886. /**
  887. * 将xx时间内未支付的pending订单取消掉,并释放产品库存。
  888. * 这个是后台脚本执行的函数。
  889. */
  890. protected function actionReturnPendingStock()
  891. {
  892. $logMessage = [];
  893. $minute = $this->minuteBeforeThatReturnPendingStock;
  894. $begin_time = strtotime(date('Y-m-d H:i:s'). ' -'.$minute.' minutes ');
  895. // 不需要释放库存的支付方式。譬如货到付款,在系统中
  896. // pending订单,如果一段时间未付款,会释放产品库存,但是货到付款类型的订单不会释放,
  897. // 如果需要释放产品库存,客服在后台取消订单即可释放产品库存。
  898. $noRelasePaymentMethod = Yii::$service->payment->noRelasePaymentMethod;
  899. $where = [
  900. ['<', 'updated_at', $begin_time],
  901. ['order_status' => $this->payment_status_pending],
  902. ['if_is_return_stock' => 2],
  903. ];
  904. $logMessage[] = 'order_updated_at: '.$begin_time;
  905. if (is_array($noRelasePaymentMethod) && !empty($noRelasePaymentMethod)) {
  906. $where[] = ['not in', 'payment_method', $noRelasePaymentMethod];
  907. }
  908. $filter = [
  909. 'where' => $where,
  910. 'numPerPage' => $this->orderCountThatReturnPendingStock,
  911. 'pageNum' => 1,
  912. 'asArray' => false,
  913. ];
  914. $data = $this->coll($filter);
  915. $coll = $data['coll'];
  916. $count = $data['count'];
  917. $logMessage[] = 'order count: '.$count;
  918. if ($count > 0) {
  919. foreach ($coll as $one) {
  920. /**
  921. * service严格上是不允许使用事务的,该方法特殊,是命令行执行的操作。
  922. * 每一个循环是一个事务。
  923. */
  924. $innerTransaction = Yii::$app->db->beginTransaction();
  925. try {
  926. $logMessage[] = 'cancel order[begin] increment_id: '.$one['increment_id'];
  927. $order_id = $one['order_id'];
  928. $updateComules = $one->updateAll(
  929. [
  930. 'if_is_return_stock' => 1,
  931. 'order_status' => $this->payment_status_canceled,
  932. ],
  933. [
  934. 'order_id' => $one['order_id'],
  935. 'order_status' => $this->payment_status_pending,
  936. 'if_is_return_stock' => 2
  937. ]
  938. );
  939. /**
  940. * 取消订单,只能操作一次,因此,我们在更新条件里面加上了order_id, order_status,if_is_return_stock
  941. * 因为在上面查询和当前执行的时间之间,订单可能被进行其他操作,
  942. * 如果被其他操作,更改了order_status,那么上面的更新行数就是0行。
  943. * 那么事务直接回滚。
  944. */
  945. if (empty($updateComules)) {
  946. $innerTransaction->rollBack();
  947. continue;
  948. } else {
  949. $product_items = Yii::$service->order->item->getByOrderId($order_id, true);
  950. Yii::$service->product->stock->returnQty($product_items);
  951. }
  952. //$one->if_is_return_stock = 1;
  953. // 将订单取消掉。取消后的订单不能再次支付。
  954. //$one->order_status = $this->payment_status_canceled;
  955. //$one->save();
  956. $innerTransaction->commit();
  957. $logMessage[] = 'cancel order[end] increment_id: '.$one['increment_id'];
  958. } catch (\Exception $e) {
  959. $innerTransaction->rollBack();
  960. }
  961. }
  962. }
  963. return $logMessage;
  964. }
  965. /**
  966. * @param $days | Int 天数
  967. * 得到最近1个月的订单数据,包括:日期,订单支付状态,订单金额
  968. * 下面的数据是为了后台的订单统计
  969. */
  970. public function getPreMonthOrder($days)
  971. {
  972. // 得到一个月前的时间戳
  973. $preMonthTime = strtotime("-$days days");
  974. $filter = [
  975. 'select' => ['created_at', 'increment_id', 'order_status', 'base_grand_total' ],
  976. 'numPerPage' => 10000000,
  977. 'pageNum' => 1,
  978. 'where' => [
  979. ['>=', 'created_at', $preMonthTime]
  980. ],
  981. 'asArray' => true,
  982. ];
  983. $orderPaymentStatusArr = $this->getOrderPaymentedStatusArr();
  984. $data = $this->coll($filter);
  985. $coll = $data['coll'];
  986. $dateArr = Yii::$service->helper->format->getPreDayDateArr($days);
  987. $orderAmountArr = $dateArr;
  988. $paymentOrderAmountArr = $dateArr;
  989. $orderCountArr = $dateArr;
  990. $paymentOrderCountArr = $dateArr;
  991. if (is_array($coll) && !empty($coll)) {
  992. foreach ($coll as $order) {
  993. $created_at = $order['created_at'];
  994. $created_at_str = date("Y-m-d", $created_at);
  995. $order_status = $order['order_status'];
  996. $base_grand_total = $order['base_grand_total'];
  997. if (isset($orderAmountArr[$created_at_str])) {
  998. $orderAmountArr[$created_at_str] += $base_grand_total;
  999. $orderCountArr[$created_at_str] += 1;
  1000. if (in_array($order_status, $orderPaymentStatusArr)) {
  1001. $paymentOrderAmountArr[$created_at_str] += $base_grand_total;
  1002. $paymentOrderCountArr[$created_at_str] += 1;
  1003. }
  1004. }
  1005. }
  1006. }
  1007. return [
  1008. [
  1009. Yii::$service->page->translate->__('Order Total') => $orderAmountArr,
  1010. Yii::$service->page->translate->__('Payment Order Total') => $paymentOrderAmountArr,
  1011. ],
  1012. [
  1013. Yii::$service->page->translate->__('Order Count') => $orderCountArr,
  1014. Yii::$service->page->translate->__('Payment Order Count') => $paymentOrderCountArr,
  1015. ],
  1016. ];
  1017. }
  1018. }