Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
Show all changes
32 commits
Select commit Hold shift + click to select a range
4c58c37
docs: adiciona plano de melhorias e briefs das fases 0-2
svitorz Nov 25, 2026
600ca07
chore(test): cria banco de testes no Postgres e desativa Vite nos testes
svitorz Nov 25, 2026
0d23aaf
chore(env): ajusta .env.example para Sail com Postgres
svitorz Nov 25, 2026
c479315
test: torna factories independentes, cria admin no seed e adiciona he…
svitorz Nov 25, 2026
e3952c7
chore(lint): configura Pint
svitorz Nov 25, 2026
4a8892c
style: aplica Pint em todo o código PHP
svitorz Nov 25, 2026
af97649
chore(lint): configura Prettier
svitorz Nov 25, 2026
a917e49
style: aplica Prettier em resources/js
svitorz Nov 25, 2026
b36ed01
ci: adiciona pipeline com Pint, Pest, Prettier e build
svitorz Nov 25, 2026
66f8255
fix(auth): retorna 403 para não-admins e implementa policies de catálogo
svitorz Nov 25, 2026
9a2b0bf
fix(orders): restringe listagem e cancelamento ao dono do pedido
svitorz Nov 25, 2026
d61dece
fix(favorites): usa usuário autenticado e corrige remoção de favoritos
svitorz Nov 25, 2026
f460051
fix(ratings): grava avaliação sempre para o usuário autenticado
svitorz Nov 25, 2026
bc5b4f1
fix(payments): deixa de armazenar número do cartão e CVV
svitorz Nov 25, 2026
357e407
fix(cart): valida estoque, tolera produto removido e usa DELETE na re…
svitorz Nov 25, 2026
6d33696
feat(orders): grava itens, baixa estoque e valida carrinho em transaç…
svitorz Nov 25, 2026
613ecad
fix(orders): devolve estoque ao cancelar pedido
svitorz Nov 25, 2026
1b70e26
fix(products): corrige redirect após edição e remove código sem efeito
svitorz Nov 25, 2026
08c74df
refactor(products): guarda preço como decimal(10,2)
svitorz Nov 25, 2026
e8b1978
fix(favorites): impede favorito e avaliação duplicados no banco
svitorz Nov 25, 2026
ca4bc98
fix(db): adiciona chaves estrangeiras e regra de exclusão
svitorz Nov 25, 2026
071684f
refactor(orders): usa enum OrderStatus para o status do pedido
svitorz Nov 25, 2026
25a85d5
fix(ui): mostra erro ao excluir categoria ou produto com dependências
svitorz Nov 25, 2026
6ae3602
docs(melhorias): briefs das fases 3 e 4 e índice atualizado
svitorz Nov 26, 2026
497559e
refactor(products): remove sessão e autenticação do model Product
svitorz Nov 26, 2026
605f301
refactor(cart): troca a trait do carrinho por App\Services\Cart
svitorz Nov 26, 2026
be7eba3
refactor(app): dashboard em controller, serviço de recomendados e nom…
svitorz Nov 26, 2026
6168fad
docs(melhorias): brief da fase 5 (desempenho)
svitorz Nov 26, 2026
6ac7e61
fix(products): libera busca para cliente comum
svitorz Nov 26, 2026
9416cc8
perf(db): cria índices nas chaves estrangeiras
svitorz Nov 26, 2026
57d2361
perf(cart): memoiza os itens do carrinho dentro da requisição
svitorz Nov 26, 2026
d11398c
perf(config): sessão e cache no Redis no exemplo de ambiente
svitorz Nov 26, 2026
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
18 changes: 9 additions & 9 deletions .env.example
Original file line number Diff line number Diff line change
@@ -1,7 +1,7 @@
APP_NAME=eCommerce
APP_ENV=local
APP_KEY=
APP_DEBUG=false
APP_DEBUG=true
APP_TIMEZONE=UTC
APP_URL=http://localhost
APP_SERVICE="ecommerce"
Expand All @@ -23,13 +23,13 @@ LOG_DEPRECATIONS_CHANNEL=null
LOG_LEVEL=debug

DB_CONNECTION=pgsql
DB_HOST=127.0.0.1
DB_PORT=3306
DB_DATABASE=laravel
DB_USERNAME=root
DB_PASSWORD=
DB_HOST=db
DB_PORT=5432
DB_DATABASE=ecommerce
DB_USERNAME=sail
DB_PASSWORD=password

