You can not select more than 25 topics
Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.
63 lines
2.2 KiB
63 lines
2.2 KiB
from django.http import JsonResponse
|
|
from django.views import View
|
|
|
|
# Таблица стран
|
|
COUNTRY_CODES = {
|
|
range(0, 140): "США и Канада",
|
|
range(200, 300): "Внутренний код предприятия",
|
|
range(300, 380): "Франция",
|
|
380: "Болгария",
|
|
482: "Украина",
|
|
# Добавьте остальные страны из таблицы
|
|
}
|
|
|
|
def get_country(code):
|
|
"""Получение страны по коду."""
|
|
for code_range, country in COUNTRY_CODES.items():
|
|
if isinstance(code_range, range) and code in code_range:
|
|
return country
|
|
elif code == code_range:
|
|
return country
|
|
return "Неизвестная страна"
|
|
|
|
def validate_barcode(barcode):
|
|
"""Проверка валидности штрих-кода."""
|
|
if len(barcode) != 13 or not barcode.isdigit():
|
|
return False, "Штрих-код должен содержать 13 цифр."
|
|
|
|
# Проверка контрольной цифры
|
|
even_sum = sum(int(barcode[i]) for i in range(1, 12, 2))
|
|
odd_sum = sum(int(barcode[i]) for i in range(0, 12, 2))
|
|
control_digit = (10 - ((even_sum * 3 + odd_sum) % 10)) % 10
|
|
|
|
if control_digit != int(barcode[-1]):
|
|
return False, "Контрольная цифра не совпадает."
|
|
|
|
return True, "Штрих-код валиден."
|
|
|
|
class BarcodeView(View):
|
|
def post(self, request):
|
|
barcode = request.POST.get("barcode", "").strip()
|
|
|
|
# Валидация штрих-кода
|
|
is_valid, message = validate_barcode(barcode)
|
|
if not is_valid:
|
|
return JsonResponse({"error": message}, status=400)
|
|
|
|
# Расшифровка штрих-кода
|
|
country_code = int(barcode[:3])
|
|
manufacturer_code = barcode[3:7]
|
|
product_code = barcode[7:12]
|
|
control_digit = barcode[-1]
|
|
|
|
country = get_country(country_code)
|
|
|
|
response = {
|
|
"barcode": barcode,
|
|
"country": country,
|
|
"manufacturer_code": manufacturer_code,
|
|
"product_code": product_code,
|
|
"control_digit": control_digit,
|
|
}
|
|
return JsonResponse(response, status=200)
|