OrderForm.php 13 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378
  1. <?php
  2. namespace common\models\forms;
  3. use common\helpers\Date;
  4. use common\components\Model;
  5. use common\helpers\Form;
  6. use common\helpers\user\Balance;
  7. use common\helpers\user\Cash;
  8. use common\helpers\user\Info;
  9. use common\libs\logging\operate\AdminOperate;
  10. use common\models\DealType;
  11. use common\models\Order;
  12. use common\models\OrderGoods;
  13. use common\models\Period;
  14. use common\models\ReceiveAddress;
  15. use common\models\Region;
  16. use common\models\ShopGoods;
  17. use common\models\User;
  18. use yii\base\Exception;
  19. /**
  20. * Login form
  21. */
  22. class OrderForm extends Model
  23. {
  24. public $sn;
  25. public $expressCompany;
  26. public $orderTrackNo;
  27. public $status;
  28. public $remark;
  29. public $type;
  30. public $addressId;
  31. public $payType;
  32. public $goodsId;
  33. public $goodsNum;
  34. public $payPassword;
  35. private $_address;
  36. private $_decAmount;
  37. private $_decPv;
  38. private $_freight;
  39. private $_payAmount;
  40. private $_orderGoods;
  41. /**
  42. * @var Order
  43. */
  44. private $_model;
  45. public function init() {
  46. parent::init();
  47. $this->adminOperateLogger = new AdminOperate([
  48. 'fetchClass' => Order::class,
  49. ]);
  50. }
  51. /**
  52. * @inheritdoc
  53. */
  54. public function rules()
  55. {
  56. return [
  57. [['sn', 'expressCompany', 'orderTrackNo', 'status', 'remark','type','addressId','payType','goodsId','goodsNum', 'payPassword'], 'trim'],
  58. [['sn', 'expressCompany', 'orderTrackNo', 'status', 'remark','type','addressId','payType','goodsId','goodsNum', 'payPassword'], 'required'],
  59. [['status'], 'isStatus'],
  60. [['addressId'], 'isAddress'],
  61. [['payType'], 'isPayType'],
  62. [['payPassword'], 'validatePassword'],
  63. ];
  64. }
  65. public function attributeLabels()
  66. {
  67. return [
  68. 'sn' => '订单号',
  69. 'expressCompany' => '快递公司',
  70. 'orderTrackNo' => '快递单号',
  71. 'status' => '状态',
  72. 'remark' => '备注',
  73. 'type' => '订单类型',
  74. 'addressId' => '收货地址',
  75. 'payType' => '支付方式',
  76. 'goodsId' => '商品ID',
  77. 'goodsNum' => '商品数量',
  78. ];
  79. }
  80. /**
  81. * 指定校验场景
  82. * @return array
  83. */
  84. public function scenarios()
  85. {
  86. $parentScenarios = parent::scenarios();
  87. $customScenarios = [
  88. // 管理员发货
  89. 'adminDelivery' => ['sn', 'expressCompany', 'orderTrackNo'],
  90. // 会员确认收货
  91. 'userConfirm' => ['sn', 'expressCompany', 'orderTrackNo'],
  92. // 管理员修改订单状态
  93. 'adminStatus' => ['sn', 'status'],
  94. // 管理员修改备注
  95. 'adminRemark' => ['sn', 'remark'],
  96. // 会员下单
  97. 'userOrder' => ['type','addressId', 'payType','goodsId','goodsNum', 'remark', 'payPassword'],
  98. ];
  99. return array_merge($parentScenarios, $customScenarios);
  100. }
  101. /**
  102. * 校验之前
  103. * @return bool
  104. */
  105. public function beforeValidate()
  106. {
  107. $parentValidate = parent::beforeValidate();
  108. if ($this->sn) {
  109. $this->_model = Order::findOne(['SN'=>$this->sn]);
  110. if (!$this->_model){
  111. $this->addError('sn', '订单不存在');
  112. return false;
  113. }
  114. }
  115. if ($this->scenario == 'adminDelivery'){
  116. if($this->_model['STATUS'] == \Yii::$app->params['orderStatus']['cancel']) {
  117. $this->addError('sn', '订单已取消不能发货');
  118. return false;
  119. }
  120. if($this->_model['STATUS'] == \Yii::$app->params['orderStatus']['del']) {
  121. $this->addError('sn', '订单已删除不能发货');
  122. return false;
  123. }
  124. }
  125. return $parentValidate;
  126. }
  127. /**
  128. * 校验支付密码
  129. * @param $attribute
  130. * @param $params
  131. */
  132. public function validatePassword($attribute, $params) {
  133. if (!User::validatePayPassword(\Yii::$app->user->id, $this->payPassword)) {
  134. $this->addError($attribute, '支付密码不正确');
  135. }
  136. }
  137. /**
  138. * 判断收货地址是否存在
  139. * @param $attribute
  140. */
  141. public function isAddress($attribute){
  142. if (!$receiveAddress = ReceiveAddress::find()->where(' ID=:ID', [':ID' => $this->addressId])->asArray()->one()) {
  143. $this->addError($attribute, '收货地址不存在');
  144. } else {
  145. $this->_address = $receiveAddress;
  146. }
  147. }
  148. /**
  149. * 判断支付方式
  150. * @param $attribute
  151. */
  152. public function isPayType($attribute){
  153. if(!array_key_exists($this->payType, ShopGoods::payTypes())){
  154. $this->addError($attribute, '支付方式错误');
  155. return;
  156. }
  157. }
  158. /**
  159. * 校验类型
  160. * @param $attribute
  161. */
  162. public function isStatus($attribute){
  163. if(!in_array($this->type, \Yii::$app->params['orderStatus'])){
  164. $this->addError($attribute, '类型错误');
  165. return ;
  166. }
  167. if ($this->scenario == 'adminStatus'){
  168. if ($this->status == $this->_model['STATUS']) {
  169. $this->addError($attribute, '订单状态没有改变');
  170. return ;
  171. }
  172. if($this->status == \Yii::$app->params['orderStatus']['notPaid'] && $this->_model['STATUS'] >= \Yii::$app->params['orderStatus']['delivery']) {
  173. $this->addError($attribute, '订单已经进入物流状态不能改为未支付');
  174. return ;
  175. }
  176. elseif($this->status == \Yii::$app->params['orderStatus']['paid'] && $this->_model['STATUS'] >= \Yii::$app->params['orderStatus']['cancel']) {
  177. $this->addError($attribute, '订单已失效不能处理');
  178. return ;
  179. }
  180. elseif($this->status == \Yii::$app->params['orderStatus']['delivery']) {
  181. $this->addError($attribute, '订单不能单独处理为物流状态');
  182. return ;
  183. }
  184. elseif($this->status == \Yii::$app->params['orderStatus']['complete'] && $this->_model['STATUS'] > \Yii::$app->params['orderStatus']['cancel']) {
  185. $this->addError($attribute, '订单已失效不能处理');
  186. return ;
  187. }
  188. elseif($this->status == \Yii::$app->params['orderStatus']['cancel']) {
  189. if($this->_model['STATUS'] == \Yii::$app->params['orderStatus']['complete']) {
  190. $this->addError($attribute, '订单已完成不能取消');
  191. return ;
  192. }
  193. if($this->_model['STATUS'] == \Yii::$app->params['orderStatus']['del']) {
  194. $this->addError($attribute, '订单已删除不能取消');
  195. return ;
  196. }
  197. }
  198. elseif($this->status == \Yii::$app->params['orderStatus']['del']) {
  199. if($this->_model['STATUS'] == \Yii::$app->params['orderStatus']['complete']) {
  200. $this->addError($attribute, '订单已完成不能删除');
  201. return ;
  202. }
  203. }
  204. }
  205. }
  206. /**
  207. * 复销
  208. * @return bool|null
  209. * @throws Exception
  210. * @throws \yii\db\Exception
  211. */
  212. public function add(){
  213. if(!$this->validate()){
  214. return null;
  215. }
  216. $ids = $this->goodsId;
  217. $totalAmount = 0;
  218. $totalPv = 0;
  219. $goodsType = ShopGoods::GOODS_TYPE;
  220. foreach ($this->goodsNum as $k => $v) {
  221. if ($v) {
  222. $goods = ShopGoods::findOneAsArray('ID=:ID AND STATUS=1',[':ID'=> $ids[$k]]);
  223. if($goods['STORE_NUMS']>0){
  224. $discount = $goodsType[$goods['TYPE']]['discount'];
  225. $realPrice = $goods['SELL_PRICE'] * $discount/100;
  226. $realPv = $goods['PRICE_PV'] * $discount/100;
  227. $totalAmount += $realPrice * intval($v);
  228. $totalPv += $realPv * intval($v);
  229. $this->_orderGoods[] = [
  230. 'GOODS_ID' => $goods['ID'],
  231. 'PRICE' => $goods['SELL_PRICE'],
  232. 'PV' => $goods['PRICE_PV'],
  233. 'REAL_PRICE' => $realPrice,
  234. 'REAL_PV' => $realPv,
  235. 'POINT' => $goods['POINT'],
  236. 'BUY_NUMS' => intval($v),
  237. 'SKU_CODE' => $goods['GOODS_NO'],
  238. 'GOODS_TITLE' => $goods['GOODS_NAME']
  239. ];
  240. }
  241. }
  242. }
  243. $this->_decAmount = $totalAmount;
  244. $this->_decPv = $totalPv;
  245. $this->_freight = ($totalAmount>=300) ? 0 : 15;
  246. $this->_payAmount = $this->_decAmount + $this->_freight;
  247. $db = \Yii::$app->db;
  248. $transaction = $db->beginTransaction();
  249. try {
  250. //判断用户余额是否充足
  251. $loginUserId = \Yii::$app->user->id;
  252. if($this->payType=='cash') {
  253. if (Cash::getAvailableBalance($loginUserId) < $this->_payAmount) {
  254. throw new Exception('余额不足,无法购买商品');
  255. }
  256. }else{
  257. if ($this->_payAmount > Balance::getBalanceReconsumePoints($loginUserId)) {
  258. throw new Exception('复消积分不足,无法购买商品');
  259. }
  260. }
  261. //写入订单
  262. if (!$orderResult = $this->addOrder()) {
  263. throw new Exception(Form::formatErrorsForApi($orderResult->getErrors()));
  264. }
  265. $transaction->commit();
  266. }catch (\Exception $e){
  267. $transaction->rollBack();
  268. $this->addError('add', $e->getMessage());
  269. return null;
  270. }
  271. return true;
  272. }
  273. public function addOrder(){
  274. $periodObj = Period::instance();
  275. $nowPeriodNum = $periodObj->getNowPeriodNum();
  276. $nowCalcMonth = $periodObj->getYearMonth($nowPeriodNum);
  277. $userId = \Yii::$app->user->id;
  278. $userName = Info::getUserNameByUserId($userId);
  279. // 加入订单信息
  280. $warehouse = Region::getWarehouseByCode($this->_address['PROVINCE']);//仓库
  281. if(!$warehouse){
  282. throw new Exception('地区暂时不支持配送,具体联系客服');
  283. }
  284. $ordNo = $this->_generateSn();
  285. $orderModel = new Order();
  286. $orderModel->SN = 'OS'.$ordNo;
  287. $orderModel->DEC_SN = 'DS'.$ordNo;
  288. $orderModel->ORDER_TYPE = $this->type;
  289. $orderModel->USER_ID = $userId;
  290. $orderModel->USER_NAME = $userName;
  291. $orderModel->ORDER_AMOUNT = $this->_decAmount;
  292. $orderModel->PV = $this->_decPv;
  293. $orderModel->PAY_AMOUNT = $this->_payAmount;
  294. $orderModel->PAY_PV = $this->_decPv;
  295. $orderModel->PAY_AT = Date::nowTime();
  296. $orderModel->PAY_TYPE = $this->payType;
  297. $orderModel->PERIOD_NUM = $nowPeriodNum;
  298. $orderModel->P_CALC_MONTH = Date::ociToDate($nowCalcMonth, Date::OCI_TIME_FORMAT_SHORT_MONTH);
  299. $orderModel->FREIGHT = $this->_freight;
  300. $orderModel->PAY_FREIGHT = $this->_freight;
  301. $orderModel->CONSIGNEE = $this->_address['CONSIGNEE'];
  302. $orderModel->MOBILE = $this->_address['MOBILE'];
  303. $orderModel->PROVINCE = $this->_address['PROVINCE'];
  304. $orderModel->CITY = $this->_address['CITY'];
  305. $orderModel->COUNTY = $this->_address['COUNTY'];
  306. $orderModel->ADDRESS = $this->_address['ADDRESS'];
  307. $orderModel->FRONT_REMARK = $this->remark;
  308. $orderModel->WAREHOUSE = $warehouse;
  309. $orderModel->STATUS = 1;
  310. $orderModel->CREATED_AT = Date::nowTime();
  311. $orderModel->CREATE_USER = $userName;
  312. if(!$orderModel->save()){
  313. $this->addErrors($orderModel->getErrors());
  314. return false;
  315. }
  316. // 加入商品到订单商品表
  317. foreach($this->_orderGoods as $key=>$value){
  318. $this->_orderGoods[$key]['ORDER_SN'] = $orderModel->SN;
  319. $this->_orderGoods[$key]['P_CALC_MONTH'] = Date::ociToDate($nowCalcMonth, Date::OCI_TIME_FORMAT_SHORT_MONTH);
  320. }
  321. OrderGoods::batchInsert($this->_orderGoods);
  322. //扣除会员余额/积分
  323. if($this->payType=='cash') {
  324. Cash::changeUserCash(\Yii::$app->user->id, 'CASH', -abs($this->_payAmount), ['REMARK' => '会员复销余额支付']);
  325. }else{
  326. }
  327. return $orderModel;
  328. }
  329. /**
  330. * 生成流水号
  331. * @return string
  332. */
  333. private function _generateSn() {
  334. return Date::today('Ymd') . $this->_random(10, 1);
  335. }
  336. /**
  337. * 生成随机数
  338. * @param $length
  339. * @param int $numeric
  340. * @return string
  341. */
  342. private function _random($length, $numeric = 0) {
  343. $seed = base_convert(md5(microtime() . $_SERVER['DOCUMENT_ROOT']), 16, $numeric ? 10 : 35);
  344. $seed = $numeric ? (str_replace('0', '', $seed) . '012340567890') : ($seed . 'zZ' . strtoupper($seed));
  345. $hash = '';
  346. $max = strlen($seed) - 1;
  347. for ($i = 0; $i < $length; $i++) {
  348. $hash .= $seed[mt_rand(0, $max)];
  349. }
  350. return $hash;
  351. }
  352. }