feat: 매출/매입 관리 API 구현
- 매출(Sale) 및 매입(Purchase) CRUD API 구현
- 문서번호 자동 생성 (SL/PU + YYYYMMDD + 시퀀스)
- 상태 관리 (draft → confirmed → invoiced)
- 확정(confirm) 및 요약(summary) 기능 추가
- BelongsToTenant, SoftDeletes 적용
- Swagger API 문서 작성 완료
추가된 파일:
- 마이그레이션: sales, purchases 테이블
- 모델: Sale, Purchase
- 서비스: SaleService, PurchaseService
- 컨트롤러: SaleController, PurchaseController
- FormRequest: Store/Update 4개
- Swagger: SaleApi.php, PurchaseApi.php
API 엔드포인트 (14개):
- GET/POST /v1/sales, /v1/purchases
- GET/PUT/DELETE /v1/{sales,purchases}/{id}
- POST /v1/{sales,purchases}/{id}/confirm
- GET /v1/{sales,purchases}/summary
2025-12-17 22:14:48 +09:00
|
|
|
<?php
|
|
|
|
|
|
|
|
|
|
namespace App\Services;
|
|
|
|
|
|
|
|
|
|
use App\Models\Tenants\Purchase;
|
|
|
|
|
use Illuminate\Contracts\Pagination\LengthAwarePaginator;
|
|
|
|
|
use Illuminate\Support\Facades\DB;
|
|
|
|
|
|
|
|
|
|
class PurchaseService extends Service
|
|
|
|
|
{
|
|
|
|
|
/**
|
|
|
|
|
* 매입 목록 조회
|
|
|
|
|
*/
|
|
|
|
|
public function index(array $params): LengthAwarePaginator
|
|
|
|
|
{
|
|
|
|
|
$tenantId = $this->tenantId();
|
|
|
|
|
|
|
|
|
|
$query = Purchase::query()
|
|
|
|
|
->where('tenant_id', $tenantId)
|
|
|
|
|
->with(['client:id,name']);
|
|
|
|
|
|
|
|
|
|
// 검색어 필터
|
|
|
|
|
if (! empty($params['search'])) {
|
|
|
|
|
$search = $params['search'];
|
|
|
|
|
$query->where(function ($q) use ($search) {
|
|
|
|
|
$q->where('purchase_number', 'like', "%{$search}%")
|
|
|
|
|
->orWhere('description', 'like', "%{$search}%")
|
|
|
|
|
->orWhereHas('client', function ($q) use ($search) {
|
|
|
|
|
$q->where('name', 'like', "%{$search}%");
|
|
|
|
|
});
|
|
|
|
|
});
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
// 날짜 범위 필터
|
|
|
|
|
if (! empty($params['start_date'])) {
|
|
|
|
|
$query->where('purchase_date', '>=', $params['start_date']);
|
|
|
|
|
}
|
|
|
|
|
if (! empty($params['end_date'])) {
|
|
|
|
|
$query->where('purchase_date', '<=', $params['end_date']);
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
// 거래처 필터
|
|
|
|
|
if (! empty($params['client_id'])) {
|
|
|
|
|
$query->where('client_id', $params['client_id']);
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
// 상태 필터
|
|
|
|
|
if (! empty($params['status'])) {
|
|
|
|
|
$query->where('status', $params['status']);
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
// 정렬
|
|
|
|
|
$sortBy = $params['sort_by'] ?? 'purchase_date';
|
|
|
|
|
$sortDir = $params['sort_dir'] ?? 'desc';
|
|
|
|
|
$query->orderBy($sortBy, $sortDir);
|
|
|
|
|
|
|
|
|
|
// 페이지네이션
|
|
|
|
|
$perPage = $params['per_page'] ?? 20;
|
|
|
|
|
|
|
|
|
|
return $query->paginate($perPage);
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
/**
|
|
|
|
|
* 매입 상세 조회
|
|
|
|
|
*/
|
|
|
|
|
public function show(int $id): Purchase
|
|
|
|
|
{
|
|
|
|
|
$tenantId = $this->tenantId();
|
|
|
|
|
|
|
|
|
|
return Purchase::query()
|
|
|
|
|
->where('tenant_id', $tenantId)
|
|
|
|
|
->with(['client:id,name', 'withdrawal', 'creator:id,name'])
|
|
|
|
|
->findOrFail($id);
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
/**
|
|
|
|
|
* 매입 등록
|
|
|
|
|
*/
|
|
|
|
|
public function store(array $data): Purchase
|
|
|
|
|
{
|
|
|
|
|
$tenantId = $this->tenantId();
|
|
|
|
|
$userId = $this->apiUserId();
|
|
|
|
|
|
|
|
|
|
return DB::transaction(function () use ($data, $tenantId, $userId) {
|
|
|
|
|
// 매입번호 자동 생성
|
|
|
|
|
$purchaseNumber = $this->generatePurchaseNumber($tenantId, $data['purchase_date']);
|
|
|
|
|
|
|
|
|
|
$purchase = new Purchase;
|
|
|
|
|
$purchase->tenant_id = $tenantId;
|
|
|
|
|
$purchase->purchase_number = $purchaseNumber;
|
|
|
|
|
$purchase->purchase_date = $data['purchase_date'];
|
|
|
|
|
$purchase->client_id = $data['client_id'];
|
|
|
|
|
$purchase->supply_amount = $data['supply_amount'];
|
|
|
|
|
$purchase->tax_amount = $data['tax_amount'];
|
|
|
|
|
$purchase->total_amount = $data['total_amount'];
|
2025-12-27 16:47:26 +09:00
|
|
|
$purchase->purchase_type = $data['purchase_type'] ?? null;
|
feat: 매출/매입 관리 API 구현
- 매출(Sale) 및 매입(Purchase) CRUD API 구현
- 문서번호 자동 생성 (SL/PU + YYYYMMDD + 시퀀스)
- 상태 관리 (draft → confirmed → invoiced)
- 확정(confirm) 및 요약(summary) 기능 추가
- BelongsToTenant, SoftDeletes 적용
- Swagger API 문서 작성 완료
추가된 파일:
- 마이그레이션: sales, purchases 테이블
- 모델: Sale, Purchase
- 서비스: SaleService, PurchaseService
- 컨트롤러: SaleController, PurchaseController
- FormRequest: Store/Update 4개
- Swagger: SaleApi.php, PurchaseApi.php
API 엔드포인트 (14개):
- GET/POST /v1/sales, /v1/purchases
- GET/PUT/DELETE /v1/{sales,purchases}/{id}
- POST /v1/{sales,purchases}/{id}/confirm
- GET /v1/{sales,purchases}/summary
2025-12-17 22:14:48 +09:00
|
|
|
$purchase->description = $data['description'] ?? null;
|
|
|
|
|
$purchase->status = 'draft';
|
|
|
|
|
$purchase->withdrawal_id = $data['withdrawal_id'] ?? null;
|
|
|
|
|
$purchase->created_by = $userId;
|
|
|
|
|
$purchase->updated_by = $userId;
|
|
|
|
|
$purchase->save();
|
|
|
|
|
|
|
|
|
|
return $purchase->load(['client:id,name']);
|
|
|
|
|
});
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
/**
|
|
|
|
|
* 매입 수정
|
|
|
|
|
*/
|
|
|
|
|
public function update(int $id, array $data): Purchase
|
|
|
|
|
{
|
|
|
|
|
$tenantId = $this->tenantId();
|
|
|
|
|
$userId = $this->apiUserId();
|
|
|
|
|
|
|
|
|
|
return DB::transaction(function () use ($id, $data, $tenantId, $userId) {
|
|
|
|
|
$purchase = Purchase::query()
|
|
|
|
|
->where('tenant_id', $tenantId)
|
|
|
|
|
->findOrFail($id);
|
|
|
|
|
|
2025-12-24 16:16:53 +09:00
|
|
|
// 토글 필드만 업데이트하는 경우는 canEdit 체크 건너뛰기
|
|
|
|
|
$toggleOnlyFields = ['tax_invoice_received'];
|
|
|
|
|
$isToggleOnly = count(array_diff(array_keys($data), $toggleOnlyFields)) === 0;
|
|
|
|
|
|
|
|
|
|
// 확정 후에는 수정 불가 (토글 필드만 업데이트하는 경우 제외)
|
|
|
|
|
if (! $isToggleOnly && ! $purchase->canEdit()) {
|
feat: 매출/매입 관리 API 구현
- 매출(Sale) 및 매입(Purchase) CRUD API 구현
- 문서번호 자동 생성 (SL/PU + YYYYMMDD + 시퀀스)
- 상태 관리 (draft → confirmed → invoiced)
- 확정(confirm) 및 요약(summary) 기능 추가
- BelongsToTenant, SoftDeletes 적용
- Swagger API 문서 작성 완료
추가된 파일:
- 마이그레이션: sales, purchases 테이블
- 모델: Sale, Purchase
- 서비스: SaleService, PurchaseService
- 컨트롤러: SaleController, PurchaseController
- FormRequest: Store/Update 4개
- Swagger: SaleApi.php, PurchaseApi.php
API 엔드포인트 (14개):
- GET/POST /v1/sales, /v1/purchases
- GET/PUT/DELETE /v1/{sales,purchases}/{id}
- POST /v1/{sales,purchases}/{id}/confirm
- GET /v1/{sales,purchases}/summary
2025-12-17 22:14:48 +09:00
|
|
|
throw new \Exception(__('error.purchase.cannot_edit'));
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
if (isset($data['purchase_date'])) {
|
|
|
|
|
$purchase->purchase_date = $data['purchase_date'];
|
|
|
|
|
}
|
|
|
|
|
if (isset($data['client_id'])) {
|
|
|
|
|
$purchase->client_id = $data['client_id'];
|
|
|
|
|
}
|
|
|
|
|
if (isset($data['supply_amount'])) {
|
|
|
|
|
$purchase->supply_amount = $data['supply_amount'];
|
|
|
|
|
}
|
|
|
|
|
if (isset($data['tax_amount'])) {
|
|
|
|
|
$purchase->tax_amount = $data['tax_amount'];
|
|
|
|
|
}
|
|
|
|
|
if (isset($data['total_amount'])) {
|
|
|
|
|
$purchase->total_amount = $data['total_amount'];
|
|
|
|
|
}
|
|
|
|
|
if (array_key_exists('description', $data)) {
|
|
|
|
|
$purchase->description = $data['description'];
|
|
|
|
|
}
|
|
|
|
|
if (array_key_exists('withdrawal_id', $data)) {
|
|
|
|
|
$purchase->withdrawal_id = $data['withdrawal_id'];
|
|
|
|
|
}
|
2025-12-27 16:47:26 +09:00
|
|
|
if (array_key_exists('purchase_type', $data)) {
|
|
|
|
|
$purchase->purchase_type = $data['purchase_type'];
|
|
|
|
|
}
|
2025-12-24 16:16:53 +09:00
|
|
|
if (array_key_exists('tax_invoice_received', $data)) {
|
|
|
|
|
$purchase->tax_invoice_received = $data['tax_invoice_received'];
|
|
|
|
|
}
|
feat: 매출/매입 관리 API 구현
- 매출(Sale) 및 매입(Purchase) CRUD API 구현
- 문서번호 자동 생성 (SL/PU + YYYYMMDD + 시퀀스)
- 상태 관리 (draft → confirmed → invoiced)
- 확정(confirm) 및 요약(summary) 기능 추가
- BelongsToTenant, SoftDeletes 적용
- Swagger API 문서 작성 완료
추가된 파일:
- 마이그레이션: sales, purchases 테이블
- 모델: Sale, Purchase
- 서비스: SaleService, PurchaseService
- 컨트롤러: SaleController, PurchaseController
- FormRequest: Store/Update 4개
- Swagger: SaleApi.php, PurchaseApi.php
API 엔드포인트 (14개):
- GET/POST /v1/sales, /v1/purchases
- GET/PUT/DELETE /v1/{sales,purchases}/{id}
- POST /v1/{sales,purchases}/{id}/confirm
- GET /v1/{sales,purchases}/summary
2025-12-17 22:14:48 +09:00
|
|
|
|
|
|
|
|
$purchase->updated_by = $userId;
|
|
|
|
|
$purchase->save();
|
|
|
|
|
|
|
|
|
|
return $purchase->fresh(['client:id,name']);
|
|
|
|
|
});
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
/**
|
|
|
|
|
* 매입 삭제
|
|
|
|
|
*/
|
|
|
|
|
public function destroy(int $id): bool
|
|
|
|
|
{
|
|
|
|
|
$tenantId = $this->tenantId();
|
|
|
|
|
$userId = $this->apiUserId();
|
|
|
|
|
|
|
|
|
|
return DB::transaction(function () use ($id, $tenantId, $userId) {
|
|
|
|
|
$purchase = Purchase::query()
|
|
|
|
|
->where('tenant_id', $tenantId)
|
|
|
|
|
->findOrFail($id);
|
|
|
|
|
|
|
|
|
|
// 확정 후에는 삭제 불가
|
|
|
|
|
if (! $purchase->canDelete()) {
|
|
|
|
|
throw new \Exception(__('error.purchase.cannot_delete'));
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
$purchase->deleted_by = $userId;
|
|
|
|
|
$purchase->save();
|
|
|
|
|
$purchase->delete();
|
|
|
|
|
|
|
|
|
|
return true;
|
|
|
|
|
});
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
/**
|
|
|
|
|
* 매입 확정
|
|
|
|
|
*/
|
|
|
|
|
public function confirm(int $id): Purchase
|
|
|
|
|
{
|
|
|
|
|
$tenantId = $this->tenantId();
|
|
|
|
|
$userId = $this->apiUserId();
|
|
|
|
|
|
|
|
|
|
return DB::transaction(function () use ($id, $tenantId, $userId) {
|
|
|
|
|
$purchase = Purchase::query()
|
|
|
|
|
->where('tenant_id', $tenantId)
|
|
|
|
|
->findOrFail($id);
|
|
|
|
|
|
|
|
|
|
if (! $purchase->canConfirm()) {
|
|
|
|
|
throw new \Exception(__('error.purchase.cannot_confirm'));
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
$purchase->status = 'confirmed';
|
|
|
|
|
$purchase->updated_by = $userId;
|
|
|
|
|
$purchase->save();
|
|
|
|
|
|
|
|
|
|
return $purchase->fresh(['client:id,name']);
|
|
|
|
|
});
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
/**
|
|
|
|
|
* 매입 요약 (기간별 합계)
|
|
|
|
|
*/
|
|
|
|
|
public function summary(array $params): array
|
|
|
|
|
{
|
|
|
|
|
$tenantId = $this->tenantId();
|
|
|
|
|
|
|
|
|
|
$query = Purchase::query()
|
|
|
|
|
->where('tenant_id', $tenantId);
|
|
|
|
|
|
|
|
|
|
// 날짜 범위 필터
|
|
|
|
|
if (! empty($params['start_date'])) {
|
|
|
|
|
$query->where('purchase_date', '>=', $params['start_date']);
|
|
|
|
|
}
|
|
|
|
|
if (! empty($params['end_date'])) {
|
|
|
|
|
$query->where('purchase_date', '<=', $params['end_date']);
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
// 거래처 필터
|
|
|
|
|
if (! empty($params['client_id'])) {
|
|
|
|
|
$query->where('client_id', $params['client_id']);
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
// 상태 필터
|
|
|
|
|
if (! empty($params['status'])) {
|
|
|
|
|
$query->where('status', $params['status']);
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
// 전체 합계
|
|
|
|
|
$totalSupply = (clone $query)->sum('supply_amount');
|
|
|
|
|
$totalTax = (clone $query)->sum('tax_amount');
|
|
|
|
|
$totalAmount = (clone $query)->sum('total_amount');
|
|
|
|
|
$count = (clone $query)->count();
|
|
|
|
|
|
|
|
|
|
// 상태별 합계
|
|
|
|
|
$byStatus = (clone $query)
|
|
|
|
|
->select('status', DB::raw('SUM(total_amount) as total'), DB::raw('COUNT(*) as count'))
|
|
|
|
|
->groupBy('status')
|
|
|
|
|
->get()
|
|
|
|
|
->keyBy('status')
|
|
|
|
|
->toArray();
|
|
|
|
|
|
|
|
|
|
return [
|
|
|
|
|
'total_supply_amount' => (float) $totalSupply,
|
|
|
|
|
'total_tax_amount' => (float) $totalTax,
|
|
|
|
|
'total_amount' => (float) $totalAmount,
|
|
|
|
|
'total_count' => $count,
|
|
|
|
|
'by_status' => $byStatus,
|
|
|
|
|
];
|
|
|
|
|
}
|
|
|
|
|
|
2026-01-19 19:42:05 +09:00
|
|
|
/**
|
|
|
|
|
* 매입유형 일괄 변경
|
|
|
|
|
*
|
|
|
|
|
* @param array<int> $ids
|
|
|
|
|
*/
|
|
|
|
|
public function bulkUpdatePurchaseType(array $ids, string $purchaseType): int
|
|
|
|
|
{
|
|
|
|
|
$tenantId = $this->tenantId();
|
|
|
|
|
$userId = $this->apiUserId();
|
|
|
|
|
|
|
|
|
|
return Purchase::query()
|
|
|
|
|
->where('tenant_id', $tenantId)
|
|
|
|
|
->whereIn('id', $ids)
|
|
|
|
|
->update([
|
|
|
|
|
'purchase_type' => $purchaseType,
|
|
|
|
|
'updated_by' => $userId,
|
|
|
|
|
]);
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
/**
|
|
|
|
|
* 세금계산서 수취 일괄 설정
|
|
|
|
|
*
|
|
|
|
|
* @param array<int> $ids
|
|
|
|
|
*/
|
|
|
|
|
public function bulkUpdateTaxReceived(array $ids, bool $taxInvoiceReceived): int
|
|
|
|
|
{
|
|
|
|
|
$tenantId = $this->tenantId();
|
|
|
|
|
$userId = $this->apiUserId();
|
|
|
|
|
|
|
|
|
|
return Purchase::query()
|
|
|
|
|
->where('tenant_id', $tenantId)
|
|
|
|
|
->whereIn('id', $ids)
|
|
|
|
|
->update([
|
|
|
|
|
'tax_invoice_received' => $taxInvoiceReceived,
|
|
|
|
|
'updated_by' => $userId,
|
|
|
|
|
]);
|
|
|
|
|
}
|
|
|
|
|
|
feat: 매출/매입 관리 API 구현
- 매출(Sale) 및 매입(Purchase) CRUD API 구현
- 문서번호 자동 생성 (SL/PU + YYYYMMDD + 시퀀스)
- 상태 관리 (draft → confirmed → invoiced)
- 확정(confirm) 및 요약(summary) 기능 추가
- BelongsToTenant, SoftDeletes 적용
- Swagger API 문서 작성 완료
추가된 파일:
- 마이그레이션: sales, purchases 테이블
- 모델: Sale, Purchase
- 서비스: SaleService, PurchaseService
- 컨트롤러: SaleController, PurchaseController
- FormRequest: Store/Update 4개
- Swagger: SaleApi.php, PurchaseApi.php
API 엔드포인트 (14개):
- GET/POST /v1/sales, /v1/purchases
- GET/PUT/DELETE /v1/{sales,purchases}/{id}
- POST /v1/{sales,purchases}/{id}/confirm
- GET /v1/{sales,purchases}/summary
2025-12-17 22:14:48 +09:00
|
|
|
/**
|
|
|
|
|
* 매입번호 자동 생성
|
|
|
|
|
*/
|
|
|
|
|
private function generatePurchaseNumber(int $tenantId, string $purchaseDate): string
|
|
|
|
|
{
|
|
|
|
|
$prefix = 'PU'.date('Ymd', strtotime($purchaseDate));
|
|
|
|
|
|
|
|
|
|
$lastPurchase = Purchase::query()
|
|
|
|
|
->where('tenant_id', $tenantId)
|
|
|
|
|
->where('purchase_number', 'like', $prefix.'%')
|
|
|
|
|
->orderBy('purchase_number', 'desc')
|
|
|
|
|
->first();
|
|
|
|
|
|
|
|
|
|
if ($lastPurchase) {
|
|
|
|
|
$lastSeq = (int) substr($lastPurchase->purchase_number, -4);
|
|
|
|
|
$newSeq = $lastSeq + 1;
|
|
|
|
|
} else {
|
|
|
|
|
$newSeq = 1;
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
return $prefix.str_pad($newSeq, 4, '0', STR_PAD_LEFT);
|
|
|
|
|
}
|
|
|
|
|
}
|