Initial release: TidyQuest v0.1.0
TidyQuest is a self-hosted web application that gamifies household chores using RPG mechanics. Complete tasks, earn coins, unlock achievements, and compete with your family on the leaderboard. Features: - 🎯 Health-based task tracking with visual decay over time - 💰 Coin system with customizable rewards - 🔥 Daily/weekly streak tracking - 🏆 Family leaderboard (week/month/quarter/year) - 🎖️ Automatic achievement unlocking - 📅 Calendar view for upcoming tasks - 🌍 Multilingual support (EN/FR/DE/ES) - 📱 Optional Telegram notifications - 🏖️ Vacation mode (pause task decay) - 🐳 Docker deployment (single container) Tech Stack: - Frontend: React 19 + Vite + TypeScript - Backend: Node.js + Express + TypeScript - Database: SQLite3 with WAL mode - Auth: JWT + bcrypt - Deployment: Docker Compose Includes: - 8 room types with 60+ predefined tasks - 10 preset rewards - 12 achievement types - Complete API documentation - Security best practices guide - Comprehensive README with examples License: GNU Affero General Public License v3.0 (AGPL-3.0) This ensures TidyQuest remains free and open-source forever, preventing proprietary SaaS forks. Any modified hosted version must share source code.
This commit is contained in:
commit
a7cd81fe81
86 changed files with 20054 additions and 0 deletions
14
.env.example
Normal file
14
.env.example
Normal file
|
|
@ -0,0 +1,14 @@
|
|||
# TidyQuest Environment Variables
|
||||
# Copy this file to .env and fill in your values
|
||||
|
||||
# Server Configuration
|
||||
NODE_ENV=production
|
||||
PORT=3000
|
||||
|
||||
# Security - REQUIRED in production
|
||||
# Generate a secure random string (at least 32 characters)
|
||||
# Example: openssl rand -base64 32
|
||||
JWT_SECRET=change-this-to-a-secure-random-string-min-32-chars
|
||||
|
||||
# Database (handled by Docker volume, no config needed)
|
||||
# Database file: ./data/tidyquest.db
|
||||
9
.gitignore
vendored
Normal file
9
.gitignore
vendored
Normal file
|
|
@ -0,0 +1,9 @@
|
|||
node_modules/
|
||||
dist/
|
||||
data/*.db
|
||||
data/*.db-*
|
||||
.env
|
||||
*.log
|
||||
.DS_Store
|
||||
projet/
|
||||
PROGRESS.md
|
||||
23
Dockerfile
Normal file
23
Dockerfile
Normal file
|
|
@ -0,0 +1,23 @@
|
|||
FROM node:22-alpine AS frontend-build
|
||||
WORKDIR /app/client
|
||||
COPY client/package*.json ./
|
||||
RUN npm ci
|
||||
COPY client/ ./
|
||||
RUN npm run build
|
||||
|
||||
FROM node:22-alpine AS server-build
|
||||
WORKDIR /app/server
|
||||
COPY server/package*.json ./
|
||||
RUN npm ci
|
||||
COPY server/ ./
|
||||
RUN npx tsc
|
||||
|
||||
FROM node:22-alpine
|
||||
WORKDIR /app
|
||||
COPY server/package*.json ./server/
|
||||
RUN cd server && npm ci --omit=dev
|
||||
COPY --from=server-build /app/server/dist ./server/dist
|
||||
COPY --from=frontend-build /app/client/dist ./client/dist
|
||||
RUN mkdir -p /app/data
|
||||
EXPOSE 3000
|
||||
CMD ["node", "server/dist/index.js"]
|
||||
679
LICENSE
Normal file
679
LICENSE
Normal file
|
|
@ -0,0 +1,679 @@
|
|||
TidyQuest - Household Chore Gamification App
|
||||
Copyright (C) 2026 TidyQuest Contributors
|
||||
|
||||
This program is free software: you can redistribute it and/or modify
|
||||
it under the terms of the GNU Affero General Public License as published
|
||||
by the Free Software Foundation, either version 3 of the License, or
|
||||
(at your option) any later version.
|
||||
|
||||
This program is distributed in the hope that it will be useful,
|
||||
but WITHOUT ANY WARRANTY; without even the implied warranty of
|
||||
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
|
||||
GNU Affero General Public License for more details.
|
||||
|
||||
You should have received a copy of the GNU Affero General Public License
|
||||
along with this program. If not, see <https://www.gnu.org/licenses/>.
|
||||
|
||||
================================================================================
|
||||
|
||||
GNU AFFERO GENERAL PUBLIC LICENSE
|
||||
Version 3, 19 November 2007
|
||||
|
||||
Copyright (C) 2007 Free Software Foundation, Inc. <https://fsf.org/>
|
||||
Everyone is permitted to copy and distribute verbatim copies
|
||||
of this license document, but changing it is not allowed.
|
||||
|
||||
Preamble
|
||||
|
||||
The GNU Affero General Public License is a free, copyleft license for
|
||||
software and other kinds of works, specifically designed to ensure
|
||||
cooperation with the community in the case of network server software.
|
||||
|
||||
The licenses for most software and other practical works are designed
|
||||
to take away your freedom to share and change the works. By contrast,
|
||||
our General Public Licenses are intended to guarantee your freedom to
|
||||
share and change all versions of a program--to make sure it remains free
|
||||
software for all its users.
|
||||
|
||||
When we speak of free software, we are referring to freedom, not
|
||||
price. Our General Public Licenses are designed to make sure that you
|
||||
have the freedom to distribute copies of free software (and charge for
|
||||
them if you wish), that you receive source code or can get it if you
|
||||
want it, that you can change the software or use pieces of it in new
|
||||
free programs, and that you know you can do these things.
|
||||
|
||||
Developers that use our General Public Licenses protect your rights
|
||||
with two steps: (1) assert copyright on the software, and (2) offer
|
||||
you this License which gives you legal permission to copy, distribute
|
||||
and/or modify the software.
|
||||
|
||||
A secondary benefit of defending all users' freedom is that
|
||||
improvements made in alternate versions of the program, if they
|
||||
receive widespread use, become available for other developers to
|
||||
incorporate. Many developers of free software are heartened and
|
||||
encouraged by the resulting cooperation. However, in the case of
|
||||
software used on network servers, this result may fail to come about.
|
||||
The GNU General Public License permits making a modified version and
|
||||
letting the public access it on a server without ever releasing its
|
||||
source code to the public.
|
||||
|
||||
The GNU Affero General Public License is designed specifically to
|
||||
ensure that, in such cases, the modified source code becomes available
|
||||
to the community. It requires the operator of a network server to
|
||||
provide the source code of the modified version running there to the
|
||||
users of that server. Therefore, public use of a modified version, on
|
||||
a publicly accessible server, gives the public access to the source
|
||||
code of the modified version.
|
||||
|
||||
An older license, called the Affero General Public License and
|
||||
published by Affero, was designed to accomplish similar goals. This is
|
||||
a different license, not a version of the Affero GPL, but Affero has
|
||||
released a new version of the Affero GPL which permits relicensing under
|
||||
this license.
|
||||
|
||||
The precise terms and conditions for copying, distribution and
|
||||
modification follow.
|
||||
|
||||
TERMS AND CONDITIONS
|
||||
|
||||
0. Definitions.
|
||||
|
||||
"This License" refers to version 3 of the GNU Affero General Public License.
|
||||
|
||||
"Copyright" also means copyright-like laws that apply to other kinds of
|
||||
works, such as semiconductor masks.
|
||||
|
||||
"The Program" refers to any copyrightable work licensed under this
|
||||
License. Each licensee is addressed as "you". "Licensees" and
|
||||
"recipients" may be individuals or organizations.
|
||||
|
||||
To "modify" a work means to copy from or adapt all or part of the work
|
||||
in a fashion requiring copyright permission, other than the making of an
|
||||
exact copy. The resulting work is called a "modified version" of the
|
||||
earlier work or a work "based on" the earlier work.
|
||||
|
||||
A "covered work" means either the unmodified Program or a work based
|
||||
on the Program.
|
||||
|
||||
To "propagate" a work means to do anything with it that, without
|
||||
permission, would make you directly or secondarily liable for
|
||||
infringement under applicable copyright law, except executing it on a
|
||||
computer or modifying a private copy. Propagation includes copying,
|
||||
distribution (with or without modification), making available to the
|
||||
public, and in some countries other activities as well.
|
||||
|
||||
To "convey" a work means any kind of propagation that enables other
|
||||
parties to make or receive copies. Mere interaction with a user through
|
||||
a computer network, with no transfer of a copy, is not conveying.
|
||||
|
||||
An interactive user interface displays "Appropriate Legal Notices"
|
||||
to the extent that it includes a convenient and prominently visible
|
||||
feature that (1) displays an appropriate copyright notice, and (2)
|
||||
tells the user that there is no warranty for the work (except to the
|
||||
extent that warranties are provided), that licensees may convey the
|
||||
work under this License, and how to view a copy of this License. If
|
||||
the interface presents a list of user commands or options, such as a
|
||||
menu, a prominent item in the list meets this criterion.
|
||||
|
||||
1. Source Code.
|
||||
|
||||
The "source code" for a work means the preferred form of the work
|
||||
for making modifications to it. "Object code" means any non-source
|
||||
form of a work.
|
||||
|
||||
A "Standard Interface" means an interface that either is an official
|
||||
standard defined by a recognized standards body, or, in the case of
|
||||
interfaces specified for a particular programming language, one that
|
||||
is widely used among developers working in that language.
|
||||
|
||||
The "System Libraries" of an executable work include anything, other
|
||||
than the work as a whole, that (a) is included in the normal form of
|
||||
packaging a Major Component, but which is not part of that Major
|
||||
Component, and (b) serves only to enable use of the work with that
|
||||
Major Component, or to implement a Standard Interface for which an
|
||||
implementation is available to the public in source code form. A
|
||||
"Major Component", in this context, means a major essential component
|
||||
(kernel, window system, and so on) of the specific operating system
|
||||
(if any) on which the executable work runs, or a compiler used to
|
||||
produce the work, or an object code interpreter used to run it.
|
||||
|
||||
The "Corresponding Source" for a work in object code form means all
|
||||
the source code needed to generate, install, and (for an executable
|
||||
work) run the object code and to modify the work, including scripts to
|
||||
control those activities. However, it does not include the work's
|
||||
System Libraries, or general-purpose tools or generally available free
|
||||
programs which are used unmodified in performing those activities but
|
||||
which are not part of the work. For example, Corresponding Source
|
||||
includes interface definition files associated with source files for
|
||||
the work, and the source code for shared libraries and dynamically
|
||||
linked subprograms that the work is specifically designed to require,
|
||||
such as by intimate data communication or control flow between those
|
||||
subprograms and other parts of the work.
|
||||
|
||||
The Corresponding Source need not include anything that users
|
||||
can regenerate automatically from other parts of the Corresponding
|
||||
Source.
|
||||
|
||||
The Corresponding Source for a work in source code form is that
|
||||
same work.
|
||||
|
||||
2. Basic Permissions.
|
||||
|
||||
All rights granted under this License are granted for the term of
|
||||
copyright on the Program, and are irrevocable provided the stated
|
||||
conditions are met. This License explicitly affirms your unlimited
|
||||
permission to run the unmodified Program. The output from running a
|
||||
covered work is covered by this License only if the output, given its
|
||||
content, constitutes a covered work. This License acknowledges your
|
||||
rights of fair use or other equivalent, as provided by copyright law.
|
||||
|
||||
You may make, run and propagate covered works that you do not
|
||||
convey, without conditions so long as your license otherwise remains
|
||||
in force. You may convey covered works to others for the sole purpose
|
||||
of having them make modifications exclusively for you, or provide you
|
||||
with facilities for running those works, provided that you comply with
|
||||
the terms of this License in conveying all material for which you do
|
||||
not control copyright. Those thus making or running the covered works
|
||||
for you must do so exclusively on your behalf, under your direction
|
||||
and control, on terms that prohibit them from making any copies of
|
||||
your copyrighted material outside their relationship with you.
|
||||
|
||||
Conveying under any other circumstances is permitted solely under
|
||||
the conditions stated below. Sublicensing is not allowed; section 10
|
||||
makes it unnecessary.
|
||||
|
||||
3. Protecting Users' Legal Rights From Anti-Circumvention Law.
|
||||
|
||||
No covered work shall be deemed part of an effective technological
|
||||
measure under any applicable law fulfilling obligations under article
|
||||
11 of the WIPO copyright treaty adopted on 20 December 1996, or
|
||||
similar laws prohibiting or restricting circumvention of such
|
||||
measures.
|
||||
|
||||
When you convey a covered work, you waive any legal power to forbid
|
||||
circumvention of technological measures to the extent such circumvention
|
||||
is effected by exercising rights under this License with respect to
|
||||
the covered work, and you disclaim any intention to limit operation or
|
||||
modification of the work as a means of enforcing, against the work's
|
||||
users, your or third parties' legal rights to forbid circumvention of
|
||||
technological measures.
|
||||
|
||||
4. Conveying Verbatim Copies.
|
||||
|
||||
You may convey verbatim copies of the Program's source code as you
|
||||
receive it, in any medium, provided that you conspicuously and
|
||||
appropriately publish on each copy an appropriate copyright notice;
|
||||
keep intact all notices stating that this License and any
|
||||
non-permissive terms added in accord with section 7 apply to the code;
|
||||
keep intact all notices of the absence of any warranty; and give all
|
||||
recipients a copy of this License along with the Program.
|
||||
|
||||
You may charge any price or no price for each copy that you convey,
|
||||
and you may offer support or warranty protection for a fee.
|
||||
|
||||
5. Conveying Modified Source Versions.
|
||||
|
||||
You may convey a work based on the Program, or the modifications to
|
||||
produce it from the Program, in the form of source code under the
|
||||
terms of section 4, provided that you also meet all of these conditions:
|
||||
|
||||
a) The work must carry prominent notices stating that you modified
|
||||
it, and giving a relevant date.
|
||||
|
||||
b) The work must carry prominent notices stating that it is
|
||||
released under this License and any conditions added under section
|
||||
7. This requirement modifies the requirement in section 4 to
|
||||
"keep intact all notices".
|
||||
|
||||
c) You must license the entire work, as a whole, under this
|
||||
License to anyone who comes into possession of a copy. This
|
||||
License will therefore apply, along with any applicable section 7
|
||||
additional terms, to the whole of the work, and all its parts,
|
||||
regardless of how they are packaged. This License gives no
|
||||
permission to license the work in any other way, but it does not
|
||||
invalidate such permission if you have separately received it.
|
||||
|
||||
d) If the work has interactive user interfaces, each must display
|
||||
Appropriate Legal Notices; however, if the Program has interactive
|
||||
interfaces that do not display Appropriate Legal Notices, your
|
||||
work need not make them do so.
|
||||
|
||||
A compilation of a covered work with other separate and independent
|
||||
works, which are not by their nature extensions of the covered work,
|
||||
and which are not combined with it such as to form a larger program,
|
||||
in or on a volume of a storage or distribution medium, is called an
|
||||
"aggregate" if the compilation and its resulting copyright are not
|
||||
used to limit the access or legal rights of the compilation's users
|
||||
beyond what the individual works permit. Inclusion of a covered work
|
||||
in an aggregate does not cause this License to apply to the other
|
||||
parts of the aggregate.
|
||||
|
||||
6. Conveying Non-Source Forms.
|
||||
|
||||
You may convey a covered work in object code form under the terms
|
||||
of sections 4 and 5, provided that you also convey the
|
||||
machine-readable Corresponding Source under the terms of this License,
|
||||
in one of these ways:
|
||||
|
||||
a) Convey the object code in, or embodied in, a physical product
|
||||
(including a physical distribution medium), accompanied by the
|
||||
Corresponding Source fixed on a durable physical medium
|
||||
customarily used for software interchange.
|
||||
|
||||
b) Convey the object code in, or embodied in, a physical product
|
||||
(including a physical distribution medium), accompanied by a
|
||||
written offer, valid for at least three years and valid for as
|
||||
long as you offer spare parts or customer support for that product
|
||||
model, to give anyone who possesses the object code either (1) a
|
||||
copy of the Corresponding Source for all the software in the
|
||||
product that is covered by this License, on a durable physical
|
||||
medium customarily used for software interchange, for a price no
|
||||
more than your reasonable cost of physically performing this
|
||||
conveying of source, or (2) access to copy the
|
||||
Corresponding Source from a network server at no charge.
|
||||
|
||||
c) Convey individual copies of the object code with a copy of the
|
||||
written offer to provide the Corresponding Source. This
|
||||
alternative is allowed only occasionally and noncommercially, and
|
||||
only if you received the object code with such an offer, in accord
|
||||
with subsection 6b.
|
||||
|
||||
d) Convey the object code by offering access from a designated
|
||||
place (gratis or for a charge), and offer equivalent access to the
|
||||
Corresponding Source in the same way through the same place at no
|
||||
further charge. You need not require recipients to copy the
|
||||
Corresponding Source along with the object code. If the place to
|
||||
copy the object code is a network server, the Corresponding Source
|
||||
may be on a different server (operated by you or a third party)
|
||||
that supports equivalent copying facilities, provided you maintain
|
||||
clear directions next to the object code saying where to find the
|
||||
Corresponding Source. Regardless of what server hosts the
|
||||
Corresponding Source, you remain obligated to ensure that it is
|
||||
available for as long as needed to satisfy these requirements.
|
||||
|
||||
e) Convey the object code using peer-to-peer transmission, provided
|
||||
you inform other peers where the object code and Corresponding
|
||||
Source of the work are being offered to the general public at no
|
||||
charge under subsection 6d.
|
||||
|
||||
A separable portion of the object code, whose source code is excluded
|
||||
from the Corresponding Source as a System Library, need not be
|
||||
included in conveying the object code work.
|
||||
|
||||
A "User Product" is either (1) a "consumer product", which means any
|
||||
tangible personal property which is normally used for personal, family,
|
||||
or household purposes, or (2) anything designed or sold for incorporation
|
||||
into a dwelling. In determining whether a product is a consumer product,
|
||||
doubtful cases shall be resolved in favor of coverage. For a particular
|
||||
product received by a particular user, "normally used" refers to a
|
||||
typical or common use of that class of product, regardless of the status
|
||||
of the particular user or of the way in which the particular user
|
||||
actually uses, or expects or is expected to use, the product. A product
|
||||
is a consumer product regardless of whether the product has substantial
|
||||
commercial, industrial or non-consumer uses, unless such uses represent
|
||||
the only significant mode of use of the product.
|
||||
|
||||
"Installation Information" for a User Product means any methods,
|
||||
procedures, authorization keys, or other information required to install
|
||||
and execute modified versions of a covered work in that User Product from
|
||||
a modified version of its Corresponding Source. The information must
|
||||
suffice to ensure that the continued functioning of the modified object
|
||||
code is in no case prevented or interfered with solely because
|
||||
modification has been made.
|
||||
|
||||
If you convey an object code work under this section in, or with, or
|
||||
specifically for use in, a User Product, and the conveying occurs as
|
||||
part of a transaction in which the right of possession and use of the
|
||||
User Product is transferred to the recipient in perpetuity or for a
|
||||
fixed term (regardless of how the transaction is characterized), the
|
||||
Corresponding Source conveyed under this section must be accompanied
|
||||
by the Installation Information. But this requirement does not apply
|
||||
if neither you nor any third party retains the ability to install
|
||||
modified object code on the User Product (for example, the work has
|
||||
been installed in ROM).
|
||||
|
||||
The requirement to provide Installation Information does not include a
|
||||
requirement to continue to provide support service, warranty, or updates
|
||||
for a work that has been modified or installed by the recipient, or for
|
||||
the User Product in which it has been modified or installed. Access to a
|
||||
network may be denied when the modification itself materially and
|
||||
adversely affects the operation of the network or violates the rules and
|
||||
protocols for communication across the network.
|
||||
|
||||
Corresponding Source conveyed, and Installation Information provided,
|
||||
in accord with this section must be in a format that is publicly
|
||||
documented (and with an implementation available to the public in
|
||||
source code form), and must require no special password or key for
|
||||
unpacking, reading or copying.
|
||||
|
||||
7. Additional Terms.
|
||||
|
||||
"Additional permissions" are terms that supplement the terms of this
|
||||
License by making exceptions from one or more of its conditions.
|
||||
Additional permissions that are applicable to the entire Program shall
|
||||
be treated as though they were included in this License, to the extent
|
||||
that they are valid under applicable law. If additional permissions
|
||||
apply only to part of the Program, that part may be used separately
|
||||
under those permissions, but the entire Program remains governed by
|
||||
this License without regard to the additional permissions.
|
||||
|
||||
When you convey a copy of a covered work, you may at your option
|
||||
remove any additional permissions from that copy, or from any part of
|
||||
it. (Additional permissions may be written to require their own
|
||||
removal in certain cases when you modify the work.) You may place
|
||||
additional permissions on material, added by you to a covered work,
|
||||
for which you have or can give appropriate copyright permission.
|
||||
|
||||
Notwithstanding any other provision of this License, for material you
|
||||
add to a covered work, you may (if authorized by the copyright holders of
|
||||
that material) supplement the terms of this License with terms:
|
||||
|
||||
a) Disclaiming warranty or limiting liability differently from the
|
||||
terms of sections 15 and 16 of this License; or
|
||||
|
||||
b) Requiring preservation of specified reasonable legal notices or
|
||||
author attributions in that material or in the Appropriate Legal
|
||||
Notices displayed by works containing it; or
|
||||
|
||||
c) Prohibiting misrepresentation of the origin of that material, or
|
||||
requiring that modified versions of such material be marked in
|
||||
reasonable ways as different from the original version; or
|
||||
|
||||
d) Limiting the use for publicity purposes of names of licensors or
|
||||
authors of the material; or
|
||||
|
||||
e) Declining to grant rights under trademark law for use of some
|
||||
trade names, trademarks, or service marks; or
|
||||
|
||||
f) Requiring indemnification of licensors and authors of that
|
||||
material by anyone who conveys the material (or modified versions of
|
||||
it) with contractual assumptions of liability to the recipient, for
|
||||
any liability that these contractual assumptions directly impose on
|
||||
those licensors and authors.
|
||||
|
||||
All other non-permissive additional terms are considered "further
|
||||
restrictions" within the meaning of section 10. If the Program as you
|
||||
received it, or any part of it, contains a notice stating that it is
|
||||
governed by this License along with a term that is a further
|
||||
restriction, you may remove that term. If a license document contains
|
||||
a further restriction but permits relicensing or conveying under this
|
||||
License, you may add to a covered work material governed by the terms
|
||||
of that license document, provided that the further restriction does
|
||||
not survive such relicensing or conveying.
|
||||
|
||||
If you add terms to a covered work in accord with this section, you
|
||||
must place, in the relevant source files, a statement of the
|
||||
additional terms that apply to those files, or a notice indicating
|
||||
where to find the applicable terms.
|
||||
|
||||
Additional terms, permissive or non-permissive, may be stated in the
|
||||
form of a separately written license, or stated as exceptions;
|
||||
the above requirements apply either way.
|
||||
|
||||
8. Termination.
|
||||
|
||||
You may not propagate or modify a covered work except as expressly
|
||||
provided under this License. Any attempt otherwise to propagate or
|
||||
modify it is void, and will automatically terminate your rights under
|
||||
this License (including any patent licenses granted under the third
|
||||
paragraph of section 11).
|
||||
|
||||
However, if you cease all violation of this License, then your
|
||||
license from a particular copyright holder is reinstated (a)
|
||||
provisionally, unless and until the copyright holder explicitly and
|
||||
finally terminates your license, and (b) permanently, if the copyright
|
||||
holder fails to notify you of the violation by some reasonable means
|
||||
prior to 60 days after the cessation.
|
||||
|
||||
Moreover, your license from a particular copyright holder is
|
||||
reinstated permanently if the copyright holder notifies you of the
|
||||
violation by some reasonable means, this is the first time you have
|
||||
received notice of violation of this License (for any work) from that
|
||||
copyright holder, and you cure the violation prior to 30 days after
|
||||
your receipt of the notice.
|
||||
|
||||
Termination of your rights under this section does not terminate the
|
||||
licenses of parties who have received copies or rights from you under
|
||||
this License. If your rights have been terminated and not permanently
|
||||
reinstated, you do not qualify to receive new licenses for the same
|
||||
material under section 10.
|
||||
|
||||
9. Acceptance Not Required for Having Copies.
|
||||
|
||||
You are not required to accept this License in order to receive or
|
||||
run a copy of the Program. Ancillary propagation of a covered work
|
||||
occurring solely as a consequence of using peer-to-peer transmission
|
||||
to receive a copy likewise does not require acceptance. However,
|
||||
nothing other than this License grants you permission to propagate or
|
||||
modify any covered work. These actions infringe copyright if you do
|
||||
not accept this License. Therefore, by modifying or propagating a
|
||||
covered work, you indicate your acceptance of this License to do so.
|
||||
|
||||
10. Automatic Licensing of Downstream Recipients.
|
||||
|
||||
Each time you convey a covered work, the recipient automatically
|
||||
receives a license from the original licensors, to run, modify and
|
||||
propagate that work, subject to this License. You are not responsible
|
||||
for enforcing compliance by third parties with this License.
|
||||
|
||||
An "entity transaction" is a transaction transferring control of an
|
||||
organization, or substantially all assets of one, or subdividing an
|
||||
organization, or merging organizations. If propagation of a covered
|
||||
work results from an entity transaction, each party to that
|
||||
transaction who receives a copy of the work also receives whatever
|
||||
licenses to the work the party's predecessor in interest had or could
|
||||
give under the previous paragraph, plus a right to possession of the
|
||||
Corresponding Source of the work from the predecessor in interest, if
|
||||
the predecessor has it or can get it with reasonable efforts.
|
||||
|
||||
You may not impose any further restrictions on the exercise of the
|
||||
rights granted or affirmed under this License. For example, you may
|
||||
not impose a license fee, royalty, or other charge for exercise of
|
||||
rights granted under this License, and you may not initiate litigation
|
||||
(including a cross-claim or counterclaim in a lawsuit) alleging that
|
||||
any patent claim is infringed by making, using, selling, offering for
|
||||
sale, or importing the Program or any portion of it.
|
||||
|
||||
11. Patents.
|
||||
|
||||
A "contributor" is a copyright holder who authorizes use under this
|
||||
License of the Program or a work on which the Program is based. The
|
||||
work thus licensed is called the contributor's "contributor version".
|
||||
|
||||
A contributor's "essential patent claims" are all patent claims
|
||||
owned or controlled by the contributor, whether already acquired or
|
||||
hereafter acquired, that would be infringed by some manner, permitted
|
||||
by this License, of making, using, or selling its contributor version,
|
||||
but do not include claims that would be infringed only as a
|
||||
consequence of further modification of the contributor version. For
|
||||
purposes of this definition, "control" includes the right to grant
|
||||
patent sublicenses in a manner consistent with the requirements of
|
||||
this License.
|
||||
|
||||
Each contributor grants you a non-exclusive, worldwide, royalty-free
|
||||
patent license under the contributor's essential patent claims, to
|
||||
make, use, sell, offer for sale, import and otherwise run, modify and
|
||||
propagate the contents of its contributor version.
|
||||
|
||||
In the following three paragraphs, a "patent license" is any express
|
||||
agreement or commitment, however denominated, not to enforce a patent
|
||||
(such as an express permission to practice a patent or covenant not to
|
||||
sue for patent infringement). To "grant" such a patent license to a
|
||||
party means to make such an agreement or commitment not to enforce a
|
||||
patent against the party.
|
||||
|
||||
If you convey a covered work, knowingly relying on a patent license,
|
||||
and the Corresponding Source of the work is not available for anyone
|
||||
to copy, free of charge and under the terms of this License, through a
|
||||
publicly available network server or other readily accessible means,
|
||||
then you must either (1) cause the Corresponding Source to be so
|
||||
available, or (2) arrange to deprive yourself of the benefit of the
|
||||
patent license for this particular work, or (3) arrange, in a manner
|
||||
consistent with the requirements of this License, to extend the patent
|
||||
license to downstream recipients. "Knowingly relying" means you have
|
||||
actual knowledge that, but for the patent license, your conveying the
|
||||
covered work in a country, or your recipient's use of the covered work
|
||||
in a country, would infringe one or more identifiable patents in that
|
||||
country that you have reason to believe are valid.
|
||||
|
||||
If, pursuant to or in connection with a single transaction or
|
||||
arrangement, you convey, or propagate by procuring conveyance of, a
|
||||
covered work, and grant a patent license to some of the parties
|
||||
receiving the covered work authorizing them to use, propagate, modify
|
||||
or convey a specific copy of the covered work, then the patent license
|
||||
you grant is automatically extended to all recipients of the covered
|
||||
work and works based on it.
|
||||
|
||||
A patent license is "discriminatory" if it does not include within
|
||||
the scope of its coverage, prohibits the exercise of, or is
|
||||
conditioned on the non-exercise of one or more of the rights that are
|
||||
specifically granted under this License. You may not convey a covered
|
||||
work if you are a party to an arrangement with a third party that is
|
||||
in the business of distributing software, under which you make payment
|
||||
to the third party based on the extent of your activity of conveying
|
||||
the work, and under which the third party grants, to any of the
|
||||
parties who would receive the covered work from you, a discriminatory
|
||||
patent license (a) in connection with copies of the covered work
|
||||
conveyed by you (or copies made from those copies), or (b) primarily
|
||||
for and in connection with specific products or compilations that
|
||||
contain the covered work, unless you entered into that arrangement,
|
||||
or that patent license was granted, prior to 28 March 2007.
|
||||
|
||||
Nothing in this License shall be construed as excluding or limiting
|
||||
any implied license or other defenses to infringement that may
|
||||
otherwise be available to you under applicable patent law.
|
||||
|
||||
12. No Surrender of Others' Freedom.
|
||||
|
||||
If conditions are imposed on you (whether by court order, agreement or
|
||||
otherwise) that contradict the conditions of this License, they do not
|
||||
excuse you from the conditions of this License. If you cannot convey a
|
||||
covered work so as to satisfy simultaneously your obligations under this
|
||||
License and any other pertinent obligations, then as a consequence you may
|
||||
not convey it at all. For example, if you agree to terms that obligate you
|
||||
to collect a royalty for further conveying from those to whom you convey
|
||||
the Program, the only way you could satisfy both those terms and this
|
||||
License would be to refrain entirely from conveying the Program.
|
||||
|
||||
13. Remote Network Interaction; Use with the GNU General Public License.
|
||||
|
||||
Notwithstanding any other provision of this License, if you modify the
|
||||
Program, your modified version must prominently offer all users
|
||||
interacting with it remotely through a computer network (if your version
|
||||
supports such interaction) an opportunity to receive the Corresponding
|
||||
Source of your version by providing access to the Corresponding Source
|
||||
from a network server at no charge, through some standard or customary
|
||||
means of facilitating copying of software. This Corresponding Source
|
||||
shall include the Corresponding Source for any work covered by version 3
|
||||
of the GNU General Public License that is incorporated pursuant to the
|
||||
following paragraph.
|
||||
|
||||
Notwithstanding any other provision of this License, you have
|
||||
permission to link or combine any covered work with a work licensed
|
||||
under version 3 of the GNU General Public License into a single
|
||||
combined work, and to convey the resulting work. The terms of this
|
||||
License will continue to apply to the part which is the covered work,
|
||||
but the work with which it is combined will remain governed by version
|
||||
3 of the GNU General Public License.
|
||||
|
||||
14. Revised Versions of this License.
|
||||
|
||||
The Free Software Foundation may publish revised and/or new versions of
|
||||
the GNU Affero General Public License from time to time. Such new versions
|
||||
will be similar in spirit to the present version, but may differ in detail to
|
||||
address new problems or concerns.
|
||||
|
||||
Each version is given a distinguishing version number. If the
|
||||
Program specifies that a certain numbered version of the GNU Affero General
|
||||
Public License "or any later version" applies to it, you have the
|
||||
option of following the terms and conditions either of that numbered
|
||||
version or of any later version published by the Free Software
|
||||
Foundation. If the Program does not specify a version number of the
|
||||
GNU Affero General Public License, you may choose any version ever published
|
||||
by the Free Software Foundation.
|
||||
|
||||
If the Program specifies that a proxy can decide which future
|
||||
versions of the GNU Affero General Public License can be used, that proxy's
|
||||
public statement of acceptance of a version permanently authorizes you
|
||||
to choose that version for the Program.
|
||||
|
||||
Later license versions may give you additional or different
|
||||
permissions. However, no additional obligations are imposed on any
|
||||
author or copyright holder as a result of your choosing to follow a
|
||||
later version.
|
||||
|
||||
15. Disclaimer of Warranty.
|
||||
|
||||
THERE IS NO WARRANTY FOR THE PROGRAM, TO THE EXTENT PERMITTED BY
|
||||
APPLICABLE LAW. EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT
|
||||
HOLDERS AND/OR OTHER PARTIES PROVIDE THE PROGRAM "AS IS" WITHOUT WARRANTY
|
||||
OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO,
|
||||
THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
|
||||
PURPOSE. THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE PROGRAM
|
||||
IS WITH YOU. SHOULD THE PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF
|
||||
ALL NECESSARY SERVICING, REPAIR OR CORRECTION.
|
||||
|
||||
16. Limitation of Liability.
|
||||
|
||||
IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING
|
||||
WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MODIFIES AND/OR CONVEYS
|
||||
THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES, INCLUDING ANY
|
||||
GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE
|
||||
USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED TO LOSS OF
|
||||
DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD
|
||||
PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER PROGRAMS),
|
||||
EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF
|
||||
SUCH DAMAGES.
|
||||
|
||||
17. Interpretation of Sections 15 and 16.
|
||||
|
||||
If the disclaimer of warranty and limitation of liability provided
|
||||
above cannot be given local legal effect according to their terms,
|
||||
reviewing courts shall apply local law that most closely approximates
|
||||
an absolute waiver of all civil liability in connection with the
|
||||
Program, unless a warranty or assumption of liability accompanies a
|
||||
copy of the Program in return for a fee.
|
||||
|
||||
END OF TERMS AND CONDITIONS
|
||||
|
||||
How to Apply These Terms to Your New Programs
|
||||
|
||||
If you develop a new program, and you want it to be of the greatest
|
||||
possible use to the public, the best way to achieve this is to make it
|
||||
free software which everyone can redistribute and change under these terms.
|
||||
|
||||
To do so, attach the following notices to the program. It is safest
|
||||
to attach them to the start of each source file to most effectively
|
||||
state the exclusion of warranty; and each file should have at least
|
||||
the "copyright" line and a pointer to where the full notice is found.
|
||||
|
||||
<one line to give the program's name and a brief idea of what it does.>
|
||||
Copyright (C) <year> <name of author>
|
||||
|
||||
This program is free software: you can redistribute it and/or modify
|
||||
it under the terms of the GNU Affero General Public License as published by
|
||||
the Free Software Foundation, either version 3 of the License, or
|
||||
(at your option) any later version.
|
||||
|
||||
This program is distributed in the hope that it will be useful,
|
||||
but WITHOUT ANY WARRANTY; without even the implied warranty of
|
||||
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
|
||||
GNU Affero General Public License for more details.
|
||||
|
||||
You should have received a copy of the GNU Affero General Public License
|
||||
along with this program. If not, see <https://www.gnu.org/licenses/>.
|
||||
|
||||
Also add information on how to contact you by electronic and paper mail.
|
||||
|
||||
If your software can interact with users remotely through a computer
|
||||
network, you should also make sure that it provides a way for users to
|
||||
get its source. For example, if your program is a web application, its
|
||||
interface could display a "Source" link that leads users to an archive
|
||||
of the code. There are many ways you could offer source, and different
|
||||
solutions will be better for different programs; see section 13 for the
|
||||
specific requirements.
|
||||
|
||||
You should also get your employer (if you work as a programmer) or school,
|
||||
if any, to sign a "copyright disclaimer" for the program, if necessary.
|
||||
For more information on this, and how to apply and follow the GNU AGPL, see
|
||||
<https://www.gnu.org/licenses/>.
|
||||
287
README.md
Normal file
287
README.md
Normal file
|
|
@ -0,0 +1,287 @@
|
|||
# 🏠 TidyQuest
|
||||
|
||||
> Transform household chores into an epic family adventure
|
||||
|
||||
**TidyQuest** is a self-hosted web application that gamifies housework using RPG mechanics. Complete tasks, earn coins, unlock achievements, and compete with your family on the leaderboard.
|
||||
|
||||

|
||||

|
||||

|
||||
|
||||
---
|
||||
|
||||
## ✨ What is TidyQuest?
|
||||
|
||||
TidyQuest turns boring chores into quests:
|
||||
- **🎯 Health Bars**: Each task has a visual health indicator that decays over time
|
||||
- **💰 Coins & Rewards**: Earn coins by completing tasks, redeem for family rewards
|
||||
- **🔥 Streaks**: Build daily/weekly streaks to stay motivated
|
||||
- **🏆 Leaderboard**: Compete with family members for top position
|
||||
- **🎖️ Achievements**: Unlock badges for milestones (100 tasks, 30-day streak, etc.)
|
||||
- **📅 Calendar View**: See upcoming due dates at a glance
|
||||
- **🌍 Multilingual**: English, French, German, Spanish
|
||||
- **📱 Telegram Notifications**: Optional reminders for due tasks and rewards
|
||||
|
||||
Perfect for families who want to:
|
||||
- Make chores fun for kids
|
||||
- Track household responsibilities
|
||||
- Encourage teamwork with gamification
|
||||
- Build consistent cleaning habits
|
||||
|
||||
---
|
||||
|
||||
## 🚀 Quick Start
|
||||
|
||||
### Prerequisites
|
||||
- Docker & Docker Compose
|
||||
- 100MB disk space
|
||||
- Port 3020 available
|
||||
|
||||
### Installation (3 steps)
|
||||
|
||||
1. **Clone the repository**
|
||||
```bash
|
||||
git clone https://github.com/mellow-fox/TidyQuest.git
|
||||
cd TidyQuest
|
||||
```
|
||||
|
||||
2. **Configure environment**
|
||||
```bash
|
||||
cp .env.example .env
|
||||
# Edit .env and set a secure JWT_SECRET
|
||||
# Generate one: openssl rand -base64 32
|
||||
```
|
||||
|
||||
3. **Launch with Docker**
|
||||
```bash
|
||||
docker compose up -d --build
|
||||
```
|
||||
|
||||
Access at **http://localhost:3020**
|
||||
|
||||
### First Login
|
||||
On first launch, the database is empty. Create an admin account via the **Register** page.
|
||||
|
||||
---
|
||||
|
||||
## 🎮 Features
|
||||
|
||||
### For Everyone
|
||||
- ✅ **Complete Tasks**: Mark chores as done, earn coins
|
||||
- 💎 **Redeem Rewards**: Request rewards like "Movie Night Pick" or "Extra Game Time"
|
||||
- 📊 **Track Progress**: See your current streak, coins, and achievements
|
||||
- 🏠 **Room Management**: Organize tasks by room (Kitchen, Bedroom, Bathroom, etc.)
|
||||
|
||||
### For Admins
|
||||
- 👥 **User Management**: Create family members (admin/member/child roles)
|
||||
- 📝 **Task CRUD**: Create, edit, delete tasks with custom frequencies (1-365 days)
|
||||
- 🎁 **Reward System**: Approve/reject reward requests, manage catalog
|
||||
- ⚙️ **Global Settings**: Configure coins-per-effort, Telegram notifications
|
||||
- 🏖️ **Vacation Mode**: Pause task health decay during family vacations
|
||||
- 📤 **Backup/Restore**: Export full database as JSON
|
||||
|
||||
### Built-in Defaults
|
||||
- **8 Room Types**: Kitchen, Bedroom, Bathroom, Living Room, Office, Garage, Laundry, Garden
|
||||
- **60+ Predefined Tasks**: Common household chores with realistic frequencies
|
||||
- **10 Preset Rewards**: Movie night, ice cream, stay up late, game time, etc.
|
||||
- **12 Achievements**: Unlocked automatically based on activity
|
||||
|
||||
---
|
||||
|
||||
## 🛠️ Tech Stack
|
||||
|
||||
| Layer | Technology |
|
||||
|-------|-----------|
|
||||
| **Frontend** | React 19 + Vite + TypeScript |
|
||||
| **Backend** | Node.js + Express + TypeScript |
|
||||
| **Database** | SQLite3 (with WAL mode) |
|
||||
| **Auth** | JWT + bcrypt |
|
||||
| **Deployment** | Docker (single container, ~300MB) |
|
||||
| **Routing** | React Router v7 |
|
||||
| **Styling** | Custom CSS (no framework) |
|
||||
|
||||
**Zero external dependencies** for core functionality. Optional Telegram integration for notifications.
|
||||
|
||||
---
|
||||
|
||||
## 📂 Project Structure
|
||||
|
||||
```
|
||||
TidyQuest/
|
||||
├── client/ # React frontend
|
||||
│ ├── src/
|
||||
│ │ ├── components/ # UI components
|
||||
│ │ ├── hooks/ # useAuth, useApi, useTranslation
|
||||
│ │ ├── i18n/ # Translation files (EN/FR/DE/ES)
|
||||
│ │ └── App.tsx
|
||||
│ └── package.json
|
||||
├── server/ # Express backend
|
||||
│ ├── src/
|
||||
│ │ ├── routes/ # API endpoints
|
||||
│ │ ├── middleware/ # JWT auth
|
||||
│ │ ├── utils/ # Health calculation, notifications
|
||||
│ │ └── database.ts # SQLite setup
|
||||
│ └── package.json
|
||||
├── data/ # Persistent storage (Docker volume)
|
||||
│ ├── tidyquest.db # SQLite database
|
||||
│ └── avatars/ # User-uploaded photos
|
||||
├── Dockerfile # Multi-stage build
|
||||
├── docker-compose.yml
|
||||
├── .env.example # Configuration template
|
||||
├── SECURITY.md # Security best practices
|
||||
└── API.md # API documentation
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
## 🔧 Configuration
|
||||
|
||||
### Environment Variables
|
||||
|
||||
See `.env.example` for all options. Key variables:
|
||||
|
||||
| Variable | Required | Description |
|
||||
|----------|----------|-------------|
|
||||
| `JWT_SECRET` | **Yes** (prod) | Secret for signing JWT tokens (min 32 chars) |
|
||||
| `NODE_ENV` | No | `production` or `development` |
|
||||
| `PORT` | No | Server port (default: 3000) |
|
||||
|
||||
### Telegram Notifications (Optional)
|
||||
|
||||
1. Create a Telegram bot via [@BotFather](https://t.me/botfather)
|
||||
2. Get your chat ID via [@userinfobot](https://t.me/userinfobot)
|
||||
3. Configure in app Settings page (admin only)
|
||||
|
||||
Notification types:
|
||||
- 🕐 **Daily Due Tasks**: Sent at configured time (default 09:00)
|
||||
- 🎁 **Reward Requests**: Notify admin when child requests reward
|
||||
- 🎖️ **Achievements**: Celebrate unlocked achievements
|
||||
|
||||
---
|
||||
|
||||
## 📖 Usage
|
||||
|
||||
### Creating Rooms
|
||||
1. Go to **Rooms** page
|
||||
2. Click **Add Room**
|
||||
3. Select room type (e.g., Kitchen)
|
||||
4. Choose from 60+ default tasks or create custom ones
|
||||
|
||||
### Completing Tasks
|
||||
1. Open a room
|
||||
2. Click ✅ on a task row
|
||||
3. Earn coins (5-25 based on effort level 1-5)
|
||||
4. Health bar resets to 100%
|
||||
|
||||
### Redeeming Rewards
|
||||
1. Go to **Rewards** page
|
||||
2. Click **Redeem** on a reward (coins deducted immediately)
|
||||
3. Admin approves/rejects request
|
||||
4. If rejected, coins are refunded
|
||||
|
||||
### Vacation Mode
|
||||
Admin can enable in **Settings** to pause all health decay. Useful for family trips.
|
||||
|
||||
---
|
||||
|
||||
## 🔒 Security
|
||||
|
||||
**Before exposing publicly**, review `SECURITY.md` for:
|
||||
- Setting strong JWT_SECRET
|
||||
- Using HTTPS reverse proxy (Caddy/Nginx)
|
||||
- Database backup strategy
|
||||
- Telegram token protection
|
||||
|
||||
⚠️ **Never expose TidyQuest directly to the internet over HTTP**.
|
||||
|
||||
---
|
||||
|
||||
## 🔄 Updating
|
||||
|
||||
```bash
|
||||
cd TidyQuest
|
||||
git pull
|
||||
docker compose down
|
||||
docker compose up -d --build
|
||||
```
|
||||
|
||||
Your data persists in the `./data` volume.
|
||||
|
||||
---
|
||||
|
||||
## 🗄️ Backup & Restore
|
||||
|
||||
### Manual Backup (via UI)
|
||||
Admin → Settings → Export Data → Download JSON
|
||||
|
||||
### File System Backup
|
||||
```bash
|
||||
cp data/tidyquest.db backups/tidyquest-$(date +%Y%m%d).db
|
||||
```
|
||||
|
||||
### Restore
|
||||
Admin → Settings → Import Data → Upload JSON
|
||||
|
||||
---
|
||||
|
||||
## 🌐 API Documentation
|
||||
|
||||
See `API.md` for full endpoint documentation with examples.
|
||||
|
||||
Quick overview:
|
||||
- **Auth**: `/api/auth/register`, `/api/auth/login`
|
||||
- **Rooms**: `/api/rooms` (CRUD)
|
||||
- **Tasks**: `/api/rooms/:id/tasks` (CRUD + complete)
|
||||
- **Dashboard**: `/api/dashboard` (aggregated view)
|
||||
- **Leaderboard**: `/api/leaderboard?period=week|month|quarter|year`
|
||||
- **Rewards**: `/api/rewards` (CRUD + redeem)
|
||||
- **Achievements**: `/api/achievements`
|
||||
|
||||
All endpoints require `Authorization: Bearer <token>` (except auth routes).
|
||||
|
||||
---
|
||||
|
||||
## 🤝 Contributing
|
||||
|
||||
Contributions are welcome! Please:
|
||||
1. Fork the repository
|
||||
2. Create a feature branch (`git checkout -b feature/amazing-feature`)
|
||||
3. Commit your changes (`git commit -m 'Add amazing feature'`)
|
||||
4. Push to the branch (`git push origin feature/amazing-feature`)
|
||||
5. Open a Pull Request
|
||||
|
||||
---
|
||||
|
||||
## 📜 License
|
||||
|
||||
This project is licensed under the **GNU Affero General Public License v3.0 (AGPL-3.0)**.
|
||||
|
||||
**What this means:**
|
||||
- ✅ You can use, modify, and distribute TidyQuest freely
|
||||
- ✅ You can run it commercially (for your business/family)
|
||||
- ⚠️ If you modify and **host** TidyQuest as a service (even privately), you **must** share your source code
|
||||
- ⚠️ Any derivative work must also be licensed under AGPL-3.0
|
||||
|
||||
**Why AGPL?** To ensure TidyQuest remains free and open-source forever, preventing proprietary SaaS forks.
|
||||
|
||||
See the `LICENSE` file for full details.
|
||||
|
||||
---
|
||||
|
||||
## 🙏 Acknowledgments
|
||||
|
||||
- Inspired by RPG mechanics from classic games
|
||||
- Built with love for families who want to make chores fun
|
||||
- Uses [Nunito](https://fonts.google.com/specimen/Nunito) font (bundled locally)
|
||||
|
||||
---
|
||||
|
||||
## 📞 Support
|
||||
|
||||
- 🐛 **Bug Reports**: [GitHub Issues](https://github.com/mellow-fox/TidyQuest/issues)
|
||||
- 💬 **Discussions**: [GitHub Discussions](https://github.com/mellow-fox/TidyQuest/discussions)
|
||||
- 🔒 **Security Issues**: See `SECURITY.md` for responsible disclosure
|
||||
|
||||
---
|
||||
|
||||
Made with ❤️ for families everywhere
|
||||
167
SECURITY.md
Normal file
167
SECURITY.md
Normal file
|
|
@ -0,0 +1,167 @@
|
|||
# Security Policy
|
||||
|
||||
## 🔒 Supported Versions
|
||||
|
||||
| Version | Supported |
|
||||
| ------- | ------------------ |
|
||||
| 0.1.x | :white_check_mark: |
|
||||
|
||||
---
|
||||
|
||||
## 🛡️ Security Best Practices
|
||||
|
||||
### Before Deploying to Production
|
||||
|
||||
#### 1. **Set a Strong JWT Secret**
|
||||
|
||||
**⚠️ CRITICAL**: The JWT secret is used to sign authentication tokens. A weak or default secret compromises all user sessions.
|
||||
|
||||
**How to set it:**
|
||||
```bash
|
||||
# Generate a secure random secret
|
||||
openssl rand -base64 32
|
||||
|
||||
# Add to .env file
|
||||
echo "JWT_SECRET=<your-generated-secret>" > .env
|
||||
```
|
||||
|
||||
**In docker-compose.yml:**
|
||||
```yaml
|
||||
environment:
|
||||
- JWT_SECRET=${JWT_SECRET}
|
||||
```
|
||||
|
||||
**Never commit your `.env` file to version control.**
|
||||
|
||||
---
|
||||
|
||||
#### 2. **Use HTTPS with a Reverse Proxy**
|
||||
|
||||
TidyQuest should **never** be exposed directly to the internet over HTTP.
|
||||
|
||||
**Recommended setup:**
|
||||
- Use Caddy, Nginx, or Traefik as a reverse proxy
|
||||
- Obtain a valid TLS certificate (Let's Encrypt)
|
||||
- Forward port 443 → TidyQuest container port 3000
|
||||
|
||||
**Example with Caddy:**
|
||||
```
|
||||
tidyquest.yourdomain.com {
|
||||
reverse_proxy localhost:3020
|
||||
}
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
#### 3. **Telegram Bot Token Protection**
|
||||
|
||||
**⚠️ Known Risk**: Telegram bot tokens are stored **unencrypted** in the SQLite database.
|
||||
|
||||
**Mitigation:**
|
||||
- Restrict file system access to the `./data/` directory
|
||||
- Use proper file permissions: `chmod 600 data/tidyquest.db`
|
||||
- Never expose the database file publicly
|
||||
- Regularly back up and encrypt database backups
|
||||
|
||||
**Future improvement (planned for v0.2)**: Encrypt sensitive settings using AES-256.
|
||||
|
||||
---
|
||||
|
||||
#### 4. **Database Backups**
|
||||
|
||||
**Location**: `./data/tidyquest.db`
|
||||
|
||||
**Backup strategy:**
|
||||
```bash
|
||||
# Manual backup
|
||||
cp data/tidyquest.db backups/tidyquest-$(date +%Y%m%d).db
|
||||
|
||||
# Automated daily backup (crontab)
|
||||
0 3 * * * cd /path/to/tidyquest && cp data/tidyquest.db backups/tidyquest-$(date +\%Y\%m\%d).db
|
||||
```
|
||||
|
||||
**Encrypt backups before storing offsite:**
|
||||
```bash
|
||||
gpg -c backups/tidyquest-20260217.db
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
#### 5. **User Avatar Uploads**
|
||||
|
||||
**Current validation:**
|
||||
- MIME type check: only `image/*` allowed
|
||||
- File size limit: 2MB
|
||||
|
||||
**Additional hardening (recommended):**
|
||||
- Serve avatars from a separate domain/subdomain
|
||||
- Implement Content-Security-Policy headers
|
||||
- Consider using image processing library to re-encode uploads
|
||||
|
||||
---
|
||||
|
||||
#### 6. **Network Exposure**
|
||||
|
||||
**Default setup (Docker Compose):**
|
||||
- Port `3020:3000` is exposed on all interfaces (`0.0.0.0`)
|
||||
|
||||
**For local-only access**, bind to localhost:
|
||||
```yaml
|
||||
ports:
|
||||
- "127.0.0.1:3020:3000"
|
||||
```
|
||||
|
||||
**For VPN/LAN access**, ensure firewall rules are configured.
|
||||
|
||||
---
|
||||
|
||||
## 🚨 Reporting a Vulnerability
|
||||
|
||||
If you discover a security vulnerability in TidyQuest, please:
|
||||
|
||||
1. **Do NOT open a public GitHub issue**
|
||||
2. Email the maintainer directly (see GitHub profile)
|
||||
3. Include:
|
||||
- Description of the vulnerability
|
||||
- Steps to reproduce
|
||||
- Potential impact
|
||||
- Suggested fix (if applicable)
|
||||
|
||||
**Response time**: We aim to acknowledge reports within 48 hours and provide a fix within 7 days for critical issues.
|
||||
|
||||
---
|
||||
|
||||
## 📋 Security Checklist Before Going Public
|
||||
|
||||
- [ ] JWT_SECRET set via environment variable (not default value)
|
||||
- [ ] HTTPS reverse proxy configured
|
||||
- [ ] Database file permissions restricted (`chmod 600`)
|
||||
- [ ] Regular backup strategy in place
|
||||
- [ ] Firewall rules configured (only allow necessary ports)
|
||||
- [ ] Docker image updated to latest version
|
||||
- [ ] OS and dependencies up to date
|
||||
- [ ] Telegram bot token kept secret (if using notifications)
|
||||
- [ ] `.env` file in `.gitignore` (verified not committed)
|
||||
|
||||
---
|
||||
|
||||
## 🔐 Authentication & Session Management
|
||||
|
||||
- **Algorithm**: JWT (JSON Web Tokens)
|
||||
- **Token expiry**: 30 days
|
||||
- **Password hashing**: bcrypt (10 rounds)
|
||||
- **Authorization**: Role-based (admin, member, child)
|
||||
|
||||
**Session invalidation**: Currently, tokens remain valid until expiry. Manual revocation is not implemented (planned for v0.2).
|
||||
|
||||
---
|
||||
|
||||
## 📚 Additional Resources
|
||||
|
||||
- [OWASP Top 10](https://owasp.org/www-project-top-ten/)
|
||||
- [Docker Security Best Practices](https://docs.docker.com/engine/security/)
|
||||
- [SQLite Security Considerations](https://www.sqlite.org/security.html)
|
||||
|
||||
---
|
||||
|
||||
**Last updated**: 2026-02-17
|
||||
24
client/.gitignore
vendored
Normal file
24
client/.gitignore
vendored
Normal file
|
|
@ -0,0 +1,24 @@
|
|||
# Logs
|
||||
logs
|
||||
*.log
|
||||
npm-debug.log*
|
||||
yarn-debug.log*
|
||||
yarn-error.log*
|
||||
pnpm-debug.log*
|
||||
lerna-debug.log*
|
||||
|
||||
node_modules
|
||||
dist
|
||||
dist-ssr
|
||||
*.local
|
||||
|
||||
# Editor directories and files
|
||||
.vscode/*
|
||||
!.vscode/extensions.json
|
||||
.idea
|
||||
.DS_Store
|
||||
*.suo
|
||||
*.ntvs*
|
||||
*.njsproj
|
||||
*.sln
|
||||
*.sw?
|
||||
73
client/README.md
Normal file
73
client/README.md
Normal file
|
|
@ -0,0 +1,73 @@
|
|||
# React + TypeScript + Vite
|
||||
|
||||
This template provides a minimal setup to get React working in Vite with HMR and some ESLint rules.
|
||||
|
||||
Currently, two official plugins are available:
|
||||
|
||||
- [@vitejs/plugin-react](https://github.com/vitejs/vite-plugin-react/blob/main/packages/plugin-react) uses [Babel](https://babeljs.io/) (or [oxc](https://oxc.rs) when used in [rolldown-vite](https://vite.dev/guide/rolldown)) for Fast Refresh
|
||||
- [@vitejs/plugin-react-swc](https://github.com/vitejs/vite-plugin-react/blob/main/packages/plugin-react-swc) uses [SWC](https://swc.rs/) for Fast Refresh
|
||||
|
||||
## React Compiler
|
||||
|
||||
The React Compiler is not enabled on this template because of its impact on dev & build performances. To add it, see [this documentation](https://react.dev/learn/react-compiler/installation).
|
||||
|
||||
## Expanding the ESLint configuration
|
||||
|
||||
If you are developing a production application, we recommend updating the configuration to enable type-aware lint rules:
|
||||
|
||||
```js
|
||||
export default defineConfig([
|
||||
globalIgnores(['dist']),
|
||||
{
|
||||
files: ['**/*.{ts,tsx}'],
|
||||
extends: [
|
||||
// Other configs...
|
||||
|
||||
// Remove tseslint.configs.recommended and replace with this
|
||||
tseslint.configs.recommendedTypeChecked,
|
||||
// Alternatively, use this for stricter rules
|
||||
tseslint.configs.strictTypeChecked,
|
||||
// Optionally, add this for stylistic rules
|
||||
tseslint.configs.stylisticTypeChecked,
|
||||
|
||||
// Other configs...
|
||||
],
|
||||
languageOptions: {
|
||||
parserOptions: {
|
||||
project: ['./tsconfig.node.json', './tsconfig.app.json'],
|
||||
tsconfigRootDir: import.meta.dirname,
|
||||
},
|
||||
// other options...
|
||||
},
|
||||
},
|
||||
])
|
||||
```
|
||||
|
||||
You can also install [eslint-plugin-react-x](https://github.com/Rel1cx/eslint-react/tree/main/packages/plugins/eslint-plugin-react-x) and [eslint-plugin-react-dom](https://github.com/Rel1cx/eslint-react/tree/main/packages/plugins/eslint-plugin-react-dom) for React-specific lint rules:
|
||||
|
||||
```js
|
||||
// eslint.config.js
|
||||
import reactX from 'eslint-plugin-react-x'
|
||||
import reactDom from 'eslint-plugin-react-dom'
|
||||
|
||||
export default defineConfig([
|
||||
globalIgnores(['dist']),
|
||||
{
|
||||
files: ['**/*.{ts,tsx}'],
|
||||
extends: [
|
||||
// Other configs...
|
||||
// Enable lint rules for React
|
||||
reactX.configs['recommended-typescript'],
|
||||
// Enable lint rules for React DOM
|
||||
reactDom.configs.recommended,
|
||||
],
|
||||
languageOptions: {
|
||||
parserOptions: {
|
||||
project: ['./tsconfig.node.json', './tsconfig.app.json'],
|
||||
tsconfigRootDir: import.meta.dirname,
|
||||
},
|
||||
// other options...
|
||||
},
|
||||
},
|
||||
])
|
||||
```
|
||||
23
client/eslint.config.js
Normal file
23
client/eslint.config.js
Normal file
|
|
@ -0,0 +1,23 @@
|
|||
import js from '@eslint/js'
|
||||
import globals from 'globals'
|
||||
import reactHooks from 'eslint-plugin-react-hooks'
|
||||
import reactRefresh from 'eslint-plugin-react-refresh'
|
||||
import tseslint from 'typescript-eslint'
|
||||
import { defineConfig, globalIgnores } from 'eslint/config'
|
||||
|
||||
export default defineConfig([
|
||||
globalIgnores(['dist']),
|
||||
{
|
||||
files: ['**/*.{ts,tsx}'],
|
||||
extends: [
|
||||
js.configs.recommended,
|
||||
tseslint.configs.recommended,
|
||||
reactHooks.configs.flat.recommended,
|
||||
reactRefresh.configs.vite,
|
||||
],
|
||||
languageOptions: {
|
||||
ecmaVersion: 2020,
|
||||
globals: globals.browser,
|
||||
},
|
||||
},
|
||||
])
|
||||
13
client/index.html
Normal file
13
client/index.html
Normal file
|
|
@ -0,0 +1,13 @@
|
|||
<!doctype html>
|
||||
<html lang="en">
|
||||
<head>
|
||||
<meta charset="UTF-8" />
|
||||
<link rel="icon" type="image/svg+xml" href="/favicon.svg" />
|
||||
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
|
||||
<title>TidyQuest</title>
|
||||
</head>
|
||||
<body>
|
||||
<div id="root"></div>
|
||||
<script type="module" src="/src/main.tsx"></script>
|
||||
</body>
|
||||
</html>
|
||||
3315
client/package-lock.json
generated
Normal file
3315
client/package-lock.json
generated
Normal file
File diff suppressed because it is too large
Load diff
31
client/package.json
Normal file
31
client/package.json
Normal file
|
|
@ -0,0 +1,31 @@
|
|||
{
|
||||
"name": "client",
|
||||
"private": true,
|
||||
"version": "0.0.0",
|
||||
"type": "module",
|
||||
"scripts": {
|
||||
"dev": "vite",
|
||||
"build": "tsc -b && vite build",
|
||||
"lint": "eslint .",
|
||||
"preview": "vite preview"
|
||||
},
|
||||
"dependencies": {
|
||||
"react": "^19.2.0",
|
||||
"react-dom": "^19.2.0",
|
||||
"react-router-dom": "^7.13.0"
|
||||
},
|
||||
"devDependencies": {
|
||||
"@eslint/js": "^9.39.1",
|
||||
"@types/node": "^24.10.1",
|
||||
"@types/react": "^19.2.7",
|
||||
"@types/react-dom": "^19.2.3",
|
||||
"@vitejs/plugin-react": "^5.1.1",
|
||||
"eslint": "^9.39.1",
|
||||
"eslint-plugin-react-hooks": "^7.0.1",
|
||||
"eslint-plugin-react-refresh": "^0.4.24",
|
||||
"globals": "^16.5.0",
|
||||
"typescript": "~5.9.3",
|
||||
"typescript-eslint": "^8.48.0",
|
||||
"vite": "^7.3.1"
|
||||
}
|
||||
}
|
||||
4
client/public/favicon.svg
Normal file
4
client/public/favicon.svg
Normal file
|
|
@ -0,0 +1,4 @@
|
|||
<svg xmlns="http://www.w3.org/2000/svg" width="64" height="64" viewBox="0 0 64 64" fill="none">
|
||||
<rect x="4" y="4" width="56" height="56" rx="18" fill="#FFE8CC" stroke="#E7D1B8" stroke-width="2"/>
|
||||
<path d="M32 10L37 28L54 32L37 36L32 54L27 36L10 32L27 28L32 10Z" fill="#F97316"/>
|
||||
</svg>
|
||||
|
After Width: | Height: | Size: 290 B |
382
client/src/App.tsx
Normal file
382
client/src/App.tsx
Normal file
|
|
@ -0,0 +1,382 @@
|
|||
import { useState, useEffect, useCallback } from 'react';
|
||||
import { BrowserRouter, Routes, Route, useNavigate, useLocation, Navigate } from 'react-router-dom';
|
||||
import { useAuth } from './hooks/useAuth';
|
||||
import { api } from './hooks/useApi';
|
||||
import { Sidebar } from './components/layout/Sidebar';
|
||||
import { PageHeader } from './components/layout/PageHeader';
|
||||
import { ConfettiEffect } from './components/shared/ConfettiEffect';
|
||||
import Dashboard from './components/pages/Dashboard';
|
||||
import { RoomsList } from './components/pages/RoomsList';
|
||||
import { RoomDetail } from './components/pages/RoomDetail';
|
||||
import { Calendar } from './components/pages/Calendar';
|
||||
import { Leaderboard } from './components/pages/Leaderboard';
|
||||
import { History } from './components/pages/History';
|
||||
import { Settings } from './components/pages/Settings';
|
||||
import { Profile } from './components/pages/Profile';
|
||||
import { Login } from './components/pages/Login';
|
||||
import { Register } from './components/pages/Register';
|
||||
import { Achievements } from './components/pages/Achievements';
|
||||
import { Rewards } from './components/pages/Rewards';
|
||||
import { useTranslation } from './hooks/useTranslation';
|
||||
|
||||
function AppContent() {
|
||||
const { user, loading, login, register, logout, refreshUser } = useAuth();
|
||||
const browserLang = typeof navigator !== 'undefined' ? navigator.language.slice(0, 2) : 'en';
|
||||
const { t: tBrowser } = useTranslation(browserLang);
|
||||
const [authView, setAuthView] = useState<'login' | 'register'>('login');
|
||||
const [dashboardData, setDashboardData] = useState<any>(null);
|
||||
const [rooms, setRooms] = useState<any[]>([]);
|
||||
const [family, setFamily] = useState<any[]>([]);
|
||||
const [familySettings, setFamilySettings] = useState<any[]>([]);
|
||||
const [leaderboard, setLeaderboard] = useState<any[]>([]);
|
||||
const [leaderboardPeriod, setLeaderboardPeriod] = useState<'week' | 'month' | 'quarter' | 'year'>('week');
|
||||
const [completions, setCompletions] = useState<any[]>([]);
|
||||
const [coinsByEffort, setCoinsByEffort] = useState<Record<number, number>>({ 1: 5, 2: 10, 3: 15, 4: 20, 5: 25 });
|
||||
const [achievementsData, setAchievementsData] = useState<any>(null);
|
||||
const [rewardsData, setRewardsData] = useState<{ rewards: any[]; mine: any[] }>({ rewards: [], mine: [] });
|
||||
const [theme, setTheme] = useState<'orange' | 'blue' | 'rose' | 'night'>(() => {
|
||||
const saved = typeof localStorage !== 'undefined' ? localStorage.getItem('tidyquest_theme') : null;
|
||||
return (saved === 'blue' || saved === 'rose' || saved === 'night') ? saved : 'orange';
|
||||
});
|
||||
const [confetti, setConfetti] = useState(false);
|
||||
const navigate = useNavigate();
|
||||
const location = useLocation();
|
||||
|
||||
const loadDashboard = useCallback(async () => {
|
||||
try {
|
||||
const [dash, lb, hist, users, coinCfg, ach] = await Promise.all([
|
||||
api.dashboard(),
|
||||
api.leaderboard(leaderboardPeriod),
|
||||
api.history(50, 0),
|
||||
api.getUsers(),
|
||||
api.getCoinsConfig(),
|
||||
api.achievements(),
|
||||
]);
|
||||
setDashboardData(dash);
|
||||
setRooms(await api.getRooms());
|
||||
setLeaderboard(lb);
|
||||
setFamily(lb);
|
||||
setFamilySettings(users);
|
||||
setCompletions(hist.history || []);
|
||||
setCoinsByEffort(coinCfg.coinsByEffort || { 1: 5, 2: 10, 3: 15, 4: 20, 5: 25 });
|
||||
setAchievementsData(ach);
|
||||
} catch { /* not logged in */ }
|
||||
}, [leaderboardPeriod]);
|
||||
|
||||
useEffect(() => {
|
||||
if (user) loadDashboard();
|
||||
}, [user, loadDashboard]);
|
||||
|
||||
// Refresh data when navigating between pages
|
||||
useEffect(() => {
|
||||
if (user) {
|
||||
loadDashboard();
|
||||
loadRewards();
|
||||
}
|
||||
}, [location.pathname]); // eslint-disable-line react-hooks/exhaustive-deps
|
||||
|
||||
const loadRewards = useCallback(async () => {
|
||||
try {
|
||||
const data = await api.getRewards();
|
||||
setRewardsData(data);
|
||||
} catch {
|
||||
setRewardsData({ rewards: [], mine: [] });
|
||||
}
|
||||
}, []);
|
||||
|
||||
useEffect(() => {
|
||||
if (user) loadRewards();
|
||||
}, [user, loadRewards]);
|
||||
|
||||
useEffect(() => {
|
||||
const html = document.documentElement;
|
||||
if (theme === 'orange') {
|
||||
html.removeAttribute('data-theme');
|
||||
} else {
|
||||
html.setAttribute('data-theme', theme);
|
||||
}
|
||||
localStorage.setItem('tidyquest_theme', theme);
|
||||
}, [theme]);
|
||||
|
||||
useEffect(() => {
|
||||
document.title = 'TidyQuest';
|
||||
}, []);
|
||||
|
||||
useEffect(() => {
|
||||
if (user && (location.pathname === '/login' || location.pathname === '/register')) {
|
||||
navigate('/', { replace: true });
|
||||
}
|
||||
}, [user, location.pathname, navigate]);
|
||||
|
||||
const handleCompleteTask = async (taskId: number) => {
|
||||
try {
|
||||
setConfetti(true);
|
||||
await api.completeTask(taskId);
|
||||
await refreshUser();
|
||||
await loadDashboard();
|
||||
setTimeout(() => setConfetti(false), 2200);
|
||||
} catch (err) {
|
||||
setConfetti(false);
|
||||
console.error('Failed to complete task:', err);
|
||||
}
|
||||
};
|
||||
|
||||
const handleLeaderboardPeriodChange = async (period: 'week' | 'month' | 'quarter' | 'year') => {
|
||||
setLeaderboardPeriod(period);
|
||||
const lb = await api.leaderboard(period);
|
||||
setLeaderboard(lb);
|
||||
};
|
||||
|
||||
const handleExport = async () => {
|
||||
const data = await api.exportData();
|
||||
const blob = new Blob([JSON.stringify(data, null, 2)], { type: 'application/json' });
|
||||
const url = URL.createObjectURL(blob);
|
||||
const a = document.createElement('a');
|
||||
a.href = url;
|
||||
a.download = 'tidyquest-backup.json';
|
||||
a.click();
|
||||
URL.revokeObjectURL(url);
|
||||
};
|
||||
|
||||
const handleImport = () => {
|
||||
const input = document.createElement('input');
|
||||
input.type = 'file';
|
||||
input.accept = '.json';
|
||||
input.onchange = async (e) => {
|
||||
const file = (e.target as HTMLInputElement).files?.[0];
|
||||
if (!file) return;
|
||||
const text = await file.text();
|
||||
const data = JSON.parse(text);
|
||||
await api.importData(data);
|
||||
await loadDashboard();
|
||||
};
|
||||
input.click();
|
||||
};
|
||||
|
||||
if (loading) {
|
||||
return (
|
||||
<div style={{ minHeight: '100vh', display: 'flex', alignItems: 'center', justifyContent: 'center', backgroundColor: 'var(--warm-bg)' }}>
|
||||
<div style={{ fontSize: 18, fontWeight: 700, color: 'var(--warm-text-light)' }}>{tBrowser('common.loading')}...</div>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
if (!user) {
|
||||
if (authView === 'register') {
|
||||
return <Register onRegister={register} onSwitchToLogin={() => setAuthView('login')} />;
|
||||
}
|
||||
return <Login onLogin={login} onSwitchToRegister={() => setAuthView('register')} />;
|
||||
}
|
||||
|
||||
const { t } = useTranslation(user.language);
|
||||
const localeMap: Record<string, string> = { en: 'en-US', fr: 'fr-FR', de: 'de-DE', es: 'es-ES' };
|
||||
const today = new Date().toLocaleDateString(localeMap[user.language] || 'en-US', { weekday: 'long', month: 'long', day: 'numeric' });
|
||||
|
||||
// Build flat tasks list for calendar
|
||||
const allTasks = rooms.flatMap((r: any) =>
|
||||
(r.tasks || []).map((t: any) => ({ ...t, roomName: r.name, roomType: r.roomType }))
|
||||
);
|
||||
|
||||
return (
|
||||
<div style={{ display: 'flex', minHeight: '100vh', backgroundColor: 'var(--warm-bg)' }}>
|
||||
<ConfettiEffect show={confetti} />
|
||||
<Sidebar user={user} />
|
||||
<main style={{ marginLeft: 240, flex: 1, padding: '28px 36px', maxWidth: 1320, backgroundColor: 'var(--warm-bg)' }}>
|
||||
<Routes>
|
||||
<Route path="/" element={
|
||||
<>
|
||||
<PageHeader title={t('nav.home')} subtitle={today} user={user} onCoinsClick={() => navigate('/rewards')} onStreakClick={() => navigate('/achievements')} />
|
||||
{dashboardData && (
|
||||
<Dashboard
|
||||
data={dashboardData}
|
||||
family={family}
|
||||
language={user.language}
|
||||
onCompleteTask={handleCompleteTask}
|
||||
onNavigateToRoom={(id) => navigate(`/rooms/${id}`)}
|
||||
onNavigateToActivity={() => navigate('/activity')}
|
||||
onRewardRequestAction={async (id, status) => {
|
||||
await api.updateRedemptionStatus(id, status);
|
||||
await Promise.all([loadDashboard(), loadRewards()]);
|
||||
}}
|
||||
/>
|
||||
)}
|
||||
</>
|
||||
} />
|
||||
|
||||
<Route path="/rooms" element={
|
||||
<>
|
||||
<PageHeader title={t('nav.rooms')} subtitle={`${rooms.length} ${t('app.roomsConfigured')}`} user={user} onCoinsClick={() => navigate('/rewards')} onStreakClick={() => navigate('/achievements')} />
|
||||
<RoomsList rooms={rooms} language={user.language} onSelectRoom={(id) => navigate(`/rooms/${id}`)}
|
||||
isAdmin={user.role === 'admin'}
|
||||
onCreateRoom={async (data) => {
|
||||
await api.createRoom({ name: data.name, roomType: data.roomType, color: data.color, accentColor: data.accentColor, tasks: data.tasks });
|
||||
setRooms(await api.getRooms());
|
||||
}}
|
||||
onDeleteRoom={async (roomId) => {
|
||||
await api.deleteRoom(roomId);
|
||||
setRooms(await api.getRooms());
|
||||
}}
|
||||
/>
|
||||
</>
|
||||
} />
|
||||
|
||||
<Route path="/rooms/:id" element={
|
||||
<RoomDetailWrapper rooms={rooms} user={user} onCompleteTask={handleCompleteTask} onRefresh={loadDashboard} />
|
||||
} />
|
||||
|
||||
<Route path="/calendar" element={
|
||||
<>
|
||||
<PageHeader title={t('nav.calendar')} subtitle={t('app.calendarSubtitle')} user={user} onCoinsClick={() => navigate('/rewards')} onStreakClick={() => navigate('/achievements')} />
|
||||
<Calendar completions={completions} tasks={allTasks} language={user.language} />
|
||||
</>
|
||||
} />
|
||||
|
||||
<Route path="/leaderboard" element={
|
||||
<>
|
||||
<PageHeader title={t('app.leaderboardTitle')} subtitle={t('app.leaderboardSubtitle')} user={user} onCoinsClick={() => navigate('/rewards')} onStreakClick={() => navigate('/achievements')} />
|
||||
<Leaderboard users={leaderboard} language={user.language} period={leaderboardPeriod} onPeriodChange={handleLeaderboardPeriodChange} />
|
||||
</>
|
||||
} />
|
||||
|
||||
<Route path="/activity" element={
|
||||
<>
|
||||
<PageHeader title={t('nav.activity')} subtitle={t('app.activitySubtitle')} user={user} onCoinsClick={() => navigate('/rewards')} onStreakClick={() => navigate('/achievements')} />
|
||||
<History language={user.language} />
|
||||
</>
|
||||
} />
|
||||
<Route path="/history" element={
|
||||
<>
|
||||
<PageHeader title={t('nav.activity')} subtitle={t('app.activitySubtitle')} user={user} onCoinsClick={() => navigate('/rewards')} onStreakClick={() => navigate('/achievements')} />
|
||||
<History language={user.language} />
|
||||
</>
|
||||
} />
|
||||
|
||||
<Route path="/profile" element={
|
||||
<>
|
||||
<PageHeader title={t('nav.profile')} subtitle={t('app.profileSubtitle')} user={user} onCoinsClick={() => navigate('/rewards')} onStreakClick={() => navigate('/achievements')} />
|
||||
<Profile user={user} onSave={async () => { await refreshUser(); }} onLogout={logout} />
|
||||
</>
|
||||
} />
|
||||
|
||||
<Route path="/settings" element={
|
||||
<>
|
||||
<PageHeader title={t('nav.settings')} subtitle={t('app.settingsSubtitle')} user={user} onCoinsClick={() => navigate('/rewards')} onStreakClick={() => navigate('/achievements')} />
|
||||
<Settings
|
||||
user={user}
|
||||
family={familySettings}
|
||||
onToggleVacation={async (enabled) => {
|
||||
await api.updateSettings(user.id, { isVacationMode: enabled });
|
||||
await refreshUser();
|
||||
}}
|
||||
onUpdateRole={async (targetUserId, role) => {
|
||||
await api.updateUserRole(targetUserId, role);
|
||||
setFamilySettings(await api.getUsers());
|
||||
await refreshUser();
|
||||
}}
|
||||
onAddMember={async (member) => {
|
||||
await api.createUser(member);
|
||||
setFamilySettings(await api.getUsers());
|
||||
}}
|
||||
onDeleteUser={async (targetUserId) => {
|
||||
await api.deleteUser(targetUserId);
|
||||
setFamilySettings(await api.getUsers());
|
||||
await refreshUser();
|
||||
await loadDashboard();
|
||||
}}
|
||||
onUpdateMemberProfile={async (memberUserId, profile) => {
|
||||
await api.updateProfile(memberUserId, profile);
|
||||
setFamilySettings(await api.getUsers());
|
||||
if (memberUserId === user.id) {
|
||||
await refreshUser();
|
||||
}
|
||||
}}
|
||||
onChangePassword={async (targetUserId, payload) => {
|
||||
await api.updatePassword(targetUserId, payload);
|
||||
}}
|
||||
coinsByEffort={coinsByEffort}
|
||||
onSaveCoinsByEffort={async (values) => {
|
||||
const updated = await api.updateCoinsConfig({ coinsByEffort: values });
|
||||
setCoinsByEffort(updated.coinsByEffort);
|
||||
}}
|
||||
onResetCoinsByEffort={async () => {
|
||||
const updated = await api.updateCoinsConfig({ useDefault: true });
|
||||
setCoinsByEffort(updated.coinsByEffort);
|
||||
}}
|
||||
theme={theme}
|
||||
onChangeTheme={setTheme}
|
||||
onExport={handleExport}
|
||||
onImport={handleImport}
|
||||
/>
|
||||
</>
|
||||
} />
|
||||
<Route path="/achievements" element={
|
||||
<>
|
||||
<PageHeader title={t('nav.achievements')} subtitle={t('app.achievementsSubtitle')} user={user} onCoinsClick={() => navigate('/rewards')} onStreakClick={() => navigate('/achievements')} />
|
||||
<Achievements data={achievementsData} language={user.language} />
|
||||
</>
|
||||
} />
|
||||
<Route path="/rewards" element={
|
||||
<>
|
||||
<PageHeader title={t('nav.rewards')} subtitle={t('app.rewardsSubtitle')} user={user} onCoinsClick={() => navigate('/rewards')} onStreakClick={() => navigate('/achievements')} />
|
||||
<Rewards
|
||||
language={user.language}
|
||||
rewards={rewardsData.rewards}
|
||||
mine={rewardsData.mine}
|
||||
userCoins={user.coins}
|
||||
onRedeem={async (rewardId) => {
|
||||
await api.redeemReward(rewardId);
|
||||
await refreshUser();
|
||||
await loadDashboard();
|
||||
await loadRewards();
|
||||
}}
|
||||
onCancel={async (redemptionId) => {
|
||||
await api.cancelRedemption(redemptionId);
|
||||
await refreshUser();
|
||||
await loadDashboard();
|
||||
await loadRewards();
|
||||
}}
|
||||
/>
|
||||
</>
|
||||
} />
|
||||
<Route path="*" element={<Navigate to="/" replace />} />
|
||||
</Routes>
|
||||
</main>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
function RoomDetailWrapper({ rooms, user, onCompleteTask, onRefresh }: { rooms: any[]; user: any; onCompleteTask: (id: number) => void; onRefresh: () => void }) {
|
||||
const navigate = useNavigate();
|
||||
const { t, roomDisplayName } = useTranslation(user?.language || 'en');
|
||||
const id = parseInt(window.location.pathname.split('/').pop() || '0');
|
||||
const room = rooms.find((r) => r.id === id);
|
||||
|
||||
if (!room) {
|
||||
return (
|
||||
<div style={{ padding: 40, textAlign: 'center', color: '#B0A090', fontWeight: 600 }}>
|
||||
{t('rooms.roomNotFound')}
|
||||
<button onClick={() => navigate('/rooms')} className="tq-btn tq-btn-secondary"
|
||||
style={{ padding: '8px 18px', fontSize: 13, marginLeft: 10 }}>
|
||||
{t('rooms.backToRooms')}
|
||||
</button>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
return (
|
||||
<>
|
||||
<PageHeader title={roomDisplayName(room.name, room.roomType)} subtitle={`${room.tasks?.length || 0} ${t('rooms.tasksTracked')}`} user={user} onCoinsClick={() => navigate('/rewards')} onStreakClick={() => navigate('/achievements')} />
|
||||
<RoomDetail room={room} language={user?.language} isAdmin={user?.role === 'admin'} onCompleteTask={onCompleteTask} onBack={() => navigate('/rooms')} onRefresh={onRefresh} />
|
||||
</>
|
||||
);
|
||||
}
|
||||
|
||||
function App() {
|
||||
return (
|
||||
<BrowserRouter>
|
||||
<AppContent />
|
||||
</BrowserRouter>
|
||||
);
|
||||
}
|
||||
|
||||
export default App;
|
||||
BIN
client/src/assets/fonts/Nunito-400.ttf
Normal file
BIN
client/src/assets/fonts/Nunito-400.ttf
Normal file
Binary file not shown.
BIN
client/src/assets/fonts/Nunito-500.ttf
Normal file
BIN
client/src/assets/fonts/Nunito-500.ttf
Normal file
Binary file not shown.
BIN
client/src/assets/fonts/Nunito-600.ttf
Normal file
BIN
client/src/assets/fonts/Nunito-600.ttf
Normal file
Binary file not shown.
BIN
client/src/assets/fonts/Nunito-700.ttf
Normal file
BIN
client/src/assets/fonts/Nunito-700.ttf
Normal file
Binary file not shown.
BIN
client/src/assets/fonts/Nunito-800.ttf
Normal file
BIN
client/src/assets/fonts/Nunito-800.ttf
Normal file
Binary file not shown.
BIN
client/src/assets/fonts/Nunito-900.ttf
Normal file
BIN
client/src/assets/fonts/Nunito-900.ttf
Normal file
Binary file not shown.
42
client/src/assets/fonts/nunito.css
Normal file
42
client/src/assets/fonts/nunito.css
Normal file
|
|
@ -0,0 +1,42 @@
|
|||
@font-face {
|
||||
font-family: 'Nunito';
|
||||
font-style: normal;
|
||||
font-weight: 400;
|
||||
font-display: swap;
|
||||
src: url(https://fonts.gstatic.com/s/nunito/v32/XRXI3I6Li01BKofiOc5wtlZ2di8HDLshRTM.ttf) format('truetype');
|
||||
}
|
||||
@font-face {
|
||||
font-family: 'Nunito';
|
||||
font-style: normal;
|
||||
font-weight: 500;
|
||||
font-display: swap;
|
||||
src: url(https://fonts.gstatic.com/s/nunito/v32/XRXI3I6Li01BKofiOc5wtlZ2di8HDIkhRTM.ttf) format('truetype');
|
||||
}
|
||||
@font-face {
|
||||
font-family: 'Nunito';
|
||||
font-style: normal;
|
||||
font-weight: 600;
|
||||
font-display: swap;
|
||||
src: url(https://fonts.gstatic.com/s/nunito/v32/XRXI3I6Li01BKofiOc5wtlZ2di8HDGUmRTM.ttf) format('truetype');
|
||||
}
|
||||
@font-face {
|
||||
font-family: 'Nunito';
|
||||
font-style: normal;
|
||||
font-weight: 700;
|
||||
font-display: swap;
|
||||
src: url(https://fonts.gstatic.com/s/nunito/v32/XRXI3I6Li01BKofiOc5wtlZ2di8HDFwmRTM.ttf) format('truetype');
|
||||
}
|
||||
@font-face {
|
||||
font-family: 'Nunito';
|
||||
font-style: normal;
|
||||
font-weight: 800;
|
||||
font-display: swap;
|
||||
src: url(https://fonts.gstatic.com/s/nunito/v32/XRXI3I6Li01BKofiOc5wtlZ2di8HDDsmRTM.ttf) format('truetype');
|
||||
}
|
||||
@font-face {
|
||||
font-family: 'Nunito';
|
||||
font-style: normal;
|
||||
font-weight: 900;
|
||||
font-display: swap;
|
||||
src: url(https://fonts.gstatic.com/s/nunito/v32/XRXI3I6Li01BKofiOc5wtlZ2di8HDBImRTM.ttf) format('truetype');
|
||||
}
|
||||
260
client/src/components/icons/AvatarPresets.tsx
Normal file
260
client/src/components/icons/AvatarPresets.tsx
Normal file
|
|
@ -0,0 +1,260 @@
|
|||
interface PresetProps {
|
||||
size?: number;
|
||||
}
|
||||
|
||||
function Cat({ size = 38 }: PresetProps) {
|
||||
return (
|
||||
<svg width={size} height={size} viewBox="0 0 100 100" fill="none">
|
||||
<circle cx="50" cy="54" r="40" fill="#FFD4A8" />
|
||||
<polygon points="18,30 10,2 38,22" fill="#FFD4A8" stroke="#F5B07A" strokeWidth="2" />
|
||||
<polygon points="82,30 90,2 62,22" fill="#FFD4A8" stroke="#F5B07A" strokeWidth="2" />
|
||||
<polygon points="22,26 16,8 36,22" fill="#FFB5C5" />
|
||||
<polygon points="78,26 84,8 64,22" fill="#FFB5C5" />
|
||||
<circle cx="38" cy="48" r="5" fill="#4A3728" />
|
||||
<circle cx="62" cy="48" r="5" fill="#4A3728" />
|
||||
<circle cx="40" cy="46" r="1.5" fill="white" />
|
||||
<circle cx="64" cy="46" r="1.5" fill="white" />
|
||||
<ellipse cx="50" cy="58" rx="4" ry="3" fill="#FFB5C5" />
|
||||
<path d="M46 62 Q50 67 54 62" stroke="#4A3728" strokeWidth="1.5" fill="none" strokeLinecap="round" />
|
||||
<line x1="20" y1="52" x2="35" y2="54" stroke="#D4A574" strokeWidth="1" />
|
||||
<line x1="20" y1="58" x2="35" y2="58" stroke="#D4A574" strokeWidth="1" />
|
||||
<line x1="65" y1="54" x2="80" y2="52" stroke="#D4A574" strokeWidth="1" />
|
||||
<line x1="65" y1="58" x2="80" y2="58" stroke="#D4A574" strokeWidth="1" />
|
||||
</svg>
|
||||
);
|
||||
}
|
||||
|
||||
function Dog({ size = 38 }: PresetProps) {
|
||||
return (
|
||||
<svg width={size} height={size} viewBox="0 0 100 100" fill="none">
|
||||
<circle cx="50" cy="54" r="40" fill="#D4A574" />
|
||||
<ellipse cx="24" cy="40" rx="16" ry="24" fill="#A0714F" transform="rotate(-15 24 40)" />
|
||||
<ellipse cx="76" cy="40" rx="16" ry="24" fill="#A0714F" transform="rotate(15 76 40)" />
|
||||
<circle cx="38" cy="48" r="5" fill="#4A3728" />
|
||||
<circle cx="62" cy="48" r="5" fill="#4A3728" />
|
||||
<circle cx="40" cy="46" r="1.5" fill="white" />
|
||||
<circle cx="64" cy="46" r="1.5" fill="white" />
|
||||
<ellipse cx="50" cy="60" rx="6" ry="5" fill="#4A3728" />
|
||||
<ellipse cx="50" cy="59" rx="3" ry="2" fill="#8B6F5E" />
|
||||
<path d="M44 66 Q50 72 56 66" stroke="#4A3728" strokeWidth="1.5" fill="none" strokeLinecap="round" />
|
||||
<ellipse cx="50" cy="72" rx="8" ry="4" fill="#FFD4A8" />
|
||||
</svg>
|
||||
);
|
||||
}
|
||||
|
||||
function Bunny({ size = 38 }: PresetProps) {
|
||||
return (
|
||||
<svg width={size} height={size} viewBox="0 0 100 100" fill="none">
|
||||
<circle cx="50" cy="60" r="36" fill="#F5F0EB" />
|
||||
<ellipse cx="38" cy="22" rx="10" ry="28" fill="#F5F0EB" stroke="#E8DDD4" strokeWidth="1.5" />
|
||||
<ellipse cx="62" cy="22" rx="10" ry="28" fill="#F5F0EB" stroke="#E8DDD4" strokeWidth="1.5" />
|
||||
<ellipse cx="38" cy="22" rx="5" ry="20" fill="#FFB5C5" />
|
||||
<ellipse cx="62" cy="22" rx="5" ry="20" fill="#FFB5C5" />
|
||||
<circle cx="40" cy="54" r="4" fill="#4A3728" />
|
||||
<circle cx="60" cy="54" r="4" fill="#4A3728" />
|
||||
<circle cx="41.5" cy="52.5" r="1.2" fill="white" />
|
||||
<circle cx="61.5" cy="52.5" r="1.2" fill="white" />
|
||||
<ellipse cx="50" cy="62" rx="3" ry="2.5" fill="#FFB5C5" />
|
||||
<path d="M47 65 Q50 69 53 65" stroke="#4A3728" strokeWidth="1.2" fill="none" strokeLinecap="round" />
|
||||
<circle cx="34" cy="64" r="6" fill="#FFD4D4" opacity="0.5" />
|
||||
<circle cx="66" cy="64" r="6" fill="#FFD4D4" opacity="0.5" />
|
||||
</svg>
|
||||
);
|
||||
}
|
||||
|
||||
function Bear({ size = 38 }: PresetProps) {
|
||||
return (
|
||||
<svg width={size} height={size} viewBox="0 0 100 100" fill="none">
|
||||
<circle cx="50" cy="56" r="38" fill="#C4956A" />
|
||||
<circle cx="24" cy="28" r="14" fill="#C4956A" />
|
||||
<circle cx="76" cy="28" r="14" fill="#C4956A" />
|
||||
<circle cx="24" cy="28" r="8" fill="#A0714F" />
|
||||
<circle cx="76" cy="28" r="8" fill="#A0714F" />
|
||||
<circle cx="50" cy="62" r="18" fill="#D4A574" />
|
||||
<circle cx="40" cy="50" r="4.5" fill="#4A3728" />
|
||||
<circle cx="60" cy="50" r="4.5" fill="#4A3728" />
|
||||
<circle cx="41.5" cy="48.5" r="1.3" fill="white" />
|
||||
<circle cx="61.5" cy="48.5" r="1.3" fill="white" />
|
||||
<ellipse cx="50" cy="60" rx="5" ry="4" fill="#4A3728" />
|
||||
<path d="M46 66 Q50 71 54 66" stroke="#4A3728" strokeWidth="1.5" fill="none" strokeLinecap="round" />
|
||||
</svg>
|
||||
);
|
||||
}
|
||||
|
||||
function Fox({ size = 38 }: PresetProps) {
|
||||
return (
|
||||
<svg width={size} height={size} viewBox="0 0 100 100" fill="none">
|
||||
<circle cx="50" cy="56" r="38" fill="#F97316" />
|
||||
<polygon points="20,34 8,4 40,26" fill="#F97316" stroke="#E8650E" strokeWidth="1.5" />
|
||||
<polygon points="80,34 92,4 60,26" fill="#F97316" stroke="#E8650E" strokeWidth="1.5" />
|
||||
<polygon points="24,30 14,10 38,26" fill="#FFD4A8" />
|
||||
<polygon points="76,30 86,10 62,26" fill="#FFD4A8" />
|
||||
<ellipse cx="50" cy="68" rx="22" ry="18" fill="white" />
|
||||
<circle cx="38" cy="50" r="4.5" fill="#4A3728" />
|
||||
<circle cx="62" cy="50" r="4.5" fill="#4A3728" />
|
||||
<circle cx="39.5" cy="48.5" r="1.3" fill="white" />
|
||||
<circle cx="63.5" cy="48.5" r="1.3" fill="white" />
|
||||
<ellipse cx="50" cy="60" rx="4" ry="3" fill="#4A3728" />
|
||||
<path d="M46 64 Q50 68 54 64" stroke="#4A3728" strokeWidth="1.5" fill="none" strokeLinecap="round" />
|
||||
</svg>
|
||||
);
|
||||
}
|
||||
|
||||
function Owl({ size = 38 }: PresetProps) {
|
||||
return (
|
||||
<svg width={size} height={size} viewBox="0 0 100 100" fill="none">
|
||||
<circle cx="50" cy="56" r="38" fill="#A0714F" />
|
||||
<polygon points="32,22 50,8 68,22" fill="#A0714F" />
|
||||
<polygon points="36,24 50,14 64,24" fill="#C4956A" />
|
||||
<circle cx="38" cy="48" r="12" fill="white" />
|
||||
<circle cx="62" cy="48" r="12" fill="white" />
|
||||
<circle cx="38" cy="48" r="6" fill="#4A3728" />
|
||||
<circle cx="62" cy="48" r="6" fill="#4A3728" />
|
||||
<circle cx="40" cy="46" r="2" fill="white" />
|
||||
<circle cx="64" cy="46" r="2" fill="white" />
|
||||
<polygon points="50,56 46,62 54,62" fill="#F59E0B" />
|
||||
<ellipse cx="50" cy="74" rx="16" ry="10" fill="#C4956A" />
|
||||
<path d="M42 74 L50 70 L58 74" stroke="#A0714F" strokeWidth="1.5" fill="none" />
|
||||
</svg>
|
||||
);
|
||||
}
|
||||
|
||||
function Panda({ size = 38 }: PresetProps) {
|
||||
return (
|
||||
<svg width={size} height={size} viewBox="0 0 100 100" fill="none">
|
||||
<circle cx="50" cy="56" r="38" fill="white" />
|
||||
<circle cx="26" cy="30" r="13" fill="#4A3728" />
|
||||
<circle cx="74" cy="30" r="13" fill="#4A3728" />
|
||||
<ellipse cx="36" cy="48" rx="12" ry="11" fill="#4A3728" />
|
||||
<ellipse cx="64" cy="48" rx="12" ry="11" fill="#4A3728" />
|
||||
<circle cx="36" cy="48" r="5" fill="white" />
|
||||
<circle cx="64" cy="48" r="5" fill="white" />
|
||||
<circle cx="37" cy="47" r="1.5" fill="white" />
|
||||
<circle cx="65" cy="47" r="1.5" fill="white" />
|
||||
<ellipse cx="50" cy="60" rx="5" ry="4" fill="#4A3728" />
|
||||
<path d="M46 65 Q50 69 54 65" stroke="#4A3728" strokeWidth="1.5" fill="none" strokeLinecap="round" />
|
||||
</svg>
|
||||
);
|
||||
}
|
||||
|
||||
function Penguin({ size = 38 }: PresetProps) {
|
||||
return (
|
||||
<svg width={size} height={size} viewBox="0 0 100 100" fill="none">
|
||||
<circle cx="50" cy="56" r="38" fill="#374151" />
|
||||
<ellipse cx="50" cy="64" rx="24" ry="26" fill="white" />
|
||||
<circle cx="38" cy="44" r="4.5" fill="white" />
|
||||
<circle cx="62" cy="44" r="4.5" fill="white" />
|
||||
<circle cx="38" cy="44" r="2.5" fill="#4A3728" />
|
||||
<circle cx="62" cy="44" r="2.5" fill="#4A3728" />
|
||||
<circle cx="39" cy="43" r="0.8" fill="white" />
|
||||
<circle cx="63" cy="43" r="0.8" fill="white" />
|
||||
<polygon points="50,52 44,58 56,58" fill="#F59E0B" />
|
||||
<circle cx="40" cy="60" r="5" fill="#FFB5C5" opacity="0.4" />
|
||||
<circle cx="60" cy="60" r="5" fill="#FFB5C5" opacity="0.4" />
|
||||
</svg>
|
||||
);
|
||||
}
|
||||
|
||||
function Unicorn({ size = 38 }: PresetProps) {
|
||||
return (
|
||||
<svg width={size} height={size} viewBox="0 0 100 100" fill="none">
|
||||
<circle cx="50" cy="58" r="36" fill="#F5F0EB" />
|
||||
<polygon points="50,2 44,30 56,30" fill="#FFD700" stroke="#F59E0B" strokeWidth="1" />
|
||||
<ellipse cx="34" cy="28" rx="8" ry="16" fill="#F5F0EB" stroke="#E8DDD4" strokeWidth="1" />
|
||||
<ellipse cx="66" cy="28" rx="8" ry="16" fill="#F5F0EB" stroke="#E8DDD4" strokeWidth="1" />
|
||||
<ellipse cx="34" cy="28" rx="4" ry="10" fill="#FFB5C5" />
|
||||
<ellipse cx="66" cy="28" rx="4" ry="10" fill="#FFB5C5" />
|
||||
<circle cx="40" cy="54" r="4" fill="#4A3728" />
|
||||
<circle cx="60" cy="54" r="4" fill="#4A3728" />
|
||||
<circle cx="41.2" cy="52.5" r="1.2" fill="white" />
|
||||
<circle cx="61.2" cy="52.5" r="1.2" fill="white" />
|
||||
<path d="M47 64 Q50 68 53 64" stroke="#4A3728" strokeWidth="1.2" fill="none" strokeLinecap="round" />
|
||||
<circle cx="36" cy="64" r="5" fill="#FFD4D4" opacity="0.4" />
|
||||
<circle cx="64" cy="64" r="5" fill="#FFD4D4" opacity="0.4" />
|
||||
<path d="M28 76 Q34 82 38 76 Q42 82 46 76" stroke="#FFB5C5" strokeWidth="2" fill="none" />
|
||||
<path d="M54 76 Q58 82 62 76 Q66 82 70 76" stroke="#B5DEFF" strokeWidth="2" fill="none" />
|
||||
</svg>
|
||||
);
|
||||
}
|
||||
|
||||
function Frog({ size = 38 }: PresetProps) {
|
||||
return (
|
||||
<svg width={size} height={size} viewBox="0 0 100 100" fill="none">
|
||||
<circle cx="50" cy="58" r="36" fill="#6DBE6D" />
|
||||
<circle cx="34" cy="32" r="12" fill="#6DBE6D" />
|
||||
<circle cx="66" cy="32" r="12" fill="#6DBE6D" />
|
||||
<circle cx="34" cy="32" r="8" fill="white" />
|
||||
<circle cx="66" cy="32" r="8" fill="white" />
|
||||
<circle cx="34" cy="32" r="4" fill="#4A3728" />
|
||||
<circle cx="66" cy="32" r="4" fill="#4A3728" />
|
||||
<circle cx="35.5" cy="30.5" r="1.2" fill="white" />
|
||||
<circle cx="67.5" cy="30.5" r="1.2" fill="white" />
|
||||
<path d="M34 58 Q50 72 66 58" stroke="#4A8C4A" strokeWidth="2" fill="none" strokeLinecap="round" />
|
||||
<circle cx="36" cy="52" r="6" fill="#FFB5C5" opacity="0.3" />
|
||||
<circle cx="64" cy="52" r="6" fill="#FFB5C5" opacity="0.3" />
|
||||
</svg>
|
||||
);
|
||||
}
|
||||
|
||||
function Koala({ size = 38 }: PresetProps) {
|
||||
return (
|
||||
<svg width={size} height={size} viewBox="0 0 100 100" fill="none">
|
||||
<circle cx="50" cy="56" r="36" fill="#9CA3AF" />
|
||||
<circle cx="22" cy="40" r="16" fill="#9CA3AF" />
|
||||
<circle cx="78" cy="40" r="16" fill="#9CA3AF" />
|
||||
<circle cx="22" cy="40" r="10" fill="#D1D5DB" />
|
||||
<circle cx="78" cy="40" r="10" fill="#D1D5DB" />
|
||||
<circle cx="40" cy="50" r="4" fill="#4A3728" />
|
||||
<circle cx="60" cy="50" r="4" fill="#4A3728" />
|
||||
<circle cx="41.2" cy="48.5" r="1.2" fill="white" />
|
||||
<circle cx="61.2" cy="48.5" r="1.2" fill="white" />
|
||||
<ellipse cx="50" cy="60" rx="8" ry="6" fill="#4A3728" />
|
||||
<ellipse cx="50" cy="58" rx="4" ry="2.5" fill="#6B5B4F" />
|
||||
</svg>
|
||||
);
|
||||
}
|
||||
|
||||
function Hedgehog({ size = 38 }: PresetProps) {
|
||||
return (
|
||||
<svg width={size} height={size} viewBox="0 0 100 100" fill="none">
|
||||
<ellipse cx="50" cy="50" rx="44" ry="40" fill="#8B6F5E" />
|
||||
<path d="M20 30 L26 18 L30 30" fill="#6B5347" />
|
||||
<path d="M30 24 L36 10 L40 24" fill="#6B5347" />
|
||||
<path d="M40 20 L46 6 L52 20" fill="#6B5347" />
|
||||
<path d="M52 20 L56 6 L62 20" fill="#6B5347" />
|
||||
<path d="M62 24 L66 10 L72 24" fill="#6B5347" />
|
||||
<path d="M72 30 L76 18 L82 30" fill="#6B5347" />
|
||||
<ellipse cx="50" cy="62" rx="30" ry="26" fill="#FFD4A8" />
|
||||
<circle cx="40" cy="54" r="3.5" fill="#4A3728" />
|
||||
<circle cx="60" cy="54" r="3.5" fill="#4A3728" />
|
||||
<circle cx="41" cy="52.5" r="1" fill="white" />
|
||||
<circle cx="61" cy="52.5" r="1" fill="white" />
|
||||
<circle cx="50" cy="62" r="4" fill="#4A3728" />
|
||||
<path d="M46 68 Q50 72 54 68" stroke="#4A3728" strokeWidth="1.2" fill="none" strokeLinecap="round" />
|
||||
<circle cx="38" cy="64" r="5" fill="#FFB5C5" opacity="0.3" />
|
||||
<circle cx="62" cy="64" r="5" fill="#FFB5C5" opacity="0.3" />
|
||||
</svg>
|
||||
);
|
||||
}
|
||||
|
||||
export const AVATAR_PRESETS: Record<string, { component: React.FC<PresetProps>; label: string; color: string }> = {
|
||||
cat: { component: Cat, label: 'Cat', color: '#FFD4A8' },
|
||||
dog: { component: Dog, label: 'Dog', color: '#D4A574' },
|
||||
bunny: { component: Bunny, label: 'Bunny', color: '#F5F0EB' },
|
||||
bear: { component: Bear, label: 'Bear', color: '#C4956A' },
|
||||
fox: { component: Fox, label: 'Fox', color: '#F97316' },
|
||||
owl: { component: Owl, label: 'Owl', color: '#A0714F' },
|
||||
panda: { component: Panda, label: 'Panda', color: '#E5E7EB' },
|
||||
penguin: { component: Penguin, label: 'Penguin', color: '#374151' },
|
||||
unicorn: { component: Unicorn, label: 'Unicorn', color: '#F5F0EB' },
|
||||
frog: { component: Frog, label: 'Frog', color: '#6DBE6D' },
|
||||
koala: { component: Koala, label: 'Koala', color: '#9CA3AF' },
|
||||
hedgehog: { component: Hedgehog, label: 'Hedgehog', color: '#8B6F5E' },
|
||||
};
|
||||
|
||||
export function AvatarPresetIcon({ presetId, size = 38 }: { presetId: string; size?: number }) {
|
||||
const preset = AVATAR_PRESETS[presetId];
|
||||
if (!preset) return null;
|
||||
const Component = preset.component;
|
||||
return <Component size={size} />;
|
||||
}
|
||||
187
client/src/components/icons/NavIcons.tsx
Normal file
187
client/src/components/icons/NavIcons.tsx
Normal file
|
|
@ -0,0 +1,187 @@
|
|||
interface NavIconProps {
|
||||
active: boolean;
|
||||
}
|
||||
|
||||
export function HomeIcon({ active }: NavIconProps) {
|
||||
return (
|
||||
<svg width="26" height="26" viewBox="0 0 26 26" fill="none">
|
||||
<path
|
||||
d="M4 11.5L13 4L22 11.5V21C22 21.55 21.55 22 21 22H5C4.45 22 4 21.55 4 21V11.5Z"
|
||||
fill={active ? "#F97316" : "none"}
|
||||
stroke={active ? "#F97316" : "#B0A090"}
|
||||
strokeWidth="2"
|
||||
strokeLinecap="round"
|
||||
strokeLinejoin="round"
|
||||
/>
|
||||
<path
|
||||
d="M10 22V14H16V22"
|
||||
stroke={active ? "#fff" : "#B0A090"}
|
||||
strokeWidth="2"
|
||||
strokeLinecap="round"
|
||||
strokeLinejoin="round"
|
||||
/>
|
||||
</svg>
|
||||
);
|
||||
}
|
||||
|
||||
export function RoomsIcon({ active }: NavIconProps) {
|
||||
return (
|
||||
<svg width="26" height="26" viewBox="0 0 26 26" fill="none">
|
||||
<rect
|
||||
x="3" y="3" width="8.5" height="8.5" rx="3"
|
||||
fill={active ? "#F97316" : "none"}
|
||||
stroke={active ? "#F97316" : "#B0A090"}
|
||||
strokeWidth="2"
|
||||
/>
|
||||
<rect
|
||||
x="14.5" y="3" width="8.5" height="8.5" rx="3"
|
||||
fill={active ? "#F9731666" : "none"}
|
||||
stroke={active ? "#F97316" : "#B0A090"}
|
||||
strokeWidth="2"
|
||||
/>
|
||||
<rect
|
||||
x="3" y="14.5" width="8.5" height="8.5" rx="3"
|
||||
fill={active ? "#F9731666" : "none"}
|
||||
stroke={active ? "#F97316" : "#B0A090"}
|
||||
strokeWidth="2"
|
||||
/>
|
||||
<rect
|
||||
x="14.5" y="14.5" width="8.5" height="8.5" rx="3"
|
||||
fill={active ? "#F9731644" : "none"}
|
||||
stroke={active ? "#F97316" : "#B0A090"}
|
||||
strokeWidth="2"
|
||||
/>
|
||||
</svg>
|
||||
);
|
||||
}
|
||||
|
||||
export function TrophyIcon({ active }: NavIconProps) {
|
||||
return (
|
||||
<svg width="26" height="26" viewBox="0 0 26 26" fill="none">
|
||||
<path
|
||||
d="M8 4H18V12C18 14.76 15.76 17 13 17C10.24 17 8 14.76 8 12V4Z"
|
||||
fill={active ? "#F97316" : "none"}
|
||||
stroke={active ? "#F97316" : "#B0A090"}
|
||||
strokeWidth="2"
|
||||
/>
|
||||
<path
|
||||
d="M8 6H5C5 9 6.5 10 8 10"
|
||||
stroke={active ? "#F97316" : "#B0A090"}
|
||||
strokeWidth="2"
|
||||
strokeLinecap="round"
|
||||
/>
|
||||
<path
|
||||
d="M18 6H21C21 9 19.5 10 18 10"
|
||||
stroke={active ? "#F97316" : "#B0A090"}
|
||||
strokeWidth="2"
|
||||
strokeLinecap="round"
|
||||
/>
|
||||
<path
|
||||
d="M10 22H16"
|
||||
stroke={active ? "#F97316" : "#B0A090"}
|
||||
strokeWidth="2"
|
||||
strokeLinecap="round"
|
||||
/>
|
||||
<path
|
||||
d="M13 17V22"
|
||||
stroke={active ? "#F97316" : "#B0A090"}
|
||||
strokeWidth="2"
|
||||
strokeLinecap="round"
|
||||
/>
|
||||
</svg>
|
||||
);
|
||||
}
|
||||
|
||||
export function CalendarIcon({ active }: NavIconProps) {
|
||||
return (
|
||||
<svg width="26" height="26" viewBox="0 0 26 26" fill="none">
|
||||
<rect
|
||||
x="3" y="5" width="20" height="18" rx="3"
|
||||
fill={active ? "#F97316" : "none"}
|
||||
stroke={active ? "#F97316" : "#B0A090"}
|
||||
strokeWidth="2"
|
||||
/>
|
||||
<path
|
||||
d="M3 11H23"
|
||||
stroke={active ? "#fff" : "#B0A090"}
|
||||
strokeWidth="2"
|
||||
/>
|
||||
<path
|
||||
d="M8 3V7"
|
||||
stroke={active ? "#F97316" : "#B0A090"}
|
||||
strokeWidth="2"
|
||||
strokeLinecap="round"
|
||||
/>
|
||||
<path
|
||||
d="M18 3V7"
|
||||
stroke={active ? "#F97316" : "#B0A090"}
|
||||
strokeWidth="2"
|
||||
strokeLinecap="round"
|
||||
/>
|
||||
<circle cx="9" cy="16" r="1.5" fill={active ? "#fff" : "#B0A090"} />
|
||||
<circle cx="13" cy="16" r="1.5" fill={active ? "#fff" : "#B0A090"} />
|
||||
</svg>
|
||||
);
|
||||
}
|
||||
|
||||
export function ActivityIcon({ active }: NavIconProps) {
|
||||
return (
|
||||
<svg width="26" height="26" viewBox="0 0 26 26" fill="none">
|
||||
<rect
|
||||
x="4" y="4" width="18" height="18" rx="4"
|
||||
fill={active ? "#F97316" : "none"}
|
||||
stroke={active ? "#F97316" : "#B0A090"}
|
||||
strokeWidth="2"
|
||||
/>
|
||||
<path d="M8 10H18" stroke={active ? "#fff" : "#B0A090"} strokeWidth="2" strokeLinecap="round" />
|
||||
<path d="M8 14H18" stroke={active ? "#fff" : "#B0A090"} strokeWidth="2" strokeLinecap="round" />
|
||||
<path d="M8 18H14" stroke={active ? "#fff" : "#B0A090"} strokeWidth="2" strokeLinecap="round" />
|
||||
</svg>
|
||||
);
|
||||
}
|
||||
|
||||
export function AchievementsIcon({ active }: NavIconProps) {
|
||||
return (
|
||||
<svg width="26" height="26" viewBox="0 0 26 26" fill="none">
|
||||
<circle cx="13" cy="11" r="7" fill={active ? "#F97316" : "none"} stroke={active ? "#F97316" : "#B0A090"} strokeWidth="2" />
|
||||
<path d="M13 7L14.3 10.2L17.8 10.4L15.1 12.7L16 16.1L13 14.2L10 16.1L10.9 12.7L8.2 10.4L11.7 10.2L13 7Z" fill={active ? "#fff" : "#B0A090"} />
|
||||
<path d="M10 18L8.5 22L13 20.5L17.5 22L16 18" stroke={active ? "#F97316" : "#B0A090"} strokeWidth="2" strokeLinecap="round" />
|
||||
</svg>
|
||||
);
|
||||
}
|
||||
|
||||
export function SettingsIcon({ active }: NavIconProps) {
|
||||
return (
|
||||
<svg width="26" height="26" viewBox="0 0 26 26" fill="none">
|
||||
<circle
|
||||
cx="13" cy="13" r="4"
|
||||
fill={active ? "#F97316" : "none"}
|
||||
stroke={active ? "#F97316" : "#B0A090"}
|
||||
strokeWidth="2"
|
||||
/>
|
||||
<path
|
||||
d="M13 3V5M13 21V23M3 13H5M21 13H23M5.6 5.6L7 7M19 19L20.4 20.4M20.4 5.6L19 7M7 19L5.6 20.4"
|
||||
stroke={active ? "#F97316" : "#B0A090"}
|
||||
strokeWidth="2"
|
||||
strokeLinecap="round"
|
||||
/>
|
||||
</svg>
|
||||
);
|
||||
}
|
||||
|
||||
export function RewardsIcon({ active }: NavIconProps) {
|
||||
return (
|
||||
<svg width="26" height="26" viewBox="0 0 26 26" fill="none">
|
||||
<rect
|
||||
x="4" y="8" width="18" height="12" rx="3"
|
||||
fill={active ? "#F97316" : "none"}
|
||||
stroke={active ? "#F97316" : "#B0A090"}
|
||||
strokeWidth="2"
|
||||
/>
|
||||
<path d="M4 12H22" stroke={active ? "#fff" : "#B0A090"} strokeWidth="2" />
|
||||
<circle cx="13" cy="14.5" r="1.8" fill={active ? "#fff" : "#B0A090"} />
|
||||
<path d="M8 8C8 6.5 9.2 5.5 10.6 5.8C11.8 6 12.4 7 13 8" stroke={active ? "#F97316" : "#B0A090"} strokeWidth="2" strokeLinecap="round" />
|
||||
<path d="M18 8C18 6.5 16.8 5.5 15.4 5.8C14.2 6 13.6 7 13 8" stroke={active ? "#F97316" : "#B0A090"} strokeWidth="2" strokeLinecap="round" />
|
||||
</svg>
|
||||
);
|
||||
}
|
||||
141
client/src/components/icons/RoomIcons.tsx
Normal file
141
client/src/components/icons/RoomIcons.tsx
Normal file
|
|
@ -0,0 +1,141 @@
|
|||
import React from 'react';
|
||||
|
||||
export function KitchenIcon() {
|
||||
return (
|
||||
<svg width="32" height="32" viewBox="0 0 32 32" fill="none">
|
||||
<rect x="9" y="4" width="14" height="24" rx="3" fill="#FFF1E5" stroke="#F97316" strokeWidth="1.8" />
|
||||
<path d="M9 13.5H23" stroke="#F97316" strokeWidth="1.4" />
|
||||
<rect x="10.8" y="6.2" width="10.4" height="6" rx="1.3" fill="#FFFFFF" stroke="#FDBA74" strokeWidth="1" />
|
||||
<rect x="10.8" y="15.2" width="10.4" height="10.6" rx="1.4" fill="#FFF7ED" stroke="#FDBA74" strokeWidth="1" />
|
||||
<path d="M20.2 8.4V10.3" stroke="#F97316" strokeWidth="1.5" strokeLinecap="round" />
|
||||
<path d="M20.2 18.8V21.8" stroke="#F97316" strokeWidth="1.5" strokeLinecap="round" />
|
||||
</svg>
|
||||
);
|
||||
}
|
||||
|
||||
export function BedroomIcon() {
|
||||
return (
|
||||
<svg width="32" height="32" viewBox="0 0 32 32" fill="none">
|
||||
<rect x="4" y="14" width="24" height="9" rx="3" fill="#F1EAFE" stroke="#9B72CF" strokeWidth="1.8" />
|
||||
<path d="M7 14V11.2C7 9.99 7.99 9 9.2 9H22.8C24.01 9 25 9.99 25 11.2V14" stroke="#9B72CF" strokeWidth="1.8" />
|
||||
<rect x="8" y="10" width="6" height="4" rx="1.5" fill="#FFFFFF" stroke="#9B72CF" strokeWidth="1.2" />
|
||||
<rect x="18" y="10" width="6" height="4" rx="1.5" fill="#FFFFFF" stroke="#9B72CF" strokeWidth="1.2" />
|
||||
<path d="M5 23V26" stroke="#9B72CF" strokeWidth="1.8" strokeLinecap="round" />
|
||||
<path d="M27 23V26" stroke="#9B72CF" strokeWidth="1.8" strokeLinecap="round" />
|
||||
</svg>
|
||||
);
|
||||
}
|
||||
|
||||
export function BathroomIcon() {
|
||||
return (
|
||||
<svg width="32" height="32" viewBox="0 0 32 32" fill="none">
|
||||
<path d="M9 9.5V8.2C9 6.99 9.99 6 11.2 6H12.2" stroke="#4AABDE" strokeWidth="1.8" strokeLinecap="round" />
|
||||
<path d="M13.2 6H15.2" stroke="#4AABDE" strokeWidth="1.8" strokeLinecap="round" />
|
||||
<rect x="8" y="10" width="16" height="8" rx="4" fill="#E9F7FD" stroke="#4AABDE" strokeWidth="1.8" />
|
||||
<path d="M10 18V22C10 23.66 12.69 25 16 25C19.31 25 22 23.66 22 22V18" stroke="#4AABDE" strokeWidth="1.8" />
|
||||
<circle cx="21.5" cy="8" r="1" fill="#4AABDE" />
|
||||
<circle cx="23.8" cy="9.4" r="0.9" fill="#4AABDE" opacity="0.7" />
|
||||
</svg>
|
||||
);
|
||||
}
|
||||
|
||||
export function LivingRoomIcon() {
|
||||
return (
|
||||
<svg width="32" height="32" viewBox="0 0 32 32" fill="none">
|
||||
<rect x="7" y="12" width="18" height="9" rx="4" fill="#E8F7EB" stroke="#5CB85C" strokeWidth="1.8" />
|
||||
<path d="M5 16C5 14.9 5.9 14 7 14V22H5V16Z" fill="#F4FFF6" stroke="#5CB85C" strokeWidth="1.2" />
|
||||
<path d="M27 16C27 14.9 26.1 14 25 14V22H27V16Z" fill="#F4FFF6" stroke="#5CB85C" strokeWidth="1.2" />
|
||||
<rect x="10" y="21" width="3" height="4" rx="1" fill="#E8F7EB" stroke="#5CB85C" strokeWidth="1.2" />
|
||||
<rect x="19" y="21" width="3" height="4" rx="1" fill="#E8F7EB" stroke="#5CB85C" strokeWidth="1.2" />
|
||||
<rect x="12" y="14" width="8" height="3.5" rx="1.7" fill="#FFFFFF" stroke="#5CB85C" strokeWidth="1" />
|
||||
</svg>
|
||||
);
|
||||
}
|
||||
|
||||
export function OfficeIcon() {
|
||||
return (
|
||||
<svg width="32" height="32" viewBox="0 0 32 32" fill="none">
|
||||
<rect x="7" y="8" width="18" height="11" rx="2" fill="#FFF9E3" stroke="#D4A017" strokeWidth="1.8" />
|
||||
<rect x="9.5" y="10.5" width="13" height="6" rx="1" fill="#FFFFFF" stroke="#D4A017" strokeWidth="1.1" />
|
||||
<path d="M14.5 19V23" stroke="#D4A017" strokeWidth="1.8" strokeLinecap="round" />
|
||||
<path d="M17.5 19V23" stroke="#D4A017" strokeWidth="1.8" strokeLinecap="round" />
|
||||
<path d="M11.5 24H20.5" stroke="#D4A017" strokeWidth="1.8" strokeLinecap="round" />
|
||||
<rect x="6" y="23.5" width="20" height="2.5" rx="1.2" fill="#FFF3CD" stroke="#D4A017" strokeWidth="1.2" />
|
||||
</svg>
|
||||
);
|
||||
}
|
||||
|
||||
export function GarageIcon() {
|
||||
return (
|
||||
<svg width="32" height="32" viewBox="0 0 32 32" fill="none">
|
||||
<path d="M5 13L16 6L27 13" stroke="#64748B" strokeWidth="1.8" strokeLinejoin="round" />
|
||||
<rect x="7" y="13" width="18" height="13" rx="2.5" fill="#F1F5F9" stroke="#64748B" strokeWidth="1.8" />
|
||||
<rect x="11" y="16" width="10" height="10" rx="1.5" fill="#E2E8F0" stroke="#64748B" strokeWidth="1.3" />
|
||||
<path d="M11 19H21" stroke="#94A3B8" strokeWidth="1" />
|
||||
<path d="M11 22H21" stroke="#94A3B8" strokeWidth="1" />
|
||||
</svg>
|
||||
);
|
||||
}
|
||||
|
||||
export function LaundryIcon() {
|
||||
return (
|
||||
<svg width="32" height="32" viewBox="0 0 32 32" fill="none">
|
||||
<rect x="7" y="4" width="18" height="24" rx="3" fill="#EAF7FF" stroke="#0EA5E9" strokeWidth="1.8" />
|
||||
<circle cx="16" cy="18" r="6.5" fill="#D2EEFF" stroke="#0EA5E9" strokeWidth="1.8" />
|
||||
<path d="M12.8 18.4C13.5 16.5 15.3 15.2 17.3 15.2C18.4 15.2 19.5 15.6 20.3 16.3" stroke="#0EA5E9" strokeWidth="1.2" strokeLinecap="round" />
|
||||
<circle cx="11" cy="8" r="1.1" fill="#0EA5E9" />
|
||||
<circle cx="14.4" cy="8" r="1.1" fill="#0EA5E9" />
|
||||
<path d="M7 10.6H25" stroke="#0EA5E9" strokeWidth="1.6" />
|
||||
</svg>
|
||||
);
|
||||
}
|
||||
|
||||
export function OtherRoomIcon() {
|
||||
return (
|
||||
<svg width="32" height="32" viewBox="0 0 32 32" fill="none">
|
||||
<path d="M6 14L16 7L26 14" stroke="#9B8A77" strokeWidth="1.8" strokeLinejoin="round" />
|
||||
<rect x="8.5" y="14" width="15" height="11" rx="2.2" fill="#F7F0E8" stroke="#9B8A77" strokeWidth="1.8" />
|
||||
<rect x="14" y="18" width="4" height="7" rx="1" fill="#EFE3D6" stroke="#9B8A77" strokeWidth="1.2" />
|
||||
<path d="M20.8 12.5V9.5" stroke="#9B8A77" strokeWidth="1.8" strokeLinecap="round" />
|
||||
</svg>
|
||||
);
|
||||
}
|
||||
|
||||
const ROOM_ICON_MAP: Record<string, () => React.JSX.Element> = {
|
||||
kitchen: KitchenIcon,
|
||||
bedroom: BedroomIcon,
|
||||
bathroom: BathroomIcon,
|
||||
living: LivingRoomIcon,
|
||||
livingroom: LivingRoomIcon,
|
||||
living_room: LivingRoomIcon,
|
||||
office: OfficeIcon,
|
||||
garage: GarageIcon,
|
||||
laundry: LaundryIcon,
|
||||
other: OtherRoomIcon,
|
||||
};
|
||||
|
||||
const ROOM_NAME_KEYWORDS: Array<{ keyword: string; key: string }> = [
|
||||
{ keyword: 'kitchen', key: 'kitchen' },
|
||||
{ keyword: 'bedroom', key: 'bedroom' },
|
||||
{ keyword: 'bathroom', key: 'bathroom' },
|
||||
{ keyword: 'living', key: 'living' },
|
||||
{ keyword: 'office', key: 'office' },
|
||||
{ keyword: 'garage', key: 'garage' },
|
||||
{ keyword: 'laundry', key: 'laundry' },
|
||||
];
|
||||
|
||||
export function getRoomIcon(roomType: string): () => React.JSX.Element {
|
||||
const lower = roomType.toLowerCase();
|
||||
|
||||
if (ROOM_ICON_MAP[lower]) {
|
||||
return ROOM_ICON_MAP[lower];
|
||||
}
|
||||
|
||||
for (const entry of ROOM_NAME_KEYWORDS) {
|
||||
if (lower.includes(entry.keyword)) {
|
||||
return ROOM_ICON_MAP[entry.key];
|
||||
}
|
||||
}
|
||||
|
||||
return OtherRoomIcon;
|
||||
}
|
||||
831
client/src/components/icons/TaskIcons.tsx
Normal file
831
client/src/components/icons/TaskIcons.tsx
Normal file
|
|
@ -0,0 +1,831 @@
|
|||
export type TaskIconKey =
|
||||
| 'sparkle' | 'dishes' | 'sink' | 'stove' | 'counter' | 'fridge' | 'oven'
|
||||
| 'microwave' | 'kettle' | 'rangehood' | 'pantry' | 'cabinet'
|
||||
| 'bed' | 'pillow' | 'sheets' | 'mattress' | 'nightstand'
|
||||
| 'toilet' | 'shower' | 'mirror' | 'towel' | 'drain' | 'bathmat'
|
||||
| 'showerhead' | 'toothbrush' | 'grout'
|
||||
| 'vacuum' | 'mop' | 'dust' | 'sweep'
|
||||
| 'window' | 'curtain' | 'lightswitch'
|
||||
| 'sofa' | 'tv' | 'lamp' | 'furniture' | 'rug'
|
||||
| 'desk' | 'keyboard' | 'monitor' | 'cable' | 'chair'
|
||||
| 'trash' | 'broom'
|
||||
| 'washer' | 'dryer' | 'detergent' | 'iron' | 'clothes'
|
||||
| 'tools' | 'cobweb' | 'chemicals' | 'garagedoor'
|
||||
| 'shelf' | 'drawer' | 'closet';
|
||||
|
||||
export const TASK_ICON_OPTIONS: Array<{ key: TaskIconKey; label: string }> = [
|
||||
{ key: 'sparkle', label: 'Sparkle' },
|
||||
{ key: 'dishes', label: 'Dishes' },
|
||||
{ key: 'sink', label: 'Sink' },
|
||||
{ key: 'stove', label: 'Stove' },
|
||||
{ key: 'counter', label: 'Counter' },
|
||||
{ key: 'fridge', label: 'Fridge' },
|
||||
{ key: 'oven', label: 'Oven' },
|
||||
{ key: 'microwave', label: 'Microwave' },
|
||||
{ key: 'kettle', label: 'Kettle' },
|
||||
{ key: 'rangehood', label: 'Range Hood' },
|
||||
{ key: 'pantry', label: 'Pantry' },
|
||||
{ key: 'cabinet', label: 'Cabinet' },
|
||||
{ key: 'bed', label: 'Bed' },
|
||||
{ key: 'pillow', label: 'Pillow' },
|
||||
{ key: 'sheets', label: 'Sheets' },
|
||||
{ key: 'mattress', label: 'Mattress' },
|
||||
{ key: 'nightstand', label: 'Nightstand' },
|
||||
{ key: 'toilet', label: 'Toilet' },
|
||||
{ key: 'shower', label: 'Shower' },
|
||||
{ key: 'mirror', label: 'Mirror' },
|
||||
{ key: 'towel', label: 'Towel' },
|
||||
{ key: 'drain', label: 'Drain' },
|
||||
{ key: 'bathmat', label: 'Bath Mat' },
|
||||
{ key: 'showerhead', label: 'Showerhead' },
|
||||
{ key: 'toothbrush', label: 'Toothbrush' },
|
||||
{ key: 'grout', label: 'Grout' },
|
||||
{ key: 'vacuum', label: 'Vacuum' },
|
||||
{ key: 'mop', label: 'Mop' },
|
||||
{ key: 'dust', label: 'Dust' },
|
||||
{ key: 'sweep', label: 'Sweep' },
|
||||
{ key: 'window', label: 'Window' },
|
||||
{ key: 'curtain', label: 'Curtain' },
|
||||
{ key: 'lightswitch', label: 'Switch' },
|
||||
{ key: 'sofa', label: 'Sofa' },
|
||||
{ key: 'tv', label: 'TV' },
|
||||
{ key: 'lamp', label: 'Lamp' },
|
||||
{ key: 'furniture', label: 'Furniture' },
|
||||
{ key: 'rug', label: 'Rug' },
|
||||
{ key: 'desk', label: 'Desk' },
|
||||
{ key: 'keyboard', label: 'Keyboard' },
|
||||
{ key: 'monitor', label: 'Monitor' },
|
||||
{ key: 'cable', label: 'Cable' },
|
||||
{ key: 'chair', label: 'Chair' },
|
||||
{ key: 'trash', label: 'Trash' },
|
||||
{ key: 'broom', label: 'Broom' },
|
||||
{ key: 'washer', label: 'Washer' },
|
||||
{ key: 'dryer', label: 'Dryer' },
|
||||
{ key: 'detergent', label: 'Detergent' },
|
||||
{ key: 'iron', label: 'Iron' },
|
||||
{ key: 'clothes', label: 'Clothes' },
|
||||
{ key: 'tools', label: 'Tools' },
|
||||
{ key: 'cobweb', label: 'Cobweb' },
|
||||
{ key: 'chemicals', label: 'Chemicals' },
|
||||
{ key: 'garagedoor', label: 'Garage' },
|
||||
{ key: 'shelf', label: 'Shelf' },
|
||||
{ key: 'drawer', label: 'Drawer' },
|
||||
{ key: 'closet', label: 'Closet' },
|
||||
];
|
||||
|
||||
// Kawaii color palettes per icon
|
||||
const P: Record<string, { s: string; b: string; f: string }> = {
|
||||
// s=stroke, b=background, f=fill accent
|
||||
sparkle: { s: '#F97316', b: '#FFF1E5', f: '#FBBF24' },
|
||||
dishes: { s: '#3B82F6', b: '#EFF6FF', f: '#93C5FD' },
|
||||
sink: { s: '#0EA5E9', b: '#E0F2FE', f: '#7DD3FC' },
|
||||
stove: { s: '#EF4444', b: '#FEF2F2', f: '#FCA5A5' },
|
||||
counter: { s: '#8B5CF6', b: '#F5F3FF', f: '#C4B5FD' },
|
||||
fridge: { s: '#06B6D4', b: '#ECFEFF', f: '#67E8F9' },
|
||||
oven: { s: '#F97316', b: '#FFF7ED', f: '#FDBA74' },
|
||||
microwave: { s: '#6366F1', b: '#EEF2FF', f: '#A5B4FC' },
|
||||
kettle: { s: '#EC4899', b: '#FDF2F8', f: '#F9A8D4' },
|
||||
rangehood: { s: '#64748B', b: '#F1F5F9', f: '#CBD5E1' },
|
||||
pantry: { s: '#D97706', b: '#FFFBEB', f: '#FDE68A' },
|
||||
cabinet: { s: '#92400E', b: '#FEF3C7', f: '#FDE68A' },
|
||||
bed: { s: '#8B5CF6', b: '#F5F3FF', f: '#DDD6FE' },
|
||||
pillow: { s: '#A78BFA', b: '#F5F3FF', f: '#EDE9FE' },
|
||||
sheets: { s: '#06B6D4', b: '#ECFEFF', f: '#A5F3FC' },
|
||||
mattress: { s: '#9333EA', b: '#FAF5FF', f: '#D8B4FE' },
|
||||
nightstand: { s: '#B45309', b: '#FFFBEB', f: '#FCD34D' },
|
||||
toilet: { s: '#3B82F6', b: '#EFF6FF', f: '#BFDBFE' },
|
||||
shower: { s: '#0EA5E9', b: '#E0F2FE', f: '#7DD3FC' },
|
||||
mirror: { s: '#6366F1', b: '#EEF2FF', f: '#C7D2FE' },
|
||||
towel: { s: '#EC4899', b: '#FDF2F8', f: '#FBCFE8' },
|
||||
drain: { s: '#64748B', b: '#F1F5F9', f: '#94A3B8' },
|
||||
bathmat: { s: '#14B8A6', b: '#F0FDFA', f: '#99F6E4' },
|
||||
showerhead: { s: '#0284C7', b: '#E0F2FE', f: '#7DD3FC' },
|
||||
toothbrush: { s: '#10B981', b: '#ECFDF5', f: '#6EE7B7' },
|
||||
grout: { s: '#78716C', b: '#F5F5F4', f: '#D6D3D1' },
|
||||
vacuum: { s: '#EF4444', b: '#FEF2F2', f: '#FCA5A5' },
|
||||
mop: { s: '#3B82F6', b: '#EFF6FF', f: '#93C5FD' },
|
||||
dust: { s: '#F59E0B', b: '#FFFBEB', f: '#FDE68A' },
|
||||
sweep: { s: '#16A34A', b: '#F0FDF4', f: '#86EFAC' },
|
||||
window: { s: '#0EA5E9', b: '#E0F2FE', f: '#BAE6FD' },
|
||||
curtain: { s: '#EC4899', b: '#FDF2F8', f: '#FBCFE8' },
|
||||
lightswitch:{ s: '#F59E0B', b: '#FFFBEB', f: '#FDE68A' },
|
||||
sofa: { s: '#16A34A', b: '#F0FDF4', f: '#BBF7D0' },
|
||||
tv: { s: '#6366F1', b: '#EEF2FF', f: '#C7D2FE' },
|
||||
lamp: { s: '#F59E0B', b: '#FFFBEB', f: '#FDE68A' },
|
||||
furniture: { s: '#92400E', b: '#FFFBEB', f: '#FDE68A' },
|
||||
rug: { s: '#DC2626', b: '#FEF2F2', f: '#FECACA' },
|
||||
desk: { s: '#D97706', b: '#FFFBEB', f: '#FDE68A' },
|
||||
keyboard: { s: '#64748B', b: '#F1F5F9', f: '#E2E8F0' },
|
||||
monitor: { s: '#3B82F6', b: '#EFF6FF', f: '#BFDBFE' },
|
||||
cable: { s: '#10B981', b: '#ECFDF5', f: '#A7F3D0' },
|
||||
chair: { s: '#B45309', b: '#FFFBEB', f: '#FCD34D' },
|
||||
trash: { s: '#64748B', b: '#F1F5F9', f: '#CBD5E1' },
|
||||
broom: { s: '#16A34A', b: '#F0FDF4', f: '#BBF7D0' },
|
||||
washer: { s: '#0EA5E9', b: '#E0F2FE', f: '#BAE6FD' },
|
||||
dryer: { s: '#F97316', b: '#FFF7ED', f: '#FED7AA' },
|
||||
detergent: { s: '#8B5CF6', b: '#F5F3FF', f: '#DDD6FE' },
|
||||
iron: { s: '#6366F1', b: '#EEF2FF', f: '#A5B4FC' },
|
||||
clothes: { s: '#EC4899', b: '#FDF2F8', f: '#FBCFE8' },
|
||||
tools: { s: '#64748B', b: '#F1F5F9', f: '#CBD5E1' },
|
||||
cobweb: { s: '#7C3AED', b: '#F5F3FF', f: '#DDD6FE' },
|
||||
chemicals: { s: '#EF4444', b: '#FEF2F2', f: '#FCA5A5' },
|
||||
garagedoor: { s: '#78716C', b: '#F5F5F4', f: '#D6D3D1' },
|
||||
shelf: { s: '#D97706', b: '#FFFBEB', f: '#FDE68A' },
|
||||
drawer: { s: '#92400E', b: '#FEF3C7', f: '#FDE68A' },
|
||||
closet: { s: '#A78BFA', b: '#F5F3FF', f: '#DDD6FE' },
|
||||
};
|
||||
|
||||
function I({ k, size }: { k: string; size: number }) {
|
||||
const p = P[k] || P.sparkle;
|
||||
const w = 1.4;
|
||||
switch (k) {
|
||||
// ===== KITCHEN =====
|
||||
case 'dishes': return (
|
||||
<svg width={size} height={size} viewBox="0 0 24 24" fill="none">
|
||||
<ellipse cx="12" cy="13.5" rx="7" ry="4.5" fill={p.b} stroke={p.s} strokeWidth={w}/>
|
||||
<ellipse cx="12" cy="12" rx="5" ry="3" fill={p.f} stroke={p.s} strokeWidth="1"/>
|
||||
<path d="M8.5 10C9 8.5 10.5 7.5 12 7.5C13.5 7.5 15 8.5 15.5 10" stroke={p.s} strokeWidth="1" fill="none"/>
|
||||
{/* kawaii face */}
|
||||
<circle cx="10.5" cy="12.5" r="0.6" fill={p.s}/>
|
||||
<circle cx="13.5" cy="12.5" r="0.6" fill={p.s}/>
|
||||
<path d="M11 13.8C11.3 14.2 12.7 14.2 13 13.8" stroke={p.s} strokeWidth="0.7" strokeLinecap="round" fill="none"/>
|
||||
{/* bubbles */}
|
||||
<circle cx="17" cy="8" r="1.2" fill={p.f} stroke={p.s} strokeWidth="0.7"/>
|
||||
<circle cx="18.5" cy="6.5" r="0.8" fill={p.f} stroke={p.s} strokeWidth="0.5"/>
|
||||
</svg>
|
||||
);
|
||||
case 'sink': return (
|
||||
<svg width={size} height={size} viewBox="0 0 24 24" fill="none">
|
||||
<path d="M5 11H19V15C19 17.2 17.2 19 15 19H9C6.8 19 5 17.2 5 15V11Z" fill={p.b} stroke={p.s} strokeWidth={w}/>
|
||||
<path d="M12 5V8" stroke={p.s} strokeWidth={w} strokeLinecap="round"/>
|
||||
<path d="M12 8C12 8 10 9 10 10.5" stroke={p.s} strokeWidth="1.2" strokeLinecap="round" fill="none"/>
|
||||
<circle cx="10.5" cy="13.5" r="0.5" fill={p.s}/>
|
||||
<circle cx="13.5" cy="13.5" r="0.5" fill={p.s}/>
|
||||
<path d="M11.3 15C11.6 15.3 12.4 15.3 12.7 15" stroke={p.s} strokeWidth="0.7" strokeLinecap="round" fill="none"/>
|
||||
<circle cx="8" cy="9" r="0.8" fill={p.f} stroke={p.s} strokeWidth="0.5"/>
|
||||
<circle cx="16" cy="8.5" r="0.6" fill={p.f} stroke={p.s} strokeWidth="0.5"/>
|
||||
</svg>
|
||||
);
|
||||
case 'stove': return (
|
||||
<svg width={size} height={size} viewBox="0 0 24 24" fill="none">
|
||||
<rect x="4" y="8" width="16" height="12" rx="2.5" fill={p.b} stroke={p.s} strokeWidth={w}/>
|
||||
<circle cx="8.5" cy="14" r="2.5" fill={p.f} stroke={p.s} strokeWidth="1"/>
|
||||
<circle cx="15.5" cy="14" r="2.5" fill={p.f} stroke={p.s} strokeWidth="1"/>
|
||||
<circle cx="8.5" cy="14" r="0.8" fill={p.b} stroke={p.s} strokeWidth="0.7"/>
|
||||
<circle cx="15.5" cy="14" r="0.8" fill={p.b} stroke={p.s} strokeWidth="0.7"/>
|
||||
{/* steam */}
|
||||
<path d="M9 6.5C9 5.5 8.5 5 8.5 4" stroke={p.s} strokeWidth="0.8" strokeLinecap="round" opacity="0.5"/>
|
||||
<path d="M12 6C12 5 11.5 4.5 11.5 3.5" stroke={p.s} strokeWidth="0.8" strokeLinecap="round" opacity="0.5"/>
|
||||
<path d="M15 6.5C15 5.5 14.5 5 14.5 4" stroke={p.s} strokeWidth="0.8" strokeLinecap="round" opacity="0.5"/>
|
||||
</svg>
|
||||
);
|
||||
case 'counter': return (
|
||||
<svg width={size} height={size} viewBox="0 0 24 24" fill="none">
|
||||
<rect x="3" y="10" width="18" height="3" rx="1.2" fill={p.f} stroke={p.s} strokeWidth={w}/>
|
||||
<rect x="4.5" y="13" width="5" height="7" rx="1" fill={p.b} stroke={p.s} strokeWidth="1.2"/>
|
||||
<rect x="14.5" y="13" width="5" height="7" rx="1" fill={p.b} stroke={p.s} strokeWidth="1.2"/>
|
||||
<circle cx="7" cy="16.5" r="0.6" fill={p.s}/>
|
||||
<circle cx="17" cy="16.5" r="0.6" fill={p.s}/>
|
||||
{/* sparkle on counter */}
|
||||
<path d="M12 7L12.6 8.4L14 9L12.6 9.6L12 11L11.4 9.6L10 9L11.4 8.4L12 7Z" fill={p.f} stroke={p.s} strokeWidth="0.6"/>
|
||||
</svg>
|
||||
);
|
||||
case 'fridge': return (
|
||||
<svg width={size} height={size} viewBox="0 0 24 24" fill="none">
|
||||
<rect x="6" y="3" width="12" height="18" rx="2.5" fill={p.b} stroke={p.s} strokeWidth={w}/>
|
||||
<line x1="6" y1="10" x2="18" y2="10" stroke={p.s} strokeWidth="1.2"/>
|
||||
<line x1="15.5" y1="6" x2="15.5" y2="9" stroke={p.s} strokeWidth="1.3" strokeLinecap="round"/>
|
||||
<line x1="15.5" y1="12" x2="15.5" y2="15" stroke={p.s} strokeWidth="1.3" strokeLinecap="round"/>
|
||||
<circle cx="10" cy="6.5" r="0.5" fill={p.s}/>
|
||||
<circle cx="12.5" cy="6.5" r="0.5" fill={p.s}/>
|
||||
<path d="M10.5 8C10.8 8.3 12.2 8.3 12.5 8" stroke={p.s} strokeWidth="0.6" strokeLinecap="round" fill="none"/>
|
||||
</svg>
|
||||
);
|
||||
case 'oven': return (
|
||||
<svg width={size} height={size} viewBox="0 0 24 24" fill="none">
|
||||
<rect x="4" y="5" width="16" height="15" rx="2.5" fill={p.b} stroke={p.s} strokeWidth={w}/>
|
||||
<rect x="6.5" y="10" width="11" height="7.5" rx="1.5" fill={p.f} stroke={p.s} strokeWidth="1.2"/>
|
||||
<line x1="6.5" y1="8" x2="17.5" y2="8" stroke={p.s} strokeWidth="1"/>
|
||||
<circle cx="8" cy="6.5" r="0.7" fill={p.f} stroke={p.s} strokeWidth="0.6"/>
|
||||
<circle cx="12" cy="6.5" r="0.7" fill={p.f} stroke={p.s} strokeWidth="0.6"/>
|
||||
<circle cx="16" cy="6.5" r="0.7" fill={p.f} stroke={p.s} strokeWidth="0.6"/>
|
||||
{/* kawaii face on window */}
|
||||
<circle cx="10.5" cy="13" r="0.5" fill={p.s}/>
|
||||
<circle cx="13.5" cy="13" r="0.5" fill={p.s}/>
|
||||
<path d="M11 14.5C11.3 14.9 12.7 14.9 13 14.5" stroke={p.s} strokeWidth="0.6" strokeLinecap="round" fill="none"/>
|
||||
</svg>
|
||||
);
|
||||
case 'microwave': return (
|
||||
<svg width={size} height={size} viewBox="0 0 24 24" fill="none">
|
||||
<rect x="3" y="6" width="18" height="12" rx="2.5" fill={p.b} stroke={p.s} strokeWidth={w}/>
|
||||
<rect x="5" y="8" width="11" height="8" rx="1.5" fill={p.f} stroke={p.s} strokeWidth="1"/>
|
||||
<circle cx="18" cy="10" r="0.7" fill={p.s}/>
|
||||
<circle cx="18" cy="12.5" r="0.7" fill={p.s}/>
|
||||
<circle cx="18" cy="15" r="0.7" fill={p.s}/>
|
||||
<circle cx="9" cy="11" r="0.5" fill={p.s}/>
|
||||
<circle cx="12" cy="11" r="0.5" fill={p.s}/>
|
||||
<path d="M9.5 13C9.8 13.4 11.7 13.4 12 13" stroke={p.s} strokeWidth="0.6" strokeLinecap="round" fill="none"/>
|
||||
</svg>
|
||||
);
|
||||
case 'kettle': return (
|
||||
<svg width={size} height={size} viewBox="0 0 24 24" fill="none">
|
||||
<path d="M7 10C7 8.3 8.3 7 10 7H14C15.7 7 17 8.3 17 10V15C17 17.2 15.2 19 13 19H11C8.8 19 7 17.2 7 15V10Z" fill={p.b} stroke={p.s} strokeWidth={w}/>
|
||||
<path d="M17 11H19C19.6 11 20 11.4 20 12V13C20 13.6 19.6 14 19 14H17" stroke={p.s} strokeWidth="1.2" fill="none"/>
|
||||
<path d="M10 7V6C10 5.4 10.4 5 11 5H13C13.6 5 14 5.4 14 6V7" stroke={p.s} strokeWidth="1.2" fill="none"/>
|
||||
<circle cx="10.5" cy="12" r="0.5" fill={p.s}/>
|
||||
<circle cx="13.5" cy="12" r="0.5" fill={p.s}/>
|
||||
<path d="M11 14C11.3 14.3 12.7 14.3 13 14" stroke={p.s} strokeWidth="0.6" strokeLinecap="round" fill="none"/>
|
||||
{/* steam */}
|
||||
<path d="M11 4C11 3 10.5 2.5 10.5 2" stroke={p.s} strokeWidth="0.7" strokeLinecap="round" opacity="0.4"/>
|
||||
<path d="M13 4C13 3 13.5 2.5 13.5 2" stroke={p.s} strokeWidth="0.7" strokeLinecap="round" opacity="0.4"/>
|
||||
</svg>
|
||||
);
|
||||
case 'rangehood': return (
|
||||
<svg width={size} height={size} viewBox="0 0 24 24" fill="none">
|
||||
<path d="M4 12H20V16C20 17.1 19.1 18 18 18H6C4.9 18 4 17.1 4 16V12Z" fill={p.b} stroke={p.s} strokeWidth={w}/>
|
||||
<path d="M6 12L8 6H16L18 12" stroke={p.s} strokeWidth="1.2" fill={p.f}/>
|
||||
<rect x="7" y="14" width="10" height="2" rx="0.8" fill={p.f} stroke={p.s} strokeWidth="0.8"/>
|
||||
<circle cx="12" cy="9" r="0.5" fill={p.s}/>
|
||||
</svg>
|
||||
);
|
||||
case 'pantry': return (
|
||||
<svg width={size} height={size} viewBox="0 0 24 24" fill="none">
|
||||
<rect x="5" y="3" width="14" height="18" rx="2" fill={p.b} stroke={p.s} strokeWidth={w}/>
|
||||
<line x1="5" y1="8" x2="19" y2="8" stroke={p.s} strokeWidth="1"/>
|
||||
<line x1="5" y1="13" x2="19" y2="13" stroke={p.s} strokeWidth="1"/>
|
||||
<line x1="5" y1="18" x2="19" y2="18" stroke={p.s} strokeWidth="1"/>
|
||||
{/* jars */}
|
||||
<rect x="7" y="9.5" width="2.5" height="2.5" rx="0.6" fill={p.f} stroke={p.s} strokeWidth="0.7"/>
|
||||
<rect x="11" y="9.5" width="2.5" height="2.5" rx="0.6" fill={p.f} stroke={p.s} strokeWidth="0.7"/>
|
||||
<rect x="15" y="9.5" width="2.5" height="2.5" rx="0.6" fill={p.f} stroke={p.s} strokeWidth="0.7"/>
|
||||
<rect x="8" y="14.5" width="3.5" height="2.5" rx="0.6" fill={p.f} stroke={p.s} strokeWidth="0.7"/>
|
||||
<rect x="13" y="14.5" width="3.5" height="2.5" rx="0.6" fill={p.f} stroke={p.s} strokeWidth="0.7"/>
|
||||
</svg>
|
||||
);
|
||||
case 'cabinet': return (
|
||||
<svg width={size} height={size} viewBox="0 0 24 24" fill="none">
|
||||
<rect x="4" y="4" width="16" height="16" rx="2" fill={p.b} stroke={p.s} strokeWidth={w}/>
|
||||
<line x1="12" y1="4" x2="12" y2="20" stroke={p.s} strokeWidth="1.2"/>
|
||||
<circle cx="10" cy="12" r="0.8" fill={p.s}/>
|
||||
<circle cx="14" cy="12" r="0.8" fill={p.s}/>
|
||||
{/* sparkle */}
|
||||
<path d="M18 5L18.5 6.2L19.7 6.7L18.5 7.2L18 8.4L17.5 7.2L16.3 6.7L17.5 6.2L18 5Z" fill={p.f} stroke={p.s} strokeWidth="0.5"/>
|
||||
</svg>
|
||||
);
|
||||
|
||||
// ===== BEDROOM =====
|
||||
case 'bed': return (
|
||||
<svg width={size} height={size} viewBox="0 0 24 24" fill="none">
|
||||
<rect x="3" y="11" width="18" height="6" rx="2.5" fill={p.b} stroke={p.s} strokeWidth={w}/>
|
||||
<path d="M5 11V9C5 7.9 5.9 7 7 7H17C18.1 7 19 7.9 19 9V11" stroke={p.s} strokeWidth={w}/>
|
||||
<rect x="5.5" y="7.8" width="5" height="3" rx="1.2" fill={p.f} stroke={p.s} strokeWidth="1"/>
|
||||
<rect x="13.5" y="7.8" width="5" height="3" rx="1.2" fill={p.f} stroke={p.s} strokeWidth="1"/>
|
||||
<path d="M4 17V19M20 17V19" stroke={p.s} strokeWidth="1.3" strokeLinecap="round"/>
|
||||
<path d="M10 14.5Q12 15.5 14 14.5" stroke={p.s} strokeWidth="0.6" strokeLinecap="round" fill="none" opacity="0.5"/>
|
||||
</svg>
|
||||
);
|
||||
case 'pillow': return (
|
||||
<svg width={size} height={size} viewBox="0 0 24 24" fill="none">
|
||||
<ellipse cx="12" cy="12" rx="8" ry="5.5" fill={p.b} stroke={p.s} strokeWidth={w}/>
|
||||
<ellipse cx="12" cy="12" rx="5.5" ry="3.5" fill={p.f} stroke={p.s} strokeWidth="0.8"/>
|
||||
<circle cx="10" cy="11.5" r="0.5" fill={p.s}/>
|
||||
<circle cx="14" cy="11.5" r="0.5" fill={p.s}/>
|
||||
<path d="M11 13C11.3 13.3 12.7 13.3 13 13" stroke={p.s} strokeWidth="0.6" strokeLinecap="round" fill="none"/>
|
||||
<path d="M6 10.5Q4.5 12 6 13.5" stroke={p.s} strokeWidth="0.7" fill="none" opacity="0.4"/>
|
||||
<path d="M18 10.5Q19.5 12 18 13.5" stroke={p.s} strokeWidth="0.7" fill="none" opacity="0.4"/>
|
||||
</svg>
|
||||
);
|
||||
case 'sheets': return (
|
||||
<svg width={size} height={size} viewBox="0 0 24 24" fill="none">
|
||||
<rect x="4" y="6" width="16" height="14" rx="2" fill={p.b} stroke={p.s} strokeWidth={w}/>
|
||||
<path d="M4 10C8 8 16 14 20 10" stroke={p.s} strokeWidth="1" fill="none" opacity="0.4"/>
|
||||
<path d="M4 14C8 12 16 18 20 14" stroke={p.s} strokeWidth="1" fill="none" opacity="0.3"/>
|
||||
<path d="M7 6V4.5C7 4 7.4 3.5 8 3.5H10C10.6 3.5 11 4 11 4.5V6" stroke={p.s} strokeWidth="1" fill="none"/>
|
||||
<circle cx="14" cy="11" r="0.5" fill={p.s}/>
|
||||
<circle cx="17" cy="11" r="0.5" fill={p.s}/>
|
||||
<path d="M14.5 12.5C14.8 12.8 16.7 12.8 17 12.5" stroke={p.s} strokeWidth="0.5" strokeLinecap="round" fill="none"/>
|
||||
</svg>
|
||||
);
|
||||
case 'mattress': return (
|
||||
<svg width={size} height={size} viewBox="0 0 24 24" fill="none">
|
||||
<rect x="3" y="8" width="18" height="10" rx="2.5" fill={p.b} stroke={p.s} strokeWidth={w}/>
|
||||
<line x1="3" y1="12" x2="21" y2="12" stroke={p.s} strokeWidth="0.8" opacity="0.4"/>
|
||||
<path d="M7 12V8.5" stroke={p.s} strokeWidth="0.8" strokeLinecap="round" opacity="0.3"/>
|
||||
<path d="M12 12V8.5" stroke={p.s} strokeWidth="0.8" strokeLinecap="round" opacity="0.3"/>
|
||||
<path d="M17 12V8.5" stroke={p.s} strokeWidth="0.8" strokeLinecap="round" opacity="0.3"/>
|
||||
{/* flip arrows */}
|
||||
<path d="M8 5L12 3L16 5" stroke={p.s} strokeWidth="1.2" strokeLinecap="round" fill="none"/>
|
||||
<path d="M8 21L12 19L16 21" stroke={p.s} strokeWidth="1.2" strokeLinecap="round" fill="none"/>
|
||||
</svg>
|
||||
);
|
||||
case 'nightstand': return (
|
||||
<svg width={size} height={size} viewBox="0 0 24 24" fill="none">
|
||||
<rect x="5" y="6" width="14" height="14" rx="2" fill={p.b} stroke={p.s} strokeWidth={w}/>
|
||||
<line x1="5" y1="13" x2="19" y2="13" stroke={p.s} strokeWidth="1"/>
|
||||
<circle cx="12" cy="9.5" r="0.8" fill={p.s}/>
|
||||
<circle cx="12" cy="16.5" r="0.8" fill={p.s}/>
|
||||
{/* lamp on top */}
|
||||
<path d="M12 6V4" stroke={p.s} strokeWidth="1" strokeLinecap="round"/>
|
||||
<path d="M9.5 4H14.5" stroke={p.f} strokeWidth="1.5" strokeLinecap="round"/>
|
||||
</svg>
|
||||
);
|
||||
|
||||
// ===== BATHROOM =====
|
||||
case 'toilet': return (
|
||||
<svg width={size} height={size} viewBox="0 0 24 24" fill="none">
|
||||
<ellipse cx="12" cy="15" rx="5" ry="4.5" fill={p.b} stroke={p.s} strokeWidth={w}/>
|
||||
<rect x="8" y="4" width="8" height="8" rx="2" fill={p.f} stroke={p.s} strokeWidth="1.2"/>
|
||||
<path d="M9 4.5H15" stroke={p.s} strokeWidth="1.5" strokeLinecap="round"/>
|
||||
<circle cx="10.5" cy="14" r="0.5" fill={p.s}/>
|
||||
<circle cx="13.5" cy="14" r="0.5" fill={p.s}/>
|
||||
<path d="M11 16C11.3 16.3 12.7 16.3 13 16" stroke={p.s} strokeWidth="0.6" strokeLinecap="round" fill="none"/>
|
||||
{/* sparkle */}
|
||||
<path d="M17.5 6L18 7L19 7.5L18 8L17.5 9L17 8L16 7.5L17 7L17.5 6Z" fill={p.f} stroke={p.s} strokeWidth="0.4"/>
|
||||
</svg>
|
||||
);
|
||||
case 'shower': return (
|
||||
<svg width={size} height={size} viewBox="0 0 24 24" fill="none">
|
||||
<path d="M8 4H10V8H18V20H6V8H8V4Z" fill={p.b} stroke={p.s} strokeWidth={w}/>
|
||||
<circle cx="14" cy="13" r="0.5" fill={p.s}/>
|
||||
<circle cx="10" cy="13" r="0.5" fill={p.s}/>
|
||||
<path d="M10.5 15C10.8 15.4 13.2 15.4 13.5 15" stroke={p.s} strokeWidth="0.6" strokeLinecap="round" fill="none"/>
|
||||
{/* water drops */}
|
||||
<circle cx="15" cy="6" r="0.7" fill={p.f}/>
|
||||
<circle cx="17" cy="7.5" r="0.5" fill={p.f}/>
|
||||
<circle cx="16" cy="4.5" r="0.5" fill={p.f}/>
|
||||
</svg>
|
||||
);
|
||||
case 'mirror': return (
|
||||
<svg width={size} height={size} viewBox="0 0 24 24" fill="none">
|
||||
<ellipse cx="12" cy="11" rx="6" ry="7" fill={p.b} stroke={p.s} strokeWidth={w}/>
|
||||
<ellipse cx="12" cy="10.5" rx="4" ry="5" fill={p.f} stroke={p.s} strokeWidth="0.8"/>
|
||||
<rect x="10.5" y="18" width="3" height="2" rx="0.8" fill={p.b} stroke={p.s} strokeWidth="1"/>
|
||||
{/* shine */}
|
||||
<path d="M9 7.5C9.5 7 10.5 6.5 11 6.5" stroke="white" strokeWidth="1" strokeLinecap="round" opacity="0.6"/>
|
||||
</svg>
|
||||
);
|
||||
case 'towel': return (
|
||||
<svg width={size} height={size} viewBox="0 0 24 24" fill="none">
|
||||
<path d="M6 5H18" stroke={p.s} strokeWidth="1.8" strokeLinecap="round"/>
|
||||
<rect x="8" y="5" width="8" height="14" rx="1.5" fill={p.b} stroke={p.s} strokeWidth={w}/>
|
||||
<path d="M8 19C8 19 10 20.5 12 19C14 17.5 16 19 16 19" stroke={p.s} strokeWidth="1" fill="none"/>
|
||||
<line x1="10" y1="8" x2="10" y2="16" stroke={p.f} strokeWidth="2" strokeLinecap="round" opacity="0.5"/>
|
||||
<line x1="14" y1="8" x2="14" y2="16" stroke={p.f} strokeWidth="2" strokeLinecap="round" opacity="0.5"/>
|
||||
</svg>
|
||||
);
|
||||
case 'drain': return (
|
||||
<svg width={size} height={size} viewBox="0 0 24 24" fill="none">
|
||||
<circle cx="12" cy="12" r="7" fill={p.b} stroke={p.s} strokeWidth={w}/>
|
||||
<circle cx="12" cy="12" r="4" fill={p.f} stroke={p.s} strokeWidth="1"/>
|
||||
<circle cx="12" cy="12" r="1.2" fill={p.b} stroke={p.s} strokeWidth="0.8"/>
|
||||
<line x1="12" y1="8" x2="12" y2="5.5" stroke={p.s} strokeWidth="0.8"/>
|
||||
<line x1="15.5" y1="10" x2="17.5" y2="8.5" stroke={p.s} strokeWidth="0.8"/>
|
||||
<line x1="15.5" y1="14" x2="17.5" y2="15.5" stroke={p.s} strokeWidth="0.8"/>
|
||||
<line x1="8.5" y1="10" x2="6.5" y2="8.5" stroke={p.s} strokeWidth="0.8"/>
|
||||
<line x1="8.5" y1="14" x2="6.5" y2="15.5" stroke={p.s} strokeWidth="0.8"/>
|
||||
<line x1="12" y1="16" x2="12" y2="18.5" stroke={p.s} strokeWidth="0.8"/>
|
||||
</svg>
|
||||
);
|
||||
case 'bathmat': return (
|
||||
<svg width={size} height={size} viewBox="0 0 24 24" fill="none">
|
||||
<rect x="4" y="8" width="16" height="10" rx="2.5" fill={p.b} stroke={p.s} strokeWidth={w}/>
|
||||
<rect x="6" y="10" width="12" height="6" rx="1.5" fill={p.f} stroke={p.s} strokeWidth="0.8"/>
|
||||
<path d="M8 12H16M8 14H16" stroke={p.s} strokeWidth="0.7" opacity="0.3"/>
|
||||
{/* tassels */}
|
||||
<path d="M6.5 18V20M8.5 18V20M10.5 18V20M12.5 18V20M14.5 18V20M16.5 18V20" stroke={p.s} strokeWidth="0.8" strokeLinecap="round"/>
|
||||
</svg>
|
||||
);
|
||||
case 'showerhead': return (
|
||||
<svg width={size} height={size} viewBox="0 0 24 24" fill="none">
|
||||
<circle cx="12" cy="8" r="4" fill={p.b} stroke={p.s} strokeWidth={w}/>
|
||||
<path d="M16 8H19V6" stroke={p.s} strokeWidth="1.3" strokeLinecap="round" fill="none"/>
|
||||
{/* water drops */}
|
||||
<circle cx="10" cy="14" r="0.8" fill={p.f}/>
|
||||
<circle cx="12" cy="15" r="0.8" fill={p.f}/>
|
||||
<circle cx="14" cy="14" r="0.8" fill={p.f}/>
|
||||
<circle cx="11" cy="17" r="0.6" fill={p.f} opacity="0.7"/>
|
||||
<circle cx="13" cy="17.5" r="0.6" fill={p.f} opacity="0.7"/>
|
||||
<circle cx="10.5" cy="19.5" r="0.5" fill={p.f} opacity="0.4"/>
|
||||
<circle cx="13.5" cy="19" r="0.5" fill={p.f} opacity="0.4"/>
|
||||
{/* face */}
|
||||
<circle cx="10.5" cy="7.5" r="0.5" fill={p.s}/>
|
||||
<circle cx="13.5" cy="7.5" r="0.5" fill={p.s}/>
|
||||
<path d="M11 9C11.3 9.3 12.7 9.3 13 9" stroke={p.s} strokeWidth="0.5" strokeLinecap="round" fill="none"/>
|
||||
</svg>
|
||||
);
|
||||
case 'toothbrush': return (
|
||||
<svg width={size} height={size} viewBox="0 0 24 24" fill="none">
|
||||
<rect x="11" y="3" width="2.5" height="14" rx="1.2" fill={p.b} stroke={p.s} strokeWidth={w}/>
|
||||
<rect x="9" y="3" width="6.5" height="4" rx="1.5" fill={p.f} stroke={p.s} strokeWidth="1"/>
|
||||
<path d="M10 4V6M11.5 4V6.5M13 4V6M14.5 4V5.5" stroke="white" strokeWidth="0.7" strokeLinecap="round" opacity="0.6"/>
|
||||
{/* sparkles */}
|
||||
<path d="M17 5L17.5 6L18.5 6.5L17.5 7L17 8L16.5 7L15.5 6.5L16.5 6L17 5Z" fill={p.f} stroke={p.s} strokeWidth="0.4"/>
|
||||
<path d="M7 8L7.3 9L8.3 9.3L7.3 9.6L7 10.6L6.7 9.6L5.7 9.3L6.7 9L7 8Z" fill={p.f} stroke={p.s} strokeWidth="0.3"/>
|
||||
</svg>
|
||||
);
|
||||
case 'grout': return (
|
||||
<svg width={size} height={size} viewBox="0 0 24 24" fill="none">
|
||||
{/* tiles */}
|
||||
<rect x="3" y="3" width="8" height="8" rx="1" fill={p.b} stroke={p.s} strokeWidth="1.2"/>
|
||||
<rect x="13" y="3" width="8" height="8" rx="1" fill={p.b} stroke={p.s} strokeWidth="1.2"/>
|
||||
<rect x="3" y="13" width="8" height="8" rx="1" fill={p.b} stroke={p.s} strokeWidth="1.2"/>
|
||||
<rect x="13" y="13" width="8" height="8" rx="1" fill={p.b} stroke={p.s} strokeWidth="1.2"/>
|
||||
{/* grout lines highlighted */}
|
||||
<line x1="12" y1="3" x2="12" y2="21" stroke={p.f} strokeWidth="2"/>
|
||||
<line x1="3" y1="12" x2="21" y2="12" stroke={p.f} strokeWidth="2"/>
|
||||
{/* brush */}
|
||||
<path d="M17 15L19 17" stroke={p.s} strokeWidth="1.5" strokeLinecap="round"/>
|
||||
<path d="M19 17L21 19" stroke={p.s} strokeWidth="2" strokeLinecap="round"/>
|
||||
</svg>
|
||||
);
|
||||
|
||||
// ===== CLEANING =====
|
||||
case 'vacuum': return (
|
||||
<svg width={size} height={size} viewBox="0 0 24 24" fill="none">
|
||||
<circle cx="10" cy="16" r="4.5" fill={p.b} stroke={p.s} strokeWidth={w}/>
|
||||
<circle cx="10" cy="16" r="2" fill={p.f} stroke={p.s} strokeWidth="0.8"/>
|
||||
<path d="M13 12L17 5" stroke={p.s} strokeWidth="1.5" strokeLinecap="round"/>
|
||||
<path d="M15 6H19" stroke={p.s} strokeWidth="1.5" strokeLinecap="round"/>
|
||||
<circle cx="9" cy="15.5" r="0.4" fill={p.s}/>
|
||||
<circle cx="11" cy="15.5" r="0.4" fill={p.s}/>
|
||||
<path d="M9.5 17C9.7 17.3 10.3 17.3 10.5 17" stroke={p.s} strokeWidth="0.5" strokeLinecap="round" fill="none"/>
|
||||
</svg>
|
||||
);
|
||||
case 'mop': return (
|
||||
<svg width={size} height={size} viewBox="0 0 24 24" fill="none">
|
||||
<line x1="12" y1="3" x2="12" y2="14" stroke={p.s} strokeWidth="1.8" strokeLinecap="round"/>
|
||||
<rect x="7" y="14" width="10" height="6" rx="1.5" fill={p.b} stroke={p.s} strokeWidth={w}/>
|
||||
<path d="M7.5 16H16.5M7.5 18H16.5" stroke={p.f} strokeWidth="1.5" strokeLinecap="round"/>
|
||||
{/* water drops */}
|
||||
<circle cx="8" cy="21.5" r="0.6" fill={p.f} opacity="0.6"/>
|
||||
<circle cx="12" cy="22" r="0.6" fill={p.f} opacity="0.6"/>
|
||||
<circle cx="16" cy="21.5" r="0.6" fill={p.f} opacity="0.6"/>
|
||||
</svg>
|
||||
);
|
||||
case 'dust': return (
|
||||
<svg width={size} height={size} viewBox="0 0 24 24" fill="none">
|
||||
{/* feather duster */}
|
||||
<path d="M15 16L19 20" stroke={p.s} strokeWidth="1.8" strokeLinecap="round"/>
|
||||
<ellipse cx="12" cy="12" rx="6" ry="5" fill={p.b} stroke={p.s} strokeWidth={w}/>
|
||||
<path d="M8 10C9 8.5 11 8 12 8C14 8 16 9 16.5 11" stroke={p.f} strokeWidth="2" strokeLinecap="round" fill="none"/>
|
||||
<path d="M9 12C10 11 13 10.5 15 12" stroke={p.f} strokeWidth="1.5" strokeLinecap="round" fill="none"/>
|
||||
{/* sparkles */}
|
||||
<path d="M5 6L5.5 7L6.5 7.5L5.5 8L5 9L4.5 8L3.5 7.5L4.5 7L5 6Z" fill={p.f} stroke={p.s} strokeWidth="0.4"/>
|
||||
<path d="M18 4L18.3 5L19.3 5.3L18.3 5.6L18 6.6L17.7 5.6L16.7 5.3L17.7 5L18 4Z" fill={p.f} stroke={p.s} strokeWidth="0.3"/>
|
||||
</svg>
|
||||
);
|
||||
case 'sweep': return (
|
||||
<svg width={size} height={size} viewBox="0 0 24 24" fill="none">
|
||||
<line x1="14" y1="3" x2="11" y2="13" stroke={p.s} strokeWidth="1.8" strokeLinecap="round"/>
|
||||
<path d="M7 13H17L16 19H8L7 13Z" fill={p.b} stroke={p.s} strokeWidth={w}/>
|
||||
<line x1="9.5" y1="14" x2="9.5" y2="18" stroke={p.s} strokeWidth="0.6" opacity="0.3"/>
|
||||
<line x1="12" y1="14" x2="12" y2="18" stroke={p.s} strokeWidth="0.6" opacity="0.3"/>
|
||||
<line x1="14.5" y1="14" x2="14.5" y2="18" stroke={p.s} strokeWidth="0.6" opacity="0.3"/>
|
||||
{/* dust cloud */}
|
||||
<circle cx="5" cy="17" r="1.2" fill={p.f} opacity="0.5"/>
|
||||
<circle cx="4" cy="15.5" r="0.8" fill={p.f} opacity="0.4"/>
|
||||
<circle cx="3.5" cy="18" r="0.6" fill={p.f} opacity="0.3"/>
|
||||
</svg>
|
||||
);
|
||||
|
||||
// ===== WINDOWS & SWITCHES =====
|
||||
case 'window': return (
|
||||
<svg width={size} height={size} viewBox="0 0 24 24" fill="none">
|
||||
<rect x="4" y="4" width="16" height="16" rx="2.5" fill={p.b} stroke={p.s} strokeWidth={w}/>
|
||||
<line x1="12" y1="4" x2="12" y2="20" stroke={p.s} strokeWidth="1.2"/>
|
||||
<line x1="4" y1="12" x2="20" y2="12" stroke={p.s} strokeWidth="1.2"/>
|
||||
{/* shine */}
|
||||
<path d="M6.5 6.5L8.5 8.5" stroke="white" strokeWidth="1" strokeLinecap="round" opacity="0.5"/>
|
||||
{/* sparkle */}
|
||||
<path d="M17 6L17.5 7L18.5 7.5L17.5 8L17 9L16.5 8L15.5 7.5L16.5 7L17 6Z" fill={p.f} stroke={p.s} strokeWidth="0.5"/>
|
||||
</svg>
|
||||
);
|
||||
case 'curtain': return (
|
||||
<svg width={size} height={size} viewBox="0 0 24 24" fill="none">
|
||||
<path d="M4 4H20" stroke={p.s} strokeWidth="1.8" strokeLinecap="round"/>
|
||||
<path d="M5 4C5 4 4 12 7 16V20" stroke={p.s} strokeWidth={w} fill="none"/>
|
||||
<path d="M5 4V16C5 16 4.5 14 5.5 12C6.5 10 7 8 7 4" fill={p.b} stroke={p.s} strokeWidth="1"/>
|
||||
<path d="M19 4C19 4 20 12 17 16V20" stroke={p.s} strokeWidth={w} fill="none"/>
|
||||
<path d="M19 4V16C19 16 19.5 14 18.5 12C17.5 10 17 8 17 4" fill={p.b} stroke={p.s} strokeWidth="1"/>
|
||||
{/* tie-backs */}
|
||||
<ellipse cx="6.5" cy="13" rx="1.5" ry="0.8" fill={p.f} stroke={p.s} strokeWidth="0.7"/>
|
||||
<ellipse cx="17.5" cy="13" rx="1.5" ry="0.8" fill={p.f} stroke={p.s} strokeWidth="0.7"/>
|
||||
{/* window behind */}
|
||||
<rect x="9" y="6" width="6" height="10" rx="0.5" fill={p.f} opacity="0.3"/>
|
||||
</svg>
|
||||
);
|
||||
case 'lightswitch': return (
|
||||
<svg width={size} height={size} viewBox="0 0 24 24" fill="none">
|
||||
<rect x="6" y="4" width="12" height="16" rx="2.5" fill={p.b} stroke={p.s} strokeWidth={w}/>
|
||||
<rect x="9" y="8" width="6" height="8" rx="1.5" fill={p.f} stroke={p.s} strokeWidth="1"/>
|
||||
<rect x="10.5" y="9" width="3" height="3" rx="0.8" fill={p.b} stroke={p.s} strokeWidth="0.8"/>
|
||||
{/* light rays */}
|
||||
<path d="M3.5 8L5 9" stroke={p.s} strokeWidth="0.8" strokeLinecap="round" opacity="0.4"/>
|
||||
<path d="M3 12H5" stroke={p.s} strokeWidth="0.8" strokeLinecap="round" opacity="0.4"/>
|
||||
<path d="M20.5 8L19 9" stroke={p.s} strokeWidth="0.8" strokeLinecap="round" opacity="0.4"/>
|
||||
<path d="M21 12H19" stroke={p.s} strokeWidth="0.8" strokeLinecap="round" opacity="0.4"/>
|
||||
</svg>
|
||||
);
|
||||
|
||||
// ===== LIVING ROOM =====
|
||||
case 'sofa': return (
|
||||
<svg width={size} height={size} viewBox="0 0 24 24" fill="none">
|
||||
<rect x="4" y="10" width="16" height="6" rx="2.5" fill={p.b} stroke={p.s} strokeWidth={w}/>
|
||||
<path d="M3 12C3 11 3.8 10 4.8 10V16H3V12Z" fill={p.f} stroke={p.s} strokeWidth="1"/>
|
||||
<path d="M21 12C21 11 20.2 10 19.2 10V16H21V12Z" fill={p.f} stroke={p.s} strokeWidth="1"/>
|
||||
<rect x="6.5" y="8.5" width="4.5" height="2" rx="1" fill={p.f} stroke={p.s} strokeWidth="0.8"/>
|
||||
<rect x="13" y="8.5" width="4.5" height="2" rx="1" fill={p.f} stroke={p.s} strokeWidth="0.8"/>
|
||||
<path d="M5 16V18.5M19 16V18.5" stroke={p.s} strokeWidth="1.2" strokeLinecap="round"/>
|
||||
<circle cx="10" cy="12.5" r="0.4" fill={p.s}/>
|
||||
<circle cx="14" cy="12.5" r="0.4" fill={p.s}/>
|
||||
<path d="M11 14C11.3 14.3 12.7 14.3 13 14" stroke={p.s} strokeWidth="0.5" strokeLinecap="round" fill="none"/>
|
||||
</svg>
|
||||
);
|
||||
case 'tv': return (
|
||||
<svg width={size} height={size} viewBox="0 0 24 24" fill="none">
|
||||
<rect x="3" y="5" width="18" height="12" rx="2" fill={p.b} stroke={p.s} strokeWidth={w}/>
|
||||
<rect x="5" y="7" width="14" height="8" rx="1" fill={p.f} stroke={p.s} strokeWidth="0.8"/>
|
||||
<path d="M9 17V19H15V17" stroke={p.s} strokeWidth="1.2"/>
|
||||
<path d="M7 19H17" stroke={p.s} strokeWidth="1.2" strokeLinecap="round"/>
|
||||
{/* screen shine */}
|
||||
<path d="M7 9L9 11" stroke="white" strokeWidth="0.8" strokeLinecap="round" opacity="0.5"/>
|
||||
</svg>
|
||||
);
|
||||
case 'lamp': return (
|
||||
<svg width={size} height={size} viewBox="0 0 24 24" fill="none">
|
||||
<path d="M8 14H16L14 5H10L8 14Z" fill={p.f} stroke={p.s} strokeWidth={w}/>
|
||||
<line x1="12" y1="14" x2="12" y2="19" stroke={p.s} strokeWidth="1.5" strokeLinecap="round"/>
|
||||
<path d="M9 19H15" stroke={p.s} strokeWidth="1.5" strokeLinecap="round"/>
|
||||
{/* warm glow */}
|
||||
<circle cx="12" cy="9" r="5" fill={p.f} opacity="0.15"/>
|
||||
{/* rays */}
|
||||
<path d="M6 8H4M18 8H20M6.5 4.5L5 3M17.5 4.5L19 3" stroke={p.s} strokeWidth="0.7" strokeLinecap="round" opacity="0.3"/>
|
||||
</svg>
|
||||
);
|
||||
case 'furniture': return (
|
||||
<svg width={size} height={size} viewBox="0 0 24 24" fill="none">
|
||||
<rect x="4" y="6" width="16" height="12" rx="2" fill={p.b} stroke={p.s} strokeWidth={w}/>
|
||||
<rect x="6" y="8" width="5" height="8" rx="1" fill={p.f} stroke={p.s} strokeWidth="0.8"/>
|
||||
<rect x="13" y="8" width="5" height="8" rx="1" fill={p.f} stroke={p.s} strokeWidth="0.8"/>
|
||||
<circle cx="8.5" cy="12" r="0.6" fill={p.s}/>
|
||||
<circle cx="15.5" cy="12" r="0.6" fill={p.s}/>
|
||||
<path d="M5 18V20M19 18V20" stroke={p.s} strokeWidth="1.2" strokeLinecap="round"/>
|
||||
{/* sparkle */}
|
||||
<path d="M20 4L20.4 5L21.4 5.4L20.4 5.8L20 6.8L19.6 5.8L18.6 5.4L19.6 5L20 4Z" fill={p.f} stroke={p.s} strokeWidth="0.3"/>
|
||||
</svg>
|
||||
);
|
||||
case 'rug': return (
|
||||
<svg width={size} height={size} viewBox="0 0 24 24" fill="none">
|
||||
<rect x="4" y="7" width="16" height="11" rx="2.5" fill={p.b} stroke={p.s} strokeWidth={w}/>
|
||||
<rect x="6" y="9" width="12" height="7" rx="1.5" fill={p.f} stroke={p.s} strokeWidth="0.8"/>
|
||||
<path d="M8 11.5H16M8 13.5H16" stroke={p.s} strokeWidth="0.7" opacity="0.3"/>
|
||||
{/* tassels */}
|
||||
<path d="M7 18V20M9 18V20M11 18V20M13 18V20M15 18V20M17 18V20" stroke={p.s} strokeWidth="0.8" strokeLinecap="round"/>
|
||||
<path d="M7 7V5M9 7V5M11 7V5M13 7V5M15 7V5M17 7V5" stroke={p.s} strokeWidth="0.8" strokeLinecap="round"/>
|
||||
</svg>
|
||||
);
|
||||
|
||||
// ===== OFFICE =====
|
||||
case 'desk': return (
|
||||
<svg width={size} height={size} viewBox="0 0 24 24" fill="none">
|
||||
<rect x="3" y="9" width="18" height="3" rx="1" fill={p.f} stroke={p.s} strokeWidth={w}/>
|
||||
<path d="M5 12V19M19 12V19" stroke={p.s} strokeWidth="1.5" strokeLinecap="round"/>
|
||||
<rect x="6" y="13" width="5" height="4" rx="1" fill={p.b} stroke={p.s} strokeWidth="1"/>
|
||||
<circle cx="8.5" cy="15" r="0.5" fill={p.s}/>
|
||||
{/* items on desk */}
|
||||
<rect x="8" y="6" width="3" height="3" rx="0.5" fill={p.b} stroke={p.s} strokeWidth="0.8"/>
|
||||
<path d="M14 8H17" stroke={p.s} strokeWidth="0.8" strokeLinecap="round" opacity="0.5"/>
|
||||
<path d="M14 6.5H16" stroke={p.s} strokeWidth="0.8" strokeLinecap="round" opacity="0.5"/>
|
||||
</svg>
|
||||
);
|
||||
case 'keyboard': return (
|
||||
<svg width={size} height={size} viewBox="0 0 24 24" fill="none">
|
||||
<rect x="2" y="8" width="20" height="9" rx="2.5" fill={p.b} stroke={p.s} strokeWidth={w}/>
|
||||
{/* keys */}
|
||||
<rect x="4.5" y="10" width="2" height="2" rx="0.5" fill={p.f} stroke={p.s} strokeWidth="0.6"/>
|
||||
<rect x="7.5" y="10" width="2" height="2" rx="0.5" fill={p.f} stroke={p.s} strokeWidth="0.6"/>
|
||||
<rect x="10.5" y="10" width="2" height="2" rx="0.5" fill={p.f} stroke={p.s} strokeWidth="0.6"/>
|
||||
<rect x="13.5" y="10" width="2" height="2" rx="0.5" fill={p.f} stroke={p.s} strokeWidth="0.6"/>
|
||||
<rect x="16.5" y="10" width="2" height="2" rx="0.5" fill={p.f} stroke={p.s} strokeWidth="0.6"/>
|
||||
<rect x="5.5" y="13" width="2" height="2" rx="0.5" fill={p.f} stroke={p.s} strokeWidth="0.6"/>
|
||||
<rect x="8.5" y="13" width="7" height="2" rx="0.5" fill={p.f} stroke={p.s} strokeWidth="0.6"/>
|
||||
<rect x="16.5" y="13" width="2" height="2" rx="0.5" fill={p.f} stroke={p.s} strokeWidth="0.6"/>
|
||||
</svg>
|
||||
);
|
||||
case 'monitor': return (
|
||||
<svg width={size} height={size} viewBox="0 0 24 24" fill="none">
|
||||
<rect x="3" y="4" width="18" height="12" rx="2" fill={p.b} stroke={p.s} strokeWidth={w}/>
|
||||
<rect x="5" y="6" width="14" height="8" rx="1" fill={p.f} stroke={p.s} strokeWidth="0.8"/>
|
||||
<path d="M10.5 16V18.5H13.5V16" stroke={p.s} strokeWidth="1.2"/>
|
||||
<path d="M8 19H16" stroke={p.s} strokeWidth="1.3" strokeLinecap="round"/>
|
||||
{/* screen face */}
|
||||
<circle cx="10" cy="10" r="0.5" fill={p.s}/>
|
||||
<circle cx="14" cy="10" r="0.5" fill={p.s}/>
|
||||
<path d="M10.5 11.5C10.8 11.9 13.2 11.9 13.5 11.5" stroke={p.s} strokeWidth="0.5" strokeLinecap="round" fill="none"/>
|
||||
</svg>
|
||||
);
|
||||
case 'cable': return (
|
||||
<svg width={size} height={size} viewBox="0 0 24 24" fill="none">
|
||||
<path d="M5 5C5 5 7 8 7 12C7 16 5 19 5 19" stroke={p.s} strokeWidth="1.5" strokeLinecap="round" fill="none"/>
|
||||
<path d="M10 4C10 4 13 8 13 12C13 16 10 20 10 20" stroke={p.f} strokeWidth="2" strokeLinecap="round" fill="none"/>
|
||||
<path d="M16 5C16 5 18 8 18 12C18 16 16 19 16 19" stroke={p.s} strokeWidth="1.5" strokeLinecap="round" fill="none"/>
|
||||
{/* plug */}
|
||||
<rect x="18" y="10" width="3" height="4" rx="1" fill={p.b} stroke={p.s} strokeWidth="1"/>
|
||||
<line x1="21" y1="11" x2="22.5" y2="11" stroke={p.s} strokeWidth="0.8" strokeLinecap="round"/>
|
||||
<line x1="21" y1="13" x2="22.5" y2="13" stroke={p.s} strokeWidth="0.8" strokeLinecap="round"/>
|
||||
</svg>
|
||||
);
|
||||
case 'chair': return (
|
||||
<svg width={size} height={size} viewBox="0 0 24 24" fill="none">
|
||||
<rect x="7" y="5" width="10" height="10" rx="2.5" fill={p.b} stroke={p.s} strokeWidth={w}/>
|
||||
<rect x="6" y="15" width="12" height="3" rx="1.2" fill={p.f} stroke={p.s} strokeWidth="1.2"/>
|
||||
<path d="M8 18V20.5M16 18V20.5" stroke={p.s} strokeWidth="1.3" strokeLinecap="round"/>
|
||||
<path d="M6 8H5V14H6M18 8H19V14H18" stroke={p.s} strokeWidth="1.2" strokeLinecap="round" fill="none"/>
|
||||
</svg>
|
||||
);
|
||||
|
||||
// ===== TRASH & BROOM =====
|
||||
case 'trash': return (
|
||||
<svg width={size} height={size} viewBox="0 0 24 24" fill="none">
|
||||
<rect x="6" y="8" width="12" height="11" rx="2.5" fill={p.b} stroke={p.s} strokeWidth={w}/>
|
||||
<path d="M5 8H19" stroke={p.s} strokeWidth="1.6" strokeLinecap="round"/>
|
||||
<path d="M9 6H15" stroke={p.s} strokeWidth="1.6" strokeLinecap="round"/>
|
||||
<path d="M10 11V16M14 11V16" stroke={p.s} strokeWidth="1.1" strokeLinecap="round"/>
|
||||
{/* face */}
|
||||
<circle cx="10" cy="12" r="0.4" fill={p.s}/>
|
||||
<circle cx="14" cy="12" r="0.4" fill={p.s}/>
|
||||
</svg>
|
||||
);
|
||||
case 'broom': return (
|
||||
<svg width={size} height={size} viewBox="0 0 24 24" fill="none">
|
||||
<line x1="15" y1="3" x2="12" y2="13" stroke={p.s} strokeWidth="1.8" strokeLinecap="round"/>
|
||||
<path d="M8 13H16L15 20H9L8 13Z" fill={p.b} stroke={p.s} strokeWidth={w}/>
|
||||
<line x1="10" y1="14" x2="10" y2="19" stroke={p.s} strokeWidth="0.5" opacity="0.3"/>
|
||||
<line x1="12" y1="14" x2="12" y2="19" stroke={p.s} strokeWidth="0.5" opacity="0.3"/>
|
||||
<line x1="14" y1="14" x2="14" y2="19" stroke={p.s} strokeWidth="0.5" opacity="0.3"/>
|
||||
{/* sparkle */}
|
||||
<path d="M5 8L5.5 9.2L6.7 9.7L5.5 10.2L5 11.4L4.5 10.2L3.3 9.7L4.5 9.2L5 8Z" fill={p.f} stroke={p.s} strokeWidth="0.5"/>
|
||||
</svg>
|
||||
);
|
||||
|
||||
// ===== LAUNDRY =====
|
||||
case 'washer': return (
|
||||
<svg width={size} height={size} viewBox="0 0 24 24" fill="none">
|
||||
<rect x="4" y="3" width="16" height="18" rx="3" fill={p.b} stroke={p.s} strokeWidth={w}/>
|
||||
<circle cx="12" cy="13.5" r="5" fill={p.f} stroke={p.s} strokeWidth="1.2"/>
|
||||
<path d="M9 13C10 11.5 12.5 11 14 12.5" stroke={p.s} strokeWidth="0.8" strokeLinecap="round" fill="none"/>
|
||||
<path d="M10 14.5C11 13 13.5 13.5 14.5 15" stroke={p.s} strokeWidth="0.8" strokeLinecap="round" fill="none"/>
|
||||
<circle cx="7" cy="6" r="0.8" fill={p.s}/>
|
||||
<circle cx="10" cy="6" r="0.8" fill={p.s}/>
|
||||
<rect x="14" y="5.5" width="4" height="1.2" rx="0.6" fill={p.f} stroke={p.s} strokeWidth="0.6"/>
|
||||
</svg>
|
||||
);
|
||||
case 'dryer': return (
|
||||
<svg width={size} height={size} viewBox="0 0 24 24" fill="none">
|
||||
<rect x="4" y="3" width="16" height="18" rx="3" fill={p.b} stroke={p.s} strokeWidth={w}/>
|
||||
<circle cx="12" cy="13.5" r="5" fill={p.f} stroke={p.s} strokeWidth="1.2"/>
|
||||
<circle cx="12" cy="13.5" r="2.5" fill={p.b} stroke={p.s} strokeWidth="0.8"/>
|
||||
<circle cx="7" cy="6" r="0.8" fill={p.s}/>
|
||||
<circle cx="10" cy="6" r="0.8" fill={p.s}/>
|
||||
{/* heat waves */}
|
||||
<path d="M11 12C11.3 11.5 11.7 12 12 11.5" stroke={p.s} strokeWidth="0.6" strokeLinecap="round" opacity="0.5"/>
|
||||
<path d="M12 14C12.3 13.5 12.7 14 13 13.5" stroke={p.s} strokeWidth="0.6" strokeLinecap="round" opacity="0.5"/>
|
||||
</svg>
|
||||
);
|
||||
case 'detergent': return (
|
||||
<svg width={size} height={size} viewBox="0 0 24 24" fill="none">
|
||||
<rect x="7" y="7" width="10" height="13" rx="2" fill={p.b} stroke={p.s} strokeWidth={w}/>
|
||||
<rect x="9" y="4" width="4" height="4" rx="1" fill={p.f} stroke={p.s} strokeWidth="1"/>
|
||||
<path d="M13 5.5H15.5C16 5.5 16.5 6 16.5 6.5V7" stroke={p.s} strokeWidth="1" fill="none"/>
|
||||
{/* label */}
|
||||
<rect x="9" y="11" width="6" height="4" rx="0.8" fill={p.f} stroke={p.s} strokeWidth="0.6"/>
|
||||
{/* bubbles */}
|
||||
<circle cx="17" cy="10" r="1" fill={p.f} stroke={p.s} strokeWidth="0.5"/>
|
||||
<circle cx="18.5" cy="8" r="0.7" fill={p.f} stroke={p.s} strokeWidth="0.4"/>
|
||||
</svg>
|
||||
);
|
||||
case 'iron': return (
|
||||
<svg width={size} height={size} viewBox="0 0 24 24" fill="none">
|
||||
<path d="M4 16H20L18 10H8L4 16Z" fill={p.b} stroke={p.s} strokeWidth={w}/>
|
||||
<path d="M8 10V7C8 6 9 5 10 5H14" stroke={p.s} strokeWidth="1.3" strokeLinecap="round" fill="none"/>
|
||||
<path d="M14 5H16C17 5 18 6 18 7V10" stroke={p.s} strokeWidth="1.3" strokeLinecap="round" fill="none"/>
|
||||
<path d="M6 16H18V17.5C18 18.3 17.3 19 16.5 19H7.5C6.7 19 6 18.3 6 17.5V16Z" fill={p.f} stroke={p.s} strokeWidth="1"/>
|
||||
{/* steam */}
|
||||
<path d="M10 3C10 2 9.5 1.5 9.5 1" stroke={p.s} strokeWidth="0.7" strokeLinecap="round" opacity="0.4"/>
|
||||
<path d="M13 3.5C13 2.5 12.5 2 12.5 1" stroke={p.s} strokeWidth="0.7" strokeLinecap="round" opacity="0.4"/>
|
||||
</svg>
|
||||
);
|
||||
case 'clothes': return (
|
||||
<svg width={size} height={size} viewBox="0 0 24 24" fill="none">
|
||||
{/* t-shirt shape */}
|
||||
<path d="M8 4L6 4L3 8L6 9L6 19H18V9L21 8L18 4L16 4" stroke={p.s} strokeWidth={w} fill={p.b}/>
|
||||
<path d="M8 4C8 4 9 6 12 6C15 6 16 4 16 4" stroke={p.s} strokeWidth="1.2" fill="none"/>
|
||||
{/* collar */}
|
||||
<path d="M10 5C10.5 6.5 13.5 6.5 14 5" stroke={p.f} strokeWidth="1.5" strokeLinecap="round" fill="none"/>
|
||||
{/* heart on shirt */}
|
||||
<path d="M12 14L10.5 12.5C10 12 10 11.2 10.5 10.7C11 10.2 11.5 10.2 12 10.7C12.5 10.2 13 10.2 13.5 10.7C14 11.2 14 12 13.5 12.5L12 14Z" fill={p.f}/>
|
||||
</svg>
|
||||
);
|
||||
|
||||
// ===== GARAGE =====
|
||||
case 'tools': return (
|
||||
<svg width={size} height={size} viewBox="0 0 24 24" fill="none">
|
||||
{/* wrench */}
|
||||
<path d="M6 17L13 10" stroke={p.s} strokeWidth="2" strokeLinecap="round"/>
|
||||
<path d="M14 5C14 5 16 4 18 6C20 8 19 10 19 10L16 7L14 9L17 12C17 12 14 13 12 11C10 9 11 6 11 6" fill={p.b} stroke={p.s} strokeWidth="1.2"/>
|
||||
{/* screwdriver */}
|
||||
<path d="M5 19L9 15" stroke={p.s} strokeWidth="2" strokeLinecap="round"/>
|
||||
<circle cx="5" cy="19" r="1.5" fill={p.f} stroke={p.s} strokeWidth="1"/>
|
||||
</svg>
|
||||
);
|
||||
case 'cobweb': return (
|
||||
<svg width={size} height={size} viewBox="0 0 24 24" fill="none">
|
||||
<path d="M4 4L20 20M4 12H20M12 4V20M4 20L20 4" stroke={p.s} strokeWidth="0.8" opacity="0.3"/>
|
||||
<path d="M8 8C9 7 11 6.5 12 6.5C13 6.5 15 7 16 8" stroke={p.s} strokeWidth="0.8" fill="none"/>
|
||||
<path d="M6 12C7 10 9.5 8.5 12 8.5C14.5 8.5 17 10 18 12" stroke={p.s} strokeWidth="0.8" fill="none"/>
|
||||
<path d="M5 16C7 13 9 11.5 12 11.5C15 11.5 17 13 19 16" stroke={p.s} strokeWidth="0.8" fill="none"/>
|
||||
{/* spider */}
|
||||
<circle cx="12" cy="12" r="1.5" fill={p.b} stroke={p.s} strokeWidth="1"/>
|
||||
<circle cx="12" cy="11" r="1" fill={p.f} stroke={p.s} strokeWidth="0.8"/>
|
||||
<circle cx="11.5" cy="10.8" r="0.3" fill={p.s}/>
|
||||
<circle cx="12.5" cy="10.8" r="0.3" fill={p.s}/>
|
||||
</svg>
|
||||
);
|
||||
case 'chemicals': return (
|
||||
<svg width={size} height={size} viewBox="0 0 24 24" fill="none">
|
||||
<path d="M9 4H15V9L18 17C18.3 18 17.5 19 16.5 19H7.5C6.5 19 5.7 18 6 17L9 9V4Z" fill={p.b} stroke={p.s} strokeWidth={w}/>
|
||||
<line x1="9" y1="4" x2="15" y2="4" stroke={p.s} strokeWidth="1.5" strokeLinecap="round"/>
|
||||
<path d="M8 14H16" stroke={p.f} strokeWidth="1.5"/>
|
||||
<circle cx="10" cy="16" r="0.8" fill={p.f}/>
|
||||
<circle cx="13" cy="15.5" r="1" fill={p.f}/>
|
||||
<circle cx="14.5" cy="17" r="0.6" fill={p.f}/>
|
||||
{/* warning */}
|
||||
<path d="M11.5 8L12 6.5L12.5 8" stroke={p.s} strokeWidth="0.8" strokeLinecap="round"/>
|
||||
</svg>
|
||||
);
|
||||
case 'garagedoor': return (
|
||||
<svg width={size} height={size} viewBox="0 0 24 24" fill="none">
|
||||
<rect x="3" y="5" width="18" height="15" rx="2" fill={p.b} stroke={p.s} strokeWidth={w}/>
|
||||
<line x1="3" y1="8" x2="21" y2="8" stroke={p.s} strokeWidth="0.8"/>
|
||||
<line x1="3" y1="11" x2="21" y2="11" stroke={p.s} strokeWidth="0.8"/>
|
||||
<line x1="3" y1="14" x2="21" y2="14" stroke={p.s} strokeWidth="0.8"/>
|
||||
<line x1="3" y1="17" x2="21" y2="17" stroke={p.s} strokeWidth="0.8"/>
|
||||
<circle cx="18" cy="14" r="0.8" fill={p.s}/>
|
||||
{/* sparkle */}
|
||||
<path d="M18 3L18.4 4L19.4 4.4L18.4 4.8L18 5.8L17.6 4.8L16.6 4.4L17.6 4L18 3Z" fill={p.f} stroke={p.s} strokeWidth="0.3"/>
|
||||
</svg>
|
||||
);
|
||||
|
||||
// ===== ORGANIZE =====
|
||||
case 'shelf': return (
|
||||
<svg width={size} height={size} viewBox="0 0 24 24" fill="none">
|
||||
<rect x="4" y="3" width="16" height="18" rx="1.5" fill="none" stroke={p.s} strokeWidth={w}/>
|
||||
<line x1="4" y1="10" x2="20" y2="10" stroke={p.s} strokeWidth="1.2"/>
|
||||
<line x1="4" y1="17" x2="20" y2="17" stroke={p.s} strokeWidth="1.2"/>
|
||||
{/* items */}
|
||||
<rect x="6" y="5" width="3" height="5" rx="0.5" fill={p.f} stroke={p.s} strokeWidth="0.7"/>
|
||||
<rect x="10" y="6" width="3" height="4" rx="0.5" fill={p.b} stroke={p.s} strokeWidth="0.7"/>
|
||||
<rect x="14" y="5.5" width="4" height="4.5" rx="0.5" fill={p.f} stroke={p.s} strokeWidth="0.7"/>
|
||||
<rect x="6" y="12" width="4" height="5" rx="0.5" fill={p.b} stroke={p.s} strokeWidth="0.7"/>
|
||||
<rect x="12" y="12" width="3" height="5" rx="0.5" fill={p.f} stroke={p.s} strokeWidth="0.7"/>
|
||||
<rect x="16" y="13" width="2.5" height="4" rx="0.5" fill={p.b} stroke={p.s} strokeWidth="0.7"/>
|
||||
</svg>
|
||||
);
|
||||
case 'drawer': return (
|
||||
<svg width={size} height={size} viewBox="0 0 24 24" fill="none">
|
||||
<rect x="4" y="4" width="16" height="16" rx="2" fill={p.b} stroke={p.s} strokeWidth={w}/>
|
||||
<line x1="4" y1="10" x2="20" y2="10" stroke={p.s} strokeWidth="1.2"/>
|
||||
<line x1="4" y1="16" x2="20" y2="16" stroke={p.s} strokeWidth="1.2"/>
|
||||
<rect x="10" y="6" width="4" height="2" rx="0.8" fill={p.f} stroke={p.s} strokeWidth="0.8"/>
|
||||
<rect x="10" y="12" width="4" height="2" rx="0.8" fill={p.f} stroke={p.s} strokeWidth="0.8"/>
|
||||
<rect x="10" y="17.5" width="4" height="1.5" rx="0.8" fill={p.f} stroke={p.s} strokeWidth="0.8"/>
|
||||
</svg>
|
||||
);
|
||||
case 'closet': return (
|
||||
<svg width={size} height={size} viewBox="0 0 24 24" fill="none">
|
||||
<rect x="4" y="3" width="16" height="18" rx="2" fill={p.b} stroke={p.s} strokeWidth={w}/>
|
||||
<line x1="12" y1="3" x2="12" y2="21" stroke={p.s} strokeWidth="1.2"/>
|
||||
<circle cx="10.5" cy="12" r="0.7" fill={p.s}/>
|
||||
<circle cx="13.5" cy="12" r="0.7" fill={p.s}/>
|
||||
{/* hanger */}
|
||||
<path d="M7 8L9 6.5L11 8" stroke={p.f} strokeWidth="1" strokeLinecap="round" fill="none"/>
|
||||
<line x1="9" y1="6.5" x2="9" y2="5.5" stroke={p.f} strokeWidth="0.8"/>
|
||||
<path d="M13 8L15 6.5L17 8" stroke={p.f} strokeWidth="1" strokeLinecap="round" fill="none"/>
|
||||
<line x1="15" y1="6.5" x2="15" y2="5.5" stroke={p.f} strokeWidth="0.8"/>
|
||||
</svg>
|
||||
);
|
||||
|
||||
// ===== DEFAULT =====
|
||||
default: return (
|
||||
<svg width={size} height={size} viewBox="0 0 24 24" fill="none">
|
||||
<path d="M12 4L13.8 9.5L19.5 11L13.8 12.5L12 18L10.2 12.5L4.5 11L10.2 9.5L12 4Z" fill={p.b} stroke={p.s} strokeWidth="1.2"/>
|
||||
<path d="M18.5 4.5L19 6L20.5 6.5L19 7L18.5 8.5L18 7L16.5 6.5L18 6L18.5 4.5Z" fill={p.f} stroke={p.s} strokeWidth="0.6"/>
|
||||
<path d="M6 16L6.3 17L7.3 17.3L6.3 17.6L6 18.6L5.7 17.6L4.7 17.3L5.7 17L6 16Z" fill={p.f} stroke={p.s} strokeWidth="0.5"/>
|
||||
</svg>
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
export function TaskIcon({ iconKey, size = 14 }: { iconKey?: string | null; size?: number }) {
|
||||
return <I k={iconKey || 'sparkle'} size={size} />;
|
||||
}
|
||||
253
client/src/components/icons/UIIcons.tsx
Normal file
253
client/src/components/icons/UIIcons.tsx
Normal file
|
|
@ -0,0 +1,253 @@
|
|||
export function CheckIcon() {
|
||||
return (
|
||||
<svg width="18" height="18" viewBox="0 0 18 18" fill="none">
|
||||
<path
|
||||
d="M4 9.5L7.5 13L14 5"
|
||||
stroke="#fff"
|
||||
strokeWidth="2.5"
|
||||
strokeLinecap="round"
|
||||
strokeLinejoin="round"
|
||||
/>
|
||||
</svg>
|
||||
);
|
||||
}
|
||||
|
||||
export function PlusIcon() {
|
||||
return (
|
||||
<svg width="20" height="20" viewBox="0 0 20 20" fill="none">
|
||||
<path
|
||||
d="M10 4V16M4 10H16"
|
||||
stroke="#F97316"
|
||||
strokeWidth="2"
|
||||
strokeLinecap="round"
|
||||
strokeLinejoin="round"
|
||||
/>
|
||||
</svg>
|
||||
);
|
||||
}
|
||||
|
||||
export function BackIcon() {
|
||||
return (
|
||||
<svg width="20" height="20" viewBox="0 0 20 20" fill="none">
|
||||
<path
|
||||
d="M12 4L6 10L12 16"
|
||||
stroke="#B0A090"
|
||||
strokeWidth="2"
|
||||
strokeLinecap="round"
|
||||
strokeLinejoin="round"
|
||||
/>
|
||||
</svg>
|
||||
);
|
||||
}
|
||||
|
||||
export function FireIcon() {
|
||||
return (
|
||||
<svg width="22" height="22" viewBox="0 0 22 22" fill="none">
|
||||
<path
|
||||
d="M11 2C11 2 5 8 5 13C5 16.31 7.69 19 11 19C14.31 19 17 16.31 17 13C17 8 11 2 11 2Z"
|
||||
fill="#F97316"
|
||||
stroke="#EA580C"
|
||||
strokeWidth="1.5"
|
||||
/>
|
||||
<path
|
||||
d="M11 11C11 11 9 13 9 14.5C9 15.6 9.9 16.5 11 16.5C12.1 16.5 13 15.6 13 14.5C13 13 11 11 11 11Z"
|
||||
fill="#FDE68A"
|
||||
/>
|
||||
</svg>
|
||||
);
|
||||
}
|
||||
|
||||
export function CoinIcon() {
|
||||
return (
|
||||
<svg width="22" height="22" viewBox="0 0 22 22" fill="none">
|
||||
<circle cx="11" cy="11" r="9" fill="#FBBF24" stroke="#F59E0B" strokeWidth="1.5" />
|
||||
<text x="11" y="15" textAnchor="middle" fontSize="11" fontWeight="800" fill="#92400E">
|
||||
$
|
||||
</text>
|
||||
</svg>
|
||||
);
|
||||
}
|
||||
|
||||
export function SparkleIcon() {
|
||||
return (
|
||||
<svg width="18" height="18" viewBox="0 0 18 18" fill="none">
|
||||
<path
|
||||
d="M9 1L10.5 6.5L16 8L10.5 9.5L9 15L7.5 9.5L2 8L7.5 6.5L9 1Z"
|
||||
fill="#F97316"
|
||||
opacity="0.8"
|
||||
/>
|
||||
</svg>
|
||||
);
|
||||
}
|
||||
|
||||
export function StarIcon() {
|
||||
return (
|
||||
<svg width="14" height="14" viewBox="0 0 14 14" fill="none">
|
||||
<path
|
||||
d="M7 1L8.5 5H12.5L9.5 7.5L10.5 11.5L7 9L3.5 11.5L4.5 7.5L1.5 5H5.5L7 1Z"
|
||||
fill="#F59E0B"
|
||||
stroke="#F59E0B"
|
||||
strokeWidth="0.5"
|
||||
/>
|
||||
</svg>
|
||||
);
|
||||
}
|
||||
|
||||
export function StarEmptyIcon() {
|
||||
return (
|
||||
<svg width="14" height="14" viewBox="0 0 14 14" fill="none">
|
||||
<path
|
||||
d="M7 1L8.5 5H12.5L9.5 7.5L10.5 11.5L7 9L3.5 11.5L4.5 7.5L1.5 5H5.5L7 1Z"
|
||||
fill="none"
|
||||
stroke="#E2D5C5"
|
||||
strokeWidth="1"
|
||||
/>
|
||||
</svg>
|
||||
);
|
||||
}
|
||||
|
||||
export function DownloadIcon() {
|
||||
return (
|
||||
<svg width="20" height="20" viewBox="0 0 20 20" fill="none">
|
||||
<path
|
||||
d="M10 3V13M10 13L6 9M10 13L14 9"
|
||||
stroke="#F97316"
|
||||
strokeWidth="2"
|
||||
strokeLinecap="round"
|
||||
strokeLinejoin="round"
|
||||
/>
|
||||
<path
|
||||
d="M3 15V16C3 16.55 3.45 17 4 17H16C16.55 17 17 16.55 17 16V15"
|
||||
stroke="#F97316"
|
||||
strokeWidth="2"
|
||||
strokeLinecap="round"
|
||||
strokeLinejoin="round"
|
||||
/>
|
||||
</svg>
|
||||
);
|
||||
}
|
||||
|
||||
export function UploadIcon() {
|
||||
return (
|
||||
<svg width="20" height="20" viewBox="0 0 20 20" fill="none">
|
||||
<path
|
||||
d="M10 13V3M10 3L6 7M10 3L14 7"
|
||||
stroke="#F97316"
|
||||
strokeWidth="2"
|
||||
strokeLinecap="round"
|
||||
strokeLinejoin="round"
|
||||
/>
|
||||
<path
|
||||
d="M3 15V16C3 16.55 3.45 17 4 17H16C16.55 17 17 16.55 17 16V15"
|
||||
stroke="#F97316"
|
||||
strokeWidth="2"
|
||||
strokeLinecap="round"
|
||||
strokeLinejoin="round"
|
||||
/>
|
||||
</svg>
|
||||
);
|
||||
}
|
||||
|
||||
export function LockIcon() {
|
||||
return (
|
||||
<svg width="20" height="20" viewBox="0 0 20 20" fill="none">
|
||||
<rect
|
||||
x="4" y="9" width="12" height="9" rx="2"
|
||||
fill="none"
|
||||
stroke="#B0A090"
|
||||
strokeWidth="2"
|
||||
strokeLinejoin="round"
|
||||
/>
|
||||
<path
|
||||
d="M7 9V6C7 4.34 8.34 3 10 3C11.66 3 13 4.34 13 6V9"
|
||||
stroke="#B0A090"
|
||||
strokeWidth="2"
|
||||
strokeLinecap="round"
|
||||
strokeLinejoin="round"
|
||||
/>
|
||||
<circle cx="10" cy="13.5" r="1.5" fill="#B0A090" />
|
||||
</svg>
|
||||
);
|
||||
}
|
||||
|
||||
export function GlobeIcon() {
|
||||
return (
|
||||
<svg width="20" height="20" viewBox="0 0 20 20" fill="none">
|
||||
<circle cx="10" cy="10" r="8" stroke="#B0A090" strokeWidth="1.5" />
|
||||
<ellipse cx="10" cy="10" rx="4" ry="8" stroke="#B0A090" strokeWidth="1.5" />
|
||||
<path d="M2 10H18" stroke="#B0A090" strokeWidth="1.5" />
|
||||
<path d="M10 2V18" stroke="#B0A090" strokeWidth="1.5" />
|
||||
</svg>
|
||||
);
|
||||
}
|
||||
|
||||
export function BellIcon() {
|
||||
return (
|
||||
<svg width="20" height="20" viewBox="0 0 20 20" fill="none">
|
||||
<path
|
||||
d="M10 2C7.24 2 5 4.24 5 7V11L3 14H17L15 11V7C15 4.24 12.76 2 10 2Z"
|
||||
stroke="#B0A090"
|
||||
strokeWidth="2"
|
||||
strokeLinecap="round"
|
||||
strokeLinejoin="round"
|
||||
/>
|
||||
<path
|
||||
d="M8 14V15C8 16.1 8.9 17 10 17C11.1 17 12 16.1 12 15V14"
|
||||
stroke="#B0A090"
|
||||
strokeWidth="2"
|
||||
strokeLinecap="round"
|
||||
/>
|
||||
</svg>
|
||||
);
|
||||
}
|
||||
|
||||
export function UsersIcon() {
|
||||
return (
|
||||
<svg width="22" height="22" viewBox="0 0 22 22" fill="none">
|
||||
<circle cx="8" cy="7" r="3" stroke="#B0A090" strokeWidth="1.5" />
|
||||
<path
|
||||
d="M2 18C2 15.24 4.24 13 7 13H9C11.76 13 14 15.24 14 18"
|
||||
stroke="#B0A090"
|
||||
strokeWidth="1.5"
|
||||
strokeLinecap="round"
|
||||
/>
|
||||
<circle cx="16" cy="8" r="2.5" stroke="#B0A090" strokeWidth="1.5" />
|
||||
<path
|
||||
d="M16 13C18.21 13 20 14.79 20 17"
|
||||
stroke="#B0A090"
|
||||
strokeWidth="1.5"
|
||||
strokeLinecap="round"
|
||||
/>
|
||||
</svg>
|
||||
);
|
||||
}
|
||||
|
||||
export function TrashIcon() {
|
||||
return (
|
||||
<svg width="16" height="16" viewBox="0 0 20 20" fill="none">
|
||||
<path
|
||||
d="M4 6H16"
|
||||
stroke="currentColor"
|
||||
strokeWidth="1.8"
|
||||
strokeLinecap="round"
|
||||
/>
|
||||
<path
|
||||
d="M7.5 6V4.8C7.5 4.36 7.86 4 8.3 4H11.7C12.14 4 12.5 4.36 12.5 4.8V6"
|
||||
stroke="currentColor"
|
||||
strokeWidth="1.8"
|
||||
strokeLinecap="round"
|
||||
/>
|
||||
<rect
|
||||
x="5.5"
|
||||
y="6"
|
||||
width="9"
|
||||
height="10"
|
||||
rx="1.6"
|
||||
stroke="currentColor"
|
||||
strokeWidth="1.8"
|
||||
/>
|
||||
<path d="M8.5 9V13" stroke="currentColor" strokeWidth="1.8" strokeLinecap="round" />
|
||||
<path d="M11.5 9V13" stroke="currentColor" strokeWidth="1.8" strokeLinecap="round" />
|
||||
</svg>
|
||||
);
|
||||
}
|
||||
60
client/src/components/layout/PageHeader.tsx
Normal file
60
client/src/components/layout/PageHeader.tsx
Normal file
|
|
@ -0,0 +1,60 @@
|
|||
import { FireIcon, CoinIcon } from '../icons/UIIcons';
|
||||
import type { User } from '../../hooks/useAuth';
|
||||
|
||||
interface PageHeaderProps {
|
||||
title: string;
|
||||
subtitle: string;
|
||||
user: User;
|
||||
rightContent?: React.ReactNode;
|
||||
onCoinsClick?: () => void;
|
||||
onStreakClick?: () => void;
|
||||
}
|
||||
|
||||
export function PageHeader({ title, subtitle, user, rightContent, onCoinsClick, onStreakClick }: PageHeaderProps) {
|
||||
return (
|
||||
<div style={{ display: 'flex', alignItems: 'center', justifyContent: 'space-between', marginBottom: 28 }}>
|
||||
<div>
|
||||
<h1 style={{ fontSize: 26, fontWeight: 900, color: 'var(--warm-text)', margin: 0, letterSpacing: -0.5 }}>
|
||||
{title}
|
||||
</h1>
|
||||
<p style={{ fontSize: 13, color: 'var(--warm-text-light)', fontWeight: 600, marginTop: 3 }}>
|
||||
{subtitle}
|
||||
</p>
|
||||
</div>
|
||||
<div style={{ display: 'flex', alignItems: 'center', gap: 16 }}>
|
||||
{rightContent}
|
||||
<div
|
||||
onClick={onStreakClick}
|
||||
role={onStreakClick ? 'button' : undefined}
|
||||
tabIndex={onStreakClick ? 0 : -1}
|
||||
onKeyDown={(e) => {
|
||||
if (!onStreakClick) return;
|
||||
if (e.key === 'Enter' || e.key === ' ') {
|
||||
e.preventDefault();
|
||||
onStreakClick();
|
||||
}
|
||||
}}
|
||||
style={{
|
||||
display: 'flex', alignItems: 'center', gap: 6,
|
||||
backgroundColor: 'var(--warm-accent-light)', borderRadius: 14, padding: '8px 16px',
|
||||
border: '1.5px solid var(--warm-streak-border)',
|
||||
cursor: onStreakClick ? 'pointer' : 'default',
|
||||
}}>
|
||||
<FireIcon />
|
||||
<span style={{ fontSize: 15, fontWeight: 800, color: 'var(--warm-streak-text)' }}>{user.currentStreak}</span>
|
||||
</div>
|
||||
<div
|
||||
onClick={onCoinsClick}
|
||||
style={{
|
||||
display: 'flex', alignItems: 'center', gap: 6,
|
||||
backgroundColor: 'var(--warm-accent-light)', borderRadius: 14, padding: '8px 16px',
|
||||
border: '1.5px solid var(--warm-streak-border)',
|
||||
cursor: onCoinsClick ? 'pointer' : 'default',
|
||||
}}>
|
||||
<CoinIcon />
|
||||
<span style={{ fontSize: 15, fontWeight: 800, color: 'var(--warm-streak-text)' }}>{user.coins}</span>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
109
client/src/components/layout/Sidebar.tsx
Normal file
109
client/src/components/layout/Sidebar.tsx
Normal file
|
|
@ -0,0 +1,109 @@
|
|||
import { NavLink, useNavigate } from 'react-router-dom';
|
||||
import { HomeIcon, RoomsIcon, TrophyIcon, CalendarIcon, ActivityIcon, AchievementsIcon, SettingsIcon, RewardsIcon } from '../icons/NavIcons';
|
||||
import { FireIcon, CoinIcon, SparkleIcon } from '../icons/UIIcons';
|
||||
import { UserAvatar } from '../shared/UserAvatar';
|
||||
import { useTranslation } from '../../hooks/useTranslation';
|
||||
import type { User } from '../../hooks/useAuth';
|
||||
|
||||
interface SidebarProps {
|
||||
user: User;
|
||||
}
|
||||
|
||||
const navItems = [
|
||||
{ to: '/', label: 'Home', Icon: HomeIcon },
|
||||
{ to: '/rooms', label: 'Rooms', Icon: RoomsIcon },
|
||||
{ to: '/leaderboard', label: 'Board', Icon: TrophyIcon },
|
||||
{ to: '/calendar', label: 'Calendar', Icon: CalendarIcon },
|
||||
{ to: '/activity', label: 'Activity', Icon: ActivityIcon },
|
||||
{ to: '/rewards', label: 'Rewards', Icon: RewardsIcon },
|
||||
{ to: '/achievements', label: 'Achievements', Icon: AchievementsIcon },
|
||||
{ to: '/settings', label: 'Settings', Icon: SettingsIcon },
|
||||
];
|
||||
|
||||
export function Sidebar({ user }: SidebarProps) {
|
||||
const navigate = useNavigate();
|
||||
const { t } = useTranslation(user.language);
|
||||
|
||||
return (
|
||||
<nav style={{
|
||||
width: 240, minHeight: '100vh', backgroundColor: 'var(--warm-sidebar)',
|
||||
borderRight: '1.5px solid var(--warm-sidebar-border)', padding: '24px 0',
|
||||
display: 'flex', flexDirection: 'column', position: 'fixed', top: 0, left: 0, zIndex: 50,
|
||||
}}>
|
||||
{/* Logo */}
|
||||
<div style={{ padding: '0 20px', marginBottom: 36, display: 'flex', alignItems: 'center', gap: 12 }}>
|
||||
<div style={{
|
||||
width: 42, height: 42, borderRadius: 14,
|
||||
background: 'var(--warm-sidebar-active)',
|
||||
border: '1.5px solid var(--warm-sidebar-user-border)',
|
||||
display: 'flex', alignItems: 'center', justifyContent: 'center',
|
||||
}}>
|
||||
<SparkleIcon />
|
||||
</div>
|
||||
<div>
|
||||
<div style={{ fontSize: 19, fontWeight: 900, color: 'var(--warm-text)', letterSpacing: -0.5 }}>TidyQuest</div>
|
||||
<div style={{ fontSize: 10, color: 'var(--warm-text-light)', fontWeight: 700, letterSpacing: 1.2, textTransform: 'uppercase' }}>
|
||||
{t('nav.tagline')}
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
{/* Nav */}
|
||||
<div style={{ flex: 1, display: 'flex', flexDirection: 'column', gap: 2, padding: '0 12px' }}>
|
||||
{navItems.map((item) => (
|
||||
<NavLink key={item.to} to={item.to} end={item.to === '/'}
|
||||
style={{ textDecoration: 'none' }}
|
||||
>
|
||||
{({ isActive }) => (
|
||||
<div style={{
|
||||
display: 'flex', alignItems: 'center', gap: 12,
|
||||
padding: '11px 16px', borderRadius: 14,
|
||||
backgroundColor: isActive ? 'var(--warm-sidebar-active)' : 'transparent',
|
||||
borderLeft: isActive ? '3px solid var(--warm-accent)' : '3px solid transparent',
|
||||
transition: 'all 0.15s ease',
|
||||
}}>
|
||||
<span style={{ flexShrink: 0 }}><item.Icon active={isActive} /></span>
|
||||
<span style={{
|
||||
fontSize: 14, fontWeight: isActive ? 800 : 600,
|
||||
color: isActive ? 'var(--warm-accent)' : 'var(--warm-text-muted)',
|
||||
}}>{t(`nav.${item.label.toLowerCase()}`)}</span>
|
||||
</div>
|
||||
)}
|
||||
</NavLink>
|
||||
))}
|
||||
</div>
|
||||
|
||||
{/* User Card */}
|
||||
<div style={{ padding: '0 14px' }}>
|
||||
<div
|
||||
onClick={() => navigate('/profile')}
|
||||
style={{
|
||||
display: 'flex', alignItems: 'center', gap: 10, padding: '12px 14px',
|
||||
backgroundColor: 'var(--warm-sidebar-user-bg)', borderRadius: 16, border: '1.5px solid var(--warm-sidebar-user-border)',
|
||||
cursor: 'pointer', transition: 'all 0.15s ease',
|
||||
}}
|
||||
>
|
||||
<UserAvatar
|
||||
name={user.displayName}
|
||||
color={user.avatarColor}
|
||||
size={38}
|
||||
avatarType={user.avatarType}
|
||||
avatarPreset={user.avatarPreset}
|
||||
avatarPhotoUrl={user.avatarPhotoUrl}
|
||||
/>
|
||||
<div style={{ flex: 1 }}>
|
||||
<div style={{ fontSize: 13, fontWeight: 800, color: 'var(--warm-text)' }}>{user.displayName}</div>
|
||||
<div style={{ display: 'flex', alignItems: 'center', gap: 8, marginTop: 2 }}>
|
||||
<span style={{ display: 'flex', alignItems: 'center', gap: 3, fontSize: 11, color: 'var(--warm-text-light)', fontWeight: 600 }}>
|
||||
<CoinIcon /> {user.coins}
|
||||
</span>
|
||||
<span style={{ display: 'flex', alignItems: 'center', gap: 3, fontSize: 11, color: 'var(--warm-text-light)', fontWeight: 600 }}>
|
||||
<FireIcon /> {user.currentStreak}d
|
||||
</span>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
</nav>
|
||||
);
|
||||
}
|
||||
162
client/src/components/pages/Achievements.tsx
Normal file
162
client/src/components/pages/Achievements.tsx
Normal file
|
|
@ -0,0 +1,162 @@
|
|||
import { SparkleIcon, FireIcon, CoinIcon, StarIcon } from '../icons/UIIcons';
|
||||
import { useTranslation } from '../../hooks/useTranslation';
|
||||
|
||||
function AchievementIcon({ type }: { type: string }) {
|
||||
if (type === 'fire') return <FireIcon />;
|
||||
if (type === 'coin') return <CoinIcon />;
|
||||
if (type === 'star') return <StarIcon />;
|
||||
if (type === 'crown') {
|
||||
return (
|
||||
<svg width="18" height="18" viewBox="0 0 20 20" fill="none">
|
||||
<path d="M3 15L5 6L10 10L15 6L17 15H3Z" fill="#F59E0B" />
|
||||
</svg>
|
||||
);
|
||||
}
|
||||
if (type === 'broom') {
|
||||
return (
|
||||
<svg width="18" height="18" viewBox="0 0 20 20" fill="none">
|
||||
<rect x="9" y="2" width="2" height="10" rx="1" fill="#B45309" />
|
||||
<path d="M6 12H14L13 18H7L6 12Z" fill="#F59E0B" />
|
||||
<line x1="8" y1="13" x2="8" y2="17" stroke="#B45309" strokeWidth="0.5" />
|
||||
<line x1="10" y1="13" x2="10" y2="17" stroke="#B45309" strokeWidth="0.5" />
|
||||
<line x1="12" y1="13" x2="12" y2="17" stroke="#B45309" strokeWidth="0.5" />
|
||||
</svg>
|
||||
);
|
||||
}
|
||||
if (type === 'heart') {
|
||||
return (
|
||||
<svg width="18" height="18" viewBox="0 0 20 20" fill="none">
|
||||
<path d="M10 16L5.5 11.8C4 10.3 4 8 5.5 6.5C6.8 5.2 9 5.2 10 6.5C11 5.2 13.2 5.2 14.5 6.5C16 8 16 10.3 14.5 11.8L10 16Z" fill="#F87171" />
|
||||
</svg>
|
||||
);
|
||||
}
|
||||
if (type === 'shield') {
|
||||
return (
|
||||
<svg width="18" height="18" viewBox="0 0 20 20" fill="none">
|
||||
<path d="M10 2L4 5V10C4 14 7 17 10 18C13 17 16 14 16 10V5L10 2Z" fill="#60A5FA" />
|
||||
<path d="M9 11L7.5 9.5L8.5 8.5L9 9L11.5 6.5L12.5 7.5L9 11Z" fill="#fff" />
|
||||
</svg>
|
||||
);
|
||||
}
|
||||
if (type === 'rocket') {
|
||||
return (
|
||||
<svg width="18" height="18" viewBox="0 0 20 20" fill="none">
|
||||
<path d="M10 3C10 3 14 6 14 12L12 14H8L6 12C6 6 10 3 10 3Z" fill="#F59E0B" />
|
||||
<circle cx="10" cy="9" r="2" fill="#fff" />
|
||||
<path d="M8 14L7 17H9L8 14Z" fill="#EF4444" />
|
||||
<path d="M12 14L13 17H11L12 14Z" fill="#EF4444" />
|
||||
</svg>
|
||||
);
|
||||
}
|
||||
if (type === 'diamond') {
|
||||
return (
|
||||
<svg width="18" height="18" viewBox="0 0 20 20" fill="none">
|
||||
<path d="M10 3L16 8L10 17L4 8L10 3Z" fill="#A78BFA" />
|
||||
<path d="M4 8H16L10 3L4 8Z" fill="#C4B5FD" />
|
||||
<line x1="10" y1="3" x2="10" y2="17" stroke="#7C3AED" strokeWidth="0.5" opacity="0.3" />
|
||||
</svg>
|
||||
);
|
||||
}
|
||||
return <SparkleIcon />;
|
||||
}
|
||||
|
||||
interface AchRow {
|
||||
id: string;
|
||||
titleKey?: string;
|
||||
title?: string;
|
||||
descKey?: string;
|
||||
description?: string;
|
||||
icon: string;
|
||||
threshold: number;
|
||||
value: number;
|
||||
progress: number;
|
||||
unlocked: boolean;
|
||||
}
|
||||
|
||||
interface AchUser {
|
||||
id: number;
|
||||
displayName: string;
|
||||
role: 'admin' | 'member' | 'child';
|
||||
avatarColor: string;
|
||||
achievements: AchRow[];
|
||||
}
|
||||
|
||||
interface Props {
|
||||
data: { me: AchUser; family: AchUser[] } | null;
|
||||
language?: string;
|
||||
}
|
||||
|
||||
export function Achievements({ data, language }: Props) {
|
||||
const { t } = useTranslation(language);
|
||||
if (!data) return null;
|
||||
|
||||
const renderUser = (u: AchUser) => {
|
||||
const unlocked = u.achievements.filter(a => a.unlocked);
|
||||
const locked = u.achievements.filter(a => !a.unlocked);
|
||||
|
||||
return (
|
||||
<div key={u.id} className="tq-card" style={{ padding: 20 }}>
|
||||
<div style={{ display: 'flex', alignItems: 'center', justifyContent: 'space-between', marginBottom: 12 }}>
|
||||
<h3 style={{ fontSize: 15, fontWeight: 900, color: 'var(--warm-text)', margin: 0 }}>{u.displayName}</h3>
|
||||
<span style={{ fontSize: 11, fontWeight: 800, color: 'var(--warm-accent)', backgroundColor: 'var(--warm-accent-light)', padding: '4px 12px', borderRadius: 99 }}>
|
||||
{unlocked.length}/{u.achievements.length}
|
||||
</span>
|
||||
</div>
|
||||
{unlocked.length > 0 && (
|
||||
<div style={{ display: 'grid', gridTemplateColumns: 'repeat(auto-fill, minmax(210px, 1fr))', gap: 10, marginBottom: locked.length > 0 ? 16 : 0 }}>
|
||||
{unlocked.map((a) => (
|
||||
<div key={a.id} style={{
|
||||
borderRadius: 14, padding: 12, border: '1.5px solid var(--warm-streak-border)',
|
||||
backgroundColor: 'var(--warm-accent-light)',
|
||||
}}>
|
||||
<div style={{ display: 'flex', alignItems: 'center', gap: 8, marginBottom: 6 }}>
|
||||
<AchievementIcon type={a.icon} />
|
||||
<div style={{ fontSize: 13, fontWeight: 800, color: 'var(--warm-text)' }}>{a.titleKey ? t(a.titleKey) : a.title}</div>
|
||||
</div>
|
||||
<div style={{ fontSize: 11, color: 'var(--warm-text-muted)', fontWeight: 600, marginBottom: 6 }}>{a.descKey ? t(a.descKey) : a.description}</div>
|
||||
<div style={{ height: 6, borderRadius: 999, background: 'var(--health-bar-track)', overflow: 'hidden', marginBottom: 6 }}>
|
||||
<div style={{ width: '100%', height: '100%', background: 'var(--health-green)' }} />
|
||||
</div>
|
||||
<div style={{ fontSize: 10, color: 'var(--warm-text-light)', fontWeight: 700 }}>
|
||||
{a.value}/{a.threshold}
|
||||
</div>
|
||||
</div>
|
||||
))}
|
||||
</div>
|
||||
)}
|
||||
{locked.length > 0 && (
|
||||
<div style={{ display: 'grid', gridTemplateColumns: 'repeat(auto-fill, minmax(210px, 1fr))', gap: 10 }}>
|
||||
{locked.map((a) => (
|
||||
<div key={a.id} style={{
|
||||
borderRadius: 14, padding: 12, border: '1.5px solid var(--warm-border)',
|
||||
backgroundColor: 'var(--warm-bg-subtle)',
|
||||
}}>
|
||||
<div style={{ display: 'flex', alignItems: 'center', gap: 8, marginBottom: 6 }}>
|
||||
<AchievementIcon type={a.icon} />
|
||||
<div style={{ fontSize: 13, fontWeight: 800, color: 'var(--warm-text)' }}>{a.titleKey ? t(a.titleKey) : a.title}</div>
|
||||
</div>
|
||||
<div style={{ fontSize: 11, color: 'var(--warm-text-muted)', fontWeight: 600, marginBottom: 6 }}>{a.descKey ? t(a.descKey) : a.description}</div>
|
||||
<div style={{ height: 6, borderRadius: 999, background: 'var(--health-bar-track)', overflow: 'hidden', marginBottom: 6 }}>
|
||||
<div style={{ width: `${a.progress}%`, height: '100%', background: 'var(--warm-coin)' }} />
|
||||
</div>
|
||||
<div style={{ fontSize: 10, color: 'var(--warm-text-light)', fontWeight: 700 }}>
|
||||
{a.value}/{a.threshold}
|
||||
</div>
|
||||
</div>
|
||||
))}
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
);
|
||||
};
|
||||
|
||||
return (
|
||||
<div className="page-enter" style={{ display: 'grid', gap: 16 }}>
|
||||
{renderUser(data.me)}
|
||||
{data.family.length > 0 && (
|
||||
<div style={{ fontSize: 14, fontWeight: 800, color: 'var(--warm-text-muted)' }}>{t('achievements.familyProgress')}</div>
|
||||
)}
|
||||
{data.family.map(renderUser)}
|
||||
</div>
|
||||
);
|
||||
}
|
||||
143
client/src/components/pages/Calendar.tsx
Normal file
143
client/src/components/pages/Calendar.tsx
Normal file
|
|
@ -0,0 +1,143 @@
|
|||
import { TaskIcon } from '../icons/TaskIcons';
|
||||
import { useTranslation } from '../../hooks/useTranslation';
|
||||
|
||||
interface CalendarProps {
|
||||
completions: Array<{ completedAt: string; taskName: string; translationKey?: string; roomName: string }>;
|
||||
tasks: Array<{ id: number; name: string; translationKey?: string; roomName: string; roomType: string; health: number; frequencyDays: number; lastCompletedAt: string | null; iconKey?: string }>;
|
||||
language?: string;
|
||||
}
|
||||
|
||||
export function Calendar({ completions, tasks, language }: CalendarProps) {
|
||||
const { taskName, t, roomDisplayName } = useTranslation(language);
|
||||
const localeMap: Record<string, string> = { en: 'en-US', fr: 'fr-FR', de: 'de-DE', es: 'es-ES' };
|
||||
const locale = localeMap[language || 'en'] || 'en-US';
|
||||
const today = new Date();
|
||||
const year = today.getFullYear();
|
||||
const month = today.getMonth();
|
||||
const firstDay = new Date(year, month, 1).getDay();
|
||||
const daysInMonth = new Date(year, month + 1, 0).getDate();
|
||||
const monthName = today.toLocaleString(locale, { month: 'long', year: 'numeric' });
|
||||
|
||||
// Days with completions this month
|
||||
const completionDays = new Set(
|
||||
completions
|
||||
.filter((c) => {
|
||||
const d = new Date(c.completedAt);
|
||||
return d.getFullYear() === year && d.getMonth() === month;
|
||||
})
|
||||
.map((c) => new Date(c.completedAt).getDate())
|
||||
);
|
||||
|
||||
// Upcoming due dates
|
||||
const upcoming = tasks
|
||||
.map((task) => {
|
||||
const dueDate = new Date(task.lastCompletedAt || Date.now());
|
||||
if (task.lastCompletedAt) {
|
||||
dueDate.setDate(dueDate.getDate() + task.frequencyDays);
|
||||
}
|
||||
const dueInDays = task.lastCompletedAt
|
||||
? Math.max(0, Math.ceil((dueDate.getTime() - Date.now()) / 86400000))
|
||||
: 0;
|
||||
return { ...task, dueInDays, dueDate };
|
||||
})
|
||||
.filter((task) => task.dueInDays <= 30)
|
||||
.sort((a, b) => a.dueInDays - b.dueInDays);
|
||||
|
||||
// Days with due tasks
|
||||
const dueDays = new Set(
|
||||
upcoming
|
||||
.filter((task) => task.dueDate.getMonth() === month && task.dueDate.getFullYear() === year)
|
||||
.map((task) => task.dueDate.getDate())
|
||||
);
|
||||
|
||||
// Calendar grid padding
|
||||
const calDays: (number | null)[] = [];
|
||||
const offset = firstDay === 0 ? 6 : firstDay - 1;
|
||||
for (let i = 0; i < offset; i++) calDays.push(null);
|
||||
for (let d = 1; d <= daysInMonth; d++) calDays.push(d);
|
||||
|
||||
return (
|
||||
<div className="page-enter" style={{ display: 'grid', gridTemplateColumns: '1fr 300px', gap: 20 }}>
|
||||
{/* Calendar Grid */}
|
||||
<div className="tq-card" style={{ padding: 28 }}>
|
||||
<div style={{ fontSize: 18, fontWeight: 800, color: 'var(--warm-text)', textAlign: 'center', marginBottom: 20 }}>{monthName}</div>
|
||||
<div style={{ display: 'grid', gridTemplateColumns: 'repeat(7, 1fr)', gap: 4, textAlign: 'center' }}>
|
||||
{[
|
||||
t('calendar.mon'),
|
||||
t('calendar.tue'),
|
||||
t('calendar.wed'),
|
||||
t('calendar.thu'),
|
||||
t('calendar.fri'),
|
||||
t('calendar.sat'),
|
||||
t('calendar.sun'),
|
||||
].map((d) => (
|
||||
<div key={d} style={{ fontSize: 12, fontWeight: 800, color: 'var(--warm-text-light)', padding: 10 }}>{d}</div>
|
||||
))}
|
||||
{calDays.map((d, i) => {
|
||||
if (!d) return <div key={`e-${i}`} />;
|
||||
const isToday = d === today.getDate();
|
||||
const hasActivity = completionDays.has(d);
|
||||
const isDue = dueDays.has(d);
|
||||
const isPast = d < today.getDate();
|
||||
return (
|
||||
<div key={d} style={{
|
||||
padding: 10, borderRadius: 14, fontSize: 14,
|
||||
fontWeight: isToday ? 900 : 600,
|
||||
color: isToday ? '#fff' : isPast ? 'var(--warm-text)' : 'var(--warm-text-light)',
|
||||
backgroundColor: isToday ? 'var(--warm-accent)' : hasActivity && isPast ? 'var(--health-green-bg)' : isDue && !isPast ? 'var(--health-red-bg)' : 'transparent',
|
||||
border: isToday ? 'none' : hasActivity && isPast ? '1.5px solid var(--health-green)' : isDue && !isPast ? '1.5px solid var(--health-red)' : '1.5px solid transparent',
|
||||
}}>
|
||||
{d}
|
||||
</div>
|
||||
);
|
||||
})}
|
||||
</div>
|
||||
<div style={{ display: 'flex', gap: 20, justifyContent: 'center', marginTop: 20 }}>
|
||||
{[
|
||||
{ bg: 'var(--health-green-bg)', border: 'var(--health-green)', label: t('calendar.choresDone') },
|
||||
{ bg: 'var(--health-red-bg)', border: 'var(--health-red)', label: t('calendar.tasksDue') },
|
||||
{ bg: 'var(--warm-accent)', border: 'var(--warm-accent)', label: t('calendar.today') },
|
||||
].map((l) => (
|
||||
<div key={l.label} style={{ display: 'flex', alignItems: 'center', gap: 6, fontSize: 12, color: 'var(--warm-text-muted)', fontWeight: 600 }}>
|
||||
<div style={{ width: 14, height: 14, borderRadius: 6, backgroundColor: l.bg, border: `1.5px solid ${l.border}` }} />
|
||||
{l.label}
|
||||
</div>
|
||||
))}
|
||||
</div>
|
||||
</div>
|
||||
|
||||
{/* Upcoming Due Dates */}
|
||||
<div className="tq-card" style={{ padding: 20 }}>
|
||||
<h3 style={{ fontSize: 15, fontWeight: 800, color: 'var(--warm-text)', margin: '0 0 14px' }}>{t('calendar.upcomingDueDates')}</h3>
|
||||
{upcoming.slice(0, 8).map((item, i) => {
|
||||
return (
|
||||
<div key={item.id} style={{
|
||||
display: 'flex', alignItems: 'center', gap: 10,
|
||||
padding: '12px 0', borderBottom: i < Math.min(upcoming.length, 8) - 1 ? '1px solid var(--warm-border)' : 'none',
|
||||
}}>
|
||||
<div style={{
|
||||
width: 36, height: 36, borderRadius: 12,
|
||||
backgroundColor: 'var(--warm-accent-light)', display: 'flex', alignItems: 'center', justifyContent: 'center',
|
||||
border: '1.5px solid var(--warm-border)',
|
||||
}}><TaskIcon iconKey={item.iconKey} size={20} /></div>
|
||||
<div style={{ flex: 1 }}>
|
||||
<div style={{ fontSize: 13, fontWeight: 700, color: 'var(--warm-text)' }}>{taskName(item.name, item.translationKey)}</div>
|
||||
<div style={{ fontSize: 11, color: 'var(--warm-text-light)', fontWeight: 600 }}>{roomDisplayName(item.roomName, item.roomType)}</div>
|
||||
</div>
|
||||
<div style={{
|
||||
fontSize: 11, fontWeight: 800, padding: '4px 12px', borderRadius: 10,
|
||||
backgroundColor: item.dueInDays <= 5 ? 'var(--health-red-bg)' : 'var(--health-yellow-bg)',
|
||||
color: item.dueInDays <= 5 ? 'var(--health-red)' : 'var(--health-yellow)',
|
||||
}}>{t('calendar.inDays').replace('{days}', `${item.dueInDays}`)}</div>
|
||||
</div>
|
||||
);
|
||||
})}
|
||||
{upcoming.length === 0 && (
|
||||
<div style={{ padding: 20, textAlign: 'center', color: 'var(--warm-text-light)', fontSize: 13, fontWeight: 600 }}>
|
||||
{t('calendar.allCaughtUp')}
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
716
client/src/components/pages/Dashboard.tsx
Normal file
716
client/src/components/pages/Dashboard.tsx
Normal file
|
|
@ -0,0 +1,716 @@
|
|||
import React from 'react';
|
||||
import HealthBar from '../shared/HealthBar';
|
||||
import RingGauge from '../shared/RingGauge';
|
||||
import UserAvatar from '../shared/UserAvatar';
|
||||
import { FireIcon, CoinIcon, CheckIcon } from '../icons/UIIcons';
|
||||
import { getRoomIcon } from '../icons/RoomIcons';
|
||||
import { TaskIcon } from '../icons/TaskIcons';
|
||||
import { getHealthColor } from '../../utils/health';
|
||||
import { useTranslation } from '../../hooks/useTranslation';
|
||||
|
||||
/* ── Types ── */
|
||||
|
||||
interface Room {
|
||||
id: number;
|
||||
name: string;
|
||||
roomType: string;
|
||||
color: string;
|
||||
accentColor: string;
|
||||
health: number;
|
||||
taskCount: number;
|
||||
criticalCount: number;
|
||||
}
|
||||
|
||||
interface Quest {
|
||||
id: number;
|
||||
name: string;
|
||||
translationKey?: string;
|
||||
iconKey?: string;
|
||||
health: number;
|
||||
effort: number;
|
||||
roomId: number;
|
||||
roomName: string;
|
||||
roomColor: string;
|
||||
roomAccent: string;
|
||||
lastCompletedAt: string | null;
|
||||
isSeasonal: boolean;
|
||||
frequencyDays: number;
|
||||
dueDate?: string;
|
||||
dueInDays?: number;
|
||||
}
|
||||
|
||||
interface CurrentUser {
|
||||
role?: 'admin' | 'member' | 'child';
|
||||
displayName: string;
|
||||
coins: number;
|
||||
goalCoins?: number | null;
|
||||
currentStreak: number;
|
||||
avatarColor: string;
|
||||
lastActiveDate?: string | null;
|
||||
}
|
||||
|
||||
interface ActivityEntry {
|
||||
displayName: string;
|
||||
avatarColor: string;
|
||||
avatarType?: string;
|
||||
avatarPreset?: string;
|
||||
avatarPhotoUrl?: string;
|
||||
taskName: string;
|
||||
translationKey?: string;
|
||||
roomId: number;
|
||||
roomName: string;
|
||||
completedAt: string;
|
||||
coinsEarned: number;
|
||||
}
|
||||
|
||||
interface FamilyMember {
|
||||
id: number;
|
||||
displayName: string;
|
||||
avatarColor: string;
|
||||
avatarType?: string;
|
||||
avatarPreset?: string;
|
||||
avatarPhotoUrl?: string;
|
||||
coins: number;
|
||||
currentStreak: number;
|
||||
points: number;
|
||||
}
|
||||
|
||||
interface DashboardProps {
|
||||
data: {
|
||||
houseHealth: number;
|
||||
rooms: Room[];
|
||||
todaysQuests: Quest[];
|
||||
nextTasks: Quest[];
|
||||
myGoal?: { goalCoins: number; currentCoins: number; progress: number; goalStartAt?: string | null; goalEndAt?: string | null } | null;
|
||||
childrenGoals?: Array<{ id: number; displayName: string; role: string; coins: number; currentCoins?: number; goalCoins: number | null; progress: number | null; goalStartAt?: string | null; goalEndAt?: string | null }>;
|
||||
pendingRewardRequests?: Array<{ id: number; title: string; displayName: string; costCoins: number; redeemedAt: string; status: 'requested' | 'approved' | 'rejected' }>;
|
||||
currentUser: CurrentUser;
|
||||
recentActivity: ActivityEntry[];
|
||||
};
|
||||
family: FamilyMember[];
|
||||
language?: string;
|
||||
onCompleteTask: (taskId: number) => void;
|
||||
onNavigateToRoom: (roomId: number) => void;
|
||||
onNavigateToActivity: () => void;
|
||||
onRewardRequestAction: (id: number, status: 'approved' | 'rejected') => void | Promise<void>;
|
||||
}
|
||||
|
||||
/* ── Component ── */
|
||||
|
||||
const Dashboard: React.FC<DashboardProps> = ({
|
||||
data,
|
||||
family,
|
||||
language,
|
||||
onCompleteTask,
|
||||
onNavigateToRoom,
|
||||
onNavigateToActivity,
|
||||
onRewardRequestAction,
|
||||
}) => {
|
||||
const { taskName, roomDisplayName, timeAgo, t } = useTranslation(language);
|
||||
const { houseHealth, rooms, todaysQuests, nextTasks, myGoal, childrenGoals = [], pendingRewardRequests = [], currentUser, recentActivity } = data;
|
||||
const localeMap: Record<string, string> = { en: 'en-US', fr: 'fr-FR', de: 'de-DE', es: 'es-ES' };
|
||||
const locale = localeMap[language || 'en'] || 'en-US';
|
||||
|
||||
const sortedRooms = [...rooms].sort((a, b) => a.health - b.health);
|
||||
const roomTypeById = new Map(rooms.map((r) => [r.id, r.roomType]));
|
||||
const totalTasks = rooms.reduce((s, r) => s + r.taskCount, 0);
|
||||
const totalCritical = rooms.reduce((s, r) => s + r.criticalCount, 0);
|
||||
const sortedFamily = [...family].sort((a, b) => b.points - a.points);
|
||||
const coinsSortedFamily = [...family].sort((a, b) => b.coins - a.coins);
|
||||
const todayIso = new Date().toISOString().slice(0, 10);
|
||||
const streakDoneToday = currentUser.lastActiveDate === todayIso;
|
||||
|
||||
const healthMessage =
|
||||
houseHealth >= 70
|
||||
? t('dashboard.healthGreat')
|
||||
: houseHealth >= 40
|
||||
? t('dashboard.healthMedium')
|
||||
: t('dashboard.healthLow');
|
||||
|
||||
return (
|
||||
<div
|
||||
style={{
|
||||
display: 'grid',
|
||||
gridTemplateColumns: '1fr 1fr 310px',
|
||||
gap: 20,
|
||||
animation: 'fadeIn 0.3s ease',
|
||||
}}
|
||||
>
|
||||
{/* ── Column 1 ── */}
|
||||
<div style={{ display: 'flex', flexDirection: 'column', gap: 20 }}>
|
||||
{/* House Health Card */}
|
||||
<div
|
||||
className="tq-card"
|
||||
style={{
|
||||
padding: 28,
|
||||
display: 'flex',
|
||||
alignItems: 'center',
|
||||
gap: 28,
|
||||
background: 'var(--warm-streak-bg)',
|
||||
}}
|
||||
>
|
||||
<RingGauge value={houseHealth} size={130} strokeWidth={11} />
|
||||
<div style={{ flex: 1 }}>
|
||||
<div
|
||||
style={{
|
||||
fontSize: 11,
|
||||
fontWeight: 800,
|
||||
color: 'var(--warm-text-light)',
|
||||
letterSpacing: 1.5,
|
||||
textTransform: 'uppercase',
|
||||
marginBottom: 6,
|
||||
}}
|
||||
>
|
||||
{t('dashboard.houseHealth')}
|
||||
</div>
|
||||
<div
|
||||
style={{
|
||||
fontSize: 14,
|
||||
fontWeight: 600,
|
||||
color: 'var(--warm-text-secondary)',
|
||||
marginBottom: 14,
|
||||
lineHeight: 1.4,
|
||||
}}
|
||||
>
|
||||
{healthMessage}
|
||||
</div>
|
||||
<div style={{ display: 'flex', gap: 8 }}>
|
||||
{[
|
||||
{ label: t('dashboard.roomsCount'), value: rooms.length, color: 'var(--warm-accent)' },
|
||||
{ label: t('dashboard.tasksCount'), value: totalTasks, color: '#4AABDE' },
|
||||
{ label: t('dashboard.criticalCount'), value: totalCritical, color: 'var(--warm-badge-text)' },
|
||||
].map((s) => (
|
||||
<div
|
||||
key={s.label}
|
||||
style={{
|
||||
flex: 1,
|
||||
backgroundColor: 'var(--warm-card)',
|
||||
borderRadius: 14,
|
||||
padding: '10px 8px',
|
||||
textAlign: 'center',
|
||||
border: '1.5px solid var(--warm-border)',
|
||||
}}
|
||||
>
|
||||
<div style={{ fontSize: 22, fontWeight: 900, color: s.color }}>
|
||||
{s.value}
|
||||
</div>
|
||||
<div style={{ fontSize: 10, color: 'var(--warm-text-light)', fontWeight: 700 }}>
|
||||
{s.label}
|
||||
</div>
|
||||
</div>
|
||||
))}
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
{/* Today's Quests Card */}
|
||||
<div className="tq-card" style={{ padding: 20, flex: 1 }}>
|
||||
<div
|
||||
style={{
|
||||
display: 'flex',
|
||||
alignItems: 'center',
|
||||
justifyContent: 'space-between',
|
||||
marginBottom: 16,
|
||||
}}
|
||||
>
|
||||
<h3 style={{ fontSize: 16, fontWeight: 800, color: 'var(--warm-text)', margin: 0 }}>
|
||||
{t('dashboard.todaysQuests')}
|
||||
</h3>
|
||||
<span
|
||||
style={{
|
||||
fontSize: 11,
|
||||
fontWeight: 800,
|
||||
backgroundColor: 'var(--warm-badge-bg)',
|
||||
color: 'var(--warm-badge-text)',
|
||||
padding: '4px 12px',
|
||||
borderRadius: 99,
|
||||
}}
|
||||
>
|
||||
{todaysQuests.length} {t('dashboard.pending')}
|
||||
</span>
|
||||
</div>
|
||||
<div style={{ display: 'flex', flexDirection: 'column', gap: 8 }}>
|
||||
{todaysQuests.slice(0, 6).map((q) => {
|
||||
return (
|
||||
<div
|
||||
key={q.id}
|
||||
style={{
|
||||
display: 'flex',
|
||||
alignItems: 'center',
|
||||
gap: 12,
|
||||
padding: '12px 14px',
|
||||
borderRadius: 16,
|
||||
backgroundColor: 'var(--warm-bg-subtle)',
|
||||
border: '1.5px solid var(--warm-border)',
|
||||
transition: 'all 0.3s ease',
|
||||
}}
|
||||
>
|
||||
<div
|
||||
style={{
|
||||
width: 40,
|
||||
height: 40,
|
||||
borderRadius: 14,
|
||||
backgroundColor: q.roomColor,
|
||||
display: 'flex',
|
||||
alignItems: 'center',
|
||||
justifyContent: 'center',
|
||||
flexShrink: 0,
|
||||
border: `1.5px solid ${q.roomAccent}44`,
|
||||
}}
|
||||
>
|
||||
<TaskIcon iconKey={q.iconKey} size={24} />
|
||||
</div>
|
||||
<div style={{ flex: 1, minWidth: 0 }}>
|
||||
<div style={{ fontSize: 13, fontWeight: 700, color: 'var(--warm-text)' }}>
|
||||
{taskName(q.name, q.translationKey)}
|
||||
</div>
|
||||
<div style={{ fontSize: 11, color: 'var(--warm-text-light)', fontWeight: 600 }}>
|
||||
{roomDisplayName(q.roomName, roomTypeById.get(q.roomId) || '')}
|
||||
{q.lastCompletedAt ? ` \u00B7 ${timeAgo(q.lastCompletedAt)}` : ''}
|
||||
</div>
|
||||
<div style={{ marginTop: 5 }}>
|
||||
<HealthBar value={q.health} height={6} showLabel={false} />
|
||||
</div>
|
||||
</div>
|
||||
<button
|
||||
onClick={() => onCompleteTask(q.id)}
|
||||
className="tq-btn tq-btn-primary"
|
||||
style={{
|
||||
padding: '8px 14px',
|
||||
backgroundColor: 'var(--warm-accent)',
|
||||
color: '#fff',
|
||||
fontSize: 12,
|
||||
boxShadow: '0 4px 14px var(--warm-primary-shadow)',
|
||||
}}
|
||||
>
|
||||
<CheckIcon /> {t('roomDetail.done')}
|
||||
</button>
|
||||
</div>
|
||||
);
|
||||
})}
|
||||
{todaysQuests.length === 0 && (
|
||||
<div style={{ fontSize: 12, color: 'var(--warm-text-light)', fontWeight: 700, padding: '8px 4px' }}>
|
||||
{t('dashboard.noQuests')}
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
</div>
|
||||
|
||||
{/* Next Tasks Card */}
|
||||
<div className="tq-card" style={{ padding: 20 }}>
|
||||
<h3 style={{ fontSize: 16, fontWeight: 800, color: 'var(--warm-text)', margin: '0 0 12px' }}>
|
||||
{t('dashboard.nextTasks')}
|
||||
</h3>
|
||||
<div style={{ display: 'flex', flexDirection: 'column', gap: 8 }}>
|
||||
{nextTasks.slice(0, 6).map((q) => {
|
||||
return (
|
||||
<div key={q.id} style={{
|
||||
display: 'flex', alignItems: 'center', gap: 10, padding: '10px 12px',
|
||||
borderRadius: 14, backgroundColor: 'var(--warm-bg-subtle)', border: '1.5px solid var(--warm-border)',
|
||||
}}>
|
||||
<div style={{
|
||||
width: 34, height: 34, borderRadius: 12, backgroundColor: q.roomColor,
|
||||
display: 'flex', alignItems: 'center', justifyContent: 'center', flexShrink: 0,
|
||||
border: `1.5px solid ${q.roomAccent}44`,
|
||||
}}><TaskIcon iconKey={q.iconKey} size={20} /></div>
|
||||
<div style={{ flex: 1 }}>
|
||||
<div style={{ fontSize: 12, fontWeight: 700, color: 'var(--warm-text)' }}>{taskName(q.name, q.translationKey)}</div>
|
||||
<div style={{ fontSize: 10, color: 'var(--warm-text-light)', fontWeight: 600 }}>
|
||||
{roomDisplayName(q.roomName, roomTypeById.get(q.roomId) || '')}
|
||||
</div>
|
||||
</div>
|
||||
<div style={{ fontSize: 11, fontWeight: 800, color: 'var(--warm-streak-subtext)', backgroundColor: 'var(--warm-accent-light)', border: '1px solid var(--warm-streak-border)', borderRadius: 999, padding: '3px 8px' }}>
|
||||
{t('calendar.inDays').replace('{days}', `${q.dueInDays || 0}`)}
|
||||
</div>
|
||||
</div>
|
||||
);
|
||||
})}
|
||||
{nextTasks.length === 0 && (
|
||||
<div style={{ fontSize: 12, color: 'var(--warm-text-light)', fontWeight: 700, padding: '8px 4px' }}>
|
||||
{t('calendar.allCaughtUp')}
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
{/* ── Column 2: Rooms ── */}
|
||||
<div className="tq-card" style={{ padding: 20 }}>
|
||||
<div
|
||||
style={{
|
||||
display: 'flex',
|
||||
alignItems: 'center',
|
||||
justifyContent: 'space-between',
|
||||
marginBottom: 16,
|
||||
}}
|
||||
>
|
||||
<h3 style={{ fontSize: 16, fontWeight: 800, color: 'var(--warm-text)', margin: 0 }}>
|
||||
{t('nav.rooms')}
|
||||
</h3>
|
||||
<span style={{ fontSize: 11, color: 'var(--warm-text-light)', fontWeight: 700 }}>
|
||||
{t('dashboard.sortedUrgency')}
|
||||
</span>
|
||||
</div>
|
||||
<div style={{ display: 'flex', flexDirection: 'column', gap: 10 }}>
|
||||
{sortedRooms.map((room) => {
|
||||
const RoomIcon = getRoomIcon(room.roomType || room.name);
|
||||
return (
|
||||
<div
|
||||
key={room.id}
|
||||
className="tq-card tq-card-hover"
|
||||
style={{ cursor: 'pointer' }}
|
||||
onClick={() => onNavigateToRoom(room.id)}
|
||||
>
|
||||
<div style={{ padding: '16px 18px' }}>
|
||||
<div
|
||||
style={{
|
||||
display: 'flex',
|
||||
alignItems: 'center',
|
||||
gap: 12,
|
||||
marginBottom: 10,
|
||||
}}
|
||||
>
|
||||
<div
|
||||
style={{
|
||||
width: 48,
|
||||
height: 48,
|
||||
borderRadius: 16,
|
||||
backgroundColor: room.color,
|
||||
display: 'flex',
|
||||
alignItems: 'center',
|
||||
justifyContent: 'center',
|
||||
border: `1.5px solid ${room.accentColor}33`,
|
||||
}}
|
||||
>
|
||||
<RoomIcon />
|
||||
</div>
|
||||
<div style={{ flex: 1 }}>
|
||||
<div style={{ fontSize: 15, fontWeight: 800, color: 'var(--warm-text)' }}>
|
||||
{roomDisplayName(room.name, room.roomType)}
|
||||
</div>
|
||||
<div style={{ fontSize: 11, color: 'var(--warm-text-light)', fontWeight: 600 }}>
|
||||
{room.taskCount} {t('rooms.tasks')}
|
||||
{room.criticalCount > 0 && (
|
||||
<span style={{ color: 'var(--warm-badge-text)', fontWeight: 800 }}>
|
||||
{' '}
|
||||
· {room.criticalCount} {t('dashboard.criticalCount')}
|
||||
</span>
|
||||
)}
|
||||
</div>
|
||||
</div>
|
||||
<div
|
||||
style={{
|
||||
fontSize: 20,
|
||||
fontWeight: 900,
|
||||
color: getHealthColor(room.health),
|
||||
}}
|
||||
>
|
||||
{room.health}%
|
||||
</div>
|
||||
</div>
|
||||
<HealthBar value={room.health} height={8} showLabel={false} />
|
||||
</div>
|
||||
</div>
|
||||
);
|
||||
})}
|
||||
</div>
|
||||
</div>
|
||||
|
||||
{/* ── Column 3: Widgets ── */}
|
||||
<div style={{ display: 'flex', flexDirection: 'column', gap: 20 }}>
|
||||
{/* Streak Card */}
|
||||
<div
|
||||
className="tq-card"
|
||||
style={{
|
||||
padding: 20,
|
||||
background: 'var(--warm-streak-bg)',
|
||||
borderColor: 'var(--warm-streak-border)',
|
||||
}}
|
||||
>
|
||||
<div
|
||||
style={{
|
||||
display: 'flex',
|
||||
alignItems: 'center',
|
||||
gap: 14,
|
||||
marginBottom: 14,
|
||||
}}
|
||||
>
|
||||
<div
|
||||
style={{
|
||||
width: 48,
|
||||
height: 48,
|
||||
borderRadius: 16,
|
||||
backgroundColor: 'var(--warm-card)',
|
||||
display: 'flex',
|
||||
alignItems: 'center',
|
||||
justifyContent: 'center',
|
||||
border: '1.5px solid var(--warm-streak-border)',
|
||||
}}
|
||||
>
|
||||
<FireIcon />
|
||||
</div>
|
||||
<div>
|
||||
<div
|
||||
style={{
|
||||
fontSize: 30,
|
||||
fontWeight: 900,
|
||||
color: 'var(--warm-streak-text)',
|
||||
lineHeight: 1,
|
||||
}}
|
||||
>
|
||||
{currentUser.currentStreak}
|
||||
</div>
|
||||
<div style={{ fontSize: 12, color: 'var(--warm-streak-subtext)', fontWeight: 700 }}>
|
||||
{t('dashboard.dayStreak')}
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
<div style={{ display: 'flex', gap: 4 }}>
|
||||
{Array.from({ length: 7 }, (_, i) => (
|
||||
<div
|
||||
key={i}
|
||||
style={{
|
||||
flex: 1,
|
||||
height: 7,
|
||||
borderRadius: 4,
|
||||
backgroundColor:
|
||||
i < (currentUser.currentStreak % 7 || 7)
|
||||
? 'var(--warm-accent)'
|
||||
: 'var(--warm-streak-border)',
|
||||
}}
|
||||
/>
|
||||
))}
|
||||
</div>
|
||||
<div
|
||||
style={{
|
||||
fontSize: 11,
|
||||
color: 'var(--warm-streak-subtext)',
|
||||
marginTop: 10,
|
||||
fontWeight: 600,
|
||||
}}
|
||||
>
|
||||
{streakDoneToday ? t('dashboard.streakDoneToday') : t('dashboard.keepStreak')}
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<div className="tq-card" style={{ padding: 20 }}>
|
||||
<div style={{ display: 'flex', alignItems: 'center', justifyContent: 'space-between', marginBottom: 10 }}>
|
||||
<div style={{ fontSize: 14, fontWeight: 800, color: 'var(--warm-text)' }}>{t('dashboard.coinsStatusTitle')}</div>
|
||||
<span style={{ fontSize: 10, fontWeight: 800, borderRadius: 999, padding: '3px 8px', backgroundColor: 'var(--warm-accent-light)', color: 'var(--warm-accent)', border: '1px solid var(--warm-accent)' }}>
|
||||
{coinsSortedFamily.length}
|
||||
</span>
|
||||
</div>
|
||||
<div style={{ display: 'grid', gap: 8 }}>
|
||||
{coinsSortedFamily.slice(0, 6).map((u) => (
|
||||
<div key={u.id} style={{ display: 'flex', alignItems: 'center', gap: 10 }}>
|
||||
<UserAvatar name={u.displayName} color={u.avatarColor} size={28} avatarType={u.avatarType as any} avatarPreset={u.avatarPreset} avatarPhotoUrl={u.avatarPhotoUrl} />
|
||||
<div style={{ flex: 1, fontSize: 12, fontWeight: 700, color: 'var(--warm-text)' }}>{u.displayName}</div>
|
||||
<div style={{ display: 'inline-flex', alignItems: 'center', gap: 4, fontSize: 12, fontWeight: 800, color: 'var(--warm-coin)' }}>
|
||||
{u.coins} <CoinIcon />
|
||||
</div>
|
||||
</div>
|
||||
))}
|
||||
</div>
|
||||
</div>
|
||||
|
||||
{myGoal && (
|
||||
<div className="tq-card" style={{ padding: 20 }}>
|
||||
<div style={{ fontSize: 14, fontWeight: 800, color: 'var(--warm-text)', marginBottom: 6 }}>{t('dashboard.myGoal')}</div>
|
||||
<div style={{ fontSize: 12, color: 'var(--warm-text-muted)', fontWeight: 700, marginBottom: 8 }}>
|
||||
{myGoal.currentCoins}/{myGoal.goalCoins} {t('leaderboard.points')}
|
||||
</div>
|
||||
{(myGoal.goalStartAt || myGoal.goalEndAt) && (
|
||||
<div style={{ fontSize: 10, color: 'var(--warm-text-light)', fontWeight: 700, marginBottom: 8 }}>
|
||||
{(myGoal.goalStartAt ? new Date(myGoal.goalStartAt).toLocaleDateString(locale) : '...')} - {(myGoal.goalEndAt ? new Date(myGoal.goalEndAt).toLocaleDateString(locale) : '...')}
|
||||
</div>
|
||||
)}
|
||||
<HealthBar value={myGoal.progress} height={8} showLabel={false} />
|
||||
</div>
|
||||
)}
|
||||
|
||||
{currentUser.role === 'admin' && childrenGoals.length > 0 && (
|
||||
<div className="tq-card" style={{ padding: 20 }}>
|
||||
<div style={{ fontSize: 14, fontWeight: 800, color: 'var(--warm-text)', marginBottom: 8 }}>{t('dashboard.childrenGoals')}</div>
|
||||
<div style={{ display: 'grid', gap: 8 }}>
|
||||
{childrenGoals.map((cg) => (
|
||||
<div key={cg.id} style={{ padding: '8px 0', borderBottom: '1px solid var(--warm-border)' }}>
|
||||
<div style={{ display: 'flex', justifyContent: 'space-between', fontSize: 12, fontWeight: 700, color: 'var(--warm-text-secondary)' }}>
|
||||
<span>{cg.displayName}</span>
|
||||
<span>{cg.goalCoins ? `${cg.currentCoins ?? cg.coins}/${cg.goalCoins}` : t('dashboard.noGoal')}</span>
|
||||
</div>
|
||||
{(cg.goalStartAt || cg.goalEndAt) && (
|
||||
<div style={{ fontSize: 10, color: 'var(--warm-text-light)', fontWeight: 700, marginTop: 2 }}>
|
||||
{(cg.goalStartAt ? new Date(cg.goalStartAt).toLocaleDateString(locale) : '...')} - {(cg.goalEndAt ? new Date(cg.goalEndAt).toLocaleDateString(locale) : '...')}
|
||||
</div>
|
||||
)}
|
||||
{cg.goalCoins && <HealthBar value={cg.progress || 0} height={6} showLabel={false} />}
|
||||
</div>
|
||||
))}
|
||||
</div>
|
||||
</div>
|
||||
)}
|
||||
|
||||
{currentUser.role === 'admin' && (
|
||||
<div className="tq-card" style={{ padding: 20 }}>
|
||||
<div style={{ display: 'flex', alignItems: 'center', justifyContent: 'space-between', marginBottom: 8 }}>
|
||||
<div style={{ fontSize: 14, fontWeight: 800, color: 'var(--warm-text)' }}>{t('dashboard.rewardRequestsTitle')}</div>
|
||||
<span style={{ fontSize: 10, fontWeight: 800, borderRadius: 999, padding: '3px 8px', backgroundColor: 'var(--warm-accent-light)', color: 'var(--warm-accent)', border: '1px solid var(--warm-accent)' }}>
|
||||
{pendingRewardRequests.length}
|
||||
</span>
|
||||
</div>
|
||||
{pendingRewardRequests.length === 0 && (
|
||||
<div style={{ fontSize: 11, color: 'var(--warm-text-light)', fontWeight: 700 }}>
|
||||
{t('dashboard.rewardRequestEmpty')}
|
||||
</div>
|
||||
)}
|
||||
<div style={{ display: 'grid', gap: 8 }}>
|
||||
{pendingRewardRequests.slice(0, 6).map((rr) => (
|
||||
<div key={rr.id} style={{ border: '1px solid var(--warm-border)', backgroundColor: 'var(--warm-bg-subtle)', borderRadius: 12, padding: '8px 10px' }}>
|
||||
<div style={{ fontSize: 12, fontWeight: 800, color: 'var(--warm-text)' }}>{rr.displayName}</div>
|
||||
<div style={{ fontSize: 11, color: 'var(--warm-text-light)', fontWeight: 700 }}>{rr.title}</div>
|
||||
<div style={{ display: 'flex', alignItems: 'center', justifyContent: 'space-between', marginTop: 6 }}>
|
||||
<div style={{ fontSize: 10, color: 'var(--warm-text-light)', fontWeight: 700 }}>
|
||||
{timeAgo(rr.redeemedAt)}
|
||||
</div>
|
||||
<div style={{ display: 'flex', gap: 4, alignItems: 'center' }}>
|
||||
<span style={{ display: 'inline-flex', alignItems: 'center', gap: 3, fontSize: 11, fontWeight: 800, color: 'var(--warm-accent)' }}>
|
||||
<CoinIcon /> {rr.costCoins}
|
||||
</span>
|
||||
<button className="tq-btn tq-btn-secondary" onClick={() => onRewardRequestAction(rr.id, 'approved')} style={{ padding: '4px 7px', fontSize: 10 }}>
|
||||
{t('dashboard.approve')}
|
||||
</button>
|
||||
<button className="tq-btn" onClick={() => onRewardRequestAction(rr.id, 'rejected')} style={{ padding: '4px 7px', fontSize: 10, backgroundColor: 'var(--warm-danger-bg)', color: 'var(--warm-danger)', border: '1.5px solid var(--warm-danger-border)' }}>
|
||||
{t('dashboard.reject')}
|
||||
</button>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
))}
|
||||
</div>
|
||||
</div>
|
||||
)}
|
||||
|
||||
{/* Mini Leaderboard */}
|
||||
<div className="tq-card" style={{ padding: 20 }}>
|
||||
<h3
|
||||
style={{
|
||||
fontSize: 14,
|
||||
fontWeight: 800,
|
||||
color: 'var(--warm-text)',
|
||||
margin: '0 0 12px',
|
||||
}}
|
||||
>
|
||||
{t('leaderboard.thisWeek')}
|
||||
</h3>
|
||||
{sortedFamily.map((u, i) => (
|
||||
<div
|
||||
key={u.id}
|
||||
style={{
|
||||
display: 'flex',
|
||||
alignItems: 'center',
|
||||
gap: 10,
|
||||
padding: '9px 0',
|
||||
borderBottom:
|
||||
i < sortedFamily.length - 1 ? '1px solid var(--warm-border)' : 'none',
|
||||
}}
|
||||
>
|
||||
<div
|
||||
style={{
|
||||
width: 28,
|
||||
height: 28,
|
||||
borderRadius: 9,
|
||||
backgroundColor: i === 0 ? 'var(--warm-accent-light)' : 'var(--warm-bg-subtle)',
|
||||
display: 'flex',
|
||||
alignItems: 'center',
|
||||
justifyContent: 'center',
|
||||
fontSize: 11,
|
||||
fontWeight: 900,
|
||||
color: i === 0 ? 'var(--warm-accent)' : 'var(--warm-text-light)',
|
||||
border: i === 0 ? '1.5px solid var(--warm-accent)' : '1px solid var(--warm-border)',
|
||||
}}
|
||||
>
|
||||
#{i + 1}
|
||||
</div>
|
||||
<UserAvatar name={u.displayName} color={u.avatarColor} size={32} avatarType={u.avatarType as any} avatarPreset={u.avatarPreset} avatarPhotoUrl={u.avatarPhotoUrl} />
|
||||
<div
|
||||
style={{
|
||||
flex: 1,
|
||||
fontSize: 13,
|
||||
fontWeight: 700,
|
||||
color: 'var(--warm-text)',
|
||||
}}
|
||||
>
|
||||
{u.displayName}
|
||||
</div>
|
||||
<div style={{ fontSize: 14, fontWeight: 900, color: 'var(--warm-accent)' }}>
|
||||
{u.points}
|
||||
</div>
|
||||
</div>
|
||||
))}
|
||||
</div>
|
||||
|
||||
{/* Recent Activity */}
|
||||
<div className="tq-card" style={{ padding: 20 }}>
|
||||
<div style={{ display: 'flex', alignItems: 'center', justifyContent: 'space-between', marginBottom: 12 }}>
|
||||
<h3
|
||||
style={{
|
||||
fontSize: 14,
|
||||
fontWeight: 800,
|
||||
color: 'var(--warm-text)',
|
||||
margin: 0,
|
||||
}}
|
||||
>
|
||||
{t('dashboard.recentActivity')}
|
||||
</h3>
|
||||
<button
|
||||
className="tq-btn tq-btn-secondary"
|
||||
onClick={onNavigateToActivity}
|
||||
style={{ padding: '6px 12px', fontSize: 11 }}
|
||||
>
|
||||
{t('dashboard.more')}
|
||||
</button>
|
||||
</div>
|
||||
{recentActivity.slice(0, 5).map((h, i) => (
|
||||
<div
|
||||
key={i}
|
||||
style={{
|
||||
display: 'flex',
|
||||
alignItems: 'center',
|
||||
gap: 10,
|
||||
padding: '7px 0',
|
||||
borderBottom: i < 4 ? '1px solid var(--warm-border-subtle)' : 'none',
|
||||
}}
|
||||
>
|
||||
<UserAvatar name={h.displayName} color={h.avatarColor} size={28} avatarType={h.avatarType as any} avatarPreset={h.avatarPreset} avatarPhotoUrl={h.avatarPhotoUrl} />
|
||||
<div style={{ flex: 1 }}>
|
||||
<div style={{ fontSize: 12, fontWeight: 700, color: 'var(--warm-text)' }}>
|
||||
{taskName(h.taskName, h.translationKey)}
|
||||
</div>
|
||||
<div style={{ fontSize: 10, color: 'var(--warm-text-light)', fontWeight: 600 }}>
|
||||
{t('history.by')} {h.displayName}
|
||||
</div>
|
||||
<div style={{ fontSize: 10, color: 'var(--warm-text-light)', fontWeight: 600 }}>
|
||||
{roomDisplayName(h.roomName, roomTypeById.get(h.roomId) || '')} · {timeAgo(h.completedAt)}
|
||||
</div>
|
||||
</div>
|
||||
<div
|
||||
style={{
|
||||
display: 'flex',
|
||||
alignItems: 'center',
|
||||
gap: 3,
|
||||
fontSize: 11,
|
||||
fontWeight: 800,
|
||||
color: 'var(--warm-coin)',
|
||||
}}
|
||||
>
|
||||
+{h.coinsEarned} <CoinIcon />
|
||||
</div>
|
||||
</div>
|
||||
))}
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
);
|
||||
};
|
||||
|
||||
export default Dashboard;
|
||||
81
client/src/components/pages/History.tsx
Normal file
81
client/src/components/pages/History.tsx
Normal file
|
|
@ -0,0 +1,81 @@
|
|||
import { useState, useEffect } from 'react';
|
||||
import { UserAvatar } from '../shared/UserAvatar';
|
||||
import { CoinIcon } from '../icons/UIIcons';
|
||||
import { api } from '../../hooks/useApi';
|
||||
import { useTranslation } from '../../hooks/useTranslation';
|
||||
|
||||
export function History({ language }: { language?: string }) {
|
||||
const { taskName, t, roomDisplayName, timeAgo } = useTranslation(language);
|
||||
const [history, setHistory] = useState<any[]>([]);
|
||||
const [total, setTotal] = useState(0);
|
||||
const [offset, setOffset] = useState(0);
|
||||
const limit = 20;
|
||||
|
||||
useEffect(() => {
|
||||
api.history(limit, offset).then((data) => {
|
||||
setHistory(data.history);
|
||||
setTotal(data.total);
|
||||
});
|
||||
}, [offset]);
|
||||
|
||||
return (
|
||||
<div className="page-enter" style={{ maxWidth: 750 }}>
|
||||
<div className="tq-card" style={{ padding: 22 }}>
|
||||
<div style={{
|
||||
display: 'grid', gridTemplateColumns: '44px 1fr 120px 100px 80px',
|
||||
gap: 12, padding: '0 8px 14px', borderBottom: '1.5px solid #F0E6D9',
|
||||
fontSize: 11, fontWeight: 800, color: '#B0A090', textTransform: 'uppercase', letterSpacing: 1,
|
||||
}}>
|
||||
<div></div>
|
||||
<div>{t('history.task')}</div>
|
||||
<div>{t('history.room')}</div>
|
||||
<div>{t('history.when')}</div>
|
||||
<div style={{ textAlign: 'right' }}>{t('history.earned')}</div>
|
||||
</div>
|
||||
|
||||
{history.map((h) => (
|
||||
<div key={h.id} style={{
|
||||
display: 'grid', gridTemplateColumns: '44px 1fr 120px 100px 80px',
|
||||
gap: 12, padding: '14px 8px', alignItems: 'center',
|
||||
borderBottom: '1px solid #F5EDE3',
|
||||
}}>
|
||||
<UserAvatar name={h.displayName} color={h.avatarColor} size={34} avatarType={h.avatarType} avatarPreset={h.avatarPreset} avatarPhotoUrl={h.avatarPhotoUrl} />
|
||||
<div>
|
||||
<div style={{ fontSize: 14, fontWeight: 700, color: '#3D2F1E' }}>{taskName(h.taskName, h.translationKey)}</div>
|
||||
<div style={{ fontSize: 11, color: '#B0A090', fontWeight: 600 }}>{t('history.by')} {h.displayName}</div>
|
||||
</div>
|
||||
<div style={{ fontSize: 13, color: '#6B5B4A', fontWeight: 600 }}>{roomDisplayName(h.roomName, h.roomType || '')}</div>
|
||||
<div style={{ fontSize: 12, color: '#B0A090', fontWeight: 600 }}>{timeAgo(h.completedAt)}</div>
|
||||
<div style={{ display: 'flex', alignItems: 'center', gap: 4, justifyContent: 'flex-end', fontSize: 13, fontWeight: 800, color: '#F59E0B' }}>
|
||||
+{h.coinsEarned} <CoinIcon />
|
||||
</div>
|
||||
</div>
|
||||
))}
|
||||
|
||||
{history.length === 0 && (
|
||||
<div style={{ padding: 40, textAlign: 'center', color: '#B0A090', fontWeight: 600, fontSize: 14 }}>
|
||||
{t('history.noActivity')}
|
||||
</div>
|
||||
)}
|
||||
|
||||
{total > limit && (
|
||||
<div style={{ display: 'flex', justifyContent: 'center', gap: 10, padding: '18px 0 4px' }}>
|
||||
<button className="tq-btn tq-btn-secondary" disabled={offset === 0}
|
||||
onClick={() => setOffset(Math.max(0, offset - limit))}
|
||||
style={{ padding: '8px 18px', fontSize: 12, opacity: offset === 0 ? 0.4 : 1 }}>
|
||||
{t('history.previous')}
|
||||
</button>
|
||||
<span style={{ fontSize: 12, color: '#B0A090', fontWeight: 600, padding: '8px 0' }}>
|
||||
{offset + 1}-{Math.min(offset + limit, total)} {t('history.of')} {total}
|
||||
</span>
|
||||
<button className="tq-btn tq-btn-secondary" disabled={offset + limit >= total}
|
||||
onClick={() => setOffset(offset + limit)}
|
||||
style={{ padding: '8px 18px', fontSize: 12, opacity: offset + limit >= total ? 0.4 : 1 }}>
|
||||
{t('history.next')}
|
||||
</button>
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
111
client/src/components/pages/Leaderboard.tsx
Normal file
111
client/src/components/pages/Leaderboard.tsx
Normal file
|
|
@ -0,0 +1,111 @@
|
|||
import { UserAvatar } from '../shared/UserAvatar';
|
||||
import { FireIcon, CoinIcon } from '../icons/UIIcons';
|
||||
import { useTranslation } from '../../hooks/useTranslation';
|
||||
|
||||
interface LeaderboardProps {
|
||||
users: Array<{ id: number; displayName: string; avatarColor: string; avatarType?: string; avatarPreset?: string; avatarPhotoUrl?: string; coins: number; currentStreak: number; points: number }>;
|
||||
period: 'week' | 'month' | 'quarter' | 'year';
|
||||
language?: string;
|
||||
onPeriodChange: (period: 'week' | 'month' | 'quarter' | 'year') => void;
|
||||
}
|
||||
|
||||
export function Leaderboard({ users, period, language, onPeriodChange }: LeaderboardProps) {
|
||||
const { t } = useTranslation(language);
|
||||
const sorted = [...users].sort((a, b) => b.points - a.points);
|
||||
|
||||
// Podium order: 2nd, 1st, 3rd
|
||||
const podium = [sorted[1], sorted[0], sorted[2]].filter(Boolean);
|
||||
const podiumHeights = [100, 140, 75];
|
||||
const podiumRanks = [2, 1, 3];
|
||||
const podiumGradients = [
|
||||
'linear-gradient(180deg, #E2E8F0, #94A3B8)',
|
||||
'linear-gradient(180deg, #FDE68A, #F59E0B)',
|
||||
'linear-gradient(180deg, #FED7AA, #EA580C)',
|
||||
];
|
||||
|
||||
return (
|
||||
<div className="page-enter" style={{ maxWidth: 700 }}>
|
||||
{/* Period Toggle */}
|
||||
<div style={{
|
||||
display: 'flex', gap: 4, backgroundColor: 'var(--warm-accent-light)', borderRadius: 14,
|
||||
padding: 4, marginBottom: 24, width: 'fit-content', border: '1.5px solid var(--warm-border)',
|
||||
}}>
|
||||
{(['week', 'month', 'quarter', 'year'] as const).map((p) => (
|
||||
<button key={p} onClick={() => onPeriodChange(p)}
|
||||
className="tq-btn"
|
||||
style={{
|
||||
padding: '9px 22px', borderRadius: 11,
|
||||
backgroundColor: period === p ? 'var(--warm-accent)' : 'transparent',
|
||||
fontSize: 13, fontWeight: 800,
|
||||
color: period === p ? '#fff' : 'var(--warm-text-light)',
|
||||
}}>
|
||||
{p === 'week'
|
||||
? t('leaderboard.thisWeek')
|
||||
: p === 'month'
|
||||
? t('leaderboard.thisMonth')
|
||||
: p === 'quarter'
|
||||
? t('leaderboard.thisQuarter')
|
||||
: t('leaderboard.thisYear')}
|
||||
</button>
|
||||
))}
|
||||
</div>
|
||||
|
||||
{/* Podium */}
|
||||
{podium.length > 0 && (
|
||||
<div className="tq-card" style={{ padding: 32, marginBottom: 20, background: 'var(--warm-streak-bg)' }}>
|
||||
<div style={{ display: 'flex', justifyContent: 'center', alignItems: 'flex-end', gap: 24, marginBottom: 8 }}>
|
||||
{podium.map((u, i) => (
|
||||
<div key={u.id} style={{ display: 'flex', flexDirection: 'column', alignItems: 'center', flex: 1, maxWidth: 150 }}>
|
||||
<UserAvatar name={u.displayName} color={u.avatarColor} size={52} avatarType={u.avatarType as any} avatarPreset={u.avatarPreset} avatarPhotoUrl={u.avatarPhotoUrl} />
|
||||
<div style={{ fontSize: 14, fontWeight: 800, color: 'var(--warm-text)', marginTop: 6, marginBottom: 6 }}>{u.displayName}</div>
|
||||
<div style={{
|
||||
width: '100%', height: podiumHeights[i], borderRadius: '18px 18px 0 0',
|
||||
background: podiumGradients[i],
|
||||
display: 'flex', flexDirection: 'column', alignItems: 'center', justifyContent: 'center',
|
||||
}}>
|
||||
<div style={{ fontSize: 12, fontWeight: 900, color: '#fff', opacity: 0.8 }}>#{podiumRanks[i]}</div>
|
||||
<div style={{ fontSize: 24, fontWeight: 900, color: '#fff' }}>{u.points}</div>
|
||||
<div style={{ fontSize: 10, color: '#ffffff99', fontWeight: 700 }}>{t('leaderboard.points')}</div>
|
||||
</div>
|
||||
</div>
|
||||
))}
|
||||
</div>
|
||||
</div>
|
||||
)}
|
||||
|
||||
{/* Stats List */}
|
||||
{sorted.map((u, i) => (
|
||||
<div key={u.id} className="tq-card" style={{
|
||||
display: 'flex', alignItems: 'center', gap: 16, padding: '16px 22px', marginBottom: 10,
|
||||
}}>
|
||||
<div style={{
|
||||
width: 32, height: 32, borderRadius: 10,
|
||||
backgroundColor: i === 0 ? 'var(--warm-accent-light)' : 'var(--warm-bg-subtle)',
|
||||
display: 'flex', alignItems: 'center', justifyContent: 'center',
|
||||
fontSize: 13, fontWeight: 900, color: i === 0 ? 'var(--warm-accent)' : 'var(--warm-text-light)',
|
||||
border: i === 0 ? '1.5px solid var(--warm-accent)' : '1px solid var(--warm-border)',
|
||||
}}>#{i + 1}</div>
|
||||
<UserAvatar name={u.displayName} color={u.avatarColor} size={44} avatarType={u.avatarType as any} avatarPreset={u.avatarPreset} avatarPhotoUrl={u.avatarPhotoUrl} />
|
||||
<div style={{ flex: 1 }}>
|
||||
<div style={{ fontSize: 16, fontWeight: 800, color: 'var(--warm-text)' }}>{u.displayName}</div>
|
||||
<div style={{ display: 'flex', alignItems: 'center', gap: 10, marginTop: 2 }}>
|
||||
<span style={{ display: 'flex', alignItems: 'center', gap: 3, fontSize: 12, color: 'var(--warm-text-light)', fontWeight: 600 }}>
|
||||
<FireIcon /> {u.currentStreak}d {t('leaderboard.streak')}
|
||||
</span>
|
||||
<span style={{ display: 'flex', alignItems: 'center', gap: 3, fontSize: 12, color: 'var(--warm-text-light)', fontWeight: 600 }}>
|
||||
<CoinIcon /> {u.coins}
|
||||
</span>
|
||||
</div>
|
||||
</div>
|
||||
<div style={{ fontSize: 24, fontWeight: 900, color: 'var(--warm-accent)' }}>{u.points}</div>
|
||||
</div>
|
||||
))}
|
||||
|
||||
{sorted.length === 0 && (
|
||||
<div className="tq-card" style={{ padding: 40, textAlign: 'center', color: 'var(--warm-text-light)', fontWeight: 600 }}>
|
||||
{t('leaderboard.noData')}
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
);
|
||||
}
|
||||
119
client/src/components/pages/Login.tsx
Normal file
119
client/src/components/pages/Login.tsx
Normal file
|
|
@ -0,0 +1,119 @@
|
|||
import { useState } from 'react';
|
||||
import { SparkleIcon } from '../icons/UIIcons';
|
||||
import { useTranslation } from '../../hooks/useTranslation';
|
||||
|
||||
interface LoginProps {
|
||||
onLogin: (username: string, password: string) => Promise<void>;
|
||||
onSwitchToRegister: () => void;
|
||||
}
|
||||
|
||||
export function Login({ onLogin, onSwitchToRegister }: LoginProps) {
|
||||
const initialLang = (() => {
|
||||
const saved = typeof localStorage !== 'undefined' ? localStorage.getItem('tidyquest_auth_lang') : null;
|
||||
if (saved && ['en', 'fr', 'de', 'es'].includes(saved)) return saved;
|
||||
const browser = typeof navigator !== 'undefined' ? navigator.language.slice(0, 2) : 'en';
|
||||
return ['en', 'fr', 'de', 'es'].includes(browser) ? browser : 'en';
|
||||
})();
|
||||
const [authLanguage, setAuthLanguage] = useState(initialLang);
|
||||
const { t } = useTranslation(authLanguage);
|
||||
const [username, setUsername] = useState('');
|
||||
const [password, setPassword] = useState('');
|
||||
const [error, setError] = useState('');
|
||||
const [loading, setLoading] = useState(false);
|
||||
|
||||
const handleSubmit = async (e: React.FormEvent) => {
|
||||
e.preventDefault();
|
||||
setError('');
|
||||
setLoading(true);
|
||||
try {
|
||||
await onLogin(username.trim(), password);
|
||||
window.location.href = '/';
|
||||
} catch (err: any) {
|
||||
setError(err.message || t('auth.loginFailed'));
|
||||
} finally {
|
||||
setLoading(false);
|
||||
}
|
||||
};
|
||||
|
||||
return (
|
||||
<div style={{
|
||||
minHeight: '100vh', display: 'flex', alignItems: 'center', justifyContent: 'center',
|
||||
backgroundColor: '#FFF9F2',
|
||||
}}>
|
||||
<div className="tq-card" style={{ padding: 40, width: 380 }}>
|
||||
<div style={{ textAlign: 'center', marginBottom: 28 }}>
|
||||
<div style={{
|
||||
width: 56, height: 56, borderRadius: 18, margin: '0 auto 14px',
|
||||
background: 'linear-gradient(135deg, #FFF7ED, #FFEDD5)',
|
||||
border: '1.5px solid #FDBA74',
|
||||
display: 'flex', alignItems: 'center', justifyContent: 'center',
|
||||
}}>
|
||||
<SparkleIcon />
|
||||
</div>
|
||||
<h1 style={{ fontSize: 24, fontWeight: 900, color: '#3D2F1E', margin: 0 }}>TidyQuest</h1>
|
||||
<p style={{ fontSize: 12, color: '#B0A090', fontWeight: 600, marginTop: 4 }}>{t('auth.welcomeBack')}</p>
|
||||
<select
|
||||
value={authLanguage}
|
||||
onChange={(e) => {
|
||||
const v = e.target.value;
|
||||
setAuthLanguage(v);
|
||||
localStorage.setItem('tidyquest_auth_lang', v);
|
||||
}}
|
||||
style={{
|
||||
marginTop: 10, padding: '6px 10px', borderRadius: 10, border: '1.5px solid #F0E6D9',
|
||||
fontSize: 12, fontFamily: 'Nunito', fontWeight: 700, color: '#6B5B4A', backgroundColor: '#FFFBF5',
|
||||
}}
|
||||
>
|
||||
<option value="en">English</option>
|
||||
<option value="fr">Français</option>
|
||||
<option value="de">Deutsch</option>
|
||||
<option value="es">Español</option>
|
||||
</select>
|
||||
</div>
|
||||
|
||||
<form onSubmit={handleSubmit}>
|
||||
<div style={{ marginBottom: 14 }}>
|
||||
<label style={{ fontSize: 12, fontWeight: 700, color: '#8A7A6A', display: 'block', marginBottom: 6 }}>{t('auth.username')}</label>
|
||||
<input value={username} onChange={(e) => setUsername(e.target.value)}
|
||||
style={{
|
||||
width: '100%', padding: '10px 14px', borderRadius: 12, border: '1.5px solid #F0E6D9',
|
||||
fontSize: 14, fontFamily: 'Nunito', fontWeight: 600, color: '#3D2F1E',
|
||||
outline: 'none', backgroundColor: '#FFFBF5',
|
||||
}}
|
||||
placeholder={t('auth.usernamePlaceholder')}
|
||||
/>
|
||||
</div>
|
||||
<div style={{ marginBottom: 20 }}>
|
||||
<label style={{ fontSize: 12, fontWeight: 700, color: '#8A7A6A', display: 'block', marginBottom: 6 }}>{t('auth.password')}</label>
|
||||
<input type="password" value={password} onChange={(e) => setPassword(e.target.value)}
|
||||
style={{
|
||||
width: '100%', padding: '10px 14px', borderRadius: 12, border: '1.5px solid #F0E6D9',
|
||||
fontSize: 14, fontFamily: 'Nunito', fontWeight: 600, color: '#3D2F1E',
|
||||
outline: 'none', backgroundColor: '#FFFBF5',
|
||||
}}
|
||||
placeholder={t('auth.passwordPlaceholder')}
|
||||
/>
|
||||
</div>
|
||||
|
||||
{error && <div style={{ fontSize: 12, color: '#E25A5A', fontWeight: 700, marginBottom: 14, textAlign: 'center' }}>{error}</div>}
|
||||
|
||||
<button type="submit" className="tq-btn tq-btn-primary"
|
||||
disabled={loading}
|
||||
style={{ width: '100%', padding: '12px', fontSize: 15, justifyContent: 'center' }}>
|
||||
{loading ? t('auth.loggingIn') : t('auth.logIn')}
|
||||
</button>
|
||||
</form>
|
||||
|
||||
<div style={{ textAlign: 'center', marginTop: 18 }}>
|
||||
<button onClick={onSwitchToRegister}
|
||||
style={{
|
||||
background: 'none', border: 'none', color: '#F97316', fontSize: 13,
|
||||
fontWeight: 700, cursor: 'pointer', fontFamily: 'Nunito',
|
||||
}}>
|
||||
{t('auth.createAccount')}
|
||||
</button>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
277
client/src/components/pages/Profile.tsx
Normal file
277
client/src/components/pages/Profile.tsx
Normal file
|
|
@ -0,0 +1,277 @@
|
|||
import { useState, useRef } from 'react';
|
||||
import { UserAvatar } from '../shared/UserAvatar';
|
||||
import { AVATAR_PRESETS, AvatarPresetIcon } from '../icons/AvatarPresets';
|
||||
import { GlobeIcon } from '../icons/UIIcons';
|
||||
import { api } from '../../hooks/useApi';
|
||||
import { useTranslation } from '../../hooks/useTranslation';
|
||||
import type { User } from '../../hooks/useAuth';
|
||||
|
||||
const COLORS = [
|
||||
'#F97316', '#EF4444', '#EC4899', '#A855F7',
|
||||
'#6366F1', '#3B82F6', '#06B6D4', '#10B981',
|
||||
'#84CC16', '#F59E0B', '#78716C', '#64748B',
|
||||
];
|
||||
|
||||
interface ProfileProps {
|
||||
user: User;
|
||||
onSave: () => void;
|
||||
onLogout: () => void;
|
||||
}
|
||||
|
||||
export function Profile({ user, onSave, onLogout }: ProfileProps) {
|
||||
const { t } = useTranslation(user.language);
|
||||
const [displayName, setDisplayName] = useState(user.displayName);
|
||||
const [avatarType, setAvatarType] = useState<'letter' | 'preset' | 'photo'>(user.avatarType || 'letter');
|
||||
const [avatarColor, setAvatarColor] = useState(user.avatarColor);
|
||||
const [avatarPreset, setAvatarPreset] = useState(user.avatarPreset || 'cat');
|
||||
const [avatarPhotoUrl, setAvatarPhotoUrl] = useState(user.avatarPhotoUrl);
|
||||
const [language, setLanguage] = useState(user.language);
|
||||
const [saving, setSaving] = useState(false);
|
||||
const [saved, setSaved] = useState(false);
|
||||
const [currentPassword, setCurrentPassword] = useState('');
|
||||
const [newPassword, setNewPassword] = useState('');
|
||||
const [confirmPassword, setConfirmPassword] = useState('');
|
||||
const [passwordMsg, setPasswordMsg] = useState('');
|
||||
const fileRef = useRef<HTMLInputElement>(null);
|
||||
|
||||
const handleSave = async () => {
|
||||
setSaving(true);
|
||||
try {
|
||||
await api.updateProfile(user.id, {
|
||||
displayName,
|
||||
avatarType,
|
||||
avatarColor,
|
||||
avatarPreset: avatarType === 'preset' ? avatarPreset : undefined,
|
||||
language,
|
||||
});
|
||||
setSaved(true);
|
||||
onSave();
|
||||
setTimeout(() => setSaved(false), 2000);
|
||||
} finally {
|
||||
setSaving(false);
|
||||
}
|
||||
};
|
||||
|
||||
const handlePhotoUpload = async (e: React.ChangeEvent<HTMLInputElement>) => {
|
||||
const file = e.target.files?.[0];
|
||||
if (!file) return;
|
||||
setSaving(true);
|
||||
try {
|
||||
const result = await api.uploadAvatar(user.id, file);
|
||||
setAvatarType('photo');
|
||||
setAvatarPhotoUrl(result.avatarPhotoUrl);
|
||||
onSave();
|
||||
} finally {
|
||||
setSaving(false);
|
||||
}
|
||||
};
|
||||
|
||||
const handlePasswordChange = async () => {
|
||||
setPasswordMsg('');
|
||||
if (!currentPassword || !newPassword) return;
|
||||
if (newPassword !== confirmPassword) {
|
||||
setPasswordMsg(t('settings.passwordMismatch'));
|
||||
return;
|
||||
}
|
||||
setSaving(true);
|
||||
try {
|
||||
await api.updatePassword(user.id, { currentPassword, newPassword });
|
||||
setCurrentPassword('');
|
||||
setNewPassword('');
|
||||
setConfirmPassword('');
|
||||
setPasswordMsg(t('settings.passwordUpdated'));
|
||||
} catch (err: any) {
|
||||
setPasswordMsg(err?.message || t('settings.passwordUpdateFailed'));
|
||||
} finally {
|
||||
setSaving(false);
|
||||
}
|
||||
};
|
||||
|
||||
const tabs: Array<{ key: 'letter' | 'preset' | 'photo'; label: string }> = [
|
||||
{ key: 'letter', label: t('profile.letterMode') },
|
||||
{ key: 'preset', label: t('profile.characterMode') },
|
||||
{ key: 'photo', label: t('profile.photoMode') },
|
||||
];
|
||||
|
||||
return (
|
||||
<div className="page-enter" style={{ maxWidth: 520 }}>
|
||||
<div className="tq-card" style={{ padding: 32 }}>
|
||||
{/* Avatar preview */}
|
||||
<div style={{ display: 'flex', justifyContent: 'center', marginBottom: 28 }}>
|
||||
<UserAvatar
|
||||
name={displayName}
|
||||
color={avatarColor}
|
||||
size={80}
|
||||
avatarType={avatarType}
|
||||
avatarPreset={avatarPreset}
|
||||
avatarPhotoUrl={avatarPhotoUrl}
|
||||
/>
|
||||
</div>
|
||||
|
||||
{/* Display name */}
|
||||
<div style={{ marginBottom: 24 }}>
|
||||
<label style={{ fontSize: 12, fontWeight: 800, color: 'var(--warm-text-muted)', textTransform: 'uppercase', letterSpacing: 0.5, marginBottom: 6, display: 'block' }}>
|
||||
{t('profile.displayName')}
|
||||
</label>
|
||||
<input
|
||||
type="text"
|
||||
value={displayName}
|
||||
onChange={(e) => setDisplayName(e.target.value)}
|
||||
style={{
|
||||
width: '100%', padding: '10px 14px', borderRadius: 12,
|
||||
border: '1.5px solid var(--warm-border)', fontSize: 14, fontWeight: 700,
|
||||
color: 'var(--warm-text)', fontFamily: 'Nunito', backgroundColor: 'var(--warm-bg-input)',
|
||||
outline: 'none', boxSizing: 'border-box',
|
||||
}}
|
||||
/>
|
||||
</div>
|
||||
|
||||
{/* Avatar mode tabs */}
|
||||
<div style={{ marginBottom: 20 }}>
|
||||
<label style={{ fontSize: 12, fontWeight: 800, color: 'var(--warm-text-muted)', textTransform: 'uppercase', letterSpacing: 0.5, marginBottom: 8, display: 'block' }}>
|
||||
{t('profile.avatarMode')}
|
||||
</label>
|
||||
<div style={{ display: 'flex', gap: 6, marginBottom: 16 }}>
|
||||
{tabs.map((tab) => (
|
||||
<button
|
||||
key={tab.key}
|
||||
onClick={() => setAvatarType(tab.key)}
|
||||
className="tq-btn"
|
||||
style={{
|
||||
flex: 1, padding: '8px 12px', fontSize: 12, fontWeight: 700,
|
||||
backgroundColor: avatarType === tab.key ? 'var(--warm-accent)' : 'var(--warm-accent-light)',
|
||||
color: avatarType === tab.key ? '#fff' : 'var(--warm-accent)',
|
||||
border: avatarType === tab.key ? 'none' : '1.5px solid var(--warm-border)',
|
||||
}}
|
||||
>
|
||||
{tab.label}
|
||||
</button>
|
||||
))}
|
||||
</div>
|
||||
|
||||
{/* Letter mode: color picker */}
|
||||
{avatarType === 'letter' && (
|
||||
<div style={{ display: 'grid', gridTemplateColumns: 'repeat(6, 1fr)', gap: 8 }}>
|
||||
{COLORS.map((c) => (
|
||||
<button
|
||||
key={c}
|
||||
onClick={() => setAvatarColor(c)}
|
||||
style={{
|
||||
width: '100%', aspectRatio: '1', borderRadius: 12, border: avatarColor === c ? `3px solid ${c}` : '2px solid var(--warm-border)',
|
||||
backgroundColor: c, cursor: 'pointer', outline: 'none',
|
||||
boxShadow: avatarColor === c ? `0 0 0 3px ${c}33` : 'none',
|
||||
}}
|
||||
/>
|
||||
))}
|
||||
</div>
|
||||
)}
|
||||
|
||||
{/* Preset mode: grid of animal faces */}
|
||||
{avatarType === 'preset' && (
|
||||
<div style={{ display: 'grid', gridTemplateColumns: 'repeat(4, 1fr)', gap: 8 }}>
|
||||
{Object.entries(AVATAR_PRESETS).map(([id]) => (
|
||||
<button
|
||||
key={id}
|
||||
onClick={() => setAvatarPreset(id)}
|
||||
style={{
|
||||
display: 'flex', flexDirection: 'column', alignItems: 'center', gap: 4,
|
||||
padding: 8, borderRadius: 14, cursor: 'pointer', outline: 'none',
|
||||
border: avatarPreset === id ? '2.5px solid var(--warm-accent)' : '1.5px solid var(--warm-border)',
|
||||
backgroundColor: avatarPreset === id ? 'var(--warm-accent-light)' : 'var(--warm-bg-subtle)',
|
||||
boxShadow: avatarPreset === id ? '0 0 0 3px var(--warm-primary-shadow)' : 'none',
|
||||
}}
|
||||
>
|
||||
<AvatarPresetIcon presetId={id} size={44} />
|
||||
<span style={{ fontSize: 10, fontWeight: 700, color: 'var(--warm-text-muted)' }}>{t(`avatars.${id}`)}</span>
|
||||
</button>
|
||||
))}
|
||||
</div>
|
||||
)}
|
||||
|
||||
{/* Photo mode: upload button */}
|
||||
{avatarType === 'photo' && (
|
||||
<div style={{ textAlign: 'center' }}>
|
||||
<input
|
||||
ref={fileRef}
|
||||
type="file"
|
||||
accept="image/*"
|
||||
onChange={handlePhotoUpload}
|
||||
style={{ display: 'none' }}
|
||||
/>
|
||||
<button
|
||||
className="tq-btn"
|
||||
onClick={() => fileRef.current?.click()}
|
||||
style={{
|
||||
padding: '10px 24px', backgroundColor: 'var(--warm-accent-light)', color: 'var(--warm-accent)',
|
||||
fontSize: 13, fontWeight: 700, border: '1.5px solid var(--warm-border)',
|
||||
}}
|
||||
>
|
||||
{t('profile.uploadPhoto')}
|
||||
</button>
|
||||
{avatarPhotoUrl && (
|
||||
<div style={{ marginTop: 8, fontSize: 11, color: '#B0A090', fontWeight: 600 }}>
|
||||
Photo uploaded
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
|
||||
{/* Language */}
|
||||
<div style={{ marginBottom: 28 }}>
|
||||
<label style={{ fontSize: 12, fontWeight: 800, color: 'var(--warm-text-muted)', textTransform: 'uppercase', letterSpacing: 0.5, marginBottom: 8, display: 'block' }}>
|
||||
{t('profile.language')}
|
||||
</label>
|
||||
<div style={{ display: 'flex', alignItems: 'center', gap: 10 }}>
|
||||
<GlobeIcon />
|
||||
<select
|
||||
value={language}
|
||||
onChange={(e) => setLanguage(e.target.value)}
|
||||
style={{
|
||||
flex: 1, padding: '10px 14px', borderRadius: 12,
|
||||
border: '1.5px solid var(--warm-border)', fontSize: 14, fontWeight: 700,
|
||||
color: 'var(--warm-text)', fontFamily: 'Nunito', backgroundColor: 'var(--warm-bg-input)',
|
||||
cursor: 'pointer', outline: 'none',
|
||||
}}
|
||||
>
|
||||
<option value="en">English</option>
|
||||
<option value="fr">Fran{'\u00E7'}ais</option>
|
||||
<option value="de">Deutsch</option>
|
||||
<option value="es">Espa{'\u00F1'}ol</option>
|
||||
</select>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<div style={{ marginBottom: 24, display: 'grid', gap: 8 }}>
|
||||
<label style={{ fontSize: 12, fontWeight: 800, color: 'var(--warm-text-muted)', textTransform: 'uppercase', letterSpacing: 0.5, marginBottom: 4, display: 'block' }}>
|
||||
{t('settings.passwordSection')}
|
||||
</label>
|
||||
<input type="password" value={currentPassword} onChange={(e) => setCurrentPassword(e.target.value)} placeholder={t('settings.currentPassword')} style={{ padding: '10px 14px', borderRadius: 12, border: '1.5px solid var(--warm-border)', fontFamily: 'Nunito', backgroundColor: 'var(--warm-bg-input)', color: 'var(--warm-text)' }} />
|
||||
<input type="password" value={newPassword} onChange={(e) => setNewPassword(e.target.value)} placeholder={t('settings.newPassword')} style={{ padding: '10px 14px', borderRadius: 12, border: '1.5px solid var(--warm-border)', fontFamily: 'Nunito', backgroundColor: 'var(--warm-bg-input)', color: 'var(--warm-text)' }} />
|
||||
<input type="password" value={confirmPassword} onChange={(e) => setConfirmPassword(e.target.value)} placeholder={t('settings.confirmPassword')} style={{ padding: '10px 14px', borderRadius: 12, border: '1.5px solid var(--warm-border)', fontFamily: 'Nunito', backgroundColor: 'var(--warm-bg-input)', color: 'var(--warm-text)' }} />
|
||||
<button className="tq-btn tq-btn-secondary" onClick={handlePasswordChange} style={{ width: 'fit-content', padding: '8px 12px', fontSize: 12 }}>
|
||||
{t('settings.updatePassword')}
|
||||
</button>
|
||||
{passwordMsg && <div style={{ fontSize: 11, color: 'var(--warm-text-light)', fontWeight: 700 }}>{passwordMsg}</div>}
|
||||
</div>
|
||||
|
||||
{/* Save */}
|
||||
<button
|
||||
className="tq-btn tq-btn-primary"
|
||||
onClick={handleSave}
|
||||
disabled={saving}
|
||||
style={{ width: '100%', padding: '12px', fontSize: 14, fontWeight: 800 }}
|
||||
>
|
||||
{saving ? t('common.loading') : saved ? t('profile.saved') : t('profile.save')}
|
||||
</button>
|
||||
<button
|
||||
className="tq-btn tq-btn-secondary"
|
||||
onClick={onLogout}
|
||||
style={{ width: '100%', padding: '10px', fontSize: 13, fontWeight: 800, marginTop: 10 }}
|
||||
>
|
||||
{t('profile.logout')}
|
||||
</button>
|
||||
</div>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
120
client/src/components/pages/Register.tsx
Normal file
120
client/src/components/pages/Register.tsx
Normal file
|
|
@ -0,0 +1,120 @@
|
|||
import { useState } from 'react';
|
||||
import { SparkleIcon } from '../icons/UIIcons';
|
||||
import { useTranslation } from '../../hooks/useTranslation';
|
||||
|
||||
interface RegisterProps {
|
||||
onRegister: (data: { username: string; password: string; displayName: string; language: string }) => Promise<void>;
|
||||
onSwitchToLogin: () => void;
|
||||
}
|
||||
|
||||
export function Register({ onRegister, onSwitchToLogin }: RegisterProps) {
|
||||
const initialLang = (() => {
|
||||
const saved = typeof localStorage !== 'undefined' ? localStorage.getItem('tidyquest_auth_lang') : null;
|
||||
if (saved && ['en', 'fr', 'de', 'es'].includes(saved)) return saved;
|
||||
const browser = typeof navigator !== 'undefined' ? navigator.language.slice(0, 2) : 'en';
|
||||
return ['en', 'fr', 'de', 'es'].includes(browser) ? browser : 'en';
|
||||
})();
|
||||
const [authLanguage, setAuthLanguage] = useState(initialLang);
|
||||
const { t } = useTranslation(authLanguage);
|
||||
const [displayName, setDisplayName] = useState('');
|
||||
const [username, setUsername] = useState('');
|
||||
const [password, setPassword] = useState('');
|
||||
const [error, setError] = useState('');
|
||||
const [loading, setLoading] = useState(false);
|
||||
|
||||
const handleSubmit = async (e: React.FormEvent) => {
|
||||
e.preventDefault();
|
||||
setError('');
|
||||
if (!displayName || !username || !password) {
|
||||
setError(t('auth.allFieldsRequired'));
|
||||
return;
|
||||
}
|
||||
setLoading(true);
|
||||
try {
|
||||
await onRegister({ username: username.trim(), password, displayName, language: authLanguage });
|
||||
window.location.href = '/';
|
||||
} catch (err: any) {
|
||||
setError(err.message || t('auth.registrationFailed'));
|
||||
} finally {
|
||||
setLoading(false);
|
||||
}
|
||||
};
|
||||
|
||||
const inputStyle = {
|
||||
width: '100%', padding: '10px 14px', borderRadius: 12, border: '1.5px solid #F0E6D9',
|
||||
fontSize: 14, fontFamily: 'Nunito', fontWeight: 600 as const, color: '#3D2F1E',
|
||||
outline: 'none', backgroundColor: '#FFFBF5',
|
||||
};
|
||||
|
||||
return (
|
||||
<div style={{
|
||||
minHeight: '100vh', display: 'flex', alignItems: 'center', justifyContent: 'center',
|
||||
backgroundColor: '#FFF9F2',
|
||||
}}>
|
||||
<div className="tq-card" style={{ padding: 40, width: 400 }}>
|
||||
<div style={{ textAlign: 'center', marginBottom: 28 }}>
|
||||
<div style={{
|
||||
width: 56, height: 56, borderRadius: 18, margin: '0 auto 14px',
|
||||
background: 'linear-gradient(135deg, #FFF7ED, #FFEDD5)',
|
||||
border: '1.5px solid #FDBA74',
|
||||
display: 'flex', alignItems: 'center', justifyContent: 'center',
|
||||
}}>
|
||||
<SparkleIcon />
|
||||
</div>
|
||||
<h1 style={{ fontSize: 24, fontWeight: 900, color: '#3D2F1E', margin: 0 }}>{t('auth.welcome')}</h1>
|
||||
<p style={{ fontSize: 12, color: '#B0A090', fontWeight: 600, marginTop: 4 }}>{t('auth.createYourAccount')}</p>
|
||||
<select
|
||||
value={authLanguage}
|
||||
onChange={(e) => {
|
||||
const v = e.target.value;
|
||||
setAuthLanguage(v);
|
||||
localStorage.setItem('tidyquest_auth_lang', v);
|
||||
}}
|
||||
style={{
|
||||
marginTop: 10, padding: '6px 10px', borderRadius: 10, border: '1.5px solid #F0E6D9',
|
||||
fontSize: 12, fontFamily: 'Nunito', fontWeight: 700, color: '#6B5B4A', backgroundColor: '#FFFBF5',
|
||||
}}
|
||||
>
|
||||
<option value="en">English</option>
|
||||
<option value="fr">Français</option>
|
||||
<option value="de">Deutsch</option>
|
||||
<option value="es">Español</option>
|
||||
</select>
|
||||
</div>
|
||||
|
||||
<form onSubmit={handleSubmit}>
|
||||
<div style={{ marginBottom: 14 }}>
|
||||
<label style={{ fontSize: 12, fontWeight: 700, color: '#8A7A6A', display: 'block', marginBottom: 6 }}>{t('auth.displayName')}</label>
|
||||
<input value={displayName} onChange={(e) => setDisplayName(e.target.value)} style={inputStyle} placeholder={t('auth.displayNamePlaceholder')} />
|
||||
</div>
|
||||
<div style={{ marginBottom: 14 }}>
|
||||
<label style={{ fontSize: 12, fontWeight: 700, color: '#8A7A6A', display: 'block', marginBottom: 6 }}>{t('auth.username')}</label>
|
||||
<input value={username} onChange={(e) => setUsername(e.target.value)} style={inputStyle} placeholder={t('auth.usernamePlaceholder')} />
|
||||
</div>
|
||||
<div style={{ marginBottom: 14 }}>
|
||||
<label style={{ fontSize: 12, fontWeight: 700, color: '#8A7A6A', display: 'block', marginBottom: 6 }}>{t('auth.password')}</label>
|
||||
<input type="password" value={password} onChange={(e) => setPassword(e.target.value)} style={inputStyle} placeholder={t('auth.passwordMinChars')} />
|
||||
</div>
|
||||
|
||||
{error && <div style={{ fontSize: 12, color: '#E25A5A', fontWeight: 700, marginBottom: 14, textAlign: 'center' }}>{error}</div>}
|
||||
|
||||
<button type="submit" className="tq-btn tq-btn-primary"
|
||||
disabled={loading}
|
||||
style={{ width: '100%', padding: '12px', fontSize: 15, justifyContent: 'center' }}>
|
||||
{loading ? t('auth.creating') : t('auth.createAccountAction')}
|
||||
</button>
|
||||
</form>
|
||||
|
||||
<div style={{ textAlign: 'center', marginTop: 18 }}>
|
||||
<button onClick={onSwitchToLogin}
|
||||
style={{
|
||||
background: 'none', border: 'none', color: '#F97316', fontSize: 13,
|
||||
fontWeight: 700, cursor: 'pointer', fontFamily: 'Nunito',
|
||||
}}>
|
||||
{t('auth.alreadyHaveAccount')}
|
||||
</button>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
219
client/src/components/pages/Rewards.tsx
Normal file
219
client/src/components/pages/Rewards.tsx
Normal file
|
|
@ -0,0 +1,219 @@
|
|||
import { useEffect, useMemo, useRef, useState, type CSSProperties } from 'react';
|
||||
import { CoinIcon } from '../icons/UIIcons';
|
||||
import { useTranslation } from '../../hooks/useTranslation';
|
||||
|
||||
interface Reward {
|
||||
id: number;
|
||||
title: string;
|
||||
description?: string | null;
|
||||
costCoins: number;
|
||||
isPreset?: boolean;
|
||||
}
|
||||
|
||||
interface Redemption {
|
||||
id: number;
|
||||
title: string;
|
||||
costCoins: number;
|
||||
redeemedAt: string;
|
||||
status: string;
|
||||
}
|
||||
|
||||
interface RewardsProps {
|
||||
language?: string;
|
||||
rewards: Reward[];
|
||||
mine: Redemption[];
|
||||
userCoins: number;
|
||||
onRedeem: (rewardId: number) => Promise<void>;
|
||||
onCancel: (redemptionId: number) => Promise<void>;
|
||||
}
|
||||
|
||||
export function Rewards({ language, rewards, mine, userCoins, onRedeem, onCancel }: RewardsProps) {
|
||||
const { t } = useTranslation(language);
|
||||
const [pendingRewardId, setPendingRewardId] = useState<number | null>(null);
|
||||
const [spendFx, setSpendFx] = useState<{ amount: number; key: number } | null>(null);
|
||||
const [refundFx, setRefundFx] = useState<{ amount: number; key: number } | null>(null);
|
||||
const previousStatuses = useRef<Record<number, string>>({});
|
||||
|
||||
const pendingReward = useMemo(() => rewards.find((r) => r.id === pendingRewardId) || null, [pendingRewardId, rewards]);
|
||||
|
||||
const presetKeyByTitle: Record<string, string> = {
|
||||
'movie night pick': 'movie_night',
|
||||
'ice cream treat': 'ice_cream',
|
||||
'stay up 30 min': 'late_bedtime',
|
||||
'game time bonus': 'game_bonus',
|
||||
'choose dinner': 'choose_dinner',
|
||||
'park adventure': 'park_adventure',
|
||||
'no-chore pass': 'chore_pass',
|
||||
'family board game': 'board_game',
|
||||
};
|
||||
|
||||
const rewardTitleByName = (title: string): string => {
|
||||
const k = presetKeyByTitle[title.toLowerCase()];
|
||||
if (k) return t(`rewardsPreset.${k}.title`);
|
||||
return title;
|
||||
};
|
||||
|
||||
const rewardTitle = (r: Reward): string => {
|
||||
return rewardTitleByName(r.title);
|
||||
};
|
||||
|
||||
const rewardDesc = (r: Reward): string => {
|
||||
const k = presetKeyByTitle[r.title.toLowerCase()];
|
||||
if (k) return t(`rewardsPreset.${k}.desc`);
|
||||
return r.description || t('rewards.noDescription');
|
||||
};
|
||||
|
||||
const confirmRedeem = async () => {
|
||||
if (!pendingReward) return;
|
||||
await onRedeem(pendingReward.id);
|
||||
setSpendFx({ amount: pendingReward.costCoins, key: Date.now() });
|
||||
setPendingRewardId(null);
|
||||
};
|
||||
|
||||
useEffect(() => {
|
||||
if (!spendFx) return;
|
||||
const id = window.setTimeout(() => setSpendFx(null), 1500);
|
||||
return () => window.clearTimeout(id);
|
||||
}, [spendFx]);
|
||||
|
||||
useEffect(() => {
|
||||
const prev = previousStatuses.current;
|
||||
for (const r of mine) {
|
||||
if (prev[r.id] === 'requested' && r.status === 'rejected') {
|
||||
setRefundFx({ amount: r.costCoins, key: Date.now() + r.id });
|
||||
break;
|
||||
}
|
||||
}
|
||||
const next: Record<number, string> = {};
|
||||
mine.forEach((r) => {
|
||||
next[r.id] = r.status;
|
||||
});
|
||||
previousStatuses.current = next;
|
||||
}, [mine]);
|
||||
|
||||
useEffect(() => {
|
||||
if (!refundFx) return;
|
||||
const id = window.setTimeout(() => setRefundFx(null), 1800);
|
||||
return () => window.clearTimeout(id);
|
||||
}, [refundFx]);
|
||||
|
||||
const statusLabel = (status: string): string => {
|
||||
if (status === 'requested') return t('rewards.statusPending');
|
||||
if (status === 'approved') return t('rewards.statusApproved');
|
||||
if (status === 'rejected') return t('rewards.statusRejected');
|
||||
if (status === 'cancelled') return t('rewards.statusCancelled');
|
||||
return status;
|
||||
};
|
||||
|
||||
const statusStyle = (status: string): CSSProperties => {
|
||||
if (status === 'approved') return { color: '#15803D', backgroundColor: '#DCFCE7', border: '1px solid #86EFAC' };
|
||||
if (status === 'rejected') return { color: '#B91C1C', backgroundColor: '#FEE2E2', border: '1px solid #FCA5A5' };
|
||||
if (status === 'cancelled') return { color: '#374151', backgroundColor: '#E5E7EB', border: '1px solid #D1D5DB' };
|
||||
return { color: 'var(--warm-accent)', backgroundColor: 'var(--warm-accent-light)', border: '1px solid var(--warm-accent)' };
|
||||
};
|
||||
|
||||
return (
|
||||
<div className="page-enter" style={{ display: 'grid', gap: 16 }}>
|
||||
<style>{`
|
||||
@keyframes coinSpendFloat {
|
||||
0% { opacity: 0; transform: translateY(12px) scale(0.9); }
|
||||
20% { opacity: 1; transform: translateY(0px) scale(1); }
|
||||
100% { opacity: 0; transform: translateY(-26px) scale(1.04); }
|
||||
}
|
||||
@keyframes coinRefundFloat {
|
||||
0% { opacity: 0; transform: translateY(10px) scale(0.95); }
|
||||
20% { opacity: 1; transform: translateY(0px) scale(1); }
|
||||
100% { opacity: 0; transform: translateY(-24px) scale(1.04); }
|
||||
}
|
||||
`}</style>
|
||||
<div className="tq-card" style={{ padding: 18 }}>
|
||||
<div style={{ display: 'flex', alignItems: 'center', gap: 8 }}>
|
||||
<CoinIcon />
|
||||
<div style={{ fontSize: 14, fontWeight: 800, color: 'var(--warm-text)' }}>{userCoins} {t('settings.coins')}</div>
|
||||
</div>
|
||||
<div style={{ fontSize: 11, color: 'var(--warm-text-light)', fontWeight: 600, marginTop: 4 }}>{t('rewards.balanceHint')}</div>
|
||||
</div>
|
||||
|
||||
<div className="tq-card" style={{ padding: 20 }}>
|
||||
<h3 style={{ margin: '0 0 10px', fontSize: 16, fontWeight: 900, color: 'var(--warm-text)' }}>{t('rewards.catalog')}</h3>
|
||||
<div style={{ display: 'grid', gridTemplateColumns: 'repeat(auto-fill, minmax(240px, 1fr))', gap: 10 }}>
|
||||
{rewards.map((r) => {
|
||||
const canBuy = userCoins >= r.costCoins;
|
||||
return (
|
||||
<div key={r.id} style={{ border: '1.5px solid var(--warm-border)', borderRadius: 14, padding: 12, backgroundColor: 'var(--warm-bg-subtle)' }}>
|
||||
<div style={{ fontSize: 14, fontWeight: 800, color: 'var(--warm-text)', marginBottom: 4 }}>{rewardTitle(r)}</div>
|
||||
<div style={{ fontSize: 11, color: 'var(--warm-text-light)', fontWeight: 600, minHeight: 32 }}>{rewardDesc(r)}</div>
|
||||
<div style={{ display: 'flex', alignItems: 'center', justifyContent: 'space-between', marginTop: 8 }}>
|
||||
<div style={{ fontSize: 13, fontWeight: 800, color: 'var(--warm-accent)', display: 'inline-flex', alignItems: 'center', justifyContent: 'center', gap: 4 }}>
|
||||
<CoinIcon /> {r.costCoins}
|
||||
</div>
|
||||
<button
|
||||
className="tq-btn tq-btn-primary"
|
||||
style={{ padding: '6px 10px', fontSize: 11, opacity: canBuy ? 1 : 0.6 }}
|
||||
disabled={!canBuy}
|
||||
onClick={() => setPendingRewardId(r.id)}
|
||||
>
|
||||
{canBuy ? t('rewards.redeem') : t('rewards.notEnough')}
|
||||
</button>
|
||||
</div>
|
||||
</div>
|
||||
);
|
||||
})}
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<div className="tq-card" style={{ padding: 20 }}>
|
||||
<h3 style={{ margin: '0 0 10px', fontSize: 16, fontWeight: 900, color: 'var(--warm-text)' }}>{t('rewards.myRequests')}</h3>
|
||||
{mine.length === 0 ? (
|
||||
<div style={{ fontSize: 12, color: 'var(--warm-text-light)', fontWeight: 600 }}>{t('rewards.noRequests')}</div>
|
||||
) : (
|
||||
<div style={{ display: 'grid', gap: 8 }}>
|
||||
{mine.map((m) => (
|
||||
<div key={m.id} style={{ border: '1.5px solid var(--warm-border)', borderRadius: 12, padding: 10, display: 'flex', justifyContent: 'space-between', alignItems: 'center', gap: 10 }}>
|
||||
<div>
|
||||
<div style={{ fontSize: 13, fontWeight: 800, color: 'var(--warm-text)' }}>{rewardTitleByName(m.title)}</div>
|
||||
<div style={{ fontSize: 10, color: 'var(--warm-text-light)', fontWeight: 700 }}>{new Date(m.redeemedAt).toLocaleString()}</div>
|
||||
</div>
|
||||
<div style={{ display: 'flex', alignItems: 'center', gap: 8 }}>
|
||||
<div style={{ fontSize: 11, fontWeight: 800, color: 'var(--warm-accent)', display: 'inline-flex', alignItems: 'center', gap: 4 }}>- {m.costCoins} <CoinIcon /></div>
|
||||
<span style={{ ...statusStyle(m.status), fontSize: 10, fontWeight: 800, borderRadius: 999, padding: '2px 8px', textTransform: 'uppercase', letterSpacing: 0.4 }}>
|
||||
{statusLabel(m.status)}
|
||||
</span>
|
||||
{m.status === 'requested' && (
|
||||
<button className="tq-btn tq-btn-secondary" onClick={() => onCancel(m.id)} style={{ padding: '4px 8px', fontSize: 10 }}>
|
||||
{t('rewards.cancelRequest')}
|
||||
</button>
|
||||
)}
|
||||
</div>
|
||||
</div>
|
||||
))}
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
{pendingReward && (
|
||||
<div style={{ position: 'fixed', inset: 0, zIndex: 120, backgroundColor: 'rgba(0,0,0,0.35)', display: 'flex', alignItems: 'center', justifyContent: 'center' }}>
|
||||
<div className="tq-card" style={{ width: 380, padding: 20 }}>
|
||||
<div style={{ fontSize: 16, fontWeight: 900, color: 'var(--warm-text)', marginBottom: 6 }}>{t('rewards.confirmTitle')}</div>
|
||||
<div style={{ fontSize: 12, color: 'var(--warm-text-light)', fontWeight: 600, marginBottom: 14 }}>
|
||||
{t('rewards.confirmText').replace('{reward}', rewardTitle(pendingReward)).replace('{coins}', String(pendingReward.costCoins))}
|
||||
</div>
|
||||
<div style={{ display: 'flex', justifyContent: 'flex-end', gap: 8 }}>
|
||||
<button className="tq-btn tq-btn-secondary" onClick={() => setPendingRewardId(null)} style={{ padding: '6px 12px', fontSize: 12 }}>{t('common.cancel')}</button>
|
||||
<button className="tq-btn tq-btn-primary" onClick={confirmRedeem} style={{ padding: '6px 12px', fontSize: 12 }}>{t('rewards.confirmBuy')}</button>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
)}
|
||||
{spendFx && (
|
||||
<div key={spendFx.key} style={{ position: 'fixed', top: 88, right: 80, zIndex: 121, animation: 'coinSpendFloat 1.4s ease forwards', backgroundColor: 'var(--warm-accent-light)', border: '1.5px solid var(--warm-accent)', borderRadius: 14, padding: '6px 10px', display: 'inline-flex', alignItems: 'center', gap: 6, fontSize: 12, fontWeight: 900, color: 'var(--warm-accent)' }}>
|
||||
-{spendFx.amount} <CoinIcon />
|
||||
</div>
|
||||
)}
|
||||
{refundFx && (
|
||||
<div key={refundFx.key} style={{ position: 'fixed', top: 126, right: 80, zIndex: 121, animation: 'coinRefundFloat 1.7s ease forwards', backgroundColor: '#DCFCE7', border: '1.5px solid #16A34A', borderRadius: 14, padding: '6px 10px', display: 'inline-flex', alignItems: 'center', gap: 6, fontSize: 12, fontWeight: 900, color: '#166534' }}>
|
||||
+{refundFx.amount} <CoinIcon />
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
);
|
||||
}
|
||||
499
client/src/components/pages/RoomDetail.tsx
Normal file
499
client/src/components/pages/RoomDetail.tsx
Normal file
|
|
@ -0,0 +1,499 @@
|
|||
import { useState } from 'react';
|
||||
import { HealthBar } from '../shared/HealthBar';
|
||||
import { RingGauge } from '../shared/RingGauge';
|
||||
import { EffortDots } from '../shared/EffortDots';
|
||||
import { getRoomIcon } from '../icons/RoomIcons';
|
||||
import { TaskIcon, TASK_ICON_OPTIONS } from '../icons/TaskIcons';
|
||||
import { CheckIcon, BackIcon, PlusIcon } from '../icons/UIIcons';
|
||||
import { getRoomHealth } from '../../utils/health';
|
||||
import { api } from '../../hooks/useApi';
|
||||
import { useTranslation } from '../../hooks/useTranslation';
|
||||
|
||||
const FREQ_UNITS = [
|
||||
{ label: 'hours', toDays: 1 / 24 },
|
||||
{ label: 'days', toDays: 1 },
|
||||
{ label: 'weeks', toDays: 7 },
|
||||
{ label: 'months', toDays: 30 },
|
||||
{ label: 'years', toDays: 365 },
|
||||
];
|
||||
|
||||
function daysToFreq(days: number): { value: number; unit: string } {
|
||||
if (days >= 365 && days % 365 === 0) return { value: days / 365, unit: 'years' };
|
||||
if (days >= 30 && days % 30 === 0) return { value: days / 30, unit: 'months' };
|
||||
if (days >= 7 && days % 7 === 0) return { value: days / 7, unit: 'weeks' };
|
||||
if (days >= 1) return { value: days, unit: 'days' };
|
||||
return { value: Math.round(days * 24), unit: 'hours' };
|
||||
}
|
||||
|
||||
function freqToDays(value: number, unit: string): number {
|
||||
const u = FREQ_UNITS.find(f => f.label === unit);
|
||||
return value * (u?.toDays || 1);
|
||||
}
|
||||
|
||||
function formatFreq(days: number, t: (key: string) => string): string {
|
||||
const { value, unit } = daysToFreq(days);
|
||||
const short = t(`unitsShort.${unit}`);
|
||||
return `${value}${short}`;
|
||||
}
|
||||
|
||||
function healthColor(value: number): string {
|
||||
if (value >= 70) return '#22C55E';
|
||||
if (value >= 40) return '#F59E0B';
|
||||
return '#EF4444';
|
||||
}
|
||||
|
||||
type SortKey = 'name' | 'health' | 'effort' | 'frequency';
|
||||
|
||||
interface Task {
|
||||
id: number; name: string; translationKey?: string; health: number; frequencyDays: number;
|
||||
effort: number; notes?: string | null; isSeasonal: boolean; lastCompletedAt: string | null; iconKey?: string;
|
||||
}
|
||||
|
||||
interface RoomDetailProps {
|
||||
room: {
|
||||
id: number; name: string; roomType: string; color: string; accentColor: string;
|
||||
tasks: Task[];
|
||||
};
|
||||
language?: string;
|
||||
isAdmin: boolean;
|
||||
onCompleteTask: (taskId: number) => void;
|
||||
onBack: () => void;
|
||||
onRefresh?: () => void;
|
||||
}
|
||||
|
||||
function FrequencyPicker({ value, unit, onChange, t }: {
|
||||
value: number; unit: string;
|
||||
onChange: (v: number, u: string) => void;
|
||||
t: (key: string) => string;
|
||||
}) {
|
||||
return (
|
||||
<div style={{ display: 'flex', gap: 4, alignItems: 'center' }}>
|
||||
<input type="number" min={1} max={999} value={value}
|
||||
onChange={(e) => onChange(Math.max(1, parseInt(e.target.value) || 1), unit)}
|
||||
style={{
|
||||
width: 52, padding: '6px 8px', borderRadius: 8, border: '1.5px solid var(--warm-border)',
|
||||
fontSize: 12, fontFamily: 'Nunito', fontWeight: 700, color: 'var(--warm-text)',
|
||||
outline: 'none', backgroundColor: 'var(--warm-bg-input)', textAlign: 'center',
|
||||
}} />
|
||||
<select value={unit} onChange={(e) => onChange(value, e.target.value)}
|
||||
style={{
|
||||
padding: '6px 8px', borderRadius: 8, border: '1.5px solid var(--warm-border)',
|
||||
fontSize: 12, fontFamily: 'Nunito', fontWeight: 600, color: 'var(--warm-text)',
|
||||
backgroundColor: 'var(--warm-bg-input)', outline: 'none', cursor: 'pointer',
|
||||
}}>
|
||||
{FREQ_UNITS.map((f) => (
|
||||
<option key={f.label} value={f.label}>{t(`units.${f.label}`)}</option>
|
||||
))}
|
||||
</select>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
function EffortPicker({ effort, onChange }: { effort: number; onChange: (e: number) => void }) {
|
||||
return (
|
||||
<div style={{ display: 'flex', gap: 2 }}>
|
||||
{[1, 2, 3, 4, 5].map((e) => (
|
||||
<button key={e} onClick={() => onChange(e)}
|
||||
style={{
|
||||
background: 'none', border: 'none', cursor: 'pointer', padding: 1,
|
||||
opacity: e <= effort ? 1 : 0.3,
|
||||
}}>
|
||||
<svg width="16" height="16" viewBox="0 0 14 14" fill="none">
|
||||
<path d="M7 1L8.5 5H12.5L9.5 7.5L10.5 11.5L7 9L3.5 11.5L4.5 7.5L1.5 5H5.5L7 1Z"
|
||||
fill={e <= effort ? '#F59E0B' : 'none'}
|
||||
stroke={e <= effort ? '#F59E0B' : '#E2D5C5'}
|
||||
strokeWidth={e <= effort ? '0.5' : '1'} />
|
||||
</svg>
|
||||
</button>
|
||||
))}
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
export function RoomDetail({ room, language, isAdmin, onCompleteTask, onBack, onRefresh }: RoomDetailProps) {
|
||||
const { taskName: translateTask, roomDisplayName, timeAgo, t } = useTranslation(language);
|
||||
const [animatedTask, setAnimatedTask] = useState<number | null>(null);
|
||||
const [editingTask, setEditingTask] = useState<number | null>(null);
|
||||
const [editForm, setEditForm] = useState({ name: '', notes: '', freqValue: 7, freqUnit: 'days', effort: 1, health: 100, iconKey: 'sparkle' });
|
||||
const [showAddTask, setShowAddTask] = useState(false);
|
||||
const [newTaskName, setNewTaskName] = useState('');
|
||||
const [newTaskNotes, setNewTaskNotes] = useState('');
|
||||
const [newFreqValue, setNewFreqValue] = useState(7);
|
||||
const [newFreqUnit, setNewFreqUnit] = useState('days');
|
||||
const [newTaskEffort, setNewTaskEffort] = useState(2);
|
||||
const [newTaskHealth, setNewTaskHealth] = useState(100);
|
||||
const [newTaskIconKey, setNewTaskIconKey] = useState('sparkle');
|
||||
const [sortKey, setSortKey] = useState<SortKey>('health');
|
||||
const [sortAsc, setSortAsc] = useState(true);
|
||||
|
||||
const health = getRoomHealth(room.tasks);
|
||||
const RoomIcon = getRoomIcon(room.roomType);
|
||||
|
||||
const sortedTasks = [...room.tasks].sort((a, b) => {
|
||||
let cmp = 0;
|
||||
switch (sortKey) {
|
||||
case 'name': cmp = a.name.localeCompare(b.name); break;
|
||||
case 'health': cmp = a.health - b.health; break;
|
||||
case 'effort': cmp = a.effort - b.effort; break;
|
||||
case 'frequency': cmp = a.frequencyDays - b.frequencyDays; break;
|
||||
}
|
||||
return sortAsc ? cmp : -cmp;
|
||||
});
|
||||
|
||||
const handleSort = (key: SortKey) => {
|
||||
if (sortKey === key) { setSortAsc(!sortAsc); }
|
||||
else { setSortKey(key); setSortAsc(true); }
|
||||
};
|
||||
|
||||
const sortIndicator = (key: SortKey) => {
|
||||
if (sortKey !== key) return '';
|
||||
return sortAsc ? ' \u25B2' : ' \u25BC';
|
||||
};
|
||||
|
||||
const handleComplete = (taskId: number) => {
|
||||
setAnimatedTask(taskId);
|
||||
onCompleteTask(taskId);
|
||||
setTimeout(() => setAnimatedTask(null), 2200);
|
||||
};
|
||||
|
||||
const startEdit = (task: Task) => {
|
||||
const { value, unit } = daysToFreq(task.frequencyDays);
|
||||
setEditingTask(task.id);
|
||||
setEditForm({ name: task.name, notes: task.notes || '', freqValue: value, freqUnit: unit, effort: task.effort, health: task.health, iconKey: task.iconKey || 'sparkle' });
|
||||
};
|
||||
|
||||
const saveEdit = async () => {
|
||||
if (!editingTask) return;
|
||||
const frequencyDays = freqToDays(editForm.freqValue, editForm.freqUnit);
|
||||
await api.updateTask(editingTask, { name: editForm.name, notes: editForm.notes, frequencyDays, effort: editForm.effort, health: editForm.health, iconKey: editForm.iconKey });
|
||||
setEditingTask(null);
|
||||
onRefresh?.();
|
||||
};
|
||||
|
||||
const deleteTask = async (taskId: number) => {
|
||||
await api.deleteTask(taskId);
|
||||
setEditingTask(null);
|
||||
onRefresh?.();
|
||||
};
|
||||
|
||||
const addTask = async () => {
|
||||
if (!newTaskName.trim()) return;
|
||||
const frequencyDays = freqToDays(newFreqValue, newFreqUnit);
|
||||
await api.createTask(room.id, {
|
||||
name: newTaskName.trim(),
|
||||
notes: newTaskNotes.trim() || undefined,
|
||||
frequencyDays,
|
||||
effort: newTaskEffort,
|
||||
health: newTaskHealth,
|
||||
iconKey: newTaskIconKey,
|
||||
});
|
||||
setNewTaskName('');
|
||||
setNewTaskNotes('');
|
||||
setNewFreqValue(7);
|
||||
setNewFreqUnit('days');
|
||||
setNewTaskEffort(2);
|
||||
setNewTaskHealth(100);
|
||||
setNewTaskIconKey('sparkle');
|
||||
setShowAddTask(false);
|
||||
onRefresh?.();
|
||||
};
|
||||
|
||||
const colStyle = (key: SortKey): React.CSSProperties => ({
|
||||
cursor: 'pointer', userSelect: 'none',
|
||||
color: sortKey === key ? 'var(--warm-accent)' : 'var(--warm-text-light)',
|
||||
});
|
||||
|
||||
return (
|
||||
<div className="page-enter">
|
||||
{/* Header */}
|
||||
<div className="tq-card" style={{
|
||||
padding: 28, marginBottom: 20, display: 'flex', alignItems: 'center', gap: 28,
|
||||
background: `linear-gradient(135deg, ${room.color}88, ${room.color}33)`,
|
||||
borderColor: `${room.accentColor}44`,
|
||||
}}>
|
||||
<RingGauge value={health} size={110} strokeWidth={10} />
|
||||
<div style={{ flex: 1 }}>
|
||||
<div style={{ marginBottom: 6 }}><RoomIcon /></div>
|
||||
<h2 style={{ fontSize: 24, fontWeight: 900, color: 'var(--warm-text)', margin: '0 0 4px' }}>{roomDisplayName(room.name, room.roomType)}</h2>
|
||||
<div style={{ fontSize: 13, color: 'var(--warm-text-muted)', fontWeight: 600 }}>{room.tasks.length} {t('rooms.tasksTracked')}</div>
|
||||
</div>
|
||||
<button onClick={onBack} className="tq-btn tq-btn-secondary"
|
||||
style={{ padding: '8px 18px', fontSize: 13 }}>
|
||||
<BackIcon /> {t('rooms.backToRooms')}
|
||||
</button>
|
||||
</div>
|
||||
|
||||
{/* Task Table */}
|
||||
<div className="tq-card" style={{ padding: 22 }}>
|
||||
{/* Column Headers (sortable) */}
|
||||
<div style={{
|
||||
display: 'grid', gridTemplateColumns: '1fr 150px 100px 90px 160px',
|
||||
gap: 12, padding: '0 8px 14px', borderBottom: '1.5px solid var(--warm-border)',
|
||||
fontSize: 11, fontWeight: 800, textTransform: 'uppercase', letterSpacing: 1,
|
||||
}}>
|
||||
<div style={colStyle('name')} onClick={() => handleSort('name')}>{t('history.task')}{sortIndicator('name')}</div>
|
||||
<div style={colStyle('health')} onClick={() => handleSort('health')}>{t('rooms.health')}{sortIndicator('health')}</div>
|
||||
<div style={colStyle('frequency')} onClick={() => handleSort('frequency')}>{t('roomDetail.frequency')}{sortIndicator('frequency')}</div>
|
||||
<div style={colStyle('effort')} onClick={() => handleSort('effort')}>{t('roomDetail.effort')}{sortIndicator('effort')}</div>
|
||||
<div style={{ textAlign: 'right', color: 'var(--warm-text-light)' }}>{t('roomDetail.actions')}</div>
|
||||
</div>
|
||||
|
||||
{sortedTasks.map((task) => (
|
||||
<div key={task.id}>
|
||||
{editingTask === task.id ? (
|
||||
<div style={{
|
||||
padding: '16px 8px', borderBottom: '1px solid var(--warm-border-subtle)',
|
||||
backgroundColor: 'var(--warm-bg-warm)', borderRadius: 12,
|
||||
}}>
|
||||
<div style={{ display: 'flex', flexDirection: 'column', gap: 12 }}>
|
||||
<div style={{ display: 'flex', alignItems: 'center', gap: 12 }}>
|
||||
<label style={{ fontSize: 11, fontWeight: 700, color: 'var(--warm-text-light)', minWidth: 70 }}>{t('roomDetail.name')}</label>
|
||||
<input value={editForm.name}
|
||||
onChange={(e) => setEditForm(f => ({ ...f, name: e.target.value }))}
|
||||
style={{
|
||||
flex: 1, padding: '8px 12px', borderRadius: 10, border: '1.5px solid var(--warm-border)',
|
||||
fontSize: 13, fontFamily: 'Nunito', fontWeight: 700, color: 'var(--warm-text)',
|
||||
outline: 'none', backgroundColor: 'var(--warm-bg-input)',
|
||||
}} />
|
||||
</div>
|
||||
<div style={{ display: 'flex', alignItems: 'center', gap: 12 }}>
|
||||
<label style={{ fontSize: 11, fontWeight: 700, color: 'var(--warm-text-light)', minWidth: 70 }}>{t('roomDetail.notes')}</label>
|
||||
<textarea
|
||||
value={editForm.notes}
|
||||
onChange={(e) => setEditForm((f) => ({ ...f, notes: e.target.value }))}
|
||||
placeholder={t('roomDetail.optionalNotes')}
|
||||
rows={2}
|
||||
style={{
|
||||
flex: 1, padding: '8px 12px', borderRadius: 10, border: '1.5px solid var(--warm-border)',
|
||||
fontSize: 12, fontFamily: 'Nunito', fontWeight: 600, color: 'var(--warm-text)',
|
||||
outline: 'none', backgroundColor: 'var(--warm-bg-input)', resize: 'vertical',
|
||||
}}
|
||||
/>
|
||||
</div>
|
||||
<div style={{ display: 'flex', alignItems: 'center', gap: 20 }}>
|
||||
<div style={{ display: 'flex', alignItems: 'center', gap: 8 }}>
|
||||
<label style={{ fontSize: 11, fontWeight: 700, color: 'var(--warm-text-light)' }}>{t('roomDetail.every')}</label>
|
||||
<FrequencyPicker value={editForm.freqValue} unit={editForm.freqUnit}
|
||||
t={t}
|
||||
onChange={(v, u) => setEditForm(f => ({ ...f, freqValue: v, freqUnit: u }))} />
|
||||
</div>
|
||||
<div style={{ display: 'flex', alignItems: 'center', gap: 8 }}>
|
||||
<label style={{ fontSize: 11, fontWeight: 700, color: 'var(--warm-text-light)' }}>{t('roomDetail.effort')}</label>
|
||||
<EffortPicker effort={editForm.effort} onChange={(e) => setEditForm(f => ({ ...f, effort: e }))} />
|
||||
</div>
|
||||
</div>
|
||||
<div style={{ display: 'flex', alignItems: 'center', gap: 10 }}>
|
||||
<label style={{ fontSize: 10, fontWeight: 700, color: 'var(--warm-text-light)', minWidth: 58 }}>{t('rooms.health')}</label>
|
||||
<div style={{ width: 220 }}>
|
||||
<div style={{ display: 'flex', alignItems: 'center', gap: 8 }}>
|
||||
<input
|
||||
type="range"
|
||||
min={0}
|
||||
max={100}
|
||||
step={10}
|
||||
value={editForm.health}
|
||||
onChange={(e) => setEditForm((f) => ({ ...f, health: parseInt(e.target.value, 10) }))}
|
||||
style={{ flex: 1, accentColor: healthColor(editForm.health) }}
|
||||
/>
|
||||
<span style={{ fontSize: 11, fontWeight: 800, color: healthColor(editForm.health), minWidth: 32, textAlign: 'right' }}>
|
||||
{editForm.health}%
|
||||
</span>
|
||||
</div>
|
||||
<div style={{ display: 'flex', justifyContent: 'space-between', fontSize: 9, color: 'var(--warm-text-light)', fontWeight: 600, marginTop: 2 }}>
|
||||
<span>{t('rooms.dirty')}</span><span>{t('rooms.clean')}</span>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
<div style={{ display: 'flex', alignItems: 'center', gap: 8 }}>
|
||||
<label style={{ fontSize: 10, fontWeight: 700, color: 'var(--warm-text-light)', minWidth: 58 }}>Icon</label>
|
||||
<select
|
||||
value={editForm.iconKey}
|
||||
onChange={(e) => setEditForm((f) => ({ ...f, iconKey: e.target.value }))}
|
||||
style={{ padding: '5px 8px', borderRadius: 8, border: '1.5px solid var(--warm-border)', fontFamily: 'Nunito', fontSize: 11 }}
|
||||
>
|
||||
{TASK_ICON_OPTIONS.map((opt) => (
|
||||
<option key={opt.key} value={opt.key}>{opt.label}</option>
|
||||
))}
|
||||
</select>
|
||||
</div>
|
||||
<div style={{ display: 'flex', gap: 8, justifyContent: 'space-between' }}>
|
||||
<button onClick={() => deleteTask(task.id)}
|
||||
style={{
|
||||
background: 'none', border: '1.5px solid var(--warm-danger-border)', borderRadius: 10,
|
||||
padding: '6px 14px', fontSize: 11, fontWeight: 700, color: 'var(--warm-danger)',
|
||||
cursor: 'pointer', fontFamily: 'Nunito',
|
||||
}}>{t('roomDetail.deleteTask')}</button>
|
||||
<div style={{ display: 'flex', gap: 8 }}>
|
||||
<button onClick={() => setEditingTask(null)} className="tq-btn tq-btn-secondary"
|
||||
style={{ padding: '6px 16px', fontSize: 12 }}>{t('common.cancel')}</button>
|
||||
<button onClick={saveEdit} className="tq-btn tq-btn-primary"
|
||||
style={{ padding: '6px 16px', fontSize: 12 }}>{t('common.save')}</button>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
) : (
|
||||
<div style={{
|
||||
display: 'grid', gridTemplateColumns: '1fr 150px 100px 90px 160px',
|
||||
gap: 12, padding: '16px 8px', alignItems: 'center',
|
||||
borderBottom: '1px solid var(--warm-border-subtle)',
|
||||
backgroundColor: animatedTask === task.id ? 'var(--health-green-bg)' : 'transparent',
|
||||
transition: 'all 0.3s ease', borderRadius: 12,
|
||||
}}>
|
||||
<div style={{ display: 'flex', alignItems: 'center', gap: 10 }}>
|
||||
<span style={{
|
||||
width: 34, height: 34, borderRadius: 11,
|
||||
display: 'inline-flex', alignItems: 'center', justifyContent: 'center',
|
||||
backgroundColor: 'var(--warm-bg-subtle)', border: '1px solid var(--warm-border)',
|
||||
flexShrink: 0,
|
||||
marginLeft: -8,
|
||||
alignSelf: 'center',
|
||||
}}>
|
||||
<TaskIcon iconKey={task.iconKey} size={24} />
|
||||
</span>
|
||||
<div style={{ minWidth: 0 }}>
|
||||
<div style={{ fontSize: 14, fontWeight: 800, color: 'var(--warm-text)' }}>
|
||||
{translateTask(task.name, task.translationKey)}
|
||||
</div>
|
||||
{task.notes && (
|
||||
<div style={{ fontSize: 11, color: 'var(--warm-text-muted)', fontWeight: 600, marginTop: 2 }}>
|
||||
{task.notes}
|
||||
</div>
|
||||
)}
|
||||
<div style={{ fontSize: 11, color: 'var(--warm-text-light)', fontWeight: 600 }}>
|
||||
{timeAgo(task.lastCompletedAt)}{task.isSeasonal ? ` · ${t('roomDetail.seasonal')}` : ''}
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
<HealthBar value={animatedTask === task.id ? 100 : task.health} height={8} animate={animatedTask === task.id} />
|
||||
<div style={{ fontSize: 13, color: 'var(--warm-text-secondary)', fontWeight: 600 }}>{t('roomDetail.every')} {formatFreq(task.frequencyDays, t)}</div>
|
||||
<EffortDots effort={task.effort} />
|
||||
<div style={{ display: 'flex', gap: 4, justifyContent: 'flex-end' }}>
|
||||
{isAdmin && (
|
||||
<>
|
||||
<button onClick={() => startEdit(task)}
|
||||
style={{
|
||||
background: 'none', border: '1.5px solid var(--warm-border)', borderRadius: 10,
|
||||
padding: '6px 10px', fontSize: 11, fontWeight: 700, color: 'var(--warm-text-muted)',
|
||||
cursor: 'pointer', fontFamily: 'Nunito',
|
||||
}}>{t('common.edit')}</button>
|
||||
<button onClick={() => deleteTask(task.id)}
|
||||
style={{
|
||||
background: 'none', border: '1.5px solid var(--warm-danger-border)', borderRadius: 10,
|
||||
padding: '6px 10px', fontSize: 11, fontWeight: 700, color: 'var(--warm-danger)',
|
||||
cursor: 'pointer', fontFamily: 'Nunito',
|
||||
}}>×</button>
|
||||
</>
|
||||
)}
|
||||
<button onClick={() => handleComplete(task.id)} className="tq-btn tq-btn-primary"
|
||||
style={{ padding: '6px 14px', fontSize: 12 }}>
|
||||
<CheckIcon /> {t('roomDetail.done')}
|
||||
</button>
|
||||
</div>
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
))}
|
||||
|
||||
{/* Add Task */}
|
||||
{isAdmin && showAddTask ? (
|
||||
<div style={{
|
||||
padding: '16px 8px', borderTop: '1px solid var(--warm-border-subtle)',
|
||||
backgroundColor: 'var(--warm-bg-warm)', borderRadius: 12, marginTop: 4,
|
||||
}}>
|
||||
<div style={{ display: 'flex', flexDirection: 'column', gap: 12 }}>
|
||||
<div style={{ display: 'flex', alignItems: 'center', gap: 12 }}>
|
||||
<label style={{ fontSize: 11, fontWeight: 700, color: 'var(--warm-text-light)', minWidth: 70 }}>{t('roomDetail.name')}</label>
|
||||
<input value={newTaskName}
|
||||
onChange={(e) => setNewTaskName(e.target.value)}
|
||||
onKeyDown={(e) => e.key === 'Enter' && addTask()}
|
||||
placeholder={t('roomDetail.taskName')}
|
||||
style={{
|
||||
flex: 1, padding: '8px 12px', borderRadius: 10, border: '1.5px solid var(--warm-border)',
|
||||
fontSize: 13, fontFamily: 'Nunito', fontWeight: 700, color: 'var(--warm-text)',
|
||||
outline: 'none', backgroundColor: 'var(--warm-bg-input)',
|
||||
}} />
|
||||
</div>
|
||||
<div style={{ display: 'flex', alignItems: 'center', gap: 12 }}>
|
||||
<label style={{ fontSize: 11, fontWeight: 700, color: 'var(--warm-text-light)', minWidth: 70 }}>{t('roomDetail.notes')}</label>
|
||||
<textarea value={newTaskNotes}
|
||||
onChange={(e) => setNewTaskNotes(e.target.value)}
|
||||
placeholder={t('roomDetail.optionalNotes')}
|
||||
rows={2}
|
||||
style={{
|
||||
flex: 1, padding: '8px 12px', borderRadius: 10, border: '1.5px solid var(--warm-border)',
|
||||
fontSize: 12, fontFamily: 'Nunito', fontWeight: 600, color: 'var(--warm-text)',
|
||||
outline: 'none', backgroundColor: 'var(--warm-bg-input)', resize: 'vertical',
|
||||
}} />
|
||||
</div>
|
||||
<div style={{ display: 'flex', alignItems: 'center', gap: 20 }}>
|
||||
<div style={{ display: 'flex', alignItems: 'center', gap: 8 }}>
|
||||
<label style={{ fontSize: 11, fontWeight: 700, color: 'var(--warm-text-light)' }}>{t('roomDetail.every')}</label>
|
||||
<FrequencyPicker value={newFreqValue} unit={newFreqUnit}
|
||||
t={t}
|
||||
onChange={(v, u) => { setNewFreqValue(v); setNewFreqUnit(u); }} />
|
||||
</div>
|
||||
<div style={{ display: 'flex', alignItems: 'center', gap: 8 }}>
|
||||
<label style={{ fontSize: 11, fontWeight: 700, color: 'var(--warm-text-light)' }}>{t('roomDetail.effort')}</label>
|
||||
<EffortPicker effort={newTaskEffort} onChange={setNewTaskEffort} />
|
||||
</div>
|
||||
</div>
|
||||
<div style={{ display: 'flex', alignItems: 'center', gap: 10 }}>
|
||||
<label style={{ fontSize: 10, fontWeight: 700, color: 'var(--warm-text-light)', minWidth: 58 }}>{t('rooms.health')}</label>
|
||||
<div style={{ width: 220 }}>
|
||||
<div style={{ display: 'flex', alignItems: 'center', gap: 8 }}>
|
||||
<input
|
||||
type="range"
|
||||
min={0}
|
||||
max={100}
|
||||
step={10}
|
||||
value={newTaskHealth}
|
||||
onChange={(e) => setNewTaskHealth(parseInt(e.target.value, 10))}
|
||||
style={{ flex: 1, accentColor: healthColor(newTaskHealth) }}
|
||||
/>
|
||||
<span style={{ fontSize: 11, fontWeight: 800, color: healthColor(newTaskHealth), minWidth: 32, textAlign: 'right' }}>
|
||||
{newTaskHealth}%
|
||||
</span>
|
||||
</div>
|
||||
<div style={{ display: 'flex', justifyContent: 'space-between', fontSize: 9, color: 'var(--warm-text-light)', fontWeight: 600, marginTop: 2 }}>
|
||||
<span>{t('rooms.dirty')}</span><span>{t('rooms.clean')}</span>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
<div style={{ display: 'flex', alignItems: 'center', gap: 8 }}>
|
||||
<label style={{ fontSize: 10, fontWeight: 700, color: 'var(--warm-text-light)', minWidth: 58 }}>Icon</label>
|
||||
<select
|
||||
value={newTaskIconKey}
|
||||
onChange={(e) => setNewTaskIconKey(e.target.value)}
|
||||
style={{ padding: '5px 8px', borderRadius: 8, border: '1.5px solid var(--warm-border)', fontFamily: 'Nunito', fontSize: 11 }}
|
||||
>
|
||||
{TASK_ICON_OPTIONS.map((opt) => (
|
||||
<option key={opt.key} value={opt.key}>{opt.label}</option>
|
||||
))}
|
||||
</select>
|
||||
</div>
|
||||
<div style={{ display: 'flex', gap: 8, justifyContent: 'flex-end' }}>
|
||||
<button onClick={() => { setShowAddTask(false); setNewTaskName(''); setNewTaskNotes(''); setNewTaskHealth(100); setNewTaskIconKey('sparkle'); }}
|
||||
className="tq-btn tq-btn-secondary" style={{ padding: '6px 16px', fontSize: 12 }}>{t('common.cancel')}</button>
|
||||
<button onClick={addTask} className="tq-btn tq-btn-primary"
|
||||
style={{ padding: '6px 16px', fontSize: 12 }}>{t('roomDetail.addTask')}</button>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
) : isAdmin ? (
|
||||
<div style={{ padding: '14px 8px' }}>
|
||||
<button onClick={() => setShowAddTask(true)}
|
||||
style={{
|
||||
background: 'none', border: '1.5px dashed var(--warm-border)', borderRadius: 12,
|
||||
padding: '10px 18px', cursor: 'pointer', display: 'flex', alignItems: 'center', gap: 8,
|
||||
fontSize: 13, fontWeight: 700, color: 'var(--warm-text-light)', fontFamily: 'Nunito', width: '100%',
|
||||
justifyContent: 'center',
|
||||
}}>
|
||||
<PlusIcon /> {t('roomDetail.addTask')}
|
||||
</button>
|
||||
</div>
|
||||
) : null}
|
||||
</div>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
541
client/src/components/pages/RoomsList.tsx
Normal file
541
client/src/components/pages/RoomsList.tsx
Normal file
|
|
@ -0,0 +1,541 @@
|
|||
import { useState, useEffect } from 'react';
|
||||
import HealthBar from '../shared/HealthBar';
|
||||
import { getRoomIcon } from '../icons/RoomIcons';
|
||||
import { TaskIcon, TASK_ICON_OPTIONS } from '../icons/TaskIcons';
|
||||
import { PlusIcon, TrashIcon } from '../icons/UIIcons';
|
||||
import { getHealthColor, getRoomHealth } from '../../utils/health';
|
||||
import { ROOM_COLORS } from '../../utils/colors';
|
||||
import { api } from '../../hooks/useApi';
|
||||
import { useTranslation } from '../../hooks/useTranslation';
|
||||
|
||||
const ROOM_TYPES = [
|
||||
{ type: 'kitchen' },
|
||||
{ type: 'bedroom' },
|
||||
{ type: 'bathroom' },
|
||||
{ type: 'living' },
|
||||
{ type: 'office' },
|
||||
{ type: 'garage' },
|
||||
{ type: 'laundry' },
|
||||
{ type: 'other' },
|
||||
];
|
||||
|
||||
const FREQ_UNITS = [
|
||||
{ label: 'hours', toDays: 1 / 24 },
|
||||
{ label: 'days', toDays: 1 },
|
||||
{ label: 'weeks', toDays: 7 },
|
||||
{ label: 'months', toDays: 30 },
|
||||
{ label: 'years', toDays: 365 },
|
||||
];
|
||||
|
||||
function daysToFreq(days: number): { value: number; unit: string } {
|
||||
if (days >= 365 && days % 365 === 0) return { value: days / 365, unit: 'years' };
|
||||
if (days >= 30 && days % 30 === 0) return { value: days / 30, unit: 'months' };
|
||||
if (days >= 7 && days % 7 === 0) return { value: days / 7, unit: 'weeks' };
|
||||
if (days >= 1) return { value: days, unit: 'days' };
|
||||
return { value: Math.round(days * 24), unit: 'hours' };
|
||||
}
|
||||
|
||||
function freqToDays(value: number, unit: string): number {
|
||||
const u = FREQ_UNITS.find(f => f.label === unit);
|
||||
return value * (u?.toDays || 1);
|
||||
}
|
||||
|
||||
interface TaskConfig {
|
||||
name: string;
|
||||
translationKey?: string;
|
||||
iconKey?: string;
|
||||
freqValue: number;
|
||||
freqUnit: string;
|
||||
effort: number;
|
||||
isSeasonal: boolean;
|
||||
selected: boolean;
|
||||
initialHealth: number;
|
||||
}
|
||||
|
||||
interface RoomsListProps {
|
||||
rooms: Array<{
|
||||
id: number;
|
||||
name: string;
|
||||
roomType: string;
|
||||
color: string;
|
||||
accentColor: string;
|
||||
health: number;
|
||||
tasks: Array<{ id: number; name: string; translationKey?: string; iconKey?: string; health: number }>;
|
||||
}>;
|
||||
language?: string;
|
||||
isAdmin: boolean;
|
||||
onSelectRoom: (roomId: number) => void;
|
||||
onCreateRoom: (data: { name: string; roomType: string; color: string; accentColor: string; tasks: any[] }) => void;
|
||||
onDeleteRoom: (roomId: number) => Promise<void>;
|
||||
}
|
||||
|
||||
export function RoomsList({ rooms, language, isAdmin, onSelectRoom, onCreateRoom, onDeleteRoom }: RoomsListProps) {
|
||||
const { taskName, t, roomName: translateRoomName, roomDisplayName } = useTranslation(language);
|
||||
const [showModal, setShowModal] = useState(false);
|
||||
const [step, setStep] = useState<1 | 2>(1);
|
||||
const [selectedType, setSelectedType] = useState('kitchen');
|
||||
const [roomName, setRoomName] = useState('');
|
||||
const [taskConfigs, setTaskConfigs] = useState<TaskConfig[]>([]);
|
||||
const [loadingTasks, setLoadingTasks] = useState(false);
|
||||
const [newTaskName, setNewTaskName] = useState('');
|
||||
|
||||
const sortedRooms = [...rooms].sort(
|
||||
(a, b) => getRoomHealth(a.tasks as any) - getRoomHealth(b.tasks as any)
|
||||
);
|
||||
|
||||
useEffect(() => {
|
||||
if (step === 2) {
|
||||
setLoadingTasks(true);
|
||||
api.getDefaultTasks(selectedType).then((defaults) => {
|
||||
setTaskConfigs(defaults.map((t) => {
|
||||
const { value, unit } = daysToFreq(t.frequencyDays);
|
||||
return {
|
||||
name: t.name,
|
||||
translationKey: (t as any).translationKey,
|
||||
iconKey: (t as any).iconKey || 'sparkle',
|
||||
freqValue: value,
|
||||
freqUnit: unit,
|
||||
effort: t.effort,
|
||||
isSeasonal: !!t.isSeasonal,
|
||||
selected: false,
|
||||
initialHealth: 100,
|
||||
};
|
||||
}));
|
||||
setLoadingTasks(false);
|
||||
}).catch(() => {
|
||||
setTaskConfigs([]);
|
||||
setLoadingTasks(false);
|
||||
});
|
||||
}
|
||||
}, [step, selectedType]);
|
||||
|
||||
const handleCreate = () => {
|
||||
const name = roomName.trim() || translateRoomName(selectedType) || t('rooms.room');
|
||||
const colors = ROOM_COLORS[selectedType] || ROOM_COLORS.other;
|
||||
const selectedTasks = taskConfigs.filter(t => t.selected).map(t => ({
|
||||
name: t.name,
|
||||
translationKey: t.translationKey,
|
||||
iconKey: t.iconKey || 'sparkle',
|
||||
frequencyDays: freqToDays(t.freqValue, t.freqUnit),
|
||||
effort: t.effort,
|
||||
isSeasonal: t.isSeasonal,
|
||||
initialHealth: t.initialHealth,
|
||||
}));
|
||||
onCreateRoom({ name, roomType: selectedType, color: colors.bg, accentColor: colors.accent, tasks: selectedTasks });
|
||||
closeModal();
|
||||
};
|
||||
|
||||
const closeModal = () => {
|
||||
setShowModal(false);
|
||||
setStep(1);
|
||||
setRoomName('');
|
||||
setSelectedType('kitchen');
|
||||
setTaskConfigs([]);
|
||||
setNewTaskName('');
|
||||
};
|
||||
|
||||
const updateTask = (idx: number, updates: Partial<TaskConfig>) => {
|
||||
setTaskConfigs(prev => prev.map((t, i) => i === idx ? { ...t, ...updates } : t));
|
||||
};
|
||||
|
||||
const addCustomTask = () => {
|
||||
if (!newTaskName.trim()) return;
|
||||
setTaskConfigs(prev => [...prev, {
|
||||
name: newTaskName.trim(),
|
||||
translationKey: undefined,
|
||||
iconKey: 'sparkle',
|
||||
freqValue: 1,
|
||||
freqUnit: 'weeks',
|
||||
effort: 2,
|
||||
isSeasonal: false,
|
||||
selected: true,
|
||||
initialHealth: 100,
|
||||
}]);
|
||||
setNewTaskName('');
|
||||
};
|
||||
|
||||
const removeTask = (idx: number) => {
|
||||
setTaskConfigs(prev => prev.filter((_, i) => i !== idx));
|
||||
};
|
||||
|
||||
const handleDeleteRoom = async (roomId: number, roomName: string) => {
|
||||
const shouldDelete = window.confirm(t('rooms.deleteRoomConfirm').replace('{room}', roomName));
|
||||
if (!shouldDelete) return;
|
||||
await onDeleteRoom(roomId);
|
||||
};
|
||||
|
||||
const healthLabel = (h: number): string =>
|
||||
h >= 70 ? t('rooms.healthHealthy') : h >= 40 ? t('rooms.healthNeedsAttention') : t('rooms.healthCritical');
|
||||
|
||||
const taskBadgeStyle = (health: number): { bg: string; text: string; border: string } => {
|
||||
if (health >= 70) {
|
||||
return { bg: '#E8F6EC', text: '#166534', border: '#86EFAC' };
|
||||
}
|
||||
if (health >= 40) {
|
||||
return { bg: '#FFF7E6', text: '#92400E', border: '#FCD34D' };
|
||||
}
|
||||
return { bg: '#FDECEC', text: '#991B1B', border: '#FCA5A5' };
|
||||
};
|
||||
|
||||
return (
|
||||
<>
|
||||
{isAdmin && (
|
||||
<div style={{ marginBottom: 20 }}>
|
||||
<button className="tq-btn tq-btn-primary"
|
||||
onClick={() => setShowModal(true)}
|
||||
style={{ padding: '10px 14px', fontSize: 14, display: 'inline-flex', alignItems: 'center', gap: 8 }}>
|
||||
<span style={{ display: 'flex', flexShrink: 0 }}>
|
||||
<svg width="18" height="18" viewBox="0 0 20 20" fill="none" aria-hidden>
|
||||
<path d="M10 4V16M4 10H16" stroke="#FFFFFF" strokeWidth="2.2" strokeLinecap="round" strokeLinejoin="round" />
|
||||
</svg>
|
||||
</span>
|
||||
<span>{t('rooms.addRoom')}</span>
|
||||
</button>
|
||||
</div>
|
||||
)}
|
||||
|
||||
<div className="page-enter" style={{
|
||||
display: 'grid',
|
||||
gridTemplateColumns: 'repeat(auto-fill, minmax(320px, 1fr))',
|
||||
gap: 16,
|
||||
}}>
|
||||
{sortedRooms.map((room) => {
|
||||
const rh = room.health;
|
||||
const RoomIcon = getRoomIcon(room.roomType);
|
||||
return (
|
||||
<div key={room.id} className="tq-card tq-card-hover"
|
||||
onClick={() => onSelectRoom(room.id)}
|
||||
style={{ padding: 24, cursor: 'pointer', position: 'relative' }}>
|
||||
{isAdmin && (
|
||||
<button
|
||||
className="tq-btn"
|
||||
onClick={(e) => {
|
||||
e.stopPropagation();
|
||||
handleDeleteRoom(room.id, room.name);
|
||||
}}
|
||||
aria-label={`${t('common.delete')} ${roomDisplayName(room.name, room.roomType)}`}
|
||||
title={`${t('common.delete')} ${roomDisplayName(room.name, room.roomType)}`}
|
||||
style={{
|
||||
position: 'absolute',
|
||||
top: 16,
|
||||
right: 16,
|
||||
width: 26,
|
||||
height: 26,
|
||||
borderRadius: 9,
|
||||
border: '1.5px solid var(--warm-danger-border)',
|
||||
backgroundColor: 'var(--warm-danger-bg)',
|
||||
color: 'var(--warm-danger)',
|
||||
display: 'inline-flex',
|
||||
alignItems: 'center',
|
||||
justifyContent: 'center',
|
||||
padding: 0,
|
||||
}}
|
||||
>
|
||||
<TrashIcon />
|
||||
</button>
|
||||
)}
|
||||
<div style={{ display: 'flex', alignItems: 'center', gap: 14, marginBottom: 16 }}>
|
||||
<div style={{
|
||||
width: 56, height: 56, borderRadius: 18,
|
||||
backgroundColor: room.color, display: 'flex', alignItems: 'center', justifyContent: 'center',
|
||||
border: `2px solid ${room.accentColor}33`,
|
||||
}}><RoomIcon /></div>
|
||||
<div style={{ flex: 1 }}>
|
||||
<div style={{ fontSize: 18, fontWeight: 800, color: 'var(--warm-text)' }}>{roomDisplayName(room.name, room.roomType)}</div>
|
||||
<div style={{ fontSize: 12, color: 'var(--warm-text-light)', fontWeight: 600 }}>
|
||||
{room.tasks.length} {t('rooms.tasks')} · {healthLabel(rh)}
|
||||
</div>
|
||||
</div>
|
||||
<div style={{ fontSize: 26, fontWeight: 900, color: getHealthColor(rh), marginRight: isAdmin ? 34 : 0 }}>{rh}%</div>
|
||||
</div>
|
||||
<HealthBar value={rh} height={10} showLabel={false} />
|
||||
<div style={{ display: 'flex', gap: 6, marginTop: 14, flexWrap: 'wrap' }}>
|
||||
{room.tasks.map((t) => {
|
||||
const badge = taskBadgeStyle(t.health);
|
||||
return (
|
||||
<div key={t.id} style={{
|
||||
fontSize: 11, fontWeight: 700, padding: '4px 10px 4px 6px', borderRadius: 10,
|
||||
backgroundColor: badge.bg, color: badge.text,
|
||||
border: `1px solid ${badge.border}`,
|
||||
display: 'inline-flex', alignItems: 'center', gap: 8,
|
||||
}}>
|
||||
<span style={{
|
||||
width: 30, height: 30, borderRadius: 10,
|
||||
display: 'inline-flex', alignItems: 'center', justifyContent: 'center',
|
||||
backgroundColor: 'rgba(255,255,255,0.45)', border: '1px solid rgba(255,255,255,0.6)',
|
||||
flexShrink: 0,
|
||||
marginLeft: -5,
|
||||
}}>
|
||||
<TaskIcon iconKey={t.iconKey} size={21} />
|
||||
</span>
|
||||
<span>{taskName(t.name, t.translationKey)}</span>
|
||||
</div>
|
||||
);
|
||||
})}
|
||||
</div>
|
||||
</div>
|
||||
);
|
||||
})}
|
||||
|
||||
{rooms.length === 0 && (
|
||||
<div style={{ gridColumn: '1 / -1', padding: 60, textAlign: 'center' }}>
|
||||
<div style={{ fontSize: 16, fontWeight: 700, color: 'var(--warm-text-light)', marginBottom: 8 }}>{t('rooms.noRoomsYet')}</div>
|
||||
<div style={{ fontSize: 13, color: 'var(--warm-text-light)' }}>{t('rooms.clickAddRoom')}</div>
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
|
||||
{/* Create Room Modal */}
|
||||
{showModal && (
|
||||
<div style={{
|
||||
position: 'fixed', inset: 0, backgroundColor: 'rgba(0,0,0,0.3)',
|
||||
display: 'flex', alignItems: 'center', justifyContent: 'center', zIndex: 100,
|
||||
}} onClick={closeModal}>
|
||||
<div className="tq-card" style={{ width: step === 1 ? 480 : 680, maxHeight: '85vh', overflow: 'hidden', boxSizing: 'border-box' }}
|
||||
onClick={(e) => e.stopPropagation()}>
|
||||
<div style={{ padding: 32, maxHeight: '85vh', overflowY: 'auto', overflowX: 'hidden', boxSizing: 'border-box' }}>
|
||||
|
||||
{step === 1 ? (
|
||||
<>
|
||||
<h2 style={{ fontSize: 20, fontWeight: 900, color: 'var(--warm-text)', margin: '0 0 6px' }}>{t('rooms.addRoomTitle')}</h2>
|
||||
<p style={{ fontSize: 12, color: 'var(--warm-text-light)', fontWeight: 600, marginBottom: 20 }}>
|
||||
{t('rooms.pickRoomType')}
|
||||
</p>
|
||||
|
||||
<div style={{ display: 'grid', gridTemplateColumns: 'repeat(4, 1fr)', gap: 10, marginBottom: 20 }}>
|
||||
{ROOM_TYPES.map((rt) => {
|
||||
const colors = ROOM_COLORS[rt.type] || ROOM_COLORS.other;
|
||||
const Icon = getRoomIcon(rt.type);
|
||||
const isSelected = selectedType === rt.type;
|
||||
return (
|
||||
<div key={rt.type}
|
||||
onClick={() => setSelectedType(rt.type)}
|
||||
style={{
|
||||
padding: '14px 8px', borderRadius: 16, textAlign: 'center', cursor: 'pointer',
|
||||
backgroundColor: isSelected ? colors.bg : 'var(--warm-bg-subtle)',
|
||||
border: isSelected ? `2px solid ${colors.accent}` : '2px solid var(--warm-border)',
|
||||
transition: 'all 0.15s ease',
|
||||
}}>
|
||||
<div style={{
|
||||
width: 40, height: 40, borderRadius: 12, margin: '0 auto 8px',
|
||||
backgroundColor: colors.bg, display: 'flex', alignItems: 'center', justifyContent: 'center',
|
||||
}}><Icon /></div>
|
||||
<div style={{ fontSize: 11, fontWeight: 700, color: isSelected ? colors.accent : 'var(--warm-text-muted)' }}>
|
||||
{translateRoomName(rt.type)}
|
||||
</div>
|
||||
</div>
|
||||
);
|
||||
})}
|
||||
</div>
|
||||
|
||||
<div style={{ marginBottom: 24 }}>
|
||||
<label style={{ fontSize: 12, fontWeight: 700, color: 'var(--warm-text-muted)', display: 'block', marginBottom: 6 }}>
|
||||
{t('rooms.customNameOptional')}
|
||||
</label>
|
||||
<input value={roomName} onChange={(e) => setRoomName(e.target.value)}
|
||||
placeholder={translateRoomName(selectedType)}
|
||||
style={{
|
||||
width: '100%', padding: '10px 14px', borderRadius: 12, border: '1.5px solid var(--warm-border)',
|
||||
fontSize: 14, fontFamily: 'Nunito', fontWeight: 600, color: 'var(--warm-text)',
|
||||
outline: 'none', backgroundColor: 'var(--warm-bg-subtle)', boxSizing: 'border-box',
|
||||
}} />
|
||||
</div>
|
||||
|
||||
<div style={{ display: 'flex', gap: 10, justifyContent: 'flex-end' }}>
|
||||
<button className="tq-btn tq-btn-secondary" onClick={closeModal}
|
||||
style={{ padding: '10px 22px', fontSize: 13 }}>{t('common.cancel')}</button>
|
||||
<button className="tq-btn tq-btn-primary" onClick={() => setStep(2)}
|
||||
style={{ padding: '10px 22px', fontSize: 13 }}>{t('rooms.nextConfigure')}</button>
|
||||
</div>
|
||||
</>
|
||||
) : (
|
||||
<>
|
||||
<div style={{ display: 'flex', alignItems: 'center', gap: 12, marginBottom: 6 }}>
|
||||
<button onClick={() => setStep(1)} style={{
|
||||
background: 'none', border: 'none', cursor: 'pointer', padding: 4,
|
||||
color: 'var(--warm-text-light)', fontSize: 18, fontWeight: 700,
|
||||
}}>←</button>
|
||||
<h2 style={{ fontSize: 20, fontWeight: 900, color: 'var(--warm-text)', margin: 0 }}>{t('rooms.configureTasks')}</h2>
|
||||
</div>
|
||||
<p style={{ fontSize: 12, color: 'var(--warm-text-light)', fontWeight: 600, marginBottom: 16 }}>
|
||||
{t('rooms.configureTasksDesc')}
|
||||
</p>
|
||||
|
||||
{loadingTasks ? (
|
||||
<div style={{ padding: 30, textAlign: 'center', color: 'var(--warm-text-light)', fontWeight: 600 }}>{t('common.loading')}...</div>
|
||||
) : (
|
||||
<div style={{ display: 'flex', flexDirection: 'column', gap: 8, marginBottom: 16 }}>
|
||||
{taskConfigs.map((task, idx) => {
|
||||
const healthColor = task.initialHealth >= 70 ? '#22C55E' : task.initialHealth >= 40 ? '#F59E0B' : '#EF4444';
|
||||
return (
|
||||
<div key={idx} style={{
|
||||
padding: '14px 16px', borderRadius: 14,
|
||||
backgroundColor: task.selected ? 'var(--warm-bg-subtle)' : 'var(--warm-bg-warm)',
|
||||
border: task.selected ? '1.5px solid var(--warm-border)' : '1.5px solid var(--warm-border-subtle)',
|
||||
opacity: task.selected ? 1 : 0.6,
|
||||
transition: 'all 0.15s ease',
|
||||
}}>
|
||||
<div style={{ display: 'flex', alignItems: 'center', gap: 10, marginBottom: task.selected ? 12 : 0 }}>
|
||||
<input type="checkbox" checked={task.selected}
|
||||
onChange={(e) => updateTask(idx, { selected: e.target.checked })}
|
||||
style={{ width: 18, height: 18, accentColor: '#F97316', cursor: 'pointer' }} />
|
||||
<div style={{ flex: 1, fontSize: 14, fontWeight: 800, color: 'var(--warm-text)', display: 'flex', alignItems: 'center', gap: 9 }}>
|
||||
<span style={{
|
||||
width: 32, height: 32, borderRadius: 10,
|
||||
display: 'inline-flex', alignItems: 'center', justifyContent: 'center',
|
||||
backgroundColor: 'var(--warm-bg-warm)', border: '1px solid var(--warm-border)',
|
||||
flexShrink: 0,
|
||||
marginLeft: -6,
|
||||
}}>
|
||||
<TaskIcon iconKey={task.iconKey} size={22} />
|
||||
</span>
|
||||
<span>{taskName(task.name, task.translationKey)}</span>
|
||||
</div>
|
||||
<button onClick={() => removeTask(idx)} style={{
|
||||
background: 'none', border: 'none', cursor: 'pointer', color: 'var(--warm-text-light)',
|
||||
fontSize: 18, fontWeight: 700, padding: '0 4px', lineHeight: 1,
|
||||
}}>×</button>
|
||||
</div>
|
||||
|
||||
{task.selected && (
|
||||
<div style={{ display: 'grid', gridTemplateColumns: '1fr 1fr 1fr 1fr', gap: 12, paddingLeft: 28 }}>
|
||||
{/* Current State */}
|
||||
<div>
|
||||
<div style={{ fontSize: 10, fontWeight: 700, color: 'var(--warm-text-light)', textTransform: 'uppercase', marginBottom: 6 }}>
|
||||
{t('rooms.currentState')}
|
||||
</div>
|
||||
<div style={{ display: 'flex', alignItems: 'center', gap: 8 }}>
|
||||
<input type="range" min={0} max={100} step={10}
|
||||
value={task.initialHealth}
|
||||
onChange={(e) => updateTask(idx, { initialHealth: parseInt(e.target.value) })}
|
||||
style={{ flex: 1, accentColor: healthColor }} />
|
||||
<span style={{ fontSize: 12, fontWeight: 800, color: healthColor, minWidth: 36, textAlign: 'right' }}>
|
||||
{task.initialHealth}%
|
||||
</span>
|
||||
</div>
|
||||
<div style={{ display: 'flex', justifyContent: 'space-between', fontSize: 9, color: 'var(--warm-text-light)', fontWeight: 600, marginTop: 2 }}>
|
||||
<span>{t('rooms.dirty')}</span><span>{t('rooms.clean')}</span>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
{/* Effort */}
|
||||
<div>
|
||||
<div style={{ fontSize: 10, fontWeight: 700, color: 'var(--warm-text-light)', textTransform: 'uppercase', marginBottom: 6 }}>
|
||||
{t('roomDetail.effort')}
|
||||
</div>
|
||||
<div style={{ display: 'flex', gap: 2 }}>
|
||||
{[1, 2, 3, 4, 5].map((e) => (
|
||||
<button key={e} onClick={() => updateTask(idx, { effort: e })}
|
||||
style={{
|
||||
background: 'none', border: 'none', cursor: 'pointer', padding: 1,
|
||||
opacity: e <= task.effort ? 1 : 0.3,
|
||||
transform: e <= task.effort ? 'scale(1.1)' : 'scale(1)',
|
||||
transition: 'all 0.1s ease',
|
||||
}}>
|
||||
<svg width="16" height="16" viewBox="0 0 14 14" fill="none">
|
||||
<path d="M7 1L8.5 5H12.5L9.5 7.5L10.5 11.5L7 9L3.5 11.5L4.5 7.5L1.5 5H5.5L7 1Z"
|
||||
fill={e <= task.effort ? '#F59E0B' : 'none'}
|
||||
stroke={e <= task.effort ? '#F59E0B' : '#E2D5C5'}
|
||||
strokeWidth={e <= task.effort ? '0.5' : '1'} />
|
||||
</svg>
|
||||
</button>
|
||||
))}
|
||||
</div>
|
||||
</div>
|
||||
|
||||
{/* Frequency */}
|
||||
<div>
|
||||
<div style={{ fontSize: 10, fontWeight: 700, color: 'var(--warm-text-light)', textTransform: 'uppercase', marginBottom: 6 }}>
|
||||
{t('roomDetail.frequency')}
|
||||
</div>
|
||||
<div style={{ display: 'flex', gap: 4, alignItems: 'center' }}>
|
||||
<input type="number" min={1} max={999} value={task.freqValue}
|
||||
onChange={(e) => updateTask(idx, { freqValue: Math.max(1, parseInt(e.target.value) || 1) })}
|
||||
style={{
|
||||
width: 48, padding: '5px 6px', borderRadius: 8, border: '1.5px solid var(--warm-border)',
|
||||
fontSize: 12, fontFamily: 'Nunito', fontWeight: 700, color: 'var(--warm-text)',
|
||||
outline: 'none', backgroundColor: '#fff', textAlign: 'center',
|
||||
}} />
|
||||
<select value={task.freqUnit}
|
||||
onChange={(e) => updateTask(idx, { freqUnit: e.target.value })}
|
||||
style={{
|
||||
padding: '5px 6px', borderRadius: 8, border: '1.5px solid var(--warm-border)',
|
||||
fontSize: 11, fontFamily: 'Nunito', fontWeight: 600, color: 'var(--warm-text)',
|
||||
backgroundColor: '#fff', outline: 'none', cursor: 'pointer',
|
||||
}}>
|
||||
{FREQ_UNITS.map((f) => (
|
||||
<option key={f.label} value={f.label}>{t(`units.${f.label}`)}</option>
|
||||
))}
|
||||
</select>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
{/* Icon */}
|
||||
<div>
|
||||
<div style={{ fontSize: 10, fontWeight: 700, color: 'var(--warm-text-light)', textTransform: 'uppercase', marginBottom: 6 }}>
|
||||
Icon
|
||||
</div>
|
||||
<select
|
||||
value={task.iconKey || 'sparkle'}
|
||||
onChange={(e) => updateTask(idx, { iconKey: e.target.value })}
|
||||
style={{
|
||||
width: '100%', padding: '5px 6px', borderRadius: 8, border: '1.5px solid var(--warm-border)',
|
||||
fontSize: 11, fontFamily: 'Nunito', fontWeight: 600, color: 'var(--warm-text)',
|
||||
backgroundColor: '#fff', outline: 'none', cursor: 'pointer',
|
||||
}}
|
||||
>
|
||||
{TASK_ICON_OPTIONS.map((opt) => (
|
||||
<option key={opt.key} value={opt.key}>{opt.label}</option>
|
||||
))}
|
||||
</select>
|
||||
</div>
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
);
|
||||
})}
|
||||
|
||||
{/* Add Custom Task */}
|
||||
<div style={{
|
||||
padding: '10px 16px', borderRadius: 14, border: '1.5px dashed var(--warm-border)',
|
||||
display: 'flex', alignItems: 'center', gap: 10,
|
||||
}}>
|
||||
<PlusIcon />
|
||||
<input value={newTaskName}
|
||||
onChange={(e) => setNewTaskName(e.target.value)}
|
||||
onKeyDown={(e) => e.key === 'Enter' && addCustomTask()}
|
||||
placeholder={t('rooms.addCustomTask')}
|
||||
style={{
|
||||
flex: 1, padding: '6px 0', border: 'none', outline: 'none',
|
||||
fontSize: 13, fontFamily: 'Nunito', fontWeight: 600, color: 'var(--warm-text)',
|
||||
backgroundColor: 'transparent',
|
||||
}} />
|
||||
<button onClick={addCustomTask} className="tq-btn tq-btn-secondary"
|
||||
style={{ padding: '6px 14px', fontSize: 12 }}>{t('common.add')}</button>
|
||||
</div>
|
||||
</div>
|
||||
)}
|
||||
|
||||
<div style={{ display: 'flex', gap: 10, justifyContent: 'space-between', alignItems: 'center' }}>
|
||||
<div style={{ fontSize: 12, color: 'var(--warm-text-light)', fontWeight: 600 }}>
|
||||
{taskConfigs.filter(t => t.selected).length} {t('rooms.tasksSelected')}
|
||||
</div>
|
||||
<div style={{ display: 'flex', gap: 10 }}>
|
||||
<button className="tq-btn tq-btn-secondary" onClick={closeModal}
|
||||
style={{ padding: '10px 22px', fontSize: 13 }}>{t('common.cancel')}</button>
|
||||
<button className="tq-btn tq-btn-primary" onClick={handleCreate}
|
||||
disabled={taskConfigs.filter(t => t.selected).length === 0}
|
||||
style={{ padding: '10px 22px', fontSize: 13 }}>{t('rooms.createRoom')}</button>
|
||||
</div>
|
||||
</div>
|
||||
</>
|
||||
)}
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
)}
|
||||
</>
|
||||
);
|
||||
}
|
||||
|
||||
export default RoomsList;
|
||||
750
client/src/components/pages/Settings.tsx
Normal file
750
client/src/components/pages/Settings.tsx
Normal file
|
|
@ -0,0 +1,750 @@
|
|||
import { useEffect, useState } from 'react';
|
||||
import { UserAvatar } from '../shared/UserAvatar';
|
||||
import { EffortDots } from '../shared/EffortDots';
|
||||
import { Toggle } from '../shared/Toggle';
|
||||
import { BellIcon, DownloadIcon, UploadIcon, LockIcon, CoinIcon } from '../icons/UIIcons';
|
||||
import { AVATAR_PRESETS } from '../icons/AvatarPresets';
|
||||
import { useTranslation } from '../../hooks/useTranslation';
|
||||
import type { User } from '../../hooks/useAuth';
|
||||
import { api } from '../../hooks/useApi';
|
||||
|
||||
interface FamilyUser {
|
||||
id: number;
|
||||
displayName: string;
|
||||
role?: 'admin' | 'member' | 'child';
|
||||
avatarColor: string;
|
||||
avatarType?: string;
|
||||
avatarPreset?: string;
|
||||
avatarPhotoUrl?: string;
|
||||
coins: number;
|
||||
currentStreak: number;
|
||||
language?: string;
|
||||
goalCoins?: number | null;
|
||||
goalStartAt?: string | null;
|
||||
goalEndAt?: string | null;
|
||||
}
|
||||
|
||||
interface SettingsProps {
|
||||
user: User;
|
||||
family: FamilyUser[];
|
||||
onToggleVacation: (enabled: boolean) => void;
|
||||
onUpdateRole: (userId: number, role: 'admin' | 'member' | 'child') => void;
|
||||
onAddMember: (data: { username: string; password: string; displayName: string; role: 'child' }) => Promise<void>;
|
||||
onDeleteUser: (userId: number) => Promise<void>;
|
||||
onUpdateMemberProfile: (userId: number, data: { avatarType?: string; avatarColor?: string; avatarPreset?: string | null; language?: string }) => Promise<void>;
|
||||
onChangePassword: (userId: number, data: { currentPassword?: string; newPassword: string }) => Promise<void>;
|
||||
coinsByEffort: Record<number, number>;
|
||||
onSaveCoinsByEffort: (values: Record<number, number>) => Promise<void>;
|
||||
onResetCoinsByEffort: () => Promise<void>;
|
||||
theme: 'orange' | 'blue' | 'rose' | 'night';
|
||||
onChangeTheme: (theme: 'orange' | 'blue' | 'rose' | 'night') => void;
|
||||
onExport: () => void;
|
||||
onImport: () => void;
|
||||
}
|
||||
|
||||
const COLORS = ['#F97316', '#9B72CF', '#4AABDE', '#5CB85C', '#D4A017', '#E25A5A', '#38BDF8', '#EC4899'];
|
||||
|
||||
export function Settings({
|
||||
user,
|
||||
family,
|
||||
onToggleVacation,
|
||||
onUpdateRole,
|
||||
onAddMember,
|
||||
onDeleteUser,
|
||||
onUpdateMemberProfile,
|
||||
onChangePassword,
|
||||
coinsByEffort,
|
||||
onSaveCoinsByEffort,
|
||||
onResetCoinsByEffort,
|
||||
theme,
|
||||
onChangeTheme,
|
||||
onExport,
|
||||
onImport,
|
||||
}: SettingsProps) {
|
||||
const { t } = useTranslation(user.language);
|
||||
const isAdmin = user.role === 'admin';
|
||||
const [showAddMember, setShowAddMember] = useState(false);
|
||||
const [newMemberName, setNewMemberName] = useState('');
|
||||
const [newMemberUsername, setNewMemberUsername] = useState('');
|
||||
const [newMemberPassword, setNewMemberPassword] = useState('');
|
||||
const [coinsDraft, setCoinsDraft] = useState<Record<number, number>>(coinsByEffort);
|
||||
const [memberEditOpen, setMemberEditOpen] = useState<Record<number, boolean>>({});
|
||||
const [memberPassword, setMemberPassword] = useState<Record<number, string>>({});
|
||||
const [memberPasswordMsg, setMemberPasswordMsg] = useState<Record<number, string>>({});
|
||||
const [memberGoals, setMemberGoals] = useState<Record<number, Array<{ id: number; title: string; goalCoins: number; startAt?: string | null; endAt?: string | null }>>>({});
|
||||
const [goalDraft, setGoalDraft] = useState<Record<number, { title: string; goalCoins: string; endAt: string }>>({});
|
||||
const [rewardsAdmin, setRewardsAdmin] = useState<Array<{ id: number; title: string; description?: string | null; costCoins: number; isActive?: boolean; isPreset?: boolean }>>([]);
|
||||
const [rewardRequests, setRewardRequests] = useState<Array<{ id: number; title: string; displayName: string; costCoins: number; redeemedAt: string; status: string }>>([]);
|
||||
const [rewardDraft, setRewardDraft] = useState({ title: '', description: '', costCoins: '30' });
|
||||
const [memberProfile, setMemberProfile] = useState<Record<number, {
|
||||
language: string;
|
||||
avatarType: 'letter' | 'preset';
|
||||
avatarColor: string;
|
||||
avatarPreset: string;
|
||||
}>>({});
|
||||
const [memberProfileMsg, setMemberProfileMsg] = useState<Record<number, string>>({});
|
||||
const [memberGoalMsg, setMemberGoalMsg] = useState<Record<number, string>>({});
|
||||
const [notifEnabled, setNotifEnabled] = useState(false);
|
||||
const [notifChatId, setNotifChatId] = useState('');
|
||||
const [notifToken, setNotifToken] = useState('');
|
||||
const [notifTime, setNotifTime] = useState('09:00');
|
||||
const [notifTypes, setNotifTypes] = useState({ taskDue: true, rewardRequest: true, achievementUnlocked: true });
|
||||
const [notifHasToken, setNotifHasToken] = useState(false);
|
||||
const [notifMsg, setNotifMsg] = useState('');
|
||||
|
||||
const localeMap: Record<string, string> = { en: 'en-US', fr: 'fr-FR', de: 'de-DE', es: 'es-ES' };
|
||||
const locale = localeMap[user.language || 'en'] || 'en-US';
|
||||
|
||||
const formatDate = (isoDate?: string | null): string => {
|
||||
if (!isoDate) return '-';
|
||||
const d = new Date(isoDate);
|
||||
if (Number.isNaN(d.getTime())) return '-';
|
||||
return d.toLocaleDateString(locale);
|
||||
};
|
||||
|
||||
const rewardStatusLabel = (status: string): string => {
|
||||
if (status === 'requested') return t('rewards.statusPending');
|
||||
if (status === 'approved') return t('rewards.statusApproved');
|
||||
if (status === 'rejected') return t('rewards.statusRejected');
|
||||
if (status === 'cancelled') return t('rewards.statusCancelled');
|
||||
return status;
|
||||
};
|
||||
|
||||
const rewardPresetKeyByTitle: Record<string, string> = {
|
||||
'movie night pick': 'movie_night',
|
||||
'ice cream treat': 'ice_cream',
|
||||
'stay up 30 min': 'late_bedtime',
|
||||
'game time bonus': 'game_bonus',
|
||||
'choose dinner': 'choose_dinner',
|
||||
'park adventure': 'park_adventure',
|
||||
'no-chore pass': 'chore_pass',
|
||||
'family board game': 'board_game',
|
||||
};
|
||||
|
||||
const rewardTitle = (r: { title: string; isPreset?: boolean }): string => {
|
||||
const k = rewardPresetKeyByTitle[r.title.toLowerCase()];
|
||||
if (k) return t(`rewardsPreset.${k}.title`);
|
||||
return r.title;
|
||||
};
|
||||
|
||||
const rewardDesc = (r: { title: string; description?: string | null; isPreset?: boolean }): string => {
|
||||
const k = rewardPresetKeyByTitle[r.title.toLowerCase()];
|
||||
if (k) return t(`rewardsPreset.${k}.desc`);
|
||||
return r.description || '-';
|
||||
};
|
||||
|
||||
useEffect(() => {
|
||||
setCoinsDraft(coinsByEffort);
|
||||
}, [coinsByEffort]);
|
||||
|
||||
useEffect(() => {
|
||||
if (!isAdmin) return;
|
||||
api.getNotificationsConfig()
|
||||
.then((cfg) => {
|
||||
setNotifEnabled(!!cfg.enabled);
|
||||
setNotifChatId(cfg.chatId || '');
|
||||
setNotifTime(cfg.notificationTime || '09:00');
|
||||
setNotifTypes(cfg.notificationTypes || { taskDue: true, rewardRequest: true, achievementUnlocked: true });
|
||||
setNotifHasToken(!!cfg.hasToken);
|
||||
})
|
||||
.catch(() => {});
|
||||
}, [isAdmin]);
|
||||
|
||||
const loadAdminGoals = async () => {
|
||||
if (!isAdmin) return;
|
||||
const entries = await Promise.all(
|
||||
family.filter((u) => u.id !== user.id && u.role !== 'admin').map(async (u) => ({ userId: u.id, goals: await api.getUserGoals(u.id) }))
|
||||
);
|
||||
const next: Record<number, Array<{ id: number; title: string; goalCoins: number; startAt?: string | null; endAt?: string | null }>> = {};
|
||||
entries.forEach((e) => { next[e.userId] = e.goals; });
|
||||
setMemberGoals(next);
|
||||
};
|
||||
|
||||
const loadRewardsAdmin = async () => {
|
||||
if (!isAdmin) return;
|
||||
const data = await api.getRewardsAdmin();
|
||||
setRewardsAdmin(data.rewards || []);
|
||||
setRewardRequests(data.redemptions || []);
|
||||
};
|
||||
|
||||
useEffect(() => {
|
||||
if (!isAdmin) return;
|
||||
void loadAdminGoals();
|
||||
void loadRewardsAdmin();
|
||||
// eslint-disable-next-line react-hooks/exhaustive-deps
|
||||
}, [isAdmin, family.length]);
|
||||
|
||||
const resetMemberForm = () => {
|
||||
setShowAddMember(false);
|
||||
setNewMemberName('');
|
||||
setNewMemberUsername('');
|
||||
setNewMemberPassword('');
|
||||
};
|
||||
|
||||
const initMemberProfile = (u: FamilyUser) => {
|
||||
setMemberProfile((prev) => ({
|
||||
...prev,
|
||||
[u.id]: prev[u.id] || {
|
||||
language: u.language || 'en',
|
||||
avatarType: u.avatarType === 'preset' ? 'preset' : 'letter',
|
||||
avatarColor: u.avatarColor || '#F97316',
|
||||
avatarPreset: u.avatarPreset || 'cat',
|
||||
},
|
||||
}));
|
||||
};
|
||||
|
||||
const handleAddMember = async () => {
|
||||
if (!newMemberName.trim() || !newMemberUsername.trim() || !newMemberPassword.trim()) return;
|
||||
await onAddMember({
|
||||
displayName: newMemberName.trim(),
|
||||
username: newMemberUsername.trim(),
|
||||
password: newMemberPassword,
|
||||
role: 'child',
|
||||
});
|
||||
resetMemberForm();
|
||||
};
|
||||
|
||||
const handleSaveChildProfile = async (u: FamilyUser) => {
|
||||
const p = memberProfile[u.id];
|
||||
if (!p) return;
|
||||
await onUpdateMemberProfile(u.id, {
|
||||
language: p.language,
|
||||
avatarType: p.avatarType,
|
||||
avatarColor: p.avatarColor,
|
||||
avatarPreset: p.avatarType === 'preset' ? p.avatarPreset : null,
|
||||
});
|
||||
setMemberProfileMsg((prev) => ({ ...prev, [u.id]: t('common.saved') }));
|
||||
window.setTimeout(() => {
|
||||
setMemberProfileMsg((prev) => ({ ...prev, [u.id]: '' }));
|
||||
}, 2000);
|
||||
};
|
||||
|
||||
const handleSetChildPassword = async (u: FamilyUser) => {
|
||||
const pwd = memberPassword[u.id] || '';
|
||||
if (!pwd.trim()) return;
|
||||
try {
|
||||
await onChangePassword(u.id, { newPassword: pwd });
|
||||
setMemberPassword((prev) => ({ ...prev, [u.id]: '' }));
|
||||
setMemberPasswordMsg((prev) => ({ ...prev, [u.id]: t('settings.passwordUpdated') }));
|
||||
} catch (err: any) {
|
||||
setMemberPasswordMsg((prev) => ({ ...prev, [u.id]: err?.message || t('settings.passwordUpdateFailed') }));
|
||||
}
|
||||
};
|
||||
|
||||
const handleAddGoal = async (u: FamilyUser) => {
|
||||
const d = goalDraft[u.id] || { title: '', goalCoins: '', endAt: '' };
|
||||
if (!d.title.trim() || !d.goalCoins.trim()) return;
|
||||
const goalCoins = Math.max(1, Math.round(Number(d.goalCoins)));
|
||||
await api.createUserGoal(u.id, {
|
||||
title: d.title.trim(),
|
||||
goalCoins,
|
||||
startAt: null,
|
||||
endAt: d.endAt ? `${d.endAt}T23:59:59.999Z` : null,
|
||||
});
|
||||
setGoalDraft((prev) => ({ ...prev, [u.id]: { title: '', goalCoins: '', endAt: '' } }));
|
||||
await loadAdminGoals();
|
||||
};
|
||||
|
||||
const handleDeleteGoal = async (goalId: number, userId: number) => {
|
||||
try {
|
||||
await api.deleteGoal(goalId);
|
||||
await loadAdminGoals();
|
||||
setMemberGoalMsg((prev) => ({ ...prev, [userId]: t('settings.goalDeleted') }));
|
||||
} catch (err: any) {
|
||||
setMemberGoalMsg((prev) => ({ ...prev, [userId]: err?.message || t('settings.goalDeleteFailed') }));
|
||||
}
|
||||
window.setTimeout(() => {
|
||||
setMemberGoalMsg((prev) => ({ ...prev, [userId]: '' }));
|
||||
}, 2500);
|
||||
};
|
||||
|
||||
const handleCreateReward = async () => {
|
||||
if (!rewardDraft.title.trim() || !rewardDraft.costCoins.trim()) return;
|
||||
await api.createReward({
|
||||
title: rewardDraft.title.trim(),
|
||||
description: rewardDraft.description.trim(),
|
||||
costCoins: Math.max(1, Math.round(Number(rewardDraft.costCoins))),
|
||||
});
|
||||
setRewardDraft({ title: '', description: '', costCoins: '30' });
|
||||
await loadRewardsAdmin();
|
||||
};
|
||||
|
||||
const handleSeedRewards = async () => {
|
||||
const presets = [
|
||||
{ title: 'Movie Night Pick', description: 'Choisir le film du soir en famille.', costCoins: 40 },
|
||||
{ title: 'Ice Cream Treat', description: 'Une glace ou un dessert special.', costCoins: 30 },
|
||||
{ title: 'Stay Up 30 Min', description: 'Se coucher 30 minutes plus tard.', costCoins: 35 },
|
||||
{ title: 'Game Time Bonus', description: '30 minutes de jeu supplementaire.', costCoins: 50 },
|
||||
{ title: 'Choose Dinner', description: 'Choisir le menu du diner.', costCoins: 45 },
|
||||
{ title: 'Park Adventure', description: 'Sortie au parc en mode aventure.', costCoins: 60 },
|
||||
{ title: 'No-Chore Pass', description: 'Une tache au choix sautee cette semaine.', costCoins: 80 },
|
||||
{ title: 'Family Board Game', description: 'Choisir un jeu de societe pour la soiree.', costCoins: 25 },
|
||||
];
|
||||
const existing = new Set(rewardsAdmin.map((r) => r.title.toLowerCase()));
|
||||
for (const p of presets) {
|
||||
if (!existing.has(p.title.toLowerCase())) {
|
||||
await api.createReward(p);
|
||||
}
|
||||
}
|
||||
await loadRewardsAdmin();
|
||||
};
|
||||
|
||||
const saveNotifications = async () => {
|
||||
setNotifMsg('');
|
||||
try {
|
||||
if (notifEnabled && !notifChatId.trim()) {
|
||||
setNotifMsg(t('settings.telegramChatIdRequired'));
|
||||
return;
|
||||
}
|
||||
if (notifEnabled && !notifHasToken && !notifToken.trim()) {
|
||||
setNotifMsg(t('settings.telegramTokenRequired'));
|
||||
return;
|
||||
}
|
||||
|
||||
const payload: {
|
||||
enabled: boolean;
|
||||
chatId: string;
|
||||
notificationTime: string;
|
||||
notificationTypes: { taskDue: boolean; rewardRequest: boolean; achievementUnlocked: boolean };
|
||||
botToken?: string;
|
||||
} = {
|
||||
enabled: notifEnabled,
|
||||
chatId: notifChatId.trim(),
|
||||
notificationTime: notifTime,
|
||||
notificationTypes: notifTypes,
|
||||
};
|
||||
if (notifToken.trim()) payload.botToken = notifToken.trim();
|
||||
const next = await api.updateNotificationsConfig(payload);
|
||||
setNotifEnabled(next.enabled);
|
||||
setNotifChatId(next.chatId || '');
|
||||
setNotifTime(next.notificationTime || '09:00');
|
||||
setNotifTypes(next.notificationTypes || { taskDue: true, rewardRequest: true, achievementUnlocked: true });
|
||||
setNotifHasToken(next.hasToken);
|
||||
setNotifToken('');
|
||||
setNotifMsg(t('settings.notificationsSaved'));
|
||||
} catch (err: any) {
|
||||
setNotifMsg(err?.message || t('settings.notificationsSaveFailed'));
|
||||
}
|
||||
};
|
||||
|
||||
const testNotifications = async () => {
|
||||
setNotifMsg('');
|
||||
try {
|
||||
await api.sendNotificationsTest({
|
||||
chatId: notifChatId.trim() || undefined,
|
||||
botToken: notifToken.trim() || undefined,
|
||||
});
|
||||
setNotifMsg(t('settings.notificationsTestSent'));
|
||||
} catch (err: any) {
|
||||
setNotifMsg(err?.message || t('settings.notificationsTestFailed'));
|
||||
}
|
||||
};
|
||||
|
||||
const saveCoins = async () => {
|
||||
await onSaveCoinsByEffort(coinsDraft);
|
||||
};
|
||||
|
||||
const resetCoins = async () => {
|
||||
await onResetCoinsByEffort();
|
||||
setCoinsDraft({ 1: 5, 2: 10, 3: 15, 4: 20, 5: 25 });
|
||||
};
|
||||
|
||||
return (
|
||||
<div className="page-enter" style={{ display: 'grid', gridTemplateColumns: '1fr 1fr', gap: 20, maxWidth: 980 }}>
|
||||
<div className="tq-card" style={{ padding: 24 }}>
|
||||
<h3 style={{ fontSize: 15, fontWeight: 800, color: 'var(--warm-text)', margin: '0 0 18px' }}>{t('settings.general')}</h3>
|
||||
<div style={{ display: 'flex', alignItems: 'center', gap: 14, padding: '14px 0', borderBottom: isAdmin ? 'none' : '1px solid var(--warm-border)' }}>
|
||||
<BellIcon />
|
||||
<div style={{ flex: 1 }}>
|
||||
<div style={{ fontSize: 14, fontWeight: 700, color: 'var(--warm-text)' }}>{t('settings.notifications')}</div>
|
||||
<div style={{ fontSize: 11, color: 'var(--warm-text-light)', fontWeight: 600 }}>{t('settings.notificationsDesc')}</div>
|
||||
</div>
|
||||
<Toggle checked={notifEnabled} onChange={isAdmin ? setNotifEnabled : () => {}} />
|
||||
</div>
|
||||
{isAdmin && (
|
||||
<div style={{ display: 'grid', gap: 8, marginTop: 10, marginBottom: 8, padding: 10, border: '1px solid var(--warm-border)', borderRadius: 10 }}>
|
||||
{notifEnabled ? (
|
||||
<>
|
||||
<div style={{ display: 'grid', gap: 4 }}>
|
||||
<label style={{ fontSize: 11, fontWeight: 700, color: 'var(--warm-text-muted)' }}>{t('settings.notificationTime')}</label>
|
||||
<input
|
||||
type="time"
|
||||
value={notifTime}
|
||||
onChange={(e) => setNotifTime(e.target.value || '09:00')}
|
||||
style={{ padding: '7px 10px', borderRadius: 10, border: '1.5px solid var(--warm-border)', fontFamily: 'Nunito' }}
|
||||
/>
|
||||
</div>
|
||||
<input
|
||||
value={notifChatId}
|
||||
onChange={(e) => setNotifChatId(e.target.value)}
|
||||
placeholder={t('settings.telegramChatId')}
|
||||
style={{ padding: '7px 10px', borderRadius: 10, border: '1.5px solid var(--warm-border)', fontFamily: 'Nunito' }}
|
||||
/>
|
||||
<div style={{ fontSize: 11, color: 'var(--warm-text-muted)', fontWeight: 700 }}>{t('settings.telegramChatIdHint')}</div>
|
||||
<input
|
||||
type="password"
|
||||
value={notifToken}
|
||||
onChange={(e) => setNotifToken(e.target.value)}
|
||||
placeholder={notifHasToken ? t('settings.telegramTokenConfigured') : t('settings.telegramToken')}
|
||||
style={{ padding: '7px 10px', borderRadius: 10, border: '1.5px solid var(--warm-border)', fontFamily: 'Nunito' }}
|
||||
/>
|
||||
<div style={{ fontSize: 11, color: 'var(--warm-text-muted)', fontWeight: 700 }}>{t('settings.telegramTokenHint')}</div>
|
||||
<div style={{ display: 'grid', gap: 6, marginTop: 2 }}>
|
||||
<label style={{ fontSize: 11, fontWeight: 700, color: 'var(--warm-text-muted)' }}>
|
||||
<input
|
||||
type="checkbox"
|
||||
checked={notifTypes.taskDue}
|
||||
onChange={(e) => setNotifTypes((prev) => ({ ...prev, taskDue: e.target.checked }))}
|
||||
style={{ marginRight: 6 }}
|
||||
/>
|
||||
{t('settings.notificationTypeTaskDue')}
|
||||
</label>
|
||||
<label style={{ fontSize: 11, fontWeight: 700, color: 'var(--warm-text-muted)' }}>
|
||||
<input
|
||||
type="checkbox"
|
||||
checked={notifTypes.rewardRequest}
|
||||
onChange={(e) => setNotifTypes((prev) => ({ ...prev, rewardRequest: e.target.checked }))}
|
||||
style={{ marginRight: 6 }}
|
||||
/>
|
||||
{t('settings.notificationTypeRewardRequest')}
|
||||
</label>
|
||||
<label style={{ fontSize: 11, fontWeight: 700, color: 'var(--warm-text-muted)' }}>
|
||||
<input
|
||||
type="checkbox"
|
||||
checked={notifTypes.achievementUnlocked}
|
||||
onChange={(e) => setNotifTypes((prev) => ({ ...prev, achievementUnlocked: e.target.checked }))}
|
||||
style={{ marginRight: 6 }}
|
||||
/>
|
||||
{t('settings.notificationTypeAchievementUnlocked')}
|
||||
</label>
|
||||
</div>
|
||||
</>
|
||||
) : (
|
||||
<div style={{ fontSize: 11, color: 'var(--warm-text-muted)', fontWeight: 700 }}>
|
||||
{t('settings.notificationsDisabledHint')}
|
||||
</div>
|
||||
)}
|
||||
<div style={{ display: 'flex', gap: 8, flexWrap: 'wrap' }}>
|
||||
{notifEnabled && (
|
||||
<>
|
||||
<button className="tq-btn tq-btn-secondary" onClick={saveNotifications} style={{ padding: '6px 10px', fontSize: 11 }}>
|
||||
{t('common.save')}
|
||||
</button>
|
||||
<button className="tq-btn tq-btn-secondary" onClick={testNotifications} style={{ padding: '6px 10px', fontSize: 11 }}>
|
||||
{t('settings.sendTestNotification')}
|
||||
</button>
|
||||
</>
|
||||
)}
|
||||
</div>
|
||||
{notifMsg && <div style={{ fontSize: 11, color: 'var(--warm-text-muted)', fontWeight: 700 }}>{notifMsg}</div>}
|
||||
</div>
|
||||
)}
|
||||
<div style={{ display: 'flex', alignItems: 'center', gap: 14, padding: '14px 0', borderBottom: '1px solid var(--warm-border)' }}>
|
||||
<div style={{ width: 20, height: 20, borderRadius: 6, background: 'linear-gradient(135deg, var(--warm-accent), var(--warm-accent-light))', border: '1px solid var(--warm-border)' }} />
|
||||
<div style={{ flex: 1 }}>
|
||||
<div style={{ fontSize: 14, fontWeight: 700, color: 'var(--warm-text)' }}>{t('settings.theme')}</div>
|
||||
<div style={{ fontSize: 11, color: 'var(--warm-text-light)', fontWeight: 600 }}>{t('settings.themeDesc')}</div>
|
||||
</div>
|
||||
<select
|
||||
value={theme}
|
||||
onChange={(e) => onChangeTheme(e.target.value as 'orange' | 'blue' | 'rose' | 'night')}
|
||||
style={{ padding: '7px 10px', borderRadius: 10, border: '1.5px solid var(--warm-border)', fontFamily: 'Nunito' }}
|
||||
>
|
||||
<option value="orange">{t('settings.themeOrange')}</option>
|
||||
<option value="blue">{t('settings.themeBlue')}</option>
|
||||
<option value="rose">{t('settings.themeRose')}</option>
|
||||
<option value="night">{t('settings.themeNight')}</option>
|
||||
</select>
|
||||
</div>
|
||||
<div style={{ display: 'flex', alignItems: 'center', gap: 14, padding: '14px 0' }}>
|
||||
<svg width="20" height="20" viewBox="0 0 20 20" fill="none">
|
||||
<circle cx="10" cy="8" r="4" stroke="#B0A090" strokeWidth="1.5" fill="none" />
|
||||
<path d="M5 17L6.5 13H13.5L15 17" stroke="#B0A090" strokeWidth="1.5" strokeLinecap="round" />
|
||||
</svg>
|
||||
<div style={{ flex: 1 }}>
|
||||
<div style={{ fontSize: 14, fontWeight: 700, color: 'var(--warm-text)' }}>{t('settings.vacationMode')}</div>
|
||||
<div style={{ fontSize: 11, color: 'var(--warm-text-light)', fontWeight: 600 }}>{t('settings.vacationDesc')}</div>
|
||||
</div>
|
||||
<Toggle checked={!!user.isVacationMode} onChange={isAdmin ? onToggleVacation : () => {}} />
|
||||
</div>
|
||||
{!isAdmin && (
|
||||
<div style={{ marginTop: 8, fontSize: 11, color: 'var(--warm-text-muted)', fontWeight: 700 }}>
|
||||
{t('settings.adminRequired')}
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
|
||||
{isAdmin && (
|
||||
<div className="tq-card" style={{ padding: 24 }}>
|
||||
<h3 style={{ fontSize: 15, fontWeight: 800, color: 'var(--warm-text)', margin: '0 0 12px' }}>{t('settings.coinsPerEffort')}</h3>
|
||||
<div style={{ fontSize: 11, color: 'var(--warm-text-light)', fontWeight: 600, marginBottom: 10 }}>{t('settings.coinsPerEffortDesc')}</div>
|
||||
<div style={{ display: 'grid', gap: 8, marginBottom: 10 }}>
|
||||
{[1, 2, 3, 4, 5].map((e) => (
|
||||
<div key={e} style={{ display: 'grid', gridTemplateColumns: '120px 1fr 130px', alignItems: 'center', gap: 10, backgroundColor: 'var(--warm-bg-subtle)', border: '1.5px solid var(--warm-border)', borderRadius: 12, padding: '8px 10px' }}>
|
||||
<div style={{ fontSize: 11, fontWeight: 700, color: 'var(--warm-text-muted)' }}>{t('roomDetail.effort')} {e}</div>
|
||||
<EffortDots effort={e} />
|
||||
<div style={{ display: 'flex', alignItems: 'center', gap: 6 }}>
|
||||
<CoinIcon />
|
||||
<input
|
||||
type="number"
|
||||
min={0}
|
||||
value={coinsDraft[e] ?? coinsByEffort[e] ?? e * 5}
|
||||
onChange={(ev) => setCoinsDraft((prev) => ({ ...prev, [e]: Math.max(0, parseInt(ev.target.value || '0', 10)) }))}
|
||||
title={`${t('roomDetail.effort')} ${e}`}
|
||||
style={{ width: '100%', padding: '7px 8px', borderRadius: 10, border: '1.5px solid var(--warm-border)', fontFamily: 'Nunito' }}
|
||||
/>
|
||||
</div>
|
||||
</div>
|
||||
))}
|
||||
</div>
|
||||
<div style={{ display: 'flex', gap: 8 }}>
|
||||
<button className="tq-btn tq-btn-primary" onClick={saveCoins} style={{ padding: '7px 12px', fontSize: 12 }}>{t('common.save')}</button>
|
||||
<button className="tq-btn tq-btn-secondary" onClick={resetCoins} style={{ padding: '7px 12px', fontSize: 12 }}>{t('settings.useDefaultCoins')}</button>
|
||||
</div>
|
||||
</div>
|
||||
)}
|
||||
|
||||
{isAdmin && (
|
||||
<div className="tq-card" style={{ padding: 24 }}>
|
||||
<h3 style={{ fontSize: 15, fontWeight: 800, color: 'var(--warm-text)', margin: '0 0 12px' }}>{t('settings.goalsSection')}</h3>
|
||||
<div style={{ fontSize: 11, color: 'var(--warm-text-light)', fontWeight: 600, marginBottom: 10 }}>{t('settings.goalsSectionDesc')}</div>
|
||||
<div style={{ display: 'grid', gap: 10 }}>
|
||||
{family
|
||||
.filter((u) => u.id !== user.id && u.role !== 'admin')
|
||||
.map((u) => (
|
||||
<div key={u.id} style={{ backgroundColor: 'var(--warm-bg-subtle)', border: '1.5px solid var(--warm-border)', borderRadius: 12, padding: '10px 12px' }}>
|
||||
<div style={{ fontSize: 12, fontWeight: 800, color: 'var(--warm-text)', marginBottom: 8 }}>{u.displayName}</div>
|
||||
<div style={{ display: 'grid', gap: 6, marginBottom: 8 }}>
|
||||
{(memberGoals[u.id] || []).map((g) => (
|
||||
<div key={g.id} style={{ display: 'grid', gridTemplateColumns: '1.4fr 120px 120px auto', gap: 8, alignItems: 'center', padding: '6px 8px', borderRadius: 10, backgroundColor: 'var(--warm-bg-warm)', border: '1px solid var(--warm-border)' }}>
|
||||
<div style={{ fontSize: 11, fontWeight: 800, color: 'var(--warm-text)' }}>{g.title}</div>
|
||||
<div style={{ fontSize: 11, fontWeight: 800, color: 'var(--warm-accent)', display: 'inline-flex', alignItems: 'center', gap: 4, justifyContent: 'center' }}><CoinIcon /> {g.goalCoins}</div>
|
||||
<div style={{ fontSize: 10, color: 'var(--warm-text-light)', fontWeight: 700 }}>{formatDate(g.endAt)}</div>
|
||||
<button className="tq-btn" onClick={() => handleDeleteGoal(g.id, u.id)} style={{ padding: '4px 8px', fontSize: 10, backgroundColor: 'var(--warm-danger-bg)', color: 'var(--warm-danger)', border: '1.5px solid var(--warm-danger-border)' }}>
|
||||
{t('common.delete')}
|
||||
</button>
|
||||
</div>
|
||||
))}
|
||||
</div>
|
||||
{memberGoalMsg[u.id] && (
|
||||
<div style={{ fontSize: 11, color: 'var(--warm-text-light)', fontWeight: 700 }}>{memberGoalMsg[u.id]}</div>
|
||||
)}
|
||||
<div style={{ display: 'grid', gridTemplateColumns: '1.4fr 100px 130px auto', gap: 8 }}>
|
||||
<input
|
||||
value={goalDraft[u.id]?.title || ''}
|
||||
onChange={(e) => setGoalDraft((prev) => ({ ...prev, [u.id]: { ...(prev[u.id] || { title: '', goalCoins: '', endAt: '' }), title: e.target.value } }))}
|
||||
placeholder={t('settings.goalTitle')}
|
||||
style={{ padding: '7px 10px', borderRadius: 10, border: '1.5px solid var(--warm-border)', fontFamily: 'Nunito' }}
|
||||
/>
|
||||
<input
|
||||
type="number"
|
||||
min={1}
|
||||
value={goalDraft[u.id]?.goalCoins || ''}
|
||||
onChange={(e) => setGoalDraft((prev) => ({ ...prev, [u.id]: { ...(prev[u.id] || { title: '', goalCoins: '', endAt: '' }), goalCoins: e.target.value } }))}
|
||||
placeholder={t('settings.goalCoins')}
|
||||
style={{ padding: '7px 10px', borderRadius: 10, border: '1.5px solid var(--warm-border)', fontFamily: 'Nunito' }}
|
||||
/>
|
||||
<input
|
||||
type="date"
|
||||
value={goalDraft[u.id]?.endAt || ''}
|
||||
onChange={(e) => setGoalDraft((prev) => ({ ...prev, [u.id]: { ...(prev[u.id] || { title: '', goalCoins: '', endAt: '' }), endAt: e.target.value } }))}
|
||||
title={t('settings.goalEnd')}
|
||||
lang={locale}
|
||||
style={{ minWidth: 130, padding: '7px 10px', borderRadius: 10, border: '1.5px solid var(--warm-border)', fontFamily: 'Nunito' }}
|
||||
/>
|
||||
<button className="tq-btn tq-btn-secondary" onClick={() => handleAddGoal(u)} style={{ padding: '6px 10px', fontSize: 11 }}>{t('settings.addGoal')}</button>
|
||||
</div>
|
||||
</div>
|
||||
))}
|
||||
</div>
|
||||
</div>
|
||||
)}
|
||||
|
||||
{isAdmin && (
|
||||
<div className="tq-card" style={{ padding: 24 }}>
|
||||
<h3 style={{ fontSize: 15, fontWeight: 800, color: 'var(--warm-text)', margin: '0 0 12px' }}>{t('settings.rewardsSection')}</h3>
|
||||
<div style={{ fontSize: 11, color: 'var(--warm-text-light)', fontWeight: 600, marginBottom: 10 }}>{t('settings.rewardsSectionDesc')}</div>
|
||||
<div style={{ display: 'grid', gridTemplateColumns: '1.2fr 1.4fr 100px auto auto', gap: 8, marginBottom: 10 }}>
|
||||
<input value={rewardDraft.title} onChange={(e) => setRewardDraft((p) => ({ ...p, title: e.target.value }))} placeholder={t('settings.rewardTitle')} style={{ padding: '7px 10px', borderRadius: 10, border: '1.5px solid var(--warm-border)', fontFamily: 'Nunito' }} />
|
||||
<input value={rewardDraft.description} onChange={(e) => setRewardDraft((p) => ({ ...p, description: e.target.value }))} placeholder={t('settings.rewardDesc')} style={{ padding: '7px 10px', borderRadius: 10, border: '1.5px solid var(--warm-border)', fontFamily: 'Nunito' }} />
|
||||
<input type="number" min={1} value={rewardDraft.costCoins} onChange={(e) => setRewardDraft((p) => ({ ...p, costCoins: e.target.value }))} placeholder={t('settings.rewardCost')} style={{ padding: '7px 10px', borderRadius: 10, border: '1.5px solid var(--warm-border)', fontFamily: 'Nunito' }} />
|
||||
<button className="tq-btn tq-btn-secondary" onClick={handleSeedRewards} style={{ padding: '6px 10px', fontSize: 11 }}>{t('settings.addPresetRewards')}</button>
|
||||
<button className="tq-btn tq-btn-primary" onClick={handleCreateReward} style={{ padding: '6px 10px', fontSize: 11 }}>{t('settings.create')}</button>
|
||||
</div>
|
||||
<div style={{ display: 'grid', gap: 6 }}>
|
||||
{rewardsAdmin.map((r) => (
|
||||
<div key={r.id} style={{ display: 'grid', gridTemplateColumns: '1.2fr 1.4fr 80px auto', gap: 8, alignItems: 'center', border: '1px solid var(--warm-border)', borderRadius: 10, padding: '8px 10px', backgroundColor: r.isActive ? 'var(--warm-bg-subtle)' : 'var(--warm-bg-warm)' }}>
|
||||
<div style={{ fontSize: 12, fontWeight: 800, color: 'var(--warm-text)' }}>{rewardTitle(r)}</div>
|
||||
<div style={{ fontSize: 11, color: 'var(--warm-text-light)', fontWeight: 600 }}>{rewardDesc(r)}</div>
|
||||
<div style={{ fontSize: 12, fontWeight: 800, color: 'var(--warm-accent)', display: 'flex', alignItems: 'center', gap: 4 }}><CoinIcon /> {r.costCoins}</div>
|
||||
<button className="tq-btn" onClick={async () => { await api.deleteReward(r.id); await loadRewardsAdmin(); }} style={{ padding: '4px 8px', fontSize: 10, backgroundColor: 'var(--warm-danger-bg)', color: 'var(--warm-danger)', border: '1.5px solid var(--warm-danger-border)' }}>{t('common.delete')}</button>
|
||||
</div>
|
||||
))}
|
||||
</div>
|
||||
<div style={{ marginTop: 14 }}>
|
||||
<h4 style={{ margin: '0 0 8px', fontSize: 13, fontWeight: 800, color: 'var(--warm-text)' }}>{t('settings.rewardRequests')}</h4>
|
||||
<div style={{ display: 'grid', gap: 6 }}>
|
||||
{rewardRequests.map((rr) => (
|
||||
<div key={rr.id} style={{ display: 'grid', gridTemplateColumns: '1.2fr 1fr 90px 110px 130px', gap: 8, alignItems: 'center', border: '1px solid var(--warm-border)', borderRadius: 10, padding: '8px 10px', backgroundColor: 'var(--warm-bg-subtle)' }}>
|
||||
<div style={{ fontSize: 12, fontWeight: 800, color: 'var(--warm-text)' }}>{rr.displayName}</div>
|
||||
<div style={{ fontSize: 11, color: 'var(--warm-text-light)', fontWeight: 700 }}>{rewardTitle(rr)}</div>
|
||||
<div style={{ fontSize: 11, fontWeight: 800, color: 'var(--warm-accent)', display: 'flex', alignItems: 'center', gap: 4, justifyContent: 'center' }}><CoinIcon /> {rr.costCoins}</div>
|
||||
<div style={{ fontSize: 10, fontWeight: 800, color: rr.status === 'approved' ? '#15803D' : rr.status === 'rejected' ? '#B91C1C' : rr.status === 'cancelled' ? '#374151' : 'var(--warm-text-light)' }}>{rewardStatusLabel(rr.status)}</div>
|
||||
<div style={{ fontSize: 10, color: 'var(--warm-text-light)', fontWeight: 700 }}>{formatDate(rr.redeemedAt)}</div>
|
||||
</div>
|
||||
))}
|
||||
{rewardRequests.length === 0 && (
|
||||
<div style={{ fontSize: 11, color: 'var(--warm-text-light)', fontWeight: 600 }}>{t('settings.noRewardRequests')}</div>
|
||||
)}
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
)}
|
||||
|
||||
<div className="tq-card" style={{ padding: 24 }}>
|
||||
<h3 style={{ fontSize: 15, fontWeight: 800, color: 'var(--warm-text)', margin: '0 0 18px' }}>{t('settings.dataPrivacy')}</h3>
|
||||
{[
|
||||
{ icon: <DownloadIcon />, title: t('settings.exportData'), desc: t('settings.exportDesc'), btn: t('settings.download'), action: onExport },
|
||||
{ icon: <UploadIcon />, title: t('settings.importData'), desc: t('settings.importDesc'), btn: t('settings.upload'), action: onImport },
|
||||
{ icon: <LockIcon />, title: t('settings.privacy'), desc: t('settings.privacyDesc'), btn: null, action: null },
|
||||
].map((s, i) => (
|
||||
<div key={i} style={{ display: 'flex', alignItems: 'center', gap: 14, padding: '14px 0', borderBottom: i < 2 ? '1px solid var(--warm-border)' : 'none' }}>
|
||||
{s.icon}
|
||||
<div style={{ flex: 1 }}>
|
||||
<div style={{ fontSize: 14, fontWeight: 700, color: 'var(--warm-text)' }}>{s.title}</div>
|
||||
<div style={{ fontSize: 11, color: 'var(--warm-text-light)', fontWeight: 600 }}>{s.desc}</div>
|
||||
</div>
|
||||
{s.btn && (
|
||||
<button className="tq-btn" onClick={isAdmin ? s.action! : () => {}} disabled={!isAdmin} style={{ padding: '7px 16px', backgroundColor: 'var(--warm-accent-light)', color: 'var(--warm-accent)', fontSize: 12, border: '1.5px solid var(--warm-accent)' }}>
|
||||
{s.btn}
|
||||
</button>
|
||||
)}
|
||||
</div>
|
||||
))}
|
||||
</div>
|
||||
|
||||
<div className="tq-card" style={{ padding: 24, gridColumn: '1 / -1' }}>
|
||||
<div style={{ display: 'flex', alignItems: 'center', justifyContent: 'space-between', marginBottom: 18 }}>
|
||||
<h3 style={{ fontSize: 15, fontWeight: 800, color: 'var(--warm-text)', margin: 0 }}>{t('settings.familyMembers')}</h3>
|
||||
<button className="tq-btn tq-btn-primary" onClick={() => isAdmin && setShowAddMember(true)} disabled={!isAdmin} style={{ padding: '7px 18px', fontSize: 12, opacity: isAdmin ? 1 : 0.5 }}>
|
||||
+ {t('settings.addMember')}
|
||||
</button>
|
||||
</div>
|
||||
{showAddMember && (
|
||||
<div style={{ marginBottom: 14, padding: 12, borderRadius: 12, backgroundColor: 'var(--warm-bg-warm)', border: '1.5px solid var(--warm-border)' }}>
|
||||
<div style={{ display: 'grid', gridTemplateColumns: '1fr 1fr 1fr auto auto', gap: 8 }}>
|
||||
<input value={newMemberName} onChange={(e) => setNewMemberName(e.target.value)} placeholder={t('settings.memberDisplayName')} style={{ padding: '8px 10px', borderRadius: 10, border: '1.5px solid var(--warm-border)', fontFamily: 'Nunito' }} />
|
||||
<input value={newMemberUsername} onChange={(e) => setNewMemberUsername(e.target.value)} placeholder={t('settings.memberUsername')} style={{ padding: '8px 10px', borderRadius: 10, border: '1.5px solid var(--warm-border)', fontFamily: 'Nunito' }} />
|
||||
<input value={newMemberPassword} onChange={(e) => setNewMemberPassword(e.target.value)} type="password" placeholder={t('settings.memberPassword')} style={{ padding: '8px 10px', borderRadius: 10, border: '1.5px solid var(--warm-border)', fontFamily: 'Nunito' }} />
|
||||
<button className="tq-btn tq-btn-secondary" onClick={resetMemberForm} style={{ padding: '8px 12px', fontSize: 12 }}>{t('common.cancel')}</button>
|
||||
<button className="tq-btn tq-btn-primary" onClick={handleAddMember} style={{ padding: '8px 12px', fontSize: 12 }}>{t('settings.create')}</button>
|
||||
</div>
|
||||
</div>
|
||||
)}
|
||||
<div style={{ display: 'grid', gridTemplateColumns: 'repeat(auto-fill, minmax(300px, 1fr))', gap: 12 }}>
|
||||
{family.map((u) => (
|
||||
<div key={u.id} style={{ backgroundColor: 'var(--warm-bg-warm)', borderRadius: 16, border: '1.5px solid var(--warm-border)', padding: '14px 16px' }}>
|
||||
<div style={{ display: 'flex', alignItems: 'center', gap: 12 }}>
|
||||
<UserAvatar name={u.displayName} color={u.avatarColor} size={44} avatarType={u.avatarType as any} avatarPreset={u.avatarPreset} avatarPhotoUrl={u.avatarPhotoUrl} />
|
||||
<div style={{ flex: 1 }}>
|
||||
<div style={{ display: 'flex', alignItems: 'center', gap: 8 }}>
|
||||
<div style={{ fontSize: 14, fontWeight: 800, color: 'var(--warm-text)' }}>{u.displayName}</div>
|
||||
<span style={{
|
||||
fontSize: 10, fontWeight: 800, textTransform: 'uppercase', letterSpacing: 0.5,
|
||||
color: u.role === 'admin' ? '#C2410C' : u.role === 'member' ? '#0369A1' : '#8A7A6A',
|
||||
backgroundColor: u.role === 'admin' ? '#FFF1E5' : u.role === 'member' ? '#EAF6FF' : '#F4EEE7',
|
||||
border: `1px solid ${u.role === 'admin' ? '#FDBA74' : u.role === 'member' ? '#BAE6FD' : '#E2D5C5'}`,
|
||||
borderRadius: 999, padding: '2px 7px',
|
||||
}}>
|
||||
{u.role === 'admin' ? t('settings.roleAdmin') : u.role === 'member' ? t('settings.roleMember') : t('settings.roleChild')}
|
||||
</span>
|
||||
</div>
|
||||
<div style={{ display: 'flex', alignItems: 'center', gap: 8, marginTop: 2 }}>
|
||||
<span style={{ fontSize: 11, color: 'var(--warm-text-light)', fontWeight: 600 }}>{u.coins} {t('settings.coins')}</span>
|
||||
<span style={{ fontSize: 11, color: 'var(--warm-text-light)', fontWeight: 600 }}>{u.currentStreak}d {t('settings.streak')}</span>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
{isAdmin && u.id !== user.id && (
|
||||
<div style={{ display: 'flex', gap: 8, marginTop: 10, flexWrap: 'wrap' }}>
|
||||
<select
|
||||
value={u.role || 'member'}
|
||||
onChange={(e) => onUpdateRole(u.id, e.target.value as 'admin' | 'member' | 'child')}
|
||||
style={{ padding: '6px 8px', borderRadius: 10, border: '1.5px solid var(--warm-border)', fontFamily: 'Nunito', fontSize: 11 }}
|
||||
>
|
||||
<option value="admin">{t('settings.roleAdmin')}</option>
|
||||
<option value="member">{t('settings.roleMember')}</option>
|
||||
<option value="child">{t('settings.roleChild')}</option>
|
||||
</select>
|
||||
{u.role !== 'admin' && (
|
||||
<button
|
||||
onClick={() => {
|
||||
initMemberProfile(u);
|
||||
setMemberEditOpen((prev) => ({ ...prev, [u.id]: !prev[u.id] }));
|
||||
}}
|
||||
className="tq-btn tq-btn-secondary"
|
||||
style={{ padding: '5px 10px', fontSize: 11 }}
|
||||
>
|
||||
{t('settings.manageMember')}
|
||||
</button>
|
||||
)}
|
||||
<button
|
||||
onClick={() => {
|
||||
if (confirm(t('settings.deleteUserConfirm').replace('{user}', u.displayName))) {
|
||||
onDeleteUser(u.id);
|
||||
}
|
||||
}}
|
||||
className="tq-btn"
|
||||
style={{ padding: '5px 10px', fontSize: 11, backgroundColor: 'var(--warm-danger-bg)', color: 'var(--warm-danger)', border: '1.5px solid var(--warm-danger-border)' }}
|
||||
>
|
||||
{t('settings.deleteUser')}
|
||||
</button>
|
||||
</div>
|
||||
)}
|
||||
{isAdmin && u.role !== 'admin' && memberEditOpen[u.id] && (
|
||||
<div style={{ marginTop: 10, paddingTop: 10, borderTop: '1px solid var(--warm-border)', display: 'grid', gap: 8 }}>
|
||||
<select value={memberProfile[u.id]?.language || 'en'} onChange={(e) => setMemberProfile((prev) => ({ ...prev, [u.id]: { ...prev[u.id], language: e.target.value } }))} style={{ padding: '7px 10px', borderRadius: 10, border: '1.5px solid var(--warm-border)', fontFamily: 'Nunito' }}>
|
||||
<option value="en">English</option>
|
||||
<option value="fr">Français</option>
|
||||
<option value="de">Deutsch</option>
|
||||
<option value="es">Español</option>
|
||||
</select>
|
||||
<select value={memberProfile[u.id]?.avatarType || 'letter'} onChange={(e) => setMemberProfile((prev) => ({ ...prev, [u.id]: { ...prev[u.id], avatarType: e.target.value as 'letter' | 'preset' } }))} style={{ padding: '7px 10px', borderRadius: 10, border: '1.5px solid var(--warm-border)', fontFamily: 'Nunito' }}>
|
||||
<option value="letter">{t('profile.letterMode')}</option>
|
||||
<option value="preset">{t('profile.characterMode')}</option>
|
||||
</select>
|
||||
{(memberProfile[u.id]?.avatarType || 'letter') === 'letter' ? (
|
||||
<div style={{ display: 'flex', gap: 6, flexWrap: 'wrap' }}>
|
||||
{COLORS.map((c) => (
|
||||
<button key={c} onClick={() => setMemberProfile((prev) => ({ ...prev, [u.id]: { ...prev[u.id], avatarColor: c } }))} style={{ width: 20, height: 20, borderRadius: 8, border: (memberProfile[u.id]?.avatarColor || '#F97316') === c ? '2px solid #3D2F1E' : '1px solid transparent', backgroundColor: c }} />
|
||||
))}
|
||||
</div>
|
||||
) : (
|
||||
<select value={memberProfile[u.id]?.avatarPreset || 'cat'} onChange={(e) => setMemberProfile((prev) => ({ ...prev, [u.id]: { ...prev[u.id], avatarPreset: e.target.value } }))} style={{ padding: '7px 10px', borderRadius: 10, border: '1.5px solid var(--warm-border)', fontFamily: 'Nunito' }}>
|
||||
{Object.keys(AVATAR_PRESETS).map((id) => (
|
||||
<option key={id} value={id}>{t(`avatars.${id}`)}</option>
|
||||
))}
|
||||
</select>
|
||||
)}
|
||||
<div style={{ display: 'flex', gap: 8, alignItems: 'center', flexWrap: 'wrap' }}>
|
||||
<button className="tq-btn tq-btn-primary" onClick={() => handleSaveChildProfile(u)} style={{ padding: '6px 10px', fontSize: 11 }}>{t('common.save')}</button>
|
||||
{memberProfileMsg[u.id] && (
|
||||
<div style={{ fontSize: 11, color: 'var(--warm-text-light)', fontWeight: 700 }}>{memberProfileMsg[u.id]}</div>
|
||||
)}
|
||||
</div>
|
||||
<div style={{ display: 'flex', gap: 8 }}>
|
||||
<input type="password" value={memberPassword[u.id] || ''} onChange={(e) => setMemberPassword((prev) => ({ ...prev, [u.id]: e.target.value }))} placeholder={t('settings.newPassword')} style={{ flex: 1, padding: '7px 10px', borderRadius: 10, border: '1.5px solid var(--warm-border)', fontFamily: 'Nunito' }} />
|
||||
<button className="tq-btn tq-btn-secondary" onClick={() => handleSetChildPassword(u)} style={{ padding: '6px 10px', fontSize: 11 }}>{t('settings.resetPassword')}</button>
|
||||
</div>
|
||||
{memberPasswordMsg[u.id] && (
|
||||
<div style={{ fontSize: 11, color: 'var(--warm-text-light)', fontWeight: 700 }}>{memberPasswordMsg[u.id]}</div>
|
||||
)}
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
))}
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
56
client/src/components/shared/ConfettiEffect.tsx
Normal file
56
client/src/components/shared/ConfettiEffect.tsx
Normal file
|
|
@ -0,0 +1,56 @@
|
|||
import React, { useMemo } from 'react';
|
||||
|
||||
interface ConfettiEffectProps {
|
||||
show: boolean;
|
||||
}
|
||||
|
||||
const COLORS = ['#F97316', '#FBBF24', '#FB923C', '#FCD34D', '#F59E0B', '#EA580C'];
|
||||
|
||||
const keyframesStyle = `
|
||||
@keyframes confettiFall {
|
||||
0% { transform: translateY(0) rotate(0deg); opacity: 1; }
|
||||
100% { transform: translateY(100vh) rotate(720deg); opacity: 0; }
|
||||
}`;
|
||||
|
||||
const ConfettiEffect: React.FC<ConfettiEffectProps> = ({ show }) => {
|
||||
const pieces = useMemo(
|
||||
() =>
|
||||
Array.from({ length: 45 }, (_, i) => ({
|
||||
id: i,
|
||||
left: Math.random() * 100,
|
||||
delay: Math.random() * 0.4,
|
||||
duration: 1.2 + Math.random() * 1.5,
|
||||
color: COLORS[Math.floor(Math.random() * COLORS.length)],
|
||||
size: 5 + Math.random() * 8,
|
||||
rotation: Math.random() * 360,
|
||||
})),
|
||||
[show],
|
||||
);
|
||||
|
||||
if (!show) return null;
|
||||
|
||||
return (
|
||||
<div style={{ position: 'fixed', inset: 0, pointerEvents: 'none', zIndex: 9999 }}>
|
||||
<style>{keyframesStyle}</style>
|
||||
{pieces.map((p) => (
|
||||
<div
|
||||
key={p.id}
|
||||
style={{
|
||||
position: 'absolute',
|
||||
left: `${p.left}%`,
|
||||
top: -12,
|
||||
width: p.size,
|
||||
height: p.size,
|
||||
backgroundColor: p.color,
|
||||
borderRadius: p.size > 9 ? '50%' : '2px',
|
||||
transform: `rotate(${p.rotation}deg)`,
|
||||
animation: `confettiFall ${p.duration}s ease-in ${p.delay}s forwards`,
|
||||
}}
|
||||
/>
|
||||
))}
|
||||
</div>
|
||||
);
|
||||
};
|
||||
|
||||
export { ConfettiEffect };
|
||||
export default ConfettiEffect;
|
||||
38
client/src/components/shared/EffortDots.tsx
Normal file
38
client/src/components/shared/EffortDots.tsx
Normal file
|
|
@ -0,0 +1,38 @@
|
|||
import React from 'react';
|
||||
|
||||
interface EffortDotsProps {
|
||||
effort: number;
|
||||
}
|
||||
|
||||
const FilledStar: React.FC = () => (
|
||||
<svg width="14" height="14" viewBox="0 0 14 14" fill="none">
|
||||
<path
|
||||
d="M7 1L8.5 5H12.5L9.5 7.5L10.5 11.5L7 9L3.5 11.5L4.5 7.5L1.5 5H5.5L7 1Z"
|
||||
fill="#F59E0B"
|
||||
stroke="#F59E0B"
|
||||
strokeWidth="0.5"
|
||||
/>
|
||||
</svg>
|
||||
);
|
||||
|
||||
const EmptyStar: React.FC = () => (
|
||||
<svg width="14" height="14" viewBox="0 0 14 14" fill="none">
|
||||
<path
|
||||
d="M7 1L8.5 5H12.5L9.5 7.5L10.5 11.5L7 9L3.5 11.5L4.5 7.5L1.5 5H5.5L7 1Z"
|
||||
fill="none"
|
||||
stroke="#E2D5C5"
|
||||
strokeWidth="1"
|
||||
/>
|
||||
</svg>
|
||||
);
|
||||
|
||||
const EffortDots: React.FC<EffortDotsProps> = ({ effort }) => (
|
||||
<div style={{ display: 'flex', gap: 1 }}>
|
||||
{Array.from({ length: 5 }, (_, i) => (
|
||||
<span key={i}>{i < effort ? <FilledStar /> : <EmptyStar />}</span>
|
||||
))}
|
||||
</div>
|
||||
);
|
||||
|
||||
export { EffortDots };
|
||||
export default EffortDots;
|
||||
60
client/src/components/shared/HealthBar.tsx
Normal file
60
client/src/components/shared/HealthBar.tsx
Normal file
|
|
@ -0,0 +1,60 @@
|
|||
import React from 'react';
|
||||
import { getHealthColor } from '../../utils/health';
|
||||
|
||||
interface HealthBarProps {
|
||||
value: number;
|
||||
height?: number;
|
||||
showLabel?: boolean;
|
||||
animate?: boolean;
|
||||
}
|
||||
|
||||
const HealthBar: React.FC<HealthBarProps> = ({
|
||||
value,
|
||||
height = 10,
|
||||
showLabel = true,
|
||||
animate = false,
|
||||
}) => {
|
||||
const color = getHealthColor(value);
|
||||
|
||||
return (
|
||||
<div style={{ display: 'flex', alignItems: 'center', gap: 10, width: '100%' }}>
|
||||
<div
|
||||
style={{
|
||||
flex: 1,
|
||||
height,
|
||||
backgroundColor: 'var(--health-bar-track)',
|
||||
borderRadius: 99,
|
||||
overflow: 'hidden',
|
||||
}}
|
||||
>
|
||||
<div
|
||||
style={{
|
||||
height: '100%',
|
||||
width: `${value}%`,
|
||||
backgroundColor: color,
|
||||
borderRadius: 99,
|
||||
transition: animate
|
||||
? 'width 0.8s cubic-bezier(.4,2,.6,1)'
|
||||
: 'width 0.3s ease',
|
||||
}}
|
||||
/>
|
||||
</div>
|
||||
{showLabel && (
|
||||
<span
|
||||
style={{
|
||||
fontSize: 12,
|
||||
fontWeight: 700,
|
||||
color,
|
||||
minWidth: 36,
|
||||
textAlign: 'right',
|
||||
}}
|
||||
>
|
||||
{value}%
|
||||
</span>
|
||||
)}
|
||||
</div>
|
||||
);
|
||||
};
|
||||
|
||||
export { HealthBar };
|
||||
export default HealthBar;
|
||||
83
client/src/components/shared/RingGauge.tsx
Normal file
83
client/src/components/shared/RingGauge.tsx
Normal file
|
|
@ -0,0 +1,83 @@
|
|||
import React from 'react';
|
||||
import { getHealthColor } from '../../utils/health';
|
||||
|
||||
interface RingGaugeProps {
|
||||
value: number;
|
||||
size?: number;
|
||||
strokeWidth?: number;
|
||||
}
|
||||
|
||||
const RingGauge: React.FC<RingGaugeProps> = ({
|
||||
value,
|
||||
size = 140,
|
||||
strokeWidth = 12,
|
||||
}) => {
|
||||
const r = (size - strokeWidth) / 2;
|
||||
const circ = 2 * Math.PI * r;
|
||||
const offset = circ - (value / 100) * circ;
|
||||
const color = getHealthColor(value);
|
||||
|
||||
return (
|
||||
<div style={{ position: 'relative', width: size, height: size }}>
|
||||
<svg width={size} height={size} style={{ transform: 'rotate(-90deg)' }}>
|
||||
<circle
|
||||
cx={size / 2}
|
||||
cy={size / 2}
|
||||
r={r}
|
||||
fill="none"
|
||||
stroke="#F5EDE3"
|
||||
strokeWidth={strokeWidth}
|
||||
/>
|
||||
<circle
|
||||
cx={size / 2}
|
||||
cy={size / 2}
|
||||
r={r}
|
||||
fill="none"
|
||||
stroke={color}
|
||||
strokeWidth={strokeWidth}
|
||||
strokeDasharray={circ}
|
||||
strokeDashoffset={offset}
|
||||
strokeLinecap="round"
|
||||
style={{
|
||||
transition:
|
||||
'stroke-dashoffset 1s cubic-bezier(.4,2,.6,1), stroke 0.5s ease',
|
||||
}}
|
||||
/>
|
||||
</svg>
|
||||
<div
|
||||
style={{
|
||||
position: 'absolute',
|
||||
inset: 0,
|
||||
display: 'flex',
|
||||
flexDirection: 'column',
|
||||
alignItems: 'center',
|
||||
justifyContent: 'center',
|
||||
}}
|
||||
>
|
||||
<div
|
||||
style={{
|
||||
fontSize: 36,
|
||||
fontWeight: 800,
|
||||
color,
|
||||
lineHeight: 1,
|
||||
}}
|
||||
>
|
||||
{value}
|
||||
</div>
|
||||
<div
|
||||
style={{
|
||||
fontSize: 11,
|
||||
color: '#B0A090',
|
||||
fontWeight: 600,
|
||||
marginTop: 2,
|
||||
}}
|
||||
>
|
||||
/ 100
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
);
|
||||
};
|
||||
|
||||
export { RingGauge };
|
||||
export default RingGauge;
|
||||
48
client/src/components/shared/Toggle.tsx
Normal file
48
client/src/components/shared/Toggle.tsx
Normal file
|
|
@ -0,0 +1,48 @@
|
|||
import React from 'react';
|
||||
|
||||
interface ToggleProps {
|
||||
checked: boolean;
|
||||
onChange: (checked: boolean) => void;
|
||||
}
|
||||
|
||||
const Toggle: React.FC<ToggleProps> = ({ checked, onChange }) => (
|
||||
<div
|
||||
role="switch"
|
||||
aria-checked={checked}
|
||||
tabIndex={0}
|
||||
onClick={() => onChange(!checked)}
|
||||
onKeyDown={(e) => {
|
||||
if (e.key === 'Enter' || e.key === ' ') {
|
||||
e.preventDefault();
|
||||
onChange(!checked);
|
||||
}
|
||||
}}
|
||||
style={{
|
||||
width: 44,
|
||||
height: 26,
|
||||
borderRadius: 13,
|
||||
padding: 3,
|
||||
cursor: 'pointer',
|
||||
backgroundColor: checked ? 'var(--warm-accent)' : 'var(--warm-border)',
|
||||
transition: 'background-color 0.2s ease',
|
||||
display: 'flex',
|
||||
alignItems: 'center',
|
||||
flexShrink: 0,
|
||||
}}
|
||||
>
|
||||
<div
|
||||
style={{
|
||||
width: 20,
|
||||
height: 20,
|
||||
borderRadius: '50%',
|
||||
backgroundColor: '#fff',
|
||||
boxShadow: '0 1px 4px rgba(0,0,0,0.1)',
|
||||
transform: checked ? 'translateX(18px)' : 'translateX(0)',
|
||||
transition: 'transform 0.2s ease',
|
||||
}}
|
||||
/>
|
||||
</div>
|
||||
);
|
||||
|
||||
export { Toggle };
|
||||
export default Toggle;
|
||||
91
client/src/components/shared/UserAvatar.tsx
Normal file
91
client/src/components/shared/UserAvatar.tsx
Normal file
|
|
@ -0,0 +1,91 @@
|
|||
import React, { useState } from 'react';
|
||||
import { AvatarPresetIcon } from '../icons/AvatarPresets';
|
||||
|
||||
interface UserAvatarProps {
|
||||
name: string;
|
||||
color: string;
|
||||
size?: number;
|
||||
avatarType?: 'letter' | 'preset' | 'photo';
|
||||
avatarPreset?: string | null;
|
||||
avatarPhotoUrl?: string | null;
|
||||
}
|
||||
|
||||
const UserAvatar: React.FC<UserAvatarProps> = ({
|
||||
name,
|
||||
color,
|
||||
size = 38,
|
||||
avatarType = 'letter',
|
||||
avatarPreset,
|
||||
avatarPhotoUrl,
|
||||
}) => {
|
||||
const [photoError, setPhotoError] = useState(false);
|
||||
|
||||
// Photo mode
|
||||
if (avatarType === 'photo' && avatarPhotoUrl && !photoError) {
|
||||
return (
|
||||
<div
|
||||
style={{
|
||||
width: size,
|
||||
height: size,
|
||||
borderRadius: '35%',
|
||||
overflow: 'hidden',
|
||||
border: `2px solid ${color}66`,
|
||||
flexShrink: 0,
|
||||
}}
|
||||
>
|
||||
<img
|
||||
src={avatarPhotoUrl}
|
||||
alt={name}
|
||||
onError={() => setPhotoError(true)}
|
||||
style={{ width: '100%', height: '100%', objectFit: 'cover' }}
|
||||
/>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
// Preset mode
|
||||
if (avatarType === 'preset' && avatarPreset) {
|
||||
return (
|
||||
<div
|
||||
style={{
|
||||
width: size,
|
||||
height: size,
|
||||
borderRadius: '35%',
|
||||
overflow: 'hidden',
|
||||
display: 'flex',
|
||||
alignItems: 'center',
|
||||
justifyContent: 'center',
|
||||
flexShrink: 0,
|
||||
}}
|
||||
>
|
||||
<AvatarPresetIcon presetId={avatarPreset} size={size} />
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
// Letter mode (default/fallback)
|
||||
const letter = name.charAt(0).toUpperCase();
|
||||
return (
|
||||
<div
|
||||
style={{
|
||||
width: size,
|
||||
height: size,
|
||||
borderRadius: '35%',
|
||||
background: `linear-gradient(135deg, ${color}44, ${color}22)`,
|
||||
border: `2px solid ${color}66`,
|
||||
display: 'flex',
|
||||
alignItems: 'center',
|
||||
justifyContent: 'center',
|
||||
fontSize: size * 0.4,
|
||||
fontWeight: 800,
|
||||
color,
|
||||
flexShrink: 0,
|
||||
}}
|
||||
>
|
||||
{letter}
|
||||
</div>
|
||||
);
|
||||
};
|
||||
|
||||
export { UserAvatar };
|
||||
export default UserAvatar;
|
||||
165
client/src/hooks/useApi.ts
Normal file
165
client/src/hooks/useApi.ts
Normal file
|
|
@ -0,0 +1,165 @@
|
|||
const API_BASE = '/api';
|
||||
|
||||
function getToken(): string | null {
|
||||
return localStorage.getItem('tidyquest_token');
|
||||
}
|
||||
|
||||
async function apiFetch<T>(path: string, options: RequestInit = {}): Promise<T> {
|
||||
const token = getToken();
|
||||
const headers: Record<string, string> = {
|
||||
'Content-Type': 'application/json',
|
||||
...(options.headers as Record<string, string> || {}),
|
||||
};
|
||||
if (token) {
|
||||
headers['Authorization'] = `Bearer ${token}`;
|
||||
}
|
||||
|
||||
const res = await fetch(`${API_BASE}${path}`, {
|
||||
...options,
|
||||
headers,
|
||||
});
|
||||
|
||||
if (res.status === 401) {
|
||||
localStorage.removeItem('tidyquest_token');
|
||||
window.location.href = '/login';
|
||||
throw new Error('Unauthorized');
|
||||
}
|
||||
|
||||
if (!res.ok) {
|
||||
const error = await res.json().catch(() => ({ error: 'Request failed' }));
|
||||
throw new Error(error.error || 'Request failed');
|
||||
}
|
||||
|
||||
return res.json();
|
||||
}
|
||||
|
||||
export const api = {
|
||||
// Auth
|
||||
register: (data: { username: string; password: string; displayName: string; avatarColor?: string; language?: string }) =>
|
||||
apiFetch<{ token: string; user: any }>('/auth/register', { method: 'POST', body: JSON.stringify(data) }),
|
||||
login: (data: { username: string; password: string }) =>
|
||||
apiFetch<{ token: string; user: any }>('/auth/login', { method: 'POST', body: JSON.stringify(data) }),
|
||||
me: () => apiFetch<any>('/auth/me'),
|
||||
|
||||
// Dashboard
|
||||
dashboard: () => apiFetch<any>('/dashboard'),
|
||||
|
||||
// Rooms
|
||||
getRooms: () => apiFetch<any[]>('/rooms'),
|
||||
getDefaultTasks: (roomType: string) =>
|
||||
apiFetch<Array<{ name: string; frequencyDays: number; effort: number; isSeasonal?: boolean }>>(`/rooms/defaults/${roomType}`),
|
||||
createRoom: (data: { name: string; roomType: string; color?: string; accentColor?: string; tasks?: any[] }) =>
|
||||
apiFetch<any>('/rooms', { method: 'POST', body: JSON.stringify(data) }),
|
||||
updateRoom: (id: number, data: any) =>
|
||||
apiFetch<any>(`/rooms/${id}`, { method: 'PUT', body: JSON.stringify(data) }),
|
||||
deleteRoom: (id: number) =>
|
||||
apiFetch<any>(`/rooms/${id}`, { method: 'DELETE' }),
|
||||
|
||||
// Tasks
|
||||
getTasks: (roomId: number) => apiFetch<any[]>(`/rooms/${roomId}/tasks`),
|
||||
createTask: (roomId: number, data: { name: string; notes?: string; frequencyDays?: number; effort?: number; isSeasonal?: boolean; health?: number; iconKey?: string }) =>
|
||||
apiFetch<any>(`/rooms/${roomId}/tasks`, { method: 'POST', body: JSON.stringify(data) }),
|
||||
updateTask: (id: number, data: any) =>
|
||||
apiFetch<any>(`/tasks/${id}`, { method: 'PUT', body: JSON.stringify(data) }),
|
||||
deleteTask: (id: number) =>
|
||||
apiFetch<any>(`/tasks/${id}`, { method: 'DELETE' }),
|
||||
completeTask: (id: number, completedAt?: string) =>
|
||||
apiFetch<{ coinsEarned: number; health: number }>(`/tasks/${id}/complete`, {
|
||||
method: 'POST', body: JSON.stringify({ completedAt }),
|
||||
}),
|
||||
|
||||
// Leaderboard
|
||||
leaderboard: (period: 'week' | 'month' | 'quarter' | 'year') => apiFetch<any[]>(`/leaderboard?period=${period}`),
|
||||
|
||||
// History
|
||||
history: (limit = 20, offset = 0) => apiFetch<any>(`/history?limit=${limit}&offset=${offset}`),
|
||||
|
||||
// Users
|
||||
getUsers: () => apiFetch<any[]>('/users'),
|
||||
createUser: (data: { username: string; password: string; displayName: string; avatarColor?: string; language?: string; role?: 'admin' | 'member' | 'child' }) =>
|
||||
apiFetch<any>('/users', { method: 'POST', body: JSON.stringify(data) }),
|
||||
updateSettings: (userId: number, data: { language?: string; isVacationMode?: boolean }) =>
|
||||
apiFetch<any>(`/users/${userId}/settings`, { method: 'PUT', body: JSON.stringify(data) }),
|
||||
updateProfile: (userId: number, data: { displayName?: string; avatarType?: string; avatarColor?: string; avatarPreset?: string | null; language?: string }) =>
|
||||
apiFetch<any>(`/users/${userId}/profile`, { method: 'PUT', body: JSON.stringify(data) }),
|
||||
updatePassword: (userId: number, data: { currentPassword?: string; newPassword: string }) =>
|
||||
apiFetch<{ success: boolean }>(`/users/${userId}/password`, { method: 'PUT', body: JSON.stringify(data) }),
|
||||
updateUserRole: (userId: number, role: 'admin' | 'member' | 'child') =>
|
||||
apiFetch<any>(`/users/${userId}/role`, { method: 'PUT', body: JSON.stringify({ role }) }),
|
||||
updateUserGoal: (userId: number, data: { goalCoins: number | null; goalStartAt?: string | null; goalEndAt?: string | null }) =>
|
||||
apiFetch<any>(`/users/${userId}/goal`, { method: 'PUT', body: JSON.stringify(data) }),
|
||||
getUserGoals: (userId: number) =>
|
||||
apiFetch<Array<{ id: number; userId: number; title: string; goalCoins: number; startAt?: string | null; endAt?: string | null; createdAt: string }>>(`/users/${userId}/goals`),
|
||||
createUserGoal: (userId: number, data: { title: string; goalCoins: number; startAt?: string | null; endAt?: string | null }) =>
|
||||
apiFetch<any>(`/users/${userId}/goals`, { method: 'POST', body: JSON.stringify(data) }),
|
||||
updateGoal: (goalId: number, data: { title: string; goalCoins: number; startAt?: string | null; endAt?: string | null }) =>
|
||||
apiFetch<any>(`/users/goals/${goalId}`, { method: 'PUT', body: JSON.stringify(data) }),
|
||||
deleteGoal: (goalId: number) =>
|
||||
apiFetch<{ success: boolean }>(`/users/goals/${goalId}`, { method: 'DELETE' }),
|
||||
deleteUser: (userId: number) =>
|
||||
apiFetch<{ success: boolean }>(`/users/${userId}`, { method: 'DELETE' }),
|
||||
getCoinsConfig: () => apiFetch<{ coinsByEffort: Record<number, number> }>('/users/coins-config'),
|
||||
updateCoinsConfig: (data: { coinsByEffort?: Record<number, number>; useDefault?: boolean }) =>
|
||||
apiFetch<{ coinsByEffort: Record<number, number> }>('/users/coins-config', { method: 'PUT', body: JSON.stringify(data) }),
|
||||
uploadAvatar: async (userId: number, file: File) => {
|
||||
const token = getToken();
|
||||
const formData = new FormData();
|
||||
formData.append('avatar', file);
|
||||
const res = await fetch(`${API_BASE}/users/${userId}/avatar-upload`, {
|
||||
method: 'POST',
|
||||
headers: token ? { 'Authorization': `Bearer ${token}` } : {},
|
||||
body: formData,
|
||||
});
|
||||
if (!res.ok) {
|
||||
const error = await res.json().catch(() => ({ error: 'Upload failed' }));
|
||||
throw new Error(error.error || 'Upload failed');
|
||||
}
|
||||
return res.json();
|
||||
},
|
||||
|
||||
// Data
|
||||
exportData: () => apiFetch<any>('/export'),
|
||||
importData: (data: any) =>
|
||||
apiFetch<any>('/import', { method: 'POST', body: JSON.stringify(data) }),
|
||||
achievements: () => apiFetch<any>('/achievements'),
|
||||
getNotificationsConfig: () =>
|
||||
apiFetch<{
|
||||
enabled: boolean;
|
||||
chatId: string;
|
||||
hasToken: boolean;
|
||||
notificationTime: string;
|
||||
notificationTypes: { taskDue: boolean; rewardRequest: boolean; achievementUnlocked: boolean };
|
||||
}>('/users/notifications-config'),
|
||||
updateNotificationsConfig: (data: {
|
||||
enabled?: boolean;
|
||||
botToken?: string;
|
||||
chatId?: string;
|
||||
notificationTime?: string;
|
||||
notificationTypes?: { taskDue: boolean; rewardRequest: boolean; achievementUnlocked: boolean };
|
||||
}) =>
|
||||
apiFetch<{
|
||||
enabled: boolean;
|
||||
chatId: string;
|
||||
hasToken: boolean;
|
||||
notificationTime: string;
|
||||
notificationTypes: { taskDue: boolean; rewardRequest: boolean; achievementUnlocked: boolean };
|
||||
}>('/users/notifications-config', { method: 'PUT', body: JSON.stringify(data) }),
|
||||
sendNotificationsTest: (data?: { botToken?: string; chatId?: string }) =>
|
||||
apiFetch<{ success: boolean }>('/users/notifications-test', { method: 'POST', body: JSON.stringify(data || {}) }),
|
||||
getRewards: () =>
|
||||
apiFetch<{ rewards: Array<{ id: number; title: string; description?: string | null; costCoins: number }>; mine: Array<{ id: number; title: string; costCoins: number; redeemedAt: string; status: string }> }>('/rewards'),
|
||||
getRewardsAdmin: () =>
|
||||
apiFetch<{ rewards: any[]; redemptions: any[] }>('/rewards/admin'),
|
||||
updateRedemptionStatus: (id: number, status: 'requested' | 'approved' | 'rejected') =>
|
||||
apiFetch<any>(`/rewards/redemptions/${id}`, { method: 'PUT', body: JSON.stringify({ status }) }),
|
||||
cancelRedemption: (id: number) =>
|
||||
apiFetch<{ redemption: any; coins: number }>(`/rewards/redemptions/${id}/cancel`, { method: 'POST' }),
|
||||
createReward: (data: { title: string; description?: string; costCoins: number }) =>
|
||||
apiFetch<any>('/rewards', { method: 'POST', body: JSON.stringify(data) }),
|
||||
updateReward: (id: number, data: { title: string; description?: string; costCoins: number; isActive?: boolean }) =>
|
||||
apiFetch<any>(`/rewards/${id}`, { method: 'PUT', body: JSON.stringify(data) }),
|
||||
deleteReward: (id: number) =>
|
||||
apiFetch<{ success: boolean }>(`/rewards/${id}`, { method: 'DELETE' }),
|
||||
redeemReward: (id: number) =>
|
||||
apiFetch<{ redemption: any; coins: number }>(`/rewards/${id}/redeem`, { method: 'POST' }),
|
||||
};
|
||||
66
client/src/hooks/useAuth.ts
Normal file
66
client/src/hooks/useAuth.ts
Normal file
|
|
@ -0,0 +1,66 @@
|
|||
import { useState, useEffect, useCallback } from 'react';
|
||||
import { api } from './useApi';
|
||||
|
||||
export interface User {
|
||||
id: number;
|
||||
username: string;
|
||||
displayName: string;
|
||||
role: 'admin' | 'member' | 'child';
|
||||
avatarColor: string;
|
||||
avatarType: 'letter' | 'preset' | 'photo';
|
||||
avatarPreset: string | null;
|
||||
avatarPhotoUrl: string | null;
|
||||
coins: number;
|
||||
currentStreak: number;
|
||||
isVacationMode: boolean;
|
||||
language: string;
|
||||
}
|
||||
|
||||
export function useAuth() {
|
||||
const [user, setUser] = useState<User | null>(null);
|
||||
const [loading, setLoading] = useState(true);
|
||||
|
||||
const checkAuth = useCallback(async () => {
|
||||
const token = localStorage.getItem('tidyquest_token');
|
||||
if (!token) {
|
||||
setLoading(false);
|
||||
return;
|
||||
}
|
||||
try {
|
||||
const userData = await api.me();
|
||||
setUser(userData);
|
||||
} catch {
|
||||
localStorage.removeItem('tidyquest_token');
|
||||
} finally {
|
||||
setLoading(false);
|
||||
}
|
||||
}, []);
|
||||
|
||||
useEffect(() => { checkAuth(); }, [checkAuth]);
|
||||
|
||||
const login = async (username: string, password: string) => {
|
||||
const { token, user: userData } = await api.login({ username, password });
|
||||
localStorage.setItem('tidyquest_token', token);
|
||||
setUser(userData);
|
||||
};
|
||||
|
||||
const register = async (data: { username: string; password: string; displayName: string; avatarColor?: string; language?: string }) => {
|
||||
const { token, user: userData } = await api.register(data);
|
||||
localStorage.setItem('tidyquest_token', token);
|
||||
setUser(userData);
|
||||
};
|
||||
|
||||
const logout = () => {
|
||||
localStorage.removeItem('tidyquest_token');
|
||||
setUser(null);
|
||||
};
|
||||
|
||||
const refreshUser = async () => {
|
||||
try {
|
||||
const userData = await api.me();
|
||||
setUser(userData);
|
||||
} catch { /* ignore */ }
|
||||
};
|
||||
|
||||
return { user, loading, login, register, logout, refreshUser };
|
||||
}
|
||||
97
client/src/hooks/useTranslation.ts
Normal file
97
client/src/hooks/useTranslation.ts
Normal file
|
|
@ -0,0 +1,97 @@
|
|||
import en from '../i18n/en.json';
|
||||
import fr from '../i18n/fr.json';
|
||||
import de from '../i18n/de.json';
|
||||
import es from '../i18n/es.json';
|
||||
|
||||
type TranslationData = typeof en;
|
||||
|
||||
const translations: Record<string, TranslationData> = { en, fr, de, es };
|
||||
|
||||
export function useTranslation(language: string = 'en') {
|
||||
const lang = translations[language] || translations.en;
|
||||
const fallback = translations.en;
|
||||
|
||||
function normalize(value: string): string {
|
||||
return value.trim().toLowerCase().replace(/\s+/g, ' ');
|
||||
}
|
||||
|
||||
/** Translate a task name: if translationKey exists and has a translation, use it; else return raw name */
|
||||
function taskName(name: string, translationKey: string | null | undefined): string {
|
||||
if (!translationKey) return name;
|
||||
|
||||
// translationKey format: "room.task_key" e.g. "kitchen.wash_dishes"
|
||||
const [room, ...rest] = translationKey.split('.');
|
||||
const taskKey = rest.join('.');
|
||||
|
||||
const roomTasks = (lang.tasks as any)?.[room];
|
||||
if (roomTasks && roomTasks[taskKey]) {
|
||||
return roomTasks[taskKey];
|
||||
}
|
||||
|
||||
// Fallback to English
|
||||
const fallbackTasks = (fallback.tasks as any)?.[room];
|
||||
if (fallbackTasks && fallbackTasks[taskKey]) {
|
||||
return fallbackTasks[taskKey];
|
||||
}
|
||||
|
||||
return name;
|
||||
}
|
||||
|
||||
/** Translate a UI string by dot-notation key, e.g. "profile.title" */
|
||||
function t(key: string): string {
|
||||
const parts = key.split('.');
|
||||
let value: any = lang.ui;
|
||||
let fallbackValue: any = fallback.ui;
|
||||
|
||||
for (const part of parts) {
|
||||
value = value?.[part];
|
||||
fallbackValue = fallbackValue?.[part];
|
||||
}
|
||||
|
||||
return (typeof value === 'string' ? value : null)
|
||||
|| (typeof fallbackValue === 'string' ? fallbackValue : null)
|
||||
|| key;
|
||||
}
|
||||
|
||||
/** Translate a room type name */
|
||||
function roomName(roomType: string): string {
|
||||
return (lang.rooms as any)?.[roomType]
|
||||
|| (fallback.rooms as any)?.[roomType]
|
||||
|| roomType;
|
||||
}
|
||||
|
||||
function roomDisplayName(name: string | null | undefined, roomType: string): string {
|
||||
const raw = (name || '').trim();
|
||||
if (!raw) return roomName(roomType);
|
||||
|
||||
const normalized = normalize(raw);
|
||||
for (const locale of Object.values(translations)) {
|
||||
const localized = (locale.rooms as any)?.[roomType];
|
||||
if (typeof localized === 'string' && normalize(localized) === normalized) {
|
||||
return roomName(roomType);
|
||||
}
|
||||
}
|
||||
return raw;
|
||||
}
|
||||
|
||||
function timeAgo(dateStr: string | null | undefined): string {
|
||||
if (!dateStr) return t('time.never');
|
||||
const diff = Date.now() - new Date(dateStr).getTime();
|
||||
const mins = Math.floor(diff / 60000);
|
||||
if (mins < 1) return t('time.justNow');
|
||||
if (mins < 60) return t('time.minutesAgo').replace('{count}', `${mins}`);
|
||||
const hours = Math.floor(mins / 60);
|
||||
if (hours < 24) return t('time.hoursAgo').replace('{count}', `${hours}`);
|
||||
const days = Math.floor(hours / 24);
|
||||
if (days === 1) return t('time.yesterday');
|
||||
if (days < 7) return t('time.daysAgo').replace('{count}', `${days}`);
|
||||
const weeks = Math.floor(days / 7);
|
||||
if (weeks === 1) return t('time.oneWeekAgo');
|
||||
if (weeks < 5) return t('time.weeksAgo').replace('{count}', `${weeks}`);
|
||||
const months = Math.floor(days / 30);
|
||||
if (months === 1) return t('time.oneMonthAgo');
|
||||
return t('time.monthsAgo').replace('{count}', `${months}`);
|
||||
}
|
||||
|
||||
return { taskName, t, roomName, roomDisplayName, timeAgo };
|
||||
}
|
||||
512
client/src/i18n/de.json
Normal file
512
client/src/i18n/de.json
Normal file
|
|
@ -0,0 +1,512 @@
|
|||
{
|
||||
"tasks": {
|
||||
"kitchen": {
|
||||
"wash_dishes": "Geschirr spülen",
|
||||
"clean_counters": "Arbeitsflächen reinigen",
|
||||
"wipe_stovetop": "Herd abwischen",
|
||||
"empty_trash": "Müll leeren",
|
||||
"empty_household_waste": "Hausmüll leeren",
|
||||
"empty_compost": "Kompost leeren",
|
||||
"empty_plastic_recycling": "Plastikrecycling leeren",
|
||||
"empty_glass_recycling": "Glasrecycling leeren",
|
||||
"clean_sink": "Spüle reinigen",
|
||||
"clean_sink_drain": "Spülensiphon reinigen",
|
||||
"wipe_appliances": "Geräte abwischen",
|
||||
"mop_floor": "Boden wischen",
|
||||
"clean_microwave": "Mikrowelle reinigen",
|
||||
"wipe_cabinet_fronts": "Schrankfronten abwischen",
|
||||
"clean_fridge": "Kühlschrank reinigen",
|
||||
"defrost_freezer": "Gefrierschrank abtauen",
|
||||
"descale_kettle": "Wasserkocher entkalken",
|
||||
"clean_dishwasher": "Spülmaschine reinigen",
|
||||
"clean_dishwasher_filter": "Spülmaschinenfilter reinigen",
|
||||
"check_dishwasher_salt": "Spülmaschinensalz prüfen/nachfüllen",
|
||||
"clean_oven": "Backofen reinigen",
|
||||
"clean_range_hood": "Dunstabzugshaube reinigen",
|
||||
"deep_clean_fridge": "Kühlschrank gründlich reinigen",
|
||||
"organize_pantry": "Vorratskammer ordnen"
|
||||
},
|
||||
"bedroom": {
|
||||
"make_bed": "Bett machen",
|
||||
"tidy_nightstand": "Nachttisch aufräumen",
|
||||
"change_sheets": "Bettwäsche wechseln",
|
||||
"vacuum_floor": "Boden staubsaugen",
|
||||
"dust_surfaces": "Oberflächen abstauben",
|
||||
"clean_under_bed": "Unter dem Bett reinigen",
|
||||
"wash_pillows": "Kissen waschen",
|
||||
"wash_duvet": "Bettdecke waschen",
|
||||
"change_fitted_sheet": "Spannbettlaken wechseln",
|
||||
"organize_closet": "Kleiderschrank ordnen",
|
||||
"flip_mattress": "Matratze wenden",
|
||||
"clean_windows": "Fenster putzen",
|
||||
"wash_curtains": "Vorhänge waschen"
|
||||
},
|
||||
"bathroom": {
|
||||
"wipe_sink_counter": "Waschbecken und Ablage abwischen",
|
||||
"squeegee_shower": "Dusche abziehen",
|
||||
"scrub_toilet": "Toilette schrubben",
|
||||
"clean_mirror": "Spiegel putzen",
|
||||
"wash_towels": "Handtücher waschen",
|
||||
"clean_shower_tub": "Dusche und Badewanne reinigen",
|
||||
"clean_sink_drain": "Waschbeckenabfluss reinigen",
|
||||
"mop_floor": "Boden wischen",
|
||||
"clean_shower_drain": "Duschabfluss reinigen",
|
||||
"wash_bath_mat": "Badematte waschen",
|
||||
"wipe_switches_handles": "Schalter und Griffe abwischen",
|
||||
"clean_grout": "Fugen reinigen",
|
||||
"descale_showerhead": "Duschkopf entkalken",
|
||||
"wash_shower_curtain": "Duschvorhang waschen",
|
||||
"organize_cabinets": "Schränke ordnen",
|
||||
"replace_toothbrush": "Zahnbürste ersetzen"
|
||||
},
|
||||
"living": {
|
||||
"tidy_up": "Aufräumen",
|
||||
"fluff_cushions": "Kissen aufschütteln",
|
||||
"vacuum_carpet": "Teppich staubsaugen",
|
||||
"dust_surfaces_shelves": "Oberflächen und Regale abstauben",
|
||||
"wipe_tv": "Fernseher abwischen",
|
||||
"clean_remotes": "Fernbedienungen reinigen",
|
||||
"dust_lampshades": "Lampenschirme abstauben",
|
||||
"vacuum_sofa": "Sofa absaugen",
|
||||
"clean_windows": "Fenster putzen",
|
||||
"wash_curtains_blinds": "Vorhänge und Jalousien waschen",
|
||||
"deep_clean_carpet": "Teppich gründlich reinigen",
|
||||
"clean_behind_furniture": "Hinter Möbeln reinigen",
|
||||
"polish_furniture": "Möbel polieren"
|
||||
},
|
||||
"office": {
|
||||
"clear_desk": "Schreibtisch freiräumen",
|
||||
"wipe_desk": "Schreibtisch abwischen",
|
||||
"clean_keyboard_mouse": "Tastatur und Maus reinigen",
|
||||
"wipe_monitor": "Bildschirm abwischen",
|
||||
"empty_paper_trash": "Papierkorb leeren",
|
||||
"vacuum_floor": "Boden staubsaugen",
|
||||
"organize_cables": "Kabel ordnen",
|
||||
"dust_shelves": "Regale abstauben",
|
||||
"clean_desk_lamp": "Schreibtischlampe reinigen",
|
||||
"organize_drawers": "Schubladen ordnen",
|
||||
"wipe_switches": "Schalter abwischen",
|
||||
"clean_chair": "Stuhl reinigen"
|
||||
},
|
||||
"garage": {
|
||||
"sweep_floor": "Boden fegen",
|
||||
"organize_tools": "Werkzeug ordnen",
|
||||
"clean_workbench": "Werkbank reinigen",
|
||||
"clear_cobwebs": "Spinnweben entfernen",
|
||||
"organize_shelves": "Regale ordnen",
|
||||
"wipe_power_tools": "Elektrowerkzeuge abwischen",
|
||||
"sort_recycling": "Recycling sortieren",
|
||||
"mop_hose_floor": "Boden wischen oder abspritzen",
|
||||
"check_chemicals": "Chemikalien überprüfen",
|
||||
"clean_door_tracks": "Türschienen reinigen"
|
||||
},
|
||||
"laundry": {
|
||||
"wipe_washer_seal": "Waschmaschinendichtung abwischen",
|
||||
"clean_lint_filter": "Flusensieb reinigen",
|
||||
"wipe_machine_exterior": "Maschinenäußeres abwischen",
|
||||
"run_cleaning_cycle": "Reinigungsprogramm starten",
|
||||
"drain_washing_machine": "Waschmaschine entleeren",
|
||||
"descale_washing_machine": "Waschmaschine entkalken",
|
||||
"clean_detergent_drawer": "Waschmittelfach reinigen",
|
||||
"sweep_mop_floor": "Boden fegen und wischen",
|
||||
"organize_supplies": "Vorräte ordnen",
|
||||
"clean_dryer_vent": "Trocknerentlüftung reinigen",
|
||||
"wipe_folding_surface": "Faltfläche abwischen",
|
||||
"sort_donate_clothes": "Kleidung sortieren und spenden"
|
||||
}
|
||||
},
|
||||
"rooms": {
|
||||
"kitchen": "Küche",
|
||||
"bedroom": "Schlafzimmer",
|
||||
"bathroom": "Badezimmer",
|
||||
"living": "Wohnzimmer",
|
||||
"office": "Büro",
|
||||
"garage": "Garage",
|
||||
"laundry": "Waschküche",
|
||||
"other": "Sonstiges"
|
||||
},
|
||||
"ui": {
|
||||
"profile": {
|
||||
"title": "Profil",
|
||||
"displayName": "Anzeigename",
|
||||
"avatarMode": "Avatar-Modus",
|
||||
"letterMode": "Buchstabe",
|
||||
"characterMode": "Figur",
|
||||
"photoMode": "Foto",
|
||||
"uploadPhoto": "Foto hochladen",
|
||||
"language": "Sprache",
|
||||
"save": "Speichern",
|
||||
"saved": "Gespeichert",
|
||||
"logout": "Abmelden"
|
||||
},
|
||||
"settings": {
|
||||
"title": "Einstellungen",
|
||||
"general": "Allgemein",
|
||||
"notifications": "Benachrichtigungen",
|
||||
"notificationsDesc": "Tägliche Erinnerungen für Hausarbeiten",
|
||||
"theme": "Design",
|
||||
"themeDesc": "Farbthema der App wechseln",
|
||||
"themeOrange": "Warmes Orange",
|
||||
"themeBlue": "Helles Blau",
|
||||
"themeRose": "Helles Rosa",
|
||||
"themeNight": "Nacht",
|
||||
"vacationMode": "Urlaubsmodus",
|
||||
"vacationDesc": "Alle Aufgabenerinnerungen während Ihrer Abwesenheit pausieren",
|
||||
"adminRequired": "Ein Admin-Elternteil ist erforderlich, um Einstellungen zu ändern.",
|
||||
"data": "Daten",
|
||||
"dataPrivacy": "Daten & Datenschutz",
|
||||
"export": "Exportieren",
|
||||
"exportData": "Daten exportieren",
|
||||
"exportDesc": "JSON-Backup herunterladen",
|
||||
"download": "Herunterladen",
|
||||
"import": "Importieren",
|
||||
"importData": "Daten importieren",
|
||||
"importDesc": "Aus Backup wiederherstellen",
|
||||
"upload": "Hochladen",
|
||||
"family": "Familie",
|
||||
"familyMembers": "Familienmitglieder",
|
||||
"addMember": "Mitglied hinzufügen",
|
||||
"memberDisplayName": "Anzeigename",
|
||||
"memberUsername": "Benutzername",
|
||||
"memberPassword": "Passwort",
|
||||
"passwordSection": "Passwort",
|
||||
"currentPassword": "Aktuelles Passwort",
|
||||
"newPassword": "Neues Passwort",
|
||||
"confirmPassword": "Neues Passwort bestätigen",
|
||||
"updatePassword": "Passwort aktualisieren",
|
||||
"resetPassword": "Passwort zurücksetzen",
|
||||
"passwordMismatch": "Passwörter stimmen nicht überein.",
|
||||
"passwordUpdated": "Passwort aktualisiert.",
|
||||
"passwordUpdateFailed": "Passwort konnte nicht aktualisiert werden.",
|
||||
"manageChild": "Kind verwalten",
|
||||
"coinsPerEffort": "Münzen pro Aufwand",
|
||||
"coinsPerEffortDesc": "Lege fest, wie viele Münzen für Aufwand 1 bis 5 vergeben werden.",
|
||||
"goalsSection": "Ziele pro Mitglied",
|
||||
"goalsSectionDesc": "Setze Münz-Ziele und Zeitraum für jedes Kind/Mitglied.",
|
||||
"useDefaultCoins": "Standardwerte verwenden",
|
||||
"create": "Erstellen",
|
||||
"privacy": "Datenschutz",
|
||||
"privacyDesc": "Alle Daten bleiben auf Ihrem Server",
|
||||
"docker": "Docker",
|
||||
"roleAdmin": "Admin",
|
||||
"roleChild": "Kind",
|
||||
"setAs": "Festlegen als",
|
||||
"coins": "Münzen",
|
||||
"streak": "Serie",
|
||||
"roleMember": "Mitglied",
|
||||
"deleteUser": "Benutzer löschen",
|
||||
"deleteUserConfirm": "\"{user}\" löschen? Dies kann nicht rückgängig gemacht werden.",
|
||||
"goalCoins": "Zielmünzen",
|
||||
"goalTitle": "Zieltitel",
|
||||
"setGoal": "Ziel setzen",
|
||||
"addGoal": "Ziel hinzufügen",
|
||||
"manageMember": "Mitglied verwalten",
|
||||
"goalStart": "Startdatum",
|
||||
"goalEnd": "Enddatum",
|
||||
"goalDeleted": "Ziel gelöscht.",
|
||||
"goalDeleteFailed": "Ziel konnte nicht gelöscht werden.",
|
||||
"rewardsSection": "Belohnungskatalog",
|
||||
"rewardsSectionDesc": "Eltern können Belohnungen erstellen, die Kinder mit Münzen kaufen.",
|
||||
"rewardTitle": "Belohnungstitel",
|
||||
"rewardDesc": "Beschreibung",
|
||||
"rewardCost": "Münzkosten",
|
||||
"addPresetRewards": "Vorgefertigte Belohnungen hinzufügen",
|
||||
"rewardRequests": "Belohnungsanfragen",
|
||||
"noRewardRequests": "Noch keine Belohnungsanfragen.",
|
||||
"telegramChatId": "Telegram-Chat-ID",
|
||||
"telegramChatIdHint": "Erwartet: numerische Chat-ID (z. B. 123456789 oder -1001234567890). Starte zuerst einen Chat mit dem Bot.",
|
||||
"notificationTime": "Benachrichtigungszeit",
|
||||
"telegramToken": "Telegram-Bot-Token",
|
||||
"telegramTokenHint": "Erwartet: Bot-Token von @BotFather (Format wie 123456789:AA...).",
|
||||
"telegramTokenConfigured": "Telegram-Token bereits gesetzt (eingeben zum Ersetzen)",
|
||||
"telegramChatIdRequired": "Telegram-Chat-ID ist erforderlich, wenn Benachrichtigungen aktiviert sind.",
|
||||
"telegramTokenRequired": "Telegram-Bot-Token ist erforderlich, wenn Benachrichtigungen aktiviert sind.",
|
||||
"notificationsDisabledHint": "Aktiviere Benachrichtigungen, um Telegram und Uhrzeit zu konfigurieren.",
|
||||
"notificationTypeTaskDue": "Fällige Aufgaben",
|
||||
"notificationTypeRewardRequest": "Belohnungsanfragen",
|
||||
"notificationTypeAchievementUnlocked": "Erfolge freigeschaltet",
|
||||
"sendTestNotification": "Testbenachrichtigung senden",
|
||||
"notificationsSaved": "Benachrichtigungseinstellungen gespeichert.",
|
||||
"notificationsSaveFailed": "Speichern der Benachrichtigungseinstellungen fehlgeschlagen.",
|
||||
"notificationsTestSent": "Testbenachrichtigung gesendet.",
|
||||
"notificationsTestFailed": "Senden der Testbenachrichtigung fehlgeschlagen."
|
||||
},
|
||||
"nav": {
|
||||
"home": "Startseite",
|
||||
"rooms": "Räume",
|
||||
"board": "Board",
|
||||
"calendar": "Kalender",
|
||||
"activity": "Aktivität",
|
||||
"rewards": "Belohnungen",
|
||||
"settings": "Einstellungen",
|
||||
"profile": "Profil",
|
||||
"tagline": "Dein Zuhause aufleveln",
|
||||
"achievements": "Erfolge"
|
||||
},
|
||||
"app": {
|
||||
"roomsConfigured": "Räume konfiguriert",
|
||||
"calendarSubtitle": "Verfolge deinen Reinigungsverlauf",
|
||||
"leaderboardTitle": "Bestenliste",
|
||||
"leaderboardSubtitle": "Wer hält das Zuhause sauber?",
|
||||
"historyTitle": "Aktivitätsprotokoll",
|
||||
"historySubtitle": "Alle erledigten Aufgaben",
|
||||
"activitySubtitle": "Wer hat was wann und für wie viele Punkte erledigt",
|
||||
"rewardsSubtitle": "Gib deine Münzen für echte Belohnungen aus",
|
||||
"profileSubtitle": "Avatar und Einstellungen anpassen",
|
||||
"settingsSubtitle": "Erlebnis konfigurieren",
|
||||
"achievementsSubtitle": "Mache Aufgaben mit Abzeichen und Meilensteinen zum Spiel"
|
||||
},
|
||||
"calendar": {
|
||||
"mon": "Mo",
|
||||
"tue": "Di",
|
||||
"wed": "Mi",
|
||||
"thu": "Do",
|
||||
"fri": "Fr",
|
||||
"sat": "Sa",
|
||||
"sun": "So",
|
||||
"choresDone": "Erledigte Aufgaben",
|
||||
"tasksDue": "Fällige Aufgaben",
|
||||
"today": "Heute",
|
||||
"upcomingDueDates": "Bevorstehende Fälligkeiten",
|
||||
"inDays": "in {days}T",
|
||||
"allCaughtUp": "Alles erledigt! Keine Aufgaben in Kürze fällig."
|
||||
},
|
||||
"leaderboard": {
|
||||
"thisWeek": "Diese Woche",
|
||||
"thisMonth": "Diesen Monat",
|
||||
"thisQuarter": "Dieses Quartal",
|
||||
"thisYear": "Dieses Jahr",
|
||||
"points": "Punkte",
|
||||
"streak": "Serie",
|
||||
"noData": "Für diesen Zeitraum noch keine Daten."
|
||||
},
|
||||
"rewards": {
|
||||
"catalog": "Belohnungskatalog",
|
||||
"balanceHint": "Erledige Aufgaben, verdiene Münzen und löse Belohnungen ein.",
|
||||
"noDescription": "Keine Beschreibung",
|
||||
"redeem": "Einlösen",
|
||||
"notEnough": "Nicht genug Münzen",
|
||||
"myRequests": "Mein Einlöseverlauf",
|
||||
"noRequests": "Noch keine Belohnung eingelöst.",
|
||||
"confirmTitle": "Kauf bestätigen",
|
||||
"confirmText": "\"{reward}\" für {coins} Münzen kaufen?",
|
||||
"confirmBuy": "Bestätigen",
|
||||
"cancelRequest": "Stornieren",
|
||||
"statusPending": "Ausstehend",
|
||||
"statusApproved": "Freigegeben",
|
||||
"statusRejected": "Abgelehnt",
|
||||
"statusCancelled": "Storniert"
|
||||
},
|
||||
"rewardsPreset": {
|
||||
"movie_night": { "title": "Filmabend wählen", "desc": "Den Familienfilm für heute Abend auswählen." },
|
||||
"ice_cream": { "title": "Eis-Extra", "desc": "Ein Eis oder besonderes Dessert bekommen." },
|
||||
"late_bedtime": { "title": "30 Min länger auf", "desc": "30 Minuten später ins Bett gehen." },
|
||||
"game_bonus": { "title": "Spielzeit-Bonus", "desc": "30 Minuten zusätzliche Spielzeit." },
|
||||
"choose_dinner": { "title": "Abendessen wählen", "desc": "Bestimmen, was es heute Abend gibt." },
|
||||
"park_adventure": { "title": "Park-Abenteuer", "desc": "Besonderer Familienausflug in den Park." },
|
||||
"chore_pass": { "title": "Aufgaben-Pass", "desc": "Diese Woche eine Aufgabe aussetzen." },
|
||||
"board_game": { "title": "Familien-Brettspiel", "desc": "Das Brettspiel für den Familienabend wählen." }
|
||||
},
|
||||
"history": {
|
||||
"task": "Aufgabe",
|
||||
"room": "Raum",
|
||||
"when": "Wann",
|
||||
"earned": "Erhalten",
|
||||
"by": "von",
|
||||
"noActivity": "Noch keine Aktivität. Erledige eine Aufgabe, um zu starten!",
|
||||
"previous": "Zurück",
|
||||
"next": "Weiter",
|
||||
"of": "von"
|
||||
},
|
||||
"roomDetail": {
|
||||
"name": "Name",
|
||||
"notes": "Notizen",
|
||||
"optionalNotes": "Optionale Notizen...",
|
||||
"every": "Alle",
|
||||
"effort": "Aufwand",
|
||||
"frequency": "Häufigkeit",
|
||||
"actions": "Aktionen",
|
||||
"deleteTask": "Aufgabe löschen",
|
||||
"done": "Erledigt",
|
||||
"seasonal": "Saisonal",
|
||||
"taskName": "Aufgabenname...",
|
||||
"addTask": "Aufgabe hinzufügen"
|
||||
},
|
||||
"avatars": {
|
||||
"cat": "Katze",
|
||||
"dog": "Hund",
|
||||
"bunny": "Hase",
|
||||
"bear": "Bär",
|
||||
"fox": "Fuchs",
|
||||
"owl": "Eule",
|
||||
"panda": "Panda",
|
||||
"penguin": "Pinguin",
|
||||
"unicorn": "Einhorn",
|
||||
"frog": "Frosch",
|
||||
"koala": "Koala",
|
||||
"hedgehog": "Igel"
|
||||
},
|
||||
"dashboard": {
|
||||
"houseHealth": "Hauszustand",
|
||||
"todaysQuests": "Heutige Aufgaben",
|
||||
"recentActivity": "Letzte Aktivitäten",
|
||||
"noQuests": "Keine Aufgaben für heute",
|
||||
"roomsCount": "Räume",
|
||||
"tasksCount": "Aufgaben",
|
||||
"criticalCount": "Kritisch",
|
||||
"pending": "offen",
|
||||
"sortedUrgency": "Nach Dringlichkeit sortiert",
|
||||
"dayStreak": "Tagesserie",
|
||||
"keepStreak": "Erledige täglich 1 Aufgabe, um dranzubleiben!",
|
||||
"streakDoneToday": "Serie für heute abgeschlossen!",
|
||||
"more": "Mehr",
|
||||
"nextTasks": "Nächste anstehende Aufgaben",
|
||||
"healthGreat": "Sieht großartig aus! Weiter so.",
|
||||
"healthMedium": "Einige Räume brauchen etwas Aufmerksamkeit.",
|
||||
"healthLow": "Zeit für eine Putzeinheit!",
|
||||
"myGoal": "Mein Ziel",
|
||||
"childrenGoals": "Ziele der Kinder",
|
||||
"noGoal": "Kein Ziel",
|
||||
"rewardRequestsTitle": "Belohnungsanfragen",
|
||||
"rewardRequestEmpty": "Keine ausstehenden Anfragen.",
|
||||
"coinsStatusTitle": "Münzstand",
|
||||
"approve": "Freigeben",
|
||||
"reject": "Ablehnen"
|
||||
},
|
||||
"rooms": {
|
||||
"addRoom": "Raum hinzufügen",
|
||||
"room": "Raum",
|
||||
"tasks": "Aufgaben",
|
||||
"health": "Zustand",
|
||||
"healthHealthy": "Gut",
|
||||
"healthNeedsAttention": "Aufmerksamkeit nötig",
|
||||
"healthCritical": "Kritisch",
|
||||
"deleteRoomConfirm": "\"{room}\" und alle Aufgaben löschen? Dies kann nicht rückgängig gemacht werden.",
|
||||
"noRoomsYet": "Noch keine Räume",
|
||||
"clickAddRoom": "Klicken Sie auf \"Raum hinzufügen\", um zu starten!",
|
||||
"addRoomTitle": "Raum hinzufügen",
|
||||
"pickRoomType": "Wählen Sie einen Raumtyp und konfigurieren Sie die Aufgaben.",
|
||||
"customNameOptional": "Eigener Name (optional)",
|
||||
"nextConfigure": "Weiter: Aufgaben konfigurieren",
|
||||
"configureTasks": "Aufgaben konfigurieren",
|
||||
"configureTasksDesc": "Aufgaben auswählen und Zustand, Aufwand, Häufigkeit festlegen.",
|
||||
"currentState": "Aktueller Zustand",
|
||||
"dirty": "Schmutzig",
|
||||
"clean": "Sauber",
|
||||
"addCustomTask": "Eigene Aufgabe hinzufügen...",
|
||||
"tasksSelected": "Aufgaben ausgewählt",
|
||||
"createRoom": "Raum erstellen",
|
||||
"roomNotFound": "Raum nicht gefunden.",
|
||||
"backToRooms": "Zurück zu Räumen",
|
||||
"tasksTracked": "Aufgaben erfasst"
|
||||
},
|
||||
"common": {
|
||||
"save": "Speichern",
|
||||
"saved": "Gespeichert",
|
||||
"cancel": "Abbrechen",
|
||||
"delete": "Löschen",
|
||||
"edit": "Bearbeiten",
|
||||
"loading": "Laden",
|
||||
"add": "Hinzufügen"
|
||||
},
|
||||
"units": {
|
||||
"hours": "Stunden",
|
||||
"days": "Tage",
|
||||
"weeks": "Wochen",
|
||||
"months": "Monate",
|
||||
"years": "Jahre"
|
||||
},
|
||||
"unitsShort": {
|
||||
"hours": "Std",
|
||||
"days": "T",
|
||||
"weeks": "Wo",
|
||||
"months": "Mon",
|
||||
"years": "J"
|
||||
},
|
||||
"time": {
|
||||
"never": "Nie",
|
||||
"justNow": "gerade eben",
|
||||
"minutesAgo": "vor {count} Min",
|
||||
"hoursAgo": "vor {count} Std",
|
||||
"yesterday": "gestern",
|
||||
"daysAgo": "vor {count} Tg",
|
||||
"oneWeekAgo": "vor 1 Wo",
|
||||
"weeksAgo": "vor {count} Wo",
|
||||
"oneMonthAgo": "vor 1 Mon",
|
||||
"monthsAgo": "vor {count} Mon"
|
||||
},
|
||||
"auth": {
|
||||
"welcomeBack": "Willkommen!",
|
||||
"welcome": "Willkommen bei TidyQuest",
|
||||
"createYourAccount": "Erstelle dein Konto",
|
||||
"username": "Benutzername",
|
||||
"usernamePlaceholder": "Benutzernamen eingeben",
|
||||
"password": "Passwort",
|
||||
"passwordPlaceholder": "Passwort eingeben",
|
||||
"passwordMinChars": "mind. 4 Zeichen",
|
||||
"displayName": "Anzeigename",
|
||||
"displayNamePlaceholder": "John",
|
||||
"avatarColor": "Avatar-Farbe",
|
||||
"loggingIn": "Anmelden...",
|
||||
"logIn": "Anmelden",
|
||||
"createAccount": "Konto erstellen",
|
||||
"createAccountAction": "Konto erstellen",
|
||||
"creating": "Wird erstellt...",
|
||||
"alreadyHaveAccount": "Schon ein Konto? Anmelden",
|
||||
"allFieldsRequired": "Alle Felder sind erforderlich",
|
||||
"loginFailed": "Anmeldung fehlgeschlagen",
|
||||
"registrationFailed": "Registrierung fehlgeschlagen"
|
||||
},
|
||||
"achievements": {
|
||||
"familyProgress": "Fortschritt der Familie",
|
||||
"firstStep": "Erster Schritt",
|
||||
"firstStepDesc": "Erledige deine erste Aufgabe",
|
||||
"helper": "Kleiner Helfer",
|
||||
"helperDesc": "Erledige 10 Aufgaben",
|
||||
"busyBee": "Fleissige Biene",
|
||||
"busyBeeDesc": "Erledige 25 Aufgaben",
|
||||
"cleaningHero": "Putzheld",
|
||||
"cleaningHeroDesc": "Erledige 50 Aufgaben",
|
||||
"choreChampion": "Aufgaben-Champion",
|
||||
"choreChampionDesc": "Erledige 100 Aufgaben",
|
||||
"legend": "TidyQuest-Legende",
|
||||
"legendDesc": "Erledige 250 Aufgaben",
|
||||
"unstoppable": "Unaufhaltbar!",
|
||||
"unstoppableDesc": "Erledige 500 Aufgaben",
|
||||
"onFire": "In Flammen",
|
||||
"onFireDesc": "Erreiche eine 3-Tage-Serie",
|
||||
"streakMaster": "Serien-Meister",
|
||||
"streakMasterDesc": "Erreiche eine 7-Tage-Serie",
|
||||
"twoWeekWarrior": "Zwei-Wochen-Krieger",
|
||||
"twoWeekWarriorDesc": "Erreiche eine 14-Tage-Serie",
|
||||
"monthlyMachine": "Monats-Maschine",
|
||||
"monthlyMachineDesc": "Erreiche eine 30-Tage-Serie",
|
||||
"centurion": "Zenturio",
|
||||
"centurionDesc": "Erreiche eine 100-Tage-Serie!",
|
||||
"piggyBank": "Sparschwein",
|
||||
"piggyBankDesc": "Verdiene 50 Munzen",
|
||||
"saver": "Sparer",
|
||||
"saverDesc": "Verdiene 100 Munzen",
|
||||
"treasureHunter": "Schatzsucherin",
|
||||
"treasureHunterDesc": "Verdiene 500 Munzen",
|
||||
"goldMaster": "Goldmeister",
|
||||
"goldMasterDesc": "Verdiene 1.000 Munzen",
|
||||
"millionaire": "Millionar",
|
||||
"millionaireDesc": "Verdiene 5.000 Munzen",
|
||||
"roomTamer": "Zimmer-Bandiger",
|
||||
"roomTamerDesc": "Halte 3 Zimmer gleichzeitig gesund",
|
||||
"housePride": "Hausstolz",
|
||||
"housePrideDesc": "Halte 5 Zimmer gleichzeitig gesund",
|
||||
"weekendWarrior": "Wochenend-Krieger",
|
||||
"weekendWarriorDesc": "Erledige 5 Aufgaben in einer Woche",
|
||||
"superWeek": "Super Woche",
|
||||
"superWeekDesc": "Erledige 15 Aufgaben in einer Woche",
|
||||
"perfectWeek": "Perfekte Woche",
|
||||
"perfectWeekDesc": "Erledige jeden Tag mindestens 1 Aufgabe eine Woche lang",
|
||||
"perfectMonth": "Perfekter Monat",
|
||||
"perfectMonthDesc": "Schaffe 4 perfekte Wochen",
|
||||
"nightOwl": "Nachtplaner",
|
||||
"nightOwlDesc": "Erreiche eine 60-Tage-Serie"
|
||||
}
|
||||
}
|
||||
}
|
||||
512
client/src/i18n/en.json
Normal file
512
client/src/i18n/en.json
Normal file
|
|
@ -0,0 +1,512 @@
|
|||
{
|
||||
"tasks": {
|
||||
"kitchen": {
|
||||
"wash_dishes": "Wash dishes",
|
||||
"clean_counters": "Clean counters",
|
||||
"wipe_stovetop": "Wipe stovetop",
|
||||
"empty_trash": "Empty trash",
|
||||
"empty_household_waste": "Empty household waste",
|
||||
"empty_compost": "Empty compost",
|
||||
"empty_plastic_recycling": "Empty plastic recycling",
|
||||
"empty_glass_recycling": "Empty glass recycling",
|
||||
"clean_sink": "Clean sink",
|
||||
"clean_sink_drain": "Clean sink drain",
|
||||
"wipe_appliances": "Wipe appliances",
|
||||
"mop_floor": "Mop floor",
|
||||
"clean_microwave": "Clean microwave",
|
||||
"wipe_cabinet_fronts": "Wipe cabinet fronts",
|
||||
"clean_fridge": "Clean fridge",
|
||||
"defrost_freezer": "Defrost freezer",
|
||||
"descale_kettle": "Descale kettle",
|
||||
"clean_dishwasher": "Clean dishwasher",
|
||||
"clean_dishwasher_filter": "Clean dishwasher filter",
|
||||
"check_dishwasher_salt": "Check/add dishwasher salt",
|
||||
"clean_oven": "Clean oven",
|
||||
"clean_range_hood": "Clean range hood",
|
||||
"deep_clean_fridge": "Deep clean fridge",
|
||||
"organize_pantry": "Organize pantry"
|
||||
},
|
||||
"bedroom": {
|
||||
"make_bed": "Make bed",
|
||||
"tidy_nightstand": "Tidy nightstand",
|
||||
"change_sheets": "Change sheets",
|
||||
"vacuum_floor": "Vacuum floor",
|
||||
"dust_surfaces": "Dust surfaces",
|
||||
"clean_under_bed": "Clean under bed",
|
||||
"wash_pillows": "Wash pillows",
|
||||
"wash_duvet": "Wash duvet",
|
||||
"change_fitted_sheet": "Change fitted sheet",
|
||||
"organize_closet": "Organize closet",
|
||||
"flip_mattress": "Flip mattress",
|
||||
"clean_windows": "Clean windows",
|
||||
"wash_curtains": "Wash curtains"
|
||||
},
|
||||
"bathroom": {
|
||||
"wipe_sink_counter": "Wipe sink & counter",
|
||||
"squeegee_shower": "Squeegee shower",
|
||||
"scrub_toilet": "Scrub toilet",
|
||||
"clean_mirror": "Clean mirror",
|
||||
"wash_towels": "Wash towels",
|
||||
"clean_shower_tub": "Clean shower & tub",
|
||||
"clean_sink_drain": "Clean sink drain",
|
||||
"mop_floor": "Mop floor",
|
||||
"clean_shower_drain": "Clean shower drain",
|
||||
"wash_bath_mat": "Wash bath mat",
|
||||
"wipe_switches_handles": "Wipe switches & handles",
|
||||
"clean_grout": "Clean grout",
|
||||
"descale_showerhead": "Descale showerhead",
|
||||
"wash_shower_curtain": "Wash shower curtain",
|
||||
"organize_cabinets": "Organize cabinets",
|
||||
"replace_toothbrush": "Replace toothbrush"
|
||||
},
|
||||
"living": {
|
||||
"tidy_up": "Tidy up",
|
||||
"fluff_cushions": "Fluff cushions",
|
||||
"vacuum_carpet": "Vacuum carpet",
|
||||
"dust_surfaces_shelves": "Dust surfaces & shelves",
|
||||
"wipe_tv": "Wipe TV",
|
||||
"clean_remotes": "Clean remotes",
|
||||
"dust_lampshades": "Dust lampshades",
|
||||
"vacuum_sofa": "Vacuum sofa",
|
||||
"clean_windows": "Clean windows",
|
||||
"wash_curtains_blinds": "Wash curtains & blinds",
|
||||
"deep_clean_carpet": "Deep clean carpet",
|
||||
"clean_behind_furniture": "Clean behind furniture",
|
||||
"polish_furniture": "Polish furniture"
|
||||
},
|
||||
"office": {
|
||||
"clear_desk": "Clear desk",
|
||||
"wipe_desk": "Wipe desk",
|
||||
"clean_keyboard_mouse": "Clean keyboard & mouse",
|
||||
"wipe_monitor": "Wipe monitor",
|
||||
"empty_paper_trash": "Empty paper trash",
|
||||
"vacuum_floor": "Vacuum floor",
|
||||
"organize_cables": "Organize cables",
|
||||
"dust_shelves": "Dust shelves",
|
||||
"clean_desk_lamp": "Clean desk lamp",
|
||||
"organize_drawers": "Organize drawers",
|
||||
"wipe_switches": "Wipe switches",
|
||||
"clean_chair": "Clean chair"
|
||||
},
|
||||
"garage": {
|
||||
"sweep_floor": "Sweep floor",
|
||||
"organize_tools": "Organize tools",
|
||||
"clean_workbench": "Clean workbench",
|
||||
"clear_cobwebs": "Clear cobwebs",
|
||||
"organize_shelves": "Organize shelves",
|
||||
"wipe_power_tools": "Wipe power tools",
|
||||
"sort_recycling": "Sort recycling",
|
||||
"mop_hose_floor": "Mop or hose floor",
|
||||
"check_chemicals": "Check chemicals",
|
||||
"clean_door_tracks": "Clean door tracks"
|
||||
},
|
||||
"laundry": {
|
||||
"wipe_washer_seal": "Wipe washer seal",
|
||||
"clean_lint_filter": "Clean lint filter",
|
||||
"wipe_machine_exterior": "Wipe machine exterior",
|
||||
"run_cleaning_cycle": "Run cleaning cycle",
|
||||
"drain_washing_machine": "Drain washing machine",
|
||||
"descale_washing_machine": "Descale washing machine",
|
||||
"clean_detergent_drawer": "Clean detergent drawer",
|
||||
"sweep_mop_floor": "Sweep & mop floor",
|
||||
"organize_supplies": "Organize supplies",
|
||||
"clean_dryer_vent": "Clean dryer vent",
|
||||
"wipe_folding_surface": "Wipe folding surface",
|
||||
"sort_donate_clothes": "Sort & donate clothes"
|
||||
}
|
||||
},
|
||||
"rooms": {
|
||||
"kitchen": "Kitchen",
|
||||
"bedroom": "Bedroom",
|
||||
"bathroom": "Bathroom",
|
||||
"living": "Living Room",
|
||||
"office": "Office",
|
||||
"garage": "Garage",
|
||||
"laundry": "Laundry Room",
|
||||
"other": "Other"
|
||||
},
|
||||
"ui": {
|
||||
"profile": {
|
||||
"title": "Profile",
|
||||
"displayName": "Display Name",
|
||||
"avatarMode": "Avatar Mode",
|
||||
"letterMode": "Letter",
|
||||
"characterMode": "Character",
|
||||
"photoMode": "Photo",
|
||||
"uploadPhoto": "Upload Photo",
|
||||
"language": "Language",
|
||||
"save": "Save",
|
||||
"saved": "Saved",
|
||||
"logout": "Log out"
|
||||
},
|
||||
"settings": {
|
||||
"title": "Settings",
|
||||
"general": "General",
|
||||
"notifications": "Notifications",
|
||||
"notificationsDesc": "Daily cleaning reminders",
|
||||
"theme": "Theme",
|
||||
"themeDesc": "Switch the app color mood",
|
||||
"themeOrange": "Warm Orange",
|
||||
"themeBlue": "Light Blue",
|
||||
"themeRose": "Light Rose",
|
||||
"themeNight": "Night",
|
||||
"vacationMode": "Vacation Mode",
|
||||
"vacationDesc": "Pause all task reminders while you're away",
|
||||
"adminRequired": "Parent admin required to change settings.",
|
||||
"data": "Data",
|
||||
"dataPrivacy": "Data & Privacy",
|
||||
"export": "Export",
|
||||
"exportData": "Export Data",
|
||||
"exportDesc": "Download JSON backup",
|
||||
"download": "Download",
|
||||
"import": "Import",
|
||||
"importData": "Import Data",
|
||||
"importDesc": "Restore from backup",
|
||||
"upload": "Upload",
|
||||
"family": "Family",
|
||||
"familyMembers": "Family Members",
|
||||
"addMember": "Add Member",
|
||||
"memberDisplayName": "Display name",
|
||||
"memberUsername": "Username",
|
||||
"memberPassword": "Password",
|
||||
"passwordSection": "Password",
|
||||
"currentPassword": "Current password",
|
||||
"newPassword": "New password",
|
||||
"confirmPassword": "Confirm new password",
|
||||
"updatePassword": "Update password",
|
||||
"resetPassword": "Reset password",
|
||||
"passwordMismatch": "Passwords do not match.",
|
||||
"passwordUpdated": "Password updated.",
|
||||
"passwordUpdateFailed": "Failed to update password.",
|
||||
"manageChild": "Manage child",
|
||||
"coinsPerEffort": "Coins per effort",
|
||||
"coinsPerEffortDesc": "Set how many coins are earned for effort levels 1 to 5.",
|
||||
"goalsSection": "Goals by member",
|
||||
"goalsSectionDesc": "Set coin targets and period for each child/member.",
|
||||
"useDefaultCoins": "Use default values",
|
||||
"create": "Create",
|
||||
"privacy": "Privacy",
|
||||
"privacyDesc": "All data stays on your server",
|
||||
"docker": "Docker",
|
||||
"roleAdmin": "Admin",
|
||||
"roleChild": "Child",
|
||||
"setAs": "Set as",
|
||||
"coins": "coins",
|
||||
"streak": "streak",
|
||||
"roleMember": "Member",
|
||||
"deleteUser": "Delete user",
|
||||
"deleteUserConfirm": "Delete \"{user}\"? This cannot be undone.",
|
||||
"goalCoins": "Goal coins",
|
||||
"goalTitle": "Goal title",
|
||||
"setGoal": "Set goal",
|
||||
"addGoal": "Add goal",
|
||||
"manageMember": "Manage member",
|
||||
"goalStart": "Start date",
|
||||
"goalEnd": "End date",
|
||||
"goalDeleted": "Goal deleted.",
|
||||
"goalDeleteFailed": "Failed to delete goal.",
|
||||
"rewardsSection": "Rewards Catalog",
|
||||
"rewardsSectionDesc": "Parents can create rewards children can buy with coins.",
|
||||
"rewardTitle": "Reward title",
|
||||
"rewardDesc": "Description",
|
||||
"rewardCost": "Coins cost",
|
||||
"addPresetRewards": "Add preset rewards",
|
||||
"rewardRequests": "Reward requests",
|
||||
"noRewardRequests": "No reward requests yet.",
|
||||
"telegramChatId": "Telegram chat ID",
|
||||
"telegramChatIdHint": "Expected: numeric chat ID (example: 123456789 or -1001234567890). Open Telegram chat with your bot first.",
|
||||
"notificationTime": "Notification time",
|
||||
"telegramToken": "Telegram bot token",
|
||||
"telegramTokenHint": "Expected: bot token from @BotFather (format like 123456789:AA...).",
|
||||
"telegramTokenConfigured": "Telegram token already configured (enter to replace)",
|
||||
"telegramChatIdRequired": "Telegram chat ID is required when notifications are enabled.",
|
||||
"telegramTokenRequired": "Telegram bot token is required when notifications are enabled.",
|
||||
"notificationsDisabledHint": "Enable Notifications to configure Telegram and notification time.",
|
||||
"notificationTypeTaskDue": "Task due reminders",
|
||||
"notificationTypeRewardRequest": "Reward requests",
|
||||
"notificationTypeAchievementUnlocked": "Achievement unlocked",
|
||||
"sendTestNotification": "Send test notification",
|
||||
"notificationsSaved": "Notifications settings saved.",
|
||||
"notificationsSaveFailed": "Failed to save notifications settings.",
|
||||
"notificationsTestSent": "Test notification sent.",
|
||||
"notificationsTestFailed": "Failed to send test notification."
|
||||
},
|
||||
"nav": {
|
||||
"home": "Home",
|
||||
"rooms": "Rooms",
|
||||
"board": "Board",
|
||||
"calendar": "Calendar",
|
||||
"activity": "Activity",
|
||||
"rewards": "Rewards",
|
||||
"settings": "Settings",
|
||||
"profile": "Profile",
|
||||
"tagline": "Level up your home",
|
||||
"achievements": "Achievements"
|
||||
},
|
||||
"app": {
|
||||
"roomsConfigured": "rooms configured",
|
||||
"calendarSubtitle": "Track your cleaning history",
|
||||
"leaderboardTitle": "Leaderboard",
|
||||
"leaderboardSubtitle": "Who's keeping the house clean?",
|
||||
"historyTitle": "Activity Log",
|
||||
"historySubtitle": "All completed tasks",
|
||||
"activitySubtitle": "Who did what, when, and for how many points",
|
||||
"rewardsSubtitle": "Spend your coins on real-life rewards",
|
||||
"profileSubtitle": "Customize your avatar & preferences",
|
||||
"settingsSubtitle": "Configure your experience",
|
||||
"achievementsSubtitle": "Turn chores into a game with badges and milestones"
|
||||
},
|
||||
"calendar": {
|
||||
"mon": "Mon",
|
||||
"tue": "Tue",
|
||||
"wed": "Wed",
|
||||
"thu": "Thu",
|
||||
"fri": "Fri",
|
||||
"sat": "Sat",
|
||||
"sun": "Sun",
|
||||
"choresDone": "Chores done",
|
||||
"tasksDue": "Tasks due",
|
||||
"today": "Today",
|
||||
"upcomingDueDates": "Upcoming Due Dates",
|
||||
"inDays": "in {days}d",
|
||||
"allCaughtUp": "All caught up! No tasks due soon."
|
||||
},
|
||||
"leaderboard": {
|
||||
"thisWeek": "This Week",
|
||||
"thisMonth": "This Month",
|
||||
"thisQuarter": "This Quarter",
|
||||
"thisYear": "This Year",
|
||||
"points": "points",
|
||||
"streak": "streak",
|
||||
"noData": "No data yet for this period."
|
||||
},
|
||||
"rewards": {
|
||||
"catalog": "Rewards Catalog",
|
||||
"balanceHint": "Complete tasks to earn coins, then redeem a reward.",
|
||||
"noDescription": "No description",
|
||||
"redeem": "Redeem",
|
||||
"notEnough": "Not enough coins",
|
||||
"myRequests": "My redemption history",
|
||||
"noRequests": "No reward redeemed yet.",
|
||||
"confirmTitle": "Confirm purchase",
|
||||
"confirmText": "Buy \"{reward}\" for {coins} coins?",
|
||||
"confirmBuy": "Confirm",
|
||||
"cancelRequest": "Cancel",
|
||||
"statusPending": "Pending",
|
||||
"statusApproved": "Approved",
|
||||
"statusRejected": "Rejected",
|
||||
"statusCancelled": "Cancelled"
|
||||
},
|
||||
"rewardsPreset": {
|
||||
"movie_night": { "title": "Movie Night Pick", "desc": "Choose tonight's family movie." },
|
||||
"ice_cream": { "title": "Ice Cream Treat", "desc": "Get an ice cream or special dessert." },
|
||||
"late_bedtime": { "title": "Stay Up 30 Min", "desc": "Go to bed 30 minutes later." },
|
||||
"game_bonus": { "title": "Game Time Bonus", "desc": "Get 30 extra minutes of game time." },
|
||||
"choose_dinner": { "title": "Choose Dinner", "desc": "Pick what the family eats tonight." },
|
||||
"park_adventure": { "title": "Park Adventure", "desc": "Special family park outing." },
|
||||
"chore_pass": { "title": "No-Chore Pass", "desc": "Skip one chore this week." },
|
||||
"board_game": { "title": "Family Board Game", "desc": "Pick the board game for family night." }
|
||||
},
|
||||
"history": {
|
||||
"task": "Task",
|
||||
"room": "Room",
|
||||
"when": "When",
|
||||
"earned": "Earned",
|
||||
"by": "by",
|
||||
"noActivity": "No activity yet. Complete a task to get started!",
|
||||
"previous": "Previous",
|
||||
"next": "Next",
|
||||
"of": "of"
|
||||
},
|
||||
"roomDetail": {
|
||||
"name": "Name",
|
||||
"notes": "Notes",
|
||||
"optionalNotes": "Optional notes...",
|
||||
"every": "Every",
|
||||
"effort": "Effort",
|
||||
"frequency": "Frequency",
|
||||
"actions": "Actions",
|
||||
"deleteTask": "Delete Task",
|
||||
"done": "Done",
|
||||
"seasonal": "Seasonal",
|
||||
"taskName": "Task name...",
|
||||
"addTask": "Add Task"
|
||||
},
|
||||
"avatars": {
|
||||
"cat": "Cat",
|
||||
"dog": "Dog",
|
||||
"bunny": "Bunny",
|
||||
"bear": "Bear",
|
||||
"fox": "Fox",
|
||||
"owl": "Owl",
|
||||
"panda": "Panda",
|
||||
"penguin": "Penguin",
|
||||
"unicorn": "Unicorn",
|
||||
"frog": "Frog",
|
||||
"koala": "Koala",
|
||||
"hedgehog": "Hedgehog"
|
||||
},
|
||||
"dashboard": {
|
||||
"houseHealth": "House Health",
|
||||
"todaysQuests": "Today's Quests",
|
||||
"recentActivity": "Recent Activity",
|
||||
"noQuests": "No quests for today",
|
||||
"roomsCount": "Rooms",
|
||||
"tasksCount": "Tasks",
|
||||
"criticalCount": "Critical",
|
||||
"pending": "pending",
|
||||
"sortedUrgency": "Sorted by urgency",
|
||||
"dayStreak": "Day Streak",
|
||||
"keepStreak": "Complete 1 task daily to keep going!",
|
||||
"streakDoneToday": "Streak completed for today!",
|
||||
"more": "More",
|
||||
"nextTasks": "Next tasks to come",
|
||||
"healthGreat": "Looking great! Keep it up.",
|
||||
"healthMedium": "Some rooms need a bit of love.",
|
||||
"healthLow": "Time for a cleaning session!",
|
||||
"myGoal": "My Goal",
|
||||
"childrenGoals": "Children Goals",
|
||||
"noGoal": "No goal",
|
||||
"rewardRequestsTitle": "Reward requests",
|
||||
"rewardRequestEmpty": "No pending reward requests.",
|
||||
"coinsStatusTitle": "Coins status",
|
||||
"approve": "Approve",
|
||||
"reject": "Reject"
|
||||
},
|
||||
"rooms": {
|
||||
"addRoom": "Add Room",
|
||||
"room": "Room",
|
||||
"tasks": "Tasks",
|
||||
"health": "Health",
|
||||
"healthHealthy": "Healthy",
|
||||
"healthNeedsAttention": "Needs attention",
|
||||
"healthCritical": "Critical",
|
||||
"deleteRoomConfirm": "Delete \"{room}\" and all its tasks? This cannot be undone.",
|
||||
"noRoomsYet": "No rooms yet",
|
||||
"clickAddRoom": "Click \"Add Room\" to get started!",
|
||||
"addRoomTitle": "Add a Room",
|
||||
"pickRoomType": "Pick a room type, then configure its tasks.",
|
||||
"customNameOptional": "Custom Name (optional)",
|
||||
"nextConfigure": "Next: Configure Tasks",
|
||||
"configureTasks": "Configure Tasks",
|
||||
"configureTasksDesc": "Select tasks, set their current state, effort, and cleaning frequency.",
|
||||
"currentState": "Current State",
|
||||
"dirty": "Dirty",
|
||||
"clean": "Clean",
|
||||
"addCustomTask": "Add a custom task...",
|
||||
"tasksSelected": "tasks selected",
|
||||
"createRoom": "Create Room",
|
||||
"roomNotFound": "Room not found.",
|
||||
"backToRooms": "Back to Rooms",
|
||||
"tasksTracked": "tasks tracked"
|
||||
},
|
||||
"common": {
|
||||
"save": "Save",
|
||||
"saved": "Saved",
|
||||
"cancel": "Cancel",
|
||||
"delete": "Delete",
|
||||
"edit": "Edit",
|
||||
"loading": "Loading",
|
||||
"add": "Add"
|
||||
},
|
||||
"units": {
|
||||
"hours": "hours",
|
||||
"days": "days",
|
||||
"weeks": "weeks",
|
||||
"months": "months",
|
||||
"years": "years"
|
||||
},
|
||||
"unitsShort": {
|
||||
"hours": "h",
|
||||
"days": "d",
|
||||
"weeks": "w",
|
||||
"months": "mo",
|
||||
"years": "y"
|
||||
},
|
||||
"time": {
|
||||
"never": "Never",
|
||||
"justNow": "just now",
|
||||
"minutesAgo": "{count}m ago",
|
||||
"hoursAgo": "{count}h ago",
|
||||
"yesterday": "yesterday",
|
||||
"daysAgo": "{count}d ago",
|
||||
"oneWeekAgo": "1w ago",
|
||||
"weeksAgo": "{count}w ago",
|
||||
"oneMonthAgo": "1mo ago",
|
||||
"monthsAgo": "{count}mo ago"
|
||||
},
|
||||
"auth": {
|
||||
"welcomeBack": "Welcome!",
|
||||
"welcome": "Welcome to TidyQuest",
|
||||
"createYourAccount": "Create your account",
|
||||
"username": "Username",
|
||||
"usernamePlaceholder": "Enter your username",
|
||||
"password": "Password",
|
||||
"passwordPlaceholder": "Enter your password",
|
||||
"passwordMinChars": "min 4 characters",
|
||||
"displayName": "Display Name",
|
||||
"displayNamePlaceholder": "John",
|
||||
"avatarColor": "Avatar Color",
|
||||
"loggingIn": "Logging in...",
|
||||
"logIn": "Log In",
|
||||
"createAccount": "Create account",
|
||||
"createAccountAction": "Create Account",
|
||||
"creating": "Creating...",
|
||||
"alreadyHaveAccount": "Already have an account? Log in",
|
||||
"allFieldsRequired": "All fields are required",
|
||||
"loginFailed": "Login failed",
|
||||
"registrationFailed": "Registration failed"
|
||||
},
|
||||
"achievements": {
|
||||
"familyProgress": "Family Progress",
|
||||
"firstStep": "First Step",
|
||||
"firstStepDesc": "Complete your first chore",
|
||||
"helper": "Little Helper",
|
||||
"helperDesc": "Complete 10 chores",
|
||||
"busyBee": "Busy Bee",
|
||||
"busyBeeDesc": "Complete 25 chores",
|
||||
"cleaningHero": "Cleaning Hero",
|
||||
"cleaningHeroDesc": "Complete 50 chores",
|
||||
"choreChampion": "Chore Champion",
|
||||
"choreChampionDesc": "Complete 100 chores",
|
||||
"legend": "TidyQuest Legend",
|
||||
"legendDesc": "Complete 250 chores",
|
||||
"unstoppable": "Unstoppable!",
|
||||
"unstoppableDesc": "Complete 500 chores",
|
||||
"onFire": "On Fire",
|
||||
"onFireDesc": "Reach a 3-day streak",
|
||||
"streakMaster": "Streak Master",
|
||||
"streakMasterDesc": "Reach a 7-day streak",
|
||||
"twoWeekWarrior": "Two-Week Warrior",
|
||||
"twoWeekWarriorDesc": "Reach a 14-day streak",
|
||||
"monthlyMachine": "Monthly Machine",
|
||||
"monthlyMachineDesc": "Reach a 30-day streak",
|
||||
"centurion": "Centurion",
|
||||
"centurionDesc": "Reach a 100-day streak!",
|
||||
"piggyBank": "Piggy Bank",
|
||||
"piggyBankDesc": "Earn 50 coins",
|
||||
"saver": "Saver",
|
||||
"saverDesc": "Earn 100 coins",
|
||||
"treasureHunter": "Treasure Hunter",
|
||||
"treasureHunterDesc": "Earn 500 coins",
|
||||
"goldMaster": "Gold Master",
|
||||
"goldMasterDesc": "Earn 1,000 coins",
|
||||
"millionaire": "Millionaire",
|
||||
"millionaireDesc": "Earn 5,000 coins",
|
||||
"roomTamer": "Room Tamer",
|
||||
"roomTamerDesc": "Keep 3 rooms healthy at the same time",
|
||||
"housePride": "House Pride",
|
||||
"housePrideDesc": "Keep 5 rooms healthy at the same time",
|
||||
"weekendWarrior": "Weekend Warrior",
|
||||
"weekendWarriorDesc": "Complete 5 chores in one week",
|
||||
"superWeek": "Super Week",
|
||||
"superWeekDesc": "Complete 15 chores in one week",
|
||||
"perfectWeek": "Perfect Week",
|
||||
"perfectWeekDesc": "Complete at least 1 chore every day for a full week",
|
||||
"perfectMonth": "Perfect Month",
|
||||
"perfectMonthDesc": "Have 4 perfect weeks",
|
||||
"nightOwl": "Night Owl Planner",
|
||||
"nightOwlDesc": "Reach a 60-day streak"
|
||||
}
|
||||
}
|
||||
}
|
||||
512
client/src/i18n/es.json
Normal file
512
client/src/i18n/es.json
Normal file
|
|
@ -0,0 +1,512 @@
|
|||
{
|
||||
"tasks": {
|
||||
"kitchen": {
|
||||
"wash_dishes": "Lavar los platos",
|
||||
"clean_counters": "Limpiar las encimeras",
|
||||
"wipe_stovetop": "Limpiar la vitrocerámica",
|
||||
"empty_trash": "Vaciar la basura",
|
||||
"empty_household_waste": "Vaciar la basura doméstica",
|
||||
"empty_compost": "Vaciar el compost",
|
||||
"empty_plastic_recycling": "Vaciar los plásticos",
|
||||
"empty_glass_recycling": "Vaciar el vidrio",
|
||||
"clean_sink": "Limpiar el fregadero",
|
||||
"clean_sink_drain": "Limpiar el sifón del fregadero",
|
||||
"wipe_appliances": "Limpiar los electrodomésticos",
|
||||
"mop_floor": "Fregar el suelo",
|
||||
"clean_microwave": "Limpiar el microondas",
|
||||
"wipe_cabinet_fronts": "Limpiar los frentes de los armarios",
|
||||
"clean_fridge": "Limpiar la nevera",
|
||||
"defrost_freezer": "Descongelar el congelador",
|
||||
"descale_kettle": "Descalcificar el hervidor",
|
||||
"clean_dishwasher": "Limpiar el lavavajillas",
|
||||
"clean_dishwasher_filter": "Limpiar el filtro del lavavajillas",
|
||||
"check_dishwasher_salt": "Comprobar/añadir sal al lavavajillas",
|
||||
"clean_oven": "Limpiar el horno",
|
||||
"clean_range_hood": "Limpiar la campana extractora",
|
||||
"deep_clean_fridge": "Limpieza profunda de la nevera",
|
||||
"organize_pantry": "Organizar la despensa"
|
||||
},
|
||||
"bedroom": {
|
||||
"make_bed": "Hacer la cama",
|
||||
"tidy_nightstand": "Ordenar la mesita de noche",
|
||||
"change_sheets": "Cambiar las sábanas",
|
||||
"vacuum_floor": "Aspirar el suelo",
|
||||
"dust_surfaces": "Quitar el polvo de las superficies",
|
||||
"clean_under_bed": "Limpiar debajo de la cama",
|
||||
"wash_pillows": "Lavar las almohadas",
|
||||
"wash_duvet": "Lavar el edredón",
|
||||
"change_fitted_sheet": "Cambiar la sábana bajera",
|
||||
"organize_closet": "Organizar el armario",
|
||||
"flip_mattress": "Girar el colchón",
|
||||
"clean_windows": "Limpiar las ventanas",
|
||||
"wash_curtains": "Lavar las cortinas"
|
||||
},
|
||||
"bathroom": {
|
||||
"wipe_sink_counter": "Limpiar el lavabo y la encimera",
|
||||
"squeegee_shower": "Pasar la rasqueta en la ducha",
|
||||
"scrub_toilet": "Fregar el inodoro",
|
||||
"clean_mirror": "Limpiar el espejo",
|
||||
"wash_towels": "Lavar las toallas",
|
||||
"clean_shower_tub": "Limpiar la ducha y la bañera",
|
||||
"clean_sink_drain": "Limpiar el desagüe del lavabo",
|
||||
"mop_floor": "Fregar el suelo",
|
||||
"clean_shower_drain": "Limpiar el desagüe de la ducha",
|
||||
"wash_bath_mat": "Lavar la alfombrilla de baño",
|
||||
"wipe_switches_handles": "Limpiar interruptores y manillas",
|
||||
"clean_grout": "Limpiar las juntas",
|
||||
"descale_showerhead": "Descalcificar el cabezal de ducha",
|
||||
"wash_shower_curtain": "Lavar la cortina de ducha",
|
||||
"organize_cabinets": "Organizar los armarios",
|
||||
"replace_toothbrush": "Reemplazar el cepillo de dientes"
|
||||
},
|
||||
"living": {
|
||||
"tidy_up": "Ordenar",
|
||||
"fluff_cushions": "Ahuecar los cojines",
|
||||
"vacuum_carpet": "Aspirar la alfombra",
|
||||
"dust_surfaces_shelves": "Quitar el polvo de superficies y estantes",
|
||||
"wipe_tv": "Limpiar la tele",
|
||||
"clean_remotes": "Limpiar los mandos a distancia",
|
||||
"dust_lampshades": "Quitar el polvo de las pantallas de lámpara",
|
||||
"vacuum_sofa": "Aspirar el sofá",
|
||||
"clean_windows": "Limpiar las ventanas",
|
||||
"wash_curtains_blinds": "Lavar cortinas y persianas",
|
||||
"deep_clean_carpet": "Limpieza profunda de la alfombra",
|
||||
"clean_behind_furniture": "Limpiar detrás de los muebles",
|
||||
"polish_furniture": "Pulir los muebles"
|
||||
},
|
||||
"office": {
|
||||
"clear_desk": "Despejar el escritorio",
|
||||
"wipe_desk": "Limpiar el escritorio",
|
||||
"clean_keyboard_mouse": "Limpiar el teclado y el ratón",
|
||||
"wipe_monitor": "Limpiar el monitor",
|
||||
"empty_paper_trash": "Vaciar la papelera",
|
||||
"vacuum_floor": "Aspirar el suelo",
|
||||
"organize_cables": "Organizar los cables",
|
||||
"dust_shelves": "Quitar el polvo de los estantes",
|
||||
"clean_desk_lamp": "Limpiar la lámpara de escritorio",
|
||||
"organize_drawers": "Organizar los cajones",
|
||||
"wipe_switches": "Limpiar los interruptores",
|
||||
"clean_chair": "Limpiar la silla"
|
||||
},
|
||||
"garage": {
|
||||
"sweep_floor": "Barrer el suelo",
|
||||
"organize_tools": "Organizar las herramientas",
|
||||
"clean_workbench": "Limpiar el banco de trabajo",
|
||||
"clear_cobwebs": "Quitar las telarañas",
|
||||
"organize_shelves": "Organizar los estantes",
|
||||
"wipe_power_tools": "Limpiar las herramientas eléctricas",
|
||||
"sort_recycling": "Clasificar el reciclaje",
|
||||
"mop_hose_floor": "Fregar o manguerear el suelo",
|
||||
"check_chemicals": "Revisar los productos químicos",
|
||||
"clean_door_tracks": "Limpiar los rieles de la puerta"
|
||||
},
|
||||
"laundry": {
|
||||
"wipe_washer_seal": "Limpiar la junta de la lavadora",
|
||||
"clean_lint_filter": "Limpiar el filtro de pelusas",
|
||||
"wipe_machine_exterior": "Limpiar el exterior de la máquina",
|
||||
"run_cleaning_cycle": "Ejecutar ciclo de limpieza",
|
||||
"drain_washing_machine": "Vaciar la lavadora",
|
||||
"descale_washing_machine": "Descalcificar la lavadora",
|
||||
"clean_detergent_drawer": "Limpiar el cajón del detergente",
|
||||
"sweep_mop_floor": "Barrer y fregar el suelo",
|
||||
"organize_supplies": "Organizar los productos",
|
||||
"clean_dryer_vent": "Limpiar la ventilación de la secadora",
|
||||
"wipe_folding_surface": "Limpiar la superficie de plegado",
|
||||
"sort_donate_clothes": "Clasificar y donar ropa"
|
||||
}
|
||||
},
|
||||
"rooms": {
|
||||
"kitchen": "Cocina",
|
||||
"bedroom": "Dormitorio",
|
||||
"bathroom": "Baño",
|
||||
"living": "Salón",
|
||||
"office": "Oficina",
|
||||
"garage": "Garaje",
|
||||
"laundry": "Lavadero",
|
||||
"other": "Otro"
|
||||
},
|
||||
"ui": {
|
||||
"profile": {
|
||||
"title": "Perfil",
|
||||
"displayName": "Nombre visible",
|
||||
"avatarMode": "Modo de avatar",
|
||||
"letterMode": "Letra",
|
||||
"characterMode": "Personaje",
|
||||
"photoMode": "Foto",
|
||||
"uploadPhoto": "Subir foto",
|
||||
"language": "Idioma",
|
||||
"save": "Guardar",
|
||||
"saved": "Guardado",
|
||||
"logout": "Cerrar sesión"
|
||||
},
|
||||
"settings": {
|
||||
"title": "Ajustes",
|
||||
"general": "General",
|
||||
"notifications": "Notificaciones",
|
||||
"notificationsDesc": "Recordatorios diarios de limpieza",
|
||||
"theme": "Tema",
|
||||
"themeDesc": "Cambiar el ambiente de color",
|
||||
"themeOrange": "Naranja cálido",
|
||||
"themeBlue": "Azul claro",
|
||||
"themeRose": "Rosa claro",
|
||||
"themeNight": "Noche",
|
||||
"vacationMode": "Modo vacaciones",
|
||||
"vacationDesc": "Pausar todos los recordatorios de tareas mientras estás fuera",
|
||||
"adminRequired": "Se requiere un padre administrador para cambiar ajustes.",
|
||||
"data": "Datos",
|
||||
"dataPrivacy": "Datos y privacidad",
|
||||
"export": "Exportar",
|
||||
"exportData": "Exportar datos",
|
||||
"exportDesc": "Descargar copia de seguridad JSON",
|
||||
"download": "Descargar",
|
||||
"import": "Importar",
|
||||
"importData": "Importar datos",
|
||||
"importDesc": "Restaurar desde copia de seguridad",
|
||||
"upload": "Subir",
|
||||
"family": "Familia",
|
||||
"familyMembers": "Miembros de la familia",
|
||||
"addMember": "Añadir miembro",
|
||||
"memberDisplayName": "Nombre visible",
|
||||
"memberUsername": "Usuario",
|
||||
"memberPassword": "Contraseña",
|
||||
"passwordSection": "Contraseña",
|
||||
"currentPassword": "Contraseña actual",
|
||||
"newPassword": "Nueva contraseña",
|
||||
"confirmPassword": "Confirmar nueva contraseña",
|
||||
"updatePassword": "Actualizar contraseña",
|
||||
"resetPassword": "Restablecer contraseña",
|
||||
"passwordMismatch": "Las contraseñas no coinciden.",
|
||||
"passwordUpdated": "Contraseña actualizada.",
|
||||
"passwordUpdateFailed": "No se pudo actualizar la contraseña.",
|
||||
"manageChild": "Gestionar niño",
|
||||
"coinsPerEffort": "Monedas por esfuerzo",
|
||||
"coinsPerEffortDesc": "Define cuántas monedas se ganan para niveles de esfuerzo del 1 al 5.",
|
||||
"goalsSection": "Objetivos por miembro",
|
||||
"goalsSectionDesc": "Define metas de monedas y periodo para cada niño/miembro.",
|
||||
"useDefaultCoins": "Usar valores por defecto",
|
||||
"create": "Crear",
|
||||
"privacy": "Privacidad",
|
||||
"privacyDesc": "Todos los datos se quedan en tu servidor",
|
||||
"docker": "Docker",
|
||||
"roleAdmin": "Admin",
|
||||
"roleChild": "Niño",
|
||||
"setAs": "Establecer como",
|
||||
"coins": "monedas",
|
||||
"streak": "racha",
|
||||
"roleMember": "Miembro",
|
||||
"deleteUser": "Eliminar usuario",
|
||||
"deleteUserConfirm": "¿Eliminar a \"{user}\"? Esta acción no se puede deshacer.",
|
||||
"goalCoins": "Monedas objetivo",
|
||||
"goalTitle": "Título del objetivo",
|
||||
"setGoal": "Definir objetivo",
|
||||
"addGoal": "Añadir objetivo",
|
||||
"manageMember": "Gestionar miembro",
|
||||
"goalStart": "Fecha de inicio",
|
||||
"goalEnd": "Fecha de fin",
|
||||
"goalDeleted": "Objetivo eliminado.",
|
||||
"goalDeleteFailed": "No se pudo eliminar el objetivo.",
|
||||
"rewardsSection": "Catálogo de recompensas",
|
||||
"rewardsSectionDesc": "Los padres pueden crear recompensas que se compran con monedas.",
|
||||
"rewardTitle": "Título recompensa",
|
||||
"rewardDesc": "Descripción",
|
||||
"rewardCost": "Costo en monedas",
|
||||
"addPresetRewards": "Añadir recompensas predefinidas",
|
||||
"rewardRequests": "Solicitudes de recompensas",
|
||||
"noRewardRequests": "Todavía no hay solicitudes de recompensas.",
|
||||
"telegramChatId": "ID de chat de Telegram",
|
||||
"telegramChatIdHint": "Esperado: ID de chat numerico (ej: 123456789 o -1001234567890). Primero abre un chat con tu bot.",
|
||||
"notificationTime": "Hora de notificación",
|
||||
"telegramToken": "Token del bot de Telegram",
|
||||
"telegramTokenHint": "Esperado: token del bot de @BotFather (formato como 123456789:AA...).",
|
||||
"telegramTokenConfigured": "Token de Telegram ya configurado (escribe para reemplazar)",
|
||||
"telegramChatIdRequired": "El ID de chat de Telegram es obligatorio si las notificaciones están activadas.",
|
||||
"telegramTokenRequired": "El token de Telegram es obligatorio si las notificaciones están activadas.",
|
||||
"notificationsDisabledHint": "Activa Notificaciones para configurar Telegram y la hora.",
|
||||
"notificationTypeTaskDue": "Recordatorios de tareas",
|
||||
"notificationTypeRewardRequest": "Solicitudes de recompensas",
|
||||
"notificationTypeAchievementUnlocked": "Logro desbloqueado",
|
||||
"sendTestNotification": "Enviar notificación de prueba",
|
||||
"notificationsSaved": "Configuración de notificaciones guardada.",
|
||||
"notificationsSaveFailed": "No se pudo guardar la configuración de notificaciones.",
|
||||
"notificationsTestSent": "Notificacion de prueba enviada.",
|
||||
"notificationsTestFailed": "No se pudo enviar la notificación de prueba."
|
||||
},
|
||||
"nav": {
|
||||
"home": "Inicio",
|
||||
"rooms": "Habitaciones",
|
||||
"board": "Tablero",
|
||||
"calendar": "Calendario",
|
||||
"activity": "Actividad",
|
||||
"rewards": "Recompensas",
|
||||
"settings": "Ajustes",
|
||||
"profile": "Perfil",
|
||||
"tagline": "Sube de nivel tu casa",
|
||||
"achievements": "Logros"
|
||||
},
|
||||
"app": {
|
||||
"roomsConfigured": "habitaciones configuradas",
|
||||
"calendarSubtitle": "Sigue tu historial de limpieza",
|
||||
"leaderboardTitle": "Clasificación",
|
||||
"leaderboardSubtitle": "¿Quién mantiene la casa limpia?",
|
||||
"historyTitle": "Registro de actividad",
|
||||
"historySubtitle": "Todas las tareas completadas",
|
||||
"activitySubtitle": "Quién hizo qué, cuándo y por cuántos puntos",
|
||||
"rewardsSubtitle": "Gasta tus monedas en recompensas reales",
|
||||
"profileSubtitle": "Personaliza tu avatar y preferencias",
|
||||
"settingsSubtitle": "Configura tu experiencia",
|
||||
"achievementsSubtitle": "Convierte las tareas en juego con insignias e hitos"
|
||||
},
|
||||
"calendar": {
|
||||
"mon": "Lun",
|
||||
"tue": "Mar",
|
||||
"wed": "Mié",
|
||||
"thu": "Jue",
|
||||
"fri": "Vie",
|
||||
"sat": "Sáb",
|
||||
"sun": "Dom",
|
||||
"choresDone": "Tareas hechas",
|
||||
"tasksDue": "Tareas pendientes",
|
||||
"today": "Hoy",
|
||||
"upcomingDueDates": "Próximas fechas límite",
|
||||
"inDays": "en {days}d",
|
||||
"allCaughtUp": "¡Todo al día! No hay tareas próximas."
|
||||
},
|
||||
"leaderboard": {
|
||||
"thisWeek": "Esta semana",
|
||||
"thisMonth": "Este mes",
|
||||
"thisQuarter": "Este trimestre",
|
||||
"thisYear": "Este año",
|
||||
"points": "puntos",
|
||||
"streak": "racha",
|
||||
"noData": "Aún no hay datos para este período."
|
||||
},
|
||||
"rewards": {
|
||||
"catalog": "Catálogo de recompensas",
|
||||
"balanceHint": "Completa tareas para ganar monedas y canjear recompensas.",
|
||||
"noDescription": "Sin descripción",
|
||||
"redeem": "Canjear",
|
||||
"notEnough": "No tienes monedas suficientes",
|
||||
"myRequests": "Mi historial de canjes",
|
||||
"noRequests": "Aún no has canjeado recompensas.",
|
||||
"confirmTitle": "Confirmar compra",
|
||||
"confirmText": "¿Comprar \"{reward}\" por {coins} monedas?",
|
||||
"confirmBuy": "Confirmar",
|
||||
"cancelRequest": "Cancelar",
|
||||
"statusPending": "Pendiente",
|
||||
"statusApproved": "Aprobada",
|
||||
"statusRejected": "Rechazada",
|
||||
"statusCancelled": "Cancelada"
|
||||
},
|
||||
"rewardsPreset": {
|
||||
"movie_night": { "title": "Elegir película", "desc": "Escoger la película familiar de esta noche." },
|
||||
"ice_cream": { "title": "Premio helado", "desc": "Tomar un helado o postre especial." },
|
||||
"late_bedtime": { "title": "Dormir +30 min", "desc": "Acostarse 30 minutos más tarde." },
|
||||
"game_bonus": { "title": "Bonus de juego", "desc": "30 minutos extra de tiempo de juego." },
|
||||
"choose_dinner": { "title": "Elegir cena", "desc": "Decidir qué se cena hoy." },
|
||||
"park_adventure": { "title": "Aventura en parque", "desc": "Salida especial al parque en familia." },
|
||||
"chore_pass": { "title": "Pase sin tarea", "desc": "Saltar una tarea esta semana." },
|
||||
"board_game": { "title": "Juego de mesa familiar", "desc": "Elegir el juego de mesa de la noche." }
|
||||
},
|
||||
"history": {
|
||||
"task": "Tarea",
|
||||
"room": "Habitación",
|
||||
"when": "Cuándo",
|
||||
"earned": "Ganado",
|
||||
"by": "por",
|
||||
"noActivity": "Aún no hay actividad. ¡Completa una tarea para empezar!",
|
||||
"previous": "Anterior",
|
||||
"next": "Siguiente",
|
||||
"of": "de"
|
||||
},
|
||||
"roomDetail": {
|
||||
"name": "Nombre",
|
||||
"notes": "Notas",
|
||||
"optionalNotes": "Notas opcionales...",
|
||||
"every": "Cada",
|
||||
"effort": "Esfuerzo",
|
||||
"frequency": "Frecuencia",
|
||||
"actions": "Acciones",
|
||||
"deleteTask": "Eliminar tarea",
|
||||
"done": "Hecho",
|
||||
"seasonal": "Estacional",
|
||||
"taskName": "Nombre de la tarea...",
|
||||
"addTask": "Añadir tarea"
|
||||
},
|
||||
"avatars": {
|
||||
"cat": "Gato",
|
||||
"dog": "Perro",
|
||||
"bunny": "Conejo",
|
||||
"bear": "Oso",
|
||||
"fox": "Zorro",
|
||||
"owl": "Búho",
|
||||
"panda": "Panda",
|
||||
"penguin": "Pingüino",
|
||||
"unicorn": "Unicornio",
|
||||
"frog": "Rana",
|
||||
"koala": "Koala",
|
||||
"hedgehog": "Erizo"
|
||||
},
|
||||
"dashboard": {
|
||||
"houseHealth": "Salud del hogar",
|
||||
"todaysQuests": "Misiones de hoy",
|
||||
"recentActivity": "Actividad reciente",
|
||||
"noQuests": "No hay misiones para hoy",
|
||||
"roomsCount": "Habitaciones",
|
||||
"tasksCount": "Tareas",
|
||||
"criticalCount": "Críticas",
|
||||
"pending": "pendientes",
|
||||
"sortedUrgency": "Ordenadas por urgencia",
|
||||
"dayStreak": "Racha diaria",
|
||||
"keepStreak": "¡Completa 1 tarea al día para mantenerla!",
|
||||
"streakDoneToday": "¡Racha completada por hoy!",
|
||||
"more": "Más",
|
||||
"nextTasks": "Próximas tareas",
|
||||
"healthGreat": "¡Todo va genial! Sigue así.",
|
||||
"healthMedium": "Algunas habitaciones necesitan atención.",
|
||||
"healthLow": "¡Hora de una sesión de limpieza!",
|
||||
"myGoal": "Mi objetivo",
|
||||
"childrenGoals": "Objetivos de niños",
|
||||
"noGoal": "Sin objetivo",
|
||||
"rewardRequestsTitle": "Solicitudes de recompensa",
|
||||
"rewardRequestEmpty": "No hay solicitudes pendientes.",
|
||||
"coinsStatusTitle": "Estado de monedas",
|
||||
"approve": "Aprobar",
|
||||
"reject": "Rechazar"
|
||||
},
|
||||
"rooms": {
|
||||
"addRoom": "Añadir habitación",
|
||||
"room": "Habitación",
|
||||
"tasks": "Tareas",
|
||||
"health": "Salud",
|
||||
"healthHealthy": "Saludable",
|
||||
"healthNeedsAttention": "Necesita atención",
|
||||
"healthCritical": "Crítico",
|
||||
"deleteRoomConfirm": "¿Eliminar \"{room}\" y todas sus tareas? Esta acción no se puede deshacer.",
|
||||
"noRoomsYet": "Aún no hay habitaciones",
|
||||
"clickAddRoom": "¡Haz clic en \"Añadir habitación\" para empezar!",
|
||||
"addRoomTitle": "Añadir una habitación",
|
||||
"pickRoomType": "Elige un tipo de habitación y luego configura sus tareas.",
|
||||
"customNameOptional": "Nombre personalizado (opcional)",
|
||||
"nextConfigure": "Siguiente: configurar tareas",
|
||||
"configureTasks": "Configurar tareas",
|
||||
"configureTasksDesc": "Selecciona tareas y define estado actual, esfuerzo y frecuencia.",
|
||||
"currentState": "Estado actual",
|
||||
"dirty": "Sucio",
|
||||
"clean": "Limpio",
|
||||
"addCustomTask": "Añadir una tarea personalizada...",
|
||||
"tasksSelected": "tareas seleccionadas",
|
||||
"createRoom": "Crear habitación",
|
||||
"roomNotFound": "Habitación no encontrada.",
|
||||
"backToRooms": "Volver a habitaciones",
|
||||
"tasksTracked": "tareas seguidas"
|
||||
},
|
||||
"common": {
|
||||
"save": "Guardar",
|
||||
"saved": "Guardado",
|
||||
"cancel": "Cancelar",
|
||||
"delete": "Eliminar",
|
||||
"edit": "Editar",
|
||||
"loading": "Cargando",
|
||||
"add": "Añadir"
|
||||
},
|
||||
"units": {
|
||||
"hours": "horas",
|
||||
"days": "días",
|
||||
"weeks": "semanas",
|
||||
"months": "meses",
|
||||
"years": "años"
|
||||
},
|
||||
"unitsShort": {
|
||||
"hours": "h",
|
||||
"days": "d",
|
||||
"weeks": "sem",
|
||||
"months": "mes",
|
||||
"years": "a"
|
||||
},
|
||||
"time": {
|
||||
"never": "Nunca",
|
||||
"justNow": "justo ahora",
|
||||
"minutesAgo": "hace {count} min",
|
||||
"hoursAgo": "hace {count} h",
|
||||
"yesterday": "ayer",
|
||||
"daysAgo": "hace {count} d",
|
||||
"oneWeekAgo": "hace 1 sem",
|
||||
"weeksAgo": "hace {count} sem",
|
||||
"oneMonthAgo": "hace 1 mes",
|
||||
"monthsAgo": "hace {count} meses"
|
||||
},
|
||||
"auth": {
|
||||
"welcomeBack": "¡Bienvenido!",
|
||||
"welcome": "Bienvenido a TidyQuest",
|
||||
"createYourAccount": "Crea tu cuenta",
|
||||
"username": "Usuario",
|
||||
"usernamePlaceholder": "Introduce tu usuario",
|
||||
"password": "Contraseña",
|
||||
"passwordPlaceholder": "Introduce tu contraseña",
|
||||
"passwordMinChars": "mín 4 caracteres",
|
||||
"displayName": "Nombre visible",
|
||||
"displayNamePlaceholder": "John",
|
||||
"avatarColor": "Color del avatar",
|
||||
"loggingIn": "Iniciando sesión...",
|
||||
"logIn": "Iniciar sesión",
|
||||
"createAccount": "Crear cuenta",
|
||||
"createAccountAction": "Crear cuenta",
|
||||
"creating": "Creando...",
|
||||
"alreadyHaveAccount": "¿Ya tienes cuenta? Inicia sesión",
|
||||
"allFieldsRequired": "Todos los campos son obligatorios",
|
||||
"loginFailed": "Error de inicio de sesión",
|
||||
"registrationFailed": "Error en el registro"
|
||||
},
|
||||
"achievements": {
|
||||
"familyProgress": "Progreso familiar",
|
||||
"firstStep": "Primer paso",
|
||||
"firstStepDesc": "Completa tu primera tarea",
|
||||
"helper": "Ayudante",
|
||||
"helperDesc": "Completa 10 tareas",
|
||||
"busyBee": "Abeja ocupada",
|
||||
"busyBeeDesc": "Completa 25 tareas",
|
||||
"cleaningHero": "Heroe de la limpieza",
|
||||
"cleaningHeroDesc": "Completa 50 tareas",
|
||||
"choreChampion": "Campeon de las tareas",
|
||||
"choreChampionDesc": "Completa 100 tareas",
|
||||
"legend": "Leyenda TidyQuest",
|
||||
"legendDesc": "Completa 250 tareas",
|
||||
"unstoppable": "Imparable!",
|
||||
"unstoppableDesc": "Completa 500 tareas",
|
||||
"onFire": "En llamas",
|
||||
"onFireDesc": "Alcanza una racha de 3 dias",
|
||||
"streakMaster": "Maestro de racha",
|
||||
"streakMasterDesc": "Alcanza una racha de 7 dias",
|
||||
"twoWeekWarrior": "Guerrero quincenal",
|
||||
"twoWeekWarriorDesc": "Alcanza una racha de 14 dias",
|
||||
"monthlyMachine": "Maquina mensual",
|
||||
"monthlyMachineDesc": "Alcanza una racha de 30 dias",
|
||||
"centurion": "Centurion",
|
||||
"centurionDesc": "Alcanza una racha de 100 dias!",
|
||||
"piggyBank": "Hucha",
|
||||
"piggyBankDesc": "Gana 50 monedas",
|
||||
"saver": "Ahorrador",
|
||||
"saverDesc": "Gana 100 monedas",
|
||||
"treasureHunter": "Cazatesoros",
|
||||
"treasureHunterDesc": "Gana 500 monedas",
|
||||
"goldMaster": "Maestro del oro",
|
||||
"goldMasterDesc": "Gana 1.000 monedas",
|
||||
"millionaire": "Millonario",
|
||||
"millionaireDesc": "Gana 5.000 monedas",
|
||||
"roomTamer": "Domador de habitaciones",
|
||||
"roomTamerDesc": "Mantener 3 habitaciones sanas al mismo tiempo",
|
||||
"housePride": "Orgullo del hogar",
|
||||
"housePrideDesc": "Mantener 5 habitaciones sanas al mismo tiempo",
|
||||
"weekendWarrior": "Guerrero del fin de semana",
|
||||
"weekendWarriorDesc": "Completa 5 tareas en una semana",
|
||||
"superWeek": "Super semana",
|
||||
"superWeekDesc": "Completa 15 tareas en una semana",
|
||||
"perfectWeek": "Semana perfecta",
|
||||
"perfectWeekDesc": "Completa al menos 1 tarea cada dia durante una semana",
|
||||
"perfectMonth": "Mes perfecto",
|
||||
"perfectMonthDesc": "Consigue 4 semanas perfectas",
|
||||
"nightOwl": "Planificador Nocturno",
|
||||
"nightOwlDesc": "Alcanza una racha de 60 días"
|
||||
}
|
||||
}
|
||||
}
|
||||
512
client/src/i18n/fr.json
Normal file
512
client/src/i18n/fr.json
Normal file
|
|
@ -0,0 +1,512 @@
|
|||
{
|
||||
"tasks": {
|
||||
"kitchen": {
|
||||
"wash_dishes": "Faire la vaisselle",
|
||||
"clean_counters": "Nettoyer les plans de travail",
|
||||
"wipe_stovetop": "Essuyer la plaque de cuisson",
|
||||
"empty_trash": "Vider la poubelle",
|
||||
"empty_household_waste": "Vider les ordures ménagères",
|
||||
"empty_compost": "Vider le compost",
|
||||
"empty_plastic_recycling": "Vider les ordures plastiques",
|
||||
"empty_glass_recycling": "Vider les verres",
|
||||
"clean_sink": "Nettoyer l'évier",
|
||||
"clean_sink_drain": "Nettoyer le siphon de l'évier",
|
||||
"wipe_appliances": "Essuyer les appareils",
|
||||
"mop_floor": "Laver le sol",
|
||||
"clean_microwave": "Nettoyer le micro-ondes",
|
||||
"wipe_cabinet_fronts": "Essuyer les façades des placards",
|
||||
"clean_fridge": "Nettoyer le réfrigérateur",
|
||||
"defrost_freezer": "Décongeler le congélateur",
|
||||
"descale_kettle": "Détartrer la bouilloire",
|
||||
"clean_dishwasher": "Nettoyer le lave-vaisselle",
|
||||
"clean_dishwasher_filter": "Nettoyer le filtre du lave-vaisselle",
|
||||
"check_dishwasher_salt": "Contrôler/rajouter du sel dans le lave-vaisselle",
|
||||
"clean_oven": "Nettoyer le four",
|
||||
"clean_range_hood": "Nettoyer la hotte",
|
||||
"deep_clean_fridge": "Nettoyage en profondeur du réfrigérateur",
|
||||
"organize_pantry": "Ranger le garde-manger"
|
||||
},
|
||||
"bedroom": {
|
||||
"make_bed": "Faire le lit",
|
||||
"tidy_nightstand": "Ranger la table de nuit",
|
||||
"change_sheets": "Changer les draps",
|
||||
"vacuum_floor": "Passer l'aspirateur",
|
||||
"dust_surfaces": "Dépoussiérer les surfaces",
|
||||
"clean_under_bed": "Nettoyer sous le lit",
|
||||
"wash_pillows": "Laver les oreillers",
|
||||
"wash_duvet": "Laver la couette",
|
||||
"change_fitted_sheet": "Changer le drap-housse",
|
||||
"organize_closet": "Ranger le placard",
|
||||
"flip_mattress": "Retourner le matelas",
|
||||
"clean_windows": "Nettoyer les fenêtres",
|
||||
"wash_curtains": "Laver les rideaux"
|
||||
},
|
||||
"bathroom": {
|
||||
"wipe_sink_counter": "Essuyer le lavabo et le plan de toilette",
|
||||
"squeegee_shower": "Racler la douche",
|
||||
"scrub_toilet": "Récurer les toilettes",
|
||||
"clean_mirror": "Nettoyer le miroir",
|
||||
"wash_towels": "Laver les serviettes",
|
||||
"clean_shower_tub": "Nettoyer la douche et la baignoire",
|
||||
"clean_sink_drain": "Nettoyer le siphon du lavabo",
|
||||
"mop_floor": "Laver le sol",
|
||||
"clean_shower_drain": "Nettoyer le siphon de douche",
|
||||
"wash_bath_mat": "Laver le tapis de bain",
|
||||
"wipe_switches_handles": "Essuyer les interrupteurs et poignées",
|
||||
"clean_grout": "Nettoyer les joints",
|
||||
"descale_showerhead": "Détartrer le pommeau de douche",
|
||||
"wash_shower_curtain": "Laver le rideau de douche",
|
||||
"organize_cabinets": "Ranger les placards",
|
||||
"replace_toothbrush": "Remplacer la brosse à dents"
|
||||
},
|
||||
"living": {
|
||||
"tidy_up": "Ranger",
|
||||
"fluff_cushions": "Regonfler les coussins",
|
||||
"vacuum_carpet": "Aspirer le tapis",
|
||||
"dust_surfaces_shelves": "Dépoussiérer les surfaces et étagères",
|
||||
"wipe_tv": "Essuyer la télé",
|
||||
"clean_remotes": "Nettoyer les télécommandes",
|
||||
"dust_lampshades": "Dépoussiérer les abat-jour",
|
||||
"vacuum_sofa": "Aspirer le canapé",
|
||||
"clean_windows": "Nettoyer les fenêtres",
|
||||
"wash_curtains_blinds": "Laver les rideaux et stores",
|
||||
"deep_clean_carpet": "Nettoyage en profondeur du tapis",
|
||||
"clean_behind_furniture": "Nettoyer derrière les meubles",
|
||||
"polish_furniture": "Cirer les meubles"
|
||||
},
|
||||
"office": {
|
||||
"clear_desk": "Débarrasser le bureau",
|
||||
"wipe_desk": "Essuyer le bureau",
|
||||
"clean_keyboard_mouse": "Nettoyer le clavier et la souris",
|
||||
"wipe_monitor": "Essuyer l'écran",
|
||||
"empty_paper_trash": "Vider la corbeille à papier",
|
||||
"vacuum_floor": "Passer l'aspirateur",
|
||||
"organize_cables": "Ranger les câbles",
|
||||
"dust_shelves": "Dépoussiérer les étagères",
|
||||
"clean_desk_lamp": "Nettoyer la lampe de bureau",
|
||||
"organize_drawers": "Ranger les tiroirs",
|
||||
"wipe_switches": "Essuyer les interrupteurs",
|
||||
"clean_chair": "Nettoyer la chaise"
|
||||
},
|
||||
"garage": {
|
||||
"sweep_floor": "Balayer le sol",
|
||||
"organize_tools": "Ranger les outils",
|
||||
"clean_workbench": "Nettoyer l'établi",
|
||||
"clear_cobwebs": "Enlever les toiles d'araignée",
|
||||
"organize_shelves": "Ranger les étagères",
|
||||
"wipe_power_tools": "Essuyer les outils électriques",
|
||||
"sort_recycling": "Trier le recyclage",
|
||||
"mop_hose_floor": "Laver le sol au jet ou à la serpillère",
|
||||
"check_chemicals": "Vérifier les produits chimiques",
|
||||
"clean_door_tracks": "Nettoyer les rails de porte"
|
||||
},
|
||||
"laundry": {
|
||||
"wipe_washer_seal": "Essuyer le joint du lave-linge",
|
||||
"clean_lint_filter": "Nettoyer le filtre à peluches",
|
||||
"wipe_machine_exterior": "Essuyer l'extérieur de la machine",
|
||||
"run_cleaning_cycle": "Lancer un cycle de nettoyage",
|
||||
"drain_washing_machine": "Vidanger le lave-linge",
|
||||
"descale_washing_machine": "Détartrer le lave-linge",
|
||||
"clean_detergent_drawer": "Nettoyer le bac à lessive",
|
||||
"sweep_mop_floor": "Balayer et laver le sol",
|
||||
"organize_supplies": "Ranger les produits",
|
||||
"clean_dryer_vent": "Nettoyer l'aération du sèche-linge",
|
||||
"wipe_folding_surface": "Essuyer la surface de pliage",
|
||||
"sort_donate_clothes": "Trier et donner des vêtements"
|
||||
}
|
||||
},
|
||||
"rooms": {
|
||||
"kitchen": "Cuisine",
|
||||
"bedroom": "Chambre",
|
||||
"bathroom": "Salle de bain",
|
||||
"living": "Salon",
|
||||
"office": "Bureau",
|
||||
"garage": "Garage",
|
||||
"laundry": "Buanderie",
|
||||
"other": "Autre"
|
||||
},
|
||||
"ui": {
|
||||
"profile": {
|
||||
"title": "Profil",
|
||||
"displayName": "Nom affiché",
|
||||
"avatarMode": "Mode avatar",
|
||||
"letterMode": "Lettre",
|
||||
"characterMode": "Personnage",
|
||||
"photoMode": "Photo",
|
||||
"uploadPhoto": "Télécharger une photo",
|
||||
"language": "Langue",
|
||||
"save": "Enregistrer",
|
||||
"saved": "Enregistré",
|
||||
"logout": "Se déconnecter"
|
||||
},
|
||||
"settings": {
|
||||
"title": "Paramètres",
|
||||
"general": "Général",
|
||||
"notifications": "Notifications",
|
||||
"notificationsDesc": "Rappels de ménage quotidiens",
|
||||
"theme": "Thème",
|
||||
"themeDesc": "Changer l'ambiance de couleur",
|
||||
"themeOrange": "Orange chaleureux",
|
||||
"themeBlue": "Bleu clair",
|
||||
"themeRose": "Rose clair",
|
||||
"themeNight": "Nuit",
|
||||
"vacationMode": "Mode vacances",
|
||||
"vacationDesc": "Suspendre tous les rappels de tâches pendant votre absence",
|
||||
"adminRequired": "Un parent admin est requis pour modifier les paramètres.",
|
||||
"data": "Données",
|
||||
"dataPrivacy": "Données et confidentialité",
|
||||
"export": "Exporter",
|
||||
"exportData": "Exporter les données",
|
||||
"exportDesc": "Télécharger une sauvegarde JSON",
|
||||
"download": "Télécharger",
|
||||
"import": "Importer",
|
||||
"importData": "Importer les données",
|
||||
"importDesc": "Restaurer depuis une sauvegarde",
|
||||
"upload": "Importer",
|
||||
"family": "Famille",
|
||||
"familyMembers": "Membres de la famille",
|
||||
"addMember": "Ajouter un membre",
|
||||
"memberDisplayName": "Nom affiché",
|
||||
"memberUsername": "Nom d'utilisateur",
|
||||
"memberPassword": "Mot de passe",
|
||||
"passwordSection": "Mot de passe",
|
||||
"currentPassword": "Mot de passe actuel",
|
||||
"newPassword": "Nouveau mot de passe",
|
||||
"confirmPassword": "Confirmer le nouveau mot de passe",
|
||||
"updatePassword": "Mettre à jour le mot de passe",
|
||||
"resetPassword": "Réinitialiser le mot de passe",
|
||||
"passwordMismatch": "Les mots de passe ne correspondent pas.",
|
||||
"passwordUpdated": "Mot de passe mis à jour.",
|
||||
"passwordUpdateFailed": "Échec de mise à jour du mot de passe.",
|
||||
"manageChild": "Gérer l'enfant",
|
||||
"coinsPerEffort": "Pièces par effort",
|
||||
"coinsPerEffortDesc": "Définissez les pièces gagnées pour les niveaux d'effort 1 à 5.",
|
||||
"goalsSection": "Objectifs par membre",
|
||||
"goalsSectionDesc": "Définissez les objectifs de pièces et la période pour chaque enfant/membre.",
|
||||
"useDefaultCoins": "Utiliser les valeurs par défaut",
|
||||
"create": "Créer",
|
||||
"privacy": "Confidentialité",
|
||||
"privacyDesc": "Toutes les données restent sur votre serveur",
|
||||
"docker": "Docker",
|
||||
"roleAdmin": "Admin",
|
||||
"roleChild": "Enfant",
|
||||
"setAs": "Définir comme",
|
||||
"coins": "pièces",
|
||||
"streak": "série",
|
||||
"roleMember": "Membre",
|
||||
"deleteUser": "Supprimer l'utilisateur",
|
||||
"deleteUserConfirm": "Supprimer \"{user}\" ? Cette action est irréversible.",
|
||||
"goalCoins": "Objectif pièces",
|
||||
"goalTitle": "Titre de l'objectif",
|
||||
"setGoal": "Définir l'objectif",
|
||||
"addGoal": "Ajouter objectif",
|
||||
"manageMember": "Gerer le membre",
|
||||
"goalStart": "Date de debut",
|
||||
"goalEnd": "Date de fin",
|
||||
"goalDeleted": "Objectif supprimé.",
|
||||
"goalDeleteFailed": "Échec de la suppression de l'objectif.",
|
||||
"rewardsSection": "Catalogue des récompenses",
|
||||
"rewardsSectionDesc": "Les parents peuvent créer des récompenses achetables avec des pièces.",
|
||||
"rewardTitle": "Titre récompense",
|
||||
"rewardDesc": "Description",
|
||||
"rewardCost": "Coût pièces",
|
||||
"addPresetRewards": "Ajouter récompenses prédéfinies",
|
||||
"rewardRequests": "Demandes de récompenses",
|
||||
"noRewardRequests": "Aucune demande de récompense.",
|
||||
"telegramChatId": "ID de chat Telegram",
|
||||
"telegramChatIdHint": "Attendu: ID de chat numerique (ex: 123456789 ou -1001234567890). Ouvre d'abord un chat Telegram avec ton bot.",
|
||||
"notificationTime": "Heure de notification",
|
||||
"telegramToken": "Token bot Telegram",
|
||||
"telegramTokenHint": "Attendu: token du bot depuis @BotFather (format du type 123456789:AA...).",
|
||||
"telegramTokenConfigured": "Token Telegram déjà configuré (saisir pour remplacer)",
|
||||
"telegramChatIdRequired": "L'ID de chat Telegram est requis quand les notifications sont activées.",
|
||||
"telegramTokenRequired": "Le token Telegram est requis quand les notifications sont activées.",
|
||||
"notificationsDisabledHint": "Active Notifications pour configurer Telegram et l'heure d'envoi.",
|
||||
"notificationTypeTaskDue": "Rappels de tâches à faire",
|
||||
"notificationTypeRewardRequest": "Demandes de récompenses",
|
||||
"notificationTypeAchievementUnlocked": "Succès débloqués",
|
||||
"sendTestNotification": "Envoyer une notification test",
|
||||
"notificationsSaved": "Paramètres de notification enregistrés.",
|
||||
"notificationsSaveFailed": "Échec de l'enregistrement des notifications.",
|
||||
"notificationsTestSent": "Notification de test envoyée.",
|
||||
"notificationsTestFailed": "Échec de l'envoi de la notification test."
|
||||
},
|
||||
"nav": {
|
||||
"home": "Accueil",
|
||||
"rooms": "Pièces",
|
||||
"board": "Tableau",
|
||||
"calendar": "Calendrier",
|
||||
"activity": "Activité",
|
||||
"rewards": "Récompenses",
|
||||
"settings": "Paramètres",
|
||||
"profile": "Profil",
|
||||
"tagline": "Fais évoluer ta maison",
|
||||
"achievements": "Succès"
|
||||
},
|
||||
"app": {
|
||||
"roomsConfigured": "pièces configurées",
|
||||
"calendarSubtitle": "Suivez votre historique de ménage",
|
||||
"leaderboardTitle": "Classement",
|
||||
"leaderboardSubtitle": "Qui garde la maison propre ?",
|
||||
"historyTitle": "Journal d'activité",
|
||||
"historySubtitle": "Toutes les tâches terminées",
|
||||
"activitySubtitle": "Qui a fait quoi, quand, et pour combien de points",
|
||||
"rewardsSubtitle": "Dépense tes pièces pour des récompenses réelles",
|
||||
"profileSubtitle": "Personnalisez votre avatar et vos préférences",
|
||||
"settingsSubtitle": "Configurez votre expérience",
|
||||
"achievementsSubtitle": "Transforme les tâches en jeu avec des badges et objectifs"
|
||||
},
|
||||
"calendar": {
|
||||
"mon": "Lun",
|
||||
"tue": "Mar",
|
||||
"wed": "Mer",
|
||||
"thu": "Jeu",
|
||||
"fri": "Ven",
|
||||
"sat": "Sam",
|
||||
"sun": "Dim",
|
||||
"choresDone": "Tâches faites",
|
||||
"tasksDue": "Tâches à faire",
|
||||
"today": "Aujourd'hui",
|
||||
"upcomingDueDates": "Échéances à venir",
|
||||
"inDays": "dans {days}j",
|
||||
"allCaughtUp": "Tout est à jour ! Aucune tâche imminente."
|
||||
},
|
||||
"leaderboard": {
|
||||
"thisWeek": "Cette semaine",
|
||||
"thisMonth": "Ce mois-ci",
|
||||
"thisQuarter": "Ce trimestre",
|
||||
"thisYear": "Cette année",
|
||||
"points": "points",
|
||||
"streak": "série",
|
||||
"noData": "Pas encore de données pour cette période."
|
||||
},
|
||||
"rewards": {
|
||||
"catalog": "Catalogue des récompenses",
|
||||
"balanceHint": "Termine des tâches pour gagner des pièces puis échange-les.",
|
||||
"noDescription": "Pas de description",
|
||||
"redeem": "Utiliser",
|
||||
"notEnough": "Pas assez de pièces",
|
||||
"myRequests": "Historique de mes demandes",
|
||||
"noRequests": "Aucune récompense utilisée pour l'instant.",
|
||||
"confirmTitle": "Confirmer l'achat",
|
||||
"confirmText": "Acheter \"{reward}\" pour {coins} pièces ?",
|
||||
"confirmBuy": "Confirmer",
|
||||
"cancelRequest": "Annuler",
|
||||
"statusPending": "En attente",
|
||||
"statusApproved": "Approuvée",
|
||||
"statusRejected": "Refusée",
|
||||
"statusCancelled": "Annulée"
|
||||
},
|
||||
"rewardsPreset": {
|
||||
"movie_night": { "title": "Choix du film", "desc": "Choisir le film en famille ce soir." },
|
||||
"ice_cream": { "title": "Pause glace", "desc": "Prendre une glace ou un dessert spécial." },
|
||||
"late_bedtime": { "title": "Coucher +30 min", "desc": "Se coucher 30 minutes plus tard." },
|
||||
"game_bonus": { "title": "Bonus jeu vidéo", "desc": "30 minutes de jeu supplémentaires." },
|
||||
"choose_dinner": { "title": "Choisir le dîner", "desc": "Choisir le repas de ce soir." },
|
||||
"park_adventure": { "title": "Aventure au parc", "desc": "Sortie spéciale au parc en famille." },
|
||||
"chore_pass": { "title": "Passe corvée", "desc": "Sauter une corvée cette semaine." },
|
||||
"board_game": { "title": "Soirée jeu de société", "desc": "Choisir le jeu de société du soir." }
|
||||
},
|
||||
"history": {
|
||||
"task": "Tâche",
|
||||
"room": "Pièce",
|
||||
"when": "Quand",
|
||||
"earned": "Gagné",
|
||||
"by": "par",
|
||||
"noActivity": "Aucune activité pour le moment. Complétez une tâche pour commencer !",
|
||||
"previous": "Précédent",
|
||||
"next": "Suivant",
|
||||
"of": "sur"
|
||||
},
|
||||
"roomDetail": {
|
||||
"name": "Nom",
|
||||
"notes": "Notes",
|
||||
"optionalNotes": "Notes optionnelles...",
|
||||
"every": "Tous les",
|
||||
"effort": "Effort",
|
||||
"frequency": "Fréquence",
|
||||
"actions": "Actions",
|
||||
"deleteTask": "Supprimer la tâche",
|
||||
"done": "Fait",
|
||||
"seasonal": "Saisonnier",
|
||||
"taskName": "Nom de la tâche...",
|
||||
"addTask": "Ajouter une tâche"
|
||||
},
|
||||
"avatars": {
|
||||
"cat": "Chat",
|
||||
"dog": "Chien",
|
||||
"bunny": "Lapin",
|
||||
"bear": "Ours",
|
||||
"fox": "Renard",
|
||||
"owl": "Hibou",
|
||||
"panda": "Panda",
|
||||
"penguin": "Pingouin",
|
||||
"unicorn": "Licorne",
|
||||
"frog": "Grenouille",
|
||||
"koala": "Koala",
|
||||
"hedgehog": "Hérisson"
|
||||
},
|
||||
"dashboard": {
|
||||
"houseHealth": "Santé de la maison",
|
||||
"todaysQuests": "Quêtes du jour",
|
||||
"recentActivity": "Activité récente",
|
||||
"noQuests": "Aucune quête pour aujourd'hui",
|
||||
"roomsCount": "Pièces",
|
||||
"tasksCount": "Tâches",
|
||||
"criticalCount": "Critiques",
|
||||
"pending": "en attente",
|
||||
"sortedUrgency": "Triées par urgence",
|
||||
"dayStreak": "Série de jours",
|
||||
"keepStreak": "Complète 1 tâche par jour pour continuer !",
|
||||
"streakDoneToday": "Série complétée pour aujourd'hui !",
|
||||
"more": "Plus",
|
||||
"nextTasks": "Prochaines tâches à venir",
|
||||
"healthGreat": "Super état ! Continue comme ça.",
|
||||
"healthMedium": "Certaines pièces ont besoin d'attention.",
|
||||
"healthLow": "C'est le moment d'une session ménage !",
|
||||
"myGoal": "Mon objectif",
|
||||
"childrenGoals": "Objectifs des enfants",
|
||||
"noGoal": "Pas d'objectif",
|
||||
"rewardRequestsTitle": "Demandes de récompenses",
|
||||
"rewardRequestEmpty": "Aucune demande en attente.",
|
||||
"coinsStatusTitle": "État des pièces",
|
||||
"approve": "Approuver",
|
||||
"reject": "Refuser"
|
||||
},
|
||||
"rooms": {
|
||||
"addRoom": "Ajouter une pièce",
|
||||
"room": "Pièce",
|
||||
"tasks": "Tâches",
|
||||
"health": "Santé",
|
||||
"healthHealthy": "En bonne santé",
|
||||
"healthNeedsAttention": "À surveiller",
|
||||
"healthCritical": "Critique",
|
||||
"deleteRoomConfirm": "Supprimer \"{room}\" et toutes ses tâches ? Cette action est définitive.",
|
||||
"noRoomsYet": "Aucune pièce pour le moment",
|
||||
"clickAddRoom": "Cliquez sur \"Ajouter une pièce\" pour commencer !",
|
||||
"addRoomTitle": "Ajouter une pièce",
|
||||
"pickRoomType": "Choisissez un type de pièce, puis configurez ses tâches.",
|
||||
"customNameOptional": "Nom personnalisé (optionnel)",
|
||||
"nextConfigure": "Suivant : configurer les tâches",
|
||||
"configureTasks": "Configurer les tâches",
|
||||
"configureTasksDesc": "Sélectionnez les tâches, leur état actuel, effort et fréquence.",
|
||||
"currentState": "État actuel",
|
||||
"dirty": "Sale",
|
||||
"clean": "Propre",
|
||||
"addCustomTask": "Ajouter une tâche personnalisée...",
|
||||
"tasksSelected": "tâches sélectionnées",
|
||||
"createRoom": "Créer la pièce",
|
||||
"roomNotFound": "Pièce introuvable.",
|
||||
"backToRooms": "Retour aux pièces",
|
||||
"tasksTracked": "tâches suivies"
|
||||
},
|
||||
"common": {
|
||||
"save": "Enregistrer",
|
||||
"saved": "Enregistré",
|
||||
"cancel": "Annuler",
|
||||
"delete": "Supprimer",
|
||||
"edit": "Modifier",
|
||||
"loading": "Chargement",
|
||||
"add": "Ajouter"
|
||||
},
|
||||
"units": {
|
||||
"hours": "heures",
|
||||
"days": "jours",
|
||||
"weeks": "semaines",
|
||||
"months": "mois",
|
||||
"years": "années"
|
||||
},
|
||||
"unitsShort": {
|
||||
"hours": "h",
|
||||
"days": "j",
|
||||
"weeks": "sem",
|
||||
"months": "mois",
|
||||
"years": "an"
|
||||
},
|
||||
"time": {
|
||||
"never": "Jamais",
|
||||
"justNow": "à l'instant",
|
||||
"minutesAgo": "il y a {count} min",
|
||||
"hoursAgo": "il y a {count} h",
|
||||
"yesterday": "hier",
|
||||
"daysAgo": "il y a {count} j",
|
||||
"oneWeekAgo": "il y a 1 sem",
|
||||
"weeksAgo": "il y a {count} sem",
|
||||
"oneMonthAgo": "il y a 1 mois",
|
||||
"monthsAgo": "il y a {count} mois"
|
||||
},
|
||||
"auth": {
|
||||
"welcomeBack": "Bienvenue !",
|
||||
"welcome": "Bienvenue sur TidyQuest",
|
||||
"createYourAccount": "Créez votre compte",
|
||||
"username": "Nom d'utilisateur",
|
||||
"usernamePlaceholder": "Entrez votre nom d'utilisateur",
|
||||
"password": "Mot de passe",
|
||||
"passwordPlaceholder": "Entrez votre mot de passe",
|
||||
"passwordMinChars": "min 4 caractères",
|
||||
"displayName": "Nom affiché",
|
||||
"displayNamePlaceholder": "John",
|
||||
"avatarColor": "Couleur d'avatar",
|
||||
"loggingIn": "Connexion...",
|
||||
"logIn": "Se connecter",
|
||||
"createAccount": "Créer un compte",
|
||||
"createAccountAction": "Créer le compte",
|
||||
"creating": "Création...",
|
||||
"alreadyHaveAccount": "Déjà un compte ? Se connecter",
|
||||
"allFieldsRequired": "Tous les champs sont requis",
|
||||
"loginFailed": "Échec de connexion",
|
||||
"registrationFailed": "Échec de l'inscription"
|
||||
},
|
||||
"achievements": {
|
||||
"familyProgress": "Progression famille",
|
||||
"firstStep": "Premier pas",
|
||||
"firstStepDesc": "Termine ta premiere tache",
|
||||
"helper": "Petit assistant",
|
||||
"helperDesc": "Termine 10 tâches",
|
||||
"busyBee": "Abeille active",
|
||||
"busyBeeDesc": "Termine 25 tâches",
|
||||
"cleaningHero": "Super nettoyeur",
|
||||
"cleaningHeroDesc": "Termine 50 tâches",
|
||||
"choreChampion": "Champion du menage",
|
||||
"choreChampionDesc": "Termine 100 tâches",
|
||||
"legend": "Legende TidyQuest",
|
||||
"legendDesc": "Termine 250 tâches",
|
||||
"unstoppable": "Inarretable !",
|
||||
"unstoppableDesc": "Termine 500 tâches",
|
||||
"onFire": "En feu",
|
||||
"onFireDesc": "Atteins une serie de 3 jours",
|
||||
"streakMaster": "Maitre de la serie",
|
||||
"streakMasterDesc": "Atteins une serie de 7 jours",
|
||||
"twoWeekWarrior": "Guerrier de la quinzaine",
|
||||
"twoWeekWarriorDesc": "Atteins une serie de 14 jours",
|
||||
"monthlyMachine": "Machine du mois",
|
||||
"monthlyMachineDesc": "Atteins une serie de 30 jours",
|
||||
"centurion": "Centurion",
|
||||
"centurionDesc": "Atteins une serie de 100 jours !",
|
||||
"piggyBank": "Tirelire",
|
||||
"piggyBankDesc": "Gagne 50 pieces",
|
||||
"saver": "Econome",
|
||||
"saverDesc": "Gagne 100 pieces",
|
||||
"treasureHunter": "Chasseur de tresor",
|
||||
"treasureHunterDesc": "Gagne 500 pieces",
|
||||
"goldMaster": "Maitre de l'or",
|
||||
"goldMasterDesc": "Gagne 1 000 pieces",
|
||||
"millionaire": "Millionnaire",
|
||||
"millionaireDesc": "Gagne 5 000 pieces",
|
||||
"roomTamer": "Dompteur de pieces",
|
||||
"roomTamerDesc": "Garde 3 pieces en bonne sante en meme temps",
|
||||
"housePride": "Fierte du foyer",
|
||||
"housePrideDesc": "Garde 5 pieces en bonne sante en meme temps",
|
||||
"weekendWarrior": "Guerrier du week-end",
|
||||
"weekendWarriorDesc": "Termine 5 tâches en une semaine",
|
||||
"superWeek": "Super semaine",
|
||||
"superWeekDesc": "Termine 15 tâches en une semaine",
|
||||
"perfectWeek": "Semaine parfaite",
|
||||
"perfectWeekDesc": "Fais au moins 1 tache chaque jour pendant une semaine",
|
||||
"perfectMonth": "Mois parfait",
|
||||
"perfectMonthDesc": "Enchaine 4 semaines parfaites",
|
||||
"nightOwl": "Planificateur Nocturne",
|
||||
"nightOwlDesc": "Atteins une serie de 60 jours"
|
||||
}
|
||||
}
|
||||
}
|
||||
224
client/src/index.css
Normal file
224
client/src/index.css
Normal file
|
|
@ -0,0 +1,224 @@
|
|||
/* Nunito Font — bundled locally, no CDN */
|
||||
@font-face { font-family: 'Nunito'; src: url('./assets/fonts/Nunito-400.ttf') format('truetype'); font-weight: 400; font-display: swap; }
|
||||
@font-face { font-family: 'Nunito'; src: url('./assets/fonts/Nunito-500.ttf') format('truetype'); font-weight: 500; font-display: swap; }
|
||||
@font-face { font-family: 'Nunito'; src: url('./assets/fonts/Nunito-600.ttf') format('truetype'); font-weight: 600; font-display: swap; }
|
||||
@font-face { font-family: 'Nunito'; src: url('./assets/fonts/Nunito-700.ttf') format('truetype'); font-weight: 700; font-display: swap; }
|
||||
@font-face { font-family: 'Nunito'; src: url('./assets/fonts/Nunito-800.ttf') format('truetype'); font-weight: 800; font-display: swap; }
|
||||
@font-face { font-family: 'Nunito'; src: url('./assets/fonts/Nunito-900.ttf') format('truetype'); font-weight: 900; font-display: swap; }
|
||||
|
||||
:root {
|
||||
--warm-bg: #FFF9F2;
|
||||
--warm-card: #FFFFFF;
|
||||
--warm-border: #F0E6D9;
|
||||
--warm-border-subtle: #F5EDE3;
|
||||
--warm-text: #3D2F1E;
|
||||
--warm-text-secondary: #6B5B4A;
|
||||
--warm-text-muted: #8A7A6A;
|
||||
--warm-text-light: #B0A090;
|
||||
--warm-accent: #F97316;
|
||||
--warm-accent-light: #FFF7ED;
|
||||
--warm-accent-hover: #EA580C;
|
||||
--warm-bg-subtle: #FFFBF5;
|
||||
--warm-bg-warm: #FFF9F0;
|
||||
--warm-bg-input: #FFFFFF;
|
||||
--warm-sidebar: #FFFFFF;
|
||||
--warm-sidebar-active: #FFF7ED;
|
||||
--warm-sidebar-border: #F0E6D9;
|
||||
--warm-sidebar-user-bg: #FFF7ED;
|
||||
--warm-sidebar-user-border: #FDE68A;
|
||||
--warm-streak-bg: linear-gradient(135deg, #FFF7ED, #FFEDD5);
|
||||
--warm-streak-border: #FDE68A;
|
||||
--warm-streak-text: #92400E;
|
||||
--warm-streak-subtext: #B45309;
|
||||
--warm-danger: #EF4444;
|
||||
--warm-danger-bg: #FFF1F1;
|
||||
--warm-danger-border: #FECACA;
|
||||
--warm-badge-bg: #FDECEC;
|
||||
--warm-badge-text: #E25A5A;
|
||||
--warm-coin: #F59E0B;
|
||||
--health-bar-track: #F5EDE3;
|
||||
--health-green: #5CB85C;
|
||||
--health-yellow: #E8A838;
|
||||
--health-red: #E25A5A;
|
||||
--health-green-bg: #EDF7ED;
|
||||
--health-yellow-bg: #FFF8EC;
|
||||
--health-red-bg: #FDECEC;
|
||||
--warm-shadow: rgba(180, 150, 100, 0.1);
|
||||
--warm-primary-shadow: rgba(249, 115, 22, 0.25);
|
||||
}
|
||||
|
||||
html[data-theme='blue'] {
|
||||
--warm-bg: #F3F9FF;
|
||||
--warm-card: #FFFFFF;
|
||||
--warm-border: #DDEAF8;
|
||||
--warm-border-subtle: #E8F1FA;
|
||||
--warm-text: #21354A;
|
||||
--warm-text-secondary: #3D5570;
|
||||
--warm-text-muted: #5A7A98;
|
||||
--warm-text-light: #8194A8;
|
||||
--warm-accent: #3B82F6;
|
||||
--warm-accent-light: #EAF2FF;
|
||||
--warm-accent-hover: #2563EB;
|
||||
--warm-bg-subtle: #F8FBFF;
|
||||
--warm-bg-warm: #F0F6FF;
|
||||
--warm-bg-input: #FFFFFF;
|
||||
--warm-sidebar: #FFFFFF;
|
||||
--warm-sidebar-active: #EAF2FF;
|
||||
--warm-sidebar-border: #DDEAF8;
|
||||
--warm-sidebar-user-bg: #EAF2FF;
|
||||
--warm-sidebar-user-border: #BAD6FC;
|
||||
--warm-streak-bg: linear-gradient(135deg, #EAF2FF, #DBEAFE);
|
||||
--warm-streak-border: #BAD6FC;
|
||||
--warm-streak-text: #1E40AF;
|
||||
--warm-streak-subtext: #2563EB;
|
||||
--warm-primary-shadow: rgba(59, 130, 246, 0.25);
|
||||
}
|
||||
|
||||
html[data-theme='rose'] {
|
||||
--warm-bg: #FFF5F8;
|
||||
--warm-card: #FFFFFF;
|
||||
--warm-border: #F2DDE6;
|
||||
--warm-border-subtle: #F7E6EE;
|
||||
--warm-text: #4A2435;
|
||||
--warm-text-secondary: #6E3E55;
|
||||
--warm-text-muted: #8A6070;
|
||||
--warm-text-light: #A37E8F;
|
||||
--warm-accent: #EC4899;
|
||||
--warm-accent-light: #FDEAF3;
|
||||
--warm-accent-hover: #DB2777;
|
||||
--warm-bg-subtle: #FFF9FB;
|
||||
--warm-bg-warm: #FFF0F5;
|
||||
--warm-bg-input: #FFFFFF;
|
||||
--warm-sidebar: #FFFFFF;
|
||||
--warm-sidebar-active: #FDEAF3;
|
||||
--warm-sidebar-border: #F2DDE6;
|
||||
--warm-sidebar-user-bg: #FDEAF3;
|
||||
--warm-sidebar-user-border: #F9A8D4;
|
||||
--warm-streak-bg: linear-gradient(135deg, #FDEAF3, #FCE7F3);
|
||||
--warm-streak-border: #F9A8D4;
|
||||
--warm-streak-text: #9D174D;
|
||||
--warm-streak-subtext: #BE185D;
|
||||
--warm-primary-shadow: rgba(236, 72, 153, 0.25);
|
||||
}
|
||||
|
||||
html[data-theme='night'] {
|
||||
--warm-bg: #0B0F19;
|
||||
--warm-card: #1C2436;
|
||||
--warm-border: #334155;
|
||||
--warm-border-subtle: #2D3B4F;
|
||||
--warm-text: #E2E8F0;
|
||||
--warm-text-secondary: #CBD5E1;
|
||||
--warm-text-muted: #94A3B8;
|
||||
--warm-text-light: #64748B;
|
||||
--warm-accent: #60A5FA;
|
||||
--warm-accent-light: #24324A;
|
||||
--warm-accent-hover: #3B82F6;
|
||||
--warm-bg-subtle: #253149;
|
||||
--warm-bg-warm: #2B3954;
|
||||
--warm-bg-input: #1A2233;
|
||||
--warm-sidebar: #141B2A;
|
||||
--warm-sidebar-active: #223048;
|
||||
--warm-sidebar-border: #334155;
|
||||
--warm-sidebar-user-bg: #223048;
|
||||
--warm-sidebar-user-border: #475569;
|
||||
--warm-streak-bg: linear-gradient(135deg, #1C2436, #253149);
|
||||
--warm-streak-border: #475569;
|
||||
--warm-streak-text: #93C5FD;
|
||||
--warm-streak-subtext: #60A5FA;
|
||||
--warm-danger: #F87171;
|
||||
--warm-danger-bg: #2A1F1F;
|
||||
--warm-danger-border: #7F1D1D;
|
||||
--warm-badge-bg: #2A1F1F;
|
||||
--warm-badge-text: #F87171;
|
||||
--warm-coin: #FBBF24;
|
||||
--health-bar-track: #334155;
|
||||
--health-green-bg: #1A2E1A;
|
||||
--health-yellow-bg: #2E2A1A;
|
||||
--health-red-bg: #2E1A1A;
|
||||
--warm-shadow: rgba(0, 0, 0, 0.3);
|
||||
--warm-primary-shadow: rgba(96, 165, 250, 0.25);
|
||||
}
|
||||
|
||||
* { box-sizing: border-box; margin: 0; padding: 0; }
|
||||
|
||||
body {
|
||||
font-family: 'Nunito', sans-serif;
|
||||
background: var(--warm-bg);
|
||||
color: var(--warm-text);
|
||||
-webkit-font-smoothing: antialiased;
|
||||
}
|
||||
|
||||
::-webkit-scrollbar { width: 5px; }
|
||||
::-webkit-scrollbar-thumb { background: var(--warm-border); border-radius: 99px; }
|
||||
::-webkit-scrollbar-track { background: transparent; }
|
||||
|
||||
@keyframes confettiFall {
|
||||
0% { transform: translateY(0) rotate(0deg); opacity: 1; }
|
||||
100% { transform: translateY(100vh) rotate(720deg); opacity: 0; }
|
||||
}
|
||||
|
||||
@keyframes fadeIn {
|
||||
from { opacity: 0; transform: translateY(8px); }
|
||||
to { opacity: 1; transform: translateY(0); }
|
||||
}
|
||||
|
||||
.page-enter { animation: fadeIn 0.3s ease; }
|
||||
|
||||
.tq-card {
|
||||
background: var(--warm-card);
|
||||
border-radius: 20px;
|
||||
border: 1.5px solid var(--warm-border);
|
||||
transition: transform 0.15s ease, box-shadow 0.15s ease;
|
||||
}
|
||||
|
||||
.tq-card-hover:hover {
|
||||
transform: translateY(-2px);
|
||||
box-shadow: 0 8px 28px var(--warm-shadow);
|
||||
}
|
||||
|
||||
.tq-btn {
|
||||
border: none;
|
||||
cursor: pointer;
|
||||
font-family: 'Nunito', sans-serif;
|
||||
font-weight: 700;
|
||||
border-radius: 14px;
|
||||
transition: all 0.15s ease;
|
||||
display: inline-flex;
|
||||
align-items: center;
|
||||
gap: 6px;
|
||||
}
|
||||
.tq-btn:hover { filter: brightness(1.05); transform: scale(1.02); }
|
||||
.tq-btn:active { transform: scale(0.97); }
|
||||
|
||||
.tq-btn-primary {
|
||||
background: var(--warm-accent);
|
||||
color: #fff;
|
||||
box-shadow: 0 4px 14px var(--warm-primary-shadow);
|
||||
}
|
||||
|
||||
.tq-btn-secondary {
|
||||
background: var(--warm-card);
|
||||
color: var(--warm-text);
|
||||
border: 1.5px solid var(--warm-border);
|
||||
}
|
||||
.tq-btn-secondary:hover {
|
||||
border-color: var(--warm-accent);
|
||||
color: var(--warm-accent);
|
||||
}
|
||||
|
||||
/* Night theme: ensure inputs and selects are readable */
|
||||
html[data-theme='night'] input,
|
||||
html[data-theme='night'] textarea,
|
||||
html[data-theme='night'] select {
|
||||
background-color: var(--warm-bg-input) !important;
|
||||
color: var(--warm-text) !important;
|
||||
border-color: var(--warm-border) !important;
|
||||
}
|
||||
html[data-theme='night'] input::placeholder,
|
||||
html[data-theme='night'] textarea::placeholder {
|
||||
color: var(--warm-text-light) !important;
|
||||
}
|
||||
html[data-theme='night'] option {
|
||||
background-color: var(--warm-card);
|
||||
color: var(--warm-text);
|
||||
}
|
||||
10
client/src/main.tsx
Normal file
10
client/src/main.tsx
Normal file
|
|
@ -0,0 +1,10 @@
|
|||
import { StrictMode } from 'react'
|
||||
import { createRoot } from 'react-dom/client'
|
||||
import './index.css'
|
||||
import App from './App.tsx'
|
||||
|
||||
createRoot(document.getElementById('root')!).render(
|
||||
<StrictMode>
|
||||
<App />
|
||||
</StrictMode>,
|
||||
)
|
||||
10
client/src/utils/colors.ts
Normal file
10
client/src/utils/colors.ts
Normal file
|
|
@ -0,0 +1,10 @@
|
|||
export const ROOM_COLORS: Record<string, { bg: string; accent: string }> = {
|
||||
kitchen: { bg: '#FFE4CC', accent: '#F97316' },
|
||||
bedroom: { bg: '#E0D4F5', accent: '#9B72CF' },
|
||||
bathroom: { bg: '#CCE8F5', accent: '#4AABDE' },
|
||||
living: { bg: '#D4EDDA', accent: '#5CB85C' },
|
||||
office: { bg: '#FFF3CD', accent: '#D4A017' },
|
||||
garage: { bg: '#E8E8E8', accent: '#888888' },
|
||||
laundry: { bg: '#E0F2FE', accent: '#38BDF8' },
|
||||
other: { bg: '#F5EDE3', accent: '#B0A090' },
|
||||
};
|
||||
17
client/src/utils/health.ts
Normal file
17
client/src/utils/health.ts
Normal file
|
|
@ -0,0 +1,17 @@
|
|||
export function getHealthColor(h: number): string {
|
||||
return h >= 70 ? '#5CB85C' : h >= 40 ? '#E8A838' : '#E25A5A';
|
||||
}
|
||||
|
||||
export function getHealthBg(h: number): string {
|
||||
return h >= 70 ? '#EDF7ED' : h >= 40 ? '#FFF8EC' : '#FDECEC';
|
||||
}
|
||||
|
||||
export function getHealthLabel(h: number): string {
|
||||
return h >= 70 ? 'Healthy' : h >= 40 ? 'Needs attention' : 'Critical';
|
||||
}
|
||||
|
||||
export function getRoomHealth(tasks: Array<{ health: number; effort: number }>): number {
|
||||
const totalEffort = tasks.reduce((s, t) => s + t.effort, 0);
|
||||
if (totalEffort === 0) return 100;
|
||||
return Math.round(tasks.reduce((s, t) => s + t.health * t.effort, 0) / totalEffort);
|
||||
}
|
||||
28
client/tsconfig.app.json
Normal file
28
client/tsconfig.app.json
Normal file
|
|
@ -0,0 +1,28 @@
|
|||
{
|
||||
"compilerOptions": {
|
||||
"tsBuildInfoFile": "./node_modules/.tmp/tsconfig.app.tsbuildinfo",
|
||||
"target": "ES2022",
|
||||
"useDefineForClassFields": true,
|
||||
"lib": ["ES2022", "DOM", "DOM.Iterable"],
|
||||
"module": "ESNext",
|
||||
"types": ["vite/client"],
|
||||
"skipLibCheck": true,
|
||||
|
||||
/* Bundler mode */
|
||||
"moduleResolution": "bundler",
|
||||
"allowImportingTsExtensions": true,
|
||||
"verbatimModuleSyntax": true,
|
||||
"moduleDetection": "force",
|
||||
"noEmit": true,
|
||||
"jsx": "react-jsx",
|
||||
|
||||
/* Linting */
|
||||
"strict": true,
|
||||
"noUnusedLocals": true,
|
||||
"noUnusedParameters": true,
|
||||
"erasableSyntaxOnly": true,
|
||||
"noFallthroughCasesInSwitch": true,
|
||||
"noUncheckedSideEffectImports": true
|
||||
},
|
||||
"include": ["src"]
|
||||
}
|
||||
7
client/tsconfig.json
Normal file
7
client/tsconfig.json
Normal file
|
|
@ -0,0 +1,7 @@
|
|||
{
|
||||
"files": [],
|
||||
"references": [
|
||||
{ "path": "./tsconfig.app.json" },
|
||||
{ "path": "./tsconfig.node.json" }
|
||||
]
|
||||
}
|
||||
26
client/tsconfig.node.json
Normal file
26
client/tsconfig.node.json
Normal file
|
|
@ -0,0 +1,26 @@
|
|||
{
|
||||
"compilerOptions": {
|
||||
"tsBuildInfoFile": "./node_modules/.tmp/tsconfig.node.tsbuildinfo",
|
||||
"target": "ES2023",
|
||||
"lib": ["ES2023"],
|
||||
"module": "ESNext",
|
||||
"types": ["node"],
|
||||
"skipLibCheck": true,
|
||||
|
||||
/* Bundler mode */
|
||||
"moduleResolution": "bundler",
|
||||
"allowImportingTsExtensions": true,
|
||||
"verbatimModuleSyntax": true,
|
||||
"moduleDetection": "force",
|
||||
"noEmit": true,
|
||||
|
||||
/* Linting */
|
||||
"strict": true,
|
||||
"noUnusedLocals": true,
|
||||
"noUnusedParameters": true,
|
||||
"erasableSyntaxOnly": true,
|
||||
"noFallthroughCasesInSwitch": true,
|
||||
"noUncheckedSideEffectImports": true
|
||||
},
|
||||
"include": ["vite.config.ts"]
|
||||
}
|
||||
15
client/vite.config.ts
Normal file
15
client/vite.config.ts
Normal file
|
|
@ -0,0 +1,15 @@
|
|||
import { defineConfig } from 'vite'
|
||||
import react from '@vitejs/plugin-react'
|
||||
|
||||
export default defineConfig({
|
||||
plugins: [react()],
|
||||
server: {
|
||||
port: 5173,
|
||||
proxy: {
|
||||
'/api': {
|
||||
target: 'http://localhost:3000',
|
||||
changeOrigin: true,
|
||||
},
|
||||
},
|
||||
},
|
||||
})
|
||||
14
docker-compose.yml
Normal file
14
docker-compose.yml
Normal file
|
|
@ -0,0 +1,14 @@
|
|||
services:
|
||||
tidyquest:
|
||||
build: .
|
||||
ports:
|
||||
- "3020:3000"
|
||||
volumes:
|
||||
- ./data:/app/data
|
||||
env_file:
|
||||
- .env
|
||||
environment:
|
||||
- NODE_ENV=${NODE_ENV:-production}
|
||||
- JWT_SECRET=${JWT_SECRET}
|
||||
- PORT=${PORT:-3000}
|
||||
restart: unless-stopped
|
||||
329
package-lock.json
generated
Normal file
329
package-lock.json
generated
Normal file
|
|
@ -0,0 +1,329 @@
|
|||
{
|
||||
"name": "tidyquest",
|
||||
"version": "1.0.0",
|
||||
"lockfileVersion": 3,
|
||||
"requires": true,
|
||||
"packages": {
|
||||
"": {
|
||||
"name": "tidyquest",
|
||||
"version": "1.0.0",
|
||||
"devDependencies": {
|
||||
"concurrently": "^9.1.2"
|
||||
}
|
||||
},
|
||||
"node_modules/ansi-regex": {
|
||||
"version": "5.0.1",
|
||||
"resolved": "https://registry.npmjs.org/ansi-regex/-/ansi-regex-5.0.1.tgz",
|
||||
"integrity": "sha512-quJQXlTSUGL2LH9SUXo8VwsY4soanhgo6LNSm84E1LBcE8s3O0wpdiRzyR9z/ZZJMlMWv37qOOb9pdJlMUEKFQ==",
|
||||
"dev": true,
|
||||
"license": "MIT",
|
||||
"engines": {
|
||||
"node": ">=8"
|
||||
}
|
||||
},
|
||||
"node_modules/ansi-styles": {
|
||||
"version": "4.3.0",
|
||||
"resolved": "https://registry.npmjs.org/ansi-styles/-/ansi-styles-4.3.0.tgz",
|
||||
"integrity": "sha512-zbB9rCJAT1rbjiVDb2hqKFHNYLxgtk8NURxZ3IZwD3F6NtxbXZQCnnSi1Lkx+IDohdPlFp222wVALIheZJQSEg==",
|
||||
"dev": true,
|
||||
"license": "MIT",
|
||||
"dependencies": {
|
||||
"color-convert": "^2.0.1"
|
||||
},
|
||||
"engines": {
|
||||
"node": ">=8"
|
||||
},
|
||||
"funding": {
|
||||
"url": "https://github.com/chalk/ansi-styles?sponsor=1"
|
||||
}
|
||||
},
|
||||
"node_modules/chalk": {
|
||||
"version": "4.1.2",
|
||||
"resolved": "https://registry.npmjs.org/chalk/-/chalk-4.1.2.tgz",
|
||||
"integrity": "sha512-oKnbhFyRIXpUuez8iBMmyEa4nbj4IOQyuhc/wy9kY7/WVPcwIO9VA668Pu8RkO7+0G76SLROeyw9CpQ061i4mA==",
|
||||
"dev": true,
|
||||
"license": "MIT",
|
||||
"dependencies": {
|
||||
"ansi-styles": "^4.1.0",
|
||||
"supports-color": "^7.1.0"
|
||||
},
|
||||
"engines": {
|
||||
"node": ">=10"
|
||||
},
|
||||
"funding": {
|
||||
"url": "https://github.com/chalk/chalk?sponsor=1"
|
||||
}
|
||||
},
|
||||
"node_modules/chalk/node_modules/supports-color": {
|
||||
"version": "7.2.0",
|
||||
"resolved": "https://registry.npmjs.org/supports-color/-/supports-color-7.2.0.tgz",
|
||||
"integrity": "sha512-qpCAvRl9stuOHveKsn7HncJRvv501qIacKzQlO/+Lwxc9+0q2wLyv4Dfvt80/DPn2pqOBsJdDiogXGR9+OvwRw==",
|
||||
"dev": true,
|
||||
"license": "MIT",
|
||||
"dependencies": {
|
||||
"has-flag": "^4.0.0"
|
||||
},
|
||||
"engines": {
|
||||
"node": ">=8"
|
||||
}
|
||||
},
|
||||
"node_modules/cliui": {
|
||||
"version": "8.0.1",
|
||||
"resolved": "https://registry.npmjs.org/cliui/-/cliui-8.0.1.tgz",
|
||||
"integrity": "sha512-BSeNnyus75C4//NQ9gQt1/csTXyo/8Sb+afLAkzAptFuMsod9HFokGNudZpi/oQV73hnVK+sR+5PVRMd+Dr7YQ==",
|
||||
"dev": true,
|
||||
"license": "ISC",
|
||||
"dependencies": {
|
||||
"string-width": "^4.2.0",
|
||||
"strip-ansi": "^6.0.1",
|
||||
"wrap-ansi": "^7.0.0"
|
||||
},
|
||||
"engines": {
|
||||
"node": ">=12"
|
||||
}
|
||||
},
|
||||
"node_modules/color-convert": {
|
||||
"version": "2.0.1",
|
||||
"resolved": "https://registry.npmjs.org/color-convert/-/color-convert-2.0.1.tgz",
|
||||
"integrity": "sha512-RRECPsj7iu/xb5oKYcsFHSppFNnsj/52OVTRKb4zP5onXwVF3zVmmToNcOfGC+CRDpfK/U584fMg38ZHCaElKQ==",
|
||||
"dev": true,
|
||||
"license": "MIT",
|
||||
"dependencies": {
|
||||
"color-name": "~1.1.4"
|
||||
},
|
||||
"engines": {
|
||||
"node": ">=7.0.0"
|
||||
}
|
||||
},
|
||||
"node_modules/color-name": {
|
||||
"version": "1.1.4",
|
||||
"resolved": "https://registry.npmjs.org/color-name/-/color-name-1.1.4.tgz",
|
||||
"integrity": "sha512-dOy+3AuW3a2wNbZHIuMZpTcgjGuLU/uBL/ubcZF9OXbDo8ff4O8yVp5Bf0efS8uEoYo5q4Fx7dY9OgQGXgAsQA==",
|
||||
"dev": true,
|
||||
"license": "MIT"
|
||||
},
|
||||
"node_modules/concurrently": {
|
||||
"version": "9.2.1",
|
||||
"resolved": "https://registry.npmjs.org/concurrently/-/concurrently-9.2.1.tgz",
|
||||
"integrity": "sha512-fsfrO0MxV64Znoy8/l1vVIjjHa29SZyyqPgQBwhiDcaW8wJc2W3XWVOGx4M3oJBnv/zdUZIIp1gDeS98GzP8Ng==",
|
||||
"dev": true,
|
||||
"license": "MIT",
|
||||
"dependencies": {
|
||||
"chalk": "4.1.2",
|
||||
"rxjs": "7.8.2",
|
||||
"shell-quote": "1.8.3",
|
||||
"supports-color": "8.1.1",
|
||||
"tree-kill": "1.2.2",
|
||||
"yargs": "17.7.2"
|
||||
},
|
||||
"bin": {
|
||||
"conc": "dist/bin/concurrently.js",
|
||||
"concurrently": "dist/bin/concurrently.js"
|
||||
},
|
||||
"engines": {
|
||||
"node": ">=18"
|
||||
},
|
||||
"funding": {
|
||||
"url": "https://github.com/open-cli-tools/concurrently?sponsor=1"
|
||||
}
|
||||
},
|
||||
"node_modules/emoji-regex": {
|
||||
"version": "8.0.0",
|
||||
"resolved": "https://registry.npmjs.org/emoji-regex/-/emoji-regex-8.0.0.tgz",
|
||||
"integrity": "sha512-MSjYzcWNOA0ewAHpz0MxpYFvwg6yjy1NG3xteoqz644VCo/RPgnr1/GGt+ic3iJTzQ8Eu3TdM14SawnVUmGE6A==",
|
||||
"dev": true,
|
||||
"license": "MIT"
|
||||
},
|
||||
"node_modules/escalade": {
|
||||
"version": "3.2.0",
|
||||
"resolved": "https://registry.npmjs.org/escalade/-/escalade-3.2.0.tgz",
|
||||
"integrity": "sha512-WUj2qlxaQtO4g6Pq5c29GTcWGDyd8itL8zTlipgECz3JesAiiOKotd8JU6otB3PACgG6xkJUyVhboMS+bje/jA==",
|
||||
"dev": true,
|
||||
"license": "MIT",
|
||||
"engines": {
|
||||
"node": ">=6"
|
||||
}
|
||||
},
|
||||
"node_modules/get-caller-file": {
|
||||
"version": "2.0.5",
|
||||
"resolved": "https://registry.npmjs.org/get-caller-file/-/get-caller-file-2.0.5.tgz",
|
||||
"integrity": "sha512-DyFP3BM/3YHTQOCUL/w0OZHR0lpKeGrxotcHWcqNEdnltqFwXVfhEBQ94eIo34AfQpo0rGki4cyIiftY06h2Fg==",
|
||||
"dev": true,
|
||||
"license": "ISC",
|
||||
"engines": {
|
||||
"node": "6.* || 8.* || >= 10.*"
|
||||
}
|
||||
},
|
||||
"node_modules/has-flag": {
|
||||
"version": "4.0.0",
|
||||
"resolved": "https://registry.npmjs.org/has-flag/-/has-flag-4.0.0.tgz",
|
||||
"integrity": "sha512-EykJT/Q1KjTWctppgIAgfSO0tKVuZUjhgMr17kqTumMl6Afv3EISleU7qZUzoXDFTAHTDC4NOoG/ZxU3EvlMPQ==",
|
||||
"dev": true,
|
||||
"license": "MIT",
|
||||
"engines": {
|
||||
"node": ">=8"
|
||||
}
|
||||
},
|
||||
"node_modules/is-fullwidth-code-point": {
|
||||
"version": "3.0.0",
|
||||
"resolved": "https://registry.npmjs.org/is-fullwidth-code-point/-/is-fullwidth-code-point-3.0.0.tgz",
|
||||
"integrity": "sha512-zymm5+u+sCsSWyD9qNaejV3DFvhCKclKdizYaJUuHA83RLjb7nSuGnddCHGv0hk+KY7BMAlsWeK4Ueg6EV6XQg==",
|
||||
"dev": true,
|
||||
"license": "MIT",
|
||||
"engines": {
|
||||
"node": ">=8"
|
||||
}
|
||||
},
|
||||
"node_modules/require-directory": {
|
||||
"version": "2.1.1",
|
||||
"resolved": "https://registry.npmjs.org/require-directory/-/require-directory-2.1.1.tgz",
|
||||
"integrity": "sha512-fGxEI7+wsG9xrvdjsrlmL22OMTTiHRwAMroiEeMgq8gzoLC/PQr7RsRDSTLUg/bZAZtF+TVIkHc6/4RIKrui+Q==",
|
||||
"dev": true,
|
||||
"license": "MIT",
|
||||
"engines": {
|
||||
"node": ">=0.10.0"
|
||||
}
|
||||
},
|
||||
"node_modules/rxjs": {
|
||||
"version": "7.8.2",
|
||||
"resolved": "https://registry.npmjs.org/rxjs/-/rxjs-7.8.2.tgz",
|
||||
"integrity": "sha512-dhKf903U/PQZY6boNNtAGdWbG85WAbjT/1xYoZIC7FAY0yWapOBQVsVrDl58W86//e1VpMNBtRV4MaXfdMySFA==",
|
||||
"dev": true,
|
||||
"license": "Apache-2.0",
|
||||
"dependencies": {
|
||||
"tslib": "^2.1.0"
|
||||
}
|
||||
},
|
||||
"node_modules/shell-quote": {
|
||||
"version": "1.8.3",
|
||||
"resolved": "https://registry.npmjs.org/shell-quote/-/shell-quote-1.8.3.tgz",
|
||||
"integrity": "sha512-ObmnIF4hXNg1BqhnHmgbDETF8dLPCggZWBjkQfhZpbszZnYur5DUljTcCHii5LC3J5E0yeO/1LIMyH+UvHQgyw==",
|
||||
"dev": true,
|
||||
"license": "MIT",
|
||||
"engines": {
|
||||
"node": ">= 0.4"
|
||||
},
|
||||
"funding": {
|
||||
"url": "https://github.com/sponsors/ljharb"
|
||||
}
|
||||
},
|
||||
"node_modules/string-width": {
|
||||
"version": "4.2.3",
|
||||
"resolved": "https://registry.npmjs.org/string-width/-/string-width-4.2.3.tgz",
|
||||
"integrity": "sha512-wKyQRQpjJ0sIp62ErSZdGsjMJWsap5oRNihHhu6G7JVO/9jIB6UyevL+tXuOqrng8j/cxKTWyWUwvSTriiZz/g==",
|
||||
"dev": true,
|
||||
"license": "MIT",
|
||||
"dependencies": {
|
||||
"emoji-regex": "^8.0.0",
|
||||
"is-fullwidth-code-point": "^3.0.0",
|
||||
"strip-ansi": "^6.0.1"
|
||||
},
|
||||
"engines": {
|
||||
"node": ">=8"
|
||||
}
|
||||
},
|
||||
"node_modules/strip-ansi": {
|
||||
"version": "6.0.1",
|
||||
"resolved": "https://registry.npmjs.org/strip-ansi/-/strip-ansi-6.0.1.tgz",
|
||||
"integrity": "sha512-Y38VPSHcqkFrCpFnQ9vuSXmquuv5oXOKpGeT6aGrr3o3Gc9AlVa6JBfUSOCnbxGGZF+/0ooI7KrPuUSztUdU5A==",
|
||||
"dev": true,
|
||||
"license": "MIT",
|
||||
"dependencies": {
|
||||
"ansi-regex": "^5.0.1"
|
||||
},
|
||||
"engines": {
|
||||
"node": ">=8"
|
||||
}
|
||||
},
|
||||
"node_modules/supports-color": {
|
||||
"version": "8.1.1",
|
||||
"resolved": "https://registry.npmjs.org/supports-color/-/supports-color-8.1.1.tgz",
|
||||
"integrity": "sha512-MpUEN2OodtUzxvKQl72cUF7RQ5EiHsGvSsVG0ia9c5RbWGL2CI4C7EpPS8UTBIplnlzZiNuV56w+FuNxy3ty2Q==",
|
||||
"dev": true,
|
||||
"license": "MIT",
|
||||
"dependencies": {
|
||||
"has-flag": "^4.0.0"
|
||||
},
|
||||
"engines": {
|
||||
"node": ">=10"
|
||||
},
|
||||
"funding": {
|
||||
"url": "https://github.com/chalk/supports-color?sponsor=1"
|
||||
}
|
||||
},
|
||||
"node_modules/tree-kill": {
|
||||
"version": "1.2.2",
|
||||
"resolved": "https://registry.npmjs.org/tree-kill/-/tree-kill-1.2.2.tgz",
|
||||
"integrity": "sha512-L0Orpi8qGpRG//Nd+H90vFB+3iHnue1zSSGmNOOCh1GLJ7rUKVwV2HvijphGQS2UmhUZewS9VgvxYIdgr+fG1A==",
|
||||
"dev": true,
|
||||
"license": "MIT",
|
||||
"bin": {
|
||||
"tree-kill": "cli.js"
|
||||
}
|
||||
},
|
||||
"node_modules/tslib": {
|
||||
"version": "2.8.1",
|
||||
"resolved": "https://registry.npmjs.org/tslib/-/tslib-2.8.1.tgz",
|
||||
"integrity": "sha512-oJFu94HQb+KVduSUQL7wnpmqnfmLsOA/nAh6b6EH0wCEoK0/mPeXU6c3wKDV83MkOuHPRHtSXKKU99IBazS/2w==",
|
||||
"dev": true,
|
||||
"license": "0BSD"
|
||||
},
|
||||
"node_modules/wrap-ansi": {
|
||||
"version": "7.0.0",
|
||||
"resolved": "https://registry.npmjs.org/wrap-ansi/-/wrap-ansi-7.0.0.tgz",
|
||||
"integrity": "sha512-YVGIj2kamLSTxw6NsZjoBxfSwsn0ycdesmc4p+Q21c5zPuZ1pl+NfxVdxPtdHvmNVOQ6XSYG4AUtyt/Fi7D16Q==",
|
||||
"dev": true,
|
||||
"license": "MIT",
|
||||
"dependencies": {
|
||||
"ansi-styles": "^4.0.0",
|
||||
"string-width": "^4.1.0",
|
||||
"strip-ansi": "^6.0.0"
|
||||
},
|
||||
"engines": {
|
||||
"node": ">=10"
|
||||
},
|
||||
"funding": {
|
||||
"url": "https://github.com/chalk/wrap-ansi?sponsor=1"
|
||||
}
|
||||
},
|
||||
"node_modules/y18n": {
|
||||
"version": "5.0.8",
|
||||
"resolved": "https://registry.npmjs.org/y18n/-/y18n-5.0.8.tgz",
|
||||
"integrity": "sha512-0pfFzegeDWJHJIAmTLRP2DwHjdF5s7jo9tuztdQxAhINCdvS+3nGINqPd00AphqJR/0LhANUS6/+7SCb98YOfA==",
|
||||
"dev": true,
|
||||
"license": "ISC",
|
||||
"engines": {
|
||||
"node": ">=10"
|
||||
}
|
||||
},
|
||||
"node_modules/yargs": {
|
||||
"version": "17.7.2",
|
||||
"resolved": "https://registry.npmjs.org/yargs/-/yargs-17.7.2.tgz",
|
||||
"integrity": "sha512-7dSzzRQ++CKnNI/krKnYRV7JKKPUXMEh61soaHKg9mrWEhzFWhFnxPxGl+69cD1Ou63C13NUPCnmIcrvqCuM6w==",
|
||||
"dev": true,
|
||||
"license": "MIT",
|
||||
"dependencies": {
|
||||
"cliui": "^8.0.1",
|
||||
"escalade": "^3.1.1",
|
||||
"get-caller-file": "^2.0.5",
|
||||
"require-directory": "^2.1.1",
|
||||
"string-width": "^4.2.3",
|
||||
"y18n": "^5.0.5",
|
||||
"yargs-parser": "^21.1.1"
|
||||
},
|
||||
"engines": {
|
||||
"node": ">=12"
|
||||
}
|
||||
},
|
||||
"node_modules/yargs-parser": {
|
||||
"version": "21.1.1",
|
||||
"resolved": "https://registry.npmjs.org/yargs-parser/-/yargs-parser-21.1.1.tgz",
|
||||
"integrity": "sha512-tVpsJW7DdjecAiFpbIB1e3qxIQsE6NoPc5/eTdrbbIC4h0LVsWhnoa3g+m2HclBIujHzsxZ4VJVA+GUuc2/LBw==",
|
||||
"dev": true,
|
||||
"license": "ISC",
|
||||
"engines": {
|
||||
"node": ">=12"
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
18
package.json
Normal file
18
package.json
Normal file
|
|
@ -0,0 +1,18 @@
|
|||
{
|
||||
"name": "tidyquest",
|
||||
"version": "1.0.0",
|
||||
"private": true,
|
||||
"description": "Self-hosted web app that gamifies household chores",
|
||||
"scripts": {
|
||||
"dev:server": "cd server && npm run dev",
|
||||
"dev:client": "cd client && npm run dev",
|
||||
"dev": "concurrently \"npm run dev:server\" \"npm run dev:client\"",
|
||||
"build:client": "cd client && npm run build",
|
||||
"build:server": "cd server && npm run build",
|
||||
"build": "npm run build:client && npm run build:server",
|
||||
"start": "cd server && npm start"
|
||||
},
|
||||
"devDependencies": {
|
||||
"concurrently": "^9.1.2"
|
||||
}
|
||||
}
|
||||
2213
server/package-lock.json
generated
Normal file
2213
server/package-lock.json
generated
Normal file
File diff suppressed because it is too large
Load diff
29
server/package.json
Normal file
29
server/package.json
Normal file
|
|
@ -0,0 +1,29 @@
|
|||
{
|
||||
"name": "tidyquest-server",
|
||||
"version": "1.0.0",
|
||||
"private": true,
|
||||
"scripts": {
|
||||
"dev": "tsx watch src/index.ts",
|
||||
"build": "tsc",
|
||||
"start": "node dist/index.js"
|
||||
},
|
||||
"dependencies": {
|
||||
"bcryptjs": "^3.0.2",
|
||||
"better-sqlite3": "^11.8.2",
|
||||
"cors": "^2.8.5",
|
||||
"express": "^4.21.2",
|
||||
"jsonwebtoken": "^9.0.2",
|
||||
"multer": "^2.0.2"
|
||||
},
|
||||
"devDependencies": {
|
||||
"@types/bcryptjs": "^2.4.6",
|
||||
"@types/better-sqlite3": "^7.6.13",
|
||||
"@types/cors": "^2.8.17",
|
||||
"@types/express": "^5.0.0",
|
||||
"@types/jsonwebtoken": "^9.0.9",
|
||||
"@types/multer": "^2.0.0",
|
||||
"@types/node": "^22.13.4",
|
||||
"tsx": "^4.19.3",
|
||||
"typescript": "^5.7.3"
|
||||
}
|
||||
}
|
||||
341
server/src/database.ts
Normal file
341
server/src/database.ts
Normal file
|
|
@ -0,0 +1,341 @@
|
|||
import Database from 'better-sqlite3';
|
||||
import path from 'path';
|
||||
import { suggestTaskIcon } from './utils/taskIcons';
|
||||
|
||||
const DB_PATH = path.join(__dirname, '..', '..', 'data', 'tidyquest.db');
|
||||
|
||||
const db = new Database(DB_PATH);
|
||||
|
||||
// Enable WAL mode for better concurrent read performance
|
||||
db.pragma('journal_mode = WAL');
|
||||
db.pragma('foreign_keys = ON');
|
||||
|
||||
export function initDatabase() {
|
||||
db.exec(`
|
||||
CREATE TABLE IF NOT EXISTS users (
|
||||
id INTEGER PRIMARY KEY AUTOINCREMENT,
|
||||
username TEXT UNIQUE NOT NULL,
|
||||
displayName TEXT NOT NULL,
|
||||
passwordHash TEXT NOT NULL,
|
||||
role TEXT NOT NULL DEFAULT 'child',
|
||||
avatarColor TEXT NOT NULL DEFAULT '#F97316',
|
||||
coins INTEGER NOT NULL DEFAULT 0,
|
||||
currentStreak INTEGER NOT NULL DEFAULT 0,
|
||||
lastActiveDate TEXT,
|
||||
isVacationMode INTEGER NOT NULL DEFAULT 0,
|
||||
vacationStartDate TEXT,
|
||||
language TEXT NOT NULL DEFAULT 'en',
|
||||
createdAt TEXT NOT NULL DEFAULT (datetime('now'))
|
||||
);
|
||||
|
||||
CREATE TABLE IF NOT EXISTS rooms (
|
||||
id INTEGER PRIMARY KEY AUTOINCREMENT,
|
||||
name TEXT NOT NULL,
|
||||
roomType TEXT NOT NULL DEFAULT 'other',
|
||||
color TEXT NOT NULL DEFAULT '#FFE4CC',
|
||||
accentColor TEXT NOT NULL DEFAULT '#F97316',
|
||||
photoUrl TEXT,
|
||||
sortOrder INTEGER NOT NULL DEFAULT 0,
|
||||
createdAt TEXT NOT NULL DEFAULT (datetime('now'))
|
||||
);
|
||||
|
||||
CREATE TABLE IF NOT EXISTS tasks (
|
||||
id INTEGER PRIMARY KEY AUTOINCREMENT,
|
||||
roomId INTEGER NOT NULL,
|
||||
name TEXT NOT NULL,
|
||||
notes TEXT,
|
||||
frequencyDays REAL NOT NULL DEFAULT 7,
|
||||
effort INTEGER NOT NULL DEFAULT 1,
|
||||
isSeasonal INTEGER NOT NULL DEFAULT 0,
|
||||
lastCompletedAt TEXT,
|
||||
createdAt TEXT NOT NULL DEFAULT (datetime('now')),
|
||||
FOREIGN KEY (roomId) REFERENCES rooms(id) ON DELETE CASCADE
|
||||
);
|
||||
|
||||
CREATE TABLE IF NOT EXISTS task_completions (
|
||||
id INTEGER PRIMARY KEY AUTOINCREMENT,
|
||||
taskId INTEGER NOT NULL,
|
||||
userId INTEGER NOT NULL,
|
||||
completedAt TEXT NOT NULL DEFAULT (datetime('now')),
|
||||
coinsEarned INTEGER NOT NULL DEFAULT 0,
|
||||
FOREIGN KEY (taskId) REFERENCES tasks(id) ON DELETE CASCADE,
|
||||
FOREIGN KEY (userId) REFERENCES users(id) ON DELETE CASCADE
|
||||
);
|
||||
|
||||
CREATE TABLE IF NOT EXISTS task_due_notifications (
|
||||
id INTEGER PRIMARY KEY AUTOINCREMENT,
|
||||
taskId INTEGER NOT NULL,
|
||||
dueDate TEXT NOT NULL,
|
||||
sentAt TEXT NOT NULL DEFAULT (datetime('now')),
|
||||
UNIQUE(taskId, dueDate),
|
||||
FOREIGN KEY (taskId) REFERENCES tasks(id) ON DELETE CASCADE
|
||||
);
|
||||
|
||||
CREATE TABLE IF NOT EXISTS user_achievement_notifications (
|
||||
id INTEGER PRIMARY KEY AUTOINCREMENT,
|
||||
userId INTEGER NOT NULL,
|
||||
achievementId TEXT NOT NULL,
|
||||
sentAt TEXT NOT NULL DEFAULT (datetime('now')),
|
||||
UNIQUE(userId, achievementId),
|
||||
FOREIGN KEY (userId) REFERENCES users(id) ON DELETE CASCADE
|
||||
);
|
||||
|
||||
CREATE TABLE IF NOT EXISTS app_settings (
|
||||
key TEXT PRIMARY KEY,
|
||||
value TEXT NOT NULL,
|
||||
updatedAt TEXT NOT NULL DEFAULT (datetime('now'))
|
||||
);
|
||||
|
||||
CREATE TABLE IF NOT EXISTS user_goals (
|
||||
id INTEGER PRIMARY KEY AUTOINCREMENT,
|
||||
userId INTEGER NOT NULL,
|
||||
title TEXT NOT NULL,
|
||||
goalCoins INTEGER NOT NULL,
|
||||
startAt TEXT,
|
||||
endAt TEXT,
|
||||
createdBy INTEGER,
|
||||
createdAt TEXT NOT NULL DEFAULT (datetime('now')),
|
||||
FOREIGN KEY (userId) REFERENCES users(id) ON DELETE CASCADE,
|
||||
FOREIGN KEY (createdBy) REFERENCES users(id) ON DELETE SET NULL
|
||||
);
|
||||
|
||||
CREATE TABLE IF NOT EXISTS rewards (
|
||||
id INTEGER PRIMARY KEY AUTOINCREMENT,
|
||||
title TEXT NOT NULL,
|
||||
description TEXT,
|
||||
costCoins INTEGER NOT NULL,
|
||||
isActive INTEGER NOT NULL DEFAULT 1,
|
||||
isPreset INTEGER NOT NULL DEFAULT 0,
|
||||
createdBy INTEGER,
|
||||
createdAt TEXT NOT NULL DEFAULT (datetime('now')),
|
||||
FOREIGN KEY (createdBy) REFERENCES users(id) ON DELETE SET NULL
|
||||
);
|
||||
|
||||
CREATE TABLE IF NOT EXISTS reward_redemptions (
|
||||
id INTEGER PRIMARY KEY AUTOINCREMENT,
|
||||
rewardId INTEGER NOT NULL,
|
||||
userId INTEGER NOT NULL,
|
||||
costCoins INTEGER NOT NULL,
|
||||
redeemedAt TEXT NOT NULL DEFAULT (datetime('now')),
|
||||
status TEXT NOT NULL DEFAULT 'requested',
|
||||
FOREIGN KEY (rewardId) REFERENCES rewards(id) ON DELETE CASCADE,
|
||||
FOREIGN KEY (userId) REFERENCES users(id) ON DELETE CASCADE
|
||||
);
|
||||
|
||||
`);
|
||||
|
||||
// Migrations: add new columns idempotently
|
||||
const migrations = [
|
||||
`ALTER TABLE users ADD COLUMN role TEXT NOT NULL DEFAULT 'child'`,
|
||||
`ALTER TABLE users ADD COLUMN avatarType TEXT NOT NULL DEFAULT 'letter'`,
|
||||
`ALTER TABLE users ADD COLUMN avatarPreset TEXT`,
|
||||
`ALTER TABLE users ADD COLUMN avatarPhotoUrl TEXT`,
|
||||
`ALTER TABLE users ADD COLUMN goalCoins INTEGER`,
|
||||
`ALTER TABLE users ADD COLUMN goalStartAt TEXT`,
|
||||
`ALTER TABLE users ADD COLUMN goalEndAt TEXT`,
|
||||
`ALTER TABLE tasks ADD COLUMN notes TEXT`,
|
||||
`ALTER TABLE tasks ADD COLUMN translationKey TEXT`,
|
||||
`ALTER TABLE tasks ADD COLUMN iconKey TEXT`,
|
||||
];
|
||||
|
||||
for (const sql of migrations) {
|
||||
try {
|
||||
db.exec(sql);
|
||||
} catch (e: any) {
|
||||
// Ignore "duplicate column" errors (column already exists)
|
||||
if (!e.message?.includes('duplicate column')) {
|
||||
throw e;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// Populate translationKey for existing tasks that match default task names
|
||||
const TASK_NAME_TO_KEY: Record<string, string> = {
|
||||
'Wash Dishes': 'kitchen.wash_dishes',
|
||||
'Clean Counters': 'kitchen.clean_counters',
|
||||
'Wipe Stovetop': 'kitchen.wipe_stovetop',
|
||||
'Empty Trash': 'kitchen.empty_trash',
|
||||
'Empty Household Waste': 'kitchen.empty_household_waste',
|
||||
'Empty Compost': 'kitchen.empty_compost',
|
||||
'Empty Plastic Recycling': 'kitchen.empty_plastic_recycling',
|
||||
'Empty Glass Recycling': 'kitchen.empty_glass_recycling',
|
||||
'Clean Sink': 'kitchen.clean_sink',
|
||||
'Clean Kitchen Sink Drain': 'kitchen.clean_sink_drain',
|
||||
'Wipe Appliances': 'kitchen.wipe_appliances',
|
||||
'Mop Floor': 'kitchen.mop_floor',
|
||||
'Clean Microwave': 'kitchen.clean_microwave',
|
||||
'Wipe Cabinet Fronts': 'kitchen.wipe_cabinet_fronts',
|
||||
'Clean Fridge': 'kitchen.clean_fridge',
|
||||
'Defrost Freezer': 'kitchen.defrost_freezer',
|
||||
'Descale Kettle': 'kitchen.descale_kettle',
|
||||
'Clean Dishwasher': 'kitchen.clean_dishwasher',
|
||||
'Clean Dishwasher Filter': 'kitchen.clean_dishwasher_filter',
|
||||
'Check Dishwasher Salt': 'kitchen.check_dishwasher_salt',
|
||||
'Clean Oven': 'kitchen.clean_oven',
|
||||
'Clean Range Hood & Filter': 'kitchen.clean_range_hood',
|
||||
'Deep Clean Fridge': 'kitchen.deep_clean_fridge',
|
||||
'Organize Pantry': 'kitchen.organize_pantry',
|
||||
'Make Bed': 'bedroom.make_bed',
|
||||
'Tidy Nightstand': 'bedroom.tidy_nightstand',
|
||||
'Change Sheets': 'bedroom.change_sheets',
|
||||
'Vacuum Floor': 'bedroom.vacuum_floor',
|
||||
'Dust Surfaces': 'bedroom.dust_surfaces',
|
||||
'Clean Under Bed': 'bedroom.clean_under_bed',
|
||||
'Wash Pillows': 'bedroom.wash_pillows',
|
||||
'Wash Duvet/Comforter': 'bedroom.wash_duvet',
|
||||
'Change Fitted Sheet': 'bedroom.change_fitted_sheet',
|
||||
'Organize Closet': 'bedroom.organize_closet',
|
||||
'Flip/Rotate Mattress': 'bedroom.flip_mattress',
|
||||
'Clean Windows': 'bedroom.clean_windows',
|
||||
'Wash Curtains': 'bedroom.wash_curtains',
|
||||
'Wipe Sink & Counter': 'bathroom.wipe_sink_counter',
|
||||
'Squeegee Shower Glass': 'bathroom.squeegee_shower',
|
||||
'Scrub Toilet': 'bathroom.scrub_toilet',
|
||||
'Clean Mirror': 'bathroom.clean_mirror',
|
||||
'Wash Towels': 'bathroom.wash_towels',
|
||||
'Clean Shower/Tub': 'bathroom.clean_shower_tub',
|
||||
'Clean Sink Drain': 'bathroom.clean_sink_drain',
|
||||
'Clean Shower Drain': 'bathroom.clean_shower_drain',
|
||||
'Wash Bath Mat': 'bathroom.wash_bath_mat',
|
||||
'Wipe Light Switches & Door Handles': 'bathroom.wipe_switches_handles',
|
||||
'Clean Grout': 'bathroom.clean_grout',
|
||||
'Descale Showerhead': 'bathroom.descale_showerhead',
|
||||
'Wash Shower Curtain': 'bathroom.wash_shower_curtain',
|
||||
'Organize Cabinets & Drawers': 'bathroom.organize_cabinets',
|
||||
'Replace Toothbrush': 'bathroom.replace_toothbrush',
|
||||
'Tidy Up / Put Things Away': 'living.tidy_up',
|
||||
'Fluff & Tidy Cushions': 'living.fluff_cushions',
|
||||
'Vacuum Carpet/Floor': 'living.vacuum_carpet',
|
||||
'Dust Surfaces & Shelves': 'living.dust_surfaces_shelves',
|
||||
'Wipe TV Screen': 'living.wipe_tv',
|
||||
'Clean Remote Controls': 'living.clean_remotes',
|
||||
'Dust Lampshades & Light Fixtures': 'living.dust_lampshades',
|
||||
'Vacuum Sofa & Under Cushions': 'living.vacuum_sofa',
|
||||
'Wash Curtains/Blinds': 'living.wash_curtains_blinds',
|
||||
'Deep Clean Carpet/Rug': 'living.deep_clean_carpet',
|
||||
'Clean Behind Furniture': 'living.clean_behind_furniture',
|
||||
'Polish Wood Furniture': 'living.polish_furniture',
|
||||
'Clear Desk': 'office.clear_desk',
|
||||
'Wipe Desk Surface': 'office.wipe_desk',
|
||||
'Clean Keyboard & Mouse': 'office.clean_keyboard_mouse',
|
||||
'Wipe Monitor': 'office.wipe_monitor',
|
||||
'Empty Paper Trash/Shredder': 'office.empty_paper_trash',
|
||||
'Organize Cables': 'office.organize_cables',
|
||||
'Dust Shelves & Bookcase': 'office.dust_shelves',
|
||||
'Clean Desk Lamp': 'office.clean_desk_lamp',
|
||||
'Organize Drawers & Filing': 'office.organize_drawers',
|
||||
'Wipe Light Switches & Door Handle': 'office.wipe_switches',
|
||||
'Clean Chair (Fabric/Leather)': 'office.clean_chair',
|
||||
'Sweep Floor': 'garage.sweep_floor',
|
||||
'Organize Tools': 'garage.organize_tools',
|
||||
'Clean Workbench': 'garage.clean_workbench',
|
||||
'Clear Cobwebs': 'garage.clear_cobwebs',
|
||||
'Organize Storage Shelves': 'garage.organize_shelves',
|
||||
'Wipe Down Power Tools': 'garage.wipe_power_tools',
|
||||
'Sort Recycling & Waste': 'garage.sort_recycling',
|
||||
'Mop/Hose Floor': 'garage.mop_hose_floor',
|
||||
'Check & Organize Chemicals': 'garage.check_chemicals',
|
||||
'Clean Garage Door Tracks': 'garage.clean_door_tracks',
|
||||
'Wipe Washer Door Seal': 'laundry.wipe_washer_seal',
|
||||
'Clean Lint Filter': 'laundry.clean_lint_filter',
|
||||
'Wipe Machine Exterior': 'laundry.wipe_machine_exterior',
|
||||
'Run Washer Cleaning Cycle': 'laundry.run_cleaning_cycle',
|
||||
'Drain Washing Machine': 'laundry.drain_washing_machine',
|
||||
'Descale Washing Machine': 'laundry.descale_washing_machine',
|
||||
'Clean Detergent Drawer': 'laundry.clean_detergent_drawer',
|
||||
'Sweep/Mop Floor': 'laundry.sweep_mop_floor',
|
||||
'Organize Supplies & Detergents': 'laundry.organize_supplies',
|
||||
'Clean Dryer Vent': 'laundry.clean_dryer_vent',
|
||||
'Wipe Folding Surface': 'laundry.wipe_folding_surface',
|
||||
'Sort & Donate Old Clothes': 'laundry.sort_donate_clothes',
|
||||
};
|
||||
|
||||
const updateStmt = db.prepare('UPDATE tasks SET translationKey = ? WHERE name = ? AND translationKey IS NULL');
|
||||
const updateIconStmt = db.prepare("UPDATE tasks SET iconKey = ? WHERE name = ? AND (iconKey IS NULL OR iconKey = '')");
|
||||
const updateMany = db.transaction(() => {
|
||||
for (const [name, key] of Object.entries(TASK_NAME_TO_KEY)) {
|
||||
updateStmt.run(key, name);
|
||||
updateIconStmt.run(suggestTaskIcon(name, key), name);
|
||||
}
|
||||
});
|
||||
updateMany();
|
||||
|
||||
const tasksWithoutIcon = db.prepare("SELECT id, name, translationKey FROM tasks WHERE iconKey IS NULL OR iconKey = ''").all() as Array<{ id: number; name: string; translationKey?: string | null }>;
|
||||
const fillIcons = db.transaction(() => {
|
||||
const setById = db.prepare('UPDATE tasks SET iconKey = ? WHERE id = ?');
|
||||
for (const t of tasksWithoutIcon) {
|
||||
setById.run(suggestTaskIcon(t.name, t.translationKey || null), t.id);
|
||||
}
|
||||
});
|
||||
fillIcons();
|
||||
|
||||
// Reclassify all task icons using the updated suggestTaskIcon mapping.
|
||||
// Old icon keys (kitchen, box, office, bath, laundry) have been replaced with specific icons.
|
||||
const OLD_ICON_KEYS = new Set(['sparkle', 'broom', 'box', 'tools', 'kitchen', 'bath', 'office', 'laundry', 'cobweb', 'sofa', 'rug', 'bed', 'window', 'trash']);
|
||||
const maybeReclassify = db.prepare('SELECT id, name, translationKey, iconKey FROM tasks').all() as Array<{
|
||||
id: number; name: string; translationKey?: string | null; iconKey?: string | null;
|
||||
}>;
|
||||
const refreshIcons = db.transaction(() => {
|
||||
const setById = db.prepare('UPDATE tasks SET iconKey = ? WHERE id = ?');
|
||||
for (const t of maybeReclassify) {
|
||||
const suggested = suggestTaskIcon(t.name, t.translationKey || null);
|
||||
const current = (t.iconKey || '').toLowerCase();
|
||||
if (!current || OLD_ICON_KEYS.has(current)) {
|
||||
if (suggested !== (t.iconKey || '')) setById.run(suggested, t.id);
|
||||
}
|
||||
}
|
||||
});
|
||||
refreshIcons();
|
||||
|
||||
// Default configurable coins mapping by effort
|
||||
db.prepare(
|
||||
"INSERT OR IGNORE INTO app_settings (key, value) VALUES ('coinsByEffort', ?)"
|
||||
).run(JSON.stringify({ 1: 5, 2: 10, 3: 15, 4: 20, 5: 25 }));
|
||||
db.prepare(
|
||||
"INSERT OR IGNORE INTO app_settings (key, value) VALUES ('telegramEnabled', '0')"
|
||||
).run();
|
||||
db.prepare(
|
||||
"INSERT OR IGNORE INTO app_settings (key, value) VALUES ('telegramBotToken', '')"
|
||||
).run();
|
||||
db.prepare(
|
||||
"INSERT OR IGNORE INTO app_settings (key, value) VALUES ('telegramChatId', '')"
|
||||
).run();
|
||||
db.prepare(
|
||||
"INSERT OR IGNORE INTO app_settings (key, value) VALUES ('telegramNotificationTime', '09:00')"
|
||||
).run();
|
||||
db.prepare(
|
||||
"INSERT OR IGNORE INTO app_settings (key, value) VALUES ('telegramNotificationTypes', ?)"
|
||||
).run(JSON.stringify({ taskDue: true, rewardRequest: true, achievementUnlocked: true }));
|
||||
|
||||
const rewardCount = (db.prepare('SELECT COUNT(*) as count FROM rewards').get() as { count: number }).count;
|
||||
if (rewardCount === 0) {
|
||||
const insertReward = db.prepare(
|
||||
'INSERT INTO rewards (title, description, costCoins, isPreset, isActive) VALUES (?, ?, ?, 1, 1)'
|
||||
);
|
||||
const defaults: Array<[string, string, number]> = [
|
||||
['Movie Night Pick', 'Choisir le film du soir en famille.', 40],
|
||||
['Ice Cream Treat', 'Une glace ou un dessert special.', 30],
|
||||
['Stay Up 30 Min', 'Se coucher 30 minutes plus tard.', 35],
|
||||
['Game Time Bonus', '30 minutes de jeu supplementaire.', 50],
|
||||
['Choose Dinner', 'Choisir le menu du diner.', 45],
|
||||
['Park Adventure', 'Sortie au parc en mode aventure.', 60],
|
||||
['No-Chore Pass', 'Une tache au choix sautee cette semaine.', 80],
|
||||
['Family Board Game', 'Choisir un jeu de societe pour la soiree.', 25],
|
||||
];
|
||||
const seed = db.transaction(() => {
|
||||
defaults.forEach(([title, description, cost]) => insertReward.run(title, description, cost));
|
||||
});
|
||||
seed();
|
||||
}
|
||||
|
||||
// Ensure there is always at least one admin user
|
||||
const adminCount = db.prepare("SELECT COUNT(*) as count FROM users WHERE role = 'admin'").get() as { count: number };
|
||||
if (adminCount.count === 0) {
|
||||
const firstUser = db.prepare('SELECT id FROM users ORDER BY id ASC LIMIT 1').get() as { id: number } | undefined;
|
||||
if (firstUser) {
|
||||
db.prepare("UPDATE users SET role = 'admin' WHERE id = ?").run(firstUser.id);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
export default db;
|
||||
58
server/src/index.ts
Normal file
58
server/src/index.ts
Normal file
|
|
@ -0,0 +1,58 @@
|
|||
import express from 'express';
|
||||
import cors from 'cors';
|
||||
import path from 'path';
|
||||
import { initDatabase } from './database';
|
||||
import authRoutes from './routes/auth';
|
||||
import roomsRoutes from './routes/rooms';
|
||||
import tasksRoutes from './routes/tasks';
|
||||
import dashboardRoutes from './routes/dashboard';
|
||||
import leaderboardRoutes from './routes/leaderboard';
|
||||
import historyRoutes from './routes/history';
|
||||
import usersRoutes from './routes/users';
|
||||
import dataRoutes from './routes/data';
|
||||
import achievementsRoutes from './routes/achievements';
|
||||
import rewardsRoutes from './routes/rewards';
|
||||
import { sendDueTaskNotificationsIfNeeded } from './utils/notifications';
|
||||
|
||||
const app = express();
|
||||
const PORT = process.env.PORT || 3000;
|
||||
|
||||
// Initialize database
|
||||
initDatabase();
|
||||
|
||||
// Middleware
|
||||
app.use(cors());
|
||||
app.use(express.json({ limit: '50mb' }));
|
||||
|
||||
// Serve uploaded avatars
|
||||
const avatarsDir = path.join(__dirname, '..', '..', 'data', 'avatars');
|
||||
app.use('/api/avatars', express.static(avatarsDir));
|
||||
|
||||
// API routes
|
||||
app.use('/api/auth', authRoutes);
|
||||
app.use('/api/rooms', roomsRoutes);
|
||||
app.use('/api', tasksRoutes);
|
||||
app.use('/api/dashboard', dashboardRoutes);
|
||||
app.use('/api/leaderboard', leaderboardRoutes);
|
||||
app.use('/api/history', historyRoutes);
|
||||
app.use('/api/users', usersRoutes);
|
||||
app.use('/api', dataRoutes);
|
||||
app.use('/api/achievements', achievementsRoutes);
|
||||
app.use('/api/rewards', rewardsRoutes);
|
||||
|
||||
// Serve static frontend in production
|
||||
const clientDist = path.join(__dirname, '..', '..', 'client', 'dist');
|
||||
app.use(express.static(clientDist));
|
||||
app.get('*', (req, res) => {
|
||||
if (!req.path.startsWith('/api')) {
|
||||
res.sendFile(path.join(clientDist, 'index.html'));
|
||||
}
|
||||
});
|
||||
|
||||
app.listen(PORT, () => {
|
||||
console.log(`TidyQuest server running on http://localhost:${PORT}`);
|
||||
void sendDueTaskNotificationsIfNeeded();
|
||||
setInterval(() => {
|
||||
void sendDueTaskNotificationsIfNeeded();
|
||||
}, 30000);
|
||||
});
|
||||
36
server/src/middleware/auth.ts
Normal file
36
server/src/middleware/auth.ts
Normal file
|
|
@ -0,0 +1,36 @@
|
|||
import { Request, Response, NextFunction } from 'express';
|
||||
import jwt from 'jsonwebtoken';
|
||||
|
||||
// Security: Require JWT_SECRET in production
|
||||
if (process.env.NODE_ENV === 'production' && !process.env.JWT_SECRET) {
|
||||
console.error('FATAL: JWT_SECRET environment variable is required in production mode.');
|
||||
console.error('Generate a secure secret: openssl rand -base64 32');
|
||||
console.error('Set it in your .env file or docker-compose.yml');
|
||||
process.exit(1);
|
||||
}
|
||||
|
||||
const JWT_SECRET = process.env.JWT_SECRET || 'tidyquest-secret-change-in-production';
|
||||
|
||||
export interface AuthRequest extends Request {
|
||||
userId?: number;
|
||||
}
|
||||
|
||||
export function authMiddleware(req: AuthRequest, res: Response, next: NextFunction) {
|
||||
const header = req.headers.authorization;
|
||||
if (!header || !header.startsWith('Bearer ')) {
|
||||
return res.status(401).json({ error: 'No token provided' });
|
||||
}
|
||||
|
||||
const token = header.slice(7);
|
||||
try {
|
||||
const payload = jwt.verify(token, JWT_SECRET) as { userId: number };
|
||||
req.userId = payload.userId;
|
||||
next();
|
||||
} catch {
|
||||
return res.status(401).json({ error: 'Invalid token' });
|
||||
}
|
||||
}
|
||||
|
||||
export function generateToken(userId: number): string {
|
||||
return jwt.sign({ userId }, JWT_SECRET, { expiresIn: '30d' });
|
||||
}
|
||||
111
server/src/routes/achievements.ts
Normal file
111
server/src/routes/achievements.ts
Normal file
|
|
@ -0,0 +1,111 @@
|
|||
import { Router, Response } from 'express';
|
||||
import db from '../database';
|
||||
import { AuthRequest, authMiddleware } from '../middleware/auth';
|
||||
import { buildAchievements } from '../utils/achievements';
|
||||
import { calculateHealth } from '../utils/health';
|
||||
|
||||
const router = Router();
|
||||
router.use(authMiddleware);
|
||||
|
||||
function getUserStats(userId: number) {
|
||||
const user = db.prepare('SELECT id, displayName, role, coins, currentStreak, avatarColor, avatarType, avatarPreset, avatarPhotoUrl, isVacationMode, vacationStartDate FROM users WHERE id = ?').get(userId) as any;
|
||||
if (!user) return null;
|
||||
|
||||
const completionsRow = db.prepare('SELECT COUNT(*) as count FROM task_completions WHERE userId = ?').get(userId) as { count: number };
|
||||
|
||||
// Rooms with health >= 70 (considered "clean")
|
||||
const rooms = db.prepare('SELECT * FROM rooms').all() as any[];
|
||||
let roomsClean = 0;
|
||||
for (const room of rooms) {
|
||||
const tasks = db.prepare('SELECT * FROM tasks WHERE roomId = ?').all(room.id) as any[];
|
||||
if (tasks.length === 0) continue;
|
||||
const nonSeasonal = tasks.filter((t: any) => !t.isSeasonal);
|
||||
const forAvg = nonSeasonal.length > 0 ? nonSeasonal : tasks;
|
||||
const totalEffort = forAvg.reduce((s: number, t: any) => s + t.effort, 0);
|
||||
const health = totalEffort > 0
|
||||
? Math.round(forAvg.reduce((s: number, t: any) => s + calculateHealth(t.lastCompletedAt, t.frequencyDays, !!user.isVacationMode, user.vacationStartDate) * t.effort, 0) / totalEffort)
|
||||
: 100;
|
||||
if (health >= 70) roomsClean++;
|
||||
}
|
||||
|
||||
// Tasks completed this week (Monday 00:00 UTC to now)
|
||||
const now = new Date();
|
||||
const dayOfWeek = now.getUTCDay() || 7; // Sunday=7
|
||||
const monday = new Date(now);
|
||||
monday.setUTCDate(now.getUTCDate() - dayOfWeek + 1);
|
||||
monday.setUTCHours(0, 0, 0, 0);
|
||||
const weeklyRow = db.prepare(
|
||||
'SELECT COUNT(*) as count FROM task_completions WHERE userId = ? AND completedAt >= ?'
|
||||
).get(userId, monday.toISOString()) as { count: number };
|
||||
|
||||
// Perfect weeks: weeks where user completed at least 1 task every day (Mon-Sun)
|
||||
// We count how many full weeks had all 7 days with at least one completion
|
||||
const allCompletions = db.prepare(
|
||||
"SELECT date(completedAt) as day FROM task_completions WHERE userId = ? GROUP BY date(completedAt) ORDER BY day"
|
||||
).all(userId) as Array<{ day: string }>;
|
||||
|
||||
const parseDayUTC = (day: string): Date => new Date(`${day}T00:00:00.000Z`);
|
||||
const mondayOfUTCDate = (d: Date): Date => {
|
||||
const out = new Date(d);
|
||||
const dow = out.getUTCDay() || 7;
|
||||
out.setUTCDate(out.getUTCDate() - dow + 1);
|
||||
out.setUTCHours(0, 0, 0, 0);
|
||||
return out;
|
||||
};
|
||||
|
||||
let perfectWeeks = 0;
|
||||
if (allCompletions.length > 0) {
|
||||
const daySet = new Set(allCompletions.map(c => c.day));
|
||||
// Check each past full week
|
||||
const firstDay = parseDayUTC(allCompletions[0].day);
|
||||
const startMonday = mondayOfUTCDate(firstDay);
|
||||
|
||||
const thisMonday = mondayOfUTCDate(now);
|
||||
const checkDate = new Date(startMonday);
|
||||
|
||||
while (checkDate < thisMonday) {
|
||||
let allDays = true;
|
||||
for (let d = 0; d < 7; d++) {
|
||||
const checkDay = new Date(checkDate);
|
||||
checkDay.setUTCDate(checkDate.getUTCDate() + d);
|
||||
const dayStr = checkDay.toISOString().slice(0, 10);
|
||||
if (!daySet.has(dayStr)) { allDays = false; break; }
|
||||
}
|
||||
if (allDays) perfectWeeks++;
|
||||
checkDate.setUTCDate(checkDate.getUTCDate() + 7);
|
||||
}
|
||||
}
|
||||
|
||||
return {
|
||||
id: user.id,
|
||||
displayName: user.displayName,
|
||||
role: user.role,
|
||||
avatarColor: user.avatarColor,
|
||||
avatarType: user.avatarType,
|
||||
avatarPreset: user.avatarPreset,
|
||||
avatarPhotoUrl: user.avatarPhotoUrl,
|
||||
achievements: buildAchievements({
|
||||
completions: completionsRow.count,
|
||||
streak: user.currentStreak || 0,
|
||||
coins: user.coins || 0,
|
||||
rooms_clean: roomsClean,
|
||||
weekly_tasks: weeklyRow.count,
|
||||
perfect_weeks: perfectWeeks,
|
||||
}),
|
||||
};
|
||||
}
|
||||
|
||||
router.get('/', (req: AuthRequest, res: Response) => {
|
||||
const me = getUserStats(req.userId!);
|
||||
if (!me) return res.status(404).json({ error: 'User not found' });
|
||||
|
||||
const family = me.role === 'admin'
|
||||
? (db.prepare("SELECT id FROM users WHERE role IN ('child', 'member') ORDER BY displayName").all() as Array<{ id: number }>)
|
||||
.map((u) => getUserStats(u.id))
|
||||
.filter(Boolean)
|
||||
: [];
|
||||
|
||||
res.json({ me, family });
|
||||
});
|
||||
|
||||
export default router;
|
||||
64
server/src/routes/auth.ts
Normal file
64
server/src/routes/auth.ts
Normal file
|
|
@ -0,0 +1,64 @@
|
|||
import { Router, Response } from 'express';
|
||||
import bcrypt from 'bcryptjs';
|
||||
import db from '../database';
|
||||
import { AuthRequest, authMiddleware, generateToken } from '../middleware/auth';
|
||||
|
||||
const router = Router();
|
||||
|
||||
router.post('/register', (req: AuthRequest, res: Response) => {
|
||||
const { username, password, displayName, avatarColor, language } = req.body;
|
||||
|
||||
if (!username || !password || !displayName) {
|
||||
return res.status(400).json({ error: 'username, password, and displayName are required' });
|
||||
}
|
||||
|
||||
const existing = db.prepare('SELECT id FROM users WHERE username = ?').get(username);
|
||||
if (existing) {
|
||||
return res.status(409).json({ error: 'Username already taken' });
|
||||
}
|
||||
|
||||
const userCount = db.prepare('SELECT COUNT(*) as count FROM users').get() as { count: number };
|
||||
const role = userCount.count === 0 ? 'admin' : 'member';
|
||||
|
||||
const passwordHash = bcrypt.hashSync(password, 10);
|
||||
const result = db.prepare(
|
||||
'INSERT INTO users (username, displayName, passwordHash, role, avatarColor, language) VALUES (?, ?, ?, ?, ?, ?)'
|
||||
).run(username, displayName, passwordHash, role, avatarColor || '#F97316', language || 'en');
|
||||
|
||||
const token = generateToken(result.lastInsertRowid as number);
|
||||
const user = db.prepare('SELECT id, username, displayName, role, avatarColor, avatarType, avatarPreset, avatarPhotoUrl, coins, currentStreak, goalCoins, goalStartAt, goalEndAt, language FROM users WHERE id = ?')
|
||||
.get(result.lastInsertRowid);
|
||||
|
||||
res.status(201).json({ token, user });
|
||||
});
|
||||
|
||||
router.post('/login', (req: AuthRequest, res: Response) => {
|
||||
const { username, password } = req.body;
|
||||
|
||||
if (!username || !password) {
|
||||
return res.status(400).json({ error: 'username and password are required' });
|
||||
}
|
||||
|
||||
const user = db.prepare('SELECT * FROM users WHERE username = ?').get(username) as any;
|
||||
if (!user || !bcrypt.compareSync(password, user.passwordHash)) {
|
||||
return res.status(401).json({ error: 'Invalid credentials' });
|
||||
}
|
||||
|
||||
const token = generateToken(user.id);
|
||||
const { passwordHash, ...safeUser } = user;
|
||||
res.json({ token, user: safeUser });
|
||||
});
|
||||
|
||||
router.get('/me', authMiddleware, (req: AuthRequest, res: Response) => {
|
||||
const user = db.prepare(
|
||||
'SELECT id, username, displayName, role, avatarColor, avatarType, avatarPreset, avatarPhotoUrl, coins, currentStreak, goalCoins, goalStartAt, goalEndAt, lastActiveDate, isVacationMode, language, createdAt FROM users WHERE id = ?'
|
||||
).get(req.userId) as any;
|
||||
|
||||
if (!user) {
|
||||
return res.status(404).json({ error: 'User not found' });
|
||||
}
|
||||
|
||||
res.json(user);
|
||||
});
|
||||
|
||||
export default router;
|
||||
139
server/src/routes/dashboard.ts
Normal file
139
server/src/routes/dashboard.ts
Normal file
|
|
@ -0,0 +1,139 @@
|
|||
import { Router, Response } from 'express';
|
||||
import db from '../database';
|
||||
import { AuthRequest, authMiddleware } from '../middleware/auth';
|
||||
import { calculateHealth } from '../utils/health';
|
||||
|
||||
const router = Router();
|
||||
router.use(authMiddleware);
|
||||
|
||||
router.get('/', (req: AuthRequest, res: Response) => {
|
||||
const user = db.prepare(
|
||||
'SELECT id, username, displayName, role, avatarColor, avatarType, avatarPreset, avatarPhotoUrl, coins, currentStreak, goalCoins, goalStartAt, goalEndAt, lastActiveDate, isVacationMode, vacationStartDate, language FROM users WHERE id = ?'
|
||||
).get(req.userId) as any;
|
||||
|
||||
const rooms = db.prepare('SELECT * FROM rooms ORDER BY sortOrder, id').all() as any[];
|
||||
const allTasks: any[] = [];
|
||||
|
||||
const nowTs = Date.now();
|
||||
const roomsWithHealth = rooms.map((room) => {
|
||||
const tasks = db.prepare('SELECT * FROM tasks WHERE roomId = ?').all(room.id) as any[];
|
||||
const tasksWithHealth = tasks.map((t) => {
|
||||
const health = calculateHealth(t.lastCompletedAt, t.frequencyDays, !!user.isVacationMode, user.vacationStartDate);
|
||||
const safeFreq = Math.max(1 / 24, Number(t.frequencyDays) || 7);
|
||||
const dueDateTs = t.lastCompletedAt
|
||||
? new Date(t.lastCompletedAt).getTime() + safeFreq * 86400000
|
||||
: nowTs;
|
||||
const dueInDays = Math.ceil((dueDateTs - nowTs) / 86400000);
|
||||
const taskWithHealth = {
|
||||
...t,
|
||||
isSeasonal: !!t.isSeasonal,
|
||||
health,
|
||||
dueDate: new Date(dueDateTs).toISOString(),
|
||||
dueInDays,
|
||||
roomName: room.name,
|
||||
roomColor: room.color,
|
||||
roomAccent: room.accentColor,
|
||||
};
|
||||
allTasks.push(taskWithHealth);
|
||||
return taskWithHealth;
|
||||
});
|
||||
|
||||
const nonSeasonal = tasksWithHealth.filter((t) => !t.isSeasonal);
|
||||
const forAvg = nonSeasonal.length > 0 ? nonSeasonal : tasksWithHealth;
|
||||
const totalEffort = forAvg.reduce((s, t) => s + t.effort, 0);
|
||||
const health = totalEffort > 0
|
||||
? Math.round(forAvg.reduce((s, t) => s + t.health * t.effort, 0) / totalEffort)
|
||||
: 100;
|
||||
|
||||
return { ...room, health, taskCount: tasks.length, criticalCount: tasksWithHealth.filter((t) => t.health < 30).length };
|
||||
});
|
||||
|
||||
// House health
|
||||
const nonSeasonal = allTasks.filter((t) => !t.isSeasonal);
|
||||
const forHouseAvg = nonSeasonal.length > 0 ? nonSeasonal : allTasks;
|
||||
const totalEffort = forHouseAvg.reduce((s, t) => s + t.effort, 0);
|
||||
const houseHealth = totalEffort > 0
|
||||
? Math.round(forHouseAvg.reduce((s, t) => s + t.health * t.effort, 0) / totalEffort)
|
||||
: 100;
|
||||
|
||||
// Today's quests: tasks due today or overdue, non-seasonal
|
||||
const todaysQuests = allTasks
|
||||
.filter((t) => !t.isSeasonal && t.dueInDays <= 0)
|
||||
.sort((a, b) => a.dueInDays - b.dueInDays || a.health - b.health)
|
||||
.slice(0, 10);
|
||||
|
||||
// Next tasks to come soon (non-seasonal)
|
||||
const nextTasks = allTasks
|
||||
.filter((t) => !t.isSeasonal && t.dueInDays > 0)
|
||||
.sort((a, b) => a.dueInDays - b.dueInDays || a.health - b.health)
|
||||
.slice(0, 10);
|
||||
|
||||
// Recent activity
|
||||
const recentActivity = db.prepare(`
|
||||
SELECT tc.*, t.name as taskName, t.translationKey, t.roomId, r.name as roomName, u.displayName, u.avatarColor, u.avatarType, u.avatarPreset, u.avatarPhotoUrl
|
||||
FROM task_completions tc
|
||||
JOIN tasks t ON tc.taskId = t.id
|
||||
JOIN rooms r ON t.roomId = r.id
|
||||
JOIN users u ON tc.userId = u.id
|
||||
ORDER BY tc.completedAt DESC
|
||||
LIMIT 5
|
||||
`).all();
|
||||
|
||||
function getGoalCoinsWithinPeriod(targetUser: any): number {
|
||||
if (!targetUser.goalStartAt && !targetUser.goalEndAt) return targetUser.coins;
|
||||
const from = targetUser.goalStartAt || '1970-01-01T00:00:00.000Z';
|
||||
const to = targetUser.goalEndAt || '9999-12-31T23:59:59.999Z';
|
||||
const row = db.prepare(
|
||||
'SELECT COALESCE(SUM(coinsEarned), 0) as total FROM task_completions WHERE userId = ? AND completedAt >= ? AND completedAt <= ?'
|
||||
).get(targetUser.id, from, to) as { total: number };
|
||||
return row?.total || 0;
|
||||
}
|
||||
|
||||
const myCurrentCoins = user.goalCoins ? getGoalCoinsWithinPeriod(user) : user.coins;
|
||||
const myGoal = user.goalCoins ? {
|
||||
goalCoins: user.goalCoins,
|
||||
currentCoins: myCurrentCoins,
|
||||
goalStartAt: user.goalStartAt || null,
|
||||
goalEndAt: user.goalEndAt || null,
|
||||
progress: Math.min(100, Math.round((myCurrentCoins / user.goalCoins) * 100)),
|
||||
} : null;
|
||||
|
||||
const childrenGoals = user.role === 'admin'
|
||||
? db.prepare(
|
||||
"SELECT id, displayName, role, coins, goalCoins, goalStartAt, goalEndAt, avatarColor, avatarType, avatarPreset, avatarPhotoUrl FROM users WHERE role != 'admin' ORDER BY displayName"
|
||||
).all().map((c: any) => {
|
||||
const currentCoins = c.goalCoins ? getGoalCoinsWithinPeriod(c) : c.coins;
|
||||
return {
|
||||
...c,
|
||||
currentCoins,
|
||||
progress: c.goalCoins ? Math.min(100, Math.round((currentCoins / c.goalCoins) * 100)) : null,
|
||||
};
|
||||
})
|
||||
: [];
|
||||
|
||||
const pendingRewardRequests = user.role === 'admin'
|
||||
? db.prepare(
|
||||
`SELECT rr.id, rr.costCoins, rr.redeemedAt, rr.status, r.title, u.displayName
|
||||
FROM reward_redemptions rr
|
||||
JOIN rewards r ON rr.rewardId = r.id
|
||||
JOIN users u ON rr.userId = u.id
|
||||
WHERE rr.status = 'requested'
|
||||
ORDER BY rr.redeemedAt DESC
|
||||
LIMIT 12`
|
||||
).all()
|
||||
: [];
|
||||
|
||||
res.json({
|
||||
houseHealth,
|
||||
rooms: roomsWithHealth,
|
||||
todaysQuests,
|
||||
nextTasks,
|
||||
myGoal,
|
||||
childrenGoals,
|
||||
pendingRewardRequests,
|
||||
currentUser: user,
|
||||
recentActivity,
|
||||
});
|
||||
});
|
||||
|
||||
export default router;
|
||||
136
server/src/routes/data.ts
Normal file
136
server/src/routes/data.ts
Normal file
|
|
@ -0,0 +1,136 @@
|
|||
import { Router, Response } from 'express';
|
||||
import db from '../database';
|
||||
import { AuthRequest, authMiddleware } from '../middleware/auth';
|
||||
|
||||
const router = Router();
|
||||
router.use(authMiddleware);
|
||||
|
||||
function ensureAdmin(userId: number | undefined): boolean {
|
||||
if (!userId) return false;
|
||||
const user = db.prepare('SELECT role FROM users WHERE id = ?').get(userId) as { role: string } | undefined;
|
||||
return user?.role === 'admin';
|
||||
}
|
||||
|
||||
// Export all data as JSON
|
||||
router.get('/export', (req: AuthRequest, res: Response) => {
|
||||
if (!ensureAdmin(req.userId)) {
|
||||
return res.status(403).json({ error: 'Admin only' });
|
||||
}
|
||||
|
||||
const users = db.prepare('SELECT id, username, displayName, role, avatarColor, avatarType, avatarPreset, avatarPhotoUrl, coins, currentStreak, goalCoins, goalStartAt, goalEndAt, lastActiveDate, isVacationMode, language, createdAt FROM users').all();
|
||||
const rooms = db.prepare('SELECT * FROM rooms').all();
|
||||
const tasks = db.prepare('SELECT * FROM tasks').all();
|
||||
const completions = db.prepare('SELECT * FROM task_completions').all();
|
||||
const settings = db.prepare('SELECT * FROM app_settings').all();
|
||||
const goals = db.prepare('SELECT * FROM user_goals').all();
|
||||
const rewards = db.prepare('SELECT * FROM rewards').all();
|
||||
const rewardRedemptions = db.prepare('SELECT * FROM reward_redemptions').all();
|
||||
|
||||
res.setHeader('Content-Disposition', 'attachment; filename=tidyquest-backup.json');
|
||||
res.json({ version: 4, exportedAt: new Date().toISOString(), users, rooms, tasks, completions, settings, goals, rewards, rewardRedemptions });
|
||||
});
|
||||
|
||||
// Import data from JSON
|
||||
router.post('/import', (req: AuthRequest, res: Response) => {
|
||||
if (!ensureAdmin(req.userId)) {
|
||||
return res.status(403).json({ error: 'Admin only' });
|
||||
}
|
||||
|
||||
const { users, rooms, tasks, completions, settings, goals, rewards, rewardRedemptions } = req.body;
|
||||
|
||||
if (!users || !rooms || !tasks || !completions) {
|
||||
return res.status(400).json({ error: 'Invalid backup format. Expected: users, rooms, tasks, completions' });
|
||||
}
|
||||
|
||||
const importData = db.transaction(() => {
|
||||
// Clear existing data
|
||||
db.prepare('DELETE FROM task_completions').run();
|
||||
db.prepare('DELETE FROM reward_redemptions').run();
|
||||
db.prepare('DELETE FROM user_goals').run();
|
||||
db.prepare('DELETE FROM rewards').run();
|
||||
db.prepare('DELETE FROM tasks').run();
|
||||
db.prepare('DELETE FROM rooms').run();
|
||||
db.prepare('DELETE FROM users').run();
|
||||
|
||||
// Re-insert
|
||||
for (const u of users) {
|
||||
db.prepare(
|
||||
'INSERT INTO users (id, username, displayName, passwordHash, role, avatarColor, avatarType, avatarPreset, avatarPhotoUrl, coins, currentStreak, goalCoins, goalStartAt, goalEndAt, lastActiveDate, isVacationMode, language, createdAt) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)'
|
||||
).run(
|
||||
u.id,
|
||||
u.username,
|
||||
u.displayName,
|
||||
u.passwordHash || '',
|
||||
u.role || 'child',
|
||||
u.avatarColor,
|
||||
u.avatarType || 'letter',
|
||||
u.avatarPreset || null,
|
||||
u.avatarPhotoUrl || null,
|
||||
u.coins,
|
||||
u.currentStreak,
|
||||
u.goalCoins || null,
|
||||
u.goalStartAt || null,
|
||||
u.goalEndAt || null,
|
||||
u.lastActiveDate,
|
||||
u.isVacationMode ? 1 : 0,
|
||||
u.language,
|
||||
u.createdAt
|
||||
);
|
||||
}
|
||||
|
||||
for (const r of rooms) {
|
||||
db.prepare(
|
||||
'INSERT INTO rooms (id, name, roomType, color, accentColor, photoUrl, sortOrder, createdAt) VALUES (?, ?, ?, ?, ?, ?, ?, ?)'
|
||||
).run(r.id, r.name, r.roomType, r.color, r.accentColor, r.photoUrl, r.sortOrder, r.createdAt);
|
||||
}
|
||||
|
||||
for (const t of tasks) {
|
||||
db.prepare(
|
||||
'INSERT INTO tasks (id, roomId, name, notes, frequencyDays, effort, isSeasonal, lastCompletedAt, translationKey, iconKey, createdAt) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)'
|
||||
).run(t.id, t.roomId, t.name, t.notes || null, t.frequencyDays, t.effort, t.isSeasonal ? 1 : 0, t.lastCompletedAt, t.translationKey || null, t.iconKey || null, t.createdAt);
|
||||
}
|
||||
|
||||
for (const c of completions) {
|
||||
db.prepare(
|
||||
'INSERT INTO task_completions (id, taskId, userId, completedAt, coinsEarned) VALUES (?, ?, ?, ?, ?)'
|
||||
).run(c.id, c.taskId, c.userId, c.completedAt, c.coinsEarned);
|
||||
}
|
||||
|
||||
if (Array.isArray(settings)) {
|
||||
db.prepare('DELETE FROM app_settings').run();
|
||||
for (const s of settings) {
|
||||
db.prepare('INSERT INTO app_settings (key, value, updatedAt) VALUES (?, ?, COALESCE(?, datetime(\'now\')))').run(s.key, s.value, s.updatedAt);
|
||||
}
|
||||
}
|
||||
|
||||
if (Array.isArray(goals)) {
|
||||
for (const g of goals) {
|
||||
db.prepare(
|
||||
'INSERT INTO user_goals (id, userId, title, goalCoins, startAt, endAt, createdBy, createdAt) VALUES (?, ?, ?, ?, ?, ?, ?, ?)'
|
||||
).run(g.id, g.userId, g.title, g.goalCoins, g.startAt || null, g.endAt || null, g.createdBy || null, g.createdAt);
|
||||
}
|
||||
}
|
||||
|
||||
if (Array.isArray(rewards)) {
|
||||
for (const r of rewards) {
|
||||
db.prepare(
|
||||
'INSERT INTO rewards (id, title, description, costCoins, isActive, isPreset, createdBy, createdAt) VALUES (?, ?, ?, ?, ?, ?, ?, ?)'
|
||||
).run(r.id, r.title, r.description || null, r.costCoins, r.isActive ? 1 : 0, r.isPreset ? 1 : 0, r.createdBy || null, r.createdAt);
|
||||
}
|
||||
}
|
||||
|
||||
if (Array.isArray(rewardRedemptions)) {
|
||||
for (const rr of rewardRedemptions) {
|
||||
db.prepare(
|
||||
'INSERT INTO reward_redemptions (id, rewardId, userId, costCoins, redeemedAt, status) VALUES (?, ?, ?, ?, ?, ?)'
|
||||
).run(rr.id, rr.rewardId, rr.userId, rr.costCoins, rr.redeemedAt, rr.status || 'requested');
|
||||
}
|
||||
}
|
||||
|
||||
});
|
||||
|
||||
importData();
|
||||
res.json({ success: true, imported: { users: users.length, rooms: rooms.length, tasks: tasks.length, completions: completions.length } });
|
||||
});
|
||||
|
||||
export default router;
|
||||
30
server/src/routes/history.ts
Normal file
30
server/src/routes/history.ts
Normal file
|
|
@ -0,0 +1,30 @@
|
|||
import { Router, Response } from 'express';
|
||||
import db from '../database';
|
||||
import { AuthRequest, authMiddleware } from '../middleware/auth';
|
||||
|
||||
const router = Router();
|
||||
router.use(authMiddleware);
|
||||
|
||||
router.get('/', (req: AuthRequest, res: Response) => {
|
||||
const limit = Math.min(parseInt(req.query.limit as string) || 20, 100);
|
||||
const offset = parseInt(req.query.offset as string) || 0;
|
||||
|
||||
const history = db.prepare(`
|
||||
SELECT tc.id, tc.completedAt, tc.coinsEarned,
|
||||
t.name as taskName, t.translationKey, t.roomId,
|
||||
r.name as roomName, r.roomType,
|
||||
u.id as userId, u.displayName, u.avatarColor, u.avatarType, u.avatarPreset, u.avatarPhotoUrl
|
||||
FROM task_completions tc
|
||||
JOIN tasks t ON tc.taskId = t.id
|
||||
JOIN rooms r ON t.roomId = r.id
|
||||
JOIN users u ON tc.userId = u.id
|
||||
ORDER BY tc.completedAt DESC
|
||||
LIMIT ? OFFSET ?
|
||||
`).all(limit, offset);
|
||||
|
||||
const total = db.prepare('SELECT COUNT(*) as count FROM task_completions').get() as any;
|
||||
|
||||
res.json({ history, total: total.count, limit, offset });
|
||||
});
|
||||
|
||||
export default router;
|
||||
55
server/src/routes/leaderboard.ts
Normal file
55
server/src/routes/leaderboard.ts
Normal file
|
|
@ -0,0 +1,55 @@
|
|||
import { Router, Response } from 'express';
|
||||
import db from '../database';
|
||||
import { AuthRequest, authMiddleware } from '../middleware/auth';
|
||||
|
||||
const router = Router();
|
||||
router.use(authMiddleware);
|
||||
|
||||
router.get('/', (req: AuthRequest, res: Response) => {
|
||||
const requested = String(req.query.period || 'week');
|
||||
const period = ['week', 'month', 'quarter', 'year'].includes(requested)
|
||||
? (requested as 'week' | 'month' | 'quarter' | 'year')
|
||||
: 'week';
|
||||
|
||||
// Calculate date range
|
||||
const now = new Date();
|
||||
let startDate: string;
|
||||
|
||||
if (period === 'week') {
|
||||
const dayOfWeek = now.getDay();
|
||||
const monday = new Date(now);
|
||||
monday.setDate(now.getDate() - (dayOfWeek === 0 ? 6 : dayOfWeek - 1));
|
||||
monday.setHours(0, 0, 0, 0);
|
||||
startDate = monday.toISOString();
|
||||
} else if (period === 'month') {
|
||||
const firstOfMonth = new Date(now.getFullYear(), now.getMonth(), 1);
|
||||
startDate = firstOfMonth.toISOString();
|
||||
} else if (period === 'quarter') {
|
||||
const quarterStartMonth = Math.floor(now.getMonth() / 3) * 3;
|
||||
const firstOfQuarter = new Date(now.getFullYear(), quarterStartMonth, 1);
|
||||
startDate = firstOfQuarter.toISOString();
|
||||
} else {
|
||||
const firstOfYear = new Date(now.getFullYear(), 0, 1);
|
||||
startDate = firstOfYear.toISOString();
|
||||
}
|
||||
|
||||
const users = db.prepare(
|
||||
'SELECT id, username, displayName, avatarColor, avatarType, avatarPreset, avatarPhotoUrl, coins, currentStreak FROM users'
|
||||
).all() as any[];
|
||||
|
||||
const leaderboard = users.map((user) => {
|
||||
const result = db.prepare(
|
||||
'SELECT COALESCE(SUM(coinsEarned), 0) as points FROM task_completions WHERE userId = ? AND completedAt >= ?'
|
||||
).get(user.id, startDate) as any;
|
||||
|
||||
return {
|
||||
...user,
|
||||
points: result.points,
|
||||
};
|
||||
});
|
||||
|
||||
leaderboard.sort((a, b) => b.points - a.points);
|
||||
res.json(leaderboard);
|
||||
});
|
||||
|
||||
export default router;
|
||||
170
server/src/routes/rewards.ts
Normal file
170
server/src/routes/rewards.ts
Normal file
|
|
@ -0,0 +1,170 @@
|
|||
import { Router, Response } from 'express';
|
||||
import db from '../database';
|
||||
import { AuthRequest, authMiddleware } from '../middleware/auth';
|
||||
import { isNotificationTypeEnabled, sendTelegramMessage } from '../utils/notifications';
|
||||
|
||||
const router = Router();
|
||||
router.use(authMiddleware);
|
||||
|
||||
function ensureAdmin(userId: number | undefined): boolean {
|
||||
if (!userId) return false;
|
||||
const requester = db.prepare('SELECT id, role FROM users WHERE id = ?').get(userId) as any;
|
||||
return !!requester && requester.role === 'admin';
|
||||
}
|
||||
|
||||
router.get('/', (req: AuthRequest, res: Response) => {
|
||||
const rewards = db.prepare(
|
||||
'SELECT id, title, description, costCoins, isActive, isPreset, createdBy, createdAt FROM rewards WHERE isActive = 1 ORDER BY costCoins ASC, id ASC'
|
||||
).all();
|
||||
const mine = db.prepare(
|
||||
`SELECT rr.id, rr.rewardId, rr.userId, rr.costCoins, rr.redeemedAt, rr.status, r.title
|
||||
FROM reward_redemptions rr
|
||||
JOIN rewards r ON rr.rewardId = r.id
|
||||
WHERE rr.userId = ?
|
||||
ORDER BY rr.redeemedAt DESC
|
||||
LIMIT 20`
|
||||
).all(req.userId);
|
||||
res.json({ rewards, mine });
|
||||
});
|
||||
|
||||
router.get('/admin', (req: AuthRequest, res: Response) => {
|
||||
if (!ensureAdmin(req.userId)) return res.status(403).json({ error: 'Admin only' });
|
||||
const rewards = db.prepare(
|
||||
'SELECT id, title, description, costCoins, isActive, isPreset, createdBy, createdAt FROM rewards ORDER BY isActive DESC, costCoins ASC, id ASC'
|
||||
).all();
|
||||
const redemptions = db.prepare(
|
||||
`SELECT rr.id, rr.rewardId, rr.userId, rr.costCoins, rr.redeemedAt, rr.status, r.title, u.displayName
|
||||
FROM reward_redemptions rr
|
||||
JOIN rewards r ON rr.rewardId = r.id
|
||||
JOIN users u ON rr.userId = u.id
|
||||
ORDER BY rr.redeemedAt DESC
|
||||
LIMIT 50`
|
||||
).all();
|
||||
res.json({ rewards, redemptions });
|
||||
});
|
||||
|
||||
router.put('/redemptions/:id', (req: AuthRequest, res: Response) => {
|
||||
if (!ensureAdmin(req.userId)) return res.status(403).json({ error: 'Admin only' });
|
||||
const id = parseInt(req.params.id as string, 10);
|
||||
const { status } = req.body as { status?: 'requested' | 'approved' | 'rejected' | 'cancelled' };
|
||||
if (!status || !['requested', 'approved', 'rejected'].includes(status)) {
|
||||
return res.status(400).json({ error: 'Invalid status' });
|
||||
}
|
||||
const row = db.prepare('SELECT id, userId, costCoins, status FROM reward_redemptions WHERE id = ?').get(id) as any;
|
||||
if (!row) return res.status(404).json({ error: 'Redemption not found' });
|
||||
db.transaction(() => {
|
||||
db.prepare('UPDATE reward_redemptions SET status = ? WHERE id = ?').run(status, id);
|
||||
// Refund coins exactly once when moving from requested -> rejected
|
||||
if (status === 'rejected' && row.status === 'requested') {
|
||||
db.prepare('UPDATE users SET coins = coins + ? WHERE id = ?').run(row.costCoins, row.userId);
|
||||
}
|
||||
})();
|
||||
const updated = db.prepare(
|
||||
`SELECT rr.id, rr.rewardId, rr.userId, rr.costCoins, rr.redeemedAt, rr.status, r.title, u.displayName
|
||||
FROM reward_redemptions rr
|
||||
JOIN rewards r ON rr.rewardId = r.id
|
||||
JOIN users u ON rr.userId = u.id
|
||||
WHERE rr.id = ?`
|
||||
).get(id);
|
||||
res.json(updated);
|
||||
});
|
||||
|
||||
router.post('/redemptions/:id/cancel', (req: AuthRequest, res: Response) => {
|
||||
const id = parseInt(req.params.id as string, 10);
|
||||
const row = db.prepare('SELECT id, userId, costCoins, status FROM reward_redemptions WHERE id = ?').get(id) as any;
|
||||
if (!row) return res.status(404).json({ error: 'Redemption not found' });
|
||||
if (row.userId !== req.userId) return res.status(403).json({ error: 'Forbidden' });
|
||||
if (row.status !== 'requested') return res.status(400).json({ error: 'Only requested rewards can be cancelled' });
|
||||
|
||||
db.transaction(() => {
|
||||
db.prepare("UPDATE reward_redemptions SET status = 'cancelled' WHERE id = ?").run(id);
|
||||
db.prepare('UPDATE users SET coins = coins + ? WHERE id = ?').run(row.costCoins, row.userId);
|
||||
})();
|
||||
|
||||
const updated = db.prepare(
|
||||
`SELECT rr.id, rr.rewardId, rr.userId, rr.costCoins, rr.redeemedAt, rr.status, r.title
|
||||
FROM reward_redemptions rr
|
||||
JOIN rewards r ON rr.rewardId = r.id
|
||||
WHERE rr.id = ?`
|
||||
).get(id);
|
||||
const user = db.prepare('SELECT coins FROM users WHERE id = ?').get(req.userId) as any;
|
||||
res.json({ redemption: updated, coins: user?.coins ?? 0 });
|
||||
});
|
||||
|
||||
router.post('/', (req: AuthRequest, res: Response) => {
|
||||
if (!ensureAdmin(req.userId)) return res.status(403).json({ error: 'Admin only' });
|
||||
const { title, description, costCoins } = req.body as { title?: string; description?: string; costCoins?: number };
|
||||
const cleanTitle = String(title || '').trim();
|
||||
if (!cleanTitle) return res.status(400).json({ error: 'title is required' });
|
||||
const cost = Math.round(Number(costCoins));
|
||||
if (!Number.isFinite(cost) || cost <= 0) return res.status(400).json({ error: 'costCoins must be > 0' });
|
||||
|
||||
const result = db.prepare(
|
||||
'INSERT INTO rewards (title, description, costCoins, isActive, isPreset, createdBy) VALUES (?, ?, ?, 1, 0, ?)'
|
||||
).run(cleanTitle, description?.trim() || null, cost, req.userId);
|
||||
const created = db.prepare(
|
||||
'SELECT id, title, description, costCoins, isActive, isPreset, createdBy, createdAt FROM rewards WHERE id = ?'
|
||||
).get(result.lastInsertRowid);
|
||||
res.status(201).json(created);
|
||||
});
|
||||
|
||||
router.put('/:id', (req: AuthRequest, res: Response) => {
|
||||
if (!ensureAdmin(req.userId)) return res.status(403).json({ error: 'Admin only' });
|
||||
const id = parseInt(req.params.id as string, 10);
|
||||
const reward = db.prepare('SELECT id FROM rewards WHERE id = ?').get(id) as any;
|
||||
if (!reward) return res.status(404).json({ error: 'Reward not found' });
|
||||
|
||||
const { title, description, costCoins, isActive } = req.body as { title?: string; description?: string; costCoins?: number; isActive?: boolean };
|
||||
const cleanTitle = String(title || '').trim();
|
||||
if (!cleanTitle) return res.status(400).json({ error: 'title is required' });
|
||||
const cost = Math.round(Number(costCoins));
|
||||
if (!Number.isFinite(cost) || cost <= 0) return res.status(400).json({ error: 'costCoins must be > 0' });
|
||||
|
||||
db.prepare('UPDATE rewards SET title = ?, description = ?, costCoins = ?, isActive = ? WHERE id = ?')
|
||||
.run(cleanTitle, description?.trim() || null, cost, isActive === false ? 0 : 1, id);
|
||||
|
||||
const updated = db.prepare(
|
||||
'SELECT id, title, description, costCoins, isActive, isPreset, createdBy, createdAt FROM rewards WHERE id = ?'
|
||||
).get(id);
|
||||
res.json(updated);
|
||||
});
|
||||
|
||||
router.delete('/:id', (req: AuthRequest, res: Response) => {
|
||||
if (!ensureAdmin(req.userId)) return res.status(403).json({ error: 'Admin only' });
|
||||
const id = parseInt(req.params.id as string, 10);
|
||||
const reward = db.prepare('SELECT id FROM rewards WHERE id = ?').get(id) as any;
|
||||
if (!reward) return res.status(404).json({ error: 'Reward not found' });
|
||||
db.prepare('DELETE FROM rewards WHERE id = ?').run(id);
|
||||
res.json({ success: true });
|
||||
});
|
||||
|
||||
router.post('/:id/redeem', (req: AuthRequest, res: Response) => {
|
||||
const id = parseInt(req.params.id as string, 10);
|
||||
const reward = db.prepare('SELECT id, title, costCoins, isActive FROM rewards WHERE id = ?').get(id) as any;
|
||||
if (!reward || !reward.isActive) return res.status(404).json({ error: 'Reward not available' });
|
||||
const me = db.prepare('SELECT id, coins, displayName FROM users WHERE id = ?').get(req.userId) as any;
|
||||
if (!me) return res.status(404).json({ error: 'User not found' });
|
||||
if (me.coins < reward.costCoins) return res.status(400).json({ error: 'Not enough coins' });
|
||||
|
||||
const tx = db.transaction(() => {
|
||||
db.prepare('UPDATE users SET coins = coins - ? WHERE id = ?').run(reward.costCoins, req.userId);
|
||||
const redemption = db.prepare(
|
||||
"INSERT INTO reward_redemptions (rewardId, userId, costCoins, status) VALUES (?, ?, ?, 'requested')"
|
||||
).run(id, req.userId, reward.costCoins);
|
||||
return redemption.lastInsertRowid;
|
||||
});
|
||||
const redemptionId = tx();
|
||||
const user = db.prepare('SELECT coins FROM users WHERE id = ?').get(req.userId) as any;
|
||||
const redemption = db.prepare(
|
||||
'SELECT id, rewardId, userId, costCoins, redeemedAt, status FROM reward_redemptions WHERE id = ?'
|
||||
).get(redemptionId);
|
||||
|
||||
if (isNotificationTypeEnabled('rewardRequest')) {
|
||||
void sendTelegramMessage(
|
||||
`🎁 Reward request: ${me.displayName} requested "${reward.title}" (${reward.costCoins} coins).`
|
||||
);
|
||||
}
|
||||
res.json({ redemption, coins: user.coins });
|
||||
});
|
||||
|
||||
export default router;
|
||||
243
server/src/routes/rooms.ts
Normal file
243
server/src/routes/rooms.ts
Normal file
|
|
@ -0,0 +1,243 @@
|
|||
import { Router, Response } from 'express';
|
||||
import db from '../database';
|
||||
import { AuthRequest, authMiddleware } from '../middleware/auth';
|
||||
import { calculateHealth } from '../utils/health';
|
||||
import { suggestTaskIcon } from '../utils/taskIcons';
|
||||
|
||||
const router = Router();
|
||||
|
||||
// Default tasks per room type
|
||||
const DEFAULT_TASKS: Record<string, Array<{ name: string; frequencyDays: number; effort: number; isSeasonal?: boolean; translationKey: string; iconKey?: string }>> = {
|
||||
kitchen: [
|
||||
{ name: 'Wash Dishes', frequencyDays: 1, effort: 2, translationKey: 'kitchen.wash_dishes' },
|
||||
{ name: 'Clean Counters', frequencyDays: 1, effort: 1, translationKey: 'kitchen.clean_counters' },
|
||||
{ name: 'Wipe Stovetop', frequencyDays: 1, effort: 2, translationKey: 'kitchen.wipe_stovetop' },
|
||||
{ name: 'Empty Household Waste', frequencyDays: 2, effort: 1, translationKey: 'kitchen.empty_household_waste' },
|
||||
{ name: 'Empty Compost', frequencyDays: 2, effort: 1, translationKey: 'kitchen.empty_compost' },
|
||||
{ name: 'Empty Plastic Recycling', frequencyDays: 7, effort: 1, translationKey: 'kitchen.empty_plastic_recycling' },
|
||||
{ name: 'Empty Glass Recycling', frequencyDays: 14, effort: 1, translationKey: 'kitchen.empty_glass_recycling' },
|
||||
{ name: 'Clean Sink', frequencyDays: 2, effort: 1, translationKey: 'kitchen.clean_sink' },
|
||||
{ name: 'Clean Kitchen Sink Drain', frequencyDays: 30, effort: 2, translationKey: 'kitchen.clean_sink_drain' },
|
||||
{ name: 'Wipe Appliances', frequencyDays: 7, effort: 2, translationKey: 'kitchen.wipe_appliances' },
|
||||
{ name: 'Mop Floor', frequencyDays: 7, effort: 4, translationKey: 'kitchen.mop_floor' },
|
||||
{ name: 'Clean Microwave', frequencyDays: 7, effort: 2, translationKey: 'kitchen.clean_microwave' },
|
||||
{ name: 'Wipe Cabinet Fronts', frequencyDays: 14, effort: 2, translationKey: 'kitchen.wipe_cabinet_fronts' },
|
||||
{ name: 'Clean Fridge', frequencyDays: 14, effort: 3, translationKey: 'kitchen.clean_fridge' },
|
||||
{ name: 'Defrost Freezer', frequencyDays: 90, effort: 4, translationKey: 'kitchen.defrost_freezer' },
|
||||
{ name: 'Descale Kettle', frequencyDays: 30, effort: 2, translationKey: 'kitchen.descale_kettle' },
|
||||
{ name: 'Clean Dishwasher Filter', frequencyDays: 30, effort: 2, translationKey: 'kitchen.clean_dishwasher_filter' },
|
||||
{ name: 'Check Dishwasher Salt', frequencyDays: 30, effort: 1, translationKey: 'kitchen.check_dishwasher_salt' },
|
||||
{ name: 'Clean Oven', frequencyDays: 30, effort: 5, translationKey: 'kitchen.clean_oven' },
|
||||
{ name: 'Clean Range Hood & Filter', frequencyDays: 90, effort: 4, translationKey: 'kitchen.clean_range_hood' },
|
||||
{ name: 'Deep Clean Fridge', frequencyDays: 90, effort: 5, translationKey: 'kitchen.deep_clean_fridge' },
|
||||
{ name: 'Organize Pantry', frequencyDays: 90, effort: 3, translationKey: 'kitchen.organize_pantry' },
|
||||
],
|
||||
bedroom: [
|
||||
{ name: 'Make Bed', frequencyDays: 1, effort: 1, translationKey: 'bedroom.make_bed' },
|
||||
{ name: 'Tidy Nightstand', frequencyDays: 3, effort: 1, translationKey: 'bedroom.tidy_nightstand' },
|
||||
{ name: 'Change Sheets', frequencyDays: 7, effort: 3, translationKey: 'bedroom.change_sheets' },
|
||||
{ name: 'Vacuum Floor', frequencyDays: 7, effort: 2, translationKey: 'bedroom.vacuum_floor' },
|
||||
{ name: 'Dust Surfaces', frequencyDays: 14, effort: 2, translationKey: 'bedroom.dust_surfaces' },
|
||||
{ name: 'Clean Under Bed', frequencyDays: 30, effort: 3, translationKey: 'bedroom.clean_under_bed' },
|
||||
{ name: 'Wash Pillows', frequencyDays: 90, effort: 3, translationKey: 'bedroom.wash_pillows' },
|
||||
{ name: 'Wash Duvet/Comforter', frequencyDays: 90, effort: 4, translationKey: 'bedroom.wash_duvet' },
|
||||
{ name: 'Change Fitted Sheet', frequencyDays: 14, effort: 2, translationKey: 'bedroom.change_fitted_sheet' },
|
||||
{ name: 'Organize Closet', frequencyDays: 90, effort: 3, translationKey: 'bedroom.organize_closet' },
|
||||
{ name: 'Flip/Rotate Mattress', frequencyDays: 180, effort: 4, translationKey: 'bedroom.flip_mattress' },
|
||||
{ name: 'Clean Windows', frequencyDays: 90, effort: 3, isSeasonal: true, translationKey: 'bedroom.clean_windows' },
|
||||
{ name: 'Wash Curtains', frequencyDays: 180, effort: 3, isSeasonal: true, translationKey: 'bedroom.wash_curtains' },
|
||||
],
|
||||
bathroom: [
|
||||
{ name: 'Wipe Sink & Counter', frequencyDays: 1, effort: 1, translationKey: 'bathroom.wipe_sink_counter' },
|
||||
{ name: 'Squeegee Shower Glass', frequencyDays: 1, effort: 1, translationKey: 'bathroom.squeegee_shower' },
|
||||
{ name: 'Scrub Toilet', frequencyDays: 3, effort: 3, translationKey: 'bathroom.scrub_toilet' },
|
||||
{ name: 'Clean Mirror', frequencyDays: 3, effort: 1, translationKey: 'bathroom.clean_mirror' },
|
||||
{ name: 'Wash Towels', frequencyDays: 7, effort: 2, translationKey: 'bathroom.wash_towels' },
|
||||
{ name: 'Clean Shower/Tub', frequencyDays: 7, effort: 4, translationKey: 'bathroom.clean_shower_tub' },
|
||||
{ name: 'Mop Floor', frequencyDays: 7, effort: 3, translationKey: 'bathroom.mop_floor' },
|
||||
{ name: 'Clean Sink Drain', frequencyDays: 14, effort: 2, translationKey: 'bathroom.clean_sink_drain' },
|
||||
{ name: 'Clean Shower Drain', frequencyDays: 14, effort: 2, translationKey: 'bathroom.clean_shower_drain' },
|
||||
{ name: 'Wash Bath Mat', frequencyDays: 14, effort: 2, translationKey: 'bathroom.wash_bath_mat' },
|
||||
{ name: 'Wipe Light Switches & Door Handles', frequencyDays: 14, effort: 1, translationKey: 'bathroom.wipe_switches_handles' },
|
||||
{ name: 'Clean Grout', frequencyDays: 90, effort: 5, translationKey: 'bathroom.clean_grout' },
|
||||
{ name: 'Descale Showerhead', frequencyDays: 90, effort: 2, translationKey: 'bathroom.descale_showerhead' },
|
||||
{ name: 'Wash Shower Curtain', frequencyDays: 30, effort: 2, translationKey: 'bathroom.wash_shower_curtain' },
|
||||
{ name: 'Organize Cabinets & Drawers', frequencyDays: 90, effort: 3, translationKey: 'bathroom.organize_cabinets' },
|
||||
{ name: 'Replace Toothbrush', frequencyDays: 90, effort: 1, translationKey: 'bathroom.replace_toothbrush' },
|
||||
],
|
||||
living: [
|
||||
{ name: 'Tidy Up / Put Things Away', frequencyDays: 1, effort: 1, translationKey: 'living.tidy_up' },
|
||||
{ name: 'Fluff & Tidy Cushions', frequencyDays: 3, effort: 1, translationKey: 'living.fluff_cushions' },
|
||||
{ name: 'Vacuum Carpet/Floor', frequencyDays: 7, effort: 3, translationKey: 'living.vacuum_carpet' },
|
||||
{ name: 'Dust Surfaces & Shelves', frequencyDays: 7, effort: 2, translationKey: 'living.dust_surfaces_shelves' },
|
||||
{ name: 'Wipe TV Screen', frequencyDays: 14, effort: 1, translationKey: 'living.wipe_tv' },
|
||||
{ name: 'Clean Remote Controls', frequencyDays: 14, effort: 1, translationKey: 'living.clean_remotes' },
|
||||
{ name: 'Dust Lampshades & Light Fixtures', frequencyDays: 30, effort: 2, translationKey: 'living.dust_lampshades' },
|
||||
{ name: 'Vacuum Sofa & Under Cushions', frequencyDays: 30, effort: 3, translationKey: 'living.vacuum_sofa' },
|
||||
{ name: 'Clean Windows', frequencyDays: 90, effort: 4, isSeasonal: true, translationKey: 'living.clean_windows' },
|
||||
{ name: 'Wash Curtains/Blinds', frequencyDays: 180, effort: 4, isSeasonal: true, translationKey: 'living.wash_curtains_blinds' },
|
||||
{ name: 'Deep Clean Carpet/Rug', frequencyDays: 180, effort: 5, translationKey: 'living.deep_clean_carpet' },
|
||||
{ name: 'Clean Behind Furniture', frequencyDays: 90, effort: 4, translationKey: 'living.clean_behind_furniture' },
|
||||
{ name: 'Polish Wood Furniture', frequencyDays: 90, effort: 3, translationKey: 'living.polish_furniture' },
|
||||
],
|
||||
office: [
|
||||
{ name: 'Clear Desk', frequencyDays: 1, effort: 1, translationKey: 'office.clear_desk' },
|
||||
{ name: 'Wipe Desk Surface', frequencyDays: 3, effort: 1, translationKey: 'office.wipe_desk' },
|
||||
{ name: 'Clean Keyboard & Mouse', frequencyDays: 7, effort: 1, translationKey: 'office.clean_keyboard_mouse' },
|
||||
{ name: 'Wipe Monitor', frequencyDays: 7, effort: 1, translationKey: 'office.wipe_monitor' },
|
||||
{ name: 'Empty Paper Trash/Shredder', frequencyDays: 7, effort: 1, translationKey: 'office.empty_paper_trash' },
|
||||
{ name: 'Vacuum Floor', frequencyDays: 7, effort: 2, translationKey: 'office.vacuum_floor' },
|
||||
{ name: 'Organize Cables', frequencyDays: 30, effort: 2, translationKey: 'office.organize_cables' },
|
||||
{ name: 'Dust Shelves & Bookcase', frequencyDays: 14, effort: 2, translationKey: 'office.dust_shelves' },
|
||||
{ name: 'Clean Desk Lamp', frequencyDays: 30, effort: 1, translationKey: 'office.clean_desk_lamp' },
|
||||
{ name: 'Organize Drawers & Filing', frequencyDays: 90, effort: 3, translationKey: 'office.organize_drawers' },
|
||||
{ name: 'Wipe Light Switches & Door Handle', frequencyDays: 14, effort: 1, translationKey: 'office.wipe_switches' },
|
||||
{ name: 'Clean Chair (Fabric/Leather)', frequencyDays: 90, effort: 3, translationKey: 'office.clean_chair' },
|
||||
],
|
||||
garage: [
|
||||
{ name: 'Sweep Floor', frequencyDays: 14, effort: 3, translationKey: 'garage.sweep_floor' },
|
||||
{ name: 'Organize Tools', frequencyDays: 30, effort: 3, translationKey: 'garage.organize_tools' },
|
||||
{ name: 'Clean Workbench', frequencyDays: 14, effort: 2, translationKey: 'garage.clean_workbench' },
|
||||
{ name: 'Clear Cobwebs', frequencyDays: 30, effort: 2, translationKey: 'garage.clear_cobwebs' },
|
||||
{ name: 'Organize Storage Shelves', frequencyDays: 90, effort: 4, translationKey: 'garage.organize_shelves' },
|
||||
{ name: 'Wipe Down Power Tools', frequencyDays: 30, effort: 2, translationKey: 'garage.wipe_power_tools' },
|
||||
{ name: 'Sort Recycling & Waste', frequencyDays: 7, effort: 2, translationKey: 'garage.sort_recycling' },
|
||||
{ name: 'Mop/Hose Floor', frequencyDays: 90, effort: 4, translationKey: 'garage.mop_hose_floor' },
|
||||
{ name: 'Check & Organize Chemicals', frequencyDays: 90, effort: 2, translationKey: 'garage.check_chemicals' },
|
||||
{ name: 'Clean Garage Door Tracks', frequencyDays: 180, effort: 3, translationKey: 'garage.clean_door_tracks' },
|
||||
],
|
||||
laundry: [
|
||||
{ name: 'Wipe Washer Door Seal', frequencyDays: 7, effort: 1, translationKey: 'laundry.wipe_washer_seal' },
|
||||
{ name: 'Clean Lint Filter', frequencyDays: 7, effort: 1, translationKey: 'laundry.clean_lint_filter' },
|
||||
{ name: 'Wipe Machine Exterior', frequencyDays: 14, effort: 2, translationKey: 'laundry.wipe_machine_exterior' },
|
||||
{ name: 'Run Washer Cleaning Cycle', frequencyDays: 30, effort: 2, translationKey: 'laundry.run_cleaning_cycle' },
|
||||
{ name: 'Drain Washing Machine', frequencyDays: 90, effort: 2, translationKey: 'laundry.drain_washing_machine' },
|
||||
{ name: 'Descale Washing Machine', frequencyDays: 60, effort: 2, translationKey: 'laundry.descale_washing_machine' },
|
||||
{ name: 'Clean Detergent Drawer', frequencyDays: 30, effort: 2, translationKey: 'laundry.clean_detergent_drawer' },
|
||||
{ name: 'Sweep/Mop Floor', frequencyDays: 14, effort: 2, translationKey: 'laundry.sweep_mop_floor' },
|
||||
{ name: 'Organize Supplies & Detergents', frequencyDays: 30, effort: 2, translationKey: 'laundry.organize_supplies' },
|
||||
{ name: 'Clean Dryer Vent', frequencyDays: 90, effort: 4, translationKey: 'laundry.clean_dryer_vent' },
|
||||
{ name: 'Wipe Folding Surface', frequencyDays: 7, effort: 1, translationKey: 'laundry.wipe_folding_surface' },
|
||||
{ name: 'Sort & Donate Old Clothes', frequencyDays: 180, effort: 3, translationKey: 'laundry.sort_donate_clothes' },
|
||||
],
|
||||
};
|
||||
|
||||
router.use(authMiddleware);
|
||||
|
||||
function ensureAdmin(userId: number | undefined): boolean {
|
||||
if (!userId) return false;
|
||||
const user = db.prepare('SELECT role FROM users WHERE id = ?').get(userId) as { role: string } | undefined;
|
||||
return user?.role === 'admin';
|
||||
}
|
||||
|
||||
// List all rooms with computed health
|
||||
router.get('/', (req: AuthRequest, res: Response) => {
|
||||
const rooms = db.prepare('SELECT * FROM rooms ORDER BY sortOrder, id').all() as any[];
|
||||
const user = db.prepare('SELECT isVacationMode, vacationStartDate FROM users WHERE id = ?').get(req.userId) as any;
|
||||
|
||||
const roomsWithHealth = rooms.map((room) => {
|
||||
const tasks = db.prepare('SELECT * FROM tasks WHERE roomId = ?').all(room.id) as any[];
|
||||
const tasksWithHealth = tasks.map((t) => ({
|
||||
...t,
|
||||
isSeasonal: !!t.isSeasonal,
|
||||
health: calculateHealth(t.lastCompletedAt, t.frequencyDays, !!user.isVacationMode, user.vacationStartDate),
|
||||
}));
|
||||
|
||||
const nonSeasonal = tasksWithHealth.filter((t) => !t.isSeasonal);
|
||||
const forAvg = nonSeasonal.length > 0 ? nonSeasonal : tasksWithHealth;
|
||||
const totalEffort = forAvg.reduce((s, t) => s + t.effort, 0);
|
||||
const health = totalEffort > 0
|
||||
? Math.round(forAvg.reduce((s, t) => s + t.health * t.effort, 0) / totalEffort)
|
||||
: 100;
|
||||
|
||||
return { ...room, tasks: tasksWithHealth, health };
|
||||
});
|
||||
|
||||
res.json(roomsWithHealth);
|
||||
});
|
||||
|
||||
// Get default tasks for a room type
|
||||
router.get('/defaults/:roomType', authMiddleware, (_req: AuthRequest, res: Response) => {
|
||||
const type = _req.params.roomType as string;
|
||||
const defaults = (DEFAULT_TASKS[type] || []).map((t) => ({
|
||||
...t,
|
||||
iconKey: t.iconKey || suggestTaskIcon(t.name, t.translationKey),
|
||||
}));
|
||||
res.json(defaults);
|
||||
});
|
||||
|
||||
// Create room (with user-selected tasks)
|
||||
router.post('/', (req: AuthRequest, res: Response) => {
|
||||
if (!ensureAdmin(req.userId)) {
|
||||
return res.status(403).json({ error: 'Admin only' });
|
||||
}
|
||||
|
||||
const { name, roomType, color, accentColor, tasks: customTasks } = req.body;
|
||||
if (!name) return res.status(400).json({ error: 'name is required' });
|
||||
|
||||
const type = roomType || 'other';
|
||||
const result = db.prepare(
|
||||
'INSERT INTO rooms (name, roomType, color, accentColor) VALUES (?, ?, ?, ?)'
|
||||
).run(name, type, color || '#FFE4CC', accentColor || '#F97316');
|
||||
|
||||
const roomId = result.lastInsertRowid;
|
||||
|
||||
// Insert user-selected tasks, or fall back to defaults
|
||||
const tasksToInsert = customTasks && customTasks.length > 0
|
||||
? customTasks
|
||||
: DEFAULT_TASKS[type] || [];
|
||||
|
||||
const insert = db.prepare(
|
||||
'INSERT INTO tasks (roomId, name, frequencyDays, effort, isSeasonal, lastCompletedAt, translationKey, iconKey) VALUES (?, ?, ?, ?, ?, ?, ?, ?)'
|
||||
);
|
||||
for (const task of tasksToInsert) {
|
||||
// If initialHealth is provided, compute a fake lastCompletedAt to represent current state
|
||||
let lastCompletedAt: string | null = null;
|
||||
if (task.initialHealth !== undefined && task.initialHealth < 100) {
|
||||
const daysSince = ((100 - task.initialHealth) / 100) * (task.frequencyDays || 7);
|
||||
const d = new Date(Date.now() - daysSince * 86400000);
|
||||
lastCompletedAt = d.toISOString();
|
||||
} else if (task.initialHealth === 100) {
|
||||
lastCompletedAt = new Date().toISOString();
|
||||
}
|
||||
const iconKey = task.iconKey || suggestTaskIcon(task.name, task.translationKey || null);
|
||||
insert.run(roomId, task.name, task.frequencyDays || 7, task.effort || 1, task.isSeasonal ? 1 : 0, lastCompletedAt, task.translationKey || null, iconKey);
|
||||
}
|
||||
|
||||
const room = db.prepare('SELECT * FROM rooms WHERE id = ?').get(roomId) as any;
|
||||
const allTasks = db.prepare('SELECT * FROM tasks WHERE roomId = ?').all(roomId);
|
||||
res.status(201).json({ ...room, tasks: allTasks });
|
||||
});
|
||||
|
||||
// Update room
|
||||
router.put('/:id', (req: AuthRequest, res: Response) => {
|
||||
if (!ensureAdmin(req.userId)) {
|
||||
return res.status(403).json({ error: 'Admin only' });
|
||||
}
|
||||
|
||||
const { name, roomType, color, accentColor, sortOrder } = req.body;
|
||||
const room = db.prepare('SELECT * FROM rooms WHERE id = ?').get(req.params.id);
|
||||
if (!room) return res.status(404).json({ error: 'Room not found' });
|
||||
|
||||
db.prepare(
|
||||
'UPDATE rooms SET name = COALESCE(?, name), roomType = COALESCE(?, roomType), color = COALESCE(?, color), accentColor = COALESCE(?, accentColor), sortOrder = COALESCE(?, sortOrder) WHERE id = ?'
|
||||
).run(name, roomType, color, accentColor, sortOrder, req.params.id);
|
||||
|
||||
const updated = db.prepare('SELECT * FROM rooms WHERE id = ?').get(req.params.id);
|
||||
res.json(updated);
|
||||
});
|
||||
|
||||
// Delete room (cascades to tasks)
|
||||
router.delete('/:id', (req: AuthRequest, res: Response) => {
|
||||
if (!ensureAdmin(req.userId)) {
|
||||
return res.status(403).json({ error: 'Admin only' });
|
||||
}
|
||||
|
||||
const room = db.prepare('SELECT * FROM rooms WHERE id = ?').get(req.params.id);
|
||||
if (!room) return res.status(404).json({ error: 'Room not found' });
|
||||
|
||||
db.prepare('DELETE FROM rooms WHERE id = ?').run(req.params.id);
|
||||
res.json({ success: true });
|
||||
});
|
||||
|
||||
export default router;
|
||||
193
server/src/routes/tasks.ts
Normal file
193
server/src/routes/tasks.ts
Normal file
|
|
@ -0,0 +1,193 @@
|
|||
import { Router, Response } from 'express';
|
||||
import db from '../database';
|
||||
import { AuthRequest, authMiddleware } from '../middleware/auth';
|
||||
import { calculateHealth, getCoinsForEffort, DEFAULT_COINS_BY_EFFORT, normalizeCoinsByEffortConfig } from '../utils/health';
|
||||
import { suggestTaskIcon } from '../utils/taskIcons';
|
||||
import { notifyAchievementUnlocksForUser } from '../utils/achievementNotifications';
|
||||
|
||||
const router = Router();
|
||||
router.use(authMiddleware);
|
||||
|
||||
function ensureAdmin(userId: number | undefined): boolean {
|
||||
if (!userId) return false;
|
||||
const user = db.prepare('SELECT role FROM users WHERE id = ?').get(userId) as { role: string } | undefined;
|
||||
return user?.role === 'admin';
|
||||
}
|
||||
|
||||
function getCoinsByEffortConfig(): Record<number, number> {
|
||||
const row = db.prepare("SELECT value FROM app_settings WHERE key = 'coinsByEffort'").get() as { value?: string } | undefined;
|
||||
if (!row?.value) return DEFAULT_COINS_BY_EFFORT;
|
||||
try {
|
||||
return normalizeCoinsByEffortConfig(JSON.parse(row.value));
|
||||
} catch {
|
||||
return DEFAULT_COINS_BY_EFFORT;
|
||||
}
|
||||
}
|
||||
|
||||
function hadDueTaskOnDate(dateIsoDay: string, user: any): boolean {
|
||||
const endOfDay = new Date(`${dateIsoDay}T23:59:59.999Z`).getTime();
|
||||
const tasks = db.prepare('SELECT id, frequencyDays, isSeasonal, lastCompletedAt FROM tasks').all() as Array<{
|
||||
id: number; frequencyDays: number; isSeasonal: number; lastCompletedAt: string | null;
|
||||
}>;
|
||||
|
||||
for (const t of tasks) {
|
||||
if (t.isSeasonal) continue;
|
||||
const safeFreq = Math.max(1 / 24, Number(t.frequencyDays) || 7);
|
||||
let dueTs: number;
|
||||
if (!t.lastCompletedAt) {
|
||||
dueTs = 0;
|
||||
} else {
|
||||
dueTs = new Date(t.lastCompletedAt).getTime() + safeFreq * 86400000;
|
||||
}
|
||||
if (dueTs <= endOfDay) {
|
||||
const health = calculateHealth(t.lastCompletedAt, safeFreq, !!user.isVacationMode, user.vacationStartDate);
|
||||
if (health < 100) return true;
|
||||
}
|
||||
}
|
||||
return false;
|
||||
}
|
||||
|
||||
// List tasks for a room
|
||||
router.get('/rooms/:roomId/tasks', (req: AuthRequest, res: Response) => {
|
||||
const user = db.prepare('SELECT isVacationMode, vacationStartDate FROM users WHERE id = ?').get(req.userId) as any;
|
||||
const tasks = db.prepare('SELECT * FROM tasks WHERE roomId = ?').all(req.params.roomId) as any[];
|
||||
|
||||
const tasksWithHealth = tasks.map((t) => ({
|
||||
...t,
|
||||
isSeasonal: !!t.isSeasonal,
|
||||
health: calculateHealth(t.lastCompletedAt, t.frequencyDays, !!user.isVacationMode, user.vacationStartDate),
|
||||
}));
|
||||
|
||||
res.json(tasksWithHealth);
|
||||
});
|
||||
|
||||
// Create task
|
||||
router.post('/rooms/:roomId/tasks', (req: AuthRequest, res: Response) => {
|
||||
if (!ensureAdmin(req.userId)) {
|
||||
return res.status(403).json({ error: 'Admin only' });
|
||||
}
|
||||
|
||||
const { name, notes, frequencyDays, effort, isSeasonal, health, iconKey } = req.body;
|
||||
if (!name) return res.status(400).json({ error: 'name is required' });
|
||||
|
||||
const room = db.prepare('SELECT id FROM rooms WHERE id = ?').get(req.params.roomId);
|
||||
if (!room) return res.status(404).json({ error: 'Room not found' });
|
||||
|
||||
const effectiveFrequency = Math.max(1 / 24, Number(frequencyDays) || 7);
|
||||
let lastCompletedAt: string | null = null;
|
||||
if (health !== undefined && health !== null) {
|
||||
const targetHealth = Math.max(0, Math.min(100, Math.round(Number(health))));
|
||||
if (targetHealth >= 100) {
|
||||
lastCompletedAt = new Date().toISOString();
|
||||
} else {
|
||||
const daysSince = ((100 - targetHealth) / 100) * effectiveFrequency;
|
||||
lastCompletedAt = new Date(Date.now() - daysSince * 86400000).toISOString();
|
||||
}
|
||||
}
|
||||
|
||||
const result = db.prepare(
|
||||
'INSERT INTO tasks (roomId, name, notes, frequencyDays, effort, isSeasonal, lastCompletedAt, iconKey) VALUES (?, ?, ?, ?, ?, ?, ?, ?)'
|
||||
).run(req.params.roomId, name, notes || null, frequencyDays || 7, effort || 1, isSeasonal ? 1 : 0, lastCompletedAt, iconKey || suggestTaskIcon(name, null));
|
||||
|
||||
const task = db.prepare('SELECT * FROM tasks WHERE id = ?').get(result.lastInsertRowid);
|
||||
res.status(201).json(task);
|
||||
});
|
||||
|
||||
// Update task
|
||||
router.put('/tasks/:id', (req: AuthRequest, res: Response) => {
|
||||
if (!ensureAdmin(req.userId)) {
|
||||
return res.status(403).json({ error: 'Admin only' });
|
||||
}
|
||||
|
||||
const { name, notes, frequencyDays, effort, isSeasonal, health, iconKey } = req.body;
|
||||
const task = db.prepare('SELECT * FROM tasks WHERE id = ?').get(req.params.id) as any;
|
||||
if (!task) return res.status(404).json({ error: 'Task not found' });
|
||||
|
||||
let lastCompletedAt: string | undefined;
|
||||
if (health !== undefined && health !== null) {
|
||||
const targetHealth = Math.max(0, Math.min(100, Math.round(Number(health))));
|
||||
if (targetHealth >= 100) {
|
||||
lastCompletedAt = new Date().toISOString();
|
||||
} else {
|
||||
const effectiveFrequency = Math.max(1 / 24, Number(frequencyDays ?? task.frequencyDays) || 7);
|
||||
const daysSince = ((100 - targetHealth) / 100) * effectiveFrequency;
|
||||
lastCompletedAt = new Date(Date.now() - daysSince * 86400000).toISOString();
|
||||
}
|
||||
}
|
||||
|
||||
db.prepare(
|
||||
'UPDATE tasks SET name = COALESCE(?, name), notes = COALESCE(?, notes), frequencyDays = COALESCE(?, frequencyDays), effort = COALESCE(?, effort), isSeasonal = COALESCE(?, isSeasonal), lastCompletedAt = COALESCE(?, lastCompletedAt), iconKey = COALESCE(?, iconKey) WHERE id = ?'
|
||||
).run(name, notes, frequencyDays, effort, isSeasonal !== undefined ? (isSeasonal ? 1 : 0) : undefined, lastCompletedAt, iconKey, req.params.id);
|
||||
|
||||
const updated = db.prepare('SELECT * FROM tasks WHERE id = ?').get(req.params.id);
|
||||
res.json(updated);
|
||||
});
|
||||
|
||||
// Delete task
|
||||
router.delete('/tasks/:id', (req: AuthRequest, res: Response) => {
|
||||
if (!ensureAdmin(req.userId)) {
|
||||
return res.status(403).json({ error: 'Admin only' });
|
||||
}
|
||||
|
||||
const task = db.prepare('SELECT * FROM tasks WHERE id = ?').get(req.params.id);
|
||||
if (!task) return res.status(404).json({ error: 'Task not found' });
|
||||
|
||||
db.prepare('DELETE FROM tasks WHERE id = ?').run(req.params.id);
|
||||
res.json({ success: true });
|
||||
});
|
||||
|
||||
// Complete task
|
||||
router.post('/tasks/:id/complete', (req: AuthRequest, res: Response) => {
|
||||
const { completedAt } = req.body;
|
||||
const task = db.prepare('SELECT * FROM tasks WHERE id = ?').get(req.params.id) as any;
|
||||
if (!task) return res.status(404).json({ error: 'Task not found' });
|
||||
|
||||
const now = completedAt || new Date().toISOString();
|
||||
const coins = getCoinsForEffort(task.effort, getCoinsByEffortConfig());
|
||||
|
||||
// Update task lastCompletedAt
|
||||
db.prepare('UPDATE tasks SET lastCompletedAt = ? WHERE id = ?').run(now, req.params.id);
|
||||
|
||||
// Record completion
|
||||
db.prepare(
|
||||
'INSERT INTO task_completions (taskId, userId, completedAt, coinsEarned) VALUES (?, ?, ?, ?)'
|
||||
).run(task.id, req.userId, now, coins);
|
||||
|
||||
// Update user coins
|
||||
db.prepare('UPDATE users SET coins = coins + ? WHERE id = ?').run(coins, req.userId);
|
||||
|
||||
// Update streak
|
||||
const user = db.prepare('SELECT * FROM users WHERE id = ?').get(req.userId) as any;
|
||||
const today = new Date().toISOString().slice(0, 10);
|
||||
|
||||
if (user.lastActiveDate !== today) {
|
||||
const yesterday = new Date(Date.now() - 86400000).toISOString().slice(0, 10);
|
||||
let keepGapWithoutPenalty = false;
|
||||
if (user.lastActiveDate && user.lastActiveDate < yesterday) {
|
||||
keepGapWithoutPenalty = true;
|
||||
const start = new Date(`${user.lastActiveDate}T00:00:00.000Z`);
|
||||
const end = new Date(`${yesterday}T00:00:00.000Z`);
|
||||
for (let d = new Date(start.getTime() + 86400000); d <= end; d = new Date(d.getTime() + 86400000)) {
|
||||
const day = d.toISOString().slice(0, 10);
|
||||
if (hadDueTaskOnDate(day, user)) {
|
||||
keepGapWithoutPenalty = false;
|
||||
break;
|
||||
}
|
||||
}
|
||||
}
|
||||
const newStreak = user.lastActiveDate === yesterday
|
||||
? user.currentStreak + 1
|
||||
: keepGapWithoutPenalty
|
||||
? user.currentStreak + 1
|
||||
: 1;
|
||||
db.prepare('UPDATE users SET currentStreak = ?, lastActiveDate = ? WHERE id = ?')
|
||||
.run(newStreak, today, req.userId);
|
||||
}
|
||||
|
||||
// Fire-and-forget achievement unlock notifications.
|
||||
void notifyAchievementUnlocksForUser(req.userId!);
|
||||
|
||||
res.json({ coinsEarned: coins, health: 100 });
|
||||
});
|
||||
|
||||
export default router;
|
||||
557
server/src/routes/users.ts
Normal file
557
server/src/routes/users.ts
Normal file
|
|
@ -0,0 +1,557 @@
|
|||
import { Router, Response } from 'express';
|
||||
import multer from 'multer';
|
||||
import path from 'path';
|
||||
import fs from 'fs';
|
||||
import bcrypt from 'bcryptjs';
|
||||
import db from '../database';
|
||||
import { AuthRequest, authMiddleware } from '../middleware/auth';
|
||||
import { DEFAULT_COINS_BY_EFFORT, normalizeCoinsByEffortConfig } from '../utils/health';
|
||||
import { NotificationTypeSettings, sendTelegramMessageDetailed } from '../utils/notifications';
|
||||
|
||||
const router = Router();
|
||||
router.use(authMiddleware);
|
||||
|
||||
const USER_SELECT = 'id, username, displayName, role, avatarColor, avatarType, avatarPreset, avatarPhotoUrl, coins, currentStreak, goalCoins, goalStartAt, goalEndAt, isVacationMode, language, createdAt';
|
||||
|
||||
function normalizeNotificationTime(value: string | undefined): string | null {
|
||||
if (value === undefined) return null;
|
||||
const trimmed = String(value).trim();
|
||||
return /^([01]\d|2[0-3]):([0-5]\d)$/.test(trimmed) ? trimmed : null;
|
||||
}
|
||||
|
||||
function normalizeNotificationTypes(value: unknown): NotificationTypeSettings | null {
|
||||
if (value === undefined) return null;
|
||||
if (!value || typeof value !== 'object') return null;
|
||||
const raw = value as Record<string, unknown>;
|
||||
const toBool = (v: unknown, fallback: boolean) => typeof v === 'boolean' ? v : fallback;
|
||||
return {
|
||||
taskDue: toBool(raw.taskDue, true),
|
||||
rewardRequest: toBool(raw.rewardRequest, true),
|
||||
achievementUnlocked: toBool(raw.achievementUnlocked, true),
|
||||
};
|
||||
}
|
||||
|
||||
function readNotificationTypesSetting(): NotificationTypeSettings {
|
||||
const rawTypes = (db.prepare("SELECT value FROM app_settings WHERE key = 'telegramNotificationTypes'").get() as any)?.value || '';
|
||||
if (!rawTypes) return { taskDue: true, rewardRequest: true, achievementUnlocked: true };
|
||||
try {
|
||||
return normalizeNotificationTypes(JSON.parse(rawTypes)) || { taskDue: true, rewardRequest: true, achievementUnlocked: true };
|
||||
} catch {
|
||||
return { taskDue: true, rewardRequest: true, achievementUnlocked: true };
|
||||
}
|
||||
}
|
||||
|
||||
function ensureAdmin(userId: number | undefined): boolean {
|
||||
if (!userId) return false;
|
||||
const requester = db.prepare('SELECT id, role FROM users WHERE id = ?').get(userId) as any;
|
||||
return !!requester && requester.role === 'admin';
|
||||
}
|
||||
|
||||
function syncPrimaryGoal(userId: number) {
|
||||
const nowIso = new Date().toISOString();
|
||||
const primary = db.prepare(
|
||||
`SELECT goalCoins, startAt, endAt
|
||||
FROM user_goals
|
||||
WHERE userId = ?
|
||||
ORDER BY
|
||||
CASE
|
||||
WHEN (startAt IS NULL OR startAt <= ?) AND (endAt IS NULL OR endAt >= ?) THEN 0
|
||||
ELSE 1
|
||||
END,
|
||||
COALESCE(startAt, createdAt) ASC,
|
||||
id DESC
|
||||
LIMIT 1`
|
||||
).get(userId, nowIso, nowIso) as { goalCoins: number; startAt: string | null; endAt: string | null } | undefined;
|
||||
|
||||
if (!primary) {
|
||||
db.prepare('UPDATE users SET goalCoins = NULL, goalStartAt = NULL, goalEndAt = NULL WHERE id = ?').run(userId);
|
||||
return;
|
||||
}
|
||||
|
||||
db.prepare('UPDATE users SET goalCoins = ?, goalStartAt = ?, goalEndAt = ? WHERE id = ?')
|
||||
.run(primary.goalCoins, primary.startAt || null, primary.endAt || null, userId);
|
||||
}
|
||||
|
||||
function getCoinsByEffortConfig(): Record<number, number> {
|
||||
const row = db.prepare("SELECT value FROM app_settings WHERE key = 'coinsByEffort'").get() as { value?: string } | undefined;
|
||||
if (!row?.value) return DEFAULT_COINS_BY_EFFORT;
|
||||
try {
|
||||
return normalizeCoinsByEffortConfig(JSON.parse(row.value));
|
||||
} catch {
|
||||
return DEFAULT_COINS_BY_EFFORT;
|
||||
}
|
||||
}
|
||||
|
||||
// Setup multer for avatar uploads
|
||||
const avatarsDir = path.join(__dirname, '..', '..', '..', 'data', 'avatars');
|
||||
if (!fs.existsSync(avatarsDir)) {
|
||||
fs.mkdirSync(avatarsDir, { recursive: true });
|
||||
}
|
||||
|
||||
const storage = multer.diskStorage({
|
||||
destination: (_req, _file, cb) => cb(null, avatarsDir),
|
||||
filename: (req, _file, cb) => {
|
||||
const ext = path.extname(_file.originalname) || '.jpg';
|
||||
const targetId = parseInt((req as any).params?.id as string, 10);
|
||||
const safeId = Number.isFinite(targetId) ? targetId : (req as AuthRequest).userId;
|
||||
cb(null, `user-${safeId}-${Date.now()}${ext}`);
|
||||
},
|
||||
});
|
||||
|
||||
const upload = multer({
|
||||
storage,
|
||||
limits: { fileSize: 2 * 1024 * 1024 }, // 2MB
|
||||
fileFilter: (_req, file, cb) => {
|
||||
if (file.mimetype.startsWith('image/')) {
|
||||
cb(null, true);
|
||||
} else {
|
||||
cb(new Error('Only image files are allowed'));
|
||||
}
|
||||
},
|
||||
});
|
||||
|
||||
// List all users (family)
|
||||
router.get('/', (req: AuthRequest, res: Response) => {
|
||||
const users = db.prepare(`SELECT ${USER_SELECT} FROM users`).all();
|
||||
res.json(users);
|
||||
});
|
||||
|
||||
router.get('/coins-config', (_req: AuthRequest, res: Response) => {
|
||||
res.json({ coinsByEffort: getCoinsByEffortConfig() });
|
||||
});
|
||||
|
||||
router.put('/coins-config', (req: AuthRequest, res: Response) => {
|
||||
const requester = db.prepare('SELECT id, role FROM users WHERE id = ?').get(req.userId) as any;
|
||||
if (!requester || requester.role !== 'admin') {
|
||||
return res.status(403).json({ error: 'Admin only' });
|
||||
}
|
||||
|
||||
const { coinsByEffort, useDefault } = req.body as { coinsByEffort?: Record<string, number>; useDefault?: boolean };
|
||||
const next = useDefault ? DEFAULT_COINS_BY_EFFORT : normalizeCoinsByEffortConfig(coinsByEffort || {});
|
||||
db.prepare("UPDATE app_settings SET value = ?, updatedAt = datetime('now') WHERE key = 'coinsByEffort'")
|
||||
.run(JSON.stringify(next));
|
||||
res.json({ coinsByEffort: next });
|
||||
});
|
||||
|
||||
// Create member (admin only)
|
||||
router.post('/', (req: AuthRequest, res: Response) => {
|
||||
const requester = db.prepare('SELECT id, role FROM users WHERE id = ?').get(req.userId) as any;
|
||||
if (!requester || requester.role !== 'admin') {
|
||||
return res.status(403).json({ error: 'Admin only' });
|
||||
}
|
||||
|
||||
const { username, password, displayName, avatarColor, language, role } = req.body as any;
|
||||
if (!username || !password || !displayName) {
|
||||
return res.status(400).json({ error: 'username, password, and displayName are required' });
|
||||
}
|
||||
|
||||
const existing = db.prepare('SELECT id FROM users WHERE username = ?').get(username);
|
||||
if (existing) {
|
||||
return res.status(409).json({ error: 'Username already taken' });
|
||||
}
|
||||
|
||||
const safeRole = role === 'admin' ? 'admin' : role === 'child' ? 'child' : 'member';
|
||||
const passwordHash = bcrypt.hashSync(password, 10);
|
||||
const result = db.prepare(
|
||||
'INSERT INTO users (username, displayName, passwordHash, role, avatarColor, language) VALUES (?, ?, ?, ?, ?, ?)'
|
||||
).run(
|
||||
username,
|
||||
displayName,
|
||||
passwordHash,
|
||||
safeRole,
|
||||
avatarColor || '#F97316',
|
||||
language || 'en',
|
||||
);
|
||||
|
||||
const created = db.prepare(`SELECT ${USER_SELECT} FROM users WHERE id = ?`).get(result.lastInsertRowid);
|
||||
res.status(201).json(created);
|
||||
});
|
||||
|
||||
// Update user profile (display name, avatar, language)
|
||||
router.put('/:id/profile', (req: AuthRequest, res: Response) => {
|
||||
const userId = parseInt(req.params.id as string);
|
||||
const requester = db.prepare('SELECT id, role FROM users WHERE id = ?').get(req.userId) as any;
|
||||
const target = db.prepare('SELECT id, role FROM users WHERE id = ?').get(userId) as any;
|
||||
if (!target) return res.status(404).json({ error: 'User not found' });
|
||||
|
||||
const isSelf = userId === req.userId;
|
||||
const canAdminEditOther = requester?.role === 'admin' && userId !== req.userId;
|
||||
if (!isSelf && !canAdminEditOther) {
|
||||
return res.status(403).json({ error: 'Cannot modify another user' });
|
||||
}
|
||||
|
||||
const { displayName, avatarType, avatarColor, avatarPreset, language } = req.body;
|
||||
|
||||
const updates: string[] = [];
|
||||
const values: any[] = [];
|
||||
|
||||
if (displayName !== undefined) { updates.push('displayName = ?'); values.push(displayName); }
|
||||
if (avatarType !== undefined) { updates.push('avatarType = ?'); values.push(avatarType); }
|
||||
if (avatarColor !== undefined) { updates.push('avatarColor = ?'); values.push(avatarColor); }
|
||||
if (avatarPreset !== undefined) { updates.push('avatarPreset = ?'); values.push(avatarPreset); }
|
||||
if (language !== undefined) { updates.push('language = ?'); values.push(language); }
|
||||
|
||||
if (updates.length > 0) {
|
||||
values.push(userId);
|
||||
db.prepare(`UPDATE users SET ${updates.join(', ')} WHERE id = ?`).run(...values);
|
||||
}
|
||||
|
||||
const updated = db.prepare(`SELECT ${USER_SELECT} FROM users WHERE id = ?`).get(userId);
|
||||
res.json(updated);
|
||||
});
|
||||
|
||||
// Upload avatar photo
|
||||
router.post('/:id/avatar-upload', upload.single('avatar'), (req: AuthRequest, res: Response) => {
|
||||
const userId = parseInt(req.params.id as string);
|
||||
const requester = db.prepare('SELECT id, role FROM users WHERE id = ?').get(req.userId) as any;
|
||||
const target = db.prepare('SELECT id, role FROM users WHERE id = ?').get(userId) as any;
|
||||
if (!target) return res.status(404).json({ error: 'User not found' });
|
||||
const isSelf = userId === req.userId;
|
||||
const canAdminEditOther = requester?.role === 'admin' && userId !== req.userId;
|
||||
if (!isSelf && !canAdminEditOther) {
|
||||
return res.status(403).json({ error: 'Cannot modify another user' });
|
||||
}
|
||||
|
||||
if (!req.file) {
|
||||
return res.status(400).json({ error: 'No file uploaded' });
|
||||
}
|
||||
|
||||
const photoUrl = `/api/avatars/${req.file.filename}`;
|
||||
db.prepare('UPDATE users SET avatarType = ?, avatarPhotoUrl = ? WHERE id = ?')
|
||||
.run('photo', photoUrl, userId);
|
||||
|
||||
const updated = db.prepare(`SELECT ${USER_SELECT} FROM users WHERE id = ?`).get(userId);
|
||||
res.json(updated);
|
||||
});
|
||||
|
||||
router.put('/:id/password', (req: AuthRequest, res: Response) => {
|
||||
const userId = parseInt(req.params.id as string);
|
||||
const { currentPassword, newPassword } = req.body as { currentPassword?: string; newPassword?: string };
|
||||
|
||||
if (!newPassword || newPassword.length < 4) {
|
||||
return res.status(400).json({ error: 'newPassword must be at least 4 characters' });
|
||||
}
|
||||
|
||||
const requester = db.prepare('SELECT id, role FROM users WHERE id = ?').get(req.userId) as any;
|
||||
const target = db.prepare('SELECT id, role, passwordHash FROM users WHERE id = ?').get(userId) as any;
|
||||
if (!target) return res.status(404).json({ error: 'User not found' });
|
||||
|
||||
const isSelf = userId === req.userId;
|
||||
const canAdminEditOther = requester?.role === 'admin' && userId !== req.userId;
|
||||
if (!isSelf && !canAdminEditOther) {
|
||||
return res.status(403).json({ error: 'Cannot modify another user password' });
|
||||
}
|
||||
|
||||
if (isSelf) {
|
||||
if (!currentPassword) {
|
||||
return res.status(400).json({ error: 'currentPassword is required' });
|
||||
}
|
||||
if (!bcrypt.compareSync(currentPassword, target.passwordHash)) {
|
||||
return res.status(401).json({ error: 'Current password is incorrect' });
|
||||
}
|
||||
}
|
||||
|
||||
const hash = bcrypt.hashSync(newPassword, 10);
|
||||
db.prepare('UPDATE users SET passwordHash = ? WHERE id = ?').run(hash, userId);
|
||||
res.json({ success: true });
|
||||
});
|
||||
|
||||
// Update user settings
|
||||
router.put('/:id/settings', (req: AuthRequest, res: Response) => {
|
||||
const { language, isVacationMode } = req.body;
|
||||
const userId = parseInt(req.params.id as string);
|
||||
|
||||
if (userId !== req.userId) {
|
||||
return res.status(403).json({ error: 'Cannot modify another user' });
|
||||
}
|
||||
|
||||
const user = db.prepare('SELECT * FROM users WHERE id = ?').get(userId) as any;
|
||||
if (!user) return res.status(404).json({ error: 'User not found' });
|
||||
|
||||
if (user.role !== 'admin') {
|
||||
return res.status(403).json({ error: 'Admin only' });
|
||||
}
|
||||
|
||||
// Handle vacation mode toggle
|
||||
if (isVacationMode !== undefined) {
|
||||
if (isVacationMode && !user.isVacationMode) {
|
||||
db.prepare('UPDATE users SET isVacationMode = 1, vacationStartDate = ? WHERE id = ?')
|
||||
.run(new Date().toISOString(), userId);
|
||||
} else if (!isVacationMode && user.isVacationMode) {
|
||||
db.prepare('UPDATE users SET isVacationMode = 0, vacationStartDate = NULL WHERE id = ?')
|
||||
.run(userId);
|
||||
}
|
||||
}
|
||||
|
||||
if (language) {
|
||||
db.prepare('UPDATE users SET language = ? WHERE id = ?').run(language, userId);
|
||||
}
|
||||
|
||||
const updated = db.prepare(`SELECT ${USER_SELECT} FROM users WHERE id = ?`).get(userId);
|
||||
res.json(updated);
|
||||
});
|
||||
|
||||
router.put('/:id/role', (req: AuthRequest, res: Response) => {
|
||||
const targetId = parseInt(req.params.id as string);
|
||||
const { role } = req.body as { role?: 'admin' | 'member' | 'child' };
|
||||
|
||||
if (!role || !['admin', 'member', 'child'].includes(role)) {
|
||||
return res.status(400).json({ error: 'role must be admin, member or child' });
|
||||
}
|
||||
|
||||
const requester = db.prepare('SELECT id, role FROM users WHERE id = ?').get(req.userId) as any;
|
||||
if (!requester || requester.role !== 'admin') {
|
||||
return res.status(403).json({ error: 'Admin only' });
|
||||
}
|
||||
|
||||
const target = db.prepare('SELECT id, role FROM users WHERE id = ?').get(targetId) as any;
|
||||
if (!target) return res.status(404).json({ error: 'User not found' });
|
||||
|
||||
if (target.role === 'admin' && role !== 'admin') {
|
||||
const adminCount = db.prepare("SELECT COUNT(*) as count FROM users WHERE role = 'admin'").get() as { count: number };
|
||||
if (adminCount.count <= 1) {
|
||||
return res.status(400).json({ error: 'At least one admin is required' });
|
||||
}
|
||||
}
|
||||
|
||||
db.prepare('UPDATE users SET role = ? WHERE id = ?').run(role, targetId);
|
||||
const updated = db.prepare(`SELECT ${USER_SELECT} FROM users WHERE id = ?`).get(targetId);
|
||||
res.json(updated);
|
||||
});
|
||||
|
||||
router.put('/:id/goal', (req: AuthRequest, res: Response) => {
|
||||
const targetId = parseInt(req.params.id as string);
|
||||
const { goalCoins, goalStartAt, goalEndAt } = req.body as { goalCoins?: number | null; goalStartAt?: string | null; goalEndAt?: string | null };
|
||||
|
||||
const requester = db.prepare('SELECT id, role FROM users WHERE id = ?').get(req.userId) as any;
|
||||
if (!requester || requester.role !== 'admin') {
|
||||
return res.status(403).json({ error: 'Admin only' });
|
||||
}
|
||||
|
||||
const target = db.prepare('SELECT id FROM users WHERE id = ?').get(targetId) as any;
|
||||
if (!target) return res.status(404).json({ error: 'User not found' });
|
||||
|
||||
let normalizedGoalCoins: number | null = null;
|
||||
if (goalCoins !== null && goalCoins !== undefined) {
|
||||
const n = Math.round(Number(goalCoins));
|
||||
if (!Number.isFinite(n) || n <= 0) return res.status(400).json({ error: 'goalCoins must be > 0' });
|
||||
normalizedGoalCoins = n;
|
||||
}
|
||||
|
||||
if (goalStartAt && Number.isNaN(new Date(goalStartAt).getTime())) {
|
||||
return res.status(400).json({ error: 'goalStartAt must be a valid date' });
|
||||
}
|
||||
if (goalEndAt && Number.isNaN(new Date(goalEndAt).getTime())) {
|
||||
return res.status(400).json({ error: 'goalEndAt must be a valid date' });
|
||||
}
|
||||
const normalizedGoalStartAt = goalStartAt ? new Date(goalStartAt).toISOString() : null;
|
||||
const normalizedGoalEndAt = goalEndAt ? new Date(goalEndAt).toISOString() : null;
|
||||
if (normalizedGoalStartAt && normalizedGoalEndAt && new Date(normalizedGoalEndAt).getTime() < new Date(normalizedGoalStartAt).getTime()) {
|
||||
return res.status(400).json({ error: 'goalEndAt must be after goalStartAt' });
|
||||
}
|
||||
|
||||
if (normalizedGoalCoins === null) {
|
||||
db.prepare('UPDATE users SET goalCoins = NULL, goalStartAt = NULL, goalEndAt = NULL WHERE id = ?').run(targetId);
|
||||
} else {
|
||||
db.prepare('UPDATE users SET goalCoins = ?, goalStartAt = ?, goalEndAt = ? WHERE id = ?')
|
||||
.run(normalizedGoalCoins, normalizedGoalStartAt, normalizedGoalEndAt, targetId);
|
||||
}
|
||||
const updated = db.prepare(`SELECT ${USER_SELECT} FROM users WHERE id = ?`).get(targetId);
|
||||
res.json(updated);
|
||||
});
|
||||
|
||||
router.get('/:id/goals', (req: AuthRequest, res: Response) => {
|
||||
const targetId = parseInt(req.params.id as string);
|
||||
const requester = db.prepare('SELECT id, role FROM users WHERE id = ?').get(req.userId) as any;
|
||||
const isSelf = targetId === req.userId;
|
||||
if (!isSelf && requester?.role !== 'admin') {
|
||||
return res.status(403).json({ error: 'Forbidden' });
|
||||
}
|
||||
|
||||
const target = db.prepare('SELECT id FROM users WHERE id = ?').get(targetId) as any;
|
||||
if (!target) return res.status(404).json({ error: 'User not found' });
|
||||
|
||||
const goals = db.prepare(
|
||||
'SELECT id, userId, title, goalCoins, startAt, endAt, createdBy, createdAt FROM user_goals WHERE userId = ? ORDER BY createdAt DESC, id DESC'
|
||||
).all(targetId);
|
||||
res.json(goals);
|
||||
});
|
||||
|
||||
router.post('/:id/goals', (req: AuthRequest, res: Response) => {
|
||||
const targetId = parseInt(req.params.id as string);
|
||||
if (!ensureAdmin(req.userId)) return res.status(403).json({ error: 'Admin only' });
|
||||
|
||||
const target = db.prepare('SELECT id, role FROM users WHERE id = ?').get(targetId) as any;
|
||||
if (!target) return res.status(404).json({ error: 'User not found' });
|
||||
if (target.role === 'admin') return res.status(400).json({ error: 'Cannot assign goals to admin' });
|
||||
|
||||
const { title, goalCoins, startAt, endAt } = req.body as { title?: string; goalCoins?: number; startAt?: string | null; endAt?: string | null };
|
||||
const cleanTitle = String(title || '').trim();
|
||||
if (!cleanTitle) return res.status(400).json({ error: 'title is required' });
|
||||
const n = Math.round(Number(goalCoins));
|
||||
if (!Number.isFinite(n) || n <= 0) return res.status(400).json({ error: 'goalCoins must be > 0' });
|
||||
if (startAt && Number.isNaN(new Date(startAt).getTime())) return res.status(400).json({ error: 'startAt must be a valid date' });
|
||||
if (endAt && Number.isNaN(new Date(endAt).getTime())) return res.status(400).json({ error: 'endAt must be a valid date' });
|
||||
const normStart = startAt ? new Date(startAt).toISOString() : null;
|
||||
const normEnd = endAt ? new Date(endAt).toISOString() : null;
|
||||
if (normStart && normEnd && new Date(normEnd).getTime() < new Date(normStart).getTime()) {
|
||||
return res.status(400).json({ error: 'endAt must be after startAt' });
|
||||
}
|
||||
|
||||
const result = db.prepare(
|
||||
'INSERT INTO user_goals (userId, title, goalCoins, startAt, endAt, createdBy) VALUES (?, ?, ?, ?, ?, ?)'
|
||||
).run(targetId, cleanTitle, n, normStart, normEnd, req.userId);
|
||||
|
||||
syncPrimaryGoal(targetId);
|
||||
const created = db.prepare(
|
||||
'SELECT id, userId, title, goalCoins, startAt, endAt, createdBy, createdAt FROM user_goals WHERE id = ?'
|
||||
).get(result.lastInsertRowid);
|
||||
res.status(201).json(created);
|
||||
});
|
||||
|
||||
router.put('/goals/:goalId', (req: AuthRequest, res: Response) => {
|
||||
const goalId = parseInt(req.params.goalId as string);
|
||||
if (!ensureAdmin(req.userId)) return res.status(403).json({ error: 'Admin only' });
|
||||
const goal = db.prepare('SELECT id, userId FROM user_goals WHERE id = ?').get(goalId) as any;
|
||||
if (!goal) return res.status(404).json({ error: 'Goal not found' });
|
||||
|
||||
const { title, goalCoins, startAt, endAt } = req.body as { title?: string; goalCoins?: number; startAt?: string | null; endAt?: string | null };
|
||||
const cleanTitle = String(title || '').trim();
|
||||
if (!cleanTitle) return res.status(400).json({ error: 'title is required' });
|
||||
const n = Math.round(Number(goalCoins));
|
||||
if (!Number.isFinite(n) || n <= 0) return res.status(400).json({ error: 'goalCoins must be > 0' });
|
||||
if (startAt && Number.isNaN(new Date(startAt).getTime())) return res.status(400).json({ error: 'startAt must be a valid date' });
|
||||
if (endAt && Number.isNaN(new Date(endAt).getTime())) return res.status(400).json({ error: 'endAt must be a valid date' });
|
||||
const normStart = startAt ? new Date(startAt).toISOString() : null;
|
||||
const normEnd = endAt ? new Date(endAt).toISOString() : null;
|
||||
if (normStart && normEnd && new Date(normEnd).getTime() < new Date(normStart).getTime()) {
|
||||
return res.status(400).json({ error: 'endAt must be after startAt' });
|
||||
}
|
||||
|
||||
db.prepare('UPDATE user_goals SET title = ?, goalCoins = ?, startAt = ?, endAt = ? WHERE id = ?')
|
||||
.run(cleanTitle, n, normStart, normEnd, goalId);
|
||||
syncPrimaryGoal(goal.userId);
|
||||
const updated = db.prepare('SELECT id, userId, title, goalCoins, startAt, endAt, createdBy, createdAt FROM user_goals WHERE id = ?').get(goalId);
|
||||
res.json(updated);
|
||||
});
|
||||
|
||||
router.delete('/goals/:goalId', (req: AuthRequest, res: Response) => {
|
||||
const goalId = parseInt(req.params.goalId as string);
|
||||
if (!ensureAdmin(req.userId)) return res.status(403).json({ error: 'Admin only' });
|
||||
const goal = db.prepare('SELECT id, userId FROM user_goals WHERE id = ?').get(goalId) as any;
|
||||
if (!goal) return res.status(404).json({ error: 'Goal not found' });
|
||||
|
||||
db.prepare('DELETE FROM user_goals WHERE id = ?').run(goalId);
|
||||
syncPrimaryGoal(goal.userId);
|
||||
res.json({ success: true });
|
||||
});
|
||||
|
||||
router.get('/notifications-config', (req: AuthRequest, res: Response) => {
|
||||
const requester = db.prepare('SELECT id, role FROM users WHERE id = ?').get(req.userId) as any;
|
||||
if (!requester || requester.role !== 'admin') {
|
||||
return res.status(403).json({ error: 'Admin only' });
|
||||
}
|
||||
|
||||
const enabled = (db.prepare("SELECT value FROM app_settings WHERE key = 'telegramEnabled'").get() as any)?.value === '1';
|
||||
const botToken = (db.prepare("SELECT value FROM app_settings WHERE key = 'telegramBotToken'").get() as any)?.value || '';
|
||||
const chatId = (db.prepare("SELECT value FROM app_settings WHERE key = 'telegramChatId'").get() as any)?.value || '';
|
||||
const notificationTime = (db.prepare("SELECT value FROM app_settings WHERE key = 'telegramNotificationTime'").get() as any)?.value || '09:00';
|
||||
const notificationTypes = readNotificationTypesSetting();
|
||||
res.json({ enabled, chatId, hasToken: !!botToken, notificationTime, notificationTypes });
|
||||
});
|
||||
|
||||
router.put('/notifications-config', (req: AuthRequest, res: Response) => {
|
||||
const requester = db.prepare('SELECT id, role FROM users WHERE id = ?').get(req.userId) as any;
|
||||
if (!requester || requester.role !== 'admin') {
|
||||
return res.status(403).json({ error: 'Admin only' });
|
||||
}
|
||||
|
||||
const { enabled, botToken, chatId, notificationTime, notificationTypes } = req.body as {
|
||||
enabled?: boolean;
|
||||
botToken?: string;
|
||||
chatId?: string;
|
||||
notificationTime?: string;
|
||||
notificationTypes?: NotificationTypeSettings;
|
||||
};
|
||||
const normalizedTime = normalizeNotificationTime(notificationTime);
|
||||
if (notificationTime !== undefined && !normalizedTime) {
|
||||
return res.status(400).json({ error: 'notificationTime must be in HH:MM format' });
|
||||
}
|
||||
const normalizedTypes = normalizeNotificationTypes(notificationTypes);
|
||||
if (notificationTypes !== undefined && !normalizedTypes) {
|
||||
return res.status(400).json({ error: 'notificationTypes is invalid' });
|
||||
}
|
||||
if (enabled !== undefined) {
|
||||
db.prepare("UPDATE app_settings SET value = ?, updatedAt = datetime('now') WHERE key = 'telegramEnabled'")
|
||||
.run(enabled ? '1' : '0');
|
||||
}
|
||||
if (botToken !== undefined) {
|
||||
db.prepare("UPDATE app_settings SET value = ?, updatedAt = datetime('now') WHERE key = 'telegramBotToken'")
|
||||
.run(botToken.trim());
|
||||
}
|
||||
if (chatId !== undefined) {
|
||||
db.prepare("UPDATE app_settings SET value = ?, updatedAt = datetime('now') WHERE key = 'telegramChatId'")
|
||||
.run(chatId.trim());
|
||||
}
|
||||
if (normalizedTime) {
|
||||
db.prepare("UPDATE app_settings SET value = ?, updatedAt = datetime('now') WHERE key = 'telegramNotificationTime'")
|
||||
.run(normalizedTime);
|
||||
}
|
||||
if (normalizedTypes) {
|
||||
db.prepare("UPDATE app_settings SET value = ?, updatedAt = datetime('now') WHERE key = 'telegramNotificationTypes'")
|
||||
.run(JSON.stringify(normalizedTypes));
|
||||
}
|
||||
|
||||
const enabledNow = (db.prepare("SELECT value FROM app_settings WHERE key = 'telegramEnabled'").get() as any)?.value === '1';
|
||||
const tokenNow = (db.prepare("SELECT value FROM app_settings WHERE key = 'telegramBotToken'").get() as any)?.value || '';
|
||||
const chatNow = (db.prepare("SELECT value FROM app_settings WHERE key = 'telegramChatId'").get() as any)?.value || '';
|
||||
if (enabledNow && (!tokenNow || !chatNow)) {
|
||||
return res.status(400).json({ error: 'To enable notifications, both Telegram bot token and Telegram chat ID are required.' });
|
||||
}
|
||||
const notificationTimeNow = (db.prepare("SELECT value FROM app_settings WHERE key = 'telegramNotificationTime'").get() as any)?.value || '09:00';
|
||||
const notificationTypesNow = readNotificationTypesSetting();
|
||||
res.json({ enabled: enabledNow, chatId: chatNow, hasToken: !!tokenNow, notificationTime: notificationTimeNow, notificationTypes: notificationTypesNow });
|
||||
});
|
||||
|
||||
router.post('/notifications-test', async (req: AuthRequest, res: Response) => {
|
||||
const requester = db.prepare('SELECT id, role, displayName FROM users WHERE id = ?').get(req.userId) as any;
|
||||
if (!requester || requester.role !== 'admin') {
|
||||
return res.status(403).json({ error: 'Admin only' });
|
||||
}
|
||||
const { botToken, chatId } = req.body as { botToken?: string; chatId?: string };
|
||||
const result = await sendTelegramMessageDetailed(
|
||||
`TidyQuest test notification from ${requester.displayName} (${new Date().toISOString()})`,
|
||||
{ ignoreEnabled: true, botToken, chatId }
|
||||
);
|
||||
if (!result.ok) {
|
||||
return res.status(400).json({ error: result.error || 'Telegram notification failed.' });
|
||||
}
|
||||
res.json({ success: true });
|
||||
});
|
||||
|
||||
router.delete('/:id', (req: AuthRequest, res: Response) => {
|
||||
const targetId = parseInt(req.params.id as string);
|
||||
|
||||
const requester = db.prepare('SELECT id, role FROM users WHERE id = ?').get(req.userId) as any;
|
||||
if (!requester || requester.role !== 'admin') {
|
||||
return res.status(403).json({ error: 'Admin only' });
|
||||
}
|
||||
if (targetId === req.userId) {
|
||||
return res.status(400).json({ error: 'Cannot delete your own account' });
|
||||
}
|
||||
|
||||
const target = db.prepare('SELECT id, role FROM users WHERE id = ?').get(targetId) as any;
|
||||
if (!target) return res.status(404).json({ error: 'User not found' });
|
||||
|
||||
if (target.role === 'admin') {
|
||||
const adminCount = db.prepare("SELECT COUNT(*) as count FROM users WHERE role = 'admin'").get() as { count: number };
|
||||
if (adminCount.count <= 1) {
|
||||
return res.status(400).json({ error: 'At least one admin is required' });
|
||||
}
|
||||
}
|
||||
|
||||
db.prepare('DELETE FROM users WHERE id = ?').run(targetId);
|
||||
res.json({ success: true });
|
||||
});
|
||||
|
||||
export default router;
|
||||
108
server/src/utils/achievementNotifications.ts
Normal file
108
server/src/utils/achievementNotifications.ts
Normal file
|
|
@ -0,0 +1,108 @@
|
|||
import db from '../database';
|
||||
import { buildAchievements } from './achievements';
|
||||
import { isNotificationTypeEnabled, sendTelegramMessage } from './notifications';
|
||||
import { calculateHealth } from './health';
|
||||
|
||||
function getUserAchievementStats(userId: number) {
|
||||
const user = db.prepare(
|
||||
'SELECT id, displayName, coins, currentStreak, isVacationMode, vacationStartDate FROM users WHERE id = ?'
|
||||
).get(userId) as any;
|
||||
if (!user) return null;
|
||||
|
||||
const completionsRow = db.prepare('SELECT COUNT(*) as count FROM task_completions WHERE userId = ?').get(userId) as { count: number };
|
||||
|
||||
const rooms = db.prepare('SELECT id FROM rooms').all() as Array<{ id: number }>;
|
||||
let roomsClean = 0;
|
||||
for (const room of rooms) {
|
||||
const tasks = db.prepare('SELECT effort, isSeasonal, lastCompletedAt, frequencyDays FROM tasks WHERE roomId = ?').all(room.id) as Array<{
|
||||
effort: number;
|
||||
isSeasonal: number;
|
||||
lastCompletedAt: string | null;
|
||||
frequencyDays: number;
|
||||
}>;
|
||||
if (tasks.length === 0) continue;
|
||||
const nonSeasonal = tasks.filter((t) => !t.isSeasonal);
|
||||
const forAvg = nonSeasonal.length > 0 ? nonSeasonal : tasks;
|
||||
const totalEffort = forAvg.reduce((s, t) => s + t.effort, 0);
|
||||
const health = totalEffort > 0
|
||||
? Math.round(forAvg.reduce((s, t) => s + calculateHealth(t.lastCompletedAt, t.frequencyDays, !!user.isVacationMode, user.vacationStartDate) * t.effort, 0) / totalEffort)
|
||||
: 100;
|
||||
if (health >= 70) roomsClean++;
|
||||
}
|
||||
|
||||
const now = new Date();
|
||||
const dayOfWeek = now.getUTCDay() || 7;
|
||||
const monday = new Date(now);
|
||||
monday.setUTCDate(now.getUTCDate() - dayOfWeek + 1);
|
||||
monday.setUTCHours(0, 0, 0, 0);
|
||||
const weeklyRow = db.prepare(
|
||||
'SELECT COUNT(*) as count FROM task_completions WHERE userId = ? AND completedAt >= ?'
|
||||
).get(userId, monday.toISOString()) as { count: number };
|
||||
|
||||
const allCompletions = db.prepare(
|
||||
"SELECT date(completedAt) as day FROM task_completions WHERE userId = ? GROUP BY date(completedAt) ORDER BY day"
|
||||
).all(userId) as Array<{ day: string }>;
|
||||
|
||||
const parseDayUTC = (day: string): Date => new Date(`${day}T00:00:00.000Z`);
|
||||
const mondayOfUTCDate = (d: Date): Date => {
|
||||
const out = new Date(d);
|
||||
const dow = out.getUTCDay() || 7;
|
||||
out.setUTCDate(out.getUTCDate() - dow + 1);
|
||||
out.setUTCHours(0, 0, 0, 0);
|
||||
return out;
|
||||
};
|
||||
|
||||
let perfectWeeks = 0;
|
||||
if (allCompletions.length > 0) {
|
||||
const daySet = new Set(allCompletions.map((c) => c.day));
|
||||
const firstDay = parseDayUTC(allCompletions[0].day);
|
||||
const startMonday = mondayOfUTCDate(firstDay);
|
||||
const thisMonday = mondayOfUTCDate(now);
|
||||
const checkDate = new Date(startMonday);
|
||||
|
||||
while (checkDate < thisMonday) {
|
||||
let allDays = true;
|
||||
for (let d = 0; d < 7; d++) {
|
||||
const checkDay = new Date(checkDate);
|
||||
checkDay.setUTCDate(checkDate.getUTCDate() + d);
|
||||
const dayStr = checkDay.toISOString().slice(0, 10);
|
||||
if (!daySet.has(dayStr)) {
|
||||
allDays = false;
|
||||
break;
|
||||
}
|
||||
}
|
||||
if (allDays) perfectWeeks++;
|
||||
checkDate.setUTCDate(checkDate.getUTCDate() + 7);
|
||||
}
|
||||
}
|
||||
|
||||
return {
|
||||
userDisplayName: String(user.displayName || 'User'),
|
||||
achievements: buildAchievements({
|
||||
completions: completionsRow.count,
|
||||
streak: user.currentStreak || 0,
|
||||
coins: user.coins || 0,
|
||||
rooms_clean: roomsClean,
|
||||
weekly_tasks: weeklyRow.count,
|
||||
perfect_weeks: perfectWeeks,
|
||||
}),
|
||||
};
|
||||
}
|
||||
|
||||
export async function notifyAchievementUnlocksForUser(userId: number): Promise<void> {
|
||||
if (!isNotificationTypeEnabled('achievementUnlocked')) return;
|
||||
const stats = getUserAchievementStats(userId);
|
||||
if (!stats) return;
|
||||
|
||||
for (const ach of stats.achievements) {
|
||||
if (!ach.unlocked) continue;
|
||||
const inserted = db.prepare(
|
||||
'INSERT OR IGNORE INTO user_achievement_notifications (userId, achievementId) VALUES (?, ?)'
|
||||
).run(userId, ach.id);
|
||||
if (inserted.changes < 1) continue;
|
||||
|
||||
await sendTelegramMessage(
|
||||
`🏆 ${stats.userDisplayName} unlocked an achievement: ${ach.id}`
|
||||
);
|
||||
}
|
||||
}
|
||||
72
server/src/utils/achievements.ts
Normal file
72
server/src/utils/achievements.ts
Normal file
|
|
@ -0,0 +1,72 @@
|
|||
export interface AchievementDef {
|
||||
id: string;
|
||||
titleKey: string;
|
||||
descKey: string;
|
||||
icon: 'spark' | 'fire' | 'coin' | 'star' | 'crown' | 'broom' | 'heart' | 'shield' | 'rocket' | 'diamond';
|
||||
threshold: number;
|
||||
metric: 'completions' | 'streak' | 'coins' | 'rooms_clean' | 'weekly_tasks' | 'perfect_weeks';
|
||||
}
|
||||
|
||||
export const ACHIEVEMENTS: AchievementDef[] = [
|
||||
// Getting started
|
||||
{ id: 'first_task', titleKey: 'achievements.firstStep', descKey: 'achievements.firstStepDesc', icon: 'spark', threshold: 1, metric: 'completions' },
|
||||
{ id: 'helper_10', titleKey: 'achievements.helper', descKey: 'achievements.helperDesc', icon: 'star', threshold: 10, metric: 'completions' },
|
||||
{ id: 'busy_bee_25', titleKey: 'achievements.busyBee', descKey: 'achievements.busyBeeDesc', icon: 'broom', threshold: 25, metric: 'completions' },
|
||||
{ id: 'cleaning_hero_50', titleKey: 'achievements.cleaningHero', descKey: 'achievements.cleaningHeroDesc', icon: 'shield', threshold: 50, metric: 'completions' },
|
||||
{ id: 'chore_champion_100', titleKey: 'achievements.choreChampion', descKey: 'achievements.choreChampionDesc', icon: 'crown', threshold: 100, metric: 'completions' },
|
||||
{ id: 'tidyquest_legend_250', titleKey: 'achievements.legend', descKey: 'achievements.legendDesc', icon: 'diamond', threshold: 250, metric: 'completions' },
|
||||
{ id: 'unstoppable_500', titleKey: 'achievements.unstoppable', descKey: 'achievements.unstoppableDesc', icon: 'rocket', threshold: 500, metric: 'completions' },
|
||||
|
||||
// Streaks
|
||||
{ id: 'streak_3', titleKey: 'achievements.onFire', descKey: 'achievements.onFireDesc', icon: 'fire', threshold: 3, metric: 'streak' },
|
||||
{ id: 'streak_7', titleKey: 'achievements.streakMaster', descKey: 'achievements.streakMasterDesc', icon: 'fire', threshold: 7, metric: 'streak' },
|
||||
{ id: 'streak_14', titleKey: 'achievements.twoWeekWarrior', descKey: 'achievements.twoWeekWarriorDesc', icon: 'fire', threshold: 14, metric: 'streak' },
|
||||
{ id: 'streak_30', titleKey: 'achievements.monthlyMachine', descKey: 'achievements.monthlyMachineDesc', icon: 'crown', threshold: 30, metric: 'streak' },
|
||||
{ id: 'streak_100', titleKey: 'achievements.centurion', descKey: 'achievements.centurionDesc', icon: 'diamond', threshold: 100, metric: 'streak' },
|
||||
{ id: 'streak_60_night_owl', titleKey: 'achievements.nightOwl', descKey: 'achievements.nightOwlDesc', icon: 'rocket', threshold: 60, metric: 'streak' },
|
||||
|
||||
// Coins
|
||||
{ id: 'coins_50', titleKey: 'achievements.piggyBank', descKey: 'achievements.piggyBankDesc', icon: 'coin', threshold: 50, metric: 'coins' },
|
||||
{ id: 'coins_100', titleKey: 'achievements.saver', descKey: 'achievements.saverDesc', icon: 'coin', threshold: 100, metric: 'coins' },
|
||||
{ id: 'coins_500', titleKey: 'achievements.treasureHunter', descKey: 'achievements.treasureHunterDesc', icon: 'coin', threshold: 500, metric: 'coins' },
|
||||
{ id: 'coins_1000', titleKey: 'achievements.goldMaster', descKey: 'achievements.goldMasterDesc', icon: 'crown', threshold: 1000, metric: 'coins' },
|
||||
{ id: 'coins_5000', titleKey: 'achievements.millionaire', descKey: 'achievements.millionaireDesc', icon: 'diamond', threshold: 5000, metric: 'coins' },
|
||||
|
||||
// Room mastery
|
||||
{ id: 'room_master_3', titleKey: 'achievements.roomTamer', descKey: 'achievements.roomTamerDesc', icon: 'heart', threshold: 3, metric: 'rooms_clean' },
|
||||
{ id: 'room_master_5', titleKey: 'achievements.housePride', descKey: 'achievements.housePrideDesc', icon: 'shield', threshold: 5, metric: 'rooms_clean' },
|
||||
|
||||
// Weekly productivity
|
||||
{ id: 'weekly_5', titleKey: 'achievements.weekendWarrior', descKey: 'achievements.weekendWarriorDesc', icon: 'star', threshold: 5, metric: 'weekly_tasks' },
|
||||
{ id: 'weekly_15', titleKey: 'achievements.superWeek', descKey: 'achievements.superWeekDesc', icon: 'rocket', threshold: 15, metric: 'weekly_tasks' },
|
||||
|
||||
// Perfect weeks (all due tasks done)
|
||||
{ id: 'perfect_1', titleKey: 'achievements.perfectWeek', descKey: 'achievements.perfectWeekDesc', icon: 'star', threshold: 1, metric: 'perfect_weeks' },
|
||||
{ id: 'perfect_4', titleKey: 'achievements.perfectMonth', descKey: 'achievements.perfectMonthDesc', icon: 'crown', threshold: 4, metric: 'perfect_weeks' },
|
||||
];
|
||||
|
||||
export interface AchievementStats {
|
||||
completions: number;
|
||||
streak: number;
|
||||
coins: number;
|
||||
rooms_clean: number;
|
||||
weekly_tasks: number;
|
||||
perfect_weeks: number;
|
||||
}
|
||||
|
||||
export function buildAchievements(stats: AchievementStats) {
|
||||
return ACHIEVEMENTS.map((a) => {
|
||||
const value = stats[a.metric] ?? 0;
|
||||
const progress = Math.min(100, Math.round((value / a.threshold) * 100));
|
||||
return {
|
||||
id: a.id,
|
||||
titleKey: a.titleKey,
|
||||
descKey: a.descKey,
|
||||
icon: a.icon,
|
||||
threshold: a.threshold,
|
||||
value,
|
||||
progress,
|
||||
unlocked: value >= a.threshold,
|
||||
};
|
||||
});
|
||||
}
|
||||
45
server/src/utils/health.ts
Normal file
45
server/src/utils/health.ts
Normal file
|
|
@ -0,0 +1,45 @@
|
|||
export function calculateHealth(
|
||||
lastCompletedAt: string | null,
|
||||
frequencyDays: number,
|
||||
isVacationMode: boolean = false,
|
||||
vacationStartDate: string | null = null
|
||||
): number {
|
||||
if (!lastCompletedAt) return 0;
|
||||
|
||||
let now = Date.now();
|
||||
|
||||
// If vacation mode is on, freeze time at vacation start
|
||||
if (isVacationMode && vacationStartDate) {
|
||||
now = new Date(vacationStartDate).getTime();
|
||||
}
|
||||
|
||||
const lastDone = new Date(lastCompletedAt).getTime();
|
||||
const safeFrequencyDays = Math.max(1 / 24, Number(frequencyDays) || 7);
|
||||
const daysSinceCompletion = (now - lastDone) / (1000 * 60 * 60 * 24);
|
||||
const health = Math.max(0, Math.round(100 - (daysSinceCompletion / safeFrequencyDays) * 100));
|
||||
return health;
|
||||
}
|
||||
|
||||
export const DEFAULT_COINS_BY_EFFORT: Record<number, number> = {
|
||||
1: 5,
|
||||
2: 10,
|
||||
3: 15,
|
||||
4: 20,
|
||||
5: 25,
|
||||
};
|
||||
|
||||
export function normalizeCoinsByEffortConfig(config: any): Record<number, number> {
|
||||
const normalized: Record<number, number> = { ...DEFAULT_COINS_BY_EFFORT };
|
||||
for (const key of [1, 2, 3, 4, 5]) {
|
||||
const v = Number(config?.[key] ?? config?.[String(key)]);
|
||||
if (Number.isFinite(v) && v >= 0) {
|
||||
normalized[key] = Math.round(v);
|
||||
}
|
||||
}
|
||||
return normalized;
|
||||
}
|
||||
|
||||
export function getCoinsForEffort(effort: number, coinsByEffort: Record<number, number> = DEFAULT_COINS_BY_EFFORT): number {
|
||||
const e = Math.max(1, Math.min(5, Math.round(effort || 1)));
|
||||
return coinsByEffort[e] ?? DEFAULT_COINS_BY_EFFORT[e];
|
||||
}
|
||||
167
server/src/utils/notifications.ts
Normal file
167
server/src/utils/notifications.ts
Normal file
|
|
@ -0,0 +1,167 @@
|
|||
import db from '../database';
|
||||
|
||||
interface TelegramSettings {
|
||||
enabled: boolean;
|
||||
botToken: string;
|
||||
chatId: string;
|
||||
notificationTime: string;
|
||||
}
|
||||
|
||||
export interface NotificationTypeSettings {
|
||||
taskDue: boolean;
|
||||
rewardRequest: boolean;
|
||||
achievementUnlocked: boolean;
|
||||
}
|
||||
|
||||
function getSetting(key: string): string {
|
||||
const row = db.prepare('SELECT value FROM app_settings WHERE key = ?').get(key) as { value?: string } | undefined;
|
||||
return row?.value || '';
|
||||
}
|
||||
|
||||
export function getTelegramSettings(): TelegramSettings {
|
||||
return {
|
||||
enabled: getSetting('telegramEnabled') === '1',
|
||||
botToken: getSetting('telegramBotToken'),
|
||||
chatId: getSetting('telegramChatId'),
|
||||
notificationTime: normalizeNotificationTime(getSetting('telegramNotificationTime')),
|
||||
};
|
||||
}
|
||||
|
||||
const DEFAULT_NOTIFICATION_TYPES: NotificationTypeSettings = {
|
||||
taskDue: true,
|
||||
rewardRequest: true,
|
||||
achievementUnlocked: true,
|
||||
};
|
||||
|
||||
export function getNotificationTypeSettings(): NotificationTypeSettings {
|
||||
const raw = getSetting('telegramNotificationTypes');
|
||||
if (!raw) return DEFAULT_NOTIFICATION_TYPES;
|
||||
try {
|
||||
const parsed = JSON.parse(raw) as Partial<NotificationTypeSettings>;
|
||||
return {
|
||||
taskDue: parsed.taskDue !== false,
|
||||
rewardRequest: parsed.rewardRequest !== false,
|
||||
achievementUnlocked: parsed.achievementUnlocked !== false,
|
||||
};
|
||||
} catch {
|
||||
return DEFAULT_NOTIFICATION_TYPES;
|
||||
}
|
||||
}
|
||||
|
||||
export function isNotificationTypeEnabled(type: keyof NotificationTypeSettings): boolean {
|
||||
return getNotificationTypeSettings()[type];
|
||||
}
|
||||
|
||||
interface SendTelegramMessageOptions {
|
||||
ignoreEnabled?: boolean;
|
||||
botToken?: string;
|
||||
chatId?: string;
|
||||
}
|
||||
|
||||
interface TelegramSendResult {
|
||||
ok: boolean;
|
||||
error?: string;
|
||||
}
|
||||
|
||||
function normalizeNotificationTime(value: string): string {
|
||||
const trimmed = value.trim();
|
||||
return /^([01]\d|2[0-3]):([0-5]\d)$/.test(trimmed) ? trimmed : '09:00';
|
||||
}
|
||||
|
||||
function toLocalIsoDay(date: Date): string {
|
||||
const year = date.getFullYear();
|
||||
const month = String(date.getMonth() + 1).padStart(2, '0');
|
||||
const day = String(date.getDate()).padStart(2, '0');
|
||||
return `${year}-${month}-${day}`;
|
||||
}
|
||||
|
||||
function getDueIsoDay(task: { lastCompletedAt: string | null; frequencyDays: number }, now: Date): string {
|
||||
const safeFrequency = Math.max(1 / 24, Number(task.frequencyDays) || 7);
|
||||
const dueTs = task.lastCompletedAt
|
||||
? new Date(task.lastCompletedAt).getTime() + safeFrequency * 86400000
|
||||
: now.getTime();
|
||||
return toLocalIsoDay(new Date(dueTs));
|
||||
}
|
||||
|
||||
export async function sendTelegramMessageDetailed(message: string, options: SendTelegramMessageOptions = {}): Promise<TelegramSendResult> {
|
||||
const cfg = getTelegramSettings();
|
||||
const botToken = options.botToken?.trim() || cfg.botToken;
|
||||
const chatId = options.chatId?.trim() || cfg.chatId;
|
||||
if (!botToken) return { ok: false, error: 'Telegram bot token is missing.' };
|
||||
if (!chatId) return { ok: false, error: 'Telegram chat ID is missing.' };
|
||||
if (!cfg.enabled && !options.ignoreEnabled) return { ok: false, error: 'Notifications are disabled.' };
|
||||
|
||||
try {
|
||||
const response = await fetch(`https://api.telegram.org/bot${botToken}/sendMessage`, {
|
||||
method: 'POST',
|
||||
headers: { 'Content-Type': 'application/json' },
|
||||
body: JSON.stringify({
|
||||
chat_id: chatId,
|
||||
text: message,
|
||||
}),
|
||||
});
|
||||
if (response.ok) return { ok: true };
|
||||
|
||||
const body = await response.json().catch(() => null) as { description?: string } | null;
|
||||
const details = body?.description ? ` ${body.description}` : '';
|
||||
return { ok: false, error: `Telegram API rejected the request.${details}`.trim() };
|
||||
} catch {
|
||||
return { ok: false, error: 'Could not reach Telegram API (network/connectivity issue).' };
|
||||
}
|
||||
}
|
||||
|
||||
export async function sendTelegramMessage(message: string, options: SendTelegramMessageOptions = {}): Promise<boolean> {
|
||||
const result = await sendTelegramMessageDetailed(message, options);
|
||||
return result.ok;
|
||||
}
|
||||
|
||||
let lastCheckedMinute: string | null = null;
|
||||
|
||||
export async function sendDueTaskNotificationsIfNeeded(
|
||||
now: Date = new Date(),
|
||||
sendFn: (message: string) => Promise<boolean> = (message) => sendTelegramMessage(message),
|
||||
): Promise<void> {
|
||||
const cfg = getTelegramSettings();
|
||||
if (!cfg.enabled || !cfg.botToken || !cfg.chatId) return;
|
||||
if (!isNotificationTypeEnabled('taskDue')) return;
|
||||
|
||||
const currentMinute = `${toLocalIsoDay(now)} ${String(now.getHours()).padStart(2, '0')}:${String(now.getMinutes()).padStart(2, '0')}`;
|
||||
if (currentMinute === lastCheckedMinute) return;
|
||||
lastCheckedMinute = currentMinute;
|
||||
|
||||
const nowHm = `${String(now.getHours()).padStart(2, '0')}:${String(now.getMinutes()).padStart(2, '0')}`;
|
||||
if (nowHm !== cfg.notificationTime) return;
|
||||
|
||||
const today = toLocalIsoDay(now);
|
||||
const tasks = db.prepare(
|
||||
`SELECT t.id, t.name, t.frequencyDays, t.lastCompletedAt, r.name as roomName
|
||||
FROM tasks t
|
||||
LEFT JOIN rooms r ON r.id = t.roomId
|
||||
WHERE t.isSeasonal = 0`
|
||||
).all() as Array<{
|
||||
id: number;
|
||||
name: string;
|
||||
frequencyDays: number;
|
||||
lastCompletedAt: string | null;
|
||||
roomName: string | null;
|
||||
}>;
|
||||
|
||||
for (const task of tasks) {
|
||||
const dueDate = getDueIsoDay(task, now);
|
||||
if (dueDate !== today) continue;
|
||||
|
||||
const alreadySent = db.prepare(
|
||||
'SELECT id FROM task_due_notifications WHERE taskId = ? AND dueDate = ?'
|
||||
).get(task.id, today) as { id: number } | undefined;
|
||||
if (alreadySent) continue;
|
||||
|
||||
const sent = await sendFn(
|
||||
`Task due today: "${task.name}"${task.roomName ? ` (${task.roomName})` : ''}.`
|
||||
);
|
||||
if (!sent) continue;
|
||||
|
||||
db.prepare(
|
||||
'INSERT OR IGNORE INTO task_due_notifications (taskId, dueDate) VALUES (?, ?)'
|
||||
).run(task.id, today);
|
||||
}
|
||||
}
|
||||
102
server/src/utils/taskIcons.ts
Normal file
102
server/src/utils/taskIcons.ts
Normal file
|
|
@ -0,0 +1,102 @@
|
|||
export type TaskIconKey =
|
||||
| 'sparkle' | 'dishes' | 'sink' | 'stove' | 'counter' | 'fridge' | 'oven'
|
||||
| 'microwave' | 'kettle' | 'rangehood' | 'pantry' | 'cabinet'
|
||||
| 'bed' | 'pillow' | 'sheets' | 'mattress' | 'nightstand'
|
||||
| 'toilet' | 'shower' | 'mirror' | 'towel' | 'drain' | 'bathmat'
|
||||
| 'showerhead' | 'toothbrush' | 'grout'
|
||||
| 'vacuum' | 'mop' | 'dust' | 'sweep'
|
||||
| 'window' | 'curtain' | 'lightswitch'
|
||||
| 'sofa' | 'tv' | 'lamp' | 'furniture' | 'rug'
|
||||
| 'desk' | 'keyboard' | 'monitor' | 'cable' | 'chair'
|
||||
| 'trash' | 'broom'
|
||||
| 'washer' | 'dryer' | 'detergent' | 'iron' | 'clothes'
|
||||
| 'tools' | 'cobweb' | 'chemicals' | 'garagedoor'
|
||||
| 'shelf' | 'drawer' | 'closet';
|
||||
|
||||
export function suggestTaskIcon(name?: string | null, translationKey?: string | null): TaskIconKey {
|
||||
const s = `${name || ''} ${translationKey || ''}`.toLowerCase();
|
||||
|
||||
// Kitchen
|
||||
if (s.includes('dish') || s.includes('dishwasher') || s.includes('vaisselle') || s.includes('geschirrspul') || s.includes('lavaplatos')) return 'dishes';
|
||||
if (s.includes('sink') || s.includes('évier') || s.includes('evier') || s.includes('spüle') || s.includes('fregadero') || s.includes('clean_sink')) return 'sink';
|
||||
if (s.includes('stove') || s.includes('stovetop') || s.includes('plaque') || s.includes('herd') || s.includes('estufa') || s.includes('wipe_stovetop')) return 'stove';
|
||||
if (s.includes('counter') || s.includes('comptoir') || s.includes('arbeitsfl') || s.includes('encimera') || s.includes('clean_counters')) return 'counter';
|
||||
if (s.includes('fridge') || s.includes('freezer') || s.includes('congélateur') || s.includes('congelateur') || s.includes('gefrier') || s.includes('congelador') || s.includes('réfri') || s.includes('refri') || s.includes('kühlschrank') || s.includes('nevera') || s.includes('frigorifico') || s.includes('defrost_freezer')) return 'fridge';
|
||||
if (s.includes('oven') || s.includes('four') || s.includes('backofen') || s.includes('horno')) return 'oven';
|
||||
if (s.includes('microwave') || s.includes('micro-onde') || s.includes('mikrowelle') || s.includes('microondas')) return 'microwave';
|
||||
if (s.includes('kettle') || s.includes('bouilloire') || s.includes('wasserkocher') || s.includes('hervidor') || s.includes('descale_kettle')) return 'kettle';
|
||||
if (s.includes('range hood') || s.includes('hotte') || s.includes('dunstabzug') || s.includes('campana') || s.includes('range_hood')) return 'rangehood';
|
||||
if (s.includes('pantry') || s.includes('garde-manger') || s.includes('speisekammer') || s.includes('despensa') || s.includes('organize_pantry')) return 'pantry';
|
||||
if (s.includes('cabinet') || s.includes('placard') || s.includes('schrank') || s.includes('armario') || s.includes('cabinet_fronts')) return 'cabinet';
|
||||
if (s.includes('appliance') || s.includes('wipe_appliances')) return 'counter';
|
||||
|
||||
// Bedroom
|
||||
if (s.includes('mattress') || s.includes('matelas') || s.includes('matratze') || s.includes('colchón') || s.includes('colchon') || s.includes('flip_mattress')) return 'mattress';
|
||||
if (s.includes('pillow') || s.includes('oreiller') || s.includes('kissen') || s.includes('almohada') || s.includes('wash_pillows')) return 'pillow';
|
||||
if (s.includes('sheet') || s.includes('drap') || s.includes('bettwäsche') || s.includes('bettwaesche') || s.includes('sábana') || s.includes('sabana') || s.includes('change_sheets')) return 'sheets';
|
||||
if (s.includes('duvet') || s.includes('comforter') || s.includes('couette') || s.includes('bettdecke') || s.includes('edredón') || s.includes('wash_duvet')) return 'sheets';
|
||||
if (s.includes('nightstand') || s.includes('table de nuit') || s.includes('nachttisch') || s.includes('mesita') || s.includes('tidy_nightstand')) return 'nightstand';
|
||||
if (s.includes('make bed') || s.includes('bed') || s.includes('make_bed') || s.includes('clean_under_bed')) return 'bed';
|
||||
|
||||
// Bathroom
|
||||
if (s.includes('toilet') || s.includes('toilette') || s.includes('wc') || s.includes('scrub_toilet')) return 'toilet';
|
||||
if (s.includes('showerhead') || s.includes('pomme de douche') || s.includes('duschkopf') || s.includes('alcachofa') || s.includes('descale_showerhead')) return 'showerhead';
|
||||
if (s.includes('shower') || s.includes('douche') || s.includes('dusche') || s.includes('ducha') || s.includes('squeegee') || s.includes('shower_tub') || s.includes('shower_curtain') || s.includes('clean_shower')) return 'shower';
|
||||
if (s.includes('mirror') || s.includes('miroir') || s.includes('spiegel') || s.includes('espejo') || s.includes('clean_mirror')) return 'mirror';
|
||||
if (s.includes('towel') || s.includes('serviette') || s.includes('handtuch') || s.includes('toalla') || s.includes('wash_towels')) return 'towel';
|
||||
if (s.includes('drain') || s.includes('siphon') || s.includes('abfluss') || s.includes('desagüe') || s.includes('desague') || s.includes('shower_drain')) return 'drain';
|
||||
if (s.includes('bath mat') || s.includes('tapis de bain') || s.includes('badematte') || s.includes('alfombra de baño') || s.includes('wash_bath_mat')) return 'bathmat';
|
||||
if (s.includes('toothbrush') || s.includes('brosse à dent') || s.includes('zahnbürste') || s.includes('cepillo de diente') || s.includes('replace_toothbrush')) return 'toothbrush';
|
||||
if (s.includes('grout') || s.includes('joint') || s.includes('fuge') || s.includes('lechada') || s.includes('clean_grout')) return 'grout';
|
||||
|
||||
// Cleaning actions
|
||||
if (s.includes('vacuum') || s.includes('aspirat') || s.includes('staubsaug') || s.includes('aspira')) return 'vacuum';
|
||||
if (s.includes('mop') || s.includes('serpill') || s.includes('wisch') || s.includes('fregona') || s.includes('mop_floor') || s.includes('hose_floor')) return 'mop';
|
||||
if (s.includes('dust') || s.includes('poussière') || s.includes('poussiere') || s.includes('staub') || s.includes('polvo') || s.includes('dust_surfaces') || s.includes('dust_shelves') || s.includes('dust_lampshades')) return 'dust';
|
||||
if (s.includes('sweep') || s.includes('balay') || s.includes('feg') || s.includes('barr') || s.includes('sweep_floor') || s.includes('sweep_mop')) return 'sweep';
|
||||
|
||||
// Living room
|
||||
if (s.includes('sofa') || s.includes('couch') || s.includes('canapé') || s.includes('canape') || s.includes('cushion') || s.includes('coussin') || s.includes('vacuum_sofa') || s.includes('fluff_cushion')) return 'sofa';
|
||||
if (s.includes('tv') || s.includes('television') || s.includes('remote') || s.includes('télécommande') || s.includes('fernseh') || s.includes('fernbedien') || s.includes('wipe_tv') || s.includes('clean_remotes')) return 'tv';
|
||||
if (s.includes('lamp') || s.includes('light fixture') || s.includes('lampe') || s.includes('lámpara') || s.includes('lampshade') || s.includes('desk_lamp')) return 'lamp';
|
||||
if (s.includes('furniture') || s.includes('meuble') || s.includes('möbel') || s.includes('mueble') || s.includes('polish') || s.includes('clean_behind')) return 'furniture';
|
||||
if (s.includes('rug') || s.includes('carpet') || s.includes('tapis') || s.includes('teppich') || s.includes('alfombra') || s.includes('deep_clean_carpet')) return 'rug';
|
||||
|
||||
// Windows & switches
|
||||
if (s.includes('curtain') || s.includes('blind') || s.includes('rideau') || s.includes('vorhang') || s.includes('cortina') || s.includes('jalousie') || s.includes('wash_curtains') || s.includes('curtains_blinds')) return 'curtain';
|
||||
if (s.includes('window') || s.includes('fenêtre') || s.includes('fenetre') || s.includes('fenster') || s.includes('ventana') || s.includes('clean_windows')) return 'window';
|
||||
if (s.includes('switch') || s.includes('handle') || s.includes('interrupteur') || s.includes('poignée') || s.includes('schalter') || s.includes('griff') || s.includes('wipe_switches') || s.includes('door_handle')) return 'lightswitch';
|
||||
|
||||
// Office
|
||||
if (s.includes('keyboard') || s.includes('mouse') || s.includes('clavier') || s.includes('souris') || s.includes('tastatur') || s.includes('maus') || s.includes('teclado') || s.includes('ratón') || s.includes('clean_keyboard')) return 'keyboard';
|
||||
if (s.includes('monitor') || s.includes('écran') || s.includes('ecran') || s.includes('bildschirm') || s.includes('wipe_monitor')) return 'monitor';
|
||||
if (s.includes('cable') || s.includes('câble') || s.includes('kabel') || s.includes('organize_cables')) return 'cable';
|
||||
if (s.includes('chair') || s.includes('chaise') || s.includes('stuhl') || s.includes('silla') || s.includes('clean_chair')) return 'chair';
|
||||
if (s.includes('desk') || s.includes('bureau') || s.includes('schreibtisch') || s.includes('escritorio') || s.includes('clear_desk') || s.includes('wipe_desk')) return 'desk';
|
||||
|
||||
// Laundry
|
||||
if (s.includes('dryer vent') || s.includes('lint') || s.includes('peluche') || s.includes('flusensieb') || s.includes('pelusa') || s.includes('lint_filter') || s.includes('dryer_vent')) return 'dryer';
|
||||
if (s.includes('washer') || s.includes('washing') || s.includes('lave-linge') || s.includes('waschmaschine') || s.includes('lavadora') || s.includes('washer_seal') || s.includes('cleaning_cycle') || s.includes('machine_exterior')) return 'washer';
|
||||
if (s.includes('detergent') || s.includes('lessive') || s.includes('waschmittel') || s.includes('detergente') || s.includes('detergent_drawer') || s.includes('organize_supplies')) return 'detergent';
|
||||
if (s.includes('fold') || s.includes('iron') || s.includes('pli') || s.includes('repass') || s.includes('bügel') || s.includes('planch') || s.includes('folding_surface')) return 'iron';
|
||||
if (s.includes('cloth') || s.includes('donat') || s.includes('vêtement') || s.includes('kleidung') || s.includes('ropa') || s.includes('sort_donate')) return 'clothes';
|
||||
|
||||
// Garage
|
||||
if (s.includes('cobweb') || s.includes('spider') || s.includes('toile') || s.includes('araignée') || s.includes('araignee') || s.includes('spinnennetz') || s.includes('telaraña') || s.includes('telarana') || s.includes('clear_cobwebs')) return 'cobweb';
|
||||
if (s.includes('chemical') || s.includes('produit chimique') || s.includes('chemikalie') || s.includes('químico') || s.includes('quimico') || s.includes('check_chemicals')) return 'chemicals';
|
||||
if (s.includes('garage door') || s.includes('porte de garage') || s.includes('garagentor') || s.includes('puerta de garaje') || s.includes('door_tracks')) return 'garagedoor';
|
||||
if (s.includes('tool') || s.includes('workbench') || s.includes('outil') || s.includes('werkzeug') || s.includes('herramienta') || s.includes('power_tools') || s.includes('organize_tools') || s.includes('clean_workbench')) return 'tools';
|
||||
|
||||
// Organize
|
||||
if (s.includes('closet') || s.includes('wardrobe') || s.includes('penderie') || s.includes('kleiderschrank') || s.includes('armario') || s.includes('organize_closet')) return 'closet';
|
||||
if (s.includes('drawer') || s.includes('filing') || s.includes('tiroir') || s.includes('schublade') || s.includes('cajón') || s.includes('cajon') || s.includes('organize_drawers') || s.includes('organize_cabinets')) return 'drawer';
|
||||
if (s.includes('shelf') || s.includes('shelv') || s.includes('étagère') || s.includes('etagere') || s.includes('regal') || s.includes('estante') || s.includes('organize_shelves') || s.includes('storage')) return 'shelf';
|
||||
|
||||
// Trash
|
||||
if (s.includes('trash') || s.includes('recycl') || s.includes('waste') || s.includes('compost') || s.includes('poubelle') || s.includes('müll') || s.includes('muell') || s.includes('basura') || s.includes('empty_trash') || s.includes('paper_trash') || s.includes('sort_recycling')) return 'trash';
|
||||
|
||||
// Tidy / general
|
||||
if (s.includes('tidy') || s.includes('ranger') || s.includes('aufräum') || s.includes('aufraeum') || s.includes('ordenar') || s.includes('tidy_up') || s.includes('put_things')) return 'broom';
|
||||
|
||||
return 'sparkle';
|
||||
}
|
||||
17
server/tsconfig.json
Normal file
17
server/tsconfig.json
Normal file
|
|
@ -0,0 +1,17 @@
|
|||
{
|
||||
"compilerOptions": {
|
||||
"target": "ES2022",
|
||||
"module": "commonjs",
|
||||
"lib": ["ES2022"],
|
||||
"outDir": "./dist",
|
||||
"rootDir": "./src",
|
||||
"strict": true,
|
||||
"esModuleInterop": true,
|
||||
"skipLibCheck": true,
|
||||
"forceConsistentCasingInFileNames": true,
|
||||
"resolveJsonModule": true,
|
||||
"declaration": false
|
||||
},
|
||||
"include": ["src/**/*"],
|
||||
"exclude": ["node_modules", "dist"]
|
||||
}
|
||||
Loading…
Reference in a new issue