From ff1d1fc49065f3d04b7e79dfbba007b5ff87a7a7 Mon Sep 17 00:00:00 2001 From: Lucio Chen Date: Thu, 21 May 2026 21:30:56 -0700 Subject: [PATCH] Add i18n framework with English and Chinese support Introduce an embedded-locale i18n package exposing a T() template function. UI strings across all templates and catalog category/item names are now translatable via locale JSON files, selectable through the new server.language config option. Falls back to English when a locale is missing or fails to load. Co-Authored-By: Claude Opus 4.6 --- config.toml.example | 3 + internal/config/config.go | 2 + internal/i18n/i18n.go | 61 +++ internal/i18n/locales/en.json | 367 ++++++++++++++++++ internal/i18n/locales/zh.json | 367 ++++++++++++++++++ internal/server/handlers.go | 40 +- internal/server/server.go | 14 +- internal/server/templates.go | 5 +- internal/server/templates/base.html | 22 +- internal/server/templates/items.html | 282 +++++++------- .../server/templates/location_folder.html | 68 ++-- internal/server/templates/locations.html | 68 ++-- internal/server/templates/login.html | 20 +- internal/server/templates/print_labels.html | 20 +- internal/server/templates/shortener.html | 78 ++-- internal/server/templates/tags.html | 62 +-- 16 files changed, 1161 insertions(+), 318 deletions(-) create mode 100644 internal/i18n/i18n.go create mode 100644 internal/i18n/locales/en.json create mode 100644 internal/i18n/locales/zh.json diff --git a/config.toml.example b/config.toml.example index 98b687e..7eb6455 100644 --- a/config.toml.example +++ b/config.toml.example @@ -5,6 +5,9 @@ port = 8889 base_url = "http://localhost:8889" read_timeout = "5s" write_timeout = "10s" +# Language for the UI. Supported: "en" (English), "zh" (Chinese). +# Add new languages by creating a JSON file in internal/i18n/locales/. +language = "en" [admin] username = "admin" diff --git a/internal/config/config.go b/internal/config/config.go index ba9fdb9..6ce7f37 100644 --- a/internal/config/config.go +++ b/internal/config/config.go @@ -21,6 +21,7 @@ type ServerConfig struct { BaseURL string `toml:"base_url"` ReadTimeout string `toml:"read_timeout"` WriteTimeout string `toml:"write_timeout"` + Language string `toml:"language"` } type AdminConfig struct { @@ -65,6 +66,7 @@ func Load(path string) (*Config, error) { BaseURL: "http://localhost:8889", ReadTimeout: "5s", WriteTimeout: "10s", + Language: "en", }, Admin: AdminConfig{ Username: "admin", diff --git a/internal/i18n/i18n.go b/internal/i18n/i18n.go new file mode 100644 index 0000000..84a9c8a --- /dev/null +++ b/internal/i18n/i18n.go @@ -0,0 +1,61 @@ +package i18n + +import ( + "embed" + "encoding/json" + "fmt" + "strings" + "sync" +) + +//go:embed locales +var localesFS embed.FS + +type Translator struct { + lang string + messages map[string]string + mu sync.RWMutex +} + +func New(lang string) (*Translator, error) { + if lang == "" { + lang = "en" + } + + t := &Translator{ + lang: lang, + messages: make(map[string]string), + } + + data, err := localesFS.ReadFile(fmt.Sprintf("locales/%s.json", lang)) + if err != nil { + return nil, fmt.Errorf("loading locale %s: %w", lang, err) + } + + if err := json.Unmarshal(data, &t.messages); err != nil { + return nil, fmt.Errorf("parsing locale %s: %w", lang, err) + } + + return t, nil +} + +func (t *Translator) T(key string) string { + t.mu.RLock() + defer t.mu.RUnlock() + if msg, ok := t.messages[key]; ok { + return msg + } + return key +} + +func (t *Translator) TF(key string, args ...string) string { + msg := t.T(key) + for _, arg := range args { + msg = strings.Replace(msg, "%s", arg, 1) + } + return msg +} + +func (t *Translator) Lang() string { + return t.lang +} diff --git a/internal/i18n/locales/en.json b/internal/i18n/locales/en.json new file mode 100644 index 0000000..b75c7d1 --- /dev/null +++ b/internal/i18n/locales/en.json @@ -0,0 +1,367 @@ +{ + "app.title": "Solis | Home Assets", + "app.title.assets": "Solis | Assets", + "app.title.tags": "Solis | Tags", + "app.title.locations": "Solis | Locations", + "app.title.shortlinks": "Solis | Shortlinks", + "app.title.print": "Solis | Print Labels", + "app.title.login": "Solis | Sign In", + + "nav.assets": "Assets", + "nav.locations": "Locations", + "nav.tags": "Tags", + "nav.shortlinks": "Shortlinks", + "nav.print_labels": "Print Labels", + "nav.sign_out": "Sign Out", + "nav.admin_login": "Admin Login", + + "common.cancel": "Cancel", + "common.save": "Save Changes", + "common.edit": "Edit", + "common.delete": "Delete", + "common.restore": "Restore", + "common.delete_forever": "Delete Forever", + "common.remove": "Remove", + "common.archive": "Archive", + "common.filter": "Filter", + "common.reset": "Reset", + "common.details": "Details", + "common.locked": "Locked", + "common.archived": "Archived", + "common.root": "Root", + "common.description": "Description", + "common.actions": "Actions", + "common.name": "Name", + "common.back": "Back", + "common.show_removed": "Show removed", + "common.unassigned": "Unassigned", + + "login.title": "Sign in to your assets", + "login.subtitle": "Enter your administrator credentials below", + "login.username": "Username", + "login.password": "Password", + "login.submit": "Sign In", + + "items.title": "Asset Inventory", + "items.subtitle": "Track, manage, and label your home equipment and tools.", + "items.add": "Add Asset", + "items.search_placeholder": "Search by asset name, model, serial number...", + "items.all_statuses": "-- All Statuses --", + "items.all_locations": "-- All Locations --", + "items.all_tags": "-- All Tags --", + "items.col.qr": "QR Label", + "items.col.name": "Name", + "items.col.location": "Location", + "items.col.status": "Status", + "items.col.quantity": "Quantity", + "items.col.tags": "Tags", + "items.empty.title": "No assets found", + "items.empty.subtitle": "Try refining your filters or click \"Add Asset\" to start tracking equipment.", + "items.remove_item": "Remove Item", + "items.archive_item": "Archive Item", + "items.confirm_delete": "Are you sure you want to permanently delete this asset? This will clean up all associated media files on disk and cannot be undone.", + "items.model_prefix": "Model", + + "items.detail.title": "Asset Details", + "items.detail.edit": "Edit Asset", + "items.detail.back_list": "Back to List", + "items.detail.back_dir": "Back to Directory", + "items.detail.description": "Description", + "items.detail.no_description": "No description provided for this asset.", + "items.detail.quantity": "Quantity", + "items.detail.model_number": "Model Number", + "items.detail.serial_number": "Serial Number", + "items.detail.photo": "Asset Photo", + "items.detail.no_photo": "No Photo Attached", + "items.detail.receipt": "Receipt / Invoice", + "items.detail.no_receipt": "No Receipt Document", + "items.detail.open_doc": "Open Document", + "items.detail.custom_fields": "Custom Asset Metadata", + "items.detail.no_custom": "No custom metadata fields defined for this asset.", + "items.detail.qr": "Asset Label QR Code", + "items.detail.download_qr": "Download Label Image", + "items.detail.no_short_url": "No short URL associated.", + "items.detail.purchase_context": "Purchase Context", + "items.detail.purchase_price": "Purchase Price", + "items.detail.supplier": "Supplier / Dealer", + "items.detail.purchase_date": "Purchase Date", + "items.detail.warranty_period": "Warranty Period", + "items.detail.months": "Months", + "items.detail.assigned_location": "Assigned Location", + + "items.edit.title_prefix": "Edit Asset", + "items.edit.subtitle": "Define inventory items, upload documentation, and generate automated QR codes.", + "items.edit.basic_info": "Basic Information", + "items.edit.asset_name": "Asset Name", + "items.edit.quantity": "Quantity", + "items.edit.description": "Description", + "items.edit.model_number": "Model Number", + "items.edit.serial_number": "Serial Number", + "items.edit.status": "Status", + "items.edit.location": "Location", + "items.edit.tags": "Tags / Categories", + "items.edit.purchase_warranty": "Purchase & Warranty", + "items.edit.purchase_price": "Purchase Price ($)", + "items.edit.purchase_date": "Purchase Date", + "items.edit.warranty_months": "Warranty (Months)", + "items.edit.supplier": "Supplier / Store", + "items.edit.docs_visuals": "Documentation & Visuals", + "items.edit.photo": "Item Photo", + "items.edit.active_image": "Active Image", + "items.edit.receipt": "Receipt / Invoice Document", + "items.edit.active_receipt": "Active Receipt", + "items.edit.custom_fields": "Custom Fields", + "items.edit.custom_fields_help": "Enter custom parameters one per line as Key: Value (e.g. Battery: 18v Lithium). These will be parsed into indexed SQLite JSON dynamically.", + "items.edit.custom_fields_editor": "Custom Fields Editor", + + "status.in_use": "In Use", + "status.in_storage": "In Storage", + "status.borrowed": "Borrowed", + "status.lost": "Lost", + "status.disposed": "Disposed", + + "wizard.title": "Add New Asset", + "wizard.subtitle": "Catalog any device, appliance, or item in seconds using our intuitive selection wizard.", + "wizard.step_category": "Category", + "wizard.step_item": "Item", + "wizard.step_brand": "Brand", + "wizard.category_question": "Which category of item do you want to add?", + "wizard.item_question": "What kind of %s is it?", + "wizard.brand_question": "What brand is the %s?", + "wizard.other_unlisted": "Other / Unlisted", + "wizard.other_item": "Other Item", + "wizard.other_brand": "Other Brand", + "wizard.back": "Back to previous step", + "wizard.asset_suffix": "Asset", + "wizard.new_asset": "New Asset", + "wizard.auto_tag_desc": "Auto-created from catalog category", + "wizard.auto_desc": "Automatically cataloged via Wizard: %s > %s > %s", + + "tags.title": "Tags", + "tags.subtitle": "Label and categorize assets to easily group similar items together (e.g. Tools, Electronics, Fragile)", + "tags.col.tag": "Tag", + "tags.col.color": "Color Hex", + "tags.empty": "No tags defined yet. Add one on the right to get started!", + "tags.show_removed": "Show removed tags", + "tags.edit_tag": "Edit Tag", + "tags.create_tag": "Create Tag", + "tags.tag_name": "Tag Name", + "tags.tag_color": "Tag Color", + "tags.add_tag": "Add Tag", + "tags.confirm_delete": "Are you sure you want to permanently delete this tag? All associated items will lose this tag reference.", + + "locations.title": "Locations", + "locations.subtitle": "Define physical areas and hierarchical storage places (e.g., House > Kitchen > Drawer A)", + "locations.col.name": "Name", + "locations.col.parent": "Parent Path", + "locations.empty": "No locations defined yet. Add one on the right to get started!", + "locations.show_removed": "Show removed locations", + "locations.edit_location": "Edit Location", + "locations.create_location": "Create Location", + "locations.location_name": "Location Name", + "locations.parent_location": "Parent Location (Optional)", + "locations.none_root": "-- None (Root Location) --", + "locations.add_location": "Add Location", + "locations.confirm_delete": "Are you sure you want to permanently delete this location? Associated sub-locations and assets will be detached.", + + "folder.home": "Home", + "folder.show_removed": "Show removed items", + "folder.edit_location": "Edit Location", + "folder.add_asset_here": "Add Asset Here", + "folder.drag_up": "Drag items or folders here to move up to the parent directory", + "folder.folders": "Folders", + "folder.no_subfolders": "No sub-folders in this location.", + "folder.state.removed": "Removed", + "folder.state.archived": "Archived", + "folder.state.active": "Active", + "folder.edit_folder": "Edit Folder", + "folder.restore_folder": "Restore Folder", + "folder.confirm_delete_location": "Are you sure you want to permanently delete this location? All items inside will be moved to the Default Room.", + "folder.delete_permanently": "Delete Permanently", + "folder.archive_folder": "Archive Folder", + "folder.remove_folder": "Remove Folder", + "folder.assets": "Assets", + "folder.no_assets": "No assets found in this location.", + "folder.qty": "Qty", + "folder.edit_asset": "Edit Asset", + "folder.show_qr": "Show QR Code", + "folder.restore_asset": "Restore Asset", + "folder.confirm_delete_asset": "Are you sure you want to permanently delete this asset? This cannot be undone.", + "folder.archive_asset": "Archive Asset", + "folder.remove_asset": "Remove Asset", + + "shortener.title": "URL Shortener", + "shortener.subtitle": "Manage custom manual redirects (e.g. warranties, external manuals) or review auto-generated asset short URLs.", + "shortener.show_removed": "Show removed links", + "shortener.col.slug": "Slug", + "shortener.col.target_url": "Target URL", + "shortener.col.link_type": "Link Type", + "shortener.col.clicks": "Clicks", + "shortener.view_qr": "View QR Code", + "shortener.asset_link": "Asset Link", + "shortener.manual_redirect": "Manual Redirect", + "shortener.managed_by_asset": "Managed by Asset", + "shortener.confirm_delete": "Are you sure you want to permanently delete this redirect? This action cannot be undone.", + "shortener.empty": "No short links recorded. Create a custom redirect on the right!", + "shortener.edit_redirect": "Edit Redirect", + "shortener.short_slug": "Short Slug", + "shortener.target_url": "Target Destination URL", + "shortener.create_redirect": "Create Redirect", + "shortener.custom_slug": "Custom Slug (Optional)", + "shortener.auto": "Auto", + "shortener.slug_hint": "Leave blank to generate a random 4-character slug.", + "shortener.destination_url": "Destination URL", + "shortener.add_redirect": "Add Redirect", + "shortener.slug_length_title": "URL Slug Length", + "shortener.slug_length_desc": "Controls the character length of auto-generated short URL slugs. Shorter slugs make smaller QR codes. Changes apply to newly created assets only.", + "shortener.characters": "characters", + + "print.title": "Printable QR Labels", + "print.subtitle": "Generate high-fidelity label sheets for your inventory. Press Ctrl + P (or Cmd + P) to print sticker sheets. Standard print stylesheets are auto-applied.", + "print.print_sheet": "Print Sheet", + "print.back_to_assets": "Back to Assets", + "print.guidelines_title": "Printing Guidelines", + "print.guideline_margins": "Set your margins to None or Minimum in the browser print dialogue.", + "print.guideline_graphics": "Enable Background graphics to preserve borders and alignments.", + "print.guideline_size": "Check the layout preview page size (standard Letter/A4) to ensure grid alignment on your sticker paper.", + "print.empty": "No items with active short links found. Create an asset to generate labels!", + + "qr.preview": "QR Code Preview", + "qr.download": "Download QR Image", + + "Tech & Electronics": "Tech & Electronics", + "Kitchen Appliances": "Kitchen Appliances", + "Furniture": "Furniture", + "Office Supplies": "Office Supplies", + "Tools & Hardware": "Tools & Hardware", + "Fitness & Sports": "Fitness & Sports", + "Home Entertainment": "Home Entertainment", + "Gardening & Outdoor": "Gardening & Outdoor", + "Lighting & Lamps": "Lighting & Lamps", + "Cleaning & Laundry": "Cleaning & Laundry", + "Smart Home Devices": "Smart Home Devices", + "Books & Stationery": "Books & Stationery", + "Security & Safety": "Security & Safety", + "Storage & Organization": "Storage & Organization", + "Audio & Instruments": "Audio & Instruments", + + "Smartphones": "Smartphones", + "Laptops": "Laptops", + "Tablets": "Tablets", + "Smartwatches": "Smartwatches", + "Desktop Computers": "Desktop Computers", + "Computer Monitors": "Computer Monitors", + "Keyboards": "Keyboards", + "Computer Mice": "Computer Mice", + "Coffee Makers": "Coffee Makers", + "Blenders": "Blenders", + "Toasters": "Toasters", + "Microwaves": "Microwaves", + "Air Fryers": "Air Fryers", + "Food Processors": "Food Processors", + "Juicers": "Juicers", + "Rice Cookers": "Rice Cookers", + "Office Chairs": "Office Chairs", + "Desks": "Desks", + "Sofas": "Sofas", + "Dining Tables": "Dining Tables", + "Mattresses": "Mattresses", + "Bookshelves": "Bookshelves", + "Coffee Tables": "Coffee Tables", + "Bed Frames": "Bed Frames", + "Paper Shredders": "Paper Shredders", + "Label Printers": "Label Printers", + "Staplers": "Staplers", + "Notebooks": "Notebooks", + "Pens": "Pens", + "Whiteboards": "Whiteboards", + "Desk Organizers": "Desk Organizers", + "Calculators": "Calculators", + "Power Drills": "Power Drills", + "Screwdriver Sets": "Screwdriver Sets", + "Hand Tool Sets": "Hand Tool Sets", + "Tape Measures": "Tape Measures", + "Hammers": "Hammers", + "Wrenches": "Wrenches", + "Pliers": "Pliers", + "Utility Knives": "Utility Knives", + "Treadmills": "Treadmills", + "Exercise Bikes": "Exercise Bikes", + "Dumbbells": "Dumbbells", + "Yoga Mats": "Yoga Mats", + "Resistance Bands": "Resistance Bands", + "Fitness Trackers": "Fitness Trackers", + "Kettlebells": "Kettlebells", + "Foam Rollers": "Foam Rollers", + "Televisions": "Televisions", + "Soundbars": "Soundbars", + "Streaming Devices": "Streaming Devices", + "Projectors": "Projectors", + "VR Headsets": "VR Headsets", + "Game Consoles": "Game Consoles", + "DVD/Blu-ray Players": "DVD/Blu-ray Players", + "Remote Controls": "Remote Controls", + "Lawn Mowers": "Lawn Mowers", + "Leaf Blowers": "Leaf Blowers", + "Pruning Shears": "Pruning Shears", + "Garden Hoses": "Garden Hoses", + "Watering Cans": "Watering Cans", + "Wheelbarrows": "Wheelbarrows", + "Weed Eaters": "Weed Eaters", + "Patio Heaters": "Patio Heaters", + "Desk Lamps": "Desk Lamps", + "Floor Lamps": "Floor Lamps", + "Smart Bulbs": "Smart Bulbs", + "String Lights": "String Lights", + "Flashlights": "Flashlights", + "Night Lights": "Night Lights", + "Ceiling Fans": "Ceiling Fans", + "Grow Lights": "Grow Lights", + "Vacuum Cleaners": "Vacuum Cleaners", + "Steam Mops": "Steam Mops", + "Air Purifiers": "Air Purifiers", + "Washing Machines": "Washing Machines", + "Clothes Dryers": "Clothes Dryers", + "Ironing Boards": "Ironing Boards", + "Steam Irons": "Steam Irons", + "Robot Mops": "Robot Mops", + "Smart Speakers": "Smart Speakers", + "Smart Thermostats": "Smart Thermostats", + "Security Cameras": "Security Cameras", + "Smart Doorlocks": "Smart Doorlocks", + "Video Doorbells": "Video Doorbells", + "Smart Plugs": "Smart Plugs", + "Robot Vacuums": "Robot Vacuums", + "Smart Displays": "Smart Displays", + "Planners": "Planners", + "Sketchbooks": "Sketchbooks", + "Colored Pencils": "Colored Pencils", + "Fountain Pens": "Fountain Pens", + "Highlighters": "Highlighters", + "Sticky Notes": "Sticky Notes", + "Pencil Cases": "Pencil Cases", + "Smoke Detectors": "Smoke Detectors", + "Fire Extinguishers": "Fire Extinguishers", + "Safes": "Safes", + "First Aid Kits": "First Aid Kits", + "Safety Flashlights": "Safety Flashlights", + "Door Barricades": "Door Barricades", + "CO Detectors": "CO Detectors", + "Motion Sensors": "Motion Sensors", + "Plastic Bins": "Plastic Bins", + "Storage Racks": "Storage Racks", + "Shoe Racks": "Shoe Racks", + "Closet Organizers": "Closet Organizers", + "Food Containers": "Food Containers", + "Hangers": "Hangers", + "Cable Organizers": "Cable Organizers", + "Toolboxes": "Toolboxes", + "Headphones": "Headphones", + "Microphones": "Microphones", + "Bluetooth Speakers": "Bluetooth Speakers", + "Keyboards & Pianos": "Keyboards & Pianos", + "Guitars": "Guitars", + "Audio Interfaces": "Audio Interfaces", + "Studio Monitors": "Studio Monitors", + "Turntables": "Turntables" +} diff --git a/internal/i18n/locales/zh.json b/internal/i18n/locales/zh.json new file mode 100644 index 0000000..1190cb7 --- /dev/null +++ b/internal/i18n/locales/zh.json @@ -0,0 +1,367 @@ +{ + "app.title": "Solis | 家庭资产", + "app.title.assets": "Solis | 资产", + "app.title.tags": "Solis | 标签", + "app.title.locations": "Solis | 位置", + "app.title.shortlinks": "Solis | 短链接", + "app.title.print": "Solis | 打印标签", + "app.title.login": "Solis | 登录", + + "nav.assets": "资产", + "nav.locations": "位置", + "nav.tags": "标签", + "nav.shortlinks": "短链接", + "nav.print_labels": "打印标签", + "nav.sign_out": "退出登录", + "nav.admin_login": "管理员登录", + + "common.cancel": "取消", + "common.save": "保存更改", + "common.edit": "编辑", + "common.delete": "删除", + "common.restore": "恢复", + "common.delete_forever": "永久删除", + "common.remove": "移除", + "common.archive": "归档", + "common.filter": "筛选", + "common.reset": "重置", + "common.details": "详情", + "common.locked": "已锁定", + "common.archived": "已归档", + "common.root": "根目录", + "common.description": "描述", + "common.actions": "操作", + "common.name": "名称", + "common.back": "返回", + "common.show_removed": "显示已移除", + "common.unassigned": "未分配", + + "login.title": "登录您的资产管理系统", + "login.subtitle": "请输入管理员凭据", + "login.username": "用户名", + "login.password": "密码", + "login.submit": "登录", + + "items.title": "资产清单", + "items.subtitle": "追踪、管理和标记您的家庭设备和工具。", + "items.add": "添加资产", + "items.search_placeholder": "按资产名称、型号、序列号搜索...", + "items.all_statuses": "-- 所有状态 --", + "items.all_locations": "-- 所有位置 --", + "items.all_tags": "-- 所有标签 --", + "items.col.qr": "二维码", + "items.col.name": "名称", + "items.col.location": "位置", + "items.col.status": "状态", + "items.col.quantity": "数量", + "items.col.tags": "标签", + "items.empty.title": "未找到资产", + "items.empty.subtitle": "请调整筛选条件,或点击「添加资产」开始记录设备。", + "items.remove_item": "移除资产", + "items.archive_item": "归档资产", + "items.confirm_delete": "确定要永久删除此资产吗?这将清除磁盘上所有相关媒体文件且无法撤销。", + "items.model_prefix": "型号", + + "items.detail.title": "资产详情", + "items.detail.edit": "编辑资产", + "items.detail.back_list": "返回列表", + "items.detail.back_dir": "返回目录", + "items.detail.description": "描述", + "items.detail.no_description": "此资产暂无描述。", + "items.detail.quantity": "数量", + "items.detail.model_number": "型号", + "items.detail.serial_number": "序列号", + "items.detail.photo": "资产照片", + "items.detail.no_photo": "暂无照片", + "items.detail.receipt": "收据 / 发票", + "items.detail.no_receipt": "暂无收据文档", + "items.detail.open_doc": "打开文档", + "items.detail.custom_fields": "自定义资产元数据", + "items.detail.no_custom": "此资产未定义自定义元数据字段。", + "items.detail.qr": "资产标签二维码", + "items.detail.download_qr": "下载标签图片", + "items.detail.no_short_url": "暂无关联短链接。", + "items.detail.purchase_context": "购买信息", + "items.detail.purchase_price": "购买价格", + "items.detail.supplier": "供应商 / 经销商", + "items.detail.purchase_date": "购买日期", + "items.detail.warranty_period": "保修期", + "items.detail.months": "个月", + "items.detail.assigned_location": "所在位置", + + "items.edit.title_prefix": "编辑资产", + "items.edit.subtitle": "定义库存物品、上传文档并生成自动二维码。", + "items.edit.basic_info": "基本信息", + "items.edit.asset_name": "资产名称", + "items.edit.quantity": "数量", + "items.edit.description": "描述", + "items.edit.model_number": "型号", + "items.edit.serial_number": "序列号", + "items.edit.status": "状态", + "items.edit.location": "位置", + "items.edit.tags": "标签 / 分类", + "items.edit.purchase_warranty": "购买与保修", + "items.edit.purchase_price": "购买价格 ($)", + "items.edit.purchase_date": "购买日期", + "items.edit.warranty_months": "保修期(月)", + "items.edit.supplier": "供应商 / 商店", + "items.edit.docs_visuals": "文档与图片", + "items.edit.photo": "物品照片", + "items.edit.active_image": "当前图片", + "items.edit.receipt": "收据 / 发票文档", + "items.edit.active_receipt": "当前收据", + "items.edit.custom_fields": "自定义字段", + "items.edit.custom_fields_help": "每行输入一个自定义参数,格式为 键: 值(例如 电池: 18V锂电池)。这些将被动态解析为 SQLite JSON。", + "items.edit.custom_fields_editor": "自定义字段编辑器", + + "status.in_use": "使用中", + "status.in_storage": "存放中", + "status.borrowed": "已借出", + "status.lost": "已丢失", + "status.disposed": "已处置", + + "wizard.title": "添加新资产", + "wizard.subtitle": "通过直观的选择向导,在几秒钟内将任何设备、电器或物品编入目录。", + "wizard.step_category": "分类", + "wizard.step_item": "物品", + "wizard.step_brand": "品牌", + "wizard.category_question": "您要添加哪类物品?", + "wizard.item_question": "这是什么类型的%s?", + "wizard.brand_question": "%s是什么品牌?", + "wizard.other_unlisted": "其他 / 未列出", + "wizard.other_item": "其他物品", + "wizard.other_brand": "其他品牌", + "wizard.back": "返回上一步", + "wizard.asset_suffix": "物品", + "wizard.new_asset": "新资产", + "wizard.auto_tag_desc": "从目录分类自动创建", + "wizard.auto_desc": "通过向导自动分类:%s > %s > %s", + + "tags.title": "标签", + "tags.subtitle": "标记和分类资产,以便轻松将相似物品分组(如 工具、电子产品、易碎品)", + "tags.col.tag": "标签", + "tags.col.color": "颜色代码", + "tags.empty": "尚未定义标签。在右侧添加一个开始使用!", + "tags.show_removed": "显示已移除标签", + "tags.edit_tag": "编辑标签", + "tags.create_tag": "创建标签", + "tags.tag_name": "标签名称", + "tags.tag_color": "标签颜色", + "tags.add_tag": "添加标签", + "tags.confirm_delete": "确定要永久删除此标签吗?所有关联的物品将失去此标签引用。", + + "locations.title": "位置", + "locations.subtitle": "定义物理区域和分层存储位置(例如:房屋 > 厨房 > 抽屉A)", + "locations.col.name": "名称", + "locations.col.parent": "上级路径", + "locations.empty": "尚未定义位置。在右侧添加一个开始使用!", + "locations.show_removed": "显示已移除位置", + "locations.edit_location": "编辑位置", + "locations.create_location": "创建位置", + "locations.location_name": "位置名称", + "locations.parent_location": "上级位置(可选)", + "locations.none_root": "-- 无(根位置)--", + "locations.add_location": "添加位置", + "locations.confirm_delete": "确定要永久删除此位置吗?关联的子位置和资产将被解除关联。", + + "folder.home": "首页", + "folder.show_removed": "显示已移除的项目", + "folder.edit_location": "编辑位置", + "folder.add_asset_here": "在此添加资产", + "folder.drag_up": "将物品或文件夹拖到此处以移至上级目录", + "folder.folders": "文件夹", + "folder.no_subfolders": "此位置没有子文件夹。", + "folder.state.removed": "已移除", + "folder.state.archived": "已归档", + "folder.state.active": "活跃", + "folder.edit_folder": "编辑文件夹", + "folder.restore_folder": "恢复文件夹", + "folder.confirm_delete_location": "确定要永久删除此位置吗?内部所有物品将被移至默认房间。", + "folder.delete_permanently": "永久删除", + "folder.archive_folder": "归档文件夹", + "folder.remove_folder": "移除文件夹", + "folder.assets": "资产", + "folder.no_assets": "此位置没有找到资产。", + "folder.qty": "数量", + "folder.edit_asset": "编辑资产", + "folder.show_qr": "显示二维码", + "folder.restore_asset": "恢复资产", + "folder.confirm_delete_asset": "确定要永久删除此资产吗?此操作无法撤销。", + "folder.archive_asset": "归档资产", + "folder.remove_asset": "移除资产", + + "shortener.title": "短链接管理", + "shortener.subtitle": "管理自定义手动重定向(如保修单、外部手册)或查看自动生成的资产短链接。", + "shortener.show_removed": "显示已移除链接", + "shortener.col.slug": "短码", + "shortener.col.target_url": "目标链接", + "shortener.col.link_type": "链接类型", + "shortener.col.clicks": "点击量", + "shortener.view_qr": "查看二维码", + "shortener.asset_link": "资产链接", + "shortener.manual_redirect": "手动重定向", + "shortener.managed_by_asset": "由资产管理", + "shortener.confirm_delete": "确定要永久删除此重定向吗?此操作无法撤销。", + "shortener.empty": "暂无短链接记录。在右侧创建自定义重定向!", + "shortener.edit_redirect": "编辑重定向", + "shortener.short_slug": "短码", + "shortener.target_url": "目标链接地址", + "shortener.create_redirect": "创建重定向", + "shortener.custom_slug": "自定义短码(可选)", + "shortener.auto": "自动", + "shortener.slug_hint": "留空将自动生成4位随机短码。", + "shortener.destination_url": "目标链接", + "shortener.add_redirect": "添加重定向", + "shortener.slug_length_title": "短链接长度", + "shortener.slug_length_desc": "控制自动生成短链接的字符长度。较短的短码生成较小的二维码。更改仅适用于新创建的资产。", + "shortener.characters": "个字符", + + "print.title": "可打印二维码标签", + "print.subtitle": "为您的库存生成高保真标签页。按 Ctrl + P(或 Cmd + P)打印贴纸页。将自动应用标准打印样式。", + "print.print_sheet": "打印标签页", + "print.back_to_assets": "返回资产", + "print.guidelines_title": "打印指南", + "print.guideline_margins": "在浏览器打印对话框中将页边距设置为「无」或「最小」。", + "print.guideline_graphics": "启用「背景图形」以保留边框和对齐。", + "print.guideline_size": "检查布局预览页面大小(标准 Letter/A4),确保贴纸纸上的网格对齐。", + "print.empty": "未找到带有活跃短链接的物品。创建资产以生成标签!", + + "qr.preview": "二维码预览", + "qr.download": "下载二维码图片", + + "Tech & Electronics": "科技与电子产品", + "Kitchen Appliances": "厨房电器", + "Furniture": "家具", + "Office Supplies": "办公用品", + "Tools & Hardware": "工具与五金", + "Fitness & Sports": "健身与运动", + "Home Entertainment": "家庭娱乐", + "Gardening & Outdoor": "园艺与户外", + "Lighting & Lamps": "照明与灯具", + "Cleaning & Laundry": "清洁与洗衣", + "Smart Home Devices": "智能家居设备", + "Books & Stationery": "书籍与文具", + "Security & Safety": "安防与安全", + "Storage & Organization": "收纳与整理", + "Audio & Instruments": "音频与乐器", + + "Smartphones": "智能手机", + "Laptops": "笔记本电脑", + "Tablets": "平板电脑", + "Smartwatches": "智能手表", + "Desktop Computers": "台式电脑", + "Computer Monitors": "电脑显示器", + "Keyboards": "键盘", + "Computer Mice": "鼠标", + "Coffee Makers": "咖啡机", + "Blenders": "搅拌机", + "Toasters": "烤面包机", + "Microwaves": "微波炉", + "Air Fryers": "空气炸锅", + "Food Processors": "食物处理器", + "Juicers": "榨汁机", + "Rice Cookers": "电饭煲", + "Office Chairs": "办公椅", + "Desks": "书桌", + "Sofas": "沙发", + "Dining Tables": "餐桌", + "Mattresses": "床垫", + "Bookshelves": "书架", + "Coffee Tables": "茶几", + "Bed Frames": "床架", + "Paper Shredders": "碎纸机", + "Label Printers": "标签打印机", + "Staplers": "订书机", + "Notebooks": "笔记本", + "Pens": "笔", + "Whiteboards": "白板", + "Desk Organizers": "桌面收纳", + "Calculators": "计算器", + "Power Drills": "电钻", + "Screwdriver Sets": "螺丝刀套装", + "Hand Tool Sets": "手工具套装", + "Tape Measures": "卷尺", + "Hammers": "锤子", + "Wrenches": "扳手", + "Pliers": "钳子", + "Utility Knives": "美工刀", + "Treadmills": "跑步机", + "Exercise Bikes": "健身车", + "Dumbbells": "哑铃", + "Yoga Mats": "瑜伽垫", + "Resistance Bands": "阻力带", + "Fitness Trackers": "健身追踪器", + "Kettlebells": "壶铃", + "Foam Rollers": "泡沫轴", + "Televisions": "电视机", + "Soundbars": "回音壁", + "Streaming Devices": "流媒体设备", + "Projectors": "投影仪", + "VR Headsets": "VR头显", + "Game Consoles": "游戏主机", + "DVD/Blu-ray Players": "DVD/蓝光播放器", + "Remote Controls": "遥控器", + "Lawn Mowers": "割草机", + "Leaf Blowers": "吹叶机", + "Pruning Shears": "修枝剪", + "Garden Hoses": "花园水管", + "Watering Cans": "浇水壶", + "Wheelbarrows": "手推车", + "Weed Eaters": "除草机", + "Patio Heaters": "户外取暖器", + "Desk Lamps": "台灯", + "Floor Lamps": "落地灯", + "Smart Bulbs": "智能灯泡", + "String Lights": "串灯", + "Flashlights": "手电筒", + "Night Lights": "小夜灯", + "Ceiling Fans": "吊扇", + "Grow Lights": "植物生长灯", + "Vacuum Cleaners": "吸尘器", + "Steam Mops": "蒸汽拖把", + "Air Purifiers": "空气净化器", + "Washing Machines": "洗衣机", + "Clothes Dryers": "烘干机", + "Ironing Boards": "熨衣板", + "Steam Irons": "蒸汽熨斗", + "Robot Mops": "拖地机器人", + "Smart Speakers": "智能音箱", + "Smart Thermostats": "智能温控器", + "Security Cameras": "安防摄像头", + "Smart Doorlocks": "智能门锁", + "Video Doorbells": "视频门铃", + "Smart Plugs": "智能插座", + "Robot Vacuums": "扫地机器人", + "Smart Displays": "智能显示屏", + "Planners": "计划本", + "Sketchbooks": "素描本", + "Colored Pencils": "彩色铅笔", + "Fountain Pens": "钢笔", + "Highlighters": "荧光笔", + "Sticky Notes": "便利贴", + "Pencil Cases": "笔袋", + "Smoke Detectors": "烟雾探测器", + "Fire Extinguishers": "灭火器", + "Safes": "保险箱", + "First Aid Kits": "急救箱", + "Safety Flashlights": "安全手电筒", + "Door Barricades": "门挡", + "CO Detectors": "一氧化碳探测器", + "Motion Sensors": "运动传感器", + "Plastic Bins": "塑料收纳箱", + "Storage Racks": "储物架", + "Shoe Racks": "鞋架", + "Closet Organizers": "衣柜收纳", + "Food Containers": "食品容器", + "Hangers": "衣架", + "Cable Organizers": "线缆收纳", + "Toolboxes": "工具箱", + "Headphones": "耳机", + "Microphones": "麦克风", + "Bluetooth Speakers": "蓝牙音箱", + "Keyboards & Pianos": "键盘与钢琴", + "Guitars": "吉他", + "Audio Interfaces": "音频接口", + "Studio Monitors": "监听音箱", + "Turntables": "唱片机" +} diff --git a/internal/server/handlers.go b/internal/server/handlers.go index abcadb4..96dfee5 100644 --- a/internal/server/handlers.go +++ b/internal/server/handlers.go @@ -13,6 +13,7 @@ import ( "strings" "time" + "Solis/internal/config" "Solis/internal/db" "Solis/internal/slug" @@ -22,6 +23,7 @@ import ( // Global View Data context type PageData struct { + Lang string CSRFToken string ActiveNav string Toast string @@ -288,7 +290,7 @@ func (s *Server) handleItemNew(w http.ResponseWriter, r *http.Request) { locations, _ := s.db.ListLocations(false) tags, _ := s.db.ListTags(false) - catalogJSON, err := json.Marshal(s.catalog) + catalogJSON, err := json.Marshal(s.localizedCatalog()) if err != nil { catalogJSON = []byte("[]") } @@ -304,6 +306,25 @@ func (s *Server) handleItemNew(w http.ResponseWriter, r *http.Request) { s.render(w, r, "items.html", data) } +func (s *Server) localizedCatalog() []config.CatalogCategory { + result := make([]config.CatalogCategory, len(s.catalog)) + for i, cat := range s.catalog { + result[i] = config.CatalogCategory{ + ID: cat.ID, + Name: s.i18n.T(cat.Name), + Color: cat.Color, + Items: make([]config.CatalogItem, len(cat.Items)), + } + for j, item := range cat.Items { + result[i].Items[j] = config.CatalogItem{ + Name: s.i18n.T(item.Name), + Brands: item.Brands, + } + } + } + return result +} + func (s *Server) handleItemCreate(w http.ResponseWriter, r *http.Request) { // Limit file uploads to prevent resource exhaustion attacks r.Body = http.MaxBytesReader(w, r.Body, s.cfg.Upload.MaxSize*1024*1024) @@ -331,26 +352,26 @@ func (s *Server) handleItemCreate(w http.ResponseWriter, r *http.Request) { } else if itemVal != "" && itemVal != "Other" { name = itemVal } else if category != "" && category != "Other" { - // Find category name from ID catName := category for _, cat := range s.catalog { if cat.ID == category { - catName = cat.Name + catName = s.i18n.T(cat.Name) break } } - name = catName + " Asset" + name = catName + " " + s.i18n.T("wizard.asset_suffix") } else { - name = "New Asset" + name = s.i18n.T("wizard.new_asset") } // 3. Auto-tag with the selected catalog category var tagIDs []int64 for _, cat := range s.catalog { if cat.ID == category { - tag, err := s.db.GetTagByName(cat.Name) + tagName := s.i18n.T(cat.Name) + tag, err := s.db.GetTagByName(tagName) if err != nil { - tag, err = s.db.CreateTag(cat.Name, cat.Color, "Auto-created from catalog category") + tag, err = s.db.CreateTag(tagName, cat.Color, s.i18n.T("wizard.auto_tag_desc")) } if err == nil { tagIDs = append(tagIDs, tag.ID) @@ -365,11 +386,11 @@ func (s *Server) handleItemCreate(w http.ResponseWriter, r *http.Request) { catLabel := category for _, cat := range s.catalog { if cat.ID == category { - catLabel = cat.Name + catLabel = s.i18n.T(cat.Name) break } } - desc = fmt.Sprintf("Automatically cataloged via Wizard: %s > %s > %s", catLabel, itemVal, brand) + desc = s.i18n.TF("wizard.auto_desc", catLabel, itemVal, brand) item := &db.Item{ Name: name, @@ -1213,6 +1234,7 @@ func (s *Server) resolveRoomTag(locationID int64, tagIDs []int64) []int64 { // render automatically injects IsAuthenticated based on the session token func (s *Server) render(w http.ResponseWriter, r *http.Request, name string, data PageData) { + data.Lang = s.i18n.Lang() cookie, err := r.Cookie("session") data.IsAuthenticated = (err == nil && s.sessions.Valid(cookie.Value)) if err := renderTemplate(w, name, data); err != nil { diff --git a/internal/server/server.go b/internal/server/server.go index 072ad74..5321305 100644 --- a/internal/server/server.go +++ b/internal/server/server.go @@ -13,6 +13,7 @@ import ( "Solis/internal/config" "Solis/internal/db" + "Solis/internal/i18n" ) type Server struct { @@ -21,6 +22,7 @@ type Server struct { sessions *sessionStore limiter *rateLimiter catalog []config.CatalogCategory + i18n *i18n.Translator } func New(cfg *config.Config, database *db.DB) *Server { @@ -30,12 +32,20 @@ func New(cfg *config.Config, database *db.DB) *Server { log.Printf("Warning: failed to load catalog.json: %v. Using empty catalog.", err) cat = []config.CatalogCategory{} } + + translator, err := i18n.New(cfg.Server.Language) + if err != nil { + log.Printf("Warning: failed to load locale %q: %v. Falling back to English.", cfg.Server.Language, err) + translator, _ = i18n.New("en") + } + return &Server{ cfg: cfg, db: database, sessions: newSessionStore(ttl), - limiter: newRateLimiter(2 * time.Second), // 2 seconds between login attempts + limiter: newRateLimiter(2 * time.Second), catalog: cat, + i18n: translator, } } @@ -82,7 +92,7 @@ func lowercasePath(next http.Handler) http.Handler { } func (s *Server) Start() error { - initTemplates() + initTemplates(s.i18n) // Ensure upload directory exists if err := os.MkdirAll(s.cfg.Upload.Dir, 0755); err != nil { diff --git a/internal/server/templates.go b/internal/server/templates.go index 349cb0f..29984cf 100644 --- a/internal/server/templates.go +++ b/internal/server/templates.go @@ -9,6 +9,7 @@ import ( "time" "Solis/internal/db" + "Solis/internal/i18n" ) //go:embed all:templates @@ -22,6 +23,7 @@ var templates *template.Template var templateMap map[string]*template.Template var templateFuncs = template.FuncMap{ + "T": func(key string) string { return key }, "safeJS": func(s string) template.JS { return template.JS(s) }, @@ -94,7 +96,8 @@ var templateFuncs = template.FuncMap{ }, } -func initTemplates() { +func initTemplates(translator *i18n.Translator) { + templateFuncs["T"] = translator.T templateMap = make(map[string]*template.Template) // Pages that use the base layout — each gets its own template set diff --git a/internal/server/templates/base.html b/internal/server/templates/base.html index 3173f3c..8ba1218 100644 --- a/internal/server/templates/base.html +++ b/internal/server/templates/base.html @@ -1,9 +1,9 @@ - + - {{block "title" .}}Solis | Home Assets{{end}} + {{block "title" .}}{{T "app.title"}}{{end}} @@ -32,7 +32,7 @@ - Assets + {{T "nav.assets"}} @@ -80,7 +80,7 @@ - Sign Out + {{T "nav.sign_out"}} @@ -97,7 +97,7 @@ - Admin Login + {{T "nav.admin_login"}} @@ -123,10 +123,10 @@