Skip to content

Commit

Permalink
Merge pull request #4224 from mikhailprivalov/cheque-v0.2
Browse files Browse the repository at this point in the history
Cheque v0.2
  • Loading branch information
urchinpro authored Sep 17, 2024
2 parents 3d3a83f + 8c68495 commit 0c756d2
Show file tree
Hide file tree
Showing 13 changed files with 789 additions and 267 deletions.
2 changes: 2 additions & 0 deletions api/cash_registers/urls.py
Original file line number Diff line number Diff line change
Expand Up @@ -7,4 +7,6 @@
path('close-shift', views.close_shift),
path('get-shift-data', views.get_shift_data),
path('get-services-coasts', views.get_services_coasts),
path('payment', views.payment),
path('get-cheque-data', views.get_cheque_data),
]
23 changes: 22 additions & 1 deletion api/cash_registers/views.py
Original file line number Diff line number Diff line change
Expand Up @@ -38,5 +38,26 @@ def get_shift_data(request):
@login_required
def get_services_coasts(request):
request_data = json.loads(request.body)
result = cash_register_views.get_service_coasts(request_data["serviceIds"])
result = cash_register_views.get_service_coasts(request_data["serviceIds"], request_data["finSourceId"])
return JsonResponse(result)


@login_required
def payment(request):
request_data = json.loads(request.body)
shift_id = request_data["shiftId"]
coasts = request_data["serviceCoasts"]
total_coast = request_data["totalCoast"]
cash = request_data["cash"]
received_cash = request_data["receivedCash"]
electronic = request_data["electronic"]
card_id = request_data["cardId"]
result = cash_register_views.payment(shift_id, coasts, total_coast, cash, received_cash, electronic, card_id)
return JsonResponse(result)


@login_required
def get_cheque_data(request):
request_data = json.loads(request.body)
result = cash_register_views.get_cheque_data(request_data["chequeId"])
return JsonResponse(result)
21 changes: 20 additions & 1 deletion cash_registers/admin.py
Original file line number Diff line number Diff line change
@@ -1,5 +1,5 @@
from django.contrib import admin
from cash_registers.models import CashRegister, Shift
from cash_registers.models import CashRegister, Shift, Cheque, ChequeItems


class CashRegisterAdmin(admin.ModelAdmin):
Expand All @@ -18,5 +18,24 @@ class ShiftAdmin(admin.ModelAdmin):
raw_id_fields = ['operator', 'cash_register']


class ChequeAdmin(admin.ModelAdmin):
list_display = ['pk', 'shift', 'type', 'status', 'payment_cash', 'payment_electronic']
list_filter = ('status',)
raw_id_fields = [
'shift',
'card',
]


class ChequeItemsAdmin(admin.ModelAdmin):
list_display = ['pk', 'cheque', 'research', 'coast', 'count', 'amount']
list_filter = ('cheque',)
raw_id_fields = [
'research',
]


admin.site.register(CashRegister, CashRegisterAdmin)
admin.site.register(Shift, ShiftAdmin)
admin.site.register(Cheque, ChequeAdmin)
admin.site.register(ChequeItems, ChequeItemsAdmin)
128 changes: 124 additions & 4 deletions cash_registers/models.py
Original file line number Diff line number Diff line change
@@ -1,7 +1,9 @@
import uuid
from django.db import models
from django.db import models, transaction
from jsonfield import JSONField
from cash_registers import sql_func
from clients.models import Card
from directory.models import Researches
from laboratory.utils import current_time
from podrazdeleniya.models import Podrazdeleniya
from users.models import DoctorProfile
Expand Down Expand Up @@ -39,9 +41,12 @@ def get_cash_registers():
return result

@staticmethod
def get_meta_data(cash_register_id):
cash_register: CashRegister = CashRegister.objects.get(pk=cash_register_id)
cash_register_data = {"address": cash_register.ip_address, "port": cash_register.port, "login": cash_register.login, "password": cash_register.password}
def get_meta_data(cash_register_id=None, cash_register_obj=None):
if cash_register_obj:
cash_register_data = {"address": cash_register_obj.ip_address, "port": cash_register_obj.port, "login": cash_register_obj.login, "password": cash_register_obj.password}
else:
cash_register: CashRegister = CashRegister.objects.get(pk=cash_register_id)
cash_register_data = {"address": cash_register.ip_address, "port": cash_register.port, "login": cash_register.login, "password": cash_register.password}
return cash_register_data


Expand Down Expand Up @@ -137,3 +142,118 @@ def change_status(current_status, job_status, shift):
shift.confirm_close_shift()
result = "Закрыта"
return result

