first commit

This commit is contained in:
Baghaztra 2025-08-27 16:32:02 +07:00
commit f4e9352d28
108 changed files with 18055 additions and 0 deletions

18
.editorconfig Normal file
View File

@ -0,0 +1,18 @@
root = true
[*]
charset = utf-8
end_of_line = lf
indent_size = 4
indent_style = space
insert_final_newline = true
trim_trailing_whitespace = true
[*.md]
trim_trailing_whitespace = false
[*.{yml,yaml}]
indent_size = 2
[docker-compose.yml]
indent_size = 4

65
.env.example Normal file
View File

@ -0,0 +1,65 @@
APP_NAME=Laravel
APP_ENV=local
APP_KEY=
APP_DEBUG=true
APP_URL=http://localhost
APP_LOCALE=en
APP_FALLBACK_LOCALE=en
APP_FAKER_LOCALE=en_US
APP_MAINTENANCE_DRIVER=file
# APP_MAINTENANCE_STORE=database
PHP_CLI_SERVER_WORKERS=4
BCRYPT_ROUNDS=12
LOG_CHANNEL=stack
LOG_STACK=single
LOG_DEPRECATIONS_CHANNEL=null
LOG_LEVEL=debug
DB_CONNECTION=sqlite
# DB_HOST=127.0.0.1
# DB_PORT=3306
# DB_DATABASE=laravel
# DB_USERNAME=root
# DB_PASSWORD=
SESSION_DRIVER=database
SESSION_LIFETIME=120
SESSION_ENCRYPT=false
SESSION_PATH=/
SESSION_DOMAIN=null
BROADCAST_CONNECTION=log
FILESYSTEM_DISK=local
QUEUE_CONNECTION=database
CACHE_STORE=database
# CACHE_PREFIX=
MEMCACHED_HOST=127.0.0.1
REDIS_CLIENT=phpredis
REDIS_HOST=127.0.0.1
REDIS_PASSWORD=null
REDIS_PORT=6379
MAIL_MAILER=log
MAIL_SCHEME=null
MAIL_HOST=127.0.0.1
MAIL_PORT=2525
MAIL_USERNAME=null
MAIL_PASSWORD=null
MAIL_FROM_ADDRESS="hello@example.com"
MAIL_FROM_NAME="${APP_NAME}"
AWS_ACCESS_KEY_ID=
AWS_SECRET_ACCESS_KEY=
AWS_DEFAULT_REGION=us-east-1
AWS_BUCKET=
AWS_USE_PATH_STYLE_ENDPOINT=false
VITE_APP_NAME="${APP_NAME}"

11
.gitattributes vendored Normal file
View File

@ -0,0 +1,11 @@
* text=auto eol=lf
*.blade.php diff=html
*.css diff=css
*.html diff=html
*.md diff=markdown
*.php diff=php
/.github export-ignore
CHANGELOG.md export-ignore
.styleci.yml export-ignore

24
.gitignore vendored Normal file
View File

@ -0,0 +1,24 @@
*.log
.DS_Store
.env
.env.backup
.env.production
.phpactor.json
.phpunit.result.cache
/.fleet
/.idea
/.nova
/.phpunit.cache
/.vscode
/.zed
/auth.json
/node_modules
/public/build
/public/hot
/public/storage
/storage/*.key
/storage/pail
/vendor
Homestead.json
Homestead.yaml
Thumbs.db

630
DOC-BACKEND.md Normal file
View File

@ -0,0 +1,630 @@
# Laravel + Vue.js Monolith Backend Concepts
## Arsitektur Overview
```
┌────────────────────────────────────────────────────────────┐
│ LARAVEL MONOLITH │
├────────────────────────────────────────────────────────────┤
│ Frontend (SPA) │ Backend (API + Web) │
│ ───────────────── │ ────────────────── │
│ • Vue.js Components │ • Controllers │
│ • Vue Router │ • Models │
│ • Axios/HTTP Client │ • Migrations │
│ • State Management │ • Services │
│ │ • Jobs/Queues │
│ │ • Middleware │
└────────────────────────────────────────────────────────────┘
```
## 1. Hybrid Approach (Recommended)
### Konsep
Kombinasi antara SPA (Vue.js) untuk user interface dan Laravel API untuk data handling.
### Routes Structure
```php
// routes/web.php
<?php
use Illuminate\Support\Facades\Route;
// API Routes untuk Vue.js
Route::prefix('api')->middleware('api')->group(function () {
Route::get('/dashboard', [DashboardController::class, 'index']);
Route::apiResource('posts', PostController::class);
Route::apiResource('users', UserController::class);
});
// Blade Routes (jika diperlukan)
Route::get('/admin', function () {
return view('admin.dashboard'); // Traditional Blade view
});
// SPA Catch-all (harus paling bawah)
Route::get('/{any}', function () {
return view('spa'); // Vue.js SPA
})->where('any', '^(?!api|admin).*$'); // Exclude api & admin routes
```
### Controller Example
```php
<?php
namespace App\Http\Controllers\Api;
use App\Http\Controllers\Controller;
use App\Models\Post;
use Illuminate\Http\Request;
use Illuminate\Http\JsonResponse;
class PostController extends Controller
{
public function index(): JsonResponse
{
$posts = Post::with('author')
->latest()
->paginate(10);
return response()->json($posts);
}
public function store(Request $request): JsonResponse
{
$request->validate([
'title' => 'required|max:255',
'content' => 'required',
]);
$post = Post::create([
'title' => $request->title,
'content' => $request->content,
'user_id' => auth()->id(),
]);
return response()->json($post->load('author'), 201);
}
public function show(Post $post): JsonResponse
{
return response()->json($post->load('author'));
}
public function update(Request $request, Post $post): JsonResponse
{
$request->validate([
'title' => 'required|max:255',
'content' => 'required',
]);
$post->update($request->only(['title', 'content']));
return response()->json($post->load('author'));
}
public function destroy(Post $post): JsonResponse
{
$post->delete();
return response()->json(['message' => 'Post deleted successfully']);
}
}
```
## 2. Frontend Integration
### Axios Setup
```javascript
// resources/js/services/api.js
import axios from 'axios'
const api = axios.create({
baseURL: '/api',
headers: {
'Content-Type': 'application/json',
'Accept': 'application/json',
}
})
// Add CSRF token for Laravel
const token = document.head.querySelector('meta[name="csrf-token"]')
if (token) {
api.defaults.headers.common['X-CSRF-TOKEN'] = token.content
}
// Request interceptor
api.interceptors.request.use((config) => {
const auth = localStorage.getItem('auth_token')
if (auth) {
config.headers.Authorization = `Bearer ${auth}`
}
return config
})
// Response interceptor
api.interceptors.response.use(
(response) => response,
(error) => {
if (error.response?.status === 401) {
// Handle unauthorized
localStorage.removeItem('auth_token')
window.location.href = '/login'
}
return Promise.reject(error)
}
)
export default api
```
### Vue Service Example
```javascript
// resources/js/services/postService.js
import api from './api'
export const postService = {
// Get all posts
async getPosts(page = 1) {
const response = await api.get(`/posts?page=${page}`)
return response.data
},
// Get single post
async getPost(id) {
const response = await api.get(`/posts/${id}`)
return response.data
},
// Create post
async createPost(postData) {
const response = await api.post('/posts', postData)
return response.data
},
// Update post
async updatePost(id, postData) {
const response = await api.put(`/posts/${id}`, postData)
return response.data
},
// Delete post
async deletePost(id) {
const response = await api.delete(`/posts/${id}`)
return response.data
}
}
```
### Vue Component with API Integration
```vue
<!-- resources/js/pages/Posts.vue -->
<template>
<div class="posts">
<div class="flex justify-between items-center mb-6">
<h1 class="text-3xl font-bold">Posts</h1>
<button
@click="showCreateForm = true"
class="bg-blue-500 text-white px-4 py-2 rounded hover:bg-blue-600"
>
Create Post
</button>
</div>
<!-- Loading State -->
<div v-if="loading" class="text-center py-8">
Loading posts...
</div>
<!-- Posts List -->
<div v-else class="grid gap-4">
<div
v-for="post in posts"
:key="post.id"
class="bg-white p-6 rounded-lg shadow"
>
<h3 class="text-xl font-semibold mb-2">{{ post.title }}</h3>
<p class="text-gray-600 mb-4">{{ post.content }}</p>
<div class="flex justify-between items-center">
<span class="text-sm text-gray-500">
By {{ post.author.name }}
</span>
<div class="space-x-2">
<button
@click="editPost(post)"
class="text-blue-500 hover:text-blue-700"
>
Edit
</button>
<button
@click="deletePost(post.id)"
class="text-red-500 hover:text-red-700"
>
Delete
</button>
</div>
</div>
</div>
</div>
<!-- Pagination -->
<div v-if="pagination.last_page > 1" class="mt-6 flex justify-center">
<nav class="flex space-x-2">
<button
v-for="page in pagination.last_page"
:key="page"
@click="loadPosts(page)"
:class="[
'px-3 py-2 rounded',
page === pagination.current_page
? 'bg-blue-500 text-white'
: 'bg-gray-200 hover:bg-gray-300'
]"
>
{{ page }}
</button>
</nav>
</div>
<!-- Create/Edit Modal -->
<div v-if="showCreateForm" class="fixed inset-0 bg-black bg-opacity-50 flex items-center justify-center">
<div class="bg-white p-6 rounded-lg w-full max-w-md">
<h2 class="text-xl font-bold mb-4">
{{ editingPost ? 'Edit Post' : 'Create Post' }}
</h2>
<form @submit.prevent="submitForm">
<div class="mb-4">
<label class="block text-sm font-medium mb-2">Title</label>
<input
v-model="form.title"
type="text"
class="w-full border rounded px-3 py-2"
required
>
</div>
<div class="mb-4">
<label class="block text-sm font-medium mb-2">Content</label>
<textarea
v-model="form.content"
class="w-full border rounded px-3 py-2 h-32"
required
></textarea>
</div>
<div class="flex justify-end space-x-2">
<button
type="button"
@click="cancelForm"
class="bg-gray-500 text-white px-4 py-2 rounded hover:bg-gray-600"
>
Cancel
</button>
<button
type="submit"
class="bg-blue-500 text-white px-4 py-2 rounded hover:bg-blue-600"
>
{{ editingPost ? 'Update' : 'Create' }}
</button>
</div>
</form>
</div>
</div>
</div>
</template>
<script setup>
import { ref, reactive, onMounted } from 'vue'
import { postService } from '../services/postService'
const posts = ref([])
const loading = ref(false)
const showCreateForm = ref(false)
const editingPost = ref(null)
const pagination = ref({})
const form = reactive({
title: '',
content: ''
})
const loadPosts = async (page = 1) => {
loading.value = true
try {
const data = await postService.getPosts(page)
posts.value = data.data
pagination.value = {
current_page: data.current_page,
last_page: data.last_page,
total: data.total
}
} catch (error) {
console.error('Error loading posts:', error)
} finally {
loading.value = false
}
}
const submitForm = async () => {
try {
if (editingPost.value) {
await postService.updatePost(editingPost.value.id, form)
} else {
await postService.createPost(form)
}
cancelForm()
loadPosts()
} catch (error) {
console.error('Error submitting form:', error)
}
}
const editPost = (post) => {
editingPost.value = post
form.title = post.title
form.content = post.content
showCreateForm.value = true
}
const deletePost = async (id) => {
if (confirm('Are you sure?')) {
try {
await postService.deletePost(id)
loadPosts()
} catch (error) {
console.error('Error deleting post:', error)
}
}
}
const cancelForm = () => {
showCreateForm.value = false
editingPost.value = null
form.title = ''
form.content = ''
}
onMounted(() => {
loadPosts()
})
</script>
```
## 3. Authentication Integration
### Laravel Sanctum Setup
```bash
# Install Sanctum
composer require laravel/sanctum
php artisan vendor:publish --provider="Laravel\Sanctum\SanctumServiceProvider"
php artisan migrate
```
### Auth Controller
```php
<?php
namespace App\Http\Controllers\Api;
use App\Http\Controllers\Controller;
use App\Models\User;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Auth;
use Illuminate\Support\Facades\Hash;
use Illuminate\Validation\ValidationException;
class AuthController extends Controller
{
public function login(Request $request)
{
$request->validate([
'email' => 'required|email',
'password' => 'required',
]);
$user = User::where('email', $request->email)->first();
if (!$user || !Hash::check($request->password, $user->password)) {
throw ValidationException::withMessages([
'email' => ['The provided credentials are incorrect.'],
]);
}
$token = $user->createToken('auth_token')->plainTextToken;
return response()->json([
'user' => $user,
'token' => $token,
]);
}
public function logout(Request $request)
{
$request->user()->currentAccessToken()->delete();
return response()->json(['message' => 'Logged out successfully']);
}
public function me(Request $request)
{
return response()->json($request->user());
}
}
```
## 4. Database Structure
### Migration Example
```php
<?php
use Illuminate\Database\Migrations\Migration;
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Support\Facades\Schema;
return new class extends Migration
{
public function up()
{
Schema::create('posts', function (Blueprint $table) {
$table->id();
$table->string('title');
$table->text('content');
$table->string('slug')->unique();
$table->foreignId('user_id')->constrained()->onDelete('cascade');
$table->boolean('published')->default(false);
$table->timestamp('published_at')->nullable();
$table->timestamps();
$table->index(['published', 'published_at']);
});
}
public function down()
{
Schema::dropIfExists('posts');
}
};
```
### Model with Relationships
```php
<?php
namespace App\Models;
use Illuminate\Database\Eloquent\Factories\HasFactory;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Database\Eloquent\Relations\BelongsTo;
class Post extends Model
{
use HasFactory;
protected $fillable = [
'title',
'content',
'slug',
'user_id',
'published',
'published_at',
];
protected $casts = [
'published' => 'boolean',
'published_at' => 'datetime',
];
public function author(): BelongsTo
{
return $this->belongsTo(User::class, 'user_id');
}
public function getRouteKeyName()
{
return 'slug';
}
}
```
## 5. Service Layer Pattern
### Service Class
```php
<?php
namespace App\Services;
use App\Models\Post;
use Illuminate\Pagination\LengthAwarePaginator;
use Illuminate\Support\Str;
class PostService
{
public function getAllPosts(int $perPage = 10): LengthAwarePaginator
{
return Post::with('author')
->where('published', true)
->latest('published_at')
->paginate($perPage);
}
public function createPost(array $data): Post
{
$data['slug'] = Str::slug($data['title']);
$data['user_id'] = auth()->id();
return Post::create($data);
}
public function updatePost(Post $post, array $data): Post
{
if (isset($data['title'])) {
$data['slug'] = Str::slug($data['title']);
}
$post->update($data);
return $post->fresh();
}
public function deletePost(Post $post): bool
{
return $post->delete();
}
}
```
## 6. Middleware untuk API
### Custom API Middleware
```php
<?php
namespace App\Http\Middleware;
use Closure;
use Illuminate\Http\Request;
class ApiResponse
{
public function handle(Request $request, Closure $next)
{
$response = $next($request);
// Add consistent API response format
if ($request->expectsJson()) {
$data = $response->getData();
return response()->json([
'success' => $response->status() < 400,
'data' => $data,
'message' => $response->status() < 400 ? 'Success' : 'Error',
'status_code' => $response->status(),
], $response->status());
}
return $response;
}
}
```
## Key Benefits Monolith
**Single Deployment** - Satu aplikasi, satu deploy
**Shared Authentication** - Session/token bersama
**Database Consistency** - Satu database, konsisten
**Easier Development** - Setup dan maintenance lebih mudah
**Performance** - Tidak ada network latency antar service
**CSRF Protection** - Built-in Laravel CSRF
**File Sharing** - Storage dan assets bersama
## Best Practices
1. **API Versioning** - Gunakan `/api/v1/` prefix
2. **Resource Controllers** - Gunakan `apiResource()` untuk CRUD
3. **Service Layer** - Pisahkan business logic dari controller
4. **Validation** - Gunakan Form Requests untuk validasi complex
5. **Caching** - Implement caching untuk data yang sering diakses
6. **Queue Jobs** - Untuk operasi yang memakan waktu
7. **Event/Listeners** - Untuk decoupling business logic
Konsep ini memberikan fleksibilitas tinggi dengan maintenance yang relatif mudah!

470
DOC-FRONTEND.md Normal file
View File

@ -0,0 +1,470 @@
# Laravel + Vue.js + Vue Router Setup Guide
Panduan lengkap untuk setup Laravel dengan Vue.js 3, Vue Router, dan Tailwind CSS menggunakan Vite.
## Prerequisites
- PHP >= 8.1
- Composer
- Node.js >= 16.x
- NPM atau Yarn
## Step 1: Instalasi Laravel
```bash
# Buat project Laravel baru
composer create-project laravel/laravel project-name
# Masuk ke directory project
cd project-name
# Setup environment
cp .env.example .env
php artisan key:generate
```
## Step 2: Instalasi Dependencies Frontend
```bash
# Install Vue.js dan dependencies
npm install vue@latest vue-router@latest
# Install Vite plugins
npm install --save-dev @vitejs/plugin-vue
# Install Tailwind CSS
npm install --save-dev tailwindcss@latest @tailwindcss/vite
# Install utilities
npm install --save-dev axios concurrently
```
### Package.json Final
```json
{
"$schema": "https://json.schemastore.org/package.json",
"private": true,
"type": "module",
"scripts": {
"build": "vite build",
"dev": "vite"
},
"devDependencies": {
"@tailwindcss/vite": "^4.0.0",
"@vitejs/plugin-vue": "^6.0.1",
"axios": "^1.11.0",
"concurrently": "^9.0.1",
"laravel-vite-plugin": "^2.0.0",
"tailwindcss": "^4.0.0",
"vite": "^7.0.4"
},
"dependencies": {
"vue": "^3.5.19",
"vue-router": "^4.5.1"
}
}
```
## Step 3: Konfigurasi Vite
Buat/update `vite.config.js`:
```javascript
import { defineConfig } from "vite";
import laravel from "laravel-vite-plugin";
import tailwindcss from "@tailwindcss/vite";
import vue from '@vitejs/plugin-vue';
export default defineConfig({
plugins: [
laravel({
input: ["resources/css/app.css", "resources/js/app.js"],
refresh: true,
}),
tailwindcss(),
vue()
],
resolve: {
alias: {
vue: 'vue/dist/vue.esm-bundler.js',
},
},
});
```
## Step 4: Setup Tailwind CSS
Buat `tailwind.config.js`:
```javascript
/** @type {import('tailwindcss').Config} */
export default {
content: [
"./resources/**/*.blade.php",
"./resources/**/*.js",
"./resources/**/*.vue",
],
theme: {
extend: {},
},
plugins: [],
}
```
Update `resources/css/app.css`:
```css
@import 'tailwindcss';
```
## Step 5: Struktur Folder Frontend
Buat struktur folder berikut di `resources/js/`:
```
resources/js/
├── components/
│ └── App.vue
├── pages/
│ ├── Home.vue
│ ├── About.vue
│ └── Contact.vue
├── router/
│ └── index.js
└── app.js
```
## Step 6: Setup Vue Router
### `resources/js/router/index.js`
```javascript
import { createRouter, createWebHistory } from 'vue-router'
import Home from '../pages/Home.vue'
import About from '../pages/About.vue'
import Contact from '../pages/Contact.vue'
const routes = [
{
path: '/',
name: 'Home',
component: Home
},
{
path: '/about',
name: 'About',
component: About
},
{
path: '/contact',
name: 'Contact',
component: Contact
}
]
const router = createRouter({
history: createWebHistory(),
routes
})
export default router
```
### `resources/js/app.js`
```javascript
import { createApp } from 'vue';
import router from './router';
import App from './components/App.vue';
const app = createApp(App);
app.use(router);
app.mount('#app');
```
## Step 7: Buat Vue Components
### `resources/js/components/App.vue`
```vue
<template>
<div id="app">
<nav class="bg-blue-600 shadow-lg">
<div class="max-w-7xl mx-auto px-4">
<div class="flex justify-between h-16">
<div class="flex space-x-8">
<router-link
to="/"
class="flex items-center px-3 py-2 text-white hover:text-blue-200"
:class="{ 'border-b-2 border-white': $route.name === 'Home' }"
>
Home
</router-link>
<router-link
to="/about"
class="flex items-center px-3 py-2 text-white hover:text-blue-200"
:class="{ 'border-b-2 border-white': $route.name === 'About' }"
>
About
</router-link>
<router-link
to="/contact"
class="flex items-center px-3 py-2 text-white hover:text-blue-200"
:class="{ 'border-b-2 border-white': $route.name === 'Contact' }"
>
Contact
</router-link>
</div>
</div>
</div>
</nav>
<main class="max-w-7xl mx-auto py-6 px-4">
<router-view />
</main>
</div>
</template>
<script setup>
// Main app component
</script>
```
### `resources/js/pages/Home.vue`
```vue
<template>
<div class="home">
<div class="text-center">
<h1 class="text-4xl font-bold text-gray-800 mb-8">Welcome Home</h1>
<div class="bg-yellow-100 border-2 border-yellow-300 rounded-lg p-8 max-w-md mx-auto">
<p class="text-2xl font-bold text-gray-800">{{ message }}</p>
</div>
</div>
</div>
</template>
<script setup>
import { ref } from 'vue'
const message = ref("Hello from Vue.js!")
</script>
```
### `resources/js/pages/About.vue`
```vue
<template>
<div class="about">
<h1 class="text-3xl font-bold text-gray-800 mb-6">About Us</h1>
<div class="bg-green-50 border border-green-200 rounded-lg p-6">
<p class="text-lg text-gray-700 mb-4">
This is our about page built with Laravel and Vue.js!
</p>
<button
@click="showMore = !showMore"
class="bg-green-500 hover:bg-green-600 text-white font-bold py-2 px-4 rounded transition duration-200"
>
{{ showMore ? 'Show Less' : 'Learn More' }}
</button>
<div v-show="showMore" class="mt-4 p-4 bg-white rounded border">
<p class="text-gray-600">
We're passionate about creating amazing web applications using modern technologies
like Laravel, Vue.js, and Tailwind CSS.
</p>
</div>
</div>
</div>
</template>
<script setup>
import { ref } from 'vue'
const showMore = ref(false)
</script>
```
### `resources/js/pages/Contact.vue`
```vue
<template>
<div class="contact">
<h1 class="text-3xl font-bold text-gray-800 mb-6">Contact Us</h1>
<div class="max-w-md mx-auto bg-white shadow-md rounded-lg p-6">
<form @submit.prevent="submitForm" class="space-y-4">
<div>
<label class="block text-sm font-medium text-gray-700 mb-1">Name</label>
<input
v-model="form.name"
type="text"
class="w-full px-3 py-2 border border-gray-300 rounded-md focus:outline-none focus:ring-2 focus:ring-blue-500"
required
>
</div>
<div>
<label class="block text-sm font-medium text-gray-700 mb-1">Email</label>
<input
v-model="form.email"
type="email"
class="w-full px-3 py-2 border border-gray-300 rounded-md focus:outline-none focus:ring-2 focus:ring-blue-500"
required
>
</div>
<div>
<label class="block text-sm font-medium text-gray-700 mb-1">Message</label>
<textarea
v-model="form.message"
class="w-full px-3 py-2 border border-gray-300 rounded-md focus:outline-none focus:ring-2 focus:ring-blue-500 h-24"
required
></textarea>
</div>
<button
type="submit"
class="w-full bg-blue-500 hover:bg-blue-600 text-white font-bold py-2 px-4 rounded transition duration-200"
>
Send Message
</button>
</form>
<div v-if="submitted" class="mt-4 p-3 bg-green-100 border border-green-300 rounded text-green-700">
✅ Thank you for your message!
</div>
</div>
</div>
</template>
<script setup>
import { ref, reactive } from 'vue'
const form = reactive({
name: '',
email: '',
message: ''
})
const submitted = ref(false)
const submitForm = () => {
console.log('Form submitted:', form)
submitted.value = true
// Reset form after 3 seconds
setTimeout(() => {
submitted.value = false
Object.assign(form, { name: '', email: '', message: '' })
}, 3000)
}
</script>
```
## Step 8: Update Laravel Views
### `resources/views/welcome.blade.php`
```html
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Laravel + Vue.js</title>
@vite(['resources/css/app.css', 'resources/js/app.js'])
</head>
<body class="bg-gray-50">
<div id="app"></div>
</body>
</html>
```
## Step 9: Setup Laravel Routes (SPA)
### `routes/web.php`
```php
<?php
use Illuminate\Support\Facades\Route;
// SPA Route - catch all and return main view
Route::get('/{any}', function () {
return view('welcome');
})->where('any', '.*');
```
## Step 10: Jalankan Development Server
```bash
# Terminal 1 - Laravel server
php artisan serve
# Terminal 2 - Vite dev server
npm run dev
```
Atau gunakan concurrently (jika sudah diinstall):
```bash
# Install concurrently jika belum
npm install --save-dev concurrently
# Tambahkan script di package.json
"scripts": {
"dev": "vite",
"build": "vite build",
"serve": "concurrently \"php artisan serve\" \"vite\""
}
# Jalankan keduanya sekaligus
npm run serve
```
## Struktur Project Final
```
project-name/
├── app/
├── resources/
│ ├── css/
│ │ └── app.css
│ ├── js/
│ │ ├── components/
│ │ │ └── App.vue
│ │ ├── pages/
│ │ │ ├── Home.vue
│ │ │ ├── About.vue
│ │ │ └── Contact.vue
│ │ ├── router/
│ │ │ └── index.js
│ │ └── app.js
│ └── views/
│ └── welcome.blade.php
├── routes/
│ └── web.php
├── package.json
├── vite.config.js
├── tailwind.config.js
└── composer.json
```
## Testing
Buka browser dan kunjungi:
- `http://localhost:8000` - Home page
- `http://localhost:8000/about` - About page
- `http://localhost:8000/contact` - Contact page
## Troubleshooting
### Error: "Component provided template option but runtime compilation is not supported"
- Pastikan `vue` alias sudah ditambahkan di `vite.config.js`
### Error: "Failed to parse source for import analysis"
- Pastikan `@vitejs/plugin-vue` sudah terinstall dan ditambahkan di plugins
### CSS tidak loading
- Pastikan `@vite` directive sudah benar di blade file
- Check jika Tailwind config sudah benar
### Router tidak bekerja
- Pastikan Laravel routes catch-all sudah ditambahkan
- Check browser console untuk error JavaScript
## Next Steps
- Tambahkan authentication
- Implementasikan API endpoints
- Setup state management (Pinia/Vuex)
- Tambahkan testing (Vitest)
- Deploy ke production
Selamat! Anda telah berhasil setup Laravel + Vue.js + Vue Router! 🎉