SESSION_DRIVER=database
SESSION_DRIVER=redis
SESSION_LIFETIME=120
SESSION_ENCRYPT=false
SESSION_PATH=/
Expand All @@ -39,13 +39,13 @@ BROADCAST_CONNECTION=log
FILESYSTEM_DISK=local
QUEUE_CONNECTION=database

CACHE_STORE=database
CACHE_STORE=redis
CACHE_PREFIX=

MEMCACHED_HOST=127.0.0.1

REDIS_CLIENT=phpredis
REDIS_HOST=127.0.0.1
REDIS_HOST=redis
REDIS_PASSWORD=null
REDIS_PORT=6379

Expand Down
59 changes: 59 additions & 0 deletions .github/workflows/ci.yml
Original file line number Diff line number Diff line change
@@ -0,0 +1,59 @@
name: CI

on:
push:
branches: [main, master]
pull_request:

jobs:
backend:
runs-on: ubuntu-latest
services:
postgres:
image: postgres:17
env:
POSTGRES_DB: testing
POSTGRES_USER: sail
POSTGRES_PASSWORD: password
ports: ['5432:5432']
options: >-
--health-cmd pg_isready
--health-interval 5s
--health-timeout 5s
--health-retries 10
env:
DB_CONNECTION: pgsql
DB_HOST: 127.0.0.1
DB_PORT: 5432
DB_DATABASE: testing
DB_USERNAME: sail
DB_PASSWORD: password
steps:
- uses: actions/checkout@v4
- uses: shivammathur/setup-php@v2
with:
php-version: '8.4'
extensions: pdo_pgsql
coverage: none
- run: composer install --no-interaction --prefer-dist --no-progress
- run: cp .env.example .env && php artisan key:generate
- run: vendor/bin/pint --test
- run: vendor/bin/pest

frontend:
runs-on: ubuntu-latest
steps:
- uses: actions/checkout@v4
# resources/js/app.js importa o Ziggy de vendor/, então o build precisa do composer
- uses: shivammathur/setup-php@v2
with:
php-version: '8.4'
coverage: none
- run: composer install --no-interaction --prefer-dist --no-progress --no-scripts
- uses: actions/setup-node@v4
with:
node-version: 22
cache: npm
- run: npm ci
- run: npm run format:check
- run: npm run build
6 changes: 6 additions & 0 deletions .prettierrc.json
Original file line number Diff line number Diff line change
@@ -0,0 +1,6 @@
{
"tabWidth": 4,
"semi": true,
"singleQuote": false,
"printWidth": 100
}
7 changes: 7 additions & 0 deletions app/Actions/Jetstream/DeleteUser.php
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,7 @@
namespace App\Actions\Jetstream;

use App\Models\User;
use Illuminate\Validation\ValidationException;
use Laravel\Jetstream\Contracts\DeletesUsers;

