ngerjain eccomerce

This commit is contained in:
rijalhabibullah 2026-05-09 02:28:41 +07:00
parent bd1112cf1a
commit 633113dce4
12 changed files with 517 additions and 132 deletions

View File

@ -4,7 +4,8 @@
<application
android:label="padi_app"
android:name="${applicationName}"
android:icon="@mipmap/ic_launcher">
android:icon="@mipmap/ic_launcher"
android:usesCleartextTraffic="true">
<activity
android:name=".MainActivity"
android:exported="true"

View File

@ -1,5 +1,6 @@
import 'package:flutter/material.dart';
import 'package:url_launcher/url_launcher.dart';
import '../services/product_service.dart';
class EcommerceScreen extends StatefulWidget {
const EcommerceScreen({super.key});
@ -10,6 +11,65 @@ class EcommerceScreen extends StatefulWidget {
class _EcommerceScreenState extends State<EcommerceScreen> {
final TextEditingController _searchController = TextEditingController();
final ProductService _productService = ProductService();
List<ProductItem> _products = [];
List<ProductItem> _filteredProducts = [];
bool _isLoading = true;
String? _errorMessage;
@override
void initState() {
super.initState();
_loadProducts();
_searchController.addListener(_applySearch);
}
@override
void dispose() {
_searchController.removeListener(_applySearch);
_searchController.dispose();
super.dispose();
}
Future<void> _loadProducts() async {
setState(() {
_isLoading = true;
_errorMessage = null;
});
try {
final products = await _productService.fetchProducts();
setState(() {
_products = products;
_filteredProducts = products;
_isLoading = false;
});
} catch (e) {
setState(() {
_errorMessage = e.toString();
_isLoading = false;
});
}
}
void _applySearch() {
final query = _searchController.text.toLowerCase().trim();
if (query.isEmpty) {
setState(() {
_filteredProducts = _products;
});
return;
}
setState(() {
_filteredProducts = _products.where((product) {
final name = product.name.toLowerCase();
final description = (product.description ?? '').toLowerCase();
return name.contains(query) || description.contains(query);
}).toList();
});
}
// Fungsi untuk membuka link Shopee di browser HP M2102J20SG
Future<void> _bukaLinkShopee(String url) async {
@ -20,74 +80,133 @@ class _EcommerceScreenState extends State<EcommerceScreen> {
}
// Fungsi Pop-up: Di sini baru kita munculkan Deskripsi Lengkap
void _tampilkanPopUpDetail(BuildContext context, Map<String, String> produk) {
void _tampilkanPopUpDetail(BuildContext context, ProductItem produk) {
final priceText = _formatPrice(produk.price);
showDialog(
context: context,
builder: (context) => AlertDialog(
shape: RoundedRectangleBorder(borderRadius: BorderRadius.circular(15)),
content: Column(
mainAxisSize: MainAxisSize.min,
children: [
// Gambar di dalam pop-up (Placeholder Hitam)
Container(
width: double.infinity,
height: 180,
decoration: BoxDecoration(
color: Colors.black,
borderRadius: BorderRadius.circular(10),
),
child: const Center(child: Text("gambar produk", style: TextStyle(color: Colors.white))),
content: SizedBox(
width: 280,
child: ConstrainedBox(
constraints: BoxConstraints(
maxHeight: MediaQuery.of(context).size.height * 0.6,
),
const SizedBox(height: 15),
Text(produk['nama']!, style: const TextStyle(fontWeight: FontWeight.bold, fontSize: 20)),
const SizedBox(height: 5),
Text("Rp ${produk['harga']}", style: const TextStyle(color: Color(0xFF0F703A), fontWeight: FontWeight.bold, fontSize: 18)),
const SizedBox(height: 15),
const Divider(),
const Text("Deskripsi Produk:", style: TextStyle(fontWeight: FontWeight.bold)),
const SizedBox(height: 5),
Text(produk['deskripsi']!, textAlign: TextAlign.center, style: const TextStyle(fontSize: 14)),
],
child: SingleChildScrollView(
child: Column(
mainAxisSize: MainAxisSize.min,
children: [
_buildDialogImage(produk.imageUrl),
const SizedBox(height: 15),
Text(produk.name, style: const TextStyle(fontWeight: FontWeight.bold, fontSize: 20)),
const SizedBox(height: 5),
Text("Rp $priceText", style: const TextStyle(color: Color(0xFF0F703A), fontWeight: FontWeight.bold, fontSize: 18)),
const SizedBox(height: 15),
const Divider(),
const Text("Deskripsi Produk:", style: TextStyle(fontWeight: FontWeight.bold)),
const SizedBox(height: 5),
Text(produk.description ?? '-', textAlign: TextAlign.center, style: const TextStyle(fontSize: 14)),
],
),
),
),
),
actions: [
TextButton(
onPressed: () => Navigator.pop(context),
child: const Text("Tutup", style: TextStyle(color: Color(0xFF0F703A))),
),
ElevatedButton(
onPressed: () => _bukaLinkShopee(produk['link']!),
style: ElevatedButton.styleFrom(backgroundColor: const Color(0xFF0F703A)),
child: const Text("Beli di Shopee", style: TextStyle(color: Colors.white)),
),
if (produk.marketplaceLink != null && produk.marketplaceLink!.trim().isNotEmpty)
ElevatedButton(
onPressed: () => _bukaLinkShopee(produk.marketplaceLink!),
style: ElevatedButton.styleFrom(backgroundColor: const Color(0xFF0F703A)),
child: const Text("Beli di Marketplace", style: TextStyle(color: Colors.white)),
),
],
),
);
}
Widget _buildProductImage(String? imageUrl, {double height = 100, double borderRadius = 12}) {
if (imageUrl == null || imageUrl.trim().isEmpty) {
return Container(
height: height,
width: double.infinity,
decoration: BoxDecoration(
color: Colors.grey,
borderRadius: BorderRadius.vertical(top: Radius.circular(borderRadius)),
),
child: const Center(child: Text("gambar", style: TextStyle(color: Colors.white))),
);
}
return ClipRRect(
borderRadius: BorderRadius.vertical(top: Radius.circular(borderRadius)),
child: Container(
height: height,
width: double.infinity,
color: Colors.grey.shade200,
child: Image.network(
imageUrl,
height: height,
width: double.infinity,
fit: BoxFit.contain,
errorBuilder: (context, error, stackTrace) {
return Container(
height: height,
width: double.infinity,
color: Colors.grey,
child: const Center(child: Text("gambar", style: TextStyle(color: Colors.white))),
);
},
),
),
);
}
Widget _buildDialogImage(String? imageUrl) {
const double height = 180;
const double width = 280;
const double radius = 10;
if (imageUrl == null || imageUrl.trim().isEmpty) {
return Container(
height: height,
width: width,
decoration: BoxDecoration(
color: Colors.grey,
borderRadius: BorderRadius.circular(radius),
),
child: const Center(child: Text("gambar", style: TextStyle(color: Colors.white))),
);
}
return ClipRRect(
borderRadius: BorderRadius.circular(radius),
child: Container(
height: height,
width: width,
color: Colors.grey.shade200,
child: Image.network(
imageUrl,
height: height,
width: width,
fit: BoxFit.contain,
errorBuilder: (context, error, stackTrace) {
return Container(
height: height,
width: width,
color: Colors.grey,
child: const Center(child: Text("gambar", style: TextStyle(color: Colors.white))),
);
},
),
),
);
}
@override
Widget build(BuildContext context) {
// Data Dummy (Nanti diganti data dari MySQL db_rice)
final List<Map<String, String>> listProduk = [
{
"nama": "Pupuk Urea",
"harga": "75.000",
"deskripsi": "Pupuk urea berkualitas tinggi untuk mempercepat pertumbuhan daun dan batang padi agar lebih hijau dan kuat.",
"link": "https://shopee.co.id"
},
{
"nama": "Benih Inpari 32",
"harga": "120.000",
"deskripsi": "Benih padi varietas unggul yang tahan terhadap hawar daun bakteri dan memiliki potensi hasil yang sangat tinggi.",
"link": "https://shopee.co.id"
},
{
"nama": "Pestisida Cair",
"harga": "45.000",
"deskripsi": "Cairan pembasmi hama wereng dan ulat grayak yang efektif melindungi tanaman padi dari serangan penyakit.",
"link": "https://shopee.co.id"
},
];
return Scaffold(
backgroundColor: Colors.grey[100],
appBar: AppBar(
@ -126,67 +245,111 @@ class _EcommerceScreenState extends State<EcommerceScreen> {
// 2. Grid Produk: Nama & Harga saja - BACKROUND.png
Expanded(
child: GridView.builder(
padding: const EdgeInsets.symmetric(horizontal: 16),
gridDelegate: const SliverGridDelegateWithFixedCrossAxisCount(
crossAxisCount: 2, // 2 kolom agar lebih rapi di HP
crossAxisSpacing: 12,
mainAxisSpacing: 12,
childAspectRatio: 0.75,
),
itemCount: listProduk.length,
itemBuilder: (context, index) {
final produk = listProduk[index];
return Card(
elevation: 3,
shape: RoundedRectangleBorder(borderRadius: BorderRadius.circular(12)),
child: Column(
children: [
// Bagian Gambar
Container(
height: 100,
width: double.infinity,
decoration: const BoxDecoration(
color: Colors.grey,
borderRadius: BorderRadius.vertical(top: Radius.circular(12)),
),
child: const Center(child: Text("gambar", style: TextStyle(color: Colors.white))),
),
// Bagian Nama & Harga
Padding(
padding: const EdgeInsets.all(10.0),
child: Column(
children: [
Text(produk['nama']!, style: const TextStyle(fontWeight: FontWeight.bold, fontSize: 14)),
const SizedBox(height: 4),
Text("Rp ${produk['harga']}", style: const TextStyle(color: Color(0xFF0F703A), fontWeight: FontWeight.bold)),
const SizedBox(height: 10),
// Tombol Lihat Detail (Akan munculkan Deskripsi)
SizedBox(
width: double.infinity,
height: 35,
child: ElevatedButton(
style: ElevatedButton.styleFrom(
backgroundColor: const Color(0xFF0F703A),
foregroundColor: Colors.white,
shape: RoundedRectangleBorder(borderRadius: BorderRadius.circular(8)),
),
onPressed: () => _tampilkanPopUpDetail(context, produk),
child: const Text("Lihat Detail", style: TextStyle(fontSize: 12, fontWeight: FontWeight.w600)),
),
),
],
),
),
],
),
);
},
),
child: _buildProductGrid(),
),
],
),
),
);
}
Widget _buildProductGrid() {
if (_isLoading) {
return const Center(child: CircularProgressIndicator());
}
if (_errorMessage != null) {
return Center(
child: Padding(
padding: const EdgeInsets.symmetric(horizontal: 16),
child: Column(
mainAxisSize: MainAxisSize.min,
children: [
Text(_errorMessage!, textAlign: TextAlign.center),
const SizedBox(height: 12),
ElevatedButton(
onPressed: _loadProducts,
style: ElevatedButton.styleFrom(backgroundColor: const Color(0xFF0F703A)),
child: const Text('Coba Lagi', style: TextStyle(color: Colors.white)),
),
],
),
),
);
}
if (_filteredProducts.isEmpty) {
return const Center(child: Text('Produk belum tersedia.'));
}
return GridView.builder(
padding: const EdgeInsets.symmetric(horizontal: 16),
gridDelegate: const SliverGridDelegateWithFixedCrossAxisCount(
crossAxisCount: 2,
crossAxisSpacing: 12,
mainAxisSpacing: 12,
childAspectRatio: 0.68,
),
itemCount: _filteredProducts.length,
itemBuilder: (context, index) {
final produk = _filteredProducts[index];
final priceText = _formatPrice(produk.price);
return Card(
elevation: 3,
shape: RoundedRectangleBorder(borderRadius: BorderRadius.circular(12)),
child: Column(
children: [
_buildProductImage(produk.imageUrl, height: 120),
Expanded(
child: Padding(
padding: const EdgeInsets.all(10.0),
child: Column(
children: [
Text(
produk.name,
maxLines: 2,
overflow: TextOverflow.ellipsis,
textAlign: TextAlign.center,
style: const TextStyle(fontWeight: FontWeight.bold, fontSize: 14),
),
const SizedBox(height: 4),
Text("Rp $priceText", style: const TextStyle(color: Color(0xFF0F703A), fontWeight: FontWeight.bold)),
const Spacer(),
SizedBox(
width: double.infinity,
height: 35,
child: ElevatedButton(
style: ElevatedButton.styleFrom(
backgroundColor: const Color(0xFF0F703A),
foregroundColor: Colors.white,
shape: RoundedRectangleBorder(borderRadius: BorderRadius.circular(8)),
),
onPressed: () => _tampilkanPopUpDetail(context, produk),
child: const Text("Lihat Detail", style: TextStyle(fontSize: 12, fontWeight: FontWeight.w600)),
),
),
],
),
),
),
],
),
);
},
);
}
String _formatPrice(double price) {
final value = price.round();
final raw = value.toString();
final buffer = StringBuffer();
for (int i = 0; i < raw.length; i++) {
final position = raw.length - i;
buffer.write(raw[i]);
if (position > 1 && position % 3 == 1) {
buffer.write('.');
}
}
return buffer.toString();
}
}

View File

@ -10,7 +10,7 @@ class ClassificationService {
// Device Fisik (WiFi): http://192.168.x.x:8000/api/classification (ganti dengan IP komputer Anda)
// Testing Lokal: http://127.0.0.1:8000/api/classification
// Production (ngrok): https://gobony-wedgy-cathi.ngrok-free.dev/api/classification
static const String _apiRoot = 'https://gobony-wedgy-cathi.ngrok-free.dev/api';
static const String _apiRoot = 'http://192.168.18.23:8000/api';
static const String _baseUrl = '$_apiRoot/classification';
static const String _historyUrl = '$_apiRoot/classifications';

View File

@ -0,0 +1,80 @@
import 'dart:convert';
import 'dart:async';
import 'package:http/http.dart' as http;
class ProductItem {
final int id;
final String name;
final String? description;
final double price;
final String? imageUrl;
final String? marketplaceLink;
ProductItem({
required this.id,
required this.name,
required this.price,
this.description,
this.imageUrl,
this.marketplaceLink,
});
factory ProductItem.fromJson(Map<String, dynamic> json) {
final dynamic rawPrice = json['price'];
double priceValue = 0.0;
if (rawPrice is num) {
priceValue = rawPrice.toDouble();
} else if (rawPrice is String) {
priceValue = double.tryParse(rawPrice) ?? 0.0;
}
return ProductItem(
id: json['id'] ?? 0,
name: json['name'] ?? '',
description: json['description'],
price: priceValue,
imageUrl: json['image_url'],
marketplaceLink: json['marketplace_link'],
);
}
}
class ProductService {
// Samakan dengan API root di classification_service.dart
static const String _apiRoot = 'http://192.168.18.23:8000/api';
static const String _productsUrl = '$_apiRoot/products';
final http.Client _httpClient;
ProductService({http.Client? httpClient}) : _httpClient = httpClient ?? http.Client();
Future<List<ProductItem>> fetchProducts() async {
try {
final response = await _httpClient
.get(Uri.parse(_productsUrl), headers: {'Accept': 'application/json'})
.timeout(const Duration(seconds: 15));
if (response.statusCode != 200) {
throw Exception('Gagal mengambil produk');
}
final jsonResponse = jsonDecode(response.body);
if (jsonResponse is! Map || jsonResponse['success'] != true) {
throw Exception(jsonResponse['message'] ?? 'Gagal mengambil produk');
}
final data = jsonResponse['data'];
if (data is! List) {
return [];
}
return data
.map((item) => ProductItem.fromJson(Map<String, dynamic>.from(item)))
.toList();
} on TimeoutException catch (e) {
throw Exception(e.message);
} catch (e) {
throw Exception('Error: $e');
}
}
}

View File

@ -15,8 +15,8 @@ public function store(Request $request) {
$request->validate([
'name' => 'required',
'price' => 'required|numeric',
'stock' => 'required|integer',
'image' => 'image|mimes:jpeg,png,jpg|max:2048'
'image' => 'image|mimes:jpeg,png,jpg|max:2048',
'marketplace_link' => 'required|url|max:2048'
]);
$imagePath = null;
@ -28,8 +28,8 @@ public function store(Request $request) {
'name' => $request->name,
'description' => $request->description,
'price' => $request->price,
'stock' => $request->stock,
'image' => $imagePath
'image' => $imagePath,
'marketplace_link' => $request->marketplace_link
]);
return back()->with('success', 'Produk berhasil ditambahkan!');
@ -41,4 +41,24 @@ public function destroy($id) {
$product->delete();
return back()->with('success', 'Produk dihapus!');
}
public function apiIndex(Request $request) {
$products = Product::all()->map(function ($product) {
$imageUrl = $product->image ? url(Storage::url($product->image)) : null;
return [
'id' => $product->id,
'name' => $product->name,
'description' => $product->description,
'price' => $product->price,
'image_url' => $imageUrl,
'marketplace_link' => $product->marketplace_link,
];
});
return response()->json([
'success' => true,
'data' => $products,
]);
}
}

View File

@ -14,7 +14,7 @@ class Product extends Model
'name',
'description',
'price',
'stock',
'image'
'image',
'marketplace_link'
];
}

View File

@ -0,0 +1,28 @@
<?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::table('products', function (Blueprint $table) {
$table->string('marketplace_link')->nullable()->after('image');
});
}
/**
* Reverse the migrations.
*/
public function down(): void
{
Schema::table('products', function (Blueprint $table) {
$table->dropColumn('marketplace_link');
});
}
};

View File

@ -0,0 +1,28 @@
<?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::table('products', function (Blueprint $table) {
$table->dropColumn('stock');
});
}
/**
* Reverse the migrations.
*/
public function down(): void
{
Schema::table('products', function (Blueprint $table) {
$table->integer('stock')->default(0)->after('price');
});
}
};