377
DOC-PRODUK.md Normal file
View File

@ -0,0 +1,377 @@
# API Documentation - Produk & Foto Sementara
## Produk API
### 1. Get All Products
**GET** `/api/produk`
Mendapatkan semua produk dengan jumlah item dan foto.
**Response Success (200):**
```json
[
{
"id": 1,
"nama": "Cincin Berlian",
"kategori": "cincin",
"berat": 2.5,
"kadar": 18,
"harga_per_gram": 850000,
"harga_jual": 2500000,
"created_at": "2025-08-27T10:30:00.000000Z",
"updated_at": "2025-08-27T10:30:00.000000Z",
"deleted_at": null,
"items_count": 5,
"foto": [
{
"id": 1,
"id_produk": 1,
"url": "http://localhost:8000/storage/foto/cincin1.jpg",
"created_at": "2025-08-27T10:30:00.000000Z",
"updated_at": "2025-08-27T10:30:00.000000Z"
}
]
}
]
```
---
### 2. Get Single Product
**GET** `/api/produk/{id}`
Mendapatkan detail produk berdasarkan ID dengan foto dan items.
**Parameters:**
- `id` (integer, required) - Product ID
**Response Success (200):**
```json
{
"id": 1,
"nama": "Cincin Berlian",
"kategori": "cincin",
"berat": 2.5,
"kadar": 18,
"harga_per_gram": 850000,
"harga_jual": 2500000,
"created_at": "2025-08-27T10:30:00.000000Z",
"updated_at": "2025-08-27T10:30:00.000000Z",
"deleted_at": null,
"foto": [
{
"id": 1,
"id_produk": 1,
"url": "http://localhost:8000/storage/foto/cincin1.jpg",
"created_at": "2025-08-27T10:30:00.000000Z",
"updated_at": "2025-08-27T10:30:00.000000Z"
}
],
"items": [
{
"id": 1,
"id_produk": 1,
"status": "tersedia",
"created_at": "2025-08-27T10:30:00.000000Z",
"updated_at": "2025-08-27T10:30:00.000000Z"
}
]
}
```
---
### 3. Create Product
**POST** `/produk`
Membuat produk baru dengan foto dari foto sementara.
**Headers:**
```
Content-Type: application/json
```
**Request Body:**
```json
{
"nama": "Cincin Berlian",
"kategori": "cincin",
"berat": 2.5,
"kadar": 18,
"harga_per_gram": 850000,
"harga_jual": 2500000,
"id_user": 1
}
```
**Request Body Parameters:**
- `nama` (string, required) - Nama produk (max: 100 karakter)
- `kategori` (string, required) - Kategori produk: `cincin`, `gelang`, `kalung`, `anting`
- `berat` (numeric, required) - Berat produk dalam gram
- `kadar` (integer, required) - Kadar emas
- `harga_per_gram` (numeric, required) - Harga per gram
- `harga_jual` (numeric, required) - Harga jual
- `id_user` (integer, optional) - User ID untuk mengambil foto sementara
**Response Success (201):**
```json
{
"message": "Produk berhasil dibuat",
"data": {
"id": 1,
"nama": "Cincin Berlian",
"kategori": "cincin",
"berat": 2.5,
"kadar": 18,
"harga_per_gram": 850000,
"harga_jual": 2500000,
"created_at": "2025-08-27T10:30:00.000000Z",
"updated_at": "2025-08-27T10:30:00.000000Z",
"foto": [
{
"id": 1,
"id_produk": 1,
"url": "http://localhost:8000/storage/foto/cincin1.jpg",
"created_at": "2025-08-27T10:30:00.000000Z",
"updated_at": "2025-08-27T10:30:00.000000Z"
}
]
}
}
```
**Response Error (422):**
```json
{
"message": "The given data was invalid.",
"errors": {
"nama": ["Nama produk harus diisi."],
"kategori": ["Kategori harus salah satu dari cincin, gelang, kalung, atau anting."],
"berat": ["Berat harus diisi."],
"kadar": ["Kadar harus diisi"],
"harga_per_gram": ["Harga per gram harus diisi"],
"harga_jual": ["Harga jual harus diisi"]
}
}
```
---
### 4. Update Product
**PUT** `/produk/{id}`
Memperbarui produk berdasarkan ID dengan opsi foto.
**Parameters:**
- `id` (integer, required) - Product ID
**Headers:**
```
Content-Type: application/json
```
**Request Body:**
```json
{
"nama": "Cincin Berlian Updated",
"kategori": "cincin",
"berat": 3.0,
"kadar": 22,
"harga_per_gram": 900000,
"harga_jual": 3000000,
"id_user": 1,
"hapus_foto_lama": true
}
```
**Request Body Parameters:**
- `nama` (string, required) - Nama produk (max: 100 karakter)
- `kategori` (string, required) - Kategori produk: `cincin`, `gelang`, `kalung`, `anting`
- `berat` (numeric, required) - Berat produk dalam gram
- `kadar` (integer, required) - Kadar emas
- `harga_per_gram` (numeric, required) - Harga per gram
- `harga_jual` (numeric, required) - Harga jual
- `id_user` (integer, optional) - User ID untuk mengambil foto sementara baru
- `hapus_foto_lama` (boolean, optional) - Flag untuk menghapus foto lama (default: false)
**Response Success (200):**
```json
{
"message": "Produk berhasil diubah",
"data": {
"id": 1,
"nama": "Cincin Berlian Updated",
"kategori": "cincin",
"berat": 3.0,
"kadar": 22,
"harga_per_gram": 900000,
"harga_jual": 3000000,
"updated_at": "2025-08-27T11:30:00.000000Z",
"foto": [
{
"id": 2,
"id_produk": 1,
"url": "http://localhost:8000/storage/foto/cincin2.jpg",
"created_at": "2025-08-27T11:30:00.000000Z",
"updated_at": "2025-08-27T11:30:00.000000Z"
}
]
}
}
```
---
### 5. Delete Product
**DELETE** `/produk/{id}`
Menghapus produk berdasarkan ID (soft delete) beserta foto-foto terkait.
**Parameters:**
- `id` (integer, required) - Product ID
**Response Success (200):**
```json
{
"message": "Produk berhasil dihapus."
}
```
**Response Error (404):**
```json
{
"message": "No query results for model [App\\Models\\Produk] 999"
}
```
---
## Foto Sementara API
### 1. Upload Foto Sementara
**POST** `/foto/upload`
Upload foto sementara yang akan digunakan saat create/update produk.
**Headers:**
```
Content-Type: multipart/form-data
```
**Request Body (Form Data):**
- `id_produk` (integer, required) - Product ID (untuk validasi exists di tabel produk)
- `foto` (file, required) - File foto (jpg, jpeg, png, max: 2MB)
**Response Success (201):**
```json
{
"message": "Foto berhasil disimpan"
}
```
**Response Error (422):**
```json
{
"message": "The given data was invalid.",
"errors": {
"id_produk": ["The id_produk field is required."],
"foto": ["The foto field is required."]
}
}
```
**Response Error - Invalid File (422):**
```json
{
"message": "The given data was invalid.",
"errors": {
"foto": [
"The foto must be an image.",
"The foto must be a file of type: jpg, jpeg, png.",
"The foto may not be greater than 2048 kilobytes."
]
}
}
```
---
### 2. Hapus Foto Sementara
**DELETE** `/foto/hapus/{id}`
Menghapus foto sementara berdasarkan ID.
**Parameters:**
- `id` (integer, required) - Foto Sementara ID
**Response Success (200):**
```json
{
"message": "Foto berhasil dihapus"
}
```
**Response Error (404):**
```json
{
"message": "No query results for model [App\\Models\\FotoSementara] 999"
}
```
---
### 3. Get Foto Sementara User
**DELETE** `/foto/get/{user_id}`
Ambil semua foto sementara milik user tertentu.
**Parameters:**
- `user_id` (integer, required) - User ID
**Response Success (200):**
```json
[
{
"id": 2,
"id_user": 1,
"url": "http://localhost:8000/storage/foto/cincin2.jpg",
"created_at": "2025-08-27T11:30:00.000000Z",
"updated_at": "2025-08-27T11:30:00.000000Z"
}
]
```
---
### 4. Reset Foto Sementara User
**DELETE** `/foto/reset/{user_id}`
Menghapus semua foto sementara milik user tertentu.
**Parameters:**
- `user_id` (integer, required) - User ID
**Response Success (200):**
```json
{
"message": "Foto sementara berhasil direset"
}
```
---
## Workflow Penggunaan
### Membuat Produk dengan Foto:
1. Upload foto menggunakan `POST /api/foto/upload` dengan `id_produk` dummy atau existing
2. Simpan `id_user` yang digunakan saat upload
3. Create produk dengan `POST /api/produk` dan sertakan `id_user`
4. Foto sementara akan otomatis dipindahkan ke foto permanent
### Update Produk dengan Foto Baru:
1. Upload foto baru dengan `POST /api/foto/upload`
2. Update produk dengan `PUT /api/produk/{id}`, sertakan `id_user` dan `hapus_foto_lama: true`
3. Foto lama akan dihapus dan foto sementara dipindahkan ke permanent
### Membersihkan Foto Sementara:
- Gunakan `DELETE /api/foto/reset/{user_id}` untuk menghapus semua foto sementara user
- Atau `DELETE /api/foto/hapus/{id}` untuk menghapus foto sementara spesifik

