v7.0.0 release
This commit is contained in:
1 parent
0e7fa04b03
commit
c4ea9a6cd1
3582 files changed
+626189
-160151
No files matched your search
@@ -18,6 +18,7 @@ class Cart extends Model
|
||||
'user_id',
|
||||
'product_id',
|
||||
'product_option_id',
|
||||
'additional_option_selections',
|
||||
'quantity',
|
||||
];
|
||||
|
||||
@@ -25,6 +26,7 @@ class Cart extends Model
|
||||
'user_id' => 'integer',
|
||||
'product_id' => 'integer',
|
||||
'product_option_id' => 'integer',
|
||||
'additional_option_selections' => 'array',
|
||||
'quantity' => 'integer',
|
||||
];
|
||||
|
||||
@@ -68,6 +70,60 @@ class Cart extends Model
|
||||
return $this->user_id === null;
|
||||
}
|
||||
|
||||
/**
|
||||
* 추가옵션 선택을 합산 판정용 정규화 해시로 변환
|
||||
*
|
||||
* 동일 상품옵션이라도 추가옵션 선택이 다르면 별개 행으로 취급하기 위해,
|
||||
* (additional_option_id => value_id) 매핑을 키 순으로 정렬한 후 해시화합니다.
|
||||
* 선택이 없으면 빈 문자열을 반환합니다.
|
||||
*
|
||||
* 직접입력(custom_text)이 다르면 같은 (옵션+선택지) 라도 별개 행으로 취급합니다(E5).
|
||||
* 서로 다른 각인 문구는 합산이 불가능하기 때문입니다.
|
||||
*
|
||||
* @param array|null $selections 추가옵션 선택 배열 [{additional_option_id, value_id, custom_text?}]
|
||||
* @return string 정규화된 선택 해시
|
||||
*/
|
||||
public static function normalizeAdditionalOptionSelectionHash(?array $selections): string
|
||||
{
|
||||
if (empty($selections)) {
|
||||
return '';
|
||||
}
|
||||
|
||||
$normalized = [];
|
||||
foreach ($selections as $selection) {
|
||||
$optionId = (int) ($selection['additional_option_id'] ?? 0);
|
||||
$valueId = (int) ($selection['value_id'] ?? 0);
|
||||
|
||||
if ($optionId <= 0 || $valueId <= 0) {
|
||||
continue;
|
||||
}
|
||||
|
||||
$customText = trim((string) ($selection['custom_text'] ?? ''));
|
||||
|
||||
$normalized[$optionId] = $customText !== ''
|
||||
? ['value_id' => $valueId, 'custom_text' => $customText]
|
||||
: $valueId;
|
||||
}
|
||||
|
||||
if (empty($normalized)) {
|
||||
return '';
|
||||
}
|
||||
|
||||
ksort($normalized);
|
||||
|
||||
return md5(json_encode($normalized));
|
||||
}
|
||||
|
||||
/**
|
||||
* 이 장바구니 행의 추가옵션 선택 해시
|
||||
*
|
||||
* @return string 정규화된 선택 해시
|
||||
*/
|
||||
public function getAdditionalOptionSelectionHash(): string
|
||||
{
|
||||
return self::normalizeAdditionalOptionSelectionHash($this->additional_option_selections);
|
||||
}
|
||||
|
||||
/**
|
||||
* 소계 금액 계산 (옵션 단가 × 수량)
|
||||
*
|
||||
|
||||
@@ -5,6 +5,8 @@ namespace Modules\Sirsoft\Ecommerce\Models;
|
||||
use App\Casts\AsUnicodeJson;
|
||||
use App\Extension\HookManager;
|
||||
use App\Search\Contracts\FulltextSearchable;
|
||||
use Illuminate\Database\Eloquent\Builder;
|
||||
use Illuminate\Database\Eloquent\Collection;
|
||||
use Illuminate\Database\Eloquent\Model;
|
||||
use Illuminate\Database\Eloquent\Relations\BelongsTo;
|
||||
use Illuminate\Database\Eloquent\Relations\BelongsToMany;
|
||||
@@ -14,6 +16,7 @@ use Laravel\Scout\Searchable;
|
||||
class Category extends Model implements FulltextSearchable
|
||||
{
|
||||
use Searchable;
|
||||
|
||||
/** @var array<string, array> 활동 로그 추적 필드 */
|
||||
public static array $activityLogFields = [
|
||||
'parent_id' => ['label_key' => 'sirsoft-ecommerce::activity_log.fields.parent_id', 'type' => 'number'],
|
||||
@@ -88,6 +91,33 @@ class Category extends Model implements FulltextSearchable
|
||||
return $this->hasMany(self::class, 'parent_id')->with('descendants');
|
||||
}
|
||||
|
||||
/**
|
||||
* 주어진 카테고리 ID와 그 모든 하위 카테고리 ID를 path 기반으로 반환합니다.
|
||||
*
|
||||
* @param int $categoryId 기준 카테고리 ID
|
||||
* @return array<int> 자기 자신 + 모든 하위 카테고리 ID
|
||||
*/
|
||||
public static function selfAndDescendantIds(int $categoryId): array
|
||||
{
|
||||
$self = self::find($categoryId, ['id', 'path']);
|
||||
if (! $self) {
|
||||
return [$categoryId];
|
||||
}
|
||||
|
||||
$ids = self::where('id', $categoryId)
|
||||
->orWhere(function ($q) use ($self) {
|
||||
// path 공백 레거시 행 방어 (실DB 측정: 공백 0건이나 안전망 유지)
|
||||
if (! empty($self->path)) {
|
||||
$q->where('path', 'like', $self->path.'/%');
|
||||
}
|
||||
})
|
||||
->pluck('id')
|
||||
->map(fn ($v) => (int) $v)
|
||||
->all();
|
||||
|
||||
return ! empty($ids) ? $ids : [$categoryId];
|
||||
}
|
||||
|
||||
/**
|
||||
* 카테고리 이미지 관계
|
||||
*
|
||||
@@ -116,7 +146,7 @@ class Category extends Model implements FulltextSearchable
|
||||
/**
|
||||
* 현재 로케일의 카테고리명 반환
|
||||
*
|
||||
* @param string|null $locale 로케일 (기본값: 현재 앱 로케일)
|
||||
* @param string|null $locale 로케일 (기본값: 현재 앱 로케일)
|
||||
* @return string
|
||||
*/
|
||||
public function getLocalizedName(?string $locale = null): string
|
||||
@@ -149,14 +179,14 @@ class Category extends Model implements FulltextSearchable
|
||||
/**
|
||||
* 조상 카테고리들 조회
|
||||
*
|
||||
* @return \Illuminate\Database\Eloquent\Collection
|
||||
* @return Collection
|
||||
*/
|
||||
public function getAncestors(): \Illuminate\Database\Eloquent\Collection
|
||||
public function getAncestors(): Collection
|
||||
{
|
||||
$ancestorIds = $this->getAncestorIds();
|
||||
|
||||
if (empty($ancestorIds)) {
|
||||
return new \Illuminate\Database\Eloquent\Collection();
|
||||
return new Collection;
|
||||
}
|
||||
|
||||
$ancestors = self::whereIn('id', $ancestorIds)->get();
|
||||
@@ -198,8 +228,8 @@ class Category extends Model implements FulltextSearchable
|
||||
*
|
||||
* 예: "가구 > 책상 > 컴퓨터책상"
|
||||
*
|
||||
* @param string|null $locale 로케일 (기본값: 현재 앱 로케일)
|
||||
* @param string $separator 구분자 (기본값: ' > ')
|
||||
* @param string|null $locale 로케일 (기본값: 현재 앱 로케일)
|
||||
* @param string $separator 구분자 (기본값: ' > ')
|
||||
* @return string
|
||||
*/
|
||||
public function getLocalizedBreadcrumbString(?string $locale = null, string $separator = ' > '): string
|
||||
@@ -220,15 +250,13 @@ class Category extends Model implements FulltextSearchable
|
||||
|
||||
/**
|
||||
* path 자동 생성 (저장 전 호출)
|
||||
*
|
||||
* @return void
|
||||
*/
|
||||
public function generatePath(): void
|
||||
{
|
||||
if ($this->parent_id) {
|
||||
$parent = self::find($this->parent_id);
|
||||
if ($parent) {
|
||||
$this->path = $parent->path ? $parent->path . '/' . $this->id : (string) $this->id;
|
||||
$this->path = $parent->path ? $parent->path.'/'.$this->id : (string) $this->id;
|
||||
$this->depth = $parent->depth + 1;
|
||||
}
|
||||
} else {
|
||||
@@ -240,8 +268,8 @@ class Category extends Model implements FulltextSearchable
|
||||
/**
|
||||
* 루트 카테고리만 조회 스코프
|
||||
*
|
||||
* @param \Illuminate\Database\Eloquent\Builder $query
|
||||
* @return \Illuminate\Database\Eloquent\Builder
|
||||
* @param Builder $query
|
||||
* @return Builder
|
||||
*/
|
||||
public function scopeRoots($query)
|
||||
{
|
||||
@@ -251,8 +279,8 @@ class Category extends Model implements FulltextSearchable
|
||||
/**
|
||||
* 활성 카테고리만 조회 스코프
|
||||
*
|
||||
* @param \Illuminate\Database\Eloquent\Builder $query
|
||||
* @return \Illuminate\Database\Eloquent\Builder
|
||||
* @param Builder $query
|
||||
* @return Builder
|
||||
*/
|
||||
public function scopeActive($query)
|
||||
{
|
||||
@@ -262,9 +290,9 @@ class Category extends Model implements FulltextSearchable
|
||||
/**
|
||||
* 특정 깊이의 카테고리 조회 스코프
|
||||
*
|
||||
* @param \Illuminate\Database\Eloquent\Builder $query
|
||||
* @param int $depth
|
||||
* @return \Illuminate\Database\Eloquent\Builder
|
||||
* @param Builder $query
|
||||
* @param int $depth 조회할 깊이
|
||||
* @return Builder
|
||||
*/
|
||||
public function scopeAtDepth($query, int $depth)
|
||||
{
|
||||
@@ -274,16 +302,16 @@ class Category extends Model implements FulltextSearchable
|
||||
/**
|
||||
* 트리 구조로 카테고리 조회 (재귀)
|
||||
*
|
||||
* @param int|null $parentId 부모 ID (null이면 루트부터)
|
||||
* @param bool $onlyActive 활성 카테고리만 조회할지 여부
|
||||
* @return \Illuminate\Database\Eloquent\Collection
|
||||
* @param int|null $parentId 부모 ID (null이면 루트부터)
|
||||
* @param bool $onlyActive 활성 카테고리만 조회할지 여부
|
||||
* @return Collection
|
||||
*/
|
||||
public static function getTree(?int $parentId = null, bool $onlyActive = false): \Illuminate\Database\Eloquent\Collection
|
||||
public static function getTree(?int $parentId = null, bool $onlyActive = false): Collection
|
||||
{
|
||||
$query = self::with([
|
||||
'images',
|
||||
'parent:id,name,slug', // parent에서 필요한 필드만 선택
|
||||
])
|
||||
'images',
|
||||
'parent:id,name,slug', // parent에서 필요한 필드만 선택
|
||||
])
|
||||
->withCount('products')
|
||||
->where('parent_id', $parentId)
|
||||
->orderBy('sort_order')
|
||||
@@ -305,11 +333,11 @@ class Category extends Model implements FulltextSearchable
|
||||
/**
|
||||
* 플랫 리스트로 변환 (들여쓰기용 depth 포함)
|
||||
*
|
||||
* @param \Illuminate\Database\Eloquent\Collection|null $categories
|
||||
* @param string $indent 들여쓰기 문자
|
||||
* @param Collection|null $categories 변환할 카테고리 컬렉션 (null이면 전체 트리)
|
||||
* @param string $indent 들여쓰기 문자
|
||||
* @return array
|
||||
*/
|
||||
public static function toFlatList(?\Illuminate\Database\Eloquent\Collection $categories = null, string $indent = ' '): array
|
||||
public static function toFlatList(?Collection $categories = null, string $indent = ' '): array
|
||||
{
|
||||
if ($categories === null) {
|
||||
$categories = self::getTree();
|
||||
@@ -321,7 +349,7 @@ class Category extends Model implements FulltextSearchable
|
||||
$prefix = str_repeat($indent, $category->depth);
|
||||
$result[] = [
|
||||
'id' => $category->id,
|
||||
'name' => $prefix . $category->getLocalizedName(),
|
||||
'name' => $prefix.$category->getLocalizedName(),
|
||||
'depth' => $category->depth,
|
||||
'is_active' => $category->is_active,
|
||||
];
|
||||
|
||||
@@ -20,6 +20,7 @@ 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\Services\CurrencyConversionService;
|
||||
|
||||
/**
|
||||
* 쿠폰 모델
|
||||
@@ -32,14 +33,14 @@ class Coupon extends Model implements FulltextSearchable
|
||||
|
||||
/** @var array<string, array> 활동 로그 추적 필드 */
|
||||
public static array $activityLogFields = [
|
||||
'target_type' => ['label_key' => 'sirsoft-ecommerce::activity_log.fields.target_type', 'type' => 'enum', 'enum' => \Modules\Sirsoft\Ecommerce\Enums\CouponTargetType::class],
|
||||
'discount_type' => ['label_key' => 'sirsoft-ecommerce::activity_log.fields.discount_type', 'type' => 'enum', 'enum' => \Modules\Sirsoft\Ecommerce\Enums\CouponDiscountType::class],
|
||||
'target_type' => ['label_key' => 'sirsoft-ecommerce::activity_log.fields.target_type', 'type' => 'enum', 'enum' => CouponTargetType::class],
|
||||
'discount_type' => ['label_key' => 'sirsoft-ecommerce::activity_log.fields.discount_type', 'type' => 'enum', 'enum' => CouponDiscountType::class],
|
||||
'discount_value' => ['label_key' => 'sirsoft-ecommerce::activity_log.fields.discount_value', 'type' => 'currency'],
|
||||
'discount_max_amount' => ['label_key' => 'sirsoft-ecommerce::activity_log.fields.discount_max_amount', 'type' => 'currency'],
|
||||
'min_order_amount' => ['label_key' => 'sirsoft-ecommerce::activity_log.fields.min_order_amount', 'type' => 'currency'],
|
||||
'issue_method' => ['label_key' => 'sirsoft-ecommerce::activity_log.fields.issue_method', 'type' => 'enum', 'enum' => \Modules\Sirsoft\Ecommerce\Enums\CouponIssueMethod::class],
|
||||
'issue_condition' => ['label_key' => 'sirsoft-ecommerce::activity_log.fields.issue_condition', 'type' => 'enum', 'enum' => \Modules\Sirsoft\Ecommerce\Enums\CouponIssueCondition::class],
|
||||
'issue_status' => ['label_key' => 'sirsoft-ecommerce::activity_log.fields.issue_status', 'type' => 'enum', 'enum' => \Modules\Sirsoft\Ecommerce\Enums\CouponIssueStatus::class],
|
||||
'issue_method' => ['label_key' => 'sirsoft-ecommerce::activity_log.fields.issue_method', 'type' => 'enum', 'enum' => CouponIssueMethod::class],
|
||||
'issue_condition' => ['label_key' => 'sirsoft-ecommerce::activity_log.fields.issue_condition', 'type' => 'enum', 'enum' => CouponIssueCondition::class],
|
||||
'issue_status' => ['label_key' => 'sirsoft-ecommerce::activity_log.fields.issue_status', 'type' => 'enum', 'enum' => CouponIssueStatus::class],
|
||||
'total_quantity' => ['label_key' => 'sirsoft-ecommerce::activity_log.fields.total_quantity', 'type' => 'number'],
|
||||
'per_user_limit' => ['label_key' => 'sirsoft-ecommerce::activity_log.fields.per_user_limit', 'type' => 'number'],
|
||||
'valid_type' => ['label_key' => 'sirsoft-ecommerce::activity_log.fields.valid_type', 'type' => 'text'],
|
||||
@@ -255,6 +256,51 @@ class Coupon extends Model implements FulltextSearchable
|
||||
]);
|
||||
}
|
||||
|
||||
/**
|
||||
* 통화별 혜택 금액 포맷 맵을 반환합니다.
|
||||
*
|
||||
* benefit_formatted 와 동일한 i18n 템플릿을 쓰되, 정액 할인액·정률 최대금액을
|
||||
* 통화별 환산값으로 렌더한다(정률 % 자체는 통화 무관). 상품상세 쿠폰 칩·모달이
|
||||
* 선택 통화로 베네핏을 표시할 때 사용한다(KRW 고정 결함 D4 해소).
|
||||
*
|
||||
* @param CurrencyConversionService $converter 통화 환산 서비스
|
||||
* @return array<string, string> 통화코드 => 포맷 문자열 (예: {'KRW': '1,000원 할인', 'USD': '$0.85 할인'})
|
||||
*/
|
||||
public function buildMultiCurrencyBenefitFormatted(CurrencyConversionService $converter): array
|
||||
{
|
||||
$result = [];
|
||||
|
||||
if ($this->discount_type === CouponDiscountType::FIXED) {
|
||||
// 정액: 할인액을 통화별 환산(환율 미설정 통화는 convertToMultiCurrency 가 자동 제외)
|
||||
foreach ($converter->convertToMultiCurrency((int) ($this->discount_value ?? 0)) as $code => $amount) {
|
||||
$result[$code] = __('sirsoft-ecommerce::messages.coupons.benefit_fixed_format', [
|
||||
'amount' => $amount['formatted'],
|
||||
]);
|
||||
}
|
||||
|
||||
return $result;
|
||||
}
|
||||
|
||||
// 정률: % 는 통화 무관. 최대 할인 금액만 통화별 환산.
|
||||
if ($this->discount_max_amount) {
|
||||
foreach ($converter->convertToMultiCurrency((int) $this->discount_max_amount) as $code => $max) {
|
||||
$result[$code] = __('sirsoft-ecommerce::messages.coupons.benefit_rate_with_max_format', [
|
||||
'rate' => $this->discount_value,
|
||||
'max' => $max['formatted'],
|
||||
]);
|
||||
}
|
||||
|
||||
return $result;
|
||||
}
|
||||
|
||||
// 정률(최대금액 없음): 전 통화 동일 문자열. 기본 통화 코드 1건만 채워 폴백 기준 제공.
|
||||
$result[$converter->getDefaultCurrency()] = __('sirsoft-ecommerce::messages.coupons.benefit_rate_format', [
|
||||
'rate' => $this->discount_value,
|
||||
]);
|
||||
|
||||
return $result;
|
||||
}
|
||||
|
||||
/**
|
||||
* 유효기간 포맷팅 반환
|
||||
*
|
||||
@@ -435,8 +481,6 @@ class Coupon extends Model implements FulltextSearchable
|
||||
|
||||
/**
|
||||
* MySQL FULLTEXT 엔진에서는 인덱스 업데이트가 불필요합니다.
|
||||
*
|
||||
* @return bool
|
||||
*/
|
||||
public function searchIndexShouldBeUpdated(): bool
|
||||
{
|
||||
|
||||
@@ -0,0 +1,56 @@
|
||||
<?php
|
||||
|
||||
namespace Modules\Sirsoft\Ecommerce\Models;
|
||||
|
||||
use Illuminate\Database\Eloquent\Model;
|
||||
use Illuminate\Support\Carbon;
|
||||
|
||||
/**
|
||||
* 이커머스 일별 판매 집계 모델
|
||||
*
|
||||
* ecommerce_stats 테이블 — 하루 1행. 대시보드 스케쥴러가 upsert 하고
|
||||
* 대시보드 API(overview/sales-graph)가 읽는다. 원본(주문/주문상품) 풀스캔을
|
||||
* 피하기 위한 집계 캐시.
|
||||
*
|
||||
* @property int $id
|
||||
* @property Carbon $date
|
||||
* @property int $sales_quantity
|
||||
* @property string $sales_amount
|
||||
* @property array<string, int>|null $option_status_counts
|
||||
* @property Carbon|null $created_at
|
||||
* @property Carbon|null $updated_at
|
||||
*/
|
||||
class EcommerceStat extends Model
|
||||
{
|
||||
/**
|
||||
* 테이블명
|
||||
*/
|
||||
protected $table = 'ecommerce_stats';
|
||||
|
||||
/**
|
||||
* 대량 할당 가능 필드
|
||||
*
|
||||
* @var array<int, string>
|
||||
*/
|
||||
protected $fillable = [
|
||||
'date',
|
||||
'sales_quantity',
|
||||
'sales_amount',
|
||||
'option_status_counts',
|
||||
];
|
||||
|
||||
/**
|
||||
* 타입 캐스팅
|
||||
*
|
||||
* @return array<string, string>
|
||||
*/
|
||||
protected function casts(): array
|
||||
{
|
||||
return [
|
||||
'date' => 'date',
|
||||
'sales_quantity' => 'integer',
|
||||
'sales_amount' => 'decimal:2',
|
||||
'option_status_counts' => 'array',
|
||||
];
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,35 @@
|
||||
<?php
|
||||
|
||||
namespace Modules\Sirsoft\Ecommerce\Models;
|
||||
|
||||
use App\Models\User;
|
||||
use Illuminate\Database\Eloquent\Model;
|
||||
use Illuminate\Database\Eloquent\Relations\BelongsTo;
|
||||
|
||||
/**
|
||||
* 이커머스 사용자 프로필 모델 (A3)
|
||||
*
|
||||
* 유저별 결제 통화·배송국가 등 커머스 전용 사용자 설정을 보관합니다. 코어 users 테이블을
|
||||
* 건드리지 않고 user_id FK 로 연결됩니다(ecommerce_user_addresses 선례). 모듈 미설치 시
|
||||
* 테이블이 부재하므로 "유저별 통화/배송국가 = 커머스 책임" 설치 게이트를 구조적으로 충족합니다(A5).
|
||||
*/
|
||||
class EcommerceUserProfile extends Model
|
||||
{
|
||||
protected $table = 'ecommerce_user_profiles';
|
||||
|
||||
protected $fillable = [
|
||||
'user_id',
|
||||
'preferred_currency',
|
||||
'preferred_shipping_country',
|
||||
];
|
||||
|
||||
/**
|
||||
* 소유 사용자 관계 (코어 User)
|
||||
*
|
||||
* @return BelongsTo 코어 User 모델과의 관계
|
||||
*/
|
||||
public function user(): BelongsTo
|
||||
{
|
||||
return $this->belongsTo(User::class, 'user_id');
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,58 @@
|
||||
<?php
|
||||
|
||||
namespace Modules\Sirsoft\Ecommerce\Models;
|
||||
|
||||
use App\Models\User;
|
||||
use Illuminate\Database\Eloquent\Model;
|
||||
use Illuminate\Database\Eloquent\Relations\BelongsTo;
|
||||
|
||||
/**
|
||||
* 마일리지 잔액 캐시 모델 (파생 캐시)
|
||||
*
|
||||
* SSoT 는 ecommerce_mileage_transactions(원장)이며 본 모델은 표시 전용 파생 캐시.
|
||||
* 활동로그 비대상($activityLogFields 불요).
|
||||
*/
|
||||
class MileageBalance extends Model
|
||||
{
|
||||
protected $table = 'ecommerce_mileage_balances';
|
||||
|
||||
protected $fillable = [
|
||||
'user_id',
|
||||
'currency',
|
||||
'available',
|
||||
'pending',
|
||||
'total_earned',
|
||||
'total_used',
|
||||
'expiring_soon',
|
||||
'expiring_date',
|
||||
'recalculated_at',
|
||||
];
|
||||
|
||||
/**
|
||||
* 캐스트 정의
|
||||
*
|
||||
* @return array<string, string> 캐스트 맵
|
||||
*/
|
||||
protected function casts(): array
|
||||
{
|
||||
return [
|
||||
'available' => 'decimal:2',
|
||||
'pending' => 'decimal:2',
|
||||
'total_earned' => 'decimal:2',
|
||||
'total_used' => 'decimal:2',
|
||||
'expiring_soon' => 'decimal:2',
|
||||
'expiring_date' => 'datetime',
|
||||
'recalculated_at' => 'datetime',
|
||||
];
|
||||
}
|
||||
|
||||
/**
|
||||
* 회원 관계
|
||||
*
|
||||
* @return BelongsTo 회원 관계
|
||||
*/
|
||||
public function user(): BelongsTo
|
||||
{
|
||||
return $this->belongsTo(User::class);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,152 @@
|
||||
<?php
|
||||
|
||||
namespace Modules\Sirsoft\Ecommerce\Models;
|
||||
|
||||
use App\Models\User;
|
||||
use Carbon\Carbon;
|
||||
use Illuminate\Database\Eloquent\Builder;
|
||||
use Illuminate\Database\Eloquent\Model;
|
||||
use Illuminate\Database\Eloquent\Relations\BelongsTo;
|
||||
use Modules\Sirsoft\Ecommerce\Enums\MileageTransactionTypeEnum;
|
||||
|
||||
/**
|
||||
* 마일리지 거래(원장) 모델
|
||||
*
|
||||
* 잔액 SSoT = SUM(remaining_amount WHERE remaining_amount > 0 AND 미만료).
|
||||
* 거래 행은 불변(ChangeDetector 미사용 — $activityLogFields 불요).
|
||||
*/
|
||||
class MileageTransaction extends Model
|
||||
{
|
||||
protected $table = 'ecommerce_mileage_transactions';
|
||||
|
||||
protected $fillable = [
|
||||
'user_id',
|
||||
'currency',
|
||||
'type',
|
||||
'amount',
|
||||
'remaining_amount',
|
||||
'balance_after',
|
||||
'order_id',
|
||||
'order_option_id',
|
||||
'order_cancel_id',
|
||||
'source_transaction_id',
|
||||
'granted_by',
|
||||
'description',
|
||||
'memo',
|
||||
'expires_at',
|
||||
'expired_at',
|
||||
'metadata',
|
||||
];
|
||||
|
||||
/**
|
||||
* 캐스트 정의
|
||||
*
|
||||
* @return array<string, string> 캐스트 맵
|
||||
*/
|
||||
protected function casts(): array
|
||||
{
|
||||
return [
|
||||
'type' => MileageTransactionTypeEnum::class,
|
||||
'amount' => 'decimal:2',
|
||||
'remaining_amount' => 'decimal:2',
|
||||
'balance_after' => 'decimal:2',
|
||||
'expires_at' => 'datetime',
|
||||
'expired_at' => 'datetime',
|
||||
'metadata' => 'array',
|
||||
];
|
||||
}
|
||||
|
||||
/**
|
||||
* 회원 관계
|
||||
*
|
||||
* @return BelongsTo 회원 관계
|
||||
*/
|
||||
public function user(): BelongsTo
|
||||
{
|
||||
return $this->belongsTo(User::class);
|
||||
}
|
||||
|
||||
/**
|
||||
* 주문 관계
|
||||
*
|
||||
* @return BelongsTo 주문 관계
|
||||
*/
|
||||
public function order(): BelongsTo
|
||||
{
|
||||
return $this->belongsTo(Order::class);
|
||||
}
|
||||
|
||||
/**
|
||||
* 주문옵션 관계 (FK 없음 — order_option_id 컬럼만 참조)
|
||||
*
|
||||
* @return BelongsTo 주문옵션 관계
|
||||
*/
|
||||
public function orderOption(): BelongsTo
|
||||
{
|
||||
return $this->belongsTo(OrderOption::class, 'order_option_id');
|
||||
}
|
||||
|
||||
/**
|
||||
* 부여 주체(관리자) 관계 — 관리자 셀 컨텍스트 메뉴용 (eager load 로 N+1 회피)
|
||||
*
|
||||
* @return BelongsTo 부여 관리자 관계
|
||||
*/
|
||||
public function grantedByUser(): BelongsTo
|
||||
{
|
||||
return $this->belongsTo(User::class, 'granted_by');
|
||||
}
|
||||
|
||||
/**
|
||||
* 원본 적립건 관계 (차감 시 FIFO 추적)
|
||||
*
|
||||
* @return BelongsTo 원본 적립건 관계
|
||||
*/
|
||||
public function sourceTransaction(): BelongsTo
|
||||
{
|
||||
return $this->belongsTo(self::class, 'source_transaction_id');
|
||||
}
|
||||
|
||||
/**
|
||||
* 사용 가능한 적립건(lot) 스코프: 잔여금액 > 0, 미소멸, 미만료
|
||||
*
|
||||
* @param Builder $query 쿼리 빌더
|
||||
* @return Builder 적용된 쿼리 빌더
|
||||
*/
|
||||
public function scopeActive(Builder $query): Builder
|
||||
{
|
||||
return $query->where('remaining_amount', '>', 0)
|
||||
->whereNull('expired_at')
|
||||
->where(function (Builder $q) {
|
||||
$q->whereNull('expires_at')
|
||||
->orWhere('expires_at', '>', now());
|
||||
});
|
||||
}
|
||||
|
||||
/**
|
||||
* 특정 시점 이전 만료 예정 적립건 스코프 (잔여금액 > 0, 미소멸)
|
||||
*
|
||||
* @param Builder $query 쿼리 빌더
|
||||
* @param Carbon $before 기준 시각
|
||||
* @return Builder 적용된 쿼리 빌더
|
||||
*/
|
||||
public function scopeExpiringBefore(Builder $query, $before): Builder
|
||||
{
|
||||
return $query->where('remaining_amount', '>', 0)
|
||||
->whereNull('expired_at')
|
||||
->whereNotNull('expires_at')
|
||||
->where('expires_at', '<=', $before);
|
||||
}
|
||||
|
||||
/**
|
||||
* 회원 + 통화 한정 스코프
|
||||
*
|
||||
* @param Builder $query 쿼리 빌더
|
||||
* @param int $userId 회원 ID
|
||||
* @param string $currency 통화 코드
|
||||
* @return Builder 적용된 쿼리 빌더
|
||||
*/
|
||||
public function scopeForUserCurrency(Builder $query, int $userId, string $currency): Builder
|
||||
{
|
||||
return $query->where('user_id', $userId)->where('currency', $currency);
|
||||
}
|
||||
}
|
||||
@@ -23,7 +23,7 @@ class Order extends Model
|
||||
|
||||
/** @var array<string, array> 활동 로그 추적 필드 */
|
||||
public static array $activityLogFields = [
|
||||
'order_status' => ['label_key' => 'sirsoft-ecommerce::activity_log.fields.order_status', 'type' => 'enum', 'enum' => \Modules\Sirsoft\Ecommerce\Enums\OrderStatusEnum::class],
|
||||
'order_status' => ['label_key' => 'sirsoft-ecommerce::activity_log.fields.order_status', 'type' => 'enum', 'enum' => OrderStatusEnum::class],
|
||||
'total_amount' => ['label_key' => 'sirsoft-ecommerce::activity_log.fields.total_amount', 'type' => 'currency'],
|
||||
'total_paid_amount' => ['label_key' => 'sirsoft-ecommerce::activity_log.fields.total_paid_amount', 'type' => 'currency'],
|
||||
'total_discount_amount' => ['label_key' => 'sirsoft-ecommerce::activity_log.fields.total_discount_amount', 'type' => 'currency'],
|
||||
@@ -50,7 +50,7 @@ class Order extends Model
|
||||
*
|
||||
* @param mixed $value 라우트 파라미터 값 (ID 또는 order_number)
|
||||
* @param string|null $field 검색할 필드명
|
||||
* @return \Illuminate\Database\Eloquent\Model|null
|
||||
* @return Model|null
|
||||
*/
|
||||
public function resolveRouteBinding($value, $field = null)
|
||||
{
|
||||
@@ -70,6 +70,7 @@ class Order extends Model
|
||||
protected $fillable = [
|
||||
'user_id',
|
||||
'order_number',
|
||||
'guest_lookup_password_hash',
|
||||
'order_status',
|
||||
'order_device',
|
||||
'is_first_order',
|
||||
@@ -91,6 +92,7 @@ class Order extends Model
|
||||
'total_vat_amount',
|
||||
'total_tax_free_amount',
|
||||
'total_points_used_amount',
|
||||
'is_mileage_deducted',
|
||||
'total_deposit_used_amount',
|
||||
'total_paid_amount',
|
||||
'total_due_amount',
|
||||
@@ -106,6 +108,7 @@ class Order extends Model
|
||||
'paid_at',
|
||||
'payment_due_at',
|
||||
'confirmed_at',
|
||||
'cancelled_at',
|
||||
'admin_memo',
|
||||
'promotions_applied_snapshot',
|
||||
'shipping_policy_applied_snapshot',
|
||||
@@ -130,6 +133,15 @@ class Order extends Model
|
||||
'mc_total_paid_amount',
|
||||
];
|
||||
|
||||
/**
|
||||
* 직렬화 시 숨길 속성 (API 응답·배열 변환 노출 차단)
|
||||
*
|
||||
* @var array<int, string>
|
||||
*/
|
||||
protected $hidden = [
|
||||
'guest_lookup_password_hash',
|
||||
];
|
||||
|
||||
protected $casts = [
|
||||
'is_first_order' => 'boolean',
|
||||
'currency_snapshot' => 'array',
|
||||
@@ -148,6 +160,7 @@ class Order extends Model
|
||||
'total_vat_amount' => 'decimal:2',
|
||||
'total_tax_free_amount' => 'decimal:2',
|
||||
'total_points_used_amount' => 'decimal:2',
|
||||
'is_mileage_deducted' => 'boolean',
|
||||
'total_deposit_used_amount' => 'decimal:2',
|
||||
'total_paid_amount' => 'decimal:2',
|
||||
'total_due_amount' => 'decimal:2',
|
||||
@@ -163,6 +176,7 @@ class Order extends Model
|
||||
'paid_at' => 'datetime',
|
||||
'payment_due_at' => 'datetime',
|
||||
'confirmed_at' => 'datetime',
|
||||
'cancelled_at' => 'datetime',
|
||||
'promotions_applied_snapshot' => 'array',
|
||||
'shipping_policy_applied_snapshot' => 'array',
|
||||
'promotions_available_snapshot' => 'array',
|
||||
@@ -310,6 +324,39 @@ class Order extends Model
|
||||
return $this->shippingAddress?->orderer_name;
|
||||
}
|
||||
|
||||
/**
|
||||
* 주문자 이메일 반환 (배송지 기준)
|
||||
*
|
||||
* @return string|null 주문자 이메일
|
||||
*/
|
||||
public function getOrdererEmail(): ?string
|
||||
{
|
||||
return $this->shippingAddress?->orderer_email;
|
||||
}
|
||||
|
||||
/**
|
||||
* 주문자 선호 언어를 반환합니다. (배송지 기준)
|
||||
*
|
||||
* 주문 시점의 화면 언어 스냅샷으로, 비회원 알림 발송 언어를 결정하는 데 사용됩니다.
|
||||
* 저장값이 없으면(구버전 주문) null 을 반환해 수신 측에서 기본 로케일로 폴백합니다.
|
||||
*
|
||||
* @return string|null 주문자 선호 언어 또는 null
|
||||
*/
|
||||
public function getOrdererLocale(): ?string
|
||||
{
|
||||
return $this->shippingAddress?->orderer_locale;
|
||||
}
|
||||
|
||||
/**
|
||||
* 비회원 주문 여부를 반환합니다.
|
||||
*
|
||||
* @return bool 회원 미연결(user_id = null) 주문이면 true
|
||||
*/
|
||||
public function isGuestOrder(): bool
|
||||
{
|
||||
return $this->user_id === null;
|
||||
}
|
||||
|
||||
/**
|
||||
* 수령인명 반환 (배송지 기준)
|
||||
*
|
||||
@@ -375,6 +422,8 @@ class Order extends Model
|
||||
return false;
|
||||
}
|
||||
|
||||
// 부분취소는 별도 상태가 아니라 잔여 옵션 기준 진행 상태(payment_complete 등)로 환원되므로,
|
||||
// 잔여 항목 재취소는 그 진행 상태가 이미 취소 가능 목록에 있어 자연히 허용된다(partial_cancelled 제거).
|
||||
$defaultStatuses = [
|
||||
OrderStatusEnum::PENDING_ORDER,
|
||||
OrderStatusEnum::PENDING_PAYMENT,
|
||||
@@ -471,4 +520,30 @@ class Order extends Model
|
||||
{
|
||||
return $this->order_status === OrderStatusEnum::DELIVERED;
|
||||
}
|
||||
|
||||
/**
|
||||
* 부분취소 상태 여부를 반환합니다 (파생 플래그).
|
||||
*
|
||||
* 부분취소는 별도 주문 상태(partial_cancelled)가 아니라 "취소된 옵션이 있으면서
|
||||
* 잔여 활성 옵션도 존재"하는 파생 상태다. 주문 상태(order_status)는 잔여 활성 옵션 기준으로
|
||||
* 결정되고, "일부가 취소되었다"는 사실은 이 플래그로 노출한다 (PO 2026-06-22, partial_cancelled 제거).
|
||||
*
|
||||
* @return bool 일부 옵션만 취소된 주문이면 true
|
||||
*/
|
||||
public function isPartiallyCancelled(): bool
|
||||
{
|
||||
$cancelledCount = $this->options
|
||||
? $this->options->where('option_status', OrderStatusEnum::CANCELLED)->count()
|
||||
: $this->options()->where('option_status', OrderStatusEnum::CANCELLED->value)->count();
|
||||
|
||||
if ($cancelledCount === 0) {
|
||||
return false;
|
||||
}
|
||||
|
||||
$activeCount = $this->options
|
||||
? $this->options->where('option_status', '!=', OrderStatusEnum::CANCELLED)->count()
|
||||
: $this->options()->where('option_status', '!=', OrderStatusEnum::CANCELLED->value)->count();
|
||||
|
||||
return $activeCount > 0;
|
||||
}
|
||||
}
|
||||
@@ -18,8 +18,6 @@ class OrderAddress extends Model
|
||||
* 활동 로그 변경 감지 대상 필드
|
||||
*
|
||||
* ChangeDetector가 이 필드 목록을 기반으로 변경 전/후를 비교합니다.
|
||||
*
|
||||
* @var array
|
||||
*/
|
||||
public static array $activityLogFields = [
|
||||
'recipient_name' => [
|
||||
@@ -46,12 +44,17 @@ class OrderAddress extends Model
|
||||
'label_key' => 'sirsoft-ecommerce::activity_log.fields.delivery_memo',
|
||||
'type' => 'text',
|
||||
],
|
||||
'delivery_memo_label' => [
|
||||
'label_key' => 'sirsoft-ecommerce::activity_log.fields.delivery_memo_label',
|
||||
'type' => 'text',
|
||||
],
|
||||
];
|
||||
|
||||
protected static function newFactory()
|
||||
{
|
||||
return OrderAddressFactory::new();
|
||||
}
|
||||
|
||||
protected $table = 'ecommerce_order_addresses';
|
||||
|
||||
protected $fillable = [
|
||||
@@ -60,6 +63,7 @@ class OrderAddress extends Model
|
||||
'orderer_name',
|
||||
'orderer_phone',
|
||||
'orderer_email',
|
||||
'orderer_locale',
|
||||
'recipient_name',
|
||||
'recipient_phone',
|
||||
'recipient_email',
|
||||
@@ -77,6 +81,7 @@ class OrderAddress extends Model
|
||||
'intl_postal_code',
|
||||
'address_type_code',
|
||||
'delivery_memo',
|
||||
'delivery_memo_label',
|
||||
];
|
||||
|
||||
protected $casts = [
|
||||
|
||||
@@ -35,6 +35,7 @@ class OrderCancel extends Model
|
||||
'cancel_reason_type',
|
||||
'cancel_reason',
|
||||
'items_snapshot',
|
||||
'shipping_snapshot',
|
||||
'cancelled_by',
|
||||
'cancelled_at',
|
||||
];
|
||||
@@ -51,6 +52,7 @@ class OrderCancel extends Model
|
||||
'cancel_status' => CancelStatusEnum::class,
|
||||
'cancel_reason_type' => 'string',
|
||||
'items_snapshot' => 'array',
|
||||
'shipping_snapshot' => 'array',
|
||||
'cancelled_at' => 'datetime',
|
||||
];
|
||||
}
|
||||
@@ -58,7 +60,7 @@ class OrderCancel extends Model
|
||||
/**
|
||||
* 주문과의 관계
|
||||
*
|
||||
* @return BelongsTo
|
||||
* @return BelongsTo 소속 주문 관계
|
||||
*/
|
||||
public function order(): BelongsTo
|
||||
{
|
||||
@@ -68,7 +70,7 @@ class OrderCancel extends Model
|
||||
/**
|
||||
* 취소 옵션 목록과의 관계
|
||||
*
|
||||
* @return HasMany
|
||||
* @return HasMany 취소 옵션 목록 관계
|
||||
*/
|
||||
public function cancelOptions(): HasMany
|
||||
{
|
||||
@@ -78,7 +80,7 @@ class OrderCancel extends Model
|
||||
/**
|
||||
* 환불 레코드와의 관계
|
||||
*
|
||||
* @return HasOne
|
||||
* @return HasOne 연결된 환불 레코드 관계
|
||||
*/
|
||||
public function refund(): HasOne
|
||||
{
|
||||
@@ -88,7 +90,7 @@ class OrderCancel extends Model
|
||||
/**
|
||||
* 취소 요청자와의 관계
|
||||
*
|
||||
* @return BelongsTo
|
||||
* @return BelongsTo 취소 요청 사용자 관계
|
||||
*/
|
||||
public function cancelledByUser(): BelongsTo
|
||||
{
|
||||
@@ -98,7 +100,7 @@ class OrderCancel extends Model
|
||||
/**
|
||||
* 전체취소 여부를 반환합니다.
|
||||
*
|
||||
* @return bool
|
||||
* @return bool 전체취소이면 true
|
||||
*/
|
||||
public function isFullCancel(): bool
|
||||
{
|
||||
@@ -108,7 +110,7 @@ class OrderCancel extends Model
|
||||
/**
|
||||
* 취소 완료 여부를 반환합니다.
|
||||
*
|
||||
* @return bool
|
||||
* @return bool 취소 완료 상태이면 true
|
||||
*/
|
||||
public function isCompleted(): bool
|
||||
{
|
||||
@@ -120,7 +122,7 @@ class OrderCancel extends Model
|
||||
*
|
||||
* DB에서 클래임 사유를 조회하여 다국어 이름을 반환합니다.
|
||||
*
|
||||
* @return string
|
||||
* @return string 현지화된 환불 사유 라벨
|
||||
*/
|
||||
public function getRefundReasonLabel(): string
|
||||
{
|
||||
|
||||
@@ -8,6 +8,7 @@ use Illuminate\Database\Eloquent\Relations\BelongsTo;
|
||||
use Illuminate\Database\Eloquent\Relations\HasMany;
|
||||
use Illuminate\Database\Eloquent\Relations\HasOne;
|
||||
use Modules\Sirsoft\Ecommerce\Database\Factories\OrderOptionFactory;
|
||||
use Modules\Sirsoft\Ecommerce\Enums\MileageTransactionTypeEnum;
|
||||
use Modules\Sirsoft\Ecommerce\Enums\OrderOptionSourceTypeEnum;
|
||||
use Modules\Sirsoft\Ecommerce\Enums\OrderStatusEnum;
|
||||
|
||||
@@ -24,7 +25,7 @@ class OrderOption extends Model
|
||||
* @var array<string, array>
|
||||
*/
|
||||
public static array $activityLogFields = [
|
||||
'option_status' => ['label_key' => 'sirsoft-ecommerce::activity_log.fields.option_status', 'type' => 'enum', 'enum' => \Modules\Sirsoft\Ecommerce\Enums\OrderStatusEnum::class],
|
||||
'option_status' => ['label_key' => 'sirsoft-ecommerce::activity_log.fields.option_status', 'type' => 'enum', 'enum' => OrderStatusEnum::class],
|
||||
'quantity' => ['label_key' => 'sirsoft-ecommerce::activity_log.fields.quantity', 'type' => 'number'],
|
||||
'cancelled_quantity' => ['label_key' => 'sirsoft-ecommerce::activity_log.fields.cancelled_quantity', 'type' => 'number'],
|
||||
];
|
||||
@@ -58,6 +59,7 @@ class OrderOption extends Model
|
||||
'subtotal_weight',
|
||||
'subtotal_volume',
|
||||
'unit_price',
|
||||
'additional_options_total',
|
||||
'subtotal_price',
|
||||
'subtotal_discount_amount',
|
||||
'product_coupon_discount_amount',
|
||||
@@ -72,18 +74,22 @@ class OrderOption extends Model
|
||||
'subtotal_earned_points_amount',
|
||||
'product_snapshot',
|
||||
'option_snapshot',
|
||||
'additional_options_snapshot',
|
||||
'promotions_applied_snapshot',
|
||||
'confirmed_at',
|
||||
'delivered_at',
|
||||
'external_option_id',
|
||||
'external_meta',
|
||||
// 다중 통화 컬럼 (JSON)
|
||||
'mc_unit_price',
|
||||
'mc_additional_options_total',
|
||||
'mc_subtotal_price',
|
||||
'mc_product_coupon_discount_amount',
|
||||
'mc_order_coupon_discount_amount',
|
||||
'mc_coupon_discount_amount',
|
||||
'mc_code_discount_amount',
|
||||
'mc_subtotal_points_used_amount',
|
||||
'mc_subtotal_earned_points_amount',
|
||||
'mc_subtotal_deposit_used_amount',
|
||||
'mc_subtotal_tax_amount',
|
||||
'mc_subtotal_tax_free_amount',
|
||||
@@ -98,6 +104,7 @@ class OrderOption extends Model
|
||||
'subtotal_weight' => 'decimal:3',
|
||||
'subtotal_volume' => 'decimal:3',
|
||||
'unit_price' => 'decimal:2',
|
||||
'additional_options_total' => 'decimal:2',
|
||||
'subtotal_price' => 'decimal:2',
|
||||
'subtotal_discount_amount' => 'decimal:2',
|
||||
'product_coupon_discount_amount' => 'decimal:2',
|
||||
@@ -116,20 +123,24 @@ class OrderOption extends Model
|
||||
'option_value' => 'array',
|
||||
'product_snapshot' => 'array',
|
||||
'option_snapshot' => 'array',
|
||||
'additional_options_snapshot' => 'array',
|
||||
'promotions_applied_snapshot' => 'array',
|
||||
'external_meta' => 'array',
|
||||
'confirmed_at' => 'datetime',
|
||||
'delivered_at' => 'datetime',
|
||||
'option_status' => OrderStatusEnum::class,
|
||||
'is_stock_deducted' => 'boolean',
|
||||
'source_type' => OrderOptionSourceTypeEnum::class,
|
||||
// 다중 통화 컬럼 (JSON)
|
||||
'mc_unit_price' => 'array',
|
||||
'mc_additional_options_total' => 'array',
|
||||
'mc_subtotal_price' => 'array',
|
||||
'mc_product_coupon_discount_amount' => 'array',
|
||||
'mc_order_coupon_discount_amount' => 'array',
|
||||
'mc_coupon_discount_amount' => 'array',
|
||||
'mc_code_discount_amount' => 'array',
|
||||
'mc_subtotal_points_used_amount' => 'array',
|
||||
'mc_subtotal_earned_points_amount' => 'array',
|
||||
'mc_subtotal_deposit_used_amount' => 'array',
|
||||
'mc_subtotal_tax_amount' => 'array',
|
||||
'mc_subtotal_tax_free_amount' => 'array',
|
||||
@@ -272,4 +283,18 @@ class OrderOption extends Model
|
||||
{
|
||||
return $this->hasOne(ProductReview::class, 'order_option_id');
|
||||
}
|
||||
|
||||
/**
|
||||
* 구매 적립 마일리지 거래 관계
|
||||
*
|
||||
* 이 주문옵션에 대해 실제 발행된 구매 적립(purchase_earn) 거래입니다.
|
||||
* FK 없이 order_option_id 컬럼만 참조하며, 적립예정액의 실제 적립 여부 판정에 사용됩니다.
|
||||
*
|
||||
* @return HasMany 구매 적립 거래와의 관계
|
||||
*/
|
||||
public function purchaseEarnTransactions(): HasMany
|
||||
{
|
||||
return $this->hasMany(MileageTransaction::class, 'order_option_id')
|
||||
->where('type', MileageTransactionTypeEnum::PURCHASE_EARN->value);
|
||||
}
|
||||
}
|
||||
@@ -21,6 +21,7 @@ class OrderPayment extends Model
|
||||
{
|
||||
return OrderPaymentFactory::new();
|
||||
}
|
||||
|
||||
protected $table = 'ecommerce_order_payments';
|
||||
|
||||
protected $fillable = [
|
||||
@@ -172,13 +173,34 @@ class OrderPayment extends Model
|
||||
}
|
||||
|
||||
/**
|
||||
* 취소 가능 금액 계산
|
||||
* 취소 가능 금액 계산 (결제 통화 order_currency 기준).
|
||||
*
|
||||
* @return float 취소 가능 금액
|
||||
* paid_amount_local 은 결제 통화 실청구액이므로 누적 취소액도 결제 통화로 맞춰야 한다.
|
||||
* 코어가 결제 통화로 누적한 mc_cancelled_amount[order_currency] 를 우선 사용하고,
|
||||
* 없으면(레거시 결제) base 누적 cancelled_amount 로 폴백한다.
|
||||
*
|
||||
* @return float 취소 가능 금액 (결제 통화)
|
||||
*/
|
||||
public function getCancellableAmount(): float
|
||||
{
|
||||
return $this->paid_amount_local - $this->cancelled_amount;
|
||||
return $this->paid_amount_local - $this->cancelledLocalAmount();
|
||||
}
|
||||
|
||||
/**
|
||||
* 결제 통화(order_currency) 기준 누적 취소액을 반환합니다.
|
||||
*
|
||||
* @return float 결제 통화 기준 누적 취소액
|
||||
*/
|
||||
public function cancelledLocalAmount(): float
|
||||
{
|
||||
$currency = $this->currency;
|
||||
$mc = $this->mc_cancelled_amount ?? [];
|
||||
|
||||
if ($currency !== null && isset($mc[$currency])) {
|
||||
return (float) $mc[$currency];
|
||||
}
|
||||
|
||||
return (float) $this->cancelled_amount;
|
||||
}
|
||||
|
||||
/**
|
||||
|
||||
@@ -31,9 +31,9 @@ class Product extends Model implements FulltextSearchable
|
||||
|
||||
/** @var array<string, array> 활동 로그 추적 필드 */
|
||||
public static array $activityLogFields = [
|
||||
'sales_status' => ['label_key' => 'sirsoft-ecommerce::activity_log.fields.sales_status', 'type' => 'enum', 'enum' => \Modules\Sirsoft\Ecommerce\Enums\ProductSalesStatus::class],
|
||||
'display_status' => ['label_key' => 'sirsoft-ecommerce::activity_log.fields.display_status', 'type' => 'enum', 'enum' => \Modules\Sirsoft\Ecommerce\Enums\ProductDisplayStatus::class],
|
||||
'tax_status' => ['label_key' => 'sirsoft-ecommerce::activity_log.fields.tax_status', 'type' => 'enum', 'enum' => \Modules\Sirsoft\Ecommerce\Enums\ProductTaxStatus::class],
|
||||
'sales_status' => ['label_key' => 'sirsoft-ecommerce::activity_log.fields.sales_status', 'type' => 'enum', 'enum' => ProductSalesStatus::class],
|
||||
'display_status' => ['label_key' => 'sirsoft-ecommerce::activity_log.fields.display_status', 'type' => 'enum', 'enum' => ProductDisplayStatus::class],
|
||||
'tax_status' => ['label_key' => 'sirsoft-ecommerce::activity_log.fields.tax_status', 'type' => 'enum', 'enum' => ProductTaxStatus::class],
|
||||
'tax_rate' => ['label_key' => 'sirsoft-ecommerce::activity_log.fields.tax_rate', 'type' => 'number'],
|
||||
'list_price' => ['label_key' => 'sirsoft-ecommerce::activity_log.fields.list_price', 'type' => 'currency'],
|
||||
'selling_price' => ['label_key' => 'sirsoft-ecommerce::activity_log.fields.selling_price', 'type' => 'currency'],
|
||||
@@ -57,7 +57,7 @@ class Product extends Model implements FulltextSearchable
|
||||
*
|
||||
* @param mixed $value 라우트 파라미터 값 (ID 또는 product_code)
|
||||
* @param string|null $field 검색할 필드명
|
||||
* @return \Illuminate\Database\Eloquent\Model|null
|
||||
* @return Model|null
|
||||
*/
|
||||
public function resolveRouteBinding($value, $field = null)
|
||||
{
|
||||
@@ -96,6 +96,8 @@ class Product extends Model implements FulltextSearchable
|
||||
'meta_title',
|
||||
'meta_description',
|
||||
'meta_keywords',
|
||||
'seo_sync_title',
|
||||
'seo_sync_description',
|
||||
'has_options',
|
||||
'option_groups',
|
||||
'min_purchase_qty',
|
||||
@@ -111,12 +113,16 @@ class Product extends Model implements FulltextSearchable
|
||||
protected $casts = [
|
||||
'name' => AsUnicodeJson::class,
|
||||
'description' => AsUnicodeJson::class,
|
||||
'meta_title' => AsUnicodeJson::class,
|
||||
'meta_description' => AsUnicodeJson::class,
|
||||
'meta_keywords' => 'array',
|
||||
'seo_sync_title' => 'boolean',
|
||||
'seo_sync_description' => 'boolean',
|
||||
'option_groups' => 'array',
|
||||
'allowed_roles' => 'array',
|
||||
'has_options' => 'boolean',
|
||||
'list_price' => 'integer',
|
||||
'selling_price' => 'integer',
|
||||
'list_price' => 'decimal:2',
|
||||
'selling_price' => 'decimal:2',
|
||||
'stock_quantity' => 'integer',
|
||||
'safe_stock_quantity' => 'integer',
|
||||
'min_purchase_qty' => 'integer',
|
||||
@@ -302,7 +308,7 @@ class Product extends Model implements FulltextSearchable
|
||||
/**
|
||||
* 상품 리뷰 관계
|
||||
*
|
||||
* @return HasMany
|
||||
* @return HasMany ProductReview 컬렉션 관계
|
||||
*/
|
||||
public function reviews(): HasMany
|
||||
{
|
||||
@@ -312,7 +318,7 @@ class Product extends Model implements FulltextSearchable
|
||||
/**
|
||||
* 전시중(visible) 리뷰만 조회 (withCount/withAvg eager loading용)
|
||||
*
|
||||
* @return HasMany
|
||||
* @return HasMany 전시중 ProductReview 컬렉션 관계
|
||||
*/
|
||||
public function visibleReviews(): HasMany
|
||||
{
|
||||
@@ -496,6 +502,20 @@ class Product extends Model implements FulltextSearchable
|
||||
return $this->stock_quantity <= $this->safe_stock_quantity;
|
||||
}
|
||||
|
||||
/**
|
||||
* 상품이 현재 구매 가능한 상태인지 반환합니다.
|
||||
*
|
||||
* 담기/합계/체크아웃의 판매상태 판정을 한 곳으로 통일하는 단일 기준(SSoT).
|
||||
* 판매중(on_sale) + 전시중(visible) 두 조건을 모두 만족해야 구매 가능합니다.
|
||||
*
|
||||
* @return bool 판매중(on_sale) + 전시중(visible) 이면 true
|
||||
*/
|
||||
public function isPurchasable(): bool
|
||||
{
|
||||
return $this->sales_status === ProductSalesStatus::ON_SALE
|
||||
&& $this->display_status === ProductDisplayStatus::VISIBLE;
|
||||
}
|
||||
|
||||
/**
|
||||
* 정가 대비 판매가의 할인율(%) 을 소수 1자리로 반환합니다.
|
||||
*
|
||||
@@ -578,7 +598,7 @@ class Product extends Model implements FulltextSearchable
|
||||
/**
|
||||
* MySQL FULLTEXT 엔진에서는 인덱스 업데이트가 불필요합니다.
|
||||
*
|
||||
* @return bool
|
||||
* @return bool 인덱스 갱신 필요 여부 (항상 false)
|
||||
*/
|
||||
public function searchIndexShouldBeUpdated(): bool
|
||||
{
|
||||
|
||||
@@ -4,9 +4,10 @@ namespace Modules\Sirsoft\Ecommerce\Models;
|
||||
|
||||
use Illuminate\Database\Eloquent\Model;
|
||||
use Illuminate\Database\Eloquent\Relations\BelongsTo;
|
||||
use Illuminate\Database\Eloquent\Relations\HasMany;
|
||||
|
||||
/**
|
||||
* 상품 추가옵션 모델
|
||||
* 상품 추가옵션 그룹 모델
|
||||
*/
|
||||
class ProductAdditionalOption extends Model
|
||||
{
|
||||
@@ -35,10 +36,30 @@ class ProductAdditionalOption extends Model
|
||||
return $this->belongsTo(Product::class, 'product_id');
|
||||
}
|
||||
|
||||
/**
|
||||
* 선택지 관계
|
||||
*
|
||||
* @return HasMany 추가옵션 선택지 모델과의 관계
|
||||
*/
|
||||
public function values(): HasMany
|
||||
{
|
||||
return $this->hasMany(ProductAdditionalOptionValue::class, 'additional_option_id');
|
||||
}
|
||||
|
||||
/**
|
||||
* 활성 선택지 관계 (정렬 적용)
|
||||
*
|
||||
* @return HasMany 활성 선택지 모델과의 관계
|
||||
*/
|
||||
public function activeValues(): HasMany
|
||||
{
|
||||
return $this->values()->where('is_active', true)->orderBy('sort_order');
|
||||
}
|
||||
|
||||
/**
|
||||
* 현재 로케일의 옵션명 반환
|
||||
*
|
||||
* @param string|null $locale 로케일
|
||||
* @param string|null $locale 로케일
|
||||
* @return string 옵션명
|
||||
*/
|
||||
public function getLocalizedName(?string $locale = null): string
|
||||
|
||||
@@ -0,0 +1,95 @@
|
||||
<?php
|
||||
|
||||
namespace Modules\Sirsoft\Ecommerce\Models;
|
||||
|
||||
use Illuminate\Database\Eloquent\Model;
|
||||
use Illuminate\Database\Eloquent\Relations\BelongsTo;
|
||||
|
||||
/**
|
||||
* 상품 추가옵션 선택지 모델
|
||||
*
|
||||
* 추가옵션 그룹(ProductAdditionalOption)의 하위 선택지로,
|
||||
* 각 선택지는 KRW 기준 추가금(price_adjustment)을 보유합니다.
|
||||
*/
|
||||
class ProductAdditionalOptionValue extends Model
|
||||
{
|
||||
protected $table = 'ecommerce_product_additional_option_values';
|
||||
|
||||
protected $fillable = [
|
||||
'additional_option_id',
|
||||
'name',
|
||||
'price_adjustment',
|
||||
'mc_price_adjustment',
|
||||
'is_default',
|
||||
'is_active',
|
||||
'allow_custom_text',
|
||||
'sort_order',
|
||||
];
|
||||
|
||||
protected $casts = [
|
||||
'additional_option_id' => 'integer',
|
||||
'name' => 'array',
|
||||
'price_adjustment' => 'integer',
|
||||
'mc_price_adjustment' => 'array',
|
||||
'is_default' => 'boolean',
|
||||
'is_active' => 'boolean',
|
||||
'allow_custom_text' => 'boolean',
|
||||
'sort_order' => 'integer',
|
||||
];
|
||||
|
||||
/**
|
||||
* 추가옵션 그룹 관계
|
||||
*
|
||||
* @return BelongsTo 추가옵션 그룹 모델과의 관계
|
||||
*/
|
||||
public function additionalOption(): BelongsTo
|
||||
{
|
||||
return $this->belongsTo(ProductAdditionalOption::class, 'additional_option_id');
|
||||
}
|
||||
|
||||
/**
|
||||
* 현재 로케일의 선택지명 반환
|
||||
*
|
||||
* @param string|null $locale 로케일 (null이면 현재 로케일)
|
||||
* @return string 로컬라이즈된 선택지명
|
||||
*/
|
||||
public function getLocalizedName(?string $locale = null): string
|
||||
{
|
||||
$locale = $locale ?? app()->getLocale();
|
||||
$name = $this->name;
|
||||
|
||||
if (! is_array($name)) {
|
||||
return is_string($name) ? $name : '';
|
||||
}
|
||||
|
||||
return $name[$locale] ?? $name[config('app.fallback_locale', 'ko')] ?? $name[array_key_first($name)] ?? '';
|
||||
}
|
||||
|
||||
/**
|
||||
* 추가금 반환 (KRW 기준)
|
||||
*
|
||||
* @return int 추가금
|
||||
*/
|
||||
public function getPriceAdjustment(): int
|
||||
{
|
||||
return (int) ($this->price_adjustment ?? 0);
|
||||
}
|
||||
|
||||
/**
|
||||
* 주문 스냅샷용 배열 반환
|
||||
*
|
||||
* 주문 생성 시점의 선택지 정보를 동결하기 위한 데이터입니다.
|
||||
*
|
||||
* @return array 스냅샷 데이터
|
||||
*/
|
||||
public function toSnapshotArray(): array
|
||||
{
|
||||
return [
|
||||
'additional_option_id' => (int) $this->additional_option_id,
|
||||
'value_id' => (int) $this->id,
|
||||
'name' => $this->name,
|
||||
'price_adjustment' => $this->getPriceAdjustment(),
|
||||
'mc_price_adjustment' => $this->mc_price_adjustment,
|
||||
];
|
||||
}
|
||||
}
|
||||
@@ -62,7 +62,7 @@ class ProductOption extends Model
|
||||
protected $casts = [
|
||||
'option_values' => 'array',
|
||||
'option_name' => 'array',
|
||||
'price_adjustment' => 'integer',
|
||||
'price_adjustment' => 'decimal:2',
|
||||
'stock_quantity' => 'integer',
|
||||
'safe_stock_quantity' => 'integer',
|
||||
'weight' => 'decimal:2',
|
||||
@@ -77,7 +77,7 @@ class ProductOption extends Model
|
||||
/**
|
||||
* 상품 관계
|
||||
*
|
||||
* @return BelongsTo
|
||||
* @return BelongsTo 이 옵션이 속한 상품 관계
|
||||
*/
|
||||
public function product(): BelongsTo
|
||||
{
|
||||
@@ -87,29 +87,31 @@ class ProductOption extends Model
|
||||
/**
|
||||
* 최종 판매가 계산 (상품 판매가 + 옵션 조정액)
|
||||
*
|
||||
* @return int
|
||||
* 기본통화가 소수 통화(USD 등)일 수 있어 소수 가격을 보존합니다.
|
||||
*
|
||||
* @return float 옵션 최종 판매가 (소수 가격 보존)
|
||||
*/
|
||||
public function getFinalPrice(): int
|
||||
public function getFinalPrice(): float
|
||||
{
|
||||
return $this->product->selling_price + $this->price_adjustment;
|
||||
return (float) $this->product->selling_price + (float) $this->price_adjustment;
|
||||
}
|
||||
|
||||
/**
|
||||
* 최종 정가 계산 (상품 정가 + 옵션 조정액)
|
||||
*
|
||||
* @return int
|
||||
* @return float 옵션 최종 정가 (소수 가격 보존)
|
||||
*/
|
||||
public function getListPrice(): int
|
||||
public function getListPrice(): float
|
||||
{
|
||||
return $this->product->list_price + $this->price_adjustment;
|
||||
return (float) $this->product->list_price + (float) $this->price_adjustment;
|
||||
}
|
||||
|
||||
/**
|
||||
* 최종 판매가 계산 (상품 판매가 + 옵션 조정액) - getFinalPrice의 별칭
|
||||
*
|
||||
* @return int
|
||||
* @return float 옵션 최종 판매가 (소수 가격 보존)
|
||||
*/
|
||||
public function getSellingPrice(): int
|
||||
public function getSellingPrice(): float
|
||||
{
|
||||
return $this->getFinalPrice();
|
||||
}
|
||||
@@ -117,7 +119,7 @@ class ProductOption extends Model
|
||||
/**
|
||||
* 안전재고 이하 여부
|
||||
*
|
||||
* @return bool
|
||||
* @return bool 현재 재고가 안전재고 이하이면 true
|
||||
*/
|
||||
public function isBelowSafeStock(): bool
|
||||
{
|
||||
|
||||
@@ -4,6 +4,7 @@ namespace Modules\Sirsoft\Ecommerce\Models;
|
||||
|
||||
use Illuminate\Database\Eloquent\Model;
|
||||
use Illuminate\Database\Eloquent\Relations\BelongsTo;
|
||||
use Modules\Sirsoft\Ecommerce\Casts\ShippingApiConfigCast;
|
||||
use Modules\Sirsoft\Ecommerce\Enums\ChargePolicyEnum;
|
||||
|
||||
/**
|
||||
@@ -28,6 +29,7 @@ class ShippingPolicyCountrySetting extends Model
|
||||
'api_endpoint',
|
||||
'api_request_fields',
|
||||
'api_response_fee_field',
|
||||
'api_config',
|
||||
'extra_fee_enabled',
|
||||
'extra_fee_settings',
|
||||
'extra_fee_multiply',
|
||||
@@ -37,6 +39,7 @@ class ShippingPolicyCountrySetting extends Model
|
||||
protected $casts = [
|
||||
'ranges' => 'array',
|
||||
'api_request_fields' => 'array',
|
||||
'api_config' => ShippingApiConfigCast::class,
|
||||
'extra_fee_settings' => 'array',
|
||||
'base_fee' => 'decimal:2',
|
||||
'free_threshold' => 'decimal:2',
|
||||
@@ -168,9 +171,9 @@ class ShippingPolicyCountrySetting extends Model
|
||||
{
|
||||
return [
|
||||
'type' => $this->charge_policy->value,
|
||||
'base_fee' => number_format($this->base_fee).'원',
|
||||
'base_fee' => ecommerce_format_price($this->base_fee ?? 0),
|
||||
'free_threshold' => $this->free_threshold
|
||||
? number_format($this->free_threshold).'원'
|
||||
? ecommerce_format_price($this->free_threshold)
|
||||
: null,
|
||||
'tiers' => $this->formatTiersArray(),
|
||||
];
|
||||
@@ -206,7 +209,7 @@ class ShippingPolicyCountrySetting extends Model
|
||||
|
||||
$result[] = [
|
||||
'range' => $range,
|
||||
'fee' => number_format($fee).'원',
|
||||
'fee' => ecommerce_format_price($fee),
|
||||
];
|
||||
}
|
||||
|
||||
|
||||
Reference in new issue
Block a user