-
Notifications
You must be signed in to change notification settings - Fork 0
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
#52 #55
Open
platsajacki
wants to merge
19
commits into
main
Choose a base branch
from
#52
base: main
Could not load branches
Branch not found: {{ refName }}
Loading
Could not load tags
Nothing to show
Loading
Are you sure you want to change the base?
Some commits from the old base branch may be removed from the timeline,
and old review comments may become outdated.
Open
#52 #55
Changes from 17 commits
Commits
Show all changes
19 commits
Select commit
Hold shift + click to select a range
b3d7736
Add a solution template.
platsajacki 4a2e103
Test solution.
platsajacki 8b24b88
A working but not unique query.
platsajacki da02129
A working query.
platsajacki 2a3c4c5
Add MaterialQuerySet.
platsajacki 6eb21c1
Add Add MaterialDateFilterSet.
platsajacki ac4d828
Add MaterialDataFilterForm.
platsajacki acd46e1
Fix MaterialQuerySet.point.
platsajacki cb24649
Add conumable_material tests.
platsajacki 6158d79
Accounting mypy.
platsajacki 2c954f7
Fix a naming.
platsajacki 20cd40f
Update tests.
platsajacki 5df0fac
Add QueryParamsValidatorService.
platsajacki 9d6b28d
Rename materials statistic service.
platsajacki 2f22b88
Complete tests.
platsajacki a403601
Accounting mypy.
platsajacki 14de900
Accounting mypy.
platsajacki 792627d
Refactor the code.
platsajacki d6bc7aa
Update tests.
platsajacki File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,108 @@ | ||
from datetime import timedelta | ||
from typing import Self | ||
|
||
from django.contrib.postgres.expressions import ArraySubquery | ||
from django.db import models | ||
from django.db.models import F, OuterRef, Q, QuerySet, Sum | ||
from django.db.models.functions import JSONObject, TruncDate | ||
from django.utils import timezone | ||
from django.utils.translation import gettext_lazy as _ | ||
|
||
from app.models import DefaultModel | ||
from companies.models.stock import StockMaterial | ||
from purchases.models import UsedMaterial | ||
|
||
|
||
class MaterialType(DefaultModel): | ||
name = models.CharField( | ||
_("material type name"), | ||
max_length=255, | ||
) | ||
|
||
class Meta: | ||
ordering = ("name",) | ||
verbose_name = _("material type") | ||
verbose_name_plural = _("material types") | ||
|
||
|
||
class MaterialQuerySet(QuerySet): | ||
def statistic(self, point_id: int, date_from: str | None = None, date_to: str | None = None) -> Self: | ||
now = timezone.now().date() | ||
q_date_from = Q(date__gte=date_from) if date_from else Q(date__gte=(now - timedelta(days=30))) | ||
platsajacki marked this conversation as resolved.
Show resolved
Hide resolved
|
||
q_date_to = Q(date__lte=date_to) if date_to else Q(date__lte=now) | ||
stock_queryset = ( | ||
StockMaterial.objects.select_related("stock__date") | ||
.filter(stock__point__id=point_id) | ||
.annotate(date=F("stock__date")) | ||
.filter(q_date_from & q_date_to) | ||
platsajacki marked this conversation as resolved.
Show resolved
Hide resolved
|
||
) | ||
stocks = ( | ||
stock_queryset.filter(material_id=OuterRef("id")) | ||
.order_by("date") | ||
.values("material_id", "date") | ||
.annotate(amount=Sum("quantity")) | ||
.annotate( # noqa: BLK100 | ||
stocks=JSONObject( | ||
date=F("date"), | ||
amount=F("amount") | ||
) | ||
) | ||
.values_list("stocks", flat=True) | ||
) | ||
usage_queryset = ( | ||
UsedMaterial.objects | ||
.filter(material__stock__point_id=point_id) | ||
.select_related("material__material_id") | ||
.annotate(date=TruncDate("modified")) | ||
.filter(q_date_from & q_date_to) | ||
) | ||
usage = ( | ||
usage_queryset.filter(material__material_id=OuterRef("id")) | ||
.order_by("date") | ||
.values("material__material_id", "date") | ||
.annotate(amount=Sum("amount")) | ||
.annotate( | ||
stocks=JSONObject( | ||
date=F("date"), | ||
amount=F("amount") | ||
) | ||
) | ||
.values_list("stocks", flat=True) | ||
) | ||
material_ids = set( | ||
list( | ||
stock_queryset.values_list("material_id", flat=True) | ||
) + list( | ||
usage_queryset.values_list("material_id", flat=True) | ||
) | ||
) | ||
return self.filter(id__in=material_ids).annotate( | ||
stocks=ArraySubquery(stocks), usage=ArraySubquery(usage) | ||
) | ||
|
||
|
||
class Material(DefaultModel): | ||
brand = models.CharField( | ||
_("material brand"), | ||
max_length=255, | ||
) | ||
name = models.CharField( | ||
_("material name"), | ||
max_length=255, | ||
) | ||
unit = models.CharField( | ||
_("material unit"), | ||
max_length=255, | ||
) | ||
kind = models.ForeignKey( | ||
"MaterialType", | ||
on_delete=models.PROTECT, | ||
related_name="materials", | ||
) | ||
|
||
objects = MaterialQuerySet.as_manager() | ||
|
||
class Meta: | ||
ordering = ("name",) | ||
verbose_name = _("material") | ||
verbose_name_plural = _("materials") |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -1,9 +1,11 @@ | ||
from companies.services.department import CategoryCreator | ||
from companies.services.employee import EmployeeCreator | ||
from companies.services.materials_statistic import DateValidatorService | ||
from companies.services.stock import MaterialTypeCreator | ||
|
||
__all__ = [ | ||
"CategoryCreator", | ||
"EmployeeCreator", | ||
"MaterialTypeCreator", | ||
"DateValidatorService", | ||
] |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,5 @@ | ||
from companies.services.materials_statistic.validator import DateValidatorService | ||
|
||
__all__ = [ | ||
"DateValidatorService", | ||
] |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,36 @@ | ||
from dataclasses import dataclass | ||
from datetime import datetime | ||
from typing import Callable | ||
|
||
from rest_framework.exceptions import ValidationError | ||
from rest_framework.request import Request | ||
|
||
from app.services import BaseService | ||
|
||
|
||
@dataclass | ||
class DateValidatorService(BaseService): | ||
request: Request | ||
platsajacki marked this conversation as resolved.
Show resolved
Hide resolved
|
||
|
||
def valide_date_query_params(self) -> None: | ||
query_params = self.request.query_params | ||
if not query_params: | ||
return | ||
try: | ||
date_format = "%Y-%m-%d" | ||
date_from_str = query_params.get("date_from") | ||
date_to_str = query_params.get("date_to") | ||
if date_from_str: | ||
date_from = datetime.strptime(date_from_str, date_format).date() | ||
if date_to_str: | ||
date_to = datetime.strptime(date_to_str, date_format).date() | ||
if date_from_str and date_to_str and date_from >= date_to: | ||
raise ValidationError("date_from must be less than the date_to.") | ||
except (TypeError, ValueError): | ||
raise ValidationError("Invalid date format.") | ||
|
||
def get_validators(self) -> list[Callable]: | ||
return super().get_validators() + [self.valide_date_query_params] | ||
|
||
def act(self) -> bool: | ||
return True |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Empty file.
Empty file.
32 changes: 32 additions & 0 deletions
32
tests/apps/companies/services/test_materials_statistic_validator.py
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,32 @@ | ||
import pytest | ||
|
||
from rest_framework.exceptions import ValidationError | ||
from rest_framework.request import Request | ||
|
||
from companies.services import DateValidatorService | ||
|
||
|
||
def test_valid_date_params(mock_request: Request, material_date_query_params: dict[str, str]): | ||
mock_request.query_params = material_date_query_params # type: ignore | ||
|
||
assert DateValidatorService(mock_request)() is True | ||
|
||
|
||
def test_only_date_from_param(mock_request: Request, material_date_query_params: dict[str, str]): | ||
del material_date_query_params["date_to"] | ||
mock_request.query_params = material_date_query_params # type: ignore | ||
|
||
assert DateValidatorService(mock_request)() is True | ||
|
||
|
||
def test_only_date_to_param(mock_request: Request, material_date_query_params: dict[str, str]): | ||
del material_date_query_params["date_from"] | ||
mock_request.query_params = material_date_query_params # type: ignore | ||
|
||
assert DateValidatorService(mock_request)() is True | ||
|
||
|
||
def test_invalid_date_params(mock_request: Request, invalide_material_date_query_params: dict[str, str]): | ||
mock_request.query_params = invalide_material_date_query_params # type: ignore | ||
platsajacki marked this conversation as resolved.
Show resolved
Hide resolved
|
||
with pytest.raises(ValidationError): | ||
DateValidatorService(mock_request)() |
Oops, something went wrong.
Oops, something went wrong.
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
We only need listing here.
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
Are you saying that we won't have a
retrieve
logic at the front? Do I need to remove theretrieve
method?There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
I can use
mixins.ListModelMixin
andGenericViewSet
.