v7.0.0 release
This commit is contained in:
1 parent
0e7fa04b03
commit
c4ea9a6cd1
3582 files changed
+626189
-160151
No files matched your search
+59
@@ -0,0 +1,59 @@
|
||||
<?php
|
||||
|
||||
namespace Modules\Sirsoft\Ecommerce\Http\Controllers\Admin;
|
||||
|
||||
use App\Helpers\ResponseHelper;
|
||||
use App\Http\Controllers\Api\Base\AdminBaseController;
|
||||
use App\Models\User;
|
||||
use Exception;
|
||||
use Illuminate\Http\JsonResponse;
|
||||
use Illuminate\Support\Facades\Log;
|
||||
use Modules\Sirsoft\Ecommerce\Http\Requests\Admin\UpdateAdminUserCurrencyRequest;
|
||||
use Modules\Sirsoft\Ecommerce\Services\UserCurrencyService;
|
||||
|
||||
/**
|
||||
* 관리자 회원 결제 통화 컨트롤러 (A3)
|
||||
*
|
||||
* 관리자가 특정 회원의 결제 통화를 변경합니다. permission:admin,sirsoft-ecommerce.user-currency.manage
|
||||
* 로 가드되며, 변경 시 활동 로그 훅을 발화합니다.
|
||||
*/
|
||||
class AdminUserCurrencyController extends AdminBaseController
|
||||
{
|
||||
public function __construct(
|
||||
private UserCurrencyService $userCurrencyService
|
||||
) {}
|
||||
|
||||
/**
|
||||
* 특정 회원의 결제 통화를 변경합니다.
|
||||
*
|
||||
* 회원은 UUID 라우트 모델 바인딩으로 주입됩니다(관리자 회원 URL 규약, getRouteKeyName='uuid').
|
||||
*
|
||||
* @param UpdateAdminUserCurrencyRequest $request 검증된 요청(등록 통화만 허용)
|
||||
* @param User $user 대상 회원(UUID 바인딩)
|
||||
* @return JsonResponse 변경 결과 JSON 응답
|
||||
*/
|
||||
public function update(UpdateAdminUserCurrencyRequest $request, User $user): JsonResponse
|
||||
{
|
||||
try {
|
||||
$currency = $request->validated('currency');
|
||||
|
||||
// 통화 저장 + 활동 로그 훅을 서비스가 한 단위로 처리(컨트롤러 모델 직접 접근 회피)
|
||||
$this->userCurrencyService->changeUserCurrencyByAdmin($user->id, $currency);
|
||||
|
||||
return ResponseHelper::success('sirsoft-ecommerce::messages.user_currency.updated', [
|
||||
'preferred_currency' => $currency,
|
||||
]);
|
||||
} catch (Exception $e) {
|
||||
Log::error('Admin user currency update failed', [
|
||||
'message' => $e->getMessage(),
|
||||
'target_user_id' => $user->id,
|
||||
]);
|
||||
|
||||
return ResponseHelper::moduleError(
|
||||
'sirsoft-ecommerce',
|
||||
'messages.user_currency.update_failed',
|
||||
500
|
||||
);
|
||||
}
|
||||
}
|
||||
}
|
||||
+59
@@ -0,0 +1,59 @@
|
||||
<?php
|
||||
|
||||
namespace Modules\Sirsoft\Ecommerce\Http\Controllers\Admin;
|
||||
|
||||
use App\Helpers\ResponseHelper;
|
||||
use App\Http\Controllers\Api\Base\AdminBaseController;
|
||||
use App\Models\User;
|
||||
use Exception;
|
||||
use Illuminate\Http\JsonResponse;
|
||||
use Illuminate\Support\Facades\Log;
|
||||
use Modules\Sirsoft\Ecommerce\Http\Requests\Admin\UpdateAdminUserShippingCountryRequest;
|
||||
use Modules\Sirsoft\Ecommerce\Services\UserShippingCountryService;
|
||||
|
||||
/**
|
||||
* 관리자 회원 배송국가 컨트롤러 (MP08 후속)
|
||||
*
|
||||
* 관리자가 특정 회원의 배송국가를 변경합니다. permission:admin,sirsoft-ecommerce.user-shipping-country.manage
|
||||
* 로 가드되며, 변경 시 활동 로그 훅을 발화합니다.
|
||||
*/
|
||||
class AdminUserShippingCountryController extends AdminBaseController
|
||||
{
|
||||
public function __construct(
|
||||
private UserShippingCountryService $service
|
||||
) {}
|
||||
|
||||
/**
|
||||
* 특정 회원의 배송국가를 변경합니다.
|
||||
*
|
||||
* 회원은 UUID 라우트 모델 바인딩으로 주입됩니다(관리자 회원 URL 규약, getRouteKeyName='uuid').
|
||||
*
|
||||
* @param UpdateAdminUserShippingCountryRequest $request 검증된 요청(활성 국가만 허용)
|
||||
* @param User $user 대상 회원(UUID 바인딩)
|
||||
* @return JsonResponse 변경 결과 JSON 응답
|
||||
*/
|
||||
public function update(UpdateAdminUserShippingCountryRequest $request, User $user): JsonResponse
|
||||
{
|
||||
try {
|
||||
$country = $request->validated('shipping_country');
|
||||
|
||||
// 배송국가 저장 + 활동 로그 훅을 서비스가 한 단위로 처리(컨트롤러 모델 직접 접근 회피)
|
||||
$this->service->changeUserShippingCountryByAdmin($user->id, $country);
|
||||
|
||||
return ResponseHelper::success('sirsoft-ecommerce::messages.user_shipping_country.updated', [
|
||||
'preferred_shipping_country' => strtoupper($country),
|
||||
]);
|
||||
} catch (Exception $e) {
|
||||
Log::error('Admin user shipping country update failed', [
|
||||
'message' => $e->getMessage(),
|
||||
'target_user_id' => $user->id,
|
||||
]);
|
||||
|
||||
return ResponseHelper::moduleError(
|
||||
'sirsoft-ecommerce',
|
||||
'messages.user_shipping_country.update_failed',
|
||||
500
|
||||
);
|
||||
}
|
||||
}
|
||||
}
|
||||
+79
-16
@@ -8,10 +8,12 @@ use Illuminate\Http\JsonResponse;
|
||||
use Modules\Sirsoft\Ecommerce\Http\Requests\Admin\BulkUpdateCouponStatusRequest;
|
||||
use Modules\Sirsoft\Ecommerce\Http\Requests\Admin\CouponIssuesListRequest;
|
||||
use Modules\Sirsoft\Ecommerce\Http\Requests\Admin\CouponListRequest;
|
||||
use Modules\Sirsoft\Ecommerce\Http\Requests\Admin\IssueCouponDirectRequest;
|
||||
use Modules\Sirsoft\Ecommerce\Http\Requests\Admin\StoreCouponRequest;
|
||||
use Modules\Sirsoft\Ecommerce\Http\Requests\Admin\UpdateCouponRequest;
|
||||
use Modules\Sirsoft\Ecommerce\Http\Resources\CouponCollection;
|
||||
use Modules\Sirsoft\Ecommerce\Http\Resources\CouponIssueCollection;
|
||||
use Modules\Sirsoft\Ecommerce\Http\Resources\CouponIssueResource;
|
||||
use Modules\Sirsoft\Ecommerce\Http\Resources\CouponResource;
|
||||
use Modules\Sirsoft\Ecommerce\Services\CouponService;
|
||||
|
||||
@@ -27,8 +29,8 @@ class CouponController extends AdminBaseController
|
||||
/**
|
||||
* 쿠폰 목록 조회
|
||||
*
|
||||
* @param CouponListRequest $request
|
||||
* @return JsonResponse
|
||||
* @param CouponListRequest $request 목록 검색/필터 요청
|
||||
* @return JsonResponse 쿠폰 목록 응답
|
||||
*/
|
||||
public function index(CouponListRequest $request): JsonResponse
|
||||
{
|
||||
@@ -47,8 +49,8 @@ class CouponController extends AdminBaseController
|
||||
/**
|
||||
* 쿠폰 생성
|
||||
*
|
||||
* @param StoreCouponRequest $request
|
||||
* @return JsonResponse
|
||||
* @param StoreCouponRequest $request 쿠폰 생성 요청
|
||||
* @return JsonResponse 생성된 쿠폰 응답
|
||||
*/
|
||||
public function store(StoreCouponRequest $request): JsonResponse
|
||||
{
|
||||
@@ -65,8 +67,8 @@ class CouponController extends AdminBaseController
|
||||
/**
|
||||
* 쿠폰 상세 조회
|
||||
*
|
||||
* @param int $id
|
||||
* @return JsonResponse
|
||||
* @param int $id 쿠폰 ID
|
||||
* @return JsonResponse 쿠폰 상세 응답
|
||||
*/
|
||||
public function show(int $id): JsonResponse
|
||||
{
|
||||
@@ -90,9 +92,9 @@ class CouponController extends AdminBaseController
|
||||
/**
|
||||
* 쿠폰 수정
|
||||
*
|
||||
* @param UpdateCouponRequest $request
|
||||
* @param int $id
|
||||
* @return JsonResponse
|
||||
* @param UpdateCouponRequest $request 쿠폰 수정 요청
|
||||
* @param int $id 쿠폰 ID
|
||||
* @return JsonResponse 수정된 쿠폰 응답
|
||||
*/
|
||||
public function update(UpdateCouponRequest $request, int $id): JsonResponse
|
||||
{
|
||||
@@ -116,8 +118,8 @@ class CouponController extends AdminBaseController
|
||||
/**
|
||||
* 쿠폰 삭제
|
||||
*
|
||||
* @param int $id
|
||||
* @return JsonResponse
|
||||
* @param int $id 쿠폰 ID
|
||||
* @return JsonResponse 삭제 결과 응답
|
||||
*/
|
||||
public function destroy(int $id): JsonResponse
|
||||
{
|
||||
@@ -141,8 +143,8 @@ class CouponController extends AdminBaseController
|
||||
/**
|
||||
* 일괄 발급상태 변경
|
||||
*
|
||||
* @param BulkUpdateCouponStatusRequest $request
|
||||
* @return JsonResponse
|
||||
* @param BulkUpdateCouponStatusRequest $request 일괄 상태 변경 요청
|
||||
* @return JsonResponse 변경 결과 응답
|
||||
*/
|
||||
public function bulkUpdateStatus(BulkUpdateCouponStatusRequest $request): JsonResponse
|
||||
{
|
||||
@@ -162,12 +164,73 @@ class CouponController extends AdminBaseController
|
||||
);
|
||||
}
|
||||
|
||||
/**
|
||||
* 쿠폰 직접 발급 (관리자가 지정한 회원들에게 즉시 발급)
|
||||
*
|
||||
* @param IssueCouponDirectRequest $request 직접 발급 요청(user_uuids)
|
||||
* @param int $id 쿠폰 ID
|
||||
* @return JsonResponse 발급 결과 응답(발급/스킵 건수)
|
||||
*/
|
||||
public function issueDirect(IssueCouponDirectRequest $request, int $id): JsonResponse
|
||||
{
|
||||
try {
|
||||
// 회원 식별은 uuid 로 받아 FormRequest 에서 내부 정수 ID 로 해석 (관리자 UI 는 uuid 만 노출)
|
||||
$result = $this->couponService->issueDirectly($id, $request->resolvedUserIds());
|
||||
|
||||
$messageKey = empty($result['skipped'])
|
||||
? 'messages.coupons.direct_issued'
|
||||
: 'messages.coupons.direct_issued_with_skip';
|
||||
|
||||
return ResponseHelper::moduleSuccess(
|
||||
'sirsoft-ecommerce',
|
||||
$messageKey,
|
||||
$result,
|
||||
200,
|
||||
['issued' => $result['issued'], 'skipped' => count($result['skipped'])]
|
||||
);
|
||||
} catch (\Exception $e) {
|
||||
return ResponseHelper::moduleError(
|
||||
'sirsoft-ecommerce',
|
||||
'exceptions.operation_failed',
|
||||
400
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* 쿠폰 발급 취소 (미사용 발급 건을 취소 처리)
|
||||
*
|
||||
* @param int $id 쿠폰 ID
|
||||
* @param int $issueId 발급 내역 ID
|
||||
* @return JsonResponse 취소 결과 응답
|
||||
*/
|
||||
public function cancelIssue(int $id, int $issueId): JsonResponse
|
||||
{
|
||||
try {
|
||||
$issue = $this->couponService->cancelIssue($id, $issueId);
|
||||
|
||||
return ResponseHelper::moduleSuccess(
|
||||
'sirsoft-ecommerce',
|
||||
'messages.coupons.issue_cancelled',
|
||||
new CouponIssueResource($issue)
|
||||
);
|
||||
} catch (\Exception $e) {
|
||||
// 취소 불가 사유(미사용 아님 등)를 관리자에게 그대로 노출
|
||||
return ResponseHelper::moduleError(
|
||||
'sirsoft-ecommerce',
|
||||
'exceptions.operation_failed',
|
||||
400,
|
||||
['detail' => $e->getMessage()]
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* 쿠폰 발급 내역 조회
|
||||
*
|
||||
* @param CouponIssuesListRequest $request
|
||||
* @param int $id
|
||||
* @return JsonResponse
|
||||
* @param CouponIssuesListRequest $request 발급 내역 조회 요청
|
||||
* @param int $id 쿠폰 ID
|
||||
* @return JsonResponse 발급 내역 응답
|
||||
*/
|
||||
public function issues(CouponIssuesListRequest $request, int $id): JsonResponse
|
||||
{
|
||||
|
||||
+123
@@ -0,0 +1,123 @@
|
||||
<?php
|
||||
|
||||
namespace Modules\Sirsoft\Ecommerce\Http\Controllers\Admin;
|
||||
|
||||
use App\Helpers\ResponseHelper;
|
||||
use App\Http\Controllers\Api\Base\AdminBaseController;
|
||||
use Illuminate\Http\JsonResponse;
|
||||
use Modules\Sirsoft\Ecommerce\Http\Requests\Admin\DashboardRangeRequest;
|
||||
use Modules\Sirsoft\Ecommerce\Http\Resources\PendingInquiryResource;
|
||||
use Modules\Sirsoft\Ecommerce\Http\Resources\RecentReviewResource;
|
||||
use Modules\Sirsoft\Ecommerce\Services\EcommerceDashboardService;
|
||||
|
||||
/**
|
||||
* 이커머스 대시보드 컨트롤러
|
||||
*
|
||||
* 관리자 대시보드의 이커머스 영역(오늘 주문 현황/판매 추세 그래프/최신 리뷰/미답변 문의) API를 제공합니다.
|
||||
*/
|
||||
class DashboardController extends AdminBaseController
|
||||
{
|
||||
/**
|
||||
* 모듈 식별자
|
||||
*/
|
||||
private const MODULE = 'sirsoft-ecommerce';
|
||||
|
||||
/**
|
||||
* 최신 리뷰/미답변 문의 카드 기본 표시 건수
|
||||
*/
|
||||
private const DEFAULT_RECENT_LIMIT = 5;
|
||||
|
||||
/**
|
||||
* 추세 그래프 기본 표시 일수
|
||||
*/
|
||||
private const DEFAULT_GRAPH_DAYS = 7;
|
||||
|
||||
/**
|
||||
* @param EcommerceDashboardService $dashboardService 대시보드 서비스
|
||||
*/
|
||||
public function __construct(
|
||||
private readonly EcommerceDashboardService $dashboardService
|
||||
) {
|
||||
parent::__construct();
|
||||
}
|
||||
|
||||
/**
|
||||
* 오늘 주문 상태별 판매 수량(배지)을 조회합니다.
|
||||
*
|
||||
* @return JsonResponse 오늘 상태별 집계
|
||||
*/
|
||||
public function overview(): JsonResponse
|
||||
{
|
||||
return ResponseHelper::moduleSuccess(
|
||||
self::MODULE,
|
||||
'messages.dashboard.fetch_success',
|
||||
$this->dashboardService->getOverview(),
|
||||
);
|
||||
}
|
||||
|
||||
/**
|
||||
* 7일 판매 추세 그래프(막대 + 합계 + 변화율)를 조회합니다.
|
||||
*
|
||||
* @return JsonResponse 그래프 데이터
|
||||
*/
|
||||
public function salesGraph(): JsonResponse
|
||||
{
|
||||
return ResponseHelper::moduleSuccess(
|
||||
self::MODULE,
|
||||
'messages.dashboard.fetch_success',
|
||||
$this->dashboardService->getSalesGraph(
|
||||
(int) g7_module_settings(self::MODULE, 'dashboard.graph_days', self::DEFAULT_GRAPH_DAYS)
|
||||
),
|
||||
);
|
||||
}
|
||||
|
||||
/**
|
||||
* 전체 상품의 최신 노출 리뷰를 조회합니다.
|
||||
*
|
||||
* @param DashboardRangeRequest $request 조회 파라미터
|
||||
* @return JsonResponse 최신 리뷰 목록
|
||||
*/
|
||||
public function recentReviews(DashboardRangeRequest $request): JsonResponse
|
||||
{
|
||||
$reviews = $this->dashboardService->getRecentReviews($this->resolveLimit($request));
|
||||
|
||||
return ResponseHelper::moduleSuccess(
|
||||
self::MODULE,
|
||||
'messages.dashboard.fetch_success',
|
||||
RecentReviewResource::collection($reviews),
|
||||
);
|
||||
}
|
||||
|
||||
/**
|
||||
* 전체 상품의 미답변 문의 목록과 총 건수를 조회합니다.
|
||||
*
|
||||
* @param DashboardRangeRequest $request 조회 파라미터
|
||||
* @return JsonResponse 미답변 문의 목록 + 총 건수
|
||||
*/
|
||||
public function pendingInquiries(DashboardRangeRequest $request): JsonResponse
|
||||
{
|
||||
$result = $this->dashboardService->getPendingInquiries($this->resolveLimit($request));
|
||||
|
||||
return ResponseHelper::moduleSuccess(
|
||||
self::MODULE,
|
||||
'messages.dashboard.fetch_success',
|
||||
[
|
||||
'items' => PendingInquiryResource::collection($result['items']),
|
||||
'total' => $result['total'],
|
||||
'board_slug' => $result['board_slug'],
|
||||
],
|
||||
);
|
||||
}
|
||||
|
||||
/**
|
||||
* 요청의 limit 파라미터를 해석합니다 (미지정 시 설정값 또는 기본값).
|
||||
*
|
||||
* @param DashboardRangeRequest $request 조회 파라미터
|
||||
* @return int 표시 건수
|
||||
*/
|
||||
private function resolveLimit(DashboardRangeRequest $request): int
|
||||
{
|
||||
return (int) ($request->validated('limit')
|
||||
?? g7_module_settings(self::MODULE, 'dashboard.recent_limit', self::DEFAULT_RECENT_LIMIT));
|
||||
}
|
||||
}
|
||||
+80
-8
@@ -2,12 +2,19 @@
|
||||
|
||||
namespace Modules\Sirsoft\Ecommerce\Http\Controllers\Admin;
|
||||
|
||||
use App\Extension\HookManager;
|
||||
use App\Helpers\PermissionHelper;
|
||||
use App\Helpers\ResponseHelper;
|
||||
use App\Http\Controllers\Api\Base\AdminBaseController;
|
||||
use App\Seo\Contracts\SeoCacheManagerInterface;
|
||||
use App\Services\NotificationChannelService;
|
||||
use App\Services\NotificationDefinitionService;
|
||||
use Exception;
|
||||
use Illuminate\Http\JsonResponse;
|
||||
use Modules\Sirsoft\Ecommerce\Enums\ShippingApiAuthType;
|
||||
use Modules\Sirsoft\Ecommerce\Enums\ShippingApiHttpMethod;
|
||||
use Modules\Sirsoft\Ecommerce\Enums\ShippingApiRequestField;
|
||||
use Modules\Sirsoft\Ecommerce\Enums\ShippingApiResponseType;
|
||||
use Modules\Sirsoft\Ecommerce\Http\Requests\Admin\GetSettingRequest;
|
||||
use Modules\Sirsoft\Ecommerce\Http\Requests\Admin\StoreBanksRequest;
|
||||
use Modules\Sirsoft\Ecommerce\Http\Requests\Admin\StoreEcommerceSettingsRequest;
|
||||
@@ -42,7 +49,9 @@ class EcommerceSettingsController extends AdminBaseController
|
||||
$settings = $this->settingsService->getAllSettings();
|
||||
$settings = $this->appendCarriersToSettings($settings);
|
||||
$settings = $this->appendShippingTypesToSettings($settings);
|
||||
$settings = $this->appendShippingApiRequestFieldsToSettings($settings);
|
||||
$settings = $this->appendClaimReasonsToSettings($settings);
|
||||
$settings = $this->appendMileageNotificationChannelsToSettings($settings);
|
||||
$settings['available_pg_providers'] = $this->settingsService->getRegisteredPgProviders();
|
||||
$settings['abilities'] = [
|
||||
'can_update' => PermissionHelper::check('sirsoft-ecommerce.settings.update', request()->user()),
|
||||
@@ -65,7 +74,7 @@ class EcommerceSettingsController extends AdminBaseController
|
||||
/**
|
||||
* 카테고리별 설정을 조회합니다.
|
||||
*
|
||||
* @param string $category 카테고리명
|
||||
* @param string $category 카테고리명
|
||||
* @return JsonResponse 카테고리 설정을 포함한 JSON 응답
|
||||
*/
|
||||
public function show(string $category): JsonResponse
|
||||
@@ -96,7 +105,7 @@ class EcommerceSettingsController extends AdminBaseController
|
||||
/**
|
||||
* 이커머스 설정을 저장합니다.
|
||||
*
|
||||
* @param StoreEcommerceSettingsRequest $request 저장 요청 데이터
|
||||
* @param StoreEcommerceSettingsRequest $request 저장 요청 데이터
|
||||
* @return JsonResponse 저장 결과 JSON 응답
|
||||
*/
|
||||
public function store(StoreEcommerceSettingsRequest $request): JsonResponse
|
||||
@@ -143,11 +152,16 @@ class EcommerceSettingsController extends AdminBaseController
|
||||
}
|
||||
|
||||
if ($result) {
|
||||
// 설정 저장 활동로그 (저장된 카테고리 목록 전달)
|
||||
HookManager::doAction('sirsoft-ecommerce.settings.after_save', array_keys($settings));
|
||||
|
||||
// 저장 후 전체 설정 반환 (관리자 UI 상태 업데이트용)
|
||||
$updatedSettings = $this->settingsService->getAllSettings();
|
||||
$updatedSettings = $this->appendCarriersToSettings($updatedSettings);
|
||||
$updatedSettings = $this->appendShippingTypesToSettings($updatedSettings);
|
||||
$updatedSettings = $this->appendShippingApiRequestFieldsToSettings($updatedSettings);
|
||||
$updatedSettings = $this->appendClaimReasonsToSettings($updatedSettings);
|
||||
$updatedSettings = $this->appendMileageNotificationChannelsToSettings($updatedSettings);
|
||||
$updatedSettings['available_pg_providers'] = $this->settingsService->getRegisteredPgProviders();
|
||||
|
||||
return ResponseHelper::moduleSuccess(
|
||||
@@ -174,7 +188,7 @@ class EcommerceSettingsController extends AdminBaseController
|
||||
/**
|
||||
* 은행 목록만 저장합니다.
|
||||
*
|
||||
* @param StoreBanksRequest $request 은행 목록 저장 요청 데이터
|
||||
* @param StoreBanksRequest $request 은행 목록 저장 요청 데이터
|
||||
* @return JsonResponse 저장 결과 JSON 응답
|
||||
*/
|
||||
public function storeBanks(StoreBanksRequest $request): JsonResponse
|
||||
@@ -211,7 +225,7 @@ class EcommerceSettingsController extends AdminBaseController
|
||||
/**
|
||||
* 특정 설정값을 조회합니다.
|
||||
*
|
||||
* @param GetSettingRequest $request 요청 데이터
|
||||
* @param GetSettingRequest $request 요청 데이터
|
||||
* @return JsonResponse 설정값을 포함한 JSON 응답
|
||||
*/
|
||||
public function getSetting(GetSettingRequest $request): JsonResponse
|
||||
@@ -241,7 +255,7 @@ class EcommerceSettingsController extends AdminBaseController
|
||||
/**
|
||||
* 특정 설정값을 업데이트합니다.
|
||||
*
|
||||
* @param UpdateSettingRequest $request 요청 데이터
|
||||
* @param UpdateSettingRequest $request 요청 데이터
|
||||
* @return JsonResponse 업데이트 결과 JSON 응답
|
||||
*/
|
||||
public function updateSetting(UpdateSettingRequest $request): JsonResponse
|
||||
@@ -364,7 +378,7 @@ class EcommerceSettingsController extends AdminBaseController
|
||||
*
|
||||
* DB 관리 대상인 carriers를 shipping 섹션에 포함시킵니다.
|
||||
*
|
||||
* @param array $settings 설정 배열
|
||||
* @param array $settings 설정 배열
|
||||
* @return array carriers가 추가된 설정 배열
|
||||
*/
|
||||
private function appendCarriersToSettings(array $settings): array
|
||||
@@ -389,7 +403,7 @@ class EcommerceSettingsController extends AdminBaseController
|
||||
*
|
||||
* DB 관리 대상인 shipping types를 shipping 섹션에 포함시킵니다.
|
||||
*
|
||||
* @param array $settings 설정 배열
|
||||
* @param array $settings 설정 배열
|
||||
* @return array shipping types가 추가된 설정 배열
|
||||
*/
|
||||
private function appendShippingTypesToSettings(array $settings): array
|
||||
@@ -399,12 +413,32 @@ class EcommerceSettingsController extends AdminBaseController
|
||||
return $settings;
|
||||
}
|
||||
|
||||
/**
|
||||
* 설정 응답에 배송 계산 API 요청 참고 필드 후보 목록을 추가합니다.
|
||||
*
|
||||
* 배송정책 폼의 "API 전송 필드" 후보(체크박스)는 프론트 하드코딩이 아니라
|
||||
* 백엔드 SSoT enum(ShippingApiRequestField)에서 번역된 {value, label} 로 내려갑니다.
|
||||
*
|
||||
* @param array $settings 설정 배열
|
||||
* @return array 후보 목록이 추가된 설정 배열
|
||||
*/
|
||||
private function appendShippingApiRequestFieldsToSettings(array $settings): array
|
||||
{
|
||||
$settings['shipping']['api_request_fields'] = ShippingApiRequestField::options();
|
||||
// 계산 API 고급 설정 옵션 — 프론트 하드코딩이 아닌 백엔드 enum SSoT 에서 번역되어 내려감
|
||||
$settings['shipping']['api_http_methods'] = ShippingApiHttpMethod::options();
|
||||
$settings['shipping']['api_auth_types'] = ShippingApiAuthType::options();
|
||||
$settings['shipping']['api_response_types'] = ShippingApiResponseType::options();
|
||||
|
||||
return $settings;
|
||||
}
|
||||
|
||||
/**
|
||||
* 설정 응답에 클래임 사유 목록을 추가합니다.
|
||||
*
|
||||
* DB 관리 대상인 claim reasons를 claim 섹션에 포함시킵니다.
|
||||
*
|
||||
* @param array $settings 설정 배열
|
||||
* @param array $settings 설정 배열
|
||||
* @return array claim reasons가 추가된 설정 배열
|
||||
*/
|
||||
private function appendClaimReasonsToSettings(array $settings): array
|
||||
@@ -413,4 +447,42 @@ class EcommerceSettingsController extends AdminBaseController
|
||||
|
||||
return $settings;
|
||||
}
|
||||
|
||||
/**
|
||||
* 마일리지 소멸 예정 알림의 실제 활성 채널을 설정 응답에 병합합니다.
|
||||
*
|
||||
* 설정 카드의 "활성 채널" 칩은 선언 고정값이 아니라 관리자가 알림 설정에서 켜고 끈
|
||||
* 실제 활성 채널을 보여줍니다. GenericNotification::via() 와 동일하게 도출합니다:
|
||||
* definition resolve → notification.channels 필터 → 확장 단위 채널 활성 여부.
|
||||
*
|
||||
* @param array $settings 설정 배열
|
||||
* @return array 활성 채널이 병합된 설정 배열
|
||||
*/
|
||||
private function appendMileageNotificationChannelsToSettings(array $settings): array
|
||||
{
|
||||
$type = 'mileage_expiring_soon';
|
||||
|
||||
try {
|
||||
$definition = app(NotificationDefinitionService::class)->resolve($type);
|
||||
$channels = $definition?->channels ?? ['mail', 'database'];
|
||||
|
||||
$channels = HookManager::applyFilters(
|
||||
'sirsoft-ecommerce.notification.channels',
|
||||
$channels,
|
||||
$type
|
||||
);
|
||||
|
||||
$channelService = app(NotificationChannelService::class);
|
||||
$active = array_values(array_filter(
|
||||
$channels,
|
||||
fn (string $channel) => $channelService->isChannelEnabledForExtension('module', 'sirsoft-ecommerce', $channel)
|
||||
));
|
||||
} catch (Exception) {
|
||||
$active = [];
|
||||
}
|
||||
|
||||
$settings['mileage']['notification_channels'] = $active;
|
||||
|
||||
return $settings;
|
||||
}
|
||||
}
|
||||
+187
@@ -0,0 +1,187 @@
|
||||
<?php
|
||||
|
||||
namespace Modules\Sirsoft\Ecommerce\Http\Controllers\Admin;
|
||||
|
||||
use App\Helpers\ResponseHelper;
|
||||
use App\Http\Controllers\Api\Base\AdminBaseController;
|
||||
use Carbon\Carbon;
|
||||
use Illuminate\Http\JsonResponse;
|
||||
use Illuminate\Support\Facades\Auth;
|
||||
use Modules\Sirsoft\Ecommerce\DTO\MileageAdminDeductDto;
|
||||
use Modules\Sirsoft\Ecommerce\DTO\MileageAdminEarnDto;
|
||||
use Modules\Sirsoft\Ecommerce\Exceptions\MileageValidationException;
|
||||
use Modules\Sirsoft\Ecommerce\Http\Requests\Admin\ExtendMileageExpiryRequest;
|
||||
use Modules\Sirsoft\Ecommerce\Http\Requests\Admin\MileageTransactionListRequest;
|
||||
use Modules\Sirsoft\Ecommerce\Http\Requests\Admin\StoreMileageTransactionRequest;
|
||||
use Modules\Sirsoft\Ecommerce\Http\Requests\Admin\UpdateMileageTransactionRequest;
|
||||
use Modules\Sirsoft\Ecommerce\Http\Resources\MileageTransactionCollection;
|
||||
use Modules\Sirsoft\Ecommerce\Http\Resources\MileageTransactionResource;
|
||||
use Modules\Sirsoft\Ecommerce\Services\UserMileageService;
|
||||
|
||||
/**
|
||||
* 관리자 마일리지 내역 관리 컨트롤러
|
||||
*/
|
||||
class MileageTransactionController extends AdminBaseController
|
||||
{
|
||||
/**
|
||||
* @param UserMileageService $mileageService 마일리지 서비스
|
||||
*/
|
||||
public function __construct(
|
||||
private UserMileageService $mileageService,
|
||||
) {}
|
||||
|
||||
/**
|
||||
* 마일리지 내역 목록 조회 (필터/페이지네이션)
|
||||
*
|
||||
* @param MileageTransactionListRequest $request 요청
|
||||
* @return JsonResponse 응답
|
||||
*/
|
||||
public function index(MileageTransactionListRequest $request): JsonResponse
|
||||
{
|
||||
$filters = $request->validated();
|
||||
$perPage = (int) ($filters['per_page'] ?? 20);
|
||||
|
||||
$transactions = $this->mileageService->paginateAdminHistory($filters, $perPage);
|
||||
|
||||
return ResponseHelper::moduleSuccess(
|
||||
'sirsoft-ecommerce',
|
||||
'messages.mileage.list_retrieved',
|
||||
(new MileageTransactionCollection($transactions))
|
||||
->withCurrencies($this->mileageService->getFilterCurrencies())
|
||||
);
|
||||
}
|
||||
|
||||
/**
|
||||
* 수동 지급/차감
|
||||
*
|
||||
* @param StoreMileageTransactionRequest $request 요청
|
||||
* @return JsonResponse 응답
|
||||
*/
|
||||
public function store(StoreMileageTransactionRequest $request): JsonResponse
|
||||
{
|
||||
$data = $request->validated();
|
||||
$userId = (int) $this->mileageService->resolveUserIdByUuid($data['user_id']);
|
||||
$grantedBy = (int) Auth::id();
|
||||
|
||||
try {
|
||||
if ($data['action'] === 'earn') {
|
||||
$transaction = $this->mileageService->adminEarn($userId, new MileageAdminEarnDto(
|
||||
amount: (int) $data['amount'],
|
||||
currency: $data['currency'],
|
||||
grantedBy: $grantedBy,
|
||||
memo: $data['memo'] ?? null,
|
||||
description: $data['description'] ?? null,
|
||||
expiresAt: $data['expires_at'] ?? null,
|
||||
useDefaultExpiry: (bool) ($data['use_default_expiry'] ?? true),
|
||||
));
|
||||
} else {
|
||||
$transaction = $this->mileageService->adminDeduct($userId, new MileageAdminDeductDto(
|
||||
amount: (int) $data['amount'],
|
||||
currency: $data['currency'],
|
||||
grantedBy: $grantedBy,
|
||||
memo: $data['memo'] ?? null,
|
||||
description: $data['description'] ?? null,
|
||||
));
|
||||
}
|
||||
} catch (MileageValidationException $e) {
|
||||
return ResponseHelper::moduleError(
|
||||
'sirsoft-ecommerce',
|
||||
'messages.mileage.validation_failed',
|
||||
422,
|
||||
['general' => [$e->getMessage()]]
|
||||
);
|
||||
}
|
||||
|
||||
return ResponseHelper::moduleSuccess(
|
||||
'sirsoft-ecommerce',
|
||||
'messages.mileage.transaction_created',
|
||||
new MileageTransactionResource($transaction),
|
||||
201
|
||||
);
|
||||
}
|
||||
|
||||
/**
|
||||
* 적립건 편집 — 사유(memo) 변경 + 만료일(expires_at) 직접 지정
|
||||
*
|
||||
* 마일리지 원장은 불변이므로 적립계 거래의 부가 필드만 보정합니다. 전달된 키만 갱신하며
|
||||
* (memo / expires_at), 적립계 외 거래·소멸/사용된 lot 등 도메인 규칙 위반은 Service 가
|
||||
* MileageValidationException(422)으로 거부합니다.
|
||||
*
|
||||
* @param UpdateMileageTransactionRequest $request 요청
|
||||
* @param int $id 거래 ID
|
||||
* @return JsonResponse 응답
|
||||
*/
|
||||
public function update(UpdateMileageTransactionRequest $request, int $id): JsonResponse
|
||||
{
|
||||
$data = $request->validated();
|
||||
$touchMemo = $request->has('memo');
|
||||
$touchExpiry = $request->has('expires_at');
|
||||
|
||||
try {
|
||||
$transaction = $this->mileageService->updateAdminTransaction(
|
||||
$id,
|
||||
$touchMemo ? ($data['memo'] ?? null) : null,
|
||||
$touchExpiry && ! empty($data['expires_at']) ? Carbon::parse($data['expires_at']) : null,
|
||||
$touchMemo,
|
||||
$touchExpiry,
|
||||
);
|
||||
} catch (MileageValidationException $e) {
|
||||
return ResponseHelper::moduleError(
|
||||
'sirsoft-ecommerce',
|
||||
'messages.mileage.validation_failed',
|
||||
422,
|
||||
['general' => [$e->getMessage()]]
|
||||
);
|
||||
}
|
||||
|
||||
return ResponseHelper::moduleSuccess(
|
||||
'sirsoft-ecommerce',
|
||||
'messages.mileage.transaction_updated',
|
||||
new MileageTransactionResource($transaction)
|
||||
);
|
||||
}
|
||||
|
||||
/**
|
||||
* 일괄 유효기간 연장
|
||||
*
|
||||
* @param ExtendMileageExpiryRequest $request 요청
|
||||
* @return JsonResponse 응답
|
||||
*/
|
||||
public function extendExpiry(ExtendMileageExpiryRequest $request): JsonResponse
|
||||
{
|
||||
$data = $request->validated();
|
||||
$userId = (int) $this->mileageService->resolveUserIdByUuid($data['user_id']);
|
||||
|
||||
$count = $this->mileageService->extendLotExpiry(
|
||||
$userId,
|
||||
array_map('intval', $data['lot_ids']),
|
||||
(int) $data['days'],
|
||||
);
|
||||
|
||||
return ResponseHelper::moduleSuccess(
|
||||
'sirsoft-ecommerce',
|
||||
'messages.mileage.expiry_extended',
|
||||
['extended_count' => $count]
|
||||
);
|
||||
}
|
||||
|
||||
/**
|
||||
* 거래 행 확장 (연결 거래 조회 — FIFO 소비 source / 복원 연결)
|
||||
*
|
||||
* @param int $id 거래 ID
|
||||
* @return JsonResponse 응답
|
||||
*/
|
||||
public function linked(int $id): JsonResponse
|
||||
{
|
||||
$linked = $this->mileageService->getLinkedTransactions($id);
|
||||
if ($linked === null) {
|
||||
return ResponseHelper::moduleError('sirsoft-ecommerce', 'messages.mileage.not_found', 404);
|
||||
}
|
||||
|
||||
return ResponseHelper::moduleSuccess(
|
||||
'sirsoft-ecommerce',
|
||||
'messages.mileage.linked_retrieved',
|
||||
new MileageTransactionCollection($linked)
|
||||
);
|
||||
}
|
||||
}
|
||||
+112
-46
@@ -5,29 +5,29 @@ namespace Modules\Sirsoft\Ecommerce\Http\Controllers\Admin;
|
||||
use App\Helpers\ResponseHelper;
|
||||
use App\Http\Controllers\Api\Base\AdminBaseController;
|
||||
use App\Http\Resources\ActivityLogResource;
|
||||
use App\Models\ActivityLog;
|
||||
use App\Services\ActivityLogService;
|
||||
use Exception;
|
||||
use Illuminate\Http\JsonResponse;
|
||||
use Illuminate\Http\Request;
|
||||
use Illuminate\Validation\ValidationException;
|
||||
use Modules\Sirsoft\Ecommerce\Enums\OrderStatusEnum;
|
||||
use Illuminate\Support\Facades\Auth;
|
||||
use Illuminate\Support\Facades\Log;
|
||||
use Modules\Sirsoft\Ecommerce\Enums\OrderStatusEnum;
|
||||
use Modules\Sirsoft\Ecommerce\Exceptions\PaymentAmountMismatchException;
|
||||
use Modules\Sirsoft\Ecommerce\Http\Requests\Admin\BulkChangeOrderOptionStatusRequest;
|
||||
use Modules\Sirsoft\Ecommerce\Http\Requests\Admin\BulkUpdateOrdersRequest;
|
||||
use Modules\Sirsoft\Ecommerce\Http\Requests\Admin\CancelOrderRequest;
|
||||
use Modules\Sirsoft\Ecommerce\Http\Requests\Admin\ConfirmDepositRequest;
|
||||
use Modules\Sirsoft\Ecommerce\Http\Requests\Admin\EstimateRefundRequest;
|
||||
use Modules\Sirsoft\Ecommerce\Http\Requests\Admin\OrderListRequest;
|
||||
use Modules\Sirsoft\Ecommerce\Http\Requests\Admin\OrderLogsRequest;
|
||||
use Modules\Sirsoft\Ecommerce\Http\Requests\Admin\ResetGuestLookupPasswordRequest;
|
||||
use Modules\Sirsoft\Ecommerce\Http\Requests\Admin\SendOrderEmailRequest;
|
||||
use Modules\Sirsoft\Ecommerce\Http\Requests\Admin\UpdateOrderRequest;
|
||||
use Modules\Sirsoft\Ecommerce\Http\Resources\OrderCollection;
|
||||
use Modules\Sirsoft\Ecommerce\Http\Resources\OrderResource;
|
||||
use Modules\Sirsoft\Ecommerce\Models\Order;
|
||||
use Modules\Sirsoft\Ecommerce\Models\OrderAddress;
|
||||
use Modules\Sirsoft\Ecommerce\Models\OrderOption;
|
||||
use Modules\Sirsoft\Ecommerce\Services\OrderCancellationService;
|
||||
use Modules\Sirsoft\Ecommerce\Services\OrderOptionService;
|
||||
use Modules\Sirsoft\Ecommerce\Services\OrderProcessingService;
|
||||
use Modules\Sirsoft\Ecommerce\Services\OrderService;
|
||||
|
||||
/**
|
||||
@@ -42,12 +42,13 @@ class OrderController extends AdminBaseController
|
||||
private OrderOptionService $orderOptionService,
|
||||
private OrderCancellationService $cancellationService,
|
||||
private ActivityLogService $activityLogService,
|
||||
private OrderProcessingService $orderProcessingService,
|
||||
) {}
|
||||
|
||||
/**
|
||||
* 필터링된 주문 목록을 조회합니다.
|
||||
*
|
||||
* @param OrderListRequest $request 주문 목록 요청 데이터
|
||||
* @param OrderListRequest $request 주문 목록 요청 데이터
|
||||
* @return JsonResponse 주문 목록과 통계 정보를 포함한 JSON 응답
|
||||
*/
|
||||
public function index(OrderListRequest $request): JsonResponse
|
||||
@@ -76,7 +77,7 @@ class OrderController extends AdminBaseController
|
||||
/**
|
||||
* 특정 주문의 상세 정보를 조회합니다.
|
||||
*
|
||||
* @param Order $order 조회할 주문 모델
|
||||
* @param Order $order 조회할 주문 모델
|
||||
* @return JsonResponse 주문 상세 정보를 포함한 JSON 응답
|
||||
*/
|
||||
public function show(Order $order): JsonResponse
|
||||
@@ -109,8 +110,8 @@ class OrderController extends AdminBaseController
|
||||
/**
|
||||
* 주문 정보를 수정합니다.
|
||||
*
|
||||
* @param UpdateOrderRequest $request 주문 수정 요청 데이터
|
||||
* @param Order $order 수정할 주문 모델
|
||||
* @param UpdateOrderRequest $request 주문 수정 요청 데이터
|
||||
* @param Order $order 수정할 주문 모델
|
||||
* @return JsonResponse 수정된 주문 정보를 포함한 JSON 응답
|
||||
*/
|
||||
public function update(UpdateOrderRequest $request, Order $order): JsonResponse
|
||||
@@ -141,7 +142,7 @@ class OrderController extends AdminBaseController
|
||||
/**
|
||||
* 여러 주문을 일괄 변경합니다.
|
||||
*
|
||||
* @param BulkUpdateOrdersRequest $request 일괄 변경 요청 데이터
|
||||
* @param BulkUpdateOrdersRequest $request 일괄 변경 요청 데이터
|
||||
* @return JsonResponse 변경 결과 JSON 응답
|
||||
*/
|
||||
public function bulkUpdate(BulkUpdateOrdersRequest $request): JsonResponse
|
||||
@@ -173,7 +174,7 @@ class OrderController extends AdminBaseController
|
||||
/**
|
||||
* 주문을 삭제합니다 (Soft Delete).
|
||||
*
|
||||
* @param Order $order 삭제할 주문 모델
|
||||
* @param Order $order 삭제할 주문 모델
|
||||
* @return JsonResponse 삭제 결과 JSON 응답
|
||||
*/
|
||||
public function destroy(Order $order): JsonResponse
|
||||
@@ -246,8 +247,8 @@ class OrderController extends AdminBaseController
|
||||
/**
|
||||
* 주문 관련 이메일을 발송합니다.
|
||||
*
|
||||
* @param SendOrderEmailRequest $request 이메일 발송 요청 데이터
|
||||
* @param Order $order 대상 주문 모델
|
||||
* @param SendOrderEmailRequest $request 이메일 발송 요청 데이터
|
||||
* @param Order $order 대상 주문 모델
|
||||
* @return JsonResponse 발송 결과 JSON 응답
|
||||
*/
|
||||
public function sendEmail(SendOrderEmailRequest $request, Order $order): JsonResponse
|
||||
@@ -363,47 +364,112 @@ class OrderController extends AdminBaseController
|
||||
}
|
||||
|
||||
/**
|
||||
* 주문의 활동 로그를 조회합니다.
|
||||
* 무통장 주문의 입금을 확인하여 결제완료로 전이합니다.
|
||||
*
|
||||
* @param Request $request 요청 객체
|
||||
* @param Order $order 주문 모델
|
||||
* @return JsonResponse 활동 로그 목록 JSON 응답
|
||||
* 무통장(dbank) 미결제 주문에 한해 입금자명·입금액을 기록하고 결제완료 처리합니다.
|
||||
* 입금액이 결제예정금액과 정확히 일치하지 않으면 422 를 반환합니다.
|
||||
*
|
||||
* @param ConfirmDepositRequest $request 입금확인 요청 데이터
|
||||
* @param Order $order 대상 주문 모델
|
||||
* @return JsonResponse 입금확인 결과 JSON 응답
|
||||
*/
|
||||
public function logs(Request $request, Order $order): JsonResponse
|
||||
public function confirmDeposit(ConfirmDepositRequest $request, Order $order): JsonResponse
|
||||
{
|
||||
try {
|
||||
$perPage = (int) ($request->query('per_page', 10));
|
||||
$sortOrder = $request->query('sort_order', 'desc');
|
||||
$this->orderProcessingService->confirmManualDeposit(
|
||||
$order,
|
||||
$request->getAmount(),
|
||||
$request->getDepositorName(),
|
||||
$request->shouldMarkOrderComplete(),
|
||||
);
|
||||
|
||||
// 주문 + 주문옵션 + 배송지 로그를 합쳐서 조회
|
||||
$optionIds = $order->options()->pluck('id')->toArray();
|
||||
$addressIds = $order->addresses()->pluck('id')->toArray();
|
||||
$updatedOrder = $this->orderService->getDetail($order->id);
|
||||
|
||||
$query = ActivityLog::where(function ($q) use ($order, $optionIds, $addressIds) {
|
||||
// 주문 자체 로그
|
||||
$q->where(function ($sub) use ($order) {
|
||||
$sub->where('loggable_type', $order->getMorphClass())
|
||||
->where('loggable_id', $order->getKey());
|
||||
});
|
||||
return ResponseHelper::moduleSuccess(
|
||||
'sirsoft-ecommerce',
|
||||
'messages.orders.deposit_confirmed',
|
||||
new OrderResource($updatedOrder)
|
||||
);
|
||||
} catch (PaymentAmountMismatchException $e) {
|
||||
// 입금액 불일치 — 사용자에게 금액 검증 실패를 알림
|
||||
return ResponseHelper::moduleError(
|
||||
'sirsoft-ecommerce',
|
||||
'messages.orders.deposit_amount_mismatch',
|
||||
422,
|
||||
['detail' => $e->getMessage()]
|
||||
);
|
||||
} catch (Exception $e) {
|
||||
Log::error('무통장 입금확인 실패 (관리자)', [
|
||||
'order_id' => $order->id,
|
||||
'error' => $e->getMessage(),
|
||||
]);
|
||||
|
||||
// 해당 주문의 옵션 로그
|
||||
if (! empty($optionIds)) {
|
||||
$q->orWhere(function ($sub) use ($optionIds) {
|
||||
$sub->where('loggable_type', (new OrderOption)->getMorphClass())
|
||||
->whereIn('loggable_id', $optionIds);
|
||||
});
|
||||
}
|
||||
return ResponseHelper::moduleError(
|
||||
'sirsoft-ecommerce',
|
||||
'messages.orders.deposit_confirm_failed',
|
||||
422,
|
||||
['detail' => $e->getMessage()]
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
// 해당 주문의 배송지 로그
|
||||
if (! empty($addressIds)) {
|
||||
$q->orWhere(function ($sub) use ($addressIds) {
|
||||
$sub->where('loggable_type', (new OrderAddress)->getMorphClass())
|
||||
->whereIn('loggable_id', $addressIds);
|
||||
});
|
||||
}
|
||||
})->orderBy('created_at', $sortOrder);
|
||||
/**
|
||||
* 비회원 주문의 조회 비밀번호를 재설정합니다.
|
||||
*
|
||||
* 비회원 주문(user_id IS NULL)만 허용하며, 회원 주문은 거부합니다.
|
||||
* 평문 비밀번호는 응답/로그에 노출하지 않고 해시만 저장합니다.
|
||||
*
|
||||
* @param ResetGuestLookupPasswordRequest $request 재설정 요청 데이터
|
||||
* @param Order $order 대상 주문 모델
|
||||
* @return JsonResponse 재설정 결과 JSON 응답
|
||||
*/
|
||||
public function resetGuestLookupPassword(ResetGuestLookupPasswordRequest $request, Order $order): JsonResponse
|
||||
{
|
||||
// 회원 주문은 조회 비밀번호 재설정 대상이 아님
|
||||
if ($order->user_id !== null) {
|
||||
return ResponseHelper::moduleError(
|
||||
'sirsoft-ecommerce',
|
||||
'messages.orders.guest_password_reset_not_guest',
|
||||
422
|
||||
);
|
||||
}
|
||||
|
||||
$logs = $query->paginate($perPage);
|
||||
try {
|
||||
$this->orderService->resetGuestLookupPassword(
|
||||
$order,
|
||||
$request->validated('guest_lookup_password')
|
||||
);
|
||||
|
||||
return ResponseHelper::moduleSuccess(
|
||||
'sirsoft-ecommerce',
|
||||
'messages.orders.guest_password_reset_success'
|
||||
);
|
||||
} catch (Exception $e) {
|
||||
Log::error('비회원 조회 비밀번호 재설정 실패', [
|
||||
'order_id' => $order->id,
|
||||
'error' => $e->getMessage(),
|
||||
]);
|
||||
|
||||
return ResponseHelper::moduleError(
|
||||
'sirsoft-ecommerce',
|
||||
'messages.orders.guest_password_reset_failed',
|
||||
500
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* 주문의 활동 로그를 조회합니다.
|
||||
*
|
||||
* @param OrderLogsRequest $request 활동 로그 조회 요청 데이터
|
||||
* @param Order $order 주문 모델
|
||||
* @return JsonResponse 활동 로그 목록 JSON 응답
|
||||
*/
|
||||
public function logs(OrderLogsRequest $request, Order $order): JsonResponse
|
||||
{
|
||||
try {
|
||||
// 주문 + 주문옵션 + 배송지 로그 합산 조회는 Repository 위임 (Service 경유)
|
||||
$logs = $this->orderService->getActivityLogs($order, $request->getFilters());
|
||||
|
||||
return ResponseHelper::moduleSuccess(
|
||||
'sirsoft-ecommerce',
|
||||
|
||||
+80
-38
@@ -8,21 +8,23 @@ use App\Http\Resources\ActivityLogResource;
|
||||
use App\Models\ActivityLog;
|
||||
use Exception;
|
||||
use Illuminate\Http\JsonResponse;
|
||||
use Illuminate\Http\Request;
|
||||
use Illuminate\Support\Facades\Log;
|
||||
use Illuminate\Validation\ValidationException;
|
||||
use Illuminate\Http\Request;
|
||||
use Modules\Sirsoft\Ecommerce\Exceptions\ProductHasOrderHistoryException;
|
||||
use Modules\Sirsoft\Ecommerce\Exceptions\ProductImageUploadLimitException;
|
||||
use Modules\Sirsoft\Ecommerce\Http\Requests\Admin\BulkUpdatePriceRequest;
|
||||
use Modules\Sirsoft\Ecommerce\Http\Requests\Admin\BulkUpdateProductsRequest;
|
||||
use Modules\Sirsoft\Ecommerce\Http\Requests\Admin\BulkUpdateStatusRequest;
|
||||
use Modules\Sirsoft\Ecommerce\Http\Requests\Admin\BulkUpdateStockRequest;
|
||||
use Modules\Sirsoft\Ecommerce\Http\Requests\Admin\ProductListRequest;
|
||||
use Modules\Sirsoft\Ecommerce\Http\Requests\Admin\ReorderProductImagesRequest;
|
||||
use Modules\Sirsoft\Ecommerce\Http\Requests\Admin\StoreProductRequest;
|
||||
use Modules\Sirsoft\Ecommerce\Http\Requests\Admin\UpdateProductRequest;
|
||||
use Modules\Sirsoft\Ecommerce\Http\Requests\Admin\ReorderProductImagesRequest;
|
||||
use Modules\Sirsoft\Ecommerce\Http\Requests\Admin\UploadProductImageRequest;
|
||||
use Modules\Sirsoft\Ecommerce\Http\Resources\ProductCollection;
|
||||
use Modules\Sirsoft\Ecommerce\Http\Resources\ProductResource;
|
||||
use Modules\Sirsoft\Ecommerce\Http\Resources\ProductOptionResource;
|
||||
use Modules\Sirsoft\Ecommerce\Http\Resources\ProductResource;
|
||||
use Modules\Sirsoft\Ecommerce\Models\Product;
|
||||
use Modules\Sirsoft\Ecommerce\Models\ProductOption;
|
||||
use Modules\Sirsoft\Ecommerce\Services\ProductImageService;
|
||||
@@ -43,7 +45,7 @@ class ProductController extends AdminBaseController
|
||||
/**
|
||||
* 필터링된 상품 목록을 조회합니다.
|
||||
*
|
||||
* @param ProductListRequest $request 상품 목록 요청 데이터
|
||||
* @param ProductListRequest $request 상품 목록 요청 데이터
|
||||
* @return JsonResponse 상품 목록과 통계 정보를 포함한 JSON 응답
|
||||
*/
|
||||
public function index(ProductListRequest $request): JsonResponse
|
||||
@@ -76,7 +78,7 @@ class ProductController extends AdminBaseController
|
||||
* - 숫자 ID: 먼저 ID로 조회 시도, 없으면 product_code로 조회
|
||||
* - product_code: product_code로 조회
|
||||
*
|
||||
* @param string $identifier 상품 ID 또는 product_code
|
||||
* @param string $identifier 상품 ID 또는 product_code
|
||||
* @return JsonResponse 상품 상세 정보를 포함한 JSON 응답
|
||||
*/
|
||||
public function show(string $identifier): JsonResponse
|
||||
@@ -111,7 +113,7 @@ class ProductController extends AdminBaseController
|
||||
/**
|
||||
* 새로운 상품을 생성합니다.
|
||||
*
|
||||
* @param StoreProductRequest $request 상품 생성 요청 데이터
|
||||
* @param StoreProductRequest $request 상품 생성 요청 데이터
|
||||
* @return JsonResponse 생성된 상품 정보를 포함한 JSON 응답
|
||||
*/
|
||||
public function store(StoreProductRequest $request): JsonResponse
|
||||
@@ -152,8 +154,8 @@ class ProductController extends AdminBaseController
|
||||
/**
|
||||
* 기존 상품 정보를 수정합니다.
|
||||
*
|
||||
* @param UpdateProductRequest $request 상품 수정 요청 데이터
|
||||
* @param Product $product 수정할 상품 모델
|
||||
* @param UpdateProductRequest $request 상품 수정 요청 데이터
|
||||
* @param Product $product 수정할 상품 모델
|
||||
* @return JsonResponse 수정된 상품 정보를 포함한 JSON 응답
|
||||
*/
|
||||
public function update(UpdateProductRequest $request, Product $product): JsonResponse
|
||||
@@ -196,7 +198,7 @@ class ProductController extends AdminBaseController
|
||||
*
|
||||
* 주문 이력이 있는 상품은 삭제할 수 없습니다.
|
||||
*
|
||||
* @param Product $product 확인할 상품 모델
|
||||
* @param Product $product 확인할 상품 모델
|
||||
* @return JsonResponse 삭제 가능 여부 JSON 응답
|
||||
*/
|
||||
public function canDelete(Product $product): JsonResponse
|
||||
@@ -221,13 +223,26 @@ class ProductController extends AdminBaseController
|
||||
/**
|
||||
* 상품을 삭제합니다.
|
||||
*
|
||||
* @param Product $product 삭제할 상품 모델
|
||||
* @param Product $product 삭제할 상품 모델
|
||||
* @return JsonResponse 삭제 결과 JSON 응답
|
||||
*/
|
||||
public function destroy(Product $product): JsonResponse
|
||||
{
|
||||
// 주문 이력 선행 검사 — 사유가 명확한 409 Conflict 로 차단 (입력검증 422 아님)
|
||||
$canDelete = $this->productService->checkCanDelete($product);
|
||||
if ($canDelete['canDelete'] !== true) {
|
||||
$count = $canDelete['relatedData']['orders'] ?? 0;
|
||||
|
||||
return ResponseHelper::moduleError(
|
||||
'sirsoft-ecommerce',
|
||||
'messages.products.has_order_history',
|
||||
409,
|
||||
null,
|
||||
['count' => $count]
|
||||
);
|
||||
}
|
||||
|
||||
try {
|
||||
$productId = $product->id;
|
||||
$this->productService->delete($product);
|
||||
|
||||
return ResponseHelper::moduleSuccess(
|
||||
@@ -235,6 +250,17 @@ class ProductController extends AdminBaseController
|
||||
'messages.products.deleted',
|
||||
['deleted' => true]
|
||||
);
|
||||
} catch (ProductHasOrderHistoryException $e) {
|
||||
// 서비스 도메인 가드 (선행 검사 우회/경합 방어) — 409 Conflict
|
||||
$count = $this->productService->checkCanDelete($product)['relatedData']['orders'] ?? 0;
|
||||
|
||||
return ResponseHelper::moduleError(
|
||||
'sirsoft-ecommerce',
|
||||
'messages.products.has_order_history',
|
||||
409,
|
||||
null,
|
||||
['count' => $count]
|
||||
);
|
||||
} catch (Exception $e) {
|
||||
return ResponseHelper::moduleError(
|
||||
'sirsoft-ecommerce',
|
||||
@@ -247,7 +273,7 @@ class ProductController extends AdminBaseController
|
||||
/**
|
||||
* 여러 상품의 상태를 일괄 변경합니다.
|
||||
*
|
||||
* @param BulkUpdateStatusRequest $request 일괄 상태 변경 요청 데이터
|
||||
* @param BulkUpdateStatusRequest $request 일괄 상태 변경 요청 데이터
|
||||
* @return JsonResponse 변경 결과 JSON 응답
|
||||
*/
|
||||
public function bulkUpdateStatus(BulkUpdateStatusRequest $request): JsonResponse
|
||||
@@ -263,7 +289,9 @@ class ProductController extends AdminBaseController
|
||||
return ResponseHelper::moduleSuccess(
|
||||
'sirsoft-ecommerce',
|
||||
'messages.products.bulk_updated',
|
||||
$result
|
||||
$result,
|
||||
200,
|
||||
['count' => $result['updated_count'] ?? 0]
|
||||
);
|
||||
} catch (ValidationException $e) {
|
||||
return ResponseHelper::moduleError(
|
||||
@@ -283,7 +311,7 @@ class ProductController extends AdminBaseController
|
||||
/**
|
||||
* 여러 상품의 가격을 일괄 변경합니다.
|
||||
*
|
||||
* @param BulkUpdatePriceRequest $request 일괄 가격 변경 요청 데이터
|
||||
* @param BulkUpdatePriceRequest $request 일괄 가격 변경 요청 데이터
|
||||
* @return JsonResponse 변경 결과 JSON 응답
|
||||
*/
|
||||
public function bulkUpdatePrice(BulkUpdatePriceRequest $request): JsonResponse
|
||||
@@ -300,7 +328,9 @@ class ProductController extends AdminBaseController
|
||||
return ResponseHelper::moduleSuccess(
|
||||
'sirsoft-ecommerce',
|
||||
'messages.products.bulk_price_updated',
|
||||
$result
|
||||
$result,
|
||||
200,
|
||||
['count' => $result['updated_count'] ?? 0]
|
||||
);
|
||||
} catch (ValidationException $e) {
|
||||
return ResponseHelper::moduleError(
|
||||
@@ -320,7 +350,7 @@ class ProductController extends AdminBaseController
|
||||
/**
|
||||
* 여러 상품의 재고를 일괄 변경합니다.
|
||||
*
|
||||
* @param BulkUpdateStockRequest $request 일괄 재고 변경 요청 데이터
|
||||
* @param BulkUpdateStockRequest $request 일괄 재고 변경 요청 데이터
|
||||
* @return JsonResponse 변경 결과 JSON 응답
|
||||
*/
|
||||
public function bulkUpdateStock(BulkUpdateStockRequest $request): JsonResponse
|
||||
@@ -336,7 +366,9 @@ class ProductController extends AdminBaseController
|
||||
return ResponseHelper::moduleSuccess(
|
||||
'sirsoft-ecommerce',
|
||||
'messages.products.bulk_stock_updated',
|
||||
$result
|
||||
$result,
|
||||
200,
|
||||
['count' => $result['updated_count'] ?? 0]
|
||||
);
|
||||
} catch (ValidationException $e) {
|
||||
return ResponseHelper::moduleError(
|
||||
@@ -359,7 +391,7 @@ class ProductController extends AdminBaseController
|
||||
* 일괄 변경(bulk_changes)과 개별 인라인 수정(items)을 동시 처리합니다.
|
||||
* 일괄 변경 조건이 설정된 필드는 우선 적용되며, 나머지는 개별 수정이 적용됩니다.
|
||||
*
|
||||
* @param BulkUpdateProductsRequest $request 통합 업데이트 요청 데이터
|
||||
* @param BulkUpdateProductsRequest $request 통합 업데이트 요청 데이터
|
||||
* @return JsonResponse 변경 결과 JSON 응답
|
||||
*/
|
||||
public function bulkUpdate(BulkUpdateProductsRequest $request): JsonResponse
|
||||
@@ -371,7 +403,9 @@ class ProductController extends AdminBaseController
|
||||
return ResponseHelper::moduleSuccess(
|
||||
'sirsoft-ecommerce',
|
||||
'messages.products.bulk_updated',
|
||||
$result
|
||||
$result,
|
||||
200,
|
||||
['count' => ($result['products_updated'] ?? 0) + ($result['options_updated'] ?? 0)]
|
||||
);
|
||||
} catch (ValidationException $e) {
|
||||
return ResponseHelper::moduleError(
|
||||
@@ -415,7 +449,7 @@ class ProductController extends AdminBaseController
|
||||
/**
|
||||
* 상품코드로 상품을 조회합니다.
|
||||
*
|
||||
* @param string $itemCode 상품코드
|
||||
* @param string $itemCode 상품코드
|
||||
* @return JsonResponse 상품 정보 JSON 응답
|
||||
*/
|
||||
public function showByCode(string $itemCode): JsonResponse
|
||||
@@ -448,8 +482,8 @@ class ProductController extends AdminBaseController
|
||||
/**
|
||||
* 상품코드로 상품을 수정합니다.
|
||||
*
|
||||
* @param UpdateProductRequest $request 상품 수정 요청 데이터
|
||||
* @param string $itemCode 상품코드
|
||||
* @param UpdateProductRequest $request 상품 수정 요청 데이터
|
||||
* @param string $itemCode 상품코드
|
||||
* @return JsonResponse 수정된 상품 정보 JSON 응답
|
||||
*/
|
||||
public function updateByCode(UpdateProductRequest $request, string $itemCode): JsonResponse
|
||||
@@ -490,7 +524,7 @@ class ProductController extends AdminBaseController
|
||||
/**
|
||||
* 폼 상세 데이터를 조회합니다.
|
||||
*
|
||||
* @param Product $product 조회할 상품 모델
|
||||
* @param Product $product 조회할 상품 모델
|
||||
* @return JsonResponse 폼 상세 데이터 JSON 응답
|
||||
*/
|
||||
public function showForForm(Product $product): JsonResponse
|
||||
@@ -523,8 +557,8 @@ class ProductController extends AdminBaseController
|
||||
/**
|
||||
* 상품 복사용 데이터를 조회합니다.
|
||||
*
|
||||
* @param Request $request HTTP 요청 (복사 옵션 포함)
|
||||
* @param Product $product 복사할 상품 모델
|
||||
* @param Request $request HTTP 요청 (복사 옵션 포함)
|
||||
* @param Product $product 복사할 상품 모델
|
||||
* @return JsonResponse 복사용 데이터 JSON 응답
|
||||
*/
|
||||
public function showForCopy(Request $request, Product $product): JsonResponse
|
||||
@@ -606,7 +640,7 @@ class ProductController extends AdminBaseController
|
||||
*
|
||||
* @param UploadProductImageRequest $request 이미지 업로드 요청
|
||||
* @param int|null $productId 상품 ID (신규 등록 시 null)
|
||||
* @return JsonResponse
|
||||
* @return JsonResponse 업로드된 이미지 정보 JSON 응답
|
||||
*/
|
||||
public function uploadImage(UploadProductImageRequest $request, ?int $productId = null): JsonResponse
|
||||
{
|
||||
@@ -642,7 +676,16 @@ class ProductController extends AdminBaseController
|
||||
],
|
||||
201
|
||||
);
|
||||
} catch (\Exception $e) {
|
||||
} catch (ProductImageUploadLimitException $e) {
|
||||
// 개수 상한 초과는 도메인 검증 실패 → 422 + 전용 메시지 (메시지 키 + 파라미터)
|
||||
return ResponseHelper::error(
|
||||
'exceptions.product_image_limit_exceeded',
|
||||
422,
|
||||
null,
|
||||
['max' => $e->maxImages],
|
||||
'sirsoft-ecommerce'
|
||||
);
|
||||
} catch (Exception $e) {
|
||||
Log::error('상품 이미지 업로드 실패', [
|
||||
'product_id' => $productId,
|
||||
'error' => $e->getMessage(),
|
||||
@@ -661,7 +704,7 @@ class ProductController extends AdminBaseController
|
||||
* 상품 이미지 삭제
|
||||
*
|
||||
* @param int $id 이미지 ID
|
||||
* @return JsonResponse
|
||||
* @return JsonResponse 삭제 결과 JSON 응답
|
||||
*/
|
||||
public function deleteImage(int $id): JsonResponse
|
||||
{
|
||||
@@ -680,7 +723,7 @@ class ProductController extends AdminBaseController
|
||||
'sirsoft-ecommerce',
|
||||
'messages.product_images.deleted'
|
||||
);
|
||||
} catch (\Exception $e) {
|
||||
} catch (Exception $e) {
|
||||
return ResponseHelper::moduleError(
|
||||
'sirsoft-ecommerce',
|
||||
'exceptions.operation_failed',
|
||||
@@ -692,8 +735,8 @@ class ProductController extends AdminBaseController
|
||||
/**
|
||||
* 상품 이미지 순서 변경
|
||||
*
|
||||
* @param Request $request
|
||||
* @return JsonResponse
|
||||
* @param ReorderProductImagesRequest $request 이미지 순서 변경 요청
|
||||
* @return JsonResponse 순서 변경 결과 JSON 응답
|
||||
*/
|
||||
public function reorderImages(ReorderProductImagesRequest $request): JsonResponse
|
||||
{
|
||||
@@ -705,7 +748,7 @@ class ProductController extends AdminBaseController
|
||||
'sirsoft-ecommerce',
|
||||
'messages.product_images.reordered'
|
||||
);
|
||||
} catch (\Exception $e) {
|
||||
} catch (Exception $e) {
|
||||
return ResponseHelper::moduleError(
|
||||
'sirsoft-ecommerce',
|
||||
'exceptions.operation_failed',
|
||||
@@ -719,7 +762,7 @@ class ProductController extends AdminBaseController
|
||||
*
|
||||
* @param int $productId 상품 ID
|
||||
* @param int $imageId 이미지 ID
|
||||
* @return JsonResponse
|
||||
* @return JsonResponse 대표 이미지 설정 결과 JSON 응답
|
||||
*/
|
||||
public function setThumbnail(int $productId, int $imageId): JsonResponse
|
||||
{
|
||||
@@ -730,7 +773,7 @@ class ProductController extends AdminBaseController
|
||||
'sirsoft-ecommerce',
|
||||
'messages.product_images.thumbnail_set'
|
||||
);
|
||||
} catch (\Exception $e) {
|
||||
} catch (Exception $e) {
|
||||
return ResponseHelper::moduleError(
|
||||
'sirsoft-ecommerce',
|
||||
'exceptions.operation_failed',
|
||||
@@ -743,7 +786,6 @@ class ProductController extends AdminBaseController
|
||||
* 파일 크기를 읽기 쉬운 형식으로 변환합니다.
|
||||
*
|
||||
* @param int $bytes 바이트 크기
|
||||
* @return string
|
||||
*/
|
||||
private function formatFileSize(int $bytes): string
|
||||
{
|
||||
@@ -754,14 +796,14 @@ class ProductController extends AdminBaseController
|
||||
$i++;
|
||||
}
|
||||
|
||||
return round($bytes, 2) . ' ' . $units[$i];
|
||||
return round($bytes, 2).' '.$units[$i];
|
||||
}
|
||||
|
||||
/**
|
||||
* 상품 처리로그(활동 로그) 목록을 조회합니다.
|
||||
*
|
||||
* @param Request $request 요청
|
||||
* @param Product $product 상품
|
||||
* @param Request $request 요청
|
||||
* @param Product $product 상품
|
||||
* @return JsonResponse 활동 로그 목록
|
||||
*/
|
||||
public function logs(Request $request, Product $product): JsonResponse
|
||||
|
||||
+36
-9
@@ -6,7 +6,7 @@ use App\Helpers\ResponseHelper;
|
||||
use App\Http\Controllers\Api\Base\AdminBaseController;
|
||||
use Exception;
|
||||
use Illuminate\Http\JsonResponse;
|
||||
use Illuminate\Http\Request;
|
||||
use Modules\Sirsoft\Ecommerce\Http\Requests\Admin\ProductNoticeTemplateListRequest;
|
||||
use Modules\Sirsoft\Ecommerce\Http\Requests\Admin\StoreProductNoticeTemplateRequest;
|
||||
use Modules\Sirsoft\Ecommerce\Http\Requests\Admin\UpdateProductNoticeTemplateRequest;
|
||||
use Modules\Sirsoft\Ecommerce\Http\Resources\ProductNoticeTemplateCollection;
|
||||
@@ -27,10 +27,10 @@ class ProductNoticeTemplateController extends AdminBaseController
|
||||
/**
|
||||
* 템플릿 목록을 조회합니다.
|
||||
*
|
||||
* @param Request $request 요청 데이터
|
||||
* @param ProductNoticeTemplateListRequest $request 요청 데이터
|
||||
* @return JsonResponse 템플릿 목록 JSON 응답
|
||||
*/
|
||||
public function index(Request $request): JsonResponse
|
||||
public function index(ProductNoticeTemplateListRequest $request): JsonResponse
|
||||
{
|
||||
$filters = [
|
||||
'search' => $request->get('search'),
|
||||
@@ -67,7 +67,7 @@ class ProductNoticeTemplateController extends AdminBaseController
|
||||
/**
|
||||
* 템플릿 상세를 조회합니다.
|
||||
*
|
||||
* @param int $id 템플릿 ID
|
||||
* @param int $id 템플릿 ID
|
||||
* @return JsonResponse 템플릿 상세 JSON 응답
|
||||
*/
|
||||
public function show(int $id): JsonResponse
|
||||
@@ -92,7 +92,7 @@ class ProductNoticeTemplateController extends AdminBaseController
|
||||
/**
|
||||
* 템플릿을 생성합니다.
|
||||
*
|
||||
* @param StoreProductNoticeTemplateRequest $request 생성 요청
|
||||
* @param StoreProductNoticeTemplateRequest $request 생성 요청
|
||||
* @return JsonResponse 생성된 템플릿 JSON 응답
|
||||
*/
|
||||
public function store(StoreProductNoticeTemplateRequest $request): JsonResponse
|
||||
@@ -118,8 +118,8 @@ class ProductNoticeTemplateController extends AdminBaseController
|
||||
/**
|
||||
* 템플릿을 수정합니다.
|
||||
*
|
||||
* @param UpdateProductNoticeTemplateRequest $request 수정 요청
|
||||
* @param int $id 템플릿 ID
|
||||
* @param UpdateProductNoticeTemplateRequest $request 수정 요청
|
||||
* @param int $id 템플릿 ID
|
||||
* @return JsonResponse 수정된 템플릿 JSON 응답
|
||||
*/
|
||||
public function update(UpdateProductNoticeTemplateRequest $request, int $id): JsonResponse
|
||||
@@ -144,7 +144,7 @@ class ProductNoticeTemplateController extends AdminBaseController
|
||||
/**
|
||||
* 템플릿을 삭제합니다.
|
||||
*
|
||||
* @param int $id 템플릿 ID
|
||||
* @param int $id 템플릿 ID
|
||||
* @return JsonResponse 삭제 결과 JSON 응답
|
||||
*/
|
||||
public function destroy(int $id): JsonResponse
|
||||
@@ -169,7 +169,7 @@ class ProductNoticeTemplateController extends AdminBaseController
|
||||
/**
|
||||
* 템플릿을 복사합니다.
|
||||
*
|
||||
* @param int $id 원본 템플릿 ID
|
||||
* @param int $id 원본 템플릿 ID
|
||||
* @return JsonResponse 복사된 템플릿 JSON 응답
|
||||
*/
|
||||
public function copy(int $id): JsonResponse
|
||||
@@ -191,4 +191,31 @@ class ProductNoticeTemplateController extends AdminBaseController
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* 템플릿 활성 상태를 토글합니다.
|
||||
*
|
||||
* @param int $id 템플릿 ID
|
||||
* @return JsonResponse 토글 결과 JSON 응답
|
||||
*/
|
||||
public function toggleActive(int $id): JsonResponse
|
||||
{
|
||||
try {
|
||||
$template = $this->templateService->toggleActive($id);
|
||||
|
||||
return ResponseHelper::moduleSuccess(
|
||||
'sirsoft-ecommerce',
|
||||
$template->is_active
|
||||
? 'messages.notice_templates.activated'
|
||||
: 'messages.notice_templates.deactivated',
|
||||
new ProductNoticeTemplateResource($template)
|
||||
);
|
||||
} catch (Exception $e) {
|
||||
return ResponseHelper::moduleError(
|
||||
'sirsoft-ecommerce',
|
||||
'exceptions.operation_failed',
|
||||
400
|
||||
);
|
||||
}
|
||||
}
|
||||
}
|
||||
+31
-1
@@ -9,9 +9,11 @@ use Modules\Sirsoft\Ecommerce\Http\Requests\Admin\ShippingPolicyBulkDeleteReques
|
||||
use Modules\Sirsoft\Ecommerce\Http\Requests\Admin\ShippingPolicyBulkToggleActiveRequest;
|
||||
use Modules\Sirsoft\Ecommerce\Http\Requests\Admin\ShippingPolicyListRequest;
|
||||
use Modules\Sirsoft\Ecommerce\Http\Requests\Admin\StoreShippingPolicyRequest;
|
||||
use Modules\Sirsoft\Ecommerce\Http\Requests\Admin\TestShippingApiRequest;
|
||||
use Modules\Sirsoft\Ecommerce\Http\Requests\Admin\UpdateShippingPolicyRequest;
|
||||
use Modules\Sirsoft\Ecommerce\Http\Resources\ShippingPolicyCollection;
|
||||
use Modules\Sirsoft\Ecommerce\Http\Resources\ShippingPolicyResource;
|
||||
use Modules\Sirsoft\Ecommerce\Services\OrderCalculationService;
|
||||
use Modules\Sirsoft\Ecommerce\Services\ShippingPolicyService;
|
||||
|
||||
/**
|
||||
@@ -20,7 +22,8 @@ use Modules\Sirsoft\Ecommerce\Services\ShippingPolicyService;
|
||||
class ShippingPolicyController extends AdminBaseController
|
||||
{
|
||||
public function __construct(
|
||||
private ShippingPolicyService $shippingPolicyService
|
||||
private ShippingPolicyService $shippingPolicyService,
|
||||
private OrderCalculationService $calculationService
|
||||
) {}
|
||||
|
||||
/**
|
||||
@@ -69,6 +72,33 @@ class ShippingPolicyController extends AdminBaseController
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* 계산 API 연동 테스트 호출
|
||||
*
|
||||
* 관리자가 폼에서 입력 중인 설정으로 외부 배송비 계산 API 를 1회 실호출하여
|
||||
* 요청 미리보기 + 응답 + 추출 배송비를 반환합니다. 타임아웃·응답 크기 제한 적용.
|
||||
*
|
||||
* @param TestShippingApiRequest $request 테스트 호출 요청
|
||||
* @return JsonResponse 테스트 결과
|
||||
*/
|
||||
public function testApiCall(TestShippingApiRequest $request): JsonResponse
|
||||
{
|
||||
$validated = $request->validated();
|
||||
|
||||
$result = $this->calculationService->testApiCall(
|
||||
endpoint: $validated['endpoint'],
|
||||
config: $validated['config'] ?? [],
|
||||
requestFields: $validated['request_fields'] ?? null,
|
||||
sample: $validated['sample'] ?? [],
|
||||
);
|
||||
|
||||
return ResponseHelper::moduleSuccess(
|
||||
'sirsoft-ecommerce',
|
||||
'messages.shipping_policy.api_test_done',
|
||||
$result
|
||||
);
|
||||
}
|
||||
|
||||
/**
|
||||
* 배송정책 수정
|
||||
*
|
||||
|
||||
@@ -6,7 +6,12 @@ use App\Helpers\ResponseHelper;
|
||||
use App\Http\Controllers\Api\Base\PublicBaseController;
|
||||
use Exception;
|
||||
use Illuminate\Http\JsonResponse;
|
||||
use Illuminate\Support\Collection;
|
||||
use Illuminate\Support\Facades\Auth;
|
||||
use Illuminate\Support\Facades\Log;
|
||||
use Modules\Sirsoft\Ecommerce\Exceptions\CartOperationException;
|
||||
use Modules\Sirsoft\Ecommerce\Exceptions\CartUnavailableException;
|
||||
use Modules\Sirsoft\Ecommerce\Http\Middleware\ResolveShippingCountry;
|
||||
use Modules\Sirsoft\Ecommerce\Http\Requests\Public\BulkAddToCartRequest;
|
||||
use Modules\Sirsoft\Ecommerce\Http\Requests\Public\ChangeCartOptionRequest;
|
||||
use Modules\Sirsoft\Ecommerce\Http\Requests\Public\DeleteAllCartItemsRequest;
|
||||
@@ -17,6 +22,7 @@ use Modules\Sirsoft\Ecommerce\Http\Requests\Public\MergeGuestCartRequest;
|
||||
use Modules\Sirsoft\Ecommerce\Http\Requests\Public\UpdateCartQuantityRequest;
|
||||
use Modules\Sirsoft\Ecommerce\Http\Resources\CartItemResource;
|
||||
use Modules\Sirsoft\Ecommerce\Services\CartService;
|
||||
use Modules\Sirsoft\Ecommerce\Services\ShippingPolicyResolver;
|
||||
|
||||
/**
|
||||
* 장바구니 컨트롤러
|
||||
@@ -96,6 +102,9 @@ class CartController extends PublicBaseController
|
||||
'item_ids' => $result->items->pluck('id')->values()->toArray(),
|
||||
'item_count' => $result->count(),
|
||||
'calculation' => $result->calculation->toArray(),
|
||||
// 선택된 배송국가로 배송 불가한 상품이 1개라도 있으면 주문 전체 차단 플래그 (D1 — layer 1)
|
||||
'has_unshippable_items' => $this->hasUnshippableItems($result->items),
|
||||
'selected_shipping_country' => ResolveShippingCountry::getCountry(),
|
||||
]);
|
||||
} catch (Exception $e) {
|
||||
return ResponseHelper::moduleError(
|
||||
@@ -141,7 +150,15 @@ class CartController extends PublicBaseController
|
||||
),
|
||||
'cart_count' => $result['cart_count'],
|
||||
], 201);
|
||||
} catch (CartUnavailableException $e) {
|
||||
// 판매불가/재고/구매수량 한도 위반 — generic 500 이 아닌 사유별 422 매핑
|
||||
return $this->cartUnavailableResponse($e);
|
||||
} catch (CartOperationException $e) {
|
||||
// 항목없음/권한없음/옵션없음 — 사유별 404/403/422 매핑
|
||||
return $this->cartOperationResponse($e);
|
||||
} catch (Exception $e) {
|
||||
Log::error('cart.store failed', ['error' => $e->getMessage()]);
|
||||
|
||||
return ResponseHelper::moduleError(
|
||||
'sirsoft-ecommerce',
|
||||
'messages.cart.add_failed',
|
||||
@@ -194,7 +211,15 @@ class CartController extends PublicBaseController
|
||||
'item_count' => $result->count(),
|
||||
'calculation' => $result->calculation->toArray(),
|
||||
]);
|
||||
} catch (CartUnavailableException $e) {
|
||||
// 판매불가/재고/구매수량 한도 위반 — generic 500 이 아닌 사유별 422 매핑
|
||||
return $this->cartUnavailableResponse($e);
|
||||
} catch (CartOperationException $e) {
|
||||
// 항목없음/권한없음/옵션없음 — 사유별 404/403/422 매핑
|
||||
return $this->cartOperationResponse($e);
|
||||
} catch (Exception $e) {
|
||||
Log::error('cart.update_quantity failed', ['error' => $e->getMessage()]);
|
||||
|
||||
return ResponseHelper::moduleError(
|
||||
'sirsoft-ecommerce',
|
||||
'messages.cart.update_failed',
|
||||
@@ -224,13 +249,22 @@ class CartController extends PublicBaseController
|
||||
$validated['product_option_id'],
|
||||
$validated['quantity'],
|
||||
$userId,
|
||||
$cartKey
|
||||
$cartKey,
|
||||
$validated['additional_option_selections'] ?? null
|
||||
);
|
||||
|
||||
return ResponseHelper::moduleSuccess('sirsoft-ecommerce', 'messages.cart.option_changed', [
|
||||
'item' => new CartItemResource($cart->load(['product', 'productOption'])),
|
||||
]);
|
||||
} catch (CartUnavailableException $e) {
|
||||
// 판매불가/재고/구매수량 한도 위반 — generic 500 이 아닌 사유별 422 매핑
|
||||
return $this->cartUnavailableResponse($e);
|
||||
} catch (CartOperationException $e) {
|
||||
// 항목없음/권한없음/옵션없음/타상품옵션 — 사유별 404/403/422 매핑
|
||||
return $this->cartOperationResponse($e);
|
||||
} catch (Exception $e) {
|
||||
Log::error('cart.change_option failed', ['error' => $e->getMessage()]);
|
||||
|
||||
return ResponseHelper::moduleError(
|
||||
'sirsoft-ecommerce',
|
||||
'messages.cart.update_failed',
|
||||
@@ -257,7 +291,12 @@ class CartController extends PublicBaseController
|
||||
$this->cartService->deleteItem($id, $userId, $cartKey);
|
||||
|
||||
return ResponseHelper::moduleSuccess('sirsoft-ecommerce', 'messages.cart.deleted');
|
||||
} catch (CartOperationException $e) {
|
||||
// 없는 항목(404)/타인 항목(403) 삭제 시도 — generic 500 이 아닌 사유별 4xx
|
||||
return $this->cartOperationResponse($e);
|
||||
} catch (Exception $e) {
|
||||
Log::error('cart.destroy failed', ['error' => $e->getMessage()]);
|
||||
|
||||
return ResponseHelper::moduleError(
|
||||
'sirsoft-ecommerce',
|
||||
'messages.cart.delete_failed',
|
||||
@@ -286,10 +325,16 @@ class CartController extends PublicBaseController
|
||||
$cartKey
|
||||
);
|
||||
|
||||
return ResponseHelper::moduleSuccess('sirsoft-ecommerce', 'messages.cart.deleted_multiple', [
|
||||
'deleted_count' => $deletedCount,
|
||||
]);
|
||||
return ResponseHelper::moduleSuccess(
|
||||
'sirsoft-ecommerce',
|
||||
'messages.cart.deleted_multiple',
|
||||
['deleted_count' => $deletedCount],
|
||||
200,
|
||||
['deleted_count' => $deletedCount],
|
||||
);
|
||||
} catch (Exception $e) {
|
||||
Log::error('cart.destroy_multiple failed', ['error' => $e->getMessage()]);
|
||||
|
||||
return ResponseHelper::moduleError(
|
||||
'sirsoft-ecommerce',
|
||||
'messages.cart.delete_failed',
|
||||
@@ -314,10 +359,16 @@ class CartController extends PublicBaseController
|
||||
|
||||
$deletedCount = $this->cartService->deleteAll($userId, $cartKey);
|
||||
|
||||
return ResponseHelper::moduleSuccess('sirsoft-ecommerce', 'messages.cart.deleted_all', [
|
||||
'deleted_count' => $deletedCount,
|
||||
]);
|
||||
return ResponseHelper::moduleSuccess(
|
||||
'sirsoft-ecommerce',
|
||||
'messages.cart.deleted_all',
|
||||
['deleted_count' => $deletedCount],
|
||||
200,
|
||||
['deleted_count' => $deletedCount],
|
||||
);
|
||||
} catch (Exception $e) {
|
||||
Log::error('cart.destroy_all failed', ['error' => $e->getMessage()]);
|
||||
|
||||
return ResponseHelper::moduleError(
|
||||
'sirsoft-ecommerce',
|
||||
'messages.cart.delete_failed',
|
||||
@@ -346,6 +397,8 @@ class CartController extends PublicBaseController
|
||||
'merged_count' => $mergedCount,
|
||||
]);
|
||||
} catch (Exception $e) {
|
||||
Log::error('cart.merge failed', ['error' => $e->getMessage()]);
|
||||
|
||||
return ResponseHelper::moduleError(
|
||||
'sirsoft-ecommerce',
|
||||
'messages.cart.merge_failed',
|
||||
@@ -382,6 +435,82 @@ class CartController extends PublicBaseController
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* 구매불가 예외를 4xx(422) 응답으로 변환합니다.
|
||||
*
|
||||
* 담기/수량변경/옵션변경 시 판매상태·구매수량 위반 예외를 generic 500 이 아닌
|
||||
* 사유별 4xx 로 매핑합니다. (재고/판매상태/구매대상제한/구매수량 한도)
|
||||
*
|
||||
* @param CartUnavailableException $e 구매불가 예외
|
||||
* @return JsonResponse 422 에러 응답
|
||||
*/
|
||||
protected function cartUnavailableResponse(CartUnavailableException $e): JsonResponse
|
||||
{
|
||||
$messageKey = $e->hasRestrictionIssue()
|
||||
? 'exceptions.purchase_not_allowed'
|
||||
: 'exceptions.cart_unavailable';
|
||||
|
||||
return ResponseHelper::moduleError(
|
||||
'sirsoft-ecommerce',
|
||||
$messageKey,
|
||||
422,
|
||||
[
|
||||
'code' => 'cart_unavailable',
|
||||
'message' => $e->getUserMessage(),
|
||||
'unavailable_items' => $e->getUnavailableItems(),
|
||||
'has_stock_issue' => $e->hasStockIssue(),
|
||||
'has_status_issue' => $e->hasStatusIssue(),
|
||||
'has_restriction_issue' => $e->hasRestrictionIssue(),
|
||||
'has_min_qty_issue' => $e->hasMinQtyIssue(),
|
||||
'has_max_qty_issue' => $e->hasMaxQtyIssue(),
|
||||
]
|
||||
);
|
||||
}
|
||||
|
||||
/**
|
||||
* 장바구니 단건 조작 예외를 사유별 4xx 응답으로 변환합니다.
|
||||
*
|
||||
* 항목없음/권한없음/옵션없음/타상품옵션 조작 예외를 generic 500 이 아닌
|
||||
* 사유별 404/403/422 로 매핑합니다. (MP07 §1-c — U9 전면 정비)
|
||||
*
|
||||
* @param CartOperationException $e 장바구니 조작 예외
|
||||
* @return JsonResponse 사유별 4xx 에러 응답
|
||||
*/
|
||||
protected function cartOperationResponse(CartOperationException $e): JsonResponse
|
||||
{
|
||||
return ResponseHelper::moduleError(
|
||||
'sirsoft-ecommerce',
|
||||
$e->getMessageKey(),
|
||||
$e->getStatusCode(),
|
||||
['code' => $e->getReason()]
|
||||
);
|
||||
}
|
||||
|
||||
/**
|
||||
* 선택된 배송국가로 배송 불가한 상품이 카트에 1개라도 있는지 판정합니다. (D1 — layer 1)
|
||||
*
|
||||
* @param Collection $items 카트 아이템 컬렉션
|
||||
* @return bool 배송 불가 상품이 1개 이상이면 true (주문 전체 차단)
|
||||
*/
|
||||
protected function hasUnshippableItems($items): bool
|
||||
{
|
||||
$country = ResolveShippingCountry::getCountry();
|
||||
$resolver = app(ShippingPolicyResolver::class);
|
||||
|
||||
foreach ($items as $item) {
|
||||
$product = $item->relationLoaded('product') ? $item->product : $item->product;
|
||||
if ($product === null) {
|
||||
continue;
|
||||
}
|
||||
|
||||
if (! $resolver->isShippableToCountry($product, $country)) {
|
||||
return true;
|
||||
}
|
||||
}
|
||||
|
||||
return false;
|
||||
}
|
||||
|
||||
/**
|
||||
* 비회원 cart_key 검증
|
||||
*
|
||||
|
||||
+104
-31
@@ -9,7 +9,10 @@ use Illuminate\Http\JsonResponse;
|
||||
use Illuminate\Support\Facades\Auth;
|
||||
use Illuminate\Support\Facades\Log;
|
||||
use Modules\Sirsoft\Ecommerce\DTO\ShippingAddress;
|
||||
use Modules\Sirsoft\Ecommerce\Exceptions\CartEmptyException;
|
||||
use Modules\Sirsoft\Ecommerce\Exceptions\CartUnavailableException;
|
||||
use Modules\Sirsoft\Ecommerce\Exceptions\MileageValidationException;
|
||||
use Modules\Sirsoft\Ecommerce\Exceptions\TempOrderNotFoundException;
|
||||
use Modules\Sirsoft\Ecommerce\Http\Requests\Public\CheckoutRequest;
|
||||
use Modules\Sirsoft\Ecommerce\Http\Requests\Public\DeleteCheckoutRequest;
|
||||
use Modules\Sirsoft\Ecommerce\Http\Requests\Public\ExtendCheckoutRequest;
|
||||
@@ -37,7 +40,7 @@ class CheckoutController extends PublicBaseController
|
||||
* 선택한 장바구니 아이템으로 임시 주문을 생성합니다.
|
||||
* 주문서 작성 페이지에서 사용할 임시 주문 데이터를 반환합니다.
|
||||
*
|
||||
* @param CheckoutRequest $request 검증된 요청 데이터
|
||||
* @param CheckoutRequest $request 검증된 요청 데이터
|
||||
* @return JsonResponse 임시 주문 정보를 포함한 JSON 응답
|
||||
*/
|
||||
public function store(CheckoutRequest $request): JsonResponse
|
||||
@@ -49,12 +52,22 @@ class CheckoutController extends PublicBaseController
|
||||
$cartKey = $request->header('X-Cart-Key');
|
||||
$validated = $request->validated();
|
||||
|
||||
$tempOrder = $this->tempOrderService->createTempOrderFromSelectedItems(
|
||||
cartIds: $validated['item_ids'],
|
||||
userId: $userId,
|
||||
cartKey: $cartKey,
|
||||
usePoints: $validated['use_points'] ?? 0
|
||||
);
|
||||
// direct_items(바로 구매, 장바구니 미경유) vs item_ids(장바구니 경유) 분기
|
||||
if (! empty($validated['direct_items'])) {
|
||||
$tempOrder = $this->tempOrderService->createTempOrderFromDirectItems(
|
||||
items: $validated['direct_items'],
|
||||
userId: $userId,
|
||||
cartKey: $cartKey,
|
||||
usePoints: $validated['use_points'] ?? 0
|
||||
);
|
||||
} else {
|
||||
$tempOrder = $this->tempOrderService->createTempOrderFromSelectedItems(
|
||||
cartIds: $validated['item_ids'],
|
||||
userId: $userId,
|
||||
cartKey: $cartKey,
|
||||
usePoints: $validated['use_points'] ?? 0
|
||||
);
|
||||
}
|
||||
|
||||
return ResponseHelper::moduleSuccess('sirsoft-ecommerce', 'messages.checkout.created', [
|
||||
'temp_order_id' => $tempOrder->id,
|
||||
@@ -62,27 +75,53 @@ class CheckoutController extends PublicBaseController
|
||||
'expires_at' => $tempOrder->expires_at->toIso8601String(),
|
||||
], 201);
|
||||
} catch (CartUnavailableException $e) {
|
||||
// 구매불가 상품 예외 처리 (재고부족 또는 판매상태)
|
||||
// 구매불가 상품 예외 처리 (재고부족 / 판매상태 / 구매대상제한)
|
||||
// 구매 권한 문제면 사유를 구분해 안내 (재고/판매상태와 동일 문구로 묶이지 않도록)
|
||||
$messageKey = $e->hasRestrictionIssue()
|
||||
? 'exceptions.purchase_not_allowed'
|
||||
: 'exceptions.cart_unavailable';
|
||||
|
||||
return ResponseHelper::moduleError(
|
||||
'sirsoft-ecommerce',
|
||||
'exceptions.cart_unavailable',
|
||||
$messageKey,
|
||||
400,
|
||||
[
|
||||
'code' => 'cart_unavailable',
|
||||
'message' => $e->getUserMessage(),
|
||||
'unavailable_items' => $e->getUnavailableItems(),
|
||||
'has_stock_issue' => $e->hasStockIssue(),
|
||||
'has_status_issue' => $e->hasStatusIssue(),
|
||||
'has_restriction_issue' => $e->hasRestrictionIssue(),
|
||||
'has_min_qty_issue' => $e->hasMinQtyIssue(),
|
||||
'has_max_qty_issue' => $e->hasMaxQtyIssue(),
|
||||
]
|
||||
);
|
||||
} catch (MileageValidationException $e) {
|
||||
// 마일리지 보유 잔액 초과 사용 요청 (U15) — generic 500 이 아닌 422 명시 차단
|
||||
return ResponseHelper::moduleError(
|
||||
'sirsoft-ecommerce',
|
||||
'messages.checkout.create_failed',
|
||||
422,
|
||||
['code' => 'mileage_exceeds_balance', 'message' => $e->getMessage()],
|
||||
);
|
||||
} catch (CartEmptyException $e) {
|
||||
// 장바구니 비어있음 — i18n 문자열 매칭 대신 타입 분기 (U14/MP06)
|
||||
Log::warning('Checkout store: cart empty', [
|
||||
'message' => $e->getMessage(),
|
||||
]);
|
||||
|
||||
return ResponseHelper::moduleError(
|
||||
'sirsoft-ecommerce',
|
||||
'exceptions.cart_empty',
|
||||
400
|
||||
);
|
||||
} catch (Exception $e) {
|
||||
// 장바구니 비어있음 예외 처리
|
||||
if (str_contains($e->getMessage(), 'cart_empty')) {
|
||||
return ResponseHelper::moduleError(
|
||||
'sirsoft-ecommerce',
|
||||
'exceptions.cart_empty',
|
||||
400
|
||||
);
|
||||
}
|
||||
Log::error('Checkout store error', [
|
||||
'message' => $e->getMessage(),
|
||||
'file' => $e->getFile(),
|
||||
'line' => $e->getLine(),
|
||||
'trace' => $e->getTraceAsString(),
|
||||
]);
|
||||
|
||||
return ResponseHelper::moduleError(
|
||||
'sirsoft-ecommerce',
|
||||
@@ -99,7 +138,7 @@ class CheckoutController extends PublicBaseController
|
||||
* 쿼리 파라미터로 배송 주소를 전달하면 해당 주소 기준으로 배송비가 계산됩니다.
|
||||
* 도서산간 지역 여부는 우편번호 기반으로 배송정책에서 자동 판별됩니다.
|
||||
*
|
||||
* @param ShowCheckoutRequest $request 검증된 요청 데이터
|
||||
* @param ShowCheckoutRequest $request 검증된 요청 데이터
|
||||
* @return JsonResponse 임시 주문 정보를 포함한 JSON 응답
|
||||
*
|
||||
* @queryParam zipcode string 우편번호 (배송비 계산용)
|
||||
@@ -115,8 +154,11 @@ class CheckoutController extends PublicBaseController
|
||||
$validated = $request->validated();
|
||||
|
||||
// 검증된 파라미터에서 배송 주소 정보 추출
|
||||
// 배송비 미리보기는 우편번호 없이 배송국가(country_code)만으로도 해당 국가 배송비를
|
||||
// 계산해 보여줘야 한다(주문 성립 요건과 별개 — 우편번호 필수는 주문 확정 검증이 담당).
|
||||
// 따라서 country_code 단독 전달도 ShippingAddress 생성 트리거에 포함한다(update 와 동일).
|
||||
$shippingAddress = null;
|
||||
if (isset($validated['zipcode']) || isset($validated['region'])) {
|
||||
if (isset($validated['zipcode']) || isset($validated['region']) || isset($validated['country_code'])) {
|
||||
$shippingAddress = new ShippingAddress(
|
||||
countryCode: $validated['country_code'] ?? 'KR',
|
||||
zipcode: $validated['zipcode'] ?? null,
|
||||
@@ -156,7 +198,7 @@ class CheckoutController extends PublicBaseController
|
||||
|
||||
return ResponseHelper::moduleError(
|
||||
'sirsoft-ecommerce',
|
||||
'messages.checkout.fetch_failed',
|
||||
'messages.checkout.fetc_failed',
|
||||
500
|
||||
);
|
||||
}
|
||||
@@ -168,7 +210,7 @@ class CheckoutController extends PublicBaseController
|
||||
* 쿠폰, 마일리지, 배송 주소 변경 시 호출하여 주문 금액을 재계산합니다.
|
||||
* 배송 주소에 따라 배송비가 달라질 수 있습니다.
|
||||
*
|
||||
* @param UpdateCheckoutRequest $request 검증된 요청 데이터
|
||||
* @param UpdateCheckoutRequest $request 검증된 요청 데이터
|
||||
* @return JsonResponse 재계산된 임시 주문 정보를 포함한 JSON 응답
|
||||
*/
|
||||
public function update(UpdateCheckoutRequest $request): JsonResponse
|
||||
@@ -220,14 +262,32 @@ class CheckoutController extends PublicBaseController
|
||||
);
|
||||
|
||||
return ResponseHelper::moduleSuccess('sirsoft-ecommerce', 'messages.checkout.updated', $responseData);
|
||||
} catch (TempOrderNotFoundException $e) {
|
||||
// 만료/미존재 임시주문 — i18n 문자열 매칭 대신 타입 분기 (U14/MP06)
|
||||
Log::warning('Checkout update: temp order not found', [
|
||||
'message' => $e->getMessage(),
|
||||
]);
|
||||
|
||||
return ResponseHelper::moduleError(
|
||||
'sirsoft-ecommerce',
|
||||
'exceptions.temp_order_not_found',
|
||||
404
|
||||
);
|
||||
} catch (MileageValidationException $e) {
|
||||
// 마일리지 보유 잔액 초과 사용 요청 (U15) — generic 500 이 아닌 422 명시 차단
|
||||
return ResponseHelper::moduleError(
|
||||
'sirsoft-ecommerce',
|
||||
'messages.checkout.update_failed',
|
||||
422,
|
||||
['code' => 'mileage_exceeds_balance', 'message' => $e->getMessage()],
|
||||
);
|
||||
} catch (Exception $e) {
|
||||
if (str_contains($e->getMessage(), 'temp_order_not_found')) {
|
||||
return ResponseHelper::moduleError(
|
||||
'sirsoft-ecommerce',
|
||||
'exceptions.temp_order_not_found',
|
||||
404
|
||||
);
|
||||
}
|
||||
Log::error('Checkout update error', [
|
||||
'message' => $e->getMessage(),
|
||||
'file' => $e->getFile(),
|
||||
'line' => $e->getLine(),
|
||||
'trace' => $e->getTraceAsString(),
|
||||
]);
|
||||
|
||||
return ResponseHelper::moduleError(
|
||||
'sirsoft-ecommerce',
|
||||
@@ -240,7 +300,7 @@ class CheckoutController extends PublicBaseController
|
||||
/**
|
||||
* 임시 주문 삭제 (주문서 페이지 이탈 시)
|
||||
*
|
||||
* @param DeleteCheckoutRequest $request 검증된 요청 데이터
|
||||
* @param DeleteCheckoutRequest $request 검증된 요청 데이터
|
||||
* @return JsonResponse 삭제 결과를 포함한 JSON 응답
|
||||
*/
|
||||
public function destroy(DeleteCheckoutRequest $request): JsonResponse
|
||||
@@ -263,6 +323,13 @@ class CheckoutController extends PublicBaseController
|
||||
|
||||
return ResponseHelper::moduleSuccess('sirsoft-ecommerce', 'messages.checkout.deleted');
|
||||
} catch (Exception $e) {
|
||||
Log::error('Checkout destroy error', [
|
||||
'message' => $e->getMessage(),
|
||||
'file' => $e->getFile(),
|
||||
'line' => $e->getLine(),
|
||||
'trace' => $e->getTraceAsString(),
|
||||
]);
|
||||
|
||||
return ResponseHelper::moduleError(
|
||||
'sirsoft-ecommerce',
|
||||
'messages.checkout.delete_failed',
|
||||
@@ -274,7 +341,7 @@ class CheckoutController extends PublicBaseController
|
||||
/**
|
||||
* 임시 주문 만료 시간 연장
|
||||
*
|
||||
* @param ExtendCheckoutRequest $request 검증된 요청 데이터
|
||||
* @param ExtendCheckoutRequest $request 검증된 요청 데이터
|
||||
* @return JsonResponse 연장된 만료 시간을 포함한 JSON 응답
|
||||
*/
|
||||
public function extend(ExtendCheckoutRequest $request): JsonResponse
|
||||
@@ -299,6 +366,13 @@ class CheckoutController extends PublicBaseController
|
||||
'expires_at' => $tempOrder->expires_at->toIso8601String(),
|
||||
]);
|
||||
} catch (Exception $e) {
|
||||
Log::error('Checkout extend error', [
|
||||
'message' => $e->getMessage(),
|
||||
'file' => $e->getFile(),
|
||||
'line' => $e->getLine(),
|
||||
'trace' => $e->getTraceAsString(),
|
||||
]);
|
||||
|
||||
return ResponseHelper::moduleError(
|
||||
'sirsoft-ecommerce',
|
||||
'messages.checkout.extend_failed',
|
||||
@@ -306,5 +380,4 @@ class CheckoutController extends PublicBaseController
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
}
|
||||
+33
@@ -86,6 +86,39 @@ class EcommerceSettingsController extends PublicBaseController
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* 리뷰 정책 설정을 조회합니다.
|
||||
*
|
||||
* 리뷰 작성 화면에서 필요한 정책을 반환합니다.
|
||||
* - 리뷰 이미지 최대 개수(max_images)
|
||||
* - 리뷰 이미지 최대 용량(max_image_size_mb)
|
||||
* - 리뷰 작성 기한(write_deadline_days)
|
||||
*
|
||||
* @return JsonResponse 리뷰 설정을 포함한 JSON 응답
|
||||
*/
|
||||
public function review(): JsonResponse
|
||||
{
|
||||
try {
|
||||
$this->logApiUsage('settings.review');
|
||||
|
||||
$reviewSettings = $this->settingsService->getSettings('review_settings');
|
||||
|
||||
return ResponseHelper::moduleSuccess(
|
||||
'sirsoft-ecommerce',
|
||||
'messages.settings.fetch_success',
|
||||
[
|
||||
'review_settings' => $reviewSettings,
|
||||
]
|
||||
);
|
||||
} catch (Exception $e) {
|
||||
return ResponseHelper::moduleError(
|
||||
'sirsoft-ecommerce',
|
||||
'messages.settings.fetch_failed',
|
||||
500
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* 체크아웃에 필요한 설정을 조회합니다.
|
||||
*
|
||||
|
||||
@@ -0,0 +1,431 @@
|
||||
<?php
|
||||
|
||||
namespace Modules\Sirsoft\Ecommerce\Http\Controllers\Public;
|
||||
|
||||
use App\Helpers\ResponseHelper;
|
||||
use App\Http\Controllers\Api\Base\PublicBaseController;
|
||||
use Exception;
|
||||
use Illuminate\Http\JsonResponse;
|
||||
use Illuminate\Support\Facades\Auth;
|
||||
use Illuminate\Support\Facades\Log;
|
||||
use Modules\Sirsoft\Ecommerce\Http\Controllers\Traits\HandlesOrderCreation;
|
||||
use Modules\Sirsoft\Ecommerce\Http\Requests\Public\CreateOrderRequest;
|
||||
use Modules\Sirsoft\Ecommerce\Http\Requests\Public\GuestCancelOrderRequest;
|
||||
use Modules\Sirsoft\Ecommerce\Http\Requests\Public\GuestEstimateRefundRequest;
|
||||
use Modules\Sirsoft\Ecommerce\Http\Requests\Public\GuestOrderTokenRequest;
|
||||
use Modules\Sirsoft\Ecommerce\Http\Requests\Public\GuestUpdateShippingAddressRequest;
|
||||
use Modules\Sirsoft\Ecommerce\Http\Requests\Public\VerifyGuestOrderRequest;
|
||||
use Modules\Sirsoft\Ecommerce\Http\Requests\User\CancelPaymentRequest;
|
||||
use Modules\Sirsoft\Ecommerce\Http\Resources\GuestOrderResource;
|
||||
use Modules\Sirsoft\Ecommerce\Http\Resources\OrderResource;
|
||||
use Modules\Sirsoft\Ecommerce\Models\Order;
|
||||
use Modules\Sirsoft\Ecommerce\Services\GuestOrderAuthService;
|
||||
use Modules\Sirsoft\Ecommerce\Services\OrderCancellationService;
|
||||
use Modules\Sirsoft\Ecommerce\Services\OrderProcessingService;
|
||||
use Modules\Sirsoft\Ecommerce\Services\OrderService;
|
||||
use Modules\Sirsoft\Ecommerce\Services\StockService;
|
||||
use Modules\Sirsoft\Ecommerce\Services\TempOrderService;
|
||||
use Modules\Sirsoft\Ecommerce\Services\UserAddressService;
|
||||
|
||||
/**
|
||||
* 주문 공유 컨트롤러 (회원/비회원 공용 + 비회원 토큰 후속 액션)
|
||||
*
|
||||
* 책임:
|
||||
* - 회원/비회원 공유: 주문 생성(store), 주문번호 상세 조회(showByOrderNumber),
|
||||
* PG 결제창 닫기(cancelPayment)
|
||||
* - 비회원 전용 토큰 후속: verify, cancel, estimateRefund, confirmOption
|
||||
*
|
||||
* 회원 전용 마이페이지 액션(index, show, cancel, estimateRefund, updateShippingAddress,
|
||||
* confirmOption, reorder)은 User\OrderController 가 담당한다.
|
||||
* (비회원 배송지 수정은 미지원 — 향후 필요 시 재도입)
|
||||
*
|
||||
* PG 플러그인 fetch 인터셉터가 /api/modules/sirsoft-ecommerce/user/orders 한 경로만
|
||||
* 매칭하므로 회원/비회원이 동일 엔드포인트(POST /user/orders)로 진입한다. 회원/비회원
|
||||
* 분기는 본 컨트롤러의 store() 내부에서 Auth::id() 로 동적 처리한다.
|
||||
*/
|
||||
class OrderController extends PublicBaseController
|
||||
{
|
||||
use HandlesOrderCreation;
|
||||
|
||||
public function __construct(
|
||||
protected OrderProcessingService $orderProcessingService,
|
||||
protected TempOrderService $tempOrderService,
|
||||
protected StockService $stockService,
|
||||
protected GuestOrderAuthService $guestOrderAuthService,
|
||||
protected OrderService $orderService,
|
||||
protected OrderCancellationService $cancellationService,
|
||||
protected UserAddressService $userAddressService
|
||||
) {}
|
||||
|
||||
/**
|
||||
* 주문 생성 (결제하기) — 회원/비회원 공유
|
||||
*
|
||||
* 회원이면 Auth::id() 를 임시주문 매칭/주문 user_id 로 사용하고 OrderResource 로 응답,
|
||||
* 비회원이면 user_id=null + GuestOrderResource 로 응답한다. 회원 전용 배송지 자동 저장
|
||||
* 후처리는 회원일 때만 수행한다.
|
||||
*
|
||||
* @param CreateOrderRequest $request 검증된 주문 생성 요청
|
||||
* @return JsonResponse 생성된 주문 정보를 포함한 JSON 응답
|
||||
*/
|
||||
public function store(CreateOrderRequest $request): JsonResponse
|
||||
{
|
||||
$userId = Auth::id();
|
||||
|
||||
return $this->processOrderCreation(
|
||||
request: $request,
|
||||
userId: $userId,
|
||||
buildResponseData: function (Order $order, bool $requiresPg, string $pgProvider) use ($userId): array {
|
||||
if ($userId !== null) {
|
||||
return $this->buildOrderResponseData(
|
||||
$order,
|
||||
$requiresPg,
|
||||
$pgProvider,
|
||||
new OrderResource($order)
|
||||
);
|
||||
}
|
||||
|
||||
// 비회원: 민감 필드 노출을 피하기 위해 GuestOrderResource 로 응답
|
||||
return $this->buildOrderResponseData(
|
||||
$order,
|
||||
$requiresPg,
|
||||
$pgProvider,
|
||||
new GuestOrderResource($order)
|
||||
);
|
||||
},
|
||||
afterCreate: function (Order $order, bool $requiresPg) use ($request, $userId): void {
|
||||
// 회원만 배송지 자동 저장 후처리 수행 (비회원은 user_addresses 매칭 대상 아님)
|
||||
if ($userId !== null) {
|
||||
$this->maybeSaveShippingAddress($userId, $request, $order, $requiresPg);
|
||||
}
|
||||
},
|
||||
logEndpoint: 'user.orders.store'
|
||||
);
|
||||
}
|
||||
|
||||
/**
|
||||
* 회원 주문 생성 시 배송지 자동 저장 (회원 전용)
|
||||
*
|
||||
* non-PG 결제는 즉시 저장하고, PG 결제는 order_meta 에 플래그를 남겨
|
||||
* completePayment() 시점에 저장하도록 위임합니다.
|
||||
*
|
||||
* @param int $userId 회원 ID (비회원은 호출 측에서 가드)
|
||||
* @param CreateOrderRequest $request 검증된 요청 데이터
|
||||
* @param Order $order 생성된 주문
|
||||
* @param bool $requiresPg PG 결제 필요 여부
|
||||
*/
|
||||
protected function maybeSaveShippingAddress(int $userId, CreateOrderRequest $request, Order $order, bool $requiresPg): void
|
||||
{
|
||||
if (! $request->boolean('save_shipping_address')) {
|
||||
return;
|
||||
}
|
||||
|
||||
if ($requiresPg) {
|
||||
// PG 결제: order_meta에 플래그 저장 (completePayment 시점에 처리)
|
||||
$order->update([
|
||||
'order_meta' => array_merge($order->order_meta ?? [], [
|
||||
'save_shipping_address' => true,
|
||||
'shipping_info_for_save' => $request->getShippingInfo(),
|
||||
]),
|
||||
]);
|
||||
|
||||
return;
|
||||
}
|
||||
|
||||
// 비PG 결제: 즉시 배송지 저장
|
||||
try {
|
||||
$name = $this->userAddressService->generateUniqueName(
|
||||
$userId,
|
||||
__('sirsoft-ecommerce::messages.address.auto_saved_label')
|
||||
);
|
||||
$shippingInfo = $request->getShippingInfo();
|
||||
$this->userAddressService->createAddress(
|
||||
$this->userAddressService->mapShippingInfoToAddressData($userId, $name, $shippingInfo)
|
||||
);
|
||||
} catch (Exception $e) {
|
||||
Log::warning('Auto save shipping address failed on order creation', [
|
||||
'user_id' => $userId,
|
||||
'order_id' => $order->id,
|
||||
'message' => $e->getMessage(),
|
||||
]);
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* 주문번호로 주문 상세 조회 (회원/비회원 공유)
|
||||
*
|
||||
* 분기 규칙:
|
||||
* - 로그인되어 있으면 본인 회원 주문만 OrderResource 로 반환, 아니면 404
|
||||
* - 비로그인이면 X-Guest-Order-Token 으로 비회원 주문 매칭 → GuestOrderResource, 실패 시 404
|
||||
*
|
||||
* 회원이 비회원 토큰을 들고 진입해도 회원 분기가 우선 — 로그인 시 토큰을 정리하는
|
||||
* 프론트 규약과 일관. 실패 사유는 모두 동일한 404 로 처리해 정보 노출을 차단.
|
||||
*
|
||||
* @param string $orderNumber 주문번호
|
||||
* @return JsonResponse 주문 상세 정보 (회원: OrderResource, 비회원: GuestOrderResource)
|
||||
*/
|
||||
public function showByOrderNumber(string $orderNumber): JsonResponse
|
||||
{
|
||||
$this->logApiUsage('user.orders.show-by-number');
|
||||
|
||||
if (Auth::check()) {
|
||||
$order = $this->orderService->getByOrderNumber($orderNumber);
|
||||
|
||||
if (! $order || $order->user_id !== Auth::id()) {
|
||||
// 회원 본인 주문 아님 → 마이페이지 주문 목록으로 안내
|
||||
return ResponseHelper::error(
|
||||
'sirsoft-ecommerce::exceptions.order_not_found',
|
||||
404,
|
||||
['redirect_to' => '/mypage/orders']
|
||||
);
|
||||
}
|
||||
|
||||
// 권한 검증 후 관계를 풀로드해 OrderResource 가 shippings/shipping_address 등 모든 필드를 응답에 포함하도록 한다.
|
||||
$detail = $this->orderService->getDetail($order->id);
|
||||
|
||||
return ResponseHelper::success('sirsoft-ecommerce::messages.orders.retrieved', new OrderResource($detail));
|
||||
}
|
||||
|
||||
$token = request()->header('X-Guest-Order-Token');
|
||||
$order = $this->guestOrderAuthService->verifyToken($token, $orderNumber);
|
||||
|
||||
if (! $order) {
|
||||
// 비회원 토큰 부재/만료/위조 → 비회원 조회 폼으로 안내
|
||||
return ResponseHelper::error(
|
||||
'sirsoft-ecommerce::exceptions.order_not_found',
|
||||
404,
|
||||
['redirect_to' => '/shop/guest/orders']
|
||||
);
|
||||
}
|
||||
|
||||
$detail = $this->orderService->getDetail($order->id);
|
||||
|
||||
return ResponseHelper::success(
|
||||
'sirsoft-ecommerce::messages.orders.retrieved',
|
||||
new GuestOrderResource($detail)
|
||||
);
|
||||
}
|
||||
|
||||
/**
|
||||
* 결제 취소 기록 (결제창 닫기) — 회원/비회원 공유
|
||||
*
|
||||
* 유저가 PG 결제창을 닫았을 때 호출됩니다.
|
||||
* 주문 상태는 변경하지 않고, order_payments에 취소 이력만 기록합니다.
|
||||
*
|
||||
* @param CancelPaymentRequest $request 검증된 요청 데이터
|
||||
* @return JsonResponse 결제 취소 기록 결과
|
||||
*/
|
||||
public function cancelPayment(CancelPaymentRequest $request): JsonResponse
|
||||
{
|
||||
$this->logApiUsage('orders.cancel-payment');
|
||||
|
||||
$this->orderProcessingService->recordPaymentCancellation(
|
||||
$request->getOrder(),
|
||||
$request->validated('cancel_code'),
|
||||
$request->validated('cancel_message')
|
||||
);
|
||||
|
||||
return ResponseHelper::success('sirsoft-ecommerce::messages.order.payment_cancelled');
|
||||
}
|
||||
|
||||
/**
|
||||
* 비회원 주문 조회 인증
|
||||
*
|
||||
* 주문번호 + 전화번호 + 조회 비밀번호로 본인 확인을 수행하고, 성공 시
|
||||
* 30분 유효한 조회 토큰을 발급합니다. 모든 실패(주문 없음/회원 주문/
|
||||
* 전화번호 불일치/비밀번호 오류/잠금)는 동일한 "주문을 찾을 수 없습니다"
|
||||
* 응답으로 처리해 정보 노출을 차단합니다.
|
||||
*
|
||||
* @param VerifyGuestOrderRequest $request 검증된 조회 인증 요청
|
||||
* @return JsonResponse 조회 토큰과 최소 주문 요약, 실패 시 404
|
||||
*/
|
||||
public function verify(VerifyGuestOrderRequest $request): JsonResponse
|
||||
{
|
||||
$result = $this->guestOrderAuthService->authenticate(
|
||||
orderNumber: $request->input('order_number'),
|
||||
ordererPhone: $request->input('orderer_phone'),
|
||||
guestLookupPassword: $request->input('guest_lookup_password'),
|
||||
clientIp: $request->ip()
|
||||
);
|
||||
|
||||
if (! $result) {
|
||||
return ResponseHelper::moduleError(
|
||||
'sirsoft-ecommerce',
|
||||
'exceptions.order_not_found',
|
||||
404
|
||||
);
|
||||
}
|
||||
|
||||
/** @var Order $order */
|
||||
$order = $result['order'];
|
||||
|
||||
return ResponseHelper::success('sirsoft-ecommerce::messages.orders.retrieved', [
|
||||
'guest_order_token' => $result['token'],
|
||||
'expires_at' => $result['expires_at'],
|
||||
// 최소 주문 요약 (상세는 토큰으로 보호되는 별도 엔드포인트에서 제공)
|
||||
'order' => [
|
||||
'order_number' => $order->order_number,
|
||||
'order_status' => $order->order_status,
|
||||
],
|
||||
]);
|
||||
}
|
||||
|
||||
/**
|
||||
* 비회원 주문 취소
|
||||
*
|
||||
* 회원 취소와 동일한 서비스를 재사용하되, 취소자(cancelledBy)는 null 로 둔다.
|
||||
*
|
||||
* @param GuestCancelOrderRequest $request 검증된 취소 요청
|
||||
* @return JsonResponse 취소 후 주문 상세
|
||||
*/
|
||||
public function cancel(GuestCancelOrderRequest $request): JsonResponse
|
||||
{
|
||||
try {
|
||||
$order = $request->getOrder();
|
||||
|
||||
if ($request->isPartialCancel()) {
|
||||
$this->cancellationService->cancelOrderOptions(
|
||||
order: $order,
|
||||
cancelItems: $request->getCancelItems(),
|
||||
reason: $request->getReason(),
|
||||
reasonDetail: $request->getReasonDetail(),
|
||||
cancelledBy: null,
|
||||
refundPriority: $request->getRefundPriority(),
|
||||
);
|
||||
} else {
|
||||
$this->cancellationService->cancelOrder(
|
||||
order: $order,
|
||||
reason: $request->getReason(),
|
||||
reasonDetail: $request->getReasonDetail(),
|
||||
cancelledBy: null,
|
||||
refundPriority: $request->getRefundPriority(),
|
||||
);
|
||||
}
|
||||
|
||||
$updatedOrder = $this->orderService->getDetail($order->id);
|
||||
|
||||
return ResponseHelper::success(
|
||||
'sirsoft-ecommerce::messages.order.cancelled',
|
||||
new GuestOrderResource($updatedOrder)
|
||||
);
|
||||
} catch (Exception $e) {
|
||||
Log::error('비회원 주문 취소 실패', [
|
||||
'order_number' => $request->getOrder()->order_number,
|
||||
'error' => $e->getMessage(),
|
||||
]);
|
||||
|
||||
return ResponseHelper::error(
|
||||
'sirsoft-ecommerce::exceptions.order_cancel_failed',
|
||||
422
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* 비회원 환불 예상금액 조회
|
||||
*
|
||||
* @param GuestEstimateRefundRequest $request 검증된 환불 예상 요청
|
||||
* @return JsonResponse 환불 예상 결과
|
||||
*/
|
||||
public function estimateRefund(GuestEstimateRefundRequest $request): JsonResponse
|
||||
{
|
||||
try {
|
||||
$result = $this->cancellationService->previewRefund(
|
||||
$request->getOrder(),
|
||||
$request->getCancelItems(),
|
||||
$request->getRefundPriority()
|
||||
);
|
||||
|
||||
return ResponseHelper::success(
|
||||
'sirsoft-ecommerce::messages.order.estimate_refund_success',
|
||||
$result->toPreviewArray()
|
||||
);
|
||||
} catch (Exception $e) {
|
||||
Log::error('비회원 환불 예상금액 계산 실패', [
|
||||
'order_number' => $request->getOrder()->order_number,
|
||||
'error' => $e->getMessage(),
|
||||
]);
|
||||
|
||||
return ResponseHelper::error(
|
||||
'sirsoft-ecommerce::exceptions.order_estimate_refund_failed',
|
||||
500
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* 비회원 주문 배송지 수정 (배송 전 상태)
|
||||
*
|
||||
* 주문 소유권은 VerifyGuestOrderToken 미들웨어가 검증한다. 비회원은 저장된
|
||||
* 회원 주소(address_id)를 쓸 수 없으므로 직접 입력한 배송지 필드를 받아
|
||||
* 회원과 동일한 OrderService::updateShippingAddress 로 처리한다.
|
||||
*
|
||||
* @param GuestUpdateShippingAddressRequest $request 검증된 배송지 데이터
|
||||
* @return JsonResponse 수정 후 주문 상세 (GuestOrderResource)
|
||||
*/
|
||||
public function updateShippingAddress(GuestUpdateShippingAddressRequest $request): JsonResponse
|
||||
{
|
||||
try {
|
||||
$order = $request->getOrder();
|
||||
$this->orderService->updateShippingAddress($order, $request->validated());
|
||||
$updatedOrder = $this->orderService->getDetail($order->id);
|
||||
|
||||
return ResponseHelper::success(
|
||||
'sirsoft-ecommerce::messages.orders.shipping_address_updated',
|
||||
new GuestOrderResource($updatedOrder)
|
||||
);
|
||||
} catch (Exception $e) {
|
||||
Log::error('비회원 배송지 수정 실패', [
|
||||
'order_number' => $request->getOrder()->order_number,
|
||||
'error' => $e->getMessage(),
|
||||
]);
|
||||
|
||||
return ResponseHelper::moduleError(
|
||||
'sirsoft-ecommerce',
|
||||
'messages.orders.cannot_modify_address',
|
||||
422
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* 비회원 주문 옵션 구매확정 (배송 완료 후)
|
||||
*
|
||||
* @param GuestOrderTokenRequest $request 토큰 검증된 요청
|
||||
* @param string $orderNumber 주문번호 (라우트 파라미터 — 미들웨어 토큰 검증에 사용)
|
||||
* @param int $optionId 주문 옵션 ID (라우트 파라미터)
|
||||
* @return JsonResponse 구매확정 후 주문 상세
|
||||
*/
|
||||
public function confirmOption(GuestOrderTokenRequest $request, string $orderNumber, int $optionId): JsonResponse
|
||||
{
|
||||
$order = $request->getOrder();
|
||||
|
||||
// 토큰으로 검증된 주문에 속한 옵션만 확정 가능
|
||||
$option = $order->options()->whereKey($optionId)->first();
|
||||
|
||||
if (! $option) {
|
||||
return ResponseHelper::moduleError('sirsoft-ecommerce', 'exceptions.order_not_found', 404);
|
||||
}
|
||||
|
||||
try {
|
||||
$this->orderService->confirmOption($order, $option);
|
||||
$updatedOrder = $this->orderService->getDetail($order->id);
|
||||
|
||||
return ResponseHelper::success(
|
||||
'sirsoft-ecommerce::messages.order.confirmed',
|
||||
new GuestOrderResource($updatedOrder)
|
||||
);
|
||||
} catch (Exception $e) {
|
||||
Log::error('비회원 구매확정 실패', [
|
||||
'order_number' => $order->order_number,
|
||||
'option_id' => $optionId,
|
||||
'error' => $e->getMessage(),
|
||||
]);
|
||||
|
||||
return ResponseHelper::moduleError(
|
||||
'sirsoft-ecommerce',
|
||||
'exceptions.order_option_cannot_confirm',
|
||||
422
|
||||
);
|
||||
}
|
||||
}
|
||||
}
|
||||
+6
-5
@@ -32,7 +32,7 @@ class ProductController extends PublicBaseController
|
||||
* 전시상태가 visible이고, 판매상태가 on_sale 또는 coming_soon인 상품만 반환합니다.
|
||||
* 정렬: latest(최신순), sales(판매순), price_asc(가격낮은순), price_desc(가격높은순)
|
||||
*
|
||||
* @param Request $request 요청 데이터
|
||||
* @param Request $request 요청 데이터
|
||||
* @return JsonResponse 상품 목록을 포함한 JSON 응답
|
||||
*/
|
||||
public function index(PublicProductListRequest $request): JsonResponse
|
||||
@@ -68,7 +68,7 @@ class ProductController extends PublicBaseController
|
||||
*
|
||||
* 최근 30일 판매량 기준으로 정렬합니다.
|
||||
*
|
||||
* @param Request $request 요청 데이터
|
||||
* @param Request $request 요청 데이터
|
||||
* @return JsonResponse 인기 상품 목록을 포함한 JSON 응답
|
||||
*/
|
||||
public function popular(PublicProductPopularRequest $request): JsonResponse
|
||||
@@ -98,7 +98,7 @@ class ProductController extends PublicBaseController
|
||||
*
|
||||
* 최신 등록순으로 정렬합니다.
|
||||
*
|
||||
* @param Request $request 요청 데이터
|
||||
* @param Request $request 요청 데이터
|
||||
* @return JsonResponse 신상품 목록을 포함한 JSON 응답
|
||||
*/
|
||||
public function new(PublicProductNewRequest $request): JsonResponse
|
||||
@@ -128,7 +128,7 @@ class ProductController extends PublicBaseController
|
||||
*
|
||||
* 클라이언트가 전달한 상품 ID 목록으로 조회합니다.
|
||||
*
|
||||
* @param Request $request 요청 데이터 (ids: 쉼표 구분 상품 ID)
|
||||
* @param Request $request 요청 데이터 (ids: 쉼표 구분 상품 ID)
|
||||
* @return JsonResponse 상품 목록을 포함한 JSON 응답
|
||||
*/
|
||||
public function recent(PublicProductRecentRequest $request): JsonResponse
|
||||
@@ -168,7 +168,7 @@ class ProductController extends PublicBaseController
|
||||
*
|
||||
* 전시상태가 visible인 상품만 조회할 수 있습니다.
|
||||
*
|
||||
* @param int $id 상품 ID
|
||||
* @param int $id 상품 ID
|
||||
* @return JsonResponse 상품 상세 정보를 포함한 JSON 응답
|
||||
*/
|
||||
public function show(int $id): JsonResponse
|
||||
@@ -194,6 +194,7 @@ class ProductController extends PublicBaseController
|
||||
'brand',
|
||||
'activeLabelAssignments.label',
|
||||
'additionalOptions',
|
||||
'additionalOptions.activeValues',
|
||||
'currentUserWishlist',
|
||||
]);
|
||||
|
||||
|
||||
+310
@@ -0,0 +1,310 @@
|
||||
<?php
|
||||
|
||||
namespace Modules\Sirsoft\Ecommerce\Http\Controllers\Traits;
|
||||
|
||||
use App\Extension\HookManager;
|
||||
use App\Helpers\ResponseHelper;
|
||||
use Exception;
|
||||
use Illuminate\Http\JsonResponse;
|
||||
use Illuminate\Http\Resources\Json\JsonResource;
|
||||
use Illuminate\Support\Facades\Log;
|
||||
use Modules\Sirsoft\Ecommerce\Enums\PaymentMethodEnum;
|
||||
use Modules\Sirsoft\Ecommerce\Exceptions\CartUnavailableException;
|
||||
use Modules\Sirsoft\Ecommerce\Exceptions\InsufficientStockException;
|
||||
use Modules\Sirsoft\Ecommerce\Exceptions\OrderProcessingException;
|
||||
use Modules\Sirsoft\Ecommerce\Exceptions\PaymentAmountMismatchException;
|
||||
use Modules\Sirsoft\Ecommerce\Exceptions\UnsupportedPaymentCurrencyException;
|
||||
use Modules\Sirsoft\Ecommerce\Http\Requests\Public\CreateOrderRequest;
|
||||
use Modules\Sirsoft\Ecommerce\Models\Order;
|
||||
use Modules\Sirsoft\Ecommerce\Models\TempOrder;
|
||||
use Modules\Sirsoft\Ecommerce\Services\CurrencyConversionService;
|
||||
use Modules\Sirsoft\Ecommerce\Services\EcommerceSettingsService;
|
||||
|
||||
/**
|
||||
* 주문 생성 공통 흐름 Trait
|
||||
*
|
||||
* 회원/비회원 주문 생성을 단일 endpoint(POST user/orders → Public\OrderController::store)
|
||||
* 에서 처리하는 공통 흐름을 한곳에 둡니다. 임시주문 조회 → 재고 검증 → 주문 생성 →
|
||||
* PG 필요 여부 판단 → 임시주문 삭제 → 응답 조립 → 예외 처리까지 공통이며,
|
||||
* 회원/비회원이 갈리는 부분(응답 Resource, 회원 전용 후처리)만 호출 측 콜백으로 위임합니다.
|
||||
* (회원 컨텍스트는 Auth::id() 로 판정 — userId 가 null 이면 비회원)
|
||||
*
|
||||
* 이 Trait을 사용하는 컨트롤러는 다음 프로퍼티를 생성자 주입으로 보유해야 합니다.
|
||||
* - $tempOrderService (TempOrderService)
|
||||
* - $stockService (StockService)
|
||||
* - $orderProcessingService (OrderProcessingService)
|
||||
*/
|
||||
trait HandlesOrderCreation
|
||||
{
|
||||
/**
|
||||
* 주문 생성 공통 흐름을 수행합니다.
|
||||
*
|
||||
* @param CreateOrderRequest $request 검증된 주문 생성 요청
|
||||
* @param int|null $userId 회원 ID (비회원은 null)
|
||||
* @param callable $buildResponseData 응답 데이터 빌더. 시그니처: fn (Order $order, bool $requiresPg, string $pgProvider): array
|
||||
* @param callable|null $afterCreate 주문 생성 직후 후처리 콜백 (회원 전용 배송지 자동저장 등). 시그니처: fn (Order $order, bool $requiresPg): void
|
||||
* @param string $logEndpoint API 사용량 로그 엔드포인트 식별자
|
||||
* @return JsonResponse 생성된 주문 정보를 포함한 JSON 응답
|
||||
*/
|
||||
protected function processOrderCreation(
|
||||
CreateOrderRequest $request,
|
||||
?int $userId,
|
||||
callable $buildResponseData,
|
||||
?callable $afterCreate = null,
|
||||
string $logEndpoint = 'order.store'
|
||||
): JsonResponse {
|
||||
try {
|
||||
$this->logApiUsage($logEndpoint);
|
||||
|
||||
$cartKey = $request->header('X-Cart-Key');
|
||||
|
||||
// 임시 주문 조회 (회원: user_id 기준, 비회원: cart_key 기준)
|
||||
$tempOrder = $this->tempOrderService->getTempOrder($userId, $cartKey);
|
||||
|
||||
// 임시 주문 없거나 만료된 경우
|
||||
if (! $tempOrder) {
|
||||
return ResponseHelper::moduleError(
|
||||
'sirsoft-ecommerce',
|
||||
'exceptions.temp_order_not_found',
|
||||
404
|
||||
);
|
||||
}
|
||||
|
||||
// 재고 검증
|
||||
$items = $this->buildStockValidationItems($tempOrder);
|
||||
$this->stockService->validateStock($items);
|
||||
|
||||
// 훅: 결제 진입 전 (사용자 본인인증(IDV) 정책 가드 지점 — checkout_verification purpose).
|
||||
// EnforceIdentityPolicyListener 가 'sirsoft-ecommerce.checkout.before_payment' 정책이
|
||||
// 활성이고 grace 만료 시 IdentityVerificationRequiredException(428) 을 throw 한다.
|
||||
// 이 예외는 \Error 를 상속하므로 아래 catch (Exception) 에 걸리지 않고 전파되어 428 이 유지된다.
|
||||
// 주문 레코드 생성(createFromTempOrder) 직전이므로 428 로 막혀도 주문 부산물이 생기지 않는다.
|
||||
HookManager::doAction('sirsoft-ecommerce.checkout.before_payment', $tempOrder, $userId);
|
||||
|
||||
// 주문 생성 (회원/비회원 공통 — TempOrder.user_id 가 주문 user_id 로 그대로 반영)
|
||||
$order = $this->orderProcessingService->createFromTempOrder(
|
||||
tempOrder: $tempOrder,
|
||||
ordererInfo: $request->getOrdererInfo(),
|
||||
shippingInfo: $request->getShippingInfo(),
|
||||
paymentMethod: $request->input('payment_method'),
|
||||
expectedTotalAmount: (float) $request->input('expected_total_amount'),
|
||||
shippingMemo: $request->input('shipping_memo'),
|
||||
depositorName: $request->input('depositor_name'),
|
||||
dbankInfo: $request->getDbankInfo(),
|
||||
guestLookupPassword: $request->getGuestLookupPassword()
|
||||
);
|
||||
|
||||
$order->load(['options', 'payment', 'shippingAddress']);
|
||||
|
||||
// PG 결제 필요 여부 판단
|
||||
$paymentMethod = PaymentMethodEnum::tryFrom($order->payment->payment_method->value ?? $order->payment->payment_method);
|
||||
$pgProvider = $this->orderProcessingService->determinePgProvider($paymentMethod->value);
|
||||
$requiresPg = $paymentMethod->needsPgProvider()
|
||||
&& ! in_array($pgProvider, ['manual', 'internal', 'none'])
|
||||
// 결제할 금액이 0원이면(전액 마일리지/예치금 등 비현금 충당) PG 호출 불필요 —
|
||||
// 주문 생성 시점에 이미 결제완료 확정됨. 결제수단 선택과 무관.
|
||||
&& (int) $order->total_due_amount > 0;
|
||||
|
||||
// 임시 주문 삭제: non-PG 만 즉시 삭제, PG 결제는 completePayment() 시점에 삭제
|
||||
if (! $requiresPg) {
|
||||
$this->tempOrderService->deleteTempOrder($userId, $cartKey);
|
||||
}
|
||||
|
||||
// 생성 직후 후처리 (회원 전용 배송지 자동저장 등) — 호출 측 위임
|
||||
if ($afterCreate !== null) {
|
||||
$afterCreate($order, $requiresPg);
|
||||
}
|
||||
|
||||
// 응답 데이터 조립 — 회원/비회원 응답 Resource 차이는 호출 측 위임
|
||||
$responseData = $buildResponseData($order, $requiresPg, $pgProvider);
|
||||
|
||||
return ResponseHelper::success('sirsoft-ecommerce::messages.order.created', $responseData, 201);
|
||||
|
||||
} catch (PaymentAmountMismatchException $e) {
|
||||
return ResponseHelper::error(
|
||||
__('sirsoft-ecommerce::exceptions.payment_amount_mismatch', [
|
||||
'expected' => number_format($e->getExpectedAmount()),
|
||||
'actual' => number_format($e->getActualAmount()),
|
||||
]),
|
||||
422
|
||||
);
|
||||
|
||||
} catch (UnsupportedPaymentCurrencyException $e) {
|
||||
// 결제 통화로 청구 불가(환율 미설정/0 또는 환산액 0) — 명확한 422 차단
|
||||
return ResponseHelper::error(
|
||||
'sirsoft-ecommerce::exceptions.unsupported_payment_currency',
|
||||
422,
|
||||
['code' => 'unsupported_payment_currency', 'currency' => $e->getCurrency()],
|
||||
['currency' => $e->getCurrency()]
|
||||
);
|
||||
|
||||
} catch (InsufficientStockException $e) {
|
||||
return ResponseHelper::error(
|
||||
'sirsoft-ecommerce::exceptions.order_create_failed',
|
||||
422,
|
||||
[
|
||||
'detail' => $e->getMessage(),
|
||||
'insufficient_items' => $e->getInsufficientItems(),
|
||||
]
|
||||
);
|
||||
|
||||
} catch (CartUnavailableException $e) {
|
||||
// 구매 대상 제한 등으로 구매 불가 상품이 있는 경우 (회원/비회원 공통)
|
||||
$messageKey = $e->hasRestrictionIssue()
|
||||
? 'sirsoft-ecommerce::exceptions.purchase_not_allowed'
|
||||
: 'sirsoft-ecommerce::exceptions.cart_unavailable';
|
||||
|
||||
return ResponseHelper::error(__($messageKey), 422, [
|
||||
'code' => 'cart_unavailable',
|
||||
'unavailable_items' => $e->getUnavailableItems(),
|
||||
'has_stock_issue' => $e->hasStockIssue(),
|
||||
'has_status_issue' => $e->hasStatusIssue(),
|
||||
'has_restriction_issue' => $e->hasRestrictionIssue(),
|
||||
]);
|
||||
|
||||
} catch (OrderProcessingException $e) {
|
||||
// 주문 확정 재계산 검증 실패(쿠폰 만료/min_amount/per_user_limit/not_combinable 등)
|
||||
// generic 500 이 아닌 422 로 하드 차단 — 서버 우회 방지 (U14/MP06)
|
||||
Log::warning('Order create: calculation validation failed', [
|
||||
'message' => $e->getMessage(),
|
||||
]);
|
||||
|
||||
return ResponseHelper::error(
|
||||
'sirsoft-ecommerce::exceptions.order_calculation_validation_failed',
|
||||
422,
|
||||
['code' => 'order_calculation_validation_failed']
|
||||
);
|
||||
|
||||
} catch (Exception $e) {
|
||||
return ResponseHelper::moduleError(
|
||||
'sirsoft-ecommerce',
|
||||
'messages.order.create_failed',
|
||||
500
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* 주문 생성 응답에 포함할 기본 응답 데이터를 구성합니다.
|
||||
*
|
||||
* 회원/비회원 컨트롤러가 응답 Resource(OrderResource / GuestOrderResource)를
|
||||
* 주입해 공통 메타(redirect_url, requires_pg_payment, PG 데이터)와 합칩니다.
|
||||
*
|
||||
* @param Order $order 생성된 주문
|
||||
* @param bool $requiresPg PG 결제 필요 여부
|
||||
* @param string $pgProvider PG 공급자 식별자
|
||||
* @param JsonResource $orderResource 주문 응답 리소스
|
||||
* @return array 응답 데이터
|
||||
*/
|
||||
protected function buildOrderResponseData(Order $order, bool $requiresPg, string $pgProvider, $orderResource): array
|
||||
{
|
||||
$responseData = [
|
||||
'order' => $orderResource,
|
||||
'redirect_url' => "/shop/orders/{$order->order_number}/complete",
|
||||
'requires_pg_payment' => $requiresPg,
|
||||
];
|
||||
|
||||
if ($requiresPg) {
|
||||
$responseData['pg_provider'] = "sirsoft-{$pgProvider}";
|
||||
$responseData['pg_payment_data'] = $this->buildPgPaymentData($order);
|
||||
|
||||
// provider-agnostic 결제 진입 — provider 레지스트리가 선언한 프론트 결제 진입
|
||||
// 핸들러 풀네임을 응답에 그대로 내려 템플릿이 dispatch 한다. provider 가 핸들러를
|
||||
// 선언하지 않으면 키를 설정하지 않아(템플릿 PG 분기 미발화) non-PG fallback 으로
|
||||
// 안전 강하한다.
|
||||
$paymentHandler = $this->resolvePgPaymentHandler($pgProvider);
|
||||
if ($paymentHandler !== null) {
|
||||
$responseData['pg_payment_handler'] = $paymentHandler;
|
||||
}
|
||||
}
|
||||
|
||||
return $responseData;
|
||||
}
|
||||
|
||||
/**
|
||||
* PG provider 의 프론트 결제 진입 핸들러 풀네임을 레지스트리에서 조회합니다.
|
||||
*
|
||||
* PG 플러그인이 `sirsoft-ecommerce.payment.registered_pg_providers` 필터 훅에 등록한
|
||||
* provider 엔트리의 `payment_handler` 키를 반환합니다. 미선언 시 null.
|
||||
*
|
||||
* @param string $pgProvider PG provider id (예: 'kginicis')
|
||||
* @return string|null 프론트 결제 진입 핸들러 풀네임 또는 null
|
||||
*/
|
||||
protected function resolvePgPaymentHandler(string $pgProvider): ?string
|
||||
{
|
||||
$providers = app(EcommerceSettingsService::class)->getRegisteredPgProviders();
|
||||
|
||||
foreach ($providers as $provider) {
|
||||
if (($provider['id'] ?? null) === $pgProvider) {
|
||||
$handler = $provider['payment_handler'] ?? null;
|
||||
|
||||
return is_string($handler) && $handler !== '' ? $handler : null;
|
||||
}
|
||||
}
|
||||
|
||||
return null;
|
||||
}
|
||||
|
||||
/**
|
||||
* 재고 검증용 아이템 목록 생성
|
||||
*
|
||||
* @param TempOrder $tempOrder 임시 주문
|
||||
* @return array 재고 검증용 아이템 배열
|
||||
*/
|
||||
protected function buildStockValidationItems(TempOrder $tempOrder): array
|
||||
{
|
||||
$items = [];
|
||||
$calculationResult = $tempOrder->calculation_result ?? [];
|
||||
|
||||
foreach ($calculationResult['items'] ?? [] as $item) {
|
||||
$items[] = [
|
||||
'product_option_id' => $item['productOptionId'] ?? $item['product_option_id'],
|
||||
'quantity' => $item['quantity'],
|
||||
];
|
||||
}
|
||||
|
||||
return $items;
|
||||
}
|
||||
|
||||
/**
|
||||
* PG 결제용 데이터 생성
|
||||
*
|
||||
* 주문 생성 API 응답에 포함될 PG 결제 요청 데이터를 빌드합니다.
|
||||
*
|
||||
* @param Order $order 주문
|
||||
* @return array PG 결제 요청 데이터
|
||||
*/
|
||||
protected function buildPgPaymentData(Order $order): array
|
||||
{
|
||||
// 주문명 생성 (로컬라이즈된 첫 번째 상품명 + 외 N건)
|
||||
$options = $order->options;
|
||||
$locale = app()->getLocale();
|
||||
$firstName = $options->first()?->product_name;
|
||||
$orderName = is_array($firstName)
|
||||
? ($firstName[$locale] ?? $firstName[config('app.fallback_locale', 'ko')] ?? reset($firstName) ?: '')
|
||||
: ($firstName ?? '');
|
||||
if ($options->count() > 1) {
|
||||
$orderName .= ' 외 '.($options->count() - 1).'건';
|
||||
}
|
||||
|
||||
// 주문자 정보 (배송지 주소에서 가져옴)
|
||||
$shippingAddress = $order->shippingAddress;
|
||||
|
||||
// PG 청구 금액/통화 = base total_due_amount 를 주문 스냅샷 환율로 결제 통화 환산.
|
||||
// amount 는 PG 가 요구하는 최소 화폐단위 정수(KRW 7058 / USD $6→600 / JPY 정수).
|
||||
// 미지원 통화(환율 0/미설정)는 resolveSnapshotPaymentCharge 가 InvalidArgumentException 으로 차단.
|
||||
$charge = app(CurrencyConversionService::class)
|
||||
->resolveSnapshotPaymentCharge((float) $order->total_due_amount, $order->currency_snapshot ?? []);
|
||||
|
||||
return [
|
||||
'order_number' => $order->order_number,
|
||||
'order_name' => $orderName,
|
||||
'amount' => $charge['minor_unit_amount'],
|
||||
'currency' => $charge['currency'],
|
||||
'customer_name' => $shippingAddress?->orderer_name,
|
||||
'customer_email' => $shippingAddress?->orderer_email,
|
||||
'customer_phone' => preg_replace('/[^0-9]/', '', $shippingAddress?->orderer_phone ?? ''),
|
||||
'customer_key' => $order->user_id ? "user_{$order->user_id}" : null,
|
||||
];
|
||||
}
|
||||
}
|
||||
@@ -8,39 +8,32 @@ use Exception;
|
||||
use Illuminate\Http\JsonResponse;
|
||||
use Illuminate\Support\Facades\Auth;
|
||||
use Illuminate\Support\Facades\Log;
|
||||
use Modules\Sirsoft\Ecommerce\Exceptions\InsufficientStockException;
|
||||
use Modules\Sirsoft\Ecommerce\Exceptions\PaymentAmountMismatchException;
|
||||
use Modules\Sirsoft\Ecommerce\Http\Requests\Public\CreateOrderRequest;
|
||||
use Modules\Sirsoft\Ecommerce\Http\Requests\User\CancelOrderRequest;
|
||||
use Modules\Sirsoft\Ecommerce\Http\Requests\User\CancelPaymentRequest;
|
||||
use Modules\Sirsoft\Ecommerce\Http\Requests\User\ConfirmOrderOptionRequest;
|
||||
use Modules\Sirsoft\Ecommerce\Http\Requests\User\EstimateRefundRequest;
|
||||
use Modules\Sirsoft\Ecommerce\Http\Requests\User\UpdateOrderShippingAddressRequest;
|
||||
use Modules\Sirsoft\Ecommerce\Http\Requests\User\UserOrderListRequest;
|
||||
use Modules\Sirsoft\Ecommerce\Enums\PaymentMethodEnum;
|
||||
use Modules\Sirsoft\Ecommerce\Http\Resources\OrderResource;
|
||||
use Modules\Sirsoft\Ecommerce\Http\Resources\UserOrderCollection;
|
||||
use Modules\Sirsoft\Ecommerce\Services\CartService;
|
||||
use Modules\Sirsoft\Ecommerce\Services\OrderCancellationService;
|
||||
use Modules\Sirsoft\Ecommerce\Services\OrderProcessingService;
|
||||
use Modules\Sirsoft\Ecommerce\Services\OrderService;
|
||||
use Modules\Sirsoft\Ecommerce\Services\StockService;
|
||||
use Modules\Sirsoft\Ecommerce\Services\TempOrderService;
|
||||
use Modules\Sirsoft\Ecommerce\Services\UserAddressService;
|
||||
|
||||
/**
|
||||
* 사용자 주문 컨트롤러
|
||||
* 회원 마이페이지 주문 컨트롤러
|
||||
*
|
||||
* 마이페이지 주문 관련 API를 제공합니다.
|
||||
* 마이페이지(인증 필수) 주문 관련 API를 제공합니다. 회원/비회원 공유 액션
|
||||
* (주문 생성, 주문번호로 상세 조회, PG 결제창 닫기 기록)과 비회원 토큰 후속 액션은
|
||||
* Public\OrderController 가 담당합니다.
|
||||
*
|
||||
* 본 컨트롤러는 AuthBaseController 상속으로 모든 메서드에 auth:sanctum 이 강제 적용됩니다.
|
||||
*/
|
||||
class OrderController extends AuthBaseController
|
||||
{
|
||||
public function __construct(
|
||||
private OrderProcessingService $orderProcessingService,
|
||||
private OrderCancellationService $cancellationService,
|
||||
private OrderService $orderService,
|
||||
private TempOrderService $tempOrderService,
|
||||
private StockService $stockService,
|
||||
private UserAddressService $userAddressService
|
||||
private CartService $cartService
|
||||
) {}
|
||||
|
||||
/**
|
||||
@@ -49,7 +42,7 @@ class OrderController extends AuthBaseController
|
||||
* 마이페이지 주문내역에서 사용됩니다.
|
||||
* 본인의 주문만 조회하며, 상태별 통계를 포함합니다.
|
||||
*
|
||||
* @param UserOrderListRequest $request 검증된 요청 데이터
|
||||
* @param UserOrderListRequest $request 검증된 요청 데이터
|
||||
* @return JsonResponse 주문 목록 및 통계
|
||||
*/
|
||||
public function index(UserOrderListRequest $request): JsonResponse
|
||||
@@ -79,7 +72,7 @@ class OrderController extends AuthBaseController
|
||||
* 마이페이지 주문 상세에서 사용됩니다.
|
||||
* 본인의 주문만 조회 가능합니다.
|
||||
*
|
||||
* @param int $id 주문 ID
|
||||
* @param int $id 주문 ID
|
||||
* @return JsonResponse 주문 상세 정보
|
||||
*/
|
||||
public function show(int $id): JsonResponse
|
||||
@@ -99,204 +92,6 @@ class OrderController extends AuthBaseController
|
||||
return ResponseHelper::success('sirsoft-ecommerce::messages.orders.retrieved', new OrderResource($order));
|
||||
}
|
||||
|
||||
/**
|
||||
* 주문번호로 주문 상세 조회
|
||||
*
|
||||
* 주문 완료 페이지에서 사용됩니다.
|
||||
* 본인의 주문만 조회 가능합니다.
|
||||
*
|
||||
* @param string $orderNumber 주문번호
|
||||
* @return JsonResponse 주문 상세 정보
|
||||
*/
|
||||
public function showByOrderNumber(string $orderNumber): JsonResponse
|
||||
{
|
||||
$this->logApiUsage('user.orders.show-by-number');
|
||||
|
||||
$order = $this->orderService->getByOrderNumber($orderNumber);
|
||||
|
||||
if (! $order || $order->user_id !== Auth::id()) {
|
||||
return ResponseHelper::moduleError(
|
||||
'sirsoft-ecommerce',
|
||||
'exceptions.order_not_found',
|
||||
404
|
||||
);
|
||||
}
|
||||
|
||||
return ResponseHelper::success('sirsoft-ecommerce::messages.orders.retrieved', new OrderResource($order));
|
||||
}
|
||||
|
||||
/**
|
||||
* 주문 생성 (결제하기)
|
||||
*
|
||||
* 임시 주문을 실제 주문으로 변환합니다.
|
||||
*
|
||||
* @param CreateOrderRequest $request 검증된 요청 데이터
|
||||
* @return JsonResponse 생성된 주문 정보를 포함한 JSON 응답
|
||||
*/
|
||||
public function store(CreateOrderRequest $request): JsonResponse
|
||||
{
|
||||
try {
|
||||
$this->logApiUsage('user.orders.store');
|
||||
|
||||
$userId = Auth::id();
|
||||
$cartKey = $request->header('X-Cart-Key');
|
||||
|
||||
// 임시 주문 조회
|
||||
$tempOrder = $this->tempOrderService->getTempOrder($userId, $cartKey);
|
||||
|
||||
// 임시 주문 없거나 만료된 경우 (findValidByUserOrCartKey에서 만료된 주문은 null 반환)
|
||||
if (! $tempOrder) {
|
||||
return ResponseHelper::moduleError(
|
||||
'sirsoft-ecommerce',
|
||||
'exceptions.temp_order_not_found',
|
||||
404
|
||||
);
|
||||
}
|
||||
|
||||
// 재고 검증
|
||||
$items = $this->buildStockValidationItems($tempOrder);
|
||||
$this->stockService->validateStock($items);
|
||||
|
||||
// 주문 생성
|
||||
$order = $this->orderProcessingService->createFromTempOrder(
|
||||
tempOrder: $tempOrder,
|
||||
ordererInfo: $request->getOrdererInfo(),
|
||||
shippingInfo: $request->getShippingInfo(),
|
||||
paymentMethod: $request->input('payment_method'),
|
||||
expectedTotalAmount: (float) $request->input('expected_total_amount'),
|
||||
shippingMemo: $request->input('shipping_memo'),
|
||||
depositorName: $request->input('depositor_name'),
|
||||
dbankInfo: $request->getDbankInfo()
|
||||
);
|
||||
|
||||
$order->load(['options', 'payment', 'shippingAddress']);
|
||||
|
||||
// PG 결제 필요 여부 판단
|
||||
$paymentMethod = PaymentMethodEnum::tryFrom($order->payment->payment_method->value ?? $order->payment->payment_method);
|
||||
$pgProvider = $this->orderProcessingService->determinePgProvider($paymentMethod->value);
|
||||
$requiresPg = $paymentMethod->needsPgProvider()
|
||||
&& ! in_array($pgProvider, ['manual', 'internal', 'none']);
|
||||
|
||||
// 임시 주문 삭제: non-PG만 즉시 삭제, PG 결제는 completePayment() 시점에 삭제
|
||||
if (! $requiresPg) {
|
||||
$this->tempOrderService->deleteTempOrder($userId, $cartKey);
|
||||
}
|
||||
|
||||
// 배송지 자동 저장 처리
|
||||
if ($userId && $request->boolean('save_shipping_address')) {
|
||||
if (! $requiresPg) {
|
||||
// 비PG 결제: 즉시 배송지 저장
|
||||
try {
|
||||
$name = $this->userAddressService->generateUniqueName(
|
||||
$userId,
|
||||
__('sirsoft-ecommerce::messages.address.auto_saved_label')
|
||||
);
|
||||
$shippingInfo = $request->getShippingInfo();
|
||||
$this->userAddressService->createAddress([
|
||||
'user_id' => $userId,
|
||||
'name' => $name,
|
||||
'recipient_name' => $shippingInfo['recipient_name'] ?? '',
|
||||
'recipient_phone' => $shippingInfo['recipient_phone'] ?? '',
|
||||
'country_code' => $shippingInfo['country_code'] ?? 'KR',
|
||||
'zipcode' => $shippingInfo['zipcode'] ?? $shippingInfo['intl_postal_code'] ?? '',
|
||||
'address' => $shippingInfo['address'] ?? $shippingInfo['address_line_1'] ?? '',
|
||||
'address_detail' => $shippingInfo['address_detail'] ?? $shippingInfo['address_line_2'] ?? '',
|
||||
'region' => $shippingInfo['region'] ?? $shippingInfo['intl_state'] ?? '',
|
||||
'city' => $shippingInfo['city'] ?? $shippingInfo['intl_city'] ?? '',
|
||||
]);
|
||||
} catch (Exception $e) {
|
||||
Log::warning('Auto save shipping address failed on order creation', [
|
||||
'user_id' => $userId,
|
||||
'order_id' => $order->id,
|
||||
'message' => $e->getMessage(),
|
||||
]);
|
||||
}
|
||||
} else {
|
||||
// PG 결제: order_meta에 플래그 저장 (completePayment 시점에 처리)
|
||||
$order->update([
|
||||
'order_meta' => array_merge($order->order_meta ?? [], [
|
||||
'save_shipping_address' => true,
|
||||
'shipping_info_for_save' => $request->getShippingInfo(),
|
||||
]),
|
||||
]);
|
||||
}
|
||||
}
|
||||
|
||||
$responseData = [
|
||||
'order' => new OrderResource($order),
|
||||
'redirect_url' => "/shop/orders/{$order->order_number}/complete",
|
||||
'requires_pg_payment' => $requiresPg,
|
||||
];
|
||||
|
||||
if ($requiresPg) {
|
||||
$responseData['pg_provider'] = "sirsoft-{$pgProvider}";
|
||||
$responseData['pg_payment_data'] = $this->buildPgPaymentData($order);
|
||||
}
|
||||
|
||||
return ResponseHelper::success('sirsoft-ecommerce::messages.order.created', $responseData, 201);
|
||||
|
||||
} catch (PaymentAmountMismatchException $e) {
|
||||
Log::warning('Order creation failed: amount mismatch', [
|
||||
'expected' => $e->getExpectedAmount(),
|
||||
'actual' => $e->getActualAmount(),
|
||||
'user_id' => Auth::id(),
|
||||
]);
|
||||
|
||||
return ResponseHelper::error(
|
||||
__('sirsoft-ecommerce::exceptions.payment_amount_mismatch', [
|
||||
'expected' => number_format($e->getExpectedAmount()),
|
||||
'actual' => number_format($e->getActualAmount()),
|
||||
]),
|
||||
422
|
||||
);
|
||||
|
||||
} catch (InsufficientStockException $e) {
|
||||
Log::warning('Order creation failed: insufficient stock', [
|
||||
'message' => $e->getMessage(),
|
||||
'user_id' => Auth::id(),
|
||||
]);
|
||||
|
||||
return ResponseHelper::error($e->getMessage(), 422);
|
||||
|
||||
} catch (Exception $e) {
|
||||
Log::error('Order creation failed', [
|
||||
'message' => $e->getMessage(),
|
||||
'file' => $e->getFile(),
|
||||
'line' => $e->getLine(),
|
||||
'trace' => $e->getTraceAsString(),
|
||||
'user_id' => Auth::id(),
|
||||
]);
|
||||
|
||||
return ResponseHelper::moduleError(
|
||||
'sirsoft-ecommerce',
|
||||
'messages.order.create_failed',
|
||||
500
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* 결제 취소 기록 (결제창 닫기)
|
||||
*
|
||||
* 유저가 PG 결제창을 닫았을 때 호출됩니다.
|
||||
* 주문 상태는 변경하지 않고, order_payments에 취소 이력만 기록합니다.
|
||||
*
|
||||
* @param CancelPaymentRequest $request 검증된 요청 데이터
|
||||
* @return JsonResponse
|
||||
*/
|
||||
public function cancelPayment(CancelPaymentRequest $request): JsonResponse
|
||||
{
|
||||
$this->logApiUsage('user.orders.cancel-payment');
|
||||
|
||||
$this->orderProcessingService->recordPaymentCancellation(
|
||||
$request->getOrder(),
|
||||
$request->validated('cancel_code'),
|
||||
$request->validated('cancel_message')
|
||||
);
|
||||
|
||||
return ResponseHelper::success('sirsoft-ecommerce::messages.order.payment_cancelled');
|
||||
}
|
||||
|
||||
/**
|
||||
* 주문 취소 (마이페이지)
|
||||
*
|
||||
@@ -305,7 +100,7 @@ class OrderController extends AuthBaseController
|
||||
* items 파라미터가 있으면 부분취소, 없으면 전체취소로 처리합니다.
|
||||
*
|
||||
* @param CancelOrderRequest $request 검증된 요청 데이터
|
||||
* @return JsonResponse
|
||||
* @return JsonResponse 취소 후 주문 상세
|
||||
*/
|
||||
public function cancel(CancelOrderRequest $request): JsonResponse
|
||||
{
|
||||
@@ -347,7 +142,10 @@ class OrderController extends AuthBaseController
|
||||
'error' => $e->getMessage(),
|
||||
]);
|
||||
|
||||
return ResponseHelper::error($e->getMessage(), 422);
|
||||
return ResponseHelper::error(
|
||||
'sirsoft-ecommerce::exceptions.order_cancel_failed',
|
||||
422
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
@@ -355,7 +153,7 @@ class OrderController extends AuthBaseController
|
||||
* 환불 예상금액을 조회합니다. (마이페이지)
|
||||
*
|
||||
* @param EstimateRefundRequest $request 환불 예상 요청 데이터
|
||||
* @return JsonResponse
|
||||
* @return JsonResponse 환불 예상 결과
|
||||
*/
|
||||
public function estimateRefund(EstimateRefundRequest $request): JsonResponse
|
||||
{
|
||||
@@ -378,16 +176,19 @@ class OrderController extends AuthBaseController
|
||||
'error' => $e->getMessage(),
|
||||
]);
|
||||
|
||||
return ResponseHelper::error($e->getMessage(), 500);
|
||||
return ResponseHelper::error(
|
||||
'sirsoft-ecommerce::exceptions.order_estimate_refund_failed',
|
||||
500
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* 주문 배송지 변경
|
||||
*
|
||||
* @param UpdateOrderShippingAddressRequest $request 검증된 배송지 데이터
|
||||
* @param int $id 주문 ID
|
||||
* @return JsonResponse
|
||||
* @param UpdateOrderShippingAddressRequest $request 검증된 배송지 데이터
|
||||
* @param int $id 주문 ID
|
||||
* @return JsonResponse 배송지 변경 후 주문 상세
|
||||
*/
|
||||
public function updateShippingAddress(UpdateOrderShippingAddressRequest $request, int $id): JsonResponse
|
||||
{
|
||||
@@ -410,7 +211,7 @@ class OrderController extends AuthBaseController
|
||||
return ResponseHelper::success('sirsoft-ecommerce::messages.orders.shipping_address_updated', [
|
||||
'order' => new OrderResource($order),
|
||||
]);
|
||||
} catch (\Exception $e) {
|
||||
} catch (Exception $e) {
|
||||
Log::error('Order shipping address update failed', [
|
||||
'message' => $e->getMessage(),
|
||||
'order_id' => $id,
|
||||
@@ -430,8 +231,8 @@ class OrderController extends AuthBaseController
|
||||
*
|
||||
* 마이페이지에서 개별 주문 옵션을 구매확정합니다.
|
||||
*
|
||||
* @param ConfirmOrderOptionRequest $request 구매확정 요청
|
||||
* @return JsonResponse
|
||||
* @param ConfirmOrderOptionRequest $request 구매확정 요청
|
||||
* @return JsonResponse 구매확정 후 주문 상세
|
||||
*/
|
||||
public function confirmOption(ConfirmOrderOptionRequest $request): JsonResponse
|
||||
{
|
||||
@@ -448,7 +249,7 @@ class OrderController extends AuthBaseController
|
||||
'sirsoft-ecommerce::messages.order.confirmed',
|
||||
['order' => new OrderResource($updatedOrder)]
|
||||
);
|
||||
} catch (\Exception $e) {
|
||||
} catch (Exception $e) {
|
||||
Log::error('Order option confirm failed', [
|
||||
'message' => $e->getMessage(),
|
||||
'order_id' => $request->route('id'),
|
||||
@@ -465,59 +266,38 @@ class OrderController extends AuthBaseController
|
||||
}
|
||||
|
||||
/**
|
||||
* 재고 검증용 아이템 목록 생성
|
||||
* 과거 주문 → 장바구니 재추가 (재주문)
|
||||
*
|
||||
* @param \Modules\Sirsoft\Ecommerce\Models\TempOrder $tempOrder 임시 주문
|
||||
* @return array 재고 검증용 아이템 배열
|
||||
* 사용자의 과거 주문 (취소된 주문 포함) 의 옵션을 현재 장바구니에 추가합니다.
|
||||
* 품절/단종 등으로 추가 불가한 항목은 skip 하고 skipped 배열로 반환합니다.
|
||||
*
|
||||
* @param int $id 주문 ID
|
||||
* @return JsonResponse {added_count, skipped[], cart_count}
|
||||
*/
|
||||
protected function buildStockValidationItems($tempOrder): array
|
||||
public function reorder(int $id): JsonResponse
|
||||
{
|
||||
$items = [];
|
||||
$calculationResult = $tempOrder->calculation_result ?? [];
|
||||
$this->logApiUsage('user.orders.reorder', ['order_id' => $id]);
|
||||
|
||||
foreach ($calculationResult['items'] ?? [] as $item) {
|
||||
$items[] = [
|
||||
'product_option_id' => $item['productOptionId'] ?? $item['product_option_id'],
|
||||
'quantity' => $item['quantity'],
|
||||
];
|
||||
try {
|
||||
$userId = Auth::id();
|
||||
$result = $this->cartService->reorderFromOrder($id, (int) $userId);
|
||||
|
||||
return ResponseHelper::success(
|
||||
'sirsoft-ecommerce::messages.cart.reorder_added',
|
||||
$result
|
||||
);
|
||||
} catch (Exception $e) {
|
||||
Log::error('Order reorder failed', [
|
||||
'message' => $e->getMessage(),
|
||||
'order_id' => $id,
|
||||
'user_id' => Auth::id(),
|
||||
]);
|
||||
|
||||
return ResponseHelper::moduleError(
|
||||
'sirsoft-ecommerce',
|
||||
'messages.cart.reorder_failed',
|
||||
422
|
||||
);
|
||||
}
|
||||
|
||||
return $items;
|
||||
}
|
||||
|
||||
/**
|
||||
* PG 결제용 데이터 생성
|
||||
*
|
||||
* 주문 생성 API 응답에 포함될 PG 결제 요청 데이터를 빌드합니다.
|
||||
*
|
||||
* @param \Modules\Sirsoft\Ecommerce\Models\Order $order 주문
|
||||
* @return array PG 결제 요청 데이터
|
||||
*/
|
||||
protected function buildPgPaymentData($order): array
|
||||
{
|
||||
// 주문명 생성 (로컬라이즈된 첫 번째 상품명 + 외 N건)
|
||||
$options = $order->options;
|
||||
$locale = app()->getLocale();
|
||||
$firstName = $options->first()?->product_name;
|
||||
$orderName = is_array($firstName)
|
||||
? ($firstName[$locale] ?? $firstName[config('app.fallback_locale', 'ko')] ?? reset($firstName) ?: '')
|
||||
: ($firstName ?? '');
|
||||
if ($options->count() > 1) {
|
||||
$orderName .= ' 외 ' . ($options->count() - 1) . '건';
|
||||
}
|
||||
|
||||
// 주문자 정보 (배송지 주소에서 가져옴)
|
||||
$shippingAddress = $order->shippingAddress;
|
||||
|
||||
return [
|
||||
'order_number' => $order->order_number,
|
||||
'order_name' => $orderName,
|
||||
'amount' => (int) $order->total_due_amount,
|
||||
'currency' => $order->currency_snapshot['order_currency'] ?? 'KRW',
|
||||
'customer_name' => $shippingAddress?->orderer_name,
|
||||
'customer_email' => $shippingAddress?->orderer_email,
|
||||
'customer_phone' => preg_replace('/[^0-9]/', '', $shippingAddress?->orderer_phone ?? ''),
|
||||
'customer_key' => $order->user_id ? "user_{$order->user_id}" : null,
|
||||
];
|
||||
}
|
||||
}
|
||||
+69
@@ -0,0 +1,69 @@
|
||||
<?php
|
||||
|
||||
namespace Modules\Sirsoft\Ecommerce\Http\Controllers\User;
|
||||
|
||||
use App\Helpers\ResponseHelper;
|
||||
use App\Http\Controllers\Api\Base\AuthBaseController;
|
||||
use Exception;
|
||||
use Illuminate\Http\JsonResponse;
|
||||
use Illuminate\Support\Facades\Auth;
|
||||
use Illuminate\Support\Facades\Log;
|
||||
use Modules\Sirsoft\Ecommerce\Http\Requests\User\UpdateUserCurrencyRequest;
|
||||
use Modules\Sirsoft\Ecommerce\Services\UserCurrencyService;
|
||||
|
||||
/**
|
||||
* 사용자 결제 통화 컨트롤러 (A3)
|
||||
*
|
||||
* 마이페이지 통화 설정 / 회원정보 수정에서 유저별 영속 통화를 조회·저장합니다.
|
||||
*/
|
||||
class UserCurrencyController extends AuthBaseController
|
||||
{
|
||||
public function __construct(
|
||||
private UserCurrencyService $userCurrencyService
|
||||
) {}
|
||||
|
||||
/**
|
||||
* 현재 사용자의 선호 통화를 조회합니다.
|
||||
*
|
||||
* @return JsonResponse 선호 통화 코드(미설정 시 null)를 포함한 JSON 응답
|
||||
*/
|
||||
public function show(): JsonResponse
|
||||
{
|
||||
$userId = (int) Auth::id();
|
||||
|
||||
return ResponseHelper::success('sirsoft-ecommerce::messages.user_currency.fetched', [
|
||||
'preferred_currency' => $this->userCurrencyService->getPreferredCurrency($userId),
|
||||
]);
|
||||
}
|
||||
|
||||
/**
|
||||
* 현재 사용자의 선호 통화를 저장합니다.
|
||||
*
|
||||
* @param UpdateUserCurrencyRequest $request 검증된 요청(등록 통화만 허용)
|
||||
* @return JsonResponse 저장 결과 JSON 응답
|
||||
*/
|
||||
public function update(UpdateUserCurrencyRequest $request): JsonResponse
|
||||
{
|
||||
try {
|
||||
$userId = (int) Auth::id();
|
||||
$currency = $request->validated('currency');
|
||||
|
||||
$this->userCurrencyService->setPreferredCurrency($userId, $currency);
|
||||
|
||||
return ResponseHelper::success('sirsoft-ecommerce::messages.user_currency.updated', [
|
||||
'preferred_currency' => $currency,
|
||||
]);
|
||||
} catch (Exception $e) {
|
||||
Log::error('User currency update failed', [
|
||||
'message' => $e->getMessage(),
|
||||
'user_id' => Auth::id(),
|
||||
]);
|
||||
|
||||
return ResponseHelper::moduleError(
|
||||
'sirsoft-ecommerce',
|
||||
'messages.user_currency.update_failed',
|
||||
500
|
||||
);
|
||||
}
|
||||
}
|
||||
}
|
||||
+28
-1
@@ -7,7 +7,9 @@ use App\Http\Controllers\Api\Base\AuthBaseController;
|
||||
use Exception;
|
||||
use Illuminate\Http\JsonResponse;
|
||||
use Illuminate\Support\Facades\Auth;
|
||||
use Modules\Sirsoft\Ecommerce\Http\Requests\User\UserMileageHistoryRequest;
|
||||
use Modules\Sirsoft\Ecommerce\Http\Requests\User\UserMileageMaxUsableRequest;
|
||||
use Modules\Sirsoft\Ecommerce\Http\Resources\MileageTransactionCollection;
|
||||
use Modules\Sirsoft\Ecommerce\Services\UserMileageService;
|
||||
|
||||
/**
|
||||
@@ -49,7 +51,7 @@ class UserMileageController extends AuthBaseController
|
||||
/**
|
||||
* 체크아웃에서 사용 가능한 최대 마일리지 조회
|
||||
*
|
||||
* @param Request $request 요청 데이터
|
||||
* @param Request $request 요청 데이터
|
||||
* @return JsonResponse 사용 가능한 최대 마일리지를 포함한 JSON 응답
|
||||
*/
|
||||
public function maxUsable(UserMileageMaxUsableRequest $request): JsonResponse
|
||||
@@ -75,4 +77,29 @@ class UserMileageController extends AuthBaseController
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* 마이페이지 마일리지 내역 조회 (4분류 필터)
|
||||
*
|
||||
* @param Request $request 요청 (category, per_page)
|
||||
* @return JsonResponse 마일리지 내역
|
||||
*/
|
||||
public function history(UserMileageHistoryRequest $request): JsonResponse
|
||||
{
|
||||
$this->logApiUsage('user.mileage.history');
|
||||
|
||||
$userId = Auth::id();
|
||||
$validated = $request->validated();
|
||||
$filters = [
|
||||
'category' => $validated['category'] ?? null,
|
||||
'currency' => $validated['currency'] ?? null,
|
||||
];
|
||||
$perPage = (int) ($validated['per_page'] ?? 20);
|
||||
|
||||
$transactions = $this->userMileageService->paginateUserHistory($userId, $filters, $perPage);
|
||||
|
||||
return ResponseHelper::success('sirsoft-ecommerce::messages.mileage.list_retrieved', [
|
||||
'transactions' => new MileageTransactionCollection($transactions),
|
||||
]);
|
||||
}
|
||||
}
|
||||
+69
@@ -0,0 +1,69 @@
|
||||
<?php
|
||||
|
||||
namespace Modules\Sirsoft\Ecommerce\Http\Controllers\User;
|
||||
|
||||
use App\Helpers\ResponseHelper;
|
||||
use App\Http\Controllers\Api\Base\AuthBaseController;
|
||||
use Exception;
|
||||
use Illuminate\Http\JsonResponse;
|
||||
use Illuminate\Support\Facades\Auth;
|
||||
use Illuminate\Support\Facades\Log;
|
||||
use Modules\Sirsoft\Ecommerce\Http\Requests\User\UpdateUserShippingCountryRequest;
|
||||
use Modules\Sirsoft\Ecommerce\Services\UserShippingCountryService;
|
||||
|
||||
/**
|
||||
* 사용자 배송국가 컨트롤러 (MP08 후속)
|
||||
*
|
||||
* 마이페이지 배송국가 설정 / 회원정보 수정에서 유저별 영속 배송국가를 조회·저장합니다.
|
||||
*/
|
||||
class UserShippingCountryController extends AuthBaseController
|
||||
{
|
||||
public function __construct(
|
||||
private UserShippingCountryService $service
|
||||
) {}
|
||||
|
||||
/**
|
||||
* 현재 사용자의 선호 배송국가를 조회합니다.
|
||||
*
|
||||
* @return JsonResponse 선호 배송국가 코드(미설정 시 null)를 포함한 JSON 응답
|
||||
*/
|
||||
public function show(): JsonResponse
|
||||
{
|
||||
$userId = (int) Auth::id();
|
||||
|
||||
return ResponseHelper::success('sirsoft-ecommerce::messages.user_shipping_country.fetched', [
|
||||
'preferred_shipping_country' => $this->service->getPreferredShippingCountry($userId),
|
||||
]);
|
||||
}
|
||||
|
||||
/**
|
||||
* 현재 사용자의 선호 배송국가를 저장합니다.
|
||||
*
|
||||
* @param UpdateUserShippingCountryRequest $request 검증된 요청(활성 국가만 허용)
|
||||
* @return JsonResponse 저장 결과 JSON 응답
|
||||
*/
|
||||
public function update(UpdateUserShippingCountryRequest $request): JsonResponse
|
||||
{
|
||||
try {
|
||||
$userId = (int) Auth::id();
|
||||
$country = $request->validated('shipping_country');
|
||||
|
||||
$this->service->setPreferredShippingCountry($userId, $country);
|
||||
|
||||
return ResponseHelper::success('sirsoft-ecommerce::messages.user_shipping_country.updated', [
|
||||
'preferred_shipping_country' => strtoupper($country),
|
||||
]);
|
||||
} catch (Exception $e) {
|
||||
Log::error('User shipping country update failed', [
|
||||
'message' => $e->getMessage(),
|
||||
'user_id' => Auth::id(),
|
||||
]);
|
||||
|
||||
return ResponseHelper::moduleError(
|
||||
'sirsoft-ecommerce',
|
||||
'messages.user_shipping_country.update_failed',
|
||||
500
|
||||
);
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,84 @@
|
||||
<?php
|
||||
|
||||
namespace Modules\Sirsoft\Ecommerce\Http\Middleware;
|
||||
|
||||
use Closure;
|
||||
use Illuminate\Http\Request;
|
||||
use Illuminate\Support\Facades\App;
|
||||
use Illuminate\Support\Facades\Auth;
|
||||
use Modules\Sirsoft\Ecommerce\Services\ShippingCountryResolver;
|
||||
use Symfony\Component\HttpFoundation\Response;
|
||||
|
||||
/**
|
||||
* 요청별 배송국가 결정 미들웨어 (MP08 후속 — D2/D11)
|
||||
*
|
||||
* SetTimezone 패턴(App::instance + static accessor)을 미러한다. 커머스 스토어프론트
|
||||
* 라우트 그룹(cart/checkout/products 등)에 적용해 요청마다 배송국가를 결정하고 컨테이너에
|
||||
* 보관한다. CartItemResource/CheckoutItemResource 등이 static accessor 로 읽는다.
|
||||
*
|
||||
* 우선순위:
|
||||
* 1) X-Shipping-Country 헤더(D11) — 활성 국가일 때만 즉시 채택(비로그인 헤더 즉시반영)
|
||||
* 2) ShippingCountryResolver::resolve(저장 → GeoIP → default)
|
||||
*/
|
||||
class ResolveShippingCountry
|
||||
{
|
||||
/**
|
||||
* 애플리케이션 컨테이너에 저장되는 배송국가 키
|
||||
*/
|
||||
public const SHIPPING_COUNTRY_KEY = 'resolved_shipping_country';
|
||||
|
||||
public function __construct(
|
||||
private ShippingCountryResolver $resolver
|
||||
) {}
|
||||
|
||||
/**
|
||||
* 들어오는 요청을 처리하고 배송국가를 결정해 컨테이너에 보관합니다.
|
||||
*
|
||||
* @param Request $request HTTP 요청
|
||||
* @param Closure $next 다음 미들웨어 또는 요청 핸들러
|
||||
* @return Response HTTP 응답
|
||||
*/
|
||||
public function handle(Request $request, Closure $next): Response
|
||||
{
|
||||
App::instance(self::SHIPPING_COUNTRY_KEY, $this->determineCountry($request));
|
||||
|
||||
return $next($request);
|
||||
}
|
||||
|
||||
/**
|
||||
* 요청의 배송국가를 결정합니다.
|
||||
*
|
||||
* @param Request $request HTTP 요청
|
||||
* @return string 결정된 배송국가 코드 (항상 활성 국가)
|
||||
*/
|
||||
private function determineCountry(Request $request): string
|
||||
{
|
||||
// 1. X-Shipping-Country 헤더 (비로그인 즉시 반영, 활성 국가만 채택)
|
||||
$header = $request->header('X-Shipping-Country');
|
||||
if (is_string($header) && $this->resolver->isAllowed($header)) {
|
||||
return strtoupper($header);
|
||||
}
|
||||
|
||||
// 2. 저장 → GeoIP → default
|
||||
return $this->resolver->resolve(
|
||||
Auth::check() ? (int) Auth::id() : null,
|
||||
$request->ip()
|
||||
);
|
||||
}
|
||||
|
||||
/**
|
||||
* 현재 요청에 결정된 배송국가를 가져옵니다.
|
||||
*
|
||||
* 미들웨어가 실행되지 않은 경우 default_country 로 폴백합니다.
|
||||
*
|
||||
* @return string 현재 배송국가 코드
|
||||
*/
|
||||
public static function getCountry(): string
|
||||
{
|
||||
if (App::bound(self::SHIPPING_COUNTRY_KEY)) {
|
||||
return App::make(self::SHIPPING_COUNTRY_KEY);
|
||||
}
|
||||
|
||||
return App::make(ShippingCountryResolver::class)->defaultCountry();
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,54 @@
|
||||
<?php
|
||||
|
||||
namespace Modules\Sirsoft\Ecommerce\Http\Middleware;
|
||||
|
||||
use App\Helpers\ResponseHelper;
|
||||
use Closure;
|
||||
use Illuminate\Http\Request;
|
||||
use Modules\Sirsoft\Ecommerce\Services\GuestOrderAuthService;
|
||||
use Symfony\Component\HttpFoundation\Response;
|
||||
|
||||
/**
|
||||
* 비회원 주문 조회 토큰 검증 미들웨어
|
||||
*
|
||||
* X-Guest-Order-Token 헤더의 HMAC 토큰을 검증하여, 라우트의 주문번호와
|
||||
* 일치하는 비회원 주문만 통과시킨다. 검증된 주문은 request attribute
|
||||
* (guest_order)로 컨트롤러에 전달된다.
|
||||
*
|
||||
* 토큰 부재/만료/위조/다른 주문 재사용은 모두 동일하게 "주문을 찾을 수 없습니다"
|
||||
* 응답으로 처리한다 (정보 노출 차단).
|
||||
*/
|
||||
class VerifyGuestOrderToken
|
||||
{
|
||||
public function __construct(
|
||||
private GuestOrderAuthService $guestOrderAuthService
|
||||
) {}
|
||||
|
||||
/**
|
||||
* 요청을 처리합니다.
|
||||
*
|
||||
* @param Request $request HTTP 요청
|
||||
* @param Closure $next 다음 미들웨어
|
||||
* @return Response HTTP 응답
|
||||
*/
|
||||
public function handle(Request $request, Closure $next): Response
|
||||
{
|
||||
$token = $request->header('X-Guest-Order-Token');
|
||||
$orderNumber = (string) $request->route('orderNumber');
|
||||
|
||||
$order = $this->guestOrderAuthService->verifyToken($token, $orderNumber);
|
||||
|
||||
if (! $order) {
|
||||
return ResponseHelper::moduleError(
|
||||
'sirsoft-ecommerce',
|
||||
'exceptions.order_not_found',
|
||||
404
|
||||
);
|
||||
}
|
||||
|
||||
// 검증된 주문을 컨트롤러로 전달 (각 액션은 동일 주문에만 접근)
|
||||
$request->attributes->set('guest_order', $order);
|
||||
|
||||
return $next($request);
|
||||
}
|
||||
}
|
||||
+34
-8
@@ -4,9 +4,11 @@ namespace Modules\Sirsoft\Ecommerce\Http\Requests\Admin;
|
||||
|
||||
use Illuminate\Foundation\Http\FormRequest;
|
||||
use Illuminate\Validation\Rule;
|
||||
use Illuminate\Validation\Validator;
|
||||
use Modules\Sirsoft\Ecommerce\Enums\OrderStatusEnum;
|
||||
use Modules\Sirsoft\Ecommerce\Models\OrderOption;
|
||||
use Modules\Sirsoft\Ecommerce\Models\ShippingCarrier;
|
||||
use Modules\Sirsoft\Ecommerce\Enums\OrderStatusEnum;
|
||||
use Modules\Sirsoft\Ecommerce\Repositories\Contracts\OrderOptionRepositoryInterface;
|
||||
|
||||
/**
|
||||
* 주문 옵션 일괄 상태 변경 요청
|
||||
@@ -16,7 +18,7 @@ class BulkChangeOrderOptionStatusRequest extends FormRequest
|
||||
/**
|
||||
* 권한 확인
|
||||
*
|
||||
* @return bool
|
||||
* @return bool 권한 미들웨어에 위임하므로 항상 true
|
||||
*/
|
||||
public function authorize(): bool
|
||||
{
|
||||
@@ -26,7 +28,7 @@ class BulkChangeOrderOptionStatusRequest extends FormRequest
|
||||
/**
|
||||
* 유효성 검사 규칙
|
||||
*
|
||||
* @return array
|
||||
* @return array<string, mixed> 필드별 검증 규칙 배열
|
||||
*/
|
||||
public function rules(): array
|
||||
{
|
||||
@@ -43,26 +45,50 @@ class BulkChangeOrderOptionStatusRequest extends FormRequest
|
||||
/**
|
||||
* 추가 검증 로직
|
||||
*
|
||||
* @param \Illuminate\Validation\Validator $validator
|
||||
* @return void
|
||||
* @param Validator $validator
|
||||
*/
|
||||
public function withValidator($validator): void
|
||||
{
|
||||
$validator->after(function ($validator) {
|
||||
$items = $this->input('items', []);
|
||||
|
||||
// 대상 옵션 스냅샷을 1회 배치 조회 (수량·전이 검증 공용, N+1 회피).
|
||||
// Repository 인터페이스 경유 — Model 직접 호출(audit formrequest-direct-data-access) 금지.
|
||||
$repo = app(OrderOptionRepositoryInterface::class);
|
||||
$optionIds = collect($items)->pluck('option_id')->filter()->all();
|
||||
$snapshots = $repo->getSnapshotsByIds($optionIds); // id 키 스냅샷 (option_status / quantity 포함)
|
||||
|
||||
$target = OrderStatusEnum::tryFrom((string) $this->input('status'));
|
||||
|
||||
foreach ($items as $index => $item) {
|
||||
if (! isset($item['option_id'], $item['quantity'])) {
|
||||
continue;
|
||||
}
|
||||
|
||||
$option = \Modules\Sirsoft\Ecommerce\Models\OrderOption::find($item['option_id']);
|
||||
if ($option && $item['quantity'] > $option->quantity) {
|
||||
$snap = $snapshots[$item['option_id']] ?? null;
|
||||
if ($snap === null) {
|
||||
continue; // rules 의 exists 검증에 위임
|
||||
}
|
||||
|
||||
// 수량 검증 (배치 스냅샷 재사용)
|
||||
if ($item['quantity'] > ($snap['quantity'] ?? 0)) {
|
||||
$validator->errors()->add(
|
||||
"items.{$index}.quantity",
|
||||
__('sirsoft-ecommerce::validation.quantity_exceeds_available')
|
||||
);
|
||||
}
|
||||
|
||||
// 상태 전이 검증 (역방향/비연속 역행 차단, all-or-nothing)
|
||||
$currentValue = $snap['option_status'] ?? null;
|
||||
$current = $currentValue !== null ? OrderStatusEnum::tryFrom(
|
||||
$currentValue instanceof OrderStatusEnum ? $currentValue->value : $currentValue
|
||||
) : null;
|
||||
if ($target !== null && $current !== null && ! $current->canTransitionTo($target)) {
|
||||
$validator->errors()->add("items.{$index}.status", __('sirsoft-ecommerce::validation.orders.status_transition.invalid', [
|
||||
'from' => $current->label(),
|
||||
'to' => $target->label(),
|
||||
]));
|
||||
}
|
||||
}
|
||||
|
||||
// 배송 관련 상태 선택 시 택배사/송장번호 필수
|
||||
@@ -82,7 +108,7 @@ class BulkChangeOrderOptionStatusRequest extends FormRequest
|
||||
/**
|
||||
* 검증 에러 메시지 정의
|
||||
*
|
||||
* @return array
|
||||
* @return array<string, string> 규칙별 다국어 에러 메시지 배열
|
||||
*/
|
||||
public function messages(): array
|
||||
{
|
||||
|
||||
+7
-6
@@ -5,6 +5,7 @@ namespace Modules\Sirsoft\Ecommerce\Http\Requests\Admin;
|
||||
use App\Extension\HookManager;
|
||||
use Illuminate\Foundation\Http\FormRequest;
|
||||
use Illuminate\Validation\Rule;
|
||||
use Illuminate\Validation\Validator;
|
||||
use Modules\Sirsoft\Ecommerce\Models\Product;
|
||||
|
||||
/**
|
||||
@@ -15,7 +16,7 @@ class BulkUpdateOptionPriceRequest extends FormRequest
|
||||
/**
|
||||
* 권한 확인
|
||||
*
|
||||
* @return bool
|
||||
* @return bool 인가 여부
|
||||
*/
|
||||
public function authorize(): bool
|
||||
{
|
||||
@@ -29,7 +30,7 @@ class BulkUpdateOptionPriceRequest extends FormRequest
|
||||
* option_ids: 옵션 ID 배열 ("productId-optionId" 형식, 개별 선택된 옵션)
|
||||
* 둘 중 하나 이상 필수
|
||||
*
|
||||
* @return array
|
||||
* @return array 검증 규칙 배열
|
||||
*/
|
||||
public function rules(): array
|
||||
{
|
||||
@@ -39,7 +40,8 @@ class BulkUpdateOptionPriceRequest extends FormRequest
|
||||
'option_ids' => ['nullable', 'array'],
|
||||
'option_ids.*' => ['string', 'regex:/^\d+-\d+$/'],
|
||||
'method' => ['required', 'in:increase,decrease,fixed'],
|
||||
'value' => ['required', 'integer', 'min:0'],
|
||||
// 금액(won) 변경은 기본통화가 소수 통화일 수 있어 소수 허용. 비율(percent)도 소수 허용.
|
||||
'value' => ['required', 'numeric', 'min:0'],
|
||||
'unit' => ['required', 'in:won,percent'],
|
||||
];
|
||||
|
||||
@@ -50,8 +52,7 @@ class BulkUpdateOptionPriceRequest extends FormRequest
|
||||
/**
|
||||
* 추가 유효성 검사
|
||||
*
|
||||
* @param \Illuminate\Validation\Validator $validator
|
||||
* @return void
|
||||
* @param Validator $validator
|
||||
*/
|
||||
public function withValidator($validator): void
|
||||
{
|
||||
@@ -68,7 +69,7 @@ class BulkUpdateOptionPriceRequest extends FormRequest
|
||||
/**
|
||||
* 유효성 검사 메시지
|
||||
*
|
||||
* @return array
|
||||
* @return array 검증 메시지 배열
|
||||
*/
|
||||
public function messages(): array
|
||||
{
|
||||
|
||||
+2
-2
@@ -19,7 +19,7 @@ class BulkUpdateOptionsRequest extends FormRequest
|
||||
/**
|
||||
* 권한 확인
|
||||
*
|
||||
* @return bool
|
||||
* @return bool 인가 여부 (권한 체크는 미들웨어에 위임)
|
||||
*/
|
||||
public function authorize(): bool
|
||||
{
|
||||
@@ -52,7 +52,7 @@ class BulkUpdateOptionsRequest extends FormRequest
|
||||
'items.*.product_id' => ['required', 'integer', Rule::exists(Product::class, 'id')],
|
||||
'items.*.option_id' => ['required', 'integer', Rule::exists(ProductOption::class, 'id')],
|
||||
'items.*.option_name' => ['nullable', 'array'],
|
||||
'items.*.option_name.*' => ['string', 'max:255'],
|
||||
'items.*.option_name.*' => ['nullable', 'string', 'max:255'],
|
||||
'items.*.sku' => ['nullable', 'string', 'max:100'],
|
||||
'items.*.list_price' => ['nullable', 'numeric', 'min:0'],
|
||||
'items.*.price_adjustment' => ['nullable', 'numeric'],
|
||||
|
||||
+33
-5
@@ -4,9 +4,11 @@ namespace Modules\Sirsoft\Ecommerce\Http\Requests\Admin;
|
||||
|
||||
use Illuminate\Foundation\Http\FormRequest;
|
||||
use Illuminate\Validation\Rule;
|
||||
use Illuminate\Validation\Validator;
|
||||
use Modules\Sirsoft\Ecommerce\Enums\OrderStatusEnum;
|
||||
use Modules\Sirsoft\Ecommerce\Models\Order;
|
||||
use Modules\Sirsoft\Ecommerce\Models\ShippingCarrier;
|
||||
use Modules\Sirsoft\Ecommerce\Repositories\Contracts\OrderRepositoryInterface;
|
||||
|
||||
/**
|
||||
* 주문 일괄 변경 요청
|
||||
@@ -16,7 +18,7 @@ class BulkUpdateOrdersRequest extends FormRequest
|
||||
/**
|
||||
* 권한 확인
|
||||
*
|
||||
* @return bool
|
||||
* @return bool 권한 미들웨어에 위임하므로 항상 true
|
||||
*/
|
||||
public function authorize(): bool
|
||||
{
|
||||
@@ -26,7 +28,7 @@ class BulkUpdateOrdersRequest extends FormRequest
|
||||
/**
|
||||
* 유효성 검사 규칙
|
||||
*
|
||||
* @return array
|
||||
* @return array<string, mixed> 필드별 검증 규칙 배열
|
||||
*/
|
||||
public function rules(): array
|
||||
{
|
||||
@@ -44,8 +46,7 @@ class BulkUpdateOrdersRequest extends FormRequest
|
||||
/**
|
||||
* 추가 검증 로직
|
||||
*
|
||||
* @param \Illuminate\Validation\Validator $validator
|
||||
* @return void
|
||||
* @param Validator $validator
|
||||
*/
|
||||
public function withValidator($validator): void
|
||||
{
|
||||
@@ -73,13 +74,40 @@ class BulkUpdateOrdersRequest extends FormRequest
|
||||
$validator->errors()->add('tracking_number', __('sirsoft-ecommerce::validation.orders.tracking_number_required'));
|
||||
}
|
||||
}
|
||||
|
||||
// 상태 일괄 전이 검증 (역방향/비연속 역행 차단, all-or-nothing)
|
||||
// 대상 주문 중 1건이라도 비합법 전이면 422 → Service 미진입 → DB 무변경.
|
||||
if ($status !== null) {
|
||||
$target = OrderStatusEnum::tryFrom($status);
|
||||
if ($target !== null) {
|
||||
$repo = app(OrderRepositoryInterface::class);
|
||||
$snapshots = $repo->getSnapshotsByIds($this->input('ids', []));
|
||||
$invalid = [];
|
||||
foreach ($snapshots as $snap) {
|
||||
$currentValue = $snap['order_status'] ?? null;
|
||||
$current = $currentValue !== null ? OrderStatusEnum::tryFrom(
|
||||
$currentValue instanceof OrderStatusEnum ? $currentValue->value : $currentValue
|
||||
) : null;
|
||||
if ($current !== null && ! $current->canTransitionTo($target)) {
|
||||
$invalid[] = $current->label();
|
||||
}
|
||||
}
|
||||
if (! empty($invalid)) {
|
||||
$validator->errors()->add('order_status', __('sirsoft-ecommerce::validation.orders.status_transition.bulk_invalid', [
|
||||
'count' => count($invalid),
|
||||
'to' => $target->label(),
|
||||
'from' => implode(', ', array_values(array_unique($invalid))),
|
||||
]));
|
||||
}
|
||||
}
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
/**
|
||||
* 검증 에러 메시지 정의
|
||||
*
|
||||
* @return array
|
||||
* @return array<string, string> 규칙별 다국어 에러 메시지 배열
|
||||
*/
|
||||
public function messages(): array
|
||||
{
|
||||
|
||||
+5
-4
@@ -15,7 +15,7 @@ class BulkUpdatePriceRequest extends FormRequest
|
||||
/**
|
||||
* 권한 확인
|
||||
*
|
||||
* @return bool
|
||||
* @return bool 인가 여부
|
||||
*/
|
||||
public function authorize(): bool
|
||||
{
|
||||
@@ -25,7 +25,7 @@ class BulkUpdatePriceRequest extends FormRequest
|
||||
/**
|
||||
* 유효성 검사 규칙
|
||||
*
|
||||
* @return array
|
||||
* @return array 검증 규칙 배열
|
||||
*/
|
||||
public function rules(): array
|
||||
{
|
||||
@@ -33,7 +33,8 @@ class BulkUpdatePriceRequest extends FormRequest
|
||||
'ids' => ['required', 'array', 'min:1'],
|
||||
'ids.*' => ['integer', Rule::exists(Product::class, 'id')],
|
||||
'method' => ['required', 'in:increase,decrease,set'],
|
||||
'value' => ['required', 'integer', 'min:0'],
|
||||
// 금액(won) 변경은 기본통화가 소수 통화일 수 있어 소수 허용. 비율(percent)도 소수 허용.
|
||||
'value' => ['required', 'numeric', 'min:0'],
|
||||
'unit' => ['required', 'in:won,percent'],
|
||||
];
|
||||
|
||||
@@ -44,7 +45,7 @@ class BulkUpdatePriceRequest extends FormRequest
|
||||
/**
|
||||
* 유효성 검사 메시지
|
||||
*
|
||||
* @return array
|
||||
* @return array 검증 메시지 배열
|
||||
*/
|
||||
public function messages(): array
|
||||
{
|
||||
|
||||
+2
-2
@@ -20,7 +20,7 @@ class BulkUpdateProductsRequest extends FormRequest
|
||||
/**
|
||||
* 권한 확인
|
||||
*
|
||||
* @return bool
|
||||
* @return bool 인가 여부 (권한 체크는 미들웨어에 위임)
|
||||
*/
|
||||
public function authorize(): bool
|
||||
{
|
||||
@@ -84,7 +84,7 @@ class BulkUpdateProductsRequest extends FormRequest
|
||||
'option_items.*.product_id' => ['required', 'integer', Rule::exists(Product::class, 'id')],
|
||||
'option_items.*.option_id' => ['required', 'integer', Rule::exists(ProductOption::class, 'id')],
|
||||
'option_items.*.option_name' => ['nullable', 'array'],
|
||||
'option_items.*.option_name.*' => ['string', 'max:255'],
|
||||
'option_items.*.option_name.*' => ['nullable', 'string', 'max:255'],
|
||||
'option_items.*.sku' => ['nullable', 'string', 'max:100'],
|
||||
'option_items.*.list_price' => ['nullable', 'numeric', 'min:0'],
|
||||
'option_items.*.price_adjustment' => ['nullable', 'numeric'],
|
||||
|
||||
+64
@@ -0,0 +1,64 @@
|
||||
<?php
|
||||
|
||||
namespace Modules\Sirsoft\Ecommerce\Http\Requests\Admin\Concerns;
|
||||
|
||||
use Illuminate\Validation\Validator;
|
||||
use Modules\Sirsoft\Ecommerce\Enums\CouponTargetScope;
|
||||
|
||||
/**
|
||||
* 쿠폰 적용대상(상품/카테고리) 미선택 저장 차단 검증 trait
|
||||
*
|
||||
* target_scope 가 products/categories 인데 include 타입 대상이 0건이면 검증 오류를 추가합니다.
|
||||
* (exclude 만 있으면 적용 대상 공집합이라 무의미하므로 차단)
|
||||
*/
|
||||
trait ValidatesCouponTargetScope
|
||||
{
|
||||
/**
|
||||
* target_scope 기준 적용대상 선택 필수 검증을 등록합니다.
|
||||
*
|
||||
* @param Validator $validator 검증기 인스턴스
|
||||
*/
|
||||
protected function validateTargetScopeSelection(Validator $validator): void
|
||||
{
|
||||
$validator->after(function (Validator $validator) {
|
||||
$scope = $this->input('target_scope', CouponTargetScope::ALL->value);
|
||||
|
||||
if ($scope === CouponTargetScope::PRODUCTS->value
|
||||
&& ! $this->hasIncludeEntry($this->input('products', []))) {
|
||||
$validator->errors()->add(
|
||||
'products',
|
||||
__('sirsoft-ecommerce::validation.coupon.target_products_required')
|
||||
);
|
||||
}
|
||||
|
||||
if ($scope === CouponTargetScope::CATEGORIES->value
|
||||
&& ! $this->hasIncludeEntry($this->input('categories', []))) {
|
||||
$validator->errors()->add(
|
||||
'categories',
|
||||
__('sirsoft-ecommerce::validation.coupon.target_categories_required')
|
||||
);
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
/**
|
||||
* 배열에 type=include 항목이 1건 이상 있는지 확인합니다.
|
||||
*
|
||||
* @param mixed $entries products/categories 입력 배열
|
||||
* @return bool include 항목 존재 여부
|
||||
*/
|
||||
private function hasIncludeEntry(mixed $entries): bool
|
||||
{
|
||||
if (! is_array($entries)) {
|
||||
return false;
|
||||
}
|
||||
|
||||
foreach ($entries as $entry) {
|
||||
if (is_array($entry) && ($entry['type'] ?? null) === 'include') {
|
||||
return true;
|
||||
}
|
||||
}
|
||||
|
||||
return false;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,150 @@
|
||||
<?php
|
||||
|
||||
namespace Modules\Sirsoft\Ecommerce\Http\Requests\Admin;
|
||||
|
||||
use App\Helpers\ResponseHelper;
|
||||
use Illuminate\Contracts\Validation\Validator;
|
||||
use Illuminate\Foundation\Http\FormRequest;
|
||||
use Illuminate\Validation\ValidationException;
|
||||
use Modules\Sirsoft\Ecommerce\Enums\PaymentMethodEnum;
|
||||
use Modules\Sirsoft\Ecommerce\Models\Order;
|
||||
|
||||
/**
|
||||
* 무통장 입금확인 요청 (관리자)
|
||||
*
|
||||
* 관리자가 무통장(dbank) 미결제 주문의 입금을 수동 확인할 때 사용됩니다.
|
||||
* 권한은 라우트 미들웨어(permission:admin,sirsoft-ecommerce.orders.update)에서 처리하며,
|
||||
* 여기서는 주문이 무통장·미결제 상태인지와 입금 금액/입금자명 형식만 검증합니다.
|
||||
*/
|
||||
class ConfirmDepositRequest extends FormRequest
|
||||
{
|
||||
/**
|
||||
* 사용자가 이 요청을 수행할 권한이 있는지 확인 (권한은 미들웨어에서 처리)
|
||||
*
|
||||
* @return bool 항상 true
|
||||
*/
|
||||
public function authorize(): bool
|
||||
{
|
||||
return true;
|
||||
}
|
||||
|
||||
/**
|
||||
* 요청에 적용할 검증 규칙
|
||||
*
|
||||
* @return array<string, array<int, string>> 검증 규칙 배열
|
||||
*/
|
||||
public function rules(): array
|
||||
{
|
||||
return [
|
||||
'amount' => ['required', 'numeric', 'min:0'],
|
||||
'depositor_name' => ['nullable', 'string', 'max:100'],
|
||||
// true 면 입금 기록과 함께 주문을 결제완료로 전이(마일리지/재고/알림 포함).
|
||||
// false 면 결제 레코드(payment)만 입금완료로 기록(주문 상태 전이 없음).
|
||||
'mark_order_complete' => ['nullable', 'boolean'],
|
||||
];
|
||||
}
|
||||
|
||||
/**
|
||||
* 검증 필드의 사용자 표시명
|
||||
*
|
||||
* @return array<string, string> 필드명 → 표시명 매핑
|
||||
*/
|
||||
public function attributes(): array
|
||||
{
|
||||
return [
|
||||
'amount' => __('sirsoft-ecommerce::messages.orders.deposit.amount'),
|
||||
'depositor_name' => __('sirsoft-ecommerce::messages.orders.deposit.depositor_name'),
|
||||
];
|
||||
}
|
||||
|
||||
/**
|
||||
* 추가 검증 로직 — 주문이 무통장·미결제 상태인지 확인
|
||||
*
|
||||
* @param Validator $validator 검증기
|
||||
*/
|
||||
protected function withValidator(Validator $validator): void
|
||||
{
|
||||
$validator->after(function (Validator $validator) {
|
||||
if ($validator->errors()->any()) {
|
||||
return;
|
||||
}
|
||||
|
||||
/** @var Order|null $order */
|
||||
$order = $this->route('order');
|
||||
|
||||
if (! $order) {
|
||||
$validator->errors()->add('order', __('sirsoft-ecommerce::exceptions.order_not_found'));
|
||||
|
||||
return;
|
||||
}
|
||||
|
||||
$order->loadMissing('payment');
|
||||
|
||||
// 무통장(dbank) 결제수단만 입금확인 대상
|
||||
if ($order->payment?->payment_method !== PaymentMethodEnum::DBANK) {
|
||||
$validator->errors()->add(
|
||||
'order',
|
||||
__('sirsoft-ecommerce::messages.orders.deposit_not_dbank')
|
||||
);
|
||||
|
||||
return;
|
||||
}
|
||||
|
||||
// 결제 레코드(payment) 자체가 미입금(ready/waiting_deposit) 상태일 때만 입금확인 가능.
|
||||
// 주문 상태(order_status)가 아닌 결제 레코드 기준으로 판정해, order_status 가 다른 경로로
|
||||
// 먼저 결제완료로 전이돼도 실제 미입금 결제는 입금확인할 수 있게 한다(버튼 노출 조건과 일관).
|
||||
if ($order->payment?->payment_status?->isAwaitingDeposit() !== true) {
|
||||
$validator->errors()->add(
|
||||
'payment_status',
|
||||
__('sirsoft-ecommerce::messages.orders.deposit_not_pending')
|
||||
);
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
/**
|
||||
* 검증 실패 시 응답 커스터마이징
|
||||
*
|
||||
* @param Validator $validator 검증기
|
||||
*
|
||||
* @throws ValidationException 검증 실패 시
|
||||
*/
|
||||
protected function failedValidation(Validator $validator): void
|
||||
{
|
||||
throw new ValidationException($validator, ResponseHelper::error(
|
||||
$validator->errors()->first(),
|
||||
422,
|
||||
$validator->errors()->toArray()
|
||||
));
|
||||
}
|
||||
|
||||
/**
|
||||
* 입금 금액을 반환합니다.
|
||||
*
|
||||
* @return float 입금 금액
|
||||
*/
|
||||
public function getAmount(): float
|
||||
{
|
||||
return (float) $this->validated('amount');
|
||||
}
|
||||
|
||||
/**
|
||||
* 입금자명을 반환합니다.
|
||||
*
|
||||
* @return string|null 입금자명 (미입력 시 null)
|
||||
*/
|
||||
public function getDepositorName(): ?string
|
||||
{
|
||||
return $this->validated('depositor_name');
|
||||
}
|
||||
|
||||
/**
|
||||
* 입금 확인 시 주문을 결제완료로 전이할지 여부를 반환합니다.
|
||||
*
|
||||
* @return bool 체크박스 미전달 시 기본값 false (입금 기록만)
|
||||
*/
|
||||
public function shouldMarkOrderComplete(): bool
|
||||
{
|
||||
return (bool) $this->validated('mark_order_complete', false);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,36 @@
|
||||
<?php
|
||||
|
||||
namespace Modules\Sirsoft\Ecommerce\Http\Requests\Admin;
|
||||
|
||||
use Illuminate\Foundation\Http\FormRequest;
|
||||
|
||||
/**
|
||||
* 대시보드 조회 파라미터 검증
|
||||
*
|
||||
* 최신 리뷰/미답변 문의 카드의 limit 을 검증합니다.
|
||||
* 그래프 표시 일수는 모듈 설정(dashboard.graph_days)이 SSoT 이므로 요청 파라미터로 받지 않습니다.
|
||||
*/
|
||||
class DashboardRangeRequest extends FormRequest
|
||||
{
|
||||
/**
|
||||
* 요청 권한 확인 (권한은 미들웨어에서 처리).
|
||||
*
|
||||
* @return bool 항상 true
|
||||
*/
|
||||
public function authorize(): bool
|
||||
{
|
||||
return true;
|
||||
}
|
||||
|
||||
/**
|
||||
* 검증 규칙을 반환합니다.
|
||||
*
|
||||
* @return array<string, array<int, mixed>> 검증 규칙
|
||||
*/
|
||||
public function rules(): array
|
||||
{
|
||||
return [
|
||||
'limit' => ['nullable', 'integer', 'min:1', 'max:50'],
|
||||
];
|
||||
}
|
||||
}
|
||||
+38
@@ -0,0 +1,38 @@
|
||||
<?php
|
||||
|
||||
namespace Modules\Sirsoft\Ecommerce\Http\Requests\Admin;
|
||||
|
||||
use App\Models\User;
|
||||
use Illuminate\Foundation\Http\FormRequest;
|
||||
use Illuminate\Validation\Rule;
|
||||
|
||||
/**
|
||||
* 관리자 마일리지 일괄 유효기간 연장 요청
|
||||
*/
|
||||
class ExtendMileageExpiryRequest extends FormRequest
|
||||
{
|
||||
/**
|
||||
* 권한 체크는 라우트의 permission 미들웨어에서 수행됩니다.
|
||||
*
|
||||
* @return bool 항상 true
|
||||
*/
|
||||
public function authorize(): bool
|
||||
{
|
||||
return true;
|
||||
}
|
||||
|
||||
/**
|
||||
* 검증 규칙
|
||||
*
|
||||
* @return array 검증 규칙
|
||||
*/
|
||||
public function rules(): array
|
||||
{
|
||||
return [
|
||||
'user_id' => ['required', 'uuid', Rule::exists(User::class, 'uuid')],
|
||||
'lot_ids' => ['required', 'array', 'min:1'],
|
||||
'lot_ids.*' => ['integer'],
|
||||
'days' => ['required', 'integer', 'min:1', 'max:3650'],
|
||||
];
|
||||
}
|
||||
}
|
||||
+64
@@ -0,0 +1,64 @@
|
||||
<?php
|
||||
|
||||
namespace Modules\Sirsoft\Ecommerce\Http\Requests\Admin;
|
||||
|
||||
use App\Models\User;
|
||||
use Illuminate\Foundation\Http\FormRequest;
|
||||
use Illuminate\Validation\Rule;
|
||||
|
||||
/**
|
||||
* 쿠폰 직접발급 요청 (관리자가 회원을 지정해 즉시 발급)
|
||||
*/
|
||||
class IssueCouponDirectRequest extends FormRequest
|
||||
{
|
||||
/**
|
||||
* 사용자가 이 요청을 수행할 권한이 있는지 확인
|
||||
*
|
||||
* @return bool 권한 미들웨어가 처리하므로 항상 true
|
||||
*/
|
||||
public function authorize(): bool
|
||||
{
|
||||
return true;
|
||||
}
|
||||
|
||||
/**
|
||||
* 요청에 적용할 검증 규칙
|
||||
*
|
||||
* @return array 검증 규칙 배열
|
||||
*/
|
||||
public function rules(): array
|
||||
{
|
||||
return [
|
||||
'user_uuids' => ['required', 'array', 'min:1'],
|
||||
'user_uuids.*' => ['string', Rule::exists(User::class, 'uuid')],
|
||||
];
|
||||
}
|
||||
|
||||
/**
|
||||
* 검증 오류 메시지 커스터마이징
|
||||
*
|
||||
* @return array 필드별 오류 메시지 배열
|
||||
*/
|
||||
public function messages(): array
|
||||
{
|
||||
return [
|
||||
'user_uuids.required' => __('sirsoft-ecommerce::validation.coupon.user_ids_required'),
|
||||
'user_uuids.min' => __('sirsoft-ecommerce::validation.coupon.user_ids_min'),
|
||||
'user_uuids.*.exists' => __('sirsoft-ecommerce::validation.coupon.user_ids_invalid'),
|
||||
];
|
||||
}
|
||||
|
||||
/**
|
||||
* 검증된 uuid 목록을 내부 정수 회원 ID 로 해석해 반환합니다.
|
||||
*
|
||||
* 관리자 UI 는 uuid 만 노출하므로 발급 서비스가 사용하는 정수 ID 로 변환합니다.
|
||||
*
|
||||
* @return int[] 발급 대상 회원 ID 배열
|
||||
*/
|
||||
public function resolvedUserIds(): array
|
||||
{
|
||||
return User::whereIn('uuid', $this->validated()['user_uuids'])
|
||||
->pluck('id')
|
||||
->all();
|
||||
}
|
||||
}
|
||||
+42
@@ -0,0 +1,42 @@
|
||||
<?php
|
||||
|
||||
namespace Modules\Sirsoft\Ecommerce\Http\Requests\Admin;
|
||||
|
||||
use Illuminate\Foundation\Http\FormRequest;
|
||||
|
||||
/**
|
||||
* 관리자 마일리지 내역 목록 조회 요청
|
||||
*/
|
||||
class MileageTransactionListRequest extends FormRequest
|
||||
{
|
||||
/**
|
||||
* 권한 체크는 라우트의 permission 미들웨어에서 수행됩니다.
|
||||
*
|
||||
* @return bool 항상 true
|
||||
*/
|
||||
public function authorize(): bool
|
||||
{
|
||||
return true;
|
||||
}
|
||||
|
||||
/**
|
||||
* 검증 규칙
|
||||
*
|
||||
* @return array 검증 규칙
|
||||
*/
|
||||
public function rules(): array
|
||||
{
|
||||
return [
|
||||
'page' => ['nullable', 'integer', 'min:1'],
|
||||
'per_page' => ['nullable', 'integer', 'min:1', 'max:100'],
|
||||
'sort' => ['nullable', 'string', 'in:created_at_desc,created_at_asc,amount_desc,amount_asc'],
|
||||
'search_field' => ['nullable', 'string', 'in:member,member_id,email,order'],
|
||||
'search_keyword' => ['nullable', 'string', 'max:100'],
|
||||
// 거래유형은 UI 4분류 슬러그(전체='', earn/use/expire/adjust)를 받아 Repository에서 8종 enum으로 역매핑
|
||||
'type' => ['nullable', 'string', 'in:earn,use,expire,adjust'],
|
||||
'currency' => ['nullable', 'string', 'max:10'],
|
||||
'start_date' => ['nullable', 'date'],
|
||||
'end_date' => ['nullable', 'date'],
|
||||
];
|
||||
}
|
||||
}
|
||||
@@ -87,6 +87,9 @@ class OrderListRequest extends FormRequest
|
||||
// 주문자 UUID (회원 검색 필터용)
|
||||
'orderer_uuid' => ['nullable', 'uuid'],
|
||||
|
||||
// 회원 구분 (member: 회원 주문, guest: 비회원 주문)
|
||||
'member_type' => ['nullable', 'in:member,guest'],
|
||||
|
||||
// 정렬 및 페이지네이션
|
||||
'sort_by' => ['nullable', 'in:ordered_at,paid_at,total_amount'],
|
||||
'sort_order' => ['nullable', 'in:asc,desc'],
|
||||
@@ -157,6 +160,7 @@ class OrderListRequest extends FormRequest
|
||||
'user_id.integer' => __('sirsoft-ecommerce::validation.orders.user_id.integer'),
|
||||
// 주문자 UUID
|
||||
'orderer_uuid.uuid' => __('sirsoft-ecommerce::validation.orders.orderer_uuid.uuid'),
|
||||
'member_type.in' => __('sirsoft-ecommerce::validation.orders.member_type.in'),
|
||||
// 정렬 및 페이지네이션
|
||||
'sort_by.in' => __('sirsoft-ecommerce::validation.orders.sort_by.in'),
|
||||
'sort_order.in' => __('sirsoft-ecommerce::validation.orders.sort_order.in'),
|
||||
|
||||
@@ -0,0 +1,51 @@
|
||||
<?php
|
||||
|
||||
namespace Modules\Sirsoft\Ecommerce\Http\Requests\Admin;
|
||||
|
||||
use Illuminate\Foundation\Http\FormRequest;
|
||||
use Illuminate\Validation\Rule;
|
||||
|
||||
/**
|
||||
* 주문 활동 로그 조회 요청 (관리자)
|
||||
*
|
||||
* 권한은 라우트 미들웨어(permission:admin,sirsoft-ecommerce.orders.read)에서 처리하며,
|
||||
* 여기서는 페이지 크기·정렬 옵션만 검증합니다.
|
||||
*/
|
||||
class OrderLogsRequest extends FormRequest
|
||||
{
|
||||
/**
|
||||
* 사용자가 이 요청을 수행할 권한이 있는지 확인 (권한은 미들웨어에서 처리)
|
||||
*
|
||||
* @return bool 항상 true
|
||||
*/
|
||||
public function authorize(): bool
|
||||
{
|
||||
return true;
|
||||
}
|
||||
|
||||
/**
|
||||
* 요청에 적용할 검증 규칙
|
||||
*
|
||||
* @return array<string, array<int, mixed>> 검증 규칙 배열
|
||||
*/
|
||||
public function rules(): array
|
||||
{
|
||||
return [
|
||||
'per_page' => ['sometimes', 'integer', 'min:1', 'max:100'],
|
||||
'sort_order' => ['sometimes', 'string', Rule::in(['asc', 'desc'])],
|
||||
];
|
||||
}
|
||||
|
||||
/**
|
||||
* 활동 로그 조회 필터(페이지 크기·정렬)를 반환합니다.
|
||||
*
|
||||
* @return array{per_page: int, sort_order: string} 조회 필터
|
||||
*/
|
||||
public function getFilters(): array
|
||||
{
|
||||
return [
|
||||
'per_page' => (int) ($this->query('per_page', 10)),
|
||||
'sort_order' => $this->query('sort_order', 'desc'),
|
||||
];
|
||||
}
|
||||
}
|
||||
@@ -26,6 +26,41 @@ class ProductListRequest extends FormRequest
|
||||
return true;
|
||||
}
|
||||
|
||||
/**
|
||||
* 검증 전 입력을 정규화합니다.
|
||||
*
|
||||
* no_category / no_brand 를 boolean 으로 해석 가능한 문자열('true','1','false','0' 등)로
|
||||
* 받아도 실제 boolean 으로 정규화하여 boolean rule 통과 + validated() 가 진짜 boolean 을
|
||||
* 반환하도록 합니다. (레이아웃 외 직접 API 호출/북마크 URL ?no_category=true 도 안전 처리)
|
||||
*
|
||||
* boolean 으로 해석 불가능한 값(예: 'banana')은 정규화하지 않고 원본을 그대로 두어
|
||||
* boolean rule 이 거부(422)하도록 합니다.
|
||||
*/
|
||||
protected function prepareForValidation(): void
|
||||
{
|
||||
$merge = [];
|
||||
foreach (['no_category', 'no_brand'] as $field) {
|
||||
if (! $this->has($field)) {
|
||||
continue;
|
||||
}
|
||||
|
||||
// FILTER_NULL_ON_FAILURE: boolean 해석 불가 값은 null → 정규화 스킵(원본 유지 → boolean rule 거부)
|
||||
$normalized = filter_var(
|
||||
$this->input($field),
|
||||
FILTER_VALIDATE_BOOLEAN,
|
||||
FILTER_NULL_ON_FAILURE
|
||||
);
|
||||
|
||||
if ($normalized !== null) {
|
||||
$merge[$field] = $normalized;
|
||||
}
|
||||
}
|
||||
|
||||
if (! empty($merge)) {
|
||||
$this->merge($merge);
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* 유효성 검사 규칙
|
||||
*
|
||||
|
||||
+72
@@ -0,0 +1,72 @@
|
||||
<?php
|
||||
|
||||
namespace Modules\Sirsoft\Ecommerce\Http\Requests\Admin;
|
||||
|
||||
use Illuminate\Foundation\Http\FormRequest;
|
||||
|
||||
/**
|
||||
* 상품정보제공고시 템플릿 목록 조회 요청
|
||||
*/
|
||||
class ProductNoticeTemplateListRequest extends FormRequest
|
||||
{
|
||||
/**
|
||||
* 사용자가 이 요청을 수행할 권한이 있는지 확인
|
||||
*
|
||||
* 권한 체크는 라우트의 permission 미들웨어에서 수행됩니다.
|
||||
*
|
||||
* @return bool 항상 true (권한은 미들웨어에서 검증)
|
||||
*/
|
||||
public function authorize(): bool
|
||||
{
|
||||
return true;
|
||||
}
|
||||
|
||||
/**
|
||||
* 검증 전 데이터 전처리
|
||||
*
|
||||
* URL 쿼리 파라미터는 문자열로 전달되므로 boolean 변환이 필요합니다.
|
||||
*/
|
||||
protected function prepareForValidation(): void
|
||||
{
|
||||
if ($this->has('active_only')) {
|
||||
$value = $this->input('active_only');
|
||||
$this->merge([
|
||||
'active_only' => filter_var($value, FILTER_VALIDATE_BOOLEAN, FILTER_NULL_ON_FAILURE),
|
||||
]);
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* 요청에 적용할 검증 규칙
|
||||
*
|
||||
* per_page 는 정수 또는 전체 조회용 'all' 키워드를 허용합니다.
|
||||
*
|
||||
* @return array 검증 규칙
|
||||
*/
|
||||
public function rules(): array
|
||||
{
|
||||
return [
|
||||
'search' => 'nullable|string|max:200',
|
||||
'active_only' => 'nullable|boolean',
|
||||
'per_page' => ['nullable', 'regex:/^(all|\d+)$/'],
|
||||
'page' => 'nullable|integer|min:1',
|
||||
];
|
||||
}
|
||||
|
||||
/**
|
||||
* 검증 오류 메시지 커스터마이징
|
||||
*
|
||||
* @return array<string, string> 검증 오류 메시지
|
||||
*/
|
||||
public function messages(): array
|
||||
{
|
||||
return [
|
||||
'search.string' => __('sirsoft-ecommerce::validation.list.search.string'),
|
||||
'search.max' => __('sirsoft-ecommerce::validation.list.search.max'),
|
||||
'active_only.boolean' => __('sirsoft-ecommerce::validation.list.active_only.boolean'),
|
||||
'per_page.regex' => __('sirsoft-ecommerce::validation.list.per_page.integer'),
|
||||
'page.integer' => __('sirsoft-ecommerce::validation.list.page.integer'),
|
||||
'page.min' => __('sirsoft-ecommerce::validation.list.page.min'),
|
||||
];
|
||||
}
|
||||
}
|
||||
+64
@@ -0,0 +1,64 @@
|
||||
<?php
|
||||
|
||||
namespace Modules\Sirsoft\Ecommerce\Http\Requests\Admin;
|
||||
|
||||
use Illuminate\Foundation\Http\FormRequest;
|
||||
|
||||
/**
|
||||
* 비회원 주문 조회 비밀번호 재설정 요청 (관리자)
|
||||
*
|
||||
* 관리자가 비회원 주문의 조회 비밀번호를 새 값으로 재설정할 때 사용됩니다.
|
||||
* 검증 규칙은 비회원 주문 생성 시(Public\CreateOrderRequest)와 동일하게
|
||||
* 8자 이상 + 확인 일치를 강제합니다 (G7 회원가입 정책 min:8|confirmed 와 일치).
|
||||
*/
|
||||
class ResetGuestLookupPasswordRequest extends FormRequest
|
||||
{
|
||||
/**
|
||||
* 사용자가 이 요청을 수행할 권한이 있는지 확인
|
||||
*
|
||||
* 권한 체크는 라우트의 permission 미들웨어에서 수행됩니다.
|
||||
*
|
||||
* @return bool 항상 true (실제 권한 검증은 미들웨어가 수행)
|
||||
*/
|
||||
public function authorize(): bool
|
||||
{
|
||||
return true;
|
||||
}
|
||||
|
||||
/**
|
||||
* 요청에 적용할 검증 규칙
|
||||
*
|
||||
* @return array<string, array<int, string>>
|
||||
*/
|
||||
public function rules(): array
|
||||
{
|
||||
// G7 회원가입 정책과 일치 — RegisterRequest 의 min:8|confirmed
|
||||
return [
|
||||
'guest_lookup_password' => [
|
||||
'required',
|
||||
'string',
|
||||
'min:8',
|
||||
'max:255',
|
||||
'confirmed',
|
||||
],
|
||||
'guest_lookup_password_confirmation' => ['required', 'string'],
|
||||
];
|
||||
}
|
||||
|
||||
/**
|
||||
* 검증 오류 메시지 커스터마이징
|
||||
*
|
||||
* 비회원 주문 생성 시와 동일한 다국어 키를 재사용합니다.
|
||||
*
|
||||
* @return array<string, string>
|
||||
*/
|
||||
public function messages(): array
|
||||
{
|
||||
return [
|
||||
'guest_lookup_password.required' => __('sirsoft-ecommerce::validation.order.guest_lookup_password_required'),
|
||||
'guest_lookup_password.min' => __('sirsoft-ecommerce::validation.order.guest_lookup_password_min'),
|
||||
'guest_lookup_password.confirmed' => __('sirsoft-ecommerce::validation.order.guest_lookup_password_confirmed'),
|
||||
'guest_lookup_password_confirmation.required' => __('sirsoft-ecommerce::validation.order.guest_lookup_password_confirmation_required'),
|
||||
];
|
||||
}
|
||||
}
|
||||
@@ -8,12 +8,14 @@ use App\Rules\LocaleRequiredTranslatable;
|
||||
use App\Rules\TranslatableField;
|
||||
use Illuminate\Foundation\Http\FormRequest;
|
||||
use Illuminate\Validation\Rule;
|
||||
use Illuminate\Validation\Validator;
|
||||
use Modules\Sirsoft\Ecommerce\Enums\CouponDiscountType;
|
||||
use Modules\Sirsoft\Ecommerce\Enums\CouponIssueCondition;
|
||||
use Modules\Sirsoft\Ecommerce\Enums\CouponIssueMethod;
|
||||
use Modules\Sirsoft\Ecommerce\Enums\CouponIssueStatus;
|
||||
use Modules\Sirsoft\Ecommerce\Enums\CouponTargetScope;
|
||||
use Modules\Sirsoft\Ecommerce\Enums\CouponTargetType;
|
||||
use Modules\Sirsoft\Ecommerce\Http\Requests\Admin\Concerns\ValidatesCouponTargetScope;
|
||||
use Modules\Sirsoft\Ecommerce\Models\Category;
|
||||
use Modules\Sirsoft\Ecommerce\Models\Product;
|
||||
|
||||
@@ -22,18 +24,60 @@ use Modules\Sirsoft\Ecommerce\Models\Product;
|
||||
*/
|
||||
class StoreCouponRequest extends FormRequest
|
||||
{
|
||||
use ValidatesCouponTargetScope;
|
||||
|
||||
/**
|
||||
* 사용자가 이 요청을 수행할 권한이 있는지 확인
|
||||
*
|
||||
* @return bool 권한 미들웨어가 처리하므로 항상 true
|
||||
*/
|
||||
public function authorize(): bool
|
||||
{
|
||||
return true;
|
||||
}
|
||||
|
||||
/**
|
||||
* 추가 검증을 등록합니다. (적용대상 미선택 차단 — A16①/A17①)
|
||||
*
|
||||
* @param Validator $validator 검증기 인스턴스
|
||||
*/
|
||||
public function withValidator(Validator $validator): void
|
||||
{
|
||||
$this->validateTargetScopeSelection($validator);
|
||||
}
|
||||
|
||||
/**
|
||||
* 검증 전 입력값을 정규화합니다.
|
||||
*
|
||||
* nullable 숫자 필드(discount_max_amount/total_quantity)와 NOT NULL default 0 인
|
||||
* min_order_amount 의 빈 문자열 입력을 각각 null / 0 으로 변환해
|
||||
* decimal/integer cast 오류(빈 문자열 → 저장 500)를 차단합니다.
|
||||
*/
|
||||
protected function prepareForValidation(): void
|
||||
{
|
||||
$merge = [];
|
||||
|
||||
// nullable 숫자 → 빈 문자열이면 null
|
||||
foreach (['discount_max_amount', 'total_quantity'] as $field) {
|
||||
if ($this->input($field) === '') {
|
||||
$merge[$field] = null;
|
||||
}
|
||||
}
|
||||
|
||||
// min_order_amount 는 NOT NULL default 0 → 빈 문자열/ null 이면 0("최소금액 없음")
|
||||
if (in_array($this->input('min_order_amount'), ['', null], true)) {
|
||||
$merge['min_order_amount'] = 0;
|
||||
}
|
||||
|
||||
if ($merge) {
|
||||
$this->merge($merge);
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* 요청에 적용할 검증 규칙
|
||||
*
|
||||
* @return array
|
||||
* @return array 검증 규칙 배열
|
||||
*/
|
||||
public function rules(): array
|
||||
{
|
||||
@@ -86,8 +130,6 @@ class StoreCouponRequest extends FormRequest
|
||||
|
||||
/**
|
||||
* 할인값 검증 규칙을 반환합니다.
|
||||
*
|
||||
* @return array
|
||||
*/
|
||||
protected function discountValueRules(): array
|
||||
{
|
||||
@@ -95,7 +137,8 @@ class StoreCouponRequest extends FormRequest
|
||||
return ['required', 'numeric', 'min:1', 'max:100'];
|
||||
}
|
||||
|
||||
return ['required', 'numeric', 'min:0'];
|
||||
// 정액(fixed): 1원 이상 (0/음수 차단 — A14)
|
||||
return ['required', 'numeric', 'min:1'];
|
||||
}
|
||||
|
||||
/**
|
||||
@@ -106,7 +149,7 @@ class StoreCouponRequest extends FormRequest
|
||||
*
|
||||
* @param string|null $key 특정 키만 반환
|
||||
* @param mixed $default 기본값
|
||||
* @return mixed
|
||||
* @return mixed 타임존 변환된 검증 데이터
|
||||
*/
|
||||
public function validated($key = null, $default = null): mixed
|
||||
{
|
||||
@@ -142,10 +185,13 @@ class StoreCouponRequest extends FormRequest
|
||||
/**
|
||||
* 검증 오류 메시지 커스터마이징
|
||||
*
|
||||
* @return array
|
||||
* @return array 필드별 오류 메시지 배열
|
||||
*/
|
||||
public function messages(): array
|
||||
{
|
||||
// 정액/정률에 따라 discount_value.min 메시지를 분기 (A14 — 정액 음수에 정률 메시지 노출 회피)
|
||||
$isRate = $this->input('discount_type') === CouponDiscountType::RATE->value;
|
||||
|
||||
return [
|
||||
'name.required' => __('sirsoft-ecommerce::validation.coupon.name_required'),
|
||||
'target_type.required' => __('sirsoft-ecommerce::validation.coupon.target_type_required'),
|
||||
@@ -154,7 +200,9 @@ class StoreCouponRequest extends FormRequest
|
||||
'issue_method.required' => __('sirsoft-ecommerce::validation.coupon.issue_method_required'),
|
||||
'issue_condition.required' => __('sirsoft-ecommerce::validation.coupon.issue_condition_required'),
|
||||
'valid_type.required' => __('sirsoft-ecommerce::validation.coupon.valid_type_required'),
|
||||
'discount_value.min' => __('sirsoft-ecommerce::validation.coupon.discount_value_rate_min'),
|
||||
'discount_value.min' => $isRate
|
||||
? __('sirsoft-ecommerce::validation.coupon.discount_value_rate_min')
|
||||
: __('sirsoft-ecommerce::validation.coupon.discount_value_fixed_min'),
|
||||
'discount_value.max' => __('sirsoft-ecommerce::validation.coupon.discount_value_rate_max'),
|
||||
'valid_days.required_if' => __('sirsoft-ecommerce::validation.coupon.valid_days_required'),
|
||||
'valid_from.required_if' => __('sirsoft-ecommerce::validation.coupon.valid_from_required'),
|
||||
|
||||
+207
-16
@@ -6,6 +6,9 @@ use App\Rules\LocaleRequiredTranslatable;
|
||||
use Illuminate\Foundation\Http\FormRequest;
|
||||
use Illuminate\Validation\Validator;
|
||||
use Modules\Sirsoft\Ecommerce\Enums\PaymentMethodEnum;
|
||||
use Modules\Sirsoft\Ecommerce\Repositories\Contracts\OrderRepositoryInterface;
|
||||
use Modules\Sirsoft\Ecommerce\Repositories\Contracts\ProductRepositoryInterface;
|
||||
use Modules\Sirsoft\Ecommerce\Services\EcommerceSettingsService;
|
||||
|
||||
/**
|
||||
* 이커머스 설정 저장 요청 검증
|
||||
@@ -16,6 +19,8 @@ class StoreEcommerceSettingsRequest extends FormRequest
|
||||
* 사용자가 이 요청을 수행할 권한이 있는지 확인
|
||||
*
|
||||
* 권한 체크는 라우트의 permission 미들웨어에서 수행됩니다.
|
||||
*
|
||||
* @return bool 항상 true
|
||||
*/
|
||||
public function authorize(): bool
|
||||
{
|
||||
@@ -32,7 +37,7 @@ class StoreEcommerceSettingsRequest extends FormRequest
|
||||
$locale = app()->getLocale();
|
||||
|
||||
return [
|
||||
'_tab' => ['sometimes', 'string', 'in:basic_info,language_currency,seo,order_settings,claim,shipping,review_settings,notification_definitions,notifications,inquiry'],
|
||||
'_tab' => ['sometimes', 'string', 'in:basic_info,language_currency,seo,order_settings,claim,shipping,review_settings,notification_definitions,notifications,inquiry,mileage'],
|
||||
|
||||
'notifications' => ['sometimes', 'array'],
|
||||
'notifications.channels' => ['sometimes', 'array'],
|
||||
@@ -68,17 +73,23 @@ class StoreEcommerceSettingsRequest extends FormRequest
|
||||
'basic_info.telecom_number' => ['nullable', 'string', 'max:100'],
|
||||
|
||||
'language_currency' => ['sometimes', 'array'],
|
||||
'language_currency.default_language' => ['nullable', 'string', 'max:10'],
|
||||
// default_language 제거 (A1-⑤, D-LANG): 사이트 언어는 코어 일반설정으로 일원화. 모듈 orphan 필드.
|
||||
'language_currency.default_currency' => ['nullable', 'string', 'max:10'],
|
||||
'language_currency.currencies' => ['nullable', 'array'],
|
||||
'language_currency.currencies.*.code' => ['required_with:language_currency.currencies', 'string', 'max:10'],
|
||||
'language_currency.currencies.*.code' => ['required_with:language_currency.currencies', 'string', 'regex:/^[A-Z]{3}$/'],
|
||||
'language_currency.currencies.*.name' => ['required_with:language_currency.currencies', 'array'],
|
||||
'language_currency.currencies.*.name.*' => ['string', 'max:100'],
|
||||
'language_currency.currencies.*.symbol' => ['nullable', 'string', 'max:8'],
|
||||
'language_currency.currencies.*.exchange_rate' => ['nullable', 'numeric', 'min:0'],
|
||||
// base_unit = 그 통화가 기본일 때 환율 입력의 분모(1단위 금액). 소액통화만 묶음(KRW=1000, JPY=100).
|
||||
'language_currency.currencies.*.base_unit' => ['nullable', 'integer', 'min:1'],
|
||||
'language_currency.currencies.*.rounding_unit' => ['nullable', 'string'],
|
||||
'language_currency.currencies.*.rounding_method' => ['nullable', 'string', 'in:floor,round,ceil'],
|
||||
'language_currency.currencies.*.decimal_places' => ['nullable', 'integer', 'min:0', 'max:8'],
|
||||
'language_currency.currencies.*.is_default' => ['nullable', 'boolean'],
|
||||
// 통화별 언어(가입 시 통화 추정용 매핑, A4). 후보 = 시스템 지원 로케일.
|
||||
'language_currency.currencies.*.locales' => ['nullable', 'array'],
|
||||
'language_currency.currencies.*.locales.*' => ['string', 'in:'.implode(',', config('app.supported_locales', ['ko', 'en']))],
|
||||
|
||||
'seo' => ['sometimes', 'array'],
|
||||
'seo.meta_category_title' => ['nullable', 'string', 'max:500'],
|
||||
@@ -108,6 +119,7 @@ class StoreEcommerceSettingsRequest extends FormRequest
|
||||
'order_settings.payment_methods.*.is_active' => ['nullable', 'boolean'],
|
||||
'order_settings.payment_methods.*.min_order_amount' => ['nullable', 'integer', 'min:0'],
|
||||
'order_settings.payment_methods.*.stock_deduction_timing' => ['nullable', 'string', 'in:order_placed,payment_complete,none'],
|
||||
'order_settings.payment_methods.*.mileage_deduction_timing' => ['nullable', 'string', 'in:order_placed,payment_complete'],
|
||||
'order_settings.banks' => ['nullable', 'array'],
|
||||
'order_settings.banks.*.code' => ['required_with:order_settings.banks', 'string', 'max:10'],
|
||||
'order_settings.banks.*.name' => ['required_with:order_settings.banks', 'array'],
|
||||
@@ -121,8 +133,6 @@ class StoreEcommerceSettingsRequest extends FormRequest
|
||||
'order_settings.bank_accounts.*.is_default' => ['nullable', 'boolean'],
|
||||
'order_settings.auto_cancel_expired' => ['nullable', 'boolean'],
|
||||
'order_settings.auto_cancel_days' => ['nullable', 'integer', 'min:0', 'max:30'],
|
||||
'order_settings.vbank_due_days' => ['nullable', 'integer', 'min:1', 'max:30'],
|
||||
'order_settings.dbank_due_days' => ['nullable', 'integer', 'min:1', 'max:30'],
|
||||
'order_settings.cart_expiry_days' => ['nullable', 'integer', 'min:1', 'max:365'],
|
||||
'order_settings.stock_restore_on_cancel' => ['nullable', 'boolean'],
|
||||
'order_settings.confirmable_statuses' => ['nullable', 'array'],
|
||||
@@ -145,6 +155,29 @@ class StoreEcommerceSettingsRequest extends FormRequest
|
||||
'review_settings.max_images' => ['nullable', 'integer', 'min:0', 'max:20'],
|
||||
'review_settings.max_image_size_mb' => ['nullable', 'integer', 'min:1', 'max:50'],
|
||||
|
||||
// mileage 섹션
|
||||
'mileage' => ['sometimes', 'array'],
|
||||
'mileage.enabled' => ['required_with:mileage', 'boolean'],
|
||||
'mileage.default_earn_rate' => ['nullable', 'numeric', 'min:0', 'max:100'],
|
||||
// 마일리지 차감 시점은 결제수단별(order_settings.payment_methods.*.mileage_deduction_timing)로 관리한다.
|
||||
'mileage.earn_trigger' => ['nullable', 'string', 'in:delivered,confirmed'],
|
||||
'mileage.earn_delay_days' => ['nullable', 'integer', 'min:0', 'max:365'],
|
||||
'mileage.currency_rules' => ['nullable', 'array'],
|
||||
// 통화 코드: ISO 4217 형식(3자리 영문 대문자) 강제
|
||||
'mileage.currency_rules.*.currency_code' => ['required_with:mileage.currency_rules', 'string', 'regex:/^[A-Z]{3}$/'],
|
||||
// 1점당 금액: 0이면 마일리지가 금전 가치 0 → 사용 불가. 최소 0 초과(0.001 단위까지 허용)
|
||||
'mileage.currency_rules.*.point_value' => ['nullable', 'numeric', 'min:0.001'],
|
||||
'mileage.currency_rules.*.min_use_amount' => ['nullable', 'integer', 'min:0'],
|
||||
'mileage.currency_rules.*.use_unit' => ['nullable', 'integer', 'min:1'],
|
||||
'mileage.currency_rules.*.max_use_type' => ['nullable', 'string', 'in:percent,fixed'],
|
||||
'mileage.currency_rules.*.max_use_percent' => ['nullable', 'numeric', 'min:0', 'max:100'],
|
||||
// 최대 사용한도(고정금액): 비합리적 거액 방지를 위해 10억 상한
|
||||
'mileage.currency_rules.*.max_use_value' => ['nullable', 'integer', 'min:0', 'max:1000000000'],
|
||||
'mileage.expiry_enabled' => ['nullable', 'boolean'],
|
||||
'mileage.expiry_days' => ['nullable', 'integer', 'min:1', 'max:3650'],
|
||||
'mileage.expiry_notification_enabled' => ['nullable', 'boolean'],
|
||||
'mileage.expiry_notification_days_before' => ['nullable', 'integer', 'min:1', 'max:365'],
|
||||
|
||||
// shipping 섹션
|
||||
'shipping' => ['sometimes', 'array'],
|
||||
'shipping.default_country' => ['nullable', 'string', 'max:10'],
|
||||
@@ -198,6 +231,7 @@ class StoreEcommerceSettingsRequest extends FormRequest
|
||||
public function withValidator(Validator $validator): void
|
||||
{
|
||||
$validator->after(function (Validator $validator) {
|
||||
$this->validateBaseCurrencyChangeable($validator);
|
||||
$this->validateUniqueCurrencyCodes($validator);
|
||||
$this->validateCurrencyNames($validator);
|
||||
$this->validateAtLeastOneActivePaymentMethod($validator);
|
||||
@@ -212,9 +246,165 @@ class StoreEcommerceSettingsRequest extends FormRequest
|
||||
$this->validateShippingTypeNames($validator);
|
||||
$this->validateUniqueRefundReasonCodes($validator);
|
||||
$this->validateRefundReasonNames($validator);
|
||||
$this->validateMileageCurrencyRules($validator);
|
||||
$this->validateMileageEarnRate($validator);
|
||||
});
|
||||
}
|
||||
|
||||
/**
|
||||
* 기본 통화(default_currency) 변경 가능 여부 검증 (A2 — D-BASE-1)
|
||||
*
|
||||
* 상품 또는 주문이 1건이라도 존재하면 기본 통화 변경을 차단한다. base 통화는 모든 금액
|
||||
* 테이블의 SSoT 이고 소급 변환이 데이터 정합성을 깨므로, 데이터가 생긴 이후에는 영구 잠금한다.
|
||||
* (소프트삭제 포함 — 삭제분도 과거 base 로 생성된 이력) 동일 통화 재저장은 변경이 아니므로 통과.
|
||||
*
|
||||
* @param Validator $validator Validator 인스턴스
|
||||
*/
|
||||
protected function validateBaseCurrencyChangeable(Validator $validator): void
|
||||
{
|
||||
$newDefault = $this->input('language_currency.default_currency');
|
||||
if ($newDefault === null) {
|
||||
return; // 통화 설정 미전달 — 변경 아님
|
||||
}
|
||||
|
||||
$current = app(EcommerceSettingsService::class)->getSetting('language_currency.default_currency');
|
||||
if ($newDefault === $current) {
|
||||
return; // 동일 통화 재저장 — 변경 아님
|
||||
}
|
||||
|
||||
// 상품/주문 1건이라도 있으면 base 변경 불가 (영구 잠금, 소프트삭제 포함)
|
||||
$hasData = app(ProductRepositoryInterface::class)->existsAny()
|
||||
|| app(OrderRepositoryInterface::class)->existsAny();
|
||||
|
||||
if ($hasData) {
|
||||
$validator->errors()->add(
|
||||
'language_currency.default_currency',
|
||||
__('sirsoft-ecommerce::validation.custom.language_currency.base_locked_after_data')
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* 마일리지 활성화 시 기본 적립률 검증
|
||||
*
|
||||
* 마일리지 사용(enabled)을 켰는데 기본 적립률이 0%면 적립이 전혀 발생하지 않아
|
||||
* 활성화 의미가 없으므로 거부한다. (비활성 상태에서는 0% 허용)
|
||||
*
|
||||
* @param Validator $validator Validator 인스턴스
|
||||
*/
|
||||
protected function validateMileageEarnRate(Validator $validator): void
|
||||
{
|
||||
if (! $this->has('mileage')) {
|
||||
return;
|
||||
}
|
||||
|
||||
$enabled = $this->boolean('mileage.enabled');
|
||||
$rate = $this->input('mileage.default_earn_rate');
|
||||
|
||||
if ($enabled && $rate !== null && (float) $rate <= 0) {
|
||||
$validator->errors()->add(
|
||||
'mileage.default_earn_rate',
|
||||
__('sirsoft-ecommerce::validation.mileage.earn_rate_required_when_enabled')
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* 마일리지 통화 규칙 검증
|
||||
*
|
||||
* 1) 통화 코드 중복 금지
|
||||
* 2) 첫 행은 기본 통화여야 함 (기본 통화 행 보장)
|
||||
* 3) 등록된 통화(language_currency.currencies)만 허용 (정합성)
|
||||
*
|
||||
* 형식(ISO 4217)은 rules() 의 regex 로 선검증되며, 여기서는 도메인 정합성만 다룬다.
|
||||
*
|
||||
* @param Validator $validator Validator 인스턴스
|
||||
*/
|
||||
protected function validateMileageCurrencyRules(Validator $validator): void
|
||||
{
|
||||
$rules = $this->input('mileage.currency_rules', []);
|
||||
|
||||
if (empty($rules) || ! is_array($rules)) {
|
||||
return;
|
||||
}
|
||||
|
||||
[$defaultCurrency, $registeredCodes] = $this->resolveRegisteredCurrencies();
|
||||
|
||||
$codes = [];
|
||||
foreach ($rules as $index => $rule) {
|
||||
if (! isset($rule['currency_code']) || ! is_string($rule['currency_code'])) {
|
||||
continue;
|
||||
}
|
||||
|
||||
$code = strtoupper(trim($rule['currency_code']));
|
||||
|
||||
// 형식 위반(regex 미통과)은 rules() 에서 이미 에러 추가됨 → 도메인 검증 스킵
|
||||
if (! preg_match('/^[A-Z]{3}$/', $code)) {
|
||||
$codes[] = $code;
|
||||
|
||||
continue;
|
||||
}
|
||||
|
||||
// 1) 중복
|
||||
if (in_array($code, $codes, true)) {
|
||||
$validator->errors()->add(
|
||||
"mileage.currency_rules.{$index}.currency_code",
|
||||
__('sirsoft-ecommerce::validation.mileage.duplicate_currency')
|
||||
);
|
||||
}
|
||||
|
||||
// 2) 첫 행 = 기본 통화
|
||||
if ($index === 0 && $defaultCurrency !== null && $code !== $defaultCurrency) {
|
||||
$validator->errors()->add(
|
||||
'mileage.currency_rules.0.currency_code',
|
||||
__('sirsoft-ecommerce::validation.mileage.first_must_be_default', ['currency' => $defaultCurrency])
|
||||
);
|
||||
}
|
||||
|
||||
// 3) 등록 통화 정합성 (등록 목록이 있을 때만)
|
||||
if (! empty($registeredCodes) && ! in_array($code, $registeredCodes, true)) {
|
||||
$validator->errors()->add(
|
||||
"mileage.currency_rules.{$index}.currency_code",
|
||||
__('sirsoft-ecommerce::validation.mileage.currency_not_registered', ['currency' => $code])
|
||||
);
|
||||
}
|
||||
|
||||
$codes[] = $code;
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* 검증 기준이 되는 등록 통화 정보를 해석합니다.
|
||||
*
|
||||
* 같은 요청에 language_currency 가 함께 오면 그 값을, 아니면 현재 저장된 설정을 기준으로 한다
|
||||
* (탭별 저장 시 마일리지 탭은 현재 통화 설정을 기준으로 정합성 검증).
|
||||
*
|
||||
* @return array{0: ?string, 1: array<int, string>} [기본통화코드, 등록통화코드목록]
|
||||
*/
|
||||
protected function resolveRegisteredCurrencies(): array
|
||||
{
|
||||
$defaultCurrency = $this->input('language_currency.default_currency');
|
||||
$currencies = $this->input('language_currency.currencies');
|
||||
|
||||
// 요청에 language_currency 가 없으면 현재 저장 설정에서 조회
|
||||
if ($defaultCurrency === null || ! is_array($currencies)) {
|
||||
$settings = app(EcommerceSettingsService::class);
|
||||
$defaultCurrency = $defaultCurrency ?? $settings->getSetting('language_currency.default_currency');
|
||||
$currencies = is_array($currencies) ? $currencies : ($settings->getSetting('language_currency.currencies') ?? []);
|
||||
}
|
||||
|
||||
$codes = [];
|
||||
foreach ((array) $currencies as $currency) {
|
||||
if (isset($currency['code']) && is_string($currency['code'])) {
|
||||
$codes[] = strtoupper(trim($currency['code']));
|
||||
}
|
||||
}
|
||||
|
||||
$defaultCurrency = is_string($defaultCurrency) ? strtoupper(trim($defaultCurrency)) : null;
|
||||
|
||||
return [$defaultCurrency, $codes];
|
||||
}
|
||||
|
||||
/**
|
||||
* 통화 코드 중복 검증
|
||||
*
|
||||
@@ -742,14 +932,21 @@ class StoreEcommerceSettingsRequest extends FormRequest
|
||||
'basic_info.telecom_number.string' => __('sirsoft-ecommerce::validation.custom.basic_info.telecom_number.string'),
|
||||
'basic_info.telecom_number.max' => __('sirsoft-ecommerce::validation.custom.basic_info.telecom_number.max'),
|
||||
|
||||
// language_currency 섹션
|
||||
'language_currency.default_language.string' => __('sirsoft-ecommerce::validation.custom.language_currency.default_language.string'),
|
||||
'language_currency.default_language.max' => __('sirsoft-ecommerce::validation.custom.language_currency.default_language.max'),
|
||||
// language_currency 섹션 (default_language 제거 — A1-⑤, D-LANG)
|
||||
'language_currency.default_currency.string' => __('sirsoft-ecommerce::validation.custom.language_currency.default_currency.string'),
|
||||
'language_currency.default_currency.max' => __('sirsoft-ecommerce::validation.custom.language_currency.default_currency.max'),
|
||||
'language_currency.currencies.*.code.required_with' => __('sirsoft-ecommerce::validation.custom.language_currency.currencies.code.required_with'),
|
||||
'language_currency.currencies.*.code.string' => __('sirsoft-ecommerce::validation.custom.language_currency.currencies.code.string'),
|
||||
'language_currency.currencies.*.code.max' => __('sirsoft-ecommerce::validation.custom.language_currency.currencies.code.max'),
|
||||
'language_currency.currencies.*.code.regex' => __('sirsoft-ecommerce::validation.custom.language_currency.currencies.code.regex'),
|
||||
|
||||
// mileage 통화 규칙 섹션
|
||||
'mileage.currency_rules.*.currency_code.required_with' => __('sirsoft-ecommerce::validation.custom.mileage.currency_rules.currency_code.required_with'),
|
||||
'mileage.currency_rules.*.currency_code.regex' => __('sirsoft-ecommerce::validation.custom.mileage.currency_rules.currency_code.regex'),
|
||||
'mileage.currency_rules.*.point_value.numeric' => __('sirsoft-ecommerce::validation.custom.mileage.currency_rules.point_value.numeric'),
|
||||
'mileage.currency_rules.*.point_value.min' => __('sirsoft-ecommerce::validation.custom.mileage.currency_rules.point_value.min'),
|
||||
'mileage.currency_rules.*.max_use_value.integer' => __('sirsoft-ecommerce::validation.custom.mileage.currency_rules.max_use_value.integer'),
|
||||
'mileage.currency_rules.*.max_use_value.min' => __('sirsoft-ecommerce::validation.custom.mileage.currency_rules.max_use_value.min'),
|
||||
'mileage.currency_rules.*.max_use_value.max' => __('sirsoft-ecommerce::validation.custom.mileage.currency_rules.max_use_value.max'),
|
||||
'language_currency.currencies.*.name.required_with' => __('sirsoft-ecommerce::validation.custom.language_currency.currencies.name.required_with'),
|
||||
'language_currency.currencies.*.name.array' => __('sirsoft-ecommerce::validation.custom.language_currency.currencies.name.array'),
|
||||
'language_currency.currencies.*.name.*.string' => __('sirsoft-ecommerce::validation.custom.language_currency.currencies.name.string'),
|
||||
@@ -822,12 +1019,6 @@ class StoreEcommerceSettingsRequest extends FormRequest
|
||||
'order_settings.auto_cancel_days.integer' => __('sirsoft-ecommerce::validation.custom.order_settings.auto_cancel_days.integer'),
|
||||
'order_settings.auto_cancel_days.min' => __('sirsoft-ecommerce::validation.custom.order_settings.auto_cancel_days.min'),
|
||||
'order_settings.auto_cancel_days.max' => __('sirsoft-ecommerce::validation.custom.order_settings.auto_cancel_days.max'),
|
||||
'order_settings.vbank_due_days.integer' => __('sirsoft-ecommerce::validation.custom.order_settings.vbank_due_days.integer'),
|
||||
'order_settings.vbank_due_days.min' => __('sirsoft-ecommerce::validation.custom.order_settings.vbank_due_days.min'),
|
||||
'order_settings.vbank_due_days.max' => __('sirsoft-ecommerce::validation.custom.order_settings.vbank_due_days.max'),
|
||||
'order_settings.dbank_due_days.integer' => __('sirsoft-ecommerce::validation.custom.order_settings.dbank_due_days.integer'),
|
||||
'order_settings.dbank_due_days.min' => __('sirsoft-ecommerce::validation.custom.order_settings.dbank_due_days.min'),
|
||||
'order_settings.dbank_due_days.max' => __('sirsoft-ecommerce::validation.custom.order_settings.dbank_due_days.max'),
|
||||
'order_settings.cart_expiry_days.integer' => __('sirsoft-ecommerce::validation.custom.order_settings.cart_expiry_days.integer'),
|
||||
'order_settings.cart_expiry_days.min' => __('sirsoft-ecommerce::validation.custom.order_settings.cart_expiry_days.min'),
|
||||
'order_settings.cart_expiry_days.max' => __('sirsoft-ecommerce::validation.custom.order_settings.cart_expiry_days.max'),
|
||||
@@ -890,7 +1081,7 @@ class StoreEcommerceSettingsRequest extends FormRequest
|
||||
public function validatedSettings(): array
|
||||
{
|
||||
$validated = $this->validated();
|
||||
$validCategories = ['basic_info', 'language_currency', 'seo', 'order_settings', 'claim', 'shipping', 'review_settings', 'inquiry', 'notifications'];
|
||||
$validCategories = ['basic_info', 'language_currency', 'seo', 'order_settings', 'claim', 'shipping', 'review_settings', 'inquiry', 'notifications', 'mileage'];
|
||||
|
||||
return array_filter(
|
||||
$validated,
|
||||
|
||||
+57
@@ -0,0 +1,57 @@
|
||||
<?php
|
||||
|
||||
namespace Modules\Sirsoft\Ecommerce\Http\Requests\Admin;
|
||||
|
||||
use App\Models\User;
|
||||
use Illuminate\Foundation\Http\FormRequest;
|
||||
use Illuminate\Validation\Rule;
|
||||
|
||||
/**
|
||||
* 관리자 마일리지 수동 지급/차감 요청
|
||||
*/
|
||||
class StoreMileageTransactionRequest extends FormRequest
|
||||
{
|
||||
/**
|
||||
* 권한 체크는 라우트의 permission 미들웨어에서 수행됩니다.
|
||||
*
|
||||
* @return bool 항상 true
|
||||
*/
|
||||
public function authorize(): bool
|
||||
{
|
||||
return true;
|
||||
}
|
||||
|
||||
/**
|
||||
* 검증 규칙
|
||||
*
|
||||
* @return array 검증 규칙
|
||||
*/
|
||||
public function rules(): array
|
||||
{
|
||||
return [
|
||||
'user_id' => ['required', 'uuid', Rule::exists(User::class, 'uuid')],
|
||||
'action' => ['required', 'string', 'in:earn,deduct'],
|
||||
'amount' => ['required', 'integer', 'min:1'],
|
||||
'currency' => ['required', 'string', 'max:10'],
|
||||
'memo' => ['nullable', 'string', 'max:1000'],
|
||||
'description' => ['nullable', 'string', 'max:500'],
|
||||
// 지급 시에만 사용 (직접 만료일 / 무기한 여부)
|
||||
'expires_at' => ['nullable', 'date'],
|
||||
'use_default_expiry' => ['nullable', 'boolean'],
|
||||
];
|
||||
}
|
||||
|
||||
/**
|
||||
* 다국어 검증 메시지
|
||||
*
|
||||
* @return array 메시지
|
||||
*/
|
||||
public function messages(): array
|
||||
{
|
||||
return [
|
||||
'user_id.required' => __('sirsoft-ecommerce::validation.mileage.user_required'),
|
||||
'amount.min' => __('sirsoft-ecommerce::validation.mileage.amount_min'),
|
||||
'action.in' => __('sirsoft-ecommerce::validation.mileage.action_invalid'),
|
||||
];
|
||||
}
|
||||
}
|
||||
+139
-18
@@ -3,11 +3,14 @@
|
||||
namespace Modules\Sirsoft\Ecommerce\Http\Requests\Admin;
|
||||
|
||||
use App\Extension\HookManager;
|
||||
use App\Models\Role;
|
||||
use App\Rules\LocaleRequiredTranslatable;
|
||||
use App\Rules\TranslatableField;
|
||||
use Illuminate\Foundation\Http\FormRequest;
|
||||
use Illuminate\Validation\Rule;
|
||||
use Illuminate\Validation\Validator;
|
||||
use Modules\Sirsoft\Ecommerce\Enums\ProductDisplayStatus;
|
||||
use Modules\Sirsoft\Ecommerce\Enums\ProductImageCollection;
|
||||
use Modules\Sirsoft\Ecommerce\Enums\ProductSalesStatus;
|
||||
use Modules\Sirsoft\Ecommerce\Enums\ProductTaxStatus;
|
||||
use Modules\Sirsoft\Ecommerce\Models\Brand;
|
||||
@@ -15,7 +18,6 @@ use Modules\Sirsoft\Ecommerce\Models\Category;
|
||||
use Modules\Sirsoft\Ecommerce\Models\Product;
|
||||
use Modules\Sirsoft\Ecommerce\Models\ProductCommonInfo;
|
||||
use Modules\Sirsoft\Ecommerce\Models\ProductLabel;
|
||||
use App\Models\Role;
|
||||
use Modules\Sirsoft\Ecommerce\Models\ShippingPolicy;
|
||||
|
||||
/**
|
||||
@@ -26,7 +28,7 @@ class StoreProductRequest extends FormRequest
|
||||
/**
|
||||
* 권한 확인
|
||||
*
|
||||
* @return bool
|
||||
* @return bool 인가 여부 (권한 체크는 미들웨어에 위임)
|
||||
*/
|
||||
public function authorize(): bool
|
||||
{
|
||||
@@ -36,10 +38,15 @@ class StoreProductRequest extends FormRequest
|
||||
/**
|
||||
* 유효성 검사 규칙
|
||||
*
|
||||
* @return array
|
||||
* @return array 필드별 검증 규칙 배열
|
||||
*/
|
||||
public function rules(): array
|
||||
{
|
||||
// 기본통화의 소수 자릿수 — 가격 입력 허용 자릿수 상한.
|
||||
// KRW(0) 이면 정수만, USD/EUR(2) 이면 소수 2자리까지 허용.
|
||||
$decimalPlaces = $this->baseCurrencyDecimalPlaces();
|
||||
$priceRule = $decimalPlaces > 0 ? 'decimal:0,'.$decimalPlaces : 'integer';
|
||||
|
||||
$rules = [
|
||||
// 기본 정보
|
||||
'name' => ['required', 'array', new LocaleRequiredTranslatable(maxLength: 200)],
|
||||
@@ -55,9 +62,9 @@ class StoreProductRequest extends FormRequest
|
||||
// 브랜드
|
||||
'brand_id' => ['nullable', 'integer', Rule::exists(Brand::class, 'id')],
|
||||
|
||||
// 가격
|
||||
'list_price' => ['required', 'integer', 'min:1'],
|
||||
'selling_price' => ['required', 'integer', 'min:1', 'lte:list_price'],
|
||||
// 가격 (기본통화 기준 — 소수 통화는 소수 입력 허용)
|
||||
'list_price' => ['required', 'numeric', $priceRule, 'min:0.01'],
|
||||
'selling_price' => ['required', 'numeric', $priceRule, 'min:0.01', 'lte:list_price'],
|
||||
|
||||
// 재고
|
||||
'stock_quantity' => ['required', 'integer', 'min:0'],
|
||||
@@ -82,19 +89,21 @@ class StoreProductRequest extends FormRequest
|
||||
// 이미지 (별도 테이블)
|
||||
'thumbnail_hash' => ['nullable', 'string', 'max:64'],
|
||||
'image_temp_key' => ['nullable', 'string', 'max:64'],
|
||||
'images' => ['nullable', 'array', 'max:10'],
|
||||
'images' => ['nullable', 'array', 'max:'.ProductImageCollection::MAX_IMAGES_PER_COLLECTION],
|
||||
'images.*.id' => ['nullable', 'integer'],
|
||||
'images.*.hash' => ['nullable', 'string'],
|
||||
'images.*.url' => ['nullable', 'url'],
|
||||
'images.*.alt_text' => ['nullable', 'array', new TranslatableField()],
|
||||
'images.*.alt_text' => ['nullable', 'array', new TranslatableField],
|
||||
'images.*.is_thumbnail' => ['nullable', 'boolean'],
|
||||
'images.*.sort_order' => ['nullable', 'integer', 'min:0'],
|
||||
|
||||
// SEO
|
||||
'meta_title' => ['nullable', 'string', 'max:200'],
|
||||
'meta_description' => ['nullable', 'string', 'max:500'],
|
||||
// SEO (다국어 — name/description 과 동일 패턴, 언어별 SEO 분기 지원)
|
||||
'meta_title' => ['nullable', 'array', new TranslatableField(maxLength: 200)],
|
||||
'meta_description' => ['nullable', 'array', new TranslatableField(maxLength: 500)],
|
||||
'meta_keywords' => ['nullable', 'array'],
|
||||
'meta_keywords.*' => ['string', 'max:50'],
|
||||
'seo_sync_title' => ['nullable', 'boolean'],
|
||||
'seo_sync_description' => ['nullable', 'boolean'],
|
||||
'use_main_image_for_og' => ['nullable', 'boolean'],
|
||||
|
||||
// 옵션
|
||||
@@ -110,9 +119,9 @@ class StoreProductRequest extends FormRequest
|
||||
'options.*.option_values' => ['required_with:options', 'array'],
|
||||
'options.*.option_values.*.key' => ['required', 'array'],
|
||||
'options.*.option_values.*.value' => ['required', 'array'],
|
||||
'options.*.list_price' => ['required_with:options', 'integer', 'min:0'],
|
||||
'options.*.selling_price' => ['required_with:options', 'integer', 'min:0'],
|
||||
'options.*.price_adjustment' => ['nullable', 'integer'],
|
||||
'options.*.list_price' => ['required_with:options', 'numeric', $priceRule, 'min:0'],
|
||||
'options.*.selling_price' => ['required_with:options', 'numeric', $priceRule, 'min:0'],
|
||||
'options.*.price_adjustment' => ['nullable', 'numeric', $priceRule],
|
||||
'options.*.stock_quantity' => ['required_with:options', 'integer', 'min:0'],
|
||||
'options.*.safe_stock_quantity' => ['nullable', 'integer', 'min:0'],
|
||||
'options.*.sku' => ['nullable', 'string', 'max:100'],
|
||||
@@ -123,10 +132,21 @@ class StoreProductRequest extends FormRequest
|
||||
'options.*.is_default' => ['nullable', 'boolean'],
|
||||
'options.*.is_active' => ['nullable', 'boolean'],
|
||||
|
||||
// 추가옵션
|
||||
// 추가옵션 (그룹 + 선택지)
|
||||
'additional_options' => ['nullable', 'array', 'max:5'],
|
||||
'additional_options.*.name' => ['required_with:additional_options', 'array', new LocaleRequiredTranslatable(maxLength: 100)],
|
||||
'additional_options.*.is_required' => ['nullable', 'boolean'],
|
||||
'additional_options.*.sort_order' => ['nullable', 'integer', 'min:0'],
|
||||
// 선택지: 그룹당 1개 이상, 최대 20개. 빈 그룹 저장 차단 (D11)
|
||||
'additional_options.*.values' => ['required_with:additional_options', 'array', 'min:1', 'max:20'],
|
||||
'additional_options.*.values.*.name' => ['required', 'array', new LocaleRequiredTranslatable(maxLength: 100)],
|
||||
// 추가금: 0 이상만 허용 (음수 금지, D16). 기본통화 자릿수 따름 (소수 통화는 소수 허용)
|
||||
'additional_options.*.values.*.price_adjustment' => ['nullable', 'numeric', $priceRule, 'min:0'],
|
||||
'additional_options.*.values.*.is_default' => ['nullable', 'boolean'],
|
||||
'additional_options.*.values.*.is_active' => ['nullable', 'boolean'],
|
||||
// 직접입력 허용 — 유저가 이 선택지 선택 시 자유 텍스트 입력 필수 (E1/E4)
|
||||
'additional_options.*.values.*.allow_custom_text' => ['nullable', 'boolean'],
|
||||
'additional_options.*.values.*.sort_order' => ['nullable', 'integer', 'min:0'],
|
||||
|
||||
// 상품정보제공고시 (템플릿은 UI용, 저장하지 않음)
|
||||
'notice_items' => ['nullable', 'array', 'max:50'],
|
||||
@@ -159,7 +179,7 @@ class StoreProductRequest extends FormRequest
|
||||
/**
|
||||
* 유효성 검사 메시지
|
||||
*
|
||||
* @return array
|
||||
* @return array 검증 실패 메시지 배열
|
||||
*/
|
||||
public function messages(): array
|
||||
{
|
||||
@@ -202,6 +222,15 @@ class StoreProductRequest extends FormRequest
|
||||
'options.*.selling_price.required_with' => __('sirsoft-ecommerce::validation.product.options.selling_price.required_with'),
|
||||
'options.*.stock_quantity.required_with' => __('sirsoft-ecommerce::validation.product.options.stock_quantity.required_with'),
|
||||
|
||||
// 추가옵션 (선택지 누락/그룹명/추가금 — 영문 키 노출 방지)
|
||||
'additional_options.max' => __('sirsoft-ecommerce::validation.product.additional_options.max'),
|
||||
'additional_options.*.name.required_with' => __('sirsoft-ecommerce::validation.product.additional_options.name.required_with'),
|
||||
'additional_options.*.values.required_with' => __('sirsoft-ecommerce::validation.product.additional_options.values.required_with'),
|
||||
'additional_options.*.values.min' => __('sirsoft-ecommerce::validation.product.additional_options.values.min'),
|
||||
'additional_options.*.values.max' => __('sirsoft-ecommerce::validation.product.additional_options.values.max'),
|
||||
'additional_options.*.values.*.name.required' => __('sirsoft-ecommerce::validation.product.additional_options.values.name.required'),
|
||||
'additional_options.*.values.*.price_adjustment.min' => __('sirsoft-ecommerce::validation.product.additional_options.values.price_adjustment.min'),
|
||||
|
||||
// 라벨 할당
|
||||
'label_assignments.*.label_id.required' => __('sirsoft-ecommerce::validation.product.label_assignments.label_id.required'),
|
||||
'label_assignments.*.label_id.exists' => __('sirsoft-ecommerce::validation.product.label_assignments.label_id.exists'),
|
||||
@@ -219,9 +248,101 @@ class StoreProductRequest extends FormRequest
|
||||
}
|
||||
|
||||
/**
|
||||
* 데이터 전처리
|
||||
* 추가 cross-field 검증을 등록합니다.
|
||||
*
|
||||
* @return void
|
||||
* 단일 필드 rules 로 표현 불가한 검증을 after() 콜백으로 등록합니다.
|
||||
*
|
||||
* @param Validator $validator Laravel validator 인스턴스
|
||||
*/
|
||||
public function withValidator(Validator $validator): void
|
||||
{
|
||||
$validator->after(function (Validator $validator) {
|
||||
$this->validatePurchaseRestrictionRoles($validator);
|
||||
});
|
||||
}
|
||||
|
||||
/**
|
||||
* 구매 대상 제한(restricted) 선택 시 허용 역할이 최소 1개 있는지 검증합니다.
|
||||
*
|
||||
* restricted 인데 allowed_roles 가 비어 있으면 모순 데이터이므로 차단합니다.
|
||||
*
|
||||
* @param Validator $validator Laravel validator 인스턴스
|
||||
*/
|
||||
protected function validatePurchaseRestrictionRoles(Validator $validator): void
|
||||
{
|
||||
// 1차 규칙 위반(형식/존재) 시 중복 에러 회피
|
||||
if ($validator->errors()->hasAny(['purchase_restriction', 'allowed_roles'])) {
|
||||
return;
|
||||
}
|
||||
|
||||
if ($this->input('purchase_restriction') !== 'restricted') {
|
||||
return;
|
||||
}
|
||||
|
||||
$roles = $this->input('allowed_roles', []);
|
||||
$validRoleCount = is_array($roles)
|
||||
? count(array_filter($roles, fn ($r) => $r !== null && $r !== ''))
|
||||
: 0;
|
||||
|
||||
if ($validRoleCount === 0) {
|
||||
$validator->errors()->add(
|
||||
'allowed_roles',
|
||||
__('sirsoft-ecommerce::validation.product.allowed_roles.required_when_restricted')
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* 검증 속성명(에러 메시지용 한글 필드명)을 반환합니다.
|
||||
*
|
||||
* 미지정 시 Laravel 이 `options.0.selling_price` 같은 raw 경로를 노출하므로,
|
||||
* 사용자에게 의미 있는 한글 명칭으로 치환합니다. 인덱스 와일드카드(`*`)는
|
||||
* 각 인덱스에 동일 라벨이 적용됩니다.
|
||||
*
|
||||
* @return array<string, string>
|
||||
*/
|
||||
public function attributes(): array
|
||||
{
|
||||
return [
|
||||
'name' => __('sirsoft-ecommerce::validation.product.attributes.name'),
|
||||
'product_code' => __('sirsoft-ecommerce::validation.product.attributes.product_code'),
|
||||
'list_price' => __('sirsoft-ecommerce::validation.product.attributes.list_price'),
|
||||
'selling_price' => __('sirsoft-ecommerce::validation.product.attributes.selling_price'),
|
||||
'stock_quantity' => __('sirsoft-ecommerce::validation.product.attributes.stock_quantity'),
|
||||
'safe_stock_quantity' => __('sirsoft-ecommerce::validation.product.attributes.safe_stock_quantity'),
|
||||
'options.*.list_price' => __('sirsoft-ecommerce::validation.product.attributes.option_list_price'),
|
||||
'options.*.selling_price' => __('sirsoft-ecommerce::validation.product.attributes.option_selling_price'),
|
||||
'options.*.price_adjustment' => __('sirsoft-ecommerce::validation.product.attributes.option_price_adjustment'),
|
||||
'options.*.stock_quantity' => __('sirsoft-ecommerce::validation.product.attributes.option_stock_quantity'),
|
||||
'options.*.option_name' => __('sirsoft-ecommerce::validation.product.attributes.option_name'),
|
||||
'options.*.option_code' => __('sirsoft-ecommerce::validation.product.attributes.option_code'),
|
||||
];
|
||||
}
|
||||
|
||||
/**
|
||||
* 기본통화의 소수 자릿수를 반환합니다.
|
||||
*
|
||||
* 환경설정 language_currency 의 default_currency 에 매칭되는 통화의
|
||||
* decimal_places 값(예: KRW=0, USD=2)을 반환합니다.
|
||||
*
|
||||
* @return int 소수 자릿수 (미설정 시 0)
|
||||
*/
|
||||
protected function baseCurrencyDecimalPlaces(): int
|
||||
{
|
||||
$settings = g7_module_settings('sirsoft-ecommerce', 'language_currency');
|
||||
$default = $settings['default_currency'] ?? 'KRW';
|
||||
|
||||
foreach ($settings['currencies'] ?? [] as $currency) {
|
||||
if (($currency['code'] ?? null) === $default) {
|
||||
return (int) ($currency['decimal_places'] ?? 0);
|
||||
}
|
||||
}
|
||||
|
||||
return 0;
|
||||
}
|
||||
|
||||
/**
|
||||
* 데이터 전처리
|
||||
*/
|
||||
protected function prepareForValidation(): void
|
||||
{
|
||||
|
||||
+109
-13
@@ -6,7 +6,12 @@ use App\Extension\HookManager;
|
||||
use App\Rules\LocaleRequiredTranslatable;
|
||||
use Illuminate\Foundation\Http\FormRequest;
|
||||
use Illuminate\Validation\Rule;
|
||||
use Illuminate\Validation\Validator;
|
||||
use Modules\Sirsoft\Ecommerce\Enums\ChargePolicyEnum;
|
||||
use Modules\Sirsoft\Ecommerce\Enums\ShippingApiAuthType;
|
||||
use Modules\Sirsoft\Ecommerce\Enums\ShippingApiHttpMethod;
|
||||
use Modules\Sirsoft\Ecommerce\Enums\ShippingApiRequestField;
|
||||
use Modules\Sirsoft\Ecommerce\Enums\ShippingApiResponseType;
|
||||
use Modules\Sirsoft\Ecommerce\Models\ShippingType;
|
||||
|
||||
/**
|
||||
@@ -44,7 +49,8 @@ class StoreShippingPolicyRequest extends FormRequest
|
||||
'country_settings.*.shipping_method' => ['required', 'string', Rule::in(ShippingType::pluck('code')->toArray())],
|
||||
'country_settings.*.custom_shipping_name' => ['nullable', 'array'],
|
||||
'country_settings.*.custom_shipping_name.*' => ['nullable', 'string', 'max:100'],
|
||||
'country_settings.*.currency_code' => ['required', 'string', 'max:10'],
|
||||
// 통화는 서버가 상점 기본 통화로 강제하므로 클라이언트 입력에 의존하지 않는다 (읽기전용 표시).
|
||||
'country_settings.*.currency_code' => ['nullable', 'string', 'max:10'],
|
||||
'country_settings.*.charge_policy' => ['required', Rule::enum(ChargePolicyEnum::class)],
|
||||
|
||||
// 배송비 관련
|
||||
@@ -63,9 +69,24 @@ class StoreShippingPolicyRequest extends FormRequest
|
||||
// API 설정
|
||||
'country_settings.*.api_endpoint' => ['nullable', 'url', 'max:500'],
|
||||
'country_settings.*.api_request_fields' => ['nullable', 'array'],
|
||||
'country_settings.*.api_request_fields.*' => ['string', 'max:100'],
|
||||
// 후보 5종 SSoT(ShippingApiRequestField) 외 필드명 거부 — silent drop 차단
|
||||
'country_settings.*.api_request_fields.*' => ['string', 'max:100', Rule::in(ShippingApiRequestField::values())],
|
||||
'country_settings.*.api_response_fee_field' => ['nullable', 'string', 'max:100'],
|
||||
|
||||
// 계산 API 고급 설정 (api_config) — 메서드/인증/매핑/응답형식
|
||||
'country_settings.*.api_config' => ['nullable', 'array'],
|
||||
'country_settings.*.api_config.http_method' => ['nullable', 'string', Rule::in(ShippingApiHttpMethod::values())],
|
||||
'country_settings.*.api_config.auth_type' => ['nullable', 'string', Rule::in(ShippingApiAuthType::values())],
|
||||
'country_settings.*.api_config.auth_token' => ['nullable', 'string', 'max:1000'],
|
||||
// 헤더명: HTTP 토큰 문자만 허용 (CRLF/콜론/공백 차단 — 헤더 인젝션 방지)
|
||||
'country_settings.*.api_config.auth_header_name' => ['nullable', 'string', 'max:100', 'regex:/^[A-Za-z0-9!#$%&\'*+.^_`|~-]+$/'],
|
||||
'country_settings.*.api_config.response_type' => ['nullable', 'string', Rule::in(ShippingApiResponseType::values())],
|
||||
'country_settings.*.api_config.response_path' => ['nullable', 'string', 'max:200'],
|
||||
'country_settings.*.api_config.skip_ssl_verify' => ['nullable', 'boolean'],
|
||||
'country_settings.*.api_config.field_map' => ['nullable', 'array'],
|
||||
// 외부 키 이름: 영숫자/언더스코어/하이픈/점만 (헤더·쿼리 인젝션 방지)
|
||||
'country_settings.*.api_config.field_map.*' => ['nullable', 'string', 'max:100', 'regex:/^[A-Za-z0-9_.\-]+$/'],
|
||||
|
||||
// 도서산간 추가배송비
|
||||
'country_settings.*.extra_fee_enabled' => ['required', 'boolean'],
|
||||
'country_settings.*.extra_fee_settings' => ['nullable', 'array'],
|
||||
@@ -97,7 +118,6 @@ class StoreShippingPolicyRequest extends FormRequest
|
||||
'country_settings.*.country_code.distinct' => __('sirsoft-ecommerce::validation.shipping_policy.country_settings.country_code.distinct'),
|
||||
'country_settings.*.shipping_method.required' => __('sirsoft-ecommerce::validation.shipping_policy.country_settings.shipping_method.required'),
|
||||
'country_settings.*.shipping_method.Illuminate\Validation\Rules\Enum' => __('sirsoft-ecommerce::validation.shipping_policy.country_settings.shipping_method.in'),
|
||||
'country_settings.*.currency_code.required' => __('sirsoft-ecommerce::validation.shipping_policy.country_settings.currency_code.required'),
|
||||
'country_settings.*.charge_policy.required' => __('sirsoft-ecommerce::validation.shipping_policy.country_settings.charge_policy.required'),
|
||||
'country_settings.*.charge_policy.Illuminate\Validation\Rules\Enum' => __('sirsoft-ecommerce::validation.shipping_policy.country_settings.charge_policy.in'),
|
||||
'country_settings.*.base_fee.numeric' => __('sirsoft-ecommerce::validation.shipping_policy.country_settings.base_fee.numeric'),
|
||||
@@ -105,8 +125,21 @@ class StoreShippingPolicyRequest extends FormRequest
|
||||
'country_settings.*.free_threshold.numeric' => __('sirsoft-ecommerce::validation.shipping_policy.country_settings.free_threshold.numeric'),
|
||||
'country_settings.*.free_threshold.min' => __('sirsoft-ecommerce::validation.shipping_policy.country_settings.free_threshold.min'),
|
||||
'country_settings.*.api_endpoint.url' => __('sirsoft-ecommerce::validation.shipping_policy.country_settings.api_endpoint.url'),
|
||||
'country_settings.*.api_request_fields.*.in' => __('sirsoft-ecommerce::validation.shipping_policy.country_settings.api_request_fields.in'),
|
||||
'country_settings.*.api_config.http_method.in' => __('sirsoft-ecommerce::validation.shipping_policy.country_settings.api_config.http_method_in'),
|
||||
'country_settings.*.api_config.auth_type.in' => __('sirsoft-ecommerce::validation.shipping_policy.country_settings.api_config.auth_type_in'),
|
||||
'country_settings.*.api_config.auth_header_name.regex' => __('sirsoft-ecommerce::validation.shipping_policy.country_settings.api_config.auth_header_name_format'),
|
||||
'country_settings.*.api_config.response_type.in' => __('sirsoft-ecommerce::validation.shipping_policy.country_settings.api_config.response_type_in'),
|
||||
'country_settings.*.api_config.field_map.*.regex' => __('sirsoft-ecommerce::validation.shipping_policy.country_settings.api_config.field_map_format'),
|
||||
'country_settings.*.extra_fee_enabled.required' => __('sirsoft-ecommerce::validation.shipping_policy.country_settings.extra_fee_enabled.required'),
|
||||
'country_settings.*.is_active.required' => __('sirsoft-ecommerce::validation.shipping_policy.country_settings.is_active.required'),
|
||||
// 구간별 배송비 음수/필수 직결 메시지 (raw key 노출 차단)
|
||||
'country_settings.*.ranges.tiers.*.fee.required' => __('sirsoft-ecommerce::validation.shipping_policy.ranges.fee_required'),
|
||||
'country_settings.*.ranges.tiers.*.fee.min' => __('sirsoft-ecommerce::validation.shipping_policy.ranges.fee_non_negative'),
|
||||
'country_settings.*.ranges.tiers.*.min.min' => __('sirsoft-ecommerce::validation.shipping_policy.ranges.tier_min_non_negative'),
|
||||
'country_settings.*.ranges.tiers.*.max.min' => __('sirsoft-ecommerce::validation.shipping_policy.ranges.tier_max_non_negative'),
|
||||
'country_settings.*.ranges.unit_value.min' => __('sirsoft-ecommerce::validation.shipping_policy.ranges.unit_value_min'),
|
||||
'country_settings.*.extra_fee_settings.*.fee.min' => __('sirsoft-ecommerce::validation.extra_fee_template.fee_min'),
|
||||
'is_active.required' => __('sirsoft-ecommerce::validation.shipping_policy.is_active.required'),
|
||||
];
|
||||
}
|
||||
@@ -118,17 +151,82 @@ class StoreShippingPolicyRequest extends FormRequest
|
||||
* - 비무료 정책의 base_fee 0 원 금지
|
||||
* - shipping_method=custom 일 때 custom_shipping_name 다국어 필수
|
||||
*
|
||||
* @param \Illuminate\Validation\Validator $validator Laravel validator 인스턴스
|
||||
* @param Validator $validator Laravel validator 인스턴스
|
||||
*/
|
||||
public function withValidator(\Illuminate\Validation\Validator $validator): void
|
||||
public function withValidator(Validator $validator): void
|
||||
{
|
||||
$validator->after(function (\Illuminate\Validation\Validator $validator) {
|
||||
$validator->after(function (Validator $validator) {
|
||||
$this->validateRangeTiersContinuity($validator);
|
||||
$this->validateNonFreeBaseFee($validator);
|
||||
$this->validateCustomShippingName($validator);
|
||||
$this->validateApiEndpointRequired($validator);
|
||||
$this->validateApiConfig($validator);
|
||||
});
|
||||
}
|
||||
|
||||
/**
|
||||
* 계산 API 정책(api) 선택 시 api_endpoint 필수 검증 (cross-field).
|
||||
*
|
||||
* 비-API 정책은 base rule 의 nullable 을 유지하여 회귀를 막고, API 정책에 한해 빈
|
||||
* endpoint 저장을 차단하여 silent base_fee 폴백을 방지합니다.
|
||||
*
|
||||
* @param Validator $validator Laravel validator 인스턴스
|
||||
*/
|
||||
private function validateApiEndpointRequired(Validator $validator): void
|
||||
{
|
||||
$countrySettings = $this->input('country_settings', []);
|
||||
|
||||
if (! is_array($countrySettings)) {
|
||||
return;
|
||||
}
|
||||
|
||||
foreach ($countrySettings as $i => $cs) {
|
||||
$policy = ChargePolicyEnum::tryFrom($cs['charge_policy'] ?? '');
|
||||
|
||||
if ($policy && $policy->requiresApiEndpoint() && trim((string) ($cs['api_endpoint'] ?? '')) === '') {
|
||||
$validator->errors()->add(
|
||||
"country_settings.{$i}.api_endpoint",
|
||||
__('sirsoft-ecommerce::validation.shipping_policy.country_settings.api_endpoint.required')
|
||||
);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* 계산 API 고급 설정(api_config)의 cross-field 검증.
|
||||
*
|
||||
* - custom_header 인증 시 헤더명 필수
|
||||
*
|
||||
* @param Validator $validator Laravel validator 인스턴스
|
||||
*/
|
||||
private function validateApiConfig(Validator $validator): void
|
||||
{
|
||||
$countrySettings = $this->input('country_settings', []);
|
||||
|
||||
if (! is_array($countrySettings)) {
|
||||
return;
|
||||
}
|
||||
|
||||
foreach ($countrySettings as $i => $cs) {
|
||||
$policy = ChargePolicyEnum::tryFrom($cs['charge_policy'] ?? '');
|
||||
|
||||
if (! $policy || ! $policy->requiresApiEndpoint()) {
|
||||
continue;
|
||||
}
|
||||
|
||||
$config = $cs['api_config'] ?? [];
|
||||
|
||||
// custom_header 인증 시 헤더명 필수
|
||||
if (($config['auth_type'] ?? null) === ShippingApiAuthType::CUSTOM_HEADER->value
|
||||
&& trim((string) ($config['auth_header_name'] ?? '')) === '') {
|
||||
$validator->errors()->add(
|
||||
"country_settings.{$i}.api_config.auth_header_name",
|
||||
__('sirsoft-ecommerce::validation.shipping_policy.country_settings.api_config.auth_header_name_required')
|
||||
);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* 구간별 배송비 tiers의 연속성을 검증합니다.
|
||||
*
|
||||
@@ -138,7 +236,7 @@ class StoreShippingPolicyRequest extends FormRequest
|
||||
* - 구간이 연속적이어야 합니다 (현재 max + 1 === 다음 min, 포함 범위 기준).
|
||||
* - 배송비는 0 이상이어야 합니다.
|
||||
*/
|
||||
private function validateRangeTiersContinuity(\Illuminate\Validation\Validator $validator): void
|
||||
private function validateRangeTiersContinuity(Validator $validator): void
|
||||
{
|
||||
$countrySettings = $this->input('country_settings', []);
|
||||
|
||||
@@ -210,11 +308,8 @@ class StoreShippingPolicyRequest extends FormRequest
|
||||
* 무료배송이 아닌 정책에서 배송비 0원을 금지합니다.
|
||||
*
|
||||
* 구간별 배송비(RANGE_*) 정책은 tiers에서 배송비를 관리하므로 예외입니다.
|
||||
*
|
||||
* @param \Illuminate\Validation\Validator $validator
|
||||
* @return void
|
||||
*/
|
||||
private function validateNonFreeBaseFee(\Illuminate\Validation\Validator $validator): void
|
||||
private function validateNonFreeBaseFee(Validator $validator): void
|
||||
{
|
||||
$countrySettings = $this->input('country_settings', []);
|
||||
|
||||
@@ -242,9 +337,9 @@ class StoreShippingPolicyRequest extends FormRequest
|
||||
/**
|
||||
* custom 배송방법 선택 시 custom_shipping_name 필수 검증
|
||||
*
|
||||
* @param \Illuminate\Validation\Validator $validator Validator 인스턴스
|
||||
* @param Validator $validator Validator 인스턴스
|
||||
*/
|
||||
private function validateCustomShippingName(\Illuminate\Validation\Validator $validator): void
|
||||
private function validateCustomShippingName(Validator $validator): void
|
||||
{
|
||||
$countrySettings = $this->input('country_settings', []);
|
||||
|
||||
@@ -309,6 +404,7 @@ class StoreShippingPolicyRequest extends FormRequest
|
||||
$countrySettings[$i]['api_endpoint'] = null;
|
||||
$countrySettings[$i]['api_request_fields'] = null;
|
||||
$countrySettings[$i]['api_response_fee_field'] = null;
|
||||
$countrySettings[$i]['api_config'] = null;
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
@@ -0,0 +1,58 @@
|
||||
<?php
|
||||
|
||||
namespace Modules\Sirsoft\Ecommerce\Http\Requests\Admin;
|
||||
|
||||
use Illuminate\Foundation\Http\FormRequest;
|
||||
use Illuminate\Validation\Rule;
|
||||
use Modules\Sirsoft\Ecommerce\Enums\ShippingApiAuthType;
|
||||
use Modules\Sirsoft\Ecommerce\Enums\ShippingApiHttpMethod;
|
||||
use Modules\Sirsoft\Ecommerce\Enums\ShippingApiRequestField;
|
||||
use Modules\Sirsoft\Ecommerce\Enums\ShippingApiResponseType;
|
||||
|
||||
/**
|
||||
* 배송정책 계산 API 테스트 호출 요청
|
||||
*
|
||||
* 관리자가 폼에서 입력 중인 단일 API 구성으로 외부 API 를 1회 실호출하기 위한 입력 검증.
|
||||
*/
|
||||
class TestShippingApiRequest extends FormRequest
|
||||
{
|
||||
/**
|
||||
* 권한 검사는 라우트의 permission 미들웨어가 담당하므로 통과시킵니다.
|
||||
*
|
||||
* @return bool 항상 true
|
||||
*/
|
||||
public function authorize(): bool
|
||||
{
|
||||
return true;
|
||||
}
|
||||
|
||||
/**
|
||||
* 테스트 호출 입력 검증 규칙을 반환합니다.
|
||||
*
|
||||
* @return array<string, mixed>
|
||||
*/
|
||||
public function rules(): array
|
||||
{
|
||||
return [
|
||||
'endpoint' => ['required', 'url', 'max:500'],
|
||||
'request_fields' => ['nullable', 'array'],
|
||||
'request_fields.*' => ['string', Rule::in(ShippingApiRequestField::values())],
|
||||
|
||||
'config' => ['nullable', 'array'],
|
||||
'config.http_method' => ['nullable', 'string', Rule::in(ShippingApiHttpMethod::values())],
|
||||
'config.auth_type' => ['nullable', 'string', Rule::in(ShippingApiAuthType::values())],
|
||||
'config.auth_token' => ['nullable', 'string', 'max:1000'],
|
||||
'config.auth_header_name' => ['nullable', 'string', 'max:100', 'regex:/^[A-Za-z0-9!#$%&\'*+.^_`|~-]+$/'],
|
||||
'config.response_type' => ['nullable', 'string', Rule::in(ShippingApiResponseType::values())],
|
||||
'config.response_path' => ['nullable', 'string', 'max:200'],
|
||||
'config.field_map' => ['nullable', 'array'],
|
||||
'config.field_map.*' => ['nullable', 'string', 'max:100', 'regex:/^[A-Za-z0-9_.\-]+$/'],
|
||||
|
||||
// 테스트용 샘플 값 (관리자 입력, 더미 자동 채움 보조)
|
||||
'sample' => ['nullable', 'array'],
|
||||
'sample.group_total' => ['nullable', 'numeric', 'min:0'],
|
||||
'sample.total_quantity' => ['nullable', 'integer', 'min:0'],
|
||||
'sample.country_code' => ['nullable', 'string', 'max:10'],
|
||||
];
|
||||
}
|
||||
}
|
||||
+69
@@ -0,0 +1,69 @@
|
||||
<?php
|
||||
|
||||
namespace Modules\Sirsoft\Ecommerce\Http\Requests\Admin;
|
||||
|
||||
use Illuminate\Foundation\Http\FormRequest;
|
||||
use Illuminate\Validation\Rule;
|
||||
use Modules\Sirsoft\Ecommerce\Services\EcommerceSettingsService;
|
||||
|
||||
/**
|
||||
* 관리자 회원 결제 통화 변경 요청 검증 (A3)
|
||||
*
|
||||
* 권한은 라우트의 permission:admin,sirsoft-ecommerce.user-currency.manage 미들웨어가 담당한다.
|
||||
* 등록 통화(is_default || exchange_rate>0)만 허용한다.
|
||||
*/
|
||||
class UpdateAdminUserCurrencyRequest extends FormRequest
|
||||
{
|
||||
/**
|
||||
* 권한 체크는 permission 미들웨어에서 수행됩니다.
|
||||
*
|
||||
* @return bool 항상 true
|
||||
*/
|
||||
public function authorize(): bool
|
||||
{
|
||||
return true;
|
||||
}
|
||||
|
||||
/**
|
||||
* 검증 규칙
|
||||
*
|
||||
* @return array<string, mixed>
|
||||
*/
|
||||
public function rules(): array
|
||||
{
|
||||
return [
|
||||
'currency' => ['required', 'string', Rule::in($this->allowedCurrencyCodes())],
|
||||
];
|
||||
}
|
||||
|
||||
/**
|
||||
* 허용 통화 코드 목록 (is_default || exchange_rate>0).
|
||||
*
|
||||
* @return array<int, string>
|
||||
*/
|
||||
private function allowedCurrencyCodes(): array
|
||||
{
|
||||
$currencies = app(EcommerceSettingsService::class)
|
||||
->getSetting('language_currency.currencies', []);
|
||||
|
||||
return collect($currencies)
|
||||
->filter(fn ($c) => ($c['is_default'] ?? false) || (float) ($c['exchange_rate'] ?? 0) > 0)
|
||||
->pluck('code')
|
||||
->filter()
|
||||
->values()
|
||||
->all();
|
||||
}
|
||||
|
||||
/**
|
||||
* 검증 메시지
|
||||
*
|
||||
* @return array<string, string>
|
||||
*/
|
||||
public function messages(): array
|
||||
{
|
||||
return [
|
||||
'currency.required' => __('sirsoft-ecommerce::validation.custom.user_currency.required'),
|
||||
'currency.in' => __('sirsoft-ecommerce::validation.custom.user_currency.invalid'),
|
||||
];
|
||||
}
|
||||
}
|
||||
+67
@@ -0,0 +1,67 @@
|
||||
<?php
|
||||
|
||||
namespace Modules\Sirsoft\Ecommerce\Http\Requests\Admin;
|
||||
|
||||
use Illuminate\Foundation\Http\FormRequest;
|
||||
use Illuminate\Validation\Rule;
|
||||
use Modules\Sirsoft\Ecommerce\Services\ShippingCountryResolver;
|
||||
|
||||
/**
|
||||
* 관리자 회원 배송국가 변경 요청 검증 (MP08 후속)
|
||||
*
|
||||
* 권한은 라우트의 permission:admin,sirsoft-ecommerce.user-shipping-country.manage 미들웨어가
|
||||
* 담당한다. 활성 배송가능 국가(available_countries[].is_active) 만 허용한다.
|
||||
*/
|
||||
class UpdateAdminUserShippingCountryRequest extends FormRequest
|
||||
{
|
||||
/**
|
||||
* 권한 체크는 permission 미들웨어에서 수행됩니다.
|
||||
*
|
||||
* @return bool 항상 true
|
||||
*/
|
||||
public function authorize(): bool
|
||||
{
|
||||
return true;
|
||||
}
|
||||
|
||||
/**
|
||||
* 검증 규칙
|
||||
*
|
||||
* @return array<string, mixed>
|
||||
*/
|
||||
public function rules(): array
|
||||
{
|
||||
return [
|
||||
'shipping_country' => [
|
||||
'required',
|
||||
'string',
|
||||
'size:2',
|
||||
Rule::in(app(ShippingCountryResolver::class)->allowedShippingCountryCodes()),
|
||||
],
|
||||
];
|
||||
}
|
||||
|
||||
/**
|
||||
* 검증 전 국가 코드를 대문자로 정규화합니다.
|
||||
*/
|
||||
protected function prepareForValidation(): void
|
||||
{
|
||||
if ($this->filled('shipping_country')) {
|
||||
$this->merge(['shipping_country' => strtoupper((string) $this->input('shipping_country'))]);
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* 검증 메시지
|
||||
*
|
||||
* @return array<string, string>
|
||||
*/
|
||||
public function messages(): array
|
||||
{
|
||||
return [
|
||||
'shipping_country.required' => __('sirsoft-ecommerce::validation.custom.user_shipping_country.required'),
|
||||
'shipping_country.in' => __('sirsoft-ecommerce::validation.custom.user_shipping_country.invalid'),
|
||||
'shipping_country.size' => __('sirsoft-ecommerce::validation.custom.user_shipping_country.invalid'),
|
||||
];
|
||||
}
|
||||
}
|
||||
@@ -8,12 +8,14 @@ use App\Rules\LocaleRequiredTranslatable;
|
||||
use App\Rules\TranslatableField;
|
||||
use Illuminate\Foundation\Http\FormRequest;
|
||||
use Illuminate\Validation\Rule;
|
||||
use Illuminate\Validation\Validator;
|
||||
use Modules\Sirsoft\Ecommerce\Enums\CouponDiscountType;
|
||||
use Modules\Sirsoft\Ecommerce\Enums\CouponIssueCondition;
|
||||
use Modules\Sirsoft\Ecommerce\Enums\CouponIssueMethod;
|
||||
use Modules\Sirsoft\Ecommerce\Enums\CouponIssueStatus;
|
||||
use Modules\Sirsoft\Ecommerce\Enums\CouponTargetScope;
|
||||
use Modules\Sirsoft\Ecommerce\Enums\CouponTargetType;
|
||||
use Modules\Sirsoft\Ecommerce\Http\Requests\Admin\Concerns\ValidatesCouponTargetScope;
|
||||
use Modules\Sirsoft\Ecommerce\Models\Category;
|
||||
use Modules\Sirsoft\Ecommerce\Models\Product;
|
||||
|
||||
@@ -22,18 +24,60 @@ use Modules\Sirsoft\Ecommerce\Models\Product;
|
||||
*/
|
||||
class UpdateCouponRequest extends FormRequest
|
||||
{
|
||||
use ValidatesCouponTargetScope;
|
||||
|
||||
/**
|
||||
* 사용자가 이 요청을 수행할 권한이 있는지 확인
|
||||
*
|
||||
* @return bool 권한 미들웨어가 처리하므로 항상 true
|
||||
*/
|
||||
public function authorize(): bool
|
||||
{
|
||||
return true;
|
||||
}
|
||||
|
||||
/**
|
||||
* 추가 검증을 등록합니다. (적용대상 미선택 차단 — A16①/A17①)
|
||||
*
|
||||
* @param Validator $validator 검증기 인스턴스
|
||||
*/
|
||||
public function withValidator(Validator $validator): void
|
||||
{
|
||||
$this->validateTargetScopeSelection($validator);
|
||||
}
|
||||
|
||||
/**
|
||||
* 검증 전 입력값을 정규화합니다.
|
||||
*
|
||||
* nullable 숫자 필드(discount_max_amount/total_quantity)와 NOT NULL default 0 인
|
||||
* min_order_amount 의 빈 문자열 입력을 각각 null / 0 으로 변환해
|
||||
* decimal/integer cast 오류(빈 문자열 → 저장 500)를 차단합니다.
|
||||
*/
|
||||
protected function prepareForValidation(): void
|
||||
{
|
||||
$merge = [];
|
||||
|
||||
// nullable 숫자 → 빈 문자열이면 null
|
||||
foreach (['discount_max_amount', 'total_quantity'] as $field) {
|
||||
if ($this->input($field) === '') {
|
||||
$merge[$field] = null;
|
||||
}
|
||||
}
|
||||
|
||||
// min_order_amount 는 NOT NULL default 0 → 명시적으로 빈 문자열/ null 전송 시 0
|
||||
if (in_array($this->input('min_order_amount'), ['', null], true) && $this->has('min_order_amount')) {
|
||||
$merge['min_order_amount'] = 0;
|
||||
}
|
||||
|
||||
if ($merge) {
|
||||
$this->merge($merge);
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* 요청에 적용할 검증 규칙
|
||||
*
|
||||
* @return array
|
||||
* @return array 검증 규칙 배열
|
||||
*/
|
||||
public function rules(): array
|
||||
{
|
||||
@@ -86,8 +130,6 @@ class UpdateCouponRequest extends FormRequest
|
||||
|
||||
/**
|
||||
* 할인값 검증 규칙을 반환합니다.
|
||||
*
|
||||
* @return array
|
||||
*/
|
||||
protected function discountValueRules(): array
|
||||
{
|
||||
@@ -95,7 +137,8 @@ class UpdateCouponRequest extends FormRequest
|
||||
return ['sometimes', 'required', 'numeric', 'min:1', 'max:100'];
|
||||
}
|
||||
|
||||
return ['sometimes', 'required', 'numeric', 'min:0'];
|
||||
// 정액(fixed): 1원 이상 (0/음수 차단 — A14)
|
||||
return ['sometimes', 'required', 'numeric', 'min:1'];
|
||||
}
|
||||
|
||||
/**
|
||||
@@ -103,7 +146,7 @@ class UpdateCouponRequest extends FormRequest
|
||||
*
|
||||
* @param string|null $key 특정 키만 반환
|
||||
* @param mixed $default 기본값
|
||||
* @return mixed
|
||||
* @return mixed 타임존 변환된 검증 데이터
|
||||
*/
|
||||
public function validated($key = null, $default = null): mixed
|
||||
{
|
||||
@@ -139,13 +182,18 @@ class UpdateCouponRequest extends FormRequest
|
||||
/**
|
||||
* 검증 오류 메시지 커스터마이징
|
||||
*
|
||||
* @return array
|
||||
* @return array 필드별 오류 메시지 배열
|
||||
*/
|
||||
public function messages(): array
|
||||
{
|
||||
// 정액/정률에 따라 discount_value.min 메시지를 분기 (A14)
|
||||
$isRate = $this->input('discount_type') === CouponDiscountType::RATE->value;
|
||||
|
||||
return [
|
||||
'name.required' => __('sirsoft-ecommerce::validation.coupon.name_required'),
|
||||
'discount_value.min' => __('sirsoft-ecommerce::validation.coupon.discount_value_rate_min'),
|
||||
'discount_value.min' => $isRate
|
||||
? __('sirsoft-ecommerce::validation.coupon.discount_value_rate_min')
|
||||
: __('sirsoft-ecommerce::validation.coupon.discount_value_fixed_min'),
|
||||
'discount_value.max' => __('sirsoft-ecommerce::validation.coupon.discount_value_rate_max'),
|
||||
'valid_to.after_or_equal' => __('sirsoft-ecommerce::validation.coupon.valid_to_after_from'),
|
||||
];
|
||||
|
||||
+51
@@ -0,0 +1,51 @@
|
||||
<?php
|
||||
|
||||
namespace Modules\Sirsoft\Ecommerce\Http\Requests\Admin;
|
||||
|
||||
use Illuminate\Foundation\Http\FormRequest;
|
||||
|
||||
/**
|
||||
* 관리자 마일리지 적립건 편집 요청 (사유 변경 + 만료일 직접 지정)
|
||||
*
|
||||
* 마일리지 원장은 불변이므로 적립계 거래의 부가 필드(memo / expires_at)만 보정한다.
|
||||
* 적립계 여부·소멸/사용 상태에 따른 편집 가능성은 Service 가 도메인 규칙으로 판정한다.
|
||||
*/
|
||||
class UpdateMileageTransactionRequest extends FormRequest
|
||||
{
|
||||
/**
|
||||
* 권한 체크는 라우트의 permission 미들웨어에서 수행됩니다.
|
||||
*
|
||||
* @return bool 항상 true
|
||||
*/
|
||||
public function authorize(): bool
|
||||
{
|
||||
return true;
|
||||
}
|
||||
|
||||
/**
|
||||
* 검증 규칙
|
||||
*
|
||||
* memo / expires_at 둘 다 nullable — 전달된 키만 갱신한다 (memo 비우기 / 만료일 무기한 허용).
|
||||
*
|
||||
* @return array<string, array<int, mixed>> 검증 규칙
|
||||
*/
|
||||
public function rules(): array
|
||||
{
|
||||
return [
|
||||
'memo' => ['nullable', 'string', 'max:1000'],
|
||||
'expires_at' => ['nullable', 'date'],
|
||||
];
|
||||
}
|
||||
|
||||
/**
|
||||
* 다국어 검증 메시지
|
||||
*
|
||||
* @return array<string, string> 메시지
|
||||
*/
|
||||
public function messages(): array
|
||||
{
|
||||
return [
|
||||
'expires_at.date' => __('sirsoft-ecommerce::validation.mileage.expires_at_invalid'),
|
||||
];
|
||||
}
|
||||
}
|
||||
@@ -4,6 +4,7 @@ namespace Modules\Sirsoft\Ecommerce\Http\Requests\Admin;
|
||||
|
||||
use Illuminate\Foundation\Http\FormRequest;
|
||||
use Illuminate\Validation\Rule;
|
||||
use Illuminate\Validation\Validator;
|
||||
use Modules\Sirsoft\Ecommerce\Enums\OrderStatusEnum;
|
||||
|
||||
/**
|
||||
@@ -14,7 +15,7 @@ class UpdateOrderRequest extends FormRequest
|
||||
/**
|
||||
* 권한 확인
|
||||
*
|
||||
* @return bool
|
||||
* @return bool 권한 미들웨어에 위임하므로 항상 true
|
||||
*/
|
||||
public function authorize(): bool
|
||||
{
|
||||
@@ -24,7 +25,7 @@ class UpdateOrderRequest extends FormRequest
|
||||
/**
|
||||
* 유효성 검사 규칙
|
||||
*
|
||||
* @return array
|
||||
* @return array<string, mixed> 필드별 검증 규칙 배열
|
||||
*/
|
||||
public function rules(): array
|
||||
{
|
||||
@@ -34,18 +35,61 @@ class UpdateOrderRequest extends FormRequest
|
||||
'recipient_name' => ['required', 'string', 'max:50'],
|
||||
'recipient_phone' => ['required_without:recipient_tel', 'nullable', 'string', 'max:20'],
|
||||
'recipient_tel' => ['required_without:recipient_phone', 'nullable', 'string', 'max:20'],
|
||||
'recipient_zipcode' => ['required', 'string', 'max:10'],
|
||||
'recipient_address' => ['required', 'string', 'max:255'],
|
||||
'recipient_detail_address' => ['required', 'string', 'max:255'],
|
||||
// 국내(KR) 주소 — 해외 주소(address_line_1)가 없을 때만 필수 (D7 해외 주문 지원)
|
||||
'recipient_zipcode' => ['required_without:address_line_1', 'nullable', 'string', 'max:10'],
|
||||
'recipient_address' => ['required_without:address_line_1', 'nullable', 'string', 'max:255'],
|
||||
'recipient_detail_address' => ['required_with:recipient_address', 'nullable', 'string', 'max:255'],
|
||||
// 해외 주소 — 국내 주소(recipient_address)가 없을 때만 필수 (D7)
|
||||
'address_line_1' => ['required_without:recipient_address', 'nullable', 'string', 'max:255'],
|
||||
'address_line_2' => ['nullable', 'string', 'max:255'],
|
||||
'intl_city' => ['required_with:address_line_1', 'nullable', 'string', 'max:100'],
|
||||
'intl_state' => ['nullable', 'string', 'max:100'],
|
||||
'intl_postal_code' => ['required_with:address_line_1', 'nullable', 'string', 'max:20'],
|
||||
'delivery_memo' => ['nullable', 'string', 'max:500'],
|
||||
'recipient_country_code' => ['nullable', 'string', 'size:2'],
|
||||
];
|
||||
}
|
||||
|
||||
/**
|
||||
* 추가 검증 로직 — 주문 상태 전이 규칙(역방향/비연속 역행 차단)
|
||||
*
|
||||
* order_status 입력이 있고 현재 상태와 다를 때만, OrderStatusEnum 전이 게이트로 평가한다.
|
||||
* 위반 시 422 + 다국어 메시지. 취소(CANCELLED) 진입은 게이트가 통과 처리(OrderCancellationService 전담).
|
||||
*
|
||||
* @param Validator $validator
|
||||
*/
|
||||
public function withValidator($validator): void
|
||||
{
|
||||
$validator->after(function ($validator) {
|
||||
$input = $this->input('order_status');
|
||||
if ($input === null) {
|
||||
return; // 상태 미변경 요청
|
||||
}
|
||||
|
||||
$order = $this->route('order');
|
||||
$current = $order?->order_status; // Enum (cast)
|
||||
if (! $current instanceof OrderStatusEnum) {
|
||||
return; // 비정상 — rules 의 in 검증에 위임
|
||||
}
|
||||
|
||||
$target = OrderStatusEnum::tryFrom($input);
|
||||
if ($target === null) {
|
||||
return; // 잘못된 값 — rules 의 Rule::in 이 처리
|
||||
}
|
||||
|
||||
if (! $current->canTransitionTo($target)) {
|
||||
$validator->errors()->add('order_status', __('sirsoft-ecommerce::validation.orders.status_transition.invalid', [
|
||||
'from' => $current->label(),
|
||||
'to' => $target->label(),
|
||||
]));
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
/**
|
||||
* 검증 에러 메시지 정의
|
||||
*
|
||||
* @return array
|
||||
* @return array<string, string> 규칙별 다국어 에러 메시지 배열
|
||||
*/
|
||||
public function messages(): array
|
||||
{
|
||||
@@ -58,12 +102,15 @@ class UpdateOrderRequest extends FormRequest
|
||||
'recipient_phone.max' => __('sirsoft-ecommerce::validation.orders.recipient_phone.max'),
|
||||
'recipient_tel.required_without' => __('sirsoft-ecommerce::validation.orders.recipient_tel.required_without'),
|
||||
'recipient_tel.max' => __('sirsoft-ecommerce::validation.orders.recipient_tel.max'),
|
||||
'recipient_zipcode.required' => __('sirsoft-ecommerce::validation.orders.recipient_zipcode.required'),
|
||||
'recipient_zipcode.required_without' => __('sirsoft-ecommerce::validation.orders.recipient_zipcode.required'),
|
||||
'recipient_zipcode.max' => __('sirsoft-ecommerce::validation.orders.recipient_zipcode.max'),
|
||||
'recipient_address.required' => __('sirsoft-ecommerce::validation.orders.recipient_address.required'),
|
||||
'recipient_address.required_without' => __('sirsoft-ecommerce::validation.orders.recipient_address.required'),
|
||||
'recipient_address.max' => __('sirsoft-ecommerce::validation.orders.recipient_address.max'),
|
||||
'recipient_detail_address.required' => __('sirsoft-ecommerce::validation.orders.recipient_detail_address.required'),
|
||||
'recipient_detail_address.required_with' => __('sirsoft-ecommerce::validation.orders.recipient_detail_address.required'),
|
||||
'recipient_detail_address.max' => __('sirsoft-ecommerce::validation.orders.recipient_detail_address.max'),
|
||||
'address_line_1.required_without' => __('sirsoft-ecommerce::validation.order.address_line_1_required'),
|
||||
'intl_city.required_with' => __('sirsoft-ecommerce::validation.order.intl_city_required'),
|
||||
'intl_postal_code.required_with' => __('sirsoft-ecommerce::validation.order.intl_postal_code_required'),
|
||||
'delivery_memo.max' => __('sirsoft-ecommerce::validation.orders.delivery_memo.max'),
|
||||
'recipient_country_code.size' => __('sirsoft-ecommerce::validation.orders.recipient_country_code.size'),
|
||||
];
|
||||
|
||||
+75
@@ -0,0 +1,75 @@
|
||||
<?php
|
||||
|
||||
namespace Modules\Sirsoft\Ecommerce\Http\Requests\Concerns;
|
||||
|
||||
/**
|
||||
* 주소록 폼 필드 ↔ UserAddress 컬럼 매핑 트레이트 (MP08 후속 — D8/D10)
|
||||
*
|
||||
* 체크아웃/주소록 폼은 해외 주소를 intl_city/intl_state/intl_postal_code 키로 제출하지만,
|
||||
* UserAddress 모델 컬럼은 city/state/postal_code 다(주문 OrderAddress 의 intl_* 와 의도적 분리).
|
||||
* 키를 그대로 mass-assign 하면 비-fillable 키가 조용히 누락돼 해외 주소가 유실된다.
|
||||
*
|
||||
* 본 트레이트는 validated() 결과를 국가별로 정규화한다:
|
||||
* - KR(국내): zipcode/address/address_detail 만 유지, 해외 필드 제거
|
||||
* - 그 외(해외): intl_* → city/state/postal_code 변환, 국내 필드 제거
|
||||
*/
|
||||
trait MapsAddressBookFields
|
||||
{
|
||||
/**
|
||||
* 검증된 데이터를 UserAddress 컬럼 구조로 국가별 정규화하여 반환합니다.
|
||||
*
|
||||
* @param string|null $key 특정 키만 추출(기본 null=전체)
|
||||
* @param mixed $default 기본값
|
||||
* @return mixed 정규화된 검증 데이터
|
||||
*/
|
||||
public function validated($key = null, $default = null): mixed
|
||||
{
|
||||
$data = parent::validated();
|
||||
|
||||
// country_code 미제출(부분 패치)이면 매핑/스트립을 적용하지 않는다(의도치 않은 필드 제거 방지).
|
||||
if (! array_key_exists('country_code', $data)) {
|
||||
if ($key !== null) {
|
||||
return $data[$key] ?? $default;
|
||||
}
|
||||
|
||||
return $data;
|
||||
}
|
||||
|
||||
$country = strtoupper((string) ($data['country_code'] ?? 'KR'));
|
||||
if ($country === '') {
|
||||
$country = 'KR';
|
||||
}
|
||||
|
||||
if ($country === 'KR') {
|
||||
// 국내: 해외 전용 필드 제거
|
||||
unset(
|
||||
$data['address_line_1'],
|
||||
$data['address_line_2'],
|
||||
$data['intl_city'],
|
||||
$data['intl_state'],
|
||||
$data['intl_postal_code'],
|
||||
);
|
||||
} else {
|
||||
// 해외: intl_* → city/state/postal_code 변환, 국내 전용 필드 제거
|
||||
$data['city'] = $data['intl_city'] ?? null;
|
||||
$data['state'] = $data['intl_state'] ?? null;
|
||||
$data['postal_code'] = $data['intl_postal_code'] ?? null;
|
||||
|
||||
unset(
|
||||
$data['intl_city'],
|
||||
$data['intl_state'],
|
||||
$data['intl_postal_code'],
|
||||
$data['zipcode'],
|
||||
$data['address'],
|
||||
$data['address_detail'],
|
||||
$data['address_type_code'],
|
||||
);
|
||||
}
|
||||
|
||||
if ($key !== null) {
|
||||
return $data[$key] ?? $default;
|
||||
}
|
||||
|
||||
return $data;
|
||||
}
|
||||
}
|
||||
@@ -36,6 +36,12 @@ class BulkAddToCartRequest extends FormRequest
|
||||
'items' => 'required|array|min:1',
|
||||
'items.*.option_values' => 'nullable|array',
|
||||
'items.*.quantity' => 'required|integer|min:1|max:9999',
|
||||
// 추가옵션 선택 (서버에서 value_id 기준 가격 재조회·검증 — 클라 가격 신뢰 금지)
|
||||
'items.*.additional_option_selections' => 'nullable|array',
|
||||
'items.*.additional_option_selections.*.additional_option_id' => 'required_with:items.*.additional_option_selections|integer',
|
||||
'items.*.additional_option_selections.*.value_id' => 'required_with:items.*.additional_option_selections|integer',
|
||||
// 직접입력 텍스트 (선택지의 allow_custom_text 여부·필수성은 서버에서 재검증)
|
||||
'items.*.additional_option_selections.*.custom_text' => 'nullable|string|max:255',
|
||||
];
|
||||
|
||||
return HookManager::applyFilters('sirsoft-ecommerce.cart.bulk_add_validation_rules', $rules, $this);
|
||||
|
||||
+8
@@ -14,6 +14,8 @@ class ChangeCartOptionRequest extends FormRequest
|
||||
{
|
||||
/**
|
||||
* 사용자가 이 요청을 수행할 권한이 있는지 확인
|
||||
*
|
||||
* @return bool
|
||||
*/
|
||||
public function authorize(): bool
|
||||
{
|
||||
@@ -30,6 +32,12 @@ class ChangeCartOptionRequest extends FormRequest
|
||||
$rules = [
|
||||
'product_option_id' => ['required', 'integer', Rule::exists(ProductOption::class, 'id')],
|
||||
'quantity' => 'required|integer|min:1|max:9999',
|
||||
// 추가옵션 재선택 (미전달 시 기존 선택 유지 — 서버에서 value_id 검증/가격 재조회)
|
||||
'additional_option_selections' => 'nullable|array',
|
||||
'additional_option_selections.*.additional_option_id' => 'required_with:additional_option_selections|integer',
|
||||
'additional_option_selections.*.value_id' => 'required_with:additional_option_selections|integer',
|
||||
// 직접입력 텍스트 (선택지의 allow_custom_text 여부·필수성은 서버에서 재검증)
|
||||
'additional_option_selections.*.custom_text' => 'nullable|string|max:255',
|
||||
];
|
||||
|
||||
return HookManager::applyFilters('sirsoft-ecommerce.cart.change_option_validation_rules', $rules, $this);
|
||||
|
||||
@@ -16,6 +16,8 @@ class CheckoutRequest extends FormRequest
|
||||
{
|
||||
/**
|
||||
* 사용자가 이 요청을 수행할 권한이 있는지 확인
|
||||
*
|
||||
* @return bool
|
||||
*/
|
||||
public function authorize(): bool
|
||||
{
|
||||
@@ -29,9 +31,22 @@ class CheckoutRequest extends FormRequest
|
||||
*/
|
||||
public function rules(): array
|
||||
{
|
||||
// item_ids(장바구니 경유) 또는 direct_items(바로 구매, 장바구니 미경유) 택일
|
||||
$isDirect = $this->has('direct_items');
|
||||
|
||||
$rules = [
|
||||
'item_ids' => 'required|array|min:1',
|
||||
'item_ids' => [Rule::requiredIf(! $isDirect), 'array', 'min:1'],
|
||||
'item_ids.*' => ['integer', Rule::exists(Cart::class, 'id')],
|
||||
'direct_items' => [Rule::requiredIf($isDirect), 'array', 'min:1'],
|
||||
'direct_items.*.product_id' => ['required_with:direct_items', 'integer'],
|
||||
'direct_items.*.option_values' => ['nullable', 'array'],
|
||||
'direct_items.*.quantity' => ['required_with:direct_items', 'integer', 'min:1'],
|
||||
// 바로구매 추가옵션 선택 (서버에서 value_id 기준 검증/가격 재조회)
|
||||
'direct_items.*.additional_option_selections' => ['nullable', 'array'],
|
||||
'direct_items.*.additional_option_selections.*.additional_option_id' => ['required_with:direct_items.*.additional_option_selections', 'integer'],
|
||||
'direct_items.*.additional_option_selections.*.value_id' => ['required_with:direct_items.*.additional_option_selections', 'integer'],
|
||||
// 직접입력 텍스트 (선택지의 allow_custom_text 여부·필수성은 서버에서 재검증)
|
||||
'direct_items.*.additional_option_selections.*.custom_text' => ['nullable', 'string', 'max:255'],
|
||||
'coupon_issue_ids' => 'nullable|array',
|
||||
'coupon_issue_ids.*' => 'integer',
|
||||
'use_points' => 'nullable|integer|min:0',
|
||||
|
||||
@@ -16,6 +16,8 @@ class CreateOrderRequest extends FormRequest
|
||||
{
|
||||
/**
|
||||
* 사용자가 이 요청을 수행할 권한이 있는지 확인
|
||||
*
|
||||
* @return bool 항상 true (권한은 미들웨어 체인에서 처리)
|
||||
*/
|
||||
public function authorize(): bool
|
||||
{
|
||||
@@ -25,15 +27,14 @@ class CreateOrderRequest extends FormRequest
|
||||
/**
|
||||
* 요청에 적용할 검증 규칙
|
||||
*
|
||||
* @return array
|
||||
* @return array<string, mixed> 검증 규칙 배열
|
||||
*/
|
||||
public function rules(): array
|
||||
{
|
||||
$rules = [
|
||||
// 주문자 정보
|
||||
// 주문자 정보 (이메일은 회원/비회원 분기 — getOrdererEmailRules)
|
||||
'orderer.name' => 'required|string|max:50',
|
||||
'orderer.phone' => 'required|string|max:20',
|
||||
'orderer.email' => 'nullable|email|max:255',
|
||||
|
||||
// 배송지 정보
|
||||
'shipping.recipient_name' => 'required|string|max:50',
|
||||
@@ -75,13 +76,70 @@ class CreateOrderRequest extends FormRequest
|
||||
'save_shipping_address' => 'nullable|boolean',
|
||||
];
|
||||
|
||||
// 주문자 이메일은 회원/비회원 분기 (비회원은 알림 수신 통로가 이메일뿐 → 필수)
|
||||
$rules = array_merge($rules, $this->getOrdererEmailRules());
|
||||
|
||||
// 비회원 주문일 때만 조회 비밀번호 규칙 추가 (회원은 미요구)
|
||||
$rules = array_merge($rules, $this->getGuestLookupRules());
|
||||
|
||||
return HookManager::applyFilters('sirsoft-ecommerce.order.create_validation_rules', $rules, $this);
|
||||
}
|
||||
|
||||
/**
|
||||
* 주문자 이메일 검증 규칙을 반환합니다.
|
||||
*
|
||||
* 회원은 가입 시점에 이메일을 보유하고 주문서에서 자동 채워지므로 nullable 로 유지하고,
|
||||
* 비회원은 주문 확인/배송/취소 알림을 받을 통로가 주문자 이메일뿐이므로 required 로 강제합니다.
|
||||
*
|
||||
* @return array<string, mixed>
|
||||
*/
|
||||
protected function getOrdererEmailRules(): array
|
||||
{
|
||||
// 로그인 사용자(회원)는 이메일 자동 채움 → 형식만 검증
|
||||
if ($this->user()) {
|
||||
return ['orderer.email' => ['nullable', 'email', 'max:255']];
|
||||
}
|
||||
|
||||
// 비회원 주문 → 알림 수신 통로 확보를 위해 이메일 필수
|
||||
return ['orderer.email' => ['required', 'email', 'max:255']];
|
||||
}
|
||||
|
||||
/**
|
||||
* 비회원 주문 조회 비밀번호 검증 규칙을 반환합니다.
|
||||
*
|
||||
* 로그인 사용자(회원)는 조회 비밀번호가 필요 없으므로 nullable 로 유지하고,
|
||||
* 비로그인 사용자(비회원)에게만 8자 이상 + 확인 일치를 강제합니다 (G7 회원가입 정책과 일치).
|
||||
* 실제 해시 저장은 후속 단계(주문 생성 시점)에서 처리합니다.
|
||||
*
|
||||
* @return array<string, mixed>
|
||||
*/
|
||||
protected function getGuestLookupRules(): array
|
||||
{
|
||||
// 로그인 사용자는 회원 주문 → 조회 비밀번호 미요구
|
||||
if ($this->user()) {
|
||||
return [
|
||||
'guest_lookup_password' => ['nullable'],
|
||||
'guest_lookup_password_confirmation' => ['nullable'],
|
||||
];
|
||||
}
|
||||
|
||||
// 비회원 주문 → 8자 이상, 확인 일치 필수 (G7 회원가입 정책과 일치 — RegisterRequest 의 min:8|confirmed)
|
||||
return [
|
||||
'guest_lookup_password' => [
|
||||
'required',
|
||||
'string',
|
||||
'min:8',
|
||||
'max:255',
|
||||
'confirmed',
|
||||
],
|
||||
'guest_lookup_password_confirmation' => ['required', 'string'],
|
||||
];
|
||||
}
|
||||
|
||||
/**
|
||||
* 검증 오류 메시지 커스터마이징
|
||||
*
|
||||
* @return array
|
||||
* @return array<string, string> 검증 메시지 배열
|
||||
*/
|
||||
public function messages(): array
|
||||
{
|
||||
@@ -89,6 +147,7 @@ class CreateOrderRequest extends FormRequest
|
||||
// 주문자 정보
|
||||
'orderer.name.required' => __('sirsoft-ecommerce::validation.order.orderer_name_required'),
|
||||
'orderer.phone.required' => __('sirsoft-ecommerce::validation.order.orderer_phone_required'),
|
||||
'orderer.email.required' => __('sirsoft-ecommerce::validation.order.orderer_email_required'),
|
||||
'orderer.email.email' => __('sirsoft-ecommerce::validation.order.orderer_email_invalid'),
|
||||
|
||||
// 배송지 정보
|
||||
@@ -113,13 +172,19 @@ class CreateOrderRequest extends FormRequest
|
||||
'dbank.bank_code.required_if' => __('sirsoft-ecommerce::validation.order.dbank_bank_code_required'),
|
||||
'dbank.account_number.required_if' => __('sirsoft-ecommerce::validation.order.dbank_account_number_required'),
|
||||
'dbank.account_holder.required_if' => __('sirsoft-ecommerce::validation.order.dbank_account_holder_required'),
|
||||
|
||||
// 비회원 조회 비밀번호
|
||||
'guest_lookup_password.required' => __('sirsoft-ecommerce::validation.order.guest_lookup_password_required'),
|
||||
'guest_lookup_password.min' => __('sirsoft-ecommerce::validation.order.guest_lookup_password_min'),
|
||||
'guest_lookup_password.confirmed' => __('sirsoft-ecommerce::validation.order.guest_lookup_password_confirmed'),
|
||||
'guest_lookup_password_confirmation.required' => __('sirsoft-ecommerce::validation.order.guest_lookup_password_confirmation_required'),
|
||||
];
|
||||
}
|
||||
|
||||
/**
|
||||
* 주문자 정보 반환
|
||||
*
|
||||
* @return array
|
||||
* @return array{name: string, phone: string, email: string} 주문자 정보
|
||||
*/
|
||||
public function getOrdererInfo(): array
|
||||
{
|
||||
@@ -135,7 +200,7 @@ class CreateOrderRequest extends FormRequest
|
||||
/**
|
||||
* 배송지 정보 반환
|
||||
*
|
||||
* @return array
|
||||
* @return array<string, mixed> 배송지 입력값 배열
|
||||
*/
|
||||
public function getShippingInfo(): array
|
||||
{
|
||||
@@ -145,14 +210,33 @@ class CreateOrderRequest extends FormRequest
|
||||
/**
|
||||
* 무통장 수동입금 정보 반환
|
||||
*
|
||||
* @return array|null
|
||||
* @return array<string, mixed>|null dbank 결제 시 입금 정보, 그 외 null
|
||||
*/
|
||||
public function getDbankInfo(): ?array
|
||||
{
|
||||
if ($this->input('payment_method') !== 'dbank') {
|
||||
if ($this->input('payment_method') !== PaymentMethodEnum::DBANK->value) {
|
||||
return null;
|
||||
}
|
||||
|
||||
return $this->input('dbank');
|
||||
}
|
||||
|
||||
/**
|
||||
* 비회원 주문 조회 비밀번호 반환 (회원 주문이면 null)
|
||||
*
|
||||
* 평문 비밀번호이며, 주문 생성 시점에 해시로 변환해 저장합니다.
|
||||
* 응답/로그에 그대로 노출하지 않습니다.
|
||||
*
|
||||
* @return string|null 비회원 조회 비밀번호 (회원이면 null)
|
||||
*/
|
||||
public function getGuestLookupPassword(): ?string
|
||||
{
|
||||
if ($this->user()) {
|
||||
return null;
|
||||
}
|
||||
|
||||
$password = $this->input('guest_lookup_password');
|
||||
|
||||
return is_string($password) && $password !== '' ? $password : null;
|
||||
}
|
||||
}
|
||||
+139
@@ -0,0 +1,139 @@
|
||||
<?php
|
||||
|
||||
namespace Modules\Sirsoft\Ecommerce\Http\Requests\Public;
|
||||
|
||||
use App\Helpers\ResponseHelper;
|
||||
use Illuminate\Contracts\Validation\Validator;
|
||||
use Illuminate\Foundation\Http\FormRequest;
|
||||
use Illuminate\Validation\Rule;
|
||||
use Modules\Sirsoft\Ecommerce\Enums\RefundPriorityEnum;
|
||||
use Modules\Sirsoft\Ecommerce\Models\ClaimReason;
|
||||
use Modules\Sirsoft\Ecommerce\Models\Order;
|
||||
|
||||
/**
|
||||
* 비회원 주문 취소 요청
|
||||
*
|
||||
* 주문 소유권은 VerifyGuestOrderToken 미들웨어가 이미 검증했으므로,
|
||||
* 본 요청은 입력값 형식과 취소 가능 상태만 검증한다. 대상 주문은
|
||||
* 미들웨어가 request attribute(guest_order)로 전달한 것을 사용한다.
|
||||
*/
|
||||
class GuestCancelOrderRequest extends FormRequest
|
||||
{
|
||||
/**
|
||||
* 사용자가 이 요청을 수행할 권한이 있는지 확인
|
||||
*
|
||||
* @return bool 항상 true (실제 인증은 VerifyGuestOrderToken 미들웨어가 수행)
|
||||
*/
|
||||
public function authorize(): bool
|
||||
{
|
||||
return true;
|
||||
}
|
||||
|
||||
/**
|
||||
* 요청에 적용할 검증 규칙
|
||||
*
|
||||
* @return array<string, array<int, string>> 필드별 규칙 배열
|
||||
*/
|
||||
public function rules(): array
|
||||
{
|
||||
return [
|
||||
'reason' => ['required', 'string', Rule::exists(ClaimReason::class, 'code')->where('type', 'refund')->where('is_active', true)->where('is_user_selectable', true)],
|
||||
'reason_detail' => ['nullable', 'string', 'max:500'],
|
||||
'items' => ['nullable', 'array', 'min:1'],
|
||||
'items.*.order_option_id' => ['required_with:items', 'integer'],
|
||||
'items.*.cancel_quantity' => ['required_with:items', 'integer', 'min:1'],
|
||||
'refund_priority' => ['sometimes', 'string', 'in:'.implode(',', RefundPriorityEnum::values())],
|
||||
];
|
||||
}
|
||||
|
||||
/**
|
||||
* 추가 검증 로직 (취소 가능 상태 확인)
|
||||
*/
|
||||
protected function withValidator(Validator $validator): void
|
||||
{
|
||||
$validator->after(function (Validator $validator) {
|
||||
$order = $this->getOrder();
|
||||
|
||||
$cancellableStatuses = module_setting(
|
||||
'sirsoft-ecommerce',
|
||||
'order_settings.cancellable_statuses',
|
||||
['payment_complete']
|
||||
);
|
||||
|
||||
if (! $order->isCancellable($cancellableStatuses)) {
|
||||
$validator->errors()->add(
|
||||
'order_status',
|
||||
$order->getCancelDeniedReason($cancellableStatuses)
|
||||
);
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
/**
|
||||
* 미들웨어가 검증한 대상 주문을 반환합니다.
|
||||
*
|
||||
* @return Order 토큰 검증을 통과한 비회원 주문
|
||||
*/
|
||||
public function getOrder(): Order
|
||||
{
|
||||
$order = $this->attributes->get('guest_order');
|
||||
|
||||
if (! $order instanceof Order) {
|
||||
abort(ResponseHelper::moduleError('sirsoft-ecommerce', 'exceptions.order_not_found', 404));
|
||||
}
|
||||
|
||||
return $order;
|
||||
}
|
||||
|
||||
/**
|
||||
* 부분취소 여부를 반환합니다.
|
||||
*
|
||||
* @return bool items 배열에 항목이 1개 이상이면 부분취소
|
||||
*/
|
||||
public function isPartialCancel(): bool
|
||||
{
|
||||
return $this->has('items') && is_array($this->input('items')) && count($this->input('items')) > 0;
|
||||
}
|
||||
|
||||
/**
|
||||
* 부분취소 대상 항목을 반환합니다.
|
||||
*
|
||||
* @return array<int, array{order_option_id: int, cancel_quantity: int}> 취소 대상 옵션 배열
|
||||
*/
|
||||
public function getCancelItems(): array
|
||||
{
|
||||
return $this->input('items', []);
|
||||
}
|
||||
|
||||
/**
|
||||
* 취소 사유 코드를 반환합니다.
|
||||
*
|
||||
* @return string|null ClaimReason 코드 (refund 타입)
|
||||
*/
|
||||
public function getReason(): ?string
|
||||
{
|
||||
return $this->input('reason');
|
||||
}
|
||||
|
||||
/**
|
||||
* 취소 사유 상세를 반환합니다.
|
||||
*
|
||||
* @return string|null 사용자 입력 사유 상세 (최대 500자)
|
||||
*/
|
||||
public function getReasonDetail(): ?string
|
||||
{
|
||||
return $this->input('reason_detail');
|
||||
}
|
||||
|
||||
/**
|
||||
* 환불 우선순위를 반환합니다.
|
||||
*
|
||||
* @return RefundPriorityEnum 환불 우선순위 (입력 없으면 PG_FIRST)
|
||||
*/
|
||||
public function getRefundPriority(): RefundPriorityEnum
|
||||
{
|
||||
$value = $this->validated('refund_priority');
|
||||
|
||||
return $value ? RefundPriorityEnum::from($value) : RefundPriorityEnum::PG_FIRST;
|
||||
}
|
||||
}
|
||||
+80
@@ -0,0 +1,80 @@
|
||||
<?php
|
||||
|
||||
namespace Modules\Sirsoft\Ecommerce\Http\Requests\Public;
|
||||
|
||||
use App\Helpers\ResponseHelper;
|
||||
use Illuminate\Foundation\Http\FormRequest;
|
||||
use Modules\Sirsoft\Ecommerce\Enums\RefundPriorityEnum;
|
||||
use Modules\Sirsoft\Ecommerce\Models\Order;
|
||||
|
||||
/**
|
||||
* 비회원 환불 예상금액 조회 요청
|
||||
*
|
||||
* 주문 소유권은 VerifyGuestOrderToken 미들웨어가 검증하며, 본 요청은
|
||||
* 환불 대상 항목 입력만 검증한다.
|
||||
*/
|
||||
class GuestEstimateRefundRequest extends FormRequest
|
||||
{
|
||||
/**
|
||||
* 사용자가 이 요청을 수행할 권한이 있는지 확인
|
||||
*
|
||||
* @return bool 항상 true (실제 인증은 VerifyGuestOrderToken 미들웨어가 수행)
|
||||
*/
|
||||
public function authorize(): bool
|
||||
{
|
||||
return true;
|
||||
}
|
||||
|
||||
/**
|
||||
* 요청에 적용할 검증 규칙
|
||||
*
|
||||
* @return array<string, array<int, string>> 필드별 규칙 배열
|
||||
*/
|
||||
public function rules(): array
|
||||
{
|
||||
return [
|
||||
'items' => ['required', 'array', 'min:1'],
|
||||
'items.*.order_option_id' => ['required', 'integer'],
|
||||
'items.*.cancel_quantity' => ['required', 'integer', 'min:1'],
|
||||
'refund_priority' => ['sometimes', 'string', 'in:'.implode(',', RefundPriorityEnum::values())],
|
||||
];
|
||||
}
|
||||
|
||||
/**
|
||||
* 미들웨어가 검증한 대상 주문을 반환합니다.
|
||||
*
|
||||
* @return Order 토큰 검증을 통과한 비회원 주문
|
||||
*/
|
||||
public function getOrder(): Order
|
||||
{
|
||||
$order = $this->attributes->get('guest_order');
|
||||
|
||||
if (! $order instanceof Order) {
|
||||
abort(ResponseHelper::moduleError('sirsoft-ecommerce', 'exceptions.order_not_found', 404));
|
||||
}
|
||||
|
||||
return $order;
|
||||
}
|
||||
|
||||
/**
|
||||
* 환불 예상 대상 항목을 반환합니다.
|
||||
*
|
||||
* @return array<int, array{order_option_id: int, cancel_quantity: int}> 환불 대상 옵션 배열
|
||||
*/
|
||||
public function getCancelItems(): array
|
||||
{
|
||||
return $this->input('items', []);
|
||||
}
|
||||
|
||||
/**
|
||||
* 환불 우선순위를 반환합니다.
|
||||
*
|
||||
* @return RefundPriorityEnum 환불 우선순위 (입력 없으면 PG_FIRST)
|
||||
*/
|
||||
public function getRefundPriority(): RefundPriorityEnum
|
||||
{
|
||||
$value = $this->validated('refund_priority');
|
||||
|
||||
return $value ? RefundPriorityEnum::from($value) : RefundPriorityEnum::PG_FIRST;
|
||||
}
|
||||
}
|
||||
+53
@@ -0,0 +1,53 @@
|
||||
<?php
|
||||
|
||||
namespace Modules\Sirsoft\Ecommerce\Http\Requests\Public;
|
||||
|
||||
use App\Helpers\ResponseHelper;
|
||||
use Illuminate\Foundation\Http\FormRequest;
|
||||
use Modules\Sirsoft\Ecommerce\Models\Order;
|
||||
|
||||
/**
|
||||
* 비회원 주문 토큰 보호 요청 (입력 본문 없는 액션용)
|
||||
*
|
||||
* 상세 조회·구매확정처럼 별도 입력 본문이 없는 비회원 액션에서 사용한다.
|
||||
* 주문 소유권은 VerifyGuestOrderToken 미들웨어가 검증하며, 본 요청은
|
||||
* 미들웨어가 전달한 주문(guest_order attribute)에 대한 접근자만 제공한다.
|
||||
*/
|
||||
class GuestOrderTokenRequest extends FormRequest
|
||||
{
|
||||
/**
|
||||
* 사용자가 이 요청을 수행할 권한이 있는지 확인
|
||||
*
|
||||
* @return bool
|
||||
*/
|
||||
public function authorize(): bool
|
||||
{
|
||||
return true;
|
||||
}
|
||||
|
||||
/**
|
||||
* 요청에 적용할 검증 규칙
|
||||
*
|
||||
* @return array
|
||||
*/
|
||||
public function rules(): array
|
||||
{
|
||||
return [];
|
||||
}
|
||||
|
||||
/**
|
||||
* 미들웨어가 검증한 대상 주문을 반환합니다.
|
||||
*
|
||||
* @return Order
|
||||
*/
|
||||
public function getOrder(): Order
|
||||
{
|
||||
$order = $this->attributes->get('guest_order');
|
||||
|
||||
if (! $order instanceof Order) {
|
||||
abort(ResponseHelper::moduleError('sirsoft-ecommerce', 'exceptions.order_not_found', 404));
|
||||
}
|
||||
|
||||
return $order;
|
||||
}
|
||||
}
|
||||
+88
@@ -0,0 +1,88 @@
|
||||
<?php
|
||||
|
||||
namespace Modules\Sirsoft\Ecommerce\Http\Requests\Public;
|
||||
|
||||
use App\Helpers\ResponseHelper;
|
||||
use Illuminate\Foundation\Http\FormRequest;
|
||||
use Modules\Sirsoft\Ecommerce\Models\Order;
|
||||
|
||||
/**
|
||||
* 비회원 주문 배송지 수정 요청
|
||||
*
|
||||
* 주문 소유권은 VerifyGuestOrderToken 미들웨어가 검증한다. 비회원은 저장된
|
||||
* 회원 주소(address_id)를 사용할 수 없으므로 배송지 필드를 직접 입력받는다.
|
||||
*/
|
||||
class GuestUpdateShippingAddressRequest extends FormRequest
|
||||
{
|
||||
/**
|
||||
* 사용자가 이 요청을 수행할 권한이 있는지 확인
|
||||
*
|
||||
* @return bool
|
||||
*/
|
||||
public function authorize(): bool
|
||||
{
|
||||
return true;
|
||||
}
|
||||
|
||||
/**
|
||||
* 요청에 적용할 검증 규칙
|
||||
*
|
||||
* @return array<string, mixed>
|
||||
*/
|
||||
public function rules(): array
|
||||
{
|
||||
return [
|
||||
'recipient_name' => ['required', 'string', 'max:50'],
|
||||
'recipient_phone' => ['required', 'string', 'max:20'],
|
||||
'recipient_tel' => ['nullable', 'string', 'max:20'],
|
||||
'country_code' => ['nullable', 'string', 'size:2'],
|
||||
|
||||
// 국내 배송 주소
|
||||
'zipcode' => ['required_without:address_line_1', 'nullable', 'string', 'max:10'],
|
||||
'address' => ['required_without:address_line_1', 'nullable', 'string', 'max:255'],
|
||||
'address_detail' => ['nullable', 'string', 'max:255'],
|
||||
|
||||
// 해외 배송 주소
|
||||
'address_line_1' => ['required_without:address', 'nullable', 'string', 'max:255'],
|
||||
'address_line_2' => ['nullable', 'string', 'max:255'],
|
||||
'intl_city' => ['required_with:address_line_1', 'nullable', 'string', 'max:100'],
|
||||
'intl_state' => ['nullable', 'string', 'max:100'],
|
||||
'intl_postal_code' => ['required_with:address_line_1', 'nullable', 'string', 'max:20'],
|
||||
|
||||
'delivery_memo' => ['nullable', 'string', 'max:255'],
|
||||
];
|
||||
}
|
||||
|
||||
/**
|
||||
* 검증 오류 메시지 커스터마이징
|
||||
*
|
||||
* @return array<string, string>
|
||||
*/
|
||||
public function messages(): array
|
||||
{
|
||||
return [
|
||||
'recipient_name.required' => __('sirsoft-ecommerce::validation.user_address.recipient_name_required'),
|
||||
'recipient_phone.required' => __('sirsoft-ecommerce::validation.user_address.recipient_phone_required'),
|
||||
'zipcode.required_without' => __('sirsoft-ecommerce::validation.user_address.zipcode_required'),
|
||||
'address.required_without' => __('sirsoft-ecommerce::validation.user_address.address_required'),
|
||||
'address_line_1.required_without' => __('sirsoft-ecommerce::validation.user_address.address_line_1_required'),
|
||||
'intl_city.required_with' => __('sirsoft-ecommerce::validation.user_address.intl_city_required'),
|
||||
];
|
||||
}
|
||||
|
||||
/**
|
||||
* 미들웨어가 검증한 대상 주문을 반환합니다.
|
||||
*
|
||||
* @return Order 토큰 검증을 통과한 비회원 주문
|
||||
*/
|
||||
public function getOrder(): Order
|
||||
{
|
||||
$order = $this->attributes->get('guest_order');
|
||||
|
||||
if (! $order instanceof Order) {
|
||||
abort(ResponseHelper::moduleError('sirsoft-ecommerce', 'exceptions.order_not_found', 404));
|
||||
}
|
||||
|
||||
return $order;
|
||||
}
|
||||
}
|
||||
+52
@@ -0,0 +1,52 @@
|
||||
<?php
|
||||
|
||||
namespace Modules\Sirsoft\Ecommerce\Http\Requests\Public;
|
||||
|
||||
use Illuminate\Foundation\Http\FormRequest;
|
||||
|
||||
/**
|
||||
* 비회원 주문 조회 인증 요청
|
||||
*
|
||||
* 주문번호 + 전화번호 + 조회 비밀번호로 본인 확인을 수행합니다.
|
||||
* 권한 체크는 라우트 미들웨어가 담당하며, 본 요청은 입력 형식만 검증합니다.
|
||||
*/
|
||||
class VerifyGuestOrderRequest extends FormRequest
|
||||
{
|
||||
/**
|
||||
* 사용자가 이 요청을 수행할 권한이 있는지 확인
|
||||
*
|
||||
* @return bool 권한 보유 여부 (라우트 미들웨어가 실제 인증 수행)
|
||||
*/
|
||||
public function authorize(): bool
|
||||
{
|
||||
return true;
|
||||
}
|
||||
|
||||
/**
|
||||
* 요청에 적용할 검증 규칙
|
||||
*
|
||||
* @return array<string, array<int, string>> 필드별 규칙 배열
|
||||
*/
|
||||
public function rules(): array
|
||||
{
|
||||
return [
|
||||
'order_number' => ['required', 'string', 'max:50'],
|
||||
'orderer_phone' => ['required', 'string', 'max:20'],
|
||||
'guest_lookup_password' => ['required', 'string', 'max:255'],
|
||||
];
|
||||
}
|
||||
|
||||
/**
|
||||
* 검증 오류 메시지 커스터마이징
|
||||
*
|
||||
* @return array<string, string> 검증 규칙 키 → 다국어 메시지
|
||||
*/
|
||||
public function messages(): array
|
||||
{
|
||||
return [
|
||||
'order_number.required' => __('sirsoft-ecommerce::validation.guest_order.order_number_required'),
|
||||
'orderer_phone.required' => __('sirsoft-ecommerce::validation.guest_order.orderer_phone_required'),
|
||||
'guest_lookup_password.required' => __('sirsoft-ecommerce::validation.guest_order.guest_lookup_password_required'),
|
||||
];
|
||||
}
|
||||
}
|
||||
+11
-3
@@ -4,14 +4,19 @@ namespace Modules\Sirsoft\Ecommerce\Http\Requests\User;
|
||||
|
||||
use App\Extension\HookManager;
|
||||
use Illuminate\Foundation\Http\FormRequest;
|
||||
use Modules\Sirsoft\Ecommerce\Http\Requests\Concerns\MapsAddressBookFields;
|
||||
|
||||
/**
|
||||
* 사용자 배송지 등록 요청
|
||||
*/
|
||||
class StoreUserAddressRequest extends FormRequest
|
||||
{
|
||||
use MapsAddressBookFields;
|
||||
|
||||
/**
|
||||
* 사용자가 이 요청을 수행할 권한이 있는지 확인
|
||||
*
|
||||
* @return bool 항상 true (권한은 미들웨어 체인이 담당)
|
||||
*/
|
||||
public function authorize(): bool
|
||||
{
|
||||
@@ -20,8 +25,6 @@ class StoreUserAddressRequest extends FormRequest
|
||||
|
||||
/**
|
||||
* 요청 데이터 전처리
|
||||
*
|
||||
* @return void
|
||||
*/
|
||||
protected function prepareForValidation(): void
|
||||
{
|
||||
@@ -31,6 +34,11 @@ class StoreUserAddressRequest extends FormRequest
|
||||
]);
|
||||
}
|
||||
|
||||
/**
|
||||
* 검증 규칙을 반환합니다.
|
||||
*
|
||||
* @return array 주소록 저장 검증 규칙 (국내/해외 상호배제)
|
||||
*/
|
||||
public function rules(): array
|
||||
{
|
||||
$rules = [
|
||||
@@ -72,7 +80,7 @@ class StoreUserAddressRequest extends FormRequest
|
||||
/**
|
||||
* 검증 오류 메시지 커스터마이징
|
||||
*
|
||||
* @return array
|
||||
* @return array 필드별 다국어 검증 메시지
|
||||
*/
|
||||
public function messages(): array
|
||||
{
|
||||
|
||||
+7
-4
@@ -4,14 +4,19 @@ namespace Modules\Sirsoft\Ecommerce\Http\Requests\User;
|
||||
|
||||
use App\Extension\HookManager;
|
||||
use Illuminate\Foundation\Http\FormRequest;
|
||||
use Modules\Sirsoft\Ecommerce\Http\Requests\Concerns\MapsAddressBookFields;
|
||||
|
||||
/**
|
||||
* 사용자 배송지 수정 요청
|
||||
*/
|
||||
class UpdateUserAddressRequest extends FormRequest
|
||||
{
|
||||
use MapsAddressBookFields;
|
||||
|
||||
/**
|
||||
* 사용자가 이 요청을 수행할 권한이 있는지 확인
|
||||
*
|
||||
* @return bool 항상 true (권한은 미들웨어 체인이 담당)
|
||||
*/
|
||||
public function authorize(): bool
|
||||
{
|
||||
@@ -20,8 +25,6 @@ class UpdateUserAddressRequest extends FormRequest
|
||||
|
||||
/**
|
||||
* 요청 데이터 전처리
|
||||
*
|
||||
* @return void
|
||||
*/
|
||||
protected function prepareForValidation(): void
|
||||
{
|
||||
@@ -36,7 +39,7 @@ class UpdateUserAddressRequest extends FormRequest
|
||||
/**
|
||||
* 요청에 적용할 검증 규칙
|
||||
*
|
||||
* @return array
|
||||
* @return array 주소록 수정 검증 규칙
|
||||
*/
|
||||
public function rules(): array
|
||||
{
|
||||
@@ -76,7 +79,7 @@ class UpdateUserAddressRequest extends FormRequest
|
||||
/**
|
||||
* 검증 오류 메시지 커스터마이징
|
||||
*
|
||||
* @return array
|
||||
* @return array 필드별 다국어 검증 메시지
|
||||
*/
|
||||
public function messages(): array
|
||||
{
|
||||
|
||||
+69
@@ -0,0 +1,69 @@
|
||||
<?php
|
||||
|
||||
namespace Modules\Sirsoft\Ecommerce\Http\Requests\User;
|
||||
|
||||
use Illuminate\Foundation\Http\FormRequest;
|
||||
use Illuminate\Validation\Rule;
|
||||
use Modules\Sirsoft\Ecommerce\Services\EcommerceSettingsService;
|
||||
|
||||
/**
|
||||
* 유저 결제 통화 변경 요청 검증 (A3)
|
||||
*
|
||||
* 관리자가 등록한 통화(language_currency.currencies) 중 환율이 설정된(또는 기본) 통화만 허용한다.
|
||||
* 환율 미설정 통화는 셀렉터에서도 숨겨지므로 저장도 거부(미등록 422).
|
||||
*/
|
||||
class UpdateUserCurrencyRequest extends FormRequest
|
||||
{
|
||||
/**
|
||||
* 권한 체크는 라우트의 auth:sanctum 미들웨어에서 수행됩니다.
|
||||
*
|
||||
* @return bool 항상 true
|
||||
*/
|
||||
public function authorize(): bool
|
||||
{
|
||||
return true;
|
||||
}
|
||||
|
||||
/**
|
||||
* 검증 규칙
|
||||
*
|
||||
* @return array<string, mixed>
|
||||
*/
|
||||
public function rules(): array
|
||||
{
|
||||
return [
|
||||
'currency' => ['required', 'string', Rule::in($this->allowedCurrencyCodes())],
|
||||
];
|
||||
}
|
||||
|
||||
/**
|
||||
* 허용 통화 코드 목록 (is_default || exchange_rate>0).
|
||||
*
|
||||
* @return array<int, string>
|
||||
*/
|
||||
private function allowedCurrencyCodes(): array
|
||||
{
|
||||
$currencies = app(EcommerceSettingsService::class)
|
||||
->getSetting('language_currency.currencies', []);
|
||||
|
||||
return collect($currencies)
|
||||
->filter(fn ($c) => ($c['is_default'] ?? false) || (float) ($c['exchange_rate'] ?? 0) > 0)
|
||||
->pluck('code')
|
||||
->filter()
|
||||
->values()
|
||||
->all();
|
||||
}
|
||||
|
||||
/**
|
||||
* 검증 메시지
|
||||
*
|
||||
* @return array<string, string>
|
||||
*/
|
||||
public function messages(): array
|
||||
{
|
||||
return [
|
||||
'currency.required' => __('sirsoft-ecommerce::validation.custom.user_currency.required'),
|
||||
'currency.in' => __('sirsoft-ecommerce::validation.custom.user_currency.invalid'),
|
||||
];
|
||||
}
|
||||
}
|
||||
+67
@@ -0,0 +1,67 @@
|
||||
<?php
|
||||
|
||||
namespace Modules\Sirsoft\Ecommerce\Http\Requests\User;
|
||||
|
||||
use Illuminate\Foundation\Http\FormRequest;
|
||||
use Illuminate\Validation\Rule;
|
||||
use Modules\Sirsoft\Ecommerce\Services\ShippingCountryResolver;
|
||||
|
||||
/**
|
||||
* 유저 배송국가 변경 요청 검증 (MP08 후속)
|
||||
*
|
||||
* 활성 배송가능 국가(available_countries[].is_active) 만 허용한다. 비활성 국가는 셀렉터에서도
|
||||
* 숨겨지므로 저장도 거부(미허용 422). 해외배송 OFF 면 활성은 KR 뿐이라 KR 만 통과한다.
|
||||
*/
|
||||
class UpdateUserShippingCountryRequest extends FormRequest
|
||||
{
|
||||
/**
|
||||
* 권한 체크는 라우트의 auth:sanctum 미들웨어에서 수행됩니다.
|
||||
*
|
||||
* @return bool 항상 true
|
||||
*/
|
||||
public function authorize(): bool
|
||||
{
|
||||
return true;
|
||||
}
|
||||
|
||||
/**
|
||||
* 검증 규칙
|
||||
*
|
||||
* @return array<string, mixed>
|
||||
*/
|
||||
public function rules(): array
|
||||
{
|
||||
return [
|
||||
'shipping_country' => [
|
||||
'required',
|
||||
'string',
|
||||
'size:2',
|
||||
Rule::in(app(ShippingCountryResolver::class)->allowedShippingCountryCodes()),
|
||||
],
|
||||
];
|
||||
}
|
||||
|
||||
/**
|
||||
* 검증 전 국가 코드를 대문자로 정규화합니다.
|
||||
*/
|
||||
protected function prepareForValidation(): void
|
||||
{
|
||||
if ($this->filled('shipping_country')) {
|
||||
$this->merge(['shipping_country' => strtoupper((string) $this->input('shipping_country'))]);
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* 검증 메시지
|
||||
*
|
||||
* @return array<string, string>
|
||||
*/
|
||||
public function messages(): array
|
||||
{
|
||||
return [
|
||||
'shipping_country.required' => __('sirsoft-ecommerce::validation.custom.user_shipping_country.required'),
|
||||
'shipping_country.in' => __('sirsoft-ecommerce::validation.custom.user_shipping_country.invalid'),
|
||||
'shipping_country.size' => __('sirsoft-ecommerce::validation.custom.user_shipping_country.invalid'),
|
||||
];
|
||||
}
|
||||
}
|
||||
+24
-6
@@ -2,6 +2,7 @@
|
||||
|
||||
namespace Modules\Sirsoft\Ecommerce\Http\Requests\User;
|
||||
|
||||
use Illuminate\Contracts\Validation\ValidationRule;
|
||||
use Illuminate\Foundation\Http\FormRequest;
|
||||
|
||||
/**
|
||||
@@ -14,7 +15,7 @@ class UploadReviewImageRequest extends FormRequest
|
||||
*
|
||||
* 권한 체크는 라우트의 permission 미들웨어에서 수행됩니다.
|
||||
*
|
||||
* @return bool
|
||||
* @return bool 항상 true (권한은 미들웨어에서 검증)
|
||||
*/
|
||||
public function authorize(): bool
|
||||
{
|
||||
@@ -24,16 +25,19 @@ class UploadReviewImageRequest extends FormRequest
|
||||
/**
|
||||
* 요청에 적용할 검증 규칙을 반환합니다.
|
||||
*
|
||||
* @return array<string, \Illuminate\Contracts\Validation\ValidationRule|array|string>
|
||||
* @return array<string, ValidationRule|array|string>
|
||||
*/
|
||||
public function rules(): array
|
||||
{
|
||||
// 리뷰 이미지 최대 용량 설정(MB)을 KB 로 환산 (설정 미반영 시 10MB 폴백)
|
||||
$maxKb = $this->maxImageSizeMb() * 1024;
|
||||
|
||||
return [
|
||||
'image' => [
|
||||
'required',
|
||||
'file',
|
||||
'image',
|
||||
'max:10240', // 10MB
|
||||
'max:'.$maxKb,
|
||||
],
|
||||
];
|
||||
}
|
||||
@@ -47,9 +51,23 @@ class UploadReviewImageRequest extends FormRequest
|
||||
{
|
||||
return [
|
||||
'image.required' => __('sirsoft-ecommerce::validation.review_image.image_required'),
|
||||
'image.file' => __('sirsoft-ecommerce::validation.review_image.image_file'),
|
||||
'image.image' => __('sirsoft-ecommerce::validation.review_image.image_image'),
|
||||
'image.max' => __('sirsoft-ecommerce::validation.review_image.image_max'),
|
||||
'image.file' => __('sirsoft-ecommerce::validation.review_image.image_file'),
|
||||
'image.image' => __('sirsoft-ecommerce::validation.review_image.image_image'),
|
||||
'image.max' => __('sirsoft-ecommerce::validation.review_image.image_max', ['max' => $this->maxImageSizeMb()]),
|
||||
];
|
||||
}
|
||||
|
||||
/**
|
||||
* 리뷰 이미지 최대 용량(MB)을 설정에서 조회합니다.
|
||||
*
|
||||
* @return int 최대 용량(MB)
|
||||
*/
|
||||
private function maxImageSizeMb(): int
|
||||
{
|
||||
return (int) module_setting(
|
||||
'sirsoft-ecommerce',
|
||||
'review_settings.max_image_size_mb',
|
||||
config('ecommerce.review.max_image_size_mb', 10)
|
||||
);
|
||||
}
|
||||
}
|
||||
+35
@@ -0,0 +1,35 @@
|
||||
<?php
|
||||
|
||||
namespace Modules\Sirsoft\Ecommerce\Http\Requests\User;
|
||||
|
||||
use Illuminate\Foundation\Http\FormRequest;
|
||||
|
||||
/**
|
||||
* 마이페이지 마일리지 내역 조회 요청
|
||||
*/
|
||||
class UserMileageHistoryRequest extends FormRequest
|
||||
{
|
||||
/**
|
||||
* 인증된 사용자만 접근 — 권한은 라우트 미들웨어에서 처리.
|
||||
*
|
||||
* @return bool 항상 true
|
||||
*/
|
||||
public function authorize(): bool
|
||||
{
|
||||
return true;
|
||||
}
|
||||
|
||||
/**
|
||||
* 검증 규칙
|
||||
*
|
||||
* @return array 검증 규칙
|
||||
*/
|
||||
public function rules(): array
|
||||
{
|
||||
return [
|
||||
'category' => ['nullable', 'string', 'in:earn,use,expire,adjust'],
|
||||
'currency' => ['nullable', 'string', 'max:10'],
|
||||
'per_page' => ['nullable', 'integer', 'min:1', 'max:100'],
|
||||
];
|
||||
}
|
||||
}
|
||||
@@ -3,9 +3,11 @@
|
||||
namespace Modules\Sirsoft\Ecommerce\Http\Resources;
|
||||
|
||||
use App\Http\Resources\BaseApiResource;
|
||||
use Modules\Sirsoft\Ecommerce\Http\Middleware\ResolveShippingCountry;
|
||||
use Modules\Sirsoft\Ecommerce\Http\Resources\Traits\HasMultiCurrencyPrices;
|
||||
use Modules\Sirsoft\Ecommerce\Models\Product;
|
||||
use Modules\Sirsoft\Ecommerce\Models\ProductOption;
|
||||
use Modules\Sirsoft\Ecommerce\Services\ShippingPolicyResolver;
|
||||
|
||||
/**
|
||||
* 주문 아이템 기본 리소스 (공통 구조)
|
||||
@@ -19,7 +21,7 @@ abstract class BaseOrderItemResource extends BaseApiResource
|
||||
/**
|
||||
* 상품 정보를 배열로 변환
|
||||
*
|
||||
* @param Product $product 상품 모델
|
||||
* @param Product $product 상품 모델
|
||||
* @return array 상품 정보 배열
|
||||
*/
|
||||
protected function formatProductInfo(Product $product): array
|
||||
@@ -39,15 +41,35 @@ abstract class BaseOrderItemResource extends BaseApiResource
|
||||
];
|
||||
}
|
||||
|
||||
/**
|
||||
* 상품이 현재 선택된 배송국가로 배송 가능한지 판정합니다. (D1)
|
||||
*
|
||||
* 상품에 배송정책이 부여되어 있으면 그 정책을, 없으면(shipping_policy_id=null)
|
||||
* 기본 배송정책으로 폴백해 해당 국가 설정 유무로 판정한다. 적용 가능한 정책이
|
||||
* 전혀 없을 때만 국내(KR) 기본 배송으로 간주. 미들웨어가 결정한
|
||||
* 배송국가(ResolveShippingCountry::getCountry)를 기준으로 한다.
|
||||
*
|
||||
* @param Product $product 상품 모델
|
||||
* @return bool 배송 가능 여부
|
||||
*/
|
||||
protected function isShippableToSelectedCountry(Product $product): bool
|
||||
{
|
||||
$country = ResolveShippingCountry::getCountry();
|
||||
|
||||
return app(ShippingPolicyResolver::class)->isShippableToCountry($product, $country);
|
||||
}
|
||||
|
||||
/**
|
||||
* 옵션 정보를 배열로 변환
|
||||
*
|
||||
* @param ProductOption $option 상품 옵션 모델
|
||||
* @param ProductOption $option 상품 옵션 모델
|
||||
* @return array 옵션 정보 배열
|
||||
*/
|
||||
protected function formatOptionInfo(ProductOption $option): array
|
||||
{
|
||||
$sellingPrice = $option->getSellingPrice();
|
||||
$listPrice = $option->getListPrice(); // 정가 (product->list_price + price_adjustment)
|
||||
$sellingPrice = $option->getSellingPrice(); // 판매가 (product->selling_price + price_adjustment)
|
||||
$defaultCurrency = $this->getDefaultCurrencyCode();
|
||||
|
||||
return [
|
||||
'id' => $option->id,
|
||||
@@ -56,9 +78,22 @@ abstract class BaseOrderItemResource extends BaseApiResource
|
||||
'option_name_localized' => $option->getLocalizedOptionName(),
|
||||
'option_values' => $option->option_values,
|
||||
'option_values_localized' => $option->getLocalizedOptionValues(),
|
||||
'selling_price' => $sellingPrice,
|
||||
'selling_price_formatted' => $this->formatCurrencyPrice($sellingPrice, $this->getDefaultCurrencyCode()),
|
||||
|
||||
// 정가 (U5·U4② — ProductOptionResource 와 동일 키. 베이스에 추가 → Cart·Checkout 양쪽 자동)
|
||||
'list_price' => $this->roundToCurrency($listPrice, $defaultCurrency),
|
||||
'list_price_formatted' => $this->formatCurrencyPrice($listPrice, $defaultCurrency),
|
||||
'multi_currency_list_price' => $this->buildMultiCurrencyPrices($listPrice),
|
||||
|
||||
// 판매가 (기존)
|
||||
'selling_price' => $this->roundToCurrency($sellingPrice, $defaultCurrency),
|
||||
'selling_price_formatted' => $this->formatCurrencyPrice($sellingPrice, $defaultCurrency),
|
||||
'multi_currency_selling_price' => $this->buildMultiCurrencyPrices($sellingPrice),
|
||||
|
||||
// 할인율 (U5·U4② — 옵션 레벨 정가 대비. list_price<=0 가드)
|
||||
'discount_rate' => $listPrice > 0
|
||||
? round((1 - $sellingPrice / $listPrice) * 100, 1)
|
||||
: 0,
|
||||
|
||||
'stock_quantity' => $option->stock_quantity,
|
||||
'is_active' => $option->is_active,
|
||||
];
|
||||
@@ -67,8 +102,8 @@ abstract class BaseOrderItemResource extends BaseApiResource
|
||||
/**
|
||||
* 소계 정보를 배열로 변환
|
||||
*
|
||||
* @param int $sellingPrice 판매가
|
||||
* @param int $quantity 수량
|
||||
* @param int $sellingPrice 판매가
|
||||
* @param int $quantity 수량
|
||||
* @return array 소계 정보 배열
|
||||
*/
|
||||
protected function formatSubtotalInfo(int $sellingPrice, int $quantity): array
|
||||
@@ -76,9 +111,73 @@ abstract class BaseOrderItemResource extends BaseApiResource
|
||||
$subtotal = $sellingPrice * $quantity;
|
||||
|
||||
return [
|
||||
'subtotal' => $subtotal,
|
||||
'subtotal' => $this->roundToBaseCurrency($subtotal),
|
||||
'subtotal_formatted' => $this->formatCurrencyPrice($subtotal, $this->getDefaultCurrencyCode()),
|
||||
'multi_currency_subtotal' => $this->buildMultiCurrencyPrices($subtotal),
|
||||
];
|
||||
}
|
||||
|
||||
/**
|
||||
* 선택된 추가옵션(value_id)을 표시용으로 해석합니다.
|
||||
*
|
||||
* 저장된 selection(value_id) 을 로드된 상품의 활성 선택지와 매칭하여
|
||||
* 그룹명·선택지명·추가금을 노출합니다. 가격은 항상 서버 DB 값을 사용합니다(클라 신뢰 금지).
|
||||
* Cart/Checkout 양 리소스가 동일 표시 계약을 공유합니다.
|
||||
*
|
||||
* @param Product|null $product 로드된 상품 모델 (additionalOptions.values eager-load 필요)
|
||||
* @param array<int, array{additional_option_id?: int, value_id?: int, custom_text?: string}> $selections 선택된 추가옵션 배열
|
||||
* @return array<int, array{additional_option_id: int, value_id: int, group_name: string, name: string, price_adjustment: int, custom_text: string}>
|
||||
*/
|
||||
protected function resolveAdditionalOptions(?Product $product, array $selections): array
|
||||
{
|
||||
if (empty($selections) || ! $product || ! $product->relationLoaded('additionalOptions')) {
|
||||
return [];
|
||||
}
|
||||
|
||||
// value_id => value, group_id => group 매핑 구성
|
||||
$valueMap = [];
|
||||
$groupMap = [];
|
||||
foreach ($product->additionalOptions as $group) {
|
||||
$groupMap[$group->id] = $group;
|
||||
if ($group->relationLoaded('values')) {
|
||||
foreach ($group->values as $value) {
|
||||
$valueMap[$value->id] = $value;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
$resolved = [];
|
||||
foreach ($selections as $selection) {
|
||||
$valueId = (int) ($selection['value_id'] ?? 0);
|
||||
$value = $valueMap[$valueId] ?? null;
|
||||
|
||||
if (! $value || ! $value->is_active) {
|
||||
continue;
|
||||
}
|
||||
|
||||
$group = $groupMap[$value->additional_option_id] ?? null;
|
||||
|
||||
// 직접입력 텍스트: allow_custom_text 선택지에 한해 선택값에서 추출 (E3)
|
||||
$customText = '';
|
||||
if ($value->allow_custom_text) {
|
||||
$customText = trim((string) ($selection['custom_text'] ?? ''));
|
||||
}
|
||||
|
||||
$priceAdjustment = $value->getPriceAdjustment();
|
||||
|
||||
$resolved[] = [
|
||||
'additional_option_id' => (int) $value->additional_option_id,
|
||||
'value_id' => (int) $value->id,
|
||||
'group_name' => $group ? $group->getLocalizedName() : '',
|
||||
'name' => $value->getLocalizedName(),
|
||||
'price_adjustment' => $this->roundToBaseCurrency($priceAdjustment),
|
||||
// 추가금 표시 문자열 — 통화 기호를 하드코딩하지 않고 기본 통화 기호로 포맷 (레이아웃의 '+N원' 하드코딩 대체)
|
||||
'price_adjustment_formatted' => ($priceAdjustment >= 0 ? '+' : '-')
|
||||
.$this->formatCurrencyPrice(abs($priceAdjustment), $this->getDefaultCurrencyCode()),
|
||||
'custom_text' => $customText,
|
||||
];
|
||||
}
|
||||
|
||||
return $resolved;
|
||||
}
|
||||
}
|
||||
@@ -3,6 +3,9 @@
|
||||
namespace Modules\Sirsoft\Ecommerce\Http\Resources;
|
||||
|
||||
use Illuminate\Http\Request;
|
||||
use Modules\Sirsoft\Ecommerce\Enums\ProductSalesStatus;
|
||||
use Modules\Sirsoft\Ecommerce\Http\Middleware\ResolveShippingCountry;
|
||||
use Modules\Sirsoft\Ecommerce\Models\Product;
|
||||
|
||||
/**
|
||||
* 장바구니 아이템 리소스
|
||||
@@ -14,7 +17,7 @@ class CartItemResource extends BaseOrderItemResource
|
||||
/**
|
||||
* 리소스를 배열로 변환
|
||||
*
|
||||
* @param Request $request 요청
|
||||
* @param Request $request 요청
|
||||
* @return array 장바구니 아이템 정보
|
||||
*/
|
||||
public function toArray(Request $request): array
|
||||
@@ -22,24 +25,40 @@ class CartItemResource extends BaseOrderItemResource
|
||||
$product = $this->relationLoaded('product') ? $this->product : null;
|
||||
$productOption = $this->relationLoaded('productOption') ? $this->productOption : null;
|
||||
|
||||
$additionalOptions = $this->resolveAdditionalOptions($product, $this->additional_option_selections ?? []);
|
||||
$additionalOptionsUnitTotal = array_sum(array_column($additionalOptions, 'price_adjustment'));
|
||||
|
||||
$result = [
|
||||
'id' => $this->id,
|
||||
'product_id' => $this->product_id,
|
||||
'product_option_id' => $this->product_option_id,
|
||||
'quantity' => $this->quantity,
|
||||
'created_at' => $this->created_at?->toIso8601String(),
|
||||
'updated_at' => $this->updated_at?->toIso8601String(),
|
||||
'additional_options' => $additionalOptions,
|
||||
'additional_options_total' => $additionalOptionsUnitTotal,
|
||||
'created_at' => $this->formatDateTimeStringForUser($this->created_at),
|
||||
'updated_at' => $this->formatDateTimeStringForUser($this->updated_at),
|
||||
|
||||
// 상품 정보
|
||||
'product' => $product ? $this->formatProductInfo($product) : null,
|
||||
|
||||
// 옵션 정보
|
||||
'product_option' => $productOption ? $this->formatOptionInfo($productOption) : null,
|
||||
|
||||
// 판매 가능 여부 플래그 (U13②/U4 — 비정상 항목은 합계 제외되며 프론트가 구분 표시)
|
||||
'available' => $product ? $product->isPurchasable() : false,
|
||||
'unavailable_reason' => $product ? $this->resolveUnavailableReason($product) : null,
|
||||
|
||||
// 선택된 배송국가로 배송 가능한지 (D1 — layer 1, 카트 표시/주문 차단 플래그)
|
||||
'is_shippable_to_selected_country' => $product
|
||||
? $this->isShippableToSelectedCountry($product)
|
||||
: false,
|
||||
'selected_shipping_country' => ResolveShippingCountry::getCountry(),
|
||||
];
|
||||
|
||||
// 계산된 값 (옵션이 로드된 경우에만)
|
||||
// 안B: 표시 소계 = (원옵션가 + 추가옵션 단위 합계) × 수량 (D6)
|
||||
if ($productOption) {
|
||||
$sellingPrice = $productOption->getSellingPrice();
|
||||
$sellingPrice = $productOption->getSellingPrice() + $additionalOptionsUnitTotal;
|
||||
$subtotalInfo = $this->formatSubtotalInfo($sellingPrice, $this->quantity);
|
||||
|
||||
$result['subtotal'] = $subtotalInfo['subtotal'];
|
||||
@@ -49,4 +68,26 @@ class CartItemResource extends BaseOrderItemResource
|
||||
|
||||
return $result;
|
||||
}
|
||||
|
||||
/**
|
||||
* 구매 불가 사유를 반환합니다.
|
||||
*
|
||||
* 판매중이 아니면 판매상태 값(suspended/sold_out/coming_soon), 판매중이지만
|
||||
* 전시중지(hidden)면 전시상태 값(hidden), 구매 가능하면 null 을 반환합니다.
|
||||
*
|
||||
* @param Product $product 상품 모델
|
||||
* @return string|null 구매 불가 사유 (구매 가능 시 null)
|
||||
*/
|
||||
protected function resolveUnavailableReason($product): ?string
|
||||
{
|
||||
if ($product->isPurchasable()) {
|
||||
return null;
|
||||
}
|
||||
|
||||
if ($product->sales_status !== ProductSalesStatus::ON_SALE) {
|
||||
return $product->sales_status->value;
|
||||
}
|
||||
|
||||
return $product->display_status->value;
|
||||
}
|
||||
}
|
||||
@@ -22,24 +22,53 @@ class CheckoutItemResource extends BaseOrderItemResource
|
||||
* calculationItems가 제공되면 금액 정보를 병합합니다.
|
||||
* productCoupons가 제공되면 각 상품에 적용 가능한 쿠폰 목록을 포함합니다.
|
||||
*
|
||||
* @param array $items TempOrder의 items 배열
|
||||
* @param array $calculationItems 계산 결과의 items 배열 (product_option_id로 매칭)
|
||||
* @param array $productCoupons 상품별 적용 가능한 쿠폰 배열 (product_id => coupons)
|
||||
* @param array $items TempOrder의 items 배열
|
||||
* @param array $calculationItems 계산 결과의 items 배열 (product_option_id로 매칭)
|
||||
* @param array $productCoupons 상품별 적용 가능한 쿠폰 배열 (product_id => coupons)
|
||||
* @param array $selectedItemCoupons 현재 선택된 상품 쿠폰 (product_option_id => [발급ID, ...]) — per_user_limit 중복 비활성화 계산용
|
||||
* @return array 변환된 아이템 배열
|
||||
*/
|
||||
public static function collectionFromArray(array $items, array $calculationItems = [], array $productCoupons = []): array
|
||||
public static function collectionFromArray(array $items, array $calculationItems = [], array $productCoupons = [], array $selectedItemCoupons = []): array
|
||||
{
|
||||
if (empty($items)) {
|
||||
return [];
|
||||
}
|
||||
|
||||
// 발급ID => coupon 메타(coupon_id, per_user_limit) 맵 — 라인 간 per_user_limit 중복 판정용
|
||||
$couponMetaByIssueId = [];
|
||||
foreach ($productCoupons as $coupons) {
|
||||
foreach ($coupons as $coupon) {
|
||||
$issueId = $coupon['id'] ?? null;
|
||||
if ($issueId !== null) {
|
||||
$couponMetaByIssueId[(int) $issueId] = [
|
||||
'coupon_id' => (int) ($coupon['coupon_id'] ?? 0),
|
||||
'per_user_limit' => (int) ($coupon['per_user_limit'] ?? 0),
|
||||
];
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// 현재 선택을 coupon_id 별로, 어느 옵션 라인에서 몇 건 선택됐는지 집계
|
||||
// [coupon_id => [optionId => 선택수]]
|
||||
$selectionByCouponId = [];
|
||||
foreach ($selectedItemCoupons as $optionId => $issueIds) {
|
||||
foreach ((array) $issueIds as $issueId) {
|
||||
$meta = $couponMetaByIssueId[(int) $issueId] ?? null;
|
||||
if ($meta === null || $meta['coupon_id'] === 0) {
|
||||
continue;
|
||||
}
|
||||
$cid = $meta['coupon_id'];
|
||||
$selectionByCouponId[$cid][(int) $optionId] = ($selectionByCouponId[$cid][(int) $optionId] ?? 0) + 1;
|
||||
}
|
||||
}
|
||||
|
||||
// ID 추출
|
||||
$productIds = array_unique(array_column($items, 'product_id'));
|
||||
$optionIds = array_unique(array_column($items, 'product_option_id'));
|
||||
|
||||
// 한번에 조회 (with images for thumbnail)
|
||||
// 한번에 조회 (with images for thumbnail, 추가옵션 표시용 선택지, 배송정책 국가설정 포함)
|
||||
$products = Product::whereIn('id', $productIds)
|
||||
->with('images')
|
||||
->with(['images', 'additionalOptions.values', 'shippingPolicy.countrySettings'])
|
||||
->get()
|
||||
->keyBy('id');
|
||||
|
||||
@@ -63,6 +92,30 @@ class CheckoutItemResource extends BaseOrderItemResource
|
||||
$option = $options->get($item['product_option_id']);
|
||||
$calculation = $calculationByOptionId[$item['product_option_id']] ?? null;
|
||||
$coupons = $productCoupons[$item['product_id']] ?? [];
|
||||
$currentOptionId = (int) ($item['product_option_id'] ?? 0);
|
||||
|
||||
// 이 라인에서 비활성화할 쿠폰 발급ID 목록 (per_user_limit 중복 — U13b/MP06)
|
||||
// 다른 옵션 라인에서 이미 선택된 per_user_limit 쿠폰과 같은 coupon_id 이고,
|
||||
// (다른 라인 선택수) >= per_user_limit 이면 이 라인에서 더 적용할 수 없다.
|
||||
$disabledCouponIds = [];
|
||||
foreach ($coupons as $coupon) {
|
||||
$limit = (int) ($coupon['per_user_limit'] ?? 0);
|
||||
if ($limit <= 0) {
|
||||
continue; // 무제한 쿠폰은 비활성화 대상 아님
|
||||
}
|
||||
$cid = (int) ($coupon['coupon_id'] ?? 0);
|
||||
$byOption = $selectionByCouponId[$cid] ?? [];
|
||||
// 이 라인을 제외한 다른 라인들의 선택 누적
|
||||
$otherLinesUsed = 0;
|
||||
foreach ($byOption as $optId => $cnt) {
|
||||
if ($optId !== $currentOptionId) {
|
||||
$otherLinesUsed += $cnt;
|
||||
}
|
||||
}
|
||||
if ($otherLinesUsed >= $limit) {
|
||||
$disabledCouponIds[] = (int) $coupon['id'];
|
||||
}
|
||||
}
|
||||
|
||||
$resource = new static([
|
||||
'item' => $item,
|
||||
@@ -70,6 +123,7 @@ class CheckoutItemResource extends BaseOrderItemResource
|
||||
'product_option' => $option,
|
||||
'calculation' => $calculation,
|
||||
'available_coupons' => $coupons,
|
||||
'disabled_coupon_ids' => $disabledCouponIds,
|
||||
]);
|
||||
|
||||
$result[] = $resource->toArray(request());
|
||||
@@ -81,7 +135,7 @@ class CheckoutItemResource extends BaseOrderItemResource
|
||||
/**
|
||||
* 리소스를 배열로 변환
|
||||
*
|
||||
* @param Request $request 요청
|
||||
* @param Request $request 요청
|
||||
* @return array 체크아웃 아이템 정보
|
||||
*/
|
||||
public function toArray(Request $request): array
|
||||
@@ -92,22 +146,34 @@ class CheckoutItemResource extends BaseOrderItemResource
|
||||
$calculation = $this->resource['calculation'] ?? null;
|
||||
$availableCoupons = $this->resource['available_coupons'] ?? [];
|
||||
|
||||
// 선택된 추가옵션 해석 (장바구니와 동일 표시 계약 — group_name/name/price_adjustment)
|
||||
$additionalOptions = $this->resolveAdditionalOptions($product, $item['additional_option_selections'] ?? []);
|
||||
$additionalOptionsUnitTotal = array_sum(array_column($additionalOptions, 'price_adjustment'));
|
||||
|
||||
$result = [
|
||||
'id' => $item['cart_id'] ?? null,
|
||||
'product_id' => $item['product_id'] ?? null,
|
||||
'product_option_id' => $item['product_option_id'] ?? null,
|
||||
'quantity' => $item['quantity'] ?? 0,
|
||||
'additional_options' => $additionalOptions,
|
||||
'additional_options_total' => $additionalOptionsUnitTotal,
|
||||
|
||||
// 상품 정보
|
||||
'product' => $product ? $this->formatProductInfo($product) : null,
|
||||
|
||||
// 옵션 정보
|
||||
'product_option' => $productOption ? $this->formatOptionInfo($productOption) : null,
|
||||
|
||||
// 선택된 배송국가로 배송 가능한지 (D1 — layer 2, 체크아웃 표시/주문하기 차단 플래그)
|
||||
'is_shippable_to_selected_country' => $product
|
||||
? $this->isShippableToSelectedCountry($product)
|
||||
: false,
|
||||
];
|
||||
|
||||
// 계산된 값 (옵션이 있는 경우에만)
|
||||
// 안B: 표시 소계 = (원옵션가 + 추가옵션 단위 합계) × 수량 (D6) — 장바구니와 동일
|
||||
if ($productOption) {
|
||||
$sellingPrice = $productOption->getSellingPrice();
|
||||
$sellingPrice = $productOption->getSellingPrice() + $additionalOptionsUnitTotal;
|
||||
$quantity = $item['quantity'] ?? 0;
|
||||
$subtotalInfo = $this->formatSubtotalInfo($sellingPrice, $quantity);
|
||||
|
||||
@@ -124,39 +190,42 @@ class CheckoutItemResource extends BaseOrderItemResource
|
||||
// 상품별 적용 가능한 쿠폰 목록
|
||||
$result['available_coupons'] = $availableCoupons;
|
||||
|
||||
// 이 라인에서 비활성화할 쿠폰 발급ID 목록 (per_user_limit 다른 라인 중복 — U13b/MP06)
|
||||
$result['disabled_coupon_ids'] = $this->resource['disabled_coupon_ids'] ?? [];
|
||||
|
||||
return $result;
|
||||
}
|
||||
|
||||
/**
|
||||
* calculation 데이터에서 금액 정보를 포맷
|
||||
*
|
||||
* @param array $calculation 계산 결과 배열
|
||||
* @param array $calculation 계산 결과 배열
|
||||
* @return array 포맷된 금액 정보
|
||||
*/
|
||||
protected function formatCalculationInfo(array $calculation): array
|
||||
{
|
||||
$result = [
|
||||
// 단가 정보
|
||||
'unit_price' => $calculation['unit_price'] ?? 0,
|
||||
'unit_price' => $this->roundToBaseCurrency($calculation['unit_price'] ?? 0),
|
||||
'unit_price_formatted' => $this->formatCurrencyPrice($calculation['unit_price'] ?? 0, $this->getDefaultCurrencyCode()),
|
||||
|
||||
// 할인 정보
|
||||
'product_coupon_discount_amount' => $calculation['product_coupon_discount_amount'] ?? 0,
|
||||
'product_coupon_discount_amount' => $this->roundToBaseCurrency($calculation['product_coupon_discount_amount'] ?? 0),
|
||||
'product_coupon_discount_formatted' => $this->formatCurrencyPrice($calculation['product_coupon_discount_amount'] ?? 0, $this->getDefaultCurrencyCode()),
|
||||
'code_discount_amount' => $calculation['code_discount_amount'] ?? 0,
|
||||
'code_discount_amount' => $this->roundToBaseCurrency($calculation['code_discount_amount'] ?? 0),
|
||||
'code_discount_formatted' => $this->formatCurrencyPrice($calculation['code_discount_amount'] ?? 0, $this->getDefaultCurrencyCode()),
|
||||
'order_coupon_discount_share' => $calculation['order_coupon_discount_share'] ?? 0,
|
||||
'order_coupon_discount_share' => $this->roundToBaseCurrency($calculation['order_coupon_discount_share'] ?? 0),
|
||||
'order_coupon_discount_share_formatted' => $this->formatCurrencyPrice($calculation['order_coupon_discount_share'] ?? 0, $this->getDefaultCurrencyCode()),
|
||||
'total_discount' => $calculation['total_discount'] ?? 0,
|
||||
'total_discount' => $this->roundToBaseCurrency($calculation['total_discount'] ?? 0),
|
||||
'total_discount_formatted' => $this->formatCurrencyPrice($calculation['total_discount'] ?? 0, $this->getDefaultCurrencyCode()),
|
||||
|
||||
// 마일리지 정보
|
||||
'points_used_share' => $calculation['points_used_share'] ?? 0,
|
||||
'points_used_share' => $this->roundToBaseCurrency($calculation['points_used_share'] ?? 0),
|
||||
'points_used_share_formatted' => $this->formatCurrencyPrice($calculation['points_used_share'] ?? 0, $this->getDefaultCurrencyCode()),
|
||||
'points_earning' => $calculation['points_earning'] ?? 0,
|
||||
|
||||
// 최종 금액
|
||||
'final_amount' => $calculation['final_amount'] ?? 0,
|
||||
'final_amount' => $this->roundToBaseCurrency($calculation['final_amount'] ?? 0),
|
||||
'final_amount_formatted' => $this->formatCurrencyPrice($calculation['final_amount'] ?? 0, $this->getDefaultCurrencyCode()),
|
||||
];
|
||||
|
||||
@@ -180,8 +249,8 @@ class CheckoutItemResource extends BaseOrderItemResource
|
||||
* multi_currency 구조: ['KRW' => ['final_amount' => 94000, 'final_amount_formatted' => '94,000원'], ...]
|
||||
* 결과 구조: ['KRW' => ['amount' => 94000, 'formatted' => '94,000원'], ...]
|
||||
*
|
||||
* @param array $multiCurrency 다중 통화 데이터
|
||||
* @param string $field 추출할 필드명
|
||||
* @param array $multiCurrency 다중 통화 데이터
|
||||
* @param string $field 추출할 필드명
|
||||
* @return array 통화코드별 금액/포맷 배열
|
||||
*/
|
||||
protected function extractMultiCurrencyField(array $multiCurrency, string $field): array
|
||||
|
||||
+37
@@ -0,0 +1,37 @@
|
||||
<?php
|
||||
|
||||
namespace Modules\Sirsoft\Ecommerce\Http\Resources\Concerns;
|
||||
|
||||
/**
|
||||
* 국가 코드 → 다국어 국가명 변환 트레이트 (MP08 후속)
|
||||
*
|
||||
* 주문 목록/상세/주소 리소스가 공유한다(OrderListResource 에서 추출). config('countries.localized_names')
|
||||
* 의 로케일별 국가명 매핑을 사용한다.
|
||||
*/
|
||||
trait LocalizesCountryName
|
||||
{
|
||||
/**
|
||||
* 국가 코드를 다국어 국가명 객체로 변환합니다.
|
||||
*
|
||||
* @param string|null $countryCode ISO alpha-2 국가 코드
|
||||
* @return array<string, string>|null 다국어 객체 (예: {ko: '한국', en: 'South Korea'}), 미상이면 null
|
||||
*/
|
||||
protected function getCountryLocalizedName(?string $countryCode): ?array
|
||||
{
|
||||
if (! $countryCode) {
|
||||
return null;
|
||||
}
|
||||
|
||||
$countryCode = strtoupper($countryCode);
|
||||
$localizedNames = config('countries.localized_names', []);
|
||||
|
||||
$result = [];
|
||||
foreach ($localizedNames as $locale => $names) {
|
||||
if (isset($names[$countryCode])) {
|
||||
$result[$locale] = $names[$countryCode];
|
||||
}
|
||||
}
|
||||
|
||||
return ! empty($result) ? $result : null;
|
||||
}
|
||||
}
|
||||
@@ -3,16 +3,21 @@
|
||||
namespace Modules\Sirsoft\Ecommerce\Http\Resources;
|
||||
|
||||
use App\Http\Resources\BaseApiResource;
|
||||
use Illuminate\Http\Request;
|
||||
use Modules\Sirsoft\Ecommerce\Http\Resources\Traits\HasMultiCurrencyPrices;
|
||||
|
||||
/**
|
||||
* 쿠폰 발급 내역 API 리소스
|
||||
*/
|
||||
class CouponIssueResource extends BaseApiResource
|
||||
{
|
||||
use HasMultiCurrencyPrices;
|
||||
|
||||
/**
|
||||
* Transform the resource into an array.
|
||||
* 리소스를 배열로 변환합니다.
|
||||
*
|
||||
* @param \Illuminate\Http\Request $request
|
||||
* @param Request $request 요청
|
||||
* @return array<string, mixed> 쿠폰 발급 내역 리소스 배열
|
||||
*/
|
||||
public function toArray($request): array
|
||||
{
|
||||
@@ -34,11 +39,14 @@ class CouponIssueResource extends BaseApiResource
|
||||
|
||||
// 사용 정보
|
||||
'order_id' => $this->order_id,
|
||||
'discount_amount' => $this->discount_amount,
|
||||
'order_number' => $this->whenLoaded('order', fn () => $this->order?->order_number),
|
||||
'discount_amount' => $this->roundToBaseCurrency($this->discount_amount),
|
||||
|
||||
// 상태 확인
|
||||
'is_used' => $this->status?->value === 'used',
|
||||
'is_expired' => $this->isExpired(),
|
||||
'is_usable' => $this->isUsable(),
|
||||
'is_cancellable' => $this->status?->value === 'available' && ! $this->isExpired(),
|
||||
|
||||
// 관계
|
||||
'user_name' => $this->whenLoaded('user', fn () => $this->user->name),
|
||||
|
||||
@@ -3,16 +3,22 @@
|
||||
namespace Modules\Sirsoft\Ecommerce\Http\Resources;
|
||||
|
||||
use App\Http\Resources\BaseApiResource;
|
||||
use Illuminate\Http\Request;
|
||||
use Modules\Sirsoft\Ecommerce\Enums\CouponDiscountType;
|
||||
use Modules\Sirsoft\Ecommerce\Http\Resources\Traits\HasMultiCurrencyPrices;
|
||||
|
||||
/**
|
||||
* 쿠폰 API 리소스
|
||||
*/
|
||||
class CouponResource extends BaseApiResource
|
||||
{
|
||||
use HasMultiCurrencyPrices;
|
||||
|
||||
/**
|
||||
* Transform the resource into an array.
|
||||
*
|
||||
* @param \Illuminate\Http\Request $request
|
||||
* @param Request $request
|
||||
* @return array<string, mixed> 쿠폰 리소스 배열 (다통화 환산 필드 포함)
|
||||
*/
|
||||
public function toArray($request): array
|
||||
{
|
||||
@@ -31,11 +37,27 @@ class CouponResource extends BaseApiResource
|
||||
// 할인 정보
|
||||
'discount_type' => $this->discount_type?->value,
|
||||
'discount_type_label' => $this->discount_type?->label(),
|
||||
'discount_value' => $this->discount_value,
|
||||
'discount_max_amount' => $this->discount_max_amount,
|
||||
'min_order_amount' => $this->min_order_amount,
|
||||
// 정액 할인은 통화 금액이므로 기본 통화 자릿수로 정규화 (정률은 % 값이라 그대로)
|
||||
'discount_value' => $this->discount_type === CouponDiscountType::FIXED
|
||||
? $this->roundToBaseCurrency($this->discount_value)
|
||||
: $this->discount_value,
|
||||
'discount_max_amount' => $this->discount_max_amount !== null
|
||||
? $this->roundToBaseCurrency($this->discount_max_amount) : null,
|
||||
'min_order_amount' => $this->min_order_amount !== null
|
||||
? $this->roundToBaseCurrency($this->min_order_amount) : null,
|
||||
'benefit_formatted' => $this->benefit_formatted,
|
||||
|
||||
// 다통화 환산 (A1-④) — 정액(fixed)만 환산, 정률(rate)은 통화 무관 → null
|
||||
'multi_currency_discount_value' => $this->discount_type === CouponDiscountType::FIXED
|
||||
? $this->buildMultiCurrencyPrices($this->discount_value ?? 0)
|
||||
: null,
|
||||
'multi_currency_min_order_amount' => ($this->min_order_amount ?? 0) > 0
|
||||
? $this->buildMultiCurrencyPrices($this->min_order_amount)
|
||||
: null,
|
||||
'multi_currency_discount_max_amount' => ($this->discount_max_amount ?? 0) > 0
|
||||
? $this->buildMultiCurrencyPrices($this->discount_max_amount)
|
||||
: null,
|
||||
|
||||
// 발급 설정
|
||||
'issue_method' => $this->issue_method?->value,
|
||||
'issue_method_label' => $this->issue_method?->label(),
|
||||
@@ -97,7 +119,7 @@ class CouponResource extends BaseApiResource
|
||||
'product_code' => $product->product_code,
|
||||
'name' => $product->getLocalizedName(),
|
||||
'name_localized' => $product->getLocalizedName(),
|
||||
'selling_price_formatted' => number_format($product->selling_price ?? 0).'원',
|
||||
'selling_price_formatted' => $this->formatBaseCurrency($product->selling_price ?? 0),
|
||||
]);
|
||||
}),
|
||||
'excluded_products' => $this->whenLoaded('excludedProducts', function () {
|
||||
@@ -106,7 +128,7 @@ class CouponResource extends BaseApiResource
|
||||
'product_code' => $product->product_code,
|
||||
'name' => $product->getLocalizedName(),
|
||||
'name_localized' => $product->getLocalizedName(),
|
||||
'selling_price_formatted' => number_format($product->selling_price ?? 0).'원',
|
||||
'selling_price_formatted' => $this->formatBaseCurrency($product->selling_price ?? 0),
|
||||
]);
|
||||
}),
|
||||
'included_categories' => $this->whenLoaded('includedCategories', function () {
|
||||
|
||||
+7
-5
@@ -6,6 +6,7 @@ use App\Http\Resources\BaseApiCollection;
|
||||
use App\Http\Resources\Traits\HasAbilityCheck;
|
||||
use Illuminate\Http\Request;
|
||||
use Illuminate\Pagination\LengthAwarePaginator;
|
||||
use Modules\Sirsoft\Ecommerce\Http\Resources\Traits\HasMultiCurrencyPrices;
|
||||
|
||||
/**
|
||||
* 추가배송비 템플릿 컬렉션 리소스
|
||||
@@ -15,6 +16,7 @@ use Illuminate\Pagination\LengthAwarePaginator;
|
||||
class ExtraFeeTemplateCollection extends BaseApiCollection
|
||||
{
|
||||
use HasAbilityCheck;
|
||||
use HasMultiCurrencyPrices;
|
||||
|
||||
/**
|
||||
* 컬렉션 레벨 능력(can_*) 매핑을 반환합니다.
|
||||
@@ -33,7 +35,7 @@ class ExtraFeeTemplateCollection extends BaseApiCollection
|
||||
/**
|
||||
* 컬렉션을 배열로 변환합니다.
|
||||
*
|
||||
* @param Request $request HTTP 요청 객체
|
||||
* @param Request $request HTTP 요청 객체
|
||||
* @return array<int|string, mixed> 변환된 컬렉션 배열
|
||||
*/
|
||||
public function toArray(Request $request): array
|
||||
@@ -63,7 +65,7 @@ class ExtraFeeTemplateCollection extends BaseApiCollection
|
||||
/**
|
||||
* 통계가 포함된 형태의 배열을 반환합니다.
|
||||
*
|
||||
* @param array $statistics 통계 데이터 배열
|
||||
* @param array $statistics 통계 데이터 배열
|
||||
* @return array<string, mixed> 통계 정보가 포함된 컬렉션
|
||||
*/
|
||||
public function withStatistics(array $statistics = []): array
|
||||
@@ -119,9 +121,9 @@ class ExtraFeeTemplateCollection extends BaseApiCollection
|
||||
return [
|
||||
'region' => $region ?: '미지정',
|
||||
'count' => $items->count(),
|
||||
'min_fee' => (float) $items->min('fee'),
|
||||
'max_fee' => (float) $items->max('fee'),
|
||||
'avg_fee' => round($items->avg('fee'), 2),
|
||||
'min_fee' => $this->roundToBaseCurrency($items->min('fee')),
|
||||
'max_fee' => $this->roundToBaseCurrency($items->max('fee')),
|
||||
'avg_fee' => $this->roundToBaseCurrency($items->avg('fee')),
|
||||
];
|
||||
})
|
||||
->values()
|
||||
|
||||
@@ -4,17 +4,20 @@ namespace Modules\Sirsoft\Ecommerce\Http\Resources;
|
||||
|
||||
use App\Http\Resources\BaseApiResource;
|
||||
use Illuminate\Http\Request;
|
||||
use Modules\Sirsoft\Ecommerce\Http\Resources\Traits\HasMultiCurrencyPrices;
|
||||
|
||||
/**
|
||||
* 추가배송비 템플릿 리소스
|
||||
*/
|
||||
class ExtraFeeTemplateResource extends BaseApiResource
|
||||
{
|
||||
use HasMultiCurrencyPrices;
|
||||
|
||||
/**
|
||||
* 리소스를 배열로 변환
|
||||
* 리소스를 배열로 변환합니다.
|
||||
*
|
||||
* @param Request $request 요청
|
||||
* @return array
|
||||
* @param Request $request 요청
|
||||
* @return array<string, mixed> 추가배송비 템플릿 리소스 배열
|
||||
*/
|
||||
public function toArray(Request $request): array
|
||||
{
|
||||
@@ -23,8 +26,8 @@ class ExtraFeeTemplateResource extends BaseApiResource
|
||||
|
||||
// 우편번호 및 배송비
|
||||
'zipcode' => $this->zipcode,
|
||||
'fee' => (float) $this->fee,
|
||||
'fee_formatted' => number_format($this->fee).'원',
|
||||
'fee' => $this->roundToBaseCurrency($this->fee),
|
||||
'fee_formatted' => $this->formatBaseCurrency($this->fee),
|
||||
|
||||
// 지역 정보
|
||||
'region' => $this->region,
|
||||
|
||||
@@ -0,0 +1,148 @@
|
||||
<?php
|
||||
|
||||
namespace Modules\Sirsoft\Ecommerce\Http\Resources;
|
||||
|
||||
use App\Http\Resources\BaseApiResource;
|
||||
use Illuminate\Http\Request;
|
||||
use Modules\Sirsoft\Ecommerce\Http\Resources\Traits\HasMultiCurrencyPrices;
|
||||
|
||||
/**
|
||||
* 비회원 주문 상세 리소스
|
||||
*
|
||||
* 조회 인증 토큰으로 보호되는 비회원 주문 상세 응답 전용 리소스.
|
||||
* 회원용 OrderResource 와 달리 다음을 노출하지 않는다.
|
||||
* - admin_memo / customer_memo (관리자·내부 메모)
|
||||
* - user / user_id / user_login_id (회원 정보)
|
||||
* - promotions_applied_snapshot / shipping_policy_applied_snapshot (내부 계산 스냅샷)
|
||||
* - 회원 권한 메타(resourceMeta/abilityMap)
|
||||
*
|
||||
* 허용 액션(abilities)은 회원 권한이 아니라 주문 상태로만 판정한다.
|
||||
*/
|
||||
class GuestOrderResource extends BaseApiResource
|
||||
{
|
||||
use HasMultiCurrencyPrices;
|
||||
|
||||
/**
|
||||
* 리소스를 배열로 변환
|
||||
*
|
||||
* @param Request $request 요청
|
||||
* @return array 비회원 주문 상세 응답 배열
|
||||
*/
|
||||
public function toArray(Request $request): array
|
||||
{
|
||||
// 주문 시점 기준 통화 — 과거 주문의 *_formatted 는 설정 변경과 무관하게 이 통화로 고정 표기한다.
|
||||
$orderCurrency = $this->resolveOrderBaseCurrencyCode($this->resource);
|
||||
|
||||
return [
|
||||
'order_number' => $this->order_number,
|
||||
'order_status' => $this->order_status,
|
||||
'order_status_label' => $this->order_status ? $this->order_status->label() : null,
|
||||
'order_status_variant' => $this->order_status ? $this->order_status->variant() : null,
|
||||
// 부분취소 파생 플래그 — 일부 옵션만 취소된 주문(별도 order_status 아님). 보조 뱃지 표시용.
|
||||
'is_partially_cancelled' => $this->whenLoaded('options', fn () => $this->resource->isPartiallyCancelled(), false),
|
||||
|
||||
// 금액
|
||||
'subtotal_amount' => $this->roundToOrderCurrency($this->subtotal_amount, $orderCurrency),
|
||||
'subtotal_amount_formatted' => $this->formatOrderCurrency($this->subtotal_amount, $orderCurrency),
|
||||
'total_discount_amount' => $this->roundToOrderCurrency($this->total_discount_amount, $orderCurrency),
|
||||
'total_discount_amount_formatted' => $this->formatOrderCurrency($this->total_discount_amount, $orderCurrency),
|
||||
'total_shipping_amount' => $this->roundToOrderCurrency($this->total_shipping_amount, $orderCurrency),
|
||||
'total_shipping_amount_formatted' => $this->formatOrderCurrency($this->total_shipping_amount, $orderCurrency),
|
||||
'total_amount' => $this->roundToOrderCurrency($this->total_amount, $orderCurrency),
|
||||
'total_amount_formatted' => $this->formatOrderCurrency($this->total_amount, $orderCurrency),
|
||||
'total_paid_amount' => $this->roundToOrderCurrency($this->total_paid_amount, $orderCurrency),
|
||||
'total_paid_amount_formatted' => $this->formatOrderCurrency($this->total_paid_amount, $orderCurrency),
|
||||
'total_cancelled_amount' => $this->roundToOrderCurrency($this->total_cancelled_amount, $orderCurrency),
|
||||
'total_cancelled_amount_formatted' => $this->formatOrderCurrency($this->total_cancelled_amount, $orderCurrency),
|
||||
'total_refunded_amount' => $this->roundToOrderCurrency($this->total_refunded_amount, $orderCurrency),
|
||||
'total_refunded_amount_formatted' => $this->formatOrderCurrency($this->total_refunded_amount, $orderCurrency),
|
||||
'total_refunded_points_amount' => $this->roundToOrderCurrency($this->total_refunded_points_amount, $orderCurrency),
|
||||
'total_refunded_points_amount_formatted' => $this->formatOrderCurrency($this->total_refunded_points_amount, $orderCurrency),
|
||||
|
||||
// 마일리지/예치금 — 회원 OrderResource 와 동일 노출. 비회원 주문상세도 회원과 같은 결제정보 partial 을
|
||||
// 재사용하므로 사용/적립 마일리지를 동등하게 표시할 수 있도록 보강 (마일리지는 base_currency 단일 정산).
|
||||
'total_points_used_amount' => $this->roundToOrderCurrency($this->total_points_used_amount, $orderCurrency),
|
||||
'total_points_used_amount_formatted' => $this->formatOrderCurrency($this->total_points_used_amount, $orderCurrency),
|
||||
'total_deposit_used_amount' => $this->roundToOrderCurrency($this->total_deposit_used_amount, $orderCurrency),
|
||||
'total_deposit_used_amount_formatted' => $this->formatOrderCurrency($this->total_deposit_used_amount, $orderCurrency),
|
||||
'total_earned_points_amount' => $this->roundToOrderCurrency($this->total_earned_points_amount, $orderCurrency),
|
||||
'total_earned_points_amount_formatted' => $this->formatOrderCurrency($this->total_earned_points_amount, $orderCurrency),
|
||||
|
||||
// 다중 통화 금액 (주문 시점 스냅샷) — 회원 OrderResource 와 동일 노출.
|
||||
// 통화 선택 UI 가 추후 노출되어도 비회원 화면이 회원과 동등하게 다중 통화를 표시할 수 있도록 보강.
|
||||
'mc_subtotal_amount' => $this->formatStoredMultiCurrency($this->mc_subtotal_amount),
|
||||
'mc_total_discount_amount' => $this->formatStoredMultiCurrency($this->mc_total_discount_amount),
|
||||
'mc_total_shipping_amount' => $this->formatStoredMultiCurrency($this->mc_total_shipping_amount),
|
||||
'mc_total_amount' => $this->formatStoredMultiCurrency($this->mc_total_amount),
|
||||
'mc_total_points_used_amount' => $this->formatStoredMultiCurrency($this->mc_total_points_used_amount),
|
||||
'mc_total_deposit_used_amount' => $this->formatStoredMultiCurrency($this->mc_total_deposit_used_amount),
|
||||
|
||||
// 수량
|
||||
'item_count' => $this->item_count,
|
||||
'total_quantity' => $this->whenLoaded('options', fn () => $this->options->sum('quantity'), 0),
|
||||
|
||||
// 일시 — raw ISO 와 사용자 타임존 변환된 *_formatted 를 함께 제공 (회원 OrderResource 와 동일 패턴)
|
||||
'ordered_at' => $this->ordered_at?->toIso8601String(), // audit:allow datetime-display-user-timezone reason: paired with *_formatted user-tz field
|
||||
'ordered_at_formatted' => $this->formatDateTimeStringForUser($this->ordered_at),
|
||||
'paid_at' => $this->paid_at?->toIso8601String(), // audit:allow datetime-display-user-timezone reason: paired with *_formatted user-tz field
|
||||
'paid_at_formatted' => $this->formatDateTimeStringForUser($this->paid_at),
|
||||
'confirmed_at' => $this->confirmed_at?->toIso8601String(), // audit:allow datetime-display-user-timezone reason: paired with *_formatted user-tz field
|
||||
'confirmed_at_formatted' => $this->formatDateTimeStringForUser($this->confirmed_at),
|
||||
'cancelled_at' => $this->cancelled_at?->toIso8601String(), // audit:allow datetime-display-user-timezone reason: paired with *_formatted user-tz field
|
||||
'cancelled_at_formatted' => $this->formatDateTimeStringForUser($this->cancelled_at),
|
||||
|
||||
// 주문자 정보 (본인이 입력한 정보 — 배송지에서 플래튼)
|
||||
'orderer_name' => $this->shippingAddress?->orderer_name,
|
||||
'orderer_phone' => $this->shippingAddress?->orderer_phone,
|
||||
'orderer_email' => $this->shippingAddress?->orderer_email,
|
||||
|
||||
// 수취인/배송지 정보
|
||||
'recipient_name' => $this->shippingAddress?->recipient_name,
|
||||
'recipient_phone' => $this->shippingAddress?->recipient_phone,
|
||||
'recipient_zipcode' => $this->shippingAddress?->zipcode,
|
||||
'recipient_address' => $this->shippingAddress?->address,
|
||||
'recipient_detail_address' => $this->shippingAddress?->address_detail,
|
||||
'delivery_memo' => $this->shippingAddress?->delivery_memo,
|
||||
'delivery_memo_label' => $this->shippingAddress?->delivery_memo_label,
|
||||
|
||||
// 주문 옵션 (품목) — 주문 시점 통화를 자식에 전파
|
||||
'options' => $this->whenLoaded('options', fn () => OrderOptionResource::collection($this->options)->each(
|
||||
fn ($r) => $r->withOrderCurrency($orderCurrency)
|
||||
)),
|
||||
|
||||
// 배송지/결제/배송 정보
|
||||
'shipping_address' => new OrderAddressResource($this->whenLoaded('shippingAddress')),
|
||||
'payment' => $this->whenLoaded('payment', fn () => (new OrderPaymentResource($this->payment))->withOrderCurrency($orderCurrency)),
|
||||
'shippings' => $this->whenLoaded('shippings', fn () => OrderShippingResource::collection($this->shippings)->each(
|
||||
fn ($r) => $r->withOrderCurrency($orderCurrency)
|
||||
)),
|
||||
|
||||
// 취소 이력 (취소 사유·상세 사유·취소일시 표시용) — 최근 취소가 먼저 오도록 정렬
|
||||
'cancels' => OrderCancelResource::collection($this->whenLoaded('cancels')),
|
||||
|
||||
// 상태 기반 허용 액션 (회원 권한이 아닌 주문 상태로만 판정)
|
||||
'abilities' => $this->guestAbilities(),
|
||||
];
|
||||
}
|
||||
|
||||
/**
|
||||
* 비회원에게 허용되는 액션을 주문 상태 기준으로 계산합니다.
|
||||
*
|
||||
* 토큰 인증으로 본인 확인이 이미 끝났으므로 회원 권한 체크는 적용하지 않고,
|
||||
* 주문 상태/환경설정으로만 가능 여부를 판정합니다.
|
||||
*
|
||||
* @return array<string, bool>
|
||||
*/
|
||||
private function guestAbilities(): array
|
||||
{
|
||||
$cancellableStatuses = module_setting(
|
||||
'sirsoft-ecommerce',
|
||||
'order_settings.cancellable_statuses',
|
||||
['payment_complete']
|
||||
);
|
||||
|
||||
return [
|
||||
'can_cancel' => $this->resource->isCancellable($cancellableStatuses),
|
||||
];
|
||||
}
|
||||
}
|
||||
+81
@@ -0,0 +1,81 @@
|
||||
<?php
|
||||
|
||||
namespace Modules\Sirsoft\Ecommerce\Http\Resources;
|
||||
|
||||
use App\Http\Resources\BaseApiCollection;
|
||||
use App\Http\Resources\Traits\HasAbilityCheck;
|
||||
use Illuminate\Http\Request;
|
||||
use Illuminate\Pagination\LengthAwarePaginator;
|
||||
|
||||
/**
|
||||
* 마일리지 거래 컬렉션 리소스
|
||||
*
|
||||
* 마일리지 거래 목록을 페이지네이션 및 통화 필터 옵션과 함께 반환합니다.
|
||||
*/
|
||||
class MileageTransactionCollection extends BaseApiCollection
|
||||
{
|
||||
use HasAbilityCheck;
|
||||
|
||||
/**
|
||||
* 통화 필터 옵션 목록 (설정 currency_rules 기준)
|
||||
*
|
||||
* @var array<int, string>
|
||||
*/
|
||||
protected array $currencies = [];
|
||||
|
||||
/**
|
||||
* 통화 필터 옵션을 주입합니다.
|
||||
*
|
||||
* @param array<int, string> $currencies 통화 코드 배열
|
||||
* @return $this
|
||||
*/
|
||||
public function withCurrencies(array $currencies): static
|
||||
{
|
||||
$this->currencies = array_values($currencies);
|
||||
|
||||
return $this;
|
||||
}
|
||||
|
||||
/**
|
||||
* 컬렉션 레벨 능력(can_*) 매핑을 반환합니다.
|
||||
*
|
||||
* @return array<string, string> 능력 매핑
|
||||
*/
|
||||
protected function abilityMap(): array
|
||||
{
|
||||
return [
|
||||
'can_manage' => 'sirsoft-ecommerce.mileage.manage',
|
||||
];
|
||||
}
|
||||
|
||||
/**
|
||||
* 컬렉션을 배열로 변환합니다.
|
||||
*
|
||||
* @param Request $request HTTP 요청
|
||||
* @return array<int|string, mixed> 변환된 배열
|
||||
*/
|
||||
public function toArray(Request $request): array
|
||||
{
|
||||
$result = [
|
||||
'data' => $this->mapWithRowNumber(function ($transaction) {
|
||||
return (new MileageTransactionResource($transaction))->toArray(request());
|
||||
}),
|
||||
'abilities' => $this->resolveAbilitiesFromMap($this->abilityMap(), $request->user()),
|
||||
'currencies' => $this->currencies,
|
||||
];
|
||||
|
||||
if ($this->resource instanceof LengthAwarePaginator) {
|
||||
$result['pagination'] = [
|
||||
'current_page' => $this->resource->currentPage(),
|
||||
'last_page' => $this->resource->lastPage(),
|
||||
'per_page' => $this->resource->perPage(),
|
||||
'total' => $this->resource->total(),
|
||||
'from' => $this->resource->firstItem(),
|
||||
'to' => $this->resource->lastItem(),
|
||||
'has_more_pages' => $this->resource->hasMorePages(),
|
||||
];
|
||||
}
|
||||
|
||||
return $result;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,136 @@
|
||||
<?php
|
||||
|
||||
namespace Modules\Sirsoft\Ecommerce\Http\Resources;
|
||||
|
||||
use App\Http\Resources\BaseApiResource;
|
||||
use Illuminate\Http\Request;
|
||||
use Modules\Sirsoft\Ecommerce\Enums\MileageTransactionTypeEnum;
|
||||
use Modules\Sirsoft\Ecommerce\Http\Resources\Traits\HasMultiCurrencyPrices;
|
||||
use Modules\Sirsoft\Ecommerce\Models\MileageTransaction;
|
||||
|
||||
/**
|
||||
* 마일리지 거래 리소스
|
||||
*
|
||||
* @property MileageTransaction $resource
|
||||
*/
|
||||
class MileageTransactionResource extends BaseApiResource
|
||||
{
|
||||
use HasMultiCurrencyPrices;
|
||||
|
||||
/**
|
||||
* 행 레벨 능력(can_*) 매핑을 반환합니다.
|
||||
*
|
||||
* DataGrid 행 액션('수동 조정')의 disabledField('abilities.can_manage')가
|
||||
* 각 행 데이터의 abilities.can_manage 를 참조하므로, 컬렉션 레벨과 동일한
|
||||
* 능력을 행 단위로도 노출합니다.
|
||||
*
|
||||
* @return array<string, string> 능력 매핑
|
||||
*/
|
||||
protected function abilityMap(): array
|
||||
{
|
||||
return [
|
||||
'can_manage' => 'sirsoft-ecommerce.mileage.manage',
|
||||
];
|
||||
}
|
||||
|
||||
/**
|
||||
* 리소스를 배열로 변환합니다.
|
||||
*
|
||||
* @param Request $request 요청
|
||||
* @return array 변환된 배열
|
||||
*/
|
||||
public function toArray(Request $request): array
|
||||
{
|
||||
$type = $this->resource->type instanceof MileageTransactionTypeEnum
|
||||
? $this->resource->type
|
||||
: MileageTransactionTypeEnum::tryFrom((string) $this->resource->type);
|
||||
|
||||
$isEarning = $type?->isEarning() ?? false;
|
||||
$earnAmount = (float) $this->resource->amount;
|
||||
|
||||
// 마일리지 금액 표기 통화 — 거래에 기록된 통화(없으면 기본 통화)의 소수 자릿수를 따른다.
|
||||
$mileageCurrency = $this->resource->currency ?: $this->getDefaultCurrencyCode();
|
||||
|
||||
// 소멸액(이 적립 lot 을 source 로 한 expired 거래 합 — paginateWithFilters 에서 eager 집계).
|
||||
// 단건 조회(연결 거래 등 집계 미주입) 시에는 0 으로 폴백.
|
||||
$expiredAmount = $this->resource->expired_amount !== null ? (float) $this->resource->expired_amount : 0.0;
|
||||
|
||||
// 소멸 상태: 적립계만 의미가 있다. fully(전액 소멸) / partial(일부 소멸) / active(미소멸)
|
||||
$expiryState = 'active';
|
||||
if ($isEarning && $expiredAmount > 0) {
|
||||
$expiryState = ($expiredAmount + 0.001) >= $earnAmount ? 'fully_expired' : 'partial_expired';
|
||||
}
|
||||
|
||||
// 기간 변경 가능: 적립계 + 미소멸 + 잔여 > 0 (소멸/전액사용 lot 은 만료일 변경 불가, memo 만 편집)
|
||||
$canEditExpiry = $isEarning
|
||||
&& $this->resource->expired_at === null
|
||||
&& (float) $this->resource->remaining_amount > 0;
|
||||
|
||||
return [
|
||||
'id' => $this->resource->id,
|
||||
'user_id' => $this->resource->user_id,
|
||||
'currency' => $this->resource->currency,
|
||||
'type' => $type?->value,
|
||||
'type_label' => $type?->label(),
|
||||
'admin_badge_group' => $type?->adminBadgeGroup(),
|
||||
'user_display_category' => $type?->userDisplayCategory(),
|
||||
'amount' => $this->roundToCurrency($this->resource->amount, $mileageCurrency),
|
||||
'amount_formatted' => $this->formatCurrencyPrice((float) $this->resource->amount, $mileageCurrency),
|
||||
'remaining_amount' => $this->roundToCurrency($this->resource->remaining_amount, $mileageCurrency),
|
||||
'remaining_amount_formatted' => $this->formatCurrencyPrice((float) $this->resource->remaining_amount, $mileageCurrency),
|
||||
'balance_after' => $this->roundToCurrency($this->resource->balance_after, $mileageCurrency),
|
||||
'order_id' => $this->resource->order_id,
|
||||
'order_option_id' => $this->resource->order_option_id,
|
||||
'order_cancel_id' => $this->resource->order_cancel_id,
|
||||
'source_transaction_id' => $this->resource->source_transaction_id,
|
||||
'granted_by' => $this->resource->granted_by,
|
||||
'granted_by_name' => $this->whenLoaded('grantedByUser', fn () => $this->resource->grantedByUser?->name),
|
||||
'granted_by_uuid' => $this->whenLoaded('grantedByUser', fn () => $this->resource->grantedByUser?->uuid),
|
||||
'user_name' => $this->whenLoaded('user', fn () => $this->resource->user?->name),
|
||||
'user_uuid' => $this->whenLoaded('user', fn () => $this->resource->user?->uuid),
|
||||
'order_number' => $this->whenLoaded('order', fn () => $this->resource->order?->order_number),
|
||||
'description' => $this->resource->description,
|
||||
'memo' => $this->resource->memo,
|
||||
'expires_at' => $this->resource->expires_at?->toIso8601String(), // audit:allow datetime-display-user-timezone reason: paired with *_formatted user-tz field
|
||||
'expires_at_formatted' => $this->formatDateTimeStringForUser($this->resource->expires_at),
|
||||
'expires_at_date' => $this->formatDateStringForSite($this->resource->expires_at),
|
||||
'expired_at' => $this->resource->expired_at?->toIso8601String(), // audit:allow datetime-display-user-timezone reason: paired with *_formatted user-tz field
|
||||
'expired_at_formatted' => $this->formatDateTimeStringForUser($this->resource->expired_at),
|
||||
'created_at' => $this->resource->created_at?->toIso8601String(), // audit:allow datetime-display-user-timezone reason: paired with *_formatted user-tz field
|
||||
'created_at_formatted' => $this->formatDateTimeStringForUser($this->resource->created_at),
|
||||
'created_at_date' => $this->formatDateStringForSite($this->resource->created_at),
|
||||
|
||||
// 적립계 여부 + 소멸 집계 (행 편집 게이팅 + 일부/전체 소멸 표시 — B-3)
|
||||
'is_earning' => $isEarning,
|
||||
'can_edit_expiry' => $canEditExpiry,
|
||||
'expired_amount' => $this->roundToCurrency($expiredAmount, $mileageCurrency),
|
||||
'expired_amount_formatted' => $this->formatCurrencyPrice($expiredAmount, $mileageCurrency),
|
||||
'expiry_state' => $expiryState,
|
||||
|
||||
// 행 레벨 권한 메타 (abilities.can_manage + can_edit) — DataGrid 행 액션 disabled 제어
|
||||
...$this->resourceMeta($request),
|
||||
];
|
||||
}
|
||||
|
||||
/**
|
||||
* 행 레벨 능력을 계산합니다.
|
||||
*
|
||||
* 표준 can_manage 에 더해, 행 편집 메뉴('사유·기간 변경') 게이팅용 can_edit 를 노출합니다.
|
||||
* can_edit = manage 권한 보유 && 적립계 거래 (비적립계 행은 메뉴 비활성 — PO 합의 C-2).
|
||||
*
|
||||
* @param Request $request HTTP 요청
|
||||
* @return array<string, bool> 능력 불리언 맵
|
||||
*/
|
||||
protected function resolveAbilities(Request $request): array
|
||||
{
|
||||
$abilities = parent::resolveAbilities($request);
|
||||
|
||||
$type = $this->resource->type instanceof MileageTransactionTypeEnum
|
||||
? $this->resource->type
|
||||
: MileageTransactionTypeEnum::tryFrom((string) $this->resource->type);
|
||||
|
||||
$abilities['can_edit'] = (bool) ($abilities['can_manage'] ?? false) && ($type?->isEarning() ?? false);
|
||||
|
||||
return $abilities;
|
||||
}
|
||||
}
|
||||
@@ -4,20 +4,25 @@ namespace Modules\Sirsoft\Ecommerce\Http\Resources;
|
||||
|
||||
use App\Http\Resources\BaseApiResource;
|
||||
use Illuminate\Http\Request;
|
||||
use Modules\Sirsoft\Ecommerce\Http\Resources\Concerns\LocalizesCountryName;
|
||||
|
||||
/**
|
||||
* 주문 배송지/청구지 리소스
|
||||
*/
|
||||
class OrderAddressResource extends BaseApiResource
|
||||
{
|
||||
use LocalizesCountryName;
|
||||
|
||||
/**
|
||||
* 리소스를 배열로 변환
|
||||
*
|
||||
* @param Request $request 요청
|
||||
* @return array
|
||||
* @param Request $request 요청
|
||||
* @return array 주소 리소스 배열 (국가명·국내/해외 필드 포함)
|
||||
*/
|
||||
public function toArray(Request $request): array
|
||||
{
|
||||
$isDomestic = empty($this->recipient_country_code) || strtoupper((string) $this->recipient_country_code) === 'KR';
|
||||
|
||||
return [
|
||||
'id' => $this->id,
|
||||
'address_type' => $this->address_type,
|
||||
@@ -26,12 +31,31 @@ class OrderAddressResource extends BaseApiResource
|
||||
'orderer_email' => $this->orderer_email,
|
||||
'recipient_name' => $this->recipient_name,
|
||||
'recipient_phone' => $this->recipient_phone,
|
||||
// 국가 (항상 표시 — D9)
|
||||
'recipient_country_code' => $this->recipient_country_code,
|
||||
'recipient_country_name' => $this->getCountryLocalizedName($this->recipient_country_code),
|
||||
'is_domestic' => $isDomestic,
|
||||
// 국내(KR) 필드
|
||||
'zipcode' => $this->zipcode,
|
||||
'address' => $this->address,
|
||||
'address_detail' => $this->address_detail,
|
||||
// 해외 배송 필드
|
||||
'address_line_1' => $this->address_line_1,
|
||||
'address_line_2' => $this->address_line_2,
|
||||
'intl_city' => $this->intl_city,
|
||||
'intl_state' => $this->intl_state,
|
||||
'intl_postal_code' => $this->intl_postal_code,
|
||||
'delivery_memo' => $this->delivery_memo,
|
||||
'full_address' => $this->address.($this->address_detail ? ' '.$this->address_detail : ''),
|
||||
'delivery_memo_label' => $this->delivery_memo_label,
|
||||
'full_address' => $isDomestic
|
||||
? $this->address.($this->address_detail ? ' '.$this->address_detail : '')
|
||||
: trim(implode(' ', array_filter([
|
||||
$this->address_line_1,
|
||||
$this->address_line_2,
|
||||
$this->intl_city,
|
||||
$this->intl_state,
|
||||
$this->intl_postal_code,
|
||||
]))),
|
||||
];
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,40 @@
|
||||
<?php
|
||||
|
||||
namespace Modules\Sirsoft\Ecommerce\Http\Resources;
|
||||
|
||||
use App\Http\Resources\BaseApiResource;
|
||||
use Illuminate\Http\Request;
|
||||
|
||||
/**
|
||||
* 주문 취소 이력 리소스
|
||||
*
|
||||
* 주문상세 화면(관리자/유저)에서 취소 사유와 취소 일시를 표시하기 위한 리소스입니다.
|
||||
*/
|
||||
class OrderCancelResource extends BaseApiResource
|
||||
{
|
||||
/**
|
||||
* 리소스를 배열로 변환합니다.
|
||||
*
|
||||
* @param Request $request 요청
|
||||
* @return array<string, mixed> 직렬화된 취소 이력 배열
|
||||
*/
|
||||
public function toArray(Request $request): array
|
||||
{
|
||||
return [
|
||||
'id' => $this->id,
|
||||
'cancel_number' => $this->cancel_number,
|
||||
'cancel_type' => $this->cancel_type,
|
||||
'cancel_type_label' => $this->cancel_type ? $this->cancel_type->label() : null,
|
||||
'cancel_status' => $this->cancel_status,
|
||||
'cancel_status_label' => $this->cancel_status ? $this->cancel_status->label() : null,
|
||||
// 사유 코드 → ClaimReason 다국어 라벨 (없으면 코드 원문 폴백)
|
||||
'cancel_reason_type' => $this->cancel_reason_type,
|
||||
'cancel_reason_label' => $this->getRefundReasonLabel(),
|
||||
// "기타" 선택 시 입력한 상세 사유 텍스트 (없으면 null)
|
||||
'cancel_reason_detail' => $this->cancel_reason,
|
||||
// 취소 일시 — raw ISO 와 사용자 타임존 변환된 *_formatted 함께 제공
|
||||
'cancelled_at' => $this->cancelled_at?->toIso8601String(), // audit:allow datetime-display-user-timezone reason: paired with *_formatted user-tz field
|
||||
'cancelled_at_formatted' => $this->formatDateTimeStringForUser($this->cancelled_at),
|
||||
];
|
||||
}
|
||||
}
|
||||
@@ -4,41 +4,69 @@ namespace Modules\Sirsoft\Ecommerce\Http\Resources;
|
||||
|
||||
use App\Http\Resources\BaseApiResource;
|
||||
use Illuminate\Http\Request;
|
||||
use Modules\Sirsoft\Ecommerce\Http\Resources\Concerns\LocalizesCountryName;
|
||||
use Modules\Sirsoft\Ecommerce\Http\Resources\Traits\HasMultiCurrencyPrices;
|
||||
use Modules\Sirsoft\Ecommerce\Http\Resources\Traits\SummarizesAdditionalOptions;
|
||||
use Modules\Sirsoft\Ecommerce\Models\OrderShipping;
|
||||
use Modules\Sirsoft\Ecommerce\Models\ShippingType;
|
||||
|
||||
/**
|
||||
* 주문 목록 리소스
|
||||
*/
|
||||
class OrderListResource extends BaseApiResource
|
||||
{
|
||||
use HasMultiCurrencyPrices;
|
||||
use LocalizesCountryName;
|
||||
use SummarizesAdditionalOptions;
|
||||
|
||||
/**
|
||||
* 리소스를 배열로 변환
|
||||
*
|
||||
* @param Request $request 요청
|
||||
* @return array
|
||||
* @param Request $request 요청
|
||||
* @return array 관리자 주문 목록 리소스 배열
|
||||
*/
|
||||
public function toArray(Request $request): array
|
||||
{
|
||||
// 주문 시점 기준 통화 — 과거 주문의 *_formatted 는 설정 변경과 무관하게 이 통화로 고정 표기한다.
|
||||
$orderCurrency = $this->resolveOrderBaseCurrencyCode($this->resource);
|
||||
|
||||
// 결제 통화(order_currency) — 유저가 선택·결제한 통화. base 통화와 다를 때 함께 표기.
|
||||
$paymentCurrency = $this->currency
|
||||
?: (data_get($this->currency_snapshot, 'order_currency') ?: $orderCurrency);
|
||||
|
||||
return [
|
||||
'id' => $this->id,
|
||||
'order_number' => $this->order_number,
|
||||
'order_status' => $this->order_status,
|
||||
'order_status_label' => $this->order_status ? $this->order_status->label() : null,
|
||||
'order_status_variant' => $this->order_status ? $this->order_status->variant() : null,
|
||||
// 금액 표기 기준 통화(base) + 결제 통화(order_currency) + 교차 통화 여부.
|
||||
'base_currency' => $orderCurrency,
|
||||
'payment_currency' => $paymentCurrency,
|
||||
'is_cross_currency' => $paymentCurrency !== $orderCurrency,
|
||||
// 부분취소 파생 플래그 — 일부 옵션만 취소된 주문(별도 order_status 아님). 보조 뱃지 표시용.
|
||||
'is_partially_cancelled' => $this->whenLoaded('options', fn () => $this->resource->isPartiallyCancelled(), false),
|
||||
|
||||
// 금액
|
||||
'total_amount' => $this->total_amount,
|
||||
'total_amount_formatted' => number_format($this->total_amount).'원',
|
||||
'total_shipping_amount' => $this->total_shipping_amount,
|
||||
'total_shipping_amount_formatted' => number_format($this->total_shipping_amount).'원',
|
||||
'total_paid_amount' => $this->total_paid_amount,
|
||||
'total_paid_amount_formatted' => number_format($this->total_paid_amount).'원',
|
||||
'total_unpaid_amount' => $this->total_amount - $this->total_paid_amount,
|
||||
'total_unpaid_amount_formatted' => number_format($this->total_amount - $this->total_paid_amount).'원',
|
||||
'total_cancelled_amount' => $this->total_cancelled_amount,
|
||||
'total_refunded_amount' => $this->total_refunded_amount,
|
||||
'total_amount' => $this->roundToOrderCurrency($this->total_amount, $orderCurrency),
|
||||
'total_amount_formatted' => $this->formatOrderCurrency($this->total_amount, $orderCurrency),
|
||||
'total_shipping_amount' => $this->roundToOrderCurrency($this->total_shipping_amount, $orderCurrency),
|
||||
'total_shipping_amount_formatted' => $this->formatOrderCurrency($this->total_shipping_amount, $orderCurrency),
|
||||
'total_paid_amount' => $this->roundToOrderCurrency($this->total_paid_amount, $orderCurrency),
|
||||
'total_paid_amount_formatted' => $this->formatOrderCurrency($this->total_paid_amount, $orderCurrency),
|
||||
'total_unpaid_amount' => $this->roundToOrderCurrency($this->total_amount - $this->total_paid_amount, $orderCurrency),
|
||||
'total_unpaid_amount_formatted' => $this->formatOrderCurrency($this->total_amount - $this->total_paid_amount, $orderCurrency),
|
||||
'total_cancelled_amount' => $this->roundToOrderCurrency($this->total_cancelled_amount, $orderCurrency),
|
||||
'total_refunded_amount' => $this->roundToOrderCurrency($this->total_refunded_amount, $orderCurrency),
|
||||
|
||||
// 일시
|
||||
'ordered_at' => $this->ordered_at?->toIso8601String(),
|
||||
// 마일리지 (목록 표시용 — 사용/적립). 마일리지는 base_currency 단일 정산.
|
||||
'total_points_used_amount' => $this->roundToOrderCurrency($this->total_points_used_amount, $orderCurrency),
|
||||
'total_points_used_amount_formatted' => $this->formatOrderCurrency($this->total_points_used_amount, $orderCurrency),
|
||||
'total_earned_points_amount' => $this->roundToOrderCurrency($this->total_earned_points_amount, $orderCurrency),
|
||||
'total_earned_points_amount_formatted' => $this->formatOrderCurrency($this->total_earned_points_amount, $orderCurrency),
|
||||
|
||||
// 일시 — raw ISO 와 사용자 타임존 변환된 *_formatted 를 함께 제공 (OrderResource 와 동일 패턴)
|
||||
'ordered_at' => $this->ordered_at?->toIso8601String(), // audit:allow datetime-display-user-timezone reason: paired with *_formatted user-tz field
|
||||
'ordered_at_formatted' => $this->formatDateTimeStringForUser($this->ordered_at),
|
||||
|
||||
// 구매환경
|
||||
@@ -58,17 +86,22 @@ class OrderListResource extends BaseApiResource
|
||||
'first_option' => $this->whenLoaded('options', function () {
|
||||
$firstOption = $this->options->first();
|
||||
$productName = $firstOption?->product_name;
|
||||
// 매직 프로퍼티(Eloquent accessor)를 reset() 에 직접 넘기면 PHP 8.3 에서
|
||||
// "Indirect modification of overloaded property" 경고가 발생하므로 지역 변수로 받는다.
|
||||
$optionName = $firstOption?->product_option_name;
|
||||
|
||||
return [
|
||||
'product_name' => is_array($productName)
|
||||
? ($productName[app()->getLocale()] ?? reset($productName) ?: '')
|
||||
: ($productName ?? ''),
|
||||
'product_option_name' => is_array($firstOption?->product_option_name)
|
||||
? ($firstOption->product_option_name[app()->getLocale()] ?? reset($firstOption->product_option_name) ?: '')
|
||||
: ($firstOption?->product_option_name ?? ''),
|
||||
'product_option_name' => is_array($optionName)
|
||||
? ($optionName[app()->getLocale()] ?? reset($optionName) ?: '')
|
||||
: ($optionName ?? ''),
|
||||
'product_code' => $firstOption?->product_snapshot['product_code'] ?? null,
|
||||
'quantity' => $firstOption?->quantity,
|
||||
'thumbnail_url' => $firstOption?->product_snapshot['thumbnail_url'] ?? null,
|
||||
// 추가옵션 요약 (스냅샷 기반 — 첫 1건 + "외 N건", custom_text 병기)
|
||||
'additional_options_summary' => $this->summarizeAdditionalOptions($firstOption),
|
||||
];
|
||||
}),
|
||||
'options_count' => $this->whenLoaded('options', fn () => $this->options->count()),
|
||||
@@ -94,7 +127,7 @@ class OrderListResource extends BaseApiResource
|
||||
return [
|
||||
'shipping_type' => $shipping?->shipping_type,
|
||||
'shipping_type_label' => $shipping?->shipping_type
|
||||
? \Modules\Sirsoft\Ecommerce\Models\ShippingType::getCachedByCode($shipping->shipping_type)?->getLocalizedName()
|
||||
? ShippingType::getCachedByCode($shipping->shipping_type)?->getLocalizedName()
|
||||
: null,
|
||||
'shipping_method_label' => $this->resolveSnapshotMethodLabel($shipping),
|
||||
'carrier_name' => $shipping?->carrier?->getLocalizedName(),
|
||||
@@ -122,46 +155,18 @@ class OrderListResource extends BaseApiResource
|
||||
|
||||
/**
|
||||
* 소유자 필드명을 반환합니다.
|
||||
*
|
||||
* @return string|null
|
||||
*/
|
||||
protected function ownerField(): ?string
|
||||
{
|
||||
return 'user_id';
|
||||
}
|
||||
|
||||
/**
|
||||
* 국가 코드를 다국어 국가명 객체로 변환합니다.
|
||||
*
|
||||
* @param string|null $countryCode ISO alpha-2 국가 코드
|
||||
* @return array|null 다국어 객체 (예: {ko: '한국', en: 'South Korea'})
|
||||
*/
|
||||
private function getCountryLocalizedName(?string $countryCode): ?array
|
||||
{
|
||||
if (! $countryCode) {
|
||||
return null;
|
||||
}
|
||||
|
||||
$countryCode = strtoupper($countryCode);
|
||||
$localizedNames = config('countries.localized_names', []);
|
||||
|
||||
$result = [];
|
||||
foreach ($localizedNames as $locale => $names) {
|
||||
if (isset($names[$countryCode])) {
|
||||
$result[$locale] = $names[$countryCode];
|
||||
}
|
||||
}
|
||||
|
||||
return ! empty($result) ? $result : null;
|
||||
}
|
||||
|
||||
/**
|
||||
* 스냅샷 기반 배송방법 라벨을 해석합니다.
|
||||
*
|
||||
* @param \Modules\Sirsoft\Ecommerce\Models\OrderShipping|null $shipping 배송 레코드
|
||||
* @return string|null
|
||||
* @param OrderShipping|null $shipping 배송 레코드
|
||||
*/
|
||||
private function resolveSnapshotMethodLabel(?\Modules\Sirsoft\Ecommerce\Models\OrderShipping $shipping): ?string
|
||||
private function resolveSnapshotMethodLabel(?OrderShipping $shipping): ?string
|
||||
{
|
||||
if (! $shipping) {
|
||||
return null;
|
||||
@@ -185,6 +190,6 @@ class OrderListResource extends BaseApiResource
|
||||
return null;
|
||||
}
|
||||
|
||||
return \Modules\Sirsoft\Ecommerce\Models\ShippingType::getCachedByCode($method)?->getLocalizedName();
|
||||
return ShippingType::getCachedByCode($method)?->getLocalizedName();
|
||||
}
|
||||
}
|
||||
@@ -7,6 +7,7 @@ use App\Http\Resources\BaseApiResource;
|
||||
use Illuminate\Http\Request;
|
||||
use Modules\Sirsoft\Ecommerce\Enums\OrderStatusEnum;
|
||||
use Modules\Sirsoft\Ecommerce\Http\Resources\Traits\HasMultiCurrencyPrices;
|
||||
use Modules\Sirsoft\Ecommerce\Models\ShippingType;
|
||||
|
||||
/**
|
||||
* 주문 옵션 리소스
|
||||
@@ -14,11 +15,12 @@ use Modules\Sirsoft\Ecommerce\Http\Resources\Traits\HasMultiCurrencyPrices;
|
||||
class OrderOptionResource extends BaseApiResource
|
||||
{
|
||||
use HasMultiCurrencyPrices;
|
||||
|
||||
/**
|
||||
* 리소스를 배열로 변환
|
||||
*
|
||||
* @param Request $request 요청
|
||||
* @return array
|
||||
* @param Request $request 요청
|
||||
* @return array 주문 옵션 배열
|
||||
*/
|
||||
public function toArray(Request $request): array
|
||||
{
|
||||
@@ -51,44 +53,61 @@ class OrderOptionResource extends BaseApiResource
|
||||
: ($optionName ?? ''),
|
||||
'quantity' => $this->quantity,
|
||||
'shipped_quantity' => $this->shipped_quantity,
|
||||
'unit_price' => $this->unit_price,
|
||||
'unit_price_formatted' => number_format($this->unit_price).'원',
|
||||
'subtotal_price' => $this->subtotal_price,
|
||||
'subtotal_price_formatted' => number_format($this->subtotal_price).'원',
|
||||
'subtotal_discount_amount' => $this->subtotal_discount_amount,
|
||||
'subtotal_discount_amount_formatted' => number_format($this->subtotal_discount_amount).'원',
|
||||
|
||||
// 재고 적용 여부 (재고 차감 완료 시 true)
|
||||
'is_stock_deducted' => (bool) $this->is_stock_deducted,
|
||||
// 실제 적립 발생 여부 (해당 옵션에 구매 적립 거래가 발행되었으면 true)
|
||||
// withExists('purchaseEarnTransactions') 로 로드된 집계 컬럼 사용 (미로드 경로에서는 false)
|
||||
'is_points_earned' => (bool) ($this->purchase_earn_transactions_exists ?? false),
|
||||
'unit_price' => $this->roundToOrderCurrency($this->unit_price),
|
||||
'unit_price_formatted' => $this->formatOrderCurrency($this->unit_price),
|
||||
'subtotal_price' => $this->roundToOrderCurrency($this->subtotal_price),
|
||||
'subtotal_price_formatted' => $this->formatOrderCurrency($this->subtotal_price),
|
||||
'subtotal_discount_amount' => $this->roundToOrderCurrency($this->subtotal_discount_amount),
|
||||
// 비교용 숫자 보조 필드 — decimal:2 캐스트는 JSON 에 문자열("0.00")로 직렬화되어
|
||||
// 레이아웃의 `=== 0` strict 비교가 항상 거짓이 된다(무할인 항목 소계 미표시 U19②).
|
||||
// 레이아웃이 숫자로 비교하도록 float 값을 함께 노출한다(기존 문자열 필드는 호환 유지).
|
||||
'subtotal_discount_amount_value' => (float) $this->subtotal_discount_amount,
|
||||
'subtotal_discount_amount_formatted' => $this->formatOrderCurrency($this->subtotal_discount_amount),
|
||||
|
||||
// 정가 (스냅샷 기준)
|
||||
'list_price' => $listPrice,
|
||||
'list_price_formatted' => $listPrice !== null ? number_format($listPrice).'원' : null,
|
||||
'list_price' => $listPrice !== null ? $this->roundToOrderCurrency($listPrice) : null,
|
||||
'list_price_formatted' => $listPrice !== null ? $this->formatOrderCurrency($listPrice) : null,
|
||||
|
||||
// 실결제 금액 (할인 후)
|
||||
'final_amount' => $finalAmount,
|
||||
'final_amount_formatted' => number_format($finalAmount).'원',
|
||||
'final_amount' => $this->roundToOrderCurrency($finalAmount),
|
||||
'final_amount_formatted' => $this->formatOrderCurrency($finalAmount),
|
||||
|
||||
// 할인 상세
|
||||
'product_coupon_discount_amount' => $this->product_coupon_discount_amount,
|
||||
'product_coupon_discount_amount_formatted' => number_format($this->product_coupon_discount_amount).'원',
|
||||
'order_coupon_discount_amount' => $this->order_coupon_discount_amount,
|
||||
'order_coupon_discount_amount_formatted' => number_format($this->order_coupon_discount_amount).'원',
|
||||
'coupon_discount_amount' => $this->coupon_discount_amount,
|
||||
'coupon_discount_amount_formatted' => number_format($this->coupon_discount_amount).'원',
|
||||
'code_discount_amount' => $this->code_discount_amount,
|
||||
'code_discount_amount_formatted' => number_format($this->code_discount_amount).'원',
|
||||
'product_coupon_discount_amount' => $this->roundToOrderCurrency($this->product_coupon_discount_amount),
|
||||
'product_coupon_discount_amount_formatted' => $this->formatOrderCurrency($this->product_coupon_discount_amount),
|
||||
'order_coupon_discount_amount' => $this->roundToOrderCurrency($this->order_coupon_discount_amount),
|
||||
'order_coupon_discount_amount_formatted' => $this->formatOrderCurrency($this->order_coupon_discount_amount),
|
||||
'coupon_discount_amount' => $this->roundToOrderCurrency($this->coupon_discount_amount),
|
||||
'coupon_discount_amount_formatted' => $this->formatOrderCurrency($this->coupon_discount_amount),
|
||||
'code_discount_amount' => $this->roundToOrderCurrency($this->code_discount_amount),
|
||||
'code_discount_amount_formatted' => $this->formatOrderCurrency($this->code_discount_amount),
|
||||
|
||||
// 마일리지/예치금
|
||||
'subtotal_points_used_amount' => $this->subtotal_points_used_amount,
|
||||
'subtotal_points_used_amount_formatted' => number_format($this->subtotal_points_used_amount).'원',
|
||||
'subtotal_deposit_used_amount' => $this->subtotal_deposit_used_amount,
|
||||
'subtotal_deposit_used_amount_formatted' => number_format($this->subtotal_deposit_used_amount).'원',
|
||||
'subtotal_earned_points_amount' => $this->subtotal_earned_points_amount,
|
||||
'subtotal_earned_points_amount_formatted' => number_format($this->subtotal_earned_points_amount).'원',
|
||||
'subtotal_points_used_amount' => $this->roundToOrderCurrency($this->subtotal_points_used_amount),
|
||||
'subtotal_points_used_amount_formatted' => $this->formatOrderCurrency($this->subtotal_points_used_amount),
|
||||
'subtotal_deposit_used_amount' => $this->roundToOrderCurrency($this->subtotal_deposit_used_amount),
|
||||
'subtotal_deposit_used_amount_formatted' => $this->formatOrderCurrency($this->subtotal_deposit_used_amount),
|
||||
'subtotal_earned_points_amount' => $this->roundToOrderCurrency($this->subtotal_earned_points_amount),
|
||||
'subtotal_earned_points_amount_formatted' => $this->formatOrderCurrency($this->subtotal_earned_points_amount),
|
||||
|
||||
// 프로모션 스냅샷
|
||||
'promotions_applied_snapshot' => $this->promotions_applied_snapshot,
|
||||
|
||||
'product_snapshot' => $this->product_snapshot,
|
||||
'option_snapshot' => $this->option_snapshot,
|
||||
|
||||
// 추가옵션 (주문 시점 스냅샷 — 관리자 수정/삭제와 무관하게 고정 표시 D8/D14)
|
||||
'additional_options' => $this->formatAdditionalOptionsSnapshot($locale),
|
||||
'additional_options_total' => $this->roundToOrderCurrency((float) $this->additional_options_total),
|
||||
'additional_options_total_formatted' => $this->formatOrderCurrency((float) $this->additional_options_total),
|
||||
'mc_additional_options_total' => $this->formatStoredMultiCurrency($this->mc_additional_options_total),
|
||||
|
||||
'thumbnail_url' => $this->product_snapshot['thumbnail_url'] ?? null,
|
||||
'parent_option_id' => $this->parent_option_id,
|
||||
'source_option_id' => $this->source_option_id,
|
||||
@@ -102,7 +121,7 @@ class OrderOptionResource extends BaseApiResource
|
||||
$shippingType = $this->shippings->first()?->shipping_type;
|
||||
|
||||
return $shippingType
|
||||
? \Modules\Sirsoft\Ecommerce\Models\ShippingType::getCachedByCode($shippingType)?->getLocalizedName()
|
||||
? ShippingType::getCachedByCode($shippingType)?->getLocalizedName()
|
||||
: null;
|
||||
}),
|
||||
'shipping_method_label' => $this->whenLoaded('shippings', function () {
|
||||
@@ -128,13 +147,13 @@ class OrderOptionResource extends BaseApiResource
|
||||
return null;
|
||||
}
|
||||
|
||||
return \Modules\Sirsoft\Ecommerce\Models\ShippingType::getCachedByCode($method)?->getLocalizedName();
|
||||
return ShippingType::getCachedByCode($method)?->getLocalizedName();
|
||||
}),
|
||||
'shipping_amount' => $this->whenLoaded('shippings', function () {
|
||||
return $this->shippings->first()?->total_shipping_amount ?? 0;
|
||||
return $this->roundToOrderCurrency($this->shippings->first()?->total_shipping_amount ?? 0);
|
||||
}),
|
||||
'shipping_amount_formatted' => $this->whenLoaded('shippings', function () {
|
||||
return number_format($this->shippings->first()?->total_shipping_amount ?? 0).'원';
|
||||
return $this->formatOrderCurrency($this->shippings->first()?->total_shipping_amount ?? 0);
|
||||
}),
|
||||
'carrier_name' => $this->whenLoaded('shippings', function () {
|
||||
return $this->shippings->first()?->carrier?->getLocalizedName();
|
||||
@@ -142,6 +161,9 @@ class OrderOptionResource extends BaseApiResource
|
||||
'tracking_number' => $this->whenLoaded('shippings', function () {
|
||||
return $this->shippings->first()?->tracking_number;
|
||||
}),
|
||||
'tracking_url' => $this->whenLoaded('shippings', function () {
|
||||
return $this->shippings->first()?->getTrackingUrl();
|
||||
}),
|
||||
|
||||
// 다중 통화 (주문 시점 스냅샷)
|
||||
'mc_unit_price' => $this->formatStoredMultiCurrency($this->mc_unit_price),
|
||||
@@ -155,17 +177,57 @@ class OrderOptionResource extends BaseApiResource
|
||||
'mc_subtotal_deposit_used_amount' => $this->formatStoredMultiCurrency($this->mc_subtotal_deposit_used_amount),
|
||||
|
||||
// 구매확정/리뷰 관련
|
||||
'confirmed_at' => $this->confirmed_at?->toIso8601String(),
|
||||
// confirmed_at 은 화면 표시용이 아닌 클라이언트 계산용(리뷰 작성 기한 등) ISO8601 머신값
|
||||
'confirmed_at' => $this->confirmed_at?->toIso8601String(), // audit:allow datetime-display-user-timezone reason: machine ISO8601 for client-side calc, not a display field
|
||||
'can_confirm' => $this->calculateCanConfirm(),
|
||||
'can_write_review' => $this->calculateCanWriteReview(),
|
||||
// 구매확정 + 미작성 상태인데 작성 기한만 지나 리뷰를 쓸 수 없는 경우 true
|
||||
// (버튼이 사라진 이유를 사용자에게 안내하기 위한 플래그)
|
||||
'review_deadline_passed' => $this->calculateReviewDeadlinePassed(),
|
||||
'has_review' => $this->review !== null,
|
||||
];
|
||||
}
|
||||
|
||||
/**
|
||||
* 구매확정 가능 여부 계산
|
||||
* 추가옵션 스냅샷을 표시용으로 변환합니다.
|
||||
*
|
||||
* @return bool
|
||||
* 주문 시점 동결된 additional_options_snapshot 의 다국어 이름/추가금을
|
||||
* 현재 로케일로 해석합니다 (관리자 수정/삭제와 무관 — D8).
|
||||
*
|
||||
* @param string $locale 현재 로케일
|
||||
* @return array<int, array{additional_option_id: int, value_id: int, name: string, price_adjustment: int, custom_text: string}>
|
||||
*/
|
||||
private function formatAdditionalOptionsSnapshot(string $locale): array
|
||||
{
|
||||
$snapshot = $this->additional_options_snapshot ?? [];
|
||||
|
||||
if (! is_array($snapshot) || empty($snapshot)) {
|
||||
return [];
|
||||
}
|
||||
|
||||
$result = [];
|
||||
foreach ($snapshot as $entry) {
|
||||
$name = $entry['name'] ?? '';
|
||||
if (is_array($name)) {
|
||||
$name = $name[$locale] ?? $name[config('app.fallback_locale', 'ko')] ?? (! empty($name) ? reset($name) : '');
|
||||
}
|
||||
|
||||
$result[] = [
|
||||
'additional_option_id' => (int) ($entry['additional_option_id'] ?? 0),
|
||||
'value_id' => (int) ($entry['value_id'] ?? 0),
|
||||
'name' => (string) $name,
|
||||
'price_adjustment' => $this->roundToOrderCurrency((int) ($entry['price_adjustment'] ?? 0)),
|
||||
'price_adjustment_formatted' => $this->formatOrderCurrency((int) ($entry['price_adjustment'] ?? 0)),
|
||||
// 직접입력 텍스트 (주문 시점 동결 — 없으면 빈 문자열)
|
||||
'custom_text' => (string) ($entry['custom_text'] ?? ''),
|
||||
];
|
||||
}
|
||||
|
||||
return $result;
|
||||
}
|
||||
|
||||
/**
|
||||
* 구매확정 가능 여부 계산
|
||||
*/
|
||||
private function calculateCanConfirm(): bool
|
||||
{
|
||||
@@ -182,7 +244,9 @@ class OrderOptionResource extends BaseApiResource
|
||||
/**
|
||||
* 리뷰 작성 가능 여부 계산
|
||||
*
|
||||
* @return bool
|
||||
* 마감일 계산은 ProductReviewService::canWrite 와 동일한 기준을 사용한다
|
||||
* (confirmed_at + N일 경계 비교, N=0 은 무제한). 버튼 노출과 제출 검증의
|
||||
* 판정이 어긋나지 않도록 단일 기준으로 통일.
|
||||
*/
|
||||
private function calculateCanWriteReview(): bool
|
||||
{
|
||||
@@ -190,8 +254,7 @@ class OrderOptionResource extends BaseApiResource
|
||||
return false;
|
||||
}
|
||||
|
||||
$deadlineDays = module_setting('sirsoft-ecommerce', 'review_settings.write_deadline_days', 90);
|
||||
if ($this->confirmed_at && $this->confirmed_at->diffInDays(now()) > $deadlineDays) {
|
||||
if ($this->isReviewDeadlinePassed()) {
|
||||
return false;
|
||||
}
|
||||
|
||||
@@ -201,4 +264,40 @@ class OrderOptionResource extends BaseApiResource
|
||||
|
||||
return PermissionHelper::check('sirsoft-ecommerce.user-reviews.write');
|
||||
}
|
||||
|
||||
/**
|
||||
* 리뷰 작성 기한 만료 안내 노출 여부 계산
|
||||
*
|
||||
* 구매확정 + 미작성 상태에서 작성 기한만 지나 리뷰를 쓸 수 없는 경우 true.
|
||||
* (리뷰 작성 버튼이 사라진 이유를 사용자에게 안내하기 위한 플래그)
|
||||
*/
|
||||
private function calculateReviewDeadlinePassed(): bool
|
||||
{
|
||||
if ($this->option_status !== OrderStatusEnum::CONFIRMED) {
|
||||
return false;
|
||||
}
|
||||
|
||||
if ($this->review !== null) {
|
||||
return false;
|
||||
}
|
||||
|
||||
return $this->isReviewDeadlinePassed();
|
||||
}
|
||||
|
||||
/**
|
||||
* 구매확정 시점 기준 리뷰 작성 기한이 지났는지 판정
|
||||
*
|
||||
* ProductReviewService::canWrite 와 동일한 경계 비교를 사용한다
|
||||
* (confirmed_at + N일 < now). N(write_deadline_days)이 0 이하면 무제한으로 간주.
|
||||
*/
|
||||
private function isReviewDeadlinePassed(): bool
|
||||
{
|
||||
$deadlineDays = (int) module_setting('sirsoft-ecommerce', 'review_settings.write_deadline_days', 90);
|
||||
|
||||
if (! $this->confirmed_at || $deadlineDays <= 0) {
|
||||
return false;
|
||||
}
|
||||
|
||||
return now()->gt($this->confirmed_at->copy()->addDays($deadlineDays));
|
||||
}
|
||||
}
|
||||
@@ -4,17 +4,21 @@ namespace Modules\Sirsoft\Ecommerce\Http\Resources;
|
||||
|
||||
use App\Http\Resources\BaseApiResource;
|
||||
use Illuminate\Http\Request;
|
||||
use Modules\Sirsoft\Ecommerce\Enums\PaymentMethodEnum;
|
||||
use Modules\Sirsoft\Ecommerce\Http\Resources\Traits\HasMultiCurrencyPrices;
|
||||
|
||||
/**
|
||||
* 주문 결제 정보 리소스
|
||||
*/
|
||||
class OrderPaymentResource extends BaseApiResource
|
||||
{
|
||||
use HasMultiCurrencyPrices;
|
||||
|
||||
/**
|
||||
* 리소스를 배열로 변환
|
||||
*
|
||||
* @param Request $request 요청
|
||||
* @return array
|
||||
* @param Request $request 요청
|
||||
* @return array 결제 정보 배열
|
||||
*/
|
||||
public function toArray(Request $request): array
|
||||
{
|
||||
@@ -26,15 +30,30 @@ class OrderPaymentResource extends BaseApiResource
|
||||
'payment_method' => $this->payment_method,
|
||||
'payment_method_label' => $this->payment_method ? $this->payment_method->label() : null,
|
||||
'payment_type_label' => $this->payment_method ? $this->payment_method->label() : null,
|
||||
// PG 환불(취소)이 필요한 결제수단인지 — 취소 모달의 'PG 함께 취소' 체크박스·'환불 우선순위' 라디오
|
||||
// 노출 여부 SSoT(무통장/포인트/예치금/무료는 false → 두 UI 숨김). U1·A28 공유 플래그.
|
||||
'requires_pg_cancellation' => (bool) $this->payment_method?->needsPgProvider(),
|
||||
'pg_provider' => $this->pg_provider,
|
||||
'transaction_id' => $this->transaction_id,
|
||||
'merchant_order_id' => $this->merchant_order_id,
|
||||
'payment_number' => $this->merchant_order_id,
|
||||
'paid_amount_local' => $this->paid_amount_local,
|
||||
'paid_amount_formatted' => number_format($this->paid_amount_local).'원',
|
||||
'vat_amount' => $this->vat_amount,
|
||||
'vat_amount_formatted' => number_format($this->vat_amount).'원',
|
||||
// 결제 통화(order_currency) 실청구액. paid_amount_local 은 PG 가 실제 청구한 결제 통화
|
||||
// 금액이므로 결제 통화 기호로 포맷한다(base≠결제 통화일 때 base 기호로 표기하면 단위 불일치).
|
||||
'paid_amount_local' => $this->roundToCurrency($this->paid_amount_local, $this->paymentCurrencyCode()),
|
||||
'paid_amount_formatted' => $this->formatCurrencyPrice(
|
||||
$this->roundToCurrency($this->paid_amount_local, $this->paymentCurrencyCode()),
|
||||
$this->paymentCurrencyCode()
|
||||
),
|
||||
// base 통화(주문 시점 기준 통화) 환산 실청구액 — 결제 통화와 다를 때 병기용.
|
||||
'paid_amount_base' => $this->roundToOrderCurrency($this->paid_amount_base),
|
||||
'paid_amount_base_formatted' => $this->formatOrderCurrency($this->paid_amount_base),
|
||||
'vat_amount' => $this->roundToOrderCurrency($this->vat_amount),
|
||||
'vat_amount_formatted' => $this->formatOrderCurrency($this->vat_amount),
|
||||
// 결제 통화 코드(order_currency) — 화면 "결제 통화" 표기 SSoT. base 통화는 base_currency.
|
||||
'currency' => $this->currency,
|
||||
'payment_currency' => $this->paymentCurrencyCode(),
|
||||
'base_currency' => $this->orderBaseCurrencyCode(),
|
||||
'is_cross_currency' => $this->paymentCurrencyCode() !== $this->orderBaseCurrencyCode(),
|
||||
|
||||
// 카드 정보
|
||||
'card_name' => $this->card_name,
|
||||
@@ -47,14 +66,18 @@ class OrderPaymentResource extends BaseApiResource
|
||||
'vbank_name' => $this->vbank_name,
|
||||
'vbank_number' => $this->vbank_number,
|
||||
'vbank_holder' => $this->vbank_holder,
|
||||
'vbank_due_at' => $this->vbank_due_at?->toIso8601String(),
|
||||
// vbank_due_at 은 PG 플러그인(kginicis/nicepayments) JS injector 가 new Date() 로
|
||||
// 파싱·재포맷하는 머신 ISO8601 값이므로 raw 유지. 화면 표시는 vbank_due_at_formatted 사용.
|
||||
'vbank_due_at' => $this->vbank_due_at?->toIso8601String(), // audit:allow datetime-display-user-timezone reason: machine ISO8601 parsed by PG plugin JS injectors, display uses *_formatted sibling
|
||||
'vbank_due_at_formatted' => $this->formatDateTimeStringForUser($this->vbank_due_at),
|
||||
|
||||
// 무통장입금 정보
|
||||
'dbank_name' => $this->dbank_name,
|
||||
'dbank_account' => $this->dbank_account,
|
||||
'dbank_holder' => $this->dbank_holder,
|
||||
'depositor_name' => $this->depositor_name,
|
||||
'deposit_due_at' => $this->deposit_due_at?->toIso8601String(),
|
||||
// 머신 ISO8601 — 표시는 deposit_due_at_formatted 사용
|
||||
'deposit_due_at' => $this->deposit_due_at?->toIso8601String(), // audit:allow datetime-display-user-timezone reason: machine ISO8601, display uses deposit_due_at_formatted sibling
|
||||
'deposit_due_at_formatted' => $this->formatDateTimeStringForUser($this->deposit_due_at),
|
||||
|
||||
// 현금영수증
|
||||
@@ -65,19 +88,48 @@ class OrderPaymentResource extends BaseApiResource
|
||||
'account_info' => $this->getAccountInfo(),
|
||||
|
||||
// 일시
|
||||
'payment_started_at' => $this->payment_started_at?->toIso8601String(),
|
||||
// 머신 ISO8601 — 표시는 requested_at_formatted / paid_at_formatted 사용
|
||||
'payment_started_at' => $this->payment_started_at?->toIso8601String(), // audit:allow datetime-display-user-timezone reason: machine ISO8601, display uses requested_at_formatted sibling
|
||||
'requested_at_formatted' => $this->formatDateTimeStringForUser($this->payment_started_at),
|
||||
'paid_at' => $this->paid_at?->toIso8601String(),
|
||||
// paid_at 은 PG 플러그인 레이아웃 if 조건(truthiness)·JS 에서 참조하는 머신 ISO8601 값
|
||||
'paid_at' => $this->paid_at?->toIso8601String(), // audit:allow datetime-display-user-timezone reason: machine ISO8601 used in layout if conditions, display uses paid_at_formatted sibling
|
||||
'paid_at_formatted' => $this->formatDateTimeStringForUser($this->paid_at),
|
||||
'due_date_formatted' => $this->formatDateTimeStringForUser($this->vbank_due_at ?? $this->deposit_due_at),
|
||||
|
||||
// 취소
|
||||
'cancelled_at' => $this->cancelled_at?->toIso8601String(),
|
||||
'cancelled_amount' => $this->cancelled_amount,
|
||||
// 머신 ISO8601 — 표시 미사용(현 화면 노출 없음)
|
||||
'cancelled_at' => $this->cancelled_at?->toIso8601String(), // audit:allow datetime-display-user-timezone reason: machine ISO8601, not a display field
|
||||
'cancelled_amount' => $this->roundToOrderCurrency($this->cancelled_amount),
|
||||
'cancel_reason' => $this->cancel_reason,
|
||||
];
|
||||
}
|
||||
|
||||
/**
|
||||
* 결제 통화(order_currency) 코드를 반환합니다.
|
||||
*
|
||||
* 결제 레코드의 currency 컬럼(주문 시점 order_currency)을 우선 사용하고,
|
||||
* 없으면 스냅샷 order_currency → 기본 통화 순으로 폴백합니다.
|
||||
*
|
||||
* @return string 결제 통화 코드
|
||||
*/
|
||||
private function paymentCurrencyCode(): string
|
||||
{
|
||||
return $this->currency
|
||||
?: (data_get($this->currency_snapshot, 'order_currency')
|
||||
?: $this->orderBaseCurrencyCode());
|
||||
}
|
||||
|
||||
/**
|
||||
* 주문 시점 기준 통화(base_currency) 코드를 반환합니다.
|
||||
*
|
||||
* @return string base 통화 코드
|
||||
*/
|
||||
private function orderBaseCurrencyCode(): string
|
||||
{
|
||||
return data_get($this->currency_snapshot, 'base_currency')
|
||||
?: $this->getDefaultCurrencyCode();
|
||||
}
|
||||
|
||||
/**
|
||||
* 결제수단별 계좌/카드 요약 정보를 반환합니다.
|
||||
*
|
||||
@@ -87,7 +139,7 @@ class OrderPaymentResource extends BaseApiResource
|
||||
{
|
||||
$method = $this->payment_method?->value ?? null;
|
||||
|
||||
if ($method === 'card') {
|
||||
if ($method === PaymentMethodEnum::CARD->value) {
|
||||
$info = $this->card_name ?? '';
|
||||
if ($this->card_number_masked) {
|
||||
$info .= ' '.$this->card_number_masked;
|
||||
@@ -101,7 +153,7 @@ class OrderPaymentResource extends BaseApiResource
|
||||
return trim($info) ?: null;
|
||||
}
|
||||
|
||||
if ($method === 'vbank') {
|
||||
if ($method === PaymentMethodEnum::VBANK->value) {
|
||||
$info = $this->vbank_name ?? '';
|
||||
if ($this->vbank_number) {
|
||||
$info .= ' '.$this->vbank_number;
|
||||
@@ -110,11 +162,15 @@ class OrderPaymentResource extends BaseApiResource
|
||||
return trim($info) ?: null;
|
||||
}
|
||||
|
||||
if ($method === 'bank_transfer') {
|
||||
// 무통장입금(dbank): 은행명 + 계좌번호 (+ 예금주) 요약.
|
||||
if ($method === PaymentMethodEnum::DBANK->value) {
|
||||
$info = $this->dbank_name ?? '';
|
||||
if ($this->dbank_account) {
|
||||
$info .= ' '.$this->dbank_account;
|
||||
}
|
||||
if ($this->dbank_holder) {
|
||||
$info .= ' ('.$this->dbank_holder.')';
|
||||
}
|
||||
|
||||
return trim($info) ?: null;
|
||||
}
|
||||
|
||||
@@ -13,57 +13,80 @@ use Modules\Sirsoft\Ecommerce\Http\Resources\Traits\HasMultiCurrencyPrices;
|
||||
class OrderResource extends BaseApiResource
|
||||
{
|
||||
use HasMultiCurrencyPrices;
|
||||
|
||||
/**
|
||||
* 리소스를 배열로 변환
|
||||
*
|
||||
* @param Request $request 요청
|
||||
* @return array
|
||||
* @param Request $request 요청
|
||||
* @return array<string, mixed> 직렬화된 주문 리소스 배열
|
||||
*/
|
||||
public function toArray(Request $request): array
|
||||
{
|
||||
// 주문 시점 기준 통화 — 과거 주문의 *_formatted 는 설정 변경과 무관하게 이 통화로 고정 표기한다.
|
||||
$orderCurrency = $this->resolveOrderBaseCurrencyCode($this->resource);
|
||||
|
||||
// 결제 통화(order_currency) — 유저가 선택·결제한 통화. base 통화와 다를 때 화면에 함께 표기한다.
|
||||
$paymentCurrency = $this->currency
|
||||
?: (data_get($this->currency_snapshot, 'order_currency') ?: $orderCurrency);
|
||||
|
||||
return [
|
||||
'id' => $this->id,
|
||||
'order_number' => $this->order_number,
|
||||
// 주문 금액 표기 기준 통화(base_currency) — 모든 *_formatted 의 통화. 다통화 병기 시 base 제외 필터에 사용.
|
||||
'base_currency' => $orderCurrency,
|
||||
// 결제 통화(order_currency) + base≠결제 통화 여부.
|
||||
'payment_currency' => $paymentCurrency,
|
||||
'is_cross_currency' => $paymentCurrency !== $orderCurrency,
|
||||
'order_status' => $this->order_status,
|
||||
'order_status_label' => $this->order_status ? $this->order_status->label() : null,
|
||||
'order_status_variant' => $this->order_status ? $this->order_status->variant() : null,
|
||||
// 부분취소 파생 플래그 — 일부 옵션만 취소된 주문(취소옵션 ∧ 잔여 활성옵션). 별도 order_status 아님.
|
||||
// 주문 상태는 잔여 활성 옵션 기준으로 결정되고, "일부 취소됨" 표시는 이 플래그로 한다 (partial_cancelled 제거).
|
||||
'is_partially_cancelled' => $this->isPartiallyCancelled(),
|
||||
'order_device' => $this->order_device,
|
||||
'order_device_label' => $this->order_device ? $this->order_device->label() : null,
|
||||
'is_first_order' => $this->is_first_order,
|
||||
|
||||
// 금액
|
||||
'subtotal_amount' => $this->subtotal_amount,
|
||||
'subtotal_amount_formatted' => number_format($this->subtotal_amount).'원',
|
||||
'total_discount_amount' => $this->total_discount_amount,
|
||||
'total_discount_amount_formatted' => number_format($this->total_discount_amount).'원',
|
||||
'total_shipping_amount' => $this->total_shipping_amount,
|
||||
'total_shipping_amount_formatted' => number_format($this->total_shipping_amount).'원',
|
||||
'total_amount' => $this->total_amount,
|
||||
'total_amount_formatted' => number_format($this->total_amount).'원',
|
||||
'total_paid_amount' => $this->total_paid_amount,
|
||||
'total_paid_amount_formatted' => number_format($this->total_paid_amount).'원',
|
||||
'total_cancelled_amount' => $this->total_cancelled_amount,
|
||||
'total_cancelled_amount_formatted' => number_format($this->total_cancelled_amount).'원',
|
||||
'total_refunded_amount' => $this->total_refunded_amount,
|
||||
'total_refunded_amount_formatted' => number_format($this->total_refunded_amount).'원',
|
||||
'subtotal_amount' => $this->roundToOrderCurrency($this->subtotal_amount, $orderCurrency),
|
||||
'subtotal_amount_formatted' => $this->formatOrderCurrency($this->subtotal_amount, $orderCurrency),
|
||||
'total_discount_amount' => $this->roundToOrderCurrency($this->total_discount_amount, $orderCurrency),
|
||||
'total_discount_amount_formatted' => $this->formatOrderCurrency($this->total_discount_amount, $orderCurrency),
|
||||
'total_shipping_amount' => $this->roundToOrderCurrency($this->total_shipping_amount, $orderCurrency),
|
||||
'total_shipping_amount_formatted' => $this->formatOrderCurrency($this->total_shipping_amount, $orderCurrency),
|
||||
'total_amount' => $this->roundToOrderCurrency($this->total_amount, $orderCurrency),
|
||||
'total_amount_formatted' => $this->formatOrderCurrency($this->total_amount, $orderCurrency),
|
||||
'total_paid_amount' => $this->roundToOrderCurrency($this->total_paid_amount, $orderCurrency),
|
||||
'total_paid_amount_formatted' => $this->formatOrderCurrency($this->total_paid_amount, $orderCurrency),
|
||||
// 입금 필요액(무통장 입금확인 모달의 기본 입금액·결제예정금액 표시 SSoT)
|
||||
'total_due_amount' => $this->roundToOrderCurrency((float) $this->total_due_amount, $orderCurrency),
|
||||
'total_due_amount_formatted' => $this->formatOrderCurrency((float) $this->total_due_amount, $orderCurrency),
|
||||
// 입금자명(무통장 입금확인 모달 기본값) — payment 관계 로드 시에만 노출 (N+1 방지)
|
||||
'depositor_name' => $this->whenLoaded('payment', fn () => $this->payment?->depositor_name),
|
||||
'total_cancelled_amount' => $this->roundToOrderCurrency($this->total_cancelled_amount, $orderCurrency),
|
||||
'total_cancelled_amount_formatted' => $this->formatOrderCurrency($this->total_cancelled_amount, $orderCurrency),
|
||||
'total_refunded_amount' => $this->roundToOrderCurrency($this->total_refunded_amount, $orderCurrency),
|
||||
'total_refunded_amount_formatted' => $this->formatOrderCurrency($this->total_refunded_amount, $orderCurrency),
|
||||
'total_refunded_points_amount' => $this->roundToOrderCurrency($this->total_refunded_points_amount, $orderCurrency),
|
||||
'total_refunded_points_amount_formatted' => $this->formatOrderCurrency($this->total_refunded_points_amount, $orderCurrency),
|
||||
|
||||
// 할인 상세
|
||||
'total_product_coupon_discount_amount' => $this->total_product_coupon_discount_amount,
|
||||
'total_product_coupon_discount_amount_formatted' => number_format($this->total_product_coupon_discount_amount).'원',
|
||||
'total_order_coupon_discount_amount' => $this->total_order_coupon_discount_amount,
|
||||
'total_order_coupon_discount_amount_formatted' => number_format($this->total_order_coupon_discount_amount).'원',
|
||||
'total_coupon_discount_amount' => $this->total_coupon_discount_amount,
|
||||
'total_coupon_discount_amount_formatted' => number_format($this->total_coupon_discount_amount).'원',
|
||||
'total_code_discount_amount' => $this->total_code_discount_amount,
|
||||
'total_code_discount_amount_formatted' => number_format($this->total_code_discount_amount).'원',
|
||||
'total_product_coupon_discount_amount' => $this->roundToOrderCurrency($this->total_product_coupon_discount_amount, $orderCurrency),
|
||||
'total_product_coupon_discount_amount_formatted' => $this->formatOrderCurrency($this->total_product_coupon_discount_amount, $orderCurrency),
|
||||
'total_order_coupon_discount_amount' => $this->roundToOrderCurrency($this->total_order_coupon_discount_amount, $orderCurrency),
|
||||
'total_order_coupon_discount_amount_formatted' => $this->formatOrderCurrency($this->total_order_coupon_discount_amount, $orderCurrency),
|
||||
'total_coupon_discount_amount' => $this->roundToOrderCurrency($this->total_coupon_discount_amount, $orderCurrency),
|
||||
'total_coupon_discount_amount_formatted' => $this->formatOrderCurrency($this->total_coupon_discount_amount, $orderCurrency),
|
||||
'total_code_discount_amount' => $this->roundToOrderCurrency($this->total_code_discount_amount, $orderCurrency),
|
||||
'total_code_discount_amount_formatted' => $this->formatOrderCurrency($this->total_code_discount_amount, $orderCurrency),
|
||||
|
||||
// 마일리지/예치금
|
||||
'total_points_used_amount' => $this->total_points_used_amount,
|
||||
'total_points_used_amount_formatted' => number_format($this->total_points_used_amount).'원',
|
||||
'total_deposit_used_amount' => $this->total_deposit_used_amount,
|
||||
'total_deposit_used_amount_formatted' => number_format($this->total_deposit_used_amount).'원',
|
||||
'total_earned_points_amount' => $this->total_earned_points_amount,
|
||||
'total_earned_points_amount_formatted' => number_format($this->total_earned_points_amount).'원',
|
||||
'total_points_used_amount' => $this->roundToOrderCurrency($this->total_points_used_amount, $orderCurrency),
|
||||
'total_points_used_amount_formatted' => $this->formatOrderCurrency($this->total_points_used_amount, $orderCurrency),
|
||||
'total_deposit_used_amount' => $this->roundToOrderCurrency($this->total_deposit_used_amount, $orderCurrency),
|
||||
'total_deposit_used_amount_formatted' => $this->formatOrderCurrency($this->total_deposit_used_amount, $orderCurrency),
|
||||
'total_earned_points_amount' => $this->roundToOrderCurrency($this->total_earned_points_amount, $orderCurrency),
|
||||
'total_earned_points_amount_formatted' => $this->formatOrderCurrency($this->total_earned_points_amount, $orderCurrency),
|
||||
|
||||
// 다중 통화 금액 (주문 시점 스냅샷)
|
||||
'mc_subtotal_amount' => $this->formatStoredMultiCurrency($this->mc_subtotal_amount),
|
||||
@@ -82,32 +105,38 @@ class OrderResource extends BaseApiResource
|
||||
'total_quantity' => $this->whenLoaded('options', fn () => $this->options->sum('quantity'), 0),
|
||||
|
||||
// 정가 합계 (스냅샷 기준)
|
||||
'total_list_price' => $this->whenLoaded('options', fn () => $this->options->sum(function ($opt) {
|
||||
'total_list_price' => $this->whenLoaded('options', fn () => $this->roundToOrderCurrency($this->options->sum(function ($opt) {
|
||||
$listPrice = $opt->option_snapshot['list_price'] ?? $opt->product_snapshot['list_price'] ?? $opt->unit_price;
|
||||
return $listPrice * $opt->quantity;
|
||||
}), 0),
|
||||
'total_list_price_formatted' => $this->whenLoaded('options', fn () => number_format($this->options->sum(function ($opt) {
|
||||
$listPrice = $opt->option_snapshot['list_price'] ?? $opt->product_snapshot['list_price'] ?? $opt->unit_price;
|
||||
return $listPrice * $opt->quantity;
|
||||
})).'원', '0원'),
|
||||
|
||||
// 일시
|
||||
'ordered_at' => $this->ordered_at?->toIso8601String(),
|
||||
return $listPrice * $opt->quantity;
|
||||
}), $orderCurrency), 0),
|
||||
'total_list_price_formatted' => $this->whenLoaded('options', fn () => $this->formatOrderCurrency($this->options->sum(function ($opt) {
|
||||
$listPrice = $opt->option_snapshot['list_price'] ?? $opt->product_snapshot['list_price'] ?? $opt->unit_price;
|
||||
|
||||
return $listPrice * $opt->quantity;
|
||||
}), $orderCurrency), $this->formatOrderCurrency(0, $orderCurrency)),
|
||||
|
||||
// 일시 — raw ISO 와 사용자 타임존 변환된 *_formatted 를 함께 제공 (프론트 raw 처리 + 백엔드 사전 포맷 양쪽 지원)
|
||||
'ordered_at' => $this->ordered_at?->toIso8601String(), // audit:allow datetime-display-user-timezone reason: paired with *_formatted user-tz field
|
||||
'ordered_at_formatted' => $this->formatDateTimeStringForUser($this->ordered_at),
|
||||
'paid_at' => $this->paid_at?->toIso8601String(),
|
||||
'paid_at' => $this->paid_at?->toIso8601String(), // audit:allow datetime-display-user-timezone reason: paired with *_formatted user-tz field
|
||||
'paid_at_formatted' => $this->formatDateTimeStringForUser($this->paid_at),
|
||||
'confirmed_at' => $this->confirmed_at?->toIso8601String(),
|
||||
'confirmed_at' => $this->confirmed_at?->toIso8601String(), // audit:allow datetime-display-user-timezone reason: paired with *_formatted user-tz field
|
||||
'confirmed_at_formatted' => $this->formatDateTimeStringForUser($this->confirmed_at),
|
||||
'cancelled_at' => $this->cancelled_at?->toIso8601String(),
|
||||
'delivered_at' => $this->delivered_at?->toIso8601String(),
|
||||
'cancelled_at' => $this->cancelled_at?->toIso8601String(), // audit:allow datetime-display-user-timezone reason: paired with *_formatted user-tz field
|
||||
'cancelled_at_formatted' => $this->formatDateTimeStringForUser($this->cancelled_at),
|
||||
'delivered_at' => $this->delivered_at?->toIso8601String(), // audit:allow datetime-display-user-timezone reason: raw ISO consumed by FE (legacy field, no *_formatted pair)
|
||||
|
||||
// 세금
|
||||
'total_tax_amount' => $this->total_tax_amount,
|
||||
'total_tax_amount_formatted' => number_format($this->total_tax_amount).'원',
|
||||
'total_vat_amount' => $this->total_vat_amount,
|
||||
'total_vat_amount_formatted' => number_format($this->total_vat_amount).'원',
|
||||
'total_tax_free_amount' => $this->total_tax_free_amount,
|
||||
'total_tax_free_amount_formatted' => number_format($this->total_tax_free_amount).'원',
|
||||
'total_tax_amount' => $this->roundToOrderCurrency($this->total_tax_amount, $orderCurrency),
|
||||
'total_tax_amount_formatted' => $this->formatOrderCurrency($this->total_tax_amount, $orderCurrency),
|
||||
'total_vat_amount' => $this->roundToOrderCurrency($this->total_vat_amount, $orderCurrency),
|
||||
'total_vat_amount_formatted' => $this->formatOrderCurrency($this->total_vat_amount, $orderCurrency),
|
||||
// 과세 공급가액(과세금액 − 부가세) — 영수증의 "과세금액" 표시 SSoT (PG 영수증 레이아웃 인라인 계산 대체)
|
||||
'total_taxable_supply_amount' => $this->roundToOrderCurrency((float) $this->total_tax_amount - (float) $this->total_vat_amount, $orderCurrency),
|
||||
'total_taxable_supply_amount_formatted' => $this->formatOrderCurrency((float) $this->total_tax_amount - (float) $this->total_vat_amount, $orderCurrency),
|
||||
'total_tax_free_amount' => $this->roundToOrderCurrency($this->total_tax_free_amount, $orderCurrency),
|
||||
'total_tax_free_amount_formatted' => $this->formatOrderCurrency($this->total_tax_free_amount, $orderCurrency),
|
||||
|
||||
// 회원 정보
|
||||
'user' => $this->whenLoaded('user', fn () => [
|
||||
@@ -132,20 +161,30 @@ class OrderResource extends BaseApiResource
|
||||
'recipient_address' => $this->shippingAddress?->address,
|
||||
'recipient_detail_address' => $this->shippingAddress?->address_detail,
|
||||
'delivery_memo' => $this->shippingAddress?->delivery_memo,
|
||||
'delivery_memo_label' => $this->shippingAddress?->delivery_memo_label,
|
||||
|
||||
// 주문 옵션 (품목)
|
||||
'options' => OrderOptionResource::collection($this->whenLoaded('options')),
|
||||
// 주문 옵션 (품목) — 주문 시점 통화를 자식에 전파
|
||||
'options' => $this->whenLoaded('options', fn () => OrderOptionResource::collection($this->options)->each(
|
||||
fn ($r) => $r->withOrderCurrency($orderCurrency)
|
||||
)),
|
||||
|
||||
// 배송지 정보
|
||||
'shipping_address' => new OrderAddressResource($this->whenLoaded('shippingAddress')),
|
||||
'billing_address' => new OrderAddressResource($this->whenLoaded('billingAddress')),
|
||||
|
||||
// 결제 정보
|
||||
'payment' => new OrderPaymentResource($this->whenLoaded('payment')),
|
||||
'payments' => OrderPaymentResource::collection($this->whenLoaded('payments')),
|
||||
'payment' => $this->whenLoaded('payment', fn () => (new OrderPaymentResource($this->payment))->withOrderCurrency($orderCurrency)),
|
||||
'payments' => $this->whenLoaded('payments', fn () => OrderPaymentResource::collection($this->payments)->each(
|
||||
fn ($r) => $r->withOrderCurrency($orderCurrency)
|
||||
)),
|
||||
|
||||
// 배송 정보
|
||||
'shippings' => OrderShippingResource::collection($this->whenLoaded('shippings')),
|
||||
'shippings' => $this->whenLoaded('shippings', fn () => OrderShippingResource::collection($this->shippings)->each(
|
||||
fn ($r) => $r->withOrderCurrency($orderCurrency)
|
||||
)),
|
||||
|
||||
// 취소 이력 (취소 사유·상세 사유·취소일시 표시용) — 최근 취소가 먼저 오도록 정렬
|
||||
'cancels' => OrderCancelResource::collection($this->whenLoaded('cancels')),
|
||||
|
||||
// 프로모션/배송정책 스냅샷
|
||||
'promotions_applied_snapshot' => $this->promotions_applied_snapshot,
|
||||
@@ -155,9 +194,9 @@ class OrderResource extends BaseApiResource
|
||||
'admin_memo' => $this->admin_memo,
|
||||
'customer_memo' => $this->customer_memo,
|
||||
|
||||
// 시스템
|
||||
'created_at' => $this->created_at?->toIso8601String(),
|
||||
'updated_at' => $this->updated_at?->toIso8601String(),
|
||||
// 시스템 — raw ISO 메타 (프론트가 자체 타임존 처리)
|
||||
'created_at' => $this->created_at?->toIso8601String(), // audit:allow datetime-display-user-timezone reason: system meta raw ISO consumed by FE
|
||||
'updated_at' => $this->updated_at?->toIso8601String(), // audit:allow datetime-display-user-timezone reason: system meta raw ISO consumed by FE
|
||||
|
||||
...$this->resourceMeta($request),
|
||||
];
|
||||
@@ -192,7 +231,7 @@ class OrderResource extends BaseApiResource
|
||||
* can_cancel은 단순 권한이 아닌 "상태 + 환경설정 + 권한" 복합 조건이므로
|
||||
* resolveAbilities()를 override하여 동적으로 계산합니다.
|
||||
*
|
||||
* @param Request $request HTTP 요청 객체
|
||||
* @param Request $request HTTP 요청 객체
|
||||
* @return array<string, bool> 능력 불리언 맵
|
||||
*/
|
||||
protected function resolveAbilities(Request $request): array
|
||||
|
||||
@@ -5,6 +5,7 @@ namespace Modules\Sirsoft\Ecommerce\Http\Resources;
|
||||
use App\Http\Resources\BaseApiResource;
|
||||
use Illuminate\Http\Request;
|
||||
use Modules\Sirsoft\Ecommerce\Http\Resources\Traits\HasMultiCurrencyPrices;
|
||||
use Modules\Sirsoft\Ecommerce\Models\ShippingType;
|
||||
|
||||
/**
|
||||
* 주문 배송 정보 리소스
|
||||
@@ -12,11 +13,12 @@ use Modules\Sirsoft\Ecommerce\Http\Resources\Traits\HasMultiCurrencyPrices;
|
||||
class OrderShippingResource extends BaseApiResource
|
||||
{
|
||||
use HasMultiCurrencyPrices;
|
||||
|
||||
/**
|
||||
* 리소스를 배열로 변환
|
||||
*
|
||||
* @param Request $request 요청
|
||||
* @return array
|
||||
* @param Request $request 요청
|
||||
* @return array 주문 배송 정보 리소스 배열 (운송장 URL·다중 통화 포함)
|
||||
*/
|
||||
public function toArray(Request $request): array
|
||||
{
|
||||
@@ -28,19 +30,19 @@ class OrderShippingResource extends BaseApiResource
|
||||
'shipping_status_variant' => $this->shipping_status ? $this->shipping_status->variant() : null,
|
||||
'shipping_type' => $this->shipping_type,
|
||||
'shipping_type_label' => $this->shipping_type
|
||||
? \Modules\Sirsoft\Ecommerce\Models\ShippingType::getCachedByCode($this->shipping_type)?->getLocalizedName()
|
||||
? ShippingType::getCachedByCode($this->shipping_type)?->getLocalizedName()
|
||||
: null,
|
||||
'shipping_method' => $this->delivery_policy_snapshot['shipping_method'] ?? null,
|
||||
'shipping_method_label' => $this->resolveSnapshotShippingMethodLabel(),
|
||||
'shipping_policy_id' => $this->shipping_policy_id,
|
||||
'base_shipping_amount' => $this->base_shipping_amount,
|
||||
'base_shipping_amount_formatted' => number_format($this->base_shipping_amount).'원',
|
||||
'extra_shipping_amount' => $this->extra_shipping_amount,
|
||||
'extra_shipping_amount_formatted' => number_format($this->extra_shipping_amount).'원',
|
||||
'total_shipping_amount' => $this->total_shipping_amount,
|
||||
'total_shipping_amount_formatted' => number_format($this->total_shipping_amount).'원',
|
||||
'shipping_discount_amount' => $this->shipping_discount_amount,
|
||||
'shipping_discount_amount_formatted' => number_format($this->shipping_discount_amount).'원',
|
||||
'base_shipping_amount' => $this->roundToOrderCurrency($this->base_shipping_amount),
|
||||
'base_shipping_amount_formatted' => $this->formatOrderCurrency($this->base_shipping_amount),
|
||||
'extra_shipping_amount' => $this->roundToOrderCurrency($this->extra_shipping_amount),
|
||||
'extra_shipping_amount_formatted' => $this->formatOrderCurrency($this->extra_shipping_amount),
|
||||
'total_shipping_amount' => $this->roundToOrderCurrency($this->total_shipping_amount),
|
||||
'total_shipping_amount_formatted' => $this->formatOrderCurrency($this->total_shipping_amount),
|
||||
'shipping_discount_amount' => $this->roundToOrderCurrency($this->shipping_discount_amount),
|
||||
'shipping_discount_amount_formatted' => $this->formatOrderCurrency($this->shipping_discount_amount),
|
||||
'is_remote_area' => $this->is_remote_area,
|
||||
'delivery_policy_snapshot' => $this->delivery_policy_snapshot,
|
||||
// 다중 통화
|
||||
@@ -51,12 +53,12 @@ class OrderShippingResource extends BaseApiResource
|
||||
'mc_return_shipping_amount' => $this->formatStoredMultiCurrency($this->mc_return_shipping_amount),
|
||||
'carrier_id' => $this->carrier_id,
|
||||
'carrier_name' => $this->carrier?->getLocalizedName(),
|
||||
'carrier_code' => $this->carrier_code,
|
||||
'carrier_code' => $this->carrier?->code,
|
||||
'tracking_number' => $this->tracking_number,
|
||||
'tracking_url' => $this->tracking_url,
|
||||
'shipped_at' => $this->shipped_at?->toIso8601String(),
|
||||
'tracking_url' => $this->getTrackingUrl(),
|
||||
'shipped_at' => $this->shipped_at?->toIso8601String(), // audit:allow datetime-display-user-timezone reason: paired with *_formatted user-tz field
|
||||
'shipped_at_formatted' => $this->formatDateTimeStringForUser($this->shipped_at),
|
||||
'delivered_at' => $this->delivered_at?->toIso8601String(),
|
||||
'delivered_at' => $this->delivered_at?->toIso8601String(), // audit:allow datetime-display-user-timezone reason: paired with *_formatted user-tz field
|
||||
'delivered_at_formatted' => $this->formatDateTimeStringForUser($this->delivered_at),
|
||||
'package_group_id' => $this->package_group_id,
|
||||
'visit_pickup_store_id' => $this->visit_pickup_store_id,
|
||||
@@ -67,8 +69,6 @@ class OrderShippingResource extends BaseApiResource
|
||||
|
||||
/**
|
||||
* 스냅샷 기반 배송방법 라벨을 해석합니다.
|
||||
*
|
||||
* @return string|null
|
||||
*/
|
||||
private function resolveSnapshotShippingMethodLabel(): ?string
|
||||
{
|
||||
@@ -90,6 +90,6 @@ class OrderShippingResource extends BaseApiResource
|
||||
return null;
|
||||
}
|
||||
|
||||
return \Modules\Sirsoft\Ecommerce\Models\ShippingType::getCachedByCode($method)?->getLocalizedName();
|
||||
return ShippingType::getCachedByCode($method)?->getLocalizedName();
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,54 @@
|
||||
<?php
|
||||
|
||||
namespace Modules\Sirsoft\Ecommerce\Http\Resources;
|
||||
|
||||
use App\Http\Resources\BaseApiResource;
|
||||
use Illuminate\Http\Request;
|
||||
|
||||
/**
|
||||
* 대시보드 미답변 문의 리소스
|
||||
*
|
||||
* 관리자 대시보드 미답변 문의 카드에 표시할 최소 필드만 노출합니다.
|
||||
*/
|
||||
class PendingInquiryResource extends BaseApiResource
|
||||
{
|
||||
/**
|
||||
* 리소스를 배열로 변환합니다.
|
||||
*
|
||||
* @param Request $request HTTP 요청
|
||||
* @return array<string, mixed> 변환된 배열 데이터
|
||||
*/
|
||||
public function toArray(Request $request): array
|
||||
{
|
||||
return [
|
||||
'id' => $this->id,
|
||||
'product_id' => $this->product_id,
|
||||
// 상품 문의 원본은 게시판 Post (inquirable). 관리자 상세는 게시판 글 상세로 이동한다.
|
||||
'inquirable_id' => $this->inquirable_id,
|
||||
'product_name' => $this->getLocalizedProductName(),
|
||||
'author_name' => $this->user?->name ?? '',
|
||||
'created_at' => $this->formatDateTimeStringForUser($this->created_at),
|
||||
];
|
||||
}
|
||||
|
||||
/**
|
||||
* 현재 로케일에 맞는 상품명 스냅샷을 반환합니다.
|
||||
*
|
||||
* @return string 로케일별 상품명 (없으면 빈 문자열)
|
||||
*/
|
||||
private function getLocalizedProductName(): string
|
||||
{
|
||||
$snapshot = $this->product_name_snapshot;
|
||||
|
||||
if (empty($snapshot)) {
|
||||
return $this->product?->getLocalizedName() ?? '';
|
||||
}
|
||||
|
||||
$locale = app()->getLocale();
|
||||
|
||||
return $snapshot[$locale]
|
||||
?? $snapshot[config('app.fallback_locale', 'ko')]
|
||||
?? array_values($snapshot)[0]
|
||||
?? '';
|
||||
}
|
||||
}
|
||||
@@ -6,6 +6,7 @@ use App\Http\Resources\BaseApiCollection;
|
||||
use App\Http\Resources\Traits\HasAbilityCheck;
|
||||
use Illuminate\Http\Request;
|
||||
use Illuminate\Pagination\LengthAwarePaginator;
|
||||
use Modules\Sirsoft\Ecommerce\Http\Resources\Traits\HasMultiCurrencyPrices;
|
||||
|
||||
/**
|
||||
* 상품 컬렉션 리소스
|
||||
@@ -15,6 +16,7 @@ use Illuminate\Pagination\LengthAwarePaginator;
|
||||
class ProductCollection extends BaseApiCollection
|
||||
{
|
||||
use HasAbilityCheck;
|
||||
use HasMultiCurrencyPrices;
|
||||
|
||||
/**
|
||||
* 컬렉션 레벨 능력(can_*) 매핑을 반환합니다.
|
||||
@@ -33,7 +35,7 @@ class ProductCollection extends BaseApiCollection
|
||||
/**
|
||||
* 상품 컬렉션을 배열로 변환합니다.
|
||||
*
|
||||
* @param Request $request HTTP 요청 객체
|
||||
* @param Request $request HTTP 요청 객체
|
||||
* @return array<int|string, mixed> 변환된 상품 컬렉션 배열
|
||||
*/
|
||||
public function toArray(Request $request): array
|
||||
@@ -63,7 +65,7 @@ class ProductCollection extends BaseApiCollection
|
||||
/**
|
||||
* 통계가 포함된 형태의 배열을 반환합니다.
|
||||
*
|
||||
* @param array $statistics 통계 데이터 배열
|
||||
* @param array $statistics 통계 데이터 배열
|
||||
* @return array<string, mixed> 통계 정보가 포함된 상품 컬렉션
|
||||
*/
|
||||
public function withStatistics(array $statistics = []): array
|
||||
@@ -103,7 +105,7 @@ class ProductCollection extends BaseApiCollection
|
||||
'id' => $product->id,
|
||||
'name' => $product->getLocalizedName(),
|
||||
'product_code' => $product->product_code,
|
||||
'selling_price' => $product->selling_price,
|
||||
'selling_price' => $this->roundToBaseCurrency($product->selling_price),
|
||||
];
|
||||
})->toArray();
|
||||
}
|
||||
|
||||
+3
-3
@@ -2,9 +2,9 @@
|
||||
|
||||
namespace Modules\Sirsoft\Ecommerce\Http\Resources;
|
||||
|
||||
use App\Http\Resources\BaseApiCollection;
|
||||
use App\Http\Resources\Traits\HasAbilityCheck;
|
||||
use Illuminate\Http\Request;
|
||||
use App\Http\Resources\BaseApiCollection;
|
||||
|
||||
/**
|
||||
* 공통정보 템플릿 컬렉션 리소스
|
||||
@@ -44,9 +44,9 @@ class ProductCommonInfoCollection extends BaseApiCollection
|
||||
*/
|
||||
public function toArray(Request $request): array
|
||||
{
|
||||
return [
|
||||
return array_merge([
|
||||
'data' => $this->collection,
|
||||
'abilities' => $this->resolveAbilitiesFromMap($this->abilityMap(), $request->user()),
|
||||
];
|
||||
], $this->paginationMeta());
|
||||
}
|
||||
}
|
||||
@@ -17,6 +17,7 @@ class ProductListResource extends BaseApiResource
|
||||
* 리소스를 배열로 변환
|
||||
*
|
||||
* @param Request $request 요청
|
||||
* @return array 상품 목록 리소스 배열 (다중 통화 가격 포함)
|
||||
*/
|
||||
public function toArray(Request $request): array
|
||||
{
|
||||
@@ -29,10 +30,10 @@ class ProductListResource extends BaseApiResource
|
||||
'thumbnail_url' => $this->getThumbnailUrl(),
|
||||
|
||||
// 가격
|
||||
'list_price' => $this->list_price,
|
||||
'list_price_formatted' => number_format($this->list_price).'원',
|
||||
'selling_price' => $this->selling_price,
|
||||
'selling_price_formatted' => number_format($this->selling_price).'원',
|
||||
'list_price' => $this->roundToBaseCurrency($this->list_price),
|
||||
'list_price_formatted' => $this->formatBaseCurrency($this->list_price),
|
||||
'selling_price' => $this->roundToBaseCurrency($this->selling_price),
|
||||
'selling_price_formatted' => $this->formatBaseCurrency($this->selling_price),
|
||||
'discount_rate' => $this->getDiscountRate(),
|
||||
|
||||
// 다중 통화 가격
|
||||
@@ -130,8 +131,6 @@ class ProductListResource extends BaseApiResource
|
||||
|
||||
/**
|
||||
* 소유자 필드명을 반환합니다.
|
||||
*
|
||||
* @return string|null
|
||||
*/
|
||||
protected function ownerField(): ?string
|
||||
{
|
||||
|
||||
+3
-3
@@ -2,9 +2,9 @@
|
||||
|
||||
namespace Modules\Sirsoft\Ecommerce\Http\Resources;
|
||||
|
||||
use App\Http\Resources\BaseApiCollection;
|
||||
use App\Http\Resources\Traits\HasAbilityCheck;
|
||||
use Illuminate\Http\Request;
|
||||
use App\Http\Resources\BaseApiCollection;
|
||||
|
||||
/**
|
||||
* 상품정보제공고시 템플릿 컬렉션 리소스
|
||||
@@ -44,9 +44,9 @@ class ProductNoticeTemplateCollection extends BaseApiCollection
|
||||
*/
|
||||
public function toArray(Request $request): array
|
||||
{
|
||||
return [
|
||||
return array_merge([
|
||||
'data' => $this->collection,
|
||||
'abilities' => $this->resolveAbilitiesFromMap($this->abilityMap(), $request->user()),
|
||||
];
|
||||
], $this->paginationMeta());
|
||||
}
|
||||
}
|
||||
@@ -17,6 +17,7 @@ class ProductOptionResource extends BaseApiResource
|
||||
* 리소스를 배열로 변환
|
||||
*
|
||||
* @param Request $request 요청
|
||||
* @return array<string, mixed> 옵션 리소스 배열
|
||||
*/
|
||||
public function toArray(Request $request): array
|
||||
{
|
||||
@@ -35,18 +36,18 @@ class ProductOptionResource extends BaseApiResource
|
||||
'option_name' => $this->option_name,
|
||||
'option_name_localized' => $this->resource->getLocalizedOptionName(),
|
||||
|
||||
'price_adjustment' => $this->price_adjustment,
|
||||
'price_adjustment' => $this->roundToBaseCurrency($this->price_adjustment),
|
||||
'price_adjustment_formatted' => ($this->price_adjustment >= 0 ? '+' : '').$this->formatCurrencyPrice(abs($this->price_adjustment), $this->getDefaultCurrencyCode()),
|
||||
'price_adjustment_type' => $this->price_adjustment >= 0 ? 'increase' : 'decrease',
|
||||
|
||||
// 정가/판매가 분리
|
||||
'list_price' => $listPrice,
|
||||
'list_price' => $this->roundToBaseCurrency($listPrice),
|
||||
'list_price_formatted' => $this->formatCurrencyPrice($listPrice, $this->getDefaultCurrencyCode()),
|
||||
'selling_price' => $sellingPrice,
|
||||
'selling_price' => $this->roundToBaseCurrency($sellingPrice),
|
||||
'selling_price_formatted' => $this->formatCurrencyPrice($sellingPrice, $this->getDefaultCurrencyCode()),
|
||||
|
||||
// 기존 호환성 유지
|
||||
'final_price' => $sellingPrice,
|
||||
'final_price' => $this->roundToBaseCurrency($sellingPrice),
|
||||
'final_price_formatted' => $this->formatCurrencyPrice($sellingPrice, $this->getDefaultCurrencyCode()),
|
||||
|
||||
// 다중 통화 가격
|
||||
@@ -57,6 +58,8 @@ class ProductOptionResource extends BaseApiResource
|
||||
'stock_quantity' => $this->stock_quantity,
|
||||
'safe_stock_quantity' => $this->safe_stock_quantity,
|
||||
'is_below_safe_stock' => $this->isBelowSafeStock(),
|
||||
// 품절 여부 — 재고 0 이하이거나 비활성 옵션 (프론트 드롭다운 비활성/라벨용, MP07 §2-b)
|
||||
'is_sold_out' => ($this->stock_quantity ?? 0) <= 0 || ! $this->is_active,
|
||||
|
||||
// 상태
|
||||
'is_default' => $this->is_default,
|
||||
|
||||
@@ -4,17 +4,20 @@ namespace Modules\Sirsoft\Ecommerce\Http\Resources;
|
||||
|
||||
use App\Http\Resources\BaseApiResource;
|
||||
use Illuminate\Http\Request;
|
||||
use Modules\Sirsoft\Ecommerce\Http\Resources\Traits\HasMultiCurrencyPrices;
|
||||
|
||||
/**
|
||||
* 상품 상세 리소스
|
||||
*/
|
||||
class ProductResource extends BaseApiResource
|
||||
{
|
||||
use HasMultiCurrencyPrices;
|
||||
|
||||
/**
|
||||
* 리소스를 배열로 변환
|
||||
*
|
||||
* @param Request $request 요청
|
||||
* @return array
|
||||
* @return array 상품 배열
|
||||
*/
|
||||
public function toArray(Request $request): array
|
||||
{
|
||||
@@ -41,9 +44,9 @@ class ProductResource extends BaseApiResource
|
||||
// 브랜드
|
||||
'brand_id' => $this->brand_id,
|
||||
|
||||
// 가격
|
||||
'list_price' => $this->list_price,
|
||||
'selling_price' => $this->selling_price,
|
||||
// 가격 (기본 통화 자릿수로 정규화 — JPY/KRW 0자리는 정수)
|
||||
'list_price' => $this->roundToBaseCurrency($this->list_price),
|
||||
'selling_price' => $this->roundToBaseCurrency($this->selling_price),
|
||||
'discount_rate' => $this->getDiscountRate(),
|
||||
|
||||
// 재고
|
||||
@@ -63,6 +66,15 @@ class ProductResource extends BaseApiResource
|
||||
|
||||
// 배송
|
||||
'shipping_policy_id' => $this->shipping_policy_id,
|
||||
// 현재 부여된 배송정책 객체 (비활성 포함) — 수정폼에서 활성 목록에 없을 때 union 표시용
|
||||
'shipping_policy' => $this->whenLoaded('shippingPolicy', fn () => $this->shippingPolicy ? [
|
||||
'id' => $this->shippingPolicy->id,
|
||||
'name' => $this->shippingPolicy->name,
|
||||
'is_active' => $this->shippingPolicy->is_active,
|
||||
'is_default' => $this->shippingPolicy->is_default,
|
||||
'fee_summary' => $this->shippingPolicy->getFeeSummary(),
|
||||
'country_settings' => $this->shippingPolicy->country_settings,
|
||||
] : null),
|
||||
|
||||
// 공통정보
|
||||
'common_info_id' => $this->common_info_id,
|
||||
@@ -112,6 +124,9 @@ class ProductResource extends BaseApiResource
|
||||
'meta_title' => $this->meta_title,
|
||||
'meta_description' => $this->meta_description,
|
||||
'meta_keywords' => $this->meta_keywords,
|
||||
// SEO 동기화 플래그 (EDIT 폼 form.seo_sync_* 바인딩용 — 동기화 토글 상태 복원)
|
||||
'seo_sync_title' => (bool) $this->seo_sync_title,
|
||||
'seo_sync_description' => (bool) $this->seo_sync_description,
|
||||
|
||||
// 옵션
|
||||
'has_options' => $this->has_options,
|
||||
@@ -120,6 +135,27 @@ class ProductResource extends BaseApiResource
|
||||
$this->relationLoaded('options') ? $this->options : $this->whenLoaded('activeOptions')
|
||||
),
|
||||
|
||||
// 추가옵션 (EDIT 폼 form.additional_options 바인딩용 — getDetailForForm 과 동일 형식)
|
||||
'additional_options' => $this->relationLoaded('additionalOptions')
|
||||
? $this->additionalOptions->sortBy('sort_order')->map(fn ($opt) => [
|
||||
'id' => $opt->id,
|
||||
'name' => $opt->name,
|
||||
'is_required' => $opt->is_required,
|
||||
'sort_order' => $opt->sort_order,
|
||||
'values' => $opt->relationLoaded('values')
|
||||
? $opt->values->sortBy('sort_order')->map(fn ($val) => [
|
||||
'id' => $val->id,
|
||||
'name' => $val->name,
|
||||
'price_adjustment' => $this->roundToBaseCurrency($val->price_adjustment),
|
||||
'is_default' => $val->is_default,
|
||||
'is_active' => $val->is_active,
|
||||
'allow_custom_text' => $val->allow_custom_text,
|
||||
'sort_order' => $val->sort_order,
|
||||
])->values()->toArray()
|
||||
: [],
|
||||
])->values()->toArray()
|
||||
: [],
|
||||
|
||||
// 시스템
|
||||
'created_at' => $this->formatDateTimeStringForUser($this->created_at),
|
||||
'updated_at' => $this->formatDateTimeStringForUser($this->updated_at),
|
||||
|
||||
@@ -4,10 +4,13 @@ namespace Modules\Sirsoft\Ecommerce\Http\Resources;
|
||||
|
||||
use App\Http\Resources\BaseApiResource;
|
||||
use Illuminate\Http\Request;
|
||||
use Modules\Sirsoft\Ecommerce\Enums\ChargePolicyEnum;
|
||||
use Illuminate\Support\Facades\Auth;
|
||||
use Modules\Sirsoft\Ecommerce\Enums\ChargePolicyEnum;
|
||||
use Modules\Sirsoft\Ecommerce\Http\Middleware\ResolveShippingCountry;
|
||||
use Modules\Sirsoft\Ecommerce\Http\Resources\Traits\HasMultiCurrencyPrices;
|
||||
use Modules\Sirsoft\Ecommerce\Models\Product;
|
||||
use Modules\Sirsoft\Ecommerce\Models\ProductWishlist;
|
||||
use Modules\Sirsoft\Ecommerce\Services\ShippingPolicyResolver;
|
||||
|
||||
/**
|
||||
* 공개 상품 상세 리소스
|
||||
@@ -23,7 +26,7 @@ class PublicProductResource extends BaseApiResource
|
||||
* 리소스를 배열로 변환
|
||||
*
|
||||
* @param Request $request 요청
|
||||
* @return array
|
||||
* @return array 공개 상품 리소스 배열 (배송 가능 여부 포함)
|
||||
*/
|
||||
public function toArray(Request $request): array
|
||||
{
|
||||
@@ -35,7 +38,7 @@ class PublicProductResource extends BaseApiResource
|
||||
'sku' => $this->sku,
|
||||
|
||||
// 카테고리
|
||||
'categories' => $this->whenLoaded('categories', fn() => $this->categories->map(fn($cat) => [
|
||||
'categories' => $this->whenLoaded('categories', fn () => $this->categories->map(fn ($cat) => [
|
||||
'id' => $cat->id,
|
||||
'name' => $cat->name,
|
||||
'name_localized' => $cat->getLocalizedName(),
|
||||
@@ -45,14 +48,14 @@ class PublicProductResource extends BaseApiResource
|
||||
])),
|
||||
'category_name' => $this->whenLoaded(
|
||||
'categories',
|
||||
fn() => $this->categories->firstWhere('pivot.is_primary', true)?->getLocalizedName()
|
||||
fn () => $this->categories->firstWhere('pivot.is_primary', true)?->getLocalizedName()
|
||||
),
|
||||
|
||||
// 가격
|
||||
'list_price' => $this->list_price,
|
||||
'list_price_formatted' => number_format($this->list_price) . '원',
|
||||
'selling_price' => $this->selling_price,
|
||||
'selling_price_formatted' => number_format($this->selling_price) . '원',
|
||||
'list_price' => $this->roundToBaseCurrency($this->list_price),
|
||||
'list_price_formatted' => $this->formatBaseCurrency($this->list_price),
|
||||
'selling_price' => $this->roundToBaseCurrency($this->selling_price),
|
||||
'selling_price_formatted' => $this->formatBaseCurrency($this->selling_price),
|
||||
'discount_rate' => $this->getDiscountRate(),
|
||||
|
||||
// 다중 통화 가격
|
||||
@@ -71,36 +74,39 @@ class PublicProductResource extends BaseApiResource
|
||||
'sales_status_label' => $this->sales_status->label(),
|
||||
|
||||
// 브랜드
|
||||
'brand_name' => $this->whenLoaded('brand', fn() => $this->brand?->getLocalizedName()),
|
||||
'brand_name' => $this->whenLoaded('brand', fn () => $this->brand?->getLocalizedName()),
|
||||
|
||||
// 라벨
|
||||
'labels' => $this->whenLoaded('activeLabelAssignments', fn() => $this->activeLabelAssignments->map(fn($a) => [
|
||||
'labels' => $this->whenLoaded('activeLabelAssignments', fn () => $this->activeLabelAssignments->map(fn ($a) => [
|
||||
'name' => $a->label?->getLocalizedName(),
|
||||
'color' => $a->label?->color,
|
||||
])->filter(fn($l) => $l['name'])->values()),
|
||||
])->filter(fn ($l) => $l['name'])->values()),
|
||||
|
||||
// 추가옵션
|
||||
'additional_options' => $this->whenLoaded('additionalOptions', fn() => $this->additionalOptions->sortBy('sort_order')->map(fn($o) => [
|
||||
// 추가옵션 (그룹 + 선택지)
|
||||
'additional_options' => $this->whenLoaded('additionalOptions', fn () => $this->additionalOptions->sortBy('sort_order')->map(fn ($o) => [
|
||||
'id' => $o->id,
|
||||
'name' => $o->getLocalizedName(),
|
||||
'is_required' => $o->is_required,
|
||||
'values' => ($o->relationLoaded('activeValues') ? $o->activeValues : $o->values->where('is_active', true))
|
||||
->sortBy('sort_order')
|
||||
->map(fn ($v) => [
|
||||
'id' => $v->id,
|
||||
'name' => $v->getLocalizedName(),
|
||||
'price_adjustment' => $this->roundToBaseCurrency($v->getPriceAdjustment()),
|
||||
// 추가금 표시 문자열 — 통화 기호 하드코딩 없이 기본 통화 기호로 포맷 (옵션 선택 UI의 '+N원' 대체)
|
||||
'price_adjustment_formatted' => ($v->getPriceAdjustment() >= 0 ? '+' : '-')
|
||||
.$this->formatCurrencyPrice(abs($v->getPriceAdjustment()), $this->getDefaultCurrencyCode()),
|
||||
'is_default' => $v->is_default,
|
||||
// 직접입력 허용 — 유저단이 이 선택지 선택 시 텍스트 입력칸 노출 판정
|
||||
'allow_custom_text' => $v->allow_custom_text,
|
||||
])->values(),
|
||||
])->values()),
|
||||
|
||||
// 배송
|
||||
'shipping_policy_id' => $this->shipping_policy_id,
|
||||
'free_shipping' => $this->whenLoaded('shippingPolicy', fn() => $this->shippingPolicy?->charge_policy === ChargePolicyEnum::FREE, false),
|
||||
'shipping_fee_formatted' => $this->whenLoaded('shippingPolicy', fn() => $this->shippingPolicy?->getFeeSummary() ?? '', ''),
|
||||
'shipping_policy' => $this->whenLoaded('shippingPolicy', fn() => $this->shippingPolicy ? [
|
||||
'name' => $this->shippingPolicy->getLocalizedName(),
|
||||
'charge_policy' => $this->shippingPolicy->charge_policy?->value,
|
||||
'charge_policy_label' => $this->shippingPolicy->charge_policy?->label(),
|
||||
'base_fee' => $this->shippingPolicy->base_fee,
|
||||
'base_fee_formatted' => number_format($this->shippingPolicy->base_fee) . '원',
|
||||
'free_threshold' => $this->shippingPolicy->free_threshold,
|
||||
'free_threshold_formatted' => $this->shippingPolicy->free_threshold
|
||||
? number_format($this->shippingPolicy->free_threshold) . '원' : null,
|
||||
'fee_summary' => $this->shippingPolicy->getFeeSummary(),
|
||||
] : null),
|
||||
// 선택된 배송국가로 배송 가능한지 + 해당 국가 배송비 요약 (B8 — 상품상세 사전 표시)
|
||||
// 상품에 정책이 없으면(shipping_policy_id=null) 기본 배송정책으로 폴백해 표시한다.
|
||||
...$this->buildShippingDisplay(),
|
||||
|
||||
// 설명 (다국어)
|
||||
'short_description' => $this->short_description,
|
||||
@@ -124,7 +130,7 @@ class PublicProductResource extends BaseApiResource
|
||||
'options' => ProductOptionResource::collection($this->whenLoaded('activeOptions')),
|
||||
|
||||
// 상품정보제공고시
|
||||
'notice' => $this->whenLoaded('notice', fn() => $this->notice ? [
|
||||
'notice' => $this->whenLoaded('notice', fn () => $this->notice ? [
|
||||
'template_name' => $this->notice->relationLoaded('template')
|
||||
? $this->notice->template?->getLocalizedName()
|
||||
: null,
|
||||
@@ -144,7 +150,7 @@ class PublicProductResource extends BaseApiResource
|
||||
] : null),
|
||||
|
||||
// 공통정보
|
||||
'common_info' => $this->whenLoaded('commonInfo', fn() => $this->commonInfo ? [
|
||||
'common_info' => $this->whenLoaded('commonInfo', fn () => $this->commonInfo ? [
|
||||
'name' => $this->commonInfo->getLocalizedName(),
|
||||
'content' => $this->commonInfo->getLocalizedContent(),
|
||||
'content_mode' => $this->commonInfo->content_mode ?? 'text',
|
||||
@@ -163,7 +169,6 @@ class PublicProductResource extends BaseApiResource
|
||||
* 다국어 JSON 필드에서 현재 로케일 값을 반환합니다.
|
||||
*
|
||||
* @param array|null $field 다국어 JSON 필드
|
||||
* @return string|null
|
||||
*/
|
||||
private function resolveLocalizedField(?array $field): ?string
|
||||
{
|
||||
@@ -175,4 +180,44 @@ class PublicProductResource extends BaseApiResource
|
||||
|
||||
return $field[$locale] ?? $field[config('app.fallback_locale', 'ko')] ?? $field[array_key_first($field)] ?? null;
|
||||
}
|
||||
|
||||
/**
|
||||
* 배송 표시 필드를 구성합니다 (배송가능 여부 + 배송비 요약 + 정책 상세).
|
||||
*
|
||||
* 상품에 정책이 부여되어 있으면 그 정책을, 없으면(shipping_policy_id=null)
|
||||
* 기본 배송정책으로 폴백해 표시한다. 적용 가능한 정책이 전혀 없을 때만
|
||||
* 국내(KR) 기본 배송으로 간주한다.
|
||||
*
|
||||
* @return array 배송 표시 필드 (is_shippable_to_selected_country 등)
|
||||
*/
|
||||
private function buildShippingDisplay(): array
|
||||
{
|
||||
$country = ResolveShippingCountry::getCountry();
|
||||
$resolver = app(ShippingPolicyResolver::class);
|
||||
|
||||
/** @var Product $product */
|
||||
$product = $this->resource;
|
||||
$policy = $resolver->resolveForProduct($product);
|
||||
|
||||
return [
|
||||
'is_shippable_to_selected_country' => $policy !== null
|
||||
? $policy->getCountrySetting($country) !== null
|
||||
: ($country === 'KR'),
|
||||
'selected_shipping_country' => $country,
|
||||
'free_shipping' => $policy?->charge_policy === ChargePolicyEnum::FREE,
|
||||
'shipping_fee_formatted' => $policy?->getFeeSummary() ?? '',
|
||||
'shipping_policy' => $policy ? [
|
||||
'name' => $policy->getLocalizedName(),
|
||||
'charge_policy' => $policy->charge_policy?->value,
|
||||
'charge_policy_label' => $policy->charge_policy?->label(),
|
||||
'base_fee' => $this->roundToBaseCurrency($policy->base_fee),
|
||||
'base_fee_formatted' => $this->formatBaseCurrency($policy->base_fee),
|
||||
'free_threshold' => $policy->free_threshold !== null
|
||||
? $this->roundToBaseCurrency($policy->free_threshold) : null,
|
||||
'free_threshold_formatted' => $policy->free_threshold
|
||||
? $this->formatBaseCurrency($policy->free_threshold) : null,
|
||||
'fee_summary' => $policy->getFeeSummary(),
|
||||
] : null,
|
||||
];
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,32 @@
|
||||
<?php
|
||||
|
||||
namespace Modules\Sirsoft\Ecommerce\Http\Resources;
|
||||
|
||||
use App\Http\Resources\BaseApiResource;
|
||||
use Illuminate\Http\Request;
|
||||
|
||||
/**
|
||||
* 대시보드 최신 리뷰 리소스
|
||||
*
|
||||
* 관리자 대시보드 최신 리뷰 카드에 표시할 최소 필드만 노출합니다.
|
||||
*/
|
||||
class RecentReviewResource extends BaseApiResource
|
||||
{
|
||||
/**
|
||||
* 리소스를 배열로 변환합니다.
|
||||
*
|
||||
* @param Request $request HTTP 요청
|
||||
* @return array<string, mixed> 변환된 배열 데이터
|
||||
*/
|
||||
public function toArray(Request $request): array
|
||||
{
|
||||
return [
|
||||
'id' => $this->id,
|
||||
'product_id' => $this->product_id,
|
||||
'product_name' => $this->product?->getLocalizedName() ?? '',
|
||||
'rating' => (int) $this->rating,
|
||||
'author_name' => $this->user?->name ?? '',
|
||||
'created_at' => $this->formatDateTimeStringForUser($this->created_at),
|
||||
];
|
||||
}
|
||||
}
|
||||
+37
-9
@@ -4,17 +4,21 @@ namespace Modules\Sirsoft\Ecommerce\Http\Resources;
|
||||
|
||||
use App\Http\Resources\BaseApiResource;
|
||||
use Illuminate\Http\Request;
|
||||
use Modules\Sirsoft\Ecommerce\Http\Resources\Traits\HasMultiCurrencyPrices;
|
||||
use Modules\Sirsoft\Ecommerce\Models\ShippingType;
|
||||
|
||||
/**
|
||||
* 배송정책 국가별 설정 리소스
|
||||
*/
|
||||
class ShippingPolicyCountrySettingResource extends BaseApiResource
|
||||
{
|
||||
use HasMultiCurrencyPrices;
|
||||
|
||||
/**
|
||||
* 리소스를 배열로 변환
|
||||
* 리소스를 배열로 변환합니다.
|
||||
*
|
||||
* @param Request $request 요청
|
||||
* @return array
|
||||
* @param Request $request 요청
|
||||
* @return array<string, mixed> 배송정책 국가별 설정 리소스 배열
|
||||
*/
|
||||
public function toArray(Request $request): array
|
||||
{
|
||||
@@ -34,15 +38,18 @@ class ShippingPolicyCountrySettingResource extends BaseApiResource
|
||||
'charge_policy' => $this->charge_policy?->value,
|
||||
'charge_policy_label' => $this->charge_policy?->label(),
|
||||
|
||||
// 배송비 관련
|
||||
'base_fee' => (float) $this->base_fee,
|
||||
'free_threshold' => $this->free_threshold ? (float) $this->free_threshold : null,
|
||||
// 배송비 관련 (행의 통화 코드 자릿수로 정규화 — 미설정 시 기본 통화)
|
||||
'base_fee' => $this->roundToCurrency($this->base_fee, $this->currency_code ?: $this->getDefaultCurrencyCode()),
|
||||
'free_threshold' => $this->free_threshold !== null
|
||||
? $this->roundToCurrency($this->free_threshold, $this->currency_code ?: $this->getDefaultCurrencyCode())
|
||||
: null,
|
||||
'ranges' => $this->ranges,
|
||||
|
||||
// API 설정
|
||||
'api_endpoint' => $this->api_endpoint,
|
||||
'api_request_fields' => $this->api_request_fields,
|
||||
'api_response_fee_field' => $this->api_response_fee_field,
|
||||
'api_config' => $this->maskApiConfig(),
|
||||
|
||||
// 도서산간
|
||||
'extra_fee_enabled' => $this->extra_fee_enabled,
|
||||
@@ -54,12 +61,33 @@ class ShippingPolicyCountrySettingResource extends BaseApiResource
|
||||
];
|
||||
}
|
||||
|
||||
/**
|
||||
* 계산 API 연동 설정을 응답용으로 변환합니다 (인증 토큰 마스킹).
|
||||
*
|
||||
* auth_token 평문은 응답에 노출하지 않습니다. 대신 설정 여부(has_auth_token)만
|
||||
* 내려, 수정 폼이 토큰 재입력 없이 기존 토큰 유지 여부를 판단할 수 있게 합니다.
|
||||
*
|
||||
* @return array<string, mixed>|null
|
||||
*/
|
||||
private function maskApiConfig(): ?array
|
||||
{
|
||||
$config = $this->api_config;
|
||||
|
||||
if (! is_array($config)) {
|
||||
return null;
|
||||
}
|
||||
|
||||
$hasToken = ! empty($config['auth_token']);
|
||||
unset($config['auth_token']);
|
||||
$config['has_auth_token'] = $hasToken;
|
||||
|
||||
return $config;
|
||||
}
|
||||
|
||||
/**
|
||||
* 배송방법 라벨을 해석합니다.
|
||||
*
|
||||
* custom인 경우 custom_shipping_name에서 현재 로케일 값을 반환합니다.
|
||||
*
|
||||
* @return string|null
|
||||
*/
|
||||
private function resolveShippingMethodLabel(): ?string
|
||||
{
|
||||
@@ -78,6 +106,6 @@ class ShippingPolicyCountrySettingResource extends BaseApiResource
|
||||
return null;
|
||||
}
|
||||
|
||||
return \Modules\Sirsoft\Ecommerce\Models\ShippingType::getCachedByCode($this->shipping_method)?->getLocalizedName();
|
||||
return ShippingType::getCachedByCode($this->shipping_method)?->getLocalizedName();
|
||||
}
|
||||
}
|
||||
+157
-3
@@ -15,6 +15,27 @@ trait HasMultiCurrencyPrices
|
||||
*/
|
||||
private static ?array $currencySettingsCache = null;
|
||||
|
||||
/**
|
||||
* 부모 주문 리소스가 주입한 주문 시점 기준 통화 코드 (자식 리소스용).
|
||||
*
|
||||
* OrderResource 등 부모가 `currency_snapshot.base_currency` 를 추출해 자식
|
||||
* (OrderOption/OrderPayment/OrderShipping) 에 전파한다. null 이면 현재 기본 통화로 폴백.
|
||||
*/
|
||||
protected ?string $orderCurrencyCode = null;
|
||||
|
||||
/**
|
||||
* 주문 시점 기준 통화 코드를 주입합니다 (부모 → 자식 리소스 전파).
|
||||
*
|
||||
* @param string|null $currencyCode 주문 시점 기준 통화 코드
|
||||
* @return $this 메서드 체이닝을 위한 자기 자신
|
||||
*/
|
||||
public function withOrderCurrency(?string $currencyCode): static
|
||||
{
|
||||
$this->orderCurrencyCode = $currencyCode;
|
||||
|
||||
return $this;
|
||||
}
|
||||
|
||||
/**
|
||||
* 다중 통화 가격 정보를 생성합니다.
|
||||
*
|
||||
@@ -24,6 +45,7 @@ trait HasMultiCurrencyPrices
|
||||
protected function buildMultiCurrencyPrices(float|int $basePrice): array
|
||||
{
|
||||
$currencies = $this->getCurrencySettings();
|
||||
$baseUnit = $this->getDefaultBaseUnit();
|
||||
$result = [];
|
||||
|
||||
foreach ($currencies as $currency) {
|
||||
@@ -45,8 +67,8 @@ trait HasMultiCurrencyPrices
|
||||
$roundingMethod = $currency['rounding_method'] ?? 'round';
|
||||
|
||||
if ($exchangeRate > 0) {
|
||||
// 계산: (기본통화가격 / 1000) * exchange_rate
|
||||
$convertedPrice = ($basePrice / 1000) * $exchangeRate;
|
||||
// 계산: (기본통화가격 / 기본통화.base_unit) * exchange_rate
|
||||
$convertedPrice = ($basePrice / $baseUnit) * $exchangeRate;
|
||||
$convertedPrice = $this->applyRounding($convertedPrice, $roundingUnit, $roundingMethod);
|
||||
|
||||
// 부동소수점 오차 제거 (4505 * 0.01 = 45.050000000000004 방지)
|
||||
@@ -103,6 +125,30 @@ trait HasMultiCurrencyPrices
|
||||
return $settings['default_currency'] ?? 'KRW';
|
||||
}
|
||||
|
||||
/**
|
||||
* 현재 설정의 기본 통화 base_unit(환율 분모)을 반환합니다.
|
||||
*
|
||||
* 설정에 base_unit 이 있으면 그 값을, 없으면 폴백(KRW=1000, JPY=100, 그 외=1)을 사용합니다.
|
||||
* CurrencyConversionService::getDefaultBaseUnit 과 동일한 규칙.
|
||||
*
|
||||
* @return int 기본 통화 base_unit (최소 1)
|
||||
*/
|
||||
protected function getDefaultBaseUnit(): int
|
||||
{
|
||||
$defaultCode = $this->getDefaultCurrencyCode();
|
||||
$fallback = ['KRW' => 1000, 'JPY' => 100];
|
||||
|
||||
foreach ($this->getCurrencySettings() as $currency) {
|
||||
if (($currency['code'] ?? null) === $defaultCode) {
|
||||
$unit = (int) ($currency['base_unit'] ?? $fallback[$defaultCode] ?? 1);
|
||||
|
||||
return max(1, $unit);
|
||||
}
|
||||
}
|
||||
|
||||
return $fallback[$defaultCode] ?? 1;
|
||||
}
|
||||
|
||||
/**
|
||||
* 절사/반올림/올림을 적용합니다.
|
||||
*
|
||||
@@ -160,6 +206,61 @@ trait HasMultiCurrencyPrices
|
||||
return $prefix.$formattedNumber.$suffix;
|
||||
}
|
||||
|
||||
/**
|
||||
* 기본 통화 기준 금액을 포맷팅합니다.
|
||||
*
|
||||
* `*_formatted` 같은 단일 통화 표시 필드는 기본 통화(설정의 is_default 통화) 기준 금액이므로,
|
||||
* 통화 기호를 원화로 하드코딩하지 않고 설정된 기본 통화의 기호·소수 자릿수로 포맷합니다.
|
||||
* 기본 통화가 원(KRW)이면 기존과 동일하게 "3,000원"으로, 달러면 "$3,000.00"으로 표시됩니다.
|
||||
*
|
||||
* @param float|int|null $price 기본 통화 기준 금액 (null 은 0 으로 처리)
|
||||
* @return string 기본 통화 기호로 포맷팅된 금액
|
||||
*/
|
||||
protected function formatBaseCurrency(float|int|null $price): string
|
||||
{
|
||||
return $this->formatCurrencyPrice($price ?? 0, $this->getDefaultCurrencyCode());
|
||||
}
|
||||
|
||||
/**
|
||||
* 주문 시점 기준 통화로 금액을 포맷팅합니다.
|
||||
*
|
||||
* 주문/결제/취소·환불 금액의 `*_formatted` 는 거래가 기록된 시점의 기준 통화로 고정 표기해야 합니다.
|
||||
* 운영자가 이후 기본 통화를 바꿔도 과거 주문의 표기 통화는 불변이어야 하므로, 주문 스냅샷에 저장된
|
||||
* 기준 통화(`currency_snapshot.base_currency`)를 명시적으로 받아 포맷합니다. 코드가 없으면(레거시
|
||||
* 주문 등) 현재 기본 통화로 폴백합니다.
|
||||
*
|
||||
* @param float|int $price 주문 기준 통화 금액
|
||||
* @param string|null $currencyCode 주문 시점 기준 통화 코드 (null 이면 현재 기본 통화)
|
||||
* @return string 해당 통화 기호로 포맷팅된 금액
|
||||
*/
|
||||
protected function formatOrderCurrency(float|int|null $price, ?string $currencyCode = null): string
|
||||
{
|
||||
$code = $currencyCode
|
||||
?: ($this->orderCurrencyCode ?: $this->getDefaultCurrencyCode());
|
||||
|
||||
return $this->formatCurrencyPrice($price ?? 0, $code);
|
||||
}
|
||||
|
||||
/**
|
||||
* 주문 모델에서 스냅샷 기준 통화 코드를 추출합니다.
|
||||
*
|
||||
* `currency_snapshot.base_currency` (주문 시점 시스템 기본 통화)를 우선 사용하고,
|
||||
* 없으면 현재 기본 통화로 폴백합니다.
|
||||
*
|
||||
* @param mixed $order 주문 모델(또는 currency_snapshot 속성을 가진 객체)
|
||||
* @return string 주문 시점 기준 통화 코드
|
||||
*/
|
||||
protected function resolveOrderBaseCurrencyCode(mixed $order): string
|
||||
{
|
||||
$snapshot = $order->currency_snapshot ?? null;
|
||||
|
||||
if (is_array($snapshot) && ! empty($snapshot['base_currency'])) {
|
||||
return $snapshot['base_currency'];
|
||||
}
|
||||
|
||||
return $this->getDefaultCurrencyCode();
|
||||
}
|
||||
|
||||
/**
|
||||
* 통화의 소수 자릿수를 반환합니다.
|
||||
*
|
||||
@@ -186,7 +287,7 @@ trait HasMultiCurrencyPrices
|
||||
* 주문 시점에 저장된 mc_* 필드를 프론트엔드에서 사용할 수 있는 형태로 변환합니다.
|
||||
* buildMultiCurrencyPrices()와 달리 환율 재계산 없이 저장된 값을 그대로 포맷합니다.
|
||||
*
|
||||
* @param array|null $multiCurrencyAmounts 다중 통화 금액 배열 (예: {'KRW': 10000, 'USD': 7.5})
|
||||
* @param array|null $multiCurrencyAmounts 다중 통화 금액 배열 (예: {'KRW': 10000, 'USD': 7.5})
|
||||
* @return array 포맷된 배열 (예: {'KRW': {'amount': 10000, 'formatted': '10,000원'}, ...})
|
||||
*/
|
||||
protected function formatStoredMultiCurrency(?array $multiCurrencyAmounts): array
|
||||
@@ -211,6 +312,59 @@ trait HasMultiCurrencyPrices
|
||||
return $result;
|
||||
}
|
||||
|
||||
/**
|
||||
* 금액을 지정 통화의 소수 자릿수로 라운딩한 raw 숫자로 반환합니다.
|
||||
*
|
||||
* DB 가격 컬럼은 통화와 무관하게 `decimal:2` 로 cast 되어, JPY/KRW(소수 0자리)
|
||||
* 통화에서도 `200.00` 처럼 소수가 붙어 응답됩니다. 이 메서드는 통화 설정의
|
||||
* `decimal_places` 를 적용해, 0자리 통화는 정수(`int`)로, 그 외는 해당 자릿수로
|
||||
* 라운딩한 `float` 로 반환합니다. JSON 직렬화 시 0자리 통화는 `200`, 2자리 통화는
|
||||
* `1.7` 처럼 표기됩니다. (표시용 `*_formatted` 와 달리 숫자 타입을 유지합니다.)
|
||||
*
|
||||
* @param float|int|null $price 기본 통화 기준 금액 (null 은 0 으로 처리)
|
||||
* @param string $code 통화 코드
|
||||
* @return float|int 통화 자릿수로 라운딩된 금액 (0자리면 int, 그 외 float)
|
||||
*/
|
||||
protected function roundToCurrency(float|int|null $price, string $code): float|int
|
||||
{
|
||||
$decimalPlaces = $this->getDecimalPlacesForCurrency($code);
|
||||
$rounded = round((float) ($price ?? 0), $decimalPlaces);
|
||||
|
||||
return $decimalPlaces === 0 ? (int) $rounded : $rounded;
|
||||
}
|
||||
|
||||
/**
|
||||
* 금액을 현재 기본 통화의 소수 자릿수로 라운딩한 raw 숫자로 반환합니다.
|
||||
*
|
||||
* 상품·쿠폰·배송비 등 기본 통화 기준 raw 가격 필드에 사용합니다.
|
||||
*
|
||||
* @param float|int|null $price 기본 통화 기준 금액
|
||||
* @return float|int 기본 통화 자릿수로 라운딩된 금액
|
||||
*/
|
||||
protected function roundToBaseCurrency(float|int|null $price): float|int
|
||||
{
|
||||
return $this->roundToCurrency($price, $this->getDefaultCurrencyCode());
|
||||
}
|
||||
|
||||
/**
|
||||
* 금액을 주문 시점 기준 통화의 소수 자릿수로 라운딩한 raw 숫자로 반환합니다.
|
||||
*
|
||||
* 주문/결제/취소·환불의 raw 금액 필드에 사용합니다. 거래가 기록된 시점의 기준 통화
|
||||
* (`currency_snapshot.base_currency`)로 자릿수를 고정하며, 코드가 없으면 현재 기본
|
||||
* 통화로 폴백합니다. `formatOrderCurrency()` 와 동일한 통화 해석 규칙을 따릅니다.
|
||||
*
|
||||
* @param float|int|null $price 주문 기준 통화 금액
|
||||
* @param string|null $currencyCode 주문 시점 기준 통화 코드 (null 이면 주입값/현재 기본 통화)
|
||||
* @return float|int 주문 통화 자릿수로 라운딩된 금액
|
||||
*/
|
||||
protected function roundToOrderCurrency(float|int|null $price, ?string $currencyCode = null): float|int
|
||||
{
|
||||
$code = $currencyCode
|
||||
?: ($this->orderCurrencyCode ?: $this->getDefaultCurrencyCode());
|
||||
|
||||
return $this->roundToCurrency($price, $code);
|
||||
}
|
||||
|
||||
/**
|
||||
* 통화 설정 캐시를 초기화합니다.
|
||||
*
|
||||
|
||||
+64
@@ -0,0 +1,64 @@
|
||||
<?php
|
||||
|
||||
namespace Modules\Sirsoft\Ecommerce\Http\Resources\Traits;
|
||||
|
||||
use Modules\Sirsoft\Ecommerce\Models\OrderOption;
|
||||
|
||||
/**
|
||||
* 주문 목록의 추가옵션 요약 트레이트
|
||||
*
|
||||
* 마이페이지 주문리스트·관리자 주문관리 목록의 대표 옵션(first_option) 아래
|
||||
* 추가옵션을 compact 요약으로 노출하기 위한 공용 로직입니다.
|
||||
* 첫 추가옵션 1건의 라벨 + "외 N건" 축약(Q-E2)으로 표기하며,
|
||||
* 직접입력(custom_text)이 있으면 선택지명에 병기합니다.
|
||||
*/
|
||||
trait SummarizesAdditionalOptions
|
||||
{
|
||||
/**
|
||||
* 대표 주문옵션의 추가옵션을 목록용으로 요약합니다.
|
||||
*
|
||||
* 주문 시점 동결된 additional_options_snapshot 을 기준으로 하며(관리자 수정/삭제 무관 D8),
|
||||
* 첫 추가옵션의 라벨과 나머지 건수를 반환합니다. 추가옵션이 없으면 null.
|
||||
*
|
||||
* @param OrderOption|null $option 대표 주문옵션
|
||||
* @return array{label: string, extra_count: int, total_count: int}|null
|
||||
*/
|
||||
protected function summarizeAdditionalOptions(?OrderOption $option): ?array
|
||||
{
|
||||
if (! $option) {
|
||||
return null;
|
||||
}
|
||||
|
||||
$snapshot = $option->additional_options_snapshot ?? [];
|
||||
|
||||
if (! is_array($snapshot) || empty($snapshot)) {
|
||||
return null;
|
||||
}
|
||||
|
||||
$locale = app()->getLocale();
|
||||
$first = $snapshot[0];
|
||||
|
||||
$name = $first['name'] ?? '';
|
||||
if (is_array($name)) {
|
||||
$name = $name[$locale]
|
||||
?? $name[config('app.fallback_locale', 'ko')]
|
||||
?? (! empty($name) ? reset($name) : '');
|
||||
}
|
||||
|
||||
$label = (string) $name;
|
||||
|
||||
// 직접입력 텍스트가 있으면 선택지명에 병기 (예: "각인 추가: 홍길동")
|
||||
$customText = trim((string) ($first['custom_text'] ?? ''));
|
||||
if ($customText !== '') {
|
||||
$label = $label !== '' ? $label.': '.$customText : $customText;
|
||||
}
|
||||
|
||||
$totalCount = count($snapshot);
|
||||
|
||||
return [
|
||||
'label' => $label,
|
||||
'extra_count' => max(0, $totalCount - 1),
|
||||
'total_count' => $totalCount,
|
||||
];
|
||||
}
|
||||
}
|
||||
@@ -4,19 +4,19 @@ namespace Modules\Sirsoft\Ecommerce\Http\Resources;
|
||||
|
||||
use App\Http\Resources\BaseApiResource;
|
||||
use Illuminate\Http\Request;
|
||||
use Modules\Sirsoft\Ecommerce\Http\Resources\Concerns\LocalizesCountryName;
|
||||
|
||||
/**
|
||||
* 사용자 배송지 리소스
|
||||
*/
|
||||
class UserAddressResource extends BaseApiResource
|
||||
{
|
||||
use LocalizesCountryName;
|
||||
|
||||
/**
|
||||
* 비즈니스 로직 기반 abilities를 반환합니다.
|
||||
* user-addresses 권한 식별자가 모듈 매니페스트에 없으므로, abilityMap()은 빈 배열.
|
||||
* 인증된 사용자는 자신의 주소를 수정 가능하며, 기본 배송지는 삭제/변경 불가.
|
||||
*
|
||||
* @param Request $request
|
||||
* @return array
|
||||
*/
|
||||
protected function resolveAbilities(Request $request): array
|
||||
{
|
||||
@@ -31,8 +31,8 @@ class UserAddressResource extends BaseApiResource
|
||||
/**
|
||||
* 리소스를 배열로 변환
|
||||
*
|
||||
* @param Request $request 요청
|
||||
* @return array
|
||||
* @param Request $request 요청
|
||||
* @return array 회원 주소록 리소스 배열 (국가명·국내/해외 필드 포함)
|
||||
*/
|
||||
public function toArray(Request $request): array
|
||||
{
|
||||
@@ -43,6 +43,7 @@ class UserAddressResource extends BaseApiResource
|
||||
'recipient_name' => $this->recipient_name,
|
||||
'recipient_phone' => $this->recipient_phone,
|
||||
'country_code' => $this->country_code,
|
||||
'country_name' => $this->getCountryLocalizedName($this->country_code),
|
||||
|
||||
// 국내 배송 주소
|
||||
'zipcode' => $this->zipcode,
|
||||
|
||||
@@ -5,7 +5,9 @@ namespace Modules\Sirsoft\Ecommerce\Http\Resources;
|
||||
use App\Helpers\PermissionHelper;
|
||||
use App\Http\Resources\BaseApiResource;
|
||||
use Illuminate\Http\Request;
|
||||
use Modules\Sirsoft\Ecommerce\Http\Resources\Concerns\LocalizesCountryName;
|
||||
use Modules\Sirsoft\Ecommerce\Http\Resources\Traits\HasMultiCurrencyPrices;
|
||||
use Modules\Sirsoft\Ecommerce\Http\Resources\Traits\SummarizesAdditionalOptions;
|
||||
|
||||
/**
|
||||
* 사용자 주문 목록 리소스
|
||||
@@ -16,51 +18,72 @@ use Modules\Sirsoft\Ecommerce\Http\Resources\Traits\HasMultiCurrencyPrices;
|
||||
class UserOrderListResource extends BaseApiResource
|
||||
{
|
||||
use HasMultiCurrencyPrices;
|
||||
use LocalizesCountryName;
|
||||
use SummarizesAdditionalOptions;
|
||||
|
||||
/**
|
||||
* 리소스를 배열로 변환
|
||||
*
|
||||
* @param Request $request 요청
|
||||
* @return array
|
||||
* @param Request $request 요청
|
||||
* @return array 마이페이지 주문 목록 리소스 배열 (배송국가 포함)
|
||||
*/
|
||||
public function toArray(Request $request): array
|
||||
{
|
||||
// 주문 시점 기준 통화 — 과거 주문의 *_formatted 는 설정 변경과 무관하게 이 통화로 고정 표기한다.
|
||||
$orderCurrency = $this->resolveOrderBaseCurrencyCode($this->resource);
|
||||
|
||||
return [
|
||||
'id' => $this->id,
|
||||
'order_number' => $this->order_number,
|
||||
'status' => $this->order_status?->value,
|
||||
'status_label' => $this->order_status?->label(),
|
||||
'status_variant' => $this->order_status?->variant(),
|
||||
// 부분취소 파생 플래그 — 일부 옵션만 취소된 주문(별도 order_status 아님). 보조 뱃지 표시용.
|
||||
'is_partially_cancelled' => $this->whenLoaded('options', fn () => $this->resource->isPartiallyCancelled(), false),
|
||||
|
||||
// 일시
|
||||
'ordered_at' => $this->ordered_at?->toIso8601String(),
|
||||
// 배송국가 (마이페이지 주문 목록 표시 — D9, 항상 표시 KR 포함)
|
||||
'recipient_country_code' => $this->whenLoaded('shippingAddress', fn () => $this->shippingAddress?->recipient_country_code),
|
||||
'recipient_country_name' => $this->whenLoaded('shippingAddress', fn () => $this->getCountryLocalizedName($this->shippingAddress?->recipient_country_code)),
|
||||
|
||||
// 일시 — raw ISO 와 사용자 타임존 변환된 *_formatted 를 함께 제공 (OrderResource 와 동일 패턴)
|
||||
'ordered_at' => $this->ordered_at?->toIso8601String(), // audit:allow datetime-display-user-timezone reason: paired with *_formatted user-tz field
|
||||
'ordered_at_formatted' => $this->formatDateTimeStringForUser($this->ordered_at),
|
||||
|
||||
// 금액
|
||||
'total_amount' => $this->total_amount,
|
||||
'total_amount_formatted' => number_format($this->total_amount).'원',
|
||||
'total_amount' => $this->roundToOrderCurrency($this->total_amount, $orderCurrency),
|
||||
'total_amount_formatted' => $this->formatOrderCurrency($this->total_amount, $orderCurrency),
|
||||
'mc_total_amount' => $this->formatStoredMultiCurrency($this->mc_total_amount),
|
||||
|
||||
// 배송비
|
||||
'total_shipping_amount' => $this->total_shipping_amount,
|
||||
'total_shipping_amount_formatted' => number_format($this->total_shipping_amount).'원',
|
||||
'total_shipping_amount' => $this->roundToOrderCurrency($this->total_shipping_amount, $orderCurrency),
|
||||
'total_shipping_amount_formatted' => $this->formatOrderCurrency($this->total_shipping_amount, $orderCurrency),
|
||||
'mc_total_shipping_amount' => $this->formatStoredMultiCurrency($this->mc_total_shipping_amount),
|
||||
|
||||
// 마일리지 (목록 표시용 — 사용/적립). 마일리지는 base_currency 단일 정산.
|
||||
'total_points_used_amount' => $this->roundToOrderCurrency($this->total_points_used_amount, $orderCurrency),
|
||||
'total_points_used_amount_formatted' => $this->formatOrderCurrency($this->total_points_used_amount, $orderCurrency),
|
||||
'total_earned_points_amount' => $this->roundToOrderCurrency($this->total_earned_points_amount, $orderCurrency),
|
||||
'total_earned_points_amount_formatted' => $this->formatOrderCurrency($this->total_earned_points_amount, $orderCurrency),
|
||||
|
||||
// 주문 옵션 (상품 정보)
|
||||
'items' => $this->whenLoaded('options', fn () => $this->options->map(fn ($option) => [
|
||||
// array_values()[0] 사용 — reset() 은 Eloquent 매직 프로퍼티에 직접 쓰면
|
||||
// PHP 8.3 "Indirect modification of overloaded property" 경고를 유발한다.
|
||||
'product_name' => is_array($option->product_name)
|
||||
? ($option->product_name[app()->getLocale()] ?? reset($option->product_name) ?: '')
|
||||
? ($option->product_name[app()->getLocale()] ?? array_values($option->product_name)[0] ?? '')
|
||||
: ($option->product_name ?? ''),
|
||||
'product_option_name' => is_array($option->product_option_name)
|
||||
? ($option->product_option_name[app()->getLocale()] ?? reset($option->product_option_name) ?: '')
|
||||
? ($option->product_option_name[app()->getLocale()] ?? array_values($option->product_option_name)[0] ?? '')
|
||||
: ($option->product_option_name ?? ''),
|
||||
'thumbnail_url' => $option->product_snapshot['thumbnail_url'] ?? null,
|
||||
'quantity' => $option->quantity,
|
||||
'unit_price_formatted' => number_format($option->unit_price).'원',
|
||||
'unit_price_formatted' => $this->formatOrderCurrency($option->unit_price, $orderCurrency),
|
||||
'mc_unit_price' => $this->formatStoredMultiCurrency($option->mc_unit_price),
|
||||
'subtotal_price' => $option->subtotal_price,
|
||||
'subtotal_price_formatted' => number_format($option->subtotal_price).'원',
|
||||
'subtotal_price' => $this->roundToOrderCurrency($option->subtotal_price, $orderCurrency),
|
||||
'subtotal_price_formatted' => $this->formatOrderCurrency($option->subtotal_price, $orderCurrency),
|
||||
'mc_subtotal_price' => $this->formatStoredMultiCurrency($option->mc_subtotal_price),
|
||||
// 추가옵션 요약 (스냅샷 기반 — 첫 1건 + "외 N건", custom_text 병기)
|
||||
'additional_options_summary' => $this->summarizeAdditionalOptions($option),
|
||||
])->toArray()),
|
||||
'item_count' => $this->whenLoaded('options', fn () => $this->options->count()),
|
||||
|
||||
|
||||
Reference in new issue
Block a user