Compare commits
36
Commits
v0.1.3
..
2d43600066
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
2d43600066 | ||
|
|
d6e6075469 | ||
|
|
289b1e8d37 | ||
|
|
c4823b7e64 | ||
|
|
f7a89b431d | ||
|
|
1bee7a7940 | ||
|
|
1bd3e17672 | ||
|
|
91ca486e64 | ||
|
|
2389bca42b | ||
|
|
520960d009 | ||
|
|
0cda791d44 | ||
|
|
a65488c304 | ||
|
|
4d9d0a894c | ||
|
|
fd1e78ba8c | ||
|
|
99e2cbc1f0 | ||
|
|
71f444b9aa | ||
|
|
a8de7cfa33 | ||
|
|
f7dcefeea6 | ||
|
|
757ebea2ba | ||
|
|
4d41513994 | ||
|
|
43441ee430 | ||
|
|
90fd4f86f8 | ||
|
|
77f6b5c5e2 | ||
|
|
3a084a9d79 | ||
|
|
85512ab48b | ||
|
|
3bf62c80d5 | ||
|
|
4cc07632f0 | ||
|
|
7b0017d1f4 | ||
|
|
1d2722b715 | ||
|
|
bfd0aec56f | ||
|
|
68d578b29d | ||
|
|
21331b75a8 | ||
|
|
6395e36c62 | ||
|
|
87fb8c744d | ||
|
|
357a2ed423 | ||
|
|
434ed7a376 |
@@ -2,9 +2,9 @@ name: Build and Publish
|
||||
|
||||
on:
|
||||
push:
|
||||
branches:
|
||||
- master
|
||||
- main
|
||||
#branches:
|
||||
# - master
|
||||
# - main
|
||||
tags:
|
||||
- 'v*.*.*'
|
||||
|
||||
|
||||
@@ -2,3 +2,4 @@
|
||||
/data
|
||||
db.sqlite3
|
||||
/uploads
|
||||
.DS_Store
|
||||
|
||||
@@ -0,0 +1,60 @@
|
||||
# AGENTS.md
|
||||
|
||||
This file provides guidance to Codex (Codex.ai/code) when working with code in this repository.
|
||||
|
||||
## Project Overview
|
||||
|
||||
Pet sitting web service for managing clients and bookings. The owner uses the site to:
|
||||
- Receive and manage client requests (leads) from the website
|
||||
- Schedule calls and visits with clients
|
||||
- Upload photos/videos of pets for remote viewing by clients (public media page via unique token)
|
||||
- Get Telegram notifications about new requests
|
||||
|
||||
## Tech Stack
|
||||
|
||||
- **Language:** Rust (edition 2024)
|
||||
- **Web framework:** [Cot](https://github.com/cot-rs/cot) - Rust web framework (Django-like), local path `../cot/cot`
|
||||
- **Database:** PostgreSQL (via Cot ORM)
|
||||
- **Notifications:** Telegram Bot API
|
||||
|
||||
## Build & Run
|
||||
|
||||
```sh
|
||||
cargo build # build
|
||||
cargo run # run dev server at http://127.0.0.1:8000
|
||||
cargo test # run all tests
|
||||
cargo test <name> # run a single test by name
|
||||
cargo clippy # lint
|
||||
cargo fmt --check # check formatting
|
||||
cot migration make # generate migrations from model changes (requires cot-cli)
|
||||
```
|
||||
|
||||
Set `WEB_PETTING_DATABASE_URL` (or `DATABASE_URL`) before running the app or migrations. Example:
|
||||
|
||||
```sh
|
||||
WEB_PETTING_DATABASE_URL=postgresql://postgres:postgres@localhost:5432/web_petting cargo run
|
||||
```
|
||||
|
||||
## Architecture
|
||||
|
||||
Monolithic Cot web app with a single PostgreSQL database.
|
||||
|
||||
- `src/main.rs` - project/app setup, router, config
|
||||
- `src/models.rs` - all database models (Lead, Client, Visit, Media, User, Setting)
|
||||
- `src/migrations.rs` - migration registry
|
||||
- `src/migrations/` - migration files
|
||||
|
||||
## Database Design Principles
|
||||
|
||||
- **Soft-delete everywhere:** records are never physically deleted, only status changes (e.g. `active` -> `archived`, `new` -> `rejected`). This ensures data can always be recovered.
|
||||
- **Status fields** are stored as `String` with enum-like values defined in `models.rs`.
|
||||
- **Foreign keys** use `cot::db::ForeignKey<T>` with `Restrict` on delete/update.
|
||||
|
||||
## Data Model
|
||||
|
||||
- **Lead** (`new`/`in_progress`/`converted`/`rejected`) - public form submission; links to Client when converted
|
||||
- **Client** (`active`/`archived`) - confirmed client with `media_token` for public media page
|
||||
- **Visit** (`scheduled`/`completed`/`cancelled`/`deleted`) - pet sitting session, belongs to Client and User
|
||||
- **Media** (`active`/`archived`) - photo/video, belongs to Client, optionally to Visit
|
||||
- **User** (`active`/`archived`) - admin accounts (supports multiple admins)
|
||||
- **Setting** - global key-value config (telegram_bot_token, telegram_chat_id, etc.)
|
||||
@@ -13,30 +13,36 @@ Pet sitting web service for managing clients and bookings. The owner uses the si
|
||||
## Tech Stack
|
||||
|
||||
- **Language:** Rust (edition 2024)
|
||||
- **Web framework:** [Cot](https://github.com/cot-rs/cot) — Rust web framework (Django-like), local path `../cot/cot`
|
||||
- **Database:** SQLite (via Cot ORM), file `db.sqlite3`
|
||||
- **Web framework:** [Cot](https://github.com/cot-rs/cot) - Rust web framework (Django-like), local path `../cot/cot`
|
||||
- **Database:** PostgreSQL (via Cot ORM)
|
||||
- **Notifications:** Telegram Bot API
|
||||
|
||||
## Build & Run
|
||||
|
||||
```sh
|
||||
cargo build # build
|
||||
cargo run # run dev server at http://127.0.0.1:8000
|
||||
cargo test # run all tests
|
||||
cargo test <name> # run a single test by name
|
||||
cargo clippy # lint
|
||||
cargo fmt --check # check formatting
|
||||
cot migration make # generate migrations from model changes (requires cot-cli)
|
||||
cargo build # build
|
||||
cargo run # run dev server at http://127.0.0.1:8000
|
||||
cargo test # run all tests
|
||||
cargo test <name> # run a single test by name
|
||||
cargo clippy # lint
|
||||
cargo fmt --check # check formatting
|
||||
cot migration make # generate migrations from model changes (requires cot-cli)
|
||||
```
|
||||
|
||||
Set `WEB_PETTING_DATABASE_URL` (or `DATABASE_URL`) before running the app or migrations. Example:
|
||||
|
||||
```sh
|
||||
WEB_PETTING_DATABASE_URL=postgresql://postgres:postgres@localhost:5432/web_petting cargo run
|
||||
```
|
||||
|
||||
## Architecture
|
||||
|
||||
Monolithic Cot web app with a single SQLite database.
|
||||
Monolithic Cot web app with a single PostgreSQL database.
|
||||
|
||||
- `src/main.rs` — project/app setup, router, config
|
||||
- `src/models.rs` — all database models (Lead, Client, Visit, Media, User, Setting)
|
||||
- `src/migrations.rs` — migration registry (auto-generated by `cot migration make`)
|
||||
- `src/migrations/` — migration files (auto-generated)
|
||||
- `src/main.rs` - project/app setup, router, config
|
||||
- `src/models.rs` - all database models (Lead, Client, Visit, Media, User, Setting)
|
||||
- `src/migrations.rs` - migration registry
|
||||
- `src/migrations/` - migration files
|
||||
|
||||
## Database Design Principles
|
||||
|
||||
@@ -46,9 +52,9 @@ Monolithic Cot web app with a single SQLite database.
|
||||
|
||||
## Data Model
|
||||
|
||||
- **Lead** (`new`/`in_progress`/`converted`/`rejected`) — public form submission; links to Client when converted
|
||||
- **Client** (`active`/`archived`) — confirmed client with `media_token` for public media page
|
||||
- **Visit** (`scheduled`/`completed`/`cancelled`) — pet sitting session, belongs to Client
|
||||
- **Media** (`active`/`archived`) — photo/video, belongs to Client, optionally to Visit
|
||||
- **User** (`active`/`archived`) — admin accounts (supports multiple admins)
|
||||
- **Setting** — global key-value config (telegram_bot_token, telegram_chat_id, etc.)
|
||||
- **Lead** (`new`/`in_progress`/`converted`/`rejected`) - public form submission; links to Client when converted
|
||||
- **Client** (`active`/`archived`) - confirmed client with `media_token` for public media page
|
||||
- **Visit** (`scheduled`/`completed`/`cancelled`/`deleted`) - pet sitting session, belongs to Client and User
|
||||
- **Media** (`active`/`archived`) - photo/video, belongs to Client, optionally to Visit
|
||||
- **User** (`active`/`archived`) - admin accounts (supports multiple admins)
|
||||
- **Setting** - global key-value config (telegram_bot_token, telegram_chat_id, etc.)
|
||||
|
||||
Generated
+955
-80
File diff suppressed because it is too large
Load Diff
+12
-3
@@ -1,11 +1,13 @@
|
||||
[package]
|
||||
name = "web-petting"
|
||||
version = "0.1.3"
|
||||
version = "1.0.3"
|
||||
edition = "2024"
|
||||
default-run = "web-petting"
|
||||
|
||||
[dependencies]
|
||||
cot = { version = "0.6.0", features = ["sqlite"] }
|
||||
cot = { version = "0.6.0", default-features = false, features = ["postgres", "json"] }
|
||||
chrono = "0.4"
|
||||
chrono-tz = "0.10"
|
||||
serde = { version = "1", features = ["derive"] }
|
||||
serde_html_form = "0.4"
|
||||
password-auth = "1"
|
||||
@@ -13,5 +15,12 @@ reqwest = { version = "0.12", default-features = false, features = ["rustls-tls"
|
||||
serde_json = "1"
|
||||
multer = "3"
|
||||
futures = "0.3"
|
||||
tokio = { version = "1", features = ["fs"] }
|
||||
image = { version = "0.25", default-features = false, features = ["jpeg", "png", "webp"] }
|
||||
tokio = { version = "1", features = ["fs", "rt-multi-thread"] }
|
||||
uuid = { version = "1", features = ["v4"] }
|
||||
base64 = "0.22"
|
||||
urlencoding = "2"
|
||||
tracing = "0.1"
|
||||
tracing-subscriber = { version = "0.3", features = ["env-filter"] }
|
||||
web-push-native = "0.5"
|
||||
async-trait = "0.1"
|
||||
|
||||
@@ -9,6 +9,8 @@ RUN cargo build --release
|
||||
FROM debian:bookworm-slim
|
||||
RUN apt-get update && apt-get install -y ca-certificates && rm -rf /var/lib/apt/lists/*
|
||||
WORKDIR /data
|
||||
ENV WEB_PETTING_UPLOAD_DIR=/data/uploads
|
||||
COPY --from=builder /app/target/release/web-petting /usr/local/bin/web-petting
|
||||
COPY static /app/static
|
||||
EXPOSE 3000
|
||||
CMD ["web-petting"]
|
||||
|
||||
+999
-100
File diff suppressed because it is too large
Load Diff
@@ -0,0 +1,20 @@
|
||||
use base64::Engine;
|
||||
use base64::engine::general_purpose::URL_SAFE_NO_PAD;
|
||||
use web_push_native::jwt_simple::algorithms::ES256KeyPair;
|
||||
use web_push_native::p256::SecretKey;
|
||||
use web_push_native::p256::elliptic_curve::sec1::ToEncodedPoint;
|
||||
|
||||
fn main() {
|
||||
let key_pair = ES256KeyPair::generate();
|
||||
let private = key_pair.to_bytes();
|
||||
let public = SecretKey::from_slice(&private)
|
||||
.expect("generated key must be valid")
|
||||
.public_key()
|
||||
.to_encoded_point(false);
|
||||
println!("VAPID private key (copy only the next line):");
|
||||
println!("{}", URL_SAFE_NO_PAD.encode(&private));
|
||||
println!("\nVAPID public key (copy only the next line):");
|
||||
println!("{}", URL_SAFE_NO_PAD.encode(public.as_bytes()));
|
||||
println!("\nVAPID subject:");
|
||||
println!("mailto:admin@example.com");
|
||||
}
|
||||
+167
-9
@@ -103,8 +103,11 @@ pub struct Translations {
|
||||
pub clients_media_link: &'static str,
|
||||
pub clients_add_title: &'static str,
|
||||
pub clients_add_button: &'static str,
|
||||
pub clients_delete: &'static str,
|
||||
pub clients_delete_confirm: &'static str,
|
||||
pub client_status_active: &'static str,
|
||||
pub client_status_archived: &'static str,
|
||||
pub client_status_deleted: &'static str,
|
||||
|
||||
// Users
|
||||
pub users_title: &'static str,
|
||||
@@ -118,6 +121,8 @@ pub struct Translations {
|
||||
pub users_add_button: &'static str,
|
||||
pub users_error_passwords_mismatch: &'static str,
|
||||
pub users_error_login_taken: &'static str,
|
||||
pub users_telegram_chat_id: &'static str,
|
||||
pub users_telegram_enabled: &'static str,
|
||||
|
||||
// Settings
|
||||
pub settings_title: &'static str,
|
||||
@@ -130,6 +135,35 @@ pub struct Translations {
|
||||
pub settings_telegram_chat_id: &'static str,
|
||||
pub settings_contact_info: &'static str,
|
||||
pub settings_pricing_info: &'static str,
|
||||
pub settings_timezone: &'static str,
|
||||
pub settings_site_domain: &'static str,
|
||||
pub settings_seo_keywords: &'static str,
|
||||
pub settings_turnstile_site_key: &'static str,
|
||||
pub settings_turnstile_secret_key: &'static str,
|
||||
pub settings_oidc_issuer_url: &'static str,
|
||||
pub settings_oidc_client_id: &'static str,
|
||||
pub settings_oidc_client_secret: &'static str,
|
||||
pub settings_oidc_allowed_groups: &'static str,
|
||||
pub settings_auth_password_enabled: &'static str,
|
||||
pub settings_auth_sso_enabled: &'static str,
|
||||
pub settings_section_advanced: &'static str,
|
||||
pub settings_section_notifications: &'static str,
|
||||
pub settings_section_captcha: &'static str,
|
||||
pub settings_section_oidc: &'static str,
|
||||
pub settings_section_general: &'static str,
|
||||
pub settings_client_notifications_enabled: &'static str,
|
||||
pub settings_client_notifications_help: &'static str,
|
||||
pub settings_vapid_public_key: &'static str,
|
||||
pub settings_vapid_private_key: &'static str,
|
||||
pub settings_vapid_subject: &'static str,
|
||||
pub settings_vapid_warning: &'static str,
|
||||
pub settings_vapid_generate: &'static str,
|
||||
pub settings_push_subscribers: &'static str,
|
||||
pub settings_push_no_subscribers: &'static str,
|
||||
pub settings_push_client: &'static str,
|
||||
pub settings_push_devices: &'static str,
|
||||
pub settings_push_language: &'static str,
|
||||
pub settings_push_updated: &'static str,
|
||||
pub landing_contact_label: &'static str,
|
||||
pub landing_pricing_title: &'static str,
|
||||
|
||||
@@ -144,6 +178,11 @@ pub struct Translations {
|
||||
pub login_title: &'static str,
|
||||
pub login_button: &'static str,
|
||||
pub login_error: &'static str,
|
||||
pub login_sso_button: &'static str,
|
||||
pub login_sso_error: &'static str,
|
||||
pub login_sso_error_group: &'static str,
|
||||
pub login_sso_error_provider: &'static str,
|
||||
pub login_sso_error_user_disabled: &'static str,
|
||||
pub logout: &'static str,
|
||||
pub setup_title: &'static str,
|
||||
pub setup_description: &'static str,
|
||||
@@ -233,6 +272,7 @@ pub struct Translations {
|
||||
pub visit_status_scheduled: &'static str,
|
||||
pub visit_status_completed: &'static str,
|
||||
pub visit_status_cancelled: &'static str,
|
||||
pub visit_status_deleted: &'static str,
|
||||
pub schedule_mark_done: &'static str,
|
||||
pub schedule_cancel: &'static str,
|
||||
pub schedule_edit_title: &'static str,
|
||||
@@ -265,6 +305,18 @@ pub struct Translations {
|
||||
pub portal_feedback_submit: &'static str,
|
||||
pub portal_feedback_thanks: &'static str,
|
||||
pub portal_link: &'static str,
|
||||
pub portal_notifications: &'static str,
|
||||
pub portal_notifications_text: &'static str,
|
||||
pub portal_notifications_enable: &'static str,
|
||||
pub portal_notifications_disable: &'static str,
|
||||
pub portal_notifications_denied: &'static str,
|
||||
pub portal_notifications_active: &'static str,
|
||||
pub portal_notifications_error: &'static str,
|
||||
pub portal_notifications_unsupported: &'static str,
|
||||
pub portal_calendar: &'static str,
|
||||
pub portal_future_visit: &'static str,
|
||||
pub portal_previous: &'static str,
|
||||
pub portal_next: &'static str,
|
||||
|
||||
// Common
|
||||
pub no_value: &'static str,
|
||||
@@ -281,7 +333,7 @@ static RU: Translations = Translations {
|
||||
nav_visits: "Визиты",
|
||||
nav_users: "Админы",
|
||||
nav_settings: "Настройки",
|
||||
nav_title: "Пет-ситтинг",
|
||||
nav_title: "МурНяня.РФ",
|
||||
|
||||
leads_title: "Заявки",
|
||||
leads_empty: "Заявок пока нет.",
|
||||
@@ -313,8 +365,11 @@ static RU: Translations = Translations {
|
||||
clients_media_link: "Медиа",
|
||||
clients_add_title: "Добавить клиента",
|
||||
clients_add_button: "Добавить",
|
||||
clients_delete: "Удалить клиента",
|
||||
clients_delete_confirm: "Точно удалить этого клиента?",
|
||||
client_status_active: "Активный",
|
||||
client_status_archived: "Архив",
|
||||
client_status_deleted: "Удалён",
|
||||
|
||||
users_title: "Администраторы",
|
||||
users_login: "Логин",
|
||||
@@ -327,6 +382,8 @@ static RU: Translations = Translations {
|
||||
users_add_button: "Добавить",
|
||||
users_error_passwords_mismatch: "Пароли не совпадают.",
|
||||
users_error_login_taken: "Этот логин уже занят.",
|
||||
users_telegram_chat_id: "Telegram Chat ID",
|
||||
users_telegram_enabled: "Уведомления",
|
||||
|
||||
settings_title: "Настройки",
|
||||
settings_key: "Параметр",
|
||||
@@ -338,6 +395,35 @@ static RU: Translations = Translations {
|
||||
settings_telegram_chat_id: "Chat ID для уведомлений",
|
||||
settings_contact_info: "Контактная информация (отображается на лендинге)",
|
||||
settings_pricing_info: "Блок с ценами (отображается на лендинге)",
|
||||
settings_timezone: "Часовой пояс (например Asia/Vladivostok)",
|
||||
settings_site_domain: "Домен сайта (например https://example.com)",
|
||||
settings_seo_keywords: "SEO-ключевые слова (через запятую, отображаются на сайте и в мета-теге keywords)",
|
||||
settings_turnstile_site_key: "Cloudflare Turnstile — Site Key (ключ виджета)",
|
||||
settings_turnstile_secret_key: "Cloudflare Turnstile — Secret Key (секретный ключ)",
|
||||
settings_oidc_issuer_url: "OIDC — URL провайдера (Issuer URL)",
|
||||
settings_oidc_client_id: "OIDC — Client ID",
|
||||
settings_oidc_client_secret: "OIDC — Client Secret",
|
||||
settings_oidc_allowed_groups: "OIDC — Разрешённые группы (через запятую, пусто = все)",
|
||||
settings_auth_password_enabled: "Вход по логину и паролю",
|
||||
settings_auth_sso_enabled: "Вход через SSO (OIDC)",
|
||||
settings_section_advanced: "Расширенные настройки",
|
||||
settings_section_notifications: "Уведомления",
|
||||
settings_section_captcha: "Защита от ботов",
|
||||
settings_section_oidc: "Единый вход (SSO / OIDC)",
|
||||
settings_section_general: "Сайт",
|
||||
settings_client_notifications_enabled: "Разрешить клиентам браузерные уведомления",
|
||||
settings_client_notifications_help: "Показывает клиентам настройку уведомлений о завершённых визитах.",
|
||||
settings_vapid_public_key: "VAPID — публичный ключ",
|
||||
settings_vapid_private_key: "VAPID — приватный ключ",
|
||||
settings_vapid_subject: "VAPID — контакт (например mailto:admin@example.com)",
|
||||
settings_vapid_warning: "Важно: смена пары VAPID-ключей сделает недействительными подписки всех клиентов. Им потребуется снова включить уведомления.",
|
||||
settings_vapid_generate: "Для генерации новой пары ключей выполните:",
|
||||
settings_push_subscribers: "Активные подписки клиентов",
|
||||
settings_push_no_subscribers: "Активных подписок пока нет.",
|
||||
settings_push_client: "Клиент",
|
||||
settings_push_devices: "Устройства",
|
||||
settings_push_language: "Язык",
|
||||
settings_push_updated: "Обновлено",
|
||||
landing_contact_label: "Или свяжитесь с нами напрямую",
|
||||
landing_pricing_title: "Стоимость",
|
||||
|
||||
@@ -358,7 +444,7 @@ static RU: Translations = Translations {
|
||||
media_delete_confirm: "Удалить этот файл?",
|
||||
media_all_clients: "Все клиенты",
|
||||
|
||||
portal_title: "Мои визиты",
|
||||
portal_title: "Визиты",
|
||||
portal_upcoming: "Предстоящие визиты",
|
||||
portal_past: "Прошлые визиты",
|
||||
portal_no_upcoming: "Нет предстоящих визитов.",
|
||||
@@ -368,10 +454,27 @@ static RU: Translations = Translations {
|
||||
portal_feedback_submit: "Отправить",
|
||||
portal_feedback_thanks: "Спасибо за отзыв!",
|
||||
portal_link: "Ссылка клиента",
|
||||
portal_notifications: "Уведомления",
|
||||
portal_notifications_text: "Получайте уведомления о завершённых визитах, даже когда страница закрыта. На iPhone сначала добавьте сайт на экран «Домой» и откройте его оттуда.",
|
||||
portal_notifications_enable: "Включить уведомления",
|
||||
portal_notifications_disable: "Отключить уведомления",
|
||||
portal_notifications_denied: "Уведомления заблокированы в настройках браузера.",
|
||||
portal_notifications_active: "Уведомления подключены на этом устройстве.",
|
||||
portal_notifications_error: "Не удалось сохранить подписку. Обновите страницу и попробуйте ещё раз.",
|
||||
portal_notifications_unsupported: "Этот браузер не поддерживает фоновые уведомления.",
|
||||
portal_calendar: "Календарь визитов",
|
||||
portal_future_visit: "Будущий визит",
|
||||
portal_previous: "Назад",
|
||||
portal_next: "Далее",
|
||||
|
||||
login_title: "Вход в систему",
|
||||
login_button: "Войти",
|
||||
login_error: "Неверный логин или пароль.",
|
||||
login_sso_button: "Войти через SSO",
|
||||
login_sso_error: "Ошибка SSO-авторизации.",
|
||||
login_sso_error_group: "У вас нет доступа: вы не состоите в разрешённой группе.",
|
||||
login_sso_error_provider: "Не удалось связаться с провайдером авторизации.",
|
||||
login_sso_error_user_disabled: "Ваша учётная запись отключена.",
|
||||
logout: "Выйти",
|
||||
setup_title: "Создание администратора",
|
||||
setup_description: "В системе нет ни одного администратора. Создайте первого для начала работы.",
|
||||
@@ -390,7 +493,7 @@ static RU: Translations = Translations {
|
||||
schedule_new_title: "Запланировать визиты",
|
||||
schedule_client: "Клиент",
|
||||
schedule_admin: "Исполнитель",
|
||||
schedule_default_time: "Время по умолчанию",
|
||||
schedule_default_time: "Время",
|
||||
schedule_time_start: "С",
|
||||
schedule_time_end: "До",
|
||||
schedule_pick_dates: "Добавить дату",
|
||||
@@ -407,6 +510,7 @@ static RU: Translations = Translations {
|
||||
visit_status_scheduled: "Запланирован",
|
||||
visit_status_completed: "Выполнен",
|
||||
visit_status_cancelled: "Отменён",
|
||||
visit_status_deleted: "Удалён",
|
||||
schedule_mark_done: "Выполнен",
|
||||
schedule_cancel: "Отменить",
|
||||
schedule_edit_title: "Редактировать визит",
|
||||
@@ -417,7 +521,7 @@ static RU: Translations = Translations {
|
||||
schedule_delete_confirm: "Точно удалить этот визит?",
|
||||
|
||||
landing_meta_description: "Профессиональный пет-ситтинг: кормление и уход за кошками, грызунами, рептилиями на вашей территории. Оставьте заявку — позаботимся о вашем любимце!",
|
||||
landing_hero_title: "Позаботимся о вашем питомце, пока вас нет дома",
|
||||
landing_hero_title: "Позаботимся о вашем питомце, пока вас нет дома. Город Хабаровск",
|
||||
landing_hero_subtitle: "Кормление и уход за кошками, грызунами, рептилиями на вашей территории. Ежедневные визиты — ваш питомец в надёжных руках, пока вы в отпуске или командировке.",
|
||||
landing_hero_description: "Почему лучше оставить кошку дома на время отъезда, чем, скажем, поместить в зоогостиницу? Как известно — кошка территориальное животное. Поэтому, когда кошка оказывается на незнакомой территории — она может испытывать стресс. К тому же в зоогостинице животное часто содержится в клетке. А кошки любят свободу. И дома ожидать своих хозяев — ей будет гораздо проще и комфортнее.",
|
||||
landing_hero_cta: "Оставить заявку",
|
||||
@@ -448,7 +552,7 @@ static RU: Translations = Translations {
|
||||
landing_guarantee: "Порядочность, честность и строгое выполнение ваших требований гарантировано.",
|
||||
landing_testimonials_title: "Отзывы",
|
||||
landing_form_consent: "Я даю согласие на обработку персональных данных",
|
||||
landing_footer_text: "Пет-ситтинг — забота о вашем питомце",
|
||||
landing_footer_text: "МурНяня.РФ — Присмотрим, погладим, покормим",
|
||||
landing_footer_copyright: "Все права защищены",
|
||||
|
||||
nav_testimonials: "Отзывы",
|
||||
@@ -479,7 +583,7 @@ static EN: Translations = Translations {
|
||||
nav_visits: "Visits",
|
||||
nav_users: "Admins",
|
||||
nav_settings: "Settings",
|
||||
nav_title: "Pet Sitting",
|
||||
nav_title: "МурНяня.РФ",
|
||||
|
||||
leads_title: "Leads",
|
||||
leads_empty: "No leads yet.",
|
||||
@@ -511,8 +615,11 @@ static EN: Translations = Translations {
|
||||
clients_media_link: "Media",
|
||||
clients_add_title: "Add Client",
|
||||
clients_add_button: "Add",
|
||||
clients_delete: "Delete client",
|
||||
clients_delete_confirm: "Are you sure you want to delete this client?",
|
||||
client_status_active: "Active",
|
||||
client_status_archived: "Archived",
|
||||
client_status_deleted: "Deleted",
|
||||
|
||||
users_title: "Administrators",
|
||||
users_login: "Login",
|
||||
@@ -525,6 +632,8 @@ static EN: Translations = Translations {
|
||||
users_add_button: "Add",
|
||||
users_error_passwords_mismatch: "Passwords do not match.",
|
||||
users_error_login_taken: "This login is already taken.",
|
||||
users_telegram_chat_id: "Telegram Chat ID",
|
||||
users_telegram_enabled: "Notifications",
|
||||
|
||||
settings_title: "Settings",
|
||||
settings_key: "Parameter",
|
||||
@@ -536,6 +645,35 @@ static EN: Translations = Translations {
|
||||
settings_telegram_chat_id: "Notification Chat ID",
|
||||
settings_contact_info: "Contact info (shown on landing page)",
|
||||
settings_pricing_info: "Pricing block (shown on landing page)",
|
||||
settings_timezone: "Timezone (e.g. Asia/Vladivostok)",
|
||||
settings_site_domain: "Site domain (e.g. https://example.com)",
|
||||
settings_seo_keywords: "SEO keywords (comma-separated, shown on site and in keywords meta tag)",
|
||||
settings_turnstile_site_key: "Cloudflare Turnstile — Site Key",
|
||||
settings_turnstile_secret_key: "Cloudflare Turnstile — Secret Key",
|
||||
settings_oidc_issuer_url: "OIDC — Issuer URL",
|
||||
settings_oidc_client_id: "OIDC — Client ID",
|
||||
settings_oidc_client_secret: "OIDC — Client Secret",
|
||||
settings_oidc_allowed_groups: "OIDC — Allowed groups (comma-separated, empty = all)",
|
||||
settings_auth_password_enabled: "Password login",
|
||||
settings_auth_sso_enabled: "SSO login (OIDC)",
|
||||
settings_section_advanced: "Advanced settings",
|
||||
settings_section_notifications: "Notifications",
|
||||
settings_section_captcha: "Bot protection",
|
||||
settings_section_oidc: "Single Sign-On (SSO / OIDC)",
|
||||
settings_section_general: "Site",
|
||||
settings_client_notifications_enabled: "Allow client browser notifications",
|
||||
settings_client_notifications_help: "Shows clients the completed-visit notification setting.",
|
||||
settings_vapid_public_key: "VAPID public key",
|
||||
settings_vapid_private_key: "VAPID private key",
|
||||
settings_vapid_subject: "VAPID contact (for example mailto:admin@example.com)",
|
||||
settings_vapid_warning: "Important: changing the VAPID key pair invalidates every client subscription. Clients will need to enable notifications again.",
|
||||
settings_vapid_generate: "To generate a new key pair, run:",
|
||||
settings_push_subscribers: "Active client subscriptions",
|
||||
settings_push_no_subscribers: "There are no active subscriptions yet.",
|
||||
settings_push_client: "Client",
|
||||
settings_push_devices: "Devices",
|
||||
settings_push_language: "Language",
|
||||
settings_push_updated: "Updated",
|
||||
landing_contact_label: "Or contact us directly",
|
||||
landing_pricing_title: "Pricing",
|
||||
|
||||
@@ -556,7 +694,7 @@ static EN: Translations = Translations {
|
||||
media_delete_confirm: "Delete this file?",
|
||||
media_all_clients: "All clients",
|
||||
|
||||
portal_title: "My Visits",
|
||||
portal_title: "Visits",
|
||||
portal_upcoming: "Upcoming visits",
|
||||
portal_past: "Past visits",
|
||||
portal_no_upcoming: "No upcoming visits.",
|
||||
@@ -566,10 +704,27 @@ static EN: Translations = Translations {
|
||||
portal_feedback_submit: "Submit",
|
||||
portal_feedback_thanks: "Thank you for your feedback!",
|
||||
portal_link: "Client link",
|
||||
portal_notifications: "Notifications",
|
||||
portal_notifications_text: "Receive completed-visit notifications even when this page is closed. On iPhone, first add this site to the Home Screen and open it from there.",
|
||||
portal_notifications_enable: "Enable notifications",
|
||||
portal_notifications_disable: "Disable notifications",
|
||||
portal_notifications_denied: "Notifications are blocked in your browser settings.",
|
||||
portal_notifications_active: "Notifications are enabled on this device.",
|
||||
portal_notifications_error: "The subscription could not be saved. Reload the page and try again.",
|
||||
portal_notifications_unsupported: "This browser does not support background notifications.",
|
||||
portal_calendar: "Visit calendar",
|
||||
portal_future_visit: "Future visit",
|
||||
portal_previous: "Previous",
|
||||
portal_next: "Next",
|
||||
|
||||
login_title: "Sign In",
|
||||
login_button: "Sign In",
|
||||
login_error: "Invalid login or password.",
|
||||
login_sso_button: "Sign in with SSO",
|
||||
login_sso_error: "SSO authentication failed.",
|
||||
login_sso_error_group: "Access denied: you are not a member of an allowed group.",
|
||||
login_sso_error_provider: "Could not reach the authentication provider.",
|
||||
login_sso_error_user_disabled: "Your account is disabled.",
|
||||
logout: "Sign Out",
|
||||
setup_title: "Create Administrator",
|
||||
setup_description: "There are no administrators yet. Create the first one to get started.",
|
||||
@@ -588,7 +743,7 @@ static EN: Translations = Translations {
|
||||
schedule_new_title: "Plan Visits",
|
||||
schedule_client: "Client",
|
||||
schedule_admin: "Assigned to",
|
||||
schedule_default_time: "Default Time",
|
||||
schedule_default_time: "Time",
|
||||
schedule_time_start: "From",
|
||||
schedule_time_end: "To",
|
||||
schedule_pick_dates: "Add date",
|
||||
@@ -605,6 +760,7 @@ static EN: Translations = Translations {
|
||||
visit_status_scheduled: "Scheduled",
|
||||
visit_status_completed: "Completed",
|
||||
visit_status_cancelled: "Cancelled",
|
||||
visit_status_deleted: "Deleted",
|
||||
schedule_mark_done: "Done",
|
||||
schedule_cancel: "Cancel",
|
||||
schedule_edit_title: "Edit Visit",
|
||||
@@ -646,7 +802,7 @@ static EN: Translations = Translations {
|
||||
landing_guarantee: "Integrity, honesty, and strict fulfillment of your requirements guaranteed.",
|
||||
landing_testimonials_title: "Testimonials",
|
||||
landing_form_consent: "I consent to the processing of my personal data",
|
||||
landing_footer_text: "Pet Sitting — caring for your pet",
|
||||
landing_footer_text: "МурНяня.РФ — Присмотрим, погладим, покормим",
|
||||
landing_footer_copyright: "All rights reserved",
|
||||
|
||||
nav_testimonials: "Testimonials",
|
||||
@@ -691,6 +847,7 @@ impl Translations {
|
||||
"scheduled" => self.visit_status_scheduled,
|
||||
"completed" => self.visit_status_completed,
|
||||
"cancelled" => self.visit_status_cancelled,
|
||||
"deleted" => self.visit_status_deleted,
|
||||
_ => "?",
|
||||
}
|
||||
}
|
||||
@@ -699,6 +856,7 @@ impl Translations {
|
||||
match status {
|
||||
"active" => self.client_status_active,
|
||||
"archived" => self.client_status_archived,
|
||||
"deleted" => self.client_status_deleted,
|
||||
_ => "?",
|
||||
}
|
||||
}
|
||||
|
||||
+77
-13
@@ -4,15 +4,21 @@ mod migrations;
|
||||
pub mod models;
|
||||
mod public;
|
||||
mod telegram;
|
||||
mod turnstile;
|
||||
mod tz;
|
||||
mod uploads;
|
||||
mod web_push;
|
||||
|
||||
use tracing_subscriber;
|
||||
|
||||
use cot::cli::CliMetadata;
|
||||
use cot::config::{
|
||||
DatabaseConfig, MiddlewareConfig, ProjectConfig, SessionMiddlewareConfig, SessionStoreConfig,
|
||||
SessionStoreTypeConfig,
|
||||
DatabaseConfig, MiddlewareConfig, ProjectConfig, SameSite, SessionMiddlewareConfig,
|
||||
SessionStoreConfig, SessionStoreTypeConfig,
|
||||
};
|
||||
use cot::db::migrations::SyncDynMigration;
|
||||
use cot::middleware::SessionMiddleware;
|
||||
use cot::project::{MiddlewareContext, RegisterAppsContext, RootHandler};
|
||||
use cot::project::{MiddlewareContext, ProjectContext, RegisterAppsContext, RootHandler};
|
||||
use cot::router::Router;
|
||||
use cot::session::db::SessionApp;
|
||||
use cot::{App, AppBuilder, Project};
|
||||
@@ -35,11 +41,17 @@ impl App for PettingApp {
|
||||
|
||||
struct PublicApp;
|
||||
|
||||
#[async_trait::async_trait]
|
||||
impl App for PublicApp {
|
||||
fn name(&self) -> &'static str {
|
||||
"public"
|
||||
}
|
||||
|
||||
async fn init(&self, context: &mut ProjectContext) -> cot::Result<()> {
|
||||
web_push::initialize(context.database()).await;
|
||||
Ok(())
|
||||
}
|
||||
|
||||
fn router(&self) -> Router {
|
||||
public::public_router()
|
||||
}
|
||||
@@ -47,24 +59,51 @@ impl App for PublicApp {
|
||||
|
||||
struct PettingProject;
|
||||
|
||||
fn parse_bool_env(name: &str) -> Option<bool> {
|
||||
let value = std::env::var(name).ok()?;
|
||||
match value.trim().to_ascii_lowercase().as_str() {
|
||||
"1" | "true" | "yes" | "on" => Some(true),
|
||||
"0" | "false" | "no" | "off" => Some(false),
|
||||
_ => None,
|
||||
}
|
||||
}
|
||||
|
||||
fn debug_enabled(config_name: &str) -> bool {
|
||||
parse_bool_env("WEB_PETTING_DEBUG").unwrap_or_else(|| {
|
||||
matches!(
|
||||
config_name,
|
||||
"dev" | "development" | "debug" | "local" | "test"
|
||||
)
|
||||
})
|
||||
}
|
||||
|
||||
fn database_url() -> String {
|
||||
std::env::var("WEB_PETTING_DATABASE_URL")
|
||||
.or_else(|_| std::env::var("DATABASE_URL"))
|
||||
.unwrap_or_else(|_| {
|
||||
eprintln!(
|
||||
"WEB_PETTING_DATABASE_URL and DATABASE_URL are not set; using the local default \
|
||||
postgresql://postgres:postgres@localhost:5432/web_petting"
|
||||
);
|
||||
"postgresql://postgres:postgres@localhost:5432/web_petting".to_string()
|
||||
})
|
||||
}
|
||||
|
||||
impl Project for PettingProject {
|
||||
fn cli_metadata(&self) -> CliMetadata {
|
||||
cot::cli::metadata!()
|
||||
}
|
||||
|
||||
fn config(&self, _config_name: &str) -> cot::Result<ProjectConfig> {
|
||||
fn config(&self, config_name: &str) -> cot::Result<ProjectConfig> {
|
||||
Ok(ProjectConfig::builder()
|
||||
.debug(true)
|
||||
.database(
|
||||
DatabaseConfig::builder()
|
||||
.url("sqlite://db.sqlite3?mode=rwc")
|
||||
.build(),
|
||||
)
|
||||
.debug(debug_enabled(config_name))
|
||||
.database(DatabaseConfig::builder().url(database_url()).build())
|
||||
.middlewares(
|
||||
MiddlewareConfig::builder()
|
||||
.session(
|
||||
SessionMiddlewareConfig::builder()
|
||||
.secure(false)
|
||||
.same_site(SameSite::Lax)
|
||||
.store(
|
||||
SessionStoreConfig::builder()
|
||||
.store_type(SessionStoreTypeConfig::Database)
|
||||
@@ -94,7 +133,32 @@ impl Project for PettingProject {
|
||||
}
|
||||
}
|
||||
|
||||
#[cot::main]
|
||||
fn main() -> impl Project {
|
||||
PettingProject
|
||||
fn main() {
|
||||
let filter = tracing_subscriber::EnvFilter::try_from_default_env()
|
||||
.unwrap_or_else(|_| tracing_subscriber::EnvFilter::new("info"));
|
||||
let _ = tracing_subscriber::fmt().with_env_filter(filter).try_init();
|
||||
let runtime = tokio::runtime::Builder::new_multi_thread()
|
||||
.enable_all()
|
||||
.build()
|
||||
.expect("failed to build Tokio runtime");
|
||||
if let Err(error) = runtime.block_on(cot::run_cli(PettingProject)) {
|
||||
let message = error.to_string();
|
||||
let details = format!("{error:?}");
|
||||
eprintln!("Failed to start web-petting: {message}\nDetails: {details}");
|
||||
if details.contains("28P01") || details.contains("password authentication failed") {
|
||||
eprintln!(
|
||||
"\nPostgreSQL rejected the configured username or password.\n\
|
||||
Set the connection string before starting the application, for example:\n\n \
|
||||
WEB_PETTING_DATABASE_URL='postgresql://postgres:YOUR_PASSWORD@localhost:5432/web_petting' cargo run\n\n\
|
||||
WEB_PETTING_DATABASE_URL takes priority over DATABASE_URL.\n\
|
||||
Check the current value with: printenv WEB_PETTING_DATABASE_URL"
|
||||
);
|
||||
} else if message.to_ascii_lowercase().contains("database") {
|
||||
eprintln!(
|
||||
"\nConfigure PostgreSQL with WEB_PETTING_DATABASE_URL or DATABASE_URL.\n\
|
||||
Example:\n\n WEB_PETTING_DATABASE_URL='postgresql://postgres:YOUR_PASSWORD@localhost:5432/web_petting' cargo run"
|
||||
);
|
||||
}
|
||||
std::process::exit(1);
|
||||
}
|
||||
}
|
||||
|
||||
+3
-9
@@ -1,17 +1,11 @@
|
||||
//! List of migrations for the current app.
|
||||
//!
|
||||
//! Generated by cot CLI 0.6.0 on 2026-04-29 10:36:47+00:00
|
||||
//! Squashed for the PostgreSQL migration on 2026-07-11.
|
||||
|
||||
pub mod m_0001_initial;
|
||||
pub mod m_0002_visit_schedule;
|
||||
pub mod m_0003_visit_feedback;
|
||||
pub mod m_0004_visit_public_notes;
|
||||
pub mod m_0005_testimonials;
|
||||
pub mod m_0002_push_subscription;
|
||||
/// The list of migrations for current app.
|
||||
pub const MIGRATIONS: &[&::cot::db::migrations::SyncDynMigration] = &[
|
||||
&m_0001_initial::Migration,
|
||||
&m_0002_visit_schedule::Migration,
|
||||
&m_0003_visit_feedback::Migration,
|
||||
&m_0004_visit_public_notes::Migration,
|
||||
&m_0005_testimonials::Migration,
|
||||
&m_0002_push_subscription::Migration,
|
||||
];
|
||||
|
||||
+376
-459
@@ -1,7 +1,8 @@
|
||||
//! Generated by cot CLI 0.6.0 on 2026-04-29 10:36:47+00:00
|
||||
//! Initial PostgreSQL schema for the current data model.
|
||||
|
||||
#[derive(Debug, Copy, Clone)]
|
||||
pub(super) struct Migration;
|
||||
|
||||
impl ::cot::db::migrations::Migration for Migration {
|
||||
const APP_NAME: &'static str = "web-petting";
|
||||
const MIGRATION_NAME: &'static str = "m_0001_initial";
|
||||
@@ -9,479 +10,395 @@ impl ::cot::db::migrations::Migration for Migration {
|
||||
const OPERATIONS: &'static [::cot::db::migrations::Operation] = &[
|
||||
::cot::db::migrations::Operation::create_model()
|
||||
.table_name(::cot::db::Identifier::new("web_petting__user"))
|
||||
.fields(
|
||||
&[
|
||||
::cot::db::migrations::Field::new(
|
||||
::cot::db::Identifier::new("id"),
|
||||
<cot::db::Auto<i64> as ::cot::db::DatabaseField>::TYPE,
|
||||
)
|
||||
.auto()
|
||||
.primary_key()
|
||||
.set_null(
|
||||
<cot::db::Auto<i64> as ::cot::db::DatabaseField>::NULLABLE,
|
||||
),
|
||||
::cot::db::migrations::Field::new(
|
||||
::cot::db::Identifier::new("login"),
|
||||
<String as ::cot::db::DatabaseField>::TYPE,
|
||||
)
|
||||
.set_null(<String as ::cot::db::DatabaseField>::NULLABLE)
|
||||
.unique(),
|
||||
::cot::db::migrations::Field::new(
|
||||
::cot::db::Identifier::new("password_hash"),
|
||||
<String as ::cot::db::DatabaseField>::TYPE,
|
||||
)
|
||||
.set_null(<String as ::cot::db::DatabaseField>::NULLABLE),
|
||||
::cot::db::migrations::Field::new(
|
||||
::cot::db::Identifier::new("display_name"),
|
||||
<Option<String> as ::cot::db::DatabaseField>::TYPE,
|
||||
)
|
||||
.set_null(
|
||||
<Option<String> as ::cot::db::DatabaseField>::NULLABLE,
|
||||
),
|
||||
::cot::db::migrations::Field::new(
|
||||
::cot::db::Identifier::new("status"),
|
||||
<String as ::cot::db::DatabaseField>::TYPE,
|
||||
)
|
||||
.set_null(<String as ::cot::db::DatabaseField>::NULLABLE),
|
||||
::cot::db::migrations::Field::new(
|
||||
::cot::db::Identifier::new("created_at"),
|
||||
<chrono::NaiveDateTime as ::cot::db::DatabaseField>::TYPE,
|
||||
)
|
||||
.set_null(
|
||||
<chrono::NaiveDateTime as ::cot::db::DatabaseField>::NULLABLE,
|
||||
),
|
||||
::cot::db::migrations::Field::new(
|
||||
::cot::db::Identifier::new("updated_at"),
|
||||
<chrono::NaiveDateTime as ::cot::db::DatabaseField>::TYPE,
|
||||
)
|
||||
.set_null(
|
||||
<chrono::NaiveDateTime as ::cot::db::DatabaseField>::NULLABLE,
|
||||
),
|
||||
],
|
||||
)
|
||||
.fields(&[
|
||||
::cot::db::migrations::Field::new(
|
||||
::cot::db::Identifier::new("id"),
|
||||
<cot::db::Auto<i64> as ::cot::db::DatabaseField>::TYPE,
|
||||
)
|
||||
.auto()
|
||||
.primary_key()
|
||||
.set_null(<cot::db::Auto<i64> as ::cot::db::DatabaseField>::NULLABLE),
|
||||
::cot::db::migrations::Field::new(
|
||||
::cot::db::Identifier::new("login"),
|
||||
<String as ::cot::db::DatabaseField>::TYPE,
|
||||
)
|
||||
.set_null(<String as ::cot::db::DatabaseField>::NULLABLE)
|
||||
.unique(),
|
||||
::cot::db::migrations::Field::new(
|
||||
::cot::db::Identifier::new("password_hash"),
|
||||
<String as ::cot::db::DatabaseField>::TYPE,
|
||||
)
|
||||
.set_null(<String as ::cot::db::DatabaseField>::NULLABLE),
|
||||
::cot::db::migrations::Field::new(
|
||||
::cot::db::Identifier::new("display_name"),
|
||||
<Option<String> as ::cot::db::DatabaseField>::TYPE,
|
||||
)
|
||||
.set_null(<Option<String> as ::cot::db::DatabaseField>::NULLABLE),
|
||||
::cot::db::migrations::Field::new(
|
||||
::cot::db::Identifier::new("telegram_chat_id"),
|
||||
<Option<String> as ::cot::db::DatabaseField>::TYPE,
|
||||
)
|
||||
.set_null(<Option<String> as ::cot::db::DatabaseField>::NULLABLE),
|
||||
::cot::db::migrations::Field::new(
|
||||
::cot::db::Identifier::new("telegram_notifications"),
|
||||
<Option<bool> as ::cot::db::DatabaseField>::TYPE,
|
||||
)
|
||||
.set_null(<Option<bool> as ::cot::db::DatabaseField>::NULLABLE),
|
||||
::cot::db::migrations::Field::new(
|
||||
::cot::db::Identifier::new("status"),
|
||||
<String as ::cot::db::DatabaseField>::TYPE,
|
||||
)
|
||||
.set_null(<String as ::cot::db::DatabaseField>::NULLABLE),
|
||||
::cot::db::migrations::Field::new(
|
||||
::cot::db::Identifier::new("created_at"),
|
||||
<chrono::NaiveDateTime as ::cot::db::DatabaseField>::TYPE,
|
||||
)
|
||||
.set_null(<chrono::NaiveDateTime as ::cot::db::DatabaseField>::NULLABLE),
|
||||
::cot::db::migrations::Field::new(
|
||||
::cot::db::Identifier::new("updated_at"),
|
||||
<chrono::NaiveDateTime as ::cot::db::DatabaseField>::TYPE,
|
||||
)
|
||||
.set_null(<chrono::NaiveDateTime as ::cot::db::DatabaseField>::NULLABLE),
|
||||
])
|
||||
.build(),
|
||||
::cot::db::migrations::Operation::create_model()
|
||||
.table_name(::cot::db::Identifier::new("web_petting__setting"))
|
||||
.fields(
|
||||
&[
|
||||
::cot::db::migrations::Field::new(
|
||||
::cot::db::Identifier::new("id"),
|
||||
<cot::db::Auto<i64> as ::cot::db::DatabaseField>::TYPE,
|
||||
)
|
||||
.auto()
|
||||
.primary_key()
|
||||
.set_null(
|
||||
<cot::db::Auto<i64> as ::cot::db::DatabaseField>::NULLABLE,
|
||||
),
|
||||
::cot::db::migrations::Field::new(
|
||||
::cot::db::Identifier::new("key"),
|
||||
<String as ::cot::db::DatabaseField>::TYPE,
|
||||
)
|
||||
.set_null(<String as ::cot::db::DatabaseField>::NULLABLE)
|
||||
.unique(),
|
||||
::cot::db::migrations::Field::new(
|
||||
::cot::db::Identifier::new("value"),
|
||||
<String as ::cot::db::DatabaseField>::TYPE,
|
||||
)
|
||||
.set_null(<String as ::cot::db::DatabaseField>::NULLABLE),
|
||||
::cot::db::migrations::Field::new(
|
||||
::cot::db::Identifier::new("updated_at"),
|
||||
<chrono::NaiveDateTime as ::cot::db::DatabaseField>::TYPE,
|
||||
)
|
||||
.set_null(
|
||||
<chrono::NaiveDateTime as ::cot::db::DatabaseField>::NULLABLE,
|
||||
),
|
||||
],
|
||||
)
|
||||
.fields(&[
|
||||
::cot::db::migrations::Field::new(
|
||||
::cot::db::Identifier::new("id"),
|
||||
<cot::db::Auto<i64> as ::cot::db::DatabaseField>::TYPE,
|
||||
)
|
||||
.auto()
|
||||
.primary_key()
|
||||
.set_null(<cot::db::Auto<i64> as ::cot::db::DatabaseField>::NULLABLE),
|
||||
::cot::db::migrations::Field::new(
|
||||
::cot::db::Identifier::new("key"),
|
||||
<String as ::cot::db::DatabaseField>::TYPE,
|
||||
)
|
||||
.set_null(<String as ::cot::db::DatabaseField>::NULLABLE)
|
||||
.unique(),
|
||||
::cot::db::migrations::Field::new(
|
||||
::cot::db::Identifier::new("value"),
|
||||
<String as ::cot::db::DatabaseField>::TYPE,
|
||||
)
|
||||
.set_null(<String as ::cot::db::DatabaseField>::NULLABLE),
|
||||
::cot::db::migrations::Field::new(
|
||||
::cot::db::Identifier::new("updated_at"),
|
||||
<chrono::NaiveDateTime as ::cot::db::DatabaseField>::TYPE,
|
||||
)
|
||||
.set_null(<chrono::NaiveDateTime as ::cot::db::DatabaseField>::NULLABLE),
|
||||
])
|
||||
.build(),
|
||||
::cot::db::migrations::Operation::create_model()
|
||||
.table_name(::cot::db::Identifier::new("web_petting__client"))
|
||||
.fields(
|
||||
&[
|
||||
::cot::db::migrations::Field::new(
|
||||
::cot::db::Identifier::new("id"),
|
||||
<cot::db::Auto<i64> as ::cot::db::DatabaseField>::TYPE,
|
||||
)
|
||||
.auto()
|
||||
.primary_key()
|
||||
.set_null(
|
||||
<cot::db::Auto<i64> as ::cot::db::DatabaseField>::NULLABLE,
|
||||
),
|
||||
::cot::db::migrations::Field::new(
|
||||
::cot::db::Identifier::new("name"),
|
||||
<String as ::cot::db::DatabaseField>::TYPE,
|
||||
)
|
||||
.set_null(<String as ::cot::db::DatabaseField>::NULLABLE),
|
||||
::cot::db::migrations::Field::new(
|
||||
::cot::db::Identifier::new("phone"),
|
||||
<Option<String> as ::cot::db::DatabaseField>::TYPE,
|
||||
)
|
||||
.set_null(
|
||||
<Option<String> as ::cot::db::DatabaseField>::NULLABLE,
|
||||
),
|
||||
::cot::db::migrations::Field::new(
|
||||
::cot::db::Identifier::new("email"),
|
||||
<Option<String> as ::cot::db::DatabaseField>::TYPE,
|
||||
)
|
||||
.set_null(
|
||||
<Option<String> as ::cot::db::DatabaseField>::NULLABLE,
|
||||
),
|
||||
::cot::db::migrations::Field::new(
|
||||
::cot::db::Identifier::new("address"),
|
||||
<Option<String> as ::cot::db::DatabaseField>::TYPE,
|
||||
)
|
||||
.set_null(
|
||||
<Option<String> as ::cot::db::DatabaseField>::NULLABLE,
|
||||
),
|
||||
::cot::db::migrations::Field::new(
|
||||
::cot::db::Identifier::new("notes"),
|
||||
<Option<String> as ::cot::db::DatabaseField>::TYPE,
|
||||
)
|
||||
.set_null(
|
||||
<Option<String> as ::cot::db::DatabaseField>::NULLABLE,
|
||||
),
|
||||
::cot::db::migrations::Field::new(
|
||||
::cot::db::Identifier::new("media_token"),
|
||||
<String as ::cot::db::DatabaseField>::TYPE,
|
||||
)
|
||||
.set_null(<String as ::cot::db::DatabaseField>::NULLABLE)
|
||||
.unique(),
|
||||
::cot::db::migrations::Field::new(
|
||||
::cot::db::Identifier::new("status"),
|
||||
<String as ::cot::db::DatabaseField>::TYPE,
|
||||
)
|
||||
.set_null(<String as ::cot::db::DatabaseField>::NULLABLE),
|
||||
::cot::db::migrations::Field::new(
|
||||
::cot::db::Identifier::new("created_at"),
|
||||
<chrono::NaiveDateTime as ::cot::db::DatabaseField>::TYPE,
|
||||
)
|
||||
.set_null(
|
||||
<chrono::NaiveDateTime as ::cot::db::DatabaseField>::NULLABLE,
|
||||
),
|
||||
::cot::db::migrations::Field::new(
|
||||
::cot::db::Identifier::new("updated_at"),
|
||||
<chrono::NaiveDateTime as ::cot::db::DatabaseField>::TYPE,
|
||||
)
|
||||
.set_null(
|
||||
<chrono::NaiveDateTime as ::cot::db::DatabaseField>::NULLABLE,
|
||||
),
|
||||
],
|
||||
)
|
||||
.fields(&[
|
||||
::cot::db::migrations::Field::new(
|
||||
::cot::db::Identifier::new("id"),
|
||||
<cot::db::Auto<i64> as ::cot::db::DatabaseField>::TYPE,
|
||||
)
|
||||
.auto()
|
||||
.primary_key()
|
||||
.set_null(<cot::db::Auto<i64> as ::cot::db::DatabaseField>::NULLABLE),
|
||||
::cot::db::migrations::Field::new(
|
||||
::cot::db::Identifier::new("name"),
|
||||
<String as ::cot::db::DatabaseField>::TYPE,
|
||||
)
|
||||
.set_null(<String as ::cot::db::DatabaseField>::NULLABLE),
|
||||
::cot::db::migrations::Field::new(
|
||||
::cot::db::Identifier::new("phone"),
|
||||
<Option<String> as ::cot::db::DatabaseField>::TYPE,
|
||||
)
|
||||
.set_null(<Option<String> as ::cot::db::DatabaseField>::NULLABLE),
|
||||
::cot::db::migrations::Field::new(
|
||||
::cot::db::Identifier::new("email"),
|
||||
<Option<String> as ::cot::db::DatabaseField>::TYPE,
|
||||
)
|
||||
.set_null(<Option<String> as ::cot::db::DatabaseField>::NULLABLE),
|
||||
::cot::db::migrations::Field::new(
|
||||
::cot::db::Identifier::new("address"),
|
||||
<Option<String> as ::cot::db::DatabaseField>::TYPE,
|
||||
)
|
||||
.set_null(<Option<String> as ::cot::db::DatabaseField>::NULLABLE),
|
||||
::cot::db::migrations::Field::new(
|
||||
::cot::db::Identifier::new("notes"),
|
||||
<Option<String> as ::cot::db::DatabaseField>::TYPE,
|
||||
)
|
||||
.set_null(<Option<String> as ::cot::db::DatabaseField>::NULLABLE),
|
||||
::cot::db::migrations::Field::new(
|
||||
::cot::db::Identifier::new("media_token"),
|
||||
<String as ::cot::db::DatabaseField>::TYPE,
|
||||
)
|
||||
.set_null(<String as ::cot::db::DatabaseField>::NULLABLE)
|
||||
.unique(),
|
||||
::cot::db::migrations::Field::new(
|
||||
::cot::db::Identifier::new("color"),
|
||||
<Option<String> as ::cot::db::DatabaseField>::TYPE,
|
||||
)
|
||||
.set_null(<Option<String> as ::cot::db::DatabaseField>::NULLABLE),
|
||||
::cot::db::migrations::Field::new(
|
||||
::cot::db::Identifier::new("status"),
|
||||
<String as ::cot::db::DatabaseField>::TYPE,
|
||||
)
|
||||
.set_null(<String as ::cot::db::DatabaseField>::NULLABLE),
|
||||
::cot::db::migrations::Field::new(
|
||||
::cot::db::Identifier::new("created_at"),
|
||||
<chrono::NaiveDateTime as ::cot::db::DatabaseField>::TYPE,
|
||||
)
|
||||
.set_null(<chrono::NaiveDateTime as ::cot::db::DatabaseField>::NULLABLE),
|
||||
::cot::db::migrations::Field::new(
|
||||
::cot::db::Identifier::new("updated_at"),
|
||||
<chrono::NaiveDateTime as ::cot::db::DatabaseField>::TYPE,
|
||||
)
|
||||
.set_null(<chrono::NaiveDateTime as ::cot::db::DatabaseField>::NULLABLE),
|
||||
])
|
||||
.build(),
|
||||
::cot::db::migrations::Operation::create_model()
|
||||
.table_name(::cot::db::Identifier::new("web_petting__testimonial"))
|
||||
.fields(&[
|
||||
::cot::db::migrations::Field::new(
|
||||
::cot::db::Identifier::new("id"),
|
||||
<cot::db::Auto<i64> as ::cot::db::DatabaseField>::TYPE,
|
||||
)
|
||||
.auto()
|
||||
.primary_key()
|
||||
.set_null(<cot::db::Auto<i64> as ::cot::db::DatabaseField>::NULLABLE),
|
||||
::cot::db::migrations::Field::new(
|
||||
::cot::db::Identifier::new("text"),
|
||||
<String as ::cot::db::DatabaseField>::TYPE,
|
||||
)
|
||||
.set_null(<String as ::cot::db::DatabaseField>::NULLABLE),
|
||||
::cot::db::migrations::Field::new(
|
||||
::cot::db::Identifier::new("author_note"),
|
||||
<Option<String> as ::cot::db::DatabaseField>::TYPE,
|
||||
)
|
||||
.set_null(<Option<String> as ::cot::db::DatabaseField>::NULLABLE),
|
||||
::cot::db::migrations::Field::new(
|
||||
::cot::db::Identifier::new("image_path"),
|
||||
<Option<String> as ::cot::db::DatabaseField>::TYPE,
|
||||
)
|
||||
.set_null(<Option<String> as ::cot::db::DatabaseField>::NULLABLE),
|
||||
::cot::db::migrations::Field::new(
|
||||
::cot::db::Identifier::new("status"),
|
||||
<String as ::cot::db::DatabaseField>::TYPE,
|
||||
)
|
||||
.set_null(<String as ::cot::db::DatabaseField>::NULLABLE),
|
||||
::cot::db::migrations::Field::new(
|
||||
::cot::db::Identifier::new("sort_order"),
|
||||
<i32 as ::cot::db::DatabaseField>::TYPE,
|
||||
)
|
||||
.set_null(<i32 as ::cot::db::DatabaseField>::NULLABLE),
|
||||
::cot::db::migrations::Field::new(
|
||||
::cot::db::Identifier::new("created_at"),
|
||||
<chrono::NaiveDateTime as ::cot::db::DatabaseField>::TYPE,
|
||||
)
|
||||
.set_null(<chrono::NaiveDateTime as ::cot::db::DatabaseField>::NULLABLE),
|
||||
])
|
||||
.build(),
|
||||
::cot::db::migrations::Operation::create_model()
|
||||
.table_name(::cot::db::Identifier::new("web_petting__visit"))
|
||||
.fields(
|
||||
&[
|
||||
::cot::db::migrations::Field::new(
|
||||
::cot::db::Identifier::new("id"),
|
||||
<cot::db::Auto<i64> as ::cot::db::DatabaseField>::TYPE,
|
||||
)
|
||||
.auto()
|
||||
.primary_key()
|
||||
.set_null(
|
||||
<cot::db::Auto<i64> as ::cot::db::DatabaseField>::NULLABLE,
|
||||
),
|
||||
::cot::db::migrations::Field::new(
|
||||
::cot::db::Identifier::new("client_id"),
|
||||
<cot::db::ForeignKey<
|
||||
crate::models::Client,
|
||||
> as ::cot::db::DatabaseField>::TYPE,
|
||||
)
|
||||
.foreign_key(
|
||||
<crate::models::Client as ::cot::db::Model>::TABLE_NAME,
|
||||
<crate::models::Client as ::cot::db::Model>::PRIMARY_KEY_NAME,
|
||||
::cot::db::ForeignKeyOnDeletePolicy::Restrict,
|
||||
::cot::db::ForeignKeyOnUpdatePolicy::Restrict,
|
||||
)
|
||||
.set_null(
|
||||
<cot::db::ForeignKey<
|
||||
crate::models::Client,
|
||||
> as ::cot::db::DatabaseField>::NULLABLE,
|
||||
),
|
||||
::cot::db::migrations::Field::new(
|
||||
::cot::db::Identifier::new("scheduled_at"),
|
||||
<chrono::NaiveDateTime as ::cot::db::DatabaseField>::TYPE,
|
||||
)
|
||||
.set_null(
|
||||
<chrono::NaiveDateTime as ::cot::db::DatabaseField>::NULLABLE,
|
||||
),
|
||||
::cot::db::migrations::Field::new(
|
||||
::cot::db::Identifier::new("duration_minutes"),
|
||||
<Option<i32> as ::cot::db::DatabaseField>::TYPE,
|
||||
)
|
||||
.set_null(<Option<i32> as ::cot::db::DatabaseField>::NULLABLE),
|
||||
::cot::db::migrations::Field::new(
|
||||
::cot::db::Identifier::new("notes"),
|
||||
<Option<String> as ::cot::db::DatabaseField>::TYPE,
|
||||
)
|
||||
.set_null(
|
||||
<Option<String> as ::cot::db::DatabaseField>::NULLABLE,
|
||||
),
|
||||
::cot::db::migrations::Field::new(
|
||||
::cot::db::Identifier::new("status"),
|
||||
<String as ::cot::db::DatabaseField>::TYPE,
|
||||
)
|
||||
.set_null(<String as ::cot::db::DatabaseField>::NULLABLE),
|
||||
::cot::db::migrations::Field::new(
|
||||
::cot::db::Identifier::new("created_at"),
|
||||
<chrono::NaiveDateTime as ::cot::db::DatabaseField>::TYPE,
|
||||
)
|
||||
.set_null(
|
||||
<chrono::NaiveDateTime as ::cot::db::DatabaseField>::NULLABLE,
|
||||
),
|
||||
::cot::db::migrations::Field::new(
|
||||
::cot::db::Identifier::new("updated_at"),
|
||||
<chrono::NaiveDateTime as ::cot::db::DatabaseField>::TYPE,
|
||||
)
|
||||
.set_null(
|
||||
<chrono::NaiveDateTime as ::cot::db::DatabaseField>::NULLABLE,
|
||||
),
|
||||
],
|
||||
)
|
||||
.fields(&[
|
||||
::cot::db::migrations::Field::new(
|
||||
::cot::db::Identifier::new("id"),
|
||||
<cot::db::Auto<i64> as ::cot::db::DatabaseField>::TYPE,
|
||||
)
|
||||
.auto()
|
||||
.primary_key()
|
||||
.set_null(<cot::db::Auto<i64> as ::cot::db::DatabaseField>::NULLABLE),
|
||||
::cot::db::migrations::Field::new(
|
||||
::cot::db::Identifier::new("client_id"),
|
||||
<cot::db::ForeignKey<crate::models::Client> as ::cot::db::DatabaseField>::TYPE,
|
||||
)
|
||||
.foreign_key(
|
||||
<crate::models::Client as ::cot::db::Model>::TABLE_NAME,
|
||||
<crate::models::Client as ::cot::db::Model>::PRIMARY_KEY_NAME,
|
||||
::cot::db::ForeignKeyOnDeletePolicy::Restrict,
|
||||
::cot::db::ForeignKeyOnUpdatePolicy::Restrict,
|
||||
)
|
||||
.set_null(
|
||||
<cot::db::ForeignKey<crate::models::Client> as ::cot::db::DatabaseField>::NULLABLE,
|
||||
),
|
||||
::cot::db::migrations::Field::new(
|
||||
::cot::db::Identifier::new("user_id"),
|
||||
<cot::db::ForeignKey<crate::models::User> as ::cot::db::DatabaseField>::TYPE,
|
||||
)
|
||||
.foreign_key(
|
||||
<crate::models::User as ::cot::db::Model>::TABLE_NAME,
|
||||
<crate::models::User as ::cot::db::Model>::PRIMARY_KEY_NAME,
|
||||
::cot::db::ForeignKeyOnDeletePolicy::Restrict,
|
||||
::cot::db::ForeignKeyOnUpdatePolicy::Restrict,
|
||||
)
|
||||
.set_null(
|
||||
<cot::db::ForeignKey<crate::models::User> as ::cot::db::DatabaseField>::NULLABLE,
|
||||
),
|
||||
::cot::db::migrations::Field::new(
|
||||
::cot::db::Identifier::new("visit_date"),
|
||||
<chrono::NaiveDate as ::cot::db::DatabaseField>::TYPE,
|
||||
)
|
||||
.set_null(<chrono::NaiveDate as ::cot::db::DatabaseField>::NULLABLE),
|
||||
::cot::db::migrations::Field::new(
|
||||
::cot::db::Identifier::new("time_start"),
|
||||
<String as ::cot::db::DatabaseField>::TYPE,
|
||||
)
|
||||
.set_null(<String as ::cot::db::DatabaseField>::NULLABLE),
|
||||
::cot::db::migrations::Field::new(
|
||||
::cot::db::Identifier::new("time_end"),
|
||||
<String as ::cot::db::DatabaseField>::TYPE,
|
||||
)
|
||||
.set_null(<String as ::cot::db::DatabaseField>::NULLABLE),
|
||||
::cot::db::migrations::Field::new(
|
||||
::cot::db::Identifier::new("notes"),
|
||||
<Option<String> as ::cot::db::DatabaseField>::TYPE,
|
||||
)
|
||||
.set_null(<Option<String> as ::cot::db::DatabaseField>::NULLABLE),
|
||||
::cot::db::migrations::Field::new(
|
||||
::cot::db::Identifier::new("public_notes"),
|
||||
<Option<String> as ::cot::db::DatabaseField>::TYPE,
|
||||
)
|
||||
.set_null(<Option<String> as ::cot::db::DatabaseField>::NULLABLE),
|
||||
::cot::db::migrations::Field::new(
|
||||
::cot::db::Identifier::new("client_feedback"),
|
||||
<Option<String> as ::cot::db::DatabaseField>::TYPE,
|
||||
)
|
||||
.set_null(<Option<String> as ::cot::db::DatabaseField>::NULLABLE),
|
||||
::cot::db::migrations::Field::new(
|
||||
::cot::db::Identifier::new("status"),
|
||||
<String as ::cot::db::DatabaseField>::TYPE,
|
||||
)
|
||||
.set_null(<String as ::cot::db::DatabaseField>::NULLABLE),
|
||||
::cot::db::migrations::Field::new(
|
||||
::cot::db::Identifier::new("created_at"),
|
||||
<chrono::NaiveDateTime as ::cot::db::DatabaseField>::TYPE,
|
||||
)
|
||||
.set_null(<chrono::NaiveDateTime as ::cot::db::DatabaseField>::NULLABLE),
|
||||
::cot::db::migrations::Field::new(
|
||||
::cot::db::Identifier::new("updated_at"),
|
||||
<chrono::NaiveDateTime as ::cot::db::DatabaseField>::TYPE,
|
||||
)
|
||||
.set_null(<chrono::NaiveDateTime as ::cot::db::DatabaseField>::NULLABLE),
|
||||
])
|
||||
.build(),
|
||||
::cot::db::migrations::Operation::create_model()
|
||||
.table_name(::cot::db::Identifier::new("web_petting__media"))
|
||||
.fields(
|
||||
&[
|
||||
::cot::db::migrations::Field::new(
|
||||
::cot::db::Identifier::new("id"),
|
||||
<cot::db::Auto<i64> as ::cot::db::DatabaseField>::TYPE,
|
||||
)
|
||||
.auto()
|
||||
.primary_key()
|
||||
.set_null(
|
||||
<cot::db::Auto<i64> as ::cot::db::DatabaseField>::NULLABLE,
|
||||
),
|
||||
::cot::db::migrations::Field::new(
|
||||
::cot::db::Identifier::new("client_id"),
|
||||
<cot::db::ForeignKey<
|
||||
crate::models::Client,
|
||||
> as ::cot::db::DatabaseField>::TYPE,
|
||||
)
|
||||
.foreign_key(
|
||||
<crate::models::Client as ::cot::db::Model>::TABLE_NAME,
|
||||
<crate::models::Client as ::cot::db::Model>::PRIMARY_KEY_NAME,
|
||||
::cot::db::ForeignKeyOnDeletePolicy::Restrict,
|
||||
::cot::db::ForeignKeyOnUpdatePolicy::Restrict,
|
||||
)
|
||||
.set_null(
|
||||
<cot::db::ForeignKey<
|
||||
crate::models::Client,
|
||||
> as ::cot::db::DatabaseField>::NULLABLE,
|
||||
),
|
||||
::cot::db::migrations::Field::new(
|
||||
::cot::db::Identifier::new("visit_id"),
|
||||
<Option<
|
||||
cot::db::ForeignKey<crate::models::Visit>,
|
||||
> as ::cot::db::DatabaseField>::TYPE,
|
||||
)
|
||||
.foreign_key(
|
||||
<crate::models::Visit as ::cot::db::Model>::TABLE_NAME,
|
||||
<crate::models::Visit as ::cot::db::Model>::PRIMARY_KEY_NAME,
|
||||
::cot::db::ForeignKeyOnDeletePolicy::Restrict,
|
||||
::cot::db::ForeignKeyOnUpdatePolicy::Restrict,
|
||||
)
|
||||
.set_null(
|
||||
<Option<
|
||||
cot::db::ForeignKey<crate::models::Visit>,
|
||||
> as ::cot::db::DatabaseField>::NULLABLE,
|
||||
),
|
||||
::cot::db::migrations::Field::new(
|
||||
::cot::db::Identifier::new("file_path"),
|
||||
<String as ::cot::db::DatabaseField>::TYPE,
|
||||
)
|
||||
.set_null(<String as ::cot::db::DatabaseField>::NULLABLE),
|
||||
::cot::db::migrations::Field::new(
|
||||
::cot::db::Identifier::new("file_type"),
|
||||
<String as ::cot::db::DatabaseField>::TYPE,
|
||||
)
|
||||
.set_null(<String as ::cot::db::DatabaseField>::NULLABLE),
|
||||
::cot::db::migrations::Field::new(
|
||||
::cot::db::Identifier::new("caption"),
|
||||
<Option<String> as ::cot::db::DatabaseField>::TYPE,
|
||||
)
|
||||
.set_null(
|
||||
<Option<String> as ::cot::db::DatabaseField>::NULLABLE,
|
||||
),
|
||||
::cot::db::migrations::Field::new(
|
||||
::cot::db::Identifier::new("status"),
|
||||
<String as ::cot::db::DatabaseField>::TYPE,
|
||||
)
|
||||
.set_null(<String as ::cot::db::DatabaseField>::NULLABLE),
|
||||
::cot::db::migrations::Field::new(
|
||||
::cot::db::Identifier::new("created_at"),
|
||||
<chrono::NaiveDateTime as ::cot::db::DatabaseField>::TYPE,
|
||||
)
|
||||
.set_null(
|
||||
<chrono::NaiveDateTime as ::cot::db::DatabaseField>::NULLABLE,
|
||||
),
|
||||
],
|
||||
)
|
||||
.fields(&[
|
||||
::cot::db::migrations::Field::new(
|
||||
::cot::db::Identifier::new("id"),
|
||||
<cot::db::Auto<i64> as ::cot::db::DatabaseField>::TYPE,
|
||||
)
|
||||
.auto()
|
||||
.primary_key()
|
||||
.set_null(<cot::db::Auto<i64> as ::cot::db::DatabaseField>::NULLABLE),
|
||||
::cot::db::migrations::Field::new(
|
||||
::cot::db::Identifier::new("client_id"),
|
||||
<cot::db::ForeignKey<crate::models::Client> as ::cot::db::DatabaseField>::TYPE,
|
||||
)
|
||||
.foreign_key(
|
||||
<crate::models::Client as ::cot::db::Model>::TABLE_NAME,
|
||||
<crate::models::Client as ::cot::db::Model>::PRIMARY_KEY_NAME,
|
||||
::cot::db::ForeignKeyOnDeletePolicy::Restrict,
|
||||
::cot::db::ForeignKeyOnUpdatePolicy::Restrict,
|
||||
)
|
||||
.set_null(
|
||||
<cot::db::ForeignKey<crate::models::Client> as ::cot::db::DatabaseField>::NULLABLE,
|
||||
),
|
||||
::cot::db::migrations::Field::new(
|
||||
::cot::db::Identifier::new("visit_id"),
|
||||
<Option<cot::db::ForeignKey<crate::models::Visit>> as ::cot::db::DatabaseField>::TYPE,
|
||||
)
|
||||
.foreign_key(
|
||||
<crate::models::Visit as ::cot::db::Model>::TABLE_NAME,
|
||||
<crate::models::Visit as ::cot::db::Model>::PRIMARY_KEY_NAME,
|
||||
::cot::db::ForeignKeyOnDeletePolicy::Restrict,
|
||||
::cot::db::ForeignKeyOnUpdatePolicy::Restrict,
|
||||
)
|
||||
.set_null(
|
||||
<Option<cot::db::ForeignKey<crate::models::Visit>> as ::cot::db::DatabaseField>::NULLABLE,
|
||||
),
|
||||
::cot::db::migrations::Field::new(
|
||||
::cot::db::Identifier::new("file_path"),
|
||||
<String as ::cot::db::DatabaseField>::TYPE,
|
||||
)
|
||||
.set_null(<String as ::cot::db::DatabaseField>::NULLABLE),
|
||||
::cot::db::migrations::Field::new(
|
||||
::cot::db::Identifier::new("file_type"),
|
||||
<String as ::cot::db::DatabaseField>::TYPE,
|
||||
)
|
||||
.set_null(<String as ::cot::db::DatabaseField>::NULLABLE),
|
||||
::cot::db::migrations::Field::new(
|
||||
::cot::db::Identifier::new("caption"),
|
||||
<Option<String> as ::cot::db::DatabaseField>::TYPE,
|
||||
)
|
||||
.set_null(<Option<String> as ::cot::db::DatabaseField>::NULLABLE),
|
||||
::cot::db::migrations::Field::new(
|
||||
::cot::db::Identifier::new("status"),
|
||||
<String as ::cot::db::DatabaseField>::TYPE,
|
||||
)
|
||||
.set_null(<String as ::cot::db::DatabaseField>::NULLABLE),
|
||||
::cot::db::migrations::Field::new(
|
||||
::cot::db::Identifier::new("created_at"),
|
||||
<chrono::NaiveDateTime as ::cot::db::DatabaseField>::TYPE,
|
||||
)
|
||||
.set_null(<chrono::NaiveDateTime as ::cot::db::DatabaseField>::NULLABLE),
|
||||
])
|
||||
.build(),
|
||||
::cot::db::migrations::Operation::create_model()
|
||||
.table_name(::cot::db::Identifier::new("web_petting__lead"))
|
||||
.fields(
|
||||
&[
|
||||
::cot::db::migrations::Field::new(
|
||||
::cot::db::Identifier::new("id"),
|
||||
<cot::db::Auto<i64> as ::cot::db::DatabaseField>::TYPE,
|
||||
)
|
||||
.auto()
|
||||
.primary_key()
|
||||
.set_null(
|
||||
<cot::db::Auto<i64> as ::cot::db::DatabaseField>::NULLABLE,
|
||||
),
|
||||
::cot::db::migrations::Field::new(
|
||||
::cot::db::Identifier::new("name"),
|
||||
<String as ::cot::db::DatabaseField>::TYPE,
|
||||
)
|
||||
.set_null(<String as ::cot::db::DatabaseField>::NULLABLE),
|
||||
::cot::db::migrations::Field::new(
|
||||
::cot::db::Identifier::new("phone"),
|
||||
<Option<String> as ::cot::db::DatabaseField>::TYPE,
|
||||
)
|
||||
.set_null(
|
||||
<Option<String> as ::cot::db::DatabaseField>::NULLABLE,
|
||||
),
|
||||
::cot::db::migrations::Field::new(
|
||||
::cot::db::Identifier::new("email"),
|
||||
<Option<String> as ::cot::db::DatabaseField>::TYPE,
|
||||
)
|
||||
.set_null(
|
||||
<Option<String> as ::cot::db::DatabaseField>::NULLABLE,
|
||||
),
|
||||
::cot::db::migrations::Field::new(
|
||||
::cot::db::Identifier::new("comment"),
|
||||
<Option<String> as ::cot::db::DatabaseField>::TYPE,
|
||||
)
|
||||
.set_null(
|
||||
<Option<String> as ::cot::db::DatabaseField>::NULLABLE,
|
||||
),
|
||||
::cot::db::migrations::Field::new(
|
||||
::cot::db::Identifier::new("status"),
|
||||
<String as ::cot::db::DatabaseField>::TYPE,
|
||||
)
|
||||
.set_null(<String as ::cot::db::DatabaseField>::NULLABLE),
|
||||
::cot::db::migrations::Field::new(
|
||||
::cot::db::Identifier::new("client_id"),
|
||||
<Option<
|
||||
cot::db::ForeignKey<crate::models::Client>,
|
||||
> as ::cot::db::DatabaseField>::TYPE,
|
||||
)
|
||||
.foreign_key(
|
||||
<crate::models::Client as ::cot::db::Model>::TABLE_NAME,
|
||||
<crate::models::Client as ::cot::db::Model>::PRIMARY_KEY_NAME,
|
||||
::cot::db::ForeignKeyOnDeletePolicy::Restrict,
|
||||
::cot::db::ForeignKeyOnUpdatePolicy::Restrict,
|
||||
)
|
||||
.set_null(
|
||||
<Option<
|
||||
cot::db::ForeignKey<crate::models::Client>,
|
||||
> as ::cot::db::DatabaseField>::NULLABLE,
|
||||
),
|
||||
::cot::db::migrations::Field::new(
|
||||
::cot::db::Identifier::new("created_at"),
|
||||
<chrono::NaiveDateTime as ::cot::db::DatabaseField>::TYPE,
|
||||
)
|
||||
.set_null(
|
||||
<chrono::NaiveDateTime as ::cot::db::DatabaseField>::NULLABLE,
|
||||
),
|
||||
::cot::db::migrations::Field::new(
|
||||
::cot::db::Identifier::new("updated_at"),
|
||||
<chrono::NaiveDateTime as ::cot::db::DatabaseField>::TYPE,
|
||||
)
|
||||
.set_null(
|
||||
<chrono::NaiveDateTime as ::cot::db::DatabaseField>::NULLABLE,
|
||||
),
|
||||
],
|
||||
)
|
||||
.fields(&[
|
||||
::cot::db::migrations::Field::new(
|
||||
::cot::db::Identifier::new("id"),
|
||||
<cot::db::Auto<i64> as ::cot::db::DatabaseField>::TYPE,
|
||||
)
|
||||
.auto()
|
||||
.primary_key()
|
||||
.set_null(<cot::db::Auto<i64> as ::cot::db::DatabaseField>::NULLABLE),
|
||||
::cot::db::migrations::Field::new(
|
||||
::cot::db::Identifier::new("name"),
|
||||
<String as ::cot::db::DatabaseField>::TYPE,
|
||||
)
|
||||
.set_null(<String as ::cot::db::DatabaseField>::NULLABLE),
|
||||
::cot::db::migrations::Field::new(
|
||||
::cot::db::Identifier::new("phone"),
|
||||
<Option<String> as ::cot::db::DatabaseField>::TYPE,
|
||||
)
|
||||
.set_null(<Option<String> as ::cot::db::DatabaseField>::NULLABLE),
|
||||
::cot::db::migrations::Field::new(
|
||||
::cot::db::Identifier::new("email"),
|
||||
<Option<String> as ::cot::db::DatabaseField>::TYPE,
|
||||
)
|
||||
.set_null(<Option<String> as ::cot::db::DatabaseField>::NULLABLE),
|
||||
::cot::db::migrations::Field::new(
|
||||
::cot::db::Identifier::new("comment"),
|
||||
<Option<String> as ::cot::db::DatabaseField>::TYPE,
|
||||
)
|
||||
.set_null(<Option<String> as ::cot::db::DatabaseField>::NULLABLE),
|
||||
::cot::db::migrations::Field::new(
|
||||
::cot::db::Identifier::new("status"),
|
||||
<String as ::cot::db::DatabaseField>::TYPE,
|
||||
)
|
||||
.set_null(<String as ::cot::db::DatabaseField>::NULLABLE),
|
||||
::cot::db::migrations::Field::new(
|
||||
::cot::db::Identifier::new("client_id"),
|
||||
<Option<cot::db::ForeignKey<crate::models::Client>> as ::cot::db::DatabaseField>::TYPE,
|
||||
)
|
||||
.foreign_key(
|
||||
<crate::models::Client as ::cot::db::Model>::TABLE_NAME,
|
||||
<crate::models::Client as ::cot::db::Model>::PRIMARY_KEY_NAME,
|
||||
::cot::db::ForeignKeyOnDeletePolicy::Restrict,
|
||||
::cot::db::ForeignKeyOnUpdatePolicy::Restrict,
|
||||
)
|
||||
.set_null(
|
||||
<Option<cot::db::ForeignKey<crate::models::Client>> as ::cot::db::DatabaseField>::NULLABLE,
|
||||
),
|
||||
::cot::db::migrations::Field::new(
|
||||
::cot::db::Identifier::new("created_at"),
|
||||
<chrono::NaiveDateTime as ::cot::db::DatabaseField>::TYPE,
|
||||
)
|
||||
.set_null(<chrono::NaiveDateTime as ::cot::db::DatabaseField>::NULLABLE),
|
||||
::cot::db::migrations::Field::new(
|
||||
::cot::db::Identifier::new("updated_at"),
|
||||
<chrono::NaiveDateTime as ::cot::db::DatabaseField>::TYPE,
|
||||
)
|
||||
.set_null(<chrono::NaiveDateTime as ::cot::db::DatabaseField>::NULLABLE),
|
||||
])
|
||||
.build(),
|
||||
];
|
||||
}
|
||||
|
||||
#[derive(::core::fmt::Debug)]
|
||||
#[::cot::db::model(model_type = "migration")]
|
||||
struct _Client {
|
||||
#[model(primary_key)]
|
||||
pub id: cot::db::Auto<i64>,
|
||||
pub name: String,
|
||||
pub phone: Option<String>,
|
||||
pub email: Option<String>,
|
||||
pub address: Option<String>,
|
||||
pub notes: Option<String>,
|
||||
/// Unique token for the public media page (client views photos/videos here).
|
||||
#[model(unique)]
|
||||
pub media_token: String,
|
||||
/// active | archived
|
||||
pub status: String,
|
||||
pub created_at: chrono::NaiveDateTime,
|
||||
pub updated_at: chrono::NaiveDateTime,
|
||||
}
|
||||
#[derive(::core::fmt::Debug)]
|
||||
#[::cot::db::model(model_type = "migration")]
|
||||
struct _Lead {
|
||||
#[model(primary_key)]
|
||||
pub id: cot::db::Auto<i64>,
|
||||
pub name: String,
|
||||
pub phone: Option<String>,
|
||||
pub email: Option<String>,
|
||||
pub comment: Option<String>,
|
||||
/// new | in_progress | converted | rejected
|
||||
pub status: String,
|
||||
pub client_id: Option<cot::db::ForeignKey<crate::models::Client>>,
|
||||
pub created_at: chrono::NaiveDateTime,
|
||||
pub updated_at: chrono::NaiveDateTime,
|
||||
}
|
||||
#[derive(::core::fmt::Debug)]
|
||||
#[::cot::db::model(model_type = "migration")]
|
||||
struct _Media {
|
||||
#[model(primary_key)]
|
||||
pub id: cot::db::Auto<i64>,
|
||||
pub client_id: cot::db::ForeignKey<crate::models::Client>,
|
||||
pub visit_id: Option<cot::db::ForeignKey<crate::models::Visit>>,
|
||||
pub file_path: String,
|
||||
/// photo | video
|
||||
pub file_type: String,
|
||||
pub caption: Option<String>,
|
||||
/// active | archived
|
||||
pub status: String,
|
||||
pub created_at: chrono::NaiveDateTime,
|
||||
}
|
||||
#[derive(::core::fmt::Debug)]
|
||||
#[::cot::db::model(model_type = "migration")]
|
||||
struct _Setting {
|
||||
#[model(primary_key)]
|
||||
pub id: cot::db::Auto<i64>,
|
||||
#[model(unique)]
|
||||
pub key: String,
|
||||
pub value: String,
|
||||
pub updated_at: chrono::NaiveDateTime,
|
||||
}
|
||||
#[derive(::core::fmt::Debug)]
|
||||
#[::cot::db::model(model_type = "migration")]
|
||||
struct _User {
|
||||
#[model(primary_key)]
|
||||
pub id: cot::db::Auto<i64>,
|
||||
#[model(unique)]
|
||||
pub login: String,
|
||||
pub password_hash: String,
|
||||
pub display_name: Option<String>,
|
||||
/// active | archived
|
||||
pub status: String,
|
||||
pub created_at: chrono::NaiveDateTime,
|
||||
pub updated_at: chrono::NaiveDateTime,
|
||||
}
|
||||
#[derive(::core::fmt::Debug)]
|
||||
#[::cot::db::model(model_type = "migration")]
|
||||
struct _Visit {
|
||||
#[model(primary_key)]
|
||||
pub id: cot::db::Auto<i64>,
|
||||
pub client_id: cot::db::ForeignKey<crate::models::Client>,
|
||||
pub scheduled_at: chrono::NaiveDateTime,
|
||||
pub duration_minutes: Option<i32>,
|
||||
pub notes: Option<String>,
|
||||
/// scheduled | completed | cancelled
|
||||
pub status: String,
|
||||
pub created_at: chrono::NaiveDateTime,
|
||||
pub updated_at: chrono::NaiveDateTime,
|
||||
}
|
||||
|
||||
@@ -0,0 +1,67 @@
|
||||
//! Store browser Web Push subscriptions for client devices.
|
||||
|
||||
#[derive(Debug, Copy, Clone)]
|
||||
pub(super) struct Migration;
|
||||
|
||||
impl ::cot::db::migrations::Migration for Migration {
|
||||
const APP_NAME: &'static str = "web-petting";
|
||||
const MIGRATION_NAME: &'static str = "m_0002_push_subscription";
|
||||
const DEPENDENCIES: &'static [::cot::db::migrations::MigrationDependency] =
|
||||
&[::cot::db::migrations::MigrationDependency::migration(
|
||||
"web-petting",
|
||||
"m_0001_initial",
|
||||
)];
|
||||
const OPERATIONS: &'static [::cot::db::migrations::Operation] = &[
|
||||
::cot::db::migrations::Operation::create_model()
|
||||
.table_name(::cot::db::Identifier::new("web_petting__push_subscription"))
|
||||
.fields(&[
|
||||
::cot::db::migrations::Field::new(
|
||||
::cot::db::Identifier::new("id"),
|
||||
<cot::db::Auto<i64> as ::cot::db::DatabaseField>::TYPE,
|
||||
)
|
||||
.auto()
|
||||
.primary_key()
|
||||
.set_null(<cot::db::Auto<i64> as ::cot::db::DatabaseField>::NULLABLE),
|
||||
::cot::db::migrations::Field::new(
|
||||
::cot::db::Identifier::new("client_id"),
|
||||
<cot::db::ForeignKey<crate::models::Client> as ::cot::db::DatabaseField>::TYPE,
|
||||
)
|
||||
.foreign_key(
|
||||
<crate::models::Client as ::cot::db::Model>::TABLE_NAME,
|
||||
<crate::models::Client as ::cot::db::Model>::PRIMARY_KEY_NAME,
|
||||
::cot::db::ForeignKeyOnDeletePolicy::Restrict,
|
||||
::cot::db::ForeignKeyOnUpdatePolicy::Restrict,
|
||||
)
|
||||
.set_null(<cot::db::ForeignKey<crate::models::Client> as ::cot::db::DatabaseField>::NULLABLE),
|
||||
::cot::db::migrations::Field::new(
|
||||
::cot::db::Identifier::new("endpoint"),
|
||||
<String as ::cot::db::DatabaseField>::TYPE,
|
||||
).set_null(false).unique(),
|
||||
::cot::db::migrations::Field::new(
|
||||
::cot::db::Identifier::new("p256dh"),
|
||||
<String as ::cot::db::DatabaseField>::TYPE,
|
||||
).set_null(false),
|
||||
::cot::db::migrations::Field::new(
|
||||
::cot::db::Identifier::new("auth"),
|
||||
<String as ::cot::db::DatabaseField>::TYPE,
|
||||
).set_null(false),
|
||||
::cot::db::migrations::Field::new(
|
||||
::cot::db::Identifier::new("language"),
|
||||
<String as ::cot::db::DatabaseField>::TYPE,
|
||||
).set_null(false),
|
||||
::cot::db::migrations::Field::new(
|
||||
::cot::db::Identifier::new("status"),
|
||||
<String as ::cot::db::DatabaseField>::TYPE,
|
||||
).set_null(false),
|
||||
::cot::db::migrations::Field::new(
|
||||
::cot::db::Identifier::new("created_at"),
|
||||
<chrono::NaiveDateTime as ::cot::db::DatabaseField>::TYPE,
|
||||
).set_null(false),
|
||||
::cot::db::migrations::Field::new(
|
||||
::cot::db::Identifier::new("updated_at"),
|
||||
<chrono::NaiveDateTime as ::cot::db::DatabaseField>::TYPE,
|
||||
).set_null(false),
|
||||
])
|
||||
.build(),
|
||||
];
|
||||
}
|
||||
@@ -1,90 +0,0 @@
|
||||
//! Migration: update Visit model for scheduling + add Client.color
|
||||
//! Visit: Remove scheduled_at, duration_minutes; Add user_id, visit_date, time_start, time_end
|
||||
//! Client: Add color
|
||||
|
||||
#[derive(Debug, Copy, Clone)]
|
||||
pub(super) struct Migration;
|
||||
impl ::cot::db::migrations::Migration for Migration {
|
||||
const APP_NAME: &'static str = "web-petting";
|
||||
const MIGRATION_NAME: &'static str = "m_0002_visit_schedule";
|
||||
const DEPENDENCIES: &'static [::cot::db::migrations::MigrationDependency] =
|
||||
&[::cot::db::migrations::MigrationDependency::migration(
|
||||
"web-petting",
|
||||
"m_0001_initial",
|
||||
)];
|
||||
const OPERATIONS: &'static [::cot::db::migrations::Operation] = &[
|
||||
// Add color to client (nullable for existing rows)
|
||||
::cot::db::migrations::Operation::add_field()
|
||||
.table_name(::cot::db::Identifier::new("web_petting__client"))
|
||||
.field(
|
||||
::cot::db::migrations::Field::new(
|
||||
::cot::db::Identifier::new("color"),
|
||||
<Option<String> as ::cot::db::DatabaseField>::TYPE,
|
||||
)
|
||||
.set_null(<Option<String> as ::cot::db::DatabaseField>::NULLABLE)
|
||||
)
|
||||
.build(),
|
||||
// Remove old visit fields
|
||||
::cot::db::migrations::Operation::remove_field()
|
||||
.table_name(::cot::db::Identifier::new("web_petting__visit"))
|
||||
.field(::cot::db::migrations::Field::new(
|
||||
::cot::db::Identifier::new("scheduled_at"),
|
||||
<chrono::NaiveDateTime as ::cot::db::DatabaseField>::TYPE,
|
||||
))
|
||||
.build(),
|
||||
::cot::db::migrations::Operation::remove_field()
|
||||
.table_name(::cot::db::Identifier::new("web_petting__visit"))
|
||||
.field(::cot::db::migrations::Field::new(
|
||||
::cot::db::Identifier::new("duration_minutes"),
|
||||
<Option<i32> as ::cot::db::DatabaseField>::TYPE,
|
||||
).set_null(<Option<i32> as ::cot::db::DatabaseField>::NULLABLE))
|
||||
.build(),
|
||||
// Add new fields
|
||||
::cot::db::migrations::Operation::add_field()
|
||||
.table_name(::cot::db::Identifier::new("web_petting__visit"))
|
||||
.field(
|
||||
::cot::db::migrations::Field::new(
|
||||
::cot::db::Identifier::new("user_id"),
|
||||
<cot::db::ForeignKey<crate::models::User> as ::cot::db::DatabaseField>::TYPE,
|
||||
)
|
||||
.foreign_key(
|
||||
<crate::models::User as ::cot::db::Model>::TABLE_NAME,
|
||||
<crate::models::User as ::cot::db::Model>::PRIMARY_KEY_NAME,
|
||||
::cot::db::ForeignKeyOnDeletePolicy::Restrict,
|
||||
::cot::db::ForeignKeyOnUpdatePolicy::Restrict,
|
||||
)
|
||||
.set_null(<cot::db::ForeignKey<crate::models::User> as ::cot::db::DatabaseField>::NULLABLE)
|
||||
)
|
||||
.build(),
|
||||
::cot::db::migrations::Operation::add_field()
|
||||
.table_name(::cot::db::Identifier::new("web_petting__visit"))
|
||||
.field(
|
||||
::cot::db::migrations::Field::new(
|
||||
::cot::db::Identifier::new("visit_date"),
|
||||
<chrono::NaiveDate as ::cot::db::DatabaseField>::TYPE,
|
||||
)
|
||||
.set_null(<chrono::NaiveDate as ::cot::db::DatabaseField>::NULLABLE)
|
||||
)
|
||||
.build(),
|
||||
::cot::db::migrations::Operation::add_field()
|
||||
.table_name(::cot::db::Identifier::new("web_petting__visit"))
|
||||
.field(
|
||||
::cot::db::migrations::Field::new(
|
||||
::cot::db::Identifier::new("time_start"),
|
||||
<String as ::cot::db::DatabaseField>::TYPE,
|
||||
)
|
||||
.set_null(<String as ::cot::db::DatabaseField>::NULLABLE)
|
||||
)
|
||||
.build(),
|
||||
::cot::db::migrations::Operation::add_field()
|
||||
.table_name(::cot::db::Identifier::new("web_petting__visit"))
|
||||
.field(
|
||||
::cot::db::migrations::Field::new(
|
||||
::cot::db::Identifier::new("time_end"),
|
||||
<String as ::cot::db::DatabaseField>::TYPE,
|
||||
)
|
||||
.set_null(<String as ::cot::db::DatabaseField>::NULLABLE)
|
||||
)
|
||||
.build(),
|
||||
];
|
||||
}
|
||||
@@ -1,24 +0,0 @@
|
||||
//! Migration: add client_feedback to Visit
|
||||
|
||||
#[derive(Debug, Copy, Clone)]
|
||||
pub(super) struct Migration;
|
||||
impl ::cot::db::migrations::Migration for Migration {
|
||||
const APP_NAME: &'static str = "web-petting";
|
||||
const MIGRATION_NAME: &'static str = "m_0003_visit_feedback";
|
||||
const DEPENDENCIES: &'static [::cot::db::migrations::MigrationDependency] =
|
||||
&[::cot::db::migrations::MigrationDependency::migration(
|
||||
"web-petting",
|
||||
"m_0002_visit_schedule",
|
||||
)];
|
||||
const OPERATIONS: &'static [::cot::db::migrations::Operation] =
|
||||
&[::cot::db::migrations::Operation::add_field()
|
||||
.table_name(::cot::db::Identifier::new("web_petting__visit"))
|
||||
.field(
|
||||
::cot::db::migrations::Field::new(
|
||||
::cot::db::Identifier::new("client_feedback"),
|
||||
<Option<String> as ::cot::db::DatabaseField>::TYPE,
|
||||
)
|
||||
.set_null(<Option<String> as ::cot::db::DatabaseField>::NULLABLE),
|
||||
)
|
||||
.build()];
|
||||
}
|
||||
@@ -1,24 +0,0 @@
|
||||
//! Migration: add public_notes to Visit
|
||||
|
||||
#[derive(Debug, Copy, Clone)]
|
||||
pub(super) struct Migration;
|
||||
impl ::cot::db::migrations::Migration for Migration {
|
||||
const APP_NAME: &'static str = "web-petting";
|
||||
const MIGRATION_NAME: &'static str = "m_0004_visit_public_notes";
|
||||
const DEPENDENCIES: &'static [::cot::db::migrations::MigrationDependency] =
|
||||
&[::cot::db::migrations::MigrationDependency::migration(
|
||||
"web-petting",
|
||||
"m_0003_visit_feedback",
|
||||
)];
|
||||
const OPERATIONS: &'static [::cot::db::migrations::Operation] =
|
||||
&[::cot::db::migrations::Operation::add_field()
|
||||
.table_name(::cot::db::Identifier::new("web_petting__visit"))
|
||||
.field(
|
||||
::cot::db::migrations::Field::new(
|
||||
::cot::db::Identifier::new("public_notes"),
|
||||
<Option<String> as ::cot::db::DatabaseField>::TYPE,
|
||||
)
|
||||
.set_null(<Option<String> as ::cot::db::DatabaseField>::NULLABLE),
|
||||
)
|
||||
.build()];
|
||||
}
|
||||
@@ -1,56 +0,0 @@
|
||||
//! Migration: create Testimonial table
|
||||
|
||||
#[derive(Debug, Copy, Clone)]
|
||||
pub(super) struct Migration;
|
||||
impl ::cot::db::migrations::Migration for Migration {
|
||||
const APP_NAME: &'static str = "web-petting";
|
||||
const MIGRATION_NAME: &'static str = "m_0005_testimonials";
|
||||
const DEPENDENCIES: &'static [::cot::db::migrations::MigrationDependency] =
|
||||
&[::cot::db::migrations::MigrationDependency::migration(
|
||||
"web-petting",
|
||||
"m_0004_visit_public_notes",
|
||||
)];
|
||||
const OPERATIONS: &'static [::cot::db::migrations::Operation] =
|
||||
&[::cot::db::migrations::Operation::create_model()
|
||||
.table_name(::cot::db::Identifier::new("web_petting__testimonial"))
|
||||
.fields(&[
|
||||
::cot::db::migrations::Field::new(
|
||||
::cot::db::Identifier::new("id"),
|
||||
<cot::db::Auto<i64> as ::cot::db::DatabaseField>::TYPE,
|
||||
)
|
||||
.auto()
|
||||
.primary_key()
|
||||
.set_null(<cot::db::Auto<i64> as ::cot::db::DatabaseField>::NULLABLE),
|
||||
::cot::db::migrations::Field::new(
|
||||
::cot::db::Identifier::new("text"),
|
||||
<String as ::cot::db::DatabaseField>::TYPE,
|
||||
)
|
||||
.set_null(<String as ::cot::db::DatabaseField>::NULLABLE),
|
||||
::cot::db::migrations::Field::new(
|
||||
::cot::db::Identifier::new("author_note"),
|
||||
<Option<String> as ::cot::db::DatabaseField>::TYPE,
|
||||
)
|
||||
.set_null(<Option<String> as ::cot::db::DatabaseField>::NULLABLE),
|
||||
::cot::db::migrations::Field::new(
|
||||
::cot::db::Identifier::new("image_path"),
|
||||
<Option<String> as ::cot::db::DatabaseField>::TYPE,
|
||||
)
|
||||
.set_null(<Option<String> as ::cot::db::DatabaseField>::NULLABLE),
|
||||
::cot::db::migrations::Field::new(
|
||||
::cot::db::Identifier::new("status"),
|
||||
<String as ::cot::db::DatabaseField>::TYPE,
|
||||
)
|
||||
.set_null(<String as ::cot::db::DatabaseField>::NULLABLE),
|
||||
::cot::db::migrations::Field::new(
|
||||
::cot::db::Identifier::new("sort_order"),
|
||||
<i32 as ::cot::db::DatabaseField>::TYPE,
|
||||
)
|
||||
.set_null(<i32 as ::cot::db::DatabaseField>::NULLABLE),
|
||||
::cot::db::migrations::Field::new(
|
||||
::cot::db::Identifier::new("created_at"),
|
||||
<chrono::NaiveDateTime as ::cot::db::DatabaseField>::TYPE,
|
||||
)
|
||||
.set_null(<chrono::NaiveDateTime as ::cot::db::DatabaseField>::NULLABLE),
|
||||
])
|
||||
.build()];
|
||||
}
|
||||
+23
-1
@@ -43,6 +43,7 @@ pub enum VisitStatus {
|
||||
Scheduled,
|
||||
Completed,
|
||||
Cancelled,
|
||||
Deleted,
|
||||
}
|
||||
|
||||
impl VisitStatus {
|
||||
@@ -51,6 +52,7 @@ impl VisitStatus {
|
||||
Self::Scheduled => "scheduled",
|
||||
Self::Completed => "completed",
|
||||
Self::Cancelled => "cancelled",
|
||||
Self::Deleted => "deleted",
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -146,7 +148,7 @@ pub struct Visit {
|
||||
pub public_notes: Option<String>,
|
||||
/// Feedback text from client via portal.
|
||||
pub client_feedback: Option<String>,
|
||||
/// scheduled | completed | cancelled
|
||||
/// scheduled | completed | cancelled | deleted
|
||||
pub status: String,
|
||||
pub created_at: chrono::NaiveDateTime,
|
||||
pub updated_at: chrono::NaiveDateTime,
|
||||
@@ -179,6 +181,8 @@ pub struct User {
|
||||
pub login: String,
|
||||
pub password_hash: String,
|
||||
pub display_name: Option<String>,
|
||||
pub telegram_chat_id: Option<String>,
|
||||
pub telegram_notifications: Option<bool>,
|
||||
/// active | archived
|
||||
pub status: String,
|
||||
pub created_at: chrono::NaiveDateTime,
|
||||
@@ -213,3 +217,21 @@ pub struct Setting {
|
||||
pub value: String,
|
||||
pub updated_at: chrono::NaiveDateTime,
|
||||
}
|
||||
|
||||
/// A browser Web Push subscription belonging to a client device.
|
||||
#[derive(Debug, Clone)]
|
||||
#[model]
|
||||
pub struct PushSubscription {
|
||||
#[model(primary_key)]
|
||||
pub id: Auto<i64>,
|
||||
pub client_id: ForeignKey<Client>,
|
||||
#[model(unique)]
|
||||
pub endpoint: String,
|
||||
pub p256dh: String,
|
||||
pub auth: String,
|
||||
pub language: String,
|
||||
/// active | archived
|
||||
pub status: String,
|
||||
pub created_at: chrono::NaiveDateTime,
|
||||
pub updated_at: chrono::NaiveDateTime,
|
||||
}
|
||||
|
||||
+681
-39
@@ -1,16 +1,18 @@
|
||||
use chrono::Datelike;
|
||||
use cot::Template;
|
||||
use cot::db::{Auto, Database, Model};
|
||||
use cot::db::{Auto, Database, ForeignKey, Model};
|
||||
use cot::html::Html;
|
||||
use cot::request::Request;
|
||||
use cot::request::extractors::Path;
|
||||
use cot::response::{IntoResponse, Redirect, Response};
|
||||
use cot::router::{Route, Router};
|
||||
use serde::Deserialize;
|
||||
use tracing::info;
|
||||
|
||||
use cot::db::query;
|
||||
|
||||
use crate::i18n::{Lang, Translations};
|
||||
use crate::models::{Client, Lead, Media, Setting, Testimonial, User, Visit};
|
||||
use crate::models::{Client, Lead, Media, PushSubscription, Setting, Testimonial, User, Visit};
|
||||
use crate::telegram;
|
||||
|
||||
fn detect_lang(request: &Request) -> Lang {
|
||||
@@ -60,7 +62,7 @@ fn html_response(body: String, lang: Lang) -> cot::Result<Response> {
|
||||
.into_response()
|
||||
}
|
||||
|
||||
fn now() -> chrono::NaiveDateTime {
|
||||
fn now_utc() -> chrono::NaiveDateTime {
|
||||
chrono::Utc::now().naive_utc()
|
||||
}
|
||||
|
||||
@@ -71,7 +73,11 @@ struct LandingTemplate<'a> {
|
||||
lang: Lang,
|
||||
contact_info: String,
|
||||
pricing_info: String,
|
||||
seo_keywords: String,
|
||||
testimonials: Vec<Testimonial>,
|
||||
site_domain: String,
|
||||
review_count: usize,
|
||||
turnstile_site_key: String,
|
||||
}
|
||||
|
||||
#[derive(Debug, Template)]
|
||||
@@ -83,6 +89,33 @@ struct ThankYouTemplate<'a> {
|
||||
|
||||
async fn landing_page(request: Request, db: Database) -> cot::Result<Response> {
|
||||
let lang = detect_lang(&request);
|
||||
|
||||
let ua = request
|
||||
.headers()
|
||||
.get("user-agent")
|
||||
.and_then(|v| v.to_str().ok())
|
||||
.unwrap_or("-");
|
||||
let referer = request
|
||||
.headers()
|
||||
.get("referer")
|
||||
.and_then(|v| v.to_str().ok())
|
||||
.unwrap_or("-");
|
||||
let ip = request
|
||||
.headers()
|
||||
.get("x-forwarded-for")
|
||||
.and_then(|v| v.to_str().ok())
|
||||
.and_then(|s| s.split(',').next())
|
||||
.map(|s| s.trim())
|
||||
.unwrap_or("-");
|
||||
|
||||
info!(
|
||||
target: "landing",
|
||||
ip = ip,
|
||||
lang = lang.code(),
|
||||
referer = referer,
|
||||
ua = ua,
|
||||
"landing visit"
|
||||
);
|
||||
let key = "contact_info".to_string();
|
||||
let contact_info = query!(Setting, $key == key)
|
||||
.get(&db)
|
||||
@@ -95,15 +128,33 @@ async fn landing_page(request: Request, db: Database) -> cot::Result<Response> {
|
||||
.await?
|
||||
.map(|s| s.value)
|
||||
.unwrap_or_default();
|
||||
let domain_key = "site_domain".to_string();
|
||||
let site_domain = query!(Setting, $key == domain_key)
|
||||
.get(&db)
|
||||
.await?
|
||||
.map(|s| s.value)
|
||||
.unwrap_or_else(|| "https://example.net".to_string());
|
||||
let seo_key = "seo_keywords".to_string();
|
||||
let seo_keywords = query!(Setting, $key == seo_key)
|
||||
.get(&db)
|
||||
.await?
|
||||
.map(|s| s.value)
|
||||
.unwrap_or_default();
|
||||
let turnstile_site_key = crate::turnstile::get_site_key(&db).await?;
|
||||
let mut testimonials = Testimonial::objects().all(&db).await?;
|
||||
testimonials.retain(|t| t.status == "active");
|
||||
testimonials.sort_by(|a, b| a.sort_order.cmp(&b.sort_order));
|
||||
let review_count = testimonials.len();
|
||||
let body = LandingTemplate {
|
||||
t: lang.t(),
|
||||
lang,
|
||||
contact_info,
|
||||
pricing_info,
|
||||
seo_keywords,
|
||||
testimonials,
|
||||
site_domain,
|
||||
review_count,
|
||||
turnstile_site_key,
|
||||
}
|
||||
.render()?;
|
||||
html_response(body, lang)
|
||||
@@ -114,6 +165,8 @@ struct LeadForm {
|
||||
name: String,
|
||||
phone: Option<String>,
|
||||
comment: Option<String>,
|
||||
#[serde(default, rename = "cf-turnstile-response")]
|
||||
cf_turnstile_response: Option<String>,
|
||||
}
|
||||
|
||||
async fn submit_lead(request: Request, db: Database) -> cot::Result<Response> {
|
||||
@@ -123,6 +176,10 @@ async fn submit_lead(request: Request, db: Database) -> cot::Result<Response> {
|
||||
let form: LeadForm =
|
||||
serde_html_form::from_bytes(&bytes).map_err(|e| cot::Error::internal(e.to_string()))?;
|
||||
|
||||
if !crate::turnstile::verify(&db, form.cf_turnstile_response.as_deref()).await? {
|
||||
return Redirect::new(format!("/?lang={}", lang.code())).into_response();
|
||||
}
|
||||
|
||||
let mut lead = Lead {
|
||||
id: Auto::auto(),
|
||||
name: form.name,
|
||||
@@ -131,8 +188,8 @@ async fn submit_lead(request: Request, db: Database) -> cot::Result<Response> {
|
||||
comment: form.comment.filter(|s| !s.trim().is_empty()),
|
||||
status: "new".to_string(),
|
||||
client_id: None,
|
||||
created_at: now(),
|
||||
updated_at: now(),
|
||||
created_at: now_utc(),
|
||||
updated_at: now_utc(),
|
||||
};
|
||||
lead.save(&db).await?;
|
||||
|
||||
@@ -159,6 +216,21 @@ struct PortalVisit {
|
||||
media: Vec<Media>,
|
||||
}
|
||||
|
||||
#[derive(Debug)]
|
||||
struct CalendarDay {
|
||||
number: u32,
|
||||
class_name: &'static str,
|
||||
href: Option<String>,
|
||||
title: String,
|
||||
}
|
||||
|
||||
#[derive(Debug)]
|
||||
struct CalendarMonth {
|
||||
label: String,
|
||||
leading_blanks: Vec<u8>,
|
||||
days: Vec<CalendarDay>,
|
||||
}
|
||||
|
||||
#[derive(Debug, Template)]
|
||||
#[template(path = "client_portal.html")]
|
||||
struct ClientPortalTemplate<'a> {
|
||||
@@ -168,6 +240,63 @@ struct ClientPortalTemplate<'a> {
|
||||
upcoming: Vec<PortalVisit>,
|
||||
past: Vec<PortalVisit>,
|
||||
feedback_sent: bool,
|
||||
turnstile_site_key: String,
|
||||
notifications_enabled: bool,
|
||||
vapid_public_key: String,
|
||||
calendar_months: Vec<CalendarMonth>,
|
||||
page: usize,
|
||||
total_pages: usize,
|
||||
has_previous_page: bool,
|
||||
has_next_page: bool,
|
||||
}
|
||||
|
||||
const PORTAL_VISITS_PER_PAGE: usize = 10;
|
||||
|
||||
fn query_page(request: &Request) -> usize {
|
||||
request
|
||||
.uri()
|
||||
.query()
|
||||
.and_then(|query| {
|
||||
query.split('&').find_map(|part| {
|
||||
part.strip_prefix("page=")
|
||||
.and_then(|value| value.parse::<usize>().ok())
|
||||
.filter(|page| *page > 0)
|
||||
})
|
||||
})
|
||||
.unwrap_or(1)
|
||||
}
|
||||
|
||||
fn month_label(year: i32, month: u32, lang: Lang) -> String {
|
||||
const RU: [&str; 12] = [
|
||||
"Январь",
|
||||
"Февраль",
|
||||
"Март",
|
||||
"Апрель",
|
||||
"Май",
|
||||
"Июнь",
|
||||
"Июль",
|
||||
"Август",
|
||||
"Сентябрь",
|
||||
"Октябрь",
|
||||
"Ноябрь",
|
||||
"Декабрь",
|
||||
];
|
||||
const EN: [&str; 12] = [
|
||||
"January",
|
||||
"February",
|
||||
"March",
|
||||
"April",
|
||||
"May",
|
||||
"June",
|
||||
"July",
|
||||
"August",
|
||||
"September",
|
||||
"October",
|
||||
"November",
|
||||
"December",
|
||||
];
|
||||
let names = if lang == Lang::Ru { RU } else { EN };
|
||||
format!("{} {year}", names[(month - 1) as usize])
|
||||
}
|
||||
|
||||
async fn client_portal(
|
||||
@@ -181,17 +310,24 @@ async fn client_portal(
|
||||
.query()
|
||||
.map(|q| q.split('&').any(|p| p == "feedback=ok"))
|
||||
.unwrap_or(false);
|
||||
let requested_page = query_page(&request);
|
||||
|
||||
let client = match query!(Client, $media_token == token).get(&db).await? {
|
||||
Some(c) => c,
|
||||
Some(c) if c.status != "deleted" => c,
|
||||
Some(_) => return Html::new("404").into_response(),
|
||||
None => return Html::new("404").into_response(),
|
||||
};
|
||||
|
||||
let client_id = client.id.unwrap();
|
||||
let today = chrono::Utc::now().date_naive();
|
||||
let tz = crate::tz::load_tz(&db).await;
|
||||
let today = crate::tz::today_in_tz(tz);
|
||||
|
||||
let mut visits = Visit::objects().all(&db).await?;
|
||||
visits.retain(|v| v.client_id.primary_key().unwrap() == client_id && v.status != "cancelled");
|
||||
visits.retain(|v| {
|
||||
v.client_id.primary_key().unwrap() == client_id
|
||||
&& v.status != "cancelled"
|
||||
&& v.status != "deleted"
|
||||
});
|
||||
visits.sort_by(|a, b| {
|
||||
a.visit_date
|
||||
.cmp(&b.visit_date)
|
||||
@@ -213,6 +349,7 @@ async fn client_portal(
|
||||
.iter()
|
||||
.filter(|m| {
|
||||
m.status == "active"
|
||||
&& m.client_id.primary_key().unwrap() == client_id
|
||||
&& m.visit_id
|
||||
.as_ref()
|
||||
.map(|fk| fk.primary_key().unwrap() == vid)
|
||||
@@ -227,17 +364,112 @@ async fn client_portal(
|
||||
}
|
||||
};
|
||||
|
||||
let mut upcoming = Vec::new();
|
||||
let mut past = Vec::new();
|
||||
let mut upcoming_visits = Vec::new();
|
||||
let mut past_visits = Vec::new();
|
||||
for v in visits {
|
||||
if v.visit_date >= today && v.status == "scheduled" {
|
||||
upcoming.push(build_portal_visit(v));
|
||||
upcoming_visits.push(v);
|
||||
} else {
|
||||
past.push(build_portal_visit(v));
|
||||
past_visits.push(v);
|
||||
}
|
||||
}
|
||||
past.reverse(); // newest first
|
||||
past_visits.reverse(); // newest first
|
||||
|
||||
let total_pages = past_visits.len().div_ceil(PORTAL_VISITS_PER_PAGE).max(1);
|
||||
let page = requested_page.min(total_pages);
|
||||
let page_start = (page - 1) * PORTAL_VISITS_PER_PAGE;
|
||||
let page_end = (page_start + PORTAL_VISITS_PER_PAGE).min(past_visits.len());
|
||||
let past = past_visits[page_start..page_end]
|
||||
.iter()
|
||||
.cloned()
|
||||
.map(&build_portal_visit)
|
||||
.collect();
|
||||
let upcoming: Vec<_> = upcoming_visits
|
||||
.iter()
|
||||
.cloned()
|
||||
.map(&build_portal_visit)
|
||||
.collect();
|
||||
|
||||
let mut month_keys: Vec<(i32, u32)> = past_visits
|
||||
.iter()
|
||||
.chain(upcoming_visits.iter())
|
||||
.map(|visit| (visit.visit_date.year(), visit.visit_date.month()))
|
||||
.collect();
|
||||
month_keys.sort();
|
||||
month_keys.dedup();
|
||||
month_keys.reverse();
|
||||
let calendar_months = month_keys
|
||||
.into_iter()
|
||||
.map(|(year, month)| {
|
||||
let first = chrono::NaiveDate::from_ymd_opt(year, month, 1).unwrap();
|
||||
let next_month = if month == 12 {
|
||||
chrono::NaiveDate::from_ymd_opt(year + 1, 1, 1).unwrap()
|
||||
} else {
|
||||
chrono::NaiveDate::from_ymd_opt(year, month + 1, 1).unwrap()
|
||||
};
|
||||
let days_in_month = (next_month - first).num_days() as u32;
|
||||
let leading_blanks = vec![0; first.weekday().num_days_from_monday() as usize];
|
||||
let days = (1..=days_in_month)
|
||||
.map(|day| {
|
||||
let date = chrono::NaiveDate::from_ymd_opt(year, month, day).unwrap();
|
||||
if let Some(_visit) = upcoming_visits
|
||||
.iter()
|
||||
.find(|visit| visit.visit_date == date)
|
||||
{
|
||||
CalendarDay {
|
||||
number: day,
|
||||
class_name: "future",
|
||||
href: None,
|
||||
title: lang.t().portal_future_visit.to_string(),
|
||||
}
|
||||
} else if let Some((index, visit)) = past_visits
|
||||
.iter()
|
||||
.enumerate()
|
||||
.find(|(_, visit)| visit.visit_date == date)
|
||||
{
|
||||
CalendarDay {
|
||||
number: day,
|
||||
class_name: "past",
|
||||
href: Some(format!(
|
||||
"?page={}#visit-{}",
|
||||
index / PORTAL_VISITS_PER_PAGE + 1,
|
||||
visit.id.unwrap()
|
||||
)),
|
||||
title: lang.t().visit_status(&visit.status).to_string(),
|
||||
}
|
||||
} else {
|
||||
CalendarDay {
|
||||
number: day,
|
||||
class_name: "empty",
|
||||
href: None,
|
||||
title: String::new(),
|
||||
}
|
||||
}
|
||||
})
|
||||
.collect();
|
||||
CalendarMonth {
|
||||
label: month_label(year, month, lang),
|
||||
leading_blanks,
|
||||
days,
|
||||
}
|
||||
})
|
||||
.collect();
|
||||
|
||||
let notification_key = "client_notifications_enabled".to_string();
|
||||
let vapid_public_key = crate::web_push::load_config(&db)
|
||||
.await
|
||||
.map(|config| config.public_key)
|
||||
.unwrap_or_default();
|
||||
// The administrator setting controls whether the client can see notification
|
||||
// controls. Keep this independent from VAPID validation so a configuration
|
||||
// error is visible in the modal instead of silently removing the button.
|
||||
let notifications_enabled = query!(Setting, $key == notification_key)
|
||||
.get(&db)
|
||||
.await?
|
||||
.map(|setting| setting.value == "true")
|
||||
.unwrap_or(false);
|
||||
|
||||
let turnstile_site_key = crate::turnstile::get_site_key(&db).await?;
|
||||
let body = ClientPortalTemplate {
|
||||
t: lang.t(),
|
||||
lang,
|
||||
@@ -245,14 +477,209 @@ async fn client_portal(
|
||||
upcoming,
|
||||
past,
|
||||
feedback_sent,
|
||||
turnstile_site_key,
|
||||
notifications_enabled,
|
||||
vapid_public_key,
|
||||
calendar_months,
|
||||
page,
|
||||
total_pages,
|
||||
has_previous_page: page > 1,
|
||||
has_next_page: page < total_pages,
|
||||
}
|
||||
.render()?;
|
||||
html_response(body, lang)
|
||||
}
|
||||
|
||||
#[derive(Deserialize)]
|
||||
struct PushKeysForm {
|
||||
p256dh: String,
|
||||
auth: String,
|
||||
}
|
||||
|
||||
#[derive(Deserialize)]
|
||||
struct PushSubscriptionForm {
|
||||
endpoint: String,
|
||||
keys: PushKeysForm,
|
||||
#[serde(default)]
|
||||
language: String,
|
||||
}
|
||||
|
||||
async fn portal_push_subscribe(
|
||||
request: Request,
|
||||
db: Database,
|
||||
Path(token): Path<String>,
|
||||
) -> cot::Result<Response> {
|
||||
tracing::info!("client Web Push subscription request");
|
||||
if crate::web_push::load_config(&db).await.is_none() {
|
||||
return Html::new("404").into_response();
|
||||
}
|
||||
let client = match query!(Client, $media_token == token).get(&db).await? {
|
||||
Some(client) if client.status != "deleted" => client,
|
||||
_ => return Html::new("404").into_response(),
|
||||
};
|
||||
let bytes = request.into_body().into_bytes().await?;
|
||||
let form: PushSubscriptionForm =
|
||||
serde_json::from_slice(&bytes).map_err(|error| cot::Error::internal(error.to_string()))?;
|
||||
if !form.endpoint.starts_with("https://")
|
||||
|| form.endpoint.len() > 4096
|
||||
|| form.keys.p256dh.len() > 512
|
||||
|| form.keys.auth.len() > 256
|
||||
{
|
||||
let mut response = Response::new(cot::Body::fixed(
|
||||
"{\"ok\":false,\"error\":\"invalid subscription\"}",
|
||||
));
|
||||
*response.status_mut() = cot::StatusCode::BAD_REQUEST;
|
||||
response
|
||||
.headers_mut()
|
||||
.insert("content-type", "application/json".parse().unwrap());
|
||||
return Ok(response);
|
||||
}
|
||||
tracing::info!(
|
||||
client_id = client.id.unwrap(),
|
||||
"client Web Push subscription saved"
|
||||
);
|
||||
let endpoint = form.endpoint.clone();
|
||||
let now = chrono::Utc::now().naive_utc();
|
||||
if let Some(mut subscription) = query!(PushSubscription, $endpoint == endpoint)
|
||||
.get(&db)
|
||||
.await?
|
||||
{
|
||||
subscription.client_id = ForeignKey::PrimaryKey(Auto::fixed(client.id.unwrap()));
|
||||
subscription.p256dh = form.keys.p256dh;
|
||||
subscription.auth = form.keys.auth;
|
||||
subscription.language = if form.language == "ru" { "ru" } else { "en" }.to_string();
|
||||
subscription.status = "active".to_string();
|
||||
subscription.updated_at = now;
|
||||
subscription.save(&db).await?;
|
||||
} else {
|
||||
let mut subscription = PushSubscription {
|
||||
id: Auto::auto(),
|
||||
client_id: ForeignKey::PrimaryKey(Auto::fixed(client.id.unwrap())),
|
||||
endpoint: form.endpoint,
|
||||
p256dh: form.keys.p256dh,
|
||||
auth: form.keys.auth,
|
||||
language: if form.language == "ru" { "ru" } else { "en" }.to_string(),
|
||||
status: "active".to_string(),
|
||||
created_at: now,
|
||||
updated_at: now,
|
||||
};
|
||||
subscription.save(&db).await?;
|
||||
}
|
||||
let mut response = Response::new(cot::Body::fixed("{\"ok\":true}"));
|
||||
response
|
||||
.headers_mut()
|
||||
.insert("content-type", "application/json".parse().unwrap());
|
||||
Ok(response)
|
||||
}
|
||||
|
||||
async fn portal_push_unsubscribe(
|
||||
request: Request,
|
||||
db: Database,
|
||||
Path(token): Path<String>,
|
||||
) -> cot::Result<Response> {
|
||||
let client = match query!(Client, $media_token == token).get(&db).await? {
|
||||
Some(client) if client.status != "deleted" => client,
|
||||
_ => return Html::new("404").into_response(),
|
||||
};
|
||||
let bytes = request.into_body().into_bytes().await?;
|
||||
let value: serde_json::Value =
|
||||
serde_json::from_slice(&bytes).map_err(|error| cot::Error::internal(error.to_string()))?;
|
||||
let endpoint = value
|
||||
.get("endpoint")
|
||||
.and_then(|value| value.as_str())
|
||||
.unwrap_or("")
|
||||
.to_string();
|
||||
if let Some(mut subscription) = query!(PushSubscription, $endpoint == endpoint)
|
||||
.get(&db)
|
||||
.await?
|
||||
{
|
||||
if subscription.client_id.primary_key().unwrap() == client.id.unwrap() {
|
||||
subscription.status = "archived".to_string();
|
||||
subscription.updated_at = chrono::Utc::now().naive_utc();
|
||||
subscription.save(&db).await?;
|
||||
}
|
||||
}
|
||||
let mut response = Response::new(cot::Body::fixed("{\"ok\":true}"));
|
||||
response
|
||||
.headers_mut()
|
||||
.insert("content-type", "application/json".parse().unwrap());
|
||||
Ok(response)
|
||||
}
|
||||
|
||||
async fn web_manifest(_request: Request, Path(token): Path<String>) -> cot::Result<Response> {
|
||||
let manifest = serde_json::json!({
|
||||
"id": format!("/client/{token}"),
|
||||
"name": "Pet Sitting Visits",
|
||||
"short_name": "Pet Visits",
|
||||
"start_url": format!("/client/{token}"),
|
||||
"display": "standalone",
|
||||
"background_color": "#f8f7ff",
|
||||
"theme_color": "#7c6cff",
|
||||
"icons": [{ "src": "/favicon.svg", "sizes": "any", "type": "image/svg+xml" }]
|
||||
});
|
||||
let mut response = Response::new(cot::Body::fixed(manifest.to_string()));
|
||||
response
|
||||
.headers_mut()
|
||||
.insert("content-type", "application/manifest+json".parse().unwrap());
|
||||
Ok(response)
|
||||
}
|
||||
|
||||
async fn service_worker(_request: Request) -> cot::Result<Response> {
|
||||
let script = r#"
|
||||
self.addEventListener('install', function(event) {
|
||||
self.skipWaiting();
|
||||
});
|
||||
self.addEventListener('activate', function(event) {
|
||||
event.waitUntil(self.clients.claim());
|
||||
});
|
||||
self.addEventListener('push', function(event) {
|
||||
var data = event.data ? event.data.json() : {};
|
||||
event.waitUntil(self.registration.showNotification(data.title || 'Pet Visits', {
|
||||
body: data.body || '', tag: data.tag || 'visit', data: { url: data.url || '/' },
|
||||
icon: '/favicon.svg', badge: '/favicon.svg'
|
||||
}));
|
||||
});
|
||||
self.addEventListener('notificationclick', function(event) {
|
||||
event.notification.close();
|
||||
var target = new URL(event.notification.data.url || '/', self.location.origin).href;
|
||||
event.waitUntil((async function() {
|
||||
var list = await clients.matchAll({ type: 'window', includeUncontrolled: true });
|
||||
for (var i = 0; i < list.length; i++) {
|
||||
if (list[i].url === target && 'focus' in list[i]) {
|
||||
return list[i].focus();
|
||||
}
|
||||
}
|
||||
for (var j = 0; j < list.length; j++) {
|
||||
if ('navigate' in list[j] && 'focus' in list[j]) {
|
||||
try {
|
||||
var navigated = await list[j].navigate(target);
|
||||
return navigated ? navigated.focus() : list[j].focus();
|
||||
} catch (_) {}
|
||||
}
|
||||
}
|
||||
if (clients.openWindow) return clients.openWindow(target);
|
||||
})());
|
||||
});
|
||||
"#;
|
||||
let mut response = Response::new(cot::Body::fixed(script));
|
||||
response
|
||||
.headers_mut()
|
||||
.insert("content-type", "application/javascript".parse().unwrap());
|
||||
response
|
||||
.headers_mut()
|
||||
.insert("service-worker-allowed", "/".parse().unwrap());
|
||||
response.headers_mut().insert(
|
||||
"cache-control",
|
||||
"no-cache, no-store, must-revalidate".parse().unwrap(),
|
||||
);
|
||||
Ok(response)
|
||||
}
|
||||
|
||||
#[derive(Deserialize)]
|
||||
struct FeedbackForm {
|
||||
feedback: String,
|
||||
#[serde(default, rename = "cf-turnstile-response")]
|
||||
cf_turnstile_response: Option<String>,
|
||||
}
|
||||
|
||||
async fn submit_feedback(
|
||||
@@ -265,7 +692,8 @@ async fn submit_feedback(
|
||||
// Verify token matches visit's client
|
||||
let token_clone = token.clone();
|
||||
let client = match query!(Client, $media_token == token).get(&db).await? {
|
||||
Some(c) => c,
|
||||
Some(c) if c.status != "deleted" => c,
|
||||
Some(_) => return Html::new("404").into_response(),
|
||||
None => return Html::new("404").into_response(),
|
||||
};
|
||||
let client_id = client.id.unwrap();
|
||||
@@ -274,10 +702,19 @@ async fn submit_feedback(
|
||||
let form: FeedbackForm =
|
||||
serde_html_form::from_bytes(&bytes).map_err(|e| cot::Error::internal(e.to_string()))?;
|
||||
|
||||
if !crate::turnstile::verify(&db, form.cf_turnstile_response.as_deref()).await? {
|
||||
return Redirect::new(format!("/client/{}?lang={}", token_clone, lang.code()))
|
||||
.into_response();
|
||||
}
|
||||
|
||||
if let Some(mut visit) = query!(Visit, $id == visit_id).get(&db).await? {
|
||||
if visit.status == "deleted" {
|
||||
return Redirect::new(format!("/client/{}?lang={}", token_clone, lang.code()))
|
||||
.into_response();
|
||||
}
|
||||
if visit.client_id.primary_key().unwrap() == client_id {
|
||||
visit.client_feedback = Some(form.feedback);
|
||||
visit.updated_at = now();
|
||||
visit.updated_at = now_utc();
|
||||
visit.save(&db).await?;
|
||||
}
|
||||
}
|
||||
@@ -292,13 +729,14 @@ async fn submit_feedback(
|
||||
|
||||
/// Serve media files for the client portal (no auth required, but only via token).
|
||||
async fn portal_media(
|
||||
_request: Request,
|
||||
request: Request,
|
||||
db: Database,
|
||||
Path((token, media_id)): Path<(String, i64)>,
|
||||
) -> cot::Result<Response> {
|
||||
// Verify token
|
||||
let client = match query!(Client, $media_token == token).get(&db).await? {
|
||||
Some(c) => c,
|
||||
Some(c) if c.status != "deleted" => c,
|
||||
Some(_) => return Html::new("404").into_response(),
|
||||
None => return Html::new("404").into_response(),
|
||||
};
|
||||
let client_id = client.id.unwrap();
|
||||
@@ -307,28 +745,97 @@ async fn portal_media(
|
||||
Some(m) if m.client_id.primary_key().unwrap() == client_id && m.status == "active" => m,
|
||||
_ => return Html::new("404").into_response(),
|
||||
};
|
||||
if let Some(fk) = &media.visit_id {
|
||||
let visit_id: i64 = fk.primary_key().unwrap();
|
||||
match query!(Visit, $id == visit_id).get(&db).await? {
|
||||
Some(v) if v.status != "deleted" => {}
|
||||
_ => return Html::new("404").into_response(),
|
||||
}
|
||||
}
|
||||
|
||||
match tokio::fs::read(&media.file_path).await {
|
||||
Ok(data) => {
|
||||
let content_type = match media.file_path.rsplit('.').next().unwrap_or("") {
|
||||
"jpg" | "jpeg" => "image/jpeg",
|
||||
"png" => "image/png",
|
||||
"heic" | "heif" => "image/heic",
|
||||
"webp" => "image/webp",
|
||||
"mp4" => "video/mp4",
|
||||
"mov" => "video/quicktime",
|
||||
"avi" => "video/x-msvideo",
|
||||
"mkv" => "video/x-matroska",
|
||||
"webm" => "video/webm",
|
||||
_ => "application/octet-stream",
|
||||
};
|
||||
let body = cot::Body::fixed(data);
|
||||
let mut resp = Response::new(body);
|
||||
resp.headers_mut()
|
||||
.insert("content-type", content_type.parse().unwrap());
|
||||
Ok(resp)
|
||||
let range = request
|
||||
.headers()
|
||||
.get("range")
|
||||
.and_then(|value| value.to_str().ok())
|
||||
.map(str::to_owned);
|
||||
|
||||
match {
|
||||
let content_type = match media.file_path.rsplit('.').next().unwrap_or("") {
|
||||
"jpg" | "jpeg" => "image/jpeg",
|
||||
"png" => "image/png",
|
||||
"heic" | "heif" => "image/heic",
|
||||
"webp" => "image/webp",
|
||||
"mp4" => "video/mp4",
|
||||
"mov" => "video/quicktime",
|
||||
"avi" => "video/x-msvideo",
|
||||
"mkv" => "video/x-matroska",
|
||||
"webm" => "video/webm",
|
||||
_ => "application/octet-stream",
|
||||
};
|
||||
crate::uploads::ranged_file_response(&media.file_path, content_type, range.as_deref()).await
|
||||
} {
|
||||
Ok(response) => Ok(response),
|
||||
Err(err) => {
|
||||
tracing::warn!(
|
||||
target: "uploads",
|
||||
media_id,
|
||||
db_path = %media.file_path,
|
||||
resolved_path = %crate::uploads::resolved_display_path(&media.file_path),
|
||||
error = %err,
|
||||
"portal media file is missing or unreadable"
|
||||
);
|
||||
Html::new("404").into_response()
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
async fn portal_media_thumbnail(
|
||||
_request: Request,
|
||||
db: Database,
|
||||
Path((token, media_id)): Path<(String, i64)>,
|
||||
) -> cot::Result<Response> {
|
||||
let client = match query!(Client, $media_token == token).get(&db).await? {
|
||||
Some(client) if client.status != "deleted" => client,
|
||||
_ => return Html::new("404").into_response(),
|
||||
};
|
||||
let media = match query!(Media, $id == media_id).get(&db).await? {
|
||||
Some(media)
|
||||
if media.client_id.primary_key().unwrap() == client.id.unwrap()
|
||||
&& media.status == "active"
|
||||
&& media.file_type == "photo" =>
|
||||
{
|
||||
media
|
||||
}
|
||||
_ => return Html::new("404").into_response(),
|
||||
};
|
||||
if let Some(visit) = &media.visit_id {
|
||||
let visit_id = visit.primary_key().unwrap();
|
||||
match query!(Visit, $id == visit_id).get(&db).await? {
|
||||
Some(visit) if visit.status != "deleted" => {}
|
||||
_ => return Html::new("404").into_response(),
|
||||
}
|
||||
}
|
||||
match crate::uploads::ensure_thumbnail(&media.file_path).await {
|
||||
Ok(path) => {
|
||||
let mut response = crate::uploads::ranged_file_response(&path, "image/jpeg", None)
|
||||
.await
|
||||
.map_err(|error| cot::Error::internal(error.to_string()))?;
|
||||
response.headers_mut().insert(
|
||||
"cache-control",
|
||||
"private, max-age=31536000, immutable".parse().unwrap(),
|
||||
);
|
||||
Ok(response)
|
||||
}
|
||||
Err(error) => {
|
||||
tracing::warn!(media_id, %error, "failed to create portal media thumbnail");
|
||||
crate::uploads::ranged_file_response(
|
||||
&media.file_path,
|
||||
crate::uploads::content_type_for_path(&media.file_path),
|
||||
None,
|
||||
)
|
||||
.await
|
||||
.map_err(|error| cot::Error::internal(error.to_string()))
|
||||
}
|
||||
Err(_) => Html::new("404").into_response(),
|
||||
}
|
||||
}
|
||||
|
||||
@@ -345,7 +852,7 @@ async fn serve_testimonial_image(
|
||||
Some(p) => p.clone(),
|
||||
None => return Html::new("404").into_response(),
|
||||
};
|
||||
match tokio::fs::read(&path).await {
|
||||
match crate::uploads::read_db_file(&path).await {
|
||||
Ok(data) => {
|
||||
let content_type = match path.rsplit('.').next().unwrap_or("") {
|
||||
"jpg" | "jpeg" => "image/jpeg",
|
||||
@@ -362,13 +869,133 @@ async fn serve_testimonial_image(
|
||||
.insert("cache-control", "public, max-age=86400".parse().unwrap());
|
||||
Ok(resp)
|
||||
}
|
||||
Err(_) => Html::new("404").into_response(),
|
||||
Err(err) => {
|
||||
tracing::warn!(
|
||||
target: "uploads",
|
||||
testimonial_id = id,
|
||||
db_path = %path,
|
||||
resolved_path = %crate::uploads::resolved_display_path(&path),
|
||||
error = %err,
|
||||
"testimonial image is missing or unreadable"
|
||||
);
|
||||
Html::new("404").into_response()
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
async fn favicon(_request: Request) -> cot::Result<Response> {
|
||||
let svg = r##"<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 64 64">
|
||||
<ellipse cx="32" cy="42" rx="14" ry="16" fill="#7c6cff"/>
|
||||
<ellipse cx="14" cy="20" rx="7" ry="9" fill="#7c6cff" transform="rotate(-10 14 20)"/>
|
||||
<ellipse cx="50" cy="20" rx="7" ry="9" fill="#7c6cff" transform="rotate(10 50 20)"/>
|
||||
<ellipse cx="23" cy="8" rx="5.5" ry="7" fill="#7c6cff" transform="rotate(-5 23 8)"/>
|
||||
<ellipse cx="41" cy="8" rx="5.5" ry="7" fill="#7c6cff" transform="rotate(5 41 8)"/>
|
||||
</svg>"##;
|
||||
let mut resp = Response::new(cot::Body::fixed(svg.as_bytes().to_vec()));
|
||||
resp.headers_mut()
|
||||
.insert("content-type", "image/svg+xml".parse().unwrap());
|
||||
resp.headers_mut()
|
||||
.insert("cache-control", "public, max-age=604800".parse().unwrap());
|
||||
Ok(resp)
|
||||
}
|
||||
|
||||
async fn serve_static(_request: Request, Path(filename): Path<String>) -> cot::Result<Response> {
|
||||
// Only allow simple filenames (no path traversal)
|
||||
if filename.contains('/') || filename.contains('\\') || filename.contains("..") {
|
||||
return Html::new("404").into_response();
|
||||
}
|
||||
let ext = filename.rsplit('.').next().unwrap_or("");
|
||||
// Try relative path first, then /app/static/ (Docker)
|
||||
let path = format!("static/{filename}");
|
||||
let data = match tokio::fs::read(&path).await {
|
||||
Ok(d) => d,
|
||||
Err(_) => match tokio::fs::read(format!("/app/static/{filename}")).await {
|
||||
Ok(d) => d,
|
||||
Err(_) => return Html::new("404").into_response(),
|
||||
},
|
||||
};
|
||||
let content_type = match ext {
|
||||
"png" => "image/png",
|
||||
"jpg" | "jpeg" => "image/jpeg",
|
||||
"webp" => "image/webp",
|
||||
"svg" => "image/svg+xml",
|
||||
"gif" => "image/gif",
|
||||
_ => "application/octet-stream",
|
||||
};
|
||||
let body = cot::Body::fixed(data);
|
||||
let mut resp = Response::new(body);
|
||||
resp.headers_mut()
|
||||
.insert("content-type", content_type.parse().unwrap());
|
||||
resp.headers_mut()
|
||||
.insert("cache-control", "public, max-age=604800".parse().unwrap());
|
||||
Ok(resp)
|
||||
}
|
||||
|
||||
async fn robots_txt(_request: Request, db: Database) -> cot::Result<Response> {
|
||||
let domain_key = "site_domain".to_string();
|
||||
let site_domain = query!(Setting, $key == domain_key)
|
||||
.get(&db)
|
||||
.await?
|
||||
.map(|s| s.value)
|
||||
.unwrap_or_else(|| "https://example.net".to_string());
|
||||
let body = format!(
|
||||
"User-agent: *\nAllow: /\nDisallow: /admin/\nDisallow: /client/\nSitemap: {}/sitemap.xml\n",
|
||||
site_domain
|
||||
);
|
||||
let mut resp = Response::new(cot::Body::fixed(body.into_bytes()));
|
||||
resp.headers_mut()
|
||||
.insert("content-type", "text/plain; charset=utf-8".parse().unwrap());
|
||||
Ok(resp)
|
||||
}
|
||||
|
||||
async fn sitemap_xml(_request: Request, db: Database) -> cot::Result<Response> {
|
||||
let domain_key = "site_domain".to_string();
|
||||
let site_domain = query!(Setting, $key == domain_key)
|
||||
.get(&db)
|
||||
.await?
|
||||
.map(|s| s.value)
|
||||
.unwrap_or_else(|| "https://example.net".to_string());
|
||||
let body = format!(
|
||||
r#"<?xml version="1.0" encoding="UTF-8"?>
|
||||
<urlset xmlns="http://www.sitemaps.org/schemas/sitemap/0.9"
|
||||
xmlns:xhtml="http://www.w3.org/1999/xhtml">
|
||||
<url>
|
||||
<loc>{domain}/?lang=ru</loc>
|
||||
<xhtml:link rel="alternate" hreflang="ru" href="{domain}/?lang=ru"/>
|
||||
<xhtml:link rel="alternate" hreflang="en" href="{domain}/?lang=en"/>
|
||||
<xhtml:link rel="alternate" hreflang="x-default" href="{domain}/"/>
|
||||
</url>
|
||||
<url>
|
||||
<loc>{domain}/?lang=en</loc>
|
||||
<xhtml:link rel="alternate" hreflang="ru" href="{domain}/?lang=ru"/>
|
||||
<xhtml:link rel="alternate" hreflang="en" href="{domain}/?lang=en"/>
|
||||
<xhtml:link rel="alternate" hreflang="x-default" href="{domain}/"/>
|
||||
</url>
|
||||
</urlset>
|
||||
"#,
|
||||
domain = site_domain
|
||||
);
|
||||
let mut resp = Response::new(cot::Body::fixed(body.into_bytes()));
|
||||
resp.headers_mut().insert(
|
||||
"content-type",
|
||||
"application/xml; charset=utf-8".parse().unwrap(),
|
||||
);
|
||||
Ok(resp)
|
||||
}
|
||||
|
||||
pub fn public_router() -> Router {
|
||||
Router::with_urls([
|
||||
Route::with_handler_and_name("/", landing_page, "landing"),
|
||||
Route::with_handler_and_name("/favicon.svg", favicon, "favicon"),
|
||||
Route::with_handler_and_name(
|
||||
"/client/{token}/manifest.webmanifest",
|
||||
web_manifest,
|
||||
"web-manifest",
|
||||
),
|
||||
Route::with_handler_and_name("/service-worker.js", service_worker, "service-worker"),
|
||||
Route::with_handler_and_name("/static/{filename}", serve_static, "static-file"),
|
||||
Route::with_handler_and_name("/robots.txt", robots_txt, "robots-txt"),
|
||||
Route::with_handler_and_name("/sitemap.xml", sitemap_xml, "sitemap-xml"),
|
||||
Route::with_handler_and_name("/submit", submit_lead, "submit-lead"),
|
||||
Route::with_handler_and_name(
|
||||
"/testimonial-image/{id}",
|
||||
@@ -376,6 +1003,16 @@ pub fn public_router() -> Router {
|
||||
"testimonial-image",
|
||||
),
|
||||
Route::with_handler_and_name("/client/{token}", client_portal, "client-portal"),
|
||||
Route::with_handler_and_name(
|
||||
"/client/{token}/push/subscribe",
|
||||
portal_push_subscribe,
|
||||
"client-push-subscribe",
|
||||
),
|
||||
Route::with_handler_and_name(
|
||||
"/client/{token}/push/unsubscribe",
|
||||
portal_push_unsubscribe,
|
||||
"client-push-unsubscribe",
|
||||
),
|
||||
Route::with_handler_and_name(
|
||||
"/client/{token}/{visit_id}/feedback",
|
||||
submit_feedback,
|
||||
@@ -386,5 +1023,10 @@ pub fn public_router() -> Router {
|
||||
portal_media,
|
||||
"client-media",
|
||||
),
|
||||
Route::with_handler_and_name(
|
||||
"/client/{token}/media/{media_id}/thumbnail",
|
||||
portal_media_thumbnail,
|
||||
"client-media-thumbnail",
|
||||
),
|
||||
])
|
||||
}
|
||||
|
||||
+28
-14
@@ -1,8 +1,8 @@
|
||||
use cot::db::{Database, query};
|
||||
|
||||
use crate::models::Setting;
|
||||
use crate::models::{Setting, User};
|
||||
|
||||
/// Send a Telegram message using bot settings from DB.
|
||||
/// Send a Telegram notification to all admins with notifications enabled.
|
||||
/// Silently ignores errors (missing config, network issues) — notifications are best-effort.
|
||||
pub async fn notify_new_lead(
|
||||
db: &Database,
|
||||
@@ -14,10 +14,6 @@ pub async fn notify_new_lead(
|
||||
Some(t) if !t.is_empty() => t,
|
||||
_ => return,
|
||||
};
|
||||
let chat_id = match get_setting(db, "telegram_chat_id").await {
|
||||
Some(c) if !c.is_empty() => c,
|
||||
_ => return,
|
||||
};
|
||||
|
||||
let mut text = format!("📋 Новая заявка!\n\nИмя: {name}");
|
||||
if let Some(phone) = phone.filter(|s| !s.is_empty()) {
|
||||
@@ -27,15 +23,33 @@ pub async fn notify_new_lead(
|
||||
text.push_str(&format!("\nКомментарий: {comment}"));
|
||||
}
|
||||
|
||||
let active = "active".to_string();
|
||||
let users = match query!(User, $status == active).all(db).await {
|
||||
Ok(u) => u,
|
||||
Err(_) => return,
|
||||
};
|
||||
|
||||
let client = reqwest::Client::new();
|
||||
let url = format!("https://api.telegram.org/bot{token}/sendMessage");
|
||||
let _ = reqwest::Client::new()
|
||||
.post(&url)
|
||||
.json(&serde_json::json!({
|
||||
"chat_id": chat_id,
|
||||
"text": text,
|
||||
}))
|
||||
.send()
|
||||
.await;
|
||||
|
||||
for user in &users {
|
||||
if user.telegram_notifications != Some(true) {
|
||||
continue;
|
||||
}
|
||||
let chat_id = match &user.telegram_chat_id {
|
||||
Some(id) if !id.is_empty() => id,
|
||||
_ => continue,
|
||||
};
|
||||
|
||||
let _ = client
|
||||
.post(&url)
|
||||
.json(&serde_json::json!({
|
||||
"chat_id": chat_id,
|
||||
"text": text,
|
||||
}))
|
||||
.send()
|
||||
.await;
|
||||
}
|
||||
}
|
||||
|
||||
async fn get_setting(db: &Database, key_name: &str) -> Option<String> {
|
||||
|
||||
@@ -0,0 +1,48 @@
|
||||
use cot::db::{Database, query};
|
||||
|
||||
use crate::models::Setting;
|
||||
|
||||
/// Read `turnstile_site_key` from Settings. Returns empty string if not configured.
|
||||
pub async fn get_site_key(db: &Database) -> cot::Result<String> {
|
||||
let key = "turnstile_site_key".to_string();
|
||||
Ok(query!(Setting, $key == key)
|
||||
.get(db)
|
||||
.await?
|
||||
.map(|s| s.value)
|
||||
.unwrap_or_default())
|
||||
}
|
||||
|
||||
/// Verify a Turnstile token against Cloudflare.
|
||||
/// Returns `true` if verification succeeds, or if no secret key is configured (passthrough).
|
||||
pub async fn verify(db: &Database, token: Option<&str>) -> cot::Result<bool> {
|
||||
let secret_key_name = "turnstile_secret_key".to_string();
|
||||
let secret_key = query!(Setting, $key == secret_key_name)
|
||||
.get(db)
|
||||
.await?
|
||||
.map(|s| s.value)
|
||||
.filter(|s| !s.is_empty());
|
||||
|
||||
let Some(secret) = secret_key else {
|
||||
return Ok(true);
|
||||
};
|
||||
|
||||
let token = token.unwrap_or("");
|
||||
let client = reqwest::Client::new();
|
||||
let resp = client
|
||||
.post("https://challenges.cloudflare.com/turnstile/v0/siteverify")
|
||||
.json(&serde_json::json!({
|
||||
"secret": secret,
|
||||
"response": token
|
||||
}))
|
||||
.send()
|
||||
.await;
|
||||
|
||||
Ok(match resp {
|
||||
Ok(r) => r
|
||||
.json::<serde_json::Value>()
|
||||
.await
|
||||
.map(|v| v["success"].as_bool() == Some(true))
|
||||
.unwrap_or(false),
|
||||
Err(_) => false,
|
||||
})
|
||||
}
|
||||
@@ -0,0 +1,30 @@
|
||||
use chrono_tz::Tz;
|
||||
use cot::db::{Database, query};
|
||||
|
||||
use crate::models::Setting;
|
||||
|
||||
const DEFAULT_TZ: &str = "UTC";
|
||||
|
||||
/// Load timezone from the database settings.
|
||||
pub async fn load_tz(db: &Database) -> Tz {
|
||||
let key = "timezone".to_string();
|
||||
let tz_str = query!(Setting, $key == key)
|
||||
.get(db)
|
||||
.await
|
||||
.ok()
|
||||
.flatten()
|
||||
.map(|s| s.value)
|
||||
.unwrap_or_else(|| DEFAULT_TZ.to_string());
|
||||
tz_str.parse::<Tz>().unwrap_or(Tz::UTC)
|
||||
}
|
||||
|
||||
/// Current date+time in the configured timezone, returned as NaiveDateTime.
|
||||
#[allow(dead_code)]
|
||||
pub fn now_in_tz(tz: Tz) -> chrono::NaiveDateTime {
|
||||
chrono::Utc::now().with_timezone(&tz).naive_local()
|
||||
}
|
||||
|
||||
/// Today's date in the configured timezone.
|
||||
pub fn today_in_tz(tz: Tz) -> chrono::NaiveDate {
|
||||
chrono::Utc::now().with_timezone(&tz).date_naive()
|
||||
}
|
||||
+247
@@ -0,0 +1,247 @@
|
||||
use std::path::{Path, PathBuf};
|
||||
|
||||
use cot::response::Response;
|
||||
use cot::{Body, StatusCode};
|
||||
use tokio::io::{AsyncReadExt, AsyncSeekExt};
|
||||
|
||||
const THUMBNAIL_MAX_DIMENSION: u32 = 360;
|
||||
const THUMBNAIL_JPEG_QUALITY: u8 = 70;
|
||||
|
||||
const DEFAULT_UPLOAD_DIR: &str = "uploads";
|
||||
const UPLOAD_DIR_ENV: &str = "WEB_PETTING_UPLOAD_DIR";
|
||||
|
||||
pub fn media_dir(client_id: i64, visit_id: i64) -> String {
|
||||
format!("{DEFAULT_UPLOAD_DIR}/{client_id}/{visit_id}")
|
||||
}
|
||||
|
||||
pub fn testimonials_dir() -> String {
|
||||
format!("{DEFAULT_UPLOAD_DIR}/testimonials")
|
||||
}
|
||||
|
||||
pub fn join_db_path(dir: &str, filename: &str) -> String {
|
||||
format!("{}/{}", dir.trim_end_matches('/'), filename)
|
||||
}
|
||||
|
||||
pub fn resolve_db_path(db_path: &str) -> PathBuf {
|
||||
let path = PathBuf::from(db_path);
|
||||
if path.is_absolute() {
|
||||
return path;
|
||||
}
|
||||
|
||||
let Some(upload_root) = std::env::var_os(UPLOAD_DIR_ENV) else {
|
||||
return path;
|
||||
};
|
||||
|
||||
let upload_root = PathBuf::from(upload_root);
|
||||
let logical_path = Path::new(db_path);
|
||||
match logical_path.strip_prefix(DEFAULT_UPLOAD_DIR) {
|
||||
Ok(stripped) => upload_root.join(stripped),
|
||||
Err(_) => upload_root.join(logical_path),
|
||||
}
|
||||
}
|
||||
|
||||
pub fn resolved_display_path(db_path: &str) -> String {
|
||||
resolve_db_path(db_path).display().to_string()
|
||||
}
|
||||
|
||||
pub async fn create_logical_dir(db_dir: &str) -> std::io::Result<()> {
|
||||
tokio::fs::create_dir_all(resolve_db_path(db_dir)).await
|
||||
}
|
||||
|
||||
pub async fn write_db_file(db_path: &str, data: &[u8]) -> std::io::Result<()> {
|
||||
let physical_path = resolve_db_path(db_path);
|
||||
if let Some(parent) = physical_path.parent() {
|
||||
tokio::fs::create_dir_all(parent).await?;
|
||||
}
|
||||
tokio::fs::write(physical_path, data).await
|
||||
}
|
||||
|
||||
pub async fn read_db_file(db_path: &str) -> std::io::Result<Vec<u8>> {
|
||||
tokio::fs::read(resolve_db_path(db_path)).await
|
||||
}
|
||||
|
||||
pub fn thumbnail_db_path(db_path: &str) -> String {
|
||||
match db_path.rsplit_once('.') {
|
||||
Some((stem, _)) => format!("{stem}.thumb.jpg"),
|
||||
None => format!("{db_path}.thumb.jpg"),
|
||||
}
|
||||
}
|
||||
|
||||
pub fn content_type_for_path(path: &str) -> &'static str {
|
||||
match path.rsplit('.').next().unwrap_or("") {
|
||||
"jpg" | "jpeg" => "image/jpeg",
|
||||
"png" => "image/png",
|
||||
"heic" | "heif" => "image/heic",
|
||||
"webp" => "image/webp",
|
||||
"mp4" => "video/mp4",
|
||||
"mov" => "video/quicktime",
|
||||
"avi" => "video/x-msvideo",
|
||||
"mkv" => "video/x-matroska",
|
||||
"webm" => "video/webm",
|
||||
_ => "application/octet-stream",
|
||||
}
|
||||
}
|
||||
|
||||
pub async fn ensure_thumbnail(db_path: &str) -> std::io::Result<String> {
|
||||
let thumbnail_path = thumbnail_db_path(db_path);
|
||||
if tokio::fs::try_exists(resolve_db_path(&thumbnail_path)).await? {
|
||||
return Ok(thumbnail_path);
|
||||
}
|
||||
let data = read_db_file(db_path).await?;
|
||||
let image = image::load_from_memory(&data)
|
||||
.map_err(|error| std::io::Error::new(std::io::ErrorKind::InvalidData, error))?;
|
||||
let thumbnail = image.thumbnail(THUMBNAIL_MAX_DIMENSION, THUMBNAIL_MAX_DIMENSION);
|
||||
let rgb = thumbnail.to_rgb8();
|
||||
let mut encoded = Vec::new();
|
||||
let mut encoder =
|
||||
image::codecs::jpeg::JpegEncoder::new_with_quality(&mut encoded, THUMBNAIL_JPEG_QUALITY);
|
||||
encoder.encode_image(&rgb).map_err(std::io::Error::other)?;
|
||||
write_db_file(&thumbnail_path, &encoded).await?;
|
||||
Ok(thumbnail_path)
|
||||
}
|
||||
|
||||
enum ByteRange {
|
||||
Full,
|
||||
Partial { start: u64, end: u64 },
|
||||
Unsatisfiable,
|
||||
}
|
||||
|
||||
fn parse_byte_range(header: Option<&str>, file_len: u64) -> ByteRange {
|
||||
let Some(value) = header else {
|
||||
return ByteRange::Full;
|
||||
};
|
||||
let Some(spec) = value.strip_prefix("bytes=") else {
|
||||
return ByteRange::Unsatisfiable;
|
||||
};
|
||||
if spec.contains(',') || file_len == 0 {
|
||||
return ByteRange::Unsatisfiable;
|
||||
}
|
||||
|
||||
let Some((start, end)) = spec.split_once('-') else {
|
||||
return ByteRange::Unsatisfiable;
|
||||
};
|
||||
if start.is_empty() {
|
||||
let Ok(suffix_len) = end.parse::<u64>() else {
|
||||
return ByteRange::Unsatisfiable;
|
||||
};
|
||||
if suffix_len == 0 {
|
||||
return ByteRange::Unsatisfiable;
|
||||
}
|
||||
let start = file_len.saturating_sub(suffix_len);
|
||||
return ByteRange::Partial {
|
||||
start,
|
||||
end: file_len - 1,
|
||||
};
|
||||
}
|
||||
|
||||
let Ok(start) = start.parse::<u64>() else {
|
||||
return ByteRange::Unsatisfiable;
|
||||
};
|
||||
if start >= file_len {
|
||||
return ByteRange::Unsatisfiable;
|
||||
}
|
||||
let end = if end.is_empty() {
|
||||
file_len - 1
|
||||
} else {
|
||||
let Ok(end) = end.parse::<u64>() else {
|
||||
return ByteRange::Unsatisfiable;
|
||||
};
|
||||
end.min(file_len - 1)
|
||||
};
|
||||
if end < start {
|
||||
return ByteRange::Unsatisfiable;
|
||||
}
|
||||
|
||||
ByteRange::Partial { start, end }
|
||||
}
|
||||
|
||||
/// Read a file into an HTTP response, honoring a single `Range: bytes=...` request.
|
||||
pub async fn ranged_file_response(
|
||||
db_path: &str,
|
||||
content_type: &str,
|
||||
range_header: Option<&str>,
|
||||
) -> std::io::Result<Response> {
|
||||
let path = resolve_db_path(db_path);
|
||||
let mut file = tokio::fs::File::open(path).await?;
|
||||
let file_len = file.metadata().await?.len();
|
||||
let range = parse_byte_range(range_header, file_len);
|
||||
|
||||
let (status, body, content_range) = match range {
|
||||
ByteRange::Full => {
|
||||
let mut data = Vec::with_capacity(file_len as usize);
|
||||
file.read_to_end(&mut data).await?;
|
||||
(StatusCode::OK, data, None)
|
||||
}
|
||||
ByteRange::Partial { start, end } => {
|
||||
let range_len = end - start + 1;
|
||||
let mut data = vec![0; range_len as usize];
|
||||
file.seek(std::io::SeekFrom::Start(start)).await?;
|
||||
file.read_exact(&mut data).await?;
|
||||
(
|
||||
StatusCode::PARTIAL_CONTENT,
|
||||
data,
|
||||
Some(format!("bytes {start}-{end}/{file_len}")),
|
||||
)
|
||||
}
|
||||
ByteRange::Unsatisfiable => {
|
||||
let mut response = Response::new(Body::fixed(Vec::<u8>::new()));
|
||||
*response.status_mut() = StatusCode::RANGE_NOT_SATISFIABLE;
|
||||
response
|
||||
.headers_mut()
|
||||
.insert("accept-ranges", "bytes".parse().unwrap());
|
||||
response.headers_mut().insert(
|
||||
"content-range",
|
||||
format!("bytes */{file_len}").parse().unwrap(),
|
||||
);
|
||||
return Ok(response);
|
||||
}
|
||||
};
|
||||
|
||||
let content_len = body.len();
|
||||
let mut response = Response::new(Body::fixed(body));
|
||||
*response.status_mut() = status;
|
||||
response
|
||||
.headers_mut()
|
||||
.insert("content-type", content_type.parse().unwrap());
|
||||
response
|
||||
.headers_mut()
|
||||
.insert("accept-ranges", "bytes".parse().unwrap());
|
||||
response
|
||||
.headers_mut()
|
||||
.insert("content-length", content_len.to_string().parse().unwrap());
|
||||
if let Some(content_range) = content_range {
|
||||
response
|
||||
.headers_mut()
|
||||
.insert("content-range", content_range.parse().unwrap());
|
||||
}
|
||||
Ok(response)
|
||||
}
|
||||
|
||||
pub async fn remove_db_file(db_path: &str) -> std::io::Result<()> {
|
||||
tokio::fs::remove_file(resolve_db_path(db_path)).await
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::{ByteRange, parse_byte_range};
|
||||
|
||||
#[test]
|
||||
fn parses_byte_ranges() {
|
||||
assert!(matches!(
|
||||
parse_byte_range(Some("bytes=10-19"), 100),
|
||||
ByteRange::Partial { start: 10, end: 19 }
|
||||
));
|
||||
assert!(matches!(
|
||||
parse_byte_range(Some("bytes=90-"), 100),
|
||||
ByteRange::Partial { start: 90, end: 99 }
|
||||
));
|
||||
assert!(matches!(
|
||||
parse_byte_range(Some("bytes=-10"), 100),
|
||||
ByteRange::Partial { start: 90, end: 99 }
|
||||
));
|
||||
assert!(matches!(
|
||||
parse_byte_range(Some("bytes=100-"), 100),
|
||||
ByteRange::Unsatisfiable
|
||||
));
|
||||
}
|
||||
}
|
||||
+190
@@ -0,0 +1,190 @@
|
||||
use base64::Engine;
|
||||
use base64::engine::general_purpose::URL_SAFE_NO_PAD;
|
||||
use cot::db::{Database, Model, query};
|
||||
use serde_json::json;
|
||||
use web_push_native::jwt_simple::algorithms::ES256KeyPair;
|
||||
use web_push_native::p256::PublicKey;
|
||||
use web_push_native::{Auth, WebPushBuilder};
|
||||
|
||||
use crate::models::{Client, PushSubscription, Setting, Visit};
|
||||
|
||||
pub struct VapidConfig {
|
||||
pub public_key: String,
|
||||
private_key: String,
|
||||
subject: String,
|
||||
}
|
||||
|
||||
fn normalize_key_pair(public_key: &str, private_key: &str) -> Option<(String, String)> {
|
||||
let strip_assignment = |value: &str, name: &str| {
|
||||
value
|
||||
.trim()
|
||||
.strip_prefix(&format!("{name}="))
|
||||
.unwrap_or(value.trim())
|
||||
.trim()
|
||||
.to_string()
|
||||
};
|
||||
let public_key = strip_assignment(public_key, "WEB_PETTING_VAPID_PUBLIC_KEY");
|
||||
let private_key = strip_assignment(private_key, "WEB_PETTING_VAPID_PRIVATE_KEY");
|
||||
let public_bytes = URL_SAFE_NO_PAD.decode(&public_key).ok()?;
|
||||
let private_bytes = URL_SAFE_NO_PAD.decode(&private_key).ok()?;
|
||||
|
||||
if public_bytes.len() == 65 && public_bytes.first() == Some(&4) && private_bytes.len() == 32 {
|
||||
return Some((public_key, private_key));
|
||||
}
|
||||
None
|
||||
}
|
||||
|
||||
pub async fn load_config(db: &Database) -> Option<VapidConfig> {
|
||||
let settings = Setting::objects().all(db).await.ok()?;
|
||||
let value = |key: &str| {
|
||||
settings
|
||||
.iter()
|
||||
.find(|setting| setting.key == key)
|
||||
.map(|setting| setting.value.trim().to_string())
|
||||
.filter(|value| !value.is_empty())
|
||||
};
|
||||
let raw_public_key = value("vapid_public_key")?;
|
||||
let raw_private_key = value("vapid_private_key")?;
|
||||
let (public_key, private_key) = match normalize_key_pair(&raw_public_key, &raw_private_key) {
|
||||
Some(keys) => keys,
|
||||
None => {
|
||||
tracing::warn!("invalid VAPID configuration in database");
|
||||
return None;
|
||||
}
|
||||
};
|
||||
let subject_value =
|
||||
value("vapid_subject").unwrap_or_else(|| "mailto:admin@localhost".to_string());
|
||||
let subject = subject_value
|
||||
.strip_prefix("WEB_PETTING_VAPID_SUBJECT=")
|
||||
.unwrap_or(&subject_value)
|
||||
.trim()
|
||||
.to_string();
|
||||
Some(VapidConfig {
|
||||
public_key,
|
||||
private_key,
|
||||
subject,
|
||||
})
|
||||
}
|
||||
|
||||
pub async fn initialize(db: &Database) {
|
||||
if load_config(db).await.is_some() {
|
||||
tracing::info!("VAPID configuration loaded from database");
|
||||
} else {
|
||||
tracing::info!("VAPID configuration is not set; client Web Push is disabled");
|
||||
}
|
||||
}
|
||||
|
||||
pub async fn notify_visit_completed(db: &Database, visit: &Visit) {
|
||||
let setting_key = "client_notifications_enabled".to_string();
|
||||
let enabled = query!(Setting, $key == setting_key)
|
||||
.get(db)
|
||||
.await
|
||||
.ok()
|
||||
.flatten()
|
||||
.map(|setting| setting.value == "true")
|
||||
.unwrap_or(false);
|
||||
let Some(config) = load_config(db).await else {
|
||||
return;
|
||||
};
|
||||
if !enabled {
|
||||
return;
|
||||
}
|
||||
|
||||
let client_id = visit.client_id.primary_key().unwrap();
|
||||
let client = match query!(Client, $id == client_id).get(db).await {
|
||||
Ok(Some(client)) => client,
|
||||
_ => return,
|
||||
};
|
||||
let active = "active".to_string();
|
||||
let subscriptions = match query!(PushSubscription, $status == active).all(db).await {
|
||||
Ok(items) => items
|
||||
.into_iter()
|
||||
.filter(|item| item.client_id.primary_key().unwrap() == client_id)
|
||||
.collect::<Vec<_>>(),
|
||||
Err(error) => {
|
||||
tracing::warn!(%error, "failed to load Web Push subscriptions");
|
||||
return;
|
||||
}
|
||||
};
|
||||
let mut visible_visits = match Visit::objects().all(db).await {
|
||||
Ok(visits) => visits
|
||||
.into_iter()
|
||||
.filter(|item| {
|
||||
item.client_id.primary_key().unwrap() == client_id
|
||||
&& item.status != "cancelled"
|
||||
&& item.status != "deleted"
|
||||
})
|
||||
.collect::<Vec<_>>(),
|
||||
Err(_) => Vec::new(),
|
||||
};
|
||||
visible_visits.sort_by(|a, b| {
|
||||
b.visit_date
|
||||
.cmp(&a.visit_date)
|
||||
.then(b.time_start.cmp(&a.time_start))
|
||||
});
|
||||
let page = visible_visits
|
||||
.iter()
|
||||
.position(|item| item.id.unwrap() == visit.id.unwrap())
|
||||
.map(|index| index / 10 + 1)
|
||||
.unwrap_or(1);
|
||||
|
||||
for mut subscription in subscriptions {
|
||||
let is_ru = subscription.language == "ru";
|
||||
let date = visit.visit_date.format("%d.%m.%Y");
|
||||
let body = if is_ru {
|
||||
format!("Визит {date} завершён. Нажмите для просмотра медиа и комментариев.")
|
||||
} else {
|
||||
format!("Visit {date} is complete. Click to view media and comments.")
|
||||
};
|
||||
let payload = json!({
|
||||
"title": if is_ru { "Визит завершён" } else { "Visit completed" },
|
||||
"body": body,
|
||||
"url": format!("/client/{}?page={}#visit-{}", client.media_token, page, visit.id.unwrap()),
|
||||
"tag": format!("visit-{}", visit.id.unwrap()),
|
||||
});
|
||||
|
||||
match send(&subscription, payload.to_string().into_bytes(), &config).await {
|
||||
Ok(status)
|
||||
if status == reqwest::StatusCode::NOT_FOUND
|
||||
|| status == reqwest::StatusCode::GONE =>
|
||||
{
|
||||
subscription.status = "archived".to_string();
|
||||
subscription.updated_at = chrono::Utc::now().naive_utc();
|
||||
if let Err(error) = subscription.save(db).await {
|
||||
tracing::warn!(%error, "failed to archive expired Web Push subscription");
|
||||
}
|
||||
}
|
||||
Ok(status) if status.is_success() => {}
|
||||
Ok(status) => tracing::warn!(%status, "Web Push gateway rejected notification"),
|
||||
Err(error) => tracing::warn!(%error, "failed to send Web Push notification"),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
async fn send(
|
||||
subscription: &PushSubscription,
|
||||
content: Vec<u8>,
|
||||
config: &VapidConfig,
|
||||
) -> Result<reqwest::StatusCode, Box<dyn std::error::Error + Send + Sync>> {
|
||||
let private = URL_SAFE_NO_PAD.decode(&config.private_key)?;
|
||||
let key_pair = ES256KeyPair::from_bytes(&private)?;
|
||||
let p256dh = URL_SAFE_NO_PAD.decode(&subscription.p256dh)?;
|
||||
let auth = URL_SAFE_NO_PAD.decode(&subscription.auth)?;
|
||||
let builder = WebPushBuilder::new(
|
||||
subscription.endpoint.parse()?,
|
||||
PublicKey::from_sec1_bytes(&p256dh)?,
|
||||
Auth::clone_from_slice(&auth),
|
||||
)
|
||||
.with_vapid(&key_pair, &config.subject);
|
||||
let request = builder.build(content)?;
|
||||
let (parts, body) = request.into_parts();
|
||||
let response = reqwest::Client::builder()
|
||||
.timeout(std::time::Duration::from_secs(10))
|
||||
.build()?
|
||||
.request(parts.method, parts.uri.to_string())
|
||||
.headers(parts.headers)
|
||||
.body(body)
|
||||
.send()
|
||||
.await?;
|
||||
Ok(response.status())
|
||||
}
|
||||
Binary file not shown.
|
After Width: | Height: | Size: 272 KiB |
Binary file not shown.
|
After Width: | Height: | Size: 457 KiB |
@@ -76,11 +76,16 @@
|
||||
<form method="post" action="/admin/clients/{{ client_id }}/archive">
|
||||
<button type="submit" class="button is-warning is-outlined is-fullwidth">{{ t.action_archive }}</button>
|
||||
</form>
|
||||
{% else %}
|
||||
{% else if client_status == "archived" %}
|
||||
<form method="post" action="/admin/clients/{{ client_id }}/activate">
|
||||
<button type="submit" class="button is-success is-outlined is-fullwidth">{{ t.action_activate }}</button>
|
||||
</form>
|
||||
{% endif %}
|
||||
{% if client_status != "deleted" %}
|
||||
<form method="post" action="/admin/clients/{{ client_id }}/delete" onsubmit="return confirm('{{ t.clients_delete_confirm }}');" style="margin-top:0.75rem;">
|
||||
<button type="submit" class="button is-danger is-outlined is-fullwidth">{{ t.clients_delete }}</button>
|
||||
</form>
|
||||
{% endif %}
|
||||
{% endif %}
|
||||
</div>
|
||||
{% endblock %}
|
||||
|
||||
@@ -47,19 +47,37 @@
|
||||
{% endfor %}
|
||||
{% endif %}
|
||||
|
||||
<!-- Recent feedbacks -->
|
||||
<!-- Feedbacks -->
|
||||
<h2 style="font-size:1.15rem;font-weight:700;margin:1.5rem 0 0.75rem;">{{ t.dashboard_recent_feedbacks }}</h2>
|
||||
{% if recent_feedbacks.is_empty() %}
|
||||
{% if feedbacks.is_empty() %}
|
||||
<p class="has-text-grey">{{ t.dashboard_no_feedbacks }}</p>
|
||||
{% else %}
|
||||
{% for fb in &recent_feedbacks %}
|
||||
<div class="item-card" style="border-left:3px solid #7c6cff;">
|
||||
{% for fb in &feedbacks %}
|
||||
<a href="/admin/schedule/{{ fb.visit_id }}/edit?lang={{ lang.code() }}" class="item-card" style="border-left:3px solid #7c6cff;display:block;text-decoration:none;color:inherit;">
|
||||
<div style="display:flex;justify-content:space-between;align-items:center;margin-bottom:0.25rem;">
|
||||
<strong style="font-size:0.9rem;">{{ fb.client_name }}</strong>
|
||||
<a href="/admin/schedule/{{ fb.visit_id }}/edit?lang={{ lang.code() }}" style="color:#999;font-size:0.8rem;text-decoration:none;">{{ fb.visit_date }}</a>
|
||||
<span style="color:#999;font-size:0.8rem;">{{ fb.visit_date }}</span>
|
||||
</div>
|
||||
<div style="font-size:0.85rem;color:#4a4570;">{{ fb.feedback }}</div>
|
||||
</div>
|
||||
</a>
|
||||
{% endfor %}
|
||||
|
||||
{% if feedback_total_pages > 1 %}
|
||||
<div style="display:flex;justify-content:center;gap:0.5rem;margin-top:1rem;">
|
||||
{% if feedback_page > 1 %}
|
||||
<a href="/admin/?lang={{ lang.code() }}&page={{ feedback_page - 1 }}" class="button is-small is-light">«</a>
|
||||
{% endif %}
|
||||
{% for p in 1..=feedback_total_pages %}
|
||||
{% if p == feedback_page %}
|
||||
<span class="button is-small is-primary">{{ p }}</span>
|
||||
{% else %}
|
||||
<a href="/admin/?lang={{ lang.code() }}&page={{ p }}" class="button is-small is-light">{{ p }}</a>
|
||||
{% endif %}
|
||||
{% endfor %}
|
||||
{% if feedback_page < feedback_total_pages %}
|
||||
<a href="/admin/?lang={{ lang.code() }}&page={{ feedback_page + 1 }}" class="button is-small is-light">»</a>
|
||||
{% endif %}
|
||||
</div>
|
||||
{% endif %}
|
||||
{% endif %}
|
||||
{% endblock %}
|
||||
|
||||
+21
-11
@@ -4,6 +4,7 @@
|
||||
<meta charset="UTF-8">
|
||||
<meta name="viewport" content="width=device-width, initial-scale=1.0">
|
||||
<title>{{ t.nav_title }} — {% block title %}{% endblock %}</title>
|
||||
<link rel="icon" type="image/svg+xml" href="/favicon.svg">
|
||||
<link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/bulma@1/css/bulma.min.css">
|
||||
<style>
|
||||
:root { --accent: #6c63ff; color-scheme: light; }
|
||||
@@ -25,15 +26,24 @@
|
||||
position: fixed; bottom: 0; left: 0; right: 0; z-index: 30;
|
||||
background: #fff; border-top: 1px solid #e8e8e8;
|
||||
display: flex; height: 3.5rem;
|
||||
overflow-x: auto; -webkit-overflow-scrolling: touch;
|
||||
scrollbar-width: none;
|
||||
}
|
||||
.bottom-tabs::-webkit-scrollbar { display: none; }
|
||||
.bottom-tabs a {
|
||||
flex: 1; display: flex; flex-direction: column; align-items: center;
|
||||
flex: 0 0 auto; min-width: 3.2rem; padding: 0 0.45rem;
|
||||
display: flex; flex-direction: column; align-items: center;
|
||||
justify-content: center; text-decoration: none; color: #999;
|
||||
font-size: 0.65rem; font-weight: 600; gap: 0.15rem;
|
||||
transition: color 0.15s;
|
||||
font-size: 0.6rem; font-weight: 600; gap: 0.1rem;
|
||||
transition: color 0.15s; white-space: nowrap;
|
||||
}
|
||||
.bottom-tabs a .tab-icon { font-size: 1.25rem; line-height: 1; }
|
||||
.bottom-tabs a .tab-label { display: block; }
|
||||
.bottom-tabs a.is-active { color: var(--accent); }
|
||||
@media (max-width: 400px) {
|
||||
.bottom-tabs a .tab-label { display: none; }
|
||||
.bottom-tabs a { min-width: 2.8rem; padding: 0 0.3rem; }
|
||||
}
|
||||
|
||||
/* ── Desktop: hide bottom tabs, show top nav ── */
|
||||
.desktop-nav { display: none; }
|
||||
@@ -134,28 +144,28 @@
|
||||
<!-- Bottom tabs (mobile) -->
|
||||
<nav class="bottom-tabs">
|
||||
<a href="/admin/?lang={{ lang.code() }}" {% if active_page == "dashboard" %}class="is-active"{% endif %}>
|
||||
<span class="tab-icon">🏠</span>{{ t.dashboard_title }}
|
||||
<span class="tab-icon">🏠</span><span class="tab-label">{{ t.dashboard_title }}</span>
|
||||
</a>
|
||||
<a href="/admin/leads?lang={{ lang.code() }}" {% if active_page == "leads" %}class="is-active"{% endif %}>
|
||||
<span class="tab-icon">📋</span>{{ t.nav_leads }}
|
||||
<span class="tab-icon">📋</span><span class="tab-label">{{ t.nav_leads }}</span>
|
||||
</a>
|
||||
<a href="/admin/clients?lang={{ lang.code() }}" {% if active_page == "clients" %}class="is-active"{% endif %}>
|
||||
<span class="tab-icon">👥</span>{{ t.nav_clients }}
|
||||
<span class="tab-icon">👥</span><span class="tab-label">{{ t.nav_clients }}</span>
|
||||
</a>
|
||||
<a href="/admin/schedule?lang={{ lang.code() }}" {% if active_page == "schedule" %}class="is-active"{% endif %}>
|
||||
<span class="tab-icon">📅</span>{{ t.nav_schedule }}
|
||||
<span class="tab-icon">📅</span><span class="tab-label">{{ t.nav_schedule }}</span>
|
||||
</a>
|
||||
<a href="/admin/media?lang={{ lang.code() }}" {% if active_page == "media" %}class="is-active"{% endif %}>
|
||||
<span class="tab-icon">📷</span>{{ t.nav_media }}
|
||||
<span class="tab-icon">📷</span><span class="tab-label">{{ t.nav_media }}</span>
|
||||
</a>
|
||||
<a href="/admin/testimonials?lang={{ lang.code() }}" {% if active_page == "testimonials" %}class="is-active"{% endif %}>
|
||||
<span class="tab-icon">💬</span>{{ t.nav_testimonials }}
|
||||
<span class="tab-icon">💬</span><span class="tab-label">{{ t.nav_testimonials }}</span>
|
||||
</a>
|
||||
<a href="/admin/users?lang={{ lang.code() }}" {% if active_page == "users" %}class="is-active"{% endif %}>
|
||||
<span class="tab-icon">🔑</span>{{ t.nav_users }}
|
||||
<span class="tab-icon">🔑</span><span class="tab-label">{{ t.nav_users }}</span>
|
||||
</a>
|
||||
<a href="/admin/settings?lang={{ lang.code() }}" {% if active_page == "settings" %}class="is-active"{% endif %}>
|
||||
<span class="tab-icon">⚙️</span>{{ t.nav_settings }}
|
||||
<span class="tab-icon">⚙️</span><span class="tab-label">{{ t.nav_settings }}</span>
|
||||
</a>
|
||||
</nav>
|
||||
|
||||
|
||||
@@ -33,12 +33,6 @@
|
||||
</div>
|
||||
{% if lead.status == "new" || lead.status == "in_progress" %}
|
||||
<div class="item-card-actions">
|
||||
{% if lead.status == "new" %}
|
||||
<form method="post" action="/admin/leads/{{ lead.id }}/status">
|
||||
<input type="hidden" name="status" value="in_progress">
|
||||
<button type="submit" class="button is-small is-info is-outlined btn-sm">{{ t.action_in_progress }}</button>
|
||||
</form>
|
||||
{% endif %}
|
||||
<form method="post" action="/admin/leads/{{ lead.id }}/convert">
|
||||
<button type="submit" class="button is-small is-success is-outlined btn-sm">{{ t.action_convert }}</button>
|
||||
</form>
|
||||
|
||||
@@ -4,11 +4,21 @@
|
||||
<meta charset="UTF-8">
|
||||
<meta name="viewport" content="width=device-width, initial-scale=1.0">
|
||||
<title>{{ t.nav_title }} — {{ t.login_title }}</title>
|
||||
<link rel="icon" type="image/svg+xml" href="/favicon.svg">
|
||||
<link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/bulma@1/css/bulma.min.css">
|
||||
{% if !turnstile_site_key.is_empty() %}
|
||||
<script src="https://challenges.cloudflare.com/turnstile/v0/api.js" async defer></script>
|
||||
{% endif %}
|
||||
<style>
|
||||
body { background: #f5f5f5; display: flex; align-items: center; justify-content: center; min-height: 100vh; }
|
||||
:root { color-scheme: light; }
|
||||
body { background: #f5f5f5; display: flex; align-items: center; justify-content: center; min-height: 100vh; color: #333; }
|
||||
.login-box { width: 100%; max-width: 380px; padding: 0 1rem; }
|
||||
.login-card { background: #fff; border-radius: 12px; padding: 2rem 1.5rem; box-shadow: 0 2px 12px rgba(0,0,0,0.06); }
|
||||
input, textarea, select, .input, .textarea, .select select {
|
||||
background-color: #fff !important; color: #333 !important; border-color: #dbdbdb !important;
|
||||
}
|
||||
.label, label { color: #363636 !important; }
|
||||
.notification { color: #333 !important; }
|
||||
</style>
|
||||
</head>
|
||||
<body>
|
||||
@@ -25,6 +35,11 @@
|
||||
{% if let Some(err) = error.as_ref() %}
|
||||
<div class="notification is-danger is-light">{{ err }}</div>
|
||||
{% endif %}
|
||||
{% if auth_sso_enabled %}
|
||||
<a href="/admin/oidc/start" class="button is-primary is-fullwidth mt-3">{{ t.login_sso_button }}</a>
|
||||
{% endif %}
|
||||
{% if auth_password_enabled %}
|
||||
{% if auth_sso_enabled %}<hr style="margin:1rem 0;">{% endif %}
|
||||
<form method="post" action="/admin/login/submit">
|
||||
<div class="field">
|
||||
<label class="label">{{ t.users_login }}</label>
|
||||
@@ -34,8 +49,12 @@
|
||||
<label class="label">{{ t.users_password }}</label>
|
||||
<div class="control"><input class="input" type="password" name="password" required></div>
|
||||
</div>
|
||||
{% if !turnstile_site_key.is_empty() %}
|
||||
<div class="cf-turnstile" data-sitekey="{{ turnstile_site_key }}" data-theme="light" style="margin-top:0.75rem;"></div>
|
||||
{% endif %}
|
||||
<button type="submit" class="button is-primary is-fullwidth mt-3">{{ t.login_button }}</button>
|
||||
</form>
|
||||
{% endif %}
|
||||
</div>
|
||||
</div>
|
||||
</body>
|
||||
|
||||
+47
-10
@@ -27,12 +27,15 @@
|
||||
{% for item in &items %}
|
||||
<div class="media-card">
|
||||
{% if item.media.file_type == "photo" %}
|
||||
<a href="/admin/uploads/{{ item.media.id }}" data-lightbox="photo">
|
||||
<img src="/admin/uploads/{{ item.media.id }}" alt="" loading="lazy">
|
||||
<a href="/admin/uploads/{{ item.media.id.unwrap() }}" data-lightbox="photo">
|
||||
<img src="/admin/uploads/{{ item.media.id.unwrap() }}/thumbnail" alt="" loading="lazy">
|
||||
</a>
|
||||
{% else %}
|
||||
<a href="/admin/uploads/{{ item.media.id }}" data-lightbox="video">
|
||||
<div class="video-thumb">🎬</div>
|
||||
<a href="/admin/uploads/{{ item.media.id.unwrap() }}" data-lightbox="video">
|
||||
<div class="video-thumb">
|
||||
<video src="/admin/uploads/{{ item.media.id.unwrap() }}#t=0.1" preload="metadata" muted playsinline></video>
|
||||
<span class="video-play">▶</span>
|
||||
</div>
|
||||
</a>
|
||||
{% endif %}
|
||||
<div class="media-info">
|
||||
@@ -45,13 +48,26 @@
|
||||
{% if let Some(cap) = item.media.caption.as_deref() %}
|
||||
<div style="font-size:0.82rem;color:#666;margin-top:0.2rem;">{{ cap }}</div>
|
||||
{% endif %}
|
||||
<form method="post" action="/admin/media/{{ item.media.id }}/delete" onsubmit="return confirm('{{ t.media_delete_confirm }}');" style="margin-top:0.3rem;">
|
||||
<form method="post" action="/admin/media/{{ item.media.id.unwrap() }}/delete" onsubmit="return confirm('{{ t.media_delete_confirm }}');" style="margin-top:0.3rem;">
|
||||
<button class="button is-small is-danger is-outlined btn-sm">{{ t.media_delete }}</button>
|
||||
</form>
|
||||
</div>
|
||||
</div>
|
||||
{% endfor %}
|
||||
</div>
|
||||
{% if total_pages > 1 %}
|
||||
<nav class="media-pagination" aria-label="Pagination">
|
||||
{% if page > 1 %}
|
||||
<a class="button is-small" href="/admin/media?lang={{ lang.code() }}&page={{ page - 1 }}{% if filter_client_id > 0 %}&client_id={{ filter_client_id }}{% endif %}">←</a>
|
||||
{% endif %}
|
||||
{% for p in 1..=total_pages %}
|
||||
<a class="button is-small{% if p == page %} is-link{% endif %}" href="/admin/media?lang={{ lang.code() }}&page={{ p }}{% if filter_client_id > 0 %}&client_id={{ filter_client_id }}{% endif %}">{{ p }}</a>
|
||||
{% endfor %}
|
||||
{% if page < total_pages %}
|
||||
<a class="button is-small" href="/admin/media?lang={{ lang.code() }}&page={{ page + 1 }}{% if filter_client_id > 0 %}&client_id={{ filter_client_id }}{% endif %}">→</a>
|
||||
{% endif %}
|
||||
</nav>
|
||||
{% endif %}
|
||||
{% endif %}
|
||||
|
||||
<style>
|
||||
@@ -73,17 +89,38 @@
|
||||
display: block;
|
||||
}
|
||||
.media-card .video-thumb {
|
||||
position: relative;
|
||||
width: 100%;
|
||||
height: 160px;
|
||||
display: flex;
|
||||
align-items: center;
|
||||
justify-content: center;
|
||||
font-size: 3rem;
|
||||
background: #f0f0f0;
|
||||
background: #111;
|
||||
}
|
||||
.media-card .video-thumb video {
|
||||
width: 100%;
|
||||
height: 100%;
|
||||
display: block;
|
||||
object-fit: cover;
|
||||
}
|
||||
.media-card .video-play {
|
||||
position: absolute;
|
||||
top: 50%;
|
||||
left: 50%;
|
||||
transform: translate(-50%, -50%);
|
||||
color: white;
|
||||
font-size: 2.5rem;
|
||||
line-height: 1;
|
||||
text-shadow: 0 1px 5px #000;
|
||||
pointer-events: none;
|
||||
}
|
||||
.media-info {
|
||||
padding: 0.6rem 0.75rem;
|
||||
}
|
||||
.media-pagination {
|
||||
display: flex;
|
||||
flex-wrap: wrap;
|
||||
justify-content: center;
|
||||
gap: 0.35rem;
|
||||
margin-top: 1.25rem;
|
||||
}
|
||||
.media-meta {
|
||||
display: flex;
|
||||
justify-content: space-between;
|
||||
|
||||
@@ -14,12 +14,13 @@
|
||||
<div><strong>{{ t.schedule_date }}:</strong> {{ visit_label }}</div>
|
||||
</div>
|
||||
|
||||
<form method="post" action="/admin/media/{{ visit_id }}/upload/submit" enctype="multipart/form-data">
|
||||
<form id="uploadForm" action="/admin/media/{{ visit_id }}/upload/submit" enctype="multipart/form-data">
|
||||
<div class="field">
|
||||
<label class="label">{{ t.media_choose_files }}</label>
|
||||
<div class="control">
|
||||
<input class="input" type="file" name="files" multiple accept="image/*,video/*" required>
|
||||
<input class="input" type="file" id="uploadFiles" name="files" multiple accept="image/*,video/*" required>
|
||||
</div>
|
||||
<p id="fileCount" style="font-size:0.8rem;color:#888;margin-top:0.3rem;"></p>
|
||||
</div>
|
||||
|
||||
<div class="field">
|
||||
@@ -29,7 +30,80 @@
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<button type="submit" class="button is-primary is-fullwidth">{{ t.media_upload }}</button>
|
||||
<!-- Progress -->
|
||||
<div id="uploadProgress" style="display:none;margin-bottom:1rem;">
|
||||
<div style="display:flex;justify-content:space-between;font-size:0.82rem;color:#555;margin-bottom:0.3rem;">
|
||||
<span id="uploadStatusText">{{ t.media_upload }}...</span>
|
||||
<span id="uploadPercent">0%</span>
|
||||
</div>
|
||||
<div style="background:#e8e8e8;border-radius:99px;height:8px;overflow:hidden;">
|
||||
<div id="uploadBar" style="height:100%;width:0%;background:linear-gradient(90deg,#6c63ff,#b06cff);border-radius:99px;transition:width 0.2s;"></div>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<button type="submit" id="uploadSubmit" class="button is-primary is-fullwidth">{{ t.media_upload }}</button>
|
||||
</form>
|
||||
|
||||
<script>
|
||||
(function() {
|
||||
var form = document.getElementById('uploadForm');
|
||||
var filesInput = document.getElementById('uploadFiles');
|
||||
var fileCount = document.getElementById('fileCount');
|
||||
var progress = document.getElementById('uploadProgress');
|
||||
var bar = document.getElementById('uploadBar');
|
||||
var percent = document.getElementById('uploadPercent');
|
||||
var statusText = document.getElementById('uploadStatusText');
|
||||
var submitBtn = document.getElementById('uploadSubmit');
|
||||
|
||||
filesInput.addEventListener('change', function() {
|
||||
var n = this.files.length;
|
||||
fileCount.textContent = n > 0 ? ('Выбрано файлов: ' + n) : '';
|
||||
});
|
||||
|
||||
form.addEventListener('submit', function(e) {
|
||||
e.preventDefault();
|
||||
if (!filesInput.files.length) return;
|
||||
|
||||
var data = new FormData(form);
|
||||
var xhr = new XMLHttpRequest();
|
||||
|
||||
progress.style.display = 'block';
|
||||
submitBtn.disabled = true;
|
||||
submitBtn.textContent = 'Загрузка...';
|
||||
bar.style.width = '0%';
|
||||
percent.textContent = '0%';
|
||||
|
||||
xhr.upload.addEventListener('progress', function(ev) {
|
||||
if (!ev.lengthComputable) return;
|
||||
var pct = Math.round(ev.loaded / ev.total * 100);
|
||||
bar.style.width = pct + '%';
|
||||
percent.textContent = pct + '%';
|
||||
if (pct === 100) statusText.textContent = 'Обработка...';
|
||||
});
|
||||
|
||||
xhr.addEventListener('load', function() {
|
||||
if (xhr.status >= 200 && xhr.status < 400) {
|
||||
bar.style.width = '100%';
|
||||
percent.textContent = '100%';
|
||||
statusText.textContent = 'Готово!';
|
||||
setTimeout(function() { window.location.href = xhr.responseURL || '/admin/media'; }, 300);
|
||||
} else {
|
||||
statusText.textContent = 'Ошибка загрузки (' + xhr.status + ')';
|
||||
submitBtn.disabled = false;
|
||||
submitBtn.textContent = '{{ t.media_upload }}';
|
||||
}
|
||||
});
|
||||
|
||||
xhr.addEventListener('error', function() {
|
||||
statusText.textContent = 'Ошибка соединения';
|
||||
submitBtn.disabled = false;
|
||||
submitBtn.textContent = '{{ t.media_upload }}';
|
||||
});
|
||||
|
||||
xhr.open('POST', form.action);
|
||||
xhr.send(data);
|
||||
});
|
||||
})();
|
||||
</script>
|
||||
</div>
|
||||
{% endblock %}
|
||||
|
||||
@@ -32,6 +32,10 @@
|
||||
.fc .fc-toolbar-title { font-size: 1.1rem !important; }
|
||||
.fc .fc-button { padding: 0.25rem 0.5rem !important; font-size: 0.8rem !important; }
|
||||
.fc-event { cursor: pointer; border: none !important; padding: 2px 5px; border-radius: 4px; }
|
||||
.fc-event.ev-completed .fc-event-title,
|
||||
.fc-event.ev-completed .fc-list-event-title { text-decoration: line-through; opacity: 0.75; }
|
||||
.fc-event.ev-cancelled .fc-event-title,
|
||||
.fc-event.ev-cancelled .fc-list-event-title { text-decoration: line-through; }
|
||||
.fc .fc-day-today { background: #eef2ff !important; }
|
||||
.fc .fc-day.day-weekend { background: #faf5f0; }
|
||||
.fc .fc-day-today.day-weekend { background: #eef2ff !important; }
|
||||
@@ -45,8 +49,6 @@
|
||||
.visit-modal { background:#fff; border-radius:12px; padding:1.5rem; width:90%; max-width:380px; box-shadow:0 4px 24px rgba(0,0,0,0.15); }
|
||||
.visit-modal h3 { margin:0 0 0.75rem; font-size:1.1rem; }
|
||||
.visit-modal .meta { color:#888; font-size:0.85rem; margin-bottom:0.75rem; line-height:1.6; }
|
||||
.visit-modal .actions { display:flex; gap:0.5rem; flex-wrap:wrap; }
|
||||
.visit-modal .actions form { margin:0; }
|
||||
.color-dot { display:inline-block; width:12px; height:12px; border-radius:50%; margin-right:6px; vertical-align:middle; }
|
||||
</style>
|
||||
|
||||
@@ -60,12 +62,8 @@
|
||||
<div id="vmTime"></div>
|
||||
<div id="vmNotes" style="margin-top:0.3rem;"></div>
|
||||
</div>
|
||||
<div id="vmStatus" style="margin-bottom:0.75rem;"></div>
|
||||
<div class="actions" id="vmActions"></div>
|
||||
<div style="display:flex;gap:0.5rem;margin-top:0.5rem;">
|
||||
<a id="vmEditLink" href="#" class="button is-info is-small" style="flex:1;">{{ t.schedule_edit_title }}</a>
|
||||
<button class="button is-light is-small" style="flex:1;" onclick="closeModal()">OK</button>
|
||||
</div>
|
||||
<div id="vmStatus" style="margin-bottom:1rem;"></div>
|
||||
<a id="vmEditLink" href="#" class="button is-primary is-fullwidth" style="font-size:1rem;font-weight:700;padding:0.65rem;">📋 {{ t.schedule_edit_title }}</a>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
@@ -81,6 +79,7 @@ document.addEventListener('DOMContentLoaded', function() {
|
||||
|
||||
const calendar = new FullCalendar.Calendar(calEl, {
|
||||
locale: lang,
|
||||
timeZone: '{{ timezone }}',
|
||||
initialView: window.innerWidth < 768 ? 'listWeek' : 'dayGridMonth',
|
||||
headerToolbar: {
|
||||
left: 'prev,next today',
|
||||
@@ -88,6 +87,11 @@ document.addEventListener('DOMContentLoaded', function() {
|
||||
right: 'dayGridMonth,timeGridWeek,timeGridDay,listWeek'
|
||||
},
|
||||
events: '/admin/schedule/events',
|
||||
eventDidMount: function(info) {
|
||||
var status = info.event.extendedProps.status;
|
||||
if (status === 'completed') info.el.classList.add('ev-completed');
|
||||
if (status === 'cancelled') info.el.classList.add('ev-cancelled');
|
||||
},
|
||||
eventClick: function(info) {
|
||||
info.jsEvent.preventDefault();
|
||||
const ev = info.event;
|
||||
@@ -101,12 +105,6 @@ document.addEventListener('DOMContentLoaded', function() {
|
||||
document.getElementById('vmNotes').textContent = p.notes || '';
|
||||
const badge = '<span class="badge badge-visit-' + p.status + '">' + statusLabels[p.status] + '</span>';
|
||||
document.getElementById('vmStatus').innerHTML = badge;
|
||||
let actions = '';
|
||||
if (p.status === 'scheduled') {
|
||||
actions += '<form method="post" action="/admin/schedule/' + ev.id + '/done"><button class="button is-small is-success is-outlined">{{ t.schedule_mark_done }}</button></form>';
|
||||
actions += '<form method="post" action="/admin/schedule/' + ev.id + '/cancel"><button class="button is-small is-danger is-outlined">{{ t.schedule_cancel }}</button></form>';
|
||||
}
|
||||
document.getElementById('vmActions').innerHTML = actions;
|
||||
document.getElementById('vmEditLink').href = '/admin/schedule/' + ev.id + '/edit?lang=' + lang;
|
||||
document.getElementById('visitModal').classList.add('is-open');
|
||||
},
|
||||
|
||||
@@ -14,15 +14,7 @@
|
||||
<div class="field">
|
||||
<label class="label">{{ t.schedule_client }}</label>
|
||||
<div class="control">
|
||||
<div class="select is-fullwidth">
|
||||
<select name="client_id" required>
|
||||
{% for c in &clients %}
|
||||
<option value="{{ c.id }}" {% if c.id.unwrap() == visit.client_id.primary_key().unwrap() %}selected{% endif %}>
|
||||
{{ c.name }}{% if let Some(p) = c.phone.as_deref() %} ({{ p }}){% endif %}
|
||||
</option>
|
||||
{% endfor %}
|
||||
</select>
|
||||
</div>
|
||||
<input class="input" type="text" value="{{ client.name }}{% if let Some(p) = client.phone.as_deref() %} ({{ p }}){% endif %}" readonly>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
@@ -70,14 +62,17 @@
|
||||
<!-- Status -->
|
||||
<div class="field">
|
||||
<label class="label">{{ t.schedule_status }}</label>
|
||||
<div class="control">
|
||||
<div class="select is-fullwidth">
|
||||
<select name="status">
|
||||
<option value="scheduled" {% if visit.status == "scheduled" %}selected{% endif %}>{{ t.visit_status_scheduled }}</option>
|
||||
<option value="completed" {% if visit.status == "completed" %}selected{% endif %}>{{ t.visit_status_completed }}</option>
|
||||
<option value="cancelled" {% if visit.status == "cancelled" %}selected{% endif %}>{{ t.visit_status_cancelled }}</option>
|
||||
</select>
|
||||
</div>
|
||||
<input type="hidden" name="status" id="statusInput" value="{{ visit.status }}">
|
||||
<div class="status-picker">
|
||||
<button type="button" class="status-btn status-btn-scheduled {% if visit.status == "scheduled" %}is-active{% endif %}" data-value="scheduled">
|
||||
<span class="status-btn-icon">📅</span>{{ t.visit_status_scheduled }}
|
||||
</button>
|
||||
<button type="button" class="status-btn status-btn-completed {% if visit.status == "completed" %}is-active{% endif %}" data-value="completed">
|
||||
<span class="status-btn-icon">✅</span>{{ t.visit_status_completed }}
|
||||
</button>
|
||||
<button type="button" class="status-btn status-btn-cancelled {% if visit.status == "cancelled" %}is-active{% endif %}" data-value="cancelled">
|
||||
<span class="status-btn-icon">✕</span>{{ t.visit_status_cancelled }}
|
||||
</button>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
@@ -97,48 +92,56 @@
|
||||
</div>
|
||||
</div>
|
||||
|
||||
{% if let Some(fb) = visit.client_feedback.as_deref() %}
|
||||
<div style="margin-bottom:1rem;">
|
||||
<label class="label">{{ t.schedule_client_feedback }}</label>
|
||||
<div style="background:#f0f0ff;border-radius:8px;padding:0.6rem 0.85rem;font-size:0.9rem;color:#4a4570;">{{ fb }}</div>
|
||||
</div>
|
||||
{% endif %}
|
||||
|
||||
<hr style="margin:1rem 0;">
|
||||
|
||||
<!-- Media -->
|
||||
<div style="display:flex;align-items:center;justify-content:space-between;margin-bottom:0.75rem;">
|
||||
<label class="label" style="margin:0;">{{ t.nav_media }}</label>
|
||||
<button type="button" class="button is-info is-small is-outlined" onclick="document.getElementById('uploadModal').classList.add('is-open')">+ {{ t.media_upload }}</button>
|
||||
</div>
|
||||
{% if media.is_empty() %}
|
||||
<p class="has-text-grey is-size-7" style="margin-bottom:1rem;">{{ t.media_empty }}</p>
|
||||
{% else %}
|
||||
<div class="visit-media-grid">
|
||||
{% for m in &media %}
|
||||
<div class="visit-media-item">
|
||||
{% if m.file_type == "photo" %}
|
||||
<a href="/admin/uploads/{{ m.id.unwrap() }}" data-lightbox="photo">
|
||||
<img src="/admin/uploads/{{ m.id.unwrap() }}/thumbnail" alt="" loading="lazy">
|
||||
</a>
|
||||
{% else %}
|
||||
<a href="/admin/uploads/{{ m.id.unwrap() }}" data-lightbox="video">
|
||||
<div class="video-thumb-sm">
|
||||
<video src="/admin/uploads/{{ m.id.unwrap() }}#t=0.1" preload="metadata" muted playsinline></video>
|
||||
<span class="video-play">▶</span>
|
||||
</div>
|
||||
</a>
|
||||
{% endif %}
|
||||
{% if let Some(cap) = m.caption.as_deref() %}
|
||||
<div class="media-cap">{{ cap }}</div>
|
||||
{% endif %}
|
||||
<div class="visit-media-delete">
|
||||
<button type="submit" form="visit-media-delete-{{ m.id.unwrap() }}" class="button is-small is-danger is-outlined">{{ t.media_delete }}</button>
|
||||
</div>
|
||||
</div>
|
||||
{% endfor %}
|
||||
</div>
|
||||
{% endif %}
|
||||
|
||||
<hr style="margin:1rem 0;">
|
||||
|
||||
<button type="submit" class="button is-primary is-fullwidth">{{ t.schedule_save }}</button>
|
||||
</form>
|
||||
|
||||
{% if let Some(fb) = visit.client_feedback.as_deref() %}
|
||||
<div style="margin-top:1rem;">
|
||||
<label class="label">{{ t.schedule_client_feedback }}</label>
|
||||
<div style="background:#f0f0ff;border-radius:8px;padding:0.6rem 0.85rem;font-size:0.9rem;color:#4a4570;">{{ fb }}</div>
|
||||
</div>
|
||||
{% endif %}
|
||||
|
||||
<hr style="margin:1rem 0;">
|
||||
|
||||
<!-- Media -->
|
||||
<div style="display:flex;align-items:center;justify-content:space-between;margin-bottom:0.75rem;">
|
||||
<label class="label" style="margin:0;">{{ t.nav_media }}</label>
|
||||
<a href="/admin/media/{{ visit.id }}/upload?lang={{ lang.code() }}" class="button is-info is-small is-outlined">📷 {{ t.media_upload }}</a>
|
||||
</div>
|
||||
{% if media.is_empty() %}
|
||||
<p class="has-text-grey is-size-7" style="margin-bottom:1rem;">{{ t.media_empty }}</p>
|
||||
{% else %}
|
||||
<div class="visit-media-grid">
|
||||
{% for m in &media %}
|
||||
<div class="visit-media-item">
|
||||
{% if m.file_type == "photo" %}
|
||||
<a href="/admin/uploads/{{ m.id }}" data-lightbox="photo">
|
||||
<img src="/admin/uploads/{{ m.id }}" alt="" loading="lazy">
|
||||
</a>
|
||||
{% else %}
|
||||
<a href="/admin/uploads/{{ m.id }}" data-lightbox="video">
|
||||
<div class="video-thumb-sm">🎬</div>
|
||||
</a>
|
||||
{% endif %}
|
||||
{% if let Some(cap) = m.caption.as_deref() %}
|
||||
<div class="media-cap">{{ cap }}</div>
|
||||
{% endif %}
|
||||
<form method="post" action="/admin/media/{{ m.id }}/delete" onsubmit="return confirm('{{ t.media_delete_confirm }}');" style="text-align:center;">
|
||||
<button class="button is-danger is-outlined btn-sm" style="font-size:0.7rem;padding:0.15rem 0.4rem;">{{ t.media_delete }}</button>
|
||||
</form>
|
||||
</div>
|
||||
{% endfor %}
|
||||
</div>
|
||||
{% endif %}
|
||||
{% for m in &media %}
|
||||
<form id="visit-media-delete-{{ m.id.unwrap() }}" method="post" action="/admin/media/{{ m.id.unwrap() }}/delete" onsubmit="return confirm('{{ t.media_delete_confirm }}');"></form>
|
||||
{% endfor %}
|
||||
|
||||
<hr style="margin:1rem 0;">
|
||||
<form method="post" action="/admin/schedule/{{ visit.id }}/delete" onsubmit="return confirm('{{ t.schedule_delete_confirm }}');">
|
||||
@@ -146,7 +149,77 @@
|
||||
</form>
|
||||
</div>
|
||||
|
||||
<!-- Upload Modal -->
|
||||
<div class="upload-modal-bg" id="uploadModal">
|
||||
<div class="upload-modal">
|
||||
<div style="display:flex;justify-content:space-between;align-items:center;margin-bottom:1rem;">
|
||||
<h3 style="font-size:1.1rem;font-weight:700;margin:0;">{{ t.media_upload_title }}</h3>
|
||||
<button type="button" id="uploadModalClose" style="background:none;border:none;font-size:1.2rem;cursor:pointer;color:#888;">✕</button>
|
||||
</div>
|
||||
<form id="uploadForm" action="/admin/media/{{ visit.id }}/upload/submit" enctype="multipart/form-data">
|
||||
<div class="field">
|
||||
<label class="label">{{ t.media_choose_files }}</label>
|
||||
<div class="control">
|
||||
<input class="input" type="file" id="uploadFiles" name="files" multiple accept="image/*,video/*" required>
|
||||
</div>
|
||||
<p id="fileCount" style="font-size:0.8rem;color:#888;margin-top:0.3rem;"></p>
|
||||
</div>
|
||||
<div class="field">
|
||||
<label class="label">{{ t.media_caption }}</label>
|
||||
<div class="control">
|
||||
<input class="input" type="text" name="caption" placeholder="{{ t.media_caption }}">
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<!-- Progress -->
|
||||
<div id="uploadProgress" style="display:none;margin-bottom:1rem;">
|
||||
<div style="display:flex;justify-content:space-between;font-size:0.82rem;color:#555;margin-bottom:0.3rem;">
|
||||
<span id="uploadStatusText">{{ t.media_upload }}...</span>
|
||||
<span id="uploadPercent">0%</span>
|
||||
</div>
|
||||
<div style="background:#e8e8e8;border-radius:99px;height:8px;overflow:hidden;">
|
||||
<div id="uploadBar" style="height:100%;width:0%;background:linear-gradient(90deg,#6c63ff,#b06cff);border-radius:99px;transition:width 0.2s;"></div>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<button type="submit" id="uploadSubmit" class="button is-primary is-fullwidth">{{ t.media_upload }}</button>
|
||||
</form>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<style>
|
||||
.status-picker {
|
||||
display: flex;
|
||||
gap: 0.5rem;
|
||||
}
|
||||
.status-btn {
|
||||
flex: 1;
|
||||
display: flex;
|
||||
flex-direction: column;
|
||||
align-items: center;
|
||||
gap: 0.3rem;
|
||||
padding: 0.6rem 0.4rem;
|
||||
border-radius: 10px;
|
||||
border: 2px solid transparent;
|
||||
background: #f5f5f5;
|
||||
font-size: 0.82rem;
|
||||
font-weight: 600;
|
||||
cursor: pointer;
|
||||
color: #777;
|
||||
transition: all 0.15s;
|
||||
line-height: 1.2;
|
||||
}
|
||||
.status-btn-icon { font-size: 1.3rem; line-height: 1; }
|
||||
.status-btn:hover { filter: brightness(0.95); }
|
||||
|
||||
.status-btn-scheduled.is-active { background: #dbeafe; border-color: #3b82f6; color: #1e40af; }
|
||||
.status-btn-completed.is-active { background: #d1fae5; border-color: #22c55e; color: #15803d; }
|
||||
.status-btn-cancelled.is-active { background: #fee2e2; border-color: #ef4444; color: #b91c1c; }
|
||||
|
||||
.status-btn-scheduled:not(.is-active):hover { background: #eff6ff; color: #3b82f6; }
|
||||
.status-btn-completed:not(.is-active):hover { background: #f0fdf4; color: #22c55e; }
|
||||
.status-btn-cancelled:not(.is-active):hover { background: #fff5f5; color: #ef4444; }
|
||||
|
||||
.visit-media-grid {
|
||||
display: grid;
|
||||
grid-template-columns: repeat(auto-fill, minmax(100px, 1fr));
|
||||
@@ -166,13 +239,27 @@
|
||||
display: block;
|
||||
}
|
||||
.visit-media-item .video-thumb-sm {
|
||||
position: relative;
|
||||
width: 100%;
|
||||
height: 80px;
|
||||
display: flex;
|
||||
align-items: center;
|
||||
justify-content: center;
|
||||
font-size: 2rem;
|
||||
background: #f0f0f0;
|
||||
background: #111;
|
||||
}
|
||||
.visit-media-item .video-thumb-sm video {
|
||||
width: 100%;
|
||||
height: 100%;
|
||||
display: block;
|
||||
object-fit: cover;
|
||||
}
|
||||
.visit-media-item .video-play {
|
||||
position: absolute;
|
||||
top: 50%;
|
||||
left: 50%;
|
||||
transform: translate(-50%, -50%);
|
||||
color: white;
|
||||
font-size: 1.6rem;
|
||||
line-height: 1;
|
||||
text-shadow: 0 1px 4px #000;
|
||||
pointer-events: none;
|
||||
}
|
||||
.visit-media-item .media-cap {
|
||||
font-size: 0.7rem;
|
||||
@@ -182,8 +269,122 @@
|
||||
overflow: hidden;
|
||||
text-overflow: ellipsis;
|
||||
}
|
||||
.visit-media-item form {
|
||||
padding: 0.2rem;
|
||||
.visit-media-delete {
|
||||
padding: 0.25rem 0.4rem 0.4rem;
|
||||
}
|
||||
.visit-media-delete .button {
|
||||
width: 100%;
|
||||
font-size: 0.68rem;
|
||||
min-height: 1.65rem;
|
||||
}
|
||||
.upload-modal-bg {
|
||||
display: none;
|
||||
position: fixed;
|
||||
inset: 0;
|
||||
background: rgba(0,0,0,0.35);
|
||||
z-index: 100;
|
||||
align-items: center;
|
||||
justify-content: center;
|
||||
}
|
||||
.upload-modal-bg.is-open {
|
||||
display: flex;
|
||||
}
|
||||
.upload-modal {
|
||||
background: #fff;
|
||||
border-radius: 12px;
|
||||
padding: 1.5rem;
|
||||
width: 90%;
|
||||
max-width: 420px;
|
||||
box-shadow: 0 4px 24px rgba(0,0,0,0.15);
|
||||
}
|
||||
</style>
|
||||
|
||||
<script>
|
||||
// Status picker
|
||||
document.querySelectorAll('.status-btn').forEach(function(btn) {
|
||||
btn.addEventListener('click', function() {
|
||||
document.querySelectorAll('.status-btn').forEach(function(b) { b.classList.remove('is-active'); });
|
||||
btn.classList.add('is-active');
|
||||
document.getElementById('statusInput').value = btn.dataset.value;
|
||||
});
|
||||
});
|
||||
</script>
|
||||
|
||||
<script>
|
||||
(function() {
|
||||
var modal = document.getElementById('uploadModal');
|
||||
var form = document.getElementById('uploadForm');
|
||||
var filesInput = document.getElementById('uploadFiles');
|
||||
var fileCount = document.getElementById('fileCount');
|
||||
var progress = document.getElementById('uploadProgress');
|
||||
var bar = document.getElementById('uploadBar');
|
||||
var percent = document.getElementById('uploadPercent');
|
||||
var statusText = document.getElementById('uploadStatusText');
|
||||
var submitBtn = document.getElementById('uploadSubmit');
|
||||
|
||||
// Close modal on backdrop click
|
||||
modal.addEventListener('click', function(e) {
|
||||
if (e.target === this) closeModal();
|
||||
});
|
||||
document.getElementById('uploadModalClose').addEventListener('click', closeModal);
|
||||
|
||||
function closeModal() {
|
||||
if (submitBtn.disabled) return; // prevent close during upload
|
||||
modal.classList.remove('is-open');
|
||||
}
|
||||
|
||||
// Show selected file count
|
||||
filesInput.addEventListener('change', function() {
|
||||
var n = this.files.length;
|
||||
fileCount.textContent = n > 0 ? ('Выбрано файлов: ' + n) : '';
|
||||
});
|
||||
|
||||
// Submit via XHR for progress tracking
|
||||
form.addEventListener('submit', function(e) {
|
||||
e.preventDefault();
|
||||
if (!filesInput.files.length) return;
|
||||
|
||||
var data = new FormData(form);
|
||||
var xhr = new XMLHttpRequest();
|
||||
|
||||
// Show progress bar, disable submit
|
||||
progress.style.display = 'block';
|
||||
submitBtn.disabled = true;
|
||||
submitBtn.textContent = 'Загрузка...';
|
||||
bar.style.width = '0%';
|
||||
percent.textContent = '0%';
|
||||
|
||||
xhr.upload.addEventListener('progress', function(ev) {
|
||||
if (!ev.lengthComputable) return;
|
||||
var pct = Math.round(ev.loaded / ev.total * 100);
|
||||
bar.style.width = pct + '%';
|
||||
percent.textContent = pct + '%';
|
||||
if (pct === 100) statusText.textContent = 'Обработка...';
|
||||
});
|
||||
|
||||
xhr.addEventListener('load', function() {
|
||||
if (xhr.status >= 200 && xhr.status < 400) {
|
||||
bar.style.width = '100%';
|
||||
percent.textContent = '100%';
|
||||
statusText.textContent = 'Готово!';
|
||||
// Reload page to show uploaded media
|
||||
setTimeout(function() { window.location.reload(); }, 300);
|
||||
} else {
|
||||
statusText.textContent = 'Ошибка загрузки (' + xhr.status + ')';
|
||||
submitBtn.disabled = false;
|
||||
submitBtn.textContent = '{{ t.media_upload }}';
|
||||
}
|
||||
});
|
||||
|
||||
xhr.addEventListener('error', function() {
|
||||
statusText.textContent = 'Ошибка соединения';
|
||||
submitBtn.disabled = false;
|
||||
submitBtn.textContent = '{{ t.media_upload }}';
|
||||
});
|
||||
|
||||
xhr.open('POST', form.action);
|
||||
xhr.send(data);
|
||||
});
|
||||
})();
|
||||
</script>
|
||||
{% endblock %}
|
||||
|
||||
+347
-164
@@ -9,238 +9,421 @@
|
||||
</div>
|
||||
|
||||
<div class="form-card">
|
||||
<form method="post" action="/admin/schedule/create" id="visitForm">
|
||||
<!-- Client -->
|
||||
<div class="field">
|
||||
<label class="label">{{ t.schedule_client }}</label>
|
||||
<div class="control">
|
||||
<div class="select is-fullwidth">
|
||||
<select name="client_id" required>
|
||||
<option value="">—</option>
|
||||
{% for c in &clients %}
|
||||
<option value="{{ c.id }}">{{ c.name }}{% if let Some(p) = c.phone.as_deref() %} ({{ p }}){% endif %}</option>
|
||||
{% endfor %}
|
||||
</select>
|
||||
</div>
|
||||
<form method="post" action="/admin/schedule/create" id="visitForm">
|
||||
|
||||
<!-- Client -->
|
||||
<div class="field">
|
||||
<label class="label">{{ t.schedule_client }}</label>
|
||||
<div class="control">
|
||||
<div class="select is-fullwidth">
|
||||
<select name="client_id" required>
|
||||
<option value="">—</option>
|
||||
{% for c in &clients %}
|
||||
<option value="{{ c.id }}">{{ c.name }}{% if let Some(p) = c.phone.as_deref() %} ({{ p }}){% endif %}</option>
|
||||
{% endfor %}
|
||||
</select>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<!-- Admin -->
|
||||
<div class="field">
|
||||
<label class="label">{{ t.schedule_admin }}</label>
|
||||
<div class="control">
|
||||
<div class="select is-fullwidth">
|
||||
<select name="user_id">
|
||||
{% for u in &users %}
|
||||
<option value="{{ u.id }}" {% if u.id.unwrap() == current_user_id %}selected{% endif %}>
|
||||
{{ u.display_name.as_deref().unwrap_or(&u.login) }}
|
||||
</option>
|
||||
{% endfor %}
|
||||
</select>
|
||||
</div>
|
||||
<!-- Admin -->
|
||||
<div class="field">
|
||||
<label class="label">{{ t.schedule_admin }}</label>
|
||||
<div class="control">
|
||||
<div class="select is-fullwidth">
|
||||
<select name="user_id">
|
||||
{% for u in &users %}
|
||||
<option value="{{ u.id }}" {% if u.id.unwrap() == current_user_id %}selected{% endif %}>
|
||||
{{ u.display_name.as_deref().unwrap_or(&u.login) }}
|
||||
</option>
|
||||
{% endfor %}
|
||||
</select>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<!-- Default time -->
|
||||
<div class="field">
|
||||
<label class="label">{{ t.schedule_default_time }}</label>
|
||||
<div class="columns is-mobile" style="margin-bottom:0;">
|
||||
<div class="column">
|
||||
<div class="control">
|
||||
<input class="input" type="time" id="defaultStart" value="18:00">
|
||||
</div>
|
||||
</div>
|
||||
<div class="column">
|
||||
<div class="control">
|
||||
<input class="input" type="time" id="defaultEnd" value="19:00">
|
||||
</div>
|
||||
</div>
|
||||
<!-- Default time -->
|
||||
<div class="field">
|
||||
<label class="label">{{ t.schedule_default_time }}</label>
|
||||
<div class="time-row">
|
||||
<div class="time-block">
|
||||
<span class="time-lbl">{{ t.schedule_time_start }}</span>
|
||||
<input class="input" type="time" id="defaultStart" value="18:00">
|
||||
</div>
|
||||
<div class="time-sep">—</div>
|
||||
<div class="time-block">
|
||||
<span class="time-lbl">{{ t.schedule_time_end }}</span>
|
||||
<input class="input" type="time" id="defaultEnd" value="19:00">
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<!-- Add individual date -->
|
||||
<div class="field">
|
||||
<label class="label">{{ t.schedule_pick_dates }}</label>
|
||||
<div class="columns is-mobile" style="margin-bottom:0;">
|
||||
<div class="column">
|
||||
<div class="control">
|
||||
<input class="input" type="date" id="pickDate">
|
||||
</div>
|
||||
</div>
|
||||
<div class="column is-narrow">
|
||||
<button type="button" class="button is-info" id="addDateBtn">+</button>
|
||||
</div>
|
||||
</div>
|
||||
<!-- Calendar -->
|
||||
<div class="field">
|
||||
<div class="cal-toolbar">
|
||||
<button type="button" id="rangeModeBtn" class="button is-small is-outlined is-info">⇔ Выбрать диапазон</button>
|
||||
<button type="button" id="resetBtn" class="button is-small is-outlined is-danger" style="display:none;">✕ Сбросить</button>
|
||||
</div>
|
||||
|
||||
<!-- Date range fill -->
|
||||
<div class="field">
|
||||
<label class="label is-small has-text-grey">{{ t.schedule_range_from }} — {{ t.schedule_range_to }}</label>
|
||||
<div class="columns is-mobile" style="margin-bottom:0;">
|
||||
<div class="column">
|
||||
<input class="input" type="date" id="rangeFrom">
|
||||
</div>
|
||||
<div class="column">
|
||||
<input class="input" type="date" id="rangeTo">
|
||||
</div>
|
||||
<div class="column is-narrow">
|
||||
<button type="button" class="button is-info is-outlined" id="fillRangeBtn">{{ t.schedule_fill_range }}</button>
|
||||
</div>
|
||||
<div class="sched-cal">
|
||||
<div class="cal-nav">
|
||||
<button type="button" id="calPrev">◀</button>
|
||||
<span id="calTitle"></span>
|
||||
<button type="button" id="calNext">▶</button>
|
||||
</div>
|
||||
<div class="cal-grid" id="calGrid"></div>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<!-- Selected days list -->
|
||||
<div class="field">
|
||||
<label class="label">{{ t.schedule_selected_days }}</label>
|
||||
<div id="daysList">
|
||||
<p class="has-text-grey is-size-7" id="noDaysMsg">{{ t.schedule_no_days }}</p>
|
||||
</div>
|
||||
<!-- Selected days -->
|
||||
<div class="field" id="selectedSection" style="display:none;">
|
||||
<label class="label">{{ t.schedule_selected_days }} <span id="selectedCount" class="tag is-info is-light" style="margin-left:0.4rem;"></span></label>
|
||||
<div id="daysList"></div>
|
||||
</div>
|
||||
|
||||
<!-- Notes -->
|
||||
<div class="field">
|
||||
<label class="label">{{ t.schedule_notes }}</label>
|
||||
<div class="control">
|
||||
<textarea class="textarea" name="notes" rows="2"></textarea>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<!-- Notes -->
|
||||
<div class="field">
|
||||
<label class="label">{{ t.schedule_notes }}</label>
|
||||
<div class="control">
|
||||
<textarea class="textarea" name="notes" rows="2"></textarea>
|
||||
</div>
|
||||
</div>
|
||||
<input type="hidden" name="days_json" id="daysJson" value="[]">
|
||||
<button type="submit" class="button is-primary is-fullwidth" id="submitBtn" disabled>{{ t.schedule_create }}</button>
|
||||
|
||||
<!-- Hidden days data -->
|
||||
<input type="hidden" name="days_json" id="daysJson" value="[]">
|
||||
|
||||
<button type="submit" class="button is-primary is-fullwidth" id="submitBtn" disabled>{{ t.schedule_create }}</button>
|
||||
</form>
|
||||
</form>
|
||||
</div>
|
||||
|
||||
<style>
|
||||
.day-row {
|
||||
display: flex; align-items: center; gap: 0.4rem; padding: 0.4rem 0;
|
||||
border-bottom: 1px solid #f0f0f0; flex-wrap: wrap;
|
||||
}
|
||||
.day-row .day-date { font-weight: 600; min-width: 6rem; font-size: 0.9rem; }
|
||||
.day-row input[type="time"] { width: 7rem; padding: 0.2rem 0.4rem; border: 1px solid #ddd; border-radius: 4px; font-size: 0.85rem; }
|
||||
.day-row .remove-btn { color: #e55; cursor: pointer; font-size: 0.8rem; margin-left: auto; background: none; border: none; }
|
||||
/* Time row */
|
||||
.time-row { display:flex; align-items:center; gap:0.5rem; }
|
||||
.time-block { display:flex; flex-direction:column; flex:1; }
|
||||
.time-lbl { font-size:0.75rem; color:#888; margin-bottom:0.2rem; }
|
||||
.time-sep { font-size:1.2rem; color:#aaa; padding-top:1.2rem; }
|
||||
|
||||
/* Calendar toolbar */
|
||||
.cal-toolbar { display:flex; align-items:center; justify-content:space-between; margin-bottom:0.5rem; }
|
||||
|
||||
|
||||
/* Calendar container */
|
||||
.sched-cal { background:#fafafa; border:1px solid #eee; border-radius:10px; overflow:hidden; }
|
||||
|
||||
.cal-nav { display:flex; align-items:center; justify-content:space-between; padding:0.6rem 0.75rem; background:#fff; border-bottom:1px solid #eee; }
|
||||
.cal-nav button { background:none; border:none; font-size:1.1rem; cursor:pointer; color:#6c63ff; padding:0.2rem 0.5rem; border-radius:4px; }
|
||||
.cal-nav button:hover { background:#f0eeff; }
|
||||
.cal-nav span { font-weight:700; font-size:1rem; color:#333; }
|
||||
|
||||
.cal-grid { display:grid; grid-template-columns:repeat(7,1fr); }
|
||||
|
||||
.cal-wday { text-align:center; font-size:0.72rem; font-weight:700; color:#aaa; padding:0.4rem 0; background:#fafafa; }
|
||||
.cal-wday.is-weekend { color:#f0a0a0; }
|
||||
|
||||
.cal-day { text-align:center; padding:0.55rem 0.2rem; font-size:0.9rem; cursor:pointer; color:#333; border-radius:0; transition:background 0.1s; position:relative; user-select:none; -webkit-user-select:none; }
|
||||
.cal-day:hover { background:#f0eeff; }
|
||||
.cal-day.is-empty { cursor:default; }
|
||||
.cal-day.is-empty:hover { background:none; }
|
||||
.cal-day.is-today { font-weight:700; color:#6c63ff; }
|
||||
.cal-day.is-selected { background:#6c63ff !important; color:#fff !important; border-radius:0; }
|
||||
.cal-day.is-range-start { background:#a89cff !important; color:#fff !important; }
|
||||
.cal-day.is-past { color:#ccc; }
|
||||
|
||||
/* Selected days list */
|
||||
.day-row { display:flex; align-items:center; gap:0.4rem; padding:0.45rem 0; border-bottom:1px solid #f5f5f5; }
|
||||
.day-row:last-child { border-bottom:none; }
|
||||
.day-date { font-weight:600; font-size:0.85rem; flex:1; min-width:0; overflow:hidden; text-overflow:ellipsis; white-space:nowrap; }
|
||||
.day-times { display:flex; align-items:center; gap:0.25rem; flex-shrink:0; }
|
||||
.day-times .time-sep { color:#bbb; font-size:0.8rem; }
|
||||
.day-rm { background:none; border:none; color:#ccc; cursor:pointer; font-size:1rem; padding:0.15rem 0.25rem; flex-shrink:0; line-height:1; }
|
||||
.day-rm:hover { color:#e55; }
|
||||
|
||||
/* Time badge */
|
||||
.time-badge-wrap {
|
||||
position: relative;
|
||||
display: inline-flex;
|
||||
align-items: center;
|
||||
justify-content: center;
|
||||
background: #ede9ff;
|
||||
color: #5b52d6;
|
||||
border: 1.5px solid #c4beff;
|
||||
border-radius: 20px;
|
||||
padding: 0.15rem 0.5rem;
|
||||
font-size: 0.78rem;
|
||||
font-weight: 700;
|
||||
cursor: pointer;
|
||||
min-width: 3.6rem;
|
||||
white-space: nowrap;
|
||||
}
|
||||
.time-badge-wrap:focus-within {
|
||||
border-color: #6c63ff;
|
||||
background: #f0eeff;
|
||||
}
|
||||
.time-badge-label { pointer-events: none; z-index: 1; }
|
||||
.time-badge-input {
|
||||
position: absolute;
|
||||
inset: 0;
|
||||
width: 100%;
|
||||
height: 100%;
|
||||
opacity: 0;
|
||||
cursor: pointer;
|
||||
border: none;
|
||||
background: transparent;
|
||||
padding: 0;
|
||||
margin: 0;
|
||||
font-size: 16px; /* prevent iOS zoom */
|
||||
}
|
||||
</style>
|
||||
|
||||
<script>
|
||||
const days = new Map(); // date string -> {start, end}
|
||||
const removeLabel = '{{ t.schedule_remove_day }}';
|
||||
const weekdays = '{{ lang.code() }}' === 'ru'
|
||||
? ['Вс','Пн','Вт','Ср','Чт','Пт','Сб']
|
||||
: ['Sun','Mon','Tue','Wed','Thu','Fri','Sat'];
|
||||
(function() {
|
||||
|
||||
const IS_RU = '{{ lang.code() }}' === 'ru';
|
||||
const TZ = '{{ timezone }}';
|
||||
const WDAYS = IS_RU ? ['Пн','Вт','Ср','Чт','Пт','Сб','Вс'] : ['Mo','Tu','We','Th','Fr','Sa','Su'];
|
||||
const MONTHS = IS_RU
|
||||
? ['Январь','Февраль','Март','Апрель','Май','Июнь','Июль','Август','Сентябрь','Октябрь','Ноябрь','Декабрь']
|
||||
: ['January','February','March','April','May','June','July','August','September','October','November','December'];
|
||||
|
||||
const days = new Map(); // dateStr -> {start, end}
|
||||
let viewYear, viewMonth;
|
||||
let rangeMode = false;
|
||||
let rangeStart = null; // dateStr of first tap in range mode
|
||||
|
||||
const now = new Date();
|
||||
const todayStr_ = tzDateStr(now);
|
||||
viewYear = parseInt(todayStr_.slice(0, 4));
|
||||
viewMonth = parseInt(todayStr_.slice(5, 7)) - 1; // 0-based
|
||||
|
||||
function isoDate(y, m, d) {
|
||||
return y + '-' + String(m+1).padStart(2,'0') + '-' + String(d).padStart(2,'0');
|
||||
}
|
||||
|
||||
function getDefaults() {
|
||||
return {
|
||||
start: document.getElementById('defaultStart').value || '18:00',
|
||||
end: document.getElementById('defaultEnd').value || '19:00'
|
||||
end: document.getElementById('defaultEnd').value || '19:00'
|
||||
};
|
||||
}
|
||||
|
||||
function addDay(dateStr) {
|
||||
if (!dateStr || days.has(dateStr)) return;
|
||||
function addDay(ds) {
|
||||
if (!ds || days.has(ds)) return;
|
||||
const def = getDefaults();
|
||||
days.set(dateStr, { start: def.start, end: def.end });
|
||||
renderDays();
|
||||
days.set(ds, { start: def.start, end: def.end });
|
||||
}
|
||||
|
||||
function removeDay(dateStr) {
|
||||
days.delete(dateStr);
|
||||
renderDays();
|
||||
function toggleDay(ds) {
|
||||
if (days.has(ds)) { days.delete(ds); } else { addDay(ds); }
|
||||
}
|
||||
|
||||
function renderDays() {
|
||||
const list = document.getElementById('daysList');
|
||||
const msg = document.getElementById('noDaysMsg');
|
||||
const btn = document.getElementById('submitBtn');
|
||||
// Получить текущую дату в нужном TZ как строку YYYY-MM-DD
|
||||
function tzDateStr(d) {
|
||||
const parts = new Intl.DateTimeFormat('en-CA', {
|
||||
timeZone: TZ, year: 'numeric', month: '2-digit', day: '2-digit'
|
||||
}).formatToParts(d);
|
||||
const p = {};
|
||||
parts.forEach(function(x) { p[x.type] = x.value; });
|
||||
return p.year + '-' + p.month + '-' + p.day;
|
||||
}
|
||||
|
||||
// Remove old day rows
|
||||
list.querySelectorAll('.day-row').forEach(el => el.remove());
|
||||
function fillRange(from, to) {
|
||||
if (from > to) { let t = from; from = to; to = t; }
|
||||
// Используем полдень чтобы избежать проблем с переходом суток при смене DST
|
||||
let cur = new Date(from + 'T12:00:00');
|
||||
const end = new Date(to + 'T12:00:00');
|
||||
while (cur <= end) {
|
||||
addDay(tzDateStr(cur));
|
||||
cur.setDate(cur.getDate() + 1);
|
||||
}
|
||||
}
|
||||
|
||||
// ── Render calendar ──────────────────────────────────────
|
||||
function renderCal() {
|
||||
document.getElementById('calTitle').textContent = MONTHS[viewMonth] + ' ' + viewYear;
|
||||
|
||||
const grid = document.getElementById('calGrid');
|
||||
grid.innerHTML = '';
|
||||
|
||||
// Weekday headers
|
||||
WDAYS.forEach(function(wd, i) {
|
||||
const cell = document.createElement('div');
|
||||
cell.className = 'cal-wday' + (i >= 5 ? ' is-weekend' : '');
|
||||
cell.textContent = wd;
|
||||
grid.appendChild(cell);
|
||||
});
|
||||
|
||||
// First day of month (Mon=0 for our grid)
|
||||
const first = new Date(viewYear, viewMonth, 1);
|
||||
let startDow = first.getDay(); // 0=Sun
|
||||
startDow = (startDow === 0) ? 6 : startDow - 1; // shift to Mon=0
|
||||
|
||||
const daysInMonth = new Date(viewYear, viewMonth + 1, 0).getDate();
|
||||
const todayStr = todayStr_;
|
||||
|
||||
// Empty cells before first day
|
||||
for (let i = 0; i < startDow; i++) {
|
||||
const empty = document.createElement('div');
|
||||
empty.className = 'cal-day is-empty';
|
||||
grid.appendChild(empty);
|
||||
}
|
||||
|
||||
for (let d = 1; d <= daysInMonth; d++) {
|
||||
const ds = isoDate(viewYear, viewMonth, d);
|
||||
const cell = document.createElement('div');
|
||||
let cls = 'cal-day';
|
||||
if (ds === todayStr) cls += ' is-today';
|
||||
if (days.has(ds)) cls += ' is-selected';
|
||||
if (ds === rangeStart) cls += ' is-range-start';
|
||||
cell.className = cls;
|
||||
cell.textContent = d;
|
||||
cell.dataset.date = ds;
|
||||
cell.addEventListener('click', onDayClick);
|
||||
grid.appendChild(cell);
|
||||
}
|
||||
}
|
||||
|
||||
function onDayClick(e) {
|
||||
const ds = e.currentTarget.dataset.date;
|
||||
if (!ds) return;
|
||||
if (rangeMode) {
|
||||
if (days.has(ds)) {
|
||||
days.delete(ds);
|
||||
if (rangeStart === ds) rangeStart = null;
|
||||
} else if (!rangeStart) {
|
||||
rangeStart = ds;
|
||||
} else {
|
||||
fillRange(rangeStart, ds);
|
||||
rangeStart = null;
|
||||
}
|
||||
} else {
|
||||
toggleDay(ds);
|
||||
}
|
||||
|
||||
renderCal();
|
||||
renderList();
|
||||
}
|
||||
|
||||
// ── Render selected days list ────────────────────────────
|
||||
function renderList() {
|
||||
const list = document.getElementById('daysList');
|
||||
const section = document.getElementById('selectedSection');
|
||||
const count = document.getElementById('selectedCount');
|
||||
const btn = document.getElementById('submitBtn');
|
||||
|
||||
list.innerHTML = '';
|
||||
|
||||
const resetBtn = document.getElementById('resetBtn');
|
||||
if (days.size === 0) {
|
||||
msg.style.display = '';
|
||||
section.style.display = 'none';
|
||||
btn.disabled = true;
|
||||
document.getElementById('daysJson').value = '[]';
|
||||
resetBtn.style.display = 'none';
|
||||
return;
|
||||
}
|
||||
msg.style.display = 'none';
|
||||
resetBtn.style.display = '';
|
||||
|
||||
section.style.display = '';
|
||||
btn.disabled = false;
|
||||
count.textContent = days.size;
|
||||
|
||||
// Sort by date
|
||||
const sorted = [...days.entries()].sort((a, b) => a[0].localeCompare(b[0]));
|
||||
const sorted = [...days.entries()].sort((a,b) => a[0].localeCompare(b[0]));
|
||||
|
||||
sorted.forEach(([dateStr, times]) => {
|
||||
const d = new Date(dateStr + 'T00:00:00');
|
||||
const wd = weekdays[d.getDay()];
|
||||
const label = dateStr.split('-').reverse().join('.') + ' ' + wd;
|
||||
sorted.forEach(function([ds, times]) {
|
||||
const d = new Date(ds + 'T00:00:00');
|
||||
const dow = IS_RU
|
||||
? ['Вс','Пн','Вт','Ср','Чт','Пт','Сб'][d.getDay()]
|
||||
: ['Sun','Mon','Tue','Wed','Thu','Fri','Sat'][d.getDay()];
|
||||
const parts = ds.split('-');
|
||||
const label = parts[2] + '.' + parts[1] + ' ' + dow; // DD.MM Вт
|
||||
|
||||
const row = document.createElement('div');
|
||||
row.className = 'day-row';
|
||||
row.innerHTML = `
|
||||
<span class="day-date">${label}</span>
|
||||
<input type="time" value="${times.start}" data-date="${dateStr}" data-field="start">
|
||||
<span>—</span>
|
||||
<input type="time" value="${times.end}" data-date="${dateStr}" data-field="end">
|
||||
<button type="button" class="remove-btn" data-date="${dateStr}">${removeLabel}</button>
|
||||
`;
|
||||
row.innerHTML =
|
||||
'<span class="day-date">' + label + '</span>' +
|
||||
'<div class="day-times">' +
|
||||
'<div class="time-badge-wrap">' +
|
||||
'<span class="time-badge-label">' + times.start + '</span>' +
|
||||
'<input type="time" class="time-badge-input" value="' + times.start + '" data-date="' + ds + '" data-field="start">' +
|
||||
'</div>' +
|
||||
'<span class="time-sep">—</span>' +
|
||||
'<div class="time-badge-wrap">' +
|
||||
'<span class="time-badge-label">' + times.end + '</span>' +
|
||||
'<input type="time" class="time-badge-input" value="' + times.end + '" data-date="' + ds + '" data-field="end">' +
|
||||
'</div>' +
|
||||
'</div>' +
|
||||
'<button type="button" class="day-rm" data-date="' + ds + '" title="Убрать">✕</button>';
|
||||
list.appendChild(row);
|
||||
});
|
||||
|
||||
// Update hidden JSON
|
||||
updateJson();
|
||||
|
||||
// Bind events
|
||||
list.querySelectorAll('input[type="time"]').forEach(inp => {
|
||||
list.querySelectorAll('.time-badge-input').forEach(function(inp) {
|
||||
inp.addEventListener('change', function() {
|
||||
const dt = this.dataset.date;
|
||||
const field = this.dataset.field;
|
||||
if (days.has(dt)) {
|
||||
days.get(dt)[field] = this.value;
|
||||
const d = days.get(this.dataset.date);
|
||||
if (d) {
|
||||
d[this.dataset.field] = this.value;
|
||||
this.previousElementSibling.textContent = this.value;
|
||||
updateJson();
|
||||
}
|
||||
});
|
||||
});
|
||||
list.querySelectorAll('.remove-btn').forEach(btn => {
|
||||
btn.addEventListener('click', function() {
|
||||
removeDay(this.dataset.date);
|
||||
list.querySelectorAll('.day-rm').forEach(function(b) {
|
||||
b.addEventListener('click', function() {
|
||||
days.delete(this.dataset.date);
|
||||
renderCal();
|
||||
renderList();
|
||||
});
|
||||
});
|
||||
|
||||
updateJson();
|
||||
}
|
||||
|
||||
function updateJson() {
|
||||
const arr = [...days.entries()].map(([date, t]) => ({
|
||||
date: date,
|
||||
time_start: t.start,
|
||||
time_end: t.end
|
||||
}));
|
||||
const arr = [...days.entries()].map(function([date, t]) {
|
||||
return { date: date, time_start: t.start, time_end: t.end };
|
||||
});
|
||||
document.getElementById('daysJson').value = JSON.stringify(arr);
|
||||
}
|
||||
|
||||
document.getElementById('addDateBtn').addEventListener('click', function() {
|
||||
const v = document.getElementById('pickDate').value;
|
||||
addDay(v);
|
||||
document.getElementById('pickDate').value = '';
|
||||
// ── Navigation ───────────────────────────────────────────
|
||||
document.getElementById('calPrev').addEventListener('click', function() {
|
||||
viewMonth--;
|
||||
if (viewMonth < 0) { viewMonth = 11; viewYear--; }
|
||||
renderCal();
|
||||
});
|
||||
document.getElementById('calNext').addEventListener('click', function() {
|
||||
viewMonth++;
|
||||
if (viewMonth > 11) { viewMonth = 0; viewYear++; }
|
||||
renderCal();
|
||||
});
|
||||
|
||||
document.getElementById('pickDate').addEventListener('keydown', function(e) {
|
||||
if (e.key === 'Enter') { e.preventDefault(); document.getElementById('addDateBtn').click(); }
|
||||
});
|
||||
|
||||
document.getElementById('fillRangeBtn').addEventListener('click', function() {
|
||||
const from = document.getElementById('rangeFrom').value;
|
||||
const to = document.getElementById('rangeTo').value;
|
||||
if (!from || !to || from > to) return;
|
||||
let cur = new Date(from + 'T00:00:00');
|
||||
const end = new Date(to + 'T00:00:00');
|
||||
while (cur <= end) {
|
||||
const ds = cur.toISOString().slice(0, 10);
|
||||
addDay(ds);
|
||||
cur.setDate(cur.getDate() + 1);
|
||||
// ── Range mode toggle ────────────────────────────────────
|
||||
document.getElementById('rangeModeBtn').addEventListener('click', function() {
|
||||
rangeMode = !rangeMode;
|
||||
rangeStart = null;
|
||||
if (rangeMode) {
|
||||
this.classList.remove('is-outlined', 'is-info');
|
||||
this.classList.add('is-warning');
|
||||
this.textContent = '✕ Выбрать отдельные дни';
|
||||
} else {
|
||||
this.classList.remove('is-warning');
|
||||
this.classList.add('is-outlined', 'is-info');
|
||||
this.textContent = '⇔ Выбрать диапазон';
|
||||
}
|
||||
document.getElementById('rangeFrom').value = '';
|
||||
document.getElementById('rangeTo').value = '';
|
||||
renderCal();
|
||||
});
|
||||
|
||||
// Set default pick date to today
|
||||
document.getElementById('pickDate').valueAsDate = new Date();
|
||||
document.getElementById('resetBtn').addEventListener('click', function() {
|
||||
days.clear();
|
||||
rangeStart = null;
|
||||
renderCal();
|
||||
renderList();
|
||||
});
|
||||
|
||||
// ── Default time change → update existing days ───────────
|
||||
// (only updates days that still have the old default)
|
||||
// kept simple: doesn't retroactively update already-added days
|
||||
|
||||
renderCal();
|
||||
renderList();
|
||||
|
||||
})();
|
||||
</script>
|
||||
{% endblock %}
|
||||
|
||||
+200
-13
@@ -14,18 +14,8 @@
|
||||
|
||||
<div class="form-card">
|
||||
<form method="post" action="/admin/settings/save">
|
||||
<div class="field">
|
||||
<label class="label">{{ t.settings_telegram_bot_token }}</label>
|
||||
<div class="control">
|
||||
<input class="input" type="text" name="telegram_bot_token" value="{% for s in &settings %}{% if s.key == "telegram_bot_token" %}{{ s.value }}{% endif %}{% endfor %}">
|
||||
</div>
|
||||
</div>
|
||||
<div class="field">
|
||||
<label class="label">{{ t.settings_telegram_chat_id }}</label>
|
||||
<div class="control">
|
||||
<input class="input" type="text" name="telegram_chat_id" value="{% for s in &settings %}{% if s.key == "telegram_chat_id" %}{{ s.value }}{% endif %}{% endfor %}">
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<h2 class="subtitle is-5 mb-3" style="border-bottom:1px solid #eee;padding-bottom:0.5rem;">{{ t.settings_contact_info }}</h2>
|
||||
<div class="field">
|
||||
<label class="label">{{ t.settings_contact_info }}</label>
|
||||
<div class="control">
|
||||
@@ -38,7 +28,204 @@
|
||||
<textarea class="input" name="pricing_info" rows="3" style="min-height:70px;resize:vertical;" placeholder="от 600 рублей за визит">{% for s in &settings %}{% if s.key == "pricing_info" %}{{ s.value }}{% endif %}{% endfor %}</textarea>
|
||||
</div>
|
||||
</div>
|
||||
<button type="submit" class="button is-primary">{{ t.settings_save }}</button>
|
||||
<div class="field">
|
||||
<label class="label">{{ t.settings_seo_keywords }}</label>
|
||||
<div class="control">
|
||||
<textarea id="seoKeywordsInput" class="textarea" name="seo_keywords" rows="3"
|
||||
style="resize:vertical;"
|
||||
placeholder="зооняня Хабаровск, присмотр за питомцем Хабаровск, догситтер Хабаровск">{% for s in &settings %}{% if s.key == "seo_keywords" %}{{ s.value }}{% endif %}{% endfor %}</textarea>
|
||||
</div>
|
||||
<div id="seoPreview" style="margin-top:0.5rem;padding:0.5rem 0.75rem;background:#fafafa;border:1px solid #eee;border-radius:6px;min-height:2rem;line-height:2;font-size:0.85rem;display:none;"></div>
|
||||
</div>
|
||||
|
||||
<details style="margin-top:1.5rem;">
|
||||
<summary class="subtitle is-5 mb-3" style="cursor:pointer;border-bottom:1px solid #eee;padding-bottom:0.5rem;">
|
||||
{{ t.settings_section_advanced }}
|
||||
</summary>
|
||||
|
||||
<div style="margin-top:1rem;">
|
||||
<h3 class="subtitle is-6 mb-2 has-text-grey">{{ t.settings_section_general }}</h3>
|
||||
<div class="field">
|
||||
<label class="label">{{ t.settings_site_domain }}</label>
|
||||
<div class="control">
|
||||
<input class="input" type="text" name="site_domain" placeholder="https://example.com" value="{% for s in &settings %}{% if s.key == "site_domain" %}{{ s.value }}{% endif %}{% endfor %}">
|
||||
</div>
|
||||
</div>
|
||||
<div class="field">
|
||||
<label class="label">{{ t.settings_timezone }}</label>
|
||||
<div class="control">
|
||||
<input class="input" type="text" name="timezone" placeholder="Asia/Vladivostok" value="{% for s in &settings %}{% if s.key == "timezone" %}{{ s.value }}{% endif %}{% endfor %}">
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<h3 class="subtitle is-6 mb-2 has-text-grey" style="margin-top:1.25rem;">{{ t.settings_section_notifications }}</h3>
|
||||
<div class="field">
|
||||
<label class="checkbox">
|
||||
<input type="checkbox" name="client_notifications_enabled" value="true"{% if client_notifications_checked %} checked{% endif %}>
|
||||
{{ t.settings_client_notifications_enabled }}
|
||||
</label>
|
||||
<p class="help">{{ t.settings_client_notifications_help }}</p>
|
||||
</div>
|
||||
<blockquote class="notification is-warning is-light" style="padding:0.8rem 1rem;font-size:0.85rem;margin:0.75rem 0;">
|
||||
<p>{{ t.settings_vapid_warning }}</p>
|
||||
<p style="margin-top:0.45rem;">{{ t.settings_vapid_generate }}</p>
|
||||
<code style="display:inline-block;margin-top:0.2rem;user-select:all;">cargo run --bin generate_vapid</code>
|
||||
</blockquote>
|
||||
<div class="field">
|
||||
<label class="label">{{ t.settings_vapid_public_key }}</label>
|
||||
<div class="control">
|
||||
<input class="input" type="text" name="vapid_public_key" autocomplete="off" value="{% for s in &settings %}{% if s.key == "vapid_public_key" %}{{ s.value }}{% endif %}{% endfor %}">
|
||||
</div>
|
||||
</div>
|
||||
<div class="field">
|
||||
<label class="label">{{ t.settings_vapid_private_key }}</label>
|
||||
<div class="control">
|
||||
<input class="input" type="password" name="vapid_private_key" autocomplete="new-password" value="{% for s in &settings %}{% if s.key == "vapid_private_key" %}{{ s.value }}{% endif %}{% endfor %}">
|
||||
</div>
|
||||
</div>
|
||||
<div class="field">
|
||||
<label class="label">{{ t.settings_vapid_subject }}</label>
|
||||
<div class="control">
|
||||
<input class="input" type="text" name="vapid_subject" placeholder="mailto:admin@example.com" value="{% for s in &settings %}{% if s.key == "vapid_subject" %}{{ s.value }}{% endif %}{% endfor %}">
|
||||
</div>
|
||||
</div>
|
||||
<details style="margin:0.9rem 0 1.25rem;border:1px solid #e8e5f5;border-radius:8px;background:#faf9ff;">
|
||||
<summary style="cursor:pointer;padding:0.7rem 0.85rem;font-weight:600;font-size:0.9rem;">
|
||||
{{ t.settings_push_subscribers }} ({{ push_subscribers.len() }})
|
||||
</summary>
|
||||
<div style="padding:0 0.85rem 0.85rem;overflow-x:auto;">
|
||||
{% if push_subscribers.is_empty() %}
|
||||
<p class="help">{{ t.settings_push_no_subscribers }}</p>
|
||||
{% else %}
|
||||
<table class="table is-fullwidth is-striped is-narrow" style="font-size:0.8rem;background:transparent;">
|
||||
<thead><tr>
|
||||
<th>{{ t.settings_push_client }}</th>
|
||||
<th>{{ t.settings_push_devices }}</th>
|
||||
<th>{{ t.settings_push_language }}</th>
|
||||
<th>{{ t.settings_push_updated }}</th>
|
||||
</tr></thead>
|
||||
<tbody>
|
||||
{% for subscriber in &push_subscribers %}
|
||||
<tr>
|
||||
<td>{{ subscriber.client_name }}</td>
|
||||
<td>{{ subscriber.device_count }}</td>
|
||||
<td>{{ subscriber.languages }}</td>
|
||||
<td style="white-space:nowrap;">{{ subscriber.last_updated }}</td>
|
||||
</tr>
|
||||
{% endfor %}
|
||||
</tbody>
|
||||
</table>
|
||||
{% endif %}
|
||||
</div>
|
||||
</details>
|
||||
<div class="field">
|
||||
<label class="label">{{ t.settings_telegram_bot_token }}</label>
|
||||
<div class="control">
|
||||
<input class="input" type="text" name="telegram_bot_token" value="{% for s in &settings %}{% if s.key == "telegram_bot_token" %}{{ s.value }}{% endif %}{% endfor %}">
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<h3 class="subtitle is-6 mb-2 has-text-grey" style="margin-top:1.25rem;">{{ t.settings_section_captcha }}</h3>
|
||||
<div class="field">
|
||||
<label class="label">{{ t.settings_turnstile_site_key }}</label>
|
||||
<div class="control">
|
||||
<input class="input" type="text" name="turnstile_site_key" value="{% for s in &settings %}{% if s.key == "turnstile_site_key" %}{{ s.value }}{% endif %}{% endfor %}">
|
||||
</div>
|
||||
</div>
|
||||
<div class="field">
|
||||
<label class="label">{{ t.settings_turnstile_secret_key }}</label>
|
||||
<div class="control">
|
||||
<input class="input" type="text" name="turnstile_secret_key" value="{% for s in &settings %}{% if s.key == "turnstile_secret_key" %}{{ s.value }}{% endif %}{% endfor %}">
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<h3 class="subtitle is-6 mb-2 has-text-grey" style="margin-top:1.25rem;">{{ t.settings_section_oidc }}</h3>
|
||||
<div class="field">
|
||||
<label class="label">{{ t.settings_oidc_issuer_url }}</label>
|
||||
<div class="control">
|
||||
<input class="input" type="text" name="oidc_issuer_url" placeholder="https://keycloak.example.com/realms/myrealm" value="{% for s in &settings %}{% if s.key == "oidc_issuer_url" %}{{ s.value }}{% endif %}{% endfor %}">
|
||||
</div>
|
||||
</div>
|
||||
<div class="field">
|
||||
<label class="label">{{ t.settings_oidc_client_id }}</label>
|
||||
<div class="control">
|
||||
<input class="input" type="text" name="oidc_client_id" value="{% for s in &settings %}{% if s.key == "oidc_client_id" %}{{ s.value }}{% endif %}{% endfor %}">
|
||||
</div>
|
||||
</div>
|
||||
<div class="field">
|
||||
<label class="label">{{ t.settings_oidc_client_secret }}</label>
|
||||
<div class="control">
|
||||
<input class="input" type="password" name="oidc_client_secret" value="{% for s in &settings %}{% if s.key == "oidc_client_secret" %}{{ s.value }}{% endif %}{% endfor %}">
|
||||
</div>
|
||||
</div>
|
||||
<div class="field">
|
||||
<label class="label">{{ t.settings_oidc_allowed_groups }}</label>
|
||||
<div class="control">
|
||||
<input class="input" type="text" name="oidc_allowed_groups" placeholder="admins, web-petting" value="{% for s in &settings %}{% if s.key == "oidc_allowed_groups" %}{{ s.value }}{% endif %}{% endfor %}">
|
||||
</div>
|
||||
</div>
|
||||
<div class="field">
|
||||
<label class="checkbox">
|
||||
<input type="checkbox" name="auth_password_enabled" value="true"{% if auth_password_checked %} checked{% endif %}>
|
||||
{{ t.settings_auth_password_enabled }}
|
||||
</label>
|
||||
</div>
|
||||
<div class="field">
|
||||
<label class="checkbox">
|
||||
<input type="checkbox" name="auth_sso_enabled" value="true"{% if auth_sso_checked %} checked{% endif %}>
|
||||
{{ t.settings_auth_sso_enabled }}
|
||||
</label>
|
||||
</div>
|
||||
</div>
|
||||
</details>
|
||||
|
||||
<button type="submit" class="button is-primary" style="margin-top:1.5rem;">{{ t.settings_save }}</button>
|
||||
</form>
|
||||
</div>
|
||||
|
||||
<script>
|
||||
(function() {
|
||||
var COLORS = [
|
||||
'rgba(124,108,255,0.18)',
|
||||
'rgba(255,82,135,0.15)',
|
||||
'rgba(255,140,38,0.18)',
|
||||
'rgba(0,180,150,0.15)',
|
||||
'rgba(77,166,255,0.18)',
|
||||
'rgba(255,179,64,0.18)',
|
||||
'rgba(176,108,255,0.16)',
|
||||
'rgba(34,180,130,0.16)',
|
||||
];
|
||||
|
||||
var ta = document.getElementById('seoKeywordsInput');
|
||||
var preview = document.getElementById('seoPreview');
|
||||
|
||||
function esc(s) {
|
||||
return s.replace(/&/g,'&').replace(/</g,'<').replace(/>/g,'>');
|
||||
}
|
||||
|
||||
function render() {
|
||||
var text = ta.value.trim();
|
||||
if (!text) { preview.style.display = 'none'; return; }
|
||||
|
||||
var parts = text.split(',');
|
||||
var html = '';
|
||||
parts.forEach(function(part, i) {
|
||||
var word = part.trim();
|
||||
if (word) {
|
||||
var color = COLORS[i % COLORS.length];
|
||||
html += '<span style="background:' + color + ';border-radius:4px;padding:2px 6px;margin:2px;">' + esc(word) + '</span>';
|
||||
}
|
||||
if (i < parts.length - 1) {
|
||||
html += '<span style="color:#ccc;font-size:0.8em;margin:0 1px">,</span>';
|
||||
}
|
||||
});
|
||||
|
||||
preview.innerHTML = html;
|
||||
preview.style.display = 'block';
|
||||
}
|
||||
|
||||
ta.addEventListener('input', render);
|
||||
render();
|
||||
})();
|
||||
</script>
|
||||
{% endblock %}
|
||||
|
||||
@@ -4,11 +4,18 @@
|
||||
<meta charset="UTF-8">
|
||||
<meta name="viewport" content="width=device-width, initial-scale=1.0">
|
||||
<title>{{ t.nav_title }} — {{ t.setup_title }}</title>
|
||||
<link rel="icon" type="image/svg+xml" href="/favicon.svg">
|
||||
<link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/bulma@1/css/bulma.min.css">
|
||||
<style>
|
||||
body { background: #f5f5f5; display: flex; align-items: center; justify-content: center; min-height: 100vh; }
|
||||
:root { color-scheme: light; }
|
||||
body { background: #f5f5f5; display: flex; align-items: center; justify-content: center; min-height: 100vh; color: #333; }
|
||||
.login-box { width: 100%; max-width: 400px; padding: 0 1rem; }
|
||||
.login-card { background: #fff; border-radius: 12px; padding: 2rem 1.5rem; box-shadow: 0 2px 12px rgba(0,0,0,0.06); }
|
||||
input, textarea, select, .input, .textarea, .select select {
|
||||
background-color: #fff !important; color: #333 !important; border-color: #dbdbdb !important;
|
||||
}
|
||||
.label, label { color: #363636 !important; }
|
||||
.notification { color: #333 !important; }
|
||||
</style>
|
||||
</head>
|
||||
<body>
|
||||
|
||||
@@ -17,6 +17,29 @@
|
||||
<div class="item-card-meta">
|
||||
<span>🕐 {{ user.created_at.format("%d.%m.%Y %H:%M") }}</span>
|
||||
</div>
|
||||
{% if user.status == "active" %}
|
||||
<form method="post" action="/admin/users/{{ user.id }}/telegram" style="margin-top:0.5rem; padding-top:0.5rem; border-top:1px solid #eee;">
|
||||
<div class="columns is-mobile is-vcentered" style="margin-bottom:0;">
|
||||
<div class="column">
|
||||
<div class="field" style="margin-bottom:0;">
|
||||
<label class="label is-small">{{ t.users_telegram_chat_id }}</label>
|
||||
<div class="control">
|
||||
<input class="input is-small" type="text" name="telegram_chat_id" placeholder="123456789" value="{{ user.telegram_chat_id.as_deref().unwrap_or_default() }}">
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
<div class="column is-narrow">
|
||||
<label class="checkbox is-small">
|
||||
<input type="checkbox" name="telegram_notifications" value="true" {% if user.telegram_notifications == Some(true) %}checked{% endif %}>
|
||||
{{ t.users_telegram_enabled }}
|
||||
</label>
|
||||
</div>
|
||||
<div class="column is-narrow">
|
||||
<button type="submit" class="button is-small is-info is-outlined">💾</button>
|
||||
</div>
|
||||
</div>
|
||||
</form>
|
||||
{% endif %}
|
||||
<div class="item-card-actions">
|
||||
{% if user.status == "active" %}
|
||||
<form method="post" action="/admin/users/{{ user.id }}/archive">
|
||||
|
||||
@@ -4,7 +4,15 @@
|
||||
<meta charset="UTF-8">
|
||||
<meta name="viewport" content="width=device-width, initial-scale=1.0">
|
||||
<title>{{ t.portal_title }} — {{ client.name }}</title>
|
||||
<link rel="icon" type="image/svg+xml" href="/favicon.svg">
|
||||
<link rel="manifest" href="/client/{{ client.media_token }}/manifest.webmanifest">
|
||||
<meta name="theme-color" content="#7c6cff">
|
||||
<meta name="apple-mobile-web-app-capable" content="yes">
|
||||
{% if !turnstile_site_key.is_empty() %}
|
||||
<script src="https://challenges.cloudflare.com/turnstile/v0/api.js" async defer></script>
|
||||
{% endif %}
|
||||
<style>
|
||||
:root { color-scheme: light; }
|
||||
*, *::before, *::after { box-sizing: border-box; margin: 0; padding: 0; }
|
||||
body {
|
||||
font-family: -apple-system, BlinkMacSystemFont, 'Segoe UI', Roboto, sans-serif;
|
||||
@@ -12,12 +20,15 @@
|
||||
padding: 0 0 2rem;
|
||||
}
|
||||
.portal-header {
|
||||
position: relative;
|
||||
background: linear-gradient(135deg, #7c6cff, #b06cff);
|
||||
color: #fff; padding: 2rem 1.5rem 1.5rem; text-align: center;
|
||||
}
|
||||
.portal-header h1 { font-size: 1.5rem; font-weight: 700; }
|
||||
.portal-header .sub { opacity: 0.85; font-size: 0.9rem; margin-top: 0.25rem; }
|
||||
.container { max-width: 700px; margin: 0 auto; padding: 0 1rem; }
|
||||
.container { max-width: 1100px; margin: 0 auto; padding: 0 1rem; }
|
||||
.portal-grid { display: grid; grid-template-columns: minmax(0, 700px) 320px; gap: 1.25rem; align-items: start; }
|
||||
.portal-settings { position: absolute; right: 1rem; bottom: 1rem; width: 38px; height: 38px; border: 0; border-radius: 50%; background: rgba(255,255,255,.2); color: #fff; font-size: 1.1rem; cursor: pointer; }
|
||||
.section-title {
|
||||
font-size: 1.15rem; font-weight: 700; margin: 1.5rem 0 0.75rem;
|
||||
padding-bottom: 0.4rem; border-bottom: 2px solid #ede7f6;
|
||||
@@ -47,13 +58,22 @@
|
||||
width: 80px; height: 60px; object-fit: cover; border-radius: 6px;
|
||||
}
|
||||
.media-row .vid-thumb {
|
||||
width: 80px; height: 60px; border-radius: 6px; background: #f0f0f0;
|
||||
display: flex; align-items: center; justify-content: center; font-size: 1.5rem;
|
||||
position: relative; width: 80px; height: 60px; border-radius: 6px;
|
||||
overflow: hidden; background: #111;
|
||||
}
|
||||
.media-row .vid-thumb video {
|
||||
width: 100%; height: 100%; display: block; object-fit: cover;
|
||||
}
|
||||
.media-row .video-play {
|
||||
position: absolute; top: 50%; left: 50%; transform: translate(-50%, -50%);
|
||||
color: white; font-size: 1.35rem; line-height: 1;
|
||||
text-shadow: 0 1px 4px #000; pointer-events: none;
|
||||
}
|
||||
.feedback-form { margin-top: 0.6rem; }
|
||||
.feedback-form textarea {
|
||||
width: 100%; padding: 0.5rem 0.75rem; border: 1px solid #ddd; border-radius: 8px;
|
||||
font-size: 0.85rem; font-family: inherit; resize: vertical; min-height: 50px;
|
||||
background-color: #fff; color: #333;
|
||||
}
|
||||
.feedback-form textarea:focus { outline: none; border-color: #7c6cff; }
|
||||
.feedback-form button {
|
||||
@@ -96,6 +116,33 @@
|
||||
font-weight: 700; min-width: 5.5rem;
|
||||
}
|
||||
.upcoming-row .up-time { color: #7a7599; }
|
||||
.calendar-panel { position: sticky; top: 1rem; margin-top: 1.5rem; background: #fff; border: 1px solid #eee; border-radius: 12px; padding: .85rem; }
|
||||
.calendar-head { display: flex; align-items: center; justify-content: space-between; margin-bottom: .65rem; }
|
||||
.calendar-head button { border: 0; background: #f0edff; color: #6255c7; width: 30px; height: 30px; border-radius: 50%; cursor: pointer; }
|
||||
.calendar-title { font-size: .95rem; font-weight: 700; }
|
||||
.calendar-weekdays, .calendar-days { display: grid; grid-template-columns: repeat(7, 1fr); gap: 3px; text-align: center; }
|
||||
.calendar-weekdays { color: #999; font-size: .68rem; margin-bottom: 3px; }
|
||||
.calendar-day { aspect-ratio: 1; display: flex; align-items: center; justify-content: center; border-radius: 7px; font-size: .78rem; color: #aaa; }
|
||||
.calendar-day.past { background: #ede9ff; color: #5145a6; font-weight: 700; text-decoration: none; }
|
||||
.calendar-day.past:hover { background: #dcd5ff; }
|
||||
.calendar-day.future { background: #f3f3f3; color: #bbb; border: 1px dashed #ddd; }
|
||||
.calendar-month[hidden] { display: none; }
|
||||
.calendar-legend { margin-top: .65rem; font-size: .72rem; color: #999; }
|
||||
.pagination { display: flex; justify-content: center; align-items: center; gap: .75rem; margin: 1rem 0; font-size: .85rem; }
|
||||
.pagination a { color: #6558c8; text-decoration: none; padding: .35rem .7rem; background: #fff; border: 1px solid #e5e1ff; border-radius: 8px; }
|
||||
.modal-bg { display: none; position: fixed; inset: 0; z-index: 1000; background: rgba(20,18,40,.55); align-items: center; justify-content: center; padding: 1rem; }
|
||||
.modal-bg.open { display: flex; }
|
||||
.notification-modal { width: min(420px, 100%); background: #fff; border-radius: 14px; padding: 1.2rem; box-shadow: 0 15px 50px rgba(0,0,0,.25); }
|
||||
.notification-modal h2 { font-size: 1.15rem; margin-bottom: .45rem; }
|
||||
.notification-modal p { font-size: .88rem; color: #777; }
|
||||
.notification-actions { display: flex; gap: .5rem; margin-top: 1rem; }
|
||||
.notification-actions button { border: 0; border-radius: 8px; padding: .55rem .9rem; cursor: pointer; }
|
||||
.notification-primary { background: #7567e8; color: #fff; }
|
||||
@media (max-width: 800px) {
|
||||
.portal-grid { display: flex; flex-direction: column; }
|
||||
.calendar-panel { position: static; order: -1; width: 100%; margin-top: 1rem; }
|
||||
.visits-column { width: 100%; }
|
||||
}
|
||||
</style>
|
||||
</head>
|
||||
<body>
|
||||
@@ -107,6 +154,7 @@
|
||||
<div class="portal-header">
|
||||
<h1>{{ t.portal_title }}</h1>
|
||||
<div class="sub">{{ client.name }}</div>
|
||||
{% if notifications_enabled %}<button class="portal-settings" type="button" onclick="openNotificationSettings()" aria-label="{{ t.portal_notifications }}">⚙</button>{% endif %}
|
||||
</div>
|
||||
|
||||
<div class="container">
|
||||
@@ -115,13 +163,15 @@
|
||||
<div class="success-msg">{{ t.portal_feedback_thanks }}</div>
|
||||
{% endif %}
|
||||
|
||||
<div class="portal-grid">
|
||||
<main class="visits-column">
|
||||
<!-- Past visits with media first -->
|
||||
<h2 class="section-title">{{ t.portal_past }}</h2>
|
||||
{% if past.is_empty() %}
|
||||
<p class="empty-msg">{{ t.portal_no_past }}</p>
|
||||
{% else %}
|
||||
{% for pv in &past %}
|
||||
<div class="visit-card">
|
||||
<div class="visit-card" id="visit-{{ pv.visit.id.unwrap() }}">
|
||||
<div class="visit-card-head">
|
||||
<span class="date">{{ pv.visit.visit_date }}</span>
|
||||
<span class="badge-sm badge-{{ pv.visit.status }}">
|
||||
@@ -141,12 +191,15 @@
|
||||
<div class="media-row">
|
||||
{% for m in &pv.media %}
|
||||
{% if m.file_type == "photo" %}
|
||||
<a href="/client/{{ client.media_token }}/media/{{ m.id }}" data-lightbox="photo">
|
||||
<img src="/client/{{ client.media_token }}/media/{{ m.id }}" alt="" loading="lazy">
|
||||
<a href="/client/{{ client.media_token }}/media/{{ m.id.unwrap() }}" data-lightbox="photo">
|
||||
<img src="/client/{{ client.media_token }}/media/{{ m.id.unwrap() }}/thumbnail" alt="" loading="lazy">
|
||||
</a>
|
||||
{% else %}
|
||||
<a href="/client/{{ client.media_token }}/media/{{ m.id }}" data-lightbox="video">
|
||||
<div class="vid-thumb">🎬</div>
|
||||
<a href="/client/{{ client.media_token }}/media/{{ m.id.unwrap() }}" data-lightbox="video">
|
||||
<div class="vid-thumb">
|
||||
<video src="/client/{{ client.media_token }}/media/{{ m.id.unwrap() }}#t=0.1" preload="metadata" muted playsinline></video>
|
||||
<span class="video-play">▶</span>
|
||||
</div>
|
||||
</a>
|
||||
{% endif %}
|
||||
{% endfor %}
|
||||
@@ -163,6 +216,9 @@
|
||||
</div>
|
||||
<form class="feedback-form" id="fb-form-{{ pv.visit.id }}" style="display:none;" method="post" action="/client/{{ client.media_token }}/{{ pv.visit.id }}/feedback">
|
||||
<textarea name="feedback" required>{{ fb }}</textarea>
|
||||
{% if !turnstile_site_key.is_empty() %}
|
||||
<div class="cf-turnstile" data-sitekey="{{ turnstile_site_key }}" data-theme="light" data-appearance="interaction-only" style="margin-top:0.4rem;"></div>
|
||||
{% endif %}
|
||||
<div style="display:flex;gap:0.4rem;">
|
||||
<button type="submit">{{ t.portal_feedback_submit }}</button>
|
||||
<button type="button" class="fb-cancel-btn" onclick="hideFbEdit({{ pv.visit.id }})">✕</button>
|
||||
@@ -171,12 +227,22 @@
|
||||
{% else %}
|
||||
<form class="feedback-form" method="post" action="/client/{{ client.media_token }}/{{ pv.visit.id }}/feedback">
|
||||
<textarea name="feedback" placeholder="{{ t.portal_feedback_placeholder }}" required></textarea>
|
||||
{% if !turnstile_site_key.is_empty() %}
|
||||
<div class="cf-turnstile" data-sitekey="{{ turnstile_site_key }}" data-theme="light" data-appearance="interaction-only" style="margin-top:0.4rem;"></div>
|
||||
{% endif %}
|
||||
<button type="submit">{{ t.portal_feedback_submit }}</button>
|
||||
</form>
|
||||
{% endif %}
|
||||
{% endif %}
|
||||
</div>
|
||||
{% endfor %}
|
||||
{% if total_pages > 1 %}
|
||||
<nav class="pagination">
|
||||
{% if has_previous_page %}<a href="?page={{ page - 1 }}">← {{ t.portal_previous }}</a>{% endif %}
|
||||
<span>{{ page }} / {{ total_pages }}</span>
|
||||
{% if has_next_page %}<a href="?page={{ page + 1 }}">{{ t.portal_next }} →</a>{% endif %}
|
||||
</nav>
|
||||
{% endif %}
|
||||
{% endif %}
|
||||
|
||||
<!-- Compact upcoming schedule -->
|
||||
@@ -186,14 +252,56 @@
|
||||
{% for pv in &upcoming %}
|
||||
<div class="upcoming-row">
|
||||
<span class="up-date">{{ pv.visit.visit_date }}</span>
|
||||
<span class="up-time">{{ pv.visit.time_start }} — {{ pv.visit.time_end }}</span>
|
||||
<span class="up-time">{{ t.portal_future_visit }}</span>
|
||||
</div>
|
||||
{% endfor %}
|
||||
</div>
|
||||
{% endif %}
|
||||
</main>
|
||||
|
||||
{% if !calendar_months.is_empty() %}
|
||||
<aside class="calendar-panel">
|
||||
<div class="calendar-head">
|
||||
<button type="button" onclick="moveCalendar(1)" aria-label="{{ t.portal_previous }}">‹</button>
|
||||
<span class="calendar-title" id="calendarTitle">{{ t.portal_calendar }}</span>
|
||||
<button type="button" onclick="moveCalendar(-1)" aria-label="{{ t.portal_next }}">›</button>
|
||||
</div>
|
||||
<div class="calendar-weekdays"><span>Пн</span><span>Вт</span><span>Ср</span><span>Чт</span><span>Пт</span><span>Сб</span><span>Вс</span></div>
|
||||
{% for month in &calendar_months %}
|
||||
<div class="calendar-month" data-label="{{ month.label }}"{% if !loop.first %} hidden{% endif %}>
|
||||
<div class="calendar-days">
|
||||
{% for _blank in &month.leading_blanks %}<span></span>{% endfor %}
|
||||
{% for day in &month.days %}
|
||||
{% if let Some(href) = day.href.as_deref() %}
|
||||
<a class="calendar-day {{ day.class_name }}" href="{{ href }}" title="{{ day.title }}">{{ day.number }}</a>
|
||||
{% else %}
|
||||
<span class="calendar-day {{ day.class_name }}" title="{{ day.title }}">{{ day.number }}</span>
|
||||
{% endif %}
|
||||
{% endfor %}
|
||||
</div>
|
||||
</div>
|
||||
{% endfor %}
|
||||
<div class="calendar-legend">{{ t.portal_future_visit }} — ···</div>
|
||||
</aside>
|
||||
{% endif %}
|
||||
</div>
|
||||
|
||||
</div>
|
||||
|
||||
{% if notifications_enabled %}
|
||||
<div class="modal-bg" id="notificationModal" onclick="if(event.target===this) closeNotificationSettings()">
|
||||
<div class="notification-modal">
|
||||
<h2>{{ t.portal_notifications }}</h2>
|
||||
<p id="notificationText">{{ t.portal_notifications_text }}</p>
|
||||
<p id="notificationStatus" style="display:none;margin-top:0.65rem;font-weight:600;"></p>
|
||||
<div class="notification-actions">
|
||||
<button type="button" class="notification-primary" id="notificationToggle">{{ t.portal_notifications_enable }}</button>
|
||||
<button type="button" onclick="closeNotificationSettings()">✕</button>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
{% endif %}
|
||||
|
||||
<script>
|
||||
function showFbEdit(id) {
|
||||
document.getElementById('fb-view-' + id).style.display = 'none';
|
||||
@@ -203,6 +311,120 @@ function hideFbEdit(id) {
|
||||
document.getElementById('fb-form-' + id).style.display = 'none';
|
||||
document.getElementById('fb-view-' + id).style.display = '';
|
||||
}
|
||||
var calendarIndex = 0;
|
||||
function renderCalendar() {
|
||||
var months = document.querySelectorAll('.calendar-month');
|
||||
if (!months.length) return;
|
||||
months.forEach(function(month, index) { month.hidden = index !== calendarIndex; });
|
||||
document.getElementById('calendarTitle').textContent = months[calendarIndex].dataset.label;
|
||||
}
|
||||
function moveCalendar(delta) {
|
||||
var months = document.querySelectorAll('.calendar-month');
|
||||
calendarIndex = Math.max(0, Math.min(months.length - 1, calendarIndex + delta));
|
||||
renderCalendar();
|
||||
}
|
||||
renderCalendar();
|
||||
{% if notifications_enabled %}
|
||||
(function() {
|
||||
var toggle = document.getElementById('notificationToggle');
|
||||
var registration;
|
||||
var subscription;
|
||||
var status = document.getElementById('notificationStatus');
|
||||
function decodeKey(value) {
|
||||
var padding = '='.repeat((4 - value.length % 4) % 4);
|
||||
var raw = atob((value + padding).replace(/-/g, '+').replace(/_/g, '/'));
|
||||
return Uint8Array.from(raw, function(char) { return char.charCodeAt(0); });
|
||||
}
|
||||
function sameKey(left, right) {
|
||||
if (!left || left.byteLength !== right.byteLength) return false;
|
||||
var a = new Uint8Array(left), b = new Uint8Array(right);
|
||||
return a.every(function(value, index) { return value === b[index]; });
|
||||
}
|
||||
function showStatus(message, error) {
|
||||
status.textContent = message;
|
||||
status.style.display = '';
|
||||
status.style.color = error ? '#b42318' : '#067647';
|
||||
}
|
||||
async function saveSubscription(value) {
|
||||
var payload = value.toJSON();
|
||||
payload.language = '{{ lang.code() }}';
|
||||
var response = await fetch('/client/{{ client.media_token }}/push/subscribe', {
|
||||
method: 'POST', headers: {'Content-Type': 'application/json'}, body: JSON.stringify(payload)
|
||||
});
|
||||
if (!response.ok) throw new Error('Subscription API returned HTTP ' + response.status);
|
||||
}
|
||||
async function refresh() {
|
||||
if (!('serviceWorker' in navigator) || !('PushManager' in window) || !('Notification' in window)) {
|
||||
toggle.disabled = true;
|
||||
showStatus('{{ t.portal_notifications_unsupported }}', true);
|
||||
return;
|
||||
}
|
||||
if (!'{{ vapid_public_key }}') {
|
||||
toggle.disabled = true;
|
||||
showStatus('{{ t.portal_notifications_error }}', true);
|
||||
return;
|
||||
}
|
||||
registration = await navigator.serviceWorker.register('/service-worker.js');
|
||||
await registration.update();
|
||||
await navigator.serviceWorker.ready;
|
||||
subscription = await registration.pushManager.getSubscription();
|
||||
var expectedKey = decodeKey('{{ vapid_public_key }}');
|
||||
if (subscription && !sameKey(subscription.options.applicationServerKey, expectedKey)) {
|
||||
await subscription.unsubscribe();
|
||||
subscription = null;
|
||||
}
|
||||
if (subscription) {
|
||||
await saveSubscription(subscription);
|
||||
showStatus('{{ t.portal_notifications_active }}', false);
|
||||
}
|
||||
toggle.textContent = subscription ? '{{ t.portal_notifications_disable }}' : '{{ t.portal_notifications_enable }}';
|
||||
}
|
||||
window.openNotificationSettings = function() {
|
||||
document.getElementById('notificationModal').classList.add('open');
|
||||
refresh().catch(function(error) {
|
||||
console.error(error);
|
||||
showStatus('{{ t.portal_notifications_error }}', true);
|
||||
});
|
||||
};
|
||||
window.closeNotificationSettings = function() { document.getElementById('notificationModal').classList.remove('open'); };
|
||||
toggle.addEventListener('click', async function() {
|
||||
toggle.disabled = true;
|
||||
try {
|
||||
if (!registration) await refresh();
|
||||
if (subscription) {
|
||||
await fetch('/client/{{ client.media_token }}/push/unsubscribe', {
|
||||
method: 'POST', headers: {'Content-Type': 'application/json'},
|
||||
body: JSON.stringify({endpoint: subscription.endpoint})
|
||||
});
|
||||
await subscription.unsubscribe();
|
||||
subscription = null;
|
||||
} else {
|
||||
var permission = await Notification.requestPermission();
|
||||
if (permission !== 'granted') {
|
||||
document.getElementById('notificationText').textContent = '{{ t.portal_notifications_denied }}';
|
||||
return;
|
||||
}
|
||||
subscription = await registration.pushManager.subscribe({
|
||||
userVisibleOnly: true,
|
||||
applicationServerKey: decodeKey('{{ vapid_public_key }}')
|
||||
});
|
||||
await saveSubscription(subscription);
|
||||
showStatus('{{ t.portal_notifications_active }}', false);
|
||||
}
|
||||
toggle.textContent = subscription ? '{{ t.portal_notifications_disable }}' : '{{ t.portal_notifications_enable }}';
|
||||
} catch (error) {
|
||||
console.error(error);
|
||||
showStatus('{{ t.portal_notifications_error }}', true);
|
||||
} finally {
|
||||
toggle.disabled = false;
|
||||
}
|
||||
});
|
||||
refresh().catch(function(error) {
|
||||
console.error(error);
|
||||
showStatus('{{ t.portal_notifications_error }}', true);
|
||||
});
|
||||
})();
|
||||
{% endif %}
|
||||
</script>
|
||||
{% include "partials/lightbox.html" %}
|
||||
</body>
|
||||
|
||||
+76
-8
@@ -5,11 +5,30 @@
|
||||
<meta name="viewport" content="width=device-width, initial-scale=1.0">
|
||||
<meta name="description" content="{{ t.landing_meta_description }}">
|
||||
<title>{{ t.nav_title }} — {{ t.landing_hero_title }}</title>
|
||||
<link rel="icon" type="image/svg+xml" href="/favicon.svg">
|
||||
|
||||
<!-- Canonical & Hreflang -->
|
||||
<link rel="canonical" href="{{ site_domain }}/?lang={{ lang.code() }}">
|
||||
<link rel="alternate" hreflang="ru" href="{{ site_domain }}/?lang=ru">
|
||||
<link rel="alternate" hreflang="en" href="{{ site_domain }}/?lang=en">
|
||||
<link rel="alternate" hreflang="x-default" href="{{ site_domain }}/">
|
||||
|
||||
<!-- Open Graph -->
|
||||
<meta property="og:title" content="{{ t.nav_title }} — {{ t.landing_hero_title }}">
|
||||
<meta property="og:description" content="{{ t.landing_meta_description }}">
|
||||
<meta property="og:type" content="website">
|
||||
<meta property="og:url" content="{{ site_domain }}/?lang={{ lang.code() }}">
|
||||
<meta property="og:locale" content="{% if lang.code() == "ru" %}ru_RU{% else %}en_US{% endif %}">
|
||||
<meta property="og:site_name" content="{{ t.nav_title }}">
|
||||
|
||||
{% if !seo_keywords.is_empty() %}
|
||||
<meta name="keywords" content="{{ seo_keywords }}">
|
||||
{% endif %}
|
||||
|
||||
<!-- Twitter Card -->
|
||||
<meta name="twitter:card" content="summary">
|
||||
<meta name="twitter:title" content="{{ t.nav_title }} — {{ t.landing_hero_title }}">
|
||||
<meta name="twitter:description" content="{{ t.landing_meta_description }}">
|
||||
|
||||
<!-- Structured Data -->
|
||||
<script type="application/ld+json">
|
||||
@@ -19,10 +38,22 @@
|
||||
"name": "{{ t.nav_title }}",
|
||||
"description": "{{ t.landing_meta_description }}",
|
||||
"serviceType": "Pet Sitting",
|
||||
"@id": "#business"
|
||||
"url": "{{ site_domain }}/",
|
||||
"@id": "#business"{% if review_count > 0 %},
|
||||
"aggregateRating": {
|
||||
"@type": "AggregateRating",
|
||||
"ratingValue": "5",
|
||||
"bestRating": "5",
|
||||
"ratingCount": "{{ review_count }}",
|
||||
"reviewCount": "{{ review_count }}"
|
||||
}{% endif %}
|
||||
}
|
||||
</script>
|
||||
|
||||
{% if !turnstile_site_key.is_empty() %}
|
||||
<script src="https://challenges.cloudflare.com/turnstile/v0/api.js" async defer></script>
|
||||
{% endif %}
|
||||
|
||||
<style>
|
||||
/* ── Reset & Base ── */
|
||||
*, *::before, *::after { box-sizing: border-box; margin: 0; padding: 0; }
|
||||
@@ -96,6 +127,25 @@
|
||||
box-shadow: 0 4px 20px rgba(124,108,255,0.35);
|
||||
}
|
||||
.hero-cta:hover { transform: translateY(-2px); box-shadow: 0 8px 30px rgba(124,108,255,0.45); }
|
||||
.hero { position: relative; overflow: clip; }
|
||||
.hero-photo {
|
||||
position: absolute; z-index: 0;
|
||||
width: 420px; height: 420px;
|
||||
border-radius: 50%;
|
||||
border: 20px solid #ffe0ec;
|
||||
object-fit: cover;
|
||||
box-sizing: border-box;
|
||||
}
|
||||
.hero-photo-tr { right: -100px; top: -100px; }
|
||||
.hero-photo-bl { left: -100px; bottom: -150px; }
|
||||
.hero-content { position: relative; z-index: 1; }
|
||||
.section-alt { position: relative; z-index: 1; }
|
||||
@media (max-width: 600px) {
|
||||
.hero-photo { width: 200px; height: 200px; border-width: 12px; }
|
||||
.hero-photo-tr { right: -50px; top: -50px; }
|
||||
.hero-photo-bl { left: -50px; bottom: -70px; }
|
||||
.hero-cta { display: block; width: fit-content; margin-left: auto; margin-right: 0; }
|
||||
}
|
||||
.hero-emoji { font-size: 4rem; margin-bottom: 1rem; display: block; }
|
||||
.hero-desc {
|
||||
font-size: clamp(0.9rem, 2vw, 1.05rem);
|
||||
@@ -118,6 +168,7 @@
|
||||
border-radius: 18px; padding: 1.75rem;
|
||||
border: 1px solid rgba(180,170,220,0.2);
|
||||
transition: transform 0.2s, box-shadow 0.2s;
|
||||
-webkit-transform: translateZ(0); transform: translateZ(0);
|
||||
}
|
||||
.testimonial-card:hover {
|
||||
transform: translateY(-3px);
|
||||
@@ -147,6 +198,7 @@
|
||||
border-radius: 18px; padding: 2rem 2.5rem;
|
||||
border: 1px solid rgba(180,170,220,0.2);
|
||||
text-align: center;
|
||||
-webkit-transform: translateZ(0); transform: translateZ(0);
|
||||
}
|
||||
.pricing-text {
|
||||
font-size: clamp(1.1rem, 2.5vw, 1.3rem);
|
||||
@@ -177,12 +229,13 @@
|
||||
border-radius: 18px; padding: 2rem 1.75rem;
|
||||
border: 1px solid rgba(180,170,220,0.2);
|
||||
transition: transform 0.2s, box-shadow 0.2s;
|
||||
-webkit-transform: translateZ(0); transform: translateZ(0);
|
||||
}
|
||||
.service-card:hover {
|
||||
transform: translateY(-4px);
|
||||
box-shadow: 0 12px 36px rgba(124,108,255,0.12);
|
||||
}
|
||||
.service-icon { font-size: 2.5rem; margin-bottom: 0.75rem; display: block; }
|
||||
.service-icon { font-size: 2.5rem; margin-bottom: 0.75rem; display: block; text-align: center; }
|
||||
.service-card h3 { font-size: 1.2rem; font-weight: 700; margin-bottom: 0.5rem; color: #2d2b55; }
|
||||
.service-card p { color: #5a5680; font-size: 0.95rem; line-height: 1.6; }
|
||||
|
||||
@@ -210,6 +263,7 @@
|
||||
border-radius: 22px; padding: 2.5rem 2rem;
|
||||
box-shadow: 0 8px 40px rgba(124,108,255,0.12);
|
||||
border: 1px solid rgba(180,170,220,0.25);
|
||||
-webkit-transform: translateZ(0); transform: translateZ(0);
|
||||
}
|
||||
.form-wrapper h2 {
|
||||
text-align: center; font-size: 1.6rem; font-weight: 800;
|
||||
@@ -255,10 +309,14 @@
|
||||
border-top: 1px solid rgba(180,170,220,0.15);
|
||||
background: rgba(255,255,255,0.3);
|
||||
}
|
||||
.seo-keywords {
|
||||
font-size: 0.72rem; color: #aaa; line-height: 2;
|
||||
max-width: 800px; margin: 0 auto 1rem;
|
||||
}
|
||||
|
||||
/* ── Mobile ── */
|
||||
@media (max-width: 600px) {
|
||||
.hero { padding: 6.5rem 1rem 3rem; }
|
||||
.hero { padding: 6.5rem 1rem 10rem; }
|
||||
.section { padding: 3rem 1rem; }
|
||||
.form-section { padding: 3rem 1rem; }
|
||||
.form-wrapper { padding: 1.75rem 1.25rem; }
|
||||
@@ -286,11 +344,15 @@
|
||||
|
||||
<!-- Hero -->
|
||||
<section class="hero">
|
||||
<span class="hero-emoji" role="img" aria-label="pets">🐱🐹🦎</span>
|
||||
<h1>{{ t.landing_hero_title }}</h1>
|
||||
<p>{{ t.landing_hero_subtitle }}</p>
|
||||
<p class="hero-desc">{{ t.landing_hero_description }}</p>
|
||||
<a href="#form" class="hero-cta">{{ t.landing_hero_cta }}</a>
|
||||
<img class="hero-photo hero-photo-tr" src="/static/cat_up_right.png" alt="">
|
||||
<img class="hero-photo hero-photo-bl" src="/static/cat_bottom_left.png" alt="">
|
||||
<div class="hero-content">
|
||||
<span class="hero-emoji" role="img" aria-label="pets">🐱🐹🦎</span>
|
||||
<h1>{{ t.landing_hero_title }}</h1>
|
||||
<p>{{ t.landing_hero_subtitle }}</p>
|
||||
<p class="hero-desc">{{ t.landing_hero_description }}</p>
|
||||
<a href="#form" class="hero-cta">{{ t.landing_hero_cta }}</a>
|
||||
</div>
|
||||
</section>
|
||||
|
||||
<!-- Services -->
|
||||
@@ -406,6 +468,9 @@
|
||||
<input type="checkbox" id="consent" name="consent" required style="margin-top:0.2rem;width:auto;flex-shrink:0;">
|
||||
<label for="consent" style="font-size:0.82rem;font-weight:400;color:#7a7599;cursor:pointer;display:inline;">{{ t.landing_form_consent }}</label>
|
||||
</div>
|
||||
{% if !turnstile_site_key.is_empty() %}
|
||||
<div class="cf-turnstile" data-sitekey="{{ turnstile_site_key }}" data-theme="light" data-size="compact" style="margin-bottom:1.25rem;"></div>
|
||||
{% endif %}
|
||||
<button type="submit" class="form-submit">{{ t.landing_form_submit }}</button>
|
||||
</form>
|
||||
{% if !contact_info.is_empty() %}
|
||||
@@ -419,6 +484,9 @@
|
||||
|
||||
<!-- Footer -->
|
||||
<footer class="site-footer">
|
||||
{% if !seo_keywords.is_empty() %}
|
||||
<p class="seo-keywords" id="seoKeywords">{{ seo_keywords }}</p>
|
||||
{% endif %}
|
||||
<p>{{ t.landing_footer_text }}</p>
|
||||
<p style="margin-top:0.4rem;">© 2026 {{ t.nav_title }}. {{ t.landing_footer_copyright }}.</p>
|
||||
</footer>
|
||||
|
||||
@@ -4,7 +4,9 @@
|
||||
<meta charset="UTF-8">
|
||||
<meta name="viewport" content="width=device-width, initial-scale=1.0">
|
||||
<title>{{ t.nav_title }} — {{ t.landing_thank_you_title }}</title>
|
||||
<link rel="icon" type="image/svg+xml" href="/favicon.svg">
|
||||
<style>
|
||||
:root { color-scheme: light; }
|
||||
*, *::before, *::after { box-sizing: border-box; margin: 0; padding: 0; }
|
||||
body {
|
||||
font-family: -apple-system, BlinkMacSystemFont, 'Segoe UI', Roboto, Oxygen, Ubuntu, sans-serif;
|
||||
|
||||
Reference in New Issue
Block a user