@staticmethod
def create_job_json(cash_register_data, uuid_data, operator, type_operations="openShift"):
body = {"cashRegister": cash_register_data, "uuid": uuid_data, "job": [{"type": type_operations, "operator": operator}]}
return body


class Cheque(models.Model):
SELL = "sell"
BUY = "buy"
SELL_RETURN = "sell-return"
BUY_RETURN = "buy-return"
CASH_IN = "cash-in"
CASH_OUT = "cash-out"
TYPES = (
(SELL, "Приход"),
(BUY, "Расход"),
(SELL_RETURN, "Возврат прихода"),
(BUY_RETURN, "Возврат расхода"),
(CASH_IN, "Внесение"),
(CASH_OUT, "Выплата"),
)

shift = models.ForeignKey(Shift, verbose_name='Смена', help_text='1', null=True, on_delete=models.CASCADE, db_index=True)
type = models.CharField(max_length=20, choices=TYPES, verbose_name='Тип операции', help_text='sell, buy и т.д', db_index=True)
uuid = models.UUIDField(verbose_name='UUID', help_text='abbfg-45fsd2')
status = models.BooleanField(verbose_name='Проведен', default=False, db_index=True)
cancelled = models.BooleanField(verbose_name='Аннулирован', default=False, db_index=True)
payment_cash = models.DecimalField(max_digits=10, verbose_name='Оплата наличными', default=0, decimal_places=2)
received_cash = models.DecimalField(max_digits=10, verbose_name='Получено наличными', default=0, decimal_places=2)
payment_electronic = models.DecimalField(max_digits=10, verbose_name='Оплата электронно', default=0, decimal_places=2)
payment_at = models.DateTimeField(verbose_name='Время оплаты', help_text='2024-07-28 16:00', null=True, blank=True, db_index=True)
card = models.ForeignKey(Card, verbose_name='Карта пациента/клиента', help_text='1', null=True, blank=True, on_delete=models.SET_NULL, db_index=True)
row_data = JSONField(blank=True, null=True, verbose_name="Json чек-документ")

class Meta:
verbose_name = "Чек"
verbose_name_plural = "Чеки"

def __str__(self):
return f"{self.type} - {self.shift} - {self.payment_at} - {self.card_id}"

@staticmethod
def create_payments(cash, received_cash, electronic):
result = []
if cash:
result.append({"type": "cash", "sum": received_cash})
if electronic:
result.append({"type": "electronically", "sum": electronic})
return result

@staticmethod
def create_job_json(cash_register_data, uuid_data, type_operations, items, payments, total):
body = {"cashRegister": cash_register_data, "uuid": uuid_data, "job": [{"type": type_operations, "items": items, "payments": payments, "total": total}]}
return body

@staticmethod
def create_cheque(shift_id, type_operations, uuid_data, cash, received_cash, electronic, card_id, items):
with transaction.atomic():
new_cheque = Cheque(shift_id=shift_id, type=type_operations, uuid=uuid_data, payment_cash=cash, received_cash=received_cash, payment_electronic=electronic, card_id=card_id)
new_cheque.save()
for item in items:
new_items = ChequeItems(cheque_id=new_cheque.pk, research_id=item["id"], coast=item["price"], discount=item["discount"], count=item["quantity"], amount=item["amount"])
new_items.save()
row_data = {
"shift_id": shift_id,
"type": type_operations,
"uuid": uuid_data,
"status": False,
"cancelled": False,
"payment_cash": cash,
"received_cash": received_cash,
"payment_electronic": electronic,
"payment_at": None,
"card_id": card_id,
"items": items,
}
new_cheque.row_data = row_data
new_cheque.save()
return new_cheque.pk


class ChequeItems(models.Model):
cheque = models.ForeignKey(Cheque, verbose_name='Чек', on_delete=models.CASCADE, db_index=True)
research = models.ForeignKey(Researches, verbose_name='Услуга', null=True, on_delete=models.SET_NULL, db_index=True)
coast = models.DecimalField(max_digits=10, decimal_places=2, verbose_name='Цена за шт')
discount = models.PositiveIntegerField(default=0, verbose_name='Скидка (%)')
count = models.PositiveIntegerField(default=1, verbose_name='Количество')
amount = models.DecimalField(max_digits=10, decimal_places=2, verbose_name='Сумма позиции')

class Meta:
verbose_name = "Элемент чека"
verbose_name_plural = "Элементы чека"

def __str__(self):
return f"{self.cheque} - {self.research_id} - {self.count} - {self.amount}"

