feat: hồ sơ khách (ngày sinh, tỉnh/phường theo mã), gộp menu + nút tắt, thông báo theo uuid

- PUT v1/client/update: gender theo enum ClientGender (0 Nam/1 Nữ), thêm
  birthday (cột mới), province_code/ward_code validate theo bảng provinces/wards
  (phường phải thuộc tỉnh). Migration nạp dữ liệu hành chính 2025 từ
  province_ward_import.sql (chỉ bảng trống), API GET v1/provinces[/{code}/wards].
- CustomerObserver/OrderObserver log giá trị cũ bằng getRawOriginal: getOriginal
  trả enum object, nối chuỗi gây 500 khi khách đổi giới tính.
- ClientResource: các cờ trả boolean, CCCD chỉ trả cccd_updated (không lộ ảnh/số).
- GET v1/setting/menu trả cả items + quick_links, bỏ v1/setting/quick-links.
- Thông báo admin/khách tra theo uuid thay vì id tự tăng.
- Chặn gửi template marketing cho khách đã tắt nhận email marketing.
- Xoá ProvinceWardSeeder và Customer::$updatable không dùng.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
baodev0
2026-10-13 16:03:18 +07:00
co-authored by Claude Opus 5.5
parent 12d5b4951c
commit bf78f3b810
30 changed files with 461 additions and 183 deletions
@@ -169,14 +169,19 @@ final class MailCampaignController extends Controller
$campaign = $this->draftCampaign($data);
$marketingOnly = $campaign->isMarketing();
$recipients = $data['recipient_type'] === 'all'
? $this->allCustomerRecipients()
: $this->selectedRecipients($data['uuids'] ?? [], $data['emails'] ?? []);
? $this->allCustomerRecipients($marketingOnly)
: $this->selectedRecipients($data['uuids'] ?? [], $data['emails'] ?? [], $marketingOnly);
$optedOut = $recipients['opted_out'];
$recipients = $recipients['recipients'];
if ($recipients === []) {
return response()->json([
'error' => true,
'message' => 'Không có người nhận hợp lệ để gửi.',
'message' => $optedOut > 0
? "Không có người nhận hợp lệ: {$optedOut} khách hàng đã tắt nhận email marketing."
: 'Không có người nhận hợp lệ để gửi.',
], 422);
}
@@ -200,7 +205,8 @@ final class MailCampaignController extends Controller
return response()->json([
'error' => false,
'message' => "Đã đưa {$campaign->total_recipients} email vào hàng đợi gửi.",
'message' => "Đã đưa {$campaign->total_recipients} email vào hàng đợi gửi."
. ($optedOut > 0 ? " Bỏ qua {$optedOut} khách hàng đã tắt nhận email marketing." : ''),
'data' => $this->mapCampaign($campaign),
]);
}
@@ -258,42 +264,62 @@ final class MailCampaignController extends Controller
}
/**
* @return array<string, int>
* @return array{recipients: array<string, int>, opted_out: int}
*/
private function allCustomerRecipients(): array
private function allCustomerRecipients(bool $marketingOnly): array
{
return Customer::query()
$customers = Customer::query()
->whereNotNull('email')
->where('email', '!=', '')
->pluck('id', 'email')
->all();
->get(['id', 'email', 'email_marketing']);
[$accepted, $optedOut] = $customers->partition(
fn (Customer $customer) => !$marketingOnly || $customer->acceptsMarketingEmail()
);
return [
'recipients' => $accepted->pluck('id', 'email')->all(),
'opted_out' => $optedOut->count(),
];
}
/**
* @param array<int, string> $uuids
* @param array<int, string> $emails
* @return array<string, int|null>
* @return array{recipients: array<string, int|null>, opted_out: int}
*/
private function selectedRecipients(array $uuids, array $emails): array
private function selectedRecipients(array $uuids, array $emails, bool $marketingOnly): array
{
$emails = array_values(array_unique(array_map(fn ($email) => mb_strtolower(trim($email)), $emails)));
$customers = Customer::query()
->where(fn ($q) => $q->whereIn('uuid', $uuids)->orWhereIn('email', $emails))
->whereNotNull('email')
->get(['id', 'email', 'uuid']);
->get(['id', 'email', 'uuid', 'email_marketing']);
$recipients = [];
$optedOutEmails = [];
foreach ($customers as $customer) {
if (in_array($customer->uuid, $uuids, true) || in_array(mb_strtolower($customer->email), $emails, true)) {
$recipients[mb_strtolower($customer->email)] = $customer->id;
$email = mb_strtolower($customer->email);
if (!in_array($customer->uuid, $uuids, true) && !in_array($email, $emails, true)) {
continue;
}
if ($marketingOnly && !$customer->acceptsMarketingEmail()) {
$optedOutEmails[$email] = true;
continue;
}
$recipients[$email] = $customer->id;
}
foreach ($emails as $email) {
$recipients[$email] ??= null;
if (!isset($optedOutEmails[$email])) {
$recipients[$email] ??= null;
}
}
return array_filter($recipients, fn ($id, $email) => filter_var($email, FILTER_VALIDATE_EMAIL), ARRAY_FILTER_USE_BOTH);
return [
'recipients' => array_filter($recipients, fn ($id, $email) => filter_var($email, FILTER_VALIDATE_EMAIL), ARRAY_FILTER_USE_BOTH),
'opted_out' => count($optedOutEmails),
];
}
private function mapCampaign(MailCampaign $campaign): array
@@ -0,0 +1,27 @@
<?php
namespace App\Http\Controllers\Api\Client;
use App\Http\Controllers\Controller;
use App\Models\Province;
use App\Models\Ward;
use Illuminate\Http\JsonResponse;
class AdministrativeDivisionController extends Controller
{
public function provinces(): JsonResponse
{
return response()->json([
'error' => false,
'data' => Province::query()->orderBy('code')->get(['code', 'name', 'full_name']),
]);
}
public function wards(string $province): JsonResponse
{
return response()->json([
'error' => false,
'data' => Ward::query()->where('province_code', $province)->orderBy('name')->get(['code', 'name', 'full_name']),
]);
}
}
@@ -50,23 +50,25 @@ class ClientController extends Controller
* @OA\Property(property="customer", type="object",
* @OA\Property(property="fullname", type="string", example="Nguyen Van A"),
* @OA\Property(property="email", type="string", example="client@example.com"),
* @OA\Property(property="phone", type="string", example="0987654321"),
* @OA\Property(property="phone", type="string", example="*******321", description="Chỉ hiển thị 3 số cuối"),
* @OA\Property(property="address", type="string", example="123 Street"),
* @OA\Property(property="city", type="string", example="Hanoi"),
* @OA\Property(property="ward", type="string", example="Ward 1"),
* @OA\Property(property="province", type="string", example="Hanoi"),
* @OA\Property(property="gender", type="string", example="Nam"),
* @OA\Property(property="ward", type="string", example="Phường Bình Trị Đông"),
* @OA\Property(property="ward_code", type="string", nullable=true, example="27460"),
* @OA\Property(property="province", type="string", example="Hồ Chí Minh"),
* @OA\Property(property="province_code", type="string", nullable=true, example="79"),
* @OA\Property(property="gender", type="integer", nullable=true, example=0, description="0 = Nam, 1 = Nữ"),
* @OA\Property(property="gender_label", type="string", example="Nam"),
* @OA\Property(property="birthday", type="string", format="date", nullable=true, example="1995-06-20"),
* @OA\Property(property="date", type="string", format="date-time", example="2024-01-01 12:00:00"),
* @OA\Property(property="company", type="string", example="Company Ltd"),
* @OA\Property(property="avatar", type="string", example="/uploads/avatar.jpg"),
* @OA\Property(property="cmnd_after", type="string", example="cmnd_back.jpg"),
* @OA\Property(property="cmnd_before", type="string", example="cmnd_front.jpg"),
* @OA\Property(property="cmnd", type="string", example="123456789"),
* @OA\Property(property="cccd_updated", type="boolean", example=true),
* @OA\Property(property="fb_link", type="string", nullable=true),
* @OA\Property(property="active_2fa", type="integer", example=0),
* @OA\Property(property="off_mail_marketing", type="integer", example=0),
* @OA\Property(property="is_recharge_zalo", type="integer", example=0),
* @OA\Property(property="is_verify_telegram", type="integer", example=0)
* @OA\Property(property="active_2fa", type="boolean", example=false),
* @OA\Property(property="off_mail_marketing", type="boolean", example=false),
* @OA\Property(property="is_recharge_zalo", type="boolean", example=false),
* @OA\Property(property="is_verify_telegram", type="boolean", example=false)
* ),
* @OA\Property(property="credit", type="object",
* @OA\Property(property="credit", type="number", example=1000000),
@@ -5,8 +5,6 @@ namespace App\Http\Controllers\Api\Client\Concerns;
use App\Http\Requests\Api\Client\ClientUpdateCccdRequest;
use App\Http\Requests\Api\Client\ClientUpdateRequest;
use App\Http\Resources\Api\Client\ClientResource;
use App\Models\Customer;
use Illuminate\Support\Facades\Storage;
trait ManagesClientProfile
{
@@ -37,7 +35,7 @@ trait ManagesClientProfile
public function updateCccd(ClientUpdateCccdRequest $request)
{
// Disk private: ảnh chỉ đọc được qua route signed `api.client.cccd`.
// Disk private: phía client chỉ nhận trạng thái đã cập nhật, không nhận đường dẫn ảnh.
$frontUrl = $request->file('cmnd_before')->store('cccd', 'local');
$backUrl = $request->file('cmnd_after')->store('cccd', 'local');
@@ -69,26 +67,4 @@ trait ManagesClientProfile
]);
}
/**
* Trả ảnh CCCD từ disk private. Route yêu cầu chữ ký (signed:relative) nên không cần
* Bearer — chữ ký do ClientResource cấp cho đúng chủ tài khoản, hết hạn sau 60 phút.
*/
public function cccdImage(int $customer, string $side)
{
$path = Customer::findOrFail($customer)->{$side === 'front' ? 'front_identity_number' : 'back_identity_number'};
abort_unless($path && str_starts_with($path, 'cccd/') && Storage::disk('local')->exists($path), 404);
$mime = match (strtolower(pathinfo($path, PATHINFO_EXTENSION))) {
'png' => 'image/png',
'webp' => 'image/webp',
default => 'image/jpeg',
};
return Storage::disk('local')->response($path, "cccd-{$side}", [
'Content-Type' => $mime,
'Content-Disposition' => "inline; filename=\"cccd-{$side}\"",
'Cache-Control' => 'private, no-store',
]);
}
}
@@ -58,15 +58,9 @@ class NotificationController extends Controller
]);
}
public function show(Request $request, string $recipientType, int $id): JsonResponse
public function show(Request $request, string $recipientType, string $uuid): JsonResponse
{
$recipient = $this->resolveRecipient($recipientType);
$notification = Notification::query()
->where('recipient_type', $recipientType)
->where('recipient_id', $recipient->id)
->whereKey($id)
->first();
$notification = $this->findOwned($recipientType, $uuid);
if (!$notification) {
return response()->json(['error' => true, 'message' => 'Notification not found'], 404);
@@ -75,15 +69,9 @@ class NotificationController extends Controller
return response()->json(['error' => false, 'data' => $notification]);
}
public function markRead(Request $request, string $recipientType, int $id): JsonResponse
public function markRead(Request $request, string $recipientType, string $uuid): JsonResponse
{
$recipient = $this->resolveRecipient($recipientType);
$notification = Notification::query()
->where('recipient_type', $recipientType)
->where('recipient_id', $recipient->id)
->whereKey($id)
->first();
$notification = $this->findOwned($recipientType, $uuid);
if (!$notification) {
return response()->json(['error' => true, 'message' => 'Notification not found'], 404);
@@ -113,6 +101,15 @@ class NotificationController extends Controller
return response()->json(['error' => false, 'message' => 'Marked as read']);
}
private function findOwned(string $recipientType, string $uuid): ?Notification
{
return Notification::query()
->where('recipient_type', $recipientType)
->where('recipient_id', $this->resolveRecipient($recipientType)->id)
->where('uuid', $uuid)
->first();
}
private function resolveRecipient(string $recipientType)
{
return match ($recipientType) {
@@ -70,15 +70,10 @@ class SettingController extends Controller
{
return response()->json([
'error' => false,
'data' => ClientMenu::items(),
]);
}
public function getQuickLinks(): \Illuminate\Http\JsonResponse
{
return response()->json([
'error' => false,
'data' => ClientQuickLinks::items(),
'data' => [
'items' => ClientMenu::items(),
'quick_links' => ClientQuickLinks::items(),
],
]);
}
@@ -2,7 +2,9 @@
namespace App\Http\Requests\Api\Client;
use App\Enums\Client\ClientGender;
use Illuminate\Foundation\Http\FormRequest;
use Illuminate\Validation\Rule;
class ClientUpdateRequest extends FormRequest
{
@@ -15,12 +17,18 @@ class ClientUpdateRequest extends FormRequest
{
return [
'fullname' => 'required|string|max:255',
'phone' => 'required|string|max:20',
'phone' => 'sometimes|required|string|max:20',
'company' => 'nullable|string|max:255',
'address' => 'nullable|string|max:500',
'province_code' => 'nullable|string|max:10',
'ward_code' => 'nullable|string|max:10',
'gender' => 'nullable|in:1,2,3',
'province_code' => ['nullable', 'string', Rule::exists('provinces', 'code')],
'ward_code' => [
'nullable',
'string',
'required_with:province_code',
Rule::exists('wards', 'code')->where('province_code', $this->input('province_code')),
],
'gender' => ['nullable', Rule::enum(ClientGender::class)],
'birthday' => ['nullable', 'date_format:Y-m-d', 'before_or_equal:today', 'after:1900-01-01'],
];
}
@@ -29,6 +37,10 @@ class ClientUpdateRequest extends FormRequest
return [
'fullname.required' => 'Họ tên là bắt buộc',
'phone.required' => 'Số điện thoại là bắt buộc',
'province_code.exists' => 'Tỉnh/Thành phố không hợp lệ',
'ward_code.required_with' => 'Vui lòng chọn Phường/Xã',
'ward_code.exists' => 'Phường/Xã không thuộc Tỉnh/Thành phố đã chọn',
'birthday.before_or_equal' => 'Ngày sinh không được ở tương lai',
];
}
}
+1 -1
View File
@@ -33,7 +33,7 @@ class CreateCustomerRequest extends FormRequest
'state' => 'nullable',
'postcode' => 'nullable',
'country' => 'nullable',
'email_marketing' => 'nullable',
'email_marketing' => 'nullable|boolean',
'note' => 'nullable|string',
];
}
@@ -19,6 +19,8 @@ class CustomerResource extends JsonResource
'note' => $this->note,
'status' => (int) $this->status,
'total' => (int) $this->total,
'email_marketing' => (bool) $this->email_marketing,
'receive_deposit' => (bool) $this->receive_deposit,
'created_at' => $this->created_at,
];
}
@@ -5,8 +5,6 @@ namespace App\Http\Resources\Api\Client;
use App\Services\Api\ServiceClient\ServiceClientService;
use Illuminate\Http\Request;
use Illuminate\Http\Resources\Json\JsonResource;
use Illuminate\Support\Facades\URL;
use Illuminate\Support\Str;
class ClientResource extends JsonResource
{
@@ -25,25 +23,31 @@ class ClientResource extends JsonResource
'customer' => [
'fullname' => $this->fullname,
'email' => $this->email,
'phone' => $this->phone,
'phone' => $this->maskedPhone(),
'address' => $this->address,
'city' => $this->city,
'ward' => $this->ward->name ?? '',
'ward_code' => $this->ward_code,
'province' => $this->province->name ?? '',
'gender' => $this->gender_label,
'province_code' => $this->province_code,
'gender' => $this->gender?->value,
'gender_label' => $this->gender_label,
'birthday' => $this->birthday?->format('Y-m-d'),
'date' => $this->created_at ? $this->created_at->format('Y-m-d H:i:s') : null,
'company' => $this->company ?? '',
'avatar' => $this->avatar,
'cmnd_before' => $this->cccdUrl('front', $this->front_identity_number),
'cmnd_after' => $this->cccdUrl('back', $this->back_identity_number),
'cmnd' => $this->identity_number ? Str::mask($this->identity_number, '*', 0, -4) : null,
'cccd_updated' => (bool) (
$this->identity_number
&& $this->front_identity_number
&& $this->back_identity_number
),
'fb_link' => null,
'active_2fa' => (int) $this->two_factor_enabled,
'off_mail_marketing' => $this->off_mail_marketing,
'active_2fa' => (bool) $this->two_factor_enabled,
'off_mail_marketing' => (bool) $this->off_mail_marketing,
'email_marketing' => (bool) $this->email_marketing,
'receive_deposit' => (bool) $this->receive_deposit,
'is_recharge_zalo' => 0,
'is_verify_telegram' => 0,
'is_recharge_zalo' => false,
'is_verify_telegram' => false,
],
'credit' => [
'credit' => $this->credit,
@@ -60,17 +64,14 @@ class ClientResource extends JsonResource
];
}
/**
* Ảnh CCCD trên disk private → URL ký tương đối (/v1/client/cccd/...), hết hạn 60 phút.
*/
private function cccdUrl(string $side, ?string $path): string
private function maskedPhone(): ?string
{
if (!$path) {
return '';
if (!$this->phone) {
return null;
}
// Giá trị import từ portal cũ (/uploads/... trên host cũ) cũng chỉ trả URL ký — không lộ đường dẫn gốc;
// route trả 404 cho chúng vì file không có trên disk private. Vẫn khác rỗng để hasCccd giữ nguyên hành vi.
return URL::temporarySignedRoute('api.client.cccd', now()->addHour(), ['customer' => $this->id, 'side' => $side], false);
$visibleDigits = mb_substr($this->phone, -3);
return str_repeat('*', max(0, mb_strlen($this->phone) - mb_strlen($visibleDigits))) . $visibleDigits;
}
}