294
README.md Normal file
View File

@ -0,0 +1,294 @@
# 💎 Aplikasi Kasir Toko Perhiasan
Aplikasi kasir modern berbasis web untuk toko perhiasan dengan sistem manajemen yang lengkap dan antarmuka yang user-friendly.
## 👥 Tim Development
**PT Teknologi Mulia Sejahtera Cemerlang (Abbauf Tech) - Internship Program**
- **Baghaztra Van Ril** - Backend Developer
- **Aditya Ahmad Afarison** - Frontend Developer
- **Timotius Julius Iwan** - Backend Developer
- **Dhilan Radya Irawan** - Frontend Developer
---
## 🚀 Tentang Aplikasi
Aplikasi Kasir Toko Perhiasan adalah sistem Point of Sale (POS) yang dirancang khusus untuk kebutuhan toko perhiasan dengan fitur manajemen yang komprehensif dan sistem role-based access control.
### ✨ Fitur Utama
#### 👑 Role Owner
- **Manajemen Produk** - CRUD produk perhiasan lengkap dengan detail
- **Manajemen Nampan** - Organisasi produk berdasarkan nampan display
- **Manajemen Brankas** - Sistem penyimpanan produk berharga
- **Manajemen Sales** - Kelola data karyawan dan sales performance
- **Kasir** - Akses penuh ke sistem transaksi
- **Laporan** - Dashboard analytics dan laporan keuangan
- **Manajemen Akun** - User management dan pengaturan sistem
#### 💼 Role Kasir
- **Lihat Produk** - View-only access ke database produk
- **Kasir** - Interface transaksi untuk penjualan
### 🛠️ Tech Stack
- **Backend**: Laravel 11.x
- **Frontend**: Vue.js 3 + Vue Router
- **Database**: MySQL/PostgreSQL
- **Styling**: Tailwind CSS
- **Build Tool**: Vite
- **Authentication**: Laravel Sanctum
- **HTTP Client**: Axios
---
## 📋 Prerequisites
Pastikan sistem Anda sudah memiliki:
- **PHP** >= 8.1
- **Composer** >= 2.0
- **Node.js** >= 16.x
- **NPM** atau **Yarn**
- **MySQL** >= 8.0 atau **PostgreSQL** >= 13
- **Git**
---
## 🔧 Instalasi
### 1. Clone Repository
```bash
git clone https://github.com/Baghaztra/tmsc-kasir-perhiasan.git
cd tmsc-kasir-perhiasan
```
### 2. Install Dependencies Backend
```bash
# Install PHP dependencies
composer install
# Copy environment file
cp .env.example .env
# Generate application key
php artisan key:generate
```
### 3. Install Dependencies Frontend
```bash
# Install Node.js dependencies
npm install
```
### 4. Konfigurasi Database
Edit file `.env` sesuai dengan konfigurasi database Anda:
```env
DB_CONNECTION=mysql
DB_HOST=127.0.0.1
DB_PORT=3306
DB_DATABASE=kasir_perhiasan
DB_USERNAME=your_username
DB_PASSWORD=your_password
```
### 5. #Install Laravel Sanctum
**BELUM DIGUNAKAN**
```bash
# Publish konfigurasi Sanctum
php artisan vendor:publish --provider="Laravel\Sanctum\SanctumServiceProvider"
```
### 6. Setup Database
```bash
# Jalankan migrasi
php artisan migrate
# Jalankan seeder (data dummy)
php artisan db:seed
```
### 7. Storage Link
```bash
# Buat symbolic link untuk storage
php artisan storage:link
```
### 8. Jalankan Aplikasi
#### Development Mode
```bash
# Terminal 1 - Laravel Server
php artisan serve
# Terminal 2 - Vite Dev Server
npm run dev
```
#### Production Mode
```bash
# Build untuk production
npm run build
# Jalankan dengan web server (Apache/Nginx)
# atau gunakan PHP built-in server
php artisan serve --host=0.0.0.0 --port=8000
```
---
## 🌐 Akses Aplikasi
Setelah instalasi berhasil, akses aplikasi melalui:
- **URL**: http://localhost:8000
- **Admin Panel**: http://localhost:8000/admin (jika tersedia)
### 👤 Default Login
**Owner Account:**
- Email: `owner@tokoperhiasan.com`
- Password: `password123`
**Kasir Account:**
- Email: `kasir@tokoperhiasan.com`
- Password: `password123`
---
## 📁 Struktur Folder
```
kasir-toko-perhiasan/
├── app/
│ ├── Http/Controllers/ # API Controllers
│ └── Models/ # Database Models
├── database/
│ ├── migrations/ # Database Migrations
│ ├── seeders/ # Data Seeders
│ └── factories/ # Model Factories
├── public/ # Public Files
├── resources/
│ ├── css/
│ │ └── app.css # Main CSS File
│ ├── js/
│ │ ├── components/ # Reusable Vue Components
│ │ ├── pages/ # Vue Pages
│ │ ├── router/ # Vue Routes
│ │ ├── services/ # API Services
│ │ └── App.vue
│ └── views/
│ └── app.blade.php # Main SPA Template
└── routes/
└── web.php # Laravel Routes
```
---
Oke, jadi penjelasan “📊 Fitur Database” yang kamu tulis nggak sepenuhnya sesuai sama struktur tabel yang udah kamu definisikan di awal. Ada tabel yang salah nama, ada juga relasi yang kebalik. Gue rapihin biar konsisten dengan skema yang udah kamu kasih:
---
## 📊 Fitur Database (Revisi)
### Tabel Utama
- **akun** → Data pengguna (owner, kasir)
- **produk** → Master data produk perhiasan
- **foto** → Kumpulan foto untuk tiap produk
- **nampan** → Organisasi tempat penyimpanan produk (display)
- **item** → Stok unit fisik dari produk (bisa ada banyak untuk 1 produk)
- **transaksi** → Data transaksi penjualan
- **item_transaksi** → Detail item yang dijual per transaksi
- **sales** → Data marketing/sales yang membawa pelanggan
_(catatan: “brankas” nggak perlu tabel khusus, karena sudah diwakili `item.id_nampan = null`)_
### Relationships
```php
// Produk bisa punya banyak foto
Produk -> hasMany -> Foto
// Produk bisa punya banyak item fisik
Produk -> hasMany -> Item
// Item bisa ada di satu nampan, atau null (brankas)
Item -> belongsTo -> Nampan
// Transaksi dicatat oleh satu kasir
Transaksi -> belongsTo -> Akun (kasir)
// Transaksi bisa melibatkan 0/1 sales
Transaksi -> belongsTo -> Sales
// Transaksi punya banyak item_transaksi
Transaksi -> hasMany -> ItemTransaksi
// Item_transaksi menghubungkan 1 transaksi dengan 1 item
ItemTransaksi -> belongsTo -> Item
```
---
## 🛠️ Development
### Menjalankan Tests
```bash
# PHP Unit Tests
php artisan test
# atau dengan coverage
php artisan test --coverage
```
### Code Quality
```bash
# PHP CS Fixer
vendor/bin/php-cs-fixer fix
# Laravel Pint
vendor/bin/pint
```
### Database Management
```bash
# Reset database dan re-seed
php artisan migrate:fresh --seed
# Backup database
php artisan backup:run
# Generate model dengan migration
php artisan make:model ProductCategory -m
```
---
## 📄 License
Lisensi dan kepemilikan atascource code adalah milik PT Teknologi Mulia Sejahtera Cemerlang.
---
_Tim Internship TMSC 2025_

View File

@ -0,0 +1,8 @@
<?php
namespace App\Http\Controllers;
abstract class Controller
{
//
}

View File

@ -0,0 +1,56 @@
<?php
namespace App\Http\Controllers;
use App\Models\FotoSementara;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Storage;
class FotoSementaraController extends Controller
{
public function upload(Request $request)
{
$request->validate([
'id_produk' => 'required|exists:produk,id',
'foto' => 'required|image|mimes:jpg,jpeg,png|max:2048',
]);
$path = $request->file('foto')->store('foto', 'public');
$url = asset('storage/' . $path);
$foto = FotoSementara::create([
'id_produk' => $request->id_produk,
'url' => $url,
]);
return response()->json(['message' => 'Foto berhasil disimpan'], 201);
}
public function hapus($id)
{
$foto = FotoSementara::findOrFail($id);
// Extract the relative path from the URL
$relativePath = str_replace(asset('storage') . '/', '', $foto->url);
if ($foto->url && Storage::disk('public')->exists($relativePath)) {
Storage::disk('public')->delete($relativePath);
}
$foto->delete();
return response()->json(['message' => 'Foto berhasil dihapus']);
}
public function getAll($user_id)
{
$data = FotoSementara::where('id_user', $user_id);
return response()->json($data);
}
public function reset($user_id)
{
FotoSementara::where('id_user', $user_id)->delete();
return response()->json(['message' => 'Foto sementara berhasil direset']);
}
}

View File

@ -0,0 +1,89 @@
<?php
namespace App\Http\Controllers;
use App\Models\Item;
use Illuminate\Http\Request;
class ItemController extends Controller
{
/**
* Display a listing of the resource.
*/
public function index()
{
return response()->json(
Item::with('produk.foto','nampan')->get()
);
}
/**
* Store a newly created resource in storage.
*/
public function store(Request $request)
{
$validated = $request->validate([
'id_produk' => 'required|in:produks.id',
'id_nampan' => 'nullable|in:nampans.id'
],[
'id_produk' => 'Id produk tidak valid.',
'id_nampan' => 'Id nampan tidak valid'
]);
$item = Item::create($validated);
return response()->json([
'message' => 'Item berhasil dibuat',
'data' => $item
],201);
}
/**
* Display the specified resource.
*/
public function show(int $id)
{
$item = Item::with('produk.foto','nampan')->findOrFail($id);
return response()->json($item);
}
/**
* Update the specified resource in storage.
*/
public function update(Request $request, int $id)
{
$validated = $request->validate([
'id_produk' => 'required|in:produks.id',
'id_nampan' => 'nullable|in:nampans.id'
],[
'id_produk' => 'Id produk tidak valid.',
'id_nampan' => 'Id nampan tidak valid'
]);
$item = Item::findOrFail($id)->update($validated);
return response()->json([
'message' => 'Item berhasil diubah',
'data' => $item
],200);
}
/**
* Remove the specified resource from storage.
*/
public function destroy(int $id)
{
Item::findOrFail($id)->delete();
return response()->json([
'message' => 'Item berhasil dihapus'
],200);
}
// custom methods
public function brankasItem(){
$items = Item::with('produk.foto','nampan')->whereNull('id_nampan')->belumTerjual()->get();
return response()->json($items);
}
}

View File

@ -0,0 +1,88 @@
<?php
namespace App\Http\Controllers;
use App\Models\Nampan;
use Illuminate\Http\Request;
class NampanController extends Controller
{
/**
* Display a listing of the resource.
*/
public function index()
{
return response()->json(
Nampan::withCount('items')->get()
);
}
/**
* Store a newly created resource in storage.
*/
public function store(Request $request)
{
$validated = $request->validate([
'nama' => 'required|string|max:100',
],
[
'nama' => 'Nama nampan harus diisi.'
]);
Nampan::create($validated);
return response()->json([
'message' => 'Nampan berhasil dibuat'
],201);
}
/**
* Display the specified resource.
*/
public function show(int $id)
{
return response()->json(
Nampan::with('items')->find($id)
);
}
/**
* Update the specified resource in storage.
*/
public function update(Request $request, int $id)
{
$validated = $request->validate([
'nama' => 'required|string|max:100',
],
[
'nama' => 'Nama nampan harus diisi.'
]);
$nampan = Nampan::findOrFail($id);
$nampan->update($validated);
return response()->json([
'message' => 'Nampan berhasil diupdate'
],200);
}
/**
* Remove the specified resource from storage.
*/
public function destroy(int $id)
{
$nampan = Nampan::findOrFail($id);
$nampan->items()->each(function ($item) {
$item->update(['id_nampan' => null]);
});
$nampan->delete();
return response()->json([
'message' => 'Nampan berhasil dihapus'
], 204);
}
}

View File

@ -0,0 +1,215 @@
<?php
namespace App\Http\Controllers;
use App\Models\Produk;
use App\Models\Foto;
use App\Models\FotoSementara;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Storage;
use Illuminate\Support\Facades\DB;
class ProdukController extends Controller
{
/**
* Display a listing of the resource.
*/
public function index()
{
return response()->json(
Produk::withCount('items')->with('foto')->get()
);
}
/**
* Store a newly created resource in storage.
*/
public function store(Request $request)
{
$validated = $request->validate([
'nama' => 'required|string|max:100',
'kategori' => 'required|in:cincin,gelang,kalung,anting',
'berat' => 'required|numeric',
'kadar' => 'required|integer',
'harga_per_gram' => 'required|numeric',
'harga_jual' => 'required|numeric',
'id_user' => 'nullable|exists:users,id', // untuk mengambil foto sementara
],
[
'nama.required' => 'Nama produk harus diisi.',
'kategori.in' => 'Kategori harus salah satu dari cincin, gelang, kalung, atau anting.',
'berat.required' => 'Berat harus diisi.',
'kadar.required' => 'Kadar harus diisi',
'harga_per_gram.required' => 'Harga per gram harus diisi',
'harga_jual.required' => 'Harga jual harus diisi'
]);
DB::beginTransaction();
try {
// Create produk
$produk = Produk::create([
'nama' => $validated['nama'],
'kategori' => $validated['kategori'],
'berat' => $validated['berat'],
'kadar' => $validated['kadar'],
'harga_per_gram' => $validated['harga_per_gram'],
'harga_jual' => $validated['harga_jual'],
]);
// Pindahkan foto sementara ke foto permanen jika ada
if (isset($validated['id_user'])) {
$fotoSementara = FotoSementara::where('id_user', $validated['id_user'])->get();
foreach ($fotoSementara as $fs) {
Foto::create([
'id_produk' => $produk->id,
'url' => $fs->url
]);
// Hapus foto sementara setelah dipindah
$fs->delete();
}
}
DB::commit();
return response()->json([
'message' => 'Produk berhasil dibuat',
'data' => $produk->load('foto')
], 201);
} catch (\Exception $e) {
DB::rollback();
return response()->json([
'message' => 'Gagal membuat produk',
'error' => $e->getMessage()
], 500);
}
}
/**
* Display the specified resource.
*/
public function show(int $id)
{
$produk = Produk::with('foto', 'items')->findOrFail($id);
return response()->json($produk);
}
/**
* Update the specified resource in storage.
*/
public function update(Request $request, int $id)
{
$validated = $request->validate([
'nama' => 'required|string|max:100',
'kategori' => 'required|in:cincin,gelang,kalung,anting',
'berat' => 'required|numeric',
'kadar' => 'required|integer',
'harga_per_gram' => 'required|numeric',
'harga_jual' => 'required|numeric',
'id_user' => 'nullable|exists:users,id', // untuk mengambil foto sementara baru
'hapus_foto_lama' => 'nullable|boolean', // flag untuk menghapus foto lama
],
[
'nama.required' => 'Nama produk harus diisi.',
'kategori.in' => 'Kategori harus salah satu dari cincin, gelang, kalung, atau anting.',
'berat.required' => 'Berat harus diisi.',
'kadar.required' => 'Kadar harus diisi',
'harga_per_gram.required' => 'Harga per gram harus diisi',
'harga_jual.required' => 'Harga jual harus diisi'
]);
DB::beginTransaction();
try {
$produk = Produk::findOrFail($id);
// Update data produk
$produk->update([
'nama' => $validated['nama'],
'kategori' => $validated['kategori'],
'berat' => $validated['berat'],
'kadar' => $validated['kadar'],
'harga_per_gram' => $validated['harga_per_gram'],
'harga_jual' => $validated['harga_jual'],
]);
// Hapus foto lama jika diminta
if (isset($validated['hapus_foto_lama']) && $validated['hapus_foto_lama']) {
foreach ($produk->foto as $foto) {
// Hapus file fisik
$relativePath = str_replace(asset('storage') . '/', '', $foto->url);
if (Storage::disk('public')->exists($relativePath)) {
Storage::disk('public')->delete($relativePath);
}
$foto->delete();
}
}
// Tambahkan foto baru dari foto sementara jika ada
if (isset($validated['id_user'])) {
$fotoSementara = FotoSementara::where('id_user', $validated['id_user'])->get();
foreach ($fotoSementara as $fs) {
Foto::create([
'id_produk' => $produk->id,
'url' => $fs->url
]);
// Hapus foto sementara setelah dipindah
$fs->delete();
}
}
DB::commit();
return response()->json([
'message' => 'Produk berhasil diubah',
'data' => $produk->load('foto')
], 200);
} catch (\Exception $e) {
DB::rollback();
return response()->json([
'message' => 'Gagal mengubah produk',
'error' => $e->getMessage()
], 500);
}
}
/**
* Remove the specified resource from storage.
*/
public function destroy(int $id)
{
DB::beginTransaction();
try {
$produk = Produk::findOrFail($id);
// Hapus file foto dari storage
foreach ($produk->foto as $foto) {
$relativePath = str_replace(asset('storage') . '/', '', $foto->url);
if (Storage::disk('public')->exists($relativePath)) {
Storage::disk('public')->delete($relativePath);
}
$foto->delete();
}
// Hapus produk (soft delete)
$produk->delete();
DB::commit();
return response()->json([
'message' => 'Produk berhasil dihapus.'
], 200);
} catch (\Exception $e) {
DB::rollback();
return response()->json([
'message' => 'Gagal menghapus produk',
'error' => $e->getMessage()
], 500);
}
}
}

