Commit baa5d9c5 by Venkatshiva

add README

parents
<?php
namespace App\Http\Controllers;
use App\Models\Order;
use App\Models\Product;
use App\Models\Pincode;
use Illuminate\Http\JsonResponse;
use Illuminate\Http\Request;
class AdminController extends Controller
{
/**
* Get overview dashboard metrics.
*/
public function metrics(): JsonResponse
{
$totalSales = Order::where('payment_status', 'paid')->sum('total');
$activeOrders = Order::whereIn('order_status', ['pending', 'processing', 'shipped'])->count();
$totalProducts = Product::count();
$recentOrders = Order::latest()->limit(5)->get();
return response()->json([
'success' => true,
'data' => [
'metrics' => [
'total_sales' => $totalSales,
'active_orders' => $activeOrders,
'total_products' => $totalProducts,
],
'recent_orders' => $recentOrders
]
]);
}
/**
* Store a newly created product.
*/
public function storeProduct(Request $request): JsonResponse
{
$request->validate([
'category_id' => 'required|exists:categories,id',
'name' => 'required|string|max:255',
'slug' => 'required|string|unique:products,slug',
'description' => 'nullable|string',
'price' => 'required|numeric|min:0',
'strike_price' => 'nullable|numeric|min:0',
'stock_quantity' => 'required|integer|min:0',
'is_bestseller' => 'boolean'
]);
$product = Product::create($request->all());
return response()->json([
'success' => true,
'message' => 'Product added successfully!',
'data' => $product
], 201);
}
/**
* Update product details.
*/
public function updateProduct(Request $request, $id): JsonResponse
{
$product = Product::findOrFail($id);
$request->validate([
'name' => 'sometimes|string|max:255',
'slug' => 'sometimes|string|unique:products,slug,' . $product->id,
'price' => 'sometimes|numeric|min:0',
'stock_quantity' => 'sometimes|integer|min:0',
]);
$product->update($request->all());
return response()->json([
'success' => true,
'message' => 'Product updated successfully!',
'data' => $product
]);
}
/**
* Delete a product.
*/
public function destroyProduct($id): JsonResponse
{
$product = Product::findOrFail($id);
$product->delete();
return response()->json([
'success' => true,
'message' => 'Product removed successfully!'
]);
}
/**
* Get list of orders.
*/
public function orders(): JsonResponse
{
$orders = Order::with('items.product')->latest()->paginate(15);
return response()->json([
'success' => true,
'data' => $orders
]);
}
/**
* Update delivery status of an order.
*/
public function updateOrderStatus(Request $request, $id): JsonResponse
{
$request->validate([
'order_status' => 'required|string|in:pending,processing,shipped,delivered,cancelled',
'payment_status' => 'sometimes|string|in:pending,paid,failed'
]);
$order = Order::findOrFail($id);
$order->update($request->only(['order_status', 'payment_status']));
return response()->json([
'success' => true,
'message' => 'Order status updated successfully!',
'data' => $order
]);
}
}
<?php
namespace App\Http\Controllers;
use App\Models\Category;
use App\Models\Product;
use Illuminate\Http\JsonResponse;
use Illuminate\Http\Request;
class CatalogController extends Controller
{
/**
* Get all categories.
*/
public function categories(): JsonResponse
{
$categories = Category::all();
return response()->json([
'success' => true,
'data' => $categories
]);
}
/**
* Get products with optional category filtering and sorting.
*/
public function products(Request $request): JsonResponse
{
$query = Product::with(['primaryImage', 'category']);
// Filter by category slug
if ($request->has('category')) {
$query->whereHas('category', function ($q) use ($request) {
$q->where('slug', $request->input('category'));
});
}
// Bestsellers filter
if ($request->has('bestsellers')) {
$query->where('is_bestseller', true);
}
$products = $query->paginate(12);
return response()->json([
'success' => true,
'data' => $products
]);
}
/**
* Get single product details by slug.
*/
public function productDetails(string $slug): JsonResponse
{
$product = Product::with(['images', 'variants', 'category'])->where('slug', $slug)->first();
if (!$product) {
return response()->json([
'success' => false,
'message' => 'Product not found'
], 404);
}
// Fetch related products from same category (excluding current)
$relatedProducts = Product::with('primaryImage')
->where('category_id', $product->category_id)
->where('id', '!=', $product->id)
->limit(4)
->get();
return response()->json([
'success' => true,
'data' => [
'product' => $product,
'related_products' => $relatedProducts
]
]);
}
}
<?php
namespace App\Http\Controllers;
use App\Models\Coupon;
use App\Models\Order;
use App\Models\OrderItem;
use App\Models\Product;
use App\Models\ProductVariant;
use Illuminate\Http\JsonResponse;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Str;
class CheckoutController extends Controller
{
/**
* Store a newly created order.
*/
public function store(Request $request): JsonResponse
{
$request->validate([
'customer_name' => 'required|string|max:255',
'email' => 'required|email|max:255',
'phone' => 'required|string|max:20',
'shipping_address' => 'required|string',
'pincode' => 'required|string|size:6',
'city' => 'required|string|max:100',
'state' => 'required|string|max:100',
'payment_method' => 'required|string|in:COD,Online',
'coupon_code' => 'nullable|string',
'items' => 'required|array|min:1',
'items.*.product_id' => 'required|exists:products,id',
'items.*.variant_id' => 'nullable|exists:product_variants,id',
'items.*.quantity' => 'required|integer|min:1',
]);
try {
DB::beginTransaction();
$subtotal = 0;
$orderItemsToCreate = [];
foreach ($request->input('items') as $item) {
$product = Product::findOrFail($item['product_id']);
$price = $product->price;
$variant = null;
// If variant selected (e.g. Size override price)
if (!empty($item['variant_id'])) {
$variant = ProductVariant::where('product_id', $product->id)
->where('id', $item['variant_id'])
->first();
if ($variant) {
if ($variant->price !== null) {
$price = $variant->price;
}
if ($variant->stock_quantity < $item['quantity']) {
throw new \Exception("Inadequate stock for product variant: {$product->name} ({$variant->size})");
}
// Deduct variant stock
$variant->decrement('stock_quantity', $item['quantity']);
}
} else {
if ($product->stock_quantity < $item['quantity']) {
throw new \Exception("Inadequate stock for product: {$product->name}");
}
// Deduct base product stock
$product->decrement('stock_quantity', $item['quantity']);
}
$itemTotal = $price * $item['quantity'];
$subtotal += $itemTotal;
$orderItemsToCreate[] = [
'product_id' => $product->id,
'product_variant_id' => $item['variant_id'] ?? null,
'quantity' => $item['quantity'],
'price' => $price,
];
}
// Coupon Code Calculation
$discount = 0.00;
if ($request->filled('coupon_code')) {
$coupon = Coupon::where('code', $request->input('coupon_code'))
->where('is_active', true)
->first();
if ($coupon) {
$discount = $coupon->calculateDiscount($subtotal);
}
}
// Simple shipping charge rule: free above 999, else 85
$shippingCharges = $subtotal >= 999 ? 0.00 : 85.00;
$total = max(0, ($subtotal - $discount)) + $shippingCharges;
// Generate a unique order number (e.g. VSI-171534567)
$orderNumber = 'VSI-' . strtoupper(Str::random(4)) . time();
$order = Order::create([
'order_number' => $orderNumber,
'customer_name' => $request->input('customer_name'),
'email' => $request->input('email'),
'phone' => $request->input('phone'),
'shipping_address' => $request->input('shipping_address'),
'pincode' => $request->input('pincode'),
'city' => $request->input('city'),
'state' => $request->input('state'),
'subtotal' => $subtotal,
'shipping_charges' => $shippingCharges,
'discount' => $discount,
'total' => $total,
'payment_method' => $request->input('payment_method'),
'payment_status' => $request->input('payment_method') === 'COD' ? 'pending' : 'paid', // simple simulation
'order_status' => 'pending',
]);
foreach ($orderItemsToCreate as $itemData) {
$itemData['order_id'] = $order->id;
OrderItem::create($itemData);
}
DB::commit();
return response()->json([
'success' => true,
'message' => 'Order placed successfully!',
'data' => [
'order_number' => $order->order_number,
'total' => $order->total
]
], 201);
} catch (\Exception $e) {
DB::rollBack();
return response()->json([
'success' => false,
'message' => $e->getMessage(),
], 500);
}
}
}
<?php
namespace App\Http\Controllers;
use App\Models\Coupon;
use Illuminate\Http\JsonResponse;
use Illuminate\Http\Request;
class CouponController extends Controller
{
/**
* Validate coupon code for checkout calculations.
*/
public function validateCoupon(Request $request): JsonResponse
{
$request->validate([
'code' => 'required|string',
'subtotal' => 'required|numeric|min:0'
]);
$coupon = Coupon::where('code', $request->input('code'))
->where('is_active', true)
->first();
if (!$coupon) {
return response()->json([
'success' => false,
'message' => 'Invalid or inactive coupon code.'
], 404);
}
$subtotal = (float) $request->input('subtotal');
if ($subtotal < $coupon->min_order_amount) {
return response()->json([
'success' => false,
'message' => "Minimum order of ₹{$coupon->min_order_amount} is required to apply this coupon."
], 422);
}
$discount = $coupon->calculateDiscount($subtotal);
return response()->json([
'success' => true,
'data' => [
'code' => $coupon->code,
'type' => $coupon->type,
'value' => $coupon->value,
'discount_amount' => $discount
]
]);
}
}
<?php
namespace App\Http\Controllers;
use App\Models\Pincode;
use Illuminate\Http\JsonResponse;
use Illuminate\Http\Request;
class PincodeController extends Controller
{
/**
* Check if a pincode is serviceable and return delivery estimate.
*/
public function checkServiceability(Request $request): JsonResponse
{
$request->validate([
'pincode' => 'required|string|size:6'
]);
$pincodeVal = $request->input('pincode');
$dbPincode = Pincode::where('pincode', $pincodeVal)->first();
// Default logic: if it's Chennai (starting with 600), default to serviceable in 3 days
if (!$dbPincode) {
if (str_starts_with($pincodeVal, '600')) {
return response()->json([
'success' => true,
'serviceable' => true,
'est_delivery_days' => 3,
'message' => 'Delivered within 3 days in Chennai.'
]);
}
// Fallback for general serviceable areas (standard all-India delivery)
return response()->json([
'success' => true,
'serviceable' => true,
'est_delivery_days' => 7,
'message' => '4-7 days all-India shipping available.'
]);
}
if (!$dbPincode->is_serviceable) {
return response()->json([
'success' => false,
'serviceable' => false,
'message' => 'Delivery is currently unavailable to this location.'
]);
}
return response()->json([
'success' => true,
'serviceable' => true,
'est_delivery_days' => $dbPincode->est_delivery_days,
'message' => "Estimated delivery in {$dbPincode->est_delivery_days} days."
]);
}
}
<?php
namespace App\Http\Controllers;
use App\Models\Wishlist;
use Illuminate\Http\JsonResponse;
use Illuminate\Http\Request;
class WishlistController extends Controller
{
/**
* Get user wishlist.
*/
public function index(Request $request): JsonResponse
{
$sessionId = $request->header('X-Session-ID') ?? session()->getId();
$wishlist = Wishlist::with('product.primaryImage')
->where('session_id', $sessionId)
->get();
return response()->json([
'success' => true,
'data' => $wishlist
]);
}
/**
* Add product to wishlist.
*/
public function store(Request $request): JsonResponse
{
$request->validate([
'product_id' => 'required|exists:products,id'
]);
$sessionId = $request->header('X-Session-ID') ?? session()->getId();
$productId = $request->input('product_id');
$exists = Wishlist::where('session_id', $sessionId)
->where('product_id', $productId)
->exists();
if ($exists) {
return response()->json([
'success' => true,
'message' => 'Product is already in your wishlist.'
]);
}
$wishlistItem = Wishlist::create([
'session_id' => $sessionId,
'product_id' => $productId
]);
return response()->json([
'success' => true,
'message' => 'Added to wishlist!',
'data' => $wishlistItem
], 201);
}
/**
* Remove product from wishlist.
*/
public function destroy(Request $request, $productId): JsonResponse
{
$sessionId = $request->header('X-Session-ID') ?? session()->getId();
Wishlist::where('session_id', $sessionId)
->where('product_id', $productId)
->delete();
return response()->json([
'success' => true,
'message' => 'Removed from wishlist.'
]);
}
}
<?php
namespace App\Models;
use Illuminate\Database\Eloquent\Factories\HasFactory;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Database\Eloquent\Relations\HasMany;
class Category extends Model
{
use HasFactory;
protected $fillable = [
'name',
'slug',
'image_url',
'description',
];
/**
* Get the products for the category.
*/
public function products(): HasMany
{
return $this->hasMany(Product::class);
}
}
<?php
namespace App\Models;
use Illuminate\Database\Eloquent\Factories\HasFactory;
use Illuminate\Database\Eloquent\Model;
class Coupon extends Model
{
use HasFactory;
protected $fillable = [
'code',
'type',
'value',
'min_order_amount',
'is_active',
];
protected $casts = [
'value' => 'decimal:2',
'min_order_amount' => 'decimal:2',
'is_active' => 'boolean',
];
/**
* Calculate discount amount based on order subtotal.
*/
public function calculateDiscount(float $subtotal): float
{
if ($subtotal < $this->min_order_amount) {
return 0.00;
}
if ($this->type === 'percent') {
return round(($subtotal * ($this->value / 100)), 2);
}
return min($this->value, $subtotal);
}
}
<?php
namespace App\Models;
use Illuminate\Database\Eloquent\Factories\HasFactory;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Database\Eloquent\Relations\HasMany;
class Order extends Model
{
use HasFactory;
protected $fillable = [
'order_number',
'customer_name',
'email',
'phone',
'shipping_address',
'pincode',
'city',
'state',
'subtotal',
'shipping_charges',
'discount',
'total',
'payment_method',
'payment_status',
'order_status',
];
/**
* Get the items for the order.
*/
public function items(): HasMany
{
return $this->hasMany(OrderItem::class);
}
}
<?php
namespace App\Models;
use Illuminate\Database\Eloquent\Factories\HasFactory;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Database\Eloquent\Relations\BelongsTo;
class OrderItem extends Model
{
use HasFactory;
protected $fillable = [
'order_id',
'product_id',
'product_variant_id',
'quantity',
'price',
];
/**
* Get the order that owns the item.
*/
public function order(): BelongsTo
{
return $this->belongsTo(Order::class);
}
/**
* Get the product associated with the item.
*/
public function product(): BelongsTo
{
return $this->belongsTo(Product::class);
}
/**
* Get the variant associated with the item.
*/
public function variant(): BelongsTo
{
return $this->belongsTo(ProductVariant::class, 'product_variant_id');
}
}
<?php
namespace App\Models;
use Illuminate\Database\Eloquent\Factories\HasFactory;
use Illuminate\Database\Eloquent\Model;
class Pincode extends Model
{
use HasFactory;
protected $fillable = [
'pincode',
'is_serviceable',
'est_delivery_days',
];
protected $casts = [
'is_serviceable' => 'boolean',
];
}
<?php
namespace App\Models;
use Illuminate\Database\Eloquent\Factories\HasFactory;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Database\Eloquent\Relations\BelongsTo;
use Illuminate\Database\Eloquent\Relations\HasMany;
class Product extends Model
{
use HasFactory;
protected $fillable = [
'category_id',
'name',
'slug',
'description',
'price',
'strike_price',
'stock_quantity',
'is_bestseller',
];
protected $casts = [
'price' => 'decimal:2',
'strike_price' => 'decimal:2',
'is_bestseller' => 'boolean',
];
/**
* Get the category that owns the product.
*/
public function category(): BelongsTo
{
return $this->belongsTo(Category::class);
}
/**
* Get the images for the product.
*/
public function images(): HasMany
{
return $this->hasMany(ProductImage::class);
}
/**
* Get the primary image of the product.
*/
public function primaryImage()
{
return $this->hasOne(ProductImage::class)->where('is_primary', true)->withDefault([
'image_url' => 'https://images.unsplash.com/photo-1618221195710-dd6b41faaea6?w=500&auto=format&fit=crop&q=80'
]);
}
/**
* Get the variants for the product.
*/
public function variants(): HasMany
{
return $this->hasMany(ProductVariant::class);
}
}
<?php
namespace App\Models;
use Illuminate\Database\Eloquent\Factories\HasFactory;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Database\Eloquent\Relations\BelongsTo;
class ProductImage extends Model
{
use HasFactory;
protected $fillable = [
'product_id',
'image_url',
'is_primary',
];
protected $casts = [
'is_primary' => 'boolean',
];
/**
* Get the product that owns the image.
*/
public function product(): BelongsTo
{
return $this->belongsTo(Product::class);
}
}
<?php
namespace App\Models;
use Illuminate\Database\Eloquent\Factories\HasFactory;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Database\Eloquent\Relations\BelongsTo;
class ProductVariant extends Model
{
use HasFactory;
protected $fillable = [
'product_id',
'size',
'price',
'stock_quantity',
];
protected $casts = [
'price' => 'decimal:2',
];
/**
* Get the product that owns the variant.
*/
public function product(): BelongsTo
{
return $this->belongsTo(Product::class);
}
}
<?php
namespace App\Models;
use Illuminate\Database\Eloquent\Factories\HasFactory;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Database\Eloquent\Relations\BelongsTo;
class Wishlist extends Model
{
use HasFactory;
protected $fillable = [
'session_id',
'product_id',
];
/**
* Get the product saved in wishlist.
*/
public function product(): BelongsTo
{
return $this->belongsTo(Product::class);
}
}
<?php
namespace App\Providers;
use Illuminate\Support\ServiceProvider;
class AppServiceProvider extends ServiceProvider
{
/**
* Register any application services.
*/
public function register(): void
{
//
}
/**
* Bootstrap any application services.
*/
public function boot(): void
{
//
}
}
#!/usr/bin/env php
<?php
define('LARAVEL_START', microtime(true));
// Register the Composer Autoloader
if (file_exists($composer = __DIR__.'/vendor/autoload.php')) {
require $composer;
}
// Boot Laravel
$app = require_once __DIR__.'/bootstrap/app.php';
$kernel = $app->make(Illuminate\Contracts\Console\Kernel::class);
$status = $kernel->handle(
$input = new Symfony\Component\Console\Input\ArgvInput,
new Symfony\Component\Console\Output\ConsoleOutput
);
$kernel->terminate($input, $status);
exit($status);
<?php
use Illuminate\Foundation\Application;
use Illuminate\Foundation\Configuration\Exceptions;
use Illuminate\Foundation\Configuration\Middleware;
return Application::configure(basePath: dirname(__DIR__))
->withRouting(
web: __DIR__.'/../routes/web.php',
api: __DIR__.'/../routes/api.php',
commands: __DIR__.'/../routes/console.php',
health: '/up',
)
->withMiddleware(function (Middleware $middleware) {
//
})
->withExceptions(function (Exceptions $exceptions) {
//
})->create();
<?php
return [
App\Providers\AppServiceProvider::class,
];
{
"name": "laravel/laravel",
"type": "project",
"description": "The skeleton application for the Laravel framework.",
"keywords": ["laravel", "framework"],
"license": "MIT",
"require": {
"php": "^8.2",
"laravel/framework": "^11.0",
"laravel/tinker": "^2.9"
},
"autoload": {
"psr-4": {
"App\\": "app/",
"Database\\Factories\\": "database/factories/",
"Database\\Seeders\\": "database/seeders/"
}
},
"config": {
"optimize-autoloader": true,
"preferred-install": "dist",
"sort-packages": true,
"allow-plugins": {
"pestphp/pest-plugin": true,
"php-http/discovery": true
}
},
"minimum-stability": "stable",
"prefer-stable": true
}
This source diff could not be displayed because it is too large. You can view the blob instead.
File added
<?php
return [
'name' => env('APP_NAME', 'Laravel'),
'env' => env('APP_ENV', 'production'),
'debug' => (bool) env('APP_DEBUG', false),
'url' => env('APP_URL', 'http://localhost'),
'timezone' => env('APP_TIMEZONE', 'UTC'),
'locale' => env('APP_LOCALE', 'en'),
'fallback_locale' => env('APP_FALLBACK_LOCALE', 'en'),
'faker_locale' => env('APP_FAKER_LOCALE', 'en_US'),
'cipher' => 'AES-256-CBC',
'key' => env('APP_KEY'),
'previous_keys' => [
...array_filter(
explode(',', env('APP_PREVIOUS_KEYS', ''))
),
],
];
<?php
use Illuminate\Support\Str;
return [
'default' => env('DB_CONNECTION', 'sqlite'),
'connections' => [
'sqlite' => [
'driver' => 'sqlite',
'url' => env('DB_URL'),
'database' => env('DB_DATABASE', database_path('database.sqlite')),
'prefix' => '',
'foreign_key_constraints' => env('DB_FOREIGN_KEYS', true),
],
'mysql' => [
'driver' => 'mysql',
'url' => env('DB_URL'),
'host' => env('DB_HOST', '127.0.0.1'),
'port' => env('DB_PORT', '3306'),
'database' => env('DB_DATABASE', 'laravel'),
'username' => env('DB_USERNAME', 'root'),
'password' => env('DB_PASSWORD', ''),
'unix_socket' => env('DB_SOCKET', ''),
'charset' => env('DB_CHARSET', 'utf8mb4'),
'collation' => env('DB_COLLATION', 'utf8mb4_unicode_ci'),
'prefix' => '',
'prefix_indexes' => true,
'strict' => true,
'engine' => null,
'options' => extension_loaded('pdo_mysql') ? array_filter([
PDO::MYSQL_ATTR_SSL_CA => env('MYSQL_ATTR_SSL_CA'),
]) : [],
],
],
'migrations' => [
'table' => 'migrations',
'update_date_on_publish' => true,
],
];
<?php
use Illuminate\Database\Migrations\Migration;
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Support\Facades\Schema;
return new class extends Migration
{
/**
* Run the migrations.
*/
public function up(): void
{
Schema::create('categories', function (Blueprint $table) {
$table->id();
$table->string('name');
$table->string('slug')->unique();
$table->string('image_url')->nullable();
$table->text('description')->nullable();
$table->timestamps();
});
}
/**
* Reverse the migrations.
*/
public function down(): void
{
Schema::dropIfExists('categories');
}
};
<?php
use Illuminate\Database\Migrations\Migration;
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Support\Facades\Schema;
return new class extends Migration
{
/**
* Run the migrations.
*/
public function up(): void
{
Schema::create('products', function (Blueprint $table) {
$table->id();
$table->foreignId('category_id')->constrained()->onDelete('cascade');
$table->string('name');
$table->string('slug')->unique();
$table->text('description')->nullable();
$table->decimal('price', 10, 2);
$table->decimal('strike_price', 10, 2)->nullable();
$table->integer('stock_quantity')->default(0);
$table->boolean('is_bestseller')->default(false);
$table->timestamps();
});
}
/**
* Reverse the migrations.
*/
public function down(): void
{
Schema::dropIfExists('products');
}
};
<?php
use Illuminate\Database\Migrations\Migration;
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Support\Facades\Schema;
return new class extends Migration
{
/**
* Run the migrations.
*/
public function up(): void
{
Schema::create('product_images', function (Blueprint $table) {
$table->id();
$table->foreignId('product_id')->constrained()->onDelete('cascade');
$table->string('image_url');
$table->boolean('is_primary')->default(false);
$table->timestamps();
});
}
/**
* Reverse the migrations.
*/
public function down(): void
{
Schema::dropIfExists('product_images');
}
};
<?php
use Illuminate\Database\Migrations\Migration;
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Support\Facades\Schema;
return new class extends Migration
{
/**
* Run the migrations.
*/
public function up(): void
{
Schema::create('product_variants', function (Blueprint $table) {
$table->id();
$table->foreignId('product_id')->constrained()->onDelete('cascade');
$table->string('size'); // Small, Medium, Large
$table->decimal('price', 10, 2)->nullable(); // override price if set
$table->integer('stock_quantity')->default(0);
$table->timestamps();
});
}
/**
* Reverse the migrations.
*/
public function down(): void
{
Schema::dropIfExists('product_variants');
}
};
<?php
use Illuminate\Database\Migrations\Migration;
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Support\Facades\Schema;
return new class extends Migration
{
/**
* Run the migrations.
*/
public function up(): void
{
Schema::create('pincodes', function (Blueprint $table) {
$table->id();
$table->string('pincode', 6)->unique();
$table->boolean('is_serviceable')->default(true);
$table->integer('est_delivery_days')->default(3);
$table->timestamps();
});
}
/**
* Reverse the migrations.
*/
public function down(): void
{
Schema::dropIfExists('pincodes');
}
};
<?php
use Illuminate\Database\Migrations\Migration;
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Support\Facades\Schema;
return new class extends Migration
{
/**
* Run the migrations.
*/
public function up(): void
{
Schema::create('orders', function (Blueprint $table) {
$table->id();
$table->string('order_number')->unique();
$table->string('customer_name');
$table->string('email');
$table->string('phone');
$table->text('shipping_address');
$table->string('pincode', 6);
$table->string('city');
$table->string('state');
$table->decimal('subtotal', 10, 2);
$table->decimal('shipping_charges', 10, 2)->default(0.00);
$table->decimal('discount', 10, 2)->default(0.00);
$table->decimal('total', 10, 2);
$table->string('payment_method')->default('COD'); // COD or Online
$table->string('payment_status')->default('pending');
$table->string('order_status')->default('pending');
$table->timestamps();
});
}
/**
* Reverse the migrations.
*/
public function down(): void
{
Schema::dropIfExists('orders');
}
};
<?php
use Illuminate\Database\Migrations\Migration;
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Support\Facades\Schema;
return new class extends Migration
{
/**
* Run the migrations.
*/
public function up(): void
{
Schema::create('order_items', function (Blueprint $table) {
$table->id();
$table->foreignId('order_id')->constrained()->onDelete('cascade');
$table->foreignId('product_id')->constrained();
$table->foreignId('product_variant_id')->nullable()->constrained()->onDelete('set null');
$table->integer('quantity');
$table->decimal('price', 10, 2);
$table->timestamps();
});
}
/**
* Reverse the migrations.
*/
public function down(): void
{
Schema::dropIfExists('order_items');
}
};
<?php
use Illuminate\Database\Migrations\Migration;
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Support\Facades\Schema;
return new class extends Migration
{
/**
* Run the migrations.
*/
public function up(): void
{
Schema::create('coupons', function (Blueprint $table) {
$table->id();
$table->string('code')->unique();
$table->string('type'); // fixed, percent
$table->decimal('value', 10, 2);
$table->decimal('min_order_amount', 10, 2)->default(0.00);
$table->boolean('is_active')->default(true);
$table->timestamps();
});
}
/**
* Reverse the migrations.
*/
public function down(): void
{
Schema::dropIfExists('coupons');
}
};
<?php
use Illuminate\Database\Migrations\Migration;
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Support\Facades\Schema;
return new class extends Migration
{
/**
* Run the migrations.
*/
public function up(): void
{
Schema::create('wishlists', function (Blueprint $table) {
$table->id();
$table->string('session_id'); // support guest wishlist via session ID
$table->foreignId('product_id')->constrained()->onDelete('cascade');
$table->timestamps();
});
}
/**
* Reverse the migrations.
*/
public function down(): void
{
Schema::dropIfExists('wishlists');
}
};
RewriteEngine On
# Resolve extensionless URLs to HTML files
RewriteCond %{REQUEST_FILENAME} !-d
RewriteCond %{REQUEST_FILENAME}.html -f
RewriteRule ^(.*?)/?$ $1.html [L]
<?php
use Illuminate\Http\Request;
define('LARAVEL_START', microtime(true));
// Determine if the application is in maintenance mode...
if (file_exists($maintenance = __DIR__.'/../storage/framework/maintenance.php')) {
require $maintenance;
}
// Register the Composer Autoloader
if (file_exists($autoload = __DIR__.'/../vendor/autoload.php')) {
require $autoload;
}
// Run the application
$app = require_once __DIR__.'/../bootstrap/app.php';
$app->handleRequest(Request::capture());
This diff is collapsed. Click to expand it.
// Cart state management
let cart = JSON.parse(localStorage.getItem('vsimart_cart')) || [];
let appliedCoupon = false;
function updateCartHeader() {
let count = cart.reduce((total, item) => total + item.quantity, 0);
$('#cart-count').text(count);
// Summary counts (cart & checkout page)
$('#summary-cart-count').text(count);
$('#summary-items-count').text(count);
$('#summary-items-label').text(`Price (${count} items)`);
$('#price-items-label').text(`Price (${count} items)`);
}
function saveCart() {
localStorage.setItem('vsimart_cart', JSON.stringify(cart));
updateCartHeader();
}
$(document).ready(function() {
updateCartHeader();
// Size Selection toggles
$(document).on('click', '.size-btn', function() {
$(this).siblings().removeClass('active');
$(this).addClass('active');
});
// Add to cart buttons (for bestsellers & product detail page)
$(document).on('click', '.btn-add-to-cart-dynamic', function() {
let card = $(this).closest('.product-card-body, .product-detail-info');
let id = $(this).data('id') || 'p1';
let name = $(this).data('name') || card.find('.product-title, h1').text().trim();
let price = parseInt($(this).data('price')) || 450;
let img = $(this).data('img') || '';
let size = card.find('.size-btn.active').text() || 'Small';
let quantity = parseInt($('#detail-qty').val()) || 1;
let existing = cart.find(item => item.id === id && item.size === size);
if (existing) {
existing.quantity += quantity;
} else {
cart.push({ id, name, price, img, size, quantity });
}
saveCart();
alert(`${name} (${size}) added to Cart!`);
// Reset detail qty if any
$('#detail-qty').val(1);
});
// Quantity selectors in Cart page
$(document).on('click', '.qty-btn', function() {
let index = $(this).data('index');
let action = $(this).data('action');
if (action === 'plus') {
cart[index].quantity += 1;
} else if (action === 'minus') {
cart[index].quantity -= 1;
if (cart[index].quantity <= 0) {
cart.splice(index, 1);
}
}
saveCart();
renderCart();
});
// Remove item in Cart page
$(document).on('click', '.btn-remove-item', function() {
let index = $(this).data('index');
cart.splice(index, 1);
saveCart();
renderCart();
});
// Render Cart items
function renderCart() {
let container = $('#cart-items-list');
if (!container.length) return;
if (cart.length === 0) {
container.html('<div class="text-center py-5"><i class="bi bi-cart-x fs-1 text-muted"></i><h4 class="mt-3">Your cart is empty</h4><a href="shop.html" class="btn btn-outline-primary rounded-pill mt-3 px-4">Go to Shop</a></div>');
$('#summary-subtotal').text('₹0');
$('#summary-total').text('₹0');
$('#discount-row').attr('style', 'display: none !important;');
return;
}
let html = '';
let subtotal = 0;
cart.forEach((item, index) => {
let itemTotal = item.price * item.quantity;
subtotal += itemTotal;
let strikePrice = Math.round(item.price * 1.18);
let saveAmt = strikePrice - item.price;
html += `
<div class="card border-0 shadow-sm rounded-4 p-3 bg-white">
<div class="row align-items-center">
<div class="col-md-2 col-4">
<img src="${item.img}" class="img-fluid rounded-3" alt="${item.name}" style="height: 80px; width: 80px; object-fit: cover;">
</div>
<div class="col-md-5 col-8">
<h6 class="fw-bold mb-1">${item.name}</h6>
<div class="d-flex align-items-center flex-wrap gap-2">
<span class="fw-bold text-dark">₹${item.price}</span>
<span class="text-muted text-decoration-line-through small">₹${strikePrice}</span>
<span class="badge bg-primary" style="font-size: 0.65rem; padding: 0.15rem 0.35rem;">SAVE ₹${saveAmt}</span>
</div>
<div class="text-primary fw-bold small mt-1" style="font-size: 0.72rem;">9% OFF</div>
<p class="text-muted small mb-0 mt-1">Size / Variant: <span class="badge bg-light text-dark border">${item.size}</span></p>
</div>
<div class="col-md-3 col-6 mt-3 mt-md-0">
<div class="d-flex align-items-center border rounded-3 p-1 bg-light justify-content-between" style="max-width: 110px;">
<button class="btn btn-link btn-sm px-2 py-0 text-dark text-decoration-none qty-btn" data-index="${index}" data-action="minus"><i class="bi bi-dash"></i></button>
<span class="fw-bold px-1">${item.quantity}</span>
<button class="btn btn-link btn-sm px-2 py-0 text-dark text-decoration-none qty-btn" data-index="${index}" data-action="plus"><i class="bi bi-plus"></i></button>
</div>
</div>
<div class="col-md-2 col-6 mt-3 mt-md-0 text-end">
<span class="fw-bold fs-5 d-block text-warning mb-2">₹${itemTotal}</span>
<button class="btn btn-link text-muted btn-remove-item p-0 align-middle" data-index="${index}" style="font-size: 1.25rem;"><i class="bi bi-trash"></i></button>
</div>
</div>
</div>
`;
});
container.html(html);
$('#summary-subtotal').text('₹' + subtotal);
let discount = 0;
if (appliedCoupon) {
discount = Math.round(subtotal * 0.10);
$('#summary-discount').text('-₹' + discount);
$('#discount-row').attr('style', 'display: flex !important;');
} else {
$('#discount-row').attr('style', 'display: none !important;');
}
let total = subtotal - discount;
$('#summary-total').text('₹' + total);
}
// Call initially for cart & checkout summary values
renderCart();
// Checkout specific initialization
if ($('#checkout-form').length) {
let subtotal = cart.reduce((sum, item) => sum + (item.price * item.quantity), 0);
$('#summary-subtotal').text('₹' + subtotal);
$('#summary-total').text('₹' + subtotal);
}
// Payment Selection
$('.payment-option').click(function() {
$('.payment-option').removeClass('active');
$(this).addClass('active');
});
// Gallery Lightbox Modal
let galleryImages = [];
$('.gallery-grid .gallery-item img').each(function() {
galleryImages.push($(this).attr('src'));
});
let currentImgIdx = 0;
$('.gallery-grid .gallery-item').click(function() {
let imgUrl = $(this).find('img').attr('src');
currentImgIdx = galleryImages.indexOf(imgUrl);
$('#lightbox-img').attr('src', imgUrl);
$('#lightbox-modal').fadeIn(300).css('display', 'flex');
});
$('#lightbox-close').click(function() {
$('#lightbox-modal').fadeOut(300);
});
// Close on backdrop click
$('#lightbox-modal').click(function(e) {
if (e.target === this) {
$('#lightbox-modal').fadeOut(300);
}
});
$('#lightbox-prev').click(function(e) {
e.stopPropagation();
currentImgIdx = (currentImgIdx - 1 + galleryImages.length) % galleryImages.length;
$('#lightbox-img').attr('src', galleryImages[currentImgIdx]);
});
$('#lightbox-next').click(function(e) {
e.stopPropagation();
currentImgIdx = (currentImgIdx + 1) % galleryImages.length;
$('#lightbox-img').attr('src', galleryImages[currentImgIdx]);
});
// Coupon Code applying simulation
$('#apply-coupon-btn').click(function() {
let code = $('#coupon-input').val().trim().toUpperCase();
let msg = $('#coupon-message');
if (code === 'OCEAN10') {
appliedCoupon = true;
msg.html('<span class="text-success fw-bold">Coupon OCEAN10 applied successfully! 10% discount subtracted.</span>');
renderCart();
} else {
msg.html('<span class="text-danger fw-bold">Invalid Coupon Code! Please try code: OCEAN10</span>');
}
});
// Checkout Form Submission
$('#checkout-form').submit(function(e) {
e.preventDefault();
alert('Thank you for your order! Your VSI Mart seashell order has been placed successfully. Order ID: VSI-' + Math.floor(100000 + Math.random() * 900000));
localStorage.removeItem('vsimart_cart');
cart = [];
window.location.href = 'index.html';
});
});
# Keep this directory
<?php
use App\Http\Controllers\AdminController;
use App\Http\Controllers\CatalogController;
use App\Http\Controllers\CheckoutController;
use App\Http\Controllers\CouponController;
use App\Http\Controllers\PincodeController;
use App\Http\Controllers\WishlistController;
use Illuminate\Support\Facades\Route;
/*
|--------------------------------------------------------------------------
| API Routes
|--------------------------------------------------------------------------
|
| Here is where you can register API routes for your application. These
| routes are loaded by the RouteServiceProvider and all of them will
| be assigned to the "api" middleware group. Make something great!
|
*/
// Catalog Endpoints
Route::get('/categories', [CatalogController::class, 'categories']);
Route::get('/products', [CatalogController::class, 'products']);
Route::get('/products/{slug}', [CatalogController::class, 'productDetails']);
// Serviceability Pincode Endpoints
Route::post('/check-pincode', [PincodeController::class, 'checkServiceability']);
// Checkout / Place Order
Route::post('/place-order', [CheckoutController::class, 'store']);
// Coupon Validation
Route::post('/validate-coupon', [CouponController::class, 'validateCoupon']);
// Wishlist Endpoints
Route::get('/wishlist', [WishlistController::class, 'index']);
Route::post('/wishlist', [WishlistController::class, 'store']);
Route::delete('/wishlist/{productId}', [WishlistController::class, 'destroy']);
// Admin Dashboard Endpoints
Route::prefix('admin')->group(function () {
Route::get('/metrics', [AdminController::class, 'metrics']);
Route::post('/products', [AdminController::class, 'storeProduct']);
Route::put('/products/{id}', [AdminController::class, 'updateProduct']);
Route::delete('/products/{id}', [AdminController::class, 'destroyProduct']);
Route::get('/orders', [AdminController::class, 'orders']);
Route::put('/orders/{id}/status', [AdminController::class, 'updateOrderStatus']);
});
<?php
use Illuminate\Support\Facades\Artisan;
Artisan::command('inspire', function () {
$this->comment(\Illuminate\Foundation\Inspiring::quote());
})->purpose('Display an inspiring quote');
<?php
use Illuminate\Support\Facades\Route;
/*
|--------------------------------------------------------------------------
| Web Routes
|--------------------------------------------------------------------------
|
| Here is where you can register web routes for your application. These
| routes are loaded by the RouteServiceProvider and all of them will
| be assigned to the "web" middleware group. Make something great!
|
*/
Route::get('/', function () {
return view('index');
});
Route::get('/shop', function () {
return view('shop');
});
Route::get('/product-detail', function () {
return view('product-detail');
});
Route::get('/cart', function () {
return view('cart');
});
Route::get('/checkout', function () {
return view('checkout');
});
Route::get('/gallery', function () {
return view('gallery');
});
Route::get('/catalog', function () {
return view('catalog');
});
Route::get('/admin', function () {
return view('admin');
});
# Keep this directory
This diff is collapsed. Click to expand it.
Markdown is supported
0% or
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment