Compare commits
10
Commits
640745925a
...
3cce2158e9
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
3cce2158e9
|
||
|
|
92b1681241
|
||
|
|
440cbbb671
|
||
|
|
dc1b9e9cc0
|
||
|
|
dbd9a4ddb0
|
||
|
|
0958bd365b
|
||
|
|
5fbf30a70b
|
||
|
|
5b4936903a
|
||
|
|
680db7dce0
|
||
|
|
0751ee5588
|
@@ -23,6 +23,8 @@ FRONTEND_ORIGINS=https://localhost,https://127.0.0.1
|
|||||||
# Keep false unless you intentionally want fail-open rate limits / captcha.
|
# Keep false unless you intentionally want fail-open rate limits / captcha.
|
||||||
DEV_MODE=false
|
DEV_MODE=false
|
||||||
SEED_CURRICULUM=false
|
SEED_CURRICULUM=false
|
||||||
|
# One registration per client IP. Keep false behind NAT / shared egress (default).
|
||||||
|
REGISTRATION_ENFORCE_IP=false
|
||||||
# METRICS_TOKEN=
|
# METRICS_TOKEN=
|
||||||
# TRUSTED_PROXY_CIDRS=10.0.0.0/8,172.16.0.0/12,192.168.0.0/16,127.0.0.0/8,::1/128
|
# TRUSTED_PROXY_CIDRS=10.0.0.0/8,172.16.0.0/12,192.168.0.0/16,127.0.0.0/8,::1/128
|
||||||
|
|
||||||
|
|||||||
@@ -23,6 +23,8 @@ FRONTEND_ORIGINS=https://app.example.com
|
|||||||
|
|
||||||
DEV_MODE=false
|
DEV_MODE=false
|
||||||
SEED_CURRICULUM=false
|
SEED_CURRICULUM=false
|
||||||
|
# Keep false behind NAT until the edge forwards real client IPs.
|
||||||
|
REGISTRATION_ENFORCE_IP=false
|
||||||
METRICS_TOKEN=replace-with-metrics-scrape-token
|
METRICS_TOKEN=replace-with-metrics-scrape-token
|
||||||
# TRUSTED_PROXY_CIDRS=10.0.0.0/8,172.16.0.0/12,192.168.0.0/16
|
# TRUSTED_PROXY_CIDRS=10.0.0.0/8,172.16.0.0/12,192.168.0.0/16
|
||||||
|
|
||||||
|
|||||||
@@ -0,0 +1,235 @@
|
|||||||
|
GNU AFFERO GENERAL PUBLIC LICENSE
|
||||||
|
Version 3, 19 November 2007
|
||||||
|
|
||||||
|
Copyright (C) 2007 Free Software Foundation, Inc. <http://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 <http://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 <http://www.gnu.org/licenses/>.
|
||||||
@@ -130,16 +130,8 @@ func (s *Server) handleRegisterInvite(w http.ResponseWriter, r *http.Request) {
|
|||||||
return
|
return
|
||||||
}
|
}
|
||||||
|
|
||||||
ip := clientAddress(r)
|
ip, ok := s.registrationClientIP(w, r)
|
||||||
if ip == "" || ip == "unknown" {
|
if !ok {
|
||||||
writeErr(w, http.StatusBadRequest, "آدرس شبکه شناسایی نشد")
|
|
||||||
return
|
|
||||||
}
|
|
||||||
if taken, err := s.store.HasRegistrationIP(r.Context(), ip); err != nil {
|
|
||||||
writeErr(w, http.StatusInternalServerError, "بررسی محدودیت ثبتنام ممکن نشد")
|
|
||||||
return
|
|
||||||
} else if taken {
|
|
||||||
writeErr(w, http.StatusConflict, "از این شبکه قبلاً ثبتنام انجام شده است")
|
|
||||||
return
|
return
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|||||||
@@ -130,6 +130,7 @@ func TestInviteRevoke(t *testing.T) {
|
|||||||
}
|
}
|
||||||
|
|
||||||
func TestInviteDuplicatePhoneAndIP(t *testing.T) {
|
func TestInviteDuplicatePhoneAndIP(t *testing.T) {
|
||||||
|
t.Setenv("REGISTRATION_ENFORCE_IP", "true")
|
||||||
e := setup(t)
|
e := setup(t)
|
||||||
inv := createInvite(t, e, 5, "", nil)
|
inv := createInvite(t, e, 5, "", nil)
|
||||||
token := inv["token"].(string)
|
token := inv["token"].(string)
|
||||||
|
|||||||
@@ -27,6 +27,29 @@ func (s *Server) registrationRequireWhitelist(r *http.Request) bool {
|
|||||||
return s.settingTruthy(r, "registration_require_whitelist", true)
|
return s.settingTruthy(r, "registration_require_whitelist", true)
|
||||||
}
|
}
|
||||||
|
|
||||||
|
// registrationClientIP returns the IP to bind to a registration when enforcement is on.
|
||||||
|
// When REGISTRATION_ENFORCE_IP is false (default), returns "" so NAT / shared egress is ignored.
|
||||||
|
func (s *Server) registrationClientIP(w http.ResponseWriter, r *http.Request) (string, bool) {
|
||||||
|
if s.cfg == nil || !s.cfg.RegistrationEnforceIP {
|
||||||
|
return "", true
|
||||||
|
}
|
||||||
|
ip := clientAddress(r)
|
||||||
|
if ip == "" || ip == "unknown" {
|
||||||
|
writeErr(w, http.StatusBadRequest, "آدرس شبکه شناسایی نشد")
|
||||||
|
return "", false
|
||||||
|
}
|
||||||
|
taken, err := s.store.HasRegistrationIP(r.Context(), ip)
|
||||||
|
if err != nil {
|
||||||
|
writeErr(w, http.StatusInternalServerError, "بررسی محدودیت ثبتنام ممکن نشد")
|
||||||
|
return "", false
|
||||||
|
}
|
||||||
|
if taken {
|
||||||
|
writeErr(w, http.StatusConflict, "از این شبکه قبلاً ثبتنام انجام شده است")
|
||||||
|
return "", false
|
||||||
|
}
|
||||||
|
return ip, true
|
||||||
|
}
|
||||||
|
|
||||||
func (s *Server) handleRegisterStatus(w http.ResponseWriter, r *http.Request) {
|
func (s *Server) handleRegisterStatus(w http.ResponseWriter, r *http.Request) {
|
||||||
writeJSON(w, http.StatusOK, map[string]any{
|
writeJSON(w, http.StatusOK, map[string]any{
|
||||||
"enabled": s.registrationEnabled(r),
|
"enabled": s.registrationEnabled(r),
|
||||||
@@ -83,16 +106,8 @@ func (s *Server) handleRegister(w http.ResponseWriter, r *http.Request) {
|
|||||||
return
|
return
|
||||||
}
|
}
|
||||||
|
|
||||||
ip := clientAddress(r)
|
ip, ok := s.registrationClientIP(w, r)
|
||||||
if ip == "" || ip == "unknown" {
|
if !ok {
|
||||||
writeErr(w, http.StatusBadRequest, "آدرس شبکه شناسایی نشد")
|
|
||||||
return
|
|
||||||
}
|
|
||||||
if taken, err := s.store.HasRegistrationIP(r.Context(), ip); err != nil {
|
|
||||||
writeErr(w, http.StatusInternalServerError, "بررسی محدودیت ثبتنام ممکن نشد")
|
|
||||||
return
|
|
||||||
} else if taken {
|
|
||||||
writeErr(w, http.StatusConflict, "از این شبکه قبلاً ثبتنام انجام شده است")
|
|
||||||
return
|
return
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|||||||
@@ -261,6 +261,7 @@ func TestRegisterDuplicatePhone(t *testing.T) {
|
|||||||
}
|
}
|
||||||
|
|
||||||
func TestRegisterSameIPRejected(t *testing.T) {
|
func TestRegisterSameIPRejected(t *testing.T) {
|
||||||
|
t.Setenv("REGISTRATION_ENFORCE_IP", "true")
|
||||||
e := setup(t)
|
e := setup(t)
|
||||||
enableRegistration(t, e)
|
enableRegistration(t, e)
|
||||||
whitelistPhones(t, e, "09121110007", "09121110008")
|
whitelistPhones(t, e, "09121110007", "09121110008")
|
||||||
@@ -278,7 +279,27 @@ func TestRegisterSameIPRejected(t *testing.T) {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
func TestRegisterSameIPAllowedWhenEnforcementOff(t *testing.T) {
|
||||||
|
t.Setenv("REGISTRATION_ENFORCE_IP", "false")
|
||||||
|
e := setup(t)
|
||||||
|
enableRegistration(t, e)
|
||||||
|
whitelistPhones(t, e, "09121110007", "09121110008")
|
||||||
|
|
||||||
|
headers := map[string]string{"X-Forwarded-For": "203.0.113.40"}
|
||||||
|
code, body := e.doHeaders(t, "POST", "/api/auth/register", "", headers,
|
||||||
|
registerBody(t, e, "09121110007", "reg-ipoff1@test.dev", "regipoff1"))
|
||||||
|
if code != http.StatusCreated {
|
||||||
|
t.Fatalf("first: %d %v", code, body)
|
||||||
|
}
|
||||||
|
code, body = e.doHeaders(t, "POST", "/api/auth/register", "", headers,
|
||||||
|
registerBody(t, e, "09121110008", "reg-ipoff2@test.dev", "regipoff2"))
|
||||||
|
if code != http.StatusCreated {
|
||||||
|
t.Fatalf("same IP must be allowed when REGISTRATION_ENFORCE_IP=false: %d %v", code, body)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
func TestRegisterUsesForwardedIP(t *testing.T) {
|
func TestRegisterUsesForwardedIP(t *testing.T) {
|
||||||
|
t.Setenv("REGISTRATION_ENFORCE_IP", "true")
|
||||||
e := setup(t)
|
e := setup(t)
|
||||||
enableRegistration(t, e)
|
enableRegistration(t, e)
|
||||||
whitelistPhones(t, e, "09121110009", "09121110010", "09121110011")
|
whitelistPhones(t, e, "09121110009", "09121110010", "09121110011")
|
||||||
|
|||||||
@@ -46,6 +46,9 @@ type Config struct {
|
|||||||
PhysicalCertEnabled bool
|
PhysicalCertEnabled bool
|
||||||
PhysicalCertPriceIRR int
|
PhysicalCertPriceIRR int
|
||||||
PhysicalCertWindowDays int
|
PhysicalCertWindowDays int
|
||||||
|
// RegistrationEnforceIP limits one successful registration per client IP.
|
||||||
|
// Default false: behind NAT / shared egress the peer IP is not a real client identity.
|
||||||
|
RegistrationEnforceIP bool
|
||||||
}
|
}
|
||||||
|
|
||||||
func getEnv(key, fallback string) string {
|
func getEnv(key, fallback string) string {
|
||||||
@@ -140,6 +143,7 @@ func Load() *Config {
|
|||||||
PhysicalCertEnabled: getEnv("PHYSICAL_CERT_ENABLED", "false") == "true",
|
PhysicalCertEnabled: getEnv("PHYSICAL_CERT_ENABLED", "false") == "true",
|
||||||
PhysicalCertPriceIRR: getEnvInt("PHYSICAL_CERT_PRICE_IRR", 2_500_000),
|
PhysicalCertPriceIRR: getEnvInt("PHYSICAL_CERT_PRICE_IRR", 2_500_000),
|
||||||
PhysicalCertWindowDays: getEnvInt("PHYSICAL_CERT_WINDOW_DAYS", 30),
|
PhysicalCertWindowDays: getEnvInt("PHYSICAL_CERT_WINDOW_DAYS", 30),
|
||||||
|
RegistrationEnforceIP: getEnv("REGISTRATION_ENFORCE_IP", "false") == "true",
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|||||||
@@ -344,16 +344,14 @@ func EvaluateInviteAvailability(inv *models.RegistrationInvite, now time.Time) e
|
|||||||
return nil
|
return nil
|
||||||
}
|
}
|
||||||
|
|
||||||
// RegisterInviteStudent creates a student, consumes the IP, and atomically consumes one invite seat.
|
// RegisterInviteStudent creates a student, optionally records the client IP, and consumes one invite seat.
|
||||||
|
// Empty ip skips one-registration-per-IP enforcement (NAT / shared egress).
|
||||||
func (s *Store) RegisterInviteStudent(
|
func (s *Store) RegisterInviteStudent(
|
||||||
ctx context.Context,
|
ctx context.Context,
|
||||||
inviteID int64,
|
inviteID int64,
|
||||||
name, email, username, passwordHash, phone, securityQuestion, securityAnswerHash, ip string,
|
name, email, username, passwordHash, phone, securityQuestion, securityAnswerHash, ip string,
|
||||||
) (*models.User, error) {
|
) (*models.User, error) {
|
||||||
ip = strings.TrimSpace(ip)
|
ip = strings.TrimSpace(ip)
|
||||||
if ip == "" {
|
|
||||||
return nil, errors.New("empty registration ip")
|
|
||||||
}
|
|
||||||
tx, err := s.pool.Begin(ctx)
|
tx, err := s.pool.Begin(ctx)
|
||||||
if err != nil {
|
if err != nil {
|
||||||
return nil, err
|
return nil, err
|
||||||
@@ -366,12 +364,14 @@ func (s *Store) RegisterInviteStudent(
|
|||||||
return nil, ErrPhoneBlacklisted
|
return nil, ErrPhoneBlacklisted
|
||||||
}
|
}
|
||||||
|
|
||||||
var taken bool
|
if ip != "" {
|
||||||
if err := tx.QueryRow(ctx, `SELECT EXISTS(SELECT 1 FROM registration_ips WHERE ip=$1)`, ip).Scan(&taken); err != nil {
|
var taken bool
|
||||||
return nil, err
|
if err := tx.QueryRow(ctx, `SELECT EXISTS(SELECT 1 FROM registration_ips WHERE ip=$1)`, ip).Scan(&taken); err != nil {
|
||||||
}
|
return nil, err
|
||||||
if taken {
|
}
|
||||||
return nil, ErrRegistrationIPTaken
|
if taken {
|
||||||
|
return nil, ErrRegistrationIPTaken
|
||||||
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
tag, err := tx.Exec(ctx, `
|
tag, err := tx.Exec(ctx, `
|
||||||
@@ -436,12 +436,14 @@ func (s *Store) RegisterInviteStudent(
|
|||||||
ON CONFLICT (user_id) DO NOTHING`, u.ID); err != nil {
|
ON CONFLICT (user_id) DO NOTHING`, u.ID); err != nil {
|
||||||
return nil, err
|
return nil, err
|
||||||
}
|
}
|
||||||
if _, err := tx.Exec(ctx, `
|
if ip != "" {
|
||||||
INSERT INTO registration_ips (ip, user_id) VALUES ($1, $2)`, ip, u.ID); err != nil {
|
if _, err := tx.Exec(ctx, `
|
||||||
if isUniqueViolation(err) {
|
INSERT INTO registration_ips (ip, user_id) VALUES ($1, $2)`, ip, u.ID); err != nil {
|
||||||
return nil, ErrRegistrationIPTaken
|
if isUniqueViolation(err) {
|
||||||
|
return nil, ErrRegistrationIPTaken
|
||||||
|
}
|
||||||
|
return nil, err
|
||||||
}
|
}
|
||||||
return nil, err
|
|
||||||
}
|
}
|
||||||
if err := tx.Commit(ctx); err != nil {
|
if err := tx.Commit(ctx); err != nil {
|
||||||
return nil, err
|
return nil, err
|
||||||
|
|||||||
@@ -331,18 +331,15 @@ func (s *Store) HasRegistrationIP(ctx context.Context, ip string) (bool, error)
|
|||||||
return exists, err
|
return exists, err
|
||||||
}
|
}
|
||||||
|
|
||||||
// RegisterPublicStudent creates a student and consumes the IP atomically.
|
// RegisterPublicStudent creates a student and optionally records the client IP.
|
||||||
// When requireWhitelist is true, the phone must be an available whitelist entry.
|
// When requireWhitelist is true, the phone must be an available whitelist entry.
|
||||||
// Concurrent same-IP registrations: one commits; the other rolls back on unique IP conflict.
|
// Empty ip skips one-registration-per-IP enforcement (NAT / shared egress).
|
||||||
func (s *Store) RegisterPublicStudent(
|
func (s *Store) RegisterPublicStudent(
|
||||||
ctx context.Context,
|
ctx context.Context,
|
||||||
name, email, username, passwordHash, phone, securityQuestion, securityAnswerHash, ip string,
|
name, email, username, passwordHash, phone, securityQuestion, securityAnswerHash, ip string,
|
||||||
requireWhitelist bool,
|
requireWhitelist bool,
|
||||||
) (*models.User, error) {
|
) (*models.User, error) {
|
||||||
ip = strings.TrimSpace(ip)
|
ip = strings.TrimSpace(ip)
|
||||||
if ip == "" {
|
|
||||||
return nil, errors.New("empty registration ip")
|
|
||||||
}
|
|
||||||
tx, err := s.pool.Begin(ctx)
|
tx, err := s.pool.Begin(ctx)
|
||||||
if err != nil {
|
if err != nil {
|
||||||
return nil, err
|
return nil, err
|
||||||
@@ -355,12 +352,14 @@ func (s *Store) RegisterPublicStudent(
|
|||||||
return nil, ErrPhoneBlacklisted
|
return nil, ErrPhoneBlacklisted
|
||||||
}
|
}
|
||||||
|
|
||||||
var taken bool
|
if ip != "" {
|
||||||
if err := tx.QueryRow(ctx, `SELECT EXISTS(SELECT 1 FROM registration_ips WHERE ip=$1)`, ip).Scan(&taken); err != nil {
|
var taken bool
|
||||||
return nil, err
|
if err := tx.QueryRow(ctx, `SELECT EXISTS(SELECT 1 FROM registration_ips WHERE ip=$1)`, ip).Scan(&taken); err != nil {
|
||||||
}
|
return nil, err
|
||||||
if taken {
|
}
|
||||||
return nil, ErrRegistrationIPTaken
|
if taken {
|
||||||
|
return nil, ErrRegistrationIPTaken
|
||||||
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
row := tx.QueryRow(ctx, `
|
row := tx.QueryRow(ctx, `
|
||||||
@@ -380,12 +379,14 @@ func (s *Store) RegisterPublicStudent(
|
|||||||
ON CONFLICT (user_id) DO NOTHING`, u.ID); err != nil {
|
ON CONFLICT (user_id) DO NOTHING`, u.ID); err != nil {
|
||||||
return nil, err
|
return nil, err
|
||||||
}
|
}
|
||||||
if _, err := tx.Exec(ctx, `
|
if ip != "" {
|
||||||
INSERT INTO registration_ips (ip, user_id) VALUES ($1, $2)`, ip, u.ID); err != nil {
|
if _, err := tx.Exec(ctx, `
|
||||||
if isUniqueViolation(err) {
|
INSERT INTO registration_ips (ip, user_id) VALUES ($1, $2)`, ip, u.ID); err != nil {
|
||||||
return nil, ErrRegistrationIPTaken
|
if isUniqueViolation(err) {
|
||||||
|
return nil, ErrRegistrationIPTaken
|
||||||
|
}
|
||||||
|
return nil, err
|
||||||
}
|
}
|
||||||
return nil, err
|
|
||||||
}
|
}
|
||||||
if err := tx.Commit(ctx); err != nil {
|
if err := tx.Commit(ctx); err != nil {
|
||||||
return nil, err
|
return nil, err
|
||||||
|
|||||||
@@ -0,0 +1,62 @@
|
|||||||
|
# Pargar deploy
|
||||||
|
|
||||||
|
Full deployment guide and production checklist: **[`docs/deployment.md`](../docs/deployment.md)**
|
||||||
|
Security & secrets: [`docs/security.md`](../docs/security.md) · Ops / backup: [`docs/operations.md`](../docs/operations.md)
|
||||||
|
|
||||||
|
Edge: **Traefik v3.7** (Compose needs Traefik ≥3.6.1 on Docker Engine 29+).
|
||||||
|
|
||||||
|
## Layout
|
||||||
|
|
||||||
|
```text
|
||||||
|
deploy/
|
||||||
|
compose/
|
||||||
|
compose.yaml # shared app + data + Traefik labels
|
||||||
|
compose.dev.yaml # laptop TLS default, DB ports on 127.0.0.1
|
||||||
|
compose.prod.yaml # Let's Encrypt, no host DB ports
|
||||||
|
traefik/dynamic/ # middlewares
|
||||||
|
helm/pargar/ # chart + values-k3s / values-prod
|
||||||
|
scripts/
|
||||||
|
compose-dev.sh compose-prod.sh k3s-load-images.sh helm-k3s.sh backup.sh
|
||||||
|
```
|
||||||
|
|
||||||
|
## Compose — development
|
||||||
|
|
||||||
|
```bash
|
||||||
|
cp .env.example .env
|
||||||
|
./scripts/compose-dev.sh up -d --build
|
||||||
|
```
|
||||||
|
|
||||||
|
- App: https://localhost
|
||||||
|
- Traefik dashboard: http://127.0.0.1:8088
|
||||||
|
|
||||||
|
## Compose — production
|
||||||
|
|
||||||
|
```bash
|
||||||
|
cp .env.prod.example .env.prod
|
||||||
|
./scripts/compose-prod.sh up -d --build
|
||||||
|
```
|
||||||
|
|
||||||
|
## k3s + Helm
|
||||||
|
|
||||||
|
```bash
|
||||||
|
./scripts/k3s-load-images.sh
|
||||||
|
./scripts/helm-k3s.sh
|
||||||
|
curl -k https://pargar.local/api/health
|
||||||
|
```
|
||||||
|
|
||||||
|
```bash
|
||||||
|
kubectl -n pargar get secret pargar-app -o jsonpath='{.data.admin-password}' | base64 -d; echo
|
||||||
|
```
|
||||||
|
|
||||||
|
Values: `values.yaml` · `values-k3s.yaml` · `values-prod.yaml`
|
||||||
|
Lint: `helm lint ./deploy/helm/pargar -f ./deploy/helm/pargar/values-k3s.yaml`
|
||||||
|
|
||||||
|
## Routing
|
||||||
|
|
||||||
|
| Path | Service |
|
||||||
|
|------|---------|
|
||||||
|
| `/api/*`, `/media/*` | backend |
|
||||||
|
| `/api/certificates/*`, `/c/*` | backend + noindex |
|
||||||
|
| else | frontend |
|
||||||
|
|
||||||
|
WS: `/api/ws` via Traefik.
|
||||||
@@ -0,0 +1,96 @@
|
|||||||
|
# Local / staging-on-laptop overlay (Traefik + published data ports + mild limits).
|
||||||
|
# Usage: see compose.yaml header or scripts/compose-dev.sh
|
||||||
|
|
||||||
|
services:
|
||||||
|
postgres:
|
||||||
|
ports:
|
||||||
|
- "127.0.0.1:5432:5432"
|
||||||
|
deploy:
|
||||||
|
resources:
|
||||||
|
limits:
|
||||||
|
memory: 512M
|
||||||
|
|
||||||
|
redis:
|
||||||
|
ports:
|
||||||
|
- "127.0.0.1:6379:6379"
|
||||||
|
deploy:
|
||||||
|
resources:
|
||||||
|
limits:
|
||||||
|
memory: 256M
|
||||||
|
|
||||||
|
rustfs:
|
||||||
|
environment:
|
||||||
|
RUSTFS_CONSOLE_ENABLE: "true"
|
||||||
|
ports:
|
||||||
|
- "127.0.0.1:9000:9000"
|
||||||
|
- "127.0.0.1:9001:9001"
|
||||||
|
deploy:
|
||||||
|
resources:
|
||||||
|
limits:
|
||||||
|
memory: 512M
|
||||||
|
|
||||||
|
backend:
|
||||||
|
environment:
|
||||||
|
DEV_MODE: ${DEV_MODE:-false}
|
||||||
|
SEED_CURRICULUM: ${SEED_CURRICULUM:-false}
|
||||||
|
deploy:
|
||||||
|
resources:
|
||||||
|
limits:
|
||||||
|
memory: 512M
|
||||||
|
|
||||||
|
frontend:
|
||||||
|
deploy:
|
||||||
|
resources:
|
||||||
|
limits:
|
||||||
|
memory: 512M
|
||||||
|
|
||||||
|
traefik:
|
||||||
|
# v3.6.1+ required for Docker Engine 29+ API negotiation
|
||||||
|
image: traefik@sha256:24841fe2de7304c149343d877d2923b4c8800a38ba015dea9174c23b20e344a0
|
||||||
|
restart: unless-stopped
|
||||||
|
security_opt:
|
||||||
|
- no-new-privileges:true
|
||||||
|
command:
|
||||||
|
- --providers.docker=true
|
||||||
|
- --providers.docker.exposedbydefault=false
|
||||||
|
- --providers.docker.network=pargar_pargar
|
||||||
|
- --providers.file.directory=/etc/traefik/dynamic
|
||||||
|
- --providers.file.watch=true
|
||||||
|
- --entrypoints.web.address=:80
|
||||||
|
- --entrypoints.websecure.address=:443
|
||||||
|
- --entrypoints.web.http.redirections.entrypoint.to=websecure
|
||||||
|
- --entrypoints.web.http.redirections.entrypoint.scheme=https
|
||||||
|
- --entrypoints.web.http.redirections.entrypoint.permanent=true
|
||||||
|
- --entrypoints.web.http.aliasHeadersStrategy=delete
|
||||||
|
- --entrypoints.websecure.http.aliasHeadersStrategy=delete
|
||||||
|
# Dev: Traefik default certificate (browser warning expected on localhost).
|
||||||
|
- --api.dashboard=true
|
||||||
|
- --api.insecure=true
|
||||||
|
- --log.level=INFO
|
||||||
|
- --accesslog=true
|
||||||
|
- --ping=true
|
||||||
|
- --global.checkNewVersion=false
|
||||||
|
ports:
|
||||||
|
- "80:80"
|
||||||
|
- "443:443"
|
||||||
|
# Dashboard only on loopback
|
||||||
|
- "127.0.0.1:8088:8080"
|
||||||
|
volumes:
|
||||||
|
- /var/run/docker.sock:/var/run/docker.sock:ro
|
||||||
|
- ../traefik/dynamic:/etc/traefik/dynamic:ro
|
||||||
|
depends_on:
|
||||||
|
backend:
|
||||||
|
condition: service_healthy
|
||||||
|
frontend:
|
||||||
|
condition: service_healthy
|
||||||
|
healthcheck:
|
||||||
|
test: ["CMD", "traefik", "healthcheck", "--ping"]
|
||||||
|
interval: 10s
|
||||||
|
timeout: 3s
|
||||||
|
retries: 10
|
||||||
|
deploy:
|
||||||
|
resources:
|
||||||
|
limits:
|
||||||
|
memory: 256M
|
||||||
|
networks:
|
||||||
|
- pargar
|
||||||
@@ -0,0 +1,112 @@
|
|||||||
|
# Internet-facing production overlay (Traefik + Let's Encrypt, no host DB ports).
|
||||||
|
# Usage:
|
||||||
|
# docker compose -f deploy/compose/compose.yaml -f deploy/compose/compose.prod.yaml \
|
||||||
|
# --env-file .env.prod up -d --build
|
||||||
|
#
|
||||||
|
# Requires: DOMAIN (public DNS), ACME_EMAIL, PUBLIC_URL=https://$DOMAIN, strong secrets.
|
||||||
|
|
||||||
|
services:
|
||||||
|
postgres:
|
||||||
|
# No host ports — only reachable on the compose network.
|
||||||
|
deploy:
|
||||||
|
resources:
|
||||||
|
limits:
|
||||||
|
memory: 1G
|
||||||
|
|
||||||
|
redis:
|
||||||
|
deploy:
|
||||||
|
resources:
|
||||||
|
limits:
|
||||||
|
memory: 512M
|
||||||
|
|
||||||
|
rustfs:
|
||||||
|
environment:
|
||||||
|
RUSTFS_CONSOLE_ENABLE: "false"
|
||||||
|
deploy:
|
||||||
|
resources:
|
||||||
|
limits:
|
||||||
|
memory: 1G
|
||||||
|
|
||||||
|
backend:
|
||||||
|
environment:
|
||||||
|
DEV_MODE: "false"
|
||||||
|
SEED_CURRICULUM: "false"
|
||||||
|
labels:
|
||||||
|
- traefik.http.routers.pargar-api.tls.certresolver=le
|
||||||
|
- traefik.http.routers.pargar-cert-api.tls.certresolver=le
|
||||||
|
deploy:
|
||||||
|
resources:
|
||||||
|
limits:
|
||||||
|
memory: 1G
|
||||||
|
reservations:
|
||||||
|
memory: 256M
|
||||||
|
|
||||||
|
frontend:
|
||||||
|
labels:
|
||||||
|
- traefik.http.routers.pargar-web.tls.certresolver=le
|
||||||
|
- traefik.http.routers.pargar-cert-web.tls.certresolver=le
|
||||||
|
deploy:
|
||||||
|
resources:
|
||||||
|
limits:
|
||||||
|
memory: 1G
|
||||||
|
reservations:
|
||||||
|
memory: 256M
|
||||||
|
|
||||||
|
traefik:
|
||||||
|
# v3.6.1+ required for Docker Engine 29+ API negotiation
|
||||||
|
image: traefik@sha256:24841fe2de7304c149343d877d2923b4c8800a38ba015dea9174c23b20e344a0
|
||||||
|
restart: unless-stopped
|
||||||
|
security_opt:
|
||||||
|
- no-new-privileges:true
|
||||||
|
command:
|
||||||
|
- --providers.docker=true
|
||||||
|
- --providers.docker.exposedbydefault=false
|
||||||
|
- --providers.docker.network=pargar_pargar
|
||||||
|
- --providers.file.directory=/etc/traefik/dynamic
|
||||||
|
- --providers.file.watch=true
|
||||||
|
- --entrypoints.web.address=:80
|
||||||
|
- --entrypoints.websecure.address=:443
|
||||||
|
- --entrypoints.web.http.redirections.entrypoint.to=websecure
|
||||||
|
- --entrypoints.web.http.redirections.entrypoint.scheme=https
|
||||||
|
- --entrypoints.web.http.redirections.entrypoint.permanent=true
|
||||||
|
- --entrypoints.web.http.aliasHeadersStrategy=delete
|
||||||
|
- --entrypoints.websecure.http.aliasHeadersStrategy=delete
|
||||||
|
- --certificatesresolvers.le.acme.email=${ACME_EMAIL:?ACME_EMAIL must be set}
|
||||||
|
- --certificatesresolvers.le.acme.storage=/data/acme.json
|
||||||
|
- --certificatesresolvers.le.acme.httpchallenge=true
|
||||||
|
- --certificatesresolvers.le.acme.httpchallenge.entrypoint=web
|
||||||
|
- --api.dashboard=false
|
||||||
|
- --log.level=WARN
|
||||||
|
- --accesslog=true
|
||||||
|
- --ping=true
|
||||||
|
- --global.checkNewVersion=false
|
||||||
|
- --serversTransport.forwardingTimeouts.dialTimeout=10s
|
||||||
|
- --serversTransport.forwardingTimeouts.responseHeaderTimeout=60s
|
||||||
|
ports:
|
||||||
|
- "80:80"
|
||||||
|
- "[::]:80:80"
|
||||||
|
- "443:443"
|
||||||
|
- "[::]:443:443"
|
||||||
|
volumes:
|
||||||
|
- /var/run/docker.sock:/var/run/docker.sock:ro
|
||||||
|
- ../traefik/dynamic:/etc/traefik/dynamic:ro
|
||||||
|
- traefik_data:/data
|
||||||
|
depends_on:
|
||||||
|
backend:
|
||||||
|
condition: service_healthy
|
||||||
|
frontend:
|
||||||
|
condition: service_healthy
|
||||||
|
healthcheck:
|
||||||
|
test: ["CMD", "traefik", "healthcheck", "--ping"]
|
||||||
|
interval: 10s
|
||||||
|
timeout: 3s
|
||||||
|
retries: 10
|
||||||
|
deploy:
|
||||||
|
resources:
|
||||||
|
limits:
|
||||||
|
memory: 256M
|
||||||
|
networks:
|
||||||
|
- pargar
|
||||||
|
|
||||||
|
volumes:
|
||||||
|
traefik_data:
|
||||||
@@ -0,0 +1,184 @@
|
|||||||
|
# Shared services — always combine with compose.dev.yaml or compose.prod.yaml:
|
||||||
|
#
|
||||||
|
# Dev: docker compose -f deploy/compose/compose.yaml -f deploy/compose/compose.dev.yaml up -d --build
|
||||||
|
# Prod: docker compose -f deploy/compose/compose.yaml -f deploy/compose/compose.prod.yaml --env-file .env.prod up -d --build
|
||||||
|
#
|
||||||
|
# Or use scripts/compose-dev.sh / scripts/compose-prod.sh / root docker-compose.yml (dev default).
|
||||||
|
|
||||||
|
name: pargar
|
||||||
|
|
||||||
|
x-backend-env: &backend-env
|
||||||
|
PORT: "8080"
|
||||||
|
DATABASE_URL: postgres://${POSTGRES_USER:-pargar}:${POSTGRES_PASSWORD:?POSTGRES_PASSWORD must be set}@postgres:5432/${POSTGRES_DB:-pargar}?sslmode=disable
|
||||||
|
REDIS_URL: redis://:${REDIS_PASSWORD:?REDIS_PASSWORD must be set}@redis:6379
|
||||||
|
JWT_SECRET: ${JWT_SECRET:?JWT_SECRET must be set}
|
||||||
|
PUBLIC_URL: ${PUBLIC_URL:?PUBLIC_URL must be set}
|
||||||
|
FRONTEND_ORIGINS: ${FRONTEND_ORIGINS:?FRONTEND_ORIGINS must be set}
|
||||||
|
METRICS_TOKEN: ${METRICS_TOKEN:-}
|
||||||
|
TRUSTED_PROXY_CIDRS: ${TRUSTED_PROXY_CIDRS:-}
|
||||||
|
STORAGE_DRIVER: s3
|
||||||
|
STORAGE_ENDPOINT: http://rustfs:9000
|
||||||
|
STORAGE_REGION: ${STORAGE_REGION:-us-east-1}
|
||||||
|
STORAGE_ACCESS_KEY: ${RUSTFS_ACCESS_KEY:?RUSTFS_ACCESS_KEY must be set}
|
||||||
|
STORAGE_SECRET_KEY: ${RUSTFS_SECRET_KEY:?RUSTFS_SECRET_KEY must be set}
|
||||||
|
STORAGE_BUCKET: ${STORAGE_BUCKET:-pargar}
|
||||||
|
SEED_CURRICULUM: ${SEED_CURRICULUM:-false}
|
||||||
|
REGISTRATION_ENFORCE_IP: ${REGISTRATION_ENFORCE_IP:-false}
|
||||||
|
ADMIN_NAME: ${ADMIN_NAME:-Admin}
|
||||||
|
ADMIN_USERNAME: ${ADMIN_USERNAME:-admin}
|
||||||
|
ADMIN_EMAIL: ${ADMIN_EMAIL:-admin@example.com}
|
||||||
|
ADMIN_PASSWORD: ${ADMIN_PASSWORD:?ADMIN_PASSWORD must be set}
|
||||||
|
OTEL_EXPORTER_OTLP_ENDPOINT: ${OTEL_EXPORTER_OTLP_ENDPOINT:-}
|
||||||
|
OTEL_SERVICE_NAME: ${OTEL_SERVICE_NAME:-pargar-api}
|
||||||
|
DONATION_ENABLED: ${DONATION_ENABLED:-true}
|
||||||
|
DONATION_NOTE: ${DONATION_NOTE:-}
|
||||||
|
PHYSICAL_CERT_ENABLED: ${PHYSICAL_CERT_ENABLED:-true}
|
||||||
|
PHYSICAL_CERT_PRICE_IRR: ${PHYSICAL_CERT_PRICE_IRR:-2500000}
|
||||||
|
PHYSICAL_CERT_WINDOW_DAYS: ${PHYSICAL_CERT_WINDOW_DAYS:-30}
|
||||||
|
|
||||||
|
services:
|
||||||
|
postgres:
|
||||||
|
image: postgres:16.4-alpine
|
||||||
|
restart: unless-stopped
|
||||||
|
environment:
|
||||||
|
POSTGRES_USER: ${POSTGRES_USER:-pargar}
|
||||||
|
POSTGRES_PASSWORD: ${POSTGRES_PASSWORD:?POSTGRES_PASSWORD must be set}
|
||||||
|
POSTGRES_DB: ${POSTGRES_DB:-pargar}
|
||||||
|
volumes:
|
||||||
|
- pgdata:/var/lib/postgresql/data
|
||||||
|
healthcheck:
|
||||||
|
test: ["CMD-SHELL", "pg_isready -U \"$$POSTGRES_USER\" -d \"$$POSTGRES_DB\""]
|
||||||
|
interval: 5s
|
||||||
|
timeout: 3s
|
||||||
|
retries: 20
|
||||||
|
networks:
|
||||||
|
- pargar
|
||||||
|
|
||||||
|
redis:
|
||||||
|
image: redis@sha256:858f009f9709ce576febc734aa78b8f6d624b82571f9ddb6bda4377c833b3499
|
||||||
|
restart: unless-stopped
|
||||||
|
command: ["redis-server", "--requirepass", "${REDIS_PASSWORD:?REDIS_PASSWORD must be set}", "--appendonly", "yes"]
|
||||||
|
volumes:
|
||||||
|
- redis_data:/data
|
||||||
|
healthcheck:
|
||||||
|
test: ["CMD", "redis-cli", "-a", "${REDIS_PASSWORD:?REDIS_PASSWORD must be set}", "ping"]
|
||||||
|
interval: 5s
|
||||||
|
timeout: 3s
|
||||||
|
retries: 20
|
||||||
|
networks:
|
||||||
|
- pargar
|
||||||
|
|
||||||
|
rustfs:
|
||||||
|
image: rustfs/rustfs@sha256:1803faef57627e2d9c2e7d89d655d712ddded5389040054987163043fecb6a3c
|
||||||
|
restart: unless-stopped
|
||||||
|
command: /data
|
||||||
|
environment:
|
||||||
|
RUSTFS_ACCESS_KEY: ${RUSTFS_ACCESS_KEY:?RUSTFS_ACCESS_KEY must be set}
|
||||||
|
RUSTFS_SECRET_KEY: ${RUSTFS_SECRET_KEY:?RUSTFS_SECRET_KEY must be set}
|
||||||
|
RUSTFS_ADDRESS: ":9000"
|
||||||
|
RUSTFS_CONSOLE_ADDRESS: ":9001"
|
||||||
|
RUSTFS_CONSOLE_ENABLE: ${RUSTFS_CONSOLE_ENABLE:-false}
|
||||||
|
volumes:
|
||||||
|
- rustfs_data:/data
|
||||||
|
healthcheck:
|
||||||
|
test: ["CMD", "wget", "--spider", "--quiet", "http://localhost:9000/health"]
|
||||||
|
interval: 5s
|
||||||
|
timeout: 3s
|
||||||
|
retries: 20
|
||||||
|
start_period: 10s
|
||||||
|
networks:
|
||||||
|
- pargar
|
||||||
|
|
||||||
|
backend:
|
||||||
|
build:
|
||||||
|
context: ../../backend
|
||||||
|
dockerfile: Dockerfile
|
||||||
|
image: ${BACKEND_IMAGE:-pargar-backend:local}
|
||||||
|
restart: unless-stopped
|
||||||
|
environment:
|
||||||
|
<<: *backend-env
|
||||||
|
DEV_MODE: ${DEV_MODE:-false}
|
||||||
|
depends_on:
|
||||||
|
postgres:
|
||||||
|
condition: service_healthy
|
||||||
|
redis:
|
||||||
|
condition: service_healthy
|
||||||
|
rustfs:
|
||||||
|
condition: service_healthy
|
||||||
|
expose:
|
||||||
|
- "8080"
|
||||||
|
healthcheck:
|
||||||
|
test: ["CMD", "wget", "--spider", "--quiet", "http://127.0.0.1:8080/api/health"]
|
||||||
|
interval: 5s
|
||||||
|
timeout: 3s
|
||||||
|
retries: 20
|
||||||
|
networks:
|
||||||
|
- pargar
|
||||||
|
labels:
|
||||||
|
- traefik.enable=true
|
||||||
|
- traefik.docker.network=pargar_pargar
|
||||||
|
# API + media (higher priority than frontend catch-all)
|
||||||
|
- traefik.http.routers.pargar-api.rule=Host(`${DOMAIN:-localhost}`) && (PathPrefix(`/api`) || PathPrefix(`/media`))
|
||||||
|
- traefik.http.routers.pargar-api.entrypoints=websecure
|
||||||
|
- traefik.http.routers.pargar-api.priority=100
|
||||||
|
- traefik.http.routers.pargar-api.tls=true
|
||||||
|
- traefik.http.routers.pargar-api.middlewares=security-headers@file,compress@file
|
||||||
|
- traefik.http.routers.pargar-api.service=pargar-api
|
||||||
|
- traefik.http.services.pargar-api.loadbalancer.server.port=8080
|
||||||
|
# Certificate public API — noindex
|
||||||
|
- traefik.http.routers.pargar-cert-api.rule=Host(`${DOMAIN:-localhost}`) && PathPrefix(`/api/certificates`)
|
||||||
|
- traefik.http.routers.pargar-cert-api.entrypoints=websecure
|
||||||
|
- traefik.http.routers.pargar-cert-api.priority=110
|
||||||
|
- traefik.http.routers.pargar-cert-api.tls=true
|
||||||
|
- traefik.http.routers.pargar-cert-api.middlewares=security-headers@file,compress@file,noindex@file
|
||||||
|
- traefik.http.routers.pargar-cert-api.service=pargar-api
|
||||||
|
|
||||||
|
frontend:
|
||||||
|
build:
|
||||||
|
context: ../../frontend
|
||||||
|
dockerfile: Dockerfile
|
||||||
|
args:
|
||||||
|
NEXT_PUBLIC_API_URL: ""
|
||||||
|
NEXT_PUBLIC_WS_URL: ""
|
||||||
|
image: ${FRONTEND_IMAGE:-pargar-frontend:local}
|
||||||
|
restart: unless-stopped
|
||||||
|
environment:
|
||||||
|
NODE_ENV: production
|
||||||
|
depends_on:
|
||||||
|
backend:
|
||||||
|
condition: service_healthy
|
||||||
|
expose:
|
||||||
|
- "3000"
|
||||||
|
healthcheck:
|
||||||
|
test: ["CMD", "wget", "--spider", "--quiet", "http://127.0.0.1:3000"]
|
||||||
|
interval: 10s
|
||||||
|
timeout: 3s
|
||||||
|
retries: 10
|
||||||
|
networks:
|
||||||
|
- pargar
|
||||||
|
labels:
|
||||||
|
- traefik.enable=true
|
||||||
|
- traefik.docker.network=pargar_pargar
|
||||||
|
- traefik.http.routers.pargar-web.rule=Host(`${DOMAIN:-localhost}`)
|
||||||
|
- traefik.http.routers.pargar-web.entrypoints=websecure
|
||||||
|
- traefik.http.routers.pargar-web.priority=1
|
||||||
|
- traefik.http.routers.pargar-web.tls=true
|
||||||
|
- traefik.http.routers.pargar-web.middlewares=security-headers@file,compress@file
|
||||||
|
- traefik.http.routers.pargar-web.service=pargar-web
|
||||||
|
- traefik.http.services.pargar-web.loadbalancer.server.port=3000
|
||||||
|
# Unlisted certificate pages
|
||||||
|
- traefik.http.routers.pargar-cert-web.rule=Host(`${DOMAIN:-localhost}`) && PathPrefix(`/c`)
|
||||||
|
- traefik.http.routers.pargar-cert-web.entrypoints=websecure
|
||||||
|
- traefik.http.routers.pargar-cert-web.priority=50
|
||||||
|
- traefik.http.routers.pargar-cert-web.tls=true
|
||||||
|
- traefik.http.routers.pargar-cert-web.middlewares=security-headers@file,compress@file,noindex@file
|
||||||
|
- traefik.http.routers.pargar-cert-web.service=pargar-web
|
||||||
|
|
||||||
|
networks:
|
||||||
|
pargar:
|
||||||
|
name: pargar_pargar
|
||||||
|
|
||||||
|
volumes:
|
||||||
|
pgdata:
|
||||||
|
redis_data:
|
||||||
|
rustfs_data:
|
||||||
@@ -0,0 +1,5 @@
|
|||||||
|
.DS_Store
|
||||||
|
.git
|
||||||
|
*.md
|
||||||
|
*.tgz
|
||||||
|
secrets*.yaml
|
||||||
@@ -0,0 +1,15 @@
|
|||||||
|
apiVersion: v2
|
||||||
|
name: pargar
|
||||||
|
description: Pargar gated LMS - Go API, Next.js frontend, Postgres, Redis, S3-compatible storage
|
||||||
|
type: application
|
||||||
|
version: 0.2.0
|
||||||
|
appVersion: "0.1.0"
|
||||||
|
keywords:
|
||||||
|
- lms
|
||||||
|
- pargar
|
||||||
|
- traefik
|
||||||
|
maintainers:
|
||||||
|
- name: Pargar
|
||||||
|
home: https://github.com/example/pargar
|
||||||
|
sources:
|
||||||
|
- https://github.com/example/pargar
|
||||||
@@ -0,0 +1,26 @@
|
|||||||
|
Pargar {{ .Chart.AppVersion }} installed as release "{{ .Release.Name }}" in namespace "{{ .Release.Namespace }}".
|
||||||
|
|
||||||
|
Public URL: {{ .Values.global.publicUrl }}
|
||||||
|
Domain: {{ .Values.global.domain }}
|
||||||
|
|
||||||
|
1) Ensure DNS /hosts points to your Traefik entrypoint:
|
||||||
|
{{ .Values.global.domain }} → Traefik LoadBalancer / node IP
|
||||||
|
|
||||||
|
2) Images must exist on the cluster nodes (k3s local):
|
||||||
|
docker compose -f deploy/compose/compose.yaml -f deploy/compose/compose.dev.yaml build
|
||||||
|
docker save pargar-backend:local pargar-frontend:local | sudo k3s ctr images import -
|
||||||
|
|
||||||
|
3) Upgrade / install:
|
||||||
|
helm upgrade --install {{ .Release.Name }} ./deploy/helm/pargar \
|
||||||
|
-n {{ .Release.Namespace }} --create-namespace \
|
||||||
|
-f deploy/helm/pargar/values-k3s.yaml
|
||||||
|
|
||||||
|
4) Health:
|
||||||
|
kubectl -n {{ .Release.Namespace }} get pods,ingressroute,svc
|
||||||
|
curl -k {{ .Values.global.publicUrl }}/api/health
|
||||||
|
|
||||||
|
{{- if not .Values.ingress.tls.existingSecret }}
|
||||||
|
|
||||||
|
TLS: chart-managed self-signed certificate (browser warning expected).
|
||||||
|
For production set ingress.tls.existingSecret (cert-manager).
|
||||||
|
{{- end }}
|
||||||
@@ -0,0 +1,110 @@
|
|||||||
|
{{/*
|
||||||
|
Expand the name of the chart.
|
||||||
|
*/}}
|
||||||
|
{{- define "pargar.name" -}}
|
||||||
|
{{- default .Chart.Name .Values.nameOverride | trunc 63 | trimSuffix "-" }}
|
||||||
|
{{- end }}
|
||||||
|
|
||||||
|
{{- define "pargar.fullname" -}}
|
||||||
|
{{- if .Values.fullnameOverride }}
|
||||||
|
{{- .Values.fullnameOverride | trunc 63 | trimSuffix "-" }}
|
||||||
|
{{- else }}
|
||||||
|
{{- $name := default .Chart.Name .Values.nameOverride }}
|
||||||
|
{{- if contains $name .Release.Name }}
|
||||||
|
{{- .Release.Name | trunc 63 | trimSuffix "-" }}
|
||||||
|
{{- else }}
|
||||||
|
{{- printf "%s-%s" .Release.Name $name | trunc 63 | trimSuffix "-" }}
|
||||||
|
{{- end }}
|
||||||
|
{{- end }}
|
||||||
|
{{- end }}
|
||||||
|
|
||||||
|
{{- define "pargar.chart" -}}
|
||||||
|
{{- printf "%s-%s" .Chart.Name .Chart.Version | replace "+" "_" | trunc 63 | trimSuffix "-" }}
|
||||||
|
{{- end }}
|
||||||
|
|
||||||
|
{{- define "pargar.labels" -}}
|
||||||
|
helm.sh/chart: {{ include "pargar.chart" . }}
|
||||||
|
{{ include "pargar.selectorLabels" . }}
|
||||||
|
app.kubernetes.io/version: {{ .Chart.AppVersion | quote }}
|
||||||
|
app.kubernetes.io/managed-by: {{ .Release.Service }}
|
||||||
|
{{- end }}
|
||||||
|
|
||||||
|
{{- define "pargar.selectorLabels" -}}
|
||||||
|
app.kubernetes.io/name: {{ include "pargar.name" . }}
|
||||||
|
app.kubernetes.io/instance: {{ .Release.Name }}
|
||||||
|
{{- end }}
|
||||||
|
|
||||||
|
{{- define "pargar.serviceAccountName" -}}
|
||||||
|
{{- if .Values.serviceAccount.create }}
|
||||||
|
{{- default (include "pargar.fullname" .) .Values.serviceAccount.name }}
|
||||||
|
{{- else }}
|
||||||
|
{{- default "default" .Values.serviceAccount.name }}
|
||||||
|
{{- end }}
|
||||||
|
{{- end }}
|
||||||
|
|
||||||
|
{{- define "pargar.appSecretName" -}}
|
||||||
|
{{- if .Values.backend.existingSecret }}
|
||||||
|
{{- .Values.backend.existingSecret }}
|
||||||
|
{{- else }}
|
||||||
|
{{- printf "%s-app" (include "pargar.fullname" .) }}
|
||||||
|
{{- end }}
|
||||||
|
{{- end }}
|
||||||
|
|
||||||
|
{{- define "pargar.postgresSecretName" -}}
|
||||||
|
{{- if .Values.postgres.existingSecret }}
|
||||||
|
{{- .Values.postgres.existingSecret }}
|
||||||
|
{{- else }}
|
||||||
|
{{- printf "%s-postgres" (include "pargar.fullname" .) }}
|
||||||
|
{{- end }}
|
||||||
|
{{- end }}
|
||||||
|
|
||||||
|
{{- define "pargar.redisSecretName" -}}
|
||||||
|
{{- if .Values.redis.existingSecret }}
|
||||||
|
{{- .Values.redis.existingSecret }}
|
||||||
|
{{- else }}
|
||||||
|
{{- printf "%s-redis" (include "pargar.fullname" .) }}
|
||||||
|
{{- end }}
|
||||||
|
{{- end }}
|
||||||
|
|
||||||
|
{{- define "pargar.rustfsSecretName" -}}
|
||||||
|
{{- if .Values.rustfs.existingSecret }}
|
||||||
|
{{- .Values.rustfs.existingSecret }}
|
||||||
|
{{- else }}
|
||||||
|
{{- printf "%s-rustfs" (include "pargar.fullname" .) }}
|
||||||
|
{{- end }}
|
||||||
|
{{- end }}
|
||||||
|
|
||||||
|
{{- define "pargar.tlsSecretName" -}}
|
||||||
|
{{- if .Values.ingress.tls.existingSecret }}
|
||||||
|
{{- .Values.ingress.tls.existingSecret }}
|
||||||
|
{{- else }}
|
||||||
|
{{- printf "%s-tls" (include "pargar.fullname" .) }}
|
||||||
|
{{- end }}
|
||||||
|
{{- end }}
|
||||||
|
|
||||||
|
{{- define "pargar.postgresHost" -}}
|
||||||
|
{{- printf "%s-postgres" (include "pargar.fullname" .) }}
|
||||||
|
{{- end }}
|
||||||
|
|
||||||
|
{{- define "pargar.redisHost" -}}
|
||||||
|
{{- printf "%s-redis" (include "pargar.fullname" .) }}
|
||||||
|
{{- end }}
|
||||||
|
|
||||||
|
{{- define "pargar.rustfsHost" -}}
|
||||||
|
{{- printf "%s-rustfs" (include "pargar.fullname" .) }}
|
||||||
|
{{- end }}
|
||||||
|
|
||||||
|
{{/*
|
||||||
|
Resolve container image: optional global.imageRegistry + repository:tag
|
||||||
|
Usage: {{ include "pargar.image" (dict "root" . "image" .Values.backend.image) }}
|
||||||
|
*/}}
|
||||||
|
{{- define "pargar.image" -}}
|
||||||
|
{{- $registry := .root.Values.global.imageRegistry | default "" -}}
|
||||||
|
{{- $repo := .image.repository -}}
|
||||||
|
{{- $tag := .image.tag | default .root.Chart.AppVersion | toString -}}
|
||||||
|
{{- if $registry -}}
|
||||||
|
{{- printf "%s/%s:%s" (trimSuffix "/" $registry) $repo $tag -}}
|
||||||
|
{{- else -}}
|
||||||
|
{{- printf "%s:%s" $repo $tag -}}
|
||||||
|
{{- end -}}
|
||||||
|
{{- end }}
|
||||||
@@ -0,0 +1,206 @@
|
|||||||
|
{{- if .Values.backend.enabled }}
|
||||||
|
apiVersion: v1
|
||||||
|
kind: Service
|
||||||
|
metadata:
|
||||||
|
name: {{ include "pargar.fullname" . }}-backend
|
||||||
|
labels:
|
||||||
|
{{- include "pargar.labels" . | nindent 4 }}
|
||||||
|
app.kubernetes.io/component: backend
|
||||||
|
spec:
|
||||||
|
type: ClusterIP
|
||||||
|
ports:
|
||||||
|
- name: http
|
||||||
|
port: {{ .Values.backend.service.port }}
|
||||||
|
targetPort: http
|
||||||
|
selector:
|
||||||
|
{{- include "pargar.selectorLabels" . | nindent 4 }}
|
||||||
|
app.kubernetes.io/component: backend
|
||||||
|
---
|
||||||
|
apiVersion: apps/v1
|
||||||
|
kind: Deployment
|
||||||
|
metadata:
|
||||||
|
name: {{ include "pargar.fullname" . }}-backend
|
||||||
|
labels:
|
||||||
|
{{- include "pargar.labels" . | nindent 4 }}
|
||||||
|
app.kubernetes.io/component: backend
|
||||||
|
spec:
|
||||||
|
{{- if not .Values.backend.autoscaling.enabled }}
|
||||||
|
replicas: {{ .Values.backend.replicaCount }}
|
||||||
|
{{- end }}
|
||||||
|
selector:
|
||||||
|
matchLabels:
|
||||||
|
{{- include "pargar.selectorLabels" . | nindent 6 }}
|
||||||
|
app.kubernetes.io/component: backend
|
||||||
|
template:
|
||||||
|
metadata:
|
||||||
|
labels:
|
||||||
|
{{- include "pargar.selectorLabels" . | nindent 8 }}
|
||||||
|
app.kubernetes.io/component: backend
|
||||||
|
spec:
|
||||||
|
serviceAccountName: {{ include "pargar.serviceAccountName" . }}
|
||||||
|
{{- with .Values.imagePullSecrets }}
|
||||||
|
imagePullSecrets:
|
||||||
|
{{- toYaml . | nindent 8 }}
|
||||||
|
{{- end }}
|
||||||
|
securityContext:
|
||||||
|
{{- toYaml .Values.podSecurityContext | nindent 8 }}
|
||||||
|
containers:
|
||||||
|
- name: backend
|
||||||
|
image: {{ include "pargar.image" (dict "root" . "image" .Values.backend.image) | quote }}
|
||||||
|
imagePullPolicy: {{ .Values.backend.image.pullPolicy }}
|
||||||
|
securityContext:
|
||||||
|
{{- toYaml .Values.securityContext | nindent 12 }}
|
||||||
|
ports:
|
||||||
|
- name: http
|
||||||
|
containerPort: {{ .Values.backend.service.port }}
|
||||||
|
env:
|
||||||
|
- name: PORT
|
||||||
|
value: {{ .Values.backend.service.port | quote }}
|
||||||
|
- name: PUBLIC_URL
|
||||||
|
value: {{ .Values.global.publicUrl | quote }}
|
||||||
|
- name: FRONTEND_ORIGINS
|
||||||
|
value: {{ .Values.global.frontendOrigins | quote }}
|
||||||
|
- name: TRUSTED_PROXY_CIDRS
|
||||||
|
value: {{ .Values.global.trustedProxyCIDRs | quote }}
|
||||||
|
- name: DEV_MODE
|
||||||
|
value: {{ .Values.backend.env.devMode | quote }}
|
||||||
|
- name: SEED_CURRICULUM
|
||||||
|
value: {{ .Values.backend.env.seedCurriculum | quote }}
|
||||||
|
- name: REGISTRATION_ENFORCE_IP
|
||||||
|
value: {{ .Values.backend.env.registrationEnforceIP | quote }}
|
||||||
|
- name: ADMIN_NAME
|
||||||
|
value: {{ .Values.backend.admin.name | quote }}
|
||||||
|
- name: ADMIN_USERNAME
|
||||||
|
value: {{ .Values.backend.admin.username | quote }}
|
||||||
|
- name: ADMIN_EMAIL
|
||||||
|
value: {{ .Values.backend.admin.email | quote }}
|
||||||
|
- name: JWT_SECRET
|
||||||
|
valueFrom:
|
||||||
|
secretKeyRef:
|
||||||
|
name: {{ include "pargar.appSecretName" . }}
|
||||||
|
key: jwt-secret
|
||||||
|
- name: ADMIN_PASSWORD
|
||||||
|
valueFrom:
|
||||||
|
secretKeyRef:
|
||||||
|
name: {{ include "pargar.appSecretName" . }}
|
||||||
|
key: admin-password
|
||||||
|
- name: METRICS_TOKEN
|
||||||
|
valueFrom:
|
||||||
|
secretKeyRef:
|
||||||
|
name: {{ include "pargar.appSecretName" . }}
|
||||||
|
key: metrics-token
|
||||||
|
optional: true
|
||||||
|
- name: DONATION_ENABLED
|
||||||
|
value: {{ .Values.backend.env.donationEnabled | quote }}
|
||||||
|
- name: PHYSICAL_CERT_ENABLED
|
||||||
|
value: {{ .Values.backend.env.physicalCertEnabled | quote }}
|
||||||
|
- name: PHYSICAL_CERT_PRICE_IRR
|
||||||
|
value: {{ .Values.backend.env.physicalCertPriceIrr | quote }}
|
||||||
|
- name: PHYSICAL_CERT_WINDOW_DAYS
|
||||||
|
value: {{ .Values.backend.env.physicalCertWindowDays | quote }}
|
||||||
|
- name: OTEL_EXPORTER_OTLP_ENDPOINT
|
||||||
|
value: {{ .Values.backend.env.otelEndpoint | quote }}
|
||||||
|
- name: OTEL_SERVICE_NAME
|
||||||
|
value: {{ .Values.backend.env.otelServiceName | quote }}
|
||||||
|
- name: STORAGE_DRIVER
|
||||||
|
value: s3
|
||||||
|
- name: STORAGE_REGION
|
||||||
|
value: {{ .Values.rustfs.region | quote }}
|
||||||
|
- name: STORAGE_BUCKET
|
||||||
|
value: {{ .Values.rustfs.bucket | quote }}
|
||||||
|
{{- if .Values.postgres.enabled }}
|
||||||
|
- name: POSTGRES_USER
|
||||||
|
value: {{ .Values.postgres.auth.username | quote }}
|
||||||
|
- name: POSTGRES_DB
|
||||||
|
value: {{ .Values.postgres.auth.database | quote }}
|
||||||
|
- name: POSTGRES_HOST
|
||||||
|
value: {{ include "pargar.postgresHost" . | quote }}
|
||||||
|
- name: POSTGRES_PORT
|
||||||
|
value: "5432"
|
||||||
|
- name: POSTGRES_SSLMODE
|
||||||
|
value: "disable"
|
||||||
|
- name: POSTGRES_PASSWORD
|
||||||
|
valueFrom:
|
||||||
|
secretKeyRef:
|
||||||
|
name: {{ include "pargar.postgresSecretName" . }}
|
||||||
|
key: postgres-password
|
||||||
|
{{- else }}
|
||||||
|
- name: DATABASE_URL
|
||||||
|
valueFrom:
|
||||||
|
secretKeyRef:
|
||||||
|
name: {{ include "pargar.appSecretName" . }}
|
||||||
|
key: database-url
|
||||||
|
{{- end }}
|
||||||
|
{{- if .Values.redis.enabled }}
|
||||||
|
- name: REDIS_HOST
|
||||||
|
value: {{ include "pargar.redisHost" . | quote }}
|
||||||
|
- name: REDIS_PORT
|
||||||
|
value: "6379"
|
||||||
|
- name: REDIS_PASSWORD
|
||||||
|
valueFrom:
|
||||||
|
secretKeyRef:
|
||||||
|
name: {{ include "pargar.redisSecretName" . }}
|
||||||
|
key: redis-password
|
||||||
|
{{- else }}
|
||||||
|
- name: REDIS_URL
|
||||||
|
valueFrom:
|
||||||
|
secretKeyRef:
|
||||||
|
name: {{ include "pargar.appSecretName" . }}
|
||||||
|
key: redis-url
|
||||||
|
{{- end }}
|
||||||
|
{{- if .Values.rustfs.enabled }}
|
||||||
|
- name: STORAGE_ENDPOINT
|
||||||
|
value: {{ printf "http://%s:9000" (include "pargar.rustfsHost" .) | quote }}
|
||||||
|
- name: STORAGE_ACCESS_KEY
|
||||||
|
valueFrom:
|
||||||
|
secretKeyRef:
|
||||||
|
name: {{ include "pargar.rustfsSecretName" . }}
|
||||||
|
key: access-key
|
||||||
|
- name: STORAGE_SECRET_KEY
|
||||||
|
valueFrom:
|
||||||
|
secretKeyRef:
|
||||||
|
name: {{ include "pargar.rustfsSecretName" . }}
|
||||||
|
key: secret-key
|
||||||
|
{{- else }}
|
||||||
|
- name: STORAGE_ENDPOINT
|
||||||
|
value: {{ required "external.storageEndpoint required when rustfs.enabled=false" .Values.external.storageEndpoint | quote }}
|
||||||
|
- name: STORAGE_ACCESS_KEY
|
||||||
|
valueFrom:
|
||||||
|
secretKeyRef:
|
||||||
|
name: {{ include "pargar.appSecretName" . }}
|
||||||
|
key: storage-access-key
|
||||||
|
- name: STORAGE_SECRET_KEY
|
||||||
|
valueFrom:
|
||||||
|
secretKeyRef:
|
||||||
|
name: {{ include "pargar.appSecretName" . }}
|
||||||
|
key: storage-secret-key
|
||||||
|
{{- end }}
|
||||||
|
readinessProbe:
|
||||||
|
httpGet:
|
||||||
|
path: /api/health
|
||||||
|
port: http
|
||||||
|
initialDelaySeconds: 5
|
||||||
|
periodSeconds: 5
|
||||||
|
livenessProbe:
|
||||||
|
httpGet:
|
||||||
|
path: /api/health
|
||||||
|
port: http
|
||||||
|
initialDelaySeconds: 15
|
||||||
|
periodSeconds: 10
|
||||||
|
{{- with .Values.backend.resources }}
|
||||||
|
resources:
|
||||||
|
{{- toYaml . | nindent 12 }}
|
||||||
|
{{- end }}
|
||||||
|
{{- with .Values.nodeSelector }}
|
||||||
|
nodeSelector:
|
||||||
|
{{- toYaml . | nindent 8 }}
|
||||||
|
{{- end }}
|
||||||
|
{{- with .Values.affinity }}
|
||||||
|
affinity:
|
||||||
|
{{- toYaml . | nindent 8 }}
|
||||||
|
{{- end }}
|
||||||
|
{{- with .Values.tolerations }}
|
||||||
|
tolerations:
|
||||||
|
{{- toYaml . | nindent 8 }}
|
||||||
|
{{- end }}
|
||||||
|
{{- end }}
|
||||||
@@ -0,0 +1,79 @@
|
|||||||
|
{{- if and .Values.postgres.enabled .Values.backup.enabled }}
|
||||||
|
apiVersion: v1
|
||||||
|
kind: PersistentVolumeClaim
|
||||||
|
metadata:
|
||||||
|
name: {{ include "pargar.fullname" . }}-backups
|
||||||
|
labels:
|
||||||
|
{{- include "pargar.labels" . | nindent 4 }}
|
||||||
|
app.kubernetes.io/component: backup
|
||||||
|
spec:
|
||||||
|
accessModes: ["ReadWriteOnce"]
|
||||||
|
{{- if .Values.backup.persistence.storageClass }}
|
||||||
|
storageClassName: {{ .Values.backup.persistence.storageClass | quote }}
|
||||||
|
{{- end }}
|
||||||
|
resources:
|
||||||
|
requests:
|
||||||
|
storage: {{ .Values.backup.persistence.size | quote }}
|
||||||
|
---
|
||||||
|
apiVersion: batch/v1
|
||||||
|
kind: CronJob
|
||||||
|
metadata:
|
||||||
|
name: {{ include "pargar.fullname" . }}-pg-backup
|
||||||
|
labels:
|
||||||
|
{{- include "pargar.labels" . | nindent 4 }}
|
||||||
|
app.kubernetes.io/component: backup
|
||||||
|
spec:
|
||||||
|
schedule: {{ .Values.backup.schedule | quote }}
|
||||||
|
concurrencyPolicy: Forbid
|
||||||
|
successfulJobsHistoryLimit: 3
|
||||||
|
failedJobsHistoryLimit: 3
|
||||||
|
jobTemplate:
|
||||||
|
spec:
|
||||||
|
template:
|
||||||
|
metadata:
|
||||||
|
labels:
|
||||||
|
{{- include "pargar.selectorLabels" . | nindent 12 }}
|
||||||
|
app.kubernetes.io/component: backup
|
||||||
|
spec:
|
||||||
|
restartPolicy: OnFailure
|
||||||
|
securityContext:
|
||||||
|
fsGroup: 999
|
||||||
|
containers:
|
||||||
|
- name: pg-dump
|
||||||
|
image: {{ .Values.backup.image | quote }}
|
||||||
|
imagePullPolicy: IfNotPresent
|
||||||
|
env:
|
||||||
|
- name: PGHOST
|
||||||
|
value: {{ include "pargar.postgresHost" . | quote }}
|
||||||
|
- name: PGPORT
|
||||||
|
value: "5432"
|
||||||
|
- name: PGUSER
|
||||||
|
value: {{ .Values.postgres.auth.username | quote }}
|
||||||
|
- name: PGDATABASE
|
||||||
|
value: {{ .Values.postgres.auth.database | quote }}
|
||||||
|
- name: RETENTION_DAYS
|
||||||
|
value: {{ .Values.backup.retentionDays | quote }}
|
||||||
|
- name: PGPASSWORD
|
||||||
|
valueFrom:
|
||||||
|
secretKeyRef:
|
||||||
|
name: {{ include "pargar.postgresSecretName" . }}
|
||||||
|
key: postgres-password
|
||||||
|
command:
|
||||||
|
- /bin/sh
|
||||||
|
- -ec
|
||||||
|
- |
|
||||||
|
set -euo pipefail
|
||||||
|
STAMP="$(date -u +%Y%m%dT%H%M%SZ)"
|
||||||
|
OUT="/backups/pargar-${STAMP}.sql.gz"
|
||||||
|
echo "Writing ${OUT}"
|
||||||
|
pg_dump --no-owner --no-acl | gzip -c > "${OUT}"
|
||||||
|
find /backups -type f -name 'pargar-*.sql.gz' -mtime +"${RETENTION_DAYS}" -print -delete || true
|
||||||
|
ls -lh /backups || true
|
||||||
|
volumeMounts:
|
||||||
|
- name: backups
|
||||||
|
mountPath: /backups
|
||||||
|
volumes:
|
||||||
|
- name: backups
|
||||||
|
persistentVolumeClaim:
|
||||||
|
claimName: {{ include "pargar.fullname" . }}-backups
|
||||||
|
{{- end }}
|
||||||
@@ -0,0 +1,23 @@
|
|||||||
|
{{- if and .Values.ingress.enabled .Values.ingress.tls.enabled .Values.certManager.enabled }}
|
||||||
|
apiVersion: cert-manager.io/v1
|
||||||
|
kind: Certificate
|
||||||
|
metadata:
|
||||||
|
name: {{ include "pargar.fullname" . }}-tls
|
||||||
|
labels:
|
||||||
|
{{- include "pargar.labels" . | nindent 4 }}
|
||||||
|
spec:
|
||||||
|
secretName: {{ include "pargar.tlsSecretName" . }}
|
||||||
|
duration: {{ .Values.certManager.duration | default "2160h" | quote }}
|
||||||
|
renewBefore: {{ .Values.certManager.renewBefore | default "360h" | quote }}
|
||||||
|
issuerRef:
|
||||||
|
name: {{ required "certManager.issuerRef.name required when certManager.enabled" .Values.certManager.issuerRef.name | quote }}
|
||||||
|
kind: {{ .Values.certManager.issuerRef.kind | default "ClusterIssuer" | quote }}
|
||||||
|
{{- if .Values.certManager.issuerRef.group }}
|
||||||
|
group: {{ .Values.certManager.issuerRef.group | quote }}
|
||||||
|
{{- end }}
|
||||||
|
dnsNames:
|
||||||
|
- {{ .Values.global.domain | quote }}
|
||||||
|
{{- range .Values.certManager.extraDnsNames }}
|
||||||
|
- {{ . | quote }}
|
||||||
|
{{- end }}
|
||||||
|
{{- end }}
|
||||||
@@ -0,0 +1,83 @@
|
|||||||
|
{{- if .Values.frontend.enabled }}
|
||||||
|
apiVersion: v1
|
||||||
|
kind: Service
|
||||||
|
metadata:
|
||||||
|
name: {{ include "pargar.fullname" . }}-frontend
|
||||||
|
labels:
|
||||||
|
{{- include "pargar.labels" . | nindent 4 }}
|
||||||
|
app.kubernetes.io/component: frontend
|
||||||
|
spec:
|
||||||
|
type: ClusterIP
|
||||||
|
ports:
|
||||||
|
- name: http
|
||||||
|
port: {{ .Values.frontend.service.port }}
|
||||||
|
targetPort: http
|
||||||
|
selector:
|
||||||
|
{{- include "pargar.selectorLabels" . | nindent 4 }}
|
||||||
|
app.kubernetes.io/component: frontend
|
||||||
|
---
|
||||||
|
apiVersion: apps/v1
|
||||||
|
kind: Deployment
|
||||||
|
metadata:
|
||||||
|
name: {{ include "pargar.fullname" . }}-frontend
|
||||||
|
labels:
|
||||||
|
{{- include "pargar.labels" . | nindent 4 }}
|
||||||
|
app.kubernetes.io/component: frontend
|
||||||
|
spec:
|
||||||
|
{{- if not .Values.frontend.autoscaling.enabled }}
|
||||||
|
replicas: {{ .Values.frontend.replicaCount }}
|
||||||
|
{{- end }}
|
||||||
|
selector:
|
||||||
|
matchLabels:
|
||||||
|
{{- include "pargar.selectorLabels" . | nindent 6 }}
|
||||||
|
app.kubernetes.io/component: frontend
|
||||||
|
template:
|
||||||
|
metadata:
|
||||||
|
labels:
|
||||||
|
{{- include "pargar.selectorLabels" . | nindent 8 }}
|
||||||
|
app.kubernetes.io/component: frontend
|
||||||
|
spec:
|
||||||
|
serviceAccountName: {{ include "pargar.serviceAccountName" . }}
|
||||||
|
{{- with .Values.imagePullSecrets }}
|
||||||
|
imagePullSecrets:
|
||||||
|
{{- toYaml . | nindent 8 }}
|
||||||
|
{{- end }}
|
||||||
|
containers:
|
||||||
|
- name: frontend
|
||||||
|
image: {{ include "pargar.image" (dict "root" . "image" .Values.frontend.image) | quote }}
|
||||||
|
imagePullPolicy: {{ .Values.frontend.image.pullPolicy }}
|
||||||
|
env:
|
||||||
|
- name: NODE_ENV
|
||||||
|
value: production
|
||||||
|
ports:
|
||||||
|
- name: http
|
||||||
|
containerPort: {{ .Values.frontend.service.port }}
|
||||||
|
readinessProbe:
|
||||||
|
httpGet:
|
||||||
|
path: /
|
||||||
|
port: http
|
||||||
|
initialDelaySeconds: 5
|
||||||
|
periodSeconds: 5
|
||||||
|
livenessProbe:
|
||||||
|
httpGet:
|
||||||
|
path: /
|
||||||
|
port: http
|
||||||
|
initialDelaySeconds: 15
|
||||||
|
periodSeconds: 10
|
||||||
|
{{- with .Values.frontend.resources }}
|
||||||
|
resources:
|
||||||
|
{{- toYaml . | nindent 12 }}
|
||||||
|
{{- end }}
|
||||||
|
{{- with .Values.nodeSelector }}
|
||||||
|
nodeSelector:
|
||||||
|
{{- toYaml . | nindent 8 }}
|
||||||
|
{{- end }}
|
||||||
|
{{- with .Values.affinity }}
|
||||||
|
affinity:
|
||||||
|
{{- toYaml . | nindent 8 }}
|
||||||
|
{{- end }}
|
||||||
|
{{- with .Values.tolerations }}
|
||||||
|
tolerations:
|
||||||
|
{{- toYaml . | nindent 8 }}
|
||||||
|
{{- end }}
|
||||||
|
{{- end }}
|
||||||
@@ -0,0 +1,67 @@
|
|||||||
|
{{- if and .Values.backend.enabled .Values.backend.autoscaling.enabled }}
|
||||||
|
apiVersion: autoscaling/v2
|
||||||
|
kind: HorizontalPodAutoscaler
|
||||||
|
metadata:
|
||||||
|
name: {{ include "pargar.fullname" . }}-backend
|
||||||
|
labels:
|
||||||
|
{{- include "pargar.labels" . | nindent 4 }}
|
||||||
|
app.kubernetes.io/component: backend
|
||||||
|
spec:
|
||||||
|
scaleTargetRef:
|
||||||
|
apiVersion: apps/v1
|
||||||
|
kind: Deployment
|
||||||
|
name: {{ include "pargar.fullname" . }}-backend
|
||||||
|
minReplicas: {{ .Values.backend.autoscaling.minReplicas }}
|
||||||
|
maxReplicas: {{ .Values.backend.autoscaling.maxReplicas }}
|
||||||
|
metrics:
|
||||||
|
{{- if .Values.backend.autoscaling.targetCPUUtilizationPercentage }}
|
||||||
|
- type: Resource
|
||||||
|
resource:
|
||||||
|
name: cpu
|
||||||
|
target:
|
||||||
|
type: Utilization
|
||||||
|
averageUtilization: {{ .Values.backend.autoscaling.targetCPUUtilizationPercentage }}
|
||||||
|
{{- end }}
|
||||||
|
{{- if .Values.backend.autoscaling.targetMemoryUtilizationPercentage }}
|
||||||
|
- type: Resource
|
||||||
|
resource:
|
||||||
|
name: memory
|
||||||
|
target:
|
||||||
|
type: Utilization
|
||||||
|
averageUtilization: {{ .Values.backend.autoscaling.targetMemoryUtilizationPercentage }}
|
||||||
|
{{- end }}
|
||||||
|
---
|
||||||
|
{{- end }}
|
||||||
|
{{- if and .Values.frontend.enabled .Values.frontend.autoscaling.enabled }}
|
||||||
|
apiVersion: autoscaling/v2
|
||||||
|
kind: HorizontalPodAutoscaler
|
||||||
|
metadata:
|
||||||
|
name: {{ include "pargar.fullname" . }}-frontend
|
||||||
|
labels:
|
||||||
|
{{- include "pargar.labels" . | nindent 4 }}
|
||||||
|
app.kubernetes.io/component: frontend
|
||||||
|
spec:
|
||||||
|
scaleTargetRef:
|
||||||
|
apiVersion: apps/v1
|
||||||
|
kind: Deployment
|
||||||
|
name: {{ include "pargar.fullname" . }}-frontend
|
||||||
|
minReplicas: {{ .Values.frontend.autoscaling.minReplicas }}
|
||||||
|
maxReplicas: {{ .Values.frontend.autoscaling.maxReplicas }}
|
||||||
|
metrics:
|
||||||
|
{{- if .Values.frontend.autoscaling.targetCPUUtilizationPercentage }}
|
||||||
|
- type: Resource
|
||||||
|
resource:
|
||||||
|
name: cpu
|
||||||
|
target:
|
||||||
|
type: Utilization
|
||||||
|
averageUtilization: {{ .Values.frontend.autoscaling.targetCPUUtilizationPercentage }}
|
||||||
|
{{- end }}
|
||||||
|
{{- if .Values.frontend.autoscaling.targetMemoryUtilizationPercentage }}
|
||||||
|
- type: Resource
|
||||||
|
resource:
|
||||||
|
name: memory
|
||||||
|
target:
|
||||||
|
type: Utilization
|
||||||
|
averageUtilization: {{ .Values.frontend.autoscaling.targetMemoryUtilizationPercentage }}
|
||||||
|
{{- end }}
|
||||||
|
{{- end }}
|
||||||
@@ -0,0 +1,50 @@
|
|||||||
|
{{- if and .Values.ingress.enabled (not .Values.ingress.useIngressRoute) }}
|
||||||
|
{{- $fullName := include "pargar.fullname" . }}
|
||||||
|
apiVersion: networking.k8s.io/v1
|
||||||
|
kind: Ingress
|
||||||
|
metadata:
|
||||||
|
name: {{ $fullName }}
|
||||||
|
labels:
|
||||||
|
{{- include "pargar.labels" . | nindent 4 }}
|
||||||
|
annotations:
|
||||||
|
traefik.ingress.kubernetes.io/router.middlewares: {{ .Release.Namespace }}-{{ $fullName }}-security-headers@kubernetescrd,{{ .Release.Namespace }}-{{ $fullName }}-compress@kubernetescrd
|
||||||
|
{{- if .Values.ingress.tls.clusterIssuer }}
|
||||||
|
cert-manager.io/cluster-issuer: {{ .Values.ingress.tls.clusterIssuer | quote }}
|
||||||
|
{{- end }}
|
||||||
|
{{- with .Values.ingress.annotations }}
|
||||||
|
{{- toYaml . | nindent 4 }}
|
||||||
|
{{- end }}
|
||||||
|
spec:
|
||||||
|
ingressClassName: {{ .Values.ingress.className | quote }}
|
||||||
|
{{- if .Values.ingress.tls.enabled }}
|
||||||
|
tls:
|
||||||
|
- hosts:
|
||||||
|
- {{ .Values.global.domain | quote }}
|
||||||
|
secretName: {{ include "pargar.tlsSecretName" . }}
|
||||||
|
{{- end }}
|
||||||
|
rules:
|
||||||
|
- host: {{ .Values.global.domain | quote }}
|
||||||
|
http:
|
||||||
|
paths:
|
||||||
|
- path: /api
|
||||||
|
pathType: Prefix
|
||||||
|
backend:
|
||||||
|
service:
|
||||||
|
name: {{ $fullName }}-backend
|
||||||
|
port:
|
||||||
|
number: {{ .Values.backend.service.port }}
|
||||||
|
- path: /media
|
||||||
|
pathType: Prefix
|
||||||
|
backend:
|
||||||
|
service:
|
||||||
|
name: {{ $fullName }}-backend
|
||||||
|
port:
|
||||||
|
number: {{ .Values.backend.service.port }}
|
||||||
|
- path: /
|
||||||
|
pathType: Prefix
|
||||||
|
backend:
|
||||||
|
service:
|
||||||
|
name: {{ $fullName }}-frontend
|
||||||
|
port:
|
||||||
|
number: {{ .Values.frontend.service.port }}
|
||||||
|
{{- end }}
|
||||||
@@ -0,0 +1,97 @@
|
|||||||
|
{{- if and .Values.ingress.enabled .Values.ingress.useIngressRoute }}
|
||||||
|
{{- $fullName := include "pargar.fullname" . }}
|
||||||
|
{{- $domain := .Values.global.domain }}
|
||||||
|
{{- $tlsSecret := include "pargar.tlsSecretName" . }}
|
||||||
|
apiVersion: traefik.io/v1alpha1
|
||||||
|
kind: IngressRoute
|
||||||
|
metadata:
|
||||||
|
name: {{ $fullName }}-http
|
||||||
|
labels:
|
||||||
|
{{- include "pargar.labels" . | nindent 4 }}
|
||||||
|
spec:
|
||||||
|
entryPoints:
|
||||||
|
- web
|
||||||
|
routes:
|
||||||
|
- match: Host(`{{ $domain }}`)
|
||||||
|
kind: Rule
|
||||||
|
{{- if .Values.middlewares.redirectHttps }}
|
||||||
|
middlewares:
|
||||||
|
- name: {{ $fullName }}-redirect-https
|
||||||
|
{{- end }}
|
||||||
|
services:
|
||||||
|
- name: {{ $fullName }}-frontend
|
||||||
|
port: {{ .Values.frontend.service.port }}
|
||||||
|
---
|
||||||
|
apiVersion: traefik.io/v1alpha1
|
||||||
|
kind: IngressRoute
|
||||||
|
metadata:
|
||||||
|
name: {{ $fullName }}-https
|
||||||
|
labels:
|
||||||
|
{{- include "pargar.labels" . | nindent 4 }}
|
||||||
|
spec:
|
||||||
|
entryPoints:
|
||||||
|
- websecure
|
||||||
|
routes:
|
||||||
|
# Certificate public API — highest priority + noindex
|
||||||
|
- match: Host(`{{ $domain }}`) && PathPrefix(`/api/certificates`)
|
||||||
|
kind: Rule
|
||||||
|
priority: 110
|
||||||
|
middlewares:
|
||||||
|
{{- if .Values.middlewares.securityHeaders }}
|
||||||
|
- name: {{ $fullName }}-security-headers
|
||||||
|
{{- end }}
|
||||||
|
{{- if .Values.middlewares.compress }}
|
||||||
|
- name: {{ $fullName }}-compress
|
||||||
|
{{- end }}
|
||||||
|
- name: {{ $fullName }}-noindex
|
||||||
|
services:
|
||||||
|
- name: {{ $fullName }}-backend
|
||||||
|
port: {{ .Values.backend.service.port }}
|
||||||
|
# API + media (+ WebSocket /api/ws)
|
||||||
|
- match: Host(`{{ $domain }}`) && (PathPrefix(`/api`) || PathPrefix(`/media`))
|
||||||
|
kind: Rule
|
||||||
|
priority: 100
|
||||||
|
middlewares:
|
||||||
|
{{- if .Values.middlewares.securityHeaders }}
|
||||||
|
- name: {{ $fullName }}-security-headers
|
||||||
|
{{- end }}
|
||||||
|
{{- if .Values.middlewares.compress }}
|
||||||
|
- name: {{ $fullName }}-compress
|
||||||
|
{{- end }}
|
||||||
|
services:
|
||||||
|
- name: {{ $fullName }}-backend
|
||||||
|
port: {{ .Values.backend.service.port }}
|
||||||
|
# Unlisted certificate pages
|
||||||
|
- match: Host(`{{ $domain }}`) && PathPrefix(`/c`)
|
||||||
|
kind: Rule
|
||||||
|
priority: 50
|
||||||
|
middlewares:
|
||||||
|
{{- if .Values.middlewares.securityHeaders }}
|
||||||
|
- name: {{ $fullName }}-security-headers
|
||||||
|
{{- end }}
|
||||||
|
{{- if .Values.middlewares.compress }}
|
||||||
|
- name: {{ $fullName }}-compress
|
||||||
|
{{- end }}
|
||||||
|
- name: {{ $fullName }}-noindex
|
||||||
|
services:
|
||||||
|
- name: {{ $fullName }}-frontend
|
||||||
|
port: {{ .Values.frontend.service.port }}
|
||||||
|
# Frontend catch-all
|
||||||
|
- match: Host(`{{ $domain }}`)
|
||||||
|
kind: Rule
|
||||||
|
priority: 1
|
||||||
|
middlewares:
|
||||||
|
{{- if .Values.middlewares.securityHeaders }}
|
||||||
|
- name: {{ $fullName }}-security-headers
|
||||||
|
{{- end }}
|
||||||
|
{{- if .Values.middlewares.compress }}
|
||||||
|
- name: {{ $fullName }}-compress
|
||||||
|
{{- end }}
|
||||||
|
services:
|
||||||
|
- name: {{ $fullName }}-frontend
|
||||||
|
port: {{ .Values.frontend.service.port }}
|
||||||
|
{{- if .Values.ingress.tls.enabled }}
|
||||||
|
tls:
|
||||||
|
secretName: {{ $tlsSecret }}
|
||||||
|
{{- end }}
|
||||||
|
{{- end }}
|
||||||
@@ -0,0 +1,63 @@
|
|||||||
|
{{- if .Values.ingress.enabled }}
|
||||||
|
{{- if .Values.middlewares.securityHeaders }}
|
||||||
|
apiVersion: traefik.io/v1alpha1
|
||||||
|
kind: Middleware
|
||||||
|
metadata:
|
||||||
|
name: {{ include "pargar.fullname" . }}-security-headers
|
||||||
|
labels:
|
||||||
|
{{- include "pargar.labels" . | nindent 4 }}
|
||||||
|
spec:
|
||||||
|
headers:
|
||||||
|
stsSeconds: 31536000
|
||||||
|
stsIncludeSubdomains: true
|
||||||
|
contentTypeNosniff: true
|
||||||
|
browserXssFilter: true
|
||||||
|
frameDeny: true
|
||||||
|
referrerPolicy: strict-origin-when-cross-origin
|
||||||
|
permissionsPolicy: "camera=(), microphone=(), geolocation=()"
|
||||||
|
customResponseHeaders:
|
||||||
|
Server: ""
|
||||||
|
Content-Security-Policy: >-
|
||||||
|
default-src 'self'; base-uri 'self'; form-action 'self';
|
||||||
|
frame-ancestors 'none'; object-src 'none';
|
||||||
|
script-src 'self' 'unsafe-inline'; style-src 'self' 'unsafe-inline';
|
||||||
|
img-src 'self' data: blob:; font-src 'self' data:;
|
||||||
|
media-src 'self' blob:; connect-src 'self' ws: wss:;
|
||||||
|
worker-src 'self' blob:
|
||||||
|
---
|
||||||
|
{{- end }}
|
||||||
|
{{- if .Values.middlewares.compress }}
|
||||||
|
apiVersion: traefik.io/v1alpha1
|
||||||
|
kind: Middleware
|
||||||
|
metadata:
|
||||||
|
name: {{ include "pargar.fullname" . }}-compress
|
||||||
|
labels:
|
||||||
|
{{- include "pargar.labels" . | nindent 4 }}
|
||||||
|
spec:
|
||||||
|
compress: {}
|
||||||
|
---
|
||||||
|
{{- end }}
|
||||||
|
apiVersion: traefik.io/v1alpha1
|
||||||
|
kind: Middleware
|
||||||
|
metadata:
|
||||||
|
name: {{ include "pargar.fullname" . }}-noindex
|
||||||
|
labels:
|
||||||
|
{{- include "pargar.labels" . | nindent 4 }}
|
||||||
|
spec:
|
||||||
|
headers:
|
||||||
|
customResponseHeaders:
|
||||||
|
X-Robots-Tag: "noindex, nofollow, noarchive"
|
||||||
|
---
|
||||||
|
{{- if and .Values.ingress.useIngressRoute .Values.middlewares.redirectHttps }}
|
||||||
|
apiVersion: traefik.io/v1alpha1
|
||||||
|
kind: Middleware
|
||||||
|
metadata:
|
||||||
|
name: {{ include "pargar.fullname" . }}-redirect-https
|
||||||
|
labels:
|
||||||
|
{{- include "pargar.labels" . | nindent 4 }}
|
||||||
|
spec:
|
||||||
|
redirectScheme:
|
||||||
|
scheme: https
|
||||||
|
permanent: true
|
||||||
|
{{- end }}
|
||||||
|
{{- end }}
|
||||||
@@ -0,0 +1,229 @@
|
|||||||
|
{{- if .Values.networkPolicy.enabled }}
|
||||||
|
{{- $fullName := include "pargar.fullname" . }}
|
||||||
|
# Default deny all ingress/egress in the release namespace, then allow required paths.
|
||||||
|
apiVersion: networking.k8s.io/v1
|
||||||
|
kind: NetworkPolicy
|
||||||
|
metadata:
|
||||||
|
name: {{ $fullName }}-default-deny
|
||||||
|
labels:
|
||||||
|
{{- include "pargar.labels" . | nindent 4 }}
|
||||||
|
spec:
|
||||||
|
podSelector: {}
|
||||||
|
policyTypes:
|
||||||
|
- Ingress
|
||||||
|
- Egress
|
||||||
|
---
|
||||||
|
{{- if .Values.backend.enabled }}
|
||||||
|
apiVersion: networking.k8s.io/v1
|
||||||
|
kind: NetworkPolicy
|
||||||
|
metadata:
|
||||||
|
name: {{ $fullName }}-backend
|
||||||
|
labels:
|
||||||
|
{{- include "pargar.labels" . | nindent 4 }}
|
||||||
|
app.kubernetes.io/component: backend
|
||||||
|
spec:
|
||||||
|
podSelector:
|
||||||
|
matchLabels:
|
||||||
|
{{- include "pargar.selectorLabels" . | nindent 6 }}
|
||||||
|
app.kubernetes.io/component: backend
|
||||||
|
policyTypes:
|
||||||
|
- Ingress
|
||||||
|
- Egress
|
||||||
|
ingress:
|
||||||
|
- from:
|
||||||
|
{{- range .Values.networkPolicy.ingressNamespaces }}
|
||||||
|
- namespaceSelector:
|
||||||
|
matchLabels:
|
||||||
|
kubernetes.io/metadata.name: {{ . | quote }}
|
||||||
|
podSelector:
|
||||||
|
matchLabels:
|
||||||
|
{{- toYaml $.Values.networkPolicy.ingressPodLabels | nindent 14 }}
|
||||||
|
{{- end }}
|
||||||
|
ports:
|
||||||
|
- protocol: TCP
|
||||||
|
port: {{ .Values.backend.service.port }}
|
||||||
|
egress:
|
||||||
|
# DNS
|
||||||
|
- to:
|
||||||
|
- namespaceSelector:
|
||||||
|
matchLabels:
|
||||||
|
kubernetes.io/metadata.name: kube-system
|
||||||
|
ports:
|
||||||
|
- protocol: UDP
|
||||||
|
port: 53
|
||||||
|
- protocol: TCP
|
||||||
|
port: 53
|
||||||
|
{{- if .Values.postgres.enabled }}
|
||||||
|
- to:
|
||||||
|
- podSelector:
|
||||||
|
matchLabels:
|
||||||
|
{{- include "pargar.selectorLabels" . | nindent 14 }}
|
||||||
|
app.kubernetes.io/component: postgres
|
||||||
|
ports:
|
||||||
|
- protocol: TCP
|
||||||
|
port: 5432
|
||||||
|
{{- end }}
|
||||||
|
{{- if .Values.redis.enabled }}
|
||||||
|
- to:
|
||||||
|
- podSelector:
|
||||||
|
matchLabels:
|
||||||
|
{{- include "pargar.selectorLabels" . | nindent 14 }}
|
||||||
|
app.kubernetes.io/component: redis
|
||||||
|
ports:
|
||||||
|
- protocol: TCP
|
||||||
|
port: 6379
|
||||||
|
{{- end }}
|
||||||
|
{{- if .Values.rustfs.enabled }}
|
||||||
|
- to:
|
||||||
|
- podSelector:
|
||||||
|
matchLabels:
|
||||||
|
{{- include "pargar.selectorLabels" . | nindent 14 }}
|
||||||
|
app.kubernetes.io/component: rustfs
|
||||||
|
ports:
|
||||||
|
- protocol: TCP
|
||||||
|
port: 9000
|
||||||
|
{{- else }}
|
||||||
|
# External S3 / managed data when in-cluster rustfs is off
|
||||||
|
- to:
|
||||||
|
- ipBlock:
|
||||||
|
cidr: 0.0.0.0/0
|
||||||
|
except:
|
||||||
|
- 10.0.0.0/8
|
||||||
|
- 172.16.0.0/12
|
||||||
|
- 192.168.0.0/16
|
||||||
|
- 169.254.0.0/16
|
||||||
|
ports:
|
||||||
|
- protocol: TCP
|
||||||
|
port: 443
|
||||||
|
- protocol: TCP
|
||||||
|
port: 5432
|
||||||
|
- protocol: TCP
|
||||||
|
port: 6379
|
||||||
|
{{- end }}
|
||||||
|
---
|
||||||
|
{{- end }}
|
||||||
|
{{- if .Values.frontend.enabled }}
|
||||||
|
apiVersion: networking.k8s.io/v1
|
||||||
|
kind: NetworkPolicy
|
||||||
|
metadata:
|
||||||
|
name: {{ $fullName }}-frontend
|
||||||
|
labels:
|
||||||
|
{{- include "pargar.labels" . | nindent 4 }}
|
||||||
|
app.kubernetes.io/component: frontend
|
||||||
|
spec:
|
||||||
|
podSelector:
|
||||||
|
matchLabels:
|
||||||
|
{{- include "pargar.selectorLabels" . | nindent 6 }}
|
||||||
|
app.kubernetes.io/component: frontend
|
||||||
|
policyTypes:
|
||||||
|
- Ingress
|
||||||
|
- Egress
|
||||||
|
ingress:
|
||||||
|
- from:
|
||||||
|
{{- range .Values.networkPolicy.ingressNamespaces }}
|
||||||
|
- namespaceSelector:
|
||||||
|
matchLabels:
|
||||||
|
kubernetes.io/metadata.name: {{ . | quote }}
|
||||||
|
podSelector:
|
||||||
|
matchLabels:
|
||||||
|
{{- toYaml $.Values.networkPolicy.ingressPodLabels | nindent 14 }}
|
||||||
|
{{- end }}
|
||||||
|
ports:
|
||||||
|
- protocol: TCP
|
||||||
|
port: {{ .Values.frontend.service.port }}
|
||||||
|
egress:
|
||||||
|
- to:
|
||||||
|
- namespaceSelector:
|
||||||
|
matchLabels:
|
||||||
|
kubernetes.io/metadata.name: kube-system
|
||||||
|
ports:
|
||||||
|
- protocol: UDP
|
||||||
|
port: 53
|
||||||
|
- protocol: TCP
|
||||||
|
port: 53
|
||||||
|
---
|
||||||
|
{{- end }}
|
||||||
|
{{- if .Values.postgres.enabled }}
|
||||||
|
apiVersion: networking.k8s.io/v1
|
||||||
|
kind: NetworkPolicy
|
||||||
|
metadata:
|
||||||
|
name: {{ $fullName }}-postgres
|
||||||
|
labels:
|
||||||
|
{{- include "pargar.labels" . | nindent 4 }}
|
||||||
|
app.kubernetes.io/component: postgres
|
||||||
|
spec:
|
||||||
|
podSelector:
|
||||||
|
matchLabels:
|
||||||
|
{{- include "pargar.selectorLabels" . | nindent 6 }}
|
||||||
|
app.kubernetes.io/component: postgres
|
||||||
|
policyTypes:
|
||||||
|
- Ingress
|
||||||
|
- Egress
|
||||||
|
ingress:
|
||||||
|
- from:
|
||||||
|
- podSelector:
|
||||||
|
matchLabels:
|
||||||
|
{{- include "pargar.selectorLabels" . | nindent 14 }}
|
||||||
|
app.kubernetes.io/component: backend
|
||||||
|
ports:
|
||||||
|
- protocol: TCP
|
||||||
|
port: 5432
|
||||||
|
egress: []
|
||||||
|
---
|
||||||
|
{{- end }}
|
||||||
|
{{- if .Values.redis.enabled }}
|
||||||
|
apiVersion: networking.k8s.io/v1
|
||||||
|
kind: NetworkPolicy
|
||||||
|
metadata:
|
||||||
|
name: {{ $fullName }}-redis
|
||||||
|
labels:
|
||||||
|
{{- include "pargar.labels" . | nindent 4 }}
|
||||||
|
app.kubernetes.io/component: redis
|
||||||
|
spec:
|
||||||
|
podSelector:
|
||||||
|
matchLabels:
|
||||||
|
{{- include "pargar.selectorLabels" . | nindent 6 }}
|
||||||
|
app.kubernetes.io/component: redis
|
||||||
|
policyTypes:
|
||||||
|
- Ingress
|
||||||
|
- Egress
|
||||||
|
ingress:
|
||||||
|
- from:
|
||||||
|
- podSelector:
|
||||||
|
matchLabels:
|
||||||
|
{{- include "pargar.selectorLabels" . | nindent 14 }}
|
||||||
|
app.kubernetes.io/component: backend
|
||||||
|
ports:
|
||||||
|
- protocol: TCP
|
||||||
|
port: 6379
|
||||||
|
egress: []
|
||||||
|
---
|
||||||
|
{{- end }}
|
||||||
|
{{- if .Values.rustfs.enabled }}
|
||||||
|
apiVersion: networking.k8s.io/v1
|
||||||
|
kind: NetworkPolicy
|
||||||
|
metadata:
|
||||||
|
name: {{ $fullName }}-rustfs
|
||||||
|
labels:
|
||||||
|
{{- include "pargar.labels" . | nindent 4 }}
|
||||||
|
app.kubernetes.io/component: rustfs
|
||||||
|
spec:
|
||||||
|
podSelector:
|
||||||
|
matchLabels:
|
||||||
|
{{- include "pargar.selectorLabels" . | nindent 6 }}
|
||||||
|
app.kubernetes.io/component: rustfs
|
||||||
|
policyTypes:
|
||||||
|
- Ingress
|
||||||
|
- Egress
|
||||||
|
ingress:
|
||||||
|
- from:
|
||||||
|
- podSelector:
|
||||||
|
matchLabels:
|
||||||
|
{{- include "pargar.selectorLabels" . | nindent 14 }}
|
||||||
|
app.kubernetes.io/component: backend
|
||||||
|
ports:
|
||||||
|
- protocol: TCP
|
||||||
|
port: 9000
|
||||||
|
egress: []
|
||||||
|
{{- end }}
|
||||||
|
{{- end }}
|
||||||
@@ -0,0 +1,41 @@
|
|||||||
|
{{- if and .Values.backend.enabled .Values.backend.podDisruptionBudget.enabled }}
|
||||||
|
apiVersion: policy/v1
|
||||||
|
kind: PodDisruptionBudget
|
||||||
|
metadata:
|
||||||
|
name: {{ include "pargar.fullname" . }}-backend
|
||||||
|
labels:
|
||||||
|
{{- include "pargar.labels" . | nindent 4 }}
|
||||||
|
app.kubernetes.io/component: backend
|
||||||
|
spec:
|
||||||
|
{{- if .Values.backend.podDisruptionBudget.minAvailable }}
|
||||||
|
minAvailable: {{ .Values.backend.podDisruptionBudget.minAvailable }}
|
||||||
|
{{- end }}
|
||||||
|
{{- if .Values.backend.podDisruptionBudget.maxUnavailable }}
|
||||||
|
maxUnavailable: {{ .Values.backend.podDisruptionBudget.maxUnavailable }}
|
||||||
|
{{- end }}
|
||||||
|
selector:
|
||||||
|
matchLabels:
|
||||||
|
{{- include "pargar.selectorLabels" . | nindent 6 }}
|
||||||
|
app.kubernetes.io/component: backend
|
||||||
|
---
|
||||||
|
{{- end }}
|
||||||
|
{{- if and .Values.frontend.enabled .Values.frontend.podDisruptionBudget.enabled }}
|
||||||
|
apiVersion: policy/v1
|
||||||
|
kind: PodDisruptionBudget
|
||||||
|
metadata:
|
||||||
|
name: {{ include "pargar.fullname" . }}-frontend
|
||||||
|
labels:
|
||||||
|
{{- include "pargar.labels" . | nindent 4 }}
|
||||||
|
app.kubernetes.io/component: frontend
|
||||||
|
spec:
|
||||||
|
{{- if .Values.frontend.podDisruptionBudget.minAvailable }}
|
||||||
|
minAvailable: {{ .Values.frontend.podDisruptionBudget.minAvailable }}
|
||||||
|
{{- end }}
|
||||||
|
{{- if .Values.frontend.podDisruptionBudget.maxUnavailable }}
|
||||||
|
maxUnavailable: {{ .Values.frontend.podDisruptionBudget.maxUnavailable }}
|
||||||
|
{{- end }}
|
||||||
|
selector:
|
||||||
|
matchLabels:
|
||||||
|
{{- include "pargar.selectorLabels" . | nindent 6 }}
|
||||||
|
app.kubernetes.io/component: frontend
|
||||||
|
{{- end }}
|
||||||
@@ -0,0 +1,93 @@
|
|||||||
|
{{- if .Values.postgres.enabled }}
|
||||||
|
apiVersion: v1
|
||||||
|
kind: Service
|
||||||
|
metadata:
|
||||||
|
name: {{ include "pargar.postgresHost" . }}
|
||||||
|
labels:
|
||||||
|
{{- include "pargar.labels" . | nindent 4 }}
|
||||||
|
app.kubernetes.io/component: postgres
|
||||||
|
spec:
|
||||||
|
type: ClusterIP
|
||||||
|
ports:
|
||||||
|
- name: postgres
|
||||||
|
port: 5432
|
||||||
|
targetPort: postgres
|
||||||
|
selector:
|
||||||
|
{{- include "pargar.selectorLabels" . | nindent 4 }}
|
||||||
|
app.kubernetes.io/component: postgres
|
||||||
|
---
|
||||||
|
apiVersion: apps/v1
|
||||||
|
kind: StatefulSet
|
||||||
|
metadata:
|
||||||
|
name: {{ include "pargar.fullname" . }}-postgres
|
||||||
|
labels:
|
||||||
|
{{- include "pargar.labels" . | nindent 4 }}
|
||||||
|
app.kubernetes.io/component: postgres
|
||||||
|
spec:
|
||||||
|
serviceName: {{ include "pargar.postgresHost" . }}
|
||||||
|
replicas: 1
|
||||||
|
selector:
|
||||||
|
matchLabels:
|
||||||
|
{{- include "pargar.selectorLabels" . | nindent 6 }}
|
||||||
|
app.kubernetes.io/component: postgres
|
||||||
|
template:
|
||||||
|
metadata:
|
||||||
|
labels:
|
||||||
|
{{- include "pargar.selectorLabels" . | nindent 8 }}
|
||||||
|
app.kubernetes.io/component: postgres
|
||||||
|
spec:
|
||||||
|
containers:
|
||||||
|
- name: postgres
|
||||||
|
image: {{ .Values.postgres.image }}
|
||||||
|
imagePullPolicy: IfNotPresent
|
||||||
|
ports:
|
||||||
|
- name: postgres
|
||||||
|
containerPort: 5432
|
||||||
|
env:
|
||||||
|
- name: POSTGRES_USER
|
||||||
|
value: {{ .Values.postgres.auth.username | quote }}
|
||||||
|
- name: POSTGRES_DB
|
||||||
|
value: {{ .Values.postgres.auth.database | quote }}
|
||||||
|
- name: POSTGRES_PASSWORD
|
||||||
|
valueFrom:
|
||||||
|
secretKeyRef:
|
||||||
|
name: {{ include "pargar.postgresSecretName" . }}
|
||||||
|
key: postgres-password
|
||||||
|
- name: PGDATA
|
||||||
|
value: /var/lib/postgresql/data/pgdata
|
||||||
|
readinessProbe:
|
||||||
|
exec:
|
||||||
|
command: ["pg_isready", "-U", {{ .Values.postgres.auth.username | quote }}, "-d", {{ .Values.postgres.auth.database | quote }}]
|
||||||
|
initialDelaySeconds: 5
|
||||||
|
periodSeconds: 5
|
||||||
|
livenessProbe:
|
||||||
|
exec:
|
||||||
|
command: ["pg_isready", "-U", {{ .Values.postgres.auth.username | quote }}, "-d", {{ .Values.postgres.auth.database | quote }}]
|
||||||
|
initialDelaySeconds: 15
|
||||||
|
periodSeconds: 10
|
||||||
|
{{- with .Values.postgres.resources }}
|
||||||
|
resources:
|
||||||
|
{{- toYaml . | nindent 12 }}
|
||||||
|
{{- end }}
|
||||||
|
volumeMounts:
|
||||||
|
- name: data
|
||||||
|
mountPath: /var/lib/postgresql/data
|
||||||
|
{{- if not .Values.postgres.persistence.enabled }}
|
||||||
|
volumes:
|
||||||
|
- name: data
|
||||||
|
emptyDir: {}
|
||||||
|
{{- end }}
|
||||||
|
{{- if .Values.postgres.persistence.enabled }}
|
||||||
|
volumeClaimTemplates:
|
||||||
|
- metadata:
|
||||||
|
name: data
|
||||||
|
spec:
|
||||||
|
accessModes: ["ReadWriteOnce"]
|
||||||
|
{{- if .Values.postgres.persistence.storageClass }}
|
||||||
|
storageClassName: {{ .Values.postgres.persistence.storageClass | quote }}
|
||||||
|
{{- end }}
|
||||||
|
resources:
|
||||||
|
requests:
|
||||||
|
storage: {{ .Values.postgres.persistence.size }}
|
||||||
|
{{- end }}
|
||||||
|
{{- end }}
|
||||||
@@ -0,0 +1,88 @@
|
|||||||
|
{{- if .Values.redis.enabled }}
|
||||||
|
apiVersion: v1
|
||||||
|
kind: Service
|
||||||
|
metadata:
|
||||||
|
name: {{ include "pargar.redisHost" . }}
|
||||||
|
labels:
|
||||||
|
{{- include "pargar.labels" . | nindent 4 }}
|
||||||
|
app.kubernetes.io/component: redis
|
||||||
|
spec:
|
||||||
|
type: ClusterIP
|
||||||
|
ports:
|
||||||
|
- name: redis
|
||||||
|
port: 6379
|
||||||
|
targetPort: redis
|
||||||
|
selector:
|
||||||
|
{{- include "pargar.selectorLabels" . | nindent 4 }}
|
||||||
|
app.kubernetes.io/component: redis
|
||||||
|
---
|
||||||
|
apiVersion: apps/v1
|
||||||
|
kind: StatefulSet
|
||||||
|
metadata:
|
||||||
|
name: {{ include "pargar.fullname" . }}-redis
|
||||||
|
labels:
|
||||||
|
{{- include "pargar.labels" . | nindent 4 }}
|
||||||
|
app.kubernetes.io/component: redis
|
||||||
|
spec:
|
||||||
|
serviceName: {{ include "pargar.redisHost" . }}
|
||||||
|
replicas: 1
|
||||||
|
selector:
|
||||||
|
matchLabels:
|
||||||
|
{{- include "pargar.selectorLabels" . | nindent 6 }}
|
||||||
|
app.kubernetes.io/component: redis
|
||||||
|
template:
|
||||||
|
metadata:
|
||||||
|
labels:
|
||||||
|
{{- include "pargar.selectorLabels" . | nindent 8 }}
|
||||||
|
app.kubernetes.io/component: redis
|
||||||
|
spec:
|
||||||
|
containers:
|
||||||
|
- name: redis
|
||||||
|
image: {{ .Values.redis.image }}
|
||||||
|
imagePullPolicy: IfNotPresent
|
||||||
|
command: ["sh", "-c", "exec redis-server --requirepass \"$REDIS_PASSWORD\" --appendonly yes"]
|
||||||
|
ports:
|
||||||
|
- name: redis
|
||||||
|
containerPort: 6379
|
||||||
|
env:
|
||||||
|
- name: REDIS_PASSWORD
|
||||||
|
valueFrom:
|
||||||
|
secretKeyRef:
|
||||||
|
name: {{ include "pargar.redisSecretName" . }}
|
||||||
|
key: redis-password
|
||||||
|
readinessProbe:
|
||||||
|
exec:
|
||||||
|
command: ["sh", "-c", "redis-cli -a \"$REDIS_PASSWORD\" ping | grep -q PONG"]
|
||||||
|
initialDelaySeconds: 5
|
||||||
|
periodSeconds: 5
|
||||||
|
livenessProbe:
|
||||||
|
exec:
|
||||||
|
command: ["sh", "-c", "redis-cli -a \"$REDIS_PASSWORD\" ping | grep -q PONG"]
|
||||||
|
initialDelaySeconds: 15
|
||||||
|
periodSeconds: 10
|
||||||
|
{{- with .Values.redis.resources }}
|
||||||
|
resources:
|
||||||
|
{{- toYaml . | nindent 12 }}
|
||||||
|
{{- end }}
|
||||||
|
volumeMounts:
|
||||||
|
- name: data
|
||||||
|
mountPath: /data
|
||||||
|
{{- if not .Values.redis.persistence.enabled }}
|
||||||
|
volumes:
|
||||||
|
- name: data
|
||||||
|
emptyDir: {}
|
||||||
|
{{- end }}
|
||||||
|
{{- if .Values.redis.persistence.enabled }}
|
||||||
|
volumeClaimTemplates:
|
||||||
|
- metadata:
|
||||||
|
name: data
|
||||||
|
spec:
|
||||||
|
accessModes: ["ReadWriteOnce"]
|
||||||
|
{{- if .Values.redis.persistence.storageClass }}
|
||||||
|
storageClassName: {{ .Values.redis.persistence.storageClass | quote }}
|
||||||
|
{{- end }}
|
||||||
|
resources:
|
||||||
|
requests:
|
||||||
|
storage: {{ .Values.redis.persistence.size }}
|
||||||
|
{{- end }}
|
||||||
|
{{- end }}
|
||||||
@@ -0,0 +1,101 @@
|
|||||||
|
{{- if .Values.rustfs.enabled }}
|
||||||
|
apiVersion: v1
|
||||||
|
kind: Service
|
||||||
|
metadata:
|
||||||
|
name: {{ include "pargar.rustfsHost" . }}
|
||||||
|
labels:
|
||||||
|
{{- include "pargar.labels" . | nindent 4 }}
|
||||||
|
app.kubernetes.io/component: rustfs
|
||||||
|
spec:
|
||||||
|
type: ClusterIP
|
||||||
|
ports:
|
||||||
|
- name: s3
|
||||||
|
port: 9000
|
||||||
|
targetPort: s3
|
||||||
|
selector:
|
||||||
|
{{- include "pargar.selectorLabels" . | nindent 4 }}
|
||||||
|
app.kubernetes.io/component: rustfs
|
||||||
|
---
|
||||||
|
apiVersion: apps/v1
|
||||||
|
kind: StatefulSet
|
||||||
|
metadata:
|
||||||
|
name: {{ include "pargar.fullname" . }}-rustfs
|
||||||
|
labels:
|
||||||
|
{{- include "pargar.labels" . | nindent 4 }}
|
||||||
|
app.kubernetes.io/component: rustfs
|
||||||
|
spec:
|
||||||
|
serviceName: {{ include "pargar.rustfsHost" . }}
|
||||||
|
replicas: 1
|
||||||
|
selector:
|
||||||
|
matchLabels:
|
||||||
|
{{- include "pargar.selectorLabels" . | nindent 6 }}
|
||||||
|
app.kubernetes.io/component: rustfs
|
||||||
|
template:
|
||||||
|
metadata:
|
||||||
|
labels:
|
||||||
|
{{- include "pargar.selectorLabels" . | nindent 8 }}
|
||||||
|
app.kubernetes.io/component: rustfs
|
||||||
|
spec:
|
||||||
|
containers:
|
||||||
|
- name: rustfs
|
||||||
|
image: {{ .Values.rustfs.image }}
|
||||||
|
imagePullPolicy: IfNotPresent
|
||||||
|
args: ["/data"]
|
||||||
|
ports:
|
||||||
|
- name: s3
|
||||||
|
containerPort: 9000
|
||||||
|
env:
|
||||||
|
- name: RUSTFS_ACCESS_KEY
|
||||||
|
valueFrom:
|
||||||
|
secretKeyRef:
|
||||||
|
name: {{ include "pargar.rustfsSecretName" . }}
|
||||||
|
key: access-key
|
||||||
|
- name: RUSTFS_SECRET_KEY
|
||||||
|
valueFrom:
|
||||||
|
secretKeyRef:
|
||||||
|
name: {{ include "pargar.rustfsSecretName" . }}
|
||||||
|
key: secret-key
|
||||||
|
- name: RUSTFS_ADDRESS
|
||||||
|
value: ":9000"
|
||||||
|
- name: RUSTFS_CONSOLE_ADDRESS
|
||||||
|
value: ":9001"
|
||||||
|
- name: RUSTFS_CONSOLE_ENABLE
|
||||||
|
value: {{ .Values.rustfs.consoleEnable | ternary "true" "false" | quote }}
|
||||||
|
readinessProbe:
|
||||||
|
httpGet:
|
||||||
|
path: /health
|
||||||
|
port: s3
|
||||||
|
initialDelaySeconds: 10
|
||||||
|
periodSeconds: 5
|
||||||
|
livenessProbe:
|
||||||
|
httpGet:
|
||||||
|
path: /health
|
||||||
|
port: s3
|
||||||
|
initialDelaySeconds: 20
|
||||||
|
periodSeconds: 10
|
||||||
|
{{- with .Values.rustfs.resources }}
|
||||||
|
resources:
|
||||||
|
{{- toYaml . | nindent 12 }}
|
||||||
|
{{- end }}
|
||||||
|
volumeMounts:
|
||||||
|
- name: data
|
||||||
|
mountPath: /data
|
||||||
|
{{- if not .Values.rustfs.persistence.enabled }}
|
||||||
|
volumes:
|
||||||
|
- name: data
|
||||||
|
emptyDir: {}
|
||||||
|
{{- end }}
|
||||||
|
{{- if .Values.rustfs.persistence.enabled }}
|
||||||
|
volumeClaimTemplates:
|
||||||
|
- metadata:
|
||||||
|
name: data
|
||||||
|
spec:
|
||||||
|
accessModes: ["ReadWriteOnce"]
|
||||||
|
{{- if .Values.rustfs.persistence.storageClass }}
|
||||||
|
storageClassName: {{ .Values.rustfs.persistence.storageClass | quote }}
|
||||||
|
{{- end }}
|
||||||
|
resources:
|
||||||
|
requests:
|
||||||
|
storage: {{ .Values.rustfs.persistence.size }}
|
||||||
|
{{- end }}
|
||||||
|
{{- end }}
|
||||||
@@ -0,0 +1,56 @@
|
|||||||
|
{{- if and .Values.backend.enabled (not .Values.backend.existingSecret) }}
|
||||||
|
{{- $name := include "pargar.appSecretName" . }}
|
||||||
|
{{- $existing := lookup "v1" "Secret" .Release.Namespace $name }}
|
||||||
|
{{- $jwt := "" }}
|
||||||
|
{{- $admin := "" }}
|
||||||
|
{{- $metrics := .Values.backend.secrets.metricsToken | default "" }}
|
||||||
|
{{- if and $existing $existing.data }}
|
||||||
|
{{- /* Reuse existing secrets so upgrades do not invalidate sessions / bootstrap. */}}
|
||||||
|
{{- if index $existing.data "jwt-secret" }}
|
||||||
|
{{- $jwt = index $existing.data "jwt-secret" | b64dec }}
|
||||||
|
{{- end }}
|
||||||
|
{{- if index $existing.data "admin-password" }}
|
||||||
|
{{- $admin = index $existing.data "admin-password" | b64dec }}
|
||||||
|
{{- end }}
|
||||||
|
{{- if and (not $metrics) (index $existing.data "metrics-token") }}
|
||||||
|
{{- $metrics = index $existing.data "metrics-token" | b64dec }}
|
||||||
|
{{- end }}
|
||||||
|
{{- end }}
|
||||||
|
{{- if not $jwt }}
|
||||||
|
{{- if and .Values.backend.secrets.jwtSecret (not (hasPrefix "change-me" .Values.backend.secrets.jwtSecret)) (ne .Values.backend.secrets.jwtSecret "") }}
|
||||||
|
{{- $jwt = .Values.backend.secrets.jwtSecret }}
|
||||||
|
{{- else }}
|
||||||
|
{{- $jwt = randAlphaNum 48 }}
|
||||||
|
{{- end }}
|
||||||
|
{{- end }}
|
||||||
|
{{- if not $admin }}
|
||||||
|
{{- if and .Values.backend.secrets.adminPassword (not (hasPrefix "change-me" .Values.backend.secrets.adminPassword)) (ne .Values.backend.secrets.adminPassword "") }}
|
||||||
|
{{- $admin = .Values.backend.secrets.adminPassword }}
|
||||||
|
{{- else }}
|
||||||
|
{{- $admin = randAlphaNum 24 }}
|
||||||
|
{{- end }}
|
||||||
|
{{- end }}
|
||||||
|
apiVersion: v1
|
||||||
|
kind: Secret
|
||||||
|
metadata:
|
||||||
|
name: {{ $name }}
|
||||||
|
labels:
|
||||||
|
{{- include "pargar.labels" . | nindent 4 }}
|
||||||
|
annotations:
|
||||||
|
pargar.io/secret-source: generated-or-values
|
||||||
|
type: Opaque
|
||||||
|
stringData:
|
||||||
|
jwt-secret: {{ $jwt | quote }}
|
||||||
|
admin-password: {{ $admin | quote }}
|
||||||
|
metrics-token: {{ $metrics | quote }}
|
||||||
|
{{- if not .Values.postgres.enabled }}
|
||||||
|
database-url: {{ required "external.databaseUrl required when postgres.enabled=false and existingSecret is empty" .Values.external.databaseUrl | quote }}
|
||||||
|
{{- end }}
|
||||||
|
{{- if not .Values.redis.enabled }}
|
||||||
|
redis-url: {{ required "external.redisUrl required when redis.enabled=false and existingSecret is empty" .Values.external.redisUrl | quote }}
|
||||||
|
{{- end }}
|
||||||
|
{{- if not .Values.rustfs.enabled }}
|
||||||
|
storage-access-key: {{ required "external.storageAccessKey required when rustfs.enabled=false and existingSecret is empty" .Values.external.storageAccessKey | quote }}
|
||||||
|
storage-secret-key: {{ required "external.storageSecretKey required when rustfs.enabled=false and existingSecret is empty" .Values.external.storageSecretKey | quote }}
|
||||||
|
{{- end }}
|
||||||
|
{{- end }}
|
||||||
@@ -0,0 +1,71 @@
|
|||||||
|
{{- if and .Values.postgres.enabled (not .Values.postgres.existingSecret) }}
|
||||||
|
{{- $pgName := include "pargar.postgresSecretName" . }}
|
||||||
|
{{- $pgExisting := lookup "v1" "Secret" .Release.Namespace $pgName }}
|
||||||
|
{{- $pgPass := "" }}
|
||||||
|
{{- if and $pgExisting $pgExisting.data (index $pgExisting.data "postgres-password") }}
|
||||||
|
{{- /* Never rotate an existing DB password — Postgres data dir is bound to it. */}}
|
||||||
|
{{- $pgPass = index $pgExisting.data "postgres-password" | b64dec }}
|
||||||
|
{{- else if and .Values.postgres.auth.password (not (hasPrefix "change-me" .Values.postgres.auth.password)) (ne .Values.postgres.auth.password "") }}
|
||||||
|
{{- $pgPass = .Values.postgres.auth.password }}
|
||||||
|
{{- else }}
|
||||||
|
{{- $pgPass = randAlphaNum 32 }}
|
||||||
|
{{- end }}
|
||||||
|
apiVersion: v1
|
||||||
|
kind: Secret
|
||||||
|
metadata:
|
||||||
|
name: {{ $pgName }}
|
||||||
|
labels:
|
||||||
|
{{- include "pargar.labels" . | nindent 4 }}
|
||||||
|
type: Opaque
|
||||||
|
stringData:
|
||||||
|
postgres-password: {{ $pgPass | quote }}
|
||||||
|
---
|
||||||
|
{{- end }}
|
||||||
|
{{- if and .Values.redis.enabled (not .Values.redis.existingSecret) }}
|
||||||
|
{{- $rdName := include "pargar.redisSecretName" . }}
|
||||||
|
{{- $rdExisting := lookup "v1" "Secret" .Release.Namespace $rdName }}
|
||||||
|
{{- $rdPass := "" }}
|
||||||
|
{{- if and $rdExisting $rdExisting.data (index $rdExisting.data "redis-password") }}
|
||||||
|
{{- $rdPass = index $rdExisting.data "redis-password" | b64dec }}
|
||||||
|
{{- else if and .Values.redis.auth.password (not (hasPrefix "change-me" .Values.redis.auth.password)) (ne .Values.redis.auth.password "") }}
|
||||||
|
{{- $rdPass = .Values.redis.auth.password }}
|
||||||
|
{{- else }}
|
||||||
|
{{- $rdPass = randAlphaNum 32 }}
|
||||||
|
{{- end }}
|
||||||
|
apiVersion: v1
|
||||||
|
kind: Secret
|
||||||
|
metadata:
|
||||||
|
name: {{ $rdName }}
|
||||||
|
labels:
|
||||||
|
{{- include "pargar.labels" . | nindent 4 }}
|
||||||
|
type: Opaque
|
||||||
|
stringData:
|
||||||
|
redis-password: {{ $rdPass | quote }}
|
||||||
|
---
|
||||||
|
{{- end }}
|
||||||
|
{{- if and .Values.rustfs.enabled (not .Values.rustfs.existingSecret) }}
|
||||||
|
{{- $rsName := include "pargar.rustfsSecretName" . }}
|
||||||
|
{{- $rsExisting := lookup "v1" "Secret" .Release.Namespace $rsName }}
|
||||||
|
{{- $access := .Values.rustfs.auth.accessKey | default "pargar" }}
|
||||||
|
{{- $secret := "" }}
|
||||||
|
{{- if and $rsExisting $rsExisting.data (index $rsExisting.data "secret-key") }}
|
||||||
|
{{- $secret = index $rsExisting.data "secret-key" | b64dec }}
|
||||||
|
{{- if index $rsExisting.data "access-key" }}
|
||||||
|
{{- $access = index $rsExisting.data "access-key" | b64dec }}
|
||||||
|
{{- end }}
|
||||||
|
{{- else if and .Values.rustfs.auth.secretKey (not (hasPrefix "change-me" .Values.rustfs.auth.secretKey)) (ne .Values.rustfs.auth.secretKey "") }}
|
||||||
|
{{- $secret = .Values.rustfs.auth.secretKey }}
|
||||||
|
{{- else }}
|
||||||
|
{{- $secret = randAlphaNum 40 }}
|
||||||
|
{{- end }}
|
||||||
|
apiVersion: v1
|
||||||
|
kind: Secret
|
||||||
|
metadata:
|
||||||
|
name: {{ $rsName }}
|
||||||
|
labels:
|
||||||
|
{{- include "pargar.labels" . | nindent 4 }}
|
||||||
|
type: Opaque
|
||||||
|
stringData:
|
||||||
|
access-key: {{ $access | quote }}
|
||||||
|
secret-key: {{ $secret | quote }}
|
||||||
|
{{- end }}
|
||||||
@@ -0,0 +1,12 @@
|
|||||||
|
{{- if .Values.serviceAccount.create }}
|
||||||
|
apiVersion: v1
|
||||||
|
kind: ServiceAccount
|
||||||
|
metadata:
|
||||||
|
name: {{ include "pargar.serviceAccountName" . }}
|
||||||
|
labels:
|
||||||
|
{{- include "pargar.labels" . | nindent 4 }}
|
||||||
|
{{- with .Values.serviceAccount.annotations }}
|
||||||
|
annotations:
|
||||||
|
{{- toYaml . | nindent 4 }}
|
||||||
|
{{- end }}
|
||||||
|
{{- end }}
|
||||||
@@ -0,0 +1,21 @@
|
|||||||
|
{{- if and .Values.ingress.enabled .Values.ingress.tls.enabled (not .Values.ingress.tls.existingSecret) (not .Values.certManager.enabled) }}
|
||||||
|
{{- $secretName := include "pargar.tlsSecretName" . }}
|
||||||
|
{{- $existing := lookup "v1" "Secret" .Release.Namespace $secretName }}
|
||||||
|
{{- $cn := .Values.global.domain }}
|
||||||
|
apiVersion: v1
|
||||||
|
kind: Secret
|
||||||
|
metadata:
|
||||||
|
name: {{ $secretName }}
|
||||||
|
labels:
|
||||||
|
{{- include "pargar.labels" . | nindent 4 }}
|
||||||
|
type: kubernetes.tls
|
||||||
|
data:
|
||||||
|
{{- if $existing }}
|
||||||
|
tls.crt: {{ index $existing.data "tls.crt" }}
|
||||||
|
tls.key: {{ index $existing.data "tls.key" }}
|
||||||
|
{{- else }}
|
||||||
|
{{- $cert := genSelfSignedCert $cn nil (list $cn) 3650 }}
|
||||||
|
tls.crt: {{ $cert.Cert | b64enc }}
|
||||||
|
tls.key: {{ $cert.Key | b64enc }}
|
||||||
|
{{- end }}
|
||||||
|
{{- end }}
|
||||||
@@ -0,0 +1,55 @@
|
|||||||
|
# Local k3s profile — self-signed TLS, in-cluster data, single replicas.
|
||||||
|
# helm upgrade --install pargar ./deploy/helm/pargar -n pargar --create-namespace -f deploy/helm/pargar/values-k3s.yaml
|
||||||
|
#
|
||||||
|
# After install, add to /etc/hosts: <NODE_IP> pargar.local
|
||||||
|
|
||||||
|
global:
|
||||||
|
domain: pargar.local
|
||||||
|
publicUrl: https://pargar.local
|
||||||
|
frontendOrigins: "https://pargar.local"
|
||||||
|
|
||||||
|
backend:
|
||||||
|
replicaCount: 1
|
||||||
|
image:
|
||||||
|
repository: pargar-backend
|
||||||
|
tag: local
|
||||||
|
pullPolicy: IfNotPresent
|
||||||
|
env:
|
||||||
|
seedCurriculum: "true"
|
||||||
|
|
||||||
|
frontend:
|
||||||
|
replicaCount: 1
|
||||||
|
image:
|
||||||
|
repository: pargar-frontend
|
||||||
|
tag: local
|
||||||
|
pullPolicy: IfNotPresent
|
||||||
|
|
||||||
|
postgres:
|
||||||
|
enabled: true
|
||||||
|
persistence:
|
||||||
|
size: 5Gi
|
||||||
|
|
||||||
|
redis:
|
||||||
|
enabled: true
|
||||||
|
persistence:
|
||||||
|
size: 1Gi
|
||||||
|
|
||||||
|
rustfs:
|
||||||
|
enabled: true
|
||||||
|
persistence:
|
||||||
|
size: 10Gi
|
||||||
|
consoleEnable: false
|
||||||
|
|
||||||
|
backup:
|
||||||
|
enabled: true
|
||||||
|
schedule: "0 3 * * *"
|
||||||
|
retentionDays: 7
|
||||||
|
persistence:
|
||||||
|
size: 2Gi
|
||||||
|
|
||||||
|
ingress:
|
||||||
|
enabled: true
|
||||||
|
useIngressRoute: true
|
||||||
|
tls:
|
||||||
|
enabled: true
|
||||||
|
existingSecret: "" # chart generates self-signed for pargar.local
|
||||||
@@ -0,0 +1,103 @@
|
|||||||
|
# Production profile — external data plane, registry images, HPA/PDB/NetworkPolicy, cert-manager.
|
||||||
|
# helm upgrade --install pargar ./deploy/helm/pargar -n pargar --create-namespace \
|
||||||
|
# -f deploy/helm/pargar/values-prod.yaml
|
||||||
|
#
|
||||||
|
# Prerequisites:
|
||||||
|
# - images pushed to ghcr.io/pargar/{backend,frontend}:<tag>
|
||||||
|
# - Secret pargar-app (jwt-secret, admin-password, metrics-token, database-url, redis-url,
|
||||||
|
# storage-access-key, storage-secret-key)
|
||||||
|
# - cert-manager ClusterIssuer letsencrypt-prod
|
||||||
|
# - imagePullSecrets if the registry is private
|
||||||
|
|
||||||
|
global:
|
||||||
|
domain: app.example.com
|
||||||
|
publicUrl: https://app.example.com
|
||||||
|
frontendOrigins: "https://app.example.com"
|
||||||
|
imageRegistry: ghcr.io/pargar
|
||||||
|
|
||||||
|
imagePullSecrets:
|
||||||
|
- name: ghcr-pull
|
||||||
|
|
||||||
|
backend:
|
||||||
|
replicaCount: 2
|
||||||
|
image:
|
||||||
|
repository: backend
|
||||||
|
tag: "0.1.0"
|
||||||
|
pullPolicy: IfNotPresent
|
||||||
|
existingSecret: pargar-app
|
||||||
|
env:
|
||||||
|
devMode: "false"
|
||||||
|
seedCurriculum: "false"
|
||||||
|
resources:
|
||||||
|
requests:
|
||||||
|
cpu: 100m
|
||||||
|
memory: 256Mi
|
||||||
|
limits:
|
||||||
|
cpu: "2"
|
||||||
|
memory: 1Gi
|
||||||
|
autoscaling:
|
||||||
|
enabled: true
|
||||||
|
minReplicas: 2
|
||||||
|
maxReplicas: 8
|
||||||
|
targetCPUUtilizationPercentage: 70
|
||||||
|
targetMemoryUtilizationPercentage: 80
|
||||||
|
podDisruptionBudget:
|
||||||
|
enabled: true
|
||||||
|
minAvailable: 1
|
||||||
|
|
||||||
|
frontend:
|
||||||
|
replicaCount: 2
|
||||||
|
image:
|
||||||
|
repository: frontend
|
||||||
|
tag: "0.1.0"
|
||||||
|
pullPolicy: IfNotPresent
|
||||||
|
resources:
|
||||||
|
requests:
|
||||||
|
cpu: 100m
|
||||||
|
memory: 256Mi
|
||||||
|
limits:
|
||||||
|
cpu: "2"
|
||||||
|
memory: 1Gi
|
||||||
|
autoscaling:
|
||||||
|
enabled: true
|
||||||
|
minReplicas: 2
|
||||||
|
maxReplicas: 8
|
||||||
|
targetCPUUtilizationPercentage: 70
|
||||||
|
targetMemoryUtilizationPercentage: 80
|
||||||
|
podDisruptionBudget:
|
||||||
|
enabled: true
|
||||||
|
minAvailable: 1
|
||||||
|
|
||||||
|
# Prefer managed Postgres / Redis / object storage in real prod.
|
||||||
|
postgres:
|
||||||
|
enabled: false
|
||||||
|
redis:
|
||||||
|
enabled: false
|
||||||
|
rustfs:
|
||||||
|
enabled: false
|
||||||
|
|
||||||
|
external:
|
||||||
|
databaseUrl: "" # prefer secret key database-url on pargar-app
|
||||||
|
redisUrl: ""
|
||||||
|
storageEndpoint: "https://s3.example.com"
|
||||||
|
|
||||||
|
ingress:
|
||||||
|
enabled: true
|
||||||
|
useIngressRoute: true
|
||||||
|
tls:
|
||||||
|
enabled: true
|
||||||
|
existingSecret: "" # Certificate CR owns the secret below
|
||||||
|
clusterIssuer: letsencrypt-prod
|
||||||
|
|
||||||
|
certManager:
|
||||||
|
enabled: true
|
||||||
|
issuerRef:
|
||||||
|
name: letsencrypt-prod
|
||||||
|
kind: ClusterIssuer
|
||||||
|
|
||||||
|
networkPolicy:
|
||||||
|
enabled: true
|
||||||
|
ingressNamespaces:
|
||||||
|
- kube-system
|
||||||
|
ingressPodLabels:
|
||||||
|
app.kubernetes.io/name: traefik
|
||||||
@@ -0,0 +1,231 @@
|
|||||||
|
# Default values — safe for local k3s. Override with values-k3s.yaml / values-prod.yaml.
|
||||||
|
|
||||||
|
nameOverride: ""
|
||||||
|
fullnameOverride: ""
|
||||||
|
|
||||||
|
global:
|
||||||
|
# Public hostname (Ingress / TLS / PUBLIC_URL)
|
||||||
|
domain: pargar.local
|
||||||
|
# Full public origin browsers use (must match Ingress TLS host)
|
||||||
|
publicUrl: https://pargar.local
|
||||||
|
frontendOrigins: "https://pargar.local"
|
||||||
|
# Docker/k8s pod+service CIDRs — Traefik peer is trusted for X-Forwarded-*
|
||||||
|
trustedProxyCIDRs: "10.0.0.0/8,172.16.0.0/12,192.168.0.0/16,127.0.0.0/8,::1/128"
|
||||||
|
# Optional registry prefix, e.g. ghcr.io/pargar → images become ghcr.io/pargar/<repository>:<tag>
|
||||||
|
imageRegistry: ""
|
||||||
|
|
||||||
|
imagePullSecrets: []
|
||||||
|
|
||||||
|
backend:
|
||||||
|
enabled: true
|
||||||
|
replicaCount: 1
|
||||||
|
image:
|
||||||
|
repository: pargar-backend
|
||||||
|
tag: local
|
||||||
|
pullPolicy: IfNotPresent
|
||||||
|
service:
|
||||||
|
port: 8080
|
||||||
|
resources:
|
||||||
|
requests:
|
||||||
|
cpu: 50m
|
||||||
|
memory: 128Mi
|
||||||
|
limits:
|
||||||
|
cpu: "1"
|
||||||
|
memory: 512Mi
|
||||||
|
autoscaling:
|
||||||
|
enabled: false
|
||||||
|
minReplicas: 2
|
||||||
|
maxReplicas: 6
|
||||||
|
targetCPUUtilizationPercentage: 70
|
||||||
|
targetMemoryUtilizationPercentage: 80
|
||||||
|
podDisruptionBudget:
|
||||||
|
enabled: false
|
||||||
|
minAvailable: 1
|
||||||
|
env:
|
||||||
|
devMode: "false"
|
||||||
|
seedCurriculum: "false"
|
||||||
|
# false behind NAT / shared egress (peer IP is not a real client).
|
||||||
|
registrationEnforceIP: "false"
|
||||||
|
donationEnabled: "true"
|
||||||
|
# Offline payment only — leave off until ops process is ready; enable in admin settings.
|
||||||
|
physicalCertEnabled: "false"
|
||||||
|
physicalCertPriceIrr: "2500000"
|
||||||
|
physicalCertWindowDays: "30"
|
||||||
|
otelEndpoint: ""
|
||||||
|
otelServiceName: pargar-api
|
||||||
|
# Created only when admin user is missing (see seed.ensureBootstrapAdmin)
|
||||||
|
admin:
|
||||||
|
name: Admin
|
||||||
|
username: admin
|
||||||
|
email: admin@example.com
|
||||||
|
# Prefer existingSecret in production. When empty, chart generate-once (lookup + rand).
|
||||||
|
existingSecret: ""
|
||||||
|
# Optional overrides; leave empty to auto-generate strong values (placeholders like change-me-* are ignored).
|
||||||
|
secrets:
|
||||||
|
jwtSecret: ""
|
||||||
|
adminPassword: ""
|
||||||
|
metricsToken: ""
|
||||||
|
|
||||||
|
frontend:
|
||||||
|
enabled: true
|
||||||
|
replicaCount: 1
|
||||||
|
image:
|
||||||
|
repository: pargar-frontend
|
||||||
|
tag: local
|
||||||
|
pullPolicy: IfNotPresent
|
||||||
|
service:
|
||||||
|
port: 3000
|
||||||
|
resources:
|
||||||
|
requests:
|
||||||
|
cpu: 50m
|
||||||
|
memory: 128Mi
|
||||||
|
limits:
|
||||||
|
cpu: "1"
|
||||||
|
memory: 512Mi
|
||||||
|
autoscaling:
|
||||||
|
enabled: false
|
||||||
|
minReplicas: 2
|
||||||
|
maxReplicas: 6
|
||||||
|
targetCPUUtilizationPercentage: 70
|
||||||
|
targetMemoryUtilizationPercentage: 80
|
||||||
|
podDisruptionBudget:
|
||||||
|
enabled: false
|
||||||
|
minAvailable: 1
|
||||||
|
|
||||||
|
# In-cluster data plane (k3s / small clusters). Disable and point to managed services in prod.
|
||||||
|
postgres:
|
||||||
|
enabled: true
|
||||||
|
image: postgres:16.4-alpine
|
||||||
|
persistence:
|
||||||
|
enabled: true
|
||||||
|
size: 10Gi
|
||||||
|
storageClass: ""
|
||||||
|
resources:
|
||||||
|
requests:
|
||||||
|
cpu: 50m
|
||||||
|
memory: 128Mi
|
||||||
|
limits:
|
||||||
|
memory: 512Mi
|
||||||
|
auth:
|
||||||
|
username: pargar
|
||||||
|
database: pargar
|
||||||
|
# Empty → chart generate-once; placeholders change-me-* are ignored.
|
||||||
|
password: ""
|
||||||
|
existingSecret: ""
|
||||||
|
|
||||||
|
redis:
|
||||||
|
enabled: true
|
||||||
|
image: redis@sha256:858f009f9709ce576febc734aa78b8f6d624b82571f9ddb6bda4377c833b3499
|
||||||
|
persistence:
|
||||||
|
enabled: true
|
||||||
|
size: 2Gi
|
||||||
|
storageClass: ""
|
||||||
|
resources:
|
||||||
|
requests:
|
||||||
|
cpu: 25m
|
||||||
|
memory: 64Mi
|
||||||
|
limits:
|
||||||
|
memory: 256Mi
|
||||||
|
auth:
|
||||||
|
password: ""
|
||||||
|
existingSecret: ""
|
||||||
|
|
||||||
|
rustfs:
|
||||||
|
enabled: true
|
||||||
|
image: rustfs/rustfs@sha256:1803faef57627e2d9c2e7d89d655d712ddded5389040054987163043fecb6a3c
|
||||||
|
persistence:
|
||||||
|
enabled: true
|
||||||
|
size: 20Gi
|
||||||
|
storageClass: ""
|
||||||
|
resources:
|
||||||
|
requests:
|
||||||
|
cpu: 50m
|
||||||
|
memory: 128Mi
|
||||||
|
limits:
|
||||||
|
memory: 512Mi
|
||||||
|
auth:
|
||||||
|
accessKey: "pargar-rustfs"
|
||||||
|
secretKey: ""
|
||||||
|
bucket: pargar
|
||||||
|
region: us-east-1
|
||||||
|
consoleEnable: false
|
||||||
|
existingSecret: ""
|
||||||
|
|
||||||
|
# Postgres dump CronJob (in-cluster postgres only).
|
||||||
|
backup:
|
||||||
|
enabled: false
|
||||||
|
schedule: "0 3 * * *"
|
||||||
|
retentionDays: 7
|
||||||
|
persistence:
|
||||||
|
size: 5Gi
|
||||||
|
storageClass: ""
|
||||||
|
image: postgres:16.4-alpine
|
||||||
|
|
||||||
|
# External endpoints when in-cluster postgres/redis/rustfs are disabled.
|
||||||
|
# Prefer putting these in backend.existingSecret in production.
|
||||||
|
external:
|
||||||
|
databaseUrl: ""
|
||||||
|
redisUrl: ""
|
||||||
|
storageEndpoint: ""
|
||||||
|
storageAccessKey: ""
|
||||||
|
storageSecretKey: ""
|
||||||
|
|
||||||
|
ingress:
|
||||||
|
enabled: true
|
||||||
|
# k3s ships Traefik; use IngressRoute CRDs (recommended) or standard Ingress
|
||||||
|
className: traefik
|
||||||
|
# Use Traefik IngressRoute + Middleware CRDs (true) vs networking.k8s.io/Ingress (false)
|
||||||
|
useIngressRoute: true
|
||||||
|
annotations: {}
|
||||||
|
tls:
|
||||||
|
enabled: true
|
||||||
|
# When empty and certManager.enabled=false, chart creates a self-signed Secret for k3s/dev.
|
||||||
|
# Prefer certManager.enabled=true in prod, or set existingSecret to a pre-created TLS secret.
|
||||||
|
existingSecret: ""
|
||||||
|
# cert-manager ClusterIssuer name (annotation helper when useIngressRoute=false)
|
||||||
|
clusterIssuer: ""
|
||||||
|
|
||||||
|
# cert-manager Certificate CR (writes TLS secret used by IngressRoute)
|
||||||
|
certManager:
|
||||||
|
enabled: false
|
||||||
|
duration: 2160h
|
||||||
|
renewBefore: 360h
|
||||||
|
issuerRef:
|
||||||
|
name: letsencrypt-prod
|
||||||
|
kind: ClusterIssuer
|
||||||
|
group: ""
|
||||||
|
extraDnsNames: []
|
||||||
|
|
||||||
|
# Restrict pod traffic (off for local k3s; on in values-prod.yaml)
|
||||||
|
networkPolicy:
|
||||||
|
enabled: false
|
||||||
|
# Namespaces whose pods may reach frontend/backend (Traefik)
|
||||||
|
ingressNamespaces:
|
||||||
|
- kube-system
|
||||||
|
ingressPodLabels:
|
||||||
|
app.kubernetes.io/name: traefik
|
||||||
|
|
||||||
|
middlewares:
|
||||||
|
securityHeaders: true
|
||||||
|
compress: true
|
||||||
|
redirectHttps: true
|
||||||
|
|
||||||
|
serviceAccount:
|
||||||
|
create: true
|
||||||
|
name: ""
|
||||||
|
annotations: {}
|
||||||
|
|
||||||
|
podSecurityContext:
|
||||||
|
fsGroup: 10001
|
||||||
|
|
||||||
|
securityContext:
|
||||||
|
runAsNonRoot: true
|
||||||
|
runAsUser: 10001
|
||||||
|
allowPrivilegeEscalation: false
|
||||||
|
readOnlyRootFilesystem: false
|
||||||
|
capabilities:
|
||||||
|
drop: ["ALL"]
|
||||||
|
|
||||||
|
nodeSelector: {}
|
||||||
|
tolerations: []
|
||||||
|
affinity: {}
|
||||||
@@ -0,0 +1,45 @@
|
|||||||
|
# Shared Traefik middlewares (file provider).
|
||||||
|
# Applied via Docker labels / IngressRoute references.
|
||||||
|
|
||||||
|
http:
|
||||||
|
middlewares:
|
||||||
|
redirect-https:
|
||||||
|
redirectScheme:
|
||||||
|
scheme: https
|
||||||
|
permanent: true
|
||||||
|
|
||||||
|
security-headers:
|
||||||
|
headers:
|
||||||
|
stsSeconds: 31536000
|
||||||
|
stsIncludeSubdomains: true
|
||||||
|
stsPreload: false
|
||||||
|
contentTypeNosniff: true
|
||||||
|
browserXssFilter: true
|
||||||
|
frameDeny: true
|
||||||
|
referrerPolicy: strict-origin-when-cross-origin
|
||||||
|
permissionsPolicy: "camera=(), microphone=(), geolocation=()"
|
||||||
|
customResponseHeaders:
|
||||||
|
Server: ""
|
||||||
|
Content-Security-Policy: >-
|
||||||
|
default-src 'self'; base-uri 'self'; form-action 'self';
|
||||||
|
frame-ancestors 'none'; object-src 'none';
|
||||||
|
script-src 'self' 'unsafe-inline'; style-src 'self' 'unsafe-inline';
|
||||||
|
img-src 'self' data: blob:; font-src 'self' data:;
|
||||||
|
media-src 'self' blob:; connect-src 'self' ws: wss:;
|
||||||
|
worker-src 'self' blob:
|
||||||
|
|
||||||
|
compress:
|
||||||
|
compress: {}
|
||||||
|
|
||||||
|
noindex:
|
||||||
|
headers:
|
||||||
|
customResponseHeaders:
|
||||||
|
X-Robots-Tag: "noindex, nofollow, noarchive"
|
||||||
|
|
||||||
|
# Strip client-supplied forwarding headers before Traefik re-adds trusted ones.
|
||||||
|
# Backend trusts X-Forwarded-* only from TRUSTED_PROXY_CIDRS (Docker/k8s nets).
|
||||||
|
strip-forwarded:
|
||||||
|
headers:
|
||||||
|
customRequestHeaders:
|
||||||
|
X-Real-IP: ""
|
||||||
|
X-Forwarded-For: ""
|
||||||
@@ -0,0 +1,11 @@
|
|||||||
|
# Default local stack = base + Traefik (dev).
|
||||||
|
# Prefer explicit scripts for clarity:
|
||||||
|
# ./scripts/compose-dev.sh up -d --build
|
||||||
|
# ./scripts/compose-prod.sh up -d --build
|
||||||
|
#
|
||||||
|
# Equivalent:
|
||||||
|
# docker compose -f deploy/compose/compose.yaml -f deploy/compose/compose.dev.yaml up -d --build
|
||||||
|
|
||||||
|
include:
|
||||||
|
- path: deploy/compose/compose.yaml
|
||||||
|
- path: deploy/compose/compose.dev.yaml
|
||||||
@@ -63,6 +63,7 @@ One of two patterns:
|
|||||||
|----------|-----------------|--------|
|
|----------|-----------------|--------|
|
||||||
| `DEV_MODE` | false | Open metrics without token, limited fail-open behavior |
|
| `DEV_MODE` | false | Open metrics without token, limited fail-open behavior |
|
||||||
| `SEED_CURRICULUM` | false (empty in DevMode → true) | Seed lessons/events |
|
| `SEED_CURRICULUM` | false (empty in DevMode → true) | Seed lessons/events |
|
||||||
|
| `REGISTRATION_ENFORCE_IP` | false | One registration per client IP; keep off behind NAT |
|
||||||
| `CAPTCHA_EXPOSE_ANSWER` | DevMode only | For tests; never in production |
|
| `CAPTCHA_EXPOSE_ANSWER` | DevMode only | For tests; never in production |
|
||||||
| `DONATION_ENABLED` | true | Support card |
|
| `DONATION_ENABLED` | true | Support card |
|
||||||
| `DONATION_NOTE` | Copy text | |
|
| `DONATION_NOTE` | Copy text | |
|
||||||
|
|||||||
+1
-1
@@ -28,7 +28,7 @@
|
|||||||
|
|
||||||
- Whitelist and blacklist are **mutually exclusive**; import resolves conflicts.
|
- Whitelist and blacklist are **mutually exclusive**; import resolves conflicts.
|
||||||
- A phone already tied to an account cannot re-enter either list as a fresh entry.
|
- A phone already tied to an account cannot re-enter either list as a fresh entry.
|
||||||
- One account per phone and per IP on registration paths.
|
- One account per phone. Optional one-account-per-IP (`REGISTRATION_ENFORCE_IP`, default off — unsuitable behind NAT).
|
||||||
- Blacklist blocks all registration paths (public + invite) and keeps a failed-attempt history tab.
|
- Blacklist blocks all registration paths (public + invite) and keeps a failed-attempt history tab.
|
||||||
|
|
||||||
## Certificates
|
## Certificates
|
||||||
|
|||||||
+5
-1
@@ -25,6 +25,10 @@ Public password recovery (`/api/auth/recovery/*` and `/recovery`) is disabled fo
|
|||||||
- Only peers in `TRUSTED_PROXY_CIDRS` are trusted for `X-Forwarded-*` / `X-Real-IP`.
|
- Only peers in `TRUSTED_PROXY_CIDRS` are trusted for `X-Forwarded-*` / `X-Real-IP`.
|
||||||
- CORS: `FRONTEND_ORIGINS` + `PUBLIC_URL` with `AllowCredentials: true`.
|
- CORS: `FRONTEND_ORIGINS` + `PUBLIC_URL` with `AllowCredentials: true`.
|
||||||
|
|
||||||
|
## Registration IP binding
|
||||||
|
|
||||||
|
`REGISTRATION_ENFORCE_IP` (default **false**) optionally limits one successful public/invite registration per client IP. Leave it off when the app sits behind NAT or shared egress and cannot see real client addresses. Enable only after the edge forwards trustworthy `X-Forwarded-For` / `X-Real-IP` via `TRUSTED_PROXY_CIDRS`.
|
||||||
|
|
||||||
## Rate limiting
|
## Rate limiting
|
||||||
|
|
||||||
| Scope | Approximate behavior |
|
| Scope | Approximate behavior |
|
||||||
@@ -34,7 +38,7 @@ Public password recovery (`/api/auth/recovery/*` and `/recovery`) is disabled fo
|
|||||||
| External chat export | ~10/min/IP |
|
| External chat export | ~10/min/IP |
|
||||||
| Per-user uploads | Separately limited |
|
| Per-user uploads | Separately limited |
|
||||||
|
|
||||||
`/api/health` is excluded from the global ceiling.
|
`/api/health` is excluded from the global ceiling. Note: per-IP rate limits still use the peer/forwarded address — configure trusted proxies when you need per-client fairness behind NAT.
|
||||||
|
|
||||||
## Uploads
|
## Uploads
|
||||||
|
|
||||||
|
|||||||
@@ -0,0 +1,4 @@
|
|||||||
|
.git
|
||||||
|
.next
|
||||||
|
node_modules
|
||||||
|
*.log
|
||||||
@@ -0,0 +1,3 @@
|
|||||||
|
# Local `npm run dev` (API on :8080 without Traefik). Leave empty when behind reverse proxy.
|
||||||
|
NEXT_PUBLIC_API_URL=http://localhost:8080
|
||||||
|
NEXT_PUBLIC_WS_URL=ws://localhost:8080/api/ws
|
||||||
@@ -0,0 +1,17 @@
|
|||||||
|
# deps
|
||||||
|
node_modules/
|
||||||
|
|
||||||
|
# next
|
||||||
|
.next/
|
||||||
|
out/
|
||||||
|
|
||||||
|
# env
|
||||||
|
.env*.local
|
||||||
|
|
||||||
|
# misc
|
||||||
|
*.log
|
||||||
|
.DS_Store
|
||||||
|
npm-debug.log*
|
||||||
|
|
||||||
|
# vendored at install/build from emoji-datasource-apple (~27MB)
|
||||||
|
/public/emoji/
|
||||||
@@ -0,0 +1,45 @@
|
|||||||
|
FROM node:22-alpine AS deps
|
||||||
|
|
||||||
|
WORKDIR /app
|
||||||
|
|
||||||
|
COPY package.json package-lock.json ./
|
||||||
|
# Ignore lifecycle scripts here — vendor script is only present after full COPY.
|
||||||
|
RUN npm ci --ignore-scripts
|
||||||
|
|
||||||
|
FROM node:22-alpine AS builder
|
||||||
|
|
||||||
|
WORKDIR /app
|
||||||
|
|
||||||
|
# Empty = same-origin (Traefik reverse proxy). For direct API access set build args.
|
||||||
|
ARG NEXT_PUBLIC_API_URL=
|
||||||
|
ARG NEXT_PUBLIC_WS_URL=
|
||||||
|
ENV NEXT_PUBLIC_API_URL=$NEXT_PUBLIC_API_URL
|
||||||
|
ENV NEXT_PUBLIC_WS_URL=$NEXT_PUBLIC_WS_URL
|
||||||
|
|
||||||
|
COPY --from=deps /app/node_modules ./node_modules
|
||||||
|
COPY . .
|
||||||
|
# Vendor Apple emoji PNGs into public/ (external CDNs are often blocked).
|
||||||
|
RUN node scripts/vendor-apple-emoji.mjs && npm run build
|
||||||
|
|
||||||
|
FROM node:22-alpine AS runner
|
||||||
|
|
||||||
|
WORKDIR /app
|
||||||
|
ENV NODE_ENV=production
|
||||||
|
|
||||||
|
RUN addgroup -S app && adduser -S app -G app
|
||||||
|
|
||||||
|
COPY --from=builder --chown=app:app /app/public ./public
|
||||||
|
COPY --from=builder --chown=app:app /app/.next ./.next
|
||||||
|
COPY --from=builder --chown=app:app /app/package.json ./package.json
|
||||||
|
COPY --from=builder --chown=app:app /app/next.config.mjs ./next.config.mjs
|
||||||
|
COPY --from=builder --chown=app:app /app/node_modules ./node_modules
|
||||||
|
|
||||||
|
# Public assets are required at runtime for /logo.png and for the
|
||||||
|
# /_next/image optimizer's internal fetch of local paths.
|
||||||
|
# next.config.mjs is required at runtime so images.contentDispositionType
|
||||||
|
# and other config overrides are applied (not only baked into manifests).
|
||||||
|
USER app
|
||||||
|
|
||||||
|
EXPOSE 3000
|
||||||
|
|
||||||
|
CMD ["npm", "run", "start"]
|
||||||
Vendored
+6
@@ -0,0 +1,6 @@
|
|||||||
|
/// <reference types="next" />
|
||||||
|
/// <reference types="next/image-types/global" />
|
||||||
|
/// <reference path="./.next/types/routes.d.ts" />
|
||||||
|
|
||||||
|
// NOTE: This file should not be edited
|
||||||
|
// see https://nextjs.org/docs/app/api-reference/config/typescript for more information.
|
||||||
@@ -0,0 +1,25 @@
|
|||||||
|
/** @type {import('next').NextConfig} */
|
||||||
|
const nextConfig = {
|
||||||
|
reactStrictMode: true,
|
||||||
|
eslint: { ignoreDuringBuilds: true },
|
||||||
|
images: {
|
||||||
|
// Default "attachment" can prevent some clients from rendering /_next/image in <img>.
|
||||||
|
contentDispositionType: "inline",
|
||||||
|
},
|
||||||
|
async redirects() {
|
||||||
|
return [
|
||||||
|
// Student self-service password recovery is disabled.
|
||||||
|
{ source: "/recovery", destination: "/login", permanent: false },
|
||||||
|
];
|
||||||
|
},
|
||||||
|
async headers() {
|
||||||
|
return [
|
||||||
|
{
|
||||||
|
source: "/c/:path*",
|
||||||
|
headers: [{ key: "X-Robots-Tag", value: "noindex, nofollow, noarchive" }],
|
||||||
|
},
|
||||||
|
];
|
||||||
|
},
|
||||||
|
};
|
||||||
|
|
||||||
|
export default nextConfig;
|
||||||
Generated
+2789
File diff suppressed because it is too large
Load Diff
@@ -0,0 +1,48 @@
|
|||||||
|
{
|
||||||
|
"name": "pargar-frontend",
|
||||||
|
"version": "0.1.0",
|
||||||
|
"private": true,
|
||||||
|
"scripts": {
|
||||||
|
"dev": "next dev -p 3000",
|
||||||
|
"prebuild": "node scripts/vendor-apple-emoji.mjs",
|
||||||
|
"vendor:emoji": "node scripts/vendor-apple-emoji.mjs",
|
||||||
|
"build": "next build",
|
||||||
|
"start": "next start -p 3000",
|
||||||
|
"lint": "next lint",
|
||||||
|
"typecheck": "tsc --noEmit"
|
||||||
|
},
|
||||||
|
"dependencies": {
|
||||||
|
"@radix-ui/react-avatar": "^1.1.2",
|
||||||
|
"@radix-ui/react-dialog": "^1.1.4",
|
||||||
|
"@radix-ui/react-dropdown-menu": "^2.1.4",
|
||||||
|
"@radix-ui/react-label": "^2.1.1",
|
||||||
|
"@radix-ui/react-slot": "^1.1.1",
|
||||||
|
"@radix-ui/react-switch": "^1.1.2",
|
||||||
|
"@radix-ui/react-tabs": "^1.1.2",
|
||||||
|
"@tanstack/react-query": "^5.62.0",
|
||||||
|
"boring-avatars": "^2.0.4",
|
||||||
|
"class-variance-authority": "^0.7.1",
|
||||||
|
"clsx": "^2.1.1",
|
||||||
|
"date-fns": "^4.1.0",
|
||||||
|
"emoji-datasource-apple": "^15.1.2",
|
||||||
|
"framer-motion": "^12.0.0",
|
||||||
|
"lucide-react": "^0.468.0",
|
||||||
|
"next": "^15.1.0",
|
||||||
|
"next-themes": "^0.4.4",
|
||||||
|
"react": "^19.0.0",
|
||||||
|
"react-dom": "^19.0.0",
|
||||||
|
"react-multi-date-picker": "^4.5.2",
|
||||||
|
"sonner": "^1.7.1",
|
||||||
|
"tailwind-merge": "^2.6.0",
|
||||||
|
"tw-animate-css": "^1.4.0",
|
||||||
|
"zustand": "^5.0.2"
|
||||||
|
},
|
||||||
|
"devDependencies": {
|
||||||
|
"@tailwindcss/postcss": "^4.0.0",
|
||||||
|
"@types/node": "^22.10.0",
|
||||||
|
"@types/react": "^19.0.0",
|
||||||
|
"@types/react-dom": "^19.0.0",
|
||||||
|
"tailwindcss": "^4.0.0",
|
||||||
|
"typescript": "^5.7.0"
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,7 @@
|
|||||||
|
const config = {
|
||||||
|
plugins: {
|
||||||
|
"@tailwindcss/postcss": {},
|
||||||
|
},
|
||||||
|
};
|
||||||
|
|
||||||
|
export default config;
|
||||||
Binary file not shown.
|
After Width: | Height: | Size: 31 KiB |
Binary file not shown.
|
After Width: | Height: | Size: 149 KiB |
@@ -0,0 +1,22 @@
|
|||||||
|
#!/usr/bin/env node
|
||||||
|
/**
|
||||||
|
* Copy Apple Color Emoji 64px PNGs into public/ so chat never depends on
|
||||||
|
* external CDNs (often blocked). Source: emoji-datasource-apple.
|
||||||
|
*/
|
||||||
|
import { cpSync, existsSync, mkdirSync, rmSync } from "node:fs";
|
||||||
|
import { dirname, join } from "node:path";
|
||||||
|
import { fileURLToPath } from "node:url";
|
||||||
|
|
||||||
|
const root = join(dirname(fileURLToPath(import.meta.url)), "..");
|
||||||
|
const src = join(root, "node_modules/emoji-datasource-apple/img/apple/64");
|
||||||
|
const dest = join(root, "public/emoji/apple/64");
|
||||||
|
|
||||||
|
if (!existsSync(src)) {
|
||||||
|
console.warn("[vendor-apple-emoji] skip: emoji-datasource-apple not installed");
|
||||||
|
process.exit(0);
|
||||||
|
}
|
||||||
|
|
||||||
|
mkdirSync(dirname(dest), { recursive: true });
|
||||||
|
rmSync(dest, { recursive: true, force: true });
|
||||||
|
cpSync(src, dest, { recursive: true });
|
||||||
|
console.log("[vendor-apple-emoji] copied → public/emoji/apple/64");
|
||||||
@@ -0,0 +1,12 @@
|
|||||||
|
"use client";
|
||||||
|
|
||||||
|
import { Suspense } from "react";
|
||||||
|
import { AdminStudio } from "@/components/admin-studio";
|
||||||
|
|
||||||
|
export default function AdminPage() {
|
||||||
|
return (
|
||||||
|
<Suspense fallback={null}>
|
||||||
|
<AdminStudio />
|
||||||
|
</Suspense>
|
||||||
|
);
|
||||||
|
}
|
||||||
Binary file not shown.
|
After Width: | Height: | Size: 19 KiB |
@@ -0,0 +1,219 @@
|
|||||||
|
"use client";
|
||||||
|
|
||||||
|
import { useQuery, useQueryClient } from "@tanstack/react-query";
|
||||||
|
import Link from "next/link";
|
||||||
|
import { useParams } from "next/navigation";
|
||||||
|
import { Loader2, Package } from "lucide-react";
|
||||||
|
import { CertificateCard } from "@/components/certificate-card";
|
||||||
|
import { Button } from "@/components/ui/button";
|
||||||
|
import { Input } from "@/components/ui/input";
|
||||||
|
import { http, toUserError } from "@/lib/api";
|
||||||
|
import { useAuth } from "@/lib/auth-store";
|
||||||
|
import type { Certificate, CertificatePhysicalOrder, PhysicalCertSettings } from "@/lib/types";
|
||||||
|
import { toast } from "@/components/providers";
|
||||||
|
import { formatFaNumber } from "@/lib/utils";
|
||||||
|
import { clampPhoneInput, normalizePhone, PHONE_INPUT_MAX_LEN } from "@/lib/validation";
|
||||||
|
import { useEffect, useState } from "react";
|
||||||
|
|
||||||
|
type PublicCertResponse = {
|
||||||
|
certificate: { publicId: string; fullName: string; issuedAt: string };
|
||||||
|
course: string;
|
||||||
|
};
|
||||||
|
|
||||||
|
const STATUS_LABEL: Record<string, string> = {
|
||||||
|
requested: "درخواستشده — منتظر تأیید پرداخت",
|
||||||
|
paid: "پرداخت تأیید شد — در صف ارسال",
|
||||||
|
shipped: "ارسال شد",
|
||||||
|
cancelled: "لغو شده",
|
||||||
|
};
|
||||||
|
|
||||||
|
export default function CertificatePage() {
|
||||||
|
const params = useParams<{ id: string }>();
|
||||||
|
const publicId = params?.id ?? "";
|
||||||
|
const authUser = useAuth((s) => s.user);
|
||||||
|
const qc = useQueryClient();
|
||||||
|
const [requesting, setRequesting] = useState(false);
|
||||||
|
const [form, setForm] = useState({
|
||||||
|
recipientName: "",
|
||||||
|
phone: "",
|
||||||
|
address: "",
|
||||||
|
city: "",
|
||||||
|
postalCode: "",
|
||||||
|
});
|
||||||
|
|
||||||
|
const { data, isLoading, error } = useQuery({
|
||||||
|
queryKey: ["certificate", publicId],
|
||||||
|
queryFn: () => http.get<PublicCertResponse>(`/api/certificates/${publicId}`),
|
||||||
|
enabled: !!publicId,
|
||||||
|
meta: { silentError: true },
|
||||||
|
});
|
||||||
|
|
||||||
|
const { data: mine } = useQuery({
|
||||||
|
queryKey: ["me", "certificate"],
|
||||||
|
queryFn: () =>
|
||||||
|
http.get<{
|
||||||
|
certificate: Certificate | null;
|
||||||
|
physicalOrder: CertificatePhysicalOrder | null;
|
||||||
|
physical: PhysicalCertSettings;
|
||||||
|
}>("/api/me/certificate"),
|
||||||
|
enabled: !!authUser,
|
||||||
|
});
|
||||||
|
|
||||||
|
const isOwner = !!authUser && mine?.certificate?.publicId === publicId;
|
||||||
|
|
||||||
|
useEffect(() => {
|
||||||
|
if (!isOwner || !authUser) return;
|
||||||
|
setForm((f) => ({
|
||||||
|
...f,
|
||||||
|
recipientName: f.recipientName || authUser.name || "",
|
||||||
|
phone: f.phone || authUser.phone || "",
|
||||||
|
}));
|
||||||
|
}, [isOwner, authUser]);
|
||||||
|
|
||||||
|
const requestPhysical = async () => {
|
||||||
|
setRequesting(true);
|
||||||
|
try {
|
||||||
|
await http.post("/api/me/certificate/physical", {
|
||||||
|
...form,
|
||||||
|
phone: normalizePhone(form.phone),
|
||||||
|
});
|
||||||
|
toast.success("درخواست ثبت شد — پس از واریز با ادمین هماهنگ کنید");
|
||||||
|
qc.invalidateQueries({ queryKey: ["me", "certificate"] });
|
||||||
|
} catch (e) {
|
||||||
|
toast.error(toUserError(e));
|
||||||
|
} finally {
|
||||||
|
setRequesting(false);
|
||||||
|
}
|
||||||
|
};
|
||||||
|
|
||||||
|
if (isLoading) {
|
||||||
|
return (
|
||||||
|
<div className="flex min-h-[60vh] items-center justify-center">
|
||||||
|
<Loader2 className="h-6 w-6 animate-spin text-muted-foreground" />
|
||||||
|
</div>
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
if (error || !data?.certificate) {
|
||||||
|
return (
|
||||||
|
<div className="mx-auto max-w-lg px-4 py-16 text-center">
|
||||||
|
<p className="text-lg font-bold">گواهینامه پیدا نشد</p>
|
||||||
|
<Button asChild className="mt-4" variant="outline">
|
||||||
|
<Link href="/">بازگشت</Link>
|
||||||
|
</Button>
|
||||||
|
</div>
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
const cert = data.certificate;
|
||||||
|
const order = isOwner ? mine?.physicalOrder : null;
|
||||||
|
const physical = isOwner ? mine?.physical : null;
|
||||||
|
const windowEndsAt = mine?.certificate?.issuedAt
|
||||||
|
? new Date(mine.certificate.issuedAt).getTime() + (physical?.windowDays ?? 30) * 86400000
|
||||||
|
: 0;
|
||||||
|
const windowStillOpen = !windowEndsAt || Date.now() < windowEndsAt;
|
||||||
|
const windowOpen =
|
||||||
|
physical?.enabled &&
|
||||||
|
windowStillOpen &&
|
||||||
|
(!order || order.status === "cancelled") &&
|
||||||
|
!!mine?.certificate;
|
||||||
|
|
||||||
|
return (
|
||||||
|
<CertificateCard
|
||||||
|
cert={{
|
||||||
|
publicId: cert.publicId,
|
||||||
|
fullName: cert.fullName,
|
||||||
|
issuedAt: cert.issuedAt,
|
||||||
|
course: data.course,
|
||||||
|
}}
|
||||||
|
showOwnerLinks={!!authUser}
|
||||||
|
>
|
||||||
|
{isOwner && physical?.enabled && (
|
||||||
|
<div className="mt-8 space-y-3 border-t border-border pt-6">
|
||||||
|
<p className="flex items-center gap-2 text-sm font-bold">
|
||||||
|
<Package className="h-4 w-4" /> نسخه فیزیکی
|
||||||
|
</p>
|
||||||
|
<p className="text-xs text-muted-foreground">
|
||||||
|
قیمت حدودی {formatFaNumber(physical.priceIrr)} ریال · مهلت درخواست{" "}
|
||||||
|
{formatFaNumber(physical.windowDays)} روز از صدور
|
||||||
|
{windowEndsAt ? ` (تا ${new Date(windowEndsAt).toLocaleDateString("fa-IR")})` : ""}.
|
||||||
|
پرداخت آنلاین در سامانه نداریم. پس از واریز بیرونی با ادمین هماهنگ کنید تا وضعیت سفارش بهروز شود.
|
||||||
|
</p>
|
||||||
|
{order && order.status !== "cancelled" ? (
|
||||||
|
<div className="space-y-2 rounded-xl border border-border bg-muted/30 p-3 text-sm">
|
||||||
|
<p>
|
||||||
|
وضعیت: <span className="font-medium">{STATUS_LABEL[order.status] ?? order.status}</span>
|
||||||
|
</p>
|
||||||
|
{order.trackingCode && (
|
||||||
|
<p className="font-mono text-xs" dir="ltr">
|
||||||
|
کد پیگیری: {order.trackingCode}
|
||||||
|
</p>
|
||||||
|
)}
|
||||||
|
{order.city && (
|
||||||
|
<p className="text-xs text-muted-foreground">
|
||||||
|
ارسال به {order.recipientName || "—"} · {order.city}
|
||||||
|
</p>
|
||||||
|
)}
|
||||||
|
{order.note && <p className="text-xs text-muted-foreground">یادداشت ادمین: {order.note}</p>}
|
||||||
|
<Button
|
||||||
|
size="sm"
|
||||||
|
variant="outline"
|
||||||
|
onClick={() =>
|
||||||
|
window.dispatchEvent(new CustomEvent("pargar:chat", { detail: { open: true } }))
|
||||||
|
}
|
||||||
|
>
|
||||||
|
هماهنگی با تیم
|
||||||
|
</Button>
|
||||||
|
</div>
|
||||||
|
) : windowOpen ? (
|
||||||
|
<div className="space-y-2">
|
||||||
|
<div className="grid gap-2 sm:grid-cols-2">
|
||||||
|
<Input
|
||||||
|
placeholder="نام گیرنده"
|
||||||
|
value={form.recipientName}
|
||||||
|
onChange={(e) => setForm((f) => ({ ...f, recipientName: e.target.value }))}
|
||||||
|
/>
|
||||||
|
<Input
|
||||||
|
placeholder="موبایل"
|
||||||
|
value={form.phone}
|
||||||
|
onChange={(e) => setForm((f) => ({ ...f, phone: clampPhoneInput(e.target.value) }))}
|
||||||
|
dir="ltr"
|
||||||
|
inputMode="tel"
|
||||||
|
maxLength={PHONE_INPUT_MAX_LEN}
|
||||||
|
className="text-left"
|
||||||
|
/>
|
||||||
|
<Input
|
||||||
|
placeholder="شهر"
|
||||||
|
value={form.city}
|
||||||
|
onChange={(e) => setForm((f) => ({ ...f, city: e.target.value }))}
|
||||||
|
/>
|
||||||
|
<Input
|
||||||
|
placeholder="کد پستی"
|
||||||
|
value={form.postalCode}
|
||||||
|
onChange={(e) => setForm((f) => ({ ...f, postalCode: e.target.value }))}
|
||||||
|
dir="ltr"
|
||||||
|
/>
|
||||||
|
</div>
|
||||||
|
<textarea
|
||||||
|
className="min-h-[72px] w-full rounded-md border border-input bg-background px-3 py-2 text-sm"
|
||||||
|
placeholder="آدرس کامل پستی"
|
||||||
|
value={form.address}
|
||||||
|
onChange={(e) => setForm((f) => ({ ...f, address: e.target.value }))}
|
||||||
|
/>
|
||||||
|
<Button
|
||||||
|
size="sm"
|
||||||
|
disabled={requesting || !form.address.trim() || !form.city.trim()}
|
||||||
|
onClick={() => void requestPhysical()}
|
||||||
|
>
|
||||||
|
{requesting ? <Loader2 className="h-3.5 w-3.5 animate-spin" /> : <Package className="h-3.5 w-3.5" />}
|
||||||
|
ثبت درخواست نسخه فیزیکی
|
||||||
|
</Button>
|
||||||
|
</div>
|
||||||
|
) : !windowStillOpen ? (
|
||||||
|
<p className="text-sm text-muted-foreground">مهلت درخواست نسخه فیزیکی به پایان رسیده است.</p>
|
||||||
|
) : null}
|
||||||
|
</div>
|
||||||
|
)}
|
||||||
|
</CertificateCard>
|
||||||
|
);
|
||||||
|
}
|
||||||
@@ -0,0 +1,21 @@
|
|||||||
|
import type { Metadata } from "next";
|
||||||
|
|
||||||
|
/** Certificate share links are unlisted — never index or follow. */
|
||||||
|
export const metadata: Metadata = {
|
||||||
|
robots: {
|
||||||
|
index: false,
|
||||||
|
follow: false,
|
||||||
|
nocache: true,
|
||||||
|
noarchive: true,
|
||||||
|
nosnippet: true,
|
||||||
|
googleBot: {
|
||||||
|
index: false,
|
||||||
|
follow: false,
|
||||||
|
noimageindex: true,
|
||||||
|
},
|
||||||
|
},
|
||||||
|
};
|
||||||
|
|
||||||
|
export default function CertificateLayout({ children }: { children: React.ReactNode }) {
|
||||||
|
return children;
|
||||||
|
}
|
||||||
@@ -0,0 +1,459 @@
|
|||||||
|
"use client";
|
||||||
|
|
||||||
|
import { useRouter, useSearchParams } from "next/navigation";
|
||||||
|
import { useQuery, useQueryClient } from "@tanstack/react-query";
|
||||||
|
import { Suspense, useEffect, useRef } from "react";
|
||||||
|
import {
|
||||||
|
Award,
|
||||||
|
ArrowLeft,
|
||||||
|
BookOpenCheck,
|
||||||
|
CheckCircle2,
|
||||||
|
CalendarDays,
|
||||||
|
Flame,
|
||||||
|
Heart,
|
||||||
|
Lock,
|
||||||
|
MessageSquare,
|
||||||
|
Package,
|
||||||
|
PlayCircle,
|
||||||
|
Sparkles,
|
||||||
|
TrendingUp,
|
||||||
|
AlertTriangle,
|
||||||
|
} from "lucide-react";
|
||||||
|
import { SkillTree } from "@/components/skill-tree";
|
||||||
|
import { Skeleton } from "@/components/ui/skeleton";
|
||||||
|
import { http, toUserError } from "@/lib/api";
|
||||||
|
import type { Certificate, CertificatePhysicalOrder, MeetingEvent, PhysicalCertSettings, TreeData, TreeLesson } from "@/lib/types";
|
||||||
|
import { Button } from "@/components/ui/button";
|
||||||
|
import { useAuth } from "@/lib/auth-store";
|
||||||
|
import { cn, formatFaNumber, formatStreakLabel } from "@/lib/utils";
|
||||||
|
import { clampHearts, hasInfiniteHearts, INFINITE_HEARTS_LABEL, MAX_HEARTS } from "@/lib/hearts";
|
||||||
|
import { toast } from "@/components/providers";
|
||||||
|
|
||||||
|
export default function CapPage() {
|
||||||
|
return (
|
||||||
|
<Suspense fallback={<CapSkeleton />}>
|
||||||
|
<CapPageInner />
|
||||||
|
</Suspense>
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
function CapPageInner() {
|
||||||
|
const router = useRouter();
|
||||||
|
const params = useSearchParams();
|
||||||
|
const rootRef = useRef<HTMLDivElement>(null);
|
||||||
|
const user = useAuth((s) => s.user);
|
||||||
|
const qc = useQueryClient();
|
||||||
|
|
||||||
|
const { data, isLoading } = useQuery({
|
||||||
|
queryKey: ["tree"],
|
||||||
|
queryFn: () => http.get<TreeData>("/api/tree"),
|
||||||
|
refetchInterval: 60_000,
|
||||||
|
});
|
||||||
|
|
||||||
|
const { data: eventsData } = useQuery({
|
||||||
|
queryKey: ["events", "upcoming-cap"],
|
||||||
|
queryFn: () => http.get<{ events: MeetingEvent[] }>("/api/events"),
|
||||||
|
staleTime: 60_000,
|
||||||
|
});
|
||||||
|
|
||||||
|
const allLessons = (data?.chapters ?? []).flatMap((ch) => ch.lessons ?? []);
|
||||||
|
const completedCount = allLessons.filter((l) => l.progress?.passedQuiz).length;
|
||||||
|
const curriculumDone = allLessons.length > 0 && completedCount === allLessons.length;
|
||||||
|
|
||||||
|
useEffect(() => {
|
||||||
|
const lesson = params.get("lesson");
|
||||||
|
if (lesson && rootRef.current) {
|
||||||
|
rootRef.current.scrollIntoView({ behavior: "smooth" });
|
||||||
|
}
|
||||||
|
}, [params]);
|
||||||
|
|
||||||
|
const { data: certData } = useQuery({
|
||||||
|
queryKey: ["me", "certificate"],
|
||||||
|
queryFn: () =>
|
||||||
|
http.get<{
|
||||||
|
certificate: Certificate | null;
|
||||||
|
physicalOrder: CertificatePhysicalOrder | null;
|
||||||
|
physical: PhysicalCertSettings;
|
||||||
|
}>("/api/me/certificate"),
|
||||||
|
enabled: !!user && curriculumDone,
|
||||||
|
});
|
||||||
|
|
||||||
|
useEffect(() => {
|
||||||
|
if (!curriculumDone || !user) return;
|
||||||
|
void http
|
||||||
|
.post("/api/me/certificate/issue", {})
|
||||||
|
.then(() => qc.invalidateQueries({ queryKey: ["me", "certificate"] }))
|
||||||
|
.catch((e) => toast.error(toUserError(e, "صدور گواهینامه ممکن نشد")));
|
||||||
|
}, [curriculumDone, user, qc]);
|
||||||
|
|
||||||
|
if (isLoading) {
|
||||||
|
return <CapSkeleton />;
|
||||||
|
}
|
||||||
|
|
||||||
|
const me = data?.me;
|
||||||
|
const all = allLessons;
|
||||||
|
const lockedCount = all.filter((l) => l.locked).length;
|
||||||
|
const inProgress = all.filter(
|
||||||
|
(l) => !l.locked && !l.progress?.passedQuiz && (l.progress?.watchedPct ?? 0) > 0 && !l.progress?.quizUnlocked,
|
||||||
|
);
|
||||||
|
const readyQuiz = all.filter((l) => !l.locked && !l.progress?.passedQuiz && !!l.progress?.quizUnlocked);
|
||||||
|
const openAndNew = all.filter((l) => !l.locked && !l.progress?.passedQuiz);
|
||||||
|
const firstLocked = all.find((l) => l.locked);
|
||||||
|
const done = curriculumDone;
|
||||||
|
|
||||||
|
const pct = all.length ? Math.round((completedCount / all.length) * 100) : 0;
|
||||||
|
const hearts = clampHearts(me?.hearts ?? user?.hearts ?? MAX_HEARTS);
|
||||||
|
const lowHearts = !hasInfiniteHearts(user?.role) && hearts > 0 && hearts <= 1;
|
||||||
|
const nextEvent = (eventsData?.events ?? [])[0];
|
||||||
|
const physicalOpen =
|
||||||
|
done &&
|
||||||
|
certData?.physical?.enabled &&
|
||||||
|
!!certData.certificate &&
|
||||||
|
(!certData.physicalOrder || certData.physicalOrder.status === "cancelled") &&
|
||||||
|
(!certData.certificate.issuedAt ||
|
||||||
|
Date.now() <
|
||||||
|
new Date(certData.certificate.issuedAt).getTime() +
|
||||||
|
(certData.physical.windowDays || 30) * 24 * 60 * 60 * 1000);
|
||||||
|
|
||||||
|
const next = nextAction(inProgress, readyQuiz, openAndNew, firstLocked, done);
|
||||||
|
|
||||||
|
return (
|
||||||
|
<div className="space-y-8" ref={rootRef}>
|
||||||
|
<div className="flex flex-wrap items-end justify-between gap-4">
|
||||||
|
<div>
|
||||||
|
<p className="section-kicker">مسیر شما</p>
|
||||||
|
<h1 className="mt-2 text-3xl font-black tracking-tight sm:text-5xl">
|
||||||
|
درخت <span className="text-primary">مهارت</span>
|
||||||
|
</h1>
|
||||||
|
<p className="mt-2 max-w-xl text-sm text-muted-foreground">
|
||||||
|
الان روی گام بعدی تمرکز کنید — تماشا، آزمون، رویداد یا گواهینامه.
|
||||||
|
</p>
|
||||||
|
</div>
|
||||||
|
<div className="flex items-center gap-2">
|
||||||
|
<span className="inline-flex items-center gap-1.5 rounded-full bg-accent/10 px-3 py-1.5 text-sm font-bold text-accent">
|
||||||
|
<Flame className="h-4 w-4" /> {formatStreakLabel(me?.streak ?? user?.streakCurrent ?? 0)}
|
||||||
|
</span>
|
||||||
|
<span className="inline-flex items-center gap-1.5 rounded-full bg-gold/10 px-3 py-1.5 text-sm font-bold text-gold">
|
||||||
|
<Sparkles className="h-4 w-4" /> {formatFaNumber(me?.xp ?? user?.xp ?? 0)} امتیاز
|
||||||
|
</span>
|
||||||
|
<span
|
||||||
|
className={cn(
|
||||||
|
"inline-flex items-center gap-1.5 rounded-full px-3 py-1.5 text-sm font-bold",
|
||||||
|
lowHearts ? "bg-destructive/15 text-destructive" : "bg-primary/10 text-primary",
|
||||||
|
)}
|
||||||
|
>
|
||||||
|
<Heart className="h-4 w-4 fill-current" />{" "}
|
||||||
|
{hasInfiniteHearts(user?.role)
|
||||||
|
? `${INFINITE_HEARTS_LABEL} جان`
|
||||||
|
: `${formatFaNumber(hearts)} جان`}
|
||||||
|
</span>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
|
||||||
|
{lowHearts && (
|
||||||
|
<div className="flex flex-wrap items-center justify-between gap-3 rounded-2xl border-2 border-destructive/30 bg-destructive/5 px-5 py-4">
|
||||||
|
<div className="flex items-start gap-3">
|
||||||
|
<AlertTriangle className="mt-0.5 h-5 w-5 shrink-0 text-destructive" />
|
||||||
|
<div>
|
||||||
|
<p className="text-sm font-extrabold text-destructive">فقط {formatFaNumber(hearts)} جان مانده</p>
|
||||||
|
<p className="text-xs text-muted-foreground">
|
||||||
|
یک اشتباه دیگر حساب را قفل میکند. قبل از آزمون مطمئن شوید؛ اگر گیر کردید با منتور حرف بزنید.
|
||||||
|
</p>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
<Button
|
||||||
|
variant="outline"
|
||||||
|
size="sm"
|
||||||
|
onClick={() =>
|
||||||
|
window.dispatchEvent(new CustomEvent("pargar:chat", { detail: { open: true } }))
|
||||||
|
}
|
||||||
|
>
|
||||||
|
<MessageSquare className="h-4 w-4" /> منتور
|
||||||
|
</Button>
|
||||||
|
</div>
|
||||||
|
)}
|
||||||
|
|
||||||
|
{done && (
|
||||||
|
<div className="flex flex-wrap items-center justify-between gap-3 rounded-2xl border-2 border-primary/30 bg-primary/5 px-5 py-4">
|
||||||
|
<div>
|
||||||
|
<p className="text-sm font-extrabold">دوره را تمام کردید</p>
|
||||||
|
<p className="text-xs text-muted-foreground">
|
||||||
|
گواهینامه دیجیتال آماده است
|
||||||
|
{physicalOpen ? " — میتوانید نسخه فیزیکی هم درخواست کنید." : "."}
|
||||||
|
</p>
|
||||||
|
</div>
|
||||||
|
<div className="flex flex-wrap gap-2">
|
||||||
|
<Button
|
||||||
|
onClick={() => {
|
||||||
|
const id = certData?.certificate?.publicId;
|
||||||
|
if (id) router.push(`/c/${id}`);
|
||||||
|
else {
|
||||||
|
void http
|
||||||
|
.post<{ certificate: { publicId: string } }>("/api/me/certificate/issue", {})
|
||||||
|
.then((r) => {
|
||||||
|
if (r.certificate?.publicId) router.push(`/c/${r.certificate.publicId}`);
|
||||||
|
})
|
||||||
|
.catch((e) => toast.error(toUserError(e, "صدور گواهینامه ممکن نشد")));
|
||||||
|
}
|
||||||
|
}}
|
||||||
|
>
|
||||||
|
<Award className="h-4 w-4" /> مشاهده گواهینامه
|
||||||
|
</Button>
|
||||||
|
{physicalOpen && certData?.certificate?.publicId && (
|
||||||
|
<Button variant="outline" onClick={() => router.push(`/c/${certData.certificate!.publicId}`)}>
|
||||||
|
<Package className="h-4 w-4" /> نسخه فیزیکی
|
||||||
|
</Button>
|
||||||
|
)}
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
)}
|
||||||
|
|
||||||
|
<div className="grid gap-5 md:grid-cols-5">
|
||||||
|
<div className="rounded-2xl border-2 border-border bg-card p-5 shadow-offset-sm md:col-span-2">
|
||||||
|
<div className="flex items-center justify-between">
|
||||||
|
<p className="flex items-center gap-2 text-sm font-extrabold">
|
||||||
|
<TrendingUp className="h-4 w-4 text-primary" /> پیشرفت کل
|
||||||
|
</p>
|
||||||
|
<span className="text-2xl font-black tabular-nums text-primary">{pct}٪</span>
|
||||||
|
</div>
|
||||||
|
<div className="mt-3 h-3.5 w-full overflow-hidden rounded-full bg-muted">
|
||||||
|
<div className="h-full rounded-full bg-primary transition-all" style={{ width: `${Math.max(pct, 3)}%` }} />
|
||||||
|
</div>
|
||||||
|
<div className="mt-4 grid grid-cols-3 gap-2 text-center">
|
||||||
|
<div className="rounded-xl bg-success/10 px-2 py-2.5">
|
||||||
|
<p className="text-lg font-black text-success">{completedCount}</p>
|
||||||
|
<p className="text-[11px] font-bold text-muted-foreground">تکمیلشده</p>
|
||||||
|
</div>
|
||||||
|
<div className="rounded-xl bg-primary/10 px-2 py-2.5">
|
||||||
|
<p className="text-lg font-black text-primary">{inProgress.length}</p>
|
||||||
|
<p className="text-[11px] font-bold text-muted-foreground">در جریان</p>
|
||||||
|
</div>
|
||||||
|
<div className="rounded-xl bg-muted px-2 py-2.5">
|
||||||
|
<p className="text-lg font-black text-muted-foreground">{lockedCount}</p>
|
||||||
|
<p className="text-[11px] font-bold text-muted-foreground">قفلشده</p>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
<div className="mt-4 space-y-1.5">
|
||||||
|
{(data?.chapters ?? []).map((ch) => {
|
||||||
|
const chDone = ch.lessons.filter((l) => l.progress?.passedQuiz).length;
|
||||||
|
return (
|
||||||
|
<div key={ch.id} className="flex items-center justify-between text-xs">
|
||||||
|
<span className="font-bold text-muted-foreground">{ch.title}</span>
|
||||||
|
<span
|
||||||
|
className={cn(
|
||||||
|
"font-black tabular-nums",
|
||||||
|
chDone === ch.lessons.length ? "text-success" : "text-foreground",
|
||||||
|
)}
|
||||||
|
>
|
||||||
|
{chDone}/{ch.lessons.length}
|
||||||
|
</span>
|
||||||
|
</div>
|
||||||
|
);
|
||||||
|
})}
|
||||||
|
</div>
|
||||||
|
{nextEvent && (
|
||||||
|
<button
|
||||||
|
type="button"
|
||||||
|
onClick={() => router.push("/unwrap?tab=events")}
|
||||||
|
className="mt-4 flex w-full items-start gap-2 rounded-xl border border-border/70 bg-muted/40 px-3 py-2.5 text-start transition hover:border-primary/40"
|
||||||
|
>
|
||||||
|
<CalendarDays className="mt-0.5 h-4 w-4 shrink-0 text-primary" />
|
||||||
|
<span className="min-w-0">
|
||||||
|
<span className="block text-[10px] font-extrabold text-primary">رویداد نزدیک</span>
|
||||||
|
<span className="block truncate text-xs font-bold">{nextEvent.title}</span>
|
||||||
|
<span className="block text-[10px] text-muted-foreground">
|
||||||
|
{new Date(nextEvent.startsAt).toLocaleString("fa-IR")}
|
||||||
|
</span>
|
||||||
|
</span>
|
||||||
|
</button>
|
||||||
|
)}
|
||||||
|
</div>
|
||||||
|
|
||||||
|
<div
|
||||||
|
className={cn(
|
||||||
|
"flex flex-col justify-between rounded-2xl border-2 p-5 md:col-span-3",
|
||||||
|
next.locked
|
||||||
|
? "border-border bg-muted/40"
|
||||||
|
: "border-primary/40 bg-primary/5"
|
||||||
|
)}
|
||||||
|
>
|
||||||
|
<p
|
||||||
|
className={cn(
|
||||||
|
"flex items-center gap-2 text-xs font-extrabold tracking-wider",
|
||||||
|
next.locked ? "text-muted-foreground" : "text-primary"
|
||||||
|
)}
|
||||||
|
>
|
||||||
|
{next.locked ? <Lock className="h-4 w-4" /> : <ZapIcon className="h-4 w-4" />}
|
||||||
|
{next.locked ? "هنوز قفل است" : "گام بعدی شما"}
|
||||||
|
</p>
|
||||||
|
<div className="mt-3 flex flex-1 flex-col items-start justify-center">
|
||||||
|
<h2 className="text-xl font-black leading-snug sm:text-2xl">{next.title}</h2>
|
||||||
|
<p className="mt-1.5 text-sm leading-relaxed text-muted-foreground">{next.desc}</p>
|
||||||
|
</div>
|
||||||
|
<div className="mt-4 flex flex-wrap gap-2">
|
||||||
|
{next.cta ? (
|
||||||
|
<Button size="lg" onClick={() => router.push(next.cta!)} className="gap-2">
|
||||||
|
{next.icon} {next.label}
|
||||||
|
</Button>
|
||||||
|
) : next.prereqId ? (
|
||||||
|
<Button size="lg" variant="secondary" onClick={() => router.push(`/player/${next.prereqId}`)} className="gap-2">
|
||||||
|
<PlayCircle className="h-5 w-5" /> رفتن به پیشنیاز
|
||||||
|
</Button>
|
||||||
|
) : (
|
||||||
|
<div className="inline-flex items-center gap-2 rounded-xl bg-muted px-3.5 py-2.5 text-sm font-bold text-muted-foreground">
|
||||||
|
<Lock className="h-4 w-4" /> ابتدا درس پیشنیاز را کامل کنید
|
||||||
|
</div>
|
||||||
|
)}
|
||||||
|
<Button
|
||||||
|
size="lg"
|
||||||
|
variant="outline"
|
||||||
|
onClick={() =>
|
||||||
|
window.dispatchEvent(new CustomEvent("pargar:chat", { detail: { open: true } }))
|
||||||
|
}
|
||||||
|
>
|
||||||
|
<MessageSquare className="h-5 w-5" /> منتور
|
||||||
|
</Button>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
|
||||||
|
{data && <SkillTree data={data} onSelect={(id) => router.push(`/player/${id}`)} />}
|
||||||
|
|
||||||
|
<div className="flex flex-wrap items-center gap-x-5 gap-y-2 text-xs font-bold text-muted-foreground">
|
||||||
|
<span className="inline-flex items-center gap-1.5">
|
||||||
|
<CheckCircle2 className="h-4 w-4 text-success" /> تکمیلشده
|
||||||
|
</span>
|
||||||
|
<span className="inline-flex items-center gap-1.5">
|
||||||
|
<PlayCircle className="h-4 w-4 text-primary" /> در دسترس
|
||||||
|
</span>
|
||||||
|
<span className="inline-flex items-center gap-1.5">
|
||||||
|
<BookOpenCheck className="h-4 w-4 text-gold" /> آمادهٔ آزمون
|
||||||
|
</span>
|
||||||
|
<span className="inline-flex items-center gap-1.5">
|
||||||
|
<Lock className="h-4 w-4 text-muted-foreground" /> قفلشده
|
||||||
|
</span>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
function nextAction(
|
||||||
|
inProgress: TreeLesson[],
|
||||||
|
readyQuiz: TreeLesson[],
|
||||||
|
openAndNew: TreeLesson[],
|
||||||
|
firstLocked: TreeLesson | undefined,
|
||||||
|
done: boolean,
|
||||||
|
) {
|
||||||
|
if (readyQuiz[0]) {
|
||||||
|
const lesson = readyQuiz[0];
|
||||||
|
return {
|
||||||
|
title: `آزمون «${lesson.title}» منتظر شماست`,
|
||||||
|
desc: "آموختههایتان را محک بزنید؛ هر پاسخ اشتباه یک جان کم میکند.",
|
||||||
|
label: "شروع آزمون",
|
||||||
|
cta: `/quiz/${lesson.id}`,
|
||||||
|
icon: <BookOpenCheck className="h-5 w-5" />,
|
||||||
|
locked: false,
|
||||||
|
prereqId: null as number | null,
|
||||||
|
};
|
||||||
|
}
|
||||||
|
if (inProgress[0]) {
|
||||||
|
const lesson = inProgress[0];
|
||||||
|
const pct = Math.round(lesson.progress?.watchedPct ?? 0);
|
||||||
|
return {
|
||||||
|
title: `ادامهٔ تماشای «${lesson.title}»`,
|
||||||
|
desc: `${formatFaNumber(pct)}٪ تماشا شده — با رسیدن به آستانه، آزمون باز میشود.`,
|
||||||
|
label: "ادامهٔ تماشا",
|
||||||
|
cta: `/player/${lesson.id}`,
|
||||||
|
icon: <PlayCircle className="h-5 w-5" />,
|
||||||
|
locked: false,
|
||||||
|
prereqId: null as number | null,
|
||||||
|
};
|
||||||
|
}
|
||||||
|
if (openAndNew[0]) {
|
||||||
|
const lesson = openAndNew[0];
|
||||||
|
return {
|
||||||
|
title: `شروع «${lesson.title}»`,
|
||||||
|
desc: `${formatFaNumber(lesson.durationSeconds)} ثانیه تماشای تأییدشده · ${formatFaNumber(lesson.xpReward)} امتیاز پاداش در صورت تکمیل.`,
|
||||||
|
label: "شروع درس",
|
||||||
|
cta: `/player/${lesson.id}`,
|
||||||
|
icon: <PlayCircle className="h-5 w-5" />,
|
||||||
|
locked: false,
|
||||||
|
prereqId: null as number | null,
|
||||||
|
};
|
||||||
|
}
|
||||||
|
if (firstLocked) {
|
||||||
|
return {
|
||||||
|
title: `«${firstLocked.title}» قفل است`,
|
||||||
|
desc: "بعد از تکمیل صادقانهٔ درس پیشنیاز و قبولی در آزمونش، این شاخه باز میشود.",
|
||||||
|
label: "",
|
||||||
|
cta: null as string | null,
|
||||||
|
icon: null,
|
||||||
|
locked: true,
|
||||||
|
prereqId: firstLocked.requiresLessonId ?? null,
|
||||||
|
};
|
||||||
|
}
|
||||||
|
if (done) {
|
||||||
|
return {
|
||||||
|
title: "همهٔ شاخهها را آزاد کردید",
|
||||||
|
desc: "تمام دروس تکمیلشدهاند. گواهینامه را ببینید یا لیگ این هفته را فتح کنید.",
|
||||||
|
label: "رفتن به لیگها",
|
||||||
|
cta: "/leaderboard",
|
||||||
|
icon: <ArrowLeft className="h-5 w-5" />,
|
||||||
|
locked: false,
|
||||||
|
prereqId: null as number | null,
|
||||||
|
};
|
||||||
|
}
|
||||||
|
return {
|
||||||
|
title: "مسیر آماده است",
|
||||||
|
desc: "دادهای برای نمایش نیست.",
|
||||||
|
label: "",
|
||||||
|
cta: null as string | null,
|
||||||
|
icon: null,
|
||||||
|
locked: false,
|
||||||
|
prereqId: null as number | null,
|
||||||
|
};
|
||||||
|
}
|
||||||
|
|
||||||
|
function CapSkeleton() {
|
||||||
|
return (
|
||||||
|
<div className="space-y-8">
|
||||||
|
<div className="flex flex-wrap items-end justify-between gap-4">
|
||||||
|
<div className="space-y-2.5">
|
||||||
|
<Skeleton className="h-3.5 w-36" />
|
||||||
|
<Skeleton className="h-10 w-64" />
|
||||||
|
<Skeleton className="h-4 w-96 max-w-full" />
|
||||||
|
</div>
|
||||||
|
<div className="flex items-center gap-2">
|
||||||
|
<Skeleton className="h-8 w-24 rounded-full" />
|
||||||
|
<Skeleton className="h-8 w-24 rounded-full" />
|
||||||
|
<Skeleton className="h-8 w-24 rounded-full" />
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
<div className="grid gap-5 md:grid-cols-5">
|
||||||
|
<div className="space-y-4 rounded-2xl border-2 border-border bg-card p-5 shadow-offset-sm md:col-span-2">
|
||||||
|
<Skeleton className="h-5 w-32" />
|
||||||
|
<Skeleton className="h-3.5 w-full rounded-full" />
|
||||||
|
<div className="grid grid-cols-3 gap-2">
|
||||||
|
{Array.from({ length: 3 }).map((_, i) => (
|
||||||
|
<Skeleton key={i} className="h-16 rounded-xl" />
|
||||||
|
))}
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
<div className="rounded-2xl border-2 border-primary/40 bg-primary/5 p-5 md:col-span-3">
|
||||||
|
<Skeleton className="h-4 w-28" />
|
||||||
|
<Skeleton className="mt-3 h-7 w-3/4" />
|
||||||
|
<Skeleton className="mt-2 h-4 w-1/2" />
|
||||||
|
<Skeleton className="mt-6 h-11 w-40 rounded-xl" />
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
function ZapIcon(props: { className?: string }) {
|
||||||
|
return (
|
||||||
|
<svg viewBox="0 0 24 24" fill="currentColor" {...props}>
|
||||||
|
<path d="M13 2 4.5 13.5H11l-.8 8.5L18.5 10H12l1-8z" />
|
||||||
|
</svg>
|
||||||
|
);
|
||||||
|
}
|
||||||
@@ -0,0 +1,13 @@
|
|||||||
|
"use client";
|
||||||
|
|
||||||
|
import { useEffect } from "react";
|
||||||
|
import { useRouter } from "next/navigation";
|
||||||
|
|
||||||
|
/** Shortcut so /community never 404s. */
|
||||||
|
export default function CommunityRedirectPage() {
|
||||||
|
const router = useRouter();
|
||||||
|
useEffect(() => {
|
||||||
|
router.replace("/unwrap?tab=community");
|
||||||
|
}, [router]);
|
||||||
|
return null;
|
||||||
|
}
|
||||||
Binary file not shown.
|
After Width: | Height: | Size: 31 KiB |
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
@@ -0,0 +1,647 @@
|
|||||||
|
@import "tailwindcss";
|
||||||
|
@import "tw-animate-css";
|
||||||
|
|
||||||
|
/* enable dark-variant & class-based theming */
|
||||||
|
@custom-variant dark (&:is(.dark *));
|
||||||
|
|
||||||
|
/* ============================================================
|
||||||
|
Pargar design system — soft pastel, a touch of glass,
|
||||||
|
calm shadows, gentle motion.
|
||||||
|
============================================================ */
|
||||||
|
:root {
|
||||||
|
--background: #f4f5fb;
|
||||||
|
--foreground: #2a2745;
|
||||||
|
--card: #ffffff;
|
||||||
|
--card-foreground: #2a2745;
|
||||||
|
--popover: #ffffff;
|
||||||
|
--popover-foreground: #2a2745;
|
||||||
|
--primary: #6d63f0;
|
||||||
|
--primary-foreground: #ffffff;
|
||||||
|
--secondary: #5a6380;
|
||||||
|
--secondary-foreground: #ffffff;
|
||||||
|
--muted: #edeef7;
|
||||||
|
--muted-foreground: #6b6c8a;
|
||||||
|
--accent: #ec6fa9;
|
||||||
|
--accent-foreground: #ffffff;
|
||||||
|
--destructive: #e05c70;
|
||||||
|
--destructive-foreground: #ffffff;
|
||||||
|
--success: #3ec98a;
|
||||||
|
--success-foreground: #ffffff;
|
||||||
|
--gold: #f2a437;
|
||||||
|
--gold-foreground: #3f2a04;
|
||||||
|
--border: #d9dbe9;
|
||||||
|
--input: #c9cbdf;
|
||||||
|
--ring: #6d63f0;
|
||||||
|
--radius: 0.5rem;
|
||||||
|
/* inverted editorial band (dark in light mode, light in dark mode) */
|
||||||
|
--invert-bg: #211f3e;
|
||||||
|
--invert-fg: #f6f5fb;
|
||||||
|
/* soft motion tokens */
|
||||||
|
--ease-soft: cubic-bezier(0.22, 1, 0.36, 1);
|
||||||
|
--ease-soft-in-out: cubic-bezier(0.45, 0.05, 0.25, 1);
|
||||||
|
--dur-fast: 280ms;
|
||||||
|
--dur-med: 420ms;
|
||||||
|
--dur-slow: 700ms;
|
||||||
|
}
|
||||||
|
|
||||||
|
.dark {
|
||||||
|
--background: #12111d;
|
||||||
|
--foreground: #ecebf6;
|
||||||
|
--card: #191830;
|
||||||
|
--card-foreground: #ecebf6;
|
||||||
|
--popover: #201f3a;
|
||||||
|
--popover-foreground: #ecebf6;
|
||||||
|
--primary: #9189fb;
|
||||||
|
--primary-foreground: #161129;
|
||||||
|
--secondary: #8d95ab;
|
||||||
|
--secondary-foreground: #10131e;
|
||||||
|
--muted: #262442;
|
||||||
|
--muted-foreground: #a7a8c9;
|
||||||
|
--accent: #f095c4;
|
||||||
|
--accent-foreground: #2a0f1f;
|
||||||
|
--destructive: #f47b8c;
|
||||||
|
--destructive-foreground: #2a0a0f;
|
||||||
|
--success: #63e0a5;
|
||||||
|
--success-foreground: #06210f;
|
||||||
|
--gold: #fab653;
|
||||||
|
--gold-foreground: #2a1a02;
|
||||||
|
--border: #353360;
|
||||||
|
--input: #4d4a7e;
|
||||||
|
--ring: #9189fb;
|
||||||
|
--radius: 0.25rem;
|
||||||
|
--invert-bg: #f0eff8;
|
||||||
|
--invert-fg: #18162e;
|
||||||
|
}
|
||||||
|
|
||||||
|
@theme inline {
|
||||||
|
/* next/font: FD default + plain Latin face for English-only fields */
|
||||||
|
/* Prefer Apple Color Emoji first; chat also renders Apple PNGs for Linux hosts. */
|
||||||
|
--font-sans: var(--font-vazirmatn), "Apple Color Emoji", "Segoe UI Emoji", "Noto Color Emoji",
|
||||||
|
sans-serif;
|
||||||
|
--font-emoji: "Apple Color Emoji", "Segoe UI Emoji", "Noto Color Emoji", sans-serif;
|
||||||
|
--font-latin: var(--font-vazirmatn-latin), var(--font-vazirmatn), Tahoma, "Segoe UI", Arial,
|
||||||
|
sans-serif;
|
||||||
|
/* Technical / English strings keep Latin digits */
|
||||||
|
--font-mono: var(--font-vazirmatn-latin), ui-monospace, "Cascadia Code", "Source Code Pro", Menlo,
|
||||||
|
Consolas, monospace;
|
||||||
|
--color-background: var(--background);
|
||||||
|
--color-foreground: var(--foreground);
|
||||||
|
--color-card: var(--card);
|
||||||
|
--color-card-foreground: var(--card-foreground);
|
||||||
|
--color-popover: var(--popover);
|
||||||
|
--color-popover-foreground: var(--popover-foreground);
|
||||||
|
--color-primary: var(--primary);
|
||||||
|
--color-primary-foreground: var(--primary-foreground);
|
||||||
|
--color-secondary: var(--secondary);
|
||||||
|
--color-secondary-foreground: var(--secondary-foreground);
|
||||||
|
--color-muted: var(--muted);
|
||||||
|
--color-muted-foreground: var(--muted-foreground);
|
||||||
|
--color-accent: var(--accent);
|
||||||
|
--color-accent-foreground: var(--accent-foreground);
|
||||||
|
--color-destructive: var(--destructive);
|
||||||
|
--color-destructive-foreground: var(--destructive-foreground);
|
||||||
|
--color-success: var(--success);
|
||||||
|
--color-success-foreground: var(--success-foreground);
|
||||||
|
--color-gold: var(--gold);
|
||||||
|
--color-gold-foreground: var(--gold-foreground);
|
||||||
|
--color-border: var(--border);
|
||||||
|
--color-input: var(--input);
|
||||||
|
--color-ring: var(--ring);
|
||||||
|
--radius-sm: 6px;
|
||||||
|
--radius-md: 8px;
|
||||||
|
--radius-lg: 10px;
|
||||||
|
--radius-xl: 14px;
|
||||||
|
--radius-2xl: 20px;
|
||||||
|
--ease-soft: cubic-bezier(0.22, 1, 0.36, 1);
|
||||||
|
--default-transition-duration: 350ms;
|
||||||
|
--default-transition-timing-function: cubic-bezier(0.22, 1, 0.36, 1);
|
||||||
|
}
|
||||||
|
|
||||||
|
@layer base {
|
||||||
|
* {
|
||||||
|
border-color: var(--color-border);
|
||||||
|
}
|
||||||
|
html {
|
||||||
|
color-scheme: light;
|
||||||
|
scroll-behavior: smooth;
|
||||||
|
font-family: var(--font-sans);
|
||||||
|
}
|
||||||
|
html.dark {
|
||||||
|
color-scheme: dark;
|
||||||
|
}
|
||||||
|
body {
|
||||||
|
background-color: var(--background);
|
||||||
|
background-image:
|
||||||
|
radial-gradient(1100px 540px at 85% -8%, color-mix(in srgb, var(--color-accent) 11%, transparent), transparent 62%),
|
||||||
|
radial-gradient(1000px 520px at -8% 26%, color-mix(in srgb, var(--color-primary) 9%, transparent), transparent 60%),
|
||||||
|
radial-gradient(800px 420px at 50% 110%, color-mix(in srgb, var(--color-gold) 7%, transparent), transparent 60%);
|
||||||
|
background-attachment: fixed;
|
||||||
|
color: var(--foreground);
|
||||||
|
font-family: var(--font-sans);
|
||||||
|
-webkit-font-smoothing: antialiased;
|
||||||
|
text-rendering: optimizeLegibility;
|
||||||
|
}
|
||||||
|
/*
|
||||||
|
* Form controls: UA + Tailwind preflight use `font: inherit`, which is flaky.
|
||||||
|
* Pin family so Vazirmatn FD (Persian digits) paints the same as surrounding UI.
|
||||||
|
*/
|
||||||
|
input,
|
||||||
|
textarea,
|
||||||
|
select,
|
||||||
|
button {
|
||||||
|
font-family: var(--font-sans) !important;
|
||||||
|
font-feature-settings: normal !important;
|
||||||
|
}
|
||||||
|
input::placeholder,
|
||||||
|
textarea::placeholder,
|
||||||
|
input::-webkit-input-placeholder,
|
||||||
|
textarea::-webkit-input-placeholder {
|
||||||
|
font-family: var(--font-sans) !important;
|
||||||
|
font-feature-settings: normal !important;
|
||||||
|
}
|
||||||
|
/*
|
||||||
|
* English-only typing surfaces: passwords, usernames, email, captcha, URLs, codes.
|
||||||
|
* Use plain Vazirmatn (non-FD) so Latin digits stay Latin.
|
||||||
|
*/
|
||||||
|
.font-latin,
|
||||||
|
input.font-latin,
|
||||||
|
textarea.font-latin,
|
||||||
|
input[type="password"],
|
||||||
|
input[type="email"],
|
||||||
|
input[type="url"],
|
||||||
|
input[type="tel"],
|
||||||
|
input[dir="ltr"],
|
||||||
|
textarea[dir="ltr"],
|
||||||
|
input[autocomplete="username"],
|
||||||
|
input[autocomplete="email"],
|
||||||
|
input[autocomplete="current-password"],
|
||||||
|
input[autocomplete="new-password"],
|
||||||
|
input[autocomplete="one-time-code"],
|
||||||
|
input[id*="captcha" i],
|
||||||
|
input[name*="captcha" i],
|
||||||
|
input[id*="password" i],
|
||||||
|
input[name*="password" i],
|
||||||
|
input[id*="username" i],
|
||||||
|
input[name*="username" i] {
|
||||||
|
font-family: var(--font-latin) !important;
|
||||||
|
font-feature-settings: normal !important;
|
||||||
|
font-variant-numeric: lining-nums !important;
|
||||||
|
}
|
||||||
|
.font-latin::placeholder,
|
||||||
|
input.font-latin::placeholder,
|
||||||
|
textarea.font-latin::placeholder,
|
||||||
|
input[type="password"]::placeholder,
|
||||||
|
input[type="email"]::placeholder,
|
||||||
|
input[type="url"]::placeholder,
|
||||||
|
input[type="tel"]::placeholder,
|
||||||
|
input[dir="ltr"]::placeholder,
|
||||||
|
textarea[dir="ltr"]::placeholder {
|
||||||
|
font-family: var(--font-latin) !important;
|
||||||
|
}
|
||||||
|
input:-webkit-autofill,
|
||||||
|
input:-webkit-autofill:hover,
|
||||||
|
input:-webkit-autofill:focus,
|
||||||
|
textarea:-webkit-autofill,
|
||||||
|
select:-webkit-autofill {
|
||||||
|
font-family: var(--font-sans) !important;
|
||||||
|
}
|
||||||
|
h1,
|
||||||
|
h2,
|
||||||
|
h3,
|
||||||
|
h4,
|
||||||
|
h5,
|
||||||
|
h6 {
|
||||||
|
font-weight: 800;
|
||||||
|
letter-spacing: -0.01em;
|
||||||
|
text-wrap: balance;
|
||||||
|
}
|
||||||
|
::selection {
|
||||||
|
background: color-mix(in srgb, var(--color-primary) 22%, transparent);
|
||||||
|
color: inherit;
|
||||||
|
}
|
||||||
|
:focus-visible {
|
||||||
|
outline: 2px solid var(--color-ring);
|
||||||
|
outline-offset: 2px;
|
||||||
|
}
|
||||||
|
code {
|
||||||
|
font-family: var(--font-mono);
|
||||||
|
font-size: 0.875em;
|
||||||
|
}
|
||||||
|
::-webkit-scrollbar {
|
||||||
|
width: 10px;
|
||||||
|
height: 10px;
|
||||||
|
}
|
||||||
|
::-webkit-scrollbar-thumb {
|
||||||
|
background: color-mix(in srgb, var(--color-muted-foreground) 30%, transparent);
|
||||||
|
border-radius: 999px;
|
||||||
|
border: 2px solid var(--color-background);
|
||||||
|
}
|
||||||
|
::-webkit-scrollbar-track {
|
||||||
|
background: transparent;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
@layer components {
|
||||||
|
.chat-scroll {
|
||||||
|
scrollbar-width: thin;
|
||||||
|
scrollbar-color: color-mix(in srgb, var(--color-muted-foreground) 35%, transparent) transparent;
|
||||||
|
}
|
||||||
|
.chat-scroll::-webkit-scrollbar {
|
||||||
|
width: 6px;
|
||||||
|
}
|
||||||
|
.chat-scroll::-webkit-scrollbar-thumb {
|
||||||
|
background: color-mix(in srgb, var(--color-muted-foreground) 35%, transparent);
|
||||||
|
border-radius: 999px;
|
||||||
|
border-width: 0;
|
||||||
|
}
|
||||||
|
.section-kicker {
|
||||||
|
display: flex;
|
||||||
|
align-items: center;
|
||||||
|
gap: 0.5rem;
|
||||||
|
font-size: 0.6875rem;
|
||||||
|
font-weight: 800;
|
||||||
|
letter-spacing: 0.1em;
|
||||||
|
color: var(--color-primary);
|
||||||
|
}
|
||||||
|
.section-kicker::before {
|
||||||
|
content: "";
|
||||||
|
display: inline-block;
|
||||||
|
width: 1.75rem;
|
||||||
|
height: 3px;
|
||||||
|
border-radius: 2px;
|
||||||
|
background: var(--color-primary);
|
||||||
|
}
|
||||||
|
/* kicker sitting on a solid primary panel — bar & text follow the opposing tone */
|
||||||
|
.section-kicker.on-primary {
|
||||||
|
color: var(--color-primary-foreground);
|
||||||
|
}
|
||||||
|
.section-kicker.on-primary::before {
|
||||||
|
background: var(--color-primary-foreground);
|
||||||
|
}
|
||||||
|
.card-hover {
|
||||||
|
transition:
|
||||||
|
border-color 150ms ease,
|
||||||
|
box-shadow 250ms ease,
|
||||||
|
transform 250ms cubic-bezier(0.16, 1, 0.3, 1);
|
||||||
|
}
|
||||||
|
.card-hover:hover {
|
||||||
|
border-color: color-mix(in srgb, var(--color-primary) 45%, transparent);
|
||||||
|
box-shadow:
|
||||||
|
0 2px 6px rgba(41, 39, 70, 0.05),
|
||||||
|
0 22px 44px -18px rgba(75, 66, 200, 0.22);
|
||||||
|
transform: translateY(-3px);
|
||||||
|
}
|
||||||
|
.dark .card-hover:hover {
|
||||||
|
border-color: color-mix(in srgb, var(--color-primary) 60%, transparent);
|
||||||
|
box-shadow:
|
||||||
|
0 2px 10px rgba(0, 0, 0, 0.4),
|
||||||
|
0 22px 44px -18px color-mix(in srgb, var(--color-primary) 40%, transparent);
|
||||||
|
}
|
||||||
|
.shadow-soft {
|
||||||
|
box-shadow:
|
||||||
|
0 2px 6px rgba(41, 39, 70, 0.05),
|
||||||
|
0 20px 44px -22px rgba(41, 39, 70, 0.2);
|
||||||
|
}
|
||||||
|
.dark .shadow-soft {
|
||||||
|
box-shadow: 0 2px 8px rgba(0, 0, 0, 0.4), 0 22px 48px -22px rgba(0, 0, 0, 0.55);
|
||||||
|
}
|
||||||
|
/* signature offset shadow — softened for the pastel identity */
|
||||||
|
.shadow-offset {
|
||||||
|
box-shadow: 5px 5px 0 0 var(--invert-fg);
|
||||||
|
}
|
||||||
|
.shadow-offset-sm {
|
||||||
|
box-shadow: 4px 4px 0 0 var(--invert-fg);
|
||||||
|
}
|
||||||
|
/* in dark mode the offset shadow must stay visible against the dark canvas */
|
||||||
|
.dark .shadow-offset {
|
||||||
|
box-shadow: 5px 5px 0 0 rgba(255, 255, 255, 0.16);
|
||||||
|
}
|
||||||
|
.dark .shadow-offset-sm {
|
||||||
|
box-shadow: 4px 4px 0 0 rgba(255, 255, 255, 0.14);
|
||||||
|
}
|
||||||
|
/* inverted editorial band */
|
||||||
|
.band-invert {
|
||||||
|
background:
|
||||||
|
radial-gradient(900px 400px at 90% -20%, color-mix(in srgb, var(--color-accent) 26%, transparent), transparent 60%),
|
||||||
|
var(--invert-bg);
|
||||||
|
color: var(--invert-fg);
|
||||||
|
}
|
||||||
|
.chip-outline {
|
||||||
|
display: inline-flex;
|
||||||
|
align-items: center;
|
||||||
|
gap: 0.4rem;
|
||||||
|
border: 2px solid currentColor;
|
||||||
|
border-radius: 999px;
|
||||||
|
padding: 0.35rem 0.8rem;
|
||||||
|
font-size: 0.75rem;
|
||||||
|
font-weight: 800;
|
||||||
|
letter-spacing: 0.04em;
|
||||||
|
}
|
||||||
|
.dot-grid {
|
||||||
|
background-image: radial-gradient(
|
||||||
|
color-mix(in srgb, currentColor 16%, transparent) 1px,
|
||||||
|
transparent 1px
|
||||||
|
);
|
||||||
|
background-size: 18px 18px;
|
||||||
|
}
|
||||||
|
.dot-grid-primary {
|
||||||
|
color: var(--color-primary);
|
||||||
|
}
|
||||||
|
|
||||||
|
/* frosted glass — a touch: soft, restrained */
|
||||||
|
.glass {
|
||||||
|
background: linear-gradient(150deg, rgba(255, 255, 255, 0.52), rgba(255, 255, 255, 0.28));
|
||||||
|
-webkit-backdrop-filter: blur(14px) saturate(1.3);
|
||||||
|
backdrop-filter: blur(14px) saturate(1.3);
|
||||||
|
border: 1px solid rgba(255, 255, 255, 0.5);
|
||||||
|
box-shadow:
|
||||||
|
inset 0 1px 0 rgba(255, 255, 255, 0.6),
|
||||||
|
0 16px 36px -22px rgba(41, 39, 70, 0.3);
|
||||||
|
}
|
||||||
|
.dark .glass {
|
||||||
|
background: linear-gradient(150deg, rgba(255, 255, 255, 0.07), rgba(255, 255, 255, 0.03));
|
||||||
|
border: 1px solid rgba(255, 255, 255, 0.1);
|
||||||
|
box-shadow:
|
||||||
|
inset 0 1px 0 rgba(255, 255, 255, 0.09),
|
||||||
|
0 16px 36px -22px rgba(0, 0, 0, 0.6);
|
||||||
|
}
|
||||||
|
|
||||||
|
/* frosted glow variants per status (colored ambience) */
|
||||||
|
.glass-glow-primary,
|
||||||
|
.glass-glow-accent,
|
||||||
|
.glass-glow-gold,
|
||||||
|
.glass-glow-success,
|
||||||
|
.glass-glow-neutral {
|
||||||
|
box-shadow:
|
||||||
|
inset 0 1px 0 rgba(255, 255, 255, 0.55),
|
||||||
|
0 14px 34px -12px rgba(41, 39, 70, 0.3);
|
||||||
|
}
|
||||||
|
.glass-glow-primary {
|
||||||
|
box-shadow:
|
||||||
|
inset 0 1px 0 rgba(255, 255, 255, 0.55),
|
||||||
|
0 14px 34px -12px color-mix(in srgb, var(--color-primary) 42%, transparent);
|
||||||
|
}
|
||||||
|
.glass-glow-accent {
|
||||||
|
box-shadow:
|
||||||
|
inset 0 1px 0 rgba(255, 255, 255, 0.55),
|
||||||
|
0 14px 34px -12px color-mix(in srgb, var(--color-accent) 40%, transparent);
|
||||||
|
}
|
||||||
|
.glass-glow-gold {
|
||||||
|
box-shadow:
|
||||||
|
inset 0 1px 0 rgba(255, 255, 255, 0.55),
|
||||||
|
0 14px 34px -12px color-mix(in srgb, var(--color-gold) 40%, transparent);
|
||||||
|
}
|
||||||
|
.glass-glow-success {
|
||||||
|
box-shadow:
|
||||||
|
inset 0 1px 0 rgba(255, 255, 255, 0.55),
|
||||||
|
0 14px 34px -12px color-mix(in srgb, var(--color-success) 40%, transparent);
|
||||||
|
}
|
||||||
|
|
||||||
|
/* glass navigation bar */
|
||||||
|
.nav-glass {
|
||||||
|
background: color-mix(in srgb, var(--color-background) 82%, transparent);
|
||||||
|
-webkit-backdrop-filter: blur(16px) saturate(1.5);
|
||||||
|
backdrop-filter: blur(16px) saturate(1.5);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
@layer utilities {
|
||||||
|
/* legacy aliases now render soft + calm */
|
||||||
|
.bg-gradient-brand {
|
||||||
|
background-color: var(--color-primary);
|
||||||
|
background-image: none;
|
||||||
|
}
|
||||||
|
.text-gradient-brand {
|
||||||
|
color: var(--color-primary);
|
||||||
|
-webkit-background-clip: initial;
|
||||||
|
background-clip: initial;
|
||||||
|
}
|
||||||
|
.shadow-glow,
|
||||||
|
.shadow-glow-cyan {
|
||||||
|
box-shadow: none;
|
||||||
|
}
|
||||||
|
|
||||||
|
/* ---------- motion system (soft by default) ---------- */
|
||||||
|
.reveal {
|
||||||
|
opacity: 0;
|
||||||
|
animation: fadeUp 0.85s var(--ease-soft) forwards;
|
||||||
|
}
|
||||||
|
.reveal-1 { animation-delay: 0.08s; }
|
||||||
|
.reveal-2 { animation-delay: 0.16s; }
|
||||||
|
.reveal-3 { animation-delay: 0.24s; }
|
||||||
|
.reveal-4 { animation-delay: 0.32s; }
|
||||||
|
.reveal-5 { animation-delay: 0.4s; }
|
||||||
|
.reveal-scale {
|
||||||
|
opacity: 0;
|
||||||
|
animation: scaleIn 0.7s var(--ease-soft) forwards;
|
||||||
|
}
|
||||||
|
.hover-lift {
|
||||||
|
transition:
|
||||||
|
transform var(--dur-med) var(--ease-soft),
|
||||||
|
box-shadow var(--dur-med) var(--ease-soft);
|
||||||
|
}
|
||||||
|
.hover-lift:hover {
|
||||||
|
transform: translateY(-3px);
|
||||||
|
box-shadow:
|
||||||
|
0 2px 6px rgba(41, 39, 70, 0.05),
|
||||||
|
0 20px 40px -18px color-mix(in srgb, var(--color-primary) 26%, transparent);
|
||||||
|
}
|
||||||
|
.dark .hover-lift:hover {
|
||||||
|
box-shadow:
|
||||||
|
0 2px 10px rgba(0, 0, 0, 0.35),
|
||||||
|
0 20px 40px -18px color-mix(in srgb, var(--color-primary) 32%, transparent);
|
||||||
|
}
|
||||||
|
.press {
|
||||||
|
transition: transform var(--dur-fast) var(--ease-soft);
|
||||||
|
}
|
||||||
|
.press:active {
|
||||||
|
transform: translateY(1px) scale(0.985);
|
||||||
|
}
|
||||||
|
.press-flat:active {
|
||||||
|
transform: translateY(0.5px) scale(0.99);
|
||||||
|
}
|
||||||
|
.float-slow {
|
||||||
|
animation: floatY 9s var(--ease-soft-in-out) infinite;
|
||||||
|
}
|
||||||
|
.animate-pulse-soft {
|
||||||
|
animation: pulseSoft 3s var(--ease-soft-in-out) infinite;
|
||||||
|
}
|
||||||
|
|
||||||
|
/* Soften common Tailwind transition utilities */
|
||||||
|
.transition,
|
||||||
|
.transition-all,
|
||||||
|
.transition-colors,
|
||||||
|
.transition-opacity,
|
||||||
|
.transition-shadow,
|
||||||
|
.transition-transform {
|
||||||
|
transition-timing-function: var(--ease-soft);
|
||||||
|
}
|
||||||
|
.duration-75 { transition-duration: 180ms; }
|
||||||
|
.duration-100 { transition-duration: 220ms; }
|
||||||
|
.duration-150 { transition-duration: 280ms; }
|
||||||
|
.duration-200 { transition-duration: 350ms; }
|
||||||
|
.duration-300 { transition-duration: 420ms; }
|
||||||
|
.ease-out { transition-timing-function: var(--ease-soft); }
|
||||||
|
.ease-in-out { transition-timing-function: var(--ease-soft-in-out); }
|
||||||
|
|
||||||
|
/* Soften snappy active scales */
|
||||||
|
.active\:scale-90:active {
|
||||||
|
transform: scale(0.96);
|
||||||
|
}
|
||||||
|
|
||||||
|
@media (prefers-reduced-motion: reduce) {
|
||||||
|
.reveal,
|
||||||
|
.reveal-scale {
|
||||||
|
opacity: 1;
|
||||||
|
animation: none;
|
||||||
|
}
|
||||||
|
.float-slow,
|
||||||
|
.hover-lift,
|
||||||
|
.press,
|
||||||
|
.animate-pulse-soft,
|
||||||
|
.chat-msg-glow {
|
||||||
|
transition: none;
|
||||||
|
animation: none;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/* keyframes live at root so they always exist regardless of layers */
|
||||||
|
@keyframes fadeUp {
|
||||||
|
from {
|
||||||
|
opacity: 0;
|
||||||
|
transform: translateY(12px);
|
||||||
|
}
|
||||||
|
to {
|
||||||
|
opacity: 1;
|
||||||
|
transform: none;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
@keyframes scaleIn {
|
||||||
|
from {
|
||||||
|
opacity: 0;
|
||||||
|
transform: scale(0.985);
|
||||||
|
}
|
||||||
|
to {
|
||||||
|
opacity: 1;
|
||||||
|
transform: none;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
@keyframes floatY {
|
||||||
|
0%,
|
||||||
|
100% {
|
||||||
|
transform: translateY(0);
|
||||||
|
}
|
||||||
|
50% {
|
||||||
|
transform: translateY(-6px);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
@keyframes pulseSoft {
|
||||||
|
0%,
|
||||||
|
100% {
|
||||||
|
opacity: 1;
|
||||||
|
}
|
||||||
|
50% {
|
||||||
|
opacity: 0.7;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
@keyframes chatMsgGlow {
|
||||||
|
0% {
|
||||||
|
filter: drop-shadow(0 0 0 transparent);
|
||||||
|
}
|
||||||
|
35% {
|
||||||
|
filter: drop-shadow(0 0 12px color-mix(in srgb, var(--color-gold) 55%, transparent))
|
||||||
|
drop-shadow(0 0 28px color-mix(in srgb, var(--color-gold) 28%, transparent));
|
||||||
|
}
|
||||||
|
100% {
|
||||||
|
filter: drop-shadow(0 0 0 transparent);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
.chat-msg-glow {
|
||||||
|
animation: chatMsgGlow 1.85s var(--ease-soft) forwards;
|
||||||
|
will-change: filter;
|
||||||
|
}
|
||||||
|
|
||||||
|
@keyframes metaprog {
|
||||||
|
0% {
|
||||||
|
transform: translateX(-120%);
|
||||||
|
}
|
||||||
|
100% {
|
||||||
|
transform: translateX(420%);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/* Soften Tailwind ping / pulse defaults for this app */
|
||||||
|
@keyframes softPing {
|
||||||
|
0% {
|
||||||
|
transform: scale(1);
|
||||||
|
opacity: 0.55;
|
||||||
|
}
|
||||||
|
75%,
|
||||||
|
100% {
|
||||||
|
transform: scale(1.45);
|
||||||
|
opacity: 0;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
.animate-ping {
|
||||||
|
animation: softPing 1.6s var(--ease-soft-in-out) infinite;
|
||||||
|
}
|
||||||
|
|
||||||
|
@keyframes softPulse {
|
||||||
|
0%,
|
||||||
|
100% {
|
||||||
|
opacity: 1;
|
||||||
|
}
|
||||||
|
50% {
|
||||||
|
opacity: 0.72;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
.animate-pulse {
|
||||||
|
animation: softPulse 2.8s var(--ease-soft-in-out) infinite;
|
||||||
|
}
|
||||||
|
|
||||||
|
/* ---- skeleton shimmer ------------------------------------------------ */
|
||||||
|
.skeleton {
|
||||||
|
position: relative;
|
||||||
|
overflow: hidden;
|
||||||
|
background-color: var(--color-muted);
|
||||||
|
border-radius: 0.75rem;
|
||||||
|
}
|
||||||
|
.skeleton::after {
|
||||||
|
content: "";
|
||||||
|
position: absolute;
|
||||||
|
inset: 0;
|
||||||
|
transform: translateX(-100%);
|
||||||
|
background: linear-gradient(
|
||||||
|
90deg,
|
||||||
|
transparent,
|
||||||
|
color-mix(in srgb, var(--color-foreground) 8%, transparent),
|
||||||
|
transparent
|
||||||
|
);
|
||||||
|
animation: skeletonShimmer 2s var(--ease-soft-in-out) infinite;
|
||||||
|
}
|
||||||
|
@keyframes skeletonShimmer {
|
||||||
|
100% {
|
||||||
|
transform: translateX(100%);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/* ---- global motion safety --------------------------------------------- */
|
||||||
|
@media (prefers-reduced-motion: no-preference) {
|
||||||
|
html {
|
||||||
|
scroll-behavior: smooth;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
@media (prefers-reduced-motion: reduce) {
|
||||||
|
*,
|
||||||
|
*::before,
|
||||||
|
*::after {
|
||||||
|
animation-duration: 0.01ms !important;
|
||||||
|
animation-iteration-count: 1 !important;
|
||||||
|
transition-duration: 0.01ms !important;
|
||||||
|
scroll-behavior: auto !important;
|
||||||
|
}
|
||||||
|
}
|
||||||
Binary file not shown.
|
After Width: | Height: | Size: 49 KiB |
@@ -0,0 +1,59 @@
|
|||||||
|
import type { Metadata } from "next";
|
||||||
|
import localFont from "next/font/local";
|
||||||
|
import "./globals.css";
|
||||||
|
import { Providers } from "@/components/providers";
|
||||||
|
import { AppShell } from "@/components/app-shell";
|
||||||
|
import { PageTransition } from "@/components/page-transition";
|
||||||
|
|
||||||
|
/** Vazirmatn FD — default UI; Latin digits render as Persian glyphs. */
|
||||||
|
const vazirmatnFd = localFont({
|
||||||
|
src: [
|
||||||
|
{ path: "./fonts/Vazirmatn-FD-Thin.woff2", weight: "100", style: "normal" },
|
||||||
|
{ path: "./fonts/Vazirmatn-FD-ExtraLight.woff2", weight: "200", style: "normal" },
|
||||||
|
{ path: "./fonts/Vazirmatn-FD-Light.woff2", weight: "300", style: "normal" },
|
||||||
|
{ path: "./fonts/Vazirmatn-FD-Regular.woff2", weight: "400", style: "normal" },
|
||||||
|
{ path: "./fonts/Vazirmatn-FD-Medium.woff2", weight: "500", style: "normal" },
|
||||||
|
{ path: "./fonts/Vazirmatn-FD-SemiBold.woff2", weight: "600", style: "normal" },
|
||||||
|
{ path: "./fonts/Vazirmatn-FD-Bold.woff2", weight: "700", style: "normal" },
|
||||||
|
{ path: "./fonts/Vazirmatn-FD-ExtraBold.woff2", weight: "800", style: "normal" },
|
||||||
|
{ path: "./fonts/Vazirmatn-FD-Black.woff2", weight: "900", style: "normal" },
|
||||||
|
],
|
||||||
|
display: "swap",
|
||||||
|
variable: "--font-vazirmatn",
|
||||||
|
fallback: ["Tahoma", "Segoe UI", "Arial", "sans-serif"],
|
||||||
|
});
|
||||||
|
|
||||||
|
/** Plain Vazirmatn — Latin digits stay Latin (passwords, usernames, captcha, URLs…). */
|
||||||
|
const vazirmatnLatin = localFont({
|
||||||
|
src: "./fonts/Vazirmatn-Variable.woff2",
|
||||||
|
weight: "100 900",
|
||||||
|
display: "swap",
|
||||||
|
variable: "--font-vazirmatn-latin",
|
||||||
|
fallback: ["Tahoma", "Segoe UI", "Arial", "sans-serif"],
|
||||||
|
});
|
||||||
|
|
||||||
|
export const metadata: Metadata = {
|
||||||
|
title: "پرگار",
|
||||||
|
description: "مسیر یادگیری واقعی پرگار",
|
||||||
|
};
|
||||||
|
|
||||||
|
export default function RootLayout({ children }: { children: React.ReactNode }) {
|
||||||
|
return (
|
||||||
|
<html
|
||||||
|
lang="fa"
|
||||||
|
dir="rtl"
|
||||||
|
className={`${vazirmatnFd.variable} ${vazirmatnLatin.variable}`}
|
||||||
|
suppressHydrationWarning
|
||||||
|
>
|
||||||
|
<body
|
||||||
|
className={`${vazirmatnFd.className} min-h-screen bg-background font-sans text-foreground antialiased`}
|
||||||
|
>
|
||||||
|
<Providers>
|
||||||
|
<AppShell>
|
||||||
|
<PageTransition>{children}</PageTransition>
|
||||||
|
</AppShell>
|
||||||
|
</Providers>
|
||||||
|
</body>
|
||||||
|
</html>
|
||||||
|
);
|
||||||
|
}
|
||||||
@@ -0,0 +1,31 @@
|
|||||||
|
"use client";
|
||||||
|
|
||||||
|
import { Suspense } from "react";
|
||||||
|
import { Trophy } from "lucide-react";
|
||||||
|
import { LeaderboardPanel } from "@/components/leaderboard-panel";
|
||||||
|
import { PageHeader } from "@/components/page-header";
|
||||||
|
|
||||||
|
export default function LeaderboardPage() {
|
||||||
|
return (
|
||||||
|
<div className="space-y-8">
|
||||||
|
<PageHeader
|
||||||
|
align="center"
|
||||||
|
kicker="رقابت هفتگی"
|
||||||
|
title={
|
||||||
|
<>
|
||||||
|
لیگ <span className="text-gradient-brand">هفتگی</span>
|
||||||
|
</>
|
||||||
|
}
|
||||||
|
description="با تکمیل صادقانه دروس امتیاز بگیرید. لیگ هر دوشنبه صفر میشود — استمرار از شدت مهمتر است."
|
||||||
|
actions={
|
||||||
|
<span className="flex h-12 w-12 items-center justify-center rounded-xl bg-primary/10 text-primary">
|
||||||
|
<Trophy className="h-6 w-6" />
|
||||||
|
</span>
|
||||||
|
}
|
||||||
|
/>
|
||||||
|
<Suspense fallback={null}>
|
||||||
|
<LeaderboardPanel />
|
||||||
|
</Suspense>
|
||||||
|
</div>
|
||||||
|
);
|
||||||
|
}
|
||||||
@@ -0,0 +1,152 @@
|
|||||||
|
"use client";
|
||||||
|
|
||||||
|
import { useCallback, useEffect, useState } from "react";
|
||||||
|
import { useRouter } from "next/navigation";
|
||||||
|
import { Heart, Lock, MessageSquare, Send, Loader2 } from "lucide-react";
|
||||||
|
import { useAuth } from "@/lib/auth-store";
|
||||||
|
import { api, http, toUserError } from "@/lib/api";
|
||||||
|
import { MAX_HEARTS, clampHearts, hasInfiniteHearts } from "@/lib/hearts";
|
||||||
|
import type { Mentor, User } from "@/lib/types";
|
||||||
|
import { Card } from "@/components/ui/card";
|
||||||
|
import { Button } from "@/components/ui/button";
|
||||||
|
import { toast } from "@/components/providers";
|
||||||
|
import { cn } from "@/lib/utils";
|
||||||
|
|
||||||
|
export default function LockoutPage() {
|
||||||
|
const router = useRouter();
|
||||||
|
const user = useAuth((s) => s.user);
|
||||||
|
const [note, setNote] = useState("");
|
||||||
|
const [busy, setBusy] = useState(false);
|
||||||
|
const [requested, setRequested] = useState(false);
|
||||||
|
const [mentorId, setMentorId] = useState<number | null>(null);
|
||||||
|
|
||||||
|
const syncUser = useCallback(async () => {
|
||||||
|
try {
|
||||||
|
const res = await api<{ user: User }>("/api/auth/me");
|
||||||
|
useAuth.getState().setUser(res.user);
|
||||||
|
if (!res.user.isLocked || hasInfiniteHearts(res.user.role)) {
|
||||||
|
router.replace("/cap");
|
||||||
|
}
|
||||||
|
} catch {
|
||||||
|
/* ignore */
|
||||||
|
}
|
||||||
|
}, [router]);
|
||||||
|
|
||||||
|
useEffect(() => {
|
||||||
|
if (user && (!user.isLocked || hasInfiniteHearts(user.role))) {
|
||||||
|
router.replace("/cap");
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
const onFocus = () => void syncUser();
|
||||||
|
window.addEventListener("focus", onFocus);
|
||||||
|
void syncUser();
|
||||||
|
return () => {
|
||||||
|
window.removeEventListener("focus", onFocus);
|
||||||
|
};
|
||||||
|
}, [syncUser, user, router]);
|
||||||
|
|
||||||
|
useEffect(() => {
|
||||||
|
void http
|
||||||
|
.get<{ mentors: Mentor[] }>("/api/mentors")
|
||||||
|
.then((r) => {
|
||||||
|
const first = r.mentors?.[0];
|
||||||
|
if (first) setMentorId(first.id);
|
||||||
|
})
|
||||||
|
.catch(() => undefined);
|
||||||
|
}, []);
|
||||||
|
|
||||||
|
const requestUnlock = async () => {
|
||||||
|
setBusy(true);
|
||||||
|
try {
|
||||||
|
const res = await http.post<{ message?: string }>("/api/me/request-unlock", { note });
|
||||||
|
setRequested(true);
|
||||||
|
toast.success(res.message || "درخواست ثبت شد");
|
||||||
|
} catch (e) {
|
||||||
|
toast.error(toUserError(e));
|
||||||
|
} finally {
|
||||||
|
setBusy(false);
|
||||||
|
}
|
||||||
|
};
|
||||||
|
|
||||||
|
const openMentorChat = () => {
|
||||||
|
const draft =
|
||||||
|
"سلام، حسابم بعد از اتمام جانها قفل شده. لطفاً برای رفع محدودیت راهنماییام کنید.";
|
||||||
|
window.dispatchEvent(
|
||||||
|
new CustomEvent("pargar:chat", {
|
||||||
|
detail: { open: true, with: mentorId ?? undefined, draft },
|
||||||
|
}),
|
||||||
|
);
|
||||||
|
};
|
||||||
|
|
||||||
|
const hearts = clampHearts(user?.hearts ?? 0);
|
||||||
|
|
||||||
|
return (
|
||||||
|
<div className="mx-auto flex min-h-[70vh] max-w-lg flex-col items-center justify-center px-4 text-center">
|
||||||
|
<div className="mb-6 flex h-20 w-20 items-center justify-center rounded-2xl bg-destructive/15">
|
||||||
|
<Lock className="h-11 w-11 text-destructive" />
|
||||||
|
</div>
|
||||||
|
|
||||||
|
<p className="text-xs font-bold tracking-wider text-destructive">حساب قفل شد</p>
|
||||||
|
<h1 className="mt-2 text-3xl font-bold tracking-tight">جانهایتان تمام شد</h1>
|
||||||
|
<p className="mt-3 text-sm leading-relaxed text-muted-foreground">
|
||||||
|
هر پاسخ اشتباه در آزمون یک جان کم میکند. با تمام شدن سه جان، یادگیری و آزمون قفل میشود تا
|
||||||
|
تیم مسیر را بررسی کند — خودتان نمیتوانید قفل را باز کنید.
|
||||||
|
</p>
|
||||||
|
|
||||||
|
<div className="mt-6 flex items-center gap-2">
|
||||||
|
{Array.from({ length: MAX_HEARTS }).map((_, i) =>
|
||||||
|
i < hearts ? (
|
||||||
|
<span key={i} className="grid h-9 w-9 place-items-center rounded-full bg-destructive/15 text-destructive">
|
||||||
|
<Heart className="h-5 w-5 fill-current" />
|
||||||
|
</span>
|
||||||
|
) : (
|
||||||
|
<span key={i} className="grid h-9 w-9 place-items-center rounded-full bg-muted text-muted-foreground/40">
|
||||||
|
<Heart className="h-5 w-5" />
|
||||||
|
</span>
|
||||||
|
),
|
||||||
|
)}
|
||||||
|
</div>
|
||||||
|
|
||||||
|
<Card className="mt-6 w-full space-y-3 border-destructive/30 bg-destructive/5 p-4 text-start text-sm text-muted-foreground">
|
||||||
|
<p className="font-bold text-foreground">گام بعدی</p>
|
||||||
|
<ol className="list-decimal space-y-1.5 pe-4 text-xs leading-relaxed">
|
||||||
|
<li>از طریق گفتگو با منتور وضعیت را توضیح دهید.</li>
|
||||||
|
<li>درخواست بررسی را برای تیم ثبت کنید (حداکثر یکبار در ۱۲ ساعت).</li>
|
||||||
|
<li>بعد از تأیید متصدی، ۳ جان برمیگردد و مسیر دوباره باز میشود.</li>
|
||||||
|
</ol>
|
||||||
|
</Card>
|
||||||
|
|
||||||
|
<div className="mt-5 w-full space-y-2">
|
||||||
|
<textarea
|
||||||
|
value={note}
|
||||||
|
onChange={(e) => setNote(e.target.value)}
|
||||||
|
maxLength={500}
|
||||||
|
rows={3}
|
||||||
|
dir="rtl"
|
||||||
|
placeholder="اختیاری: چه آزمونی گیر کردید؟ چه کمکی لازم دارید؟"
|
||||||
|
className="w-full rounded-xl border-2 border-border bg-background px-3 py-2 text-sm outline-none focus-visible:border-primary/50"
|
||||||
|
/>
|
||||||
|
<div className="flex flex-col gap-2 sm:flex-row">
|
||||||
|
<Button className="flex-1" disabled={busy || requested} onClick={() => void requestUnlock()}>
|
||||||
|
{busy ? <Loader2 className="h-4 w-4 animate-spin" /> : <Send className="h-4 w-4" />}
|
||||||
|
{requested ? "درخواست ارسال شد" : "درخواست رفع قفل"}
|
||||||
|
</Button>
|
||||||
|
<Button
|
||||||
|
variant="outline"
|
||||||
|
className="flex-1"
|
||||||
|
onClick={openMentorChat}
|
||||||
|
>
|
||||||
|
<MessageSquare className="h-4 w-4" /> گفتگو با منتور
|
||||||
|
</Button>
|
||||||
|
</div>
|
||||||
|
<Button
|
||||||
|
variant="ghost"
|
||||||
|
className={cn("w-full text-muted-foreground")}
|
||||||
|
onClick={() => router.push("/unwrap?tab=community")}
|
||||||
|
>
|
||||||
|
جامعه و حمایت
|
||||||
|
</Button>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
);
|
||||||
|
}
|
||||||
@@ -0,0 +1,240 @@
|
|||||||
|
"use client";
|
||||||
|
|
||||||
|
import { useCallback, useEffect, useState } from "react";
|
||||||
|
import Link from "next/link";
|
||||||
|
import { useRouter } from "next/navigation";
|
||||||
|
import { useQuery } from "@tanstack/react-query";
|
||||||
|
import { CheckCircle2, Loader2, RefreshCw, ShieldCheck, Timer, Zap } from "lucide-react";
|
||||||
|
import { BrandMark } from "@/components/brand-mark";
|
||||||
|
import { useAuth } from "@/lib/auth-store";
|
||||||
|
import { http, toUserError } from "@/lib/api";
|
||||||
|
import type { User } from "@/lib/types";
|
||||||
|
import { Button } from "@/components/ui/button";
|
||||||
|
import { Input } from "@/components/ui/input";
|
||||||
|
import { PasswordInput } from "@/components/ui/password-input";
|
||||||
|
import { Label } from "@/components/ui/label";
|
||||||
|
import { Switch } from "@/components/ui/switch";
|
||||||
|
import { CardContent, CardHeader, CardTitle, CardDescription } from "@/components/ui/card";
|
||||||
|
|
||||||
|
const perks = [
|
||||||
|
{ icon: Timer, text: "زمان تماشای راستیآزماییشده — بدون میانبر" },
|
||||||
|
{ icon: ShieldCheck, text: "قفلشدن پس از سه اشتباه، تا وقتی واقعاً یاد بگیرید" },
|
||||||
|
{ icon: CheckCircle2, text: "لیگ هفتگی، رویداد زنده و منتور یکبهیک" },
|
||||||
|
];
|
||||||
|
|
||||||
|
type CaptchaChallenge = {
|
||||||
|
challengeId: string;
|
||||||
|
imageBase64: string;
|
||||||
|
};
|
||||||
|
|
||||||
|
export default function LoginPage() {
|
||||||
|
const router = useRouter();
|
||||||
|
const setSession = useAuth((s) => s.setSession);
|
||||||
|
const [email, setEmail] = useState("");
|
||||||
|
const [password, setPassword] = useState("");
|
||||||
|
const [captchaAnswer, setCaptchaAnswer] = useState("");
|
||||||
|
const [challenge, setChallenge] = useState<CaptchaChallenge | null>(null);
|
||||||
|
const [captchaLoading, setCaptchaLoading] = useState(true);
|
||||||
|
const [rememberMe, setRememberMe] = useState(false);
|
||||||
|
const [loading, setLoading] = useState(false);
|
||||||
|
const [error, setError] = useState<string | null>(null);
|
||||||
|
|
||||||
|
const { data: registerStatus } = useQuery({
|
||||||
|
queryKey: ["auth", "register-status"],
|
||||||
|
queryFn: () => http.get<{ enabled: boolean }>("/api/auth/register-status"),
|
||||||
|
});
|
||||||
|
|
||||||
|
const loadCaptcha = useCallback(async () => {
|
||||||
|
setCaptchaLoading(true);
|
||||||
|
setCaptchaAnswer("");
|
||||||
|
try {
|
||||||
|
const data = await http.get<CaptchaChallenge>("/api/auth/captcha");
|
||||||
|
setChallenge(data);
|
||||||
|
} catch (err) {
|
||||||
|
setChallenge(null);
|
||||||
|
setError(toUserError(err, "بارگذاری کد امنیتی ممکن نشد"));
|
||||||
|
} finally {
|
||||||
|
setCaptchaLoading(false);
|
||||||
|
}
|
||||||
|
}, []);
|
||||||
|
|
||||||
|
useEffect(() => {
|
||||||
|
void loadCaptcha();
|
||||||
|
}, [loadCaptcha]);
|
||||||
|
|
||||||
|
const submit = async (e: React.FormEvent) => {
|
||||||
|
e.preventDefault();
|
||||||
|
if (!challenge) {
|
||||||
|
setError("ابتدا کد امنیتی را بارگذاری کنید");
|
||||||
|
void loadCaptcha();
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
setLoading(true);
|
||||||
|
setError(null);
|
||||||
|
try {
|
||||||
|
const data = await http.post<{ accessToken: string; refreshToken: string; user: User }>("/api/auth/login", {
|
||||||
|
username: email,
|
||||||
|
password,
|
||||||
|
challengeId: challenge.challengeId,
|
||||||
|
captchaAnswer,
|
||||||
|
rememberMe,
|
||||||
|
});
|
||||||
|
setSession(data.accessToken, data.refreshToken, data.user);
|
||||||
|
router.push("/cap");
|
||||||
|
} catch (err) {
|
||||||
|
setError(toUserError(err, "ورود ناموفق بود"));
|
||||||
|
void loadCaptcha();
|
||||||
|
} finally {
|
||||||
|
setLoading(false);
|
||||||
|
}
|
||||||
|
};
|
||||||
|
|
||||||
|
return (
|
||||||
|
<div className="mx-auto flex min-h-[80vh] max-w-4xl flex-col justify-center px-4 py-8">
|
||||||
|
<div className="grid overflow-hidden rounded-2xl border border-border bg-card shadow-soft md:grid-cols-2">
|
||||||
|
{/* brand panel */}
|
||||||
|
<aside className="relative hidden flex-col justify-between overflow-hidden bg-primary p-7 text-primary-foreground md:flex">
|
||||||
|
<div className="dot-grid pointer-events-none absolute -end-20 -top-20 h-72 w-72 rotate-12 text-primary-foreground opacity-50" aria-hidden />
|
||||||
|
<span className="pointer-events-none absolute end-8 top-8 h-6 w-6 rotate-12 rounded-md bg-accent" aria-hidden />
|
||||||
|
<div className="relative">
|
||||||
|
<BrandMark locale="fa" size="lg" className="text-primary-foreground [&_span]:text-accent" />
|
||||||
|
<p className="section-kicker on-primary mt-5">بوتکمپ دگرگونی</p>
|
||||||
|
<h2 className="mt-3 text-2xl font-bold leading-snug">
|
||||||
|
سیستم، میانبر ندارد.
|
||||||
|
<br />
|
||||||
|
شما هم ندارید.
|
||||||
|
</h2>
|
||||||
|
<p className="mt-2.5 text-sm leading-relaxed text-primary-foreground/80">
|
||||||
|
یادگیری را قابل کنترل و قابل اثبات میکند — برای خودتان هم که شده.
|
||||||
|
</p>
|
||||||
|
</div>
|
||||||
|
<ul className="relative mt-6 space-y-2.5">
|
||||||
|
{perks.map((p) => (
|
||||||
|
<li key={p.text} className="flex items-start gap-2.5 text-sm">
|
||||||
|
<p.icon className="mt-0.5 h-4 w-4 shrink-0 text-primary-foreground/90" />
|
||||||
|
<span className="leading-relaxed text-primary-foreground/90">{p.text}</span>
|
||||||
|
</li>
|
||||||
|
))}
|
||||||
|
</ul>
|
||||||
|
</aside>
|
||||||
|
|
||||||
|
{/* form panel */}
|
||||||
|
<div className="flex flex-col justify-center bg-card p-6 sm:p-8">
|
||||||
|
<CardHeader className="items-center space-y-1.5 px-0 pb-5 pt-0 text-center">
|
||||||
|
<div className="mb-1 flex justify-center md:hidden">
|
||||||
|
<BrandMark locale="fa" size="lg" logoOnly />
|
||||||
|
</div>
|
||||||
|
<CardTitle className="text-2xl">خوش برگشتید</CardTitle>
|
||||||
|
<CardDescription>برای ادامه مسیر خود وارد شوید.</CardDescription>
|
||||||
|
</CardHeader>
|
||||||
|
<CardContent className="mx-auto w-full max-w-md px-0 pt-0">
|
||||||
|
<form onSubmit={submit} className="space-y-4">
|
||||||
|
<div className="space-y-2">
|
||||||
|
<Label htmlFor="username">شناسه کاربری</Label>
|
||||||
|
<Input
|
||||||
|
id="username"
|
||||||
|
type="text"
|
||||||
|
autoComplete="username"
|
||||||
|
value={email}
|
||||||
|
onChange={(e) => setEmail(e.target.value)}
|
||||||
|
required
|
||||||
|
dir="ltr"
|
||||||
|
className="text-left"
|
||||||
|
/>
|
||||||
|
</div>
|
||||||
|
<div className="space-y-2">
|
||||||
|
<Label htmlFor="password">رمز عبور</Label>
|
||||||
|
<PasswordInput
|
||||||
|
id="password"
|
||||||
|
autoComplete="current-password"
|
||||||
|
value={password}
|
||||||
|
onChange={(e) => setPassword(e.target.value)}
|
||||||
|
required
|
||||||
|
placeholder="رمز عبور"
|
||||||
|
/>
|
||||||
|
</div>
|
||||||
|
<div className="space-y-2">
|
||||||
|
<div className="flex items-center justify-between gap-2">
|
||||||
|
<Label htmlFor="captcha">کد امنیتی</Label>
|
||||||
|
<button
|
||||||
|
type="button"
|
||||||
|
onClick={() => void loadCaptcha()}
|
||||||
|
disabled={captchaLoading}
|
||||||
|
className="inline-flex items-center gap-1 text-xs font-medium text-primary underline-offset-4 hover:underline disabled:opacity-50"
|
||||||
|
>
|
||||||
|
<RefreshCw className={`h-3.5 w-3.5 ${captchaLoading ? "animate-spin" : ""}`} />
|
||||||
|
تازهسازی
|
||||||
|
</button>
|
||||||
|
</div>
|
||||||
|
<div className="flex items-stretch gap-3">
|
||||||
|
<div
|
||||||
|
className="relative flex h-14 min-w-[9.5rem] shrink-0 items-center justify-center overflow-hidden rounded-xl border border-border bg-muted/60 shadow-inner"
|
||||||
|
aria-live="polite"
|
||||||
|
>
|
||||||
|
{captchaLoading || !challenge?.imageBase64 ? (
|
||||||
|
<span className="text-sm text-muted-foreground">…</span>
|
||||||
|
) : (
|
||||||
|
// eslint-disable-next-line @next/next/no-img-element
|
||||||
|
<img
|
||||||
|
src={`data:image/png;base64,${challenge.imageBase64}`}
|
||||||
|
alt="کد امنیتی"
|
||||||
|
width={160}
|
||||||
|
height={52}
|
||||||
|
className="h-full w-full object-contain select-none"
|
||||||
|
draggable={false}
|
||||||
|
/>
|
||||||
|
)}
|
||||||
|
</div>
|
||||||
|
<Input
|
||||||
|
id="captcha"
|
||||||
|
type="text"
|
||||||
|
autoComplete="off"
|
||||||
|
autoCapitalize="characters"
|
||||||
|
spellCheck={false}
|
||||||
|
value={captchaAnswer}
|
||||||
|
onChange={(e) => setCaptchaAnswer(e.target.value.toUpperCase())}
|
||||||
|
required
|
||||||
|
dir="ltr"
|
||||||
|
className="h-14 text-center font-mono tracking-widest uppercase placeholder:text-center"
|
||||||
|
placeholder="کد تصویر"
|
||||||
|
maxLength={6}
|
||||||
|
/>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
<label className="flex items-center justify-between gap-3 text-sm">
|
||||||
|
<span>مرا به یاد داشته باش</span>
|
||||||
|
<Switch
|
||||||
|
checked={rememberMe}
|
||||||
|
onCheckedChange={setRememberMe}
|
||||||
|
aria-label="مرا به یاد داشته باش"
|
||||||
|
/>
|
||||||
|
</label>
|
||||||
|
{error && <p className="text-sm text-destructive">{error}</p>}
|
||||||
|
<Button
|
||||||
|
type="submit"
|
||||||
|
variant="gradient"
|
||||||
|
className="h-12 w-full"
|
||||||
|
size="lg"
|
||||||
|
disabled={loading || captchaLoading || !challenge}
|
||||||
|
>
|
||||||
|
{loading ? <Loader2 className="h-4 w-4 animate-spin" /> : <Zap className="h-4 w-4" />} ورود
|
||||||
|
</Button>
|
||||||
|
</form>
|
||||||
|
<p className="mt-6 text-center text-sm text-muted-foreground">
|
||||||
|
{registerStatus?.enabled ? (
|
||||||
|
<>
|
||||||
|
حساب ندارید؟{" "}
|
||||||
|
<Link href="/register" className="font-medium text-primary underline-offset-4 hover:underline">
|
||||||
|
ثبتنام
|
||||||
|
</Link>
|
||||||
|
</>
|
||||||
|
) : (
|
||||||
|
"حساب شما توسط متصدی بوتکمپ ساخته و اعلام میشود."
|
||||||
|
)}
|
||||||
|
</p>
|
||||||
|
</CardContent>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
);
|
||||||
|
}
|
||||||
@@ -0,0 +1,58 @@
|
|||||||
|
"use client";
|
||||||
|
|
||||||
|
import Link from "next/link";
|
||||||
|
import { BrandMark } from "@/components/brand-mark";
|
||||||
|
import { Button } from "@/components/ui/button";
|
||||||
|
import { useAuth, useAuthHydrated } from "@/lib/auth-store";
|
||||||
|
import { Home, LogIn, Trees } from "lucide-react";
|
||||||
|
|
||||||
|
export default function NotFound() {
|
||||||
|
const hydrated = useAuthHydrated();
|
||||||
|
const user = useAuth((s) => s.user);
|
||||||
|
const loggedIn = hydrated && !!user;
|
||||||
|
|
||||||
|
return (
|
||||||
|
<div className="mx-auto flex max-w-lg flex-col items-center px-4 py-16 text-center">
|
||||||
|
<div className="relative w-full overflow-hidden rounded-2xl border-2 border-border bg-card px-8 py-14 shadow-offset">
|
||||||
|
<div className="dot-grid dot-grid-primary pointer-events-none absolute -end-10 -top-10 h-40 w-40 opacity-60" aria-hidden />
|
||||||
|
<p className="text-7xl font-black tabular-nums text-primary/25">۴۰۴</p>
|
||||||
|
<div className="mt-4 flex justify-center">
|
||||||
|
<BrandMark locale="fa" size="lg" />
|
||||||
|
</div>
|
||||||
|
<h1 className="mt-6 text-2xl font-black tracking-tight">این مسیر پیدا نشد</h1>
|
||||||
|
<p className="mt-3 text-sm leading-relaxed text-muted-foreground">
|
||||||
|
{loggedIn
|
||||||
|
? "این آدرس در سامانه نیست. از درخت مهارت یا مرکز ادامه دهید."
|
||||||
|
: "صفحهای که دنبالش بودید پیدا نشد. میتوانید به خانه برگردید یا وارد حساب شوید."}
|
||||||
|
</p>
|
||||||
|
<div className="mt-8 flex flex-wrap items-center justify-center gap-3">
|
||||||
|
{loggedIn ? (
|
||||||
|
<>
|
||||||
|
<Button asChild className="gap-2">
|
||||||
|
<Link href="/cap">
|
||||||
|
<Trees className="h-4 w-4" /> درخت مهارت
|
||||||
|
</Link>
|
||||||
|
</Button>
|
||||||
|
<Button asChild variant="outline" className="gap-2">
|
||||||
|
<Link href="/unwrap?tab=community">مرکز · حمایت</Link>
|
||||||
|
</Button>
|
||||||
|
</>
|
||||||
|
) : (
|
||||||
|
<>
|
||||||
|
<Button asChild className="gap-2">
|
||||||
|
<Link href="/">
|
||||||
|
<Home className="h-4 w-4" /> خانه
|
||||||
|
</Link>
|
||||||
|
</Button>
|
||||||
|
<Button asChild variant="outline" className="gap-2">
|
||||||
|
<Link href="/login">
|
||||||
|
<LogIn className="h-4 w-4" /> ورود
|
||||||
|
</Link>
|
||||||
|
</Button>
|
||||||
|
</>
|
||||||
|
)}
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
);
|
||||||
|
}
|
||||||
@@ -0,0 +1,135 @@
|
|||||||
|
"use client";
|
||||||
|
|
||||||
|
import { useMutation, useQuery, useQueryClient } from "@tanstack/react-query";
|
||||||
|
import { useState } from "react";
|
||||||
|
import { BellRing, Loader2, Save } from "lucide-react";
|
||||||
|
import { http } from "@/lib/api";
|
||||||
|
import type { NotificationPrefs } from "@/lib/types";
|
||||||
|
import { NotificationsPanel } from "@/components/notifications-panel";
|
||||||
|
import { PageHeader } from "@/components/page-header";
|
||||||
|
import { Panel } from "@/components/panel";
|
||||||
|
import { Skeleton } from "@/components/ui/skeleton";
|
||||||
|
import { Button } from "@/components/ui/button";
|
||||||
|
import { Switch } from "@/components/ui/switch";
|
||||||
|
import { Label } from "@/components/ui/label";
|
||||||
|
|
||||||
|
const prefsMeta: { key: keyof NotificationPrefs; title: string; desc: string }[] = [
|
||||||
|
{ key: "progress", title: "پیشرفت و باز شدن دروس", desc: "باز شدن آزمون، تکمیل درس، شاخههای جدید." },
|
||||||
|
{ key: "gamification", title: "بازیسازی", desc: "امتیاز، زنجیرهٔ فعالیت، لیگها و هشدار قلب." },
|
||||||
|
{ key: "mentor", title: "منتور و گفتگو", desc: "پاسخ منتور، پیام همدورهای، تایید رفع قفل." },
|
||||||
|
{ key: "event", title: "رویدادها و اطلاعیهها", desc: "تایید ثبتنام و یادآوری ۱۵ دقیقه قبل از شروع." },
|
||||||
|
];
|
||||||
|
|
||||||
|
export default function NotificationsPage() {
|
||||||
|
const qc = useQueryClient();
|
||||||
|
const { data, isLoading } = useQuery({
|
||||||
|
queryKey: ["prefs"],
|
||||||
|
queryFn: () => http.get<{ prefs: NotificationPrefs }>("/api/notifications/preferences"),
|
||||||
|
});
|
||||||
|
const [draft, setDraft] = useState<NotificationPrefs | null>(null);
|
||||||
|
const [prefs, setPrefs] = useState<{ prefs: NotificationPrefs }>();
|
||||||
|
|
||||||
|
const prefsValue = draft ?? prefs?.prefs ?? data?.prefs;
|
||||||
|
|
||||||
|
const save = useMutation({
|
||||||
|
mutationFn: (p: NotificationPrefs) => http.put<{ prefs: NotificationPrefs }>("/api/notifications/preferences", p),
|
||||||
|
onSuccess: (res) => {
|
||||||
|
setPrefs(res);
|
||||||
|
setDraft(null);
|
||||||
|
qc.invalidateQueries({ queryKey: ["prefs"] });
|
||||||
|
},
|
||||||
|
});
|
||||||
|
|
||||||
|
if (isLoading) {
|
||||||
|
return (
|
||||||
|
<div className="mx-auto max-w-3xl space-y-8">
|
||||||
|
<div className="space-y-2">
|
||||||
|
<Skeleton className="h-3.5 w-32" />
|
||||||
|
<Skeleton className="h-8 w-44" />
|
||||||
|
<Skeleton className="h-4 w-72" />
|
||||||
|
</div>
|
||||||
|
<div className="rounded-2xl border border-border/70 bg-card p-6 shadow-soft">
|
||||||
|
<div className="flex items-center gap-3">
|
||||||
|
<Skeleton className="h-10 w-10 rounded-xl" />
|
||||||
|
<div className="flex-1 space-y-1.5">
|
||||||
|
<Skeleton className="h-4 w-40" />
|
||||||
|
<Skeleton className="h-3 w-64" />
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
<div className="mt-6 space-y-6">
|
||||||
|
{Array.from({ length: 4 }).map((_, i) => (
|
||||||
|
<div key={i} className="flex items-center justify-between gap-4">
|
||||||
|
<div className="flex-1 space-y-1.5">
|
||||||
|
<Skeleton className="h-4 w-48" />
|
||||||
|
<Skeleton className="h-3 w-64" />
|
||||||
|
</div>
|
||||||
|
<Skeleton className="h-6 w-11 rounded-full" />
|
||||||
|
</div>
|
||||||
|
))}
|
||||||
|
<div className="flex justify-end border-t border-border/70 pt-5">
|
||||||
|
<Skeleton className="h-10 w-36 rounded-xl" />
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
<div className="space-y-2">
|
||||||
|
{Array.from({ length: 3 }).map((_, i) => (
|
||||||
|
<Skeleton key={i} className="h-16 rounded-2xl" />
|
||||||
|
))}
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
const toggle = (key: keyof NotificationPrefs) => {
|
||||||
|
if (!prefsValue) return;
|
||||||
|
setDraft({ ...prefsValue, [key]: !prefsValue[key] });
|
||||||
|
};
|
||||||
|
|
||||||
|
const dirty = draft != null;
|
||||||
|
|
||||||
|
return (
|
||||||
|
<div className="mx-auto max-w-3xl space-y-8">
|
||||||
|
<PageHeader
|
||||||
|
kicker="صندوق پیام و تنظیمات"
|
||||||
|
title="اعلانها"
|
||||||
|
description="همهچیز درونبرنامه و بیدرنگ ارسال میشود — نیازی به ایمیل نیست."
|
||||||
|
/>
|
||||||
|
|
||||||
|
<Panel
|
||||||
|
title="دستهبندی اعلانها"
|
||||||
|
description="هر دسته را همانجا بیصدا کنید. تغییرات پس از ذخیره اعمال میشود."
|
||||||
|
icon={<BellRing className="h-5 w-5" />}
|
||||||
|
tint="bg-primary/10 text-primary"
|
||||||
|
>
|
||||||
|
<div className="space-y-6">
|
||||||
|
{prefsValue &&
|
||||||
|
prefsMeta.map((m) => (
|
||||||
|
<div key={m.key} className="flex items-center justify-between gap-4">
|
||||||
|
<div>
|
||||||
|
<Label htmlFor={`pref-${m.key}`} className="font-medium">{m.title}</Label>
|
||||||
|
<p className="text-xs text-muted-foreground">{m.desc}</p>
|
||||||
|
</div>
|
||||||
|
<Switch
|
||||||
|
id={`pref-${m.key}`}
|
||||||
|
checked={!!prefsValue[m.key]}
|
||||||
|
onCheckedChange={() => toggle(m.key)}
|
||||||
|
/>
|
||||||
|
</div>
|
||||||
|
))}
|
||||||
|
<div className="flex justify-end border-t border-border/70 pt-5">
|
||||||
|
<Button
|
||||||
|
className="gap-1.5"
|
||||||
|
disabled={!dirty || save.isPending}
|
||||||
|
onClick={() => draft && save.mutate(draft)}
|
||||||
|
>
|
||||||
|
{save.isPending ? <Loader2 className="h-4 w-4 animate-spin" /> : <Save className="h-4 w-4" />}
|
||||||
|
ذخیره تنظیمات
|
||||||
|
</Button>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
</Panel>
|
||||||
|
|
||||||
|
<NotificationsPanel />
|
||||||
|
</div>
|
||||||
|
);
|
||||||
|
}
|
||||||
@@ -0,0 +1,305 @@
|
|||||||
|
"use client";
|
||||||
|
|
||||||
|
import { useRouter } from "next/navigation";
|
||||||
|
import { useQuery } from "@tanstack/react-query";
|
||||||
|
import {
|
||||||
|
BookOpenCheck,
|
||||||
|
Clock3,
|
||||||
|
Flag,
|
||||||
|
PlayCircle,
|
||||||
|
Sparkles,
|
||||||
|
Timer,
|
||||||
|
UnlockKeyhole,
|
||||||
|
Users2,
|
||||||
|
Zap,
|
||||||
|
ExternalLink,
|
||||||
|
} from "lucide-react";
|
||||||
|
import { useAuth } from "@/lib/auth-store";
|
||||||
|
import { Button } from "@/components/ui/button";
|
||||||
|
import { BrandMark } from "@/components/brand-mark";
|
||||||
|
import { Reveal } from "@/components/reveal";
|
||||||
|
import Link from "next/link";
|
||||||
|
import { http } from "@/lib/api";
|
||||||
|
|
||||||
|
const stats = [
|
||||||
|
{ value: "۱۲", label: "هفته مسیر", tile: "bg-primary text-primary-foreground" },
|
||||||
|
{ value: "۶", label: "درس ویدیویی", tile: "bg-accent text-accent-foreground" },
|
||||||
|
{ value: "۳", label: "فصل مهارتی", tile: "bg-gold text-gold-foreground" },
|
||||||
|
{ value: "۱۸", label: "سوال آزمون", tile: "bg-success text-success-foreground" },
|
||||||
|
];
|
||||||
|
|
||||||
|
const steps = [
|
||||||
|
{
|
||||||
|
icon: PlayCircle,
|
||||||
|
step: "۰۱",
|
||||||
|
title: "تماشای کامل",
|
||||||
|
desc: "ویدیو را همانطور واقعی تماشا کنید؛ زمان، بهراستی تأیید میشود.",
|
||||||
|
tile: "bg-primary text-primary-foreground",
|
||||||
|
},
|
||||||
|
{
|
||||||
|
icon: BookOpenCheck,
|
||||||
|
step: "۰۲",
|
||||||
|
title: "قبولی در آزمون",
|
||||||
|
desc: "آزمون همان درس را باز میکند؛ هر اشتباه یک قلب هزینه دارد.",
|
||||||
|
tile: "bg-accent text-accent-foreground",
|
||||||
|
},
|
||||||
|
{
|
||||||
|
icon: UnlockKeyhole,
|
||||||
|
step: "۰۳",
|
||||||
|
title: "باز شدن شاخهها",
|
||||||
|
desc: "با هر قبولی، شاخههای بعدی درخت مهارت آزاد میشوند.",
|
||||||
|
tile: "bg-gold text-gold-foreground",
|
||||||
|
},
|
||||||
|
];
|
||||||
|
|
||||||
|
const features = [
|
||||||
|
{
|
||||||
|
icon: Timer,
|
||||||
|
title: "تماشای تاییدشده",
|
||||||
|
desc: "زمان تماشا با ضربانهای دورهای راستیآزمایی میشود؛ میانبر و پرش سریع جواب نمیدهد.",
|
||||||
|
tile: "bg-primary/10 text-primary",
|
||||||
|
},
|
||||||
|
{
|
||||||
|
icon: Users2,
|
||||||
|
title: "آزمون با قلبها",
|
||||||
|
desc: "هر پاسخ اشتباه یک قلب کم میکند. با سه اشتباه، حساب قفل میشود — مجبورید واقعاً یاد بگیرید.",
|
||||||
|
tile: "bg-accent/10 text-accent",
|
||||||
|
},
|
||||||
|
{
|
||||||
|
icon: Sparkles,
|
||||||
|
title: "جامعه و منتور",
|
||||||
|
desc: "رویدادهای زنده، لیگ هفتگی و گفتگوی یکبهیک با منتور برای وقتی که به مانع میخورید.",
|
||||||
|
tile: "bg-gold/10 text-gold",
|
||||||
|
},
|
||||||
|
];
|
||||||
|
|
||||||
|
const principles = [
|
||||||
|
"پیشنیازهای واقعی — هر شاخه فقط بعد از قبولی در والدش باز میشود",
|
||||||
|
"بدون میانبر — پرش سریع و چندبرابری، غیرفعال است",
|
||||||
|
"قفل پس از سه اشتباه؛ رفع قفل فقط با بررسی مدیریت",
|
||||||
|
"لیگ هفتگی که هر دوشنبه از نو آغاز میشود",
|
||||||
|
];
|
||||||
|
|
||||||
|
export default function Home() {
|
||||||
|
const router = useRouter();
|
||||||
|
const user = useAuth((s) => s.user);
|
||||||
|
|
||||||
|
const { data: sponsorsData } = useQuery({
|
||||||
|
queryKey: ["sponsors"],
|
||||||
|
queryFn: () => http.get<{ sponsors: { name: string; url?: string; blurb?: string }[] }>("/api/sponsors"),
|
||||||
|
staleTime: 60_000,
|
||||||
|
});
|
||||||
|
const sponsors = sponsorsData?.sponsors ?? [];
|
||||||
|
|
||||||
|
const goCap = () => router.push("/cap");
|
||||||
|
const goLogin = () => router.push("/login");
|
||||||
|
|
||||||
|
return (
|
||||||
|
<div className="mx-auto flex max-w-5xl flex-col items-center">
|
||||||
|
{/* hero */}
|
||||||
|
<section className="relative w-full overflow-hidden rounded-2xl border-2 border-border bg-card px-6 py-16 text-center shadow-offset sm:px-12 sm:py-24">
|
||||||
|
<div className="dot-grid dot-grid-primary pointer-events-none absolute -end-16 -top-16 h-72 w-72 opacity-70" aria-hidden />
|
||||||
|
<span className="pointer-events-none absolute end-8 top-8 hidden h-8 w-8 rotate-12 rounded-lg bg-accent sm:block" aria-hidden />
|
||||||
|
<div className="relative mx-auto flex max-w-2xl flex-col items-center text-center">
|
||||||
|
<div className="reveal reveal-1">
|
||||||
|
<BrandMark size="lg" />
|
||||||
|
</div>
|
||||||
|
<div className="reveal reveal-2 mt-6 flex flex-wrap items-center justify-center gap-2">
|
||||||
|
{["بدون میانبر", "۱۲ هفته", "منتور ۱:۱"].map((c) => (
|
||||||
|
<span key={c} className="chip-outline border-primary text-primary bg-primary/5">
|
||||||
|
{c}
|
||||||
|
</span>
|
||||||
|
))}
|
||||||
|
</div>
|
||||||
|
<p className="section-kicker reveal reveal-3 mt-6 justify-center">بوتکمپ ۱۲ هفتهای دگرگونی</p>
|
||||||
|
<h1 className="reveal reveal-4 mt-4 text-5xl font-black leading-[1.05] tracking-tight sm:text-6xl">
|
||||||
|
با انضباط،{" "}
|
||||||
|
<span className="relative inline-block whitespace-nowrap">
|
||||||
|
<span className="text-primary">متحول</span>
|
||||||
|
<span className="absolute inset-x-0 -bottom-1 h-4 rounded-sm bg-accent/20" aria-hidden />
|
||||||
|
</span>{" "}
|
||||||
|
شو
|
||||||
|
</h1>
|
||||||
|
<p className="reveal reveal-5 mt-6 max-w-xl text-base leading-relaxed text-muted-foreground">
|
||||||
|
پلتفرمی که خودش حرف نمیزند — زمان تماشا، آزمونها و قفلشدن را جدا از قضاوت خودتان کنترل
|
||||||
|
میکند تا یادگیری واقعاً رخ بدهد.
|
||||||
|
</p>
|
||||||
|
<div className="reveal reveal-5 mt-9 flex flex-wrap items-center justify-center gap-3">
|
||||||
|
{user ? (
|
||||||
|
<Button size="lg" onClick={goCap} className="gap-2 px-8">
|
||||||
|
<Zap className="h-5 w-5" /> ادامه مسیر
|
||||||
|
</Button>
|
||||||
|
) : (
|
||||||
|
<>
|
||||||
|
<Button size="lg" onClick={goLogin} className="gap-2 px-8">
|
||||||
|
ورود
|
||||||
|
</Button>
|
||||||
|
<Button size="lg" variant="outline" onClick={goLogin} className="gap-2 px-8">
|
||||||
|
<Zap className="h-5 w-5" /> شروع مسیر
|
||||||
|
</Button>
|
||||||
|
</>
|
||||||
|
)}
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
</section>
|
||||||
|
|
||||||
|
{/* stats strip — solid color blocks */}
|
||||||
|
<section className="mt-8 w-full">
|
||||||
|
<div className="grid grid-cols-2 gap-4 sm:grid-cols-4">
|
||||||
|
{stats.map((s, i) => (
|
||||||
|
<Reveal
|
||||||
|
key={s.label}
|
||||||
|
delay={i * 0.07}
|
||||||
|
className={`${s.tile} flex flex-col items-center justify-center rounded-2xl px-6 py-8 text-center shadow-offset-sm hover-lift`}
|
||||||
|
>
|
||||||
|
<p className="text-4xl font-black tabular-nums">{s.value}</p>
|
||||||
|
<p className="mt-1.5 text-xs font-bold opacity-90">{s.label}</p>
|
||||||
|
</Reveal>
|
||||||
|
))}
|
||||||
|
</div>
|
||||||
|
</section>
|
||||||
|
|
||||||
|
{/* how it works */}
|
||||||
|
<section className="mt-20 w-full">
|
||||||
|
<div className="mx-auto max-w-md space-y-3 text-center">
|
||||||
|
<p className="section-kicker justify-center">چگونه کار میکند</p>
|
||||||
|
<h2 className="text-3xl font-black tracking-tight sm:text-4xl">مسیری که گریز ندارد</h2>
|
||||||
|
<p className="text-sm leading-relaxed text-muted-foreground">
|
||||||
|
بقای شما در بوتکمپ صفر و یک است؛ سیستم نمیپذیرد که فقط «خوب دیدن کردم» بگویید.
|
||||||
|
</p>
|
||||||
|
</div>
|
||||||
|
<div className="mt-10 grid gap-5 md:grid-cols-3">
|
||||||
|
{steps.map((s, i) => (
|
||||||
|
<Reveal key={s.step} delay={i * 0.1} className="group relative flex flex-col rounded-2xl border-2 border-border bg-card p-6 shadow-offset-sm hover-lift">
|
||||||
|
<div className="flex items-center justify-between">
|
||||||
|
<span className={`flex h-12 w-12 items-center justify-center rounded-2xl ${s.tile} shadow-offset-sm`}>
|
||||||
|
<s.icon className="h-6 w-6" />
|
||||||
|
</span>
|
||||||
|
<span className="text-3xl font-black tabular-nums text-muted-foreground/30">{s.step}</span>
|
||||||
|
</div>
|
||||||
|
<h3 className="mt-5 text-lg font-extrabold">{s.title}</h3>
|
||||||
|
<p className="mt-2 text-sm leading-relaxed text-muted-foreground">{s.desc}</p>
|
||||||
|
</Reveal>
|
||||||
|
))}
|
||||||
|
</div>
|
||||||
|
</section>
|
||||||
|
|
||||||
|
{/* features */}
|
||||||
|
<section className="mt-20 w-full">
|
||||||
|
<h2 className="text-center text-3xl font-black tracking-tight sm:text-4xl">
|
||||||
|
چرا منحصربهفرد <span className="text-accent">است</span>
|
||||||
|
</h2>
|
||||||
|
<div className="mt-10 grid gap-5 md:grid-cols-3">
|
||||||
|
{features.map((f, i) => (
|
||||||
|
<Reveal key={f.title} delay={i * 0.1} className="card-hover rounded-2xl border-2 border-border bg-card p-6">
|
||||||
|
<span className={`flex h-12 w-12 items-center justify-center rounded-2xl ${f.tile}`}>
|
||||||
|
<f.icon className="h-6 w-6" />
|
||||||
|
</span>
|
||||||
|
<h3 className="mt-5 text-lg font-extrabold">{f.title}</h3>
|
||||||
|
<p className="mt-2 text-sm leading-relaxed text-muted-foreground">{f.desc}</p>
|
||||||
|
</Reveal>
|
||||||
|
))}
|
||||||
|
</div>
|
||||||
|
</section>
|
||||||
|
|
||||||
|
{/* principles — inverted editorial band */}
|
||||||
|
<section className="band-invert mt-20 w-full rounded-2xl p-8 sm:p-12">
|
||||||
|
<div className="flex flex-col gap-8 lg:flex-row lg:items-start lg:justify-between">
|
||||||
|
<div className="lg:sticky lg:top-24 lg:max-w-xs">
|
||||||
|
<p className="section-kicker text-accent">
|
||||||
|
<span className="text-accent">اصول غیرقابل مذاکره</span>
|
||||||
|
</p>
|
||||||
|
<h2 className="mt-3 text-3xl font-black leading-tight sm:text-4xl">
|
||||||
|
مهم نیست قول
|
||||||
|
<br />
|
||||||
|
بدهید؛ سیستم
|
||||||
|
<br />
|
||||||
|
<span className="text-accent">ثبت میکند.</span>
|
||||||
|
</h2>
|
||||||
|
</div>
|
||||||
|
<div className="grid gap-4 sm:grid-cols-2 lg:flex-1">
|
||||||
|
{principles.map((p, i) => (
|
||||||
|
<Reveal key={p} delay={i * 0.08} className="flex items-start gap-3 rounded-2xl border-2 border-border/60 p-5">
|
||||||
|
<span className="mt-0.5 flex h-7 w-7 shrink-0 items-center justify-center rounded-xl bg-success/20">
|
||||||
|
<Flag className="h-4 w-4 text-success" />
|
||||||
|
</span>
|
||||||
|
<p className="text-sm font-medium leading-relaxed opacity-90">{p}</p>
|
||||||
|
</Reveal>
|
||||||
|
))}
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
</section>
|
||||||
|
|
||||||
|
{sponsors.length > 0 && (
|
||||||
|
<section className="mt-20 w-full">
|
||||||
|
<div className="mx-auto max-w-md space-y-3 text-center">
|
||||||
|
<p className="section-kicker justify-center">حامیان</p>
|
||||||
|
<h2 className="text-3xl font-black tracking-tight sm:text-4xl">اسپانسرهای پرگار</h2>
|
||||||
|
<p className="text-sm leading-relaxed text-muted-foreground">
|
||||||
|
سازمانها و افرادی که مسیر یادگیری را ممکن میکنند.
|
||||||
|
</p>
|
||||||
|
</div>
|
||||||
|
<div className="mt-10 grid gap-4 sm:grid-cols-2 lg:grid-cols-3">
|
||||||
|
{sponsors.map((sp, i) => {
|
||||||
|
const inner = (
|
||||||
|
<Reveal
|
||||||
|
delay={i * 0.08}
|
||||||
|
className="flex h-full flex-col rounded-2xl border-2 border-border bg-card p-6 shadow-offset-sm transition hover-lift"
|
||||||
|
>
|
||||||
|
<p className="text-lg font-extrabold">{sp.name}</p>
|
||||||
|
{sp.blurb && (
|
||||||
|
<p className="mt-2 flex-1 text-sm leading-relaxed text-muted-foreground">{sp.blurb}</p>
|
||||||
|
)}
|
||||||
|
{sp.url && (
|
||||||
|
<span className="mt-4 inline-flex items-center gap-1 text-xs font-bold text-primary">
|
||||||
|
مشاهده <ExternalLink className="h-3.5 w-3.5" />
|
||||||
|
</span>
|
||||||
|
)}
|
||||||
|
</Reveal>
|
||||||
|
);
|
||||||
|
return sp.url ? (
|
||||||
|
<a key={`${sp.name}-${i}`} href={sp.url} target="_blank" rel="noopener noreferrer" className="block">
|
||||||
|
{inner}
|
||||||
|
</a>
|
||||||
|
) : (
|
||||||
|
<div key={`${sp.name}-${i}`}>{inner}</div>
|
||||||
|
);
|
||||||
|
})}
|
||||||
|
</div>
|
||||||
|
</section>
|
||||||
|
)}
|
||||||
|
|
||||||
|
{/* final CTA */}
|
||||||
|
<section className="mt-20 w-full pb-4 text-center">
|
||||||
|
<Reveal>
|
||||||
|
<span className="mx-auto flex h-14 w-14 items-center justify-center rounded-2xl bg-accent/10 shadow-offset-sm float-slow">
|
||||||
|
<Clock3 className="h-7 w-7 text-accent" />
|
||||||
|
</span>
|
||||||
|
<h2 className="mt-5 text-3xl font-black tracking-tight sm:text-4xl">آماده آغازید؟</h2>
|
||||||
|
<p className="mt-3 text-base text-muted-foreground">۱۲ هفته اثر — و سیستم کنترل را خودش بر عهده میگیرد.</p>
|
||||||
|
<div className="mt-8 flex flex-wrap items-center justify-center gap-3">
|
||||||
|
{user ? (
|
||||||
|
<Button size="lg" onClick={goCap} className="gap-2 px-8">
|
||||||
|
<PlayCircle className="h-5 w-5" /> ادامه مسیر
|
||||||
|
</Button>
|
||||||
|
) : (
|
||||||
|
<>
|
||||||
|
<Button size="lg" asChild className="gap-2 px-8">
|
||||||
|
<Link href="/login">ورود</Link>
|
||||||
|
</Button>
|
||||||
|
<Button size="lg" variant="outline" asChild className="gap-2 px-8">
|
||||||
|
<Link href="/login">
|
||||||
|
<PlayCircle className="h-5 w-5" /> شروع مسیر
|
||||||
|
</Link>
|
||||||
|
</Button>
|
||||||
|
</>
|
||||||
|
)}
|
||||||
|
</div>
|
||||||
|
<p className="mt-10 text-xs text-muted-foreground">
|
||||||
|
<BrandMark locale="fa" size="sm" className="align-middle" /> — نسخهٔ نمایشی · توسعهیافته توسط امیرحسین پناهیفر
|
||||||
|
</p>
|
||||||
|
</Reveal>
|
||||||
|
</section>
|
||||||
|
</div>
|
||||||
|
);
|
||||||
|
}
|
||||||
@@ -0,0 +1,200 @@
|
|||||||
|
"use client";
|
||||||
|
|
||||||
|
import Link from "next/link";
|
||||||
|
import { useParams, useRouter } from "next/navigation";
|
||||||
|
import { useEffect } from "react";
|
||||||
|
import { useQuery } from "@tanstack/react-query";
|
||||||
|
import { ArrowRight, Lock, TreePine } from "lucide-react";
|
||||||
|
import { VideoPlayer } from "@/components/video-player";
|
||||||
|
import { ApiError, http, toUserError } from "@/lib/api";
|
||||||
|
import type { Lesson, LessonProgress } from "@/lib/types";
|
||||||
|
import { Button } from "@/components/ui/button";
|
||||||
|
import { Badge } from "@/components/ui/badge";
|
||||||
|
import { Skeleton } from "@/components/ui/skeleton";
|
||||||
|
import { useAuth } from "@/lib/auth-store";
|
||||||
|
import { formatFaNumber } from "@/lib/utils";
|
||||||
|
import { hasInfiniteHearts } from "@/lib/hearts";
|
||||||
|
|
||||||
|
function isLessonLockedError(error: unknown): boolean {
|
||||||
|
if (!(error instanceof ApiError)) return false;
|
||||||
|
if (error.status !== 403) return false;
|
||||||
|
return error.message.includes("قفل");
|
||||||
|
}
|
||||||
|
|
||||||
|
export default function PlayerPage() {
|
||||||
|
const { lessonId } = useParams<{ lessonId: string }>();
|
||||||
|
const id = Number(lessonId);
|
||||||
|
const router = useRouter();
|
||||||
|
const user = useAuth((s) => s.user);
|
||||||
|
|
||||||
|
const { data, isLoading, isError, error, refetch } = useQuery({
|
||||||
|
queryKey: ["lesson", id],
|
||||||
|
queryFn: () =>
|
||||||
|
http.get<{
|
||||||
|
lesson: Lesson;
|
||||||
|
videoUrl: string;
|
||||||
|
videoIsSample?: boolean;
|
||||||
|
progress: LessonProgress | null;
|
||||||
|
quizStatus: string;
|
||||||
|
}>(`/api/lessons/${id}`),
|
||||||
|
enabled: !!user && (!user.isLocked || hasInfiniteHearts(user.role)),
|
||||||
|
staleTime: 5 * 60_000,
|
||||||
|
retry: (count, err) => {
|
||||||
|
if (isLessonLockedError(err)) return false;
|
||||||
|
return count < 2;
|
||||||
|
},
|
||||||
|
});
|
||||||
|
|
||||||
|
useEffect(() => {
|
||||||
|
if (user?.isLocked && !hasInfiniteHearts(user.role)) router.replace("/lockout");
|
||||||
|
}, [user?.isLocked, user?.role, router]);
|
||||||
|
|
||||||
|
if (user?.isLocked && !hasInfiniteHearts(user.role)) {
|
||||||
|
return null;
|
||||||
|
}
|
||||||
|
|
||||||
|
if (isLoading) {
|
||||||
|
return (
|
||||||
|
<div className="mx-auto max-w-4xl space-y-6">
|
||||||
|
<div className="flex flex-wrap items-center justify-between gap-4">
|
||||||
|
<div className="flex items-center gap-3">
|
||||||
|
<Skeleton className="h-10 w-10 rounded-xl" />
|
||||||
|
<div className="space-y-1.5">
|
||||||
|
<Skeleton className="h-6 w-64" />
|
||||||
|
<Skeleton className="h-4 w-48" />
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
<Skeleton className="h-8 w-28 rounded-full" />
|
||||||
|
</div>
|
||||||
|
<Skeleton className="aspect-video w-full rounded-2xl" />
|
||||||
|
<div className="flex items-center justify-between gap-4">
|
||||||
|
<Skeleton className="h-4 w-72" />
|
||||||
|
<Skeleton className="h-10 w-32 rounded-xl" />
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
if (isError || !data) {
|
||||||
|
if (isLessonLockedError(error)) {
|
||||||
|
return <LockedLessonState onBack={() => router.push("/cap")} />;
|
||||||
|
}
|
||||||
|
return (
|
||||||
|
<div className="mx-auto max-w-lg space-y-4 py-16 text-center">
|
||||||
|
<p className="font-medium text-destructive">{toUserError(error, "بارگذاری درس ممکن نشد")}</p>
|
||||||
|
<div className="flex justify-center gap-2">
|
||||||
|
<Button variant="outline" onClick={() => router.push("/cap")}>
|
||||||
|
بازگشت به درخت
|
||||||
|
</Button>
|
||||||
|
<Button onClick={() => refetch()}>تلاش دوباره</Button>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
const { lesson, videoUrl, videoIsSample, progress, quizStatus } = data;
|
||||||
|
const passed = !!progress?.passedQuiz;
|
||||||
|
|
||||||
|
return (
|
||||||
|
<div className="mx-auto max-w-4xl space-y-6">
|
||||||
|
<div className="flex flex-wrap items-center justify-between gap-4">
|
||||||
|
<div className="flex items-center gap-3">
|
||||||
|
<Button variant="outline" size="icon" onClick={() => router.push("/cap")} aria-label="بازگشت به درخت مهارت">
|
||||||
|
<ArrowRight className="h-4 w-4" />
|
||||||
|
</Button>
|
||||||
|
<div>
|
||||||
|
<h1 className="text-2xl font-bold tracking-tight">{lesson.title}</h1>
|
||||||
|
<p className="text-sm text-muted-foreground">{lesson.description}</p>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
<div className="flex items-center gap-2">
|
||||||
|
{videoIsSample && (
|
||||||
|
<Badge variant="outline" className="px-3 py-1 text-muted-foreground">
|
||||||
|
نمونهٔ موقت
|
||||||
|
</Badge>
|
||||||
|
)}
|
||||||
|
{passed ? (
|
||||||
|
<Badge variant="success" className="px-3 py-1">تکمیل شده</Badge>
|
||||||
|
) : (
|
||||||
|
<Badge variant="secondary" className="px-3 py-1">{formatFaNumber(lesson.xpReward)} امتیاز پاداش</Badge>
|
||||||
|
)}
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
|
||||||
|
{videoUrl ? (
|
||||||
|
<div className="space-y-2">
|
||||||
|
<VideoPlayer
|
||||||
|
lessonId={id}
|
||||||
|
videoUrl={videoUrl}
|
||||||
|
duration={lesson.durationSeconds}
|
||||||
|
completionThresholdPct={lesson.completionThresholdPct}
|
||||||
|
initialProgress={progress}
|
||||||
|
/>
|
||||||
|
{videoIsSample && (
|
||||||
|
<p className="text-center text-xs text-muted-foreground">
|
||||||
|
ویدیوی اختصاصی هنوز وصل نشده — <span className="font-bold">sample.mp4</span> بهعنوان حداقل پخش
|
||||||
|
نمایش داده میشود تا پلیر خالی نماند.
|
||||||
|
</p>
|
||||||
|
)}
|
||||||
|
</div>
|
||||||
|
) : (
|
||||||
|
<div className="rounded-xl border border-dashed border-border p-10 text-center text-muted-foreground">
|
||||||
|
این درس هنوز ویدیو ندارد.
|
||||||
|
</div>
|
||||||
|
)}
|
||||||
|
|
||||||
|
<div className="flex items-center justify-between gap-4 text-sm">
|
||||||
|
<div className="flex items-center gap-2 text-muted-foreground">
|
||||||
|
<Lock className="h-4 w-4" />
|
||||||
|
آزمون با {`≥${lesson.completionThresholdPct}`}٪ زمان تماشای تاییدشده باز میشود.
|
||||||
|
{quizStatus === "failed" && (
|
||||||
|
<span className="text-destructive">تلاش قبلی ناموفق بود — هر وقت آماده بودید دوباره تلاش کنید.</span>
|
||||||
|
)}
|
||||||
|
</div>
|
||||||
|
{passed && (
|
||||||
|
<Button asChild variant="gradient">
|
||||||
|
<Link href="/cap">ادامه مسیر</Link>
|
||||||
|
</Button>
|
||||||
|
)}
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
function LockedLessonState({ onBack }: { onBack: () => void }) {
|
||||||
|
return (
|
||||||
|
<div className="mx-auto flex max-w-lg flex-col items-center px-2 py-10 text-center sm:py-16">
|
||||||
|
<div className="relative mb-6">
|
||||||
|
<div
|
||||||
|
aria-hidden
|
||||||
|
className="absolute inset-0 -m-6 rounded-full bg-muted/80 blur-2xl"
|
||||||
|
/>
|
||||||
|
<div className="relative grid h-20 w-20 place-items-center rounded-3xl border-2 border-border bg-card shadow-offset-sm">
|
||||||
|
<Lock className="h-9 w-9 text-muted-foreground" strokeWidth={1.75} />
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
|
||||||
|
<p className="text-[11px] font-extrabold tracking-wider text-muted-foreground">پیشنیاز باز نشده</p>
|
||||||
|
<h1 className="mt-2 text-2xl font-black tracking-tight sm:text-3xl">این درس هنوز قفل است</h1>
|
||||||
|
<p className="mt-3 max-w-sm text-sm leading-relaxed text-muted-foreground">
|
||||||
|
اول درس قبلی را کامل تماشا کنید و در آزمونش قبول شوید؛ بعد این شاخه خودش باز میشود.
|
||||||
|
</p>
|
||||||
|
|
||||||
|
<div className="mt-8 flex w-full max-w-xs flex-col gap-2.5">
|
||||||
|
<Button size="lg" onClick={onBack} className="gap-2">
|
||||||
|
<TreePine className="h-4 w-4" />
|
||||||
|
بازگشت به درخت مهارت
|
||||||
|
</Button>
|
||||||
|
<Button
|
||||||
|
size="lg"
|
||||||
|
variant="outline"
|
||||||
|
onClick={() =>
|
||||||
|
window.dispatchEvent(new CustomEvent("pargar:chat", { detail: { open: true } }))
|
||||||
|
}
|
||||||
|
>
|
||||||
|
پرسیدن از منتور
|
||||||
|
</Button>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
);
|
||||||
|
}
|
||||||
@@ -0,0 +1,171 @@
|
|||||||
|
"use client";
|
||||||
|
|
||||||
|
import Link from "next/link";
|
||||||
|
import { useQuery } from "@tanstack/react-query";
|
||||||
|
import { Flame, Heart, Sparkles, Trophy, User as UserIcon } from "lucide-react";
|
||||||
|
import { useAuth } from "@/lib/auth-store";
|
||||||
|
import { http, toUserError } from "@/lib/api";
|
||||||
|
import type { LeaderboardData } from "@/lib/types";
|
||||||
|
import { Panel } from "@/components/panel";
|
||||||
|
import { Card, CardContent } from "@/components/ui/card";
|
||||||
|
import { Button } from "@/components/ui/button";
|
||||||
|
import { Skeleton } from "@/components/ui/skeleton";
|
||||||
|
import { UserAvatar, avatarPropsOf } from "@/components/ui/user-avatar";
|
||||||
|
import { ProfileCertificateSlot } from "@/components/profile-certificate-slot";
|
||||||
|
import { ChallengeCards } from "@/components/challenge-cards";
|
||||||
|
import { AvatarStudio } from "@/components/avatar-studio";
|
||||||
|
import {
|
||||||
|
Dialog,
|
||||||
|
DialogContent,
|
||||||
|
DialogHeader,
|
||||||
|
DialogTitle,
|
||||||
|
} from "@/components/ui/dialog";
|
||||||
|
import { formatFaNumber, formatStreakLabel } from "@/lib/utils";
|
||||||
|
import { useState } from "react";
|
||||||
|
|
||||||
|
export default function ProfilePage() {
|
||||||
|
const user = useAuth((s) => s.user);
|
||||||
|
const [studioOpen, setStudioOpen] = useState(false);
|
||||||
|
const { data: lb, isError: lbError, error: lbErr } = useQuery({
|
||||||
|
queryKey: ["leaderboard"],
|
||||||
|
queryFn: () => http.get<LeaderboardData>("/api/leaderboard/weekly"),
|
||||||
|
enabled: !!user,
|
||||||
|
});
|
||||||
|
|
||||||
|
if (!user) {
|
||||||
|
return (
|
||||||
|
<div className="mx-auto max-w-2xl py-16 text-center">
|
||||||
|
<p className="text-muted-foreground">برای مشاهدهٔ پروفایل وارد شوید.</p>
|
||||||
|
<Button asChild className="mt-4">
|
||||||
|
<Link href="/login">ورود</Link>
|
||||||
|
</Button>
|
||||||
|
</div>
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
return (
|
||||||
|
<div className="mx-auto max-w-2xl space-y-6">
|
||||||
|
<Panel
|
||||||
|
title="پروفایل من"
|
||||||
|
description="هویت، آمار یادگیری، چالشها و گواهینامه در یک نگاه."
|
||||||
|
icon={<UserIcon className="h-5 w-5" />}
|
||||||
|
tint="bg-primary/10 text-primary"
|
||||||
|
actions={
|
||||||
|
<Button variant="outline" size="sm" onClick={() => setStudioOpen(true)}>
|
||||||
|
ویرایش آواتار
|
||||||
|
</Button>
|
||||||
|
}
|
||||||
|
>
|
||||||
|
<div className="flex flex-col items-center gap-4 sm:flex-row sm:items-start">
|
||||||
|
<UserAvatar name={user.name} className="h-20 w-20" {...avatarPropsOf(user)} />
|
||||||
|
<div className="min-w-0 flex-1 space-y-2 text-center sm:text-start">
|
||||||
|
<h1 className="text-2xl font-black tracking-tight">{user.name}</h1>
|
||||||
|
<dl className="mt-1 space-y-2 text-sm">
|
||||||
|
<div className="flex items-baseline justify-between gap-3">
|
||||||
|
<dt className="shrink-0 text-xs text-muted-foreground">نام کاربری</dt>
|
||||||
|
<dd className="min-w-0 font-latin font-bold tracking-tight" dir="ltr">
|
||||||
|
@{user.username}
|
||||||
|
</dd>
|
||||||
|
</div>
|
||||||
|
<div className="flex items-baseline justify-between gap-3">
|
||||||
|
<dt className="shrink-0 text-xs text-muted-foreground">ایمیل</dt>
|
||||||
|
<dd className="min-w-0 break-all font-latin font-medium" dir="ltr">
|
||||||
|
{user.email}
|
||||||
|
</dd>
|
||||||
|
</div>
|
||||||
|
{user.phone && (
|
||||||
|
<div className="flex items-baseline justify-between gap-3">
|
||||||
|
<dt className="shrink-0 text-xs text-muted-foreground">تلفن</dt>
|
||||||
|
<dd className="min-w-0 font-latin font-medium" dir="ltr">
|
||||||
|
{user.phone}
|
||||||
|
</dd>
|
||||||
|
</div>
|
||||||
|
)}
|
||||||
|
<div className="flex items-baseline justify-between gap-3">
|
||||||
|
<dt className="shrink-0 text-xs text-muted-foreground">عضویت از</dt>
|
||||||
|
<dd className="min-w-0 font-medium">
|
||||||
|
{new Date(user.createdAt).toLocaleDateString("fa-IR", {
|
||||||
|
year: "numeric",
|
||||||
|
month: "long",
|
||||||
|
day: "numeric",
|
||||||
|
})}
|
||||||
|
</dd>
|
||||||
|
</div>
|
||||||
|
</dl>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
</Panel>
|
||||||
|
|
||||||
|
<div className="grid gap-3 sm:grid-cols-2">
|
||||||
|
<StatCard icon={<Sparkles className="h-4 w-4 text-gold" />} label="امتیاز کل" value={formatFaNumber(user.xp)} />
|
||||||
|
<StatCard icon={<Heart className="h-4 w-4 text-destructive" />} label="قلبها" value={formatFaNumber(user.hearts)} />
|
||||||
|
<StatCard
|
||||||
|
icon={<Flame className="h-4 w-4 text-accent" />}
|
||||||
|
label="زنجیرهٔ فعلی"
|
||||||
|
value={formatStreakLabel(user.streakCurrent)}
|
||||||
|
/>
|
||||||
|
<StatCard
|
||||||
|
icon={<Flame className="h-4 w-4 text-muted-foreground" />}
|
||||||
|
label="بلندترین زنجیره"
|
||||||
|
value={formatStreakLabel(user.streakLongest)}
|
||||||
|
/>
|
||||||
|
</div>
|
||||||
|
|
||||||
|
<Card>
|
||||||
|
<CardContent className="flex items-center gap-3 p-4">
|
||||||
|
<Trophy className="h-5 w-5 text-gold" />
|
||||||
|
<div className="flex-1">
|
||||||
|
<p className="text-sm font-bold">رتبهٔ لیگ این هفته</p>
|
||||||
|
{lbError ? (
|
||||||
|
<p className="text-xs text-destructive">{toUserError(lbErr)}</p>
|
||||||
|
) : lb?.me && lb.me.rank > 0 ? (
|
||||||
|
<p className="text-xs text-muted-foreground">
|
||||||
|
رتبه {formatFaNumber(lb.me.rank)} با {formatFaNumber(Math.round(lb.me.xp))} امتیاز هفتگی
|
||||||
|
</p>
|
||||||
|
) : lb ? (
|
||||||
|
<p className="text-xs text-muted-foreground">هنوز در رتبهبندی این هفته نیستید</p>
|
||||||
|
) : (
|
||||||
|
<Skeleton className="mt-1 h-3 w-40" />
|
||||||
|
)}
|
||||||
|
</div>
|
||||||
|
<Button asChild size="sm" variant="outline">
|
||||||
|
<Link href="/leaderboard">لیگها</Link>
|
||||||
|
</Button>
|
||||||
|
</CardContent>
|
||||||
|
</Card>
|
||||||
|
|
||||||
|
<div>
|
||||||
|
<h2 className="mb-2 text-sm font-black text-muted-foreground">چالشهای فعال</h2>
|
||||||
|
<ChallengeCards />
|
||||||
|
</div>
|
||||||
|
|
||||||
|
<div>
|
||||||
|
<h2 className="mb-2 text-sm font-black text-muted-foreground">گواهینامه</h2>
|
||||||
|
<ProfileCertificateSlot />
|
||||||
|
</div>
|
||||||
|
|
||||||
|
<Dialog open={studioOpen} onOpenChange={setStudioOpen}>
|
||||||
|
<DialogContent className="max-w-lg">
|
||||||
|
<DialogHeader>
|
||||||
|
<DialogTitle className="text-center">ویرایش آواتار</DialogTitle>
|
||||||
|
</DialogHeader>
|
||||||
|
<AvatarStudio user={user} onClose={() => setStudioOpen(false)} />
|
||||||
|
</DialogContent>
|
||||||
|
</Dialog>
|
||||||
|
</div>
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
function StatCard({ icon, label, value }: { icon: React.ReactNode; label: string; value: string }) {
|
||||||
|
return (
|
||||||
|
<Card>
|
||||||
|
<CardContent className="flex items-center gap-3 p-4">
|
||||||
|
<div className="grid h-9 w-9 place-items-center rounded-lg bg-muted">{icon}</div>
|
||||||
|
<div>
|
||||||
|
<p className="text-xs text-muted-foreground">{label}</p>
|
||||||
|
<p className="text-lg font-black tabular-nums">{value}</p>
|
||||||
|
</div>
|
||||||
|
</CardContent>
|
||||||
|
</Card>
|
||||||
|
);
|
||||||
|
}
|
||||||
@@ -0,0 +1,30 @@
|
|||||||
|
"use client";
|
||||||
|
|
||||||
|
import { useEffect } from "react";
|
||||||
|
import { useParams, useRouter } from "next/navigation";
|
||||||
|
import { useAuth } from "@/lib/auth-store";
|
||||||
|
import { hasInfiniteHearts } from "@/lib/hearts";
|
||||||
|
import { QuizExperience } from "@/components/quiz-experience";
|
||||||
|
|
||||||
|
export default function QuizPage() {
|
||||||
|
const { lessonId } = useParams<{ lessonId: string }>();
|
||||||
|
const id = Number(lessonId);
|
||||||
|
const router = useRouter();
|
||||||
|
const user = useAuth((s) => s.user);
|
||||||
|
|
||||||
|
useEffect(() => {
|
||||||
|
if (user?.isLocked && !hasInfiniteHearts(user.role)) {
|
||||||
|
router.replace("/lockout");
|
||||||
|
}
|
||||||
|
}, [user?.isLocked, user?.role, router]);
|
||||||
|
|
||||||
|
if (user?.isLocked && !hasInfiniteHearts(user.role)) {
|
||||||
|
return null;
|
||||||
|
}
|
||||||
|
|
||||||
|
return (
|
||||||
|
<div className="pt-2">
|
||||||
|
<QuizExperience lessonId={id} />
|
||||||
|
</div>
|
||||||
|
);
|
||||||
|
}
|
||||||
@@ -0,0 +1,6 @@
|
|||||||
|
import { redirect } from "next/navigation";
|
||||||
|
|
||||||
|
/** Self-service password recovery is disabled for students. */
|
||||||
|
export default function RecoveryPage() {
|
||||||
|
redirect("/login");
|
||||||
|
}
|
||||||
@@ -0,0 +1,111 @@
|
|||||||
|
"use client";
|
||||||
|
|
||||||
|
import Link from "next/link";
|
||||||
|
import { useParams } from "next/navigation";
|
||||||
|
import { useQuery } from "@tanstack/react-query";
|
||||||
|
import { Loader2, Lock, Ticket } from "lucide-react";
|
||||||
|
import { BrandMark } from "@/components/brand-mark";
|
||||||
|
import { RegisterForm } from "@/components/register-form";
|
||||||
|
import { http, ApiError } from "@/lib/api";
|
||||||
|
import { Button } from "@/components/ui/button";
|
||||||
|
import { CardContent, CardDescription, CardHeader, CardTitle } from "@/components/ui/card";
|
||||||
|
|
||||||
|
type InviteStatus = {
|
||||||
|
valid: boolean;
|
||||||
|
label?: string;
|
||||||
|
};
|
||||||
|
|
||||||
|
export default function InviteRegisterPage() {
|
||||||
|
const params = useParams<{ token: string }>();
|
||||||
|
const token = params?.token ?? "";
|
||||||
|
|
||||||
|
const { data: invite, isLoading, error, isError } = useQuery({
|
||||||
|
queryKey: ["auth", "register-invite", token],
|
||||||
|
queryFn: () => http.get<InviteStatus>(`/api/auth/register-invite/${encodeURIComponent(token)}`),
|
||||||
|
enabled: !!token,
|
||||||
|
retry: false,
|
||||||
|
meta: { silentError: true },
|
||||||
|
});
|
||||||
|
|
||||||
|
const closedMessage = (() => {
|
||||||
|
if (!isError) return null;
|
||||||
|
if (error instanceof ApiError) return error.message;
|
||||||
|
return "این لینک عضویت قابل استفاده نیست.";
|
||||||
|
})();
|
||||||
|
|
||||||
|
if (!token || isLoading) {
|
||||||
|
return (
|
||||||
|
<div className="flex min-h-[60vh] items-center justify-center">
|
||||||
|
<Loader2 className="h-6 w-6 animate-spin text-muted-foreground" />
|
||||||
|
</div>
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
if (closedMessage || !invite?.valid) {
|
||||||
|
return (
|
||||||
|
<div className="mx-auto flex min-h-[70vh] max-w-md flex-col justify-center px-4">
|
||||||
|
<div className="rounded-2xl border border-border bg-card p-8 text-center shadow-soft">
|
||||||
|
<div className="mx-auto mb-4 flex h-12 w-12 items-center justify-center rounded-xl bg-muted">
|
||||||
|
<Lock className="h-5 w-5 text-muted-foreground" />
|
||||||
|
</div>
|
||||||
|
<BrandMark locale="fa" size="lg" logoOnly className="mx-auto mb-4" />
|
||||||
|
<h1 className="text-xl font-bold">لینک عضویت بسته است</h1>
|
||||||
|
<p className="mt-2 text-sm leading-relaxed text-muted-foreground">
|
||||||
|
{closedMessage ?? "این لینک عضویت قابل استفاده نیست."}
|
||||||
|
</p>
|
||||||
|
<Button asChild className="mt-6 w-full" variant="gradient">
|
||||||
|
<Link href="/login">ورود به حساب</Link>
|
||||||
|
</Button>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
return (
|
||||||
|
<div className="mx-auto flex min-h-[80vh] max-w-4xl flex-col justify-center py-8">
|
||||||
|
<div className="grid overflow-hidden rounded-2xl border border-border bg-card shadow-soft md:grid-cols-2">
|
||||||
|
<aside className="relative hidden flex-col justify-between overflow-hidden bg-primary p-8 text-primary-foreground md:flex">
|
||||||
|
<div
|
||||||
|
className="dot-grid pointer-events-none absolute -end-20 -top-20 h-72 w-72 rotate-12 text-primary-foreground opacity-50"
|
||||||
|
aria-hidden
|
||||||
|
/>
|
||||||
|
<div className="relative">
|
||||||
|
<BrandMark locale="fa" size="lg" className="text-primary-foreground [&_span]:text-accent" />
|
||||||
|
<p className="section-kicker on-primary mt-6">عضویت با دعوت</p>
|
||||||
|
<h2 className="mt-4 text-2xl font-bold leading-snug">
|
||||||
|
{invite.label || "لینک اختصاصی"}
|
||||||
|
</h2>
|
||||||
|
<p className="mt-3 text-sm leading-relaxed text-primary-foreground/80">
|
||||||
|
با این دعوت میتوانید حساب عضویت بسازید.
|
||||||
|
</p>
|
||||||
|
<p className="mt-2 text-sm leading-relaxed text-primary-foreground/70">
|
||||||
|
شماره تلفن و شبکه شما فقط یکبار برای ثبتنام قابل استفادهاند.
|
||||||
|
</p>
|
||||||
|
</div>
|
||||||
|
<p className="relative flex items-center gap-2 text-xs text-primary-foreground/70">
|
||||||
|
<Ticket className="h-3.5 w-3.5" />
|
||||||
|
پس از ثبتنام، پیامک را خودتان برای تیم ارسال کنید؛ سامانه پیامک خودکار ندارد.
|
||||||
|
</p>
|
||||||
|
</aside>
|
||||||
|
|
||||||
|
<div className="bg-card p-8 sm:p-10">
|
||||||
|
<CardHeader className="items-center px-0 pb-4 pt-0 text-center">
|
||||||
|
<div className="mb-2 flex justify-center md:hidden">
|
||||||
|
<BrandMark locale="fa" size="lg" logoOnly />
|
||||||
|
</div>
|
||||||
|
<CardTitle className="text-2xl">ساخت حساب با دعوت</CardTitle>
|
||||||
|
<CardDescription>
|
||||||
|
{invite.label ? invite.label : "فرم ثبتنام با لینک دعوت"}
|
||||||
|
</CardDescription>
|
||||||
|
</CardHeader>
|
||||||
|
<CardContent className="px-0 pt-0">
|
||||||
|
<RegisterForm
|
||||||
|
endpoint={`/api/auth/register-invite/${encodeURIComponent(token)}`}
|
||||||
|
submitLabel="ثبتنام با دعوت"
|
||||||
|
/>
|
||||||
|
</CardContent>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
);
|
||||||
|
}
|
||||||
@@ -0,0 +1,87 @@
|
|||||||
|
"use client";
|
||||||
|
|
||||||
|
import Link from "next/link";
|
||||||
|
import { useQuery } from "@tanstack/react-query";
|
||||||
|
import { Loader2, Lock } from "lucide-react";
|
||||||
|
import { BrandMark } from "@/components/brand-mark";
|
||||||
|
import { RegisterForm } from "@/components/register-form";
|
||||||
|
import { http } from "@/lib/api";
|
||||||
|
import { Button } from "@/components/ui/button";
|
||||||
|
import { CardContent, CardDescription, CardHeader, CardTitle } from "@/components/ui/card";
|
||||||
|
|
||||||
|
export default function RegisterPage() {
|
||||||
|
const { data: status, isLoading: statusLoading } = useQuery({
|
||||||
|
queryKey: ["auth", "register-status"],
|
||||||
|
queryFn: () => http.get<{ enabled: boolean }>("/api/auth/register-status"),
|
||||||
|
});
|
||||||
|
|
||||||
|
if (statusLoading) {
|
||||||
|
return (
|
||||||
|
<div className="flex min-h-[60vh] items-center justify-center">
|
||||||
|
<Loader2 className="h-6 w-6 animate-spin text-muted-foreground" />
|
||||||
|
</div>
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
if (!status?.enabled) {
|
||||||
|
return (
|
||||||
|
<div className="mx-auto flex min-h-[70vh] max-w-md flex-col justify-center px-4">
|
||||||
|
<div className="rounded-2xl border border-border bg-card p-8 text-center shadow-soft">
|
||||||
|
<div className="mx-auto mb-4 flex h-12 w-12 items-center justify-center rounded-xl bg-muted">
|
||||||
|
<Lock className="h-5 w-5 text-muted-foreground" />
|
||||||
|
</div>
|
||||||
|
<BrandMark locale="fa" size="lg" logoOnly className="mx-auto mb-4" />
|
||||||
|
<h1 className="text-xl font-bold">ثبتنام عمومی بسته است</h1>
|
||||||
|
<p className="mt-2 text-sm leading-relaxed text-muted-foreground">
|
||||||
|
در حال حاضر امکان ساخت حساب از این صفحه وجود ندارد. اگر حساب دارید وارد شوید،
|
||||||
|
یا منتظر اعلام متصدی بمانید.
|
||||||
|
</p>
|
||||||
|
<Button asChild className="mt-6 w-full" variant="gradient">
|
||||||
|
<Link href="/login">ورود به حساب</Link>
|
||||||
|
</Button>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
return (
|
||||||
|
<div className="mx-auto flex min-h-[80vh] max-w-4xl flex-col justify-center px-4 py-8">
|
||||||
|
<div className="grid overflow-hidden rounded-2xl border border-border bg-card shadow-soft md:grid-cols-2">
|
||||||
|
<aside className="relative hidden flex-col justify-between overflow-hidden bg-primary p-7 text-primary-foreground md:flex">
|
||||||
|
<div
|
||||||
|
className="dot-grid pointer-events-none absolute -end-20 -top-20 h-72 w-72 rotate-12 text-primary-foreground opacity-50"
|
||||||
|
aria-hidden
|
||||||
|
/>
|
||||||
|
<div className="relative">
|
||||||
|
<BrandMark locale="fa" size="lg" className="text-primary-foreground [&_span]:text-accent" />
|
||||||
|
<p className="section-kicker on-primary mt-5">ثبتنام</p>
|
||||||
|
<h2 className="mt-3 text-2xl font-bold leading-snug">
|
||||||
|
یک حساب.
|
||||||
|
<br />
|
||||||
|
یک مسیر.
|
||||||
|
</h2>
|
||||||
|
<p className="mt-2.5 text-sm leading-relaxed text-primary-foreground/80">
|
||||||
|
شماره تلفن شما یکبار مصرف است — هر شبکه فقط یک ثبتنام.
|
||||||
|
</p>
|
||||||
|
</div>
|
||||||
|
<p className="relative text-xs text-primary-foreground/70">
|
||||||
|
پس از ثبتنام، پیامک را خودتان برای تیم ارسال کنید؛ سامانه پیامک خودکار ندارد.
|
||||||
|
</p>
|
||||||
|
</aside>
|
||||||
|
|
||||||
|
<div className="bg-card p-6 sm:p-8">
|
||||||
|
<CardHeader className="items-center space-y-1.5 px-0 pb-4 pt-0 text-center">
|
||||||
|
<div className="mb-1 flex justify-center md:hidden">
|
||||||
|
<BrandMark locale="fa" size="lg" logoOnly />
|
||||||
|
</div>
|
||||||
|
<CardTitle className="text-2xl">ساخت حساب</CardTitle>
|
||||||
|
<CardDescription>در سه گام کوتاه حساب بسازید.</CardDescription>
|
||||||
|
</CardHeader>
|
||||||
|
<CardContent className="px-0 pt-0">
|
||||||
|
<RegisterForm endpoint="/api/auth/register" submitLabel="ثبتنام" />
|
||||||
|
</CardContent>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
);
|
||||||
|
}
|
||||||
@@ -0,0 +1,11 @@
|
|||||||
|
import type { MetadataRoute } from "next";
|
||||||
|
|
||||||
|
/** Keep certificate share URLs out of search indexes (unlisted-by-link). */
|
||||||
|
export default function robots(): MetadataRoute.Robots {
|
||||||
|
return {
|
||||||
|
rules: {
|
||||||
|
userAgent: "*",
|
||||||
|
disallow: ["/c/", "/api/certificates/"],
|
||||||
|
},
|
||||||
|
};
|
||||||
|
}
|
||||||
@@ -0,0 +1,274 @@
|
|||||||
|
"use client";
|
||||||
|
|
||||||
|
import { Suspense, useEffect, useState } from "react";
|
||||||
|
import { useRouter, useSearchParams } from "next/navigation";
|
||||||
|
import { Award, CalendarDays, HeartHandshake, MessageSquareHeart, Sparkles } from "lucide-react";
|
||||||
|
import { useQuery } from "@tanstack/react-query";
|
||||||
|
import { Tabs, TabsContent, TabsList, TabsTrigger } from "@/components/ui/tabs";
|
||||||
|
import { PageHeader } from "@/components/page-header";
|
||||||
|
import { EventsPanel } from "@/components/events-panel";
|
||||||
|
import { LeaderboardPanel } from "@/components/leaderboard-panel";
|
||||||
|
import { CommunityPanel } from "@/components/community-panel";
|
||||||
|
import { Button } from "@/components/ui/button";
|
||||||
|
import { UserAvatar, avatarPropsOf } from "@/components/ui/user-avatar";
|
||||||
|
import { Skeleton, SkeletonAvatar } from "@/components/ui/skeleton";
|
||||||
|
import { Panel } from "@/components/panel";
|
||||||
|
import { Badge } from "@/components/ui/badge";
|
||||||
|
import type { Mentor } from "@/lib/types";
|
||||||
|
import { http } from "@/lib/api";
|
||||||
|
import type { ChatMessage, Conversation } from "@/lib/types";
|
||||||
|
import { cn } from "@/lib/utils";
|
||||||
|
|
||||||
|
type Tab = "events" | "chats" | "leagues" | "community";
|
||||||
|
|
||||||
|
const TABS: Tab[] = ["events", "chats", "leagues", "community"];
|
||||||
|
|
||||||
|
function parseTab(raw: string | null): Tab {
|
||||||
|
if (raw && (TABS as string[]).includes(raw)) {
|
||||||
|
return raw as Tab;
|
||||||
|
}
|
||||||
|
return "events";
|
||||||
|
}
|
||||||
|
|
||||||
|
export default function UnwrapPage() {
|
||||||
|
return (
|
||||||
|
<Suspense fallback={null}>
|
||||||
|
<HubTabs />
|
||||||
|
</Suspense>
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
function HubTabs() {
|
||||||
|
const router = useRouter();
|
||||||
|
const params = useSearchParams();
|
||||||
|
const [tab, setTab] = useState<Tab>(() => parseTab(params.get("tab")));
|
||||||
|
|
||||||
|
useEffect(() => {
|
||||||
|
const raw = params.get("tab");
|
||||||
|
const next = parseTab(raw);
|
||||||
|
setTab(next);
|
||||||
|
// Invalid / unknown ?tab=… → clean URL so content isn't blank.
|
||||||
|
if (raw != null && raw !== next) {
|
||||||
|
router.replace(next === "events" ? "/unwrap" : `/unwrap?tab=${next}`, { scroll: false });
|
||||||
|
}
|
||||||
|
}, [params, router]);
|
||||||
|
|
||||||
|
const onTab = (value: string) => {
|
||||||
|
const next = parseTab(value);
|
||||||
|
setTab(next);
|
||||||
|
const url = next === "events" ? "/unwrap" : `/unwrap?tab=${next}`;
|
||||||
|
router.replace(url, { scroll: false });
|
||||||
|
};
|
||||||
|
|
||||||
|
return (
|
||||||
|
<div className="space-y-6">
|
||||||
|
<PageHeader
|
||||||
|
kicker="مرکز"
|
||||||
|
title={
|
||||||
|
<>
|
||||||
|
جامعه، <span className="text-gradient-brand">استمرار و منتورها</span>
|
||||||
|
</>
|
||||||
|
}
|
||||||
|
description="رویدادهای زنده برای تقویت مهارت، لیگهای هفتگی برای ثبات، گفتگو با منتور، و هماهنگی حمایت مالی."
|
||||||
|
className="mb-0"
|
||||||
|
/>
|
||||||
|
|
||||||
|
<Tabs value={tab} onValueChange={onTab} className="w-full space-y-5">
|
||||||
|
<TabsList className="grid h-auto w-full grid-cols-2 gap-1 p-1.5 sm:grid-cols-4">
|
||||||
|
<TabsTrigger value="events" className="h-10 gap-1.5 px-2 sm:px-3">
|
||||||
|
<CalendarDays className="h-4 w-4 shrink-0" />
|
||||||
|
<span className="truncate">رویدادها</span>
|
||||||
|
</TabsTrigger>
|
||||||
|
<TabsTrigger value="chats" className="h-10 gap-1.5 px-2 sm:px-3">
|
||||||
|
<MessageSquareHeart className="h-4 w-4 shrink-0" />
|
||||||
|
<span className="truncate">گفتگو با منتور</span>
|
||||||
|
</TabsTrigger>
|
||||||
|
<TabsTrigger value="leagues" className="h-10 gap-1.5 px-2 sm:px-3">
|
||||||
|
<Award className="h-4 w-4 shrink-0" />
|
||||||
|
<span className="truncate">لیگها</span>
|
||||||
|
</TabsTrigger>
|
||||||
|
<TabsTrigger value="community" className="h-10 gap-1.5 px-2 sm:px-3">
|
||||||
|
<HeartHandshake className="h-4 w-4 shrink-0" />
|
||||||
|
<span className="truncate">حمایت</span>
|
||||||
|
</TabsTrigger>
|
||||||
|
</TabsList>
|
||||||
|
<TabsContent value="events" className="mt-0 space-y-4">
|
||||||
|
<button
|
||||||
|
type="button"
|
||||||
|
onClick={() => onTab("community")}
|
||||||
|
className="flex w-full items-center gap-3 rounded-2xl border-2 border-accent/30 bg-accent/5 px-4 py-3.5 text-start transition hover:bg-accent/10"
|
||||||
|
>
|
||||||
|
<span className="grid h-10 w-10 shrink-0 place-items-center rounded-xl bg-accent/15 text-accent">
|
||||||
|
<HeartHandshake className="h-5 w-5" />
|
||||||
|
</span>
|
||||||
|
<span className="min-w-0 flex-1">
|
||||||
|
<span className="block text-sm font-extrabold">حمایت مالی</span>
|
||||||
|
<span className="mt-0.5 block text-xs text-muted-foreground">
|
||||||
|
هماهنگی دونیت از طریق گفتگو با تیم
|
||||||
|
</span>
|
||||||
|
</span>
|
||||||
|
</button>
|
||||||
|
<EventsPanel />
|
||||||
|
</TabsContent>
|
||||||
|
<TabsContent value="chats" className="mt-0">
|
||||||
|
<ChatsLauncher />
|
||||||
|
</TabsContent>
|
||||||
|
<TabsContent value="leagues" className="mt-0">
|
||||||
|
<LeaderboardPanel />
|
||||||
|
</TabsContent>
|
||||||
|
<TabsContent value="community" className="mt-0">
|
||||||
|
<CommunityPanel />
|
||||||
|
</TabsContent>
|
||||||
|
</Tabs>
|
||||||
|
</div>
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
function openChat(withId?: number) {
|
||||||
|
window.dispatchEvent(new CustomEvent("pargar:chat", { detail: { open: true, with: withId } }));
|
||||||
|
}
|
||||||
|
|
||||||
|
function ChatsLauncher() {
|
||||||
|
const { data, isLoading } = useQuery({
|
||||||
|
queryKey: ["mentors"],
|
||||||
|
queryFn: () => http.get<{ mentors: Mentor[] }>("/api/mentors"),
|
||||||
|
});
|
||||||
|
const { data: convData, isLoading: convLoading } = useQuery({
|
||||||
|
queryKey: ["conversations"],
|
||||||
|
queryFn: () => http.get<{ conversations: Conversation[] }>("/api/chats/conversations"),
|
||||||
|
});
|
||||||
|
const mentors = data?.mentors ?? [];
|
||||||
|
const conversations = convData?.conversations ?? [];
|
||||||
|
|
||||||
|
return (
|
||||||
|
<div className="grid gap-4 lg:grid-cols-2">
|
||||||
|
<Panel className="justify-center text-center" title="گفتگوها" description="یک پنجرهٔ شناور شیشهای در تمام صفحات — با صدا، عکس، ویدیو و پیام صوتی.">
|
||||||
|
<div className="flex flex-col items-center gap-4 pt-1">
|
||||||
|
<div className="grid h-14 w-14 place-items-center rounded-2xl bg-primary/10">
|
||||||
|
<MessageSquareHeart className="h-7 w-7 text-primary" />
|
||||||
|
</div>
|
||||||
|
<p className="max-w-sm text-sm text-muted-foreground">
|
||||||
|
گفتگو همیشه در دکمهٔ شناور پایین صفحه در دسترس شماست؛ گفتگوها خصوصی هستند و پاسخ منتورها معمولاً کمتر از یک روز طول میکشد.
|
||||||
|
</p>
|
||||||
|
<Button onClick={() => openChat()} className="gap-2">
|
||||||
|
<Sparkles className="h-4 w-4" /> باز کردن گفتگوها
|
||||||
|
</Button>
|
||||||
|
</div>
|
||||||
|
</Panel>
|
||||||
|
|
||||||
|
<Panel title="گفتگوهای شما" description="مکالمات جاری با منتورها — روی هر کدام بزنید تا باز شود.">
|
||||||
|
<div className="space-y-1.5 pt-1">
|
||||||
|
{convLoading && (
|
||||||
|
<div className="space-y-2">
|
||||||
|
{[0, 1, 2].map((i) => (
|
||||||
|
<div key={i} className="flex items-center gap-3 rounded-xl border-2 border-border/70 px-3 py-2.5">
|
||||||
|
<SkeletonAvatar />
|
||||||
|
<div className="flex-1 space-y-1.5">
|
||||||
|
<div className="flex items-center justify-between gap-2">
|
||||||
|
<Skeleton className="h-4 w-32" />
|
||||||
|
<Skeleton className="h-3 w-14" />
|
||||||
|
</div>
|
||||||
|
<Skeleton className="h-3 w-2/3" />
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
))}
|
||||||
|
</div>
|
||||||
|
)}
|
||||||
|
{conversations.map((c) => (
|
||||||
|
<button
|
||||||
|
key={c.partner.id}
|
||||||
|
onClick={() => openChat(c.partner.id)}
|
||||||
|
className="flex w-full items-center gap-3 rounded-xl border-2 border-border/70 px-3 py-2.5 text-right transition-colors hover:border-primary/50 hover:bg-primary/5"
|
||||||
|
>
|
||||||
|
<UserAvatar name={c.partner.name} className="h-10 w-10" {...avatarPropsOf(c.partner)} />
|
||||||
|
<div className="min-w-0 flex-1">
|
||||||
|
<div className="flex items-center justify-between gap-2">
|
||||||
|
<p className="truncate font-bold">{c.partner.name}</p>
|
||||||
|
{c.lastMessage && (
|
||||||
|
<span className="shrink-0 text-[10px] text-muted-foreground">{timeAgo(c.lastMessage.createdAt)}</span>
|
||||||
|
)}
|
||||||
|
</div>
|
||||||
|
<p
|
||||||
|
dir="auto"
|
||||||
|
className={cn(
|
||||||
|
"truncate text-xs [unicode-bidi:plaintext]",
|
||||||
|
c.unreadCount > 0 ? "font-bold text-foreground" : "text-muted-foreground"
|
||||||
|
)}
|
||||||
|
>
|
||||||
|
{c.lastMessage ? messagePreview(c.lastMessage) : "پیامی ندارد"}
|
||||||
|
</p>
|
||||||
|
</div>
|
||||||
|
{c.unreadCount > 0 && (
|
||||||
|
<Badge variant="accent" className="h-5 min-w-5 justify-center rounded-full px-1.5">
|
||||||
|
{c.unreadCount}
|
||||||
|
</Badge>
|
||||||
|
)}
|
||||||
|
</button>
|
||||||
|
))}
|
||||||
|
{!convLoading && conversations.length === 0 && (
|
||||||
|
<p className="px-1 text-sm text-muted-foreground">
|
||||||
|
هنوز گفتگویی ندارید — از «شروع سریع» یک منتور انتخاب کنید.
|
||||||
|
</p>
|
||||||
|
)}
|
||||||
|
</div>
|
||||||
|
</Panel>
|
||||||
|
|
||||||
|
<Panel title="شروع سریع با منتور" description="یک گفتگو را مستقیم باز کنید.">
|
||||||
|
<div className="space-y-1 pt-1">
|
||||||
|
{isLoading && (
|
||||||
|
<div className="space-y-2">
|
||||||
|
{[0, 1, 2, 3].map((i) => (
|
||||||
|
<div key={i} className="flex items-center gap-3 rounded-xl border-2 border-border/70 px-3 py-2.5">
|
||||||
|
<SkeletonAvatar />
|
||||||
|
<div className="flex-1 space-y-1.5">
|
||||||
|
<Skeleton className="h-4 w-40" />
|
||||||
|
<Skeleton className="h-3 w-16" />
|
||||||
|
</div>
|
||||||
|
<Skeleton className="h-5 w-20 rounded-full" />
|
||||||
|
</div>
|
||||||
|
))}
|
||||||
|
</div>
|
||||||
|
)}
|
||||||
|
{mentors.map((m) => (
|
||||||
|
<button
|
||||||
|
key={m.id}
|
||||||
|
onClick={() => openChat(m.id)}
|
||||||
|
className="flex w-full items-center gap-3 rounded-xl border-2 border-border/70 px-3 py-2.5 text-right transition-colors hover:border-primary/50 hover:bg-primary/5"
|
||||||
|
>
|
||||||
|
<UserAvatar name={m.name} className="h-10 w-10" {...avatarPropsOf(m)} />
|
||||||
|
<div className="min-w-0 flex-1">
|
||||||
|
<p className="truncate font-bold">{m.name}</p>
|
||||||
|
<p className="text-xs text-muted-foreground">منتور</p>
|
||||||
|
</div>
|
||||||
|
<span className="inline-flex items-center gap-1.5 text-xs font-bold text-success">
|
||||||
|
<span className="h-1.5 w-1.5 rounded-full bg-success" /> در دسترس
|
||||||
|
</span>
|
||||||
|
</button>
|
||||||
|
))}
|
||||||
|
{!isLoading && mentors.length === 0 && (
|
||||||
|
<p className="text-sm text-muted-foreground">هنوز منتوری در دسترس نیست.</p>
|
||||||
|
)}
|
||||||
|
</div>
|
||||||
|
</Panel>
|
||||||
|
</div>
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
function messagePreview(m: ChatMessage) {
|
||||||
|
if (m.body) return m.body;
|
||||||
|
if (m.attachment) {
|
||||||
|
const labels: Record<string, string> = { image: "📷 عکس", video: "🎬 ویدیو", audio: "🎵 پیام صوتی" };
|
||||||
|
return labels[m.attachment.type] ?? `📎 ${m.attachment.name}`;
|
||||||
|
}
|
||||||
|
return "";
|
||||||
|
}
|
||||||
|
|
||||||
|
function timeAgo(iso: string) {
|
||||||
|
const diff = Date.now() - new Date(iso).getTime();
|
||||||
|
const m = Math.floor(diff / 60_000);
|
||||||
|
if (m < 1) return "الان";
|
||||||
|
if (m < 60) return `${m} دقیقه قبل`;
|
||||||
|
const h = Math.floor(m / 60);
|
||||||
|
if (h < 24) return `${h} ساعت قبل`;
|
||||||
|
return new Date(iso).toLocaleDateString("fa-IR");
|
||||||
|
}
|
||||||
File diff suppressed because it is too large
Load Diff
@@ -0,0 +1,285 @@
|
|||||||
|
"use client";
|
||||||
|
|
||||||
|
import { useState } from "react";
|
||||||
|
import {
|
||||||
|
Bell,
|
||||||
|
Calendar,
|
||||||
|
Eye,
|
||||||
|
Gamepad2,
|
||||||
|
Loader2,
|
||||||
|
Megaphone,
|
||||||
|
Route,
|
||||||
|
TrendingUp,
|
||||||
|
Users,
|
||||||
|
} from "lucide-react";
|
||||||
|
import { http, toUserError } from "@/lib/api";
|
||||||
|
import { Button } from "@/components/ui/button";
|
||||||
|
import { Card, CardContent, CardHeader, CardTitle } from "@/components/ui/card";
|
||||||
|
import { Input } from "@/components/ui/input";
|
||||||
|
import { Label } from "@/components/ui/label";
|
||||||
|
import {
|
||||||
|
Dialog,
|
||||||
|
DialogContent,
|
||||||
|
DialogDescription,
|
||||||
|
DialogFooter,
|
||||||
|
DialogHeader,
|
||||||
|
DialogTitle,
|
||||||
|
} from "@/components/ui/dialog";
|
||||||
|
import { Badge } from "@/components/ui/badge";
|
||||||
|
import { cn } from "@/lib/utils";
|
||||||
|
import { toast } from "@/components/providers";
|
||||||
|
|
||||||
|
const CATEGORIES = [
|
||||||
|
{ id: "event", label: "رویداد", icon: Calendar, hint: "جلسه زنده، کارگاه، ددلاین" },
|
||||||
|
{ id: "progress", label: "پیشرفت", icon: TrendingUp, hint: "درس جدید، فصل بازشده" },
|
||||||
|
{ id: "gamification", label: "بازیسازی", icon: Gamepad2, hint: "جایزه، استریک، چالش" },
|
||||||
|
{ id: "mentor", label: "منتور", icon: Users, hint: "پیام مستقیم تیم منتور" },
|
||||||
|
] as const;
|
||||||
|
|
||||||
|
const ROUTES = [
|
||||||
|
{ path: "/unwrap", label: "نقشه مسیر" },
|
||||||
|
{ path: "/notifications", label: "اعلانها" },
|
||||||
|
{ path: "/leaderboard", label: "لیدربورد" },
|
||||||
|
{ path: "/cap", label: "داشبورد" },
|
||||||
|
];
|
||||||
|
|
||||||
|
function PreviewCard({
|
||||||
|
title,
|
||||||
|
body,
|
||||||
|
category,
|
||||||
|
route,
|
||||||
|
}: {
|
||||||
|
title: string;
|
||||||
|
body: string;
|
||||||
|
category: string;
|
||||||
|
route: string;
|
||||||
|
}) {
|
||||||
|
const cat = CATEGORIES.find((c) => c.id === category);
|
||||||
|
return (
|
||||||
|
<div className="rounded-xl border border-border bg-background p-3.5">
|
||||||
|
<div className="flex h-8 items-center gap-2">
|
||||||
|
<span className="grid h-8 w-8 shrink-0 place-items-center rounded-lg bg-primary/10 text-primary">
|
||||||
|
<Megaphone className="h-4 w-4" />
|
||||||
|
</span>
|
||||||
|
<Badge variant="secondary" className="text-[10px]">
|
||||||
|
{cat?.label ?? category}
|
||||||
|
</Badge>
|
||||||
|
</div>
|
||||||
|
<p className="mt-2.5 text-sm font-black leading-snug">{title.trim() || "عنوان اطلاعیه"}</p>
|
||||||
|
<p className="mt-1 min-h-[2.5rem] text-xs leading-relaxed text-muted-foreground">
|
||||||
|
{body.trim() || "متن پیام اینجا دیده میشود…"}
|
||||||
|
</p>
|
||||||
|
<p className="mt-2.5 truncate text-[10px] font-mono text-primary" dir="ltr">
|
||||||
|
→ {route || "/"}
|
||||||
|
</p>
|
||||||
|
</div>
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
export function AnnouncePanel() {
|
||||||
|
const [title, setTitle] = useState("");
|
||||||
|
const [body, setBody] = useState("");
|
||||||
|
const [category, setCategory] = useState<string>("event");
|
||||||
|
const [route, setRoute] = useState("/unwrap");
|
||||||
|
const [busy, setBusy] = useState(false);
|
||||||
|
const [confirmOpen, setConfirmOpen] = useState(false);
|
||||||
|
const [lastSent, setLastSent] = useState<{ title: string; recipients: number } | null>(null);
|
||||||
|
|
||||||
|
const titleOk = title.trim().length >= 3;
|
||||||
|
const bodyOk = body.trim().length >= 8;
|
||||||
|
const valid = titleOk && bodyOk;
|
||||||
|
|
||||||
|
const send = async () => {
|
||||||
|
if (!valid) return;
|
||||||
|
setBusy(true);
|
||||||
|
try {
|
||||||
|
const res = await http.post<{ recipients: number }>("/api/admin/announce", {
|
||||||
|
title: title.trim(),
|
||||||
|
body: body.trim(),
|
||||||
|
category,
|
||||||
|
route,
|
||||||
|
});
|
||||||
|
toast.success(`اطلاعیه برای ${res.recipients} نفر ارسال شد`);
|
||||||
|
setLastSent({ title: title.trim(), recipients: res.recipients });
|
||||||
|
setTitle("");
|
||||||
|
setBody("");
|
||||||
|
setConfirmOpen(false);
|
||||||
|
} catch (e) {
|
||||||
|
toast.error(toUserError(e, "ارسال اطلاعیه ممکن نشد"));
|
||||||
|
} finally {
|
||||||
|
setBusy(false);
|
||||||
|
}
|
||||||
|
};
|
||||||
|
|
||||||
|
return (
|
||||||
|
<>
|
||||||
|
<div className="grid items-start gap-4 lg:grid-cols-[minmax(0,1fr)_20rem]">
|
||||||
|
<Card>
|
||||||
|
<CardHeader className="space-y-1">
|
||||||
|
<CardTitle className="text-base">نگارش اعلان</CardTitle>
|
||||||
|
<p className="text-xs text-muted-foreground">
|
||||||
|
به همه هنرجویان فعال میرسد و در مرکز اعلانها دیده میشود.
|
||||||
|
</p>
|
||||||
|
</CardHeader>
|
||||||
|
<CardContent className="space-y-5">
|
||||||
|
<div className="space-y-2">
|
||||||
|
<Label className="text-sm font-bold">عنوان</Label>
|
||||||
|
<Input
|
||||||
|
value={title}
|
||||||
|
onChange={(e) => setTitle(e.target.value)}
|
||||||
|
placeholder="مثلاً جلسه زنده هفته ۴ · پنجشنبه ۲۰:۰۰"
|
||||||
|
className={cn("h-11 rounded-2xl", !titleOk && title.length > 0 && "border-destructive")}
|
||||||
|
autoFocus
|
||||||
|
/>
|
||||||
|
</div>
|
||||||
|
|
||||||
|
<div className="space-y-2">
|
||||||
|
<div className="flex h-5 items-center justify-between gap-3">
|
||||||
|
<Label className="text-sm font-bold">پیام</Label>
|
||||||
|
<span className="text-[11px] tabular-nums text-muted-foreground">{body.length}/۵۰۰</span>
|
||||||
|
</div>
|
||||||
|
<textarea
|
||||||
|
value={body}
|
||||||
|
onChange={(e) => setBody(e.target.value.slice(0, 500))}
|
||||||
|
rows={5}
|
||||||
|
maxLength={500}
|
||||||
|
className={cn(
|
||||||
|
"w-full resize-y rounded-xl border bg-background px-4 py-3 text-sm leading-relaxed focus:outline-none focus:ring-2 focus:ring-primary",
|
||||||
|
!bodyOk && body.length > 0 ? "border-destructive/50" : "border-input"
|
||||||
|
)}
|
||||||
|
placeholder="یک جملهٔ واضح و کوتاه — لینک یا زمان را حتماً بگویید…"
|
||||||
|
/>
|
||||||
|
{body.trim().length > 0 && body.trim().length < 8 && (
|
||||||
|
<p className="text-xs font-bold text-destructive">پیام حداقل چند کلمه باشد.</p>
|
||||||
|
)}
|
||||||
|
</div>
|
||||||
|
|
||||||
|
<div className="space-y-2">
|
||||||
|
<Label className="text-sm font-bold">دسته</Label>
|
||||||
|
<div className="grid gap-2 sm:grid-cols-2">
|
||||||
|
{CATEGORIES.map((c) => {
|
||||||
|
const active = category === c.id;
|
||||||
|
const Icon = c.icon;
|
||||||
|
return (
|
||||||
|
<button
|
||||||
|
key={c.id}
|
||||||
|
type="button"
|
||||||
|
onClick={() => setCategory(c.id)}
|
||||||
|
className={cn(
|
||||||
|
"grid h-[4.25rem] grid-cols-[2.25rem_minmax(0,1fr)] items-center gap-3 rounded-xl border px-3 text-right transition-colors",
|
||||||
|
active ? "border-primary bg-primary/10" : "border-border hover:border-primary/40"
|
||||||
|
)}
|
||||||
|
>
|
||||||
|
<span
|
||||||
|
className={cn(
|
||||||
|
"grid h-9 w-9 place-items-center rounded-xl",
|
||||||
|
active ? "bg-primary text-primary-foreground" : "bg-muted text-muted-foreground"
|
||||||
|
)}
|
||||||
|
>
|
||||||
|
<Icon className="h-4 w-4" />
|
||||||
|
</span>
|
||||||
|
<span className="min-w-0">
|
||||||
|
<span className="block truncate text-sm font-extrabold">{c.label}</span>
|
||||||
|
<span className="block truncate text-[11px] text-muted-foreground">{c.hint}</span>
|
||||||
|
</span>
|
||||||
|
</button>
|
||||||
|
);
|
||||||
|
})}
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
|
||||||
|
<div className="space-y-2">
|
||||||
|
<Label className="flex h-5 items-center gap-1.5 text-sm font-bold">
|
||||||
|
<Route className="h-3.5 w-3.5" /> مقصد کلیک
|
||||||
|
</Label>
|
||||||
|
<div className="flex flex-wrap gap-2">
|
||||||
|
{ROUTES.map((r) => (
|
||||||
|
<button
|
||||||
|
key={r.path}
|
||||||
|
type="button"
|
||||||
|
onClick={() => setRoute(r.path)}
|
||||||
|
className={cn(
|
||||||
|
"inline-flex h-8 items-center rounded-full border px-3 text-xs font-bold transition-colors",
|
||||||
|
route === r.path
|
||||||
|
? "border-primary bg-primary text-primary-foreground"
|
||||||
|
: "border-border hover:border-primary/40"
|
||||||
|
)}
|
||||||
|
>
|
||||||
|
{r.label}
|
||||||
|
</button>
|
||||||
|
))}
|
||||||
|
</div>
|
||||||
|
<Input
|
||||||
|
value={route}
|
||||||
|
onChange={(e) => setRoute(e.target.value)}
|
||||||
|
dir="ltr"
|
||||||
|
className="h-10 rounded-2xl font-mono text-xs"
|
||||||
|
placeholder="/unwrap"
|
||||||
|
/>
|
||||||
|
</div>
|
||||||
|
|
||||||
|
<div className="flex flex-wrap items-center gap-3 border-t border-border pt-4">
|
||||||
|
<Button
|
||||||
|
size="lg"
|
||||||
|
className="h-11 gap-2"
|
||||||
|
disabled={!valid}
|
||||||
|
onClick={() => setConfirmOpen(true)}
|
||||||
|
>
|
||||||
|
<Eye className="h-4 w-4" />
|
||||||
|
پیشنمایش و ارسال
|
||||||
|
</Button>
|
||||||
|
{!valid && (
|
||||||
|
<p className="text-xs text-muted-foreground">عنوان و پیام را کامل کنید تا ادامه فعال شود.</p>
|
||||||
|
)}
|
||||||
|
</div>
|
||||||
|
</CardContent>
|
||||||
|
</Card>
|
||||||
|
|
||||||
|
<div className="space-y-4 lg:sticky lg:top-24">
|
||||||
|
<Card className="border bg-muted/20">
|
||||||
|
<CardHeader className="space-y-1 pb-3">
|
||||||
|
<CardTitle className="flex h-6 items-center gap-2 text-sm">
|
||||||
|
<Eye className="h-3.5 w-3.5" /> پیشنمایش زنده
|
||||||
|
</CardTitle>
|
||||||
|
<p className="text-[11px] text-muted-foreground">همزمان با تایپ بهروز میشود.</p>
|
||||||
|
</CardHeader>
|
||||||
|
<CardContent>
|
||||||
|
<PreviewCard title={title} body={body} category={category} route={route} />
|
||||||
|
</CardContent>
|
||||||
|
</Card>
|
||||||
|
|
||||||
|
{lastSent && (
|
||||||
|
<Card className="border border-success/40 bg-success/5">
|
||||||
|
<CardContent className="space-y-1 pt-5 text-sm">
|
||||||
|
<p className="font-bold text-success">آخرین ارسال موفق</p>
|
||||||
|
<p className="truncate font-extrabold">{lastSent.title}</p>
|
||||||
|
<p className="text-xs text-muted-foreground">{lastSent.recipients} گیرنده</p>
|
||||||
|
</CardContent>
|
||||||
|
</Card>
|
||||||
|
)}
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
|
||||||
|
<Dialog open={confirmOpen} onOpenChange={setConfirmOpen}>
|
||||||
|
<DialogContent className="max-w-md gap-0 overflow-hidden p-0 sm:rounded-2xl">
|
||||||
|
<DialogHeader className="space-y-1 border-b border-border px-6 py-4 text-start">
|
||||||
|
<DialogTitle className="text-lg font-black">تأیید ارسال</DialogTitle>
|
||||||
|
<DialogDescription>این پیشنمایش نهایی است؛ بعد از تأیید برای همه ارسال میشود.</DialogDescription>
|
||||||
|
</DialogHeader>
|
||||||
|
<div className="px-6 py-5">
|
||||||
|
<PreviewCard title={title} body={body} category={category} route={route} />
|
||||||
|
</div>
|
||||||
|
<DialogFooter className="flex-row items-center justify-between gap-2 border-t border-border px-6 py-4 sm:space-x-0">
|
||||||
|
<Button variant="outline" className="h-10" onClick={() => setConfirmOpen(false)} disabled={busy}>
|
||||||
|
بازگشت
|
||||||
|
</Button>
|
||||||
|
<Button className="h-10 gap-2" disabled={busy || !valid} onClick={() => void send()}>
|
||||||
|
{busy ? <Loader2 className="h-4 w-4 animate-spin" /> : <Bell className="h-4 w-4" />}
|
||||||
|
تأیید و ارسال
|
||||||
|
</Button>
|
||||||
|
</DialogFooter>
|
||||||
|
</DialogContent>
|
||||||
|
</Dialog>
|
||||||
|
</>
|
||||||
|
);
|
||||||
|
}
|
||||||
@@ -0,0 +1,401 @@
|
|||||||
|
"use client";
|
||||||
|
|
||||||
|
import { useQuery, useQueryClient } from "@tanstack/react-query";
|
||||||
|
import { useEffect, useMemo, useState } from "react";
|
||||||
|
import { Loader2, Trash2, Upload } from "lucide-react";
|
||||||
|
import { http, toUserError } from "@/lib/api";
|
||||||
|
import type { RegistrationBlacklistAttempt, RegistrationPhoneBlacklist } from "@/lib/types";
|
||||||
|
import { Button } from "@/components/ui/button";
|
||||||
|
import { Card, CardContent, CardHeader, CardTitle } from "@/components/ui/card";
|
||||||
|
import { Input } from "@/components/ui/input";
|
||||||
|
import { Label } from "@/components/ui/label";
|
||||||
|
import { Textarea } from "@/components/ui/textarea";
|
||||||
|
import { toast } from "@/components/providers";
|
||||||
|
import { formatFaNumber } from "@/lib/utils";
|
||||||
|
import {
|
||||||
|
DEFAULT_PAGE_SIZE,
|
||||||
|
ListPagination,
|
||||||
|
buildPageQuery,
|
||||||
|
type Paginated,
|
||||||
|
} from "@/components/admin/list-pagination";
|
||||||
|
import { ListToolbar } from "@/components/admin/list-toolbar";
|
||||||
|
import { useConfirm } from "@/components/admin/use-confirm";
|
||||||
|
|
||||||
|
const pathLabel: Record<string, string> = {
|
||||||
|
public: "عمومی",
|
||||||
|
invite: "دعوت",
|
||||||
|
};
|
||||||
|
|
||||||
|
type ImportResult = {
|
||||||
|
inserted: number;
|
||||||
|
skipped: number;
|
||||||
|
invalid: number;
|
||||||
|
rejected: number;
|
||||||
|
rejectedPhones?: string[];
|
||||||
|
removedWhitelist?: number;
|
||||||
|
whitelistedConflicts?: string[];
|
||||||
|
};
|
||||||
|
|
||||||
|
export function BlacklistPanel() {
|
||||||
|
const qc = useQueryClient();
|
||||||
|
const { confirm, dialog } = useConfirm();
|
||||||
|
const [text, setText] = useState("");
|
||||||
|
const [busy, setBusy] = useState(false);
|
||||||
|
const [deleteBusy, setDeleteBusy] = useState<number | null>(null);
|
||||||
|
const [listQ, setListQ] = useState("");
|
||||||
|
const [historyQ, setHistoryQ] = useState("");
|
||||||
|
const [listPage, setListPage] = useState(1);
|
||||||
|
const [historyPage, setHistoryPage] = useState(1);
|
||||||
|
const [pendingConflicts, setPendingConflicts] = useState<string[]>([]);
|
||||||
|
|
||||||
|
useEffect(() => {
|
||||||
|
setListPage(1);
|
||||||
|
}, [listQ]);
|
||||||
|
|
||||||
|
useEffect(() => {
|
||||||
|
setHistoryPage(1);
|
||||||
|
}, [historyQ]);
|
||||||
|
|
||||||
|
const { data, isLoading } = useQuery({
|
||||||
|
queryKey: ["admin", "phone-blacklist", listQ, listPage],
|
||||||
|
queryFn: () => {
|
||||||
|
const params = new URLSearchParams(buildPageQuery(listPage));
|
||||||
|
if (listQ.trim()) params.set("q", listQ.trim());
|
||||||
|
return http.get<Paginated<RegistrationPhoneBlacklist>>(
|
||||||
|
`/api/admin/phone-blacklist?${params.toString()}`,
|
||||||
|
);
|
||||||
|
},
|
||||||
|
});
|
||||||
|
|
||||||
|
const { data: historyData, isLoading: historyLoading } = useQuery({
|
||||||
|
queryKey: ["admin", "phone-blacklist", "attempts", historyQ, historyPage],
|
||||||
|
queryFn: () => {
|
||||||
|
const params = new URLSearchParams(buildPageQuery(historyPage));
|
||||||
|
if (historyQ.trim()) params.set("q", historyQ.trim());
|
||||||
|
return http.get<Paginated<RegistrationBlacklistAttempt>>(
|
||||||
|
`/api/admin/phone-blacklist/attempts?${params.toString()}`,
|
||||||
|
);
|
||||||
|
},
|
||||||
|
});
|
||||||
|
|
||||||
|
const entries = useMemo(() => data?.items ?? [], [data]);
|
||||||
|
const attempts = useMemo(() => historyData?.items ?? [], [historyData]);
|
||||||
|
const listTotal = data?.total ?? 0;
|
||||||
|
const listPageSize = data?.pageSize ?? DEFAULT_PAGE_SIZE;
|
||||||
|
const historyTotal = historyData?.total ?? 0;
|
||||||
|
const historyPageSize = historyData?.pageSize ?? DEFAULT_PAGE_SIZE;
|
||||||
|
|
||||||
|
const summarizeImport = (res: ImportResult) => {
|
||||||
|
const parts = [
|
||||||
|
`${formatFaNumber(res.inserted)} افزوده`,
|
||||||
|
res.skipped ? `${formatFaNumber(res.skipped)} تکراری` : null,
|
||||||
|
res.removedWhitelist ? `${formatFaNumber(res.removedWhitelist)} از فهرست مجاز حذف` : null,
|
||||||
|
res.invalid ? `${formatFaNumber(res.invalid)} نامعتبر` : null,
|
||||||
|
].filter(Boolean);
|
||||||
|
if (parts.length > 0) {
|
||||||
|
toast.success(parts.join(" · "));
|
||||||
|
}
|
||||||
|
if (res.rejected > 0) {
|
||||||
|
const phones = res.rejectedPhones ?? [];
|
||||||
|
const detail =
|
||||||
|
phones.length > 0
|
||||||
|
? ` (${phones.slice(0, 3).join("، ")}${phones.length > 3 ? "…" : ""})`
|
||||||
|
: "";
|
||||||
|
toast.error(
|
||||||
|
`${formatFaNumber(res.rejected)} شماره قبلاً ثبتنام شده و قابل انتقال به فهرست سیاه نیست${detail}`,
|
||||||
|
);
|
||||||
|
}
|
||||||
|
};
|
||||||
|
|
||||||
|
const postImport = async (payload: {
|
||||||
|
text?: string;
|
||||||
|
phones?: string[];
|
||||||
|
resolveConflicts?: boolean;
|
||||||
|
}) => {
|
||||||
|
return http.post<ImportResult>("/api/admin/phone-blacklist/import", payload);
|
||||||
|
};
|
||||||
|
|
||||||
|
const finishImport = (res: ImportResult) => {
|
||||||
|
summarizeImport(res);
|
||||||
|
setText("");
|
||||||
|
setPendingConflicts([]);
|
||||||
|
setListPage(1);
|
||||||
|
qc.invalidateQueries({ queryKey: ["admin", "phone-blacklist"] });
|
||||||
|
if (res.removedWhitelist) {
|
||||||
|
qc.invalidateQueries({ queryKey: ["admin", "phone-whitelist"] });
|
||||||
|
}
|
||||||
|
};
|
||||||
|
|
||||||
|
const importPhones = async () => {
|
||||||
|
if (!text.trim()) {
|
||||||
|
toast.error("حداقل یک شماره وارد کنید");
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
setBusy(true);
|
||||||
|
setPendingConflicts([]);
|
||||||
|
try {
|
||||||
|
const res = await postImport({ text });
|
||||||
|
const conflicts = res.whitelistedConflicts ?? [];
|
||||||
|
if (conflicts.length > 0) {
|
||||||
|
summarizeImport(res);
|
||||||
|
if (conflicts.length === 1) {
|
||||||
|
const phone = conflicts[0];
|
||||||
|
const ok = await confirm(
|
||||||
|
"این شماره در فهرست مجاز است",
|
||||||
|
`شماره ${phone} در فهرست مجاز است. حذف از فهرست مجاز و افزودن به فهرست سیاه؟`,
|
||||||
|
"حذف از فهرست مجاز و افزودن",
|
||||||
|
);
|
||||||
|
if (!ok) {
|
||||||
|
setPendingConflicts(conflicts);
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
const resolved = await postImport({ phones: conflicts, resolveConflicts: true });
|
||||||
|
finishImport(resolved);
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
setPendingConflicts(conflicts);
|
||||||
|
toast.error(
|
||||||
|
`${formatFaNumber(conflicts.length)} شماره در فهرست مجاز است — برای ادامه تعارض را حل کنید`,
|
||||||
|
);
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
finishImport(res);
|
||||||
|
} catch (e) {
|
||||||
|
toast.error(toUserError(e));
|
||||||
|
} finally {
|
||||||
|
setBusy(false);
|
||||||
|
}
|
||||||
|
};
|
||||||
|
|
||||||
|
const resolveConflicts = async () => {
|
||||||
|
if (pendingConflicts.length === 0) {
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
setBusy(true);
|
||||||
|
try {
|
||||||
|
const res = await postImport({ phones: pendingConflicts, resolveConflicts: true });
|
||||||
|
finishImport(res);
|
||||||
|
} catch (e) {
|
||||||
|
toast.error(toUserError(e));
|
||||||
|
} finally {
|
||||||
|
setBusy(false);
|
||||||
|
}
|
||||||
|
};
|
||||||
|
|
||||||
|
const remove = async (id: number) => {
|
||||||
|
setDeleteBusy(id);
|
||||||
|
try {
|
||||||
|
await http.del(`/api/admin/phone-blacklist/${id}`);
|
||||||
|
toast.success("شماره از فهرست سیاه حذف شد");
|
||||||
|
qc.invalidateQueries({ queryKey: ["admin", "phone-blacklist"] });
|
||||||
|
} catch (e) {
|
||||||
|
toast.error(toUserError(e));
|
||||||
|
} finally {
|
||||||
|
setDeleteBusy(null);
|
||||||
|
}
|
||||||
|
};
|
||||||
|
|
||||||
|
return (
|
||||||
|
<div className="space-y-5">
|
||||||
|
{dialog}
|
||||||
|
<Card>
|
||||||
|
<CardHeader className="space-y-1 pb-3">
|
||||||
|
<CardTitle className="text-base">واردات شماره</CardTitle>
|
||||||
|
<p className="text-xs text-muted-foreground">
|
||||||
|
این شمارهها همیشه رد میشوند — ثبتنام عمومی و دعوتنامه. اگر شماره در فهرست مجاز باشد، قبل
|
||||||
|
از انتقال تأیید میگیریم. فرمت: هر خط یا جدا با ویرگول.
|
||||||
|
</p>
|
||||||
|
</CardHeader>
|
||||||
|
<CardContent className="space-y-4">
|
||||||
|
<div className="space-y-2">
|
||||||
|
<Label htmlFor="bl-text">شمارهها</Label>
|
||||||
|
<Textarea
|
||||||
|
id="bl-text"
|
||||||
|
className="min-h-[120px] text-left tracking-wide"
|
||||||
|
dir="ltr"
|
||||||
|
value={text}
|
||||||
|
onChange={(e) => setText(e.target.value)}
|
||||||
|
placeholder={"09121234567\n09129876543"}
|
||||||
|
/>
|
||||||
|
</div>
|
||||||
|
<Button type="button" variant="gradient" disabled={busy} onClick={() => void importPhones()}>
|
||||||
|
{busy ? <Loader2 className="h-4 w-4 animate-spin" /> : <Upload className="h-4 w-4" />}
|
||||||
|
واردات
|
||||||
|
</Button>
|
||||||
|
{pendingConflicts.length > 0 && (
|
||||||
|
<div className="space-y-3 rounded-xl border border-border bg-muted/30 p-4">
|
||||||
|
<p className="text-sm font-medium">این شماره در فهرست مجاز است</p>
|
||||||
|
<p className="text-xs text-muted-foreground">
|
||||||
|
حذف از فهرست مجاز و افزودن به فهرست سیاه؟
|
||||||
|
</p>
|
||||||
|
<ul className="max-h-40 space-y-1 overflow-y-auto text-sm tracking-wide" dir="ltr">
|
||||||
|
{pendingConflicts.map((phone) => (
|
||||||
|
<li key={phone}>{phone}</li>
|
||||||
|
))}
|
||||||
|
</ul>
|
||||||
|
<div className="flex flex-wrap gap-2">
|
||||||
|
<Button
|
||||||
|
type="button"
|
||||||
|
variant="gradient"
|
||||||
|
disabled={busy}
|
||||||
|
onClick={() => void resolveConflicts()}
|
||||||
|
>
|
||||||
|
{busy ? <Loader2 className="h-4 w-4 animate-spin" /> : null}
|
||||||
|
حل تعارض و ادامه
|
||||||
|
</Button>
|
||||||
|
<Button
|
||||||
|
type="button"
|
||||||
|
variant="outline"
|
||||||
|
disabled={busy}
|
||||||
|
onClick={() => setPendingConflicts([])}
|
||||||
|
>
|
||||||
|
انصراف
|
||||||
|
</Button>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
)}
|
||||||
|
</CardContent>
|
||||||
|
</Card>
|
||||||
|
|
||||||
|
<Card>
|
||||||
|
<CardHeader className="space-y-1 pb-3">
|
||||||
|
<CardTitle className="text-base">فهرست سیاه</CardTitle>
|
||||||
|
<p className="text-xs text-muted-foreground">جستجو و مدیریت شمارههای مسدود.</p>
|
||||||
|
</CardHeader>
|
||||||
|
<CardContent className="space-y-4">
|
||||||
|
<ListToolbar>
|
||||||
|
<Input
|
||||||
|
placeholder="جستجو با شماره…"
|
||||||
|
value={listQ}
|
||||||
|
onChange={(e) => setListQ(e.target.value)}
|
||||||
|
className="max-w-xs text-left tracking-wide"
|
||||||
|
dir="ltr"
|
||||||
|
/>
|
||||||
|
{listQ && (
|
||||||
|
<Button type="button" size="sm" variant="ghost" onClick={() => setListQ("")}>
|
||||||
|
پاک کردن
|
||||||
|
</Button>
|
||||||
|
)}
|
||||||
|
</ListToolbar>
|
||||||
|
|
||||||
|
{isLoading && (
|
||||||
|
<div className="flex justify-center py-8">
|
||||||
|
<Loader2 className="h-5 w-5 animate-spin text-muted-foreground" />
|
||||||
|
</div>
|
||||||
|
)}
|
||||||
|
{!isLoading && entries.length === 0 && (
|
||||||
|
<p className="py-6 text-center text-sm text-muted-foreground">
|
||||||
|
هنوز شمارهای در فهرست سیاه نیست.
|
||||||
|
</p>
|
||||||
|
)}
|
||||||
|
<div className="space-y-2">
|
||||||
|
{entries.map((entry) => (
|
||||||
|
<div
|
||||||
|
key={entry.id}
|
||||||
|
className="flex flex-wrap items-center justify-between gap-3 rounded-lg border border-border px-3 py-3"
|
||||||
|
>
|
||||||
|
<div className="min-w-0 space-y-1">
|
||||||
|
<p className="text-sm font-medium tracking-wide" dir="ltr">
|
||||||
|
{entry.phone}
|
||||||
|
</p>
|
||||||
|
<p className="text-[11px] text-muted-foreground">
|
||||||
|
افزوده: {new Date(entry.createdAt).toLocaleString("fa-IR")}
|
||||||
|
</p>
|
||||||
|
</div>
|
||||||
|
<Button
|
||||||
|
type="button"
|
||||||
|
size="sm"
|
||||||
|
variant="destructive"
|
||||||
|
disabled={deleteBusy === entry.id}
|
||||||
|
onClick={() => void remove(entry.id)}
|
||||||
|
>
|
||||||
|
{deleteBusy === entry.id ? (
|
||||||
|
<Loader2 className="h-3.5 w-3.5 animate-spin" />
|
||||||
|
) : (
|
||||||
|
<Trash2 className="h-3.5 w-3.5" />
|
||||||
|
)}
|
||||||
|
حذف
|
||||||
|
</Button>
|
||||||
|
</div>
|
||||||
|
))}
|
||||||
|
</div>
|
||||||
|
<ListPagination
|
||||||
|
page={listPage}
|
||||||
|
pageSize={listPageSize}
|
||||||
|
total={listTotal}
|
||||||
|
onPageChange={setListPage}
|
||||||
|
/>
|
||||||
|
</CardContent>
|
||||||
|
</Card>
|
||||||
|
|
||||||
|
<Card>
|
||||||
|
<CardHeader className="space-y-1 pb-3">
|
||||||
|
<CardTitle className="text-base">تاریخچه تلاش</CardTitle>
|
||||||
|
<p className="text-xs text-muted-foreground">
|
||||||
|
تلاشهای ثبتنام با شمارهٔ مسدود — فقط برای ممیزی ثبت میشوند.
|
||||||
|
</p>
|
||||||
|
</CardHeader>
|
||||||
|
<CardContent className="space-y-4">
|
||||||
|
<ListToolbar>
|
||||||
|
<Input
|
||||||
|
id="bl-hist-q"
|
||||||
|
value={historyQ}
|
||||||
|
onChange={(e) => setHistoryQ(e.target.value)}
|
||||||
|
dir="ltr"
|
||||||
|
className="max-w-sm text-left tracking-wide"
|
||||||
|
placeholder="۰۹۱۲… یا نام کاربری"
|
||||||
|
/>
|
||||||
|
{historyQ && (
|
||||||
|
<Button type="button" size="sm" variant="ghost" onClick={() => setHistoryQ("")}>
|
||||||
|
پاک کردن
|
||||||
|
</Button>
|
||||||
|
)}
|
||||||
|
</ListToolbar>
|
||||||
|
|
||||||
|
{historyLoading && (
|
||||||
|
<div className="flex justify-center py-8">
|
||||||
|
<Loader2 className="h-5 w-5 animate-spin text-muted-foreground" />
|
||||||
|
</div>
|
||||||
|
)}
|
||||||
|
{!historyLoading && attempts.length === 0 && (
|
||||||
|
<p className="py-6 text-center text-sm text-muted-foreground">
|
||||||
|
هنوز تلاشی ثبت نشده است.
|
||||||
|
</p>
|
||||||
|
)}
|
||||||
|
<div className="space-y-2">
|
||||||
|
{attempts.map((a) => (
|
||||||
|
<div
|
||||||
|
key={a.id}
|
||||||
|
className="space-y-1 rounded-lg border border-border px-3 py-3 text-sm"
|
||||||
|
>
|
||||||
|
<div className="flex flex-wrap items-center justify-between gap-2">
|
||||||
|
<p className="font-medium tracking-wide" dir="ltr">
|
||||||
|
{a.phone}
|
||||||
|
</p>
|
||||||
|
<span className="rounded-md bg-muted px-2 py-0.5 text-[11px] text-muted-foreground">
|
||||||
|
{pathLabel[a.path] ?? a.path}
|
||||||
|
</span>
|
||||||
|
</div>
|
||||||
|
<p className="text-[11px] text-muted-foreground">
|
||||||
|
{new Date(a.attemptedAt).toLocaleString("fa-IR")}
|
||||||
|
{a.ip ? ` · IP: ${a.ip}` : ""}
|
||||||
|
</p>
|
||||||
|
{(a.attemptedUsername || a.attemptedEmail) && (
|
||||||
|
<p className="truncate text-[11px] text-muted-foreground" dir="ltr">
|
||||||
|
{[a.attemptedUsername, a.attemptedEmail].filter(Boolean).join(" · ")}
|
||||||
|
</p>
|
||||||
|
)}
|
||||||
|
</div>
|
||||||
|
))}
|
||||||
|
</div>
|
||||||
|
<ListPagination
|
||||||
|
page={historyPage}
|
||||||
|
pageSize={historyPageSize}
|
||||||
|
total={historyTotal}
|
||||||
|
onPageChange={setHistoryPage}
|
||||||
|
/>
|
||||||
|
</CardContent>
|
||||||
|
</Card>
|
||||||
|
</div>
|
||||||
|
);
|
||||||
|
}
|
||||||
@@ -0,0 +1,250 @@
|
|||||||
|
"use client";
|
||||||
|
|
||||||
|
import { useEffect, useState } from "react";
|
||||||
|
import { useQuery, useQueryClient } from "@tanstack/react-query";
|
||||||
|
import { Plus, Trash2, Trophy } from "lucide-react";
|
||||||
|
import { http, toUserError } from "@/lib/api";
|
||||||
|
import { Button } from "@/components/ui/button";
|
||||||
|
import { Card, CardContent, CardHeader, CardTitle } from "@/components/ui/card";
|
||||||
|
import { Badge } from "@/components/ui/badge";
|
||||||
|
import { Input } from "@/components/ui/input";
|
||||||
|
import { Label } from "@/components/ui/label";
|
||||||
|
import { Switch } from "@/components/ui/switch";
|
||||||
|
import { Skeleton } from "@/components/ui/skeleton";
|
||||||
|
import {
|
||||||
|
Dialog,
|
||||||
|
DialogContent,
|
||||||
|
DialogDescription,
|
||||||
|
DialogFooter,
|
||||||
|
DialogHeader,
|
||||||
|
DialogTitle,
|
||||||
|
} from "@/components/ui/dialog";
|
||||||
|
import { JalaliDateTimePicker, isValidIsoRange } from "@/components/ui/jalali-datetime-picker";
|
||||||
|
import { useConfirm } from "@/components/admin/use-confirm";
|
||||||
|
import { toast } from "@/components/providers";
|
||||||
|
import { formatFaNumber } from "@/lib/utils";
|
||||||
|
|
||||||
|
export type AdminChallenge = {
|
||||||
|
id: number;
|
||||||
|
title: string;
|
||||||
|
description: string;
|
||||||
|
targetXp: number;
|
||||||
|
startsAt: string;
|
||||||
|
endsAt: string;
|
||||||
|
isActive: boolean;
|
||||||
|
createdAt: string;
|
||||||
|
};
|
||||||
|
|
||||||
|
export function ChallengesPanel() {
|
||||||
|
const qc = useQueryClient();
|
||||||
|
const { confirm, dialog } = useConfirm();
|
||||||
|
const [modal, setModal] = useState<AdminChallenge | null>(null);
|
||||||
|
const { data, isLoading, isError, error, refetch } = useQuery({
|
||||||
|
queryKey: ["admin", "challenges"],
|
||||||
|
queryFn: () => http.get<{ challenges: AdminChallenge[] }>("/api/admin/challenges"),
|
||||||
|
});
|
||||||
|
|
||||||
|
const save = async (c: AdminChallenge) => {
|
||||||
|
if (!isValidIsoRange(c.startsAt, c.endsAt)) {
|
||||||
|
toast.error("زمان پایان باید پس از زمان شروع باشد");
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
if (!c.targetXp || c.targetXp <= 0) {
|
||||||
|
toast.error("هدف امتیاز باید بزرگتر از صفر باشد");
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
try {
|
||||||
|
const { createdAt: _c, ...body } = c;
|
||||||
|
if (c.id) await http.put(`/api/admin/challenges/${c.id}`, body);
|
||||||
|
else await http.post("/api/admin/challenges", body);
|
||||||
|
setModal(null);
|
||||||
|
qc.invalidateQueries({ queryKey: ["admin", "challenges"] });
|
||||||
|
qc.invalidateQueries({ queryKey: ["challenges"] });
|
||||||
|
toast.success(c.id ? "چالش بهروزرسانی شد" : "چالش ساخته شد");
|
||||||
|
} catch (e) {
|
||||||
|
toast.error(toUserError(e));
|
||||||
|
}
|
||||||
|
};
|
||||||
|
|
||||||
|
const del = async (c: AdminChallenge) => {
|
||||||
|
if (!(await confirm("حذف چالش", `چالش «${c.title}» حذف شود؟`))) return;
|
||||||
|
try {
|
||||||
|
await http.del(`/api/admin/challenges/${c.id}`);
|
||||||
|
qc.invalidateQueries({ queryKey: ["admin", "challenges"] });
|
||||||
|
toast.success("چالش حذف شد");
|
||||||
|
} catch (e) {
|
||||||
|
toast.error(toUserError(e));
|
||||||
|
}
|
||||||
|
};
|
||||||
|
|
||||||
|
const fmt = (iso: string) =>
|
||||||
|
new Intl.DateTimeFormat("fa-IR", {
|
||||||
|
weekday: "short",
|
||||||
|
month: "long",
|
||||||
|
day: "numeric",
|
||||||
|
hour: "2-digit",
|
||||||
|
minute: "2-digit",
|
||||||
|
}).format(new Date(iso));
|
||||||
|
|
||||||
|
return (
|
||||||
|
<>
|
||||||
|
{dialog}
|
||||||
|
<Card>
|
||||||
|
<CardHeader className="flex-row items-center justify-between gap-4">
|
||||||
|
<div>
|
||||||
|
<CardTitle className="text-base">چالشهای امتیاز</CardTitle>
|
||||||
|
<p className="mt-1 text-xs text-muted-foreground">
|
||||||
|
چالش ماهانه با هدف امتیاز؛ پیشرفت هنرجو با تکمیل آزمونها بهروز میشود.
|
||||||
|
</p>
|
||||||
|
</div>
|
||||||
|
<Button
|
||||||
|
className="gap-1.5"
|
||||||
|
onClick={() =>
|
||||||
|
setModal({
|
||||||
|
id: 0,
|
||||||
|
title: "",
|
||||||
|
description: "",
|
||||||
|
targetXp: 500,
|
||||||
|
startsAt: "",
|
||||||
|
endsAt: "",
|
||||||
|
isActive: true,
|
||||||
|
createdAt: "",
|
||||||
|
})
|
||||||
|
}
|
||||||
|
>
|
||||||
|
<Plus className="h-4 w-4" /> چالش جدید
|
||||||
|
</Button>
|
||||||
|
</CardHeader>
|
||||||
|
<CardContent>
|
||||||
|
{isLoading && (
|
||||||
|
<div className="space-y-3">
|
||||||
|
{[0, 1].map((i) => (
|
||||||
|
<Skeleton key={i} className="h-20 rounded-xl" />
|
||||||
|
))}
|
||||||
|
</div>
|
||||||
|
)}
|
||||||
|
{isError && (
|
||||||
|
<div className="rounded-md border border-destructive/30 bg-destructive/5 p-4 text-sm">
|
||||||
|
<p className="font-medium text-destructive">{toUserError(error)}</p>
|
||||||
|
<Button size="sm" variant="outline" className="mt-2" onClick={() => refetch()}>
|
||||||
|
تلاش دوباره
|
||||||
|
</Button>
|
||||||
|
</div>
|
||||||
|
)}
|
||||||
|
<div className="grid gap-3 sm:grid-cols-2">
|
||||||
|
{(data?.challenges ?? []).map((c) => (
|
||||||
|
<div key={c.id} className="rounded-md border border-border p-4">
|
||||||
|
<div className="flex items-center gap-2">
|
||||||
|
<Trophy className="h-4 w-4 text-gold" />
|
||||||
|
<Badge variant={c.isActive ? "success" : "secondary"}>{c.isActive ? "فعال" : "خاموش"}</Badge>
|
||||||
|
<Badge variant="accent">هدف {formatFaNumber(c.targetXp)} امتیاز</Badge>
|
||||||
|
<div className="ms-auto flex gap-1">
|
||||||
|
<Button size="sm" variant="outline" className="h-7 px-2" onClick={() => setModal({ ...c })}>
|
||||||
|
ویرایش
|
||||||
|
</Button>
|
||||||
|
<Button size="sm" variant="ghost" className="h-7 px-2 text-destructive" onClick={() => del(c)}>
|
||||||
|
<Trash2 className="h-3.5 w-3.5" />
|
||||||
|
</Button>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
<p className="mt-2 font-medium">{c.title}</p>
|
||||||
|
<p className="line-clamp-2 text-xs text-muted-foreground">{c.description || "—"}</p>
|
||||||
|
<p className="mt-1.5 text-xs text-muted-foreground">
|
||||||
|
{fmt(c.startsAt)} تا {fmt(c.endsAt)}
|
||||||
|
</p>
|
||||||
|
</div>
|
||||||
|
))}
|
||||||
|
</div>
|
||||||
|
{!isLoading && !isError && (data?.challenges ?? []).length === 0 && (
|
||||||
|
<p className="py-8 text-center text-sm text-muted-foreground">هنوز چالشی نیست.</p>
|
||||||
|
)}
|
||||||
|
</CardContent>
|
||||||
|
<ChallengeDialog challenge={modal} onClose={() => setModal(null)} onSave={save} />
|
||||||
|
</Card>
|
||||||
|
</>
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
function ChallengeDialog({
|
||||||
|
challenge,
|
||||||
|
onClose,
|
||||||
|
onSave,
|
||||||
|
}: {
|
||||||
|
challenge: AdminChallenge | null;
|
||||||
|
onClose: () => void;
|
||||||
|
onSave: (c: AdminChallenge) => void;
|
||||||
|
}) {
|
||||||
|
const [draft, setDraft] = useState<AdminChallenge | null>(challenge);
|
||||||
|
useEffect(() => setDraft(challenge), [challenge]);
|
||||||
|
const set = (patch: Partial<AdminChallenge>) => setDraft((d) => (d ? { ...d, ...patch } : d));
|
||||||
|
const valid =
|
||||||
|
!!draft?.title.trim() &&
|
||||||
|
!!draft?.startsAt &&
|
||||||
|
!!draft?.endsAt &&
|
||||||
|
(draft?.targetXp ?? 0) > 0 &&
|
||||||
|
isValidIsoRange(draft!.startsAt, draft!.endsAt);
|
||||||
|
|
||||||
|
return (
|
||||||
|
<Dialog open={!!challenge} onOpenChange={(o) => !o && onClose()}>
|
||||||
|
<DialogContent>
|
||||||
|
<DialogHeader>
|
||||||
|
<DialogTitle>{draft?.id ? "ویرایش چالش" : "چالش جدید"}</DialogTitle>
|
||||||
|
<DialogDescription>بازه را با تقویم جلالی تنظیم کنید؛ هنرجویان پیشرفت تا هدف امتیاز را میبینند.</DialogDescription>
|
||||||
|
</DialogHeader>
|
||||||
|
{draft && (
|
||||||
|
<div className="grid gap-3">
|
||||||
|
<div className="space-y-1.5">
|
||||||
|
<Label>عنوان</Label>
|
||||||
|
<Input value={draft.title} onChange={(e) => set({ title: e.target.value })} placeholder="مثلاً چالش ماه مهر" />
|
||||||
|
</div>
|
||||||
|
<div className="space-y-1.5">
|
||||||
|
<Label>توضیحات</Label>
|
||||||
|
<textarea
|
||||||
|
value={draft.description}
|
||||||
|
onChange={(e) => set({ description: e.target.value })}
|
||||||
|
rows={3}
|
||||||
|
className="w-full resize-y rounded-md border border-input bg-background px-3 py-2 text-sm focus:outline-none focus:ring-2 focus:ring-primary"
|
||||||
|
placeholder="هدف و انگیزهٔ چالش…"
|
||||||
|
/>
|
||||||
|
</div>
|
||||||
|
<div className="space-y-1.5">
|
||||||
|
<Label>هدف امتیاز</Label>
|
||||||
|
<Input
|
||||||
|
type="number"
|
||||||
|
dir="ltr"
|
||||||
|
min={1}
|
||||||
|
value={draft.targetXp}
|
||||||
|
onChange={(e) => set({ targetXp: Number(e.target.value) || 0 })}
|
||||||
|
/>
|
||||||
|
</div>
|
||||||
|
<div className="grid grid-cols-1 gap-3 sm:grid-cols-2">
|
||||||
|
<div className="space-y-1.5">
|
||||||
|
<Label>شروع (جلالی)</Label>
|
||||||
|
<JalaliDateTimePicker value={draft.startsAt} onChange={(iso) => set({ startsAt: iso })} aria-label="شروع چالش" />
|
||||||
|
</div>
|
||||||
|
<div className="space-y-1.5">
|
||||||
|
<Label>پایان (جلالی)</Label>
|
||||||
|
<JalaliDateTimePicker value={draft.endsAt} onChange={(iso) => set({ endsAt: iso })} aria-label="پایان چالش" />
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
<div className="flex items-center justify-between rounded-md border border-border px-3 py-2.5">
|
||||||
|
<div>
|
||||||
|
<p className="text-sm font-medium">فعال</p>
|
||||||
|
<p className="text-[11px] text-muted-foreground">فقط چالشهای فعال در بازهٔ زمانی به هنرجو نشان داده میشوند</p>
|
||||||
|
</div>
|
||||||
|
<Switch checked={draft.isActive} onCheckedChange={(v) => set({ isActive: v })} />
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
)}
|
||||||
|
<DialogFooter>
|
||||||
|
<Button variant="outline" onClick={onClose}>
|
||||||
|
انصراف
|
||||||
|
</Button>
|
||||||
|
<Button disabled={!valid} onClick={() => draft && onSave(draft)}>
|
||||||
|
ذخیره چالش
|
||||||
|
</Button>
|
||||||
|
</DialogFooter>
|
||||||
|
</DialogContent>
|
||||||
|
</Dialog>
|
||||||
|
);
|
||||||
|
}
|
||||||
@@ -0,0 +1,379 @@
|
|||||||
|
"use client";
|
||||||
|
|
||||||
|
import { useQuery, useQueryClient } from "@tanstack/react-query";
|
||||||
|
import { useRef, useState } from "react";
|
||||||
|
import { Ban, Copy, Download, Link2, Loader2, Upload } from "lucide-react";
|
||||||
|
import { API_URL, http, refreshSession, throwFromResponse, toUserError } from "@/lib/api";
|
||||||
|
import { useAuth } from "@/lib/auth-store";
|
||||||
|
import { Button } from "@/components/ui/button";
|
||||||
|
import { Card, CardContent, CardHeader, CardTitle } from "@/components/ui/card";
|
||||||
|
import { Badge } from "@/components/ui/badge";
|
||||||
|
import { Label } from "@/components/ui/label";
|
||||||
|
import { toast } from "@/components/providers";
|
||||||
|
import { AdminSelect } from "@/components/admin/list-toolbar";
|
||||||
|
import { formatFaNumber } from "@/lib/utils";
|
||||||
|
|
||||||
|
type ChatExportToken = {
|
||||||
|
id: number;
|
||||||
|
label: string;
|
||||||
|
expiresAt: string;
|
||||||
|
revokedAt?: string | null;
|
||||||
|
usedAt?: string | null;
|
||||||
|
createdAt: string;
|
||||||
|
lastUsedAt?: string | null;
|
||||||
|
active: boolean;
|
||||||
|
token?: string;
|
||||||
|
url?: string;
|
||||||
|
};
|
||||||
|
|
||||||
|
type ChatExportStats = {
|
||||||
|
conversationCount: number;
|
||||||
|
messageCount: number;
|
||||||
|
attachmentBytes: number;
|
||||||
|
bodyBytes: number;
|
||||||
|
estimatedBytes: number;
|
||||||
|
};
|
||||||
|
|
||||||
|
function formatFaBytes(n: number): string {
|
||||||
|
if (!Number.isFinite(n) || n < 0) n = 0;
|
||||||
|
if (n < 1024) return `${formatFaNumber(n)} بایت`;
|
||||||
|
if (n < 1024 * 1024) return `${formatFaNumber(Math.round(n / 1024))} کیلوبایت`;
|
||||||
|
const mb = n / (1024 * 1024);
|
||||||
|
if (mb < 1024) {
|
||||||
|
const rounded = mb >= 10 ? Math.round(mb) : Number(mb.toFixed(1).replace(/\.0$/, ""));
|
||||||
|
return `${formatFaNumber(rounded, mb >= 10 ? 0 : 1)} مگابایت`;
|
||||||
|
}
|
||||||
|
const gb = mb / 1024;
|
||||||
|
const rounded = gb >= 10 ? Math.round(gb) : Number(gb.toFixed(1).replace(/\.0$/, ""));
|
||||||
|
return `${formatFaNumber(rounded, gb >= 10 ? 0 : 1)} گیگابایت`;
|
||||||
|
}
|
||||||
|
|
||||||
|
function formatFaDate(iso: string): string {
|
||||||
|
try {
|
||||||
|
return new Intl.DateTimeFormat("fa-IR", {
|
||||||
|
dateStyle: "medium",
|
||||||
|
timeStyle: "short",
|
||||||
|
}).format(new Date(iso));
|
||||||
|
} catch {
|
||||||
|
return iso;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
export function ChatExportPanel() {
|
||||||
|
const qc = useQueryClient();
|
||||||
|
const fileRef = useRef<HTMLInputElement>(null);
|
||||||
|
const [exportBusy, setExportBusy] = useState(false);
|
||||||
|
const [restoreBusy, setRestoreBusy] = useState(false);
|
||||||
|
const [createBusy, setCreateBusy] = useState(false);
|
||||||
|
const [revokeBusy, setRevokeBusy] = useState<number | null>(null);
|
||||||
|
const [expiresInHours, setExpiresInHours] = useState<1 | 24>(24);
|
||||||
|
const [lastCreatedURL, setLastCreatedURL] = useState("");
|
||||||
|
|
||||||
|
const { data, isLoading } = useQuery({
|
||||||
|
queryKey: ["admin", "chat-export", "tokens"],
|
||||||
|
queryFn: () => http.get<{ items: ChatExportToken[] }>("/api/admin/chat-export/tokens"),
|
||||||
|
});
|
||||||
|
|
||||||
|
const { data: statsData } = useQuery({
|
||||||
|
queryKey: ["admin", "chat-export", "stats"],
|
||||||
|
queryFn: () => http.get<{ stats: ChatExportStats }>("/api/admin/chat-export/stats"),
|
||||||
|
});
|
||||||
|
|
||||||
|
const tokens = data?.items ?? [];
|
||||||
|
const stats = statsData?.stats;
|
||||||
|
|
||||||
|
const copyText = async (text: string, okMsg: string) => {
|
||||||
|
if (!text) return;
|
||||||
|
try {
|
||||||
|
await navigator.clipboard.writeText(text);
|
||||||
|
toast.success(okMsg);
|
||||||
|
} catch {
|
||||||
|
toast.error("کپی ممکن نشد");
|
||||||
|
}
|
||||||
|
};
|
||||||
|
|
||||||
|
const downloadExport = async () => {
|
||||||
|
setExportBusy(true);
|
||||||
|
try {
|
||||||
|
const doFetch = (token: string | null) =>
|
||||||
|
fetch(`${API_URL}/api/admin/chat-export`, {
|
||||||
|
credentials: "include",
|
||||||
|
headers: token ? { Authorization: `Bearer ${token}` } : {},
|
||||||
|
});
|
||||||
|
let res = await doFetch(useAuth.getState().accessToken);
|
||||||
|
if (res.status === 401 && (useAuth.getState().refreshToken || useAuth.getState().user)) {
|
||||||
|
await refreshSession();
|
||||||
|
res = await doFetch(useAuth.getState().accessToken);
|
||||||
|
}
|
||||||
|
if (!res.ok) {
|
||||||
|
await throwFromResponse(res, "دانلود خروجی گفتگوها ممکن نشد");
|
||||||
|
}
|
||||||
|
const blob = await res.blob();
|
||||||
|
const url = URL.createObjectURL(blob);
|
||||||
|
const a = document.createElement("a");
|
||||||
|
a.href = url;
|
||||||
|
a.download = `chat-export-${new Date().toISOString().slice(0, 10)}.zip`;
|
||||||
|
a.click();
|
||||||
|
URL.revokeObjectURL(url);
|
||||||
|
toast.success("آرشیو ZIP گفتگوها دانلود شد");
|
||||||
|
} catch (e) {
|
||||||
|
toast.error(toUserError(e, "دانلود خروجی گفتگوها ممکن نشد"));
|
||||||
|
} finally {
|
||||||
|
setExportBusy(false);
|
||||||
|
}
|
||||||
|
};
|
||||||
|
|
||||||
|
const restoreExport = async (file: File) => {
|
||||||
|
setRestoreBusy(true);
|
||||||
|
try {
|
||||||
|
const isZip =
|
||||||
|
file.name.toLowerCase().endsWith(".zip") ||
|
||||||
|
file.type === "application/zip" ||
|
||||||
|
file.type === "application/x-zip-compressed";
|
||||||
|
const doFetch = async (token: string | null) => {
|
||||||
|
if (isZip) {
|
||||||
|
return fetch(`${API_URL}/api/admin/chat-export/restore`, {
|
||||||
|
method: "POST",
|
||||||
|
credentials: "include",
|
||||||
|
headers: {
|
||||||
|
...(token ? { Authorization: `Bearer ${token}` } : {}),
|
||||||
|
"Content-Type": "application/zip",
|
||||||
|
},
|
||||||
|
body: file,
|
||||||
|
});
|
||||||
|
}
|
||||||
|
const text = await file.text();
|
||||||
|
const payload = JSON.parse(text) as unknown;
|
||||||
|
return fetch(`${API_URL}/api/admin/chat-export/restore`, {
|
||||||
|
method: "POST",
|
||||||
|
credentials: "include",
|
||||||
|
headers: {
|
||||||
|
"Content-Type": "application/json",
|
||||||
|
...(token ? { Authorization: `Bearer ${token}` } : {}),
|
||||||
|
},
|
||||||
|
body: JSON.stringify(payload),
|
||||||
|
});
|
||||||
|
};
|
||||||
|
let res = await doFetch(useAuth.getState().accessToken);
|
||||||
|
if (res.status === 401 && (useAuth.getState().refreshToken || useAuth.getState().user)) {
|
||||||
|
await refreshSession();
|
||||||
|
res = await doFetch(useAuth.getState().accessToken);
|
||||||
|
}
|
||||||
|
if (!res.ok) {
|
||||||
|
await throwFromResponse(res, "بازیابی خروجی گفتگوها ممکن نشد");
|
||||||
|
}
|
||||||
|
const data = (await res.json()) as { imported?: number };
|
||||||
|
toast.success(`${formatFaNumber(data.imported ?? 0)} پیام بازیابی شد`);
|
||||||
|
await qc.invalidateQueries({ queryKey: ["admin", "chat-export", "stats"] });
|
||||||
|
} catch (e) {
|
||||||
|
toast.error(toUserError(e, "بازیابی خروجی گفتگوها ممکن نشد"));
|
||||||
|
} finally {
|
||||||
|
setRestoreBusy(false);
|
||||||
|
}
|
||||||
|
};
|
||||||
|
|
||||||
|
const createLink = async () => {
|
||||||
|
setCreateBusy(true);
|
||||||
|
try {
|
||||||
|
const res = await http.post<{ token: ChatExportToken }>("/api/admin/chat-export/tokens", {
|
||||||
|
expiresInHours,
|
||||||
|
});
|
||||||
|
const url = res.token?.url ?? "";
|
||||||
|
setLastCreatedURL(url);
|
||||||
|
if (url) {
|
||||||
|
await copyText(url, "لینک دانلود ساخته و کپی شد");
|
||||||
|
} else {
|
||||||
|
toast.success("لینک دانلود ساخته شد");
|
||||||
|
}
|
||||||
|
await qc.invalidateQueries({ queryKey: ["admin", "chat-export", "tokens"] });
|
||||||
|
} catch (e) {
|
||||||
|
toast.error(toUserError(e, "ساخت لینک دانلود ممکن نشد"));
|
||||||
|
} finally {
|
||||||
|
setCreateBusy(false);
|
||||||
|
}
|
||||||
|
};
|
||||||
|
|
||||||
|
const revokeLink = async (id: number) => {
|
||||||
|
setRevokeBusy(id);
|
||||||
|
try {
|
||||||
|
await http.post(`/api/admin/chat-export/tokens/${id}/revoke`, {});
|
||||||
|
toast.success("لینک لغو شد");
|
||||||
|
await qc.invalidateQueries({ queryKey: ["admin", "chat-export", "tokens"] });
|
||||||
|
} catch (e) {
|
||||||
|
toast.error(toUserError(e, "لغو لینک ممکن نشد"));
|
||||||
|
} finally {
|
||||||
|
setRevokeBusy(null);
|
||||||
|
}
|
||||||
|
};
|
||||||
|
|
||||||
|
return (
|
||||||
|
<div className="space-y-4">
|
||||||
|
<Card>
|
||||||
|
<CardHeader className="pb-3">
|
||||||
|
<CardTitle className="text-base">آرشیو گفتگوها</CardTitle>
|
||||||
|
</CardHeader>
|
||||||
|
<CardContent className="space-y-3">
|
||||||
|
<p className="text-sm leading-relaxed text-muted-foreground">
|
||||||
|
آرشیو فشردهٔ ZIP شامل <span className="font-medium text-foreground">manifest.json</span> و پوشهٔ{" "}
|
||||||
|
<span className="font-medium text-foreground">attachments/</span> برای همه گفتگوهای دانشجو↔منتور.
|
||||||
|
</p>
|
||||||
|
{stats ? (
|
||||||
|
<p className="rounded-lg border border-border bg-muted/30 px-3 py-2 text-sm leading-relaxed text-foreground">
|
||||||
|
کل تاریخچه تقریباً{" "}
|
||||||
|
<span className="font-medium">{formatFaBytes(stats.estimatedBytes)}</span> حجم دارد
|
||||||
|
{" "}
|
||||||
|
<span className="text-muted-foreground">
|
||||||
|
({formatFaNumber(stats.conversationCount)} گفتگو، {formatFaNumber(stats.messageCount)} پیام
|
||||||
|
{stats.attachmentBytes > 0
|
||||||
|
? `، حدود ${formatFaBytes(stats.attachmentBytes)} پیوست`
|
||||||
|
: ""}
|
||||||
|
). حجم فایل ZIP نزدیک همین مقدار است.
|
||||||
|
</span>
|
||||||
|
</p>
|
||||||
|
) : null}
|
||||||
|
<div className="flex flex-wrap gap-2">
|
||||||
|
<Button type="button" onClick={() => void downloadExport()} disabled={exportBusy}>
|
||||||
|
{exportBusy ? <Loader2 className="h-4 w-4 animate-spin" /> : <Download className="h-4 w-4" />}
|
||||||
|
دانلود آرشیو ZIP
|
||||||
|
</Button>
|
||||||
|
<Button
|
||||||
|
type="button"
|
||||||
|
variant="outline"
|
||||||
|
disabled={restoreBusy}
|
||||||
|
onClick={() => fileRef.current?.click()}
|
||||||
|
>
|
||||||
|
{restoreBusy ? <Loader2 className="h-4 w-4 animate-spin" /> : <Upload className="h-4 w-4" />}
|
||||||
|
بازیابی از ZIP یا JSON
|
||||||
|
</Button>
|
||||||
|
<input
|
||||||
|
ref={fileRef}
|
||||||
|
type="file"
|
||||||
|
accept="application/zip,application/x-zip-compressed,.zip,application/json,.json"
|
||||||
|
className="hidden"
|
||||||
|
onChange={(e) => {
|
||||||
|
const f = e.target.files?.[0];
|
||||||
|
e.target.value = "";
|
||||||
|
if (f) void restoreExport(f);
|
||||||
|
}}
|
||||||
|
/>
|
||||||
|
</div>
|
||||||
|
</CardContent>
|
||||||
|
</Card>
|
||||||
|
|
||||||
|
<Card>
|
||||||
|
<CardHeader className="pb-3">
|
||||||
|
<CardTitle className="text-base">لینک دانلود خارجی</CardTitle>
|
||||||
|
</CardHeader>
|
||||||
|
<CardContent className="space-y-4">
|
||||||
|
<p className="text-sm leading-relaxed text-muted-foreground">
|
||||||
|
لینک یکبارمصرف با مهلت محدود بسازید؛ همان آرشیو ZIP را بدون ورود ادمین میدهد و پس از اولین دانلود باطل میشود (لغو دستی هم ممکن است).
|
||||||
|
</p>
|
||||||
|
<div className="flex flex-wrap items-end gap-3">
|
||||||
|
<div className="space-y-1.5">
|
||||||
|
<Label htmlFor="export-ttl">مهلت اعتبار</Label>
|
||||||
|
<AdminSelect
|
||||||
|
id="export-ttl"
|
||||||
|
value={String(expiresInHours)}
|
||||||
|
onChange={(e) => setExpiresInHours(Number(e.target.value) === 1 ? 1 : 24)}
|
||||||
|
>
|
||||||
|
<option value="1">۱ ساعت</option>
|
||||||
|
<option value="24">۲۴ ساعت</option>
|
||||||
|
</AdminSelect>
|
||||||
|
</div>
|
||||||
|
<Button type="button" onClick={() => void createLink()} disabled={createBusy}>
|
||||||
|
{createBusy ? <Loader2 className="h-4 w-4 animate-spin" /> : <Link2 className="h-4 w-4" />}
|
||||||
|
ایجاد لینک دانلود
|
||||||
|
</Button>
|
||||||
|
</div>
|
||||||
|
{lastCreatedURL ? (
|
||||||
|
<div className="flex flex-col gap-2 sm:flex-row sm:items-center">
|
||||||
|
<code
|
||||||
|
dir="ltr"
|
||||||
|
className="min-w-0 flex-1 truncate rounded-lg border border-border bg-muted/40 px-3 py-2 text-xs font-mono"
|
||||||
|
>
|
||||||
|
{lastCreatedURL}
|
||||||
|
</code>
|
||||||
|
<Button
|
||||||
|
type="button"
|
||||||
|
variant="outline"
|
||||||
|
onClick={() => void copyText(lastCreatedURL, "لینک کپی شد")}
|
||||||
|
>
|
||||||
|
<Copy className="h-4 w-4" />
|
||||||
|
کپی
|
||||||
|
</Button>
|
||||||
|
</div>
|
||||||
|
) : null}
|
||||||
|
|
||||||
|
<div className="space-y-2">
|
||||||
|
<p className="text-sm font-medium">لینکهای فعال و اخیر</p>
|
||||||
|
{isLoading ? (
|
||||||
|
<p className="text-sm text-muted-foreground">در حال بارگذاری…</p>
|
||||||
|
) : tokens.length === 0 ? (
|
||||||
|
<p className="text-sm text-muted-foreground">هنوز لینکی ساخته نشده است.</p>
|
||||||
|
) : (
|
||||||
|
<ul className="space-y-2">
|
||||||
|
{tokens.map((tok) => (
|
||||||
|
<li
|
||||||
|
key={tok.id}
|
||||||
|
className="flex flex-col gap-2 rounded-lg border border-border px-3 py-2 sm:flex-row sm:items-center sm:justify-between"
|
||||||
|
>
|
||||||
|
<div className="min-w-0 space-y-1">
|
||||||
|
<div className="flex flex-wrap items-center gap-2">
|
||||||
|
{tok.active ? (
|
||||||
|
<Badge variant="secondary">فعال</Badge>
|
||||||
|
) : tok.revokedAt ? (
|
||||||
|
<Badge variant="destructive">لغو شده</Badge>
|
||||||
|
) : tok.usedAt ? (
|
||||||
|
<Badge variant="outline">استفاده شده</Badge>
|
||||||
|
) : (
|
||||||
|
<Badge variant="outline">منقضی</Badge>
|
||||||
|
)}
|
||||||
|
<span className="text-xs text-muted-foreground" dir="ltr">
|
||||||
|
تا {formatFaDate(tok.expiresAt)}
|
||||||
|
</span>
|
||||||
|
</div>
|
||||||
|
{tok.url ? (
|
||||||
|
<code dir="ltr" className="block truncate text-xs font-mono text-muted-foreground">
|
||||||
|
{tok.url}
|
||||||
|
</code>
|
||||||
|
) : null}
|
||||||
|
</div>
|
||||||
|
<div className="flex flex-wrap gap-2">
|
||||||
|
{tok.url ? (
|
||||||
|
<Button
|
||||||
|
type="button"
|
||||||
|
size="sm"
|
||||||
|
variant="outline"
|
||||||
|
onClick={() => void copyText(tok.url!, "لینک کپی شد")}
|
||||||
|
>
|
||||||
|
<Copy className="h-3.5 w-3.5" />
|
||||||
|
کپی
|
||||||
|
</Button>
|
||||||
|
) : null}
|
||||||
|
{tok.active ? (
|
||||||
|
<Button
|
||||||
|
type="button"
|
||||||
|
size="sm"
|
||||||
|
variant="outline"
|
||||||
|
disabled={revokeBusy === tok.id}
|
||||||
|
onClick={() => void revokeLink(tok.id)}
|
||||||
|
>
|
||||||
|
{revokeBusy === tok.id ? (
|
||||||
|
<Loader2 className="h-3.5 w-3.5 animate-spin" />
|
||||||
|
) : (
|
||||||
|
<Ban className="h-3.5 w-3.5" />
|
||||||
|
)}
|
||||||
|
لغو
|
||||||
|
</Button>
|
||||||
|
) : null}
|
||||||
|
</div>
|
||||||
|
</li>
|
||||||
|
))}
|
||||||
|
</ul>
|
||||||
|
)}
|
||||||
|
</div>
|
||||||
|
</CardContent>
|
||||||
|
</Card>
|
||||||
|
</div>
|
||||||
|
);
|
||||||
|
}
|
||||||
@@ -0,0 +1,54 @@
|
|||||||
|
"use client";
|
||||||
|
|
||||||
|
import {
|
||||||
|
Dialog,
|
||||||
|
DialogContent,
|
||||||
|
DialogDescription,
|
||||||
|
DialogFooter,
|
||||||
|
DialogHeader,
|
||||||
|
DialogTitle,
|
||||||
|
} from "@/components/ui/dialog";
|
||||||
|
import { Button } from "@/components/ui/button";
|
||||||
|
|
||||||
|
type ConfirmDialogProps = {
|
||||||
|
open: boolean;
|
||||||
|
title: string;
|
||||||
|
description: string;
|
||||||
|
confirmLabel?: string;
|
||||||
|
onConfirm: () => void;
|
||||||
|
onOpenChange: (open: boolean) => void;
|
||||||
|
};
|
||||||
|
|
||||||
|
export function ConfirmDialog({
|
||||||
|
open,
|
||||||
|
title,
|
||||||
|
description,
|
||||||
|
confirmLabel = "حذف",
|
||||||
|
onConfirm,
|
||||||
|
onOpenChange,
|
||||||
|
}: ConfirmDialogProps) {
|
||||||
|
return (
|
||||||
|
<Dialog open={open} onOpenChange={onOpenChange}>
|
||||||
|
<DialogContent className="max-w-md rounded-2xl">
|
||||||
|
<DialogHeader>
|
||||||
|
<DialogTitle>{title}</DialogTitle>
|
||||||
|
<DialogDescription className="leading-relaxed">{description}</DialogDescription>
|
||||||
|
</DialogHeader>
|
||||||
|
<DialogFooter className="gap-2 sm:gap-2">
|
||||||
|
<Button type="button" variant="outline" onClick={() => onOpenChange(false)}>
|
||||||
|
انصراف
|
||||||
|
</Button>
|
||||||
|
<Button
|
||||||
|
type="button"
|
||||||
|
variant="destructive"
|
||||||
|
onClick={() => {
|
||||||
|
onConfirm();
|
||||||
|
}}
|
||||||
|
>
|
||||||
|
{confirmLabel}
|
||||||
|
</Button>
|
||||||
|
</DialogFooter>
|
||||||
|
</DialogContent>
|
||||||
|
</Dialog>
|
||||||
|
);
|
||||||
|
}
|
||||||
@@ -0,0 +1,510 @@
|
|||||||
|
"use client";
|
||||||
|
|
||||||
|
import { useQuery, useQueryClient } from "@tanstack/react-query";
|
||||||
|
import { useEffect, useMemo, useState } from "react";
|
||||||
|
import { Copy, Loader2, Plus, Ban, Pause, Play, Pencil } from "lucide-react";
|
||||||
|
import { http, toUserError } from "@/lib/api";
|
||||||
|
import type { RegistrationInvite } from "@/lib/types";
|
||||||
|
import { Button } from "@/components/ui/button";
|
||||||
|
import { Card, CardContent, CardHeader, CardTitle } from "@/components/ui/card";
|
||||||
|
import { Badge } from "@/components/ui/badge";
|
||||||
|
import { Input } from "@/components/ui/input";
|
||||||
|
import { Label } from "@/components/ui/label";
|
||||||
|
import {
|
||||||
|
Dialog,
|
||||||
|
DialogContent,
|
||||||
|
DialogDescription,
|
||||||
|
DialogFooter,
|
||||||
|
DialogHeader,
|
||||||
|
DialogTitle,
|
||||||
|
} from "@/components/ui/dialog";
|
||||||
|
import { Switch } from "@/components/ui/switch";
|
||||||
|
import { toast } from "@/components/providers";
|
||||||
|
import { formatFaNumber } from "@/lib/utils";
|
||||||
|
import {
|
||||||
|
DEFAULT_PAGE_SIZE,
|
||||||
|
ListPagination,
|
||||||
|
buildPageQuery,
|
||||||
|
type Paginated,
|
||||||
|
} from "@/components/admin/list-pagination";
|
||||||
|
import { ListToolbar } from "@/components/admin/list-toolbar";
|
||||||
|
import { validateInviteLabel } from "@/lib/validation";
|
||||||
|
|
||||||
|
const STATUS_LABEL: Record<RegistrationInvite["status"], string> = {
|
||||||
|
active: "فعال",
|
||||||
|
paused: "متوقف موقت",
|
||||||
|
revoked: "لغو شده",
|
||||||
|
exhausted: "تکمیل شده",
|
||||||
|
};
|
||||||
|
|
||||||
|
function inviteDisplayURL(inv: RegistrationInvite): string {
|
||||||
|
if (inv.url) return inv.url;
|
||||||
|
if (inv.token && typeof window !== "undefined") {
|
||||||
|
return `${window.location.origin}/register/invite/${inv.token}`;
|
||||||
|
}
|
||||||
|
return "";
|
||||||
|
}
|
||||||
|
|
||||||
|
function statusBadgeVariant(
|
||||||
|
status: RegistrationInvite["status"],
|
||||||
|
): "secondary" | "destructive" | "outline" {
|
||||||
|
if (status === "active") return "secondary";
|
||||||
|
if (status === "revoked") return "destructive";
|
||||||
|
return "outline";
|
||||||
|
}
|
||||||
|
|
||||||
|
export function InvitesPanel() {
|
||||||
|
const qc = useQueryClient();
|
||||||
|
const [maxUses, setMaxUses] = useState(10);
|
||||||
|
const [label, setLabel] = useState("");
|
||||||
|
const [expiresInDays, setExpiresInDays] = useState("");
|
||||||
|
const [busy, setBusy] = useState(false);
|
||||||
|
const [actionBusy, setActionBusy] = useState<number | null>(null);
|
||||||
|
const [editing, setEditing] = useState<RegistrationInvite | null>(null);
|
||||||
|
const [editLabel, setEditLabel] = useState("");
|
||||||
|
const [editMaxUses, setEditMaxUses] = useState(1);
|
||||||
|
const [editExpiresInDays, setEditExpiresInDays] = useState("");
|
||||||
|
const [editClearExpires, setEditClearExpires] = useState(false);
|
||||||
|
const [editBusy, setEditBusy] = useState(false);
|
||||||
|
const [page, setPage] = useState(1);
|
||||||
|
const [q, setQ] = useState("");
|
||||||
|
|
||||||
|
useEffect(() => {
|
||||||
|
setPage(1);
|
||||||
|
}, [q]);
|
||||||
|
|
||||||
|
const { data, isLoading } = useQuery({
|
||||||
|
queryKey: ["admin", "invites", q, page],
|
||||||
|
queryFn: () => {
|
||||||
|
const params = new URLSearchParams(buildPageQuery(page));
|
||||||
|
if (q.trim()) params.set("q", q.trim());
|
||||||
|
return http.get<Paginated<RegistrationInvite>>(`/api/admin/invites?${params.toString()}`);
|
||||||
|
},
|
||||||
|
});
|
||||||
|
|
||||||
|
const invites = useMemo(() => data?.items ?? [], [data]);
|
||||||
|
const total = data?.total ?? 0;
|
||||||
|
const pageSize = data?.pageSize ?? DEFAULT_PAGE_SIZE;
|
||||||
|
|
||||||
|
const create = async () => {
|
||||||
|
if (maxUses < 1 || maxUses > 10_000) {
|
||||||
|
toast.error("ظرفیت باید بین ۱ تا ۱۰۰۰۰ باشد");
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
const labelErr = validateInviteLabel(label);
|
||||||
|
if (labelErr) {
|
||||||
|
toast.error(labelErr);
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
setBusy(true);
|
||||||
|
try {
|
||||||
|
const body: { maxUses: number; label?: string; expiresInDays?: number } = {
|
||||||
|
maxUses,
|
||||||
|
};
|
||||||
|
if (label.trim()) body.label = label.trim();
|
||||||
|
const days = Number(expiresInDays);
|
||||||
|
if (expiresInDays.trim() && Number.isFinite(days) && days > 0) {
|
||||||
|
body.expiresInDays = Math.floor(days);
|
||||||
|
}
|
||||||
|
const res = await http.post<{ invite: RegistrationInvite }>("/api/admin/invites", body);
|
||||||
|
const url = inviteDisplayURL(res.invite);
|
||||||
|
if (url) {
|
||||||
|
try {
|
||||||
|
await navigator.clipboard.writeText(url);
|
||||||
|
toast.success("لینک ساخته و کپی شد");
|
||||||
|
} catch {
|
||||||
|
toast.success("لینک عضویت ساخته شد");
|
||||||
|
}
|
||||||
|
} else {
|
||||||
|
toast.success("لینک عضویت ساخته شد");
|
||||||
|
}
|
||||||
|
setLabel("");
|
||||||
|
setExpiresInDays("");
|
||||||
|
setPage(1);
|
||||||
|
qc.invalidateQueries({ queryKey: ["admin", "invites"] });
|
||||||
|
} catch (e) {
|
||||||
|
toast.error(toUserError(e));
|
||||||
|
} finally {
|
||||||
|
setBusy(false);
|
||||||
|
}
|
||||||
|
};
|
||||||
|
|
||||||
|
const copy = async (inv: RegistrationInvite) => {
|
||||||
|
const url = inviteDisplayURL(inv);
|
||||||
|
if (!url) {
|
||||||
|
toast.error("آدرس لینک در دسترس نیست");
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
try {
|
||||||
|
await navigator.clipboard.writeText(url);
|
||||||
|
toast.success("لینک کپی شد");
|
||||||
|
} catch {
|
||||||
|
toast.error("کپی ممکن نشد");
|
||||||
|
}
|
||||||
|
};
|
||||||
|
|
||||||
|
const pause = async (id: number) => {
|
||||||
|
setActionBusy(id);
|
||||||
|
try {
|
||||||
|
await http.post(`/api/admin/invites/${id}/pause`, {});
|
||||||
|
toast.success("لینک موقتاً متوقف شد");
|
||||||
|
qc.invalidateQueries({ queryKey: ["admin", "invites"] });
|
||||||
|
} catch (e) {
|
||||||
|
toast.error(toUserError(e));
|
||||||
|
} finally {
|
||||||
|
setActionBusy(null);
|
||||||
|
}
|
||||||
|
};
|
||||||
|
|
||||||
|
const resume = async (id: number) => {
|
||||||
|
setActionBusy(id);
|
||||||
|
try {
|
||||||
|
await http.post(`/api/admin/invites/${id}/resume`, {});
|
||||||
|
toast.success("لینک دوباره فعال شد");
|
||||||
|
qc.invalidateQueries({ queryKey: ["admin", "invites"] });
|
||||||
|
} catch (e) {
|
||||||
|
toast.error(toUserError(e));
|
||||||
|
} finally {
|
||||||
|
setActionBusy(null);
|
||||||
|
}
|
||||||
|
};
|
||||||
|
|
||||||
|
const revoke = async (id: number) => {
|
||||||
|
setActionBusy(id);
|
||||||
|
try {
|
||||||
|
await http.post(`/api/admin/invites/${id}/revoke`, {});
|
||||||
|
toast.success("لینک لغو شد");
|
||||||
|
qc.invalidateQueries({ queryKey: ["admin", "invites"] });
|
||||||
|
} catch (e) {
|
||||||
|
toast.error(toUserError(e));
|
||||||
|
} finally {
|
||||||
|
setActionBusy(null);
|
||||||
|
}
|
||||||
|
};
|
||||||
|
|
||||||
|
const openEdit = (inv: RegistrationInvite) => {
|
||||||
|
setEditing(inv);
|
||||||
|
setEditLabel(inv.label ?? "");
|
||||||
|
setEditMaxUses(inv.maxUses);
|
||||||
|
setEditExpiresInDays("");
|
||||||
|
setEditClearExpires(false);
|
||||||
|
};
|
||||||
|
|
||||||
|
const saveEdit = async () => {
|
||||||
|
if (!editing) return;
|
||||||
|
if (editMaxUses < editing.usedCount) {
|
||||||
|
toast.error(`ظرفیت نمیتواند کمتر از ${formatFaNumber(editing.usedCount)} (استفادهشده) باشد`);
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
if (editMaxUses < 1 || editMaxUses > 10_000) {
|
||||||
|
toast.error("ظرفیت باید بین ۱ تا ۱۰۰۰۰ باشد");
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
const labelErr = validateInviteLabel(editLabel);
|
||||||
|
if (labelErr) {
|
||||||
|
toast.error(labelErr);
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
setEditBusy(true);
|
||||||
|
try {
|
||||||
|
const body: {
|
||||||
|
label: string;
|
||||||
|
maxUses: number;
|
||||||
|
expiresInDays?: number;
|
||||||
|
clearExpires?: boolean;
|
||||||
|
} = {
|
||||||
|
label: editLabel.trim(),
|
||||||
|
maxUses: editMaxUses,
|
||||||
|
};
|
||||||
|
if (editClearExpires) {
|
||||||
|
body.clearExpires = true;
|
||||||
|
} else {
|
||||||
|
const days = Number(editExpiresInDays);
|
||||||
|
if (editExpiresInDays.trim() && Number.isFinite(days) && days > 0) {
|
||||||
|
body.expiresInDays = Math.floor(days);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
await http.put(`/api/admin/invites/${editing.id}`, body);
|
||||||
|
toast.success("لینک بهروز شد");
|
||||||
|
setEditing(null);
|
||||||
|
qc.invalidateQueries({ queryKey: ["admin", "invites"] });
|
||||||
|
} catch (e) {
|
||||||
|
toast.error(toUserError(e));
|
||||||
|
} finally {
|
||||||
|
setEditBusy(false);
|
||||||
|
}
|
||||||
|
};
|
||||||
|
|
||||||
|
return (
|
||||||
|
<div className="space-y-5">
|
||||||
|
<Card>
|
||||||
|
<CardHeader className="space-y-1 pb-3">
|
||||||
|
<CardTitle className="text-base">ساخت لینک جدید</CardTitle>
|
||||||
|
<p className="text-xs text-muted-foreground">
|
||||||
|
ظرفیت، برچسب و مهلت اختیاری — لینک را بعد از ساخت کپی کنید.
|
||||||
|
</p>
|
||||||
|
</CardHeader>
|
||||||
|
<CardContent className="space-y-4">
|
||||||
|
<div className="grid gap-4 sm:grid-cols-4">
|
||||||
|
<div className="space-y-2">
|
||||||
|
<Label htmlFor="inv-max">ظرفیت (نفر)</Label>
|
||||||
|
<Input
|
||||||
|
id="inv-max"
|
||||||
|
type="number"
|
||||||
|
min={1}
|
||||||
|
max={10000}
|
||||||
|
value={maxUses}
|
||||||
|
onChange={(e) => setMaxUses(Number(e.target.value) || 1)}
|
||||||
|
dir="ltr"
|
||||||
|
className="text-left"
|
||||||
|
/>
|
||||||
|
</div>
|
||||||
|
<div className="space-y-2 sm:col-span-2">
|
||||||
|
<Label htmlFor="inv-label">برچسب (اختیاری)</Label>
|
||||||
|
<Input
|
||||||
|
id="inv-label"
|
||||||
|
value={label}
|
||||||
|
onChange={(e) => setLabel(e.target.value)}
|
||||||
|
placeholder="مثلاً دوره بهار"
|
||||||
|
/>
|
||||||
|
</div>
|
||||||
|
<div className="space-y-2">
|
||||||
|
<Label htmlFor="inv-exp">مهلت روز (اختیاری)</Label>
|
||||||
|
<Input
|
||||||
|
id="inv-exp"
|
||||||
|
type="number"
|
||||||
|
min={1}
|
||||||
|
value={expiresInDays}
|
||||||
|
onChange={(e) => setExpiresInDays(e.target.value)}
|
||||||
|
dir="ltr"
|
||||||
|
className="text-left"
|
||||||
|
placeholder="—"
|
||||||
|
/>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
<Button type="button" variant="gradient" disabled={busy} onClick={() => void create()}>
|
||||||
|
{busy ? <Loader2 className="h-4 w-4 animate-spin" /> : <Plus className="h-4 w-4" />}
|
||||||
|
ساخت لینک
|
||||||
|
</Button>
|
||||||
|
</CardContent>
|
||||||
|
</Card>
|
||||||
|
|
||||||
|
<Card>
|
||||||
|
<CardHeader className="space-y-1 pb-3">
|
||||||
|
<CardTitle className="text-base">لینکهای عضویت</CardTitle>
|
||||||
|
<p className="text-xs text-muted-foreground">مدیریت، کپی و توقف لینکهای ساختهشده.</p>
|
||||||
|
</CardHeader>
|
||||||
|
<CardContent className="space-y-4">
|
||||||
|
<ListToolbar>
|
||||||
|
<Input
|
||||||
|
placeholder="جستجو با برچسب…"
|
||||||
|
value={q}
|
||||||
|
onChange={(e) => setQ(e.target.value)}
|
||||||
|
className="max-w-xs"
|
||||||
|
/>
|
||||||
|
{q && (
|
||||||
|
<Button type="button" size="sm" variant="ghost" onClick={() => setQ("")}>
|
||||||
|
پاک کردن
|
||||||
|
</Button>
|
||||||
|
)}
|
||||||
|
</ListToolbar>
|
||||||
|
{isLoading && (
|
||||||
|
<div className="flex justify-center py-8">
|
||||||
|
<Loader2 className="h-5 w-5 animate-spin text-muted-foreground" />
|
||||||
|
</div>
|
||||||
|
)}
|
||||||
|
{!isLoading && invites.length === 0 && (
|
||||||
|
<p className="py-6 text-center text-sm text-muted-foreground">
|
||||||
|
{q.trim() ? "نتیجهای یافت نشد." : "هنوز لینک عضویتی ساخته نشده است."}
|
||||||
|
</p>
|
||||||
|
)}
|
||||||
|
<div className="space-y-2">
|
||||||
|
{invites.map((inv) => (
|
||||||
|
<div
|
||||||
|
key={inv.id}
|
||||||
|
className="flex flex-wrap items-center justify-between gap-3 rounded-lg border border-border px-3 py-3"
|
||||||
|
>
|
||||||
|
<div className="min-w-0 space-y-1">
|
||||||
|
<div className="flex flex-wrap items-center gap-2">
|
||||||
|
<p className="text-sm font-medium">
|
||||||
|
{inv.label || `لینک #${formatFaNumber(inv.id)}`}
|
||||||
|
</p>
|
||||||
|
<Badge variant={statusBadgeVariant(inv.status)}>{STATUS_LABEL[inv.status]}</Badge>
|
||||||
|
</div>
|
||||||
|
<p className="text-xs text-muted-foreground">
|
||||||
|
استفاده: {formatFaNumber(inv.usedCount)} / {formatFaNumber(inv.maxUses)}
|
||||||
|
{inv.status === "active" || inv.status === "paused"
|
||||||
|
? ` · باقیمانده: ${formatFaNumber(inv.remaining)}`
|
||||||
|
: null}
|
||||||
|
</p>
|
||||||
|
{inv.expiresAt && (
|
||||||
|
<p className="text-[11px] text-muted-foreground">
|
||||||
|
انقضا: {new Date(inv.expiresAt).toLocaleString("fa-IR")}
|
||||||
|
</p>
|
||||||
|
)}
|
||||||
|
{inv.token && (
|
||||||
|
<p className="truncate font-mono text-[11px] text-muted-foreground" dir="ltr">
|
||||||
|
{inviteDisplayURL(inv)}
|
||||||
|
</p>
|
||||||
|
)}
|
||||||
|
</div>
|
||||||
|
<div className="flex flex-wrap items-center gap-2">
|
||||||
|
<Button
|
||||||
|
type="button"
|
||||||
|
size="sm"
|
||||||
|
variant="outline"
|
||||||
|
disabled={!inv.token && !inv.url}
|
||||||
|
onClick={() => void copy(inv)}
|
||||||
|
>
|
||||||
|
<Copy className="h-3.5 w-3.5" />
|
||||||
|
کپی
|
||||||
|
</Button>
|
||||||
|
{(inv.status === "active" || inv.status === "paused") && (
|
||||||
|
<Button
|
||||||
|
type="button"
|
||||||
|
size="sm"
|
||||||
|
variant="outline"
|
||||||
|
disabled={actionBusy === inv.id}
|
||||||
|
onClick={() => openEdit(inv)}
|
||||||
|
>
|
||||||
|
<Pencil className="h-3.5 w-3.5" />
|
||||||
|
ویرایش
|
||||||
|
</Button>
|
||||||
|
)}
|
||||||
|
{inv.status === "active" && (
|
||||||
|
<Button
|
||||||
|
type="button"
|
||||||
|
size="sm"
|
||||||
|
variant="secondary"
|
||||||
|
disabled={actionBusy === inv.id}
|
||||||
|
onClick={() => void pause(inv.id)}
|
||||||
|
>
|
||||||
|
{actionBusy === inv.id ? (
|
||||||
|
<Loader2 className="h-3.5 w-3.5 animate-spin" />
|
||||||
|
) : (
|
||||||
|
<Pause className="h-3.5 w-3.5" />
|
||||||
|
)}
|
||||||
|
توقف موقت
|
||||||
|
</Button>
|
||||||
|
)}
|
||||||
|
{inv.status === "paused" && (
|
||||||
|
<Button
|
||||||
|
type="button"
|
||||||
|
size="sm"
|
||||||
|
variant="secondary"
|
||||||
|
disabled={actionBusy === inv.id}
|
||||||
|
onClick={() => void resume(inv.id)}
|
||||||
|
>
|
||||||
|
{actionBusy === inv.id ? (
|
||||||
|
<Loader2 className="h-3.5 w-3.5 animate-spin" />
|
||||||
|
) : (
|
||||||
|
<Play className="h-3.5 w-3.5" />
|
||||||
|
)}
|
||||||
|
ازسرگیری
|
||||||
|
</Button>
|
||||||
|
)}
|
||||||
|
{(inv.status === "active" || inv.status === "paused") && (
|
||||||
|
<Button
|
||||||
|
type="button"
|
||||||
|
size="sm"
|
||||||
|
variant="destructive"
|
||||||
|
disabled={actionBusy === inv.id}
|
||||||
|
onClick={() => void revoke(inv.id)}
|
||||||
|
>
|
||||||
|
{actionBusy === inv.id ? (
|
||||||
|
<Loader2 className="h-3.5 w-3.5 animate-spin" />
|
||||||
|
) : (
|
||||||
|
<Ban className="h-3.5 w-3.5" />
|
||||||
|
)}
|
||||||
|
لغو
|
||||||
|
</Button>
|
||||||
|
)}
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
))}
|
||||||
|
</div>
|
||||||
|
<ListPagination page={page} pageSize={pageSize} total={total} onPageChange={setPage} />
|
||||||
|
</CardContent>
|
||||||
|
</Card>
|
||||||
|
|
||||||
|
<Dialog open={!!editing} onOpenChange={(o) => !o && setEditing(null)}>
|
||||||
|
<DialogContent className="max-w-md sm:rounded-2xl">
|
||||||
|
<DialogHeader className="text-start">
|
||||||
|
<DialogTitle>ویرایش لینک عضویت</DialogTitle>
|
||||||
|
<DialogDescription>
|
||||||
|
ظرفیت و برچسب را تغییر دهید. ظرفیت نمیتواند کمتر از تعداد استفادهشده باشد.
|
||||||
|
</DialogDescription>
|
||||||
|
</DialogHeader>
|
||||||
|
{editing && (
|
||||||
|
<div className="space-y-3 py-2">
|
||||||
|
<p className="text-xs text-muted-foreground">
|
||||||
|
استفادهشده: {formatFaNumber(editing.usedCount)} از {formatFaNumber(editing.maxUses)}
|
||||||
|
</p>
|
||||||
|
<div className="space-y-1.5">
|
||||||
|
<Label htmlFor="edit-label">برچسب</Label>
|
||||||
|
<Input
|
||||||
|
id="edit-label"
|
||||||
|
value={editLabel}
|
||||||
|
onChange={(e) => setEditLabel(e.target.value)}
|
||||||
|
placeholder="مثلاً دوره بهار"
|
||||||
|
/>
|
||||||
|
</div>
|
||||||
|
<div className="space-y-1.5">
|
||||||
|
<Label htmlFor="edit-max">ظرفیت (نفر)</Label>
|
||||||
|
<Input
|
||||||
|
id="edit-max"
|
||||||
|
type="number"
|
||||||
|
min={editing.usedCount || 1}
|
||||||
|
max={10000}
|
||||||
|
value={editMaxUses}
|
||||||
|
onChange={(e) => setEditMaxUses(Number(e.target.value) || 1)}
|
||||||
|
dir="ltr"
|
||||||
|
className="text-left"
|
||||||
|
/>
|
||||||
|
</div>
|
||||||
|
<div className="space-y-1.5">
|
||||||
|
<Label htmlFor="edit-exp">مهلت جدید (روز از الان — اختیاری)</Label>
|
||||||
|
<Input
|
||||||
|
id="edit-exp"
|
||||||
|
type="number"
|
||||||
|
min={1}
|
||||||
|
value={editExpiresInDays}
|
||||||
|
onChange={(e) => {
|
||||||
|
setEditExpiresInDays(e.target.value);
|
||||||
|
if (e.target.value.trim()) setEditClearExpires(false);
|
||||||
|
}}
|
||||||
|
dir="ltr"
|
||||||
|
className="text-left"
|
||||||
|
placeholder={editing.expiresAt ? "بدون تغییر" : "—"}
|
||||||
|
disabled={editClearExpires}
|
||||||
|
/>
|
||||||
|
</div>
|
||||||
|
{editing.expiresAt && (
|
||||||
|
<label className="flex items-center justify-between gap-3 text-sm text-muted-foreground">
|
||||||
|
<span>حذف مهلت انقضا</span>
|
||||||
|
<Switch
|
||||||
|
checked={editClearExpires}
|
||||||
|
onCheckedChange={(v) => {
|
||||||
|
setEditClearExpires(v);
|
||||||
|
if (v) setEditExpiresInDays("");
|
||||||
|
}}
|
||||||
|
aria-label="حذف مهلت انقضا"
|
||||||
|
/>
|
||||||
|
</label>
|
||||||
|
)}
|
||||||
|
</div>
|
||||||
|
)}
|
||||||
|
<DialogFooter className="gap-2 sm:space-x-0">
|
||||||
|
<Button type="button" variant="outline" onClick={() => setEditing(null)} disabled={editBusy}>
|
||||||
|
انصراف
|
||||||
|
</Button>
|
||||||
|
<Button type="button" variant="gradient" disabled={editBusy} onClick={() => void saveEdit()}>
|
||||||
|
{editBusy ? <Loader2 className="h-4 w-4 animate-spin" /> : null}
|
||||||
|
ذخیره
|
||||||
|
</Button>
|
||||||
|
</DialogFooter>
|
||||||
|
</DialogContent>
|
||||||
|
</Dialog>
|
||||||
|
</div>
|
||||||
|
);
|
||||||
|
}
|
||||||
@@ -0,0 +1,468 @@
|
|||||||
|
"use client";
|
||||||
|
|
||||||
|
import { useMemo, useState } from "react";
|
||||||
|
import { useQuery, useQueryClient } from "@tanstack/react-query";
|
||||||
|
import {
|
||||||
|
AlertTriangle,
|
||||||
|
Flame,
|
||||||
|
Heart,
|
||||||
|
Loader2,
|
||||||
|
Lock,
|
||||||
|
Search,
|
||||||
|
Sparkles,
|
||||||
|
Trophy,
|
||||||
|
Unlock,
|
||||||
|
Users,
|
||||||
|
} from "lucide-react";
|
||||||
|
import { http, toUserError } from "@/lib/api";
|
||||||
|
import type {
|
||||||
|
LearningOverview,
|
||||||
|
StudentLearningRow,
|
||||||
|
UserLearningDetail,
|
||||||
|
} from "@/lib/types";
|
||||||
|
import { Button } from "@/components/ui/button";
|
||||||
|
import { Card, CardContent, CardHeader, CardTitle } from "@/components/ui/card";
|
||||||
|
import { Badge } from "@/components/ui/badge";
|
||||||
|
import { Input } from "@/components/ui/input";
|
||||||
|
import { Skeleton } from "@/components/ui/skeleton";
|
||||||
|
import {
|
||||||
|
Dialog,
|
||||||
|
DialogContent,
|
||||||
|
DialogDescription,
|
||||||
|
DialogHeader,
|
||||||
|
DialogTitle,
|
||||||
|
} from "@/components/ui/dialog";
|
||||||
|
import { toast } from "@/components/providers";
|
||||||
|
import { cn, formatFaNumber } from "@/lib/utils";
|
||||||
|
|
||||||
|
type SortKey = "xp" | "progress" | "activity" | "streak";
|
||||||
|
type FilterKey = "all" | "active" | "locked";
|
||||||
|
|
||||||
|
function pct(n: number) {
|
||||||
|
return `${formatFaNumber(Math.round(n))}٪`;
|
||||||
|
}
|
||||||
|
|
||||||
|
function fmtDate(v?: string) {
|
||||||
|
if (!v) return "—";
|
||||||
|
try {
|
||||||
|
return new Date(v).toLocaleString("fa-IR", { dateStyle: "medium", timeStyle: "short" });
|
||||||
|
} catch {
|
||||||
|
return v;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
export function LearningPanel() {
|
||||||
|
const qc = useQueryClient();
|
||||||
|
const [q, setQ] = useState("");
|
||||||
|
const [filter, setFilter] = useState<FilterKey>("all");
|
||||||
|
const [sort, setSort] = useState<SortKey>("xp");
|
||||||
|
const [selectedId, setSelectedId] = useState<number | null>(null);
|
||||||
|
const [unlocking, setUnlocking] = useState(false);
|
||||||
|
|
||||||
|
const overviewQ = useQuery({
|
||||||
|
queryKey: ["admin", "learning", "overview"],
|
||||||
|
queryFn: () => http.get<{ overview: LearningOverview }>("/api/admin/learning/overview"),
|
||||||
|
retry: 1,
|
||||||
|
});
|
||||||
|
|
||||||
|
const studentsQ = useQuery({
|
||||||
|
queryKey: ["admin", "learning", "students", q],
|
||||||
|
queryFn: () =>
|
||||||
|
http.get<{ students: StudentLearningRow[] }>(
|
||||||
|
`/api/admin/learning/students?q=${encodeURIComponent(q)}`
|
||||||
|
),
|
||||||
|
retry: 1,
|
||||||
|
});
|
||||||
|
|
||||||
|
const detailQ = useQuery({
|
||||||
|
queryKey: ["admin", "learning", "user", selectedId],
|
||||||
|
queryFn: () => http.get<{ learning: UserLearningDetail }>(`/api/admin/users/${selectedId}/learning`),
|
||||||
|
enabled: selectedId != null,
|
||||||
|
retry: 1,
|
||||||
|
});
|
||||||
|
|
||||||
|
const unlockStudent = async (id: number) => {
|
||||||
|
setUnlocking(true);
|
||||||
|
try {
|
||||||
|
await http.post(`/api/admin/users/${id}/unlock`);
|
||||||
|
toast.success("قفل حساب باز شد و جانها بازگردانی شدند");
|
||||||
|
await Promise.all([
|
||||||
|
qc.invalidateQueries({ queryKey: ["admin", "learning"] }),
|
||||||
|
qc.invalidateQueries({ queryKey: ["admin", "learning", "user", id] }),
|
||||||
|
]);
|
||||||
|
} catch (e) {
|
||||||
|
toast.error(toUserError(e, "باز کردن قفل ممکن نشد"));
|
||||||
|
} finally {
|
||||||
|
setUnlocking(false);
|
||||||
|
}
|
||||||
|
};
|
||||||
|
|
||||||
|
const overview = overviewQ.data?.overview;
|
||||||
|
const students = useMemo(() => {
|
||||||
|
let rows = [...(studentsQ.data?.students ?? [])];
|
||||||
|
if (filter === "active") rows = rows.filter((r) => r.isActive && !r.isLocked);
|
||||||
|
if (filter === "locked") rows = rows.filter((r) => r.isLocked);
|
||||||
|
rows.sort((a, b) => {
|
||||||
|
switch (sort) {
|
||||||
|
case "progress":
|
||||||
|
return b.progressPct - a.progressPct;
|
||||||
|
case "streak":
|
||||||
|
return b.streakCurrent - a.streakCurrent;
|
||||||
|
case "activity": {
|
||||||
|
const at = a.lastActivityAt ? new Date(a.lastActivityAt).getTime() : 0;
|
||||||
|
const bt = b.lastActivityAt ? new Date(b.lastActivityAt).getTime() : 0;
|
||||||
|
return bt - at;
|
||||||
|
}
|
||||||
|
default:
|
||||||
|
return b.xp - a.xp;
|
||||||
|
}
|
||||||
|
});
|
||||||
|
return rows;
|
||||||
|
}, [studentsQ.data?.students, filter, sort]);
|
||||||
|
|
||||||
|
const cards = overview
|
||||||
|
? [
|
||||||
|
{ label: "هنرجویان فعال", value: overview.studentsActive, hint: `از ${formatFaNumber(overview.studentsTotal)} نفر`, icon: Users },
|
||||||
|
{ label: "قفلشده", value: overview.studentsLocked, hint: "نیاز به باز کردن قفل", icon: Lock },
|
||||||
|
{ label: "تکمیل درس", value: overview.completions, hint: `${formatFaNumber(overview.lessonsTotal)} درس فعال`, icon: Trophy },
|
||||||
|
{ label: "نرخ قبولی ۷روزه", value: Math.round(overview.passRate7d), hint: `${formatFaNumber(overview.passes7d)}/${formatFaNumber(overview.attempts7d)} تلاش`, icon: Sparkles, suffix: "٪" },
|
||||||
|
{ label: "میانگین تماشا", value: Math.round(overview.avgWatchPct), hint: "درسهای ناتمام", icon: Flame, suffix: "٪" },
|
||||||
|
{ label: "امتیاز ۷روزه", value: overview.xpAwarded7d, hint: `${formatFaNumber(overview.studentsStreaking)} با استریک`, icon: Sparkles },
|
||||||
|
]
|
||||||
|
: [];
|
||||||
|
|
||||||
|
return (
|
||||||
|
<div className="space-y-4">
|
||||||
|
{(overviewQ.isError || studentsQ.isError) && (
|
||||||
|
<div className="flex flex-wrap items-center gap-3 rounded-2xl border border-destructive/40 bg-destructive/5 px-4 py-3 text-sm">
|
||||||
|
<AlertTriangle className="h-4 w-4 shrink-0 text-destructive" />
|
||||||
|
<p className="min-w-0 flex-1 font-bold text-destructive">
|
||||||
|
{toUserError(overviewQ.error ?? studentsQ.error, "بارگذاری داشبورد یادگیری ممکن نشد")}
|
||||||
|
</p>
|
||||||
|
<Button
|
||||||
|
size="sm"
|
||||||
|
variant="outline"
|
||||||
|
onClick={() => {
|
||||||
|
void overviewQ.refetch();
|
||||||
|
void studentsQ.refetch();
|
||||||
|
}}
|
||||||
|
>
|
||||||
|
تلاش دوباره
|
||||||
|
</Button>
|
||||||
|
</div>
|
||||||
|
)}
|
||||||
|
|
||||||
|
<div className="grid gap-3 sm:grid-cols-2 lg:grid-cols-3">
|
||||||
|
{overviewQ.isLoading &&
|
||||||
|
[0, 1, 2, 3, 4, 5].map((i) => <Skeleton key={i} className="h-28 rounded-2xl" />)}
|
||||||
|
{cards.map((c) => (
|
||||||
|
<Card key={c.label}>
|
||||||
|
<CardContent className="pt-5">
|
||||||
|
<div className="mb-3 flex h-10 w-10 items-center justify-center rounded-2xl bg-primary/10 text-primary">
|
||||||
|
<c.icon className="h-5 w-5" />
|
||||||
|
</div>
|
||||||
|
<p className="text-3xl font-black tabular-nums">
|
||||||
|
{formatFaNumber(c.value)}
|
||||||
|
{c.suffix ?? ""}
|
||||||
|
</p>
|
||||||
|
<p className="text-sm font-bold">{c.label}</p>
|
||||||
|
<p className="mt-1 text-[11px] text-muted-foreground">{c.hint}</p>
|
||||||
|
</CardContent>
|
||||||
|
</Card>
|
||||||
|
))}
|
||||||
|
</div>
|
||||||
|
|
||||||
|
<Card>
|
||||||
|
<CardHeader className="flex flex-col gap-3 space-y-0 sm:flex-row sm:items-center sm:justify-between">
|
||||||
|
<div>
|
||||||
|
<CardTitle className="text-base">جدول هنرجویان</CardTitle>
|
||||||
|
<p className="mt-1 text-xs text-muted-foreground">
|
||||||
|
{formatFaNumber(students.length)} نفر · برای جزئیات روی ردیف بزنید
|
||||||
|
</p>
|
||||||
|
</div>
|
||||||
|
<div className="flex flex-wrap items-center gap-2">
|
||||||
|
<div className="relative w-full sm:w-56">
|
||||||
|
<Search className="pointer-events-none absolute start-3 top-1/2 h-4 w-4 -translate-y-1/2 text-muted-foreground" />
|
||||||
|
<Input
|
||||||
|
value={q}
|
||||||
|
onChange={(e) => setQ(e.target.value)}
|
||||||
|
placeholder="جستجوی نام یا ایمیل…"
|
||||||
|
className="h-10 ps-9"
|
||||||
|
/>
|
||||||
|
</div>
|
||||||
|
<select
|
||||||
|
className="h-10 rounded-lg border border-input bg-card px-3 text-sm font-bold outline-none focus-visible:ring-2 focus-visible:ring-ring"
|
||||||
|
value={filter}
|
||||||
|
onChange={(e) => setFilter(e.target.value as FilterKey)}
|
||||||
|
>
|
||||||
|
<option value="all">همه</option>
|
||||||
|
<option value="active">فعال</option>
|
||||||
|
<option value="locked">قفلشده</option>
|
||||||
|
</select>
|
||||||
|
<select
|
||||||
|
className="h-10 rounded-lg border border-input bg-card px-3 text-sm font-bold outline-none focus-visible:ring-2 focus-visible:ring-ring"
|
||||||
|
value={sort}
|
||||||
|
onChange={(e) => setSort(e.target.value as SortKey)}
|
||||||
|
>
|
||||||
|
<option value="xp">مرتبسازی: امتیاز</option>
|
||||||
|
<option value="progress">مرتبسازی: پیشرفت</option>
|
||||||
|
<option value="activity">مرتبسازی: آخرین فعالیت</option>
|
||||||
|
<option value="streak">مرتبسازی: استریک</option>
|
||||||
|
</select>
|
||||||
|
</div>
|
||||||
|
</CardHeader>
|
||||||
|
<CardContent>
|
||||||
|
{studentsQ.isLoading && (
|
||||||
|
<div className="space-y-2">
|
||||||
|
{[0, 1, 2, 3].map((i) => (
|
||||||
|
<Skeleton key={i} className="h-16 rounded-xl" />
|
||||||
|
))}
|
||||||
|
</div>
|
||||||
|
)}
|
||||||
|
<div className="overflow-x-auto">
|
||||||
|
<table className="w-full min-w-[720px] text-sm">
|
||||||
|
<thead>
|
||||||
|
<tr className="border-b border-border text-xs text-muted-foreground">
|
||||||
|
<th className="px-2 py-2 text-right font-bold">هنرجو</th>
|
||||||
|
<th className="px-2 py-2 text-right font-bold">پیشرفت</th>
|
||||||
|
<th className="px-2 py-2 text-right font-bold">امتیاز</th>
|
||||||
|
<th className="px-2 py-2 text-right font-bold">جان</th>
|
||||||
|
<th className="px-2 py-2 text-right font-bold">استریک</th>
|
||||||
|
<th className="px-2 py-2 text-right font-bold">۷روزه</th>
|
||||||
|
<th className="px-2 py-2 text-right font-bold">آخرین فعالیت</th>
|
||||||
|
</tr>
|
||||||
|
</thead>
|
||||||
|
<tbody>
|
||||||
|
{students.map((s) => (
|
||||||
|
<tr
|
||||||
|
key={s.id}
|
||||||
|
className="cursor-pointer border-b border-border/70 transition-colors hover:bg-muted/40"
|
||||||
|
onClick={() => setSelectedId(s.id)}
|
||||||
|
>
|
||||||
|
<td className="px-2 py-3">
|
||||||
|
<div className="flex items-center gap-2">
|
||||||
|
<div className="min-w-0">
|
||||||
|
<p className="truncate font-extrabold">
|
||||||
|
{s.name}
|
||||||
|
{s.isLocked && (
|
||||||
|
<Badge variant="destructive" className="ms-2 px-1.5 text-[10px]">
|
||||||
|
قفل
|
||||||
|
</Badge>
|
||||||
|
)}
|
||||||
|
</p>
|
||||||
|
<p className="truncate text-[11px] text-muted-foreground" dir="ltr">
|
||||||
|
@{s.username}
|
||||||
|
</p>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
</td>
|
||||||
|
<td className="px-2 py-3">
|
||||||
|
<div className="w-28">
|
||||||
|
<div className="mb-1 flex justify-between text-[10px] font-bold">
|
||||||
|
<span>
|
||||||
|
{formatFaNumber(s.lessonsPassed)}/{formatFaNumber(s.lessonsTotal)}
|
||||||
|
</span>
|
||||||
|
<span>{pct(s.progressPct)}</span>
|
||||||
|
</div>
|
||||||
|
<div className="h-2 overflow-hidden rounded-full bg-muted">
|
||||||
|
<div
|
||||||
|
className="h-full rounded-full bg-primary"
|
||||||
|
style={{ width: `${Math.min(100, s.progressPct)}%` }}
|
||||||
|
/>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
</td>
|
||||||
|
<td className="px-2 py-3 font-bold tabular-nums">{formatFaNumber(s.xp)}</td>
|
||||||
|
<td className="px-2 py-3">
|
||||||
|
<span className="inline-flex items-center gap-1 font-bold">
|
||||||
|
<Heart className={cn("h-3.5 w-3.5", s.hearts <= 1 && "fill-current text-destructive")} />
|
||||||
|
{formatFaNumber(s.hearts)}
|
||||||
|
</span>
|
||||||
|
</td>
|
||||||
|
<td className="px-2 py-3 font-bold tabular-nums">{formatFaNumber(s.streakCurrent)}</td>
|
||||||
|
<td className="px-2 py-3 text-xs text-muted-foreground">
|
||||||
|
{formatFaNumber(s.passes7d)}/{formatFaNumber(s.attempts7d)}
|
||||||
|
{s.attempts7d > 0 && (
|
||||||
|
<span className="ms-1 font-bold text-foreground">({pct(s.passRate7d)})</span>
|
||||||
|
)}
|
||||||
|
</td>
|
||||||
|
<td className="px-2 py-3 text-xs text-muted-foreground">{fmtDate(s.lastActivityAt)}</td>
|
||||||
|
</tr>
|
||||||
|
))}
|
||||||
|
</tbody>
|
||||||
|
</table>
|
||||||
|
{students.length === 0 && !studentsQ.isLoading && (
|
||||||
|
<p className="py-10 text-center text-sm text-muted-foreground">هنرجویی یافت نشد.</p>
|
||||||
|
)}
|
||||||
|
</div>
|
||||||
|
</CardContent>
|
||||||
|
</Card>
|
||||||
|
|
||||||
|
<Dialog open={selectedId != null} onOpenChange={(o) => !o && setSelectedId(null)}>
|
||||||
|
<DialogContent className="max-h-[92vh] max-w-3xl overflow-y-auto p-0 sm:rounded-2xl">
|
||||||
|
<DialogHeader className="space-y-1 border-b border-border px-6 py-4 text-start">
|
||||||
|
<DialogTitle className="text-lg font-black">
|
||||||
|
{detailQ.data?.learning.user.name ?? "جزئیات یادگیری"}
|
||||||
|
</DialogTitle>
|
||||||
|
<DialogDescription>
|
||||||
|
{detailQ.data
|
||||||
|
? `@${detailQ.data.learning.user.username} · ${pct(detailQ.data.learning.user.progressPct)} مسیر`
|
||||||
|
: "در حال بارگذاری…"}
|
||||||
|
</DialogDescription>
|
||||||
|
</DialogHeader>
|
||||||
|
<div className="space-y-5 px-6 py-5">
|
||||||
|
{detailQ.isLoading && (
|
||||||
|
<div className="flex items-center justify-center gap-2 py-12 text-muted-foreground">
|
||||||
|
<Loader2 className="h-5 w-5 animate-spin" /> بارگذاری جزئیات
|
||||||
|
</div>
|
||||||
|
)}
|
||||||
|
{detailQ.isError && (
|
||||||
|
<p className="text-sm font-bold text-destructive">{toUserError(detailQ.error)}</p>
|
||||||
|
)}
|
||||||
|
{detailQ.data && (
|
||||||
|
<>
|
||||||
|
{detailQ.data.learning.user.isLocked && (
|
||||||
|
<div className="flex flex-wrap items-center justify-between gap-3 rounded-2xl border-2 border-destructive/30 bg-destructive/5 px-4 py-3">
|
||||||
|
<div className="flex items-start gap-2">
|
||||||
|
<Lock className="mt-0.5 h-4 w-4 shrink-0 text-destructive" />
|
||||||
|
<div>
|
||||||
|
<p className="text-sm font-extrabold text-destructive">حساب قفل است</p>
|
||||||
|
<p className="text-xs text-muted-foreground">
|
||||||
|
پس از باز کردن قفل، سه جان بازمیگردد و مسیر ادامه پیدا میکند.
|
||||||
|
</p>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
<Button
|
||||||
|
size="sm"
|
||||||
|
variant="success"
|
||||||
|
disabled={unlocking}
|
||||||
|
onClick={() => unlockStudent(detailQ.data!.learning.user.id)}
|
||||||
|
className="gap-1.5"
|
||||||
|
>
|
||||||
|
{unlocking ? <Loader2 className="h-3.5 w-3.5 animate-spin" /> : <Unlock className="h-3.5 w-3.5" />}
|
||||||
|
باز کردن قفل
|
||||||
|
</Button>
|
||||||
|
</div>
|
||||||
|
)}
|
||||||
|
|
||||||
|
<div className="grid grid-cols-2 gap-2 sm:grid-cols-4">
|
||||||
|
{[
|
||||||
|
{ l: "امتیاز", v: formatFaNumber(detailQ.data.learning.user.xp) },
|
||||||
|
{ l: "جان", v: formatFaNumber(detailQ.data.learning.user.hearts) },
|
||||||
|
{ l: "استریک", v: formatFaNumber(detailQ.data.learning.user.streakCurrent) },
|
||||||
|
{
|
||||||
|
l: "تکمیل",
|
||||||
|
v: `${formatFaNumber(detailQ.data.learning.user.lessonsPassed)}/${formatFaNumber(detailQ.data.learning.user.lessonsTotal)}`,
|
||||||
|
},
|
||||||
|
].map((x) => (
|
||||||
|
<div key={x.l} className="rounded-2xl border border-border px-3 py-2 text-center">
|
||||||
|
<p className="text-[10px] font-bold text-muted-foreground">{x.l}</p>
|
||||||
|
<p className="text-lg font-black tabular-nums">{x.v}</p>
|
||||||
|
</div>
|
||||||
|
))}
|
||||||
|
</div>
|
||||||
|
|
||||||
|
<section className="space-y-2">
|
||||||
|
<h3 className="text-sm font-black">دروس</h3>
|
||||||
|
<div className="max-h-64 space-y-1.5 overflow-y-auto">
|
||||||
|
{detailQ.data.learning.lessons.map((l) => (
|
||||||
|
<div
|
||||||
|
key={l.lessonId}
|
||||||
|
className="grid grid-cols-[minmax(0,1fr)_auto] items-center gap-2 rounded-xl border border-border px-3 py-2"
|
||||||
|
>
|
||||||
|
<div className="min-w-0">
|
||||||
|
<p className="truncate text-sm font-bold">
|
||||||
|
L{l.lessonId} · {l.title}
|
||||||
|
</p>
|
||||||
|
<p className="truncate text-[11px] text-muted-foreground">{l.chapterTitle}</p>
|
||||||
|
</div>
|
||||||
|
<div className="flex shrink-0 items-center gap-1.5">
|
||||||
|
<span className="text-[10px] font-bold tabular-nums text-muted-foreground">
|
||||||
|
{pct(l.watchedPct)}
|
||||||
|
</span>
|
||||||
|
{l.passedQuiz ? (
|
||||||
|
<Badge variant="success" className="text-[10px]">
|
||||||
|
قبول
|
||||||
|
</Badge>
|
||||||
|
) : l.quizUnlocked ? (
|
||||||
|
<Badge variant="secondary" className="text-[10px]">
|
||||||
|
آزمون باز
|
||||||
|
</Badge>
|
||||||
|
) : (
|
||||||
|
<Badge variant="outline" className="text-[10px]">
|
||||||
|
در حال تماشا
|
||||||
|
</Badge>
|
||||||
|
)}
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
))}
|
||||||
|
</div>
|
||||||
|
</section>
|
||||||
|
|
||||||
|
<section className="space-y-2">
|
||||||
|
<h3 className="text-sm font-black">تلاشهای آزمون</h3>
|
||||||
|
{detailQ.data.learning.attempts.length === 0 ? (
|
||||||
|
<p className="text-xs text-muted-foreground">هنوز تلاشی ثبت نشده.</p>
|
||||||
|
) : (
|
||||||
|
<div className="max-h-48 space-y-1.5 overflow-y-auto">
|
||||||
|
{detailQ.data.learning.attempts.map((a) => (
|
||||||
|
<div
|
||||||
|
key={a.id}
|
||||||
|
className="flex items-center justify-between gap-2 rounded-xl border border-border px-3 py-2 text-xs"
|
||||||
|
>
|
||||||
|
<span className="min-w-0 truncate font-bold">{a.lessonTitle}</span>
|
||||||
|
<span className="shrink-0 tabular-nums text-muted-foreground">
|
||||||
|
{formatFaNumber(a.correctCount)}/{formatFaNumber(a.total)} · {pct(a.scorePct)}
|
||||||
|
</span>
|
||||||
|
<Badge
|
||||||
|
variant={a.status === "passed" ? "success" : "destructive"}
|
||||||
|
className="shrink-0 text-[10px]"
|
||||||
|
>
|
||||||
|
{a.status === "passed" ? "قبول" : "رد"}
|
||||||
|
</Badge>
|
||||||
|
<span className="shrink-0 text-muted-foreground">{fmtDate(a.createdAt)}</span>
|
||||||
|
</div>
|
||||||
|
))}
|
||||||
|
</div>
|
||||||
|
)}
|
||||||
|
</section>
|
||||||
|
|
||||||
|
<section className="grid gap-4 sm:grid-cols-2">
|
||||||
|
<div className="space-y-2">
|
||||||
|
<h3 className="text-sm font-black">امتیازها</h3>
|
||||||
|
<div className="max-h-40 space-y-1 overflow-y-auto text-xs">
|
||||||
|
{detailQ.data.learning.xpEvents.map((x) => (
|
||||||
|
<div key={x.id} className="flex justify-between gap-2 rounded-lg bg-muted/40 px-2 py-1.5">
|
||||||
|
<span className="font-bold text-gold">+{formatFaNumber(x.amount)}</span>
|
||||||
|
<span className="text-muted-foreground">{x.source}</span>
|
||||||
|
<span className="text-muted-foreground">{fmtDate(x.createdAt)}</span>
|
||||||
|
</div>
|
||||||
|
))}
|
||||||
|
{detailQ.data.learning.xpEvents.length === 0 && (
|
||||||
|
<p className="text-muted-foreground">رویداد امتیازی نیست.</p>
|
||||||
|
)}
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
<div className="space-y-2">
|
||||||
|
<h3 className="text-sm font-black">نشستهای تماشا</h3>
|
||||||
|
<div className="max-h-40 space-y-1 overflow-y-auto text-xs">
|
||||||
|
{detailQ.data.learning.sessions.map((s) => (
|
||||||
|
<div key={`${s.lessonId}-${s.startedAt}`} className="rounded-lg bg-muted/40 px-2 py-1.5">
|
||||||
|
<p className="truncate font-bold">{s.lessonTitle}</p>
|
||||||
|
<p className="text-muted-foreground">آخرین ضربان: {fmtDate(s.lastHeartbeatAt)}</p>
|
||||||
|
</div>
|
||||||
|
))}
|
||||||
|
{detailQ.data.learning.sessions.length === 0 && (
|
||||||
|
<p className="text-muted-foreground">نشست تماشایی نیست.</p>
|
||||||
|
)}
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
</section>
|
||||||
|
</>
|
||||||
|
)}
|
||||||
|
</div>
|
||||||
|
</DialogContent>
|
||||||
|
</Dialog>
|
||||||
|
</div>
|
||||||
|
);
|
||||||
|
}
|
||||||
@@ -0,0 +1,83 @@
|
|||||||
|
"use client";
|
||||||
|
|
||||||
|
import { ChevronLeft, ChevronRight } from "lucide-react";
|
||||||
|
import { Button } from "@/components/ui/button";
|
||||||
|
import { formatFaNumber } from "@/lib/utils";
|
||||||
|
|
||||||
|
export type Paginated<T> = {
|
||||||
|
items: T[];
|
||||||
|
total: number;
|
||||||
|
page: number;
|
||||||
|
pageSize: number;
|
||||||
|
};
|
||||||
|
|
||||||
|
export const DEFAULT_PAGE_SIZE = 10;
|
||||||
|
|
||||||
|
export function buildPageQuery(page: number, pageSize = DEFAULT_PAGE_SIZE): string {
|
||||||
|
const params = new URLSearchParams();
|
||||||
|
params.set("page", String(page));
|
||||||
|
params.set("pageSize", String(pageSize));
|
||||||
|
return params.toString();
|
||||||
|
}
|
||||||
|
|
||||||
|
export function ListPagination({
|
||||||
|
page,
|
||||||
|
pageSize,
|
||||||
|
total,
|
||||||
|
onPageChange,
|
||||||
|
className,
|
||||||
|
}: {
|
||||||
|
page: number;
|
||||||
|
pageSize: number;
|
||||||
|
total: number;
|
||||||
|
onPageChange: (page: number) => void;
|
||||||
|
className?: string;
|
||||||
|
}) {
|
||||||
|
if (total <= 0) {
|
||||||
|
return null;
|
||||||
|
}
|
||||||
|
const totalPages = Math.max(1, Math.ceil(total / pageSize));
|
||||||
|
if (totalPages <= 1) {
|
||||||
|
return (
|
||||||
|
<p className={className ?? "mt-2 pt-4 text-xs text-muted-foreground"}>
|
||||||
|
{formatFaNumber(total)} مورد
|
||||||
|
</p>
|
||||||
|
);
|
||||||
|
}
|
||||||
|
return (
|
||||||
|
<div
|
||||||
|
className={
|
||||||
|
className ??
|
||||||
|
"mt-2 flex flex-wrap items-center justify-between gap-3 border-t border-border pt-4 text-sm text-muted-foreground"
|
||||||
|
}
|
||||||
|
>
|
||||||
|
<p>
|
||||||
|
صفحه {formatFaNumber(page)} از {formatFaNumber(totalPages)}
|
||||||
|
{" · "}
|
||||||
|
{formatFaNumber(total)} مورد
|
||||||
|
</p>
|
||||||
|
<div className="flex items-center gap-2">
|
||||||
|
<Button
|
||||||
|
type="button"
|
||||||
|
size="sm"
|
||||||
|
variant="outline"
|
||||||
|
disabled={page <= 1}
|
||||||
|
onClick={() => onPageChange(page - 1)}
|
||||||
|
>
|
||||||
|
<ChevronRight className="h-3.5 w-3.5" />
|
||||||
|
قبلی
|
||||||
|
</Button>
|
||||||
|
<Button
|
||||||
|
type="button"
|
||||||
|
size="sm"
|
||||||
|
variant="outline"
|
||||||
|
disabled={page >= totalPages}
|
||||||
|
onClick={() => onPageChange(page + 1)}
|
||||||
|
>
|
||||||
|
بعدی
|
||||||
|
<ChevronLeft className="h-3.5 w-3.5" />
|
||||||
|
</Button>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
);
|
||||||
|
}
|
||||||
@@ -0,0 +1,38 @@
|
|||||||
|
import type { ReactNode, SelectHTMLAttributes } from "react";
|
||||||
|
import { cn } from "@/lib/utils";
|
||||||
|
|
||||||
|
/** Shared chrome for admin list search / filter rows. */
|
||||||
|
export function ListToolbar({
|
||||||
|
children,
|
||||||
|
className,
|
||||||
|
}: {
|
||||||
|
children: ReactNode;
|
||||||
|
className?: string;
|
||||||
|
}) {
|
||||||
|
return (
|
||||||
|
<div
|
||||||
|
className={cn(
|
||||||
|
"flex flex-wrap items-center gap-2.5 border-b border-border pb-4",
|
||||||
|
className,
|
||||||
|
)}
|
||||||
|
>
|
||||||
|
{children}
|
||||||
|
</div>
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
/** Native select styled to match Input height and radius. */
|
||||||
|
export function AdminSelect({
|
||||||
|
className,
|
||||||
|
...props
|
||||||
|
}: SelectHTMLAttributes<HTMLSelectElement>) {
|
||||||
|
return (
|
||||||
|
<select
|
||||||
|
className={cn(
|
||||||
|
"h-11 rounded-lg border border-input bg-card px-3 font-sans text-sm outline-none transition-colors focus-visible:ring-2 focus-visible:ring-ring disabled:cursor-not-allowed disabled:opacity-50",
|
||||||
|
className,
|
||||||
|
)}
|
||||||
|
{...props}
|
||||||
|
/>
|
||||||
|
);
|
||||||
|
}
|
||||||
@@ -0,0 +1,205 @@
|
|||||||
|
import type { LucideIcon } from "lucide-react";
|
||||||
|
import {
|
||||||
|
Activity,
|
||||||
|
BookOpen,
|
||||||
|
CalendarPlus,
|
||||||
|
DatabaseBackup,
|
||||||
|
FileVideo,
|
||||||
|
GraduationCap,
|
||||||
|
HelpCircle,
|
||||||
|
Link2,
|
||||||
|
Megaphone,
|
||||||
|
Package,
|
||||||
|
Phone,
|
||||||
|
PhoneOff,
|
||||||
|
Settings2,
|
||||||
|
Trophy,
|
||||||
|
UserPlus,
|
||||||
|
Users,
|
||||||
|
} from "lucide-react";
|
||||||
|
|
||||||
|
export type AdminTabId =
|
||||||
|
| "stats"
|
||||||
|
| "learning"
|
||||||
|
| "users"
|
||||||
|
| "orders"
|
||||||
|
| "registration"
|
||||||
|
| "invites"
|
||||||
|
| "whitelist"
|
||||||
|
| "blacklist"
|
||||||
|
| "curriculum"
|
||||||
|
| "questions"
|
||||||
|
| "videos"
|
||||||
|
| "events"
|
||||||
|
| "challenges"
|
||||||
|
| "announce"
|
||||||
|
| "chat-export"
|
||||||
|
| "settings";
|
||||||
|
|
||||||
|
export type AdminNavItem = {
|
||||||
|
id: AdminTabId;
|
||||||
|
label: string;
|
||||||
|
description: string;
|
||||||
|
icon: LucideIcon;
|
||||||
|
adminOnly?: boolean;
|
||||||
|
};
|
||||||
|
|
||||||
|
export type AdminNavGroup = {
|
||||||
|
title: string;
|
||||||
|
items: AdminNavItem[];
|
||||||
|
};
|
||||||
|
|
||||||
|
export const ADMIN_NAV: AdminNavGroup[] = [
|
||||||
|
{
|
||||||
|
title: "نمای کلی",
|
||||||
|
items: [
|
||||||
|
{
|
||||||
|
id: "stats",
|
||||||
|
label: "نمای کلی",
|
||||||
|
description: "آمار سریع سامانه و یادداشتهای کاری ادمین.",
|
||||||
|
icon: Activity,
|
||||||
|
adminOnly: true,
|
||||||
|
},
|
||||||
|
],
|
||||||
|
},
|
||||||
|
{
|
||||||
|
title: "افراد",
|
||||||
|
items: [
|
||||||
|
{
|
||||||
|
id: "learning",
|
||||||
|
label: "پیشرفت یادگیری",
|
||||||
|
description: "وضعیت پیشرفت، استریک و جزئیات مسیر هر هنرجو.",
|
||||||
|
icon: GraduationCap,
|
||||||
|
},
|
||||||
|
{
|
||||||
|
id: "users",
|
||||||
|
label: "کاربران",
|
||||||
|
description: "ساخت، ویرایش، قفل و مدیریت نقش حسابها.",
|
||||||
|
icon: Users,
|
||||||
|
adminOnly: true,
|
||||||
|
},
|
||||||
|
{
|
||||||
|
id: "orders",
|
||||||
|
label: "سفارش فیزیکی",
|
||||||
|
description: "پیگیری درخواست و ارسال گواهینامه فیزیکی.",
|
||||||
|
icon: Package,
|
||||||
|
adminOnly: true,
|
||||||
|
},
|
||||||
|
],
|
||||||
|
},
|
||||||
|
{
|
||||||
|
title: "ثبتنام و دسترسی",
|
||||||
|
items: [
|
||||||
|
{
|
||||||
|
id: "registration",
|
||||||
|
label: "ثبتنام عمومی",
|
||||||
|
description: "روشن/خاموش کردن ثبتنام آزاد در /register و نمای کلی دسترسی.",
|
||||||
|
icon: UserPlus,
|
||||||
|
adminOnly: true,
|
||||||
|
},
|
||||||
|
{
|
||||||
|
id: "invites",
|
||||||
|
label: "لینک عضویت",
|
||||||
|
description: "ساخت و مدیریت لینکهای دعوت با ظرفیت و مهلت.",
|
||||||
|
icon: Link2,
|
||||||
|
adminOnly: true,
|
||||||
|
},
|
||||||
|
{
|
||||||
|
id: "whitelist",
|
||||||
|
label: "فهرست مجاز",
|
||||||
|
description: "شمارههایی که وقتی اجبار فهرست مجاز روشن است اجازه ثبتنام عمومی دارند.",
|
||||||
|
icon: Phone,
|
||||||
|
adminOnly: true,
|
||||||
|
},
|
||||||
|
{
|
||||||
|
id: "blacklist",
|
||||||
|
label: "فهرست سیاه",
|
||||||
|
description: "شمارههایی که همیشه رد میشوند — ثبتنام عمومی و دعوتنامه.",
|
||||||
|
icon: PhoneOff,
|
||||||
|
adminOnly: true,
|
||||||
|
},
|
||||||
|
],
|
||||||
|
},
|
||||||
|
{
|
||||||
|
title: "محتوای دوره",
|
||||||
|
items: [
|
||||||
|
{
|
||||||
|
id: "curriculum",
|
||||||
|
label: "دروس",
|
||||||
|
description: "فصلها، درسها، ترتیب و درخت مهارت.",
|
||||||
|
icon: BookOpen,
|
||||||
|
},
|
||||||
|
{
|
||||||
|
id: "questions",
|
||||||
|
label: "سوالات",
|
||||||
|
description: "بانک سوالات چندگزینهای هر درس.",
|
||||||
|
icon: HelpCircle,
|
||||||
|
},
|
||||||
|
{
|
||||||
|
id: "videos",
|
||||||
|
label: "ویدیوها",
|
||||||
|
description: "آپلود و مدیریت فایلهای ویدیوی دروس.",
|
||||||
|
icon: FileVideo,
|
||||||
|
},
|
||||||
|
],
|
||||||
|
},
|
||||||
|
{
|
||||||
|
title: "ارتباط",
|
||||||
|
items: [
|
||||||
|
{
|
||||||
|
id: "events",
|
||||||
|
label: "رویدادها",
|
||||||
|
description: "کارگاهها و جلسات قابلنمایش در مرکز هنرجو.",
|
||||||
|
icon: CalendarPlus,
|
||||||
|
},
|
||||||
|
{
|
||||||
|
id: "challenges",
|
||||||
|
label: "چالشها",
|
||||||
|
description: "چالش ماهانه با هدف امتیاز برای هنرجویان.",
|
||||||
|
icon: Trophy,
|
||||||
|
adminOnly: true,
|
||||||
|
},
|
||||||
|
{
|
||||||
|
id: "announce",
|
||||||
|
label: "اطلاعیه",
|
||||||
|
description: "ارسال اعلان گروهی به هنرجویان فعال.",
|
||||||
|
icon: Megaphone,
|
||||||
|
adminOnly: true,
|
||||||
|
},
|
||||||
|
{
|
||||||
|
id: "chat-export",
|
||||||
|
label: "آرشیو گفتگوها",
|
||||||
|
description: "خروجی ساختاریافته و لینک دانلود موقت برای همه گفتگوهای پروژه.",
|
||||||
|
icon: DatabaseBackup,
|
||||||
|
adminOnly: true,
|
||||||
|
},
|
||||||
|
],
|
||||||
|
},
|
||||||
|
{
|
||||||
|
title: "سایت",
|
||||||
|
items: [
|
||||||
|
{
|
||||||
|
id: "settings",
|
||||||
|
label: "تنظیمات سایت",
|
||||||
|
description: "حمایت مالی، گواهینامه فیزیکی و اسپانسرهای لندینگ.",
|
||||||
|
icon: Settings2,
|
||||||
|
adminOnly: true,
|
||||||
|
},
|
||||||
|
],
|
||||||
|
},
|
||||||
|
];
|
||||||
|
|
||||||
|
export function findAdminNavItem(id: AdminTabId): AdminNavItem | undefined {
|
||||||
|
return ADMIN_NAV.flatMap((g) => g.items).find((i) => i.id === id);
|
||||||
|
}
|
||||||
|
|
||||||
|
export function defaultAdminTab(_isAdmin: boolean): AdminTabId {
|
||||||
|
return "learning";
|
||||||
|
}
|
||||||
|
|
||||||
|
export function isValidAdminTab(id: string, isAdmin: boolean): id is AdminTabId {
|
||||||
|
const item = findAdminNavItem(id as AdminTabId);
|
||||||
|
if (!item) return false;
|
||||||
|
if (item.adminOnly && !isAdmin) return false;
|
||||||
|
return true;
|
||||||
|
}
|
||||||
Some files were not shown because too many files have changed in this diff Show More
Reference in New Issue
Block a user