feat: Implement order and invoice management, enhance addon features, and remove the 'Type' module.

This commit is contained in:
pbao9
2026-02-11 17:02:07 +07:00
parent 58a9aa685b
commit 556b2c02e6
47 changed files with 1367 additions and 497 deletions
@@ -0,0 +1,68 @@
<?php
namespace App\Http\Controllers\Api\Service;
use App\Http\Controllers\Controller;
use App\Http\Requests\Api\Order\PayOrderRequest;
use App\Http\Requests\Api\Order\StoreOrderRequest;
use App\Repositories\Api\Order\OrderRepository;
use App\Services\Api\Order\OrderService;
use Illuminate\Http\JsonResponse;
use Illuminate\Http\Request;
class OrderController extends Controller
{
public function __construct(
protected OrderService $orderService,
protected OrderRepository $orderRepo
) {}
public function storeOrder(StoreOrderRequest $request): JsonResponse
{
try {
$customer = $request->user();
$result = $this->orderService->create($request->validated(), $customer);
return response()->json([
'success' => true,
'data' => $result,
'message' => 'Tạo đơn hàng thành công'
], 201);
} catch (\Exception $e) {
return response()->json([
'success' => false,
'message' => $e->getMessage()
], 400);
}
}
public function payOrder(int $id, PayOrderRequest $request): JsonResponse
{
try {
$order = $this->orderRepo->find($id);
if (!$order) {
return response()->json(['message' => 'Đơn hàng không tồn tại'], 404);
}
if ($order->customer_id !== $request->user()->id) {
return response()->json(['message' => 'Không có quyền truy cập'], 403);
}
$this->orderService->pay($order, $request->payment_method);
return response()->json([
'success' => true,
'message' => 'Thanh toán thành công'
]);
} catch (\Exception $e) {
return response()->json([
'success' => false,
'message' => $e->getMessage()
], 400);
}
}
}
@@ -0,0 +1,68 @@
<?php
namespace App\Http\Controllers\Api\Service;
class PaymentController
{
/**
* Thanh toán order bằng credit
* POST /v1/services/orders/{order_id}/pay
*/
public function payOrder(Request $request, $orderId)
{
try {
$customer = $request->user();
$order = Order::with(['invoice', 'orderItems', 'customer'])
->where('id', $orderId)
->where('customer_id', $customer->id)
->first();
if (!$order) {
return response()->json([
'error' => true,
'message' => 'Không tìm thấy đơn hàng'
], 404);
}
if ($order->status == 2) { // Already paid
return response()->json([
'error' => true,
'message' => 'Đơn hàng đã được thanh toán'
], 400);
}
// Kiểm tra credit
if ($customer->credit < $order->amount) {
return response()->json([
'error' => true,
'message' => 'Số dư không đủ để thanh toán',
'data' => [
'required' => $order->amount,
'current_credit' => $customer->credit,
'shortage' => $order->amount - $customer->credit
]
], 400);
}
// Dispatch job để xử lý thanh toán và tạo VM
ProcessOrderPaymentJob::dispatch($order);
return response()->json([
'error' => false,
'message' => 'Đơn hàng đang được xử lý. Bạn sẽ nhận được thông báo khi hoàn tất.',
'data' => [
'order_id' => $order->id,
'order_num' => $order->order_num,
'status' => 'processing'
]
]);
} catch (\Exception $e) {
Log::error('Pay order error: ' . $e->getMessage());
return response()->json([
'error' => true,
'message' => 'Có lỗi xảy ra khi thanh toán đơn hàng'
], 500);
}
}
}
@@ -5,22 +5,38 @@ namespace App\Http\Controllers\Api\Service;
use App\Http\Controllers\Controller;
use App\Http\Resources\Api\Service\ServiceListResource;
use App\Http\Resources\Api\Service\ServiceResource;
use App\Http\Services\Invoice\InvoiceService;
use App\Jobs\VirtualMachine\ProcessOrderPaymentJob;
use App\Models\Addon;
use App\Models\Cart;
use App\Models\CartAddon;
use App\Models\Discount;
use App\Models\Order;
use App\Models\OrderAddon;
use App\Models\OrderItem;
use App\Models\Product;
use App\Models\ProductPricings;
use App\Repositories\Api\Service\ServiceRepository;
use App\Services\Api\Service\ServiceService;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Log;
use Illuminate\Support\Facades\Validator;
class ServiceController extends Controller
{
protected $serviceService;
protected $serviceRepository;
public function __construct(ServiceService $serviceService)
public function __construct(
ServiceService $serviceService,
ServiceRepository $serviceRepository
)
{
$this->serviceService = $serviceService;
$this->serviceRepository = $serviceRepository;
}
/**
* Lấy danh sách dịch vụ (sản phẩm) đang hoạt động
*/
public function getService(Request $request)
{
$limit = $request->get('limit', 10);
@@ -35,7 +51,12 @@ class ServiceController extends Controller
public function getDetailService(Product $product)
{
$product->load(['osVersions.osGroup', 'category', 'pricings' => fn ($q) => $q->where('is_active', 1)]);
$product->load([
'osVersions.osGroup',
'category',
'pricings' => fn($q) => $q->where('is_active', 1),
'addons'
]);
return response()->json([
'error' => false,
+30 -6
View File
@@ -8,13 +8,15 @@ use App\Models\Addon;
use App\Repositories\Addon\AddonRepositoryInterface;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\DB;
use Yajra\DataTables\Facades\DataTables;
class AddonController extends Controller
{
//
public function __construct(
public AddonRepositoryInterface $addonRepository
) {}
) {
}
public function index(Request $request)
{
$addOns = $this->addonRepository->filter(
@@ -46,13 +48,13 @@ class AddonController extends Controller
return back()->withErrors($error->getMessage());
}
return redirect()->route('addon.index')->with('success', 'Added successfully');
return redirect()->route('addon.index')->with('success', 'Added successfully');
}
public function edit($id = 0)
{
$addon = $this->addonRepository->find($id);
if (! $addon) {
if (!$addon) {
return back()->withErrors('Invalid request');
}
@@ -63,7 +65,7 @@ class AddonController extends Controller
public function update(int $id = 0, AddOnRequest $request)
{
$addon = $this->addonRepository->find($id);
if (! $addon) {
if (!$addon) {
return back()->withErrors('Invalid request');
}
$request->validated();
@@ -77,12 +79,12 @@ class AddonController extends Controller
return back()->withErrors($error->getMessage());
}
return redirect()->route('addon.index')->with('success', 'Updated successfully');
return redirect()->route('addon.index')->with('success', 'Updated successfully');
}
public function destroy($id)
{
$addon = $this->addonRepository->find($id);
if (! $addon) {
if (!$addon) {
return back()->withErrors('Invalid request');
}
DB::beginTransaction();
@@ -96,4 +98,26 @@ class AddonController extends Controller
return redirect()->route('addon.index')->with('success', 'Deleted successfully');
}
public function datatable(Request $request)
{
$query = $this->addonRepository->filter(
$request->all(),
[],
[],
['*'],
true
);
return DataTables::eloquent($query)
->addColumn(
'action',
function ($d) {
return view('administrator.pages.addon.datatable.action', ['row' => $d])->render();
}
)
->rawColumns(['status', 'action'])
->make(true);
}
}
@@ -8,7 +8,7 @@ use App\Http\Requests\Product\ProductRequest;
use App\Http\Services\ProductService;
use App\Repositories\Group\GroupRepositoryInterface;
use App\Repositories\Admin\Product\ProductRepositoryInterface;
use App\Repositories\Type\TypeRepositoryInterface;
use Illuminate\Http\Request;
use Yajra\DataTables\Facades\DataTables;
use Exception;
@@ -16,7 +16,6 @@ use Exception;
class ProductController extends Controller
{
public function __construct(
public TypeRepositoryInterface $typeRepository,
public GroupRepositoryInterface $groupRepository,
public ProductRepositoryInterface $productRepository,
public ProductService $productService
@@ -31,7 +30,7 @@ class ProductController extends Controller
'page' => $request->get('page') ?? 1
]
);
$title = "List All Product";
return view('administrator.pages.product.index', compact('title', 'products'));
@@ -43,7 +42,7 @@ class ProductController extends Controller
$title = 'Add new product';
// Fetch Product Categories instead of generic groups
$group = \App\Models\ProductCategories::where('is_active', \App\Enums\Status::ACTIVE->value)->get();
$type = $this->typeRepository->getAll();
$type = null;
// Fetch OS versions with their group for the OS selector component
$osVersions = \App\Models\Os::with('osGroup')->where('status', 1)->get();
@@ -93,7 +92,7 @@ class ProductController extends Controller
$title = 'Edit product: ' . $product->name;
$group = \App\Models\ProductCategories::where('is_active', \App\Enums\Status::ACTIVE->value)->get();
$type = $this->typeRepository->getAll();
$type = null;
// Fetch OS versions for select
$osVersions = \App\Models\Os::with('osGroup')->where('status', 1)->get();
@@ -0,0 +1,20 @@
<?php
namespace App\Http\Requests\Api\Order;
use Illuminate\Foundation\Http\FormRequest;
class PayOrderRequest extends FormRequest
{
public function authorize(): bool
{
return true;
}
public function rules(): array
{
return [
'payment_method' => 'required|in:credit,vnpay'
];
}
}
@@ -0,0 +1,43 @@
<?php
namespace App\Http\Requests\Api\Order;
use Illuminate\Foundation\Http\FormRequest;
use Illuminate\Validation\Rule;
use App\Enums\Product\ProductBillingCycle;
class StoreOrderRequest extends FormRequest
{
public function authorize(): bool
{
return true;
}
public function rules(): array
{
return [
'product_id' => 'required|exists:products,id',
'billing_cycle'=> ['required', Rule::enum(ProductBillingCycle::class), 'exists:product_pricings,billing_cycle'],
'server_name' => 'nullable|string|max:255',
'os_id' => 'nullable|exists:os,id',
'addons' => 'array',
'addons.*.addon_id' => 'required|exists:product_addon,id',
'addons.*.qty' => 'required|integer|min:1',
];
}
public function messages(): array
{
return [
'product_id.required' => 'Vui lòng chọn sản phẩm',
'product_id.exists' => 'Sản phẩm không tồn tại',
'billing_cycle.required' => 'Vui lòng chọn chu kỳ thanh toán',
'billing_cycle.enum' => 'Chu kỳ thanh toán không hợp lệ',
'billing_cycle.exists' => 'Chu kỳ thanh toán không áp dụng cho sản phẩm này',
'os_id.exists' => 'Hệ điều hành không hợp lệ',
'addons.*.addon_id.exists' => 'Addon không tồn tại',
'addons.*.qty.min' => 'Số lượng addon phải lớn hơn 0',
];
}
}
@@ -20,13 +20,13 @@ class ClientResource extends JsonResource
return [
'customer' => [
'name' => $this->fullname,
'fullname' => $this->fullname,
'email' => $this->email,
'phone' => $this->phone,
'address' => $this->address,
'city' => $this->city,
'ward' => $this->ward->name,
'province' => $this->province->name,
'ward' => $this->ward->name ?? '',
'province' => $this->province->name ?? '',
'gender' => $this->gender_label,
'date' => $this->created_at ? $this->created_at->format('Y-m-d H:i:s') : null,
'company' => $this->company ?? '',
@@ -39,17 +39,11 @@ class ServiceListResource extends JsonResource
return [$pricing->billing_cycle => $pricing->price_sale];
}),
'group' => $this->category->name,
'os' => $this->osVersions->groupBy('os_group_id')->map(function ($versions) {
$group = $versions->first()->osGroup;
'os' => $this->osVersions->map(function ($os) {
return [
'name' => $group?->name,
'thumbnail' => $group?->thumbnail,
'versions' => $versions->map(fn($os) => [
'version' => $os->version,
'name' => $os->name,
])->values(),
'group' => $os->osGroup->name ?? null,
];
})->values(),
})->unique('group')->values(),
];
}
}
@@ -61,7 +61,38 @@ class ProcessOrderPaymentJob implements ShouldQueue
return;
}
// Tạo VM cho các sản phẩm VPS
/**
* OPTIMIZED PAYMENT FLOW
*
* Thay đổi: TRỪ TIỀN TRƯỚC → TẠO VM SAU
*
* Lý do:
* 1. User đã có credit trong hệ thống (đã nạp qua VNPay)
* 2. Nếu tạo VM fail → refund credit dễ dàng
* 3. Tránh tình huống: VM tạo ok nhưng chưa trừ tiền
* 4. Đảm bảo tính nhất quán: Đã trừ tiền = đã có order valid
*/
DB::beginTransaction();
try {
// STEP 1: Trừ tiền người dùng
$user->decrement('credit', (int) $this->order->amount);
// STEP 2: Cập nhật trạng thái hóa đơn và đơn hàng
$invoiceService->markAsPaid($invoice);
$this->order->update(['status' => OrderStatus::ACTIVE->value]);
DB::commit();
Log::info("✓ Đã trừ credit và cập nhật order #{$this->order->order_num}");
} catch (\Throwable $e) {
DB::rollBack();
Log::error("Lỗi khi trừ credit cho order #{$this->order->order_num}: " . $e->getMessage());
throw $e;
}
// STEP 3: Tạo VM cho các sản phẩm VPS (sau khi đã trừ tiền)
$vmCreationResults = [];
$allVMsCreated = true;
$hasVMCreationAttempt = false;
@@ -97,119 +128,111 @@ class ProcessOrderPaymentJob implements ShouldQueue
}
}
// Kiểm tra xem có thực sự có VM nào được tạo không
// STEP 4: Xử lý kết quả tạo VM
if (!$hasVMCreationAttempt) {
$errorMessage = "Không có sản phẩm VPS nào được xử lý trong đơn hàng #{$this->order->order_num}";
Log::error($errorMessage);
$telegram->SendErrorMessage($errorMessage, 'ProcessOrderPaymentJob - No VM Creation Attempt');
// Không có VPS nào trong order → OK, chỉ là Hosting/Domain
$telegram->SendOrderPaidNotification($invoice);
$this->sendSuccessNotification([]);
return;
}
// Kiểm tra kết quả tạo VM
if (empty($vmCreationResults)) {
$errorMessage = "Không có kết quả tạo VM nào được trả về cho đơn hàng #{$this->order->order_num}";
Log::error($errorMessage);
$telegram->SendErrorMessage($errorMessage, 'ProcessOrderPaymentJob - Empty VM Results');
$this->handleVMCreationFailure($user, $invoice, $vmCreationResults, $telegram);
return;
}
// Kiểm tra xem có ít nhất một VM thành công không
$successfulVMs = array_filter($vmCreationResults, fn($vm) => $vm['success']);
$failedVMs = array_filter($vmCreationResults, fn($vm) => !$vm['success']);
// Nếu tất cả VM được tạo thành công, tiến hành thanh toán
// Nếu tất cả VM được tạo thành công
if ($allVMsCreated && count($successfulVMs) > 0) {
DB::beginTransaction();
try {
// Trừ tiền người dùng
$user->decrement('credit', (int) $this->order->amount);
// Gửi thông báo thành công
$telegram->SendOrderPaidNotification($invoice);
$this->sendSuccessNotification($vmCreationResults);
// Cập nhật trạng thái hóa đơn và đơn hàng
$invoiceService->markAsPaid($invoice);
$this->order->update(['status' => OrderStatus::ACTIVE->value]);
// Gửi thông báo Telegram
$telegram->SendOrderPaidNotification($invoice);
DB::commit();
// Gửi thông báo thành công cho khách hàng
$this->sendSuccessNotification($vmCreationResults);
} catch (\Throwable $e) {
DB::rollBack();
throw $e;
}
Log::info("✓ Hoàn tất order #{$this->order->order_num} - Tất cả VM đã được tạo");
} else {
// Có lỗi khi tạo VM hoặc không có VM nào thành công
$errorDetails = [
'order_id' => $this->order->id,
'order_num' => $this->order->order_num,
'vm_results' => $vmCreationResults,
'total_vms' => count($vmCreationResults),
'successful_vms' => count($successfulVMs),
'failed_vms' => count($failedVMs),
'all_vms_created' => $allVMsCreated
];
// Kiểm tra trường hợp đặc biệt: có VPS nhưng không có VM nào thành công
if (count($vmCreationResults) > 0 && count($successfulVMs) === 0) {
Log::error("Có sản phẩm VPS nhưng không có VM nào được tạo thành công", $errorDetails);
$telegram->SendErrorMessage(array_merge($errorDetails, [
'error' => 'Tất cả VM đều thất bại - không có VM nào thành công'
]), 'ProcessOrderPaymentJob - All VMs Failed');
}
// Thử lại nếu chưa vượt quá số lần thử
if ($this->retryCount < self::MAX_RETRIES) {
// Kiểm tra nếu lỗi là timeout, tăng delay time
$isTimeoutError = $this->isTimeoutError($failedVMs);
$delayMinutes = $isTimeoutError ? 10 : 10; // Timeout thì chờ 10 phút, lỗi khác chờ 10 phút
Log::warning("Có lỗi khi tạo VM, thử lại lần " . ($this->retryCount + 1), array_merge($errorDetails, [
'is_timeout_error' => $isTimeoutError,
'delay_minutes' => $delayMinutes
]));
// Thử lại với delay tùy theo loại lỗi
self::dispatch($this->order, $this->retryCount + 1)
->delay(now()->addMinutes($delayMinutes));
} else {
// Đã thử hết số lần, gửi thông báo lỗi
Log::error("Đã thử tạo VM {$this->retryCount} lần nhưng vẫn thất bại", $errorDetails);
$telegram->SendErrorMessage(array_merge($errorDetails, [
'error' => 'Không thể tạo VM sau nhiều lần thử',
'retry_count' => $this->retryCount
]), 'ProcessOrderPaymentJob - VM Creation Failed After Retries');
// Gửi thông báo lỗi cho khách hàng
$this->sendFailureNotification($vmCreationResults);
}
// Có lỗi khi tạo VM
$this->handleVMCreationFailure($user, $invoice, $vmCreationResults, $telegram);
}
} catch (\Throwable $e) {
$isTimeoutException = strpos(strtolower($e->getMessage()), 'timeout') !== false ||
strpos(strtolower($e->getMessage()), 'curl error 28') !== false;
Log::error("Lỗi trong ProcessOrderPaymentJob: " . $e->getMessage(), [
Log::error("Lỗi nghiêm trọng trong ProcessOrderPaymentJob: " . $e->getMessage(), [
'order_id' => $this->order->id,
'order_num' => $this->order->order_num,
'is_timeout' => $isTimeoutException,
'retry_count' => $this->retryCount,
'trace' => $e->getTraceAsString()
]);
$telegram->SendErrorMessage(
"Lỗi nghiêm trọng khi xử lý order #{$this->order->order_num}: " . $e->getMessage(),
'ProcessOrderPaymentJob - Critical Error'
);
}
}
$telegram->SendErrorMessage([
'error' => $e->getMessage(),
'order_id' => $this->order->id,
'order_num' => $this->order->order_num,
'file' => $e->getFile(),
'line' => $e->getLine(),
'is_timeout' => $isTimeoutException,
/**
* Xử lý khi tạo VM thất bại
*/
private function handleVMCreationFailure($user, $invoice, $vmCreationResults, Telegram $telegram): void
{
$successfulVMs = array_filter($vmCreationResults, fn($vm) => $vm['success']);
$failedVMs = array_filter($vmCreationResults, fn($vm) => !$vm['success']);
$errorDetails = [
'order_id' => $this->order->id,
'order_num' => $this->order->order_num,
'vm_results' => $vmCreationResults,
'total_vms' => count($vmCreationResults),
'successful_vms' => count($successfulVMs),
'failed_vms' => count($failedVMs),
];
// Kiểm tra trường hợp đặc biệt: có VPS nhưng không có VM nào thành công
if (count($vmCreationResults) > 0 && count($successfulVMs) === 0) {
Log::error("Có sản phẩm VPS nhưng không có VM nào được tạo thành công", $errorDetails);
$telegram->SendErrorMessage(array_merge($errorDetails, [
'error' => 'Tất cả VM đều thất bại - không có VM nào thành công'
]), 'ProcessOrderPaymentJob - All VMs Failed');
// REFUND CREDIT vì không tạo được VM nào
try {
DB::transaction(function () use ($user, $invoice) {
$user->increment('credit', (int) $this->order->amount);
$invoice->update(['status' => InvoiceStatus::UNPAID->value]);
$this->order->update(['status' => OrderStatus::PENDING->value]);
Log::info("✓ Đã hoàn tiền cho order #{$this->order->order_num} do không tạo được VM");
});
} catch (\Throwable $e) {
Log::error("Lỗi khi hoàn tiền: " . $e->getMessage());
}
}
// Thử lại nếu chưa vượt quá số lần thử và có VM fail
if ($this->retryCount < self::MAX_RETRIES && count($failedVMs) > 0) {
// Kiểm tra nếu lỗi là timeout, tăng delay time
$isTimeoutError = $this->isTimeoutError($failedVMs);
$delayMinutes = $isTimeoutError ? 10 : 5; // Timeout chờ 10 phút, lỗi khác 5 phút
Log::warning("Có lỗi khi tạo VM, thử lại lần " . ($this->retryCount + 1), array_merge($errorDetails, [
'is_timeout_error' => $isTimeoutError,
'delay_minutes' => $delayMinutes
]));
// Thử lại với delay tùy theo loại lỗi
self::dispatch($this->order, $this->retryCount + 1)
->delay(now()->addMinutes($delayMinutes));
} else if (count($failedVMs) > 0) {
// Đã thử hết số lần, gửi thông báo lỗi
Log::error("Đã thử tạo VM {$this->retryCount} lần nhưng vẫn thất bại", $errorDetails);
$telegram->SendErrorMessage(array_merge($errorDetails, [
'error' => 'Không thể tạo VM sau nhiều lần thử',
'retry_count' => $this->retryCount
], 'ProcessOrderPaymentJob - Exception');
]), 'ProcessOrderPaymentJob - VM Creation Failed After Retries');
// Gửi thông báo lỗi cho khách hàng
$this->sendFailureNotification($vmCreationResults);
}
}
+3 -6
View File
@@ -12,16 +12,13 @@ class Addon extends Model
protected $table = 'product_addon';
protected $fillable = [
'code',
'name',
'price',
'min',
'max',
'prefix',
'step',
'type_id'
'prefix',
'status'
];
public function type()
{
return $this->belongsTo(\App\Models\Type::class);
}
}
+18
View File
@@ -64,4 +64,22 @@ class Cart extends Model
{
return $this->belongsTo(ProductPricings::class, 'product_pricing_id');
}
/**
* Relationship: Cart has many addons
*/
public function addons()
{
return $this->hasMany(CartAddon::class, 'cart_id');
}
/**
* Get total price including addons
*/
public function getTotalPriceAttribute()
{
$basePrice = $this->price * $this->quantity;
$addonsPrice = $this->addons->sum('price');
return $basePrice + $addonsPrice;
}
}
+36
View File
@@ -0,0 +1,36 @@
<?php
namespace App\Models;
use Illuminate\Database\Eloquent\Factories\HasFactory;
use Illuminate\Database\Eloquent\Model;
class CartAddon extends Model
{
use HasFactory;
protected $table = 'cart_addons';
protected $fillable = [
'cart_id',
'addon_id',
'qty',
'price',
];
/**
* Relationship: CartAddon belongs to Cart
*/
public function cart()
{
return $this->belongsTo(Cart::class, 'cart_id');
}
/**
* Relationship: CartAddon belongs to Addon
*/
public function addon()
{
return $this->belongsTo(Addon::class, 'addon_id');
}
}
+11
View File
@@ -103,6 +103,17 @@ class Product extends Model
return $this->belongsToMany(ProductCategories::class, 'product_product_category', 'product_id', 'product_category_id');
}
/**
* Relationship: Product has many addons (through product type)
* Addons are linked via type_id in product_addon table
*/
public function addons()
{
// Assuming product_addon has type_id field that links to product type
return $this->hasMany(Addon::class, 'type_id', 'product_type')
->orderBy('sort_order');
}
/**
* Get monthly pricing (or first available pricing)
*/
-44
View File
@@ -1,44 +0,0 @@
<?php
namespace App\Models;
use Illuminate\Database\Eloquent\Factories\HasFactory;
use Illuminate\Database\Eloquent\Model;
class Type extends Model
{
use HasFactory;
protected $table = 'type';
protected $fillable = [
'name',
'status',
'icon'
];
public function invoiceItem()
{
return $this->belongsTo(\App\Models\InvoiceItem::class);
}
public function group()
{
return $this->hasMany(\App\Models\Group::class);
}
public function hosting()
{
return $this->hasMany(\App\Models\Hosting::class);
}
public function vps()
{
return $this->hasMany(\App\Models\VPS::class);
}
public function domain()
{
return $this->hasMany(\App\Models\Domain::class);
}
}
-5
View File
@@ -250,11 +250,6 @@ class RepositoryProvider extends ServiceProvider
TransactionRepositoryInterface::class,
TransactionCachedRepository::class
);
//Type
$this->app->bind(
TypeRepositoryInterface::class,
TypeCachedRepository::class
);
//Module Datacenter
$this->app->bind(
DatacenterRepositoryInterface::class,
@@ -16,18 +16,31 @@ class AddonCachedRepository extends BaseCachedRepository implements AddonReposit
{
return $this->addonRepository->getModel();
}
public function filter(array $data = [], array $relationships = [], array $withCount = [], array $select = ['*'])
{
public function filter(
array $data = [],
array $relationships = [],
array $withCount = [],
array $select = ['*'],
bool $returnQuery = false
) {
if (
$returnQuery ||
!empty($data['paginate'])
) {
return $this->addonRepository
->filter($data, $relationships, $withCount, $select, $returnQuery);
}
$cacheKey = $this->getCacheKey(md5(json_encode([
'filterItem' => [
'data' => $data,
'relationships' => $relationships,
'select' => $select,
'withCount' => $withCount
]
'filter' => compact('data', 'relationships', 'withCount', 'select')
])));
return Cache::remember($cacheKey, $this->cacheTime, function () use ($data, $relationships, $select, $withCount) {
return $this->addonRepository->filter($data, $relationships, $withCount, $select);
});
return Cache::remember(
$cacheKey,
$this->cacheTime,
fn() =>
$this->addonRepository
->filter($data, $relationships, $withCount, $select, $returnQuery)
);
}
}
+28 -9
View File
@@ -11,16 +11,35 @@ class AddonRepository extends BaseRepository implements AddonRepositoryInterface
{
return Addon::class;
}
public function filter(array $data = [], array $relationships = [], array $withCount = [], array $select = ['*'])
{
$model = $this->model->with($relationships)->select($select);
if (count($withCount) > 0) {
$model = $model->withCount($withCount);
public function filter(
array $data = [],
array $relationships = [],
array $withCount = [],
array $select = ['*'],
bool $returnQuery = false
) {
$query = $this->model
->select($select)
->with($relationships);
if (!empty($data['vcenter_id'])) {
$query->where('vcenter_id', $data['vcenter_id']);
}
if(isset($data['page'])) {
return $model->paginate(15);
if (!empty($withCount)) {
$query->withCount($withCount);
}
return $model->get();
if ($returnQuery) {
return $query;
}
if (!empty($data['paginate'])) {
return $query->paginate(
$data['per_page'] ?? 15
);
}
return $query->get();
}
}
@@ -4,6 +4,13 @@ namespace App\Repositories\Addon;
use App\Repositories\BaseRepositoryInterface;
interface AddonRepositoryInterface extends BaseRepositoryInterface{
public function filter(array $data = [],array $relationships = [],array $withCount = [],array $select = ['*']);
interface AddonRepositoryInterface extends BaseRepositoryInterface
{
public function filter(
array $data = [],
array $relationships = [],
array $withCount = [],
array $select = ['*'],
bool $returnQuery = false
);
}
@@ -0,0 +1,54 @@
<?php
namespace App\Repositories\Api\Invoice;
use App\Models\Invoice;
use App\Repositories\Api\BaseApiRepository;
class InvoiceRepository extends BaseApiRepository implements InvoiceRepositoryInterface
{
public function getModel()
{
return Invoice::class;
}
/**
* Lấy danh sách sản phẩm đang hoạt động
*/
public function getInvoice(int $limit = 10, $customer = null)
{
return $this->model->where('customer_id', $customer)->paginate($limit);
}
public function createFromOrder($order)
{
$invoice = $this->model->create([
'customer_id' => $order->customer_id,
'date' => now(),
'due_date' => now()->addDays(3),
'amount' => $order->amount,
'status' => 1, // Unpaid
]);
$order->update(['invoice_id' => $invoice->id]);
$orderItems = $order->orderItems;
if ($orderItems->isEmpty()) {
$orderItems = $order->orderItems()->get();
}
foreach ($orderItems as $item) {
\App\Models\InvoiceItem::create([
'invoice_id' => $invoice->id,
'customer_id' => $invoice->customer_id,
'product_id' => $item->product_id,
'description' => optional($item->product)->name ?? 'Order Item',
'amount' => $item->price ?? $order->amount,
'type_id' => 1,
'billing' => $item->billing_cycle ?? 'monthly',
]);
}
return $invoice;
}
}
@@ -0,0 +1,12 @@
<?php
namespace App\Repositories\Api\Invoice;
use App\Repositories\BaseRepositoryInterface;
interface InvoiceRepositoryInterface extends BaseRepositoryInterface
{
public function getInvoice(int $limit = 10, $customer = null);
public function createFromOrder($order);
}
@@ -0,0 +1,31 @@
<?php
namespace App\Repositories\Api\Order;
use App\Models\Order;
use App\Repositories\Api\BaseApiRepository;
class OrderRepository extends BaseApiRepository implements OrderRepositoryInterface
{
public function getModel()
{
return Order::class;
}
public function createItem($orderId, array $data)
{
return \App\Models\OrderItem::create(array_merge(
['order_id' => $orderId],
$data
));
}
public function processPayment($order, $method)
{
return $order->update([
'status' => 'paid',
'payment_method' => $method,
'paid_at' => now()
]);
}
}
@@ -0,0 +1,12 @@
<?php
namespace App\Repositories\Api\Order;
use App\Repositories\BaseRepositoryInterface;
interface OrderRepositoryInterface extends BaseRepositoryInterface
{
public function createItem($orderId, array $data);
public function processPayment($order, $method);
}
@@ -32,4 +32,15 @@ class ServiceRepository extends BaseApiRepository implements ServiceRepositoryIn
->where('is_active', 1)
->first();
}
public function getPricing(int $productId, string $billingCycle)
{
$pricing = $this->model->find($productId)
->pricings()
->where('billing_cycle', $billingCycle)
->where('is_active', 1)
->first();
return $pricing ? $pricing->price : null;
}
}
@@ -12,4 +12,6 @@ interface ServiceRepositoryInterface extends BaseRepositoryInterface
public function getActiveServices(int $limit = 10);
public function findActiveBySlug(string $slug);
public function getPricing(int $productId, string $billingCycle);
}
@@ -1,18 +0,0 @@
<?php
namespace App\Repositories\Type;
use App\Repositories\BaseCachedRepository;
class TypeCachedRepository extends BaseCachedRepository implements TypeRepositoryInterface
{
public function __construct(
public TypeRepository $typeRepository
) {
parent::__construct();
}
public function getModel()
{
return $this->typeRepository->getModel();
}
}
-14
View File
@@ -1,14 +0,0 @@
<?php
namespace App\Repositories\Type;
use App\Models\Type;
use App\Repositories\BaseRepository;
class TypeRepository extends BaseRepository implements TypeRepositoryInterface
{
public function getModel()
{
return Type::class;
}
}
@@ -1,6 +0,0 @@
<?php
namespace App\Repositories\Type;
use App\Repositories\BaseRepositoryInterface;
interface TypeRepositoryInterface extends BaseRepositoryInterface {}
+67
View File
@@ -0,0 +1,67 @@
<?php
namespace App\Services\Api\Order;
use App\Repositories\Api\Service\ServiceRepository;
use App\Repositories\Api\Invoice\InvoiceRepository;
use App\Repositories\Api\Order\OrderRepository;
use Illuminate\Support\Facades\DB;
use Exception;
class OrderService
{
public function __construct(
protected OrderRepository $orderRepo,
protected ServiceRepository $productRepo,
protected InvoiceRepository $invoiceRepo
) {}
public function create(array $data, $customer)
{
return DB::transaction(function () use ($data, $customer) {
$product = $this->productRepo->find($data['product_id']);
if (!$product) {
throw new Exception('Sản phẩm không tồn tại');
}
$price = $this->productRepo
->getPricing($product->id, $data['billing_cycle']);
if (is_null($price)) {
throw new Exception('Không tìm thấy giá cho sản phẩm này');
}
$order = $this->orderRepo->create([
'customer_id' => $customer->id,
'amount' => $price,
'status' => 'pending'
]);
$this->orderRepo->createItem($order->id, [
'product_id' => $product->id,
'billing_cycle' => $data['billing_cycle'],
'server_name' => $data['server_name'] ?? null,
'os_id' => $data['os_id'] ?? null,
'price' => $price
]);
$invoice = $this->invoiceRepo->createFromOrder($order);
return [
'order' => $order,
'invoice' => $invoice
];
});
}
public function pay($order, string $method)
{
if ($order->status === 'paid') {
throw new Exception('Đơn hàng đã thanh toán');
}
return $this->orderRepo->processPayment($order, $method);
}
}