View File

@ -0,0 +1,90 @@
<?php
namespace App\Http\Controllers;
use App\Models\Sales;
use Illuminate\Http\Request;
class SalesController extends Controller
{
/**
* Display a listing of the resource.
*/
public function index()
{
return response()->json(
Sales::withCount('transaksi')->get()
);
}
/**
* Store a newly created resource in storage.
*/
public function store(Request $request)
{
$request->validate([
'nama' => 'required|string|max:80',
'no_hp' => 'required|string|max:20',
'alamat' => 'required|string|max:80',
]);
Sales::create([
'nama' => $request->nama,
'no_hp' => $request->no_hp,
'alamat' => $request->alamat,
]);
return response()->json([
'message' => 'Sales berhasil dibuat'
],201);
}
/**
* Display the specified resource.
*/
public function show(int $id)
{
return response()->json(
Sales::with('transaksi')->find($id)
);
}
/**
* Update the specified resource in storage.
*/
public function update(Request $request, int $id)
{
$request->validate([
'nama' => 'required|string|max:80',
'no_hp' => 'required|string|max:20',
'alamat' => 'required|string|max:80',
]);
$sales = Sales::find($id);
if (!$sales) {
return response()->json(['message' => 'Sales not found'], 404);
}
$sales->update([
'nama' => $request->nama,
'no_hp' => $request->no_hp,
'alamat' => $request->alamat,
]);
return response()->json([
'message' => 'Sales berhasil diupdate'
],200);
}
/**
* Remove the specified resource from storage.
*/
public function destroy(int $id)
{
Sales::findOrFail($id)->delete();
return response()->json([
'message' => 'Sales berhasil dihapus'
], 200);
}
}

View File

@ -0,0 +1,94 @@
<?php
namespace App\Http\Controllers;
use App\Models\Transaksi;
use App\Models\ItemTransaksi;
use App\Models\Item;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\DB;
class TransaksiController extends Controller
{
// List semua transaksi
public function index()
{
$transaksi = Transaksi::with(['kasir', 'sales', 'items.item.produk'])->get();
return response()->json($transaksi);
}
// Detail transaksi by ID
public function show($id)
{
$transaksi = Transaksi::with(['kasir', 'sales', 'items.item.produk'])->findOrFail($id);
return response()->json($transaksi);
}
// Membuat transaksi baru
public function store(Request $request)
{
$request->validate([
'id_kasir' => 'required|exists:akun,id',
'id_sales' => 'nullable|exists:sales,id',
'nama_sales' => 'nullable|string',
'no_hp' => 'nullable|string',
'alamat' => 'nullable|string',
'ongkos_bikin' => 'nullable|numeric',
'total_harga' => 'required|numeric',
'items' => 'required|array',
'items.*.id_item' => 'required|exists:item,id',
'items.*.harga_deal' => 'required|numeric',
]);
DB::beginTransaction();
try {
$transaksi = Transaksi::create([
'id_kasir' => $request->id_kasir,
'id_sales' => $request->id_sales,
'nama_sales' => $request->nama_sales,
'no_hp' => $request->no_hp,
'alamat' => $request->alamat,
'ongkos_bikin' => $request->ongkos_bikin,
'total_harga' => $request->total_harga,
]);
foreach ($request->items as $it) {
ItemTransaksi::create([
'id_transaksi' => $transaksi->id,
'id_item' => $it['id_item'],
'harga_deal' => $it['harga_deal'],
]);
Item::where('id', $it['id_item'])->update(['is_sold' => true]);
}
DB::commit();
return response()->json($transaksi->load('items'), 201);
} catch (\Exception $e) {
DB::rollBack();
return response()->json(['error' => $e->getMessage()], 500);
}
}
// Update transaksi
public function update(Request $request, $id)
{
$transaksi = Transaksi::findOrFail($id);
$transaksi->update($request->only([
'id_sales', 'nama_sales', 'no_hp', 'alamat', 'ongkos_bikin', 'total_harga'
]));
return response()->json($transaksi);
}
// Hapus transaksi
public function destroy($id)
{
$transaksi = Transaksi::findOrFail($id);
$transaksi->delete();
return response()->json(['message' => 'Transaksi berhasil dihapus']);
}
}

View File

@ -0,0 +1,68 @@
<?php
namespace App\Http\Controllers;
use Illuminate\Http\Request;
use App\Models\User;
use Illuminate\Support\Facades\Auth;
class UserController extends Controller
{
public function index()
{
$users = User::all();
return response()->json(
$users
);
}
public function store(Request $request)
{
$request->validate([
'nama' => 'required|nama|unique:users',
'password' => 'required|min:6',
'role' => 'required|in:owner, kasir',
]);
User::create([
'nama' => $request->nama,
'password' => bcrypt($request->password),
'role' => $request->role,
]);
return response()->json([
'message' => 'User berhasil ditambahkan'
], 200);
}
public function update(Request $request, $id)
{
$user = User::findOrFail($id);
$request->validate([
'nama' => 'required|nama|unique:users,nama,' . $id,
'password' => 'required|min:6',
'role' => 'required|in:owner, kasir',
]);
$user->update([
'nama' => $request->nama,
'password' => $request->password,
'role' => $request->role,
]);
return response()->json([
'message' => 'User berhasil diupdate'
],200);
}
public function destroy($id)
{
$user = User::findOrFail($id);
$user->delete();
return response()->json([
'message' => 'User berhasil dihapus'
], 200);
}
}

22
app/Models/Foto.php Normal file
View File

@ -0,0 +1,22 @@
<?php
namespace App\Models;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Database\Eloquent\Factories\HasFactory;
class Foto extends Model
{
use HasFactory;
protected $fillable = [
'id_produk',
'url',
];
public function produk()
{
return $this->belongsTo(Produk::class, 'id_produk');
}
}

View File

@ -0,0 +1,13 @@
<?php
namespace App\Models;
use Illuminate\Database\Eloquent\Model;
class FotoSementara extends Model
{
protected $fillable = [
'id_user',
'url',
];
}

38
app/Models/Item.php Normal file
View File

@ -0,0 +1,38 @@
<?php
namespace App\Models;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Database\Eloquent\Factories\HasFactory;
class Item extends Model
{
use HasFactory;
protected $fillable = [
'id_produk',
'id_nampan',
'is_sold',
];
public function produk()
{
return $this->belongsTo(Produk::class, 'id_produk');
}
public function scopeBelumTerjual($query)
{
return $query->where('is_sold', false);
}
public function nampan()
{
return $this->belongsTo(Nampan::class, 'id_nampan');
}
public function itemTransaksi()
{
return $this->hasMany(ItemTransaksi::class, 'id_item');
}
}

View File

@ -0,0 +1,28 @@
<?php
namespace App\Models;
use Illuminate\Database\Eloquent\Factories\HasFactory;
use Illuminate\Database\Eloquent\Model;
class ItemTransaksi extends Model
{
/** @use HasFactory<\Database\Factories\ItemTransaksiFactory> */
use HasFactory;
protected $fillable = [
'id_transaksi',
'id_item',
'harga_deal'
];
public function transaksi()
{
return $this->belongsTo(Transaksi::class, 'id_transaksi');
}
public function item()
{
return $this->belongsTo(Item::class, 'id_item');
}
}

21
app/Models/Nampan.php Normal file
View File

@ -0,0 +1,21 @@
<?php
namespace App\Models;
use Illuminate\Database\Eloquent\Factories\HasFactory;
use Illuminate\Database\Eloquent\Model;
class Nampan extends Model
{
/** @use HasFactory<\Database\Factories\NampanFactory> */
use HasFactory;
protected $fillable = [
'nama'
];
public function items()
{
return $this->hasMany(Item::class, 'id_nampan');
}
}

31
app/Models/Produk.php Normal file
View File

@ -0,0 +1,31 @@
<?php
namespace App\Models;
use Illuminate\Database\Eloquent\Factories\HasFactory;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Database\Eloquent\SoftDeletes;
class Produk extends Model
{
use HasFactory, SoftDeletes;
protected $fillable = [
'nama',
'kategori',
'berat',
'kadar',
'harga_per_gram',
'harga_jual',
];
public function items()
{
return $this->hasMany(Item::class, 'id_produk');
}
public function foto()
{
return $this->hasMany(Foto::class, 'id_produk');
}
}

23
app/Models/Sales.php Normal file
View File

@ -0,0 +1,23 @@
<?php
namespace App\Models;
use Illuminate\Database\Eloquent\Factories\HasFactory;
use Illuminate\Database\Eloquent\Model;
class Sales extends Model
{
/** @use HasFactory<\Database\Factories\SalesFactory> */
use HasFactory;
protected $fillable = [
'nama',
'no_hp',
'alamat'
];
public function transaksi()
{
return $this->hasMany(Transaksi::class, 'id_sales');
}
}

47
app/Models/Transaksi.php Normal file
View File

@ -0,0 +1,47 @@
<?php
namespace App\Models;
use Illuminate\Database\Eloquent\Factories\HasFactory;
use Illuminate\Database\Eloquent\Model;
class Transaksi extends Model
{
/** @use HasFactory<\Database\Factories\TransaksiFactory> */
use HasFactory;
protected $fillable = [
'id_kasir',
'id_sales',
'nama_sales',
'no_hp',
'alamat',
'ongkos_bikin',
'total_harga',
'created_at',
];
public function kasir()
{
return $this->belongsTo(User::class, 'id_kasir');
}
public function sales()
{
return $this->belongsTo(Sales::class, 'id_sales');
}
public function itemTransaksi()
{
return $this->hasMany(ItemTransaksi::class, 'id_transaksi');
}
public function items()
{
return $this->hasMany(ItemTransaksi::class, 'id_transaksi');
}
public function foto ()
{
return $this->hasMany(Foto::class, 'id_produk');
}
}

48
app/Models/User.php Normal file
View File

@ -0,0 +1,48 @@
<?php
namespace App\Models;
// use Illuminate\Contracts\Auth\MustVerifyEmail;
use Illuminate\Database\Eloquent\Factories\HasFactory;
use Illuminate\Foundation\Auth\User as Authenticatable;
use Illuminate\Notifications\Notifiable;
class User extends Authenticatable
{
/** @use HasFactory<\Database\Factories\UserFactory> */
use HasFactory, Notifiable;
/**
* The attributes that are mass assignable.
*
* @var list<string>
*/
protected $fillable = [
'nama',
'role',
'password',
];
/**
* The attributes that should be hidden for serialization.
*
* @var list<string>
*/
protected $hidden = [
'password',
// 'remember_token',
];
/**
* Get the attributes that should be cast.
*
* @return array<string, string>
*/
protected function casts(): array
{
return [
// 'email_verified_at' => 'datetime',
'password' => 'hashed',
];
}
}

View File

@ -0,0 +1,24 @@
<?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
{
//
}
}

18
artisan Normal file
View File

@ -0,0 +1,18 @@
#!/usr/bin/env php
<?php
use Illuminate\Foundation\Application;
use Symfony\Component\Console\Input\ArgvInput;
define('LARAVEL_START', microtime(true));
// Register the Composer autoloader...
require __DIR__.'/vendor/autoload.php';
// Bootstrap Laravel and handle the command...
/** @var Application $app */
$app = require_once __DIR__.'/bootstrap/app.php';
$status = $app->handleCommand(new ArgvInput);
exit($status);

21
bootstrap/app.php Normal file
View File

@ -0,0 +1,21 @@
<?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',
commands: __DIR__.'/../routes/console.php',
health: '/up',
)
->withMiddleware(function (Middleware $middleware) {
// Exclude CSRF untuk API routes
$middleware->validateCsrfTokens(except: [
'api/*'
]);
})
->withExceptions(function (Exceptions $exceptions): void {
//
})->create();

2
bootstrap/cache/.gitignore vendored Normal file
View File

@ -0,0 +1,2 @@
*
!.gitignore

5
bootstrap/providers.php Normal file
View File

@ -0,0 +1,5 @@
<?php
return [
App\Providers\AppServiceProvider::class,
];

77
composer.json Normal file
View File

@ -0,0 +1,77 @@
{
"$schema": "https://getcomposer.org/schema.json",
"name": "laravel/laravel",
"type": "project",
"description": "The skeleton application for the Laravel framework.",
"keywords": ["laravel", "framework"],
"license": "MIT",
"require": {
"php": "^8.2",
"laravel/framework": "^12.0",
"laravel/sanctum": "^4.2",
"laravel/tinker": "^2.10.1"
},
"require-dev": {
"fakerphp/faker": "^1.23",
"laravel/pail": "^1.2.2",
"laravel/pint": "^1.24",
"laravel/sail": "^1.41",
"mockery/mockery": "^1.6",
"nunomaduro/collision": "^8.6",
"pestphp/pest": "^3.8",
"pestphp/pest-plugin-laravel": "^3.2"
},
"autoload": {
"psr-4": {
"App\\": "app/",
"Database\\Factories\\": "database/factories/",
"Database\\Seeders\\": "database/seeders/"
}
},
"autoload-dev": {
"psr-4": {
"Tests\\": "tests/"
}
},
"scripts": {
"post-autoload-dump": [
"Illuminate\\Foundation\\ComposerScripts::postAutoloadDump",
"@php artisan package:discover --ansi"
],
"post-update-cmd": [
"@php artisan vendor:publish --tag=laravel-assets --ansi --force"
],
"post-root-package-install": [
"@php -r \"file_exists('.env') || copy('.env.example', '.env');\""
],
"post-create-project-cmd": [
"@php artisan key:generate --ansi",
"@php -r \"file_exists('database/database.sqlite') || touch('database/database.sqlite');\"",
"@php artisan migrate --graceful --ansi"
],
"dev": [
"Composer\\Config::disableProcessTimeout",
"npx concurrently -c \"#93c5fd,#c4b5fd,#fb7185,#fdba74\" \"php artisan serve\" \"php artisan queue:listen --tries=1\" \"php artisan pail --timeout=0\" \"npm run dev\" --names=server,queue,logs,vite --kill-others"
],
"test": [
"@php artisan config:clear --ansi",
"@php artisan test"
]
},
"extra": {
"laravel": {
"dont-discover": []
}
},
"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
}

9388
composer.lock generated Normal file

File diff suppressed because it is too large Load Diff

BIN
composer.phar Normal file

Binary file not shown.

126
config/app.php Normal file
View File

@ -0,0 +1,126 @@
<?php
return [
/*
|--------------------------------------------------------------------------
| Application Name
|--------------------------------------------------------------------------
|
| This value is the name of your application, which will be used when the
| framework needs to place the application's name in a notification or
| other UI elements where an application name needs to be displayed.
|
*/
'name' => env('APP_NAME', 'Laravel'),
/*
|--------------------------------------------------------------------------
| Application Environment
|--------------------------------------------------------------------------
|
| This value determines the "environment" your application is currently
| running in. This may determine how you prefer to configure various
| services the application utilizes. Set this in your ".env" file.
|
*/
'env' => env('APP_ENV', 'production'),
/*
|--------------------------------------------------------------------------
| Application Debug Mode
|--------------------------------------------------------------------------
|
| When your application is in debug mode, detailed error messages with
| stack traces will be shown on every error that occurs within your
| application. If disabled, a simple generic error page is shown.
|
*/
'debug' => (bool) env('APP_DEBUG', false),
/*
|--------------------------------------------------------------------------
| Application URL
|--------------------------------------------------------------------------
|
| This URL is used by the console to properly generate URLs when using
| the Artisan command line tool. You should set this to the root of
| the application so that it's available within Artisan commands.
|
*/
'url' => env('APP_URL', 'http://localhost'),
/*
|--------------------------------------------------------------------------
| Application Timezone
|--------------------------------------------------------------------------
|
| Here you may specify the default timezone for your application, which
| will be used by the PHP date and date-time functions. The timezone
| is set to "UTC" by default as it is suitable for most use cases.
|
*/
'timezone' => 'Asia/Jakarta',
/*
|--------------------------------------------------------------------------
| Application Locale Configuration
|--------------------------------------------------------------------------
|
| The application locale determines the default locale that will be used
| by Laravel's translation / localization methods. This option can be
| set to any locale for which you plan to have translation strings.
|
*/
'locale' => env('APP_LOCALE', 'id'),
'fallback_locale' => env('APP_FALLBACK_LOCALE', 'id'),
'faker_locale' => env('APP_FAKER_LOCALE', 'id_ID'),
/*
|--------------------------------------------------------------------------
| Encryption Key
|--------------------------------------------------------------------------
|
| This key is utilized by Laravel's encryption services and should be set
| to a random, 32 character string to ensure that all encrypted values
| are secure. You should do this prior to deploying the application.
|
*/
'cipher' => 'AES-256-CBC',
'key' => env('APP_KEY'),
'previous_keys' => [
...array_filter(
explode(',', (string) env('APP_PREVIOUS_KEYS', ''))
),
],
/*
|--------------------------------------------------------------------------
| Maintenance Mode Driver
|--------------------------------------------------------------------------
|
| These configuration options determine the driver used to determine and
| manage Laravel's "maintenance mode" status. The "cache" driver will
| allow maintenance mode to be controlled across multiple machines.
|
| Supported drivers: "file", "cache"
|
*/
'maintenance' => [
'driver' => env('APP_MAINTENANCE_DRIVER', 'file'),
'store' => env('APP_MAINTENANCE_STORE', 'database'),
],
];

