From 778c979aa396986ac4f8d15c0887aba0dced4889 Mon Sep 17 00:00:00 2001 From: Andrey Smakotin Date: Sun, 14 Dec 2025 20:41:21 +0300 Subject: [PATCH] =?UTF-8?q?=D0=94=D0=BE=D0=B1=D0=B0=D0=B2=D0=BB=D0=B5?= =?UTF-8?q?=D0=BD=D1=8B=20=D0=BA=D0=BD=D0=BE=D0=BF=D0=BA=D0=B8=20=D0=98?= =?UTF-8?q?=D0=BC=D0=BF=D0=BE=D1=80=D1=82=20=D0=B8=20=D0=AD=D0=BA=D1=81?= =?UTF-8?q?=D0=BF=D0=BE=D1=80=D1=82=20=D0=BD=D0=B0=20=D1=81=D1=82=D1=80?= =?UTF-8?q?=D0=B0=D0=BD=D0=B8=D1=86=D1=83=20=D1=81=D0=BF=D0=B8=D1=81=D0=BA?= =?UTF-8?q?=D0=B0=20=D0=BA=D0=BB=D0=B8=D0=B5=D0=BD=D1=82=D0=BE=D0=B2?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit - Добавлены кнопки Импорт и Экспорт в header страницы customers/ - Создан URL-маршрут для customer-import и customer-export - Реализована функция customer_export: экспорт всех клиентов в CSV файл с BOM для Excel - Экспортируются поля: ID, Имя, Фамилия, Email, Телефон, Баланс кошелька, Дата создания - Создан шаблон customer_import.html с инструкцией и формой загрузки файла - Функция customer_import пока заглушка (TODO: реализовать парсинг CSV/Excel) - Кнопки оформлены в btn-group с иконками Bootstrap Icons - Системный клиент исключён из экспорта --- .../templates/customers/customer_import.html | 75 +++++++++++++++++++ .../templates/customers/customer_list.html | 12 ++- myproject/customers/urls.py | 2 + myproject/customers/views.py | 66 ++++++++++++++++ 4 files changed, 154 insertions(+), 1 deletion(-) create mode 100644 myproject/customers/templates/customers/customer_import.html diff --git a/myproject/customers/templates/customers/customer_import.html b/myproject/customers/templates/customers/customer_import.html new file mode 100644 index 0000000..49858e2 --- /dev/null +++ b/myproject/customers/templates/customers/customer_import.html @@ -0,0 +1,75 @@ +{% extends "base.html" %} + +{% block title %}Импорт клиентов{% endblock %} + +{% block content %} +
+
+
+ +
+

Импорт клиентов

+ + Назад к списку + +
+ + +
+
Инструкция
+

Загрузите CSV или Excel файл со следующими столбцами:

+
    +
  • Имя (обязательно)
  • +
  • Фамилия (опционально)
  • +
  • Email (опционально)
  • +
  • Телефон (опционально, формат: +375XXXXXXXXX)
  • +
  • Баланс кошелька (опционально, по умолчанию 0)
  • +
+

+ + Скачать образец (текущие клиенты) + +

+
+ + +
+
+
+ {% csrf_token %} + +
+ + + + Поддерживаемые форматы: CSV, Excel (.xlsx, .xls) + +
+ +
+ + +
+ +
+ + Внимание! Функция импорта находится в разработке. +
+ + + + Отмена + +
+
+
+ +
+
+
+{% endblock %} diff --git a/myproject/customers/templates/customers/customer_list.html b/myproject/customers/templates/customers/customer_list.html index ea2b9b9..3b69d0f 100644 --- a/myproject/customers/templates/customers/customer_list.html +++ b/myproject/customers/templates/customers/customer_list.html @@ -9,7 +9,17 @@

Клиенты

- Добавить клиента +
diff --git a/myproject/customers/urls.py b/myproject/customers/urls.py index 2fffff9..c50c2ff 100644 --- a/myproject/customers/urls.py +++ b/myproject/customers/urls.py @@ -6,6 +6,8 @@ app_name = 'customers' urlpatterns = [ path('', views.customer_list, name='customer-list'), path('create/', views.customer_create, name='customer-create'), + path('import/', views.customer_import, name='customer-import'), + path('export/', views.customer_export, name='customer-export'), path('/', views.customer_detail, name='customer-detail'), path('/edit/', views.customer_update, name='customer-update'), path('/delete/', views.customer_delete, name='customer-delete'), diff --git a/myproject/customers/views.py b/myproject/customers/views.py index 6995784..b5659b2 100644 --- a/myproject/customers/views.py +++ b/myproject/customers/views.py @@ -591,3 +591,69 @@ def wallet_withdraw(request, pk): messages.error(request, '; '.join(e.messages) if hasattr(e, 'messages') else str(e)) return redirect('customers:customer-detail', pk=pk) + + +@login_required +@manager_or_owner_required +def customer_import(request): + """ + Импорт клиентов из CSV/Excel файла. + TODO: Реализовать логику импорта + """ + if request.method == 'POST': + # TODO: Обработка загруженного файла + messages.info(request, 'Функция импорта в разработке') + return redirect('customers:customer-list') + + context = { + 'title': 'Импорт клиентов', + } + return render(request, 'customers/customer_import.html', context) + + +@login_required +@manager_or_owner_required +def customer_export(request): + """ + Экспорт клиентов в CSV/Excel файл. + TODO: Реализовать логику экспорта + """ + import csv + from django.http import HttpResponse + from django.utils import timezone + + # Создаём HTTP ответ с CSV файлом + response = HttpResponse(content_type='text/csv; charset=utf-8') + response['Content-Disposition'] = f'attachment; filename="customers_export_{timezone.now().strftime("%Y%m%d_%H%M%S")}.csv"' + + # Добавляем BOM для корректного открытия в Excel + response.write('\ufeff') + + writer = csv.writer(response) + + # Заголовки + writer.writerow([ + 'ID', + 'Имя', + 'Фамилия', + 'Email', + 'Телефон', + 'Баланс кошелька', + 'Дата создания', + ]) + + # Данные (исключаем системного клиента) + customers = Customer.objects.filter(is_system_customer=False).order_by('-created_at') + + for customer in customers: + writer.writerow([ + customer.id, + customer.first_name or '', + customer.last_name or '', + customer.email or '', + str(customer.phone) if customer.phone else '', + str(customer.wallet_balance), + customer.created_at.strftime('%Y-%m-%d %H:%M:%S'), + ]) + + return response