6 Commits

Author SHA1 Message Date
81e81f8763 replace 2023-08-08 12:07:50 +02:00
5f64b6c71a replace requirements by latest en dev branch 2023-08-08 11:53:09 +02:00
51dcaf01c8 edit dockerfile 2023-08-07 10:56:16 +02:00
bd91ce1572 test 2023-07-26 15:01:25 +02:00
edb03ae3b4 test 2023-07-26 14:57:45 +02:00
5ea89bf0b2 edit dockerfile 2023-07-26 14:55:08 +02:00
181 changed files with 6967 additions and 18314 deletions

View File

@@ -1,81 +0,0 @@
name: Build and Push Docker Image
on:
push:
tags:
- '*'
branches:
- main
- dev
jobs:
build_and_push:
runs-on: ubuntu-latest
steps:
- name: Install Docker
run: |
apt-get update
apt-get install -y docker.io
- name: Checkout Repository
uses: actions/checkout@v4
- name: Set Kubernetes Context
uses: azure/k8s-set-context@v4
with:
method: kubeconfig
kubeconfig: ${{secrets.buildx_kubeconfig}}
- name: Set up Docker Buildx
uses: docker/setup-buildx-action@v3
with:
driver: kubernetes
driver-opts: |
namespace=gitea
- name: Login to Docker Registry
uses: docker/login-action@v3
with:
registry: git.coopgo.io
username: ${{ secrets.REGISTRY_USER }}
password: ${{ secrets.REGISTRY_TOKEN }}
- name: Extract metadata (tags, labels) for Docker image
id: metadata
uses: docker/metadata-action@v3
with:
images: git.coopgo.io/${{gitea.repository}}
tags: |
type=ref,event=branch
type=ref,event=tag
type=ref,event=pr
flavor: |
latest=auto
- name: Build and push
uses: docker/build-push-action@v5
with:
context: .
push: true
tags: |
${{ steps.metadata.outputs.tags }}
build-args: |
ACCESS_TOKEN_USR=${{gitea.actor}}
ACCESS_TOKEN_PWD=${{gitea.token}}
# BUILD WITH KANIKO
# - name: Kaniko build and push
# uses: aevea/action-kaniko@master
# with:
# build_file: Dockerfile
# registry: git.coopgo.io
# username: ${{secrets.registry_user}}
# password: ${{secrets.registry_token}}
# image: ${{gitea.repository}}
# tag: ${{gitea.ref_name}}
# cache: true
# cache_registry: git.coopgo.io/${{gitea.repository}}/cache
# extra-args: |
# ACCESS_TOKEN_USR=${{gitea.actor}}
# ACCESS_TOKEN_PWD=${{gitea.token}}

2
.gitignore vendored
View File

