import json
import time
import datetime as dtLib
import pandas as pd
import numpy as np
from decimal import Decimal, getcontext
getcontext().prec = 1
# from django.conf import settings
# from django.contrib.auth.decorators import permission_required
from django.contrib.auth.decorators import user_passes_test
# from django.contrib.auth.models import User # FIXME USE User from User = get_user_model()
from django.contrib.auth import get_user_model
from django.contrib.postgres.aggregates import ArrayAgg
from django.shortcuts import render
from django.views.decorators.http import require_http_methods
from django.http import JsonResponse, HttpResponse# ,HttpResponseRedirect
from django.db.models import Q, F, Func, Sum, DecimalField, Exists, OuterRef, Case, Value, When, BooleanField, CharField
from django.db.models.functions import Concat
from .models import Grades, ExtendAccount, Locations
from .helpers import getWorkingHours, getSheetByGroup, has_any_permissions, originalizeField, userizeField, userizeDictKeys
from .helpers import VIEW_PERMISSIONS, CHANGE_PERMISSIONS, DELETE_PERMISSIONS
from .FF_LUVR_filter import deserializeSortAndFilter, getSortAndFilter
from myconfig.config import PERIOD_RECONCILIATION_OF_RESULTS
ORIGINAL_WORKSHEET_LIST_FIELDS = ['id', 'created', 'date_for_work', 'shop_code__shop_code', 'shop_code__shop_type', 'shop_code__workplace_address', 'work_type__type_of_work', 'workplace_app_note', 'start_work', 'end_work', 'lying_worker_id', 'timesheets__worker_id__worker_id', 'timesheets__start_work', 'timesheets__end_work', 'timesheets__amount_of_work_time', 'timesheets__worker_id__worker_full_name', 'timesheets__grade__grade_num', 'timesheets__is_worker_skip_work', 'workplace_note', 'note_from_SR', 'confirmation_app', 'is_cancel', 'timesheets__export4payment__is_exported', 'timesheets__worker_id__payment_type__payment_type', 'shop_code__shop_region__id', 'timesheets__worker_id__payment_type__id']
# HEAD_WORKSHEET_LIST_FIELDS = ['id', 'created', 'date_for_work', 'shop_code', 'workplace_app_note', 'start_work', 'end_work', 'lying_worker_id', 'timesheets__worker_id__worker_id', 'timesheets__start_work', 'timesheets__end_work', 'timesheets__amount_of_work_time', 'timesheets__worker_id__worker_full_name', 'timesheets__grade__grade_num', 'timesheets__is_worker_skip_work', 'workplace_note', 'note_from_SR', 'confirmation_app', 'is_cancel', 'timesheets__export4payment__is_exported', 'timesheets__worker_id__payment_type__payment_type', 'shop_code__shop_region__id', 'timesheets__worker_id__payment_type__id']
# SHOPS_FIELDS = ['id', 'shop_code__shop_code', 'shop_code__shop_type', 'shop_code__workplace_address', 'work_type__type_of_work',]
DEBUG_THIS_FUNC = False
# USER = settings.AUTH_USER_MODEL
User = get_user_model()
class UnixTimestamp(Func):
# Функция для преобразования datetime в unixtime
function = 'EXTRACT'
template = "%(function)s('epoch' FROM %(expressions)s)"
@require_http_methods("GET")
@user_passes_test(lambda user: has_any_permissions(user, VIEW_PERMISSIONS)) # FIXME
def FF_LUVR_View(request):
'''JUST GET MAIN PAGE'''
response = render(request, 'KRSK_WorkSheets/FF_LUVR.html', context={'title':'ЛУВРЫ'})
return response
@require_http_methods("GET")
@user_passes_test(lambda user: has_any_permissions(user, CHANGE_PERMISSIONS)) # FIXME
def FF_Exporting_page_View(request):
'''JUST GET MAIN PAGE'''
response = render(request, 'KRSK_WorkSheets/FF_Exporting_page.html', context={'title':'ЛУВРЫ'})
return response
@require_http_methods("POST")
@user_passes_test(lambda user: has_any_permissions(user, VIEW_PERMISSIONS)) # FIXME
def FF_LUVR_getHead(request):
'''DATA FOR FILTERS:
input: #FIXME DOC
output: #FIXME DOC'''
# perf = time.perf_counter_ns()
json_reqest = json.loads(request.body)
location = json_reqest.get('shop_code__shop_region__id', [])
location_filter_data = { 'shop_code__shop_region__id': location }
if isinstance(WorkSheets := getSheetByGroup(request.user, 'WorkSheets'), JsonResponse):
return WorkSheets
USER_WORKSHEET_LIST_FIELDS = [userizeField(request.user, field) for field in ORIGINAL_WORKSHEET_LIST_FIELDS]
data_for_extended_account = {'last_filter_data': {**location_filter_data}, 'last_sort_data': []}
ea, is_ea_created = ExtendAccount.objects.get_or_create( user=request.user,
defaults=data_for_extended_account)
if ea.last_filter_data.get('shop_code__shop_region__id') != location and json_reqest.get("status") != 'START':
ea.last_filter_data = location_filter_data
ea.save()
result_data_for_filter = ea.last_filter_data if not is_ea_created else {}
result_sort_data = ea.last_sort_data if not is_ea_created else []
sort_list, filter_kwargs, q_objects, list_fields = deserializeSortAndFilter(
raw_sort = None,
raw_filter = location_filter_data, # ea.last_filter_data, # json_reqest.get('FILTER_DATA'),
user = request.user,
list_fields = ORIGINAL_WORKSHEET_LIST_FIELDS[:],)
filter_kwargs, list_fields = userizeDictKeys(request.user, filter_kwargs), [userizeField(request.user, field) for field in list_fields]
# print(f"FILTER = {filter_kwargs}\nFilter = {BASE_WORKSHEET_LIST_FIELDS[:]}")
qs = WorkSheets.objects.all()
qs = qs.filter(*q_objects, **filter_kwargs)
# print(f"list_fields = {list_fields}")
qs = qs.aggregate(**{f'values_{ff}': ArrayAgg(ff, distinct=True) for ff in list_fields})
qs2 = [qs[f'values_{ff}'] for ff in list_fields] # не помню, почему не могу values_list здесь....
payload = { 'ROLE' : list(request.user.groups.values_list('name')), # FIXME bad data
'FILTER_DATA' : list(qs2),
'OLD_SORT_AND_FILTER_DATA': {'sort': result_sort_data, 'filter': result_data_for_filter},
'LOCATIONS' : list(Locations.objects.all().values_list('id', 'location')),
'OLD_LOCATIONS' : ea.last_filter_data.get('shop_code__shop_region__id', []),
'FIELDS': [originalizeField(field) for field in list_fields], }
response = JsonResponse(payload, safe=False)
Это часть моего проекта на Django.
У меня есть несколько таблиц с Workers, Worksheets, Timesheets.
В файле helpers.py есть переключение таблиц в зависимости от пользователя.
Предложи как можно изменить архитектуру проекта, чтоб при добавлении новых контрагентов было проще
Based on your description and code, it seems that the current architecture involves having separate models for each contractor (e.g., KWorkers, SSWorkers, RazgulayWorkers, etc.), and you switch between them using helper functions based on the user's group. This setup leads to code duplication and makes adding new contractors cumbersome, as you have to create new models and adjust various parts of the codebase.
To simplify the architecture and make it easier to add new contractors, I suggest the following approach:
Refactor Models to Use a Contractor (or Company) Foreign Key
Instead of creating separate models for each contractor, you can have a single set of models (e.g., Worker, Worksheet, Timesheet, etc.) that include a foreign key to a Contractor model. This way, you can differentiate data belonging to different contractors without duplicating code or models.
Here's how you can implement this:
1. Create a Contractor Model
python
# models.py
class Contractor(models.Model):
name = models.CharField(max_length=255, unique=True)
# Add any other relevant fields
def __str__(self):
return self.name
2. Update Your Models to Include a ForeignKey to Contractor
Modify your existing base models to include a contractor field. For example:
python
# models.py
class Worker(models.Model):
contractor = models.ForeignKey(Contractor, on_delete=models.CASCADE, related_name='workers')
# Include all the common fields for workers here
def __str__(self):
return f"{self.contractor.name} - {self.worker_id}: {self.worker_full_name}"
class Worksheet(models.Model):
contractor = models.ForeignKey(Contractor, on_delete=models.CASCADE, related_name='worksheets')
# Include all the common fields for worksheets here
def __str__(self):
return f"{self.contractor.name} - Worksheet {self.id}"
class Timesheet(models.Model):
contractor = models.ForeignKey(Contractor, on_delete=models.CASCADE, related_name='timesheets')
# Include all the common fields for timesheets here
def __str__(self):
return f"{self.contractor.name} - Timesheet {self.id}"
# Similarly for other models
3. Update User Profiles to Associate Users with Contractors
Create an extended user profile model (if not already existing) to associate users with contractors. For example:
python
# models.py
from django.contrib.auth.models import User
class UserProfile(models.Model):
user = models.OneToOneField(User, on_delete=models.CASCADE)
contractor = models.ForeignKey(Contractor, on_delete=models.CASCADE, null=True, blank=True)
# Add any other fields you need
def __str__(self):
return f"{self.user.username} - {self.contractor.name}"
Don't forget to create or update signals to automatically create UserProfile instances when new users are created.
4. Adjust Views to Filter Data Based on the Contractor
In your views, filter the data based on the contractor associated with the logged-in user. For example:
python
# views.py
from django.shortcuts import render, get_object_or_404
from .models import Worker, Worksheet, Timesheet, UserProfile
def worksheet_list(request):
user_profile = get_object_or_404(UserProfile, user=request.user)
contractor = user_profile.contractor
worksheets = Worksheet.objects.filter(contractor=contractor)
# Apply any other filtering or sorting as needed
context = {
'worksheets': worksheets,
'contractor': contractor,
}
return render(request, 'worksheet_list.html', context)
5. Use Permissions to Control Access
Use Django's permissions framework to control access to data. For example, you can create custom permissions to allow users to view or edit only the data related to their contractor.
Alternatively, if your application requires row-level permissions, you might consider using third-party packages like django-guardian to provide object-level permissions.
6. Remove Unnecessary Code and Simplify Helpers
Since you're no longer switching between different models, you can simplify your helper functions and remove the code that manipulates field names based on prefixes. The TABLE_RELATION_BY_USER and related functions can be removed or simplified.
7. Update Templates and Frontend Code
Ensure that your templates and frontend code expect data in the new format. Update any JavaScript or frontend logic that was relying on the old structure.
Benefits of This Approach
Simpler Models: A single set of models reduces code duplication and makes the codebase easier to maintain.
Easier to Add Contractors: Adding a new contractor involves creating a new Contractor instance, without modifying the models or code.
Better Data Integrity: Using foreign keys ensures that each record is associated with the correct contractor.
Simplified Permissions: Managing permissions at the contractor level is more straightforward.
Improved Scalability: The application can scale to handle many contractors without significant changes to the codebase.
Considerations
Data Migration: You'll need to migrate existing data into the new schema. This might involve writing data migration scripts to move data from the old tables to the new ones.
Testing: Thoroughly test the application to ensure that all functionality works correctly after the refactor.
Performance: Ensure that filtering data based on contractors does not introduce performance issues. Proper indexing and query optimization might be necessary.
User Permissions: Review your user permissions and groups to ensure they align with the new model.
Example Models After Refactor
Here's how your models might look after the refactor:
python
# models.py
class Contractor(models.Model):
name = models.CharField(max_length=255, unique=True)
# Additional fields as needed
class Worker(models.Model):
contractor = models.ForeignKey(Contractor, on_delete=models.CASCADE, related_name='workers')
worker_id = models.IntegerField(help_text="Worker ID", unique=True)
worker_full_name = models.CharField(max_length=500, help_text="Worker's full name")
# Other fields...
class Worksheet(models.Model):
contractor = models.ForeignKey(Contractor, on_delete=models.CASCADE, related_name='worksheets')
date_for_work = models.DateField()
shop_code = models.ForeignKey('Shop', on_delete=models.PROTECT)
work_type = models.ForeignKey('TypeOfWork', on_delete=models.PROTECT)
# Other fields...
class Timesheet(models.Model):
contractor = models.ForeignKey(Contractor, on_delete=models.CASCADE, related_name='timesheets')
worksheet = models.OneToOneField(Worksheet, on_delete=models.CASCADE)
worker = models.ForeignKey(Worker, on_delete=models.PROTECT)
start_work = models.TimeField()
end_work = models.TimeField()
# Other fields...
By adopting this approach, you centralize your data models and make your application more maintainable and extensible.