ApproachOrderForm.php 17 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497
  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'],
  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()
  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. if (!$this->_model->save()) {
  274. throw new Exception(Form::formatErrorsForApi($this->_model->getErrors()));
  275. }
  276. // 同步准订单到正式订单
  277. Order::insertOne($this->_model->toArray());
  278. OrderGoods::batchInsert(ApproachOrderGoods::findAllAsArray('ORDER_SN = :ORDER_SN', [':ORDER_SN' => $this->sn]));
  279. $transaction->commit();
  280. } catch (Exception $e) {
  281. $transaction->rollBack();
  282. $this->addError('edit', $e->getMessage());
  283. return null;
  284. }
  285. return $this->_model;
  286. }
  287. /**
  288. * 复销
  289. * @throws Exception
  290. * @throws \yii\db\Exception
  291. */
  292. public function add(){
  293. if(!$this->validate()){
  294. return null;
  295. }
  296. $ids = $this->goodsId;
  297. $totalAmount = 0;
  298. $totalPv = 0;
  299. $goodsType = ShopGoods::GOODS_TYPE;
  300. foreach ($this->goodsNum as $k => $v) {
  301. if ($v) {
  302. $goods = ShopGoods::findOneAsArray('ID=:ID AND STATUS=1',[':ID'=> $ids[$k]]);
  303. if($goods['STORE_NUMS']>0){
  304. if ($goods['TYPE'] == 1 || $goods['TYPE'] == 2) {
  305. $discount = $goodsType[$goods['TYPE']]['discount'];
  306. $realPrice = $goods['SELL_PRICE'] * $discount/100;
  307. $realPv = $goods['PRICE_PV'] * $discount/100;
  308. } else {
  309. $discount = $goods['SELL_DISCOUNT'];
  310. $realPrice = $goods['SELL_PRICE'] * $discount;
  311. $realPv = $goods['PRICE_PV'] * $discount;
  312. }
  313. $totalAmount += $realPrice * intval($v);
  314. $totalPv += $realPv * intval($v);
  315. $this->_orderGoods[] = [
  316. 'GOODS_ID' => $goods['ID'],
  317. 'PRICE' => $goods['SELL_PRICE'],
  318. 'PV' => $goods['PRICE_PV'],
  319. 'REAL_PRICE' => $realPrice,
  320. 'REAL_PV' => $realPv,
  321. 'POINT' => $goods['POINT'],
  322. 'BUY_NUMS' => intval($v),
  323. 'SKU_CODE' => $goods['GOODS_NO'],
  324. 'GOODS_TITLE' => $goods['GOODS_NAME'],
  325. 'CATEGORY_TYPE' => $goods['CATEGORY_TYPE'],
  326. 'PAY_TYPE' => $this->payType,
  327. 'EMAIL' => $this->email,
  328. ];
  329. }
  330. }
  331. }
  332. $this->_decAmount = $totalAmount;
  333. $this->_decPv = $totalPv;
  334. $this->_freight = ($totalAmount>=300) ? 0 : 15;
  335. if($this->_address['PROVINCE']==1){
  336. $this->_freight = 0;
  337. }
  338. $this->_payAmount = $this->_decAmount + $this->_freight;
  339. $db = \Yii::$app->db;
  340. $transaction = $db->beginTransaction();
  341. try {
  342. //写入订单
  343. if (!$orderResult = $this->addOrder()) {
  344. throw new Exception(Form::formatErrorsForApi($orderResult->getErrors()));
  345. }
  346. $transaction->commit();
  347. return $orderResult;
  348. }catch (\Exception $e){
  349. $transaction->rollBack();
  350. $this->addError('add', $e->getMessage());
  351. return null;
  352. }
  353. }
  354. /**
  355. * 复销订单
  356. * @throws Exception
  357. */
  358. public function addOrder()
  359. {
  360. $periodObj = Period::instance();
  361. $nowPeriodNum = $periodObj->getNowPeriodNum();
  362. $nowCalcMonth = $periodObj->getYearMonth($nowPeriodNum);
  363. $userId = \Yii::$app->user->id;
  364. $userName = Info::getUserNameByUserId($userId);
  365. $userRealName = Info::getUserRealNameByUserId($userId);
  366. $userMobile = Info::getUserMobileByUserId($userId);
  367. $userEmail = Info::getUserEmailByUserId($userId);
  368. // 加入订单信息
  369. if ($this->_address['PROVINCE'] != 1) {
  370. $warehouse = Region::getWarehouseByCode($this->_address['PROVINCE']);//仓库
  371. if (!$warehouse) {
  372. // throw new Exception('地区2暂时不支持配送,具体联系客服');
  373. }
  374. }else{
  375. $warehouse = '01';
  376. }
  377. $_hasPV = $this->_decPv;
  378. $ordNo = $this->_generateSn();
  379. $orderModel = new ApproachOrder();
  380. $orderModel->SN = 'OS' . $ordNo;
  381. $orderModel->DEC_SN = 'DS' . $ordNo;
  382. $orderModel->ORDER_TYPE = $this->type;
  383. $orderModel->USER_ID = $userId;
  384. $orderModel->USER_NAME = $userName;
  385. $orderModel->ORDER_AMOUNT = $this->_decAmount;
  386. $orderModel->PV = $_hasPV;
  387. $orderModel->PAY_AMOUNT = $this->_payAmount;
  388. $orderModel->PAY_PV = $_hasPV; // 兑换积分不能算业绩
  389. $orderModel->PAY_AT = 0;
  390. $orderModel->PAY_TYPE = $this->payType;
  391. $orderModel->PERIOD_NUM = $nowPeriodNum;
  392. $orderModel->P_CALC_MONTH = Date::ociToDate($nowCalcMonth, Date::OCI_TIME_FORMAT_SHORT_MONTH);
  393. $orderModel->FREIGHT = $this->_freight;
  394. $orderModel->PAY_FREIGHT = $this->_freight;
  395. $orderModel->CONSIGNEE = $this->_address['CONSIGNEE'];
  396. $orderModel->MOBILE = $this->_address['MOBILE'];
  397. $orderModel->PROVINCE = $this->_address['PROVINCE'];
  398. // $orderModel->CITY = $this->_address['CITY'];
  399. // $orderModel->COUNTY = $this->_address['COUNTY'];
  400. $orderModel->LGA_NAME = $this->_address['LGA_NAME'];
  401. $orderModel->CITY_NAME = $this->_address['CITY_NAME'];
  402. $orderModel->ADDRESS = $this->_address['ADDRESS'];
  403. $orderModel->FRONT_REMARK = $this->remark;
  404. $orderModel->WAREHOUSE = $warehouse;
  405. $orderModel->STATUS = \Yii::$app->params['orderStatus']['notPaid']['value'];
  406. $orderModel->CREATED_AT = Date::nowTime();
  407. $orderModel->CREATE_USER = $userName;
  408. $orderModel->EMAIL = $userEmail?$userEmail:$userName.'@elken.net';
  409. if($this->_address['PROVINCE']==1){
  410. $orderModel->EXPRESS_TYPE = 1;
  411. $orderModel->CONSIGNEE = $userRealName;
  412. $orderModel->MOBILE = $userMobile;
  413. $orderModel->PROVINCE = 1;
  414. $orderModel->CITY = 1;
  415. $orderModel->COUNTY = 1;
  416. $orderModel->ADDRESS = '';
  417. }
  418. if(!$orderModel->save()){
  419. $this->addErrors($orderModel->getErrors());
  420. return false;
  421. }
  422. // 加入商品到订单商品表
  423. foreach($this->_orderGoods as $key=>$value) {
  424. $this->_orderGoods[$key]['ORDER_SN'] = $orderModel->SN;
  425. $this->_orderGoods[$key]['P_CALC_MONTH'] = Date::ociToDate($nowCalcMonth, Date::OCI_TIME_FORMAT_SHORT_MONTH);
  426. }
  427. ApproachOrderGoods::batchInsert($this->_orderGoods);
  428. // TODO: 记录流水
  429. return $orderModel;
  430. }
  431. /**
  432. * 生成流水号
  433. * @return string
  434. */
  435. private function _generateSn() {
  436. return Date::today('Ymd') . $this->_random(10, 1);
  437. }
  438. /**
  439. * 生成随机数
  440. * @param $length
  441. * @param int $numeric
  442. * @return string
  443. */
  444. private function _random($length, $numeric = 0) {
  445. $seed = base_convert(md5(microtime() . $_SERVER['DOCUMENT_ROOT']), 16, $numeric ? 10 : 35);
  446. $seed = $numeric ? (str_replace('0', '', $seed) . '012340567890') : ($seed . 'zZ' . strtoupper($seed));
  447. $hash = '';
  448. $max = strlen($seed) - 1;
  449. for ($i = 0; $i < $length; $i++) {
  450. $hash .= $seed[mt_rand(0, $max)];
  451. }
  452. return $hash;
  453. }
  454. }