class DeleteUser implements DeletesUsers
Expand All @@ -12,6 +13,12 @@ class DeleteUser implements DeletesUsers
*/
public function delete(User $user): void
{
if ($user->orders()->exists()) {
throw ValidationException::withMessages([
'password' => 'Não é possível excluir a conta com pedidos registrados.',
]);
}

$user->deleteProfilePhoto();
$user->tokens->each->delete();
$user->delete();
Expand Down
73 changes: 73 additions & 0 deletions app/Actions/Order/PlaceOrder.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,73 @@
<?php

namespace App\Actions\Order;

use App\Enums\OrderStatus;
use App\Models\Order;
use App\Models\Product;
use App\Models\User;
use Carbon\Carbon;
use Illuminate\Support\Facades\DB;
use Illuminate\Validation\ValidationException;

class PlaceOrder
{
/**
* @param array<int, array{id: int, quantity: int}> $cartItems
* @param array{fullName: string, cardNumber: string, cardExpiration: string} $payment
*/
public function handle(User $user, array $cartItems, array $payment): Order
{
if ($cartItems === []) {
throw ValidationException::withMessages(['cart' => 'Seu carrinho está vazio.']);
}

return DB::transaction(function () use ($user, $cartItems, $payment) {
$quantities = collect($cartItems)
->mapWithKeys(fn ($item) => [$item['id'] => (int) $item['quantity']]);

$products = Product::whereIn('id', $quantities->keys())
->lockForUpdate()
->get()
->keyBy('id');

$subtotal = 0;
$pivot = [];

foreach ($quantities as $productId => $quantity) {
$product = $products->get($productId);

if (! $product || $product->stock < $quantity) {
throw ValidationException::withMessages([
'cart' => 'Estoque insuficiente para '.($product->name ?? 'um dos produtos').'.',
]);
}

$subtotal += $product->price * $quantity;
$pivot[$productId] = ['quantity' => $quantity, 'unit_price' => $product->price];
}

$order = $user->orders()->create([
'status' => OrderStatus::PendingPayment,
'subtotal' => round($subtotal, 2),
]);

$order->products()->attach($pivot);

foreach ($pivot as $productId => $item) {
$products->get($productId)->decrement('stock', $item['quantity']);
}

$order->payments()->create([
'full_name' => $payment['fullName'],
'card_last_four' => substr(preg_replace('/\D/', '', $payment['cardNumber']), -4),
'card_expiration' => Carbon::createFromFormat('!m/Y', $payment['cardExpiration'])->toDateString(),
]);

// Pagamento simulado: aprovado na hora.
$order->update(['status' => OrderStatus::Transporting]);

return $order;
});
}
}
20 changes: 0 additions & 20 deletions app/Actions/Payment/StoreNewPayment.php

This file was deleted.

11 changes: 11 additions & 0 deletions app/Enums/OrderStatus.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,11 @@
<?php

namespace App\Enums;

enum OrderStatus: string
{
case PendingPayment = 'pending_payment';
case Transporting = 'transporting';
case Completed = 'completed';
case Canceled = 'canceled';
}
2 changes: 1 addition & 1 deletion app/Http/Controllers/AddressController.php
Original file line number Diff line number Diff line change
Expand Up @@ -13,7 +13,7 @@ public function store(StoreAddressRequest $request)
{
$validated = $request->validated();
$user = auth()->user();
$address = $user->address()->first() ?? new Address();
$address = $user->address()->first() ?? new Address;
$address->fill($validated);
$user->address()->save($address);
}
Expand Down
57 changes: 27 additions & 30 deletions app/Http/Controllers/CartController.php
Original file line number Diff line number Diff line change
Expand Up @@ -2,33 +2,25 @@

namespace App\Http\Controllers;

use App\Http\Traits\CartTrait;
use App\Models\Product;
use App\Services\Cart;
use App\Services\RecommendedProducts;
use Illuminate\Http\Request;
use Inertia\Inertia;
use App\Http\Controllers\calculateSubTotalController;

class CartController extends Controller
{
use CartTrait;

public function __construct()
{
$this->initializeCartSession();
}

public function getAll()
public function __construct(private Cart $cart)
{
return $this->getCartItems();
$this->cart->initialize();
}


public function index(calculateSubTotalController $subtotalCalculator, GetRecommendedProductsController $recommendedProducts)
public function index(RecommendedProducts $recommendedProducts)
{
return Inertia::render('Cart/IndexCart',[
'products' => (array) $this->getCartItems(), // vem da trait.
'subtotal' => number_format($subtotalCalculator->calculate(), 2, '.', ''),
'recommended_products' => (array) $recommendedProducts->handle(),
return Inertia::render('Cart/IndexCart', [
'products' => $this->cart->items(),
'subtotal' => number_format($this->cart->subtotal(), 2, '.', ''),
'recommended_products' => (array) $recommendedProducts->handle($this->cart),
'is_admin' => auth()->user()->isAdmin(),
]);
}
Expand All @@ -40,19 +32,17 @@ public function store(Request $request)
'quantity' => 'required|integer|min:1',
]);
$product = Product::findOrFail($validated['product_id']);
if (!$product) {
return back()->with([
'message' => 'Product not found',
'error' => true,
]);

if ($validated['quantity'] > $product->stock) {
return back()->withErrors(['quantity' => 'Quantidade maior que o estoque disponível.']);
}
$product->quantity = $validated['quantity'];

$this->addToCart($product);
$this->cart->add($product, $validated['quantity']);

return back()->with([
'message' => 'Product successfully added to cart!',
'success' => true,
]);;
]);
}

public function update(Product $product, Request $request)
Expand All @@ -61,17 +51,24 @@ public function update(Product $product, Request $request)
'quantity' => 'required|integer|min:1',
]);

//verifica se o item está no carrinho
if(! $this->isInCart($product) ){
return back()->with('error','The product is not in the cart.');
// verifica se o item está no carrinho
if (! $this->cart->has($product)) {
return back()->withErrors(['cart' => 'O produto não está no carrinho.']);
}

if ($validated['quantity'] > $product->stock) {
return back()->withErrors(['quantity' => 'Quantidade maior que o estoque disponível.']);
}

$this->updateQuantity($product,$validated['quantity']);
$this->cart->update($product, $validated['quantity']);

return back()->with('success', 'Quantity successfully updated.');
}

public function destroy(Product $product)
{
$this->removefromCart($product);
$this->cart->remove($product);

return back();
}
}
Loading
Loading