Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
4 changes: 3 additions & 1 deletion .github/workflows/deploy.yaml
Original file line number Diff line number Diff line change
Expand Up @@ -54,5 +54,7 @@ jobs:

DB_PASSWORD_PROD: ${{ secrets.PROD_DB_PASSWORD }}
REDIS_PASSWORD_PROD: ${{ secrets.PROD_REDIS_PASSWORD }}
JWT_SECRET_PROD: ${{ secrets.PROD_JWT_SECRET }}
DB_PASSWORD_DEV: ${{ secrets.DEV_DB_PASSWORD }}
REDIS_PASSWORD_DEV: ${{ secrets.DEV_REDIS_PASSWORD }}
REDIS_PASSWORD_DEV: ${{ secrets.DEV_REDIS_PASSWORD }}
JWT_SECRET_DEV: ${{ secrets.DEV_JWT_SECRET }}
110 changes: 110 additions & 0 deletions app/Http/Controllers/CartController.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,110 @@
<?php

namespace App\Http\Controllers;

use App\Models\Cart;
use App\Models\CartItem;
use App\Services\ProductClient;
use Illuminate\Http\Request;

class CartController extends Controller
{
private function userId(Request $request): int
{
return (int) $request->attributes->get('user_id');
}

private function activeCart(int $userId): Cart
{
return Cart::query()->firstOrCreate(
['user_id' => $userId, 'status' => 'active'],
['user_id' => $userId, 'status' => 'active']
);
}

public function show(Request $request)
{
$cart = $this->activeCart($this->userId($request));
$cart->load('items');

$total = $cart->items->sum(fn ($i) => $i->unit_price_snapshot * $i->qty);

return response()->json([
'data' => [
'id' => $cart->id,
'items' => $cart->items,
'total_price' => (int) $total,
],
]);
}

public function addItem(Request $request, ProductClient $products)
{
$data = $request->validate([
'product_id' => ['required', 'integer', 'min:1'],
'qty' => ['required', 'integer', 'min:1', 'max:999'],
]);

$userId = $this->userId($request);
$cart = $this->activeCart($userId);

$p = $products->getProduct((int) $data['product_id']);

$item = CartItem::query()->where('cart_id', $cart->id)
->where('product_id', (int) $data['product_id'])
->first();

if ($item) {
$item->qty = $item->qty + (int) $data['qty'];
// osveži snapshot (optional)
$item->name_snapshot = $p['name'];
$item->unit_price_snapshot = $p['price'];
$item->save();
} else {
$item = CartItem::query()->create([
'cart_id' => $cart->id,
'product_id' => (int) $p['id'],
'name_snapshot' => $p['name'],
'unit_price_snapshot' => (int) $p['price'],
'qty' => (int) $data['qty'],
]);
}

return response()->json(['data' => $item], 201);
}

public function updateItem(Request $request, int $itemId)
{
$data = $request->validate([
'qty' => ['required', 'integer', 'min:1', 'max:999'],
]);

$userId = $this->userId($request);
$cart = $this->activeCart($userId);

$item = CartItem::query()
->where('cart_id', $cart->id)
->where('id', $itemId)
->firstOrFail();

$item->qty = (int) $data['qty'];
$item->save();

return response()->json(['data' => $item]);
}

public function removeItem(Request $request, int $itemId)
{
$userId = $this->userId($request);
$cart = $this->activeCart($userId);

$item = CartItem::query()
->where('cart_id', $cart->id)
->where('id', $itemId)
->firstOrFail();

$item->delete();

return response()->json(['status' => 'ok']);
}
}
91 changes: 91 additions & 0 deletions app/Http/Controllers/OrderController.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,91 @@
<?php

namespace App\Http\Controllers;

use App\Models\Cart;
use App\Models\Order;
use App\Models\OrderItem;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\DB;

class OrderController extends Controller
{
private function userId(Request $request): int
{
return (int) $request->attributes->get('user_id');
}

private function activeCart(int $userId): Cart
{
return Cart::query()->firstOrCreate(
['user_id' => $userId, 'status' => 'active'],
['user_id' => $userId, 'status' => 'active']
);
}

public function createFromCart(Request $request)
{
$userId = $this->userId($request);
$cart = $this->activeCart($userId);
$cart->load('items');

if ($cart->items->isEmpty()) {
return response()->json(['message' => 'Cart is empty'], 422);
}

$order = DB::transaction(function () use ($cart, $userId) {
$total = $cart->items->sum(fn ($i) => $i->unit_price_snapshot * $i->qty);

$order = Order::query()->create([
'user_id' => $userId,
'status' => 'pending_payment',
'total_price' => (int) $total,
]);

foreach ($cart->items as $item) {
OrderItem::query()->create([
'order_id' => $order->id,
'product_id' => $item->product_id,
'name_snapshot' => $item->name_snapshot,
'unit_price_snapshot' => $item->unit_price_snapshot,
'qty' => $item->qty,
]);
}

// počistimo košarico
$cart->items()->delete();

return $order;
});

$order->load('items');

return response()->json(['data' => $order], 201);
}

public function index(Request $request)
{
$userId = $this->userId($request);

$orders = Order::query()
->where('user_id', $userId)
->orderByDesc('id')
->get();

return response()->json(['data' => $orders]);
}

public function show(Request $request, int $orderId)
{
$userId = $this->userId($request);

$order = Order::query()
->where('user_id', $userId)
->where('id', $orderId)
->firstOrFail();

$order->load('items');

return response()->json(['data' => $order]);
}
}
37 changes: 37 additions & 0 deletions app/Http/Middleware/JwtAuth.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,37 @@
<?php