@staticmethod
def create_items(items):
result = [
{
"id": item["id"],
"type": "position",
"name": item["title"],
"price": float(item["discountedCoast"]),
"discount": item["discountRelative"],
"quantity": int(item["count"]),
"amount": float(item["total"]),
"tax": {"type": "none"},
"paymentMethod": "fullPayment",
"paymentObject": "service",
}
for item in items
]
return result
18 changes: 3 additions & 15 deletions cash_registers/req.py
Original file line number Diff line number Diff line change
Expand Up @@ -11,7 +11,7 @@ def check_cash_register_status(cash_register_data: dict) -> dict:
headers = get_authorization_header()
body = {"cashRegister": cash_register_data}
try:
response = requests.post(f"{CASH_REGISTER_SERVER_ADDRESS}get-cash-register-status", json=body, headers=headers, timeout=30)
response = requests.post(f"{CASH_REGISTER_SERVER_ADDRESS}/get-cash-register-status", json=body, headers=headers, timeout=20)
response_data = response.json()
except Exception as e:
return {
Expand Down Expand Up @@ -45,7 +45,7 @@ def check_cash_register(cash_register_data: dict):
def send_job(body: dict):
headers = get_authorization_header()
try:
response = requests.post(f"{CASH_REGISTER_SERVER_ADDRESS}push-job", json=body, headers=headers, timeout=5)
response = requests.post(f"{CASH_REGISTER_SERVER_ADDRESS}/push-job", json=body, headers=headers, timeout=60)
response_data = response.json()
except Exception as e:
return {"ok": False, "message": "Ошибка", "data": f"{e}", "connection_middle_server_error": True}
Expand All @@ -56,20 +56,8 @@ def get_job_status(uuid: str, cash_register: dict):
body = {"cashRegister": cash_register, "uuid": uuid}
headers = get_authorization_header()
try:
response = requests.post(f"{CASH_REGISTER_SERVER_ADDRESS}get-job-status", json=body, headers=headers, timeout=5)
response = requests.post(f"{CASH_REGISTER_SERVER_ADDRESS}/get-job-status", json=body, headers=headers, timeout=60)
response_data = response.json()
except Exception as e:
return {"ok": False, "message": "Ошибка", "data": f"{e}", "connection_middle_server_error": True}
return response_data


def open_shift(uuid: str, cash_register: dict, operator: dict):
body = {"cashRegister": cash_register, "uuid": uuid, "job": [{"type": "openShift", "operator": operator}]}
result = send_job(body)
return result


def close_shift(uuid: str, cash_register: dict, operator: dict):
body = {"cashRegister": cash_register, "uuid": uuid, "job": [{"type": "closeShift", "operator": operator}]}
result = send_job(body)
return result
20 changes: 10 additions & 10 deletions cash_registers/sql_func.py
Original file line number Diff line number Diff line change
Expand Up @@ -33,19 +33,19 @@ def check_shift(cash_register_id, doctor_profile_id):
return rows


def get_service_coasts(services_ids):
def get_service_coasts(services_ids, price_id):
with connection.cursor() as cursor:
cursor.execute(
"""
SELECT directory_researches.id as research_id, directory_researches.title, contracts_pricecoast.coast FROM directions_istochnikifinansirovaniya
INNER JOIN clients_cardbase ON directions_istochnikifinansirovaniya.base_id = clients_cardbase.id
INNER JOIN contracts_contract ON directions_istochnikifinansirovaniya.contracts_id = contracts_contract.id
INNER JOIN contracts_pricecoast ON contracts_contract.price_id = contracts_pricecoast.price_name_id
INNER JOIN directory_researches ON contracts_pricecoast.research_id = directory_researches.id
WHERE LOWER(directions_istochnikifinansirovaniya.title) = 'платно' and clients_cardbase.internal_type = true
AND contracts_pricecoast.research_id in %(services_ids)s
SELECT
contracts_pricecoast.coast,
contracts_pricecoast.research_id
FROM contracts_pricecoast
WHERE
contracts_pricecoast.price_name_id = %(price_id)s and
contracts_pricecoast.research_id in %(services_ids)s
""",
params={"services_ids": services_ids},
params={"services_ids": services_ids, "price_id": price_id},
)
rows = namedtuplefetchall(cursor)
return rows
Expand All @@ -55,7 +55,7 @@ def get_services(services_ids):
with connection.cursor() as cursor:
cursor.execute(
"""
SELECT directory_researches.id, directory_researches.title FROM directory_researches
SELECT directory_researches.id, directory_researches.title, directory_researches.def_discount, directory_researches.prior_discount FROM directory_researches
WHERE directory_researches.id in %(services_ids)s
""",
params={"services_ids": services_ids},
Expand Down
Loading

0 comments on commit 0c756d2

Please sign in to comment.