115
config/auth.php Normal file
View File

@ -0,0 +1,115 @@
<?php
return [
/*
|--------------------------------------------------------------------------
| Authentication Defaults
|--------------------------------------------------------------------------
|
| This option defines the default authentication "guard" and password
| reset "broker" for your application. You may change these values
| as required, but they're a perfect start for most applications.
|
*/
'defaults' => [
'guard' => env('AUTH_GUARD', 'web'),
'passwords' => env('AUTH_PASSWORD_BROKER', 'users'),
],
/*
|--------------------------------------------------------------------------
| Authentication Guards
|--------------------------------------------------------------------------
|
| Next, you may define every authentication guard for your application.
| Of course, a great default configuration has been defined for you
| which utilizes session storage plus the Eloquent user provider.
|
| All authentication guards have a user provider, which defines how the
| users are actually retrieved out of your database or other storage
| system used by the application. Typically, Eloquent is utilized.
|
| Supported: "session"
|
*/
'guards' => [
'web' => [
'driver' => 'session',
'provider' => 'users',
],
],
/*
|--------------------------------------------------------------------------
| User Providers
|--------------------------------------------------------------------------
|
| All authentication guards have a user provider, which defines how the
| users are actually retrieved out of your database or other storage
| system used by the application. Typically, Eloquent is utilized.
|
| If you have multiple user tables or models you may configure multiple
| providers to represent the model / table. These providers may then
| be assigned to any extra authentication guards you have defined.
|
| Supported: "database", "eloquent"
|
*/
'providers' => [
'users' => [
'driver' => 'eloquent',
'model' => env('AUTH_MODEL', App\Models\User::class),
],
// 'users' => [
// 'driver' => 'database',
// 'table' => 'users',
// ],
],
/*
|--------------------------------------------------------------------------
| Resetting Passwords
|--------------------------------------------------------------------------
|
| These configuration options specify the behavior of Laravel's password
| reset functionality, including the table utilized for token storage
| and the user provider that is invoked to actually retrieve users.
|
| The expiry time is the number of minutes that each reset token will be
| considered valid. This security feature keeps tokens short-lived so
| they have less time to be guessed. You may change this as needed.
|
| The throttle setting is the number of seconds a user must wait before
| generating more password reset tokens. This prevents the user from
| quickly generating a very large amount of password reset tokens.
|
*/
'passwords' => [
'users' => [
'provider' => 'users',
'table' => env('AUTH_PASSWORD_RESET_TOKEN_TABLE', 'password_reset_tokens'),
'expire' => 60,
'throttle' => 60,
],
],
/*
|--------------------------------------------------------------------------
| Password Confirmation Timeout
|--------------------------------------------------------------------------
|
| Here you may define the number of seconds before a password confirmation
| window expires and users are asked to re-enter their password via the
| confirmation screen. By default, the timeout lasts for three hours.
|
*/
'password_timeout' => env('AUTH_PASSWORD_TIMEOUT', 10800),
];

108
config/cache.php Normal file
View File

@ -0,0 +1,108 @@
<?php
use Illuminate\Support\Str;
return [
/*
|--------------------------------------------------------------------------
| Default Cache Store
|--------------------------------------------------------------------------
|
| This option controls the default cache store that will be used by the
| framework. This connection is utilized if another isn't explicitly
| specified when running a cache operation inside the application.
|
*/
'default' => env('CACHE_STORE', 'database'),
/*
|--------------------------------------------------------------------------
| Cache Stores
|--------------------------------------------------------------------------
|
| Here you may define all of the cache "stores" for your application as
| well as their drivers. You may even define multiple stores for the
| same cache driver to group types of items stored in your caches.
|
| Supported drivers: "array", "database", "file", "memcached",
| "redis", "dynamodb", "octane", "null"
|
*/
'stores' => [
'array' => [
'driver' => 'array',
'serialize' => false,
],
'database' => [
'driver' => 'database',
'connection' => env('DB_CACHE_CONNECTION'),
'table' => env('DB_CACHE_TABLE', 'cache'),
'lock_connection' => env('DB_CACHE_LOCK_CONNECTION'),
'lock_table' => env('DB_CACHE_LOCK_TABLE'),
],
'file' => [
'driver' => 'file',
'path' => storage_path('framework/cache/data'),
'lock_path' => storage_path('framework/cache/data'),
],
'memcached' => [
'driver' => 'memcached',
'persistent_id' => env('MEMCACHED_PERSISTENT_ID'),
'sasl' => [
env('MEMCACHED_USERNAME'),
env('MEMCACHED_PASSWORD'),
],
'options' => [
// Memcached::OPT_CONNECT_TIMEOUT => 2000,
],
'servers' => [
[
'host' => env('MEMCACHED_HOST', '127.0.0.1'),
'port' => env('MEMCACHED_PORT', 11211),
'weight' => 100,
],
],
],
'redis' => [
'driver' => 'redis',
'connection' => env('REDIS_CACHE_CONNECTION', 'cache'),
'lock_connection' => env('REDIS_CACHE_LOCK_CONNECTION', 'default'),
],
'dynamodb' => [
'driver' => 'dynamodb',
'key' => env('AWS_ACCESS_KEY_ID'),
'secret' => env('AWS_SECRET_ACCESS_KEY'),
'region' => env('AWS_DEFAULT_REGION', 'us-east-1'),
'table' => env('DYNAMODB_CACHE_TABLE', 'cache'),
'endpoint' => env('DYNAMODB_ENDPOINT'),
],
'octane' => [
'driver' => 'octane',
],
],
/*
|--------------------------------------------------------------------------
| Cache Key Prefix
|--------------------------------------------------------------------------
|
| When utilizing the APC, database, memcached, Redis, and DynamoDB cache
| stores, there might be other applications using the same cache. For
| that reason, you may prefix every cache key to avoid collisions.
|
*/
'prefix' => env('CACHE_PREFIX', Str::slug((string) env('APP_NAME', 'laravel')).'-cache-'),
];

174
config/database.php Normal file
View File

@ -0,0 +1,174 @@
<?php
use Illuminate\Support\Str;
return [
/*
|--------------------------------------------------------------------------
| Default Database Connection Name
|--------------------------------------------------------------------------
|
| Here you may specify which of the database connections below you wish
| to use as your default connection for database operations. This is
| the connection which will be utilized unless another connection
| is explicitly specified when you execute a query / statement.
|
*/
'default' => env('DB_CONNECTION', 'sqlite'),
/*
|--------------------------------------------------------------------------
| Database Connections
|--------------------------------------------------------------------------
|
| Below are all of the database connections defined for your application.
| An example configuration is provided for each database system which
| is supported by Laravel. You're free to add / remove connections.
|
*/
'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),
'busy_timeout' => null,
'journal_mode' => null,
'synchronous' => null,
],
'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'),
]) : [],
],
'mariadb' => [
'driver' => 'mariadb',
'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'),
]) : [],
],
'pgsql' => [
'driver' => 'pgsql',
'url' => env('DB_URL'),
'host' => env('DB_HOST', '127.0.0.1'),
'port' => env('DB_PORT', '5432'),
'database' => env('DB_DATABASE', 'laravel'),
'username' => env('DB_USERNAME', 'root'),
'password' => env('DB_PASSWORD', ''),
'charset' => env('DB_CHARSET', 'utf8'),
'prefix' => '',
'prefix_indexes' => true,
'search_path' => 'public',
'sslmode' => 'prefer',
],
'sqlsrv' => [
'driver' => 'sqlsrv',
'url' => env('DB_URL'),
'host' => env('DB_HOST', 'localhost'),
'port' => env('DB_PORT', '1433'),
'database' => env('DB_DATABASE', 'laravel'),
'username' => env('DB_USERNAME', 'root'),
'password' => env('DB_PASSWORD', ''),
'charset' => env('DB_CHARSET', 'utf8'),
'prefix' => '',
'prefix_indexes' => true,
// 'encrypt' => env('DB_ENCRYPT', 'yes'),
// 'trust_server_certificate' => env('DB_TRUST_SERVER_CERTIFICATE', 'false'),
],
],
/*
|--------------------------------------------------------------------------
| Migration Repository Table
|--------------------------------------------------------------------------
|
| This table keeps track of all the migrations that have already run for
| your application. Using this information, we can determine which of
| the migrations on disk haven't actually been run on the database.
|
*/
'migrations' => [
'table' => 'migrations',
'update_date_on_publish' => true,
],
/*
|--------------------------------------------------------------------------
| Redis Databases
|--------------------------------------------------------------------------
|
| Redis is an open source, fast, and advanced key-value store that also
| provides a richer body of commands than a typical key-value system
| such as Memcached. You may define your connection settings here.
|
*/
'redis' => [
'client' => env('REDIS_CLIENT', 'phpredis'),
'options' => [
'cluster' => env('REDIS_CLUSTER', 'redis'),
'prefix' => env('REDIS_PREFIX', Str::slug((string) env('APP_NAME', 'laravel')).'-database-'),
'persistent' => env('REDIS_PERSISTENT', false),
],
'default' => [
'url' => env('REDIS_URL'),
'host' => env('REDIS_HOST', '127.0.0.1'),
'username' => env('REDIS_USERNAME'),
'password' => env('REDIS_PASSWORD'),
'port' => env('REDIS_PORT', '6379'),
'database' => env('REDIS_DB', '0'),
],
'cache' => [
'url' => env('REDIS_URL'),
'host' => env('REDIS_HOST', '127.0.0.1'),
'username' => env('REDIS_USERNAME'),
'password' => env('REDIS_PASSWORD'),
'port' => env('REDIS_PORT', '6379'),
'database' => env('REDIS_CACHE_DB', '1'),
],
],
];

80
config/filesystems.php Normal file
View File

@ -0,0 +1,80 @@
<?php
return [
/*
|--------------------------------------------------------------------------
| Default Filesystem Disk
|--------------------------------------------------------------------------
|
| Here you may specify the default filesystem disk that should be used
| by the framework. The "local" disk, as well as a variety of cloud
| based disks are available to your application for file storage.
|
*/
'default' => env('FILESYSTEM_DISK', 'local'),
/*
|--------------------------------------------------------------------------
| Filesystem Disks
|--------------------------------------------------------------------------
|
| Below you may configure as many filesystem disks as necessary, and you
| may even configure multiple disks for the same driver. Examples for
| most supported storage drivers are configured here for reference.
|
| Supported drivers: "local", "ftp", "sftp", "s3"
|
*/
'disks' => [
'local' => [
'driver' => 'local',
'root' => storage_path('app/private'),
'serve' => true,
'throw' => false,
'report' => false,
],
'public' => [
'driver' => 'local',
'root' => storage_path('app/public'),
'url' => env('APP_URL').'/storage',
'visibility' => 'public',
'throw' => false,
'report' => false,
],
's3' => [
'driver' => 's3',
'key' => env('AWS_ACCESS_KEY_ID'),
'secret' => env('AWS_SECRET_ACCESS_KEY'),
'region' => env('AWS_DEFAULT_REGION'),
'bucket' => env('AWS_BUCKET'),
'url' => env('AWS_URL'),
'endpoint' => env('AWS_ENDPOINT'),
'use_path_style_endpoint' => env('AWS_USE_PATH_STYLE_ENDPOINT', false),
'throw' => false,
'report' => false,
],
],
/*
|--------------------------------------------------------------------------
| Symbolic Links
|--------------------------------------------------------------------------
|
| Here you may configure the symbolic links that will be created when the
| `storage:link` Artisan command is executed. The array keys should be
| the locations of the links and the values should be their targets.
|
*/
'links' => [
public_path('storage') => storage_path('app/public'),
],
];

132
config/logging.php Normal file
View File

@ -0,0 +1,132 @@
<?php
use Monolog\Handler\NullHandler;
use Monolog\Handler\StreamHandler;
use Monolog\Handler\SyslogUdpHandler;
use Monolog\Processor\PsrLogMessageProcessor;
return [
/*
|--------------------------------------------------------------------------
| Default Log Channel
|--------------------------------------------------------------------------
|
| This option defines the default log channel that is utilized to write
| messages to your logs. The value provided here should match one of
| the channels present in the list of "channels" configured below.
|
*/
'default' => env('LOG_CHANNEL', 'stack'),
/*
|--------------------------------------------------------------------------
| Deprecations Log Channel
|--------------------------------------------------------------------------
|
| This option controls the log channel that should be used to log warnings
| regarding deprecated PHP and library features. This allows you to get
| your application ready for upcoming major versions of dependencies.
|
*/
'deprecations' => [
'channel' => env('LOG_DEPRECATIONS_CHANNEL', 'null'),
'trace' => env('LOG_DEPRECATIONS_TRACE', false),
],
/*
|--------------------------------------------------------------------------
| Log Channels
|--------------------------------------------------------------------------
|
| Here you may configure the log channels for your application. Laravel
| utilizes the Monolog PHP logging library, which includes a variety
| of powerful log handlers and formatters that you're free to use.
|
| Available drivers: "single", "daily", "slack", "syslog",
| "errorlog", "monolog", "custom", "stack"
|
*/
'channels' => [
'stack' => [
'driver' => 'stack',
'channels' => explode(',', (string) env('LOG_STACK', 'single')),
'ignore_exceptions' => false,
],
'single' => [
'driver' => 'single',
'path' => storage_path('logs/laravel.log'),
'level' => env('LOG_LEVEL', 'debug'),
'replace_placeholders' => true,
],
'daily' => [
'driver' => 'daily',
'path' => storage_path('logs/laravel.log'),
'level' => env('LOG_LEVEL', 'debug'),
'days' => env('LOG_DAILY_DAYS', 14),
'replace_placeholders' => true,
],
'slack' => [
'driver' => 'slack',
'url' => env('LOG_SLACK_WEBHOOK_URL'),
'username' => env('LOG_SLACK_USERNAME', 'Laravel Log'),
'emoji' => env('LOG_SLACK_EMOJI', ':boom:'),
'level' => env('LOG_LEVEL', 'critical'),
'replace_placeholders' => true,
],
'papertrail' => [
'driver' => 'monolog',
'level' => env('LOG_LEVEL', 'debug'),
'handler' => env('LOG_PAPERTRAIL_HANDLER', SyslogUdpHandler::class),
'handler_with' => [
'host' => env('PAPERTRAIL_URL'),
'port' => env('PAPERTRAIL_PORT'),
'connectionString' => 'tls://'.env('PAPERTRAIL_URL').':'.env('PAPERTRAIL_PORT'),
],
'processors' => [PsrLogMessageProcessor::class],
],
'stderr' => [
'driver' => 'monolog',
'level' => env('LOG_LEVEL', 'debug'),
'handler' => StreamHandler::class,
'handler_with' => [
'stream' => 'php://stderr',
],
'formatter' => env('LOG_STDERR_FORMATTER'),
'processors' => [PsrLogMessageProcessor::class],
],
'syslog' => [
'driver' => 'syslog',
'level' => env('LOG_LEVEL', 'debug'),
'facility' => env('LOG_SYSLOG_FACILITY', LOG_USER),
'replace_placeholders' => true,
],
'errorlog' => [
'driver' => 'errorlog',
'level' => env('LOG_LEVEL', 'debug'),
'replace_placeholders' => true,
],
'null' => [
'driver' => 'monolog',
'handler' => NullHandler::class,
],
'emergency' => [
'path' => storage_path('logs/laravel.log'),
],
],
];

118
config/mail.php Normal file
View File

