ApproachOrderForm.php 18 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500
  1. <?php
  2. namespace common\models\forms;
  3. use common\helpers\Cache;
  4. use common\helpers\Date;
  5. use common\components\Model;
  6. use common\helpers\Form;
  7. use common\helpers\PayStack;
  8. use common\helpers\user\Balance;
  9. use common\helpers\user\Cash;
  10. use common\helpers\user\Info;
  11. use common\libs\logging\operate\AdminOperate;
  12. use common\models\ApproachOrder;
  13. use common\models\ApproachOrderGoods;
  14. use common\models\DealType;
  15. use common\models\Order;
  16. use common\models\OrderGoods;
  17. use common\models\Period;
  18. use common\models\ReceiveAddress;
  19. use common\models\Region;
  20. use common\models\ShopGoods;
  21. use common\models\User;
  22. use common\models\UserNetwork;
  23. use yii\base\Exception;
  24. /**
  25. * Login form
  26. */
  27. class ApproachOrderForm extends Model
  28. {
  29. public $sn;
  30. public $expressCompany;
  31. public $orderTrackNo;
  32. public $status;
  33. public $remark;
  34. public $type;
  35. public $addressId;
  36. public $payType;
  37. public $goodsId;
  38. public $goodsNum;
  39. public $payPassword;
  40. public $email;
  41. public $userName;
  42. public $consignee;
  43. public $acceptMobile;
  44. public $province;
  45. public $city;
  46. public $county;
  47. public $detailaddress;
  48. private $_address;
  49. private $_decAmount;
  50. private $_decPv;
  51. private $_freight;
  52. private $_payAmount;
  53. private $_orderGoods;
  54. /**
  55. * @var ApproachOrder
  56. */
  57. private $_model;
  58. public function init() {
  59. parent::init();
  60. $this->adminOperateLogger = new AdminOperate([
  61. 'fetchClass' => ApproachOrder::class,
  62. ]);
  63. }
  64. /**
  65. * @inheritdoc
  66. */
  67. public function rules()
  68. {
  69. return [
  70. [['sn', 'expressCompany', 'orderTrackNo', 'status', 'remark','type','addressId','payType','goodsId','goodsNum', 'payPassword','userName','consignee','acceptMobile','province','city','county','detailaddress','email'], 'trim'],
  71. [['sn', 'expressCompany', 'orderTrackNo', 'status', 'remark','type','addressId','payType','goodsId','goodsNum', 'payPassword','userName','consignee','acceptMobile','province','city','county','detailaddress','email'], 'required'],
  72. [['status'], 'isStatus'],
  73. [['addressId'], 'isAddress'],
  74. [['payType'], 'isPayType'],
  75. [['payPassword'], 'validatePassword'],
  76. ];
  77. }
  78. public function attributeLabels()
  79. {
  80. return [
  81. 'sn' => '订单号',
  82. 'expressCompany' => '快递公司',
  83. 'orderTrackNo' => '快递单号',
  84. 'status' => '状态',
  85. 'remark' => '备注',
  86. 'type' => '订单类型',
  87. 'addressId' => '收货地址',
  88. 'payType' => '支付方式',
  89. 'goodsId' => '商品ID',
  90. 'goodsNum' => '商品数量',
  91. 'userName' => '复消会员编号',
  92. 'consignee' => '收货人',
  93. 'acceptMobile' => '收货电话',
  94. 'province' => '省',
  95. 'city' => '市',
  96. 'county' => '区',
  97. 'detailaddress' => '收货详细地址',
  98. 'email' => 'Email',
  99. ];
  100. }
  101. /**
  102. * 指定校验场景
  103. * @return array
  104. */
  105. public function scenarios()
  106. {
  107. $parentScenarios = parent::scenarios();
  108. $customScenarios = [
  109. // 管理员修改订单状态
  110. 'adminStatus' => ['sn', 'status'],
  111. // 管理员修改订单状态
  112. 'verifyPayStack' => ['sn', 'remark', 'email'],
  113. // 会员下单
  114. 'userOrder' => ['type','addressId', 'payType','goodsId','goodsNum', 'remark', 'payPassword', 'email'],
  115. ];
  116. return array_merge($parentScenarios, $customScenarios);
  117. }
  118. /**
  119. * 校验之前
  120. * @return bool
  121. */
  122. public function beforeValidate()
  123. {
  124. $parentValidate = parent::beforeValidate();
  125. if ($this->sn) {
  126. $this->_model = ApproachOrder::findOne(['SN' => $this->sn]);
  127. if (!$this->_model){
  128. $this->addError('sn', '订单不存在');
  129. return false;
  130. }
  131. }
  132. if ($this->scenario == 'verifyPayStack'){
  133. if ($this->_model['STATUS'] != \Yii::$app->params['orderStatus']['notPaid']['value']) {
  134. $this->addError('sn', '订单支付状态错误');
  135. return false;
  136. }
  137. }
  138. return $parentValidate;
  139. }
  140. /**
  141. * 判断收货地址是否存在
  142. * @param $attribute
  143. */
  144. public function isAddress($attribute){
  145. if (!$receiveAddress = ReceiveAddress::find()->where(' ID=:ID', [':ID' => $this->addressId])->asArray()->one()) {
  146. $this->addError($attribute, '收货地址不存在');
  147. } else {
  148. $this->_address = $receiveAddress;
  149. }
  150. }
  151. /**
  152. * 校验支付密码
  153. * @param $attribute
  154. * @param $params
  155. */
  156. public function validatePassword($attribute, $params) {
  157. if (!User::validatePayPassword(\Yii::$app->user->id, $this->payPassword)) {
  158. $this->addError($attribute, '支付密码不正确');
  159. }
  160. }
  161. /**
  162. * 判断支付方式
  163. * @param $attribute
  164. */
  165. public function isPayType($attribute)
  166. {
  167. if ($this->payType != 'pay_stack'){
  168. $this->addError($attribute, '只允许PayStack方式支付');
  169. return;
  170. }
  171. // 一个订单只能包含一类商品
  172. $goods = ShopGoods::find()->select('ID,CATEGORY_TYPE')->where(['in', 'ID', $this->goodsId])->andWhere(['STATUS' => 1])->asArray()->all();
  173. $goodsCategoryType = array_unique(array_column($goods, 'CATEGORY_TYPE'));
  174. if (count($goodsCategoryType) != 1) {
  175. $this->addError($attribute, '订单不能包含多种商品分类');
  176. return;
  177. }
  178. // 购买方式
  179. $sellTypeLabelMap = array_column(ShopGoods::SALE_TYPE, NULL, 'label');
  180. if (!array_key_exists($this->payType, $sellTypeLabelMap)) {
  181. $this->addError($attribute, '不支持PayStack方式支付');
  182. return;
  183. }
  184. // 所选支付方式必须是商品分类支持的类型
  185. $categoryType = array_column(ShopGoods::CATEGORY_TYPE, NULL, 'id');
  186. // 商品类型
  187. $currCategoryType = $goodsCategoryType[0];
  188. if (!array_key_exists($currCategoryType, $categoryType)) {
  189. $this->addError($attribute, '商品分类错误');
  190. return;
  191. }
  192. $sellType = $categoryType[$currCategoryType]['sell_type'] ?? [];
  193. if (!$sellType || !in_array($this->payType, array_column($sellType, 'label'))) {
  194. $this->addError($attribute, '支付方式错误3');
  195. }
  196. }
  197. /**
  198. * 校验类型
  199. * @param $attribute
  200. */
  201. public function isStatus($attribute){
  202. if(!in_array($this->type, \Yii::$app->params['orderStatus'])){
  203. $this->addError($attribute, '类型错误');
  204. return ;
  205. }
  206. if ($this->scenario == 'adminStatus'){
  207. if ($this->status == $this->_model['STATUS']) {
  208. $this->addError($attribute, '订单状态没有改变');
  209. return ;
  210. }
  211. if($this->status == \Yii::$app->params['orderStatus']['notPaid'] && $this->_model['STATUS'] >= \Yii::$app->params['orderStatus']['delivery']) {
  212. $this->addError($attribute, '订单已经进入物流状态不能改为未支付');
  213. return ;
  214. }
  215. elseif($this->status == \Yii::$app->params['orderStatus']['paid'] && $this->_model['STATUS'] >= \Yii::$app->params['orderStatus']['cancel']) {
  216. $this->addError($attribute, '订单已失效不能处理');
  217. return ;
  218. }
  219. elseif($this->status == \Yii::$app->params['orderStatus']['delivery']) {
  220. $this->addError($attribute, '订单不能单独处理为物流状态');
  221. return ;
  222. }
  223. elseif($this->status == \Yii::$app->params['orderStatus']['complete'] && $this->_model['STATUS'] > \Yii::$app->params['orderStatus']['cancel']) {
  224. $this->addError($attribute, '订单已失效不能处理');
  225. return ;
  226. }
  227. elseif($this->status == \Yii::$app->params['orderStatus']['cancel']) {
  228. if($this->_model['STATUS'] == \Yii::$app->params['orderStatus']['complete']) {
  229. $this->addError($attribute, '订单已完成不能取消');
  230. return ;
  231. }
  232. if($this->_model['STATUS'] == \Yii::$app->params['orderStatus']['del']) {
  233. $this->addError($attribute, '订单已删除不能取消');
  234. return ;
  235. }
  236. }
  237. elseif($this->status == \Yii::$app->params['orderStatus']['del']) {
  238. if($this->_model['STATUS'] == \Yii::$app->params['orderStatus']['complete']) {
  239. $this->addError($attribute, '订单已完成不能删除');
  240. return ;
  241. }
  242. }
  243. }
  244. }
  245. /**
  246. * 校验PayStack支付,更新订单状态.同步到正式订单.
  247. * @throws Exception
  248. */
  249. public function verifyPayStack(): ?ApproachOrder
  250. {
  251. if (!$this->validate()) {
  252. return null;
  253. }
  254. // 调用PayStack支付校验
  255. $payload = PayStack::transactionVerify($this->remark['reference']);
  256. if ($payload['status'] !== true) {
  257. throw new Exception(Form::formatErrorsForApi($payload['message']));
  258. }
  259. if ($payload['data']['amount'] != $this->_model->PAY_AMOUNT * 100) {
  260. throw new Exception(Form::formatErrorsForApi('支付金额与订单金额不符'));
  261. }
  262. $db = \Yii::$app->db;
  263. $transaction = $db->beginTransaction();
  264. try {
  265. // 更新准订单状态为已支付
  266. $this->_model->STATUS = \Yii::$app->params['orderStatus']['paid']['value'];
  267. $this->_model->REMARK = json_encode($this->remark);
  268. $this->_model->PAY_AT = Date::nowTime();
  269. $this->_model->EMAIL = $this->email;
  270. if (!$this->_model->save()) {
  271. throw new Exception(Form::formatErrorsForApi($this->_model->getErrors()));
  272. }
  273. // 更新订单商品的支付Email
  274. ApproachOrderGoods::updateAll(['EMAIL' => $this->email], 'ORDER_SN = :ORDER_SN', [':ORDER_SN' => $this->sn]);
  275. // 同步准订单到正式订单
  276. Order::insertOne($this->_model->toArray());
  277. // 同步准订单商品到正式订单商品
  278. $approachOrderGoods = ApproachOrderGoods::findAllAsArray('ORDER_SN = :ORDER_SN', [':ORDER_SN' => $this->sn]);
  279. foreach ($approachOrderGoods as &$approachOrderGood) {
  280. $approachOrderGood['EMAIL'] = $this->email;
  281. }
  282. OrderGoods::batchInsert($approachOrderGoods);
  283. $transaction->commit();
  284. } catch (Exception $e) {
  285. $transaction->rollBack();
  286. $this->addError('edit', $e->getMessage());
  287. return null;
  288. }
  289. return $this->_model;
  290. }
  291. /**
  292. * 复销
  293. * @throws Exception
  294. * @throws \yii\db\Exception
  295. */
  296. public function add(){
  297. if(!$this->validate()){
  298. return null;
  299. }
  300. $ids = $this->goodsId;
  301. $totalAmount = 0;
  302. $totalPv = 0;
  303. $goodsType = ShopGoods::GOODS_TYPE;
  304. foreach ($this->goodsNum as $k => $v) {
  305. if ($v) {
  306. $goods = ShopGoods::findOneAsArray('ID=:ID AND STATUS=1',[':ID'=> $ids[$k]]);
  307. if($goods['STORE_NUMS']>0){
  308. if ($goods['TYPE'] == 1 || $goods['TYPE'] == 2) {
  309. $discount = $goodsType[$goods['TYPE']]['discount'];
  310. $realPrice = $goods['SELL_PRICE'] * $discount/100;
  311. $realPv = $goods['PRICE_PV'] * $discount/100;
  312. } else {
  313. $discount = $goods['SELL_DISCOUNT'];
  314. $realPrice = $goods['SELL_PRICE'] * $discount;
  315. $realPv = $goods['PRICE_PV'] * $discount;
  316. }
  317. $totalAmount += $realPrice * intval($v);
  318. $totalPv += $realPv * intval($v);
  319. $this->_orderGoods[] = [
  320. 'GOODS_ID' => $goods['ID'],
  321. 'PRICE' => $goods['SELL_PRICE'],
  322. 'PV' => $goods['PRICE_PV'],
  323. 'REAL_PRICE' => $realPrice,
  324. 'REAL_PV' => $realPv,
  325. 'POINT' => $goods['POINT'],
  326. 'BUY_NUMS' => intval($v),
  327. 'SKU_CODE' => $goods['GOODS_NO'],
  328. 'GOODS_TITLE' => $goods['GOODS_NAME'],
  329. 'CATEGORY_TYPE' => $goods['CATEGORY_TYPE'],
  330. 'PAY_TYPE' => $this->payType,
  331. 'EMAIL' => $this->email,
  332. ];
  333. }
  334. }
  335. }
  336. $this->_decAmount = $totalAmount;
  337. $this->_decPv = $totalPv;
  338. $this->_freight = ($totalAmount>=300) ? 0 : 15;
  339. if($this->_address['PROVINCE']==1){
  340. $this->_freight = 0;
  341. }
  342. $this->_payAmount = $this->_decAmount + $this->_freight;
  343. $db = \Yii::$app->db;
  344. $transaction = $db->beginTransaction();
  345. try {
  346. //写入订单
  347. if (!$orderResult = $this->addOrder()) {
  348. throw new Exception(Form::formatErrorsForApi($orderResult->getErrors()));
  349. }
  350. $transaction->commit();
  351. return $orderResult;
  352. }catch (\Exception $e){
  353. $transaction->rollBack();
  354. $this->addError('add', $e->getMessage());
  355. return null;
  356. }
  357. }
  358. /**
  359. * 复销订单
  360. * @throws Exception
  361. */
  362. public function addOrder()
  363. {
  364. $periodObj = Period::instance();
  365. $nowPeriodNum = $periodObj->getNowPeriodNum();
  366. $nowCalcMonth = $periodObj->getYearMonth($nowPeriodNum);
  367. $userId = \Yii::$app->user->id;
  368. $userName = Info::getUserNameByUserId($userId);
  369. $userRealName = Info::getUserRealNameByUserId($userId);
  370. $userMobile = Info::getUserMobileByUserId($userId);
  371. $userEmail = Info::getUserEmailByUserId($userId);
  372. // 加入订单信息
  373. if ($this->_address['PROVINCE'] != 1) {
  374. $warehouse = Region::getWarehouseByCode($this->_address['PROVINCE']);//仓库
  375. if (!$warehouse) {
  376. // throw new Exception('地区2暂时不支持配送,具体联系客服');
  377. }
  378. }else{
  379. $warehouse = '01';
  380. }
  381. $_hasPV = $this->_decPv;
  382. $ordNo = $this->_generateSn();
  383. $orderModel = new ApproachOrder();
  384. $orderModel->SN = 'OS' . $ordNo;
  385. $orderModel->DEC_SN = 'DS' . $ordNo;
  386. $orderModel->ORDER_TYPE = $this->type;
  387. $orderModel->USER_ID = $userId;
  388. $orderModel->USER_NAME = $userName;
  389. $orderModel->ORDER_AMOUNT = $this->_decAmount;
  390. $orderModel->PV = $_hasPV;
  391. $orderModel->PAY_AMOUNT = $this->_payAmount;
  392. $orderModel->PAY_PV = $_hasPV; // 兑换积分不能算业绩
  393. $orderModel->PAY_AT = 0;
  394. $orderModel->PAY_TYPE = $this->payType;
  395. $orderModel->PERIOD_NUM = $nowPeriodNum;
  396. $orderModel->P_CALC_MONTH = Date::ociToDate($nowCalcMonth, Date::OCI_TIME_FORMAT_SHORT_MONTH);
  397. $orderModel->FREIGHT = $this->_freight;
  398. $orderModel->PAY_FREIGHT = $this->_freight;
  399. $orderModel->CONSIGNEE = $this->_address['CONSIGNEE'];
  400. $orderModel->MOBILE = $this->_address['MOBILE'];
  401. $orderModel->PROVINCE = $this->_address['PROVINCE'];
  402. $orderModel->CITY = $this->_address['CITY'];
  403. $orderModel->COUNTY = $this->_address['COUNTY'];
  404. $orderModel->ADDRESS = $this->_address['ADDRESS'];
  405. $orderModel->FRONT_REMARK = $this->remark;
  406. $orderModel->WAREHOUSE = $warehouse;
  407. $orderModel->STATUS = \Yii::$app->params['orderStatus']['notPaid']['value'];
  408. $orderModel->CREATED_AT = Date::nowTime();
  409. $orderModel->CREATE_USER = $userName;
  410. $orderModel->EMAIL = $userEmail;
  411. if($this->_address['PROVINCE']==1){
  412. $orderModel->EXPRESS_TYPE = 1;
  413. $orderModel->CONSIGNEE = $userRealName;
  414. $orderModel->MOBILE = $userMobile;
  415. $orderModel->PROVINCE = 1;
  416. $orderModel->CITY = 1;
  417. $orderModel->COUNTY = 1;
  418. $orderModel->ADDRESS = '';
  419. }
  420. if(!$orderModel->save()){
  421. $this->addErrors($orderModel->getErrors());
  422. return false;
  423. }
  424. // 加入商品到订单商品表
  425. foreach($this->_orderGoods as $key=>$value) {
  426. $this->_orderGoods[$key]['ORDER_SN'] = $orderModel->SN;
  427. $this->_orderGoods[$key]['P_CALC_MONTH'] = Date::ociToDate($nowCalcMonth, Date::OCI_TIME_FORMAT_SHORT_MONTH);
  428. }
  429. ApproachOrderGoods::batchInsert($this->_orderGoods);
  430. // TODO: 记录流水
  431. return $orderModel;
  432. }
  433. /**
  434. * 生成流水号
  435. * @return string
  436. */
  437. private function _generateSn() {
  438. return Date::today('Ymd') . $this->_random(10, 1);
  439. }
  440. /**
  441. * 生成随机数
  442. * @param $length
  443. * @param int $numeric
  444. * @return string
  445. */
  446. private function _random($length, $numeric = 0) {
  447. $seed = base_convert(md5(microtime() . $_SERVER['DOCUMENT_ROOT']), 16, $numeric ? 10 : 35);
  448. $seed = $numeric ? (str_replace('0', '', $seed) . '012340567890') : ($seed . 'zZ' . strtoupper($seed));
  449. $hash = '';
  450. $max = strlen($seed) - 1;
  451. for ($i = 0; $i < $length; $i++) {
  452. $hash .= $seed[mt_rand(0, $max)];
  453. }
  454. return $hash;
  455. }
  456. }