namespace App\Http\Middleware;

use App\Services\JwtService;
use Closure;
use Illuminate\Http\Request;

class JwtAuth
{
public function handle(Request $request, Closure $next)
{
$authHeader = (string) $request->header('Authorization', '');

if (!str_starts_with($authHeader, 'Bearer ')) {
return response()->json(['message' => 'Missing Bearer token'], 401);
}

$token = trim(substr($authHeader, 7));

try {
$claims = app(JwtService::class)->decode($token);
$userId = $claims['sub'] ?? null;

if (!$userId) {
return response()->json(['message' => 'Invalid token'], 401);
}

// nastavimo user_id na request (ker v tem servisu nimamo users tabele)
$request->attributes->set('user_id', (int) $userId);

return $next($request);
} catch (\Throwable $e) {
return response()->json(['message' => 'Invalid or expired token'], 401);
}
}
}
16 changes: 16 additions & 0 deletions app/Models/Cart.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,16 @@
<?php

namespace App\Models;

use Illuminate\Database\Eloquent\Model;
use Illuminate\Database\Eloquent\Relations\HasMany;

class Cart extends Model
{
protected $fillable = ['user_id', 'status'];

public function items(): HasMany
{
return $this->hasMany(CartItem::class);
}
}
22 changes: 22 additions & 0 deletions app/Models/CartItem.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,22 @@
<?php

namespace App\Models;

use Illuminate\Database\Eloquent\Model;
use Illuminate\Database\Eloquent\Relations\BelongsTo;

class CartItem extends Model
{
protected $fillable = [
'cart_id',
'product_id',
'name_snapshot',
'unit_price_snapshot',
'qty',
];

public function cart(): BelongsTo
{
return $this->belongsTo(Cart::class);
}
}
16 changes: 16 additions & 0 deletions app/Models/Order.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,16 @@
<?php

namespace App\Models;

use Illuminate\Database\Eloquent\Model;
use Illuminate\Database\Eloquent\Relations\HasMany;

class Order extends Model
{
protected $fillable = ['user_id', 'status', 'total_price'];

public function items(): HasMany
{
return $this->hasMany(OrderItem::class);
}
}
22 changes: 22 additions & 0 deletions app/Models/OrderItem.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,22 @@
<?php

namespace App\Models;

use Illuminate\Database\Eloquent\Model;
use Illuminate\Database\Eloquent\Relations\BelongsTo;

class OrderItem extends Model
{
protected $fillable = [
'order_id',
'product_id',
'name_snapshot',
'unit_price_snapshot',
'qty',
];

public function order(): BelongsTo
{
return $this->belongsTo(Order::class);
}
}
20 changes: 20 additions & 0 deletions app/Services/JwtService.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,20 @@
<?php

namespace App\Services;

use Firebase\JWT\JWT;
use Firebase\JWT\Key;

class JwtService
{
public function decode(string $token): array
{
$secret = (string) config('jwt.secret');
if ($secret === '') {
throw new \RuntimeException('JWT secret is not configured (JWT_SECRET).');
}

$decoded = JWT::decode($token, new Key($secret, 'HS256'));
return (array) $decoded;
}
}
34 changes: 34 additions & 0 deletions app/Services/ProductClient.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,34 @@
<?php

namespace App\Services;

use Illuminate\Support\Facades\Http;

class ProductClient
{
public function getProduct(int $productId): array
{
$base = rtrim((string) config('services.products.base_url'), '/');
$url = $base . '/items/' . $productId;

$resp = Http::acceptJson()->get($url);

if (!$resp->successful()) {
throw new \RuntimeException("Product not found or product-service error (status {$resp->status()}).");
}

$json = $resp->json();

// pričakujemo { data: { id, name, price, ... } }
$p = $json['data'] ?? null;
if (!$p || !isset($p['name'], $p['price'], $p['id'])) {
throw new \RuntimeException('Unexpected product-service response.');
}

return [
'id' => (int) $p['id'],
'name' => (string) $p['name'],
'price' => (int) $p['price'],
];
}
}
Loading