@ -0,0 +1,118 @@
<?php
return [
/*
|--------------------------------------------------------------------------
| Default Mailer
|--------------------------------------------------------------------------
|
| This option controls the default mailer that is used to send all email
| messages unless another mailer is explicitly specified when sending
| the message. All additional mailers can be configured within the
| "mailers" array. Examples of each type of mailer are provided.
|
*/
'default' => env('MAIL_MAILER', 'log'),
/*
|--------------------------------------------------------------------------
| Mailer Configurations
|--------------------------------------------------------------------------
|
| Here you may configure all of the mailers used by your application plus
| their respective settings. Several examples have been configured for
| you and you are free to add your own as your application requires.
|
| Laravel supports a variety of mail "transport" drivers that can be used
| when delivering an email. You may specify which one you're using for
| your mailers below. You may also add additional mailers if needed.
|
| Supported: "smtp", "sendmail", "mailgun", "ses", "ses-v2",
| "postmark", "resend", "log", "array",
| "failover", "roundrobin"
|
*/
'mailers' => [
'smtp' => [
'transport' => 'smtp',
'scheme' => env('MAIL_SCHEME'),
'url' => env('MAIL_URL'),
'host' => env('MAIL_HOST', '127.0.0.1'),
'port' => env('MAIL_PORT', 2525),
'username' => env('MAIL_USERNAME'),
'password' => env('MAIL_PASSWORD'),
'timeout' => null,
'local_domain' => env('MAIL_EHLO_DOMAIN', parse_url((string) env('APP_URL', 'http://localhost'), PHP_URL_HOST)),
],
'ses' => [
'transport' => 'ses',
],
'postmark' => [
'transport' => 'postmark',
// 'message_stream_id' => env('POSTMARK_MESSAGE_STREAM_ID'),
// 'client' => [
// 'timeout' => 5,
// ],
],
'resend' => [
'transport' => 'resend',
],
'sendmail' => [
'transport' => 'sendmail',
'path' => env('MAIL_SENDMAIL_PATH', '/usr/sbin/sendmail -bs -i'),
],
'log' => [
'transport' => 'log',
'channel' => env('MAIL_LOG_CHANNEL'),
],
'array' => [
'transport' => 'array',
],
'failover' => [
'transport' => 'failover',
'mailers' => [
'smtp',
'log',
],
'retry_after' => 60,
],
'roundrobin' => [
'transport' => 'roundrobin',
'mailers' => [
'ses',
'postmark',
],
'retry_after' => 60,
],
],
/*
|--------------------------------------------------------------------------
| Global "From" Address
|--------------------------------------------------------------------------
|
| You may wish for all emails sent by your application to be sent from
| the same address. Here you may specify a name and address that is
| used globally for all emails that are sent by your application.
|
*/
'from' => [
'address' => env('MAIL_FROM_ADDRESS', 'hello@example.com'),
'name' => env('MAIL_FROM_NAME', 'Example'),
],
];

112
config/queue.php Normal file
View File

@ -0,0 +1,112 @@
<?php
return [
/*
|--------------------------------------------------------------------------
| Default Queue Connection Name
|--------------------------------------------------------------------------
|
| Laravel's queue supports a variety of backends via a single, unified
| API, giving you convenient access to each backend using identical
| syntax for each. The default queue connection is defined below.
|
*/
'default' => env('QUEUE_CONNECTION', 'database'),
/*
|--------------------------------------------------------------------------
| Queue Connections
|--------------------------------------------------------------------------
|
| Here you may configure the connection options for every queue backend
| used by your application. An example configuration is provided for
| each backend supported by Laravel. You're also free to add more.
|
| Drivers: "sync", "database", "beanstalkd", "sqs", "redis", "null"
|
*/
'connections' => [
'sync' => [
'driver' => 'sync',
],
'database' => [
'driver' => 'database',
'connection' => env('DB_QUEUE_CONNECTION'),
'table' => env('DB_QUEUE_TABLE', 'jobs'),
'queue' => env('DB_QUEUE', 'default'),
'retry_after' => (int) env('DB_QUEUE_RETRY_AFTER', 90),
'after_commit' => false,
],
'beanstalkd' => [
'driver' => 'beanstalkd',
'host' => env('BEANSTALKD_QUEUE_HOST', 'localhost'),
'queue' => env('BEANSTALKD_QUEUE', 'default'),
'retry_after' => (int) env('BEANSTALKD_QUEUE_RETRY_AFTER', 90),
'block_for' => 0,
'after_commit' => false,
],
'sqs' => [
'driver' => 'sqs',
'key' => env('AWS_ACCESS_KEY_ID'),
'secret' => env('AWS_SECRET_ACCESS_KEY'),
'prefix' => env('SQS_PREFIX', 'https://sqs.us-east-1.amazonaws.com/your-account-id'),
'queue' => env('SQS_QUEUE', 'default'),
'suffix' => env('SQS_SUFFIX'),
'region' => env('AWS_DEFAULT_REGION', 'us-east-1'),
'after_commit' => false,
],
'redis' => [
'driver' => 'redis',
'connection' => env('REDIS_QUEUE_CONNECTION', 'default'),
'queue' => env('REDIS_QUEUE', 'default'),
'retry_after' => (int) env('REDIS_QUEUE_RETRY_AFTER', 90),
'block_for' => null,
'after_commit' => false,
],
],
/*
|--------------------------------------------------------------------------
| Job Batching
|--------------------------------------------------------------------------
|
| The following options configure the database and table that store job
| batching information. These options can be updated to any database
| connection and table which has been defined by your application.
|
*/
'batching' => [
'database' => env('DB_CONNECTION', 'sqlite'),
'table' => 'job_batches',
],
/*
|--------------------------------------------------------------------------
| Failed Queue Jobs
|--------------------------------------------------------------------------
|
| These options configure the behavior of failed queue job logging so you
| can control how and where failed jobs are stored. Laravel ships with
| support for storing failed jobs in a simple file or in a database.
|
| Supported drivers: "database-uuids", "dynamodb", "file", "null"
|
*/
'failed' => [
'driver' => env('QUEUE_FAILED_DRIVER', 'database-uuids'),
'database' => env('DB_CONNECTION', 'sqlite'),
'table' => 'failed_jobs',
],
];

84
config/sanctum.php Normal file
View File

@ -0,0 +1,84 @@
<?php
use Laravel\Sanctum\Sanctum;
return [
/*
|--------------------------------------------------------------------------
| Stateful Domains
|--------------------------------------------------------------------------
|
| Requests from the following domains / hosts will receive stateful API
| authentication cookies. Typically, these should include your local
| and production domains which access your API via a frontend SPA.
|
*/
'stateful' => explode(',', env('SANCTUM_STATEFUL_DOMAINS', sprintf(
'%s%s',
'localhost,localhost:3000,127.0.0.1,127.0.0.1:8000,::1',
Sanctum::currentApplicationUrlWithPort(),
// Sanctum::currentRequestHost(),
))),
/*
|--------------------------------------------------------------------------
| Sanctum Guards
|--------------------------------------------------------------------------
|
| This array contains the authentication guards that will be checked when
| Sanctum is trying to authenticate a request. If none of these guards
| are able to authenticate the request, Sanctum will use the bearer
| token that's present on an incoming request for authentication.
|
*/
'guard' => ['web'],
/*
|--------------------------------------------------------------------------
| Expiration Minutes
|--------------------------------------------------------------------------
|
| This value controls the number of minutes until an issued token will be
| considered expired. This will override any values set in the token's
| "expires_at" attribute, but first-party sessions are not affected.
|
*/
'expiration' => null,
/*
|--------------------------------------------------------------------------
| Token Prefix
|--------------------------------------------------------------------------
|
| Sanctum can prefix new tokens in order to take advantage of numerous
| security scanning initiatives maintained by open source platforms
| that notify developers if they commit tokens into repositories.
|
| See: https://docs.github.com/en/code-security/secret-scanning/about-secret-scanning
|
*/
'token_prefix' => env('SANCTUM_TOKEN_PREFIX', ''),
/*
|--------------------------------------------------------------------------
| Sanctum Middleware
|--------------------------------------------------------------------------
|
| When authenticating your first-party SPA with Sanctum you may need to
| customize some of the middleware Sanctum uses while processing the
| request. You may change the middleware listed below as required.
|
*/
'middleware' => [
'authenticate_session' => Laravel\Sanctum\Http\Middleware\AuthenticateSession::class,
'encrypt_cookies' => Illuminate\Cookie\Middleware\EncryptCookies::class,
'validate_csrf_token' => Illuminate\Foundation\Http\Middleware\ValidateCsrfToken::class,
],
];

38
config/services.php Normal file
View File

@ -0,0 +1,38 @@
<?php
return [
/*
|--------------------------------------------------------------------------
| Third Party Services
|--------------------------------------------------------------------------
|
| This file is for storing the credentials for third party services such
| as Mailgun, Postmark, AWS and more. This file provides the de facto
| location for this type of information, allowing packages to have
| a conventional file to locate the various service credentials.
|
*/
'postmark' => [
'token' => env('POSTMARK_TOKEN'),
],
'resend' => [
'key' => env('RESEND_KEY'),
],
'ses' => [
'key' => env('AWS_ACCESS_KEY_ID'),
'secret' => env('AWS_SECRET_ACCESS_KEY'),
'region' => env('AWS_DEFAULT_REGION', 'us-east-1'),
],
'slack' => [
'notifications' => [
'bot_user_oauth_token' => env('SLACK_BOT_USER_OAUTH_TOKEN'),
'channel' => env('SLACK_BOT_USER_DEFAULT_CHANNEL'),
],
],
];

217
config/session.php Normal file
View File

@ -0,0 +1,217 @@
<?php
use Illuminate\Support\Str;
return [
/*
|--------------------------------------------------------------------------
| Default Session Driver
|--------------------------------------------------------------------------
|
| This option determines the default session driver that is utilized for
| incoming requests. Laravel supports a variety of storage options to
| persist session data. Database storage is a great default choice.
|
| Supported: "file", "cookie", "database", "memcached",
| "redis", "dynamodb", "array"
|
*/
'driver' => env('SESSION_DRIVER', 'database'),
/*
|--------------------------------------------------------------------------
| Session Lifetime
|--------------------------------------------------------------------------
|
| Here you may specify the number of minutes that you wish the session
| to be allowed to remain idle before it expires. If you want them
| to expire immediately when the browser is closed then you may
| indicate that via the expire_on_close configuration option.
|
*/
'lifetime' => (int) env('SESSION_LIFETIME', 120),
'expire_on_close' => env('SESSION_EXPIRE_ON_CLOSE', false),
/*
|--------------------------------------------------------------------------
| Session Encryption
|--------------------------------------------------------------------------
|
| This option allows you to easily specify that all of your session data
| should be encrypted before it's stored. All encryption is performed
| automatically by Laravel and you may use the session like normal.
|
*/
'encrypt' => env('SESSION_ENCRYPT', false),
/*
|--------------------------------------------------------------------------
| Session File Location
|--------------------------------------------------------------------------
|
| When utilizing the "file" session driver, the session files are placed
| on disk. The default storage location is defined here; however, you
| are free to provide another location where they should be stored.
|
*/
'files' => storage_path('framework/sessions'),
/*
|--------------------------------------------------------------------------
| Session Database Connection
|--------------------------------------------------------------------------
|
| When using the "database" or "redis" session drivers, you may specify a
| connection that should be used to manage these sessions. This should
| correspond to a connection in your database configuration options.
|
*/
'connection' => env('SESSION_CONNECTION'),
/*
|--------------------------------------------------------------------------
| Session Database Table
|--------------------------------------------------------------------------
|
| When using the "database" session driver, you may specify the table to
| be used to store sessions. Of course, a sensible default is defined
| for you; however, you're welcome to change this to another table.
|
*/
'table' => env('SESSION_TABLE', 'sessions'),
/*
|--------------------------------------------------------------------------
| Session Cache Store
|--------------------------------------------------------------------------
|
| When using one of the framework's cache driven session backends, you may
| define the cache store which should be used to store the session data
| between requests. This must match one of your defined cache stores.
|
| Affects: "dynamodb", "memcached", "redis"
|
*/
'store' => env('SESSION_STORE'),
/*
|--------------------------------------------------------------------------
| Session Sweeping Lottery
|--------------------------------------------------------------------------
|
| Some session drivers must manually sweep their storage location to get
| rid of old sessions from storage. Here are the chances that it will
| happen on a given request. By default, the odds are 2 out of 100.
|
*/
'lottery' => [2, 100],
/*
|--------------------------------------------------------------------------
| Session Cookie Name
|--------------------------------------------------------------------------
|
| Here you may change the name of the session cookie that is created by
| the framework. Typically, you should not need to change this value
| since doing so does not grant a meaningful security improvement.
|
*/
'cookie' => env(
'SESSION_COOKIE',
Str::slug(env('APP_NAME', 'laravel')).'-session'
),
/*
|--------------------------------------------------------------------------
| Session Cookie Path
|--------------------------------------------------------------------------
|
| The session cookie path determines the path for which the cookie will
| be regarded as available. Typically, this will be the root path of
| your application, but you're free to change this when necessary.
|
*/
'path' => env('SESSION_PATH', '/'),
/*
|--------------------------------------------------------------------------
| Session Cookie Domain
|--------------------------------------------------------------------------
|
| This value determines the domain and subdomains the session cookie is
| available to. By default, the cookie will be available to the root
| domain and all subdomains. Typically, this shouldn't be changed.
|
*/
'domain' => env('SESSION_DOMAIN'),
/*
|--------------------------------------------------------------------------
| HTTPS Only Cookies
|--------------------------------------------------------------------------
|
| By setting this option to true, session cookies will only be sent back
| to the server if the browser has a HTTPS connection. This will keep
| the cookie from being sent to you when it can't be done securely.
|
*/
'secure' => env('SESSION_SECURE_COOKIE'),
/*
|--------------------------------------------------------------------------
| HTTP Access Only
|--------------------------------------------------------------------------
|
| Setting this value to true will prevent JavaScript from accessing the
| value of the cookie and the cookie will only be accessible through
| the HTTP protocol. It's unlikely you should disable this option.
|
*/
'http_only' => env('SESSION_HTTP_ONLY', true),
/*
|--------------------------------------------------------------------------
| Same-Site Cookies
|--------------------------------------------------------------------------
|
| This option determines how your cookies behave when cross-site requests
| take place, and can be used to mitigate CSRF attacks. By default, we
| will set this value to "lax" to permit secure cross-site requests.
|
| See: https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/Set-Cookie#samesitesamesite-value
|
| Supported: "lax", "strict", "none", null
|
*/
'same_site' => env('SESSION_SAME_SITE', 'lax'),
/*
|--------------------------------------------------------------------------
| Partitioned Cookies
|--------------------------------------------------------------------------
|
| Setting this value to true will tie the cookie to the top-level site for
| a cross-site context. Partitioned cookies are accepted by the browser
| when flagged "secure" and the Same-Site attribute is set to "none".
|
*/
'partitioned' => env('SESSION_PARTITIONED_COOKIE', false),
];

1
database/.gitignore vendored Normal file
View File

@ -0,0 +1 @@
*.sqlite*

View File

@ -0,0 +1,24 @@
<?php
namespace Database\Factories;
use Illuminate\Database\Eloquent\Factories\Factory;
/**
* @extends \Illuminate\Database\Eloquent\Factories\Factory<\App\Models\Foto>
*/
class FotoFactory extends Factory
{
/**
* Define the model's default state.
*
* @return array<string, mixed>
*/
public function definition(): array
{
return [
'id_produk' => \App\Models\Produk::factory(),
'url' => $this->faker->imageUrl(),
];
}
}

View File

@ -0,0 +1,25 @@
<?php
namespace Database\Factories;
use Illuminate\Database\Eloquent\Factories\Factory;
/**
* @extends \Illuminate\Database\Eloquent\Factories\Factory<\App\Models\Item>
*/
class ItemFactory extends Factory
{
/**
* Define the model's default state.
*
* @return array<string, mixed>
*/
public function definition(): array
{
return [
'id_produk' => \App\Models\Produk::factory(),
'id_nampan' => null,
'is_sold' => false,
];
}
}

View File

@ -0,0 +1,28 @@
<?php
namespace Database\Factories;
use App\Models\Item;
use App\Models\Transaksi;
use Illuminate\Database\Eloquent\Factories\Factory;
/**
* @extends \Illuminate\Database\Eloquent\Factories\Factory<\App\Models\ItemTransaksi>
*/
class ItemTransaksiFactory extends Factory
{
/**
* Define the model's default state.
*
* @return array<string, mixed>
*/
public function definition(): array
{
return [
'id_transaksi' => Transaksi::factory(),
'id_item' => Item::factory(),
'harga_deal' => $this->faker->randomFloat(2, 100000, 5000000),
'created_at' => now(),
];
}
}

View File

@ -0,0 +1,23 @@
<?php
namespace Database\Factories;
use Illuminate\Database\Eloquent\Factories\Factory;
/**
* @extends \Illuminate\Database\Eloquent\Factories\Factory<\App\Models\Nampan>
*/
class NampanFactory extends Factory
{
/**
* Define the model's default state.
*
* @return array<string, mixed>
*/
public function definition(): array
{
return [
'nama' => $this->faker->unique()->word(),
];
}
}

View File

@ -0,0 +1,30 @@
<?php
namespace Database\Factories;
use Illuminate\Database\Eloquent\Factories\Factory;
/**
* @extends \Illuminate\Database\Eloquent\Factories\Factory<\App\Models\Produk>
*/
class ProdukFactory extends Factory
{
/**
* Define the model's default state.
*
* @return array<string, mixed>
*/
public function definition(): array
{
$harga_per_gram = $this->faker->numberBetween(80, 120) * 10000;
$berat = $this->faker->randomFloat(2, 1, 10);
return [
'nama' => $this->faker->words(3, true),
'kategori' => $this->faker->randomElement(['cincin', 'gelang', 'kalung', 'anting']),
'berat' => $berat,
'kadar' => $this->faker->numberBetween(10, 24),
'harga_per_gram' => $harga_per_gram,
'harga_jual' => $harga_per_gram * $berat,
];
}
}

