Fakultas Ilmu Komputer UI

Verified Commit f20b3869 authored by Giovan Isa Musthofa's avatar Giovan Isa Musthofa
Browse files

[CHORES] Implement query and add more style to excel workbook

parent 9a56002a
Pipeline #48908 passed with stages
in 4 minutes and 41 seconds
......@@ -11,16 +11,51 @@ def download_jadwaldonor(modeladmin, request, queryset):
response = HttpResponse(content_type='application/vnd.openxmlformats-officedocument.spreadsheetml.sheet')
response['Content-Disposition'] = f'attachment; filename={modeladmin.model._meta}.xlsx'
df = read_frame(queryset)
df['time_start'] = df['time_start'].dt.tz_localize(None)
df['time_end'] = df['time_end'].dt.tz_localize(None)
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
workbook.close()
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
......
......@@ -45,10 +45,6 @@ class JadwalDonor(models.Model):
time_end = localtime(self.time_end)
return f"{self.location}, {time_start.date()} ({time_start.time()} - {time_end.time()})"
@classmethod
def download_query(cls, ids):
return DaftarDonor.objects.filter(jadwal_donor__id__in=ids, has_attended=True)
class Meta:
pass
......@@ -101,10 +97,14 @@ class DaftarDonor(models.Model):
seks_dengan_orang_afrika = models.BooleanField()
tinggal_di_afrika = models.BooleanField()
def __str__(self):
return str(self.user) + " - " + str(self.jadwal_donor)
@classmethod
def download_query(cls, jadwal_qs):
return cls.objects.filter(jadwal_donor__in=jadwal_qs, has_attended=True)
class Meta:
constraints = [
models.UniqueConstraint(fields=['user', 'jadwal_donor'], name='unique__user-jadwal_donor')
]
def __str__(self):
return str(self.user) + " - " + str(self.jadwal_donor)
......@@ -4,7 +4,7 @@ from django.utils import timezone
from django.core.exceptions import ValidationError
from main.factories import UserFactory
from donor.models import JadwalDonor
from donor.models import JadwalDonor, DaftarDonor
from donor.factories import JadwalDonorFactory, DaftarDonorFactory
......@@ -28,6 +28,16 @@ class JadwalDonorTest(TestCase):
time_end=datetime.fromisoformat(time_end), quota=150, category=JadwalDonor.Category.PRIVATE
)
class DaftarDonorTest(TestCase):
def test_str_daftar_donor(self):
user = UserFactory()
user.save()
jadwal_donor = JadwalDonorFactory()
daftar_donor = DaftarDonorFactory(user=user, jadwal_donor=jadwal_donor)
self.assertEqual(str(daftar_donor), str(user) + ' - ' + str(jadwal_donor))
def test_download_query(self):
user1 = UserFactory(email='donald@duckduckgo.org')
user1.save()
......@@ -38,15 +48,6 @@ class JadwalDonorTest(TestCase):
DaftarDonorFactory(user=user1, jadwal_donor=jadwal_donor, has_attended=True)
DaftarDonorFactory(user=user2, jadwal_donor=jadwal_donor, has_attended=True)
qs = JadwalDonor.download_query([jadwal_donor.id])
qs = DaftarDonor.download_query(JadwalDonor.objects.filter(id=jadwal_donor.id))
self.assertEqual(len(qs), 2)
class DaftarDonorTest(TestCase):
def test_str_daftar_donor(self):
user = UserFactory()
user.save()
jadwal_donor = JadwalDonorFactory()
daftar_donor = DaftarDonorFactory(user=user, jadwal_donor=jadwal_donor)
self.assertEqual(str(daftar_donor), str(user) + ' - ' + str(jadwal_donor))
......@@ -289,9 +289,7 @@ class JadwalDonorAdminTest(TestCase):
user.save()
jadwal_donor = JadwalDonorFactory(time_start=timezone.localtime() - timedelta(hours=24),
time_end=timezone.localtime() - timedelta(hours=23))
daftar_donor = DaftarDonorFactory(user=user,
jadwal_donor=jadwal_donor,
has_attended=True)
DaftarDonorFactory(user=user, jadwal_donor=jadwal_donor, has_attended=True)
endpoint = reverse('admin:donor_jadwaldonor_changelist')
data = {'action': 'download_jadwaldonor', '_selected_action': [jadwal_donor.id]}
......
from datetime import date
from django.conf import settings
from django.contrib.auth.models import AbstractUser, BaseUserManager
from django.db import models
......@@ -90,6 +91,12 @@ class Profile(models.Model):
work_email = models.EmailField(blank=True)
work_phone_no = models.CharField(max_length=20, blank=True)
@property
def age(self):
born = self.birthdate
today = date.today()
return today.year - born.year - ((today.month, today.day) < (born.month, born.day))
def __str__(self):
return f'({self.sex}, {self.blood_type})'
......
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