feat: implement consumable inventory module, network LAN access, and CI/CD enhancements
- Modul Consumable Item: model master, buku besar transaksi (stock ledger), purchase unit conversion, stock opname, dan transaction reversal - Integrasi ke Employee Management, Asset Unit, dan tiket/work order - Konfigurasi akses jaringan lokal (LAN) via 0.0.0.0:8000, ALLOWED_HOSTS, dan CSRF_TRUSTED_ORIGINS otomatis - Script pembuka firewall Windows (buka_firewall_lan.bat) dan menu interaktif run.bat - Skema migrasi 0019_consumableitem_consumabletransaction - Seeder 11 item consumable riil (seed_consumables.py) - Test suite komprehensif (41 automated tests, 100% lulus) - Pipeline CI/CD GitHub Actions (.github/workflows/ci.yml)
This commit is contained in:
@@ -0,0 +1,194 @@
|
||||
"""
|
||||
Package assets.views
|
||||
Mengekspos seluruh controller view untuk backward compatibility penuh
|
||||
dengan konfigurasi URL dan import existing di itam_core.
|
||||
"""
|
||||
|
||||
# Base & Dashboard
|
||||
from .base_views import (
|
||||
dashboard,
|
||||
custom_404_view,
|
||||
)
|
||||
|
||||
# Authentication & Profile
|
||||
from .auth_views import (
|
||||
login_view,
|
||||
logout_view,
|
||||
profile_view,
|
||||
)
|
||||
|
||||
# Assets & Units Management
|
||||
from .asset_views import (
|
||||
asset_list,
|
||||
asset_add,
|
||||
asset_edit,
|
||||
asset_delete,
|
||||
asset_units,
|
||||
unit_add,
|
||||
unit_edit,
|
||||
unit_update_status,
|
||||
unit_delete,
|
||||
unit_history,
|
||||
)
|
||||
|
||||
# Status Aset
|
||||
from .status_views import (
|
||||
status_aset_list,
|
||||
)
|
||||
|
||||
# Distribusi & Penugasan
|
||||
from .distribution_views import (
|
||||
distribusi_list,
|
||||
distribusi_handover,
|
||||
distribusi_mutation,
|
||||
distribusi_return,
|
||||
distribusi_upload_doc,
|
||||
validate_uploaded_document,
|
||||
)
|
||||
|
||||
# Karyawan (Employees)
|
||||
from .employee_views import (
|
||||
employee_list,
|
||||
employee_detail,
|
||||
employee_create,
|
||||
employee_edit,
|
||||
employee_delete,
|
||||
employee_activate,
|
||||
)
|
||||
|
||||
# Configuration Item (CI / CMDB)
|
||||
from .ci_views import (
|
||||
ci_list,
|
||||
ci_detail,
|
||||
ci_create,
|
||||
ci_edit,
|
||||
ci_assign,
|
||||
ci_remove,
|
||||
ci_replace,
|
||||
ci_report_damage,
|
||||
)
|
||||
|
||||
# Consumable Item (Barang Habis Pakai)
|
||||
from .consumable_views import (
|
||||
consumable_list,
|
||||
consumable_detail,
|
||||
consumable_create,
|
||||
consumable_edit,
|
||||
consumable_in,
|
||||
consumable_out,
|
||||
consumable_adjust,
|
||||
consumable_transaction_reverse,
|
||||
consumable_export_excel,
|
||||
consumable_export_pdf,
|
||||
)
|
||||
|
||||
# QR Code & Public Info
|
||||
from .qr_views import (
|
||||
unit_qr_code,
|
||||
unit_public_detail,
|
||||
)
|
||||
|
||||
# Database Backup
|
||||
from .backup_views import (
|
||||
backup_database_view,
|
||||
)
|
||||
|
||||
# Report Exports - PDF
|
||||
from .report_pdf_views import (
|
||||
asset_export_pdf,
|
||||
distribusi_export_pdf,
|
||||
status_aset_export_pdf,
|
||||
employee_export_pdf,
|
||||
employee_detail_export_pdf,
|
||||
unit_history_export_pdf,
|
||||
asset_units_export_pdf,
|
||||
)
|
||||
|
||||
# Report Exports - Excel
|
||||
from .report_excel_views import (
|
||||
asset_export_excel,
|
||||
distribusi_export_excel,
|
||||
status_aset_export_excel,
|
||||
employee_export_excel,
|
||||
employee_detail_export_excel,
|
||||
unit_history_export_excel,
|
||||
asset_units_export_excel,
|
||||
)
|
||||
|
||||
__all__ = [
|
||||
# Base
|
||||
'dashboard',
|
||||
'custom_404_view',
|
||||
# Auth
|
||||
'login_view',
|
||||
'logout_view',
|
||||
'profile_view',
|
||||
# Assets & Units
|
||||
'asset_list',
|
||||
'asset_add',
|
||||
'asset_edit',
|
||||
'asset_delete',
|
||||
'asset_units',
|
||||
'unit_add',
|
||||
'unit_edit',
|
||||
'unit_update_status',
|
||||
'unit_delete',
|
||||
'unit_history',
|
||||
# Status
|
||||
'status_aset_list',
|
||||
# Distribusi
|
||||
'distribusi_list',
|
||||
'distribusi_handover',
|
||||
'distribusi_mutation',
|
||||
'distribusi_return',
|
||||
'distribusi_upload_doc',
|
||||
'validate_uploaded_document',
|
||||
# Employees
|
||||
'employee_list',
|
||||
'employee_detail',
|
||||
'employee_create',
|
||||
'employee_edit',
|
||||
'employee_delete',
|
||||
'employee_activate',
|
||||
# Configuration Items (CI)
|
||||
'ci_list',
|
||||
'ci_detail',
|
||||
'ci_create',
|
||||
'ci_edit',
|
||||
'ci_assign',
|
||||
'ci_remove',
|
||||
'ci_replace',
|
||||
'ci_report_damage',
|
||||
# Consumable Items
|
||||
'consumable_list',
|
||||
'consumable_detail',
|
||||
'consumable_create',
|
||||
'consumable_edit',
|
||||
'consumable_in',
|
||||
'consumable_out',
|
||||
'consumable_adjust',
|
||||
'consumable_transaction_reverse',
|
||||
'consumable_export_excel',
|
||||
'consumable_export_pdf',
|
||||
# QR & Public
|
||||
'unit_qr_code',
|
||||
'unit_public_detail',
|
||||
# Backup
|
||||
'backup_database_view',
|
||||
# Export PDF
|
||||
'asset_export_pdf',
|
||||
'distribusi_export_pdf',
|
||||
'status_aset_export_pdf',
|
||||
'employee_export_pdf',
|
||||
'employee_detail_export_pdf',
|
||||
'unit_history_export_pdf',
|
||||
'asset_units_export_pdf',
|
||||
# Export Excel
|
||||
'asset_export_excel',
|
||||
'distribusi_export_excel',
|
||||
'status_aset_export_excel',
|
||||
'employee_export_excel',
|
||||
'employee_detail_export_excel',
|
||||
'unit_history_export_excel',
|
||||
'asset_units_export_excel',
|
||||
]
|
||||
@@ -0,0 +1,333 @@
|
||||
import re
|
||||
from django.shortcuts import render, redirect, get_object_or_404
|
||||
from django.contrib.auth.decorators import login_required
|
||||
from django.contrib import messages
|
||||
from django.http import JsonResponse
|
||||
from django.db.models import Count, Q
|
||||
from django.core.paginator import Paginator
|
||||
from assets.models import Asset, AssetUnit, Category, Employee, UnitLog
|
||||
from assets.permissions import operator_required
|
||||
|
||||
|
||||
@login_required
|
||||
def asset_list(request):
|
||||
"""Menampilkan katalog master jenis aset dengan tab Karyawan/Network dan paginasi."""
|
||||
search_query = request.GET.get('q', '').strip()
|
||||
active_tab = request.GET.get('tab', 'karyawan')
|
||||
|
||||
assets_qs = Asset.objects.select_related('category').annotate(
|
||||
unit_tersedia=Count('units', filter=Q(units__status='tersedia')),
|
||||
unit_digunakan=Count('units', filter=Q(units__status='digunakan')),
|
||||
total_units=Count('units'),
|
||||
)
|
||||
|
||||
if search_query:
|
||||
assets_qs = assets_qs.filter(
|
||||
Q(asset_code__icontains=search_query) |
|
||||
Q(name__icontains=search_query) |
|
||||
Q(brand__icontains=search_query)
|
||||
)
|
||||
|
||||
if active_tab == 'network':
|
||||
assets_qs = assets_qs.filter(category__name__icontains='Network')
|
||||
else:
|
||||
assets_qs = assets_qs.filter(category__name__icontains='Karyawan')
|
||||
|
||||
assets_qs = assets_qs.order_by('asset_code')
|
||||
categories = Category.objects.all().order_by('name')
|
||||
|
||||
counts = {
|
||||
'karyawan': Asset.objects.filter(category__name__icontains='Karyawan').count(),
|
||||
'network': Asset.objects.filter(category__name__icontains='Network').count(),
|
||||
}
|
||||
|
||||
# Implementasi Pagination (25 aset per halaman)
|
||||
paginator = Paginator(assets_qs, 25)
|
||||
page_number = request.GET.get('page')
|
||||
page_obj = paginator.get_page(page_number)
|
||||
|
||||
return render(request, 'asset_list.html', {
|
||||
'assets': page_obj,
|
||||
'page_obj': page_obj,
|
||||
'search_query': search_query,
|
||||
'active_tab': active_tab,
|
||||
'categories': categories,
|
||||
'counts': counts,
|
||||
})
|
||||
|
||||
|
||||
@login_required
|
||||
@operator_required
|
||||
def asset_add(request):
|
||||
"""Menambahkan master jenis aset baru."""
|
||||
if request.method == 'POST':
|
||||
category_id = request.POST.get('category')
|
||||
asset_code = request.POST.get('asset_code', '').strip().upper()
|
||||
name = request.POST.get('name', '').strip()
|
||||
brand = request.POST.get('brand', '').strip()
|
||||
uom = request.POST.get('uom', '').strip()
|
||||
|
||||
if Asset.objects.filter(asset_code=asset_code).exists():
|
||||
return JsonResponse({'success': False, 'error': f"Kode Aset '{asset_code}' sudah digunakan. Silakan pilih kode lain."})
|
||||
|
||||
Asset.objects.create(
|
||||
category_id=category_id,
|
||||
asset_code=asset_code,
|
||||
name=name,
|
||||
brand=brand,
|
||||
uom=uom
|
||||
)
|
||||
messages.success(request, f'Aset {name} berhasil ditambahkan.')
|
||||
return JsonResponse({'success': True})
|
||||
return redirect('asset_list')
|
||||
|
||||
|
||||
@login_required
|
||||
@operator_required
|
||||
def asset_edit(request, asset_id):
|
||||
"""Memperbarui informasi master aset dan menyinkronkan kode unit jika kode aset berubah."""
|
||||
asset = get_object_or_404(Asset, id=asset_id)
|
||||
if request.method == 'POST':
|
||||
category_id = request.POST.get('category')
|
||||
new_code = request.POST.get('asset_code', '').strip().upper()
|
||||
name = request.POST.get('name', '').strip()
|
||||
brand = request.POST.get('brand', '').strip()
|
||||
uom = request.POST.get('uom', '').strip()
|
||||
|
||||
old_code = asset.asset_code
|
||||
if new_code and new_code != old_code:
|
||||
if Asset.objects.exclude(id=asset.id).filter(asset_code=new_code).exists():
|
||||
return JsonResponse({'success': False, 'error': f"Kode Aset '{new_code}' sudah digunakan oleh aset lain."})
|
||||
|
||||
# Validasi benturan kode unit turunan
|
||||
for unit in asset.units.all():
|
||||
if unit.unit_code.startswith(f"{old_code}-"):
|
||||
suffix = unit.unit_code[len(f"{old_code}-"):]
|
||||
elif '-' in unit.unit_code:
|
||||
suffix = unit.unit_code.rsplit('-', 1)[-1]
|
||||
else:
|
||||
suffix = unit.unit_code
|
||||
target_unit_code = f"{new_code}-{suffix}"
|
||||
if AssetUnit.objects.exclude(asset=asset).filter(unit_code=target_unit_code).exists():
|
||||
return JsonResponse({'success': False, 'error': f"Gagal mengubah kode aset: Kode unit '{target_unit_code}' sudah digunakan oleh unit lain di sistem."})
|
||||
|
||||
asset.asset_code = new_code
|
||||
|
||||
asset.category_id = category_id
|
||||
asset.name = name
|
||||
asset.brand = brand
|
||||
asset.uom = uom
|
||||
asset.save()
|
||||
|
||||
messages.success(request, f'Perubahan pada aset {new_code} berhasil disimpan.')
|
||||
return JsonResponse({'success': True})
|
||||
return redirect('asset_list')
|
||||
|
||||
|
||||
@login_required
|
||||
@operator_required
|
||||
def asset_delete(request, asset_id):
|
||||
"""Menghapus master jenis aset beserta unit fisiknya secara cascade."""
|
||||
asset = get_object_or_404(Asset, id=asset_id)
|
||||
if request.method == 'POST':
|
||||
asset.delete()
|
||||
messages.success(request, "Data aset berhasil dihapus.")
|
||||
return redirect('asset_list')
|
||||
return redirect('asset_list')
|
||||
|
||||
|
||||
@login_required
|
||||
def asset_units(request, asset_id):
|
||||
"""Menampilkan seluruh unit fisik individual yang terdaftar pada jenis aset tertentu."""
|
||||
asset = get_object_or_404(Asset, id=asset_id)
|
||||
units = asset.units.all().order_by('unit_code')
|
||||
employees = Employee.objects.filter(is_active=True).order_by('name')
|
||||
|
||||
tersedia = units.filter(status='tersedia').count()
|
||||
digunakan = units.filter(status='digunakan').count()
|
||||
|
||||
return render(request, 'asset_units.html', {
|
||||
'asset': asset,
|
||||
'units': units,
|
||||
'employees': employees,
|
||||
'tersedia': tersedia,
|
||||
'digunakan': digunakan
|
||||
})
|
||||
|
||||
|
||||
@login_required
|
||||
@operator_required
|
||||
def unit_add(request, asset_id):
|
||||
"""Mendaftarkan unit fisik baru di bawah jenis aset induk."""
|
||||
if request.method == 'POST':
|
||||
asset = get_object_or_404(Asset, id=asset_id)
|
||||
suffix = request.POST.get('unit_code_suffix', '').strip()
|
||||
status = 'tersedia'
|
||||
|
||||
if suffix:
|
||||
unit_code = f"{asset.asset_code}-{suffix}"
|
||||
if AssetUnit.objects.filter(unit_code=unit_code).exists():
|
||||
if request.headers.get('Accept') == 'application/json' or request.headers.get('x-requested-with') == 'XMLHttpRequest':
|
||||
return JsonResponse({'status': 'error', 'message': f'Kode Unit "{unit_code}" sudah terdaftar di sistem!'}, status=400)
|
||||
else:
|
||||
new_unit = AssetUnit.objects.create(asset=asset, unit_code=unit_code, status=status)
|
||||
UnitLog.objects.create(unit=new_unit, action='created', notes="Ditambahkan ke Sistem")
|
||||
|
||||
asset.qty = asset.units.count()
|
||||
asset.save()
|
||||
messages.success(request, "Unit fisik berhasil ditambahkan.")
|
||||
|
||||
if request.headers.get('Accept') == 'application/json' or request.headers.get('x-requested-with') == 'XMLHttpRequest':
|
||||
return JsonResponse({'status': 'success'})
|
||||
|
||||
return redirect('asset_units', asset_id=asset_id)
|
||||
|
||||
|
||||
@login_required
|
||||
@operator_required
|
||||
def unit_edit(request, unit_id):
|
||||
"""Memperbarui informasi kode unit dan status operasionalnya."""
|
||||
unit = get_object_or_404(AssetUnit, id=unit_id)
|
||||
old_status = unit.status
|
||||
old_assigned = unit.assigned_to
|
||||
|
||||
if request.method == 'POST':
|
||||
suffix = request.POST.get('unit_code_suffix', '').strip()
|
||||
new_unit_code = f"{unit.asset.asset_code}-{suffix}" if suffix else unit.unit_code
|
||||
|
||||
if AssetUnit.objects.exclude(id=unit.id).filter(unit_code=new_unit_code).exists():
|
||||
if request.headers.get('Accept') == 'application/json' or request.headers.get('x-requested-with') == 'XMLHttpRequest':
|
||||
return JsonResponse({'status': 'error', 'message': f'Kode Unit "{new_unit_code}" sudah digunakan oleh unit lain!'}, status=400)
|
||||
|
||||
unit.unit_code = new_unit_code
|
||||
new_status = request.POST.get('status')
|
||||
unit.status = new_status
|
||||
|
||||
if new_status in ['tersedia', 'pensiun']:
|
||||
unit.assigned_to = None
|
||||
|
||||
unit.save()
|
||||
new_assigned = unit.assigned_to
|
||||
|
||||
notes = request.POST.get('notes', '')
|
||||
if old_status != new_status or old_assigned != new_assigned:
|
||||
if old_status == 'digunakan' and new_status == 'tersedia':
|
||||
UnitLog.objects.create(unit=unit, action='returned', employee=old_assigned, notes=notes or "Dikembalikan ke gudang")
|
||||
elif old_status == 'tersedia' and new_status == 'digunakan':
|
||||
UnitLog.objects.create(unit=unit, action='assigned', employee=new_assigned, notes=notes or "Diserahkan ke karyawan (Manual Edit)")
|
||||
elif old_status == 'digunakan' and new_status == 'digunakan' and old_assigned != new_assigned:
|
||||
UnitLog.objects.create(unit=unit, action='returned', employee=old_assigned, notes="Mutasi: Dikembalikan oleh pemegang sebelumnya")
|
||||
UnitLog.objects.create(unit=unit, action='assigned', employee=new_assigned, notes=notes or "Mutasi: Diserahkan ke pemegang baru")
|
||||
elif new_status == 'rusak' and old_status != 'rusak':
|
||||
UnitLog.objects.create(unit=unit, action='maintenance_in', employee=old_assigned, notes=notes or "Unit dilaporkan rusak / masuk maintenance")
|
||||
elif old_status == 'rusak' and new_status == 'tersedia':
|
||||
UnitLog.objects.create(unit=unit, action='maintenance_out', notes=notes or "Perbaikan selesai, unit kembali tersedia")
|
||||
elif old_status == 'rusak' and new_status == 'digunakan':
|
||||
UnitLog.objects.create(unit=unit, action='maintenance_out', employee=new_assigned, notes=notes or "Perbaikan selesai, unit kembali digunakan oleh karyawan")
|
||||
elif new_status == 'pensiun':
|
||||
UnitLog.objects.create(unit=unit, action='retired', notes=notes or "Unit dipensiunkan")
|
||||
elif old_status == 'pensiun' and new_status != 'pensiun':
|
||||
UnitLog.objects.create(unit=unit, action='other', notes=notes or f"Status dipulihkan dari pensiun menjadi {new_status}")
|
||||
else:
|
||||
UnitLog.objects.create(unit=unit, action='other', notes=notes or f"Status diubah dari {old_status} menjadi {new_status}")
|
||||
|
||||
if request.headers.get('Accept') == 'application/json' or request.headers.get('x-requested-with') == 'XMLHttpRequest':
|
||||
return JsonResponse({'status': 'success'})
|
||||
|
||||
return redirect('asset_units', asset_id=unit.asset.id)
|
||||
|
||||
|
||||
@login_required
|
||||
@operator_required
|
||||
def unit_update_status(request, unit_id):
|
||||
"""Memperbarui status unit dan metadata area lokasi untuk aset jaringan."""
|
||||
if request.method == 'POST':
|
||||
unit = get_object_or_404(AssetUnit, id=unit_id)
|
||||
new_status = request.POST.get('status')
|
||||
notes = request.POST.get('notes', '')
|
||||
old_status = unit.status
|
||||
is_network = 'Network' in unit.asset.category.name
|
||||
|
||||
new_area = request.POST.get('area')
|
||||
new_location = request.POST.get('location')
|
||||
|
||||
status_changed = new_status and new_status != old_status
|
||||
location_changed = False
|
||||
|
||||
if is_network and new_status in ['digunakan', 'rusak']:
|
||||
if unit.area != new_area or unit.location != new_location:
|
||||
location_changed = True
|
||||
|
||||
if status_changed or location_changed:
|
||||
unit.status = new_status
|
||||
action_type = 'updated'
|
||||
log_notes = ""
|
||||
|
||||
if status_changed:
|
||||
log_notes += f"Status diubah dari '{old_status}' menjadi '{new_status}'. "
|
||||
if new_status == 'rusak':
|
||||
action_type = 'maintenance_in'
|
||||
elif old_status == 'rusak' and (new_status == 'digunakan' or new_status == 'tersedia'):
|
||||
action_type = 'maintenance_out'
|
||||
elif location_changed:
|
||||
log_notes += "Lokasi / Area diperbarui. "
|
||||
|
||||
if new_status in ['digunakan', 'rusak'] and is_network:
|
||||
unit.area = new_area
|
||||
unit.location = new_location
|
||||
log_notes += f"Pemasangan di {unit.area}, {unit.location}. "
|
||||
elif new_status == 'tersedia':
|
||||
unit.area = None
|
||||
unit.location = None
|
||||
|
||||
if notes:
|
||||
log_notes += f"Catatan: {notes}"
|
||||
|
||||
unit.save()
|
||||
|
||||
UnitLog.objects.create(
|
||||
unit=unit,
|
||||
action=action_type,
|
||||
employee=unit.assigned_to,
|
||||
notes=log_notes.strip()
|
||||
)
|
||||
messages.success(request, "Status unit berhasil diperbarui.")
|
||||
|
||||
return redirect(request.META.get('HTTP_REFERER', 'dashboard'))
|
||||
|
||||
|
||||
@login_required
|
||||
@operator_required
|
||||
def unit_delete(request, unit_id):
|
||||
"""Menghapus unit fisik individual dan memperbarui kuantitas aset induk."""
|
||||
unit = get_object_or_404(AssetUnit, id=unit_id)
|
||||
asset_id = unit.asset.id
|
||||
if request.method == 'POST':
|
||||
unit.delete()
|
||||
asset = Asset.objects.get(id=asset_id)
|
||||
asset.qty = asset.units.count()
|
||||
asset.save()
|
||||
messages.success(request, "Unit berhasil dihapus.")
|
||||
return redirect('asset_units', asset_id=asset_id)
|
||||
|
||||
|
||||
@login_required
|
||||
def unit_history(request, unit_id):
|
||||
"""Menampilkan timeline kronologis riwayat log peristiwa pada suatu unit."""
|
||||
unit = get_object_or_404(AssetUnit, id=unit_id)
|
||||
logs_qs = unit.logs.all().select_related('employee')
|
||||
|
||||
logs = []
|
||||
pattern = re.compile(r"^(.+?) \((.+?)\) - (.*)$")
|
||||
|
||||
for log in logs_qs:
|
||||
log.deleted_employee_name = None
|
||||
if not log.employee and log.notes:
|
||||
match = pattern.match(log.notes.strip())
|
||||
if match:
|
||||
name, nik, rest_of_notes = match.groups()
|
||||
log.deleted_employee_name = name
|
||||
log.notes = rest_of_notes.strip()
|
||||
logs.append(log)
|
||||
|
||||
return render(request, 'unit_history.html', {'unit': unit, 'logs': logs})
|
||||
@@ -0,0 +1,96 @@
|
||||
from django.shortcuts import render, redirect
|
||||
from django.contrib.auth import authenticate, login, logout, update_session_auth_hash
|
||||
from django.contrib.auth.decorators import login_required
|
||||
from django.contrib.auth.models import User
|
||||
from django.contrib.auth.password_validation import validate_password
|
||||
from django.contrib import messages
|
||||
from django.utils.http import url_has_allowed_host_and_scheme
|
||||
|
||||
|
||||
def login_view(request):
|
||||
"""Menangani autentikasi login via username atau email."""
|
||||
if request.user.is_authenticated:
|
||||
return redirect('dashboard')
|
||||
|
||||
if request.method == 'POST':
|
||||
u = request.POST.get('username', '').strip()
|
||||
p = request.POST.get('password', '')
|
||||
|
||||
# Izinkan login menggunakan email
|
||||
login_username = u
|
||||
if '@' in u:
|
||||
try:
|
||||
user_obj = User.objects.get(email=u)
|
||||
login_username = user_obj.username
|
||||
except User.DoesNotExist:
|
||||
pass
|
||||
|
||||
user = authenticate(request, username=login_username, password=p)
|
||||
if user is not None:
|
||||
login(request, user)
|
||||
next_url = request.GET.get('next', '')
|
||||
if not next_url or not url_has_allowed_host_and_scheme(next_url, allowed_hosts={request.get_host()}):
|
||||
next_url = 'dashboard'
|
||||
return redirect(next_url)
|
||||
else:
|
||||
messages.error(request, 'Username / Email atau password salah.')
|
||||
|
||||
return render(request, 'login.html')
|
||||
|
||||
|
||||
def logout_view(request):
|
||||
"""Mengakhiri sesi pengguna."""
|
||||
if request.method == 'POST':
|
||||
logout(request)
|
||||
return redirect('login')
|
||||
|
||||
|
||||
@login_required
|
||||
def profile_view(request):
|
||||
"""Mengelola pembaruan data profil akun dan perubahan kata sandi."""
|
||||
user = request.user
|
||||
if request.method == 'POST':
|
||||
action = request.POST.get('action')
|
||||
|
||||
if action == 'update_info':
|
||||
first_name = request.POST.get('first_name', '')
|
||||
last_name = request.POST.get('last_name', '')
|
||||
email = request.POST.get('email', '')
|
||||
username = request.POST.get('username', '').strip()
|
||||
|
||||
if not username:
|
||||
messages.error(request, "Username tidak boleh kosong.")
|
||||
else:
|
||||
try:
|
||||
user.first_name = first_name
|
||||
user.last_name = last_name
|
||||
user.email = email
|
||||
user.username = username
|
||||
user.save()
|
||||
messages.success(request, "Informasi profil berhasil diperbarui.")
|
||||
except Exception:
|
||||
messages.error(request, "Gagal memperbarui profil. Username mungkin sudah digunakan.")
|
||||
|
||||
elif action == 'update_password':
|
||||
old_password = request.POST.get('old_password')
|
||||
new_password = request.POST.get('new_password')
|
||||
confirm_password = request.POST.get('confirm_password')
|
||||
|
||||
if not user.check_password(old_password):
|
||||
messages.error(request, "Password lama salah.")
|
||||
elif new_password != confirm_password:
|
||||
messages.error(request, "Konfirmasi password baru tidak cocok.")
|
||||
else:
|
||||
try:
|
||||
validate_password(new_password, user)
|
||||
user.set_password(new_password)
|
||||
user.save()
|
||||
update_session_auth_hash(request, user)
|
||||
messages.success(request, "Password berhasil diubah.")
|
||||
except Exception as e:
|
||||
for error in getattr(e, 'messages', [str(e)]):
|
||||
messages.error(request, error)
|
||||
|
||||
return redirect('profile')
|
||||
|
||||
return render(request, 'profile.html')
|
||||
@@ -0,0 +1,80 @@
|
||||
import io
|
||||
import datetime
|
||||
import os
|
||||
import subprocess
|
||||
from django.shortcuts import render
|
||||
from django.contrib.auth.decorators import login_required
|
||||
from assets.permissions import admin_required
|
||||
from django.core.management import call_command
|
||||
from django.http import HttpResponse, HttpResponseServerError, HttpResponseForbidden
|
||||
from django.conf import settings
|
||||
|
||||
|
||||
@login_required
|
||||
@admin_required
|
||||
def backup_database_view(request):
|
||||
"""Menangani pencadangan database manual ke format JSON atau SQL."""
|
||||
if not request.user.is_superuser:
|
||||
return HttpResponseForbidden("Anda tidak memiliki akses ke halaman ini.")
|
||||
|
||||
if request.method == 'POST':
|
||||
backup_format = request.POST.get('format', 'json')
|
||||
now = datetime.datetime.now().strftime('%Y-%m-%d_%H%M')
|
||||
|
||||
if backup_format == 'sql':
|
||||
db = settings.DATABASES['default']
|
||||
db_engine = db.get('ENGINE', '')
|
||||
|
||||
# Jika database adalah sqlite, lakukan copy database file langsung
|
||||
if 'sqlite' in db_engine:
|
||||
sqlite_path = db.get('NAME')
|
||||
if os.path.exists(sqlite_path):
|
||||
with open(sqlite_path, 'rb') as f:
|
||||
response = HttpResponse(f.read(), content_type='application/x-sqlite3')
|
||||
response['Content-Disposition'] = f'attachment; filename="backup_manajemen_aset_{now}.sqlite3"'
|
||||
return response
|
||||
return HttpResponseServerError("File database SQLite tidak ditemukan.")
|
||||
|
||||
db_name = db['NAME']
|
||||
db_user = db['USER']
|
||||
db_pass = db['PASSWORD']
|
||||
db_host = db['HOST'] or '127.0.0.1'
|
||||
db_port = db['PORT'] or '3306'
|
||||
|
||||
cmd = ['mysqldump', f'--user={db_user}', f'--host={db_host}', f'--port={db_port}', db_name]
|
||||
|
||||
try:
|
||||
env = os.environ.copy()
|
||||
if db_pass:
|
||||
env['MYSQL_PWD'] = db_pass
|
||||
result = subprocess.run(cmd, env=env, capture_output=True, text=False)
|
||||
|
||||
if result.returncode != 0:
|
||||
return HttpResponseServerError(
|
||||
f"Gagal melakukan backup SQL. Pastikan 'mysqldump' tersedia di server. Error: {result.stderr.decode('utf-8', errors='ignore')}"
|
||||
)
|
||||
|
||||
response = HttpResponse(result.stdout, content_type='application/sql')
|
||||
response['Content-Disposition'] = f'attachment; filename="backup_manajemen_aset_{now}.sql"'
|
||||
return response
|
||||
except Exception as e:
|
||||
return HttpResponseServerError(f"Terjadi kesalahan saat mengeksekusi mysqldump: {str(e)}")
|
||||
|
||||
else:
|
||||
# Default format JSON menggunakan dumpdata
|
||||
buffer = io.StringIO()
|
||||
call_command(
|
||||
'dumpdata',
|
||||
'--exclude', 'contenttypes',
|
||||
'--exclude', 'auth.permission',
|
||||
'--exclude', 'admin.logentry',
|
||||
'--exclude', 'sessions',
|
||||
stdout=buffer
|
||||
)
|
||||
buffer.seek(0)
|
||||
|
||||
response = HttpResponse(buffer.getvalue(), content_type='application/json')
|
||||
response['Content-Disposition'] = f'attachment; filename="backup_manajemen_aset_{now}.json"'
|
||||
return response
|
||||
|
||||
return render(request, 'backup.html')
|
||||
@@ -0,0 +1,43 @@
|
||||
from django.shortcuts import render
|
||||
from django.contrib.auth.decorators import login_required
|
||||
from assets.models import AssetUnit, AssetAssignment
|
||||
|
||||
|
||||
@login_required
|
||||
def dashboard(request):
|
||||
"""Menampilkan ringkasan statistik aset dan aktivitas distribusi terbaru."""
|
||||
count_karyawan = AssetUnit.objects.filter(asset__category__name__icontains='Karyawan').count()
|
||||
count_network = AssetUnit.objects.filter(asset__category__name__icontains='Network').count()
|
||||
|
||||
count_tersedia = AssetUnit.objects.filter(status='tersedia').count()
|
||||
count_digunakan = AssetUnit.objects.filter(status='digunakan').count()
|
||||
count_maintenance = AssetUnit.objects.filter(status='rusak').count()
|
||||
|
||||
recent_handovers = AssetAssignment.objects.filter(type='handover').select_related(
|
||||
'unit', 'unit__asset', 'employee'
|
||||
).order_by('-assigned_date', '-id')[:5]
|
||||
|
||||
recent_mutations = AssetAssignment.objects.filter(type='mutation').select_related(
|
||||
'unit', 'unit__asset', 'employee', 'from_employee'
|
||||
).order_by('-assigned_date', '-id')[:3]
|
||||
|
||||
recent_returns = AssetAssignment.objects.filter(type='return').select_related(
|
||||
'unit', 'unit__asset', 'employee'
|
||||
).order_by('-assigned_date', '-id')[:3]
|
||||
|
||||
context = {
|
||||
'count_karyawan': count_karyawan,
|
||||
'count_network': count_network,
|
||||
'count_tersedia': count_tersedia,
|
||||
'count_digunakan': count_digunakan,
|
||||
'count_maintenance': count_maintenance,
|
||||
'recent_handovers': recent_handovers,
|
||||
'recent_mutations': recent_mutations,
|
||||
'recent_returns': recent_returns,
|
||||
}
|
||||
return render(request, 'dashboard.html', context)
|
||||
|
||||
|
||||
def custom_404_view(request, exception=None):
|
||||
"""Handler halaman error 404 kustom."""
|
||||
return render(request, '404.html', status=404)
|
||||
@@ -0,0 +1,498 @@
|
||||
import re
|
||||
from datetime import datetime
|
||||
from django.shortcuts import render, redirect, get_object_or_404
|
||||
from django.contrib.auth.decorators import login_required
|
||||
from django.contrib import messages
|
||||
from django.http import JsonResponse
|
||||
from django.db import transaction
|
||||
from django.db.models import Count, Q
|
||||
from django.core.paginator import Paginator
|
||||
|
||||
from assets.models import ConfigurationItem, CIHistory, AssetUnit, Employee, UnitLog
|
||||
from assets.permissions import operator_required
|
||||
|
||||
|
||||
@login_required
|
||||
def ci_list(request):
|
||||
"""Menampilkan katalog Configuration Item (CI) dengan kartu ringkasan,
|
||||
filter kategori, status operasional, kondisi fisik, dan paginasi 25 baris.
|
||||
"""
|
||||
search_query = request.GET.get('q', '').strip()
|
||||
status_filter = request.GET.get('status', '').strip()
|
||||
category_filter = request.GET.get('category', '').strip()
|
||||
condition_filter = request.GET.get('condition', '').strip()
|
||||
|
||||
# Base queryset
|
||||
ci_qs = ConfigurationItem.objects.select_related(
|
||||
'installed_on', 'installed_on__asset', 'installed_on__assigned_to', 'assigned_to'
|
||||
)
|
||||
|
||||
# Ringkasan KPI operasional
|
||||
counts = {
|
||||
'total': ConfigurationItem.objects.count(),
|
||||
'in_use': ConfigurationItem.objects.filter(status='in_use').count(),
|
||||
'available': ConfigurationItem.objects.filter(status='available').count(),
|
||||
'under_repair': ConfigurationItem.objects.filter(status__in=['under_inspection', 'under_repair']).count(),
|
||||
'retired': ConfigurationItem.objects.filter(status='retired').count(),
|
||||
}
|
||||
|
||||
# Penerapan Filter
|
||||
if status_filter:
|
||||
if status_filter == 'repair':
|
||||
ci_qs = ci_qs.filter(status__in=['under_inspection', 'under_repair'])
|
||||
else:
|
||||
ci_qs = ci_qs.filter(status=status_filter)
|
||||
|
||||
if category_filter:
|
||||
ci_qs = ci_qs.filter(category=category_filter)
|
||||
|
||||
if condition_filter:
|
||||
ci_qs = ci_qs.filter(condition=condition_filter)
|
||||
|
||||
if search_query:
|
||||
ci_qs = ci_qs.filter(
|
||||
Q(ci_code__icontains=search_query) |
|
||||
Q(name__icontains=search_query) |
|
||||
Q(brand__icontains=search_query) |
|
||||
Q(model_series__icontains=search_query) |
|
||||
Q(serial_number__icontains=search_query) |
|
||||
Q(specifications__icontains=search_query) |
|
||||
Q(installed_on__unit_code__icontains=search_query) |
|
||||
Q(assigned_to__name__icontains=search_query)
|
||||
)
|
||||
|
||||
# Paginasi 25 item per halaman
|
||||
paginator = Paginator(ci_qs, 25)
|
||||
page_number = request.GET.get('page')
|
||||
page_obj = paginator.get_page(page_number)
|
||||
|
||||
# Master data untuk modal aksi
|
||||
available_units = AssetUnit.objects.select_related('asset', 'assigned_to').filter(
|
||||
status__in=['tersedia', 'digunakan']
|
||||
).order_by('unit_code')
|
||||
|
||||
available_employees = Employee.objects.filter(is_active=True).order_by('name')
|
||||
|
||||
# CI yang berstatus available untuk pilihan modal ganti/upgrade
|
||||
spare_cis = ConfigurationItem.objects.filter(status='available').order_by('name')
|
||||
|
||||
return render(request, 'ci_list.html', {
|
||||
'items': page_obj,
|
||||
'page_obj': page_obj,
|
||||
'counts': counts,
|
||||
'search_query': search_query,
|
||||
'status_filter': status_filter,
|
||||
'category_filter': category_filter,
|
||||
'condition_filter': condition_filter,
|
||||
'categories': ConfigurationItem.CATEGORY_CHOICES,
|
||||
'status_choices': ConfigurationItem.STATUS_CHOICES,
|
||||
'condition_choices': ConfigurationItem.CONDITION_CHOICES,
|
||||
'available_units': available_units,
|
||||
'available_employees': available_employees,
|
||||
'spare_cis': spare_cis,
|
||||
})
|
||||
|
||||
|
||||
@login_required
|
||||
def ci_detail(request, ci_id):
|
||||
"""Menampilkan informasi komprehensif suatu CI: spesifikasi, relasi aktif,
|
||||
dan timeline riwayat siklus hidup (audit trail).
|
||||
"""
|
||||
ci = get_object_or_404(
|
||||
ConfigurationItem.objects.select_related(
|
||||
'installed_on', 'installed_on__asset', 'installed_on__assigned_to', 'assigned_to'
|
||||
),
|
||||
id=ci_id
|
||||
)
|
||||
|
||||
history_logs = ci.history.select_related(
|
||||
'related_unit', 'related_unit__asset', 'related_employee', 'performed_by'
|
||||
).all()
|
||||
|
||||
return render(request, 'ci_detail.html', {
|
||||
'ci': ci,
|
||||
'history_logs': history_logs,
|
||||
})
|
||||
|
||||
|
||||
@login_required
|
||||
@operator_required
|
||||
def ci_create(request):
|
||||
"""Menambahkan Configuration Item baru ke dalam sistem."""
|
||||
if request.method == 'POST':
|
||||
ci_code = request.POST.get('ci_code', '').strip().upper()
|
||||
name = request.POST.get('name', '').strip()
|
||||
category = request.POST.get('category', 'storage')
|
||||
brand = request.POST.get('brand', '').strip()
|
||||
model_series = request.POST.get('model_series', '').strip()
|
||||
serial_number = request.POST.get('serial_number', '').strip()
|
||||
specifications = request.POST.get('specifications', '').strip()
|
||||
condition = request.POST.get('condition', 'new')
|
||||
status = request.POST.get('status', 'available')
|
||||
location = request.POST.get('location', '').strip() or "Gudang IT"
|
||||
purchase_date = request.POST.get('purchase_date') or None
|
||||
warranty_expiry = request.POST.get('warranty_expiry') or None
|
||||
price = request.POST.get('price') or 0
|
||||
notes = request.POST.get('notes', '').strip()
|
||||
|
||||
# Auto-generate CI code jika tidak diisi
|
||||
if not ci_code:
|
||||
prefix_map = {
|
||||
'storage': 'CI-STR',
|
||||
'memory': 'CI-MEM',
|
||||
'processor': 'CI-CPU',
|
||||
'motherboard': 'CI-MB',
|
||||
'gpu': 'CI-GPU',
|
||||
'peripheral': 'CI-PER',
|
||||
'network': 'CI-NET',
|
||||
'power': 'CI-PWR',
|
||||
'other': 'CI-GEN',
|
||||
}
|
||||
prefix = prefix_map.get(category, 'CI-IT')
|
||||
last_item = ConfigurationItem.objects.filter(ci_code__startswith=f"{prefix}-").order_by('-id').first()
|
||||
counter = 1
|
||||
if last_item:
|
||||
match = re.search(r'-(\d+)$', last_item.ci_code)
|
||||
if match:
|
||||
counter = int(match.group(1)) + 1
|
||||
ci_code = f"{prefix}-{counter:03d}"
|
||||
|
||||
# Validasi keunikan CI code
|
||||
if ConfigurationItem.objects.filter(ci_code=ci_code).exists():
|
||||
msg = f'Kode CI "{ci_code}" sudah terdaftar di sistem!'
|
||||
if request.headers.get('Accept') == 'application/json' or request.headers.get('x-requested-with') == 'XMLHttpRequest':
|
||||
return JsonResponse({'status': 'error', 'message': msg}, status=400)
|
||||
messages.error(request, msg)
|
||||
return redirect('ci_list')
|
||||
|
||||
ci = ConfigurationItem.objects.create(
|
||||
ci_code=ci_code,
|
||||
name=name,
|
||||
category=category,
|
||||
brand=brand,
|
||||
model_series=model_series,
|
||||
serial_number=serial_number,
|
||||
specifications=specifications,
|
||||
condition=condition,
|
||||
status=status,
|
||||
location=location,
|
||||
purchase_date=purchase_date,
|
||||
warranty_expiry=warranty_expiry,
|
||||
price=price,
|
||||
notes=notes
|
||||
)
|
||||
|
||||
CIHistory.objects.create(
|
||||
ci=ci,
|
||||
action='created',
|
||||
performed_by=request.user,
|
||||
notes=f"Didaftarkan ke sistem dengan status {ci.get_status_display()}, kondisi {ci.get_condition_display()} di {location}."
|
||||
)
|
||||
|
||||
messages.success(request, f'Configuration Item "{ci.ci_code} - {ci.name}" berhasil ditambahkan.')
|
||||
if request.headers.get('Accept') == 'application/json' or request.headers.get('x-requested-with') == 'XMLHttpRequest':
|
||||
return JsonResponse({'status': 'success', 'ci_id': ci.id})
|
||||
|
||||
return redirect('ci_list')
|
||||
|
||||
|
||||
@login_required
|
||||
@operator_required
|
||||
def ci_edit(request, ci_id):
|
||||
"""Memperbarui informasi metadata dan spesifikasi Configuration Item."""
|
||||
ci = get_object_or_404(ConfigurationItem, id=ci_id)
|
||||
|
||||
if request.method == 'POST':
|
||||
name = request.POST.get('name', '').strip()
|
||||
brand = request.POST.get('brand', '').strip()
|
||||
model_series = request.POST.get('model_series', '').strip()
|
||||
serial_number = request.POST.get('serial_number', '').strip()
|
||||
specifications = request.POST.get('specifications', '').strip()
|
||||
condition = request.POST.get('condition', ci.condition)
|
||||
location = request.POST.get('location', ci.location)
|
||||
warranty_expiry = request.POST.get('warranty_expiry') or None
|
||||
notes = request.POST.get('notes', '').strip()
|
||||
|
||||
old_condition = ci.condition
|
||||
ci.name = name
|
||||
ci.brand = brand
|
||||
ci.model_series = model_series
|
||||
ci.serial_number = serial_number
|
||||
ci.specifications = specifications
|
||||
ci.condition = condition
|
||||
ci.location = location
|
||||
ci.warranty_expiry = warranty_expiry
|
||||
ci.notes = notes
|
||||
ci.save()
|
||||
|
||||
if old_condition != condition:
|
||||
CIHistory.objects.create(
|
||||
ci=ci,
|
||||
action='status_change',
|
||||
performed_by=request.user,
|
||||
notes=f"Kondisi fisik diperbarui dari {dict(ConfigurationItem.CONDITION_CHOICES).get(old_condition)} ke {ci.get_condition_display()}."
|
||||
)
|
||||
|
||||
messages.success(request, f'Perubahan pada {ci.ci_code} berhasil disimpan.')
|
||||
if request.headers.get('Accept') == 'application/json' or request.headers.get('x-requested-with') == 'XMLHttpRequest':
|
||||
return JsonResponse({'status': 'success'})
|
||||
|
||||
return redirect('ci_detail', ci_id=ci.id)
|
||||
|
||||
|
||||
@login_required
|
||||
@operator_required
|
||||
def ci_assign(request, ci_id):
|
||||
"""Alur 'Gunakan Untuk' (Assignment): Memasang komponen ke perangkat utama (AssetUnit)
|
||||
atau mengalokasikannya langsung ke Karyawan secara transaksional.
|
||||
"""
|
||||
ci = get_object_or_404(ConfigurationItem, id=ci_id)
|
||||
|
||||
if request.method == 'POST':
|
||||
usage_type = request.POST.get('usage_type') # 'asset' atau 'employee'
|
||||
target_id = request.POST.get('target_id')
|
||||
notes = request.POST.get('notes', '').strip()
|
||||
|
||||
if ci.status == 'in_use':
|
||||
messages.error(request, f'Komponen {ci.ci_code} sedang digunakan. Lepas terlebih dahulu sebelum dialokasikan.')
|
||||
return redirect('ci_list')
|
||||
|
||||
if ci.status == 'retired':
|
||||
messages.error(request, f'Komponen {ci.ci_code} sudah dipensiunkan.')
|
||||
return redirect('ci_list')
|
||||
|
||||
with transaction.atomic():
|
||||
if usage_type == 'asset':
|
||||
unit = get_object_or_404(AssetUnit, id=target_id)
|
||||
ci.installed_on = unit
|
||||
ci.assigned_to = None
|
||||
ci.status = 'in_use'
|
||||
ci.location = None
|
||||
ci.save()
|
||||
|
||||
pic_info = f" (Pengguna: {unit.assigned_to.name})" if unit.assigned_to else ""
|
||||
log_text = f"Dipasang pada perangkat {unit.unit_code} ({unit.asset.name}){pic_info}. {notes}".strip()
|
||||
|
||||
CIHistory.objects.create(
|
||||
ci=ci,
|
||||
action='installed',
|
||||
related_unit=unit,
|
||||
related_employee=unit.assigned_to,
|
||||
performed_by=request.user,
|
||||
notes=log_text
|
||||
)
|
||||
|
||||
# Rekam juga di UnitLog perangkat induk
|
||||
UnitLog.objects.create(
|
||||
unit=unit,
|
||||
action='other',
|
||||
employee=unit.assigned_to,
|
||||
notes=f"Pemasangan komponen CI: {ci.name} ({ci.ci_code}). {notes}".strip()
|
||||
)
|
||||
|
||||
messages.success(request, f'{ci.name} berhasil dipasang pada perangkat {unit.unit_code}.')
|
||||
|
||||
elif usage_type == 'employee':
|
||||
employee = get_object_or_404(Employee, id=target_id, is_active=True)
|
||||
ci.assigned_to = employee
|
||||
ci.installed_on = None
|
||||
ci.status = 'in_use'
|
||||
ci.location = None
|
||||
ci.save()
|
||||
|
||||
log_text = f"Dialokasikan langsung kepada karyawan {employee.name} ({employee.nik}). {notes}".strip()
|
||||
|
||||
CIHistory.objects.create(
|
||||
ci=ci,
|
||||
action='assigned',
|
||||
related_employee=employee,
|
||||
performed_by=request.user,
|
||||
notes=log_text
|
||||
)
|
||||
|
||||
messages.success(request, f'{ci.name} berhasil dialokasikan kepada {employee.name}.')
|
||||
|
||||
if request.headers.get('Accept') == 'application/json' or request.headers.get('x-requested-with') == 'XMLHttpRequest':
|
||||
return JsonResponse({'status': 'success'})
|
||||
|
||||
return redirect('ci_list')
|
||||
|
||||
|
||||
@login_required
|
||||
@operator_required
|
||||
def ci_remove(request, ci_id):
|
||||
"""Alur 'Lepas dari Perangkat / Pengguna': Memutus relasi aktif dan mengembalikan
|
||||
komponen ke gudang, pemeriksaan, atau perbaikan secara transaksional.
|
||||
"""
|
||||
ci = get_object_or_404(ConfigurationItem, id=ci_id)
|
||||
|
||||
if request.method == 'POST':
|
||||
new_status = request.POST.get('new_status', 'available') # available, under_inspection, under_repair
|
||||
new_condition = request.POST.get('new_condition', ci.condition)
|
||||
location = request.POST.get('location', '').strip() or "Gudang IT"
|
||||
notes = request.POST.get('notes', '').strip()
|
||||
|
||||
old_unit = ci.installed_on
|
||||
old_emp = ci.assigned_to
|
||||
|
||||
with transaction.atomic():
|
||||
ci.installed_on = None
|
||||
ci.assigned_to = None
|
||||
ci.status = new_status
|
||||
ci.condition = new_condition
|
||||
ci.location = location
|
||||
ci.save()
|
||||
|
||||
from_desc = ""
|
||||
if old_unit:
|
||||
from_desc = f"perangkat {old_unit.unit_code}"
|
||||
elif old_emp:
|
||||
from_desc = f"karyawan {old_emp.name}"
|
||||
|
||||
log_text = f"Dilepas dari {from_desc}. Status kini {ci.get_status_display()}, kondisi {ci.get_condition_display()} di {location}. {notes}".strip()
|
||||
|
||||
CIHistory.objects.create(
|
||||
ci=ci,
|
||||
action='removed',
|
||||
related_unit=old_unit,
|
||||
related_employee=old_emp,
|
||||
performed_by=request.user,
|
||||
notes=log_text
|
||||
)
|
||||
|
||||
# Jika dilepas dari unit perangkat fisik, rekam di UnitLog
|
||||
if old_unit:
|
||||
UnitLog.objects.create(
|
||||
unit=old_unit,
|
||||
action='other',
|
||||
employee=old_unit.assigned_to,
|
||||
notes=f"Pelepasan komponen CI: {ci.name} ({ci.ci_code}). {notes}".strip()
|
||||
)
|
||||
|
||||
messages.success(request, f'{ci.name} berhasil dilepas dan status diperbarui ke {ci.get_status_display()}.')
|
||||
if request.headers.get('Accept') == 'application/json' or request.headers.get('x-requested-with') == 'XMLHttpRequest':
|
||||
return JsonResponse({'status': 'success'})
|
||||
|
||||
return redirect('ci_list')
|
||||
|
||||
|
||||
@login_required
|
||||
@operator_required
|
||||
def ci_replace(request, ci_id):
|
||||
"""Alur 'Ganti / Upgrade Komponen': Menggantikan komponen lama yang terpasang pada
|
||||
suatu perangkat dengan komponen baru/cadangan dalam satu transaksi atomik.
|
||||
"""
|
||||
old_ci = get_object_or_404(ConfigurationItem, id=ci_id)
|
||||
|
||||
if request.method == 'POST':
|
||||
replacement_ci_id = request.POST.get('replacement_ci_id')
|
||||
reason = request.POST.get('reason', 'Replacement Kerusakan')
|
||||
old_ci_status = request.POST.get('old_ci_status', 'under_repair') # under_repair, available, retired
|
||||
old_ci_condition = request.POST.get('old_ci_condition', 'damaged')
|
||||
old_ci_location = request.POST.get('old_ci_location', 'Gudang Perbaikan')
|
||||
notes = request.POST.get('notes', '').strip()
|
||||
|
||||
if not old_ci.installed_on:
|
||||
messages.error(request, f'Komponen {old_ci.ci_code} tidak terpasang pada perangkat apapun.')
|
||||
return redirect('ci_list')
|
||||
|
||||
new_ci = get_object_or_404(ConfigurationItem, id=replacement_ci_id)
|
||||
|
||||
if new_ci.id == old_ci.id:
|
||||
messages.error(request, 'Komponen pengganti tidak boleh sama dengan komponen yang diganti.')
|
||||
return redirect('ci_list')
|
||||
|
||||
if new_ci.status != 'available':
|
||||
messages.error(request, f'Komponen pengganti {new_ci.ci_code} tidak berstatus Tersedia (sedang {new_ci.get_status_display()}).')
|
||||
return redirect('ci_list')
|
||||
|
||||
target_unit = old_ci.installed_on
|
||||
|
||||
with transaction.atomic():
|
||||
# 1. Lepas komponen lama
|
||||
old_ci.installed_on = None
|
||||
old_ci.assigned_to = None
|
||||
old_ci.status = old_ci_status
|
||||
old_ci.condition = old_ci_condition
|
||||
old_ci.location = old_ci_location
|
||||
old_ci.save()
|
||||
|
||||
# 2. Pasang komponen baru
|
||||
new_ci.installed_on = target_unit
|
||||
new_ci.assigned_to = None
|
||||
new_ci.status = 'in_use'
|
||||
new_ci.location = None
|
||||
new_ci.save()
|
||||
|
||||
# 3. Catat history komponen lama
|
||||
CIHistory.objects.create(
|
||||
ci=old_ci,
|
||||
action='replaced',
|
||||
related_unit=target_unit,
|
||||
performed_by=request.user,
|
||||
notes=f"Dilepas dari unit {target_unit.unit_code} dan digantikan oleh {new_ci.ci_code} ({new_ci.name}) [Alasan: {reason}]. {notes}".strip()
|
||||
)
|
||||
|
||||
# 4. Catat history komponen baru
|
||||
CIHistory.objects.create(
|
||||
ci=new_ci,
|
||||
action='installed',
|
||||
related_unit=target_unit,
|
||||
performed_by=request.user,
|
||||
notes=f"Dipasang pada unit {target_unit.unit_code} menggantikan komponen lama {old_ci.ci_code} ({old_ci.name}) [Alasan: {reason}]. {notes}".strip()
|
||||
)
|
||||
|
||||
# 5. Rekam jejak di UnitLog perangkat induk
|
||||
UnitLog.objects.create(
|
||||
unit=target_unit,
|
||||
action='other',
|
||||
employee=target_unit.assigned_to,
|
||||
notes=f"Upgrade/Penggantian Komponen: {old_ci.name} digantikan oleh {new_ci.name}. Alasan: {reason}. {notes}".strip()
|
||||
)
|
||||
|
||||
messages.success(request, f'Penggantian komponen pada unit {target_unit.unit_code} berhasil: {new_ci.ci_code} menggantikan {old_ci.ci_code}.')
|
||||
if request.headers.get('Accept') == 'application/json' or request.headers.get('x-requested-with') == 'XMLHttpRequest':
|
||||
return JsonResponse({'status': 'success'})
|
||||
|
||||
return redirect('ci_list')
|
||||
|
||||
|
||||
@login_required
|
||||
@operator_required
|
||||
def ci_report_damage(request, ci_id):
|
||||
"""Melaporkan keluhan kerusakan pada CI dan mengarahkan ke status pemeriksaan/perbaikan."""
|
||||
ci = get_object_or_404(ConfigurationItem, id=ci_id)
|
||||
|
||||
if request.method == 'POST':
|
||||
action_type = request.POST.get('action_type', 'repair_in') # 'repair_in' atau 'repair_out'
|
||||
condition = request.POST.get('condition', 'damaged')
|
||||
notes = request.POST.get('notes', '').strip()
|
||||
|
||||
if action_type == 'repair_in':
|
||||
ci.status = 'under_repair'
|
||||
ci.condition = condition
|
||||
ci.save()
|
||||
|
||||
CIHistory.objects.create(
|
||||
ci=ci,
|
||||
action='repair_in',
|
||||
performed_by=request.user,
|
||||
notes=f"Dilaporkan rusak / masuk perbaikan. Kondisi: {ci.get_condition_display()}. Catatan: {notes}"
|
||||
)
|
||||
messages.success(request, f'Komponen {ci.ci_code} ditandai masuk perbaikan.')
|
||||
|
||||
elif action_type == 'repair_out':
|
||||
ci.status = 'available'
|
||||
ci.condition = 'good'
|
||||
ci.location = request.POST.get('location', 'Gudang IT')
|
||||
ci.save()
|
||||
|
||||
CIHistory.objects.create(
|
||||
ci=ci,
|
||||
action='repair_out',
|
||||
performed_by=request.user,
|
||||
notes=f"Perbaikan selesai, kondisi dinyatakan bagus dan siap digunakan di {ci.location}. Catatan: {notes}"
|
||||
)
|
||||
messages.success(request, f'Komponen {ci.ci_code} selesai diperbaiki dan siap digunakan.')
|
||||
|
||||
return redirect(request.META.get('HTTP_REFERER', 'ci_list'))
|
||||
File diff suppressed because it is too large
Load Diff
@@ -0,0 +1,292 @@
|
||||
import os
|
||||
import datetime
|
||||
import re
|
||||
from django.shortcuts import render, redirect, get_object_or_404
|
||||
from django.contrib.auth.decorators import login_required
|
||||
from django.contrib import messages
|
||||
from django.db import transaction
|
||||
from django.db.models import Q
|
||||
from django.core.paginator import Paginator
|
||||
from assets.models import AssetAssignment, AssetUnit, Employee, UnitLog
|
||||
from assets.permissions import operator_required
|
||||
|
||||
|
||||
def validate_uploaded_document(doc):
|
||||
"""Memvalidasi format dan batas ukuran berkas BAST yang diunggah."""
|
||||
ext = os.path.splitext(doc.name)[1].lower()
|
||||
allowed_ext = ['.pdf', '.doc', '.docx', '.jpg', '.jpeg', '.png']
|
||||
if ext not in allowed_ext:
|
||||
return False, f'Format file tidak diizinkan. Gunakan: {", ".join(allowed_ext)}'
|
||||
if doc.size > 5 * 1024 * 1024:
|
||||
return False, 'Ukuran file maksimal 5MB.'
|
||||
return True, None
|
||||
|
||||
|
||||
@login_required
|
||||
def distribusi_list(request):
|
||||
"""Menampilkan daftar riwayat transaksi serah terima, mutasi, dan pengembalian dengan paginasi."""
|
||||
tab = request.GET.get('tab', 'handover')
|
||||
if not tab:
|
||||
tab = 'handover'
|
||||
search_query = request.GET.get('q', '').strip()
|
||||
sort_order = request.GET.get('sort', 'desc')
|
||||
|
||||
assignments_qs = AssetAssignment.objects.filter(type=tab).select_related(
|
||||
'unit', 'unit__asset', 'employee', 'from_employee'
|
||||
)
|
||||
|
||||
if sort_order == 'asc':
|
||||
assignments_qs = assignments_qs.order_by('assigned_date', 'id')
|
||||
else:
|
||||
assignments_qs = assignments_qs.order_by('-assigned_date', '-id')
|
||||
|
||||
if search_query:
|
||||
date_q = Q(assigned_date__icontains=search_query)
|
||||
query_lower = search_query.lower()
|
||||
months = {
|
||||
'jan': 1, 'feb': 2, 'mar': 3, 'apr': 4, 'mei': 5, 'may': 5, 'jun': 6,
|
||||
'jul': 7, 'agu': 8, 'aug': 8, 'sep': 9, 'okt': 10, 'oct': 10, 'nov': 11, 'des': 12, 'dec': 12
|
||||
}
|
||||
|
||||
try:
|
||||
dt = datetime.datetime.strptime(query_lower.title(), "%d %b %Y")
|
||||
date_q = Q(assigned_date=dt.date())
|
||||
except ValueError:
|
||||
month_val = None
|
||||
for k, v in months.items():
|
||||
if k in query_lower:
|
||||
month_val = v
|
||||
break
|
||||
|
||||
year_match = re.search(r' (20\d{2}) ', query_lower)
|
||||
year_val = int(year_match.group(1)) if year_match else None
|
||||
|
||||
day_match = re.search(r' (0?[1-9]|[12]\d|3[01]) ', query_lower)
|
||||
day_val = int(day_match.group(1)) if day_match and len(query_lower) <= 2 else None
|
||||
|
||||
if month_val and year_val:
|
||||
date_q = Q(assigned_date__month=month_val, assigned_date__year=year_val)
|
||||
elif month_val:
|
||||
date_q = Q(assigned_date__month=month_val)
|
||||
elif year_val:
|
||||
date_q = Q(assigned_date__year=year_val)
|
||||
elif day_val:
|
||||
date_q = Q(assigned_date__day=day_val)
|
||||
|
||||
assignments_qs = assignments_qs.filter(
|
||||
Q(unit__unit_code__icontains=search_query) |
|
||||
Q(unit__asset__name__icontains=search_query) |
|
||||
Q(employee__name__icontains=search_query) |
|
||||
Q(employee__nik__icontains=search_query) |
|
||||
Q(from_employee__name__icontains=search_query) |
|
||||
Q(from_employee__nik__icontains=search_query) |
|
||||
date_q
|
||||
)
|
||||
|
||||
counts = {
|
||||
'handover': AssetAssignment.objects.filter(type='handover').count(),
|
||||
'mutation': AssetAssignment.objects.filter(type='mutation').count(),
|
||||
'return': AssetAssignment.objects.filter(type='return').count(),
|
||||
}
|
||||
|
||||
available_units = AssetUnit.objects.filter(
|
||||
status='tersedia', asset__category__name__icontains='Karyawan'
|
||||
).select_related('asset').order_by('asset__name', 'unit_code')
|
||||
|
||||
used_units = AssetUnit.objects.filter(
|
||||
status='digunakan', asset__category__name__icontains='Karyawan'
|
||||
).select_related('asset', 'assigned_to').order_by('asset__name', 'unit_code')
|
||||
# Ambil data karyawan aktif untuk pilihan form handover & mutation
|
||||
employees = Employee.objects.filter(is_active=True).order_by('name')
|
||||
|
||||
# Implementasi Pagination (25 baris per halaman)
|
||||
paginator = Paginator(assignments_qs, 25)
|
||||
page_number = request.GET.get('page')
|
||||
page_obj = paginator.get_page(page_number)
|
||||
|
||||
return render(request, 'distribusi_list.html', {
|
||||
'assignments': page_obj,
|
||||
'page_obj': page_obj,
|
||||
'tab': tab,
|
||||
'search_query': search_query,
|
||||
'counts': counts,
|
||||
'available_units': available_units,
|
||||
'used_units': used_units,
|
||||
'employees': employees,
|
||||
})
|
||||
|
||||
|
||||
@login_required
|
||||
@operator_required
|
||||
@transaction.atomic
|
||||
def distribusi_handover(request):
|
||||
"""Memproses transaksi serah terima aset dari gudang ke karyawan."""
|
||||
if request.method == 'POST':
|
||||
unit_id = request.POST.get('unit')
|
||||
employee_id = request.POST.get('employee')
|
||||
assigned_date = request.POST.get('assigned_date')
|
||||
notes = request.POST.get('notes', '')
|
||||
document = request.FILES.get('document')
|
||||
|
||||
if document:
|
||||
is_valid, err_msg = validate_uploaded_document(document)
|
||||
if not is_valid:
|
||||
messages.error(request, err_msg)
|
||||
return redirect('/distribusi/?tab=handover')
|
||||
|
||||
unit = get_object_or_404(AssetUnit, id=unit_id)
|
||||
employee = get_object_or_404(Employee, id=employee_id)
|
||||
|
||||
AssetAssignment.objects.create(
|
||||
type='handover',
|
||||
unit=unit,
|
||||
employee=employee,
|
||||
assigned_date=assigned_date,
|
||||
status='aktif',
|
||||
notes=notes,
|
||||
document=document
|
||||
)
|
||||
|
||||
unit.status = 'digunakan'
|
||||
unit.assigned_to = employee
|
||||
unit.save()
|
||||
|
||||
UnitLog.objects.create(
|
||||
unit=unit,
|
||||
action='assigned',
|
||||
employee=employee,
|
||||
notes=f"Diserahkan melalui Distribusi Aset. {notes}".strip()
|
||||
)
|
||||
messages.success(request, "Serah terima aset berhasil diproses.")
|
||||
return redirect('/distribusi/?tab=handover')
|
||||
|
||||
|
||||
@login_required
|
||||
@operator_required
|
||||
@transaction.atomic
|
||||
def distribusi_mutation(request):
|
||||
"""Memproses transaksi mutasi aset antar karyawan."""
|
||||
if request.method == 'POST':
|
||||
unit_id = request.POST.get('unit')
|
||||
new_employee_id = request.POST.get('employee')
|
||||
assigned_date = request.POST.get('assigned_date')
|
||||
notes = request.POST.get('notes', '')
|
||||
document = request.FILES.get('document')
|
||||
|
||||
if document:
|
||||
is_valid, err_msg = validate_uploaded_document(document)
|
||||
if not is_valid:
|
||||
messages.error(request, err_msg)
|
||||
return redirect('/distribusi/?tab=mutation')
|
||||
|
||||
unit = get_object_or_404(AssetUnit, id=unit_id)
|
||||
old_employee = unit.assigned_to
|
||||
new_employee = get_object_or_404(Employee, id=new_employee_id)
|
||||
|
||||
# Update assignment aktif sebelumnya jika ada
|
||||
AssetAssignment.objects.filter(unit=unit, status='aktif').update(
|
||||
status='dikembalikan',
|
||||
returned_date=assigned_date
|
||||
)
|
||||
|
||||
AssetAssignment.objects.create(
|
||||
type='mutation',
|
||||
unit=unit,
|
||||
from_employee=old_employee,
|
||||
employee=new_employee,
|
||||
assigned_date=assigned_date,
|
||||
status='aktif',
|
||||
notes=notes,
|
||||
document=document
|
||||
)
|
||||
|
||||
unit.assigned_to = new_employee
|
||||
unit.save()
|
||||
|
||||
UnitLog.objects.create(
|
||||
unit=unit,
|
||||
action='returned',
|
||||
employee=old_employee,
|
||||
notes="Mutasi: Dikembalikan oleh pemegang sebelumnya."
|
||||
)
|
||||
UnitLog.objects.create(
|
||||
unit=unit,
|
||||
action='assigned',
|
||||
employee=new_employee,
|
||||
notes=f"Mutasi: Diserahkan ke pemegang baru. {notes}".strip()
|
||||
)
|
||||
messages.success(request, "Mutasi aset berhasil diproses.")
|
||||
return redirect('/distribusi/?tab=mutation')
|
||||
|
||||
|
||||
@login_required
|
||||
@operator_required
|
||||
@transaction.atomic
|
||||
def distribusi_return(request):
|
||||
"""Memproses transaksi pengembalian aset dari karyawan kembali ke gudang."""
|
||||
if request.method == 'POST':
|
||||
unit_id = request.POST.get('unit')
|
||||
assigned_date = request.POST.get('assigned_date')
|
||||
notes = request.POST.get('notes', '')
|
||||
document = request.FILES.get('document')
|
||||
|
||||
if document:
|
||||
is_valid, err_msg = validate_uploaded_document(document)
|
||||
if not is_valid:
|
||||
messages.error(request, err_msg)
|
||||
return redirect('/distribusi/?tab=return')
|
||||
|
||||
unit = get_object_or_404(AssetUnit, id=unit_id)
|
||||
old_employee = unit.assigned_to
|
||||
|
||||
# Tutup assignment aktif sebelumnya untuk unit ini
|
||||
AssetAssignment.objects.filter(unit=unit, status='aktif').update(
|
||||
status='dikembalikan',
|
||||
returned_date=assigned_date
|
||||
)
|
||||
|
||||
AssetAssignment.objects.create(
|
||||
type='return',
|
||||
unit=unit,
|
||||
from_employee=old_employee,
|
||||
employee=old_employee,
|
||||
assigned_date=assigned_date,
|
||||
returned_date=assigned_date,
|
||||
status='dikembalikan',
|
||||
notes=notes,
|
||||
document=document
|
||||
)
|
||||
|
||||
unit.status = 'tersedia'
|
||||
unit.assigned_to = None
|
||||
unit.save()
|
||||
|
||||
UnitLog.objects.create(
|
||||
unit=unit,
|
||||
action='returned',
|
||||
employee=old_employee,
|
||||
notes=f"Dikembalikan oleh karyawan. {notes}".strip()
|
||||
)
|
||||
messages.success(request, "Pengembalian aset berhasil diproses.")
|
||||
return redirect('/distribusi/?tab=return')
|
||||
|
||||
|
||||
@login_required
|
||||
@operator_required
|
||||
def distribusi_upload_doc(request, assignment_id):
|
||||
"""Menangani pengunggahan berkas susulan dokumen BAST pada transaksi distribusi."""
|
||||
if request.method == 'POST':
|
||||
assignment = get_object_or_404(AssetAssignment, id=assignment_id)
|
||||
if 'document' in request.FILES:
|
||||
doc = request.FILES['document']
|
||||
is_valid, err_msg = validate_uploaded_document(doc)
|
||||
if not is_valid:
|
||||
messages.error(request, err_msg)
|
||||
return redirect(f"/distribusi/?tab={assignment.type}")
|
||||
|
||||
assignment.document = doc
|
||||
assignment.save()
|
||||
messages.success(request, "Dokumen berhasil diunggah.")
|
||||
tab = assignment.type
|
||||
return redirect(f'/distribusi/?tab={tab}')
|
||||
return redirect('/distribusi/')
|
||||
@@ -0,0 +1,143 @@
|
||||
from django.shortcuts import render, redirect, get_object_or_404
|
||||
from django.contrib.auth.decorators import login_required
|
||||
from django.contrib import messages
|
||||
from django.http import JsonResponse
|
||||
from django.db.models import Count, Q
|
||||
from django.core.paginator import Paginator
|
||||
from assets.models import Employee, UnitLog
|
||||
from assets.permissions import operator_required
|
||||
|
||||
|
||||
@login_required
|
||||
def employee_list(request):
|
||||
"""Menampilkan daftar karyawan dengan jumlah unit aset yang sedang dipegang dan dukungan pagination & soft delete."""
|
||||
search_query = request.GET.get('q', '').strip()
|
||||
status_filter = request.GET.get('status', 'aktif')
|
||||
|
||||
base_qs = Employee.objects.annotate(
|
||||
active_assets=Count('held_units')
|
||||
).order_by('name')
|
||||
|
||||
count_active = Employee.objects.filter(is_active=True).count()
|
||||
count_inactive = Employee.objects.filter(is_active=False).count()
|
||||
count_all = count_active + count_inactive
|
||||
|
||||
if status_filter == 'aktif':
|
||||
employees_qs = base_qs.filter(is_active=True)
|
||||
elif status_filter == 'nonaktif':
|
||||
employees_qs = base_qs.filter(is_active=False)
|
||||
else:
|
||||
employees_qs = base_qs
|
||||
|
||||
if search_query:
|
||||
employees_qs = employees_qs.filter(
|
||||
Q(name__icontains=search_query) |
|
||||
Q(nik__icontains=search_query)
|
||||
)
|
||||
|
||||
paginator = Paginator(employees_qs, 25)
|
||||
page_number = request.GET.get('page')
|
||||
page_obj = paginator.get_page(page_number)
|
||||
|
||||
return render(request, 'employee_list.html', {
|
||||
'employees': page_obj,
|
||||
'page_obj': page_obj,
|
||||
'search_query': search_query,
|
||||
'status_filter': status_filter,
|
||||
'count_active': count_active,
|
||||
'count_inactive': count_inactive,
|
||||
'count_all': count_all,
|
||||
})
|
||||
|
||||
|
||||
@login_required
|
||||
def employee_detail(request, emp_id):
|
||||
"""Menampilkan rincian profil karyawan dan unit aset spesifik yang sedang dipinjam."""
|
||||
employee = get_object_or_404(Employee, id=emp_id)
|
||||
units = employee.held_units.select_related('asset').all()
|
||||
return render(request, 'employee_detail.html', {
|
||||
'employee': employee,
|
||||
'units': units
|
||||
})
|
||||
|
||||
|
||||
@login_required
|
||||
@operator_required
|
||||
def employee_create(request):
|
||||
"""Menambahkan data karyawan baru."""
|
||||
if request.method == 'POST':
|
||||
nik = request.POST.get('nik', '').strip()
|
||||
name = request.POST.get('name', '').strip()
|
||||
position = request.POST.get('position', '').strip()
|
||||
|
||||
if Employee.objects.filter(nik=nik).exists():
|
||||
if request.headers.get('Accept') == 'application/json' or request.headers.get('x-requested-with') == 'XMLHttpRequest':
|
||||
return JsonResponse({'status': 'error', 'message': f'NIK "{nik}" sudah terdaftar!'}, status=400)
|
||||
messages.error(request, f'NIK "{nik}" sudah terdaftar!')
|
||||
return redirect('employee_list')
|
||||
|
||||
Employee.objects.create(nik=nik, name=name, position=position, is_active=True)
|
||||
messages.success(request, "Data karyawan berhasil ditambahkan.")
|
||||
|
||||
if request.headers.get('Accept') == 'application/json' or request.headers.get('x-requested-with') == 'XMLHttpRequest':
|
||||
return JsonResponse({'status': 'success'})
|
||||
|
||||
return redirect('employee_list')
|
||||
|
||||
|
||||
@login_required
|
||||
@operator_required
|
||||
def employee_edit(request, emp_id):
|
||||
"""Memperbarui informasi data karyawan."""
|
||||
employee = get_object_or_404(Employee, id=emp_id)
|
||||
if request.method == 'POST':
|
||||
nik = request.POST.get('nik', '').strip()
|
||||
name = request.POST.get('name', '').strip()
|
||||
position = request.POST.get('position', '').strip()
|
||||
|
||||
if Employee.objects.filter(nik=nik).exclude(id=emp_id).exists():
|
||||
if request.headers.get('Accept') == 'application/json' or request.headers.get('x-requested-with') == 'XMLHttpRequest':
|
||||
return JsonResponse({'status': 'error', 'message': f'NIK "{nik}" sudah terdaftar pada karyawan lain!'}, status=400)
|
||||
messages.error(request, f'NIK "{nik}" sudah terdaftar pada karyawan lain!')
|
||||
return redirect('employee_list')
|
||||
|
||||
employee.nik = nik
|
||||
employee.name = name
|
||||
employee.position = position
|
||||
employee.save()
|
||||
messages.success(request, "Perubahan data karyawan berhasil disimpan.")
|
||||
|
||||
if request.headers.get('Accept') == 'application/json' or request.headers.get('x-requested-with') == 'XMLHttpRequest':
|
||||
return JsonResponse({'status': 'success'})
|
||||
|
||||
return redirect('employee_list')
|
||||
|
||||
|
||||
@login_required
|
||||
@operator_required
|
||||
def employee_delete(request, emp_id):
|
||||
"""Menonaktifkan data karyawan (soft delete) untuk menjaga integritas riwayat transaksi."""
|
||||
employee = get_object_or_404(Employee, id=emp_id)
|
||||
if request.method == 'POST':
|
||||
# Larang penonaktifan jika karyawan masih memegang unit aktif
|
||||
if employee.held_units.count() > 0:
|
||||
messages.error(request, "Karyawan tidak dapat dinonaktifkan karena masih memegang unit aset.")
|
||||
return redirect('employee_list')
|
||||
|
||||
# Soft delete: tandai is_active = False tanpa menghapus baris riwayat di database
|
||||
employee.is_active = False
|
||||
employee.save()
|
||||
messages.success(request, f"Data karyawan {employee.name} berhasil dinonaktifkan.")
|
||||
return redirect('employee_list')
|
||||
|
||||
|
||||
@login_required
|
||||
@operator_required
|
||||
def employee_activate(request, emp_id):
|
||||
"""Mengaktifkan kembali data karyawan yang sebelumnya dinonaktifkan."""
|
||||
employee = get_object_or_404(Employee, id=emp_id)
|
||||
if request.method == 'POST':
|
||||
employee.is_active = True
|
||||
employee.save()
|
||||
messages.success(request, f"Data karyawan {employee.name} berhasil diaktifkan kembali.")
|
||||
return redirect('employee_list')
|
||||
@@ -0,0 +1,59 @@
|
||||
import qrcode
|
||||
from PIL import Image, ImageDraw, ImageFont
|
||||
from django.shortcuts import render, get_object_or_404
|
||||
from django.http import HttpResponse
|
||||
from assets.models import AssetUnit, UnitLog
|
||||
|
||||
|
||||
def unit_qr_code(request, uuid):
|
||||
"""Menghasilkan gambar PNG QR Code unik dengan label nama aset dan kode unit."""
|
||||
unit = get_object_or_404(AssetUnit, id_uuid=uuid)
|
||||
url = request.build_absolute_uri(f'/public/unit/{uuid}/')
|
||||
|
||||
qr = qrcode.QRCode(version=1, box_size=12, border=2)
|
||||
qr.add_data(url)
|
||||
qr.make(fit=True)
|
||||
|
||||
qr_img = qr.make_image(fill_color="black", back_color="white").convert('RGB')
|
||||
text = f"{unit.asset.name} - {unit.unit_code}"
|
||||
|
||||
try:
|
||||
font = ImageFont.truetype("arial.ttf", 20)
|
||||
except Exception:
|
||||
font = ImageFont.load_default()
|
||||
|
||||
qr_w, qr_h = qr_img.size
|
||||
|
||||
try:
|
||||
bbox = font.getbbox(text)
|
||||
text_w = bbox[2] - bbox[0]
|
||||
text_h = bbox[3] - bbox[1]
|
||||
except AttributeError:
|
||||
text_w, text_h = font.getsize(text)
|
||||
|
||||
padding = 20
|
||||
new_h = qr_h + text_h + padding * 2
|
||||
new_w = max(qr_w, text_w + padding * 2)
|
||||
|
||||
img = Image.new('RGB', (new_w, new_h), color='white')
|
||||
img.paste(qr_img, ((new_w - qr_w) // 2, padding // 2))
|
||||
|
||||
draw = ImageDraw.Draw(img)
|
||||
text_x = (new_w - text_w) // 2
|
||||
text_y = qr_h + (padding // 2) + 5
|
||||
draw.text((text_x, text_y), text, font=font, fill="black")
|
||||
|
||||
response = HttpResponse(content_type="image/png")
|
||||
img.save(response, "PNG")
|
||||
return response
|
||||
|
||||
|
||||
def unit_public_detail(request, uuid):
|
||||
"""Halaman publik detail unit aset dan riwayat yang diakses saat memindai QR Code."""
|
||||
unit = get_object_or_404(AssetUnit, id_uuid=uuid)
|
||||
logs = UnitLog.objects.filter(unit=unit).order_by('-timestamp')
|
||||
|
||||
return render(request, 'unit_public_detail.html', {
|
||||
'unit': unit,
|
||||
'logs': logs
|
||||
})
|
||||
@@ -0,0 +1,579 @@
|
||||
import openpyxl
|
||||
from openpyxl.styles import Font, PatternFill, Alignment, Border, Side
|
||||
from openpyxl.utils import get_column_letter
|
||||
|
||||
from django.shortcuts import get_object_or_404
|
||||
from django.http import HttpResponse
|
||||
from django.contrib.auth.decorators import login_required
|
||||
from django.utils import timezone
|
||||
from django.db.models import Q
|
||||
|
||||
from assets.models import Asset, AssetUnit, Category, Employee, AssetAssignment, UnitLog
|
||||
|
||||
@login_required
|
||||
def asset_export_excel(request):
|
||||
"""Generate Excel report for assets."""
|
||||
from openpyxl import Workbook
|
||||
from openpyxl.styles import Font, Alignment, PatternFill, Border, Side
|
||||
from django.http import HttpResponse
|
||||
from django.db.models import Count, Q
|
||||
import datetime
|
||||
|
||||
# Get the tab filter
|
||||
tab = request.GET.get('tab', 'all')
|
||||
search_query = request.GET.get('q', '').strip()
|
||||
|
||||
assets = Asset.objects.annotate(
|
||||
tersedia_count=Count('units', filter=Q(units__status='tersedia')),
|
||||
digunakan_count=Count('units', filter=Q(units__status='digunakan')),
|
||||
rusak_count=Count('units', filter=Q(units__status='rusak')),
|
||||
total_unit_count=Count('units')
|
||||
).order_by('name')
|
||||
|
||||
category_label = 'Semua Kategori'
|
||||
|
||||
if tab == 'karyawan':
|
||||
assets = assets.exclude(category__name__icontains='Network')
|
||||
category_label = 'Aset Karyawan'
|
||||
elif tab == 'networking':
|
||||
assets = assets.filter(category__name__icontains='Network')
|
||||
category_label = 'Aset Network & Infrastruktur'
|
||||
|
||||
if search_query:
|
||||
assets = assets.filter(
|
||||
Q(name__icontains=search_query) |
|
||||
Q(asset_code__icontains=search_query) |
|
||||
Q(brand__icontains=search_query)
|
||||
)
|
||||
|
||||
wb = Workbook()
|
||||
ws = wb.active
|
||||
ws.title = "Daftar Aset"
|
||||
|
||||
# Header styles
|
||||
header_font = Font(bold=True, color="FFFFFF")
|
||||
header_fill = PatternFill(start_color="002060", end_color="002060", fill_type="solid")
|
||||
center_align = Alignment(horizontal="center", vertical="center")
|
||||
left_align = Alignment(horizontal="left", vertical="center")
|
||||
border = Border(left=Side(style='thin'), right=Side(style='thin'), top=Side(style='thin'), bottom=Side(style='thin'))
|
||||
|
||||
# Write metadata
|
||||
ws.merge_cells('A1:I1')
|
||||
ws['A1'] = "LAPORAN DAFTAR ASET IT"
|
||||
ws['A1'].font = Font(bold=True, size=14)
|
||||
ws['A1'].alignment = center_align
|
||||
|
||||
ws.merge_cells('A2:I2')
|
||||
ws['A2'] = f"Kategori: {category_label}"
|
||||
ws['A2'].alignment = center_align
|
||||
|
||||
ws.merge_cells('A3:I3')
|
||||
ws['A3'] = f"Tanggal Dicetak: {datetime.datetime.now().strftime('%d-%m-%Y %H:%M')}"
|
||||
ws['A3'].alignment = center_align
|
||||
|
||||
# Headers
|
||||
headers = ['No', 'Kode Aset', 'Kategori', 'Merek', 'Nama Aset', 'Total (Qty)', 'Tersedia', 'Digunakan', 'Maintenance']
|
||||
for col_num, header_title in enumerate(headers, 1):
|
||||
cell = ws.cell(row=5, column=col_num, value=header_title)
|
||||
cell.font = header_font
|
||||
cell.fill = header_fill
|
||||
cell.alignment = center_align
|
||||
cell.border = border
|
||||
|
||||
# Write data
|
||||
for idx, asset in enumerate(assets, 1):
|
||||
row_num = idx + 5
|
||||
data = [
|
||||
idx,
|
||||
asset.asset_code,
|
||||
asset.category.name if asset.category else '-',
|
||||
asset.brand,
|
||||
asset.name,
|
||||
asset.qty,
|
||||
asset.tersedia_count,
|
||||
asset.digunakan_count,
|
||||
asset.rusak_count
|
||||
]
|
||||
|
||||
for col_num, cell_value in enumerate(data, 1):
|
||||
cell = ws.cell(row=row_num, column=col_num, value=cell_value)
|
||||
cell.border = border
|
||||
if col_num in [1, 6, 7, 8, 9]:
|
||||
cell.alignment = center_align
|
||||
else:
|
||||
cell.alignment = left_align
|
||||
|
||||
# Adjust column widths
|
||||
column_widths = {'A': 5, 'B': 15, 'C': 20, 'D': 15, 'E': 40, 'F': 12, 'G': 12, 'H': 12, 'I': 15}
|
||||
for col, width in column_widths.items():
|
||||
ws.column_dimensions[col].width = width
|
||||
|
||||
# Prepare response
|
||||
response = HttpResponse(content_type='application/vnd.openxmlformats-officedocument.spreadsheetml.sheet')
|
||||
now_str = datetime.datetime.now().strftime('%Y%m%d_%H%M')
|
||||
response['Content-Disposition'] = f'attachment; filename="Laporan_Aset_{now_str}.xlsx"'
|
||||
|
||||
wb.save(response)
|
||||
return response
|
||||
|
||||
|
||||
|
||||
@login_required
|
||||
def distribusi_export_excel(request):
|
||||
from openpyxl import Workbook
|
||||
from openpyxl.styles import Font, Alignment, PatternFill, Border, Side
|
||||
from django.http import HttpResponse
|
||||
import datetime
|
||||
|
||||
tab = request.GET.get('tab', 'semua')
|
||||
assignments = AssetAssignment.objects.select_related('unit__asset', 'employee', 'from_employee').order_by('-assigned_date')
|
||||
|
||||
if tab == 'aktif':
|
||||
assignments = assignments.filter(status='aktif')
|
||||
status_label = 'Aktif'
|
||||
elif tab == 'kembali':
|
||||
assignments = assignments.filter(status='dikembalikan')
|
||||
status_label = 'Dikembalikan'
|
||||
else:
|
||||
status_label = 'Semua'
|
||||
|
||||
wb = Workbook()
|
||||
ws = wb.active
|
||||
ws.title = "Data Distribusi"
|
||||
|
||||
header_font = Font(bold=True, color="FFFFFF")
|
||||
header_fill = PatternFill(start_color="002060", end_color="002060", fill_type="solid")
|
||||
center_align = Alignment(horizontal="center", vertical="center")
|
||||
left_align = Alignment(horizontal="left", vertical="center")
|
||||
border = Border(left=Side(style='thin'), right=Side(style='thin'), top=Side(style='thin'), bottom=Side(style='thin'))
|
||||
|
||||
ws.merge_cells('A1:G1')
|
||||
ws['A1'] = "LAPORAN DISTRIBUSI ASET"
|
||||
ws['A1'].font = Font(bold=True, size=14)
|
||||
ws['A1'].alignment = center_align
|
||||
|
||||
ws.merge_cells('A2:G2')
|
||||
ws['A2'] = f"Status: {status_label}"
|
||||
ws['A2'].alignment = center_align
|
||||
|
||||
headers = ['No', 'Tanggal', 'Tipe', 'Kode Unit', 'Aset', 'Pihak Terkait', 'Status']
|
||||
for col_num, header_title in enumerate(headers, 1):
|
||||
cell = ws.cell(row=4, column=col_num, value=header_title)
|
||||
cell.font = header_font
|
||||
cell.fill = header_fill
|
||||
cell.alignment = center_align
|
||||
cell.border = border
|
||||
|
||||
for idx, a in enumerate(assignments, 1):
|
||||
row_num = idx + 4
|
||||
|
||||
pihak = ""
|
||||
if a.type == 'handover':
|
||||
pihak = a.employee.name if a.employee else "-"
|
||||
elif a.type == 'return':
|
||||
pihak = f"Dari: {a.employee.name if a.employee else '-'}"
|
||||
elif a.type == 'mutation':
|
||||
from_name = a.from_employee.name if a.from_employee else "-"
|
||||
to_name = a.employee.name if a.employee else "-"
|
||||
pihak = f"{from_name} -> {to_name}"
|
||||
|
||||
tipe = dict(AssetAssignment.TYPE_CHOICES).get(a.type, a.type)
|
||||
status_str = "Aktif" if a.status == 'aktif' else "Dikembalikan"
|
||||
|
||||
data = [
|
||||
idx,
|
||||
a.assigned_date.strftime('%d %b %Y') if a.assigned_date else '-',
|
||||
tipe,
|
||||
a.unit.unit_code if a.unit else '-',
|
||||
a.unit.asset.name if a.unit and a.unit.asset else '-',
|
||||
pihak,
|
||||
status_str
|
||||
]
|
||||
|
||||
for col_num, cell_value in enumerate(data, 1):
|
||||
cell = ws.cell(row=row_num, column=col_num, value=cell_value)
|
||||
cell.border = border
|
||||
if col_num in [1, 2, 3, 4, 7]:
|
||||
cell.alignment = center_align
|
||||
else:
|
||||
cell.alignment = left_align
|
||||
|
||||
for col, width in zip(['A','B','C','D','E','F','G'], [5, 15, 15, 15, 30, 30, 15]):
|
||||
ws.column_dimensions[col].width = width
|
||||
|
||||
response = HttpResponse(content_type='application/vnd.openxmlformats-officedocument.spreadsheetml.sheet')
|
||||
now_str = datetime.datetime.now().strftime('%Y%m%d_%H%M')
|
||||
response['Content-Disposition'] = f'attachment; filename="Distribusi_{now_str}.xlsx"'
|
||||
wb.save(response)
|
||||
return response
|
||||
|
||||
@login_required
|
||||
def status_aset_export_excel(request):
|
||||
from openpyxl import Workbook
|
||||
from openpyxl.styles import Font, Alignment, PatternFill, Border, Side
|
||||
from django.http import HttpResponse
|
||||
from django.db.models import Count, Q
|
||||
import datetime
|
||||
|
||||
tab = request.GET.get('tab', 'semua')
|
||||
|
||||
units = AssetUnit.objects.select_related('asset', 'asset__category').all()
|
||||
if tab == 'tersedia':
|
||||
units = units.filter(status='tersedia')
|
||||
title_label = "Aset Tersedia"
|
||||
elif tab == 'digunakan':
|
||||
units = units.filter(status='digunakan')
|
||||
title_label = "Aset Digunakan"
|
||||
elif tab == 'rusak':
|
||||
units = units.filter(status='rusak')
|
||||
title_label = "Aset Maintenance / Rusak"
|
||||
else:
|
||||
title_label = "Semua Status Aset"
|
||||
|
||||
wb = Workbook()
|
||||
ws = wb.active
|
||||
ws.title = "Status Aset"
|
||||
|
||||
header_font = Font(bold=True, color="FFFFFF")
|
||||
header_fill = PatternFill(start_color="002060", end_color="002060", fill_type="solid")
|
||||
center_align = Alignment(horizontal="center", vertical="center")
|
||||
left_align = Alignment(horizontal="left", vertical="center")
|
||||
border = Border(left=Side(style='thin'), right=Side(style='thin'), top=Side(style='thin'), bottom=Side(style='thin'))
|
||||
|
||||
ws.merge_cells('A1:F1')
|
||||
ws['A1'] = "LAPORAN STATUS UNIT ASET"
|
||||
ws['A1'].font = Font(bold=True, size=14)
|
||||
ws['A1'].alignment = center_align
|
||||
|
||||
ws.merge_cells('A2:F2')
|
||||
ws['A2'] = f"Kategori: {title_label}"
|
||||
ws['A2'].alignment = center_align
|
||||
|
||||
headers = ['No', 'Kode Unit', 'Nama Aset', 'Area', 'Status', 'Lokasi']
|
||||
for col_num, header_title in enumerate(headers, 1):
|
||||
cell = ws.cell(row=4, column=col_num, value=header_title)
|
||||
cell.font = header_font
|
||||
cell.fill = header_fill
|
||||
cell.alignment = center_align
|
||||
cell.border = border
|
||||
|
||||
for idx, u in enumerate(units, 1):
|
||||
row_num = idx + 4
|
||||
|
||||
status_map = {'tersedia': 'Tersedia', 'digunakan': 'Digunakan', 'rusak': 'Maintenance'}
|
||||
|
||||
data = [
|
||||
idx,
|
||||
u.unit_code,
|
||||
u.asset.name if u.asset else '-',
|
||||
u.area or '-',
|
||||
status_map.get(u.status, u.status),
|
||||
u.location or '-'
|
||||
]
|
||||
|
||||
for col_num, cell_value in enumerate(data, 1):
|
||||
cell = ws.cell(row=row_num, column=col_num, value=cell_value)
|
||||
cell.border = border
|
||||
if col_num in [1, 2, 5]:
|
||||
cell.alignment = center_align
|
||||
else:
|
||||
cell.alignment = left_align
|
||||
|
||||
for col, width in zip(['A','B','C','D','E','F'], [5, 15, 30, 20, 15, 30]):
|
||||
ws.column_dimensions[col].width = width
|
||||
|
||||
response = HttpResponse(content_type='application/vnd.openxmlformats-officedocument.spreadsheetml.sheet')
|
||||
now_str = datetime.datetime.now().strftime('%Y%m%d_%H%M')
|
||||
response['Content-Disposition'] = f'attachment; filename="Status_Aset_{now_str}.xlsx"'
|
||||
wb.save(response)
|
||||
return response
|
||||
|
||||
@login_required
|
||||
def employee_export_excel(request):
|
||||
from openpyxl import Workbook
|
||||
from openpyxl.styles import Font, Alignment, PatternFill, Border, Side
|
||||
from django.http import HttpResponse
|
||||
import datetime
|
||||
|
||||
employees = Employee.objects.all().order_by('name')
|
||||
|
||||
wb = Workbook()
|
||||
ws = wb.active
|
||||
ws.title = "Data Karyawan"
|
||||
|
||||
header_font = Font(bold=True, color="FFFFFF")
|
||||
header_fill = PatternFill(start_color="002060", end_color="002060", fill_type="solid")
|
||||
center_align = Alignment(horizontal="center", vertical="center")
|
||||
left_align = Alignment(horizontal="left", vertical="center")
|
||||
border = Border(left=Side(style='thin'), right=Side(style='thin'), top=Side(style='thin'), bottom=Side(style='thin'))
|
||||
|
||||
ws.merge_cells('A1:D1')
|
||||
ws['A1'] = "LAPORAN DATA KARYAWAN"
|
||||
ws['A1'].font = Font(bold=True, size=14)
|
||||
ws['A1'].alignment = center_align
|
||||
|
||||
headers = ['No', 'NIK', 'Nama Karyawan', 'Jabatan']
|
||||
for col_num, header_title in enumerate(headers, 1):
|
||||
cell = ws.cell(row=4, column=col_num, value=header_title)
|
||||
cell.font = header_font
|
||||
cell.fill = header_fill
|
||||
cell.alignment = center_align
|
||||
cell.border = border
|
||||
|
||||
for idx, e in enumerate(employees, 1):
|
||||
row_num = idx + 4
|
||||
|
||||
data = [
|
||||
idx,
|
||||
e.nik,
|
||||
e.name,
|
||||
e.position or '-'
|
||||
]
|
||||
|
||||
for col_num, cell_value in enumerate(data, 1):
|
||||
cell = ws.cell(row=row_num, column=col_num, value=cell_value)
|
||||
cell.border = border
|
||||
if col_num in [1, 2]:
|
||||
cell.alignment = center_align
|
||||
else:
|
||||
cell.alignment = left_align
|
||||
|
||||
for col, width in zip(['A','B','C','D'], [5, 15, 35, 35]):
|
||||
ws.column_dimensions[col].width = width
|
||||
|
||||
response = HttpResponse(content_type='application/vnd.openxmlformats-officedocument.spreadsheetml.sheet')
|
||||
now_str = datetime.datetime.now().strftime('%Y%m%d_%H%M')
|
||||
response['Content-Disposition'] = f'attachment; filename="Karyawan_{now_str}.xlsx"'
|
||||
wb.save(response)
|
||||
return response
|
||||
|
||||
@login_required
|
||||
def employee_detail_export_excel(request, emp_id):
|
||||
from openpyxl import Workbook
|
||||
from openpyxl.styles import Font, Alignment, PatternFill, Border, Side
|
||||
from django.http import HttpResponse
|
||||
from django.shortcuts import get_object_or_404
|
||||
import datetime
|
||||
|
||||
employee = get_object_or_404(Employee, id=emp_id)
|
||||
assignments = AssetAssignment.objects.filter(employee=employee, status='aktif').select_related('unit__asset')
|
||||
|
||||
wb = Workbook()
|
||||
ws = wb.active
|
||||
ws.title = "Aset Karyawan"
|
||||
|
||||
header_font = Font(bold=True, color="FFFFFF")
|
||||
header_fill = PatternFill(start_color="002060", end_color="002060", fill_type="solid")
|
||||
center_align = Alignment(horizontal="center", vertical="center")
|
||||
left_align = Alignment(horizontal="left", vertical="center")
|
||||
border = Border(left=Side(style='thin'), right=Side(style='thin'), top=Side(style='thin'), bottom=Side(style='thin'))
|
||||
|
||||
ws.merge_cells('A1:E1')
|
||||
ws['A1'] = "LAPORAN ASET KARYAWAN"
|
||||
ws['A1'].font = Font(bold=True, size=14)
|
||||
ws['A1'].alignment = center_align
|
||||
|
||||
ws.merge_cells('A2:E2')
|
||||
ws['A2'] = f"{employee.name} ({employee.nik})"
|
||||
ws['A2'].alignment = center_align
|
||||
|
||||
headers = ['No', 'Kode Unit', 'Nama Aset', 'Area', 'Tanggal Diberikan']
|
||||
for col_num, header_title in enumerate(headers, 1):
|
||||
cell = ws.cell(row=4, column=col_num, value=header_title)
|
||||
cell.font = header_font
|
||||
cell.fill = header_fill
|
||||
cell.alignment = center_align
|
||||
cell.border = border
|
||||
|
||||
for idx, a in enumerate(assignments, 1):
|
||||
row_num = idx + 4
|
||||
|
||||
data = [
|
||||
idx,
|
||||
a.unit.unit_code if a.unit else '-',
|
||||
a.unit.asset.name if a.unit and a.unit.asset else '-',
|
||||
a.unit.area if a.unit else '-',
|
||||
a.assigned_date.strftime('%d %b %Y') if a.assigned_date else '-'
|
||||
]
|
||||
|
||||
for col_num, cell_value in enumerate(data, 1):
|
||||
cell = ws.cell(row=row_num, column=col_num, value=cell_value)
|
||||
cell.border = border
|
||||
if col_num in [1, 2, 5]:
|
||||
cell.alignment = center_align
|
||||
else:
|
||||
cell.alignment = left_align
|
||||
|
||||
for col, width in zip(['A','B','C','D','E'], [5, 15, 30, 20, 15]):
|
||||
ws.column_dimensions[col].width = width
|
||||
|
||||
response = HttpResponse(content_type='application/vnd.openxmlformats-officedocument.spreadsheetml.sheet')
|
||||
now_str = datetime.datetime.now().strftime('%Y%m%d_%H%M')
|
||||
response['Content-Disposition'] = f'attachment; filename="Aset_{employee.name}_{now_str}.xlsx"'
|
||||
wb.save(response)
|
||||
return response
|
||||
|
||||
@login_required
|
||||
def unit_history_export_excel(request, unit_id):
|
||||
from openpyxl import Workbook
|
||||
from openpyxl.styles import Font, Alignment, PatternFill, Border, Side
|
||||
from django.http import HttpResponse
|
||||
from django.shortcuts import get_object_or_404
|
||||
import datetime
|
||||
|
||||
unit = get_object_or_404(AssetUnit, id=unit_id)
|
||||
logs_qs = unit.logs.all().select_related('employee')
|
||||
|
||||
wb = Workbook()
|
||||
ws = wb.active
|
||||
ws.title = "Riwayat Unit"
|
||||
|
||||
header_font = Font(bold=True, color="FFFFFF")
|
||||
header_fill = PatternFill(start_color="002060", end_color="002060", fill_type="solid")
|
||||
center_align = Alignment(horizontal="center", vertical="center")
|
||||
left_align = Alignment(horizontal="left", vertical="center")
|
||||
border = Border(left=Side(style='thin'), right=Side(style='thin'), top=Side(style='thin'), bottom=Side(style='thin'))
|
||||
|
||||
ws.merge_cells('A1:E1')
|
||||
ws['A1'] = "LAPORAN RIWAYAT UNIT ASET"
|
||||
ws['A1'].font = Font(bold=True, size=14)
|
||||
ws['A1'].alignment = center_align
|
||||
|
||||
ws.merge_cells('A2:E2')
|
||||
ws['A2'] = f"{unit.unit_code} - {unit.asset.name}"
|
||||
ws['A2'].alignment = center_align
|
||||
|
||||
headers = ['No', 'Tanggal', 'Aksi', 'Keterangan', 'Pihak Terkait']
|
||||
for col_num, header_title in enumerate(headers, 1):
|
||||
cell = ws.cell(row=4, column=col_num, value=header_title)
|
||||
cell.font = header_font
|
||||
cell.fill = header_fill
|
||||
cell.alignment = center_align
|
||||
cell.border = border
|
||||
|
||||
import re
|
||||
pattern = re.compile(r"^(.+?) \((.+?)\) - (.*)$")
|
||||
|
||||
for idx, log in enumerate(logs_qs, 1):
|
||||
row_num = idx + 4
|
||||
|
||||
pihak = log.employee.name if log.employee else "-"
|
||||
notes = log.notes or "-"
|
||||
|
||||
if not log.employee and log.notes:
|
||||
match = pattern.match(log.notes.strip())
|
||||
if match:
|
||||
name, nik, rest_of_notes = match.groups()
|
||||
pihak = name
|
||||
notes = rest_of_notes.strip()
|
||||
|
||||
data = [
|
||||
idx,
|
||||
log.timestamp.strftime('%d %b %Y %H:%M'),
|
||||
log.get_action_display(),
|
||||
notes,
|
||||
pihak
|
||||
]
|
||||
|
||||
for col_num, cell_value in enumerate(data, 1):
|
||||
cell = ws.cell(row=row_num, column=col_num, value=cell_value)
|
||||
cell.border = border
|
||||
if col_num in [1, 2, 3]:
|
||||
cell.alignment = center_align
|
||||
else:
|
||||
cell.alignment = left_align
|
||||
|
||||
for col, width in zip(['A','B','C','D','E'], [5, 20, 15, 40, 20]):
|
||||
ws.column_dimensions[col].width = width
|
||||
|
||||
response = HttpResponse(content_type='application/vnd.openxmlformats-officedocument.spreadsheetml.sheet')
|
||||
now_str = datetime.datetime.now().strftime('%Y%m%d_%H%M')
|
||||
response['Content-Disposition'] = f'attachment; filename="Riwayat_{unit.unit_code}_{now_str}.xlsx"'
|
||||
wb.save(response)
|
||||
return response
|
||||
|
||||
@login_required
|
||||
def asset_units_export_excel(request, asset_id):
|
||||
from openpyxl import Workbook
|
||||
from openpyxl.styles import Font, Alignment, PatternFill, Border, Side
|
||||
from django.http import HttpResponse
|
||||
from django.shortcuts import get_object_or_404
|
||||
import datetime
|
||||
|
||||
asset = get_object_or_404(Asset, id=asset_id)
|
||||
tab = request.GET.get('tab', 'semua')
|
||||
|
||||
units = asset.units.all()
|
||||
if tab == 'tersedia':
|
||||
units = units.filter(status='tersedia')
|
||||
elif tab == 'digunakan':
|
||||
units = units.filter(status='digunakan')
|
||||
elif tab == 'rusak':
|
||||
units = units.filter(status='rusak')
|
||||
|
||||
wb = Workbook()
|
||||
ws = wb.active
|
||||
ws.title = "Daftar Unit"
|
||||
|
||||
header_font = Font(bold=True, color="FFFFFF")
|
||||
header_fill = PatternFill(start_color="002060", end_color="002060", fill_type="solid")
|
||||
center_align = Alignment(horizontal="center", vertical="center")
|
||||
left_align = Alignment(horizontal="left", vertical="center")
|
||||
border = Border(left=Side(style='thin'), right=Side(style='thin'), top=Side(style='thin'), bottom=Side(style='thin'))
|
||||
|
||||
ws.merge_cells('A1:F1')
|
||||
ws['A1'] = "LAPORAN DAFTAR UNIT ASET"
|
||||
ws['A1'].font = Font(bold=True, size=14)
|
||||
ws['A1'].alignment = center_align
|
||||
|
||||
ws.merge_cells('A2:F2')
|
||||
ws['A2'] = f"{asset.name}"
|
||||
ws['A2'].alignment = center_align
|
||||
|
||||
headers = ['No', 'Kode Unit', 'Area', 'Status', 'Lokasi/Pengguna', '-']
|
||||
for col_num, header_title in enumerate(headers, 1):
|
||||
cell = ws.cell(row=4, column=col_num, value=header_title)
|
||||
cell.font = header_font
|
||||
cell.fill = header_fill
|
||||
cell.alignment = center_align
|
||||
cell.border = border
|
||||
|
||||
for idx, u in enumerate(units, 1):
|
||||
row_num = idx + 4
|
||||
|
||||
status_map = {'tersedia': 'Tersedia', 'digunakan': 'Digunakan', 'rusak': 'Maintenance'}
|
||||
lokasi = "-"
|
||||
|
||||
if u.status == 'digunakan':
|
||||
assignment = AssetAssignment.objects.filter(unit=u, status='aktif').first()
|
||||
if assignment and assignment.employee:
|
||||
lokasi = assignment.employee.name
|
||||
elif u.status == 'rusak' and u.location:
|
||||
lokasi = u.location
|
||||
|
||||
data = [
|
||||
idx,
|
||||
u.unit_code,
|
||||
u.area or '-',
|
||||
status_map.get(u.status, u.status),
|
||||
lokasi,
|
||||
u.location or '-'
|
||||
]
|
||||
|
||||
for col_num, cell_value in enumerate(data, 1):
|
||||
cell = ws.cell(row=row_num, column=col_num, value=cell_value)
|
||||
cell.border = border
|
||||
if col_num in [1, 2, 4]:
|
||||
cell.alignment = center_align
|
||||
else:
|
||||
cell.alignment = left_align
|
||||
|
||||
for col, width in zip(['A','B','C','D','E','F'], [5, 15, 20, 15, 30, 30]):
|
||||
ws.column_dimensions[col].width = width
|
||||
|
||||
response = HttpResponse(content_type='application/vnd.openxmlformats-officedocument.spreadsheetml.sheet')
|
||||
now_str = datetime.datetime.now().strftime('%Y%m%d_%H%M')
|
||||
response['Content-Disposition'] = f'attachment; filename="Unit_{asset.asset_code}_{now_str}.xlsx"'
|
||||
wb.save(response)
|
||||
return response
|
||||
|
||||
File diff suppressed because it is too large
Load Diff
@@ -0,0 +1,59 @@
|
||||
from django.shortcuts import render
|
||||
from django.contrib.auth.decorators import login_required
|
||||
from django.db.models import Q
|
||||
from django.core.paginator import Paginator
|
||||
from assets.models import AssetUnit
|
||||
|
||||
|
||||
@login_required
|
||||
def status_aset_list(request):
|
||||
"""Menampilkan pemantauan status seluruh unit fisik dengan paginasi dan filter kategori/status."""
|
||||
tab = request.GET.get('tab', 'tersedia')
|
||||
cat_filter = request.GET.get('cat', 'karyawan')
|
||||
search_query = request.GET.get('q', '').strip()
|
||||
|
||||
units_qs = AssetUnit.objects.select_related('asset', 'assigned_to', 'asset__category').order_by('-id')
|
||||
|
||||
if cat_filter == 'network':
|
||||
units_qs = units_qs.filter(asset__category__name__icontains='Network')
|
||||
else:
|
||||
units_qs = units_qs.filter(asset__category__name__icontains='Karyawan')
|
||||
|
||||
counts = {
|
||||
'tersedia': units_qs.filter(status='tersedia').count(),
|
||||
'digunakan': units_qs.filter(status='digunakan').count(),
|
||||
'rusak': units_qs.filter(status='rusak').count(),
|
||||
}
|
||||
|
||||
if tab == 'tersedia':
|
||||
units_qs = units_qs.filter(status='tersedia')
|
||||
elif tab == 'digunakan':
|
||||
units_qs = units_qs.filter(status='digunakan')
|
||||
elif tab == 'rusak':
|
||||
units_qs = units_qs.filter(status='rusak')
|
||||
else:
|
||||
units_qs = units_qs.filter(status='tersedia')
|
||||
|
||||
if search_query:
|
||||
units_qs = units_qs.filter(
|
||||
Q(unit_code__icontains=search_query) |
|
||||
Q(asset__name__icontains=search_query) |
|
||||
Q(assigned_to__name__icontains=search_query) |
|
||||
Q(assigned_to__nik__icontains=search_query) |
|
||||
Q(area__icontains=search_query) |
|
||||
Q(location__icontains=search_query)
|
||||
)
|
||||
|
||||
# Implementasi Pagination (25 unit per halaman)
|
||||
paginator = Paginator(units_qs, 25)
|
||||
page_number = request.GET.get('page')
|
||||
page_obj = paginator.get_page(page_number)
|
||||
|
||||
return render(request, 'status_aset_list.html', {
|
||||
'units': page_obj,
|
||||
'page_obj': page_obj,
|
||||
'tab': tab,
|
||||
'cat_filter': cat_filter,
|
||||
'search_query': search_query,
|
||||
'counts': counts,
|
||||
})
|
||||
Reference in New Issue
Block a user