Merge commit '06316e17152006aa1395930ad76efb0b86d46657' as 'frontend'

This commit is contained in:
2026-04-27 22:43:56 +02:00
318 changed files with 24246 additions and 0 deletions
+6
View File
@@ -0,0 +1,6 @@
**/.git
**/node_modules
**/Dockerfile*
**/dist
/.angular/cache
**/compose.yml
+16
View File
@@ -0,0 +1,16 @@
# Editor configuration, see https://editorconfig.org
root = true
[*]
charset = utf-8
indent_style = space
indent_size = 2
insert_final_newline = true
trim_trailing_whitespace = true
[*.ts]
quote_type = single
[*.md]
max_line_length = off
trim_trailing_whitespace = false
+44
View File
@@ -0,0 +1,44 @@
# See http://help.github.com/ignore-files/ for more about ignoring files.
# Compiled output
/dist
/tmp
/out-tsc
/bazel-out
# Node
/node_modules
npm-debug.log
yarn-error.log
# IDEs and editors
.idea/
.project
.classpath
.c9/
*.launch
.settings/
*.sublime-workspace
# Visual Studio Code
.vscode/*
!.vscode/settings.json
!.vscode/tasks.json
!.vscode/launch.json
!.vscode/extensions.json
.history/*
# Miscellaneous
/.angular/cache
.sass-cache/
/connect.lock
/coverage
/libpeerconnection.log
testem.log
/typings
# System files
.DS_Store
Thumbs.db
*.old
+8
View File
@@ -0,0 +1,8 @@
angular.json
compose.yml
*.md
tsconfig*.json
*.html
.vscode
package*.json
ngsw-config.json
+6
View File
@@ -0,0 +1,6 @@
{
"arrowParens": "avoid",
"semi": false,
"trailingComma": "es5",
"bracketSpacing": true
}
+4
View File
@@ -0,0 +1,4 @@
{
// For more information, visit: https://go.microsoft.com/fwlink/?linkid=827846
"recommendations": ["angular.ng-template"]
}
+20
View File
@@ -0,0 +1,20 @@
{
// For more information, visit: https://go.microsoft.com/fwlink/?linkid=830387
"version": "0.2.0",
"configurations": [
{
"name": "ng serve",
"type": "pwa-chrome",
"request": "launch",
"preLaunchTask": "npm: start",
"url": "http://localhost:4200/"
},
{
"name": "ng test",
"type": "chrome",
"request": "launch",
"preLaunchTask": "npm: test",
"url": "http://localhost:9876/debug.html"
}
]
}
+42
View File
@@ -0,0 +1,42 @@
{
// For more information, visit: https://go.microsoft.com/fwlink/?LinkId=733558
"version": "2.0.0",
"tasks": [
{
"type": "npm",
"script": "start",
"isBackground": true,
"problemMatcher": {
"owner": "typescript",
"pattern": "$tsc",
"background": {
"activeOnStart": true,
"beginsPattern": {
"regexp": "(.*?)"
},
"endsPattern": {
"regexp": "bundle generation complete"
}
}
}
},
{
"type": "npm",
"script": "test",
"isBackground": true,
"problemMatcher": {
"owner": "typescript",
"pattern": "$tsc",
"background": {
"activeOnStart": true,
"beginsPattern": {
"regexp": "(.*?)"
},
"endsPattern": {
"regexp": "bundle generation complete"
}
}
}
}
]
}
+676
View File
@@ -0,0 +1,676 @@
# GNU GENERAL PUBLIC LICENSE
Version 3, 29 June 2007
Copyright (C) 2007 Free Software Foundation, Inc.
<https://fsf.org/>
Everyone is permitted to copy and distribute verbatim copies of this
license document, but changing it is not allowed.
## Preamble
The GNU General Public License is a free, copyleft license for
software and other kinds of works.
The licenses for most software and other practical works are designed
to take away your freedom to share and change the works. By contrast,
the GNU General Public License is 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. We, the Free Software Foundation, use
the GNU General Public License for most of our software; it applies
also to any other work released this way by its authors. You can apply
it to your programs, too.
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.
To protect your rights, we need to prevent others from denying you
these rights or asking you to surrender the rights. Therefore, you
have certain responsibilities if you distribute copies of the
software, or if you modify it: responsibilities to respect the freedom
of others.
For example, if you distribute copies of such a program, whether
gratis or for a fee, you must pass on to the recipients the same
freedoms that you received. You must make sure that they, too, receive
or can get the source code. And you must show them these terms so they
know their rights.
Developers that use the GNU GPL protect your rights with two steps:
(1) assert copyright on the software, and (2) offer you this License
giving you legal permission to copy, distribute and/or modify it.
For the developers' and authors' protection, the GPL clearly explains
that there is no warranty for this free software. For both users' and
authors' sake, the GPL requires that modified versions be marked as
changed, so that their problems will not be attributed erroneously to
authors of previous versions.
Some devices are designed to deny users access to install or run
modified versions of the software inside them, although the
manufacturer can do so. This is fundamentally incompatible with the
aim of protecting users' freedom to change the software. The
systematic pattern of such abuse occurs in the area of products for
individuals to use, which is precisely where it is most unacceptable.
Therefore, we have designed this version of the GPL to prohibit the
practice for those products. If such problems arise substantially in
other domains, we stand ready to extend this provision to those
domains in future versions of the GPL, as needed to protect the
freedom of users.
Finally, every program is threatened constantly by software patents.
States should not allow patents to restrict development and use of
software on general-purpose computers, but in those that do, we wish
to avoid the special danger that patents applied to a free program
could make it effectively proprietary. To prevent this, the GPL
assures that patents cannot be used to render the program non-free.
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 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. Use with the GNU Affero General Public License.
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 Affero 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 special requirements of the GNU Affero General Public License,
section 13, concerning interaction through a network will apply to the
combination as such.
### 14. Revised Versions of this License.
The Free Software Foundation may publish revised and/or new versions
of the GNU 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 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 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 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 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 General Public License for more details.
You should have received a copy of the GNU General Public License
along with this program. If not, see <https://www.gnu.org/licenses/>.
Also add information on how to contact you by electronic and paper
mail.
If the program does terminal interaction, make it output a short
notice like this when it starts in an interactive mode:
<program> Copyright (C) <year> <name of author>
This program comes with ABSOLUTELY NO WARRANTY; for details type `show w'.
This is free software, and you are welcome to redistribute it
under certain conditions; type `show c' for details.
The hypothetical commands \`show w' and \`show c' should show the
appropriate parts of the General Public License. Of course, your
program's commands might be different; for a GUI interface, you would
use an "about box".
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 GPL, see <https://www.gnu.org/licenses/>.
The GNU General Public License does not permit incorporating your
program into proprietary programs. If your program is a subroutine
library, you may consider it more useful to permit linking proprietary
applications with the library. If this is what you want to do, use the
GNU Lesser General Public License instead of this License. But first,
please read <https://www.gnu.org/licenses/why-not-lgpl.html>.
+23
View File
@@ -0,0 +1,23 @@
FROM node:22.12-alpine AS build
WORKDIR /build
ADD . .
RUN [ "npm", "ci" ]
RUN [ "npm", "run", "build" ]
FROM httpd:alpine AS runtime
RUN apk add --no-cache certbot certbot-apache
COPY httpd.conf /usr/local/apache2/conf/httpd.conf
COPY cli.ini /etc/letsencrypt/cli.ini
COPY --from=build /build/dist/ipwa/browser /usr/local/apache2/htdocs/ipwa
COPY <<EOF /usr/local/apache2/htdocs/ipwa/.htaccess
RewriteEngine on
RewriteCond %{DOCUMENT_ROOT}%{REQUEST_URI} -f [OR]
RewriteCond %{DOCUMENT_ROOT}%{REQUEST_URI} -d
RewriteRule ^ - [L]
RewriteRule ^ /ipwa/index.html
EOF
RUN chmod +rx /usr/local/apache2/htdocs/ipwa/.htaccess
COPY entrypoint.sh entrypoint.sh
EXPOSE 80
EXPOSE 443
CMD ["sh", "entrypoint.sh"]
+4
View File
@@ -0,0 +1,4 @@
# Ipwa
This project was generated with [Angular CLI](https://github.com/angular/angular-cli) version 15.0.4.
This project depends on the [Backend server](https://github.com/Slasherss1/ipwa-backend)
+190
View File
@@ -0,0 +1,190 @@
{
"$schema": "./node_modules/@angular/cli/lib/config/schema.json",
"version": 1,
"newProjectRoot": "projects",
"projects": {
"ipwa": {
"projectType": "application",
"schematics": {
"@schematics/angular:component": {
"style": "scss",
"standalone": false
}
},
"root": "",
"sourceRoot": "src",
"prefix": "app",
"architect": {
"build": {
"builder": "@angular/build:application",
"options": {
"outputPath": {
"base": "dist/ipwa"
},
"index": "src/index.html",
"polyfills": [
"zone.js",
"@angular/localize/init"
],
"tsConfig": "tsconfig.app.json",
"inlineStyleLanguage": "scss",
"assets": [
"src/favicon.ico",
"src/assets",
"src/manifest.webmanifest"
],
"styles": [
"src/styles.scss"
],
"scripts": [],
"serviceWorker": "ngsw-config.json",
"allowedCommonJsDependencies": [
"moment"
],
"browser": "src/main.ts"
},
"configurations": {
"production": {
"budgets": [
{
"type": "initial",
"maximumWarning": "5mb",
"maximumError": "10mb"
},
{
"type": "anyComponentStyle",
"maximumWarning": "5kb",
"maximumError": "10kb"
}
],
"outputHashing": "all"
},
"development": {
"optimization": false,
"extractLicenses": false,
"sourceMap": true,
"namedChunks": true,
"fileReplacements": [
{
"replace": "src/environments/environment.ts",
"with": "src/environments/environment.development.ts"
}
]
},
"swDevelopment": {
"optimization": false,
"extractLicenses": false,
"sourceMap": true,
"namedChunks": true,
"outputHashing": "all",
"fileReplacements": [
{
"replace": "src/environments/environment.ts",
"with": "src/environments/environment.swdev.ts"
}
],
"assets": [
{
"glob": "ngsw-worker.js",
"input": "node_modules/@angular/servce-worker",
"output": "."
},
"src/ngsw.json",
"src/manifest.webmanifest"
]
}
},
"defaultConfiguration": "production"
},
"serve": {
"builder": "@angular/build:dev-server",
"configurations": {
"production": {
"buildTarget": "ipwa:build:production"
},
"development": {
"buildTarget": "ipwa:build:development"
}
},
"options": {
"servePath": "/ipwa/",
"open": false
},
"defaultConfiguration": "development"
},
"extract-i18n": {
"builder": "@angular/build:extract-i18n",
"options": {
"buildTarget": "ipwa:build"
}
},
"test": {
"builder": "@angular/build:karma",
"options": {
"polyfills": [
"zone.js",
"zone.js/testing",
"@angular/localize/init"
],
"tsConfig": "tsconfig.spec.json",
"inlineStyleLanguage": "scss",
"assets": [
"src/favicon.ico",
"src/assets",
"src/manifest.webmanifest"
],
"styles": [
"src/styles.scss"
],
"scripts": [],
"codeCoverage": true
}
},
"lint": {
"builder": "@angular-eslint/builder:lint",
"options": {
"lintFilePatterns": [
"src/**/*.ts",
"src/**/*.html"
]
}
}
},
"i18n": {
"sourceLocale": "pl"
}
}
},
"schematics": {
"@schematics/angular:component": {
"type": "component"
},
"@schematics/angular:directive": {
"type": "directive"
},
"@schematics/angular:service": {
"type": "service"
},
"@schematics/angular:guard": {
"typeSeparator": "."
},
"@schematics/angular:interceptor": {
"typeSeparator": "."
},
"@schematics/angular:module": {
"typeSeparator": "."
},
"@schematics/angular:pipe": {
"typeSeparator": "."
},
"@schematics/angular:resolver": {
"typeSeparator": "."
}
},
"cli": {
"schematicCollections": [
"angular-eslint"
],
"analytics": false
}
}
+3
View File
@@ -0,0 +1,3 @@
agree-tos = true
apache-challenge-location = /usr/local/apache2
apache-server-root = /usr/local/apache2
+11
View File
@@ -0,0 +1,11 @@
services:
front:
build: .
ports:
- 80:80
- 443:443
environment:
- DOMAIN=
- EMAIL=
volumes:
- cert:/etc/letsencrypt
+17
View File
@@ -0,0 +1,17 @@
#!/bin/sh
if [ $DOMAIN -a $EMAIL ]; then
if [ ! -e /usr/local/apache2/.configured ]; then
cat >> /usr/local/apache2/conf/httpd.conf <<EOF
ServerName $DOMAIN
ServerAdmin $EMAIL
<VirtualHost *:80>
ServerName $DOMAIN
</VirtualHost>
EOF
httpd -k start
certbot --apache -n --keep -d $DOMAIN -m $EMAIL
httpd -k stop
touch /usr/local/apache2/.configured
fi
fi
httpd-foreground
+49
View File
@@ -0,0 +1,49 @@
// @ts-check
const eslint = require("@eslint/js");
const tseslint = require("typescript-eslint");
const angular = require("angular-eslint");
module.exports = tseslint.config(
{
files: ["**/*.ts"],
extends: [
eslint.configs.recommended,
...tseslint.configs.recommended,
...tseslint.configs.stylistic,
...angular.configs.tsRecommended,
],
processor: angular.processInlineTemplates,
rules: {
"@angular-eslint/directive-selector": [
"error",
{
type: "attribute",
prefix: "app",
style: "camelCase",
},
],
"@angular-eslint/component-selector": [
"error",
{
type: "element",
prefix: "app",
style: "kebab-case",
},
],
"@angular-eslint/prefer-standalone": [
"off"
],
"no-unexpected-multiline": [
"off"
]
},
},
{
files: ["**/*.html"],
extends: [
...angular.configs.templateRecommended,
...angular.configs.templateAccessibility,
],
rules: {},
}
);
+556
View File
@@ -0,0 +1,556 @@
#
# This is the main Apache HTTP server configuration file. It contains the
# configuration directives that give the server its instructions.
# See <URL:http://httpd.apache.org/docs/2.4/> for detailed information.
# In particular, see
# <URL:http://httpd.apache.org/docs/2.4/mod/directives.html>
# for a discussion of each configuration directive.
#
# Do NOT simply read the instructions in here without understanding
# what they do. They're here only as hints or reminders. If you are unsure
# consult the online docs. You have been warned.
#
# Configuration and logfile names: If the filenames you specify for many
# of the server's control files begin with "/" (or "drive:/" for Win32), the
# server will use that explicit path. If the filenames do *not* begin
# with "/", the value of ServerRoot is prepended -- so "logs/access_log"
# with ServerRoot set to "/usr/local/apache2" will be interpreted by the
# server as "/usr/local/apache2/logs/access_log", whereas "/logs/access_log"
# will be interpreted as '/logs/access_log'.
#
# ServerRoot: The top of the directory tree under which the server's
# configuration, error, and log files are kept.
#
# Do not add a slash at the end of the directory path. If you point
# ServerRoot at a non-local disk, be sure to specify a local disk on the
# Mutex directive, if file-based mutexes are used. If you wish to share the
# same ServerRoot for multiple httpd daemons, you will need to change at
# least PidFile.
#
ServerRoot "/usr/local/apache2"
#
# Mutex: Allows you to set the mutex mechanism and mutex file directory
# for individual mutexes, or change the global defaults
#
# Uncomment and change the directory if mutexes are file-based and the default
# mutex file directory is not on a local disk or is not appropriate for some
# other reason.
#
# Mutex default:logs
#
# Listen: Allows you to bind Apache to specific IP addresses and/or
# ports, instead of the default. See also the <VirtualHost>
# directive.
#
# Change this to Listen on specific IP addresses as shown below to
# prevent Apache from glomming onto all bound IP addresses.
#
#Listen 12.34.56.78:80
Listen 80
Listen 443
#
# Dynamic Shared Object (DSO) Support
#
# To be able to use the functionality of a module which was built as a DSO you
# have to place corresponding `LoadModule' lines at this location so the
# directives contained in it are actually available _before_ they are used.
# Statically compiled modules (those listed by `httpd -l') do not need
# to be loaded here.
#
# Example:
# LoadModule foo_module modules/mod_foo.so
#
LoadModule mpm_event_module modules/mod_mpm_event.so
#LoadModule mpm_prefork_module modules/mod_mpm_prefork.so
#LoadModule mpm_worker_module modules/mod_mpm_worker.so
LoadModule authn_file_module modules/mod_authn_file.so
#LoadModule authn_dbm_module modules/mod_authn_dbm.so
#LoadModule authn_anon_module modules/mod_authn_anon.so
#LoadModule authn_dbd_module modules/mod_authn_dbd.so
#LoadModule authn_socache_module modules/mod_authn_socache.so
LoadModule authn_core_module modules/mod_authn_core.so
LoadModule authz_host_module modules/mod_authz_host.so
LoadModule authz_groupfile_module modules/mod_authz_groupfile.so
LoadModule authz_user_module modules/mod_authz_user.so
#LoadModule authz_dbm_module modules/mod_authz_dbm.so
#LoadModule authz_owner_module modules/mod_authz_owner.so
#LoadModule authz_dbd_module modules/mod_authz_dbd.so
LoadModule authz_core_module modules/mod_authz_core.so
#LoadModule authnz_ldap_module modules/mod_authnz_ldap.so
#LoadModule authnz_fcgi_module modules/mod_authnz_fcgi.so
LoadModule access_compat_module modules/mod_access_compat.so
LoadModule auth_basic_module modules/mod_auth_basic.so
#LoadModule auth_form_module modules/mod_auth_form.so
#LoadModule auth_digest_module modules/mod_auth_digest.so
#LoadModule allowmethods_module modules/mod_allowmethods.so
#LoadModule isapi_module modules/mod_isapi.so
#LoadModule file_cache_module modules/mod_file_cache.so
#LoadModule cache_module modules/mod_cache.so
#LoadModule cache_disk_module modules/mod_cache_disk.so
#LoadModule cache_socache_module modules/mod_cache_socache.so
LoadModule socache_shmcb_module modules/mod_socache_shmcb.so
#LoadModule socache_dbm_module modules/mod_socache_dbm.so
#LoadModule socache_memcache_module modules/mod_socache_memcache.so
#LoadModule socache_redis_module modules/mod_socache_redis.so
#LoadModule watchdog_module modules/mod_watchdog.so
#LoadModule macro_module modules/mod_macro.so
#LoadModule dbd_module modules/mod_dbd.so
#LoadModule bucketeer_module modules/mod_bucketeer.so
#LoadModule dumpio_module modules/mod_dumpio.so
#LoadModule echo_module modules/mod_echo.so
#LoadModule example_hooks_module modules/mod_example_hooks.so
#LoadModule case_filter_module modules/mod_case_filter.so
#LoadModule case_filter_in_module modules/mod_case_filter_in.so
#LoadModule example_ipc_module modules/mod_example_ipc.so
#LoadModule buffer_module modules/mod_buffer.so
#LoadModule data_module modules/mod_data.so
#LoadModule ratelimit_module modules/mod_ratelimit.so
LoadModule reqtimeout_module modules/mod_reqtimeout.so
#LoadModule ext_filter_module modules/mod_ext_filter.so
#LoadModule request_module modules/mod_request.so
#LoadModule include_module modules/mod_include.so
LoadModule filter_module modules/mod_filter.so
#LoadModule reflector_module modules/mod_reflector.so
#LoadModule substitute_module modules/mod_substitute.so
#LoadModule sed_module modules/mod_sed.so
#LoadModule charset_lite_module modules/mod_charset_lite.so
#LoadModule deflate_module modules/mod_deflate.so
#LoadModule xml2enc_module modules/mod_xml2enc.so
#LoadModule proxy_html_module modules/mod_proxy_html.so
#LoadModule brotli_module modules/mod_brotli.so
LoadModule mime_module modules/mod_mime.so
#LoadModule ldap_module modules/mod_ldap.so
LoadModule log_config_module modules/mod_log_config.so
#LoadModule log_debug_module modules/mod_log_debug.so
#LoadModule log_forensic_module modules/mod_log_forensic.so
#LoadModule logio_module modules/mod_logio.so
#LoadModule lua_module modules/mod_lua.so
LoadModule env_module modules/mod_env.so
#LoadModule mime_magic_module modules/mod_mime_magic.so
#LoadModule cern_meta_module modules/mod_cern_meta.so
#LoadModule expires_module modules/mod_expires.so
LoadModule headers_module modules/mod_headers.so
#LoadModule ident_module modules/mod_ident.so
#LoadModule usertrack_module modules/mod_usertrack.so
#LoadModule unique_id_module modules/mod_unique_id.so
LoadModule setenvif_module modules/mod_setenvif.so
LoadModule version_module modules/mod_version.so
#LoadModule remoteip_module modules/mod_remoteip.so
LoadModule proxy_module modules/mod_proxy.so
#LoadModule proxy_connect_module modules/mod_proxy_connect.so
#LoadModule proxy_ftp_module modules/mod_proxy_ftp.so
LoadModule proxy_http_module modules/mod_proxy_http.so
#LoadModule proxy_fcgi_module modules/mod_proxy_fcgi.so
#LoadModule proxy_scgi_module modules/mod_proxy_scgi.so
#LoadModule proxy_uwsgi_module modules/mod_proxy_uwsgi.so
#LoadModule proxy_fdpass_module modules/mod_proxy_fdpass.so
#LoadModule proxy_wstunnel_module modules/mod_proxy_wstunnel.so
#LoadModule proxy_ajp_module modules/mod_proxy_ajp.so
#LoadModule proxy_balancer_module modules/mod_proxy_balancer.so
#LoadModule proxy_express_module modules/mod_proxy_express.so
#LoadModule proxy_hcheck_module modules/mod_proxy_hcheck.so
#LoadModule session_module modules/mod_session.so
#LoadModule session_cookie_module modules/mod_session_cookie.so
#LoadModule session_crypto_module modules/mod_session_crypto.so
#LoadModule session_dbd_module modules/mod_session_dbd.so
#LoadModule slotmem_shm_module modules/mod_slotmem_shm.so
#LoadModule slotmem_plain_module modules/mod_slotmem_plain.so
LoadModule ssl_module modules/mod_ssl.so
#LoadModule optional_hook_export_module modules/mod_optional_hook_export.so
#LoadModule optional_hook_import_module modules/mod_optional_hook_import.so
#LoadModule optional_fn_import_module modules/mod_optional_fn_import.so
#LoadModule optional_fn_export_module modules/mod_optional_fn_export.so
#LoadModule dialup_module modules/mod_dialup.so
#LoadModule http2_module modules/mod_http2.so
#LoadModule proxy_http2_module modules/mod_proxy_http2.so
#LoadModule md_module modules/mod_md.so
#LoadModule lbmethod_byrequests_module modules/mod_lbmethod_byrequests.so
#LoadModule lbmethod_bytraffic_module modules/mod_lbmethod_bytraffic.so
#LoadModule lbmethod_bybusyness_module modules/mod_lbmethod_bybusyness.so
#LoadModule lbmethod_heartbeat_module modules/mod_lbmethod_heartbeat.so
LoadModule unixd_module modules/mod_unixd.so
#LoadModule heartbeat_module modules/mod_heartbeat.so
#LoadModule heartmonitor_module modules/mod_heartmonitor.so
#LoadModule dav_module modules/mod_dav.so
LoadModule status_module modules/mod_status.so
LoadModule autoindex_module modules/mod_autoindex.so
#LoadModule asis_module modules/mod_asis.so
#LoadModule info_module modules/mod_info.so
#LoadModule suexec_module modules/mod_suexec.so
<IfModule !mpm_prefork_module>
#LoadModule cgid_module modules/mod_cgid.so
</IfModule>
<IfModule mpm_prefork_module>
#LoadModule cgi_module modules/mod_cgi.so
</IfModule>
#LoadModule dav_fs_module modules/mod_dav_fs.so
#LoadModule dav_lock_module modules/mod_dav_lock.so
#LoadModule vhost_alias_module modules/mod_vhost_alias.so
#LoadModule negotiation_module modules/mod_negotiation.so
LoadModule dir_module modules/mod_dir.so
#LoadModule imagemap_module modules/mod_imagemap.so
#LoadModule actions_module modules/mod_actions.so
#LoadModule speling_module modules/mod_speling.so
#LoadModule userdir_module modules/mod_userdir.so
LoadModule alias_module modules/mod_alias.so
LoadModule rewrite_module modules/mod_rewrite.so
<IfModule unixd_module>
#
# If you wish httpd to run as a different user or group, you must run
# httpd as root initially and it will switch.
#
# User/Group: The name (or #number) of the user/group to run httpd as.
# It is usually good practice to create a dedicated user and group for
# running httpd, as with most system services.
#
User www-data
Group www-data
</IfModule>
# 'Main' server configuration
#
# The directives in this section set up the values used by the 'main'
# server, which responds to any requests that aren't handled by a
# <VirtualHost> definition. These values also provide defaults for
# any <VirtualHost> containers you may define later in the file.
#
# All of these directives may appear inside <VirtualHost> containers,
# in which case these default settings will be overridden for the
# virtual host being defined.
#
#
# Deny access to the entirety of your server's filesystem. You must
# explicitly permit access to web content directories in other
# <Directory> blocks below.
#
<Directory />
AllowOverride none
Require all denied
</Directory>
#
# Note that from this point forward you must specifically allow
# particular features to be enabled - so if something's not working as
# you might expect, make sure that you have specifically enabled it
# below.
#
#
# DocumentRoot: The directory out of which you will serve your
# documents. By default, all requests are taken from this directory, but
# symbolic links and aliases may be used to point to other locations.
#
DocumentRoot "/usr/local/apache2/htdocs"
<Directory "/usr/local/apache2/htdocs">
#
# Possible values for the Options directive are "None", "All",
# or any combination of:
# Indexes Includes FollowSymLinks SymLinksifOwnerMatch ExecCGI MultiViews
#
# Note that "MultiViews" must be named *explicitly* --- "Options All"
# doesn't give it to you.
#
# The Options directive is both complicated and important. Please see
# http://httpd.apache.org/docs/2.4/mod/core.html#options
# for more information.
#
Options Indexes FollowSymLinks
#
# AllowOverride controls what directives may be placed in .htaccess files.
# It can be "All", "None", or any combination of the keywords:
# AllowOverride FileInfo AuthConfig Limit
#
AllowOverride All
#
# Controls who can get stuff from this server.
#
Require all granted
</Directory>
<Directory "/var/www/certbot/">
Options Indexes FollowSymLinks
AllowOverride None
Require all granted
</Directory>
ProxyPass "/api" "http://api:8080"
ProxyPassReverse "/api" "http://api:8080"
RedirectMatch ^/$ /ipwa
<Location "/.well-known/acme-challenge/">
AliasPreservePath on
Alias "/var/www/certbot/.well-known/acme-challenge/"
</Location>
#
# DirectoryIndex: sets the file that Apache will serve if a directory
# is requested.
#
<IfModule dir_module>
DirectoryIndex index.html
</IfModule>
#
# The following lines prevent .htaccess and .htpasswd files from being
# viewed by Web clients.
#
<Files ".ht*">
Require all denied
</Files>
#
# ErrorLog: The location of the error log file.
# If you do not specify an ErrorLog directive within a <VirtualHost>
# container, error messages relating to that virtual host will be
# logged here. If you *do* define an error logfile for a <VirtualHost>
# container, that host's errors will be logged there and not here.
#
ErrorLog /proc/self/fd/2
#
# LogLevel: Control the number of messages logged to the error_log.
# Possible values include: debug, info, notice, warn, error, crit,
# alert, emerg.
#
LogLevel warn
<IfModule log_config_module>
#
# The following directives define some format nicknames for use with
# a CustomLog directive (see below).
#
LogFormat "%h %l %u %t \"%r\" %>s %b \"%{Referer}i\" \"%{User-Agent}i\"" combined
LogFormat "%h %l %u %t \"%r\" %>s %b" common
<IfModule logio_module>
# You need to enable mod_logio.c to use %I and %O
LogFormat "%h %l %u %t \"%r\" %>s %b \"%{Referer}i\" \"%{User-Agent}i\" %I %O" combinedio
</IfModule>
#
# The location and format of the access logfile (Common Logfile Format).
# If you do not define any access logfiles within a <VirtualHost>
# container, they will be logged here. Contrariwise, if you *do*
# define per-<VirtualHost> access logfiles, transactions will be
# logged therein and *not* in this file.
#
CustomLog /proc/self/fd/1 common
#
# If you prefer a logfile with access, agent, and referer information
# (Combined Logfile Format) you can use the following directive.
#
#CustomLog "logs/access_log" combined
</IfModule>
<IfModule alias_module>
#
# Redirect: Allows you to tell clients about documents that used to
# exist in your server's namespace, but do not anymore. The client
# will make a new request for the document at its new location.
# Example:
# Redirect permanent /foo http://www.example.com/bar
#
# Alias: Maps web paths into filesystem paths and is used to
# access content that does not live under the DocumentRoot.
# Example:
# Alias /webpath /full/filesystem/path
#
# If you include a trailing / on /webpath then the server will
# require it to be present in the URL. You will also likely
# need to provide a <Directory> section to allow access to
# the filesystem path.
#
# ScriptAlias: This controls which directories contain server scripts.
# ScriptAliases are essentially the same as Aliases, except that
# documents in the target directory are treated as applications and
# run by the server when requested rather than as documents sent to the
# client. The same rules about trailing "/" apply to ScriptAlias
# directives as to Alias.
#
ScriptAlias /cgi-bin/ "/usr/local/apache2/cgi-bin/"
</IfModule>
<IfModule cgid_module>
#
# ScriptSock: On threaded servers, designate the path to the UNIX
# socket used to communicate with the CGI daemon of mod_cgid.
#
#Scriptsock cgisock
</IfModule>
#
# "/usr/local/apache2/cgi-bin" should be changed to whatever your ScriptAliased
# CGI directory exists, if you have that configured.
#
<Directory "/usr/local/apache2/cgi-bin">
AllowOverride None
Options None
Require all granted
</Directory>
<IfModule headers_module>
#
# Avoid passing HTTP_PROXY environment to CGI's on this or any proxied
# backend servers which have lingering "httpoxy" defects.
# 'Proxy' request header is undefined by the IETF, not listed by IANA
#
RequestHeader unset Proxy early
</IfModule>
<IfModule mime_module>
#
# TypesConfig points to the file containing the list of mappings from
# filename extension to MIME-type.
#
TypesConfig conf/mime.types
#
# AddType allows you to add to or override the MIME configuration
# file specified in TypesConfig for specific file types.
#
#AddType application/x-gzip .tgz
#
# AddEncoding allows you to have certain browsers uncompress
# information on the fly. Note: Not all browsers support this.
#
#AddEncoding x-compress .Z
#AddEncoding x-gzip .gz .tgz
#
# If the AddEncoding directives above are commented-out, then you
# probably should define those extensions to indicate media types:
#
AddType application/x-compress .Z
AddType application/x-gzip .gz .tgz
#
# AddHandler allows you to map certain file extensions to "handlers":
# actions unrelated to filetype. These can be either built into the server
# or added with the Action directive (see below)
#
# To use CGI scripts outside of ScriptAliased directories:
# (You will also need to add "ExecCGI" to the "Options" directive.)
#
#AddHandler cgi-script .cgi
# For type maps (negotiated resources):
#AddHandler type-map var
#
# Filters allow you to process content before it is sent to the client.
#
# To parse .shtml files for server-side includes (SSI):
# (You will also need to add "Includes" to the "Options" directive.)
#
#AddType text/html .shtml
#AddOutputFilter INCLUDES .shtml
</IfModule>
#
# The mod_mime_magic module allows the server to use various hints from the
# contents of the file itself to determine its type. The MIMEMagicFile
# directive tells the module where the hint definitions are located.
#
#MIMEMagicFile conf/magic
#
# Customizable error responses come in three flavors:
# 1) plain text 2) local redirects 3) external redirects
#
# Some examples:
#ErrorDocument 500 "The server made a boo boo."
#ErrorDocument 404 /missing.html
#ErrorDocument 404 "/cgi-bin/missing_handler.pl"
#ErrorDocument 402 http://www.example.com/subscription_info.html
#
#
# MaxRanges: Maximum number of Ranges in a request before
# returning the entire resource, or one of the special
# values 'default', 'none' or 'unlimited'.
# Default setting is to accept 200 Ranges.
#MaxRanges unlimited
#
# EnableMMAP and EnableSendfile: On systems that support it,
# memory-mapping or the sendfile syscall may be used to deliver
# files. This usually improves server performance, but must
# be turned off when serving from networked-mounted
# filesystems or if support for these functions is otherwise
# broken on your system.
# Defaults: EnableMMAP On, EnableSendfile Off
#
#EnableMMAP off
#EnableSendfile on
# Supplemental configuration
#
# The configuration files in the conf/extra/ directory can be
# included to add extra features or to modify the default configuration of
# the server, or you may simply copy their contents here and change as
# necessary.
# Server-pool management (MPM specific)
#Include conf/extra/httpd-mpm.conf
# Multi-language error messages
#Include conf/extra/httpd-multilang-errordoc.conf
# Fancy directory listings
#Include conf/extra/httpd-autoindex.conf
# Language settings
#Include conf/extra/httpd-languages.conf
# User home directories
#Include conf/extra/httpd-userdir.conf
# Real-time info on requests and configuration
#Include conf/extra/httpd-info.conf
# Virtual hosts
#Include conf/extra/httpd-vhosts.conf
# Local access to the Apache HTTP Server Manual
#Include conf/extra/httpd-manual.conf
# Distributed authoring and versioning (WebDAV)
#Include conf/extra/httpd-dav.conf
# Various default settings
#Include conf/extra/httpd-default.conf
# Configure mod_proxy_html to understand HTML4/XHTML1
<IfModule proxy_html_module>
Include conf/extra/proxy-html.conf
</IfModule>
# Secure (SSL/TLS) connections
#Include conf/extra/httpd-ssl.conf
#
# Note: The following must must be present to support
# starting without SSL on platforms with no /dev/random equivalent
# but a statically compiled-in mod_ssl.
#
SSLSessionCache "shmcb:/usr/local/apache2/logs/ssl_cache(512000)"
SSLSessionCacheTimeout 300
<IfModule ssl_module>
SSLRandomSeed startup builtin
SSLRandomSeed connect builtin
</IfModule>
+29
View File
@@ -0,0 +1,29 @@
{
"$schema": "./node_modules/@angular/service-worker/config/schema.json",
"index": "/ipwa/index.html",
"assetGroups": [
{
"name": "app",
"installMode": "prefetch",
"resources": {
"files": [
"/ipwa/favicon.ico",
"/ipwa/manifest.webmanifest",
"/ipwa/*.css",
"/ipwa/*.js"
]
}
},
{
"name": "assets",
"installMode": "lazy",
"updateMode": "prefetch",
"resources": {
"files": [
"/ipwa/assets/**",
"/ipwa/**/*.(svg|cur|jpg|jpeg|png|apng|webp|avif|gif|otf|ttf|woff|woff2)"
]
}
}
]
}
+11821
View File
File diff suppressed because it is too large Load Diff
+55
View File
@@ -0,0 +1,55 @@
{
"name": "ipwa",
"version": "2.1.0",
"license": "GPL-3.0-or-later",
"scripts": {
"ng": "ng",
"start": "ng serve",
"build": "ng build -c production",
"watch": "ng build --watch --configuration development",
"test": "ng test",
"ci": "ng test --no-watch --no-progress --browsers=ChromiumHeadless",
"lint": "ng lint"
},
"private": true,
"dependencies": {
"@angular/animations": "^20.0.2",
"@angular/cdk": "^20.0.2",
"@angular/cli": "^20.3.18",
"@angular/common": "^20.3.14",
"@angular/compiler": "^20.3.16",
"@angular/core": "^20.3.17",
"@angular/forms": "^20.0.2",
"@angular/material": "^20.0.2",
"@angular/material-luxon-adapter": "^20.0.2",
"@angular/platform-browser": "^20.0.2",
"@angular/platform-browser-dynamic": "^20.0.2",
"@angular/router": "^20.0.2",
"@angular/service-worker": "^20.0.2",
"luxon": "^3.6.1",
"marked": "^12.0.1",
"rxjs": "~7.5.0",
"tslib": "^2.3.0",
"underscore": "^1.13.8",
"zone.js": "~0.15.1"
},
"devDependencies": {
"@angular/build": "^20.0.1",
"@angular/compiler-cli": "^20.0.2",
"@angular/localize": "^20.0.2",
"@types/jasmine": "~4.3.0",
"@types/luxon": "^3.6.2",
"@types/underscore": "^1.13.0",
"angular-eslint": "20.0.0",
"eslint": "^9.28.0",
"jasmine-core": "~4.5.0",
"karma": "~6.4.0",
"karma-chrome-launcher": "~3.1.0",
"karma-coverage": "~2.2.0",
"karma-jasmine": "~5.1.0",
"karma-jasmine-html-reporter": "~2.0.0",
"prettier": "3.5.3",
"typescript": "~5.8.3",
"typescript-eslint": "8.33.1"
}
}
+205
View File
@@ -0,0 +1,205 @@
// This file was generated by running 'ng generate @angular/material:theme-color'.
// Proceed with caution if making changes to this file.
@use 'sass:map';
@use '@angular/material' as mat;
// Note: Color palettes are generated from primary: #3850b0, secondary: #c5c330
$_palettes: (
primary: (
0: #000000,
10: #001354,
20: #002486,
25: #143192,
30: #243e9e,
35: #324aaa,
40: #3f57b7,
50: #5970d2,
60: #748aee,
70: #93a6ff,
80: #b8c4ff,
90: #dde1ff,
95: #efefff,
98: #fbf8ff,
99: #fefbff,
100: #ffffff,
),
secondary: (
0: #000000,
10: #1d1d00,
20: #333200,
25: #3e3d00,
30: #4a4900,
35: #565500,
40: #636100,
50: #7c7b00,
60: #979500,
70: #b2b01a,
80: #cecc39,
90: #ebe954,
95: #f9f761,
98: #fffcc4,
99: #fffbff,
100: #ffffff,
),
tertiary: (
0: #000000,
10: #36003d,
20: #560860,
25: #63196c,
30: #702678,
35: #7e3385,
40: #8b4092,
50: #a759ad,
60: #c473c9,
70: #e28de5,
80: #fdaaff,
90: #ffd6fc,
95: #ffebfa,
98: #fff7fa,
99: #fffbff,
100: #ffffff,
),
neutral: (
0: #000000,
10: #1a1b21,
20: #2f3037,
25: #3a3b42,
30: #46464d,
35: #525259,
40: #5e5e65,
50: #76767e,
60: #909098,
70: #abaab3,
80: #c7c5ce,
90: #e3e1ea,
95: #f1f0f9,
98: #fbf8ff,
99: #fefbff,
100: #ffffff,
4: #0d0e14,
6: #121319,
12: #1e1f25,
17: #292a30,
22: #34343b,
24: #38393f,
87: #dad9e2,
92: #e9e7f0,
94: #eeedf6,
96: #f4f2fb,
),
neutral-variant: (
0: #000000,
10: #191b26,
20: #2e303b,
25: #393b47,
30: #444652,
35: #50525e,
40: #5c5e6a,
50: #757684,
60: #8f909e,
70: #a9aab9,
80: #c5c5d4,
90: #e1e1f1,
95: #f0efff,
98: #fbf8ff,
99: #fefbff,
100: #ffffff,
),
error: (
0: #000000,
10: #410002,
20: #690005,
25: #7e0007,
30: #93000a,
35: #a80710,
40: #ba1a1a,
50: #de3730,
60: #ff5449,
70: #ff897d,
80: #ffb4ab,
90: #ffdad6,
95: #ffedea,
98: #fff8f7,
99: #fffbff,
100: #ffffff,
),
);
$_rest: (
secondary: map.get($_palettes, secondary),
neutral: map.get($_palettes, neutral),
neutral-variant: map.get($_palettes, neutral-variant),
error: map.get($_palettes, error),
);
$primary-palette: map.merge(map.get($_palettes, primary), $_rest);
$tertiary-palette: map.merge(map.get($_palettes, tertiary), $_rest);
@function _high-contrast-value($light, $dark, $theme-type) {
@if ($theme-type == light) {
@return $light;
}
@if ($theme-type == dark) {
@return $dark;
}
@if ($theme-type == color-scheme) {
@return light-dark(#{$light}, #{$dark});
}
@error 'Unknown theme-type #{$theme-type}. Expected light, dark, or color-scheme';
}
@mixin high-contrast-overrides($theme-type) {
@include mat.theme-overrides((
primary: _high-contrast-value(#00217c, #efefff, $theme-type),
on-primary: _high-contrast-value(#ffffff, #000000, $theme-type),
primary-container: _high-contrast-value(#2740a0, #b3bfff, $theme-type),
on-primary-container: _high-contrast-value(#ffffff, #00072e, $theme-type),
inverse-primary: _high-contrast-value(#b8c4ff, #253f9f, $theme-type),
primary-fixed: _high-contrast-value(#2740a0, #dde1ff, $theme-type),
primary-fixed-dim: _high-contrast-value(#032789, #b8c4ff, $theme-type),
on-primary-fixed: _high-contrast-value(#ffffff, #000000, $theme-type),
on-primary-fixed-variant: _high-contrast-value(#ffffff, #000b3c, $theme-type),
secondary: _high-contrast-value(#2e2e00, #f9f660, $theme-type),
on-secondary: _high-contrast-value(#ffffff, #000000, $theme-type),
secondary-container: _high-contrast-value(#4c4c00, #cac835, $theme-type),
on-secondary-container: _high-contrast-value(#ffffff, #0c0c00, $theme-type),
secondary-fixed: _high-contrast-value(#4c4c00, #ebe954, $theme-type),
secondary-fixed-dim: _high-contrast-value(#353400, #cecc39, $theme-type),
on-secondary-fixed: _high-contrast-value(#ffffff, #000000, $theme-type),
on-secondary-fixed-variant: _high-contrast-value(#ffffff, #121200, $theme-type),
tertiary: _high-contrast-value(#51015b, #ffeafa, $theme-type),
on-tertiary: _high-contrast-value(#ffffff, #000000, $theme-type),
tertiary-container: _high-contrast-value(#73297b, #fba4fe, $theme-type),
on-tertiary-container: _high-contrast-value(#ffffff, #1b0020, $theme-type),
tertiary-fixed: _high-contrast-value(#73297b, #ffd6fc, $theme-type),
tertiary-fixed-dim: _high-contrast-value(#590c62, #fdaaff, $theme-type),
on-tertiary-fixed: _high-contrast-value(#ffffff, #000000, $theme-type),
on-tertiary-fixed-variant: _high-contrast-value(#ffffff, #25002a, $theme-type),
background: _high-contrast-value(#fbf8ff, #121319, $theme-type),
on-background: _high-contrast-value(#1a1b21, #e3e1ea, $theme-type),
surface: _high-contrast-value(#fbf8ff, #121319, $theme-type),
surface-dim: _high-contrast-value(#b9b8c0, #121319, $theme-type),
surface-bright: _high-contrast-value(#fbf8ff, #4f4f57, $theme-type),
surface-container-low: _high-contrast-value(#f1f0f9, #1e1f25, $theme-type),
surface-container-lowest: _high-contrast-value(#ffffff, #000000, $theme-type),
surface-container: _high-contrast-value(#e3e1ea, #2f3037, $theme-type),
surface-container-high: _high-contrast-value(#d5d3dc, #3a3b42, $theme-type),
surface-container-highest: _high-contrast-value(#c7c5ce, #46464d, $theme-type),
on-surface: _high-contrast-value(#000000, #ffffff, $theme-type),
shadow: _high-contrast-value(#000000, #000000, $theme-type),
scrim: _high-contrast-value(#000000, #000000, $theme-type),
surface-tint: _high-contrast-value(#3f57b7, #b8c4ff, $theme-type),
inverse-surface: _high-contrast-value(#2f3037, #e3e1ea, $theme-type),
inverse-on-surface: _high-contrast-value(#ffffff, #000000, $theme-type),
outline: _high-contrast-value(#2a2b37, #efeffe, $theme-type),
outline-variant: _high-contrast-value(#474855, #c1c1d0, $theme-type),
error: _high-contrast-value(#600004, #ffece9, $theme-type),
on-error: _high-contrast-value(#ffffff, #000000, $theme-type),
error-container: _high-contrast-value(#98000a, #ffaea4, $theme-type),
on-error-container: _high-contrast-value(#ffffff, #220001, $theme-type),
surface-variant: _high-contrast-value(#e1e1f1, #444652, $theme-type),
on-surface-variant: _high-contrast-value(#000000, #ffffff, $theme-type),
))
}
@@ -0,0 +1,39 @@
<div id="upper-bar">
<mat-form-field subscriptSizing="dynamic">
<mat-label>Wyszukaj</mat-label>
<input matInput (keyup)="filter($event)">
</mat-form-field>
<button mat-icon-button (click)="openUserCard()"><mat-icon>add</mat-icon></button>
</div>
<div class="mainc">
@if (ac.state() !== STATE.LOADED) {
<app-load-shade [state]="ac.state()" [error]="ac.error()" (refresh)="ac.refresh()"/>
}
<table mat-table [dataSource]="users">
<div matColumnDef="name">
<th mat-header-cell *matHeaderCellDef>Imię</th>
<td mat-cell *matCellDef="let element">{{element.fname}}</td>
</div>
<div matColumnDef="surname">
<th mat-header-cell *matHeaderCellDef>Nazwisko</th>
<td mat-cell *matCellDef="let element">{{element.surname}}</td>
</div>
<div matColumnDef="room">
<th mat-header-cell *matHeaderCellDef>Pokój</th>
<td mat-cell *matCellDef="let element">{{element.room}}</td>
</div>
<div matColumnDef="uname">
<th mat-header-cell *matHeaderCellDef>Nazwa użytkownika</th>
<td mat-cell *matCellDef="let element">{{element.uname}}</td>
</div>
<div matColumnDef="actions">
<th mat-header-cell *matHeaderCellDef>Karta użytkownika</th>
<td mat-cell *matCellDef="let element">
<button mat-mini-fab (click)="openUserCard(element._id)"><mat-icon>manage_accounts</mat-icon></button>
</td>
</div>
<tr mat-header-row *matHeaderRowDef="collumns"></tr>
<tr mat-row *matRowDef="let row; columns: collumns"></tr>
</table>
<mat-paginator pageSize="9" [pageSizeOptions]="[9, 15, 20, 50, 160]"></mat-paginator>
</div>
@@ -0,0 +1,30 @@
:host {
display: flex;
flex-direction: column;
height: 100%;
}
.mainc {
position: relative;
height: 100%;
display: flex;
flex-direction: column;
}
mat-paginator {
margin-top: auto;
}
mat-form-field {
flex-grow: 1;
}
#upper-bar {
display: flex;
}
button[mat-icon-button] {
margin-left: 4pt;
margin-right: 4pt;
margin-top: 4pt;
}
@@ -0,0 +1,54 @@
import { ComponentFixture, TestBed } from '@angular/core/testing'
import { AccountMgmtComponent } from './account-mgmt.component'
import { MatDialogModule } from '@angular/material/dialog'
import { MatSnackBarModule } from '@angular/material/snack-bar'
import { MatFormFieldModule } from '@angular/material/form-field'
import { MatIconModule } from '@angular/material/icon'
import { MatPaginatorModule } from '@angular/material/paginator'
import { MatTableModule } from '@angular/material/table'
import { MatInputModule } from '@angular/material/input'
import { BrowserAnimationsModule } from '@angular/platform-browser/animations'
import { MatProgressSpinnerModule } from '@angular/material/progress-spinner'
import { AccountMgmtService } from './account-mgmt.service'
import { LoadShadeComponent } from 'src/app/commonComponents/load-shade/load-shade.component'
import { of } from 'rxjs'
import { signal } from '@angular/core'
import { STATE } from 'src/app/types/state'
describe('AccountMgmtComponent', () => {
let component: AccountMgmtComponent
let fixture: ComponentFixture<AccountMgmtComponent>
let acMock
beforeEach(async () => {
acMock = {
accs: of([]),
state: signal(STATE.NOT_LOADED),
refresh: jasmine.createSpy('getAccs'),
error: signal(undefined)
}
await TestBed.configureTestingModule({
declarations: [AccountMgmtComponent, LoadShadeComponent],
providers: [{ provide: AccountMgmtService, useValue: acMock }],
imports: [
MatDialogModule,
MatSnackBarModule,
MatFormFieldModule,
MatIconModule,
MatPaginatorModule,
MatTableModule,
MatInputModule,
BrowserAnimationsModule,
MatProgressSpinnerModule,
],
}).compileComponents()
fixture = TestBed.createComponent(AccountMgmtComponent)
component = fixture.componentInstance
fixture.detectChanges()
})
it('should create', () => {
expect(component).toBeTruthy()
})
})
@@ -0,0 +1,79 @@
import { AfterViewInit, Component, inject, ViewChild } from '@angular/core'
import { MatDialog } from '@angular/material/dialog'
import { MatTableDataSource } from '@angular/material/table'
import { MatPaginator } from '@angular/material/paginator'
import { UserEditComponent, UserEditComponentInputData, UserEditComponentReturnData } from './user-edit/user-edit.component'
import { LocalStorageService } from 'src/app/services/local-storage.service'
import { Group } from 'src/app/types/group'
import { User } from 'src/app/admin-view/account-mgmt/account.model'
import { AccountMgmtService } from './account-mgmt.service'
import { STATE } from 'src/app/types/state'
@Component({
selector: 'app-account-mgmt',
templateUrl: './account-mgmt.component.html',
styleUrls: ['./account-mgmt.component.scss'],
standalone: false,
})
export class AccountMgmtComponent implements AfterViewInit {
protected groups: Group[] = []
users: MatTableDataSource<User>
@ViewChild(MatPaginator) paginator!: MatPaginator
protected ac = inject(AccountMgmtService)
private dialog = inject(MatDialog)
protected ls = inject(LocalStorageService)
constructor() {
this.users = new MatTableDataSource<User>()
this.users.filterPredicate = (
data: User,
filter: string
): boolean => {
const dataStr = Object.keys(data)
.reduce((curr: string, key: string) => {
if (['_id', 'admin', 'groups', '__v', 'locked'].find(v => v == key)) {
return curr + ''
}
return curr + data[key as keyof User] + '⫂'
}, '')
.toLowerCase()
const filternew = filter.trim().toLowerCase()
return dataStr.indexOf(filternew) != -1
}
this.ac.refresh()
this.ac.accs.subscribe(d => {
this.users.data = d
})
}
protected get STATE(): typeof STATE {
return STATE
}
ngAfterViewInit() {
this.users.paginator = this.paginator
}
filter(event: Event) {
const value = (event.target as HTMLInputElement).value
this.users.filter = value.toLowerCase().trim()
}
openUserCard(id?: string) {
this.dialog
.open<
UserEditComponent,
UserEditComponentInputData,
UserEditComponentReturnData
>(UserEditComponent, {
data: { id: id, type: id ? 'edit' : 'new', groups: this.groups },
})
.afterClosed()
.subscribe(r => {
if (r) this.ac.refresh()
})
}
collumns = ['name', 'surname', 'uname', 'actions']
}
@@ -0,0 +1,96 @@
import { TestBed } from '@angular/core/testing';
import { AccountMgmtService } from './account-mgmt.service';
import { provideHttpClient } from '@angular/common/http';
import { HttpTestingController, provideHttpClientTesting } from '@angular/common/http/testing';
import { environment } from 'src/environments/environment';
import { skip } from 'rxjs';
describe('AccountMgmtService', () => {
let service: AccountMgmtService;
let httpTesting: HttpTestingController;
beforeEach(() => {
TestBed.configureTestingModule({
providers: [
provideHttpClient(),
provideHttpClientTesting()
]
});
httpTesting = TestBed.inject(HttpTestingController);
service = TestBed.inject(AccountMgmtService);
});
it('should be created', () => {
expect(service).toBeTruthy();
});
it('should get user accounts', () => {
service.refresh()
const req = httpTesting.expectOne(environment.apiEndpoint + "/admin/accs", "Request to load all users")
expect(req.request.method).toBe("GET")
req.flush([])
httpTesting.verify()
})
describe('create user', () => {
xit('should create a user account and refresh list', () => {
const test_user = {
uname: "test",
groups: []
}
service.postAcc(test_user).subscribe(v => {
expect(v).toEqual(jasmine.objectContaining(test_user))
})
const req = httpTesting.expectOne(environment.apiEndpoint + "/admin/accs", "Request new user")
expect(req.request.method).toBe("POST")
req.flush({
...test_user,
_id: "test_id"
})
const req2 = httpTesting.expectOne(environment.apiEndpoint + "/admin/accs", "Request to load all users")
expect(req2.request.method).toBe("GET")
// service.accs.pipe(skip(1)).subscribe(v => {
// expect(v).toContain(createdUser)
// })
req2.flush([
{
...test_user,
_id: "test_id"
}
])
httpTesting.verify()
})
})
describe("delete user", () => {
it('should refresh accounts and not to contain deleted user', async () => {
service.deleteAcc("test").subscribe()
const req = httpTesting.expectOne(environment.apiEndpoint + "/admin/accs/test", "Request delete user")
expect(req.request.method).toBe("DELETE")
req.flush({ status: 200 })
const req2 = httpTesting.expectOne(environment.apiEndpoint + "/admin/accs", "Request to load all users")
expect(req2.request.method).toBe("GET")
service.accs.pipe(skip(1)).subscribe(v => {
expect(v).not.toContain(jasmine.objectContaining({ _id: "test" }))
})
req2.flush([])
httpTesting.verify()
})
})
});
@@ -0,0 +1,109 @@
import { HttpClient } from '@angular/common/http';
import { inject, Injectable, signal } from '@angular/core';
import { BehaviorSubject, catchError, map, of, tap } from 'rxjs';
import { STATE } from 'src/app/types/state';
import { Status } from 'src/app/types/status';
import { User, UserAPI } from 'src/app/admin-view/account-mgmt/account.model';
import { environment } from 'src/environments/environment';
import { DateTime } from 'luxon';
@Injectable({
providedIn: 'root'
})
export class AccountMgmtService {
private http = inject(HttpClient)
private _accs = new BehaviorSubject<User[]>([])
public readonly accs = this._accs.asObservable()
private _state = signal(STATE.NOT_LOADED);
public readonly state = this._state.asReadonly();
private _error = signal<string | undefined>(undefined);
public readonly error = this._error.asReadonly();
private _selAcc = new BehaviorSubject<User | null>(null)
public readonly selAcc = this._selAcc.asObservable()
public refresh() {
this.getAccs()
}
private getAccs() {
this._state.set(STATE.PENDING)
this.http.get
<UserAPI[]>
(environment.apiEndpoint + `/admin/accs`, { withCredentials: true })
.pipe(
catchError((err: Error) => {
this._state.set(STATE.ERROR)
this._error.set(err.message)
return of()
}),
map<UserAPI[], User[]>(v => {
return v.map(i => ({
...i,
regDate: DateTime.fromISO(i.regDate)
}))
})
).subscribe(v => {
this._error.set(undefined)
this._accs.next(v ?? [])
this._state.set(STATE.LOADED)
})
}
selectAccount(acc: User) {
this._selAcc.next(acc)
}
//#region legacy
postAcc(item: Omit<User, "_id" | "regDate">) {
return this.http.post<User>(
environment.apiEndpoint + `/admin/accs`,
item,
{ withCredentials: true }
).pipe(tap(v => {
if (v instanceof Array) this.refresh()
}))
}
putAcc(id: string, update: Partial<User>) {
return this.http.put<Status>(
environment.apiEndpoint + `/admin/accs/${id}`,
update,
{ withCredentials: true }
)
}
resetPass(id: string) {
return this.http.patch<Status>(
environment.apiEndpoint + `/admin/accs/${id}/reset`,
undefined,
{ withCredentials: true }
)
}
deleteAcc(id: string) {
return this.http.delete<Status>(
environment.apiEndpoint + `/admin/accs/${id}`,
{ withCredentials: true }
)
.pipe(tap(v => {
if (v.status == 200) this.refresh()
}))
}
getUser(id: string) {
return this.http.get<
Omit<User, 'regDate'> & { lockout: boolean; regDate: string }
>(environment.apiEndpoint + `/admin/accs/${id}`, {
withCredentials: true,
})
}
clearLockout(id: string) {
return this.http.delete<Status>(
environment.apiEndpoint + `/admin/accs/${id}/lockout`,
{ withCredentials: true }
)
}
//#endregion
}
@@ -0,0 +1,16 @@
import { DateTime } from 'luxon'
export interface User {
_id: string
uname: string
room?: string
admin?: string[]
locked?: boolean
fname?: string
surname?: string
groups: string[]
regDate: DateTime
defaultPage?: string
}
export type UserAPI = Omit<User, "regDate"> & {regDate: "string"}
@@ -0,0 +1,5 @@
<h1 mat-dialog-title>Czy na pewno chcesz usunąć tego użytkownika</h1>
<mat-dialog-actions align="end">
<button mat-button mat-dialog-close>Nie</button>
<button mat-button class="error-color" [mat-dialog-close]="true">Tak</button>
</mat-dialog-actions>
@@ -0,0 +1,23 @@
import { ComponentFixture, TestBed } from '@angular/core/testing'
import { UserDeleteComponent } from './user-delete.component'
import { MatDialogModule } from '@angular/material/dialog'
describe('UserDeleteComponent', () => {
let component: UserDeleteComponent
let fixture: ComponentFixture<UserDeleteComponent>
beforeEach(() => {
TestBed.configureTestingModule({
declarations: [UserDeleteComponent],
imports: [MatDialogModule],
})
fixture = TestBed.createComponent(UserDeleteComponent)
component = fixture.componentInstance
fixture.detectChanges()
})
it('should create', () => {
expect(component).toBeTruthy()
})
})
@@ -0,0 +1,9 @@
import { Component } from '@angular/core'
@Component({
selector: 'app-user-delete',
templateUrl: './user-delete.component.html',
styleUrls: ['./user-delete.component.scss'],
standalone: false,
})
export class UserDeleteComponent {}
@@ -0,0 +1,85 @@
<h1 mat-dialog-title>Karta użytkownika</h1>
<mat-dialog-content>
<form [formGroup]="form">
<div>
<mat-form-field appearance="outline">
<mat-label>Imię</mat-label>
<input type="text" matInput formControlName="fname">
</mat-form-field>
<mat-form-field appearance="outline">
<mat-label>Nazwisko</mat-label>
<input type="text" matInput formControlName="surname">
</mat-form-field>
<mat-form-field appearance="outline">
<mat-label>Pokój</mat-label>
<input type="text" matInput formControlName="room">
</mat-form-field>
<mat-form-field appearance="outline">
<mat-label>Grupy</mat-label>
<mat-select multiple formControlName="groups">
@for (item of adsyn.groups; track $index) {
<mat-option [value]="item._id">{{item.name}}</mat-option>
}
</mat-select>
</mat-form-field>
@if (data.type === 'edit') {
<span>Data rejestracji:<br>{{regDate?.toFormat('D')}}</span>
}
</div>
<div>
<mat-form-field appearance="outline">
<mat-label>Nazwa użytkownika</mat-label>
<input type="text" matInput required formControlName="uname">
</mat-form-field>
@if (data.type === "edit") {
<button mat-stroked-button (click)="resetPass()">Resetuj hasło</button>
@if (locked) {
<button mat-stroked-button class="error-color" (click)="toggleLock(false)"><mat-icon>lock</mat-icon>Blokada ręczna</button>
} @else {
<button mat-stroked-button (click)="toggleLock(true)">Zablokuj konto</button>
}
@if (lockout) {
<button mat-stroked-button class="error-color" (click)="disableLockout()"><mat-icon>lock_clock</mat-icon>Auto-Blokada</button>
} @else {
<button mat-stroked-button disabled>Auto-Blokada nieczynna</button>
}
@if (ls.permChecker("accs")) {
<mat-form-field>
<mat-label>Uprawnienia</mat-label>
<mat-select multiple formControlName="flags">
@if (ls.capCheck("news")) {
<mat-option value="news">Wiadomości</mat-option>
}
@if (ls.capCheck("menu")) {
<mat-option value="menu">Jadłospis</mat-option>
}
@if (ls.capCheck("notif")) {
<mat-option value="notif">Powiadomienia</mat-option>
}
@if (ls.capCheck("groups")) {
<mat-option value="groups">Grupy</mat-option>
}
<mat-option value="accs">Konta</mat-option>
@if (ls.capCheck("key")) {
<mat-option value="keys">Klucze</mat-option>
}
@if (ls.capCheck("clean")) {
<mat-option value="grades">Czystość</mat-option>
}
</mat-select>
</mat-form-field>
}
}
</div>
</form>
</mat-dialog-content>
<mat-dialog-actions>
@if (data.type === "edit") {
<button mat-stroked-button class="error-color" style="margin-right: auto;" (click)="delete()">Usuń konto</button>
}
<button mat-stroked-button mat-dialog-close>Zamknij</button>
<button mat-flat-button (click)="submit()">Zapisz</button>
@if (loading) {
<mat-spinner diameter="32"></mat-spinner>
}
</mat-dialog-actions>
@@ -0,0 +1,32 @@
:host {
padding: 8pt;
display: block;
}
form {
margin-top: 1ch !important;
display: flex;
grid-auto-flow: column;
flex-direction: row;
flex-wrap: wrap;
align-items: center;
justify-content: center;
column-gap: 3ch;
div {
display: grid;
grid-template-columns: 1fr;
grid-template-rows: repeat(5, 1fr);
align-items: center;
button {
align-self: stretch;
justify-self: stretch;
height: auto;
margin-bottom: 1lh;
}
}
}
mat-dialog-actions {
display: flex;
justify-content: flex-end;
}
@@ -0,0 +1,47 @@
import { ComponentFixture, TestBed } from '@angular/core/testing'
import { UserEditComponent } from './user-edit.component'
import {
MAT_DIALOG_DATA,
MatDialogModule,
MatDialogRef,
} from '@angular/material/dialog'
import { MatFormFieldModule } from '@angular/material/form-field'
import { ReactiveFormsModule } from '@angular/forms'
import { MatInputModule } from '@angular/material/input'
import { NoopAnimationsModule } from '@angular/platform-browser/animations'
import { MatSelectModule } from '@angular/material/select'
import { AccountMgmtService } from '../account-mgmt.service'
xdescribe('UserEditComponent', () => {
let component: UserEditComponent
let fixture: ComponentFixture<UserEditComponent>
let acMock
beforeEach(async () => {
acMock = {}
await TestBed.configureTestingModule({
declarations: [UserEditComponent],
imports: [
MatDialogModule,
MatFormFieldModule,
ReactiveFormsModule,
MatInputModule,
NoopAnimationsModule,
MatSelectModule,
],
providers: [
{ provide: MatDialogRef, useValue: {} },
{ provide: MAT_DIALOG_DATA, useValue: { groups: [] } },
{ provide: AccountMgmtService, useValue: acMock },
],
}).compileComponents()
fixture = TestBed.createComponent(UserEditComponent)
component = fixture.componentInstance
fixture.detectChanges()
})
it('should create', () => {
expect(component).toBeTruthy()
})
})
@@ -0,0 +1,198 @@
import { Component, inject } from '@angular/core'
import {
MAT_DIALOG_DATA,
MatDialog,
MatDialogRef,
} from '@angular/material/dialog'
import { FormControl, FormGroup } from '@angular/forms'
import { LocalStorageService } from 'src/app/services/local-storage.service'
import { Group } from 'src/app/types/group'
import { UserDeleteComponent } from '../user-delete/user-delete.component'
import { MatSnackBar } from '@angular/material/snack-bar'
import { UserResetComponent } from '../user-reset/user-reset.component'
import { catchError, throwError } from 'rxjs'
import { DateTime } from 'luxon'
import { AccountMgmtService } from '../account-mgmt.service'
import { AdminSyncService } from '../../admin-sync.service'
export interface UserEditComponentInputData { type: 'new' | 'edit'; id?: string; groups: Group[] }
export type UserEditComponentReturnData = true | undefined
@Component({
selector: 'app-user-edit',
templateUrl: './user-edit.component.html',
styleUrls: ['./user-edit.component.scss'],
standalone: false,
})
export class UserEditComponent {
lockout = false
locked = false
loading = false
form: FormGroup = new FormGroup({
fname: new FormControl<string>(''),
surname: new FormControl<string>(''),
room: new FormControl<string>(''),
uname: new FormControl<string>(''),
groups: new FormControl<string[]>([]),
flags: new FormControl<string[]>([]),
})
id?: string
regDate?: DateTime
public dialogRef: MatDialogRef<UserEditComponent> = inject(MatDialogRef)
public data: UserEditComponentInputData = inject(MAT_DIALOG_DATA)
protected ls = inject(LocalStorageService)
private acu = inject(AccountMgmtService)
private dialog = inject(MatDialog)
private sb = inject(MatSnackBar)
protected adsyn = inject(AdminSyncService)
constructor() {
if (this.data.type == 'edit') {
this.id = this.data.id
this.acu.getUser(this.data.id!).subscribe(r => {
this.regDate = DateTime.fromISO(r.regDate)
this.locked = r.locked ? true : false
this.lockout = r.lockout
this.form.get('fname')?.setValue(r.fname)
this.form.get('surname')?.setValue(r.surname)
this.form.get('room')?.setValue(r.room)
this.form.get('uname')?.setValue(r.uname)
this.form.get('groups')?.setValue(r.groups)
this.form.get('flags')?.setValue(r.admin)
})
}
}
protected submit() {
this.loading = true
if (this.data.type == 'edit') {
this.acu
.putAcc(this.id!, this.getForm())
.pipe(
catchError(err => {
this.sb.open('Wystąpił błąd. Skontaktuj się z obsługą programu.')
return throwError(() => new Error(err.message))
})
)
.subscribe(data => {
if (data.status == 200) {
this.sb.open('Użytkownik został zmodyfikowany.', undefined, {
duration: 2500,
})
this.dialogRef.close(true)
} else {
this.sb.open('Wystąpił błąd. Skontaktuj się z obsługą programu.')
this.loading = false
}
})
} else {
this.acu
.postAcc(this.getForm())
.pipe(
catchError(err => {
this.sb.open('Wystąpił błąd. Skontaktuj się z obsługą programu.')
return throwError(() => new Error(err.message))
})
)
.subscribe(data => {
if (data) {
this.sb.open('Użytkownik został utworzony.', undefined, {
duration: 2500,
})
this.dialogRef.close(true)
} else {
this.sb.open('Wystąpił błąd. Skontaktuj się z obsługą programu.')
this.loading = false
}
})
}
}
protected disableLockout() {
this.loading = true
this.acu
.clearLockout(this.id!)
.pipe(
catchError(err => {
this.sb.open('Wystąpił błąd. Skontaktuj się z obsługą programu.')
return throwError(() => new Error(err.message))
})
)
.subscribe(s => {
if (s.status == 200) {
this.loading = false
this.lockout = false
} else {
this.sb.open('Wystąpił błąd. Skontaktuj się z obsługą programu.')
this.loading = false
}
})
}
protected getForm() {
return {
fname: this.form.get('fname')?.value,
surname: this.form.get('surname')?.value,
room: this.form.get('room')?.value,
uname: this.form.get('uname')?.value,
groups: this.form.get('groups')?.value,
admin: (() => {
const value = this.form.get('flags')?.value
if (this.ls.permChecker("super")) {
return value
} else {
return undefined
}
})(),
}
}
protected delete() {
this.dialog
.open(UserDeleteComponent)
.afterClosed()
.subscribe(reply => {
if (reply) {
this.acu.deleteAcc(this.id!).subscribe(res => {
if (res.status == 200) {
this.sb.open('Użytkownik został usunięty.', undefined, {
duration: 2500,
})
this.dialogRef.close()
} else {
this.sb.open('Wystąpił błąd. Skontaktuj się z obsługą programu.')
console.error(res)
}
})
}
})
}
protected resetPass() {
this.loading = true
this.dialog
.open(UserResetComponent)
.afterClosed()
.subscribe(res => {
if (res == true) {
this.acu.resetPass(this.id!).subscribe(patch => {
if (patch.status == 200) {
this.sb.open('Hasło zostało zresetowane', undefined, {
duration: 2500,
})
this.loading = false
}
})
}
})
}
protected toggleLock(state: boolean) {
this.acu.putAcc(this.id!, { locked: state }).subscribe(res => {
if (res.status == 200) {
this.locked = state
}
})
}
}
@@ -0,0 +1,8 @@
<h1 mat-dialog-title>Reset hasła</h1>
<mat-dialog-content>
Czy chcesz zresetować hasło temu użytkownikowi?
</mat-dialog-content>
<mat-dialog-actions>
<button mat-button [mat-dialog-close]="true" class="error-color">Tak</button>
<button mat-button mat-dialog-close>Nie</button>
</mat-dialog-actions>
@@ -0,0 +1,23 @@
import { ComponentFixture, TestBed } from '@angular/core/testing'
import { UserResetComponent } from './user-reset.component'
import { MatDialogModule } from '@angular/material/dialog'
describe('UserResetComponent', () => {
let component: UserResetComponent
let fixture: ComponentFixture<UserResetComponent>
beforeEach(() => {
TestBed.configureTestingModule({
declarations: [UserResetComponent],
imports: [MatDialogModule],
})
fixture = TestBed.createComponent(UserResetComponent)
component = fixture.componentInstance
fixture.detectChanges()
})
it('should create', () => {
expect(component).toBeTruthy()
})
})
@@ -0,0 +1,9 @@
import { Component } from '@angular/core'
@Component({
selector: 'app-user-reset',
templateUrl: './user-reset.component.html',
styleUrls: ['./user-reset.component.scss'],
standalone: false,
})
export class UserResetComponent {}
@@ -0,0 +1,23 @@
import { TestBed } from '@angular/core/testing';
import { AdminSyncService } from './admin-sync.service';
import { provideHttpClient } from '@angular/common/http';
import { provideHttpClientTesting } from '@angular/common/http/testing';
describe('AdminSyncService', () => {
let service: AdminSyncService;
beforeEach(() => {
TestBed.configureTestingModule({
providers: [
provideHttpClient(),
provideHttpClientTesting()
]
});
service = TestBed.inject(AdminSyncService);
});
it('should be created', () => {
expect(service).toBeTruthy();
});
});
@@ -0,0 +1,27 @@
import { HttpClient } from '@angular/common/http';
import { inject, Injectable } from '@angular/core';
import { Group } from '../types/group';
import { environment } from 'src/environments/environment';
@Injectable({
providedIn: 'root'
})
export class AdminSyncService {
private http = inject(HttpClient)
// eslint-disable-next-line @typescript-eslint/no-explicit-any
private _data: any
private sync() {
this.http.get(environment.apiEndpoint + `/admin/sync`, { withCredentials: true }).subscribe(v => {
this._data = v
})
}
public get groups(): Group[] {
const groups = this._data?.groups
if (!groups) this.sync()
return groups
}
}
@@ -0,0 +1,24 @@
<app-toolbar [drawer]="drawer"/>
<mat-sidenav-container>
<mat-sidenav #drawer mode="over" autoFocus="false">
<mat-nav-list>
@for (link of LINKS; track $index) {
<mat-list-item [routerLink]="link.href" routerLinkActive #rla="routerLinkActive" [activated]="rla.isActive">
<mat-icon matListItemIcon>{{link.icon}}</mat-icon>
<a matListItemTitle>{{link.title}}</a>
</mat-list-item>
}
<a mat-list-item href="https://foliand.men/wiki/index.php/IPWA:Start" target="_blank">
<mat-icon matListItemIcon>developer_guide</mat-icon>
<a matListItemTitle>Dokumentacja</a>
</a>
<mat-list-item (click)="goNormal()">
<mat-icon matListItemIcon>close</mat-icon>
<h4 matListItemTitle>Zakończ edycję</h4>
</mat-list-item>
</mat-nav-list>
</mat-sidenav>
<mat-sidenav-content>
<router-outlet></router-outlet>
</mat-sidenav-content>
</mat-sidenav-container>
@@ -0,0 +1,21 @@
@use "@angular/material" as mat;
@use "../../theme-colors" as theme;
:host {
width: 100%;
height: 100%;
display: flex;
flex-direction: column;
@include mat.theme((
color: theme.$tertiary-palette
))
}
mat-sidenav,
mat-toolbar {
padding: 8pt;
}
mat-sidenav-container {
flex-grow: 1;
}
@@ -0,0 +1,45 @@
import { ComponentFixture, TestBed } from '@angular/core/testing'
import { AdminViewComponent } from './admin-view.component'
import { MatToolbarModule } from '@angular/material/toolbar'
import { MatIconModule } from '@angular/material/icon'
import { MatDrawer, MatSidenavModule } from '@angular/material/sidenav'
import { BrowserAnimationsModule } from '@angular/platform-browser/animations'
import { MatListModule } from '@angular/material/list'
import { RouterModule } from '@angular/router'
import { Component, Input } from '@angular/core'
@Component({
selector: 'app-toolbar',
template: '',
standalone: false,
})
class ToolbarMock {
@Input() drawer!: MatDrawer
}
describe('AdminViewComponent', () => {
let component: AdminViewComponent
let fixture: ComponentFixture<AdminViewComponent>
beforeEach(() => {
TestBed.configureTestingModule({
declarations: [AdminViewComponent, ToolbarMock],
imports: [
MatToolbarModule,
MatIconModule,
MatSidenavModule,
BrowserAnimationsModule,
MatListModule,
RouterModule.forRoot([]),
],
})
fixture = TestBed.createComponent(AdminViewComponent)
component = fixture.componentInstance
fixture.detectChanges()
})
it('should create', () => {
expect(component).toBeTruthy()
})
})
@@ -0,0 +1,78 @@
import { Component, inject } from '@angular/core'
import { Router } from '@angular/router'
import { LocalStorageService } from '../services/local-storage.service'
import { Link } from '../types/link'
@Component({
selector: 'app-admin-view',
templateUrl: './admin-view.component.html',
styleUrls: ['./admin-view.component.scss'],
standalone: false,
})
export class AdminViewComponent {
readonly router = inject(Router)
readonly ls = inject(LocalStorageService)
private readonly _LINKS: Link[] = [
{
title: 'Wiadomości',
icon: 'newspaper',
href: 'news',
enabled: this.ls.permChecker("news") && this.ls.capCheck("news"),
},
{
title: 'Jadłospis',
icon: 'restaurant_menu',
href: 'menu',
enabled: this.ls.permChecker("menu") && this.ls.capCheck("menu"),
},
{
title: 'Wysyłanie powiadomień',
icon: 'notifications',
href: 'notifications',
enabled: this.ls.permChecker("notif") && this.ls.capCheck("notif"),
},
{
title: 'Grupy',
icon: 'groups',
href: 'groups',
enabled: this.ls.permChecker("groups") && this.ls.capCheck("groups"),
},
{
title: 'Zarządzanie kontami',
icon: 'manage_accounts',
href: 'accounts',
enabled: this.ls.permChecker("accs"),
},
{
title: 'Klucze',
icon: 'key',
href: 'keys',
enabled: this.ls.permChecker("keys") && this.ls.capCheck("key"),
},
{
title: 'Czystość',
icon: 'cleaning_services',
href: 'grades',
enabled: this.ls.permChecker("grades") && this.ls.capCheck("clean"),
},
{
title: 'Frekwencja',
icon: 'checklist',
href: 'attendence',
enabled: false,
},
{
title: 'Ustawienia',
icon: 'settings_applications',
href: 'settings',
enabled: this.ls.permChecker("super"),
},
]
public get LINKS(): Link[] {
return this._LINKS.filter(v => v.enabled)
}
goNormal() {
this.router.navigateByUrl('app')
}
}
@@ -0,0 +1,29 @@
<div id="guide">
<p><b>Uwaga:</b> Obecność resetuje się o codziennie o 00:00</p>
<div id="legend">
<b>Legenda: </b>
<span class="circle">Wychowanek obecny</span>
<span class="circle">Wyjście w ciągu 30 min.</span>
<span class="circle">Wychowanek nieobecny</span>
</div>
</div>
<table mat-table [dataSource]="data" matSort>
<div matColumnDef="room">
<th mat-header-cell *matHeaderCellDef mat-sort-header>Pokój</th>
<td mat-cell *matCellDef="let item">{{item.room}}</td>
</div>
<div matColumnDef="hours">
<th mat-header-cell *matHeaderCellDef mat-sort-header>Godziny</th>
<td mat-cell *matCellDef="let item">@for (i of item.hours.sort().reverse(); track i; let isLast = $last) {
<span><app-hour-display [value]="i"></app-hour-display>{{ isLast ? '' : ', '}}</span>
}<span>{{item.notes}}</span></td>
</div>
<div matColumnDef="actions">
<th mat-header-cell *matHeaderCellDef>Usuń</th>
<td mat-cell *matCellDef="let item">@if (!item.auto) {
<button mat-mini-fab class="error-color" (click)="delete(item.room)"><mat-icon>delete</mat-icon></button>
}</td>
</div>
<tr mat-header-row *matHeaderRowDef="collumns"></tr>
<tr mat-row *matRowDef="let rowData; columns: collumns"></tr>
</table>
@@ -0,0 +1,34 @@
@use "sass:list";
#guide {
margin: 1em;
}
#legend {
display: flex;
justify-self: center;
gap: 3ch;
* {
margin: 2px;
}
}
.circle {
&::before {
border-radius: 7.5%;
width: 2.5ch;
height: 2.5ch;
display: inline-block;
content: "";
vertical-align: middle;
margin-right: 3px;
}
$list: (red, yellow, green);
@for $n from 1 through 3 {
&:nth-of-type(#{$n})::before {
background-color: list.nth($list, $n);
}
}
}
@@ -0,0 +1,29 @@
import { ComponentFixture, TestBed } from '@angular/core/testing'
import { AttendenceSummaryComponent } from './attendence-summary.component'
import { RouterModule } from '@angular/router'
import { MatTableModule } from '@angular/material/table'
import { GradesService } from '../grades.service'
xdescribe('AttendenceSummaryComponent', () => {
let component: AttendenceSummaryComponent
let fixture: ComponentFixture<AttendenceSummaryComponent>
let acMock
beforeEach(async () => {
acMock = {}
await TestBed.configureTestingModule({
declarations: [AttendenceSummaryComponent],
imports: [RouterModule.forRoot([]), MatTableModule],
providers: [{ provide: GradesService, useValue: acMock }],
}).compileComponents()
fixture = TestBed.createComponent(AttendenceSummaryComponent)
component = fixture.componentInstance
fixture.detectChanges()
})
it('should create', () => {
expect(component).toBeTruthy()
})
})
@@ -0,0 +1,54 @@
import { Component, inject, OnInit } from '@angular/core'
import { ToolbarService } from '../../toolbar/toolbar.service'
import { Router, ActivatedRoute } from '@angular/router'
import { MatTableDataSource } from '@angular/material/table'
import { GradesService } from '../grades.service'
@Component({
selector: 'app-attendence-summary',
templateUrl: './attendence-summary.component.html',
styleUrl: './attendence-summary.component.scss',
standalone: false,
})
export class AttendenceSummaryComponent implements OnInit {
data: MatTableDataSource<{
room: string
hours: string[]
notes: string
auto: boolean
}> = new MatTableDataSource<{
room: string
hours: string[]
notes: string
auto: boolean
}>()
collumns = ['room', 'hours', 'actions']
private toolbar = inject(ToolbarService)
private router = inject(Router)
private route = inject(ActivatedRoute)
private ac = inject(GradesService)
constructor() {
this.toolbar.comp = this
this.toolbar.menu = [
{ check: true, title: 'Ocenianie', fn: 'goBack', icon: 'arrow_back' },
]
}
delete(room: string) {
this.ac.attendence.deleteRoom(room).subscribe(() => {
this.ngOnInit()
})
}
ngOnInit(): void {
this.ac.attendence.getSummary().subscribe(v => {
this.data.data = v
})
}
goBack() {
this.router.navigate(['../'], { relativeTo: this.route })
}
}
@@ -0,0 +1 @@
<span [ngStyle]="style()">{{value}}</span>
@@ -0,0 +1,8 @@
:host {
display: inline;
}
span {
padding: 2px;
border-radius: 7.5%;
}
@@ -0,0 +1,22 @@
import { ComponentFixture, TestBed } from '@angular/core/testing'
import { HourDisplayComponent } from './hour-display.component'
describe('HourDisplayComponent', () => {
let component: HourDisplayComponent
let fixture: ComponentFixture<HourDisplayComponent>
beforeEach(async () => {
await TestBed.configureTestingModule({
declarations: [HourDisplayComponent],
}).compileComponents()
fixture = TestBed.createComponent(HourDisplayComponent)
component = fixture.componentInstance
fixture.detectChanges()
})
it('should create', () => {
expect(component).toBeTruthy()
})
})
@@ -0,0 +1,27 @@
import { Component, Input } from '@angular/core'
import { DateTime } from 'luxon'
@Component({
selector: 'app-hour-display',
templateUrl: './hour-display.component.html',
styleUrl: './hour-display.component.scss',
standalone: false,
})
export class HourDisplayComponent {
@Input() value = ''
style() {
if (/(0+[0-9]|1[0-9]|2[0-3]):(0+[0-9]|[1-5][0-9])/g.test(this.value)) {
const diff = DateTime.fromFormat(this.value, 'HH:mm').diffNow('minutes')
if (diff.as('minutes') > 30) {
return { 'background-color': 'red' }
} else if (diff.as('minutes') > 0) {
return { 'background-color': 'yellow', color: 'black' }
} else {
return { 'background-color': 'green' }
}
} else {
return { color: 'gray' }
}
}
}
@@ -0,0 +1,22 @@
<span mat-dialog-title>Obecność w {{room}}</span>
<mat-dialog-content>
<form [formGroup]="this.form">
<div formArrayName="users">
@for (item of users.controls; track i; let i = $index) {
<div [formGroupName]="i">
<mat-checkbox formControlName="att" #cb>
<span control="label"></span>:
<input type="time" formControlName="hour" (input)="cb.writeValue(true)">
</mat-checkbox>
</div>
}
</div>
<mat-form-field>
<mat-label>Notatki</mat-label>
<input type="text" matInput formControlName="notes">
</mat-form-field>
</form>
</mat-dialog-content>
<mat-dialog-actions>
<button mat-button (click)="save()">Zapisz</button>
</mat-dialog-actions>
@@ -0,0 +1,46 @@
import { ComponentFixture, TestBed } from '@angular/core/testing'
import { AttendenceComponent } from './attendence.component'
import {
MAT_DIALOG_DATA,
MatDialogModule,
MatDialogRef,
} from '@angular/material/dialog'
import { MatFormFieldModule } from '@angular/material/form-field'
import { FormsModule, ReactiveFormsModule } from '@angular/forms'
import { MatInputModule } from '@angular/material/input'
import { NoopAnimationsModule } from '@angular/platform-browser/animations'
import { GradesService } from '../grades.service'
xdescribe('AttendenceComponent', () => {
let component: AttendenceComponent
let fixture: ComponentFixture<AttendenceComponent>
beforeEach(async () => {
const acMock = {}
await TestBed.configureTestingModule({
declarations: [AttendenceComponent],
providers: [
{ provide: MAT_DIALOG_DATA, useValue: {} },
{ provide: MatDialogRef, useValue: {} },
{ provide: GradesService, useValue: acMock },
],
imports: [
MatDialogModule,
MatFormFieldModule,
FormsModule,
ReactiveFormsModule,
MatInputModule,
NoopAnimationsModule,
],
}).compileComponents()
fixture = TestBed.createComponent(AttendenceComponent)
component = fixture.componentInstance
fixture.detectChanges()
})
it('should create', () => {
expect(component).toBeTruthy()
})
})
@@ -0,0 +1,55 @@
import { Component, inject, OnInit } from '@angular/core'
import { FormArray, FormBuilder, FormGroup } from '@angular/forms'
import { MAT_DIALOG_DATA, MatDialogRef } from '@angular/material/dialog'
import { GradesService } from '../grades.service'
@Component({
selector: 'app-attendence',
templateUrl: './attendence.component.html',
styleUrl: './attendence.component.scss',
standalone: false,
})
export class AttendenceComponent implements OnInit {
private fb = inject(FormBuilder)
public data: { room: string } = inject(MAT_DIALOG_DATA)
public dialogRef: MatDialogRef<AttendenceComponent> = inject(MatDialogRef)
private ac = inject(GradesService)
ngOnInit(): void {
this.room = this.data.room
this.ac.attendence.getUsers(this.room).subscribe(query => {
query.users.forEach(v => {
const att = query.attendence
? query.attendence.auto.find(z => z.id == v._id)
: false
this.users.push(
this.fb.group({
id: v._id,
label: `${v.fname} ${v.surname}`,
att: this.fb.control(att),
hour: this.fb.control(att ? att.hour : ''),
})
)
})
this.form.get('notes')?.setValue(query.attendence?.notes)
})
}
save() {
this.dialogRef.close({
room: this.room,
...this.form.value,
})
}
room = ''
form: FormGroup = this.fb.group({
users: this.fb.array([]),
notes: this.fb.control(''),
})
get users() {
return this.form.get('users') as FormArray
}
}
@@ -0,0 +1,34 @@
<app-date-selector [(date)]="date" [filter]="filter" (dateChange)="downloadData()"></app-date-selector>
<app-room-chooser [rooms]="rooms" (room)="roomNumber($event)"/>
<form [formGroup]="form">
<p>Czystość pokoju {{room}} na {{date().toFormat("cccc, D")}}</p>
<p>Ocena: <span [appGradeColor]="grade">{{grade}}</span></p>
<div id="buttons">
<button mat-mini-fab (click)="downloadData()"><mat-icon>cancel</mat-icon></button>
<button mat-mini-fab (click)="attendence()"><mat-icon>overview</mat-icon></button>
<button mat-mini-fab (click)="save()"><mat-icon>save</mat-icon></button>
@if (id) {
<button mat-mini-fab class="error-color" (click)="remove()"><mat-icon>delete</mat-icon></button>
}
</div>
@for (item of things.controls; track item; let i = $index) {
<div formArrayName="things" id="things">
<div formGroupName="{{i}}">
<mat-checkbox formControlName="cb" #cb>
<span control="label"></span>
@if (cb.checked) {
<span>
<button mat-icon-button (click)="group.sub(i)"><mat-icon>remove</mat-icon></button>
<span control="weight"></span>
<button mat-icon-button (click)="group.add(i)"><mat-icon>add</mat-icon></button>
</span>
}
</mat-checkbox>
</div>
</div>
}
<mat-form-field style="width: 100%;">
<mat-label>Dodatkowe uwagi</mat-label>
<textarea matNativeControl cdkTextareaAutosize formControlName="tips"></textarea>
</mat-form-field>
</form>
@@ -0,0 +1,10 @@
div#things {
display: flex;
flex-direction: column;
}
div#buttons {
* {
margin: 0 2px 0 2px;
}
}
@@ -0,0 +1,64 @@
import { ComponentFixture, TestBed } from '@angular/core/testing'
import { GradesComponent } from './grades.component'
import { RouterModule } from '@angular/router'
import { Component, EventEmitter, Input, Output } from '@angular/core'
import { MatIconModule } from '@angular/material/icon'
import { MatFormFieldModule } from '@angular/material/form-field'
import { FormsModule, ReactiveFormsModule } from '@angular/forms'
import { MatInputModule } from '@angular/material/input'
import { NoopAnimationsModule } from '@angular/platform-browser/animations'
import { DateTime } from 'luxon'
import { GradesService } from './grades.service'
@Component({
selector: 'app-date-selector',
template: '',
standalone: false,
})
class DateSelectorStub {
@Input() date: string = DateTime.now().toISODate()
@Output() dateChange = new EventEmitter<string>()
@Input() filter: (date: DateTime | null) => boolean = () => true
}
@Component({
selector: 'app-room-chooser',
template: '',
standalone: false,
})
class RoomSelectorStub {
@Input() rooms: string[] = []
@Output() room: EventEmitter<string> = new EventEmitter<string>()
}
xdescribe('GradesComponent', () => {
let component: GradesComponent
let fixture: ComponentFixture<GradesComponent>
let acMock
beforeEach(async () => {
acMock = {}
await TestBed.configureTestingModule({
declarations: [GradesComponent, DateSelectorStub, RoomSelectorStub],
providers: [{ provide: GradesService, useValue: acMock }],
imports: [
RouterModule.forRoot([]),
MatIconModule,
MatFormFieldModule,
FormsModule,
ReactiveFormsModule,
MatInputModule,
NoopAnimationsModule,
],
}).compileComponents()
fixture = TestBed.createComponent(GradesComponent)
component = fixture.componentInstance
fixture.detectChanges()
})
it('should create', () => {
expect(component).toBeTruthy()
})
})
@@ -0,0 +1,221 @@
import { Component, inject, OnDestroy, OnInit, signal } from '@angular/core'
import { FormArray, FormBuilder } from '@angular/forms'
import { filterLook, weekendFilter } from 'src/app/util'
import { MatSnackBar } from '@angular/material/snack-bar'
import { ToolbarService } from '../toolbar/toolbar.service'
import { ActivatedRoute, Router } from '@angular/router'
import { MatDialog } from '@angular/material/dialog'
import { AttendenceComponent } from './attendence/attendence.component'
import { DateTime } from 'luxon'
import { GradesService } from './grades.service'
@Component({
selector: 'app-grades',
templateUrl: './grades.component.html',
styleUrl: './grades.component.scss',
standalone: false,
})
export class GradesComponent implements OnInit, OnDestroy {
private ac = inject(GradesService)
private fb = inject(FormBuilder)
private sb = inject(MatSnackBar)
private toolbar = inject(ToolbarService)
private router = inject(Router)
private route = inject(ActivatedRoute)
private dialog = inject(MatDialog)
rooms!: string[]
room = '0'
grade = 6
gradeDate?: DateTime
id?: string
filter = weekendFilter
date = signal<DateTime>(filterLook(this.filter, "behind", DateTime.now(), 7)!)
get notes(): { label: string; weight: number }[] {
const th = this.things.value as {
cb: boolean
label: string
weight: number
}[]
return th
.filter(v => v.cb)
.map(v => {
return { ...v, cb: undefined }
})
}
set notes(value: { label: string; weight: number }[]) {
const things = this.things.controls
things.forEach(v => {
const thing = value.find(s => s.label == v.get('label')?.value)
if (thing) {
v.get('cb')?.setValue(true)
v.get('weight')?.setValue(thing.weight)
} else {
v.get('cb')?.setValue(false)
v.get('weight')?.setValue(1)
}
})
}
constructor() {
// if (!this.filter(this.date)) this.date.isoWeekday(8);
this.toolbar.comp = this
this.toolbar.menu = [
{
title: 'Pokoje do sprawdzenia',
check: true,
fn: 'attendenceSummary',
icon: 'overview',
},
{ title: 'Podsumowanie', check: true, fn: 'summary', icon: 'analytics' },
]
this.form.valueChanges.subscribe(() => {
this.calculate()
})
}
form = this.fb.group({
things: this.fb.array([]),
tips: this.fb.control(''),
})
get things() {
return this.form.get('things') as FormArray
}
summary() {
this.router.navigate(['summary'], { relativeTo: this.route })
}
attendenceSummary() {
this.router.navigate(['attendenceSummary'], { relativeTo: this.route })
}
ngOnInit(): void {
this.ac.getConfig().subscribe(s => {
this.rooms = s.rooms
s.things.forEach(s =>
this.things.push(
this.fb.group({
cb: this.fb.control(false),
label: this.fb.control(s),
weight: this.fb.control(1),
})
)
)
})
}
ngOnDestroy(): void {
this.toolbar.comp = undefined
this.toolbar.menu = undefined
}
downloadData() {
this.ac.getClean(this.date(), this.room).subscribe(v => {
if (v) {
this.notes = v.notes
this.gradeDate = DateTime.fromISO(v.gradeDate)
this.grade = v.grade
this.id = v._id
this.form.get('tips')?.setValue(v.tips)
} else {
this.gradeDate = undefined
this.grade = 6
this.notes = []
this.id = undefined
this.form.get('tips')?.setValue('')
}
})
}
calculate() {
this.grade = 6
this.things.controls.forEach(s => {
if (s.get('cb')?.value) this.grade -= 1 * s.get('weight')?.value
if (this.grade < 0) this.grade = 0
})
}
group = {
add: (index: number) => {
const weight = this.things.at(index).get('weight')!
weight.setValue(weight.value + 1)
},
sub: (index: number) => {
const weight = this.things.at(index).get('weight')!
if (weight.value < 1) {
weight.setValue(1)
} else {
if (weight.value - 1 < 1) {
weight.setValue(1)
} else {
weight.setValue(weight.value - 1)
}
}
},
}
save() {
this.calculate()
const obj = {
grade: this.grade,
date: this.date().toISODate(),
room: this.room,
notes: this.notes,
tips: this.form.get('tips')?.value,
}
this.ac.postClean(obj).subscribe(() => {
this.sb.open('Zapisano!', undefined, { duration: 1500 })
this.downloadData()
})
}
remove() {
this.ac.delete(this.id!).subscribe(s => {
if (s.status == 200) {
this.downloadData()
}
})
}
roomNumber(value: string) {
this.room = value
this.downloadData()
}
attendence() {
this.dialog
.open(AttendenceComponent, { data: { room: this.room } })
.afterClosed()
.subscribe(
(v: {
room: string
users: { att: boolean; id: string; hour: string }[]
notes: string
}) => {
if (!v) return
const x: { room: string; users: { id: string; hour?: string }[] } = {
room: v.room,
users: [],
}
v.users.forEach(i => {
if (i.att && i.hour) {
x.users.push({ id: i.id, hour: i.hour })
}
})
this.ac.attendence
.postAttendence(x.room, { auto: x.users, notes: v.notes })
.subscribe(s => {
if (s.status == 200) {
this.sb.open('Zapisano obecność!', undefined, {
duration: 1500,
})
}
})
}
)
}
}
@@ -0,0 +1,23 @@
import { TestBed } from '@angular/core/testing';
import { GradesService } from './grades.service';
import { provideHttpClient } from '@angular/common/http';
import { provideHttpClientTesting } from '@angular/common/http/testing';
describe('GradesService', () => {
let service: GradesService;
beforeEach(() => {
TestBed.configureTestingModule({
providers: [
provideHttpClient(),
provideHttpClientTesting()
]
});
service = TestBed.inject(GradesService);
});
it('should be created', () => {
expect(service).toBeTruthy();
});
});
@@ -0,0 +1,92 @@
import { HttpClient } from '@angular/common/http';
import { inject, Injectable } from '@angular/core';
import { DateTime } from 'luxon';
import { Status } from 'src/app/types/status';
import { environment } from 'src/environments/environment';
@Injectable({
providedIn: 'root'
})
export class GradesService {
private http = inject(HttpClient)
getConfig() {
return this.http.get<{ rooms: string[]; things: string[] }>(
environment.apiEndpoint + `/admin/clean/config`,
{ withCredentials: true }
)
}
getClean(date: DateTime, room: string) {
return this.http.get<{
_id: string
date: string
grade: number
gradeDate: string
notes: { label: string; weight: number }[]
room: string
tips: string
} | null>(environment.apiEndpoint + `/admin/clean/${date.toISODate()}/${room}`, {
withCredentials: true,
})
}
postClean(obj: object) {
return this.http.post<Status>(
environment.apiEndpoint + `/admin/clean/`,
obj,
{ withCredentials: true }
)
}
delete(id: string) {
return this.http.delete<Status>(
environment.apiEndpoint + `/admin/clean/${id}`,
{ withCredentials: true }
)
}
summary = {
getSummary: (start: DateTime, end: DateTime) => {
return this.http.get<{ room: string; avg: number }[]>(
environment.apiEndpoint +
`/admin/clean/summary/${start.toISO()}/${end.toISO()}`,
{ withCredentials: true }
)
},
}
attendence = {
getUsers: (room: string) => {
return this.http.get<{
users: { fname: string; surname: string; _id: string }[]
attendence?: { auto: { id: string; hour?: string }[]; notes: string }
}>(environment.apiEndpoint + `/admin/clean/attendence/${room}`, {
withCredentials: true,
})
},
postAttendence: (
room: string,
attendence: { auto: { id: string; hour?: string }[]; notes: string }
) => {
return this.http.post<Status>(
environment.apiEndpoint + `/admin/clean/attendence/${room}`,
attendence,
{ withCredentials: true }
)
},
getSummary: () => {
return this.http.get<
{ room: string; hours: string[]; notes: string; auto: boolean }[]
>(environment.apiEndpoint + `/admin/clean/attendenceSummary`, {
withCredentials: true,
})
},
deleteRoom: (room: string) => {
return this.http.delete<Status>(
environment.apiEndpoint + `/admin/clean/attendence/${room}`,
{ withCredentials: true }
)
},
}
}
@@ -0,0 +1,25 @@
<div>
<mat-form-field>
<mat-label>Wybierz tydzień</mat-label>
<mat-date-range-input [rangePicker]="picker" [formGroup]="dateSelector">
<input matStartDate formControlName="start">
<input matEndDate formControlName="end">
</mat-date-range-input>
<mat-datepicker-toggle matIconSuffix [for]="picker"></mat-datepicker-toggle>
<mat-date-range-picker #picker></mat-date-range-picker>
</mat-form-field>
<button mat-icon-button><mat-icon>query_stats</mat-icon></button>
</div>
<table mat-table [dataSource]="data" matSort>
<div matColumnDef="room">
<th mat-header-cell *matHeaderCellDef mat-sort-header>Pokój</th>
<td mat-cell *matCellDef="let item">{{item.room}}</td>
</div>
<div matColumnDef="avg">
<th mat-header-cell *matHeaderCellDef mat-sort-header>Średnia</th>
<td mat-cell *matCellDef="let item">{{item.avg}}</td>
</div>
<tr mat-header-row *matHeaderRowDef="collumns"></tr>
<tr mat-row *matRowDef="let rowData; columns: collumns"></tr>
</table>
@@ -0,0 +1,46 @@
import { ComponentFixture, TestBed } from '@angular/core/testing'
import { SummaryComponent } from './summary.component'
import { RouterModule } from '@angular/router'
import { MatFormFieldModule } from '@angular/material/form-field'
import { MatDatepickerModule } from '@angular/material/datepicker'
import { MatIconModule } from '@angular/material/icon'
import { FormsModule, ReactiveFormsModule } from '@angular/forms'
import { MatTableModule } from '@angular/material/table'
import { NoopAnimationsModule } from '@angular/platform-browser/animations'
import { provideLuxonDateAdapter } from '@angular/material-luxon-adapter'
import { GradesService } from '../grades.service'
xdescribe('SummaryComponent', () => {
let component: SummaryComponent
let fixture: ComponentFixture<SummaryComponent>
beforeEach(async () => {
const acMock = {}
await TestBed.configureTestingModule({
declarations: [SummaryComponent],
providers: [
{ provide: GradesService, useValue: acMock },
provideLuxonDateAdapter(),
],
imports: [
RouterModule.forRoot([]),
MatFormFieldModule,
MatDatepickerModule,
MatIconModule,
FormsModule,
ReactiveFormsModule,
MatTableModule,
NoopAnimationsModule,
],
}).compileComponents()
fixture = TestBed.createComponent(SummaryComponent)
component = fixture.componentInstance
fixture.detectChanges()
})
it('should create', () => {
expect(component).toBeTruthy()
})
})
@@ -0,0 +1,68 @@
import { Component, inject, OnDestroy, OnInit, ViewChild } from '@angular/core'
import { ToolbarService } from '../../toolbar/toolbar.service'
import { ActivatedRoute, Router } from '@angular/router'
import { MatTableDataSource } from '@angular/material/table'
import { FormBuilder } from '@angular/forms'
import { MatSort } from '@angular/material/sort'
import { DateTime } from 'luxon'
import { GradesService } from '../grades.service'
@Component({
selector: 'app-summary',
templateUrl: './summary.component.html',
styleUrl: './summary.component.scss',
standalone: false,
})
export class SummaryComponent implements OnInit, OnDestroy {
private toolbar = inject(ToolbarService)
private router = inject(Router)
private route = inject(ActivatedRoute)
private ac = inject(GradesService)
private fb = inject(FormBuilder)
data: MatTableDataSource<{ room: string; avg: number }> =
new MatTableDataSource<{ room: string; avg: number }>()
collumns = ['room', 'avg']
dateSelector = this.fb.group({
start: this.fb.control(DateTime.utc().startOf('day')),
end: this.fb.control(DateTime.utc().endOf('day')),
})
@ViewChild(MatSort, { static: false }) set content(sort: MatSort) {
this.data.sort = sort
}
constructor() {
this.toolbar.comp = this
this.toolbar.menu = [
{ check: true, title: 'Ocenianie', fn: 'goBack', icon: 'arrow_back' },
]
this.dateSelector.valueChanges.subscribe(() => {
this.download()
})
}
ngOnInit(): void {
this.download()
}
download() {
this.ac.summary
.getSummary(
this.dateSelector.get('start')!.value!.startOf('day')!,
this.dateSelector.get('end')!.value!.endOf('day')!
)
.subscribe(v => {
this.data.data = v
})
}
goBack() {
this.router.navigate(['../'], { relativeTo: this.route })
}
ngOnDestroy(): void {
this.toolbar.comp = undefined
this.toolbar.menu = undefined
}
}
@@ -0,0 +1,11 @@
<button matButton="outlined" (click)="newGroup()">Nowa grupa</button>
@for (item of groups; track item) {
<mat-card>
<mat-card-header>
<mat-card-title contenteditable appCe (edit)="nameEdit(item._id, $event)">{{item.name}}</mat-card-title>
</mat-card-header>
<mat-card-actions>
<button mat-button class="error-color" (click)="remove(item._id)">Usuń</button>
</mat-card-actions>
</mat-card>
}
@@ -0,0 +1,12 @@
:host {
display: flex;
}
mat-card {
margin: 15px;
padding: 1ch;
}
mat-card-title {
font-size: 1.5rem;
}
@@ -0,0 +1,24 @@
import { ComponentFixture, TestBed } from '@angular/core/testing'
import { GroupsComponent } from './groups.component'
import { GroupsService } from './groups.service'
xdescribe('GroupsComponent', () => {
let component: GroupsComponent
let fixture: ComponentFixture<GroupsComponent>
beforeEach(() => {
const acMock = {}
TestBed.configureTestingModule({
declarations: [GroupsComponent],
providers: [{ provide: GroupsService, useValue: acMock }],
})
fixture = TestBed.createComponent(GroupsComponent)
component = fixture.componentInstance
fixture.detectChanges()
})
it('should create', () => {
expect(component).toBeTruthy()
})
})
@@ -0,0 +1,69 @@
import { Component, inject, OnInit } from '@angular/core'
import { Group } from 'src/app/types/group'
import { Status } from 'src/app/types/status'
import { MatDialog } from '@angular/material/dialog'
import { RemoveConfirmComponent } from './remove-confirm/remove-confirm.component'
import { GroupsService } from './groups.service'
@Component({
selector: 'app-groups',
templateUrl: './groups.component.html',
styleUrls: ['./groups.component.scss'],
standalone: false,
})
export class GroupsComponent implements OnInit {
protected acs = inject(GroupsService)
private dialog = inject(MatDialog)
groups?: Group[]
ngOnInit(): void {
this.acs.getGroups().subscribe(v => {
this.groups = v
})
}
private refreshIfGood(s: Status) {
if (s.status.toString().match(/2\d\d/)) {
this.ngOnInit()
}
}
get groupOptions(): { id: string; text: string }[] {
return this.groups!.map(v => {
return { id: v._id as string, text: v.name as string }
})
}
protected getId(g: Group[] | undefined) {
if (!g) return undefined
return g.map(v => v._id)
}
groupNames(groups: Group[]) {
return groups.flatMap(g => g.name)
}
protected nameEdit(id: string, name: string | string[]) {
name = name as string
this.acs.editName(id, name).subscribe(s => this.refreshIfGood(s))
}
protected newGroup() {
const name = prompt('Nazwa grupy')
if (name) {
this.acs.newGroup(name).subscribe(s => this.refreshIfGood(s))
}
}
protected remove(id: string) {
this.dialog
.open(RemoveConfirmComponent)
.afterClosed()
.subscribe(v => {
if (v) {
this.acs.remove(id).subscribe(s => this.refreshIfGood(s))
}
})
}
}
@@ -0,0 +1,23 @@
import { TestBed } from '@angular/core/testing';
import { GroupsService } from './groups.service';
import { provideHttpClient } from '@angular/common/http';
import { provideHttpClientTesting } from '@angular/common/http/testing';
describe('GroupsService', () => {
let service: GroupsService;
beforeEach(() => {
TestBed.configureTestingModule({
providers: [
provideHttpClient(),
provideHttpClientTesting()
]
});
service = TestBed.inject(GroupsService);
});
it('should be created', () => {
expect(service).toBeTruthy();
});
});
@@ -0,0 +1,45 @@
import { HttpClient } from '@angular/common/http';
import { inject, Injectable } from '@angular/core';
import { Group } from 'src/app/types/group';
import { Status } from 'src/app/types/status';
import { environment } from 'src/environments/environment';
@Injectable({
providedIn: 'root'
})
export class GroupsService {
private http = inject(HttpClient)
getGroups() {
return this.http.get<Group[]>(environment.apiEndpoint + `/admin/groups`, {
withCredentials: true,
})
}
newGroup(name: string) {
return this.http.post<Status>(
environment.apiEndpoint + `/admin/groups`,
{ name: name },
{ withCredentials: true }
)
}
editName(id: string, name: string) {
return this.putGroups(id, { name: name.trim() })
}
remove(id: string) {
return this.http.delete<Status>(
environment.apiEndpoint + `/admin/groups/${id}`,
{ withCredentials: true }
)
}
private putGroups(id: string, update: Partial<Group>) {
return this.http.put<Status>(
environment.apiEndpoint + `/admin/groups/${id}`,
update,
{ withCredentials: true }
)
}
}
@@ -0,0 +1,8 @@
<h1 mat-dialog-title>Czy chcesz usunąć tą grupę?</h1>
<mat-dialog-content>
Ta akcja jest nieodwracalna!
</mat-dialog-content>
<mat-dialog-actions align="end">
<button mat-button mat-dialog-close>Nie</button>
<button mat-button mat-dialog-close="yes" class="error-color">Tak</button>
</mat-dialog-actions>
@@ -0,0 +1,23 @@
import { ComponentFixture, TestBed } from '@angular/core/testing'
import { RemoveConfirmComponent } from './remove-confirm.component'
import { MatDialogModule } from '@angular/material/dialog'
describe('RemoveConfirmComponent', () => {
let component: RemoveConfirmComponent
let fixture: ComponentFixture<RemoveConfirmComponent>
beforeEach(() => {
TestBed.configureTestingModule({
declarations: [RemoveConfirmComponent],
imports: [MatDialogModule],
})
fixture = TestBed.createComponent(RemoveConfirmComponent)
component = fixture.componentInstance
fixture.detectChanges()
})
it('should create', () => {
expect(component).toBeTruthy()
})
})
@@ -0,0 +1,9 @@
import { Component } from '@angular/core'
@Component({
selector: 'app-remove-confirm',
templateUrl: './remove-confirm.component.html',
styleUrls: ['./remove-confirm.component.scss'],
standalone: false,
})
export class RemoveConfirmComponent {}
@@ -0,0 +1,46 @@
<div id="upper-bar">
<mat-form-field>
<mat-label>Wyszukaj</mat-label>
<input matInput (keyup)="filter($event)">
</mat-form-field>
<mat-chip-listbox [(ngModel)]="filters" multiple>
<mat-chip-option value="showAll">Pokaż wszystko</mat-chip-option>
</mat-chip-listbox>
<button mat-icon-button (click)="new()"><mat-icon>add</mat-icon></button>
</div>
@if (loading) {
<mat-spinner></mat-spinner>
}
<table mat-table [dataSource]="keys">
<div matColumnDef="room">
<th mat-header-cell *matHeaderCellDef>Sala</th>
<td mat-cell *matCellDef="let element">{{element.room}}</td>
</div>
<div matColumnDef="whom">
<th mat-header-cell *matHeaderCellDef>Wypożyczający</th>
<td mat-cell *matCellDef="let element"><app-user-display [item]="element.whom"/></td>
</div>
<div matColumnDef="borrow">
<th mat-header-cell *matHeaderCellDef>Data wypożyczenia</th>
<td mat-cell *matCellDef="let element">{{element.borrow.toFormat("HH:mm, ccc d.LL.")}}</td>
</div>
<div matColumnDef="tb">
<th mat-header-cell *matHeaderCellDef>Data zwrotu</th>
<td mat-cell *matCellDef="let element">
@if (element.tb) {
{{element.tb.toFormat("HH:mm, ccc d.LL.")}}
}
</td>
</div>
<div matColumnDef="actions">
<th mat-header-cell *matHeaderCellDef>Akcje</th>
<td mat-cell *matCellDef="let element">
@if (!element.tb) {
<button mat-mini-fab (click)="tb(element._id)"><mat-icon>person_cancel</mat-icon></button>
}
</td>
</div>
<tr mat-header-row *matHeaderRowDef="collumns"></tr>
<tr mat-row *matRowDef="let row; columns: collumns"></tr>
</table>
<mat-paginator pageSize="9" [pageSizeOptions]="[9, 15, 20, 50, 160]"></mat-paginator>
@@ -0,0 +1,5 @@
#upper-bar {
display: flex;
align-items: baseline;
gap: 4pt;
}
@@ -0,0 +1,46 @@
import { ComponentFixture, TestBed } from '@angular/core/testing'
import { AdminKeyComponent } from './key.component'
import { MatFormFieldModule } from '@angular/material/form-field'
import { MatChipsModule } from '@angular/material/chips'
import { MatIconModule } from '@angular/material/icon'
import { MatPaginatorModule } from '@angular/material/paginator'
import { FormsModule } from '@angular/forms'
import { MatProgressSpinnerModule } from '@angular/material/progress-spinner'
import { MatTableModule } from '@angular/material/table'
import { MatInputModule } from '@angular/material/input'
import { NoopAnimationsModule } from '@angular/platform-browser/animations'
import { KeyService } from './key.service'
xdescribe('AdminKeyComponent', () => {
let component: AdminKeyComponent
let fixture: ComponentFixture<AdminKeyComponent>
let acMock
beforeEach(async () => {
acMock = {}
await TestBed.configureTestingModule({
declarations: [AdminKeyComponent],
providers: [{ provide: KeyService, useValue: acMock }],
imports: [
MatFormFieldModule,
MatChipsModule,
MatIconModule,
MatPaginatorModule,
FormsModule,
MatProgressSpinnerModule,
MatTableModule,
MatInputModule,
NoopAnimationsModule,
],
}).compileComponents()
fixture = TestBed.createComponent(AdminKeyComponent)
component = fixture.componentInstance
fixture.detectChanges()
})
it('should create', () => {
expect(component).toBeTruthy()
})
})
@@ -0,0 +1,111 @@
import { AfterViewInit, Component, inject, OnInit, ViewChild } from '@angular/core'
import { MatPaginator } from '@angular/material/paginator'
import { MatTableDataSource } from '@angular/material/table'
import { AKey } from 'src/app/types/key'
import { MatDialog } from '@angular/material/dialog'
import { NewKeyComponent } from './new-key/new-key.component'
import { catchError, throwError } from 'rxjs'
import { MatSnackBar } from '@angular/material/snack-bar'
import { KeyService } from './key.service'
@Component({
selector: 'app-admin-key',
templateUrl: './key.component.html',
styleUrl: './key.component.scss',
standalone: false,
})
export class AdminKeyComponent implements AfterViewInit, OnInit {
private ac = inject(KeyService)
private dialog = inject(MatDialog)
private sb = inject(MatSnackBar)
keys: MatTableDataSource<AKey> = new MatTableDataSource<AKey>()
pureData: AKey[] = []
private _filters: string[] = []
public get filters(): string[] {
return this._filters
}
public set filters(value: string[]) {
if (value.includes('showAll')) {
this.collumns = ['room', 'whom', 'borrow', 'tb', 'actions']
} else {
this.collumns = ['room', 'whom', 'borrow', 'actions']
}
this._filters = value
this.transformData()
}
collumns = ['room', 'whom', 'borrow', 'tb', 'actions']
loading = true
@ViewChild(MatPaginator) paginator!: MatPaginator
constructor(
) {
this.filters = []
}
fetchData() {
this.loading = true
this.ac.getKeys().subscribe(r => {
this.loading = false
this.pureData = r
this.transformData()
})
}
transformData() {
let finalData: AKey[] = this.pureData
if (!this.filters.includes('showAll'))
finalData = finalData.filter(v => v.tb == undefined)
this.keys.data = finalData
}
filter(event: Event) {
const value = (event.target as HTMLInputElement).value
this.keys.filter = value.toLowerCase().trim()
}
ngAfterViewInit(): void {
this.keys.paginator = this.paginator
}
ngOnInit(): void {
this.fetchData()
}
new() {
this.dialog
.open(NewKeyComponent)
.afterClosed()
.subscribe(v => {
if (v) {
this.ac
.postKey(v.room, v.user)
.pipe(
catchError((err) => {
if (err.status == 404) {
this.sb.open('Nie znaleziono użytkownika', undefined, {
duration: 2500,
})
}
return throwError(() => new Error(err.message))
})
)
.subscribe(s => {
if (s.status == 201) {
this.fetchData()
}
})
}
})
}
tb(id: string) {
this.ac.returnKey(id).subscribe(r => {
if (r.status == 200) {
this.fetchData()
}
})
}
}
@@ -0,0 +1,23 @@
import { TestBed } from '@angular/core/testing';
import { KeyService } from './key.service';
import { provideHttpClient } from '@angular/common/http';
import { provideHttpClientTesting } from '@angular/common/http/testing';
describe('KeyService', () => {
let service: KeyService;
beforeEach(() => {
TestBed.configureTestingModule({
providers: [
provideHttpClient(),
provideHttpClientTesting()
]
});
service = TestBed.inject(KeyService);
});
it('should be created', () => {
expect(service).toBeTruthy();
});
});
@@ -0,0 +1,55 @@
import { HttpClient } from '@angular/common/http';
import { inject, Injectable } from '@angular/core';
import { DateTime } from 'luxon';
import { map } from 'rxjs';
import { AKey, AKeyAPI } from 'src/app/types/key';
import { Status } from 'src/app/types/status';
import { environment } from 'src/environments/environment';
@Injectable({
providedIn: 'root'
})
export class KeyService {
private http = inject(HttpClient)
getKeys() {
return this.http
.get<AKeyAPI[]>(environment.apiEndpoint + `/admin/keys`, { withCredentials: true })
.pipe(
map<AKeyAPI[], AKey[]>(v => v.map(r => ({
...r,
borrow: DateTime.fromISO(r.borrow!),
tb: r.tb ? DateTime.fromISO(r.tb!) : undefined
})))
)
}
avalKeys() {
return this.http.get<string[]>(
environment.apiEndpoint + `/admin/keys/available`,
{ withCredentials: true }
)
}
postKey(room: string, uname: string) {
return this.http.post<Status>(
environment.apiEndpoint + `/admin/keys/`,
{ room: room, whom: uname },
{ withCredentials: true }
)
}
returnKey(id: string) {
return this.putKeys(id, { tb: DateTime.now() })
}
private putKeys(id: string, update: Partial<AKey>) {
return this.http.put<Status>(
environment.apiEndpoint + `/admin/keys/${id}`,
update,
{ withCredentials: true }
)
}
}
@@ -0,0 +1,23 @@
<mat-dialog-content>
<form (ngSubmit)="send()" [formGroup]="form">
<mat-form-field>
<mat-label>Sala</mat-label>
<mat-select formControlName="room" required>
@for (item of rooms; track $index) {
<mat-option [value]="item">{{item}}</mat-option>
}
</mat-select>
@if (form.controls['room'].hasError('required')) {
<mat-error>Wymagane</mat-error>
}
</mat-form-field>
<mat-form-field>
<mat-label>Wypożyczający</mat-label>
<app-user-search formControlName="user" required/>
@if (form.controls['user'].hasError('required')) {
<mat-error>Wymagane</mat-error>
}
</mat-form-field>
<button mat-button>Wyślij</button>
</form>
</mat-dialog-content>
@@ -0,0 +1,4 @@
form {
display: flex;
flex-direction: column;
}
@@ -0,0 +1,102 @@
import { ComponentFixture, TestBed } from '@angular/core/testing'
import { NewKeyComponent } from './new-key.component'
import { MatDialogModule, MatDialogRef } from '@angular/material/dialog'
import {
MatFormFieldControl,
MatFormFieldModule,
} from '@angular/material/form-field'
import { MatSelectModule } from '@angular/material/select'
import { Component, forwardRef } from '@angular/core'
import { Observable, of } from 'rxjs'
import {
AbstractControlDirective,
ControlValueAccessor,
FormsModule,
NG_VALUE_ACCESSOR,
NgControl,
ReactiveFormsModule,
} from '@angular/forms'
import { NoopAnimationsModule } from '@angular/platform-browser/animations'
import { KeyService } from '../key.service'
@Component({
selector: 'app-user-search',
template: '',
providers: [
{
provide: NG_VALUE_ACCESSOR,
useExisting: forwardRef(() => UserSearchStub),
multi: true,
},
{
provide: MatFormFieldControl,
useExisting: UserSearchStub,
},
],
standalone: false,
})
class UserSearchStub
implements ControlValueAccessor, MatFormFieldControl<never>
{
value = null
stateChanges: Observable<void> = of()
id = ''
placeholder = ''
ngControl: NgControl | AbstractControlDirective | null = null
focused = false
empty = true
shouldLabelFloat = true
required = false
disabled = false
errorState = false
controlType?: string | undefined
autofilled?: boolean | undefined
userAriaDescribedBy?: string | undefined
// eslint-disable-next-line @typescript-eslint/no-empty-function, @typescript-eslint/no-unused-vars
setDescribedByIds(ids: string[]): void {}
// eslint-disable-next-line @typescript-eslint/no-empty-function, @typescript-eslint/no-unused-vars
onContainerClick(event: MouseEvent): void {}
// eslint-disable-next-line @typescript-eslint/no-empty-function, @typescript-eslint/no-unused-vars
writeValue(obj: unknown): void {}
// eslint-disable-next-line @typescript-eslint/no-empty-function, @typescript-eslint/no-unused-vars
registerOnChange(fn: unknown): void {}
// eslint-disable-next-line @typescript-eslint/no-empty-function, @typescript-eslint/no-unused-vars
registerOnTouched(fn: unknown): void {}
// eslint-disable-next-line @typescript-eslint/no-empty-function, @typescript-eslint/no-unused-vars
setDisabledState?(isDisabled: boolean): void {}
}
xdescribe('NewKeyComponent', () => {
let component: NewKeyComponent
let fixture: ComponentFixture<NewKeyComponent>
let acMock
beforeEach(async () => {
acMock = {
}
await TestBed.configureTestingModule({
declarations: [NewKeyComponent, UserSearchStub],
providers: [
{ provide: KeyService, useValue: acMock },
{ provide: MatDialogRef, useValue: {} },
],
imports: [
MatDialogModule,
MatFormFieldModule,
MatSelectModule,
FormsModule,
ReactiveFormsModule,
NoopAnimationsModule,
],
}).compileComponents()
fixture = TestBed.createComponent(NewKeyComponent)
component = fixture.componentInstance
fixture.detectChanges()
})
it('should create', () => {
expect(component).toBeTruthy()
})
})
@@ -0,0 +1,32 @@
import { Component, inject, OnInit } from '@angular/core'
import { MatDialogRef } from '@angular/material/dialog'
import { FormControl, FormGroup } from '@angular/forms'
import { UserSearchResult } from 'src/app/commonComponents/user-search/user-search.component'
import { KeyService } from '../key.service'
@Component({
selector: 'app-new-key',
templateUrl: './new-key.component.html',
styleUrl: './new-key.component.scss',
standalone: false,
})
export class NewKeyComponent implements OnInit {
private ac = inject(KeyService)
public dialogRef: MatDialogRef<NewKeyComponent> = inject(MatDialogRef)
rooms: string[] = []
form = new FormGroup({
room: new FormControl<string>(''),
user: new FormControl<UserSearchResult | null>(null),
})
ngOnInit(): void {
this.ac.avalKeys().subscribe(v => {
this.rooms = v
})
}
send() {
if (this.form.valid) this.dialogRef.close(this.form.value)
}
}
@@ -0,0 +1,33 @@
<h1 mat-dialog-title>Tworzenie wpisów do jadłospisu</h1>
<mat-dialog-content>
<mat-radio-group [(ngModel)]="type">
<mat-radio-button value="day">Dzień</mat-radio-button>
<mat-radio-button value="week">Tydzień</mat-radio-button>
<mat-radio-button value="file">Plik</mat-radio-button>
</mat-radio-group>
<div>
@switch (type) {
@case ("day") {
<app-date-selector [filter]="filter" [(date)]="day"></app-date-selector>
}
@case ("week") {
<mat-form-field>
<mat-label>Wybierz tydzień</mat-label>
<mat-date-range-input [rangePicker]="picker" [formGroup]="range">
<input matStartDate formControlName="start">
<input matEndDate formControlName="end">
</mat-date-range-input>
<mat-datepicker-toggle matIconSuffix [for]="picker"></mat-datepicker-toggle>
<mat-date-range-picker #picker></mat-date-range-picker>
</mat-form-field>
}
@case ("file") {
<button mat-flat-button (click)="activateUpload()">Otwórz okno</button>
}
}
</div>
</mat-dialog-content>
<mat-dialog-actions>
<button matButton="outlined" (click)="submit()">Utwórz pozycje</button>
<button mat-button mat-dialog-close>Anuluj</button>
</mat-dialog-actions>
@@ -0,0 +1,39 @@
import { ComponentFixture, TestBed } from '@angular/core/testing'
import { MenuAddComponent } from './menu-add.component'
import {
MAT_DIALOG_DATA,
MatDialogModule,
MatDialogRef,
} from '@angular/material/dialog'
import { MatRadioModule } from '@angular/material/radio'
import { FormsModule, ReactiveFormsModule } from '@angular/forms'
describe('MenuAddComponent', () => {
let component: MenuAddComponent
let fixture: ComponentFixture<MenuAddComponent>
beforeEach(async () => {
await TestBed.configureTestingModule({
declarations: [MenuAddComponent],
providers: [
{ provide: MAT_DIALOG_DATA, useValue: {} },
{ provide: MatDialogRef, useValue: {} },
],
imports: [
MatDialogModule,
MatRadioModule,
ReactiveFormsModule,
FormsModule,
],
}).compileComponents()
fixture = TestBed.createComponent(MenuAddComponent)
component = fixture.componentInstance
fixture.detectChanges()
})
it('should create', () => {
expect(component).toBeTruthy()
})
})
@@ -0,0 +1,59 @@
import { Component, inject, signal } from '@angular/core'
import { MenuUploadComponent } from '../menu-upload/menu-upload.component'
import { MatDialog, MatDialogRef } from '@angular/material/dialog'
import { FDSelection } from 'src/app/fd.da'
import { FormControl, FormGroup } from '@angular/forms'
import { MAT_DATE_RANGE_SELECTION_STRATEGY } from '@angular/material/datepicker'
import { DateTime } from 'luxon'
import { weekendFilter } from 'src/app/util'
@Component({
selector: 'app-menu-add',
templateUrl: './menu-add.component.html',
styleUrl: './menu-add.component.scss',
providers: [
{ provide: MAT_DATE_RANGE_SELECTION_STRATEGY, useClass: FDSelection },
],
standalone: false,
})
export class MenuAddComponent {
public dialogRef: MatDialogRef<MenuAddComponent> = inject(MatDialogRef)
private dialog = inject(MatDialog)
type: string | undefined
filter = weekendFilter
day = signal<DateTime>(DateTime.now())
range = new FormGroup({
start: new FormControl<DateTime | null>(null),
end: new FormControl<DateTime | null>(null),
})
submit() {
switch (this.type) {
case 'day':
this.dialogRef.close({ type: 'day', value: this.day() })
break
case 'week':
this.dialogRef.close({
type: 'week',
value: { start: this.range.value.start, count: 5 },
})
break
default:
break
}
}
activateUpload() {
this.dialog
.open(MenuUploadComponent)
.afterClosed()
.subscribe(data => {
if (data) {
this.dialogRef.close({ type: 'file', ...data })
}
})
}
}
@@ -0,0 +1,147 @@
<div id="upper-bar">
<mat-form-field subscriptSizing="dynamic">
<mat-label>Wybierz tydzień</mat-label>
<mat-date-range-input [rangePicker]="picker" [formGroup]="range">
<input matStartDate formControlName="start">
<input matEndDate formControlName="end">
</mat-date-range-input>
<mat-datepicker-toggle matIconSuffix [for]="picker"></mat-datepicker-toggle>
<mat-date-range-picker #picker></mat-date-range-picker>
</mat-form-field>
<button mat-icon-button (click)="ac.refresh()"><mat-icon>search</mat-icon></button>
<button mat-icon-button (click)="addDate()"><mat-icon>add</mat-icon></button>
<button mat-icon-button (click)="print()"><mat-icon>print</mat-icon></button>
</div>
<div class="mainc">
@switch (ac.state()) {
@case (0) {
<p>Wybierz zakres dat powyżej i kliknij szukaj</p>
}
@case (1) {
<div class="spinner">
<mat-spinner/>
</div>
}
@case (2) {
<table mat-table [dataSource]="dataSource">
<div matColumnDef="day">
<th mat-header-cell *matHeaderCellDef>Dzień</th>
<td mat-cell *matCellDef="let element">
<span>{{element.day.toFormat('dd.LL.yyyy')}}r.</span>
<p>{{element.day.toFormat('cccc') | titlecase }}</p>
<app-field-editor category="Nazwa" [(word)]="element.dayTitle" (wordChange)="editTitle(element._id)"/><br><hr>
<button (click)="remove(element._id)">Usuń dzień</button>
</td>
</div>
<div matColumnDef="sn">
<th mat-header-cell *matHeaderCellDef>Śniadanie</th>
<td mat-cell *matCellDef="let element">
<ul class="non-editable">
@for (i of ls.defaultItems.sn; track i) {
<li>{{i}}</li>
}
</ul><hr>
<app-list-editor [(list)]="element.sn.fancy" (edit)="editSn(element._id)" dataList="sn-fancy"/><hr>
<ul>
<li><app-field-editor category="II Śniadanie" [(word)]="element.sn.second" list="sn-second" (wordChange)="editSn(element._id)"/></li>
</ul>
</td>
</div>
<div matColumnDef="ob">
<th mat-header-cell *matHeaderCellDef>Obiad</th>
<td mat-cell *matCellDef="let element">
<ul>
<li><app-field-editor category="Zupa" [(word)]="element.ob.soup" list="ob-soup" (wordChange)="editOb(element._id)"/></li>
<li><app-field-editor category="Vege" [(word)]="element.ob.vege" list="ob-vege" (wordChange)="editOb(element._id)"/></li>
<li><app-field-editor category="Danie główne" [(word)]="element.ob.meal" list="ob-meal" (wordChange)="editOb(element._id)"/></li>
</ul><hr>
<app-list-editor [(list)]="element.ob.condiments" (edit)="editOb(element._id)" dataList="ob-condiments"/><hr>
<ul>
<li><app-field-editor category="Napój" [(word)]="element.ob.drink" list="ob-drink" (wordChange)="editOb(element._id)"/></li>
</ul><hr>
<app-list-editor [(list)]="element.ob.other" (edit)="editOb(element._id)" dataList="ob-other"/>
</td>
</div>
<div matColumnDef="kol">
<th mat-header-cell *matHeaderCellDef>Kolacja</th>
<td mat-cell *matCellDef="let element">
<div>
@switch (element.day.weekday) {
@default {
<div>
<ul class="non-editable">
@for (i of ls.defaultItems.kol; track i) {
<li>{{i}}</li>
}
</ul><hr>
<ul>
<li><app-field-editor category="Kolacja" [(word)]="element.kol" list="kol" (wordChange)="editKol(element._id)"/></li>
</ul>
</div>
}
@case (5) {
<div class="non-editable">
<p>Kolacja w domu!</p>
<p>(Nie edytowalne)</p>
</div>
}
}
</div>
</td>
</div>
<tr mat-header-row *matHeaderRowDef="dcols"></tr>
<tr mat-row *matRowDef="let row; columns: dcols"></tr>
</table>
}
}
</div>
@if (options) {
<datalist id="sn-fancy">
@for (i of options.sn.fancy; track i) {
<option>{{i}}</option>
}
</datalist>
<datalist id="sn-second">
@for (i of options.sn.second; track i) {
<option>{{i}}</option>
}
</datalist>
<datalist id="ob-soup">
@for (i of options.ob.soup; track i) {
<option>{{i}}</option>
}
</datalist>
<datalist id="ob-vege">
@for (i of options.ob.vege; track i) {
<option>{{i}}</option>
}
</datalist>
<datalist id="ob-meal">
@for (i of options.ob.meal; track i) {
<option>{{i}}</option>
}
</datalist>
<datalist id="ob-condiments">
@for (i of options.ob.condiments; track i) {
<option>{{i}}</option>
}
</datalist>
<datalist id="ob-drink">
@for (i of options.ob.drink; track i) {
<option>{{i}}</option>
}
</datalist>
<datalist id="ob-other">
@for (i of options.ob.other; track i) {
<option>{{i}}</option>
}
</datalist>
<datalist id="kol">
@for (i of options.kol; track i) {
<option>{{i}}</option>
}
</datalist>
}
@@ -0,0 +1,34 @@
#upper-bar {
display: flex;
}
mat-form-field {
flex-grow: 1;
}
button[mat-icon-button] {
margin-left: 4pt;
margin-right: 4pt;
margin-top: 4pt;
}
.non-editable {
color: gray;
font-style: italic;
}
.mainc {
height: 100%;
position: relative;
}
.spinner {
position: absolute;
top: 0;
bottom: 0;
left: 0;
right: 0;
display: flex;
align-items: center;
justify-content: center;
}
@@ -0,0 +1,49 @@
import { ComponentFixture, TestBed } from '@angular/core/testing'
import { MenuEditComponent } from './menu-edit.component'
import { MatTableModule } from '@angular/material/table'
import { MatInputModule } from '@angular/material/input'
import {
MAT_DATE_RANGE_SELECTION_STRATEGY,
MatDatepickerModule,
} from '@angular/material/datepicker'
import { BrowserAnimationsModule } from '@angular/platform-browser/animations'
import { FDSelection } from 'src/app/fd.da'
import { ReactiveFormsModule } from '@angular/forms'
import { MatDialogModule } from '@angular/material/dialog'
import { MatIconModule } from '@angular/material/icon'
import { provideLuxonDateAdapter } from '@angular/material-luxon-adapter'
import { MenuEditService } from './menu-edit.service'
xdescribe('MenuEditComponent', () => {
let component: MenuEditComponent
let fixture: ComponentFixture<MenuEditComponent>
beforeEach(() => {
const acMock = jasmine.createSpyObj('MenuEditService', {})
TestBed.configureTestingModule({
declarations: [MenuEditComponent],
imports: [
MatTableModule,
MatInputModule,
MatDatepickerModule,
BrowserAnimationsModule,
ReactiveFormsModule,
MatDialogModule,
MatIconModule,
],
providers: [
provideLuxonDateAdapter(),
{ provide: MAT_DATE_RANGE_SELECTION_STRATEGY, useClass: FDSelection },
{ provide: MenuEditService, useValue: acMock },
],
})
fixture = TestBed.createComponent(MenuEditComponent)
component = fixture.componentInstance
fixture.detectChanges()
})
it('should create', () => {
expect(component).toBeTruthy()
})
})
@@ -0,0 +1,160 @@
import { Component, inject, OnDestroy } from '@angular/core'
import { FormControl, FormGroup } from '@angular/forms'
import { MAT_DATE_RANGE_SELECTION_STRATEGY } from '@angular/material/datepicker'
import { FDSelection } from 'src/app/fd.da'
import { Menu } from 'src/app/types/menu'
import { MatTableDataSource } from '@angular/material/table'
import { MatDialog } from '@angular/material/dialog'
import { MenuUploadComponent } from './menu-upload/menu-upload.component'
import { Status } from 'src/app/types/status'
import { MatSnackBar } from '@angular/material/snack-bar'
import { MenuAddComponent } from './menu-add/menu-add.component'
import { LocalStorageService } from 'src/app/services/local-storage.service'
import { DateTime } from 'luxon'
import { MenuEditService } from './menu-edit.service'
import { MenuOptions } from './menu-edit.model'
import { ToolbarService } from '../toolbar/toolbar.service'
import { ActivatedRoute, Router } from '@angular/router'
@Component({
selector: 'app-menu-edit',
templateUrl: './menu-edit.component.html',
styleUrls: ['./menu-edit.component.scss'],
providers: [
{ provide: MAT_DATE_RANGE_SELECTION_STRATEGY, useClass: FDSelection },
],
standalone: false,
})
export class MenuEditComponent implements OnDestroy {
protected ac = inject(MenuEditService)
private dialog = inject(MatDialog)
private sb = inject(MatSnackBar)
private tb = inject(ToolbarService)
private router = inject(Router)
private route = inject(ActivatedRoute)
readonly ls = inject(LocalStorageService)
dcols: string[] = ['day', 'sn', 'ob', 'kol']
dataSource: MatTableDataSource<Menu> = new MatTableDataSource<Menu>()
range = new FormGroup({
start: new FormControl<DateTime | null>(null),
end: new FormControl<DateTime | null>(null),
})
public options?: MenuOptions
constructor() {
this.range.setValue(this.ac.seDates())
this.range.valueChanges.subscribe(v => {
this.ac.seDates.set({start: v.start!, end: v.end!})
})
this.ac.menuItems.subscribe(v => {
this.dataSource.data = v
})
this.refresh()
this.tb.comp = this
this.tb.menu = [
{ title: "Badanie opinii", icon: "analytics", fn: "statistics"}
]
}
ngOnDestroy(): void {
this.tb.comp = undefined
this.tb.menu = undefined
}
statistics() {
this.router.navigate(['stats'], { relativeTo: this.route })
}
print() {
this.ac
.print(this.range.value.start, this.range.value.end)
?.subscribe(r => {
if (r && r.length > 0) {
const mywindow = window.open(
undefined,
'Drukowanie',
'height=400,width=400'
)
mywindow?.document.write(r)
mywindow?.print()
mywindow?.close()
}
})
}
addDate() {
this.dialog
.open(MenuAddComponent)
.afterClosed()
.subscribe(data => {
if (data) {
switch (data.type) {
case 'day':
this.ac.new
.single(data.value)
.subscribe(s => this.refreshIfGood(s))
break
case 'week':
this.ac.new
.range(data.value.start, data.value.count)
.subscribe(s => this.refreshIfGood(s))
break
case 'file':
this.refresh()
break
default:
break
}
}
})
}
refresh() {
this.ac.refresh()
this.ac.getOpts().subscribe(o => {
this.options = o
})
}
private refreshIfGood(s: Status) {
if (s.status.toString().match(/2\d\d/)) this.refresh()
}
activateUpload() {
this.dialog
.open(MenuUploadComponent)
.afterClosed()
.subscribe(data => {
if (data) this.refresh()
})
}
editSn(id: string) {
this.ac
.editSn(id, this.dataSource.data.find(v => v._id == id)!.sn)
.subscribe(s => this.refreshIfGood(s))
}
editOb(id: string) {
this.ac
.editOb(id, this.dataSource.data.find(v => v._id == id)!.ob)
.subscribe(s => this.refreshIfGood(s))
}
editKol(id: string) {
this.ac
.editKol(id, this.dataSource.data.find(v => v._id == id)?.kol)
.subscribe(s => this.refreshIfGood(s))
}
editTitle(id: string) {
this.ac
.editTitle(id, this.dataSource.data.find(v => v._id == id)?.dayTitle)
.subscribe(s => this.refreshIfGood(s))
}
remove(id: string) {
this.ac.rm(id).subscribe(s => this.refreshIfGood(s))
}
}
@@ -0,0 +1,15 @@
export interface MenuOptions {
sn: {
fancy: string[]
second: string[]
}
ob: {
soup: string[]
vege: string[]
meal: string[]
condiments: string[]
drink: string[]
other: string[]
}
kol: string[]
}
@@ -0,0 +1,23 @@
import { TestBed } from '@angular/core/testing';
import { MenuEditService } from './menu-edit.service';
import { provideHttpClient } from '@angular/common/http';
import { provideHttpClientTesting } from '@angular/common/http/testing';
describe('MenuEditService', () => {
let service: MenuEditService;
beforeEach(() => {
TestBed.configureTestingModule({
providers: [
provideHttpClient(),
provideHttpClientTesting()
]
});
service = TestBed.inject(MenuEditService);
});
it('should be created', () => {
expect(service).toBeTruthy();
});
});
@@ -0,0 +1,145 @@
import { HttpClient } from '@angular/common/http';
import { inject, Injectable, signal } from '@angular/core';
import { DateTime } from 'luxon';
import { BehaviorSubject, catchError, map, of } from 'rxjs';
import { Menu, MenuAPI } from 'src/app/types/menu';
import { STATE } from 'src/app/types/state';
import { Status } from 'src/app/types/status';
import { environment } from 'src/environments/environment';
import { MenuOptions } from './menu-edit.model';
@Injectable({
providedIn: 'root'
})
export class MenuEditService {
private http = inject(HttpClient)
private _menuItems = new BehaviorSubject<Menu[]>([])
public readonly menuItems = this._menuItems.asObservable()
private _state = signal(STATE.NOT_LOADED);
public readonly state = this._state.asReadonly();
private _error = signal<string | undefined>(undefined);
public readonly error = this._error.asReadonly();
seDates = signal<{
start: DateTime | null,
end: DateTime | null
}>({
start: null,
end: null
})
public refresh() {
this.getMenu()
}
private getMenu() {
if (!(this.seDates().start && this.seDates().end)) return
this._state.set(STATE.PENDING)
const body = { start: this.seDates().start!.toString(), end: this.seDates().end!.toString() }
this.http.get
<MenuAPI[]>
(environment.apiEndpoint + `/admin/menu`, { withCredentials: true, params: body })
.pipe(
catchError((err: Error) => {
this._state.set(STATE.ERROR)
this._error.set(err.message)
return of()
}),
map<MenuAPI[], Menu[]>(v =>
v.map(i => ({
...i,
day: DateTime.fromISO(i.day)
})))
).subscribe(v => {
this._error.set(undefined)
this._menuItems.next(v ?? [])
this._state.set(STATE.LOADED)
})
}
getOpts() {
return this.http.get<MenuOptions>(environment.apiEndpoint + `/admin/menu/opts`, {
withCredentials: true,
})
}
postMenu(file: File) {
if (file) {
const formData = new FormData()
formData.append('menu', file)
return this.http.post<Status>(
environment.apiEndpoint + '/admin/menu/upload',
formData,
{ withCredentials: true }
)
}
return
}
editSn(id: string, content: Menu['sn']) {
return this.putMenu(id, { sn: content })
}
editOb(id: string, content: Menu['ob']) {
return this.putMenu(id, { ob: content })
}
editKol(id: string, content: Menu['kol']) {
return this.putMenu(id, { kol: content })
}
editTitle(id: string, content: Menu['dayTitle']) {
return this.putMenu(id, { dayTitle: content })
}
print(start?: DateTime | null, end?: DateTime | null) {
if (start && end) {
const body = { start: start.toString(), end: end.toString() }
return this.http.get(environment.apiEndpoint + '/admin/menu/print', {
withCredentials: true,
params: body,
responseType: 'text',
})
}
return
}
stat(day: DateTime, m: 'ob' | 'kol') {
return this.http.get<{ y: number; n: number }>(
environment.apiEndpoint + `/admin/menu/${day.toISO()}/votes/${m}`,
{ withCredentials: true }
)
}
new = {
single: (day: DateTime) => {
return this.http.post<Status>(
environment.apiEndpoint + `/admin/menu/${day.toISO()}`,
null,
{ withCredentials: true }
)
},
range: (start: DateTime, count: number) => {
return this.http.post<Status>(
environment.apiEndpoint + `/admin/menu/${start.toISO()}/${count}/`,
null,
{ withCredentials: true }
)
},
}
rm(id: string) {
return this.http.delete<Status>(
environment.apiEndpoint + `/admin/menu/${id}`,
{ withCredentials: true }
)
}
private putMenu(id: string, update: Partial<Menu>) {
return this.http.put<Status>(
environment.apiEndpoint + `/admin/menu/${id}`,
update,
{ withCredentials: true }
)
}
}
@@ -0,0 +1,45 @@
<h2 mat-dialog-title>
{{ data.date.toFormat('dd.LL.yyyy') }}<br />
{{ data.item }}
</h2>
<mat-dialog-content>
@switch (msi.state()) {
@case (1) {
<div class="spinner">
<mat-spinner />
</div>
}
@case (2) {
<p>Ilość opinii: {{ count }}</p>
<p>Ocena:</p>
<app-star-control [value]="rating" [display]="true"></app-star-control>
<p>Komentarze:</p>
@for (item of comments; track $index) {
<mat-card class="comment">
<mat-card-content>
{{item}}
</mat-card-content>
</mat-card>
}
@empty {
<p class="gray">Brak</p>
}
<p>Tagi:</p>
<mat-chip-set role="list">
@for (tag of tags | keyvalue; track tag.key) {
<mat-chip role="listitem">
{{tag.key}} — {{tag.value}}
</mat-chip>
}
</mat-chip-set>
}
@case (3) {
<p>Wystąpił błąd podczas ładowania statystyk: {{msi.error()}}</p>
}
}
</mat-dialog-content>
<mat-dialog-actions align="end">
<button mat-button mat-dialog-close>Close</button>
</mat-dialog-actions>

Some files were not shown because too many files have changed in this diff Show More