DefaultController.php
19.2 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
<?php
namespace app\api\modules\user\controllers;
use yii\base\Exception;
use yii\db\Query;
use app\api\controllers\ScopeUserController;
use common\business\Redpacks;
use common\helpers\Utils;
use common\models\RepairOrder as RepairOrderModel;
use common\models\ClientUser as ClientUserModel;
use common\models\MarketingRedpacks as MarketingRedpacksModel;
use common\models\UserCoupon as UserCouponModel;
use common\models\User as UserModel;
use common\models\UserDeviceFav as UserDeviceFavModel;
use common\models\Address as AddressModel;
use common\helpers\ImageManager;
use common\exts\wechat\Log as WxLog;
use common\helpers\Log as AppLog;
use common\helpers\OrderSqlHelper;
use domain\device\DeviceCatRepository;
use domain\trade\RepairOrderStatus;
use stdClass;
use function array_key_exists;
use function implode;
use function time;
use function sizeof;
/**
* 用户中心
*/
class DefaultController extends ScopeUserController
{
/**
* @return string
*/
public function actionAjaxMgets()
{
$e = new stdClass();
$e->success = true;
$e->content = $this->mgets();
return $e;
}
/**
* @return stdClass
*/
private function mgets()
{
$userId = $this->getUserId();
$clientUserId = $this->getClientUserId();
$home = new stdClass();
$home->effect_coupon_num = 0;
$home->redpacks_count = 0;
/**
* 构造user的共用信息
*/
$home->user = $this->buildUserResult($userId);
// 我的设备收藏数
$home->device_fav_num = ($userId > 0) ? UserDeviceFavModel::getFavNum($userId) : 0;
// 有效优惠券数
if (!empty($userId) && $userId > 0 ) {
$effectCoupons = UserCouponModel::getEffectCoupons($userId);
$home->effect_coupon_num = $effectCoupons ? $effectCoupons->count() : 0;
}
// 未领取红包个数
$clientUserId = empty($clientUserId) ? 0 : $clientUserId;
$userId = empty($userId) ? 0 : $userId;
$sql = Redpacks::waitReceiveSql($userId, 0, $clientUserId, 0, 0, false);
$home->redpacks_count = MarketingRedpacksModel::findBySql($sql)->count();
return $home;
}
/**
* @param $userModel
* @return stdClass
*/
private function buildUserResult($userId)
{
$clientUserId = $this->getClientUserId();
if (empty($clientUserId)) {
return false; // 未登录
}
if ($userId > 0) {
$query = UserModel::find()
->select(['user.*', 'client_user_mina.headimgurl AS headimgurl', 'client_user_mina.nickname AS nickname', 'client_user_mina.gender AS gender'])
->leftJoin('client_user', 'user.id = client_user.user_id')
->leftJoin('client_user_mina', 'client_user.id = client_user_mina.client_user_id')
->where(['user.id' => $userId, 'client_user.id' => $clientUserId]);
$query->asArray();
$userArray = $query->one();
} else {
$query = ClientUserModel::find()
->select(['cum.headimgurl AS headimgurl', 'cum.nickname AS nickname', 'cum.gender AS gender'])
->leftJoin('client_user_mina cum', 'client_user.id = cum.client_user_id')
->where(['client_user.id' => $clientUserId]);
$query->asArray();
$userArray = $query->one();
}
if (empty($userArray)) {
return false;
}
$user = new stdClass();
$user->headimgurl = !empty($userArray['headimgurl']) ? Utils::getUserAvatar($userArray['headimgurl']) : '/i/ic_default_avatar.png';
$user->nickname = !empty($userArray['nickname']) ? $userArray['nickname'] : '匿名';
$user->gender = (int)$userArray['gender'];
$user->address_id = array_key_exists('address_id', $userArray) ? (int)$userArray['address_id'] : 0;
return $user;
}
/**
* 个人信息
* @return string
*/
public function actionAjaxProfile()
{
$e = new stdClass();
$e->success = false;
$e->user = null;
if ($this->request->isGet) {
$e->success = true;
$userId = $this->getUserId();
if ($userId == 0) {
return $e;
}
$e->user = $this->buildAjaxProfileResult($userId);
}
return $e;
}
/**
* 构造个人信息返回的AJAX结果
* @param $userModel
* @return stdClass
*/
private function buildAjaxProfileResult($userId)
{
/**
* 构造user的共用信息
*/
$user = $this->buildUserResult($userId);
// 获取地址
$addressModel = AddressModel::findOne($user->address_id);
if ($addressModel) {
$user->address = $addressModel->address;
}
return $user;
}
/**
* 保存个人信息
* @return string
*/
public function actionAjaxSaveProfile()
{
$e = new stdClass();
$e->success = false;
$userModel = $this->getUserModel();
if ($this->request->isPost && $userModel) {
$gender = (int)$this->request->post('gender');
$userModel->gender = $gender;
if ($userModel->save()) {
$e->success = true;
$e->user = $this->buildAjaxProfileResult($userModel->id);
}
}
return $e;
}
/**
* 更新用户地址
* @return stdClass
* @throws Exception
*/
public function actionUpdateUserAddress()
{
AppLog::DEBUG('actionUpdateUserAddress(): 更新用户地址');
$e = new stdClass();
$e->success = false;
if (false == $this->request->isPost) {
$e->error = '无效请求';
return $e;
}
$address = $this->request->post('address');
$longitude = (float)$this->request->post('longitude');
$latitude = (float)$this->request->post('latitude');
$clientUserId = $this->getClientUserId();
$clientUser = ClientUserModel::findOne($clientUserId);
if (false == $clientUser) {
$e->error = '无效用户';
return $e;
}
if (empty($address )) {
$e->error = '地址为空';
return $e;
}
if (!Utils::isValidCoordinate($latitude, $longitude)) {
$e->error = '无效地址';
return $e;
}
$addressModel = AddressModel::findOne($clientUser->address_id);
if ($addressModel) { // 更新地址
$addressModel->address = $address;
$addressModel->longitude = $longitude;
$addressModel->latitude = $latitude;
if (false == $addressModel->save()) {
throw new Exception(implode("\r\n", $addressModel->getFirstErrors()));
}
AppLog::DEBUG('actionUpdateUserAddress(): 用户地址已存在, 更新成功[' . $clientUserId . ']=>' . $address . ' | address_id=' . $clientUser->address_id);
} else { // 创建地址
$newAddressModel = new AddressModel([
'address' => $address,
'longitude' => $longitude,
'latitude' => $latitude,
'type' => AddressModel::TYPE_LBS,
]);
if (false == $newAddressModel->save()) {
throw new Exception(implode("\r\n", $newAddressModel->getFirstErrors()));
}
// 保存地址id到终端用户对象中
$clientUser->address_id = $newAddressModel->id;
if (false == $clientUser->save()) {
throw new Exception(implode("\r\n", $clientUser->getFirstErrors()));
}
AppLog::DEBUG('actionUpdateUserAddress(): 新建用户地址成功[' . $clientUserId . ']=>' . $address . ' | address_id=' . $newAddressModel->id);
}
$e->success = true;
return $e;
}
/**
* 我的设备收藏夹
* @return string
*/
public function actionAjaxFav()
{
$e = new stdClass();
$e->success = false;
$e->devices = [];
if ($this->request->isGet) {
$offset = (int)$this->request->get('offset');
$limit = (int)$this->request->get('limit');
$userId = $this->getUserId();
if ($userId == 0) {
return $e;
}
$statusDoing = RepairOrderStatus::STATUS_WAIT_PICK . "," . RepairOrderStatus::STATUS_WAIT_DOOR . "," . RepairOrderStatus::STATUS_WAIT_PRICE
. "," . RepairOrderStatus::STATUS_CONFIRM_PRICE . "," . RepairOrderStatus::STATUS_WAIT_ACCEPT . "," . RepairOrderStatus::STATUS_WAIT_PAY;
$q = new Query();
$q->select(["user_device_fav.*"]);
$q->from('user_device_fav');
$q->where(['user_id'=> $userId, 'fav_device_type' => UserDeviceFavModel::DeviceTypeUser]); // 仅读取收藏夹里面的用户设备, 游客设备不再收藏
$q->orderBy('user_device_fav.updated_at DESC');
$rows = $q->offset($offset)->limit($limit)->all();
// 按收藏设备类型准备好ID,做IN查询,避免大数据量多关联查询
$userDevIds = [];
foreach ($rows as $row) {
$userDevIds[] = $row['fav_device_id'];
}
// 查询用户设备资料
$userDevs = [];
if (!empty($userDevIds)) {
$q = new Query();
$q->select(['user_device.*', 'device.device_name AS device_name',
'brand.id AS brand_id', 'brand.chinese_name AS brand_name',
'device_cat.id AS device_cat_id', 'device_cat.name AS device_cat_name',
'device_img.path AS device_img', 'device_cat.parent_id AS parent_cat_id']);
$q->from('user_device');
$q->leftJoin('device', 'user_device.device_id = device.id');
$q->leftJoin('device_cat', 'device.device_cat_id = device_cat.id');
$q->leftJoin('model', 'device.model_id = model.id');
$q->leftJoin('brand', 'model.brand_id = brand.id');
$q->leftJoin('device_img', "`device_img`.`device_id` = `user_device`.`device_id`");
$userDevRows = $q->where(['user_device.id' => $userDevIds])->all();
foreach ($userDevRows as $userDevRow) {
// 覆盖设备,这里是空的
if (!empty($userDevRow['id'])) {
$userDevs[$userDevRow['id']] = $userDevRow;
}
}
}
// 读取设备分类图片数组
$deviceCatImgMap = DeviceCatRepository::loadDeviceCatImages();
// 获取最终结果
$devices = [];
foreach ($rows as $row) {
$s = new stdClass();
$s->id = $row['id'];
$s->has_order = 0;
$s->order_id = 0;
$s->order_status = 0;
$s->fav_device_type = $row['fav_device_type'];
$s->update_time = $row['updated_at'] ? date('Y年m月d日', $row['updated_at']) : '';
$deviceOrderQuery = RepairOrderModel::find();
$deviceOrderQuery->where(['repair_device_id'=>$row['fav_device_id'], 'repair_device_type'=>$row['fav_device_type'],'is_system_delete'=>0]);
$deviceOrderQuery->andWhere("status in ({$statusDoing})");
$doingOrder = $deviceOrderQuery->asArray()->one();
if ($doingOrder) {
$s->has_order = 1;
//$s->order_id = $doingOrder['id'];
$s->order_id = $doingOrder['uuid'];
$s->order_status = $doingOrder["status"];
$s->is_order_owner = ($userId == $doingOrder["user_id"]) ? true : false; // 判断是否订单拥有者
}
// 获取历史维修次数
$orderQuery = RepairOrderModel::find();
$orderQuery->where(['repair_device_id'=>$row['fav_device_id'], 'repair_device_type'=>$row['fav_device_type'],'is_system_delete'=>0]);
// 展示全部订单
//$statusValues = [RepairOrderStatus::STATUS_WAIT_RATE, RepairOrderStatus::STATUS_FINISH];
//$orderQuery->andFilterWhere(['status' => $statusValues]);
$s->history_repair_num = $orderQuery->count();
$s->device_name = '';
$s->device_img = '';
$s->brand_id = '';
$s->device_cat_id = '';
$s->brand_name = '';
$s->device_cat_name = '';
$s->parent_cat_id = '';
// 用户设备
if ($row['fav_device_type'] == UserDeviceFavModel::DeviceTypeUser && isset($userDevs[$row['fav_device_id']])) {
$dev = $userDevs[$row['fav_device_id']];
$s->device_name = $dev['device_name'];
$s->fav_device_id = $dev['uuid'];
$deviceImg = isset($deviceCatImgMap[$dev['device_cat_id']])?$deviceCatImgMap[$dev['device_cat_id']]:'';
$s->device_img = empty($dev['device_img']) ? $deviceImg : ImageManager::getUrl($dev['device_img'], ImageManager::$STYLE_90);
$s->brand_id = $dev['brand_id'];
$s->device_cat_id = $dev['device_cat_id'];
$s->brand_name = $dev['brand_name'];
$s->device_cat_name = $dev['device_cat_name'];
$s->parent_cat_id = $dev['parent_cat_id'];
}
$devices[] = $s;
}
if (sizeof($devices)) {
$e->hasMore = true;
$e->devices = $devices;
} else {
$e->hasMore = false;
}
$e->success = true;
}
return $e;
}
/**
* 删除指定的收藏设备
* @return string
* @throws Exception
*/
public function actionAjaxRemoveFav()
{
$e = new stdClass();
$e->success = false;
$e->error = false;
if (false == $this->request->isPost) {
$e->error = '无效请求';
return $e;
}
$favId = (int)$this->request->post('id');
$userId = $this->getUserId();
if ($userId == 0) {
$e->error = '无效用户ID';
return $e;
}
$userDeviceFavModel = UserDeviceFavModel::findOne($favId);
if ($userDeviceFavModel) {
// 只能删除自己的收藏设备
if ($userDeviceFavModel->user_id != $userId) {
$e->error = '只能删除自己的收藏设备';
return $e;
}
$success = $userDeviceFavModel->delete();
if (!$success) {
$e->error = '删除收藏设备失败';
return $e;
}
} else {
$e->error = '收藏设备不存在';
return $e;
}
$e->success = true;
return $e;
}
/**
* @return string
*/
public function actionAjaxCoupons()
{
$e = new stdClass();
$e->success = false;
$e->coupons = [];
if (false == $this->request->isGet) {
$e->error = '无效请求';
return $e;
}
$status = (string)$this->request->get('status');
$coupons = $this->buildCouponsResult($status);
if (sizeof($coupons)) {
$e->hasMore = true;
$e->coupons = $coupons;
} else {
$e->hasMore = false;
}
$e->success = true;
return $e;
}
/**
* @return array
*/
private function buildCouponsResult($status)
{
$userId = $this->getUserId();
if ($userId == 0) {
return false;
}
$offset = (int)$this->request->get('offset');
$limit = (int)$this->request->get('limit');
$tt = time();
$q = UserCouponModel::find()
->select(["user_coupon.*", "coupon_rule.remark"])
->where(['user_id' => $userId])
->leftJoin("coupon_rule", "coupon_rule.id = user_coupon.coupon_rule_id");
$q->offset($offset)->limit($limit)->orderBy("created_at desc");
if ($status == 'available') { // 仅显示可用优惠券
$q->andWhere(['is_use' => UserCouponModel::COUPON_NOT_USED]);
$q->andWhere(['or', ['>=', 'expired_at', $tt], ['expired_at' => 0]]);
} elseif ($status == 'used') { // 仅显示已使用优惠券
$q->andWhere(['is_use' => UserCouponModel::COUPON_USED]);
} elseif ($status == 'expired') { // 仅显示可用优惠券
$q->andWhere(['is_use' => UserCouponModel::COUPON_NOT_USED]);
$q->andWhere(['>', 'expired_at', 0]);
$q->andWhere(['<', 'expired_at', $tt]);
}
$coupons = [];
$couponsArr = $q->asArray()->all();
foreach ($couponsArr as $coupon) {
$c = new stdClass();
$c->coupon_name = $coupon['coupon_name'];
$c->amount = (float)$coupon['amount'];
$c->min_consume_amount = (float)$coupon['min_consume_amount'];
$c->is_use = (bool)$coupon['is_use'];
$c->is_expire = $coupon['expired_at'] ? ($coupon['expired_at'] < $tt) : false;
$c->started_at = date('Y.m.d', $coupon['started_at']);
$c->created_at = date('Y.m.d', $coupon['created_at']);
$c->expired_at = $coupon['expired_at'] ? date('Y.m.d', $coupon['expired_at']) : '永久有效';
$c->rule_remark = $coupon['remark']? $coupon['remark']:'';
$coupons[] = $c;
}
return $coupons;
}
/**
* 获取小程序底部TAB栏的徽章计数器
* @return string
*/
public function actionGetBadgeCounter()
{
$e = new stdClass();
$e->success = false;
$e->order_badge_num = 0; // 订单tab栏-小红点提示数量(待处理订单数量)
$e->home_badge_num = 0; // 个人中心tab栏-小红点消息提示数量(待领取红包数量 + 未使用优惠券数量)
$userId = $this->getUserId();
$clientUserId = $this->getClientUserId();
if (empty($userId) || empty($clientUserId)) {
return $e;
}
// 订单tab栏-小红点提示数量(待处理订单数量)
$doingOrderCount = RepairOrderModel::find()->where("user_id=" . $userId . " and " .OrderSqlHelper::SQL_WHERE_TODO)->count();
$e->order_badge_num = $doingOrderCount;
// 有效优惠券数
$effectCoupons = UserCouponModel::getEffectCoupons($userId);
$effect_coupon_num = $effectCoupons ? $effectCoupons->count() : 0;
// 未领取红包个数
$clientUserId = empty($clientUserId) ? 0 : $clientUserId;
$userId = empty($userId) ? 0 : $userId;
$sql = Redpacks::waitReceiveSql($userId, 0, $clientUserId, 0, 0, false);
$unopen_redpacks_count = MarketingRedpacksModel::findBySql($sql)->count();
// 个人中心tab栏-小红点消息提示数量(待领取红包数量 + 未使用优惠券数量)
$e->home_badge_num = $effect_coupon_num + $unopen_redpacks_count;
$e->success = true;
return $e;
}
}