ApproachOrderForm.php 18 KB

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