Compare commits
17 Commits
diags
...
solidarity
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
52de8d363e | ||
|
|
d992a7984f | ||
|
|
a6f70a6e85 | ||
|
|
20a3b6ed3b | ||
|
|
8c0b6f7d5c | ||
|
|
9ab7b66b68 | ||
| 95b60ea737 | |||
| ea5be2e157 | |||
| 7914cd919f | |||
| 0dc694324e | |||
| a75a31b151 | |||
| 2660b82bdb | |||
| 1685d1e1ac | |||
| 7c78ce9c37 | |||
| 90614ab65a | |||
| c8f8f82535 | |||
| 0f5a0ed5ab |
2
.gitignore
vendored
2
.gitignore
vendored
@@ -2,3 +2,5 @@
|
||||
themes/*
|
||||
.vscode
|
||||
__debug_bin
|
||||
parcoursmob
|
||||
.idea
|
||||
|
||||
@@ -19,9 +19,12 @@ COPY . .
|
||||
|
||||
RUN go mod download && CGO_ENABLED=0 GOOS=linux GOARCH=amd64 go build -o /server
|
||||
|
||||
RUN rm -r themes/*
|
||||
RUN rm -r themes
|
||||
RUN mkdir themes
|
||||
|
||||
RUN git clone --depth 1 https://git.coopgo.io/coopgo-apps/parcoursmob-default-theme themes/default
|
||||
RUN git clone -b spie06 --depth 1 https://git.coopgo.io/coopgo-apps/parcoursmob-default-theme themes/spie06
|
||||
RUN git clone -b solidarity-transport-dev --depth 1 https://git.coopgo.io/coopgo-apps/parcoursmob-default-theme themes/solidarity-transport
|
||||
|
||||
FROM scratch
|
||||
COPY --from=builder /etc/ssl/certs/ca-certificates.crt /etc/ssl/certs/
|
||||
|
||||
660
LICENSE.md
Normal file
660
LICENSE.md
Normal file
@@ -0,0 +1,660 @@
|
||||
# GNU AFFERO GENERAL PUBLIC LICENSE
|
||||
|
||||
Version 3, 19 November 2007
|
||||
|
||||
Copyright (C) 2007 Free Software Foundation, Inc.
|
||||
<https://fsf.org/>
|
||||
|
||||
Everyone is permitted to copy and distribute verbatim copies of this
|
||||
license document, but changing it is not allowed.
|
||||
|
||||
## Preamble
|
||||
|
||||
The GNU Affero General Public License is a free, copyleft license for
|
||||
software and other kinds of works, specifically designed to ensure
|
||||
cooperation with the community in the case of network server software.
|
||||
|
||||
The licenses for most software and other practical works are designed
|
||||
to take away your freedom to share and change the works. By contrast,
|
||||
our General Public Licenses are intended to guarantee your freedom to
|
||||
share and change all versions of a program--to make sure it remains
|
||||
free software for all its users.
|
||||
|
||||
When we speak of free software, we are referring to freedom, not
|
||||
price. Our General Public Licenses are designed to make sure that you
|
||||
have the freedom to distribute copies of free software (and charge for
|
||||
them if you wish), that you receive source code or can get it if you
|
||||
want it, that you can change the software or use pieces of it in new
|
||||
free programs, and that you know you can do these things.
|
||||
|
||||
Developers that use our General Public Licenses protect your rights
|
||||
with two steps: (1) assert copyright on the software, and (2) offer
|
||||
you this License which gives you legal permission to copy, distribute
|
||||
and/or modify the software.
|
||||
|
||||
A secondary benefit of defending all users' freedom is that
|
||||
improvements made in alternate versions of the program, if they
|
||||
receive widespread use, become available for other developers to
|
||||
incorporate. Many developers of free software are heartened and
|
||||
encouraged by the resulting cooperation. However, in the case of
|
||||
software used on network servers, this result may fail to come about.
|
||||
The GNU General Public License permits making a modified version and
|
||||
letting the public access it on a server without ever releasing its
|
||||
source code to the public.
|
||||
|
||||
The GNU Affero General Public License is designed specifically to
|
||||
ensure that, in such cases, the modified source code becomes available
|
||||
to the community. It requires the operator of a network server to
|
||||
provide the source code of the modified version running there to the
|
||||
users of that server. Therefore, public use of a modified version, on
|
||||
a publicly accessible server, gives the public access to the source
|
||||
code of the modified version.
|
||||
|
||||
An older license, called the Affero General Public License and
|
||||
published by Affero, was designed to accomplish similar goals. This is
|
||||
a different license, not a version of the Affero GPL, but Affero has
|
||||
released a new version of the Affero GPL which permits relicensing
|
||||
under this license.
|
||||
|
||||
The precise terms and conditions for copying, distribution and
|
||||
modification follow.
|
||||
|
||||
## TERMS AND CONDITIONS
|
||||
|
||||
### 0. Definitions.
|
||||
|
||||
"This License" refers to version 3 of the GNU Affero General Public
|
||||
License.
|
||||
|
||||
"Copyright" also means copyright-like laws that apply to other kinds
|
||||
of works, such as semiconductor masks.
|
||||
|
||||
"The Program" refers to any copyrightable work licensed under this
|
||||
License. Each licensee is addressed as "you". "Licensees" and
|
||||
"recipients" may be individuals or organizations.
|
||||
|
||||
To "modify" a work means to copy from or adapt all or part of the work
|
||||
in a fashion requiring copyright permission, other than the making of
|
||||
an exact copy. The resulting work is called a "modified version" of
|
||||
the earlier work or a work "based on" the earlier work.
|
||||
|
||||
A "covered work" means either the unmodified Program or a work based
|
||||
on the Program.
|
||||
|
||||
To "propagate" a work means to do anything with it that, without
|
||||
permission, would make you directly or secondarily liable for
|
||||
infringement under applicable copyright law, except executing it on a
|
||||
computer or modifying a private copy. Propagation includes copying,
|
||||
distribution (with or without modification), making available to the
|
||||
public, and in some countries other activities as well.
|
||||
|
||||
To "convey" a work means any kind of propagation that enables other
|
||||
parties to make or receive copies. Mere interaction with a user
|
||||
through a computer network, with no transfer of a copy, is not
|
||||
conveying.
|
||||
|
||||
An interactive user interface displays "Appropriate Legal Notices" to
|
||||
the extent that it includes a convenient and prominently visible
|
||||
feature that (1) displays an appropriate copyright notice, and (2)
|
||||
tells the user that there is no warranty for the work (except to the
|
||||
extent that warranties are provided), that licensees may convey the
|
||||
work under this License, and how to view a copy of this License. If
|
||||
the interface presents a list of user commands or options, such as a
|
||||
menu, a prominent item in the list meets this criterion.
|
||||
|
||||
### 1. Source Code.
|
||||
|
||||
The "source code" for a work means the preferred form of the work for
|
||||
making modifications to it. "Object code" means any non-source form of
|
||||
a work.
|
||||
|
||||
A "Standard Interface" means an interface that either is an official
|
||||
standard defined by a recognized standards body, or, in the case of
|
||||
interfaces specified for a particular programming language, one that
|
||||
is widely used among developers working in that language.
|
||||
|
||||
The "System Libraries" of an executable work include anything, other
|
||||
than the work as a whole, that (a) is included in the normal form of
|
||||
packaging a Major Component, but which is not part of that Major
|
||||
Component, and (b) serves only to enable use of the work with that
|
||||
Major Component, or to implement a Standard Interface for which an
|
||||
implementation is available to the public in source code form. A
|
||||
"Major Component", in this context, means a major essential component
|
||||
(kernel, window system, and so on) of the specific operating system
|
||||
(if any) on which the executable work runs, or a compiler used to
|
||||
produce the work, or an object code interpreter used to run it.
|
||||
|
||||
The "Corresponding Source" for a work in object code form means all
|
||||
the source code needed to generate, install, and (for an executable
|
||||
work) run the object code and to modify the work, including scripts to
|
||||
control those activities. However, it does not include the work's
|
||||
System Libraries, or general-purpose tools or generally available free
|
||||
programs which are used unmodified in performing those activities but
|
||||
which are not part of the work. For example, Corresponding Source
|
||||
includes interface definition files associated with source files for
|
||||
the work, and the source code for shared libraries and dynamically
|
||||
linked subprograms that the work is specifically designed to require,
|
||||
such as by intimate data communication or control flow between those
|
||||
subprograms and other parts of the work.
|
||||
|
||||
The Corresponding Source need not include anything that users can
|
||||
regenerate automatically from other parts of the Corresponding Source.
|
||||
|
||||
The Corresponding Source for a work in source code form is that same
|
||||
work.
|
||||
|
||||
### 2. Basic Permissions.
|
||||
|
||||
All rights granted under this License are granted for the term of
|
||||
copyright on the Program, and are irrevocable provided the stated
|
||||
conditions are met. This License explicitly affirms your unlimited
|
||||
permission to run the unmodified Program. The output from running a
|
||||
covered work is covered by this License only if the output, given its
|
||||
content, constitutes a covered work. This License acknowledges your
|
||||
rights of fair use or other equivalent, as provided by copyright law.
|
||||
|
||||
You may make, run and propagate covered works that you do not convey,
|
||||
without conditions so long as your license otherwise remains in force.
|
||||
You may convey covered works to others for the sole purpose of having
|
||||
them make modifications exclusively for you, or provide you with
|
||||
facilities for running those works, provided that you comply with the
|
||||
terms of this License in conveying all material for which you do not
|
||||
control copyright. Those thus making or running the covered works for
|
||||
you must do so exclusively on your behalf, under your direction and
|
||||
control, on terms that prohibit them from making any copies of your
|
||||
copyrighted material outside their relationship with you.
|
||||
|
||||
Conveying under any other circumstances is permitted solely under the
|
||||
conditions stated below. Sublicensing is not allowed; section 10 makes
|
||||
it unnecessary.
|
||||
|
||||
### 3. Protecting Users' Legal Rights From Anti-Circumvention Law.
|
||||
|
||||
No covered work shall be deemed part of an effective technological
|
||||
measure under any applicable law fulfilling obligations under article
|
||||
11 of the WIPO copyright treaty adopted on 20 December 1996, or
|
||||
similar laws prohibiting or restricting circumvention of such
|
||||
measures.
|
||||
|
||||
When you convey a covered work, you waive any legal power to forbid
|
||||
circumvention of technological measures to the extent such
|
||||
circumvention is effected by exercising rights under this License with
|
||||
respect to the covered work, and you disclaim any intention to limit
|
||||
operation or modification of the work as a means of enforcing, against
|
||||
the work's users, your or third parties' legal rights to forbid
|
||||
circumvention of technological measures.
|
||||
|
||||
### 4. Conveying Verbatim Copies.
|
||||
|
||||
You may convey verbatim copies of the Program's source code as you
|
||||
receive it, in any medium, provided that you conspicuously and
|
||||
appropriately publish on each copy an appropriate copyright notice;
|
||||
keep intact all notices stating that this License and any
|
||||
non-permissive terms added in accord with section 7 apply to the code;
|
||||
keep intact all notices of the absence of any warranty; and give all
|
||||
recipients a copy of this License along with the Program.
|
||||
|
||||
You may charge any price or no price for each copy that you convey,
|
||||
and you may offer support or warranty protection for a fee.
|
||||
|
||||
### 5. Conveying Modified Source Versions.
|
||||
|
||||
You may convey a work based on the Program, or the modifications to
|
||||
produce it from the Program, in the form of source code under the
|
||||
terms of section 4, provided that you also meet all of these
|
||||
conditions:
|
||||
|
||||
- a) The work must carry prominent notices stating that you modified
|
||||
it, and giving a relevant date.
|
||||
- b) The work must carry prominent notices stating that it is
|
||||
released under this License and any conditions added under
|
||||
section 7. This requirement modifies the requirement in section 4
|
||||
to "keep intact all notices".
|
||||
- c) You must license the entire work, as a whole, under this
|
||||
License to anyone who comes into possession of a copy. This
|
||||
License will therefore apply, along with any applicable section 7
|
||||
additional terms, to the whole of the work, and all its parts,
|
||||
regardless of how they are packaged. This License gives no
|
||||
permission to license the work in any other way, but it does not
|
||||
invalidate such permission if you have separately received it.
|
||||
- d) If the work has interactive user interfaces, each must display
|
||||
Appropriate Legal Notices; however, if the Program has interactive
|
||||
interfaces that do not display Appropriate Legal Notices, your
|
||||
work need not make them do so.
|
||||
|
||||
A compilation of a covered work with other separate and independent
|
||||
works, which are not by their nature extensions of the covered work,
|
||||
and which are not combined with it such as to form a larger program,
|
||||
in or on a volume of a storage or distribution medium, is called an
|
||||
"aggregate" if the compilation and its resulting copyright are not
|
||||
used to limit the access or legal rights of the compilation's users
|
||||
beyond what the individual works permit. Inclusion of a covered work
|
||||
in an aggregate does not cause this License to apply to the other
|
||||
parts of the aggregate.
|
||||
|
||||
### 6. Conveying Non-Source Forms.
|
||||
|
||||
You may convey a covered work in object code form under the terms of
|
||||
sections 4 and 5, provided that you also convey the machine-readable
|
||||
Corresponding Source under the terms of this License, in one of these
|
||||
ways:
|
||||
|
||||
- a) Convey the object code in, or embodied in, a physical product
|
||||
(including a physical distribution medium), accompanied by the
|
||||
Corresponding Source fixed on a durable physical medium
|
||||
customarily used for software interchange.
|
||||
- b) Convey the object code in, or embodied in, a physical product
|
||||
(including a physical distribution medium), accompanied by a
|
||||
written offer, valid for at least three years and valid for as
|
||||
long as you offer spare parts or customer support for that product
|
||||
model, to give anyone who possesses the object code either (1) a
|
||||
copy of the Corresponding Source for all the software in the
|
||||
product that is covered by this License, on a durable physical
|
||||
medium customarily used for software interchange, for a price no
|
||||
more than your reasonable cost of physically performing this
|
||||
conveying of source, or (2) access to copy the Corresponding
|
||||
Source from a network server at no charge.
|
||||
- c) Convey individual copies of the object code with a copy of the
|
||||
written offer to provide the Corresponding Source. This
|
||||
alternative is allowed only occasionally and noncommercially, and
|
||||
only if you received the object code with such an offer, in accord
|
||||
with subsection 6b.
|
||||
- d) Convey the object code by offering access from a designated
|
||||
place (gratis or for a charge), and offer equivalent access to the
|
||||
Corresponding Source in the same way through the same place at no
|
||||
further charge. You need not require recipients to copy the
|
||||
Corresponding Source along with the object code. If the place to
|
||||
copy the object code is a network server, the Corresponding Source
|
||||
may be on a different server (operated by you or a third party)
|
||||
that supports equivalent copying facilities, provided you maintain
|
||||
clear directions next to the object code saying where to find the
|
||||
Corresponding Source. Regardless of what server hosts the
|
||||
Corresponding Source, you remain obligated to ensure that it is
|
||||
available for as long as needed to satisfy these requirements.
|
||||
- e) Convey the object code using peer-to-peer transmission,
|
||||
provided you inform other peers where the object code and
|
||||
Corresponding Source of the work are being offered to the general
|
||||
public at no charge under subsection 6d.
|
||||
|
||||
A separable portion of the object code, whose source code is excluded
|
||||
from the Corresponding Source as a System Library, need not be
|
||||
included in conveying the object code work.
|
||||
|
||||
A "User Product" is either (1) a "consumer product", which means any
|
||||
tangible personal property which is normally used for personal,
|
||||
family, or household purposes, or (2) anything designed or sold for
|
||||
incorporation into a dwelling. In determining whether a product is a
|
||||
consumer product, doubtful cases shall be resolved in favor of
|
||||
coverage. For a particular product received by a particular user,
|
||||
"normally used" refers to a typical or common use of that class of
|
||||
product, regardless of the status of the particular user or of the way
|
||||
in which the particular user actually uses, or expects or is expected
|
||||
to use, the product. A product is a consumer product regardless of
|
||||
whether the product has substantial commercial, industrial or
|
||||
non-consumer uses, unless such uses represent the only significant
|
||||
mode of use of the product.
|
||||
|
||||
"Installation Information" for a User Product means any methods,
|
||||
procedures, authorization keys, or other information required to
|
||||
install and execute modified versions of a covered work in that User
|
||||
Product from a modified version of its Corresponding Source. The
|
||||
information must suffice to ensure that the continued functioning of
|
||||
the modified object code is in no case prevented or interfered with
|
||||
solely because modification has been made.
|
||||
|
||||
If you convey an object code work under this section in, or with, or
|
||||
specifically for use in, a User Product, and the conveying occurs as
|
||||
part of a transaction in which the right of possession and use of the
|
||||
User Product is transferred to the recipient in perpetuity or for a
|
||||
fixed term (regardless of how the transaction is characterized), the
|
||||
Corresponding Source conveyed under this section must be accompanied
|
||||
by the Installation Information. But this requirement does not apply
|
||||
if neither you nor any third party retains the ability to install
|
||||
modified object code on the User Product (for example, the work has
|
||||
been installed in ROM).
|
||||
|
||||
The requirement to provide Installation Information does not include a
|
||||
requirement to continue to provide support service, warranty, or
|
||||
updates for a work that has been modified or installed by the
|
||||
recipient, or for the User Product in which it has been modified or
|
||||
installed. Access to a network may be denied when the modification
|
||||
itself materially and adversely affects the operation of the network
|
||||
or violates the rules and protocols for communication across the
|
||||
network.
|
||||
|
||||
Corresponding Source conveyed, and Installation Information provided,
|
||||
in accord with this section must be in a format that is publicly
|
||||
documented (and with an implementation available to the public in
|
||||
source code form), and must require no special password or key for
|
||||
unpacking, reading or copying.
|
||||
|
||||
### 7. Additional Terms.
|
||||
|
||||
"Additional permissions" are terms that supplement the terms of this
|
||||
License by making exceptions from one or more of its conditions.
|
||||
Additional permissions that are applicable to the entire Program shall
|
||||
be treated as though they were included in this License, to the extent
|
||||
that they are valid under applicable law. If additional permissions
|
||||
apply only to part of the Program, that part may be used separately
|
||||
under those permissions, but the entire Program remains governed by
|
||||
this License without regard to the additional permissions.
|
||||
|
||||
When you convey a copy of a covered work, you may at your option
|
||||
remove any additional permissions from that copy, or from any part of
|
||||
it. (Additional permissions may be written to require their own
|
||||
removal in certain cases when you modify the work.) You may place
|
||||
additional permissions on material, added by you to a covered work,
|
||||
for which you have or can give appropriate copyright permission.
|
||||
|
||||
Notwithstanding any other provision of this License, for material you
|
||||
add to a covered work, you may (if authorized by the copyright holders
|
||||
of that material) supplement the terms of this License with terms:
|
||||
|
||||
- a) Disclaiming warranty or limiting liability differently from the
|
||||
terms of sections 15 and 16 of this License; or
|
||||
- b) Requiring preservation of specified reasonable legal notices or
|
||||
author attributions in that material or in the Appropriate Legal
|
||||
Notices displayed by works containing it; or
|
||||
- c) Prohibiting misrepresentation of the origin of that material,
|
||||
or requiring that modified versions of such material be marked in
|
||||
reasonable ways as different from the original version; or
|
||||
- d) Limiting the use for publicity purposes of names of licensors
|
||||
or authors of the material; or
|
||||
- e) Declining to grant rights under trademark law for use of some
|
||||
trade names, trademarks, or service marks; or
|
||||
- f) Requiring indemnification of licensors and authors of that
|
||||
material by anyone who conveys the material (or modified versions
|
||||
of it) with contractual assumptions of liability to the recipient,
|
||||
for any liability that these contractual assumptions directly
|
||||
impose on those licensors and authors.
|
||||
|
||||
All other non-permissive additional terms are considered "further
|
||||
restrictions" within the meaning of section 10. If the Program as you
|
||||
received it, or any part of it, contains a notice stating that it is
|
||||
governed by this License along with a term that is a further
|
||||
restriction, you may remove that term. If a license document contains
|
||||
a further restriction but permits relicensing or conveying under this
|
||||
License, you may add to a covered work material governed by the terms
|
||||
of that license document, provided that the further restriction does
|
||||
not survive such relicensing or conveying.
|
||||
|
||||
If you add terms to a covered work in accord with this section, you
|
||||
must place, in the relevant source files, a statement of the
|
||||
additional terms that apply to those files, or a notice indicating
|
||||
where to find the applicable terms.
|
||||
|
||||
Additional terms, permissive or non-permissive, may be stated in the
|
||||
form of a separately written license, or stated as exceptions; the
|
||||
above requirements apply either way.
|
||||
|
||||
### 8. Termination.
|
||||
|
||||
You may not propagate or modify a covered work except as expressly
|
||||
provided under this License. Any attempt otherwise to propagate or
|
||||
modify it is void, and will automatically terminate your rights under
|
||||
this License (including any patent licenses granted under the third
|
||||
paragraph of section 11).
|
||||
|
||||
However, if you cease all violation of this License, then your license
|
||||
from a particular copyright holder is reinstated (a) provisionally,
|
||||
unless and until the copyright holder explicitly and finally
|
||||
terminates your license, and (b) permanently, if the copyright holder
|
||||
fails to notify you of the violation by some reasonable means prior to
|
||||
60 days after the cessation.
|
||||
|
||||
Moreover, your license from a particular copyright holder is
|
||||
reinstated permanently if the copyright holder notifies you of the
|
||||
violation by some reasonable means, this is the first time you have
|
||||
received notice of violation of this License (for any work) from that
|
||||
copyright holder, and you cure the violation prior to 30 days after
|
||||
your receipt of the notice.
|
||||
|
||||
Termination of your rights under this section does not terminate the
|
||||
licenses of parties who have received copies or rights from you under
|
||||
this License. If your rights have been terminated and not permanently
|
||||
reinstated, you do not qualify to receive new licenses for the same
|
||||
material under section 10.
|
||||
|
||||
### 9. Acceptance Not Required for Having Copies.
|
||||
|
||||
You are not required to accept this License in order to receive or run
|
||||
a copy of the Program. Ancillary propagation of a covered work
|
||||
occurring solely as a consequence of using peer-to-peer transmission
|
||||
to receive a copy likewise does not require acceptance. However,
|
||||
nothing other than this License grants you permission to propagate or
|
||||
modify any covered work. These actions infringe copyright if you do
|
||||
not accept this License. Therefore, by modifying or propagating a
|
||||
covered work, you indicate your acceptance of this License to do so.
|
||||
|
||||
### 10. Automatic Licensing of Downstream Recipients.
|
||||
|
||||
Each time you convey a covered work, the recipient automatically
|
||||
receives a license from the original licensors, to run, modify and
|
||||
propagate that work, subject to this License. You are not responsible
|
||||
for enforcing compliance by third parties with this License.
|
||||
|
||||
An "entity transaction" is a transaction transferring control of an
|
||||
organization, or substantially all assets of one, or subdividing an
|
||||
organization, or merging organizations. If propagation of a covered
|
||||
work results from an entity transaction, each party to that
|
||||
transaction who receives a copy of the work also receives whatever
|
||||
licenses to the work the party's predecessor in interest had or could
|
||||
give under the previous paragraph, plus a right to possession of the
|
||||
Corresponding Source of the work from the predecessor in interest, if
|
||||
the predecessor has it or can get it with reasonable efforts.
|
||||
|
||||
You may not impose any further restrictions on the exercise of the
|
||||
rights granted or affirmed under this License. For example, you may
|
||||
not impose a license fee, royalty, or other charge for exercise of
|
||||
rights granted under this License, and you may not initiate litigation
|
||||
(including a cross-claim or counterclaim in a lawsuit) alleging that
|
||||
any patent claim is infringed by making, using, selling, offering for
|
||||
sale, or importing the Program or any portion of it.
|
||||
|
||||
### 11. Patents.
|
||||
|
||||
A "contributor" is a copyright holder who authorizes use under this
|
||||
License of the Program or a work on which the Program is based. The
|
||||
work thus licensed is called the contributor's "contributor version".
|
||||
|
||||
A contributor's "essential patent claims" are all patent claims owned
|
||||
or controlled by the contributor, whether already acquired or
|
||||
hereafter acquired, that would be infringed by some manner, permitted
|
||||
by this License, of making, using, or selling its contributor version,
|
||||
but do not include claims that would be infringed only as a
|
||||
consequence of further modification of the contributor version. For
|
||||
purposes of this definition, "control" includes the right to grant
|
||||
patent sublicenses in a manner consistent with the requirements of
|
||||
this License.
|
||||
|
||||
Each contributor grants you a non-exclusive, worldwide, royalty-free
|
||||
patent license under the contributor's essential patent claims, to
|
||||
make, use, sell, offer for sale, import and otherwise run, modify and
|
||||
propagate the contents of its contributor version.
|
||||
|
||||
In the following three paragraphs, a "patent license" is any express
|
||||
agreement or commitment, however denominated, not to enforce a patent
|
||||
(such as an express permission to practice a patent or covenant not to
|
||||
sue for patent infringement). To "grant" such a patent license to a
|
||||
party means to make such an agreement or commitment not to enforce a
|
||||
patent against the party.
|
||||
|
||||
If you convey a covered work, knowingly relying on a patent license,
|
||||
and the Corresponding Source of the work is not available for anyone
|
||||
to copy, free of charge and under the terms of this License, through a
|
||||
publicly available network server or other readily accessible means,
|
||||
then you must either (1) cause the Corresponding Source to be so
|
||||
available, or (2) arrange to deprive yourself of the benefit of the
|
||||
patent license for this particular work, or (3) arrange, in a manner
|
||||
consistent with the requirements of this License, to extend the patent
|
||||
license to downstream recipients. "Knowingly relying" means you have
|
||||
actual knowledge that, but for the patent license, your conveying the
|
||||
covered work in a country, or your recipient's use of the covered work
|
||||
in a country, would infringe one or more identifiable patents in that
|
||||
country that you have reason to believe are valid.
|
||||
|
||||
If, pursuant to or in connection with a single transaction or
|
||||
arrangement, you convey, or propagate by procuring conveyance of, a
|
||||
covered work, and grant a patent license to some of the parties
|
||||
receiving the covered work authorizing them to use, propagate, modify
|
||||
or convey a specific copy of the covered work, then the patent license
|
||||
you grant is automatically extended to all recipients of the covered
|
||||
work and works based on it.
|
||||
|
||||
A patent license is "discriminatory" if it does not include within the
|
||||
scope of its coverage, prohibits the exercise of, or is conditioned on
|
||||
the non-exercise of one or more of the rights that are specifically
|
||||
granted under this License. You may not convey a covered work if you
|
||||
are a party to an arrangement with a third party that is in the
|
||||
business of distributing software, under which you make payment to the
|
||||
third party based on the extent of your activity of conveying the
|
||||
work, and under which the third party grants, to any of the parties
|
||||
who would receive the covered work from you, a discriminatory patent
|
||||
license (a) in connection with copies of the covered work conveyed by
|
||||
you (or copies made from those copies), or (b) primarily for and in
|
||||
connection with specific products or compilations that contain the
|
||||
covered work, unless you entered into that arrangement, or that patent
|
||||
license was granted, prior to 28 March 2007.
|
||||
|
||||
Nothing in this License shall be construed as excluding or limiting
|
||||
any implied license or other defenses to infringement that may
|
||||
otherwise be available to you under applicable patent law.
|
||||
|
||||
### 12. No Surrender of Others' Freedom.
|
||||
|
||||
If conditions are imposed on you (whether by court order, agreement or
|
||||
otherwise) that contradict the conditions of this License, they do not
|
||||
excuse you from the conditions of this License. If you cannot convey a
|
||||
covered work so as to satisfy simultaneously your obligations under
|
||||
this License and any other pertinent obligations, then as a
|
||||
consequence you may not convey it at all. For example, if you agree to
|
||||
terms that obligate you to collect a royalty for further conveying
|
||||
from those to whom you convey the Program, the only way you could
|
||||
satisfy both those terms and this License would be to refrain entirely
|
||||
from conveying the Program.
|
||||
|
||||
### 13. Remote Network Interaction; Use with the GNU General Public License.
|
||||
|
||||
Notwithstanding any other provision of this License, if you modify the
|
||||
Program, your modified version must prominently offer all users
|
||||
interacting with it remotely through a computer network (if your
|
||||
version supports such interaction) an opportunity to receive the
|
||||
Corresponding Source of your version by providing access to the
|
||||
Corresponding Source from a network server at no charge, through some
|
||||
standard or customary means of facilitating copying of software. This
|
||||
Corresponding Source shall include the Corresponding Source for any
|
||||
work covered by version 3 of the GNU General Public License that is
|
||||
incorporated pursuant to the following paragraph.
|
||||
|
||||
Notwithstanding any other provision of this License, you have
|
||||
permission to link or combine any covered work with a work licensed
|
||||
under version 3 of the GNU General Public License into a single
|
||||
combined work, and to convey the resulting work. The terms of this
|
||||
License will continue to apply to the part which is the covered work,
|
||||
but the work with which it is combined will remain governed by version
|
||||
3 of the GNU General Public License.
|
||||
|
||||
### 14. Revised Versions of this License.
|
||||
|
||||
The Free Software Foundation may publish revised and/or new versions
|
||||
of the GNU Affero General Public License from time to time. Such new
|
||||
versions will be similar in spirit to the present version, but may
|
||||
differ in detail to address new problems or concerns.
|
||||
|
||||
Each version is given a distinguishing version number. If the Program
|
||||
specifies that a certain numbered version of the GNU Affero General
|
||||
Public License "or any later version" applies to it, you have the
|
||||
option of following the terms and conditions either of that numbered
|
||||
version or of any later version published by the Free Software
|
||||
Foundation. If the Program does not specify a version number of the
|
||||
GNU Affero General Public License, you may choose any version ever
|
||||
published by the Free Software Foundation.
|
||||
|
||||
If the Program specifies that a proxy can decide which future versions
|
||||
of the GNU Affero General Public License can be used, that proxy's
|
||||
public statement of acceptance of a version permanently authorizes you
|
||||
to choose that version for the Program.
|
||||
|
||||
Later license versions may give you additional or different
|
||||
permissions. However, no additional obligations are imposed on any
|
||||
author or copyright holder as a result of your choosing to follow a
|
||||
later version.
|
||||
|
||||
### 15. Disclaimer of Warranty.
|
||||
|
||||
THERE IS NO WARRANTY FOR THE PROGRAM, TO THE EXTENT PERMITTED BY
|
||||
APPLICABLE LAW. EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT
|
||||
HOLDERS AND/OR OTHER PARTIES PROVIDE THE PROGRAM "AS IS" WITHOUT
|
||||
WARRANTY OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT
|
||||
LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
|
||||
A PARTICULAR PURPOSE. THE ENTIRE RISK AS TO THE QUALITY AND
|
||||
PERFORMANCE OF THE PROGRAM IS WITH YOU. SHOULD THE PROGRAM PROVE
|
||||
DEFECTIVE, YOU ASSUME THE COST OF ALL NECESSARY SERVICING, REPAIR OR
|
||||
CORRECTION.
|
||||
|
||||
### 16. Limitation of Liability.
|
||||
|
||||
IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING
|
||||
WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MODIFIES AND/OR
|
||||
CONVEYS THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES,
|
||||
INCLUDING ANY GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES
|
||||
ARISING OUT OF THE USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT
|
||||
NOT LIMITED TO LOSS OF DATA OR DATA BEING RENDERED INACCURATE OR
|
||||
LOSSES SUSTAINED BY YOU OR THIRD PARTIES OR A FAILURE OF THE PROGRAM
|
||||
TO OPERATE WITH ANY OTHER PROGRAMS), EVEN IF SUCH HOLDER OR OTHER
|
||||
PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF SUCH DAMAGES.
|
||||
|
||||
### 17. Interpretation of Sections 15 and 16.
|
||||
|
||||
If the disclaimer of warranty and limitation of liability provided
|
||||
above cannot be given local legal effect according to their terms,
|
||||
reviewing courts shall apply local law that most closely approximates
|
||||
an absolute waiver of all civil liability in connection with the
|
||||
Program, unless a warranty or assumption of liability accompanies a
|
||||
copy of the Program in return for a fee.
|
||||
|
||||
END OF TERMS AND CONDITIONS
|
||||
|
||||
## How to Apply These Terms to Your New Programs
|
||||
|
||||
If you develop a new program, and you want it to be of the greatest
|
||||
possible use to the public, the best way to achieve this is to make it
|
||||
free software which everyone can redistribute and change under these
|
||||
terms.
|
||||
|
||||
To do so, attach the following notices to the program. It is safest to
|
||||
attach them to the start of each source file to most effectively state
|
||||
the exclusion of warranty; and each file should have at least the
|
||||
"copyright" line and a pointer to where the full notice is found.
|
||||
|
||||
<one line to give the program's name and a brief idea of what it does.>
|
||||
Copyright (C) <year> <name of author>
|
||||
|
||||
This program is free software: you can redistribute it and/or modify
|
||||
it under the terms of the GNU Affero General Public License as
|
||||
published by the Free Software Foundation, either version 3 of the
|
||||
License, or (at your option) any later version.
|
||||
|
||||
This program is distributed in the hope that it will be useful,
|
||||
but WITHOUT ANY WARRANTY; without even the implied warranty of
|
||||
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
|
||||
GNU Affero General Public License for more details.
|
||||
|
||||
You should have received a copy of the GNU Affero General Public License
|
||||
along with this program. If not, see <https://www.gnu.org/licenses/>.
|
||||
|
||||
Also add information on how to contact you by electronic and paper
|
||||
mail.
|
||||
|
||||
If your software can interact with users remotely through a computer
|
||||
network, you should also make sure that it provides a way for users to
|
||||
get its source. For example, if your program is a web application, its
|
||||
interface could display a "Source" link that leads users to an archive
|
||||
of the code. There are many ways you could offer source, and different
|
||||
solutions will be better for different programs; see section 13 for
|
||||
the specific requirements.
|
||||
|
||||
You should also get your employer (if you work as a programmer) or
|
||||
school, if any, to sign a "copyright disclaimer" for the program, if
|
||||
necessary. For more information on this, and how to apply and follow
|
||||
the GNU AGPL, see <https://www.gnu.org/licenses/>.
|
||||
@@ -10,5 +10,3 @@ This new version of PARCOURSMOB brings :
|
||||
- A configurable and themeable approach of rendering web pages : the default theme is located in the folder [themes/default/](themes/default/)
|
||||
- A modular architecture based on groups and access rights, using [COOPGO Groups Management](https://git.coopgo.io/coopgo-groups-management)
|
||||
- A distributed cache system through [etcd](https://etcd.io/) to handle distributed state management like pagination in a cloud native way
|
||||
|
||||
|
||||
|
||||
259
config.go
259
config.go
@@ -14,7 +14,15 @@ func ReadConfig() (*viper.Viper, error) {
|
||||
"public_dir": "template/default/public",
|
||||
},
|
||||
"server": map[string]any{
|
||||
"listen": "0.0.0.0:9000",
|
||||
"listen": "0.0.0.0:9000", // DEPRECATED
|
||||
"web": map[string]any{
|
||||
"enabled": true,
|
||||
"listen": "0.0.0.0:8080",
|
||||
},
|
||||
"mcp": map[string]any{
|
||||
"enabled": true,
|
||||
"listen": "0.0.0.0:8081",
|
||||
},
|
||||
},
|
||||
"identification": map[string]any{
|
||||
"sessions": map[string]any{
|
||||
@@ -22,9 +30,258 @@ func ReadConfig() (*viper.Viper, error) {
|
||||
"session_key": "SESSION_KEY",
|
||||
},
|
||||
},
|
||||
"storage": map[string]any{
|
||||
"files": map[string]any{
|
||||
"file_types": map[string]string{
|
||||
"driving_licence": "Permis de conduire",
|
||||
"work_contract": "Contrat de travail",
|
||||
"identity_proof": "Pièce d'identité",
|
||||
"membership_form": "Bulletin d'adhésion",
|
||||
"other": "Autre",
|
||||
},
|
||||
},
|
||||
},
|
||||
"modules": map[string]any{
|
||||
"dashboard": map[string]any{
|
||||
"enabled": true,
|
||||
},
|
||||
"members": map[string]any{
|
||||
"enabled": true,
|
||||
"profile_optional_fields": []map[string]any{},
|
||||
},
|
||||
"beneficiaries": map[string]any{
|
||||
"enabled": true,
|
||||
"validated_profile": map[string]any{
|
||||
"enabled": false,
|
||||
"required": map[string]any{
|
||||
"fields": []string{},
|
||||
"documents": []string{},
|
||||
},
|
||||
},
|
||||
"profile_optional_fields": []map[string]any{
|
||||
{
|
||||
"name": "gender",
|
||||
"label": "Genre",
|
||||
"type": "select",
|
||||
"options": []map[string]string{
|
||||
{"value": "0", "label": "Inconnu"},
|
||||
{"value": "1", "label": "Masculin"},
|
||||
{"value": "2", "label": "Féminin"},
|
||||
{"value": "9", "label": "Sans objet"},
|
||||
},
|
||||
},
|
||||
{
|
||||
"name": "social_situation",
|
||||
"label": "Situation sociale",
|
||||
"type": "select",
|
||||
"options": []map[string]string{
|
||||
{"value": "", "label": "Inconnu"},
|
||||
{"value": "BRSA", "label": "BRSA"},
|
||||
{"value": "Demandeur d'emploi", "label": "Demandeur d'emploi"},
|
||||
{"value": "Chantier d'insertion", "label": "Chantier d'insertion"},
|
||||
{"value": "Jeune -25", "label": "Jeune -25"},
|
||||
},
|
||||
},
|
||||
{
|
||||
"name": "registration_reason",
|
||||
"label": "Motif d'inscription",
|
||||
"type": "select",
|
||||
"options": []map[string]string{
|
||||
{"value": "", "label": "Inconnu"},
|
||||
{"value": "Pas de permis", "label": "Pas de permis"},
|
||||
{"value": "Pas de véhicule", "label": "Pas de véhicule"},
|
||||
{"value": "Perte d'autonomie", "label": "Perte d'autonomie"},
|
||||
{"value": "Autre", "label": "Autre"},
|
||||
},
|
||||
},
|
||||
{
|
||||
"name": "status",
|
||||
"label": "Statut (prioritaire / non prioritaire)",
|
||||
"type": "select",
|
||||
"options": []map[string]string{
|
||||
{"value": "Non prioritaire", "label": "Non prioritaire"},
|
||||
{"value": "Prioritaire", "label": "Prioritaire"},
|
||||
},
|
||||
},
|
||||
{
|
||||
"name": "last_subscription_date",
|
||||
"label": "Date de dernière adhésion",
|
||||
"type": "date",
|
||||
},
|
||||
{
|
||||
"name": "previous_solidarity_transports_count",
|
||||
"label": "Nombre de transports solidaires précédents",
|
||||
"type": "number",
|
||||
},
|
||||
{
|
||||
"name": "comment",
|
||||
"label": "Commentaire",
|
||||
"type": "textarea",
|
||||
},
|
||||
},
|
||||
},
|
||||
"journeys": map[string]any{
|
||||
"enabled": true,
|
||||
"search_view": "tabs",
|
||||
"solutions": map[string]any{
|
||||
"solidarity_transport": map[string]any{
|
||||
"enabled": true,
|
||||
},
|
||||
"organized_carpool": map[string]any{
|
||||
"enabled": true,
|
||||
},
|
||||
"carpool_operators": map[string]any{
|
||||
"enabled": true,
|
||||
},
|
||||
"transit": map[string]any{
|
||||
"enabled": true,
|
||||
},
|
||||
"fleet_vehicles": map[string]any{
|
||||
"enabled": true,
|
||||
},
|
||||
"knowledge_base": map[string]any{
|
||||
"enabled": true,
|
||||
},
|
||||
},
|
||||
},
|
||||
"solidarity_transport": map[string]any{
|
||||
"enabled": true,
|
||||
"pagination": map[string]any{
|
||||
"trips_items_per_page": 10,
|
||||
"drivers_items_per_page": 10,
|
||||
},
|
||||
"drivers": map[string]any{
|
||||
"documents_types": []string{"membership_form", "driving_licence", "identity_proof", "other"},
|
||||
"validated_profile": map[string]any{
|
||||
"enabled": false,
|
||||
"required": map[string]any{
|
||||
"fields": []string{},
|
||||
"documents": []string{},
|
||||
},
|
||||
},
|
||||
"profile_optional_fields": []map[string]any{
|
||||
{
|
||||
"name": "gender",
|
||||
"label": "Genre",
|
||||
"type": "select",
|
||||
"options": []map[string]string{
|
||||
{"value": "0", "label": "Inconnu"},
|
||||
{"value": "1", "label": "Masculin"},
|
||||
{"value": "2", "label": "Féminin"},
|
||||
{"value": "9", "label": "Sans objet"},
|
||||
},
|
||||
},
|
||||
{
|
||||
"name": "last_subscription_date",
|
||||
"label": "Date de dernière adhésion",
|
||||
"type": "date",
|
||||
},
|
||||
{
|
||||
"name": "comment",
|
||||
"label": "Commentaire",
|
||||
"type": "textarea",
|
||||
},
|
||||
},
|
||||
},
|
||||
"booking_motivations": []map[string]string{
|
||||
{"value": "Administratif", "label": "Administratif (trajet garanti)"},
|
||||
{"value": "Commerce", "label": "Commerce"},
|
||||
{"value": "Courses", "label": "Courses"},
|
||||
{"value": "Insertion", "label": "Insertion (trajet garanti)"},
|
||||
{"value": "Loisirs", "label": "Loisirs"},
|
||||
{"value": "Visite Ă un proche", "label": "Visite Ă un proche"},
|
||||
{"value": "Santé", "label": "Santé (trajet garanti)"},
|
||||
{"value": "", "label": "Autre "},
|
||||
},
|
||||
"guaranteed_trip_motivations": []string{"Santé", "Insertion", "Administratif"},
|
||||
},
|
||||
"organized_carpool": map[string]any{
|
||||
"enabled": true,
|
||||
"pagination": map[string]any{
|
||||
"trips_items_per_page": 10,
|
||||
"drivers_items_per_page": 10,
|
||||
},
|
||||
"drivers": map[string]any{
|
||||
"documents_types": []string{"membership_form", "driving_licence", "identity_proof", "other"},
|
||||
"validated_profile": map[string]any{
|
||||
"enabled": true,
|
||||
"required": map[string]any{
|
||||
"fields": []string{},
|
||||
"documents": []string{"driving_licence"},
|
||||
},
|
||||
},
|
||||
},
|
||||
"booking_motivations": []map[string]string{
|
||||
{"value": "Administratif", "label": "Administratif"},
|
||||
{"value": "Commerce", "label": "Commerce"},
|
||||
{"value": "Courses", "label": "Courses"},
|
||||
{"value": "Insertion", "label": "Insertion"},
|
||||
{"value": "Loisirs", "label": "Loisirs"},
|
||||
{"value": "Travail", "label": "Travail"},
|
||||
{"value": "Formation", "label": "Formation"},
|
||||
{"value": "Visite Ă un proche", "label": "Visite Ă un proche"},
|
||||
{"value": "Santé", "label": "Santé"},
|
||||
{"value": "", "label": "Autre "},
|
||||
},
|
||||
},
|
||||
"vehicles": map[string]any{
|
||||
"enabled": true,
|
||||
},
|
||||
"vehicles_management": map[string]any{
|
||||
"enabled": true,
|
||||
},
|
||||
"fleets": map[string]any{
|
||||
"vehicle_types": []string{"Voiture", "Voiture sans permis", "Scooter", "Trotinette", "Vélo électrique"},
|
||||
"vehicle_optional_fields": []map[string]any{},
|
||||
},
|
||||
"agenda": map[string]any{
|
||||
"enabled": true,
|
||||
},
|
||||
"directory": map[string]any{
|
||||
"enabled": true,
|
||||
},
|
||||
"support": map[string]any{
|
||||
"enabled": true,
|
||||
"email": "support@mobicoop.fr",
|
||||
},
|
||||
},
|
||||
"geo": map[string]any{
|
||||
"type": "addok", // Options: "pelias", "addok"
|
||||
"pelias": map[string]any{
|
||||
"url": "https://geocode.ridygo.fr",
|
||||
"autocomplete": "/autocomplete?text=",
|
||||
},
|
||||
"addok": map[string]any{
|
||||
"url": "https://api-adresse.data.gouv.fr",
|
||||
"autocomplete": "/search/?q=",
|
||||
},
|
||||
},
|
||||
"geography": map[string]any{
|
||||
"storage": map[string]any{
|
||||
"index": map[string]any{
|
||||
"type": "memory_rtree",
|
||||
"bleve": map[string]any{
|
||||
"file": "index.bleve",
|
||||
},
|
||||
},
|
||||
},
|
||||
"services": map[string]any{
|
||||
"grpc": map[string]any{
|
||||
"enable": true,
|
||||
"port": 8080,
|
||||
},
|
||||
},
|
||||
"data": map[string]any{
|
||||
"layers": map[string]string{
|
||||
"regions": "https://etalab-datasets.geo.data.gouv.fr/contours-administratifs/latest/geojson/regions-50m.geojson",
|
||||
"departements": "https://etalab-datasets.geo.data.gouv.fr/contours-administratifs/latest/geojson/departements-50m.geojson",
|
||||
"epci": "https://etalab-datasets.geo.data.gouv.fr/contours-administratifs/latest/geojson/epci-50m.geojson",
|
||||
"communes": "https://etalab-datasets.geo.data.gouv.fr/contours-administratifs/latest/geojson/communes-50m.geojson",
|
||||
},
|
||||
},
|
||||
"filters": map[string]any{
|
||||
"enabled": false,
|
||||
"geographies": []map[string]string{},
|
||||
},
|
||||
},
|
||||
}
|
||||
|
||||
658
core/application/administration.go
Executable file
658
core/application/administration.go
Executable file
@@ -0,0 +1,658 @@
|
||||
package application
|
||||
|
||||
import (
|
||||
"context"
|
||||
"crypto/rand"
|
||||
"encoding/base64"
|
||||
"fmt"
|
||||
"io"
|
||||
"net/http"
|
||||
"sort"
|
||||
"sync"
|
||||
"time"
|
||||
|
||||
"git.coopgo.io/coopgo-apps/parcoursmob/core/utils/identification"
|
||||
"git.coopgo.io/coopgo-apps/parcoursmob/core/utils/sorting"
|
||||
agenda "git.coopgo.io/coopgo-platform/agenda/grpcapi"
|
||||
agendastorage "git.coopgo.io/coopgo-platform/agenda/storage"
|
||||
fleets "git.coopgo.io/coopgo-platform/fleets/grpcapi"
|
||||
fleetsstorage "git.coopgo.io/coopgo-platform/fleets/storage"
|
||||
groupsmanagement "git.coopgo.io/coopgo-platform/groups-management/grpcapi"
|
||||
"git.coopgo.io/coopgo-platform/groups-management/storage"
|
||||
groupstorage "git.coopgo.io/coopgo-platform/groups-management/storage"
|
||||
accounts "git.coopgo.io/coopgo-platform/mobility-accounts/grpcapi"
|
||||
mobilityaccounts "git.coopgo.io/coopgo-platform/mobility-accounts/grpcapi"
|
||||
mobilityaccountsstorage "git.coopgo.io/coopgo-platform/mobility-accounts/storage"
|
||||
"github.com/google/uuid"
|
||||
"github.com/rs/zerolog/log"
|
||||
"google.golang.org/protobuf/types/known/structpb"
|
||||
)
|
||||
|
||||
type AdministrationDataResult struct {
|
||||
Accounts []mobilityaccountsstorage.Account
|
||||
Beneficiaries []mobilityaccountsstorage.Account
|
||||
Groups []groupstorage.Group
|
||||
Bookings []fleetsstorage.Booking
|
||||
Events []agendastorage.Event
|
||||
}
|
||||
|
||||
type AdminVehiclesStatsResult struct {
|
||||
Vehicles []fleetsstorage.Vehicle
|
||||
Bookings []fleetsstorage.Booking
|
||||
Groups map[string]any
|
||||
}
|
||||
|
||||
type AdminBookingsStatsResult struct {
|
||||
Vehicles map[string]fleetsstorage.Vehicle
|
||||
Bookings []fleetsstorage.Booking
|
||||
Groups map[string]any
|
||||
BeneficiariesMap map[string]any
|
||||
}
|
||||
|
||||
type AdminBeneficiariesStatsResult struct {
|
||||
Beneficiaries []mobilityaccountsstorage.Account
|
||||
CacheID string
|
||||
}
|
||||
|
||||
type AdminEventsStatsResult struct {
|
||||
Events []agendastorage.Event
|
||||
Groups map[string]any
|
||||
}
|
||||
|
||||
// GetAdministrationData retrieves all data needed for the administration dashboard
|
||||
func (h *ApplicationHandler) GetAdministrationData(ctx context.Context) (*AdministrationDataResult, error) {
|
||||
var (
|
||||
wg sync.WaitGroup
|
||||
accounts, beneficiaries []mobilityaccountsstorage.Account
|
||||
bookings []fleetsstorage.Booking
|
||||
accountsErr, beneficiariesErr, bookingsErr, groupsResponseErr, eventsResponseErr, groupsBatchErr error
|
||||
groups = []groupstorage.Group{}
|
||||
responses = []agendastorage.Event{}
|
||||
groupsResponse *groupsmanagement.GetGroupsResponse
|
||||
eventsResponse *agenda.GetEventsResponse
|
||||
groupids = []string{}
|
||||
)
|
||||
|
||||
// Retrieve accounts in a goroutine
|
||||
wg.Add(1)
|
||||
go func() {
|
||||
defer wg.Done()
|
||||
accounts, accountsErr = h.services.GetAccounts()
|
||||
}()
|
||||
|
||||
// Retrieve beneficiaries in a goroutine
|
||||
wg.Add(1)
|
||||
go func() {
|
||||
defer wg.Done()
|
||||
beneficiaries, beneficiariesErr = h.services.GetBeneficiaries()
|
||||
}()
|
||||
|
||||
// Retrieve bookings in a goroutine
|
||||
wg.Add(1)
|
||||
go func() {
|
||||
defer wg.Done()
|
||||
bookings, bookingsErr = h.services.GetBookings()
|
||||
}()
|
||||
|
||||
// Retrieve groups in a goroutine
|
||||
wg.Add(1)
|
||||
go func() {
|
||||
defer wg.Done()
|
||||
request := &groupsmanagement.GetGroupsRequest{
|
||||
Namespaces: []string{"parcoursmob_organizations"},
|
||||
}
|
||||
groupsResponse, groupsResponseErr = h.services.GRPC.GroupsManagement.GetGroups(ctx, request)
|
||||
if groupsResponseErr == nil {
|
||||
for _, group := range groupsResponse.Groups {
|
||||
g := group.ToStorageType()
|
||||
groups = append(groups, g)
|
||||
}
|
||||
sort.Sort(sorting.GroupsByName(groups))
|
||||
}
|
||||
}()
|
||||
|
||||
// Retrieve Events in a goroutine
|
||||
wg.Add(1)
|
||||
go func() {
|
||||
defer wg.Done()
|
||||
eventsResponse, eventsResponseErr = h.services.GRPC.Agenda.GetEvents(ctx, &agenda.GetEventsRequest{
|
||||
Namespaces: []string{"parcoursmob_dispositifs"},
|
||||
})
|
||||
if eventsResponseErr == nil {
|
||||
for _, e := range eventsResponse.Events {
|
||||
groupids = append(groupids, e.Owners...)
|
||||
responses = append(responses, e.ToStorageType())
|
||||
}
|
||||
sort.Sort(sorting.EventsByStartdate(responses))
|
||||
}
|
||||
}()
|
||||
|
||||
wg.Wait()
|
||||
|
||||
// Check for errors
|
||||
if accountsErr != nil || beneficiariesErr != nil || bookingsErr != nil || groupsResponseErr != nil || eventsResponseErr != nil {
|
||||
log.Error().
|
||||
Any("accounts error", accountsErr).
|
||||
Any("beneficiaries error", beneficiariesErr).
|
||||
Any("bookings error", bookingsErr).
|
||||
Any("groups response error", groupsResponseErr).
|
||||
Any("events response error", eventsResponseErr).
|
||||
Any("groups batch error", groupsBatchErr).
|
||||
Msg("Error in retrieving administration data")
|
||||
return nil, fmt.Errorf("error retrieving administration data")
|
||||
}
|
||||
|
||||
return &AdministrationDataResult{
|
||||
Accounts: accounts,
|
||||
Beneficiaries: beneficiaries,
|
||||
Groups: groups,
|
||||
Bookings: bookings,
|
||||
Events: responses,
|
||||
}, nil
|
||||
}
|
||||
|
||||
// CreateAdministrationGroup creates a new administration group
|
||||
func (h *ApplicationHandler) CreateAdministrationGroup(ctx context.Context, name string, modules map[string]any) (string, error) {
|
||||
groupid := uuid.NewString()
|
||||
|
||||
dataMap := map[string]any{
|
||||
"name": name,
|
||||
"modules": modules,
|
||||
}
|
||||
|
||||
data, err := structpb.NewValue(dataMap)
|
||||
if err != nil {
|
||||
log.Error().Err(err).Msg("Cannot create PB struct from data map")
|
||||
return "", fmt.Errorf("failed to create group data: %w", err)
|
||||
}
|
||||
|
||||
request_organization := &groupsmanagement.AddGroupRequest{
|
||||
Group: &groupsmanagement.Group{
|
||||
Id: groupid,
|
||||
Namespace: "parcoursmob_organizations",
|
||||
Data: data.GetStructValue(),
|
||||
},
|
||||
}
|
||||
|
||||
request_role := &groupsmanagement.AddGroupRequest{
|
||||
Group: &groupsmanagement.Group{
|
||||
Id: groupid + ":admin",
|
||||
Namespace: "parcoursmob_roles",
|
||||
},
|
||||
}
|
||||
|
||||
// Create organization group
|
||||
_, err = h.services.GRPC.GroupsManagement.AddGroup(ctx, request_organization)
|
||||
if err != nil {
|
||||
log.Error().Err(err).Msg("Issue in Groups management service - AddGroup")
|
||||
return "", fmt.Errorf("failed to create organization group: %w", err)
|
||||
}
|
||||
|
||||
// Create admin role for the organization
|
||||
_, err = h.services.GRPC.GroupsManagement.AddGroup(ctx, request_role)
|
||||
if err != nil {
|
||||
log.Error().Err(err).Msg("Issue in Groups management service - AddGroup")
|
||||
return "", fmt.Errorf("failed to create admin role: %w", err)
|
||||
}
|
||||
|
||||
return groupid, nil
|
||||
}
|
||||
|
||||
type AdministrationGroupDataResult struct {
|
||||
Group groupstorage.Group
|
||||
Members []mobilityaccountsstorage.Account
|
||||
Admins []mobilityaccountsstorage.Account
|
||||
}
|
||||
|
||||
// GetAdministrationGroupData retrieves data for a specific administration group
|
||||
func (h *ApplicationHandler) GetAdministrationGroupData(ctx context.Context, groupID string) (*AdministrationGroupDataResult, error) {
|
||||
request := &groupsmanagement.GetGroupRequest{
|
||||
Id: groupID,
|
||||
}
|
||||
|
||||
resp, err := h.services.GRPC.GroupsManagement.GetGroup(ctx, request)
|
||||
if err != nil {
|
||||
log.Error().Err(err).Msg("Issue in Groups management service - GetGroup")
|
||||
return nil, fmt.Errorf("failed to get group: %w", err)
|
||||
}
|
||||
|
||||
groupmembers, admins, err := h.groupmembers(groupID)
|
||||
if err != nil {
|
||||
log.Error().Err(err).Msg("issue retrieving group members")
|
||||
return nil, fmt.Errorf("failed to get group members: %w", err)
|
||||
}
|
||||
|
||||
return &AdministrationGroupDataResult{
|
||||
Group: resp.Group.ToStorageType(),
|
||||
Members: groupmembers,
|
||||
Admins: admins,
|
||||
}, nil
|
||||
}
|
||||
|
||||
// InviteAdministrationGroupAdmin invites a user as admin to an administration group
|
||||
func (h *ApplicationHandler) InviteAdministrationGroupAdmin(ctx context.Context, groupID, username string) error {
|
||||
// Get group info
|
||||
groupResp, err := h.services.GRPC.GroupsManagement.GetGroup(ctx, &groupsmanagement.GetGroupRequest{
|
||||
Id: groupID,
|
||||
})
|
||||
if err != nil {
|
||||
return fmt.Errorf("failed to get group: %w", err)
|
||||
}
|
||||
|
||||
group := groupResp.Group.ToStorageType()
|
||||
|
||||
accountresp, err := h.services.GRPC.MobilityAccounts.GetAccountUsername(ctx, &mobilityaccounts.GetAccountUsernameRequest{
|
||||
Username: username,
|
||||
Namespace: "parcoursmob",
|
||||
})
|
||||
|
||||
if err == nil {
|
||||
// Account already exists: adding the existing account to group as admin
|
||||
account := accountresp.Account.ToStorageType()
|
||||
if account.Data["groups"] == nil {
|
||||
account.Data["groups"] = []any{}
|
||||
}
|
||||
account.Data["groups"] = append(account.Data["groups"].([]any), groupID+":admin")
|
||||
|
||||
as, err := mobilityaccounts.AccountFromStorageType(&account)
|
||||
if err != nil {
|
||||
return fmt.Errorf("failed to convert account: %w", err)
|
||||
}
|
||||
|
||||
_, err = h.services.GRPC.MobilityAccounts.UpdateData(ctx, &mobilityaccounts.UpdateDataRequest{
|
||||
Account: as,
|
||||
})
|
||||
if err != nil {
|
||||
return fmt.Errorf("failed to update account: %w", err)
|
||||
}
|
||||
|
||||
data := map[string]any{
|
||||
"group": group.Data["name"],
|
||||
"baseUrl": h.config.GetString("base_url"),
|
||||
}
|
||||
|
||||
if err := h.emailing.Send("onboarding.existing_administrator", username, data); err != nil {
|
||||
log.Warn().Err(err).Msg("failed to send existing admin email")
|
||||
}
|
||||
} else {
|
||||
// Create onboarding for new admin
|
||||
onboarding := map[string]any{
|
||||
"username": username,
|
||||
"group": groupID,
|
||||
"admin": true,
|
||||
}
|
||||
|
||||
b := make([]byte, 16)
|
||||
if _, err := io.ReadFull(rand.Reader, b); err != nil {
|
||||
return fmt.Errorf("failed to generate random key: %w", err)
|
||||
}
|
||||
key := base64.RawURLEncoding.EncodeToString(b)
|
||||
|
||||
h.cache.PutWithTTL("onboarding/"+key, onboarding, 72*time.Hour)
|
||||
|
||||
data := map[string]any{
|
||||
"group": group.Data["name"],
|
||||
"key": key,
|
||||
"baseUrl": h.config.GetString("base_url"),
|
||||
}
|
||||
|
||||
if err := h.emailing.Send("onboarding.new_administrator", username, data); err != nil {
|
||||
return fmt.Errorf("failed to send new admin email: %w", err)
|
||||
}
|
||||
}
|
||||
|
||||
return nil
|
||||
}
|
||||
|
||||
// InviteAdministrationGroupMember invites a user as member to an administration group
|
||||
func (h *ApplicationHandler) InviteAdministrationGroupMember(ctx context.Context, groupID, username string) error {
|
||||
// Get group info
|
||||
groupResp, err := h.services.GRPC.GroupsManagement.GetGroup(ctx, &groupsmanagement.GetGroupRequest{
|
||||
Id: groupID,
|
||||
})
|
||||
if err != nil {
|
||||
return fmt.Errorf("failed to get group: %w", err)
|
||||
}
|
||||
|
||||
group := groupResp.Group.ToStorageType()
|
||||
|
||||
accountresp, err := h.services.GRPC.MobilityAccounts.GetAccountUsername(ctx, &mobilityaccounts.GetAccountUsernameRequest{
|
||||
Username: username,
|
||||
Namespace: "parcoursmob",
|
||||
})
|
||||
|
||||
if err == nil {
|
||||
// Account already exists: adding the existing account to group
|
||||
account := accountresp.Account.ToStorageType()
|
||||
if account.Data["groups"] == nil {
|
||||
account.Data["groups"] = []any{}
|
||||
}
|
||||
account.Data["groups"] = append(account.Data["groups"].([]any), groupID)
|
||||
|
||||
as, err := mobilityaccounts.AccountFromStorageType(&account)
|
||||
if err != nil {
|
||||
return fmt.Errorf("failed to convert account: %w", err)
|
||||
}
|
||||
|
||||
_, err = h.services.GRPC.MobilityAccounts.UpdateData(ctx, &mobilityaccounts.UpdateDataRequest{
|
||||
Account: as,
|
||||
})
|
||||
if err != nil {
|
||||
return fmt.Errorf("failed to update account: %w", err)
|
||||
}
|
||||
|
||||
data := map[string]any{
|
||||
"group": group.Data["name"],
|
||||
"baseUrl": h.config.GetString("base_url"),
|
||||
}
|
||||
|
||||
if err := h.emailing.Send("onboarding.existing_member", username, data); err != nil {
|
||||
log.Warn().Err(err).Msg("failed to send existing member email")
|
||||
}
|
||||
} else {
|
||||
// Create onboarding for new member
|
||||
onboarding := map[string]any{
|
||||
"username": username,
|
||||
"group": groupID,
|
||||
"admin": false,
|
||||
}
|
||||
|
||||
b := make([]byte, 16)
|
||||
if _, err := io.ReadFull(rand.Reader, b); err != nil {
|
||||
return fmt.Errorf("failed to generate random key: %w", err)
|
||||
}
|
||||
key := base64.RawURLEncoding.EncodeToString(b)
|
||||
|
||||
h.cache.PutWithTTL("onboarding/"+key, onboarding, 72*time.Hour)
|
||||
|
||||
data := map[string]any{
|
||||
"group": group.Data["name"],
|
||||
"key": key,
|
||||
"baseUrl": h.config.GetString("base_url"),
|
||||
}
|
||||
|
||||
if err := h.emailing.Send("onboarding.new_member", username, data); err != nil {
|
||||
return fmt.Errorf("failed to send new member email: %w", err)
|
||||
}
|
||||
}
|
||||
|
||||
return nil
|
||||
}
|
||||
|
||||
func filteVehicle(r *http.Request, v *fleets.Vehicle) bool {
|
||||
g := r.Context().Value(identification.GroupKey)
|
||||
if g == nil {
|
||||
return false
|
||||
}
|
||||
|
||||
group := g.(storage.Group)
|
||||
|
||||
for _, n := range v.Administrators {
|
||||
if n == group.ID {
|
||||
return true
|
||||
}
|
||||
}
|
||||
|
||||
return false
|
||||
}
|
||||
|
||||
func (h *ApplicationHandler) GetVehiclesStats() (*AdminVehiclesStatsResult, error) {
|
||||
bookings := []fleetsstorage.Booking{}
|
||||
administrators := []string{}
|
||||
request := &fleets.GetVehiclesRequest{
|
||||
Namespaces: []string{"parcoursmob"},
|
||||
}
|
||||
resp, err := h.services.GRPC.Fleets.GetVehicles(context.TODO(), request)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
|
||||
vehicles := []fleetsstorage.Vehicle{}
|
||||
for _, vehicle := range resp.Vehicles {
|
||||
v := vehicle.ToStorageType()
|
||||
adminfound := false
|
||||
for _, a := range administrators {
|
||||
if len(v.Administrators) > 0 && a == v.Administrators[0] {
|
||||
adminfound = true
|
||||
break
|
||||
}
|
||||
}
|
||||
if !adminfound && len(v.Administrators) > 0 {
|
||||
administrators = append(administrators, v.Administrators[0])
|
||||
}
|
||||
|
||||
vehicleBookings := []fleetsstorage.Booking{}
|
||||
for _, b := range v.Bookings {
|
||||
if b.Unavailableto.After(time.Now()) {
|
||||
vehicleBookings = append(vehicleBookings, b)
|
||||
}
|
||||
}
|
||||
|
||||
v.Bookings = vehicleBookings
|
||||
vehicles = append(vehicles, v)
|
||||
}
|
||||
|
||||
groups := map[string]any{}
|
||||
if len(administrators) > 0 {
|
||||
admingroups, err := h.services.GRPC.GroupsManagement.GetGroupsBatch(context.TODO(), &groupsmanagement.GetGroupsBatchRequest{
|
||||
Groupids: administrators,
|
||||
})
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
|
||||
for _, g := range admingroups.Groups {
|
||||
groups[g.Id] = g.ToStorageType()
|
||||
}
|
||||
}
|
||||
|
||||
sort.Sort(sorting.VehiclesByLicencePlate(vehicles))
|
||||
sort.Sort(sorting.BookingsByStartdate(bookings))
|
||||
|
||||
return &AdminVehiclesStatsResult{
|
||||
Vehicles: vehicles,
|
||||
Bookings: bookings,
|
||||
Groups: groups,
|
||||
}, nil
|
||||
}
|
||||
|
||||
func (h *ApplicationHandler) GetBookingsStats(status, startDate, endDate string) (*AdminBookingsStatsResult, error) {
|
||||
vehicles := map[string]fleetsstorage.Vehicle{}
|
||||
bookings := []fleetsstorage.Booking{}
|
||||
|
||||
// Parse start date filter
|
||||
var startdate time.Time
|
||||
if startDate != "" {
|
||||
if parsed, err := time.Parse("2006-01-02", startDate); err == nil {
|
||||
startdate = parsed
|
||||
}
|
||||
}
|
||||
|
||||
// Parse end date filter
|
||||
var enddate time.Time
|
||||
if endDate != "" {
|
||||
if parsed, err := time.Parse("2006-01-02", endDate); err == nil {
|
||||
enddate = parsed.Add(24 * time.Hour) // End of day
|
||||
}
|
||||
}
|
||||
|
||||
request := &fleets.GetVehiclesRequest{
|
||||
Namespaces: []string{"parcoursmob"},
|
||||
IncludeDeleted: true,
|
||||
}
|
||||
resp, err := h.services.GRPC.Fleets.GetVehicles(context.TODO(), request)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
|
||||
beneficiaries_ids := []string{}
|
||||
|
||||
for _, vehicle := range resp.Vehicles {
|
||||
v := vehicle.ToStorageType()
|
||||
|
||||
for _, b := range v.Bookings {
|
||||
// Apply status filter
|
||||
if status != "" {
|
||||
bookingStatus := b.Status()
|
||||
statusInt := 0
|
||||
|
||||
if b.Deleted {
|
||||
statusInt = -2 // Use -2 for cancelled to distinguish from terminated
|
||||
} else {
|
||||
statusInt = bookingStatus
|
||||
}
|
||||
|
||||
// Map status string to int
|
||||
var filterStatusInt int
|
||||
switch status {
|
||||
case "FORTHCOMING":
|
||||
filterStatusInt = 1
|
||||
case "ONGOING":
|
||||
filterStatusInt = 0
|
||||
case "TERMINATED":
|
||||
filterStatusInt = -1
|
||||
case "CANCELLED":
|
||||
filterStatusInt = -2
|
||||
default:
|
||||
filterStatusInt = 999 // Invalid status, won't match anything
|
||||
}
|
||||
|
||||
if statusInt != filterStatusInt {
|
||||
continue
|
||||
}
|
||||
}
|
||||
|
||||
// Apply date filter (on startdate)
|
||||
if !startdate.IsZero() && b.Startdate.Before(startdate) {
|
||||
continue
|
||||
}
|
||||
if !enddate.IsZero() && b.Startdate.After(enddate) {
|
||||
continue
|
||||
}
|
||||
|
||||
bookings = append(bookings, b)
|
||||
beneficiaries_ids = append(beneficiaries_ids, b.Driver)
|
||||
}
|
||||
|
||||
vehicles[v.ID] = v
|
||||
}
|
||||
|
||||
groups := map[string]any{}
|
||||
|
||||
admingroups, err := h.services.GRPC.GroupsManagement.GetGroups(context.TODO(), &groupsmanagement.GetGroupsRequest{
|
||||
Namespaces: []string{"parcoursmob_organizations"},
|
||||
})
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
|
||||
for _, g := range admingroups.Groups {
|
||||
groups[g.Id] = g.ToStorageType()
|
||||
}
|
||||
|
||||
beneficiaries, err := h.services.GRPC.MobilityAccounts.GetAccountsBatch(context.TODO(), &accounts.GetAccountsBatchRequest{
|
||||
Accountids: beneficiaries_ids,
|
||||
})
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
|
||||
beneficiaries_map := map[string]any{}
|
||||
for _, ben := range beneficiaries.Accounts {
|
||||
beneficiaries_map[ben.Id] = ben.ToStorageType()
|
||||
}
|
||||
|
||||
return &AdminBookingsStatsResult{
|
||||
Vehicles: vehicles,
|
||||
Bookings: bookings,
|
||||
Groups: groups,
|
||||
BeneficiariesMap: beneficiaries_map,
|
||||
}, nil
|
||||
}
|
||||
|
||||
func (h *ApplicationHandler) GetBeneficiariesStats() (*AdminBeneficiariesStatsResult, error) {
|
||||
beneficiaries, err := h.services.GetBeneficiaries()
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
|
||||
cacheid := uuid.New().String()
|
||||
h.cache.Put(cacheid, beneficiaries)
|
||||
|
||||
return &AdminBeneficiariesStatsResult{
|
||||
Beneficiaries: beneficiaries,
|
||||
CacheID: cacheid,
|
||||
}, nil
|
||||
}
|
||||
|
||||
func (h *ApplicationHandler) GetEventsStats() (*AdminEventsStatsResult, error) {
|
||||
resp, err := h.services.GRPC.Agenda.GetEvents(context.TODO(), &agenda.GetEventsRequest{
|
||||
Namespaces: []string{"parcoursmob_dispositifs"},
|
||||
})
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
|
||||
responses := []agendastorage.Event{}
|
||||
groupids := []string{}
|
||||
|
||||
for _, event := range resp.Events {
|
||||
responses = append(responses, event.ToStorageType())
|
||||
groupids = append(groupids, event.Owners...)
|
||||
}
|
||||
|
||||
groupsResponse, err := h.services.GRPC.GroupsManagement.GetGroupsBatch(context.TODO(), &groupsmanagement.GetGroupsBatchRequest{
|
||||
Groupids: groupids,
|
||||
})
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
|
||||
groups := map[string]any{}
|
||||
for _, g := range groupsResponse.Groups {
|
||||
groups[g.Id] = g.ToStorageType()
|
||||
}
|
||||
|
||||
return &AdminEventsStatsResult{
|
||||
Events: responses,
|
||||
Groups: groups,
|
||||
}, nil
|
||||
}
|
||||
|
||||
func (h *ApplicationHandler) members() ([]*accounts.Account, error) {
|
||||
resp, err := h.services.GRPC.MobilityAccounts.GetAccounts(context.TODO(), &accounts.GetAccountsRequest{
|
||||
Namespaces: []string{"parcoursmob"},
|
||||
})
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
|
||||
return resp.Accounts, nil
|
||||
}
|
||||
|
||||
func (h *ApplicationHandler) groupmembers(groupid string) (groupmembers []mobilityaccountsstorage.Account, admins []mobilityaccountsstorage.Account, err error) {
|
||||
members, err := h.members()
|
||||
if err != nil {
|
||||
if err != nil {
|
||||
log.Error().Err(err).Msg("Cannot get members")
|
||||
return nil, nil, err
|
||||
}
|
||||
}
|
||||
|
||||
groupmembers = []mobilityaccountsstorage.Account{}
|
||||
admins = []mobilityaccountsstorage.Account{}
|
||||
|
||||
for _, m := range members {
|
||||
mm := m.ToStorageType()
|
||||
for _, g := range mm.Data["groups"].([]any) {
|
||||
if g.(string) == groupid {
|
||||
groupmembers = append(groupmembers, mm)
|
||||
}
|
||||
if g.(string) == groupid+":admin" {
|
||||
admins = append(admins, mm)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
return groupmembers, admins, err
|
||||
}
|
||||
602
core/application/agenda.go
Executable file
602
core/application/agenda.go
Executable file
@@ -0,0 +1,602 @@
|
||||
package application
|
||||
|
||||
import (
|
||||
"context"
|
||||
"fmt"
|
||||
"io"
|
||||
"sort"
|
||||
"time"
|
||||
|
||||
"git.coopgo.io/coopgo-apps/parcoursmob/core/utils/identification"
|
||||
"git.coopgo.io/coopgo-apps/parcoursmob/core/utils/sorting"
|
||||
"git.coopgo.io/coopgo-apps/parcoursmob/services"
|
||||
filestorage "git.coopgo.io/coopgo-apps/parcoursmob/core/utils/storage"
|
||||
agenda "git.coopgo.io/coopgo-platform/agenda/grpcapi"
|
||||
agendastorage "git.coopgo.io/coopgo-platform/agenda/storage"
|
||||
groupsmanagement "git.coopgo.io/coopgo-platform/groups-management/grpcapi"
|
||||
"git.coopgo.io/coopgo-platform/groups-management/storage"
|
||||
mobilityaccounts "git.coopgo.io/coopgo-platform/mobility-accounts/grpcapi"
|
||||
ics "github.com/arran4/golang-ical"
|
||||
"github.com/google/uuid"
|
||||
"github.com/rs/zerolog/log"
|
||||
"google.golang.org/protobuf/types/known/structpb"
|
||||
"google.golang.org/protobuf/types/known/timestamppb"
|
||||
)
|
||||
|
||||
|
||||
type AgendaEventsResult struct {
|
||||
Events []agendastorage.Event
|
||||
Groups map[string]any
|
||||
}
|
||||
|
||||
func (h *ApplicationHandler) GetAgendaEvents(ctx context.Context, minDate, maxDate *time.Time) (*AgendaEventsResult, error) {
|
||||
request := &agenda.GetEventsRequest{
|
||||
Namespaces: []string{"parcoursmob_dispositifs"},
|
||||
}
|
||||
|
||||
if minDate != nil {
|
||||
request.Mindate = timestamppb.New(*minDate)
|
||||
}
|
||||
if maxDate != nil {
|
||||
request.Maxdate = timestamppb.New(*maxDate)
|
||||
}
|
||||
|
||||
resp, err := h.services.GRPC.Agenda.GetEvents(ctx, request)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
|
||||
responses := []agendastorage.Event{}
|
||||
groupids := []string{}
|
||||
for _, e := range resp.Events {
|
||||
groupids = append(groupids, e.Owners...)
|
||||
responses = append(responses, e.ToStorageType())
|
||||
}
|
||||
|
||||
sort.Sort(sorting.EventsByStartdate(responses))
|
||||
|
||||
groups := map[string]any{}
|
||||
if len(groupids) > 0 {
|
||||
groupsresp, err := h.services.GRPC.GroupsManagement.GetGroupsBatch(ctx, &groupsmanagement.GetGroupsBatchRequest{
|
||||
Groupids: groupids,
|
||||
})
|
||||
if err == nil {
|
||||
for _, g := range groupsresp.Groups {
|
||||
groups[g.Id] = g.ToStorageType()
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
return &AgendaEventsResult{
|
||||
Events: responses,
|
||||
Groups: groups,
|
||||
}, nil
|
||||
}
|
||||
|
||||
|
||||
|
||||
func (h *ApplicationHandler) CreateAgendaEvent(ctx context.Context, name, eventType, description string, address any, allday bool, startdate, enddate *time.Time, starttime, endtime string, maxSubscribers int, file io.Reader, filename string, fileSize int64, documentType, documentName string) (string, error) {
|
||||
// Get current group
|
||||
g := ctx.Value(identification.GroupKey)
|
||||
if g == nil {
|
||||
return "", fmt.Errorf("no group found in context")
|
||||
}
|
||||
|
||||
group := g.(storage.Group)
|
||||
|
||||
data, _ := structpb.NewStruct(map[string]any{
|
||||
"address": address,
|
||||
})
|
||||
|
||||
request := &agenda.CreateEventRequest{
|
||||
Event: &agenda.Event{
|
||||
Namespace: "parcoursmob_dispositifs",
|
||||
Owners: []string{group.ID},
|
||||
Type: eventType,
|
||||
Name: name,
|
||||
Description: description,
|
||||
Startdate: timestamppb.New(*startdate),
|
||||
Enddate: timestamppb.New(*enddate),
|
||||
Starttime: starttime,
|
||||
Endtime: endtime,
|
||||
Allday: allday,
|
||||
MaxSubscribers: int64(maxSubscribers),
|
||||
Data: data,
|
||||
Deleted: false,
|
||||
},
|
||||
}
|
||||
|
||||
resp, err := h.services.GRPC.Agenda.CreateEvent(ctx, request)
|
||||
if err != nil {
|
||||
return "", err
|
||||
}
|
||||
|
||||
// Handle file upload if provided
|
||||
if file != nil && filename != "" {
|
||||
fileid := uuid.NewString()
|
||||
|
||||
metadata := map[string]string{
|
||||
"file_type": documentType,
|
||||
"file_name": documentName,
|
||||
}
|
||||
|
||||
if err := h.filestorage.Put(file, filestorage.PREFIX_AGENDA, fmt.Sprintf("%s/%s_%s", resp.Event.Id, fileid, filename), fileSize, metadata); err != nil {
|
||||
return "", err
|
||||
}
|
||||
}
|
||||
|
||||
return resp.Event.Id, nil
|
||||
}
|
||||
|
||||
|
||||
type AgendaEventResult struct {
|
||||
Event agendastorage.Event
|
||||
Group storage.Group
|
||||
Documents []filestorage.FileInfo
|
||||
Subscribers map[string]any
|
||||
Accounts []any
|
||||
}
|
||||
|
||||
func (h *ApplicationHandler) GetAgendaEvent(ctx context.Context, eventID string) (*AgendaEventResult, error) {
|
||||
request := &agenda.GetEventRequest{
|
||||
Id: eventID,
|
||||
}
|
||||
|
||||
resp, err := h.services.GRPC.Agenda.GetEvent(ctx, request)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
|
||||
grouprequest := &groupsmanagement.GetGroupRequest{
|
||||
Id: resp.Event.Owners[0],
|
||||
}
|
||||
|
||||
groupresp, err := h.services.GRPC.GroupsManagement.GetGroup(ctx, grouprequest)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
|
||||
subscribers := map[string]any{}
|
||||
accids := []string{}
|
||||
for _, v := range resp.Event.Subscriptions {
|
||||
accids = append(accids, v.Subscriber)
|
||||
}
|
||||
|
||||
if len(accids) > 0 {
|
||||
subscriberresp, err := h.services.GRPC.MobilityAccounts.GetAccountsBatch(
|
||||
ctx,
|
||||
&mobilityaccounts.GetAccountsBatchRequest{
|
||||
Accountids: accids,
|
||||
},
|
||||
)
|
||||
if err == nil {
|
||||
for _, sub := range subscriberresp.Accounts {
|
||||
subscribers[sub.Id] = sub.ToStorageType()
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
g := ctx.Value(identification.GroupKey)
|
||||
if g == nil {
|
||||
return nil, fmt.Errorf("no group found in context")
|
||||
}
|
||||
|
||||
group := g.(storage.Group)
|
||||
|
||||
accountids := []string{}
|
||||
for _, m := range group.Members {
|
||||
if !contains(resp.Event.Subscriptions, m) {
|
||||
accountids = append(accountids, m)
|
||||
}
|
||||
}
|
||||
|
||||
accounts := []any{}
|
||||
if len(accountids) > 0 {
|
||||
accountresp, err := h.services.GRPC.MobilityAccounts.GetAccountsBatch(
|
||||
ctx,
|
||||
&mobilityaccounts.GetAccountsBatchRequest{
|
||||
Accountids: accountids,
|
||||
},
|
||||
)
|
||||
if err == nil {
|
||||
for _, acc := range accountresp.Accounts {
|
||||
accounts = append(accounts, acc)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
documents := h.filestorage.List(filestorage.PREFIX_AGENDA + "/" + eventID)
|
||||
|
||||
return &AgendaEventResult{
|
||||
Event: resp.Event.ToStorageType(),
|
||||
Group: groupresp.Group.ToStorageType(),
|
||||
Documents: documents,
|
||||
Subscribers: subscribers,
|
||||
Accounts: accounts,
|
||||
}, nil
|
||||
}
|
||||
|
||||
|
||||
func (h *ApplicationHandler) SubscribeToAgendaEvent(ctx context.Context, eventID, subscriber string, subscriptionData map[string]any) error {
|
||||
datapb, err := structpb.NewStruct(subscriptionData)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
request := &agenda.SubscribeEventRequest{
|
||||
Eventid: eventID,
|
||||
Subscriber: subscriber,
|
||||
Data: datapb,
|
||||
}
|
||||
|
||||
_, err = h.services.GRPC.Agenda.SubscribeEvent(ctx, request)
|
||||
return err
|
||||
}
|
||||
|
||||
func (h *ApplicationHandler) UnsubscribeFromAgendaEvent(ctx context.Context, eventID, subscribeID, motif, currentUserID, currentUserDisplayName, currentUserEmail, currentGroupID, currentGroupName string) error {
|
||||
// Get the event first
|
||||
request := &agenda.GetEventRequest{
|
||||
Id: eventID,
|
||||
}
|
||||
|
||||
resp, err := h.services.GRPC.Agenda.GetEvent(ctx, request)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
// Find subscription data for the subscriber being removed
|
||||
var s_b_id, s_b_name, s_b_email, s_b_group_id, s_b_group_name string
|
||||
for i := range resp.Event.Subscriptions {
|
||||
if resp.Event.Subscriptions[i].Subscriber == subscribeID {
|
||||
s_b_id = resp.Event.Subscriptions[i].Data.Fields["subscribed_by"].GetStructValue().Fields["user"].GetStructValue().Fields["id"].GetStringValue()
|
||||
s_b_name = resp.Event.Subscriptions[i].Data.Fields["subscribed_by"].GetStructValue().Fields["user"].GetStructValue().Fields["display_name"].GetStringValue()
|
||||
s_b_email = resp.Event.Subscriptions[i].Data.Fields["subscribed_by"].GetStructValue().Fields["user"].GetStructValue().Fields["email"].GetStringValue()
|
||||
s_b_group_id = resp.Event.Subscriptions[i].Data.Fields["subscribed_by"].GetStructValue().Fields["group"].GetStructValue().Fields["id"].GetStringValue()
|
||||
s_b_group_name = resp.Event.Subscriptions[i].Data.Fields["subscribed_by"].GetStructValue().Fields["group"].GetStructValue().Fields["name"].GetStringValue()
|
||||
break
|
||||
}
|
||||
}
|
||||
|
||||
data := map[string]any{
|
||||
"subscribed_by": map[string]any{
|
||||
"user": map[string]any{
|
||||
"id": s_b_id,
|
||||
"display_name": s_b_name,
|
||||
"email": s_b_email,
|
||||
},
|
||||
"group": map[string]any{
|
||||
"id": s_b_group_id,
|
||||
"name": s_b_group_name,
|
||||
},
|
||||
},
|
||||
"unsubscribed_by": map[string]any{
|
||||
"user": map[string]any{
|
||||
"id": currentUserID,
|
||||
"display_name": currentUserDisplayName,
|
||||
"email": currentUserEmail,
|
||||
},
|
||||
"group": map[string]any{
|
||||
"id": currentGroupID,
|
||||
"name": currentGroupName,
|
||||
},
|
||||
},
|
||||
"motif": motif,
|
||||
}
|
||||
|
||||
datapb, err := structpb.NewStruct(data)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
deleteRequest := &agenda.DeleteSubscriptionRequest{
|
||||
Subscriber: subscribeID,
|
||||
Eventid: eventID,
|
||||
Data: datapb,
|
||||
}
|
||||
|
||||
_, err = h.services.GRPC.Agenda.DeleteSubscription(ctx, deleteRequest)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
// Send email notification
|
||||
emailData := map[string]any{
|
||||
"motif": motif,
|
||||
"user": currentUserDisplayName,
|
||||
"subscriber": fmt.Sprintf("http://localhost:9000/app/beneficiaries/%s", subscribeID),
|
||||
"link": fmt.Sprintf("http://localhost:9000/app/agenda/%s", eventID),
|
||||
}
|
||||
|
||||
if err := h.emailing.Send("delete_subscriber.request", s_b_email, emailData); err != nil {
|
||||
log.Error().Err(err).Msg("Cannot send email")
|
||||
// Don't return error for email failure
|
||||
}
|
||||
|
||||
return nil
|
||||
}
|
||||
|
||||
type AgendaEventHistoryResult struct {
|
||||
Event agendastorage.Event
|
||||
Group storage.Group
|
||||
Subscribers map[string]any
|
||||
Accounts []any
|
||||
}
|
||||
|
||||
func (h *ApplicationHandler) GetAgendaEventHistory(ctx context.Context, eventID string) (*AgendaEventHistoryResult, error) {
|
||||
request := &agenda.GetEventRequest{
|
||||
Id: eventID,
|
||||
}
|
||||
|
||||
resp, err := h.services.GRPC.Agenda.GetEvent(ctx, request)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
|
||||
grouprequest := &groupsmanagement.GetGroupRequest{
|
||||
Id: resp.Event.Owners[0],
|
||||
}
|
||||
|
||||
groupresp, err := h.services.GRPC.GroupsManagement.GetGroup(ctx, grouprequest)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
|
||||
subscribers := map[string]any{}
|
||||
|
||||
accids := []string{}
|
||||
for _, v := range resp.Event.DeletedSubscription {
|
||||
accids = append(accids, v.Subscriber)
|
||||
}
|
||||
|
||||
if len(accids) > 0 {
|
||||
subscriberresp, err := h.services.GRPC.MobilityAccounts.GetAccountsBatch(
|
||||
ctx,
|
||||
&mobilityaccounts.GetAccountsBatchRequest{
|
||||
Accountids: accids,
|
||||
},
|
||||
)
|
||||
|
||||
if err == nil {
|
||||
for _, sub := range subscriberresp.Accounts {
|
||||
subscribers[sub.Id] = sub.ToStorageType()
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
g := ctx.Value(identification.GroupKey)
|
||||
if g == nil {
|
||||
return nil, fmt.Errorf("no group found in context")
|
||||
}
|
||||
|
||||
group := g.(storage.Group)
|
||||
|
||||
accountids := []string{}
|
||||
for _, m := range group.Members {
|
||||
if !contains(resp.Event.DeletedSubscription, m) {
|
||||
accountids = append(accountids, m)
|
||||
}
|
||||
}
|
||||
|
||||
accounts := []any{}
|
||||
if len(accountids) > 0 {
|
||||
accountresp, err := h.services.GRPC.MobilityAccounts.GetAccountsBatch(
|
||||
ctx,
|
||||
&mobilityaccounts.GetAccountsBatchRequest{
|
||||
Accountids: accountids,
|
||||
},
|
||||
)
|
||||
|
||||
if err == nil {
|
||||
for _, acc := range accountresp.Accounts {
|
||||
accounts = append(accounts, acc)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
return &AgendaEventHistoryResult{
|
||||
Event: resp.Event.ToStorageType(),
|
||||
Group: groupresp.Group.ToStorageType(),
|
||||
Subscribers: subscribers,
|
||||
Accounts: accounts,
|
||||
}, nil
|
||||
}
|
||||
|
||||
func (h *ApplicationHandler) AddEventDocument(ctx context.Context, eventID string, file io.Reader, filename string, fileSize int64, documentType, documentName string) error {
|
||||
fileid := uuid.NewString()
|
||||
|
||||
metadata := map[string]string{
|
||||
"type": documentType,
|
||||
"name": documentName,
|
||||
}
|
||||
|
||||
if err := h.filestorage.Put(file, filestorage.PREFIX_AGENDA, fmt.Sprintf("%s/%s_%s", eventID, fileid, filename), fileSize, metadata); err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
return nil
|
||||
}
|
||||
|
||||
func (h *ApplicationHandler) GetEventDocument(ctx context.Context, eventID, document string) (io.Reader, *filestorage.FileInfo, error) {
|
||||
file, info, err := h.filestorage.Get(filestorage.PREFIX_AGENDA, fmt.Sprintf("%s/%s", eventID, document))
|
||||
if err != nil {
|
||||
return nil, nil, err
|
||||
}
|
||||
|
||||
return file, info, nil
|
||||
}
|
||||
|
||||
|
||||
|
||||
func contains(s []*agenda.Subscription, e string) bool {
|
||||
for _, a := range s {
|
||||
if a.Subscriber == e {
|
||||
return true
|
||||
}
|
||||
}
|
||||
return false
|
||||
}
|
||||
|
||||
func (h *ApplicationHandler) UpdateAgendaEvent(ctx context.Context, eventID, name, eventType, description string, address any, allday bool, startdate, enddate *time.Time, starttime, endtime string, maxSubscribers int) (string, error) {
|
||||
// Get current group
|
||||
g := ctx.Value(identification.GroupKey)
|
||||
if g == nil {
|
||||
return "", fmt.Errorf("no group found in context")
|
||||
}
|
||||
|
||||
group := g.(storage.Group)
|
||||
|
||||
// Get existing event first
|
||||
getRequest := &agenda.GetEventRequest{
|
||||
Id: eventID,
|
||||
}
|
||||
|
||||
resp, err := h.services.GRPC.Agenda.GetEvent(ctx, getRequest)
|
||||
if err != nil {
|
||||
return "", err
|
||||
}
|
||||
|
||||
data, _ := structpb.NewStruct(map[string]any{
|
||||
"address": address,
|
||||
})
|
||||
|
||||
request := &agenda.UpdateEventRequest{
|
||||
Event: &agenda.Event{
|
||||
Namespace: "parcoursmob_dispositifs",
|
||||
Id: eventID,
|
||||
Owners: []string{group.ID},
|
||||
Type: eventType,
|
||||
Name: name,
|
||||
Description: description,
|
||||
Startdate: timestamppb.New(*startdate),
|
||||
Enddate: timestamppb.New(*enddate),
|
||||
Starttime: starttime,
|
||||
Endtime: endtime,
|
||||
Allday: allday,
|
||||
MaxSubscribers: int64(maxSubscribers),
|
||||
Data: data,
|
||||
Subscriptions: resp.Event.Subscriptions,
|
||||
},
|
||||
}
|
||||
|
||||
updateResp, err := h.services.GRPC.Agenda.UpdateEvent(ctx, request)
|
||||
if err != nil {
|
||||
return "", err
|
||||
}
|
||||
|
||||
return updateResp.Event.Id, nil
|
||||
}
|
||||
|
||||
|
||||
func (h *ApplicationHandler) DeleteAgendaEvent(ctx context.Context, eventID string) error {
|
||||
request := &agenda.GetEventRequest{
|
||||
Id: eventID,
|
||||
}
|
||||
|
||||
resp, err := h.services.GRPC.Agenda.GetEvent(ctx, request)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
updateRequest := &agenda.UpdateEventRequest{
|
||||
Event: &agenda.Event{
|
||||
Namespace: resp.Event.Namespace,
|
||||
Id: resp.Event.Id,
|
||||
Owners: resp.Event.Owners,
|
||||
Type: resp.Event.Type,
|
||||
Name: resp.Event.Name,
|
||||
Description: resp.Event.Description,
|
||||
Startdate: resp.Event.Startdate,
|
||||
Enddate: resp.Event.Enddate,
|
||||
Starttime: resp.Event.Starttime,
|
||||
Endtime: resp.Event.Endtime,
|
||||
Allday: resp.Event.Allday,
|
||||
MaxSubscribers: int64(resp.Event.MaxSubscribers),
|
||||
Data: resp.Event.Data,
|
||||
Subscriptions: resp.Event.Subscriptions,
|
||||
Deleted: true,
|
||||
},
|
||||
}
|
||||
|
||||
_, err = h.services.GRPC.Agenda.UpdateEvent(ctx, updateRequest)
|
||||
return err
|
||||
}
|
||||
|
||||
type CalendarResult struct {
|
||||
CalendarData string
|
||||
}
|
||||
|
||||
func (h *ApplicationHandler) GenerateGlobalCalendar(ctx context.Context) (*CalendarResult, error) {
|
||||
events, err := h.services.GetAgendaEvents()
|
||||
if err != nil {
|
||||
log.Error().Err(err).Msg("error retrieving agenda events")
|
||||
return nil, err
|
||||
}
|
||||
|
||||
calendar, err := h.icsCalendar(events)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
|
||||
return &CalendarResult{
|
||||
CalendarData: calendar.Serialize(),
|
||||
}, nil
|
||||
}
|
||||
|
||||
func (h *ApplicationHandler) GenerateOrganizationCalendar(ctx context.Context, groupID string) (*CalendarResult, error) {
|
||||
events, err := h.services.GetAgendaEvents()
|
||||
if err != nil {
|
||||
log.Error().Err(err).Msg("error retrieving agenda events")
|
||||
return nil, err
|
||||
}
|
||||
|
||||
filteredEvents := []services.AgendaEvent{}
|
||||
for _, e := range events {
|
||||
for _, g := range e.Owners {
|
||||
if g == groupID {
|
||||
filteredEvents = append(filteredEvents, e)
|
||||
break
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
calendar, err := h.icsCalendar(filteredEvents)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
|
||||
return &CalendarResult{
|
||||
CalendarData: calendar.Serialize(),
|
||||
}, nil
|
||||
}
|
||||
|
||||
func (h *ApplicationHandler) icsCalendar(events []services.AgendaEvent) (*ics.Calendar, error) {
|
||||
calendar := ics.NewCalendarFor(h.config.GetString("service_name"))
|
||||
|
||||
for _, e := range events {
|
||||
vevent := ics.NewEvent(e.ID)
|
||||
vevent.SetSummary(e.Name)
|
||||
vevent.SetDescription(e.Description)
|
||||
if e.Allday {
|
||||
vevent.SetAllDayStartAt(e.Startdate)
|
||||
if e.Enddate.After(e.Startdate) {
|
||||
vevent.SetAllDayEndAt(e.Enddate.Add(24 * time.Hour))
|
||||
}
|
||||
} else {
|
||||
timeloc, err := time.LoadLocation("Europe/Paris")
|
||||
if err != nil {
|
||||
log.Error().Err(err).Msg("Tried to load timezone location Europe/Paris. Error. Missing zones in container ?")
|
||||
return nil, err
|
||||
}
|
||||
vevent.SetStartAt(e.Startdate.In(timeloc))
|
||||
vevent.SetEndAt(e.Enddate.In(timeloc))
|
||||
}
|
||||
calendar.AddVEvent(vevent)
|
||||
}
|
||||
|
||||
return calendar, nil
|
||||
}
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
@@ -4,10 +4,9 @@ import (
|
||||
"errors"
|
||||
"net/http"
|
||||
|
||||
"git.coopgo.io/coopgo-apps/parcoursmob/renderer"
|
||||
"git.coopgo.io/coopgo-apps/parcoursmob/services"
|
||||
"git.coopgo.io/coopgo-apps/parcoursmob/utils/identification"
|
||||
cache "git.coopgo.io/coopgo-apps/parcoursmob/utils/storage"
|
||||
"git.coopgo.io/coopgo-apps/parcoursmob/core/utils/identification"
|
||||
cache "git.coopgo.io/coopgo-apps/parcoursmob/core/utils/storage"
|
||||
"git.coopgo.io/coopgo-platform/emailing"
|
||||
"git.coopgo.io/coopgo-platform/groups-management/storage"
|
||||
"github.com/coreos/go-oidc/v3/oidc"
|
||||
@@ -16,29 +15,24 @@ import (
|
||||
|
||||
type ApplicationHandler struct {
|
||||
config *viper.Viper
|
||||
Renderer *renderer.Renderer
|
||||
services *services.ServicesHandler
|
||||
cache cache.CacheHandler
|
||||
filestorage cache.FileStorage
|
||||
emailing *emailing.Mailer
|
||||
idp *identification.IdentificationProvider
|
||||
}
|
||||
|
||||
func NewApplicationHandler(cfg *viper.Viper, svc *services.ServicesHandler, cache cache.CacheHandler, filestorage cache.FileStorage, emailing *emailing.Mailer) (*ApplicationHandler, error) {
|
||||
templates_root := cfg.GetString("templates.root")
|
||||
renderer := renderer.NewRenderer(cfg, templates_root)
|
||||
func NewApplicationHandler(cfg *viper.Viper, svc *services.ServicesHandler, cache cache.CacheHandler, filestorage cache.FileStorage, emailing *emailing.Mailer, idp *identification.IdentificationProvider) (*ApplicationHandler, error) {
|
||||
return &ApplicationHandler{
|
||||
config: cfg,
|
||||
Renderer: renderer,
|
||||
services: svc,
|
||||
cache: cache,
|
||||
filestorage: filestorage,
|
||||
emailing: emailing,
|
||||
idp: idp,
|
||||
}, nil
|
||||
}
|
||||
|
||||
func (h *ApplicationHandler) NotFound(w http.ResponseWriter, r *http.Request) {
|
||||
w.WriteHeader(http.StatusNotFound)
|
||||
}
|
||||
|
||||
func (h *ApplicationHandler) templateFile(file string) string {
|
||||
return h.config.GetString("templates.root") + file
|
||||
240
core/application/auth.go
Normal file
240
core/application/auth.go
Normal file
@@ -0,0 +1,240 @@
|
||||
package application
|
||||
|
||||
import (
|
||||
"context"
|
||||
"crypto/rand"
|
||||
"encoding/base64"
|
||||
"errors"
|
||||
"io"
|
||||
"time"
|
||||
|
||||
"git.coopgo.io/coopgo-platform/groups-management/grpcapi"
|
||||
mobilityaccounts "git.coopgo.io/coopgo-platform/mobility-accounts/grpcapi"
|
||||
ma "git.coopgo.io/coopgo-platform/mobility-accounts/storage"
|
||||
groupsstorage "git.coopgo.io/coopgo-platform/groups-management/storage"
|
||||
"github.com/coreos/go-oidc/v3/oidc"
|
||||
"github.com/rs/zerolog/log"
|
||||
)
|
||||
|
||||
type OAuth2CallbackResult struct {
|
||||
RedirectURL string
|
||||
IDToken string
|
||||
}
|
||||
|
||||
func (h *ApplicationHandler) ProcessOAuth2Callback(code string, redirectSession string) (*OAuth2CallbackResult, error) {
|
||||
oauth2Token, err := h.idp.OAuth2Config.Exchange(context.Background(), code)
|
||||
if err != nil {
|
||||
log.Error().Err(err).Msg("Exchange error")
|
||||
return nil, err
|
||||
}
|
||||
|
||||
// Extract the ID Token from OAuth2 token.
|
||||
rawIDToken, ok := oauth2Token.Extra("id_token").(string)
|
||||
if !ok {
|
||||
log.Error().Msg("Cannot retrieve ID token")
|
||||
return nil, errors.New("cannot retrieve ID token")
|
||||
}
|
||||
|
||||
_, err = h.idp.TokenVerifier.Verify(context.Background(), rawIDToken)
|
||||
if err != nil {
|
||||
log.Error().Err(err).Msg("Not able to verify token")
|
||||
return nil, err
|
||||
}
|
||||
|
||||
redirect := "/app/"
|
||||
if redirectSession != "" {
|
||||
redirect = redirectSession
|
||||
}
|
||||
|
||||
return &OAuth2CallbackResult{
|
||||
RedirectURL: redirect,
|
||||
IDToken: rawIDToken,
|
||||
}, nil
|
||||
}
|
||||
|
||||
type LostPasswordInitResult struct {
|
||||
Success bool
|
||||
}
|
||||
|
||||
func (h *ApplicationHandler) InitiateLostPassword(email string) (*LostPasswordInitResult, error) {
|
||||
account, err := h.services.GRPC.MobilityAccounts.GetAccountUsername(context.TODO(), &mobilityaccounts.GetAccountUsernameRequest{
|
||||
Username: email,
|
||||
Namespace: "parcoursmob",
|
||||
})
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
|
||||
b := make([]byte, 16)
|
||||
if _, err := io.ReadFull(rand.Reader, b); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
key := base64.RawURLEncoding.EncodeToString(b)
|
||||
|
||||
passwordretrieval := map[string]any{
|
||||
"username": email,
|
||||
"account_id": account.Account.Id,
|
||||
"key": key,
|
||||
}
|
||||
|
||||
h.cache.PutWithTTL("retrieve-password/"+key, passwordretrieval, 72*time.Hour)
|
||||
|
||||
if err := h.emailing.Send("auth.retrieve_password", email, passwordretrieval); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
|
||||
return &LostPasswordInitResult{Success: true}, nil
|
||||
}
|
||||
|
||||
type LostPasswordRecoverResult struct {
|
||||
Success bool
|
||||
}
|
||||
|
||||
func (h *ApplicationHandler) RecoverLostPassword(key, newPassword string) (*LostPasswordRecoverResult, error) {
|
||||
recover, err := h.cache.Get("retrieve-password/" + key)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
|
||||
if newPassword == "" {
|
||||
return nil, errors.New("password is empty")
|
||||
}
|
||||
|
||||
_, err = h.services.GRPC.MobilityAccounts.ChangePassword(context.TODO(), &mobilityaccounts.ChangePasswordRequest{
|
||||
Id: recover.(map[string]any)["account_id"].(string),
|
||||
Password: newPassword,
|
||||
})
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
|
||||
err = h.cache.Delete("retrieve-password/" + key)
|
||||
if err != nil {
|
||||
log.Error().Err(err).Msg("Failed to delete password recovery key")
|
||||
}
|
||||
|
||||
return &LostPasswordRecoverResult{Success: true}, nil
|
||||
}
|
||||
|
||||
func (h *ApplicationHandler) GetPasswordRecoveryData(key string) (map[string]any, error) {
|
||||
recover, err := h.cache.Get("retrieve-password/" + key)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
return recover.(map[string]any), nil
|
||||
}
|
||||
|
||||
type OnboardingResult struct {
|
||||
Success bool
|
||||
}
|
||||
|
||||
func (h *ApplicationHandler) CompleteOnboarding(key, password, firstName, lastName string) (*OnboardingResult, error) {
|
||||
onboarding, err := h.cache.Get("onboarding/" + key)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
|
||||
onboardingmap := onboarding.(map[string]any)
|
||||
|
||||
if password == "" {
|
||||
return nil, errors.New("password is empty")
|
||||
}
|
||||
|
||||
groups := []string{
|
||||
onboardingmap["group"].(string),
|
||||
}
|
||||
|
||||
if onboardingmap["admin"].(bool) {
|
||||
groups = append(groups, onboardingmap["group"].(string)+":admin")
|
||||
}
|
||||
|
||||
display_name := firstName + " " + lastName
|
||||
account := &ma.Account{
|
||||
Authentication: ma.AccountAuth{
|
||||
Local: ma.LocalAuth{
|
||||
Username: onboardingmap["username"].(string),
|
||||
Password: password,
|
||||
},
|
||||
},
|
||||
Namespace: "parcoursmob",
|
||||
Data: map[string]any{
|
||||
"display_name": display_name,
|
||||
"first_name": firstName,
|
||||
"last_name": lastName,
|
||||
"email": onboardingmap["username"],
|
||||
"groups": groups,
|
||||
},
|
||||
}
|
||||
|
||||
acc, err := mobilityaccounts.AccountFromStorageType(account)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
|
||||
request := &mobilityaccounts.RegisterRequest{
|
||||
Account: acc,
|
||||
}
|
||||
|
||||
_, err = h.services.GRPC.MobilityAccounts.Register(context.TODO(), request)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
|
||||
err = h.cache.Delete("onboarding/" + key)
|
||||
if err != nil {
|
||||
log.Error().Err(err).Msg("Failed to delete onboarding key")
|
||||
}
|
||||
|
||||
return &OnboardingResult{Success: true}, nil
|
||||
}
|
||||
|
||||
func (h *ApplicationHandler) GetOnboardingData(key string) (map[string]any, error) {
|
||||
onboarding, err := h.cache.Get("onboarding/" + key)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
return onboarding.(map[string]any), nil
|
||||
}
|
||||
|
||||
type UserGroupsResult struct {
|
||||
Groups []groupsstorage.Group
|
||||
}
|
||||
|
||||
func (h *ApplicationHandler) GetUserGroups(idtoken *oidc.IDToken) (*UserGroupsResult, error) {
|
||||
var claims map[string]any
|
||||
err := idtoken.Claims(&claims)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
|
||||
g := claims["groups"]
|
||||
groups_interface, ok := g.([]any)
|
||||
if !ok {
|
||||
return nil, errors.New("invalid groups format")
|
||||
}
|
||||
|
||||
groups := []string{}
|
||||
for _, v := range groups_interface {
|
||||
groups = append(groups, v.(string))
|
||||
}
|
||||
|
||||
request := &grpcapi.GetGroupsBatchRequest{
|
||||
Groupids: groups,
|
||||
}
|
||||
|
||||
resp, err := h.services.GRPC.GroupsManagement.GetGroupsBatch(context.TODO(), request)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
|
||||
var groupsresponse []groupsstorage.Group
|
||||
for _, group := range resp.Groups {
|
||||
if group.Namespace != "parcoursmob_organizations" {
|
||||
continue
|
||||
}
|
||||
g := group.ToStorageType()
|
||||
groupsresponse = append(groupsresponse, g)
|
||||
}
|
||||
|
||||
return &UserGroupsResult{Groups: groupsresponse}, nil
|
||||
}
|
||||
929
core/application/beneficiaries.go
Normal file
929
core/application/beneficiaries.go
Normal file
@@ -0,0 +1,929 @@
|
||||
package application
|
||||
|
||||
import (
|
||||
"bytes"
|
||||
"context"
|
||||
"encoding/json"
|
||||
"errors"
|
||||
"fmt"
|
||||
"image/png"
|
||||
"io"
|
||||
"net/http"
|
||||
"sort"
|
||||
"strings"
|
||||
"time"
|
||||
|
||||
formvalidators "git.coopgo.io/coopgo-apps/parcoursmob/core/utils/form-validators"
|
||||
"git.coopgo.io/coopgo-apps/parcoursmob/core/utils/identification"
|
||||
profilepictures "git.coopgo.io/coopgo-apps/parcoursmob/core/utils/profile-pictures"
|
||||
"git.coopgo.io/coopgo-apps/parcoursmob/core/utils/sorting"
|
||||
filestorage "git.coopgo.io/coopgo-apps/parcoursmob/core/utils/storage"
|
||||
agenda "git.coopgo.io/coopgo-platform/agenda/grpcapi"
|
||||
agendastorage "git.coopgo.io/coopgo-platform/agenda/storage"
|
||||
"git.coopgo.io/coopgo-platform/carpool-service/servers/grpc/proto"
|
||||
fleets "git.coopgo.io/coopgo-platform/fleets/grpcapi"
|
||||
fleetsstorage "git.coopgo.io/coopgo-platform/fleets/storage"
|
||||
groupsmanagement "git.coopgo.io/coopgo-platform/groups-management/grpcapi"
|
||||
"git.coopgo.io/coopgo-platform/groups-management/storage"
|
||||
mobilityaccounts "git.coopgo.io/coopgo-platform/mobility-accounts/grpcapi"
|
||||
mobilityaccountsstorage "git.coopgo.io/coopgo-platform/mobility-accounts/storage"
|
||||
"git.coopgo.io/coopgo-platform/solidarity-transport/servers/grpc/proto/gen"
|
||||
solidaritytransformers "git.coopgo.io/coopgo-platform/solidarity-transport/servers/grpc/transformers"
|
||||
solidaritytypes "git.coopgo.io/coopgo-platform/solidarity-transport/types"
|
||||
"github.com/google/uuid"
|
||||
"github.com/rs/zerolog/log"
|
||||
"google.golang.org/protobuf/types/known/structpb"
|
||||
"google.golang.org/protobuf/types/known/timestamppb"
|
||||
)
|
||||
|
||||
type BeneficiariesResult struct {
|
||||
Accounts []mobilityaccountsstorage.Account
|
||||
CacheID string
|
||||
}
|
||||
|
||||
func (h *ApplicationHandler) GetBeneficiaries(ctx context.Context, searchFilter string, archivedFilter bool) (*BeneficiariesResult, error) {
|
||||
accounts, err := h.getBeneficiariesWithFilters(ctx, searchFilter, archivedFilter)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
|
||||
sort.Sort(sorting.BeneficiariesByName(accounts))
|
||||
|
||||
cacheID := uuid.NewString()
|
||||
h.cache.PutWithTTL(cacheID, accounts, 1*time.Hour)
|
||||
|
||||
return &BeneficiariesResult{
|
||||
Accounts: accounts,
|
||||
CacheID: cacheID,
|
||||
}, nil
|
||||
}
|
||||
|
||||
func (h *ApplicationHandler) CreateBeneficiary(ctx context.Context, firstName, lastName, email string, birthdate *time.Time, phoneNumber, fileNumber string, address any, gender string, otherProperties any) (string, error) {
|
||||
// Get current group
|
||||
g := ctx.Value(identification.GroupKey)
|
||||
if g == nil {
|
||||
return "", fmt.Errorf("no group found in context")
|
||||
}
|
||||
group := g.(storage.Group)
|
||||
|
||||
// Create data map for the beneficiary
|
||||
dataMap := map[string]any{
|
||||
"first_name": firstName,
|
||||
"last_name": lastName,
|
||||
"email": email,
|
||||
"phone_number": phoneNumber,
|
||||
"file_number": fileNumber,
|
||||
"gender": gender,
|
||||
}
|
||||
|
||||
// Convert birthdate to string format for structpb compatibility
|
||||
if birthdate != nil {
|
||||
dataMap["birthdate"] = birthdate.Format("2006-01-02")
|
||||
}
|
||||
|
||||
if address != nil {
|
||||
dataMap["address"] = address
|
||||
}
|
||||
if otherProperties != nil {
|
||||
dataMap["other_properties"] = otherProperties
|
||||
}
|
||||
|
||||
data, err := structpb.NewValue(dataMap)
|
||||
if err != nil {
|
||||
return "", err
|
||||
}
|
||||
|
||||
request := &mobilityaccounts.RegisterRequest{
|
||||
Account: &mobilityaccounts.Account{
|
||||
Namespace: "parcoursmob_beneficiaries",
|
||||
Data: data.GetStructValue(),
|
||||
},
|
||||
}
|
||||
|
||||
resp, err := h.services.GRPC.MobilityAccounts.Register(ctx, request)
|
||||
if err != nil {
|
||||
return "", err
|
||||
}
|
||||
|
||||
subscribe := &groupsmanagement.SubscribeRequest{
|
||||
Groupid: group.ID,
|
||||
Memberid: resp.Account.Id,
|
||||
}
|
||||
|
||||
_, err = h.services.GRPC.GroupsManagement.Subscribe(ctx, subscribe)
|
||||
if err != nil {
|
||||
return "", err
|
||||
}
|
||||
|
||||
return resp.Account.Id, nil
|
||||
}
|
||||
|
||||
type BeneficiaryDataResult struct {
|
||||
Account mobilityaccountsstorage.Account
|
||||
Bookings []fleetsstorage.Booking
|
||||
Organizations []any
|
||||
Documents []filestorage.FileInfo
|
||||
EventsList []Event_Beneficiary
|
||||
SolidarityTransportStats map[string]int64
|
||||
SolidarityTransportBookings []*solidaritytypes.Booking
|
||||
SolidarityDriversMap map[string]mobilityaccountsstorage.Account
|
||||
OrganizedCarpoolStats map[string]int64
|
||||
OrganizedCarpoolBookings []*proto.CarpoolServiceBooking
|
||||
OrganizedCarpoolDriversMap map[string]mobilityaccountsstorage.Account
|
||||
WalletBalance float64
|
||||
}
|
||||
|
||||
func (h *ApplicationHandler) GetBeneficiaryData(ctx context.Context, beneficiaryID string) (*BeneficiaryDataResult, error) {
|
||||
// Get beneficiary account
|
||||
request := &mobilityaccounts.GetAccountRequest{
|
||||
Id: beneficiaryID,
|
||||
}
|
||||
|
||||
resp, err := h.services.GRPC.MobilityAccounts.GetAccount(ctx, request)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
|
||||
// Security check: ensure this is actually a beneficiary account
|
||||
if resp.Account.Namespace != "parcoursmob_beneficiaries" {
|
||||
return nil, fmt.Errorf("account %s is not a beneficiary (namespace: %s)", beneficiaryID, resp.Account.Namespace)
|
||||
}
|
||||
|
||||
account := resp.Account.ToStorageType()
|
||||
|
||||
// Get documents
|
||||
documents := h.filestorage.List(filestorage.PREFIX_BENEFICIARIES + "/" + beneficiaryID)
|
||||
|
||||
// Get events subscriptions
|
||||
subscriptionRequest := &agenda.GetSubscriptionByUserRequest{
|
||||
Subscriber: beneficiaryID,
|
||||
}
|
||||
|
||||
subscriptionResp, err := h.services.GRPC.Agenda.GetSubscriptionByUser(ctx, subscriptionRequest)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
|
||||
events := []agendastorage.Event{}
|
||||
currentTime := time.Now().Truncate(24 * time.Hour)
|
||||
|
||||
for _, e := range subscriptionResp.Subscription {
|
||||
eventRequest := &agenda.GetEventRequest{
|
||||
Id: e.Eventid,
|
||||
}
|
||||
eventResp, err := h.services.GRPC.Agenda.GetEvent(ctx, eventRequest)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
events = append(events, eventResp.Event.ToStorageType())
|
||||
}
|
||||
|
||||
sort.Sort(sorting.EventsByStartdate(events))
|
||||
|
||||
// Get bookings
|
||||
bookingsRequest := &fleets.GetDriverBookingsRequest{
|
||||
Driver: beneficiaryID,
|
||||
}
|
||||
bookingsResp, err := h.services.GRPC.Fleets.GetDriverBookings(ctx, bookingsRequest)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
|
||||
bookings := []fleetsstorage.Booking{}
|
||||
for _, b := range bookingsResp.Bookings {
|
||||
bookings = append(bookings, b.ToStorageType())
|
||||
}
|
||||
|
||||
// Build events list
|
||||
var eventsList []Event_Beneficiary
|
||||
var statusEvent int
|
||||
|
||||
for _, e := range events {
|
||||
if e.Startdate.After(currentTime) {
|
||||
statusEvent = 1
|
||||
} else if e.Startdate.Before(currentTime) && e.Enddate.After(currentTime) || e.Enddate.Equal(currentTime) {
|
||||
statusEvent = 2
|
||||
} else {
|
||||
statusEvent = 3
|
||||
}
|
||||
|
||||
event := Event{
|
||||
NameVal: e.Name,
|
||||
DateVal: e.Startdate,
|
||||
DateEndVal: e.Enddate,
|
||||
TypeVal: e.Type,
|
||||
IDVal: e.ID,
|
||||
DbVal: "/app/agenda/",
|
||||
IconSet: "calendar",
|
||||
StatusVal: statusEvent,
|
||||
}
|
||||
|
||||
eventsList = append(eventsList, event)
|
||||
}
|
||||
|
||||
// Add vehicle bookings to events list
|
||||
var statusBooking int
|
||||
for _, b := range bookings {
|
||||
if b.Enddate.After(currentTime) || b.Enddate.Equal(currentTime) {
|
||||
getVehicleRequest := &fleets.GetVehicleRequest{
|
||||
Vehicleid: b.Vehicleid,
|
||||
}
|
||||
|
||||
getVehicleResp, err := h.services.GRPC.Fleets.GetVehicle(ctx, getVehicleRequest)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
|
||||
if b.Startdate.After(currentTime) {
|
||||
statusBooking = 1
|
||||
} else if b.Startdate.Before(currentTime) && b.Enddate.After(currentTime) || b.Enddate.Equal(currentTime) {
|
||||
statusBooking = 2
|
||||
} else {
|
||||
statusBooking = 3
|
||||
}
|
||||
|
||||
event := Event{
|
||||
NameVal: getVehicleResp.Vehicle.ToStorageType().Data["name"].(string),
|
||||
DateVal: b.Startdate,
|
||||
DateEndVal: b.Enddate,
|
||||
TypeVal: "Réservation de véhicule",
|
||||
IDVal: b.ID,
|
||||
DbVal: "/app/vehicles-management/bookings/",
|
||||
IconSet: "vehicle",
|
||||
StatusVal: statusBooking,
|
||||
}
|
||||
|
||||
eventsList = append(eventsList, event)
|
||||
}
|
||||
}
|
||||
|
||||
// Get solidarity transport bookings (all statuses for display)
|
||||
solidarityResp, err := h.services.GRPC.SolidarityTransport.GetSolidarityTransportBookings(ctx, &gen.GetSolidarityTransportBookingsRequest{
|
||||
Passengerid: beneficiaryID,
|
||||
StartDate: timestamppb.New(time.Now().Add(-365 * 24 * time.Hour)),
|
||||
EndDate: timestamppb.New(time.Now().Add(365 * 24 * time.Hour)),
|
||||
})
|
||||
|
||||
protoBookings := []*gen.SolidarityTransportBooking{}
|
||||
if err == nil {
|
||||
protoBookings = solidarityResp.Bookings
|
||||
} else {
|
||||
log.Error().Err(err).Msg("error retrieving solidarity transport bookings for beneficiary")
|
||||
}
|
||||
|
||||
// Convert proto bookings to types with geojson.Feature
|
||||
solidarityTransportBookings := []*solidaritytypes.Booking{}
|
||||
for _, protoBooking := range protoBookings {
|
||||
booking, err := solidaritytransformers.BookingProtoToType(protoBooking)
|
||||
if err != nil {
|
||||
log.Error().Err(err).Msg("error converting booking proto to type")
|
||||
continue
|
||||
}
|
||||
solidarityTransportBookings = append(solidarityTransportBookings, booking)
|
||||
}
|
||||
|
||||
// Don't filter out replaced bookings from beneficiary profile - show all bookings
|
||||
|
||||
// Collect unique driver IDs
|
||||
driverIDs := []string{}
|
||||
driverIDsMap := make(map[string]bool)
|
||||
for _, booking := range solidarityTransportBookings {
|
||||
if booking.DriverId != "" {
|
||||
if !driverIDsMap[booking.DriverId] {
|
||||
driverIDs = append(driverIDs, booking.DriverId)
|
||||
driverIDsMap[booking.DriverId] = true
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// Get drivers in batch
|
||||
driversMap := make(map[string]mobilityaccountsstorage.Account)
|
||||
if len(driverIDs) > 0 {
|
||||
driversResp, err := h.services.GRPC.MobilityAccounts.GetAccountsBatch(ctx, &mobilityaccounts.GetAccountsBatchRequest{
|
||||
Accountids: driverIDs,
|
||||
})
|
||||
if err == nil {
|
||||
for _, account := range driversResp.Accounts {
|
||||
a := account.ToStorageType()
|
||||
driversMap[a.ID] = a
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// Calculate stats only for validated bookings
|
||||
solidarityTransportStats := map[string]int64{
|
||||
"count": 0,
|
||||
"km": 0,
|
||||
}
|
||||
|
||||
for _, b := range solidarityTransportBookings {
|
||||
if b.Status == "VALIDATED" {
|
||||
solidarityTransportStats["count"] = solidarityTransportStats["count"] + 1
|
||||
if b.Journey != nil {
|
||||
solidarityTransportStats["km"] = solidarityTransportStats["km"] + b.Journey.PassengerDistance
|
||||
}
|
||||
|
||||
// Add to events list
|
||||
event := Event{
|
||||
NameVal: fmt.Sprintf("%s (%d km)", b.Journey.PassengerDrop.Properties.MustString("label", ""), b.Journey.PassengerDistance),
|
||||
DateVal: b.Journey.PassengerPickupDate,
|
||||
DateEndVal: b.Journey.PassengerPickupDate,
|
||||
TypeVal: "Transport solidaire",
|
||||
IDVal: b.Id,
|
||||
DbVal: "/app/solidarity-transport/bookings/",
|
||||
IconSet: "vehicle",
|
||||
StatusVal: 1,
|
||||
}
|
||||
|
||||
eventsList = append(eventsList, event)
|
||||
}
|
||||
}
|
||||
|
||||
// Get organized carpool bookings
|
||||
carpoolBookingsResp, err := h.services.GRPC.CarpoolService.GetUserBookings(ctx, &proto.GetUserBookingsRequest{
|
||||
UserId: beneficiaryID,
|
||||
})
|
||||
|
||||
organizedCarpoolBookings := []*proto.CarpoolServiceBooking{}
|
||||
if err == nil {
|
||||
organizedCarpoolBookings = carpoolBookingsResp.Bookings
|
||||
} else {
|
||||
log.Error().Err(err).Msg("error retrieving organized carpool bookings for beneficiary")
|
||||
}
|
||||
|
||||
// Collect unique driver IDs from organized carpool bookings
|
||||
carpoolDriverIDs := []string{}
|
||||
carpoolDriverIDsMap := make(map[string]bool)
|
||||
for _, booking := range organizedCarpoolBookings {
|
||||
if booking.Driver != nil && booking.Driver.Id != "" {
|
||||
if !carpoolDriverIDsMap[booking.Driver.Id] {
|
||||
carpoolDriverIDs = append(carpoolDriverIDs, booking.Driver.Id)
|
||||
carpoolDriverIDsMap[booking.Driver.Id] = true
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// Get organized carpool drivers in batch
|
||||
organizedCarpoolDriversMap := make(map[string]mobilityaccountsstorage.Account)
|
||||
if len(carpoolDriverIDs) > 0 {
|
||||
carpoolDriversResp, err := h.services.GRPC.MobilityAccounts.GetAccountsBatch(ctx, &mobilityaccounts.GetAccountsBatchRequest{
|
||||
Accountids: carpoolDriverIDs,
|
||||
})
|
||||
if err == nil {
|
||||
for _, account := range carpoolDriversResp.Accounts {
|
||||
a := account.ToStorageType()
|
||||
organizedCarpoolDriversMap[a.ID] = a
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// Calculate organized carpool stats (only confirmed bookings)
|
||||
organizedCarpoolStats := map[string]int64{
|
||||
"count": 0,
|
||||
"km": 0,
|
||||
}
|
||||
|
||||
for _, cb := range organizedCarpoolBookings {
|
||||
if cb.Status == proto.CarpoolServiceBookingStatus_CONFIRMED {
|
||||
organizedCarpoolStats["count"]++
|
||||
if cb.Distance != nil {
|
||||
organizedCarpoolStats["km"] += *cb.Distance
|
||||
}
|
||||
|
||||
// Build journey name from drop address and distance for events
|
||||
journeyName := "Covoiturage"
|
||||
if cb.PassengerDropAddress != nil {
|
||||
if cb.Distance != nil {
|
||||
journeyName = fmt.Sprintf("%s (%d km)", *cb.PassengerDropAddress, *cb.Distance)
|
||||
} else {
|
||||
journeyName = *cb.PassengerDropAddress
|
||||
}
|
||||
}
|
||||
|
||||
// Get departure date
|
||||
departureDate := time.Now()
|
||||
if cb.PassengerPickupDate != nil {
|
||||
departureDate = cb.PassengerPickupDate.AsTime()
|
||||
}
|
||||
|
||||
event := Event{
|
||||
NameVal: journeyName,
|
||||
DateVal: departureDate,
|
||||
DateEndVal: departureDate,
|
||||
TypeVal: "Covoiturage solidaire",
|
||||
IDVal: cb.Id,
|
||||
DbVal: "/app/organized-carpool/bookings/",
|
||||
IconSet: "vehicle",
|
||||
StatusVal: 1,
|
||||
}
|
||||
|
||||
eventsList = append(eventsList, event)
|
||||
}
|
||||
}
|
||||
|
||||
sortByDate(eventsList)
|
||||
|
||||
// Get organizations
|
||||
groupsRequest := &groupsmanagement.GetGroupsRequest{
|
||||
Namespaces: []string{"parcoursmob_organizations"},
|
||||
Member: beneficiaryID,
|
||||
}
|
||||
|
||||
groupsResp, err := h.services.GRPC.GroupsManagement.GetGroups(ctx, groupsRequest)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
|
||||
organizations := []any{}
|
||||
for _, o := range groupsResp.Groups {
|
||||
organizations = append(organizations, o.ToStorageType())
|
||||
}
|
||||
|
||||
// Calculate wallet balance
|
||||
walletBalance := h.calculateWalletBalance(account)
|
||||
|
||||
return &BeneficiaryDataResult{
|
||||
Account: account,
|
||||
Bookings: bookings,
|
||||
Organizations: organizations,
|
||||
Documents: documents,
|
||||
EventsList: eventsList,
|
||||
SolidarityTransportStats: solidarityTransportStats,
|
||||
SolidarityTransportBookings: solidarityTransportBookings,
|
||||
SolidarityDriversMap: driversMap,
|
||||
OrganizedCarpoolStats: organizedCarpoolStats,
|
||||
OrganizedCarpoolBookings: organizedCarpoolBookings,
|
||||
OrganizedCarpoolDriversMap: organizedCarpoolDriversMap,
|
||||
WalletBalance: walletBalance,
|
||||
}, nil
|
||||
}
|
||||
|
||||
type BeneficiaryResult struct {
|
||||
Account mobilityaccountsstorage.Account
|
||||
}
|
||||
|
||||
func (h *ApplicationHandler) GetBeneficiary(ctx context.Context, beneficiaryID string) (*BeneficiaryResult, error) {
|
||||
request := &mobilityaccounts.GetAccountRequest{
|
||||
Id: beneficiaryID,
|
||||
}
|
||||
|
||||
resp, err := h.services.GRPC.MobilityAccounts.GetAccount(ctx, request)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
|
||||
// Security check: ensure this is actually a beneficiary account
|
||||
if resp.Account.Namespace != "parcoursmob_beneficiaries" {
|
||||
return nil, fmt.Errorf("account %s is not a beneficiary (namespace: %s)", beneficiaryID, resp.Account.Namespace)
|
||||
}
|
||||
|
||||
return &BeneficiaryResult{
|
||||
Account: resp.Account.ToStorageType(),
|
||||
}, nil
|
||||
}
|
||||
|
||||
func (h *ApplicationHandler) UpdateBeneficiary(ctx context.Context, beneficiaryID, firstName, lastName, email string, birthdate *time.Time, phoneNumber, fileNumber string, address any, gender string, otherProperties any) (string, error) {
|
||||
// Security check: verify the account exists and is a beneficiary
|
||||
getRequest := &mobilityaccounts.GetAccountRequest{
|
||||
Id: beneficiaryID,
|
||||
}
|
||||
getResp, err := h.services.GRPC.MobilityAccounts.GetAccount(ctx, getRequest)
|
||||
if err != nil {
|
||||
return "", err
|
||||
}
|
||||
if getResp.Account.Namespace != "parcoursmob_beneficiaries" {
|
||||
return "", fmt.Errorf("account %s is not a beneficiary (namespace: %s)", beneficiaryID, getResp.Account.Namespace)
|
||||
}
|
||||
|
||||
// Create data map for the beneficiary
|
||||
dataMap := map[string]any{
|
||||
"first_name": firstName,
|
||||
"last_name": lastName,
|
||||
"email": email,
|
||||
"phone_number": phoneNumber,
|
||||
"file_number": fileNumber,
|
||||
"gender": gender,
|
||||
}
|
||||
|
||||
// Handle birthdate conversion for protobuf compatibility
|
||||
if birthdate != nil {
|
||||
dataMap["birthdate"] = birthdate.Format(time.RFC3339)
|
||||
}
|
||||
|
||||
if address != nil {
|
||||
dataMap["address"] = address
|
||||
}
|
||||
if otherProperties != nil {
|
||||
dataMap["other_properties"] = otherProperties
|
||||
}
|
||||
|
||||
data, err := structpb.NewValue(dataMap)
|
||||
if err != nil {
|
||||
return "", err
|
||||
}
|
||||
|
||||
request := &mobilityaccounts.UpdateDataRequest{
|
||||
Account: &mobilityaccounts.Account{
|
||||
Id: beneficiaryID,
|
||||
Namespace: "parcoursmob_beneficiaries",
|
||||
Data: data.GetStructValue(),
|
||||
},
|
||||
}
|
||||
|
||||
resp, err := h.services.GRPC.MobilityAccounts.UpdateData(ctx, request)
|
||||
if err != nil {
|
||||
return "", err
|
||||
}
|
||||
|
||||
return resp.Account.Id, nil
|
||||
}
|
||||
|
||||
func (h *ApplicationHandler) ArchiveBeneficiary(ctx context.Context, beneficiaryID string) error {
|
||||
// Security check: verify the account exists and is a beneficiary
|
||||
getRequest := &mobilityaccounts.GetAccountRequest{
|
||||
Id: beneficiaryID,
|
||||
}
|
||||
getResp, err := h.services.GRPC.MobilityAccounts.GetAccount(ctx, getRequest)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
if getResp.Account.Namespace != "parcoursmob_beneficiaries" {
|
||||
return fmt.Errorf("account %s is not a beneficiary (namespace: %s)", beneficiaryID, getResp.Account.Namespace)
|
||||
}
|
||||
|
||||
data, err := structpb.NewValue(map[string]any{
|
||||
"archived": true,
|
||||
})
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
request := &mobilityaccounts.UpdateDataRequest{
|
||||
Account: &mobilityaccounts.Account{
|
||||
Id: beneficiaryID,
|
||||
Namespace: "parcoursmob_beneficiaries",
|
||||
Data: data.GetStructValue(),
|
||||
},
|
||||
}
|
||||
|
||||
_, err = h.services.GRPC.MobilityAccounts.UpdateData(ctx, request)
|
||||
return err
|
||||
}
|
||||
|
||||
func (h *ApplicationHandler) UnarchiveBeneficiary(ctx context.Context, beneficiaryID string) error {
|
||||
// Security check: verify the account exists and is a beneficiary
|
||||
getRequest := &mobilityaccounts.GetAccountRequest{
|
||||
Id: beneficiaryID,
|
||||
}
|
||||
getResp, err := h.services.GRPC.MobilityAccounts.GetAccount(ctx, getRequest)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
if getResp.Account.Namespace != "parcoursmob_beneficiaries" {
|
||||
return fmt.Errorf("account %s is not a beneficiary (namespace: %s)", beneficiaryID, getResp.Account.Namespace)
|
||||
}
|
||||
|
||||
data, err := structpb.NewValue(map[string]any{
|
||||
"archived": false,
|
||||
})
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
request := &mobilityaccounts.UpdateDataRequest{
|
||||
Account: &mobilityaccounts.Account{
|
||||
Id: beneficiaryID,
|
||||
Namespace: "parcoursmob_beneficiaries",
|
||||
Data: data.GetStructValue(),
|
||||
},
|
||||
}
|
||||
|
||||
_, err = h.services.GRPC.MobilityAccounts.UpdateData(ctx, request)
|
||||
return err
|
||||
}
|
||||
|
||||
func (h *ApplicationHandler) GetBeneficiaryPicture(ctx context.Context, beneficiaryID string) ([]byte, string, error) {
|
||||
request := &mobilityaccounts.GetAccountRequest{
|
||||
Id: beneficiaryID,
|
||||
}
|
||||
|
||||
resp, err := h.services.GRPC.MobilityAccounts.GetAccount(ctx, request)
|
||||
if err != nil {
|
||||
return nil, "", err
|
||||
}
|
||||
|
||||
// Security check: ensure this is actually a beneficiary account
|
||||
// if resp.Account.Namespace != "parcoursmob_beneficiaries" {
|
||||
// return nil, "", fmt.Errorf("account %s is not a beneficiary (namespace: %s)", beneficiaryID, resp.Account.Namespace)
|
||||
// }
|
||||
|
||||
account := resp.Account.ToStorageType()
|
||||
|
||||
firstName, ok := account.Data["first_name"].(string)
|
||||
if !ok || firstName == "" {
|
||||
firstName = "U"
|
||||
}
|
||||
lastName, ok := account.Data["last_name"].(string)
|
||||
if !ok || lastName == "" {
|
||||
lastName = "U"
|
||||
}
|
||||
|
||||
initials := strings.ToUpper(string(firstName[0]) + string(lastName[0]))
|
||||
picture := profilepictures.DefaultProfilePicture(initials)
|
||||
|
||||
buffer := new(bytes.Buffer)
|
||||
if err := png.Encode(buffer, picture); err != nil {
|
||||
return nil, "", err
|
||||
}
|
||||
|
||||
return buffer.Bytes(), "image/png", nil
|
||||
}
|
||||
|
||||
func (h *ApplicationHandler) AddBeneficiaryDocument(ctx context.Context, beneficiaryID string, file io.Reader, filename string, fileSize int64, documentType, documentName string) error {
|
||||
// Security check: verify the account exists and is a beneficiary
|
||||
getRequest := &mobilityaccounts.GetAccountRequest{
|
||||
Id: beneficiaryID,
|
||||
}
|
||||
getResp, err := h.services.GRPC.MobilityAccounts.GetAccount(ctx, getRequest)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
if getResp.Account.Namespace != "parcoursmob_beneficiaries" {
|
||||
return fmt.Errorf("account %s is not a beneficiary (namespace: %s)", beneficiaryID, getResp.Account.Namespace)
|
||||
}
|
||||
|
||||
fileid := uuid.NewString()
|
||||
|
||||
metadata := map[string]string{
|
||||
"type": documentType,
|
||||
"name": documentName,
|
||||
}
|
||||
|
||||
if err := h.filestorage.Put(file, filestorage.PREFIX_BENEFICIARIES, fmt.Sprintf("%s/%s_%s", beneficiaryID, fileid, filename), fileSize, metadata); err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
return nil
|
||||
}
|
||||
|
||||
func (h *ApplicationHandler) GetBeneficiaryDocument(ctx context.Context, beneficiaryID, document string) (io.Reader, *filestorage.FileInfo, error) {
|
||||
// Security check: verify the account exists and is a beneficiary
|
||||
getRequest := &mobilityaccounts.GetAccountRequest{
|
||||
Id: beneficiaryID,
|
||||
}
|
||||
getResp, err := h.services.GRPC.MobilityAccounts.GetAccount(ctx, getRequest)
|
||||
if err != nil {
|
||||
return nil, nil, err
|
||||
}
|
||||
if getResp.Account.Namespace != "parcoursmob_beneficiaries" {
|
||||
return nil, nil, fmt.Errorf("account %s is not a beneficiary (namespace: %s)", beneficiaryID, getResp.Account.Namespace)
|
||||
}
|
||||
|
||||
file, info, err := h.filestorage.Get(filestorage.PREFIX_BENEFICIARIES, fmt.Sprintf("%s/%s", beneficiaryID, document))
|
||||
if err != nil {
|
||||
return nil, nil, err
|
||||
}
|
||||
|
||||
return file, info, nil
|
||||
}
|
||||
|
||||
func (h *ApplicationHandler) DeleteBeneficiaryDocument(ctx context.Context, beneficiaryID, document string) error {
|
||||
return h.DeleteDocument(ctx, BeneficiaryDocumentConfig, beneficiaryID, document)
|
||||
}
|
||||
|
||||
func (h *ApplicationHandler) getBeneficiariesWithFilters(ctx context.Context, searchFilter string, archivedFilter bool) ([]mobilityaccountsstorage.Account, error) {
|
||||
accounts := []mobilityaccountsstorage.Account{}
|
||||
g := ctx.Value(identification.GroupKey)
|
||||
if g == nil {
|
||||
return accounts, errors.New("no group provided")
|
||||
}
|
||||
|
||||
group := g.(storage.Group)
|
||||
|
||||
request := &mobilityaccounts.GetAccountsBatchRequest{
|
||||
Accountids: group.Members,
|
||||
}
|
||||
|
||||
resp, err := h.services.GRPC.MobilityAccounts.GetAccountsBatch(ctx, request)
|
||||
if err != nil {
|
||||
log.Error().Err(err).Msg("issue in mobilityaccounts call")
|
||||
return accounts, err
|
||||
}
|
||||
|
||||
for _, account := range resp.Accounts {
|
||||
if h.filterAccount(account, searchFilter, archivedFilter) {
|
||||
a := account.ToStorageType()
|
||||
accounts = append(accounts, a)
|
||||
}
|
||||
}
|
||||
|
||||
return accounts, err
|
||||
}
|
||||
|
||||
func (h *ApplicationHandler) filterAccount(a *mobilityaccounts.Account, searchFilter string, archivedFilter bool) bool {
|
||||
// Search filter
|
||||
if searchFilter != "" {
|
||||
name := a.Data.AsMap()["first_name"].(string) + " " + a.Data.AsMap()["last_name"].(string)
|
||||
if !strings.Contains(strings.ToLower(name), strings.ToLower(searchFilter)) {
|
||||
return false
|
||||
}
|
||||
}
|
||||
|
||||
// Archived filter
|
||||
if archivedFilter {
|
||||
if archived, ok := a.Data.AsMap()["archived"].(bool); ok && archived {
|
||||
return true
|
||||
}
|
||||
return false
|
||||
} else {
|
||||
if archived, ok := a.Data.AsMap()["archived"].(bool); ok && archived {
|
||||
return false
|
||||
}
|
||||
}
|
||||
|
||||
return true
|
||||
}
|
||||
|
||||
type Event_Beneficiary interface {
|
||||
Name() string
|
||||
Date() time.Time
|
||||
DateEnd() time.Time
|
||||
Type() string
|
||||
Db() string
|
||||
ID() string
|
||||
Icons() string
|
||||
Status() int
|
||||
}
|
||||
|
||||
type Event struct {
|
||||
IDVal string
|
||||
NameVal string
|
||||
DateVal time.Time
|
||||
DateEndVal time.Time
|
||||
TypeVal string
|
||||
DbVal string
|
||||
Deleted bool
|
||||
IconSet string
|
||||
StatusVal int
|
||||
}
|
||||
|
||||
func (e Event) Name() string {
|
||||
return e.NameVal
|
||||
}
|
||||
|
||||
func (e Event) Date() time.Time {
|
||||
return e.DateVal
|
||||
}
|
||||
|
||||
func (e Event) DateEnd() time.Time {
|
||||
return e.DateEndVal
|
||||
}
|
||||
|
||||
func (e Event) Type() string {
|
||||
return e.TypeVal
|
||||
}
|
||||
|
||||
func (e Event) ID() string {
|
||||
return e.IDVal
|
||||
}
|
||||
|
||||
func (e Event) Db() string {
|
||||
return e.DbVal
|
||||
}
|
||||
|
||||
func (e Event) Icons() string {
|
||||
return e.IconSet
|
||||
}
|
||||
|
||||
func (e Event) Status() int {
|
||||
return e.StatusVal
|
||||
}
|
||||
|
||||
func sortByDate(events []Event_Beneficiary) {
|
||||
sort.Slice(events, func(i, j int) bool {
|
||||
return events[i].Date().After(events[j].Date())
|
||||
})
|
||||
}
|
||||
|
||||
// Utility functions needed by other modules
|
||||
func filterAccount(r *http.Request, a *mobilityaccounts.Account) bool {
|
||||
searchFilter, ok := r.URL.Query()["search"]
|
||||
|
||||
if ok && len(searchFilter[0]) > 0 {
|
||||
name := a.Data.AsMap()["first_name"].(string) + " " + a.Data.AsMap()["last_name"].(string)
|
||||
if !strings.Contains(strings.ToLower(name), strings.ToLower(searchFilter[0])) {
|
||||
return false
|
||||
}
|
||||
}
|
||||
|
||||
archivedFilter, ok := r.URL.Query()["archived"]
|
||||
if ok && archivedFilter[0] == "true" {
|
||||
if archived, ok := a.Data.AsMap()["archived"].(bool); ok && archived {
|
||||
return true
|
||||
}
|
||||
return false
|
||||
} else {
|
||||
if archived, ok := a.Data.AsMap()["archived"].(bool); ok && archived {
|
||||
return false
|
||||
}
|
||||
}
|
||||
|
||||
return true
|
||||
}
|
||||
|
||||
func (h *ApplicationHandler) beneficiaries(r *http.Request) ([]mobilityaccountsstorage.Account, error) {
|
||||
accounts := []mobilityaccountsstorage.Account{}
|
||||
g := r.Context().Value(identification.GroupKey)
|
||||
if g == nil {
|
||||
return accounts, errors.New("no group provided")
|
||||
}
|
||||
|
||||
group := g.(storage.Group)
|
||||
|
||||
request := &mobilityaccounts.GetAccountsBatchRequest{
|
||||
Accountids: group.Members,
|
||||
}
|
||||
|
||||
resp, err := h.services.GRPC.MobilityAccounts.GetAccountsBatch(context.TODO(), request)
|
||||
if err != nil {
|
||||
log.Error().Err(err).Msg("issue in mobilityaccounts call")
|
||||
return accounts, err
|
||||
}
|
||||
|
||||
for _, account := range resp.Accounts {
|
||||
if filterAccount(r, account) {
|
||||
a := account.ToStorageType()
|
||||
accounts = append(accounts, a)
|
||||
}
|
||||
}
|
||||
|
||||
return accounts, err
|
||||
}
|
||||
|
||||
type BeneficiariesForm struct {
|
||||
FirstName string `json:"first_name" validate:"required"`
|
||||
LastName string `json:"last_name" validate:"required"`
|
||||
Email string `json:"email" validate:"required,email"`
|
||||
Birthdate *time.Time `json:"birthdate" validate:"required"`
|
||||
PhoneNumber string `json:"phone_number" validate:"required,phoneNumber"`
|
||||
FileNumber string `json:"file_number"`
|
||||
Address any `json:"address,omitempty"`
|
||||
Gender string `json:"gender"`
|
||||
OtherProperties any `json:"other_properties,omitempty"`
|
||||
}
|
||||
|
||||
func parseBeneficiariesForm(r *http.Request) (map[string]any, error) {
|
||||
if err := r.ParseForm(); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
|
||||
var date *time.Time
|
||||
|
||||
if r.PostFormValue("birthdate") != "" {
|
||||
d, err := time.Parse("2006-01-02", r.PostFormValue("birthdate"))
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
date = &d
|
||||
}
|
||||
|
||||
formData := BeneficiariesForm{
|
||||
FirstName: r.PostFormValue("first_name"),
|
||||
LastName: r.PostFormValue("last_name"),
|
||||
Email: r.PostFormValue("email"),
|
||||
Birthdate: date,
|
||||
PhoneNumber: r.PostFormValue("phone_number"),
|
||||
FileNumber: r.PostFormValue("file_number"),
|
||||
Gender: r.PostFormValue("gender"),
|
||||
}
|
||||
|
||||
if r.PostFormValue("address") != "" {
|
||||
var a any
|
||||
json.Unmarshal([]byte(r.PostFormValue("address")), &a)
|
||||
formData.Address = a
|
||||
}
|
||||
|
||||
if r.PostFormValue("other_properties") != "" {
|
||||
var a any
|
||||
json.Unmarshal([]byte(r.PostFormValue("other_properties")), &a)
|
||||
formData.OtherProperties = a
|
||||
}
|
||||
|
||||
validate := formvalidators.New()
|
||||
if err := validate.Struct(formData); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
|
||||
d, err := json.Marshal(formData)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
|
||||
var dataMap map[string]any
|
||||
err = json.Unmarshal(d, &dataMap)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
|
||||
return dataMap, nil
|
||||
}
|
||||
228
core/application/dashboard.go
Executable file
228
core/application/dashboard.go
Executable file
@@ -0,0 +1,228 @@
|
||||
package application
|
||||
|
||||
import (
|
||||
"context"
|
||||
"encoding/json"
|
||||
"fmt"
|
||||
"sort"
|
||||
"sync"
|
||||
"time"
|
||||
|
||||
"git.coopgo.io/coopgo-apps/parcoursmob/core/utils/identification"
|
||||
"git.coopgo.io/coopgo-apps/parcoursmob/core/utils/sorting"
|
||||
agenda "git.coopgo.io/coopgo-platform/agenda/grpcapi"
|
||||
agendastorage "git.coopgo.io/coopgo-platform/agenda/storage"
|
||||
fleets "git.coopgo.io/coopgo-platform/fleets/grpcapi"
|
||||
fleetstorage "git.coopgo.io/coopgo-platform/fleets/storage"
|
||||
"git.coopgo.io/coopgo-platform/groups-management/storage"
|
||||
mobilityaccounts "git.coopgo.io/coopgo-platform/mobility-accounts/grpcapi"
|
||||
mobilityaccountsstorage "git.coopgo.io/coopgo-platform/mobility-accounts/storage"
|
||||
"github.com/paulmach/orb"
|
||||
"github.com/paulmach/orb/geojson"
|
||||
"github.com/rs/zerolog/log"
|
||||
"google.golang.org/protobuf/types/known/timestamppb"
|
||||
)
|
||||
|
||||
type DashboardResult struct {
|
||||
Accounts []mobilityaccountsstorage.Account
|
||||
Members []mobilityaccountsstorage.Account
|
||||
Events []agendastorage.Event
|
||||
Bookings []fleetstorage.Booking
|
||||
SolidarityDrivers []mobilityaccountsstorage.Account
|
||||
OrganizedCarpoolDrivers []mobilityaccountsstorage.Account
|
||||
}
|
||||
|
||||
func (h *ApplicationHandler) GetDashboardData(ctx context.Context, driverAddressGeoLayer, driverAddressGeoCode string) (*DashboardResult, error) {
|
||||
g := ctx.Value(identification.GroupKey)
|
||||
if g == nil {
|
||||
return nil, fmt.Errorf("no group found in context")
|
||||
}
|
||||
group := g.(storage.Group)
|
||||
|
||||
// Load geography polygons for driver address filtering
|
||||
var driverAddressPolygons []orb.Polygon
|
||||
if driverAddressGeoLayer != "" && driverAddressGeoCode != "" {
|
||||
polygons, err := h.loadGeographyPolygon(driverAddressGeoLayer, driverAddressGeoCode)
|
||||
if err != nil {
|
||||
log.Warn().Err(err).Msg("failed to load driver address geography filter")
|
||||
} else {
|
||||
driverAddressPolygons = polygons
|
||||
}
|
||||
}
|
||||
|
||||
// Get accounts (recent beneficiaries)
|
||||
request := &mobilityaccounts.GetAccountsBatchRequest{
|
||||
Accountids: group.Members,
|
||||
}
|
||||
|
||||
resp, err := h.services.GRPC.MobilityAccounts.GetAccountsBatch(ctx, request)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
|
||||
accounts := []mobilityaccountsstorage.Account{}
|
||||
|
||||
// We only display the 5 most recent here
|
||||
count := len(resp.Accounts)
|
||||
min := count - 5
|
||||
if min < 0 {
|
||||
min = 0
|
||||
}
|
||||
|
||||
for _, account := range resp.Accounts[min:] {
|
||||
// Check if not archived
|
||||
if archived, ok := account.Data.AsMap()["archived"].(bool); !ok || !archived {
|
||||
a := account.ToStorageType()
|
||||
accounts = append([]mobilityaccountsstorage.Account{a}, accounts...)
|
||||
}
|
||||
}
|
||||
|
||||
// Fetch remaining data in parallel using goroutines
|
||||
var wg sync.WaitGroup
|
||||
var mu sync.Mutex
|
||||
|
||||
var members []mobilityaccountsstorage.Account
|
||||
var events []agendastorage.Event
|
||||
var bookings []fleetstorage.Booking
|
||||
var solidarityDrivers []mobilityaccountsstorage.Account
|
||||
var organizedCarpoolDrivers []mobilityaccountsstorage.Account
|
||||
|
||||
// Get members
|
||||
wg.Add(1)
|
||||
go func() {
|
||||
defer wg.Done()
|
||||
m, _, err := h.groupmembers(group.ID)
|
||||
if err == nil {
|
||||
mu.Lock()
|
||||
members = m
|
||||
mu.Unlock()
|
||||
}
|
||||
}()
|
||||
|
||||
// Get events
|
||||
wg.Add(1)
|
||||
go func() {
|
||||
defer wg.Done()
|
||||
eventsresp, err := h.services.GRPC.Agenda.GetEvents(ctx, &agenda.GetEventsRequest{
|
||||
Namespaces: []string{"parcoursmob_dispositifs"},
|
||||
Mindate: timestamppb.Now(),
|
||||
})
|
||||
if err == nil {
|
||||
mu.Lock()
|
||||
for _, e := range eventsresp.Events {
|
||||
events = append(events, e.ToStorageType())
|
||||
}
|
||||
sort.Sort(sorting.EventsByStartdate(events))
|
||||
mu.Unlock()
|
||||
}
|
||||
}()
|
||||
|
||||
// Get bookings
|
||||
wg.Add(1)
|
||||
go func() {
|
||||
defer wg.Done()
|
||||
bookingsresp, err := h.services.GRPC.Fleets.GetBookings(ctx, &fleets.GetBookingsRequest{
|
||||
Namespaces: []string{"parcoursmob_dispositifs"},
|
||||
})
|
||||
if err == nil {
|
||||
mu.Lock()
|
||||
for _, b := range bookingsresp.Bookings {
|
||||
if b.Enddate.AsTime().After(time.Now()) {
|
||||
bookings = append(bookings, b.ToStorageType())
|
||||
}
|
||||
}
|
||||
mu.Unlock()
|
||||
}
|
||||
}()
|
||||
|
||||
// Get solidarity transport drivers
|
||||
wg.Add(1)
|
||||
go func() {
|
||||
defer wg.Done()
|
||||
solidarityRequest := &mobilityaccounts.GetAccountsRequest{
|
||||
Namespaces: []string{"solidarity_drivers"},
|
||||
}
|
||||
solidarityResp, err := h.services.GRPC.MobilityAccounts.GetAccounts(ctx, solidarityRequest)
|
||||
if err == nil {
|
||||
mu.Lock()
|
||||
for _, account := range solidarityResp.Accounts {
|
||||
// Only include non-archived drivers with addresses
|
||||
if archived, ok := account.Data.AsMap()["archived"].(bool); !ok || !archived {
|
||||
if address, ok := account.Data.AsMap()["address"]; ok && address != nil {
|
||||
// Apply geography filter if specified
|
||||
if len(driverAddressPolygons) > 0 {
|
||||
if addr, ok := account.Data.AsMap()["address"].(map[string]interface{}); ok {
|
||||
jsonAddr, err := json.Marshal(addr)
|
||||
if err == nil {
|
||||
addrGeojson, err := geojson.UnmarshalFeature(jsonAddr)
|
||||
if err == nil && addrGeojson.Geometry != nil {
|
||||
if point, ok := addrGeojson.Geometry.(orb.Point); ok {
|
||||
if isPointInGeographies(point, driverAddressPolygons) {
|
||||
solidarityDrivers = append(solidarityDrivers, account.ToStorageType())
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
} else {
|
||||
solidarityDrivers = append(solidarityDrivers, account.ToStorageType())
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
mu.Unlock()
|
||||
}
|
||||
}()
|
||||
|
||||
// Get organized carpool drivers
|
||||
wg.Add(1)
|
||||
go func() {
|
||||
defer wg.Done()
|
||||
carpoolRequest := &mobilityaccounts.GetAccountsRequest{
|
||||
Namespaces: []string{"organized_carpool_drivers"},
|
||||
}
|
||||
carpoolResp, err := h.services.GRPC.MobilityAccounts.GetAccounts(ctx, carpoolRequest)
|
||||
if err == nil {
|
||||
mu.Lock()
|
||||
for _, account := range carpoolResp.Accounts {
|
||||
// Only include non-archived drivers with addresses
|
||||
if archived, ok := account.Data.AsMap()["archived"].(bool); !ok || !archived {
|
||||
if address, ok := account.Data.AsMap()["address"]; ok && address != nil {
|
||||
// Apply geography filter if specified
|
||||
if len(driverAddressPolygons) > 0 {
|
||||
if addr, ok := account.Data.AsMap()["address"].(map[string]interface{}); ok {
|
||||
jsonAddr, err := json.Marshal(addr)
|
||||
if err == nil {
|
||||
addrGeojson, err := geojson.UnmarshalFeature(jsonAddr)
|
||||
if err == nil && addrGeojson.Geometry != nil {
|
||||
if point, ok := addrGeojson.Geometry.(orb.Point); ok {
|
||||
if isPointInGeographies(point, driverAddressPolygons) {
|
||||
organizedCarpoolDrivers = append(organizedCarpoolDrivers, account.ToStorageType())
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
} else {
|
||||
organizedCarpoolDrivers = append(organizedCarpoolDrivers, account.ToStorageType())
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
mu.Unlock()
|
||||
}
|
||||
}()
|
||||
|
||||
// Wait for all goroutines to complete
|
||||
wg.Wait()
|
||||
|
||||
return &DashboardResult{
|
||||
Accounts: accounts,
|
||||
Members: members,
|
||||
Events: events,
|
||||
Bookings: bookings,
|
||||
SolidarityDrivers: solidarityDrivers,
|
||||
OrganizedCarpoolDrivers: organizedCarpoolDrivers,
|
||||
}, nil
|
||||
}
|
||||
|
||||
3
core/application/directory.go
Executable file
3
core/application/directory.go
Executable file
@@ -0,0 +1,3 @@
|
||||
package application
|
||||
|
||||
// Directory module - no business logic needed, all functionality moved to WebServer handlers
|
||||
171
core/application/documents.go
Normal file
171
core/application/documents.go
Normal file
@@ -0,0 +1,171 @@
|
||||
package application
|
||||
|
||||
import (
|
||||
"context"
|
||||
"fmt"
|
||||
"io"
|
||||
|
||||
filestorage "git.coopgo.io/coopgo-apps/parcoursmob/core/utils/storage"
|
||||
mobilityaccounts "git.coopgo.io/coopgo-platform/mobility-accounts/grpcapi"
|
||||
"github.com/google/uuid"
|
||||
)
|
||||
|
||||
// DocumentConfig defines entity-specific document configuration
|
||||
type DocumentConfig struct {
|
||||
// Storage prefix for this entity type
|
||||
StoragePrefix string
|
||||
|
||||
// Namespace for account validation (empty if no validation needed)
|
||||
AccountNamespace string
|
||||
|
||||
// Whether to validate against MobilityAccounts service
|
||||
RequiresAccountValidation bool
|
||||
|
||||
// Custom validator function (optional)
|
||||
CustomValidator func(ctx context.Context, entityID string) error
|
||||
}
|
||||
|
||||
// Pre-configured document configs for each entity type
|
||||
var (
|
||||
BeneficiaryDocumentConfig = DocumentConfig{
|
||||
StoragePrefix: filestorage.PREFIX_BENEFICIARIES,
|
||||
AccountNamespace: "parcoursmob_beneficiaries",
|
||||
RequiresAccountValidation: true,
|
||||
}
|
||||
|
||||
SolidarityDriverDocumentConfig = DocumentConfig{
|
||||
StoragePrefix: filestorage.PREFIX_SOLIDARITY_TRANSPORT_DRIVERS,
|
||||
AccountNamespace: "solidarity_drivers",
|
||||
RequiresAccountValidation: true,
|
||||
}
|
||||
|
||||
OrganizedCarpoolDriverDocumentConfig = DocumentConfig{
|
||||
StoragePrefix: filestorage.PREFIX_ORGANIZED_CARPOOL_DRIVERS,
|
||||
AccountNamespace: "organized_carpool_drivers",
|
||||
RequiresAccountValidation: true,
|
||||
}
|
||||
|
||||
BookingDocumentConfig = DocumentConfig{
|
||||
StoragePrefix: filestorage.PREFIX_BOOKINGS,
|
||||
RequiresAccountValidation: false,
|
||||
}
|
||||
)
|
||||
|
||||
// AddDocument adds a document for any entity with validation
|
||||
func (h *ApplicationHandler) AddDocument(
|
||||
ctx context.Context,
|
||||
config DocumentConfig,
|
||||
entityID string,
|
||||
file io.Reader,
|
||||
filename string,
|
||||
fileSize int64,
|
||||
documentType string,
|
||||
documentName string,
|
||||
) error {
|
||||
// Perform validation if required
|
||||
if config.RequiresAccountValidation {
|
||||
if err := h.validateAccountForDocument(ctx, entityID, config.AccountNamespace); err != nil {
|
||||
return err
|
||||
}
|
||||
}
|
||||
|
||||
// Custom validation if provided
|
||||
if config.CustomValidator != nil {
|
||||
if err := config.CustomValidator(ctx, entityID); err != nil {
|
||||
return err
|
||||
}
|
||||
}
|
||||
|
||||
// Generate unique file ID
|
||||
fileid := uuid.NewString()
|
||||
|
||||
// Prepare metadata
|
||||
metadata := map[string]string{
|
||||
"type": documentType,
|
||||
"name": documentName,
|
||||
}
|
||||
|
||||
// Construct file path
|
||||
filepath := fmt.Sprintf("%s/%s_%s", entityID, fileid, filename)
|
||||
|
||||
// Store file
|
||||
return h.filestorage.Put(file, config.StoragePrefix, filepath, fileSize, metadata)
|
||||
}
|
||||
|
||||
// GetDocument retrieves a document for any entity with validation
|
||||
func (h *ApplicationHandler) GetDocument(
|
||||
ctx context.Context,
|
||||
config DocumentConfig,
|
||||
entityID string,
|
||||
document string,
|
||||
) (io.Reader, *filestorage.FileInfo, error) {
|
||||
// Perform validation if required
|
||||
if config.RequiresAccountValidation {
|
||||
if err := h.validateAccountForDocument(ctx, entityID, config.AccountNamespace); err != nil {
|
||||
return nil, nil, err
|
||||
}
|
||||
}
|
||||
|
||||
// Custom validation if provided
|
||||
if config.CustomValidator != nil {
|
||||
if err := config.CustomValidator(ctx, entityID); err != nil {
|
||||
return nil, nil, err
|
||||
}
|
||||
}
|
||||
|
||||
// Retrieve file
|
||||
filepath := fmt.Sprintf("%s/%s", entityID, document)
|
||||
return h.filestorage.Get(config.StoragePrefix, filepath)
|
||||
}
|
||||
|
||||
// ListDocuments retrieves all documents for an entity
|
||||
func (h *ApplicationHandler) ListDocuments(
|
||||
config DocumentConfig,
|
||||
entityID string,
|
||||
) []filestorage.FileInfo {
|
||||
prefix := fmt.Sprintf("%s/%s", config.StoragePrefix, entityID)
|
||||
return h.filestorage.List(prefix)
|
||||
}
|
||||
|
||||
// DeleteDocument deletes a document for any entity with validation
|
||||
func (h *ApplicationHandler) DeleteDocument(
|
||||
ctx context.Context,
|
||||
config DocumentConfig,
|
||||
entityID string,
|
||||
document string,
|
||||
) error {
|
||||
// Perform validation if required
|
||||
if config.RequiresAccountValidation {
|
||||
if err := h.validateAccountForDocument(ctx, entityID, config.AccountNamespace); err != nil {
|
||||
return err
|
||||
}
|
||||
}
|
||||
|
||||
// Custom validation if provided
|
||||
if config.CustomValidator != nil {
|
||||
if err := config.CustomValidator(ctx, entityID); err != nil {
|
||||
return err
|
||||
}
|
||||
}
|
||||
|
||||
// Delete file
|
||||
filepath := fmt.Sprintf("%s/%s", entityID, document)
|
||||
return h.filestorage.Delete(config.StoragePrefix, filepath)
|
||||
}
|
||||
|
||||
// validateAccountForDocument validates entity against MobilityAccounts service
|
||||
func (h *ApplicationHandler) validateAccountForDocument(ctx context.Context, accountID string, expectedNamespace string) error {
|
||||
resp, err := h.services.GRPC.MobilityAccounts.GetAccount(ctx, &mobilityaccounts.GetAccountRequest{
|
||||
Id: accountID,
|
||||
})
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
if resp.Account.Namespace != expectedNamespace {
|
||||
return fmt.Errorf("account %s is not of type %s (namespace: %s)",
|
||||
accountID, expectedNamespace, resp.Account.Namespace)
|
||||
}
|
||||
|
||||
return nil
|
||||
}
|
||||
429
core/application/exports.go
Normal file
429
core/application/exports.go
Normal file
@@ -0,0 +1,429 @@
|
||||
package application
|
||||
|
||||
import (
|
||||
"context"
|
||||
"encoding/json"
|
||||
"fmt"
|
||||
"sort"
|
||||
"strconv"
|
||||
|
||||
"git.coopgo.io/coopgo-apps/parcoursmob/core/utils/sorting"
|
||||
agenda "git.coopgo.io/coopgo-platform/agenda/grpcapi"
|
||||
agendastorage "git.coopgo.io/coopgo-platform/agenda/storage"
|
||||
fleets "git.coopgo.io/coopgo-platform/fleets/grpcapi"
|
||||
fleetsstorage "git.coopgo.io/coopgo-platform/fleets/storage"
|
||||
groupsmanagement "git.coopgo.io/coopgo-platform/groups-management/grpcapi"
|
||||
groupsstorage "git.coopgo.io/coopgo-platform/groups-management/storage"
|
||||
accounts "git.coopgo.io/coopgo-platform/mobility-accounts/grpcapi"
|
||||
accountsstorage "git.coopgo.io/coopgo-platform/mobility-accounts/storage"
|
||||
"github.com/xuri/excelize/v2"
|
||||
)
|
||||
|
||||
type FlatMaps []map[string]any
|
||||
|
||||
func (maps FlatMaps) GetHeaders() (res []string) {
|
||||
keys := map[string]bool{}
|
||||
for _, m := range maps {
|
||||
for k, _ := range m {
|
||||
if _, ok := keys[k]; !ok {
|
||||
keys[k] = true
|
||||
res = append(res, k)
|
||||
}
|
||||
}
|
||||
}
|
||||
sort.Strings(res)
|
||||
return
|
||||
}
|
||||
|
||||
func (maps FlatMaps) GetValues() (res [][]string) {
|
||||
headers := maps.GetHeaders()
|
||||
for _, m := range maps {
|
||||
line := []string{}
|
||||
for _, k := range headers {
|
||||
if v, ok := m[k]; ok && v != nil {
|
||||
line = append(line, fmt.Sprint(v))
|
||||
} else {
|
||||
line = append(line, "")
|
||||
}
|
||||
}
|
||||
res = append(res, line)
|
||||
}
|
||||
return
|
||||
}
|
||||
|
||||
type ExportCacheResult struct {
|
||||
Headers []string
|
||||
Values [][]string
|
||||
}
|
||||
|
||||
func (h *ApplicationHandler) ExportCacheAsCSV(cacheID string) (*ExportCacheResult, error) {
|
||||
d, err := h.cache.Get(cacheID)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
|
||||
var data []any
|
||||
if dataSlice, ok := d.([]any); ok {
|
||||
data = dataSlice
|
||||
} else {
|
||||
// Convert single item to slice
|
||||
jsonData, err := json.Marshal(d)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
if err := json.Unmarshal(jsonData, &data); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
}
|
||||
|
||||
flatmaps := FlatMaps{}
|
||||
for _, v := range data {
|
||||
if vMap, ok := v.(map[string]any); ok {
|
||||
fm := map[string]any{}
|
||||
flatten("", vMap, fm)
|
||||
flatmaps = append(flatmaps, fm)
|
||||
}
|
||||
}
|
||||
|
||||
return &ExportCacheResult{
|
||||
Headers: flatmaps.GetHeaders(),
|
||||
Values: flatmaps.GetValues(),
|
||||
}, nil
|
||||
}
|
||||
|
||||
func flatten(prefix string, src map[string]any, dest map[string]any) {
|
||||
if len(prefix) > 0 {
|
||||
prefix += "."
|
||||
}
|
||||
for k, v := range src {
|
||||
switch child := v.(type) {
|
||||
case map[string]any:
|
||||
flatten(prefix+k, child, dest)
|
||||
case []any:
|
||||
for i := 0; i < len(child); i++ {
|
||||
dest[prefix+k+"."+strconv.Itoa(i)] = child[i]
|
||||
}
|
||||
default:
|
||||
dest[prefix+k] = v
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
type AgendaExportResult struct {
|
||||
ExcelFile *excelize.File
|
||||
}
|
||||
|
||||
func (h *ApplicationHandler) ExportAllAgendaEvents() (*AgendaExportResult, error) {
|
||||
resp, err := h.services.GRPC.Agenda.GetEvents(context.TODO(), &agenda.GetEventsRequest{
|
||||
Namespaces: []string{"parcoursmob_dispositifs"},
|
||||
})
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
|
||||
events := []agendastorage.Event{}
|
||||
groupids := []string{}
|
||||
beneficiaries_ids := []string{}
|
||||
|
||||
for _, e := range resp.Events {
|
||||
groupids = append(groupids, e.Owners...)
|
||||
events = append(events, e.ToStorageType())
|
||||
|
||||
for _, subscriptions := range e.Subscriptions {
|
||||
beneficiaries_ids = append(beneficiaries_ids, subscriptions.Subscriber)
|
||||
}
|
||||
}
|
||||
|
||||
sort.Sort(sorting.EventsByStartdate(events))
|
||||
|
||||
groups, beneficiaries_map, err := h.getAgendaMetadata(groupids, beneficiaries_ids)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
|
||||
file := h.generateAgendaExcel(events, groups, beneficiaries_map)
|
||||
return &AgendaExportResult{ExcelFile: file}, nil
|
||||
}
|
||||
|
||||
func (h *ApplicationHandler) ExportSingleAgendaEvent(eventID string) (*AgendaExportResult, error) {
|
||||
resp, err := h.services.GRPC.Agenda.GetEvent(context.TODO(), &agenda.GetEventRequest{
|
||||
Id: eventID,
|
||||
})
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
|
||||
groupids := []string{}
|
||||
beneficiaries_ids := []string{}
|
||||
groupids = append(groupids, resp.Event.Owners...)
|
||||
|
||||
for _, subscriptions := range resp.Event.Subscriptions {
|
||||
beneficiaries_ids = append(beneficiaries_ids, subscriptions.Subscriber)
|
||||
}
|
||||
|
||||
groups, beneficiaries_map, err := h.getAgendaMetadata(groupids, beneficiaries_ids)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
|
||||
events := []agendastorage.Event{resp.Event.ToStorageType()}
|
||||
file := h.generateAgendaExcel(events, groups, beneficiaries_map)
|
||||
return &AgendaExportResult{ExcelFile: file}, nil
|
||||
}
|
||||
|
||||
func (h *ApplicationHandler) getAgendaMetadata(groupids, beneficiaries_ids []string) (map[string]groupsstorage.Group, map[string]accountsstorage.Account, error) {
|
||||
groupsresp, err := h.services.GRPC.GroupsManagement.GetGroupsBatch(context.TODO(), &groupsmanagement.GetGroupsBatchRequest{
|
||||
Groupids: groupids,
|
||||
})
|
||||
|
||||
groups := map[string]groupsstorage.Group{}
|
||||
if err == nil {
|
||||
for _, g := range groupsresp.Groups {
|
||||
groups[g.Id] = g.ToStorageType()
|
||||
}
|
||||
}
|
||||
|
||||
beneficiaries, err := h.services.GRPC.MobilityAccounts.GetAccountsBatch(context.TODO(), &accounts.GetAccountsBatchRequest{
|
||||
Accountids: beneficiaries_ids,
|
||||
})
|
||||
if err != nil {
|
||||
return nil, nil, err
|
||||
}
|
||||
|
||||
beneficiaries_map := map[string]accountsstorage.Account{}
|
||||
for _, ben := range beneficiaries.Accounts {
|
||||
beneficiaries_map[ben.Id] = ben.ToStorageType()
|
||||
}
|
||||
|
||||
return groups, beneficiaries_map, nil
|
||||
}
|
||||
|
||||
func (h *ApplicationHandler) generateAgendaExcel(events []agendastorage.Event, groups map[string]groupsstorage.Group, beneficiaries_map map[string]accountsstorage.Account) *excelize.File {
|
||||
f := excelize.NewFile()
|
||||
|
||||
f.SetCellValue("Sheet1", "A1", "Evénement")
|
||||
f.SetCellValue("Sheet1", "B1", "Date de début")
|
||||
f.SetCellValue("Sheet1", "C1", "Date de fin")
|
||||
f.SetCellValue("Sheet1", "D1", "Nom bénéficiaire")
|
||||
f.SetCellValue("Sheet1", "E1", "Prenom bénéficiaire")
|
||||
f.SetCellValue("Sheet1", "F1", "Numéro allocataire / Pole emploi")
|
||||
f.SetCellValue("Sheet1", "G1", "Prescipteur")
|
||||
f.SetCellValue("Sheet1", "H1", "Prescipteur Nom")
|
||||
f.SetCellValue("Sheet1", "I1", "Prescipteur Email")
|
||||
f.SetCellValue("Sheet1", "J1", "Gestionnaire événement")
|
||||
|
||||
i := 2
|
||||
for _, e := range events {
|
||||
if len(e.Owners) == 0 {
|
||||
continue
|
||||
}
|
||||
admin := groups[e.Owners[0]]
|
||||
|
||||
for _, s := range e.Subscriptions {
|
||||
subscribedbygroup := ""
|
||||
subscribedbyuser := ""
|
||||
subscribedbyemail := ""
|
||||
if v, ok := s.Data["subscribed_by"].(map[string]any); ok {
|
||||
if v2, ok := v["group"].(map[string]any); ok {
|
||||
if v3, ok := v2["name"].(string); ok {
|
||||
subscribedbygroup = v3
|
||||
}
|
||||
}
|
||||
if v4, ok := v["user"].(map[string]any); ok {
|
||||
if v5, ok := v4["display_name"].(string); ok {
|
||||
subscribedbyuser = v5
|
||||
}
|
||||
if v6, ok := v4["email"].(string); ok {
|
||||
subscribedbyemail = v6
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
beneficiary := beneficiaries_map[s.Subscriber]
|
||||
|
||||
f.SetCellValue("Sheet1", fmt.Sprintf("A%d", i), e.Name)
|
||||
f.SetCellValue("Sheet1", fmt.Sprintf("B%d", i), e.Startdate.Format("2006-01-02"))
|
||||
f.SetCellValue("Sheet1", fmt.Sprintf("C%d", i), e.Enddate.Format("2006-01-02"))
|
||||
f.SetCellValue("Sheet1", fmt.Sprintf("D%d", i), beneficiary.Data["last_name"])
|
||||
f.SetCellValue("Sheet1", fmt.Sprintf("E%d", i), beneficiary.Data["first_name"])
|
||||
f.SetCellValue("Sheet1", fmt.Sprintf("F%d", i), beneficiary.Data["file_number"])
|
||||
f.SetCellValue("Sheet1", fmt.Sprintf("G%d", i), subscribedbygroup)
|
||||
f.SetCellValue("Sheet1", fmt.Sprintf("H%d", i), subscribedbyuser)
|
||||
f.SetCellValue("Sheet1", fmt.Sprintf("I%d", i), subscribedbyemail)
|
||||
f.SetCellValue("Sheet1", fmt.Sprintf("J%d", i), admin.Data["name"])
|
||||
i = i + 1
|
||||
}
|
||||
}
|
||||
return f
|
||||
}
|
||||
|
||||
type FleetBookingsExportResult struct {
|
||||
ExcelFile *excelize.File
|
||||
}
|
||||
|
||||
func (h *ApplicationHandler) ExportAllFleetBookings() (*FleetBookingsExportResult, error) {
|
||||
vehicles, bookings, err := h.getFleetData()
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
|
||||
groups, beneficiaries_map, err := h.getFleetMetadata(bookings)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
|
||||
file := h.generateFleetExcel(bookings, vehicles, groups, beneficiaries_map, "")
|
||||
return &FleetBookingsExportResult{ExcelFile: file}, nil
|
||||
}
|
||||
|
||||
func (h *ApplicationHandler) ExportFleetBookingsByGroup(groupID string) (*FleetBookingsExportResult, error) {
|
||||
vehicles, bookings, err := h.getFleetData()
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
|
||||
groups, beneficiaries_map, err := h.getFleetMetadata(bookings)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
|
||||
file := h.generateFleetExcel(bookings, vehicles, groups, beneficiaries_map, groupID)
|
||||
return &FleetBookingsExportResult{ExcelFile: file}, nil
|
||||
}
|
||||
|
||||
func (h *ApplicationHandler) getFleetData() (map[string]fleetsstorage.Vehicle, []fleetsstorage.Booking, error) {
|
||||
vehicles := map[string]fleetsstorage.Vehicle{}
|
||||
bookings := []fleetsstorage.Booking{}
|
||||
|
||||
request := &fleets.GetVehiclesRequest{
|
||||
Namespaces: []string{"parcoursmob"},
|
||||
}
|
||||
resp, err := h.services.GRPC.Fleets.GetVehicles(context.TODO(), request)
|
||||
if err != nil {
|
||||
return nil, nil, err
|
||||
}
|
||||
|
||||
for _, vehicle := range resp.Vehicles {
|
||||
v := vehicle.ToStorageType()
|
||||
for _, b := range v.Bookings {
|
||||
bookings = append(bookings, b)
|
||||
}
|
||||
vehicles[vehicle.Id] = v
|
||||
}
|
||||
|
||||
return vehicles, bookings, nil
|
||||
}
|
||||
|
||||
func (h *ApplicationHandler) getFleetMetadata(bookings []fleetsstorage.Booking) (map[string]groupsstorage.Group, map[string]accountsstorage.Account, error) {
|
||||
beneficiaries_ids := []string{}
|
||||
for _, b := range bookings {
|
||||
beneficiaries_ids = append(beneficiaries_ids, b.Driver)
|
||||
}
|
||||
|
||||
groups := map[string]groupsstorage.Group{}
|
||||
admingroups, err := h.services.GRPC.GroupsManagement.GetGroups(context.TODO(), &groupsmanagement.GetGroupsRequest{
|
||||
Namespaces: []string{"parcoursmob_organizations"},
|
||||
})
|
||||
if err != nil {
|
||||
return nil, nil, err
|
||||
}
|
||||
|
||||
for _, g := range admingroups.Groups {
|
||||
groups[g.Id] = g.ToStorageType()
|
||||
}
|
||||
|
||||
beneficiaries, err := h.services.GRPC.MobilityAccounts.GetAccountsBatch(context.TODO(), &accounts.GetAccountsBatchRequest{
|
||||
Accountids: beneficiaries_ids,
|
||||
})
|
||||
if err != nil {
|
||||
return nil, nil, err
|
||||
}
|
||||
|
||||
beneficiaries_map := map[string]accountsstorage.Account{}
|
||||
for _, ben := range beneficiaries.Accounts {
|
||||
beneficiaries_map[ben.Id] = ben.ToStorageType()
|
||||
}
|
||||
|
||||
return groups, beneficiaries_map, nil
|
||||
}
|
||||
|
||||
func (h *ApplicationHandler) generateFleetExcel(bookings []fleetsstorage.Booking, vehicles map[string]fleetsstorage.Vehicle, groups map[string]groupsstorage.Group, beneficiaries_map map[string]accountsstorage.Account, filterGroupID string) *excelize.File {
|
||||
f := excelize.NewFile()
|
||||
|
||||
f.SetCellValue("Sheet1", "A1", "Numéro")
|
||||
f.SetCellValue("Sheet1", "B1", "Type")
|
||||
f.SetCellValue("Sheet1", "C1", "Gestionnaire")
|
||||
f.SetCellValue("Sheet1", "D1", "Prescripteur")
|
||||
f.SetCellValue("Sheet1", "E1", "Bénéficiaire")
|
||||
f.SetCellValue("Sheet1", "F1", "Numéro allocataire / Pole emploi")
|
||||
f.SetCellValue("Sheet1", "G1", "Début de Mise à disposition")
|
||||
f.SetCellValue("Sheet1", "H1", "Fin de mise Ă disposition")
|
||||
f.SetCellValue("Sheet1", "I1", "Début indisponibilité")
|
||||
f.SetCellValue("Sheet1", "J1", "Fin indisponibilité")
|
||||
f.SetCellValue("Sheet1", "K1", "Véhicule retiré")
|
||||
f.SetCellValue("Sheet1", "L1", "Commentaire - Retrait véhicule")
|
||||
f.SetCellValue("Sheet1", "M1", "Réservation supprimée")
|
||||
f.SetCellValue("Sheet1", "N1", "Motif de la suppression")
|
||||
|
||||
i := 2
|
||||
for _, b := range bookings {
|
||||
vehicle := vehicles[b.Vehicleid]
|
||||
if len(vehicle.Administrators) == 0 {
|
||||
continue
|
||||
}
|
||||
admin := groups[vehicle.Administrators[0]]
|
||||
|
||||
bookedby := ""
|
||||
if v, ok := b.Data["booked_by"].(map[string]any); ok {
|
||||
if v2, ok := v["user"].(map[string]any); ok {
|
||||
if v3, ok := v2["display_name"].(string); ok {
|
||||
bookedby = v3
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
bookedbygroup := ""
|
||||
if v4, ok := b.Data["booked_by"].(map[string]any); ok {
|
||||
if v5, ok := v4["group"].(map[string]any); ok {
|
||||
if v6, ok := v5["id"].(string); ok {
|
||||
bookedbygroup = v6
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// Filter by group if specified
|
||||
if filterGroupID != "" && bookedbygroup != filterGroupID {
|
||||
continue
|
||||
}
|
||||
|
||||
beneficiary := beneficiaries_map[b.Driver]
|
||||
adminunavailability := false
|
||||
|
||||
if av, ok := b.Data["administrator_unavailability"].(bool); ok && av {
|
||||
adminunavailability = true
|
||||
}
|
||||
|
||||
deleted := ""
|
||||
if b.Deleted {
|
||||
deleted = "DELETED"
|
||||
}
|
||||
|
||||
f.SetCellValue("Sheet1", fmt.Sprintf("A%d", i), vehicle.Data["licence_plate"])
|
||||
f.SetCellValue("Sheet1", fmt.Sprintf("B%d", i), vehicle.Type)
|
||||
f.SetCellValue("Sheet1", fmt.Sprintf("C%d", i), admin.Data["name"])
|
||||
f.SetCellValue("Sheet1", fmt.Sprintf("D%d", i), bookedby)
|
||||
f.SetCellValue("Sheet1", fmt.Sprintf("E%d", i), fmt.Sprintf("%v %v", beneficiary.Data["first_name"], beneficiary.Data["last_name"]))
|
||||
f.SetCellValue("Sheet1", fmt.Sprintf("F%d", i), beneficiary.Data["file_number"])
|
||||
f.SetCellValue("Sheet1", fmt.Sprintf("G%d", i), b.Startdate.Format("2006-01-02"))
|
||||
f.SetCellValue("Sheet1", fmt.Sprintf("H%d", i), b.Enddate.Format("2006-01-02"))
|
||||
f.SetCellValue("Sheet1", fmt.Sprintf("I%d", i), b.Unavailablefrom.Format("2006-01-02"))
|
||||
f.SetCellValue("Sheet1", fmt.Sprintf("J%d", i), b.Unavailableto.Format("2006-01-02"))
|
||||
f.SetCellValue("Sheet1", fmt.Sprintf("K%d", i), adminunavailability)
|
||||
f.SetCellValue("Sheet1", fmt.Sprintf("L%d", i), b.Data["comment"])
|
||||
f.SetCellValue("Sheet1", fmt.Sprintf("M%d", i), deleted)
|
||||
f.SetCellValue("Sheet1", fmt.Sprintf("N%d", i), b.Data["motif"])
|
||||
i = i + 1
|
||||
}
|
||||
|
||||
return f
|
||||
}
|
||||
133
core/application/group.go
Executable file
133
core/application/group.go
Executable file
@@ -0,0 +1,133 @@
|
||||
package application
|
||||
|
||||
import (
|
||||
"context"
|
||||
"crypto/rand"
|
||||
"encoding/base64"
|
||||
"fmt"
|
||||
"io"
|
||||
"time"
|
||||
|
||||
groupsmanagement "git.coopgo.io/coopgo-platform/groups-management/grpcapi"
|
||||
"git.coopgo.io/coopgo-platform/groups-management/storage"
|
||||
accounts "git.coopgo.io/coopgo-platform/mobility-accounts/grpcapi"
|
||||
"github.com/rs/zerolog/log"
|
||||
)
|
||||
|
||||
type GroupSettingsResult struct {
|
||||
Group storage.Group
|
||||
GroupMembers []any
|
||||
Admins []any
|
||||
}
|
||||
|
||||
func (h *ApplicationHandler) GetGroupSettings(ctx context.Context, groupID string) (*GroupSettingsResult, error) {
|
||||
// Get group info
|
||||
groupResp, err := h.services.GRPC.GroupsManagement.GetGroup(ctx, &groupsmanagement.GetGroupRequest{
|
||||
Id: groupID,
|
||||
})
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("failed to get group: %w", err)
|
||||
}
|
||||
|
||||
group := groupResp.Group.ToStorageType()
|
||||
|
||||
members, err := h.members()
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("failed to get members: %w", err)
|
||||
}
|
||||
|
||||
admins := []any{}
|
||||
groupMembers := []any{}
|
||||
|
||||
for _, m := range members {
|
||||
mm := m.ToStorageType()
|
||||
if groups, ok := mm.Data["groups"].([]any); ok {
|
||||
for _, g := range groups {
|
||||
if g.(string) == groupID {
|
||||
groupMembers = append(groupMembers, mm)
|
||||
}
|
||||
if g.(string) == groupID+":admin" {
|
||||
admins = append(admins, mm)
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
return &GroupSettingsResult{
|
||||
Group: group,
|
||||
GroupMembers: groupMembers,
|
||||
Admins: admins,
|
||||
}, nil
|
||||
}
|
||||
|
||||
func (h *ApplicationHandler) InviteMemberToGroup(ctx context.Context, groupID string, username string) error {
|
||||
// Get group info
|
||||
groupResp, err := h.services.GRPC.GroupsManagement.GetGroup(ctx, &groupsmanagement.GetGroupRequest{
|
||||
Id: groupID,
|
||||
})
|
||||
if err != nil {
|
||||
return fmt.Errorf("failed to get group: %w", err)
|
||||
}
|
||||
|
||||
group := groupResp.Group.ToStorageType()
|
||||
|
||||
accountresp, err := h.services.GRPC.MobilityAccounts.GetAccountUsername(ctx, &accounts.GetAccountUsernameRequest{
|
||||
Username: username,
|
||||
Namespace: "parcoursmob",
|
||||
})
|
||||
|
||||
if err == nil {
|
||||
// Account already exists: adding the existing account to group
|
||||
account := accountresp.Account.ToStorageType()
|
||||
if account.Data["groups"] == nil {
|
||||
account.Data["groups"] = []any{}
|
||||
}
|
||||
account.Data["groups"] = append(account.Data["groups"].([]any), groupID)
|
||||
|
||||
as, err := accounts.AccountFromStorageType(&account)
|
||||
if err != nil {
|
||||
return fmt.Errorf("failed to convert account: %w", err)
|
||||
}
|
||||
|
||||
_, err = h.services.GRPC.MobilityAccounts.UpdateData(ctx, &accounts.UpdateDataRequest{
|
||||
Account: as,
|
||||
})
|
||||
if err != nil {
|
||||
return fmt.Errorf("failed to update account: %w", err)
|
||||
}
|
||||
|
||||
data := map[string]any{
|
||||
"group": group.Data["name"],
|
||||
}
|
||||
|
||||
if err := h.emailing.Send("onboarding.existing_member", username, data); err != nil {
|
||||
log.Warn().Err(err).Msg("failed to send existing member email")
|
||||
}
|
||||
} else {
|
||||
// Create onboarding for new member
|
||||
onboarding := map[string]any{
|
||||
"username": username,
|
||||
"group": groupID,
|
||||
"admin": false,
|
||||
}
|
||||
|
||||
b := make([]byte, 16)
|
||||
if _, err := io.ReadFull(rand.Reader, b); err != nil {
|
||||
return fmt.Errorf("failed to generate random key: %w", err)
|
||||
}
|
||||
key := base64.RawURLEncoding.EncodeToString(b)
|
||||
|
||||
h.cache.PutWithTTL("onboarding/"+key, onboarding, 72*time.Hour)
|
||||
|
||||
data := map[string]any{
|
||||
"group": group.Data["name"],
|
||||
"key": key,
|
||||
}
|
||||
|
||||
if err := h.emailing.Send("onboarding.new_member", username, data); err != nil {
|
||||
return fmt.Errorf("failed to send new member email: %w", err)
|
||||
}
|
||||
}
|
||||
|
||||
return nil
|
||||
}
|
||||
219
core/application/group_module.go
Executable file
219
core/application/group_module.go
Executable file
@@ -0,0 +1,219 @@
|
||||
package application
|
||||
|
||||
import (
|
||||
"context"
|
||||
"encoding/json"
|
||||
"fmt"
|
||||
"sort"
|
||||
"strings"
|
||||
"time"
|
||||
|
||||
groupsmanagement "git.coopgo.io/coopgo-platform/groups-management/grpcapi"
|
||||
groupstorage "git.coopgo.io/coopgo-platform/groups-management/storage"
|
||||
mobilityaccounts "git.coopgo.io/coopgo-platform/mobility-accounts/grpcapi"
|
||||
mobilityaccountsstorage "git.coopgo.io/coopgo-platform/mobility-accounts/storage"
|
||||
"github.com/google/uuid"
|
||||
"github.com/rs/zerolog/log"
|
||||
"google.golang.org/protobuf/types/known/structpb"
|
||||
)
|
||||
|
||||
type GroupsResult struct {
|
||||
Groups []groupstorage.Group
|
||||
}
|
||||
|
||||
type CreateGroupModuleResult struct {
|
||||
GroupID string
|
||||
}
|
||||
|
||||
type GroupModuleCreateDataResult struct {
|
||||
GroupTypes []string
|
||||
}
|
||||
|
||||
type DisplayGroupModuleResult struct {
|
||||
GroupID string
|
||||
Accounts []any
|
||||
CacheID string
|
||||
Searched bool
|
||||
Beneficiary any
|
||||
Group groupstorage.Group
|
||||
AccountsBeneficiaire []mobilityaccountsstorage.Account
|
||||
}
|
||||
|
||||
var Addres any
|
||||
|
||||
type BeneficiariesGroupForm struct {
|
||||
FirstName string `json:"first_name" validate:"required"`
|
||||
LastName string `json:"last_name" validate:"required"`
|
||||
Email string `json:"email" validate:"required,email"`
|
||||
Birthdate *time.Time `json:"birthdate"`
|
||||
PhoneNumber string `json:"phone_number" validate:"required,phoneNumber"`
|
||||
Address any `json:"address,omitempty"`
|
||||
Gender string `json:"gender"`
|
||||
}
|
||||
|
||||
type GroupsModuleByName []groupstorage.Group
|
||||
|
||||
func (a GroupsModuleByName) Len() int { return len(a) }
|
||||
func (a GroupsModuleByName) Less(i, j int) bool {
|
||||
return strings.Compare(a[i].Data["name"].(string), a[j].Data["name"].(string)) < 0
|
||||
}
|
||||
func (a GroupsModuleByName) Swap(i, j int) { a[i], a[j] = a[j], a[i] }
|
||||
|
||||
func (h *ApplicationHandler) GetGroups(ctx context.Context) (*GroupsResult, error) {
|
||||
request := &groupsmanagement.GetGroupsRequest{
|
||||
Namespaces: []string{"parcoursmob_groups"},
|
||||
}
|
||||
|
||||
resp, err := h.services.GRPC.GroupsManagement.GetGroups(ctx, request)
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("failed to get groups: %w", err)
|
||||
}
|
||||
|
||||
var groups = []groupstorage.Group{}
|
||||
|
||||
for _, group := range resp.Groups {
|
||||
g := group.ToStorageType()
|
||||
groups = append(groups, g)
|
||||
}
|
||||
|
||||
sort.Sort(GroupsModuleByName(groups))
|
||||
|
||||
return &GroupsResult{
|
||||
Groups: groups,
|
||||
}, nil
|
||||
}
|
||||
|
||||
func (h *ApplicationHandler) GetGroupModuleCreateData(ctx context.Context) (*GroupModuleCreateDataResult, error) {
|
||||
groupTypes := h.config.GetStringSlice("modules.groups.group_types")
|
||||
return &GroupModuleCreateDataResult{
|
||||
GroupTypes: groupTypes,
|
||||
}, nil
|
||||
}
|
||||
|
||||
func (h *ApplicationHandler) CreateGroupModule(ctx context.Context, name, groupType, description, address string) (*CreateGroupModuleResult, error) {
|
||||
if name == "" {
|
||||
return nil, fmt.Errorf("name is required")
|
||||
}
|
||||
if groupType == "" {
|
||||
return nil, fmt.Errorf("type is required")
|
||||
}
|
||||
|
||||
var addressData any
|
||||
if address != "" {
|
||||
if err := json.Unmarshal([]byte(address), &addressData); err != nil {
|
||||
return nil, fmt.Errorf("failed to parse address: %w", err)
|
||||
}
|
||||
Addres = addressData
|
||||
}
|
||||
|
||||
groupID := uuid.NewString()
|
||||
|
||||
dataMap := map[string]any{
|
||||
"name": name,
|
||||
"type": groupType,
|
||||
"description": description,
|
||||
"address": Addres,
|
||||
}
|
||||
|
||||
data, err := structpb.NewValue(dataMap)
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("failed to create data structure: %w", err)
|
||||
}
|
||||
|
||||
request := &groupsmanagement.AddGroupRequest{
|
||||
Group: &groupsmanagement.Group{
|
||||
Id: groupID,
|
||||
Namespace: "parcoursmob_groups",
|
||||
Data: data.GetStructValue(),
|
||||
},
|
||||
}
|
||||
|
||||
_, err = h.services.GRPC.GroupsManagement.AddGroup(ctx, request)
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("failed to add group: %w", err)
|
||||
}
|
||||
|
||||
return &CreateGroupModuleResult{
|
||||
GroupID: groupID,
|
||||
}, nil
|
||||
}
|
||||
|
||||
func filterAccountBySearch(searchFilter string, a *mobilityaccounts.Account) bool {
|
||||
if searchFilter != "" {
|
||||
name := a.Data.AsMap()["first_name"].(string) + " " + a.Data.AsMap()["last_name"].(string)
|
||||
if !strings.Contains(strings.ToLower(name), strings.ToLower(searchFilter)) {
|
||||
return false
|
||||
}
|
||||
}
|
||||
return true
|
||||
}
|
||||
func (h *ApplicationHandler) DisplayGroupModule(ctx context.Context, groupID string, searchFilter string, currentUserGroup groupstorage.Group) (*DisplayGroupModuleResult, error) {
|
||||
request := &groupsmanagement.GetGroupRequest{
|
||||
Id: groupID,
|
||||
}
|
||||
|
||||
resp, err := h.services.GRPC.GroupsManagement.GetGroup(ctx, request)
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("failed to get group: %w", err)
|
||||
}
|
||||
|
||||
var accounts = []any{}
|
||||
|
||||
accountsRequest := &mobilityaccounts.GetAccountsBatchRequest{
|
||||
Accountids: resp.Group.Members,
|
||||
}
|
||||
|
||||
accountsResp, err := h.services.GRPC.MobilityAccounts.GetAccountsBatch(ctx, accountsRequest)
|
||||
if err != nil {
|
||||
log.Warn().Err(err).Msg("failed to get accounts batch")
|
||||
} else {
|
||||
for _, account := range accountsResp.Accounts {
|
||||
if filterAccountBySearch(searchFilter, account) {
|
||||
a := account.ToStorageType()
|
||||
accounts = append(accounts, a)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
cacheID := uuid.NewString()
|
||||
h.cache.PutWithTTL(cacheID, accounts, 1*time.Hour)
|
||||
|
||||
// Get beneficiaries in current user's group
|
||||
accountsBeneficiaire, err := h.services.GetBeneficiariesInGroup(currentUserGroup)
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("failed to get beneficiaries in group: %w", err)
|
||||
}
|
||||
|
||||
return &DisplayGroupModuleResult{
|
||||
GroupID: resp.Group.ToStorageType().ID,
|
||||
Accounts: accounts,
|
||||
CacheID: cacheID,
|
||||
Searched: false,
|
||||
Beneficiary: nil,
|
||||
Group: resp.Group.ToStorageType(),
|
||||
AccountsBeneficiaire: accountsBeneficiaire,
|
||||
}, nil
|
||||
}
|
||||
|
||||
func (h *ApplicationHandler) SubscribeBeneficiaryToGroup(ctx context.Context, groupID string, beneficiaryID string) error {
|
||||
beneficiaryRequest := &mobilityaccounts.GetAccountRequest{
|
||||
Id: beneficiaryID,
|
||||
}
|
||||
|
||||
beneficiaryResp, err := h.services.GRPC.MobilityAccounts.GetAccount(ctx, beneficiaryRequest)
|
||||
if err != nil {
|
||||
return fmt.Errorf("failed to get beneficiary: %w", err)
|
||||
}
|
||||
|
||||
subscribe := &groupsmanagement.SubscribeRequest{
|
||||
Groupid: groupID,
|
||||
Memberid: beneficiaryResp.Account.Id,
|
||||
}
|
||||
|
||||
_, err = h.services.GRPC.GroupsManagement.Subscribe(ctx, subscribe)
|
||||
if err != nil {
|
||||
return fmt.Errorf("failed to subscribe beneficiary to group: %w", err)
|
||||
}
|
||||
|
||||
return nil
|
||||
}
|
||||
458
core/application/journeys.go
Executable file
458
core/application/journeys.go
Executable file
@@ -0,0 +1,458 @@
|
||||
package application
|
||||
|
||||
import (
|
||||
"context"
|
||||
"fmt"
|
||||
"slices"
|
||||
"sort"
|
||||
"strings"
|
||||
"sync"
|
||||
"time"
|
||||
|
||||
"git.coopgo.io/coopgo-apps/parcoursmob/core/utils/sorting"
|
||||
carpoolproto "git.coopgo.io/coopgo-platform/carpool-service/servers/grpc/proto"
|
||||
fleets "git.coopgo.io/coopgo-platform/fleets/grpcapi"
|
||||
fleetsstorage "git.coopgo.io/coopgo-platform/fleets/storage"
|
||||
mobilityaccountsstorage "git.coopgo.io/coopgo-platform/mobility-accounts/storage"
|
||||
"git.coopgo.io/coopgo-platform/multimodal-routing/libs/transit/transitous"
|
||||
savedsearchtypes "git.coopgo.io/coopgo-platform/saved-search/data/types"
|
||||
savedsearchproto "git.coopgo.io/coopgo-platform/saved-search/servers/grpc/proto/gen"
|
||||
savedsearchtransformers "git.coopgo.io/coopgo-platform/saved-search/servers/grpc/transformers"
|
||||
"git.coopgo.io/coopgo-platform/solidarity-transport/servers/grpc/proto/gen"
|
||||
"git.coopgo.io/coopgo-platform/solidarity-transport/servers/grpc/transformers"
|
||||
"github.com/paulmach/orb/geojson"
|
||||
"github.com/rs/zerolog/log"
|
||||
|
||||
"google.golang.org/protobuf/types/known/structpb"
|
||||
"google.golang.org/protobuf/types/known/timestamppb"
|
||||
)
|
||||
|
||||
type SearchJourneysResult struct {
|
||||
CarpoolResults []*geojson.FeatureCollection
|
||||
TransitResults []*transitous.Itinerary
|
||||
VehicleResults []fleetsstorage.Vehicle
|
||||
Searched bool
|
||||
DriverJourneys []*gen.SolidarityTransportDriverJourney
|
||||
Drivers map[string]mobilityaccountsstorage.Account
|
||||
OrganizedCarpools []*carpoolproto.CarpoolServiceDriverJourney
|
||||
KnowledgeBaseResults []any
|
||||
}
|
||||
|
||||
// SearchJourneyOptions contains per-request options for journey search
|
||||
type SearchJourneyOptions struct {
|
||||
DisableSolidarityTransport bool
|
||||
DisableOrganizedCarpool bool
|
||||
DisableCarpoolOperators bool
|
||||
DisableTransit bool
|
||||
DisableFleetVehicles bool
|
||||
DisableKnowledgeBase bool
|
||||
}
|
||||
|
||||
// SearchJourneys performs the business logic for journey search
|
||||
func (h *ApplicationHandler) SearchJourneys(
|
||||
ctx context.Context,
|
||||
departureDateTime time.Time,
|
||||
departureGeo *geojson.Feature,
|
||||
destinationGeo *geojson.Feature,
|
||||
passengerID string,
|
||||
solidarityTransportExcludeDriver string,
|
||||
solidarityExcludeGroupId string,
|
||||
options *SearchJourneyOptions,
|
||||
) (*SearchJourneysResult, error) {
|
||||
var (
|
||||
// Results
|
||||
transitResults []*transitous.Itinerary
|
||||
carpoolResults []*geojson.FeatureCollection
|
||||
vehicleResults []fleetsstorage.Vehicle
|
||||
solidarityTransportResults []*gen.SolidarityTransportDriverJourney
|
||||
organizedCarpoolResults []*carpoolproto.CarpoolServiceDriverJourney
|
||||
knowledgeBaseResults []any
|
||||
|
||||
drivers = map[string]mobilityaccountsstorage.Account{}
|
||||
searched = false
|
||||
)
|
||||
|
||||
// Only search if we have complete departure and destination info
|
||||
if departureGeo != nil && destinationGeo != nil && !departureDateTime.IsZero() {
|
||||
searched = true
|
||||
|
||||
// Default options if not provided
|
||||
if options == nil {
|
||||
options = &SearchJourneyOptions{}
|
||||
}
|
||||
|
||||
// Check solution type configurations (global config AND per-request options)
|
||||
solidarityTransportEnabled := h.config.GetBool("modules.journeys.solutions.solidarity_transport.enabled") && !options.DisableSolidarityTransport
|
||||
organizedCarpoolEnabled := h.config.GetBool("modules.journeys.solutions.organized_carpool.enabled") && !options.DisableOrganizedCarpool
|
||||
carpoolOperatorsEnabled := h.config.GetBool("modules.journeys.solutions.carpool_operators.enabled") && !options.DisableCarpoolOperators
|
||||
transitEnabled := h.config.GetBool("modules.journeys.solutions.transit.enabled") && !options.DisableTransit
|
||||
fleetVehiclesEnabled := h.config.GetBool("modules.journeys.solutions.fleet_vehicles.enabled") && !options.DisableFleetVehicles
|
||||
knowledgeBaseEnabled := h.config.GetBool("modules.journeys.solutions.knowledge_base.enabled") && !options.DisableKnowledgeBase
|
||||
|
||||
// SOLIDARITY TRANSPORT
|
||||
var err error
|
||||
drivers, err = h.services.GetAccountsInNamespacesMap([]string{"solidarity_drivers", "organized_carpool_drivers"})
|
||||
if err != nil {
|
||||
drivers = map[string]mobilityaccountsstorage.Account{}
|
||||
}
|
||||
|
||||
protodep, _ := transformers.GeoJsonToProto(departureGeo)
|
||||
protodest, _ := transformers.GeoJsonToProto(destinationGeo)
|
||||
|
||||
// Get driver IDs to exclude based on group_id (drivers who already have bookings in this group)
|
||||
excludedDriverIds := make(map[string]bool)
|
||||
if solidarityExcludeGroupId != "" {
|
||||
bookingsResp, err := h.services.GRPC.SolidarityTransport.GetSolidarityTransportBookings(ctx, &gen.GetSolidarityTransportBookingsRequest{
|
||||
StartDate: timestamppb.New(time.Date(2000, 1, 1, 0, 0, 0, 0, time.UTC)),
|
||||
EndDate: timestamppb.New(time.Date(9999, 12, 31, 0, 0, 0, 0, time.UTC)),
|
||||
})
|
||||
if err == nil {
|
||||
for _, booking := range bookingsResp.Bookings {
|
||||
if booking.GroupId == solidarityExcludeGroupId {
|
||||
excludedDriverIds[booking.DriverId] = true
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
if solidarityTransportEnabled {
|
||||
log.Debug().Time("departure time", departureDateTime).Msg("calling driver journeys with ...")
|
||||
|
||||
res, err := h.services.GRPC.SolidarityTransport.GetDriverJourneys(ctx, &gen.GetDriverJourneysRequest{
|
||||
Departure: protodep,
|
||||
Arrival: protodest,
|
||||
DepartureDate: timestamppb.New(departureDateTime),
|
||||
})
|
||||
if err != nil {
|
||||
log.Error().Err(err).Msg("error in grpc call to GetDriverJourneys")
|
||||
} else {
|
||||
solidarityTransportResults = slices.Collect(func(yield func(*gen.SolidarityTransportDriverJourney) bool) {
|
||||
for _, dj := range res.DriverJourneys {
|
||||
if a, ok := drivers[dj.DriverId].Data["archived"]; ok {
|
||||
if archived, ok := a.(bool); ok {
|
||||
if archived {
|
||||
continue
|
||||
}
|
||||
}
|
||||
}
|
||||
if dj.DriverId == solidarityTransportExcludeDriver {
|
||||
continue
|
||||
}
|
||||
// Skip drivers who already have bookings in the same group
|
||||
if excludedDriverIds[dj.DriverId] {
|
||||
continue
|
||||
}
|
||||
if !yield(dj) {
|
||||
return
|
||||
}
|
||||
}
|
||||
})
|
||||
sort.Slice(solidarityTransportResults, func(i, j int) bool {
|
||||
return solidarityTransportResults[i].DriverDistance < solidarityTransportResults[j].DriverDistance
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
// Get departure and destination addresses from properties
|
||||
var departureAddress, destinationAddress string
|
||||
if departureGeo.Properties != nil {
|
||||
if label, ok := departureGeo.Properties["label"].(string); ok {
|
||||
departureAddress = label
|
||||
}
|
||||
}
|
||||
if destinationGeo.Properties != nil {
|
||||
if label, ok := destinationGeo.Properties["label"].(string); ok {
|
||||
destinationAddress = label
|
||||
}
|
||||
}
|
||||
|
||||
// ORGANIZED CARPOOL
|
||||
if organizedCarpoolEnabled {
|
||||
radius := float64(5)
|
||||
organizedCarpoolResultsRes, err := h.services.GRPC.CarpoolService.DriverJourneys(ctx, &carpoolproto.DriverJourneysRequest{
|
||||
DepartureLat: departureGeo.Point().Lat(),
|
||||
DepartureLng: departureGeo.Point().Lon(),
|
||||
ArrivalLat: destinationGeo.Point().Lat(),
|
||||
ArrivalLng: destinationGeo.Point().Lon(),
|
||||
DepartureDate: timestamppb.New(departureDateTime),
|
||||
DepartureAddress: &departureAddress,
|
||||
ArrivalAddress: &destinationAddress,
|
||||
DepartureRadius: &radius,
|
||||
ArrivalRadius: &radius,
|
||||
})
|
||||
if err != nil {
|
||||
log.Error().Err(err).Msg("error retrieving organized carpools")
|
||||
} else {
|
||||
organizedCarpoolResults = organizedCarpoolResultsRes.DriverJourneys
|
||||
sort.Slice(organizedCarpoolResults, func(i, j int) bool {
|
||||
return *organizedCarpoolResults[i].Distance < *organizedCarpoolResults[j].Distance
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
var wg sync.WaitGroup
|
||||
// CARPOOL OPERATORS
|
||||
if carpoolOperatorsEnabled {
|
||||
carpools := make(chan *geojson.FeatureCollection)
|
||||
go h.services.InteropCarpool.Search(carpools, *departureGeo, *destinationGeo, departureDateTime)
|
||||
wg.Add(1)
|
||||
go func() {
|
||||
defer wg.Done()
|
||||
for c := range carpools {
|
||||
carpoolResults = append(carpoolResults, c)
|
||||
}
|
||||
}()
|
||||
}
|
||||
|
||||
// TRANSIT
|
||||
if transitEnabled {
|
||||
transitch := make(chan *transitous.Itinerary)
|
||||
go func(transitch chan *transitous.Itinerary, departure *geojson.Feature, destination *geojson.Feature, datetime *time.Time) {
|
||||
defer close(transitch)
|
||||
response, err := h.services.TransitRouting.PlanWithResponse(ctx, &transitous.PlanParams{
|
||||
FromPlace: fmt.Sprintf("%f,%f", departure.Point().Lat(), departure.Point().Lon()),
|
||||
ToPlace: fmt.Sprintf("%f,%f", destination.Point().Lat(), destination.Point().Lon()),
|
||||
Time: datetime,
|
||||
})
|
||||
if err != nil {
|
||||
log.Error().Err(err).Msg("error retrieving transit data from Transitous server")
|
||||
return
|
||||
}
|
||||
for _, i := range response.Itineraries {
|
||||
transitch <- &i
|
||||
}
|
||||
}(transitch, departureGeo, destinationGeo, &departureDateTime)
|
||||
wg.Add(1)
|
||||
go func() {
|
||||
defer wg.Done()
|
||||
paris, _ := time.LoadLocation("Europe/Paris")
|
||||
requestedDay := departureDateTime.In(paris).Truncate(24 * time.Hour)
|
||||
|
||||
for itinerary := range transitch {
|
||||
// Only include journeys that start on the requested day (in Paris timezone)
|
||||
if !itinerary.StartTime.IsZero() && !itinerary.EndTime.IsZero() {
|
||||
log.Info().
|
||||
Time("startTime", itinerary.StartTime).
|
||||
Time("endTime", itinerary.EndTime).
|
||||
Str("startTimezone", itinerary.StartTime.Location().String()).
|
||||
Str("endTimezone", itinerary.EndTime.Location().String()).
|
||||
Str("startTimeRFC3339", itinerary.StartTime.Format(time.RFC3339)).
|
||||
Str("endTimeRFC3339", itinerary.EndTime.Format(time.RFC3339)).
|
||||
Msg("Journey search - received transit itinerary from Transitous")
|
||||
|
||||
startInParis := itinerary.StartTime.In(paris)
|
||||
startDay := startInParis.Truncate(24 * time.Hour)
|
||||
|
||||
// Check if journey starts on the requested day
|
||||
if startDay.Equal(requestedDay) {
|
||||
transitResults = append(transitResults, itinerary)
|
||||
} else {
|
||||
log.Info().
|
||||
Str("requestedDay", requestedDay.Format("2006-01-02")).
|
||||
Str("startDay", startDay.Format("2006-01-02")).
|
||||
Msg("Journey search - filtered out transit journey (not on requested day)")
|
||||
}
|
||||
}
|
||||
}
|
||||
}()
|
||||
}
|
||||
|
||||
// VEHICLES
|
||||
if fleetVehiclesEnabled {
|
||||
vehiclech := make(chan fleetsstorage.Vehicle)
|
||||
go h.vehicleRequest(vehiclech, departureDateTime.Add(-24*time.Hour), departureDateTime.Add(168*time.Hour))
|
||||
wg.Add(1)
|
||||
go func() {
|
||||
defer wg.Done()
|
||||
for vehicle := range vehiclech {
|
||||
vehicleResults = append(vehicleResults, vehicle)
|
||||
}
|
||||
slices.SortFunc(vehicleResults, sorting.VehiclesByDistanceFrom(*departureGeo))
|
||||
}()
|
||||
}
|
||||
wg.Wait()
|
||||
|
||||
// KNOWLEDGE BASE
|
||||
if knowledgeBaseEnabled {
|
||||
departureGeoSearch, _ := h.services.Geography.GeoSearch(departureGeo)
|
||||
kbData := h.config.Get("knowledge_base")
|
||||
if kb, ok := kbData.([]any); ok {
|
||||
for _, sol := range kb {
|
||||
if solution, ok := sol.(map[string]any); ok {
|
||||
if g, ok := solution["geography"]; ok {
|
||||
if geography, ok := g.([]any); ok {
|
||||
for _, gg := range geography {
|
||||
if geog, ok := gg.(map[string]any); ok {
|
||||
if layer, ok := geog["layer"].(string); ok {
|
||||
code := geog["code"]
|
||||
geo, err := h.services.Geography.Find(layer, fmt.Sprintf("%v", code))
|
||||
if err == nil {
|
||||
geog["geography"] = geo
|
||||
geog["name"] = geo.Properties.MustString("nom")
|
||||
}
|
||||
if strings.Compare(fmt.Sprintf("%v", code), departureGeoSearch[layer].Properties.MustString("code")) == 0 {
|
||||
knowledgeBaseResults = append(knowledgeBaseResults, solution)
|
||||
break
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
return &SearchJourneysResult{
|
||||
CarpoolResults: carpoolResults,
|
||||
TransitResults: transitResults,
|
||||
VehicleResults: vehicleResults,
|
||||
Searched: searched,
|
||||
DriverJourneys: solidarityTransportResults,
|
||||
Drivers: drivers,
|
||||
OrganizedCarpools: organizedCarpoolResults,
|
||||
KnowledgeBaseResults: knowledgeBaseResults,
|
||||
}, nil
|
||||
}
|
||||
|
||||
func (h *ApplicationHandler) vehicleRequest(vehiclech chan fleetsstorage.Vehicle, start time.Time, end time.Time) {
|
||||
defer close(vehiclech)
|
||||
vehiclerequest := &fleets.GetVehiclesRequest{
|
||||
Namespaces: []string{"parcoursmob"},
|
||||
}
|
||||
vehicleresp, err := h.services.GRPC.Fleets.GetVehicles(context.TODO(), vehiclerequest)
|
||||
if err != nil {
|
||||
log.Error().Err(err).Msg("")
|
||||
return
|
||||
}
|
||||
for _, vehicle := range vehicleresp.Vehicles {
|
||||
v := vehicle.ToStorageType()
|
||||
if v.Free(start, end) {
|
||||
vehiclech <- v
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// SaveSearch saves a group's search to the saved-search microservice
|
||||
func (h *ApplicationHandler) SaveSearch(
|
||||
ctx context.Context,
|
||||
groupID string,
|
||||
departureDateTime time.Time,
|
||||
departureGeo *geojson.Feature,
|
||||
destinationGeo *geojson.Feature,
|
||||
additionalData map[string]interface{},
|
||||
) error {
|
||||
// Convert geojson.Feature to proto format
|
||||
var protoDepart, protoDest *savedsearchproto.SavedSearchGeoJsonFeature
|
||||
|
||||
log.Debug().
|
||||
Bool("departure_nil", departureGeo == nil).
|
||||
Bool("destination_nil", destinationGeo == nil).
|
||||
Msg("SaveSearch: checking geo features")
|
||||
|
||||
if departureGeo != nil {
|
||||
departureBytes, err := departureGeo.MarshalJSON()
|
||||
if err != nil {
|
||||
return fmt.Errorf("error marshaling departure: %w", err)
|
||||
}
|
||||
protoDepart = &savedsearchproto.SavedSearchGeoJsonFeature{
|
||||
Serialized: string(departureBytes),
|
||||
}
|
||||
log.Debug().Str("departure_json", string(departureBytes)).Msg("SaveSearch: departure converted")
|
||||
}
|
||||
|
||||
if destinationGeo != nil {
|
||||
destinationBytes, err := destinationGeo.MarshalJSON()
|
||||
if err != nil {
|
||||
return fmt.Errorf("error marshaling destination: %w", err)
|
||||
}
|
||||
protoDest = &savedsearchproto.SavedSearchGeoJsonFeature{
|
||||
Serialized: string(destinationBytes),
|
||||
}
|
||||
log.Debug().Str("destination_json", string(destinationBytes)).Msg("SaveSearch: destination converted")
|
||||
}
|
||||
|
||||
// Convert additional data to protobuf Struct
|
||||
var protoData *structpb.Struct
|
||||
if additionalData != nil && len(additionalData) > 0 {
|
||||
var err error
|
||||
protoData, err = structpb.NewStruct(additionalData)
|
||||
if err != nil {
|
||||
return fmt.Errorf("error converting additional data: %w", err)
|
||||
}
|
||||
}
|
||||
|
||||
// Handle zero time value
|
||||
var protoDateTime *timestamppb.Timestamp
|
||||
if !departureDateTime.IsZero() {
|
||||
protoDateTime = timestamppb.New(departureDateTime)
|
||||
}
|
||||
|
||||
// Call the saved-search service
|
||||
_, err := h.services.GRPC.SavedSearch.CreateSavedSearch(ctx, &savedsearchproto.CreateSavedSearchRequest{
|
||||
OwnerId: groupID,
|
||||
Departure: protoDepart,
|
||||
Destination: protoDest,
|
||||
Datetime: protoDateTime,
|
||||
Data: protoData,
|
||||
})
|
||||
if err != nil {
|
||||
return fmt.Errorf("error calling saved-search service: %w", err)
|
||||
}
|
||||
|
||||
log.Info().Str("group_id", groupID).Msg("search saved successfully")
|
||||
return nil
|
||||
}
|
||||
|
||||
// GetSavedSearchesByOwner retrieves saved searches for a group
|
||||
func (h *ApplicationHandler) GetSavedSearchesByOwner(
|
||||
ctx context.Context,
|
||||
groupID string,
|
||||
) ([]*savedsearchtypes.SavedSearch, error) {
|
||||
// Call the saved-search service to get searches by owner
|
||||
response, err := h.services.GRPC.SavedSearch.GetSavedSearchesByOwner(ctx, &savedsearchproto.GetSavedSearchesByOwnerRequest{
|
||||
OwnerId: groupID,
|
||||
})
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("error calling saved-search service: %w", err)
|
||||
}
|
||||
|
||||
// Convert protobuf searches to domain types
|
||||
var searches []*savedsearchtypes.SavedSearch
|
||||
for _, protoSearch := range response.SavedSearches {
|
||||
search, err := savedsearchtransformers.SavedSearchProtoToType(protoSearch)
|
||||
if err != nil {
|
||||
log.Error().Err(err).Str("search_id", protoSearch.Id).Msg("failed to convert saved search")
|
||||
continue
|
||||
}
|
||||
searches = append(searches, search)
|
||||
}
|
||||
|
||||
// Sort searches by datetime (earliest first)
|
||||
sort.Slice(searches, func(i, j int) bool {
|
||||
return searches[i].DateTime.Before(searches[j].DateTime)
|
||||
})
|
||||
|
||||
return searches, nil
|
||||
}
|
||||
|
||||
// DeleteSavedSearch deletes a saved search by ID for the specified owner
|
||||
func (h *ApplicationHandler) DeleteSavedSearch(
|
||||
ctx context.Context,
|
||||
searchID string,
|
||||
ownerID string,
|
||||
) error {
|
||||
// Call the saved-search service to delete the search
|
||||
_, err := h.services.GRPC.SavedSearch.DeleteSavedSearch(ctx, &savedsearchproto.DeleteSavedSearchRequest{
|
||||
Id: searchID,
|
||||
OwnerId: ownerID, // For authorization - ensure only the owner can delete
|
||||
})
|
||||
if err != nil {
|
||||
return fmt.Errorf("error calling saved-search service: %w", err)
|
||||
}
|
||||
|
||||
log.Info().Str("search_id", searchID).Str("owner_id", ownerID).Msg("saved search deleted successfully")
|
||||
return nil
|
||||
}
|
||||
247
core/application/members.go
Executable file
247
core/application/members.go
Executable file
@@ -0,0 +1,247 @@
|
||||
package application
|
||||
|
||||
import (
|
||||
"context"
|
||||
"fmt"
|
||||
"strings"
|
||||
"time"
|
||||
|
||||
formvalidators "git.coopgo.io/coopgo-apps/parcoursmob/core/utils/form-validators"
|
||||
groupsmanagement "git.coopgo.io/coopgo-platform/groups-management/grpcapi"
|
||||
mobilityaccounts "git.coopgo.io/coopgo-platform/mobility-accounts/grpcapi"
|
||||
mobilityaccountsstorage "git.coopgo.io/coopgo-platform/mobility-accounts/storage"
|
||||
"github.com/google/uuid"
|
||||
"google.golang.org/protobuf/types/known/structpb"
|
||||
)
|
||||
|
||||
type MembersResult struct {
|
||||
Accounts []mobilityaccountsstorage.Account
|
||||
CacheID string
|
||||
GroupsNames []string
|
||||
}
|
||||
|
||||
func (h *ApplicationHandler) GetMembers(ctx context.Context) (*MembersResult, error) {
|
||||
accounts, err := h.services.GetAccounts()
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
|
||||
var groupsNames []string
|
||||
|
||||
for _, v := range accounts {
|
||||
adminid := v.ID
|
||||
request := &mobilityaccounts.GetAccountRequest{
|
||||
Id: adminid,
|
||||
}
|
||||
|
||||
resp, err := h.services.GRPC.MobilityAccounts.GetAccount(ctx, request)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
|
||||
var allIds []string
|
||||
for _, v := range resp.Account.ToStorageType().Data["groups"].([]any) {
|
||||
s := fmt.Sprintf("%v", v)
|
||||
if !(strings.Contains(s, "admin")) {
|
||||
allIds = append(allIds, s)
|
||||
}
|
||||
}
|
||||
|
||||
reques := &groupsmanagement.GetGroupsBatchRequest{
|
||||
Groupids: allIds,
|
||||
}
|
||||
|
||||
res, err := h.services.GRPC.GroupsManagement.GetGroupsBatch(ctx, reques)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
|
||||
g := ""
|
||||
for _, group := range res.Groups {
|
||||
g += fmt.Sprintf("%v", group.ToStorageType().Data["name"]) + " "
|
||||
}
|
||||
groupsNames = append(groupsNames, g)
|
||||
}
|
||||
|
||||
cacheID := uuid.NewString()
|
||||
h.cache.PutWithTTL(cacheID, accounts, 1*time.Hour)
|
||||
|
||||
return &MembersResult{
|
||||
Accounts: accounts,
|
||||
CacheID: cacheID,
|
||||
GroupsNames: groupsNames,
|
||||
}, nil
|
||||
}
|
||||
|
||||
type MemberDataResult struct {
|
||||
Account mobilityaccountsstorage.Account
|
||||
GroupsNames []string
|
||||
}
|
||||
|
||||
func (h *ApplicationHandler) GetMemberData(ctx context.Context, memberID string) (*MemberDataResult, error) {
|
||||
request := &mobilityaccounts.GetAccountRequest{
|
||||
Id: memberID,
|
||||
}
|
||||
|
||||
resp, err := h.services.GRPC.MobilityAccounts.GetAccount(ctx, request)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
|
||||
// Security check: ensure this is actually a member account
|
||||
if resp.Account.Namespace != "parcoursmob" {
|
||||
return nil, fmt.Errorf("account %s is not a member (namespace: %s)", memberID, resp.Account.Namespace)
|
||||
}
|
||||
|
||||
var allIds []string
|
||||
for _, v := range resp.Account.ToStorageType().Data["groups"].([]any) {
|
||||
s := fmt.Sprintf("%v", v)
|
||||
if !(strings.Contains(s, "admin")) {
|
||||
allIds = append(allIds, s)
|
||||
}
|
||||
}
|
||||
|
||||
reques := &groupsmanagement.GetGroupsBatchRequest{
|
||||
Groupids: allIds,
|
||||
}
|
||||
|
||||
res, err := h.services.GRPC.GroupsManagement.GetGroupsBatch(ctx, reques)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
|
||||
var groupsNames []string
|
||||
for _, group := range res.Groups {
|
||||
g := fmt.Sprintf("%v", group.ToStorageType().Data["name"])
|
||||
groupsNames = append(groupsNames, g)
|
||||
}
|
||||
|
||||
return &MemberDataResult{
|
||||
Account: resp.Account.ToStorageType(),
|
||||
GroupsNames: groupsNames,
|
||||
}, nil
|
||||
}
|
||||
|
||||
type MemberResult struct {
|
||||
Account mobilityaccountsstorage.Account
|
||||
}
|
||||
|
||||
func (h *ApplicationHandler) GetMember(ctx context.Context, memberID string) (*MemberResult, error) {
|
||||
request := &mobilityaccounts.GetAccountRequest{
|
||||
Id: memberID,
|
||||
}
|
||||
|
||||
resp, err := h.services.GRPC.MobilityAccounts.GetAccount(ctx, request)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
|
||||
// Security check: ensure this is actually a member account
|
||||
if resp.Account.Namespace != "parcoursmob" {
|
||||
return nil, fmt.Errorf("account %s is not a member (namespace: %s)", memberID, resp.Account.Namespace)
|
||||
}
|
||||
|
||||
return &MemberResult{
|
||||
Account: resp.Account.ToStorageType(),
|
||||
}, nil
|
||||
}
|
||||
|
||||
func (h *ApplicationHandler) UpdateMember(ctx context.Context, memberID, firstName, lastName, email, phoneNumber, gender string) (string, error) {
|
||||
// Security check: verify the account exists and is a member
|
||||
getRequest := &mobilityaccounts.GetAccountRequest{
|
||||
Id: memberID,
|
||||
}
|
||||
getResp, err := h.services.GRPC.MobilityAccounts.GetAccount(ctx, getRequest)
|
||||
if err != nil {
|
||||
return "", err
|
||||
}
|
||||
if getResp.Account.Namespace != "parcoursmob" {
|
||||
return "", fmt.Errorf("account %s is not a member (namespace: %s)", memberID, getResp.Account.Namespace)
|
||||
}
|
||||
|
||||
dataMap := map[string]any{
|
||||
"first_name": firstName,
|
||||
"last_name": lastName,
|
||||
"email": email,
|
||||
"phone_number": phoneNumber,
|
||||
"gender": gender,
|
||||
}
|
||||
|
||||
// Validate the data
|
||||
formData := UserForm{
|
||||
FirstName: firstName,
|
||||
LastName: lastName,
|
||||
Email: email,
|
||||
PhoneNumber: phoneNumber,
|
||||
Gender: gender,
|
||||
}
|
||||
|
||||
validate := formvalidators.New()
|
||||
if err := validate.Struct(formData); err != nil {
|
||||
return "", err
|
||||
}
|
||||
|
||||
data, err := structpb.NewValue(dataMap)
|
||||
if err != nil {
|
||||
return "", err
|
||||
}
|
||||
|
||||
request := &mobilityaccounts.UpdateDataRequest{
|
||||
Account: &mobilityaccounts.Account{
|
||||
Id: memberID,
|
||||
Namespace: "parcoursmob",
|
||||
Data: data.GetStructValue(),
|
||||
},
|
||||
}
|
||||
|
||||
resp, err := h.services.GRPC.MobilityAccounts.UpdateData(ctx, request)
|
||||
if err != nil {
|
||||
return "", err
|
||||
}
|
||||
|
||||
return resp.Account.Id, nil
|
||||
}
|
||||
|
||||
type UserForm struct {
|
||||
FirstName string `json:"first_name" validate:"required"`
|
||||
LastName string `json:"last_name" validate:"required"`
|
||||
Email string `json:"email" validate:"required,email"`
|
||||
PhoneNumber string `json:"phone_number" `
|
||||
Address any `json:"address,omitempty"`
|
||||
Gender string `json:"gender"`
|
||||
}
|
||||
|
||||
type RegisterUserResult struct {
|
||||
UserID string
|
||||
}
|
||||
|
||||
func (h *ApplicationHandler) RegisterUser(ctx context.Context, user mobilityaccountsstorage.Account) (*RegisterUserResult, error) {
|
||||
account, err := mobilityaccounts.AccountFromStorageType(&user)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
|
||||
resp, err := h.services.GRPC.MobilityAccounts.Register(ctx, &mobilityaccounts.RegisterRequest{
|
||||
Account: account,
|
||||
})
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
|
||||
if g, ok := user.Metadata["import_in_group"]; ok {
|
||||
if group, ok := g.(string); ok {
|
||||
_, err = h.services.GRPC.GroupsManagement.Subscribe(ctx, &groupsmanagement.SubscribeRequest{
|
||||
Groupid: group,
|
||||
Memberid: resp.Account.Id,
|
||||
})
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
return &RegisterUserResult{
|
||||
UserID: resp.Account.Id,
|
||||
}, nil
|
||||
}
|
||||
|
||||
1481
core/application/organized-carpool.go
Normal file
1481
core/application/organized-carpool.go
Normal file
File diff suppressed because it is too large
Load Diff
41
core/application/sms.go
Normal file
41
core/application/sms.go
Normal file
@@ -0,0 +1,41 @@
|
||||
package application
|
||||
|
||||
import (
|
||||
"context"
|
||||
"errors"
|
||||
|
||||
"github.com/rs/zerolog/log"
|
||||
)
|
||||
|
||||
func (h *ApplicationHandler) SendSMS(ctx context.Context, beneficiaryID, message string) error {
|
||||
return h.GenerateSMS(beneficiaryID, message)
|
||||
}
|
||||
|
||||
func (h *ApplicationHandler) GenerateSMS(recipientid string, message string) error {
|
||||
recipient, err := h.services.GetAccount(recipientid)
|
||||
if err != nil {
|
||||
log.Error().Err(err).Msg("user not found")
|
||||
return err
|
||||
}
|
||||
|
||||
pn, ok := recipient.Data["phone_number"]
|
||||
if !ok {
|
||||
log.Error().Msg("Beneficiary doesn't have a phone number")
|
||||
return errors.New("missing phone number")
|
||||
}
|
||||
phoneNumber, ok := pn.(string)
|
||||
if !ok {
|
||||
log.Error().Msg("phone number type error")
|
||||
return errors.New("phone number type error")
|
||||
}
|
||||
|
||||
sender := h.config.GetString("service_name")
|
||||
|
||||
err = h.services.SMS.Send(phoneNumber, message, sender)
|
||||
if err != nil {
|
||||
log.Error().Err(err).Msg("cannot send SMS")
|
||||
return err
|
||||
}
|
||||
|
||||
return nil
|
||||
}
|
||||
1514
core/application/solidarity-transport.go
Normal file
1514
core/application/solidarity-transport.go
Normal file
File diff suppressed because it is too large
Load Diff
33
core/application/support.go
Executable file
33
core/application/support.go
Executable file
@@ -0,0 +1,33 @@
|
||||
package application
|
||||
|
||||
import (
|
||||
"context"
|
||||
"fmt"
|
||||
|
||||
"github.com/rs/zerolog/log"
|
||||
)
|
||||
|
||||
type Message struct {
|
||||
Content string
|
||||
}
|
||||
|
||||
func (h *ApplicationHandler) SendSupportMessage(ctx context.Context, comment, userEmail string) error {
|
||||
data := map[string]any{
|
||||
"key": comment,
|
||||
"user": userEmail,
|
||||
}
|
||||
|
||||
supportEmail := h.config.GetString("modules.support.email")
|
||||
if supportEmail == "" {
|
||||
supportEmail = "support@mobicoop.fr"
|
||||
}
|
||||
|
||||
log.Debug().Str("user_email", userEmail).Str("support_email", supportEmail).Msg("Sending support message")
|
||||
|
||||
if err := h.emailing.Send("support.request", supportEmail, data); err != nil {
|
||||
return fmt.Errorf("failed to send support email: %w", err)
|
||||
}
|
||||
|
||||
return nil
|
||||
}
|
||||
|
||||
600
core/application/vehicles-management.go
Executable file
600
core/application/vehicles-management.go
Executable file
@@ -0,0 +1,600 @@
|
||||
package application
|
||||
|
||||
import (
|
||||
"context"
|
||||
"fmt"
|
||||
"sort"
|
||||
"time"
|
||||
|
||||
"git.coopgo.io/coopgo-apps/parcoursmob/core/utils/identification"
|
||||
"git.coopgo.io/coopgo-apps/parcoursmob/core/utils/sorting"
|
||||
filestorage "git.coopgo.io/coopgo-apps/parcoursmob/core/utils/storage"
|
||||
fleets "git.coopgo.io/coopgo-platform/fleets/grpcapi"
|
||||
fleetsstorage "git.coopgo.io/coopgo-platform/fleets/storage"
|
||||
groupsmanagement "git.coopgo.io/coopgo-platform/groups-management/grpcapi"
|
||||
"git.coopgo.io/coopgo-platform/groups-management/storage"
|
||||
mobilityaccounts "git.coopgo.io/coopgo-platform/mobility-accounts/grpcapi"
|
||||
mobilityaccountsstorage "git.coopgo.io/coopgo-platform/mobility-accounts/storage"
|
||||
"github.com/google/uuid"
|
||||
"github.com/rs/zerolog/log"
|
||||
"google.golang.org/protobuf/types/known/structpb"
|
||||
"google.golang.org/protobuf/types/known/timestamppb"
|
||||
)
|
||||
|
||||
type VehiclesManagementOverviewResult struct {
|
||||
Vehicles []fleetsstorage.Vehicle
|
||||
VehiclesMap map[string]fleetsstorage.Vehicle
|
||||
DriversMap map[string]mobilityaccountsstorage.Account
|
||||
Bookings []fleetsstorage.Booking
|
||||
}
|
||||
|
||||
func (h *ApplicationHandler) GetVehiclesManagementOverview(ctx context.Context, groupID string) (*VehiclesManagementOverviewResult, error) {
|
||||
request := &fleets.GetVehiclesRequest{
|
||||
Namespaces: []string{"parcoursmob"},
|
||||
}
|
||||
resp, err := h.services.GRPC.Fleets.GetVehicles(ctx, request)
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("failed to get vehicles: %w", err)
|
||||
}
|
||||
|
||||
vehicles := []fleetsstorage.Vehicle{}
|
||||
bookings := []fleetsstorage.Booking{}
|
||||
vehiclesMap := map[string]fleetsstorage.Vehicle{}
|
||||
|
||||
for _, vehicle := range resp.Vehicles {
|
||||
if h.filterVehicleByGroup(vehicle, groupID) {
|
||||
v := vehicle.ToStorageType()
|
||||
vehicleBookings := []fleetsstorage.Booking{}
|
||||
for _, b := range v.Bookings {
|
||||
log.Debug().Any("booking", b).Msg("debug")
|
||||
if b.Status() != fleetsstorage.StatusOld {
|
||||
if !b.Deleted {
|
||||
bookings = append(bookings, b)
|
||||
}
|
||||
}
|
||||
if b.Unavailableto.After(time.Now()) {
|
||||
vehicleBookings = append(vehicleBookings, b)
|
||||
}
|
||||
}
|
||||
v.Bookings = vehicleBookings
|
||||
vehicles = append(vehicles, v)
|
||||
vehiclesMap[v.ID] = v
|
||||
}
|
||||
}
|
||||
|
||||
driversMap, _ := h.services.GetBeneficiariesMap()
|
||||
|
||||
sort.Sort(sorting.VehiclesByLicencePlate(vehicles))
|
||||
sort.Sort(sorting.BookingsByStartdate(bookings))
|
||||
|
||||
return &VehiclesManagementOverviewResult{
|
||||
Vehicles: vehicles,
|
||||
VehiclesMap: vehiclesMap,
|
||||
DriversMap: driversMap,
|
||||
Bookings: bookings,
|
||||
}, nil
|
||||
}
|
||||
|
||||
func (h *ApplicationHandler) filterVehicleByGroup(v *fleets.Vehicle, groupID string) bool {
|
||||
if groupID == "" {
|
||||
return false
|
||||
}
|
||||
|
||||
for _, n := range v.Administrators {
|
||||
if n == groupID {
|
||||
return true
|
||||
}
|
||||
}
|
||||
return false
|
||||
}
|
||||
|
||||
type VehiclesManagementBookingsListResult struct {
|
||||
VehiclesMap map[string]fleetsstorage.Vehicle
|
||||
DriversMap map[string]mobilityaccountsstorage.Account
|
||||
Bookings []fleetsstorage.Booking
|
||||
CacheID string
|
||||
}
|
||||
|
||||
func (h *ApplicationHandler) GetVehiclesManagementBookingsList(ctx context.Context, groupID, status, startDate, endDate string) (*VehiclesManagementBookingsListResult, error) {
|
||||
request := &fleets.GetVehiclesRequest{
|
||||
Namespaces: []string{"parcoursmob"},
|
||||
IncludeDeleted: true,
|
||||
}
|
||||
resp, err := h.services.GRPC.Fleets.GetVehicles(ctx, request)
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("failed to get vehicles: %w", err)
|
||||
}
|
||||
|
||||
bookings := []fleetsstorage.Booking{}
|
||||
vehiclesMap := map[string]fleetsstorage.Vehicle{}
|
||||
|
||||
// Parse start date filter
|
||||
var startdate time.Time
|
||||
if startDate != "" {
|
||||
if parsed, err := time.Parse("2006-01-02", startDate); err == nil {
|
||||
startdate = parsed
|
||||
}
|
||||
}
|
||||
|
||||
// Parse end date filter
|
||||
var enddate time.Time
|
||||
if endDate != "" {
|
||||
if parsed, err := time.Parse("2006-01-02", endDate); err == nil {
|
||||
enddate = parsed.Add(24 * time.Hour) // End of day
|
||||
}
|
||||
}
|
||||
|
||||
for _, vehicle := range resp.Vehicles {
|
||||
if h.filterVehicleByGroup(vehicle, groupID) {
|
||||
v := vehicle.ToStorageType()
|
||||
vehiclesMap[v.ID] = v
|
||||
for _, b := range v.Bookings {
|
||||
if v, ok := b.Data["administrator_unavailability"].(bool); !ok || !v {
|
||||
// Apply status filter
|
||||
if status != "" {
|
||||
bookingStatus := b.Status()
|
||||
statusInt := 0
|
||||
|
||||
if b.Deleted {
|
||||
statusInt = -2 // Use -2 for cancelled to distinguish from terminated
|
||||
} else {
|
||||
statusInt = bookingStatus
|
||||
}
|
||||
|
||||
// Map status string to int
|
||||
var filterStatusInt int
|
||||
switch status {
|
||||
case "FORTHCOMING":
|
||||
filterStatusInt = 1
|
||||
case "ONGOING":
|
||||
filterStatusInt = 0
|
||||
case "TERMINATED":
|
||||
filterStatusInt = -1
|
||||
case "CANCELLED":
|
||||
filterStatusInt = -2
|
||||
default:
|
||||
filterStatusInt = 999 // Invalid status, won't match anything
|
||||
}
|
||||
|
||||
if statusInt != filterStatusInt {
|
||||
continue
|
||||
}
|
||||
}
|
||||
|
||||
// Apply date filter (on startdate)
|
||||
if !startdate.IsZero() && b.Startdate.Before(startdate) {
|
||||
continue
|
||||
}
|
||||
if !enddate.IsZero() && b.Startdate.After(enddate) {
|
||||
continue
|
||||
}
|
||||
|
||||
bookings = append(bookings, b)
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
sort.Sort(sorting.BookingsByStartdate(bookings))
|
||||
|
||||
cacheID := uuid.NewString()
|
||||
h.cache.PutWithTTL(cacheID, bookings, 1*time.Hour)
|
||||
|
||||
driversMap, _ := h.services.GetBeneficiariesMap()
|
||||
|
||||
return &VehiclesManagementBookingsListResult{
|
||||
VehiclesMap: vehiclesMap,
|
||||
DriversMap: driversMap,
|
||||
Bookings: bookings,
|
||||
CacheID: cacheID,
|
||||
}, nil
|
||||
}
|
||||
|
||||
func (h *ApplicationHandler) CreateVehicle(ctx context.Context, name, vehicleType, informations, licencePlate, kilometers string, automatic bool, address map[string]any, otherProperties map[string]any) (string, error) {
|
||||
g := ctx.Value(identification.GroupKey)
|
||||
if g == nil {
|
||||
return "", fmt.Errorf("no group found in context")
|
||||
}
|
||||
group := g.(storage.Group)
|
||||
|
||||
dataMap := map[string]any{}
|
||||
if name != "" {
|
||||
dataMap["name"] = name
|
||||
}
|
||||
if address != nil {
|
||||
dataMap["address"] = address
|
||||
}
|
||||
if informations != "" {
|
||||
dataMap["informations"] = informations
|
||||
}
|
||||
if licencePlate != "" {
|
||||
dataMap["licence_plate"] = licencePlate
|
||||
}
|
||||
dataMap["automatic"] = automatic
|
||||
if kilometers != "" {
|
||||
dataMap["kilometers"] = kilometers
|
||||
}
|
||||
// Add other properties
|
||||
for key, value := range otherProperties {
|
||||
dataMap[key] = value
|
||||
}
|
||||
|
||||
data, err := structpb.NewValue(dataMap)
|
||||
if err != nil {
|
||||
return "", fmt.Errorf("failed to create data struct: %w", err)
|
||||
}
|
||||
|
||||
vehicle := &fleets.Vehicle{
|
||||
Id: uuid.NewString(),
|
||||
Namespace: "parcoursmob",
|
||||
Type: vehicleType,
|
||||
Administrators: []string{group.ID},
|
||||
Data: data.GetStructValue(),
|
||||
}
|
||||
|
||||
request := &fleets.AddVehicleRequest{
|
||||
Vehicle: vehicle,
|
||||
}
|
||||
|
||||
_, err = h.services.GRPC.Fleets.AddVehicle(ctx, request)
|
||||
if err != nil {
|
||||
return "", fmt.Errorf("failed to add vehicle: %w", err)
|
||||
}
|
||||
|
||||
return vehicle.Id, nil
|
||||
}
|
||||
|
||||
func (h *ApplicationHandler) GetVehicleTypes(ctx context.Context) ([]string, error) {
|
||||
return h.config.GetStringSlice("modules.fleets.vehicle_types"), nil
|
||||
}
|
||||
|
||||
type VehicleDisplayResult struct {
|
||||
Vehicle fleetsstorage.Vehicle
|
||||
Beneficiaries map[string]mobilityaccountsstorage.Account
|
||||
}
|
||||
|
||||
func (h *ApplicationHandler) GetVehicleDisplay(ctx context.Context, vehicleID string) (*VehicleDisplayResult, error) {
|
||||
request := &fleets.GetVehicleRequest{
|
||||
Vehicleid: vehicleID,
|
||||
}
|
||||
|
||||
resp, err := h.services.GRPC.Fleets.GetVehicle(ctx, request)
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("failed to get vehicle: %w", err)
|
||||
}
|
||||
|
||||
beneficiaries, err := h.services.GetBeneficiariesMap()
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("failed to get beneficiaries: %w", err)
|
||||
}
|
||||
|
||||
vehicle := resp.Vehicle.ToStorageType()
|
||||
|
||||
// Sort bookings by start date (most recent first)
|
||||
sort.Slice(vehicle.Bookings, func(i, j int) bool {
|
||||
return vehicle.Bookings[i].Startdate.After(vehicle.Bookings[j].Startdate)
|
||||
})
|
||||
|
||||
return &VehicleDisplayResult{
|
||||
Vehicle: vehicle,
|
||||
Beneficiaries: beneficiaries,
|
||||
}, nil
|
||||
}
|
||||
|
||||
func (h *ApplicationHandler) UpdateBooking(ctx context.Context, bookingID, startdate, enddate, unavailablefrom, unavailableto string) error {
|
||||
booking, err := h.services.GetBooking(bookingID)
|
||||
if err != nil {
|
||||
return fmt.Errorf("failed to get booking: %w", err)
|
||||
}
|
||||
|
||||
newbooking, _ := fleets.BookingFromStorageType(&booking)
|
||||
|
||||
if startdate != "" {
|
||||
newstartdate, _ := time.Parse("2006-01-02", startdate)
|
||||
newbooking.Startdate = timestamppb.New(newstartdate)
|
||||
|
||||
if newstartdate.Before(newbooking.Unavailablefrom.AsTime()) {
|
||||
newbooking.Unavailablefrom = timestamppb.New(newstartdate)
|
||||
}
|
||||
}
|
||||
|
||||
if enddate != "" {
|
||||
newenddate, _ := time.Parse("2006-01-02", enddate)
|
||||
newbooking.Enddate = timestamppb.New(newenddate)
|
||||
|
||||
if newenddate.After(newbooking.Unavailableto.AsTime()) || newenddate.Equal(newbooking.Unavailableto.AsTime()) {
|
||||
newbooking.Unavailableto = timestamppb.New(newenddate.Add(24 * time.Hour))
|
||||
}
|
||||
}
|
||||
|
||||
if unavailablefrom != "" {
|
||||
newunavailablefrom, _ := time.Parse("2006-01-02", unavailablefrom)
|
||||
newbooking.Unavailablefrom = timestamppb.New(newunavailablefrom)
|
||||
}
|
||||
|
||||
if unavailableto != "" {
|
||||
newunavailableto, _ := time.Parse("2006-01-02", unavailableto)
|
||||
newbooking.Unavailableto = timestamppb.New(newunavailableto)
|
||||
}
|
||||
|
||||
request := &fleets.UpdateBookingRequest{
|
||||
Booking: newbooking,
|
||||
}
|
||||
|
||||
_, err = h.services.GRPC.Fleets.UpdateBooking(ctx, request)
|
||||
return err
|
||||
}
|
||||
|
||||
type BookingDisplayResult struct {
|
||||
Booking fleetsstorage.Booking
|
||||
Vehicle fleetsstorage.Vehicle
|
||||
Beneficiary mobilityaccountsstorage.Account
|
||||
Group storage.Group
|
||||
Documents []filestorage.FileInfo
|
||||
FileTypesMap map[string]string
|
||||
Alternatives []any
|
||||
}
|
||||
|
||||
func (h *ApplicationHandler) GetBookingDisplay(ctx context.Context, bookingID string) (*BookingDisplayResult, error) {
|
||||
booking, err := h.services.GetBooking(bookingID)
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("failed to get booking: %w", err)
|
||||
}
|
||||
|
||||
beneficiary := mobilityaccountsstorage.Account{}
|
||||
if booking.Driver != "" {
|
||||
beneficiaryrequest := &mobilityaccounts.GetAccountRequest{
|
||||
Id: booking.Driver,
|
||||
}
|
||||
|
||||
beneficiaryresp, err := h.services.GRPC.MobilityAccounts.GetAccount(ctx, beneficiaryrequest)
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("failed to get beneficiary: %w", err)
|
||||
}
|
||||
beneficiary = beneficiaryresp.Account.ToStorageType()
|
||||
}
|
||||
|
||||
grouprequest := &groupsmanagement.GetGroupRequest{
|
||||
Id: booking.Vehicle.Administrators[0],
|
||||
}
|
||||
|
||||
groupresp, err := h.services.GRPC.GroupsManagement.GetGroup(ctx, grouprequest)
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("failed to get group: %w", err)
|
||||
}
|
||||
|
||||
alternativerequest := &fleets.GetVehiclesRequest{
|
||||
Namespaces: []string{"parcoursmob"},
|
||||
Types: []string{booking.Vehicle.Type},
|
||||
Administrators: booking.Vehicle.Administrators,
|
||||
AvailabilityFrom: timestamppb.New(booking.Startdate),
|
||||
AvailabilityTo: timestamppb.New(booking.Enddate.Add(24 * time.Hour)),
|
||||
}
|
||||
|
||||
alternativeresp, err := h.services.GRPC.Fleets.GetVehicles(ctx, alternativerequest)
|
||||
if err != nil {
|
||||
log.Error().Err(err).Msg("failed to get alternative vehicles")
|
||||
}
|
||||
|
||||
alternatives := []any{}
|
||||
for _, a := range alternativeresp.Vehicles {
|
||||
alternatives = append(alternatives, a.ToStorageType())
|
||||
}
|
||||
|
||||
documents := h.filestorage.List(filestorage.PREFIX_BOOKINGS + "/" + bookingID)
|
||||
fileTypesMap := h.config.GetStringMapString("storage.files.file_types")
|
||||
|
||||
return &BookingDisplayResult{
|
||||
Booking: booking,
|
||||
Vehicle: booking.Vehicle,
|
||||
Beneficiary: beneficiary,
|
||||
Group: groupresp.Group.ToStorageType(),
|
||||
Documents: documents,
|
||||
FileTypesMap: fileTypesMap,
|
||||
Alternatives: alternatives,
|
||||
}, nil
|
||||
}
|
||||
|
||||
func (h *ApplicationHandler) ChangeBookingVehicle(ctx context.Context, bookingID, newVehicleID string) error {
|
||||
booking, err := h.services.GetBooking(bookingID)
|
||||
if err != nil {
|
||||
return fmt.Errorf("failed to get booking: %w", err)
|
||||
}
|
||||
|
||||
booking.Vehicleid = newVehicleID
|
||||
b, _ := fleets.BookingFromStorageType(&booking)
|
||||
|
||||
request := &fleets.UpdateBookingRequest{
|
||||
Booking: b,
|
||||
}
|
||||
|
||||
_, err = h.services.GRPC.Fleets.UpdateBooking(ctx, request)
|
||||
return err
|
||||
}
|
||||
|
||||
func (h *ApplicationHandler) MakeVehicleUnavailable(ctx context.Context, vehicleID, unavailablefrom, unavailableto, comment, currentUserID string, currentUserClaims map[string]any) error {
|
||||
g := ctx.Value(identification.GroupKey)
|
||||
if g == nil {
|
||||
return fmt.Errorf("no group found in context")
|
||||
}
|
||||
currentGroup := g.(storage.Group)
|
||||
|
||||
unavailablefromTime, _ := time.Parse("2006-01-02", unavailablefrom)
|
||||
unavailabletoTime, _ := time.Parse("2006-01-02", unavailableto)
|
||||
|
||||
data := map[string]any{
|
||||
"comment": comment,
|
||||
"administrator_unavailability": true,
|
||||
"booked_by": map[string]any{
|
||||
"user": map[string]any{
|
||||
"id": currentUserID,
|
||||
"display_name": currentUserClaims["display_name"],
|
||||
},
|
||||
"group": map[string]any{
|
||||
"id": currentGroup.ID,
|
||||
"name": currentGroup.Data["name"],
|
||||
},
|
||||
},
|
||||
}
|
||||
|
||||
datapb, err := structpb.NewStruct(data)
|
||||
if err != nil {
|
||||
return fmt.Errorf("failed to create data struct: %w", err)
|
||||
}
|
||||
|
||||
booking := &fleets.Booking{
|
||||
Id: uuid.NewString(),
|
||||
Vehicleid: vehicleID,
|
||||
Unavailablefrom: timestamppb.New(unavailablefromTime),
|
||||
Unavailableto: timestamppb.New(unavailabletoTime),
|
||||
Data: datapb,
|
||||
}
|
||||
|
||||
request := &fleets.CreateBookingRequest{
|
||||
Booking: booking,
|
||||
}
|
||||
|
||||
_, err = h.services.GRPC.Fleets.CreateBooking(ctx, request)
|
||||
return err
|
||||
}
|
||||
|
||||
func (h *ApplicationHandler) DeleteBooking(ctx context.Context, bookingID string) error {
|
||||
request := &fleets.DeleteBookingRequest{
|
||||
Id: bookingID,
|
||||
}
|
||||
|
||||
_, err := h.services.GRPC.Fleets.DeleteBooking(ctx, request)
|
||||
return err
|
||||
}
|
||||
|
||||
func (h *ApplicationHandler) GetBookingForUnbooking(ctx context.Context, bookingID string) (fleetsstorage.Booking, error) {
|
||||
request := &fleets.GetBookingRequest{
|
||||
Bookingid: bookingID,
|
||||
}
|
||||
|
||||
resp, err := h.services.GRPC.Fleets.GetBooking(ctx, request)
|
||||
if err != nil {
|
||||
return fleetsstorage.Booking{}, fmt.Errorf("failed to get booking: %w", err)
|
||||
}
|
||||
|
||||
return resp.Booking.ToStorageType(), nil
|
||||
}
|
||||
|
||||
func (h *ApplicationHandler) UnbookVehicle(ctx context.Context, bookingID, motif, currentUserID string, currentUserClaims map[string]any, currentGroup any) error {
|
||||
group := currentGroup.(storage.Group)
|
||||
|
||||
// Prepare deletion metadata (microservice will add deleted_at automatically)
|
||||
deletionMetadata := map[string]any{
|
||||
"deleted_by": map[string]any{
|
||||
"user": map[string]any{
|
||||
"id": currentUserID,
|
||||
"display_name": currentUserClaims["first_name"].(string) + " " + currentUserClaims["last_name"].(string),
|
||||
"email": currentUserClaims["email"],
|
||||
},
|
||||
"group": map[string]any{
|
||||
"id": group.ID,
|
||||
"name": group.Data["name"],
|
||||
},
|
||||
},
|
||||
"reason": motif,
|
||||
}
|
||||
|
||||
deletionMetadataPb, err := structpb.NewStruct(deletionMetadata)
|
||||
if err != nil {
|
||||
return fmt.Errorf("failed to create deletion metadata: %w", err)
|
||||
}
|
||||
|
||||
// Use the microservice's delete endpoint with metadata
|
||||
deleteRequest := &fleets.DeleteBookingRequest{
|
||||
Id: bookingID,
|
||||
DeletionMetadata: deletionMetadataPb,
|
||||
}
|
||||
|
||||
_, err = h.services.GRPC.Fleets.DeleteBooking(ctx, deleteRequest)
|
||||
return err
|
||||
}
|
||||
|
||||
type VehicleForUpdateResult struct {
|
||||
Vehicle fleetsstorage.Vehicle
|
||||
VehicleTypes []string
|
||||
}
|
||||
|
||||
func (h *ApplicationHandler) GetVehicleForUpdate(ctx context.Context, vehicleID string) (*VehicleForUpdateResult, error) {
|
||||
request := &fleets.GetVehicleRequest{
|
||||
Vehicleid: vehicleID,
|
||||
}
|
||||
|
||||
resp, err := h.services.GRPC.Fleets.GetVehicle(ctx, request)
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("failed to get vehicle: %w", err)
|
||||
}
|
||||
|
||||
vehicleTypes := h.config.GetStringSlice("modules.fleets.vehicle_types")
|
||||
|
||||
return &VehicleForUpdateResult{
|
||||
Vehicle: resp.Vehicle.ToStorageType(),
|
||||
VehicleTypes: vehicleTypes,
|
||||
}, nil
|
||||
}
|
||||
|
||||
func (h *ApplicationHandler) UpdateVehicle(ctx context.Context, vehicleID, name, vehicleType, informations, licencePlate, kilometers string, automatic bool, address map[string]any, otherProperties map[string]any) (string, error) {
|
||||
getRequest := &fleets.GetVehicleRequest{
|
||||
Vehicleid: vehicleID,
|
||||
}
|
||||
|
||||
resp, err := h.services.GRPC.Fleets.GetVehicle(ctx, getRequest)
|
||||
if err != nil {
|
||||
return "", fmt.Errorf("failed to get vehicle: %w", err)
|
||||
}
|
||||
|
||||
// Start with existing data to preserve all fields
|
||||
dataMap := resp.Vehicle.Data.AsMap()
|
||||
if dataMap == nil {
|
||||
dataMap = map[string]any{}
|
||||
}
|
||||
|
||||
// Update with new values
|
||||
if name != "" {
|
||||
dataMap["name"] = name
|
||||
}
|
||||
if address != nil {
|
||||
dataMap["address"] = address
|
||||
}
|
||||
if informations != "" {
|
||||
dataMap["informations"] = informations
|
||||
}
|
||||
if licencePlate != "" {
|
||||
dataMap["licence_plate"] = licencePlate
|
||||
}
|
||||
if kilometers != "" {
|
||||
dataMap["kilometers"] = kilometers
|
||||
}
|
||||
dataMap["automatic"] = automatic
|
||||
// Add other properties
|
||||
for key, value := range otherProperties {
|
||||
dataMap[key] = value
|
||||
}
|
||||
|
||||
data, err := structpb.NewValue(dataMap)
|
||||
if err != nil {
|
||||
return "", fmt.Errorf("failed to create data struct: %w", err)
|
||||
}
|
||||
|
||||
updateRequest := &fleets.UpdateVehicleRequest{
|
||||
Vehicle: &fleets.Vehicle{
|
||||
Id: vehicleID,
|
||||
Namespace: resp.Vehicle.Namespace,
|
||||
Type: vehicleType,
|
||||
Administrators: resp.Vehicle.Administrators,
|
||||
Data: data.GetStructValue(),
|
||||
},
|
||||
}
|
||||
|
||||
updateResp, err := h.services.GRPC.Fleets.UpdateVehicle(ctx, updateRequest)
|
||||
if err != nil {
|
||||
return "", fmt.Errorf("failed to update vehicle: %w", err)
|
||||
}
|
||||
|
||||
return updateResp.Vehicle.Id, nil
|
||||
}
|
||||
|
||||
393
core/application/vehicles.go
Executable file
393
core/application/vehicles.go
Executable file
@@ -0,0 +1,393 @@
|
||||
package application
|
||||
|
||||
import (
|
||||
"context"
|
||||
"encoding/json"
|
||||
"fmt"
|
||||
"io"
|
||||
"slices"
|
||||
"sort"
|
||||
"strings"
|
||||
"time"
|
||||
|
||||
"git.coopgo.io/coopgo-apps/parcoursmob/core/utils/sorting"
|
||||
filestorage "git.coopgo.io/coopgo-apps/parcoursmob/core/utils/storage"
|
||||
fleets "git.coopgo.io/coopgo-platform/fleets/grpcapi"
|
||||
"git.coopgo.io/coopgo-platform/fleets/storage"
|
||||
groupsmanagement "git.coopgo.io/coopgo-platform/groups-management/grpcapi"
|
||||
groupsmanagementstorage "git.coopgo.io/coopgo-platform/groups-management/storage"
|
||||
mobilityaccounts "git.coopgo.io/coopgo-platform/mobility-accounts/grpcapi"
|
||||
mobilityaccountsstorage "git.coopgo.io/coopgo-platform/mobility-accounts/storage"
|
||||
"github.com/google/uuid"
|
||||
"github.com/paulmach/orb/geojson"
|
||||
"github.com/rs/zerolog/log"
|
||||
"google.golang.org/protobuf/types/known/structpb"
|
||||
"google.golang.org/protobuf/types/known/timestamppb"
|
||||
)
|
||||
|
||||
type VehiclesSearchResult struct {
|
||||
Vehicles []storage.Vehicle
|
||||
Beneficiary mobilityaccountsstorage.Account
|
||||
BeneficiaryDocuments []filestorage.FileInfo
|
||||
Groups map[string]any
|
||||
Searched bool
|
||||
StartDate string
|
||||
EndDate string
|
||||
VehicleType string
|
||||
Automatic bool
|
||||
MandatoryDocuments []string
|
||||
FileTypesMap map[string]string
|
||||
VehicleTypes []string
|
||||
Beneficiaries []mobilityaccountsstorage.Account
|
||||
}
|
||||
|
||||
func (h *ApplicationHandler) SearchVehicles(ctx context.Context, beneficiaryID, startDateStr, endDateStr, vehicleType string, automatic bool) (*VehiclesSearchResult, error) {
|
||||
var beneficiary mobilityaccountsstorage.Account
|
||||
beneficiarydocuments := []filestorage.FileInfo{}
|
||||
vehicles := []storage.Vehicle{}
|
||||
searched := false
|
||||
administrators := []string{}
|
||||
|
||||
startdate, err := time.Parse("2006-01-02", startDateStr)
|
||||
if err != nil {
|
||||
startdate = time.Time{}
|
||||
}
|
||||
enddate, err := time.Parse("2006-01-02", endDateStr)
|
||||
if err != nil {
|
||||
enddate = time.Time{}
|
||||
}
|
||||
|
||||
if beneficiaryID != "" && startdate.After(time.Now().Add(-24*time.Hour)) && enddate.After(startdate) {
|
||||
// Handler form
|
||||
searched = true
|
||||
|
||||
requestbeneficiary := &mobilityaccounts.GetAccountRequest{
|
||||
Id: beneficiaryID,
|
||||
}
|
||||
|
||||
respbeneficiary, err := h.services.GRPC.MobilityAccounts.GetAccount(ctx, requestbeneficiary)
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("failed to get beneficiary: %w", err)
|
||||
}
|
||||
|
||||
beneficiary = respbeneficiary.Account.ToStorageType()
|
||||
|
||||
request := &fleets.GetVehiclesRequest{
|
||||
Namespaces: []string{"parcoursmob"},
|
||||
AvailabilityFrom: timestamppb.New(startdate),
|
||||
AvailabilityTo: timestamppb.New(enddate),
|
||||
}
|
||||
|
||||
if vehicleType != "" {
|
||||
request.Types = []string{vehicleType}
|
||||
}
|
||||
|
||||
resp, err := h.services.GRPC.Fleets.GetVehicles(ctx, request)
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("failed to get vehicles: %w", err)
|
||||
}
|
||||
|
||||
for _, vehicle := range resp.Vehicles {
|
||||
v := vehicle.ToStorageType()
|
||||
|
||||
if vehicleType == "Voiture" && automatic {
|
||||
if auto, ok := v.Data["automatic"].(bool); !ok || !auto {
|
||||
continue
|
||||
}
|
||||
}
|
||||
|
||||
adminfound := false
|
||||
for _, a := range administrators {
|
||||
if a == v.Administrators[0] {
|
||||
adminfound = true
|
||||
break
|
||||
}
|
||||
}
|
||||
if !adminfound {
|
||||
administrators = append(administrators, v.Administrators[0])
|
||||
}
|
||||
|
||||
vehicles = append(vehicles, v)
|
||||
}
|
||||
|
||||
// Sort vehicles if beneficiary address is set
|
||||
if beneficiaryAddress, ok := beneficiary.Data["address"]; ok {
|
||||
beneficiaryAddressJson, err := json.Marshal(beneficiaryAddress)
|
||||
if err == nil {
|
||||
beneficiaryAddressGeojson, err := geojson.UnmarshalFeature(beneficiaryAddressJson)
|
||||
if err == nil {
|
||||
slices.SortFunc(vehicles, sorting.VehiclesByDistanceFrom(*beneficiaryAddressGeojson))
|
||||
} else {
|
||||
log.Error().Err(err).Msg("error transforming beneficiary address to GeoJSON")
|
||||
}
|
||||
} else {
|
||||
log.Error().Err(err).Msg("error transforming beneficiary address to JSON")
|
||||
}
|
||||
}
|
||||
|
||||
beneficiarydocuments = h.filestorage.List(filestorage.PREFIX_BENEFICIARIES + "/" + beneficiary.ID)
|
||||
}
|
||||
|
||||
accounts, err := h.services.GetBeneficiariesMap()
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("failed to get beneficiaries: %w", err)
|
||||
}
|
||||
|
||||
// Convert map to slice for compatibility
|
||||
beneficiaries := make([]mobilityaccountsstorage.Account, 0, len(accounts))
|
||||
for _, account := range accounts {
|
||||
beneficiaries = append(beneficiaries, account)
|
||||
}
|
||||
|
||||
groups := map[string]any{}
|
||||
if len(administrators) > 0 {
|
||||
admingroups, err := h.services.GRPC.GroupsManagement.GetGroupsBatch(ctx, &groupsmanagement.GetGroupsBatchRequest{
|
||||
Groupids: administrators,
|
||||
})
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("failed to get admin groups: %w", err)
|
||||
}
|
||||
|
||||
for _, g := range admingroups.Groups {
|
||||
groups[g.Id] = g.ToStorageType()
|
||||
}
|
||||
}
|
||||
|
||||
sort.Sort(sorting.BeneficiariesByName(beneficiaries))
|
||||
|
||||
mandatoryDocuments := h.config.GetStringSlice("modules.fleets.booking_documents.mandatory")
|
||||
fileTypesMap := h.config.GetStringMapString("storage.files.file_types")
|
||||
vehicleTypes := h.config.GetStringSlice("modules.fleets.vehicle_types")
|
||||
|
||||
return &VehiclesSearchResult{
|
||||
Vehicles: vehicles,
|
||||
Beneficiary: beneficiary,
|
||||
BeneficiaryDocuments: beneficiarydocuments,
|
||||
Groups: groups,
|
||||
Searched: searched,
|
||||
StartDate: startDateStr,
|
||||
EndDate: endDateStr,
|
||||
VehicleType: vehicleType,
|
||||
Automatic: automatic,
|
||||
MandatoryDocuments: mandatoryDocuments,
|
||||
FileTypesMap: fileTypesMap,
|
||||
VehicleTypes: vehicleTypes,
|
||||
Beneficiaries: beneficiaries,
|
||||
}, nil
|
||||
}
|
||||
|
||||
type BookVehicleResult struct {
|
||||
BookingID string
|
||||
}
|
||||
|
||||
func (h *ApplicationHandler) BookVehicle(ctx context.Context, vehicleID, beneficiaryID, startDateStr, endDateStr string, documents map[string]io.Reader, documentHeaders map[string]string, existingDocs map[string]string, currentUserID string, currentUserClaims map[string]any, currentGroup any) (*BookVehicleResult, error) {
|
||||
group := currentGroup.(groupsmanagementstorage.Group)
|
||||
|
||||
vehicle, err := h.services.GRPC.Fleets.GetVehicle(ctx, &fleets.GetVehicleRequest{
|
||||
Vehicleid: vehicleID,
|
||||
})
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("vehicle not found: %w", err)
|
||||
}
|
||||
|
||||
startdate, err := time.Parse("2006-01-02", startDateStr)
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("invalid start date: %w", err)
|
||||
}
|
||||
enddate, err := time.Parse("2006-01-02", endDateStr)
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("invalid end date: %w", err)
|
||||
}
|
||||
|
||||
data := map[string]any{
|
||||
"booked_by": map[string]any{
|
||||
"user": map[string]any{
|
||||
"id": currentUserID,
|
||||
"display_name": fmt.Sprintf("%s %s", currentUserClaims["first_name"], currentUserClaims["last_name"]),
|
||||
},
|
||||
"group": map[string]any{
|
||||
"id": group.ID,
|
||||
"name": group.Data["name"],
|
||||
},
|
||||
},
|
||||
}
|
||||
datapb, err := structpb.NewStruct(data)
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("failed to create booking metadata: %w", err)
|
||||
}
|
||||
|
||||
bookingID := uuid.NewString()
|
||||
booking := &fleets.Booking{
|
||||
Id: bookingID,
|
||||
Vehicleid: vehicleID,
|
||||
Driver: beneficiaryID,
|
||||
Startdate: timestamppb.New(startdate),
|
||||
Enddate: timestamppb.New(enddate),
|
||||
Unavailablefrom: timestamppb.New(startdate),
|
||||
Unavailableto: timestamppb.New(enddate.Add(72 * time.Hour)),
|
||||
Data: datapb,
|
||||
}
|
||||
|
||||
request := &fleets.CreateBookingRequest{
|
||||
Booking: booking,
|
||||
}
|
||||
|
||||
// Handle document uploads
|
||||
for docType, file := range documents {
|
||||
fileid := uuid.NewString()
|
||||
filename := documentHeaders[docType]
|
||||
|
||||
metadata := map[string]string{
|
||||
"type": docType,
|
||||
"name": filename,
|
||||
}
|
||||
|
||||
if err := h.filestorage.Put(file, filestorage.PREFIX_BOOKINGS, fmt.Sprintf("%s/%s_%s", bookingID, fileid, filename), -1, metadata); err != nil {
|
||||
return nil, fmt.Errorf("failed to upload document %s: %w", docType, err)
|
||||
}
|
||||
}
|
||||
|
||||
// Handle existing documents
|
||||
for docType, existingFile := range existingDocs {
|
||||
path := strings.Split(existingFile, "/")
|
||||
if err := h.filestorage.Copy(existingFile, fmt.Sprintf("%s/%s/%s", filestorage.PREFIX_BOOKINGS, bookingID, path[len(path)-1])); err != nil {
|
||||
return nil, fmt.Errorf("failed to copy existing document %s: %w", docType, err)
|
||||
}
|
||||
}
|
||||
|
||||
_, err = h.services.GRPC.Fleets.CreateBooking(ctx, request)
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("failed to create booking: %w", err)
|
||||
}
|
||||
|
||||
// NOTIFY GROUP MEMBERS
|
||||
members, _, err := h.groupmembers(vehicle.Vehicle.Administrators[0])
|
||||
if err != nil {
|
||||
log.Error().Err(err).Msg("failed to get group members for notification")
|
||||
} else {
|
||||
for _, m := range members {
|
||||
if email, ok := m.Data["email"].(string); ok {
|
||||
h.emailing.Send("fleets.bookings.creation_admin_alert", email, map[string]string{
|
||||
"bookingid": bookingID,
|
||||
})
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
return &BookVehicleResult{
|
||||
BookingID: bookingID,
|
||||
}, nil
|
||||
}
|
||||
|
||||
|
||||
|
||||
|
||||
type VehicleBookingDetailsResult struct {
|
||||
Booking storage.Booking
|
||||
Vehicle storage.Vehicle
|
||||
Beneficiary mobilityaccountsstorage.Account
|
||||
Group groupsmanagementstorage.Group
|
||||
Documents []filestorage.FileInfo
|
||||
FileTypesMap map[string]string
|
||||
}
|
||||
|
||||
func (h *ApplicationHandler) GetVehicleBookingDetails(ctx context.Context, bookingID string) (*VehicleBookingDetailsResult, error) {
|
||||
request := &fleets.GetBookingRequest{
|
||||
Bookingid: bookingID,
|
||||
}
|
||||
resp, err := h.services.GRPC.Fleets.GetBooking(ctx, request)
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("failed to get booking: %w", err)
|
||||
}
|
||||
|
||||
booking := resp.Booking.ToStorageType()
|
||||
|
||||
beneficiaryrequest := &mobilityaccounts.GetAccountRequest{
|
||||
Id: booking.Driver,
|
||||
}
|
||||
|
||||
beneficiaryresp, err := h.services.GRPC.MobilityAccounts.GetAccount(ctx, beneficiaryrequest)
|
||||
if err != nil {
|
||||
beneficiaryresp = &mobilityaccounts.GetAccountResponse{
|
||||
Account: &mobilityaccounts.Account{},
|
||||
}
|
||||
}
|
||||
|
||||
grouprequest := &groupsmanagement.GetGroupRequest{
|
||||
Id: booking.Vehicle.Administrators[0],
|
||||
}
|
||||
|
||||
groupresp, err := h.services.GRPC.GroupsManagement.GetGroup(ctx, grouprequest)
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("failed to get group: %w", err)
|
||||
}
|
||||
|
||||
documents := h.filestorage.List(filestorage.PREFIX_BOOKINGS + "/" + bookingID)
|
||||
fileTypesMap := h.config.GetStringMapString("storage.files.file_types")
|
||||
|
||||
return &VehicleBookingDetailsResult{
|
||||
Booking: booking,
|
||||
Vehicle: booking.Vehicle,
|
||||
Beneficiary: beneficiaryresp.Account.ToStorageType(),
|
||||
Group: groupresp.Group.ToStorageType(),
|
||||
Documents: documents,
|
||||
FileTypesMap: fileTypesMap,
|
||||
}, nil
|
||||
}
|
||||
|
||||
type VehicleBookingsListResult struct {
|
||||
Bookings []storage.Booking
|
||||
VehiclesMap map[string]storage.Vehicle
|
||||
GroupsMap map[string]groupsmanagementstorage.Group
|
||||
}
|
||||
|
||||
func (h *ApplicationHandler) GetVehicleBookingsList(ctx context.Context, groupID string) (*VehicleBookingsListResult, error) {
|
||||
request := &fleets.GetBookingsRequest{}
|
||||
resp, err := h.services.GRPC.Fleets.GetBookings(ctx, request)
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("failed to get bookings: %w", err)
|
||||
}
|
||||
|
||||
bookings := []storage.Booking{}
|
||||
|
||||
for _, b := range resp.Bookings {
|
||||
booking := b.ToStorageType()
|
||||
if b1, ok := booking.Data["booked_by"].(map[string]any); ok {
|
||||
if b2, ok := b1["group"].(map[string]any); ok {
|
||||
if b2["id"] == groupID {
|
||||
bookings = append(bookings, booking)
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
vehiclesMap, err := h.services.GetVehiclesMap()
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("failed to get vehicles map: %w", err)
|
||||
}
|
||||
|
||||
groupsMap, err := h.services.GetGroupsMap()
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("failed to get groups map: %w", err)
|
||||
}
|
||||
|
||||
return &VehicleBookingsListResult{
|
||||
Bookings: bookings,
|
||||
VehiclesMap: vehiclesMap,
|
||||
GroupsMap: groupsMap,
|
||||
}, nil
|
||||
}
|
||||
|
||||
func (h *ApplicationHandler) GetBookingDocument(ctx context.Context, bookingID, document string) (io.Reader, string, error) {
|
||||
file, info, err := h.filestorage.Get(filestorage.PREFIX_BOOKINGS, fmt.Sprintf("%s/%s", bookingID, document))
|
||||
if err != nil {
|
||||
return nil, "", fmt.Errorf("failed to get document: %w", err)
|
||||
}
|
||||
|
||||
return file, info.ContentType, nil
|
||||
}
|
||||
|
||||
// Helper method to expose config to web handlers
|
||||
func (h *ApplicationHandler) GetConfig() interface{} {
|
||||
return h.config
|
||||
}
|
||||
146
core/application/wallets.go
Normal file
146
core/application/wallets.go
Normal file
@@ -0,0 +1,146 @@
|
||||
package application
|
||||
|
||||
import (
|
||||
"context"
|
||||
"time"
|
||||
|
||||
"git.coopgo.io/coopgo-platform/mobility-accounts/grpcapi"
|
||||
mobilityaccountsstorage "git.coopgo.io/coopgo-platform/mobility-accounts/storage"
|
||||
"github.com/rs/zerolog/log"
|
||||
)
|
||||
|
||||
func (h *ApplicationHandler) CreditWallet(ctx context.Context, userid string, amount float64, paymentMethod string, description string) error {
|
||||
account, err := h.services.GetAccount(userid)
|
||||
if err != nil {
|
||||
log.Error().Err(err).Msg("could not retrieve account")
|
||||
return err
|
||||
}
|
||||
|
||||
// Initialize wallet if it doesn't exist
|
||||
if account.Data["wallet"] == nil {
|
||||
account.Data["wallet"] = float64(0)
|
||||
}
|
||||
|
||||
// Initialize wallet history if it doesn't exist
|
||||
if account.Data["wallet_history"] == nil {
|
||||
account.Data["wallet_history"] = []map[string]interface{}{}
|
||||
}
|
||||
|
||||
// Determine operation type based on amount sign
|
||||
operationType := "credit"
|
||||
if amount < 0 {
|
||||
operationType = "debit"
|
||||
}
|
||||
|
||||
// Create wallet operation record
|
||||
operation := map[string]interface{}{
|
||||
"timestamp": time.Now().Format(time.RFC3339),
|
||||
"amount": amount,
|
||||
"payment_method": paymentMethod,
|
||||
"description": description,
|
||||
"operation_type": operationType,
|
||||
}
|
||||
|
||||
// Add operation to history
|
||||
var history []map[string]interface{}
|
||||
if existingHistory, ok := account.Data["wallet_history"].([]interface{}); ok {
|
||||
// Convert []interface{} to []map[string]interface{}
|
||||
for _, item := range existingHistory {
|
||||
if historyItem, ok := item.(map[string]interface{}); ok {
|
||||
history = append(history, historyItem)
|
||||
}
|
||||
}
|
||||
} else if existingHistory, ok := account.Data["wallet_history"].([]map[string]interface{}); ok {
|
||||
history = existingHistory
|
||||
}
|
||||
|
||||
history = append(history, operation)
|
||||
account.Data["wallet_history"] = history
|
||||
|
||||
log.Debug().
|
||||
Str("userid", userid).
|
||||
Float64("amount", amount).
|
||||
Str("paymentMethod", paymentMethod).
|
||||
Str("description", description).
|
||||
Int("historyCount", len(history)).
|
||||
Msg("Adding operation to wallet history")
|
||||
|
||||
// Note: wallet balance is NOT updated here - it remains as initial amount
|
||||
// Balance is calculated from initial amount + sum of all operations
|
||||
|
||||
accountproto, err := grpcapi.AccountFromStorageType(&account)
|
||||
if err != nil {
|
||||
log.Error().Err(err).Msg("account type transformation issue")
|
||||
return err
|
||||
}
|
||||
|
||||
_, err = h.services.GRPC.MobilityAccounts.UpdateData(ctx, &grpcapi.UpdateDataRequest{
|
||||
Account: accountproto,
|
||||
})
|
||||
if err != nil {
|
||||
log.Error().Err(err).Msg("account update issue")
|
||||
return err
|
||||
}
|
||||
|
||||
log.Info().
|
||||
Str("userid", userid).
|
||||
Float64("amount", amount).
|
||||
Str("payment_method", paymentMethod).
|
||||
Str("description", description).
|
||||
Msg("Wallet credited successfully")
|
||||
|
||||
return nil
|
||||
}
|
||||
|
||||
// calculateWalletBalance calculates the current wallet balance from initial amount + all operations
|
||||
func (h *ApplicationHandler) calculateWalletBalance(account mobilityaccountsstorage.Account) float64 {
|
||||
// Return 0 if account data is nil
|
||||
if account.Data == nil {
|
||||
log.Debug().Msg("calculateWalletBalance: account.Data is nil, returning 0")
|
||||
return float64(0)
|
||||
}
|
||||
|
||||
// Get initial wallet amount (default to 0 if not set)
|
||||
initialAmount := float64(0)
|
||||
if walletValue, exists := account.Data["wallet"]; exists && walletValue != nil {
|
||||
if val, ok := walletValue.(float64); ok {
|
||||
initialAmount = val
|
||||
}
|
||||
}
|
||||
|
||||
// Calculate total from all operations
|
||||
operationsTotal := float64(0)
|
||||
operationCount := 0
|
||||
if historyValue, exists := account.Data["wallet_history"]; exists && historyValue != nil {
|
||||
var operations []map[string]interface{}
|
||||
|
||||
// Handle both []interface{} and []map[string]interface{} types
|
||||
if history, ok := historyValue.([]interface{}); ok {
|
||||
for _, item := range history {
|
||||
if operation, ok := item.(map[string]interface{}); ok {
|
||||
operations = append(operations, operation)
|
||||
}
|
||||
}
|
||||
} else if history, ok := historyValue.([]map[string]interface{}); ok {
|
||||
operations = history
|
||||
}
|
||||
|
||||
for _, operation := range operations {
|
||||
if amount, ok := operation["amount"].(float64); ok {
|
||||
operationsTotal += amount
|
||||
operationCount++
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
result := initialAmount + operationsTotal
|
||||
log.Debug().
|
||||
Str("accountId", account.ID).
|
||||
Float64("initialAmount", initialAmount).
|
||||
Float64("operationsTotal", operationsTotal).
|
||||
Int("operationCount", operationCount).
|
||||
Float64("result", result).
|
||||
Msg("calculateWalletBalance")
|
||||
|
||||
return result
|
||||
}
|
||||
74
core/utils/cache/cache.go
vendored
Normal file
74
core/utils/cache/cache.go
vendored
Normal file
@@ -0,0 +1,74 @@
|
||||
package cache
|
||||
|
||||
import (
|
||||
"encoding/json"
|
||||
"strconv"
|
||||
|
||||
"git.coopgo.io/coopgo-apps/parcoursmob/core/utils/storage"
|
||||
"github.com/rs/zerolog/log"
|
||||
)
|
||||
|
||||
type CacheService struct {
|
||||
cache storage.CacheHandler
|
||||
}
|
||||
|
||||
func NewCacheService(cache storage.CacheHandler) *CacheService {
|
||||
return &CacheService{cache: cache}
|
||||
}
|
||||
|
||||
type GetCacheResult struct {
|
||||
Data []byte
|
||||
}
|
||||
|
||||
func (s *CacheService) GetCacheData(cacheID string, limitsMin, limitsMax *int) (*GetCacheResult, error) {
|
||||
d, err := s.cache.Get(cacheID)
|
||||
if err != nil {
|
||||
log.Error().Err(err).Msg("")
|
||||
return nil, err
|
||||
}
|
||||
|
||||
var data []any
|
||||
if val, ok := d.([]any); ok {
|
||||
data = val
|
||||
} else {
|
||||
data = []any{d}
|
||||
}
|
||||
|
||||
result := data
|
||||
if limitsMin != nil {
|
||||
min := *limitsMin
|
||||
if limitsMax != nil {
|
||||
max := *limitsMax
|
||||
if max > len(data) {
|
||||
result = data[min:]
|
||||
} else {
|
||||
result = data[min:max]
|
||||
}
|
||||
} else {
|
||||
result = data[min:]
|
||||
}
|
||||
}
|
||||
|
||||
j, err := json.Marshal(result)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
|
||||
return &GetCacheResult{
|
||||
Data: j,
|
||||
}, nil
|
||||
}
|
||||
|
||||
func ParseLimits(limitsMinStr, limitsMaxStr string) (limitsMin, limitsMax *int) {
|
||||
if limitsMinStr != "" {
|
||||
if min, err := strconv.Atoi(limitsMinStr); err == nil {
|
||||
limitsMin = &min
|
||||
}
|
||||
}
|
||||
if limitsMaxStr != "" {
|
||||
if max, err := strconv.Atoi(limitsMaxStr); err == nil {
|
||||
limitsMax = &max
|
||||
}
|
||||
}
|
||||
return
|
||||
}
|
||||
17
core/utils/gender/gender.go
Normal file
17
core/utils/gender/gender.go
Normal file
@@ -0,0 +1,17 @@
|
||||
package gender
|
||||
|
||||
// ISO5218ToString converts ISO 5218 gender codes to French text labels
|
||||
func ISO5218ToString(value string) string {
|
||||
switch value {
|
||||
case "0":
|
||||
return "Inconnu"
|
||||
case "1":
|
||||
return "Masculin"
|
||||
case "2":
|
||||
return "Féminin"
|
||||
case "9":
|
||||
return "Sans objet"
|
||||
default:
|
||||
return value
|
||||
}
|
||||
}
|
||||
45
core/utils/geo/geo.go
Normal file
45
core/utils/geo/geo.go
Normal file
@@ -0,0 +1,45 @@
|
||||
package geo
|
||||
|
||||
import (
|
||||
"io"
|
||||
"net/http"
|
||||
|
||||
"github.com/paulmach/orb/geojson"
|
||||
"github.com/rs/zerolog/log"
|
||||
)
|
||||
|
||||
type GeoService struct {
|
||||
geoType string
|
||||
baseURL string
|
||||
autocompleteURL string
|
||||
}
|
||||
|
||||
func NewGeoService(geoType, baseURL, autocompleteEndpoint string) *GeoService {
|
||||
return &GeoService{
|
||||
geoType: geoType,
|
||||
baseURL: baseURL,
|
||||
autocompleteURL: baseURL + autocompleteEndpoint,
|
||||
}
|
||||
}
|
||||
|
||||
func (s *GeoService) Autocomplete(text string) (*geojson.FeatureCollection, error) {
|
||||
resp, err := http.Get(s.autocompleteURL + text)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
defer resp.Body.Close()
|
||||
|
||||
body, err := io.ReadAll(resp.Body)
|
||||
if err != nil {
|
||||
log.Error().Err(err).Msg("Failed to read response body")
|
||||
return nil, err
|
||||
}
|
||||
|
||||
featureCollection, err := geojson.UnmarshalFeatureCollection(body)
|
||||
if err != nil {
|
||||
log.Error().Err(err).Msg("Failed to unmarshal feature collection")
|
||||
return nil, err
|
||||
}
|
||||
|
||||
return featureCollection, nil
|
||||
}
|
||||
@@ -8,7 +8,7 @@ import (
|
||||
"net/http"
|
||||
|
||||
"git.coopgo.io/coopgo-apps/parcoursmob/services"
|
||||
"git.coopgo.io/coopgo-apps/parcoursmob/utils/storage"
|
||||
"git.coopgo.io/coopgo-apps/parcoursmob/core/utils/storage"
|
||||
"github.com/coreos/go-oidc/v3/oidc"
|
||||
"github.com/gorilla/sessions"
|
||||
"github.com/rs/zerolog/log"
|
||||
73
core/utils/sorting/fleets.go
Executable file
73
core/utils/sorting/fleets.go
Executable file
@@ -0,0 +1,73 @@
|
||||
package sorting
|
||||
|
||||
import (
|
||||
"cmp"
|
||||
"encoding/json"
|
||||
"strings"
|
||||
|
||||
"git.coopgo.io/coopgo-platform/fleets/storage"
|
||||
fleetsstorage "git.coopgo.io/coopgo-platform/fleets/storage"
|
||||
"github.com/paulmach/orb/geo"
|
||||
"github.com/paulmach/orb/geojson"
|
||||
"github.com/rs/zerolog/log"
|
||||
)
|
||||
|
||||
type VehiclesByLicencePlate []fleetsstorage.Vehicle
|
||||
|
||||
func (a VehiclesByLicencePlate) Len() int { return len(a) }
|
||||
func (a VehiclesByLicencePlate) Less(i, j int) bool {
|
||||
return strings.Compare(a[i].Data["licence_plate"].(string), a[j].Data["licence_plate"].(string)) < 0
|
||||
}
|
||||
func (a VehiclesByLicencePlate) Swap(i, j int) { a[i], a[j] = a[j], a[i] }
|
||||
|
||||
type BookingsByStartdate []fleetsstorage.Booking
|
||||
|
||||
func (a BookingsByStartdate) Len() int { return len(a) }
|
||||
func (a BookingsByStartdate) Less(i, j int) bool {
|
||||
return a[i].Startdate.Before(a[j].Startdate)
|
||||
}
|
||||
func (a BookingsByStartdate) Swap(i, j int) { a[i], a[j] = a[j], a[i] }
|
||||
|
||||
// Functions
|
||||
|
||||
func VehiclesByDistanceFrom(from geojson.Feature) func(vehicle1, vehicle2 storage.Vehicle) int {
|
||||
return func(vehicle1, vehicle2 storage.Vehicle) int {
|
||||
vehicle1Address, ok := vehicle1.Data["address"]
|
||||
if !ok {
|
||||
return 1
|
||||
}
|
||||
vehicle1Json, err := json.Marshal(vehicle1Address)
|
||||
if err != nil {
|
||||
log.Error().Err(err).Msg("failed marshalling vehicle 1 json")
|
||||
return 1
|
||||
}
|
||||
|
||||
vehicle1Geojson, err := geojson.UnmarshalFeature(vehicle1Json)
|
||||
if err != nil {
|
||||
log.Error().Err(err).Msg("failed unmarshalling vehicle 1 geojson")
|
||||
return 1
|
||||
}
|
||||
|
||||
vehicle2Address, ok := vehicle2.Data["address"]
|
||||
if !ok {
|
||||
log.Debug().Msg("Vehicle 2 does not have an address")
|
||||
return -1
|
||||
}
|
||||
vehicle2Json, err := json.Marshal(vehicle2Address)
|
||||
if err != nil {
|
||||
log.Error().Err(err).Msg("failed marshalling vehicle 2 json")
|
||||
return -1
|
||||
}
|
||||
|
||||
vehicle2Geojson, err := geojson.UnmarshalFeature(vehicle2Json)
|
||||
if err != nil {
|
||||
log.Error().Err(err).Msg("failed unmarshalling vehicle 2 geojson")
|
||||
return -1
|
||||
}
|
||||
|
||||
distance1 := geo.Distance(from.Point(), vehicle1Geojson.Point())
|
||||
distance2 := geo.Distance(from.Point(), vehicle2Geojson.Point())
|
||||
|
||||
return cmp.Compare(distance1, distance2)
|
||||
}
|
||||
}
|
||||
32
core/utils/sorting/solidarity-transport.go
Normal file
32
core/utils/sorting/solidarity-transport.go
Normal file
@@ -0,0 +1,32 @@
|
||||
package sorting
|
||||
|
||||
import (
|
||||
"strings"
|
||||
|
||||
mobilityaccountsstorage "git.coopgo.io/coopgo-platform/mobility-accounts/storage"
|
||||
"git.coopgo.io/coopgo-platform/solidarity-transport/servers/grpc/proto/gen"
|
||||
)
|
||||
|
||||
type SolidarityDriversByName []mobilityaccountsstorage.Account
|
||||
|
||||
func (e SolidarityDriversByName) Len() int { return len(e) }
|
||||
func (e SolidarityDriversByName) Less(i, j int) bool {
|
||||
return e[i].Data["first_name"].(string) < e[j].Data["first_name"].(string)
|
||||
}
|
||||
func (e SolidarityDriversByName) Swap(i, j int) { e[i], e[j] = e[j], e[i] }
|
||||
|
||||
type SolidarityAvailabilitiesByDay []*gen.DriverRegularAvailability
|
||||
|
||||
func (e SolidarityAvailabilitiesByDay) Len() int { return len(e) }
|
||||
func (e SolidarityAvailabilitiesByDay) Less(i, j int) bool {
|
||||
if e[i].Day == e[j].Day {
|
||||
return strings.Compare(e[i].StartTime, e[j].StartTime) < 0
|
||||
}
|
||||
|
||||
if e[i].Day == 0 {
|
||||
return false
|
||||
}
|
||||
|
||||
return e[i].Day < e[j].Day
|
||||
}
|
||||
func (e SolidarityAvailabilitiesByDay) Swap(i, j int) { e[i], e[j] = e[j], e[i] }
|
||||
@@ -9,9 +9,10 @@ import (
|
||||
|
||||
const (
|
||||
PREFIX_BENEFICIARIES = "beneficiaries"
|
||||
PREFIX_SOLIDARITY_TRANSPORT_DRIVERS = "solidarity_transport/drivers"
|
||||
PREFIX_ORGANIZED_CARPOOL_DRIVERS = "organized_carpool/drivers"
|
||||
PREFIX_BOOKINGS = "fleets_bookings"
|
||||
PREFIX_AGENDA = "event_files"
|
||||
PREFIX_DIAGS = "diags"
|
||||
)
|
||||
|
||||
type FileInfo struct {
|
||||
@@ -27,6 +28,7 @@ type FileStorage interface {
|
||||
List(prefix string) []FileInfo
|
||||
Get(prefix string, file string) (io.Reader, *FileInfo, error)
|
||||
Copy(src string, dest string) error
|
||||
Delete(prefix string, file string) error
|
||||
}
|
||||
|
||||
func NewFileStorage(cfg *viper.Viper) (FileStorage, error) {
|
||||
@@ -122,3 +122,12 @@ func (s *MinioStorageHandler) Copy(src string, dst string) error {
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
func (s *MinioStorageHandler) Delete(prefix string, file string) error {
|
||||
err := s.Client.RemoveObject(context.Background(), s.BucketName, prefix+"/"+file, minio.RemoveObjectOptions{})
|
||||
if err != nil {
|
||||
log.Error().Err(err).Msg("Error deleting file from storage")
|
||||
return err
|
||||
}
|
||||
return nil
|
||||
}
|
||||
102
core/utils/validated-profile/validated-profile.go
Normal file
102
core/utils/validated-profile/validated-profile.go
Normal file
@@ -0,0 +1,102 @@
|
||||
package validatedprofile
|
||||
|
||||
import (
|
||||
"cmp"
|
||||
"slices"
|
||||
"time"
|
||||
|
||||
"git.coopgo.io/coopgo-apps/parcoursmob/core/utils/storage"
|
||||
mobilityaccountsstorage "git.coopgo.io/coopgo-platform/mobility-accounts/storage"
|
||||
"github.com/go-viper/mapstructure/v2"
|
||||
"github.com/rs/zerolog/log"
|
||||
"github.com/spf13/viper"
|
||||
"github.com/stretchr/objx"
|
||||
)
|
||||
|
||||
type Comparison struct {
|
||||
Field string
|
||||
Type string
|
||||
Value any
|
||||
}
|
||||
|
||||
func ValidateProfile(cfg *viper.Viper) func(mobilityaccountsstorage.Account, []storage.FileInfo) bool {
|
||||
enabled := cfg.GetBool("enabled")
|
||||
requiredDocuments := cfg.GetStringSlice("required.documents")
|
||||
requiredFields := cfg.GetStringSlice("required.fields")
|
||||
comp := cfg.Get("assert.compare")
|
||||
var comparisons []Comparison
|
||||
err := mapstructure.Decode(comp, &comparisons)
|
||||
if err != nil {
|
||||
log.Error().Err(err).Msg("reading comparisons issue")
|
||||
}
|
||||
return func(account mobilityaccountsstorage.Account, docs []storage.FileInfo) bool {
|
||||
if !enabled {
|
||||
return true
|
||||
}
|
||||
|
||||
for _, d := range requiredDocuments {
|
||||
if !slices.ContainsFunc(docs, func(f storage.FileInfo) bool {
|
||||
log.Debug().Str("required", d).Str("checked", f.Metadata["Type"]).Msg("file check")
|
||||
return f.Metadata["Type"] == d
|
||||
}) {
|
||||
log.Debug().Msg("file missing")
|
||||
return false
|
||||
}
|
||||
}
|
||||
|
||||
obj := objx.Map(account.Data)
|
||||
|
||||
for _, f := range requiredFields {
|
||||
if obj.Get(f) == nil {
|
||||
log.Debug().Msg("field missing")
|
||||
return false
|
||||
}
|
||||
}
|
||||
|
||||
for _, c := range comparisons {
|
||||
val := obj.Get(c.Field)
|
||||
if val == nil {
|
||||
return false
|
||||
}
|
||||
value := ""
|
||||
if v, ok := c.Value.(string); ok {
|
||||
value = v
|
||||
} else if v, ok := c.Value.(time.Time); ok {
|
||||
value = v.Format("2006-01-02")
|
||||
} else {
|
||||
log.Error().Msg("could not get type")
|
||||
return false
|
||||
}
|
||||
result := cmp.Compare(val.String(), value)
|
||||
|
||||
if c.Type == "gte" {
|
||||
if result < 0 {
|
||||
log.Debug().Int("comparison result", result).Str("operand", c.Type).Msg("comparison issue")
|
||||
return false
|
||||
}
|
||||
} else if c.Type == "gt" {
|
||||
if result <= 0 {
|
||||
log.Debug().Int("comparison result", result).Str("operand", c.Type).Msg("comparison issue")
|
||||
return false
|
||||
}
|
||||
} else if c.Type == "lt" {
|
||||
if result >= 0 {
|
||||
log.Debug().Int("comparison result", result).Str("operand", c.Type).Msg("comparison issue")
|
||||
return false
|
||||
}
|
||||
} else if c.Type == "lte" {
|
||||
if result < 0 {
|
||||
log.Debug().Int("comparison result", result).Str("operand", c.Type).Msg("comparison issue")
|
||||
return false
|
||||
}
|
||||
} else if c.Type == "eq" {
|
||||
if result != 0 {
|
||||
log.Debug().Int("comparison result", result).Str("operand", c.Type).Msg("comparison issue")
|
||||
return false
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
return true
|
||||
}
|
||||
}
|
||||
170
go.mod
170
go.mod
@@ -1,6 +1,6 @@
|
||||
module git.coopgo.io/coopgo-apps/parcoursmob
|
||||
|
||||
go 1.22.8
|
||||
go 1.24.6
|
||||
|
||||
// replace git.coopgo.io/coopgo-platform/mobility-accounts => ../../coopgo-platform/mobility-accounts/
|
||||
|
||||
@@ -12,114 +12,168 @@ go 1.22.8
|
||||
|
||||
// replace git.coopgo.io/coopgo-platform/emailing => ../../coopgo-platform/emailing/
|
||||
|
||||
// replace git.coopgo.io/coopgo-platform/data-hub => ../../coopgo-platform/data-hub/
|
||||
|
||||
// replace git.coopgo.io/coopgo-platform/solidarity-transport => ../../coopgo-platform/solidarity-transport/
|
||||
|
||||
// replace git.coopgo.io/coopgo-platform/saved-search => ../../coopgo-platform/saved-search/
|
||||
|
||||
// replace git.coopgo.io/coopgo-platform/carpool-service => ../../coopgo-platform/carpool-service/
|
||||
|
||||
// replace git.coopgo.io/coopgo-platform/multimodal-routing => ../../coopgo-platform/multimodal-routing/
|
||||
|
||||
// replace git.coopgo.io/coopgo-platform/payments => ../../coopgo-platform/payments/
|
||||
|
||||
// replace git.coopgo.io/coopgo-platform/geography => ../../coopgo-platform/geography/
|
||||
|
||||
// replace git.coopgo.io/coopgo-platform/sms => ../../coopgo-platform/sms/
|
||||
|
||||
require (
|
||||
github.com/fogleman/gg v1.3.0
|
||||
github.com/go-playground/validator/v10 v10.11.0
|
||||
github.com/go-playground/validator/v10 v10.14.1
|
||||
github.com/google/uuid v1.6.0
|
||||
github.com/gorilla/mux v1.8.0
|
||||
github.com/gorilla/sessions v1.2.1
|
||||
github.com/paulmach/go.geojson v1.4.0
|
||||
github.com/spf13/viper v1.19.0
|
||||
github.com/paulmach/go.geojson v1.4.0 // indirect
|
||||
github.com/spf13/viper v1.21.0
|
||||
gitlab.scity.coop/maas/navitia-golang v0.0.0-20220429110621-5c22d6efdd0c
|
||||
go.etcd.io/etcd/client/v3 v3.5.12
|
||||
golang.org/x/image v0.5.0
|
||||
golang.org/x/oauth2 v0.23.0
|
||||
google.golang.org/grpc v1.68.0
|
||||
google.golang.org/protobuf v1.35.2
|
||||
golang.org/x/image v0.25.0
|
||||
golang.org/x/oauth2 v0.30.0
|
||||
google.golang.org/grpc v1.76.0
|
||||
google.golang.org/protobuf v1.36.10
|
||||
)
|
||||
|
||||
require (
|
||||
git.coopgo.io/coopgo-platform/agenda v1.0.0
|
||||
git.coopgo.io/coopgo-platform/emailing v0.0.0-20241119141913-9836b30191c1
|
||||
git.coopgo.io/coopgo-platform/fleets v0.0.0-20230310144446-feb935f8bf4e
|
||||
git.coopgo.io/coopgo-platform/carpool-service v0.0.0-20251008165122-38cb3c5ad9b4
|
||||
git.coopgo.io/coopgo-platform/emailing v0.0.0-20250212064257-167ef5864260
|
||||
git.coopgo.io/coopgo-platform/fleets v1.1.0
|
||||
git.coopgo.io/coopgo-platform/geography v0.0.0-20251010131258-ec939649e858
|
||||
git.coopgo.io/coopgo-platform/groups-management v0.0.0-20230310123255-5ef94ee0746c
|
||||
git.coopgo.io/coopgo-platform/mobility-accounts v0.0.0-20230329105908-a76c0412a386
|
||||
git.coopgo.io/coopgo-platform/multimodal-routing v0.0.0-20251013140400-42fb40437ac3
|
||||
git.coopgo.io/coopgo-platform/payments v0.0.0-20251013175712-75d0288d2d4f
|
||||
git.coopgo.io/coopgo-platform/routing-service v0.0.0-20250304234521-faabcc54f536
|
||||
git.coopgo.io/coopgo-platform/saved-search v0.0.0-20251008070953-efccea3f6463
|
||||
git.coopgo.io/coopgo-platform/sms v0.0.0-20250523074631-1f1e7fc6b7af
|
||||
git.coopgo.io/coopgo-platform/solidarity-transport v0.0.0-20251016152145-e0882db1bcbc
|
||||
github.com/arran4/golang-ical v0.3.1
|
||||
github.com/coreos/go-oidc/v3 v3.11.0
|
||||
github.com/go-viper/mapstructure/v2 v2.4.0
|
||||
github.com/gorilla/securecookie v1.1.1
|
||||
github.com/minio/minio-go/v7 v7.0.43
|
||||
github.com/rs/zerolog v1.33.0
|
||||
github.com/xuri/excelize/v2 v2.7.1
|
||||
github.com/modelcontextprotocol/go-sdk v1.0.0
|
||||
github.com/paulmach/orb v0.12.0
|
||||
github.com/rs/zerolog v1.34.0
|
||||
github.com/stretchr/objx v0.5.3
|
||||
github.com/xuri/excelize/v2 v2.9.1
|
||||
)
|
||||
|
||||
require (
|
||||
github.com/sagikazarmark/locafero v0.4.0 // indirect
|
||||
github.com/sagikazarmark/slog-shim v0.1.0 // indirect
|
||||
github.com/sourcegraph/conc v0.3.0 // indirect
|
||||
golang.org/x/exp v0.0.0-20240222234643-814bf88cf225 // indirect
|
||||
git.coopgo.io/coopgo-platform/carpool-service/interoperability/ocss v0.0.0-20251008142525-4392f227836a // indirect
|
||||
github.com/RoaringBitmap/roaring/v2 v2.4.5 // indirect
|
||||
github.com/apparentlymart/go-textseg/v15 v15.0.0 // indirect
|
||||
github.com/bits-and-blooms/bitset v1.22.0 // indirect
|
||||
github.com/blevesearch/bleve/v2 v2.5.2 // indirect
|
||||
github.com/blevesearch/bleve_index_api v1.2.8 // indirect
|
||||
github.com/blevesearch/geo v0.2.3 // indirect
|
||||
github.com/blevesearch/go-faiss v1.0.25 // indirect
|
||||
github.com/blevesearch/go-porterstemmer v1.0.3 // indirect
|
||||
github.com/blevesearch/gtreap v0.1.1 // indirect
|
||||
github.com/blevesearch/mmap-go v1.0.4 // indirect
|
||||
github.com/blevesearch/scorch_segment_api/v2 v2.3.10 // indirect
|
||||
github.com/blevesearch/segment v0.9.1 // indirect
|
||||
github.com/blevesearch/snowballstem v0.9.0 // indirect
|
||||
github.com/blevesearch/upsidedown_store_api v1.0.2 // indirect
|
||||
github.com/blevesearch/vellum v1.1.0 // indirect
|
||||
github.com/blevesearch/zapx/v11 v11.4.2 // indirect
|
||||
github.com/blevesearch/zapx/v12 v12.4.2 // indirect
|
||||
github.com/blevesearch/zapx/v13 v13.4.2 // indirect
|
||||
github.com/blevesearch/zapx/v14 v14.4.2 // indirect
|
||||
github.com/blevesearch/zapx/v15 v15.4.2 // indirect
|
||||
github.com/blevesearch/zapx/v16 v16.2.4 // indirect
|
||||
github.com/bmatcuk/doublestar v1.3.4 // indirect
|
||||
github.com/gabriel-vasile/mimetype v1.4.2 // indirect
|
||||
github.com/gorilla/schema v1.4.1 // indirect
|
||||
github.com/mschoch/smat v0.2.0 // indirect
|
||||
github.com/sagikazarmark/locafero v0.12.0 // indirect
|
||||
github.com/tidwall/geoindex v1.7.0 // indirect
|
||||
github.com/tidwall/rtree v1.10.0 // indirect
|
||||
github.com/twpayne/go-polyline v1.1.1 // indirect
|
||||
github.com/zclconf/go-cty-yaml v1.1.0 // indirect
|
||||
go.etcd.io/bbolt v1.4.0 // indirect
|
||||
go.yaml.in/yaml/v3 v3.0.4 // indirect
|
||||
golang.org/x/mod v0.28.0 // indirect
|
||||
golang.org/x/tools v0.37.0 // indirect
|
||||
)
|
||||
|
||||
require (
|
||||
ariga.io/atlas v0.12.0 // indirect
|
||||
git.coopgo.io/coopgo-platform/diags v0.0.0-20250212093351-64da61495c9d
|
||||
github.com/agext/levenshtein v1.2.1 // indirect
|
||||
github.com/apparentlymart/go-textseg/v13 v13.0.0 // indirect
|
||||
ariga.io/atlas v0.37.0 // indirect
|
||||
github.com/agext/levenshtein v1.2.3 // indirect
|
||||
github.com/coreos/go-semver v0.3.0 // indirect
|
||||
github.com/coreos/go-systemd/v22 v22.5.0 // indirect
|
||||
github.com/dustin/go-humanize v1.0.0 // indirect
|
||||
github.com/fsnotify/fsnotify v1.7.0 // indirect
|
||||
github.com/go-jose/go-jose/v4 v4.0.2 // indirect
|
||||
github.com/go-openapi/inflect v0.19.0 // indirect
|
||||
github.com/go-playground/locales v0.14.0 // indirect
|
||||
github.com/go-playground/universal-translator v0.18.0 // indirect
|
||||
github.com/fsnotify/fsnotify v1.9.0 // indirect
|
||||
github.com/go-jose/go-jose/v4 v4.1.2 // indirect
|
||||
github.com/go-openapi/inflect v0.21.3 // indirect
|
||||
github.com/go-playground/locales v0.14.1 // indirect
|
||||
github.com/go-playground/universal-translator v0.18.1 // indirect
|
||||
github.com/gogo/protobuf v1.3.2 // indirect
|
||||
github.com/golang/freetype v0.0.0-20170609003504-e2365dfdc4a0 // indirect
|
||||
github.com/golang/protobuf v1.5.4 // indirect
|
||||
github.com/golang/snappy v0.0.4 // indirect
|
||||
github.com/google/go-cmp v0.6.0 // indirect
|
||||
github.com/hashicorp/hcl v1.0.0 // indirect
|
||||
github.com/hashicorp/hcl/v2 v2.10.0 // indirect
|
||||
github.com/golang/snappy v1.0.0 // indirect
|
||||
github.com/google/go-cmp v0.7.0 // indirect
|
||||
github.com/google/jsonschema-go v0.3.0 // indirect
|
||||
github.com/hashicorp/hcl/v2 v2.24.0 // indirect
|
||||
github.com/json-iterator/go v1.1.12 // indirect
|
||||
github.com/klauspost/compress v1.17.7 // indirect
|
||||
github.com/klauspost/cpuid/v2 v2.1.0 // indirect
|
||||
github.com/leodido/go-urn v1.2.1 // indirect
|
||||
github.com/klauspost/compress v1.18.0 // indirect
|
||||
github.com/klauspost/cpuid/v2 v2.2.5 // indirect
|
||||
github.com/leodido/go-urn v1.2.4 // indirect
|
||||
github.com/lib/pq v1.10.9 // indirect
|
||||
github.com/magiconair/properties v1.8.7 // indirect
|
||||
github.com/mattn/go-colorable v0.1.13 // indirect
|
||||
github.com/mattn/go-colorable v0.1.14 // indirect
|
||||
github.com/mattn/go-isatty v0.0.20 // indirect
|
||||
github.com/mb0/wkt v0.0.0-20170420051526-a30afd545ee1 // indirect
|
||||
github.com/minio/md5-simd v1.1.2 // indirect
|
||||
github.com/minio/sha256-simd v1.0.0 // indirect
|
||||
github.com/mitchellh/go-wordwrap v0.0.0-20150314170334-ad45545899c7 // indirect
|
||||
github.com/mitchellh/mapstructure v1.5.0 // indirect
|
||||
github.com/mitchellh/go-wordwrap v1.0.1 // indirect
|
||||
github.com/modern-go/concurrent v0.0.0-20180306012644-bacd9c7ef1dd // indirect
|
||||
github.com/modern-go/reflect2 v1.0.2 // indirect
|
||||
github.com/mohae/deepcopy v0.0.0-20170929034955-c48cc78d4826 // indirect
|
||||
github.com/montanaflynn/stats v0.7.1 // indirect
|
||||
github.com/pelletier/go-toml/v2 v2.2.2 // indirect
|
||||
github.com/pelletier/go-toml/v2 v2.2.4 // indirect
|
||||
github.com/pkg/errors v0.9.1 // indirect
|
||||
github.com/richardlehane/mscfb v1.0.4 // indirect
|
||||
github.com/richardlehane/msoleps v1.0.3 // indirect
|
||||
github.com/rs/xid v1.5.0 // indirect
|
||||
github.com/richardlehane/msoleps v1.0.4 // indirect
|
||||
github.com/rs/xid v1.6.0 // indirect
|
||||
github.com/santhosh-tekuri/jsonschema/v5 v5.0.0 // indirect
|
||||
github.com/sergi/go-diff v1.1.0 // indirect
|
||||
github.com/sirupsen/logrus v1.9.3 // indirect
|
||||
github.com/spf13/afero v1.11.0 // indirect
|
||||
github.com/spf13/cast v1.6.0 // indirect
|
||||
github.com/spf13/pflag v1.0.5 // indirect
|
||||
github.com/spf13/afero v1.15.0 // indirect
|
||||
github.com/spf13/cast v1.10.0 // indirect
|
||||
github.com/spf13/pflag v1.0.10 // indirect
|
||||
github.com/subosito/gotenv v1.6.0 // indirect
|
||||
github.com/tiendc/go-deepcopy v1.7.1 // indirect
|
||||
github.com/twpayne/go-geom v1.5.7 // indirect
|
||||
github.com/wneessen/go-mail v0.5.2 // indirect
|
||||
github.com/xdg-go/pbkdf2 v1.0.0 // indirect
|
||||
github.com/xdg-go/scram v1.1.2 // indirect
|
||||
github.com/xdg-go/stringprep v1.0.4 // indirect
|
||||
github.com/xuri/efp v0.0.0-20220603152613-6918739fd470 // indirect
|
||||
github.com/xuri/nfp v0.0.0-20220409054826-5e722a1d9e22 // indirect
|
||||
github.com/xuri/efp v0.0.1 // indirect
|
||||
github.com/xuri/nfp v0.0.1 // indirect
|
||||
github.com/yosida95/uritemplate/v3 v3.0.2 // indirect
|
||||
github.com/youmark/pkcs8 v0.0.0-20240726163527-a2c0da244d78 // indirect
|
||||
github.com/zclconf/go-cty v1.8.0 // indirect
|
||||
github.com/zclconf/go-cty v1.17.0 // indirect
|
||||
go.etcd.io/etcd/api/v3 v3.5.12 // indirect
|
||||
go.etcd.io/etcd/client/pkg/v3 v3.5.12 // indirect
|
||||
go.mongodb.org/mongo-driver v1.17.1 // indirect
|
||||
go.uber.org/atomic v1.9.0 // indirect
|
||||
go.uber.org/multierr v1.9.0 // indirect
|
||||
go.mongodb.org/mongo-driver v1.17.4 // indirect
|
||||
go.uber.org/atomic v1.11.0 // indirect
|
||||
go.uber.org/multierr v1.11.0 // indirect
|
||||
go.uber.org/zap v1.21.0 // indirect
|
||||
golang.org/x/crypto v0.28.0 // indirect
|
||||
golang.org/x/net v0.29.0 // indirect
|
||||
golang.org/x/sync v0.8.0 // indirect
|
||||
golang.org/x/sys v0.27.0 // indirect
|
||||
golang.org/x/text v0.19.0 // indirect
|
||||
google.golang.org/genproto/googleapis/api v0.0.0-20240903143218-8af14fe29dc1 // indirect
|
||||
google.golang.org/genproto/googleapis/rpc v0.0.0-20240903143218-8af14fe29dc1 // indirect
|
||||
golang.org/x/crypto v0.43.0 // indirect
|
||||
golang.org/x/net v0.46.0 // indirect
|
||||
golang.org/x/sync v0.17.0 // indirect
|
||||
golang.org/x/sys v0.37.0 // indirect
|
||||
golang.org/x/text v0.30.0 // indirect
|
||||
google.golang.org/genproto/googleapis/api v0.0.0-20250804133106-a7a43d27e69b // indirect
|
||||
google.golang.org/genproto/googleapis/rpc v0.0.0-20251007200510-49b9836ed3ff // indirect
|
||||
gopkg.in/ini.v1 v1.67.0 // indirect
|
||||
gopkg.in/mgo.v2 v2.0.0-20190816093944-a6b53ec6cb22 // indirect
|
||||
gopkg.in/yaml.v3 v3.0.1 // indirect
|
||||
|
||||
434
go.sum
434
go.sum
@@ -1,21 +1,33 @@
|
||||
ariga.io/atlas v0.12.0 h1:jDfjxT3ppKhzqLS26lZv9ni7p9TVNrhy7SQquaF7bPs=
|
||||
ariga.io/atlas v0.12.0/go.mod h1:+TR129FJZ5Lvzms6dvCeGWh1yR6hMvmXBhug4hrNIGk=
|
||||
ariga.io/atlas v0.37.0 h1:MvbQ25CAHFslttEKEySwYNFrFUdLAPhtU1izOzjXV+o=
|
||||
ariga.io/atlas v0.37.0/go.mod h1:mHE83ptCxEkd3rO3c7Rvkk6Djf6mVhEiSVhoiNu96CI=
|
||||
git.coopgo.io/coopgo-platform/agenda v1.0.0 h1:rTHgva1JKKO0wAPlINegifMkHm+xOg3IWW4yQRy334w=
|
||||
git.coopgo.io/coopgo-platform/agenda v1.0.0/go.mod h1:/hToSla0p6SeWn1zo1MDrfxdmo7RBdZDkbLqCVituIM=
|
||||
git.coopgo.io/coopgo-platform/diags v0.0.0-20250210110754-726bb4643c63 h1:BvNTshj4TToGptaheeAzEmaNeuqPCR/NIH6TGePd54A=
|
||||
git.coopgo.io/coopgo-platform/diags v0.0.0-20250210110754-726bb4643c63/go.mod h1:diyq11WNkgJ0kYHdT7SphXPMQUyoq4lRk7T6IgM5yPA=
|
||||
git.coopgo.io/coopgo-platform/diags v0.0.0-20250211082457-291671c295e6 h1:McRGfPLueD+wcx8yf19a31uei4Ha0ugiDtnYtHYErrg=
|
||||
git.coopgo.io/coopgo-platform/diags v0.0.0-20250211082457-291671c295e6/go.mod h1:diyq11WNkgJ0kYHdT7SphXPMQUyoq4lRk7T6IgM5yPA=
|
||||
git.coopgo.io/coopgo-platform/diags v0.0.0-20250212093351-64da61495c9d h1:fBxVvik4Cb/6d4+HAXZi9e8x8P9UBCJt8JcWgqnNjsE=
|
||||
git.coopgo.io/coopgo-platform/diags v0.0.0-20250212093351-64da61495c9d/go.mod h1:diyq11WNkgJ0kYHdT7SphXPMQUyoq4lRk7T6IgM5yPA=
|
||||
git.coopgo.io/coopgo-platform/emailing v0.0.0-20241119141913-9836b30191c1 h1:gAhJ9wwlitMiETmnD4U2L6xLnVd5xE4hPX72IJ5s7+I=
|
||||
git.coopgo.io/coopgo-platform/emailing v0.0.0-20241119141913-9836b30191c1/go.mod h1:EXy6NRvFfpW6yIHoZUixldkXrj1qzjCbTHpumDvzaKI=
|
||||
git.coopgo.io/coopgo-platform/fleets v0.0.0-20230310144446-feb935f8bf4e h1:eHahRTKlC8aBWYCd6LbXNcX8HoQhuZj31OFWrw0EL0U=
|
||||
git.coopgo.io/coopgo-platform/fleets v0.0.0-20230310144446-feb935f8bf4e/go.mod h1:s9OIFCNcjBAbBzRNHwoCTYV6kAntPG9CpT3GVweGdTY=
|
||||
git.coopgo.io/coopgo-platform/carpool-service v0.0.0-20251008165122-38cb3c5ad9b4 h1:L3HJnjQo5M0maOKkILAIq257tbHHCsr6OpAWGVQoGJs=
|
||||
git.coopgo.io/coopgo-platform/carpool-service v0.0.0-20251008165122-38cb3c5ad9b4/go.mod h1:4qy6Ha8/cA3L+hZyzPYbKJ0dFO+zyDh8W7bMXDXE6WQ=
|
||||
git.coopgo.io/coopgo-platform/carpool-service/interoperability/ocss v0.0.0-20251008142525-4392f227836a h1:roBn3oQRQ/j5JBAP01wIs1UQvtm3tjui+D4EAa/Hfa4=
|
||||
git.coopgo.io/coopgo-platform/carpool-service/interoperability/ocss v0.0.0-20251008142525-4392f227836a/go.mod h1:c9aJwNtY4PJuqAFYZ9afnx46UAZtWJ3P8ICZM02/DBA=
|
||||
git.coopgo.io/coopgo-platform/emailing v0.0.0-20250212064257-167ef5864260 h1:Li3dotY6raKu9+oxEgICU7nwdomYpjgu19i3mZNiqTc=
|
||||
git.coopgo.io/coopgo-platform/emailing v0.0.0-20250212064257-167ef5864260/go.mod h1:6cvvjv0RLSwBthIQ4TiuZoXFGvQXZ55hNSJchWXAgB4=
|
||||
git.coopgo.io/coopgo-platform/fleets v1.1.0 h1:pfW/K3fWfap54yNfkLzBXjvOjjoTaEGFEqS/+VkHv7s=
|
||||
git.coopgo.io/coopgo-platform/fleets v1.1.0/go.mod h1:nuK2mi1M2+DdntinqK/8C4ttW4WWyKCCY/xD1D7XjkE=
|
||||
git.coopgo.io/coopgo-platform/geography v0.0.0-20251010131258-ec939649e858 h1:4E0tbT8jj5oxaK66Ny61o7zqPaVc0qRN2cZG9IUR4Es=
|
||||
git.coopgo.io/coopgo-platform/geography v0.0.0-20251010131258-ec939649e858/go.mod h1:TbR3g1Awa8hpAe6LR1z1EQbv2IBVgN5JQ/FjXfKX4K0=
|
||||
git.coopgo.io/coopgo-platform/groups-management v0.0.0-20230310123255-5ef94ee0746c h1:bY7PyrAgYY02f5IpDyf1WVfRqvWzivu31K6aEAYbWCw=
|
||||
git.coopgo.io/coopgo-platform/groups-management v0.0.0-20230310123255-5ef94ee0746c/go.mod h1:lozSy6qlIIYhvKKXscZzz28HAtS0qBDUTv5nofLRmYA=
|
||||
git.coopgo.io/coopgo-platform/mobility-accounts v0.0.0-20230329105908-a76c0412a386 h1:v1JUdx8sknw2YYhFGz5cOAa1dEWNIBKvyiOpKr3RR+s=
|
||||
git.coopgo.io/coopgo-platform/mobility-accounts v0.0.0-20230329105908-a76c0412a386/go.mod h1:1typNYtO+PQT6KG77vs/PUv0fO60/nbeSGZL2tt1LLg=
|
||||
git.coopgo.io/coopgo-platform/multimodal-routing v0.0.0-20251013140400-42fb40437ac3 h1:jo7fF7tLIAU110tUSIYXkMAvu30g8wHzZCLq3YomooQ=
|
||||
git.coopgo.io/coopgo-platform/multimodal-routing v0.0.0-20251013140400-42fb40437ac3/go.mod h1:npYccQZcZj1WzTHhpLfFHFSBA3RiZOkO5R9x4uy1a9I=
|
||||
git.coopgo.io/coopgo-platform/payments v0.0.0-20251013175712-75d0288d2d4f h1:B/+AP+rLFx8AojO2bKV3R93kMU84g8Dhy7DNVoT8xCY=
|
||||
git.coopgo.io/coopgo-platform/payments v0.0.0-20251013175712-75d0288d2d4f/go.mod h1:gSAH2Tr9x8K8QC0vsUMwSWLrQOlsG+v64ACrjYw4BL0=
|
||||
git.coopgo.io/coopgo-platform/routing-service v0.0.0-20250304234521-faabcc54f536 h1:SllXX1VJXulfhNi+Pd0R9chksm8zO6gkWcTQ/uSMsdc=
|
||||
git.coopgo.io/coopgo-platform/routing-service v0.0.0-20250304234521-faabcc54f536/go.mod h1:Nh7o15LlV0OuO9zxvJIs9FlelpeAaLYkXtFdgIkFrgg=
|
||||
git.coopgo.io/coopgo-platform/saved-search v0.0.0-20251008070953-efccea3f6463 h1:TjjqFEkRLDqy300pGOLIhsVYBpE0J640pFW9//OknzA=
|
||||
git.coopgo.io/coopgo-platform/saved-search v0.0.0-20251008070953-efccea3f6463/go.mod h1:0fuGuYub5CBy9NB6YMqxawE0HoBaxPb9gmSw1gjfDy0=
|
||||
git.coopgo.io/coopgo-platform/sms v0.0.0-20250523074631-1f1e7fc6b7af h1:KxHim1dFcOVbFhRqelec8cJ65QBD2cma6eytW8llgYY=
|
||||
git.coopgo.io/coopgo-platform/sms v0.0.0-20250523074631-1f1e7fc6b7af/go.mod h1:mad9D+WICDdpJzB+8H/wEVVbllK2mU6VLVByrppc9x0=
|
||||
git.coopgo.io/coopgo-platform/solidarity-transport v0.0.0-20251016152145-e0882db1bcbc h1:NLU5DUo5Kt3jkPhV3KkqQMahTHIrGildBvYlHwJ6JmM=
|
||||
git.coopgo.io/coopgo-platform/solidarity-transport v0.0.0-20251016152145-e0882db1bcbc/go.mod h1:iaFXcIn7DYtKlLrSYs9C47Dt7eeMGYkpx+unLCx8TpQ=
|
||||
github.com/Azure/go-ansiterm v0.0.0-20170929234023-d6e3b3328b78/go.mod h1:LmzpDX56iTiv29bbRTIsUNlaFfuhWRQBWjQdVyAevI8=
|
||||
github.com/DATA-DOG/go-sqlmock v1.3.2/go.mod h1:f/Ixk793poVmq4qj/V1dPUg2JEAKC73Q5eFN3EC/SaM=
|
||||
github.com/DATA-DOG/go-sqlmock v1.5.2 h1:OcvFkGmslmlZibjAjaHm3L//6LiuBgolP7OputlJIzU=
|
||||
@@ -25,20 +37,61 @@ github.com/Masterminds/semver v1.5.0/go.mod h1:MB6lktGJrhw8PrUyiEoblNEGEQ+RzHPF0
|
||||
github.com/Masterminds/sprig v2.22.0+incompatible/go.mod h1:y6hNFY5UBTIWBxnzTeuNhlNS5hqE0NB0E6fgfo2Br3o=
|
||||
github.com/Microsoft/go-winio v0.4.14/go.mod h1:qXqCSQ3Xa7+6tgxaGTIe4Kpcdsi+P8jBhyzoq1bpyYA=
|
||||
github.com/Nvveen/Gotty v0.0.0-20120604004816-cd527374f1e5/go.mod h1:lmUJ/7eu/Q8D7ML55dXQrVaamCz2vxCfdQBasLZfHKk=
|
||||
github.com/agext/levenshtein v1.2.1 h1:QmvMAjj2aEICytGiWzmxoE0x2KZvE0fvmqMOfy2tjT8=
|
||||
github.com/agext/levenshtein v1.2.1/go.mod h1:JEDfjyjHDjOF/1e4FlBE/PkbqA9OfWu2ki2W0IB5558=
|
||||
github.com/RoaringBitmap/roaring/v2 v2.4.5 h1:uGrrMreGjvAtTBobc0g5IrW1D5ldxDQYe2JW2gggRdg=
|
||||
github.com/RoaringBitmap/roaring/v2 v2.4.5/go.mod h1:FiJcsfkGje/nZBZgCu0ZxCPOKD/hVXDS2dXi7/eUFE0=
|
||||
github.com/agext/levenshtein v1.2.3 h1:YB2fHEn0UJagG8T1rrWknE3ZQzWM06O8AMAatNn7lmo=
|
||||
github.com/agext/levenshtein v1.2.3/go.mod h1:JEDfjyjHDjOF/1e4FlBE/PkbqA9OfWu2ki2W0IB5558=
|
||||
github.com/alecthomas/assert/v2 v2.10.0 h1:jjRCHsj6hBJhkmhznrCzoNpbA3zqy0fYiUcYZP/GkPY=
|
||||
github.com/alecthomas/assert/v2 v2.10.0/go.mod h1:Bze95FyfUr7x34QZrjL+XP+0qgp/zg8yS+TtBj1WA3k=
|
||||
github.com/alecthomas/repr v0.4.0 h1:GhI2A8MACjfegCPVq9f1FLvIBS+DrQ2KQBFZP1iFzXc=
|
||||
github.com/alecthomas/repr v0.4.0/go.mod h1:Fr0507jx4eOXV7AlPV6AVZLYrLIuIeSOWtW57eE/O/4=
|
||||
github.com/apparentlymart/go-dump v0.0.0-20180507223929-23540a00eaa3/go.mod h1:oL81AME2rN47vu18xqj1S1jPIPuN7afo62yKTNn3XMM=
|
||||
github.com/apparentlymart/go-textseg v1.0.0/go.mod h1:z96Txxhf3xSFMPmb5X/1W05FF/Nj9VFpLOpjS5yuumk=
|
||||
github.com/apparentlymart/go-textseg/v13 v13.0.0 h1:Y+KvPE1NYz0xl601PVImeQfFyEy6iT90AvPUL1NNfNw=
|
||||
github.com/apparentlymart/go-textseg/v13 v13.0.0/go.mod h1:ZK2fH7c4NqDTLtiYLvIkEghdlcqw7yxLeM89kiTRPUo=
|
||||
github.com/apparentlymart/go-textseg/v15 v15.0.0 h1:uYvfpb3DyLSCGWnctWKGj857c6ew1u1fNQOlOtuGxQY=
|
||||
github.com/apparentlymart/go-textseg/v15 v15.0.0/go.mod h1:K8XmNZdhEBkdlyDdvbmmsvpAG721bKi0joRfFdHIWJ4=
|
||||
github.com/arran4/golang-ical v0.3.1 h1:v13B3eQZ9VDHTAvT6M11vVzxYgcYmjyPBE2eAZl3VZk=
|
||||
github.com/arran4/golang-ical v0.3.1/go.mod h1:LZWxF8ZIu/sjBVUCV0udiVPrQAgq3V0aa0RfbO99Qkk=
|
||||
github.com/benbjohnson/clock v1.1.0 h1:Q92kusRqC1XV2MjkWETPvjJVqKetz1OzxZB7mHJLju8=
|
||||
github.com/benbjohnson/clock v1.1.0/go.mod h1:J11/hYXuz8f4ySSvYwY0FKfm+ezbsZBKZxNJlLklBHA=
|
||||
github.com/bits-and-blooms/bitset v1.12.0/go.mod h1:7hO7Gc7Pp1vODcmWvKMRA9BNmbv6a/7QIWpPxHddWR8=
|
||||
github.com/bits-and-blooms/bitset v1.22.0 h1:Tquv9S8+SGaS3EhyA+up3FXzmkhxPGjQQCkcs2uw7w4=
|
||||
github.com/bits-and-blooms/bitset v1.22.0/go.mod h1:7hO7Gc7Pp1vODcmWvKMRA9BNmbv6a/7QIWpPxHddWR8=
|
||||
github.com/blevesearch/bleve/v2 v2.5.2 h1:Ab0r0MODV2C5A6BEL87GqLBySqp/s9xFgceCju6BQk8=
|
||||
github.com/blevesearch/bleve/v2 v2.5.2/go.mod h1:5Dj6dUQxZM6aqYT3eutTD/GpWKGFSsV8f7LDidFbwXo=
|
||||
github.com/blevesearch/bleve_index_api v1.2.8 h1:Y98Pu5/MdlkRyLM0qDHostYo7i+Vv1cDNhqTeR4Sy6Y=
|
||||
github.com/blevesearch/bleve_index_api v1.2.8/go.mod h1:rKQDl4u51uwafZxFrPD1R7xFOwKnzZW7s/LSeK4lgo0=
|
||||
github.com/blevesearch/geo v0.2.3 h1:K9/vbGI9ehlXdxjxDRJtoAMt7zGAsMIzc6n8zWcwnhg=
|
||||
github.com/blevesearch/geo v0.2.3/go.mod h1:K56Q33AzXt2YExVHGObtmRSFYZKYGv0JEN5mdacJJR8=
|
||||
github.com/blevesearch/go-faiss v1.0.25 h1:lel1rkOUGbT1CJ0YgzKwC7k+XH0XVBHnCVWahdCXk4U=
|
||||
github.com/blevesearch/go-faiss v1.0.25/go.mod h1:OMGQwOaRRYxrmeNdMrXJPvVx8gBnvE5RYrr0BahNnkk=
|
||||
github.com/blevesearch/go-porterstemmer v1.0.3 h1:GtmsqID0aZdCSNiY8SkuPJ12pD4jI+DdXTAn4YRcHCo=
|
||||
github.com/blevesearch/go-porterstemmer v1.0.3/go.mod h1:angGc5Ht+k2xhJdZi511LtmxuEf0OVpvUUNrwmM1P7M=
|
||||
github.com/blevesearch/gtreap v0.1.1 h1:2JWigFrzDMR+42WGIN/V2p0cUvn4UP3C4Q5nmaZGW8Y=
|
||||
github.com/blevesearch/gtreap v0.1.1/go.mod h1:QaQyDRAT51sotthUWAH4Sj08awFSSWzgYICSZ3w0tYk=
|
||||
github.com/blevesearch/mmap-go v1.0.4 h1:OVhDhT5B/M1HNPpYPBKIEJaD0F3Si+CrEKULGCDPWmc=
|
||||
github.com/blevesearch/mmap-go v1.0.4/go.mod h1:EWmEAOmdAS9z/pi/+Toxu99DnsbhG1TIxUoRmJw/pSs=
|
||||
github.com/blevesearch/scorch_segment_api/v2 v2.3.10 h1:Yqk0XD1mE0fDZAJXTjawJ8If/85JxnLd8v5vG/jWE/s=
|
||||
github.com/blevesearch/scorch_segment_api/v2 v2.3.10/go.mod h1:Z3e6ChN3qyN35yaQpl00MfI5s8AxUJbpTR/DL8QOQ+8=
|
||||
github.com/blevesearch/segment v0.9.1 h1:+dThDy+Lvgj5JMxhmOVlgFfkUtZV2kw49xax4+jTfSU=
|
||||
github.com/blevesearch/segment v0.9.1/go.mod h1:zN21iLm7+GnBHWTao9I+Au/7MBiL8pPFtJBJTsk6kQw=
|
||||
github.com/blevesearch/snowballstem v0.9.0 h1:lMQ189YspGP6sXvZQ4WZ+MLawfV8wOmPoD/iWeNXm8s=
|
||||
github.com/blevesearch/snowballstem v0.9.0/go.mod h1:PivSj3JMc8WuaFkTSRDW2SlrulNWPl4ABg1tC/hlgLs=
|
||||
github.com/blevesearch/upsidedown_store_api v1.0.2 h1:U53Q6YoWEARVLd1OYNc9kvhBMGZzVrdmaozG2MfoB+A=
|
||||
github.com/blevesearch/upsidedown_store_api v1.0.2/go.mod h1:M01mh3Gpfy56Ps/UXHjEO/knbqyQ1Oamg8If49gRwrQ=
|
||||
github.com/blevesearch/vellum v1.1.0 h1:CinkGyIsgVlYf8Y2LUQHvdelgXr6PYuvoDIajq6yR9w=
|
||||
github.com/blevesearch/vellum v1.1.0/go.mod h1:QgwWryE8ThtNPxtgWJof5ndPfx0/YMBh+W2weHKPw8Y=
|
||||
github.com/blevesearch/zapx/v11 v11.4.2 h1:l46SV+b0gFN+Rw3wUI1YdMWdSAVhskYuvxlcgpQFljs=
|
||||
github.com/blevesearch/zapx/v11 v11.4.2/go.mod h1:4gdeyy9oGa/lLa6D34R9daXNUvfMPZqUYjPwiLmekwc=
|
||||
github.com/blevesearch/zapx/v12 v12.4.2 h1:fzRbhllQmEMUuAQ7zBuMvKRlcPA5ESTgWlDEoB9uQNE=
|
||||
github.com/blevesearch/zapx/v12 v12.4.2/go.mod h1:TdFmr7afSz1hFh/SIBCCZvcLfzYvievIH6aEISCte58=
|
||||
github.com/blevesearch/zapx/v13 v13.4.2 h1:46PIZCO/ZuKZYgxI8Y7lOJqX3Irkc3N8W82QTK3MVks=
|
||||
github.com/blevesearch/zapx/v13 v13.4.2/go.mod h1:knK8z2NdQHlb5ot/uj8wuvOq5PhDGjNYQQy0QDnopZk=
|
||||
github.com/blevesearch/zapx/v14 v14.4.2 h1:2SGHakVKd+TrtEqpfeq8X+So5PShQ5nW6GNxT7fWYz0=
|
||||
github.com/blevesearch/zapx/v14 v14.4.2/go.mod h1:rz0XNb/OZSMjNorufDGSpFpjoFKhXmppH9Hi7a877D8=
|
||||
github.com/blevesearch/zapx/v15 v15.4.2 h1:sWxpDE0QQOTjyxYbAVjt3+0ieu8NCE0fDRaFxEsp31k=
|
||||
github.com/blevesearch/zapx/v15 v15.4.2/go.mod h1:1pssev/59FsuWcgSnTa0OeEpOzmhtmr/0/11H0Z8+Nw=
|
||||
github.com/blevesearch/zapx/v16 v16.2.4 h1:tGgfvleXTAkwsD5mEzgM3zCS/7pgocTCnO1oyAUjlww=
|
||||
github.com/blevesearch/zapx/v16 v16.2.4/go.mod h1:Rti/REtuuMmzwsI8/C/qIzRaEoSK/wiFYw5e5ctUKKs=
|
||||
github.com/bmatcuk/doublestar v1.3.4 h1:gPypJ5xD31uhX6Tf54sDPUOBXTqKH4c9aPY66CyQrS0=
|
||||
github.com/bmatcuk/doublestar v1.3.4/go.mod h1:wiQtGV+rzVYxB7WIlirSN++5HPtPlXEo9MEoZQC/PmE=
|
||||
github.com/cenkalti/backoff v2.1.1+incompatible/go.mod h1:90ReRw6GdpyfrHakVjL/QHaoyV4aDUVVkXQJJJ3NXXM=
|
||||
github.com/containerd/continuity v0.0.0-20181203112020-004b46473808/go.mod h1:GL3xCUCBDV3CZiTSEKksMWbLE66hEyuu9qyDOOqM47Y=
|
||||
github.com/coreos/go-oidc/v3 v3.11.0 h1:Ia3MxdwpSw702YW0xgfmP1GVCMA9aEFWu12XUZ3/OtI=
|
||||
@@ -57,58 +110,70 @@ github.com/docker/go-connections v0.4.0/go.mod h1:Gbd7IOopHjR8Iph03tsViu4nIes5Xh
|
||||
github.com/docker/go-units v0.3.3/go.mod h1:fgPhTUdO+D/Jk86RDLlptpiXQzgHJF7gydDDbaIK4Dk=
|
||||
github.com/dustin/go-humanize v1.0.0 h1:VSnTsYCnlFHaM2/igO1h6X3HA71jcobQuxemgkq4zYo=
|
||||
github.com/dustin/go-humanize v1.0.0/go.mod h1:HtrtbFcZ19U5GC7JDqmcUSB87Iq5E25KnS6fMYU6eOk=
|
||||
github.com/dvyukov/go-fuzz v0.0.0-20200318091601-be3528f3a813/go.mod h1:11Gm+ccJnvAhCNLlf5+cS9KjtbaD5I5zaZpFMsTHWTw=
|
||||
github.com/fatih/color v1.9.0/go.mod h1:eQcE1qtQxscV5RaZvpXrrb8Drkc3/DdQ+uUYCNjL+zU=
|
||||
github.com/fogleman/gg v1.3.0 h1:/7zJX8F6AaYQc57WQCyN9cAIz+4bCJGO9B+dyW29am8=
|
||||
github.com/fogleman/gg v1.3.0/go.mod h1:R/bRT+9gY/C5z7JzPU0zXsXHKM4/ayA+zqcVNZzPa1k=
|
||||
github.com/frankban/quicktest v1.14.6 h1:7Xjx+VpznH+oBnejlPUj8oUpdxnVs4f8XU8WnHkI4W8=
|
||||
github.com/frankban/quicktest v1.14.6/go.mod h1:4ptaffx2x8+WTWXmUCuVU6aPUX1/Mz7zb5vbUoiM6w0=
|
||||
github.com/fsnotify/fsnotify v1.7.0 h1:8JEhPFa5W2WU7YfeZzPNqzMP6Lwt7L2715Ggo0nosvA=
|
||||
github.com/fsnotify/fsnotify v1.7.0/go.mod h1:40Bi/Hjc2AVfZrqy+aj+yEI+/bRxZnMJyTJwOpGvigM=
|
||||
github.com/go-jose/go-jose/v4 v4.0.2 h1:R3l3kkBds16bO7ZFAEEcofK0MkrAJt3jlJznWZG0nvk=
|
||||
github.com/go-jose/go-jose/v4 v4.0.2/go.mod h1:WVf9LFMHh/QVrmqrOfqun0C45tMe3RoiKJMPvgWwLfY=
|
||||
github.com/go-openapi/inflect v0.19.0 h1:9jCH9scKIbHeV9m12SmPilScz6krDxKRasNNSNPXu/4=
|
||||
github.com/go-openapi/inflect v0.19.0/go.mod h1:lHpZVlpIQqLyKwJ4N+YSc9hchQy/i12fJykb83CRBH4=
|
||||
github.com/go-playground/assert/v2 v2.0.1 h1:MsBgLAaY856+nPRTKrp3/OZK38U/wa0CcBYNjji3q3A=
|
||||
github.com/go-playground/assert/v2 v2.0.1/go.mod h1:VDjEfimB/XKnb+ZQfWdccd7VUvScMdVu0Titje2rxJ4=
|
||||
github.com/go-playground/locales v0.14.0 h1:u50s323jtVGugKlcYeyzC0etD1HifMjqmJqb8WugfUU=
|
||||
github.com/go-playground/locales v0.14.0/go.mod h1:sawfccIbzZTqEDETgFXqTho0QybSa7l++s0DH+LDiLs=
|
||||
github.com/go-playground/universal-translator v0.18.0 h1:82dyy6p4OuJq4/CByFNOn/jYrnRPArHwAcmLoJZxyho=
|
||||
github.com/go-playground/universal-translator v0.18.0/go.mod h1:UvRDBj+xPUEGrFYl+lu/H90nyDXpg0fqeB/AQUGNTVA=
|
||||
github.com/go-playground/validator/v10 v10.11.0 h1:0W+xRM511GY47Yy3bZUbJVitCNg2BOGlCyvTqsp/xIw=
|
||||
github.com/go-playground/validator/v10 v10.11.0/go.mod h1:i+3WkQ1FvaUjjxh1kSvIA4dMGDBiPU55YFDl0WbKdWU=
|
||||
github.com/fsnotify/fsnotify v1.9.0 h1:2Ml+OJNzbYCTzsxtv8vKSFD9PbJjmhYF14k/jKC7S9k=
|
||||
github.com/fsnotify/fsnotify v1.9.0/go.mod h1:8jBTzvmWwFyi3Pb8djgCCO5IBqzKJ/Jwo8TRcHyHii0=
|
||||
github.com/gabriel-vasile/mimetype v1.4.2 h1:w5qFW6JKBz9Y393Y4q372O9A7cUSequkh1Q7OhCmWKU=
|
||||
github.com/gabriel-vasile/mimetype v1.4.2/go.mod h1:zApsH/mKG4w07erKIaJPFiX0Tsq9BFQgN3qGY5GnNgA=
|
||||
github.com/go-jose/go-jose/v4 v4.1.2 h1:TK/7NqRQZfgAh+Td8AlsrvtPoUyiHh0LqVvokh+1vHI=
|
||||
github.com/go-jose/go-jose/v4 v4.1.2/go.mod h1:22cg9HWM1pOlnRiY+9cQYJ9XHmya1bYW8OeDM6Ku6Oo=
|
||||
github.com/go-logr/logr v1.4.3 h1:CjnDlHq8ikf6E492q6eKboGOC0T8CDaOvkHCIg8idEI=
|
||||
github.com/go-logr/logr v1.4.3/go.mod h1:9T104GzyrTigFIr8wt5mBrctHMim0Nb2HLGrmQ40KvY=
|
||||
github.com/go-logr/stdr v1.2.2 h1:hSWxHoqTgW2S2qGc0LTAI563KZ5YKYRhT3MFKZMbjag=
|
||||
github.com/go-logr/stdr v1.2.2/go.mod h1:mMo/vtBO5dYbehREoey6XUKy/eSumjCCveDpRre4VKE=
|
||||
github.com/go-openapi/inflect v0.21.3 h1:TmQvw+9eLrsNp4X0BBQacEZZtAnzk2z1FaLdQQJsDiU=
|
||||
github.com/go-openapi/inflect v0.21.3/go.mod h1:INezMuUu7SJQc2AyR3WO0DqqYUJSj8Kb4hBd7WtjlAw=
|
||||
github.com/go-playground/assert/v2 v2.2.0 h1:JvknZsQTYeFEAhQwI4qEt9cyV5ONwRHC+lYKSsYSR8s=
|
||||
github.com/go-playground/assert/v2 v2.2.0/go.mod h1:VDjEfimB/XKnb+ZQfWdccd7VUvScMdVu0Titje2rxJ4=
|
||||
github.com/go-playground/locales v0.14.1 h1:EWaQ/wswjilfKLTECiXz7Rh+3BjFhfDFKv/oXslEjJA=
|
||||
github.com/go-playground/locales v0.14.1/go.mod h1:hxrqLVvrK65+Rwrd5Fc6F2O76J/NuW9t0sjnWqG1slY=
|
||||
github.com/go-playground/universal-translator v0.18.1 h1:Bcnm0ZwsGyWbCzImXv+pAJnYK9S473LQFuzCbDbfSFY=
|
||||
github.com/go-playground/universal-translator v0.18.1/go.mod h1:xekY+UJKNuX9WP91TpwSH2VMlDf28Uj24BCp08ZFTUY=
|
||||
github.com/go-playground/validator/v10 v10.14.1 h1:9c50NUPC30zyuKprjL3vNZ0m5oG+jU0zvx4AqHGnv4k=
|
||||
github.com/go-playground/validator/v10 v10.14.1/go.mod h1:9iXMNT7sEkjXb0I+enO7QXmzG6QCsPWY4zveKFVRSyU=
|
||||
github.com/go-test/deep v1.0.3 h1:ZrJSEWsXzPOxaZnFteGEfooLba+ju3FYIbOrS+rQd68=
|
||||
github.com/go-test/deep v1.0.3/go.mod h1:wGDj63lr65AM2AQyKZd/NYHGb0R+1RLqB8NKt3aSFNA=
|
||||
github.com/go-viper/mapstructure/v2 v2.4.0 h1:EBsztssimR/CONLSZZ04E8qAkxNYq4Qp9LvH92wZUgs=
|
||||
github.com/go-viper/mapstructure/v2 v2.4.0/go.mod h1:oJDH3BJKyqBA2TXFhDsKDGDTlndYOZ6rGS0BRZIxGhM=
|
||||
github.com/godbus/dbus/v5 v5.0.4/go.mod h1:xhWf0FNVPg57R7Z0UbKHbJfkEywrmjJnf7w5xrFpKfA=
|
||||
github.com/gogo/protobuf v1.3.2 h1:Ov1cvc58UF3b5XjBnZv7+opcTcQFZebYjWzi34vdm4Q=
|
||||
github.com/gogo/protobuf v1.3.2/go.mod h1:P1XiOD3dCwIKUDQYPy72D8LYyHL2YPYrpS2s69NZV8Q=
|
||||
github.com/golang/freetype v0.0.0-20170609003504-e2365dfdc4a0 h1:DACJavvAHhabrF08vX0COfcOBJRhZ8lUbR+ZWIs0Y5g=
|
||||
github.com/golang/freetype v0.0.0-20170609003504-e2365dfdc4a0/go.mod h1:E/TSTwGwJL78qG/PmXZO1EjYhfJinVAhrmmHX6Z8B9k=
|
||||
github.com/golang/protobuf v1.1.0/go.mod h1:6lQm79b+lXiMfvg/cZm0SGofjICqVBUtrP5yJMmIC1U=
|
||||
github.com/golang/protobuf v1.3.1/go.mod h1:6lQm79b+lXiMfvg/cZm0SGofjICqVBUtrP5yJMmIC1U=
|
||||
github.com/golang/protobuf v1.3.4/go.mod h1:vzj43D7+SQXF/4pzW/hwtAqwc6iTitCiVSaWz5lYuqw=
|
||||
github.com/golang/protobuf v1.5.0/go.mod h1:FsONVRAS9T7sI+LIUmWTfcYkHO4aIWwzhcaSAoJOfIk=
|
||||
github.com/golang/protobuf v1.5.4 h1:i7eJL8qZTpSEXOPTxNKhASYpMn+8e5Q6AdndVa1dWek=
|
||||
github.com/golang/protobuf v1.5.4/go.mod h1:lnTiLA8Wa4RWRcIUkrtSVa5nRhsEGBg48fD6rSs7xps=
|
||||
github.com/golang/snappy v0.0.4 h1:yAGX7huGHXlcLOEtBnF4w7FQwA26wojNCwOYAEhLjQM=
|
||||
github.com/golang/snappy v0.0.4/go.mod h1:/XxbfmMg8lxefKM7IXC3fBNl/7bRcc72aCRzEWrmP2Q=
|
||||
github.com/google/go-cmp v0.3.1/go.mod h1:8QqcDgzrUqlUb/G2PQTWiueGozuR1884gddMywk6iLU=
|
||||
github.com/golang/snappy v0.0.1/go.mod h1:/XxbfmMg8lxefKM7IXC3fBNl/7bRcc72aCRzEWrmP2Q=
|
||||
github.com/golang/snappy v1.0.0 h1:Oy607GVXHs7RtbggtPBnr2RmDArIsAefDwvrdWvRhGs=
|
||||
github.com/golang/snappy v1.0.0/go.mod h1:/XxbfmMg8lxefKM7IXC3fBNl/7bRcc72aCRzEWrmP2Q=
|
||||
github.com/google/go-cmp v0.4.0/go.mod h1:v8dTdLbMG2kIc/vJvl+f65V22dbkXbowE6jgT/gNBxE=
|
||||
github.com/google/go-cmp v0.6.0 h1:ofyhxvXcZhMsU5ulbFiLKl/XBFqE1GSq7atu8tAmTRI=
|
||||
github.com/google/go-cmp v0.5.2/go.mod h1:v8dTdLbMG2kIc/vJvl+f65V22dbkXbowE6jgT/gNBxE=
|
||||
github.com/google/go-cmp v0.5.5/go.mod h1:v8dTdLbMG2kIc/vJvl+f65V22dbkXbowE6jgT/gNBxE=
|
||||
github.com/google/go-cmp v0.6.0/go.mod h1:17dUlkBOakJ0+DkrSSNjCkIjxS6bF9zb3elmeNGIjoY=
|
||||
github.com/google/go-cmp v0.7.0 h1:wk8382ETsv4JYUZwIsn6YpYiWiBsYLSJiTsyBybVuN8=
|
||||
github.com/google/go-cmp v0.7.0/go.mod h1:pXiqmnSA92OHEEa9HXL2W4E7lf9JzCmGVUdgjX3N/iU=
|
||||
github.com/google/gofuzz v1.0.0/go.mod h1:dBl0BpW6vV/+mYPU4Po3pmUjxk6FQPldtuIdl/M65Eg=
|
||||
github.com/google/jsonschema-go v0.3.0 h1:6AH2TxVNtk3IlvkkhjrtbUc4S8AvO0Xii0DxIygDg+Q=
|
||||
github.com/google/jsonschema-go v0.3.0/go.mod h1:r5quNTdLOYEz95Ru18zA0ydNbBuYoo9tgaYcxEYhJVE=
|
||||
github.com/google/uuid v1.1.1/go.mod h1:TIyPZe4MgqvfeYDBFedMoGGpEw/LqOeaOT+nhxU+yHo=
|
||||
github.com/google/uuid v1.6.0 h1:NIvaJDMOsjHA8n1jAhLSgzrAzy1Hgr+hNrb57e+94F0=
|
||||
github.com/google/uuid v1.6.0/go.mod h1:TIyPZe4MgqvfeYDBFedMoGGpEw/LqOeaOT+nhxU+yHo=
|
||||
github.com/gorilla/mux v1.8.0 h1:i40aqfkR1h2SlN9hojwV5ZA91wcXFOvkdNIeFDP5koI=
|
||||
github.com/gorilla/mux v1.8.0/go.mod h1:DVbg23sWSpFRCP0SfiEN6jmj59UnW/n46BH5rLB71So=
|
||||
github.com/gorilla/schema v1.4.1 h1:jUg5hUjCSDZpNGLuXQOgIWGdlgrIdYvgQ0wZtdK1M3E=
|
||||
github.com/gorilla/schema v1.4.1/go.mod h1:Dg5SSm5PV60mhF2NFaTV1xuYYj8tV8NOPRo4FggUMnM=
|
||||
github.com/gorilla/securecookie v1.1.1 h1:miw7JPhV+b/lAHSXz4qd/nN9jRiAFV5FwjeKyCS8BvQ=
|
||||
github.com/gorilla/securecookie v1.1.1/go.mod h1:ra0sb63/xPlUeL+yeDciTfxMRAA+MP+HVt/4epWDjd4=
|
||||
github.com/gorilla/sessions v1.2.1 h1:DHd3rPN5lE3Ts3D8rKkQ8x/0kqfeNmBAaiSi+o7FsgI=
|
||||
github.com/gorilla/sessions v1.2.1/go.mod h1:dk2InVEVJ0sfLlnXv9EAgkf6ecYs/i80K/zI+bUmuGM=
|
||||
github.com/gotestyourself/gotestyourself v2.2.0+incompatible/go.mod h1:zZKM6oeNM8k+FRljX1mnzVYeS8wiGgQyvST1/GafPbY=
|
||||
github.com/hashicorp/hcl v1.0.0 h1:0Anlzjpi4vEasTeNFn2mLJgTSwt0+6sfsiTG8qcWGx4=
|
||||
github.com/hashicorp/hcl v1.0.0/go.mod h1:E5yfLk+7swimpb2L/Alb/PJmXilQ/rhwaUYs4T20WEQ=
|
||||
github.com/hashicorp/hcl/v2 v2.10.0 h1:1S1UnuhDGlv3gRFV4+0EdwB+znNP5HmcGbIqwnSCByg=
|
||||
github.com/hashicorp/hcl/v2 v2.10.0/go.mod h1:FwWsfWEjyV/CMj8s/gqAuiviY72rJ1/oayI9WftqcKg=
|
||||
github.com/hashicorp/hcl/v2 v2.24.0 h1:2QJdZ454DSsYGoaE6QheQZjtKZSUs9Nh2izTWiwQxvE=
|
||||
github.com/hashicorp/hcl/v2 v2.24.0/go.mod h1:oGoO1FIQYfn/AgyOhlg9qLC6/nOJPX3qGbkZpYAcqfM=
|
||||
github.com/hexops/gotextdiff v1.0.3 h1:gitA9+qJrrTCsiCl7+kh75nPqQt1cx4ZkudSTLoUqJM=
|
||||
github.com/hexops/gotextdiff v1.0.3/go.mod h1:pSWU5MAI3yDq+fZBTazCSJysOMbxWL1BSow5/V2vxeg=
|
||||
github.com/huandu/xstrings v1.3.0/go.mod h1:y5/lhBue+AyNmUVz9RLU9xbLR0o4KIIExikq4ovT0aE=
|
||||
@@ -117,34 +182,30 @@ github.com/json-iterator/go v1.1.12 h1:PV8peI4a0ysnczrg+LtxykD8LfKY9ML6u2jnxaEnr
|
||||
github.com/json-iterator/go v1.1.12/go.mod h1:e30LSqwooZae/UwlEbR2852Gd8hjQvJoHmT4TnhNGBo=
|
||||
github.com/kisielk/errcheck v1.5.0/go.mod h1:pFxgyoBC7bSaBwPgfKdkLd5X25qrDl4LWUI2bnpBCr8=
|
||||
github.com/kisielk/gotool v1.0.0/go.mod h1:XhKaO+MFFWcvkIS/tQcRk01m1F5IRFswLeQ+oQHNcck=
|
||||
github.com/klauspost/compress v1.17.7 h1:ehO88t2UGzQK66LMdE8tibEd1ErmzZjNEqWkjLAKQQg=
|
||||
github.com/klauspost/compress v1.17.7/go.mod h1:Di0epgTjJY877eYKx5yC51cX2A2Vl2ibi7bDH9ttBbw=
|
||||
github.com/klauspost/compress v1.13.6/go.mod h1:/3/Vjq9QcHkK5uEr5lBEmyoZ1iFhe47etQ6QUkpK6sk=
|
||||
github.com/klauspost/compress v1.18.0 h1:c/Cqfb0r+Yi+JtIEq73FWXVkRonBlf0CRNYc8Zttxdo=
|
||||
github.com/klauspost/compress v1.18.0/go.mod h1:2Pp+KzxcywXVXMr50+X0Q/Lsb43OQHYWRCY2AiWywWQ=
|
||||
github.com/klauspost/cpuid/v2 v2.0.1/go.mod h1:FInQzS24/EEf25PyTYn52gqo7WaD8xa0213Md/qVLRg=
|
||||
github.com/klauspost/cpuid/v2 v2.0.4/go.mod h1:FInQzS24/EEf25PyTYn52gqo7WaD8xa0213Md/qVLRg=
|
||||
github.com/klauspost/cpuid/v2 v2.1.0 h1:eyi1Ad2aNJMW95zcSbmGg7Cg6cq3ADwLpMAP96d8rF0=
|
||||
github.com/klauspost/cpuid/v2 v2.1.0/go.mod h1:RVVoqg1df56z8g3pUjL/3lE5UfnlrJX8tyFgg4nqhuY=
|
||||
github.com/klauspost/cpuid/v2 v2.2.5 h1:0E5MSMDEoAulmXNFquVs//DdoomxaoTY1kUhbc/qbZg=
|
||||
github.com/klauspost/cpuid/v2 v2.2.5/go.mod h1:Lcz8mBdAVJIBVzewtcLocK12l3Y+JytZYpaMropDUws=
|
||||
github.com/konsorten/go-windows-terminal-sequences v1.0.1/go.mod h1:T0+1ngSBFLxvqU3pZ+m/2kptfBszLMUkC4ZK/EgS/cQ=
|
||||
github.com/kr/pretty v0.1.0/go.mod h1:dAy3ld7l9f0ibDNOQOHHMYYIIbhfbHSm3C4ZsoJORNo=
|
||||
github.com/kr/pretty v0.2.1/go.mod h1:ipq/a2n7PKx3OHsz4KJII5eveXtPO4qwEXGdVfWzfnI=
|
||||
github.com/kr/pretty v0.3.0/go.mod h1:640gp4NfQd8pI5XOwp5fnNeVWj67G7CFk/SaSQn7NBk=
|
||||
github.com/kr/pretty v0.3.1 h1:flRD4NNwYAUpkphVc1HcthR4KEIFJ65n8Mw5qdRn3LE=
|
||||
github.com/kr/pretty v0.3.1/go.mod h1:hoEshYVHaxMs3cyo3Yncou5ZscifuDolrwPKZanG3xk=
|
||||
github.com/kr/pty v1.1.1/go.mod h1:pFQYn66WHrOpPYNljwOMqo10TkYh1fy3cYio2l3bCsQ=
|
||||
github.com/kr/text v0.1.0/go.mod h1:4Jbv+DJW3UT/LiOwJeYQe1efqtUx/iVham/4vfdArNI=
|
||||
github.com/kr/text v0.2.0 h1:5Nx0Ya0ZqY2ygV366QzturHI13Jq95ApcVaJBhpS+AY=
|
||||
github.com/kr/text v0.2.0/go.mod h1:eLer722TekiGuMkidMxC/pM04lWEeraHUUmBw8l2grE=
|
||||
github.com/kylelemons/godebug v0.0.0-20170820004349-d65d576e9348 h1:MtvEpTB6LX3vkb4ax0b5D2DHbNAUsen0Gx5wZoq3lV4=
|
||||
github.com/kylelemons/godebug v0.0.0-20170820004349-d65d576e9348/go.mod h1:B69LEHPfb2qLo0BaaOLcbitczOKLWTsrBG9LczfCD4k=
|
||||
github.com/leodido/go-urn v1.2.1 h1:BqpAaACuzVSgi/VLzGZIobT2z4v53pjosyNd9Yv6n/w=
|
||||
github.com/leodido/go-urn v1.2.1/go.mod h1:zt4jvISO2HfUBqxjfIshjdMTYS56ZS/qv49ictyFfxY=
|
||||
github.com/leodido/go-urn v1.2.4 h1:XlAE/cm/ms7TE/VMVoduSpNBoyc2dOxHs5MZSwAN63Q=
|
||||
github.com/leodido/go-urn v1.2.4/go.mod h1:7ZrI8mTSeBSHl/UaRyKQW1qZeMgak41ANeCNaVckg+4=
|
||||
github.com/lib/pq v1.3.0/go.mod h1:5WUZQaWbwv1U+lTReE5YruASi9Al49XbQIvNi/34Woo=
|
||||
github.com/lib/pq v1.10.9 h1:YXG7RB+JIjhP29X+OtkiDnYaXQwpS4JEWq7dtCCRUEw=
|
||||
github.com/lib/pq v1.10.9/go.mod h1:AlVN5x4E4T544tWzH6hKfbfQvm3HdbOxrmggDNAPY9o=
|
||||
github.com/magiconair/properties v1.8.7 h1:IeQXZAiQcpL9mgcAe1Nu6cX9LLw6ExEHKjN0VQdvPDY=
|
||||
github.com/magiconair/properties v1.8.7/go.mod h1:Dhd985XPs7jluiymwWYZ0G4Z61jb3vdS329zhj2hYo0=
|
||||
github.com/mattn/go-colorable v0.1.4/go.mod h1:U0ppj6V5qS13XJ6of8GYAs25YV2eR4EVcfRqFIhoBtE=
|
||||
github.com/mattn/go-colorable v0.1.13 h1:fFA4WZxdEF4tXPZVKMLwD8oUnCTTo08duU7wxecdEvA=
|
||||
github.com/mattn/go-colorable v0.1.13/go.mod h1:7S9/ev0klgBDR4GtXTXX8a3vIGJpMovkB8vQcUbaXHg=
|
||||
github.com/mattn/go-colorable v0.1.14 h1:9A9LHSqF/7dyVVX6g0U9cwm9pG3kP9gSzcuIPHPsaIE=
|
||||
github.com/mattn/go-colorable v0.1.14/go.mod h1:6LmQG8QLFO4G5z1gPvYEzlUgJ2wF+stgPZH1UqBm1s8=
|
||||
github.com/mattn/go-isatty v0.0.8/go.mod h1:Iq45c/XA43vh69/j3iqttzPXn0bhXyGjM0Hdxcsrc5s=
|
||||
github.com/mattn/go-isatty v0.0.11/go.mod h1:PhnuNfih5lzO57/f3n+odYbM4JtupLOxQOAqxQCu2WE=
|
||||
github.com/mattn/go-isatty v0.0.16/go.mod h1:kYGgaQfpe5nmfYZH+SKPsOc2e4SrIfOl2e/yFXSvRLM=
|
||||
@@ -160,20 +221,22 @@ github.com/minio/minio-go/v7 v7.0.43/go.mod h1:nCrRzjoSUQh8hgKKtu3Y708OLvRLtuASM
|
||||
github.com/minio/sha256-simd v1.0.0 h1:v1ta+49hkWZyvaKwrQB8elexRqm6Y0aMLjCNsrYxo6g=
|
||||
github.com/minio/sha256-simd v1.0.0/go.mod h1:OuYzVNI5vcoYIAmbIvHPl3N3jUzVedXbKy5RFepssQM=
|
||||
github.com/mitchellh/copystructure v1.0.0/go.mod h1:SNtv71yrdKgLRyLFxmLdkAbkKEFWgYaq1OVrnRcwhnw=
|
||||
github.com/mitchellh/go-wordwrap v0.0.0-20150314170334-ad45545899c7 h1:DpOJ2HYzCv8LZP15IdmG+YdwD2luVPHITV96TkirNBM=
|
||||
github.com/mitchellh/go-wordwrap v0.0.0-20150314170334-ad45545899c7/go.mod h1:ZXFpozHsX6DPmq2I0TCekCxypsnAUbP2oI0UX1GXzOo=
|
||||
github.com/mitchellh/mapstructure v1.5.0 h1:jeMsZIYE/09sWLaz43PL7Gy6RuMjD2eJVyuac5Z2hdY=
|
||||
github.com/mitchellh/mapstructure v1.5.0/go.mod h1:bFUtVrKA4DC2yAKiSyO/QUcy7e+RRV2QTWOzhPopBRo=
|
||||
github.com/mitchellh/go-wordwrap v1.0.1 h1:TLuKupo69TCn6TQSyGxwI1EblZZEsQ0vMlAFQflz0v0=
|
||||
github.com/mitchellh/go-wordwrap v1.0.1/go.mod h1:R62XHJLzvMFRBbcrT7m7WgmE1eOyTSsCt+hzestvNj0=
|
||||
github.com/mitchellh/reflectwalk v1.0.0/go.mod h1:mSTlrgnPZtwu0c4WaC2kGObEpuNDbx0jmZXqmk4esnw=
|
||||
github.com/modelcontextprotocol/go-sdk v1.0.0 h1:Z4MSjLi38bTgLrd/LjSmofqRqyBiVKRyQSJgw8q8V74=
|
||||
github.com/modelcontextprotocol/go-sdk v1.0.0/go.mod h1:nYtYQroQ2KQiM0/SbyEPUWQ6xs4B95gJjEalc9AQyOs=
|
||||
github.com/modern-go/concurrent v0.0.0-20180228061459-e0a39a4cb421/go.mod h1:6dJC0mAP4ikYIbvyc7fijjWJddQyLn8Ig3JB5CqoB9Q=
|
||||
github.com/modern-go/concurrent v0.0.0-20180306012644-bacd9c7ef1dd h1:TRLaZ9cD/w8PVh93nsPXa1VrQ6jlwL5oN8l14QlcNfg=
|
||||
github.com/modern-go/concurrent v0.0.0-20180306012644-bacd9c7ef1dd/go.mod h1:6dJC0mAP4ikYIbvyc7fijjWJddQyLn8Ig3JB5CqoB9Q=
|
||||
github.com/modern-go/reflect2 v1.0.2 h1:xBagoLtFs94CBntxluKeaWgTMpvLxC4ur3nMaC9Gz0M=
|
||||
github.com/modern-go/reflect2 v1.0.2/go.mod h1:yWuevngMOJpCy52FWWMvUC8ws7m/LJsjYzDa0/r8luk=
|
||||
github.com/mohae/deepcopy v0.0.0-20170929034955-c48cc78d4826 h1:RWengNIwukTxcDr9M+97sNutRR1RKhG96O6jWumTTnw=
|
||||
github.com/mohae/deepcopy v0.0.0-20170929034955-c48cc78d4826/go.mod h1:TaXosZuwdSHYgviHp1DAtfrULt5eUgsSMsZf+YrPgl8=
|
||||
github.com/montanaflynn/stats v0.0.0-20171201202039-1bf9dbcd8cbe/go.mod h1:wL8QJuTMNUDYhXwkmfOly8iTdp5TEcJFWZD2D7SIkUc=
|
||||
github.com/montanaflynn/stats v0.7.1 h1:etflOAAHORrCC44V+aR6Ftzort912ZU+YLiSTuV8eaE=
|
||||
github.com/montanaflynn/stats v0.7.1/go.mod h1:etXPPgVO6n31NxCd9KQUMvCM+ve0ruNzt6R8Bnaayow=
|
||||
github.com/mschoch/smat v0.2.0 h1:8imxQsjDm8yFEAVBe7azKmKSgzSkZXDuKkSq9374khM=
|
||||
github.com/mschoch/smat v0.2.0/go.mod h1:kc9mz7DoBKqDyiRL7VZN8KvXQMWeTaVnttLRXOlotKw=
|
||||
github.com/niemeyer/pretty v0.0.0-20200227124842-a10e7caefd8e h1:fD57ERR4JtEqsWbfPhv4DMiApHyliiK5xCTNVSPiaAs=
|
||||
github.com/niemeyer/pretty v0.0.0-20200227124842-a10e7caefd8e/go.mod h1:zD1mROLANZcx1PVRCS0qkT7pwLkGfwJo4zjcN/Tysno=
|
||||
github.com/opencontainers/go-digest v1.0.0-rc1/go.mod h1:cMLVZDEM3+U2I4VmLI6N8jQYUd2OVphdqWwCJHrFt2s=
|
||||
github.com/opencontainers/image-spec v1.0.1/go.mod h1:BtxoFyWECRxE4U/7sNtV5W15zMzWCbyJoFRP3s7yZA0=
|
||||
@@ -181,9 +244,11 @@ github.com/opencontainers/runc v0.1.1/go.mod h1:qT5XzbpPznkRYVz/mWwUaVBUv2rmF59P
|
||||
github.com/ory/dockertest v3.3.4+incompatible/go.mod h1:1vX4m9wsvi00u5bseYwXaSnhNrne+V0E6LAcBILJdPs=
|
||||
github.com/paulmach/go.geojson v1.4.0 h1:5x5moCkCtDo5x8af62P9IOAYGQcYHtxz2QJ3x1DoCgY=
|
||||
github.com/paulmach/go.geojson v1.4.0/go.mod h1:YaKx1hKpWF+T2oj2lFJPsW/t1Q5e1jQI61eoQSTwpIs=
|
||||
github.com/pelletier/go-toml/v2 v2.2.2 h1:aYUidT7k73Pcl9nb2gScu7NSrKCSHIDE89b3+6Wq+LM=
|
||||
github.com/pelletier/go-toml/v2 v2.2.2/go.mod h1:1t835xjRzz80PqgE6HHgN2JOsmgYu/h4qDAS4n929Rs=
|
||||
github.com/pkg/diff v0.0.0-20210226163009-20ebb0f2a09e/go.mod h1:pJLUxLENpZxwdsKMEsNbx1VGcRFpLqf3715MtcvvzbA=
|
||||
github.com/paulmach/orb v0.12.0 h1:z+zOwjmG3MyEEqzv92UN49Lg1JFYx0L9GpGKNVDKk1s=
|
||||
github.com/paulmach/orb v0.12.0/go.mod h1:5mULz1xQfs3bmQm63QEJA6lNGujuRafwA5S/EnuLaLU=
|
||||
github.com/paulmach/protoscan v0.2.1/go.mod h1:SpcSwydNLrxUGSDvXvO0P7g7AuhJ7lcKfDlhJCDw2gY=
|
||||
github.com/pelletier/go-toml/v2 v2.2.4 h1:mye9XuhQ6gvn5h28+VilKrrPoQVanw5PMw/TB0t5Ec4=
|
||||
github.com/pelletier/go-toml/v2 v2.2.4/go.mod h1:2gIqNv+qfxSVS7cM2xJQKtLSTLUE9V8t9Stt+h56mCY=
|
||||
github.com/pkg/errors v0.8.1/go.mod h1:bwawxfHBFNV+L2hUp1rHADufV3IMtnDRdf1r5NINEl0=
|
||||
github.com/pkg/errors v0.9.1 h1:FEBLx1zS214owpjy7qsBeixbURkuhQAwrK5UwLGTwt4=
|
||||
github.com/pkg/errors v0.9.1/go.mod h1:bwawxfHBFNV+L2hUp1rHADufV3IMtnDRdf1r5NINEl0=
|
||||
@@ -193,174 +258,173 @@ github.com/pmezard/go-difflib v1.0.1-0.20181226105442-5d4384ee4fb2/go.mod h1:iKH
|
||||
github.com/richardlehane/mscfb v1.0.4 h1:WULscsljNPConisD5hR0+OyZjwK46Pfyr6mPu5ZawpM=
|
||||
github.com/richardlehane/mscfb v1.0.4/go.mod h1:YzVpcZg9czvAuhk9T+a3avCpcFPMUWm7gK3DypaEsUk=
|
||||
github.com/richardlehane/msoleps v1.0.1/go.mod h1:BWev5JBpU9Ko2WAgmZEuiz4/u3ZYTKbjLycmwiWUfWg=
|
||||
github.com/richardlehane/msoleps v1.0.3 h1:aznSZzrwYRl3rLKRT3gUk9am7T/mLNSnJINvN0AQoVM=
|
||||
github.com/richardlehane/msoleps v1.0.3/go.mod h1:BWev5JBpU9Ko2WAgmZEuiz4/u3ZYTKbjLycmwiWUfWg=
|
||||
github.com/rogpeppe/go-internal v1.6.1/go.mod h1:xXDCJY+GAPziupqXw64V24skbSoqbTEfhy4qGm1nDQc=
|
||||
github.com/rogpeppe/go-internal v1.8.0/go.mod h1:WmiCO8CzOY8rg0OYDC4/i/2WRWAB6poM+XZ2dLUbcbE=
|
||||
github.com/richardlehane/msoleps v1.0.4 h1:WuESlvhX3gH2IHcd8UqyCuFY5yiq/GR/yqaSM/9/g00=
|
||||
github.com/richardlehane/msoleps v1.0.4/go.mod h1:BWev5JBpU9Ko2WAgmZEuiz4/u3ZYTKbjLycmwiWUfWg=
|
||||
github.com/rogpeppe/go-internal v1.9.0 h1:73kH8U+JUqXU8lRuOHeVHaa/SZPifC7BkcraZVejAe8=
|
||||
github.com/rogpeppe/go-internal v1.9.0/go.mod h1:WtVeX8xhTBvf0smdhujwtBcq4Qrzq/fJaraNFVN+nFs=
|
||||
github.com/rs/xid v1.5.0 h1:mKX4bl4iPYJtEIxp6CYiUuLQ/8DYMoz0PUdtGgMFRVc=
|
||||
github.com/rs/xid v1.5.0/go.mod h1:trrq9SKmegXys3aeAKXMUTdJsYXVwGY3RLcfgqegfbg=
|
||||
github.com/rs/zerolog v1.33.0 h1:1cU2KZkvPxNyfgEmhHAz/1A9Bz+llsdYzklWFzgp0r8=
|
||||
github.com/rs/zerolog v1.33.0/go.mod h1:/7mN4D5sKwJLZQ2b/znpjC3/GQWY/xaDXUM0kKWRHss=
|
||||
github.com/sagikazarmark/locafero v0.4.0 h1:HApY1R9zGo4DBgr7dqsTH/JJxLTTsOt7u6keLGt6kNQ=
|
||||
github.com/sagikazarmark/locafero v0.4.0/go.mod h1:Pe1W6UlPYUk/+wc/6KFhbORCfqzgYEpgQ3O5fPuL3H4=
|
||||
github.com/sagikazarmark/slog-shim v0.1.0 h1:diDBnUNK9N/354PgrxMywXnAwEr1QZcOr6gto+ugjYE=
|
||||
github.com/sagikazarmark/slog-shim v0.1.0/go.mod h1:SrcSrq8aKtyuqEI1uvTDTK1arOWRIczQRv+GVI1AkeQ=
|
||||
github.com/rs/xid v1.6.0 h1:fV591PaemRlL6JfRxGDEPl69wICngIQ3shQtzfy2gxU=
|
||||
github.com/rs/xid v1.6.0/go.mod h1:7XoLgs4eV+QndskICGsho+ADou8ySMSjJKDIan90Nz0=
|
||||
github.com/rs/zerolog v1.34.0 h1:k43nTLIwcTVQAncfCw4KZ2VY6ukYoZaBPNOE8txlOeY=
|
||||
github.com/rs/zerolog v1.34.0/go.mod h1:bJsvje4Z08ROH4Nhs5iH600c3IkWhwp44iRc54W6wYQ=
|
||||
github.com/sagikazarmark/locafero v0.12.0 h1:/NQhBAkUb4+fH1jivKHWusDYFjMOOKU88eegjfxfHb4=
|
||||
github.com/sagikazarmark/locafero v0.12.0/go.mod h1:sZh36u/YSZ918v0Io+U9ogLYQJ9tLLBmM4eneO6WwsI=
|
||||
github.com/santhosh-tekuri/jsonschema/v5 v5.0.0 h1:TToq11gyfNlrMFZiYujSekIsPd9AmsA2Bj/iv+s4JHE=
|
||||
github.com/santhosh-tekuri/jsonschema/v5 v5.0.0/go.mod h1:FKdcjfQW6rpZSnxxUvEA5H/cDPdvJ/SZJQLWWXWGrZ0=
|
||||
github.com/sergi/go-diff v1.0.0/go.mod h1:0CfEIISq7TuYL3j771MWULgwwjU+GofnZX9QAmXWZgo=
|
||||
github.com/sergi/go-diff v1.1.0 h1:we8PVUC3FE2uYfodKH/nBHMSetSfHDR6scGdBi+erh0=
|
||||
github.com/sergi/go-diff v1.1.0/go.mod h1:STckp+ISIX8hZLjrqAeVduY0gWCT9IjLuqbuNXdaHfM=
|
||||
github.com/sirupsen/logrus v1.4.1/go.mod h1:ni0Sbl8bgC9z8RoU9G6nDWqqs/fq4eDPysMBDgk/93Q=
|
||||
github.com/sirupsen/logrus v1.9.3 h1:dueUQJ1C2q9oE3F7wvmSGAaVtTmUizReu6fjN8uqzbQ=
|
||||
github.com/sirupsen/logrus v1.9.3/go.mod h1:naHLuLoDiP4jHNo9R0sCBMtWGeIprob74mVsIT4qYEQ=
|
||||
github.com/sourcegraph/conc v0.3.0 h1:OQTbbt6P72L20UqAkXXuLOj79LfEanQ+YQFNpLA9ySo=
|
||||
github.com/sourcegraph/conc v0.3.0/go.mod h1:Sdozi7LEKbFPqYX2/J+iBAM6HpqSLTASQIKqDmF7Mt0=
|
||||
github.com/spf13/afero v1.11.0 h1:WJQKhtpdm3v2IzqG8VMqrr6Rf3UYpEF239Jy9wNepM8=
|
||||
github.com/spf13/afero v1.11.0/go.mod h1:GH9Y3pIexgf1MTIWtNGyogA5MwRIDXGUr+hbWNoBjkY=
|
||||
github.com/spf13/cast v1.6.0 h1:GEiTHELF+vaR5dhz3VqZfFSzZjYbgeKDpBxQVS4GYJ0=
|
||||
github.com/spf13/cast v1.6.0/go.mod h1:ancEpBxwJDODSW/UG4rDrAqiKolqNNh2DX3mk86cAdo=
|
||||
github.com/spf13/pflag v1.0.2/go.mod h1:DYY7MBk1bdzusC3SYhjObp+wFpr4gzcvqqNjLnInEg4=
|
||||
github.com/spf13/pflag v1.0.5 h1:iy+VFUOCP1a+8yFto/drg2CJ5u0yRoB7fZw3DKv/JXA=
|
||||
github.com/spf13/pflag v1.0.5/go.mod h1:McXfInJRrz4CZXVZOBLb0bTZqETkiAhM9Iw0y3An2Bg=
|
||||
github.com/spf13/viper v1.19.0 h1:RWq5SEjt8o25SROyN3z2OrDB9l7RPd3lwTWU8EcEdcI=
|
||||
github.com/spf13/viper v1.19.0/go.mod h1:GQUN9bilAbhU/jgc1bKs99f/suXKeUMct8Adx5+Ntkg=
|
||||
github.com/spf13/afero v1.15.0 h1:b/YBCLWAJdFWJTN9cLhiXXcD7mzKn9Dm86dNnfyQw1I=
|
||||
github.com/spf13/afero v1.15.0/go.mod h1:NC2ByUVxtQs4b3sIUphxK0NioZnmxgyCrfzeuq8lxMg=
|
||||
github.com/spf13/cast v1.10.0 h1:h2x0u2shc1QuLHfxi+cTJvs30+ZAHOGRic8uyGTDWxY=
|
||||
github.com/spf13/cast v1.10.0/go.mod h1:jNfB8QC9IA6ZuY2ZjDp0KtFO2LZZlg4S/7bzP6qqeHo=
|
||||
github.com/spf13/pflag v1.0.10 h1:4EBh2KAYBwaONj6b2Ye1GiHfwjqyROoF4RwYO+vPwFk=
|
||||
github.com/spf13/pflag v1.0.10/go.mod h1:McXfInJRrz4CZXVZOBLb0bTZqETkiAhM9Iw0y3An2Bg=
|
||||
github.com/spf13/viper v1.21.0 h1:x5S+0EU27Lbphp4UKm1C+1oQO+rKx36vfCoaVebLFSU=
|
||||
github.com/spf13/viper v1.21.0/go.mod h1:P0lhsswPGWD/1lZJ9ny3fYnVqxiegrlNrEmgLjbTCAY=
|
||||
github.com/stretchr/objx v0.1.0/go.mod h1:HFkY916IF+rwdDfMAkV7OtwuqBVzrE8GR6GFx+wExME=
|
||||
github.com/stretchr/objx v0.1.1/go.mod h1:HFkY916IF+rwdDfMAkV7OtwuqBVzrE8GR6GFx+wExME=
|
||||
github.com/stretchr/objx v0.3.0/go.mod h1:qt09Ya8vawLte6SNmTgCsAVtYtaKzEcn8ATUoHMkEqE=
|
||||
github.com/stretchr/objx v0.4.0/go.mod h1:YvHI0jy2hoMjB+UWwv71VJQ9isScKT/TqJzVSSt89Yw=
|
||||
github.com/stretchr/objx v0.5.0/go.mod h1:Yh+to48EsGEfYuaHDzXPcE3xhTkx73EhmCGUpEOglKo=
|
||||
github.com/stretchr/objx v0.5.2/go.mod h1:FRsXN1f5AsAjCGJKqEizvkpNtU+EGNCLh3NxZ/8L+MA=
|
||||
github.com/stretchr/objx v0.5.3 h1:jmXUvGomnU1o3W/V5h2VEradbpJDwGrzugQQvL0POH4=
|
||||
github.com/stretchr/objx v0.5.3/go.mod h1:rDQraq+vQZU7Fde9LOZLr8Tax6zZvy4kuNKF+QYS+U0=
|
||||
github.com/stretchr/testify v1.2.2/go.mod h1:a8OnRcib4nhh0OaRAV+Yts87kKdq0PP7pXfy6kDkUVs=
|
||||
github.com/stretchr/testify v1.3.0/go.mod h1:M5WIy9Dh21IEIfnGCwXGc5bZfKNJtfHm1UVUgZn+9EI=
|
||||
github.com/stretchr/testify v1.4.0/go.mod h1:j7eGeouHqKxXV5pUuKE4zz7dFj8WfuZ+81PSLYec5m4=
|
||||
github.com/stretchr/testify v1.5.1/go.mod h1:5W2xD1RspED5o8YsWQXVCued0rvSQ+mT+I5cxcmMvtA=
|
||||
github.com/stretchr/testify v1.6.1/go.mod h1:6Fq8oRcR53rry900zMqJjRRixrwX3KX962/h/Wwjteg=
|
||||
github.com/stretchr/testify v1.7.0/go.mod h1:6Fq8oRcR53rry900zMqJjRRixrwX3KX962/h/Wwjteg=
|
||||
github.com/stretchr/testify v1.7.1/go.mod h1:6Fq8oRcR53rry900zMqJjRRixrwX3KX962/h/Wwjteg=
|
||||
github.com/stretchr/testify v1.8.0/go.mod h1:yNjHg4UonilssWZ8iaSj1OCr/vHnekPRkoO+kdMU+MU=
|
||||
github.com/stretchr/testify v1.8.4/go.mod h1:sz/lmYIOXD/1dqDmKjjqLyZ2RngseejIcXlSw2iwfAo=
|
||||
github.com/stretchr/testify v1.9.0 h1:HtqpIVDClZ4nwg75+f6Lvsy/wHu+3BoSGCbBAcpTsTg=
|
||||
github.com/stretchr/testify v1.9.0/go.mod h1:r2ic/lqez/lEtzL7wO/rwa5dbSLXVDPFyf8C91i36aY=
|
||||
github.com/stretchr/testify v1.8.2/go.mod h1:w2LPCIKwWwSfY2zedu0+kehJoqGctiVI29o6fzry7u4=
|
||||
github.com/stretchr/testify v1.11.1 h1:7s2iGBzp5EwR7/aIZr8ao5+dra3wiQyKjjFuvgVKu7U=
|
||||
github.com/stretchr/testify v1.11.1/go.mod h1:wZwfW3scLgRK+23gO65QZefKpKQRnfz6sD981Nm4B6U=
|
||||
github.com/subosito/gotenv v1.6.0 h1:9NlTDc1FTs4qu0DDq7AEtTPNw6SVm7uBMsUCUjABIf8=
|
||||
github.com/subosito/gotenv v1.6.0/go.mod h1:Dk4QP5c2W3ibzajGcXpNraDfq2IrhjMIvMSWPKKo0FU=
|
||||
github.com/tidwall/cities v0.1.0 h1:CVNkmMf7NEC9Bvokf5GoSsArHCKRMTgLuubRTHnH0mE=
|
||||
github.com/tidwall/cities v0.1.0/go.mod h1:lV/HDp2gCcRcHJWqgt6Di54GiDrTZwh1aG2ZUPNbqa4=
|
||||
github.com/tidwall/geoindex v1.7.0 h1:jtk41sfgwIt8MEDyC3xyKSj75iXXf6rjReJGDNPtR5o=
|
||||
github.com/tidwall/geoindex v1.7.0/go.mod h1:rvVVNEFfkJVWGUdEfU8QaoOg/9zFX0h9ofWzA60mz1I=
|
||||
github.com/tidwall/lotsa v1.0.2 h1:dNVBH5MErdaQ/xd9s769R31/n2dXavsQ0Yf4TMEHHw8=
|
||||
github.com/tidwall/lotsa v1.0.2/go.mod h1:X6NiU+4yHA3fE3Puvpnn1XMDrFZrE9JO2/w+UMuqgR8=
|
||||
github.com/tidwall/pretty v1.0.0/go.mod h1:XNkn88O1ChpSDQmQeStsy+sBenx6DDtFZJxhVysOjyk=
|
||||
github.com/tidwall/rtree v1.10.0 h1:+EcI8fboEaW1L3/9oW/6AMoQ8HiEIHyR7bQOGnmz4Mg=
|
||||
github.com/tidwall/rtree v1.10.0/go.mod h1:iDJQ9NBRtbfKkzZu02za+mIlaP+bjYPnunbSNidpbCQ=
|
||||
github.com/tiendc/go-deepcopy v1.7.1 h1:LnubftI6nYaaMOcaz0LphzwraqN8jiWTwm416sitff4=
|
||||
github.com/tiendc/go-deepcopy v1.7.1/go.mod h1:4bKjNC2r7boYOkD2IOuZpYjmlDdzjbpTRyCx+goBCJQ=
|
||||
github.com/twpayne/go-geom v1.2.1/go.mod h1:90yvs0wf/gyT5eQ9W4v5WOZ9w/Xnrj5RMlA9XNKqxyA=
|
||||
github.com/twpayne/go-geom v1.5.7 h1:7fdceDUr03/MP7rAKOaTV6x9njMiQdxB/D0PDzMTCDc=
|
||||
github.com/twpayne/go-geom v1.5.7/go.mod h1:y4fTAQtLedXW8eG2Yo4tYrIGN1yIwwKkmA+K3iSHKBA=
|
||||
github.com/twpayne/go-kml v1.5.0/go.mod h1:g/OG8Q8JUxqFw8LGXE44W7osn1uXDAYaVFr1Yld43yc=
|
||||
github.com/twpayne/go-polyline v1.0.0/go.mod h1:ICh24bcLYBX8CknfvNPKqoTbe+eg+MX1NPyJmSBo7pU=
|
||||
github.com/vmihailenco/msgpack v3.3.3+incompatible/go.mod h1:fy3FlTQTDXWkZ7Bh6AcGMlsjHatGryHQYUTf1ShIgkk=
|
||||
github.com/vmihailenco/msgpack/v4 v4.3.12/go.mod h1:gborTTJjAo/GWTqqRjrLCn9pgNN+NXzzngzBKDPIqw4=
|
||||
github.com/vmihailenco/tagparser v0.1.1/go.mod h1:OeAg3pn3UbLjkWt+rN9oFYB6u/cQgqMEUPoW2WPyhdI=
|
||||
github.com/wneessen/go-mail v0.5.2 h1:MZKwgHJoRboLJ+EHMLuHpZc95wo+u1xViL/4XSswDT8=
|
||||
github.com/wneessen/go-mail v0.5.2/go.mod h1:kRroJvEq2hOSEPFRiKjN7Csrz0G1w+RpiGR3b6yo+Ck=
|
||||
github.com/twpayne/go-polyline v1.1.1 h1:/tSF1BR7rN4HWj4XKqvRUNrCiYVMCvywxTFVofvDV0w=
|
||||
github.com/twpayne/go-polyline v1.1.1/go.mod h1:ybd9IWWivW/rlXPXuuckeKUyF3yrIim+iqA7kSl4NFY=
|
||||
github.com/xdg-go/pbkdf2 v1.0.0 h1:Su7DPu48wXMwC3bs7MCNG+z4FhcyEuz5dlvchbq0B0c=
|
||||
github.com/xdg-go/pbkdf2 v1.0.0/go.mod h1:jrpuAogTd400dnrH08LKmI/xc1MbPOebTwRqcT5RDeI=
|
||||
github.com/xdg-go/scram v1.1.1/go.mod h1:RaEWvsqvNKKvBPvcKeFjrG2cJqOkHTiyTpzz23ni57g=
|
||||
github.com/xdg-go/scram v1.1.2 h1:FHX5I5B4i4hKRVRBCFRxq1iQRej7WO3hhBuJf+UUySY=
|
||||
github.com/xdg-go/scram v1.1.2/go.mod h1:RT/sEzTbU5y00aCK8UOx6R7YryM0iF1N2MOmC3kKLN4=
|
||||
github.com/xdg-go/stringprep v1.0.3/go.mod h1:W3f5j4i+9rC0kuIEJL0ky1VpHXQU3ocBgklLGvcBnW8=
|
||||
github.com/xdg-go/stringprep v1.0.4 h1:XLI/Ng3O1Atzq0oBs3TWm+5ZVgkq2aqdlvP9JtoZ6c8=
|
||||
github.com/xdg-go/stringprep v1.0.4/go.mod h1:mPGuuIYwz7CmR2bT9j4GbQqutWS1zV24gijq1dTyGkM=
|
||||
github.com/xuri/efp v0.0.0-20220603152613-6918739fd470 h1:6932x8ltq1w4utjmfMPVj09jdMlkY0aiA6+Skbtl3/c=
|
||||
github.com/xuri/efp v0.0.0-20220603152613-6918739fd470/go.mod h1:ybY/Jr0T0GTCnYjKqmdwxyxn2BQf2RcQIIvex5QldPI=
|
||||
github.com/xuri/excelize/v2 v2.7.1 h1:gm8q0UCAyaTt3MEF5wWMjVdmthm2EHAWesGSKS9tdVI=
|
||||
github.com/xuri/excelize/v2 v2.7.1/go.mod h1:qc0+2j4TvAUrBw36ATtcTeC1VCM0fFdAXZOmcF4nTpY=
|
||||
github.com/xuri/nfp v0.0.0-20220409054826-5e722a1d9e22 h1:OAmKAfT06//esDdpi/DZ8Qsdt4+M5+ltca05dA5bG2M=
|
||||
github.com/xuri/nfp v0.0.0-20220409054826-5e722a1d9e22/go.mod h1:WwHg+CVyzlv/TX9xqBFXEZAuxOPxn2k1GNHwG41IIUQ=
|
||||
github.com/xuri/efp v0.0.1 h1:fws5Rv3myXyYni8uwj2qKjVaRP30PdjeYe2Y6FDsCL8=
|
||||
github.com/xuri/efp v0.0.1/go.mod h1:ybY/Jr0T0GTCnYjKqmdwxyxn2BQf2RcQIIvex5QldPI=
|
||||
github.com/xuri/excelize/v2 v2.9.1 h1:VdSGk+rraGmgLHGFaGG9/9IWu1nj4ufjJ7uwMDtj8Qw=
|
||||
github.com/xuri/excelize/v2 v2.9.1/go.mod h1:x7L6pKz2dvo9ejrRuD8Lnl98z4JLt0TGAwjhW+EiP8s=
|
||||
github.com/xuri/nfp v0.0.1 h1:MDamSGatIvp8uOmDP8FnmjuQpu90NzdJxo7242ANR9Q=
|
||||
github.com/xuri/nfp v0.0.1/go.mod h1:WwHg+CVyzlv/TX9xqBFXEZAuxOPxn2k1GNHwG41IIUQ=
|
||||
github.com/yosida95/uritemplate/v3 v3.0.2 h1:Ed3Oyj9yrmi9087+NczuL5BwkIc4wvTb5zIM+UJPGz4=
|
||||
github.com/yosida95/uritemplate/v3 v3.0.2/go.mod h1:ILOh0sOhIJR3+L/8afwt/kE++YT040gmv5BQTMR2HP4=
|
||||
github.com/youmark/pkcs8 v0.0.0-20181117223130-1be2e3e5546d/go.mod h1:rHwXgn7JulP+udvsHwJoVG1YGAP6VLg4y9I5dyZdqmA=
|
||||
github.com/youmark/pkcs8 v0.0.0-20240726163527-a2c0da244d78 h1:ilQV1hzziu+LLM3zUTJ0trRztfwgjqKnBWNtSRkbmwM=
|
||||
github.com/youmark/pkcs8 v0.0.0-20240726163527-a2c0da244d78/go.mod h1:aL8wCCfTfSfmXjznFBSZNN13rSJjlIOI1fUNAtF7rmI=
|
||||
github.com/yuin/goldmark v1.1.27/go.mod h1:3hX8gzYuyVAZsxl0MRgGTJEmQBFcNTphYh9decYSb74=
|
||||
github.com/yuin/goldmark v1.2.1/go.mod h1:3hX8gzYuyVAZsxl0MRgGTJEmQBFcNTphYh9decYSb74=
|
||||
github.com/yuin/goldmark v1.3.5/go.mod h1:mwnBkeHKe2W/ZEtQ+71ViKU8L12m81fl3OWwC1Zlc8k=
|
||||
github.com/yuin/goldmark v1.4.13/go.mod h1:6yULJ656Px+3vBD8DxQVa3kxgyrAnzto9xy5taEt/CY=
|
||||
github.com/zclconf/go-cty v1.2.0/go.mod h1:hOPWgoHbaTUnI5k4D2ld+GRpFJSCe6bCM7m1q/N4PQ8=
|
||||
github.com/zclconf/go-cty v1.8.0 h1:s4AvqaeQzJIu3ndv4gVIhplVD0krU+bgrcLSVUnaWuA=
|
||||
github.com/zclconf/go-cty v1.8.0/go.mod h1:vVKLxnk3puL4qRAv72AO+W99LUD4da90g3uUAzyuvAk=
|
||||
github.com/zclconf/go-cty-debug v0.0.0-20191215020915-b22d67c1ba0b/go.mod h1:ZRKQfBXbGkpdV6QMzT3rU1kSTAnfu1dO8dPKjYprgj8=
|
||||
github.com/zclconf/go-cty v1.17.0 h1:seZvECve6XX4tmnvRzWtJNHdscMtYEx5R7bnnVyd/d0=
|
||||
github.com/zclconf/go-cty v1.17.0/go.mod h1:wqFzcImaLTI6A5HfsRwB0nj5n0MRZFwmey8YoFPPs3U=
|
||||
github.com/zclconf/go-cty-debug v0.0.0-20240509010212-0d6042c53940 h1:4r45xpDWB6ZMSMNJFMOjqrGHynW3DIBuR2H9j0ug+Mo=
|
||||
github.com/zclconf/go-cty-debug v0.0.0-20240509010212-0d6042c53940/go.mod h1:CmBdvvj3nqzfzJ6nTCIwDTPZ56aVGvDrmztiO5g3qrM=
|
||||
github.com/zclconf/go-cty-yaml v1.1.0 h1:nP+jp0qPHv2IhUVqmQSzjvqAWcObN0KBkUl2rWBdig0=
|
||||
github.com/zclconf/go-cty-yaml v1.1.0/go.mod h1:9YLUH4g7lOhVWqUbctnVlZ5KLpg7JAprQNgxSZ1Gyxs=
|
||||
gitlab.scity.coop/maas/navitia-golang v0.0.0-20220429110621-5c22d6efdd0c h1:pCazzEsTvjDopl3bvo6H2f2xjo1cDjOZ9QpJRNFCc00=
|
||||
gitlab.scity.coop/maas/navitia-golang v0.0.0-20220429110621-5c22d6efdd0c/go.mod h1:M1U2osA6dYQF8zuJOTb/0O1F/Xgcb+4AkRdw+Un6Rp4=
|
||||
go.etcd.io/bbolt v1.4.0 h1:TU77id3TnN/zKr7CO/uk+fBCwF2jGcMuw2B/FMAzYIk=
|
||||
go.etcd.io/bbolt v1.4.0/go.mod h1:AsD+OCi/qPN1giOX1aiLAha3o1U8rAz65bvN4j0sRuk=
|
||||
go.etcd.io/etcd/api/v3 v3.5.12 h1:W4sw5ZoU2Juc9gBWuLk5U6fHfNVyY1WC5g9uiXZio/c=
|
||||
go.etcd.io/etcd/api/v3 v3.5.12/go.mod h1:Ot+o0SWSyT6uHhA56al1oCED0JImsRiU9Dc26+C2a+4=
|
||||
go.etcd.io/etcd/client/pkg/v3 v3.5.12 h1:EYDL6pWwyOsylrQyLp2w+HkQ46ATiOvoEdMarindU2A=
|
||||
go.etcd.io/etcd/client/pkg/v3 v3.5.12/go.mod h1:seTzl2d9APP8R5Y2hFL3NVlD6qC/dOT+3kvrqPyTas4=
|
||||
go.etcd.io/etcd/client/v3 v3.5.12 h1:v5lCPXn1pf1Uu3M4laUE2hp/geOTc5uPcYYsNe1lDxg=
|
||||
go.etcd.io/etcd/client/v3 v3.5.12/go.mod h1:tSbBCakoWmmddL+BKVAJHa9km+O/E+bumDe9mSbPiqw=
|
||||
go.mongodb.org/mongo-driver v1.17.1 h1:Wic5cJIwJgSpBhe3lx3+/RybR5PiYRMpVFgO7cOHyIM=
|
||||
go.mongodb.org/mongo-driver v1.17.1/go.mod h1:wwWm/+BuOddhcq3n68LKRmgk2wXzmF6s0SFOa0GINL4=
|
||||
go.mongodb.org/mongo-driver v1.11.4/go.mod h1:PTSz5yu21bkT/wXpkS7WR5f0ddqw5quethTUn9WM+2g=
|
||||
go.mongodb.org/mongo-driver v1.17.4 h1:jUorfmVzljjr0FLzYQsGP8cgN/qzzxlY9Vh0C9KFXVw=
|
||||
go.mongodb.org/mongo-driver v1.17.4/go.mod h1:Hy04i7O2kC4RS06ZrhPRqj/u4DTYkFDAAccj+rVKqgQ=
|
||||
go.opentelemetry.io/auto/sdk v1.1.0 h1:cH53jehLUN6UFLY71z+NDOiNJqDdPRaXzTel0sJySYA=
|
||||
go.opentelemetry.io/auto/sdk v1.1.0/go.mod h1:3wSPjt5PWp2RhlCcmmOial7AvC4DQqZb7a7wCow3W8A=
|
||||
go.opentelemetry.io/otel v1.37.0 h1:9zhNfelUvx0KBfu/gb+ZgeAfAgtWrfHJZcAqFC228wQ=
|
||||
go.opentelemetry.io/otel v1.37.0/go.mod h1:ehE/umFRLnuLa/vSccNq9oS1ErUlkkK71gMcN34UG8I=
|
||||
go.opentelemetry.io/otel/metric v1.37.0 h1:mvwbQS5m0tbmqML4NqK+e3aDiO02vsf/WgbsdpcPoZE=
|
||||
go.opentelemetry.io/otel/metric v1.37.0/go.mod h1:04wGrZurHYKOc+RKeye86GwKiTb9FKm1WHtO+4EVr2E=
|
||||
go.opentelemetry.io/otel/sdk v1.37.0 h1:ItB0QUqnjesGRvNcmAcU0LyvkVyGJ2xftD29bWdDvKI=
|
||||
go.opentelemetry.io/otel/sdk v1.37.0/go.mod h1:VredYzxUvuo2q3WRcDnKDjbdvmO0sCzOvVAiY+yUkAg=
|
||||
go.opentelemetry.io/otel/sdk/metric v1.37.0 h1:90lI228XrB9jCMuSdA0673aubgRobVZFhbjxHHspCPc=
|
||||
go.opentelemetry.io/otel/sdk/metric v1.37.0/go.mod h1:cNen4ZWfiD37l5NhS+Keb5RXVWZWpRE+9WyVCpbo5ps=
|
||||
go.opentelemetry.io/otel/trace v1.37.0 h1:HLdcFNbRQBE2imdSEgm/kwqmQj1Or1l/7bW6mxVK7z4=
|
||||
go.opentelemetry.io/otel/trace v1.37.0/go.mod h1:TlgrlQ+PtQO5XFerSPUYG0JSgGyryXewPGyayAWSBS0=
|
||||
go.uber.org/atomic v1.7.0/go.mod h1:fEN4uk6kAWBTFdckzkM89CLk9XfWZrxpCo0nPH17wJc=
|
||||
go.uber.org/atomic v1.9.0 h1:ECmE8Bn/WFTYwEW/bpKD3M8VtR/zQVbavAoalC1PYyE=
|
||||
go.uber.org/atomic v1.9.0/go.mod h1:fEN4uk6kAWBTFdckzkM89CLk9XfWZrxpCo0nPH17wJc=
|
||||
go.uber.org/atomic v1.11.0 h1:ZvwS0R+56ePWxUNi+Atn9dWONBPp/AUETXlHW0DxSjE=
|
||||
go.uber.org/atomic v1.11.0/go.mod h1:LUxbIzbOniOlMKjJjyPfpl4v+PKK2cNJn91OQbhoJI0=
|
||||
go.uber.org/goleak v1.1.11 h1:wy28qYRKZgnJTxGxvye5/wgWr1EKjmUDGYox5mGlRlI=
|
||||
go.uber.org/goleak v1.1.11/go.mod h1:cwTWslyiVhfpKIDGSZEM2HlOvcqm+tG4zioyIeLoqMQ=
|
||||
go.uber.org/multierr v1.6.0/go.mod h1:cdWPpRnG4AhwMwsgIHip0KRBQjJy5kYEpYjJxpXp9iU=
|
||||
go.uber.org/multierr v1.9.0 h1:7fIwc/ZtS0q++VgcfqFDxSBZVv/Xo49/SYnDFupUwlI=
|
||||
go.uber.org/multierr v1.9.0/go.mod h1:X2jQV1h+kxSjClGpnseKVIxpmcjrj7MNnI0bnlfKTVQ=
|
||||
go.uber.org/multierr v1.11.0 h1:blXXJkSxSSfBVBlC76pxqeO+LN3aDfLQo+309xJstO0=
|
||||
go.uber.org/multierr v1.11.0/go.mod h1:20+QtiLqy0Nd6FdQB9TLXag12DsQkrbs3htMFfDN80Y=
|
||||
go.uber.org/zap v1.21.0 h1:WefMeulhovoZ2sYXz7st6K0sLj7bBhpiFaud4r4zST8=
|
||||
go.uber.org/zap v1.21.0/go.mod h1:wjWOCqI0f2ZZrJF/UufIOkiC8ii6tm1iqIsLo76RfJw=
|
||||
go.yaml.in/yaml/v3 v3.0.4 h1:tfq32ie2Jv2UxXFdLJdh3jXuOzWiL1fo0bu/FbuKpbc=
|
||||
go.yaml.in/yaml/v3 v3.0.4/go.mod h1:DhzuOOF2ATzADvBadXxruRBLzYTpT36CKvDb3+aBEFg=
|
||||
golang.org/x/crypto v0.0.0-20190308221718-c2843e01d9a2/go.mod h1:djNgcEr1/C05ACkg1iLfiJU5Ep61QUkGW8qpdssI0+w=
|
||||
golang.org/x/crypto v0.0.0-20190426145343-a29dc8fdc734/go.mod h1:yigFU9vqHzYiE8UmvKecakEJjdnWj3jj499lnFckfCI=
|
||||
golang.org/x/crypto v0.0.0-20191011191535-87dc89f01550/go.mod h1:yigFU9vqHzYiE8UmvKecakEJjdnWj3jj499lnFckfCI=
|
||||
golang.org/x/crypto v0.0.0-20200323165209-0ec3e9974c59/go.mod h1:LzIPMQfyMNhhGPhUkYOs5KpL4U8rLKemX1yGLhDgUto=
|
||||
golang.org/x/crypto v0.0.0-20200622213623-75b288015ac9/go.mod h1:LzIPMQfyMNhhGPhUkYOs5KpL4U8rLKemX1yGLhDgUto=
|
||||
golang.org/x/crypto v0.0.0-20210921155107-089bfa567519/go.mod h1:GvvjBRRGRdwPK5ydBHafDWAxML/pGHZbMvKqRZ5+Abc=
|
||||
golang.org/x/crypto v0.0.0-20211215153901-e495a2d5b3d3/go.mod h1:IxCIyHEi3zRg3s0A5j5BB6A9Jmi73HwBIUl50j+osU4=
|
||||
golang.org/x/crypto v0.8.0/go.mod h1:mRqEX+O9/h5TFCrQhkgjo2yKi0yYA+9ecGkdQoHrywE=
|
||||
golang.org/x/crypto v0.13.0/go.mod h1:y6Z2r+Rw4iayiXXAIxJIDAJ1zMW4yaTpebo8fPOliYc=
|
||||
golang.org/x/crypto v0.19.0/go.mod h1:Iy9bg/ha4yyC70EfRS8jz+B6ybOBKMaSxLj6P6oBDfU=
|
||||
golang.org/x/crypto v0.23.0/go.mod h1:CKFgDieR+mRhux2Lsu27y0fO304Db0wZe70UKqHu0v8=
|
||||
golang.org/x/crypto v0.28.0 h1:GBDwsMXVQi34v5CCYUm2jkJvu4cbtru2U4TN2PSyQnw=
|
||||
golang.org/x/crypto v0.28.0/go.mod h1:rmgy+3RHxRZMyY0jjAJShp2zgEdOqj2AO7U0pYmeQ7U=
|
||||
golang.org/x/exp v0.0.0-20240222234643-814bf88cf225 h1:LfspQV/FYTatPTr/3HzIcmiUFH7PGP+OQ6mgDYo3yuQ=
|
||||
golang.org/x/exp v0.0.0-20240222234643-814bf88cf225/go.mod h1:CxmFvTBINI24O/j8iY7H1xHzx2i4OsyguNBmN/uPtqc=
|
||||
golang.org/x/image v0.5.0 h1:5JMiNunQeQw++mMOz48/ISeNu3Iweh/JaZU8ZLqHRrI=
|
||||
golang.org/x/image v0.5.0/go.mod h1:FVC7BI/5Ym8R25iw5OLsgshdUBbT1h5jZTpA+mvAdZ4=
|
||||
golang.org/x/crypto v0.0.0-20220622213112-05595931fe9d/go.mod h1:IxCIyHEi3zRg3s0A5j5BB6A9Jmi73HwBIUl50j+osU4=
|
||||
golang.org/x/crypto v0.43.0 h1:dduJYIi3A3KOfdGOHX8AVZ/jGiyPa3IbBozJ5kNuE04=
|
||||
golang.org/x/crypto v0.43.0/go.mod h1:BFbav4mRNlXJL4wNeejLpWxB7wMbc79PdRGhWKncxR0=
|
||||
golang.org/x/image v0.25.0 h1:Y6uW6rH1y5y/LK1J8BPWZtr6yZ7hrsy6hFrXjgsc2fQ=
|
||||
golang.org/x/image v0.25.0/go.mod h1:tCAmOEGthTtkalusGp1g3xa2gke8J6c2N565dTyl9Rs=
|
||||
golang.org/x/lint v0.0.0-20190930215403-16217165b5de/go.mod h1:6SW0HCj/g11FgYtHlgUYUwCkIfeOF89ocIRzGO/8vkc=
|
||||
golang.org/x/mod v0.2.0/go.mod h1:s0Qsj1ACt9ePp/hMypM3fl4fZqREWJwdYDEqhRiZZUA=
|
||||
golang.org/x/mod v0.3.0/go.mod h1:s0Qsj1ACt9ePp/hMypM3fl4fZqREWJwdYDEqhRiZZUA=
|
||||
golang.org/x/mod v0.4.2/go.mod h1:s0Qsj1ACt9ePp/hMypM3fl4fZqREWJwdYDEqhRiZZUA=
|
||||
golang.org/x/mod v0.6.0-dev.0.20220419223038-86c51ed26bb4/go.mod h1:jJ57K6gSWd91VN4djpZkiMVwK6gcyfeH4XE8wZrZaV4=
|
||||
golang.org/x/mod v0.8.0/go.mod h1:iBbtSCu2XBx23ZKBPSOrRkjjQPZFPuis4dIYUhu/chs=
|
||||
golang.org/x/mod v0.12.0/go.mod h1:iBbtSCu2XBx23ZKBPSOrRkjjQPZFPuis4dIYUhu/chs=
|
||||
golang.org/x/mod v0.15.0/go.mod h1:hTbmBsO62+eylJbnUtE2MGJUyE7QWk4xUqPFrRgJ+7c=
|
||||
golang.org/x/mod v0.17.0/go.mod h1:hTbmBsO62+eylJbnUtE2MGJUyE7QWk4xUqPFrRgJ+7c=
|
||||
golang.org/x/net v0.0.0-20180811021610-c39426892332/go.mod h1:mL1N/T3taQHkDXs73rZJwtUhF3w3ftmwwsq0BUmARs4=
|
||||
golang.org/x/mod v0.28.0 h1:gQBtGhjxykdjY9YhZpSlZIsbnaE2+PgjfLWUQTnoZ1U=
|
||||
golang.org/x/mod v0.28.0/go.mod h1:yfB/L0NOf/kmEbXjzCPOx1iK1fRutOydrCMsqRhEBxI=
|
||||
golang.org/x/net v0.0.0-20190311183353-d8887717615a/go.mod h1:t9HGtf8HONx5eT2rtn7q6eTqICYqUVnKs3thJo3Qplg=
|
||||
golang.org/x/net v0.0.0-20190404232315-eb5bcb51f2a3/go.mod h1:t9HGtf8HONx5eT2rtn7q6eTqICYqUVnKs3thJo3Qplg=
|
||||
golang.org/x/net v0.0.0-20190603091049-60506f45cf65/go.mod h1:HSz+uSET+XFnRR8LxR5pz3Of3rY3CfYBVs4xY44aLks=
|
||||
golang.org/x/net v0.0.0-20190620200207-3b0461eec859/go.mod h1:z5CRVTTTmAJ677TzLLGU+0bjPO0LkuOLi4/5GtJWs/s=
|
||||
golang.org/x/net v0.0.0-20200226121028-0de0cce0169b/go.mod h1:z5CRVTTTmAJ677TzLLGU+0bjPO0LkuOLi4/5GtJWs/s=
|
||||
golang.org/x/net v0.0.0-20200301022130-244492dfa37a/go.mod h1:z5CRVTTTmAJ677TzLLGU+0bjPO0LkuOLi4/5GtJWs/s=
|
||||
golang.org/x/net v0.0.0-20201021035429-f5854403a974/go.mod h1:sp8m0HH+o8qH0wwXwYZr8TS3Oi6o0r6Gce1SSxlDquU=
|
||||
golang.org/x/net v0.0.0-20210226172049-e18ecbb05110/go.mod h1:m0MpNAwzfU5UDzcl9v0D8zg8gWTRqZa9RBIspLL5mdg=
|
||||
golang.org/x/net v0.0.0-20210405180319-a5a99cb37ef4/go.mod h1:p54w0d4576C0XHj96bSt6lcn1PtDYWL6XObtHCRCNQM=
|
||||
golang.org/x/net v0.0.0-20211112202133-69e39bad7dc2/go.mod h1:9nx3DQGgdP8bBQD5qxJ1jj9UTztislL4KSBs9R2vV5Y=
|
||||
golang.org/x/net v0.0.0-20220722155237-a158d28d115b/go.mod h1:XRhObCWvk6IyKnWLug+ECip1KBveYUHfp+8e9klMJ9c=
|
||||
golang.org/x/net v0.6.0/go.mod h1:2Tu9+aMcznHK/AK1HMvgo6xiTLG5rD5rZLDS+rp2Bjs=
|
||||
golang.org/x/net v0.9.0/go.mod h1:d48xBJpPfHeWQsugry2m+kC02ZBRGRgulfHnEXEuWns=
|
||||
golang.org/x/net v0.10.0/go.mod h1:0qNGK6F8kojg2nk9dLZ2mShWaEBan6FAoqfSigmmuDg=
|
||||
golang.org/x/net v0.15.0/go.mod h1:idbUs1IY1+zTqbi8yxTbhexhEEk5ur9LInksu6HrEpk=
|
||||
golang.org/x/net v0.21.0/go.mod h1:bIjVDfnllIU7BJ2DNgfnXvpSvtn8VRwhlsaeUTyUS44=
|
||||
golang.org/x/net v0.25.0/go.mod h1:JkAGAh7GEvH74S6FOH42FLoXpXbE/aqXSrIQjXgsiwM=
|
||||
golang.org/x/net v0.29.0 h1:5ORfpBpCs4HzDYoodCDBbwHzdR5UrLBZ3sOnUJmFoHo=
|
||||
golang.org/x/net v0.29.0/go.mod h1:gLkgy8jTGERgjzMic6DS9+SP0ajcu6Xu3Orq/SpETg0=
|
||||
golang.org/x/oauth2 v0.23.0 h1:PbgcYx2W7i4LvjJWEbf0ngHV6qJYr86PkAV3bXdLEbs=
|
||||
golang.org/x/oauth2 v0.23.0/go.mod h1:XYTD2NtWslqkgxebSiOHnXEap4TF09sJSc7H1sXbhtI=
|
||||
golang.org/x/sync v0.0.0-20180314180146-1d60e4601c6f/go.mod h1:RxMgew5VJxzue5/jJTE5uejpjVlOe/izrB70Jof72aM=
|
||||
golang.org/x/net v0.46.0 h1:giFlY12I07fugqwPuWJi68oOnpfqFnJIJzaIIm2JVV4=
|
||||
golang.org/x/net v0.46.0/go.mod h1:Q9BGdFy1y4nkUwiLvT5qtyhAnEHgnQ/zd8PfU6nc210=
|
||||
golang.org/x/oauth2 v0.30.0 h1:dnDm7JmhM45NNpd8FDDeLhK6FwqbOf4MLCM9zb1BOHI=
|
||||
golang.org/x/oauth2 v0.30.0/go.mod h1:B++QgG3ZKulg6sRPGD/mqlHQs5rB3Ml9erfeDY7xKlU=
|
||||
golang.org/x/sync v0.0.0-20190423024810-112230192c58/go.mod h1:RxMgew5VJxzue5/jJTE5uejpjVlOe/izrB70Jof72aM=
|
||||
golang.org/x/sync v0.0.0-20190911185100-cd5d95a43a6e/go.mod h1:RxMgew5VJxzue5/jJTE5uejpjVlOe/izrB70Jof72aM=
|
||||
golang.org/x/sync v0.0.0-20201020160332-67f06af15bc9/go.mod h1:RxMgew5VJxzue5/jJTE5uejpjVlOe/izrB70Jof72aM=
|
||||
golang.org/x/sync v0.0.0-20210220032951-036812b2e83c/go.mod h1:RxMgew5VJxzue5/jJTE5uejpjVlOe/izrB70Jof72aM=
|
||||
golang.org/x/sync v0.0.0-20220722155255-886fb9371eb4/go.mod h1:RxMgew5VJxzue5/jJTE5uejpjVlOe/izrB70Jof72aM=
|
||||
golang.org/x/sync v0.1.0/go.mod h1:RxMgew5VJxzue5/jJTE5uejpjVlOe/izrB70Jof72aM=
|
||||
golang.org/x/sync v0.3.0/go.mod h1:FU7BRWz2tNW+3quACPkgCx/L+uEAv1htQ0V83Z9Rj+Y=
|
||||
golang.org/x/sync v0.6.0/go.mod h1:Czt+wKu1gCyEFDUtn0jG5QVvpJ6rzVqr5aXyt9drQfk=
|
||||
golang.org/x/sync v0.7.0/go.mod h1:Czt+wKu1gCyEFDUtn0jG5QVvpJ6rzVqr5aXyt9drQfk=
|
||||
golang.org/x/sync v0.8.0 h1:3NFvSEYkUoMifnESzZl15y791HH1qU2xm6eCJU5ZPXQ=
|
||||
golang.org/x/sync v0.8.0/go.mod h1:Czt+wKu1gCyEFDUtn0jG5QVvpJ6rzVqr5aXyt9drQfk=
|
||||
golang.org/x/sync v0.17.0 h1:l60nONMj9l5drqw6jlhIELNv9I0A4OFgRsG9k2oT9Ug=
|
||||
golang.org/x/sync v0.17.0/go.mod h1:9KTHXmSnoGruLpwFjVSX0lNNA75CykiMECbovNTZqGI=
|
||||
golang.org/x/sys v0.0.0-20180905080454-ebe1bf3edb33/go.mod h1:STP8DvDyc/dI5b8T5hshtkjS+E42TnysNCUPdjciGhY=
|
||||
golang.org/x/sys v0.0.0-20190215142949-d0b11bdaac8a/go.mod h1:STP8DvDyc/dI5b8T5hshtkjS+E42TnysNCUPdjciGhY=
|
||||
golang.org/x/sys v0.0.0-20190222072716-a9d3bda3a223/go.mod h1:STP8DvDyc/dI5b8T5hshtkjS+E42TnysNCUPdjciGhY=
|
||||
golang.org/x/sys v0.0.0-20190412213103-97732733099d/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs=
|
||||
golang.org/x/sys v0.0.0-20190502175342-a43fa875dd82/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs=
|
||||
golang.org/x/sys v0.0.0-20190507160741-ecd444e8653b/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs=
|
||||
golang.org/x/sys v0.0.0-20191026070338-33540a1f6037/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs=
|
||||
golang.org/x/sys v0.0.0-20200930185726-fdedc70b468f/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs=
|
||||
@@ -369,46 +433,25 @@ golang.org/x/sys v0.0.0-20210330210617-4fbd30eecc44/go.mod h1:h1NjWce9XRLGQEsW7w
|
||||
golang.org/x/sys v0.0.0-20210423082822-04245dca01da/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs=
|
||||
golang.org/x/sys v0.0.0-20210510120138-977fb7262007/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg=
|
||||
golang.org/x/sys v0.0.0-20210615035016-665e8c7367d1/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg=
|
||||
golang.org/x/sys v0.0.0-20210806184541-e5e7981a1069/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg=
|
||||
golang.org/x/sys v0.0.0-20220520151302-bc2c85ada10a/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg=
|
||||
golang.org/x/sys v0.0.0-20220704084225-05e143d24a9e/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg=
|
||||
golang.org/x/sys v0.0.0-20220715151400-c0bba94af5f8/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg=
|
||||
golang.org/x/sys v0.0.0-20220722155257-8c9f86f7a55f/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg=
|
||||
golang.org/x/sys v0.0.0-20220811171246-fbc7d0a398ab/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg=
|
||||
golang.org/x/sys v0.5.0/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg=
|
||||
golang.org/x/sys v0.6.0/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg=
|
||||
golang.org/x/sys v0.7.0/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg=
|
||||
golang.org/x/sys v0.8.0/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg=
|
||||
golang.org/x/sys v0.12.0/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg=
|
||||
golang.org/x/sys v0.17.0/go.mod h1:/VUhepiaJMQUp4+oa/7Zr1D23ma6VTLIYjOOTFZPUcA=
|
||||
golang.org/x/sys v0.20.0/go.mod h1:/VUhepiaJMQUp4+oa/7Zr1D23ma6VTLIYjOOTFZPUcA=
|
||||
golang.org/x/sys v0.26.0/go.mod h1:/VUhepiaJMQUp4+oa/7Zr1D23ma6VTLIYjOOTFZPUcA=
|
||||
golang.org/x/sys v0.27.0 h1:wBqf8DvsY9Y/2P8gAfPDEYNuS30J4lPHJxXSb/nJZ+s=
|
||||
golang.org/x/sys v0.27.0/go.mod h1:/VUhepiaJMQUp4+oa/7Zr1D23ma6VTLIYjOOTFZPUcA=
|
||||
golang.org/x/telemetry v0.0.0-20240228155512-f48c80bd79b2/go.mod h1:TeRTkGYfJXctD9OcfyVLyj2J3IxLnKwHJR8f4D8a3YE=
|
||||
golang.org/x/sys v0.37.0 h1:fdNQudmxPjkdUTPnLn5mdQv7Zwvbvpaxqs831goi9kQ=
|
||||
golang.org/x/sys v0.37.0/go.mod h1:OgkHotnGiDImocRcuBABYBEXf8A9a87e/uXjp9XT3ks=
|
||||
golang.org/x/term v0.0.0-20201126162022-7de9c90e9dd1/go.mod h1:bj7SfCRtBDWHUb9snDiAeCFNEtKQo2Wmx5Cou7ajbmo=
|
||||
golang.org/x/term v0.0.0-20210927222741-03fcf44c2211/go.mod h1:jbD1KX2456YbFQfuXm/mYQcufACuNUgVhRMnK/tPxf8=
|
||||
golang.org/x/term v0.5.0/go.mod h1:jMB1sMXY+tzblOD4FWmEbocvup2/aLOaQEp7JmGp78k=
|
||||
golang.org/x/term v0.7.0/go.mod h1:P32HKFT3hSsZrRxla30E9HqToFYAQPCMs/zFMBUFqPY=
|
||||
golang.org/x/term v0.8.0/go.mod h1:xPskH00ivmX89bAKVGSKKtLOWNx2+17Eiy94tnKShWo=
|
||||
golang.org/x/term v0.12.0/go.mod h1:owVbMEjm3cBLCHdkQu9b1opXd4ETQWc3BhuQGKgXgvU=
|
||||
golang.org/x/term v0.17.0/go.mod h1:lLRBjIVuehSbZlaOtGMbcMncT+aqLLLmKrsjNrUguwk=
|
||||
golang.org/x/term v0.20.0/go.mod h1:8UkIAJTvZgivsXaD6/pH6U9ecQzZ45awqEOzuCvwpFY=
|
||||
golang.org/x/term v0.25.0/go.mod h1:RPyXicDX+6vLxogjjRxjgD2TKtmAO6NZBsBRfrOLu7M=
|
||||
golang.org/x/text v0.3.0/go.mod h1:NqM8EUOU14njkJ3fqMW+pc6Ldnwhi/IjpwHt7yyuwOQ=
|
||||
golang.org/x/text v0.3.2/go.mod h1:bEr9sfX3Q8Zfm5fL9x+3itogRgK3+ptLWKqgva+5dAk=
|
||||
golang.org/x/text v0.3.3/go.mod h1:5Zoc/QRtKVWzQhOtBMvqHzDpF6irO9z98xDceosuGiQ=
|
||||
golang.org/x/text v0.3.5/go.mod h1:5Zoc/QRtKVWzQhOtBMvqHzDpF6irO9z98xDceosuGiQ=
|
||||
golang.org/x/text v0.3.6/go.mod h1:5Zoc/QRtKVWzQhOtBMvqHzDpF6irO9z98xDceosuGiQ=
|
||||
golang.org/x/text v0.3.7/go.mod h1:u+2+/6zg+i71rQMx5EYifcz6MCKuco9NR6JIITiCfzQ=
|
||||
golang.org/x/text v0.3.8/go.mod h1:E6s5w1FMmriuDzIBO73fBruAKo1PCIq6d2Q6DHfQ8WQ=
|
||||
golang.org/x/text v0.7.0/go.mod h1:mrYo+phRRbMaCq/xk9113O4dZlRixOauAjOtrjsXDZ8=
|
||||
golang.org/x/text v0.9.0/go.mod h1:e1OnstbJyHTd6l/uOt8jFFHp6TRDWZR/bV3emEE/zU8=
|
||||
golang.org/x/text v0.13.0/go.mod h1:TvPlkZtksWOMsz7fbANvkp4WM8x/WCo/om8BMLbz+aE=
|
||||
golang.org/x/text v0.14.0/go.mod h1:18ZOQIKpY8NJVqYksKHtTdi31H5itFRjB5/qKTNYzSU=
|
||||
golang.org/x/text v0.15.0/go.mod h1:18ZOQIKpY8NJVqYksKHtTdi31H5itFRjB5/qKTNYzSU=
|
||||
golang.org/x/text v0.19.0 h1:kTxAhCbGbxhK0IwgSKiMO5awPoDQ0RpfiVYBfK860YM=
|
||||
golang.org/x/text v0.19.0/go.mod h1:BuEKDfySbSR4drPmRPG/7iBdf8hvFMuRexcpahXilzY=
|
||||
golang.org/x/text v0.30.0 h1:yznKA/E9zq54KzlzBEAWn1NXSQ8DIp/NYMy88xJjl4k=
|
||||
golang.org/x/text v0.30.0/go.mod h1:yDdHFIX9t+tORqspjENWgzaCVXgk0yYnYuSZ8UzzBVM=
|
||||
golang.org/x/tools v0.0.0-20180917221912-90fa682c2a6e/go.mod h1:n7NCudcB/nEzxVGmLbDWY5pfWTLqBcC2KZ6jyYvM4mQ=
|
||||
golang.org/x/tools v0.0.0-20190311212946-11955173bddd/go.mod h1:LCzVGOaR6xXOjkQ3onu1FJEFr0SW1gC7cKk1uF8kGRs=
|
||||
golang.org/x/tools v0.0.0-20191119224855-298f0cb1881e/go.mod h1:b+2E5dAYhXwXZwtnZ6UAqBI28+e2cm9otk0dWdXHAEo=
|
||||
@@ -416,36 +459,33 @@ golang.org/x/tools v0.0.0-20200619180055-7c47624df98f/go.mod h1:EkVYQZoAsY45+roY
|
||||
golang.org/x/tools v0.0.0-20210106214847-113979e3529a/go.mod h1:emZCQorbCU4vsT4fOWvOPXz4eW1wZW4PmDk9uLelYpA=
|
||||
golang.org/x/tools v0.1.5/go.mod h1:o0xws9oXOQQZyjljx8fwUC0k7L1pTE6eaCbjGeHmOkk=
|
||||
golang.org/x/tools v0.1.12/go.mod h1:hNGJHUnrk76NpqgfD5Aqm5Crs+Hm0VOH/i9J2+nxYbc=
|
||||
golang.org/x/tools v0.6.0/go.mod h1:Xwgl3UAJ/d3gWutnCtw505GrjyAbvKui8lOU390QaIU=
|
||||
golang.org/x/tools v0.13.0/go.mod h1:HvlwmtVNQAhOuCjW7xxvovg8wbNq7LwfXh/k7wXUl58=
|
||||
golang.org/x/tools v0.21.1-0.20240508182429-e35e4ccd0d2d/go.mod h1:aiJjzUbINMkxbQROHiO6hDPo2LHcIPhhQsa9DLh0yGk=
|
||||
golang.org/x/tools v0.37.0 h1:DVSRzp7FwePZW356yEAChSdNcQo6Nsp+fex1SUW09lE=
|
||||
golang.org/x/tools v0.37.0/go.mod h1:MBN5QPQtLMHVdvsbtarmTNukZDdgwdwlO5qGacAzF0w=
|
||||
golang.org/x/xerrors v0.0.0-20190717185122-a985d3407aa7/go.mod h1:I/5z698sn9Ka8TeJc9MKroUUfqBBauWjQqLJ2OPfmY0=
|
||||
golang.org/x/xerrors v0.0.0-20191011141410-1b5146add898/go.mod h1:I/5z698sn9Ka8TeJc9MKroUUfqBBauWjQqLJ2OPfmY0=
|
||||
golang.org/x/xerrors v0.0.0-20191204190536-9bdfabe68543/go.mod h1:I/5z698sn9Ka8TeJc9MKroUUfqBBauWjQqLJ2OPfmY0=
|
||||
golang.org/x/xerrors v0.0.0-20200804184101-5ec99f83aff1/go.mod h1:I/5z698sn9Ka8TeJc9MKroUUfqBBauWjQqLJ2OPfmY0=
|
||||
google.golang.org/appengine v1.1.0/go.mod h1:EbEs0AVv82hx2wNQdGPgUI5lhzA/G0D9YwlJXL52JkM=
|
||||
google.golang.org/appengine v1.6.5/go.mod h1:8WjMMxjGQR8xUklV/ARdw2HLXBOI7O7uCIDZVag1xfc=
|
||||
google.golang.org/genproto/googleapis/api v0.0.0-20240903143218-8af14fe29dc1 h1:hjSy6tcFQZ171igDaN5QHOw2n6vx40juYbC/x67CEhc=
|
||||
google.golang.org/genproto/googleapis/api v0.0.0-20240903143218-8af14fe29dc1/go.mod h1:qpvKtACPCQhAdu3PyQgV4l3LMXZEtft7y8QcarRsp9I=
|
||||
google.golang.org/genproto/googleapis/rpc v0.0.0-20240903143218-8af14fe29dc1 h1:pPJltXNxVzT4pK9yD8vR9X75DaWYYmLGMsEvBfFQZzQ=
|
||||
google.golang.org/genproto/googleapis/rpc v0.0.0-20240903143218-8af14fe29dc1/go.mod h1:UqMtugtsSgubUsoxbuAoiCXvqvErP7Gf0so0mK9tHxU=
|
||||
google.golang.org/grpc v1.68.0 h1:aHQeeJbo8zAkAa3pRzrVjZlbz6uSfeOXlJNQM0RAbz0=
|
||||
google.golang.org/grpc v1.68.0/go.mod h1:fmSPC5AsjSBCK54MyHRx48kpOti1/jRfOlwEWywNjWA=
|
||||
google.golang.org/protobuf v1.35.2 h1:8Ar7bF+apOIoThw1EdZl0p1oWvMqTHmpA2fRTyZO8io=
|
||||
google.golang.org/protobuf v1.35.2/go.mod h1:9fA7Ob0pmnwhb644+1+CVWFRbNajQ6iRojtC/QF5bRE=
|
||||
gonum.org/v1/gonum v0.16.0 h1:5+ul4Swaf3ESvrOnidPp4GZbzf0mxVQpDCYUQE7OJfk=
|
||||
gonum.org/v1/gonum v0.16.0/go.mod h1:fef3am4MQ93R2HHpKnLk4/Tbh/s0+wqD5nfa6Pnwy4E=
|
||||
google.golang.org/genproto/googleapis/api v0.0.0-20250804133106-a7a43d27e69b h1:ULiyYQ0FdsJhwwZUwbaXpZF5yUE3h+RA+gxvBu37ucc=
|
||||
google.golang.org/genproto/googleapis/api v0.0.0-20250804133106-a7a43d27e69b/go.mod h1:oDOGiMSXHL4sDTJvFvIB9nRQCGdLP1o/iVaqQK8zB+M=
|
||||
google.golang.org/genproto/googleapis/rpc v0.0.0-20251007200510-49b9836ed3ff h1:A90eA31Wq6HOMIQlLfzFwzqGKBTuaVztYu/g8sn+8Zc=
|
||||
google.golang.org/genproto/googleapis/rpc v0.0.0-20251007200510-49b9836ed3ff/go.mod h1:7i2o+ce6H/6BluujYR+kqX3GKH+dChPTQU19wjRPiGk=
|
||||
google.golang.org/grpc v1.76.0 h1:UnVkv1+uMLYXoIz6o7chp59WfQUYA2ex/BXQ9rHZu7A=
|
||||
google.golang.org/grpc v1.76.0/go.mod h1:Ju12QI8M6iQJtbcsV+awF5a4hfJMLi4X0JLo94ULZ6c=
|
||||
google.golang.org/protobuf v1.26.0-rc.1/go.mod h1:jlhhOSvTdKEhbULTjvd4ARK9grFBp09yW+WbY/TyQbw=
|
||||
google.golang.org/protobuf v1.27.1/go.mod h1:9q0QmTI4eRPtz6boOQmLYwt+qCgq0jsYwAQnmE0givc=
|
||||
google.golang.org/protobuf v1.36.10 h1:AYd7cD/uASjIL6Q9LiTjz8JLcrh/88q5UObnmY3aOOE=
|
||||
google.golang.org/protobuf v1.36.10/go.mod h1:HTf+CrKn2C3g5S8VImy6tdcUvCska2kB7j23XfzDpco=
|
||||
gopkg.in/check.v1 v0.0.0-20161208181325-20d25e280405/go.mod h1:Co6ibVJAznAaIkqp8huTwlJQCZ016jof/cbN4VW5Yz0=
|
||||
gopkg.in/check.v1 v1.0.0-20180628173108-788fd7840127/go.mod h1:Co6ibVJAznAaIkqp8huTwlJQCZ016jof/cbN4VW5Yz0=
|
||||
gopkg.in/check.v1 v1.0.0-20190902080502-41f04d3bba15/go.mod h1:Co6ibVJAznAaIkqp8huTwlJQCZ016jof/cbN4VW5Yz0=
|
||||
gopkg.in/check.v1 v1.0.0-20200227125254-8fa46927fb4f h1:BLraFXnmrev5lT+xlilqcH8XK9/i0At2xKjWk4p6zsU=
|
||||
gopkg.in/check.v1 v1.0.0-20200227125254-8fa46927fb4f/go.mod h1:Co6ibVJAznAaIkqp8huTwlJQCZ016jof/cbN4VW5Yz0=
|
||||
gopkg.in/check.v1 v1.0.0-20201130134442-10cb98267c6c h1:Hei/4ADfdWqJk1ZMxUNpqntNwaWcugrBjAiHlqqRiVk=
|
||||
gopkg.in/check.v1 v1.0.0-20201130134442-10cb98267c6c/go.mod h1:JHkPIbrfpd72SG/EVd6muEfDQjcINNoR0C8j2r3qZ4Q=
|
||||
gopkg.in/errgo.v2 v2.1.0/go.mod h1:hNsd1EY+bozCKY1Ytp96fpM3vjJbqLJn88ws8XvfDNI=
|
||||
gopkg.in/ini.v1 v1.67.0 h1:Dgnx+6+nfE+IfzjUEISNeydPJh9AXNNsWbGP9KzCsOA=
|
||||
gopkg.in/ini.v1 v1.67.0/go.mod h1:pNLf8WUiyNEtQjuu5G5vTm06TEv9tsIgeAvK8hOrP4k=
|
||||
gopkg.in/mgo.v2 v2.0.0-20190816093944-a6b53ec6cb22 h1:VpOs+IwYnYBaFnrNAeB8UUWtL3vEUnzSCL1nVjPhqrw=
|
||||
gopkg.in/mgo.v2 v2.0.0-20190816093944-a6b53ec6cb22/go.mod h1:yeKp02qBN3iKW1OzL3MGk2IdtZzaj7SFntXj72NppTA=
|
||||
gopkg.in/yaml.v2 v2.2.2/go.mod h1:hI93XBmqTisBFMUTm0b8Fm+jr3Dg1NNxqwp+5A1VGuI=
|
||||
gopkg.in/yaml.v2 v2.2.4/go.mod h1:hI93XBmqTisBFMUTm0b8Fm+jr3Dg1NNxqwp+5A1VGuI=
|
||||
gopkg.in/yaml.v2 v2.2.8/go.mod h1:hI93XBmqTisBFMUTm0b8Fm+jr3Dg1NNxqwp+5A1VGuI=
|
||||
gopkg.in/yaml.v2 v2.4.0 h1:D8xgwECY7CYvx+Y2n4sBz93Jn9JRvxdiyyo8CTfuKaY=
|
||||
gopkg.in/yaml.v2 v2.4.0/go.mod h1:RDklbk79AGWmwhnvt/jBztapEOGDOx6ZbXqjP6csGnQ=
|
||||
|
||||
@@ -1,30 +0,0 @@
|
||||
package api
|
||||
|
||||
import (
|
||||
"net/http"
|
||||
|
||||
"git.coopgo.io/coopgo-apps/parcoursmob/services"
|
||||
"git.coopgo.io/coopgo-apps/parcoursmob/utils/identification"
|
||||
cache "git.coopgo.io/coopgo-apps/parcoursmob/utils/storage"
|
||||
"github.com/spf13/viper"
|
||||
)
|
||||
|
||||
type APIHandler struct {
|
||||
idp *identification.IdentificationProvider
|
||||
config *viper.Viper
|
||||
services *services.ServicesHandler
|
||||
cache cache.CacheHandler
|
||||
}
|
||||
|
||||
func NewAPIHandler(cfg *viper.Viper, idp *identification.IdentificationProvider, svc *services.ServicesHandler, cache cache.CacheHandler) (*APIHandler, error) {
|
||||
return &APIHandler{
|
||||
idp: idp,
|
||||
config: cfg,
|
||||
services: svc,
|
||||
cache: cache,
|
||||
}, nil
|
||||
}
|
||||
|
||||
func (h *APIHandler) NotFound(w http.ResponseWriter, r *http.Request) {
|
||||
w.WriteHeader(http.StatusNotFound)
|
||||
}
|
||||
@@ -1,70 +0,0 @@
|
||||
package api
|
||||
|
||||
import (
|
||||
"encoding/json"
|
||||
"net/http"
|
||||
"strconv"
|
||||
|
||||
"github.com/rs/zerolog/log"
|
||||
|
||||
"github.com/gorilla/mux"
|
||||
)
|
||||
|
||||
func (h APIHandler) GetCache(w http.ResponseWriter, r *http.Request) {
|
||||
vars := mux.Vars(r)
|
||||
cacheid := vars["cacheid"]
|
||||
// Use a channel to synchronize the goroutines
|
||||
ch := make(chan []byte)
|
||||
// Fetch data from cache asynchronously
|
||||
go func() {
|
||||
d, err := h.cache.Get(cacheid)
|
||||
if err != nil {
|
||||
log.Error().Err(err).Msg("")
|
||||
w.WriteHeader(http.StatusNotFound)
|
||||
ch <- nil
|
||||
return
|
||||
}
|
||||
var data []any
|
||||
if val, ok := d.([]any); ok {
|
||||
data = val
|
||||
} else {
|
||||
data = []any{d}
|
||||
}
|
||||
j := toJSON(data, w, r)
|
||||
ch <- j // Signal that the data has been fetched successfully
|
||||
close(ch)
|
||||
}()
|
||||
// wait for the JSON marshaling goroutine to finish
|
||||
j := <-ch
|
||||
if j == nil {
|
||||
return // Stop processing if an error occurred
|
||||
}
|
||||
// Send the JSON response to the client
|
||||
w.WriteHeader(http.StatusOK)
|
||||
w.Header().Set("Content-Type", "application/json")
|
||||
w.Write(j)
|
||||
|
||||
<-ch
|
||||
}
|
||||
func toJSON(data []any, w http.ResponseWriter, r *http.Request) []byte {
|
||||
result := data
|
||||
if limitsmin, ok := r.URL.Query()["limits.min"]; ok {
|
||||
min, _ := strconv.Atoi(limitsmin[0])
|
||||
if limitsmax, ok := r.URL.Query()["limits.max"]; ok {
|
||||
max, _ := strconv.Atoi(limitsmax[0])
|
||||
if max > len(data) {
|
||||
result = data[min:]
|
||||
} else {
|
||||
result = data[min:max]
|
||||
}
|
||||
} else {
|
||||
result = data[min:]
|
||||
}
|
||||
}
|
||||
j, err := json.Marshal(result)
|
||||
if err != nil {
|
||||
w.WriteHeader(http.StatusNotFound)
|
||||
return nil
|
||||
}
|
||||
return j
|
||||
}
|
||||
@@ -1,120 +0,0 @@
|
||||
package api
|
||||
|
||||
import (
|
||||
"net/http"
|
||||
"time"
|
||||
|
||||
"git.coopgo.io/coopgo-apps/parcoursmob/services"
|
||||
ics "github.com/arran4/golang-ical"
|
||||
"github.com/gorilla/mux"
|
||||
"github.com/rs/zerolog/log"
|
||||
)
|
||||
|
||||
func (h *APIHandler) icsCalendar(events []services.AgendaEvent) (*ics.Calendar, error) {
|
||||
calendar := ics.NewCalendarFor(h.config.GetString("service_name"))
|
||||
|
||||
for _, e := range events {
|
||||
vevent := ics.NewEvent(e.ID)
|
||||
vevent.SetSummary(e.Name)
|
||||
vevent.SetDescription(e.Description)
|
||||
if e.Allday {
|
||||
vevent.SetAllDayStartAt(e.Startdate)
|
||||
if e.Enddate.After(e.Startdate) {
|
||||
vevent.SetAllDayEndAt(e.Enddate.Add(24 * time.Hour))
|
||||
}
|
||||
} else {
|
||||
timeloc, err := time.LoadLocation("Europe/Paris")
|
||||
if err != nil {
|
||||
log.Error().Err(err).Msg("Tried to load timezone location Europe/Paris. Error. Missing zones in container ?")
|
||||
return nil, err
|
||||
}
|
||||
|
||||
starttime, err := time.ParseInLocation("15:04", e.Starttime, timeloc)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
startdatetime := time.Date(e.Startdate.Year(), e.Startdate.Month(), e.Startdate.Day(), starttime.Hour(), starttime.Minute(), 0, 0, timeloc)
|
||||
|
||||
endtime, err := time.Parse("15:04", e.Endtime)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
enddatetime := time.Date(e.Enddate.Year(), e.Enddate.Month(), e.Enddate.Day(), endtime.Hour(), endtime.Minute(), 0, 0, timeloc)
|
||||
|
||||
vevent.SetStartAt(startdatetime)
|
||||
vevent.SetEndAt(enddatetime)
|
||||
}
|
||||
calendar.AddVEvent(vevent)
|
||||
}
|
||||
return calendar, nil
|
||||
}
|
||||
|
||||
func (h *APIHandler) CalendarGlobal(w http.ResponseWriter, r *http.Request) {
|
||||
enabled := h.config.GetBool("modules.agenda.enabled") && h.config.GetBool("modules.agenda.calendars.global.enabled")
|
||||
if !enabled {
|
||||
log.Error().Msg("global calendar not activated in configuration")
|
||||
w.WriteHeader(http.StatusForbidden)
|
||||
return
|
||||
}
|
||||
|
||||
events, err := h.services.GetAgendaEvents()
|
||||
if err != nil {
|
||||
log.Error().Err(err).Msg("error retrieving agenda events")
|
||||
w.WriteHeader(http.StatusInternalServerError)
|
||||
return
|
||||
}
|
||||
|
||||
calendar, err := h.icsCalendar(events)
|
||||
if err != nil {
|
||||
log.Error().Err(err).Msg("error while creating ics calendar")
|
||||
w.WriteHeader(http.StatusInternalServerError)
|
||||
return
|
||||
}
|
||||
|
||||
w.WriteHeader(http.StatusOK)
|
||||
w.Header().Set("Content-Type", "text/calendar")
|
||||
w.Write([]byte(calendar.Serialize()))
|
||||
}
|
||||
|
||||
func (h *APIHandler) CalendarOrganizations(w http.ResponseWriter, r *http.Request) {
|
||||
enabled := h.config.GetBool("modules.agenda.enabled") && h.config.GetBool("modules.agenda.calendars.organizations.enabled")
|
||||
if !enabled {
|
||||
log.Error().Msg("organizations calendar not activated in configuration")
|
||||
w.WriteHeader(http.StatusForbidden)
|
||||
return
|
||||
}
|
||||
|
||||
// TODO set additional calendar rights in group configuration to prevent default behavior ?
|
||||
|
||||
vars := mux.Vars(r)
|
||||
groupid := vars["groupid"]
|
||||
|
||||
events, err := h.services.GetAgendaEvents()
|
||||
if err != nil {
|
||||
log.Error().Err(err).Msg("error retrieving agenda events")
|
||||
w.WriteHeader(http.StatusInternalServerError)
|
||||
return
|
||||
}
|
||||
|
||||
filteredEvents := []services.AgendaEvent{}
|
||||
|
||||
for _, e := range events {
|
||||
for _, g := range e.Owners {
|
||||
if g == groupid {
|
||||
filteredEvents = append(filteredEvents, e)
|
||||
continue
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
calendar, err := h.icsCalendar(filteredEvents)
|
||||
if err != nil {
|
||||
log.Error().Err(err).Msg("error while creating ics calendar")
|
||||
w.WriteHeader(http.StatusInternalServerError)
|
||||
return
|
||||
}
|
||||
|
||||
w.WriteHeader(http.StatusOK)
|
||||
w.Header().Set("Content-Type", "text/calendar")
|
||||
w.Write([]byte(calendar.Serialize()))
|
||||
}
|
||||
@@ -1,97 +0,0 @@
|
||||
package api
|
||||
|
||||
import (
|
||||
"encoding/csv"
|
||||
"fmt"
|
||||
"net/http"
|
||||
"sort"
|
||||
"strconv"
|
||||
|
||||
"github.com/gorilla/mux"
|
||||
"github.com/rs/zerolog/log"
|
||||
)
|
||||
|
||||
type FlatMaps []map[string]any
|
||||
|
||||
func (maps FlatMaps) GetHeaders() (res []string) {
|
||||
keys := map[string]bool{}
|
||||
for _, m := range maps {
|
||||
for k, _ := range m {
|
||||
if _, ok := keys[k]; !ok {
|
||||
keys[k] = true
|
||||
res = append(res, k)
|
||||
}
|
||||
}
|
||||
}
|
||||
sort.Strings(res)
|
||||
return
|
||||
}
|
||||
|
||||
func (maps FlatMaps) GetValues() (res [][]string) {
|
||||
headers := maps.GetHeaders()
|
||||
for _, m := range maps {
|
||||
line := []string{}
|
||||
for _, k := range headers {
|
||||
if v, ok := m[k]; ok && v != nil {
|
||||
line = append(line, fmt.Sprint(v))
|
||||
} else {
|
||||
line = append(line, "")
|
||||
}
|
||||
}
|
||||
res = append(res, line)
|
||||
}
|
||||
return
|
||||
}
|
||||
|
||||
func (h APIHandler) CacheExport(w http.ResponseWriter, r *http.Request) {
|
||||
vars := mux.Vars(r)
|
||||
cacheid := vars["cacheid"]
|
||||
|
||||
d, err := h.cache.Get(cacheid)
|
||||
if err != nil {
|
||||
log.Error().Err(err).Msg("Error getting cache")
|
||||
w.WriteHeader(http.StatusNotFound)
|
||||
return
|
||||
}
|
||||
|
||||
if data, ok := d.([]any); ok {
|
||||
|
||||
flatmaps := FlatMaps{}
|
||||
|
||||
for _, v := range data {
|
||||
fm := map[string]any{}
|
||||
flatten("", v.(map[string]any), fm)
|
||||
flatmaps = append(flatmaps, fm)
|
||||
}
|
||||
|
||||
w.Header().Set("Content-Type", "text/csv")
|
||||
w.Header().Set("Content-Disposition", fmt.Sprintf("attachment; filename=export-%s.csv", cacheid))
|
||||
c := csv.NewWriter(w)
|
||||
c.Write(flatmaps.GetHeaders())
|
||||
c.WriteAll(flatmaps.GetValues())
|
||||
return
|
||||
|
||||
}
|
||||
|
||||
w.WriteHeader(http.StatusNotFound)
|
||||
|
||||
}
|
||||
|
||||
func flatten(prefix string, src map[string]any, dest map[string]any) {
|
||||
if len(prefix) > 0 {
|
||||
prefix += "."
|
||||
}
|
||||
for k, v := range src {
|
||||
switch child := v.(type) {
|
||||
case map[string]any:
|
||||
flatten(prefix+k, child, dest)
|
||||
case []any:
|
||||
for i := 0; i < len(child); i++ {
|
||||
dest[prefix+k+"."+strconv.Itoa(i)] = child[i]
|
||||
}
|
||||
default:
|
||||
// log.Trace().Str("key", prefix+k).Any("value", v).Msg("")
|
||||
dest[prefix+k] = v
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -1,52 +0,0 @@
|
||||
package api
|
||||
|
||||
import (
|
||||
"encoding/json"
|
||||
"fmt"
|
||||
"io"
|
||||
"log"
|
||||
"net/http"
|
||||
)
|
||||
|
||||
func (h *APIHandler) GeoAutocomplete(w http.ResponseWriter, r *http.Request) {
|
||||
pelias := h.config.GetString("geo.pelias.url")
|
||||
|
||||
t, ok := r.URL.Query()["text"]
|
||||
|
||||
if !ok || len(t[0]) < 1 {
|
||||
w.WriteHeader(http.StatusBadRequest)
|
||||
return
|
||||
}
|
||||
|
||||
text := t[0]
|
||||
|
||||
resp, err := http.Get(fmt.Sprintf("%s/autocomplete?text=%s", pelias, text))
|
||||
if err != nil {
|
||||
w.WriteHeader(http.StatusInternalServerError)
|
||||
return
|
||||
}
|
||||
|
||||
defer resp.Body.Close()
|
||||
|
||||
body, err := io.ReadAll(resp.Body)
|
||||
if err != nil {
|
||||
log.Fatal(err)
|
||||
}
|
||||
|
||||
var response map[string]any
|
||||
jsonErr := json.Unmarshal(body, &response)
|
||||
if jsonErr != nil {
|
||||
w.WriteHeader(http.StatusInternalServerError)
|
||||
return
|
||||
}
|
||||
|
||||
j, err := json.Marshal(response["features"])
|
||||
if err != nil {
|
||||
w.WriteHeader(http.StatusNotFound)
|
||||
return
|
||||
}
|
||||
|
||||
w.WriteHeader(http.StatusOK)
|
||||
w.Header().Set("Content-Type", "application/json")
|
||||
w.Write(j)
|
||||
}
|
||||
@@ -1,50 +0,0 @@
|
||||
package api
|
||||
|
||||
import (
|
||||
"context"
|
||||
"net/http"
|
||||
|
||||
"github.com/rs/zerolog/log"
|
||||
)
|
||||
|
||||
func (h APIHandler) OAuth2Callback(w http.ResponseWriter, r *http.Request) {
|
||||
oauth2Token, err := h.idp.OAuth2Config.Exchange(context.Background(), r.URL.Query().Get("code"))
|
||||
if err != nil {
|
||||
log.Error().Err(err).Msg("Exchange error")
|
||||
w.WriteHeader(http.StatusInternalServerError)
|
||||
return
|
||||
}
|
||||
|
||||
// Extract the ID Token from OAuth2 token.
|
||||
rawIDToken, ok := oauth2Token.Extra("id_token").(string)
|
||||
if !ok {
|
||||
log.Error().Msg("Cannot retrieve ID token")
|
||||
w.WriteHeader(http.StatusInternalServerError)
|
||||
return
|
||||
}
|
||||
|
||||
_, err = h.idp.TokenVerifier.Verify(context.Background(), rawIDToken)
|
||||
if err != nil {
|
||||
log.Error().Err(err).Msg("Not able to verify token")
|
||||
w.WriteHeader(http.StatusUnauthorized)
|
||||
return
|
||||
}
|
||||
|
||||
session, _ := h.idp.SessionsStore.Get(r, "parcoursmob_session")
|
||||
session.Values["idtoken"] = rawIDToken
|
||||
|
||||
redirect := "/app/"
|
||||
|
||||
if session.Values["redirect"] != nil && session.Values["redirect"] != "" {
|
||||
redirect = session.Values["redirect"].(string)
|
||||
delete(session.Values, "redirect")
|
||||
}
|
||||
|
||||
if err = session.Save(r, w); err != nil {
|
||||
log.Error().Err(err).Msg("Cannot save session")
|
||||
w.WriteHeader(http.StatusInternalServerError)
|
||||
return
|
||||
}
|
||||
|
||||
http.Redirect(w, r, redirect, http.StatusFound)
|
||||
}
|
||||
@@ -1,585 +0,0 @@
|
||||
package application
|
||||
|
||||
import (
|
||||
"context"
|
||||
"crypto/rand"
|
||||
"encoding/base64"
|
||||
"fmt"
|
||||
"io"
|
||||
"net/http"
|
||||
"sort"
|
||||
"sync"
|
||||
"time"
|
||||
|
||||
"git.coopgo.io/coopgo-apps/parcoursmob/utils/identification"
|
||||
"git.coopgo.io/coopgo-apps/parcoursmob/utils/sorting"
|
||||
agenda "git.coopgo.io/coopgo-platform/agenda/grpcapi"
|
||||
agendastorage "git.coopgo.io/coopgo-platform/agenda/storage"
|
||||
fleets "git.coopgo.io/coopgo-platform/fleets/grpcapi"
|
||||
fleetsstorage "git.coopgo.io/coopgo-platform/fleets/storage"
|
||||
groupsmanagement "git.coopgo.io/coopgo-platform/groups-management/grpcapi"
|
||||
"git.coopgo.io/coopgo-platform/groups-management/storage"
|
||||
groupstorage "git.coopgo.io/coopgo-platform/groups-management/storage"
|
||||
accounts "git.coopgo.io/coopgo-platform/mobility-accounts/grpcapi"
|
||||
mobilityaccountsstorage "git.coopgo.io/coopgo-platform/mobility-accounts/storage"
|
||||
"github.com/google/uuid"
|
||||
"github.com/gorilla/mux"
|
||||
"github.com/rs/zerolog/log"
|
||||
"google.golang.org/protobuf/types/known/structpb"
|
||||
)
|
||||
|
||||
func (h *ApplicationHandler) Administration(w http.ResponseWriter, r *http.Request) {
|
||||
var (
|
||||
wg sync.WaitGroup
|
||||
accounts, beneficiaries []mobilityaccountsstorage.Account
|
||||
bookings []fleetsstorage.Booking
|
||||
accountsErr, beneficiariesErr, bookingsErr, groupsResponseErr, eventsResponseErr, groupsBatchErr error
|
||||
groups = []groupstorage.Group{}
|
||||
responses = []agendastorage.Event{}
|
||||
groupsResponse *groupsmanagement.GetGroupsResponse
|
||||
eventsResponse *agenda.GetEventsResponse
|
||||
groupids = []string{}
|
||||
groupsBatchResponse *groupsmanagement.GetGroupsBatchResponse
|
||||
)
|
||||
// Retrieve accounts in a goroutine
|
||||
wg.Add(1)
|
||||
go func() {
|
||||
defer wg.Done()
|
||||
accounts, accountsErr = h.services.GetAccounts()
|
||||
}()
|
||||
// Retrieve beneficiaries in a goroutine
|
||||
wg.Add(1)
|
||||
go func() {
|
||||
defer wg.Done()
|
||||
beneficiaries, beneficiariesErr = h.services.GetBeneficiaries()
|
||||
}()
|
||||
// Retrieve bookings in a goroutine
|
||||
wg.Add(1)
|
||||
go func() {
|
||||
defer wg.Done()
|
||||
bookings, bookingsErr = h.services.GetBookings()
|
||||
}()
|
||||
// Retrieve groupsRequest in a goroutine
|
||||
wg.Add(1)
|
||||
go func() {
|
||||
defer wg.Done()
|
||||
request := &groupsmanagement.GetGroupsRequest{
|
||||
Namespaces: []string{"parcoursmob_organizations"},
|
||||
}
|
||||
groupsResponse, groupsResponseErr = h.services.GRPC.GroupsManagement.GetGroups(context.TODO(), request)
|
||||
for _, group := range groupsResponse.Groups {
|
||||
g := group.ToStorageType()
|
||||
groups = append(groups, g)
|
||||
}
|
||||
sort.Sort(sorting.GroupsByName(groups))
|
||||
}()
|
||||
// Retrieve Events in a goroutine
|
||||
wg.Add(1)
|
||||
go func() {
|
||||
defer wg.Done()
|
||||
eventsResponse, eventsResponseErr = h.services.GRPC.Agenda.GetEvents(context.TODO(), &agenda.GetEventsRequest{
|
||||
Namespaces: []string{"parcoursmob_dispositifs"},
|
||||
})
|
||||
for _, e := range eventsResponse.Events {
|
||||
groupids = append(groupids, e.Owners...)
|
||||
responses = append(responses, e.ToStorageType())
|
||||
}
|
||||
sort.Sort(sorting.EventsByStartdate(responses))
|
||||
}()
|
||||
wg.Add(1)
|
||||
// Retrieve groupsBatch in a goroutine
|
||||
go func() {
|
||||
defer wg.Done()
|
||||
groupsBatchResponse, groupsBatchErr = h.services.GRPC.GroupsManagement.GetGroupsBatch(context.TODO(), &groupsmanagement.GetGroupsBatchRequest{
|
||||
Groupids: groupids,
|
||||
})
|
||||
groupps := map[string]any{}
|
||||
if groupsBatchErr == nil {
|
||||
for _, g := range groupsBatchResponse.Groups {
|
||||
groupps[g.Id] = g.ToStorageType()
|
||||
}
|
||||
}
|
||||
}()
|
||||
wg.Wait()
|
||||
if accountsErr != nil || beneficiariesErr != nil || bookingsErr != nil || groupsResponseErr != nil || eventsResponseErr != nil {
|
||||
log.Error().
|
||||
Any("accounts error", accountsErr).
|
||||
Any("beneficiaries error", beneficiariesErr).
|
||||
Any("bookings error", bookingsErr).
|
||||
Any("groups response error", groupsResponseErr).
|
||||
Any("events response error", eventsResponseErr).
|
||||
Any("groups batch error", groupsBatchErr).
|
||||
Msg("Error in retrieving administration data")
|
||||
w.WriteHeader(http.StatusInternalServerError)
|
||||
return
|
||||
}
|
||||
h.Renderer.Administration(w, r, accounts, beneficiaries, groups, bookings, responses)
|
||||
}
|
||||
|
||||
func (h *ApplicationHandler) AdministrationCreateGroup(w http.ResponseWriter, r *http.Request) {
|
||||
if r.Method == "POST" {
|
||||
r.ParseForm()
|
||||
|
||||
if r.FormValue("name") == "" {
|
||||
|
||||
log.Error().Str("name", r.FormValue("name")).Msg("Invalid name")
|
||||
w.WriteHeader(http.StatusBadRequest)
|
||||
return
|
||||
}
|
||||
|
||||
modules := map[string]any{
|
||||
"beneficiaries": r.FormValue("modules.beneficiaries") == "on",
|
||||
"journeys": r.FormValue("modules.journeys") == "on",
|
||||
"vehicles": r.FormValue("modules.vehicles") == "on",
|
||||
"vehicles_management": r.FormValue("modules.vehicles_management") == "on",
|
||||
"events": r.FormValue("modules.events") == "on",
|
||||
"agenda": r.FormValue("modules.agenda") == "on",
|
||||
"groups": r.FormValue("modules.groups") == "on",
|
||||
"administration": r.FormValue("modules.administration") == "on",
|
||||
"support": r.FormValue("modules.support") == "on",
|
||||
"group_module": r.FormValue("modules.group_module") == "on",
|
||||
}
|
||||
|
||||
groupid := uuid.NewString()
|
||||
|
||||
dataMap := map[string]any{
|
||||
"name": r.FormValue("name"),
|
||||
"modules": modules,
|
||||
}
|
||||
|
||||
data, err := structpb.NewValue(dataMap)
|
||||
if err != nil {
|
||||
log.Error().Err(err).Msg("Cannot create PB struct from data map")
|
||||
w.WriteHeader(http.StatusInternalServerError)
|
||||
return
|
||||
}
|
||||
|
||||
request_organization := &groupsmanagement.AddGroupRequest{
|
||||
Group: &groupsmanagement.Group{
|
||||
Id: groupid,
|
||||
Namespace: "parcoursmob_organizations",
|
||||
Data: data.GetStructValue(),
|
||||
},
|
||||
}
|
||||
|
||||
request_role := &groupsmanagement.AddGroupRequest{
|
||||
Group: &groupsmanagement.Group{
|
||||
Id: groupid + ":admin",
|
||||
Namespace: "parcoursmob_roles",
|
||||
},
|
||||
}
|
||||
go func() {
|
||||
_, err = h.services.GRPC.GroupsManagement.AddGroup(context.TODO(), request_organization)
|
||||
if err != nil {
|
||||
log.Error().Err(err).Msg("Issue in Groups management service - AddGroup")
|
||||
w.WriteHeader(http.StatusInternalServerError)
|
||||
return
|
||||
}
|
||||
}()
|
||||
// Create the admin role for the organization
|
||||
go func() {
|
||||
_, err = h.services.GRPC.GroupsManagement.AddGroup(context.TODO(), request_role)
|
||||
if err != nil {
|
||||
log.Error().Err(err).Msg("Issue in Groups management service - AddGroup")
|
||||
w.WriteHeader(http.StatusInternalServerError)
|
||||
return
|
||||
}
|
||||
}()
|
||||
http.Redirect(w, r, fmt.Sprintf("/app/administration/groups/%s", groupid), http.StatusFound)
|
||||
return
|
||||
}
|
||||
h.Renderer.AdministrationCreateGroup(w, r)
|
||||
}
|
||||
|
||||
func (h *ApplicationHandler) AdministrationGroupDisplay(w http.ResponseWriter, r *http.Request) {
|
||||
vars := mux.Vars(r)
|
||||
groupid := vars["groupid"]
|
||||
|
||||
request := &groupsmanagement.GetGroupRequest{
|
||||
Id: groupid,
|
||||
}
|
||||
|
||||
resp, err := h.services.GRPC.GroupsManagement.GetGroup(context.TODO(), request)
|
||||
if err != nil {
|
||||
log.Error().Err(err).Msg("Issue in Groups management service - GetGroup")
|
||||
w.WriteHeader(http.StatusInternalServerError)
|
||||
return
|
||||
}
|
||||
|
||||
groupmembers, admins, err := h.groupmembers(groupid)
|
||||
if err != nil {
|
||||
log.Error().Err(err).Msg("inssue retrieving group members")
|
||||
w.WriteHeader(http.StatusInternalServerError)
|
||||
return
|
||||
}
|
||||
|
||||
h.Renderer.AdministrationGroupDisplay(w, r, resp.Group.ToStorageType(), groupmembers, admins)
|
||||
}
|
||||
|
||||
func (h *ApplicationHandler) AdministrationGroupInviteAdmin(w http.ResponseWriter, r *http.Request) {
|
||||
vars := mux.Vars(r)
|
||||
groupid := vars["groupid"]
|
||||
var (
|
||||
groupresp *groupsmanagement.GetGroupResponse
|
||||
accountresp *accounts.GetAccountUsernameResponse
|
||||
err error
|
||||
)
|
||||
groupresp, err = h.services.GRPC.GroupsManagement.GetGroup(context.TODO(), &groupsmanagement.GetGroupRequest{
|
||||
Id: groupid,
|
||||
Namespace: "parcoursmob_organizations",
|
||||
})
|
||||
if err != nil {
|
||||
log.Error().Err(err).Msg("Issue in Groups management service - GetGroup")
|
||||
w.WriteHeader(http.StatusInternalServerError)
|
||||
return
|
||||
}
|
||||
r.ParseForm()
|
||||
|
||||
accountresp, err = h.services.GRPC.MobilityAccounts.GetAccountUsername(context.TODO(), &accounts.GetAccountUsernameRequest{
|
||||
Username: r.FormValue("username"),
|
||||
Namespace: "parcoursmob",
|
||||
})
|
||||
if err == nil {
|
||||
log.Print("account exists")
|
||||
// Account already exists : adding the existing account to admin list
|
||||
account := accountresp.Account.ToStorageType()
|
||||
// account.Data["groups"] = append(account.Data["groups"].([]any), groupid, groupid)
|
||||
account.Data["groups"] = append(account.Data["groups"].([]any), groupid, groupid+":admin")
|
||||
|
||||
as, _ := accounts.AccountFromStorageType(&account)
|
||||
|
||||
if _, err = h.services.GRPC.MobilityAccounts.UpdateData(context.TODO(), &accounts.UpdateDataRequest{Account: as}); err != nil {
|
||||
log.Error().Err(err).Msg("could not set groups to user account")
|
||||
w.WriteHeader(http.StatusInternalServerError)
|
||||
return
|
||||
}
|
||||
|
||||
data := map[string]any{
|
||||
"group": groupresp.Group.ToStorageType().Data["name"],
|
||||
}
|
||||
|
||||
if err := h.emailing.Send("onboarding.existing_administrator", r.FormValue("username"), data); err != nil {
|
||||
log.Error().Err(err).Msg("Cannot send email")
|
||||
}
|
||||
|
||||
} else {
|
||||
// Onboard now administrator
|
||||
onboarding := map[string]any{
|
||||
"username": r.FormValue("username"),
|
||||
"group": groupid,
|
||||
"admin": true,
|
||||
}
|
||||
|
||||
b := make([]byte, 16)
|
||||
if _, err := io.ReadFull(rand.Reader, b); err != nil {
|
||||
log.Error().Err(err).Msg("Issue creating random bytes")
|
||||
w.WriteHeader(http.StatusInternalServerError)
|
||||
return
|
||||
}
|
||||
key := base64.RawURLEncoding.EncodeToString(b)
|
||||
|
||||
h.cache.PutWithTTL("onboarding/"+key, onboarding, 168*time.Hour) // 1 week TTL
|
||||
|
||||
data := map[string]any{
|
||||
"group": groupresp.Group.ToStorageType().Data["name"],
|
||||
"key": key,
|
||||
}
|
||||
|
||||
if err := h.emailing.Send("onboarding.new_administrator", r.FormValue("username"), data); err != nil {
|
||||
log.Error().Err(err).Msg("Cannot send email")
|
||||
w.WriteHeader(http.StatusInternalServerError)
|
||||
return
|
||||
}
|
||||
}
|
||||
|
||||
http.Redirect(w, r, fmt.Sprintf("/app/administration/groups/%s", groupid), http.StatusFound)
|
||||
}
|
||||
|
||||
func (h *ApplicationHandler) AdministrationGroupInviteMember(w http.ResponseWriter, r *http.Request) {
|
||||
vars := mux.Vars(r)
|
||||
groupid := vars["groupid"]
|
||||
group, err := h.services.GetGroup(groupid)
|
||||
if err != nil {
|
||||
log.Error().Err(err).Msg("Issue in Groups management service - GetGroup")
|
||||
w.WriteHeader(http.StatusInternalServerError)
|
||||
return
|
||||
}
|
||||
r.ParseForm()
|
||||
accountresp, err := h.services.GRPC.MobilityAccounts.GetAccountUsername(context.TODO(), &accounts.GetAccountUsernameRequest{
|
||||
Username: r.FormValue("username"),
|
||||
Namespace: "parcoursmob",
|
||||
})
|
||||
if err == nil {
|
||||
account := accountresp.Account.ToStorageType()
|
||||
account.Data["groups"] = append(account.Data["groups"].([]any), group.ID)
|
||||
|
||||
as, _ := accounts.AccountFromStorageType(&account)
|
||||
|
||||
_, err = h.services.GRPC.MobilityAccounts.UpdateData(
|
||||
context.TODO(),
|
||||
&accounts.UpdateDataRequest{
|
||||
Account: as,
|
||||
},
|
||||
)
|
||||
data := map[string]any{
|
||||
"group": group.Data["name"],
|
||||
}
|
||||
|
||||
if err := h.emailing.Send("onboarding.existing_member", r.FormValue("username"), data); err != nil {
|
||||
log.Error().Err(err).Msg("error sending email onboarding.existing_member")
|
||||
}
|
||||
|
||||
// http.Redirect(w, r, "/app/group/settings", http.StatusFound)
|
||||
// return
|
||||
} else {
|
||||
// Onboard new administrator
|
||||
onboarding := map[string]any{
|
||||
"username": r.FormValue("username"),
|
||||
"group": group.ID,
|
||||
"admin": false,
|
||||
}
|
||||
|
||||
b := make([]byte, 16)
|
||||
if _, err := io.ReadFull(rand.Reader, b); err != nil {
|
||||
w.WriteHeader(http.StatusInternalServerError)
|
||||
return
|
||||
}
|
||||
key := base64.RawURLEncoding.EncodeToString(b)
|
||||
|
||||
h.cache.PutWithTTL("onboarding/"+key, onboarding, 168*time.Hour) // 1 week TTL
|
||||
data := map[string]any{
|
||||
"group": group.Data["name"],
|
||||
"key": key,
|
||||
}
|
||||
|
||||
if err := h.emailing.Send("onboarding.new_member", r.FormValue("username"), data); err != nil {
|
||||
log.Error().Err(err).Msg("error sending email onboarding.new_member")
|
||||
w.WriteHeader(http.StatusInternalServerError)
|
||||
return
|
||||
}
|
||||
}
|
||||
http.Redirect(w, r, "/app/administration/groups/"+group.ID, http.StatusFound)
|
||||
}
|
||||
|
||||
func filteVehicle(r *http.Request, v *fleets.Vehicle) bool {
|
||||
g := r.Context().Value(identification.GroupKey)
|
||||
if g == nil {
|
||||
return false
|
||||
}
|
||||
|
||||
group := g.(storage.Group)
|
||||
|
||||
for _, n := range v.Administrators {
|
||||
if n == group.ID {
|
||||
return true
|
||||
}
|
||||
}
|
||||
|
||||
return false
|
||||
}
|
||||
|
||||
func (h ApplicationHandler) AdminStatVehicles(w http.ResponseWriter, r *http.Request) {
|
||||
bookings := []fleetsstorage.Booking{}
|
||||
administrators := []string{}
|
||||
reequest := &fleets.GetVehiclesRequest{
|
||||
Namespaces: []string{"parcoursmob"},
|
||||
}
|
||||
reesp, err := h.services.GRPC.Fleets.GetVehicles(context.TODO(), reequest)
|
||||
if err != nil {
|
||||
log.Error().Err(err).Msg("Issue in Fleets service - GetVehicles")
|
||||
w.WriteHeader(http.StatusInternalServerError)
|
||||
}
|
||||
|
||||
vehicles := []fleetsstorage.Vehicle{}
|
||||
for _, vehiicle := range reesp.Vehicles {
|
||||
|
||||
v := vehiicle.ToStorageType()
|
||||
adminfound := false
|
||||
for _, a := range administrators {
|
||||
if a == v.Administrators[0] {
|
||||
adminfound = true
|
||||
break
|
||||
}
|
||||
}
|
||||
if !adminfound {
|
||||
administrators = append(administrators, v.Administrators[0])
|
||||
}
|
||||
|
||||
vehicleBookings := []fleetsstorage.Booking{}
|
||||
for _, b := range v.Bookings {
|
||||
if b.Unavailableto.After(time.Now()) {
|
||||
vehicleBookings = append(vehicleBookings, b)
|
||||
}
|
||||
}
|
||||
|
||||
v.Bookings = vehicleBookings
|
||||
|
||||
vehicles = append(vehicles, v)
|
||||
|
||||
}
|
||||
groups := map[string]any{}
|
||||
|
||||
if len(administrators) > 0 {
|
||||
admingroups, err := h.services.GRPC.GroupsManagement.GetGroupsBatch(context.TODO(), &groupsmanagement.GetGroupsBatchRequest{
|
||||
Groupids: administrators,
|
||||
})
|
||||
if err != nil {
|
||||
log.Error().Err(err).Msg("Issue in Groups management service - GetGroupsBatch")
|
||||
w.WriteHeader(http.StatusInternalServerError)
|
||||
return
|
||||
}
|
||||
|
||||
for _, g := range admingroups.Groups {
|
||||
groups[g.Id] = g.ToStorageType()
|
||||
}
|
||||
|
||||
}
|
||||
sort.Sort(sorting.VehiclesByLicencePlate(vehicles))
|
||||
sort.Sort(sorting.BookingsByStartdate(bookings))
|
||||
h.Renderer.AdminStatVehicles(w, r, vehicles, bookings, groups)
|
||||
}
|
||||
|
||||
func (h ApplicationHandler) AdminStatBookings(w http.ResponseWriter, r *http.Request) {
|
||||
vehicles := map[string]fleetsstorage.Vehicle{}
|
||||
bookings := []fleetsstorage.Booking{}
|
||||
|
||||
reequest := &fleets.GetVehiclesRequest{
|
||||
Namespaces: []string{"parcoursmob"},
|
||||
}
|
||||
reesp, err := h.services.GRPC.Fleets.GetVehicles(context.TODO(), reequest)
|
||||
if err != nil {
|
||||
log.Error().Err(err).Msg("Issue in Fleets service - GetVehicles")
|
||||
w.WriteHeader(http.StatusInternalServerError)
|
||||
return
|
||||
}
|
||||
|
||||
beneficiaries_ids := []string{}
|
||||
|
||||
for _, vehicle := range reesp.Vehicles {
|
||||
|
||||
v := vehicle.ToStorageType()
|
||||
|
||||
for _, b := range v.Bookings {
|
||||
bookings = append(bookings, b)
|
||||
beneficiaries_ids = append(beneficiaries_ids, b.Driver)
|
||||
}
|
||||
|
||||
vehicles[v.ID] = v
|
||||
|
||||
}
|
||||
|
||||
groups := map[string]any{}
|
||||
|
||||
admingroups, err := h.services.GRPC.GroupsManagement.GetGroups(context.TODO(), &groupsmanagement.GetGroupsRequest{
|
||||
Namespaces: []string{"parcoursmob_organizations"},
|
||||
})
|
||||
if err != nil {
|
||||
log.Error().Err(err).Msg("Issue in Groups management service - GetGroups")
|
||||
w.WriteHeader(http.StatusInternalServerError)
|
||||
return
|
||||
}
|
||||
|
||||
for _, g := range admingroups.Groups {
|
||||
groups[g.Id] = g.ToStorageType()
|
||||
}
|
||||
|
||||
beneficiaries, err := h.services.GRPC.MobilityAccounts.GetAccountsBatch(context.TODO(), &accounts.GetAccountsBatchRequest{
|
||||
Accountids: beneficiaries_ids,
|
||||
})
|
||||
if err != nil {
|
||||
log.Error().Err(err).Msg("Issue in Mobility accounts service - GetAccountsBatch")
|
||||
w.WriteHeader(http.StatusInternalServerError)
|
||||
return
|
||||
}
|
||||
|
||||
beneficiaries_map := map[string]any{}
|
||||
for _, ben := range beneficiaries.Accounts {
|
||||
beneficiaries_map[ben.Id] = ben.ToStorageType()
|
||||
}
|
||||
|
||||
sort.Sort(sorting.BookingsByStartdate(bookings))
|
||||
h.Renderer.AdminStatBookings(w, r, vehicles, bookings, groups, beneficiaries_map)
|
||||
}
|
||||
|
||||
func (h *ApplicationHandler) members() ([]*accounts.Account, error) {
|
||||
resp, err := h.services.GRPC.MobilityAccounts.GetAccounts(context.TODO(), &accounts.GetAccountsRequest{
|
||||
Namespaces: []string{"parcoursmob"},
|
||||
})
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
|
||||
return resp.Accounts, nil
|
||||
}
|
||||
|
||||
func (h *ApplicationHandler) groupmembers(groupid string) (groupmembers []mobilityaccountsstorage.Account, admins []mobilityaccountsstorage.Account, err error) {
|
||||
members, err := h.members()
|
||||
if err != nil {
|
||||
if err != nil {
|
||||
log.Error().Err(err).Msg("Cannot get members")
|
||||
return nil, nil, err
|
||||
}
|
||||
}
|
||||
|
||||
groupmembers = []mobilityaccountsstorage.Account{}
|
||||
admins = []mobilityaccountsstorage.Account{}
|
||||
|
||||
for _, m := range members {
|
||||
mm := m.ToStorageType()
|
||||
for _, g := range mm.Data["groups"].([]any) {
|
||||
if g.(string) == groupid {
|
||||
groupmembers = append(groupmembers, mm)
|
||||
}
|
||||
if g.(string) == groupid+":admin" {
|
||||
admins = append(admins, mm)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
return groupmembers, admins, err
|
||||
}
|
||||
|
||||
func (h ApplicationHandler) AdminStatBeneficaires(w http.ResponseWriter, r *http.Request) {
|
||||
beneficiaries, err := h.services.GetBeneficiaries()
|
||||
if err != nil {
|
||||
log.Error().Err(err).Msg("Cannot get beneficiaries")
|
||||
w.WriteHeader(http.StatusInternalServerError)
|
||||
return
|
||||
}
|
||||
cacheid := uuid.NewString()
|
||||
h.cache.PutWithTTL(cacheid, beneficiaries, 1*time.Hour)
|
||||
h.Renderer.AdminStatBeneficaires(w, r, beneficiaries, cacheid)
|
||||
}
|
||||
|
||||
func (h ApplicationHandler) AdminStatEvents(w http.ResponseWriter, r *http.Request) {
|
||||
resp, err := h.services.GRPC.Agenda.GetEvents(context.TODO(), &agenda.GetEventsRequest{
|
||||
Namespaces: []string{"parcoursmob_dispositifs"},
|
||||
})
|
||||
if err != nil {
|
||||
log.Error().Err(err).Msg("Issue in Agenda service - GetEvents")
|
||||
w.WriteHeader(http.StatusInternalServerError)
|
||||
return
|
||||
}
|
||||
|
||||
responses := []agendastorage.Event{}
|
||||
|
||||
groupids := []string{}
|
||||
for _, e := range resp.Events {
|
||||
groupids = append(groupids, e.Owners...)
|
||||
responses = append(responses, e.ToStorageType())
|
||||
}
|
||||
|
||||
sort.Sort(sorting.EventsByStartdate(responses))
|
||||
|
||||
groupsresp, err := h.services.GRPC.GroupsManagement.GetGroupsBatch(context.TODO(), &groupsmanagement.GetGroupsBatchRequest{
|
||||
Groupids: groupids,
|
||||
})
|
||||
groups := map[string]any{}
|
||||
|
||||
if err == nil {
|
||||
for _, g := range groupsresp.Groups {
|
||||
groups[g.Id] = g.ToStorageType()
|
||||
}
|
||||
}
|
||||
h.Renderer.AdminStatEvents(w, r, responses, groups)
|
||||
}
|
||||
@@ -1,790 +0,0 @@
|
||||
package application
|
||||
|
||||
import (
|
||||
"context"
|
||||
"encoding/json"
|
||||
"fmt"
|
||||
"io"
|
||||
"net/http"
|
||||
"sort"
|
||||
"strconv"
|
||||
"strings"
|
||||
"time"
|
||||
|
||||
formvalidators "git.coopgo.io/coopgo-apps/parcoursmob/utils/form-validators"
|
||||
"git.coopgo.io/coopgo-apps/parcoursmob/utils/identification"
|
||||
"git.coopgo.io/coopgo-apps/parcoursmob/utils/sorting"
|
||||
filestorage "git.coopgo.io/coopgo-apps/parcoursmob/utils/storage"
|
||||
agenda "git.coopgo.io/coopgo-platform/agenda/grpcapi"
|
||||
agendastorage "git.coopgo.io/coopgo-platform/agenda/storage"
|
||||
groupsmanagement "git.coopgo.io/coopgo-platform/groups-management/grpcapi"
|
||||
"git.coopgo.io/coopgo-platform/groups-management/storage"
|
||||
mobilityaccounts "git.coopgo.io/coopgo-platform/mobility-accounts/grpcapi"
|
||||
"github.com/google/uuid"
|
||||
"github.com/gorilla/mux"
|
||||
"github.com/rs/zerolog/log"
|
||||
"google.golang.org/protobuf/types/known/structpb"
|
||||
"google.golang.org/protobuf/types/known/timestamppb"
|
||||
)
|
||||
|
||||
type EventsForm struct {
|
||||
Name string `json:"name" validate:"required"`
|
||||
Type string `json:"type" validate:"required"`
|
||||
Description string `json:"description"`
|
||||
Address any `json:"address,omitempty"`
|
||||
Allday bool `json:"allday"`
|
||||
Startdate *time.Time `json:"startdate"`
|
||||
Enddate *time.Time `json:"enddate"`
|
||||
Starttime string `json:"starttime"`
|
||||
Endtime string `json:"endtime"`
|
||||
MaxSubscribers int `json:"max_subscribers"`
|
||||
}
|
||||
|
||||
func (h *ApplicationHandler) AgendaHome(w http.ResponseWriter, r *http.Request) {
|
||||
resp, err := h.services.GRPC.Agenda.GetEvents(context.TODO(), &agenda.GetEventsRequest{
|
||||
Namespaces: []string{"parcoursmob_dispositifs"},
|
||||
Mindate: timestamppb.New(time.Now().Add(-24 * time.Hour)),
|
||||
})
|
||||
|
||||
if err != nil {
|
||||
log.Error().Err(err).Msg("")
|
||||
w.WriteHeader(http.StatusInternalServerError)
|
||||
return
|
||||
}
|
||||
|
||||
responses := []agendastorage.Event{}
|
||||
|
||||
groupids := []string{}
|
||||
for _, e := range resp.Events {
|
||||
groupids = append(groupids, e.Owners...)
|
||||
responses = append(responses, e.ToStorageType())
|
||||
}
|
||||
|
||||
sort.Sort(sorting.EventsByStartdate(responses))
|
||||
|
||||
groupsresp, err := h.services.GRPC.GroupsManagement.GetGroupsBatch(context.TODO(), &groupsmanagement.GetGroupsBatchRequest{
|
||||
Groupids: groupids,
|
||||
})
|
||||
groups := map[string]any{}
|
||||
|
||||
if err == nil {
|
||||
for _, g := range groupsresp.Groups {
|
||||
groups[g.Id] = g.ToStorageType()
|
||||
}
|
||||
}
|
||||
h.Renderer.AgendaHome(w, r, responses, groups)
|
||||
}
|
||||
|
||||
func (h *ApplicationHandler) AgendaHistory(w http.ResponseWriter, r *http.Request) {
|
||||
resp, err := h.services.GRPC.Agenda.GetEvents(context.TODO(), &agenda.GetEventsRequest{
|
||||
Namespaces: []string{"parcoursmob_dispositifs"},
|
||||
//Maxdate: timestamppb.New(time.Now().Add(24 * time.Hour)),
|
||||
})
|
||||
|
||||
if err != nil {
|
||||
log.Error().Err(err).Msg("")
|
||||
w.WriteHeader(http.StatusInternalServerError)
|
||||
return
|
||||
}
|
||||
|
||||
responses := []agendastorage.Event{}
|
||||
|
||||
groupids := []string{}
|
||||
for _, e := range resp.Events {
|
||||
groupids = append(groupids, e.Owners...)
|
||||
responses = append(responses, e.ToStorageType())
|
||||
}
|
||||
|
||||
sort.Sort(sorting.EventsByStartdate(responses))
|
||||
|
||||
groupsresp, err := h.services.GRPC.GroupsManagement.GetGroupsBatch(context.TODO(), &groupsmanagement.GetGroupsBatchRequest{
|
||||
Groupids: groupids,
|
||||
})
|
||||
groups := map[string]any{}
|
||||
|
||||
if err == nil {
|
||||
for _, g := range groupsresp.Groups {
|
||||
groups[g.Id] = g.ToStorageType()
|
||||
}
|
||||
}
|
||||
h.Renderer.AgendaHistory(w, r, responses, groups)
|
||||
}
|
||||
|
||||
func (h *ApplicationHandler) AgendaCreateEvent(w http.ResponseWriter, r *http.Request) {
|
||||
if r.Method == "POST" {
|
||||
// Get current group
|
||||
g := r.Context().Value(identification.GroupKey)
|
||||
if g == nil {
|
||||
w.WriteHeader(http.StatusBadRequest)
|
||||
return
|
||||
}
|
||||
|
||||
group := g.(storage.Group)
|
||||
|
||||
eventForm, err := parseEventsForm(r)
|
||||
if err != nil {
|
||||
log.Error().Err(err).Msg("")
|
||||
w.WriteHeader(http.StatusBadRequest)
|
||||
return
|
||||
}
|
||||
|
||||
log.Debug().Any("eventFrom", eventForm).Msg("Form data submitted to create event")
|
||||
|
||||
data, _ := structpb.NewStruct(map[string]any{
|
||||
"address": eventForm.Address,
|
||||
})
|
||||
|
||||
request := &agenda.CreateEventRequest{
|
||||
Event: &agenda.Event{
|
||||
Namespace: "parcoursmob_dispositifs",
|
||||
Owners: []string{group.ID},
|
||||
Type: eventForm.Type,
|
||||
Name: eventForm.Name,
|
||||
Description: eventForm.Description,
|
||||
Startdate: timestamppb.New(*eventForm.Startdate),
|
||||
Enddate: timestamppb.New(*eventForm.Enddate),
|
||||
Starttime: eventForm.Starttime,
|
||||
Endtime: eventForm.Endtime,
|
||||
Allday: eventForm.Allday,
|
||||
MaxSubscribers: int64(eventForm.MaxSubscribers),
|
||||
Data: data,
|
||||
Deleted: false,
|
||||
},
|
||||
}
|
||||
|
||||
resp, err := h.services.GRPC.Agenda.CreateEvent(context.TODO(), request)
|
||||
if err != nil {
|
||||
log.Error().Err(err).Msg("")
|
||||
w.WriteHeader(http.StatusInternalServerError)
|
||||
return
|
||||
}
|
||||
|
||||
contentType := r.Header.Get("Content-Type")
|
||||
if strings.HasPrefix(contentType, "multipart/form-data") {
|
||||
err = r.ParseMultipartForm(100 * 1024 * 1024) // 100 MB limit
|
||||
if err != nil {
|
||||
log.Error().Err(err).Msg("Error parsing multipart form")
|
||||
w.WriteHeader(http.StatusBadRequest)
|
||||
return
|
||||
}
|
||||
|
||||
file, header, err := r.FormFile("file-upload")
|
||||
if err == nil {
|
||||
defer file.Close()
|
||||
|
||||
document_type := r.FormValue("file_type")
|
||||
document_name := r.FormValue("file_name")
|
||||
|
||||
fileid := uuid.NewString()
|
||||
|
||||
metadata := map[string]string{
|
||||
"file_type": document_type,
|
||||
"file_name": document_name,
|
||||
}
|
||||
|
||||
if err := h.filestorage.Put(file, filestorage.PREFIX_AGENDA, fmt.Sprintf("%s/%s_%s", resp.Event.Id, fileid, header.Filename), header.Size, metadata); err != nil {
|
||||
log.Error().Err(err).Msg("Error uploading file")
|
||||
w.WriteHeader(http.StatusInternalServerError)
|
||||
return
|
||||
}
|
||||
} else if err != http.ErrMissingFile {
|
||||
log.Error().Err(err).Msg("Error retrieving file")
|
||||
w.WriteHeader(http.StatusInternalServerError)
|
||||
return
|
||||
}
|
||||
}
|
||||
|
||||
http.Redirect(w, r, fmt.Sprintf("/app/agenda/%s", resp.Event.Id), http.StatusFound)
|
||||
return
|
||||
}
|
||||
|
||||
h.Renderer.AgendaCreateEvent(w, r, h.config.GetStringSlice("modules.agenda.documents_types"), h.config.GetStringMapString("storage.files.file_types"), nil)
|
||||
}
|
||||
|
||||
func (h *ApplicationHandler) AgendaDisplayEvent(w http.ResponseWriter, r *http.Request) {
|
||||
vars := mux.Vars(r)
|
||||
eventid := vars["eventid"]
|
||||
|
||||
request := &agenda.GetEventRequest{
|
||||
Id: eventid,
|
||||
}
|
||||
|
||||
resp, err := h.services.GRPC.Agenda.GetEvent(context.TODO(), request)
|
||||
if err != nil {
|
||||
log.Error().Err(err).Msg("")
|
||||
w.WriteHeader(http.StatusInternalServerError)
|
||||
return
|
||||
}
|
||||
|
||||
grouprequest := &groupsmanagement.GetGroupRequest{
|
||||
Id: resp.Event.Owners[0],
|
||||
}
|
||||
|
||||
groupresp, err := h.services.GRPC.GroupsManagement.GetGroup(context.TODO(), grouprequest)
|
||||
if err != nil {
|
||||
log.Error().Err(err).Msg("")
|
||||
w.WriteHeader(http.StatusInternalServerError)
|
||||
return
|
||||
}
|
||||
|
||||
subscribers := map[string]any{}
|
||||
|
||||
accids := []string{}
|
||||
for _, v := range resp.Event.Subscriptions {
|
||||
accids = append(accids, v.Subscriber)
|
||||
}
|
||||
|
||||
subscriberresp, err := h.services.GRPC.MobilityAccounts.GetAccountsBatch(
|
||||
context.TODO(),
|
||||
&mobilityaccounts.GetAccountsBatchRequest{
|
||||
Accountids: accids,
|
||||
},
|
||||
)
|
||||
|
||||
if err == nil {
|
||||
for _, sub := range subscriberresp.Accounts {
|
||||
subscribers[sub.Id] = sub.ToStorageType()
|
||||
}
|
||||
}
|
||||
|
||||
g := r.Context().Value(identification.GroupKey)
|
||||
if g == nil {
|
||||
log.Error().Err(err).Msg("")
|
||||
w.WriteHeader(http.StatusInternalServerError)
|
||||
return
|
||||
}
|
||||
|
||||
group := g.(storage.Group)
|
||||
|
||||
accountids := []string{}
|
||||
for _, m := range group.Members {
|
||||
if !contains(resp.Event.Subscriptions, m) {
|
||||
accountids = append(accountids, m)
|
||||
}
|
||||
}
|
||||
|
||||
accountresp, err := h.services.GRPC.MobilityAccounts.GetAccountsBatch(
|
||||
context.TODO(),
|
||||
&mobilityaccounts.GetAccountsBatchRequest{
|
||||
Accountids: accountids,
|
||||
},
|
||||
)
|
||||
|
||||
accounts := []any{}
|
||||
|
||||
if err == nil {
|
||||
for _, acc := range accountresp.Accounts {
|
||||
accounts = append(accounts, acc)
|
||||
}
|
||||
}
|
||||
|
||||
documents := h.filestorage.List(filestorage.PREFIX_AGENDA + "/" + eventid)
|
||||
|
||||
events_file_types := h.config.GetStringSlice("modules.agenda.documents_types")
|
||||
file_types_map := h.config.GetStringMapString("storage.files.file_types")
|
||||
|
||||
h.Renderer.AgendaDisplayEvent(w, r, resp.Event.ToStorageType(), groupresp.Group.ToStorageType(), events_file_types, file_types_map, documents, subscribers, accounts)
|
||||
}
|
||||
|
||||
func (h *ApplicationHandler) AgendaSubscribeEvent(w http.ResponseWriter, r *http.Request) {
|
||||
current_group, err := h.currentGroup(r)
|
||||
if err != nil {
|
||||
log.Error().Err(err).Msg("")
|
||||
w.WriteHeader(http.StatusInternalServerError)
|
||||
return
|
||||
}
|
||||
current_user_token, current_user_claims, err := h.currentUser(r)
|
||||
if err != nil {
|
||||
log.Error().Err(err).Msg("")
|
||||
w.WriteHeader(http.StatusInternalServerError)
|
||||
return
|
||||
}
|
||||
vars := mux.Vars(r)
|
||||
eventid := vars["eventid"]
|
||||
|
||||
if err := r.ParseForm(); err != nil {
|
||||
log.Error().Err(err).Msg("")
|
||||
w.WriteHeader(http.StatusBadRequest)
|
||||
return
|
||||
}
|
||||
subscriber := r.FormValue("subscriber")
|
||||
data := map[string]any{
|
||||
"subscribed_by": map[string]any{
|
||||
"user": map[string]any{
|
||||
"id": current_user_token.Subject,
|
||||
"display_name": current_user_claims["first_name"].(string) + " " + current_user_claims["last_name"].(string),
|
||||
"email": current_user_claims["email"].(string),
|
||||
},
|
||||
"group": map[string]any{
|
||||
"id": current_group.ID,
|
||||
"name": current_group.Data["name"],
|
||||
},
|
||||
},
|
||||
}
|
||||
datapb, err := structpb.NewStruct(data)
|
||||
if err != nil {
|
||||
log.Error().Err(err).Msg("")
|
||||
w.WriteHeader(http.StatusInternalServerError)
|
||||
return
|
||||
}
|
||||
|
||||
request := &agenda.SubscribeEventRequest{
|
||||
Eventid: eventid,
|
||||
Subscriber: subscriber,
|
||||
Data: datapb,
|
||||
}
|
||||
|
||||
_, err = h.services.GRPC.Agenda.SubscribeEvent(context.TODO(), request)
|
||||
if err != nil {
|
||||
log.Error().Err(err).Msg("")
|
||||
w.WriteHeader(http.StatusInternalServerError)
|
||||
return
|
||||
}
|
||||
|
||||
http.Redirect(w, r, fmt.Sprintf("/app/agenda/%s", eventid), http.StatusFound)
|
||||
}
|
||||
|
||||
func parseEventsForm(r *http.Request) (*EventsForm, error) {
|
||||
if err := r.ParseForm(); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
|
||||
var startdate *time.Time
|
||||
var enddate *time.Time
|
||||
|
||||
if r.PostFormValue("startdate") != "" {
|
||||
d, err := time.Parse("2006-01-02", r.PostFormValue("startdate"))
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
startdate = &d
|
||||
}
|
||||
|
||||
if r.PostFormValue("enddate") != "" {
|
||||
d, err := time.Parse("2006-01-02", r.PostFormValue("enddate"))
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
enddate = &d
|
||||
}
|
||||
|
||||
max_subscribers, err := strconv.Atoi(r.PostFormValue("max_subscribers"))
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
|
||||
formData := &EventsForm{
|
||||
Name: r.PostFormValue("name"),
|
||||
Type: r.PostFormValue("type"),
|
||||
Description: r.PostFormValue("description"),
|
||||
Startdate: startdate,
|
||||
Enddate: enddate,
|
||||
Starttime: r.PostFormValue("starttime"),
|
||||
Endtime: r.PostFormValue("endtime"),
|
||||
MaxSubscribers: max_subscribers,
|
||||
}
|
||||
|
||||
if r.PostFormValue("allday") == "true" {
|
||||
formData.Allday = true
|
||||
}
|
||||
|
||||
if r.PostFormValue("address") != "" {
|
||||
var a any
|
||||
json.Unmarshal([]byte(r.PostFormValue("address")), &a)
|
||||
|
||||
formData.Address = a
|
||||
}
|
||||
|
||||
validate := formvalidators.New()
|
||||
if err := validate.Struct(formData); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
|
||||
return formData, nil
|
||||
}
|
||||
|
||||
func contains(s []*agenda.Subscription, e string) bool {
|
||||
for _, a := range s {
|
||||
if a.Subscriber == e {
|
||||
return true
|
||||
}
|
||||
}
|
||||
return false
|
||||
}
|
||||
|
||||
// /////////////////////////////Update Event/////////////////////////////////////////
|
||||
func (h *ApplicationHandler) AgendaUpdateEvent(w http.ResponseWriter, r *http.Request) {
|
||||
adm := strings.Split(r.URL.Path, "/")
|
||||
eventID := adm[3]
|
||||
request := &agenda.GetEventRequest{
|
||||
Id: eventID,
|
||||
}
|
||||
|
||||
resp, err := h.services.GRPC.Agenda.GetEvent(context.TODO(), request)
|
||||
if err != nil {
|
||||
log.Error().Err(err).Msg("")
|
||||
w.WriteHeader(http.StatusInternalServerError)
|
||||
return
|
||||
}
|
||||
if r.Method == "POST" {
|
||||
g := r.Context().Value(identification.GroupKey)
|
||||
if g == nil {
|
||||
w.WriteHeader(http.StatusBadRequest)
|
||||
return
|
||||
}
|
||||
|
||||
group := g.(storage.Group)
|
||||
|
||||
eventForm, err := parseEventsForm(r)
|
||||
if err != nil {
|
||||
log.Error().Err(err).Msg("")
|
||||
w.WriteHeader(http.StatusBadRequest)
|
||||
return
|
||||
}
|
||||
|
||||
data, _ := structpb.NewStruct(map[string]any{
|
||||
"address": eventForm.Address,
|
||||
})
|
||||
|
||||
request := &agenda.UpdateEventRequest{
|
||||
Event: &agenda.Event{
|
||||
Namespace: "parcoursmob_dispositifs",
|
||||
Id: eventID,
|
||||
Owners: []string{group.ID},
|
||||
Type: eventForm.Type,
|
||||
Name: eventForm.Name,
|
||||
Description: eventForm.Description,
|
||||
Startdate: timestamppb.New(*eventForm.Startdate),
|
||||
Enddate: timestamppb.New(*eventForm.Enddate),
|
||||
Starttime: eventForm.Starttime,
|
||||
Endtime: eventForm.Endtime,
|
||||
Allday: eventForm.Allday,
|
||||
MaxSubscribers: int64(eventForm.MaxSubscribers),
|
||||
Data: data,
|
||||
Subscriptions: resp.Event.Subscriptions,
|
||||
},
|
||||
}
|
||||
|
||||
resp, err := h.services.GRPC.Agenda.UpdateEvent(context.TODO(), request)
|
||||
|
||||
if err != nil {
|
||||
log.Error().Err(err).Msg("")
|
||||
w.WriteHeader(http.StatusInternalServerError)
|
||||
return
|
||||
}
|
||||
|
||||
http.Redirect(w, r, fmt.Sprintf("/app/agenda/%s", resp.Event.Id), http.StatusFound)
|
||||
return
|
||||
}
|
||||
h.Renderer.AgendaUpdateEvent(w, r, resp.Event.ToStorageType())
|
||||
}
|
||||
|
||||
func (h *ApplicationHandler) AgendaDeleteEvent(w http.ResponseWriter, r *http.Request) {
|
||||
|
||||
vars := mux.Vars(r)
|
||||
eventID := vars["eventid"]
|
||||
request := &agenda.GetEventRequest{
|
||||
Id: eventID,
|
||||
}
|
||||
|
||||
resp, err := h.services.GRPC.Agenda.GetEvent(context.TODO(), request)
|
||||
if err != nil {
|
||||
log.Error().Err(err).Msg("")
|
||||
w.WriteHeader(http.StatusInternalServerError)
|
||||
return
|
||||
}
|
||||
|
||||
if r.Method == "POST" {
|
||||
|
||||
request := &agenda.UpdateEventRequest{
|
||||
Event: &agenda.Event{
|
||||
Namespace: resp.Event.Namespace,
|
||||
Id: resp.Event.Id,
|
||||
Owners: resp.Event.Owners,
|
||||
Type: resp.Event.Type,
|
||||
Name: resp.Event.Name,
|
||||
Description: resp.Event.Description,
|
||||
Startdate: resp.Event.Startdate,
|
||||
Enddate: resp.Event.Enddate,
|
||||
Starttime: resp.Event.Starttime,
|
||||
Endtime: resp.Event.Endtime,
|
||||
Allday: resp.Event.Allday,
|
||||
MaxSubscribers: int64(resp.Event.MaxSubscribers),
|
||||
Data: resp.Event.Data,
|
||||
Subscriptions: resp.Event.Subscriptions,
|
||||
Deleted: true,
|
||||
},
|
||||
}
|
||||
|
||||
_, err := h.services.GRPC.Agenda.UpdateEvent(context.TODO(), request)
|
||||
|
||||
if err != nil {
|
||||
log.Error().Err(err).Msg("")
|
||||
w.WriteHeader(http.StatusInternalServerError)
|
||||
return
|
||||
}
|
||||
|
||||
http.Redirect(w, r, "/app/agenda/", http.StatusFound)
|
||||
return
|
||||
}
|
||||
h.Renderer.AgendaDeleteEvent(w, r, resp.Event.ToStorageType())
|
||||
}
|
||||
|
||||
// /////////////////////////Delete subscriber///////////////////////////////
|
||||
func (h *ApplicationHandler) AgendaDeleteSubscribeEvent(w http.ResponseWriter, r *http.Request) {
|
||||
vars := mux.Vars(r)
|
||||
eventId := vars["eventid"]
|
||||
subscribeid := vars["subscribeid"]
|
||||
s_b_id := ""
|
||||
s_b_name := ""
|
||||
s_b_email := ""
|
||||
s_b_group_id := ""
|
||||
s_b_group_name := ""
|
||||
request := &agenda.GetEventRequest{
|
||||
Id: eventId,
|
||||
}
|
||||
|
||||
resp, err := h.services.GRPC.Agenda.GetEvent(context.TODO(), request)
|
||||
if err != nil {
|
||||
log.Error().Err(err).Msg("")
|
||||
w.WriteHeader(http.StatusInternalServerError)
|
||||
return
|
||||
}
|
||||
|
||||
for i := range resp.Event.Subscriptions {
|
||||
if resp.Event.Subscriptions[i].Subscriber == subscribeid {
|
||||
subscribed_by_id := resp.Event.Subscriptions[i].Data.Fields["subscribed_by"].GetStructValue().Fields["user"].GetStructValue().Fields["id"].GetStringValue()
|
||||
subscribed_by_name := resp.Event.Subscriptions[i].Data.Fields["subscribed_by"].GetStructValue().Fields["user"].GetStructValue().Fields["display_name"].GetStringValue()
|
||||
subscribed_by_email := resp.Event.Subscriptions[i].Data.Fields["subscribed_by"].GetStructValue().Fields["user"].GetStructValue().Fields["email"].GetStringValue()
|
||||
subscribed_by_group_id := resp.Event.Subscriptions[i].Data.Fields["subscribed_by"].GetStructValue().Fields["group"].GetStructValue().Fields["id"].GetStringValue()
|
||||
subscribed_by_group_name := resp.Event.Subscriptions[i].Data.Fields["subscribed_by"].GetStructValue().Fields["group"].GetStructValue().Fields["name"].GetStringValue()
|
||||
s_b_id = subscribed_by_id
|
||||
s_b_name = subscribed_by_name
|
||||
s_b_email = subscribed_by_email
|
||||
s_b_group_id = subscribed_by_group_id
|
||||
s_b_group_name = subscribed_by_group_name
|
||||
}
|
||||
}
|
||||
|
||||
current_group, err := h.currentGroup(r)
|
||||
if err != nil {
|
||||
log.Error().Err(err).Msg("")
|
||||
w.WriteHeader(http.StatusInternalServerError)
|
||||
return
|
||||
}
|
||||
|
||||
current_user_token, current_user_claims, err := h.currentUser(r)
|
||||
if err != nil {
|
||||
log.Error().Err(err).Msg("")
|
||||
w.WriteHeader(http.StatusInternalServerError)
|
||||
return
|
||||
}
|
||||
|
||||
data := map[string]any{
|
||||
"subscribed_by": map[string]any{
|
||||
"user": map[string]any{
|
||||
"id": s_b_id,
|
||||
"display_name": s_b_name,
|
||||
"email": s_b_email,
|
||||
},
|
||||
"group": map[string]any{
|
||||
"id": s_b_group_id,
|
||||
"name": s_b_group_name,
|
||||
},
|
||||
},
|
||||
"unsubscribed_by": map[string]any{
|
||||
"user": map[string]any{
|
||||
"id": current_user_token.Subject,
|
||||
"display_name": current_user_claims["first_name"].(string) + " " + current_user_claims["last_name"].(string),
|
||||
"email": current_user_claims["email"],
|
||||
},
|
||||
"group": map[string]any{
|
||||
"id": current_group.ID,
|
||||
"name": current_group.Data["name"],
|
||||
},
|
||||
},
|
||||
"motif": r.FormValue("motif"),
|
||||
}
|
||||
|
||||
datapb, err := structpb.NewStruct(data)
|
||||
if err != nil {
|
||||
log.Error().Err(err).Msg("")
|
||||
w.WriteHeader(http.StatusInternalServerError)
|
||||
return
|
||||
}
|
||||
|
||||
if r.Method == "POST" {
|
||||
request := &agenda.DeleteSubscriptionRequest{
|
||||
Subscriber: subscribeid,
|
||||
Eventid: eventId,
|
||||
Data: datapb,
|
||||
}
|
||||
|
||||
data := map[string]any{
|
||||
"motif": r.FormValue("motif"),
|
||||
"user": current_user_claims["first_name"].(string) + " " + current_user_claims["last_name"].(string),
|
||||
"subscriber": fmt.Sprintf("http://localhost:9000/app/beneficiaries/%s", subscribeid),
|
||||
"link": fmt.Sprintf("http://localhost:9000/app/agenda/%s", eventId),
|
||||
}
|
||||
|
||||
// récupérer l'adresse mail de l'utilisateur qui a créé l'événement
|
||||
mail := s_b_email
|
||||
log.Debug().Str("mail", mail).Msg("Email content")
|
||||
|
||||
_, err := h.services.GRPC.Agenda.DeleteSubscription(context.TODO(), request)
|
||||
|
||||
if err != nil {
|
||||
log.Error().Err(err).Msg("")
|
||||
w.WriteHeader(http.StatusInternalServerError)
|
||||
return
|
||||
}
|
||||
|
||||
if err := h.emailing.Send("delete_subscriber.request", mail, data); err != nil {
|
||||
log.Error().Err(err).Msg("")
|
||||
w.WriteHeader(http.StatusInternalServerError)
|
||||
return
|
||||
}
|
||||
|
||||
http.Redirect(w, r, fmt.Sprintf("/app/agenda/%s", eventId), http.StatusFound)
|
||||
return
|
||||
}
|
||||
h.Renderer.AgendaDeleteSubscribeEvent(w, r, eventId)
|
||||
}
|
||||
|
||||
// //////////////////////////////////////////////////////
|
||||
// /////////////////////History Event////////////////////////
|
||||
func (h *ApplicationHandler) AgendaHistoryEvent(w http.ResponseWriter, r *http.Request) {
|
||||
vars := mux.Vars(r)
|
||||
eventId := vars["eventid"]
|
||||
request := &agenda.GetEventRequest{
|
||||
Id: eventId,
|
||||
}
|
||||
|
||||
resp, err := h.services.GRPC.Agenda.GetEvent(context.TODO(), request)
|
||||
if err != nil {
|
||||
log.Error().Err(err).Msg("")
|
||||
w.WriteHeader(http.StatusInternalServerError)
|
||||
return
|
||||
}
|
||||
|
||||
grouprequest := &groupsmanagement.GetGroupRequest{
|
||||
Id: resp.Event.Owners[0],
|
||||
}
|
||||
|
||||
groupresp, err := h.services.GRPC.GroupsManagement.GetGroup(context.TODO(), grouprequest)
|
||||
if err != nil {
|
||||
log.Error().Err(err).Msg("")
|
||||
w.WriteHeader(http.StatusInternalServerError)
|
||||
return
|
||||
}
|
||||
|
||||
subscribers := map[string]any{}
|
||||
|
||||
accids := []string{}
|
||||
for _, v := range resp.Event.DeletedSubscription {
|
||||
accids = append(accids, v.Subscriber)
|
||||
}
|
||||
|
||||
subscriberresp, err := h.services.GRPC.MobilityAccounts.GetAccountsBatch(
|
||||
context.TODO(),
|
||||
&mobilityaccounts.GetAccountsBatchRequest{
|
||||
Accountids: accids,
|
||||
},
|
||||
)
|
||||
|
||||
if err == nil {
|
||||
for _, sub := range subscriberresp.Accounts {
|
||||
subscribers[sub.Id] = sub.ToStorageType()
|
||||
}
|
||||
}
|
||||
|
||||
g := r.Context().Value(identification.GroupKey)
|
||||
if g == nil {
|
||||
w.WriteHeader(http.StatusInternalServerError)
|
||||
return
|
||||
}
|
||||
|
||||
group := g.(storage.Group)
|
||||
|
||||
accountids := []string{}
|
||||
for _, m := range group.Members {
|
||||
if !contains(resp.Event.DeletedSubscription, m) {
|
||||
accountids = append(accountids, m)
|
||||
}
|
||||
}
|
||||
|
||||
accountresp, err := h.services.GRPC.MobilityAccounts.GetAccountsBatch(
|
||||
context.TODO(),
|
||||
&mobilityaccounts.GetAccountsBatchRequest{
|
||||
Accountids: accountids,
|
||||
},
|
||||
)
|
||||
|
||||
accounts := []any{}
|
||||
|
||||
if err == nil {
|
||||
for _, acc := range accountresp.Accounts {
|
||||
accounts = append(accounts, acc)
|
||||
}
|
||||
}
|
||||
|
||||
h.Renderer.AgendaHistoryEvent(w, r, resp.Event.ToStorageType(), groupresp.Group.ToStorageType(), subscribers, accounts)
|
||||
}
|
||||
|
||||
// //// ADD DOCUMENTS //////
|
||||
func (h *ApplicationHandler) EventDocuments(w http.ResponseWriter, r *http.Request) {
|
||||
vars := mux.Vars(r)
|
||||
eventID := vars["eventid"]
|
||||
|
||||
//r.ParseForm()
|
||||
r.ParseMultipartForm(100 * 1024 * 1024)
|
||||
|
||||
document_type := r.FormValue("type")
|
||||
document_name := r.FormValue("name")
|
||||
|
||||
file, header, err := r.FormFile("file-upload")
|
||||
if err != nil {
|
||||
log.Error().Err(err).Msg("")
|
||||
return
|
||||
}
|
||||
defer file.Close()
|
||||
|
||||
fileid := uuid.NewString()
|
||||
|
||||
metadata := map[string]string{
|
||||
"type": document_type,
|
||||
"name": document_name,
|
||||
}
|
||||
|
||||
if err := h.filestorage.Put(file, filestorage.PREFIX_AGENDA, fmt.Sprintf("%s/%s_%s", eventID, fileid, header.Filename), header.Size, metadata); err != nil {
|
||||
log.Error().Err(err).Msg("")
|
||||
w.WriteHeader(http.StatusInternalServerError)
|
||||
return
|
||||
}
|
||||
|
||||
http.Redirect(w, r, fmt.Sprintf("/app/agenda/%s", eventID), http.StatusFound)
|
||||
|
||||
}
|
||||
|
||||
func (h *ApplicationHandler) EventDocumentDownload(w http.ResponseWriter, r *http.Request) {
|
||||
vars := mux.Vars(r)
|
||||
eventID := vars["eventid"]
|
||||
document := vars["document"]
|
||||
|
||||
file, info, err := h.filestorage.Get(filestorage.PREFIX_AGENDA, fmt.Sprintf("%s/%s", eventID, document))
|
||||
if err != nil {
|
||||
log.Error().Err(err).Msg("")
|
||||
w.WriteHeader(http.StatusInternalServerError)
|
||||
return
|
||||
}
|
||||
|
||||
w.Header().Set("Content-Type", info.ContentType)
|
||||
if _, err = io.Copy(w, file); err != nil {
|
||||
log.Error().Err(err).Msg("")
|
||||
w.WriteHeader(http.StatusInternalServerError)
|
||||
return
|
||||
}
|
||||
|
||||
http.Redirect(w, r, fmt.Sprintf("/app/agenda/%s", eventID), http.StatusFound)
|
||||
|
||||
}
|
||||
@@ -1,602 +0,0 @@
|
||||
package application
|
||||
|
||||
import (
|
||||
"bytes"
|
||||
"context"
|
||||
"encoding/json"
|
||||
"errors"
|
||||
"fmt"
|
||||
"image/png"
|
||||
"io"
|
||||
"net/http"
|
||||
"sort"
|
||||
"strconv"
|
||||
"strings"
|
||||
"time"
|
||||
|
||||
formvalidators "git.coopgo.io/coopgo-apps/parcoursmob/utils/form-validators"
|
||||
"git.coopgo.io/coopgo-apps/parcoursmob/utils/identification"
|
||||
profilepictures "git.coopgo.io/coopgo-apps/parcoursmob/utils/profile-pictures"
|
||||
"git.coopgo.io/coopgo-apps/parcoursmob/utils/sorting"
|
||||
filestorage "git.coopgo.io/coopgo-apps/parcoursmob/utils/storage"
|
||||
agenda "git.coopgo.io/coopgo-platform/agenda/grpcapi"
|
||||
agendastorage "git.coopgo.io/coopgo-platform/agenda/storage"
|
||||
fleets "git.coopgo.io/coopgo-platform/fleets/grpcapi"
|
||||
fleetsstorage "git.coopgo.io/coopgo-platform/fleets/storage"
|
||||
groupsmanagement "git.coopgo.io/coopgo-platform/groups-management/grpcapi"
|
||||
"git.coopgo.io/coopgo-platform/groups-management/storage"
|
||||
mobilityaccounts "git.coopgo.io/coopgo-platform/mobility-accounts/grpcapi"
|
||||
mobilityaccountsstorage "git.coopgo.io/coopgo-platform/mobility-accounts/storage"
|
||||
diags "git.coopgo.io/coopgo-platform/diags/grpcapi"
|
||||
diagsstorage "git.coopgo.io/coopgo-platform/diags/storage"
|
||||
"github.com/google/uuid"
|
||||
"github.com/gorilla/mux"
|
||||
"github.com/rs/zerolog/log"
|
||||
"google.golang.org/protobuf/types/known/structpb"
|
||||
)
|
||||
|
||||
type BeneficiariesForm struct {
|
||||
FirstName string `json:"first_name" validate:"required"`
|
||||
LastName string `json:"last_name" validate:"required"`
|
||||
Email string `json:"email" validate:"required,email"`
|
||||
Birthdate *time.Time `json:"birthdate" validate:"required"`
|
||||
PhoneNumber string `json:"phone_number" validate:"required,phoneNumber"`
|
||||
FileNumber string `json:"file_number"`
|
||||
Address any `json:"address,omitempty"`
|
||||
Gender string `json:"gender"`
|
||||
}
|
||||
|
||||
type Event_Beneficiary interface {
|
||||
Name() string
|
||||
Date() time.Time
|
||||
DateEnd() time.Time
|
||||
Type() string
|
||||
Db() string
|
||||
ID() string
|
||||
Icons() string
|
||||
Status() int
|
||||
}
|
||||
|
||||
type Event struct {
|
||||
IDVal string
|
||||
NameVal string
|
||||
DateVal time.Time
|
||||
DateEndVal time.Time
|
||||
TypeVal string
|
||||
DbVal string
|
||||
Deleted bool
|
||||
IconSet string
|
||||
StatusVal int
|
||||
}
|
||||
|
||||
func (e Event) Name() string {
|
||||
return e.NameVal
|
||||
}
|
||||
|
||||
func (e Event) Date() time.Time {
|
||||
return e.DateVal
|
||||
}
|
||||
|
||||
func (e Event) DateEnd() time.Time {
|
||||
return e.DateEndVal
|
||||
}
|
||||
|
||||
func (e Event) Type() string {
|
||||
return e.TypeVal
|
||||
}
|
||||
|
||||
func (e Event) ID() string {
|
||||
return e.IDVal
|
||||
}
|
||||
|
||||
func (e Event) Db() string {
|
||||
return e.DbVal
|
||||
}
|
||||
|
||||
func (e Event) Icons() string {
|
||||
return e.IconSet
|
||||
}
|
||||
|
||||
func (e Event) Status() int {
|
||||
return e.StatusVal
|
||||
}
|
||||
|
||||
func sortByDate(events []Event_Beneficiary) {
|
||||
sort.Slice(events, func(i, j int) bool {
|
||||
return events[i].Date().After(events[j].Date())
|
||||
})
|
||||
}
|
||||
|
||||
func (h *ApplicationHandler) BeneficiariesList(w http.ResponseWriter, r *http.Request) {
|
||||
|
||||
accounts, err := h.beneficiaries(r)
|
||||
if err != nil {
|
||||
log.Error().Err(err).Msg("")
|
||||
w.WriteHeader(http.StatusBadRequest)
|
||||
return
|
||||
}
|
||||
|
||||
sort.Sort(sorting.BeneficiariesByName(accounts))
|
||||
|
||||
cacheid := uuid.NewString()
|
||||
h.cache.PutWithTTL(cacheid, accounts, 1*time.Hour)
|
||||
h.Renderer.BeneficiariesList(w, r, accounts, cacheid)
|
||||
}
|
||||
|
||||
func (h *ApplicationHandler) BeneficiaryCreate(w http.ResponseWriter, r *http.Request) {
|
||||
g := r.Context().Value(identification.GroupKey)
|
||||
if g == nil {
|
||||
log.Error().Msg("Create beneficiary : could not find group")
|
||||
w.WriteHeader(http.StatusBadRequest)
|
||||
return
|
||||
}
|
||||
|
||||
group := g.(storage.Group)
|
||||
|
||||
if r.Method == "POST" {
|
||||
|
||||
dataMap, err := parseBeneficiariesForm(r)
|
||||
if err != nil {
|
||||
log.Error().Err(err).Msg("")
|
||||
w.WriteHeader(http.StatusBadRequest)
|
||||
return
|
||||
}
|
||||
|
||||
data, err := structpb.NewValue(dataMap)
|
||||
if err != nil {
|
||||
log.Error().Err(err).Msg("")
|
||||
w.WriteHeader(http.StatusInternalServerError)
|
||||
return
|
||||
}
|
||||
|
||||
request := &mobilityaccounts.RegisterRequest{
|
||||
Account: &mobilityaccounts.Account{
|
||||
Namespace: "parcoursmob_beneficiaries",
|
||||
Data: data.GetStructValue(),
|
||||
},
|
||||
}
|
||||
|
||||
resp, err := h.services.GRPC.MobilityAccounts.Register(context.TODO(), request)
|
||||
|
||||
if err != nil {
|
||||
log.Error().Err(err).Msg("")
|
||||
w.WriteHeader(http.StatusInternalServerError)
|
||||
return
|
||||
}
|
||||
|
||||
subscribe := &groupsmanagement.SubscribeRequest{
|
||||
Groupid: group.ID,
|
||||
Memberid: resp.Account.Id,
|
||||
}
|
||||
|
||||
_, err = h.services.GRPC.GroupsManagement.Subscribe(context.TODO(), subscribe)
|
||||
|
||||
if err != nil {
|
||||
log.Error().Err(err).Msg("")
|
||||
w.WriteHeader(http.StatusInternalServerError)
|
||||
return
|
||||
}
|
||||
|
||||
http.Redirect(w, r, fmt.Sprintf("/app/beneficiaries/%s", resp.Account.Id), http.StatusFound)
|
||||
|
||||
return
|
||||
}
|
||||
h.Renderer.BeneficiaryCreate(w, r)
|
||||
}
|
||||
|
||||
func (h *ApplicationHandler) BeneficiaryDisplay(w http.ResponseWriter, r *http.Request) {
|
||||
vars := mux.Vars(r)
|
||||
beneficiaryID := vars["beneficiaryid"]
|
||||
|
||||
documents := h.filestorage.List(filestorage.PREFIX_BENEFICIARIES + "/" + beneficiaryID)
|
||||
|
||||
request := &mobilityaccounts.GetAccountRequest{
|
||||
Id: beneficiaryID,
|
||||
}
|
||||
|
||||
resp, err := h.services.GRPC.MobilityAccounts.GetAccount(context.TODO(), request)
|
||||
if err != nil {
|
||||
log.Error().Err(err).Msg("")
|
||||
w.WriteHeader(http.StatusInternalServerError)
|
||||
return
|
||||
}
|
||||
|
||||
subscriptionrequest := &agenda.GetSubscriptionByUserRequest{
|
||||
Subscriber: beneficiaryID,
|
||||
}
|
||||
|
||||
subcriptionresp, err := h.services.GRPC.Agenda.GetSubscriptionByUser(context.TODO(), subscriptionrequest)
|
||||
if err != nil {
|
||||
log.Error().Err(err).Msg("")
|
||||
w.WriteHeader(http.StatusInternalServerError)
|
||||
return
|
||||
}
|
||||
|
||||
events := []agendastorage.Event{}
|
||||
currentTime := time.Now().Truncate(24 * time.Hour)
|
||||
|
||||
for _, e := range subcriptionresp.Subscription {
|
||||
eventresquest := &agenda.GetEventRequest{
|
||||
Id: e.Eventid,
|
||||
}
|
||||
eventresp, err := h.services.GRPC.Agenda.GetEvent(context.TODO(), eventresquest)
|
||||
if err != nil {
|
||||
log.Error().Err(err).Msg("")
|
||||
w.WriteHeader(http.StatusInternalServerError)
|
||||
return
|
||||
}
|
||||
events = append(events, eventresp.Event.ToStorageType())
|
||||
}
|
||||
|
||||
sort.Sort(sorting.EventsByStartdate(events))
|
||||
|
||||
bookingsrequest := &fleets.GetDriverBookingsRequest{
|
||||
Driver: beneficiaryID,
|
||||
}
|
||||
bookingsresp, err := h.services.GRPC.Fleets.GetDriverBookings(context.TODO(), bookingsrequest)
|
||||
if err != nil {
|
||||
log.Error().Err(err).Msg("")
|
||||
w.WriteHeader(http.StatusInternalServerError)
|
||||
return
|
||||
}
|
||||
|
||||
bookings := []fleetsstorage.Booking{}
|
||||
|
||||
for _, b := range bookingsresp.Bookings {
|
||||
bookings = append(bookings, b.ToStorageType())
|
||||
}
|
||||
|
||||
var events_list []Event_Beneficiary
|
||||
var status_event int
|
||||
|
||||
for _, e := range events {
|
||||
|
||||
if e.Startdate.After(currentTime) {
|
||||
status_event = 1
|
||||
} else if e.Startdate.Before(currentTime) && e.Enddate.After(currentTime) || e.Enddate.Equal(currentTime) {
|
||||
status_event = 2
|
||||
} else {
|
||||
status_event = 3
|
||||
}
|
||||
|
||||
event := Event{
|
||||
NameVal: e.Name,
|
||||
DateVal: e.Startdate,
|
||||
DateEndVal: e.Enddate,
|
||||
TypeVal: e.Type,
|
||||
IDVal: e.ID,
|
||||
DbVal: "/app/agenda/",
|
||||
IconSet: "calendar",
|
||||
StatusVal: status_event,
|
||||
}
|
||||
|
||||
events_list = append(events_list, event)
|
||||
}
|
||||
|
||||
var status_booking int
|
||||
for _, b := range bookings {
|
||||
|
||||
if b.Enddate.After(currentTime) || b.Enddate.Equal(currentTime) {
|
||||
GetVehiculeRequest := &fleets.GetVehicleRequest{
|
||||
Vehicleid: b.Vehicleid,
|
||||
}
|
||||
|
||||
GetVehiculeResp, err := h.services.GRPC.Fleets.GetVehicle(context.Background(), GetVehiculeRequest)
|
||||
if err != nil {
|
||||
log.Error().Err(err).Msg("")
|
||||
w.WriteHeader(http.StatusInternalServerError)
|
||||
return
|
||||
}
|
||||
|
||||
if b.Startdate.After(currentTime) {
|
||||
status_booking = 1
|
||||
} else if b.Startdate.Before(currentTime) && b.Enddate.After(currentTime) || b.Enddate.Equal(currentTime) {
|
||||
status_booking = 2
|
||||
} else {
|
||||
status_booking = 3
|
||||
}
|
||||
|
||||
event := Event{
|
||||
NameVal: GetVehiculeResp.Vehicle.ToStorageType().Data["name"].(string),
|
||||
DateVal: b.Startdate,
|
||||
DateEndVal: b.Enddate,
|
||||
TypeVal: "Réservation de véhicule",
|
||||
IDVal: b.ID,
|
||||
DbVal: "/app/vehicles-management/bookings/",
|
||||
IconSet: "vehicle",
|
||||
StatusVal: status_booking,
|
||||
}
|
||||
|
||||
events_list = append(events_list, event)
|
||||
}
|
||||
}
|
||||
sortByDate(events_list)
|
||||
|
||||
diag := []diagsstorage.Diag{}
|
||||
|
||||
diagsrequest := &diags.GetDiagsRequest{
|
||||
Namespaces: []string{"parcoursmob_beneficiaries"},
|
||||
}
|
||||
|
||||
diagsresp, err := h.services.GRPC.Diags.GetDiags(context.TODO(), diagsrequest)
|
||||
if err != nil {
|
||||
log.Error().Err(err).Msg("")
|
||||
w.WriteHeader(http.StatusInternalServerError)
|
||||
return
|
||||
}
|
||||
|
||||
for _, d := range diagsresp.Diags {
|
||||
diagData := d.Data.AsMap()
|
||||
if beneficiary, ok := diagData["beneficiary"].(string); ok && beneficiary == beneficiaryID {
|
||||
diag = append(diag, d.ToStorageType())
|
||||
}
|
||||
}
|
||||
|
||||
groupsrequest := &groupsmanagement.GetGroupsRequest{
|
||||
Namespaces: []string{"parcoursmob_organizations"},
|
||||
Member: beneficiaryID,
|
||||
}
|
||||
|
||||
groupsresp, err := h.services.GRPC.GroupsManagement.GetGroups(context.TODO(), groupsrequest)
|
||||
if err != nil {
|
||||
log.Error().Err(err).Msg("")
|
||||
}
|
||||
|
||||
organizations := []any{}
|
||||
for _, o := range groupsresp.Groups {
|
||||
organizations = append(organizations, o.ToStorageType())
|
||||
}
|
||||
|
||||
beneficiaries_file_types := h.config.GetStringSlice("modules.beneficiaries.documents_types")
|
||||
file_types_map := h.config.GetStringMapString("storage.files.file_types")
|
||||
|
||||
diagsAny := make([]any, len(diag))
|
||||
for i, d := range diag {
|
||||
diagsAny[i] = d
|
||||
}
|
||||
h.Renderer.BeneficiaryDisplay(w, r, resp.Account.ToStorageType(), bookings, organizations, beneficiaries_file_types, file_types_map, documents, events_list, diagsAny)
|
||||
}
|
||||
|
||||
func (h *ApplicationHandler) BeneficiaryUpdate(w http.ResponseWriter, r *http.Request) {
|
||||
vars := mux.Vars(r)
|
||||
beneficiaryID := vars["beneficiaryid"]
|
||||
|
||||
if r.Method == "POST" {
|
||||
|
||||
dataMap, err := parseBeneficiariesForm(r)
|
||||
if err != nil {
|
||||
log.Error().Err(err).Msg("")
|
||||
w.WriteHeader(http.StatusBadRequest)
|
||||
return
|
||||
}
|
||||
|
||||
data, err := structpb.NewValue(dataMap)
|
||||
if err != nil {
|
||||
log.Error().Err(err).Msg("")
|
||||
w.WriteHeader(http.StatusInternalServerError)
|
||||
return
|
||||
}
|
||||
|
||||
request := &mobilityaccounts.UpdateDataRequest{
|
||||
Account: &mobilityaccounts.Account{
|
||||
Id: beneficiaryID,
|
||||
Namespace: "parcoursmob_beneficiaries",
|
||||
Data: data.GetStructValue(),
|
||||
},
|
||||
}
|
||||
|
||||
resp, err := h.services.GRPC.MobilityAccounts.UpdateData(context.TODO(), request)
|
||||
|
||||
if err != nil {
|
||||
log.Error().Err(err).Msg("")
|
||||
w.WriteHeader(http.StatusInternalServerError)
|
||||
return
|
||||
}
|
||||
|
||||
http.Redirect(w, r, fmt.Sprintf("/app/beneficiaries/%s", resp.Account.Id), http.StatusFound)
|
||||
|
||||
return
|
||||
}
|
||||
|
||||
request := &mobilityaccounts.GetAccountRequest{
|
||||
Id: beneficiaryID,
|
||||
}
|
||||
|
||||
resp, err := h.services.GRPC.MobilityAccounts.GetAccount(context.TODO(), request)
|
||||
if err != nil {
|
||||
log.Error().Err(err).Msg("")
|
||||
w.WriteHeader(http.StatusInternalServerError)
|
||||
return
|
||||
}
|
||||
|
||||
//TODO filter namespaces
|
||||
//TODO filter groups
|
||||
|
||||
h.Renderer.BeneficiaryUpdate(w, r, resp.Account.ToStorageType())
|
||||
}
|
||||
|
||||
func (h *ApplicationHandler) BeneficiaryPicture(w http.ResponseWriter, r *http.Request) {
|
||||
vars := mux.Vars(r)
|
||||
beneficiaryID := vars["beneficiaryid"]
|
||||
|
||||
request := &mobilityaccounts.GetAccountRequest{
|
||||
Id: beneficiaryID,
|
||||
}
|
||||
|
||||
resp, err := h.services.GRPC.MobilityAccounts.GetAccount(context.TODO(), request)
|
||||
if err != nil {
|
||||
log.Error().Err(err).Msg("")
|
||||
w.WriteHeader(http.StatusInternalServerError)
|
||||
return
|
||||
}
|
||||
|
||||
account := resp.Account.ToStorageType()
|
||||
|
||||
firstName := account.Data["first_name"].(string)
|
||||
lastName := account.Data["last_name"].(string)
|
||||
picture := profilepictures.DefaultProfilePicture(strings.ToUpper(firstName[0:1] + lastName[0:1]))
|
||||
|
||||
buffer := new(bytes.Buffer)
|
||||
if err := png.Encode(buffer, picture); err != nil {
|
||||
log.Error().Err(err).Msg("unable to encode image.")
|
||||
}
|
||||
|
||||
w.Header().Set("Content-Type", "image/png")
|
||||
w.Header().Set("Content-Length", strconv.Itoa(len(buffer.Bytes())))
|
||||
if _, err := w.Write(buffer.Bytes()); err != nil {
|
||||
log.Error().Err(err).Msg("unable to write image.")
|
||||
}
|
||||
}
|
||||
|
||||
func (h *ApplicationHandler) BeneficiaryDocuments(w http.ResponseWriter, r *http.Request) {
|
||||
vars := mux.Vars(r)
|
||||
beneficiaryID := vars["beneficiaryid"]
|
||||
|
||||
//r.ParseForm()
|
||||
r.ParseMultipartForm(100 * 1024 * 1024)
|
||||
|
||||
document_type := r.FormValue("type")
|
||||
document_name := r.FormValue("name")
|
||||
|
||||
file, header, err := r.FormFile("file-upload")
|
||||
if err != nil {
|
||||
log.Error().Err(err).Msg("")
|
||||
return
|
||||
}
|
||||
defer file.Close()
|
||||
|
||||
fileid := uuid.NewString()
|
||||
|
||||
metadata := map[string]string{
|
||||
"type": document_type,
|
||||
"name": document_name,
|
||||
}
|
||||
|
||||
log.Debug().Any("metadata", metadata).Msg("Metadata")
|
||||
|
||||
if err := h.filestorage.Put(file, filestorage.PREFIX_BENEFICIARIES, fmt.Sprintf("%s/%s_%s", beneficiaryID, fileid, header.Filename), header.Size, metadata); err != nil {
|
||||
log.Error().Err(err).Msg("")
|
||||
w.WriteHeader(http.StatusInternalServerError)
|
||||
return
|
||||
}
|
||||
|
||||
http.Redirect(w, r, fmt.Sprintf("/app/beneficiaries/%s", beneficiaryID), http.StatusFound)
|
||||
|
||||
}
|
||||
|
||||
func (h *ApplicationHandler) BeneficiaryDocumentDownload(w http.ResponseWriter, r *http.Request) {
|
||||
vars := mux.Vars(r)
|
||||
beneficiaryID := vars["beneficiaryid"]
|
||||
document := vars["document"]
|
||||
|
||||
file, info, err := h.filestorage.Get(filestorage.PREFIX_BENEFICIARIES, fmt.Sprintf("%s/%s", beneficiaryID, document))
|
||||
if err != nil {
|
||||
log.Error().Err(err).Msg("")
|
||||
w.WriteHeader(http.StatusInternalServerError)
|
||||
return
|
||||
}
|
||||
|
||||
w.Header().Set("Content-Type", info.ContentType)
|
||||
if _, err = io.Copy(w, file); err != nil {
|
||||
log.Error().Err(err).Msg("")
|
||||
w.WriteHeader(http.StatusInternalServerError)
|
||||
return
|
||||
}
|
||||
|
||||
http.Redirect(w, r, fmt.Sprintf("/app/beneficiaries/%s", beneficiaryID), http.StatusFound)
|
||||
|
||||
}
|
||||
|
||||
func filterAccount(r *http.Request, a *mobilityaccounts.Account) bool {
|
||||
searchFilter, ok := r.URL.Query()["search"]
|
||||
|
||||
if ok && len(searchFilter[0]) > 0 {
|
||||
name := a.Data.AsMap()["first_name"].(string) + " " + a.Data.AsMap()["last_name"].(string)
|
||||
if !strings.Contains(strings.ToLower(name), strings.ToLower(searchFilter[0])) {
|
||||
return false
|
||||
}
|
||||
}
|
||||
|
||||
return true
|
||||
}
|
||||
|
||||
// func BeneficiariesEventList()
|
||||
|
||||
func (h *ApplicationHandler) beneficiaries(r *http.Request) ([]mobilityaccountsstorage.Account, error) {
|
||||
var accounts = []mobilityaccountsstorage.Account{}
|
||||
g := r.Context().Value(identification.GroupKey)
|
||||
if g == nil {
|
||||
return accounts, errors.New("no group provided")
|
||||
}
|
||||
|
||||
group := g.(storage.Group)
|
||||
|
||||
request := &mobilityaccounts.GetAccountsBatchRequest{
|
||||
Accountids: group.Members,
|
||||
}
|
||||
|
||||
resp, err := h.services.GRPC.MobilityAccounts.GetAccountsBatch(context.TODO(), request)
|
||||
if err != nil {
|
||||
return accounts, err
|
||||
}
|
||||
|
||||
for _, account := range resp.Accounts {
|
||||
if filterAccount(r, account) {
|
||||
a := account.ToStorageType()
|
||||
accounts = append(accounts, a)
|
||||
}
|
||||
}
|
||||
|
||||
return accounts, err
|
||||
}
|
||||
|
||||
func parseBeneficiariesForm(r *http.Request) (map[string]any, error) {
|
||||
if err := r.ParseForm(); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
|
||||
var date *time.Time
|
||||
|
||||
if r.PostFormValue("birthdate") != "" {
|
||||
d, err := time.Parse("2006-01-02", r.PostFormValue("birthdate"))
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
date = &d
|
||||
}
|
||||
|
||||
formData := BeneficiariesForm{
|
||||
FirstName: r.PostFormValue("first_name"),
|
||||
LastName: r.PostFormValue("last_name"),
|
||||
Email: r.PostFormValue("email"),
|
||||
Birthdate: date,
|
||||
PhoneNumber: r.PostFormValue("phone_number"),
|
||||
FileNumber: r.PostFormValue("file_number"),
|
||||
Gender: r.PostFormValue("gender"),
|
||||
}
|
||||
|
||||
if r.PostFormValue("address") != "" {
|
||||
var a any
|
||||
json.Unmarshal([]byte(r.PostFormValue("address")), &a)
|
||||
|
||||
formData.Address = a
|
||||
}
|
||||
|
||||
validate := formvalidators.New()
|
||||
if err := validate.Struct(formData); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
|
||||
d, err := json.Marshal(formData)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
|
||||
var dataMap map[string]any
|
||||
err = json.Unmarshal(d, &dataMap)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
|
||||
return dataMap, nil
|
||||
}
|
||||
@@ -1,95 +0,0 @@
|
||||
package application
|
||||
|
||||
import (
|
||||
"context"
|
||||
"net/http"
|
||||
"sort"
|
||||
|
||||
"git.coopgo.io/coopgo-apps/parcoursmob/utils/identification"
|
||||
"git.coopgo.io/coopgo-apps/parcoursmob/utils/sorting"
|
||||
agenda "git.coopgo.io/coopgo-platform/agenda/grpcapi"
|
||||
agendastorage "git.coopgo.io/coopgo-platform/agenda/storage"
|
||||
fleets "git.coopgo.io/coopgo-platform/fleets/grpcapi"
|
||||
fleetstorage "git.coopgo.io/coopgo-platform/fleets/storage"
|
||||
"git.coopgo.io/coopgo-platform/groups-management/storage"
|
||||
mobilityaccounts "git.coopgo.io/coopgo-platform/mobility-accounts/grpcapi"
|
||||
"github.com/rs/zerolog/log"
|
||||
"google.golang.org/protobuf/types/known/timestamppb"
|
||||
)
|
||||
|
||||
func (h *ApplicationHandler) Dashboard(w http.ResponseWriter, r *http.Request) {
|
||||
|
||||
g := r.Context().Value(identification.GroupKey)
|
||||
if g == nil {
|
||||
w.WriteHeader(http.StatusBadRequest)
|
||||
return
|
||||
}
|
||||
|
||||
group := g.(storage.Group)
|
||||
|
||||
request := &mobilityaccounts.GetAccountsBatchRequest{
|
||||
Accountids: group.Members,
|
||||
}
|
||||
|
||||
resp, err := h.services.GRPC.MobilityAccounts.GetAccountsBatch(context.TODO(), request)
|
||||
if err != nil {
|
||||
log.Error().Err(err).Msg("")
|
||||
w.WriteHeader(http.StatusInternalServerError)
|
||||
return
|
||||
}
|
||||
|
||||
var accounts = []any{}
|
||||
|
||||
// We only display the 10 last here
|
||||
count := len(resp.Accounts)
|
||||
min := count - 5
|
||||
if min < 0 {
|
||||
min = 0
|
||||
}
|
||||
|
||||
for _, account := range resp.Accounts[min:] {
|
||||
if filterAccount(r, account) {
|
||||
a := account.ToStorageType()
|
||||
accounts = append([]any{a}, accounts...)
|
||||
}
|
||||
}
|
||||
|
||||
members, _, err := h.groupmembers(group.ID)
|
||||
if err != nil {
|
||||
log.Error().Err(err).Msg("")
|
||||
w.WriteHeader(http.StatusInternalServerError)
|
||||
return
|
||||
}
|
||||
|
||||
count_members := len(members)
|
||||
|
||||
events := []agendastorage.Event{}
|
||||
|
||||
eventsresp, err := h.services.GRPC.Agenda.GetEvents(context.TODO(), &agenda.GetEventsRequest{
|
||||
Namespaces: []string{"parcoursmob_dispositifs"},
|
||||
Mindate: timestamppb.Now(),
|
||||
})
|
||||
|
||||
if err == nil {
|
||||
for _, e := range eventsresp.Events {
|
||||
events = append(events, e.ToStorageType())
|
||||
}
|
||||
}
|
||||
|
||||
sort.Sort(sorting.EventsByStartdate(events))
|
||||
|
||||
bookings := []fleetstorage.Booking{}
|
||||
|
||||
bookingsresp, err := h.services.GRPC.Fleets.GetBookings(context.TODO(), &fleets.GetBookingsRequest{
|
||||
Namespaces: []string{"parcoursmob_dispositifs"},
|
||||
})
|
||||
|
||||
if err == nil {
|
||||
for _, b := range bookingsresp.Bookings {
|
||||
bookings = append(bookings, b.ToStorageType())
|
||||
}
|
||||
}
|
||||
|
||||
h.Renderer.Dashboard(w, r, accounts, count, count_members, events, bookings)
|
||||
|
||||
}
|
||||
@@ -1,642 +0,0 @@
|
||||
package application
|
||||
|
||||
import (
|
||||
"context"
|
||||
"encoding/json"
|
||||
"errors"
|
||||
"fmt"
|
||||
"io"
|
||||
|
||||
// "io"
|
||||
"net/http"
|
||||
// "strconv"
|
||||
"strings"
|
||||
"time"
|
||||
|
||||
"git.coopgo.io/coopgo-apps/parcoursmob/services"
|
||||
"git.coopgo.io/coopgo-apps/parcoursmob/utils/identification"
|
||||
filestorage "git.coopgo.io/coopgo-apps/parcoursmob/utils/storage"
|
||||
|
||||
// filestorage "git.coopgo.io/coopgo-apps/parcoursmob/utils/storage"
|
||||
diags "git.coopgo.io/coopgo-platform/diags/grpcapi"
|
||||
diagsstorage "git.coopgo.io/coopgo-platform/diags/storage"
|
||||
|
||||
groupsmanagement "git.coopgo.io/coopgo-platform/groups-management/grpcapi"
|
||||
"git.coopgo.io/coopgo-platform/groups-management/storage"
|
||||
// mobilityaccounts "git.coopgo.io/coopgo-platform/mobility-accounts/grpcapi"
|
||||
// "github.com/google/uuid"
|
||||
"github.com/google/uuid"
|
||||
"github.com/gorilla/mux"
|
||||
"github.com/rs/zerolog/log"
|
||||
"google.golang.org/protobuf/types/known/structpb"
|
||||
"google.golang.org/protobuf/types/known/timestamppb"
|
||||
)
|
||||
|
||||
type DiagsForm struct {
|
||||
Name string `json:"name" validate:"required"`
|
||||
Namespace string `json:"namespace" validate:"required"`
|
||||
JsonSchema string `json:"json_schema"`
|
||||
UiSchema string `json:"ui_schema"`
|
||||
Data map[string]any `json:"data"`
|
||||
Deleted bool `json:"deleted"`
|
||||
Diagdate *time.Time `json:"diagdate"`
|
||||
Owners []string `json:"owners"`
|
||||
}
|
||||
|
||||
func (h *ApplicationHandler) DiagsHome(w http.ResponseWriter, r *http.Request) {
|
||||
groupID := r.Context().Value(identification.GroupKey).(storage.Group).ID
|
||||
|
||||
resp, err := h.services.GRPC.Diags.GetDiags(context.TODO(), &diags.GetDiagsRequest{
|
||||
Namespaces: []string{"parcoursmob_beneficiaries", "parcoursmob_diagnostiques", "parcoursmob_vehicles", "parcoursmob_bookings"},
|
||||
})
|
||||
|
||||
if err != nil {
|
||||
log.Error().Err(err).Msg("")
|
||||
w.WriteHeader(http.StatusInternalServerError)
|
||||
return
|
||||
}
|
||||
|
||||
responses := []diagsstorage.Diag{}
|
||||
|
||||
groupids := []string{}
|
||||
for _, e := range resp.Diags {
|
||||
groupids = append(groupids, e.Owners...)
|
||||
responses = append(responses, e.ToStorageType())
|
||||
}
|
||||
|
||||
groupsresp, err := h.services.GRPC.GroupsManagement.GetGroupsBatch(context.TODO(), &groupsmanagement.GetGroupsBatchRequest{
|
||||
Groupids: groupids,
|
||||
})
|
||||
groups := map[string]any{}
|
||||
|
||||
if err == nil {
|
||||
for _, g := range groupsresp.Groups {
|
||||
groups[g.Id] = g.ToStorageType()
|
||||
}
|
||||
}
|
||||
|
||||
filteredDiags := []diagsstorage.Diag{}
|
||||
for _, diag := range responses {
|
||||
for _, owner := range diag.Owners {
|
||||
if string(owner) == groupID {
|
||||
filteredDiags = append(filteredDiags, diag)
|
||||
log.Debug().Msgf("Diag %s added to filtered list", diag.ID)
|
||||
break
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
h.Renderer.DiagsHome(w, r, filteredDiags, groups)
|
||||
}
|
||||
|
||||
func (h *ApplicationHandler) DiagsHistory(w http.ResponseWriter, r *http.Request) {
|
||||
resp, err := h.services.GRPC.Diags.GetDiags(context.TODO(), &diags.GetDiagsRequest{
|
||||
Namespaces: []string{"parcoursmob_beneficiaries", "parcoursmob_diagnostiques", "parcoursmob_vehicles", "parcoursmob_bookings"},
|
||||
})
|
||||
|
||||
if err != nil {
|
||||
log.Error().Err(err).Msg("")
|
||||
w.WriteHeader(http.StatusInternalServerError)
|
||||
return
|
||||
}
|
||||
|
||||
responses := []diagsstorage.Diag{}
|
||||
|
||||
for _, e := range resp.Diags {
|
||||
if e.Deleted {
|
||||
responses = append(responses, e.ToStorageType())
|
||||
}
|
||||
}
|
||||
|
||||
h.Renderer.DiagsHistory(w, r, responses)
|
||||
}
|
||||
|
||||
func (h *ApplicationHandler) BeneficiariesCreateDiag(w http.ResponseWriter, r *http.Request) {
|
||||
vars := mux.Vars(r)
|
||||
beneficiaryID := vars["beneficiaryid"]
|
||||
|
||||
if h.services == nil || (h.services.GRPC == services.GRPCServices{}) || h.services.GRPC.Diags == nil {
|
||||
log.Error().Msg("Diags service is not initialized")
|
||||
http.Error(w, "Internal server error", http.StatusInternalServerError)
|
||||
return
|
||||
}
|
||||
|
||||
|
||||
if r.Method == http.MethodPost {
|
||||
g := r.Context().Value(identification.GroupKey)
|
||||
if g == nil {
|
||||
http.Error(w, "Missing group information", http.StatusBadRequest)
|
||||
return
|
||||
}
|
||||
|
||||
group := g.(storage.Group)
|
||||
|
||||
diagForm, err := parseDiagsForm(r)
|
||||
if err != nil {
|
||||
log.Error().Err(err).Msg("Invalid form data")
|
||||
http.Error(w, err.Error(), http.StatusBadRequest)
|
||||
return
|
||||
}
|
||||
|
||||
data, err := structpb.NewStruct(map[string]any{
|
||||
"beneficiary": beneficiaryID,
|
||||
})
|
||||
if err != nil {
|
||||
log.Error().Err(err).Msg("Failed to create protobuf struct")
|
||||
w.WriteHeader(http.StatusInternalServerError)
|
||||
return
|
||||
}
|
||||
|
||||
request := &diags.CreateDiagRequest{
|
||||
Diag: &diags.Diag{
|
||||
Name: diagForm.Name,
|
||||
Namespace: diagForm.Namespace,
|
||||
JsonSchema: diagForm.JsonSchema,
|
||||
UiSchema: diagForm.UiSchema,
|
||||
Data: data,
|
||||
Deleted: diagForm.Deleted,
|
||||
Diagdate: timestamppb.New(time.Now()),
|
||||
Owners: []string{group.ID},
|
||||
},
|
||||
}
|
||||
|
||||
resp, err := h.services.GRPC.Diags.CreateDiag(context.TODO(), request)
|
||||
if err != nil {
|
||||
log.Error().Err(err).Msg("Failed to create diagnostic")
|
||||
w.WriteHeader(http.StatusInternalServerError)
|
||||
return
|
||||
}
|
||||
|
||||
contentType := r.Header.Get("Content-Type")
|
||||
if strings.HasPrefix(contentType, "multipart/form-data") {
|
||||
err = r.ParseMultipartForm(100 * 1024 * 1024) // 100 MB limit
|
||||
if err != nil {
|
||||
log.Error().Err(err).Msg("Error parsing multipart form")
|
||||
w.WriteHeader(http.StatusBadRequest)
|
||||
return
|
||||
}
|
||||
|
||||
file, header, err := r.FormFile("file-upload")
|
||||
if err == nil {
|
||||
defer file.Close()
|
||||
|
||||
document_type := r.FormValue("file_type")
|
||||
document_name := r.FormValue("file_name")
|
||||
|
||||
fileid := uuid.NewString()
|
||||
|
||||
metadata := map[string]string{
|
||||
"file_type": document_type,
|
||||
"file_name": document_name,
|
||||
}
|
||||
|
||||
if err := h.filestorage.Put(file, filestorage.PREFIX_DIAGS, fmt.Sprintf("%s/%s_%s", resp.Diag.Id, fileid, header.Filename), header.Size, metadata); err != nil {
|
||||
log.Error().Err(err).Msg("Error uploading file")
|
||||
w.WriteHeader(http.StatusInternalServerError)
|
||||
return
|
||||
}
|
||||
} else if err != http.ErrMissingFile {
|
||||
log.Error().Err(err).Msg("Error retrieving file")
|
||||
w.WriteHeader(http.StatusInternalServerError)
|
||||
return
|
||||
}
|
||||
}
|
||||
|
||||
http.Redirect(w, r, fmt.Sprintf("/app/diags/%s", resp.Diag.Id), http.StatusFound)
|
||||
return
|
||||
}
|
||||
|
||||
h.Renderer.BeneficiariesCreateDiag(w, r, beneficiaryID, h.config.GetStringSlice("modules.diags.documents_types"), h.config.GetStringMapString("storage.files.file_types"), nil)
|
||||
}
|
||||
|
||||
func (h *ApplicationHandler) VehiclesCreateDiag(w http.ResponseWriter, r *http.Request) {
|
||||
vars := mux.Vars(r)
|
||||
vehicleID := vars["vehicleid"]
|
||||
|
||||
if h.services == nil || (h.services.GRPC == services.GRPCServices{}) || h.services.GRPC.Diags == nil {
|
||||
log.Error().Msg("Diags service is not initialized")
|
||||
http.Error(w, "Internal server error", http.StatusInternalServerError)
|
||||
return
|
||||
}
|
||||
|
||||
|
||||
if r.Method == http.MethodPost {
|
||||
g := r.Context().Value(identification.GroupKey)
|
||||
if g == nil {
|
||||
http.Error(w, "Missing group information", http.StatusBadRequest)
|
||||
return
|
||||
}
|
||||
|
||||
diagForm, err := parseDiagsForm(r)
|
||||
if err != nil {
|
||||
log.Error().Err(err).Msg("Invalid form data")
|
||||
http.Error(w, err.Error(), http.StatusBadRequest)
|
||||
return
|
||||
}
|
||||
|
||||
log.Debug().Interface("diagForm", diagForm).Msg("Form data parsed")
|
||||
|
||||
data, err := structpb.NewStruct(map[string]any{
|
||||
"vehicle": vehicleID,
|
||||
})
|
||||
if err != nil {
|
||||
log.Error().Err(err).Msg("Failed to create protobuf struct")
|
||||
w.WriteHeader(http.StatusInternalServerError)
|
||||
return
|
||||
}
|
||||
|
||||
group := g.(storage.Group)
|
||||
|
||||
request := &diags.CreateDiagRequest{
|
||||
Diag: &diags.Diag{
|
||||
Name: diagForm.Name,
|
||||
Namespace: diagForm.Namespace,
|
||||
JsonSchema: diagForm.JsonSchema,
|
||||
UiSchema: diagForm.UiSchema,
|
||||
Data: data,
|
||||
Deleted: diagForm.Deleted,
|
||||
Diagdate: timestamppb.New(time.Now()),
|
||||
Owners: []string{group.ID},
|
||||
},
|
||||
}
|
||||
|
||||
resp, err := h.services.GRPC.Diags.CreateDiag(context.TODO(), request)
|
||||
if err != nil {
|
||||
log.Error().Err(err).Msg("Failed to create diagnostic")
|
||||
w.WriteHeader(http.StatusInternalServerError)
|
||||
return
|
||||
}
|
||||
|
||||
http.Redirect(w, r, fmt.Sprintf("/app/diags/%s", resp.Diag.Id), http.StatusFound)
|
||||
return
|
||||
}
|
||||
|
||||
h.Renderer.VehiclesCreateDiag(w, r, vehicleID)
|
||||
}
|
||||
|
||||
func (h *ApplicationHandler) BookingsCreateDiag(w http.ResponseWriter, r *http.Request) {
|
||||
vars := mux.Vars(r)
|
||||
bookingID := vars["bookingid"]
|
||||
|
||||
if h.services == nil || (h.services.GRPC == services.GRPCServices{}) || h.services.GRPC.Diags == nil {
|
||||
log.Error().Msg("Diags service is not initialized")
|
||||
http.Error(w, "Internal server error", http.StatusInternalServerError)
|
||||
return
|
||||
}
|
||||
|
||||
|
||||
if r.Method == http.MethodPost {
|
||||
g := r.Context().Value(identification.GroupKey)
|
||||
if g == nil {
|
||||
http.Error(w, "Missing group information", http.StatusBadRequest)
|
||||
return
|
||||
}
|
||||
|
||||
diagForm, err := parseDiagsForm(r)
|
||||
if err != nil {
|
||||
log.Error().Err(err).Msg("Invalid form data")
|
||||
http.Error(w, err.Error(), http.StatusBadRequest)
|
||||
return
|
||||
}
|
||||
|
||||
log.Debug().Interface("diagForm", diagForm).Msg("Form data parsed")
|
||||
|
||||
data, err := structpb.NewStruct(map[string]any{
|
||||
"booking": bookingID,
|
||||
})
|
||||
if err != nil {
|
||||
log.Error().Err(err).Msg("Failed to create protobuf struct")
|
||||
w.WriteHeader(http.StatusInternalServerError)
|
||||
return
|
||||
}
|
||||
|
||||
group := g.(storage.Group)
|
||||
|
||||
request := &diags.CreateDiagRequest{
|
||||
Diag: &diags.Diag{
|
||||
Name: diagForm.Name,
|
||||
Namespace: diagForm.Namespace,
|
||||
JsonSchema: diagForm.JsonSchema,
|
||||
UiSchema: diagForm.UiSchema,
|
||||
Data: data,
|
||||
Deleted: diagForm.Deleted,
|
||||
Diagdate: timestamppb.New(time.Now()),
|
||||
Owners: []string{group.ID},
|
||||
},
|
||||
}
|
||||
|
||||
resp, err := h.services.GRPC.Diags.CreateDiag(context.TODO(), request)
|
||||
if err != nil {
|
||||
log.Error().Err(err).Msg("Failed to create diagnostic")
|
||||
w.WriteHeader(http.StatusInternalServerError)
|
||||
return
|
||||
}
|
||||
|
||||
http.Redirect(w, r, fmt.Sprintf("/app/diags/%s", resp.Diag.Id), http.StatusFound)
|
||||
return
|
||||
}
|
||||
|
||||
h.Renderer.BookingsCreateDiag(w, r, bookingID)
|
||||
}
|
||||
|
||||
func (h *ApplicationHandler) VehicleBookingsCreateDiag(w http.ResponseWriter, r *http.Request) {
|
||||
vars := mux.Vars(r)
|
||||
bookingID := vars["bookingid"]
|
||||
|
||||
if h.services == nil || (h.services.GRPC == services.GRPCServices{}) || h.services.GRPC.Diags == nil {
|
||||
log.Error().Msg("Diags service is not initialized")
|
||||
http.Error(w, "Internal server error", http.StatusInternalServerError)
|
||||
return
|
||||
}
|
||||
|
||||
|
||||
if r.Method == http.MethodPost {
|
||||
g := r.Context().Value(identification.GroupKey)
|
||||
if g == nil {
|
||||
http.Error(w, "Missing group information", http.StatusBadRequest)
|
||||
return
|
||||
}
|
||||
|
||||
diagForm, err := parseDiagsForm(r)
|
||||
if err != nil {
|
||||
log.Error().Err(err).Msg("Invalid form data")
|
||||
http.Error(w, err.Error(), http.StatusBadRequest)
|
||||
return
|
||||
}
|
||||
|
||||
log.Debug().Interface("diagForm", diagForm).Msg("Form data parsed")
|
||||
|
||||
data, err := structpb.NewStruct(map[string]any{
|
||||
"booking": bookingID,
|
||||
})
|
||||
if err != nil {
|
||||
log.Error().Err(err).Msg("Failed to create protobuf struct")
|
||||
w.WriteHeader(http.StatusInternalServerError)
|
||||
return
|
||||
}
|
||||
|
||||
group := g.(storage.Group)
|
||||
|
||||
request := &diags.CreateDiagRequest{
|
||||
Diag: &diags.Diag{
|
||||
Name: diagForm.Name,
|
||||
Namespace: diagForm.Namespace,
|
||||
JsonSchema: diagForm.JsonSchema,
|
||||
UiSchema: diagForm.UiSchema,
|
||||
Data: data,
|
||||
Deleted: diagForm.Deleted,
|
||||
Diagdate: timestamppb.New(time.Now()),
|
||||
Owners: []string{group.ID},
|
||||
},
|
||||
}
|
||||
|
||||
resp, err := h.services.GRPC.Diags.CreateDiag(context.TODO(), request)
|
||||
if err != nil {
|
||||
log.Error().Err(err).Msg("Failed to create diagnostic")
|
||||
w.WriteHeader(http.StatusInternalServerError)
|
||||
return
|
||||
}
|
||||
|
||||
http.Redirect(w, r, fmt.Sprintf("/app/diags/%s", resp.Diag.Id), http.StatusFound)
|
||||
return
|
||||
}
|
||||
|
||||
h.Renderer.VehicleBookingsCreateDiag(w, r, bookingID)
|
||||
}
|
||||
|
||||
func (h *ApplicationHandler) DiagsDisplayDiag(w http.ResponseWriter, r *http.Request) {
|
||||
vars := mux.Vars(r)
|
||||
diagid := vars["diagid"]
|
||||
|
||||
request := &diags.GetDiagRequest{
|
||||
Id: diagid,
|
||||
}
|
||||
|
||||
resp, err := h.services.GRPC.Diags.GetDiag(context.TODO(), request)
|
||||
if err != nil {
|
||||
log.Error().Err(err).Msg("")
|
||||
w.WriteHeader(http.StatusInternalServerError)
|
||||
return
|
||||
}
|
||||
|
||||
g := r.Context().Value(identification.GroupKey)
|
||||
if g == nil {
|
||||
log.Error().Err(err).Msg("")
|
||||
w.WriteHeader(http.StatusInternalServerError)
|
||||
return
|
||||
}
|
||||
|
||||
|
||||
documents := h.filestorage.List(filestorage.PREFIX_DIAGS + "/" + diagid)
|
||||
|
||||
events_file_types := h.config.GetStringSlice("modules.diags.documents_types")
|
||||
file_types_map := h.config.GetStringMapString("storage.files.file_types")
|
||||
|
||||
h.Renderer.DiagsDisplayDiag(w, r, resp.Diag.ToStorageType(), events_file_types, file_types_map, documents)
|
||||
}
|
||||
|
||||
func parseDiagsForm(r *http.Request) (*DiagsForm, error) {
|
||||
if err := r.ParseForm(); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
|
||||
formData := &DiagsForm{
|
||||
Name: r.PostFormValue("name"),
|
||||
Namespace: r.PostFormValue("namespace"), // Récupère le namespace
|
||||
JsonSchema: r.PostFormValue("json_schema"),
|
||||
UiSchema: r.PostFormValue("ui_schema"),
|
||||
Deleted: false,
|
||||
}
|
||||
|
||||
if formData.Name == "" || formData.Namespace == "" {
|
||||
return nil, errors.New("missing required fields: 'name' or 'namespace'")
|
||||
}
|
||||
|
||||
// Gestion de la valeur JSON dans `data`
|
||||
if rawData := r.PostFormValue("data"); rawData != "" {
|
||||
data := map[string]any{}
|
||||
if err := json.Unmarshal([]byte(rawData), &data); err != nil {
|
||||
return nil, errors.New("invalid 'data' field: must be a valid JSON object")
|
||||
}
|
||||
formData.Data = data
|
||||
}
|
||||
|
||||
return formData, nil
|
||||
}
|
||||
|
||||
func (h *ApplicationHandler) DiagUpdate(w http.ResponseWriter, r *http.Request) {
|
||||
adm := strings.Split(r.URL.Path, "/")
|
||||
diagID := adm[3]
|
||||
request := &diags.GetDiagRequest{
|
||||
Id: diagID,
|
||||
}
|
||||
|
||||
resp, err := h.services.GRPC.Diags.GetDiag(context.TODO(), request)
|
||||
if err != nil {
|
||||
log.Error().Err(err).Msg("")
|
||||
w.WriteHeader(http.StatusInternalServerError)
|
||||
return
|
||||
}
|
||||
if r.Method == "POST" {
|
||||
g := r.Context().Value(identification.GroupKey)
|
||||
if g == nil {
|
||||
w.WriteHeader(http.StatusBadRequest)
|
||||
return
|
||||
}
|
||||
|
||||
group := g.(storage.Group)
|
||||
|
||||
diagForm, err := parseDiagsForm(r)
|
||||
if err != nil {
|
||||
log.Error().Err(err).Msg("")
|
||||
w.WriteHeader(http.StatusBadRequest)
|
||||
return
|
||||
}
|
||||
|
||||
data, _ := structpb.NewStruct(map[string]any{})
|
||||
|
||||
request := &diags.UpdateDiagRequest{
|
||||
Diag: &diags.Diag{
|
||||
Namespace: diagForm.Namespace,
|
||||
Id: diagID,
|
||||
Name: diagForm.Name,
|
||||
JsonSchema: diagForm.JsonSchema,
|
||||
UiSchema: diagForm.UiSchema,
|
||||
Data: data,
|
||||
Diagdate: timestamppb.New(time.Now()),
|
||||
Owners: []string{group.ID},
|
||||
},
|
||||
}
|
||||
|
||||
resp, err := h.services.GRPC.Diags.UpdateDiag(context.TODO(), request)
|
||||
|
||||
if err != nil {
|
||||
log.Error().Err(err).Msg("")
|
||||
w.WriteHeader(http.StatusInternalServerError)
|
||||
return
|
||||
}
|
||||
|
||||
http.Redirect(w, r, fmt.Sprintf("/app/diags/%s", resp.Diag.Id), http.StatusFound)
|
||||
return
|
||||
}
|
||||
h.Renderer.DiagUpdate(w, r, resp.Diag.ToStorageType())
|
||||
}
|
||||
|
||||
func (h *ApplicationHandler) DiagDelete(w http.ResponseWriter, r *http.Request) {
|
||||
|
||||
vars := mux.Vars(r)
|
||||
diagID := vars["diagid"]
|
||||
request := &diags.GetDiagRequest{
|
||||
Id: diagID,
|
||||
}
|
||||
|
||||
resp, err := h.services.GRPC.Diags.GetDiag(context.TODO(), request)
|
||||
if err != nil {
|
||||
log.Error().Err(err).Msg("")
|
||||
w.WriteHeader(http.StatusInternalServerError)
|
||||
return
|
||||
}
|
||||
|
||||
if r.Method == "POST" {
|
||||
|
||||
request := &diags.UpdateDiagRequest{
|
||||
Diag: &diags.Diag{
|
||||
Namespace: resp.Diag.Namespace,
|
||||
Id: resp.Diag.Id,
|
||||
Name: resp.Diag.Name,
|
||||
JsonSchema: resp.Diag.JsonSchema,
|
||||
UiSchema: resp.Diag.UiSchema,
|
||||
Data: resp.Diag.Data,
|
||||
Deleted: true,
|
||||
Diagdate: resp.Diag.Diagdate,
|
||||
},
|
||||
}
|
||||
|
||||
_, err := h.services.GRPC.Diags.UpdateDiag(context.TODO(), request)
|
||||
|
||||
if err != nil {
|
||||
log.Error().Err(err).Msg("")
|
||||
w.WriteHeader(http.StatusInternalServerError)
|
||||
return
|
||||
}
|
||||
|
||||
http.Redirect(w, r, "/app/diags/", http.StatusFound)
|
||||
return
|
||||
}
|
||||
h.Renderer.DiagDelete(w, r, resp.Diag.ToStorageType())
|
||||
}
|
||||
|
||||
func (h *ApplicationHandler) DiagsHistoryDiag(w http.ResponseWriter, r *http.Request) {
|
||||
vars := mux.Vars(r)
|
||||
diagId := vars["diagid"]
|
||||
request := &diags.GetDiagRequest{
|
||||
Id: diagId,
|
||||
}
|
||||
|
||||
resp, err := h.services.GRPC.Diags.GetDiag(context.TODO(), request)
|
||||
if err != nil {
|
||||
log.Error().Err(err).Msg("")
|
||||
w.WriteHeader(http.StatusInternalServerError)
|
||||
return
|
||||
}
|
||||
|
||||
h.Renderer.DiagsHistoryDiag(w, r, resp.Diag.ToStorageType())
|
||||
}
|
||||
|
||||
// //// ADD DOCUMENTS //////
|
||||
func (h *ApplicationHandler) DiagsDocuments(w http.ResponseWriter, r *http.Request) {
|
||||
vars := mux.Vars(r)
|
||||
diagID := vars["diagid"]
|
||||
|
||||
//r.ParseForm()
|
||||
r.ParseMultipartForm(100 * 1024 * 1024)
|
||||
|
||||
document_type := r.FormValue("type")
|
||||
document_name := r.FormValue("name")
|
||||
|
||||
file, header, err := r.FormFile("file-upload")
|
||||
if err != nil {
|
||||
log.Error().Err(err).Msg("")
|
||||
return
|
||||
}
|
||||
defer file.Close()
|
||||
|
||||
fileid := uuid.NewString()
|
||||
|
||||
metadata := map[string]string{
|
||||
"type": document_type,
|
||||
"name": document_name,
|
||||
}
|
||||
|
||||
if err := h.filestorage.Put(file, filestorage.PREFIX_DIAGS, fmt.Sprintf("%s/%s_%s", diagID, fileid, header.Filename), header.Size, metadata); err != nil {
|
||||
log.Error().Err(err).Msg("")
|
||||
w.WriteHeader(http.StatusInternalServerError)
|
||||
return
|
||||
}
|
||||
|
||||
http.Redirect(w, r, fmt.Sprintf("/app/diags/%s", diagID), http.StatusFound)
|
||||
|
||||
}
|
||||
|
||||
func (h *ApplicationHandler) DiagsDocumentDownload(w http.ResponseWriter, r *http.Request) {
|
||||
vars := mux.Vars(r)
|
||||
diagID := vars["diagid"]
|
||||
document := vars["document"]
|
||||
|
||||
file, info, err := h.filestorage.Get(filestorage.PREFIX_DIAGS, fmt.Sprintf("%s/%s", diagID, document))
|
||||
if err != nil {
|
||||
log.Error().Err(err).Msg("")
|
||||
w.WriteHeader(http.StatusInternalServerError)
|
||||
return
|
||||
}
|
||||
|
||||
w.Header().Set("Content-Type", info.ContentType)
|
||||
if _, err = io.Copy(w, file); err != nil {
|
||||
log.Error().Err(err).Msg("")
|
||||
w.WriteHeader(http.StatusInternalServerError)
|
||||
return
|
||||
}
|
||||
|
||||
http.Redirect(w, r, fmt.Sprintf("/app/diags/%s", diagID), http.StatusFound)
|
||||
|
||||
}
|
||||
@@ -1,7 +0,0 @@
|
||||
package application
|
||||
|
||||
import "net/http"
|
||||
|
||||
func (h *ApplicationHandler) DirectoryHome(w http.ResponseWriter, r *http.Request) {
|
||||
h.Renderer.DirectoryHome(w, r)
|
||||
}
|
||||
@@ -1,130 +0,0 @@
|
||||
package application
|
||||
|
||||
import (
|
||||
"context"
|
||||
"crypto/rand"
|
||||
"encoding/base64"
|
||||
"io"
|
||||
"net/http"
|
||||
"time"
|
||||
|
||||
"git.coopgo.io/coopgo-apps/parcoursmob/utils/identification"
|
||||
"git.coopgo.io/coopgo-platform/groups-management/storage"
|
||||
accounts "git.coopgo.io/coopgo-platform/mobility-accounts/grpcapi"
|
||||
"github.com/rs/zerolog/log"
|
||||
)
|
||||
|
||||
func (h *ApplicationHandler) GroupSettingsDisplay(w http.ResponseWriter, r *http.Request) {
|
||||
g := r.Context().Value(identification.GroupKey)
|
||||
if g == nil {
|
||||
w.WriteHeader(http.StatusBadRequest)
|
||||
return
|
||||
}
|
||||
|
||||
group := g.(storage.Group)
|
||||
|
||||
members, err := h.members()
|
||||
if err != nil {
|
||||
if err != nil {
|
||||
log.Error().Err(err).Msg("")
|
||||
w.WriteHeader(http.StatusInternalServerError)
|
||||
return
|
||||
}
|
||||
}
|
||||
|
||||
admins := []any{}
|
||||
groupMembers := []any{}
|
||||
|
||||
for _, m := range members {
|
||||
mm := m.ToStorageType()
|
||||
for _, g := range mm.Data["groups"].([]any) {
|
||||
if g.(string) == group.ID {
|
||||
groupMembers = append(groupMembers, mm)
|
||||
}
|
||||
if g.(string) == group.ID+":admin" {
|
||||
admins = append(admins, mm)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
h.Renderer.GroupSettingsDisplay(w, r, group, groupMembers, admins)
|
||||
}
|
||||
|
||||
func (h *ApplicationHandler) GroupSettingsInviteMember(w http.ResponseWriter, r *http.Request) {
|
||||
g := r.Context().Value(identification.GroupKey)
|
||||
if g == nil {
|
||||
w.WriteHeader(http.StatusBadRequest)
|
||||
return
|
||||
}
|
||||
|
||||
group := g.(storage.Group)
|
||||
|
||||
r.ParseForm()
|
||||
|
||||
accountresp, err := h.services.GRPC.MobilityAccounts.GetAccountUsername(context.TODO(), &accounts.GetAccountUsernameRequest{
|
||||
Username: r.FormValue("username"),
|
||||
Namespace: "parcoursmob",
|
||||
})
|
||||
|
||||
if err == nil {
|
||||
// Account already exists : adding the existing account to admin list
|
||||
account := accountresp.Account.ToStorageType()
|
||||
//account.Data["groups"] = append(account.Data["groups"].([]any), groupid, groupid)
|
||||
account.Data["groups"] = append(account.Data["groups"].([]any), group.ID)
|
||||
|
||||
as, _ := accounts.AccountFromStorageType(&account)
|
||||
|
||||
_, err = h.services.GRPC.MobilityAccounts.UpdateData(
|
||||
context.TODO(),
|
||||
&accounts.UpdateDataRequest{
|
||||
Account: as,
|
||||
},
|
||||
)
|
||||
|
||||
if err != nil {
|
||||
log.Error().Err(err).Msg("")
|
||||
}
|
||||
|
||||
data := map[string]any{
|
||||
"group": group.Data["name"],
|
||||
}
|
||||
|
||||
if err := h.emailing.Send("onboarding.existing_member", r.FormValue("username"), data); err != nil {
|
||||
log.Error().Err(err).Msg("")
|
||||
}
|
||||
|
||||
http.Redirect(w, r, "/app/group/settings", http.StatusFound)
|
||||
return
|
||||
} else {
|
||||
// Onboard now administrator
|
||||
onboarding := map[string]any{
|
||||
"username": r.FormValue("username"),
|
||||
"group": group.ID,
|
||||
"admin": false,
|
||||
}
|
||||
|
||||
b := make([]byte, 16)
|
||||
if _, err := io.ReadFull(rand.Reader, b); err != nil {
|
||||
log.Error().Err(err).Msg("")
|
||||
w.WriteHeader(http.StatusInternalServerError)
|
||||
return
|
||||
}
|
||||
key := base64.RawURLEncoding.EncodeToString(b)
|
||||
|
||||
h.cache.PutWithTTL("onboarding/"+key, onboarding, 72*time.Hour)
|
||||
|
||||
data := map[string]any{
|
||||
"group": group.Data["name"],
|
||||
"key": key,
|
||||
}
|
||||
|
||||
if err := h.emailing.Send("onboarding.new_member", r.FormValue("username"), data); err != nil {
|
||||
log.Error().Err(err).Msg("")
|
||||
w.WriteHeader(http.StatusInternalServerError)
|
||||
return
|
||||
}
|
||||
}
|
||||
|
||||
http.Redirect(w, r, "/app/group/settings", http.StatusFound)
|
||||
return
|
||||
}
|
||||
@@ -1,220 +0,0 @@
|
||||
package application
|
||||
|
||||
import (
|
||||
"context"
|
||||
"encoding/json"
|
||||
"fmt"
|
||||
"net/http"
|
||||
"sort"
|
||||
"strings"
|
||||
"time"
|
||||
|
||||
groupsmanagement "git.coopgo.io/coopgo-platform/groups-management/grpcapi"
|
||||
groupstorage "git.coopgo.io/coopgo-platform/groups-management/storage"
|
||||
mobilityaccounts "git.coopgo.io/coopgo-platform/mobility-accounts/grpcapi"
|
||||
"github.com/google/uuid"
|
||||
"github.com/gorilla/mux"
|
||||
"github.com/rs/zerolog/log"
|
||||
"google.golang.org/protobuf/types/known/structpb"
|
||||
)
|
||||
|
||||
var Addres any
|
||||
|
||||
type BeneficiariesGroupForm struct {
|
||||
FirstName string `json:"first_name" validate:"required"`
|
||||
LastName string `json:"last_name" validate:"required"`
|
||||
Email string `json:"email" validate:"required,email"`
|
||||
Birthdate *time.Time `json:"birthdate"`
|
||||
PhoneNumber string `json:"phone_number" validate:"required,phoneNumber"`
|
||||
Address any `json:"address,omitempty"`
|
||||
Gender string `json:"gender"`
|
||||
}
|
||||
|
||||
type GroupsModuleByName []groupstorage.Group
|
||||
|
||||
func (a GroupsModuleByName) Len() int { return len(a) }
|
||||
func (a GroupsModuleByName) Less(i, j int) bool {
|
||||
return strings.Compare(a[i].Data["name"].(string), a[j].Data["name"].(string)) < 0
|
||||
}
|
||||
func (a GroupsModuleByName) Swap(i, j int) { a[i], a[j] = a[j], a[i] }
|
||||
|
||||
func (h *ApplicationHandler) Groups(w http.ResponseWriter, r *http.Request) {
|
||||
|
||||
request := &groupsmanagement.GetGroupsRequest{
|
||||
Namespaces: []string{"parcoursmob_groups"},
|
||||
}
|
||||
|
||||
resp, err := h.services.GRPC.GroupsManagement.GetGroups(context.TODO(), request)
|
||||
if err != nil {
|
||||
log.Error().Err(err).Msg("")
|
||||
w.WriteHeader(http.StatusInternalServerError)
|
||||
return
|
||||
}
|
||||
|
||||
var groups = []groupstorage.Group{}
|
||||
|
||||
for _, group := range resp.Groups {
|
||||
g := group.ToStorageType()
|
||||
groups = append(groups, g)
|
||||
}
|
||||
|
||||
sort.Sort(GroupsModuleByName(groups))
|
||||
|
||||
h.Renderer.Groups(w, r, groups)
|
||||
}
|
||||
|
||||
func (h *ApplicationHandler) CreateGroupModule(w http.ResponseWriter, r *http.Request) {
|
||||
if r.Method == "POST" {
|
||||
if r.PostFormValue("address") != "" {
|
||||
var a any
|
||||
json.Unmarshal([]byte(r.PostFormValue("address")), &a)
|
||||
|
||||
Addres = a
|
||||
}
|
||||
r.ParseForm()
|
||||
|
||||
if r.FormValue("name") == "" {
|
||||
log.Error().Msg("Invalid name")
|
||||
w.WriteHeader(http.StatusBadRequest)
|
||||
return
|
||||
}
|
||||
if r.FormValue("type") == "" {
|
||||
log.Error().Msg("Invalid type")
|
||||
w.WriteHeader(http.StatusBadRequest)
|
||||
return
|
||||
}
|
||||
|
||||
groupid := uuid.NewString()
|
||||
|
||||
dataMap := map[string]any{
|
||||
"name": r.FormValue("name"),
|
||||
"type": r.FormValue("type"),
|
||||
"description": r.FormValue("description"),
|
||||
"address": Addres,
|
||||
}
|
||||
|
||||
data, err := structpb.NewValue(dataMap)
|
||||
if err != nil {
|
||||
log.Error().Err(err).Msg("")
|
||||
w.WriteHeader(http.StatusInternalServerError)
|
||||
return
|
||||
}
|
||||
|
||||
request_organization := &groupsmanagement.AddGroupRequest{
|
||||
Group: &groupsmanagement.Group{
|
||||
Id: groupid,
|
||||
Namespace: "parcoursmob_groups",
|
||||
Data: data.GetStructValue(),
|
||||
},
|
||||
}
|
||||
|
||||
_, err = h.services.GRPC.GroupsManagement.AddGroup(context.TODO(), request_organization)
|
||||
if err != nil {
|
||||
log.Error().Err(err).Msg("")
|
||||
w.WriteHeader(http.StatusInternalServerError)
|
||||
return
|
||||
}
|
||||
|
||||
http.Redirect(w, r, fmt.Sprintf("/app/group_module/groups/%s", groupid), http.StatusFound)
|
||||
return
|
||||
}
|
||||
group_types := h.config.GetStringSlice("modules.groups.group_types")
|
||||
h.Renderer.CreateGroupModule(w, r, group_types)
|
||||
}
|
||||
|
||||
func filterAcccount(r *http.Request, a *mobilityaccounts.Account) bool {
|
||||
searchFilter, ok := r.URL.Query()["search"]
|
||||
|
||||
if ok && len(searchFilter[0]) > 0 {
|
||||
name := a.Data.AsMap()["first_name"].(string) + " " + a.Data.AsMap()["last_name"].(string)
|
||||
if !strings.Contains(strings.ToLower(name), strings.ToLower(searchFilter[0])) {
|
||||
return false
|
||||
}
|
||||
}
|
||||
|
||||
return true
|
||||
}
|
||||
func (h *ApplicationHandler) DisplayGroupModule(w http.ResponseWriter, r *http.Request) {
|
||||
vars := mux.Vars(r)
|
||||
groupid := vars["groupid"]
|
||||
|
||||
request := &groupsmanagement.GetGroupRequest{
|
||||
Id: groupid,
|
||||
}
|
||||
|
||||
resp, err := h.services.GRPC.GroupsManagement.GetGroup(context.TODO(), request)
|
||||
if err != nil {
|
||||
log.Error().Err(err).Msg("")
|
||||
w.WriteHeader(http.StatusInternalServerError)
|
||||
return
|
||||
}
|
||||
|
||||
var accounts = []any{}
|
||||
|
||||
requesst := &mobilityaccounts.GetAccountsBatchRequest{
|
||||
Accountids: resp.Group.Members,
|
||||
}
|
||||
|
||||
ressp, _ := h.services.GRPC.MobilityAccounts.GetAccountsBatch(context.TODO(), requesst)
|
||||
// if err != nil {
|
||||
// return err
|
||||
// }
|
||||
for _, account := range ressp.Accounts {
|
||||
if filterAcccount(r, account) {
|
||||
a := account.ToStorageType()
|
||||
accounts = append(accounts, a)
|
||||
}
|
||||
}
|
||||
|
||||
cacheid := uuid.NewString()
|
||||
h.cache.PutWithTTL(cacheid, accounts, 1*time.Hour)
|
||||
r.ParseForm()
|
||||
|
||||
var beneficiary any
|
||||
|
||||
searched := false
|
||||
|
||||
// if r.Method == "POST" {
|
||||
if r.FormValue("beneficiaryid") != "" {
|
||||
// Handler form
|
||||
searched = true
|
||||
|
||||
requestbeneficiary := &mobilityaccounts.GetAccountRequest{
|
||||
Id: r.FormValue("beneficiaryid"),
|
||||
}
|
||||
|
||||
respbeneficiary, err := h.services.GRPC.MobilityAccounts.GetAccount(context.TODO(), requestbeneficiary)
|
||||
if err != nil {
|
||||
log.Error().Err(err).Msg("")
|
||||
w.WriteHeader(http.StatusInternalServerError)
|
||||
return
|
||||
}
|
||||
|
||||
beneficiary = respbeneficiary.Account.ToStorageType()
|
||||
|
||||
subscribe := &groupsmanagement.SubscribeRequest{
|
||||
Groupid: resp.Group.ToStorageType().ID,
|
||||
Memberid: respbeneficiary.Account.Id,
|
||||
}
|
||||
|
||||
_, err = h.services.GRPC.GroupsManagement.Subscribe(context.TODO(), subscribe)
|
||||
|
||||
if err != nil {
|
||||
log.Error().Err(err).Msg("")
|
||||
w.WriteHeader(http.StatusInternalServerError)
|
||||
return
|
||||
}
|
||||
|
||||
http.Redirect(w, r, fmt.Sprintf("/app/group_module/groups/%s", resp.Group.ToStorageType().ID), http.StatusFound)
|
||||
return
|
||||
}
|
||||
|
||||
accountsBeneficaire, err := h.beneficiaries(r)
|
||||
if err != nil {
|
||||
log.Error().Err(err).Msg("")
|
||||
w.WriteHeader(http.StatusBadRequest)
|
||||
return
|
||||
}
|
||||
//h.Renderer.BeneficaireSearch(w, r, accounts, searched, beneficiary, resp.Group.ToStorageType())
|
||||
h.Renderer.DisplayGroupModule(w, r, resp.Group.ToStorageType().ID, accounts, cacheid, searched, beneficiary, resp.Group.ToStorageType(), accountsBeneficaire)
|
||||
}
|
||||
@@ -1,582 +0,0 @@
|
||||
package application
|
||||
|
||||
import (
|
||||
"context"
|
||||
"encoding/json"
|
||||
"fmt"
|
||||
"net/http"
|
||||
"sort"
|
||||
"strconv"
|
||||
"strings"
|
||||
"time"
|
||||
|
||||
fleets "git.coopgo.io/coopgo-platform/fleets/grpcapi"
|
||||
groupsmanagement "git.coopgo.io/coopgo-platform/groups-management/grpcapi"
|
||||
groupstorage "git.coopgo.io/coopgo-platform/groups-management/storage"
|
||||
mobilityaccounts "git.coopgo.io/coopgo-platform/mobility-accounts/grpcapi"
|
||||
"github.com/google/uuid"
|
||||
"github.com/gorilla/mux"
|
||||
geojson "github.com/paulmach/go.geojson"
|
||||
"github.com/rs/zerolog/log"
|
||||
"gitlab.scity.coop/maas/navitia-golang"
|
||||
"gitlab.scity.coop/maas/navitia-golang/types"
|
||||
"google.golang.org/protobuf/types/known/structpb"
|
||||
)
|
||||
|
||||
var Depart any
|
||||
var Arrive any
|
||||
|
||||
func (h *ApplicationHandler) JourneysSearch(w http.ResponseWriter, r *http.Request) {
|
||||
r.ParseForm()
|
||||
var (
|
||||
journeys_results *navitia.JourneyResults
|
||||
carpool_results any
|
||||
vehicle_results []any
|
||||
)
|
||||
vehiclech := make(chan []any, 1)
|
||||
navitiaCh := make(chan *navitia.JourneyResults, 1)
|
||||
carpoolCh := make(chan any, 1)
|
||||
locTime, errTime := time.LoadLocation("Europe/Paris")
|
||||
if errTime != nil {
|
||||
log.Panic().Err(errTime).Msg("Tried to load timezone location Europe/Paris. Error. Missing zones in container ?")
|
||||
}
|
||||
|
||||
departuredate := r.FormValue("departuredate")
|
||||
departuretime := r.FormValue("departuretime")
|
||||
departuredatetime, _ := time.ParseInLocation("2006-01-02 15:04", fmt.Sprintf("%s %s", departuredate, departuretime), locTime)
|
||||
|
||||
departure := r.FormValue("departure")
|
||||
destination := r.FormValue("destination")
|
||||
|
||||
searched := false
|
||||
|
||||
var (
|
||||
departuregeo *geojson.Feature
|
||||
destinationgeo *geojson.Feature
|
||||
journeys *navitia.JourneyResults
|
||||
carpoolresults any
|
||||
vehicles = []any{}
|
||||
)
|
||||
|
||||
if departuredate != "" && departuretime != "" && departure != "" && destination != "" {
|
||||
searched = true
|
||||
|
||||
var err error
|
||||
|
||||
departuregeo, err = geojson.UnmarshalFeature([]byte(departure))
|
||||
if err != nil {
|
||||
log.Error().Err(err).Msg("")
|
||||
w.WriteHeader(http.StatusBadRequest)
|
||||
return
|
||||
}
|
||||
|
||||
destinationgeo, err = geojson.UnmarshalFeature([]byte(destination))
|
||||
if err != nil {
|
||||
log.Error().Err(err).Msg("")
|
||||
w.WriteHeader(http.StatusBadRequest)
|
||||
return
|
||||
}
|
||||
////////////////////////////////////////////////////////////////////////////////////////////////////////////////
|
||||
journeysRequest := func() {
|
||||
//TODO make it a library
|
||||
session, _ := navitia.NewCustom(
|
||||
h.config.GetString("services.navitia.api_key"),
|
||||
"https://api.navitia.io/v1",
|
||||
&http.Client{})
|
||||
if err != nil {
|
||||
log.Error().Err(err).Msg("")
|
||||
w.WriteHeader(http.StatusBadRequest)
|
||||
navitiaCh <- nil
|
||||
return
|
||||
}
|
||||
|
||||
request := navitia.JourneyRequest{
|
||||
From: types.ID(fmt.Sprintf("%f", departuregeo.Geometry.Point[0]) + ";" + fmt.Sprintf("%f", departuregeo.Geometry.Point[1])),
|
||||
To: types.ID(fmt.Sprintf("%f", destinationgeo.Geometry.Point[0]) + ";" + fmt.Sprintf("%f", destinationgeo.Geometry.Point[1])),
|
||||
Date: departuredatetime.Add(-2 * time.Hour),
|
||||
DateIsArrival: false, //TODO
|
||||
}
|
||||
|
||||
journeys, err = session.Journeys(context.Background(), request)
|
||||
if err != nil {
|
||||
log.Error().Err(err).Msg("")
|
||||
// w.WriteHeader(http.StatusBadRequest)
|
||||
// return
|
||||
}
|
||||
navitiaCh <- journeys
|
||||
|
||||
}
|
||||
////////////////////////////////////////////////////////////////////////////////////////////////////////////////
|
||||
//CARPOOL
|
||||
carpoolRequest := func() {
|
||||
carpoolrequest := "https://api.rdex.ridygo.fr/journeys.json"
|
||||
|
||||
client := &http.Client{}
|
||||
req, err := http.NewRequest("GET", carpoolrequest, nil)
|
||||
if err != nil {
|
||||
log.Error().Err(err).Msg("")
|
||||
}
|
||||
|
||||
req.URL.RawQuery = fmt.Sprintf(
|
||||
"p[driver][state]=1&frequency=punctual&p[passenger][state]=0&p[from][latitude]=%f&p[from][longitude]=%f&p[to][latitude]=%f&p[to][longitude]=%f&p[outward][mindate]=%s&p[outward][maxdate]=%s",
|
||||
departuregeo.Geometry.Point[1], departuregeo.Geometry.Point[0],
|
||||
destinationgeo.Geometry.Point[1], destinationgeo.Geometry.Point[0],
|
||||
departuredatetime.Format("2006-01-02"), departuredatetime.Format("2006-01-02"))
|
||||
|
||||
req.Header.Set("X-API-KEY", "123456")
|
||||
resp, err := client.Do(req)
|
||||
if err != nil {
|
||||
log.Error().Err(err).Msg("")
|
||||
}
|
||||
|
||||
if err == nil && resp.StatusCode == http.StatusOK {
|
||||
err = json.NewDecoder(resp.Body).Decode(&carpoolresults)
|
||||
if err != nil {
|
||||
log.Error().Err(err).Msg("")
|
||||
}
|
||||
|
||||
if carpoolresults == nil {
|
||||
carpoolresults = []any{}
|
||||
}
|
||||
} else {
|
||||
carpoolresults = []any{}
|
||||
}
|
||||
carpoolCh <- carpoolresults
|
||||
}
|
||||
////////////////////////////////////////////////////////////////////////////////////////////////////////////////
|
||||
// Vehicles
|
||||
vehicleRequest := func() {
|
||||
vehiclerequest := &fleets.GetVehiclesRequest{
|
||||
Namespaces: []string{"parcoursmob"},
|
||||
}
|
||||
vehicleresp, err := h.services.GRPC.Fleets.GetVehicles(context.TODO(), vehiclerequest)
|
||||
if err != nil {
|
||||
log.Error().Err(err).Msg("")
|
||||
w.WriteHeader(http.StatusInternalServerError)
|
||||
}
|
||||
for _, vehicle := range vehicleresp.Vehicles {
|
||||
v := vehicle.ToStorageType()
|
||||
if v.Free(departuredatetime.Add(-24*time.Hour), departuredatetime.Add(168*time.Hour)) {
|
||||
vehicles = append(vehicles, v)
|
||||
}
|
||||
}
|
||||
vehiclech <- vehicles
|
||||
}
|
||||
go journeysRequest()
|
||||
go carpoolRequest()
|
||||
go vehicleRequest()
|
||||
carpool_results = <-carpoolCh
|
||||
journeys_results = <-navitiaCh
|
||||
vehicle_results = <-vehiclech
|
||||
}
|
||||
|
||||
h.Renderer.JourneysSearch(w, r, carpool_results, journeys_results, vehicle_results, searched, departuregeo, destinationgeo, departuredate, departuretime)
|
||||
}
|
||||
|
||||
type GroupsModule []groupstorage.Group
|
||||
|
||||
func (a GroupsModule) Len() int { return len(a) }
|
||||
func (a GroupsModule) Less(i, j int) bool {
|
||||
return strings.Compare(a[i].Data["name"].(string), a[j].Data["name"].(string)) < 0
|
||||
}
|
||||
func (a GroupsModule) Swap(i, j int) { a[i], a[j] = a[j], a[i] }
|
||||
|
||||
func (h *ApplicationHandler) GroupsGestion(w http.ResponseWriter, r *http.Request) {
|
||||
|
||||
request := &groupsmanagement.GetGroupsRequest{
|
||||
Namespaces: []string{"parcoursmob_groups_covoiturage"},
|
||||
}
|
||||
|
||||
resp, err := h.services.GRPC.GroupsManagement.GetGroups(context.TODO(), request)
|
||||
if err != nil {
|
||||
log.Error().Err(err).Msg("")
|
||||
w.WriteHeader(http.StatusInternalServerError)
|
||||
return
|
||||
}
|
||||
|
||||
var groups = []groupstorage.Group{}
|
||||
|
||||
for _, group := range resp.Groups {
|
||||
g := group.ToStorageType()
|
||||
groups = append(groups, g)
|
||||
}
|
||||
|
||||
cacheid := uuid.NewString()
|
||||
|
||||
sort.Sort(GroupsModule(groups))
|
||||
h.cache.PutWithTTL(cacheid, groups, 1*time.Hour)
|
||||
|
||||
h.Renderer.GroupsGestion(w, r, groups, cacheid)
|
||||
}
|
||||
func filterAcc(r *http.Request, a *mobilityaccounts.Account) bool {
|
||||
searchFilter, ok := r.URL.Query()["search"]
|
||||
|
||||
if ok && len(searchFilter[0]) > 0 {
|
||||
name := a.Data.AsMap()["first_name"].(string) + " " + a.Data.AsMap()["last_name"].(string)
|
||||
if !strings.Contains(strings.ToLower(name), strings.ToLower(searchFilter[0])) {
|
||||
return false
|
||||
}
|
||||
}
|
||||
|
||||
return true
|
||||
}
|
||||
|
||||
func (h *ApplicationHandler) CreateGroup(w http.ResponseWriter, r *http.Request) {
|
||||
|
||||
var beneficiary any
|
||||
var (
|
||||
departurgeo *geojson.Feature
|
||||
dstinationgeo *geojson.Feature
|
||||
)
|
||||
searched := false
|
||||
|
||||
if r.FormValue("beneficiaryid") != "" {
|
||||
|
||||
searched = true
|
||||
|
||||
requestbeneficiary := &mobilityaccounts.GetAccountRequest{
|
||||
Id: r.FormValue("beneficiaryid"),
|
||||
}
|
||||
|
||||
respbeneficiary, err := h.services.GRPC.MobilityAccounts.GetAccount(context.TODO(), requestbeneficiary)
|
||||
if err != nil {
|
||||
log.Error().Err(err).Msg("")
|
||||
w.WriteHeader(http.StatusInternalServerError)
|
||||
return
|
||||
}
|
||||
|
||||
beneficiary = respbeneficiary.Account.ToStorageType()
|
||||
|
||||
if r.Method == "POST" {
|
||||
departure := r.FormValue("departure")
|
||||
destination := r.FormValue("destination")
|
||||
|
||||
if departure != "" && destination != "" {
|
||||
|
||||
var err error
|
||||
|
||||
departurgeo, err = geojson.UnmarshalFeature([]byte(departure))
|
||||
if err != nil {
|
||||
log.Error().Err(err).Msg("")
|
||||
w.WriteHeader(http.StatusBadRequest)
|
||||
return
|
||||
}
|
||||
|
||||
dstinationgeo, err = geojson.UnmarshalFeature([]byte(destination))
|
||||
if err != nil {
|
||||
log.Error().Err(err).Msg("")
|
||||
w.WriteHeader(http.StatusBadRequest)
|
||||
return
|
||||
}
|
||||
}
|
||||
if r.FormValue("departure") != "" {
|
||||
var a any
|
||||
json.Unmarshal([]byte(r.FormValue("departure")), &a)
|
||||
|
||||
Depart = a
|
||||
}
|
||||
if r.FormValue("destination") != "" {
|
||||
var a any
|
||||
json.Unmarshal([]byte(r.FormValue("destination")), &a)
|
||||
|
||||
Arrive = a
|
||||
}
|
||||
r.ParseForm()
|
||||
|
||||
if r.FormValue("name") == "" {
|
||||
|
||||
log.Error().Msg("invalid name")
|
||||
w.WriteHeader(http.StatusBadRequest)
|
||||
return
|
||||
}
|
||||
|
||||
if r.FormValue("number") == "" {
|
||||
|
||||
log.Error().Msg("invalid number of personne")
|
||||
w.WriteHeader(http.StatusBadRequest)
|
||||
return
|
||||
}
|
||||
|
||||
planDays := map[string]any{
|
||||
"lundi": r.FormValue("lundi") == "on",
|
||||
"mardi": r.FormValue("mardi") == "on",
|
||||
"mercredi": r.FormValue("mercredi") == "on",
|
||||
"jeudi": r.FormValue("jeudi") == "on",
|
||||
"vendredi": r.FormValue("vendredi") == "on",
|
||||
"samedi": r.FormValue("samedi") == "on",
|
||||
"dimanche": r.FormValue("dimanche") == "on",
|
||||
}
|
||||
|
||||
groupidd := uuid.NewString()
|
||||
|
||||
dataMap := map[string]any{
|
||||
"name": r.FormValue("name"),
|
||||
"number": r.FormValue("number"),
|
||||
"driver_first_name": respbeneficiary.Account.ToStorageType().Data["first_name"],
|
||||
"driver_last_name": respbeneficiary.Account.ToStorageType().Data["last_name"],
|
||||
"depart": Depart,
|
||||
"arrive": Arrive,
|
||||
"departdate": r.FormValue("departdate"),
|
||||
"date": r.FormValue("date"),
|
||||
"enddate": r.FormValue("enddate"),
|
||||
"departtime": r.FormValue("departtime"),
|
||||
"time": r.FormValue("time"),
|
||||
|
||||
"planDays": planDays,
|
||||
"recurrent": r.FormValue("recurrent"),
|
||||
"pontuelle": r.FormValue("ponctuelle"),
|
||||
}
|
||||
|
||||
data, err := structpb.NewValue(dataMap)
|
||||
if err != nil {
|
||||
log.Error().Err(err).Msg("")
|
||||
w.WriteHeader(http.StatusInternalServerError)
|
||||
return
|
||||
}
|
||||
|
||||
request_organization := &groupsmanagement.AddGroupRequest{
|
||||
Group: &groupsmanagement.Group{
|
||||
Id: groupidd,
|
||||
Namespace: "parcoursmob_groups_covoiturage",
|
||||
Data: data.GetStructValue(),
|
||||
},
|
||||
}
|
||||
|
||||
_, err = h.services.GRPC.GroupsManagement.AddGroup(context.TODO(), request_organization)
|
||||
if err != nil {
|
||||
log.Error().Err(err).Msg("")
|
||||
w.WriteHeader(http.StatusInternalServerError)
|
||||
return
|
||||
}
|
||||
|
||||
http.Redirect(w, r, fmt.Sprintf("/app/journeys/groups_covoiturage/create/%s", request_organization.Group.ToStorageType().ID), http.StatusFound)
|
||||
|
||||
return
|
||||
}
|
||||
}
|
||||
accountsBeneficaire, err := h.beneficiaries(r)
|
||||
if err != nil {
|
||||
log.Error().Err(err).Msg("")
|
||||
w.WriteHeader(http.StatusBadRequest)
|
||||
return
|
||||
}
|
||||
|
||||
h.Renderer.CreateGroup(w, r, Depart, Arrive, searched, beneficiary, accountsBeneficaire, departurgeo, dstinationgeo)
|
||||
|
||||
}
|
||||
|
||||
func (h *ApplicationHandler) DisplayGroupCovoiturage(w http.ResponseWriter, r *http.Request) {
|
||||
vars := mux.Vars(r)
|
||||
groupid := vars["groupid"]
|
||||
|
||||
request := &groupsmanagement.GetGroupRequest{
|
||||
Id: groupid,
|
||||
}
|
||||
|
||||
resp, err := h.services.GRPC.GroupsManagement.GetGroup(context.TODO(), request)
|
||||
if err != nil {
|
||||
log.Error().Err(err).Msg("")
|
||||
w.WriteHeader(http.StatusInternalServerError)
|
||||
return
|
||||
}
|
||||
|
||||
var accounts = []any{}
|
||||
|
||||
requesst := &mobilityaccounts.GetAccountsBatchRequest{
|
||||
Accountids: resp.Group.Members,
|
||||
}
|
||||
|
||||
ressp, _ := h.services.GRPC.MobilityAccounts.GetAccountsBatch(context.TODO(), requesst)
|
||||
|
||||
for _, account := range ressp.Accounts {
|
||||
if filterAcc(r, account) {
|
||||
a := account.ToStorageType()
|
||||
accounts = append(accounts, a)
|
||||
}
|
||||
}
|
||||
|
||||
cacheid := uuid.NewString()
|
||||
h.cache.PutWithTTL(cacheid, accounts, 1*time.Hour)
|
||||
r.ParseForm()
|
||||
|
||||
var beneficiary any
|
||||
searched := false
|
||||
|
||||
if r.FormValue("beneficiaryid") != "" {
|
||||
|
||||
searched = true
|
||||
|
||||
requestbeneficiary := &mobilityaccounts.GetAccountRequest{
|
||||
Id: r.FormValue("beneficiaryid"),
|
||||
}
|
||||
|
||||
respbeneficiary, err := h.services.GRPC.MobilityAccounts.GetAccount(context.TODO(), requestbeneficiary)
|
||||
if err != nil {
|
||||
log.Error().Err(err).Msg("")
|
||||
w.WriteHeader(http.StatusInternalServerError)
|
||||
return
|
||||
}
|
||||
|
||||
beneficiary = respbeneficiary.Account.ToStorageType()
|
||||
|
||||
subscribe := &groupsmanagement.SubscribeRequest{
|
||||
Groupid: resp.Group.ToStorageType().ID,
|
||||
Memberid: respbeneficiary.Account.Id,
|
||||
}
|
||||
|
||||
_, err = h.services.GRPC.GroupsManagement.Subscribe(context.TODO(), subscribe)
|
||||
|
||||
if err != nil {
|
||||
log.Error().Err(err).Msg("")
|
||||
w.WriteHeader(http.StatusInternalServerError)
|
||||
return
|
||||
}
|
||||
/*******************Code to store more information about mermbers groupscovoiturage**************/
|
||||
if r.FormValue("departure") != "" {
|
||||
var a any
|
||||
json.Unmarshal([]byte(r.FormValue("departure")), &a)
|
||||
|
||||
Depart = a
|
||||
}
|
||||
if r.FormValue("destination") != "" {
|
||||
var a any
|
||||
json.Unmarshal([]byte(r.FormValue("destination")), &a)
|
||||
|
||||
Arrive = a
|
||||
}
|
||||
r.ParseForm()
|
||||
dataMap := map[string]any{
|
||||
|
||||
"depart": Depart,
|
||||
"arrive": Arrive,
|
||||
}
|
||||
id := uuid.NewString()
|
||||
data, err := structpb.NewValue(dataMap)
|
||||
if err != nil {
|
||||
log.Error().Err(err).Msg("")
|
||||
w.WriteHeader(http.StatusInternalServerError)
|
||||
return
|
||||
}
|
||||
|
||||
request_organizatio := &groupsmanagement.AddGroupMemberRequest{
|
||||
Group: &groupsmanagement.GroupMember{
|
||||
Id: id,
|
||||
Memberid: respbeneficiary.Account.Id,
|
||||
Groupid: resp.Group.ToStorageType().ID,
|
||||
Data: data.GetStructValue(),
|
||||
},
|
||||
}
|
||||
|
||||
_, err = h.services.GRPC.GroupsManagement.AddGroupMember(context.TODO(), request_organizatio)
|
||||
if err != nil {
|
||||
log.Error().Err(err).Msg("")
|
||||
w.WriteHeader(http.StatusInternalServerError)
|
||||
return
|
||||
}
|
||||
|
||||
http.Redirect(w, r, fmt.Sprintf("/app/journeys/groups_covoiturage/create/%s", resp.Group.ToStorageType().ID), http.StatusFound)
|
||||
return
|
||||
}
|
||||
//////////find all groups to store the adresse passenger///////
|
||||
// grp := &groupsmanagement.GetGroupsBatchMemberRequest{
|
||||
|
||||
// Groupids: []string{resp.Group.ToStorageType().ID},
|
||||
// }
|
||||
// s, err := h.services.GRPC.GroupsManagement.GetGroupsBatchMember(context.TODO(), grp)
|
||||
// if err != nil {
|
||||
// log.Error().Err(err).Msg("")
|
||||
// w.WriteHeader(http.StatusInternalServerError)
|
||||
// return
|
||||
// }
|
||||
// groups := map[string]any{}
|
||||
|
||||
// if err == nil {
|
||||
// for _, g := range s.Groups {
|
||||
// groups[g.Memberid] = g.ToStorageType()
|
||||
// }
|
||||
// }
|
||||
//////////find all groups to store the adresse passenger///////
|
||||
///////////try to optimise the code ////////////////////////////
|
||||
groups, _ := h.services.GetGroupsMemberMap(resp.Group.ToStorageType().ID)
|
||||
var number string = strconv.Itoa(len(resp.Group.Members))
|
||||
accountsBeneficaire, err := h.beneficiaries(r)
|
||||
if err != nil {
|
||||
log.Error().Err(err).Msg("")
|
||||
w.WriteHeader(http.StatusBadRequest)
|
||||
return
|
||||
}
|
||||
|
||||
h.Renderer.DisplayGroupCovoiturage(w, r, number, resp.Group.ToStorageType().ID, Depart, Arrive, accounts, cacheid, searched, beneficiary, resp.Group.ToStorageType(), accountsBeneficaire, groups)
|
||||
}
|
||||
|
||||
func (h *ApplicationHandler) UpdateGroupCovoiturage(w http.ResponseWriter, r *http.Request) {
|
||||
vars := mux.Vars(r)
|
||||
id := vars["id"]
|
||||
groupid := vars["groupid"]
|
||||
memberid := vars["memberid"]
|
||||
|
||||
if r.Method == "POST" {
|
||||
|
||||
//////////get groupid covoiturage//////////
|
||||
request := &groupsmanagement.GetGroupRequest{
|
||||
Id: groupid,
|
||||
}
|
||||
|
||||
resp, err := h.services.GRPC.GroupsManagement.GetGroup(context.TODO(), request)
|
||||
if err != nil {
|
||||
log.Error().Err(err).Msg("")
|
||||
w.WriteHeader(http.StatusInternalServerError)
|
||||
return
|
||||
}
|
||||
|
||||
//////////////////////////get group member////////////////////////////////
|
||||
|
||||
reequest := &groupsmanagement.GetGroupMemberRequest{
|
||||
Id: id,
|
||||
}
|
||||
|
||||
ressp, err := h.services.GRPC.GroupsManagement.GetGroupMember(context.TODO(), reequest)
|
||||
if err != nil {
|
||||
log.Error().Err(err).Msg("")
|
||||
w.WriteHeader(http.StatusInternalServerError)
|
||||
return
|
||||
}
|
||||
req := &groupsmanagement.UnsubscribeMemberRequest{
|
||||
Id: ressp.Group.Id,
|
||||
}
|
||||
|
||||
_, errr := h.services.GRPC.GroupsManagement.UnsubscribeMember(context.TODO(), req)
|
||||
if errr != nil {
|
||||
log.Error().Err(errr).Msg("Issue in groups management service - InsubscribeMember")
|
||||
w.WriteHeader(http.StatusInternalServerError)
|
||||
return
|
||||
}
|
||||
|
||||
members := resp.Group.Members
|
||||
for i := 0; i < len(members); i++ {
|
||||
if members[i] == memberid {
|
||||
members = append(members[:i], members[(i+1):]...)
|
||||
resp.Group.Members = members
|
||||
reequest := &groupsmanagement.UnsubscribeRequest{
|
||||
Groupid: resp.Group.ToStorageType().ID,
|
||||
Memberid: memberid,
|
||||
}
|
||||
|
||||
_, err := h.services.GRPC.GroupsManagement.Unsubscribe(context.TODO(), reequest)
|
||||
if err != nil {
|
||||
log.Error().Err(err).Msg("")
|
||||
w.WriteHeader(http.StatusInternalServerError)
|
||||
return
|
||||
}
|
||||
}
|
||||
|
||||
}
|
||||
http.Redirect(w, r, fmt.Sprintf("/app/journeys/groups_covoiturage/create/%s", groupid), http.StatusFound)
|
||||
/*
|
||||
I must add "return" to resolve the err
|
||||
http: superfluous response.WriteHeader call from git.coopgo.io/coopgo-apps/parcoursmob/renderer.(*Renderer).Render (renderer.go:50)
|
||||
*/
|
||||
return
|
||||
}
|
||||
h.Renderer.UpdateGroupCovoiturage(w, r, groupid, memberid)
|
||||
}
|
||||
@@ -1,214 +0,0 @@
|
||||
package application
|
||||
|
||||
import (
|
||||
"context"
|
||||
"encoding/json"
|
||||
"fmt"
|
||||
"net/http"
|
||||
"strings"
|
||||
"time"
|
||||
|
||||
formvalidators "git.coopgo.io/coopgo-apps/parcoursmob/utils/form-validators"
|
||||
groupsmanagement "git.coopgo.io/coopgo-platform/groups-management/grpcapi"
|
||||
mobilityaccounts "git.coopgo.io/coopgo-platform/mobility-accounts/grpcapi"
|
||||
"github.com/google/uuid"
|
||||
"github.com/rs/zerolog/log"
|
||||
"google.golang.org/protobuf/types/known/structpb"
|
||||
)
|
||||
|
||||
type UserForm struct {
|
||||
FirstName string `json:"first_name" validate:"required"`
|
||||
LastName string `json:"last_name" validate:"required"`
|
||||
Email string `json:"email" validate:"required,email"`
|
||||
PhoneNumber string `json:"phone_number" `
|
||||
Address any `json:"address,omitempty"`
|
||||
Gender string `json:"gender"`
|
||||
}
|
||||
|
||||
func (h *ApplicationHandler) MemberDisplay(w http.ResponseWriter, r *http.Request) {
|
||||
|
||||
adm := strings.Split(r.URL.Path, "/")
|
||||
adminid := adm[3]
|
||||
|
||||
request := &mobilityaccounts.GetAccountRequest{
|
||||
Id: adminid,
|
||||
}
|
||||
|
||||
resp, err := h.services.GRPC.MobilityAccounts.GetAccount(context.TODO(), request)
|
||||
if err != nil {
|
||||
log.Error().Err(err).Msg("")
|
||||
w.WriteHeader(http.StatusInternalServerError)
|
||||
return
|
||||
}
|
||||
//////////////////////////////////add organisations/////////////////////////////////////////////////
|
||||
|
||||
var allIds []string
|
||||
for _, v := range resp.Account.ToStorageType().Data["groups"].([]any) {
|
||||
s := fmt.Sprintf("%v", v)
|
||||
if !(strings.Contains(s, "admin")) {
|
||||
allIds = append(allIds, s)
|
||||
}
|
||||
}
|
||||
reques := &groupsmanagement.GetGroupsBatchRequest{
|
||||
Groupids: allIds,
|
||||
}
|
||||
|
||||
res, err := h.services.GRPC.GroupsManagement.GetGroupsBatch(context.TODO(), reques)
|
||||
if err != nil {
|
||||
log.Error().Err(err).Msg("")
|
||||
w.WriteHeader(http.StatusInternalServerError)
|
||||
return
|
||||
}
|
||||
|
||||
var groupsName []string
|
||||
|
||||
for _, group := range res.Groups {
|
||||
g := fmt.Sprintf("%v", group.ToStorageType().Data["name"])
|
||||
groupsName = append(groupsName, g)
|
||||
}
|
||||
|
||||
h.Renderer.MemberDisplay(w, r, resp.Account.ToStorageType(), groupsName)
|
||||
}
|
||||
|
||||
func (h *ApplicationHandler) MemberUpdate(w http.ResponseWriter, r *http.Request) {
|
||||
adm := strings.Split(r.URL.Path, "/")
|
||||
userID := adm[3]
|
||||
|
||||
if r.Method == "POST" {
|
||||
|
||||
dataMap, err := parseUserForm(r)
|
||||
if err != nil {
|
||||
log.Error().Err(err).Msg("")
|
||||
w.WriteHeader(http.StatusBadRequest)
|
||||
return
|
||||
}
|
||||
|
||||
data, err := structpb.NewValue(dataMap)
|
||||
if err != nil {
|
||||
log.Error().Err(err).Msg("")
|
||||
w.WriteHeader(http.StatusInternalServerError)
|
||||
return
|
||||
}
|
||||
|
||||
request := &mobilityaccounts.UpdateDataRequest{
|
||||
Account: &mobilityaccounts.Account{
|
||||
Id: userID,
|
||||
Namespace: "parcoursmob",
|
||||
Data: data.GetStructValue(),
|
||||
},
|
||||
}
|
||||
|
||||
resp, err := h.services.GRPC.MobilityAccounts.UpdateData(context.TODO(), request)
|
||||
|
||||
if err != nil {
|
||||
log.Error().Err(err).Msg("")
|
||||
w.WriteHeader(http.StatusInternalServerError)
|
||||
return
|
||||
}
|
||||
|
||||
http.Redirect(w, r, fmt.Sprintf("/app/members/%s", resp.Account.Id), http.StatusFound)
|
||||
|
||||
return
|
||||
}
|
||||
|
||||
request := &mobilityaccounts.GetAccountRequest{
|
||||
Id: userID,
|
||||
}
|
||||
|
||||
resp, err := h.services.GRPC.MobilityAccounts.GetAccount(context.TODO(), request)
|
||||
if err != nil {
|
||||
log.Error().Err(err).Msg("")
|
||||
w.WriteHeader(http.StatusInternalServerError)
|
||||
return
|
||||
}
|
||||
|
||||
h.Renderer.MemberUpdate(w, r, resp.Account.ToStorageType())
|
||||
}
|
||||
|
||||
func parseUserForm(r *http.Request) (map[string]any, error) {
|
||||
if err := r.ParseForm(); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
|
||||
formData := UserForm{
|
||||
FirstName: r.PostFormValue("first_name"),
|
||||
LastName: r.PostFormValue("last_name"),
|
||||
Email: r.PostFormValue("email"),
|
||||
PhoneNumber: r.PostFormValue("phone_number"),
|
||||
Gender: r.PostFormValue("gender"),
|
||||
}
|
||||
|
||||
validate := formvalidators.New()
|
||||
if err := validate.Struct(formData); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
|
||||
d, err := json.Marshal(formData)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
|
||||
var dataMap map[string]any
|
||||
err = json.Unmarshal(d, &dataMap)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
|
||||
return dataMap, nil
|
||||
}
|
||||
|
||||
func (h *ApplicationHandler) MembersList(w http.ResponseWriter, r *http.Request) {
|
||||
|
||||
accounts, err := h.services.GetAccounts()
|
||||
if err != nil {
|
||||
log.Error().Err(err).Msg("")
|
||||
w.WriteHeader(http.StatusInternalServerError)
|
||||
return
|
||||
}
|
||||
var groupsName []string
|
||||
|
||||
for _, v := range accounts {
|
||||
adminid := v.ID
|
||||
request := &mobilityaccounts.GetAccountRequest{
|
||||
Id: adminid,
|
||||
}
|
||||
|
||||
resp, err := h.services.GRPC.MobilityAccounts.GetAccount(context.TODO(), request)
|
||||
if err != nil {
|
||||
log.Error().Err(err).Msg("")
|
||||
w.WriteHeader(http.StatusInternalServerError)
|
||||
return
|
||||
}
|
||||
//////////////////////////////////add organisations/////////////////////////////////////////////////
|
||||
|
||||
var allIds []string
|
||||
for _, v := range resp.Account.ToStorageType().Data["groups"].([]any) {
|
||||
s := fmt.Sprintf("%v", v)
|
||||
if !(strings.Contains(s, "admin")) {
|
||||
allIds = append(allIds, s)
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
reques := &groupsmanagement.GetGroupsBatchRequest{
|
||||
Groupids: allIds,
|
||||
}
|
||||
|
||||
res, err := h.services.GRPC.GroupsManagement.GetGroupsBatch(context.TODO(), reques)
|
||||
if err != nil {
|
||||
log.Error().Err(err).Msg("")
|
||||
w.WriteHeader(http.StatusInternalServerError)
|
||||
return
|
||||
}
|
||||
g := ""
|
||||
for _, group := range res.Groups {
|
||||
g += fmt.Sprintf("%v", group.ToStorageType().Data["name"]) + " "
|
||||
}
|
||||
groupsName = append(groupsName, g)
|
||||
|
||||
}
|
||||
cacheid := uuid.NewString()
|
||||
h.cache.PutWithTTL(cacheid, accounts, 1*time.Hour)
|
||||
|
||||
h.Renderer.MembersList(w, r, accounts, cacheid, groupsName)
|
||||
}
|
||||
@@ -1,47 +0,0 @@
|
||||
package application
|
||||
|
||||
import (
|
||||
"net/http"
|
||||
|
||||
"git.coopgo.io/coopgo-apps/parcoursmob/utils/identification"
|
||||
"git.coopgo.io/coopgo-platform/emailing"
|
||||
"github.com/rs/zerolog/log"
|
||||
)
|
||||
|
||||
type Message struct {
|
||||
Content string
|
||||
}
|
||||
|
||||
func (h *ApplicationHandler) SupportSend(w http.ResponseWriter, r *http.Request) {
|
||||
|
||||
c := r.Context().Value(identification.ClaimsKey)
|
||||
if c == nil {
|
||||
log.Error().Msg("no current user claims")
|
||||
w.WriteHeader(http.StatusInternalServerError)
|
||||
return
|
||||
}
|
||||
current_user_claims := c.(map[string]any)
|
||||
|
||||
comment := r.PostFormValue(("comment"))
|
||||
|
||||
|
||||
if r.Method == "POST" {
|
||||
user_email := current_user_claims["email"].(string)
|
||||
|
||||
data := map[string]any{
|
||||
"key": comment,
|
||||
"user": user_email,
|
||||
}
|
||||
|
||||
log.Debug().Str("user_email", user_email).Msg("Sending message")
|
||||
|
||||
if err := h.emailing.Send("support.request", "support@parcoursmob.fr", data, emailing.WithReplyTo(user_email), emailing.WithTLSOpportunistic()); err != nil {
|
||||
log.Error().Err(err).Msg("error sending email")
|
||||
w.WriteHeader(http.StatusInternalServerError)
|
||||
return
|
||||
}
|
||||
http.Redirect(w, r, "/app/", http.StatusFound)
|
||||
return
|
||||
}
|
||||
h.Renderer.SupportSend(w, r, comment, current_user_claims)
|
||||
}
|
||||
@@ -1,689 +0,0 @@
|
||||
package application
|
||||
|
||||
import (
|
||||
"context"
|
||||
"encoding/json"
|
||||
"fmt"
|
||||
"net/http"
|
||||
"sort"
|
||||
"time"
|
||||
|
||||
"git.coopgo.io/coopgo-apps/parcoursmob/utils/identification"
|
||||
"git.coopgo.io/coopgo-apps/parcoursmob/utils/sorting"
|
||||
filestorage "git.coopgo.io/coopgo-apps/parcoursmob/utils/storage"
|
||||
diags "git.coopgo.io/coopgo-platform/diags/grpcapi"
|
||||
diagsstorage "git.coopgo.io/coopgo-platform/diags/storage"
|
||||
fleets "git.coopgo.io/coopgo-platform/fleets/grpcapi"
|
||||
fleetsstorage "git.coopgo.io/coopgo-platform/fleets/storage"
|
||||
groupsmanagement "git.coopgo.io/coopgo-platform/groups-management/grpcapi"
|
||||
"git.coopgo.io/coopgo-platform/groups-management/storage"
|
||||
mobilityaccounts "git.coopgo.io/coopgo-platform/mobility-accounts/grpcapi"
|
||||
mobilityaccountsstorage "git.coopgo.io/coopgo-platform/mobility-accounts/storage"
|
||||
"github.com/coreos/go-oidc/v3/oidc"
|
||||
"github.com/google/uuid"
|
||||
"github.com/gorilla/mux"
|
||||
"github.com/rs/zerolog/log"
|
||||
"google.golang.org/protobuf/types/known/structpb"
|
||||
"google.golang.org/protobuf/types/known/timestamppb"
|
||||
)
|
||||
|
||||
func (h *ApplicationHandler) VehiclesManagementOverview(w http.ResponseWriter, r *http.Request) {
|
||||
//Get Vehicles
|
||||
request := &fleets.GetVehiclesRequest{
|
||||
Namespaces: []string{"parcoursmob"},
|
||||
}
|
||||
resp, err := h.services.GRPC.Fleets.GetVehicles(context.TODO(), request)
|
||||
if err != nil {
|
||||
log.Error().Err(err).Msg("")
|
||||
w.WriteHeader(http.StatusInternalServerError)
|
||||
}
|
||||
|
||||
vehicles := []fleetsstorage.Vehicle{}
|
||||
bookings := []fleetsstorage.Booking{}
|
||||
vehicles_map := map[string]fleetsstorage.Vehicle{}
|
||||
|
||||
for _, vehicle := range resp.Vehicles {
|
||||
if filterVehicle(r, vehicle) {
|
||||
v := vehicle.ToStorageType()
|
||||
vehicleBookings := []fleetsstorage.Booking{}
|
||||
for _, b := range v.Bookings {
|
||||
if b.Status() != fleetsstorage.StatusOld {
|
||||
if deleted, ok := b.Data["Deleted"].(bool); !ok && !deleted {
|
||||
bookings = append(bookings, b)
|
||||
}
|
||||
}
|
||||
if b.Unavailableto.After(time.Now()) {
|
||||
vehicleBookings = append(vehicleBookings, b)
|
||||
}
|
||||
}
|
||||
v.Bookings = vehicleBookings
|
||||
vehicles = append(vehicles, v)
|
||||
vehicles_map[v.ID] = v
|
||||
|
||||
}
|
||||
}
|
||||
|
||||
driversMap, _ := h.services.GetBeneficiariesMap()
|
||||
|
||||
sort.Sort(sorting.VehiclesByLicencePlate(vehicles))
|
||||
sort.Sort(sorting.BookingsByStartdate(bookings))
|
||||
h.Renderer.VehiclesManagementOverview(w, r, vehicles, vehicles_map, driversMap, bookings)
|
||||
}
|
||||
|
||||
func (h *ApplicationHandler) VehiclesManagementBookingsList(w http.ResponseWriter, r *http.Request) {
|
||||
//Get Vehicles
|
||||
request := &fleets.GetVehiclesRequest{
|
||||
Namespaces: []string{"parcoursmob"},
|
||||
}
|
||||
resp, err := h.services.GRPC.Fleets.GetVehicles(context.TODO(), request)
|
||||
if err != nil {
|
||||
log.Error().Err(err).Msg("")
|
||||
w.WriteHeader(http.StatusInternalServerError)
|
||||
}
|
||||
|
||||
bookings := []fleetsstorage.Booking{}
|
||||
vehicles_map := map[string]fleetsstorage.Vehicle{}
|
||||
|
||||
for _, vehicle := range resp.Vehicles {
|
||||
if filterVehicle(r, vehicle) {
|
||||
v := vehicle.ToStorageType()
|
||||
vehicles_map[v.ID] = v
|
||||
// bookings = append(bookings, v.Bookings...)
|
||||
for _, b := range v.Bookings {
|
||||
if v, ok := b.Data["administrator_unavailability"].(bool); !ok || !v {
|
||||
bookings = append(bookings, b)
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
sort.Sort(sorting.BookingsByStartdate(bookings))
|
||||
|
||||
cacheid := uuid.NewString()
|
||||
h.cache.PutWithTTL(cacheid, bookings, 1*time.Hour)
|
||||
|
||||
driversMap, _ := h.services.GetBeneficiariesMap()
|
||||
|
||||
h.Renderer.VehiclesManagementBookingsList(w, r, vehicles_map, driversMap, bookings, cacheid)
|
||||
}
|
||||
|
||||
func (h *ApplicationHandler) VehiclesFleetAdd(w http.ResponseWriter, r *http.Request) {
|
||||
if r.Method == "POST" {
|
||||
g := r.Context().Value(identification.GroupKey)
|
||||
if g == nil {
|
||||
w.WriteHeader(http.StatusBadRequest)
|
||||
return
|
||||
}
|
||||
|
||||
group := g.(storage.Group)
|
||||
|
||||
if err := r.ParseForm(); err != nil {
|
||||
log.Error().Err(err).Msg("")
|
||||
w.WriteHeader(http.StatusBadRequest)
|
||||
return
|
||||
}
|
||||
|
||||
dataMap := map[string]any{}
|
||||
if v := r.FormValue("name"); v != "" {
|
||||
dataMap["name"] = v
|
||||
}
|
||||
if v := r.FormValue("address"); v != "" {
|
||||
var address map[string]any
|
||||
err := json.Unmarshal([]byte(v), &address)
|
||||
if err != nil {
|
||||
log.Error().Err(err).Msg("")
|
||||
w.WriteHeader(http.StatusInternalServerError)
|
||||
return
|
||||
}
|
||||
dataMap["address"] = address
|
||||
}
|
||||
if v := r.FormValue("informations"); v != "" {
|
||||
dataMap["informations"] = v
|
||||
}
|
||||
if v := r.FormValue("licence_plate"); v != "" {
|
||||
dataMap["licence_plate"] = v
|
||||
}
|
||||
if v := r.FormValue("automatic"); v != "" {
|
||||
dataMap["automatic"] = (v == "on")
|
||||
}
|
||||
if v := r.FormValue("kilometers"); v != "" {
|
||||
dataMap["kilometers"] = v
|
||||
}
|
||||
|
||||
data, err := structpb.NewValue(dataMap)
|
||||
if err != nil {
|
||||
log.Error().Err(err).Msg("")
|
||||
w.WriteHeader(http.StatusInternalServerError)
|
||||
return
|
||||
}
|
||||
|
||||
vehicle := &fleets.Vehicle{
|
||||
Id: uuid.NewString(),
|
||||
Namespace: "parcoursmob",
|
||||
Type: r.FormValue("type"),
|
||||
Administrators: []string{group.ID},
|
||||
Data: data.GetStructValue(),
|
||||
}
|
||||
|
||||
request := &fleets.AddVehicleRequest{
|
||||
Vehicle: vehicle,
|
||||
}
|
||||
|
||||
_, err = h.services.GRPC.Fleets.AddVehicle(context.TODO(), request)
|
||||
|
||||
if err != nil {
|
||||
log.Error().Err(err).Msg("")
|
||||
w.WriteHeader(http.StatusInternalServerError)
|
||||
return
|
||||
}
|
||||
|
||||
http.Redirect(w, r, fmt.Sprintf("/app/vehicles-management/fleet/%s", vehicle.Id), http.StatusFound)
|
||||
return
|
||||
}
|
||||
|
||||
vehicles_types := h.config.GetStringSlice("modules.fleets.vehicle_types")
|
||||
h.Renderer.VehiclesFleetAdd(w, r, vehicles_types)
|
||||
}
|
||||
|
||||
func (h *ApplicationHandler) VehiclesFleetDisplay(w http.ResponseWriter, r *http.Request) {
|
||||
vars := mux.Vars(r)
|
||||
vehicleid := vars["vehicleid"]
|
||||
|
||||
request := &fleets.GetVehicleRequest{
|
||||
Vehicleid: vehicleid,
|
||||
}
|
||||
|
||||
resp, err := h.services.GRPC.Fleets.GetVehicle(context.TODO(), request)
|
||||
if err != nil {
|
||||
log.Error().Err(err).Msg("")
|
||||
w.WriteHeader(http.StatusInternalServerError)
|
||||
return
|
||||
}
|
||||
|
||||
diag := []diagsstorage.Diag{}
|
||||
|
||||
diagsrequest := &diags.GetDiagsRequest{
|
||||
Namespaces: []string{"parcoursmob_vehicles"},
|
||||
}
|
||||
|
||||
diagsresp, err := h.services.GRPC.Diags.GetDiags(context.TODO(), diagsrequest)
|
||||
if err != nil {
|
||||
log.Error().Err(err).Msg("")
|
||||
w.WriteHeader(http.StatusInternalServerError)
|
||||
return
|
||||
}
|
||||
|
||||
for _, d := range diagsresp.Diags {
|
||||
diagData := d.Data.AsMap()
|
||||
if vehicle, ok := diagData["vehicle"].(string); ok && vehicle == vehicleid {
|
||||
diag = append(diag, d.ToStorageType())
|
||||
}
|
||||
}
|
||||
|
||||
diagsAny := make([]any, len(diag))
|
||||
for i, d := range diag {
|
||||
diagsAny[i] = d
|
||||
}
|
||||
|
||||
h.Renderer.VehiclesFleetDisplay(w, r, resp.Vehicle.ToStorageType(), diagsAny)
|
||||
}
|
||||
|
||||
func filterVehicle(r *http.Request, v *fleets.Vehicle) bool {
|
||||
g := r.Context().Value(identification.GroupKey)
|
||||
if g == nil {
|
||||
return false
|
||||
}
|
||||
|
||||
group := g.(storage.Group)
|
||||
|
||||
for _, n := range v.Administrators {
|
||||
if n == group.ID {
|
||||
return true
|
||||
}
|
||||
}
|
||||
|
||||
return false
|
||||
}
|
||||
|
||||
func (h ApplicationHandler) VehicleManagementBookingDisplay(w http.ResponseWriter, r *http.Request) {
|
||||
vars := mux.Vars(r)
|
||||
bookingid := vars["bookingid"]
|
||||
|
||||
booking, err := h.services.GetBooking(bookingid)
|
||||
if err != nil {
|
||||
log.Error().Err(err).Msg("")
|
||||
w.WriteHeader(http.StatusInternalServerError)
|
||||
return
|
||||
}
|
||||
|
||||
if r.Method == "POST" {
|
||||
r.ParseForm()
|
||||
|
||||
newbooking, _ := fleets.BookingFromStorageType(&booking)
|
||||
|
||||
startdate := r.FormValue("startdate")
|
||||
if startdate != "" {
|
||||
newstartdate, _ := time.Parse("2006-01-02", startdate)
|
||||
newbooking.Startdate = timestamppb.New(newstartdate)
|
||||
|
||||
if newstartdate.Before(newbooking.Unavailablefrom.AsTime()) {
|
||||
newbooking.Unavailablefrom = timestamppb.New(newstartdate)
|
||||
}
|
||||
}
|
||||
|
||||
enddate := r.FormValue("enddate")
|
||||
if enddate != "" {
|
||||
newenddate, _ := time.Parse("2006-01-02", enddate)
|
||||
newbooking.Enddate = timestamppb.New(newenddate)
|
||||
|
||||
if newenddate.After(newbooking.Unavailableto.AsTime()) || newenddate.Equal(newbooking.Unavailableto.AsTime()) {
|
||||
newbooking.Unavailableto = timestamppb.New(newenddate.Add(24 * time.Hour))
|
||||
}
|
||||
}
|
||||
|
||||
unavailablefrom := r.FormValue("unavailablefrom")
|
||||
if unavailablefrom != "" {
|
||||
newunavailablefrom, _ := time.Parse("2006-01-02", unavailablefrom)
|
||||
newbooking.Unavailablefrom = timestamppb.New(newunavailablefrom)
|
||||
}
|
||||
|
||||
unavailableto := r.FormValue("unavailableto")
|
||||
if unavailableto != "" {
|
||||
newunavailableto, _ := time.Parse("2006-01-02", unavailableto)
|
||||
newbooking.Unavailableto = timestamppb.New(newunavailableto)
|
||||
}
|
||||
|
||||
request := &fleets.UpdateBookingRequest{
|
||||
Booking: newbooking,
|
||||
}
|
||||
|
||||
_, err := h.services.GRPC.Fleets.UpdateBooking(context.TODO(), request)
|
||||
if err != nil {
|
||||
log.Error().Err(err).Msg("")
|
||||
w.WriteHeader(http.StatusInternalServerError)
|
||||
return
|
||||
}
|
||||
|
||||
booking = newbooking.ToStorageType()
|
||||
}
|
||||
|
||||
beneficiary := mobilityaccountsstorage.Account{}
|
||||
|
||||
if booking.Driver != "" {
|
||||
beneficiaryrequest := &mobilityaccounts.GetAccountRequest{
|
||||
Id: booking.Driver,
|
||||
}
|
||||
|
||||
beneficiaryresp, err := h.services.GRPC.MobilityAccounts.GetAccount(context.TODO(), beneficiaryrequest)
|
||||
if err != nil {
|
||||
log.Error().Err(err).Msg("")
|
||||
w.WriteHeader(http.StatusInternalServerError)
|
||||
return
|
||||
}
|
||||
|
||||
beneficiary = beneficiaryresp.Account.ToStorageType()
|
||||
}
|
||||
|
||||
grouprequest := &groupsmanagement.GetGroupRequest{
|
||||
Id: booking.Vehicle.Administrators[0],
|
||||
}
|
||||
|
||||
groupresp, err := h.services.GRPC.GroupsManagement.GetGroup(context.TODO(), grouprequest)
|
||||
if err != nil {
|
||||
log.Error().Err(err).Msg("")
|
||||
w.WriteHeader(http.StatusInternalServerError)
|
||||
return
|
||||
}
|
||||
|
||||
alternativerequest := &fleets.GetVehiclesRequest{
|
||||
Namespaces: []string{"parcoursmob"},
|
||||
Types: []string{booking.Vehicle.Type},
|
||||
Administrators: booking.Vehicle.Administrators,
|
||||
AvailabilityFrom: timestamppb.New(booking.Startdate),
|
||||
AvailabilityTo: timestamppb.New(booking.Enddate.Add(24 * time.Hour)),
|
||||
}
|
||||
|
||||
alternativeresp, err := h.services.GRPC.Fleets.GetVehicles(context.TODO(), alternativerequest)
|
||||
if err != nil {
|
||||
log.Error().Err(err).Msg("")
|
||||
}
|
||||
|
||||
alternatives := []any{}
|
||||
|
||||
for _, a := range alternativeresp.Vehicles {
|
||||
alternatives = append(alternatives, a.ToStorageType())
|
||||
}
|
||||
|
||||
documents := h.filestorage.List(filestorage.PREFIX_BOOKINGS + "/" + bookingid)
|
||||
file_types_map := h.config.GetStringMapString("storage.files.file_types")
|
||||
|
||||
diag := []diagsstorage.Diag{}
|
||||
|
||||
diagsrequest := &diags.GetDiagsRequest{
|
||||
Namespaces: []string{"parcoursmob_bookings"},
|
||||
}
|
||||
|
||||
diagsresp, err := h.services.GRPC.Diags.GetDiags(context.TODO(), diagsrequest)
|
||||
if err != nil {
|
||||
log.Error().Err(err).Msg("")
|
||||
w.WriteHeader(http.StatusInternalServerError)
|
||||
return
|
||||
}
|
||||
|
||||
for _, d := range diagsresp.Diags {
|
||||
diagData := d.Data.AsMap()
|
||||
if booking, ok := diagData["booking"].(string); ok && booking == bookingid {
|
||||
diag = append(diag, d.ToStorageType())
|
||||
}
|
||||
}
|
||||
|
||||
diagsAny := make([]any, len(diag))
|
||||
for i, d := range diag {
|
||||
diagsAny[i] = d
|
||||
}
|
||||
|
||||
h.Renderer.VehicleManagementBookingDisplay(w, r, booking, booking.Vehicle, beneficiary, groupresp.Group.ToStorageType(), documents, file_types_map, alternatives, diagsAny)
|
||||
}
|
||||
|
||||
func (h ApplicationHandler) VehicleManagementBookingChangeVehicle(w http.ResponseWriter, r *http.Request) {
|
||||
vars := mux.Vars(r)
|
||||
bookingid := vars["bookingid"]
|
||||
|
||||
r.ParseForm()
|
||||
|
||||
newvehicle := r.FormValue("vehicle")
|
||||
|
||||
booking, err := h.services.GetBooking(bookingid)
|
||||
if err != nil {
|
||||
log.Error().Err(err).Msg("")
|
||||
w.WriteHeader(http.StatusInternalServerError)
|
||||
return
|
||||
}
|
||||
|
||||
booking.Vehicleid = newvehicle
|
||||
|
||||
b, _ := fleets.BookingFromStorageType(&booking)
|
||||
|
||||
request := &fleets.UpdateBookingRequest{
|
||||
Booking: b,
|
||||
}
|
||||
|
||||
_, err = h.services.GRPC.Fleets.UpdateBooking(context.TODO(), request)
|
||||
if err != nil {
|
||||
log.Error().Err(err).Msg("")
|
||||
w.WriteHeader(http.StatusInternalServerError)
|
||||
return
|
||||
}
|
||||
|
||||
http.Redirect(w, r, fmt.Sprintf("/app/vehicles-management/bookings/%s", bookingid), http.StatusFound)
|
||||
|
||||
}
|
||||
|
||||
func (h ApplicationHandler) VehiclesFleetMakeUnavailable(w http.ResponseWriter, r *http.Request) { // Get Group
|
||||
g := r.Context().Value(identification.GroupKey)
|
||||
if g == nil {
|
||||
log.Error().Msg("no current group")
|
||||
w.WriteHeader(http.StatusInternalServerError)
|
||||
return
|
||||
}
|
||||
current_group := g.(storage.Group)
|
||||
|
||||
// Get current user ID
|
||||
u := r.Context().Value(identification.IdtokenKey)
|
||||
if u == nil {
|
||||
log.Error().Msg("no current user")
|
||||
w.WriteHeader(http.StatusInternalServerError)
|
||||
return
|
||||
}
|
||||
current_user_token := u.(*oidc.IDToken)
|
||||
|
||||
// Get current user claims
|
||||
c := r.Context().Value(identification.ClaimsKey)
|
||||
if c == nil {
|
||||
log.Error().Msg("no current user claims")
|
||||
w.WriteHeader(http.StatusInternalServerError)
|
||||
return
|
||||
}
|
||||
current_user_claims := c.(map[string]any)
|
||||
|
||||
vars := mux.Vars(r)
|
||||
vehicleid := vars["vehicleid"]
|
||||
|
||||
r.ParseForm()
|
||||
|
||||
start := r.FormValue("unavailablefrom")
|
||||
end := r.FormValue("unavailableto")
|
||||
comment := r.FormValue("comment")
|
||||
|
||||
unavailablefrom, _ := time.Parse("2006-01-02", start)
|
||||
unavailableto, _ := time.Parse("2006-01-02", end)
|
||||
|
||||
data := map[string]any{
|
||||
"comment": comment,
|
||||
"administrator_unavailability": true,
|
||||
"booked_by": map[string]any{
|
||||
"user": map[string]any{
|
||||
"id": current_user_token.Subject,
|
||||
"display_name": current_user_claims["display_name"],
|
||||
},
|
||||
"group": map[string]any{
|
||||
"id": current_group.ID,
|
||||
"name": current_group.Data["name"],
|
||||
},
|
||||
},
|
||||
}
|
||||
|
||||
datapb, err := structpb.NewStruct(data)
|
||||
if err != nil {
|
||||
log.Error().Err(err).Msg("")
|
||||
w.WriteHeader(http.StatusInternalServerError)
|
||||
return
|
||||
}
|
||||
|
||||
booking := &fleets.Booking{
|
||||
Id: uuid.NewString(),
|
||||
Vehicleid: vehicleid,
|
||||
Unavailablefrom: timestamppb.New(unavailablefrom),
|
||||
Unavailableto: timestamppb.New(unavailableto),
|
||||
Data: datapb,
|
||||
}
|
||||
|
||||
request := &fleets.CreateBookingRequest{
|
||||
Booking: booking,
|
||||
}
|
||||
|
||||
_, err = h.services.GRPC.Fleets.CreateBooking(context.TODO(), request)
|
||||
if err != nil {
|
||||
log.Error().Err(err).Msg("")
|
||||
w.WriteHeader(http.StatusBadRequest)
|
||||
return
|
||||
}
|
||||
|
||||
http.Redirect(w, r, fmt.Sprintf("/app/vehicles-management/fleet/%s", vehicleid), http.StatusFound)
|
||||
}
|
||||
|
||||
func (h *ApplicationHandler) UnbookingVehicle(w http.ResponseWriter, r *http.Request) {
|
||||
vars := mux.Vars(r)
|
||||
bookingid := vars["bookingid"]
|
||||
|
||||
request := &fleets.GetBookingRequest{
|
||||
Bookingid: bookingid,
|
||||
}
|
||||
|
||||
resp, err := h.services.GRPC.Fleets.GetBooking(context.TODO(), request)
|
||||
if err != nil {
|
||||
log.Error().Err(err).Msg("")
|
||||
w.WriteHeader(http.StatusInternalServerError)
|
||||
return
|
||||
}
|
||||
now := time.Now()
|
||||
date := now.Format("2006-01-02")
|
||||
unavailableto, _ := time.Parse("2006-01-02", date)
|
||||
|
||||
current_group, err := h.currentGroup(r)
|
||||
if err != nil {
|
||||
log.Error().Err(err).Msg("")
|
||||
w.WriteHeader(http.StatusInternalServerError)
|
||||
return
|
||||
}
|
||||
|
||||
current_user_token, current_user_claims, err := h.currentUser(r)
|
||||
if err != nil {
|
||||
log.Error().Err(err).Msg("")
|
||||
w.WriteHeader(http.StatusInternalServerError)
|
||||
return
|
||||
}
|
||||
|
||||
booked_by_id := resp.Booking.Data.Fields["booked_by"].GetStructValue().Fields["user"].GetStructValue().Fields["id"].GetStringValue()
|
||||
booked_by_name := resp.Booking.Data.Fields["booked_by"].GetStructValue().Fields["user"].GetStructValue().Fields["display_name"].GetStringValue()
|
||||
booked_by_email := resp.Booking.Data.Fields["booked_by"].GetStructValue().Fields["user"].GetStructValue().Fields["email"].GetStringValue()
|
||||
booked_by_group_id := resp.Booking.Data.Fields["booked_by"].GetStructValue().Fields["group"].GetStructValue().Fields["id"].GetStringValue()
|
||||
booked_by_group_name := resp.Booking.Data.Fields["booked_by"].GetStructValue().Fields["group"].GetStructValue().Fields["name"].GetStringValue()
|
||||
|
||||
data := map[string]any{
|
||||
"booked_by": map[string]any{
|
||||
"user": map[string]any{
|
||||
"id": booked_by_id,
|
||||
"display_name": booked_by_name,
|
||||
"email": booked_by_email,
|
||||
},
|
||||
"group": map[string]any{
|
||||
"id": booked_by_group_id,
|
||||
"name": booked_by_group_name,
|
||||
},
|
||||
},
|
||||
"unbooked_by": map[string]any{
|
||||
"user": map[string]any{
|
||||
"id": current_user_token.Subject,
|
||||
"display_name": current_user_claims["first_name"].(string) + " " + current_user_claims["last_name"].(string),
|
||||
"email": current_user_claims["email"],
|
||||
},
|
||||
"group": map[string]any{
|
||||
"id": current_group.ID,
|
||||
"name": current_group.Data["name"],
|
||||
},
|
||||
},
|
||||
"Deleted": true,
|
||||
"motif": r.FormValue("motif"),
|
||||
}
|
||||
|
||||
datapb, err := structpb.NewStruct(data)
|
||||
if err != nil {
|
||||
log.Error().Err(err).Msg("")
|
||||
w.WriteHeader(http.StatusInternalServerError)
|
||||
return
|
||||
}
|
||||
|
||||
if r.Method == "POST" {
|
||||
|
||||
request := &fleets.UpdateBookingRequest{
|
||||
Booking: &fleets.Booking{
|
||||
Id: resp.Booking.Id,
|
||||
Vehicleid: resp.Booking.Vehicleid,
|
||||
Driver: resp.Booking.Driver,
|
||||
Startdate: resp.Booking.Startdate,
|
||||
Enddate: resp.Booking.Enddate,
|
||||
Unavailablefrom: resp.Booking.Unavailablefrom,
|
||||
Unavailableto: timestamppb.New(unavailableto),
|
||||
Data: datapb,
|
||||
},
|
||||
}
|
||||
|
||||
_, err := h.services.GRPC.Fleets.UpdateBooking(context.TODO(), request)
|
||||
|
||||
if err != nil {
|
||||
log.Error().Err(err).Msg("")
|
||||
w.WriteHeader(http.StatusInternalServerError)
|
||||
return
|
||||
}
|
||||
|
||||
http.Redirect(w, r, "/app/vehicles-management/", http.StatusFound)
|
||||
return
|
||||
}
|
||||
h.Renderer.UnbookingVehicle(w, r, resp.Booking.ToStorageType())
|
||||
}
|
||||
|
||||
////////////////////////UpdateVehicle///////////////////////
|
||||
|
||||
func (h *ApplicationHandler) VehiclesFleetUpdate(w http.ResponseWriter, r *http.Request) {
|
||||
vars := mux.Vars(r)
|
||||
vehicleID := vars["vehicleid"]
|
||||
request := &fleets.GetVehicleRequest{
|
||||
Vehicleid: vehicleID,
|
||||
}
|
||||
|
||||
resp, err := h.services.GRPC.Fleets.GetVehicle(context.TODO(), request)
|
||||
if err != nil {
|
||||
log.Error().Err(err).Msg("")
|
||||
w.WriteHeader(http.StatusInternalServerError)
|
||||
return
|
||||
}
|
||||
namespaceV := resp.Vehicle.Namespace
|
||||
//typeV := resp.Vehicle.Type
|
||||
administratorsV := resp.Vehicle.Administrators
|
||||
|
||||
if r.Method == "POST" {
|
||||
fmt.Print(r.FormValue("vehicle_type"))
|
||||
if err := r.ParseForm(); err != nil {
|
||||
log.Error().Err(err).Msg("")
|
||||
w.WriteHeader(http.StatusBadRequest)
|
||||
return
|
||||
}
|
||||
dataMap := map[string]any{}
|
||||
if v := r.FormValue("name"); v != "" {
|
||||
dataMap["name"] = v
|
||||
}
|
||||
if v := r.FormValue("address"); v != "" {
|
||||
var address map[string]any
|
||||
err := json.Unmarshal([]byte(v), &address)
|
||||
if err != nil {
|
||||
log.Error().Err(err).Msg("")
|
||||
w.WriteHeader(http.StatusInternalServerError)
|
||||
return
|
||||
}
|
||||
dataMap["address"] = address
|
||||
}
|
||||
if v := r.FormValue("informations"); v != "" {
|
||||
dataMap["informations"] = v
|
||||
}
|
||||
if v := r.FormValue("licence_plate"); v != "" {
|
||||
dataMap["licence_plate"] = v
|
||||
}
|
||||
if v := r.FormValue("kilometers"); v != "" {
|
||||
dataMap["kilometers"] = v
|
||||
}
|
||||
if v := r.FormValue("automatic"); v != "" {
|
||||
dataMap["automatic"] = (v == "on")
|
||||
}
|
||||
|
||||
data, err := structpb.NewValue(dataMap)
|
||||
if err != nil {
|
||||
log.Error().Err(err).Msg("")
|
||||
w.WriteHeader(http.StatusInternalServerError)
|
||||
return
|
||||
}
|
||||
|
||||
request := &fleets.UpdateVehicleRequest{
|
||||
Vehicle: &fleets.Vehicle{
|
||||
Id: vehicleID,
|
||||
Namespace: namespaceV,
|
||||
Type: r.FormValue("type"),
|
||||
Administrators: administratorsV,
|
||||
Data: data.GetStructValue(),
|
||||
},
|
||||
}
|
||||
|
||||
resp, err := h.services.GRPC.Fleets.UpdateVehicle(context.TODO(), request)
|
||||
|
||||
if err != nil {
|
||||
log.Error().Err(err).Msg("")
|
||||
w.WriteHeader(http.StatusInternalServerError)
|
||||
return
|
||||
}
|
||||
|
||||
http.Redirect(w, r, fmt.Sprintf("/app/vehicles-management/fleet/%s", resp.Vehicle.Id), http.StatusFound)
|
||||
return
|
||||
}
|
||||
vehicles_types := h.config.GetStringSlice("modules.fleets.vehicle_types")
|
||||
h.Renderer.VehiclesFleetUpdate(w, r, resp.Vehicle.ToStorageType(), vehicles_types)
|
||||
}
|
||||
@@ -1,399 +0,0 @@
|
||||
package application
|
||||
|
||||
import (
|
||||
"context"
|
||||
"fmt"
|
||||
"io"
|
||||
"net/http"
|
||||
"sort"
|
||||
"strings"
|
||||
"time"
|
||||
|
||||
"git.coopgo.io/coopgo-apps/parcoursmob/utils/identification"
|
||||
"git.coopgo.io/coopgo-apps/parcoursmob/utils/sorting"
|
||||
filestorage "git.coopgo.io/coopgo-apps/parcoursmob/utils/storage"
|
||||
diags "git.coopgo.io/coopgo-platform/diags/grpcapi"
|
||||
diagsstorage "git.coopgo.io/coopgo-platform/diags/storage"
|
||||
fleets "git.coopgo.io/coopgo-platform/fleets/grpcapi"
|
||||
"git.coopgo.io/coopgo-platform/fleets/storage"
|
||||
groupsmanagement "git.coopgo.io/coopgo-platform/groups-management/grpcapi"
|
||||
groupsmanagementstorage "git.coopgo.io/coopgo-platform/groups-management/storage"
|
||||
mobilityaccounts "git.coopgo.io/coopgo-platform/mobility-accounts/grpcapi"
|
||||
mobilityaccountsstorage "git.coopgo.io/coopgo-platform/mobility-accounts/storage"
|
||||
"github.com/google/uuid"
|
||||
"github.com/gorilla/mux"
|
||||
"github.com/rs/zerolog/log"
|
||||
"google.golang.org/protobuf/types/known/structpb"
|
||||
"google.golang.org/protobuf/types/known/timestamppb"
|
||||
)
|
||||
|
||||
func (h ApplicationHandler) VehiclesSearch(w http.ResponseWriter, r *http.Request) {
|
||||
r.ParseForm()
|
||||
var beneficiary mobilityaccountsstorage.Account
|
||||
|
||||
beneficiarydocuments := []filestorage.FileInfo{}
|
||||
|
||||
vehicles := []any{}
|
||||
searched := false
|
||||
start := r.FormValue("startdate")
|
||||
end := r.FormValue("enddate")
|
||||
|
||||
startdate, _ := time.Parse("2006-01-02", start)
|
||||
enddate, _ := time.Parse("2006-01-02", end)
|
||||
automatic := (r.FormValue("automatic") == "on")
|
||||
|
||||
administrators := []string{}
|
||||
|
||||
if r.FormValue("beneficiaryid") != "" && startdate.After(time.Now()) && enddate.After(startdate) {
|
||||
// Handler form
|
||||
searched = true
|
||||
|
||||
requestbeneficiary := &mobilityaccounts.GetAccountRequest{
|
||||
Id: r.FormValue("beneficiaryid"),
|
||||
}
|
||||
|
||||
respbeneficiary, err := h.services.GRPC.MobilityAccounts.GetAccount(context.TODO(), requestbeneficiary)
|
||||
if err != nil {
|
||||
log.Error().Err(err).Msg("")
|
||||
w.WriteHeader(http.StatusInternalServerError)
|
||||
return
|
||||
}
|
||||
|
||||
beneficiary = respbeneficiary.Account.ToStorageType()
|
||||
|
||||
request := &fleets.GetVehiclesRequest{
|
||||
Namespaces: []string{"parcoursmob"},
|
||||
AvailabilityFrom: timestamppb.New(startdate),
|
||||
AvailabilityTo: timestamppb.New(enddate),
|
||||
}
|
||||
|
||||
if r.FormValue("type") != "" {
|
||||
request.Types = []string{r.FormValue("type")}
|
||||
}
|
||||
|
||||
resp, err := h.services.GRPC.Fleets.GetVehicles(context.TODO(), request)
|
||||
if err != nil {
|
||||
log.Error().Err(err).Msg("")
|
||||
w.WriteHeader(http.StatusInternalServerError)
|
||||
}
|
||||
|
||||
for _, vehicle := range resp.Vehicles {
|
||||
v := vehicle.ToStorageType()
|
||||
|
||||
if r.FormValue("type") == "Voiture" && automatic {
|
||||
if auto, ok := v.Data["automatic"].(bool); !ok || !auto {
|
||||
continue
|
||||
}
|
||||
}
|
||||
|
||||
adminfound := false
|
||||
for _, a := range administrators {
|
||||
if a == v.Administrators[0] {
|
||||
adminfound = true
|
||||
break
|
||||
}
|
||||
}
|
||||
if !adminfound {
|
||||
administrators = append(administrators, v.Administrators[0])
|
||||
}
|
||||
|
||||
vehicles = append(vehicles, v)
|
||||
}
|
||||
|
||||
beneficiarydocuments = h.filestorage.List(filestorage.PREFIX_BENEFICIARIES + "/" + beneficiary.ID)
|
||||
}
|
||||
|
||||
accounts, err := h.beneficiaries(r)
|
||||
if err != nil {
|
||||
log.Error().Err(err).Msg("")
|
||||
w.WriteHeader(http.StatusBadRequest)
|
||||
return
|
||||
}
|
||||
groups := map[string]any{}
|
||||
|
||||
if len(administrators) > 0 {
|
||||
admingroups, err := h.services.GRPC.GroupsManagement.GetGroupsBatch(context.TODO(), &groupsmanagement.GetGroupsBatchRequest{
|
||||
Groupids: administrators,
|
||||
})
|
||||
if err != nil {
|
||||
log.Error().Err(err).Msg("")
|
||||
w.WriteHeader(http.StatusInternalServerError)
|
||||
return
|
||||
}
|
||||
|
||||
for _, g := range admingroups.Groups {
|
||||
groups[g.Id] = g.ToStorageType()
|
||||
}
|
||||
|
||||
}
|
||||
sort.Sort(sorting.BeneficiariesByName(accounts))
|
||||
|
||||
mandatory_documents := h.config.GetStringSlice("modules.fleets.booking_documents.mandatory")
|
||||
file_types_map := h.config.GetStringMapString("storage.files.file_types")
|
||||
vehicles_types := h.config.GetStringSlice("modules.fleets.vehicle_types")
|
||||
|
||||
h.Renderer.VehiclesSearch(w, r, accounts, searched, vehicles, beneficiary, r.FormValue("startdate"), r.FormValue("enddate"), mandatory_documents, file_types_map, beneficiarydocuments, r.FormValue("type"), automatic, vehicles_types, groups)
|
||||
}
|
||||
|
||||
func (h ApplicationHandler) Book(w http.ResponseWriter, r *http.Request) {
|
||||
current_group, err := h.currentGroup(r)
|
||||
if err != nil {
|
||||
log.Error().Err(err).Msg("")
|
||||
w.WriteHeader(http.StatusInternalServerError)
|
||||
return
|
||||
}
|
||||
|
||||
current_user_token, current_user_claims, err := h.currentUser(r)
|
||||
if err != nil {
|
||||
log.Error().Err(err).Msg("")
|
||||
w.WriteHeader(http.StatusInternalServerError)
|
||||
return
|
||||
}
|
||||
|
||||
vars := mux.Vars(r)
|
||||
vehicleid := vars["vehicleid"]
|
||||
beneficiaryid := vars["beneficiaryid"]
|
||||
|
||||
vehicle, err := h.services.GRPC.Fleets.GetVehicle(context.TODO(), &fleets.GetVehicleRequest{
|
||||
Vehicleid: vehicleid,
|
||||
})
|
||||
if err != nil {
|
||||
log.Error().Err(err).Msg("")
|
||||
w.WriteHeader(http.StatusInternalServerError)
|
||||
w.Write([]byte("Vehicle not found"))
|
||||
w.Write([]byte(err.Error()))
|
||||
return
|
||||
}
|
||||
|
||||
r.ParseMultipartForm(100 * 1024 * 1024)
|
||||
|
||||
start := r.FormValue("startdate")
|
||||
end := r.FormValue("enddate")
|
||||
|
||||
startdate, _ := time.Parse("2006-01-02", start)
|
||||
enddate, _ := time.Parse("2006-01-02", end)
|
||||
|
||||
data := map[string]any{
|
||||
"booked_by": map[string]any{
|
||||
"user": map[string]any{
|
||||
"id": current_user_token.Subject,
|
||||
"display_name": fmt.Sprintf("%s %s", current_user_claims["first_name"], current_user_claims["last_name"]),
|
||||
},
|
||||
"group": map[string]any{
|
||||
"id": current_group.ID,
|
||||
"name": current_group.Data["name"],
|
||||
},
|
||||
},
|
||||
}
|
||||
datapb, err := structpb.NewStruct(data)
|
||||
if err != nil {
|
||||
log.Error().Err(err).Msg("")
|
||||
w.WriteHeader(http.StatusInternalServerError)
|
||||
return
|
||||
}
|
||||
|
||||
booking := &fleets.Booking{
|
||||
Id: uuid.NewString(),
|
||||
Vehicleid: vehicleid,
|
||||
Driver: beneficiaryid,
|
||||
Startdate: timestamppb.New(startdate),
|
||||
Enddate: timestamppb.New(enddate),
|
||||
Unavailablefrom: timestamppb.New(startdate),
|
||||
Unavailableto: timestamppb.New(enddate.Add(72 * time.Hour)),
|
||||
Data: datapb,
|
||||
}
|
||||
|
||||
request := &fleets.CreateBookingRequest{
|
||||
Booking: booking,
|
||||
}
|
||||
|
||||
for _, v := range h.config.GetStringSlice("modules.fleets.booking_documents.mandatory") {
|
||||
existing_file := r.FormValue("type-" + v)
|
||||
if existing_file == "" {
|
||||
file, header, err := r.FormFile("doc-" + v)
|
||||
if err != nil {
|
||||
log.Error().Err(err).Msg("")
|
||||
w.WriteHeader(http.StatusBadRequest)
|
||||
w.Write([]byte("Document manquant : " + v))
|
||||
return
|
||||
}
|
||||
defer file.Close()
|
||||
|
||||
fileid := uuid.NewString()
|
||||
|
||||
metadata := map[string]string{
|
||||
"type": v,
|
||||
"name": header.Filename,
|
||||
}
|
||||
|
||||
if err := h.filestorage.Put(file, filestorage.PREFIX_BOOKINGS, fmt.Sprintf("%s/%s_%s", booking.Id, fileid, header.Filename), header.Size, metadata); err != nil {
|
||||
log.Error().Err(err).Msg("")
|
||||
w.WriteHeader(http.StatusInternalServerError)
|
||||
return
|
||||
}
|
||||
} else {
|
||||
path := strings.Split(existing_file, "/")
|
||||
|
||||
if err := h.filestorage.Copy(existing_file, fmt.Sprintf("%s/%s/%s", filestorage.PREFIX_BOOKINGS, booking.Id, path[len(path)-1])); err != nil {
|
||||
log.Error().Err(err).Msg("")
|
||||
w.WriteHeader(http.StatusInternalServerError)
|
||||
return
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
_, err = h.services.GRPC.Fleets.CreateBooking(context.TODO(), request)
|
||||
if err != nil {
|
||||
log.Error().Err(err).Msg("")
|
||||
w.WriteHeader(http.StatusBadRequest)
|
||||
return
|
||||
}
|
||||
|
||||
// NOTIFY GROUP MEMBERS
|
||||
members, _, err := h.groupmembers(vehicle.Vehicle.Administrators[0])
|
||||
if err != nil {
|
||||
log.Error().Err(err).Msg("")
|
||||
} else {
|
||||
for _, m := range members {
|
||||
if email, ok := m.Data["email"].(string); ok {
|
||||
h.emailing.Send("fleets.bookings.creation_admin_alert", email, map[string]string{
|
||||
"bookingid": booking.Id,
|
||||
})
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
http.Redirect(w, r, fmt.Sprintf("/app/vehicles/bookings/%s", booking.Id), http.StatusFound)
|
||||
}
|
||||
|
||||
func (h ApplicationHandler) VehicleBookingDisplay(w http.ResponseWriter, r *http.Request) {
|
||||
vars := mux.Vars(r)
|
||||
bookingid := vars["bookingid"]
|
||||
|
||||
request := &fleets.GetBookingRequest{
|
||||
Bookingid: bookingid,
|
||||
}
|
||||
resp, err := h.services.GRPC.Fleets.GetBooking(context.TODO(), request)
|
||||
if err != nil {
|
||||
log.Error().Err(err).Msg("")
|
||||
w.WriteHeader(http.StatusInternalServerError)
|
||||
return
|
||||
}
|
||||
|
||||
booking := resp.Booking.ToStorageType()
|
||||
|
||||
beneficiaryrequest := &mobilityaccounts.GetAccountRequest{
|
||||
Id: booking.Driver,
|
||||
}
|
||||
|
||||
beneficiaryresp, err := h.services.GRPC.MobilityAccounts.GetAccount(context.TODO(), beneficiaryrequest)
|
||||
if err != nil {
|
||||
beneficiaryresp = &mobilityaccounts.GetAccountResponse{
|
||||
Account: &mobilityaccounts.Account{},
|
||||
}
|
||||
}
|
||||
|
||||
grouprequest := &groupsmanagement.GetGroupRequest{
|
||||
Id: booking.Vehicle.Administrators[0],
|
||||
}
|
||||
|
||||
groupresp, err := h.services.GRPC.GroupsManagement.GetGroup(context.TODO(), grouprequest)
|
||||
if err != nil {
|
||||
log.Error().Err(err).Msg("")
|
||||
w.WriteHeader(http.StatusInternalServerError)
|
||||
return
|
||||
}
|
||||
|
||||
documents := h.filestorage.List(filestorage.PREFIX_BOOKINGS + "/" + bookingid)
|
||||
file_types_map := h.config.GetStringMapString("storage.files.file_types")
|
||||
|
||||
diag := []diagsstorage.Diag{}
|
||||
|
||||
diagsrequest := &diags.GetDiagsRequest{
|
||||
Namespaces: []string{"parcoursmob_bookings"},
|
||||
}
|
||||
|
||||
diagsresp, err := h.services.GRPC.Diags.GetDiags(context.TODO(), diagsrequest)
|
||||
if err != nil {
|
||||
log.Error().Err(err).Msg("")
|
||||
w.WriteHeader(http.StatusInternalServerError)
|
||||
return
|
||||
}
|
||||
|
||||
for _, d := range diagsresp.Diags {
|
||||
diagData := d.Data.AsMap()
|
||||
if booking, ok := diagData["booking"].(string); ok && booking == bookingid {
|
||||
diag = append(diag, d.ToStorageType())
|
||||
}
|
||||
}
|
||||
|
||||
diagsAny := make([]any, len(diag))
|
||||
for i, d := range diag {
|
||||
diagsAny[i] = d
|
||||
}
|
||||
|
||||
h.Renderer.VehicleBookingDisplay(w, r, booking, booking.Vehicle, beneficiaryresp.Account.ToStorageType(), groupresp.Group.ToStorageType(), documents, file_types_map, diagsAny)
|
||||
}
|
||||
|
||||
func (h ApplicationHandler) VehiclesBookingsList(w http.ResponseWriter, r *http.Request) {
|
||||
g := r.Context().Value(identification.GroupKey)
|
||||
if g == nil {
|
||||
w.WriteHeader(http.StatusBadRequest)
|
||||
return
|
||||
}
|
||||
|
||||
group := g.(groupsmanagementstorage.Group)
|
||||
|
||||
request := &fleets.GetBookingsRequest{}
|
||||
resp, err := h.services.GRPC.Fleets.GetBookings(context.TODO(), request)
|
||||
if err != nil {
|
||||
log.Error().Err(err).Msg("")
|
||||
w.WriteHeader(http.StatusNotFound)
|
||||
return
|
||||
}
|
||||
|
||||
bookings := []storage.Booking{}
|
||||
|
||||
for _, b := range resp.Bookings {
|
||||
booking := b.ToStorageType()
|
||||
if b1, ok := booking.Data["booked_by"].(map[string]any); ok {
|
||||
if b2, ok := b1["group"].(map[string]any); ok {
|
||||
if b2["id"] == group.ID {
|
||||
bookings = append(bookings, booking)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
sort.Sort(sorting.BookingsByStartdate(bookings))
|
||||
|
||||
vehicles, _ := h.services.GetVehiclesMap()
|
||||
groups, _ := h.services.GetGroupsMap()
|
||||
|
||||
h.Renderer.VehicleBookingsList(w, r, bookings, vehicles, groups)
|
||||
}
|
||||
|
||||
func (h *ApplicationHandler) BookingDocumentDownload(w http.ResponseWriter, r *http.Request) {
|
||||
vars := mux.Vars(r)
|
||||
bookingid := vars["bookingid"]
|
||||
document := vars["document"]
|
||||
|
||||
log.Debug().Str("booking id", bookingid).Str("document", document).Msg("Document and booking ID")
|
||||
|
||||
file, info, err := h.filestorage.Get(filestorage.PREFIX_BOOKINGS, fmt.Sprintf("%s/%s", bookingid, document))
|
||||
if err != nil {
|
||||
log.Error().Err(err).Msg("")
|
||||
w.WriteHeader(http.StatusInternalServerError)
|
||||
return
|
||||
}
|
||||
|
||||
w.Header().Set("Content-Type", info.ContentType)
|
||||
if _, err = io.Copy(w, file); err != nil {
|
||||
log.Error().Err(err).Msg("")
|
||||
w.WriteHeader(http.StatusInternalServerError)
|
||||
return
|
||||
}
|
||||
|
||||
http.Redirect(w, r, fmt.Sprintf("/app/vehicles/bookings/%s", bookingid), http.StatusFound)
|
||||
}
|
||||
@@ -1,32 +0,0 @@
|
||||
package auth
|
||||
|
||||
import (
|
||||
"git.coopgo.io/coopgo-apps/parcoursmob/renderer"
|
||||
"git.coopgo.io/coopgo-apps/parcoursmob/services"
|
||||
"git.coopgo.io/coopgo-apps/parcoursmob/utils/identification"
|
||||
cache "git.coopgo.io/coopgo-apps/parcoursmob/utils/storage"
|
||||
"git.coopgo.io/coopgo-platform/emailing"
|
||||
"github.com/spf13/viper"
|
||||
)
|
||||
|
||||
type AuthHandler struct {
|
||||
idp *identification.IdentificationProvider
|
||||
config *viper.Viper
|
||||
services *services.ServicesHandler
|
||||
Renderer *renderer.Renderer
|
||||
cache cache.CacheHandler
|
||||
emailing *emailing.Mailer
|
||||
}
|
||||
|
||||
func NewAuthHandler(cfg *viper.Viper, idp *identification.IdentificationProvider, svc *services.ServicesHandler, cache cache.CacheHandler, emailing *emailing.Mailer) (*AuthHandler, error) {
|
||||
templates_root := cfg.GetString("templates.root")
|
||||
renderer := renderer.NewRenderer(cfg, templates_root)
|
||||
return &AuthHandler{
|
||||
idp: idp,
|
||||
config: cfg,
|
||||
services: svc,
|
||||
Renderer: renderer,
|
||||
cache: cache,
|
||||
emailing: emailing,
|
||||
}, nil
|
||||
}
|
||||
@@ -1,91 +0,0 @@
|
||||
package auth
|
||||
|
||||
import (
|
||||
"context"
|
||||
"net/http"
|
||||
|
||||
groupsmanagement "git.coopgo.io/coopgo-platform/groups-management/grpcapi"
|
||||
"github.com/rs/zerolog/log"
|
||||
)
|
||||
|
||||
func (h *AuthHandler) Groups(w http.ResponseWriter, r *http.Request) {
|
||||
session, _ := h.idp.SessionsStore.Get(r, "parcoursmob_session")
|
||||
|
||||
if r.Method == "POST" {
|
||||
r.ParseForm()
|
||||
|
||||
groupid := r.FormValue("group")
|
||||
|
||||
session.Values["organization"] = groupid
|
||||
session.Save(r, w)
|
||||
|
||||
http.Redirect(w, r, "/app/", http.StatusFound)
|
||||
|
||||
return
|
||||
}
|
||||
|
||||
tokenstring, ok := session.Values["idtoken"]
|
||||
|
||||
if !ok {
|
||||
http.Redirect(w, r, "/app/", http.StatusFound)
|
||||
return
|
||||
}
|
||||
|
||||
idtoken, err := h.idp.TokenVerifier.Verify(context.Background(), tokenstring.(string))
|
||||
if err != nil {
|
||||
delete(session.Values, "idtoken")
|
||||
http.Redirect(w, r, "/app/", http.StatusFound)
|
||||
return
|
||||
}
|
||||
|
||||
var claims map[string]any
|
||||
|
||||
err = idtoken.Claims(&claims)
|
||||
if err != nil {
|
||||
log.Error().Err(err).Msg("")
|
||||
}
|
||||
|
||||
g := claims["groups"]
|
||||
|
||||
groups_interface, ok := g.([]any)
|
||||
if !ok {
|
||||
w.WriteHeader(http.StatusInternalServerError)
|
||||
return
|
||||
}
|
||||
|
||||
groups := []string{}
|
||||
|
||||
for _, v := range groups_interface {
|
||||
groups = append(groups, v.(string))
|
||||
}
|
||||
|
||||
request := &groupsmanagement.GetGroupsBatchRequest{
|
||||
Groupids: groups,
|
||||
}
|
||||
|
||||
resp, err := h.services.GRPC.GroupsManagement.GetGroupsBatch(context.TODO(), request)
|
||||
if err != nil {
|
||||
log.Error().Err(err).Msg("")
|
||||
w.WriteHeader(http.StatusInternalServerError)
|
||||
return
|
||||
}
|
||||
|
||||
var groupsresponse = []any{}
|
||||
|
||||
for _, group := range resp.Groups {
|
||||
if group.Namespace != "parcoursmob_organizations" {
|
||||
continue
|
||||
}
|
||||
g := group.ToStorageType()
|
||||
groupsresponse = append(groupsresponse, g)
|
||||
}
|
||||
|
||||
h.Renderer.AuthGroups(w, r, groupsresponse)
|
||||
}
|
||||
|
||||
func (h *AuthHandler) GroupSwitch(w http.ResponseWriter, r *http.Request) {
|
||||
session, _ := h.idp.SessionsStore.Get(r, "parcoursmob_session")
|
||||
delete(session.Values, "organization")
|
||||
session.Save(r, w)
|
||||
http.Redirect(w, r, "/app/", http.StatusFound)
|
||||
}
|
||||
@@ -1,97 +0,0 @@
|
||||
package auth
|
||||
|
||||
import (
|
||||
"context"
|
||||
"crypto/rand"
|
||||
"encoding/base64"
|
||||
"io"
|
||||
"net/http"
|
||||
"time"
|
||||
|
||||
"git.coopgo.io/coopgo-platform/mobility-accounts/grpcapi"
|
||||
"github.com/rs/zerolog/log"
|
||||
)
|
||||
|
||||
func (h *AuthHandler) LostPasswordInit(w http.ResponseWriter, r *http.Request) {
|
||||
if r.Method == "POST" {
|
||||
r.ParseForm()
|
||||
email := r.FormValue("email")
|
||||
if email != "" {
|
||||
account, err := h.services.GRPC.MobilityAccounts.GetAccountUsername(context.TODO(), &grpcapi.GetAccountUsernameRequest{
|
||||
Username: email,
|
||||
Namespace: "parcoursmob",
|
||||
})
|
||||
if err != nil {
|
||||
log.Error().Err(err).Msg("")
|
||||
http.Redirect(w, r, "/app/", http.StatusFound)
|
||||
return
|
||||
}
|
||||
|
||||
b := make([]byte, 16)
|
||||
if _, err := io.ReadFull(rand.Reader, b); err != nil {
|
||||
log.Error().Err(err).Msg("")
|
||||
w.WriteHeader(http.StatusInternalServerError)
|
||||
return
|
||||
}
|
||||
key := base64.RawURLEncoding.EncodeToString(b)
|
||||
|
||||
passwordretrieval := map[string]any{
|
||||
"username": email,
|
||||
"account_id": account.Account.Id,
|
||||
"key": key,
|
||||
}
|
||||
|
||||
h.cache.PutWithTTL("retrieve-password/"+key, passwordretrieval, 72*time.Hour)
|
||||
|
||||
if err := h.emailing.Send("auth.retrieve_password", email, passwordretrieval); err != nil {
|
||||
log.Error().Err(err).Msg("")
|
||||
w.WriteHeader(http.StatusInternalServerError)
|
||||
return
|
||||
}
|
||||
|
||||
http.Redirect(w, r, "/app/", http.StatusFound)
|
||||
}
|
||||
}
|
||||
h.Renderer.LostPasswordInit(w, r)
|
||||
|
||||
}
|
||||
|
||||
func (h *AuthHandler) LostPasswordRecover(w http.ResponseWriter, r *http.Request) {
|
||||
r.ParseForm()
|
||||
|
||||
key := r.FormValue("key")
|
||||
recover, err := h.cache.Get("retrieve-password/" + key)
|
||||
if err != nil {
|
||||
log.Error().Err(err).Msg("")
|
||||
h.Renderer.LostPasswordRecoverKO(w, r, key)
|
||||
return
|
||||
}
|
||||
|
||||
if r.Method == "POST" {
|
||||
newpassword := r.FormValue("password")
|
||||
if newpassword == "" {
|
||||
w.WriteHeader(http.StatusInternalServerError)
|
||||
w.Write([]byte("Password is empty"))
|
||||
return
|
||||
}
|
||||
|
||||
_, err := h.services.GRPC.MobilityAccounts.ChangePassword(context.TODO(), &grpcapi.ChangePasswordRequest{
|
||||
Id: recover.(map[string]any)["account_id"].(string),
|
||||
Password: newpassword,
|
||||
})
|
||||
|
||||
if err != nil {
|
||||
log.Error().Err(err).Msg("")
|
||||
w.WriteHeader(http.StatusInternalServerError)
|
||||
}
|
||||
|
||||
err = h.cache.Delete("retrieve-password/" + key)
|
||||
if err != nil {
|
||||
log.Error().Err(err).Msg("")
|
||||
}
|
||||
|
||||
http.Redirect(w, r, "/app/", http.StatusFound)
|
||||
|
||||
}
|
||||
h.Renderer.LostPasswordRecover(w, r, recover)
|
||||
}
|
||||
@@ -1,88 +0,0 @@
|
||||
package auth
|
||||
|
||||
import (
|
||||
"context"
|
||||
"fmt"
|
||||
"net/http"
|
||||
|
||||
mobilityaccounts "git.coopgo.io/coopgo-platform/mobility-accounts/grpcapi"
|
||||
ma "git.coopgo.io/coopgo-platform/mobility-accounts/storage"
|
||||
"github.com/rs/zerolog/log"
|
||||
)
|
||||
|
||||
func (h *AuthHandler) Onboarding(w http.ResponseWriter, r *http.Request) {
|
||||
r.ParseForm()
|
||||
|
||||
key := r.FormValue("key")
|
||||
onboarding, err := h.cache.Get("onboarding/" + key)
|
||||
if err != nil {
|
||||
log.Error().Err(err).Msg("")
|
||||
h.Renderer.AuthOnboardingKO(w, r, key)
|
||||
return
|
||||
}
|
||||
|
||||
onboardingmap := onboarding.(map[string]any)
|
||||
|
||||
if r.Method == "POST" {
|
||||
if r.FormValue("password") == "" {
|
||||
log.Error().Msg("Password is empty")
|
||||
w.WriteHeader(http.StatusInternalServerError)
|
||||
return
|
||||
}
|
||||
|
||||
groups := []string{
|
||||
onboardingmap["group"].(string),
|
||||
//onboardingmap["group"].(string) + ":admin",
|
||||
}
|
||||
|
||||
if onboardingmap["admin"].(bool) {
|
||||
groups = append(groups, onboardingmap["group"].(string)+":admin")
|
||||
}
|
||||
display_name := fmt.Sprint(r.FormValue("first_name")) + " " + fmt.Sprint(r.FormValue("last_name"))
|
||||
account := &ma.Account{
|
||||
Authentication: ma.AccountAuth{
|
||||
Local: ma.LocalAuth{
|
||||
Username: onboardingmap["username"].(string),
|
||||
Password: r.FormValue("password"),
|
||||
},
|
||||
},
|
||||
Namespace: "parcoursmob",
|
||||
|
||||
Data: map[string]any{
|
||||
"display_name": display_name,
|
||||
"first_name": r.FormValue("first_name"),
|
||||
"last_name": r.FormValue("last_name"),
|
||||
"email": onboardingmap["username"],
|
||||
"groups": groups,
|
||||
},
|
||||
}
|
||||
|
||||
acc, err := mobilityaccounts.AccountFromStorageType(account)
|
||||
if err != nil {
|
||||
log.Error().Err(err).Msg("")
|
||||
w.WriteHeader(http.StatusInternalServerError)
|
||||
return
|
||||
}
|
||||
|
||||
request := &mobilityaccounts.RegisterRequest{
|
||||
Account: acc,
|
||||
}
|
||||
|
||||
_, err = h.services.GRPC.MobilityAccounts.Register(context.TODO(), request)
|
||||
|
||||
if err != nil {
|
||||
log.Error().Err(err).Msg("")
|
||||
w.WriteHeader(http.StatusInternalServerError)
|
||||
return
|
||||
}
|
||||
|
||||
err = h.cache.Delete("onboarding/" + key)
|
||||
if err != nil {
|
||||
log.Error().Err(err).Msg("")
|
||||
}
|
||||
|
||||
http.Redirect(w, r, "/app/", http.StatusFound)
|
||||
}
|
||||
|
||||
h.Renderer.AuthOnboarding(w, r, key, onboarding)
|
||||
}
|
||||
@@ -1,198 +0,0 @@
|
||||
package exports
|
||||
|
||||
import (
|
||||
"context"
|
||||
"fmt"
|
||||
"net/http"
|
||||
"sort"
|
||||
|
||||
"git.coopgo.io/coopgo-apps/parcoursmob/utils/sorting"
|
||||
agenda "git.coopgo.io/coopgo-platform/agenda/grpcapi"
|
||||
agendastorage "git.coopgo.io/coopgo-platform/agenda/storage"
|
||||
groupsmanagement "git.coopgo.io/coopgo-platform/groups-management/grpcapi"
|
||||
groupsstorage "git.coopgo.io/coopgo-platform/groups-management/storage"
|
||||
accounts "git.coopgo.io/coopgo-platform/mobility-accounts/grpcapi"
|
||||
accountsstorage "git.coopgo.io/coopgo-platform/mobility-accounts/storage"
|
||||
"github.com/gorilla/mux"
|
||||
"github.com/rs/zerolog/log"
|
||||
"github.com/xuri/excelize/v2"
|
||||
)
|
||||
|
||||
func (h *ExportsHandler) Agenda(filter string) func(w http.ResponseWriter, r *http.Request) {
|
||||
switch filter {
|
||||
case "allEvents":
|
||||
return func(w http.ResponseWriter, r *http.Request) {
|
||||
resp, err := h.services.GRPC.Agenda.GetEvents(context.TODO(), &agenda.GetEventsRequest{
|
||||
Namespaces: []string{"parcoursmob_dispositifs"},
|
||||
})
|
||||
if err != nil {
|
||||
log.Error().Err(err).Msg("")
|
||||
w.WriteHeader(http.StatusInternalServerError)
|
||||
return
|
||||
}
|
||||
|
||||
events := []agendastorage.Event{}
|
||||
|
||||
groupids := []string{}
|
||||
beneficiaries_ids := []string{}
|
||||
for _, e := range resp.Events {
|
||||
groupids = append(groupids, e.Owners...)
|
||||
events = append(events, e.ToStorageType())
|
||||
|
||||
for _, subscriptions := range e.Subscriptions {
|
||||
beneficiaries_ids = append(beneficiaries_ids, subscriptions.Subscriber)
|
||||
}
|
||||
}
|
||||
|
||||
sort.Sort(sorting.EventsByStartdate(events))
|
||||
|
||||
groupsresp, err := h.services.GRPC.GroupsManagement.GetGroupsBatch(context.TODO(), &groupsmanagement.GetGroupsBatchRequest{
|
||||
Groupids: groupids,
|
||||
})
|
||||
groups := map[string]groupsstorage.Group{}
|
||||
|
||||
if err == nil {
|
||||
for _, g := range groupsresp.Groups {
|
||||
groups[g.Id] = g.ToStorageType()
|
||||
}
|
||||
}
|
||||
|
||||
beneficiaries, err := h.services.GRPC.MobilityAccounts.GetAccountsBatch(context.TODO(), &accounts.GetAccountsBatchRequest{
|
||||
Accountids: beneficiaries_ids,
|
||||
})
|
||||
if err != nil {
|
||||
log.Error().Err(err).Msg("")
|
||||
w.WriteHeader(http.StatusInternalServerError)
|
||||
return
|
||||
}
|
||||
|
||||
beneficiaries_map := map[string]accountsstorage.Account{}
|
||||
for _, ben := range beneficiaries.Accounts {
|
||||
beneficiaries_map[ben.Id] = ben.ToStorageType()
|
||||
}
|
||||
|
||||
f := h.generateExcel(events, groups, beneficiaries_map)
|
||||
|
||||
h.writeFileResponse(f, w)
|
||||
}
|
||||
|
||||
case "oneEvent":
|
||||
return func(w http.ResponseWriter, r *http.Request) {
|
||||
vars := mux.Vars(r)
|
||||
eventId := vars["eventid"]
|
||||
resp, err := h.services.GRPC.Agenda.GetEvent(context.TODO(), &agenda.GetEventRequest{
|
||||
Id: eventId,
|
||||
})
|
||||
if err != nil {
|
||||
log.Error().Err(err).Msg("")
|
||||
w.WriteHeader(http.StatusInternalServerError)
|
||||
return
|
||||
}
|
||||
groupids := []string{}
|
||||
beneficiaries_ids := []string{}
|
||||
groupids = append(groupids, resp.Event.Owners...)
|
||||
for _, subscriptions := range resp.Event.Subscriptions {
|
||||
beneficiaries_ids = append(beneficiaries_ids, subscriptions.Subscriber)
|
||||
}
|
||||
groupsresp, err := h.services.GRPC.GroupsManagement.GetGroupsBatch(context.TODO(), &groupsmanagement.GetGroupsBatchRequest{
|
||||
Groupids: groupids,
|
||||
})
|
||||
groups := map[string]groupsstorage.Group{}
|
||||
|
||||
if err == nil {
|
||||
for _, g := range groupsresp.Groups {
|
||||
groups[g.Id] = g.ToStorageType()
|
||||
}
|
||||
}
|
||||
|
||||
beneficiaries, err := h.services.GRPC.MobilityAccounts.GetAccountsBatch(context.TODO(), &accounts.GetAccountsBatchRequest{
|
||||
Accountids: beneficiaries_ids,
|
||||
})
|
||||
if err != nil {
|
||||
log.Error().Err(err).Msg("")
|
||||
w.WriteHeader(http.StatusInternalServerError)
|
||||
return
|
||||
}
|
||||
|
||||
beneficiaries_map := map[string]accountsstorage.Account{}
|
||||
for _, ben := range beneficiaries.Accounts {
|
||||
beneficiaries_map[ben.Id] = ben.ToStorageType()
|
||||
}
|
||||
|
||||
f := h.generateExcel([]agendastorage.Event{resp.Event.ToStorageType()}, groups, beneficiaries_map)
|
||||
h.writeFileResponse(f, w)
|
||||
|
||||
}
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
func (h *ExportsHandler) generateExcel(events []agendastorage.Event, groups map[string]groupsstorage.Group,
|
||||
beneficiaries_map map[string]accountsstorage.Account) *excelize.File {
|
||||
f := excelize.NewFile()
|
||||
defer func() {
|
||||
if err := f.Close(); err != nil {
|
||||
log.Error().Err(err).Msg("")
|
||||
}
|
||||
}()
|
||||
f.SetCellValue("Sheet1", "A1", "Evénement")
|
||||
f.SetCellValue("Sheet1", "B1", "Date de début")
|
||||
f.SetCellValue("Sheet1", "C1", "Date de fin")
|
||||
f.SetCellValue("Sheet1", "D1", "Nom bénéficiaire")
|
||||
f.SetCellValue("Sheet1", "E1", "Prenom bénéficiaire")
|
||||
f.SetCellValue("Sheet1", "F1", "Numéro allocataire / Pole emploi")
|
||||
f.SetCellValue("Sheet1", "G1", "Prescipteur")
|
||||
f.SetCellValue("Sheet1", "H1", "Prescipteur Nom")
|
||||
f.SetCellValue("Sheet1", "I1", "Gestionnaire événement")
|
||||
i := 2
|
||||
for _, e := range events {
|
||||
if len(e.Owners) == 0 {
|
||||
continue
|
||||
}
|
||||
admin := groups[e.Owners[0]]
|
||||
|
||||
subscribedbygroup := ""
|
||||
subscribedbyuser := ""
|
||||
if v, ok := e.Data["subscribed_by"].(map[string]any); ok {
|
||||
if v2, ok := v["group"].(map[string]any); ok {
|
||||
if v3, ok := v2["id"].(string); ok {
|
||||
subscribedbygroup = v3
|
||||
}
|
||||
|
||||
}
|
||||
if v4, ok := v["user"].(map[string]any); ok {
|
||||
if v5, ok := v4["display_name"].(string); ok {
|
||||
subscribedbyuser = v5
|
||||
}
|
||||
|
||||
}
|
||||
}
|
||||
|
||||
for _, s := range e.Subscriptions {
|
||||
|
||||
beneficiary := beneficiaries_map[s.Subscriber]
|
||||
|
||||
f.SetCellValue("Sheet1", fmt.Sprintf("A%d", i), e.Name)
|
||||
f.SetCellValue("Sheet1", fmt.Sprintf("B%d", i), e.Startdate.Format("2006-01-02"))
|
||||
f.SetCellValue("Sheet1", fmt.Sprintf("C%d", i), e.Enddate.Format("2006-01-02"))
|
||||
f.SetCellValue("Sheet1", fmt.Sprintf("D%d", i), beneficiary.Data["last_name"])
|
||||
f.SetCellValue("Sheet1", fmt.Sprintf("E%d", i), beneficiary.Data["first_name"])
|
||||
f.SetCellValue("Sheet1", fmt.Sprintf("F%d", i), beneficiary.Data["file_number"])
|
||||
f.SetCellValue("Sheet1", fmt.Sprintf("G%d", i), groups[subscribedbygroup].Data["name"])
|
||||
f.SetCellValue("Sheet1", fmt.Sprintf("H%d", i), subscribedbyuser)
|
||||
f.SetCellValue("Sheet1", fmt.Sprintf("I%d", i), admin.Data["name"])
|
||||
i = i + 1
|
||||
}
|
||||
|
||||
}
|
||||
return f
|
||||
|
||||
}
|
||||
|
||||
func (h *ExportsHandler) writeFileResponse(file *excelize.File, w http.ResponseWriter) {
|
||||
w.Header().Set("Content-Type", "application/octet-stream")
|
||||
w.Header().Set("Content-Disposition", "attachment; filename="+"Workbook.xlsx")
|
||||
w.Header().Set("Content-Transfer-Encoding", "binary")
|
||||
w.Header().Set("Expires", "0")
|
||||
file.Write(w)
|
||||
}
|
||||
@@ -1,21 +0,0 @@
|
||||
package exports
|
||||
|
||||
import (
|
||||
"git.coopgo.io/coopgo-apps/parcoursmob/services"
|
||||
"git.coopgo.io/coopgo-platform/emailing"
|
||||
"github.com/spf13/viper"
|
||||
)
|
||||
|
||||
type ExportsHandler struct {
|
||||
config *viper.Viper
|
||||
services *services.ServicesHandler
|
||||
emailing *emailing.Mailer
|
||||
}
|
||||
|
||||
func NewExportsHandler(cfg *viper.Viper, svc *services.ServicesHandler, emailing *emailing.Mailer) (*ExportsHandler, error) {
|
||||
return &ExportsHandler{
|
||||
config: cfg,
|
||||
services: svc,
|
||||
emailing: emailing,
|
||||
}, nil
|
||||
}
|
||||
@@ -1,162 +0,0 @@
|
||||
package exports
|
||||
|
||||
import (
|
||||
"context"
|
||||
"fmt"
|
||||
"net/http"
|
||||
|
||||
"git.coopgo.io/coopgo-apps/parcoursmob/utils/identification"
|
||||
fleets "git.coopgo.io/coopgo-platform/fleets/grpcapi"
|
||||
fleetsstorage "git.coopgo.io/coopgo-platform/fleets/storage"
|
||||
groupsmanagement "git.coopgo.io/coopgo-platform/groups-management/grpcapi"
|
||||
groupsstorage "git.coopgo.io/coopgo-platform/groups-management/storage"
|
||||
accounts "git.coopgo.io/coopgo-platform/mobility-accounts/grpcapi"
|
||||
accountsstorage "git.coopgo.io/coopgo-platform/mobility-accounts/storage"
|
||||
"github.com/rs/zerolog/log"
|
||||
"github.com/xuri/excelize/v2"
|
||||
)
|
||||
|
||||
func (h *ExportsHandler) Bookings(w http.ResponseWriter, r *http.Request) {
|
||||
|
||||
vehicles := map[string]fleetsstorage.Vehicle{}
|
||||
bookings := []fleetsstorage.Booking{}
|
||||
reequest := &fleets.GetVehiclesRequest{
|
||||
Namespaces: []string{"parcoursmob"},
|
||||
}
|
||||
reesp, err := h.services.GRPC.Fleets.GetVehicles(context.TODO(), reequest)
|
||||
if err != nil {
|
||||
log.Error().Err(err).Msg("")
|
||||
w.WriteHeader(http.StatusInternalServerError)
|
||||
return
|
||||
}
|
||||
|
||||
beneficiaries_ids := []string{}
|
||||
|
||||
for _, vehicle := range reesp.Vehicles {
|
||||
|
||||
v := vehicle.ToStorageType()
|
||||
|
||||
for _, b := range v.Bookings {
|
||||
bookings = append(bookings, b)
|
||||
beneficiaries_ids = append(beneficiaries_ids, b.Driver)
|
||||
}
|
||||
|
||||
vehicles[vehicle.Id] = v
|
||||
|
||||
}
|
||||
|
||||
groups := map[string]groupsstorage.Group{}
|
||||
|
||||
admingroups, err := h.services.GRPC.GroupsManagement.GetGroups(context.TODO(), &groupsmanagement.GetGroupsRequest{
|
||||
Namespaces: []string{"parcoursmob_organizations"},
|
||||
})
|
||||
if err != nil {
|
||||
log.Error().Err(err).Msg("")
|
||||
w.WriteHeader(http.StatusInternalServerError)
|
||||
return
|
||||
}
|
||||
|
||||
for _, g := range admingroups.Groups {
|
||||
groups[g.Id] = g.ToStorageType()
|
||||
}
|
||||
|
||||
beneficiaries, err := h.services.GRPC.MobilityAccounts.GetAccountsBatch(context.TODO(), &accounts.GetAccountsBatchRequest{
|
||||
Accountids: beneficiaries_ids,
|
||||
})
|
||||
if err != nil {
|
||||
log.Error().Err(err).Msg("")
|
||||
w.WriteHeader(http.StatusInternalServerError)
|
||||
return
|
||||
}
|
||||
|
||||
beneficiaries_map := map[string]accountsstorage.Account{}
|
||||
for _, ben := range beneficiaries.Accounts {
|
||||
beneficiaries_map[ben.Id] = ben.ToStorageType()
|
||||
}
|
||||
|
||||
/////////////// Generate file
|
||||
|
||||
f := excelize.NewFile()
|
||||
defer func() {
|
||||
if err := f.Close(); err != nil {
|
||||
log.Error().Err(err).Msg("")
|
||||
}
|
||||
}()
|
||||
|
||||
f.SetCellValue("Sheet1", "A1", "Numéro")
|
||||
f.SetCellValue("Sheet1", "B1", "Type")
|
||||
f.SetCellValue("Sheet1", "C1", "Gestionnaire")
|
||||
f.SetCellValue("Sheet1", "D1", "Prescripteur")
|
||||
f.SetCellValue("Sheet1", "E1", "Bénéficiaire")
|
||||
f.SetCellValue("Sheet1", "F1", "Numéro allocataire / Pole emploi")
|
||||
f.SetCellValue("Sheet1", "G1", "Début de Mise à disposition")
|
||||
f.SetCellValue("Sheet1", "H1", "Fin de mise Ă disposition")
|
||||
f.SetCellValue("Sheet1", "I1", "Début indisponibilité")
|
||||
f.SetCellValue("Sheet1", "J1", "Fin indisponibilité")
|
||||
f.SetCellValue("Sheet1", "K1", "Retrait par le gestionnaire")
|
||||
f.SetCellValue("Sheet1", "L1", "Commentaire")
|
||||
|
||||
i := 2
|
||||
for _, b := range bookings {
|
||||
vehicle := vehicles[b.Vehicleid]
|
||||
if len(vehicle.Administrators) == 0 {
|
||||
continue
|
||||
}
|
||||
admin := groups[vehicle.Administrators[0]]
|
||||
|
||||
bookedby := ""
|
||||
if v, ok := b.Data["booked_by"].(map[string]any); ok {
|
||||
if v2, ok := v["user"].(map[string]any); ok {
|
||||
if v3, ok := v2["display_name"].(string); ok {
|
||||
bookedby = v3
|
||||
}
|
||||
|
||||
}
|
||||
}
|
||||
|
||||
bookedbygroup := ""
|
||||
if v4, ok := b.Data["booked_by"].(map[string]any); ok {
|
||||
if v5, ok := v4["group"].(map[string]any); ok {
|
||||
if v6, ok := v5["id"].(string); ok {
|
||||
bookedbygroup = v6
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// filter by group
|
||||
g := r.Context().Value(identification.GroupKey)
|
||||
group := g.(groupsstorage.Group)
|
||||
|
||||
if bookedbygroup != group.ID {
|
||||
continue
|
||||
}
|
||||
|
||||
beneficiary := beneficiaries_map[b.Driver]
|
||||
adminunavailability := false
|
||||
|
||||
if av, ok := b.Data["administrator_unavailability"].(bool); ok && av {
|
||||
adminunavailability = true
|
||||
}
|
||||
|
||||
f.SetCellValue("Sheet1", fmt.Sprintf("A%d", i), vehicle.Data["licence_plate"])
|
||||
f.SetCellValue("Sheet1", fmt.Sprintf("B%d", i), vehicle.Type)
|
||||
f.SetCellValue("Sheet1", fmt.Sprintf("C%d", i), admin.Data["name"])
|
||||
f.SetCellValue("Sheet1", fmt.Sprintf("D%d", i), bookedby)
|
||||
f.SetCellValue("Sheet1", fmt.Sprintf("E%d", i), fmt.Sprintf("%v %v", beneficiary.Data["first_name"], beneficiary.Data["last_name"]))
|
||||
f.SetCellValue("Sheet1", fmt.Sprintf("F%d", i), beneficiary.Data["file_number"])
|
||||
f.SetCellValue("Sheet1", fmt.Sprintf("G%d", i), b.Startdate.Format("2006-01-02"))
|
||||
f.SetCellValue("Sheet1", fmt.Sprintf("H%d", i), b.Enddate.Format("2006-01-02"))
|
||||
f.SetCellValue("Sheet1", fmt.Sprintf("I%d", i), b.Unavailablefrom.Format("2006-01-02"))
|
||||
f.SetCellValue("Sheet1", fmt.Sprintf("J%d", i), b.Unavailableto.Format("2006-01-02"))
|
||||
f.SetCellValue("Sheet1", fmt.Sprintf("K%d", i), adminunavailability)
|
||||
f.SetCellValue("Sheet1", fmt.Sprintf("L%d", i), b.Data["comment"])
|
||||
i = i + 1
|
||||
}
|
||||
|
||||
w.Header().Set("Content-Type", "application/octet-stream")
|
||||
w.Header().Set("Content-Disposition", "attachment; filename="+"Workbook.xlsx")
|
||||
w.Header().Set("Content-Transfer-Encoding", "binary")
|
||||
w.Header().Set("Expires", "0")
|
||||
f.Write(w)
|
||||
|
||||
}
|
||||
213
main.go
213
main.go
@@ -1,42 +1,38 @@
|
||||
package main
|
||||
|
||||
import (
|
||||
"net/http"
|
||||
"os"
|
||||
"time"
|
||||
"sync"
|
||||
|
||||
"github.com/rs/zerolog"
|
||||
"github.com/rs/zerolog/log"
|
||||
|
||||
"git.coopgo.io/coopgo-apps/parcoursmob/handlers/api"
|
||||
"git.coopgo.io/coopgo-apps/parcoursmob/handlers/application"
|
||||
"git.coopgo.io/coopgo-apps/parcoursmob/handlers/auth"
|
||||
"git.coopgo.io/coopgo-apps/parcoursmob/handlers/exports"
|
||||
"git.coopgo.io/coopgo-apps/parcoursmob/core/application"
|
||||
"git.coopgo.io/coopgo-apps/parcoursmob/renderer"
|
||||
"git.coopgo.io/coopgo-apps/parcoursmob/servers/mcp"
|
||||
"git.coopgo.io/coopgo-apps/parcoursmob/servers/web"
|
||||
"git.coopgo.io/coopgo-apps/parcoursmob/services"
|
||||
"git.coopgo.io/coopgo-apps/parcoursmob/utils/identification"
|
||||
cache "git.coopgo.io/coopgo-apps/parcoursmob/utils/storage"
|
||||
"github.com/gorilla/mux"
|
||||
"git.coopgo.io/coopgo-apps/parcoursmob/core/utils/identification"
|
||||
cache "git.coopgo.io/coopgo-apps/parcoursmob/core/utils/storage"
|
||||
)
|
||||
|
||||
func main() {
|
||||
zerolog.TimeFieldFormat = zerolog.TimeFormatUnix
|
||||
|
||||
cfg, err := ReadConfig()
|
||||
if err != nil {
|
||||
log.Fatal().Err(err).Msg("cannot read config")
|
||||
log.Fatal().Err(err).Msg("cannot read config!")
|
||||
return
|
||||
}
|
||||
|
||||
var (
|
||||
address = cfg.GetString("server.listen")
|
||||
service_name = cfg.GetString("service_name")
|
||||
templates_public_dir = cfg.GetString("templates.public_dir")
|
||||
dev_env = cfg.GetBool("dev_env")
|
||||
webEnabled = cfg.GetBool("server.web.enabled")
|
||||
mcpEnabled = cfg.GetBool("server.mcp.enabled")
|
||||
)
|
||||
|
||||
if dev_env {
|
||||
log.Logger = log.Output(zerolog.ConsoleWriter{Out: os.Stderr})
|
||||
} else {
|
||||
zerolog.TimeFieldFormat = zerolog.TimeFormatUnix
|
||||
}
|
||||
|
||||
svc, err := services.NewServicesHandler(cfg)
|
||||
@@ -60,180 +56,29 @@ func main() {
|
||||
log.Panic().Err(err).Msg("Error creating emailing handler")
|
||||
}
|
||||
|
||||
apiHandler, _ := api.NewAPIHandler(cfg, idp, svc, kv)
|
||||
applicationHandler, _ := application.NewApplicationHandler(cfg, svc, kv, filestorage, emailing)
|
||||
exportsHandler, _ := exports.NewExportsHandler(cfg, svc, emailing)
|
||||
authHandler, _ := auth.NewAuthHandler(cfg, idp, svc, kv, emailing)
|
||||
// Create renderer for web server
|
||||
templates_root := cfg.GetString("templates.root")
|
||||
webRenderer := renderer.NewRenderer(cfg, templates_root, filestorage)
|
||||
|
||||
r := mux.NewRouter()
|
||||
applicationHandler, _ := application.NewApplicationHandler(cfg, svc, kv, filestorage, emailing, idp)
|
||||
|
||||
r.PathPrefix("/public/").Handler(http.StripPrefix("/public/", http.FileServer(http.Dir(templates_public_dir))))
|
||||
var wg sync.WaitGroup
|
||||
|
||||
r.HandleFunc("/auth/onboarding", authHandler.Onboarding)
|
||||
r.HandleFunc("/auth/disconnect", authHandler.Disconnect)
|
||||
r.HandleFunc("/auth/lost-password", authHandler.LostPasswordInit)
|
||||
r.HandleFunc("/auth/lost-password/recover", authHandler.LostPasswordRecover)
|
||||
r.HandleFunc("/auth/groups/", authHandler.Groups)
|
||||
r.HandleFunc("/auth/groups/switch", authHandler.GroupSwitch)
|
||||
r.HandleFunc("/", redirectApp)
|
||||
|
||||
if dev_env {
|
||||
r.Use(trackPage)
|
||||
if webEnabled {
|
||||
wg.Add(1)
|
||||
go func() {
|
||||
defer wg.Done()
|
||||
web.Run(cfg, svc, webRenderer, applicationHandler, idp, kv, filestorage)
|
||||
}()
|
||||
}
|
||||
|
||||
calendars_router := r.PathPrefix("/api/calendars").Subrouter()
|
||||
calendars_router.HandleFunc("/global.ics", apiHandler.CalendarGlobal)
|
||||
calendars_router.HandleFunc("/organizations/{groupid}.ics", apiHandler.CalendarOrganizations)
|
||||
|
||||
api_router := r.PathPrefix("/api").Subrouter()
|
||||
api_router.HandleFunc("/", apiHandler.NotFound)
|
||||
api_router.HandleFunc("/geo/autocomplete", apiHandler.GeoAutocomplete)
|
||||
api_router.HandleFunc("/cache/{cacheid}", apiHandler.GetCache)
|
||||
api_router.HandleFunc("/cache/{cacheid}/export", apiHandler.CacheExport)
|
||||
api_router.HandleFunc("/oauth2/callback", apiHandler.OAuth2Callback)
|
||||
|
||||
application := r.PathPrefix("/app").Subrouter()
|
||||
application.HandleFunc("/", applicationHandler.Dashboard)
|
||||
application.HandleFunc("/beneficiaries/", applicationHandler.BeneficiariesList)
|
||||
application.HandleFunc("/beneficiaries/create", applicationHandler.BeneficiaryCreate)
|
||||
application.HandleFunc("/beneficiaries/{beneficiaryid}", applicationHandler.BeneficiaryDisplay)
|
||||
application.HandleFunc("/beneficiaries/{beneficiaryid}/update", applicationHandler.BeneficiaryUpdate)
|
||||
application.HandleFunc("/beneficiaries/{beneficiaryid}/documents", applicationHandler.BeneficiaryDocuments)
|
||||
application.HandleFunc("/beneficiaries/{beneficiaryid}/documents/{document}", applicationHandler.BeneficiaryDocumentDownload)
|
||||
application.HandleFunc("/beneficiaries/{beneficiaryid}/picture", applicationHandler.BeneficiaryPicture)
|
||||
application.HandleFunc("/members/{beneficiaryid}/picture", applicationHandler.BeneficiaryPicture)
|
||||
application.HandleFunc("/members/{adminid}", applicationHandler.MemberDisplay)
|
||||
application.HandleFunc("/members/{adminid}/update", applicationHandler.MemberUpdate)
|
||||
application.HandleFunc("/members/", applicationHandler.MembersList)
|
||||
application.HandleFunc("/journeys/", applicationHandler.JourneysSearch)
|
||||
application.HandleFunc("/vehicles/", applicationHandler.VehiclesSearch)
|
||||
application.HandleFunc("/vehicles/bookings/", applicationHandler.VehiclesBookingsList)
|
||||
application.HandleFunc("/vehicles/bookings/{bookingid}", applicationHandler.VehicleBookingDisplay)
|
||||
application.HandleFunc("/vehicles/v/{vehicleid}/b/{beneficiaryid}", applicationHandler.Book)
|
||||
application.HandleFunc("/vehicles/bookings/{bookingid}/documents/{document}", applicationHandler.BookingDocumentDownload)
|
||||
application.HandleFunc("/vehicles-management/", applicationHandler.VehiclesManagementOverview)
|
||||
application.HandleFunc("/vehicles-management/fleet/add", applicationHandler.VehiclesFleetAdd)
|
||||
application.HandleFunc("/vehicles-management/fleet/{vehicleid}", applicationHandler.VehiclesFleetDisplay)
|
||||
application.HandleFunc("/vehicles-management/fleet/{vehicleid}/unavailability", applicationHandler.VehiclesFleetMakeUnavailable)
|
||||
application.HandleFunc("/vehicles-management/fleet/{vehicleid}/update", applicationHandler.VehiclesFleetUpdate)
|
||||
application.HandleFunc("/vehicles-management/bookings/", applicationHandler.VehiclesManagementBookingsList)
|
||||
application.HandleFunc("/vehicles-management/bookings/{bookingid}", applicationHandler.VehicleManagementBookingDisplay)
|
||||
application.HandleFunc("/vehicles-management/bookings/{bookingid}/change-vehicle", applicationHandler.VehicleManagementBookingChangeVehicle)
|
||||
/////////////////////////////////////Remove booking vehicle/////////////////////////////////////////
|
||||
application.HandleFunc("/vehicles-management/bookings/{bookingid}/delete", applicationHandler.UnbookingVehicle)
|
||||
////////////////////////////////////////////////////////////////////////////////////////////////////
|
||||
application.HandleFunc("/vehicles-management/bookings/{bookingid}/documents/{document}", applicationHandler.BookingDocumentDownload)
|
||||
application.HandleFunc("/agenda/", applicationHandler.AgendaHome)
|
||||
application.HandleFunc("/agenda/history", applicationHandler.AgendaHistory)
|
||||
application.HandleFunc("/agenda/create-event", applicationHandler.AgendaCreateEvent)
|
||||
application.HandleFunc("/agenda/{eventid}", applicationHandler.AgendaDisplayEvent)
|
||||
///////////////////////////////Code to modify event///////////////////////
|
||||
application.HandleFunc("/agenda/{eventid}/update", applicationHandler.AgendaUpdateEvent)
|
||||
application.HandleFunc("/agenda/{eventid}/delete", applicationHandler.AgendaDeleteEvent)
|
||||
|
||||
/////////////////////////////////////////////////////
|
||||
application.HandleFunc("/agenda/{eventid}/subscribe", applicationHandler.AgendaSubscribeEvent)
|
||||
application.HandleFunc("/directory/", applicationHandler.DirectoryHome)
|
||||
|
||||
application.HandleFunc("/group/settings", applicationHandler.GroupSettingsDisplay)
|
||||
application.HandleFunc("/group/settings/invite-member", applicationHandler.GroupSettingsInviteMember)
|
||||
|
||||
/****************************Groupe Déplacement ************************************/
|
||||
application.HandleFunc("/journeys/groups_covoiturage", applicationHandler.GroupsGestion)
|
||||
application.HandleFunc("/journeys/groups_covoiturage/create", applicationHandler.CreateGroup)
|
||||
application.HandleFunc("/journeys/groups_covoiturage/create/{groupid}", applicationHandler.DisplayGroupCovoiturage)
|
||||
application.HandleFunc("/journeys/groups_covoiturage/create/{id}/{groupid}/{memberid}", applicationHandler.UpdateGroupCovoiturage)
|
||||
/****************************************************************/
|
||||
|
||||
/********************Code Supprt Emailing************************/
|
||||
application.HandleFunc("/support/", applicationHandler.SupportSend)
|
||||
/*********************** CODE GROUP **************************/
|
||||
|
||||
appGroup := application.PathPrefix("/group_module").Subrouter()
|
||||
appGroup.HandleFunc("/", applicationHandler.Groups)
|
||||
appGroup.HandleFunc("/groups", applicationHandler.CreateGroupModule)
|
||||
appGroup.HandleFunc("/groups/{groupid}", applicationHandler.DisplayGroupModule)
|
||||
|
||||
// TODO Subrouters with middlewares checking security for each module ?
|
||||
application.Use(idp.Middleware)
|
||||
application.Use(idp.GroupsMiddleware)
|
||||
|
||||
appAdmin := application.PathPrefix("/administration").Subrouter()
|
||||
appAdmin.HandleFunc("/", applicationHandler.Administration)
|
||||
appAdmin.HandleFunc("/groups/", applicationHandler.AdministrationCreateGroup)
|
||||
appAdmin.HandleFunc("/groups/{groupid}", applicationHandler.AdministrationGroupDisplay)
|
||||
appAdmin.HandleFunc("/groups/{groupid}/invite-admin", applicationHandler.AdministrationGroupInviteAdmin)
|
||||
appAdmin.HandleFunc("/groups/{groupid}/invite-member", applicationHandler.AdministrationGroupInviteMember)
|
||||
// add statistiques
|
||||
appAdmin.HandleFunc("/stats/vehicles", applicationHandler.AdminStatVehicles)
|
||||
appAdmin.HandleFunc("/stats/bookings", applicationHandler.AdminStatBookings)
|
||||
appAdmin.HandleFunc("/stats/beneficaires", applicationHandler.AdminStatBeneficaires)
|
||||
appAdmin.HandleFunc("/stats/events", applicationHandler.AdminStatEvents)
|
||||
|
||||
/////////////////////////////////////Delete subscriber///////////////////////////////////////////////
|
||||
application.HandleFunc("/agenda/{eventid}/{subscribeid}/delete", applicationHandler.AgendaDeleteSubscribeEvent)
|
||||
application.HandleFunc("/agenda/{eventid}/history", applicationHandler.AgendaHistoryEvent)
|
||||
/////////////////////////////////////////////////////////////////////////////////////////////////////
|
||||
//////////////////Add documents in event////////////////////////
|
||||
application.HandleFunc("/agenda/{eventid}/documents", applicationHandler.EventDocuments)
|
||||
application.HandleFunc("/agenda/{eventid}/documents/{document}", applicationHandler.EventDocumentDownload)
|
||||
////////////////////////////////////////////////////////////////
|
||||
//////////////////Diag in event////////////////////////
|
||||
// application.HandleFunc("/agenda/{eventid}/create-diag", applicationHandler.DiagsCreateDiag)
|
||||
application.HandleFunc("/agenda/{eventid}/diags", applicationHandler.DiagsHome)
|
||||
application.HandleFunc("/agenda/{eventid}/diags/{diagid}", applicationHandler.DiagsDisplayDiag)
|
||||
application.HandleFunc("/agenda/{eventid}/diags/history", applicationHandler.DiagsHistory)
|
||||
application.HandleFunc("/agenda/{eventid}/diags/{diagid}/history", applicationHandler.DiagsHistoryDiag)
|
||||
////////////////////////////////////////////////////////////////
|
||||
//////////////////Diag in benefeciaries////////////////////////
|
||||
application.HandleFunc("/beneficiaries/{beneficiaryid}/create-diag", applicationHandler.BeneficiariesCreateDiag)
|
||||
application.HandleFunc("/beneficiaries/{beneficiaryid}/diags/{diagid}", applicationHandler.DiagsDisplayDiag)
|
||||
////////////////////////////////////////////////////////////////
|
||||
//////////////////Diag in vehicules////////////////////////
|
||||
application.HandleFunc("/vehicles-management/fleet/{vehicleid}/create-diag", applicationHandler.VehiclesCreateDiag)
|
||||
application.HandleFunc("/vehicles-management/fleet/{vehicleid}/diags", applicationHandler.DiagsHome)
|
||||
application.HandleFunc("/vehicles-management/fleet/{vehicleid}/diags/{diagid}", applicationHandler.DiagsDisplayDiag)
|
||||
////////////////////////////////////////////////////////////////
|
||||
//////////////////Diag in bookings////////////////////////
|
||||
application.HandleFunc("/vehicles-management/bookings/{bookingid}/create-diag", applicationHandler.BookingsCreateDiag)
|
||||
application.HandleFunc("/vehicles/bookings/{vehicleid}/diags", applicationHandler.DiagsHome)
|
||||
application.HandleFunc("/vehicles/bookings/{bookingid}/create-diag", applicationHandler.VehicleBookingsCreateDiag)
|
||||
//////////////////Diags////////////////////////
|
||||
application.HandleFunc("/diags/", applicationHandler.DiagsHome)
|
||||
application.HandleFunc("/diags/{diagid}/documents", applicationHandler.DiagsDocuments)
|
||||
application.HandleFunc("/diags/{diagid}/documents/{document}", applicationHandler.DiagsDocumentDownload)
|
||||
application.HandleFunc("/diags/{diagid}", applicationHandler.DiagsDisplayDiag)
|
||||
application.HandleFunc("/diags/{diagid}/update", applicationHandler.DiagUpdate)
|
||||
application.HandleFunc("/diags/{diagid}/delete", applicationHandler.DiagDelete)
|
||||
// application.HandleFunc("/diags/history", applicationHandler.DiagsHistory)
|
||||
|
||||
export := r.PathPrefix("/exports").Subrouter()
|
||||
export.HandleFunc("/fleets/bookings", exportsHandler.Bookings)
|
||||
export.HandleFunc("/fleets/bookings/{groupid}", exportsHandler.Bookings)
|
||||
export.HandleFunc("/agenda/subscriptions", exportsHandler.Agenda("allEvents"))
|
||||
export.HandleFunc("/agenda/{eventid}", exportsHandler.Agenda("oneEvent"))
|
||||
export.Use(idp.Middleware)
|
||||
export.Use(idp.GroupsMiddleware)
|
||||
|
||||
srv := &http.Server{
|
||||
Handler: r,
|
||||
Addr: address,
|
||||
WriteTimeout: 15 * time.Second,
|
||||
ReadTimeout: 15 * time.Second,
|
||||
if mcpEnabled {
|
||||
wg.Add(1)
|
||||
go func() {
|
||||
defer wg.Done()
|
||||
mcp.Run(cfg, svc, applicationHandler, kv, filestorage)
|
||||
}()
|
||||
}
|
||||
|
||||
log.Info().Str("service_name", service_name).Str("address", address).Msg("Running HTTP server")
|
||||
|
||||
log.Fatal().Err(srv.ListenAndServe())
|
||||
}
|
||||
|
||||
func redirectApp(w http.ResponseWriter, r *http.Request) {
|
||||
http.Redirect(w, r, "/app/", http.StatusFound)
|
||||
}
|
||||
|
||||
func trackPage(next http.Handler) http.Handler {
|
||||
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
|
||||
log.Trace().Str("requested_uri", r.RequestURI).Msg("New request")
|
||||
next.ServeHTTP(w, r.WithContext(r.Context()))
|
||||
})
|
||||
wg.Wait()
|
||||
}
|
||||
|
||||
@@ -100,7 +100,7 @@ func (renderer *Renderer) AdminStatVehicles(w http.ResponseWriter, r *http.Reque
|
||||
renderer.Render("vehicles_state", w, r, files, state)
|
||||
}
|
||||
|
||||
func (renderer *Renderer) AdminStatBookings(w http.ResponseWriter, r *http.Request, vehicles map[string]fleetsstorage.Vehicle, bookings []fleetsstorage.Booking, admingroups map[string]any, beneficiaries map[string]any) {
|
||||
func (renderer *Renderer) AdminStatBookings(w http.ResponseWriter, r *http.Request, vehicles map[string]fleetsstorage.Vehicle, bookings []fleetsstorage.Booking, admingroups map[string]any, beneficiaries map[string]any, filters map[string]string) {
|
||||
files := renderer.ThemeConfig.GetStringSlice("views.administration.bookings_list.files")
|
||||
state := NewState(r, renderer.ThemeConfig, administrationMenu)
|
||||
state.ViewState = map[string]any{
|
||||
@@ -108,6 +108,7 @@ func (renderer *Renderer) AdminStatBookings(w http.ResponseWriter, r *http.Reque
|
||||
"bookings": bookings,
|
||||
"admingroups": admingroups,
|
||||
"beneficiaries_map": beneficiaries,
|
||||
"filters": filters,
|
||||
}
|
||||
|
||||
renderer.Render("bookings_stats", w, r, files, state)
|
||||
|
||||
@@ -15,6 +15,7 @@ type BeneficiariesListState struct {
|
||||
Count int `json:"count"`
|
||||
CacheId string `json:"cache_id"`
|
||||
Beneficiaries []mobilityaccountsstorage.Account `json:"beneficiaries"`
|
||||
Archived bool `json:"archived"`
|
||||
}
|
||||
|
||||
func (s BeneficiariesListState) JSON() template.JS {
|
||||
@@ -29,7 +30,7 @@ func (s BeneficiariesListState) JSONWithLimits(a int, b int) template.JS {
|
||||
return s.JSON()
|
||||
}
|
||||
|
||||
func (renderer *Renderer) BeneficiariesList(w http.ResponseWriter, r *http.Request, accounts []mobilityaccountsstorage.Account, cacheid string) {
|
||||
func (renderer *Renderer) BeneficiariesList(w http.ResponseWriter, r *http.Request, accounts []mobilityaccountsstorage.Account, cacheid string, archived bool) {
|
||||
files := renderer.ThemeConfig.GetStringSlice("views.beneficiaries.list.files")
|
||||
|
||||
state := NewState(r, renderer.ThemeConfig, beneficiariesMenu)
|
||||
@@ -37,6 +38,7 @@ func (renderer *Renderer) BeneficiariesList(w http.ResponseWriter, r *http.Reque
|
||||
Count: len(accounts),
|
||||
CacheId: cacheid,
|
||||
Beneficiaries: accounts,
|
||||
Archived: archived,
|
||||
}
|
||||
|
||||
renderer.Render("beneficiaries_list", w, r, files, state)
|
||||
@@ -44,7 +46,12 @@ func (renderer *Renderer) BeneficiariesList(w http.ResponseWriter, r *http.Reque
|
||||
|
||||
func (renderer *Renderer) BeneficiaryCreate(w http.ResponseWriter, r *http.Request) {
|
||||
files := renderer.ThemeConfig.GetStringSlice("views.beneficiaries.create.files")
|
||||
profileFields := renderer.GlobalConfig.Get("modules.beneficiaries.profile_optional_fields")
|
||||
|
||||
state := NewState(r, renderer.ThemeConfig, beneficiariesMenu)
|
||||
state.ViewState = map[string]any{
|
||||
"profile_optional_fields": profileFields,
|
||||
}
|
||||
|
||||
renderer.Render("beneficiaries_create", w, r, files, state)
|
||||
}
|
||||
@@ -53,8 +60,10 @@ type BeneficiariesDisplayState struct {
|
||||
Beneficiary any
|
||||
}
|
||||
|
||||
func (renderer *Renderer) BeneficiaryDisplay(w http.ResponseWriter, r *http.Request, beneficiary any, bookings []fleetsstorage.Booking, organizations []any, beneficiaries_file_types []string, file_types_map map[string]string, documents any, event interface{}, diags []any) {
|
||||
func (renderer *Renderer) BeneficiaryDisplay(w http.ResponseWriter, r *http.Request, beneficiary any, bookings []fleetsstorage.Booking, organizations []any, beneficiaries_file_types []string, file_types_map map[string]string, documents any, event interface{}, solidarityTransportStats any, solidarityTransportBookings any, solidarityDriversMap any, organizedCarpoolStats any, organizedCarpoolBookings any, organizedCarpoolDriversMap any, walletBalance float64, tab string) {
|
||||
files := renderer.ThemeConfig.GetStringSlice("views.beneficiaries.display.files")
|
||||
profileFields := renderer.GlobalConfig.Get("modules.beneficiaries.profile_optional_fields")
|
||||
|
||||
state := NewState(r, renderer.ThemeConfig, beneficiariesMenu)
|
||||
state.ViewState = map[string]any{
|
||||
"beneficiary": beneficiary,
|
||||
@@ -64,15 +73,29 @@ func (renderer *Renderer) BeneficiaryDisplay(w http.ResponseWriter, r *http.Requ
|
||||
"documents": documents,
|
||||
"organizations": organizations,
|
||||
"event": event,
|
||||
"diags": diags,
|
||||
"solidarity_transport_stats": solidarityTransportStats,
|
||||
"solidarity_transport_bookings": solidarityTransportBookings,
|
||||
"solidarity_transport_drivers_map": solidarityDriversMap,
|
||||
"organized_carpool_stats": organizedCarpoolStats,
|
||||
"organized_carpool_bookings": organizedCarpoolBookings,
|
||||
"organized_carpool_drivers_map": organizedCarpoolDriversMap,
|
||||
"profile_optional_fields": profileFields,
|
||||
"wallet_balance": walletBalance,
|
||||
"tab": tab,
|
||||
"search_view": renderer.GlobalConfig.GetString("modules.journeys.search_view"),
|
||||
}
|
||||
renderer.Render("beneficiaries_display", w, r, files, state)
|
||||
}
|
||||
|
||||
func (renderer *Renderer) BeneficiaryUpdate(w http.ResponseWriter, r *http.Request, beneficiary any) {
|
||||
files := renderer.ThemeConfig.GetStringSlice("views.beneficiaries.update.files")
|
||||
profileFields := renderer.GlobalConfig.Get("modules.beneficiaries.profile_optional_fields")
|
||||
|
||||
state := NewState(r, renderer.ThemeConfig, beneficiariesMenu)
|
||||
state.ViewState = beneficiary
|
||||
state.ViewState = map[string]any{
|
||||
"beneficiary": beneficiary,
|
||||
"profile_optional_fields": profileFields,
|
||||
}
|
||||
|
||||
renderer.Render("beneficiaries_update", w, r, files, state)
|
||||
}
|
||||
|
||||
@@ -5,11 +5,12 @@ import (
|
||||
|
||||
agendastorage "git.coopgo.io/coopgo-platform/agenda/storage"
|
||||
fleetstorage "git.coopgo.io/coopgo-platform/fleets/storage"
|
||||
mobilityaccountsstorage "git.coopgo.io/coopgo-platform/mobility-accounts/storage"
|
||||
)
|
||||
|
||||
const dashboardMenu = "dashboard"
|
||||
|
||||
func (renderer *Renderer) Dashboard(w http.ResponseWriter, r *http.Request, accounts []any, nbaccounts int, count_members int, events []agendastorage.Event, fleets []fleetstorage.Booking) {
|
||||
func (renderer *Renderer) Dashboard(w http.ResponseWriter, r *http.Request, accounts any, nbaccounts int, count_members int, events []agendastorage.Event, fleets []fleetstorage.Booking, solidarityDrivers []mobilityaccountsstorage.Account, organizedCarpoolDrivers []mobilityaccountsstorage.Account, driverAddressGeo string, enrichedGeoFilters []map[string]string) {
|
||||
files := renderer.ThemeConfig.GetStringSlice("views.dashboard.files")
|
||||
state := NewState(r, renderer.ThemeConfig, dashboardMenu)
|
||||
state.ViewState = map[string]any{
|
||||
@@ -20,6 +21,13 @@ func (renderer *Renderer) Dashboard(w http.ResponseWriter, r *http.Request, acco
|
||||
"count_members": count_members,
|
||||
"events": events,
|
||||
"fleets": fleets,
|
||||
"solidarity_drivers": solidarityDrivers,
|
||||
"organized_carpool_drivers": organizedCarpoolDrivers,
|
||||
"geography_filters_enabled": renderer.GlobalConfig.GetBool("geography.filters.enabled"),
|
||||
"geography_filters_list": enrichedGeoFilters,
|
||||
"filters": map[string]any{
|
||||
"driver_address_geo": driverAddressGeo,
|
||||
},
|
||||
}
|
||||
|
||||
renderer.Render("dashboard", w, r, files, state)
|
||||
|
||||
@@ -1,115 +0,0 @@
|
||||
package renderer
|
||||
|
||||
import (
|
||||
"net/http"
|
||||
|
||||
diagsstorage "git.coopgo.io/coopgo-platform/diags/storage"
|
||||
)
|
||||
|
||||
const diagsMenu = "diags"
|
||||
|
||||
func (renderer *Renderer) DiagsHome(w http.ResponseWriter, r *http.Request, diags []diagsstorage.Diag, groups map[string]any) {
|
||||
files := renderer.ThemeConfig.GetStringSlice("views.diags.list.files")
|
||||
state := NewState(r, renderer.ThemeConfig, diagsMenu)
|
||||
state.ViewState = map[string]any{
|
||||
"diags": diags,
|
||||
"groups": groups,
|
||||
}
|
||||
|
||||
renderer.Render("diags home", w, r, files, state)
|
||||
}
|
||||
|
||||
func (renderer *Renderer) DiagsHistory(w http.ResponseWriter, r *http.Request, diags []diagsstorage.Diag) {
|
||||
files := renderer.ThemeConfig.GetStringSlice("views.diags.history.files")
|
||||
state := NewState(r, renderer.ThemeConfig, diagsMenu)
|
||||
state.ViewState = map[string]any{
|
||||
"diags": diags,
|
||||
}
|
||||
|
||||
renderer.Render("diags history", w, r, files, state)
|
||||
}
|
||||
|
||||
func (renderer *Renderer) BeneficiariesCreateDiag(w http.ResponseWriter, r *http.Request, beneficiary string, diags_file_types []string, file_types_map map[string]string, documents any) {
|
||||
state := NewState(r, renderer.ThemeConfig, diagsMenu)
|
||||
files := renderer.ThemeConfig.GetStringSlice("views.beneficiaries.create_diag.files")
|
||||
state.ViewState = map[string]any{
|
||||
"beneficiary": beneficiary,
|
||||
"diags_file_types": diags_file_types,
|
||||
"file_types_map": file_types_map,
|
||||
"documents": documents,
|
||||
}
|
||||
renderer.Render("diag create for beneficiary", w, r, files, state)
|
||||
}
|
||||
|
||||
func (renderer *Renderer) VehiclesCreateDiag(w http.ResponseWriter, r *http.Request, vehicle string) {
|
||||
state := NewState(r, renderer.ThemeConfig, diagsMenu)
|
||||
files := renderer.ThemeConfig.GetStringSlice("views.vehicles_management.create_vehicle_diag.files")
|
||||
state.ViewState = map[string]any{
|
||||
"vehicle": vehicle,
|
||||
}
|
||||
renderer.Render("diag create for vehicle", w, r, files, state)
|
||||
}
|
||||
|
||||
func (renderer *Renderer) BookingsCreateDiag(w http.ResponseWriter, r *http.Request, booking string) {
|
||||
state := NewState(r, renderer.ThemeConfig, diagsMenu)
|
||||
files := renderer.ThemeConfig.GetStringSlice("views.vehicles_management.create_booking_diag.files")
|
||||
state.ViewState = map[string]any{
|
||||
"booking": booking,
|
||||
}
|
||||
renderer.Render("diag create for booking", w, r, files, state)
|
||||
}
|
||||
|
||||
func (renderer *Renderer) VehicleBookingsCreateDiag(w http.ResponseWriter, r *http.Request, booking string) {
|
||||
state := NewState(r, renderer.ThemeConfig, diagsMenu)
|
||||
files := renderer.ThemeConfig.GetStringSlice("views.vehicles.create_booking_diag.files")
|
||||
state.ViewState = map[string]any{
|
||||
"booking": booking,
|
||||
}
|
||||
renderer.Render("diag create for booking", w, r, files, state)
|
||||
}
|
||||
|
||||
func (renderer *Renderer) DiagsDisplayDiag(w http.ResponseWriter, r *http.Request, diag any, diags_file_types []string, file_types_map map[string]string, documents any) {
|
||||
files := renderer.ThemeConfig.GetStringSlice("views.diags.display_diag.files")
|
||||
state := NewState(r, renderer.ThemeConfig, diagsMenu)
|
||||
|
||||
state.ViewState = map[string]any{
|
||||
"diag": diag,
|
||||
"diags_file_types": diags_file_types,
|
||||
"file_types_map": file_types_map,
|
||||
"documents": documents,
|
||||
}
|
||||
|
||||
renderer.Render("diags create diag", w, r, files, state)
|
||||
}
|
||||
|
||||
func (renderer *Renderer) DiagsHistoryDiag(w http.ResponseWriter, r *http.Request, diag any) {
|
||||
files := renderer.ThemeConfig.GetStringSlice("views.diags.history_diag.files")
|
||||
state := NewState(r, renderer.ThemeConfig, diagsMenu)
|
||||
state.ViewState = map[string]any{
|
||||
"diag": diag,
|
||||
}
|
||||
|
||||
renderer.Render("diags history diag", w, r, files, state)
|
||||
}
|
||||
|
||||
func (renderer *Renderer) DiagUpdate(w http.ResponseWriter, r *http.Request, diag any) {
|
||||
files := renderer.ThemeConfig.GetStringSlice("views.diags.update.files")
|
||||
state := NewState(r, renderer.ThemeConfig, diagsMenu)
|
||||
|
||||
state.ViewState = map[string]any{
|
||||
"diag": diag,
|
||||
}
|
||||
|
||||
renderer.Render("diag_update", w, r, files, state)
|
||||
}
|
||||
|
||||
func (renderer *Renderer) DiagDelete(w http.ResponseWriter, r *http.Request, diag any) {
|
||||
files := renderer.ThemeConfig.GetStringSlice("views.diags.delete.files")
|
||||
state := NewState(r, renderer.ThemeConfig, diagsMenu)
|
||||
|
||||
state.ViewState = map[string]any{
|
||||
"diag": diag,
|
||||
}
|
||||
|
||||
renderer.Render("diag_deleteDiag", w, r, files, state)
|
||||
}
|
||||
@@ -5,22 +5,51 @@ import (
|
||||
"encoding/json"
|
||||
"fmt"
|
||||
"html/template"
|
||||
"math"
|
||||
"reflect"
|
||||
"strings"
|
||||
"time"
|
||||
|
||||
filestorage "git.coopgo.io/coopgo-apps/parcoursmob/core/utils/storage"
|
||||
validatedprofile "git.coopgo.io/coopgo-apps/parcoursmob/core/utils/validated-profile"
|
||||
groupsstorage "git.coopgo.io/coopgo-platform/groups-management/storage"
|
||||
"github.com/rs/zerolog/log"
|
||||
"github.com/spf13/viper"
|
||||
"gitlab.scity.coop/maas/navitia-golang/types"
|
||||
)
|
||||
|
||||
func TimeFrom(d any) *time.Time {
|
||||
func ModuleAvailable(group groupsstorage.Group, configmodules *viper.Viper) func(string) bool {
|
||||
return func(module string) bool {
|
||||
if module == "dashboard" {
|
||||
return true
|
||||
}
|
||||
groupmodules := group.Data["modules"].(map[string]any)
|
||||
modAvailable, ok := groupmodules[module].(bool)
|
||||
if ok && modAvailable && configmodules.GetBool(fmt.Sprintf("modules.%s.enabled", module)) {
|
||||
return true
|
||||
}
|
||||
return false
|
||||
}
|
||||
}
|
||||
|
||||
func TimeFrom(d any) *time.Time {
|
||||
paris, err := time.LoadLocation("Europe/Paris")
|
||||
if date, ok := d.(time.Time); ok {
|
||||
if err != nil {
|
||||
return &date
|
||||
}
|
||||
nd := date.In(paris)
|
||||
return &nd
|
||||
} else if date, ok := d.(string); ok {
|
||||
datetime, err := time.Parse("2006-01-02T15:04:05Z", date)
|
||||
if err != nil {
|
||||
panic(err)
|
||||
datetime, err = time.Parse("2006-01-02", date)
|
||||
if err != nil {
|
||||
log.Error().Err(err).Msg("cannot parse date")
|
||||
}
|
||||
return &datetime
|
||||
}
|
||||
dt := datetime.In(paris)
|
||||
return &dt
|
||||
}
|
||||
return nil
|
||||
}
|
||||
@@ -78,7 +107,6 @@ func RawJSON(v any) string {
|
||||
return ""
|
||||
}
|
||||
return strings.TrimSuffix(buf.String(), "\n")
|
||||
|
||||
}
|
||||
|
||||
func UnescapeHTML(s string) template.HTML {
|
||||
@@ -124,6 +152,106 @@ func strval(v interface{}) string {
|
||||
}
|
||||
}
|
||||
|
||||
// JSEscape escapes a string for safe use in JavaScript
|
||||
func JSEscape(s string) template.JS {
|
||||
return template.JS(template.JSEscapeString(s))
|
||||
}
|
||||
|
||||
// IsGuaranteedTripMotivation checks if a motivation is a guaranteed trip
|
||||
func IsGuaranteedTripMotivation(globalConfig *viper.Viper) func(string) bool {
|
||||
return func(motivation string) bool {
|
||||
guaranteedMotivations := globalConfig.GetStringSlice("modules.solidarity_transport.guaranteed_trip_motivations")
|
||||
for _, m := range guaranteedMotivations {
|
||||
if m == motivation {
|
||||
return true
|
||||
}
|
||||
}
|
||||
return false
|
||||
}
|
||||
}
|
||||
|
||||
// GetTemplateFuncMap returns the common template functions for rendering
|
||||
func GetTemplateFuncMap(group groupsstorage.Group, globalConfig *viper.Viper, fileStorage filestorage.FileStorage) template.FuncMap {
|
||||
return template.FuncMap{
|
||||
"moduleAvailable": ModuleAvailable(group, globalConfig),
|
||||
"timeFrom": TimeFrom,
|
||||
"timeFormat": TimeFormat,
|
||||
"genderISO5218": GenderISO5218,
|
||||
"dict": Dict,
|
||||
"json": JSON,
|
||||
"rawjson": RawJSON,
|
||||
"unescapeHTML": UnescapeHTML,
|
||||
"jsEscape": JSEscape,
|
||||
"walkingLength": WalkingLength,
|
||||
"divideFloat64": Divide[float64],
|
||||
"divideInt": Divide[int],
|
||||
"typeOf": reflect.TypeOf,
|
||||
"shortDuration": ShortDuration,
|
||||
"round2": Round2,
|
||||
"beneficiaryValidatedProfile": validatedprofile.ValidateProfile(globalConfig.Sub("modules.beneficiaries.validated_profile")),
|
||||
"solidarityDriverValidatedProfile": validatedprofile.ValidateProfile(globalConfig.Sub("modules.solidarity_transport.drivers.validated_profile")),
|
||||
"carpoolDriverValidatedProfile": validatedprofile.ValidateProfile(globalConfig.Sub("modules.organized_carpool.drivers.validated_profile")),
|
||||
"isGuaranteedTripMotivation": IsGuaranteedTripMotivation(globalConfig),
|
||||
"beneficiaryDocuments": func(id string) []filestorage.FileInfo {
|
||||
return fileStorage.List(filestorage.PREFIX_BENEFICIARIES + "/" + id)
|
||||
},
|
||||
"solidarityDocuments": func(id string) []filestorage.FileInfo {
|
||||
return fileStorage.List(filestorage.PREFIX_SOLIDARITY_TRANSPORT_DRIVERS + "/" + id)
|
||||
},
|
||||
"carpoolDocuments": func(id string) []filestorage.FileInfo {
|
||||
return fileStorage.List(filestorage.PREFIX_ORGANIZED_CARPOOL_DRIVERS + "/" + id)
|
||||
},
|
||||
}
|
||||
}
|
||||
|
||||
func Divide[V int | float64](a, b V) V {
|
||||
return a / b
|
||||
}
|
||||
|
||||
func ShortDuration(d interface{}) string {
|
||||
var duration time.Duration
|
||||
|
||||
switch v := d.(type) {
|
||||
case time.Duration:
|
||||
duration = v
|
||||
case int:
|
||||
duration = time.Duration(v) * time.Second
|
||||
case int64:
|
||||
duration = time.Duration(v) * time.Second
|
||||
case float64:
|
||||
duration = time.Duration(v) * time.Second
|
||||
default:
|
||||
return ""
|
||||
}
|
||||
|
||||
s := duration.String()
|
||||
if strings.HasSuffix(s, "m0s") {
|
||||
s = s[:len(s)-2]
|
||||
}
|
||||
if strings.HasSuffix(s, "h0m") {
|
||||
s = s[:len(s)-2]
|
||||
}
|
||||
return s
|
||||
}
|
||||
|
||||
// Round2 rounds a float64 to 2 decimal places to avoid floating point issues
|
||||
func Round2(value interface{}) float64 {
|
||||
var f float64
|
||||
switch v := value.(type) {
|
||||
case float64:
|
||||
f = v
|
||||
case *float64:
|
||||
if v != nil {
|
||||
f = *v
|
||||
}
|
||||
case float32:
|
||||
f = float64(v)
|
||||
case int:
|
||||
f = float64(v)
|
||||
case int64:
|
||||
f = float64(v)
|
||||
default:
|
||||
return 0
|
||||
}
|
||||
return math.Round(f*100) / 100
|
||||
}
|
||||
|
||||
@@ -7,6 +7,7 @@ import (
|
||||
|
||||
groupstorage "git.coopgo.io/coopgo-platform/groups-management/storage"
|
||||
mobilityaccountsstorage "git.coopgo.io/coopgo-platform/mobility-accounts/storage"
|
||||
geojson "github.com/paulmach/orb/geojson"
|
||||
)
|
||||
|
||||
const journeysMenu = "journeys"
|
||||
@@ -35,9 +36,10 @@ func (s BeneficiariesCovoiturage) JSONWithLimits(a int, b int) template.JS {
|
||||
return s.JSON()
|
||||
}
|
||||
|
||||
func (renderer *Renderer) JourneysSearch(w http.ResponseWriter, r *http.Request, carpools any, transitjourneys any, vehicles []any, searched bool, departure any, destination any, departuredate string, departuretime string) {
|
||||
func (renderer *Renderer) JourneysSearch(w http.ResponseWriter, r *http.Request, carpools []*geojson.FeatureCollection, transitjourneys any, vehicles any, searched bool, departure any, destination any, departuredate string, departuretime string, driverJourneys any, solidarityDrivers any, organizedCarpools any, beneficiaries any, kbData any, passengerid string, savedSearches any, beneficiariesMap any) {
|
||||
files := renderer.ThemeConfig.GetStringSlice("views.journeys.search.files")
|
||||
state := NewState(r, renderer.ThemeConfig, journeysMenu)
|
||||
journeyTabs := renderer.ThemeConfig.Get("journey_tabs")
|
||||
state.ViewState = map[string]any{
|
||||
"searched": searched,
|
||||
"departuredate": departuredate,
|
||||
@@ -46,7 +48,18 @@ func (renderer *Renderer) JourneysSearch(w http.ResponseWriter, r *http.Request,
|
||||
"destination": destination,
|
||||
"journeys": transitjourneys,
|
||||
"carpools": carpools,
|
||||
"organized_carpools": organizedCarpools,
|
||||
"vehicles": vehicles,
|
||||
"driver_journeys": driverJourneys,
|
||||
"solidarity_drivers": solidarityDrivers,
|
||||
"querystring": r.URL.RawQuery,
|
||||
"beneficiaries": beneficiariesMap,
|
||||
"beneficiaries_list": beneficiaries,
|
||||
"kb_data": kbData,
|
||||
"passengerid": passengerid,
|
||||
"journey_tabs": journeyTabs,
|
||||
"saved_searches": savedSearches,
|
||||
"search_view": renderer.GlobalConfig.GetString("modules.journeys.search_view"),
|
||||
}
|
||||
|
||||
renderer.Render("journeys", w, r, files, state)
|
||||
@@ -69,6 +82,7 @@ func (s BeneficiariesListstate) JSONWithLimits(a int, b int) template.JS {
|
||||
}
|
||||
return s.JSON()
|
||||
}
|
||||
|
||||
func (renderer *Renderer) GroupsGestion(w http.ResponseWriter, r *http.Request, groups []groupstorage.Group, cacheid string) {
|
||||
files := renderer.ThemeConfig.GetStringSlice("views.journeys.list.files")
|
||||
state := NewState(r, renderer.ThemeConfig, journeysMenu)
|
||||
@@ -98,7 +112,6 @@ func (renderer *Renderer) CreateGroup(w http.ResponseWriter, r *http.Request, de
|
||||
viewstate["search"] = map[string]any{
|
||||
"beneficiary": beneficiary,
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
state.ViewState = viewstate
|
||||
@@ -130,7 +143,6 @@ func (renderer *Renderer) DisplayGroupCovoiturage(w http.ResponseWriter, r *http
|
||||
viewstate["search"] = map[string]any{
|
||||
"beneficiary": beneficiary,
|
||||
}
|
||||
|
||||
}
|
||||
state.ViewState = viewstate
|
||||
|
||||
@@ -146,5 +158,29 @@ func (renderer *Renderer) UpdateGroupCovoiturage(w http.ResponseWriter, r *http.
|
||||
"memberid": memberid,
|
||||
}
|
||||
renderer.Render("journeys", w, r, files, state)
|
||||
|
||||
}
|
||||
|
||||
func (renderer *Renderer) JourneysSearchCompact(w http.ResponseWriter, r *http.Request, carpools []*geojson.FeatureCollection, transitjourneys any, vehicles any, searched bool, departure any, destination any, departuredate string, departuretime string, driverJourneys any, solidarityDrivers any, organizedCarpools any, kbData any, passengerid string) {
|
||||
files := renderer.ThemeConfig.GetStringSlice("views.journeys.search_compact.files")
|
||||
vehicleOptionalFields := renderer.GlobalConfig.Get("modules.fleets.vehicle_optional_fields")
|
||||
|
||||
state := NewState(r, renderer.ThemeConfig, journeysMenu)
|
||||
state.ViewState = map[string]any{
|
||||
"searched": searched,
|
||||
"departuredate": departuredate,
|
||||
"departuretime": departuretime,
|
||||
"departure": departure,
|
||||
"destination": destination,
|
||||
"journeys": transitjourneys,
|
||||
"carpools": carpools,
|
||||
"organized_carpools": organizedCarpools,
|
||||
"vehicles": vehicles,
|
||||
"vehicle_optional_fields": vehicleOptionalFields,
|
||||
"driver_journeys": driverJourneys,
|
||||
"solidarity_drivers": solidarityDrivers,
|
||||
"kb_data": kbData,
|
||||
"passengerid": passengerid,
|
||||
}
|
||||
|
||||
renderer.Render("journeys", w, r, files, state)
|
||||
}
|
||||
|
||||
@@ -2,9 +2,14 @@ package renderer
|
||||
|
||||
type LayoutState struct {
|
||||
AdministrationState AdministrationState
|
||||
Menu any
|
||||
ActiveMenu string
|
||||
|
||||
// DEPRECATED
|
||||
MenuItems []MenuItem
|
||||
}
|
||||
|
||||
// DEPRECATED
|
||||
type MenuItem struct {
|
||||
Title string
|
||||
Link string
|
||||
|
||||
@@ -12,19 +12,26 @@ const membersMenu = "members"
|
||||
|
||||
func (renderer *Renderer) MemberDisplay(w http.ResponseWriter, r *http.Request, admins any, groups []string) {
|
||||
files := renderer.ThemeConfig.GetStringSlice("views.members.display.files")
|
||||
profileFields := renderer.GlobalConfig.Get("modules.members.profile_optional_fields")
|
||||
|
||||
state := NewState(r, renderer.ThemeConfig, membersMenu)
|
||||
state.ViewState = map[string]any{
|
||||
"admins": admins,
|
||||
"groups": groups,
|
||||
"profile_optional_fields": profileFields,
|
||||
}
|
||||
renderer.Render("members_list", w, r, files, state)
|
||||
}
|
||||
|
||||
func (renderer *Renderer) MemberUpdate(w http.ResponseWriter, r *http.Request, user any) {
|
||||
files := renderer.ThemeConfig.GetStringSlice("views.members.update.files")
|
||||
profileFields := renderer.GlobalConfig.Get("modules.members.profile_optional_fields")
|
||||
|
||||
state := NewState(r, renderer.ThemeConfig, membersMenu)
|
||||
state.ViewState = user
|
||||
state.ViewState = map[string]any{
|
||||
"user": user,
|
||||
"profile_optional_fields": profileFields,
|
||||
}
|
||||
renderer.Render("members_update", w, r, files, state)
|
||||
}
|
||||
|
||||
@@ -53,7 +60,6 @@ func (renderer *Renderer) MembersList(w http.ResponseWriter, r *http.Request, ac
|
||||
state := NewState(r, renderer.ThemeConfig, membersMenu)
|
||||
|
||||
state.ViewState = map[string]any{
|
||||
|
||||
"list": MembersListState{
|
||||
Count: len(accounts),
|
||||
CacheId: cacheid,
|
||||
|
||||
110
renderer/organized-carpool.go
Normal file
110
renderer/organized-carpool.go
Normal file
@@ -0,0 +1,110 @@
|
||||
package renderer
|
||||
|
||||
import (
|
||||
"net/http"
|
||||
|
||||
mobilityaccountsstorage "git.coopgo.io/coopgo-platform/mobility-accounts/storage"
|
||||
"git.coopgo.io/coopgo-platform/payments/pricing"
|
||||
)
|
||||
|
||||
const organizedCarpoolMenu = "organized_carpool"
|
||||
|
||||
func (renderer *Renderer) OrganizedCarpoolOverview(w http.ResponseWriter, r *http.Request, drivers any, driversMap any, passengersMap any, bookings any, bookingsHistory any, filters map[string]any, histFilters map[string]any, tab string, enrichedGeoFilters []map[string]string, archived bool) {
|
||||
files := renderer.ThemeConfig.GetStringSlice("views.organized_carpool.overview.files")
|
||||
tripsItemsPerPage := renderer.GlobalConfig.GetInt("modules.organized_carpool.pagination.trips_items_per_page")
|
||||
driversItemsPerPage := renderer.GlobalConfig.GetInt("modules.organized_carpool.pagination.drivers_items_per_page")
|
||||
|
||||
geoFiltersEnabled := len(enrichedGeoFilters) > 0
|
||||
|
||||
state := NewState(r, renderer.ThemeConfig, organizedCarpoolMenu)
|
||||
state.ViewState = map[string]any{
|
||||
"drivers": drivers,
|
||||
"drivers_map": driversMap,
|
||||
"passengers_map": passengersMap,
|
||||
"bookings": bookings,
|
||||
"bookings_history": bookingsHistory,
|
||||
"filters": filters,
|
||||
"hist_filters": histFilters,
|
||||
"tab": tab,
|
||||
"trips_items_per_page": tripsItemsPerPage,
|
||||
"drivers_items_per_page": driversItemsPerPage,
|
||||
"geography_filters_enabled": geoFiltersEnabled,
|
||||
"geography_filters_list": enrichedGeoFilters,
|
||||
"archived": archived,
|
||||
}
|
||||
|
||||
renderer.Render("organized carpool overview", w, r, files, state)
|
||||
}
|
||||
|
||||
func (renderer *Renderer) OrganizedCarpoolCreateDriver(w http.ResponseWriter, r *http.Request) {
|
||||
files := renderer.ThemeConfig.GetStringSlice("views.organized_carpool.driver_create.files")
|
||||
state := NewState(r, renderer.ThemeConfig, organizedCarpoolMenu)
|
||||
state.ViewState = map[string]any{}
|
||||
|
||||
renderer.Render("organized carpool driver creation", w, r, files, state)
|
||||
}
|
||||
|
||||
func (renderer *Renderer) OrganizedCarpoolUpdateDriver(w http.ResponseWriter, r *http.Request, driver any) {
|
||||
files := renderer.ThemeConfig.GetStringSlice("views.organized_carpool.driver_update.files")
|
||||
state := NewState(r, renderer.ThemeConfig, organizedCarpoolMenu)
|
||||
state.ViewState = map[string]any{
|
||||
"driver": driver,
|
||||
}
|
||||
|
||||
renderer.Render("organized carpool driver update", w, r, files, state)
|
||||
}
|
||||
|
||||
func (renderer *Renderer) OrganizedCarpoolDriverDisplay(w http.ResponseWriter, r *http.Request, driver mobilityaccountsstorage.Account, trips any, documents any, bookings any, beneficiariesMap any, stats map[string]any, walletBalance float64, tab string) {
|
||||
files := renderer.ThemeConfig.GetStringSlice("views.organized_carpool.driver_display.files")
|
||||
state := NewState(r, renderer.ThemeConfig, organizedCarpoolMenu)
|
||||
|
||||
drivers_file_types := renderer.GlobalConfig.GetStringSlice("modules.organized_carpool.drivers.documents_types")
|
||||
file_types_map := renderer.GlobalConfig.GetStringMapString("storage.files.file_types")
|
||||
|
||||
state.ViewState = map[string]any{
|
||||
"driver": driver,
|
||||
"trips": trips,
|
||||
"documents": documents,
|
||||
"bookings": bookings,
|
||||
"beneficiaries_map": beneficiariesMap,
|
||||
"stats": stats,
|
||||
"drivers_file_types": drivers_file_types,
|
||||
"file_types_map": file_types_map,
|
||||
"wallet_balance": walletBalance,
|
||||
"tab": tab,
|
||||
}
|
||||
|
||||
renderer.Render("organized carpool driver display", w, r, files, state)
|
||||
}
|
||||
|
||||
func (renderer *Renderer) OrganizedCarpoolJourney(w http.ResponseWriter, r *http.Request, journey any, driver any, passenger any, beneficiaries any, passengerWalletBalance float64, pricingResult map[string]pricing.Price) {
|
||||
files := renderer.ThemeConfig.GetStringSlice("views.organized_carpool.journey.files")
|
||||
bookingMotivations := renderer.GlobalConfig.Get("modules.organized_carpool.booking_motivations")
|
||||
state := NewState(r, renderer.ThemeConfig, organizedCarpoolMenu)
|
||||
state.ViewState = map[string]any{
|
||||
"driver": driver,
|
||||
"passenger": passenger,
|
||||
"beneficiaries": beneficiaries,
|
||||
"journey": journey,
|
||||
"config": renderer.GlobalConfig,
|
||||
"booking_motivations": bookingMotivations,
|
||||
"passenger_wallet_balance": passengerWalletBalance,
|
||||
"pricing_result": pricingResult,
|
||||
}
|
||||
|
||||
renderer.Render("organized carpool journey", w, r, files, state)
|
||||
}
|
||||
|
||||
func (renderer *Renderer) OrganizedCarpoolBookingDisplay(w http.ResponseWriter, r *http.Request, booking any, driver any, passenger any, driverDepartureAddress, driverArrivalAddress string) {
|
||||
files := renderer.ThemeConfig.GetStringSlice("views.organized_carpool.booking_display.files")
|
||||
state := NewState(r, renderer.ThemeConfig, organizedCarpoolMenu)
|
||||
state.ViewState = map[string]any{
|
||||
"driver": driver,
|
||||
"passenger": passenger,
|
||||
"booking": booking,
|
||||
"driverDepartureAddress": driverDepartureAddress,
|
||||
"driverArrivalAddress": driverArrivalAddress,
|
||||
}
|
||||
|
||||
renderer.Render("organized carpool booking display", w, r, files, state)
|
||||
}
|
||||
@@ -5,8 +5,10 @@ import (
|
||||
"html/template"
|
||||
"net/http"
|
||||
|
||||
"git.coopgo.io/coopgo-apps/parcoursmob/utils/icons"
|
||||
"git.coopgo.io/coopgo-apps/parcoursmob/utils/identification"
|
||||
"git.coopgo.io/coopgo-apps/parcoursmob/core/utils/icons"
|
||||
"git.coopgo.io/coopgo-apps/parcoursmob/core/utils/identification"
|
||||
cache "git.coopgo.io/coopgo-apps/parcoursmob/core/utils/storage"
|
||||
xlsxrenderer "git.coopgo.io/coopgo-apps/parcoursmob/renderer/xlsx"
|
||||
"git.coopgo.io/coopgo-platform/emailing"
|
||||
"git.coopgo.io/coopgo-platform/groups-management/storage"
|
||||
"github.com/coreos/go-oidc/v3/oidc"
|
||||
@@ -19,9 +21,11 @@ type Renderer struct {
|
||||
GlobalConfig *viper.Viper
|
||||
ThemeConfig *viper.Viper
|
||||
Mailer *emailing.Mailer
|
||||
FileStorage cache.FileStorage
|
||||
XLSX *xlsxrenderer.XLSXRenderer
|
||||
}
|
||||
|
||||
func NewRenderer(global *viper.Viper, templates_dir string) *Renderer {
|
||||
func NewRenderer(global *viper.Viper, templates_dir string, filestorage cache.FileStorage) *Renderer {
|
||||
theme := viper.New()
|
||||
theme.SetConfigName("config")
|
||||
theme.AddConfigPath(templates_dir)
|
||||
@@ -33,11 +37,12 @@ func NewRenderer(global *viper.Viper, templates_dir string) *Renderer {
|
||||
TemplatesDir: templates_dir,
|
||||
GlobalConfig: global,
|
||||
ThemeConfig: theme,
|
||||
FileStorage: filestorage,
|
||||
XLSX: xlsxrenderer.NewXLSXRenderer(global),
|
||||
}
|
||||
}
|
||||
|
||||
func (renderer *Renderer) Render(name string, w http.ResponseWriter, r *http.Request, files []string, state RenderState) {
|
||||
|
||||
genericFiles := renderer.ThemeConfig.GetStringSlice("views.generic.files")
|
||||
|
||||
prefixed_files := []string{}
|
||||
@@ -49,54 +54,28 @@ func (renderer *Renderer) Render(name string, w http.ResponseWriter, r *http.Req
|
||||
}
|
||||
|
||||
w.WriteHeader(http.StatusOK)
|
||||
t := template.New(name).Funcs(
|
||||
template.FuncMap{
|
||||
"timeFrom": TimeFrom,
|
||||
"timeFormat": TimeFormat,
|
||||
"genderISO5218": GenderISO5218,
|
||||
"dict": Dict,
|
||||
"json": JSON,
|
||||
"rawjson": RawJSON,
|
||||
"unescapeHTML": UnescapeHTML,
|
||||
"walkingLength": WalkingLength,
|
||||
"divideFloat64": Divide[float64],
|
||||
"divideInt": Divide[int],
|
||||
},
|
||||
)
|
||||
t := template.New(name).Funcs(GetTemplateFuncMap(state.Group, renderer.GlobalConfig, renderer.FileStorage))
|
||||
t = template.Must(t.ParseFiles(prefixed_files...))
|
||||
|
||||
err := t.ExecuteTemplate(w, "main", state)
|
||||
if err != nil {
|
||||
log.Error().Err(err).Msg("")
|
||||
log.Error().Err(err).Msg("issue executing template")
|
||||
}
|
||||
}
|
||||
|
||||
func (renderer *Renderer) RenderNoLayout(name string, w http.ResponseWriter, r *http.Request, files []string, state RenderState) {
|
||||
|
||||
prefixed_files := []string{}
|
||||
for _, f := range files {
|
||||
prefixed_files = append(prefixed_files, renderer.templateFile(f))
|
||||
}
|
||||
|
||||
w.WriteHeader(http.StatusOK)
|
||||
t := template.New(name).Funcs(
|
||||
template.FuncMap{
|
||||
"timeFrom": TimeFrom,
|
||||
"timeFormat": TimeFormat,
|
||||
"genderISO5218": GenderISO5218,
|
||||
"dict": Dict,
|
||||
"json": JSON,
|
||||
"rawjson": RawJSON,
|
||||
"unsescapeHTML": UnescapeHTML,
|
||||
"divideFloat64": Divide[float64],
|
||||
"divideInt": Divide[int],
|
||||
},
|
||||
)
|
||||
t := template.New(name).Funcs(GetTemplateFuncMap(state.Group, renderer.GlobalConfig, renderer.FileStorage))
|
||||
|
||||
t = template.Must(t.ParseFiles(prefixed_files...))
|
||||
err := t.ExecuteTemplate(w, "main", state)
|
||||
if err != nil {
|
||||
log.Error().Err(err).Msg("")
|
||||
log.Error().Err(err).Msg("issue executing template")
|
||||
}
|
||||
}
|
||||
|
||||
@@ -116,6 +95,7 @@ type RenderState struct {
|
||||
|
||||
func NewState(r *http.Request, themeConfig *viper.Viper, menuState string) RenderState {
|
||||
iconset := themeConfig.GetStringMapString("icons.svg")
|
||||
menu := themeConfig.Get("menu_items")
|
||||
|
||||
// Get State elements from Request
|
||||
var userid string
|
||||
@@ -161,6 +141,10 @@ func NewState(r *http.Request, themeConfig *viper.Viper, menuState string) Rende
|
||||
Active: menuState == administrationMenu,
|
||||
},
|
||||
|
||||
Menu: menu,
|
||||
ActiveMenu: menuState,
|
||||
|
||||
// DEPRECATED
|
||||
MenuItems: []MenuItem{
|
||||
{
|
||||
Title: "Tableau de bord",
|
||||
@@ -171,6 +155,7 @@ func NewState(r *http.Request, themeConfig *viper.Viper, menuState string) Rende
|
||||
},
|
||||
}
|
||||
|
||||
// DEPRECATED
|
||||
if modules["beneficiaries"] != nil && modules["beneficiaries"].(bool) {
|
||||
ls.MenuItems = append(ls.MenuItems, MenuItem{
|
||||
Title: "Bénéficiaires",
|
||||
@@ -189,6 +174,15 @@ func NewState(r *http.Request, themeConfig *viper.Viper, menuState string) Rende
|
||||
})
|
||||
}
|
||||
|
||||
if modules["solidarity_transport"] != nil && modules["solidarity_transport"].(bool) {
|
||||
ls.MenuItems = append(ls.MenuItems, MenuItem{
|
||||
Title: "Transport solidaire",
|
||||
Link: "/app/solidarity-transport/",
|
||||
Active: menuState == solidarityTransportMenu,
|
||||
Icon: "tabler-icons:car",
|
||||
})
|
||||
}
|
||||
|
||||
if modules["vehicles"] != nil && modules["vehicles"].(bool) {
|
||||
ls.MenuItems = append(ls.MenuItems, MenuItem{
|
||||
Title: "Véhicules partagés",
|
||||
@@ -223,7 +217,6 @@ func NewState(r *http.Request, themeConfig *viper.Viper, menuState string) Rende
|
||||
Active: menuState == groupMenu,
|
||||
Icon: "hero:outline/group_module",
|
||||
})
|
||||
|
||||
}
|
||||
|
||||
if modules["support"] != nil && modules["support"].(bool) {
|
||||
@@ -233,7 +226,6 @@ func NewState(r *http.Request, themeConfig *viper.Viper, menuState string) Rende
|
||||
Active: menuState == commentMenu,
|
||||
Icon: "hero:outline/support",
|
||||
})
|
||||
|
||||
}
|
||||
|
||||
if modules["directory"] != nil && modules["directory"].(bool) {
|
||||
@@ -244,22 +236,7 @@ func NewState(r *http.Request, themeConfig *viper.Viper, menuState string) Rende
|
||||
Icon: "hero:outline/document-text",
|
||||
})
|
||||
}
|
||||
if modules["conseillers"] != nil && modules["conseillers"].(bool) {
|
||||
ls.MenuItems = append(ls.MenuItems, MenuItem{
|
||||
Title: "Conseillers",
|
||||
Link: "/app/conseillers/",
|
||||
Active: menuState == membersMenu,
|
||||
Icon: "hero:outline/user-group",
|
||||
})
|
||||
}
|
||||
if modules["diags"] != nil && modules["diags"].(bool) {
|
||||
ls.MenuItems = append(ls.MenuItems, MenuItem{
|
||||
Title: "Diagnostics",
|
||||
Link: "/app/diags/",
|
||||
Active: menuState == diagsMenu,
|
||||
Icon: "hero:outline/document-text",
|
||||
})
|
||||
}
|
||||
|
||||
return RenderState{
|
||||
IconSet: icons.NewIconSet(iconset),
|
||||
Group: group,
|
||||
|
||||
16
renderer/solidarity-transport-ext.go
Normal file
16
renderer/solidarity-transport-ext.go
Normal file
@@ -0,0 +1,16 @@
|
||||
package renderer
|
||||
|
||||
import "net/http"
|
||||
|
||||
func (renderer *Renderer) SolidarityTransportExternalBookingDisplay(w http.ResponseWriter, r *http.Request, booking any, driver any, passenger any) {
|
||||
files := renderer.ThemeConfig.GetStringSlice("views.solidarity_transport.ext.booking_proposal.files")
|
||||
state := NewState(r, renderer.ThemeConfig, solidarityTransportMenu)
|
||||
state.ViewState = map[string]any{
|
||||
"driver": driver,
|
||||
"passenger": passenger,
|
||||
"booking": booking,
|
||||
"config": renderer.GlobalConfig,
|
||||
}
|
||||
|
||||
renderer.RenderNoLayout("booking display", w, r, files, state)
|
||||
}
|
||||
130
renderer/solidarity-transport.go
Normal file
130
renderer/solidarity-transport.go
Normal file
@@ -0,0 +1,130 @@
|
||||
package renderer
|
||||
|
||||
import (
|
||||
"net/http"
|
||||
|
||||
mobilityaccountsstorage "git.coopgo.io/coopgo-platform/mobility-accounts/storage"
|
||||
"git.coopgo.io/coopgo-platform/payments/pricing"
|
||||
)
|
||||
|
||||
const solidarityTransportMenu = "solidarity_transport"
|
||||
|
||||
func (renderer *Renderer) SolidarityTransportOverview(w http.ResponseWriter, r *http.Request, drivers any, driversMap any, passengersMap any, bookings any, bookingsHistory any, filters any, hist_filters any, tab string, enrichedGeoFilters []map[string]string, archived bool) {
|
||||
files := renderer.ThemeConfig.GetStringSlice("views.solidarity_transport.overview.files")
|
||||
tripsItemsPerPage := renderer.GlobalConfig.GetInt("modules.solidarity_transport.pagination.trips_items_per_page")
|
||||
driversItemsPerPage := renderer.GlobalConfig.GetInt("modules.solidarity_transport.pagination.drivers_items_per_page")
|
||||
|
||||
guaranteedMotivations := renderer.GlobalConfig.GetStringSlice("modules.solidarity_transport.guaranteed_trip_motivations")
|
||||
|
||||
// Geography filters
|
||||
geoFiltersEnabled := len(enrichedGeoFilters) > 0
|
||||
|
||||
state := NewState(r, renderer.ThemeConfig, solidarityTransportMenu)
|
||||
state.ViewState = map[string]any{
|
||||
"drivers": drivers,
|
||||
"drivers_map": driversMap,
|
||||
"passengers_map": passengersMap,
|
||||
"bookings": bookings,
|
||||
"bookings_history": bookingsHistory,
|
||||
"filters": filters,
|
||||
"hist_filters": hist_filters,
|
||||
"tab": tab,
|
||||
"trips_items_per_page": tripsItemsPerPage,
|
||||
"drivers_items_per_page": driversItemsPerPage,
|
||||
"guaranteed_trip_motivations": guaranteedMotivations,
|
||||
"geography_filters_enabled": geoFiltersEnabled,
|
||||
"geography_filters_list": enrichedGeoFilters,
|
||||
"archived": archived,
|
||||
}
|
||||
|
||||
renderer.Render("solidarity transport overview", w, r, files, state)
|
||||
}
|
||||
|
||||
func (renderer *Renderer) SolidarityTransportCreateDriver(w http.ResponseWriter, r *http.Request) {
|
||||
files := renderer.ThemeConfig.GetStringSlice("views.solidarity_transport.driver_create.files")
|
||||
profileFields := renderer.GlobalConfig.Get("modules.solidarity_transport.drivers.profile_optional_fields")
|
||||
|
||||
state := NewState(r, renderer.ThemeConfig, solidarityTransportMenu)
|
||||
state.ViewState = map[string]any{
|
||||
"profile_optional_fields": profileFields,
|
||||
}
|
||||
|
||||
renderer.Render("solidarity transport driver creation", w, r, files, state)
|
||||
}
|
||||
|
||||
func (renderer *Renderer) SolidarityTransportUpdateDriver(w http.ResponseWriter, r *http.Request, driver any) {
|
||||
files := renderer.ThemeConfig.GetStringSlice("views.solidarity_transport.driver_update.files")
|
||||
profileFields := renderer.GlobalConfig.Get("modules.solidarity_transport.drivers.profile_optional_fields")
|
||||
|
||||
state := NewState(r, renderer.ThemeConfig, solidarityTransportMenu)
|
||||
state.ViewState = map[string]any{
|
||||
"driver": driver,
|
||||
"profile_optional_fields": profileFields,
|
||||
}
|
||||
|
||||
renderer.Render("solidarity transport driver update", w, r, files, state)
|
||||
}
|
||||
|
||||
func (renderer *Renderer) SolidarityTransportDriverDisplay(w http.ResponseWriter, r *http.Request, driver mobilityaccountsstorage.Account, availabilities any, documents any, bookings any, beneficiariesMap any, stats map[string]any, walletBalance float64, tab string) {
|
||||
files := renderer.ThemeConfig.GetStringSlice("views.solidarity_transport.driver_display.files")
|
||||
profileFields := renderer.GlobalConfig.Get("modules.solidarity_transport.drivers.profile_optional_fields")
|
||||
state := NewState(r, renderer.ThemeConfig, solidarityTransportMenu)
|
||||
|
||||
drivers_file_types := renderer.GlobalConfig.GetStringSlice("modules.solidarity_transport.drivers.documents_types")
|
||||
file_types_map := renderer.GlobalConfig.GetStringMapString("storage.files.file_types")
|
||||
|
||||
state.ViewState = map[string]any{
|
||||
"driver": driver,
|
||||
"availabilities": availabilities,
|
||||
"bookings": bookings,
|
||||
"beneficiaries_map": beneficiariesMap,
|
||||
"documents": documents,
|
||||
"drivers_file_types": drivers_file_types,
|
||||
"file_types_map": file_types_map,
|
||||
"stats": stats,
|
||||
"profile_optional_fields": profileFields,
|
||||
"wallet_balance": walletBalance,
|
||||
"tab": tab,
|
||||
}
|
||||
|
||||
renderer.Render("solidarity transport driver creation", w, r, files, state)
|
||||
}
|
||||
|
||||
func (renderer *Renderer) SolidarityTransportDriverJourney(w http.ResponseWriter, r *http.Request, driverJourney any, driver any, passenger any, beneficiaries any, passengerWalletBalance float64, pricingResult map[string]pricing.Price, replacesBookingID string) {
|
||||
files := renderer.ThemeConfig.GetStringSlice("views.solidarity_transport.driver_journey.files")
|
||||
bookingMotivations := renderer.GlobalConfig.Get("modules.solidarity_transport.booking_motivations")
|
||||
state := NewState(r, renderer.ThemeConfig, solidarityTransportMenu)
|
||||
state.ViewState = map[string]any{
|
||||
"driver": driver,
|
||||
"passenger": passenger,
|
||||
"beneficiaries": beneficiaries,
|
||||
"driver_journey": driverJourney,
|
||||
"config": renderer.GlobalConfig,
|
||||
"passenger_wallet_balance": passengerWalletBalance,
|
||||
"pricing_result": pricingResult,
|
||||
"booking_motivations": bookingMotivations,
|
||||
"replaces_booking_id": replacesBookingID,
|
||||
}
|
||||
|
||||
renderer.Render("solidarity transport driver creation", w, r, files, state)
|
||||
}
|
||||
|
||||
func (renderer *Renderer) SolidarityTransportBookingDisplay(w http.ResponseWriter, r *http.Request, booking any, driver any, passenger any, passengerWalletBalance float64, replacementDrivers any, replacementDriversMap any, replacementPricing any, replacementLocations any) {
|
||||
files := renderer.ThemeConfig.GetStringSlice("views.solidarity_transport.booking_display.files")
|
||||
bookingMotivations := renderer.GlobalConfig.Get("modules.solidarity_transport.booking_motivations")
|
||||
state := NewState(r, renderer.ThemeConfig, solidarityTransportMenu)
|
||||
state.ViewState = map[string]any{
|
||||
"driver": driver,
|
||||
"passenger": passenger,
|
||||
"booking": booking,
|
||||
"config": renderer.GlobalConfig,
|
||||
"passenger_wallet_balance": passengerWalletBalance,
|
||||
"booking_motivations": bookingMotivations,
|
||||
"replacement_drivers": replacementDrivers,
|
||||
"replacement_drivers_map": replacementDriversMap,
|
||||
"replacement_pricing": replacementPricing,
|
||||
"replacement_locations": replacementLocations,
|
||||
}
|
||||
|
||||
renderer.Render("booking display", w, r, files, state)
|
||||
}
|
||||
@@ -3,7 +3,7 @@ package renderer
|
||||
import (
|
||||
"net/http"
|
||||
|
||||
filestorage "git.coopgo.io/coopgo-apps/parcoursmob/utils/storage"
|
||||
filestorage "git.coopgo.io/coopgo-apps/parcoursmob/core/utils/storage"
|
||||
fleetsstorage "git.coopgo.io/coopgo-platform/fleets/storage"
|
||||
mobilityaccountsstorage "git.coopgo.io/coopgo-platform/mobility-accounts/storage"
|
||||
)
|
||||
@@ -23,7 +23,7 @@ func (renderer *Renderer) VehiclesManagementOverview(w http.ResponseWriter, r *h
|
||||
renderer.Render("fleet overview", w, r, files, state)
|
||||
}
|
||||
|
||||
func (renderer *Renderer) VehiclesManagementBookingsList(w http.ResponseWriter, r *http.Request, vehiclesMap map[string]fleetsstorage.Vehicle, driversMap map[string]mobilityaccountsstorage.Account, bookings []fleetsstorage.Booking, cacheid string) {
|
||||
func (renderer *Renderer) VehiclesManagementBookingsList(w http.ResponseWriter, r *http.Request, vehiclesMap map[string]fleetsstorage.Vehicle, driversMap map[string]mobilityaccountsstorage.Account, bookings []fleetsstorage.Booking, cacheid string, filters map[string]string) {
|
||||
files := renderer.ThemeConfig.GetStringSlice("views.vehicles_management.bookings_list.files")
|
||||
state := NewState(r, renderer.ThemeConfig, vehiclesmanagementMenu)
|
||||
state.ViewState = map[string]any{
|
||||
@@ -31,6 +31,7 @@ func (renderer *Renderer) VehiclesManagementBookingsList(w http.ResponseWriter,
|
||||
"vehicles_map": vehiclesMap,
|
||||
"drivers_map": driversMap,
|
||||
"cacheid": cacheid,
|
||||
"filters": filters,
|
||||
}
|
||||
|
||||
renderer.Render("fleet overview", w, r, files, state)
|
||||
@@ -38,20 +39,26 @@ func (renderer *Renderer) VehiclesManagementBookingsList(w http.ResponseWriter,
|
||||
|
||||
func (renderer *Renderer) VehiclesFleetAdd(w http.ResponseWriter, r *http.Request, vehicle_types []string) {
|
||||
files := renderer.ThemeConfig.GetStringSlice("views.vehicles_management.fleet_add.files")
|
||||
vehicleOptionalFields := renderer.GlobalConfig.Get("modules.fleets.vehicle_optional_fields")
|
||||
|
||||
state := NewState(r, renderer.ThemeConfig, vehiclesmanagementMenu)
|
||||
state.ViewState = map[string]any{
|
||||
"vehicle_types": vehicle_types,
|
||||
"vehicle_optional_fields": vehicleOptionalFields,
|
||||
}
|
||||
|
||||
renderer.Render("fleet add vehicle", w, r, files, state)
|
||||
}
|
||||
|
||||
func (renderer *Renderer) VehiclesFleetDisplay(w http.ResponseWriter, r *http.Request, vehicle any, diags []any) {
|
||||
func (renderer *Renderer) VehiclesFleetDisplay(w http.ResponseWriter, r *http.Request, vehicle any, beneficiaries any) {
|
||||
files := renderer.ThemeConfig.GetStringSlice("views.vehicles_management.fleet_display.files")
|
||||
vehicleOptionalFields := renderer.GlobalConfig.Get("modules.fleets.vehicle_optional_fields")
|
||||
|
||||
state := NewState(r, renderer.ThemeConfig, vehiclesmanagementMenu)
|
||||
state.ViewState = map[string]any{
|
||||
"vehicle": vehicle,
|
||||
"diags": diags,
|
||||
"beneficiaries": beneficiaries,
|
||||
"vehicle_optional_fields": vehicleOptionalFields,
|
||||
}
|
||||
|
||||
renderer.Render("fleet display vehicle", w, r, files, state)
|
||||
@@ -59,16 +66,19 @@ func (renderer *Renderer) VehiclesFleetDisplay(w http.ResponseWriter, r *http.Re
|
||||
|
||||
func (renderer *Renderer) VehiclesFleetUpdate(w http.ResponseWriter, r *http.Request, vehicle any, vehicle_types []string) {
|
||||
files := renderer.ThemeConfig.GetStringSlice("views.vehicles_management.fleet_update.files")
|
||||
vehicleOptionalFields := renderer.GlobalConfig.Get("modules.fleets.vehicle_optional_fields")
|
||||
|
||||
state := NewState(r, renderer.ThemeConfig, vehiclesmanagementMenu)
|
||||
state.ViewState = map[string]any{
|
||||
"vehicle": vehicle,
|
||||
"vehicle_types": vehicle_types,
|
||||
"vehicle_optional_fields": vehicleOptionalFields,
|
||||
}
|
||||
|
||||
renderer.Render("fleet display vehicle", w, r, files, state)
|
||||
}
|
||||
|
||||
func (renderer *Renderer) VehicleManagementBookingDisplay(w http.ResponseWriter, r *http.Request, booking any, vehicle any, beneficiary any, group any, documents []filestorage.FileInfo, file_types_map map[string]string, alternative_vehicles []any, diags []any) {
|
||||
func (renderer *Renderer) VehicleManagementBookingDisplay(w http.ResponseWriter, r *http.Request, booking any, vehicle any, beneficiary any, group any, documents []filestorage.FileInfo, file_types_map map[string]string, alternative_vehicles []any) {
|
||||
files := renderer.ThemeConfig.GetStringSlice("views.vehicles_management.booking_display.files")
|
||||
state := NewState(r, renderer.ThemeConfig, vehiclesmanagementMenu)
|
||||
state.ViewState = map[string]any{
|
||||
@@ -79,7 +89,6 @@ func (renderer *Renderer) VehicleManagementBookingDisplay(w http.ResponseWriter,
|
||||
"documents": documents,
|
||||
"file_types_map": file_types_map,
|
||||
"alternative_vehicles": alternative_vehicles,
|
||||
"diags": diags,
|
||||
}
|
||||
|
||||
renderer.Render("vehicles search", w, r, files, state)
|
||||
@@ -93,5 +102,4 @@ func (renderer *Renderer) UnbookingVehicle(w http.ResponseWriter, r *http.Reques
|
||||
}
|
||||
|
||||
renderer.Render("vehicule unbooking", w, r, files, state)
|
||||
|
||||
}
|
||||
|
||||
@@ -3,8 +3,9 @@ package renderer
|
||||
import (
|
||||
"net/http"
|
||||
|
||||
filestorage "git.coopgo.io/coopgo-apps/parcoursmob/utils/storage"
|
||||
filestorage "git.coopgo.io/coopgo-apps/parcoursmob/core/utils/storage"
|
||||
"git.coopgo.io/coopgo-platform/fleets/storage"
|
||||
fleetsstorage "git.coopgo.io/coopgo-platform/fleets/storage"
|
||||
mobilityaccountsstorage "git.coopgo.io/coopgo-platform/mobility-accounts/storage"
|
||||
)
|
||||
|
||||
@@ -22,7 +23,7 @@ func selectDocumentsDefaults(beneficiarydocuments []filestorage.FileInfo, mandat
|
||||
return res
|
||||
}
|
||||
|
||||
func (renderer *Renderer) VehiclesSearch(w http.ResponseWriter, r *http.Request, beneficiaries []mobilityaccountsstorage.Account, searched bool, vehicles []any, beneficiary any, startdate any, enddate any, mandatory_documents []string, file_types_map map[string]string, beneficiarydocuments []filestorage.FileInfo, selected_type string, automatic bool, vehicles_types []string, admingroups map[string]any) {
|
||||
func (renderer *Renderer) VehiclesSearch(w http.ResponseWriter, r *http.Request, beneficiaries []mobilityaccountsstorage.Account, searched bool, vehicles []fleetsstorage.Vehicle, beneficiary any, startdate any, enddate any, mandatory_documents []string, file_types_map map[string]string, beneficiarydocuments []filestorage.FileInfo, selected_type string, automatic bool, vehicles_types []string, admingroups map[string]any) {
|
||||
files := renderer.ThemeConfig.GetStringSlice("views.vehicles.search.files")
|
||||
state := NewState(r, renderer.ThemeConfig, vehiclesMenu)
|
||||
viewstate := map[string]any{
|
||||
@@ -52,7 +53,7 @@ func (renderer *Renderer) VehiclesSearch(w http.ResponseWriter, r *http.Request,
|
||||
renderer.Render("vehicles search", w, r, files, state)
|
||||
}
|
||||
|
||||
func (renderer *Renderer) VehicleBookingDisplay(w http.ResponseWriter, r *http.Request, booking any, vehicle any, beneficiary any, group any, documents []filestorage.FileInfo, file_types_map map[string]string, diags []any) {
|
||||
func (renderer *Renderer) VehicleBookingDisplay(w http.ResponseWriter, r *http.Request, booking any, vehicle any, beneficiary any, group any, documents []filestorage.FileInfo, file_types_map map[string]string) {
|
||||
files := renderer.ThemeConfig.GetStringSlice("views.vehicles.booking_display.files")
|
||||
state := NewState(r, renderer.ThemeConfig, vehiclesMenu)
|
||||
state.ViewState = map[string]any{
|
||||
@@ -62,7 +63,6 @@ func (renderer *Renderer) VehicleBookingDisplay(w http.ResponseWriter, r *http.R
|
||||
"group": group,
|
||||
"documents": documents,
|
||||
"file_types_map": file_types_map,
|
||||
"diags": diags,
|
||||
}
|
||||
|
||||
renderer.Render("vehicles search", w, r, files, state)
|
||||
|
||||
273
renderer/xlsx/organized-carpool.go
Normal file
273
renderer/xlsx/organized-carpool.go
Normal file
@@ -0,0 +1,273 @@
|
||||
package xlsx
|
||||
|
||||
import (
|
||||
"fmt"
|
||||
"net/http"
|
||||
|
||||
"git.coopgo.io/coopgo-apps/parcoursmob/core/application"
|
||||
"git.coopgo.io/coopgo-apps/parcoursmob/core/utils/gender"
|
||||
"github.com/rs/zerolog/log"
|
||||
)
|
||||
|
||||
func (r *XLSXRenderer) OrganizedCarpoolBookings(w http.ResponseWriter, result *application.OrganizedCarpoolBookingsResult) {
|
||||
// Create Excel spreadsheet
|
||||
spreadsheet := r.NewSpreadsheet("Covoiturage solidaire")
|
||||
|
||||
// Build headers dynamically based on configuration
|
||||
headers := []string{
|
||||
"ID Réservation",
|
||||
"Statut",
|
||||
"Motif de réservation",
|
||||
"Date de prise en charge",
|
||||
"Heure de prise en charge",
|
||||
}
|
||||
|
||||
// Add driver fields from config
|
||||
driverOptionalFields := r.Config.Get("modules.organized_carpool.profile_optional_fields")
|
||||
driverFields := []string{"last_name", "first_name", "email", "phone_number"}
|
||||
driverHeaders := []string{"Conducteur - Nom", "Conducteur - Prénom", "Conducteur - Email", "Conducteur - Téléphone"}
|
||||
|
||||
if driverOptionalFieldsList, ok := driverOptionalFields.([]interface{}); ok {
|
||||
for _, field := range driverOptionalFieldsList {
|
||||
if fieldMap, ok := field.(map[string]interface{}); ok {
|
||||
if name, ok := fieldMap["name"].(string); ok {
|
||||
driverFields = append(driverFields, name)
|
||||
label := name
|
||||
if labelVal, ok := fieldMap["label"].(string); ok {
|
||||
label = labelVal
|
||||
}
|
||||
driverHeaders = append(driverHeaders, fmt.Sprintf("Conducteur - %s", label))
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
headers = append(headers, driverHeaders...)
|
||||
|
||||
// Add beneficiary fields from config
|
||||
beneficiaryOptionalFields := r.Config.Get("modules.beneficiaries.profile_optional_fields")
|
||||
beneficiaryFields := []string{"last_name", "first_name", "email", "phone_number"}
|
||||
beneficiaryHeaders := []string{"Bénéficiaire - Nom", "Bénéficiaire - Prénom", "Bénéficiaire - Email", "Bénéficiaire - Téléphone"}
|
||||
|
||||
if beneficiaryOptionalFieldsList, ok := beneficiaryOptionalFields.([]interface{}); ok {
|
||||
for _, field := range beneficiaryOptionalFieldsList {
|
||||
if fieldMap, ok := field.(map[string]interface{}); ok {
|
||||
if name, ok := fieldMap["name"].(string); ok {
|
||||
beneficiaryFields = append(beneficiaryFields, name)
|
||||
label := name
|
||||
if labelVal, ok := fieldMap["label"].(string); ok {
|
||||
label = labelVal
|
||||
}
|
||||
beneficiaryHeaders = append(beneficiaryHeaders, fmt.Sprintf("Bénéficiaire - %s", label))
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
headers = append(headers, beneficiaryHeaders...)
|
||||
|
||||
// Add journey information headers
|
||||
headers = append(headers,
|
||||
"Lieu de départ - Adresse",
|
||||
"Destination - Adresse",
|
||||
"Distance passager (km)",
|
||||
"Durée trajet (minutes)",
|
||||
"Prix passager",
|
||||
"Devise prix passager",
|
||||
"Compensation conducteur",
|
||||
"Devise compensation",
|
||||
)
|
||||
|
||||
spreadsheet.SetHeaders(headers)
|
||||
|
||||
// Add data rows
|
||||
for _, booking := range result.Bookings {
|
||||
driver := result.DriversMap[booking.Driver.Id]
|
||||
beneficiary := result.BeneficiariesMap[booking.Passenger.Id]
|
||||
|
||||
row := []interface{}{}
|
||||
|
||||
// Booking information
|
||||
row = append(row, booking.Id)
|
||||
row = append(row, booking.Status.String())
|
||||
|
||||
// Motivation
|
||||
motivation := ""
|
||||
if booking.Motivation != nil {
|
||||
motivation = *booking.Motivation
|
||||
}
|
||||
row = append(row, motivation)
|
||||
|
||||
// Journey date and time
|
||||
row = append(row, booking.PassengerPickupDate.AsTime().Format("2006-01-02"))
|
||||
row = append(row, booking.PassengerPickupDate.AsTime().Format("15:04"))
|
||||
|
||||
// Driver data
|
||||
for _, field := range driverFields {
|
||||
row = append(row, getAccountFieldValue(driver.Data, field))
|
||||
}
|
||||
|
||||
// Beneficiary data
|
||||
for _, field := range beneficiaryFields {
|
||||
row = append(row, getAccountFieldValue(beneficiary.Data, field))
|
||||
}
|
||||
|
||||
// Journey information
|
||||
if booking.PassengerPickupAddress != nil {
|
||||
row = append(row, *booking.PassengerPickupAddress)
|
||||
} else {
|
||||
row = append(row, "")
|
||||
}
|
||||
|
||||
if booking.PassengerDropAddress != nil {
|
||||
row = append(row, *booking.PassengerDropAddress)
|
||||
} else {
|
||||
row = append(row, "")
|
||||
}
|
||||
|
||||
// Distance
|
||||
if booking.Distance != nil {
|
||||
row = append(row, *booking.Distance)
|
||||
} else {
|
||||
row = append(row, "")
|
||||
}
|
||||
|
||||
// Duration
|
||||
if booking.Duration != nil {
|
||||
row = append(row, *booking.Duration)
|
||||
} else {
|
||||
row = append(row, "")
|
||||
}
|
||||
|
||||
// Pricing
|
||||
if booking.Price != nil && booking.Price.Amount != nil {
|
||||
row = append(row, fmt.Sprintf("%.2f", *booking.Price.Amount))
|
||||
if booking.Price.Currency != nil {
|
||||
row = append(row, *booking.Price.Currency)
|
||||
} else {
|
||||
row = append(row, "")
|
||||
}
|
||||
} else {
|
||||
row = append(row, "", "")
|
||||
}
|
||||
|
||||
// Driver compensation
|
||||
if booking.DriverCompensationAmount != nil {
|
||||
row = append(row, fmt.Sprintf("%.2f", *booking.DriverCompensationAmount))
|
||||
if booking.DriverCompensationCurrency != nil {
|
||||
row = append(row, *booking.DriverCompensationCurrency)
|
||||
} else {
|
||||
row = append(row, "")
|
||||
}
|
||||
} else {
|
||||
row = append(row, "", "")
|
||||
}
|
||||
|
||||
spreadsheet.AddRow(row)
|
||||
}
|
||||
|
||||
// Write Excel to response
|
||||
w.Header().Set("Content-Type", "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet")
|
||||
w.Header().Set("Content-Disposition", "attachment; filename=\"export-covoiturage-solidaire.xlsx\"")
|
||||
|
||||
if err := spreadsheet.GetFile().Write(w); err != nil {
|
||||
log.Error().Err(err).Msg("Error generating Excel file")
|
||||
http.Error(w, "Error generating Excel file", http.StatusInternalServerError)
|
||||
return
|
||||
}
|
||||
}
|
||||
|
||||
func (r *XLSXRenderer) OrganizedCarpoolDrivers(w http.ResponseWriter, result *application.OrganizedCarpoolOverviewResult) {
|
||||
// Create Excel spreadsheet
|
||||
spreadsheet := r.NewSpreadsheet("Covoitureurs solidaires")
|
||||
|
||||
// Build headers dynamically based on configuration
|
||||
driverOptionalFields := r.Config.Get("modules.organized_carpool.drivers.profile_optional_fields")
|
||||
driverFields := []string{"last_name", "first_name", "email", "phone_number", "birthdate", "gender", "file_number"}
|
||||
headers := []string{"ID", "Nom", "Prénom", "Email", "Téléphone", "Date de naissance", "Genre", "Numéro de dossier"}
|
||||
|
||||
if driverOptionalFieldsList, ok := driverOptionalFields.([]interface{}); ok {
|
||||
for _, field := range driverOptionalFieldsList {
|
||||
if fieldMap, ok := field.(map[string]interface{}); ok {
|
||||
if name, ok := fieldMap["name"].(string); ok {
|
||||
driverFields = append(driverFields, name)
|
||||
label := name
|
||||
if labelVal, ok := fieldMap["label"].(string); ok {
|
||||
label = labelVal
|
||||
}
|
||||
headers = append(headers, label)
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// Add address columns
|
||||
headers = append(headers, "Adresse départ", "Adresse destination", "Archivé")
|
||||
|
||||
spreadsheet.SetHeaders(headers)
|
||||
|
||||
// Add data rows
|
||||
for _, driver := range result.Accounts {
|
||||
row := []interface{}{}
|
||||
|
||||
// Driver ID
|
||||
row = append(row, driver.ID)
|
||||
|
||||
// Driver data
|
||||
for _, field := range driverFields {
|
||||
value := getAccountFieldValue(driver.Data, field)
|
||||
// Convert gender code to text
|
||||
if field == "gender" && value != "" {
|
||||
value = gender.ISO5218ToString(value)
|
||||
}
|
||||
row = append(row, value)
|
||||
}
|
||||
|
||||
// Address departure
|
||||
addressDeparture := ""
|
||||
if addr, ok := driver.Data["address"]; ok {
|
||||
if addrMap, ok := addr.(map[string]interface{}); ok {
|
||||
if props, ok := addrMap["properties"]; ok {
|
||||
if propsMap, ok := props.(map[string]interface{}); ok {
|
||||
if label, ok := propsMap["label"].(string); ok {
|
||||
addressDeparture = label
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
row = append(row, addressDeparture)
|
||||
|
||||
// Address destination
|
||||
addressDestination := ""
|
||||
if addr, ok := driver.Data["address_destination"]; ok {
|
||||
if addrMap, ok := addr.(map[string]interface{}); ok {
|
||||
if props, ok := addrMap["properties"]; ok {
|
||||
if propsMap, ok := props.(map[string]interface{}); ok {
|
||||
if label, ok := propsMap["label"].(string); ok {
|
||||
addressDestination = label
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
row = append(row, addressDestination)
|
||||
|
||||
// Archived status
|
||||
archived := "Non"
|
||||
if archivedVal, ok := driver.Data["archived"].(bool); ok && archivedVal {
|
||||
archived = "Oui"
|
||||
}
|
||||
row = append(row, archived)
|
||||
|
||||
spreadsheet.AddRow(row)
|
||||
}
|
||||
|
||||
// Write Excel to response
|
||||
w.Header().Set("Content-Type", "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet")
|
||||
w.Header().Set("Content-Disposition", "attachment; filename=\"export-covoitureurs-solidaires.xlsx\"")
|
||||
|
||||
if err := spreadsheet.GetFile().Write(w); err != nil {
|
||||
log.Error().Err(err).Msg("Error generating Excel file")
|
||||
http.Error(w, "Error generating Excel file", http.StatusInternalServerError)
|
||||
return
|
||||
}
|
||||
}
|
||||
332
renderer/xlsx/solidarity-transport.go
Normal file
332
renderer/xlsx/solidarity-transport.go
Normal file
@@ -0,0 +1,332 @@
|
||||
package xlsx
|
||||
|
||||
import (
|
||||
"fmt"
|
||||
"net/http"
|
||||
|
||||
"git.coopgo.io/coopgo-apps/parcoursmob/core/application"
|
||||
"git.coopgo.io/coopgo-apps/parcoursmob/core/utils/gender"
|
||||
"github.com/paulmach/orb/geojson"
|
||||
"github.com/rs/zerolog/log"
|
||||
)
|
||||
|
||||
func (r *XLSXRenderer) SolidarityTransportBookings(w http.ResponseWriter, result *application.SolidarityTransportBookingsResult) {
|
||||
// Create Excel spreadsheet
|
||||
spreadsheet := r.NewSpreadsheet("Transport solidaire")
|
||||
|
||||
// Build headers dynamically based on configuration
|
||||
headers := []string{
|
||||
"ID Réservation",
|
||||
"ID Groupe",
|
||||
"Statut",
|
||||
"Motif de réservation",
|
||||
"Raison d'annulation",
|
||||
"Remplacé par (ID)",
|
||||
"Date de prise en charge",
|
||||
"Heure de prise en charge",
|
||||
}
|
||||
|
||||
// Add driver fields from config
|
||||
driverOptionalFields := r.Config.Get("modules.solidarity_transport.profile_optional_fields")
|
||||
driverFields := []string{"last_name", "first_name", "email", "phone_number"}
|
||||
driverHeaders := []string{"Conducteur - Nom", "Conducteur - Prénom", "Conducteur - Email", "Conducteur - Téléphone"}
|
||||
|
||||
if driverOptionalFieldsList, ok := driverOptionalFields.([]interface{}); ok {
|
||||
for _, field := range driverOptionalFieldsList {
|
||||
if fieldMap, ok := field.(map[string]interface{}); ok {
|
||||
if name, ok := fieldMap["name"].(string); ok {
|
||||
driverFields = append(driverFields, name)
|
||||
label := name
|
||||
if labelVal, ok := fieldMap["label"].(string); ok {
|
||||
label = labelVal
|
||||
}
|
||||
driverHeaders = append(driverHeaders, fmt.Sprintf("Conducteur - %s", label))
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
headers = append(headers, driverHeaders...)
|
||||
|
||||
// Add beneficiary fields from config
|
||||
beneficiaryOptionalFields := r.Config.Get("modules.beneficiaries.profile_optional_fields")
|
||||
beneficiaryFields := []string{"last_name", "first_name", "email", "phone_number"}
|
||||
beneficiaryHeaders := []string{"Bénéficiaire - Nom", "Bénéficiaire - Prénom", "Bénéficiaire - Email", "Bénéficiaire - Téléphone"}
|
||||
|
||||
if beneficiaryOptionalFieldsList, ok := beneficiaryOptionalFields.([]interface{}); ok {
|
||||
for _, field := range beneficiaryOptionalFieldsList {
|
||||
if fieldMap, ok := field.(map[string]interface{}); ok {
|
||||
if name, ok := fieldMap["name"].(string); ok {
|
||||
beneficiaryFields = append(beneficiaryFields, name)
|
||||
label := name
|
||||
if labelVal, ok := fieldMap["label"].(string); ok {
|
||||
label = labelVal
|
||||
}
|
||||
beneficiaryHeaders = append(beneficiaryHeaders, fmt.Sprintf("Bénéficiaire - %s", label))
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
headers = append(headers, beneficiaryHeaders...)
|
||||
|
||||
// Add journey information headers
|
||||
headers = append(headers,
|
||||
"Lieu de départ - Adresse",
|
||||
"Lieu de départ - Latitude",
|
||||
"Lieu de départ - Longitude",
|
||||
"Destination - Adresse",
|
||||
"Destination - Latitude",
|
||||
"Destination - Longitude",
|
||||
"Distance passager (km)",
|
||||
"Distance conducteur totale (km)",
|
||||
"Durée trajet (minutes)",
|
||||
"Prix passager",
|
||||
"Devise prix passager",
|
||||
"Compensation conducteur",
|
||||
"Devise compensation",
|
||||
"Temps d'attente retour",
|
||||
"Aller simple",
|
||||
"Départ conducteur - Adresse",
|
||||
"Départ conducteur - Latitude",
|
||||
"Départ conducteur - Longitude",
|
||||
"Arrivée conducteur - Adresse",
|
||||
"Arrivée conducteur - Latitude",
|
||||
"Arrivée conducteur - Longitude",
|
||||
)
|
||||
|
||||
spreadsheet.SetHeaders(headers)
|
||||
|
||||
// Add data rows
|
||||
for _, booking := range result.Bookings {
|
||||
driver := result.DriversMap[booking.DriverId]
|
||||
beneficiary := result.BeneficiariesMap[booking.PassengerId]
|
||||
|
||||
row := []interface{}{}
|
||||
|
||||
// Booking information
|
||||
row = append(row, booking.Id)
|
||||
row = append(row, booking.GroupId)
|
||||
row = append(row, booking.Status)
|
||||
|
||||
// Motivation (from booking.Data)
|
||||
motivation := ""
|
||||
if booking.Data != nil {
|
||||
if motivationVal, ok := booking.Data["motivation"]; ok && motivationVal != nil {
|
||||
motivation = fmt.Sprint(motivationVal)
|
||||
}
|
||||
}
|
||||
row = append(row, motivation)
|
||||
|
||||
// Cancellation reason (from booking.Data)
|
||||
cancellationReason := ""
|
||||
if booking.Data != nil {
|
||||
if reasonVal, ok := booking.Data["reason"]; ok && reasonVal != nil {
|
||||
cancellationReason = fmt.Sprint(reasonVal)
|
||||
}
|
||||
}
|
||||
row = append(row, cancellationReason)
|
||||
|
||||
// Replaced by (from booking.Data)
|
||||
replacedBy := ""
|
||||
if booking.Data != nil {
|
||||
if replacedByVal, ok := booking.Data["replaced_by"]; ok && replacedByVal != nil {
|
||||
replacedBy = fmt.Sprint(replacedByVal)
|
||||
}
|
||||
}
|
||||
row = append(row, replacedBy)
|
||||
|
||||
// Journey date and time
|
||||
if booking.Journey != nil {
|
||||
row = append(row, booking.Journey.PassengerPickupDate.Format("2006-01-02"))
|
||||
row = append(row, booking.Journey.PassengerPickupDate.Format("15:04"))
|
||||
} else {
|
||||
row = append(row, "", "")
|
||||
}
|
||||
|
||||
// Driver data
|
||||
for _, field := range driverFields {
|
||||
row = append(row, getAccountFieldValue(driver.Data, field))
|
||||
}
|
||||
|
||||
// Beneficiary data
|
||||
for _, field := range beneficiaryFields {
|
||||
row = append(row, getAccountFieldValue(beneficiary.Data, field))
|
||||
}
|
||||
|
||||
// Journey locations and details
|
||||
if booking.Journey != nil {
|
||||
// Passenger pickup
|
||||
pickupAddr, pickupLat, pickupLon := getLocationData(booking.Journey.PassengerPickup)
|
||||
row = append(row, pickupAddr, pickupLat, pickupLon)
|
||||
|
||||
// Passenger drop
|
||||
dropAddr, dropLat, dropLon := getLocationData(booking.Journey.PassengerDrop)
|
||||
row = append(row, dropAddr, dropLat, dropLon)
|
||||
|
||||
// Distances and duration
|
||||
row = append(row, booking.Journey.PassengerDistance)
|
||||
row = append(row, booking.Journey.DriverDistance)
|
||||
row = append(row, int64(booking.Journey.Duration.Minutes()))
|
||||
|
||||
// Pricing
|
||||
row = append(row, fmt.Sprintf("%.2f", booking.Journey.Price.Amount))
|
||||
row = append(row, booking.Journey.Price.Currency)
|
||||
|
||||
// Driver compensation
|
||||
if booking.DriverCompensationAmount > 0 {
|
||||
row = append(row, fmt.Sprintf("%.2f", booking.DriverCompensationAmount))
|
||||
row = append(row, booking.DriverCompensationCurrency)
|
||||
} else {
|
||||
row = append(row, "", "")
|
||||
}
|
||||
|
||||
// Return wait time
|
||||
row = append(row, "")
|
||||
|
||||
// One way trip (Noreturn field)
|
||||
if booking.Journey.Noreturn {
|
||||
row = append(row, "Oui")
|
||||
} else {
|
||||
row = append(row, "Non")
|
||||
}
|
||||
|
||||
// Driver departure
|
||||
driverDepartAddr, driverDepartLat, driverDepartLon := getLocationData(booking.Journey.DriverDeparture)
|
||||
row = append(row, driverDepartAddr, driverDepartLat, driverDepartLon)
|
||||
|
||||
// Driver arrival
|
||||
driverArrivalAddr, driverArrivalLat, driverArrivalLon := getLocationData(booking.Journey.DriverArrival)
|
||||
row = append(row, driverArrivalAddr, driverArrivalLat, driverArrivalLon)
|
||||
} else {
|
||||
// No journey data - fill with empty values
|
||||
for i := 0; i < 21; i++ {
|
||||
row = append(row, "")
|
||||
}
|
||||
}
|
||||
|
||||
spreadsheet.AddRow(row)
|
||||
}
|
||||
|
||||
// Write Excel to response
|
||||
w.Header().Set("Content-Type", "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet")
|
||||
w.Header().Set("Content-Disposition", "attachment; filename=\"export-transport-solidaire.xlsx\"")
|
||||
|
||||
if err := spreadsheet.GetFile().Write(w); err != nil {
|
||||
log.Error().Err(err).Msg("Error generating Excel file")
|
||||
http.Error(w, "Error generating Excel file", http.StatusInternalServerError)
|
||||
return
|
||||
}
|
||||
}
|
||||
|
||||
func getAccountFieldValue(data map[string]interface{}, field string) string {
|
||||
// First check direct field
|
||||
if val, ok := data[field]; ok && val != nil {
|
||||
return fmt.Sprint(val)
|
||||
}
|
||||
|
||||
// Check in other_properties
|
||||
if otherProps, ok := data["other_properties"]; ok {
|
||||
if otherPropsMap, ok := otherProps.(map[string]interface{}); ok {
|
||||
if val, ok := otherPropsMap[field]; ok && val != nil {
|
||||
return fmt.Sprint(val)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
return ""
|
||||
}
|
||||
|
||||
func getLocationData(feature *geojson.Feature) (address string, lat interface{}, lon interface{}) {
|
||||
if feature != nil && feature.Properties != nil {
|
||||
if label, ok := feature.Properties["label"].(string); ok {
|
||||
address = label
|
||||
}
|
||||
if feature.Geometry != nil {
|
||||
coords := feature.Geometry.Bound().Center()
|
||||
lat = fmt.Sprintf("%.6f", coords.Lat())
|
||||
lon = fmt.Sprintf("%.6f", coords.Lon())
|
||||
}
|
||||
}
|
||||
return
|
||||
}
|
||||
|
||||
func (r *XLSXRenderer) SolidarityTransportDrivers(w http.ResponseWriter, result *application.SolidarityTransportOverviewResult) {
|
||||
// Create Excel spreadsheet
|
||||
spreadsheet := r.NewSpreadsheet("Conducteurs solidaires")
|
||||
|
||||
// Build headers dynamically based on configuration
|
||||
driverOptionalFields := r.Config.Get("modules.solidarity_transport.drivers.profile_optional_fields")
|
||||
driverFields := []string{"last_name", "first_name", "email", "phone_number", "birthdate", "gender", "file_number"}
|
||||
headers := []string{"ID", "Nom", "Prénom", "Email", "Téléphone", "Date de naissance", "Genre", "Numéro de dossier"}
|
||||
|
||||
if driverOptionalFieldsList, ok := driverOptionalFields.([]interface{}); ok {
|
||||
for _, field := range driverOptionalFieldsList {
|
||||
if fieldMap, ok := field.(map[string]interface{}); ok {
|
||||
if name, ok := fieldMap["name"].(string); ok {
|
||||
driverFields = append(driverFields, name)
|
||||
label := name
|
||||
if labelVal, ok := fieldMap["label"].(string); ok {
|
||||
label = labelVal
|
||||
}
|
||||
headers = append(headers, label)
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// Add address and archived columns
|
||||
headers = append(headers, "Adresse", "Archivé")
|
||||
|
||||
spreadsheet.SetHeaders(headers)
|
||||
|
||||
// Add data rows
|
||||
for _, driver := range result.Accounts {
|
||||
row := []interface{}{}
|
||||
|
||||
// Driver ID
|
||||
row = append(row, driver.ID)
|
||||
|
||||
// Driver data
|
||||
for _, field := range driverFields {
|
||||
value := getAccountFieldValue(driver.Data, field)
|
||||
// Convert gender code to text
|
||||
if field == "gender" && value != "" {
|
||||
value = gender.ISO5218ToString(value)
|
||||
}
|
||||
row = append(row, value)
|
||||
}
|
||||
|
||||
// Address
|
||||
address := ""
|
||||
if addr, ok := driver.Data["address"]; ok {
|
||||
if addrMap, ok := addr.(map[string]interface{}); ok {
|
||||
if props, ok := addrMap["properties"]; ok {
|
||||
if propsMap, ok := props.(map[string]interface{}); ok {
|
||||
if label, ok := propsMap["label"].(string); ok {
|
||||
address = label
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
row = append(row, address)
|
||||
|
||||
// Archived status
|
||||
archived := "Non"
|
||||
if archivedVal, ok := driver.Data["archived"].(bool); ok && archivedVal {
|
||||
archived = "Oui"
|
||||
}
|
||||
row = append(row, archived)
|
||||
|
||||
spreadsheet.AddRow(row)
|
||||
}
|
||||
|
||||
// Write Excel to response
|
||||
w.Header().Set("Content-Type", "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet")
|
||||
w.Header().Set("Content-Disposition", "attachment; filename=\"export-conducteurs-solidaires.xlsx\"")
|
||||
|
||||
if err := spreadsheet.GetFile().Write(w); err != nil {
|
||||
log.Error().Err(err).Msg("Error generating Excel file")
|
||||
http.Error(w, "Error generating Excel file", http.StatusInternalServerError)
|
||||
return
|
||||
}
|
||||
}
|
||||
350
renderer/xlsx/vehicle-bookings.go
Normal file
350
renderer/xlsx/vehicle-bookings.go
Normal file
@@ -0,0 +1,350 @@
|
||||
package xlsx
|
||||
|
||||
import (
|
||||
"fmt"
|
||||
"net/http"
|
||||
|
||||
fleetsstorage "git.coopgo.io/coopgo-platform/fleets/storage"
|
||||
groupsstorage "git.coopgo.io/coopgo-platform/groups-management/storage"
|
||||
mobilityaccountsstorage "git.coopgo.io/coopgo-platform/mobility-accounts/storage"
|
||||
"github.com/rs/zerolog/log"
|
||||
)
|
||||
|
||||
func (r *XLSXRenderer) VehicleBookings(w http.ResponseWriter, bookings []fleetsstorage.Booking, vehiclesMap map[string]fleetsstorage.Vehicle, driversMap map[string]mobilityaccountsstorage.Account) {
|
||||
// Create Excel spreadsheet
|
||||
spreadsheet := r.NewSpreadsheet("Réservations véhicules")
|
||||
|
||||
// Build headers
|
||||
headers := []string{
|
||||
"ID Réservation",
|
||||
"Statut",
|
||||
"Type de véhicule",
|
||||
"Nom du véhicule",
|
||||
"Immatriculation",
|
||||
}
|
||||
|
||||
// Add beneficiary fields from config
|
||||
beneficiaryOptionalFields := r.Config.Get("modules.beneficiaries.profile_optional_fields")
|
||||
beneficiaryFields := []string{"last_name", "first_name", "email", "phone_number"}
|
||||
beneficiaryHeaders := []string{"Bénéficiaire - Nom", "Bénéficiaire - Prénom", "Bénéficiaire - Email", "Bénéficiaire - Téléphone"}
|
||||
|
||||
if beneficiaryOptionalFieldsList, ok := beneficiaryOptionalFields.([]interface{}); ok {
|
||||
for _, field := range beneficiaryOptionalFieldsList {
|
||||
if fieldMap, ok := field.(map[string]interface{}); ok {
|
||||
if name, ok := fieldMap["name"].(string); ok {
|
||||
beneficiaryFields = append(beneficiaryFields, name)
|
||||
label := name
|
||||
if labelVal, ok := fieldMap["label"].(string); ok {
|
||||
label = labelVal
|
||||
}
|
||||
beneficiaryHeaders = append(beneficiaryHeaders, fmt.Sprintf("Bénéficiaire - %s", label))
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
headers = append(headers, beneficiaryHeaders...)
|
||||
|
||||
// Add booking date headers
|
||||
headers = append(headers,
|
||||
"Date de début",
|
||||
"Date de fin",
|
||||
"Durée (jours)",
|
||||
"Commentaire",
|
||||
"Raison d'annulation",
|
||||
)
|
||||
|
||||
spreadsheet.SetHeaders(headers)
|
||||
|
||||
// Add data rows
|
||||
for _, booking := range bookings {
|
||||
vehicle := vehiclesMap[booking.Vehicleid]
|
||||
beneficiary := driversMap[booking.Driver]
|
||||
|
||||
row := []interface{}{}
|
||||
|
||||
// Booking information
|
||||
row = append(row, booking.ID)
|
||||
|
||||
// Status
|
||||
status := ""
|
||||
if booking.Deleted {
|
||||
status = "Annulé"
|
||||
} else {
|
||||
switch booking.Status() {
|
||||
case 1:
|
||||
status = "A venir"
|
||||
case 0:
|
||||
status = "En cours"
|
||||
case -1:
|
||||
status = "Terminé"
|
||||
}
|
||||
}
|
||||
row = append(row, status)
|
||||
|
||||
// Vehicle information
|
||||
row = append(row, vehicle.Type)
|
||||
if vehicleName, ok := vehicle.Data["name"].(string); ok {
|
||||
row = append(row, vehicleName)
|
||||
} else {
|
||||
row = append(row, "")
|
||||
}
|
||||
if licencePlate, ok := vehicle.Data["licence_plate"].(string); ok {
|
||||
row = append(row, licencePlate)
|
||||
} else {
|
||||
row = append(row, "")
|
||||
}
|
||||
|
||||
// Beneficiary data (including other_properties)
|
||||
for _, field := range beneficiaryFields {
|
||||
value := ""
|
||||
// First check direct field
|
||||
if val, ok := beneficiary.Data[field]; ok && val != nil {
|
||||
value = fmt.Sprint(val)
|
||||
} else {
|
||||
// Check in other_properties
|
||||
if otherProps, ok := beneficiary.Data["other_properties"]; ok {
|
||||
if otherPropsMap, ok := otherProps.(map[string]interface{}); ok {
|
||||
if val, ok := otherPropsMap[field]; ok && val != nil {
|
||||
value = fmt.Sprint(val)
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
row = append(row, value)
|
||||
}
|
||||
|
||||
// Booking dates
|
||||
row = append(row, booking.Startdate.Format("2006-01-02"))
|
||||
row = append(row, booking.Enddate.Format("2006-01-02"))
|
||||
|
||||
// Duration in days
|
||||
duration := booking.Enddate.Sub(booking.Startdate).Hours() / 24
|
||||
row = append(row, fmt.Sprintf("%.0f", duration))
|
||||
|
||||
// Comment
|
||||
comment := ""
|
||||
if booking.Data != nil {
|
||||
if commentVal, ok := booking.Data["comment"]; ok && commentVal != nil {
|
||||
comment = fmt.Sprint(commentVal)
|
||||
}
|
||||
}
|
||||
row = append(row, comment)
|
||||
|
||||
// Cancellation reason
|
||||
cancellationReason := ""
|
||||
if booking.Deleted && booking.Data != nil {
|
||||
if reasonVal, ok := booking.Data["reason"]; ok && reasonVal != nil {
|
||||
cancellationReason = fmt.Sprint(reasonVal)
|
||||
}
|
||||
}
|
||||
row = append(row, cancellationReason)
|
||||
|
||||
spreadsheet.AddRow(row)
|
||||
}
|
||||
|
||||
// Write Excel to response
|
||||
w.Header().Set("Content-Type", "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet")
|
||||
w.Header().Set("Content-Disposition", "attachment; filename=\"export-reservations-vehicules.xlsx\"")
|
||||
|
||||
if err := spreadsheet.GetFile().Write(w); err != nil {
|
||||
log.Error().Err(err).Msg("Error generating Excel file")
|
||||
http.Error(w, "Error generating Excel file", http.StatusInternalServerError)
|
||||
return
|
||||
}
|
||||
}
|
||||
|
||||
func (r *XLSXRenderer) VehicleBookingsAdmin(w http.ResponseWriter, bookings []fleetsstorage.Booking, vehiclesMap map[string]interface{}, driversMap map[string]interface{}, groupsMap map[string]any) {
|
||||
// Create Excel spreadsheet
|
||||
spreadsheet := r.NewSpreadsheet("Réservations véhicules")
|
||||
|
||||
// Build headers
|
||||
headers := []string{
|
||||
"ID Réservation",
|
||||
"Statut",
|
||||
"Date de début",
|
||||
"Date de fin",
|
||||
"Durée (jours)",
|
||||
"Commentaire",
|
||||
"Raison d'annulation",
|
||||
"Type de véhicule",
|
||||
"Nom du véhicule",
|
||||
"Immatriculation",
|
||||
"Gestionnaire véhicule",
|
||||
}
|
||||
|
||||
// Add vehicle optional fields from config
|
||||
vehicleOptionalFields := r.Config.Get("modules.fleets.vehicle_optional_fields")
|
||||
vehicleFields := []string{}
|
||||
vehicleHeaders := []string{}
|
||||
|
||||
if vehicleOptionalFieldsList, ok := vehicleOptionalFields.([]interface{}); ok {
|
||||
for _, field := range vehicleOptionalFieldsList {
|
||||
if fieldMap, ok := field.(map[string]interface{}); ok {
|
||||
if name, ok := fieldMap["name"].(string); ok {
|
||||
vehicleFields = append(vehicleFields, name)
|
||||
label := name
|
||||
if labelVal, ok := fieldMap["label"].(string); ok {
|
||||
label = labelVal
|
||||
}
|
||||
vehicleHeaders = append(vehicleHeaders, fmt.Sprintf("Véhicule - %s", label))
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
headers = append(headers, vehicleHeaders...)
|
||||
|
||||
// Add beneficiary fields from config
|
||||
beneficiaryOptionalFields := r.Config.Get("modules.beneficiaries.profile_optional_fields")
|
||||
beneficiaryFields := []string{"last_name", "first_name", "email", "phone_number"}
|
||||
beneficiaryHeaders := []string{"Bénéficiaire - Nom", "Bénéficiaire - Prénom", "Bénéficiaire - Email", "Bénéficiaire - Téléphone"}
|
||||
|
||||
if beneficiaryOptionalFieldsList, ok := beneficiaryOptionalFields.([]interface{}); ok {
|
||||
for _, field := range beneficiaryOptionalFieldsList {
|
||||
if fieldMap, ok := field.(map[string]interface{}); ok {
|
||||
if name, ok := fieldMap["name"].(string); ok {
|
||||
beneficiaryFields = append(beneficiaryFields, name)
|
||||
label := name
|
||||
if labelVal, ok := fieldMap["label"].(string); ok {
|
||||
label = labelVal
|
||||
}
|
||||
beneficiaryHeaders = append(beneficiaryHeaders, fmt.Sprintf("Bénéficiaire - %s", label))
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
headers = append(headers, beneficiaryHeaders...)
|
||||
|
||||
spreadsheet.SetHeaders(headers)
|
||||
|
||||
// Add data rows
|
||||
for _, booking := range bookings {
|
||||
// Get vehicle from map
|
||||
var vehicle fleetsstorage.Vehicle
|
||||
if v, ok := vehiclesMap[booking.Vehicleid]; ok {
|
||||
if vTyped, ok := v.(fleetsstorage.Vehicle); ok {
|
||||
vehicle = vTyped
|
||||
}
|
||||
}
|
||||
|
||||
// Get beneficiary from map
|
||||
var beneficiary mobilityaccountsstorage.Account
|
||||
if d, ok := driversMap[booking.Driver]; ok {
|
||||
if dTyped, ok := d.(mobilityaccountsstorage.Account); ok {
|
||||
beneficiary = dTyped
|
||||
}
|
||||
}
|
||||
|
||||
row := []interface{}{}
|
||||
|
||||
// Booking information
|
||||
row = append(row, booking.ID)
|
||||
|
||||
// Status
|
||||
status := ""
|
||||
if booking.Deleted {
|
||||
status = "Annulé"
|
||||
} else {
|
||||
switch booking.Status() {
|
||||
case 1:
|
||||
status = "A venir"
|
||||
case 0:
|
||||
status = "En cours"
|
||||
case -1:
|
||||
status = "Terminé"
|
||||
}
|
||||
}
|
||||
row = append(row, status)
|
||||
|
||||
// Booking dates
|
||||
row = append(row, booking.Startdate.Format("2006-01-02"))
|
||||
row = append(row, booking.Enddate.Format("2006-01-02"))
|
||||
|
||||
// Duration in days
|
||||
duration := booking.Enddate.Sub(booking.Startdate).Hours() / 24
|
||||
row = append(row, fmt.Sprintf("%.0f", duration))
|
||||
|
||||
// Comment
|
||||
comment := ""
|
||||
if booking.Data != nil {
|
||||
if commentVal, ok := booking.Data["comment"]; ok && commentVal != nil {
|
||||
comment = fmt.Sprint(commentVal)
|
||||
}
|
||||
}
|
||||
row = append(row, comment)
|
||||
|
||||
// Cancellation reason
|
||||
cancellationReason := ""
|
||||
if booking.Deleted && booking.Data != nil {
|
||||
if reasonVal, ok := booking.Data["reason"]; ok && reasonVal != nil {
|
||||
cancellationReason = fmt.Sprint(reasonVal)
|
||||
}
|
||||
}
|
||||
row = append(row, cancellationReason)
|
||||
|
||||
// Vehicle information
|
||||
row = append(row, vehicle.Type)
|
||||
if vehicleName, ok := vehicle.Data["name"].(string); ok {
|
||||
row = append(row, vehicleName)
|
||||
} else {
|
||||
row = append(row, "")
|
||||
}
|
||||
if licencePlate, ok := vehicle.Data["licence_plate"].(string); ok {
|
||||
row = append(row, licencePlate)
|
||||
} else {
|
||||
row = append(row, "")
|
||||
}
|
||||
|
||||
// Vehicle administrator (group name)
|
||||
administratorName := ""
|
||||
if len(vehicle.Administrators) > 0 {
|
||||
if group, ok := groupsMap[vehicle.Administrators[0]]; ok {
|
||||
if groupTyped, ok := group.(groupsstorage.Group); ok {
|
||||
if name, ok := groupTyped.Data["name"]; ok {
|
||||
administratorName = fmt.Sprint(name)
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
row = append(row, administratorName)
|
||||
|
||||
// Vehicle optional fields
|
||||
for _, field := range vehicleFields {
|
||||
value := ""
|
||||
if val, ok := vehicle.Data[field]; ok && val != nil {
|
||||
value = fmt.Sprint(val)
|
||||
}
|
||||
row = append(row, value)
|
||||
}
|
||||
|
||||
// Beneficiary data (including other_properties)
|
||||
for _, field := range beneficiaryFields {
|
||||
value := ""
|
||||
// First check direct field
|
||||
if val, ok := beneficiary.Data[field]; ok && val != nil {
|
||||
value = fmt.Sprint(val)
|
||||
} else {
|
||||
// Check in other_properties
|
||||
if otherProps, ok := beneficiary.Data["other_properties"]; ok {
|
||||
if otherPropsMap, ok := otherProps.(map[string]interface{}); ok {
|
||||
if val, ok := otherPropsMap[field]; ok && val != nil {
|
||||
value = fmt.Sprint(val)
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
row = append(row, value)
|
||||
}
|
||||
|
||||
spreadsheet.AddRow(row)
|
||||
}
|
||||
|
||||
// Write Excel to response
|
||||
w.Header().Set("Content-Type", "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet")
|
||||
w.Header().Set("Content-Disposition", "attachment; filename=\"all_bookings.xlsx\"")
|
||||
|
||||
if err := spreadsheet.GetFile().Write(w); err != nil {
|
||||
log.Error().Err(err).Msg("Error generating Excel file")
|
||||
http.Error(w, "Error generating Excel file", http.StatusInternalServerError)
|
||||
return
|
||||
}
|
||||
}
|
||||
60
renderer/xlsx/xlsx.go
Normal file
60
renderer/xlsx/xlsx.go
Normal file
@@ -0,0 +1,60 @@
|
||||
package xlsx
|
||||
|
||||
import (
|
||||
"github.com/spf13/viper"
|
||||
"github.com/xuri/excelize/v2"
|
||||
)
|
||||
|
||||
// XLSXRenderer handles rendering data to Excel XLSX format
|
||||
type XLSXRenderer struct {
|
||||
Config *viper.Viper
|
||||
}
|
||||
|
||||
func NewXLSXRenderer(config *viper.Viper) *XLSXRenderer {
|
||||
return &XLSXRenderer{
|
||||
Config: config,
|
||||
}
|
||||
}
|
||||
|
||||
// Spreadsheet represents an Excel spreadsheet
|
||||
type Spreadsheet struct {
|
||||
file *excelize.File
|
||||
sheetName string
|
||||
rowIndex int
|
||||
}
|
||||
|
||||
// NewSpreadsheet creates a new Excel spreadsheet
|
||||
func (r *XLSXRenderer) NewSpreadsheet(sheetName string) *Spreadsheet {
|
||||
f := excelize.NewFile()
|
||||
// Rename default sheet
|
||||
f.SetSheetName("Sheet1", sheetName)
|
||||
|
||||
return &Spreadsheet{
|
||||
file: f,
|
||||
sheetName: sheetName,
|
||||
rowIndex: 1,
|
||||
}
|
||||
}
|
||||
|
||||
// SetHeaders sets the header row
|
||||
func (s *Spreadsheet) SetHeaders(headers []string) {
|
||||
for i, header := range headers {
|
||||
cell, _ := excelize.CoordinatesToCellName(i+1, s.rowIndex)
|
||||
s.file.SetCellValue(s.sheetName, cell, header)
|
||||
}
|
||||
s.rowIndex++
|
||||
}
|
||||
|
||||
// AddRow adds a data row
|
||||
func (s *Spreadsheet) AddRow(values []interface{}) {
|
||||
for i, value := range values {
|
||||
cell, _ := excelize.CoordinatesToCellName(i+1, s.rowIndex)
|
||||
s.file.SetCellValue(s.sheetName, cell, value)
|
||||
}
|
||||
s.rowIndex++
|
||||
}
|
||||
|
||||
// GetFile returns the underlying excelize File
|
||||
func (s *Spreadsheet) GetFile() *excelize.File {
|
||||
return s.file
|
||||
}
|
||||
221
servers/mcp/README.md
Normal file
221
servers/mcp/README.md
Normal file
@@ -0,0 +1,221 @@
|
||||
# MCP Server for PARCOURSMOB
|
||||
|
||||
This package implements a Model Context Protocol (MCP) HTTP server for the PARCOURSMOB application, exposing journey search functionality as an MCP tool.
|
||||
|
||||
## Overview
|
||||
|
||||
The MCP server provides a standardized interface for AI assistants to search for multimodal journeys, including:
|
||||
- Public transit routes
|
||||
- Carpooling solutions (via operators like Mobicoop)
|
||||
- Solidarity transport
|
||||
- Organized carpools
|
||||
- Fleet vehicles
|
||||
- Local knowledge base solutions
|
||||
|
||||
## Configuration
|
||||
|
||||
Enable the MCP server in your config file:
|
||||
|
||||
```yaml
|
||||
server:
|
||||
mcp:
|
||||
enabled: true
|
||||
listen: "0.0.0.0:8081"
|
||||
```
|
||||
|
||||
Or via environment variables:
|
||||
```bash
|
||||
export SERVER_MCP_ENABLED=true
|
||||
export SERVER_MCP_LISTEN="0.0.0.0:8081"
|
||||
```
|
||||
|
||||
## API Endpoints
|
||||
|
||||
### Initialize
|
||||
```http
|
||||
POST /mcp/v1/initialize
|
||||
```
|
||||
|
||||
Returns server capabilities and protocol version.
|
||||
|
||||
### List Tools
|
||||
```http
|
||||
GET /mcp/v1/tools/list
|
||||
```
|
||||
|
||||
Returns available MCP tools.
|
||||
|
||||
### Call Tool
|
||||
```http
|
||||
POST /mcp/v1/tools/call
|
||||
Content-Type: application/json
|
||||
|
||||
{
|
||||
"name": "search_journeys",
|
||||
"arguments": {
|
||||
"departure": "123 Main St, Paris, France",
|
||||
"destination": "456 Oak Ave, Lyon, France",
|
||||
"departure_date": "2025-01-20",
|
||||
"departure_time": "14:30"
|
||||
}
|
||||
}
|
||||
```
|
||||
|
||||
### Health Check
|
||||
```http
|
||||
GET /health
|
||||
```
|
||||
|
||||
## Available Tools
|
||||
|
||||
### search_journeys
|
||||
|
||||
Searches for multimodal journey options between two locations.
|
||||
|
||||
**Parameters:**
|
||||
- `departure` (string, required): Departure address as text
|
||||
- `destination` (string, required): Destination address as text
|
||||
- `departure_date` (string, required): Date in YYYY-MM-DD format
|
||||
- `departure_time` (string, required): Time in HH:MM format (24-hour)
|
||||
- `passenger_id` (string, optional): Passenger ID to retrieve address from account
|
||||
- `exclude_driver_ids` (array, optional): List of driver IDs to exclude from solidarity transport results
|
||||
|
||||
**Example Request:**
|
||||
```bash
|
||||
curl -X POST http://localhost:8081/mcp/v1/tools/call \
|
||||
-H "Content-Type: application/json" \
|
||||
-d '{
|
||||
"name": "search_journeys",
|
||||
"arguments": {
|
||||
"departure": "Gare de Lyon, Paris",
|
||||
"destination": "Part-Dieu, Lyon",
|
||||
"departure_date": "2025-01-20",
|
||||
"departure_time": "09:00"
|
||||
}
|
||||
}'
|
||||
```
|
||||
|
||||
**Response Format:**
|
||||
```json
|
||||
{
|
||||
"search_parameters": {
|
||||
"departure": {
|
||||
"label": "Gare de Lyon, Paris, France",
|
||||
"coordinates": { "type": "Point", "coordinates": [2.3736, 48.8443] }
|
||||
},
|
||||
"destination": {
|
||||
"label": "Part-Dieu, Lyon, France",
|
||||
"coordinates": { "type": "Point", "coordinates": [4.8575, 45.7605] }
|
||||
},
|
||||
"departure_date": "2025-01-20",
|
||||
"departure_time": "09:00"
|
||||
},
|
||||
"results": {
|
||||
"CarpoolResults": [...],
|
||||
"TransitResults": [...],
|
||||
"VehicleResults": [...],
|
||||
"DriverJourneys": [...],
|
||||
"OrganizedCarpools": [...],
|
||||
"KnowledgeBaseResults": [...]
|
||||
}
|
||||
}
|
||||
```
|
||||
|
||||
## Architecture
|
||||
|
||||
### Package Structure
|
||||
|
||||
- `mcp.go`: HTTP server and request routing
|
||||
- `tools.go`: Tool registration and execution
|
||||
- `journey_search.go`: Journey search tool implementation
|
||||
|
||||
### Flow
|
||||
|
||||
1. HTTP request received at MCP endpoint
|
||||
2. Tool name and arguments extracted
|
||||
3. Addresses geocoded using Pelias geocoding service
|
||||
4. Journey search executed via ApplicationHandler
|
||||
5. Results formatted and returned as JSON
|
||||
|
||||
### Dependencies
|
||||
|
||||
The MCP server uses:
|
||||
- Pelias geocoding service (configured via `geo.pelias.url`)
|
||||
- ApplicationHandler for journey search business logic
|
||||
- All backend services (GRPC): solidarity transport, carpool service, transit routing, fleets, etc.
|
||||
|
||||
## Integration with AI Assistants
|
||||
|
||||
The MCP server follows the Model Context Protocol specification, making it compatible with AI assistants that support MCP, such as Claude Desktop or other MCP-enabled tools.
|
||||
|
||||
Example Claude Desktop configuration:
|
||||
```json
|
||||
{
|
||||
"mcpServers": {
|
||||
"parcoursmob": {
|
||||
"url": "http://localhost:8081/mcp/v1"
|
||||
}
|
||||
}
|
||||
}
|
||||
```
|
||||
|
||||
## Development
|
||||
|
||||
### Testing
|
||||
|
||||
Test the health endpoint:
|
||||
```bash
|
||||
curl http://localhost:8081/health
|
||||
```
|
||||
|
||||
List available tools:
|
||||
```bash
|
||||
curl http://localhost:8081/mcp/v1/tools/list
|
||||
```
|
||||
|
||||
Test journey search:
|
||||
```bash
|
||||
curl -X POST http://localhost:8081/mcp/v1/tools/call \
|
||||
-H "Content-Type: application/json" \
|
||||
-d '{
|
||||
"name": "search_journeys",
|
||||
"arguments": {
|
||||
"departure": "Paris",
|
||||
"destination": "Lyon",
|
||||
"departure_date": "2025-01-20",
|
||||
"departure_time": "10:00"
|
||||
}
|
||||
}'
|
||||
```
|
||||
|
||||
### Adding New Tools
|
||||
|
||||
To add a new MCP tool:
|
||||
|
||||
1. Define the tool in `tools.go`:
|
||||
```go
|
||||
func (h *ToolsHandler) registerNewTool() {
|
||||
tool := &Tool{
|
||||
Name: "tool_name",
|
||||
Description: "Tool description",
|
||||
InputSchema: map[string]any{...},
|
||||
}
|
||||
h.tools["tool_name"] = tool
|
||||
}
|
||||
```
|
||||
|
||||
2. Implement the handler:
|
||||
```go
|
||||
func (h *ToolsHandler) handleNewTool(ctx context.Context, arguments map[string]any) (any, error) {
|
||||
// Implementation
|
||||
}
|
||||
```
|
||||
|
||||
3. Add to CallTool switch statement in `tools.go`
|
||||
|
||||
## Notes
|
||||
|
||||
- All times are handled in Europe/Paris timezone
|
||||
- Geocoding uses the first result from Pelias
|
||||
- Journey search runs multiple transport mode queries in parallel
|
||||
- Results include all available transport options for the requested route
|
||||
158
servers/mcp/journey_tool.go
Normal file
158
servers/mcp/journey_tool.go
Normal file
@@ -0,0 +1,158 @@
|
||||
package mcp
|
||||
|
||||
import (
|
||||
"context"
|
||||
"fmt"
|
||||
"time"
|
||||
|
||||
"git.coopgo.io/coopgo-apps/parcoursmob/core/application"
|
||||
mcpsdk "github.com/modelcontextprotocol/go-sdk/mcp"
|
||||
"github.com/paulmach/orb/geojson"
|
||||
"github.com/rs/zerolog/log"
|
||||
)
|
||||
|
||||
// JourneySearchInput represents the input for journey search
|
||||
type JourneySearchInput struct {
|
||||
Departure string `json:"departure" jsonschema:"Departure address as text (e.g. Paris or Gare de Lyon Paris)"`
|
||||
Destination string `json:"destination" jsonschema:"Destination address as text (e.g. Lyon or Part-Dieu Lyon)"`
|
||||
DepartureDate string `json:"departure_date" jsonschema:"Departure date in YYYY-MM-DD format"`
|
||||
DepartureTime string `json:"departure_time" jsonschema:"Departure time in HH:MM format (24-hour)"`
|
||||
PassengerID string `json:"passenger_id,omitempty" jsonschema:"Optional passenger ID to retrieve address from account"`
|
||||
ExcludeDriverIDs []string `json:"exclude_driver_ids,omitempty" jsonschema:"Optional list of driver IDs to exclude from solidarity transport results"`
|
||||
}
|
||||
|
||||
// JourneySearchOutput represents the output of journey search
|
||||
type JourneySearchOutput struct {
|
||||
SearchParameters map[string]any `json:"search_parameters"`
|
||||
Results any `json:"results"`
|
||||
}
|
||||
|
||||
// registerJourneySearchTool registers the journey search tool with the MCP server
|
||||
func (s *MCPServer) registerJourneySearchTool() {
|
||||
mcpsdk.AddTool(
|
||||
s.mcpServer,
|
||||
&mcpsdk.Tool{
|
||||
Name: "search_journeys",
|
||||
Description: "Search for multimodal journeys including transit, carpooling, solidarity transport, organized carpool, and local solutions. Accepts departure and destination as text addresses that will be geocoded automatically.",
|
||||
},
|
||||
s.handleJourneySearch,
|
||||
)
|
||||
}
|
||||
|
||||
// handleJourneySearch handles the journey search tool execution
|
||||
func (s *MCPServer) handleJourneySearch(ctx context.Context, req *mcpsdk.CallToolRequest, input JourneySearchInput) (*mcpsdk.CallToolResult, *JourneySearchOutput, error) {
|
||||
// Geocode departure address using French government API
|
||||
log.Info().Str("address", input.Departure).Msg("Geocoding departure address")
|
||||
departureFeature, err := s.geocodeAddress(input.Departure)
|
||||
if err != nil {
|
||||
log.Error().Err(err).Msg("failed to geocode departure address")
|
||||
return nil, nil, fmt.Errorf("failed to geocode departure address: %w", err)
|
||||
}
|
||||
|
||||
// Geocode destination address using French government API
|
||||
log.Info().Str("address", input.Destination).Msg("Geocoding destination address")
|
||||
destinationFeature, err := s.geocodeAddress(input.Destination)
|
||||
if err != nil {
|
||||
log.Error().Err(err).Msg("failed to geocode destination address")
|
||||
return nil, nil, fmt.Errorf("failed to geocode destination address: %w", err)
|
||||
}
|
||||
|
||||
// Parse date and time
|
||||
parisLoc, err := time.LoadLocation("Europe/Paris")
|
||||
if err != nil {
|
||||
return nil, nil, fmt.Errorf("failed to load Paris timezone: %w", err)
|
||||
}
|
||||
|
||||
departureDateTime, err := time.ParseInLocation("2006-01-02 15:04", fmt.Sprintf("%s %s", input.DepartureDate, input.DepartureTime), parisLoc)
|
||||
if err != nil {
|
||||
log.Error().Err(err).Msg("failed to parse date/time")
|
||||
return nil, nil, fmt.Errorf("failed to parse departure date/time: %w", err)
|
||||
}
|
||||
|
||||
// Convert to UTC for the search
|
||||
departureDateTime = departureDateTime.UTC()
|
||||
|
||||
log.Info().
|
||||
Str("departure", input.Departure).
|
||||
Str("destination", input.Destination).
|
||||
Time("departure_datetime", departureDateTime).
|
||||
Msg("Executing journey search")
|
||||
|
||||
// Prepare exclude driver ID (only first one if provided)
|
||||
excludeDriverID := ""
|
||||
if len(input.ExcludeDriverIDs) > 0 {
|
||||
excludeDriverID = input.ExcludeDriverIDs[0]
|
||||
}
|
||||
|
||||
// Prepare search options - disable transit for MCP requests
|
||||
searchOptions := &application.SearchJourneyOptions{
|
||||
DisableTransit: true,
|
||||
}
|
||||
|
||||
// Call the journey search from application handler
|
||||
searchResult, err := s.applicationHandler.SearchJourneys(
|
||||
ctx,
|
||||
departureDateTime,
|
||||
departureFeature,
|
||||
destinationFeature,
|
||||
input.PassengerID,
|
||||
excludeDriverID,
|
||||
"", // solidarityExcludeGroupId - not used in MCP context
|
||||
searchOptions,
|
||||
)
|
||||
if err != nil {
|
||||
return nil, nil, fmt.Errorf("journey search failed: %w", err)
|
||||
}
|
||||
|
||||
// Format the results for MCP response
|
||||
response := &JourneySearchOutput{
|
||||
SearchParameters: map[string]any{
|
||||
"departure": map[string]any{
|
||||
"label": getFeatureLabel(departureFeature),
|
||||
"coordinates": departureFeature.Geometry,
|
||||
},
|
||||
"destination": map[string]any{
|
||||
"label": getFeatureLabel(destinationFeature),
|
||||
"coordinates": destinationFeature.Geometry,
|
||||
},
|
||||
"departure_date": input.DepartureDate,
|
||||
"departure_time": input.DepartureTime,
|
||||
},
|
||||
Results: searchResult,
|
||||
}
|
||||
|
||||
return &mcpsdk.CallToolResult{}, response, nil
|
||||
}
|
||||
|
||||
// geocodeAddress uses the geo service helper to geocode an address
|
||||
func (s *MCPServer) geocodeAddress(address string) (*geojson.Feature, error) {
|
||||
// Use the geo service to get autocomplete results
|
||||
featureCollection, err := s.geoService.Autocomplete(address)
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("geocoding request failed: %w", err)
|
||||
}
|
||||
|
||||
if len(featureCollection.Features) == 0 {
|
||||
return nil, fmt.Errorf("no results found for address: %s", address)
|
||||
}
|
||||
|
||||
// Return the first feature directly
|
||||
return featureCollection.Features[0], nil
|
||||
}
|
||||
|
||||
// getFeatureLabel extracts a human-readable label from a GeoJSON Feature
|
||||
func getFeatureLabel(feature *geojson.Feature) string {
|
||||
if feature.Properties == nil {
|
||||
return ""
|
||||
}
|
||||
|
||||
// Try common label fields
|
||||
if label, ok := feature.Properties["label"].(string); ok {
|
||||
return label
|
||||
}
|
||||
if name, ok := feature.Properties["name"].(string); ok {
|
||||
return name
|
||||
}
|
||||
|
||||
return ""
|
||||
}
|
||||
109
servers/mcp/mcp.go
Normal file
109
servers/mcp/mcp.go
Normal file
@@ -0,0 +1,109 @@
|
||||
package mcp
|
||||
|
||||
import (
|
||||
"net/http"
|
||||
"time"
|
||||
|
||||
mcpsdk "github.com/modelcontextprotocol/go-sdk/mcp"
|
||||
"github.com/rs/zerolog/log"
|
||||
"github.com/spf13/viper"
|
||||
|
||||
"git.coopgo.io/coopgo-apps/parcoursmob/core/application"
|
||||
"git.coopgo.io/coopgo-apps/parcoursmob/core/utils/geo"
|
||||
cache "git.coopgo.io/coopgo-apps/parcoursmob/core/utils/storage"
|
||||
"git.coopgo.io/coopgo-apps/parcoursmob/services"
|
||||
)
|
||||
|
||||
// MCPServer represents the MCP HTTP server
|
||||
type MCPServer struct {
|
||||
cfg *viper.Viper
|
||||
services *services.ServicesHandler
|
||||
kv cache.KVHandler
|
||||
filestorage cache.FileStorage
|
||||
applicationHandler *application.ApplicationHandler
|
||||
mcpServer *mcpsdk.Server
|
||||
geoService *geo.GeoService
|
||||
}
|
||||
|
||||
// NewMCPServer creates a new MCP server instance
|
||||
func NewMCPServer(
|
||||
cfg *viper.Viper,
|
||||
svc *services.ServicesHandler,
|
||||
applicationHandler *application.ApplicationHandler,
|
||||
kv cache.KVHandler,
|
||||
filestorage cache.FileStorage,
|
||||
) *MCPServer {
|
||||
// Initialize geocoding service
|
||||
geoType := cfg.GetString("geo.type")
|
||||
baseURL := cfg.GetString("geo." + geoType + ".url")
|
||||
autocompleteEndpoint := cfg.GetString("geo." + geoType + ".autocomplete")
|
||||
geoService := geo.NewGeoService(geoType, baseURL, autocompleteEndpoint)
|
||||
|
||||
server := &MCPServer{
|
||||
cfg: cfg,
|
||||
services: svc,
|
||||
kv: kv,
|
||||
filestorage: filestorage,
|
||||
applicationHandler: applicationHandler,
|
||||
geoService: geoService,
|
||||
}
|
||||
|
||||
// Create MCP server with implementation info
|
||||
server.mcpServer = mcpsdk.NewServer(&mcpsdk.Implementation{
|
||||
Name: "parcoursmob-mcp-server",
|
||||
Version: "1.0.0",
|
||||
}, nil)
|
||||
|
||||
// Register journey search tool
|
||||
server.registerJourneySearchTool()
|
||||
|
||||
return server
|
||||
}
|
||||
|
||||
// Run starts the MCP HTTP server with SSE transport
|
||||
func Run(
|
||||
cfg *viper.Viper,
|
||||
svc *services.ServicesHandler,
|
||||
applicationHandler *application.ApplicationHandler,
|
||||
kv cache.KVHandler,
|
||||
filestorage cache.FileStorage,
|
||||
) {
|
||||
address := cfg.GetString("server.mcp.listen")
|
||||
service_name := cfg.GetString("service_name")
|
||||
|
||||
mcpServer := NewMCPServer(cfg, svc, applicationHandler, kv, filestorage)
|
||||
|
||||
// Create HTTP server with SSE transport
|
||||
mux := http.NewServeMux()
|
||||
|
||||
// Health check endpoint
|
||||
mux.HandleFunc("/health", func(w http.ResponseWriter, r *http.Request) {
|
||||
w.Header().Set("Content-Type", "application/json")
|
||||
w.WriteHeader(http.StatusOK)
|
||||
w.Write([]byte(`{"status":"healthy"}`))
|
||||
})
|
||||
|
||||
// MCP Streamable HTTP endpoint (preferred over SSE as of 2025-03-26 spec)
|
||||
streamHandler := mcpsdk.NewStreamableHTTPHandler(func(r *http.Request) *mcpsdk.Server {
|
||||
return mcpServer.mcpServer
|
||||
}, nil)
|
||||
mux.Handle("/", streamHandler)
|
||||
|
||||
// Also support legacy SSE endpoint for backwards compatibility
|
||||
sseHandler := mcpsdk.NewSSEHandler(func(r *http.Request) *mcpsdk.Server {
|
||||
return mcpServer.mcpServer
|
||||
}, nil)
|
||||
mux.Handle("/sse", sseHandler)
|
||||
|
||||
srv := &http.Server{
|
||||
Handler: mux,
|
||||
Addr: address,
|
||||
WriteTimeout: 60 * time.Second,
|
||||
ReadTimeout: 30 * time.Second,
|
||||
}
|
||||
|
||||
log.Info().Str("service_name", service_name).Str("address", address).Msg("Running MCP HTTP server with SSE transport")
|
||||
|
||||
err := srv.ListenAndServe()
|
||||
log.Error().Err(err).Msg("MCP server error")
|
||||
}
|
||||
38
servers/web/api/auth.go
Normal file
38
servers/web/api/auth.go
Normal file
@@ -0,0 +1,38 @@
|
||||
package api
|
||||
|
||||
import (
|
||||
"net/http"
|
||||
|
||||
"github.com/rs/zerolog/log"
|
||||
)
|
||||
|
||||
func (h *Handler) OAuth2Callback(w http.ResponseWriter, r *http.Request) {
|
||||
code := r.URL.Query().Get("code")
|
||||
if code == "" {
|
||||
w.WriteHeader(http.StatusBadRequest)
|
||||
return
|
||||
}
|
||||
|
||||
session, _ := h.idp.SessionsStore.Get(r, "parcoursmob_session")
|
||||
redirectSession := ""
|
||||
if session.Values["redirect"] != nil && session.Values["redirect"] != "" {
|
||||
redirectSession = session.Values["redirect"].(string)
|
||||
delete(session.Values, "redirect")
|
||||
}
|
||||
|
||||
result, err := h.applicationHandler.ProcessOAuth2Callback(code, redirectSession)
|
||||
if err != nil {
|
||||
w.WriteHeader(http.StatusInternalServerError)
|
||||
return
|
||||
}
|
||||
|
||||
session.Values["idtoken"] = result.IDToken
|
||||
|
||||
if err = session.Save(r, w); err != nil {
|
||||
log.Error().Err(err).Msg("Cannot save session")
|
||||
w.WriteHeader(http.StatusInternalServerError)
|
||||
return
|
||||
}
|
||||
|
||||
http.Redirect(w, r, result.RedirectURL, http.StatusFound)
|
||||
}
|
||||
48
servers/web/api/cache.go
Normal file
48
servers/web/api/cache.go
Normal file
@@ -0,0 +1,48 @@
|
||||
package api
|
||||
|
||||
import (
|
||||
"net/http"
|
||||
|
||||
"git.coopgo.io/coopgo-apps/parcoursmob/core/utils/cache"
|
||||
"github.com/gorilla/mux"
|
||||
"github.com/rs/zerolog/log"
|
||||
)
|
||||
|
||||
func (h *Handler) GetCache(w http.ResponseWriter, r *http.Request) {
|
||||
vars := mux.Vars(r)
|
||||
cacheID := vars["cacheid"]
|
||||
|
||||
// Parse query parameters
|
||||
limitsMinStr := r.URL.Query().Get("limits.min")
|
||||
limitsMaxStr := r.URL.Query().Get("limits.max")
|
||||
limitsMin, limitsMax := cache.ParseLimits(limitsMinStr, limitsMaxStr)
|
||||
|
||||
// Use a channel to synchronize the goroutines
|
||||
ch := make(chan []byte)
|
||||
|
||||
// Fetch data from cache asynchronously
|
||||
go func() {
|
||||
result, err := h.cacheService.GetCacheData(cacheID, limitsMin, limitsMax)
|
||||
if err != nil {
|
||||
log.Error().Err(err).Msg("Failed to get cache data")
|
||||
w.WriteHeader(http.StatusNotFound)
|
||||
ch <- nil
|
||||
return
|
||||
}
|
||||
ch <- result.Data // Signal that the data has been fetched successfully
|
||||
close(ch)
|
||||
}()
|
||||
|
||||
// Wait for the JSON marshaling goroutine to finish
|
||||
data := <-ch
|
||||
if data == nil {
|
||||
return // Stop processing if an error occurred
|
||||
}
|
||||
|
||||
// Send the JSON response to the client
|
||||
w.Header().Set("Content-Type", "application/json")
|
||||
w.WriteHeader(http.StatusOK)
|
||||
w.Write(data)
|
||||
|
||||
<-ch
|
||||
}
|
||||
Some files were not shown because too many files have changed in this diff Show More
Reference in New Issue
Block a user