@@ -2,5 +2,3 @@
themes/* themes/*
.vscode .vscode
__debug_bin __debug_bin
parcoursmob
.idea

8
.idea/.gitignore generated vendored
View File

@@ -1,8 +0,0 @@
# Default ignored files
/shelf/
/workspace.xml
# Editor-based HTTP Client requests
/httpRequests/
# Datasource local storage ignored files
/dataSources/
/dataSources.local.xml

8
.idea/modules.xml generated
View File

@@ -1,8 +0,0 @@
<?xml version="1.0" encoding="UTF-8"?>
<project version="4">
<component name="ProjectModuleManager">
<modules>
<module fileurl="file://$PROJECT_DIR$/.idea/parcoursmob.iml" filepath="$PROJECT_DIR$/.idea/parcoursmob.iml" />
</modules>
</component>
</project>

9
.idea/parcoursmob.iml generated
View File

@@ -1,9 +0,0 @@
<?xml version="1.0" encoding="UTF-8"?>
<module type="WEB_MODULE" version="4">
<component name="Go" enabled="true" />
<component name="NewModuleRootManager">
<content url="file://$MODULE_DIR$" />
<orderEntry type="inheritedJdk" />
<orderEntry type="sourceFolder" forTests="false" />
</component>
</module>

7
.idea/vcs.xml generated
View File

@@ -1,7 +0,0 @@
<?xml version="1.0" encoding="UTF-8"?>
<project version="4">
<component name="VcsDirectoryMappings">
<mapping directory="" vcs="Git" />
<mapping directory="$PROJECT_DIR$/themes" vcs="Git" />
</component>
</project>

5
Dockerfile Executable file → Normal file
View File

@@ -19,12 +19,9 @@ COPY . .
RUN go mod download && CGO_ENABLED=0 GOOS=linux GOARCH=amd64 go build -o /server 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 --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 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 FROM scratch
COPY --from=builder /etc/ssl/certs/ca-certificates.crt /etc/ssl/certs/ COPY --from=builder /etc/ssl/certs/ca-certificates.crt /etc/ssl/certs/

View File

@@ -1,660 +0,0 @@
# 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/>.

2
README.md Executable file → Normal file
View File

@@ -10,3 +10,5 @@ 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 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 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 - A distributed cache system through [etcd](https://etcd.io/) to handle distributed state management like pagination in a cloud native way

259
config.go Executable file → Normal file
View File

@@ -14,15 +14,7 @@ func ReadConfig() (*viper.Viper, error) {
"public_dir": "template/default/public", "public_dir": "template/default/public",
}, },
"server": map[string]any{ "server": map[string]any{
"listen": "0.0.0.0:9000", // DEPRECATED "listen": "0.0.0.0:9000",
"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{ "identification": map[string]any{
"sessions": map[string]any{ "sessions": map[string]any{
@@ -30,258 +22,9 @@ func ReadConfig() (*viper.Viper, error) {
"session_key": "SESSION_KEY", "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{ "geo": map[string]any{
"type": "addok", // Options: "pelias", "addok"
"pelias": map[string]any{ "pelias": map[string]any{
"url": "https://geocode.ridygo.fr", "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{},
}, },
}, },
} }

View File

@@ -1,658 +0,0 @@
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
}

View File

@@ -1,602 +0,0 @@
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
}

View File

@@ -1,240 +0,0 @@
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
}

View File

@@ -1,929 +0,0 @@
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
}

View File

@@ -1,228 +0,0 @@
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
}

View File

@@ -1,3 +0,0 @@
package application
// Directory module - no business logic needed, all functionality moved to WebServer handlers

View File

@@ -1,171 +0,0 @@
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
}

View File

@@ -1,429 +0,0 @@
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
}

View File

@@ -1,133 +0,0 @@
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
}

View File

@@ -1,219 +0,0 @@
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
}

View File

@@ -1,458 +0,0 @@
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
}

View File

@@ -1,247 +0,0 @@
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
}

File diff suppressed because it is too large Load Diff

View File

@@ -1,41 +0,0 @@
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
}

File diff suppressed because it is too large Load Diff

View File

@@ -1,33 +0,0 @@
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
}

View File

@@ -1,600 +0,0 @@
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
}

View File

@@ -1,393 +0,0 @@
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
}

View File

@@ -1,146 +0,0 @@
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
}

View File

@@ -1,74 +0,0 @@
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
}

View File

@@ -1,17 +0,0 @@
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
}
}

View File

@@ -1,45 +0,0 @@
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
}

View File

@@ -1,73 +0,0 @@
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)
}
}

View File

@@ -1,32 +0,0 @@
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] }

View File

@@ -1 +0,0 @@
package storage

View File

@@ -1,102 +0,0 @@
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
}
}

217
go.mod Executable file → Normal file
View File

@@ -1,6 +1,6 @@
module git.coopgo.io/coopgo-apps/parcoursmob module git.coopgo.io/coopgo-apps/parcoursmob
go 1.24.6 go 1.18
// replace git.coopgo.io/coopgo-platform/mobility-accounts => ../../coopgo-platform/mobility-accounts/ // replace git.coopgo.io/coopgo-platform/mobility-accounts => ../../coopgo-platform/mobility-accounts/
@@ -12,169 +12,114 @@ go 1.24.6
// replace git.coopgo.io/coopgo-platform/emailing => ../../coopgo-platform/emailing/ // 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 ( require (
github.com/coreos/go-oidc v2.2.1+incompatible
github.com/fogleman/gg v1.3.0 github.com/fogleman/gg v1.3.0
github.com/go-playground/validator/v10 v10.14.1 github.com/go-playground/validator/v10 v10.11.0
github.com/google/uuid v1.6.0 github.com/google/uuid v1.3.0
github.com/gorilla/mux v1.8.0 github.com/gorilla/mux v1.8.0
github.com/gorilla/sessions v1.2.1 github.com/gorilla/sessions v1.2.1
github.com/paulmach/go.geojson v1.4.0 // indirect github.com/paulmach/go.geojson v1.4.0
github.com/spf13/viper v1.21.0 github.com/spf13/viper v1.13.0
gitlab.scity.coop/maas/navitia-golang v0.0.0-20220429110621-5c22d6efdd0c gitlab.scity.coop/maas/navitia-golang v0.0.0-20220429110621-5c22d6efdd0c
go.etcd.io/etcd/client/v3 v3.5.12 go.etcd.io/etcd/client/v3 v3.5.4
golang.org/x/image v0.25.0 golang.org/x/image v0.5.0
golang.org/x/oauth2 v0.30.0 golang.org/x/oauth2 v0.0.0-20220411215720-9780585627b5
google.golang.org/grpc v1.76.0 google.golang.org/grpc v1.48.0
google.golang.org/protobuf v1.36.10 google.golang.org/protobuf v1.28.1
) )
require ( require (
git.coopgo.io/coopgo-platform/agenda v1.0.0 git.coopgo.io/coopgo-platform/agenda v0.0.0-20230222135722-e55cf41e203b
git.coopgo.io/coopgo-platform/carpool-service v0.0.0-20251008165122-38cb3c5ad9b4 git.coopgo.io/coopgo-platform/emailing v0.0.0-20221017030337-c71888d90c15
git.coopgo.io/coopgo-platform/emailing v0.0.0-20250212064257-167ef5864260 git.coopgo.io/coopgo-platform/fleets v0.0.0-20230519092636-41bf03682ca9
git.coopgo.io/coopgo-platform/fleets v1.1.0 git.coopgo.io/coopgo-platform/groups-management v0.0.0-20230117140716-312200e21063
git.coopgo.io/coopgo-platform/geography v0.0.0-20251010131258-ec939649e858 git.coopgo.io/coopgo-platform/mobility-accounts v0.0.0-20221107003506-e2ff98094b81
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/gorilla/securecookie v1.1.1
github.com/minio/minio-go/v7 v7.0.43 github.com/minio/minio-go/v7 v7.0.43
github.com/modelcontextprotocol/go-sdk v1.0.0 github.com/ory/viper v1.7.5
github.com/paulmach/orb v0.12.0 github.com/xuri/excelize/v2 v2.7.1
github.com/rs/zerolog v1.34.0
github.com/stretchr/objx v0.5.3
github.com/xuri/excelize/v2 v2.9.1
) )
require ( require (
git.coopgo.io/coopgo-platform/carpool-service/interoperability/ocss v0.0.0-20251008142525-4392f227836a // indirect github.com/asaskevich/govalidator v0.0.0-20200428143746-21a406dcc535 // indirect
github.com/RoaringBitmap/roaring/v2 v2.4.5 // indirect github.com/cespare/xxhash v1.1.0 // 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.37.0 // indirect
github.com/agext/levenshtein v1.2.3 // indirect
github.com/coreos/go-semver v0.3.0 // indirect github.com/coreos/go-semver v0.3.0 // indirect
github.com/coreos/go-systemd/v22 v22.5.0 // indirect github.com/coreos/go-systemd/v22 v22.3.2 // indirect
github.com/dgraph-io/ristretto v0.0.3 // indirect
github.com/dustin/go-humanize v1.0.0 // indirect github.com/dustin/go-humanize v1.0.0 // indirect
github.com/fsnotify/fsnotify v1.9.0 // indirect github.com/fsnotify/fsnotify v1.5.4 // indirect
github.com/go-jose/go-jose/v4 v4.1.2 // indirect github.com/go-playground/locales v0.14.0 // indirect
github.com/go-openapi/inflect v0.21.3 // indirect github.com/go-playground/universal-translator v0.18.0 // 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/gogo/protobuf v1.3.2 // indirect
github.com/golang/freetype v0.0.0-20170609003504-e2365dfdc4a0 // indirect github.com/golang/freetype v0.0.0-20170609003504-e2365dfdc4a0 // indirect
github.com/golang/protobuf v1.5.4 // indirect github.com/golang/protobuf v1.5.2 // indirect
github.com/golang/snappy v1.0.0 // indirect github.com/golang/snappy v0.0.1 // indirect
github.com/google/go-cmp v0.7.0 // indirect github.com/gorilla/csrf v1.7.1 // indirect
github.com/google/jsonschema-go v0.3.0 // indirect github.com/gorilla/websocket v1.4.2 // indirect
github.com/hashicorp/hcl/v2 v2.24.0 // indirect github.com/hashicorp/hcl v1.0.0 // indirect
github.com/inconshreveable/mousetrap v1.0.0 // indirect
github.com/json-iterator/go v1.1.12 // indirect github.com/json-iterator/go v1.1.12 // indirect
github.com/klauspost/compress v1.18.0 // indirect github.com/klauspost/compress v1.15.9 // indirect
github.com/klauspost/cpuid/v2 v2.2.5 // indirect github.com/klauspost/cpuid/v2 v2.1.0 // indirect
github.com/leodido/go-urn v1.2.4 // indirect github.com/leodido/go-urn v1.2.1 // indirect
github.com/lib/pq v1.10.9 // indirect github.com/magiconair/properties v1.8.6 // indirect
github.com/mattn/go-colorable v0.1.14 // indirect github.com/mattn/goveralls v0.0.6 // indirect
github.com/mattn/go-isatty v0.0.20 // indirect
github.com/mb0/wkt v0.0.0-20170420051526-a30afd545ee1 // indirect github.com/mb0/wkt v0.0.0-20170420051526-a30afd545ee1 // indirect
github.com/minio/md5-simd v1.1.2 // indirect github.com/minio/md5-simd v1.1.2 // indirect
github.com/minio/sha256-simd v1.0.0 // indirect github.com/minio/sha256-simd v1.0.0 // indirect
github.com/mitchellh/go-wordwrap v1.0.1 // indirect github.com/mitchellh/mapstructure v1.5.0 // indirect
github.com/modern-go/concurrent v0.0.0-20180306012644-bacd9c7ef1dd // indirect github.com/modern-go/concurrent v0.0.0-20180306012644-bacd9c7ef1dd // indirect
github.com/modern-go/reflect2 v1.0.2 // indirect github.com/modern-go/reflect2 v1.0.2 // indirect
github.com/montanaflynn/stats v0.7.1 // indirect github.com/mohae/deepcopy v0.0.0-20170929034955-c48cc78d4826 // indirect
github.com/pelletier/go-toml/v2 v2.2.4 // indirect github.com/montanaflynn/stats v0.0.0-20171201202039-1bf9dbcd8cbe // indirect
github.com/ory/fosite v0.42.2 // indirect
github.com/ory/go-acc v0.2.6 // indirect
github.com/ory/go-convenience v0.1.0 // indirect
github.com/ory/x v0.0.214 // indirect
github.com/pborman/uuid v1.2.0 // indirect
github.com/pelletier/go-toml v1.9.5 // indirect
github.com/pelletier/go-toml/v2 v2.0.5 // indirect
github.com/pkg/errors v0.9.1 // indirect github.com/pkg/errors v0.9.1 // indirect
github.com/pquerna/cachecontrol v0.1.0 // indirect
github.com/richardlehane/mscfb v1.0.4 // indirect github.com/richardlehane/mscfb v1.0.4 // indirect
github.com/richardlehane/msoleps v1.0.4 // indirect github.com/richardlehane/msoleps v1.0.3 // indirect
github.com/rs/xid v1.6.0 // indirect github.com/rs/xid v1.4.0 // indirect
github.com/santhosh-tekuri/jsonschema/v5 v5.0.0 // indirect github.com/santhosh-tekuri/jsonschema/v5 v5.0.0 // indirect
github.com/sirupsen/logrus v1.9.3 // indirect github.com/sirupsen/logrus v1.9.0 // indirect
github.com/spf13/afero v1.15.0 // indirect github.com/spf13/afero v1.8.2 // indirect
github.com/spf13/cast v1.10.0 // indirect github.com/spf13/cast v1.5.0 // indirect
github.com/spf13/pflag v1.0.10 // indirect github.com/spf13/cobra v1.0.0 // indirect
github.com/subosito/gotenv v1.6.0 // indirect github.com/spf13/jwalterweatherman v1.1.0 // indirect
github.com/tiendc/go-deepcopy v1.7.1 // indirect github.com/spf13/pflag v1.0.5 // indirect
github.com/twpayne/go-geom v1.5.7 // indirect github.com/subosito/gotenv v1.4.1 // indirect
github.com/tidwall/pretty v1.1.0 // indirect
github.com/twpayne/go-geom v1.3.6 // indirect
github.com/xdg-go/pbkdf2 v1.0.0 // indirect github.com/xdg-go/pbkdf2 v1.0.0 // indirect
github.com/xdg-go/scram v1.1.2 // indirect github.com/xdg-go/scram v1.1.1 // indirect
github.com/xdg-go/stringprep v1.0.4 // indirect github.com/xdg-go/stringprep v1.0.3 // indirect
github.com/xuri/efp v0.0.1 // indirect github.com/xuri/efp v0.0.0-20220603152613-6918739fd470 // indirect
github.com/xuri/nfp v0.0.1 // indirect github.com/xuri/nfp v0.0.0-20220409054826-5e722a1d9e22 // indirect
github.com/yosida95/uritemplate/v3 v3.0.2 // indirect github.com/youmark/pkcs8 v0.0.0-20181117223130-1be2e3e5546d // indirect
github.com/youmark/pkcs8 v0.0.0-20240726163527-a2c0da244d78 // indirect go.etcd.io/etcd/api/v3 v3.5.4 // indirect
github.com/zclconf/go-cty v1.17.0 // indirect go.etcd.io/etcd/client/pkg/v3 v3.5.4 // indirect
go.etcd.io/etcd/api/v3 v3.5.12 // indirect go.mongodb.org/mongo-driver v1.10.1 // indirect
go.etcd.io/etcd/client/pkg/v3 v3.5.12 // indirect go.uber.org/atomic v1.7.0 // indirect
go.mongodb.org/mongo-driver v1.17.4 // indirect go.uber.org/multierr v1.6.0 // indirect
go.uber.org/atomic v1.11.0 // indirect go.uber.org/zap v1.17.0 // indirect
go.uber.org/multierr v1.11.0 // indirect golang.org/x/crypto v0.8.0 // indirect
go.uber.org/zap v1.21.0 // indirect golang.org/x/net v0.9.0 // indirect
golang.org/x/crypto v0.43.0 // indirect golang.org/x/sync v0.1.0 // indirect
golang.org/x/net v0.46.0 // indirect golang.org/x/sys v0.7.0 // indirect
golang.org/x/sync v0.17.0 // indirect golang.org/x/text v0.9.0 // indirect
golang.org/x/sys v0.37.0 // indirect golang.org/x/tools v0.6.0 // indirect
golang.org/x/text v0.30.0 // indirect google.golang.org/appengine v1.6.7 // indirect
google.golang.org/genproto/googleapis/api v0.0.0-20250804133106-a7a43d27e69b // indirect google.golang.org/genproto v0.0.0-20220519153652-3a47de7e79bd // indirect
google.golang.org/genproto/googleapis/rpc v0.0.0-20251007200510-49b9836ed3ff // indirect gopkg.in/alexcesaro/quotedprintable.v3 v3.0.0-20150716171945-2caba252f4dc // indirect
gopkg.in/ini.v1 v1.67.0 // indirect gopkg.in/ini.v1 v1.67.0 // indirect
gopkg.in/mail.v2 v2.3.1 // indirect
gopkg.in/mgo.v2 v2.0.0-20190816093944-a6b53ec6cb22 // indirect gopkg.in/mgo.v2 v2.0.0-20190816093944-a6b53ec6cb22 // indirect
gopkg.in/square/go-jose.v2 v2.5.2-0.20210529014059-a5c7eec3c614 // indirect
gopkg.in/yaml.v2 v2.4.0 // indirect
gopkg.in/yaml.v3 v3.0.1 // indirect gopkg.in/yaml.v3 v3.0.1 // indirect
) )

1877
go.sum

File diff suppressed because it is too large Load Diff

30
handlers/api/api.go Normal file
View File

@@ -0,0 +1,30 @@
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)
}

51
handlers/api/cache.go Normal file
View File

@@ -0,0 +1,51 @@
package api
import (
"encoding/json"
"fmt"
"net/http"
"strconv"
"github.com/gorilla/mux"
)
func (h APIHandler) GetCache(w http.ResponseWriter, r *http.Request) {
vars := mux.Vars(r)
cacheid := vars["cacheid"]
d, err := h.cache.Get(cacheid)
if err != nil {
fmt.Println(err)
w.WriteHeader(http.StatusNotFound)
return
}
result := d
if data, ok := d.([]any); ok {
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
}
w.WriteHeader(http.StatusOK)
w.Header().Set("Content-Type", "application/json")
w.Write(j)
}

97
handlers/api/export.go Normal file
View File

@@ -0,0 +1,97 @@
package api
import (
"encoding/csv"
"fmt"
"net/http"
"sort"
"strconv"
"github.com/gorilla/mux"
)
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 {
fmt.Println(err)
w.WriteHeader(http.StatusNotFound)
return
}
if data, ok := d.([]any); ok {
flatmaps := FlatMaps{}
//fmt.Println(data)
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:
fmt.Println(prefix+k, " : ", v)
dest[prefix+k] = v
}
}
}

54
handlers/api/geo.go Normal file
View File

@@ -0,0 +1,54 @@
package api
import (
"encoding/json"
"fmt"
"io/ioutil"
"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 := ioutil.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)
}

51
handlers/api/oidc.go Normal file
View File

@@ -0,0 +1,51 @@
package api
import (
"context"
"fmt"
"net/http"
)
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 {
fmt.Println("Exchange error")
fmt.Println(err)
w.WriteHeader(http.StatusInternalServerError)
return
}
// Extract the ID Token from OAuth2 token.
rawIDToken, ok := oauth2Token.Extra("id_token").(string)
if !ok {
fmt.Println("issue retrieving token")
w.WriteHeader(http.StatusInternalServerError)
return
}
_, err = h.idp.TokenVerifier.Verify(context.Background(), rawIDToken)
if err != nil {
fmt.Println("not able to verify token")
fmt.Println(err)
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 {
fmt.Println(err)
w.WriteHeader(http.StatusInternalServerError)
return
}
http.Redirect(w, r, redirect, http.StatusFound)
}

View File

@@ -0,0 +1,595 @@
package application
import (
"context"
"crypto/rand"
"encoding/base64"
"fmt"
"io"
"net/http"
"sort"
"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"
"google.golang.org/protobuf/types/known/structpb"
)
func (h *ApplicationHandler) Administration(w http.ResponseWriter, r *http.Request) {
accounts, err := h.services.GetAccounts()
if err != nil {
fmt.Println(err)
w.WriteHeader(http.StatusInternalServerError)
return
}
beneficiaries, err := h.services.GetBeneficiaries()
if err != nil {
fmt.Println(err)
w.WriteHeader(http.StatusInternalServerError)
return
}
bookings, err := h.services.GetBookings()
if err != nil {
fmt.Println(err)
w.WriteHeader(http.StatusInternalServerError)
return
}
request := &groupsmanagement.GetGroupsRequest{
Namespaces: []string{"parcoursmob_organizations"},
}
resp, err := h.services.GRPC.GroupsManagement.GetGroups(context.TODO(), request)
if err != nil {
fmt.Println(err)
w.WriteHeader(http.StatusInternalServerError)
return
}
var groups = []groupstorage.Group{}
for _, group := range resp.Groups {
g := group.ToStorageType()
groups = append(groups, g)
}
sort.Sort(sorting.GroupsByName(groups))
////////////////////////////////////add event////////////////////////////////////////////
rresp, err := h.services.GRPC.Agenda.GetEvents(context.TODO(), &agenda.GetEventsRequest{
Namespaces: []string{"parcoursmob_dispositifs"},
})
if err != nil {
fmt.Println(err)
w.WriteHeader(http.StatusInternalServerError)
return
}
responses := []agendastorage.Event{}
groupids := []string{}
for _, e := range rresp.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,
})
groupps := map[string]any{}
if err == nil {
for _, g := range groupsresp.Groups {
groupps[g.Id] = g.ToStorageType()
}
}
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") == "" {
fmt.Println("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 {
fmt.Println(err)
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",
},
}
_, err = h.services.GRPC.GroupsManagement.AddGroup(context.TODO(), request_organization)
if err != nil {
fmt.Println(err)
w.WriteHeader(http.StatusInternalServerError)
return
}
// Create the admin role for the organization
_, err = h.services.GRPC.GroupsManagement.AddGroup(context.TODO(), request_role)
if err != nil {
fmt.Println(err)
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 {
fmt.Println(err)
w.WriteHeader(http.StatusInternalServerError)
return
}
groupmembers, admins, err := h.groupmembers(groupid)
if err != nil {
fmt.Println(err)
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"]
groupresp, err := h.services.GRPC.GroupsManagement.GetGroup(context.TODO(), &groupsmanagement.GetGroupRequest{
Id: groupid,
Namespace: "parcoursmob_organizations",
})
if err != nil {
fmt.Println(err)
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 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)
_, err = h.services.GRPC.MobilityAccounts.UpdateData(
context.TODO(),
&accounts.UpdateDataRequest{
Account: as,
},
)
fmt.Println(err)
data := map[string]any{
"group": groupresp.Group.ToStorageType().Data["name"],
}
if err := h.emailing.Send("onboarding.existing_administrator", r.FormValue("username"), data); err != nil {
fmt.Println(err)
}
http.Redirect(w, r, fmt.Sprintf("/app/administration/groups/%s", groupid), http.StatusFound)
return
} 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 {
fmt.Println(err)
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 {
fmt.Println(err)
w.WriteHeader(http.StatusInternalServerError)
return
}
}
http.Redirect(w, r, fmt.Sprintf("/app/administration/groups/%s", groupid), http.StatusFound)
return
}
func (h *ApplicationHandler) AdministrationGroupInviteMember(w http.ResponseWriter, r *http.Request) {
vars := mux.Vars(r)
groupid := vars["groupid"]
groupresp, err := h.services.GRPC.GroupsManagement.GetGroup(context.TODO(), &groupsmanagement.GetGroupRequest{
Id: groupid,
Namespace: "parcoursmob_organizations",
})
if err != nil {
fmt.Println(err)
w.WriteHeader(http.StatusInternalServerError)
return
}
group := groupresp.Group.ToStorageType()
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,
},
)
fmt.Println(err)
data := map[string]any{
"group": group.Data["name"],
}
if err := h.emailing.Send("onboarding.existing_member", r.FormValue("username"), data); err != nil {
fmt.Println(err)
}
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 {
fmt.Println(err)
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 {
fmt.Println(err)
w.WriteHeader(http.StatusInternalServerError)
return
}
}
http.Redirect(w, r, "/app/administration/groups/"+group.ID, http.StatusFound)
return
}
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 {
fmt.Println(err)
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 {
fmt.Println(err)
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 {
fmt.Println(err)
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 {
fmt.Println(err)
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 {
fmt.Println(err)
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 {
fmt.Println(err)
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 {
fmt.Println(err)
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 {
fmt.Println(err)
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)
}

View File

@@ -0,0 +1,687 @@
package application
import (
"context"
"encoding/json"
"fmt"
"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"
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/gorilla/mux"
"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 {
fmt.Println(err)
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 {
fmt.Println(err)
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 {
fmt.Println(err)
w.WriteHeader(http.StatusBadRequest)
return
}
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 {
fmt.Println(err)
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)
}
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 {
fmt.Println(err)
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 {
fmt.Println(err)
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 {
fmt.Println(err)
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)
}
}
h.Renderer.AgendaDisplayEvent(w, r, resp.Event.ToStorageType(), groupresp.Group.ToStorageType(), subscribers, accounts)
}
func (h *ApplicationHandler) AgendaSubscribeEvent(w http.ResponseWriter, r *http.Request) {
current_group, err := h.currentGroup(r)
if err != nil {
fmt.Println(err)
w.WriteHeader(http.StatusInternalServerError)
return
}
current_user_token, current_user_claims, err := h.currentUser(r)
if err != nil {
fmt.Println(err)
w.WriteHeader(http.StatusInternalServerError)
return
}
vars := mux.Vars(r)
eventid := vars["eventid"]
if err := r.ParseForm(); err != nil {
fmt.Println(err)
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 {
fmt.Println(err)
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 {
fmt.Println(err)
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 {
fmt.Println(err)
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 {
fmt.Println(err)
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 {
fmt.Println(err)
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 {
fmt.Println(err)
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 {
fmt.Println(err)
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 {
fmt.Println(err)
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 {
fmt.Println(err)
w.WriteHeader(http.StatusInternalServerError)
return
}
current_user_token, current_user_claims, err := h.currentUser(r)
if err != nil {
fmt.Println(err)
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 {
fmt.Println(err)
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
fmt.Println(mail)
_, err := h.services.GRPC.Agenda.DeleteSubscription(context.TODO(), request)
if err != nil {
fmt.Println(err)
w.WriteHeader(http.StatusInternalServerError)
return
}
if err := h.emailing.Send("delete_subscriber.request", mail, data); err != nil {
fmt.Println(err)
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 {
fmt.Println(err)
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 {
fmt.Println(err)
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 {
fmt.Println(err)
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)
}

View File

@@ -4,35 +4,41 @@ import (
"errors" "errors"
"net/http" "net/http"
"git.coopgo.io/coopgo-apps/parcoursmob/renderer"
"git.coopgo.io/coopgo-apps/parcoursmob/services" "git.coopgo.io/coopgo-apps/parcoursmob/services"
"git.coopgo.io/coopgo-apps/parcoursmob/core/utils/identification" "git.coopgo.io/coopgo-apps/parcoursmob/utils/identification"
cache "git.coopgo.io/coopgo-apps/parcoursmob/core/utils/storage" cache "git.coopgo.io/coopgo-apps/parcoursmob/utils/storage"
"git.coopgo.io/coopgo-platform/emailing" "git.coopgo.io/coopgo-platform/emailing"
"git.coopgo.io/coopgo-platform/groups-management/storage" "git.coopgo.io/coopgo-platform/groups-management/storage"
"github.com/coreos/go-oidc/v3/oidc" "github.com/coreos/go-oidc"
"github.com/spf13/viper" "github.com/spf13/viper"
) )
type ApplicationHandler struct { type ApplicationHandler struct {
config *viper.Viper config *viper.Viper
Renderer *renderer.Renderer
services *services.ServicesHandler services *services.ServicesHandler
cache cache.CacheHandler cache cache.CacheHandler
filestorage cache.FileStorage filestorage cache.FileStorage
emailing *emailing.Mailer emailing *emailing.Mailer
idp *identification.IdentificationProvider
} }
func NewApplicationHandler(cfg *viper.Viper, svc *services.ServicesHandler, cache cache.CacheHandler, filestorage cache.FileStorage, emailing *emailing.Mailer, idp *identification.IdentificationProvider) (*ApplicationHandler, error) { 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)
return &ApplicationHandler{ return &ApplicationHandler{
config: cfg, config: cfg,
Renderer: renderer,
services: svc, services: svc,
cache: cache, cache: cache,
filestorage: filestorage, filestorage: filestorage,
emailing: emailing, emailing: emailing,
idp: idp,
}, nil }, nil
} }
func (h *ApplicationHandler) NotFound(w http.ResponseWriter, r *http.Request) {
w.WriteHeader(http.StatusNotFound)
}
func (h *ApplicationHandler) templateFile(file string) string { func (h *ApplicationHandler) templateFile(file string) string {
return h.config.GetString("templates.root") + file return h.config.GetString("templates.root") + file

View File

@@ -0,0 +1,413 @@
package application
import (
"bytes"
"context"
"encoding/json"
"errors"
"fmt"
"image/png"
"io"
"log"
"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"
fleets "git.coopgo.io/coopgo-platform/fleets/grpcapi"
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/gorilla/mux"
"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"`
}
func (h *ApplicationHandler) BeneficiariesList(w http.ResponseWriter, r *http.Request) {
accounts, err := h.beneficiaries(r)
if err != nil {
fmt.Println(err)
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 {
fmt.Println("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 {
fmt.Println(err)
w.WriteHeader(http.StatusBadRequest)
return
}
data, err := structpb.NewValue(dataMap)
if err != nil {
fmt.Println(err)
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 {
fmt.Println(err)
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 {
fmt.Println(err)
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 {
fmt.Println(err)
w.WriteHeader(http.StatusInternalServerError)
return
}
bookingsrequest := &fleets.GetDriverBookingsRequest{
Driver: beneficiaryID,
}
bookingsresp, err := h.services.GRPC.Fleets.GetDriverBookings(context.TODO(), bookingsrequest)
if err != nil {
fmt.Println(err)
w.WriteHeader(http.StatusInternalServerError)
return
}
bookings := []any{}
for _, b := range bookingsresp.Bookings {
bookings = append(bookings, b.ToStorageType())
}
groupsrequest := &groupsmanagement.GetGroupsRequest{
Namespaces: []string{"parcoursmob_organizations"},
Member: beneficiaryID,
}
groupsresp, err := h.services.GRPC.GroupsManagement.GetGroups(context.TODO(), groupsrequest)
if err != nil {
fmt.Println(err)
}
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")
h.Renderer.BeneficiaryDisplay(w, r, resp.Account.ToStorageType(), bookings, organizations, beneficiaries_file_types, file_types_map, documents)
}
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 {
fmt.Println(err)
w.WriteHeader(http.StatusBadRequest)
return
}
data, err := structpb.NewValue(dataMap)
if err != nil {
fmt.Println(err)
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 {
fmt.Println(err)
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 {
fmt.Println(err)
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 {
fmt.Println(err)
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.Println("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.Println("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 {
fmt.Println(err)
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_BENEFICIARIES, fmt.Sprintf("%s/%s_%s", beneficiaryID, fileid, header.Filename), header.Size, metadata); err != nil {
fmt.Println(err)
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 {
fmt.Println(err)
w.WriteHeader(http.StatusInternalServerError)
return
}
w.Header().Set("Content-Type", info.ContentType)
if _, err = io.Copy(w, file); err != nil {
fmt.Println(err)
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 (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
}

View File

@@ -0,0 +1,79 @@
package application
import (
"context"
"fmt"
"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"
"git.coopgo.io/coopgo-platform/groups-management/storage"
mobilityaccounts "git.coopgo.io/coopgo-platform/mobility-accounts/grpcapi"
"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 {
fmt.Println(err)
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 {
fmt.Println(err)
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(),
})
for _, e := range eventsresp.Events {
events = append(events, e.ToStorageType())
}
sort.Sort(sorting.EventsByStartdate(events))
h.Renderer.Dashboard(w, r, accounts, count, count_members, events)
}

View File

@@ -0,0 +1,7 @@
package application
import "net/http"
func (h *ApplicationHandler) DirectoryHome(w http.ResponseWriter, r *http.Request) {
h.Renderer.DirectoryHome(w, r)
}

View File

@@ -0,0 +1,128 @@
package application
import (
"context"
"crypto/rand"
"encoding/base64"
"fmt"
"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"
)
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 {
fmt.Println(err)
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,
},
)
fmt.Println(err)
data := map[string]any{
"group": group.Data["name"],
}
if err := h.emailing.Send("onboarding.existing_member", r.FormValue("username"), data); err != nil {
fmt.Println(err)
}
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 {
fmt.Println(err)
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 {
fmt.Println(err)
w.WriteHeader(http.StatusInternalServerError)
return
}
}
http.Redirect(w, r, "/app/group/settings", http.StatusFound)
return
}

View File

@@ -0,0 +1,221 @@
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"
"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 {
fmt.Println(err)
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") == "" {
fmt.Println("invalid name")
w.WriteHeader(http.StatusBadRequest)
return
}
if r.FormValue("type") == "" {
fmt.Println("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 {
fmt.Println(err)
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 {
fmt.Println(err)
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 {
fmt.Println(err)
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 {
fmt.Println(err)
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 {
fmt.Println(err)
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 {
fmt.Println(err)
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)
}

View File

@@ -0,0 +1,568 @@
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"
"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()
locTime, errTime := time.LoadLocation("Europe/Paris")
if errTime != nil {
fmt.Println("Loading timezone location Europe/Paris error : ")
fmt.Println("Missing zones in container ? ")
panic(errTime)
}
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 {
fmt.Println(err)
w.WriteHeader(http.StatusBadRequest)
return
}
destinationgeo, err = geojson.UnmarshalFeature([]byte(destination))
if err != nil {
fmt.Println(err)
w.WriteHeader(http.StatusBadRequest)
return
}
//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 {
fmt.Println(err)
w.WriteHeader(http.StatusBadRequest)
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 {
fmt.Println(err)
// w.WriteHeader(http.StatusBadRequest)
// return
}
//CARPOOL
// carpoolrequest := fmt.Sprintf(
// "https://api.rdex.ridygo.fr/journeys.json?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.Add(24*time.Hour).Format("2006-01-02"))
carpoolrequest := "https://api.rdex.ridygo.fr/journeys.json"
client := &http.Client{}
req, err := http.NewRequest("GET", carpoolrequest, nil)
if err != nil {
fmt.Println(err)
}
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 {
fmt.Println(err)
}
if err == nil && resp.StatusCode == http.StatusOK {
err = json.NewDecoder(resp.Body).Decode(&carpoolresults)
if err != nil {
fmt.Println(err)
}
if carpoolresults == nil {
carpoolresults = []any{}
}
} else {
carpoolresults = []any{}
}
// Vehicles
vehiclerequest := &fleets.GetVehiclesRequest{
Namespaces: []string{"parcoursmob"},
}
vehicleresp, err := h.services.GRPC.Fleets.GetVehicles(context.TODO(), vehiclerequest)
if err != nil {
fmt.Println(err)
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)
}
}
}
h.Renderer.JourneysSearch(w, r, carpoolresults, journeys, vehicles, 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 {
fmt.Println(err)
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 {
fmt.Println(err)
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 {
fmt.Println(err)
w.WriteHeader(http.StatusBadRequest)
return
}
dstinationgeo, err = geojson.UnmarshalFeature([]byte(destination))
if err != nil {
fmt.Println(err)
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") == "" {
fmt.Println("invalid name")
w.WriteHeader(http.StatusBadRequest)
return
}
if r.FormValue("number") == "" {
fmt.Println("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 {
fmt.Println(err)
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 {
fmt.Println(err)
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 {
fmt.Println(err)
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 {
fmt.Println(err)
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 {
fmt.Println(err)
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 {
fmt.Println(err)
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 {
fmt.Println(err)
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 {
fmt.Println(err)
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 {
// fmt.Println(err)
// 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)
//fmt.Println(groups)
var number string = strconv.Itoa(len(resp.Group.Members))
/////////////////////
accountsBeneficaire, err := h.beneficiaries(r)
if err != nil {
fmt.Println(err)
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 {
fmt.Println(err)
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 {
fmt.Println(err)
w.WriteHeader(http.StatusInternalServerError)
return
}
req := &groupsmanagement.UnsubscribeMemberRequest{
Id: ressp.Group.Id,
}
_, errr := h.services.GRPC.GroupsManagement.UnsubscribeMember(context.TODO(), req)
if errr != nil {
fmt.Println(errr)
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 {
fmt.Println(err)
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)
}

View File

@@ -0,0 +1,213 @@
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"
"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 {
fmt.Println(err)
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 {
fmt.Println(err)
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 {
fmt.Println(err)
w.WriteHeader(http.StatusBadRequest)
return
}
data, err := structpb.NewValue(dataMap)
if err != nil {
fmt.Println(err)
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 {
fmt.Println(err)
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 {
fmt.Println(err)
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 {
fmt.Println(err)
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 {
fmt.Println(err)
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 {
fmt.Println(err)
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)
}

View File

@@ -0,0 +1,40 @@
package application
import (
"fmt"
"net/http"
"git.coopgo.io/coopgo-apps/parcoursmob/utils/identification"
)
type Message struct {
Content string
}
func (h *ApplicationHandler) SupportSend(w http.ResponseWriter, r *http.Request) {
c := r.Context().Value(identification.ClaimsKey)
if c == nil {
fmt.Println("no current user claims")
w.WriteHeader(http.StatusInternalServerError)
return
}
current_user_claims := c.(map[string]any)
comment := r.PostFormValue(("comment"))
if r.Method == "POST" {
data := map[string]any{
"key": comment,
"user": current_user_claims["email"],
}
if err := h.emailing.Send("support.request", "support@parcoursmob.fr", data); err != nil {
fmt.Println(err)
w.WriteHeader(http.StatusInternalServerError)
}
http.Redirect(w, r, "/app/", http.StatusFound)
return
}
h.Renderer.SupportSend(w, r, comment, current_user_claims)
}

View File

@@ -0,0 +1,652 @@
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"
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"
"github.com/google/uuid"
"github.com/gorilla/mux"
"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 {
fmt.Println(err)
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
}
}
sort.Sort(sorting.VehiclesByLicencePlate(vehicles))
sort.Sort(sorting.BookingsByStartdate(bookings))
h.Renderer.VehiclesManagementOverview(w, r, vehicles, vehicles_map, 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 {
fmt.Println(err)
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)
h.Renderer.VehiclesManagementBookingsList(w, r, vehicles_map, 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 {
fmt.Println(err)
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 {
fmt.Println(err)
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 != "" {
fmt.Println(v)
dataMap["automatic"] = (v == "on")
}
data, err := structpb.NewValue(dataMap)
if err != nil {
fmt.Println(err)
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 {
fmt.Println(err)
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 {
fmt.Println(err)
w.WriteHeader(http.StatusInternalServerError)
return
}
h.Renderer.VehiclesFleetDisplay(w, r, resp.Vehicle.ToStorageType())
}
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 {
fmt.Println(err)
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 {
fmt.Println(err)
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 {
fmt.Println(err)
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 {
fmt.Println(err)
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 {
fmt.Println(err)
}
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")
h.Renderer.VehicleManagementBookingDisplay(w, r, booking, booking.Vehicle, beneficiary, groupresp.Group.ToStorageType(), documents, file_types_map, alternatives)
}
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 {
fmt.Println(err)
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 {
fmt.Println(err)
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 {
fmt.Println("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 {
fmt.Println("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 {
fmt.Println("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 {
fmt.Println(err)
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 {
fmt.Println(err)
w.WriteHeader(http.StatusBadRequest)
return
}
http.Redirect(w, r, fmt.Sprintf("/app/vehicles-management/fleet/%s", vehicleid), http.StatusFound)
}
// func (h *ApplicationHandler) UnbookingVehicles(w http.ResponseWriter, r *http.Request) {
// request := &fleets.GetVehiclesRequest{
// Namespaces: []string{"parcoursmob"},
// }
// resp, err := h.services.GRPC.Fleets.GetVehicles(context.TODO(), request)
// if err != nil {
// fmt.Println(err)
// w.WriteHeader(http.StatusInternalServerError)
// }
// vehicles := []fleetsstorage.Vehicle{}
// fmt.Println(resp.Vehicles[0].Bookings)
// for i, vehicle := range resp.Vehicles {
// if len(resp.Vehicles[i].Bookings) == 0 {
// v := vehicle.ToStorageType()
// vehicles = append(vehicles, v)
// }
// }
// // if len(resp.Vehicle.ToStorageType().Bookings) == 0 {
// // h.Renderer.UnbookingVehicles(w, r, resp.Vehicle.ToStorageType())
// // }
// // fmt.Println(resp.Vehicle.ToStorageType().Bookings)
// fmt.Println(vehicles)
// h.Renderer.UnbookingVehicles(w, r, vehicles)
// }
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 {
fmt.Println(err)
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 {
fmt.Println(err)
w.WriteHeader(http.StatusInternalServerError)
return
}
current_user_token, current_user_claims, err := h.currentUser(r)
if err != nil {
fmt.Println(err)
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 {
fmt.Println(err)
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 {
fmt.Println(err)
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 {
fmt.Println(err)
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 {
fmt.Println(err)
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 {
fmt.Println(err)
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 != "" {
fmt.Println(v)
dataMap["automatic"] = (v == "on")
}
data, err := structpb.NewValue(dataMap)
if err != nil {
fmt.Println(err)
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 {
fmt.Println(err)
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)
}

View File

@@ -0,0 +1,378 @@
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"
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"
"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") != "" {
// Handler form
searched = true
requestbeneficiary := &mobilityaccounts.GetAccountRequest{
Id: r.FormValue("beneficiaryid"),
}
respbeneficiary, err := h.services.GRPC.MobilityAccounts.GetAccount(context.TODO(), requestbeneficiary)
if err != nil {
fmt.Println(err)
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 {
fmt.Println(err)
w.WriteHeader(http.StatusInternalServerError)
}
for _, vehicle := range resp.Vehicles {
v := vehicle.ToStorageType()
if r.FormValue("type") == "Voiture" && automatic {
fmt.Println(v.Data["automatic"])
if auto, ok := v.Data["automatic"].(bool); !ok || !auto {
fmt.Println(v.Data["automatic"])
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 {
fmt.Println(err)
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 {
fmt.Println(err)
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) {
fmt.Println("Book")
current_group, err := h.currentGroup(r)
if err != nil {
fmt.Println(err)
w.WriteHeader(http.StatusInternalServerError)
return
}
current_user_token, current_user_claims, err := h.currentUser(r)
if err != nil {
fmt.Println(err)
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 {
fmt.Println(err)
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 {
fmt.Println(err)
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 {
fmt.Println(err)
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 {
fmt.Println(err)
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 {
fmt.Println(err)
w.WriteHeader(http.StatusInternalServerError)
return
}
}
}
_, err = h.services.GRPC.Fleets.CreateBooking(context.TODO(), request)
if err != nil {
fmt.Println(err)
w.WriteHeader(http.StatusBadRequest)
return
}
//NOTIFY GROUP MEMBERS
members, _, err := h.groupmembers(vehicle.Vehicle.Administrators[0])
if err != nil {
fmt.Println(err)
} 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 {
fmt.Println(err)
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 {
fmt.Println(err)
w.WriteHeader(http.StatusInternalServerError)
return
}
documents := h.filestorage.List(filestorage.PREFIX_BOOKINGS + "/" + bookingid)
file_types_map := h.config.GetStringMapString("storage.files.file_types")
h.Renderer.VehicleBookingDisplay(w, r, booking, booking.Vehicle, beneficiaryresp.Account.ToStorageType(), groupresp.Group.ToStorageType(), documents, file_types_map)
}
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 {
fmt.Println(err)
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"]
fmt.Println(fmt.Sprintf("%s/%s", bookingid, document))
file, info, err := h.filestorage.Get(filestorage.PREFIX_BOOKINGS, fmt.Sprintf("%s/%s", bookingid, document))
if err != nil {
fmt.Println(err)
w.WriteHeader(http.StatusInternalServerError)
return
}
w.Header().Set("Content-Type", info.ContentType)
if _, err = io.Copy(w, file); err != nil {
fmt.Println(err)
w.WriteHeader(http.StatusInternalServerError)
return
}
http.Redirect(w, r, fmt.Sprintf("/app/vehicles/bookings/%s", bookingid), http.StatusFound)
}

32
handlers/auth/auth.go Normal file
View File

@@ -0,0 +1,32 @@
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
}

View File

@@ -2,7 +2,7 @@ package auth
import "net/http" import "net/http"
func (h *Handler) Disconnect(w http.ResponseWriter, r *http.Request) { func (h *AuthHandler) Disconnect(w http.ResponseWriter, r *http.Request) {
session, err := h.idp.SessionsStore.Get(r, "parcoursmob_session") session, err := h.idp.SessionsStore.Get(r, "parcoursmob_session")
if err == nil { if err == nil {
session.Options.MaxAge = -1 session.Options.MaxAge = -1

91
handlers/auth/groups.go Normal file
View File

@@ -0,0 +1,91 @@
package auth
import (
"context"
"fmt"
"net/http"
groupsmanagement "git.coopgo.io/coopgo-platform/groups-management/grpcapi"
)
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 {
fmt.Println(err)
}
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 {
fmt.Println(err)
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)
}

View File

@@ -0,0 +1,97 @@
package auth
import (
"context"
"crypto/rand"
"encoding/base64"
"fmt"
"io"
"net/http"
"time"
"git.coopgo.io/coopgo-platform/mobility-accounts/grpcapi"
)
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 {
fmt.Println(err)
http.Redirect(w, r, "/app/", http.StatusFound)
return
}
b := make([]byte, 16)
if _, err := io.ReadFull(rand.Reader, b); err != nil {
fmt.Println(err)
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 {
fmt.Println(err)
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 {
fmt.Println(err)
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 {
fmt.Println(err)
w.WriteHeader(http.StatusInternalServerError)
}
err = h.cache.Delete("retrieve-password/" + key)
if err != nil {
fmt.Println(err)
}
http.Redirect(w, r, "/app/", http.StatusFound)
}
h.Renderer.LostPasswordRecover(w, r, recover)
}

View File

@@ -0,0 +1,87 @@
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"
)
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 {
fmt.Println(err)
h.Renderer.AuthOnboardingKO(w, r, key)
return
}
onboardingmap := onboarding.(map[string]any)
if r.Method == "POST" {
if r.FormValue("password") == "" {
fmt.Println("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 {
fmt.Println(err)
w.WriteHeader(http.StatusInternalServerError)
return
}
request := &mobilityaccounts.RegisterRequest{
Account: acc,
}
_, err = h.services.GRPC.MobilityAccounts.Register(context.TODO(), request)
if err != nil {
fmt.Println(err)
w.WriteHeader(http.StatusInternalServerError)
return
}
err = h.cache.Delete("onboarding/" + key)
if err != nil {
fmt.Println(err)
}
http.Redirect(w, r, "/app/", http.StatusFound)
}
h.Renderer.AuthOnboarding(w, r, key, onboarding)
}

196
handlers/exports/agenda.go Normal file
View File

@@ -0,0 +1,196 @@
package exports
import (
"context"
"fmt"
"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/xuri/excelize/v2"
"net/http"
"sort"
)
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 {
fmt.Println(err)
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 {
fmt.Println(err)
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 {
fmt.Println(err)
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 {
fmt.Println(err)
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 {
fmt.Println(err)
}
}()
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)
}

View File

@@ -0,0 +1,21 @@
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
}

163
handlers/exports/fleets.go Normal file
View File

@@ -0,0 +1,163 @@
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/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 {
fmt.Println(err)
w.WriteHeader(http.StatusInternalServerError)
return
}
beneficiaries_ids := []string{}
for _, vehicle := range reesp.Vehicles {
v := vehicle.ToStorageType()
fmt.Println(v)
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 {
fmt.Println(err)
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 {
fmt.Println(err)
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 {
fmt.Println(err)
}
}()
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)
}

196
main.go Executable file → Normal file
View File

@@ -1,84 +1,190 @@
package main package main
import ( import (
"os" "fmt"
"sync" "log"
"net/http"
"time"
"github.com/rs/zerolog" "git.coopgo.io/coopgo-apps/parcoursmob/handlers/api"
"github.com/rs/zerolog/log" "git.coopgo.io/coopgo-apps/parcoursmob/handlers/application"
"git.coopgo.io/coopgo-apps/parcoursmob/handlers/auth"
"git.coopgo.io/coopgo-apps/parcoursmob/core/application" "git.coopgo.io/coopgo-apps/parcoursmob/handlers/exports"
"git.coopgo.io/coopgo-apps/parcoursmob/renderer" "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/services"
"git.coopgo.io/coopgo-apps/parcoursmob/core/utils/identification" "git.coopgo.io/coopgo-apps/parcoursmob/utils/identification"
cache "git.coopgo.io/coopgo-apps/parcoursmob/core/utils/storage" cache "git.coopgo.io/coopgo-apps/parcoursmob/utils/storage"
"github.com/gorilla/mux"
) )
func main() { func main() {
cfg, err := ReadConfig() cfg, err := ReadConfig()
if err != nil { if err != nil {
log.Fatal().Err(err).Msg("cannot read config!") panic(err)
return
} }
var ( 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") 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) svc, err := services.NewServicesHandler(cfg)
if err != nil { if err != nil {
log.Panic().Err(err).Msg("Error creating services handler") panic(err)
} }
kv, err := cache.NewKVHandler(cfg) kv, err := cache.NewKVHandler(cfg)
if err != nil { if err != nil {
log.Panic().Err(err).Msg("Error creating KV handler") panic(err)
} }
filestorage, _ := cache.NewFileStorage(cfg)
filestorage, err := cache.NewFileStorage(cfg)
idp, err := identification.NewIdentificationProvider(cfg, svc, kv) idp, err := identification.NewIdentificationProvider(cfg, svc, kv)
if err != nil { if err != nil {
log.Panic().Err(err).Msg("Error creating identification provider") panic(err)
} }
emailing, err := renderer.NewEmailingHandler(cfg) emailing, err := renderer.NewEmailingHandler(cfg)
if err != nil { if err != nil {
log.Panic().Err(err).Msg("Error creating emailing handler") panic(err)
} }
// Create renderer for web server apiHandler, _ := api.NewAPIHandler(cfg, idp, svc, kv)
templates_root := cfg.GetString("templates.root") applicationHandler, _ := application.NewApplicationHandler(cfg, svc, kv, filestorage, emailing)
webRenderer := renderer.NewRenderer(cfg, templates_root, filestorage) exportsHandler, _ := exports.NewExportsHandler(cfg, svc, emailing)
authHandler, _ := auth.NewAuthHandler(cfg, idp, svc, kv, emailing)
applicationHandler, _ := application.NewApplicationHandler(cfg, svc, kv, filestorage, emailing, idp) fmt.Println("Running", service_name, ":")
if dev_env {
var wg sync.WaitGroup fmt.Printf("\033]0;%s\007", service_name)
if webEnabled {
wg.Add(1)
go func() {
defer wg.Done()
web.Run(cfg, svc, webRenderer, applicationHandler, idp, kv, filestorage)
}()
} }
if mcpEnabled { r := mux.NewRouter()
wg.Add(1)
go func() { r.PathPrefix("/public/").Handler(http.StripPrefix("/public/", http.FileServer(http.Dir(templates_public_dir))))
defer wg.Done()
mcp.Run(cfg, svc, applicationHandler, kv, filestorage) 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)
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)
/////////////////////////////////////////////////////////////////////////////////////////////////////
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)
fmt.Println("-> HTTP server listening on", address)
srv := &http.Server{
Handler: r,
Addr: address,
WriteTimeout: 15 * time.Second,
ReadTimeout: 15 * time.Second,
} }
wg.Wait() log.Fatal(srv.ListenAndServe())
}
func redirectApp(w http.ResponseWriter, r *http.Request) {
http.Redirect(w, r, "/app/", http.StatusFound)
} }

3
renderer/administration.go Executable file → Normal file
View File

@@ -100,7 +100,7 @@ func (renderer *Renderer) AdminStatVehicles(w http.ResponseWriter, r *http.Reque
renderer.Render("vehicles_state", w, r, files, state) 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, filters map[string]string) { 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) {
files := renderer.ThemeConfig.GetStringSlice("views.administration.bookings_list.files") files := renderer.ThemeConfig.GetStringSlice("views.administration.bookings_list.files")
state := NewState(r, renderer.ThemeConfig, administrationMenu) state := NewState(r, renderer.ThemeConfig, administrationMenu)
state.ViewState = map[string]any{ state.ViewState = map[string]any{
@@ -108,7 +108,6 @@ func (renderer *Renderer) AdminStatBookings(w http.ResponseWriter, r *http.Reque
"bookings": bookings, "bookings": bookings,
"admingroups": admingroups, "admingroups": admingroups,
"beneficiaries_map": beneficiaries, "beneficiaries_map": beneficiaries,
"filters": filters,
} }
renderer.Render("bookings_stats", w, r, files, state) renderer.Render("bookings_stats", w, r, files, state)

28
renderer/agenda.go Executable file → Normal file
View File

@@ -30,29 +30,20 @@ func (renderer *Renderer) AgendaHistory(w http.ResponseWriter, r *http.Request,
renderer.Render("agenda history", w, r, files, state) renderer.Render("agenda history", w, r, files, state)
} }
func (renderer *Renderer) AgendaCreateEvent(w http.ResponseWriter, r *http.Request, events_file_types []string, file_types_map map[string]string, documents any) { func (renderer *Renderer) AgendaCreateEvent(w http.ResponseWriter, r *http.Request) {
files := renderer.ThemeConfig.GetStringSlice("views.agenda.create_event.files") files := renderer.ThemeConfig.GetStringSlice("views.agenda.create_event.files")
state := NewState(r, renderer.ThemeConfig, agendaMenu) state := NewState(r, renderer.ThemeConfig, agendaMenu)
state.ViewState = map[string]any{
"events_file_types": events_file_types,
"file_types_map": file_types_map,
"documents": documents,
}
renderer.Render("agenda create event", w, r, files, state) renderer.Render("agenda create event", w, r, files, state)
} }
func (renderer *Renderer) AgendaDisplayEvent(w http.ResponseWriter, r *http.Request, event any, group any, events_file_types []string, file_types_map map[string]string, documents any, subscribers map[string]any, beneficiaries any) { func (renderer *Renderer) AgendaDisplayEvent(w http.ResponseWriter, r *http.Request, event any, group any, subscribers map[string]any, beneficiaries any) {
files := renderer.ThemeConfig.GetStringSlice("views.agenda.display_event.files") files := renderer.ThemeConfig.GetStringSlice("views.agenda.display_event.files")
state := NewState(r, renderer.ThemeConfig, agendaMenu) state := NewState(r, renderer.ThemeConfig, agendaMenu)
state.ViewState = map[string]any{ state.ViewState = map[string]any{
"event": event, "event": event,
"group": group, "group": group,
"events_file_types": events_file_types,
"file_types_map": file_types_map,
"documents": documents,
"subscribers": subscribers, "subscribers": subscribers,
"beneficiaries": beneficiaries, "beneficiaries": beneficiaries,
} }
@@ -109,18 +100,3 @@ func (renderer *Renderer) AgendaDeleteEvent(w http.ResponseWriter, r *http.Reque
renderer.Render("event_deleteEvent", w, r, files, state) renderer.Render("event_deleteEvent", w, r, files, state)
} }
////////Event documents////////////////////////
// func (renderer *Renderer) EventDocuments(w http.ResponseWriter, r *http.Request, event any, documents []any) {
// files := renderer.ThemeConfig.GetStringSlice("views.agenda.event_files.files")
// state := NewState(r, renderer.ThemeConfig, agendaMenu)
// state.ViewState = map[string]any{
// "event": event,
// "documents": documents,
// "eventid": event.(map[string]any)["id"],
// "eventtitle": event.(map[string]any)["title"],
// }
// renderer.Render("event_files", w, r, files, state)
// }

0
renderer/auth.go Executable file → Normal file
View File

33
renderer/beneficiaries.go Executable file → Normal file
View File

@@ -5,7 +5,6 @@ import (
"html/template" "html/template"
"net/http" "net/http"
fleetsstorage "git.coopgo.io/coopgo-platform/fleets/storage"
mobilityaccountsstorage "git.coopgo.io/coopgo-platform/mobility-accounts/storage" mobilityaccountsstorage "git.coopgo.io/coopgo-platform/mobility-accounts/storage"
) )
@@ -15,7 +14,6 @@ type BeneficiariesListState struct {
Count int `json:"count"` Count int `json:"count"`
CacheId string `json:"cache_id"` CacheId string `json:"cache_id"`
Beneficiaries []mobilityaccountsstorage.Account `json:"beneficiaries"` Beneficiaries []mobilityaccountsstorage.Account `json:"beneficiaries"`
Archived bool `json:"archived"`
} }
func (s BeneficiariesListState) JSON() template.JS { func (s BeneficiariesListState) JSON() template.JS {
@@ -30,7 +28,7 @@ func (s BeneficiariesListState) JSONWithLimits(a int, b int) template.JS {
return s.JSON() return s.JSON()
} }
func (renderer *Renderer) BeneficiariesList(w http.ResponseWriter, r *http.Request, accounts []mobilityaccountsstorage.Account, cacheid string, archived bool) { func (renderer *Renderer) BeneficiariesList(w http.ResponseWriter, r *http.Request, accounts []mobilityaccountsstorage.Account, cacheid string) {
files := renderer.ThemeConfig.GetStringSlice("views.beneficiaries.list.files") files := renderer.ThemeConfig.GetStringSlice("views.beneficiaries.list.files")
state := NewState(r, renderer.ThemeConfig, beneficiariesMenu) state := NewState(r, renderer.ThemeConfig, beneficiariesMenu)
@@ -38,7 +36,6 @@ func (renderer *Renderer) BeneficiariesList(w http.ResponseWriter, r *http.Reque
Count: len(accounts), Count: len(accounts),
CacheId: cacheid, CacheId: cacheid,
Beneficiaries: accounts, Beneficiaries: accounts,
Archived: archived,
} }
renderer.Render("beneficiaries_list", w, r, files, state) renderer.Render("beneficiaries_list", w, r, files, state)
@@ -46,12 +43,7 @@ func (renderer *Renderer) BeneficiariesList(w http.ResponseWriter, r *http.Reque
func (renderer *Renderer) BeneficiaryCreate(w http.ResponseWriter, r *http.Request) { func (renderer *Renderer) BeneficiaryCreate(w http.ResponseWriter, r *http.Request) {
files := renderer.ThemeConfig.GetStringSlice("views.beneficiaries.create.files") files := renderer.ThemeConfig.GetStringSlice("views.beneficiaries.create.files")
profileFields := renderer.GlobalConfig.Get("modules.beneficiaries.profile_optional_fields")
state := NewState(r, renderer.ThemeConfig, beneficiariesMenu) state := NewState(r, renderer.ThemeConfig, beneficiariesMenu)
state.ViewState = map[string]any{
"profile_optional_fields": profileFields,
}
renderer.Render("beneficiaries_create", w, r, files, state) renderer.Render("beneficiaries_create", w, r, files, state)
} }
@@ -60,10 +52,8 @@ type BeneficiariesDisplayState struct {
Beneficiary any 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{}, solidarityTransportStats any, solidarityTransportBookings any, solidarityDriversMap any, organizedCarpoolStats any, organizedCarpoolBookings any, organizedCarpoolDriversMap any, walletBalance float64, tab string) { func (renderer *Renderer) BeneficiaryDisplay(w http.ResponseWriter, r *http.Request, beneficiary any, bookings []any, organizations []any, beneficiaries_file_types []string, file_types_map map[string]string, documents any) {
files := renderer.ThemeConfig.GetStringSlice("views.beneficiaries.display.files") files := renderer.ThemeConfig.GetStringSlice("views.beneficiaries.display.files")
profileFields := renderer.GlobalConfig.Get("modules.beneficiaries.profile_optional_fields")
state := NewState(r, renderer.ThemeConfig, beneficiariesMenu) state := NewState(r, renderer.ThemeConfig, beneficiariesMenu)
state.ViewState = map[string]any{ state.ViewState = map[string]any{
"beneficiary": beneficiary, "beneficiary": beneficiary,
@@ -72,30 +62,15 @@ func (renderer *Renderer) BeneficiaryDisplay(w http.ResponseWriter, r *http.Requ
"file_types_map": file_types_map, "file_types_map": file_types_map,
"documents": documents, "documents": documents,
"organizations": organizations, "organizations": organizations,
"event": event,
"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) renderer.Render("beneficiaries_display", w, r, files, state)
} }
func (renderer *Renderer) BeneficiaryUpdate(w http.ResponseWriter, r *http.Request, beneficiary any) { func (renderer *Renderer) BeneficiaryUpdate(w http.ResponseWriter, r *http.Request, beneficiary any) {
files := renderer.ThemeConfig.GetStringSlice("views.beneficiaries.update.files") files := renderer.ThemeConfig.GetStringSlice("views.beneficiaries.update.files")
profileFields := renderer.GlobalConfig.Get("modules.beneficiaries.profile_optional_fields")
state := NewState(r, renderer.ThemeConfig, beneficiariesMenu) state := NewState(r, renderer.ThemeConfig, beneficiariesMenu)
state.ViewState = map[string]any{ state.ViewState = beneficiary
"beneficiary": beneficiary,
"profile_optional_fields": profileFields,
}
renderer.Render("beneficiaries_update", w, r, files, state) renderer.Render("beneficiaries_update", w, r, files, state)
} }

12
renderer/dashboard.go Executable file → Normal file
View File

@@ -4,13 +4,11 @@ import (
"net/http" "net/http"
agendastorage "git.coopgo.io/coopgo-platform/agenda/storage" 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" 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, solidarityDrivers []mobilityaccountsstorage.Account, organizedCarpoolDrivers []mobilityaccountsstorage.Account, driverAddressGeo string, enrichedGeoFilters []map[string]string) { func (renderer *Renderer) Dashboard(w http.ResponseWriter, r *http.Request, accounts []any, nbaccounts int, count_members int, events []agendastorage.Event) {
files := renderer.ThemeConfig.GetStringSlice("views.dashboard.files") files := renderer.ThemeConfig.GetStringSlice("views.dashboard.files")
state := NewState(r, renderer.ThemeConfig, dashboardMenu) state := NewState(r, renderer.ThemeConfig, dashboardMenu)
state.ViewState = map[string]any{ state.ViewState = map[string]any{
@@ -20,14 +18,6 @@ func (renderer *Renderer) Dashboard(w http.ResponseWriter, r *http.Request, acco
}, },
"count_members": count_members, "count_members": count_members,
"events": events, "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) renderer.Render("dashboard", w, r, files, state)

0
renderer/directory.go Executable file → Normal file
View File

136
renderer/func-maps.go Executable file → Normal file
View File

@@ -5,51 +5,22 @@ import (
"encoding/json" "encoding/json"
"fmt" "fmt"
"html/template" "html/template"
"math"
"reflect"
"strings" "strings"
"time" "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" "gitlab.scity.coop/maas/navitia-golang/types"
) )
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 { func TimeFrom(d any) *time.Time {
paris, err := time.LoadLocation("Europe/Paris")
if date, ok := d.(time.Time); ok { if date, ok := d.(time.Time); ok {
if err != nil {
return &date return &date
}
nd := date.In(paris)
return &nd
} else if date, ok := d.(string); ok { } else if date, ok := d.(string); ok {
datetime, err := time.Parse("2006-01-02T15:04:05Z", date) datetime, err := time.Parse("2006-01-02T15:04:05Z", date)
if err != nil { if err != nil {
datetime, err = time.Parse("2006-01-02", date) panic(err)
if err != nil {
log.Error().Err(err).Msg("cannot parse date")
} }
} return &datetime
dt := datetime.In(paris)
return &dt
} }
return nil return nil
} }
@@ -107,6 +78,7 @@ func RawJSON(v any) string {
return "" return ""
} }
return strings.TrimSuffix(buf.String(), "\n") return strings.TrimSuffix(buf.String(), "\n")
} }
func UnescapeHTML(s string) template.HTML { func UnescapeHTML(s string) template.HTML {
@@ -152,106 +124,6 @@ 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 { func Divide[V int | float64](a, b V) V {
return a / b 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
}

0
renderer/group.go Executable file → Normal file
View File

0
renderer/group_module.go Executable file → Normal file
View File

44
renderer/journeys.go Executable file → Normal file
View File

@@ -7,7 +7,6 @@ import (
groupstorage "git.coopgo.io/coopgo-platform/groups-management/storage" groupstorage "git.coopgo.io/coopgo-platform/groups-management/storage"
mobilityaccountsstorage "git.coopgo.io/coopgo-platform/mobility-accounts/storage" mobilityaccountsstorage "git.coopgo.io/coopgo-platform/mobility-accounts/storage"
geojson "github.com/paulmach/orb/geojson"
) )
const journeysMenu = "journeys" const journeysMenu = "journeys"
@@ -36,10 +35,9 @@ func (s BeneficiariesCovoiturage) JSONWithLimits(a int, b int) template.JS {
return s.JSON() return s.JSON()
} }
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) { 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) {
files := renderer.ThemeConfig.GetStringSlice("views.journeys.search.files") files := renderer.ThemeConfig.GetStringSlice("views.journeys.search.files")
state := NewState(r, renderer.ThemeConfig, journeysMenu) state := NewState(r, renderer.ThemeConfig, journeysMenu)
journeyTabs := renderer.ThemeConfig.Get("journey_tabs")
state.ViewState = map[string]any{ state.ViewState = map[string]any{
"searched": searched, "searched": searched,
"departuredate": departuredate, "departuredate": departuredate,
@@ -48,18 +46,7 @@ func (renderer *Renderer) JourneysSearch(w http.ResponseWriter, r *http.Request,
"destination": destination, "destination": destination,
"journeys": transitjourneys, "journeys": transitjourneys,
"carpools": carpools, "carpools": carpools,
"organized_carpools": organizedCarpools,
"vehicles": vehicles, "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) renderer.Render("journeys", w, r, files, state)
@@ -82,7 +69,6 @@ func (s BeneficiariesListstate) JSONWithLimits(a int, b int) template.JS {
} }
return s.JSON() return s.JSON()
} }
func (renderer *Renderer) GroupsGestion(w http.ResponseWriter, r *http.Request, groups []groupstorage.Group, cacheid string) { func (renderer *Renderer) GroupsGestion(w http.ResponseWriter, r *http.Request, groups []groupstorage.Group, cacheid string) {
files := renderer.ThemeConfig.GetStringSlice("views.journeys.list.files") files := renderer.ThemeConfig.GetStringSlice("views.journeys.list.files")
state := NewState(r, renderer.ThemeConfig, journeysMenu) state := NewState(r, renderer.ThemeConfig, journeysMenu)
@@ -112,6 +98,7 @@ func (renderer *Renderer) CreateGroup(w http.ResponseWriter, r *http.Request, de
viewstate["search"] = map[string]any{ viewstate["search"] = map[string]any{
"beneficiary": beneficiary, "beneficiary": beneficiary,
} }
} }
state.ViewState = viewstate state.ViewState = viewstate
@@ -143,6 +130,7 @@ func (renderer *Renderer) DisplayGroupCovoiturage(w http.ResponseWriter, r *http
viewstate["search"] = map[string]any{ viewstate["search"] = map[string]any{
"beneficiary": beneficiary, "beneficiary": beneficiary,
} }
} }
state.ViewState = viewstate state.ViewState = viewstate
@@ -158,29 +146,5 @@ func (renderer *Renderer) UpdateGroupCovoiturage(w http.ResponseWriter, r *http.
"memberid": memberid, "memberid": memberid,
} }
renderer.Render("journeys", w, r, files, state) 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)
} }

5
renderer/layout.go Executable file → Normal file
View File

@@ -2,14 +2,9 @@ package renderer
type LayoutState struct { type LayoutState struct {
AdministrationState AdministrationState AdministrationState AdministrationState
Menu any
ActiveMenu string
// DEPRECATED
MenuItems []MenuItem MenuItems []MenuItem
} }
// DEPRECATED
type MenuItem struct { type MenuItem struct {
Title string Title string
Link string Link string

0
renderer/mailer.go Executable file → Normal file
View File

10
renderer/members.go Executable file → Normal file
View File

@@ -12,26 +12,19 @@ const membersMenu = "members"
func (renderer *Renderer) MemberDisplay(w http.ResponseWriter, r *http.Request, admins any, groups []string) { func (renderer *Renderer) MemberDisplay(w http.ResponseWriter, r *http.Request, admins any, groups []string) {
files := renderer.ThemeConfig.GetStringSlice("views.members.display.files") files := renderer.ThemeConfig.GetStringSlice("views.members.display.files")
profileFields := renderer.GlobalConfig.Get("modules.members.profile_optional_fields")
state := NewState(r, renderer.ThemeConfig, membersMenu) state := NewState(r, renderer.ThemeConfig, membersMenu)
state.ViewState = map[string]any{ state.ViewState = map[string]any{
"admins": admins, "admins": admins,
"groups": groups, "groups": groups,
"profile_optional_fields": profileFields,
} }
renderer.Render("members_list", w, r, files, state) renderer.Render("members_list", w, r, files, state)
} }
func (renderer *Renderer) MemberUpdate(w http.ResponseWriter, r *http.Request, user any) { func (renderer *Renderer) MemberUpdate(w http.ResponseWriter, r *http.Request, user any) {
files := renderer.ThemeConfig.GetStringSlice("views.members.update.files") files := renderer.ThemeConfig.GetStringSlice("views.members.update.files")
profileFields := renderer.GlobalConfig.Get("modules.members.profile_optional_fields")
state := NewState(r, renderer.ThemeConfig, membersMenu) state := NewState(r, renderer.ThemeConfig, membersMenu)
state.ViewState = map[string]any{ state.ViewState = user
"user": user,
"profile_optional_fields": profileFields,
}
renderer.Render("members_update", w, r, files, state) renderer.Render("members_update", w, r, files, state)
} }
@@ -60,6 +53,7 @@ func (renderer *Renderer) MembersList(w http.ResponseWriter, r *http.Request, ac
state := NewState(r, renderer.ThemeConfig, membersMenu) state := NewState(r, renderer.ThemeConfig, membersMenu)
state.ViewState = map[string]any{ state.ViewState = map[string]any{
"list": MembersListState{ "list": MembersListState{
Count: len(accounts), Count: len(accounts),
CacheId: cacheid, CacheId: cacheid,

View File

@@ -1,110 +0,0 @@
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)
}

76
renderer/renderer.go Executable file → Normal file
View File

@@ -5,14 +5,11 @@ import (
"html/template" "html/template"
"net/http" "net/http"
"git.coopgo.io/coopgo-apps/parcoursmob/core/utils/icons" "git.coopgo.io/coopgo-apps/parcoursmob/utils/icons"
"git.coopgo.io/coopgo-apps/parcoursmob/core/utils/identification" "git.coopgo.io/coopgo-apps/parcoursmob/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/emailing"
"git.coopgo.io/coopgo-platform/groups-management/storage" "git.coopgo.io/coopgo-platform/groups-management/storage"
"github.com/coreos/go-oidc/v3/oidc" "github.com/coreos/go-oidc"
"github.com/rs/zerolog/log"
"github.com/spf13/viper" "github.com/spf13/viper"
) )
@@ -21,11 +18,9 @@ type Renderer struct {
GlobalConfig *viper.Viper GlobalConfig *viper.Viper
ThemeConfig *viper.Viper ThemeConfig *viper.Viper
Mailer *emailing.Mailer Mailer *emailing.Mailer
FileStorage cache.FileStorage
XLSX *xlsxrenderer.XLSXRenderer
} }
func NewRenderer(global *viper.Viper, templates_dir string, filestorage cache.FileStorage) *Renderer { func NewRenderer(global *viper.Viper, templates_dir string) *Renderer {
theme := viper.New() theme := viper.New()
theme.SetConfigName("config") theme.SetConfigName("config")
theme.AddConfigPath(templates_dir) theme.AddConfigPath(templates_dir)
@@ -37,12 +32,11 @@ func NewRenderer(global *viper.Viper, templates_dir string, filestorage cache.Fi
TemplatesDir: templates_dir, TemplatesDir: templates_dir,
GlobalConfig: global, GlobalConfig: global,
ThemeConfig: theme, ThemeConfig: theme,
FileStorage: filestorage,
XLSX: xlsxrenderer.NewXLSXRenderer(global),
} }
} }
func (renderer *Renderer) Render(name string, w http.ResponseWriter, r *http.Request, files []string, state RenderState) { func (renderer *Renderer) Render(name string, w http.ResponseWriter, r *http.Request, files []string, state RenderState) {
genericFiles := renderer.ThemeConfig.GetStringSlice("views.generic.files") genericFiles := renderer.ThemeConfig.GetStringSlice("views.generic.files")
prefixed_files := []string{} prefixed_files := []string{}
@@ -54,28 +48,54 @@ func (renderer *Renderer) Render(name string, w http.ResponseWriter, r *http.Req
} }
w.WriteHeader(http.StatusOK) w.WriteHeader(http.StatusOK)
t := template.New(name).Funcs(GetTemplateFuncMap(state.Group, renderer.GlobalConfig, renderer.FileStorage)) 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.Must(t.ParseFiles(prefixed_files...)) t = template.Must(t.ParseFiles(prefixed_files...))
err := t.ExecuteTemplate(w, "main", state) err := t.ExecuteTemplate(w, "main", state)
if err != nil { if err != nil {
log.Error().Err(err).Msg("issue executing template") fmt.Println(err)
} }
} }
func (renderer *Renderer) RenderNoLayout(name string, w http.ResponseWriter, r *http.Request, files []string, state RenderState) { func (renderer *Renderer) RenderNoLayout(name string, w http.ResponseWriter, r *http.Request, files []string, state RenderState) {
prefixed_files := []string{} prefixed_files := []string{}
for _, f := range files { for _, f := range files {
prefixed_files = append(prefixed_files, renderer.templateFile(f)) prefixed_files = append(prefixed_files, renderer.templateFile(f))
} }
w.WriteHeader(http.StatusOK) w.WriteHeader(http.StatusOK)
t := template.New(name).Funcs(GetTemplateFuncMap(state.Group, renderer.GlobalConfig, renderer.FileStorage)) 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.Must(t.ParseFiles(prefixed_files...)) t = template.Must(t.ParseFiles(prefixed_files...))
err := t.ExecuteTemplate(w, "main", state) err := t.ExecuteTemplate(w, "main", state)
if err != nil { if err != nil {
log.Error().Err(err).Msg("issue executing template") fmt.Println(err)
} }
} }
@@ -95,7 +115,6 @@ type RenderState struct {
func NewState(r *http.Request, themeConfig *viper.Viper, menuState string) RenderState { func NewState(r *http.Request, themeConfig *viper.Viper, menuState string) RenderState {
iconset := themeConfig.GetStringMapString("icons.svg") iconset := themeConfig.GetStringMapString("icons.svg")
menu := themeConfig.Get("menu_items")
// Get State elements from Request // Get State elements from Request
var userid string var userid string
@@ -141,10 +160,6 @@ func NewState(r *http.Request, themeConfig *viper.Viper, menuState string) Rende
Active: menuState == administrationMenu, Active: menuState == administrationMenu,
}, },
Menu: menu,
ActiveMenu: menuState,
// DEPRECATED
MenuItems: []MenuItem{ MenuItems: []MenuItem{
{ {
Title: "Tableau de bord", Title: "Tableau de bord",
@@ -155,7 +170,6 @@ func NewState(r *http.Request, themeConfig *viper.Viper, menuState string) Rende
}, },
} }
// DEPRECATED
if modules["beneficiaries"] != nil && modules["beneficiaries"].(bool) { if modules["beneficiaries"] != nil && modules["beneficiaries"].(bool) {
ls.MenuItems = append(ls.MenuItems, MenuItem{ ls.MenuItems = append(ls.MenuItems, MenuItem{
Title: "Bénéficiaires", Title: "Bénéficiaires",
@@ -174,15 +188,6 @@ 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) { if modules["vehicles"] != nil && modules["vehicles"].(bool) {
ls.MenuItems = append(ls.MenuItems, MenuItem{ ls.MenuItems = append(ls.MenuItems, MenuItem{
Title: "Véhicules partagés", Title: "Véhicules partagés",
@@ -217,6 +222,7 @@ func NewState(r *http.Request, themeConfig *viper.Viper, menuState string) Rende
Active: menuState == groupMenu, Active: menuState == groupMenu,
Icon: "hero:outline/group_module", Icon: "hero:outline/group_module",
}) })
} }
if modules["support"] != nil && modules["support"].(bool) { if modules["support"] != nil && modules["support"].(bool) {
@@ -226,6 +232,7 @@ func NewState(r *http.Request, themeConfig *viper.Viper, menuState string) Rende
Active: menuState == commentMenu, Active: menuState == commentMenu,
Icon: "hero:outline/support", Icon: "hero:outline/support",
}) })
} }
if modules["directory"] != nil && modules["directory"].(bool) { if modules["directory"] != nil && modules["directory"].(bool) {
@@ -236,7 +243,14 @@ func NewState(r *http.Request, themeConfig *viper.Viper, menuState string) Rende
Icon: "hero:outline/document-text", 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",
})
}
return RenderState{ return RenderState{
IconSet: icons.NewIconSet(iconset), IconSet: icons.NewIconSet(iconset),
Group: group, Group: group,

View File

@@ -1,16 +0,0 @@
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)
}

View File

@@ -1,130 +0,0 @@
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)
}

0
renderer/support.go Executable file → Normal file
View File

25
renderer/vehicle-management.go Executable file → Normal file
View File

@@ -3,35 +3,31 @@ package renderer
import ( import (
"net/http" "net/http"
filestorage "git.coopgo.io/coopgo-apps/parcoursmob/core/utils/storage" filestorage "git.coopgo.io/coopgo-apps/parcoursmob/utils/storage"
fleetsstorage "git.coopgo.io/coopgo-platform/fleets/storage" fleetsstorage "git.coopgo.io/coopgo-platform/fleets/storage"
mobilityaccountsstorage "git.coopgo.io/coopgo-platform/mobility-accounts/storage"
) )
const vehiclesmanagementMenu = "vehicles_management" const vehiclesmanagementMenu = "vehicles_management"
func (renderer *Renderer) VehiclesManagementOverview(w http.ResponseWriter, r *http.Request, vehicles []fleetsstorage.Vehicle, vehicles_map map[string]fleetsstorage.Vehicle, driversMap map[string]mobilityaccountsstorage.Account, bookings []fleetsstorage.Booking) { func (renderer *Renderer) VehiclesManagementOverview(w http.ResponseWriter, r *http.Request, vehicles []fleetsstorage.Vehicle, vehicles_map map[string]fleetsstorage.Vehicle, bookings []fleetsstorage.Booking) {
files := renderer.ThemeConfig.GetStringSlice("views.vehicles_management.overview.files") files := renderer.ThemeConfig.GetStringSlice("views.vehicles_management.overview.files")
state := NewState(r, renderer.ThemeConfig, vehiclesmanagementMenu) state := NewState(r, renderer.ThemeConfig, vehiclesmanagementMenu)
state.ViewState = map[string]any{ state.ViewState = map[string]any{
"vehicles": vehicles, "vehicles": vehicles,
"bookings": bookings, "bookings": bookings,
"vehicles_map": vehicles_map, "vehicles_map": vehicles_map,
"drivers_map": driversMap,
} }
renderer.Render("fleet overview", w, r, files, state) 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, filters map[string]string) { func (renderer *Renderer) VehiclesManagementBookingsList(w http.ResponseWriter, r *http.Request, vehicles_map map[string]fleetsstorage.Vehicle, bookings []fleetsstorage.Booking, cacheid string) {
files := renderer.ThemeConfig.GetStringSlice("views.vehicles_management.bookings_list.files") files := renderer.ThemeConfig.GetStringSlice("views.vehicles_management.bookings_list.files")
state := NewState(r, renderer.ThemeConfig, vehiclesmanagementMenu) state := NewState(r, renderer.ThemeConfig, vehiclesmanagementMenu)
state.ViewState = map[string]any{ state.ViewState = map[string]any{
"bookings": bookings, "bookings": bookings,
"vehicles_map": vehiclesMap, "vehicles_map": vehicles_map,
"drivers_map": driversMap,
"cacheid": cacheid, "cacheid": cacheid,
"filters": filters,
} }
renderer.Render("fleet overview", w, r, files, state) renderer.Render("fleet overview", w, r, files, state)
@@ -39,26 +35,19 @@ func (renderer *Renderer) VehiclesManagementBookingsList(w http.ResponseWriter,
func (renderer *Renderer) VehiclesFleetAdd(w http.ResponseWriter, r *http.Request, vehicle_types []string) { func (renderer *Renderer) VehiclesFleetAdd(w http.ResponseWriter, r *http.Request, vehicle_types []string) {
files := renderer.ThemeConfig.GetStringSlice("views.vehicles_management.fleet_add.files") 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 := NewState(r, renderer.ThemeConfig, vehiclesmanagementMenu)
state.ViewState = map[string]any{ state.ViewState = map[string]any{
"vehicle_types": vehicle_types, "vehicle_types": vehicle_types,
"vehicle_optional_fields": vehicleOptionalFields,
} }
renderer.Render("fleet add vehicle", w, r, files, state) renderer.Render("fleet add vehicle", w, r, files, state)
} }
func (renderer *Renderer) VehiclesFleetDisplay(w http.ResponseWriter, r *http.Request, vehicle any, beneficiaries any) { func (renderer *Renderer) VehiclesFleetDisplay(w http.ResponseWriter, r *http.Request, vehicle any) {
files := renderer.ThemeConfig.GetStringSlice("views.vehicles_management.fleet_display.files") 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 := NewState(r, renderer.ThemeConfig, vehiclesmanagementMenu)
state.ViewState = map[string]any{ state.ViewState = map[string]any{
"vehicle": vehicle, "vehicle": vehicle,
"beneficiaries": beneficiaries,
"vehicle_optional_fields": vehicleOptionalFields,
} }
renderer.Render("fleet display vehicle", w, r, files, state) renderer.Render("fleet display vehicle", w, r, files, state)
@@ -66,13 +55,10 @@ 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) { 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") 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 := NewState(r, renderer.ThemeConfig, vehiclesmanagementMenu)
state.ViewState = map[string]any{ state.ViewState = map[string]any{
"vehicle": vehicle, "vehicle": vehicle,
"vehicle_types": vehicle_types, "vehicle_types": vehicle_types,
"vehicle_optional_fields": vehicleOptionalFields,
} }
renderer.Render("fleet display vehicle", w, r, files, state) renderer.Render("fleet display vehicle", w, r, files, state)
@@ -102,4 +88,5 @@ func (renderer *Renderer) UnbookingVehicle(w http.ResponseWriter, r *http.Reques
} }
renderer.Render("vehicule unbooking", w, r, files, state) renderer.Render("vehicule unbooking", w, r, files, state)
} }

5
renderer/vehicles.go Executable file → Normal file
View File

@@ -3,9 +3,8 @@ package renderer
import ( import (
"net/http" "net/http"
filestorage "git.coopgo.io/coopgo-apps/parcoursmob/core/utils/storage" filestorage "git.coopgo.io/coopgo-apps/parcoursmob/utils/storage"
"git.coopgo.io/coopgo-platform/fleets/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" mobilityaccountsstorage "git.coopgo.io/coopgo-platform/mobility-accounts/storage"
) )
@@ -23,7 +22,7 @@ func selectDocumentsDefaults(beneficiarydocuments []filestorage.FileInfo, mandat
return res return res
} }
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) { 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) {
files := renderer.ThemeConfig.GetStringSlice("views.vehicles.search.files") files := renderer.ThemeConfig.GetStringSlice("views.vehicles.search.files")
state := NewState(r, renderer.ThemeConfig, vehiclesMenu) state := NewState(r, renderer.ThemeConfig, vehiclesMenu)
viewstate := map[string]any{ viewstate := map[string]any{

View File

@@ -1,273 +0,0 @@
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
}
}

View File

@@ -1,332 +0,0 @@
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
}
}

View File

@@ -1,350 +0,0 @@
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
}
}

View File

@@ -1,60 +0,0 @@
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
}

View File

@@ -1,221 +0,0 @@
# 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

View File

@@ -1,158 +0,0 @@
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 ""
}

View File

@@ -1,109 +0,0 @@
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")
}

View File

@@ -1,38 +0,0 @@
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)
}

View File

@@ -1,48 +0,0 @@
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
}

View File

@@ -1,51 +0,0 @@
package api
import (
"net/http"
"github.com/gorilla/mux"
"github.com/rs/zerolog/log"
)
func (h *Handler) 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
}
result, err := h.applicationHandler.GenerateGlobalCalendar(r.Context())
if err != nil {
log.Error().Err(err).Msg("error generating global calendar")
w.WriteHeader(http.StatusInternalServerError)
return
}
w.Header().Set("Content-Type", "text/calendar; charset=utf-8")
w.WriteHeader(http.StatusOK)
w.Write([]byte(result.CalendarData))
}
func (h *Handler) 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
}
vars := mux.Vars(r)
groupID := vars["groupid"]
result, err := h.applicationHandler.GenerateOrganizationCalendar(r.Context(), groupID)
if err != nil {
log.Error().Err(err).Msg("error generating organization calendar")
w.WriteHeader(http.StatusInternalServerError)
return
}
w.Header().Set("Content-Type", "text/calendar; charset=utf-8")
w.WriteHeader(http.StatusOK)
w.Write([]byte(result.CalendarData))
}

View File

@@ -1,31 +0,0 @@
package api
import (
"encoding/csv"
"fmt"
"net/http"
"github.com/gorilla/mux"
"github.com/rs/zerolog/log"
)
func (h *Handler) CacheExport(w http.ResponseWriter, r *http.Request) {
vars := mux.Vars(r)
cacheID := vars["cacheid"]
result, err := h.applicationHandler.ExportCacheAsCSV(cacheID)
if err != nil {
log.Error().Err(err).Msg("Error exporting cache")
w.WriteHeader(http.StatusNotFound)
return
}
w.Header().Set("Content-Type", "text/csv")
w.Header().Set("Content-Disposition", fmt.Sprintf("attachment; filename=export-%s.csv", cacheID))
csvWriter := csv.NewWriter(w)
defer csvWriter.Flush()
csvWriter.Write(result.Headers)
csvWriter.WriteAll(result.Values)
}

View File

@@ -1,31 +0,0 @@
package api
import (
"net/http"
)
func (h *Handler) GeoAutocomplete(w http.ResponseWriter, r *http.Request) {
t, ok := r.URL.Query()["text"]
if !ok || len(t[0]) < 1 {
w.WriteHeader(http.StatusBadRequest)
return
}
text := t[0]
featureCollection, err := h.geoService.Autocomplete(text)
if err != nil {
w.WriteHeader(http.StatusInternalServerError)
return
}
j, err := featureCollection.MarshalJSON()
if err != nil {
w.WriteHeader(http.StatusInternalServerError)
return
}
w.Header().Set("Content-Type", "application/json")
w.WriteHeader(http.StatusOK)
w.Write(j)
}

View File

@@ -1,42 +0,0 @@
package api
import (
"net/http"
"git.coopgo.io/coopgo-apps/parcoursmob/core/application"
"git.coopgo.io/coopgo-apps/parcoursmob/core/utils/cache"
"git.coopgo.io/coopgo-apps/parcoursmob/core/utils/geo"
"git.coopgo.io/coopgo-apps/parcoursmob/core/utils/identification"
cacheStorage "git.coopgo.io/coopgo-apps/parcoursmob/core/utils/storage"
"github.com/spf13/viper"
)
type Handler struct {
config *viper.Viper
idp *identification.IdentificationProvider
applicationHandler *application.ApplicationHandler
cacheService *cache.CacheService
geoService *geo.GeoService
}
func NewHandler(cfg *viper.Viper, idp *identification.IdentificationProvider, appHandler *application.ApplicationHandler, cacheHandler cacheStorage.CacheHandler) *Handler {
cacheService := cache.NewCacheService(cacheHandler)
// Get geocoding configuration
geoType := cfg.GetString("geo.type")
baseURL := cfg.GetString("geo." + geoType + ".url")
autocompleteEndpoint := cfg.GetString("geo." + geoType + ".autocomplete")
geoService := geo.NewGeoService(geoType, baseURL, autocompleteEndpoint)
return &Handler{
config: cfg,
idp: idp,
applicationHandler: appHandler,
cacheService: cacheService,
geoService: geoService,
}
}
func (h *Handler) NotFound(w http.ResponseWriter, r *http.Request) {
w.WriteHeader(http.StatusNotFound)
}

View File

@@ -1,26 +0,0 @@
package protected
import (
"net/http"
"git.coopgo.io/coopgo-apps/parcoursmob/core/application"
"github.com/spf13/viper"
)
type Handler struct {
apiKey string
config *viper.Viper
applicationHandler *application.ApplicationHandler
}
func NewHandler(cfg *viper.Viper, appHandler *application.ApplicationHandler) *Handler {
return &Handler{
apiKey: cfg.GetString("services.api.api_key"),
config: cfg,
applicationHandler: appHandler,
}
}
func (h *Handler) NotFound(w http.ResponseWriter, r *http.Request) {
w.WriteHeader(http.StatusNotFound)
}

View File

@@ -1,29 +0,0 @@
package protected
import (
"context"
"encoding/json"
"net/http"
"git.coopgo.io/coopgo-platform/mobility-accounts/storage"
"github.com/rs/zerolog/log"
)
func (h *Handler) RegisterUserHTTP(w http.ResponseWriter, r *http.Request) {
var user storage.Account
if err := json.NewDecoder(r.Body).Decode(&user); err != nil {
w.WriteHeader(http.StatusBadRequest)
return
}
result, err := h.applicationHandler.RegisterUser(context.Background(), user)
if err != nil {
log.Error().Err(err).Msg("Failed to register user")
w.WriteHeader(http.StatusInternalServerError)
return
}
w.Header().Set("Content-Type", "application/json")
w.WriteHeader(http.StatusOK)
json.NewEncoder(w).Encode(result)
}

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