-
-
Notifications
You must be signed in to change notification settings - Fork 30
Lock Receipt
during validation and other concurrency improvements
#217
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
Draft
npazosmendez
wants to merge
1
commit into
WhyNotHugo:main
Choose a base branch
from
npazosmendez:njpm/interrupted-validations
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.
Draft
Changes from all commits
Commits
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 hidden or 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 |
---|---|---|
|
@@ -25,6 +25,7 @@ | |
from django.core.validators import MinValueValidator | ||
from django.db import connection | ||
from django.db import models | ||
from django.db import transaction | ||
from django.db.models import CheckConstraint | ||
from django.db.models import Count | ||
from django.db.models import F | ||
|
@@ -944,41 +945,44 @@ def validate(self, ticket: AuthTicket | None = None) -> list[str]: | |
return [] | ||
|
||
qs.order_by("issued_date", "id")._assign_numbers() | ||
ids = qs.values_list("id", flat=True) | ||
|
||
ticket = ticket or first.point_of_sales.owner.get_or_create_ticket("wsfe") | ||
client = clients.get_client("wsfe", first.point_of_sales.owner.is_sandboxed) | ||
response = client.service.FECAESolicitar( | ||
serializers.serialize_ticket(ticket), | ||
serializers.serialize_multiple_receipts(qs), | ||
) | ||
check_response(response) | ||
errs = [] | ||
for cae_data in response.FeDetResp.FECAEDetResponse: | ||
if cae_data.Resultado == ReceiptValidation.RESULT_APPROVED: | ||
validation = ReceiptValidation.objects.create( | ||
result=cae_data.Resultado, | ||
cae=cae_data.CAE, | ||
cae_expiration=parsers.parse_date(cae_data.CAEFchVto), | ||
receipt=qs.get( | ||
receipt_number=cae_data.CbteDesde, | ||
), | ||
processed_date=parsers.parse_datetime( | ||
response.FeCabResp.FchProceso, | ||
), | ||
) | ||
if cae_data.Observaciones: | ||
with transaction.atomic(): | ||
qs = Receipt.objects.filter(id__in=ids, receipt_number__isnull=False).select_for_update() | ||
ticket = ticket or first.point_of_sales.owner.get_or_create_ticket("wsfe") | ||
client = clients.get_client("wsfe", first.point_of_sales.owner.is_sandboxed) | ||
response = client.service.FECAESolicitar( | ||
serializers.serialize_ticket(ticket), | ||
serializers.serialize_multiple_receipts(qs), | ||
) | ||
check_response(response) | ||
for cae_data in response.FeDetResp.FECAEDetResponse: | ||
if cae_data.Resultado == ReceiptValidation.RESULT_APPROVED: | ||
validation = ReceiptValidation.objects.create( | ||
result=cae_data.Resultado, | ||
cae=cae_data.CAE, | ||
cae_expiration=parsers.parse_date(cae_data.CAEFchVto), | ||
receipt=qs.get( | ||
receipt_number=cae_data.CbteDesde, | ||
), | ||
processed_date=parsers.parse_datetime( | ||
response.FeCabResp.FchProceso, | ||
), | ||
) | ||
if cae_data.Observaciones: | ||
for obs in cae_data.Observaciones.Obs: | ||
observation = Observation.objects.create( | ||
code=obs.Code, | ||
message=obs.Msg, | ||
) | ||
validation.observations.add(observation) | ||
elif cae_data.Observaciones: | ||
for obs in cae_data.Observaciones.Obs: | ||
observation = Observation.objects.create( | ||
code=obs.Code, | ||
message=obs.Msg, | ||
) | ||
validation.observations.add(observation) | ||
elif cae_data.Observaciones: | ||
for obs in cae_data.Observaciones.Obs: | ||
errs.append(f"Error {obs.Code}: {parsers.parse_string(obs.Msg)}") | ||
errs.append(f"Error {obs.Code}: {parsers.parse_string(obs.Msg)}") | ||
|
||
# Remove the number from ones that failed to validate: | ||
qs.filter(validation__isnull=True).update(receipt_number=None) | ||
Receipt.objects.filter(id__in=ids, validation__isnull=True).update(receipt_number=None) | ||
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. Idem |
||
|
||
return errs | ||
|
||
|
@@ -1334,6 +1338,11 @@ def revalidate(self) -> ReceiptValidation | None: | |
) | ||
validation.observations.add(observation) | ||
return validation | ||
|
||
# Update atomically, skip if it was just validated | ||
Receipt.objects.filter(pk=self.pk, validation__isnull=True).update( | ||
receipt_number=None, | ||
) | ||
return None | ||
|
||
def approximate_date(receipt: Receipt) -> bool: | ||
|
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.
Podés reusar el QuerySet existente acá:
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.
Eso intenté en un principio, pero me da esta excepción:
Me parece que el problema es el
qs = self.filter(validation__isnull=True)
de un par de lineas más arriba. Por lo que leí, Postgres dice que no puede lockear las filas según un criterio como ese, porque en cualquier momento podría suceder quevalidation__isnull=True
si se agregara un Validation que apunte alReceipt
; tendría que lockear la tabla Validations entera supongo, o algo similar.Decime si estoy tirando fruta, no sé mucho PG pero menos aun Django