Fakultas Ilmu Komputer UI

Commit 85154f3a authored by Giovan Isa Musthofa's avatar Giovan Isa Musthofa
Browse files

Merge branch 'warmfix-excel' into 'staging'

Warmfix excel

See merge request !123
parents b2f07c00 70b94fc6
Pipeline #50035 passed with stages
in 5 minutes and 50 seconds
from main.admin import InputFilter
from donor.models import DaftarDonor, JadwalDonor
from django.utils.translation import gettext_lazy as _
from django.http import HttpResponse
from django.conf import settings
from django.db.models import Q
from django.contrib import admin
from django.db.models import Q
from django.utils.translation import gettext_lazy as _
from .models import JadwalDonor, DaftarDonor
from .services import jadwal_donor_spreadsheet_service
from main.admin import InputFilter
def download_jadwaldonor(modeladmin, request, queryset):
import pandas as pd
from django_pandas.io import read_frame
response = HttpResponse(content_type='application/vnd.openxmlformats-officedocument.spreadsheetml.sheet')
response['Content-Disposition'] = f'attachment; filename={modeladmin.model._meta}.xlsx'
daftar_donor = DaftarDonor.download_query(queryset)
fieldnames = [
'id',
'jadwal_donor__time_start',
'user__profile__id_card_no',
'user__first_name',
'user__profile__address',
'user__profile__phone_no',
'user__profile__blood_type',
'user__profile__sex',
]
df = read_frame(daftar_donor, fieldnames=fieldnames)
df = df.rename(columns={
fieldnames[0]: "NoTrans",
fieldnames[1]: "Tanggal",
fieldnames[2]: "ID",
fieldnames[3]: "Nama Lengkap",
fieldnames[4]: "Alamat",
fieldnames[5]: "HP",
fieldnames[6]: "Gol (RH)",
fieldnames[7]: "JK",
})
if len(df):
df['Tanggal'] = df['Tanggal'].dt.tz_localize(None)
writer = pd.ExcelWriter(response, engine='xlsxwriter')
df.to_excel(writer, sheet_name='Sheet1')
workbook = writer.book
worksheet = writer.sheets['Sheet1']
def get_col_widths(dataframe):
# First we find the maximum length of the index column
idx_max = max([len(str(s)) for s in dataframe.index.values] + [len(str(dataframe.index.name))])
# Then, we concatenate this to the max of the lengths of column name
# and its values for each column, left to right
return [idx_max] + [max([len(str(s)) for s in dataframe[col].values] + [len(col)]) for col in dataframe.columns]
text_format = workbook.add_format({'text_wrap': True})
for i, width in enumerate(get_col_widths(df)):
worksheet.set_column(i, i, width, text_format)
workbook.close()
return response
return jadwal_donor_spreadsheet_service.download_jadwaldonor(modeladmin, queryset)
download_jadwaldonor.short_description = 'Download Jadwal Donor as Excel Workbook'
......
......@@ -27,15 +27,14 @@ class Command(BaseCommand):
) if options['users_email'] else list(User.objects.all())
list_daftar_donor = []
ada = {}
for jadwal_donor in list_jadwal_donor:
random.shuffle(list_user)
for i in range(rand_int(0, min(5, len(list_user)))):
jumlah_pendaftar = rand_int(0, len(list_user))
for i in range(jumlah_pendaftar):
user = list_user[i]
if DaftarDonor.objects.filter(user=user, jadwal_donor=jadwal_donor).count() > 0:
continue
sedang_hamil = rand_bool()
ada[(user.id, jadwal_donor.id)] = True
list_daftar_donor.append(
DaftarDonor(
user=user,
......
from datetime import datetime
import os
from dateutil.relativedelta import relativedelta
from django.conf import settings
from django.http import HttpResponse
from django_pandas.io import read_frame
import pandas as pd
from PIL import Image, ImageDraw, ImageFont
from main.utils.numbers import last_digit, second_last_digit
from main.utils.python import default_kwargs_with_override
from .models import DaftarDonor
resource_path = os.path.join(settings.BASE_DIR, "donor", "resources")
......@@ -228,3 +235,129 @@ class FormulirDaftarDonorService:
formulir_daftar_donor_service = FormulirDaftarDonorService()
class JadwalDonorSpreadsheetService:
@classmethod
def _birthdates_to_age(cls, birthdates):
today = datetime.today()
return [relativedelta(today, birthdate).years for birthdate in birthdates]
@classmethod
def _get_daftar_donor_ulang_list(cls, daftar_donor_qs):
daftar_donor_ulang_list = []
for daftar_donor in daftar_donor_qs:
daftar_donor_ulang = DaftarDonor.objects.filter(
user=daftar_donor.user,
has_attended=True,
jadwal_donor__time_end__lt=daftar_donor.jadwal_donor.time_start)
daftar_donor_ulang_list.append(daftar_donor_ulang)
return daftar_donor_ulang_list
@classmethod
def _get_baru_ulang(cls, daftar_donor_qs):
baru_ulang_list = []
for daftar_donor in daftar_donor_qs:
daftar_donor_ulang = DaftarDonor.objects.filter(
user=daftar_donor.user,
has_attended=True,
jadwal_donor__time_end__lt=daftar_donor.jadwal_donor.time_start)
baru_ulang_list.append('Ulang' if daftar_donor_ulang.exists() else 'Baru')
return baru_ulang_list
@classmethod
def _write_header(cls, writer):
workbook = writer.book
merge_format = workbook.add_format({
'align': 'center',
'valign': 'vcenter',
'bold': True,
})
merge_format.set_border(1)
worksheet = writer.sheets['Sheet1']
worksheet.merge_range('A1:A3', 'No', merge_format)
worksheet.merge_range('B1:B3', 'NoTrans', merge_format)
worksheet.merge_range('C1:C3', 'Lokasi', merge_format)
worksheet.merge_range('D1:D3', 'Tanggal', merge_format)
worksheet.merge_range('E1:M1', 'Pendonor', merge_format)
headers = 'ID', 'Nama Lengkap', 'Alamat', 'HP', 'Umur', 'Gol (RH)', 'JK', 'Baru Ulang', 'Donor Ke-'
for i, header in enumerate(headers):
col = 4 + i
worksheet.merge_range(1, col, 2, col, header, merge_format)
@classmethod
def _get_col_widths(cls, df):
# First we find the maximum length of the index column
idx_max = max([len(str(s)) for s in df.index.values] + [len(str(df.index.name))])
# Then, we concatenate this to the max of the lengths of column name
# and its values for each column, left to right
return [idx_max] + [max([len(str(s)) for s in df[col].values] + [len(col)]) for col in df.columns]
def download_jadwaldonor(self, modeladmin, queryset):
response = HttpResponse(content_type='application/vnd.openxmlformats-officedocument.spreadsheetml.sheet')
response['Content-Disposition'] = f'attachment; filename={modeladmin.model._meta}.xlsx'
daftar_donor = DaftarDonor.download_query(queryset)
fieldnames = [
'id',
'jadwal_donor__location',
'jadwal_donor__time_start',
'user__profile__id_card_no',
'user__first_name',
'user__profile__address',
'user__profile__phone_no',
'user__profile__birthdate',
'user__profile__blood_type',
'user__profile__sex',
]
df = read_frame(daftar_donor, fieldnames=fieldnames)
df[fieldnames[7]] = self._birthdates_to_age(df[fieldnames[7]])
daftar_donor_ulang_list = self._get_daftar_donor_ulang_list(daftar_donor)
df['Baru/Ulang'] = [
'Ulang' if daftar_donor_ulang.exists() else 'Belum'
for daftar_donor_ulang in daftar_donor_ulang_list
]
df['Daftar Ke-'] = [
len(daftar_donor_ulang) + 1
for daftar_donor_ulang in daftar_donor_ulang_list
]
if len(df):
df[fieldnames[2]] = df[fieldnames[2]].dt.tz_localize(None)
# Not actually used to write headers but still usefull to adjust column widths
df = df.rename(columns={
fieldnames[0]: 'NoTrans',
fieldnames[1]: 'Lokasi',
fieldnames[2]: 'Tanggal',
fieldnames[3]: 'ID',
fieldnames[4]: 'Nama Lengkap',
fieldnames[5]: 'Alamat',
fieldnames[6]: 'HP',
fieldnames[7]: 'Umur',
fieldnames[8]: 'Gol (RH)',
fieldnames[9]: 'JK',
})
writer = pd.ExcelWriter(response, engine='xlsxwriter')
df.to_excel(writer, sheet_name='Sheet1', startrow=3, header=False)
self._write_header(writer)
workbook = writer.book
worksheet = writer.sheets['Sheet1']
text_format = workbook.add_format({'text_wrap': True})
for i, width in enumerate(self._get_col_widths(df)):
worksheet.set_column(i, i, width, text_format)
workbook.close()
return response
jadwal_donor_spreadsheet_service = JadwalDonorSpreadsheetService()
from django.core.management.base import BaseCommand
from ...factories import UserFactory
class Command(BaseCommand):
help = 'Seeds 100 users.'
def add_arguments(self, parser):
parser.add_argument('--size', default=100, type=int)
def handle(self, *args, **options):
size = abs(options['size'])
for _ in range(size):
u = UserFactory()
u.save()
self.stdout.write(self.style.SUCCESS(f'Successfully seeds {size} users.'))
from io import StringIO
from django.core.management import call_command
from django.test import TestCase
from .models import User
class SeedUserTest(TestCase):
def test_command_success(self):
out = StringIO()
users_amount = len(User.objects.filter())
call_command('seed_users', stdout=out)
self.assertIn('Successfully seeds 100 users.', out.getvalue())
self.assertEqual(users_amount + 100, len(User.objects.filter()))
.vscode/
# Logs
logs
*.log
......
Supports Markdown
0% or .
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment