first upload to git

parents
Pipeline #1247 failed with stages
from django.contrib import admin
# Register your models here.
from django.apps import AppConfig
class DashboardConfig(AppConfig):
name = 'dashboard'
from django.db import models
# Create your models here.
This diff is collapsed.
from django.test import TestCase
# Create your tests here.
from re import X
from xlsxwriter import workbook
import management
from time import sleep
from django.shortcuts import redirect, render
from datetime import date, datetime, timedelta
from pos.models import *
from management.models import Product
from django.contrib.auth.decorators import login_required
from management.permission_page import pos_manager_only
import xlsxwriter
import glob
from icecream import ic
# Create your views here.
# https://linuxhint.com/download-the-file-in-django/
import mimetypes
# import os module
import os
# Import HttpResponse module
from django.http.response import HttpResponse
def download_file(request, filename=''):
if filename == '':
filename = 'constFile/example_for_add_product.xlsx'
path = open(filename, 'rb')
# Set the mime type
mime_type, _ = mimetypes.guess_type(filename)
# Set the return value of the HttpResponse
response = HttpResponse(path, content_type=mime_type)
# Set the HTTP header for sending to browser
response['Content-Disposition'] = "attachment; filename=%s" % filename
# Return the response value
return response
@login_required
@pos_manager_only
def dashborad(req):
context=dict()
userlabel = str(req.user.id)+'_'+str(req.user)
print('------------------------------------xlsx file --------------------------------------------------')
for name in glob.glob('*.xlsx'):
print(name)
try:
if userlabel in name:
os.remove(name)
except:
print("can't delete filename:",name)
if req.method == 'POST':
#pick time range
print(req.POST)
context['mode'] = 'post'
else :
strnowtime = datetime.now().strftime("%Y%m%d%H%M%S")
labelfilexlsx = userlabel+'_'+strnowtime
today_filename = 'today_of_'+labelfilexlsx+'.xlsx'
last_week_filename = 'last_week_of_'+labelfilexlsx+'.xlsx'
last_month_filename = 'last_month_of_'+labelfilexlsx+'.xlsx'
context['today_filename'] = today_filename
context['last_week_filename'] = last_week_filename
context['last_month_filename'] = last_month_filename
context['today'] = billlistsNdays(filename=today_filename)
context['week'] = billlistinrange(date.today() - timedelta(days=7),date.today(),last_week_filename)
context['month'] = billlistinrange(date.today() - timedelta(days=30),date.today(),last_month_filename)
return render(req,'dashboard.html',context)
def billlistinrange(start,end,filename=''):
bills = Bill.objects.filter(created__gte=start).filter(created__lt=end)
data = dict()
soldValueInDay = dict()
dataset = dict()
nday = (end-start).days
sumSoldValue = 0
for i in bills:
listsInBill = BillList.objects.filter(bill=i)
datekey = i.created.strftime('%d/%m/%Y')
if soldValueInDay.get(datekey) == None : soldValueInDay[datekey] = 0
for j in listsInBill:
v = j.product.price * j.quantity
soldValueInDay[datekey] += v
sumSoldValue += v
if dataset.get(j.product.id) != None:
# print(dataset.get(j.product.id))
dataset[j.product.id]['sold']+=int(j.quantity)
else :
# id : autoincrement field in db
dataset[j.product.id] = {
'id':j.product.product_id,
'name':j.product.name,
'price':j.product.price,
'sold':j.quantity
}
if filename!='':
workbook = xlsxwriter.Workbook(filename)
sheet_by_day = workbook.add_worksheet('days')
sheet_by_product = workbook.add_worksheet('products')
columns_by_p = [
{'header':'id'},
{'header':'name'},
{'header':'price'},
{'header':'sold'},
{'header':'value'},
{'header':'sold/day'},
{'header':'value/day'},
]
columns_by_d = [
{'header':'day'},
{'header':'value'},
]
product_tableArea = 'A1:G'+str(len(dataset.keys())+1)
sheet_by_product.add_table(product_tableArea,{'columns':columns_by_p,'style':None})
row_counter = 2
for key in dataset.keys():
tmp = dataset[key]
val = tmp['price'] * tmp['sold']
tmp['value'] = val
tmp['soldperday'] = round(tmp['sold']/nday,2)
tmp['valueperday'] = round(val/nday,2)
dataset[key] = tmp
if filename!='':
cellstr = 'A'+str(row_counter)
sheet_by_product.write_row(cellstr,list(tmp.values()))
row_counter+=1
if filename!='':
keysol = list(soldValueInDay.keys())
day_tableArea = 'A1:B'+str(len(keysol)+1)
sheet_by_day.add_table(day_tableArea,{'columns':columns_by_d, 'style':None})
for i in range(len(keysol)) :
cellstr = 'A'+str(i+2)
sheet_by_day.write_row(cellstr,[keysol[i],soldValueInDay.get(keysol[i])])
workbook.close()
data['dataProduct'] = dataset
data['soldValueInDay'] = soldValueInDay
x_axis = []
y_axis = []
for i in range(nday):
k = (start+timedelta(days=i)).strftime('%d/%m/%Y')
x_axis.append(k)
y_axis.append(0) if soldValueInDay.get(k) == None else y_axis.append(float(soldValueInDay.get(k)))
data['avgSoldValue'] = [round(float(sumSoldValue)/nday,2)]*nday
data['labels'] = x_axis
data['data'] = y_axis
return data
def billlistsNdays(n=0,filename=''):
start_date = date.today() - timedelta(days=n)
bills = Bill.objects.filter(created__gte=start_date)
dataset = {}
for i in bills:
listsInBill = BillList.objects.filter(bill=i)
for j in listsInBill:
if dataset.get(j.product.id) != None:
# print(dataset.get(j.product.id))
dataset[j.product.id]['sold']+=int(j.quantity)
else :
# id : autoincrement field in db
dataset[j.product.id] = {
'id':j.product.product_id,
'name':j.product.name,
'price':j.product.price,
'sold':j.quantity
}
if filename!='':
workbook = xlsxwriter.Workbook(filename)
sheet = workbook.add_worksheet('products')
columns_table = [
{'header':'id'},
{'header':'name'},
{'header':'price'},
{'header':'sold'},
{'header':'value'}
]
tableArea = 'A1:E'+str(len(dataset.keys())+1)
sheet.add_table(tableArea,{'style':None,'columns':columns_table})
row_counter=2
for key in dataset.keys():
dataset[key]['value'] = dataset[key]['price'] * dataset[key]['sold']
if filename != '' :
cellstr = 'A'+str(row_counter)
sheet.write_row(cellstr,dataset[key].values())
if filename!='':
workbook.close()
return dataset
\ No newline at end of file
#!/usr/bin/env python
"""Django's command-line utility for administrative tasks."""
import os
import sys
def main():
"""Run administrative tasks."""
os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'webproject.settings')
try:
from django.core.management import execute_from_command_line
except ImportError as exc:
raise ImportError(
"Couldn't import Django. Are you sure it's installed and "
"available on your PYTHONPATH environment variable? Did you "
"forget to activate a virtual environment?"
) from exc
execute_from_command_line(sys.argv)
if __name__ == '__main__':
main()
from django.contrib import admin
from .models import *
# Register your models here.
admin.site.register(Product)
admin.site.register(EmployeeUser)
admin.site.register(FileForSave)
admin.site.register(POSManager)
from django.apps import AppConfig
class ManagementConfig(AppConfig):
name = 'management'
from django import forms
from django.db.models import fields
from .models import Product #,EmployeeUser
from django.utils.translation import ugettext, ugettext_lazy as _
from pos.models import Bill
class FileForm(forms.Form):
docfile = forms.FileField(label='Select a file')
class ProductForm(forms.ModelForm):
class Meta:
model = Product
exclude = ['manager']
class BillForm(forms.ModelForm):
class Meta:
model = Bill
exclude = ['manager']
class EmployeeForm(forms.Form):
username = forms.CharField(label=_('username '), required=True)
password = forms.CharField(label=_('password '), required=True)
note = forms.CharField(label=_('note '), required=False)
class SendProductID(forms.Form):
pid = forms.CharField(required=False)
# Generated by Django 3.1.4 on 2021-04-16 01:10
from django.db import migrations, models
class Migration(migrations.Migration):
initial = True
dependencies = [
]
operations = [
migrations.CreateModel(
name='FileForSave',
fields=[
('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')),
('docfile', models.FileField(upload_to='')),
],
),
migrations.CreateModel(
name='Manager',
fields=[
('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')),
('test', models.CharField(max_length=50)),
],
),
migrations.CreateModel(
name='Product',
fields=[
('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')),
('product_id', models.CharField(max_length=50)),
('name', models.CharField(max_length=50)),
('description', models.CharField(max_length=50)),
('price', models.DecimalField(decimal_places=2, max_digits=7)),
('quantity', models.IntegerField()),
('category', models.CharField(max_length=50)),
],
),
migrations.CreateModel(
name='SubUser',
fields=[
('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')),
('test', models.CharField(max_length=50)),
],
),
]
# Generated by Django 3.2 on 2021-04-16 07:14
from django.db import migrations
class Migration(migrations.Migration):
dependencies = [
('management', '0001_initial'),
]
operations = [
migrations.DeleteModel(
name='Manager',
),
migrations.DeleteModel(
name='SubUser',
),
]
# Generated by Django 3.2 on 2021-04-17 07:59
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('management', '0002_auto_20210416_1414'),
]
operations = [
migrations.AddField(
model_name='product',
name='manager_username',
field=models.CharField(default=2, max_length=50),
preserve_default=False,
),
]
# Generated by Django 3.2 on 2021-04-21 13:33
import django.contrib.auth.models
import django.contrib.auth.validators
from django.db import migrations, models
import django.utils.timezone
class Migration(migrations.Migration):
dependencies = [
('auth', '0012_alter_user_first_name_max_length'),
('management', '0003_product_manager_username'),
]
operations = [
migrations.CreateModel(
name='EmployeeUser',
fields=[
('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')),
('username', models.CharField(max_length=50)),
('password', models.CharField(max_length=15)),
('manager_username', models.CharField(max_length=50)),
],
),
migrations.CreateModel(
name='Manager',
fields=[
('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')),
('password', models.CharField(max_length=128, verbose_name='password')),
('last_login', models.DateTimeField(blank=True, null=True, verbose_name='last login')),
('is_superuser', models.BooleanField(default=False, help_text='Designates that this user has all permissions without explicitly assigning them.', verbose_name='superuser status')),
('username', models.CharField(error_messages={'unique': 'A user with that username already exists.'}, help_text='Required. 150 characters or fewer. Letters, digits and @/./+/-/_ only.', max_length=150, unique=True, validators=[django.contrib.auth.validators.UnicodeUsernameValidator()], verbose_name='username')),
('first_name', models.CharField(blank=True, max_length=150, verbose_name='first name')),
('last_name', models.CharField(blank=True, max_length=150, verbose_name='last name')),
('is_staff', models.BooleanField(default=False, help_text='Designates whether the user can log into this admin site.', verbose_name='staff status')),
('is_active', models.BooleanField(default=True, help_text='Designates whether this user should be treated as active. Unselect this instead of deleting accounts.', verbose_name='active')),
('date_joined', models.DateTimeField(default=django.utils.timezone.now, verbose_name='date joined')),
('email', models.EmailField(max_length=254, unique=True, verbose_name='email address')),
('groups', models.ManyToManyField(blank=True, help_text='The groups this user belongs to. A user will get all permissions granted to each of their groups.', related_name='user_set', related_query_name='user', to='auth.Group', verbose_name='groups')),
('user_permissions', models.ManyToManyField(blank=True, help_text='Specific permissions for this user.', related_name='user_set', related_query_name='user', to='auth.Permission', verbose_name='user permissions')),
],
options={
'verbose_name': 'user',
'verbose_name_plural': 'users',
'abstract': False,
},
managers=[
('objects', django.contrib.auth.models.UserManager()),
],
),
]
# Generated by Django 3.2 on 2021-04-21 13:51
from django.db import migrations
class Migration(migrations.Migration):
dependencies = [
('management', '0004_employeeuser_manager'),
]
operations = [
migrations.DeleteModel(
name='Manager',
),
]
# Generated by Django 3.2 on 2021-04-24 04:49
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('management', '0005_delete_manager'),
]
operations = [
migrations.DeleteModel(
name='EmployeeUser',
),
migrations.AlterField(
model_name='product',
name='product_id',
field=models.CharField(max_length=50, unique=True),
),
]
# Generated by Django 3.2 on 2021-04-24 06:42
from django.conf import settings
from django.db import migrations, models
import django.db.models.deletion
class Migration(migrations.Migration):
dependencies = [
migrations.swappable_dependency(settings.AUTH_USER_MODEL),
('management', '0006_auto_20210424_1149'),
]
operations = [
migrations.CreateModel(
name='EmployeeUser',
fields=[
('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')),
('note', models.CharField(max_length=15)),
('manager_username', models.CharField(max_length=150)),
('user', models.OneToOneField(on_delete=django.db.models.deletion.CASCADE, to=settings.AUTH_USER_MODEL)),
],
),
]
# Generated by Django 3.2 on 2021-04-24 07:36
from django.db import migrations
class Migration(migrations.Migration):
dependencies = [
('management', '0007_employeeuser'),
]
operations = [
migrations.RenameField(
model_name='employeeuser',
old_name='manager_username',
new_name='create_by',
),
]
# Generated by Django 3.2 on 2021-04-24 07:39
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('management', '0008_rename_manager_username_employeeuser_create_by'),
]
operations = [
migrations.AlterField(
model_name='employeeuser',
name='id',
field=models.AutoField(primary_key=True, serialize=False),
),
]
# Generated by Django 3.2 on 2021-04-24 07:42
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('management', '0009_alter_employeeuser_id'),
]
operations = [
migrations.AlterField(
model_name='employeeuser',
name='id',
field=models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID'),
),
]
# Generated by Django 3.2 on 2021-04-25 03:51
from django.conf import settings
from django.db import migrations, models
import django.db.models.deletion
class Migration(migrations.Migration):
dependencies = [
migrations.swappable_dependency(settings.AUTH_USER_MODEL),
('management', '0010_alter_employeeuser_id'),
]
operations = [
migrations.AlterField(
model_name='employeeuser',
name='create_by',
field=models.ForeignKey(on_delete=django.db.models.deletion.CASCADE, related_name='Manager', to=settings.AUTH_USER_MODEL),
),
]
# Generated by Django 3.2 on 2021-04-25 03:54
from django.conf import settings
from django.db import migrations, models
import django.db.models.deletion
class Migration(migrations.Migration):
dependencies = [
migrations.swappable_dependency(settings.AUTH_USER_MODEL),
('management', '0011_alter_employeeuser_create_by'),