View File

@ -0,0 +1,25 @@
<?php
namespace Database\Factories;
use Illuminate\Database\Eloquent\Factories\Factory;
/**
* @extends \Illuminate\Database\Eloquent\Factories\Factory<\App\Models\Sales>
*/
class SalesFactory extends Factory
{
/**
* Define the model's default state.
*
* @return array<string, mixed>
*/
public function definition(): array
{
return [
'nama' => $this->faker->unique()->name(),
'no_hp' => $this->faker->phoneNumber(),
'alamat' => $this->faker->address(),
];
}
}

View File

@ -0,0 +1,36 @@
<?php
namespace Database\Factories;
use App\Models\Sales;
use App\Models\User;
use Illuminate\Database\Eloquent\Factories\Factory;
/**
* @extends \Illuminate\Database\Eloquent\Factories\Factory<\App\Models\Transaksi>
*/
class TransaksiFactory extends Factory
{
/**
* Define the model's default state.
*
* @return array<string, mixed>
*/
public function definition(): array
{
$sales = Sales::inRandomOrder()->first();
$kasir = User::inRandomOrder()->first();
return [
'id_kasir' => $kasir?->id,
'id_sales' => $sales?->id,
'nama_sales' => $sales?->nama ?? $this->faker->name(),
'no_hp' => $this->faker->phoneNumber(),
'alamat' => $this->faker->address(),
'ongkos_bikin' => $this->faker->randomFloat(2, 0, 1000000),
'total_harga' => $this->faker->randomFloat(2, 100000, 5000000),
'created_at' => now(),
];
}
}

View File

@ -0,0 +1,42 @@
<?php
namespace Database\Factories;
use Illuminate\Database\Eloquent\Factories\Factory;
use Illuminate\Support\Facades\Hash;
use Illuminate\Support\Str;
/**
* @extends \Illuminate\Database\Eloquent\Factories\Factory<\App\Models\User>
*/
class UserFactory extends Factory
{
/**
* The current password being used by the factory.
*/
protected static ?string $password;
/**
* Define the model's default state.
*
* @return array<string, mixed>
*/
public function definition(): array
{
return [
'nama' => fake()->name(),
'password' => static::$password ??= Hash::make('password'),
'role' => 'kasir',
];
}
/**
* Indicate that the model's email address should be unverified.
*/
public function unverified(): static
{
return $this->state(fn (array $attributes) => [
'email_verified_at' => null,
]);
}
}

View File

@ -0,0 +1,48 @@
<?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('users', function (Blueprint $table) {
$table->id();
$table->string('nama', 80)->unique();
$table->string('password');
$table->enum('role', ['owner', 'kasir']);
$table->timestamps();
$table->softDeletes();
});
Schema::create('password_reset_tokens', function (Blueprint $table) {
$table->string('email')->primary();
$table->string('token');
$table->timestamp('created_at')->nullable();
});
Schema::create('sessions', function (Blueprint $table) {
$table->string('id')->primary();
$table->foreignId('user_id')->nullable()->index();
$table->string('ip_address', 45)->nullable();
$table->text('user_agent')->nullable();
$table->longText('payload');
$table->integer('last_activity')->index();
});
}
/**
* Reverse the migrations.
*/
public function down(): void
{
Schema::dropIfExists('users');
Schema::dropIfExists('password_reset_tokens');
Schema::dropIfExists('sessions');
}
};

View File

@ -0,0 +1,35 @@
<?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('cache', function (Blueprint $table) {
$table->string('key')->primary();
$table->mediumText('value');
$table->integer('expiration');
});
Schema::create('cache_locks', function (Blueprint $table) {
$table->string('key')->primary();
$table->string('owner');
$table->integer('expiration');
});
}
/**
* Reverse the migrations.
*/
public function down(): void
{
Schema::dropIfExists('cache');
Schema::dropIfExists('cache_locks');
}
};

View File

@ -0,0 +1,57 @@
<?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('jobs', function (Blueprint $table) {
$table->id();
$table->string('queue')->index();
$table->longText('payload');
$table->unsignedTinyInteger('attempts');
$table->unsignedInteger('reserved_at')->nullable();
$table->unsignedInteger('available_at');
$table->unsignedInteger('created_at');
});
Schema::create('job_batches', function (Blueprint $table) {
$table->string('id')->primary();
$table->string('name');
$table->integer('total_jobs');
$table->integer('pending_jobs');
$table->integer('failed_jobs');
$table->longText('failed_job_ids');
$table->mediumText('options')->nullable();
$table->integer('cancelled_at')->nullable();
$table->integer('created_at');
$table->integer('finished_at')->nullable();
});
Schema::create('failed_jobs', function (Blueprint $table) {
$table->id();
$table->string('uuid')->unique();
$table->text('connection');
$table->text('queue');
$table->longText('payload');
$table->longText('exception');
$table->timestamp('failed_at')->useCurrent();
});
}
/**
* Reverse the migrations.
*/
public function down(): void
{
Schema::dropIfExists('jobs');
Schema::dropIfExists('job_batches');
Schema::dropIfExists('failed_jobs');
}
};

View File

@ -0,0 +1,33 @@
<?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('personal_access_tokens', function (Blueprint $table) {
$table->id();
$table->morphs('tokenable');
$table->text('name');
$table->string('token', 64)->unique();
$table->text('abilities')->nullable();
$table->timestamp('last_used_at')->nullable();
$table->timestamp('expires_at')->nullable()->index();
$table->timestamps();
});
}
/**
* Reverse the migrations.
*/
public function down(): void
{
Schema::dropIfExists('personal_access_tokens');
}
};

View File

@ -0,0 +1,33 @@
<?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('personal_access_tokens', function (Blueprint $table) {
$table->id();
$table->morphs('tokenable');
$table->text('name');
$table->string('token', 64)->unique();
$table->text('abilities')->nullable();
$table->timestamp('last_used_at')->nullable();
$table->timestamp('expires_at')->nullable()->index();
$table->timestamps();
});
}
/**
* Reverse the migrations.
*/
public function down(): void
{
Schema::dropIfExists('personal_access_tokens');
}
};

View File

@ -0,0 +1,34 @@
<?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('produks', function (Blueprint $table) {
$table->id();
$table->string('nama', 100);
$table->enum('kategori', ['cincin', 'gelang', 'kalung', 'anting']);
$table->float('berat');
$table->integer('kadar');
$table->double('harga_per_gram');
$table->double('harga_jual');
$table->timestamps();
$table->softDeletes();
});
}
/**
* Reverse the migrations.
*/
public function down(): void
{
Schema::dropIfExists('produks');
}
};

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::create('fotos', function (Blueprint $table) {
$table->id();
$table->foreignId('id_produk')->constrained('produks')->cascadeOnDelete();
$table->string('url');
$table->timestamps();
});
}
/**
* Reverse the migrations.
*/
public function down(): void
{
Schema::dropIfExists('fotos');
}
};

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::create('nampans', function (Blueprint $table) {
$table->id();
$table->string('nama', 100)->unique();
$table->timestamps();
});
}
/**
* Reverse the migrations.
*/
public function down(): void
{
Schema::dropIfExists('nampans');
}
};

View File

@ -0,0 +1,30 @@
<?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('items', function (Blueprint $table) {
$table->id();
$table->foreignId('id_produk')->constrained('produks')->cascadeOnDelete();
$table->foreignId('id_nampan')->nullable()->constrained('nampans');
$table->boolean('is_sold')->default(false);
$table->timestamps();
});
}
/**
* Reverse the migrations.
*/
public function down(): void
{
Schema::dropIfExists('items');
}
};

View File

@ -0,0 +1,30 @@
<?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('sales', function (Blueprint $table) {
$table->id();
$table->string('nama', 80)->unique();
$table->string('no_hp', 20);
$table->string('alamat', 100);
$table->timestamps();
});
}
/**
* Reverse the migrations.
*/
public function down(): void
{
Schema::dropIfExists('sales');
}
};

View File

@ -0,0 +1,34 @@
<?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('transaksis', function (Blueprint $table) {
$table->id();
$table->foreignId('id_kasir')->constrained('users');
$table->foreignId('id_sales')->nullable()->constrained('sales');
$table->string('nama_sales', 100);
$table->string('no_hp', 20);
$table->string('alamat', 100);
$table->double('ongkos_bikin')->nullable();
$table->double('total_harga');
$table->timestamps();
});
}
/**
* Reverse the migrations.
*/
public function down(): void
{
Schema::dropIfExists('transaksis');
}
};

View File

@ -0,0 +1,30 @@
<?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('item_transaksis', function (Blueprint $table) {
$table->id();
$table->foreignId('id_transaksi')->constrained('transaksis')->onDelete('cascade');
$table->foreignId('id_item')->constrained('items');
$table->double('harga_deal');
$table->timestamps();
});
}
/**
* Reverse the migrations.
*/
public function down(): void
{
Schema::dropIfExists('item_transaksis');
}
};

View File

@ -0,0 +1,33 @@
<?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('personal_access_tokens', function (Blueprint $table) {
$table->id();
$table->morphs('tokenable');
$table->text('name');
$table->string('token', 64)->unique();
$table->text('abilities')->nullable();
$table->timestamp('last_used_at')->nullable();
$table->timestamp('expires_at')->nullable()->index();
$table->timestamps();
});
}
/**
* Reverse the migrations.
*/
public function down(): void
{
Schema::dropIfExists('personal_access_tokens');
}
};

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::create('foto_sementaras', function (Blueprint $table) {
$table->id();
$table->foreignId('id_user')->constrained('users')->onDelete('cascade');
$table->string('url');
$table->timestamps();
});
}
/**
* Reverse the migrations.
*/
public function down(): void
{
Schema::dropIfExists('foto_sementaras');
}
};

View File

@ -0,0 +1,84 @@
<?php
namespace Database\Seeders;
use App\Models\Item;
use App\Models\Nampan;
use App\Models\Produk;
use App\Models\Sales;
use App\Models\Transaksi;
use App\Models\User;
// use Illuminate\Database\Console\Seeds\WithoutModelEvents;
use Illuminate\Database\Seeder;
class DatabaseSeeder extends Seeder
{
/**
* Seed the application's database.
*/
public function run(): void
{
User::factory()->create([
'nama' => 'Test User',
'role' => 'owner',
'password' => bcrypt('123123123'),
]);
User::factory(2)->create();
Sales::factory(5)->create();
$kodeNampan = ['A', 'B'];
foreach ($kodeNampan as $kode) {
for ($i=0; $i < 4; $i++) {
Nampan::factory()->create([
'nama' => $kode . ($i + 1) // A1, A2, ... B4
]);
}
}
Produk::factory(10)->create()->each(function ($produk) {
// setiap produk punya 1-3 foto
$jumlah_foto = rand(1, 3);
$fotoData = [];
for ($i = 0; $i < $jumlah_foto; $i++) {
$fotoData[] = [
'url' => 'https://random-image-pepebigotes.vercel.app/api/random-image'
];
}
$produk->foto()->createMany($fotoData);
$jumlah_item = rand(1, 20);
Item::factory($jumlah_item)->create([
'id_produk' => $produk->id,
'is_sold' => false,
]);
});
// 30% peluang item masuk nampan, sisanya di brankas
$nampans = Nampan::all()->pluck('id')->toArray();
$jumlahNampan = count($nampans);
$counter = 0;
foreach (Item::all() as $item) {
if (rand(1, 100) <= 30) {
$item->update([
'id_nampan' => $nampans[$counter % $jumlahNampan],
]);
$counter++;
}
}
Transaksi::factory(20)->create()->each(function ($transaksi) {
$jumlah_item = rand(1, 5);
$items = Item::where('is_sold', false)->inRandomOrder()->limit($jumlah_item)->get();
if ($items->isEmpty()) return;
foreach ($items as $item) {
$transaksi->itemTransaksi()->create([
'id_item' => $item->id,
'harga_deal' => $item->produk->harga_jual,
]);
$item->update(['is_sold' => true]);
}
});
}
}

2675
package-lock.json generated Normal file

File diff suppressed because it is too large Load Diff

23
package.json Normal file
View File

@ -0,0 +1,23 @@
{
"$schema": "https://json.schemastore.org/package.json",
"private": true,
"type": "module",
"scripts": {
"build": "vite build",
"dev": "vite"
},
"devDependencies": {
"@tailwindcss/vite": "^4.0.0",
"@vitejs/plugin-vue": "^6.0.1",
"axios": "^1.11.0",
"concurrently": "^9.0.1",
"laravel-vite-plugin": "^2.0.0",
"tailwindcss": "^4.0.0",
"vite": "^7.0.4"
},
"dependencies": {
"vue": "^3.5.19",
"vue-router": "^4.5.1",
"vuex": "^4.1.0"
}
}

34
phpunit.xml Normal file
View File

@ -0,0 +1,34 @@
<?xml version="1.0" encoding="UTF-8"?>
<phpunit xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:noNamespaceSchemaLocation="vendor/phpunit/phpunit/phpunit.xsd"
bootstrap="vendor/autoload.php"
colors="true"
>
<testsuites>
<testsuite name="Unit">
<directory>tests/Unit</directory>
</testsuite>
<testsuite name="Feature">
<directory>tests/Feature</directory>
</testsuite>
</testsuites>
<source>
<include>
<directory>app</directory>
</include>
</source>
<php>
<env name="APP_ENV" value="testing"/>
<env name="APP_MAINTENANCE_DRIVER" value="file"/>
<env name="BCRYPT_ROUNDS" value="4"/>
<env name="CACHE_STORE" value="array"/>
<env name="DB_CONNECTION" value="sqlite"/>
<env name="DB_DATABASE" value=":memory:"/>
<env name="MAIL_MAILER" value="array"/>
<env name="QUEUE_CONNECTION" value="sync"/>
<env name="SESSION_DRIVER" value="array"/>
<env name="PULSE_ENABLED" value="false"/>
<env name="TELESCOPE_ENABLED" value="false"/>
<env name="NIGHTWATCH_ENABLED" value="false"/>
</php>
</phpunit>

25
public/.htaccess Normal file
View File

@ -0,0 +1,25 @@
<IfModule mod_rewrite.c>
<IfModule mod_negotiation.c>
Options -MultiViews -Indexes
</IfModule>
RewriteEngine On
# Handle Authorization Header
RewriteCond %{HTTP:Authorization} .
RewriteRule .* - [E=HTTP_AUTHORIZATION:%{HTTP:Authorization}]
# Handle X-XSRF-Token Header
RewriteCond %{HTTP:x-xsrf-token} .
RewriteRule .* - [E=HTTP_X_XSRF_TOKEN:%{HTTP:X-XSRF-Token}]
# Redirect Trailing Slashes If Not A Folder...
RewriteCond %{REQUEST_FILENAME} !-d
RewriteCond %{REQUEST_URI} (.+)/$
RewriteRule ^ %1 [L,R=301]
# Send Requests To Front Controller...
RewriteCond %{REQUEST_FILENAME} !-d
RewriteCond %{REQUEST_FILENAME} !-f
RewriteRule ^ index.php [L]
</IfModule>

0
public/favicon.ico Normal file
View File

20
public/index.php Normal file
View File

@ -0,0 +1,20 @@
<?php
use Illuminate\Foundation\Application;
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...
require __DIR__.'/../vendor/autoload.php';
// Bootstrap Laravel and handle the request...
/** @var Application $app */
$app = require_once __DIR__.'/../bootstrap/app.php';
$app->handleRequest(Request::capture());

2
public/robots.txt Normal file
View File

@ -0,0 +1,2 @@
User-agent: *
Disallow:

24
resources/css/app.css Normal file
View File

@ -0,0 +1,24 @@
@import 'tailwindcss';
@source '../../vendor/laravel/framework/src/Illuminate/Pagination/resources/views/*.blade.php';
@source '../../storage/framework/views/*.php';
@source '../**/*.blade.php';
@source '../**/*.js';
@import url('https://fonts.googleapis.com/css2?family=Platypi:wght@400;500;600;700&display=swap');
html, body {
font-family: "Platypi", sans-serif;
}
@theme {
--font-sans: 'Instrument Sans', ui-sans-serif, system-ui, sans-serif, 'Apple Color Emoji', 'Segoe UI Emoji',
'Segoe UI Symbol', 'Noto Color Emoji';
}
@theme {
--color-A: #F8F0E5;
--color-B: #EADBC8;
--color-C: #DAC0A3;
--color-D: #0F2C59;
}

5
resources/js/App.vue Normal file
View File

@ -0,0 +1,5 @@
<template>
<div id="app">
<router-view />
</div>
</template>

9
resources/js/app.js Normal file
View File

@ -0,0 +1,9 @@
// import './bootstrap';
import { createApp } from 'vue';
import router from './router';
import App from './App.vue';
const app = createApp(App);
app.use(router);
app.mount('#app');

4
resources/js/bootstrap.js vendored Normal file
View File

@ -0,0 +1,4 @@
import axios from 'axios';
window.axios = axios;
window.axios.defaults.headers.common['X-Requested-With'] = 'XMLHttpRequest';

View File