View File

@ -0,0 +1,29 @@
<?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::table('products', function (Blueprint $table) {
$table->id()->first();
$table->timestamps();
});
}
/**
* Reverse the migrations.
*/
public function down(): void
{
Schema::table('products', function (Blueprint $table) {
$table->dropColumn(['id', 'created_at', 'updated_at']);
});
}
};

View File

@ -0,0 +1,28 @@
<?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::table('products', function (Blueprint $table) {
$table->text('marketplace_link')->nullable()->change();
});
}
/**
* Reverse the migrations.
*/
public function down(): void
{
Schema::table('products', function (Blueprint $table) {
$table->string('marketplace_link')->nullable()->change();
});
}
};

View File

@ -9,6 +9,16 @@
</div>
@endif
@if($errors->any())
<div class="bg-red-100 border border-red-400 text-red-700 px-4 py-3 rounded mb-4">
<ul class="list-disc list-inside">
@foreach($errors->all() as $error)
<li>{{ $error }}</li>
@endforeach
</ul>
</div>
@endif
<div class="flex flex-col lg:flex-row gap-8">
<div class="w-full lg:w-1/3">
@ -18,28 +28,28 @@
@csrf
<div class="mb-4">
<label class="block text-sm font-medium text-gray-700 mb-1">Nama Produk</label>
<input type="text" name="name" class="w-full border-gray-300 rounded-lg shadow-sm focus:ring-emerald-500 focus:border-emerald-500 p-2 border" placeholder="Contoh: Urea" required>
<input type="text" name="name" value="{{ old('name') }}" class="w-full border-gray-300 rounded-lg shadow-sm focus:ring-emerald-500 focus:border-emerald-500 p-2 border" placeholder="Contoh: Urea" required>
</div>
<div class="grid grid-cols-2 gap-4 mb-4">
<div>
<label class="block text-sm font-medium text-gray-700 mb-1">Harga (Rp)</label>
<input type="number" name="price" class="w-full border-gray-300 rounded-lg shadow-sm p-2 border" required>
</div>
<div>
<label class="block text-sm font-medium text-gray-700 mb-1">Stok</label>
<input type="number" name="stock" class="w-full border-gray-300 rounded-lg shadow-sm p-2 border" required>
</div>
<div class="mb-4">
<label class="block text-sm font-medium text-gray-700 mb-1">Harga (Rp)</label>
<input type="number" name="price" value="{{ old('price') }}" class="w-full border-gray-300 rounded-lg shadow-sm p-2 border" required>
</div>
<div class="mb-4">
<label class="block text-sm font-medium text-gray-700 mb-1">Deskripsi</label>
<textarea name="description" rows="3" class="w-full border-gray-300 rounded-lg shadow-sm p-2 border"></textarea>
<textarea name="description" rows="3" class="w-full border-gray-300 rounded-lg shadow-sm p-2 border">{{ old('description') }}</textarea>
</div>
<div class="mb-4">
<label class="block text-sm font-medium text-gray-700 mb-1">Link Marketplace</label>
<input type="url" name="marketplace_link" value="{{ old('marketplace_link') }}" class="w-full border-gray-300 rounded-lg shadow-sm p-2 border" placeholder="https://shopee.co.id/..." required>
</div>
<div class="mb-4">
<label class="block text-sm font-medium text-gray-700 mb-1">Foto Produk</label>
<input type="file" name="image" class="block w-full text-sm text-gray-500 file:mr-4 file:py-2 file:px-4 file:rounded-full file:border-0 file:text-sm file:font-semibold file:bg-emerald-50 file:text-emerald-700 hover:file:bg-emerald-100">
<p class="text-xs text-gray-500 mt-1">Maksimal 2 MB (jpg/png).</p>
</div>
<button type="submit" class="w-full bg-emerald-600 hover:bg-emerald-700 text-white font-bold py-2 rounded-lg transition">Simpan Produk</button>
@ -54,7 +64,6 @@
<tr>
<th class="px-6 py-3 text-left text-xs font-medium text-gray-500 uppercase tracking-wider">Info Produk</th>
<th class="px-6 py-3 text-left text-xs font-medium text-gray-500 uppercase tracking-wider">Harga</th>
<th class="px-6 py-3 text-left text-xs font-medium text-gray-500 uppercase tracking-wider">Stok</th>
<th class="px-6 py-3 text-right text-xs font-medium text-gray-500 uppercase tracking-wider">Aksi</th>
</tr>
</thead>
@ -76,11 +85,6 @@
</div>
</td>
<td class="px-6 py-4 whitespace-nowrap text-sm text-gray-500">Rp {{ number_format($product->price) }}</td>
<td class="px-6 py-4 whitespace-nowrap">
<span class="px-2 inline-flex text-xs leading-5 font-semibold rounded-full {{ $product->stock < 5 ? 'bg-red-100 text-red-800' : 'bg-green-100 text-green-800' }}">
{{ $product->stock }} Unit
</span>
</td>
<td class="px-6 py-4 whitespace-nowrap text-right text-sm font-medium">
<form action="{{ route('produk.destroy', $product->id) }}" method="POST" onsubmit="return confirm('Yakin hapus?')">
@csrf @method('DELETE')

View File

@ -4,6 +4,7 @@
use App\Http\Controllers\AuthController;
use App\Http\Controllers\ClassificationController;
use App\Http\Controllers\ClassificationHistoryController;
use App\Http\Controllers\ProductController;
/*
|--------------------------------------------------------------------------
@ -51,3 +52,6 @@
Route::get('/stats/summary', [ClassificationHistoryController::class, 'stats']);
});
// Products endpoint for mobile
Route::get('/products', [ProductController::class, 'apiIndex']);