@ -0,0 +1,64 @@
<template>
<div class="grid grid-cols-1 md:grid-cols-2 lg:grid-cols-3 xl:grid-cols-4 gap-4">
<div
v-for="item in filteredItems"
:key="item.id"
class="flex justify-between items-center border rounded-lg p-3 shadow-sm hover:shadow-md transition"
>
<!-- Gambar -->
<div class="flex items-center gap-3">
<img
:src="item.image"
alt="Product Image"
class="w-12 h-12 object-contain"
/>
<!-- Info produk -->
<div>
<p class="font-semibold">{{ item.produk.nama }}</p>
<p class="text-sm text-gray-500">{{ item.produk.id }}</p>
</div>
</div>
<!-- Berat -->
<span class="font-medium">{{ item.berat }}g</span>
</div>
</div>
</template>
<script setup>
import { ref, computed, onMounted } from "vue";
import axios from "axios";
const props = defineProps({
search: {
type: String,
default: "",
},
});
const items = ref([]);
const loading = ref(true);
const error = ref(null);
onMounted(async () => {
try {
const res = await axios.get("/api/item"); // ganti sesuai URL backend
items.value = res.data; // pastikan backend return array of items
console.log(res.data);
} catch (err) {
error.value = err.message || "Gagal mengambil data";
} finally {
loading.value = false;
}
});
const filteredItems = computed(() => {
if (!props.search) return items.value;
return items.value.filter((item) =>
item.produk?.nama?.toLowerCase().includes(props.search.toLowerCase())
);
});
</script>

View File

@ -0,0 +1,17 @@
<script setup>
const items = ['Manajemen Produk', 'Kasir', 'Laporan', 'Akun'];
</script>
<template>
<div class="h-25 shadow-lg shadow-D rounded-b-md">
<div class="bg-D h-5 rounded-b-md shadow-lg">
<div class="h-15"></div>
<div class="w-full px-50 flex justify-between items-center h-5">
<router-link to="/" v-for="item in items"
class="text-center text-lg text-D hover:underline cursor-pointer">
{{ item }}
</router-link>
</div>
</div>
</div>
</template>

View File

@ -0,0 +1,65 @@
<template>
<div>
<!-- Card Produk -->
<div
class="border border-C rounded-md aspect-square flex items-center justify-center hover:shadow-md transition cursor-pointer"
@click="showDetail = true"
>
<span class="text-gray-700 font-medium text-center px-2">
{{ product.nama }}
</span>
</div>
<!-- Overlay Detail -->
<div
v-if="showDetail"
class="fixed inset-0 bg-black bg-opacity-50 flex items-center justify-center z-50"
>
<div
class="bg-white rounded-lg shadow-lg w-[90%] max-w-md p-6 relative"
>
<!-- Tombol Close -->
<button
class="absolute top-3 right-3 text-gray-500 hover:text-gray-800"
@click="showDetail = false"
>
</button>
<!-- Judul -->
<h2 class="text-xl font-semibold text-D mb-4 text-center">
Detail Produk
</h2>
<!-- Data Produk -->
<div class="space-y-2 text-gray-700">
<p><span class="font-semibold">Nama:</span> {{ product.nama }}</p>
<p><span class="font-semibold">Kategori:</span> {{ product.kategori }}</p>
<p><span class="font-semibold">Berat:</span> {{ product.berat }} gram</p>
<p><span class="font-semibold">Kadar:</span> {{ product.kadar }}%</p>
<p><span class="font-semibold">Harga/gram:</span> Rp {{ formatHarga(product.harga_per_gram) }}</p>
<p><span class="font-semibold">Harga Jual:</span> Rp {{ formatHarga(product.harga_jual) }}</p>
<p><span class="font-semibold">Stok:</span> {{ product.items_count }} pcs</p>
</div>
</div>
</div>
</div>
</template>
<script setup>
import { ref } from "vue";
const props = defineProps({
product: {
type: Object,
required: true,
},
});
const showDetail = ref(false);
// Format rupiah
function formatHarga(value) {
return new Intl.NumberFormat("id-ID").format(value);
}
</script>

View File

@ -0,0 +1,118 @@
<template>
<div>
<!-- Loading -->
<div v-if="loading" class="text-center py-6">Loading...</div>
<!-- Error -->
<div v-else-if="error" class="text-center text-red-500 py-6">{{ error }}</div>
<!-- Kalau hasil search kosong -->
<div
v-else-if="filteredTrays.length === 0"
class="text-center text-gray-500 py-6"
>
Nampan tidak ditemukan.
</div>
<!-- Grid nampan -->
<div
v-else
class="grid grid-cols-1 md:grid-cols-2 lg:grid-cols-3 xl:grid-cols-4 gap-4"
>
<div
v-for="tray in filteredTrays"
:key="tray.id"
class="border rounded-lg p-4 shadow-sm hover:shadow-md transition"
>
<!-- Header Nampan -->
<div class="flex justify-between items-center mb-3">
<h2 class="font-bold text-lg">{{ tray.nama }}</h2>
<div class="flex gap-2">
<button class="bg-yellow-300 p-1 rounded"></button>
<button class="bg-red-500 text-white p-1 rounded">🗑</button>
</div>
</div>
<!-- Isi Nampan -->
<div v-if="tray.items && tray.items.length > 0" class="space-y-2">
<div
v-for="item in tray.items"
:key="item.id"
class="flex justify-between items-center border rounded-lg p-2"
>
<!-- Gambar + Info -->
<div class="flex items-center gap-3">
<img
:src="item.image"
alt="Product Image"
class="w-12 h-12 object-contain"
/>
<div>
<p class="font-semibold">{{ item.produk.nama }}</p>
<p class="text-sm text-gray-500">{{ item.produk.id }}</p>
</div>
</div>
<!-- Berat -->
<span class="font-medium">{{ item.berat }}g</span>
</div>
</div>
<!-- Kalau nampan kosong -->
<div v-else class="text-gray-400 text-center py-4">
Nampan kosong.<br />
Masuk ke menu <b>Brankas</b> untuk memindahkan item ke nampan.
</div>
<!-- Total Berat -->
<div class="border-t mt-3 pt-2 text-right font-semibold">
Berat Total: {{ totalWeight(tray) }}g
</div>
</div>
</div>
</div>
</template>
<script setup>
import { ref, onMounted, computed } from "vue";
import axios from "axios";
// terima search dari parent
const props = defineProps({
search: {
type: String,
default: "",
},
});
const trays = ref([]);
const loading = ref(true);
const error = ref(null);
// hitung total berat
const totalWeight = (tray) => {
if (!tray.items) return 0;
return tray.items.reduce((sum, item) => sum + (item.berat || 0), 0);
};
// ambil data dari backend
onMounted(async () => {
try {
const res = await axios.get("/api/nampan");
trays.value = res.data; // harus array tray dengan items
console.log("Data nampan:", res.data);
} catch (err) {
error.value = err.message || "Gagal mengambil data";
} finally {
loading.value = false;
}
});
// filter berdasarkan nama nampan
const filteredTrays = computed(() => {
if (!props.search) return trays.value;
return trays.value.filter((tray) =>
tray.nama.toLowerCase().includes(props.search.toLowerCase())
);
});
</script>

View File

@ -0,0 +1,17 @@
<template>
<div class="flex justify-end mb-4">
<input
v-model="searchText"
type="text"
placeholder="Cari ..."
class="border rounded-md px-3 py-2 w-64 focus:outline-none focus:ring-2 focus:ring-blue-400"
@input="$emit('update:search', searchText)"
/>
</div>
</template>
<script setup>
import { ref } from "vue";
const searchText = ref("");
defineEmits(["update:search"]);
</script>

View File

@ -0,0 +1,10 @@
<template>
<Header />
<div class="mx-2 md:mx-4 lg:mx-6 xl:mx-7 my-6">
<slot />
</div>
</template>
<script setup>
import Header from '../components/Header.vue'
</script>

View File

@ -0,0 +1,16 @@
<template>
<mainLayout>
<p style="font-family: 'IM FELL Great Primer', serif; font-style: italic;font-size: 25px;">BRANKAS</p>
<searchbar v-model:search="searchQuery" />
<BrankasList :search="searchQuery" />
</mainLayout>
</template>
<script setup>
import { ref } from 'vue';
import mainLayout from '../layouts/mainLayout.vue'
import searchbar from '../components/searchbar.vue';
import BrankasList from '../components/BrankasList.vue';
const searchQuery = ref("");
</script>

View File

@ -0,0 +1,45 @@
<template>
<mainLayout>
<div class="home">
<h1 class="text-3xl font-bold text-D mb-4">Contoh penggunaan halaman</h1>
<div class="message-model">
<p>{{ message }}</p>
</div>
<hr class="my-6 border-D" />
<h1 class="text-xl font-bold text-D mb-4">Contoh grid</h1>
<div class="grid grid-cols-1 sm:grid-cols-2 md:grid-cols-3 gap-4">
<div v-for="value in data" :key="value" class="p-5 shadow-lg rounded-lg shadow-C bg-A text-D text-lg">
Item: {{ value }}
</div>
</div>
</div>
</mainLayout>
</template>
<script setup>
import { ref } from 'vue'
import mainLayout from '../layouts/mainLayout.vue'
const message = ref("Style dan message dari script dan style di dalam halaman")
const data = ref([1, 2, 3, 4, 5])
</script>
<style scoped>
.message-model {
border: 1px solid yellow;
text-align: center;
border-radius: 10px;
width: 80%;
margin: auto;
background-color: yellow;
padding: 20px;
}
.message-model p {
font-weight: bold;
font-size: 24px;
}
</style>

View File

@ -0,0 +1,153 @@
<template>
<mainLayout>
<div class="p-6">
<!-- Judul -->
<p class="font-serif italic text-[25px] text-D">PRODUK</p>
<!-- Search -->
<searchbar v-model:search="searchQuery" />
<!-- Tombol Tambah Produk -->
<div class="mt-3 flex justify-end">
<button
class="bg-B text-[#0a1a3c] px-4 py-2 rounded-md shadow hover:bg-C transition"
>
Tambah Produk
</button>
</div>
<!-- Grid Produk -->
<div class="grid grid-cols-2 md:grid-cols-4 lg:grid-cols-6 gap-4 mt-4">
<ProductCard
v-for="item in filteredProducts"
:key="item.id"
:product="item"
@showDetail="openOverlay"
/>
</div>
</div>
<!-- Overlay Detail Produk -->
<div
v-if="showOverlay"
class="fixed inset-0 bg-black bg-opacity-50 flex justify-center items-center z-50"
@click.self="closeOverlay"
>
<div
class="bg-white rounded-lg shadow-lg p-6 w-[400px] border-2 border-[#e6d3b3] relative"
>
<!-- Tombol Close -->
<button
@click="closeOverlay"
class="absolute top-2 right-2 text-gray-500 hover:text-black"
>
</button>
<!-- Foto Produk -->
<div class="border border-[#e6d3b3] p-2 mb-4 flex justify-center">
<img
v-if="detail.gambar"
:src="`http://127.0.0.1:8000/storage/${detail.gambar}`"
:alt="detail.nama"
class="w-40 h-40 object-contain"
/>
<span v-else class="text-gray-400 text-sm">[gambar]</span>
</div>
<!-- Stok -->
<p class="text-sm mb-1">{{ detail.item_count }} pcs</p>
<!-- Nama Produk -->
<h2 class="text-xl font-semibold text-center mb-3">
{{ detail.nama }}
</h2>
<!-- Detail Harga & Info -->
<div class="grid grid-cols-2 gap-2 text-sm mb-4">
<p>Harga Beli : Rp. {{ formatNumber(detail.harga_beli) }}</p>
<p class="text-right">{{ detail.kadar }} K</p>
<p>Harga Jual : Rp. {{ formatNumber(detail.harga_jual) }}</p>
<p class="text-right">{{ detail.berat }} gram</p>
<p class="col-span-2">
Harga/gram : Rp. {{ formatNumber(detail.harga_per_gram) }}
</p>
</div>
<!-- Tombol Aksi -->
<div class="flex justify-between">
<button
class="bg-yellow-400 text-black px-4 py-2 rounded font-bold"
>
Ubah
</button>
<button
class="bg-green-400 text-black px-4 py-2 rounded font-bold"
>
Tambah
</button>
<button
class="bg-red-500 text-white px-4 py-2 rounded font-bold"
>
Hapus
</button>
</div>
</div>
</div>
</mainLayout>
</template>
<script setup>
import { ref, onMounted, computed } from "vue";
import axios from "axios";
import mainLayout from "../layouts/mainLayout.vue";
import ProductCard from "../components/ProductCard.vue";
import searchbar from "../components/searchbar.vue";
const products = ref([]);
const searchQuery = ref("");
// overlay state
const showOverlay = ref(false);
const detail = ref({});
// Fetch data awal
onMounted(async () => {
try {
const res = await axios.get("http://127.0.0.1:8000/api/produk");
products.value = res.data;
} catch (error) {
console.error("Gagal ambil data produk:", error);
}
});
// Filter
const filteredProducts = computed(() => {
if (!searchQuery.value) return products.value;
return products.value.filter((p) =>
p.nama.toLowerCase().includes(searchQuery.value.toLowerCase())
);
});
// Fungsi buka overlay
async function openOverlay(id) {
try {
const res = await axios.get(`http://127.0.0.1:8000/api/produk/${id}`);
detail.value = res.data;
showOverlay.value = true;
} catch (error) {
console.error("Gagal fetch detail produk:", error);
}
}
// Fungsi tutup overlay
function closeOverlay() {
showOverlay.value = false;
detail.value = {};
}
// Format angka
function formatNumber(num) {
return new Intl.NumberFormat().format(num || 0);
}
</script>

View File

@ -0,0 +1,16 @@
<template>
<mainLayout>
<p style="font-family: 'IM FELL Great Primer', serif; font-style: italic;font-size: 25px;">NAMPAN</p>
<searchbar v-model:search="searchQuery" />
<TrayList :search="searchQuery" />
</mainLayout>
</template>
<script setup>
import { ref } from 'vue';
import mainLayout from '../layouts/mainLayout.vue'
import searchbar from '../components/searchbar.vue';
import TrayList from '../components/TrayList.vue';
const searchQuery = ref("");
</script>

View File

@ -0,0 +1,37 @@
import { createRouter, createWebHistory } from 'vue-router'
import Home from '../pages/Home.vue'
import Produk from '../pages/Produk.vue'
import Brankas from '../pages/Brankas.vue'
import Tray from '../pages/Tray.vue'
const routes = [
{
path: '/',
name: 'Home',
component: Home
},
{
path: '/produk',
name: 'Produk',
component: Produk
},
{
path: '/brankas',
name: 'Brankas',
component: Brankas
},
{
path: '/nampan',
name: 'Nampan',
component: Tray
},
]
const router = createRouter({
history: createWebHistory(),
routes
})
export default router

View File

@ -0,0 +1,10 @@
<!DOCTYPE html>
<html>
<head>
<title>Abbauf App</title>
</head>
<body>
<div id="app"></div>
</body>
@vite(['resources/js/app.js', 'resources/css/app.css'])
</html>

8
routes/console.php Normal file
View File

@ -0,0 +1,8 @@
<?php
use Illuminate\Foundation\Inspiring;
use Illuminate\Support\Facades\Artisan;
Artisan::command('inspire', function () {
$this->comment(Inspiring::quote());
})->purpose('Display an inspiring quote');

31
routes/web.php Normal file
View File

@ -0,0 +1,31 @@
<?php
use App\Http\Controllers\FotoSementaraController;
use App\Http\Controllers\ItemController;
use App\Http\Controllers\NampanController;
use App\Http\Controllers\ProdukController;
use App\Http\Controllers\SalesController;
use App\Http\Controllers\UserController;
use App\Http\Controllers\TransaksiController;
use Illuminate\Support\Facades\Route;
// Backend API
Route::prefix('api')->group(function () {
Route::apiResource('nampan', NampanController::class);
Route::apiResource('produk', ProdukController::class);
Route::apiResource('item', ItemController::class);
Route::apiResource('sales', SalesController::class);
Route::apiResource('user', UserController::class);
Route::apiResource('transaksi', TransaksiController::class);
Route::get('brankas', [ItemController::class, 'brankasItem']);
Route::post('foto/upload', [FotoSementaraController::class, 'upload']);
Route::delete('foto/hapus/<id>', [FotoSementaraController::class, 'hapus']);
Route::get('foto/<user_id>', [FotoSementaraController::class, 'getAll']);
Route::delete('foto/reset/<user_id>', [FotoSementaraController::class, 'reset']);
});
// Frontend SPA
Route::get('/{any}', function () {
return view('app');
})->where('any', '.*');

4
storage/app/.gitignore vendored Normal file
View File

@ -0,0 +1,4 @@
*
!private/
!public/
!.gitignore

2
storage/app/private/.gitignore vendored Normal file
View File

@ -0,0 +1,2 @@
*
!.gitignore

2
storage/app/public/.gitignore vendored Normal file
View File

@ -0,0 +1,2 @@
*
!.gitignore

9
storage/framework/.gitignore vendored Normal file
View File

@ -0,0 +1,9 @@
compiled.php
config.php
down
events.scanned.php
maintenance.php
routes.php
routes.scanned.php
schedule-*
services.json

3
storage/framework/cache/.gitignore vendored Normal file
View File

@ -0,0 +1,3 @@
*
!data/
!.gitignore

View File

@ -0,0 +1,2 @@
*
!.gitignore

2
storage/framework/sessions/.gitignore vendored Normal file
View File

@ -0,0 +1,2 @@
*
!.gitignore

Some files were not shown because too many files have changed in this diff Show More