Publication initiale de RelaisSMS : documentation et sources nettoyees
This commit is contained in:
@@ -0,0 +1,18 @@
|
|||||||
|
root = true
|
||||||
|
|
||||||
|
[*]
|
||||||
|
charset = utf-8
|
||||||
|
end_of_line = lf
|
||||||
|
indent_size = 4
|
||||||
|
indent_style = space
|
||||||
|
insert_final_newline = true
|
||||||
|
trim_trailing_whitespace = true
|
||||||
|
|
||||||
|
[*.md]
|
||||||
|
trim_trailing_whitespace = false
|
||||||
|
|
||||||
|
[*.{yml,yaml}]
|
||||||
|
indent_size = 2
|
||||||
|
|
||||||
|
[{compose,docker-compose}.{yml,yaml}]
|
||||||
|
indent_size = 4
|
||||||
+107
@@ -0,0 +1,107 @@
|
|||||||
|
APP_NAME=RelaisSMS
|
||||||
|
APP_ENV=local
|
||||||
|
APP_KEY=
|
||||||
|
APP_DEBUG=true
|
||||||
|
APP_URL=http://localhost
|
||||||
|
|
||||||
|
APP_LOCALE=fr
|
||||||
|
APP_FALLBACK_LOCALE=fr
|
||||||
|
APP_FAKER_LOCALE=fr_FR
|
||||||
|
|
||||||
|
APP_MAINTENANCE_DRIVER=file
|
||||||
|
# APP_MAINTENANCE_STORE=database
|
||||||
|
|
||||||
|
# PHP_CLI_SERVER_WORKERS=4
|
||||||
|
|
||||||
|
BCRYPT_ROUNDS=12
|
||||||
|
|
||||||
|
LOG_CHANNEL=stack
|
||||||
|
LOG_STACK=single
|
||||||
|
LOG_DEPRECATIONS_CHANNEL=null
|
||||||
|
LOG_LEVEL=debug
|
||||||
|
|
||||||
|
DB_CONNECTION=sqlite
|
||||||
|
# DB_HOST=127.0.0.1
|
||||||
|
# DB_PORT=3306
|
||||||
|
# DB_DATABASE=laravel
|
||||||
|
# DB_USERNAME=root
|
||||||
|
# DB_PASSWORD=
|
||||||
|
|
||||||
|
SESSION_DRIVER=database
|
||||||
|
SESSION_LIFETIME=120
|
||||||
|
SESSION_ENCRYPT=false
|
||||||
|
SESSION_PATH=/
|
||||||
|
SESSION_DOMAIN=null
|
||||||
|
|
||||||
|
BROADCAST_CONNECTION=log
|
||||||
|
FILESYSTEM_DISK=local
|
||||||
|
QUEUE_CONNECTION=database
|
||||||
|
|
||||||
|
CACHE_STORE=database
|
||||||
|
# CACHE_PREFIX=
|
||||||
|
|
||||||
|
MEMCACHED_HOST=127.0.0.1
|
||||||
|
|
||||||
|
REDIS_CLIENT=phpredis
|
||||||
|
REDIS_HOST=127.0.0.1
|
||||||
|
REDIS_PASSWORD=null
|
||||||
|
REDIS_PORT=6379
|
||||||
|
|
||||||
|
MAIL_MAILER=log
|
||||||
|
MAIL_SCHEME=null
|
||||||
|
MAIL_HOST=127.0.0.1
|
||||||
|
MAIL_PORT=2525
|
||||||
|
MAIL_USERNAME=null
|
||||||
|
MAIL_PASSWORD=null
|
||||||
|
MAIL_FROM_ADDRESS="hello@example.com"
|
||||||
|
MAIL_FROM_NAME="${APP_NAME}"
|
||||||
|
|
||||||
|
AWS_ACCESS_KEY_ID=
|
||||||
|
AWS_SECRET_ACCESS_KEY=
|
||||||
|
AWS_DEFAULT_REGION=us-east-1
|
||||||
|
AWS_BUCKET=
|
||||||
|
AWS_USE_PATH_STYLE_ENDPOINT=false
|
||||||
|
|
||||||
|
VITE_APP_NAME="${APP_NAME}"
|
||||||
|
|
||||||
|
RELAIS_SMS_ADMIN_NAME="Administrateur RelaisSMS"
|
||||||
|
RELAIS_SMS_ADMIN_EMAIL=admin@relais-sms.test
|
||||||
|
RELAIS_SMS_ADMIN_PASSWORD=relais-sms
|
||||||
|
|
||||||
|
RELAIS_SMS_DEFAULT_COUNTRY=FR
|
||||||
|
RELAIS_SMS_MAX_SMS_PER_CAMPAIGN=100
|
||||||
|
RELAIS_SMS_HISTORY_RETENTION_YEARS=3
|
||||||
|
RELAIS_SMS_SCHEDULED_SENDS_ENABLED=true
|
||||||
|
RELAIS_SMS_ACTIVE_SMS_PROVIDER=ovh
|
||||||
|
RELAIS_SMS_GALETTE_SYNC_ENABLED=false
|
||||||
|
RELAIS_SMS_CARDDAV_SYNC_ENABLED=false
|
||||||
|
RELAIS_SMS_CARDDAV_URL=
|
||||||
|
RELAIS_SMS_CARDDAV_USERNAME=
|
||||||
|
RELAIS_SMS_CARDDAV_PASSWORD=
|
||||||
|
RELAIS_SMS_CARDDAV_TIMEOUT=20
|
||||||
|
RELAIS_SMS_CALDAV_CALENDAR_SYNC_ENABLED=false
|
||||||
|
RELAIS_SMS_CALDAV_CALENDAR_URL=
|
||||||
|
RELAIS_SMS_CALDAV_CALENDAR_USERNAME=
|
||||||
|
RELAIS_SMS_CALDAV_CALENDAR_PASSWORD=
|
||||||
|
RELAIS_SMS_CALDAV_CALENDAR_TIMEOUT=20
|
||||||
|
RELAIS_SMS_CALDAV_CALENDAR_LOOKAHEAD_DAYS=90
|
||||||
|
RELAIS_SMS_CALDAV_SYNC_INTERVAL_MINUTES=60
|
||||||
|
RELAIS_SMS_CALDAV_DEFAULT_CONTACT_IDS=
|
||||||
|
RELAIS_SMS_CALDAV_DEFAULT_GROUP_IDS=
|
||||||
|
RELAIS_SMS_CALDAV_REMINDER_USER_ID=
|
||||||
|
RELAIS_SMS_CALDAV_REMINDER_HEADER=
|
||||||
|
RELAIS_SMS_CALDAV_REMINDER_FOOTER=
|
||||||
|
RELAIS_SMS_CALDAV_DESCRIPTION_MAX_LENGTH=120
|
||||||
|
RELAIS_SMS_CALDAV_TIMEZONE=Europe/Paris
|
||||||
|
|
||||||
|
OVH_ENDPOINT=ovh-eu
|
||||||
|
OVH_APPLICATION_KEY=
|
||||||
|
OVH_APPLICATION_SECRET=
|
||||||
|
OVH_CONSUMER_KEY=
|
||||||
|
OVH_SMS_SERVICE_NAME=
|
||||||
|
OVH_SMS_SENDER=
|
||||||
|
OVH_SMS_SHORT_CODE=true
|
||||||
|
OVH_SMS_NO_STOP_CLAUSE=true
|
||||||
|
OVH_SMS_STOP_CALLBACK_TOKEN=
|
||||||
|
OVH_SMS_TIMEOUT=20
|
||||||
|
OVH_SMS_SEND_TIMEOUT=60
|
||||||
@@ -0,0 +1,11 @@
|
|||||||
|
* text=auto eol=lf
|
||||||
|
|
||||||
|
*.blade.php diff=html
|
||||||
|
*.css diff=css
|
||||||
|
*.html diff=html
|
||||||
|
*.md diff=markdown
|
||||||
|
*.php diff=php
|
||||||
|
|
||||||
|
/.github export-ignore
|
||||||
|
CHANGELOG.md export-ignore
|
||||||
|
.styleci.yml export-ignore
|
||||||
+43
@@ -0,0 +1,43 @@
|
|||||||
|
*.log
|
||||||
|
.DS_Store
|
||||||
|
.env
|
||||||
|
.env.*
|
||||||
|
!.env.example
|
||||||
|
*.sqlite
|
||||||
|
*.sqlite-*
|
||||||
|
*.sqlite3
|
||||||
|
*.sqlite3-*
|
||||||
|
*.db
|
||||||
|
*.db-*
|
||||||
|
*.sql
|
||||||
|
*.sql.gz
|
||||||
|
*.pem
|
||||||
|
*.key
|
||||||
|
*.p12
|
||||||
|
*.pfx
|
||||||
|
/.git-credentials
|
||||||
|
/AGENTS.md
|
||||||
|
/backups/
|
||||||
|
/doc/tmp/
|
||||||
|
.phpactor.json
|
||||||
|
.phpunit.result.cache
|
||||||
|
/.codex
|
||||||
|
/.cursor/
|
||||||
|
/.idea
|
||||||
|
/.nova
|
||||||
|
/.phpunit.cache
|
||||||
|
/.vscode
|
||||||
|
/.zed
|
||||||
|
/auth.json
|
||||||
|
/node_modules
|
||||||
|
/public/build
|
||||||
|
/public/fonts-manifest.dev.json
|
||||||
|
/public/hot
|
||||||
|
/public/storage
|
||||||
|
/storage/*.key
|
||||||
|
/storage/pail
|
||||||
|
/vendor
|
||||||
|
_ide_helper.php
|
||||||
|
Homestead.json
|
||||||
|
Homestead.yaml
|
||||||
|
Thumbs.db
|
||||||
@@ -0,0 +1,232 @@
|
|||||||
|
GNU GENERAL PUBLIC LICENSE
|
||||||
|
Version 3, 29 June 2007
|
||||||
|
|
||||||
|
Copyright © 2007 Free Software Foundation, Inc. <https://fsf.org/>
|
||||||
|
|
||||||
|
Everyone is permitted to copy and distribute verbatim copies of this license document, but changing it is not allowed.
|
||||||
|
|
||||||
|
Preamble
|
||||||
|
|
||||||
|
The GNU General Public License is a free, copyleft license for software and other kinds of works.
|
||||||
|
|
||||||
|
The licenses for most software and other practical works are designed to take away your freedom to share and change the works. By contrast, the GNU General Public License is intended to guarantee your freedom to share and change all versions of a program--to make sure it remains free software for all its users. We, the Free Software Foundation, use the GNU General Public License for most of our software; it applies also to any other work released this way by its authors. You can apply it to your programs, too.
|
||||||
|
|
||||||
|
When we speak of free software, we are referring to freedom, not price. Our General Public Licenses are designed to make sure that you have the freedom to distribute copies of free software (and charge for them if you wish), that you receive source code or can get it if you want it, that you can change the software or use pieces of it in new free programs, and that you know you can do these things.
|
||||||
|
|
||||||
|
To protect your rights, we need to prevent others from denying you these rights or asking you to surrender the rights. Therefore, you have certain responsibilities if you distribute copies of the software, or if you modify it: responsibilities to respect the freedom of others.
|
||||||
|
|
||||||
|
For example, if you distribute copies of such a program, whether gratis or for a fee, you must pass on to the recipients the same freedoms that you received. You must make sure that they, too, receive or can get the source code. And you must show them these terms so they know their rights.
|
||||||
|
|
||||||
|
Developers that use the GNU GPL protect your rights with two steps: (1) assert copyright on the software, and (2) offer you this License giving you legal permission to copy, distribute and/or modify it.
|
||||||
|
|
||||||
|
For the developers' and authors' protection, the GPL clearly explains that there is no warranty for this free software. For both users' and authors' sake, the GPL requires that modified versions be marked as changed, so that their problems will not be attributed erroneously to authors of previous versions.
|
||||||
|
|
||||||
|
Some devices are designed to deny users access to install or run modified versions of the software inside them, although the manufacturer can do so. This is fundamentally incompatible with the aim of protecting users' freedom to change the software. The systematic pattern of such abuse occurs in the area of products for individuals to use, which is precisely where it is most unacceptable. Therefore, we have designed this version of the GPL to prohibit the practice for those products. If such problems arise substantially in other domains, we stand ready to extend this provision to those domains in future versions of the GPL, as needed to protect the freedom of users.
|
||||||
|
|
||||||
|
Finally, every program is threatened constantly by software patents. States should not allow patents to restrict development and use of software on general-purpose computers, but in those that do, we wish to avoid the special danger that patents applied to a free program could make it effectively proprietary. To prevent this, the GPL assures that patents cannot be used to render the program non-free.
|
||||||
|
|
||||||
|
The precise terms and conditions for copying, distribution and modification follow.
|
||||||
|
|
||||||
|
TERMS AND CONDITIONS
|
||||||
|
|
||||||
|
0. Definitions.
|
||||||
|
|
||||||
|
“This License” refers to version 3 of the GNU General Public License.
|
||||||
|
|
||||||
|
“Copyright” also means copyright-like laws that apply to other kinds of works, such as semiconductor masks.
|
||||||
|
|
||||||
|
“The Program” refers to any copyrightable work licensed under this License. Each licensee is addressed as “you”. “Licensees” and “recipients” may be individuals or organizations.
|
||||||
|
|
||||||
|
To “modify” a work means to copy from or adapt all or part of the work in a fashion requiring copyright permission, other than the making of an exact copy. The resulting work is called a “modified version” of the earlier work or a work “based on” the earlier work.
|
||||||
|
|
||||||
|
A “covered work” means either the unmodified Program or a work based on the Program.
|
||||||
|
|
||||||
|
To “propagate” a work means to do anything with it that, without permission, would make you directly or secondarily liable for infringement under applicable copyright law, except executing it on a computer or modifying a private copy. Propagation includes copying, distribution (with or without modification), making available to the public, and in some countries other activities as well.
|
||||||
|
|
||||||
|
To “convey” a work means any kind of propagation that enables other parties to make or receive copies. Mere interaction with a user through a computer network, with no transfer of a copy, is not conveying.
|
||||||
|
|
||||||
|
An interactive user interface displays “Appropriate Legal Notices” to the extent that it includes a convenient and prominently visible feature that (1) displays an appropriate copyright notice, and (2) tells the user that there is no warranty for the work (except to the extent that warranties are provided), that licensees may convey the work under this License, and how to view a copy of this License. If the interface presents a list of user commands or options, such as a menu, a prominent item in the list meets this criterion.
|
||||||
|
|
||||||
|
1. Source Code.
|
||||||
|
The “source code” for a work means the preferred form of the work for making modifications to it. “Object code” means any non-source form of a work.
|
||||||
|
|
||||||
|
A “Standard Interface” means an interface that either is an official standard defined by a recognized standards body, or, in the case of interfaces specified for a particular programming language, one that is widely used among developers working in that language.
|
||||||
|
|
||||||
|
The “System Libraries” of an executable work include anything, other than the work as a whole, that (a) is included in the normal form of packaging a Major Component, but which is not part of that Major Component, and (b) serves only to enable use of the work with that Major Component, or to implement a Standard Interface for which an implementation is available to the public in source code form. A “Major Component”, in this context, means a major essential component (kernel, window system, and so on) of the specific operating system (if any) on which the executable work runs, or a compiler used to produce the work, or an object code interpreter used to run it.
|
||||||
|
|
||||||
|
The “Corresponding Source” for a work in object code form means all the source code needed to generate, install, and (for an executable work) run the object code and to modify the work, including scripts to control those activities. However, it does not include the work's System Libraries, or general-purpose tools or generally available free programs which are used unmodified in performing those activities but which are not part of the work. For example, Corresponding Source includes interface definition files associated with source files for the work, and the source code for shared libraries and dynamically linked subprograms that the work is specifically designed to require, such as by intimate data communication or control flow between those subprograms and other parts of the work.
|
||||||
|
|
||||||
|
The Corresponding Source need not include anything that users can regenerate automatically from other parts of the Corresponding Source.
|
||||||
|
|
||||||
|
The Corresponding Source for a work in source code form is that same work.
|
||||||
|
|
||||||
|
2. Basic Permissions.
|
||||||
|
All rights granted under this License are granted for the term of copyright on the Program, and are irrevocable provided the stated conditions are met. This License explicitly affirms your unlimited permission to run the unmodified Program. The output from running a covered work is covered by this License only if the output, given its content, constitutes a covered work. This License acknowledges your rights of fair use or other equivalent, as provided by copyright law.
|
||||||
|
|
||||||
|
You may make, run and propagate covered works that you do not convey, without conditions so long as your license otherwise remains in force. You may convey covered works to others for the sole purpose of having them make modifications exclusively for you, or provide you with facilities for running those works, provided that you comply with the terms of this License in conveying all material for which you do not control copyright. Those thus making or running the covered works for you must do so exclusively on your behalf, under your direction and control, on terms that prohibit them from making any copies of your copyrighted material outside their relationship with you.
|
||||||
|
|
||||||
|
Conveying under any other circumstances is permitted solely under the conditions stated below. Sublicensing is not allowed; section 10 makes it unnecessary.
|
||||||
|
|
||||||
|
3. Protecting Users' Legal Rights From Anti-Circumvention Law.
|
||||||
|
No covered work shall be deemed part of an effective technological measure under any applicable law fulfilling obligations under article 11 of the WIPO copyright treaty adopted on 20 December 1996, or similar laws prohibiting or restricting circumvention of such measures.
|
||||||
|
|
||||||
|
When you convey a covered work, you waive any legal power to forbid circumvention of technological measures to the extent such circumvention is effected by exercising rights under this License with respect to the covered work, and you disclaim any intention to limit operation or modification of the work as a means of enforcing, against the work's users, your or third parties' legal rights to forbid circumvention of technological measures.
|
||||||
|
|
||||||
|
4. Conveying Verbatim Copies.
|
||||||
|
You may convey verbatim copies of the Program's source code as you receive it, in any medium, provided that you conspicuously and appropriately publish on each copy an appropriate copyright notice; keep intact all notices stating that this License and any non-permissive terms added in accord with section 7 apply to the code; keep intact all notices of the absence of any warranty; and give all recipients a copy of this License along with the Program.
|
||||||
|
|
||||||
|
You may charge any price or no price for each copy that you convey, and you may offer support or warranty protection for a fee.
|
||||||
|
|
||||||
|
5. Conveying Modified Source Versions.
|
||||||
|
You may convey a work based on the Program, or the modifications to produce it from the Program, in the form of source code under the terms of section 4, provided that you also meet all of these conditions:
|
||||||
|
|
||||||
|
a) The work must carry prominent notices stating that you modified it, and giving a relevant date.
|
||||||
|
|
||||||
|
b) The work must carry prominent notices stating that it is released under this License and any conditions added under section 7. This requirement modifies the requirement in section 4 to “keep intact all notices”.
|
||||||
|
|
||||||
|
c) You must license the entire work, as a whole, under this License to anyone who comes into possession of a copy. This License will therefore apply, along with any applicable section 7 additional terms, to the whole of the work, and all its parts, regardless of how they are packaged. This License gives no permission to license the work in any other way, but it does not invalidate such permission if you have separately received it.
|
||||||
|
|
||||||
|
d) If the work has interactive user interfaces, each must display Appropriate Legal Notices; however, if the Program has interactive interfaces that do not display Appropriate Legal Notices, your work need not make them do so.
|
||||||
|
|
||||||
|
A compilation of a covered work with other separate and independent works, which are not by their nature extensions of the covered work, and which are not combined with it such as to form a larger program, in or on a volume of a storage or distribution medium, is called an “aggregate” if the compilation and its resulting copyright are not used to limit the access or legal rights of the compilation's users beyond what the individual works permit. Inclusion of a covered work in an aggregate does not cause this License to apply to the other parts of the aggregate.
|
||||||
|
|
||||||
|
6. Conveying Non-Source Forms.
|
||||||
|
You may convey a covered work in object code form under the terms of sections 4 and 5, provided that you also convey the machine-readable Corresponding Source under the terms of this License, in one of these ways:
|
||||||
|
|
||||||
|
a) Convey the object code in, or embodied in, a physical product (including a physical distribution medium), accompanied by the Corresponding Source fixed on a durable physical medium customarily used for software interchange.
|
||||||
|
|
||||||
|
b) Convey the object code in, or embodied in, a physical product (including a physical distribution medium), accompanied by a written offer, valid for at least three years and valid for as long as you offer spare parts or customer support for that product model, to give anyone who possesses the object code either (1) a copy of the Corresponding Source for all the software in the product that is covered by this License, on a durable physical medium customarily used for software interchange, for a price no more than your reasonable cost of physically performing this conveying of source, or (2) access to copy the Corresponding Source from a network server at no charge.
|
||||||
|
|
||||||
|
c) Convey individual copies of the object code with a copy of the written offer to provide the Corresponding Source. This alternative is allowed only occasionally and noncommercially, and only if you received the object code with such an offer, in accord with subsection 6b.
|
||||||
|
|
||||||
|
d) Convey the object code by offering access from a designated place (gratis or for a charge), and offer equivalent access to the Corresponding Source in the same way through the same place at no further charge. You need not require recipients to copy the Corresponding Source along with the object code. If the place to copy the object code is a network server, the Corresponding Source may be on a different server (operated by you or a third party) that supports equivalent copying facilities, provided you maintain clear directions next to the object code saying where to find the Corresponding Source. Regardless of what server hosts the Corresponding Source, you remain obligated to ensure that it is available for as long as needed to satisfy these requirements.
|
||||||
|
|
||||||
|
e) Convey the object code using peer-to-peer transmission, provided you inform other peers where the object code and Corresponding Source of the work are being offered to the general public at no charge under subsection 6d.
|
||||||
|
|
||||||
|
A separable portion of the object code, whose source code is excluded from the Corresponding Source as a System Library, need not be included in conveying the object code work.
|
||||||
|
|
||||||
|
A “User Product” is either (1) a “consumer product”, which means any tangible personal property which is normally used for personal, family, or household purposes, or (2) anything designed or sold for incorporation into a dwelling. In determining whether a product is a consumer product, doubtful cases shall be resolved in favor of coverage. For a particular product received by a particular user, “normally used” refers to a typical or common use of that class of product, regardless of the status of the particular user or of the way in which the particular user actually uses, or expects or is expected to use, the product. A product is a consumer product regardless of whether the product has substantial commercial, industrial or non-consumer uses, unless such uses represent the only significant mode of use of the product.
|
||||||
|
|
||||||
|
“Installation Information” for a User Product means any methods, procedures, authorization keys, or other information required to install and execute modified versions of a covered work in that User Product from a modified version of its Corresponding Source. The information must suffice to ensure that the continued functioning of the modified object code is in no case prevented or interfered with solely because modification has been made.
|
||||||
|
|
||||||
|
If you convey an object code work under this section in, or with, or specifically for use in, a User Product, and the conveying occurs as part of a transaction in which the right of possession and use of the User Product is transferred to the recipient in perpetuity or for a fixed term (regardless of how the transaction is characterized), the Corresponding Source conveyed under this section must be accompanied by the Installation Information. But this requirement does not apply if neither you nor any third party retains the ability to install modified object code on the User Product (for example, the work has been installed in ROM).
|
||||||
|
|
||||||
|
The requirement to provide Installation Information does not include a requirement to continue to provide support service, warranty, or updates for a work that has been modified or installed by the recipient, or for the User Product in which it has been modified or installed. Access to a network may be denied when the modification itself materially and adversely affects the operation of the network or violates the rules and protocols for communication across the network.
|
||||||
|
|
||||||
|
Corresponding Source conveyed, and Installation Information provided, in accord with this section must be in a format that is publicly documented (and with an implementation available to the public in source code form), and must require no special password or key for unpacking, reading or copying.
|
||||||
|
|
||||||
|
7. Additional Terms.
|
||||||
|
“Additional permissions” are terms that supplement the terms of this License by making exceptions from one or more of its conditions. Additional permissions that are applicable to the entire Program shall be treated as though they were included in this License, to the extent that they are valid under applicable law. If additional permissions apply only to part of the Program, that part may be used separately under those permissions, but the entire Program remains governed by this License without regard to the additional permissions.
|
||||||
|
|
||||||
|
When you convey a copy of a covered work, you may at your option remove any additional permissions from that copy, or from any part of it. (Additional permissions may be written to require their own removal in certain cases when you modify the work.) You may place additional permissions on material, added by you to a covered work, for which you have or can give appropriate copyright permission.
|
||||||
|
|
||||||
|
Notwithstanding any other provision of this License, for material you add to a covered work, you may (if authorized by the copyright holders of that material) supplement the terms of this License with terms:
|
||||||
|
|
||||||
|
a) Disclaiming warranty or limiting liability differently from the terms of sections 15 and 16 of this License; or
|
||||||
|
|
||||||
|
b) Requiring preservation of specified reasonable legal notices or author attributions in that material or in the Appropriate Legal Notices displayed by works containing it; or
|
||||||
|
|
||||||
|
c) Prohibiting misrepresentation of the origin of that material, or requiring that modified versions of such material be marked in reasonable ways as different from the original version; or
|
||||||
|
|
||||||
|
d) Limiting the use for publicity purposes of names of licensors or authors of the material; or
|
||||||
|
|
||||||
|
e) Declining to grant rights under trademark law for use of some trade names, trademarks, or service marks; or
|
||||||
|
|
||||||
|
f) Requiring indemnification of licensors and authors of that material by anyone who conveys the material (or modified versions of it) with contractual assumptions of liability to the recipient, for any liability that these contractual assumptions directly impose on those licensors and authors.
|
||||||
|
|
||||||
|
All other non-permissive additional terms are considered “further restrictions” within the meaning of section 10. If the Program as you received it, or any part of it, contains a notice stating that it is governed by this License along with a term that is a further restriction, you may remove that term. If a license document contains a further restriction but permits relicensing or conveying under this License, you may add to a covered work material governed by the terms of that license document, provided that the further restriction does not survive such relicensing or conveying.
|
||||||
|
|
||||||
|
If you add terms to a covered work in accord with this section, you must place, in the relevant source files, a statement of the additional terms that apply to those files, or a notice indicating where to find the applicable terms.
|
||||||
|
|
||||||
|
Additional terms, permissive or non-permissive, may be stated in the form of a separately written license, or stated as exceptions; the above requirements apply either way.
|
||||||
|
|
||||||
|
8. Termination.
|
||||||
|
You may not propagate or modify a covered work except as expressly provided under this License. Any attempt otherwise to propagate or modify it is void, and will automatically terminate your rights under this License (including any patent licenses granted under the third paragraph of section 11).
|
||||||
|
|
||||||
|
However, if you cease all violation of this License, then your license from a particular copyright holder is reinstated (a) provisionally, unless and until the copyright holder explicitly and finally terminates your license, and (b) permanently, if the copyright holder fails to notify you of the violation by some reasonable means prior to 60 days after the cessation.
|
||||||
|
|
||||||
|
Moreover, your license from a particular copyright holder is reinstated permanently if the copyright holder notifies you of the violation by some reasonable means, this is the first time you have received notice of violation of this License (for any work) from that copyright holder, and you cure the violation prior to 30 days after your receipt of the notice.
|
||||||
|
|
||||||
|
Termination of your rights under this section does not terminate the licenses of parties who have received copies or rights from you under this License. If your rights have been terminated and not permanently reinstated, you do not qualify to receive new licenses for the same material under section 10.
|
||||||
|
|
||||||
|
9. Acceptance Not Required for Having Copies.
|
||||||
|
You are not required to accept this License in order to receive or run a copy of the Program. Ancillary propagation of a covered work occurring solely as a consequence of using peer-to-peer transmission to receive a copy likewise does not require acceptance. However, nothing other than this License grants you permission to propagate or modify any covered work. These actions infringe copyright if you do not accept this License. Therefore, by modifying or propagating a covered work, you indicate your acceptance of this License to do so.
|
||||||
|
|
||||||
|
10. Automatic Licensing of Downstream Recipients.
|
||||||
|
Each time you convey a covered work, the recipient automatically receives a license from the original licensors, to run, modify and propagate that work, subject to this License. You are not responsible for enforcing compliance by third parties with this License.
|
||||||
|
|
||||||
|
An “entity transaction” is a transaction transferring control of an organization, or substantially all assets of one, or subdividing an organization, or merging organizations. If propagation of a covered work results from an entity transaction, each party to that transaction who receives a copy of the work also receives whatever licenses to the work the party's predecessor in interest had or could give under the previous paragraph, plus a right to possession of the Corresponding Source of the work from the predecessor in interest, if the predecessor has it or can get it with reasonable efforts.
|
||||||
|
|
||||||
|
You may not impose any further restrictions on the exercise of the rights granted or affirmed under this License. For example, you may not impose a license fee, royalty, or other charge for exercise of rights granted under this License, and you may not initiate litigation (including a cross-claim or counterclaim in a lawsuit) alleging that any patent claim is infringed by making, using, selling, offering for sale, or importing the Program or any portion of it.
|
||||||
|
|
||||||
|
11. Patents.
|
||||||
|
A “contributor” is a copyright holder who authorizes use under this License of the Program or a work on which the Program is based. The work thus licensed is called the contributor's “contributor version”.
|
||||||
|
|
||||||
|
A contributor's “essential patent claims” are all patent claims owned or controlled by the contributor, whether already acquired or hereafter acquired, that would be infringed by some manner, permitted by this License, of making, using, or selling its contributor version, but do not include claims that would be infringed only as a consequence of further modification of the contributor version. For purposes of this definition, “control” includes the right to grant patent sublicenses in a manner consistent with the requirements of this License.
|
||||||
|
|
||||||
|
Each contributor grants you a non-exclusive, worldwide, royalty-free patent license under the contributor's essential patent claims, to make, use, sell, offer for sale, import and otherwise run, modify and propagate the contents of its contributor version.
|
||||||
|
|
||||||
|
In the following three paragraphs, a “patent license” is any express agreement or commitment, however denominated, not to enforce a patent (such as an express permission to practice a patent or covenant not to sue for patent infringement). To “grant” such a patent license to a party means to make such an agreement or commitment not to enforce a patent against the party.
|
||||||
|
|
||||||
|
If you convey a covered work, knowingly relying on a patent license, and the Corresponding Source of the work is not available for anyone to copy, free of charge and under the terms of this License, through a publicly available network server or other readily accessible means, then you must either (1) cause the Corresponding Source to be so available, or (2) arrange to deprive yourself of the benefit of the patent license for this particular work, or (3) arrange, in a manner consistent with the requirements of this License, to extend the patent license to downstream recipients. “Knowingly relying” means you have actual knowledge that, but for the patent license, your conveying the covered work in a country, or your recipient's use of the covered work in a country, would infringe one or more identifiable patents in that country that you have reason to believe are valid.
|
||||||
|
|
||||||
|
If, pursuant to or in connection with a single transaction or arrangement, you convey, or propagate by procuring conveyance of, a covered work, and grant a patent license to some of the parties receiving the covered work authorizing them to use, propagate, modify or convey a specific copy of the covered work, then the patent license you grant is automatically extended to all recipients of the covered work and works based on it.
|
||||||
|
|
||||||
|
A patent license is “discriminatory” if it does not include within the scope of its coverage, prohibits the exercise of, or is conditioned on the non-exercise of one or more of the rights that are specifically granted under this License. You may not convey a covered work if you are a party to an arrangement with a third party that is in the business of distributing software, under which you make payment to the third party based on the extent of your activity of conveying the work, and under which the third party grants, to any of the parties who would receive the covered work from you, a discriminatory patent license (a) in connection with copies of the covered work conveyed by you (or copies made from those copies), or (b) primarily for and in connection with specific products or compilations that contain the covered work, unless you entered into that arrangement, or that patent license was granted, prior to 28 March 2007.
|
||||||
|
|
||||||
|
Nothing in this License shall be construed as excluding or limiting any implied license or other defenses to infringement that may otherwise be available to you under applicable patent law.
|
||||||
|
|
||||||
|
12. No Surrender of Others' Freedom.
|
||||||
|
If conditions are imposed on you (whether by court order, agreement or otherwise) that contradict the conditions of this License, they do not excuse you from the conditions of this License. If you cannot convey a covered work so as to satisfy simultaneously your obligations under this License and any other pertinent obligations, then as a consequence you may not convey it at all. For example, if you agree to terms that obligate you to collect a royalty for further conveying from those to whom you convey the Program, the only way you could satisfy both those terms and this License would be to refrain entirely from conveying the Program.
|
||||||
|
|
||||||
|
13. Use with the GNU Affero General Public License.
|
||||||
|
Notwithstanding any other provision of this License, you have permission to link or combine any covered work with a work licensed under version 3 of the GNU Affero General Public License into a single combined work, and to convey the resulting work. The terms of this License will continue to apply to the part which is the covered work, but the special requirements of the GNU Affero General Public License, section 13, concerning interaction through a network will apply to the combination as such.
|
||||||
|
|
||||||
|
14. Revised Versions of this License.
|
||||||
|
The Free Software Foundation may publish revised and/or new versions of the GNU General Public License from time to time. Such new versions will be similar in spirit to the present version, but may differ in detail to address new problems or concerns.
|
||||||
|
|
||||||
|
Each version is given a distinguishing version number. If the Program specifies that a certain numbered version of the GNU General Public License “or any later version” applies to it, you have the option of following the terms and conditions either of that numbered version or of any later version published by the Free Software Foundation. If the Program does not specify a version number of the GNU General Public License, you may choose any version ever published by the Free Software Foundation.
|
||||||
|
|
||||||
|
If the Program specifies that a proxy can decide which future versions of the GNU General Public License can be used, that proxy's public statement of acceptance of a version permanently authorizes you to choose that version for the Program.
|
||||||
|
|
||||||
|
Later license versions may give you additional or different permissions. However, no additional obligations are imposed on any author or copyright holder as a result of your choosing to follow a later version.
|
||||||
|
|
||||||
|
15. Disclaimer of Warranty.
|
||||||
|
THERE IS NO WARRANTY FOR THE PROGRAM, TO THE EXTENT PERMITTED BY APPLICABLE LAW. EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT HOLDERS AND/OR OTHER PARTIES PROVIDE THE PROGRAM “AS IS” WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE. THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE PROGRAM IS WITH YOU. SHOULD THE PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF ALL NECESSARY SERVICING, REPAIR OR CORRECTION.
|
||||||
|
|
||||||
|
16. Limitation of Liability.
|
||||||
|
IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MODIFIES AND/OR CONVEYS THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES, INCLUDING ANY GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED TO LOSS OF DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER PROGRAMS), EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF SUCH DAMAGES.
|
||||||
|
|
||||||
|
17. Interpretation of Sections 15 and 16.
|
||||||
|
If the disclaimer of warranty and limitation of liability provided above cannot be given local legal effect according to their terms, reviewing courts shall apply local law that most closely approximates an absolute waiver of all civil liability in connection with the Program, unless a warranty or assumption of liability accompanies a copy of the Program in return for a fee.
|
||||||
|
|
||||||
|
END OF TERMS AND CONDITIONS
|
||||||
|
|
||||||
|
How to Apply These Terms to Your New Programs
|
||||||
|
|
||||||
|
If you develop a new program, and you want it to be of the greatest possible use to the public, the best way to achieve this is to make it free software which everyone can redistribute and change under these terms.
|
||||||
|
|
||||||
|
To do so, attach the following notices to the program. It is safest to attach them to the start of each source file to most effectively state the exclusion of warranty; and each file should have at least the “copyright” line and a pointer to where the full notice is found.
|
||||||
|
|
||||||
|
RelaisSMS
|
||||||
|
Copyright (C) 2026 afpma
|
||||||
|
|
||||||
|
This program is free software: you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version.
|
||||||
|
|
||||||
|
This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details.
|
||||||
|
|
||||||
|
You should have received a copy of the GNU General Public License along with this program. If not, see <https://www.gnu.org/licenses/>.
|
||||||
|
|
||||||
|
Also add information on how to contact you by electronic and paper mail.
|
||||||
|
|
||||||
|
If the program does terminal interaction, make it output a short notice like this when it starts in an interactive mode:
|
||||||
|
|
||||||
|
RelaisSMS Copyright (C) 2026 afpma
|
||||||
|
This program comes with ABSOLUTELY NO WARRANTY; for details type `show w'.
|
||||||
|
This is free software, and you are welcome to redistribute it under certain conditions; type `show c' for details.
|
||||||
|
|
||||||
|
The hypothetical commands `show w' and `show c' should show the appropriate parts of the General Public License. Of course, your program's commands might be different; for a GUI interface, you would use an “about box”.
|
||||||
|
|
||||||
|
You should also get your employer (if you work as a programmer) or school, if any, to sign a “copyright disclaimer” for the program, if necessary. For more information on this, and how to apply and follow the GNU GPL, see <https://www.gnu.org/licenses/>.
|
||||||
|
|
||||||
|
The GNU General Public License does not permit incorporating your program into proprietary programs. If your program is a subroutine library, you may consider it more useful to permit linking proprietary applications with the library. If this is what you want to do, use the GNU Lesser General Public License instead of this License. But first, please read <https://www.gnu.org/philosophy/why-not-lgpl.html>.
|
||||||
@@ -0,0 +1,215 @@
|
|||||||
|
# RelaisSMS
|
||||||
|
|
||||||
|
**Vos contacts, votre agenda, vos SMS — au même endroit.**
|
||||||
|
|
||||||
|
RelaisSMS est une petite application web auto-hébergée qui permet d'envoyer des SMS à des contacts ou à des groupes, immédiatement ou à une date choisie. Elle relie un carnet d'adresses **CardDAV**, un agenda **CalDAV** et l'API **OVHcloud SMS** pour centraliser les notifications et automatiser les rappels de rendez-vous.
|
||||||
|
|
||||||
|
Pensée à l'origine pour les besoins d'une association, elle propose une interface en français et fonctionne avec PHP et une base SQLite. Les contacts peuvent aussi être gérés directement dans l'application, sans serveur DAV.
|
||||||
|
|
||||||
|
## Fonctionnalités
|
||||||
|
|
||||||
|
| Domaine | Ce que fait RelaisSMS |
|
||||||
|
| --- | --- |
|
||||||
|
| **Contacts** | Fiches locales ou synchronisées par CardDAV, plusieurs numéros, normalisation au format international et détection des mobiles. |
|
||||||
|
| **Groupes et favoris** | Sélection de contacts et de groupes, recherche et accès rapide aux favoris. |
|
||||||
|
| **Préparation des envois** | Aperçu des destinataires, dédoublonnage des numéros, exclusion des contacts en refus SMS et limite de destinataires configurable. |
|
||||||
|
| **Campagnes SMS** | Envoi immédiat ou programmé, annulation avant envoi, en-tête et pied de message configurables. |
|
||||||
|
| **Rappels d'agenda** | Synchronisation CalDAV, alarmes de notification, événements récurrents, exceptions et annulations. |
|
||||||
|
| **Suivi** | Historique des campagnes et de leurs destinataires, statuts détaillés, filtres et export CSV. |
|
||||||
|
| **Envois incertains** | Rapprochement avec l'historique OVH après une interruption ou un délai dépassé, sans renvoi automatique. |
|
||||||
|
| **Désinscription** | Refus SMS géré dans l'interface et prise en compte des réponses STOP via un callback OVH protégé par un jeton. |
|
||||||
|
| **Exploitation** | Commandes CLI, tâches planifiées, suivi des synchronisations et purge de l'historique selon une durée configurable. |
|
||||||
|
|
||||||
|
**Intégrations disponibles :** CardDAV et CalDAV, notamment avec Nextcloud, et OVHcloud SMS. Le connecteur Galette et les autres fournisseurs SMS restent des pistes d'évolution ; ils ne sont pas implémentés.
|
||||||
|
|
||||||
|
## Comment ça fonctionne ?
|
||||||
|
|
||||||
|
1. Ajoutez vos contacts ou synchronisez votre carnet CardDAV.
|
||||||
|
2. Sélectionnez des contacts ou des groupes et vérifiez les numéros retenus.
|
||||||
|
3. Rédigez votre message, puis envoyez-le immédiatement ou programmez-le.
|
||||||
|
4. Consultez le résultat dans l'historique et exportez-le si nécessaire.
|
||||||
|
|
||||||
|
Pour les rappels automatiques, ajoutez un événement et une alarme de type **notification** dans votre agenda CalDAV. RelaisSMS retrouve les contacts correspondant aux adresses e-mail de l'organisateur et des participants, puis prépare les SMS à l'échéance de l'alarme. Des contacts ou groupes fixes peuvent compléter cette liste.
|
||||||
|
|
||||||
|
## Stack et prérequis
|
||||||
|
|
||||||
|
- **PHP 8.3+**, Composer et les extensions Laravel usuelles, dont PDO SQLite, mbstring, OpenSSL, XML, DOM, ctype et fileinfo.
|
||||||
|
- **Laravel 13**, vues Blade et **Tailwind CSS 4**.
|
||||||
|
- **Node.js 20.19+ ou 22.12+** et npm pour construire les assets avec **Vite 8**.
|
||||||
|
- **SQLite** par défaut ; les autres connexions Laravel nécessitent leur propre configuration et validation.
|
||||||
|
- Un compte OVHcloud SMS avec des crédits et des identifiants API pour les envois réels.
|
||||||
|
- Un serveur CardDAV et/ou CalDAV si vous souhaitez utiliser les synchronisations.
|
||||||
|
|
||||||
|
## Installation locale
|
||||||
|
|
||||||
|
```bash
|
||||||
|
git clone https://git.afpma.pro/afpma/RelaisSMS.git
|
||||||
|
cd RelaisSMS
|
||||||
|
composer install
|
||||||
|
cp .env.example .env
|
||||||
|
touch database/database.sqlite
|
||||||
|
php artisan key:generate
|
||||||
|
php artisan migrate --seed
|
||||||
|
npm ci
|
||||||
|
npm run build
|
||||||
|
php artisan serve
|
||||||
|
```
|
||||||
|
|
||||||
|
Ouvrez ensuite **http://127.0.0.1:8000/login**.
|
||||||
|
|
||||||
|
Le compte de développement créé par le seeder est `admin@relais-sms.test`, avec le mot de passe `relais-sms`. Ces valeurs de démonstration sont réservées au développement. Définissez vos propres `RELAIS_SMS_ADMIN_NAME`, `RELAIS_SMS_ADMIN_EMAIL` et `RELAIS_SMS_ADMIN_PASSWORD` dans `.env` **avant toute installation accessible au public**. Le seeder refuse de créer un compte avec le mot de passe par défaut ou un mot de passe vide hors des environnements `local` et `testing`.
|
||||||
|
|
||||||
|
Le seeder ne change pas le mot de passe d'un compte déjà existant. Modifier `.env` puis relancer `db:seed` ne constitue donc pas une réinitialisation du mot de passe.
|
||||||
|
|
||||||
|
Sans identifiants OVH, l'application reste utilisable pour gérer les contacts et préparer les sélections ; les envois réels échoueront. Pour travailler sur l'interface, lancez `npm run dev` dans un second terminal. Pour exécuter les tâches planifiées localement :
|
||||||
|
|
||||||
|
```bash
|
||||||
|
php artisan schedule:work
|
||||||
|
```
|
||||||
|
|
||||||
|
Ce scheduler peut déclencher des envois si les intégrations sont configurées et si des campagnes ou rappels sont dus.
|
||||||
|
|
||||||
|
## Configuration
|
||||||
|
|
||||||
|
Le fichier [`.env.example`](.env.example) décrit les variables disponibles. Copiez-le en `.env` et renseignez vos secrets uniquement dans ce fichier, jamais dans le dépôt. Après une modification de configuration, exécutez `php artisan config:clear`.
|
||||||
|
|
||||||
|
### SMS OVHcloud
|
||||||
|
|
||||||
|
```dotenv
|
||||||
|
RELAIS_SMS_ACTIVE_SMS_PROVIDER=ovh
|
||||||
|
OVH_ENDPOINT=ovh-eu
|
||||||
|
OVH_APPLICATION_KEY=
|
||||||
|
OVH_APPLICATION_SECRET=
|
||||||
|
OVH_CONSUMER_KEY=
|
||||||
|
OVH_SMS_SERVICE_NAME=
|
||||||
|
OVH_SMS_SENDER=
|
||||||
|
OVH_SMS_SHORT_CODE=true
|
||||||
|
OVH_SMS_NO_STOP_CLAUSE=true
|
||||||
|
OVH_SMS_STOP_CALLBACK_TOKEN=
|
||||||
|
OVH_SMS_TIMEOUT=20
|
||||||
|
OVH_SMS_SEND_TIMEOUT=60
|
||||||
|
```
|
||||||
|
|
||||||
|
Renseignez les clés et le service SMS dans `.env`. Les autorisations API utilisées sont :
|
||||||
|
|
||||||
|
- `GET /sms` pour consulter les services ;
|
||||||
|
- `POST /sms/{serviceName}/jobs` pour envoyer ;
|
||||||
|
- `GET /sms/{serviceName}/outgoing` et `GET /sms/{serviceName}/outgoing/*` pour rapprocher les envois incertains.
|
||||||
|
|
||||||
|
Deux modes d'expéditeur sont proposés :
|
||||||
|
|
||||||
|
| Mode | Configuration | Comportement |
|
||||||
|
| --- | --- | --- |
|
||||||
|
| Numéro court avec réponse | `OVH_SMS_SHORT_CODE=true`, expéditeur vide | RelaisSMS retire les liens et domaines du texte envoyé. Les libellés des liens Markdown et HTML sont conservés. |
|
||||||
|
| Expéditeur personnalisé | `OVH_SMS_SHORT_CODE=false`, `OVH_SMS_SENDER` renseigné | Les liens sont conservés ; le nom d'expéditeur doit être accepté par OVH. |
|
||||||
|
|
||||||
|
Un texte devenu vide après filtrage est refusé. L'historique conserve le message effectivement transmis. `OVH_SMS_NO_STOP_CLAUSE` contrôle la demande de clause STOP auprès du fournisseur ; adaptez ce réglage à la nature de vos messages et aux conditions du service.
|
||||||
|
|
||||||
|
**Un délai dépassé ne signifie pas forcément que le SMS n'est pas parti.** Les campagnes concernées passent en « À vérifier ». La commande suivante consulte l'historique OVH sans renvoyer de SMS :
|
||||||
|
|
||||||
|
```bash
|
||||||
|
php artisan sms-campaigns:reconcile
|
||||||
|
```
|
||||||
|
|
||||||
|
Elle traite aussi les campagnes bloquées en « Envoi » depuis plus de dix minutes. Une absence de résultat ne suffit pas à déclarer l'envoi en échec. Le statut « Envoyé » indique une acceptation par OVH, pas une confirmation de livraison au téléphone.
|
||||||
|
|
||||||
|
Pour les réponses STOP, générez un jeton aléatoire dédié dans `OVH_SMS_STOP_CALLBACK_TOKEN`, puis configurez chez OVH l'URL de callback STOP :
|
||||||
|
|
||||||
|
```text
|
||||||
|
https://sms.example.org/ovh/sms/stop-callback?token=VOTRE_JETON
|
||||||
|
```
|
||||||
|
|
||||||
|
Le callback marque les contacts correspondant au numéro reçu en refus SMS. Le callback de changement d'état de livraison n'est pas implémenté.
|
||||||
|
|
||||||
|
### Carnet d'adresses CardDAV
|
||||||
|
|
||||||
|
```dotenv
|
||||||
|
RELAIS_SMS_CARDDAV_SYNC_ENABLED=true
|
||||||
|
RELAIS_SMS_CARDDAV_URL=https://cloud.example.org/remote.php/dav/addressbooks/users/UTILISATEUR/CARNET/
|
||||||
|
RELAIS_SMS_CARDDAV_USERNAME=
|
||||||
|
RELAIS_SMS_CARDDAV_PASSWORD=
|
||||||
|
```
|
||||||
|
|
||||||
|
Utilisez de préférence un mot de passe d'application DAV. Une synchronisation peut être lancée depuis l'interface ou avec `php artisan contacts:sync-carddav`. Le scheduler la prévoit toutes les heures.
|
||||||
|
|
||||||
|
### Agenda CalDAV et rappels
|
||||||
|
|
||||||
|
```dotenv
|
||||||
|
RELAIS_SMS_CALDAV_CALENDAR_SYNC_ENABLED=true
|
||||||
|
RELAIS_SMS_CALDAV_CALENDAR_URL=https://cloud.example.org/remote.php/dav/calendars/UTILISATEUR/CALENDRIER/
|
||||||
|
RELAIS_SMS_CALDAV_CALENDAR_USERNAME=
|
||||||
|
RELAIS_SMS_CALDAV_CALENDAR_PASSWORD=
|
||||||
|
RELAIS_SMS_CALDAV_CALENDAR_LOOKAHEAD_DAYS=90
|
||||||
|
RELAIS_SMS_CALDAV_SYNC_INTERVAL_MINUTES=60
|
||||||
|
RELAIS_SMS_CALDAV_DEFAULT_CONTACT_IDS=
|
||||||
|
RELAIS_SMS_CALDAV_DEFAULT_GROUP_IDS=
|
||||||
|
RELAIS_SMS_CALDAV_TIMEZONE=Europe/Paris
|
||||||
|
```
|
||||||
|
|
||||||
|
- Seules les alarmes `VALARM` avec `ACTION:DISPLAY` déclenchent un SMS. Les alarmes e-mail sont ignorées.
|
||||||
|
- L'organisateur et les participants sont rapprochés des contacts par leur adresse e-mail ; un mobile valide est nécessaire.
|
||||||
|
- Les identifiants de contacts et groupes par défaut sont séparés par des virgules.
|
||||||
|
- Les récurrences `RRULE`, les dates `RDATE`, les exclusions `EXDATE`, ainsi que les occurrences modifiées ou annulées sont prises en compte dans la fenêtre de synchronisation.
|
||||||
|
- Chaque occurrence et son alarme disposent d'une protection contre les doublons. Les rappels déjà envoyés ou incertains ne sont pas renvoyés lors d'une synchronisation.
|
||||||
|
- Un rappel tient dans **un seul segment SMS** : titre et date sont prioritaires, puis lieu et description selon la place disponible et l'encodage GSM ou Unicode.
|
||||||
|
- Le préfixe, le suffixe et la longueur de description sont réglables avec les variables `RELAIS_SMS_CALDAV_REMINDER_HEADER`, `RELAIS_SMS_CALDAV_REMINDER_FOOTER` et `RELAIS_SMS_CALDAV_DESCRIPTION_MAX_LENGTH`.
|
||||||
|
|
||||||
|
Pour importer l'agenda sans traiter les envois :
|
||||||
|
|
||||||
|
```bash
|
||||||
|
php artisan calendar:sync-caldav
|
||||||
|
```
|
||||||
|
|
||||||
|
`calendar:process-reminders` traite les rappels dus et synchronise l'agenda si l'intervalle configuré est écoulé. Ses options `--no-sync` et `--force-sync` permettent respectivement d'ignorer ou de forcer cette synchronisation. **Cette commande peut envoyer des SMS.**
|
||||||
|
|
||||||
|
## Tâches planifiées
|
||||||
|
|
||||||
|
### Serveur avec cron à la minute
|
||||||
|
|
||||||
|
```cron
|
||||||
|
* * * * * cd /chemin/vers/RelaisSMS && php artisan schedule:run >> /dev/null 2>&1
|
||||||
|
```
|
||||||
|
|
||||||
|
Le scheduler vérifie chaque minute les rappels, les campagnes dues et les envois incertains. CardDAV est synchronisé toutes les heures ; les lectures CalDAV suivent l'intervalle configuré. L'historique expiré est purgé chaque jour à 02:30 selon le fuseau du scheduler Laravel.
|
||||||
|
|
||||||
|
### Hébergement mutualisé OVHcloud
|
||||||
|
|
||||||
|
Si le planificateur ne permet qu'un passage horaire, configurez une seule tâche PHP 8.3 pointant vers `RelaisSMS/cron.php` (adaptez le chemin au dossier d'installation).
|
||||||
|
|
||||||
|
Ce point d'entrée **CLI uniquement** exécute explicitement, dans l'ordre : CardDAV, CalDAV et les rappels dus, les campagnes programmées, le rapprochement OVH, puis la purge de l'historique. Un simple `schedule:run` lancé à une minute quelconque de chaque heure pourrait manquer les tâches prévues à une heure précise.
|
||||||
|
|
||||||
|
La précision dépend du planificateur : avec un passage par heure, un envoi peut être retardé d'environ **0 à 60 minutes**. Les commandes traitent par défaut jusqu'à 50 rappels ou 50 campagnes par passage ; un volume supérieur peut prolonger ce délai. Activez les rapports d'erreur du planificateur.
|
||||||
|
|
||||||
|
## Déploiement et données privées
|
||||||
|
|
||||||
|
1. Construisez les dépendances et les assets : `composer install --no-dev --optimize-autoloader`, `npm ci`, puis `npm run build`. Sur un hébergement sans Composer, transférez aussi `vendor/` depuis un environnement compatible.
|
||||||
|
2. Configurez le serveur web pour exposer **uniquement `public/`**. Si l'hébergeur impose une autre disposition, bloquez l'accès HTTP aux fichiers privés et conservez les fichiers de routage propres à l'installation.
|
||||||
|
3. Créez le `.env` du serveur avec ses propres secrets et `APP_ENV=production`, `APP_DEBUG=false`, une `APP_URL` HTTPS et `SESSION_SECURE_COOKIE=true`.
|
||||||
|
4. Sauvegardez le code remplacé, `.env` et SQLite avant toute mise à jour. Protégez les sauvegardes et `.env` avec des permissions restrictives, par exemple `600` ; autorisez l'écriture sur `storage/` et `bootstrap/cache/` au processus PHP.
|
||||||
|
5. Passez en maintenance avec `php artisan down`, transférez le code et les assets, appliquez `php artisan migrate --force`, puis `php artisan optimize:clear`. Lors de la première installation uniquement, créez le compte avec `php artisan db:seed --force` après avoir défini son mot de passe.
|
||||||
|
6. Remettez le service en ligne avec `php artisan up`, vérifiez la connexion et configurez le planificateur.
|
||||||
|
|
||||||
|
Conservez l'`APP_KEY`, les données et le jeton STOP lors des mises à jour. Sur l'installation mutualisée OVHcloud à l'origine du projet, **n'activez pas `config:cache` ni `artisan optimize`** : le cache de configuration y a provoqué une erreur HTTP 500. `view:cache` peut être utilisé séparément.
|
||||||
|
|
||||||
|
Le dépôt exclut les fichiers `.env` privés, bases locales, journaux, sessions, exports temporaires, sauvegardes et consignes locales d'exploitation. Ne publiez pas de véritables coordonnées dans des fixtures ou des captures d'écran. L'historique applicatif contient des données personnelles : sa rétention est réglée par `RELAIS_SMS_HISTORY_RETENTION_YEARS` (3 ans par défaut). Prévisualisez la purge avec :
|
||||||
|
|
||||||
|
```bash
|
||||||
|
php artisan sms-campaigns:prune-history --dry-run
|
||||||
|
```
|
||||||
|
|
||||||
|
## Tests et contribution
|
||||||
|
|
||||||
|
```bash
|
||||||
|
php artisan test --compact
|
||||||
|
vendor/bin/pint --test
|
||||||
|
vendor/bin/phpstan analyse --memory-limit=1G --no-progress
|
||||||
|
npm run build
|
||||||
|
```
|
||||||
|
|
||||||
|
Les tests utilisent SQLite en mémoire ; les tests des intégrations utilisent des doublures HTTP. N'utilisez pas vos identifiants de production pour les tests. La commande `sms:send-test` effectue un envoi réel et consomme des crédits : ne l'exécutez qu'avec l'accord du destinataire et une autorisation explicite.
|
||||||
|
|
||||||
|
Les documents de conception et la maquette initiale sont dans [`doc/`](doc/). Ils décrivent aussi des intentions historiques ; le tableau des fonctionnalités ci-dessus présente le périmètre actuellement implémenté.
|
||||||
|
|
||||||
|
## Licence
|
||||||
|
|
||||||
|
RelaisSMS est distribué sous [licence GNU GPL v3](LICENSE), conservée depuis l’initialisation du dépôt. Les dépendances restent soumises à leurs licences respectives.
|
||||||
@@ -0,0 +1,69 @@
|
|||||||
|
<?php
|
||||||
|
|
||||||
|
namespace App\Console\Commands;
|
||||||
|
|
||||||
|
use App\Models\SourceSyncRun;
|
||||||
|
use App\Services\Calendar\CalendarEventSyncService;
|
||||||
|
use App\Services\Calendar\CalendarReminderSender;
|
||||||
|
use Illuminate\Console\Command;
|
||||||
|
use Illuminate\Support\Carbon;
|
||||||
|
use Throwable;
|
||||||
|
|
||||||
|
class ProcessCalendarRemindersCommand extends Command
|
||||||
|
{
|
||||||
|
protected $signature = 'calendar:process-reminders
|
||||||
|
{--no-sync : Ne synchronise pas l agenda avant traitement}
|
||||||
|
{--force-sync : Force la synchronisation CalDAV avant traitement}';
|
||||||
|
|
||||||
|
protected $description = 'Synchronise l agenda CalDAV et envoie les rappels SMS dus.';
|
||||||
|
|
||||||
|
public function handle(CalendarEventSyncService $syncService, CalendarReminderSender $sender): int
|
||||||
|
{
|
||||||
|
if ($this->shouldSync()) {
|
||||||
|
try {
|
||||||
|
$run = $syncService->sync();
|
||||||
|
$this->line((string) $run->message);
|
||||||
|
} catch (Throwable $exception) {
|
||||||
|
$this->error('Synchronisation CalDAV agenda en echec : '.$exception->getMessage());
|
||||||
|
|
||||||
|
return self::FAILURE;
|
||||||
|
}
|
||||||
|
} elseif (! $this->option('no-sync')) {
|
||||||
|
$interval = (int) config('relais_sms.caldav.sync_interval_minutes', 60);
|
||||||
|
$this->line('Synchronisation CalDAV ignoree : derniere synchronisation recente, intervalle '.$interval.' minute(s).');
|
||||||
|
}
|
||||||
|
|
||||||
|
$sent = $sender->sendDue();
|
||||||
|
$this->info($sent.' rappel(s) SMS envoye(s).');
|
||||||
|
|
||||||
|
return self::SUCCESS;
|
||||||
|
}
|
||||||
|
|
||||||
|
private function shouldSync(): bool
|
||||||
|
{
|
||||||
|
if ($this->option('no-sync')) {
|
||||||
|
return false;
|
||||||
|
}
|
||||||
|
|
||||||
|
if ($this->option('force-sync')) {
|
||||||
|
return true;
|
||||||
|
}
|
||||||
|
|
||||||
|
$interval = max(1, (int) config('relais_sms.caldav.sync_interval_minutes', 60));
|
||||||
|
$lastRun = SourceSyncRun::query()
|
||||||
|
->where('source', 'caldav_calendar')
|
||||||
|
->latest('started_at')
|
||||||
|
->first();
|
||||||
|
|
||||||
|
$rawStartedAt = $lastRun?->getRawOriginal('started_at');
|
||||||
|
|
||||||
|
if ($rawStartedAt === null) {
|
||||||
|
return true;
|
||||||
|
}
|
||||||
|
|
||||||
|
$lastStartedAt = Carbon::parse((string) $rawStartedAt, 'UTC');
|
||||||
|
$nextAllowedSyncAt = Carbon::now()->utc()->subMinutes($interval);
|
||||||
|
|
||||||
|
return $lastStartedAt->lessThanOrEqualTo($nextAllowedSyncAt);
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,39 @@
|
|||||||
|
<?php
|
||||||
|
|
||||||
|
namespace App\Console\Commands;
|
||||||
|
|
||||||
|
use App\Models\SmsCampaign;
|
||||||
|
use Illuminate\Console\Command;
|
||||||
|
|
||||||
|
class PruneSmsHistoryCommand extends Command
|
||||||
|
{
|
||||||
|
protected $signature = 'sms-campaigns:prune-history {--dry-run : Compte les campagnes expirees sans les supprimer.}';
|
||||||
|
|
||||||
|
protected $description = 'Supprime les campagnes SMS plus anciennes que la duree de retention configuree.';
|
||||||
|
|
||||||
|
public function handle(): int
|
||||||
|
{
|
||||||
|
$retentionYears = (int) config('relais_sms.default_settings.history_retention_years', 3);
|
||||||
|
|
||||||
|
if ($retentionYears < 1) {
|
||||||
|
$this->error('La retention doit etre superieure ou egale a 1 an.');
|
||||||
|
|
||||||
|
return self::FAILURE;
|
||||||
|
}
|
||||||
|
|
||||||
|
$expiresBefore = now()->subYears($retentionYears);
|
||||||
|
$query = SmsCampaign::query()->where('created_at', '<', $expiresBefore);
|
||||||
|
$count = $query->count();
|
||||||
|
|
||||||
|
if ($this->option('dry-run')) {
|
||||||
|
$this->line($count.' campagne(s) SMS expiree(s) avant '.$expiresBefore->format('Y-m-d H:i:s').'.');
|
||||||
|
|
||||||
|
return self::SUCCESS;
|
||||||
|
}
|
||||||
|
|
||||||
|
$query->delete();
|
||||||
|
$this->line($count.' campagne(s) SMS supprimee(s).');
|
||||||
|
|
||||||
|
return self::SUCCESS;
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,44 @@
|
|||||||
|
<?php
|
||||||
|
|
||||||
|
namespace App\Console\Commands;
|
||||||
|
|
||||||
|
use App\Models\SmsCampaign;
|
||||||
|
use App\Services\Sms\SmsCampaignReconciler;
|
||||||
|
use Illuminate\Console\Command;
|
||||||
|
use Illuminate\Database\Eloquent\Builder;
|
||||||
|
|
||||||
|
class ReconcileSmsCampaignsCommand extends Command
|
||||||
|
{
|
||||||
|
protected $signature = 'sms-campaigns:reconcile {--limit=50 : Nombre maximum de campagnes a verifier.}';
|
||||||
|
|
||||||
|
protected $description = 'Verifie les envois incertains dans l historique OVH sans renvoyer de SMS.';
|
||||||
|
|
||||||
|
public function handle(SmsCampaignReconciler $reconciler): int
|
||||||
|
{
|
||||||
|
$processed = 0;
|
||||||
|
SmsCampaign::query()
|
||||||
|
->where('provider', 'ovh')
|
||||||
|
->where(function (Builder $query): void {
|
||||||
|
$query->where('status', 'uncertain')
|
||||||
|
->orWhere(fn (Builder $query): Builder => $query->where('status', 'sending')->where('updated_at', '<', now()->subMinutes(10)));
|
||||||
|
})
|
||||||
|
->orderBy('updated_at')
|
||||||
|
->limit(max(1, (int) $this->option('limit')))
|
||||||
|
->get()
|
||||||
|
->each(function (SmsCampaign $campaign) use ($reconciler, &$processed): void {
|
||||||
|
if ($campaign->status === 'sending') {
|
||||||
|
$campaign->update([
|
||||||
|
'status' => 'uncertain',
|
||||||
|
'error_message' => 'Envoi interrompu avant confirmation. Verification OVH necessaire ; ne pas renvoyer cette campagne.',
|
||||||
|
]);
|
||||||
|
$campaign->deliveries()->where('status', 'queued')->update(['status' => 'uncertain']);
|
||||||
|
}
|
||||||
|
$reconciler->reconcile($campaign);
|
||||||
|
$processed++;
|
||||||
|
});
|
||||||
|
|
||||||
|
$this->line($processed.' campagne(s) verifiee(s), sans nouvel envoi.');
|
||||||
|
|
||||||
|
return self::SUCCESS;
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,37 @@
|
|||||||
|
<?php
|
||||||
|
|
||||||
|
namespace App\Console\Commands;
|
||||||
|
|
||||||
|
use App\Models\SmsCampaign;
|
||||||
|
use App\Services\Sms\SmsCampaignSender;
|
||||||
|
use Illuminate\Console\Command;
|
||||||
|
|
||||||
|
class SendDueSmsCampaignsCommand extends Command
|
||||||
|
{
|
||||||
|
protected $signature = 'sms-campaigns:send-due {--limit=50 : Nombre maximum de campagnes a prendre en charge.}';
|
||||||
|
|
||||||
|
protected $description = 'Envoie les campagnes SMS programmees arrivees a echeance.';
|
||||||
|
|
||||||
|
public function handle(SmsCampaignSender $sender): int
|
||||||
|
{
|
||||||
|
$limit = max(1, (int) $this->option('limit'));
|
||||||
|
$processed = 0;
|
||||||
|
|
||||||
|
SmsCampaign::query()
|
||||||
|
->where('status', 'scheduled')
|
||||||
|
->whereNotNull('scheduled_at')
|
||||||
|
->where('scheduled_at', '<=', now())
|
||||||
|
->orderBy('scheduled_at')
|
||||||
|
->limit($limit)
|
||||||
|
->get()
|
||||||
|
->each(function (SmsCampaign $campaign) use ($sender, &$processed): void {
|
||||||
|
if ($sender->sendScheduled($campaign) !== null) {
|
||||||
|
$processed++;
|
||||||
|
}
|
||||||
|
});
|
||||||
|
|
||||||
|
$this->line($processed.' campagne(s) SMS programmee(s) prise(s) en charge.');
|
||||||
|
|
||||||
|
return self::SUCCESS;
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,96 @@
|
|||||||
|
<?php
|
||||||
|
|
||||||
|
namespace App\Console\Commands;
|
||||||
|
|
||||||
|
use App\Contracts\PhoneNumberNormalizerInterface;
|
||||||
|
use App\Models\Contact;
|
||||||
|
use App\Models\ContactPhoneNumber;
|
||||||
|
use App\Models\User;
|
||||||
|
use App\Services\Sms\SmsCampaignSender;
|
||||||
|
use Illuminate\Console\Command;
|
||||||
|
use Illuminate\Support\Facades\DB;
|
||||||
|
|
||||||
|
class SendTestSmsCommand extends Command
|
||||||
|
{
|
||||||
|
protected $signature = 'sms:send-test {phone} {--message=Test RelaisSMS}';
|
||||||
|
|
||||||
|
protected $description = 'Cree le contact de test si besoin et envoie un SMS uniquement a ce numero.';
|
||||||
|
|
||||||
|
public function handle(PhoneNumberNormalizerInterface $normalizer, SmsCampaignSender $sender): int
|
||||||
|
{
|
||||||
|
$phone = (string) $this->argument('phone');
|
||||||
|
$message = trim((string) $this->option('message'));
|
||||||
|
$normalized = $normalizer->normalize($phone, (string) config('relais_sms.default_settings.default_country', 'FR'));
|
||||||
|
|
||||||
|
if (! $normalized->isValid || ! $normalized->isMobile || $normalized->normalizedNumber === null) {
|
||||||
|
$this->error($normalized->error ?: 'Numero invalide ou non mobile.');
|
||||||
|
|
||||||
|
return self::FAILURE;
|
||||||
|
}
|
||||||
|
|
||||||
|
if ($message === '') {
|
||||||
|
$this->error('Message vide.');
|
||||||
|
|
||||||
|
return self::FAILURE;
|
||||||
|
}
|
||||||
|
|
||||||
|
[$contact, $phoneNumber] = DB::transaction(function () use ($normalized): array {
|
||||||
|
$phoneNumber = ContactPhoneNumber::query()
|
||||||
|
->where('normalized_number', $normalized->normalizedNumber)
|
||||||
|
->with('contact')
|
||||||
|
->first();
|
||||||
|
|
||||||
|
if ($phoneNumber !== null && $phoneNumber->contact !== null) {
|
||||||
|
return [$phoneNumber->contact, $phoneNumber];
|
||||||
|
}
|
||||||
|
|
||||||
|
$contact = Contact::query()->create([
|
||||||
|
'source' => 'local',
|
||||||
|
'first_name' => 'Test',
|
||||||
|
'last_name' => 'RelaisSMS',
|
||||||
|
'notes' => 'Contact cree pour test envoi SMS.',
|
||||||
|
]);
|
||||||
|
|
||||||
|
$phoneNumber = $contact->phoneNumbers()->create([
|
||||||
|
'label' => 'Test',
|
||||||
|
'raw_number' => $normalized->rawNumber,
|
||||||
|
'normalized_number' => $normalized->normalizedNumber,
|
||||||
|
'country' => $normalized->country,
|
||||||
|
'is_valid' => $normalized->isValid,
|
||||||
|
'is_mobile' => $normalized->isMobile,
|
||||||
|
'is_primary' => true,
|
||||||
|
'validation_error' => $normalized->error,
|
||||||
|
]);
|
||||||
|
|
||||||
|
return [$contact, $phoneNumber];
|
||||||
|
});
|
||||||
|
|
||||||
|
$user = User::query()->first();
|
||||||
|
|
||||||
|
if ($user === null) {
|
||||||
|
$this->error('Aucun utilisateur applicatif disponible.');
|
||||||
|
|
||||||
|
return self::FAILURE;
|
||||||
|
}
|
||||||
|
|
||||||
|
$campaign = $sender->send($user, $message, [[
|
||||||
|
'contact_id' => $contact->id,
|
||||||
|
'contact_name' => $contact->displayName(),
|
||||||
|
'phone_number_id' => $phoneNumber->id,
|
||||||
|
'number' => $normalized->normalizedNumber,
|
||||||
|
'raw_number' => $normalized->rawNumber,
|
||||||
|
'label' => $phoneNumber->label,
|
||||||
|
'selection' => ['Test CLI'],
|
||||||
|
]]);
|
||||||
|
|
||||||
|
$this->line('Campagne #'.$campaign->id.' : '.$campaign->status);
|
||||||
|
|
||||||
|
if ($campaign->error_message !== null) {
|
||||||
|
$this->error($campaign->error_message);
|
||||||
|
|
||||||
|
return self::FAILURE;
|
||||||
|
}
|
||||||
|
|
||||||
|
return $campaign->status === 'failed' ? self::FAILURE : self::SUCCESS;
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,32 @@
|
|||||||
|
<?php
|
||||||
|
|
||||||
|
namespace App\Console\Commands;
|
||||||
|
|
||||||
|
use App\Services\Calendar\CalendarEventSyncService;
|
||||||
|
use Illuminate\Console\Command;
|
||||||
|
use Throwable;
|
||||||
|
|
||||||
|
class SyncCalDavCalendarCommand extends Command
|
||||||
|
{
|
||||||
|
protected $signature = 'calendar:sync-caldav';
|
||||||
|
|
||||||
|
protected $description = 'Synchronise les evenements depuis l agenda CalDAV configure.';
|
||||||
|
|
||||||
|
public function handle(CalendarEventSyncService $syncService): int
|
||||||
|
{
|
||||||
|
try {
|
||||||
|
$run = $syncService->sync();
|
||||||
|
} catch (Throwable $exception) {
|
||||||
|
$this->error('Synchronisation CalDAV agenda en echec : '.$exception->getMessage());
|
||||||
|
|
||||||
|
return self::FAILURE;
|
||||||
|
}
|
||||||
|
|
||||||
|
$this->info((string) $run->message);
|
||||||
|
$this->line('Objets lus : '.$run->fetched_contacts);
|
||||||
|
$this->line('Evenements synchronises : '.$run->synced_contacts);
|
||||||
|
$this->line('Evenements annules localement : '.$run->deleted_contacts);
|
||||||
|
|
||||||
|
return self::SUCCESS;
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,32 @@
|
|||||||
|
<?php
|
||||||
|
|
||||||
|
namespace App\Console\Commands;
|
||||||
|
|
||||||
|
use App\Services\CardDav\CardDavContactSyncService;
|
||||||
|
use Illuminate\Console\Command;
|
||||||
|
use Throwable;
|
||||||
|
|
||||||
|
class SyncCardDavContactsCommand extends Command
|
||||||
|
{
|
||||||
|
protected $signature = 'contacts:sync-carddav';
|
||||||
|
|
||||||
|
protected $description = 'Synchronise les contacts depuis le carnet CardDAV configure.';
|
||||||
|
|
||||||
|
public function handle(CardDavContactSyncService $syncService): int
|
||||||
|
{
|
||||||
|
try {
|
||||||
|
$run = $syncService->sync();
|
||||||
|
} catch (Throwable $exception) {
|
||||||
|
$this->error('Synchronisation CardDAV en echec : '.$exception->getMessage());
|
||||||
|
|
||||||
|
return self::FAILURE;
|
||||||
|
}
|
||||||
|
|
||||||
|
$this->info((string) $run->message);
|
||||||
|
$this->line('Contacts lus : '.$run->fetched_contacts);
|
||||||
|
$this->line('Contacts synchronises : '.$run->synced_contacts);
|
||||||
|
$this->line('Contacts supprimes localement : '.$run->deleted_contacts);
|
||||||
|
|
||||||
|
return self::SUCCESS;
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,14 @@
|
|||||||
|
<?php
|
||||||
|
|
||||||
|
namespace App\Contracts\Calendar;
|
||||||
|
|
||||||
|
use App\Services\Calendar\CalendarRemoteEvent;
|
||||||
|
use Carbon\CarbonInterface;
|
||||||
|
|
||||||
|
interface CalendarClientInterface
|
||||||
|
{
|
||||||
|
/**
|
||||||
|
* @return array<int, CalendarRemoteEvent>
|
||||||
|
*/
|
||||||
|
public function fetchEvents(CarbonInterface $from, CarbonInterface $to): array;
|
||||||
|
}
|
||||||
@@ -0,0 +1,13 @@
|
|||||||
|
<?php
|
||||||
|
|
||||||
|
namespace App\Contracts\CardDav;
|
||||||
|
|
||||||
|
use App\Services\CardDav\CardDavRemoteCard;
|
||||||
|
|
||||||
|
interface CardDavClientInterface
|
||||||
|
{
|
||||||
|
/**
|
||||||
|
* @return array<int, CardDavRemoteCard>
|
||||||
|
*/
|
||||||
|
public function fetchCards(): array;
|
||||||
|
}
|
||||||
@@ -0,0 +1,10 @@
|
|||||||
|
<?php
|
||||||
|
|
||||||
|
namespace App\Contracts;
|
||||||
|
|
||||||
|
use App\Services\Phone\PhoneNumberResult;
|
||||||
|
|
||||||
|
interface PhoneNumberNormalizerInterface
|
||||||
|
{
|
||||||
|
public function normalize(string $rawNumber, string $defaultCountry): PhoneNumberResult;
|
||||||
|
}
|
||||||
@@ -0,0 +1,14 @@
|
|||||||
|
<?php
|
||||||
|
|
||||||
|
namespace App\Contracts\Sms;
|
||||||
|
|
||||||
|
use App\Models\SmsCampaign;
|
||||||
|
use App\Services\Sms\SmsSendResult;
|
||||||
|
|
||||||
|
interface SmsProviderInterface
|
||||||
|
{
|
||||||
|
/**
|
||||||
|
* @param array<int, array<string, mixed>> $recipients
|
||||||
|
*/
|
||||||
|
public function send(SmsCampaign $campaign, array $recipients): SmsSendResult;
|
||||||
|
}
|
||||||
@@ -0,0 +1,48 @@
|
|||||||
|
<?php
|
||||||
|
|
||||||
|
namespace App\Http\Controllers\Auth;
|
||||||
|
|
||||||
|
use App\Http\Controllers\Controller;
|
||||||
|
use Illuminate\Http\RedirectResponse;
|
||||||
|
use Illuminate\Http\Request;
|
||||||
|
use Illuminate\Support\Facades\Auth;
|
||||||
|
use Illuminate\Validation\ValidationException;
|
||||||
|
use Illuminate\View\View;
|
||||||
|
|
||||||
|
class AuthenticatedSessionController extends Controller
|
||||||
|
{
|
||||||
|
public function create(): View
|
||||||
|
{
|
||||||
|
return view('auth.login');
|
||||||
|
}
|
||||||
|
|
||||||
|
public function store(Request $request): RedirectResponse
|
||||||
|
{
|
||||||
|
$credentials = $request->validate([
|
||||||
|
'email' => ['required', 'string', 'max:255'],
|
||||||
|
'password' => ['required', 'string'],
|
||||||
|
]);
|
||||||
|
|
||||||
|
$remember = $request->boolean('remember');
|
||||||
|
|
||||||
|
if (! Auth::attempt($credentials, $remember)) {
|
||||||
|
throw ValidationException::withMessages([
|
||||||
|
'email' => __('auth.failed'),
|
||||||
|
]);
|
||||||
|
}
|
||||||
|
|
||||||
|
$request->session()->regenerate();
|
||||||
|
|
||||||
|
return redirect()->intended(route('recipients.index', absolute: false));
|
||||||
|
}
|
||||||
|
|
||||||
|
public function destroy(Request $request): RedirectResponse
|
||||||
|
{
|
||||||
|
Auth::guard('web')->logout();
|
||||||
|
|
||||||
|
$request->session()->invalidate();
|
||||||
|
$request->session()->regenerateToken();
|
||||||
|
|
||||||
|
return redirect()->route('login');
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,25 @@
|
|||||||
|
<?php
|
||||||
|
|
||||||
|
namespace App\Http\Controllers;
|
||||||
|
|
||||||
|
use App\Services\CardDav\CardDavContactSyncService;
|
||||||
|
use Illuminate\Http\RedirectResponse;
|
||||||
|
use Throwable;
|
||||||
|
|
||||||
|
class CardDavSyncController extends Controller
|
||||||
|
{
|
||||||
|
public function __invoke(CardDavContactSyncService $syncService): RedirectResponse
|
||||||
|
{
|
||||||
|
try {
|
||||||
|
$run = $syncService->sync();
|
||||||
|
} catch (Throwable $exception) {
|
||||||
|
return redirect()
|
||||||
|
->route('contacts.index')
|
||||||
|
->with('status', 'Synchronisation CardDAV en echec : '.$exception->getMessage());
|
||||||
|
}
|
||||||
|
|
||||||
|
return redirect()
|
||||||
|
->route('contacts.index')
|
||||||
|
->with('status', $run->message ?? 'Synchronisation CardDAV terminee.');
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,287 @@
|
|||||||
|
<?php
|
||||||
|
|
||||||
|
namespace App\Http\Controllers;
|
||||||
|
|
||||||
|
use App\Contracts\PhoneNumberNormalizerInterface;
|
||||||
|
use App\Models\Contact;
|
||||||
|
use App\Models\ContactGroup;
|
||||||
|
use App\Models\SourceSyncRun;
|
||||||
|
use Illuminate\Contracts\View\View;
|
||||||
|
use Illuminate\Http\RedirectResponse;
|
||||||
|
use Illuminate\Http\Request;
|
||||||
|
use Illuminate\Support\Facades\DB;
|
||||||
|
use Illuminate\Validation\Rule;
|
||||||
|
|
||||||
|
class ContactController extends Controller
|
||||||
|
{
|
||||||
|
public function index(Request $request): View
|
||||||
|
{
|
||||||
|
$search = (string) $request->query('q', '');
|
||||||
|
$groupId = $request->integer('group');
|
||||||
|
$favoriteOnly = $request->boolean('favorite');
|
||||||
|
$selectedStatus = (string) $request->query('status', '');
|
||||||
|
$selectedMobileFilter = (string) $request->query('mobile', 'detected');
|
||||||
|
|
||||||
|
if (! in_array($selectedStatus, ['', 'active', 'favorite', 'opt_out'], true)) {
|
||||||
|
$selectedStatus = '';
|
||||||
|
}
|
||||||
|
|
||||||
|
if (! in_array($selectedMobileFilter, ['all', 'detected', 'non_mobile', 'invalid', 'missing'], true)) {
|
||||||
|
$selectedMobileFilter = 'detected';
|
||||||
|
}
|
||||||
|
|
||||||
|
$contacts = Contact::query()
|
||||||
|
->with(['groups', 'phoneNumbers'])
|
||||||
|
->withCount('groups')
|
||||||
|
->search($search)
|
||||||
|
->when($groupId > 0, function ($query) use ($groupId): void {
|
||||||
|
$query->whereHas('groups', fn ($query) => $query->whereKey($groupId));
|
||||||
|
})
|
||||||
|
->when($favoriteOnly || $selectedStatus === 'favorite', function ($query): void {
|
||||||
|
$query->where('is_favorite', true);
|
||||||
|
})
|
||||||
|
->when($selectedStatus === 'opt_out', function ($query): void {
|
||||||
|
$query->where('sms_opt_out', true);
|
||||||
|
})
|
||||||
|
->when($selectedStatus === 'active', function ($query): void {
|
||||||
|
$query->where('sms_opt_out', false);
|
||||||
|
})
|
||||||
|
->when($selectedMobileFilter === 'detected', function ($query): void {
|
||||||
|
$query->whereHas('phoneNumbers', function ($query): void {
|
||||||
|
$query->where('is_valid', true)
|
||||||
|
->where(function ($query): void {
|
||||||
|
$query
|
||||||
|
->where('is_mobile', true)
|
||||||
|
->orWhere('normalized_number', 'like', '+336%')
|
||||||
|
->orWhere('normalized_number', 'like', '+337%');
|
||||||
|
});
|
||||||
|
});
|
||||||
|
})
|
||||||
|
->when($selectedMobileFilter === 'non_mobile', function ($query): void {
|
||||||
|
$query->whereHas('phoneNumbers', function ($query): void {
|
||||||
|
$query->where('is_valid', true)
|
||||||
|
->where('is_mobile', false)
|
||||||
|
->where('normalized_number', 'not like', '+336%')
|
||||||
|
->where('normalized_number', 'not like', '+337%');
|
||||||
|
});
|
||||||
|
})
|
||||||
|
->when($selectedMobileFilter === 'invalid', function ($query): void {
|
||||||
|
$query->whereHas('phoneNumbers', fn ($query) => $query->where('is_valid', false));
|
||||||
|
})
|
||||||
|
->when($selectedMobileFilter === 'missing', function ($query): void {
|
||||||
|
$query->whereDoesntHave('phoneNumbers');
|
||||||
|
})
|
||||||
|
->orderByDesc('is_favorite')
|
||||||
|
->orderBy('last_name')
|
||||||
|
->orderBy('first_name')
|
||||||
|
->paginate(15)
|
||||||
|
->withQueryString();
|
||||||
|
|
||||||
|
$groups = ContactGroup::query()
|
||||||
|
->withCount('contacts')
|
||||||
|
->orderBy('name')
|
||||||
|
->get();
|
||||||
|
|
||||||
|
return view('contacts.index', [
|
||||||
|
'contacts' => $contacts,
|
||||||
|
'groups' => $groups,
|
||||||
|
'search' => $search,
|
||||||
|
'selectedGroupId' => $groupId,
|
||||||
|
'favoriteOnly' => $favoriteOnly,
|
||||||
|
'selectedStatus' => $selectedStatus,
|
||||||
|
'selectedMobileFilter' => $selectedMobileFilter,
|
||||||
|
'cardDavSyncEnabled' => (bool) config('relais_sms.default_settings.carddav_sync_enabled'),
|
||||||
|
'lastCardDavSyncRun' => SourceSyncRun::query()
|
||||||
|
->where('source', 'carddav')
|
||||||
|
->latest('started_at')
|
||||||
|
->first(),
|
||||||
|
]);
|
||||||
|
}
|
||||||
|
|
||||||
|
public function create(): View
|
||||||
|
{
|
||||||
|
return view('contacts.create', [
|
||||||
|
'groups' => ContactGroup::query()->where('source', 'local')->orderBy('name')->get(),
|
||||||
|
]);
|
||||||
|
}
|
||||||
|
|
||||||
|
public function store(Request $request, PhoneNumberNormalizerInterface $normalizer): RedirectResponse
|
||||||
|
{
|
||||||
|
$validated = $request->validate($this->rules());
|
||||||
|
|
||||||
|
$contact = DB::transaction(function () use ($request, $validated, $normalizer): Contact {
|
||||||
|
$contact = Contact::query()->create([
|
||||||
|
'source' => 'local',
|
||||||
|
'first_name' => $validated['first_name'] ?? null,
|
||||||
|
'last_name' => $validated['last_name'],
|
||||||
|
'organization' => $validated['organization'] ?? null,
|
||||||
|
'email' => $validated['email'] ?? null,
|
||||||
|
'notes' => $validated['notes'] ?? null,
|
||||||
|
'sms_opt_out' => $request->boolean('sms_opt_out'),
|
||||||
|
'is_favorite' => $request->boolean('is_favorite'),
|
||||||
|
]);
|
||||||
|
|
||||||
|
$contact->groups()->sync($validated['group_ids'] ?? []);
|
||||||
|
$this->syncPrimaryPhoneNumber($contact, $validated, $normalizer);
|
||||||
|
|
||||||
|
return $contact;
|
||||||
|
});
|
||||||
|
|
||||||
|
return redirect()
|
||||||
|
->route('contacts.show', $contact)
|
||||||
|
->with('status', 'Contact cree.');
|
||||||
|
}
|
||||||
|
|
||||||
|
public function show(Contact $contact): View
|
||||||
|
{
|
||||||
|
$contact->load(['groups', 'phoneNumbers']);
|
||||||
|
|
||||||
|
return view('contacts.show', [
|
||||||
|
'contact' => $contact,
|
||||||
|
]);
|
||||||
|
}
|
||||||
|
|
||||||
|
public function favorite(Request $request, Contact $contact): RedirectResponse
|
||||||
|
{
|
||||||
|
$validated = $request->validate([
|
||||||
|
'is_favorite' => ['required', 'boolean'],
|
||||||
|
]);
|
||||||
|
|
||||||
|
$contact->update([
|
||||||
|
'is_favorite' => (bool) $validated['is_favorite'],
|
||||||
|
]);
|
||||||
|
|
||||||
|
return back()->with('status', $contact->is_favorite ? 'Contact ajoute aux favoris.' : 'Contact retire des favoris.');
|
||||||
|
}
|
||||||
|
|
||||||
|
public function optOut(Request $request, Contact $contact): RedirectResponse
|
||||||
|
{
|
||||||
|
$validated = $request->validate([
|
||||||
|
'sms_opt_out' => ['required', 'boolean'],
|
||||||
|
]);
|
||||||
|
|
||||||
|
$contact->update([
|
||||||
|
'sms_opt_out' => (bool) $validated['sms_opt_out'],
|
||||||
|
]);
|
||||||
|
|
||||||
|
return back()->with('status', $contact->sms_opt_out ? 'Contact ajoute aux refus SMS.' : 'Contact retire des refus SMS.');
|
||||||
|
}
|
||||||
|
|
||||||
|
public function edit(Contact $contact): View
|
||||||
|
{
|
||||||
|
$this->ensureLocalContact($contact);
|
||||||
|
|
||||||
|
$contact->load(['groups', 'phoneNumbers']);
|
||||||
|
|
||||||
|
return view('contacts.edit', [
|
||||||
|
'contact' => $contact,
|
||||||
|
'groups' => ContactGroup::query()->where('source', 'local')->orderBy('name')->get(),
|
||||||
|
'primaryPhone' => $contact->phoneNumbers->firstWhere('is_primary', true) ?? $contact->phoneNumbers->first(),
|
||||||
|
]);
|
||||||
|
}
|
||||||
|
|
||||||
|
public function update(Request $request, Contact $contact, PhoneNumberNormalizerInterface $normalizer): RedirectResponse
|
||||||
|
{
|
||||||
|
$this->ensureLocalContact($contact);
|
||||||
|
|
||||||
|
$validated = $request->validate($this->rules());
|
||||||
|
|
||||||
|
DB::transaction(function () use ($request, $contact, $validated, $normalizer): void {
|
||||||
|
$contact->update([
|
||||||
|
'first_name' => $validated['first_name'] ?? null,
|
||||||
|
'last_name' => $validated['last_name'],
|
||||||
|
'organization' => $validated['organization'] ?? null,
|
||||||
|
'email' => $validated['email'] ?? null,
|
||||||
|
'notes' => $validated['notes'] ?? null,
|
||||||
|
'sms_opt_out' => $request->boolean('sms_opt_out'),
|
||||||
|
'is_favorite' => $request->boolean('is_favorite'),
|
||||||
|
]);
|
||||||
|
|
||||||
|
$contact->groups()->sync($validated['group_ids'] ?? []);
|
||||||
|
$this->syncPrimaryPhoneNumber($contact, $validated, $normalizer);
|
||||||
|
});
|
||||||
|
|
||||||
|
return redirect()
|
||||||
|
->route('contacts.show', $contact)
|
||||||
|
->with('status', 'Contact modifie.');
|
||||||
|
}
|
||||||
|
|
||||||
|
public function destroy(Contact $contact): RedirectResponse
|
||||||
|
{
|
||||||
|
$this->ensureLocalContact($contact);
|
||||||
|
|
||||||
|
$contact->delete();
|
||||||
|
|
||||||
|
return redirect()
|
||||||
|
->route('contacts.index')
|
||||||
|
->with('status', 'Contact supprime.');
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* @return array<string, array<int, string>>
|
||||||
|
*/
|
||||||
|
private function rules(): array
|
||||||
|
{
|
||||||
|
return [
|
||||||
|
'first_name' => ['nullable', 'string', 'max:255'],
|
||||||
|
'last_name' => ['required', 'string', 'max:255'],
|
||||||
|
'organization' => ['nullable', 'string', 'max:255'],
|
||||||
|
'email' => ['nullable', 'email', 'max:255'],
|
||||||
|
'notes' => ['nullable', 'string'],
|
||||||
|
'phone_label' => ['nullable', 'string', 'max:255'],
|
||||||
|
'raw_phone_number' => ['nullable', 'string', 'max:255'],
|
||||||
|
'group_ids' => ['array'],
|
||||||
|
'group_ids.*' => [
|
||||||
|
'integer',
|
||||||
|
Rule::exists('contact_groups', 'id')
|
||||||
|
->where('source', 'local')
|
||||||
|
->whereNull('deleted_at'),
|
||||||
|
],
|
||||||
|
];
|
||||||
|
}
|
||||||
|
|
||||||
|
private function ensureLocalContact(Contact $contact): void
|
||||||
|
{
|
||||||
|
abort_if($contact->source !== 'local', 403, 'Les contacts importes ne sont pas modifiables localement.');
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* @param array<string, mixed> $validated
|
||||||
|
*/
|
||||||
|
private function syncPrimaryPhoneNumber(Contact $contact, array $validated, PhoneNumberNormalizerInterface $normalizer): void
|
||||||
|
{
|
||||||
|
$rawPhoneNumber = trim((string) ($validated['raw_phone_number'] ?? ''));
|
||||||
|
$primaryPhone = $contact->phoneNumbers()->where('is_primary', true)->first()
|
||||||
|
?? $contact->phoneNumbers()->first();
|
||||||
|
|
||||||
|
if ($rawPhoneNumber === '') {
|
||||||
|
$primaryPhone?->delete();
|
||||||
|
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
|
||||||
|
$result = $normalizer->normalize(
|
||||||
|
$rawPhoneNumber,
|
||||||
|
(string) config('relais_sms.default_settings.default_country'),
|
||||||
|
);
|
||||||
|
|
||||||
|
$attributes = [
|
||||||
|
'label' => $validated['phone_label'] ?? null,
|
||||||
|
'raw_number' => $result->rawNumber,
|
||||||
|
'normalized_number' => $result->normalizedNumber,
|
||||||
|
'country' => $result->country,
|
||||||
|
'is_valid' => $result->isValid,
|
||||||
|
'is_mobile' => $result->isMobile,
|
||||||
|
'is_primary' => true,
|
||||||
|
'validation_error' => $result->error,
|
||||||
|
];
|
||||||
|
|
||||||
|
if ($primaryPhone) {
|
||||||
|
$primaryPhone->update($attributes);
|
||||||
|
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
|
||||||
|
$contact->phoneNumbers()->create($attributes);
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,117 @@
|
|||||||
|
<?php
|
||||||
|
|
||||||
|
namespace App\Http\Controllers;
|
||||||
|
|
||||||
|
use App\Models\Contact;
|
||||||
|
use App\Models\ContactGroup;
|
||||||
|
use Illuminate\Contracts\View\View;
|
||||||
|
use Illuminate\Http\RedirectResponse;
|
||||||
|
use Illuminate\Http\Request;
|
||||||
|
use Illuminate\Support\Str;
|
||||||
|
use Illuminate\Validation\Rule;
|
||||||
|
|
||||||
|
class ContactGroupController extends Controller
|
||||||
|
{
|
||||||
|
public function store(Request $request): RedirectResponse
|
||||||
|
{
|
||||||
|
$validated = $request->validate([
|
||||||
|
'name' => ['required', 'string', 'max:255', Rule::unique('contact_groups', 'name')->whereNull('deleted_at')],
|
||||||
|
'description' => ['nullable', 'string'],
|
||||||
|
]);
|
||||||
|
|
||||||
|
ContactGroup::query()->create([
|
||||||
|
'source' => 'local',
|
||||||
|
'name' => $validated['name'],
|
||||||
|
'slug' => $this->uniqueSlug($validated['name']),
|
||||||
|
'description' => $validated['description'] ?? null,
|
||||||
|
'is_favorite' => $request->boolean('is_favorite'),
|
||||||
|
]);
|
||||||
|
|
||||||
|
return redirect()
|
||||||
|
->route('contacts.index')
|
||||||
|
->with('status', 'Groupe cree.');
|
||||||
|
}
|
||||||
|
|
||||||
|
public function edit(ContactGroup $contactGroup): View
|
||||||
|
{
|
||||||
|
$this->ensureLocalGroup($contactGroup);
|
||||||
|
|
||||||
|
return view('contact-groups.edit', [
|
||||||
|
'group' => $contactGroup->load('contacts')->loadCount('contacts'),
|
||||||
|
'contacts' => Contact::query()
|
||||||
|
->with('phoneNumbers')
|
||||||
|
->orderBy('last_name')
|
||||||
|
->orderBy('first_name')
|
||||||
|
->get(),
|
||||||
|
'selectedContactIds' => $contactGroup->contacts->pluck('id')->all(),
|
||||||
|
]);
|
||||||
|
}
|
||||||
|
|
||||||
|
public function update(Request $request, ContactGroup $contactGroup): RedirectResponse
|
||||||
|
{
|
||||||
|
$this->ensureLocalGroup($contactGroup);
|
||||||
|
|
||||||
|
$validated = $request->validate([
|
||||||
|
'name' => [
|
||||||
|
'required',
|
||||||
|
'string',
|
||||||
|
'max:255',
|
||||||
|
Rule::unique('contact_groups', 'name')->ignore($contactGroup)->whereNull('deleted_at'),
|
||||||
|
],
|
||||||
|
'description' => ['nullable', 'string'],
|
||||||
|
'contact_ids' => ['array'],
|
||||||
|
'contact_ids.*' => [Rule::exists('contacts', 'id')->whereNull('deleted_at')],
|
||||||
|
]);
|
||||||
|
|
||||||
|
$contactGroup->update([
|
||||||
|
'name' => $validated['name'],
|
||||||
|
'slug' => $this->uniqueSlug($validated['name'], $contactGroup),
|
||||||
|
'description' => $validated['description'] ?? null,
|
||||||
|
'is_favorite' => $request->boolean('is_favorite'),
|
||||||
|
]);
|
||||||
|
|
||||||
|
if ($request->has('members_submitted')) {
|
||||||
|
$contactGroup->contacts()->sync($validated['contact_ids'] ?? []);
|
||||||
|
}
|
||||||
|
|
||||||
|
return redirect()
|
||||||
|
->route('contacts.index', ['group' => $contactGroup->id])
|
||||||
|
->with('status', 'Groupe modifie.');
|
||||||
|
}
|
||||||
|
|
||||||
|
public function destroy(ContactGroup $contactGroup): RedirectResponse
|
||||||
|
{
|
||||||
|
$this->ensureLocalGroup($contactGroup);
|
||||||
|
|
||||||
|
$contactGroup->contacts()->detach();
|
||||||
|
$contactGroup->delete();
|
||||||
|
|
||||||
|
return redirect()
|
||||||
|
->route('contacts.index')
|
||||||
|
->with('status', 'Groupe supprime.');
|
||||||
|
}
|
||||||
|
|
||||||
|
private function uniqueSlug(string $name, ?ContactGroup $ignore = null): string
|
||||||
|
{
|
||||||
|
$baseSlug = Str::slug($name);
|
||||||
|
$baseSlug = $baseSlug === '' ? 'groupe' : $baseSlug;
|
||||||
|
$slug = $baseSlug;
|
||||||
|
$index = 2;
|
||||||
|
|
||||||
|
while (ContactGroup::query()
|
||||||
|
->where('slug', $slug)
|
||||||
|
->when($ignore, fn ($query) => $query->whereKeyNot($ignore->id))
|
||||||
|
->exists()
|
||||||
|
) {
|
||||||
|
$slug = $baseSlug.'-'.$index;
|
||||||
|
$index++;
|
||||||
|
}
|
||||||
|
|
||||||
|
return $slug;
|
||||||
|
}
|
||||||
|
|
||||||
|
private function ensureLocalGroup(ContactGroup $contactGroup): void
|
||||||
|
{
|
||||||
|
abort_if($contactGroup->source !== 'local', 403, 'Les groupes importes ne sont pas modifiables localement.');
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,8 @@
|
|||||||
|
<?php
|
||||||
|
|
||||||
|
namespace App\Http\Controllers;
|
||||||
|
|
||||||
|
abstract class Controller
|
||||||
|
{
|
||||||
|
//
|
||||||
|
}
|
||||||
@@ -0,0 +1,83 @@
|
|||||||
|
<?php
|
||||||
|
|
||||||
|
namespace App\Http\Controllers;
|
||||||
|
|
||||||
|
use App\Contracts\PhoneNumberNormalizerInterface;
|
||||||
|
use App\Models\ContactPhoneNumber;
|
||||||
|
use Illuminate\Http\JsonResponse;
|
||||||
|
use Illuminate\Http\Request;
|
||||||
|
|
||||||
|
class OvhStopCallbackController extends Controller
|
||||||
|
{
|
||||||
|
public function __invoke(Request $request, PhoneNumberNormalizerInterface $normalizer): JsonResponse
|
||||||
|
{
|
||||||
|
$configuredToken = trim((string) config('relais_sms.ovh.stop_callback_token', ''));
|
||||||
|
$receivedToken = trim((string) ($request->query('token') ?: $request->header('X-RelaisSMS-Callback-Token', '')));
|
||||||
|
|
||||||
|
abort_if($configuredToken === '' || ! hash_equals($configuredToken, $receivedToken), 403);
|
||||||
|
|
||||||
|
$sender = $this->sender($request);
|
||||||
|
|
||||||
|
if ($sender === '') {
|
||||||
|
return response()->json([
|
||||||
|
'status' => 'ignored',
|
||||||
|
'reason' => 'missing_sender',
|
||||||
|
], 422);
|
||||||
|
}
|
||||||
|
|
||||||
|
$result = $normalizer->normalize(
|
||||||
|
$sender,
|
||||||
|
(string) config('relais_sms.default_settings.default_country'),
|
||||||
|
);
|
||||||
|
|
||||||
|
if (! $result->isValid || $result->normalizedNumber === null) {
|
||||||
|
return response()->json([
|
||||||
|
'status' => 'ignored',
|
||||||
|
'reason' => 'invalid_sender',
|
||||||
|
], 422);
|
||||||
|
}
|
||||||
|
|
||||||
|
$contacts = ContactPhoneNumber::query()
|
||||||
|
->with('contact')
|
||||||
|
->where('normalized_number', $result->normalizedNumber)
|
||||||
|
->get()
|
||||||
|
->pluck('contact')
|
||||||
|
->filter()
|
||||||
|
->unique('id')
|
||||||
|
->values();
|
||||||
|
|
||||||
|
$updatedContacts = 0;
|
||||||
|
$alreadyOptedOutContacts = 0;
|
||||||
|
|
||||||
|
foreach ($contacts as $contact) {
|
||||||
|
if ($contact->sms_opt_out) {
|
||||||
|
$alreadyOptedOutContacts++;
|
||||||
|
|
||||||
|
continue;
|
||||||
|
}
|
||||||
|
|
||||||
|
$contact->update(['sms_opt_out' => true]);
|
||||||
|
$updatedContacts++;
|
||||||
|
}
|
||||||
|
|
||||||
|
return response()->json([
|
||||||
|
'status' => $contacts->isEmpty() ? 'unmatched' : 'ok',
|
||||||
|
'sender' => $result->normalizedNumber,
|
||||||
|
'updated_contacts' => $updatedContacts,
|
||||||
|
'already_opted_out_contacts' => $alreadyOptedOutContacts,
|
||||||
|
]);
|
||||||
|
}
|
||||||
|
|
||||||
|
private function sender(Request $request): string
|
||||||
|
{
|
||||||
|
foreach (['sender', 'from', 'number', 'phone', 'msisdn'] as $key) {
|
||||||
|
$value = $request->input($key);
|
||||||
|
|
||||||
|
if (is_string($value) && trim($value) !== '') {
|
||||||
|
return trim($value);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
return '';
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,186 @@
|
|||||||
|
<?php
|
||||||
|
|
||||||
|
namespace App\Http\Controllers;
|
||||||
|
|
||||||
|
use App\Models\Contact;
|
||||||
|
use App\Models\ContactGroup;
|
||||||
|
use App\Services\Recipients\RecipientResolutionResult;
|
||||||
|
use App\Services\Recipients\RecipientResolver;
|
||||||
|
use App\Services\Sms\SmsMessageComposer;
|
||||||
|
use Illuminate\Contracts\View\View;
|
||||||
|
use Illuminate\Http\JsonResponse;
|
||||||
|
use Illuminate\Http\RedirectResponse;
|
||||||
|
use Illuminate\Http\Request;
|
||||||
|
use Illuminate\Validation\Rule;
|
||||||
|
|
||||||
|
class RecipientSelectionController extends Controller
|
||||||
|
{
|
||||||
|
public function index(Request $request, SmsMessageComposer $messageComposer): View
|
||||||
|
{
|
||||||
|
return $this->view($request, messageComposer: $messageComposer);
|
||||||
|
}
|
||||||
|
|
||||||
|
public function search(Request $request): JsonResponse
|
||||||
|
{
|
||||||
|
$search = trim((string) $request->query('q', ''));
|
||||||
|
$like = '%'.str_replace(['%', '_'], ['\%', '\_'], $search).'%';
|
||||||
|
|
||||||
|
$contacts = Contact::query()
|
||||||
|
->with('phoneNumbers')
|
||||||
|
->search($search)
|
||||||
|
->orderByDesc('is_favorite')
|
||||||
|
->orderBy('last_name')
|
||||||
|
->orderBy('first_name')
|
||||||
|
->limit(10)
|
||||||
|
->get()
|
||||||
|
->map(function (Contact $contact): array {
|
||||||
|
$primaryPhone = $contact->phoneNumbers->firstWhere('is_primary', true)
|
||||||
|
?? $contact->phoneNumbers->first();
|
||||||
|
|
||||||
|
return [
|
||||||
|
'type' => 'contact',
|
||||||
|
'id' => $contact->id,
|
||||||
|
'label' => $contact->displayName(),
|
||||||
|
'meta' => $primaryPhone?->normalized_number
|
||||||
|
?: $primaryPhone?->raw_number
|
||||||
|
?: $contact->email
|
||||||
|
?: ucfirst($contact->source),
|
||||||
|
'source' => $contact->source,
|
||||||
|
'is_favorite' => $contact->is_favorite,
|
||||||
|
];
|
||||||
|
});
|
||||||
|
|
||||||
|
$groups = ContactGroup::query()
|
||||||
|
->withCount('contacts')
|
||||||
|
->when($search !== '', function ($query) use ($like): void {
|
||||||
|
$query->where(function ($query) use ($like): void {
|
||||||
|
$query
|
||||||
|
->where('name', 'like', $like)
|
||||||
|
->orWhere('description', 'like', $like);
|
||||||
|
});
|
||||||
|
})
|
||||||
|
->orderByDesc('is_favorite')
|
||||||
|
->orderBy('name')
|
||||||
|
->limit(10)
|
||||||
|
->get()
|
||||||
|
->map(fn (ContactGroup $group): array => [
|
||||||
|
'type' => 'group',
|
||||||
|
'id' => $group->id,
|
||||||
|
'label' => $group->name,
|
||||||
|
'meta' => $group->contacts_count.' contact(s)',
|
||||||
|
'source' => $group->source,
|
||||||
|
'is_favorite' => $group->is_favorite,
|
||||||
|
]);
|
||||||
|
|
||||||
|
return response()->json([
|
||||||
|
'results' => $groups->concat($contacts)->values(),
|
||||||
|
]);
|
||||||
|
}
|
||||||
|
|
||||||
|
public function preview(Request $request, RecipientResolver $resolver, SmsMessageComposer $messageComposer): View|RedirectResponse
|
||||||
|
{
|
||||||
|
$validated = $request->validate([
|
||||||
|
'q' => ['nullable', 'string', 'max:255'],
|
||||||
|
'message' => ['nullable', 'string', 'max:612'],
|
||||||
|
'include_sms_header' => ['nullable', 'boolean'],
|
||||||
|
'include_sms_footer' => ['nullable', 'boolean'],
|
||||||
|
'contact_ids' => ['array'],
|
||||||
|
'contact_ids.*' => ['integer', Rule::exists('contacts', 'id')->whereNull('deleted_at')],
|
||||||
|
'group_ids' => ['array'],
|
||||||
|
'group_ids.*' => ['integer', Rule::exists('contact_groups', 'id')->whereNull('deleted_at')],
|
||||||
|
]);
|
||||||
|
|
||||||
|
$contactIds = $validated['contact_ids'] ?? [];
|
||||||
|
$groupIds = $validated['group_ids'] ?? [];
|
||||||
|
|
||||||
|
if ($contactIds === [] && $groupIds === []) {
|
||||||
|
return redirect()
|
||||||
|
->route('recipients.index', ['q' => $validated['q'] ?? null])
|
||||||
|
->withErrors(['selection' => 'Selectionnez au moins un contact ou un groupe.'])
|
||||||
|
->withInput();
|
||||||
|
}
|
||||||
|
|
||||||
|
return $this->view(
|
||||||
|
$request,
|
||||||
|
$resolver->resolve($contactIds, $groupIds),
|
||||||
|
$contactIds,
|
||||||
|
$groupIds,
|
||||||
|
$messageComposer,
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* @param array<int, int|string> $selectedContactIds
|
||||||
|
* @param array<int, int|string> $selectedGroupIds
|
||||||
|
*/
|
||||||
|
private function view(
|
||||||
|
Request $request,
|
||||||
|
?RecipientResolutionResult $resolution = null,
|
||||||
|
array $selectedContactIds = [],
|
||||||
|
array $selectedGroupIds = [],
|
||||||
|
?SmsMessageComposer $messageComposer = null,
|
||||||
|
): View {
|
||||||
|
$messageComposer ??= app(SmsMessageComposer::class);
|
||||||
|
$messageSettings = $messageComposer->settings();
|
||||||
|
$oldHeaderChoice = $request->old('include_sms_header');
|
||||||
|
$oldFooterChoice = $request->old('include_sms_footer');
|
||||||
|
$hasHeaderChoice = $oldHeaderChoice !== null || $request->has('include_sms_header');
|
||||||
|
$hasFooterChoice = $oldFooterChoice !== null || $request->has('include_sms_footer');
|
||||||
|
$includeHeader = $hasHeaderChoice
|
||||||
|
? filter_var($oldHeaderChoice ?? $request->input('include_sms_header'), FILTER_VALIDATE_BOOLEAN)
|
||||||
|
: $messageSettings['header'] !== '';
|
||||||
|
$includeFooter = $hasFooterChoice
|
||||||
|
? filter_var($oldFooterChoice ?? $request->input('include_sms_footer'), FILTER_VALIDATE_BOOLEAN)
|
||||||
|
: $messageSettings['footer'] !== '';
|
||||||
|
$messageBody = (string) $request->old('message', $request->input('message', ''));
|
||||||
|
|
||||||
|
$search = trim((string) $request->input('q', ''));
|
||||||
|
$like = '%'.str_replace(['%', '_'], ['\%', '\_'], $search).'%';
|
||||||
|
|
||||||
|
$contacts = Contact::query()
|
||||||
|
->with(['groups', 'phoneNumbers'])
|
||||||
|
->search($search)
|
||||||
|
->orderByDesc('is_favorite')
|
||||||
|
->orderBy('last_name')
|
||||||
|
->orderBy('first_name')
|
||||||
|
->limit(50)
|
||||||
|
->get();
|
||||||
|
|
||||||
|
$groups = ContactGroup::query()
|
||||||
|
->withCount('contacts')
|
||||||
|
->when($search !== '', function ($query) use ($like): void {
|
||||||
|
$query->where(function ($query) use ($like): void {
|
||||||
|
$query
|
||||||
|
->where('name', 'like', $like)
|
||||||
|
->orWhere('description', 'like', $like);
|
||||||
|
});
|
||||||
|
})
|
||||||
|
->orderByDesc('is_favorite')
|
||||||
|
->orderBy('name')
|
||||||
|
->limit(50)
|
||||||
|
->get();
|
||||||
|
|
||||||
|
return view('recipients.index', [
|
||||||
|
'contacts' => $contacts,
|
||||||
|
'groups' => $groups,
|
||||||
|
'search' => $search,
|
||||||
|
'selectedContactIds' => collect($selectedContactIds)->map(fn (int|string $id): int => (int) $id)->all(),
|
||||||
|
'selectedGroupIds' => collect($selectedGroupIds)->map(fn (int|string $id): int => (int) $id)->all(),
|
||||||
|
'selectedContacts' => Contact::query()
|
||||||
|
->whereKey($selectedContactIds)
|
||||||
|
->orderBy('last_name')
|
||||||
|
->orderBy('first_name')
|
||||||
|
->get(),
|
||||||
|
'selectedGroups' => ContactGroup::query()
|
||||||
|
->whereKey($selectedGroupIds)
|
||||||
|
->orderBy('name')
|
||||||
|
->get(),
|
||||||
|
'resolution' => $resolution,
|
||||||
|
'smsHeader' => $messageSettings['header'],
|
||||||
|
'smsFooter' => $messageSettings['footer'],
|
||||||
|
'includeSmsHeader' => $includeHeader,
|
||||||
|
'includeSmsFooter' => $includeFooter,
|
||||||
|
'composedMessage' => $messageComposer->compose($messageBody, $includeHeader, $includeFooter),
|
||||||
|
]);
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,34 @@
|
|||||||
|
<?php
|
||||||
|
|
||||||
|
namespace App\Http\Controllers;
|
||||||
|
|
||||||
|
use App\Models\AppSetting;
|
||||||
|
use Illuminate\Contracts\View\View;
|
||||||
|
use Illuminate\Http\RedirectResponse;
|
||||||
|
use Illuminate\Http\Request;
|
||||||
|
|
||||||
|
class SettingsController extends Controller
|
||||||
|
{
|
||||||
|
public function edit(): View
|
||||||
|
{
|
||||||
|
return view('settings.edit', [
|
||||||
|
'smsHeader' => AppSetting::string('sms_message_header'),
|
||||||
|
'smsFooter' => AppSetting::string('sms_message_footer'),
|
||||||
|
]);
|
||||||
|
}
|
||||||
|
|
||||||
|
public function update(Request $request): RedirectResponse
|
||||||
|
{
|
||||||
|
$validated = $request->validate([
|
||||||
|
'sms_message_header' => ['nullable', 'string', 'max:612'],
|
||||||
|
'sms_message_footer' => ['nullable', 'string', 'max:612'],
|
||||||
|
]);
|
||||||
|
|
||||||
|
AppSetting::putString('sms_message_header', trim((string) ($validated['sms_message_header'] ?? '')));
|
||||||
|
AppSetting::putString('sms_message_footer', trim((string) ($validated['sms_message_footer'] ?? '')));
|
||||||
|
|
||||||
|
return redirect()
|
||||||
|
->route('settings.edit')
|
||||||
|
->with('status', 'Parametres enregistres.');
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,287 @@
|
|||||||
|
<?php
|
||||||
|
|
||||||
|
namespace App\Http\Controllers;
|
||||||
|
|
||||||
|
use App\Models\ContactGroup;
|
||||||
|
use App\Models\SmsCampaign;
|
||||||
|
use App\Models\User;
|
||||||
|
use App\Services\Recipients\RecipientResolver;
|
||||||
|
use App\Services\Sms\SmsCampaignSender;
|
||||||
|
use App\Services\Sms\SmsMessageComposer;
|
||||||
|
use Illuminate\Contracts\View\View;
|
||||||
|
use Illuminate\Database\Eloquent\Builder;
|
||||||
|
use Illuminate\Http\RedirectResponse;
|
||||||
|
use Illuminate\Http\Request;
|
||||||
|
use Illuminate\Support\Carbon;
|
||||||
|
use Illuminate\Support\Facades\DB;
|
||||||
|
use Illuminate\Validation\Rule;
|
||||||
|
use Symfony\Component\HttpFoundation\StreamedResponse;
|
||||||
|
|
||||||
|
class SmsCampaignController extends Controller
|
||||||
|
{
|
||||||
|
private const STATUSES = [
|
||||||
|
'draft' => 'Brouillon',
|
||||||
|
'scheduled' => 'Programme',
|
||||||
|
'sending' => 'Envoi',
|
||||||
|
'uncertain' => 'A verifier',
|
||||||
|
'sent' => 'Envoye',
|
||||||
|
'partial' => 'Partiel',
|
||||||
|
'failed' => 'Echec',
|
||||||
|
'canceled' => 'Annule',
|
||||||
|
];
|
||||||
|
|
||||||
|
public function index(Request $request): View
|
||||||
|
{
|
||||||
|
$filters = $this->validateFilters($request);
|
||||||
|
|
||||||
|
return view('sms-campaigns.index', [
|
||||||
|
'campaigns' => $this->filteredCampaignsQuery($filters)
|
||||||
|
->latest()
|
||||||
|
->paginate(20)
|
||||||
|
->withQueryString(),
|
||||||
|
'filters' => $filters,
|
||||||
|
'groups' => ContactGroup::query()->orderBy('name')->get(['id', 'name']),
|
||||||
|
'statuses' => self::STATUSES,
|
||||||
|
'users' => User::query()->orderBy('name')->get(['id', 'name']),
|
||||||
|
]);
|
||||||
|
}
|
||||||
|
|
||||||
|
public function show(SmsCampaign $smsCampaign): View
|
||||||
|
{
|
||||||
|
return view('sms-campaigns.show', [
|
||||||
|
'campaign' => $smsCampaign->load(['deliveries' => fn ($query) => $query->orderBy('id'), 'user']),
|
||||||
|
]);
|
||||||
|
}
|
||||||
|
|
||||||
|
public function export(Request $request): StreamedResponse
|
||||||
|
{
|
||||||
|
$filters = $this->validateFilters($request);
|
||||||
|
$query = $this->filteredCampaignsQuery($filters)
|
||||||
|
->with(['deliveries' => fn ($query) => $query->orderBy('id')])
|
||||||
|
->latest();
|
||||||
|
|
||||||
|
return response()->streamDownload(function () use ($query): void {
|
||||||
|
$csv = fopen('php://output', 'w');
|
||||||
|
|
||||||
|
fputcsv($csv, [
|
||||||
|
'campagne_id',
|
||||||
|
'date_creation',
|
||||||
|
'date_programmee',
|
||||||
|
'date_envoi',
|
||||||
|
'utilisateur',
|
||||||
|
'statut_campagne',
|
||||||
|
'groupes_selectionnes',
|
||||||
|
'message',
|
||||||
|
'destinataires_prevus',
|
||||||
|
'destinataires_envoyes',
|
||||||
|
'destinataires_echoues',
|
||||||
|
'contact',
|
||||||
|
'numero',
|
||||||
|
'statut_destinataire',
|
||||||
|
'message_fournisseur_id',
|
||||||
|
'erreur',
|
||||||
|
], ';');
|
||||||
|
|
||||||
|
$query->chunk(100, function ($campaigns) use ($csv): void {
|
||||||
|
foreach ($campaigns as $campaign) {
|
||||||
|
foreach ($campaign->deliveries as $delivery) {
|
||||||
|
fputcsv($csv, [
|
||||||
|
$campaign->id,
|
||||||
|
$campaign->created_at->format('Y-m-d H:i:s'),
|
||||||
|
$campaign->scheduled_at?->format('Y-m-d H:i:s'),
|
||||||
|
$campaign->sent_at?->format('Y-m-d H:i:s'),
|
||||||
|
$campaign->user?->name ?: 'Utilisateur supprime',
|
||||||
|
self::STATUSES[$campaign->status] ?? $campaign->status,
|
||||||
|
implode(', ', $campaign->selected_group_names ?? []),
|
||||||
|
$campaign->message,
|
||||||
|
$campaign->recipients_count,
|
||||||
|
$campaign->sent_count,
|
||||||
|
$campaign->failed_count,
|
||||||
|
$delivery->contact_name,
|
||||||
|
$delivery->number,
|
||||||
|
$delivery->status,
|
||||||
|
$delivery->provider_message_id,
|
||||||
|
$delivery->error_message,
|
||||||
|
], ';');
|
||||||
|
}
|
||||||
|
}
|
||||||
|
});
|
||||||
|
}, 'historique-sms-'.now()->format('Ymd-His').'.csv', [
|
||||||
|
'Content-Type' => 'text/csv; charset=UTF-8',
|
||||||
|
]);
|
||||||
|
}
|
||||||
|
|
||||||
|
public function store(
|
||||||
|
Request $request,
|
||||||
|
RecipientResolver $resolver,
|
||||||
|
SmsCampaignSender $sender,
|
||||||
|
SmsMessageComposer $messageComposer,
|
||||||
|
): RedirectResponse {
|
||||||
|
$validated = $request->validate([
|
||||||
|
'message' => ['required', 'string', 'min:1', 'max:612'],
|
||||||
|
'include_sms_header' => ['nullable', 'boolean'],
|
||||||
|
'include_sms_footer' => ['nullable', 'boolean'],
|
||||||
|
'contact_ids' => ['array'],
|
||||||
|
'contact_ids.*' => ['integer', Rule::exists('contacts', 'id')->whereNull('deleted_at')],
|
||||||
|
'group_ids' => ['array'],
|
||||||
|
'group_ids.*' => ['integer', Rule::exists('contact_groups', 'id')->whereNull('deleted_at')],
|
||||||
|
'send_mode' => ['nullable', Rule::in(['now', 'scheduled'])],
|
||||||
|
'scheduled_at' => ['nullable', 'date'],
|
||||||
|
]);
|
||||||
|
|
||||||
|
$contactIds = $validated['contact_ids'] ?? [];
|
||||||
|
$groupIds = $validated['group_ids'] ?? [];
|
||||||
|
$resolution = $resolver->resolve($contactIds, $groupIds);
|
||||||
|
$recipients = $resolution->recipients;
|
||||||
|
$maxRecipients = (int) config('relais_sms.default_settings.max_sms_per_campaign', 100);
|
||||||
|
$messageSettings = $messageComposer->settings();
|
||||||
|
$message = $messageComposer->compose(
|
||||||
|
(string) $validated['message'],
|
||||||
|
$request->has('include_sms_header') ? $request->boolean('include_sms_header') : $messageSettings['header'] !== '',
|
||||||
|
$request->has('include_sms_footer') ? $request->boolean('include_sms_footer') : $messageSettings['footer'] !== '',
|
||||||
|
);
|
||||||
|
|
||||||
|
if ($recipients === []) {
|
||||||
|
return redirect()
|
||||||
|
->route('recipients.index')
|
||||||
|
->withErrors(['selection' => 'Aucun numero valide a envoyer.'])
|
||||||
|
->withInput();
|
||||||
|
}
|
||||||
|
|
||||||
|
if (mb_strlen($message) > 612) {
|
||||||
|
return redirect()
|
||||||
|
->route('recipients.index')
|
||||||
|
->withErrors(['message' => 'Le message complet avec entete et pied depasse 612 caracteres.'])
|
||||||
|
->withInput();
|
||||||
|
}
|
||||||
|
|
||||||
|
if (count($recipients) > $maxRecipients) {
|
||||||
|
return redirect()
|
||||||
|
->route('recipients.index')
|
||||||
|
->withErrors(['selection' => 'La selection depasse la limite de '.$maxRecipients.' SMS.'])
|
||||||
|
->withInput();
|
||||||
|
}
|
||||||
|
|
||||||
|
if (($validated['send_mode'] ?? 'now') === 'scheduled') {
|
||||||
|
if (! (bool) config('relais_sms.default_settings.scheduled_sends_enabled', true)) {
|
||||||
|
return redirect()
|
||||||
|
->route('recipients.index')
|
||||||
|
->withErrors(['scheduled_at' => 'Les envois programmes sont desactives.'])
|
||||||
|
->withInput();
|
||||||
|
}
|
||||||
|
|
||||||
|
if (($validated['scheduled_at'] ?? null) === null) {
|
||||||
|
return redirect()
|
||||||
|
->route('recipients.index')
|
||||||
|
->withErrors(['scheduled_at' => 'La date et l heure d envoi sont obligatoires pour programmer un SMS.'])
|
||||||
|
->withInput();
|
||||||
|
}
|
||||||
|
|
||||||
|
$scheduledAt = Carbon::parse((string) $validated['scheduled_at'], $this->scheduledTimezone())->utc();
|
||||||
|
|
||||||
|
if ($scheduledAt->lte(now())) {
|
||||||
|
return redirect()
|
||||||
|
->route('recipients.index')
|
||||||
|
->withErrors(['scheduled_at' => 'La date et l heure d envoi doivent etre futures.'])
|
||||||
|
->withInput();
|
||||||
|
}
|
||||||
|
|
||||||
|
$campaign = $sender->schedule($request->user(), $message, $recipients, $contactIds, $groupIds, $scheduledAt);
|
||||||
|
|
||||||
|
return redirect()
|
||||||
|
->route('sms-campaigns.show', $campaign)
|
||||||
|
->with('status', 'Campagne programmee pour le '.$campaign->scheduled_at?->timezone($this->scheduledTimezone())->format('d/m/Y H:i').'.');
|
||||||
|
}
|
||||||
|
|
||||||
|
$campaign = $sender->send($request->user(), $message, $recipients, $contactIds, $groupIds);
|
||||||
|
|
||||||
|
if ($campaign->status === 'uncertain') {
|
||||||
|
return redirect()->route('sms-campaigns.show', $campaign)->with('status', $campaign->error_message);
|
||||||
|
}
|
||||||
|
|
||||||
|
return redirect()
|
||||||
|
->route('sms-campaigns.show', $campaign)
|
||||||
|
->with(
|
||||||
|
$campaign->status === 'failed' ? 'error' : 'status',
|
||||||
|
$campaign->status === 'failed'
|
||||||
|
? 'Envoi refuse ou echoue : '.$campaign->error_message
|
||||||
|
: 'Campagne envoyee a '.$campaign->sent_count.' destinataire(s).',
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
public function cancel(SmsCampaign $smsCampaign): RedirectResponse
|
||||||
|
{
|
||||||
|
$canceled = DB::transaction(function () use ($smsCampaign): bool {
|
||||||
|
$campaign = SmsCampaign::query()
|
||||||
|
->whereKey($smsCampaign->id)
|
||||||
|
->lockForUpdate()
|
||||||
|
->first();
|
||||||
|
|
||||||
|
if (! $campaign || $campaign->status !== 'scheduled') {
|
||||||
|
return false;
|
||||||
|
}
|
||||||
|
|
||||||
|
$campaign->update([
|
||||||
|
'status' => 'canceled',
|
||||||
|
'canceled_at' => now(),
|
||||||
|
]);
|
||||||
|
|
||||||
|
$campaign->deliveries()
|
||||||
|
->where('status', 'queued')
|
||||||
|
->update(['status' => 'canceled']);
|
||||||
|
|
||||||
|
return true;
|
||||||
|
});
|
||||||
|
|
||||||
|
return redirect()
|
||||||
|
->route('sms-campaigns.show', $smsCampaign)
|
||||||
|
->with(
|
||||||
|
$canceled ? 'status' : 'error',
|
||||||
|
$canceled
|
||||||
|
? 'Campagne programmee annulee.'
|
||||||
|
: 'Cette campagne ne peut plus etre annulee.',
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* @return array{from?: string|null, to?: string|null, status?: string|null, user_id?: string|null, group_id?: string|null}
|
||||||
|
*/
|
||||||
|
private function validateFilters(Request $request): array
|
||||||
|
{
|
||||||
|
return $request->validate([
|
||||||
|
'from' => ['nullable', 'date'],
|
||||||
|
'to' => ['nullable', 'date'],
|
||||||
|
'status' => ['nullable', Rule::in(array_keys(self::STATUSES))],
|
||||||
|
'user_id' => ['nullable', 'integer', Rule::exists('users', 'id')],
|
||||||
|
'group_id' => ['nullable', 'integer', Rule::exists('contact_groups', 'id')->whereNull('deleted_at')],
|
||||||
|
]);
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* @param array{from?: string|null, to?: string|null, status?: string|null, user_id?: string|null, group_id?: string|null} $filters
|
||||||
|
* @return Builder<SmsCampaign>
|
||||||
|
*/
|
||||||
|
private function filteredCampaignsQuery(array $filters): Builder
|
||||||
|
{
|
||||||
|
return SmsCampaign::query()
|
||||||
|
->with('user')
|
||||||
|
->when($filters['from'] ?? null, fn (Builder $query, string $date): Builder => $query->whereDate('created_at', '>=', $date))
|
||||||
|
->when($filters['to'] ?? null, fn (Builder $query, string $date): Builder => $query->whereDate('created_at', '<=', $date))
|
||||||
|
->when($filters['status'] ?? null, fn (Builder $query, string $status): Builder => $query->where('status', $status))
|
||||||
|
->when($filters['user_id'] ?? null, fn (Builder $query, string $userId): Builder => $query->where('user_id', (int) $userId))
|
||||||
|
->when($filters['group_id'] ?? null, function (Builder $query, string $groupId): Builder {
|
||||||
|
$groupId = (int) $groupId;
|
||||||
|
|
||||||
|
return $query->where(function (Builder $query) use ($groupId): void {
|
||||||
|
$query
|
||||||
|
->whereJsonContains('selected_group_ids', $groupId)
|
||||||
|
->orWhereHas('deliveries.contact.groups', fn (Builder $query): Builder => $query->where('contact_groups.id', $groupId));
|
||||||
|
});
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
|
private function scheduledTimezone(): string
|
||||||
|
{
|
||||||
|
return (string) config('relais_sms.default_settings.display_timezone', 'Europe/Paris');
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,34 @@
|
|||||||
|
<?php
|
||||||
|
|
||||||
|
namespace App\Models;
|
||||||
|
|
||||||
|
use Illuminate\Database\Eloquent\Attributes\Fillable;
|
||||||
|
use Illuminate\Database\Eloquent\Model;
|
||||||
|
|
||||||
|
#[Fillable(['key', 'value', 'type'])]
|
||||||
|
class AppSetting extends Model
|
||||||
|
{
|
||||||
|
public static function string(string $key, string $default = ''): string
|
||||||
|
{
|
||||||
|
$setting = self::query()->where('key', $key)->first();
|
||||||
|
|
||||||
|
if ($setting === null) {
|
||||||
|
$configured = config('relais_sms.default_settings.'.$key);
|
||||||
|
|
||||||
|
return is_string($configured) ? $configured : $default;
|
||||||
|
}
|
||||||
|
|
||||||
|
return (string) $setting->value;
|
||||||
|
}
|
||||||
|
|
||||||
|
public static function putString(string $key, string $value): void
|
||||||
|
{
|
||||||
|
self::query()->updateOrCreate(
|
||||||
|
['key' => $key],
|
||||||
|
[
|
||||||
|
'value' => $value,
|
||||||
|
'type' => 'string',
|
||||||
|
],
|
||||||
|
);
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,43 @@
|
|||||||
|
<?php
|
||||||
|
|
||||||
|
namespace App\Models;
|
||||||
|
|
||||||
|
use Illuminate\Database\Eloquent\Attributes\Fillable;
|
||||||
|
use Illuminate\Database\Eloquent\Model;
|
||||||
|
use Illuminate\Database\Eloquent\Relations\HasMany;
|
||||||
|
|
||||||
|
#[Fillable([
|
||||||
|
'source',
|
||||||
|
'external_id',
|
||||||
|
'remote_url',
|
||||||
|
'remote_etag',
|
||||||
|
'summary',
|
||||||
|
'description',
|
||||||
|
'location',
|
||||||
|
'starts_at',
|
||||||
|
'ends_at',
|
||||||
|
'attendees',
|
||||||
|
'synced_at',
|
||||||
|
'deleted_at',
|
||||||
|
])]
|
||||||
|
class CalendarEvent extends Model
|
||||||
|
{
|
||||||
|
/**
|
||||||
|
* @return HasMany<CalendarReminder, $this>
|
||||||
|
*/
|
||||||
|
public function reminders(): HasMany
|
||||||
|
{
|
||||||
|
return $this->hasMany(CalendarReminder::class);
|
||||||
|
}
|
||||||
|
|
||||||
|
protected function casts(): array
|
||||||
|
{
|
||||||
|
return [
|
||||||
|
'starts_at' => 'datetime',
|
||||||
|
'ends_at' => 'datetime',
|
||||||
|
'attendees' => 'array',
|
||||||
|
'synced_at' => 'datetime',
|
||||||
|
'deleted_at' => 'datetime',
|
||||||
|
];
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,45 @@
|
|||||||
|
<?php
|
||||||
|
|
||||||
|
namespace App\Models;
|
||||||
|
|
||||||
|
use Illuminate\Database\Eloquent\Attributes\Fillable;
|
||||||
|
use Illuminate\Database\Eloquent\Model;
|
||||||
|
use Illuminate\Database\Eloquent\Relations\BelongsTo;
|
||||||
|
|
||||||
|
#[Fillable([
|
||||||
|
'calendar_event_id',
|
||||||
|
'sms_campaign_id',
|
||||||
|
'reminder_key',
|
||||||
|
'action',
|
||||||
|
'trigger_minutes',
|
||||||
|
'remind_at',
|
||||||
|
'status',
|
||||||
|
'last_error',
|
||||||
|
'sent_at',
|
||||||
|
])]
|
||||||
|
class CalendarReminder extends Model
|
||||||
|
{
|
||||||
|
/**
|
||||||
|
* @return BelongsTo<CalendarEvent, $this>
|
||||||
|
*/
|
||||||
|
public function event(): BelongsTo
|
||||||
|
{
|
||||||
|
return $this->belongsTo(CalendarEvent::class, 'calendar_event_id');
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* @return BelongsTo<SmsCampaign, $this>
|
||||||
|
*/
|
||||||
|
public function smsCampaign(): BelongsTo
|
||||||
|
{
|
||||||
|
return $this->belongsTo(SmsCampaign::class);
|
||||||
|
}
|
||||||
|
|
||||||
|
protected function casts(): array
|
||||||
|
{
|
||||||
|
return [
|
||||||
|
'remind_at' => 'datetime',
|
||||||
|
'sent_at' => 'datetime',
|
||||||
|
];
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,94 @@
|
|||||||
|
<?php
|
||||||
|
|
||||||
|
namespace App\Models;
|
||||||
|
|
||||||
|
use Illuminate\Database\Eloquent\Attributes\Fillable;
|
||||||
|
use Illuminate\Database\Eloquent\Attributes\Scope;
|
||||||
|
use Illuminate\Database\Eloquent\Builder;
|
||||||
|
use Illuminate\Database\Eloquent\Model;
|
||||||
|
use Illuminate\Database\Eloquent\Relations\BelongsToMany;
|
||||||
|
use Illuminate\Database\Eloquent\Relations\HasMany;
|
||||||
|
use Illuminate\Database\Eloquent\SoftDeletes;
|
||||||
|
|
||||||
|
#[Fillable([
|
||||||
|
'source',
|
||||||
|
'external_id',
|
||||||
|
'remote_url',
|
||||||
|
'remote_etag',
|
||||||
|
'first_name',
|
||||||
|
'last_name',
|
||||||
|
'organization',
|
||||||
|
'email',
|
||||||
|
'notes',
|
||||||
|
'sms_opt_out',
|
||||||
|
'is_favorite',
|
||||||
|
'synced_at',
|
||||||
|
])]
|
||||||
|
class Contact extends Model
|
||||||
|
{
|
||||||
|
use SoftDeletes;
|
||||||
|
|
||||||
|
/**
|
||||||
|
* @return HasMany<ContactPhoneNumber, $this>
|
||||||
|
*/
|
||||||
|
public function phoneNumbers(): HasMany
|
||||||
|
{
|
||||||
|
return $this->hasMany(ContactPhoneNumber::class);
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* @return BelongsToMany<ContactGroup, $this>
|
||||||
|
*/
|
||||||
|
public function groups(): BelongsToMany
|
||||||
|
{
|
||||||
|
return $this->belongsToMany(ContactGroup::class, 'contact_contact_group')
|
||||||
|
->withTimestamps();
|
||||||
|
}
|
||||||
|
|
||||||
|
public function displayName(): string
|
||||||
|
{
|
||||||
|
return trim(implode(' ', array_filter([$this->first_name, $this->last_name])));
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* @param Builder<Contact> $query
|
||||||
|
*/
|
||||||
|
#[Scope]
|
||||||
|
protected function search(Builder $query, ?string $term): void
|
||||||
|
{
|
||||||
|
$term = trim((string) $term);
|
||||||
|
|
||||||
|
if ($term === '') {
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
|
||||||
|
$like = '%'.str_replace(['%', '_'], ['\%', '\_'], $term).'%';
|
||||||
|
|
||||||
|
$query->where(function (Builder $query) use ($like): void {
|
||||||
|
$query
|
||||||
|
->where('first_name', 'like', $like)
|
||||||
|
->orWhere('last_name', 'like', $like)
|
||||||
|
->orWhere('organization', 'like', $like)
|
||||||
|
->orWhere('email', 'like', $like)
|
||||||
|
->orWhereHas('phoneNumbers', function (Builder $query) use ($like): void {
|
||||||
|
$query
|
||||||
|
->where('raw_number', 'like', $like)
|
||||||
|
->orWhere('normalized_number', 'like', $like);
|
||||||
|
});
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Get the attributes that should be cast.
|
||||||
|
*
|
||||||
|
* @return array<string, string>
|
||||||
|
*/
|
||||||
|
protected function casts(): array
|
||||||
|
{
|
||||||
|
return [
|
||||||
|
'sms_opt_out' => 'boolean',
|
||||||
|
'is_favorite' => 'boolean',
|
||||||
|
'synced_at' => 'datetime',
|
||||||
|
];
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,44 @@
|
|||||||
|
<?php
|
||||||
|
|
||||||
|
namespace App\Models;
|
||||||
|
|
||||||
|
use Illuminate\Database\Eloquent\Attributes\Fillable;
|
||||||
|
use Illuminate\Database\Eloquent\Model;
|
||||||
|
use Illuminate\Database\Eloquent\Relations\BelongsToMany;
|
||||||
|
use Illuminate\Database\Eloquent\SoftDeletes;
|
||||||
|
|
||||||
|
#[Fillable([
|
||||||
|
'source',
|
||||||
|
'external_id',
|
||||||
|
'name',
|
||||||
|
'slug',
|
||||||
|
'description',
|
||||||
|
'is_favorite',
|
||||||
|
'synced_at',
|
||||||
|
])]
|
||||||
|
class ContactGroup extends Model
|
||||||
|
{
|
||||||
|
use SoftDeletes;
|
||||||
|
|
||||||
|
/**
|
||||||
|
* @return BelongsToMany<Contact, $this>
|
||||||
|
*/
|
||||||
|
public function contacts(): BelongsToMany
|
||||||
|
{
|
||||||
|
return $this->belongsToMany(Contact::class, 'contact_contact_group')
|
||||||
|
->withTimestamps();
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Get the attributes that should be cast.
|
||||||
|
*
|
||||||
|
* @return array<string, string>
|
||||||
|
*/
|
||||||
|
protected function casts(): array
|
||||||
|
{
|
||||||
|
return [
|
||||||
|
'is_favorite' => 'boolean',
|
||||||
|
'synced_at' => 'datetime',
|
||||||
|
];
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,62 @@
|
|||||||
|
<?php
|
||||||
|
|
||||||
|
namespace App\Models;
|
||||||
|
|
||||||
|
use Illuminate\Database\Eloquent\Attributes\Fillable;
|
||||||
|
use Illuminate\Database\Eloquent\Model;
|
||||||
|
use Illuminate\Database\Eloquent\Relations\BelongsTo;
|
||||||
|
|
||||||
|
#[Fillable([
|
||||||
|
'contact_id',
|
||||||
|
'label',
|
||||||
|
'raw_number',
|
||||||
|
'normalized_number',
|
||||||
|
'country',
|
||||||
|
'is_valid',
|
||||||
|
'is_mobile',
|
||||||
|
'is_primary',
|
||||||
|
'validation_error',
|
||||||
|
])]
|
||||||
|
class ContactPhoneNumber extends Model
|
||||||
|
{
|
||||||
|
public function hasDetectedMobileNumber(): bool
|
||||||
|
{
|
||||||
|
if ($this->is_mobile) {
|
||||||
|
return true;
|
||||||
|
}
|
||||||
|
|
||||||
|
$normalizedNumber = (string) $this->normalized_number;
|
||||||
|
|
||||||
|
if (preg_match('/^\+33[67]\d{8}$/', $normalizedNumber) === 1) {
|
||||||
|
return true;
|
||||||
|
}
|
||||||
|
|
||||||
|
$rawDigits = preg_replace('/\D+/', '', (string) $this->raw_number) ?? '';
|
||||||
|
|
||||||
|
return preg_match('/^0[67]\d{8}$/', $rawDigits) === 1
|
||||||
|
|| preg_match('/^33[67]\d{8}$/', $rawDigits) === 1
|
||||||
|
|| preg_match('/^0033[67]\d{8}$/', $rawDigits) === 1;
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* @return BelongsTo<Contact, $this>
|
||||||
|
*/
|
||||||
|
public function contact(): BelongsTo
|
||||||
|
{
|
||||||
|
return $this->belongsTo(Contact::class);
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Get the attributes that should be cast.
|
||||||
|
*
|
||||||
|
* @return array<string, string>
|
||||||
|
*/
|
||||||
|
protected function casts(): array
|
||||||
|
{
|
||||||
|
return [
|
||||||
|
'is_valid' => 'boolean',
|
||||||
|
'is_mobile' => 'boolean',
|
||||||
|
'is_primary' => 'boolean',
|
||||||
|
];
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,62 @@
|
|||||||
|
<?php
|
||||||
|
|
||||||
|
namespace App\Models;
|
||||||
|
|
||||||
|
use Illuminate\Database\Eloquent\Attributes\Fillable;
|
||||||
|
use Illuminate\Database\Eloquent\Model;
|
||||||
|
use Illuminate\Database\Eloquent\Relations\BelongsTo;
|
||||||
|
use Illuminate\Database\Eloquent\Relations\HasMany;
|
||||||
|
|
||||||
|
#[Fillable([
|
||||||
|
'user_id',
|
||||||
|
'provider',
|
||||||
|
'status',
|
||||||
|
'message',
|
||||||
|
'recipients_count',
|
||||||
|
'selected_contact_ids',
|
||||||
|
'selected_group_ids',
|
||||||
|
'selected_group_names',
|
||||||
|
'sent_count',
|
||||||
|
'failed_count',
|
||||||
|
'provider_service_name',
|
||||||
|
'provider_tag',
|
||||||
|
'provider_job_id',
|
||||||
|
'request_payload',
|
||||||
|
'response_payload',
|
||||||
|
'error_message',
|
||||||
|
'scheduled_at',
|
||||||
|
'sent_at',
|
||||||
|
'canceled_at',
|
||||||
|
])]
|
||||||
|
class SmsCampaign extends Model
|
||||||
|
{
|
||||||
|
/**
|
||||||
|
* @return BelongsTo<User, $this>
|
||||||
|
*/
|
||||||
|
public function user(): BelongsTo
|
||||||
|
{
|
||||||
|
return $this->belongsTo(User::class);
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* @return HasMany<SmsDelivery, $this>
|
||||||
|
*/
|
||||||
|
public function deliveries(): HasMany
|
||||||
|
{
|
||||||
|
return $this->hasMany(SmsDelivery::class);
|
||||||
|
}
|
||||||
|
|
||||||
|
protected function casts(): array
|
||||||
|
{
|
||||||
|
return [
|
||||||
|
'request_payload' => 'array',
|
||||||
|
'response_payload' => 'array',
|
||||||
|
'selected_contact_ids' => 'array',
|
||||||
|
'selected_group_ids' => 'array',
|
||||||
|
'selected_group_names' => 'array',
|
||||||
|
'scheduled_at' => 'datetime',
|
||||||
|
'sent_at' => 'datetime',
|
||||||
|
'canceled_at' => 'datetime',
|
||||||
|
];
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,54 @@
|
|||||||
|
<?php
|
||||||
|
|
||||||
|
namespace App\Models;
|
||||||
|
|
||||||
|
use Illuminate\Database\Eloquent\Attributes\Fillable;
|
||||||
|
use Illuminate\Database\Eloquent\Model;
|
||||||
|
use Illuminate\Database\Eloquent\Relations\BelongsTo;
|
||||||
|
|
||||||
|
#[Fillable([
|
||||||
|
'sms_campaign_id',
|
||||||
|
'contact_id',
|
||||||
|
'contact_phone_number_id',
|
||||||
|
'contact_name',
|
||||||
|
'number',
|
||||||
|
'status',
|
||||||
|
'provider_message_id',
|
||||||
|
'provider_response',
|
||||||
|
'error_message',
|
||||||
|
'sent_at',
|
||||||
|
])]
|
||||||
|
class SmsDelivery extends Model
|
||||||
|
{
|
||||||
|
/**
|
||||||
|
* @return BelongsTo<SmsCampaign, $this>
|
||||||
|
*/
|
||||||
|
public function campaign(): BelongsTo
|
||||||
|
{
|
||||||
|
return $this->belongsTo(SmsCampaign::class, 'sms_campaign_id');
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* @return BelongsTo<Contact, $this>
|
||||||
|
*/
|
||||||
|
public function contact(): BelongsTo
|
||||||
|
{
|
||||||
|
return $this->belongsTo(Contact::class);
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* @return BelongsTo<ContactPhoneNumber, $this>
|
||||||
|
*/
|
||||||
|
public function phoneNumber(): BelongsTo
|
||||||
|
{
|
||||||
|
return $this->belongsTo(ContactPhoneNumber::class, 'contact_phone_number_id');
|
||||||
|
}
|
||||||
|
|
||||||
|
protected function casts(): array
|
||||||
|
{
|
||||||
|
return [
|
||||||
|
'provider_response' => 'array',
|
||||||
|
'sent_at' => 'datetime',
|
||||||
|
];
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,33 @@
|
|||||||
|
<?php
|
||||||
|
|
||||||
|
namespace App\Models;
|
||||||
|
|
||||||
|
use Illuminate\Database\Eloquent\Attributes\Fillable;
|
||||||
|
use Illuminate\Database\Eloquent\Model;
|
||||||
|
|
||||||
|
#[Fillable([
|
||||||
|
'source',
|
||||||
|
'status',
|
||||||
|
'started_at',
|
||||||
|
'finished_at',
|
||||||
|
'fetched_contacts',
|
||||||
|
'synced_contacts',
|
||||||
|
'deleted_contacts',
|
||||||
|
'message',
|
||||||
|
'error',
|
||||||
|
])]
|
||||||
|
class SourceSyncRun extends Model
|
||||||
|
{
|
||||||
|
/**
|
||||||
|
* Get the attributes that should be cast.
|
||||||
|
*
|
||||||
|
* @return array<string, string>
|
||||||
|
*/
|
||||||
|
protected function casts(): array
|
||||||
|
{
|
||||||
|
return [
|
||||||
|
'started_at' => 'datetime',
|
||||||
|
'finished_at' => 'datetime',
|
||||||
|
];
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,32 @@
|
|||||||
|
<?php
|
||||||
|
|
||||||
|
namespace App\Models;
|
||||||
|
|
||||||
|
// use Illuminate\Contracts\Auth\MustVerifyEmail;
|
||||||
|
use Database\Factories\UserFactory;
|
||||||
|
use Illuminate\Database\Eloquent\Attributes\Fillable;
|
||||||
|
use Illuminate\Database\Eloquent\Attributes\Hidden;
|
||||||
|
use Illuminate\Database\Eloquent\Factories\HasFactory;
|
||||||
|
use Illuminate\Foundation\Auth\User as Authenticatable;
|
||||||
|
use Illuminate\Notifications\Notifiable;
|
||||||
|
|
||||||
|
#[Fillable(['name', 'email', 'password'])]
|
||||||
|
#[Hidden(['password', 'remember_token'])]
|
||||||
|
class User extends Authenticatable
|
||||||
|
{
|
||||||
|
/** @use HasFactory<UserFactory> */
|
||||||
|
use HasFactory, Notifiable;
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Get the attributes that should be cast.
|
||||||
|
*
|
||||||
|
* @return array<string, string>
|
||||||
|
*/
|
||||||
|
protected function casts(): array
|
||||||
|
{
|
||||||
|
return [
|
||||||
|
'email_verified_at' => 'datetime',
|
||||||
|
'password' => 'hashed',
|
||||||
|
];
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,40 @@
|
|||||||
|
<?php
|
||||||
|
|
||||||
|
namespace App\Providers;
|
||||||
|
|
||||||
|
use App\Contracts\Calendar\CalendarClientInterface;
|
||||||
|
use App\Contracts\CardDav\CardDavClientInterface;
|
||||||
|
use App\Contracts\PhoneNumberNormalizerInterface;
|
||||||
|
use App\Contracts\Sms\SmsProviderInterface;
|
||||||
|
use App\Services\Calendar\CalDavCalendarClient;
|
||||||
|
use App\Services\CardDav\CardDavClient;
|
||||||
|
use App\Services\Phone\LibPhoneNumberNormalizer;
|
||||||
|
use App\Services\Sms\OvhSmsProvider;
|
||||||
|
use GuzzleHttp\Client;
|
||||||
|
use GuzzleHttp\ClientInterface;
|
||||||
|
use Illuminate\Support\ServiceProvider;
|
||||||
|
use libphonenumber\PhoneNumberUtil;
|
||||||
|
|
||||||
|
class AppServiceProvider extends ServiceProvider
|
||||||
|
{
|
||||||
|
/**
|
||||||
|
* Register any application services.
|
||||||
|
*/
|
||||||
|
public function register(): void
|
||||||
|
{
|
||||||
|
$this->app->singleton(PhoneNumberUtil::class, fn (): PhoneNumberUtil => PhoneNumberUtil::getInstance());
|
||||||
|
$this->app->bind(PhoneNumberNormalizerInterface::class, LibPhoneNumberNormalizer::class);
|
||||||
|
$this->app->singleton(ClientInterface::class, fn (): ClientInterface => new Client);
|
||||||
|
$this->app->bind(CardDavClientInterface::class, CardDavClient::class);
|
||||||
|
$this->app->bind(CalendarClientInterface::class, CalDavCalendarClient::class);
|
||||||
|
$this->app->bind(SmsProviderInterface::class, OvhSmsProvider::class);
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Bootstrap any application services.
|
||||||
|
*/
|
||||||
|
public function boot(): void
|
||||||
|
{
|
||||||
|
//
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,232 @@
|
|||||||
|
<?php
|
||||||
|
|
||||||
|
namespace App\Services\Calendar;
|
||||||
|
|
||||||
|
use App\Contracts\Calendar\CalendarClientInterface;
|
||||||
|
use Carbon\CarbonInterface;
|
||||||
|
use GuzzleHttp\ClientInterface;
|
||||||
|
use GuzzleHttp\Exception\GuzzleException;
|
||||||
|
use RuntimeException;
|
||||||
|
use SimpleXMLElement;
|
||||||
|
use Throwable;
|
||||||
|
|
||||||
|
class CalDavCalendarClient implements CalendarClientInterface
|
||||||
|
{
|
||||||
|
public function __construct(
|
||||||
|
private readonly ClientInterface $http,
|
||||||
|
) {}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* @return array<int, CalendarRemoteEvent>
|
||||||
|
*/
|
||||||
|
public function fetchEvents(CarbonInterface $from, CarbonInterface $to): array
|
||||||
|
{
|
||||||
|
try {
|
||||||
|
$events = $this->fetchEventsWithReport($from, $to);
|
||||||
|
|
||||||
|
if ($events !== []) {
|
||||||
|
return $events;
|
||||||
|
}
|
||||||
|
} catch (GuzzleException|RuntimeException) {
|
||||||
|
// Some CalDAV servers restrict calendar-query. Fall back to PROPFIND + GET.
|
||||||
|
}
|
||||||
|
|
||||||
|
return $this->fetchEventsWithPropfind();
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* @return array<int, CalendarRemoteEvent>
|
||||||
|
*/
|
||||||
|
private function fetchEventsWithReport(CarbonInterface $from, CarbonInterface $to): array
|
||||||
|
{
|
||||||
|
$url = rtrim((string) config('relais_sms.caldav.url'), '/').'/';
|
||||||
|
$username = (string) config('relais_sms.caldav.username');
|
||||||
|
$password = (string) config('relais_sms.caldav.password');
|
||||||
|
|
||||||
|
$this->ensureConfigured($url, $username, $password);
|
||||||
|
|
||||||
|
$response = $this->http->request('REPORT', $url, [
|
||||||
|
'auth' => [$username, $password],
|
||||||
|
'headers' => [
|
||||||
|
'Content-Type' => 'application/xml; charset=utf-8',
|
||||||
|
'Depth' => '1',
|
||||||
|
],
|
||||||
|
'body' => $this->calendarQueryBody($from, $to),
|
||||||
|
'timeout' => (float) config('relais_sms.caldav.timeout'),
|
||||||
|
]);
|
||||||
|
|
||||||
|
return $this->parseReport((string) $response->getBody());
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* @return array<int, CalendarRemoteEvent>
|
||||||
|
*/
|
||||||
|
private function fetchEventsWithPropfind(): array
|
||||||
|
{
|
||||||
|
$url = rtrim((string) config('relais_sms.caldav.url'), '/').'/';
|
||||||
|
$username = (string) config('relais_sms.caldav.username');
|
||||||
|
$password = (string) config('relais_sms.caldav.password');
|
||||||
|
|
||||||
|
$this->ensureConfigured($url, $username, $password);
|
||||||
|
|
||||||
|
$response = $this->http->request('PROPFIND', $url, [
|
||||||
|
'auth' => [$username, $password],
|
||||||
|
'headers' => [
|
||||||
|
'Content-Type' => 'application/xml; charset=utf-8',
|
||||||
|
'Depth' => '1',
|
||||||
|
],
|
||||||
|
'body' => <<<'XML'
|
||||||
|
<?xml version="1.0" encoding="utf-8" ?>
|
||||||
|
<d:propfind xmlns:d="DAV:">
|
||||||
|
<d:prop>
|
||||||
|
<d:getetag />
|
||||||
|
</d:prop>
|
||||||
|
</d:propfind>
|
||||||
|
XML,
|
||||||
|
'timeout' => (float) config('relais_sms.caldav.timeout'),
|
||||||
|
]);
|
||||||
|
|
||||||
|
$entries = $this->parsePropfind((string) $response->getBody(), $url);
|
||||||
|
$events = [];
|
||||||
|
|
||||||
|
foreach ($entries as $entry) {
|
||||||
|
$eventResponse = $this->http->request('GET', $entry['url'], [
|
||||||
|
'auth' => [$username, $password],
|
||||||
|
'headers' => [
|
||||||
|
'Accept' => 'text/calendar,text/plain,*/*',
|
||||||
|
],
|
||||||
|
'timeout' => (float) config('relais_sms.caldav.timeout'),
|
||||||
|
]);
|
||||||
|
|
||||||
|
$events[] = new CalendarRemoteEvent(
|
||||||
|
href: $entry['href'],
|
||||||
|
etag: $entry['etag'],
|
||||||
|
ical: (string) $eventResponse->getBody(),
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
return $events;
|
||||||
|
}
|
||||||
|
|
||||||
|
private function ensureConfigured(string $url, string $username, string $password): void
|
||||||
|
{
|
||||||
|
if ($url === '/' || $username === '' || $password === '') {
|
||||||
|
throw new RuntimeException('Configuration CalDAV agenda incomplete.');
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
private function calendarQueryBody(CarbonInterface $from, CarbonInterface $to): string
|
||||||
|
{
|
||||||
|
$start = $from->copy()->utc()->format('Ymd\THis\Z');
|
||||||
|
$end = $to->copy()->utc()->format('Ymd\THis\Z');
|
||||||
|
|
||||||
|
return <<<XML
|
||||||
|
<?xml version="1.0" encoding="utf-8" ?>
|
||||||
|
<c:calendar-query xmlns:d="DAV:" xmlns:c="urn:ietf:params:xml:ns:caldav">
|
||||||
|
<d:prop>
|
||||||
|
<d:getetag />
|
||||||
|
<c:calendar-data />
|
||||||
|
</d:prop>
|
||||||
|
<c:filter>
|
||||||
|
<c:comp-filter name="VCALENDAR">
|
||||||
|
<c:comp-filter name="VEVENT">
|
||||||
|
<c:time-range start="$start" end="$end" />
|
||||||
|
</c:comp-filter>
|
||||||
|
</c:comp-filter>
|
||||||
|
</c:filter>
|
||||||
|
</c:calendar-query>
|
||||||
|
XML;
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* @return array<int, CalendarRemoteEvent>
|
||||||
|
*/
|
||||||
|
private function parseReport(string $xml): array
|
||||||
|
{
|
||||||
|
try {
|
||||||
|
$document = new SimpleXMLElement($xml);
|
||||||
|
} catch (Throwable $exception) {
|
||||||
|
throw new RuntimeException('Reponse CalDAV REPORT illisible.', previous: $exception);
|
||||||
|
}
|
||||||
|
|
||||||
|
$document->registerXPathNamespace('d', 'DAV:');
|
||||||
|
$responses = $document->xpath('//d:response') ?: [];
|
||||||
|
$events = [];
|
||||||
|
|
||||||
|
foreach ($responses as $response) {
|
||||||
|
$response->registerXPathNamespace('d', 'DAV:');
|
||||||
|
$response->registerXPathNamespace('c', 'urn:ietf:params:xml:ns:caldav');
|
||||||
|
|
||||||
|
$hrefNodes = $response->xpath('./d:href') ?: [];
|
||||||
|
$calendarDataNodes = $response->xpath('.//c:calendar-data') ?: [];
|
||||||
|
$href = trim((string) ($hrefNodes[0] ?? ''));
|
||||||
|
$ical = (string) ($calendarDataNodes[0] ?? '');
|
||||||
|
|
||||||
|
if ($href === '' || trim($ical) === '') {
|
||||||
|
continue;
|
||||||
|
}
|
||||||
|
|
||||||
|
$etagNodes = $response->xpath('.//d:getetag') ?: [];
|
||||||
|
$events[] = new CalendarRemoteEvent(
|
||||||
|
href: $href,
|
||||||
|
etag: trim((string) ($etagNodes[0] ?? ''), '"') ?: null,
|
||||||
|
ical: $ical,
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
return $events;
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* @return array<int, array{href: string, etag: ?string, url: string}>
|
||||||
|
*/
|
||||||
|
private function parsePropfind(string $xml, string $baseUrl): array
|
||||||
|
{
|
||||||
|
try {
|
||||||
|
$document = new SimpleXMLElement($xml);
|
||||||
|
} catch (Throwable $exception) {
|
||||||
|
throw new RuntimeException('Reponse CalDAV PROPFIND illisible.', previous: $exception);
|
||||||
|
}
|
||||||
|
|
||||||
|
$document->registerXPathNamespace('d', 'DAV:');
|
||||||
|
$responses = $document->xpath('//d:response') ?: [];
|
||||||
|
$entries = [];
|
||||||
|
|
||||||
|
foreach ($responses as $response) {
|
||||||
|
$response->registerXPathNamespace('d', 'DAV:');
|
||||||
|
$hrefNodes = $response->xpath('./d:href') ?: [];
|
||||||
|
$href = trim((string) ($hrefNodes[0] ?? ''));
|
||||||
|
|
||||||
|
if ($href === '' || ! str_ends_with(strtolower(parse_url($href, PHP_URL_PATH) ?: $href), '.ics')) {
|
||||||
|
continue;
|
||||||
|
}
|
||||||
|
|
||||||
|
$etagNodes = $response->xpath('.//d:getetag') ?: [];
|
||||||
|
$entries[] = [
|
||||||
|
'href' => $href,
|
||||||
|
'etag' => trim((string) ($etagNodes[0] ?? ''), '"') ?: null,
|
||||||
|
'url' => $this->absoluteUrl($baseUrl, $href),
|
||||||
|
];
|
||||||
|
}
|
||||||
|
|
||||||
|
return $entries;
|
||||||
|
}
|
||||||
|
|
||||||
|
private function absoluteUrl(string $baseUrl, string $href): string
|
||||||
|
{
|
||||||
|
if (parse_url($href, PHP_URL_SCHEME)) {
|
||||||
|
return $href;
|
||||||
|
}
|
||||||
|
|
||||||
|
$base = parse_url($baseUrl);
|
||||||
|
|
||||||
|
if (! isset($base['scheme'], $base['host'])) {
|
||||||
|
throw new RuntimeException('URL CalDAV agenda invalide.');
|
||||||
|
}
|
||||||
|
|
||||||
|
$port = isset($base['port']) ? ':'.$base['port'] : '';
|
||||||
|
$path = str_starts_with($href, '/') ? $href : rtrim((string) ($base['path'] ?? ''), '/').'/'.$href;
|
||||||
|
|
||||||
|
return $base['scheme'].'://'.$base['host'].$port.$path;
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,214 @@
|
|||||||
|
<?php
|
||||||
|
|
||||||
|
namespace App\Services\Calendar;
|
||||||
|
|
||||||
|
use App\Contracts\Calendar\CalendarClientInterface;
|
||||||
|
use App\Models\CalendarEvent;
|
||||||
|
use App\Models\CalendarReminder;
|
||||||
|
use App\Models\SourceSyncRun;
|
||||||
|
use Illuminate\Support\Carbon;
|
||||||
|
use Illuminate\Support\Facades\DB;
|
||||||
|
use Throwable;
|
||||||
|
|
||||||
|
class CalendarEventSyncService
|
||||||
|
{
|
||||||
|
public function __construct(
|
||||||
|
private readonly CalendarClientInterface $client,
|
||||||
|
private readonly ICalendarParser $parser,
|
||||||
|
) {}
|
||||||
|
|
||||||
|
public function sync(?Carbon $from = null, ?Carbon $to = null): SourceSyncRun
|
||||||
|
{
|
||||||
|
$from ??= Carbon::now()->subDay();
|
||||||
|
$to ??= Carbon::now()->addDays((int) config('relais_sms.caldav.lookahead_days', 90));
|
||||||
|
|
||||||
|
$run = SourceSyncRun::query()->create([
|
||||||
|
'source' => 'caldav_calendar',
|
||||||
|
'status' => 'running',
|
||||||
|
'started_at' => Carbon::now(),
|
||||||
|
]);
|
||||||
|
|
||||||
|
try {
|
||||||
|
$remoteEvents = $this->client->fetchEvents($from, $to);
|
||||||
|
|
||||||
|
DB::transaction(function () use ($run, $remoteEvents, $from, $to): void {
|
||||||
|
$seenExternalIds = [];
|
||||||
|
$syncedEvents = 0;
|
||||||
|
$scheduledReminders = 0;
|
||||||
|
|
||||||
|
foreach ($remoteEvents as $remoteEvent) {
|
||||||
|
foreach ($this->parser->parse($remoteEvent->ical, $from, $to) as $parsedEvent) {
|
||||||
|
$externalId = $parsedEvent->recurrenceId === null
|
||||||
|
? $parsedEvent->uid
|
||||||
|
: 'recurrence:'.sha1($parsedEvent->uid.'|'.$parsedEvent->recurrenceId->format('Y-m-d H:i:s'));
|
||||||
|
$seenExternalIds[] = $externalId;
|
||||||
|
|
||||||
|
$event = $this->upsertEvent($externalId, $remoteEvent, $parsedEvent);
|
||||||
|
$scheduledReminders += $this->syncReminders($event, $parsedEvent);
|
||||||
|
$syncedEvents++;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
$cancelledEvents = $this->cancelMissingEvents($seenExternalIds);
|
||||||
|
|
||||||
|
$run->update([
|
||||||
|
'status' => 'success',
|
||||||
|
'finished_at' => Carbon::now(),
|
||||||
|
'fetched_contacts' => count($remoteEvents),
|
||||||
|
'synced_contacts' => $syncedEvents,
|
||||||
|
'deleted_contacts' => $cancelledEvents,
|
||||||
|
'message' => $syncedEvents.' evenement(s) CalDAV synchronise(s), '.$scheduledReminders.' rappel(s) programme(s).',
|
||||||
|
]);
|
||||||
|
});
|
||||||
|
} catch (Throwable $exception) {
|
||||||
|
$run->update([
|
||||||
|
'status' => 'failed',
|
||||||
|
'finished_at' => Carbon::now(),
|
||||||
|
'error' => $exception->getMessage(),
|
||||||
|
]);
|
||||||
|
|
||||||
|
throw $exception;
|
||||||
|
}
|
||||||
|
|
||||||
|
return $run->refresh();
|
||||||
|
}
|
||||||
|
|
||||||
|
private function upsertEvent(string $externalId, CalendarRemoteEvent $remoteEvent, ParsedCalendarEvent $parsedEvent): CalendarEvent
|
||||||
|
{
|
||||||
|
$event = CalendarEvent::query()
|
||||||
|
->where('source', 'caldav')
|
||||||
|
->where('external_id', $externalId)
|
||||||
|
->first();
|
||||||
|
|
||||||
|
// Preserve the reminder history when an existing single event becomes a series.
|
||||||
|
if (! $event && $parsedEvent->recurrenceId !== null) {
|
||||||
|
$event = CalendarEvent::query()
|
||||||
|
->where('source', 'caldav')
|
||||||
|
->where('external_id', $parsedEvent->uid)
|
||||||
|
->where('starts_at', $parsedEvent->recurrenceId->format('Y-m-d H:i:s'))
|
||||||
|
->first();
|
||||||
|
}
|
||||||
|
|
||||||
|
$attributes = [
|
||||||
|
'source' => 'caldav',
|
||||||
|
'external_id' => $externalId,
|
||||||
|
'remote_url' => $remoteEvent->href,
|
||||||
|
'remote_etag' => $remoteEvent->etag,
|
||||||
|
'summary' => $parsedEvent->summary,
|
||||||
|
'description' => $parsedEvent->description,
|
||||||
|
'location' => $parsedEvent->location,
|
||||||
|
'starts_at' => $parsedEvent->startsAt,
|
||||||
|
'ends_at' => $parsedEvent->endsAt,
|
||||||
|
'attendees' => $parsedEvent->attendees,
|
||||||
|
'synced_at' => Carbon::now(),
|
||||||
|
'deleted_at' => null,
|
||||||
|
];
|
||||||
|
|
||||||
|
if (! $event) {
|
||||||
|
return CalendarEvent::query()->create($attributes);
|
||||||
|
}
|
||||||
|
|
||||||
|
$event->fill($attributes);
|
||||||
|
$event->save();
|
||||||
|
|
||||||
|
return $event;
|
||||||
|
}
|
||||||
|
|
||||||
|
private function syncReminders(CalendarEvent $event, ParsedCalendarEvent $parsedEvent): int
|
||||||
|
{
|
||||||
|
$seenReminderKeys = [];
|
||||||
|
$scheduledReminders = 0;
|
||||||
|
|
||||||
|
foreach ($parsedEvent->alarms as $index => $alarm) {
|
||||||
|
if ($alarm->action !== 'DISPLAY') {
|
||||||
|
continue;
|
||||||
|
}
|
||||||
|
|
||||||
|
$remindAt = $this->remindAt($parsedEvent, $alarm);
|
||||||
|
|
||||||
|
if ($remindAt === null) {
|
||||||
|
continue;
|
||||||
|
}
|
||||||
|
|
||||||
|
$reminderKey = sha1($alarm->action.'|'.$alarm->trigger.'|'.$index);
|
||||||
|
$seenReminderKeys[] = $reminderKey;
|
||||||
|
$reminder = CalendarReminder::query()
|
||||||
|
->where('calendar_event_id', $event->id)
|
||||||
|
->where('reminder_key', $reminderKey)
|
||||||
|
->first();
|
||||||
|
|
||||||
|
$attributes = [
|
||||||
|
'action' => $alarm->action,
|
||||||
|
'trigger_minutes' => $alarm->triggerMinutes,
|
||||||
|
'remind_at' => $remindAt,
|
||||||
|
];
|
||||||
|
|
||||||
|
if (! $reminder) {
|
||||||
|
CalendarReminder::query()->create(array_merge($attributes, [
|
||||||
|
'calendar_event_id' => $event->id,
|
||||||
|
'reminder_key' => $reminderKey,
|
||||||
|
'status' => 'pending',
|
||||||
|
]));
|
||||||
|
$scheduledReminders++;
|
||||||
|
|
||||||
|
continue;
|
||||||
|
}
|
||||||
|
|
||||||
|
if (! in_array($reminder->status, ['sent', 'sending', 'uncertain', 'skipped'], true)) {
|
||||||
|
$reminder->update(array_merge($attributes, [
|
||||||
|
'status' => 'pending',
|
||||||
|
'last_error' => null,
|
||||||
|
]));
|
||||||
|
$scheduledReminders++;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
CalendarReminder::query()
|
||||||
|
->where('calendar_event_id', $event->id)
|
||||||
|
->whereNotIn('reminder_key', $seenReminderKeys ?: [''])
|
||||||
|
->whereIn('status', ['pending', 'failed'])
|
||||||
|
->update([
|
||||||
|
'status' => 'cancelled',
|
||||||
|
'last_error' => 'Rappel absent de la derniere synchronisation.',
|
||||||
|
]);
|
||||||
|
|
||||||
|
return $scheduledReminders;
|
||||||
|
}
|
||||||
|
|
||||||
|
private function remindAt(ParsedCalendarEvent $event, ParsedCalendarAlarm $alarm): ?Carbon
|
||||||
|
{
|
||||||
|
if ($alarm->absoluteRemindAt !== null) {
|
||||||
|
return $alarm->absoluteRemindAt;
|
||||||
|
}
|
||||||
|
|
||||||
|
if ($event->startsAt === null || $alarm->triggerMinutes === null) {
|
||||||
|
return null;
|
||||||
|
}
|
||||||
|
|
||||||
|
return $event->startsAt->copy()->addMinutes($alarm->triggerMinutes);
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* @param array<int, string> $seenExternalIds
|
||||||
|
*/
|
||||||
|
private function cancelMissingEvents(array $seenExternalIds): int
|
||||||
|
{
|
||||||
|
$events = CalendarEvent::query()
|
||||||
|
->where('source', 'caldav')
|
||||||
|
->whereNull('deleted_at')
|
||||||
|
->whereNotIn('external_id', $seenExternalIds ?: [''])
|
||||||
|
->get();
|
||||||
|
|
||||||
|
foreach ($events as $event) {
|
||||||
|
$event->update(['deleted_at' => Carbon::now()]);
|
||||||
|
$event->reminders()
|
||||||
|
->whereIn('status', ['pending', 'failed'])
|
||||||
|
->update([
|
||||||
|
'status' => 'cancelled',
|
||||||
|
'last_error' => 'Evenement absent de la derniere synchronisation.',
|
||||||
|
]);
|
||||||
|
}
|
||||||
|
|
||||||
|
return $events->count();
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,82 @@
|
|||||||
|
<?php
|
||||||
|
|
||||||
|
namespace App\Services\Calendar;
|
||||||
|
|
||||||
|
use Carbon\CarbonInterface;
|
||||||
|
use DateTimeZone;
|
||||||
|
use RuntimeException;
|
||||||
|
use Sabre\VObject\Component\VCalendar;
|
||||||
|
use Sabre\VObject\Component\VEvent;
|
||||||
|
use Sabre\VObject\Reader;
|
||||||
|
|
||||||
|
class CalendarOccurrenceExpander
|
||||||
|
{
|
||||||
|
public function expand(string $ical, CarbonInterface $from, CarbonInterface $to): string
|
||||||
|
{
|
||||||
|
if (! preg_match('/^(RRULE|RDATE|RECURRENCE-ID)[;:]/mi', $ical)) {
|
||||||
|
return $ical;
|
||||||
|
}
|
||||||
|
|
||||||
|
$calendar = Reader::read($ical);
|
||||||
|
if (! $calendar instanceof VCalendar) {
|
||||||
|
throw new RuntimeException('La source agenda ne contient pas un calendrier iCalendar.');
|
||||||
|
}
|
||||||
|
|
||||||
|
$additionalDates = clone $calendar;
|
||||||
|
$additionalUids = [];
|
||||||
|
|
||||||
|
foreach ($calendar->select('VEVENT') as $event) {
|
||||||
|
// A cancelled detached occurrence may contain only UID and RECURRENCE-ID.
|
||||||
|
// It must still suppress the original occurrence during expansion.
|
||||||
|
if (! isset($event->DTSTART) && isset($event->{'RECURRENCE-ID'})) {
|
||||||
|
$start = clone $event->{'RECURRENCE-ID'};
|
||||||
|
$start->name = 'DTSTART';
|
||||||
|
$event->add($start);
|
||||||
|
}
|
||||||
|
|
||||||
|
// VObject chooses RDATE instead of RRULE when both are present.
|
||||||
|
// Expand their union separately, then deduplicate by occurrence identity.
|
||||||
|
if (isset($event->RRULE, $event->RDATE)) {
|
||||||
|
$additionalUids[] = (string) $event->UID;
|
||||||
|
unset($event->RDATE);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
$timezone = new DateTimeZone((string) config('app.timezone', 'UTC'));
|
||||||
|
$expanded = $calendar->expand($from, $to, $timezone);
|
||||||
|
|
||||||
|
if ($additionalUids !== []) {
|
||||||
|
foreach ($additionalDates->select('VEVENT') as $event) {
|
||||||
|
if (! in_array((string) $event->UID, $additionalUids, true)) {
|
||||||
|
$additionalDates->remove($event);
|
||||||
|
} else {
|
||||||
|
unset($event->RRULE);
|
||||||
|
if (! isset($event->DTSTART) && isset($event->{'RECURRENCE-ID'})) {
|
||||||
|
$start = clone $event->{'RECURRENCE-ID'};
|
||||||
|
$start->name = 'DTSTART';
|
||||||
|
$event->add($start);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
$seen = [];
|
||||||
|
foreach ($expanded->select('VEVENT') as $event) {
|
||||||
|
$seen[$this->identity($event)] = true;
|
||||||
|
}
|
||||||
|
foreach ($additionalDates->expand($from, $to, $timezone)->select('VEVENT') as $event) {
|
||||||
|
$key = $this->identity($event);
|
||||||
|
if (! isset($seen[$key])) {
|
||||||
|
$expanded->add(clone $event);
|
||||||
|
$seen[$key] = true;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
return $expanded->serialize();
|
||||||
|
}
|
||||||
|
|
||||||
|
private function identity(VEvent $event): string
|
||||||
|
{
|
||||||
|
return (string) $event->UID.'|'.(string) $event->{'RECURRENCE-ID'};
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,269 @@
|
|||||||
|
<?php
|
||||||
|
|
||||||
|
namespace App\Services\Calendar;
|
||||||
|
|
||||||
|
use App\Models\CalendarReminder;
|
||||||
|
use App\Models\Contact;
|
||||||
|
use App\Models\User;
|
||||||
|
use App\Services\Recipients\RecipientResolver;
|
||||||
|
use App\Services\Sms\SmsCampaignSender;
|
||||||
|
use App\Services\Sms\SmsMessageLength;
|
||||||
|
use Illuminate\Support\Carbon;
|
||||||
|
use Illuminate\Support\Facades\DB;
|
||||||
|
use Illuminate\Support\Str;
|
||||||
|
|
||||||
|
class CalendarReminderSender
|
||||||
|
{
|
||||||
|
public function __construct(
|
||||||
|
private readonly RecipientResolver $recipientResolver,
|
||||||
|
private readonly SmsCampaignSender $campaignSender,
|
||||||
|
private readonly SmsMessageLength $smsMessageLength,
|
||||||
|
) {}
|
||||||
|
|
||||||
|
public function sendDue(?Carbon $now = null, int $limit = 50): int
|
||||||
|
{
|
||||||
|
$now ??= Carbon::now();
|
||||||
|
$dueAt = $now->copy()->utc()->format('Y-m-d H:i:s');
|
||||||
|
$sent = 0;
|
||||||
|
|
||||||
|
CalendarReminder::query()
|
||||||
|
->with('event')
|
||||||
|
->where('status', 'pending')
|
||||||
|
->whereNotNull('remind_at')
|
||||||
|
->where('remind_at', '<=', $dueAt)
|
||||||
|
->orderBy('remind_at')
|
||||||
|
->limit($limit)
|
||||||
|
->get()
|
||||||
|
->each(function (CalendarReminder $reminder) use (&$sent, $now): void {
|
||||||
|
if ($this->sendReminder($reminder, $now)) {
|
||||||
|
$sent++;
|
||||||
|
}
|
||||||
|
});
|
||||||
|
|
||||||
|
return $sent;
|
||||||
|
}
|
||||||
|
|
||||||
|
private function sendReminder(CalendarReminder $reminder, Carbon $now): bool
|
||||||
|
{
|
||||||
|
$reminder = DB::transaction(function () use ($reminder): ?CalendarReminder {
|
||||||
|
$fresh = CalendarReminder::query()
|
||||||
|
->whereKey($reminder->id)
|
||||||
|
->lockForUpdate()
|
||||||
|
->first();
|
||||||
|
|
||||||
|
if (! $fresh || $fresh->status !== 'pending') {
|
||||||
|
return null;
|
||||||
|
}
|
||||||
|
|
||||||
|
$fresh->update(['status' => 'sending']);
|
||||||
|
|
||||||
|
return $fresh->load('event');
|
||||||
|
});
|
||||||
|
|
||||||
|
if (! $reminder || ! $reminder->event || $reminder->event->deleted_at !== null) {
|
||||||
|
return false;
|
||||||
|
}
|
||||||
|
|
||||||
|
$rawStartsAt = $reminder->event->getRawOriginal('starts_at');
|
||||||
|
$rawRemindAt = $reminder->getRawOriginal('remind_at');
|
||||||
|
|
||||||
|
if ($rawStartsAt !== null && $rawRemindAt !== null) {
|
||||||
|
$startsAt = Carbon::parse((string) $rawStartsAt, 'UTC');
|
||||||
|
$remindAt = Carbon::parse((string) $rawRemindAt, 'UTC');
|
||||||
|
|
||||||
|
if ($remindAt->lessThan($startsAt) && $startsAt->lessThanOrEqualTo($now)) {
|
||||||
|
$reminder->update([
|
||||||
|
'status' => 'skipped',
|
||||||
|
'last_error' => 'Rappel expire : evenement deja commence.',
|
||||||
|
]);
|
||||||
|
|
||||||
|
return false;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
$resolution = $this->recipientResolver->resolve(
|
||||||
|
$this->contactIdsForReminder($reminder),
|
||||||
|
$this->configuredIds('relais_sms.caldav.default_group_ids'),
|
||||||
|
);
|
||||||
|
|
||||||
|
if ($resolution->recipients === []) {
|
||||||
|
$reminder->update([
|
||||||
|
'status' => 'skipped',
|
||||||
|
'last_error' => 'Aucun destinataire SMS valide pour ce rappel.',
|
||||||
|
]);
|
||||||
|
|
||||||
|
return false;
|
||||||
|
}
|
||||||
|
|
||||||
|
$maxRecipients = (int) config('relais_sms.default_settings.max_sms_per_campaign', 100);
|
||||||
|
|
||||||
|
if (count($resolution->recipients) > $maxRecipients) {
|
||||||
|
$reminder->update([
|
||||||
|
'status' => 'failed',
|
||||||
|
'last_error' => 'La selection depasse la limite de '.$maxRecipients.' SMS.',
|
||||||
|
]);
|
||||||
|
|
||||||
|
return false;
|
||||||
|
}
|
||||||
|
|
||||||
|
$user = $this->user();
|
||||||
|
|
||||||
|
if ($user === null) {
|
||||||
|
$reminder->update([
|
||||||
|
'status' => 'failed',
|
||||||
|
'last_error' => 'Aucun utilisateur applicatif disponible.',
|
||||||
|
]);
|
||||||
|
|
||||||
|
return false;
|
||||||
|
}
|
||||||
|
|
||||||
|
$campaign = $this->campaignSender->send($user, $this->message($reminder), $resolution->recipients);
|
||||||
|
|
||||||
|
$reminder->update([
|
||||||
|
'sms_campaign_id' => $campaign->id,
|
||||||
|
'status' => in_array($campaign->status, ['failed', 'uncertain'], true) ? $campaign->status : 'sent',
|
||||||
|
'last_error' => $campaign->error_message,
|
||||||
|
'sent_at' => in_array($campaign->status, ['failed', 'uncertain'], true) ? null : Carbon::now(),
|
||||||
|
]);
|
||||||
|
|
||||||
|
return in_array($campaign->status, ['sent', 'partial'], true);
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* @return array<int, int>
|
||||||
|
*/
|
||||||
|
private function contactIdsForReminder(CalendarReminder $reminder): array
|
||||||
|
{
|
||||||
|
$ids = $this->configuredIds('relais_sms.caldav.default_contact_ids');
|
||||||
|
$attendeeEmails = collect($reminder->event->attendees ?? [])
|
||||||
|
->pluck('email')
|
||||||
|
->filter()
|
||||||
|
->map(fn (string $email): string => strtolower($email))
|
||||||
|
->unique()
|
||||||
|
->values()
|
||||||
|
->all();
|
||||||
|
|
||||||
|
if ($attendeeEmails !== []) {
|
||||||
|
$ids = array_merge($ids, Contact::query()
|
||||||
|
->whereIn(DB::raw('lower(email)'), $attendeeEmails)
|
||||||
|
->pluck('id')
|
||||||
|
->all());
|
||||||
|
}
|
||||||
|
|
||||||
|
return array_values(array_unique(array_map('intval', $ids)));
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* @return array<int, int>
|
||||||
|
*/
|
||||||
|
private function configuredIds(string $key): array
|
||||||
|
{
|
||||||
|
return collect(config($key, []))
|
||||||
|
->map(fn (mixed $id): int => (int) $id)
|
||||||
|
->filter(fn (int $id): bool => $id > 0)
|
||||||
|
->unique()
|
||||||
|
->values()
|
||||||
|
->all();
|
||||||
|
}
|
||||||
|
|
||||||
|
private function user(): ?User
|
||||||
|
{
|
||||||
|
$userId = (int) config('relais_sms.caldav.reminder_user_id');
|
||||||
|
|
||||||
|
if ($userId > 0) {
|
||||||
|
return User::query()->find($userId);
|
||||||
|
}
|
||||||
|
|
||||||
|
return User::query()->orderBy('id')->first();
|
||||||
|
}
|
||||||
|
|
||||||
|
private function message(CalendarReminder $reminder): string
|
||||||
|
{
|
||||||
|
$event = $reminder->event;
|
||||||
|
$rawStartsAt = $event->getRawOriginal('starts_at');
|
||||||
|
$startsAt = $rawStartsAt === null
|
||||||
|
? 'date inconnue'
|
||||||
|
: Carbon::parse((string) $rawStartsAt, 'UTC')
|
||||||
|
->timezone((string) config('relais_sms.caldav.display_timezone'))
|
||||||
|
->format('d/m/Y H:i');
|
||||||
|
$titlePrefix = 'Rappel : ';
|
||||||
|
$title = trim((string) ($event->summary ?: 'Evenement'));
|
||||||
|
$title = $this->smsMessageLength->truncateBetween(
|
||||||
|
$titlePrefix,
|
||||||
|
$title,
|
||||||
|
"\n".$startsAt,
|
||||||
|
);
|
||||||
|
$coreLines = [$titlePrefix.$title, $startsAt];
|
||||||
|
$header = '';
|
||||||
|
$footer = '';
|
||||||
|
|
||||||
|
$configuredHeader = trim($this->configuredText('relais_sms.caldav.reminder_message_header'));
|
||||||
|
if ($configuredHeader !== '' && $this->smsMessageLength->fitsInOneSms($this->assembleMessage($coreLines, $configuredHeader))) {
|
||||||
|
$header = $configuredHeader;
|
||||||
|
}
|
||||||
|
|
||||||
|
$configuredFooter = trim($this->configuredText('relais_sms.caldav.reminder_message_footer'));
|
||||||
|
if ($configuredFooter !== '' && $this->smsMessageLength->fitsInOneSms($this->assembleMessage($coreLines, $header, $configuredFooter))) {
|
||||||
|
$footer = $configuredFooter;
|
||||||
|
}
|
||||||
|
|
||||||
|
$location = trim(preg_replace('/\s+/', ' ', (string) $event->location) ?? '');
|
||||||
|
if ($location !== '' && $this->fitsWithOptionalParts($coreLines, [$location], $header, $footer)) {
|
||||||
|
$coreLines[] = $location;
|
||||||
|
}
|
||||||
|
|
||||||
|
$description = $this->description((string) $event->description);
|
||||||
|
if ($description !== '') {
|
||||||
|
$prefix = collect([$header, ...$coreLines])
|
||||||
|
->filter(fn (string $part): bool => $part !== '')
|
||||||
|
->implode("\n")."\n";
|
||||||
|
$suffix = $footer === '' ? '' : "\n".$footer;
|
||||||
|
$description = $this->smsMessageLength->truncateBetween($prefix, $description, $suffix);
|
||||||
|
|
||||||
|
if ($description !== '') {
|
||||||
|
$coreLines[] = $description;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
return $this->assembleMessage($coreLines, $header, $footer);
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* @param array<int, string> $coreLines
|
||||||
|
* @param array<int, string> $optionalLines
|
||||||
|
*/
|
||||||
|
private function fitsWithOptionalParts(array $coreLines, array $optionalLines, string $header, string $footer): bool
|
||||||
|
{
|
||||||
|
return $this->smsMessageLength->fitsInOneSms($this->assembleMessage([...$coreLines, ...$optionalLines], $header, $footer));
|
||||||
|
}
|
||||||
|
|
||||||
|
/** @param array<int, string> $coreLines */
|
||||||
|
private function assembleMessage(array $coreLines, string $header = '', string $footer = ''): string
|
||||||
|
{
|
||||||
|
return collect([
|
||||||
|
$header,
|
||||||
|
...$coreLines,
|
||||||
|
$footer,
|
||||||
|
])->map(fn (string $part): string => trim($part))
|
||||||
|
->filter()
|
||||||
|
->implode("\n");
|
||||||
|
}
|
||||||
|
|
||||||
|
private function description(string $description): string
|
||||||
|
{
|
||||||
|
$description = trim(preg_replace('/\s+/', ' ', $description) ?? '');
|
||||||
|
|
||||||
|
if ($description === '') {
|
||||||
|
return '';
|
||||||
|
}
|
||||||
|
|
||||||
|
$maxLength = max(1, (int) config('relais_sms.caldav.reminder_description_max_length', 120));
|
||||||
|
|
||||||
|
return Str::limit($description, $maxLength, '[...]');
|
||||||
|
}
|
||||||
|
|
||||||
|
private function configuredText(string $key): string
|
||||||
|
{
|
||||||
|
return str_replace('\n', "\n", (string) config($key, ''));
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,12 @@
|
|||||||
|
<?php
|
||||||
|
|
||||||
|
namespace App\Services\Calendar;
|
||||||
|
|
||||||
|
class CalendarRemoteEvent
|
||||||
|
{
|
||||||
|
public function __construct(
|
||||||
|
public readonly string $href,
|
||||||
|
public readonly ?string $etag,
|
||||||
|
public readonly string $ical,
|
||||||
|
) {}
|
||||||
|
}
|
||||||
@@ -0,0 +1,341 @@
|
|||||||
|
<?php
|
||||||
|
|
||||||
|
namespace App\Services\Calendar;
|
||||||
|
|
||||||
|
use Carbon\CarbonInterface;
|
||||||
|
use Illuminate\Support\Carbon;
|
||||||
|
|
||||||
|
class ICalendarParser
|
||||||
|
{
|
||||||
|
/**
|
||||||
|
* @return array<int, ParsedCalendarEvent>
|
||||||
|
*/
|
||||||
|
public function parse(string $ical, ?CarbonInterface $from = null, ?CarbonInterface $to = null): array
|
||||||
|
{
|
||||||
|
$ical = (new CalendarOccurrenceExpander)->expand(
|
||||||
|
$ical,
|
||||||
|
$from ?? Carbon::now()->subDay(),
|
||||||
|
$to ?? Carbon::now()->addDays((int) config('relais_sms.caldav.lookahead_days', 90)),
|
||||||
|
);
|
||||||
|
$lines = $this->unfoldLines($ical);
|
||||||
|
$events = [];
|
||||||
|
$eventLines = null;
|
||||||
|
$alarmLines = null;
|
||||||
|
$alarms = [];
|
||||||
|
|
||||||
|
foreach ($lines as $line) {
|
||||||
|
$upper = strtoupper($line);
|
||||||
|
|
||||||
|
if ($upper === 'BEGIN:VEVENT') {
|
||||||
|
$eventLines = [];
|
||||||
|
$alarms = [];
|
||||||
|
|
||||||
|
continue;
|
||||||
|
}
|
||||||
|
|
||||||
|
if ($upper === 'END:VEVENT') {
|
||||||
|
if ($eventLines !== null) {
|
||||||
|
$event = $this->parseEvent($eventLines, $alarms);
|
||||||
|
if (! $event->cancelled) {
|
||||||
|
$events[] = $event;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
$eventLines = null;
|
||||||
|
$alarmLines = null;
|
||||||
|
$alarms = [];
|
||||||
|
|
||||||
|
continue;
|
||||||
|
}
|
||||||
|
|
||||||
|
if ($eventLines === null) {
|
||||||
|
continue;
|
||||||
|
}
|
||||||
|
|
||||||
|
if ($upper === 'BEGIN:VALARM') {
|
||||||
|
$alarmLines = [];
|
||||||
|
|
||||||
|
continue;
|
||||||
|
}
|
||||||
|
|
||||||
|
if ($upper === 'END:VALARM') {
|
||||||
|
if ($alarmLines !== null) {
|
||||||
|
$alarms[] = $this->parseAlarm($alarmLines);
|
||||||
|
}
|
||||||
|
|
||||||
|
$alarmLines = null;
|
||||||
|
|
||||||
|
continue;
|
||||||
|
}
|
||||||
|
|
||||||
|
if ($alarmLines !== null) {
|
||||||
|
$alarmLines[] = $line;
|
||||||
|
|
||||||
|
continue;
|
||||||
|
}
|
||||||
|
|
||||||
|
$eventLines[] = $line;
|
||||||
|
}
|
||||||
|
|
||||||
|
return array_values(array_filter($events, fn (ParsedCalendarEvent $event): bool => $event->uid !== ''));
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* @param array<int, string> $lines
|
||||||
|
* @param array<int, ParsedCalendarAlarm> $alarms
|
||||||
|
*/
|
||||||
|
private function parseEvent(array $lines, array $alarms): ParsedCalendarEvent
|
||||||
|
{
|
||||||
|
$uid = '';
|
||||||
|
$summary = null;
|
||||||
|
$description = null;
|
||||||
|
$location = null;
|
||||||
|
$startsAt = null;
|
||||||
|
$endsAt = null;
|
||||||
|
$attendees = [];
|
||||||
|
$recurrenceId = null;
|
||||||
|
$cancelled = false;
|
||||||
|
|
||||||
|
foreach ($lines as $line) {
|
||||||
|
$property = $this->parseProperty($line);
|
||||||
|
$name = strtoupper($property['name']);
|
||||||
|
|
||||||
|
match ($name) {
|
||||||
|
'UID' => $uid = $this->decodeText($property['value']),
|
||||||
|
'SUMMARY' => $summary = $this->decodeText($property['value']),
|
||||||
|
'DESCRIPTION' => $description = $this->decodeText($property['value']),
|
||||||
|
'LOCATION' => $location = $this->decodeText($property['value']),
|
||||||
|
'DTSTART' => $startsAt = $this->parseDateTime($property['value'], $property['params']),
|
||||||
|
'DTEND' => $endsAt = $this->parseDateTime($property['value'], $property['params']),
|
||||||
|
'RECURRENCE-ID' => $recurrenceId = $this->parseDateTime($property['value'], $property['params']),
|
||||||
|
'STATUS' => $cancelled = strtoupper($property['value']) === 'CANCELLED',
|
||||||
|
'ATTENDEE', 'ORGANIZER' => $attendees[] = $this->parseAttendee($property['value'], $property['params']),
|
||||||
|
default => null,
|
||||||
|
};
|
||||||
|
}
|
||||||
|
|
||||||
|
return new ParsedCalendarEvent(
|
||||||
|
uid: $uid,
|
||||||
|
summary: $summary,
|
||||||
|
description: $description,
|
||||||
|
location: $location,
|
||||||
|
startsAt: $startsAt,
|
||||||
|
endsAt: $endsAt,
|
||||||
|
attendees: array_values(array_filter(
|
||||||
|
$attendees,
|
||||||
|
fn (array $attendee): bool => $attendee['email'] !== '',
|
||||||
|
)),
|
||||||
|
alarms: $alarms,
|
||||||
|
recurrenceId: $recurrenceId,
|
||||||
|
cancelled: $cancelled,
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* @param array<int, string> $lines
|
||||||
|
*/
|
||||||
|
private function parseAlarm(array $lines): ParsedCalendarAlarm
|
||||||
|
{
|
||||||
|
$action = '';
|
||||||
|
$trigger = '';
|
||||||
|
$triggerMinutes = null;
|
||||||
|
$absoluteRemindAt = null;
|
||||||
|
|
||||||
|
foreach ($lines as $line) {
|
||||||
|
$property = $this->parseProperty($line);
|
||||||
|
$name = strtoupper($property['name']);
|
||||||
|
|
||||||
|
if ($name === 'ACTION') {
|
||||||
|
$action = strtoupper($property['value']);
|
||||||
|
}
|
||||||
|
|
||||||
|
if ($name === 'TRIGGER') {
|
||||||
|
$trigger = $property['value'];
|
||||||
|
|
||||||
|
if (strtoupper((string) ($property['params']['VALUE'] ?? '')) === 'DATE-TIME') {
|
||||||
|
$absoluteRemindAt = $this->parseDateTime($property['value'], $property['params']);
|
||||||
|
} else {
|
||||||
|
$triggerMinutes = $this->parseDurationMinutes($property['value']);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
return new ParsedCalendarAlarm(
|
||||||
|
action: $action,
|
||||||
|
trigger: $trigger,
|
||||||
|
triggerMinutes: $triggerMinutes,
|
||||||
|
absoluteRemindAt: $absoluteRemindAt,
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* @return array{name: string, params: array<string, string>, value: string}
|
||||||
|
*/
|
||||||
|
private function parseProperty(string $line): array
|
||||||
|
{
|
||||||
|
[$left, $value] = $this->splitPropertyValue($line);
|
||||||
|
$parts = $this->splitOutsideQuotes($left, ';');
|
||||||
|
$name = array_shift($parts) ?: '';
|
||||||
|
$params = [];
|
||||||
|
|
||||||
|
foreach ($parts as $part) {
|
||||||
|
[$key, $paramValue] = array_pad(explode('=', $part, 2), 2, '');
|
||||||
|
|
||||||
|
if ($key !== '') {
|
||||||
|
$params[strtoupper($key)] = trim($paramValue, '"');
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
return [
|
||||||
|
'name' => $name,
|
||||||
|
'params' => $params,
|
||||||
|
'value' => $value,
|
||||||
|
];
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* A CalDAV parameter can contain a URI, for example
|
||||||
|
* MEMBER="mailto:circle+id@example.test". The colon in that quoted URI is
|
||||||
|
* not the separator between the property metadata and its value.
|
||||||
|
*
|
||||||
|
* @return array{string, string}
|
||||||
|
*/
|
||||||
|
private function splitPropertyValue(string $line): array
|
||||||
|
{
|
||||||
|
$quoted = false;
|
||||||
|
|
||||||
|
for ($index = 0, $length = strlen($line); $index < $length; $index++) {
|
||||||
|
if ($line[$index] === '"') {
|
||||||
|
$quoted = ! $quoted;
|
||||||
|
|
||||||
|
continue;
|
||||||
|
}
|
||||||
|
|
||||||
|
if ($line[$index] === ':' && ! $quoted) {
|
||||||
|
return [substr($line, 0, $index), substr($line, $index + 1)];
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
return [$line, ''];
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* @return array<int, string>
|
||||||
|
*/
|
||||||
|
private function splitOutsideQuotes(string $value, string $delimiter): array
|
||||||
|
{
|
||||||
|
$parts = [];
|
||||||
|
$part = '';
|
||||||
|
$quoted = false;
|
||||||
|
|
||||||
|
for ($index = 0, $length = strlen($value); $index < $length; $index++) {
|
||||||
|
$character = $value[$index];
|
||||||
|
|
||||||
|
if ($character === '"') {
|
||||||
|
$quoted = ! $quoted;
|
||||||
|
}
|
||||||
|
|
||||||
|
if ($character === $delimiter && ! $quoted) {
|
||||||
|
$parts[] = $part;
|
||||||
|
$part = '';
|
||||||
|
|
||||||
|
continue;
|
||||||
|
}
|
||||||
|
|
||||||
|
$part .= $character;
|
||||||
|
}
|
||||||
|
|
||||||
|
$parts[] = $part;
|
||||||
|
|
||||||
|
return $parts;
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* @param array<string, string> $params
|
||||||
|
* @return array{email: string, name: ?string}
|
||||||
|
*/
|
||||||
|
private function parseAttendee(string $value, array $params): array
|
||||||
|
{
|
||||||
|
$email = preg_replace('/^mailto:/i', '', trim($value)) ?? '';
|
||||||
|
|
||||||
|
return [
|
||||||
|
'email' => strtolower($email),
|
||||||
|
'name' => isset($params['CN']) ? $this->decodeText($params['CN']) : null,
|
||||||
|
];
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* @param array<string, string> $params
|
||||||
|
*/
|
||||||
|
private function parseDateTime(string $value, array $params): ?Carbon
|
||||||
|
{
|
||||||
|
$value = trim($value);
|
||||||
|
|
||||||
|
if ($value === '') {
|
||||||
|
return null;
|
||||||
|
}
|
||||||
|
|
||||||
|
$timezone = $params['TZID'] ?? config('app.timezone', 'UTC');
|
||||||
|
|
||||||
|
if (str_ends_with($value, 'Z')) {
|
||||||
|
return Carbon::createFromFormat('Ymd\THis\Z', $value, 'UTC')?->utc();
|
||||||
|
}
|
||||||
|
|
||||||
|
if (str_contains($value, 'T')) {
|
||||||
|
return Carbon::createFromFormat('Ymd\THis', $value, $timezone)?->utc();
|
||||||
|
}
|
||||||
|
|
||||||
|
return Carbon::createFromFormat('Ymd', $value, $timezone)?->startOfDay()->utc();
|
||||||
|
}
|
||||||
|
|
||||||
|
private function parseDurationMinutes(string $value): ?int
|
||||||
|
{
|
||||||
|
$value = strtoupper(trim($value));
|
||||||
|
|
||||||
|
if (! preg_match('/^([+-])?P(?:(\d+)D)?(?:T(?:(\d+)H)?(?:(\d+)M)?(?:(\d+)S)?)?$/', $value, $matches)) {
|
||||||
|
return null;
|
||||||
|
}
|
||||||
|
|
||||||
|
$sign = ($matches[1] ?? '') === '-' ? -1 : 1;
|
||||||
|
$days = (int) ($matches[2] ?? 0);
|
||||||
|
$hours = (int) ($matches[3] ?? 0);
|
||||||
|
$minutes = (int) ($matches[4] ?? 0);
|
||||||
|
$seconds = (int) ($matches[5] ?? 0);
|
||||||
|
|
||||||
|
return $sign * (($days * 24 * 60) + ($hours * 60) + $minutes + (int) ceil($seconds / 60));
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* @return array<int, string>
|
||||||
|
*/
|
||||||
|
private function unfoldLines(string $ical): array
|
||||||
|
{
|
||||||
|
$rawLines = preg_split('/\r\n|\n|\r/', $ical) ?: [];
|
||||||
|
$lines = [];
|
||||||
|
|
||||||
|
foreach ($rawLines as $line) {
|
||||||
|
if ($line === '') {
|
||||||
|
continue;
|
||||||
|
}
|
||||||
|
|
||||||
|
if ((str_starts_with($line, ' ') || str_starts_with($line, "\t")) && $lines !== []) {
|
||||||
|
$lines[array_key_last($lines)] .= substr($line, 1);
|
||||||
|
|
||||||
|
continue;
|
||||||
|
}
|
||||||
|
|
||||||
|
$lines[] = $line;
|
||||||
|
}
|
||||||
|
|
||||||
|
return $lines;
|
||||||
|
}
|
||||||
|
|
||||||
|
private function decodeText(string $value): string
|
||||||
|
{
|
||||||
|
return str_replace(
|
||||||
|
['\\n', '\\N', '\\,', '\\;', '\\\\'],
|
||||||
|
["\n", "\n", ',', ';', '\\'],
|
||||||
|
$value,
|
||||||
|
);
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,15 @@
|
|||||||
|
<?php
|
||||||
|
|
||||||
|
namespace App\Services\Calendar;
|
||||||
|
|
||||||
|
use Illuminate\Support\Carbon;
|
||||||
|
|
||||||
|
class ParsedCalendarAlarm
|
||||||
|
{
|
||||||
|
public function __construct(
|
||||||
|
public readonly string $action,
|
||||||
|
public readonly string $trigger,
|
||||||
|
public readonly ?int $triggerMinutes,
|
||||||
|
public readonly ?Carbon $absoluteRemindAt,
|
||||||
|
) {}
|
||||||
|
}
|
||||||
@@ -0,0 +1,25 @@
|
|||||||
|
<?php
|
||||||
|
|
||||||
|
namespace App\Services\Calendar;
|
||||||
|
|
||||||
|
use Illuminate\Support\Carbon;
|
||||||
|
|
||||||
|
class ParsedCalendarEvent
|
||||||
|
{
|
||||||
|
/**
|
||||||
|
* @param array<int, array{email: string, name: ?string}> $attendees
|
||||||
|
* @param array<int, ParsedCalendarAlarm> $alarms
|
||||||
|
*/
|
||||||
|
public function __construct(
|
||||||
|
public readonly string $uid,
|
||||||
|
public readonly ?string $summary,
|
||||||
|
public readonly ?string $description,
|
||||||
|
public readonly ?string $location,
|
||||||
|
public readonly ?Carbon $startsAt,
|
||||||
|
public readonly ?Carbon $endsAt,
|
||||||
|
public readonly array $attendees,
|
||||||
|
public readonly array $alarms,
|
||||||
|
public readonly ?Carbon $recurrenceId = null,
|
||||||
|
public readonly bool $cancelled = false,
|
||||||
|
) {}
|
||||||
|
}
|
||||||
@@ -0,0 +1,213 @@
|
|||||||
|
<?php
|
||||||
|
|
||||||
|
namespace App\Services\CardDav;
|
||||||
|
|
||||||
|
use App\Contracts\CardDav\CardDavClientInterface;
|
||||||
|
use GuzzleHttp\ClientInterface;
|
||||||
|
use GuzzleHttp\Exception\GuzzleException;
|
||||||
|
use RuntimeException;
|
||||||
|
use SimpleXMLElement;
|
||||||
|
use Throwable;
|
||||||
|
|
||||||
|
class CardDavClient implements CardDavClientInterface
|
||||||
|
{
|
||||||
|
public function __construct(
|
||||||
|
private readonly ClientInterface $http,
|
||||||
|
) {}
|
||||||
|
|
||||||
|
public function fetchCards(): array
|
||||||
|
{
|
||||||
|
try {
|
||||||
|
$cards = $this->fetchCardsWithReport();
|
||||||
|
|
||||||
|
if ($cards !== []) {
|
||||||
|
return $cards;
|
||||||
|
}
|
||||||
|
} catch (GuzzleException|RuntimeException) {
|
||||||
|
// Some CardDAV servers restrict addressbook-query. Fall back to PROPFIND + GET.
|
||||||
|
}
|
||||||
|
|
||||||
|
return $this->fetchCardsWithPropfind();
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* @return array<int, CardDavRemoteCard>
|
||||||
|
*/
|
||||||
|
private function fetchCardsWithReport(): array
|
||||||
|
{
|
||||||
|
$url = rtrim((string) config('relais_sms.carddav.url'), '/').'/';
|
||||||
|
$username = (string) config('relais_sms.carddav.username');
|
||||||
|
$password = (string) config('relais_sms.carddav.password');
|
||||||
|
|
||||||
|
$this->ensureConfigured($url, $username, $password);
|
||||||
|
|
||||||
|
$response = $this->http->request('REPORT', $url, [
|
||||||
|
'auth' => [$username, $password],
|
||||||
|
'headers' => [
|
||||||
|
'Content-Type' => 'application/xml; charset=utf-8',
|
||||||
|
'Depth' => '1',
|
||||||
|
],
|
||||||
|
'body' => <<<'XML'
|
||||||
|
<?xml version="1.0" encoding="utf-8" ?>
|
||||||
|
<c:addressbook-query xmlns:d="DAV:" xmlns:c="urn:ietf:params:xml:ns:carddav">
|
||||||
|
<d:prop>
|
||||||
|
<d:getetag />
|
||||||
|
<c:address-data />
|
||||||
|
</d:prop>
|
||||||
|
</c:addressbook-query>
|
||||||
|
XML,
|
||||||
|
'timeout' => (float) config('relais_sms.carddav.timeout'),
|
||||||
|
]);
|
||||||
|
|
||||||
|
return $this->parseReport((string) $response->getBody());
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* @return array<int, CardDavRemoteCard>
|
||||||
|
*/
|
||||||
|
private function fetchCardsWithPropfind(): array
|
||||||
|
{
|
||||||
|
$url = rtrim((string) config('relais_sms.carddav.url'), '/').'/';
|
||||||
|
$username = (string) config('relais_sms.carddav.username');
|
||||||
|
$password = (string) config('relais_sms.carddav.password');
|
||||||
|
|
||||||
|
$this->ensureConfigured($url, $username, $password);
|
||||||
|
|
||||||
|
$response = $this->http->request('PROPFIND', $url, [
|
||||||
|
'auth' => [$username, $password],
|
||||||
|
'headers' => [
|
||||||
|
'Content-Type' => 'application/xml; charset=utf-8',
|
||||||
|
'Depth' => '1',
|
||||||
|
],
|
||||||
|
'body' => <<<'XML'
|
||||||
|
<?xml version="1.0" encoding="utf-8" ?>
|
||||||
|
<d:propfind xmlns:d="DAV:">
|
||||||
|
<d:prop>
|
||||||
|
<d:getetag />
|
||||||
|
</d:prop>
|
||||||
|
</d:propfind>
|
||||||
|
XML,
|
||||||
|
'timeout' => (float) config('relais_sms.carddav.timeout'),
|
||||||
|
]);
|
||||||
|
|
||||||
|
$entries = $this->parsePropfind((string) $response->getBody(), $url);
|
||||||
|
$cards = [];
|
||||||
|
|
||||||
|
foreach ($entries as $entry) {
|
||||||
|
$cardResponse = $this->http->request('GET', $entry['url'], [
|
||||||
|
'auth' => [$username, $password],
|
||||||
|
'headers' => [
|
||||||
|
'Accept' => 'text/vcard,text/x-vcard,text/plain,*/*',
|
||||||
|
],
|
||||||
|
'timeout' => (float) config('relais_sms.carddav.timeout'),
|
||||||
|
]);
|
||||||
|
|
||||||
|
$cards[] = new CardDavRemoteCard(
|
||||||
|
href: $entry['href'],
|
||||||
|
etag: $entry['etag'],
|
||||||
|
vcard: (string) $cardResponse->getBody(),
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
return $cards;
|
||||||
|
}
|
||||||
|
|
||||||
|
private function ensureConfigured(string $url, string $username, string $password): void
|
||||||
|
{
|
||||||
|
if ($url === '/' || $username === '' || $password === '') {
|
||||||
|
throw new RuntimeException('Configuration CardDAV incomplete.');
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* @return array<int, CardDavRemoteCard>
|
||||||
|
*/
|
||||||
|
private function parseReport(string $xml): array
|
||||||
|
{
|
||||||
|
try {
|
||||||
|
$document = new SimpleXMLElement($xml);
|
||||||
|
} catch (Throwable $exception) {
|
||||||
|
throw new RuntimeException('Reponse CardDAV REPORT illisible.', previous: $exception);
|
||||||
|
}
|
||||||
|
|
||||||
|
$document->registerXPathNamespace('d', 'DAV:');
|
||||||
|
$responses = $document->xpath('//d:response') ?: [];
|
||||||
|
$cards = [];
|
||||||
|
|
||||||
|
foreach ($responses as $response) {
|
||||||
|
$response->registerXPathNamespace('d', 'DAV:');
|
||||||
|
$response->registerXPathNamespace('c', 'urn:ietf:params:xml:ns:carddav');
|
||||||
|
|
||||||
|
$hrefNodes = $response->xpath('./d:href') ?: [];
|
||||||
|
$cardNodes = $response->xpath('.//c:address-data') ?: [];
|
||||||
|
$href = trim((string) ($hrefNodes[0] ?? ''));
|
||||||
|
$vcard = (string) ($cardNodes[0] ?? '');
|
||||||
|
|
||||||
|
if ($href === '' || trim($vcard) === '') {
|
||||||
|
continue;
|
||||||
|
}
|
||||||
|
|
||||||
|
$etagNodes = $response->xpath('.//d:getetag') ?: [];
|
||||||
|
$cards[] = new CardDavRemoteCard(
|
||||||
|
href: $href,
|
||||||
|
etag: trim((string) ($etagNodes[0] ?? ''), '"') ?: null,
|
||||||
|
vcard: $vcard,
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
return $cards;
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* @return array<int, array{href: string, etag: ?string, url: string}>
|
||||||
|
*/
|
||||||
|
private function parsePropfind(string $xml, string $baseUrl): array
|
||||||
|
{
|
||||||
|
try {
|
||||||
|
$document = new SimpleXMLElement($xml);
|
||||||
|
} catch (Throwable $exception) {
|
||||||
|
throw new RuntimeException('Reponse CardDAV PROPFIND illisible.', previous: $exception);
|
||||||
|
}
|
||||||
|
|
||||||
|
$document->registerXPathNamespace('d', 'DAV:');
|
||||||
|
$responses = $document->xpath('//d:response') ?: [];
|
||||||
|
$entries = [];
|
||||||
|
|
||||||
|
foreach ($responses as $response) {
|
||||||
|
$response->registerXPathNamespace('d', 'DAV:');
|
||||||
|
$hrefNodes = $response->xpath('./d:href') ?: [];
|
||||||
|
$href = trim((string) ($hrefNodes[0] ?? ''));
|
||||||
|
|
||||||
|
if ($href === '' || ! str_ends_with(strtolower(parse_url($href, PHP_URL_PATH) ?: $href), '.vcf')) {
|
||||||
|
continue;
|
||||||
|
}
|
||||||
|
|
||||||
|
$etagNodes = $response->xpath('.//d:getetag') ?: [];
|
||||||
|
$entries[] = [
|
||||||
|
'href' => $href,
|
||||||
|
'etag' => trim((string) ($etagNodes[0] ?? ''), '"') ?: null,
|
||||||
|
'url' => $this->absoluteUrl($baseUrl, $href),
|
||||||
|
];
|
||||||
|
}
|
||||||
|
|
||||||
|
return $entries;
|
||||||
|
}
|
||||||
|
|
||||||
|
private function absoluteUrl(string $baseUrl, string $href): string
|
||||||
|
{
|
||||||
|
if (parse_url($href, PHP_URL_SCHEME)) {
|
||||||
|
return $href;
|
||||||
|
}
|
||||||
|
|
||||||
|
$base = parse_url($baseUrl);
|
||||||
|
|
||||||
|
if (! isset($base['scheme'], $base['host'])) {
|
||||||
|
throw new RuntimeException('URL CardDAV invalide.');
|
||||||
|
}
|
||||||
|
|
||||||
|
$port = isset($base['port']) ? ':'.$base['port'] : '';
|
||||||
|
$path = str_starts_with($href, '/') ? $href : rtrim((string) ($base['path'] ?? ''), '/').'/'.$href;
|
||||||
|
|
||||||
|
return $base['scheme'].'://'.$base['host'].$port.$path;
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,240 @@
|
|||||||
|
<?php
|
||||||
|
|
||||||
|
namespace App\Services\CardDav;
|
||||||
|
|
||||||
|
use App\Contracts\CardDav\CardDavClientInterface;
|
||||||
|
use App\Contracts\PhoneNumberNormalizerInterface;
|
||||||
|
use App\Models\Contact;
|
||||||
|
use App\Models\ContactGroup;
|
||||||
|
use App\Models\SourceSyncRun;
|
||||||
|
use Illuminate\Support\Carbon;
|
||||||
|
use Illuminate\Support\Facades\DB;
|
||||||
|
use Illuminate\Support\Str;
|
||||||
|
use Throwable;
|
||||||
|
|
||||||
|
class CardDavContactSyncService
|
||||||
|
{
|
||||||
|
public function __construct(
|
||||||
|
private readonly CardDavClientInterface $client,
|
||||||
|
private readonly VCardParser $parser,
|
||||||
|
private readonly PhoneNumberNormalizerInterface $phoneNumberNormalizer,
|
||||||
|
) {}
|
||||||
|
|
||||||
|
public function sync(): SourceSyncRun
|
||||||
|
{
|
||||||
|
$run = SourceSyncRun::query()->create([
|
||||||
|
'source' => 'carddav',
|
||||||
|
'status' => 'running',
|
||||||
|
'started_at' => Carbon::now(),
|
||||||
|
]);
|
||||||
|
|
||||||
|
try {
|
||||||
|
$cards = $this->client->fetchCards();
|
||||||
|
|
||||||
|
DB::transaction(function () use ($run, $cards): void {
|
||||||
|
$seenContactExternalIds = [];
|
||||||
|
$seenGroupExternalIds = [];
|
||||||
|
$syncedContacts = 0;
|
||||||
|
|
||||||
|
foreach ($cards as $card) {
|
||||||
|
$parsedCard = $this->parser->parse($card->vcard);
|
||||||
|
$externalId = $this->externalId($parsedCard, $card);
|
||||||
|
$seenContactExternalIds[] = $externalId;
|
||||||
|
|
||||||
|
$contact = $this->upsertContact($externalId, $card, $parsedCard);
|
||||||
|
$this->replacePhoneNumbers($contact, $parsedCard);
|
||||||
|
|
||||||
|
$groupIds = [];
|
||||||
|
|
||||||
|
foreach ($parsedCard->categories as $category) {
|
||||||
|
$group = $this->upsertGroup($category);
|
||||||
|
$groupIds[] = $group->id;
|
||||||
|
$seenGroupExternalIds[] = (string) $group->external_id;
|
||||||
|
}
|
||||||
|
|
||||||
|
$this->syncCardDavGroupMemberships($contact, $groupIds);
|
||||||
|
$syncedContacts++;
|
||||||
|
}
|
||||||
|
|
||||||
|
$deletedContacts = $this->deleteMissingContacts($seenContactExternalIds);
|
||||||
|
$this->deleteMissingGroups(array_values(array_unique($seenGroupExternalIds)));
|
||||||
|
|
||||||
|
$run->update([
|
||||||
|
'status' => 'success',
|
||||||
|
'finished_at' => Carbon::now(),
|
||||||
|
'fetched_contacts' => count($cards),
|
||||||
|
'synced_contacts' => $syncedContacts,
|
||||||
|
'deleted_contacts' => $deletedContacts,
|
||||||
|
'message' => $syncedContacts.' contact(s) CardDAV synchronise(s).',
|
||||||
|
]);
|
||||||
|
});
|
||||||
|
} catch (Throwable $exception) {
|
||||||
|
$run->update([
|
||||||
|
'status' => 'failed',
|
||||||
|
'finished_at' => Carbon::now(),
|
||||||
|
'error' => $exception->getMessage(),
|
||||||
|
]);
|
||||||
|
|
||||||
|
throw $exception;
|
||||||
|
}
|
||||||
|
|
||||||
|
return $run->refresh();
|
||||||
|
}
|
||||||
|
|
||||||
|
private function upsertContact(string $externalId, CardDavRemoteCard $card, ParsedVCard $parsedCard): Contact
|
||||||
|
{
|
||||||
|
$contact = Contact::withTrashed()
|
||||||
|
->where('source', 'carddav')
|
||||||
|
->where('external_id', $externalId)
|
||||||
|
->first();
|
||||||
|
|
||||||
|
$attributes = [
|
||||||
|
'source' => 'carddav',
|
||||||
|
'external_id' => $externalId,
|
||||||
|
'remote_url' => $card->href,
|
||||||
|
'remote_etag' => $card->etag,
|
||||||
|
'first_name' => $parsedCard->firstName,
|
||||||
|
'last_name' => $this->lastName($parsedCard),
|
||||||
|
'organization' => $parsedCard->organization,
|
||||||
|
'email' => $parsedCard->email,
|
||||||
|
'synced_at' => Carbon::now(),
|
||||||
|
];
|
||||||
|
|
||||||
|
if (! $contact) {
|
||||||
|
return Contact::query()->create($attributes);
|
||||||
|
}
|
||||||
|
|
||||||
|
$contact->fill($attributes);
|
||||||
|
$contact->deleted_at = null;
|
||||||
|
$contact->save();
|
||||||
|
|
||||||
|
return $contact;
|
||||||
|
}
|
||||||
|
|
||||||
|
private function replacePhoneNumbers(Contact $contact, ParsedVCard $parsedCard): void
|
||||||
|
{
|
||||||
|
$contact->phoneNumbers()->delete();
|
||||||
|
$defaultCountry = (string) config('relais_sms.default_settings.default_country');
|
||||||
|
|
||||||
|
foreach ($parsedCard->phoneNumbers as $index => $phoneNumber) {
|
||||||
|
$result = $this->phoneNumberNormalizer->normalize($phoneNumber->rawNumber, $defaultCountry);
|
||||||
|
|
||||||
|
$contact->phoneNumbers()->create([
|
||||||
|
'label' => $phoneNumber->label,
|
||||||
|
'raw_number' => $result->rawNumber,
|
||||||
|
'normalized_number' => $result->normalizedNumber,
|
||||||
|
'country' => $result->country,
|
||||||
|
'is_valid' => $result->isValid,
|
||||||
|
'is_mobile' => $result->isMobile,
|
||||||
|
'is_primary' => $index === 0,
|
||||||
|
'validation_error' => $result->error,
|
||||||
|
]);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
private function upsertGroup(string $category): ContactGroup
|
||||||
|
{
|
||||||
|
$externalId = Str::slug($category);
|
||||||
|
$slug = 'carddav-'.$externalId;
|
||||||
|
$group = ContactGroup::withTrashed()
|
||||||
|
->where('source', 'carddav')
|
||||||
|
->where('external_id', $externalId)
|
||||||
|
->first();
|
||||||
|
|
||||||
|
$attributes = [
|
||||||
|
'source' => 'carddav',
|
||||||
|
'external_id' => $externalId,
|
||||||
|
'name' => $category,
|
||||||
|
'slug' => $slug,
|
||||||
|
'synced_at' => Carbon::now(),
|
||||||
|
];
|
||||||
|
|
||||||
|
if (! $group) {
|
||||||
|
return ContactGroup::query()->create($attributes);
|
||||||
|
}
|
||||||
|
|
||||||
|
$group->fill($attributes);
|
||||||
|
$group->deleted_at = null;
|
||||||
|
$group->save();
|
||||||
|
|
||||||
|
return $group;
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* @param array<int, int> $groupIds
|
||||||
|
*/
|
||||||
|
private function syncCardDavGroupMemberships(Contact $contact, array $groupIds): void
|
||||||
|
{
|
||||||
|
$currentCardDavGroupIds = $contact->groups()
|
||||||
|
->where('contact_groups.source', 'carddav')
|
||||||
|
->pluck('contact_groups.id')
|
||||||
|
->all();
|
||||||
|
|
||||||
|
if ($currentCardDavGroupIds !== []) {
|
||||||
|
$contact->groups()->detach($currentCardDavGroupIds);
|
||||||
|
}
|
||||||
|
|
||||||
|
if ($groupIds !== []) {
|
||||||
|
$contact->groups()->syncWithoutDetaching($groupIds);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* @param array<int, string> $seenExternalIds
|
||||||
|
*/
|
||||||
|
private function deleteMissingContacts(array $seenExternalIds): int
|
||||||
|
{
|
||||||
|
$contacts = Contact::query()
|
||||||
|
->where('source', 'carddav')
|
||||||
|
->whereNotIn('external_id', $seenExternalIds ?: [''])
|
||||||
|
->get();
|
||||||
|
|
||||||
|
foreach ($contacts as $contact) {
|
||||||
|
$cardDavGroupIds = $contact->groups()
|
||||||
|
->where('contact_groups.source', 'carddav')
|
||||||
|
->pluck('contact_groups.id')
|
||||||
|
->all();
|
||||||
|
|
||||||
|
if ($cardDavGroupIds !== []) {
|
||||||
|
$contact->groups()->detach($cardDavGroupIds);
|
||||||
|
}
|
||||||
|
|
||||||
|
$contact->delete();
|
||||||
|
}
|
||||||
|
|
||||||
|
return $contacts->count();
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* @param array<int, string> $seenExternalIds
|
||||||
|
*/
|
||||||
|
private function deleteMissingGroups(array $seenExternalIds): void
|
||||||
|
{
|
||||||
|
ContactGroup::query()
|
||||||
|
->where('source', 'carddav')
|
||||||
|
->whereNotIn('external_id', $seenExternalIds ?: [''])
|
||||||
|
->delete();
|
||||||
|
}
|
||||||
|
|
||||||
|
private function externalId(ParsedVCard $parsedCard, CardDavRemoteCard $card): string
|
||||||
|
{
|
||||||
|
return $parsedCard->uid ?: sha1($card->href);
|
||||||
|
}
|
||||||
|
|
||||||
|
private function lastName(ParsedVCard $parsedCard): string
|
||||||
|
{
|
||||||
|
if ($parsedCard->lastName) {
|
||||||
|
return $parsedCard->lastName;
|
||||||
|
}
|
||||||
|
|
||||||
|
if ($parsedCard->fullName) {
|
||||||
|
return $parsedCard->fullName;
|
||||||
|
}
|
||||||
|
|
||||||
|
if ($parsedCard->organization) {
|
||||||
|
return $parsedCard->organization;
|
||||||
|
}
|
||||||
|
|
||||||
|
return 'Contact CardDAV';
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,12 @@
|
|||||||
|
<?php
|
||||||
|
|
||||||
|
namespace App\Services\CardDav;
|
||||||
|
|
||||||
|
readonly class CardDavRemoteCard
|
||||||
|
{
|
||||||
|
public function __construct(
|
||||||
|
public string $href,
|
||||||
|
public ?string $etag,
|
||||||
|
public string $vcard,
|
||||||
|
) {}
|
||||||
|
}
|
||||||
@@ -0,0 +1,21 @@
|
|||||||
|
<?php
|
||||||
|
|
||||||
|
namespace App\Services\CardDav;
|
||||||
|
|
||||||
|
readonly class ParsedVCard
|
||||||
|
{
|
||||||
|
/**
|
||||||
|
* @param array<int, ParsedVCardPhoneNumber> $phoneNumbers
|
||||||
|
* @param array<int, string> $categories
|
||||||
|
*/
|
||||||
|
public function __construct(
|
||||||
|
public ?string $uid,
|
||||||
|
public ?string $fullName,
|
||||||
|
public ?string $firstName,
|
||||||
|
public ?string $lastName,
|
||||||
|
public ?string $organization,
|
||||||
|
public ?string $email,
|
||||||
|
public array $phoneNumbers,
|
||||||
|
public array $categories,
|
||||||
|
) {}
|
||||||
|
}
|
||||||
@@ -0,0 +1,11 @@
|
|||||||
|
<?php
|
||||||
|
|
||||||
|
namespace App\Services\CardDav;
|
||||||
|
|
||||||
|
readonly class ParsedVCardPhoneNumber
|
||||||
|
{
|
||||||
|
public function __construct(
|
||||||
|
public string $rawNumber,
|
||||||
|
public ?string $label,
|
||||||
|
) {}
|
||||||
|
}
|
||||||
@@ -0,0 +1,189 @@
|
|||||||
|
<?php
|
||||||
|
|
||||||
|
namespace App\Services\CardDav;
|
||||||
|
|
||||||
|
class VCardParser
|
||||||
|
{
|
||||||
|
public function parse(string $contents): ParsedVCard
|
||||||
|
{
|
||||||
|
$uid = null;
|
||||||
|
$fullName = null;
|
||||||
|
$firstName = null;
|
||||||
|
$lastName = null;
|
||||||
|
$organization = null;
|
||||||
|
$email = null;
|
||||||
|
$phoneNumbers = [];
|
||||||
|
$categories = [];
|
||||||
|
|
||||||
|
foreach ($this->parseLines($contents) as $line) {
|
||||||
|
[$name, $params, $value] = $line;
|
||||||
|
|
||||||
|
match ($name) {
|
||||||
|
'UID' => $uid = $uid ?? $this->cleanValue($value),
|
||||||
|
'FN' => $fullName = $fullName ?? $this->cleanValue($value),
|
||||||
|
'N' => [$lastName, $firstName] = $this->parseStructuredName($value, $lastName, $firstName),
|
||||||
|
'ORG' => $organization = $organization ?? $this->cleanValue($this->splitEscaped($value, ';')[0] ?? ''),
|
||||||
|
'EMAIL' => $email = $email ?? $this->cleanValue($value),
|
||||||
|
'TEL' => $phoneNumbers[] = new ParsedVCardPhoneNumber($this->cleanValue($value), $this->phoneLabel($params)),
|
||||||
|
'CATEGORIES' => $categories = array_merge($categories, $this->parseCategories($value)),
|
||||||
|
default => null,
|
||||||
|
};
|
||||||
|
}
|
||||||
|
|
||||||
|
$categories = array_values(array_unique(array_filter($categories)));
|
||||||
|
|
||||||
|
return new ParsedVCard(
|
||||||
|
uid: $uid,
|
||||||
|
fullName: $fullName,
|
||||||
|
firstName: $firstName,
|
||||||
|
lastName: $lastName,
|
||||||
|
organization: $organization,
|
||||||
|
email: $email,
|
||||||
|
phoneNumbers: array_values(array_filter(
|
||||||
|
$phoneNumbers,
|
||||||
|
fn (ParsedVCardPhoneNumber $phoneNumber): bool => $phoneNumber->rawNumber !== '',
|
||||||
|
)),
|
||||||
|
categories: $categories,
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* @return array<int, array{0: string, 1: array<string, array<int, string>>, 2: string}>
|
||||||
|
*/
|
||||||
|
private function parseLines(string $contents): array
|
||||||
|
{
|
||||||
|
$contents = str_replace(["\r\n", "\r"], "\n", $contents);
|
||||||
|
$contents = preg_replace("/\n[ \t]/", '', $contents) ?? $contents;
|
||||||
|
$lines = [];
|
||||||
|
|
||||||
|
foreach (explode("\n", $contents) as $line) {
|
||||||
|
$line = trim($line);
|
||||||
|
|
||||||
|
if ($line === '' || ! str_contains($line, ':')) {
|
||||||
|
continue;
|
||||||
|
}
|
||||||
|
|
||||||
|
[$left, $value] = explode(':', $line, 2);
|
||||||
|
$propertyParts = explode(';', $left);
|
||||||
|
$name = strtoupper((string) array_shift($propertyParts));
|
||||||
|
|
||||||
|
if ($name === 'BEGIN' || $name === 'END' || $name === 'VERSION') {
|
||||||
|
continue;
|
||||||
|
}
|
||||||
|
|
||||||
|
$params = [];
|
||||||
|
|
||||||
|
foreach ($propertyParts as $part) {
|
||||||
|
if (str_contains($part, '=')) {
|
||||||
|
[$paramName, $paramValue] = explode('=', $part, 2);
|
||||||
|
$paramName = strtoupper($paramName);
|
||||||
|
$params[$paramName] = array_merge(
|
||||||
|
$params[$paramName] ?? [],
|
||||||
|
array_map('strtoupper', $this->splitEscaped($paramValue, ',')),
|
||||||
|
);
|
||||||
|
|
||||||
|
continue;
|
||||||
|
}
|
||||||
|
|
||||||
|
$params['TYPE'][] = strtoupper($part);
|
||||||
|
}
|
||||||
|
|
||||||
|
$lines[] = [$name, $params, $value];
|
||||||
|
}
|
||||||
|
|
||||||
|
return $lines;
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* @return array{0: ?string, 1: ?string}
|
||||||
|
*/
|
||||||
|
private function parseStructuredName(string $value, ?string $currentLastName, ?string $currentFirstName): array
|
||||||
|
{
|
||||||
|
$parts = $this->splitEscaped($value, ';');
|
||||||
|
$lastName = $this->cleanValue($parts[0] ?? '') ?: $currentLastName;
|
||||||
|
$firstName = $this->cleanValue($parts[1] ?? '') ?: $currentFirstName;
|
||||||
|
|
||||||
|
return [$lastName, $firstName];
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* @return array<int, string>
|
||||||
|
*/
|
||||||
|
private function parseCategories(string $value): array
|
||||||
|
{
|
||||||
|
return array_map(
|
||||||
|
fn (string $category): string => $this->cleanValue($category),
|
||||||
|
$this->splitEscaped($value, ','),
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* @param array<string, array<int, string>> $params
|
||||||
|
*/
|
||||||
|
private function phoneLabel(array $params): ?string
|
||||||
|
{
|
||||||
|
$types = array_filter($params['TYPE'] ?? []);
|
||||||
|
|
||||||
|
if ($types === []) {
|
||||||
|
return null;
|
||||||
|
}
|
||||||
|
|
||||||
|
return implode(', ', array_map(
|
||||||
|
fn (string $type): string => ucfirst(strtolower($type)),
|
||||||
|
array_unique($types),
|
||||||
|
));
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* @return array<int, string>
|
||||||
|
*/
|
||||||
|
private function splitEscaped(string $value, string $separator): array
|
||||||
|
{
|
||||||
|
$parts = [];
|
||||||
|
$buffer = '';
|
||||||
|
$escaped = false;
|
||||||
|
|
||||||
|
foreach (str_split($value) as $char) {
|
||||||
|
if ($escaped) {
|
||||||
|
$buffer .= '\\'.$char;
|
||||||
|
$escaped = false;
|
||||||
|
|
||||||
|
continue;
|
||||||
|
}
|
||||||
|
|
||||||
|
if ($char === '\\') {
|
||||||
|
$escaped = true;
|
||||||
|
|
||||||
|
continue;
|
||||||
|
}
|
||||||
|
|
||||||
|
if ($char === $separator) {
|
||||||
|
$parts[] = $buffer;
|
||||||
|
$buffer = '';
|
||||||
|
|
||||||
|
continue;
|
||||||
|
}
|
||||||
|
|
||||||
|
$buffer .= $char;
|
||||||
|
}
|
||||||
|
|
||||||
|
if ($escaped) {
|
||||||
|
$buffer .= '\\';
|
||||||
|
}
|
||||||
|
|
||||||
|
$parts[] = $buffer;
|
||||||
|
|
||||||
|
return $parts;
|
||||||
|
}
|
||||||
|
|
||||||
|
private function cleanValue(string $value): string
|
||||||
|
{
|
||||||
|
$value = str_replace(
|
||||||
|
['\n', '\N', '\;', '\,', '\\\\'],
|
||||||
|
["\n", "\n", ';', ',', '\\'],
|
||||||
|
trim($value),
|
||||||
|
);
|
||||||
|
|
||||||
|
return trim($value);
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,56 @@
|
|||||||
|
<?php
|
||||||
|
|
||||||
|
namespace App\Services\Phone;
|
||||||
|
|
||||||
|
use App\Contracts\PhoneNumberNormalizerInterface;
|
||||||
|
use libphonenumber\NumberParseException;
|
||||||
|
use libphonenumber\PhoneNumberFormat;
|
||||||
|
use libphonenumber\PhoneNumberType;
|
||||||
|
use libphonenumber\PhoneNumberUtil;
|
||||||
|
|
||||||
|
class LibPhoneNumberNormalizer implements PhoneNumberNormalizerInterface
|
||||||
|
{
|
||||||
|
public function __construct(
|
||||||
|
private readonly PhoneNumberUtil $phoneNumberUtil,
|
||||||
|
) {}
|
||||||
|
|
||||||
|
public function normalize(string $rawNumber, string $defaultCountry): PhoneNumberResult
|
||||||
|
{
|
||||||
|
$rawNumber = trim($rawNumber);
|
||||||
|
$defaultCountry = strtoupper(trim($defaultCountry));
|
||||||
|
|
||||||
|
if ($rawNumber === '') {
|
||||||
|
return new PhoneNumberResult($rawNumber, null, null, false, false, 'Numero vide.');
|
||||||
|
}
|
||||||
|
|
||||||
|
try {
|
||||||
|
$number = $this->phoneNumberUtil->parse($rawNumber, $defaultCountry);
|
||||||
|
} catch (NumberParseException $exception) {
|
||||||
|
return new PhoneNumberResult($rawNumber, null, null, false, false, $exception->getMessage());
|
||||||
|
}
|
||||||
|
|
||||||
|
$isValid = $this->phoneNumberUtil->isValidNumber($number);
|
||||||
|
$normalizedNumber = $isValid
|
||||||
|
? $this->phoneNumberUtil->format($number, PhoneNumberFormat::E164)
|
||||||
|
: null;
|
||||||
|
$country = $this->phoneNumberUtil->getRegionCodeForNumber($number);
|
||||||
|
$mobileRegex = (string) config('relais_sms.default_settings.mobile_phone_regex');
|
||||||
|
$numberType = $this->phoneNumberUtil->getNumberType($number);
|
||||||
|
$isMobile = $isValid && (
|
||||||
|
in_array($numberType, [PhoneNumberType::MOBILE, PhoneNumberType::FIXED_LINE_OR_MOBILE], true)
|
||||||
|
|| ($mobileRegex !== '' && (
|
||||||
|
preg_match($mobileRegex, $rawNumber) === 1
|
||||||
|
|| ($normalizedNumber !== null && preg_match($mobileRegex, $normalizedNumber) === 1)
|
||||||
|
))
|
||||||
|
);
|
||||||
|
|
||||||
|
return new PhoneNumberResult(
|
||||||
|
rawNumber: $rawNumber,
|
||||||
|
normalizedNumber: $normalizedNumber,
|
||||||
|
country: $country,
|
||||||
|
isValid: $isValid,
|
||||||
|
isMobile: $isMobile,
|
||||||
|
error: $isValid ? null : 'Numero invalide.',
|
||||||
|
);
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,15 @@
|
|||||||
|
<?php
|
||||||
|
|
||||||
|
namespace App\Services\Phone;
|
||||||
|
|
||||||
|
final readonly class PhoneNumberResult
|
||||||
|
{
|
||||||
|
public function __construct(
|
||||||
|
public string $rawNumber,
|
||||||
|
public ?string $normalizedNumber,
|
||||||
|
public ?string $country,
|
||||||
|
public bool $isValid,
|
||||||
|
public bool $isMobile,
|
||||||
|
public ?string $error = null,
|
||||||
|
) {}
|
||||||
|
}
|
||||||
@@ -0,0 +1,51 @@
|
|||||||
|
<?php
|
||||||
|
|
||||||
|
namespace App\Services\Recipients;
|
||||||
|
|
||||||
|
final readonly class RecipientResolutionResult
|
||||||
|
{
|
||||||
|
/**
|
||||||
|
* @param array<int, array<string, mixed>> $recipients
|
||||||
|
* @param array<int, array<string, mixed>> $excluded
|
||||||
|
*/
|
||||||
|
public function __construct(
|
||||||
|
public array $recipients,
|
||||||
|
public array $excluded,
|
||||||
|
public int $selectedContactCount,
|
||||||
|
public int $selectedGroupCount,
|
||||||
|
) {}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* @return array<string, int>
|
||||||
|
*/
|
||||||
|
public function summary(): array
|
||||||
|
{
|
||||||
|
return [
|
||||||
|
'selected_contacts' => $this->selectedContactCount,
|
||||||
|
'selected_groups' => $this->selectedGroupCount,
|
||||||
|
'ready_numbers' => count($this->recipients),
|
||||||
|
'excluded_total' => count($this->excluded),
|
||||||
|
'opt_out' => $this->countExcludedReason('opt_out'),
|
||||||
|
'missing_phone' => $this->countExcludedReason('missing_phone'),
|
||||||
|
'invalid' => $this->countExcludedReason('invalid'),
|
||||||
|
'non_mobile' => $this->countExcludedReason('non_mobile'),
|
||||||
|
'duplicate' => $this->countExcludedReason('duplicate'),
|
||||||
|
];
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* @return array<int, array<string, mixed>>
|
||||||
|
*/
|
||||||
|
public function excludedByReason(string $reason): array
|
||||||
|
{
|
||||||
|
return array_values(array_filter(
|
||||||
|
$this->excluded,
|
||||||
|
fn (array $entry): bool => ($entry['reason'] ?? null) === $reason,
|
||||||
|
));
|
||||||
|
}
|
||||||
|
|
||||||
|
private function countExcludedReason(string $reason): int
|
||||||
|
{
|
||||||
|
return count($this->excludedByReason($reason));
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,173 @@
|
|||||||
|
<?php
|
||||||
|
|
||||||
|
namespace App\Services\Recipients;
|
||||||
|
|
||||||
|
use App\Models\Contact;
|
||||||
|
use App\Models\ContactGroup;
|
||||||
|
use App\Models\ContactPhoneNumber;
|
||||||
|
use Illuminate\Support\Collection;
|
||||||
|
|
||||||
|
class RecipientResolver
|
||||||
|
{
|
||||||
|
/**
|
||||||
|
* @param array<int, int|string> $contactIds
|
||||||
|
* @param array<int, int|string> $groupIds
|
||||||
|
*/
|
||||||
|
public function resolve(array $contactIds, array $groupIds): RecipientResolutionResult
|
||||||
|
{
|
||||||
|
$directContactIds = $this->cleanIds($contactIds);
|
||||||
|
$selectedGroupIds = $this->cleanIds($groupIds);
|
||||||
|
|
||||||
|
$groups = ContactGroup::query()
|
||||||
|
->with(['contacts' => fn ($query) => $query->select('contacts.id')])
|
||||||
|
->whereKey($selectedGroupIds)
|
||||||
|
->orderBy('name')
|
||||||
|
->get();
|
||||||
|
|
||||||
|
/** @var array<int, array<int, string>> $groupNamesByContactId */
|
||||||
|
$groupNamesByContactId = [];
|
||||||
|
|
||||||
|
foreach ($groups as $group) {
|
||||||
|
foreach ($group->contacts as $contact) {
|
||||||
|
$groupNamesByContactId[$contact->id][] = $group->name;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
$selectedContactIds = $directContactIds
|
||||||
|
->merge($groups->flatMap(fn (ContactGroup $group): Collection => $group->contacts->pluck('id')))
|
||||||
|
->unique()
|
||||||
|
->values();
|
||||||
|
|
||||||
|
$contacts = Contact::query()
|
||||||
|
->with([
|
||||||
|
'groups',
|
||||||
|
'phoneNumbers' => fn ($query) => $query
|
||||||
|
->orderByDesc('is_primary')
|
||||||
|
->orderBy('id'),
|
||||||
|
])
|
||||||
|
->whereKey($selectedContactIds)
|
||||||
|
->orderBy('last_name')
|
||||||
|
->orderBy('first_name')
|
||||||
|
->get();
|
||||||
|
|
||||||
|
$recipients = [];
|
||||||
|
$excluded = [];
|
||||||
|
$seenNumbers = [];
|
||||||
|
|
||||||
|
foreach ($contacts as $contact) {
|
||||||
|
$selection = $this->selectionLabels($contact, $directContactIds, $groupNamesByContactId[$contact->id] ?? []);
|
||||||
|
|
||||||
|
if ($contact->sms_opt_out) {
|
||||||
|
$excluded[] = $this->excludedEntry($contact, 'opt_out', null, $selection);
|
||||||
|
|
||||||
|
continue;
|
||||||
|
}
|
||||||
|
|
||||||
|
if ($contact->phoneNumbers->isEmpty()) {
|
||||||
|
$excluded[] = $this->excludedEntry($contact, 'missing_phone', null, $selection);
|
||||||
|
|
||||||
|
continue;
|
||||||
|
}
|
||||||
|
|
||||||
|
foreach ($contact->phoneNumbers as $phoneNumber) {
|
||||||
|
if (! $phoneNumber->is_valid || $phoneNumber->normalized_number === null) {
|
||||||
|
$excluded[] = $this->excludedEntry($contact, 'invalid', $phoneNumber, $selection);
|
||||||
|
|
||||||
|
continue;
|
||||||
|
}
|
||||||
|
|
||||||
|
if (! $phoneNumber->hasDetectedMobileNumber()) {
|
||||||
|
$excluded[] = $this->excludedEntry($contact, 'non_mobile', $phoneNumber, $selection);
|
||||||
|
|
||||||
|
continue;
|
||||||
|
}
|
||||||
|
|
||||||
|
if (isset($seenNumbers[$phoneNumber->normalized_number])) {
|
||||||
|
$excluded[] = $this->excludedEntry(
|
||||||
|
$contact,
|
||||||
|
'duplicate',
|
||||||
|
$phoneNumber,
|
||||||
|
$selection,
|
||||||
|
['duplicate_of' => $seenNumbers[$phoneNumber->normalized_number]],
|
||||||
|
);
|
||||||
|
|
||||||
|
continue;
|
||||||
|
}
|
||||||
|
|
||||||
|
$entry = [
|
||||||
|
'contact_id' => $contact->id,
|
||||||
|
'contact_name' => $contact->displayName(),
|
||||||
|
'phone_number_id' => $phoneNumber->id,
|
||||||
|
'number' => $phoneNumber->normalized_number,
|
||||||
|
'raw_number' => $phoneNumber->raw_number,
|
||||||
|
'label' => $phoneNumber->label,
|
||||||
|
'selection' => $selection,
|
||||||
|
];
|
||||||
|
|
||||||
|
$recipients[] = $entry;
|
||||||
|
$seenNumbers[$phoneNumber->normalized_number] = $entry['contact_name'];
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
return new RecipientResolutionResult(
|
||||||
|
recipients: $recipients,
|
||||||
|
excluded: $excluded,
|
||||||
|
selectedContactCount: $contacts->count(),
|
||||||
|
selectedGroupCount: $groups->count(),
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* @param array<int, int|string> $ids
|
||||||
|
* @return Collection<int, int>
|
||||||
|
*/
|
||||||
|
private function cleanIds(array $ids): Collection
|
||||||
|
{
|
||||||
|
return collect($ids)
|
||||||
|
->map(fn (int|string $id): int => (int) $id)
|
||||||
|
->filter(fn (int $id): bool => $id > 0)
|
||||||
|
->unique()
|
||||||
|
->values();
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* @param Collection<int, int> $directContactIds
|
||||||
|
* @param array<int, string> $groupNames
|
||||||
|
* @return array<int, string>
|
||||||
|
*/
|
||||||
|
private function selectionLabels(Contact $contact, Collection $directContactIds, array $groupNames): array
|
||||||
|
{
|
||||||
|
$selection = $groupNames;
|
||||||
|
|
||||||
|
if ($directContactIds->contains($contact->id)) {
|
||||||
|
array_unshift($selection, 'Selection directe');
|
||||||
|
}
|
||||||
|
|
||||||
|
return array_values(array_unique($selection));
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* @param array<int, string> $selection
|
||||||
|
* @param array<string, mixed> $extra
|
||||||
|
* @return array<string, mixed>
|
||||||
|
*/
|
||||||
|
private function excludedEntry(
|
||||||
|
Contact $contact,
|
||||||
|
string $reason,
|
||||||
|
?ContactPhoneNumber $phoneNumber,
|
||||||
|
array $selection,
|
||||||
|
array $extra = [],
|
||||||
|
): array {
|
||||||
|
return array_merge([
|
||||||
|
'contact_id' => $contact->id,
|
||||||
|
'contact_name' => $contact->displayName(),
|
||||||
|
'contact_source' => $contact->source,
|
||||||
|
'phone_number_id' => $phoneNumber?->id,
|
||||||
|
'reason' => $reason,
|
||||||
|
'number' => $phoneNumber?->normalized_number,
|
||||||
|
'raw_number' => $phoneNumber?->raw_number,
|
||||||
|
'label' => $phoneNumber?->label,
|
||||||
|
'selection' => $selection,
|
||||||
|
], $extra);
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,21 @@
|
|||||||
|
<?php
|
||||||
|
|
||||||
|
namespace App\Services\Sms;
|
||||||
|
|
||||||
|
class OvhShortCodeMessage
|
||||||
|
{
|
||||||
|
public function prepare(string $message): string
|
||||||
|
{
|
||||||
|
// Keep visible labels of Markdown/HTML links, but never their target.
|
||||||
|
$message = preg_replace('~\[([^\]\r\n]*)\]\(https?://[^\s)]+\)~iu', '$1', $message) ?? $message;
|
||||||
|
$message = preg_replace('~<a\b[^>]*>(.*?)</a>~isu', '$1', $message) ?? $message;
|
||||||
|
$message = preg_replace('~https?://[^\s<>"\']+|(?<![\pL\pN_@])www\.[^\s<>"\']+~iu', '', $message) ?? $message;
|
||||||
|
// Also remove bare domain links, without eating email addresses or dates.
|
||||||
|
$message = preg_replace('~(?<![\pL\pN_@.-])(?:[\pL\pN](?:[\pL\pN-]*[\pL\pN])?\.)+[\pL]{2,63}(?::\d+)?(?:[/\?#][^\s<>"\']*)?(?![\pL\pN_@-])~iu', '', $message) ?? $message;
|
||||||
|
$message = preg_replace('/[ \t]+/u', ' ', $message) ?? $message;
|
||||||
|
$message = preg_replace('/ *\R */u', "\n", $message) ?? $message;
|
||||||
|
$message = preg_replace('/\n{3,}/', "\n\n", $message) ?? $message;
|
||||||
|
|
||||||
|
return trim($message);
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,256 @@
|
|||||||
|
<?php
|
||||||
|
|
||||||
|
namespace App\Services\Sms;
|
||||||
|
|
||||||
|
use App\Contracts\Sms\SmsProviderInterface;
|
||||||
|
use App\Models\SmsCampaign;
|
||||||
|
use GuzzleHttp\ClientInterface;
|
||||||
|
use GuzzleHttp\Exception\GuzzleException;
|
||||||
|
use GuzzleHttp\Exception\RequestException;
|
||||||
|
|
||||||
|
class OvhSmsProvider implements SmsProviderInterface
|
||||||
|
{
|
||||||
|
private ?int $serverTimestamp = null;
|
||||||
|
|
||||||
|
private int $timestampFetchedAt = 0;
|
||||||
|
|
||||||
|
public function __construct(private readonly ClientInterface $client) {}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* @param array<int, array<string, mixed>> $recipients
|
||||||
|
*/
|
||||||
|
public function send(SmsCampaign $campaign, array $recipients): SmsSendResult
|
||||||
|
{
|
||||||
|
$payload = $this->payload($campaign, $recipients);
|
||||||
|
$serviceName = $this->serviceName();
|
||||||
|
$path = '/sms/'.rawurlencode($serviceName).'/jobs';
|
||||||
|
// Keep the exact request even if the process loses OVH's response.
|
||||||
|
if ($campaign->exists) {
|
||||||
|
$campaign->update([
|
||||||
|
'provider_service_name' => $serviceName,
|
||||||
|
'request_payload' => $payload,
|
||||||
|
'message' => $payload['message'],
|
||||||
|
]);
|
||||||
|
}
|
||||||
|
$response = $this->request('POST', $path, $payload);
|
||||||
|
|
||||||
|
if (! isset($response['ids']) || ! is_array($response['ids'])
|
||||||
|
|| count($response['ids']) + count($this->stringList($response['invalidReceivers'] ?? [])) < count($recipients)) {
|
||||||
|
throw new SmsProviderException('Reponse OVH incomplete : envoi a verifier.', $response, outcomeUnknown: true);
|
||||||
|
}
|
||||||
|
|
||||||
|
return new SmsSendResult(
|
||||||
|
serviceName: $serviceName,
|
||||||
|
providerJobId: $this->stringValue($response['id'] ?? $response['jobId'] ?? null),
|
||||||
|
requestPayload: $payload,
|
||||||
|
responsePayload: $response,
|
||||||
|
providerMessageIds: $this->stringList($response['ids'] ?? []),
|
||||||
|
failedNumbers: $this->stringList($response['invalidReceivers'] ?? []),
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
/** @return array<int, array<string, mixed>> */
|
||||||
|
public function outgoing(SmsCampaign $campaign): array
|
||||||
|
{
|
||||||
|
if (! $campaign->provider_tag) {
|
||||||
|
throw new SmsProviderException('Verification impossible sans reference de campagne OVH.');
|
||||||
|
}
|
||||||
|
|
||||||
|
$path = '/sms/'.rawurlencode($campaign->provider_service_name ?: $this->serviceName()).'/outgoing';
|
||||||
|
$ids = $this->request('GET', $path.'?'.http_build_query(['tag' => $campaign->provider_tag]));
|
||||||
|
$messages = [];
|
||||||
|
|
||||||
|
foreach ($ids as $id) {
|
||||||
|
$messages[] = $this->request('GET', $path.'/'.rawurlencode((string) $id));
|
||||||
|
}
|
||||||
|
|
||||||
|
return $messages;
|
||||||
|
}
|
||||||
|
|
||||||
|
private function serviceName(): string
|
||||||
|
{
|
||||||
|
$configured = trim((string) config('relais_sms.ovh.sms_service_name', ''));
|
||||||
|
|
||||||
|
if ($configured !== '') {
|
||||||
|
return $configured;
|
||||||
|
}
|
||||||
|
|
||||||
|
$services = $this->request('GET', '/sms');
|
||||||
|
$service = $services[0] ?? null;
|
||||||
|
|
||||||
|
if (! is_string($service) || $service === '') {
|
||||||
|
throw new SmsProviderException('Aucun service SMS OVH disponible pour ces identifiants.', [
|
||||||
|
'services' => $services,
|
||||||
|
]);
|
||||||
|
}
|
||||||
|
|
||||||
|
return $service;
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* @param array<int, array<string, mixed>> $recipients
|
||||||
|
* @return array<string, mixed>
|
||||||
|
*/
|
||||||
|
private function payload(SmsCampaign $campaign, array $recipients): array
|
||||||
|
{
|
||||||
|
$shortCode = (bool) config('relais_sms.ovh.sms_short_code');
|
||||||
|
$sender = trim((string) config('relais_sms.ovh.sms_sender', ''));
|
||||||
|
|
||||||
|
if ($shortCode && $sender !== '') {
|
||||||
|
throw new SmsProviderException('OVH_SMS_SHORT_CODE=true est incompatible avec OVH_SMS_SENDER.');
|
||||||
|
}
|
||||||
|
|
||||||
|
if (! $shortCode && $sender === '') {
|
||||||
|
throw new SmsProviderException('Configurer OVH_SMS_SENDER pour utiliser OVH_SMS_SHORT_CODE=false.');
|
||||||
|
}
|
||||||
|
|
||||||
|
$message = $shortCode ? (new OvhShortCodeMessage)->prepare($campaign->message) : $campaign->message;
|
||||||
|
|
||||||
|
if (trim($message) === '') {
|
||||||
|
throw new SmsProviderException('Le SMS est vide apres retrait des liens interdits par OVH en numero court.');
|
||||||
|
}
|
||||||
|
|
||||||
|
$payload = [
|
||||||
|
'message' => $message,
|
||||||
|
'receivers' => array_values(array_map(
|
||||||
|
fn (array $recipient): string => (string) $recipient['number'],
|
||||||
|
$recipients,
|
||||||
|
)),
|
||||||
|
'noStopClause' => (bool) config('relais_sms.ovh.sms_no_stop_clause'),
|
||||||
|
'tag' => $campaign->provider_tag,
|
||||||
|
];
|
||||||
|
|
||||||
|
if ($sender !== '') {
|
||||||
|
$payload['sender'] = $sender;
|
||||||
|
} elseif ($shortCode) {
|
||||||
|
$payload['senderForResponse'] = true;
|
||||||
|
}
|
||||||
|
|
||||||
|
return $payload;
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* @param array<string, mixed>|null $payload
|
||||||
|
* @return array<string, mixed>|array<int, mixed>
|
||||||
|
*/
|
||||||
|
private function request(string $method, string $path, ?array $payload = null): array
|
||||||
|
{
|
||||||
|
$body = $payload === null ? '' : json_encode($payload, JSON_THROW_ON_ERROR);
|
||||||
|
$url = $this->baseUrl().$path;
|
||||||
|
$timestamp = $this->timestamp();
|
||||||
|
|
||||||
|
try {
|
||||||
|
$response = $this->client->request($method, $url, [
|
||||||
|
'headers' => [
|
||||||
|
'Content-Type' => 'application/json',
|
||||||
|
'X-Ovh-Application' => $this->requiredConfig('application_key'),
|
||||||
|
'X-Ovh-Consumer' => $this->requiredConfig('consumer_key'),
|
||||||
|
'X-Ovh-Signature' => $this->signature($method, $url, $body, $timestamp),
|
||||||
|
'X-Ovh-Timestamp' => (string) $timestamp,
|
||||||
|
],
|
||||||
|
'body' => $body,
|
||||||
|
'timeout' => $method === 'POST'
|
||||||
|
? (float) config('relais_sms.ovh.send_timeout', 60)
|
||||||
|
: (float) config('relais_sms.ovh.timeout', 20),
|
||||||
|
'connect_timeout' => 10,
|
||||||
|
'allow_redirects' => false,
|
||||||
|
]);
|
||||||
|
} catch (RequestException $exception) {
|
||||||
|
$responsePayload = $this->decode((string) $exception->getResponse()?->getBody());
|
||||||
|
$message = $responsePayload['message'] ?? $exception->getMessage();
|
||||||
|
|
||||||
|
throw new SmsProviderException((string) $message, $responsePayload,
|
||||||
|
outcomeUnknown: $method === 'POST' && ($exception->getResponse() === null || $exception->getResponse()->getStatusCode() >= 500));
|
||||||
|
} catch (GuzzleException $exception) {
|
||||||
|
throw new SmsProviderException($exception->getMessage(), outcomeUnknown: $method === 'POST');
|
||||||
|
}
|
||||||
|
|
||||||
|
return $this->decode((string) $response->getBody());
|
||||||
|
}
|
||||||
|
|
||||||
|
private function timestamp(): int
|
||||||
|
{
|
||||||
|
if ($this->serverTimestamp !== null) {
|
||||||
|
return $this->serverTimestamp + time() - $this->timestampFetchedAt;
|
||||||
|
}
|
||||||
|
|
||||||
|
try {
|
||||||
|
$response = $this->client->request('GET', $this->baseUrl().'/auth/time', [
|
||||||
|
'timeout' => (float) config('relais_sms.ovh.timeout', 20),
|
||||||
|
]);
|
||||||
|
|
||||||
|
$this->timestampFetchedAt = time();
|
||||||
|
|
||||||
|
return $this->serverTimestamp = (int) trim((string) $response->getBody());
|
||||||
|
} catch (GuzzleException) {
|
||||||
|
return time();
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
private function signature(string $method, string $url, string $body, int $timestamp): string
|
||||||
|
{
|
||||||
|
return '$1$'.sha1(implode('+', [
|
||||||
|
$this->requiredConfig('application_secret'),
|
||||||
|
$this->requiredConfig('consumer_key'),
|
||||||
|
strtoupper($method),
|
||||||
|
$url,
|
||||||
|
$body,
|
||||||
|
(string) $timestamp,
|
||||||
|
]));
|
||||||
|
}
|
||||||
|
|
||||||
|
private function baseUrl(): string
|
||||||
|
{
|
||||||
|
return match ((string) config('relais_sms.ovh.endpoint', 'ovh-eu')) {
|
||||||
|
'ovh-ca' => 'https://ca.api.ovh.com/1.0',
|
||||||
|
'ovh-eu' => 'https://eu.api.ovh.com/1.0',
|
||||||
|
default => throw new SmsProviderException('Endpoint OVH non pris en charge : utiliser ovh-eu ou ovh-ca.'),
|
||||||
|
};
|
||||||
|
}
|
||||||
|
|
||||||
|
private function requiredConfig(string $key): string
|
||||||
|
{
|
||||||
|
$value = trim((string) config('relais_sms.ovh.'.$key, ''));
|
||||||
|
|
||||||
|
if ($value === '') {
|
||||||
|
throw new SmsProviderException('Configuration OVH incomplete : '.$key.'.');
|
||||||
|
}
|
||||||
|
|
||||||
|
return $value;
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* @return array<string, mixed>|array<int, mixed>
|
||||||
|
*/
|
||||||
|
private function decode(string $body): array
|
||||||
|
{
|
||||||
|
if (trim($body) === '') {
|
||||||
|
return [];
|
||||||
|
}
|
||||||
|
|
||||||
|
$decoded = json_decode($body, true);
|
||||||
|
|
||||||
|
return is_array($decoded) ? $decoded : [];
|
||||||
|
}
|
||||||
|
|
||||||
|
private function stringValue(mixed $value): ?string
|
||||||
|
{
|
||||||
|
if ($value === null || $value === '') {
|
||||||
|
return null;
|
||||||
|
}
|
||||||
|
|
||||||
|
return (string) $value;
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* @return array<int, string>
|
||||||
|
*/
|
||||||
|
private function stringList(mixed $values): array
|
||||||
|
{
|
||||||
|
if (! is_array($values)) {
|
||||||
|
return [];
|
||||||
|
}
|
||||||
|
|
||||||
|
return array_values(array_map('strval', $values));
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,99 @@
|
|||||||
|
<?php
|
||||||
|
|
||||||
|
namespace App\Services\Sms;
|
||||||
|
|
||||||
|
use App\Models\CalendarReminder;
|
||||||
|
use App\Models\SmsCampaign;
|
||||||
|
use Illuminate\Support\Facades\DB;
|
||||||
|
use Illuminate\Support\Facades\Log;
|
||||||
|
|
||||||
|
class SmsCampaignReconciler
|
||||||
|
{
|
||||||
|
public function __construct(private readonly OvhSmsProvider $provider) {}
|
||||||
|
|
||||||
|
public function reconcile(SmsCampaign $campaign): SmsCampaign
|
||||||
|
{
|
||||||
|
try {
|
||||||
|
$messages = $this->provider->outgoing($campaign);
|
||||||
|
} catch (SmsProviderException $exception) {
|
||||||
|
Log::warning('SMS campaign verification unavailable.', [
|
||||||
|
'sms_campaign_id' => $campaign->id,
|
||||||
|
'reason' => $exception->getMessage(),
|
||||||
|
]);
|
||||||
|
|
||||||
|
return $campaign;
|
||||||
|
}
|
||||||
|
|
||||||
|
return $this->applyOutgoing($campaign, $messages);
|
||||||
|
}
|
||||||
|
|
||||||
|
/** @param array<int, array<string, mixed>> $messages */
|
||||||
|
public function applyOutgoing(SmsCampaign $campaign, array $messages): SmsCampaign
|
||||||
|
{
|
||||||
|
return DB::transaction(function () use ($campaign, $messages): SmsCampaign {
|
||||||
|
$campaign = SmsCampaign::query()->lockForUpdate()->findOrFail($campaign->id);
|
||||||
|
|
||||||
|
if (! in_array($campaign->status, ['uncertain', 'sending'], true)) {
|
||||||
|
return $campaign;
|
||||||
|
}
|
||||||
|
|
||||||
|
$byNumber = [];
|
||||||
|
foreach ($messages as $message) {
|
||||||
|
if (($message['tag'] ?? null) !== $campaign->provider_tag
|
||||||
|
|| ($message['message'] ?? null) !== $campaign->message
|
||||||
|
|| empty($message['id']) || empty($message['receiver'])) {
|
||||||
|
continue;
|
||||||
|
}
|
||||||
|
|
||||||
|
$byNumber[(string) $message['receiver']] = $message;
|
||||||
|
}
|
||||||
|
|
||||||
|
foreach ($campaign->deliveries()->whereIn('status', ['uncertain', 'queued'])->get() as $delivery) {
|
||||||
|
$message = $byNumber[$delivery->number] ?? null;
|
||||||
|
if ($message === null) {
|
||||||
|
$delivery->update(['status' => 'uncertain']);
|
||||||
|
|
||||||
|
continue;
|
||||||
|
}
|
||||||
|
|
||||||
|
// "sent" records acceptance by OVH, not delivery to the handset.
|
||||||
|
$delivery->update([
|
||||||
|
'status' => 'sent',
|
||||||
|
'provider_message_id' => (string) $message['id'],
|
||||||
|
'provider_response' => $message,
|
||||||
|
'error_message' => null,
|
||||||
|
'sent_at' => $message['sentAt'] ?? $message['creationDatetime'] ?? now(),
|
||||||
|
]);
|
||||||
|
}
|
||||||
|
|
||||||
|
$sentCount = $campaign->deliveries()->where('status', 'sent')->count();
|
||||||
|
$failedCount = $campaign->deliveries()->where('status', 'failed')->count();
|
||||||
|
$unconfirmed = $campaign->deliveries()->whereIn('status', ['uncertain', 'queued'])->exists();
|
||||||
|
$status = $unconfirmed ? 'uncertain' : ($failedCount > 0 ? ($sentCount > 0 ? 'partial' : 'failed') : 'sent');
|
||||||
|
$campaign->update([
|
||||||
|
'status' => $status,
|
||||||
|
'sent_count' => $sentCount,
|
||||||
|
'failed_count' => $failedCount,
|
||||||
|
'sent_at' => $campaign->deliveries()->where('status', 'sent')->min('sent_at'),
|
||||||
|
'response_payload' => ['verification' => 'OVH outgoing history', 'confirmed_recipients' => $sentCount],
|
||||||
|
'error_message' => $unconfirmed
|
||||||
|
? 'Certains envois restent a verifier chez OVH. Aucun renvoi automatique ; ne pas renvoyer cette campagne.'
|
||||||
|
: null,
|
||||||
|
]);
|
||||||
|
|
||||||
|
CalendarReminder::query()->where('sms_campaign_id', $campaign->id)->where('status', 'uncertain')->update([
|
||||||
|
'status' => $status === 'uncertain' ? 'uncertain' : ($sentCount > 0 ? 'sent' : 'failed'),
|
||||||
|
'last_error' => $campaign->error_message,
|
||||||
|
'sent_at' => $campaign->sent_at,
|
||||||
|
]);
|
||||||
|
|
||||||
|
Log::info('SMS campaign verified against OVH history.', [
|
||||||
|
'sms_campaign_id' => $campaign->id,
|
||||||
|
'sent_count' => $sentCount,
|
||||||
|
'status' => $status,
|
||||||
|
]);
|
||||||
|
|
||||||
|
return $campaign->fresh(['deliveries', 'user']);
|
||||||
|
});
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,260 @@
|
|||||||
|
<?php
|
||||||
|
|
||||||
|
namespace App\Services\Sms;
|
||||||
|
|
||||||
|
use App\Contracts\Sms\SmsProviderInterface;
|
||||||
|
use App\Models\ContactGroup;
|
||||||
|
use App\Models\SmsCampaign;
|
||||||
|
use App\Models\SmsDelivery;
|
||||||
|
use App\Models\User;
|
||||||
|
use Carbon\CarbonInterface;
|
||||||
|
use Illuminate\Support\Facades\DB;
|
||||||
|
use Illuminate\Support\Facades\Log;
|
||||||
|
|
||||||
|
class SmsCampaignSender
|
||||||
|
{
|
||||||
|
public function __construct(private readonly SmsProviderInterface $provider) {}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* @param array<int, array<string, mixed>> $recipients
|
||||||
|
* @param array<int, int|string> $selectedContactIds
|
||||||
|
* @param array<int, int|string> $selectedGroupIds
|
||||||
|
*/
|
||||||
|
public function send(
|
||||||
|
User $user,
|
||||||
|
string $message,
|
||||||
|
array $recipients,
|
||||||
|
array $selectedContactIds = [],
|
||||||
|
array $selectedGroupIds = [],
|
||||||
|
): SmsCampaign {
|
||||||
|
$campaign = $this->createCampaign($user, $message, $recipients, $selectedContactIds, $selectedGroupIds, 'sending');
|
||||||
|
|
||||||
|
return $this->sendExistingCampaign($campaign, $recipients);
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* @param array<int, array<string, mixed>> $recipients
|
||||||
|
* @param array<int, int|string> $selectedContactIds
|
||||||
|
* @param array<int, int|string> $selectedGroupIds
|
||||||
|
*/
|
||||||
|
public function schedule(
|
||||||
|
User $user,
|
||||||
|
string $message,
|
||||||
|
array $recipients,
|
||||||
|
array $selectedContactIds,
|
||||||
|
array $selectedGroupIds,
|
||||||
|
CarbonInterface $scheduledAt,
|
||||||
|
): SmsCampaign {
|
||||||
|
return $this->createCampaign($user, $message, $recipients, $selectedContactIds, $selectedGroupIds, 'scheduled', $scheduledAt);
|
||||||
|
}
|
||||||
|
|
||||||
|
public function sendScheduled(SmsCampaign $campaign): ?SmsCampaign
|
||||||
|
{
|
||||||
|
$campaign = DB::transaction(function () use ($campaign): ?SmsCampaign {
|
||||||
|
$fresh = SmsCampaign::query()
|
||||||
|
->whereKey($campaign->id)
|
||||||
|
->lockForUpdate()
|
||||||
|
->first();
|
||||||
|
|
||||||
|
if (! $fresh || $fresh->status !== 'scheduled') {
|
||||||
|
return null;
|
||||||
|
}
|
||||||
|
|
||||||
|
$fresh->update(['status' => 'sending']);
|
||||||
|
|
||||||
|
Log::info('SMS campaign status changed from scheduled to sending.', [
|
||||||
|
'sms_campaign_id' => $fresh->id,
|
||||||
|
'scheduled_at' => $fresh->scheduled_at?->toIso8601String(),
|
||||||
|
]);
|
||||||
|
|
||||||
|
return $fresh->fresh(['deliveries', 'user']);
|
||||||
|
});
|
||||||
|
|
||||||
|
if ($campaign === null) {
|
||||||
|
return null;
|
||||||
|
}
|
||||||
|
|
||||||
|
return $this->sendExistingCampaign($campaign, $this->recipientsFromDeliveries($campaign));
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* @param array<int, array<string, mixed>> $recipients
|
||||||
|
* @param array<int, int|string> $selectedContactIds
|
||||||
|
* @param array<int, int|string> $selectedGroupIds
|
||||||
|
*/
|
||||||
|
private function createCampaign(
|
||||||
|
User $user,
|
||||||
|
string $message,
|
||||||
|
array $recipients,
|
||||||
|
array $selectedContactIds,
|
||||||
|
array $selectedGroupIds,
|
||||||
|
string $status,
|
||||||
|
?CarbonInterface $scheduledAt = null,
|
||||||
|
): SmsCampaign {
|
||||||
|
$selectedContactIds = $this->cleanIds($selectedContactIds);
|
||||||
|
$selectedGroupIds = $this->cleanIds($selectedGroupIds);
|
||||||
|
$selectedGroupNames = ContactGroup::query()
|
||||||
|
->whereKey($selectedGroupIds)
|
||||||
|
->orderBy('name')
|
||||||
|
->pluck('name')
|
||||||
|
->values()
|
||||||
|
->all();
|
||||||
|
|
||||||
|
return $this->createResolvedCampaign(
|
||||||
|
$user,
|
||||||
|
$message,
|
||||||
|
$recipients,
|
||||||
|
$selectedContactIds,
|
||||||
|
$selectedGroupIds,
|
||||||
|
$selectedGroupNames,
|
||||||
|
$status,
|
||||||
|
$scheduledAt,
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* @param array<int, array<string, mixed>> $recipients
|
||||||
|
* @param array<int, int> $selectedContactIds
|
||||||
|
* @param array<int, int> $selectedGroupIds
|
||||||
|
* @param array<int, string> $selectedGroupNames
|
||||||
|
*/
|
||||||
|
private function createResolvedCampaign(
|
||||||
|
User $user,
|
||||||
|
string $message,
|
||||||
|
array $recipients,
|
||||||
|
array $selectedContactIds,
|
||||||
|
array $selectedGroupIds,
|
||||||
|
array $selectedGroupNames,
|
||||||
|
string $status,
|
||||||
|
?CarbonInterface $scheduledAt,
|
||||||
|
): SmsCampaign {
|
||||||
|
return DB::transaction(function () use ($user, $message, $recipients, $selectedContactIds, $selectedGroupIds, $selectedGroupNames, $status, $scheduledAt): SmsCampaign {
|
||||||
|
$attributes = [
|
||||||
|
'user_id' => $user->id,
|
||||||
|
'provider' => (string) config('relais_sms.default_settings.active_sms_provider', 'ovh'),
|
||||||
|
'status' => $status,
|
||||||
|
'message' => $message,
|
||||||
|
'recipients_count' => count($recipients),
|
||||||
|
'selected_contact_ids' => $selectedContactIds,
|
||||||
|
'selected_group_ids' => $selectedGroupIds,
|
||||||
|
'selected_group_names' => $selectedGroupNames,
|
||||||
|
];
|
||||||
|
|
||||||
|
if ($scheduledAt !== null) {
|
||||||
|
$attributes['scheduled_at'] = $scheduledAt;
|
||||||
|
}
|
||||||
|
|
||||||
|
$campaign = SmsCampaign::query()->create($attributes);
|
||||||
|
$campaign->update(['provider_tag' => 'relais-sms-campaign-'.$campaign->id]);
|
||||||
|
|
||||||
|
foreach ($recipients as $recipient) {
|
||||||
|
$campaign->deliveries()->create([
|
||||||
|
'contact_id' => $recipient['contact_id'] ?? null,
|
||||||
|
'contact_phone_number_id' => $recipient['phone_number_id'] ?? null,
|
||||||
|
'contact_name' => (string) $recipient['contact_name'],
|
||||||
|
'number' => (string) $recipient['number'],
|
||||||
|
'status' => 'queued',
|
||||||
|
]);
|
||||||
|
}
|
||||||
|
|
||||||
|
return $campaign;
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* @param array<int, array<string, mixed>> $recipients
|
||||||
|
*/
|
||||||
|
private function sendExistingCampaign(SmsCampaign $campaign, array $recipients): SmsCampaign
|
||||||
|
{
|
||||||
|
try {
|
||||||
|
$result = $this->provider->send($campaign, $recipients);
|
||||||
|
} catch (SmsProviderException $exception) {
|
||||||
|
$status = $exception->outcomeUnknown ? 'uncertain' : 'failed';
|
||||||
|
$message = $exception->outcomeUnknown
|
||||||
|
? 'OVH n a pas confirme la reponse. Les SMS peuvent avoir ete envoyes. Verification automatique au prochain passage du cron ; ne pas renvoyer cette campagne.'
|
||||||
|
: $exception->getMessage();
|
||||||
|
|
||||||
|
DB::transaction(function () use ($campaign, $exception, $status, $message, $recipients): void {
|
||||||
|
$campaign->deliveries()->update(['status' => $status, 'error_message' => $message]);
|
||||||
|
$campaign->update([
|
||||||
|
'status' => $status,
|
||||||
|
'failed_count' => $exception->outcomeUnknown ? 0 : count($recipients),
|
||||||
|
'response_payload' => $exception->responsePayload,
|
||||||
|
'error_message' => $message,
|
||||||
|
]);
|
||||||
|
});
|
||||||
|
|
||||||
|
Log::warning('SMS provider request failed.', [
|
||||||
|
'sms_campaign_id' => $campaign->id,
|
||||||
|
'outcome_unknown' => $exception->outcomeUnknown,
|
||||||
|
'reason' => $exception->getMessage(),
|
||||||
|
]);
|
||||||
|
|
||||||
|
return $campaign->fresh(['deliveries', 'user']);
|
||||||
|
}
|
||||||
|
|
||||||
|
$failedNumbers = array_flip($result->failedNumbers);
|
||||||
|
$sentCount = 0;
|
||||||
|
$failedCount = 0;
|
||||||
|
|
||||||
|
foreach ($campaign->deliveries()->orderBy('id')->get()->values() as $index => $delivery) {
|
||||||
|
$failed = isset($failedNumbers[$delivery->number]);
|
||||||
|
|
||||||
|
$delivery->update([
|
||||||
|
'status' => $failed ? 'failed' : 'sent',
|
||||||
|
'provider_message_id' => $result->providerMessageIds[$index] ?? null,
|
||||||
|
'provider_response' => $result->responsePayload,
|
||||||
|
'error_message' => $failed ? 'Numero refuse par OVH.' : null,
|
||||||
|
'sent_at' => $failed ? null : now(),
|
||||||
|
]);
|
||||||
|
|
||||||
|
$failed ? $failedCount++ : $sentCount++;
|
||||||
|
}
|
||||||
|
|
||||||
|
$campaign->update([
|
||||||
|
'status' => $failedCount > 0 ? ($sentCount > 0 ? 'partial' : 'failed') : 'sent',
|
||||||
|
'sent_count' => $sentCount,
|
||||||
|
'failed_count' => $failedCount,
|
||||||
|
'provider_service_name' => $result->serviceName,
|
||||||
|
'provider_job_id' => $result->providerJobId,
|
||||||
|
'message' => (string) ($result->requestPayload['message'] ?? $campaign->message),
|
||||||
|
'request_payload' => $result->requestPayload,
|
||||||
|
'response_payload' => $result->responsePayload,
|
||||||
|
'sent_at' => $sentCount > 0 ? now() : null,
|
||||||
|
]);
|
||||||
|
|
||||||
|
return $campaign->fresh(['deliveries', 'user']);
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* @return array<int, array<string, mixed>>
|
||||||
|
*/
|
||||||
|
private function recipientsFromDeliveries(SmsCampaign $campaign): array
|
||||||
|
{
|
||||||
|
return $campaign->deliveries()
|
||||||
|
->orderBy('id')
|
||||||
|
->get()
|
||||||
|
->map(fn (SmsDelivery $delivery): array => [
|
||||||
|
'contact_id' => $delivery->contact_id,
|
||||||
|
'phone_number_id' => $delivery->contact_phone_number_id,
|
||||||
|
'contact_name' => $delivery->contact_name,
|
||||||
|
'number' => $delivery->number,
|
||||||
|
])
|
||||||
|
->values()
|
||||||
|
->all();
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* @param array<int, int|string> $ids
|
||||||
|
* @return array<int, int>
|
||||||
|
*/
|
||||||
|
private function cleanIds(array $ids): array
|
||||||
|
{
|
||||||
|
return collect($ids)
|
||||||
|
->map(fn (int|string $id): int => (int) $id)
|
||||||
|
->filter(fn (int $id): bool => $id > 0)
|
||||||
|
->unique()
|
||||||
|
->values()
|
||||||
|
->all();
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,39 @@
|
|||||||
|
<?php
|
||||||
|
|
||||||
|
namespace App\Services\Sms;
|
||||||
|
|
||||||
|
use App\Models\AppSetting;
|
||||||
|
|
||||||
|
class SmsMessageComposer
|
||||||
|
{
|
||||||
|
/**
|
||||||
|
* @return array{header: string, footer: string}
|
||||||
|
*/
|
||||||
|
public function settings(): array
|
||||||
|
{
|
||||||
|
return [
|
||||||
|
'header' => AppSetting::string('sms_message_header'),
|
||||||
|
'footer' => AppSetting::string('sms_message_footer'),
|
||||||
|
];
|
||||||
|
}
|
||||||
|
|
||||||
|
public function compose(string $body, bool $includeHeader = true, bool $includeFooter = true): string
|
||||||
|
{
|
||||||
|
$settings = $this->settings();
|
||||||
|
$parts = [];
|
||||||
|
|
||||||
|
if ($includeHeader && $settings['header'] !== '') {
|
||||||
|
$parts[] = $settings['header'];
|
||||||
|
}
|
||||||
|
|
||||||
|
if (trim($body) !== '') {
|
||||||
|
$parts[] = trim($body);
|
||||||
|
}
|
||||||
|
|
||||||
|
if ($includeFooter && $settings['footer'] !== '') {
|
||||||
|
$parts[] = $settings['footer'];
|
||||||
|
}
|
||||||
|
|
||||||
|
return implode("\n", $parts);
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,69 @@
|
|||||||
|
<?php
|
||||||
|
|
||||||
|
namespace App\Services\Sms;
|
||||||
|
|
||||||
|
class SmsMessageLength
|
||||||
|
{
|
||||||
|
private const GSM_BASIC = "@\u{00A3}$\u{00A5}\u{00E8}\u{00E9}\u{00F9}\u{00EC}\u{00F2}\u{00C7}\n\u{00D8}\u{00F8}\r\u{00C5}\u{00E5}\u{0394}_\u{03A6}\u{0393}\u{039B}\u{03A9}\u{03A0}\u{03A8}\u{03A3}\u{0398}\u{039E}\u{00C6}\u{00E6}\u{00DF}\u{00C9} !\"#\u{00A4}%&'()*+,-./0123456789:;<=>?\u{00A1}ABCDEFGHIJKLMNOPQRSTUVWXYZ\u{00C4}\u{00D6}\u{00D1}\u{00DC}\u{00A7}\u{00BF}abcdefghijklmnopqrstuvwxyz\u{00E4}\u{00F6}\u{00F1}\u{00FC}\u{00E0}";
|
||||||
|
|
||||||
|
private const GSM_EXTENDED = "^{}\\[~]|\u{20AC}";
|
||||||
|
|
||||||
|
public function fitsInOneSms(string $message): bool
|
||||||
|
{
|
||||||
|
return $this->units($message) <= $this->singleSmsCapacity($message);
|
||||||
|
}
|
||||||
|
|
||||||
|
public function units(string $message): int
|
||||||
|
{
|
||||||
|
if (! $this->usesGsmAlphabet($message)) {
|
||||||
|
return intdiv(strlen(mb_convert_encoding($message, 'UTF-16BE', 'UTF-8')), 2);
|
||||||
|
}
|
||||||
|
|
||||||
|
return array_sum(array_map(
|
||||||
|
fn (string $character): int => str_contains(self::GSM_EXTENDED, $character) ? 2 : 1,
|
||||||
|
mb_str_split($message),
|
||||||
|
));
|
||||||
|
}
|
||||||
|
|
||||||
|
public function singleSmsCapacity(string $message): int
|
||||||
|
{
|
||||||
|
return $this->usesGsmAlphabet($message) ? 160 : 70;
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Truncate a value so that prefix + value + suffix still fits in one SMS.
|
||||||
|
*/
|
||||||
|
public function truncateBetween(string $prefix, string $value, string $suffix, string $marker = '[...]'): string
|
||||||
|
{
|
||||||
|
if ($this->fitsInOneSms($prefix.$value.$suffix)) {
|
||||||
|
return $value;
|
||||||
|
}
|
||||||
|
|
||||||
|
$truncated = '';
|
||||||
|
|
||||||
|
foreach (mb_str_split($value) as $character) {
|
||||||
|
if (! $this->fitsInOneSms($prefix.$truncated.$character.$marker.$suffix)) {
|
||||||
|
break;
|
||||||
|
}
|
||||||
|
|
||||||
|
$truncated .= $character;
|
||||||
|
}
|
||||||
|
|
||||||
|
if ($this->fitsInOneSms($prefix.$truncated.$marker.$suffix)) {
|
||||||
|
return rtrim($truncated).$marker;
|
||||||
|
}
|
||||||
|
|
||||||
|
return rtrim($truncated);
|
||||||
|
}
|
||||||
|
|
||||||
|
private function usesGsmAlphabet(string $message): bool
|
||||||
|
{
|
||||||
|
foreach (mb_str_split($message) as $character) {
|
||||||
|
if (! str_contains(self::GSM_BASIC, $character) && ! str_contains(self::GSM_EXTENDED, $character)) {
|
||||||
|
return false;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
return true;
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,19 @@
|
|||||||
|
<?php
|
||||||
|
|
||||||
|
namespace App\Services\Sms;
|
||||||
|
|
||||||
|
use RuntimeException;
|
||||||
|
|
||||||
|
class SmsProviderException extends RuntimeException
|
||||||
|
{
|
||||||
|
/**
|
||||||
|
* @param array<string, mixed>|null $responsePayload
|
||||||
|
*/
|
||||||
|
public function __construct(
|
||||||
|
string $message,
|
||||||
|
public readonly ?array $responsePayload = null,
|
||||||
|
public readonly bool $outcomeUnknown = false,
|
||||||
|
) {
|
||||||
|
parent::__construct($message);
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,21 @@
|
|||||||
|
<?php
|
||||||
|
|
||||||
|
namespace App\Services\Sms;
|
||||||
|
|
||||||
|
class SmsSendResult
|
||||||
|
{
|
||||||
|
/**
|
||||||
|
* @param array<string, mixed> $requestPayload
|
||||||
|
* @param array<string, mixed> $responsePayload
|
||||||
|
* @param array<int, string> $providerMessageIds
|
||||||
|
* @param array<int, string> $failedNumbers
|
||||||
|
*/
|
||||||
|
public function __construct(
|
||||||
|
public readonly string $serviceName,
|
||||||
|
public readonly ?string $providerJobId,
|
||||||
|
public readonly array $requestPayload,
|
||||||
|
public readonly array $responsePayload,
|
||||||
|
public readonly array $providerMessageIds = [],
|
||||||
|
public readonly array $failedNumbers = [],
|
||||||
|
) {}
|
||||||
|
}
|
||||||
@@ -0,0 +1,18 @@
|
|||||||
|
#!/usr/bin/env php
|
||||||
|
<?php
|
||||||
|
|
||||||
|
use Illuminate\Foundation\Application;
|
||||||
|
use Symfony\Component\Console\Input\ArgvInput;
|
||||||
|
|
||||||
|
define('LARAVEL_START', microtime(true));
|
||||||
|
|
||||||
|
// Register the Composer autoloader...
|
||||||
|
require __DIR__.'/vendor/autoload.php';
|
||||||
|
|
||||||
|
// Bootstrap Laravel and handle the command...
|
||||||
|
/** @var Application $app */
|
||||||
|
$app = require_once __DIR__.'/bootstrap/app.php';
|
||||||
|
|
||||||
|
$status = $app->handleCommand(new ArgvInput);
|
||||||
|
|
||||||
|
exit($status);
|
||||||
@@ -0,0 +1,23 @@
|
|||||||
|
<?php
|
||||||
|
|
||||||
|
use Illuminate\Foundation\Application;
|
||||||
|
use Illuminate\Foundation\Configuration\Exceptions;
|
||||||
|
use Illuminate\Foundation\Configuration\Middleware;
|
||||||
|
use Illuminate\Http\Request;
|
||||||
|
|
||||||
|
return Application::configure(basePath: dirname(__DIR__))
|
||||||
|
->withRouting(
|
||||||
|
web: __DIR__.'/../routes/web.php',
|
||||||
|
commands: __DIR__.'/../routes/console.php',
|
||||||
|
health: '/up',
|
||||||
|
)
|
||||||
|
->withMiddleware(function (Middleware $middleware): void {
|
||||||
|
$middleware->validateCsrfTokens(except: [
|
||||||
|
'ovh/sms/stop-callback',
|
||||||
|
]);
|
||||||
|
})
|
||||||
|
->withExceptions(function (Exceptions $exceptions): void {
|
||||||
|
$exceptions->shouldRenderJsonWhen(
|
||||||
|
fn (Request $request) => $request->is('api/*'),
|
||||||
|
);
|
||||||
|
})->create();
|
||||||
@@ -0,0 +1,2 @@
|
|||||||
|
*
|
||||||
|
!.gitignore
|
||||||
@@ -0,0 +1,7 @@
|
|||||||
|
<?php
|
||||||
|
|
||||||
|
use App\Providers\AppServiceProvider;
|
||||||
|
|
||||||
|
return [
|
||||||
|
AppServiceProvider::class,
|
||||||
|
];
|
||||||
+103
@@ -0,0 +1,103 @@
|
|||||||
|
{
|
||||||
|
"$schema": "https://getcomposer.org/schema.json",
|
||||||
|
"name": "laravel/laravel",
|
||||||
|
"type": "project",
|
||||||
|
"description": "Gestion de contacts, campagnes SMS OVHcloud et rappels CalDAV.",
|
||||||
|
"keywords": ["sms", "ovhcloud", "carddav", "caldav", "laravel"],
|
||||||
|
"license": "GPL-3.0-only",
|
||||||
|
"require": {
|
||||||
|
"php": "^8.3",
|
||||||
|
"giggsey/libphonenumber-for-php": "^9.0",
|
||||||
|
"laravel/framework": "^13.8",
|
||||||
|
"laravel/tinker": "^3.0",
|
||||||
|
"sabre/vobject": "^4.6"
|
||||||
|
},
|
||||||
|
"require-dev": {
|
||||||
|
"fakerphp/faker": "^1.23",
|
||||||
|
"laravel/pail": "^1.2.5",
|
||||||
|
"laravel/pao": "^1.0.6",
|
||||||
|
"laravel/pint": "^1.27",
|
||||||
|
"mockery/mockery": "^1.6",
|
||||||
|
"nunomaduro/collision": "^8.6",
|
||||||
|
"phpstan/phpstan": "^2.2",
|
||||||
|
"phpunit/phpunit": "^12.5.12"
|
||||||
|
},
|
||||||
|
"autoload": {
|
||||||
|
"psr-4": {
|
||||||
|
"App\\": "app/",
|
||||||
|
"Database\\Factories\\": "database/factories/",
|
||||||
|
"Database\\Seeders\\": "database/seeders/"
|
||||||
|
}
|
||||||
|
},
|
||||||
|
"autoload-dev": {
|
||||||
|
"psr-4": {
|
||||||
|
"Tests\\": "tests/"
|
||||||
|
}
|
||||||
|
},
|
||||||
|
"scripts": {
|
||||||
|
"setup": [
|
||||||
|
"composer install",
|
||||||
|
"@php -r \"file_exists('.env') || copy('.env.example', '.env');\"",
|
||||||
|
"@php artisan key:generate",
|
||||||
|
"@php artisan migrate --force",
|
||||||
|
"npm install --ignore-scripts",
|
||||||
|
"npm run build"
|
||||||
|
],
|
||||||
|
"dev": [
|
||||||
|
"Composer\\Config::disableProcessTimeout",
|
||||||
|
"@php artisan serve"
|
||||||
|
],
|
||||||
|
"lint": [
|
||||||
|
"pint --test"
|
||||||
|
],
|
||||||
|
"analyse": [
|
||||||
|
"@php vendor/bin/phpstan analyse --memory-limit=1G --no-progress --debug"
|
||||||
|
],
|
||||||
|
"ci": [
|
||||||
|
"@lint",
|
||||||
|
"@analyse",
|
||||||
|
"@test"
|
||||||
|
],
|
||||||
|
"test": [
|
||||||
|
"@php artisan config:clear --ansi",
|
||||||
|
"@php artisan test"
|
||||||
|
],
|
||||||
|
"post-autoload-dump": [
|
||||||
|
"Illuminate\\Foundation\\ComposerScripts::postAutoloadDump",
|
||||||
|
"@php artisan package:discover --ansi"
|
||||||
|
],
|
||||||
|
"post-update-cmd": [
|
||||||
|
"@php artisan vendor:publish --tag=laravel-assets --ansi --force"
|
||||||
|
],
|
||||||
|
"post-root-package-install": [
|
||||||
|
"@php -r \"file_exists('.env') || copy('.env.example', '.env');\""
|
||||||
|
],
|
||||||
|
"post-create-project-cmd": [
|
||||||
|
"@php artisan key:generate --ansi",
|
||||||
|
"@php -r \"file_exists('database/database.sqlite') || touch('database/database.sqlite');\"",
|
||||||
|
"@php artisan migrate --graceful --ansi"
|
||||||
|
],
|
||||||
|
"pre-package-uninstall": [
|
||||||
|
"Illuminate\\Foundation\\ComposerScripts::prePackageUninstall"
|
||||||
|
]
|
||||||
|
},
|
||||||
|
"extra": {
|
||||||
|
"laravel": {
|
||||||
|
"dont-discover": []
|
||||||
|
}
|
||||||
|
},
|
||||||
|
"config": {
|
||||||
|
"optimize-autoloader": true,
|
||||||
|
"platform": {
|
||||||
|
"php": "8.3.23"
|
||||||
|
},
|
||||||
|
"preferred-install": "dist",
|
||||||
|
"sort-packages": true,
|
||||||
|
"allow-plugins": {
|
||||||
|
"pestphp/pest-plugin": true,
|
||||||
|
"php-http/discovery": true
|
||||||
|
}
|
||||||
|
},
|
||||||
|
"minimum-stability": "stable",
|
||||||
|
"prefer-stable": true
|
||||||
|
}
|
||||||
Generated
+8845
File diff suppressed because it is too large
Load Diff
+126
@@ -0,0 +1,126 @@
|
|||||||
|
<?php
|
||||||
|
|
||||||
|
return [
|
||||||
|
|
||||||
|
/*
|
||||||
|
|--------------------------------------------------------------------------
|
||||||
|
| Application Name
|
||||||
|
|--------------------------------------------------------------------------
|
||||||
|
|
|
||||||
|
| This value is the name of your application, which will be used when the
|
||||||
|
| framework needs to place the application's name in a notification or
|
||||||
|
| other UI elements where an application name needs to be displayed.
|
||||||
|
|
|
||||||
|
*/
|
||||||
|
|
||||||
|
'name' => env('APP_NAME', 'Laravel'),
|
||||||
|
|
||||||
|
/*
|
||||||
|
|--------------------------------------------------------------------------
|
||||||
|
| Application Environment
|
||||||
|
|--------------------------------------------------------------------------
|
||||||
|
|
|
||||||
|
| This value determines the "environment" your application is currently
|
||||||
|
| running in. This may determine how you prefer to configure various
|
||||||
|
| services the application utilizes. Set this in your ".env" file.
|
||||||
|
|
|
||||||
|
*/
|
||||||
|
|
||||||
|
'env' => env('APP_ENV', 'production'),
|
||||||
|
|
||||||
|
/*
|
||||||
|
|--------------------------------------------------------------------------
|
||||||
|
| Application Debug Mode
|
||||||
|
|--------------------------------------------------------------------------
|
||||||
|
|
|
||||||
|
| When your application is in debug mode, detailed error messages with
|
||||||
|
| stack traces will be shown on every error that occurs within your
|
||||||
|
| application. If disabled, a simple generic error page is shown.
|
||||||
|
|
|
||||||
|
*/
|
||||||
|
|
||||||
|
'debug' => (bool) env('APP_DEBUG', false),
|
||||||
|
|
||||||
|
/*
|
||||||
|
|--------------------------------------------------------------------------
|
||||||
|
| Application URL
|
||||||
|
|--------------------------------------------------------------------------
|
||||||
|
|
|
||||||
|
| This URL is used by the console to properly generate URLs when using
|
||||||
|
| the Artisan command line tool. You should set this to the root of
|
||||||
|
| the application so that it's available within Artisan commands.
|
||||||
|
|
|
||||||
|
*/
|
||||||
|
|
||||||
|
'url' => env('APP_URL', 'http://localhost'),
|
||||||
|
|
||||||
|
/*
|
||||||
|
|--------------------------------------------------------------------------
|
||||||
|
| Application Timezone
|
||||||
|
|--------------------------------------------------------------------------
|
||||||
|
|
|
||||||
|
| Here you may specify the default timezone for your application, which
|
||||||
|
| will be used by the PHP date and date-time functions. The timezone
|
||||||
|
| is set to "UTC" by default as it is suitable for most use cases.
|
||||||
|
|
|
||||||
|
*/
|
||||||
|
|
||||||
|
'timezone' => 'UTC',
|
||||||
|
|
||||||
|
/*
|
||||||
|
|--------------------------------------------------------------------------
|
||||||
|
| Application Locale Configuration
|
||||||
|
|--------------------------------------------------------------------------
|
||||||
|
|
|
||||||
|
| The application locale determines the default locale that will be used
|
||||||
|
| by Laravel's translation / localization methods. This option can be
|
||||||
|
| set to any locale for which you plan to have translation strings.
|
||||||
|
|
|
||||||
|
*/
|
||||||
|
|
||||||
|
'locale' => env('APP_LOCALE', 'en'),
|
||||||
|
|
||||||
|
'fallback_locale' => env('APP_FALLBACK_LOCALE', 'en'),
|
||||||
|
|
||||||
|
'faker_locale' => env('APP_FAKER_LOCALE', 'en_US'),
|
||||||
|
|
||||||
|
/*
|
||||||
|
|--------------------------------------------------------------------------
|
||||||
|
| Encryption Key
|
||||||
|
|--------------------------------------------------------------------------
|
||||||
|
|
|
||||||
|
| This key is utilized by Laravel's encryption services and should be set
|
||||||
|
| to a random, 32 character string to ensure that all encrypted values
|
||||||
|
| are secure. You should do this prior to deploying the application.
|
||||||
|
|
|
||||||
|
*/
|
||||||
|
|
||||||
|
'cipher' => 'AES-256-CBC',
|
||||||
|
|
||||||
|
'key' => env('APP_KEY'),
|
||||||
|
|
||||||
|
'previous_keys' => [
|
||||||
|
...array_filter(
|
||||||
|
explode(',', (string) env('APP_PREVIOUS_KEYS', ''))
|
||||||
|
),
|
||||||
|
],
|
||||||
|
|
||||||
|
/*
|
||||||
|
|--------------------------------------------------------------------------
|
||||||
|
| Maintenance Mode Driver
|
||||||
|
|--------------------------------------------------------------------------
|
||||||
|
|
|
||||||
|
| These configuration options determine the driver used to determine and
|
||||||
|
| manage Laravel's "maintenance mode" status. The "cache" driver will
|
||||||
|
| allow maintenance mode to be controlled across multiple machines.
|
||||||
|
|
|
||||||
|
| Supported drivers: "file", "cache"
|
||||||
|
|
|
||||||
|
*/
|
||||||
|
|
||||||
|
'maintenance' => [
|
||||||
|
'driver' => env('APP_MAINTENANCE_DRIVER', 'file'),
|
||||||
|
'store' => env('APP_MAINTENANCE_STORE', 'database'),
|
||||||
|
],
|
||||||
|
|
||||||
|
];
|
||||||
+117
@@ -0,0 +1,117 @@
|
|||||||
|
<?php
|
||||||
|
|
||||||
|
use App\Models\User;
|
||||||
|
|
||||||
|
return [
|
||||||
|
|
||||||
|
/*
|
||||||
|
|--------------------------------------------------------------------------
|
||||||
|
| Authentication Defaults
|
||||||
|
|--------------------------------------------------------------------------
|
||||||
|
|
|
||||||
|
| This option defines the default authentication "guard" and password
|
||||||
|
| reset "broker" for your application. You may change these values
|
||||||
|
| as required, but they're a perfect start for most applications.
|
||||||
|
|
|
||||||
|
*/
|
||||||
|
|
||||||
|
'defaults' => [
|
||||||
|
'guard' => env('AUTH_GUARD', 'web'),
|
||||||
|
'passwords' => env('AUTH_PASSWORD_BROKER', 'users'),
|
||||||
|
],
|
||||||
|
|
||||||
|
/*
|
||||||
|
|--------------------------------------------------------------------------
|
||||||
|
| Authentication Guards
|
||||||
|
|--------------------------------------------------------------------------
|
||||||
|
|
|
||||||
|
| Next, you may define every authentication guard for your application.
|
||||||
|
| Of course, a great default configuration has been defined for you
|
||||||
|
| which utilizes session storage plus the Eloquent user provider.
|
||||||
|
|
|
||||||
|
| All authentication guards have a user provider, which defines how the
|
||||||
|
| users are actually retrieved out of your database or other storage
|
||||||
|
| system used by the application. Typically, Eloquent is utilized.
|
||||||
|
|
|
||||||
|
| Supported: "session"
|
||||||
|
|
|
||||||
|
*/
|
||||||
|
|
||||||
|
'guards' => [
|
||||||
|
'web' => [
|
||||||
|
'driver' => 'session',
|
||||||
|
'provider' => 'users',
|
||||||
|
],
|
||||||
|
],
|
||||||
|
|
||||||
|
/*
|
||||||
|
|--------------------------------------------------------------------------
|
||||||
|
| User Providers
|
||||||
|
|--------------------------------------------------------------------------
|
||||||
|
|
|
||||||
|
| All authentication guards have a user provider, which defines how the
|
||||||
|
| users are actually retrieved out of your database or other storage
|
||||||
|
| system used by the application. Typically, Eloquent is utilized.
|
||||||
|
|
|
||||||
|
| If you have multiple user tables or models you may configure multiple
|
||||||
|
| providers to represent the model / table. These providers may then
|
||||||
|
| be assigned to any extra authentication guards you have defined.
|
||||||
|
|
|
||||||
|
| Supported: "database", "eloquent"
|
||||||
|
|
|
||||||
|
*/
|
||||||
|
|
||||||
|
'providers' => [
|
||||||
|
'users' => [
|
||||||
|
'driver' => 'eloquent',
|
||||||
|
'model' => env('AUTH_MODEL', User::class),
|
||||||
|
],
|
||||||
|
|
||||||
|
// 'users' => [
|
||||||
|
// 'driver' => 'database',
|
||||||
|
// 'table' => 'users',
|
||||||
|
// ],
|
||||||
|
],
|
||||||
|
|
||||||
|
/*
|
||||||
|
|--------------------------------------------------------------------------
|
||||||
|
| Resetting Passwords
|
||||||
|
|--------------------------------------------------------------------------
|
||||||
|
|
|
||||||
|
| These configuration options specify the behavior of Laravel's password
|
||||||
|
| reset functionality, including the table utilized for token storage
|
||||||
|
| and the user provider that is invoked to actually retrieve users.
|
||||||
|
|
|
||||||
|
| The expiry time is the number of minutes that each reset token will be
|
||||||
|
| considered valid. This security feature keeps tokens short-lived so
|
||||||
|
| they have less time to be guessed. You may change this as needed.
|
||||||
|
|
|
||||||
|
| The throttle setting is the number of seconds a user must wait before
|
||||||
|
| generating more password reset tokens. This prevents the user from
|
||||||
|
| quickly generating a very large amount of password reset tokens.
|
||||||
|
|
|
||||||
|
*/
|
||||||
|
|
||||||
|
'passwords' => [
|
||||||
|
'users' => [
|
||||||
|
'provider' => 'users',
|
||||||
|
'table' => env('AUTH_PASSWORD_RESET_TOKEN_TABLE', 'password_reset_tokens'),
|
||||||
|
'expire' => 60,
|
||||||
|
'throttle' => 60,
|
||||||
|
],
|
||||||
|
],
|
||||||
|
|
||||||
|
/*
|
||||||
|
|--------------------------------------------------------------------------
|
||||||
|
| Password Confirmation Timeout
|
||||||
|
|--------------------------------------------------------------------------
|
||||||
|
|
|
||||||
|
| Here you may define the number of seconds before a password confirmation
|
||||||
|
| window expires and users are asked to re-enter their password via the
|
||||||
|
| confirmation screen. By default, the timeout lasts for three hours.
|
||||||
|
|
|
||||||
|
*/
|
||||||
|
|
||||||
|
'password_timeout' => env('AUTH_PASSWORD_TIMEOUT', 10800),
|
||||||
|
|
||||||
|
];
|
||||||
@@ -0,0 +1,136 @@
|
|||||||
|
<?php
|
||||||
|
|
||||||
|
use Illuminate\Support\Str;
|
||||||
|
|
||||||
|
return [
|
||||||
|
|
||||||
|
/*
|
||||||
|
|--------------------------------------------------------------------------
|
||||||
|
| Default Cache Store
|
||||||
|
|--------------------------------------------------------------------------
|
||||||
|
|
|
||||||
|
| This option controls the default cache store that will be used by the
|
||||||
|
| framework. This connection is utilized if another isn't explicitly
|
||||||
|
| specified when running a cache operation inside the application.
|
||||||
|
|
|
||||||
|
*/
|
||||||
|
|
||||||
|
'default' => env('CACHE_STORE', 'database'),
|
||||||
|
|
||||||
|
/*
|
||||||
|
|--------------------------------------------------------------------------
|
||||||
|
| Cache Stores
|
||||||
|
|--------------------------------------------------------------------------
|
||||||
|
|
|
||||||
|
| Here you may define all of the cache "stores" for your application as
|
||||||
|
| well as their drivers. You may even define multiple stores for the
|
||||||
|
| same cache driver to group types of items stored in your caches.
|
||||||
|
|
|
||||||
|
| Supported drivers: "array", "database", "file", "memcached",
|
||||||
|
| "redis", "dynamodb", "storage", "octane",
|
||||||
|
| "session", "failover", "null"
|
||||||
|
|
|
||||||
|
*/
|
||||||
|
|
||||||
|
'stores' => [
|
||||||
|
|
||||||
|
'array' => [
|
||||||
|
'driver' => 'array',
|
||||||
|
'serialize' => false,
|
||||||
|
],
|
||||||
|
|
||||||
|
'database' => [
|
||||||
|
'driver' => 'database',
|
||||||
|
'connection' => env('DB_CACHE_CONNECTION'),
|
||||||
|
'table' => env('DB_CACHE_TABLE', 'cache'),
|
||||||
|
'lock_connection' => env('DB_CACHE_LOCK_CONNECTION'),
|
||||||
|
'lock_table' => env('DB_CACHE_LOCK_TABLE'),
|
||||||
|
],
|
||||||
|
|
||||||
|
'file' => [
|
||||||
|
'driver' => 'file',
|
||||||
|
'path' => storage_path('framework/cache/data'),
|
||||||
|
'lock_path' => storage_path('framework/cache/data'),
|
||||||
|
],
|
||||||
|
|
||||||
|
'storage' => [
|
||||||
|
'driver' => 'storage',
|
||||||
|
'disk' => env('CACHE_STORAGE_DISK'),
|
||||||
|
'path' => env('CACHE_STORAGE_PATH', 'framework/cache/data'),
|
||||||
|
],
|
||||||
|
|
||||||
|
'memcached' => [
|
||||||
|
'driver' => 'memcached',
|
||||||
|
'persistent_id' => env('MEMCACHED_PERSISTENT_ID'),
|
||||||
|
'sasl' => [
|
||||||
|
env('MEMCACHED_USERNAME'),
|
||||||
|
env('MEMCACHED_PASSWORD'),
|
||||||
|
],
|
||||||
|
'options' => [
|
||||||
|
// Memcached::OPT_CONNECT_TIMEOUT => 2000,
|
||||||
|
],
|
||||||
|
'servers' => [
|
||||||
|
[
|
||||||
|
'host' => env('MEMCACHED_HOST', '127.0.0.1'),
|
||||||
|
'port' => env('MEMCACHED_PORT', 11211),
|
||||||
|
'weight' => 100,
|
||||||
|
],
|
||||||
|
],
|
||||||
|
],
|
||||||
|
|
||||||
|
'redis' => [
|
||||||
|
'driver' => 'redis',
|
||||||
|
'connection' => env('REDIS_CACHE_CONNECTION', 'cache'),
|
||||||
|
'lock_connection' => env('REDIS_CACHE_LOCK_CONNECTION', 'default'),
|
||||||
|
],
|
||||||
|
|
||||||
|
'dynamodb' => [
|
||||||
|
'driver' => 'dynamodb',
|
||||||
|
'key' => env('AWS_ACCESS_KEY_ID'),
|
||||||
|
'secret' => env('AWS_SECRET_ACCESS_KEY'),
|
||||||
|
'region' => env('AWS_DEFAULT_REGION', 'us-east-1'),
|
||||||
|
'table' => env('DYNAMODB_CACHE_TABLE', 'cache'),
|
||||||
|
'endpoint' => env('DYNAMODB_ENDPOINT'),
|
||||||
|
],
|
||||||
|
|
||||||
|
'octane' => [
|
||||||
|
'driver' => 'octane',
|
||||||
|
],
|
||||||
|
|
||||||
|
'failover' => [
|
||||||
|
'driver' => 'failover',
|
||||||
|
'stores' => [
|
||||||
|
'database',
|
||||||
|
'array',
|
||||||
|
],
|
||||||
|
],
|
||||||
|
|
||||||
|
],
|
||||||
|
|
||||||
|
/*
|
||||||
|
|--------------------------------------------------------------------------
|
||||||
|
| Cache Key Prefix
|
||||||
|
|--------------------------------------------------------------------------
|
||||||
|
|
|
||||||
|
| When utilizing the APC, database, memcached, Redis, and DynamoDB cache
|
||||||
|
| stores, there might be other applications using the same cache. For
|
||||||
|
| that reason, you may prefix every cache key to avoid collisions.
|
||||||
|
|
|
||||||
|
*/
|
||||||
|
|
||||||
|
'prefix' => env('CACHE_PREFIX', Str::slug((string) env('APP_NAME', 'laravel')).'-cache-'),
|
||||||
|
|
||||||
|
/*
|
||||||
|
|--------------------------------------------------------------------------
|
||||||
|
| Serializable Classes
|
||||||
|
|--------------------------------------------------------------------------
|
||||||
|
|
|
||||||
|
| This value determines the classes that can be unserialized from cache
|
||||||
|
| storage. By default, no PHP classes will be unserialized from your
|
||||||
|
| cache to prevent gadget chain attacks if your APP_KEY is leaked.
|
||||||
|
|
|
||||||
|
*/
|
||||||
|
|
||||||
|
'serializable_classes' => false,
|
||||||
|
|
||||||
|
];
|
||||||
@@ -0,0 +1,184 @@
|
|||||||
|
<?php
|
||||||
|
|
||||||
|
use Illuminate\Support\Str;
|
||||||
|
use Pdo\Mysql;
|
||||||
|
|
||||||
|
return [
|
||||||
|
|
||||||
|
/*
|
||||||
|
|--------------------------------------------------------------------------
|
||||||
|
| Default Database Connection Name
|
||||||
|
|--------------------------------------------------------------------------
|
||||||
|
|
|
||||||
|
| Here you may specify which of the database connections below you wish
|
||||||
|
| to use as your default connection for database operations. This is
|
||||||
|
| the connection which will be utilized unless another connection
|
||||||
|
| is explicitly specified when you execute a query / statement.
|
||||||
|
|
|
||||||
|
*/
|
||||||
|
|
||||||
|
'default' => env('DB_CONNECTION', 'sqlite'),
|
||||||
|
|
||||||
|
/*
|
||||||
|
|--------------------------------------------------------------------------
|
||||||
|
| Database Connections
|
||||||
|
|--------------------------------------------------------------------------
|
||||||
|
|
|
||||||
|
| Below are all of the database connections defined for your application.
|
||||||
|
| An example configuration is provided for each database system which
|
||||||
|
| is supported by Laravel. You're free to add / remove connections.
|
||||||
|
|
|
||||||
|
*/
|
||||||
|
|
||||||
|
'connections' => [
|
||||||
|
|
||||||
|
'sqlite' => [
|
||||||
|
'driver' => 'sqlite',
|
||||||
|
'url' => env('DB_URL'),
|
||||||
|
'database' => env('DB_DATABASE', database_path('database.sqlite')),
|
||||||
|
'prefix' => '',
|
||||||
|
'foreign_key_constraints' => env('DB_FOREIGN_KEYS', true),
|
||||||
|
'busy_timeout' => null,
|
||||||
|
'journal_mode' => null,
|
||||||
|
'synchronous' => null,
|
||||||
|
'transaction_mode' => 'DEFERRED',
|
||||||
|
],
|
||||||
|
|
||||||
|
'mysql' => [
|
||||||
|
'driver' => 'mysql',
|
||||||
|
'url' => env('DB_URL'),
|
||||||
|
'host' => env('DB_HOST', '127.0.0.1'),
|
||||||
|
'port' => env('DB_PORT', '3306'),
|
||||||
|
'database' => env('DB_DATABASE', 'laravel'),
|
||||||
|
'username' => env('DB_USERNAME', 'root'),
|
||||||
|
'password' => env('DB_PASSWORD', ''),
|
||||||
|
'unix_socket' => env('DB_SOCKET', ''),
|
||||||
|
'charset' => env('DB_CHARSET', 'utf8mb4'),
|
||||||
|
'collation' => env('DB_COLLATION', 'utf8mb4_unicode_ci'),
|
||||||
|
'prefix' => '',
|
||||||
|
'prefix_indexes' => true,
|
||||||
|
'strict' => true,
|
||||||
|
'engine' => null,
|
||||||
|
'options' => extension_loaded('pdo_mysql') ? array_filter([
|
||||||
|
Mysql::ATTR_SSL_CA => env('MYSQL_ATTR_SSL_CA'),
|
||||||
|
]) : [],
|
||||||
|
],
|
||||||
|
|
||||||
|
'mariadb' => [
|
||||||
|
'driver' => 'mariadb',
|
||||||
|
'url' => env('DB_URL'),
|
||||||
|
'host' => env('DB_HOST', '127.0.0.1'),
|
||||||
|
'port' => env('DB_PORT', '3306'),
|
||||||
|
'database' => env('DB_DATABASE', 'laravel'),
|
||||||
|
'username' => env('DB_USERNAME', 'root'),
|
||||||
|
'password' => env('DB_PASSWORD', ''),
|
||||||
|
'unix_socket' => env('DB_SOCKET', ''),
|
||||||
|
'charset' => env('DB_CHARSET', 'utf8mb4'),
|
||||||
|
'collation' => env('DB_COLLATION', 'utf8mb4_unicode_ci'),
|
||||||
|
'prefix' => '',
|
||||||
|
'prefix_indexes' => true,
|
||||||
|
'strict' => true,
|
||||||
|
'engine' => null,
|
||||||
|
'options' => extension_loaded('pdo_mysql') ? array_filter([
|
||||||
|
Mysql::ATTR_SSL_CA => env('MYSQL_ATTR_SSL_CA'),
|
||||||
|
]) : [],
|
||||||
|
],
|
||||||
|
|
||||||
|
'pgsql' => [
|
||||||
|
'driver' => 'pgsql',
|
||||||
|
'url' => env('DB_URL'),
|
||||||
|
'host' => env('DB_HOST', '127.0.0.1'),
|
||||||
|
'port' => env('DB_PORT', '5432'),
|
||||||
|
'database' => env('DB_DATABASE', 'laravel'),
|
||||||
|
'username' => env('DB_USERNAME', 'root'),
|
||||||
|
'password' => env('DB_PASSWORD', ''),
|
||||||
|
'charset' => env('DB_CHARSET', 'utf8'),
|
||||||
|
'prefix' => '',
|
||||||
|
'prefix_indexes' => true,
|
||||||
|
'search_path' => 'public',
|
||||||
|
'sslmode' => env('DB_SSLMODE', 'prefer'),
|
||||||
|
],
|
||||||
|
|
||||||
|
'sqlsrv' => [
|
||||||
|
'driver' => 'sqlsrv',
|
||||||
|
'url' => env('DB_URL'),
|
||||||
|
'host' => env('DB_HOST', 'localhost'),
|
||||||
|
'port' => env('DB_PORT', '1433'),
|
||||||
|
'database' => env('DB_DATABASE', 'laravel'),
|
||||||
|
'username' => env('DB_USERNAME', 'root'),
|
||||||
|
'password' => env('DB_PASSWORD', ''),
|
||||||
|
'charset' => env('DB_CHARSET', 'utf8'),
|
||||||
|
'prefix' => '',
|
||||||
|
'prefix_indexes' => true,
|
||||||
|
// 'encrypt' => env('DB_ENCRYPT', 'yes'),
|
||||||
|
// 'trust_server_certificate' => env('DB_TRUST_SERVER_CERTIFICATE', 'false'),
|
||||||
|
],
|
||||||
|
|
||||||
|
],
|
||||||
|
|
||||||
|
/*
|
||||||
|
|--------------------------------------------------------------------------
|
||||||
|
| Migration Repository Table
|
||||||
|
|--------------------------------------------------------------------------
|
||||||
|
|
|
||||||
|
| This table keeps track of all the migrations that have already run for
|
||||||
|
| your application. Using this information, we can determine which of
|
||||||
|
| the migrations on disk haven't actually been run on the database.
|
||||||
|
|
|
||||||
|
*/
|
||||||
|
|
||||||
|
'migrations' => [
|
||||||
|
'table' => 'migrations',
|
||||||
|
'update_date_on_publish' => true,
|
||||||
|
],
|
||||||
|
|
||||||
|
/*
|
||||||
|
|--------------------------------------------------------------------------
|
||||||
|
| Redis Databases
|
||||||
|
|--------------------------------------------------------------------------
|
||||||
|
|
|
||||||
|
| Redis is an open source, fast, and advanced key-value store that also
|
||||||
|
| provides a richer body of commands than a typical key-value system
|
||||||
|
| such as Memcached. You may define your connection settings here.
|
||||||
|
|
|
||||||
|
*/
|
||||||
|
|
||||||
|
'redis' => [
|
||||||
|
|
||||||
|
'client' => env('REDIS_CLIENT', 'phpredis'),
|
||||||
|
|
||||||
|
'options' => [
|
||||||
|
'cluster' => env('REDIS_CLUSTER', 'redis'),
|
||||||
|
'prefix' => env('REDIS_PREFIX', Str::slug((string) env('APP_NAME', 'laravel')).'-database-'),
|
||||||
|
'persistent' => env('REDIS_PERSISTENT', false),
|
||||||
|
],
|
||||||
|
|
||||||
|
'default' => [
|
||||||
|
'url' => env('REDIS_URL'),
|
||||||
|
'host' => env('REDIS_HOST', '127.0.0.1'),
|
||||||
|
'username' => env('REDIS_USERNAME'),
|
||||||
|
'password' => env('REDIS_PASSWORD'),
|
||||||
|
'port' => env('REDIS_PORT', '6379'),
|
||||||
|
'database' => env('REDIS_DB', '0'),
|
||||||
|
'max_retries' => env('REDIS_MAX_RETRIES', 3),
|
||||||
|
'backoff_algorithm' => env('REDIS_BACKOFF_ALGORITHM', 'decorrelated_jitter'),
|
||||||
|
'backoff_base' => env('REDIS_BACKOFF_BASE', 100),
|
||||||
|
'backoff_cap' => env('REDIS_BACKOFF_CAP', 1000),
|
||||||
|
],
|
||||||
|
|
||||||
|
'cache' => [
|
||||||
|
'url' => env('REDIS_URL'),
|
||||||
|
'host' => env('REDIS_HOST', '127.0.0.1'),
|
||||||
|
'username' => env('REDIS_USERNAME'),
|
||||||
|
'password' => env('REDIS_PASSWORD'),
|
||||||
|
'port' => env('REDIS_PORT', '6379'),
|
||||||
|
'database' => env('REDIS_CACHE_DB', '1'),
|
||||||
|
'max_retries' => env('REDIS_MAX_RETRIES', 3),
|
||||||
|
'backoff_algorithm' => env('REDIS_BACKOFF_ALGORITHM', 'decorrelated_jitter'),
|
||||||
|
'backoff_base' => env('REDIS_BACKOFF_BASE', 100),
|
||||||
|
'backoff_cap' => env('REDIS_BACKOFF_CAP', 1000),
|
||||||
|
],
|
||||||
|
|
||||||
|
],
|
||||||
|
|
||||||
|
];
|
||||||
@@ -0,0 +1,80 @@
|
|||||||
|
<?php
|
||||||
|
|
||||||
|
return [
|
||||||
|
|
||||||
|
/*
|
||||||
|
|--------------------------------------------------------------------------
|
||||||
|
| Default Filesystem Disk
|
||||||
|
|--------------------------------------------------------------------------
|
||||||
|
|
|
||||||
|
| Here you may specify the default filesystem disk that should be used
|
||||||
|
| by the framework. The "local" disk, as well as a variety of cloud
|
||||||
|
| based disks are available to your application for file storage.
|
||||||
|
|
|
||||||
|
*/
|
||||||
|
|
||||||
|
'default' => env('FILESYSTEM_DISK', 'local'),
|
||||||
|
|
||||||
|
/*
|
||||||
|
|--------------------------------------------------------------------------
|
||||||
|
| Filesystem Disks
|
||||||
|
|--------------------------------------------------------------------------
|
||||||
|
|
|
||||||
|
| Below you may configure as many filesystem disks as necessary, and you
|
||||||
|
| may even configure multiple disks for the same driver. Examples for
|
||||||
|
| most supported storage drivers are configured here for reference.
|
||||||
|
|
|
||||||
|
| Supported drivers: "local", "ftp", "sftp", "s3"
|
||||||
|
|
|
||||||
|
*/
|
||||||
|
|
||||||
|
'disks' => [
|
||||||
|
|
||||||
|
'local' => [
|
||||||
|
'driver' => 'local',
|
||||||
|
'root' => storage_path('app/private'),
|
||||||
|
'serve' => true,
|
||||||
|
'throw' => false,
|
||||||
|
'report' => false,
|
||||||
|
],
|
||||||
|
|
||||||
|
'public' => [
|
||||||
|
'driver' => 'local',
|
||||||
|
'root' => storage_path('app/public'),
|
||||||
|
'url' => rtrim(env('APP_URL', 'http://localhost'), '/').'/storage',
|
||||||
|
'visibility' => 'public',
|
||||||
|
'throw' => false,
|
||||||
|
'report' => false,
|
||||||
|
],
|
||||||
|
|
||||||
|
's3' => [
|
||||||
|
'driver' => 's3',
|
||||||
|
'key' => env('AWS_ACCESS_KEY_ID'),
|
||||||
|
'secret' => env('AWS_SECRET_ACCESS_KEY'),
|
||||||
|
'region' => env('AWS_DEFAULT_REGION'),
|
||||||
|
'bucket' => env('AWS_BUCKET'),
|
||||||
|
'url' => env('AWS_URL'),
|
||||||
|
'endpoint' => env('AWS_ENDPOINT'),
|
||||||
|
'use_path_style_endpoint' => env('AWS_USE_PATH_STYLE_ENDPOINT', false),
|
||||||
|
'throw' => false,
|
||||||
|
'report' => false,
|
||||||
|
],
|
||||||
|
|
||||||
|
],
|
||||||
|
|
||||||
|
/*
|
||||||
|
|--------------------------------------------------------------------------
|
||||||
|
| Symbolic Links
|
||||||
|
|--------------------------------------------------------------------------
|
||||||
|
|
|
||||||
|
| Here you may configure the symbolic links that will be created when the
|
||||||
|
| `storage:link` Artisan command is executed. The array keys should be
|
||||||
|
| the locations of the links and the values should be their targets.
|
||||||
|
|
|
||||||
|
*/
|
||||||
|
|
||||||
|
'links' => [
|
||||||
|
public_path('storage') => storage_path('app/public'),
|
||||||
|
],
|
||||||
|
|
||||||
|
];
|
||||||
@@ -0,0 +1,132 @@
|
|||||||
|
<?php
|
||||||
|
|
||||||
|
use Monolog\Handler\NullHandler;
|
||||||
|
use Monolog\Handler\StreamHandler;
|
||||||
|
use Monolog\Handler\SyslogUdpHandler;
|
||||||
|
use Monolog\Processor\PsrLogMessageProcessor;
|
||||||
|
|
||||||
|
return [
|
||||||
|
|
||||||
|
/*
|
||||||
|
|--------------------------------------------------------------------------
|
||||||
|
| Default Log Channel
|
||||||
|
|--------------------------------------------------------------------------
|
||||||
|
|
|
||||||
|
| This option defines the default log channel that is utilized to write
|
||||||
|
| messages to your logs. The value provided here should match one of
|
||||||
|
| the channels present in the list of "channels" configured below.
|
||||||
|
|
|
||||||
|
*/
|
||||||
|
|
||||||
|
'default' => env('LOG_CHANNEL', 'stack'),
|
||||||
|
|
||||||
|
/*
|
||||||
|
|--------------------------------------------------------------------------
|
||||||
|
| Deprecations Log Channel
|
||||||
|
|--------------------------------------------------------------------------
|
||||||
|
|
|
||||||
|
| This option controls the log channel that should be used to log warnings
|
||||||
|
| regarding deprecated PHP and library features. This allows you to get
|
||||||
|
| your application ready for upcoming major versions of dependencies.
|
||||||
|
|
|
||||||
|
*/
|
||||||
|
|
||||||
|
'deprecations' => [
|
||||||
|
'channel' => env('LOG_DEPRECATIONS_CHANNEL', 'null'),
|
||||||
|
'trace' => env('LOG_DEPRECATIONS_TRACE', false),
|
||||||
|
],
|
||||||
|
|
||||||
|
/*
|
||||||
|
|--------------------------------------------------------------------------
|
||||||
|
| Log Channels
|
||||||
|
|--------------------------------------------------------------------------
|
||||||
|
|
|
||||||
|
| Here you may configure the log channels for your application. Laravel
|
||||||
|
| utilizes the Monolog PHP logging library, which includes a variety
|
||||||
|
| of powerful log handlers and formatters that you're free to use.
|
||||||
|
|
|
||||||
|
| Available drivers: "single", "daily", "slack", "syslog",
|
||||||
|
| "errorlog", "monolog", "custom", "stack"
|
||||||
|
|
|
||||||
|
*/
|
||||||
|
|
||||||
|
'channels' => [
|
||||||
|
|
||||||
|
'stack' => [
|
||||||
|
'driver' => 'stack',
|
||||||
|
'channels' => explode(',', (string) env('LOG_STACK', 'single')),
|
||||||
|
'ignore_exceptions' => false,
|
||||||
|
],
|
||||||
|
|
||||||
|
'single' => [
|
||||||
|
'driver' => 'single',
|
||||||
|
'path' => storage_path('logs/laravel.log'),
|
||||||
|
'level' => env('LOG_LEVEL', 'debug'),
|
||||||
|
'replace_placeholders' => true,
|
||||||
|
],
|
||||||
|
|
||||||
|
'daily' => [
|
||||||
|
'driver' => 'daily',
|
||||||
|
'path' => storage_path('logs/laravel.log'),
|
||||||
|
'level' => env('LOG_LEVEL', 'debug'),
|
||||||
|
'days' => env('LOG_DAILY_DAYS', 14),
|
||||||
|
'replace_placeholders' => true,
|
||||||
|
],
|
||||||
|
|
||||||
|
'slack' => [
|
||||||
|
'driver' => 'slack',
|
||||||
|
'url' => env('LOG_SLACK_WEBHOOK_URL'),
|
||||||
|
'username' => env('LOG_SLACK_USERNAME', env('APP_NAME', 'Laravel')),
|
||||||
|
'emoji' => env('LOG_SLACK_EMOJI', ':boom:'),
|
||||||
|
'level' => env('LOG_LEVEL', 'critical'),
|
||||||
|
'replace_placeholders' => true,
|
||||||
|
],
|
||||||
|
|
||||||
|
'papertrail' => [
|
||||||
|
'driver' => 'monolog',
|
||||||
|
'level' => env('LOG_LEVEL', 'debug'),
|
||||||
|
'handler' => env('LOG_PAPERTRAIL_HANDLER', SyslogUdpHandler::class),
|
||||||
|
'handler_with' => [
|
||||||
|
'host' => env('PAPERTRAIL_URL'),
|
||||||
|
'port' => env('PAPERTRAIL_PORT'),
|
||||||
|
'connectionString' => 'tls://'.env('PAPERTRAIL_URL').':'.env('PAPERTRAIL_PORT'),
|
||||||
|
],
|
||||||
|
'processors' => [PsrLogMessageProcessor::class],
|
||||||
|
],
|
||||||
|
|
||||||
|
'stderr' => [
|
||||||
|
'driver' => 'monolog',
|
||||||
|
'level' => env('LOG_LEVEL', 'debug'),
|
||||||
|
'handler' => StreamHandler::class,
|
||||||
|
'handler_with' => [
|
||||||
|
'stream' => 'php://stderr',
|
||||||
|
],
|
||||||
|
'formatter' => env('LOG_STDERR_FORMATTER'),
|
||||||
|
'processors' => [PsrLogMessageProcessor::class],
|
||||||
|
],
|
||||||
|
|
||||||
|
'syslog' => [
|
||||||
|
'driver' => 'syslog',
|
||||||
|
'level' => env('LOG_LEVEL', 'debug'),
|
||||||
|
'facility' => env('LOG_SYSLOG_FACILITY', LOG_USER),
|
||||||
|
'replace_placeholders' => true,
|
||||||
|
],
|
||||||
|
|
||||||
|
'errorlog' => [
|
||||||
|
'driver' => 'errorlog',
|
||||||
|
'level' => env('LOG_LEVEL', 'debug'),
|
||||||
|
'replace_placeholders' => true,
|
||||||
|
],
|
||||||
|
|
||||||
|
'null' => [
|
||||||
|
'driver' => 'monolog',
|
||||||
|
'handler' => NullHandler::class,
|
||||||
|
],
|
||||||
|
|
||||||
|
'emergency' => [
|
||||||
|
'path' => storage_path('logs/laravel.log'),
|
||||||
|
],
|
||||||
|
|
||||||
|
],
|
||||||
|
|
||||||
|
];
|
||||||
+118
@@ -0,0 +1,118 @@
|
|||||||
|
<?php
|
||||||
|
|
||||||
|
return [
|
||||||
|
|
||||||
|
/*
|
||||||
|
|--------------------------------------------------------------------------
|
||||||
|
| Default Mailer
|
||||||
|
|--------------------------------------------------------------------------
|
||||||
|
|
|
||||||
|
| This option controls the default mailer that is used to send all email
|
||||||
|
| messages unless another mailer is explicitly specified when sending
|
||||||
|
| the message. All additional mailers can be configured within the
|
||||||
|
| "mailers" array. Examples of each type of mailer are provided.
|
||||||
|
|
|
||||||
|
*/
|
||||||
|
|
||||||
|
'default' => env('MAIL_MAILER', 'log'),
|
||||||
|
|
||||||
|
/*
|
||||||
|
|--------------------------------------------------------------------------
|
||||||
|
| Mailer Configurations
|
||||||
|
|--------------------------------------------------------------------------
|
||||||
|
|
|
||||||
|
| Here you may configure all of the mailers used by your application plus
|
||||||
|
| their respective settings. Several examples have been configured for
|
||||||
|
| you and you are free to add your own as your application requires.
|
||||||
|
|
|
||||||
|
| Laravel supports a variety of mail "transport" drivers that can be used
|
||||||
|
| when delivering an email. You may specify which one you're using for
|
||||||
|
| your mailers below. You may also add additional mailers if needed.
|
||||||
|
|
|
||||||
|
| Supported: "smtp", "sendmail", "mailgun", "ses", "ses-v2",
|
||||||
|
| "postmark", "resend", "log", "array",
|
||||||
|
| "failover", "roundrobin"
|
||||||
|
|
|
||||||
|
*/
|
||||||
|
|
||||||
|
'mailers' => [
|
||||||
|
|
||||||
|
'smtp' => [
|
||||||
|
'transport' => 'smtp',
|
||||||
|
'scheme' => env('MAIL_SCHEME'),
|
||||||
|
'url' => env('MAIL_URL'),
|
||||||
|
'host' => env('MAIL_HOST', '127.0.0.1'),
|
||||||
|
'port' => env('MAIL_PORT', 2525),
|
||||||
|
'username' => env('MAIL_USERNAME'),
|
||||||
|
'password' => env('MAIL_PASSWORD'),
|
||||||
|
'timeout' => null,
|
||||||
|
'local_domain' => env('MAIL_EHLO_DOMAIN', parse_url((string) env('APP_URL', 'http://localhost'), PHP_URL_HOST)),
|
||||||
|
],
|
||||||
|
|
||||||
|
'ses' => [
|
||||||
|
'transport' => 'ses',
|
||||||
|
],
|
||||||
|
|
||||||
|
'postmark' => [
|
||||||
|
'transport' => 'postmark',
|
||||||
|
// 'message_stream_id' => env('POSTMARK_MESSAGE_STREAM_ID'),
|
||||||
|
// 'client' => [
|
||||||
|
// 'timeout' => 5,
|
||||||
|
// ],
|
||||||
|
],
|
||||||
|
|
||||||
|
'resend' => [
|
||||||
|
'transport' => 'resend',
|
||||||
|
],
|
||||||
|
|
||||||
|
'sendmail' => [
|
||||||
|
'transport' => 'sendmail',
|
||||||
|
'path' => env('MAIL_SENDMAIL_PATH', '/usr/sbin/sendmail -bs -i'),
|
||||||
|
],
|
||||||
|
|
||||||
|
'log' => [
|
||||||
|
'transport' => 'log',
|
||||||
|
'channel' => env('MAIL_LOG_CHANNEL'),
|
||||||
|
],
|
||||||
|
|
||||||
|
'array' => [
|
||||||
|
'transport' => 'array',
|
||||||
|
],
|
||||||
|
|
||||||
|
'failover' => [
|
||||||
|
'transport' => 'failover',
|
||||||
|
'mailers' => [
|
||||||
|
'smtp',
|
||||||
|
'log',
|
||||||
|
],
|
||||||
|
'retry_after' => 60,
|
||||||
|
],
|
||||||
|
|
||||||
|
'roundrobin' => [
|
||||||
|
'transport' => 'roundrobin',
|
||||||
|
'mailers' => [
|
||||||
|
'ses',
|
||||||
|
'postmark',
|
||||||
|
],
|
||||||
|
'retry_after' => 60,
|
||||||
|
],
|
||||||
|
|
||||||
|
],
|
||||||
|
|
||||||
|
/*
|
||||||
|
|--------------------------------------------------------------------------
|
||||||
|
| Global "From" Address
|
||||||
|
|--------------------------------------------------------------------------
|
||||||
|
|
|
||||||
|
| You may wish for all emails sent by your application to be sent from
|
||||||
|
| the same address. Here you may specify a name and address that is
|
||||||
|
| used globally for all emails that are sent by your application.
|
||||||
|
|
|
||||||
|
*/
|
||||||
|
|
||||||
|
'from' => [
|
||||||
|
'address' => env('MAIL_FROM_ADDRESS', 'hello@example.com'),
|
||||||
|
'name' => env('MAIL_FROM_NAME', env('APP_NAME', 'Laravel')),
|
||||||
|
],
|
||||||
|
|
||||||
|
];
|
||||||
@@ -0,0 +1,129 @@
|
|||||||
|
<?php
|
||||||
|
|
||||||
|
return [
|
||||||
|
|
||||||
|
/*
|
||||||
|
|--------------------------------------------------------------------------
|
||||||
|
| Default Queue Connection Name
|
||||||
|
|--------------------------------------------------------------------------
|
||||||
|
|
|
||||||
|
| Laravel's queue supports a variety of backends via a single, unified
|
||||||
|
| API, giving you convenient access to each backend using identical
|
||||||
|
| syntax for each. The default queue connection is defined below.
|
||||||
|
|
|
||||||
|
*/
|
||||||
|
|
||||||
|
'default' => env('QUEUE_CONNECTION', 'database'),
|
||||||
|
|
||||||
|
/*
|
||||||
|
|--------------------------------------------------------------------------
|
||||||
|
| Queue Connections
|
||||||
|
|--------------------------------------------------------------------------
|
||||||
|
|
|
||||||
|
| Here you may configure the connection options for every queue backend
|
||||||
|
| used by your application. An example configuration is provided for
|
||||||
|
| each backend supported by Laravel. You're also free to add more.
|
||||||
|
|
|
||||||
|
| Drivers: "sync", "database", "beanstalkd", "sqs", "redis",
|
||||||
|
| "deferred", "background", "failover", "null"
|
||||||
|
|
|
||||||
|
*/
|
||||||
|
|
||||||
|
'connections' => [
|
||||||
|
|
||||||
|
'sync' => [
|
||||||
|
'driver' => 'sync',
|
||||||
|
],
|
||||||
|
|
||||||
|
'database' => [
|
||||||
|
'driver' => 'database',
|
||||||
|
'connection' => env('DB_QUEUE_CONNECTION'),
|
||||||
|
'table' => env('DB_QUEUE_TABLE', 'jobs'),
|
||||||
|
'queue' => env('DB_QUEUE', 'default'),
|
||||||
|
'retry_after' => (int) env('DB_QUEUE_RETRY_AFTER', 90),
|
||||||
|
'after_commit' => false,
|
||||||
|
],
|
||||||
|
|
||||||
|
'beanstalkd' => [
|
||||||
|
'driver' => 'beanstalkd',
|
||||||
|
'host' => env('BEANSTALKD_QUEUE_HOST', 'localhost'),
|
||||||
|
'queue' => env('BEANSTALKD_QUEUE', 'default'),
|
||||||
|
'retry_after' => (int) env('BEANSTALKD_QUEUE_RETRY_AFTER', 90),
|
||||||
|
'block_for' => 0,
|
||||||
|
'after_commit' => false,
|
||||||
|
],
|
||||||
|
|
||||||
|
'sqs' => [
|
||||||
|
'driver' => 'sqs',
|
||||||
|
'key' => env('AWS_ACCESS_KEY_ID'),
|
||||||
|
'secret' => env('AWS_SECRET_ACCESS_KEY'),
|
||||||
|
'prefix' => env('SQS_PREFIX', 'https://sqs.us-east-1.amazonaws.com/your-account-id'),
|
||||||
|
'queue' => env('SQS_QUEUE', 'default'),
|
||||||
|
'suffix' => env('SQS_SUFFIX'),
|
||||||
|
'region' => env('AWS_DEFAULT_REGION', 'us-east-1'),
|
||||||
|
'after_commit' => false,
|
||||||
|
],
|
||||||
|
|
||||||
|
'redis' => [
|
||||||
|
'driver' => 'redis',
|
||||||
|
'connection' => env('REDIS_QUEUE_CONNECTION', 'default'),
|
||||||
|
'queue' => env('REDIS_QUEUE', 'default'),
|
||||||
|
'retry_after' => (int) env('REDIS_QUEUE_RETRY_AFTER', 90),
|
||||||
|
'block_for' => null,
|
||||||
|
'after_commit' => false,
|
||||||
|
],
|
||||||
|
|
||||||
|
'deferred' => [
|
||||||
|
'driver' => 'deferred',
|
||||||
|
],
|
||||||
|
|
||||||
|
'background' => [
|
||||||
|
'driver' => 'background',
|
||||||
|
],
|
||||||
|
|
||||||
|
'failover' => [
|
||||||
|
'driver' => 'failover',
|
||||||
|
'connections' => [
|
||||||
|
'database',
|
||||||
|
'deferred',
|
||||||
|
],
|
||||||
|
],
|
||||||
|
|
||||||
|
],
|
||||||
|
|
||||||
|
/*
|
||||||
|
|--------------------------------------------------------------------------
|
||||||
|
| Job Batching
|
||||||
|
|--------------------------------------------------------------------------
|
||||||
|
|
|
||||||
|
| The following options configure the database and table that store job
|
||||||
|
| batching information. These options can be updated to any database
|
||||||
|
| connection and table which has been defined by your application.
|
||||||
|
|
|
||||||
|
*/
|
||||||
|
|
||||||
|
'batching' => [
|
||||||
|
'database' => env('DB_CONNECTION', 'sqlite'),
|
||||||
|
'table' => 'job_batches',
|
||||||
|
],
|
||||||
|
|
||||||
|
/*
|
||||||
|
|--------------------------------------------------------------------------
|
||||||
|
| Failed Queue Jobs
|
||||||
|
|--------------------------------------------------------------------------
|
||||||
|
|
|
||||||
|
| These options configure the behavior of failed queue job logging so you
|
||||||
|
| can control how and where failed jobs are stored. Laravel ships with
|
||||||
|
| support for storing failed jobs in a simple file or in a database.
|
||||||
|
|
|
||||||
|
| Supported drivers: "database-uuids", "dynamodb", "file", "null"
|
||||||
|
|
|
||||||
|
*/
|
||||||
|
|
||||||
|
'failed' => [
|
||||||
|
'driver' => env('QUEUE_FAILED_DRIVER', 'database-uuids'),
|
||||||
|
'database' => env('DB_CONNECTION', 'sqlite'),
|
||||||
|
'table' => 'failed_jobs',
|
||||||
|
],
|
||||||
|
|
||||||
|
];
|
||||||
@@ -0,0 +1,53 @@
|
|||||||
|
<?php
|
||||||
|
|
||||||
|
return [
|
||||||
|
'default_settings' => [
|
||||||
|
'default_country' => env('RELAIS_SMS_DEFAULT_COUNTRY', 'FR'),
|
||||||
|
'mobile_phone_regex' => env('RELAIS_SMS_MOBILE_PHONE_REGEX', '/^\s*(?:(?:\(\s*\+33\s*\)|\+33|0033)\s*(?:\(0\)\s*)?|0)\s*[67](?:[\s.-]*\d{2}){4}\s*$/'),
|
||||||
|
'max_sms_per_campaign' => (int) env('RELAIS_SMS_MAX_SMS_PER_CAMPAIGN', 100),
|
||||||
|
'history_retention_years' => (int) env('RELAIS_SMS_HISTORY_RETENTION_YEARS', 3),
|
||||||
|
'scheduled_sends_enabled' => filter_var(env('RELAIS_SMS_SCHEDULED_SENDS_ENABLED', true), FILTER_VALIDATE_BOOLEAN),
|
||||||
|
'display_timezone' => env('RELAIS_SMS_TIMEZONE', 'Europe/Paris'),
|
||||||
|
'active_sms_provider' => env('RELAIS_SMS_ACTIVE_SMS_PROVIDER', 'ovh'),
|
||||||
|
'galette_sync_enabled' => filter_var(env('RELAIS_SMS_GALETTE_SYNC_ENABLED', false), FILTER_VALIDATE_BOOLEAN),
|
||||||
|
'carddav_sync_enabled' => filter_var(env('RELAIS_SMS_CARDDAV_SYNC_ENABLED', false), FILTER_VALIDATE_BOOLEAN),
|
||||||
|
'caldav_calendar_sync_enabled' => filter_var(env('RELAIS_SMS_CALDAV_CALENDAR_SYNC_ENABLED', false), FILTER_VALIDATE_BOOLEAN),
|
||||||
|
'sms_message_header' => env('RELAIS_SMS_MESSAGE_HEADER', ''),
|
||||||
|
'sms_message_footer' => env('RELAIS_SMS_MESSAGE_FOOTER', ''),
|
||||||
|
],
|
||||||
|
'carddav' => [
|
||||||
|
'url' => env('RELAIS_SMS_CARDDAV_URL'),
|
||||||
|
'username' => env('RELAIS_SMS_CARDDAV_USERNAME'),
|
||||||
|
'password' => env('RELAIS_SMS_CARDDAV_PASSWORD'),
|
||||||
|
'timeout' => (float) env('RELAIS_SMS_CARDDAV_TIMEOUT', 20),
|
||||||
|
],
|
||||||
|
'caldav' => [
|
||||||
|
'url' => env('RELAIS_SMS_CALDAV_CALENDAR_URL'),
|
||||||
|
'username' => env('RELAIS_SMS_CALDAV_CALENDAR_USERNAME'),
|
||||||
|
'password' => env('RELAIS_SMS_CALDAV_CALENDAR_PASSWORD'),
|
||||||
|
'timeout' => (float) env('RELAIS_SMS_CALDAV_CALENDAR_TIMEOUT', 20),
|
||||||
|
'lookahead_days' => (int) env('RELAIS_SMS_CALDAV_CALENDAR_LOOKAHEAD_DAYS', 90),
|
||||||
|
'sync_interval_minutes' => (int) env('RELAIS_SMS_CALDAV_SYNC_INTERVAL_MINUTES', 60),
|
||||||
|
'default_contact_ids' => array_values(array_filter(array_map('intval', explode(',', (string) env('RELAIS_SMS_CALDAV_DEFAULT_CONTACT_IDS', ''))))),
|
||||||
|
'default_group_ids' => array_values(array_filter(array_map('intval', explode(',', (string) env('RELAIS_SMS_CALDAV_DEFAULT_GROUP_IDS', ''))))),
|
||||||
|
'reminder_user_id' => env('RELAIS_SMS_CALDAV_REMINDER_USER_ID'),
|
||||||
|
'reminder_message_header' => env('RELAIS_SMS_CALDAV_REMINDER_HEADER', ''),
|
||||||
|
'reminder_message_footer' => env('RELAIS_SMS_CALDAV_REMINDER_FOOTER', ''),
|
||||||
|
'reminder_description_max_length' => (int) env('RELAIS_SMS_CALDAV_DESCRIPTION_MAX_LENGTH', 120),
|
||||||
|
'display_timezone' => env('RELAIS_SMS_CALDAV_TIMEZONE', 'Europe/Paris'),
|
||||||
|
],
|
||||||
|
'ovh' => [
|
||||||
|
'endpoint' => env('OVH_ENDPOINT', 'ovh-eu'),
|
||||||
|
'application_key' => env('OVH_APPLICATION_KEY'),
|
||||||
|
'application_secret' => env('OVH_APPLICATION_SECRET'),
|
||||||
|
'consumer_key' => env('OVH_CONSUMER_KEY'),
|
||||||
|
'sms_service_name' => env('OVH_SMS_SERVICE_NAME'),
|
||||||
|
'sms_sender' => env('OVH_SMS_SENDER'),
|
||||||
|
'sms_short_code' => filter_var(env('OVH_SMS_SHORT_CODE', trim((string) env('OVH_SMS_SENDER', '')) === '' && filter_var(env('OVH_SMS_SENDER_FOR_RESPONSE', true), FILTER_VALIDATE_BOOLEAN)), FILTER_VALIDATE_BOOLEAN),
|
||||||
|
'sms_sender_for_response' => filter_var(env('OVH_SMS_SENDER_FOR_RESPONSE', true), FILTER_VALIDATE_BOOLEAN),
|
||||||
|
'sms_no_stop_clause' => filter_var(env('OVH_SMS_NO_STOP_CLAUSE', true), FILTER_VALIDATE_BOOLEAN),
|
||||||
|
'stop_callback_token' => env('OVH_SMS_STOP_CALLBACK_TOKEN'),
|
||||||
|
'timeout' => (float) env('OVH_SMS_TIMEOUT', 20),
|
||||||
|
'send_timeout' => (float) env('OVH_SMS_SEND_TIMEOUT', 60),
|
||||||
|
],
|
||||||
|
];
|
||||||
@@ -0,0 +1,38 @@
|
|||||||
|
<?php
|
||||||
|
|
||||||
|
return [
|
||||||
|
|
||||||
|
/*
|
||||||
|
|--------------------------------------------------------------------------
|
||||||
|
| Third Party Services
|
||||||
|
|--------------------------------------------------------------------------
|
||||||
|
|
|
||||||
|
| This file is for storing the credentials for third party services such
|
||||||
|
| as Mailgun, Postmark, AWS and more. This file provides the de facto
|
||||||
|
| location for this type of information, allowing packages to have
|
||||||
|
| a conventional file to locate the various service credentials.
|
||||||
|
|
|
||||||
|
*/
|
||||||
|
|
||||||
|
'postmark' => [
|
||||||
|
'key' => env('POSTMARK_API_KEY'),
|
||||||
|
],
|
||||||
|
|
||||||
|
'resend' => [
|
||||||
|
'key' => env('RESEND_API_KEY'),
|
||||||
|
],
|
||||||
|
|
||||||
|
'ses' => [
|
||||||
|
'key' => env('AWS_ACCESS_KEY_ID'),
|
||||||
|
'secret' => env('AWS_SECRET_ACCESS_KEY'),
|
||||||
|
'region' => env('AWS_DEFAULT_REGION', 'us-east-1'),
|
||||||
|
],
|
||||||
|
|
||||||
|
'slack' => [
|
||||||
|
'notifications' => [
|
||||||
|
'bot_user_oauth_token' => env('SLACK_BOT_USER_OAUTH_TOKEN'),
|
||||||
|
'channel' => env('SLACK_BOT_USER_DEFAULT_CHANNEL'),
|
||||||
|
],
|
||||||
|
],
|
||||||
|
|
||||||
|
];
|
||||||
@@ -0,0 +1,233 @@
|
|||||||
|
<?php
|
||||||
|
|
||||||
|
use Illuminate\Support\Str;
|
||||||
|
|
||||||
|
return [
|
||||||
|
|
||||||
|
/*
|
||||||
|
|--------------------------------------------------------------------------
|
||||||
|
| Default Session Driver
|
||||||
|
|--------------------------------------------------------------------------
|
||||||
|
|
|
||||||
|
| This option determines the default session driver that is utilized for
|
||||||
|
| incoming requests. Laravel supports a variety of storage options to
|
||||||
|
| persist session data. Database storage is a great default choice.
|
||||||
|
|
|
||||||
|
| Supported: "file", "cookie", "database", "memcached",
|
||||||
|
| "redis", "dynamodb", "array"
|
||||||
|
|
|
||||||
|
*/
|
||||||
|
|
||||||
|
'driver' => env('SESSION_DRIVER', 'database'),
|
||||||
|
|
||||||
|
/*
|
||||||
|
|--------------------------------------------------------------------------
|
||||||
|
| Session Lifetime
|
||||||
|
|--------------------------------------------------------------------------
|
||||||
|
|
|
||||||
|
| Here you may specify the number of minutes that you wish the session
|
||||||
|
| to be allowed to remain idle before it expires. If you want them
|
||||||
|
| to expire immediately when the browser is closed then you may
|
||||||
|
| indicate that via the expire_on_close configuration option.
|
||||||
|
|
|
||||||
|
*/
|
||||||
|
|
||||||
|
'lifetime' => (int) env('SESSION_LIFETIME', 120),
|
||||||
|
|
||||||
|
'expire_on_close' => env('SESSION_EXPIRE_ON_CLOSE', false),
|
||||||
|
|
||||||
|
/*
|
||||||
|
|--------------------------------------------------------------------------
|
||||||
|
| Session Encryption
|
||||||
|
|--------------------------------------------------------------------------
|
||||||
|
|
|
||||||
|
| This option allows you to easily specify that all of your session data
|
||||||
|
| should be encrypted before it's stored. All encryption is performed
|
||||||
|
| automatically by Laravel and you may use the session like normal.
|
||||||
|
|
|
||||||
|
*/
|
||||||
|
|
||||||
|
'encrypt' => env('SESSION_ENCRYPT', false),
|
||||||
|
|
||||||
|
/*
|
||||||
|
|--------------------------------------------------------------------------
|
||||||
|
| Session File Location
|
||||||
|
|--------------------------------------------------------------------------
|
||||||
|
|
|
||||||
|
| When utilizing the "file" session driver, the session files are placed
|
||||||
|
| on disk. The default storage location is defined here; however, you
|
||||||
|
| are free to provide another location where they should be stored.
|
||||||
|
|
|
||||||
|
*/
|
||||||
|
|
||||||
|
'files' => storage_path('framework/sessions'),
|
||||||
|
|
||||||
|
/*
|
||||||
|
|--------------------------------------------------------------------------
|
||||||
|
| Session Database Connection
|
||||||
|
|--------------------------------------------------------------------------
|
||||||
|
|
|
||||||
|
| When using the "database" or "redis" session drivers, you may specify a
|
||||||
|
| connection that should be used to manage these sessions. This should
|
||||||
|
| correspond to a connection in your database configuration options.
|
||||||
|
|
|
||||||
|
*/
|
||||||
|
|
||||||
|
'connection' => env('SESSION_CONNECTION'),
|
||||||
|
|
||||||
|
/*
|
||||||
|
|--------------------------------------------------------------------------
|
||||||
|
| Session Database Table
|
||||||
|
|--------------------------------------------------------------------------
|
||||||
|
|
|
||||||
|
| When using the "database" session driver, you may specify the table to
|
||||||
|
| be used to store sessions. Of course, a sensible default is defined
|
||||||
|
| for you; however, you're welcome to change this to another table.
|
||||||
|
|
|
||||||
|
*/
|
||||||
|
|
||||||
|
'table' => env('SESSION_TABLE', 'sessions'),
|
||||||
|
|
||||||
|
/*
|
||||||
|
|--------------------------------------------------------------------------
|
||||||
|
| Session Cache Store
|
||||||
|
|--------------------------------------------------------------------------
|
||||||
|
|
|
||||||
|
| When using one of the framework's cache driven session backends, you may
|
||||||
|
| define the cache store which should be used to store the session data
|
||||||
|
| between requests. This must match one of your defined cache stores.
|
||||||
|
|
|
||||||
|
| Affects: "dynamodb", "memcached", "redis"
|
||||||
|
|
|
||||||
|
*/
|
||||||
|
|
||||||
|
'store' => env('SESSION_STORE'),
|
||||||
|
|
||||||
|
/*
|
||||||
|
|--------------------------------------------------------------------------
|
||||||
|
| Session Sweeping Lottery
|
||||||
|
|--------------------------------------------------------------------------
|
||||||
|
|
|
||||||
|
| Some session drivers must manually sweep their storage location to get
|
||||||
|
| rid of old sessions from storage. Here are the chances that it will
|
||||||
|
| happen on a given request. By default, the odds are 2 out of 100.
|
||||||
|
|
|
||||||
|
*/
|
||||||
|
|
||||||
|
'lottery' => [2, 100],
|
||||||
|
|
||||||
|
/*
|
||||||
|
|--------------------------------------------------------------------------
|
||||||
|
| Session Cookie Name
|
||||||
|
|--------------------------------------------------------------------------
|
||||||
|
|
|
||||||
|
| Here you may change the name of the session cookie that is created by
|
||||||
|
| the framework. Typically, you should not need to change this value
|
||||||
|
| since doing so does not grant a meaningful security improvement.
|
||||||
|
|
|
||||||
|
*/
|
||||||
|
|
||||||
|
'cookie' => env(
|
||||||
|
'SESSION_COOKIE',
|
||||||
|
Str::slug((string) env('APP_NAME', 'laravel')).'-session'
|
||||||
|
),
|
||||||
|
|
||||||
|
/*
|
||||||
|
|--------------------------------------------------------------------------
|
||||||
|
| Session Cookie Path
|
||||||
|
|--------------------------------------------------------------------------
|
||||||
|
|
|
||||||
|
| The session cookie path determines the path for which the cookie will
|
||||||
|
| be regarded as available. Typically, this will be the root path of
|
||||||
|
| your application, but you're free to change this when necessary.
|
||||||
|
|
|
||||||
|
*/
|
||||||
|
|
||||||
|
'path' => env('SESSION_PATH', '/'),
|
||||||
|
|
||||||
|
/*
|
||||||
|
|--------------------------------------------------------------------------
|
||||||
|
| Session Cookie Domain
|
||||||
|
|--------------------------------------------------------------------------
|
||||||
|
|
|
||||||
|
| This value determines the domain and subdomains the session cookie is
|
||||||
|
| available to. By default, the cookie will be available to the root
|
||||||
|
| domain without subdomains. Typically, this shouldn't be changed.
|
||||||
|
|
|
||||||
|
*/
|
||||||
|
|
||||||
|
'domain' => env('SESSION_DOMAIN'),
|
||||||
|
|
||||||
|
/*
|
||||||
|
|--------------------------------------------------------------------------
|
||||||
|
| HTTPS Only Cookies
|
||||||
|
|--------------------------------------------------------------------------
|
||||||
|
|
|
||||||
|
| By setting this option to true, session cookies will only be sent back
|
||||||
|
| to the server if the browser has a HTTPS connection. This will keep
|
||||||
|
| the cookie from being sent to you when it can't be done securely.
|
||||||
|
|
|
||||||
|
*/
|
||||||
|
|
||||||
|
'secure' => env('SESSION_SECURE_COOKIE'),
|
||||||
|
|
||||||
|
/*
|
||||||
|
|--------------------------------------------------------------------------
|
||||||
|
| HTTP Access Only
|
||||||
|
|--------------------------------------------------------------------------
|
||||||
|
|
|
||||||
|
| Setting this value to true will prevent JavaScript from accessing the
|
||||||
|
| value of the cookie and the cookie will only be accessible through
|
||||||
|
| the HTTP protocol. It's unlikely you should disable this option.
|
||||||
|
|
|
||||||
|
*/
|
||||||
|
|
||||||
|
'http_only' => env('SESSION_HTTP_ONLY', true),
|
||||||
|
|
||||||
|
/*
|
||||||
|
|--------------------------------------------------------------------------
|
||||||
|
| Same-Site Cookies
|
||||||
|
|--------------------------------------------------------------------------
|
||||||
|
|
|
||||||
|
| This option determines how your cookies behave when cross-site requests
|
||||||
|
| take place, and can be used to mitigate CSRF attacks. By default, we
|
||||||
|
| will set this value to "lax" to permit secure cross-site requests.
|
||||||
|
|
|
||||||
|
| See: https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/Set-Cookie#samesitesamesite-value
|
||||||
|
|
|
||||||
|
| Supported: "lax", "strict", "none", null
|
||||||
|
|
|
||||||
|
*/
|
||||||
|
|
||||||
|
'same_site' => env('SESSION_SAME_SITE', 'lax'),
|
||||||
|
|
||||||
|
/*
|
||||||
|
|--------------------------------------------------------------------------
|
||||||
|
| Partitioned Cookies
|
||||||
|
|--------------------------------------------------------------------------
|
||||||
|
|
|
||||||
|
| Setting this value to true will tie the cookie to the top-level site for
|
||||||
|
| a cross-site context. Partitioned cookies are accepted by the browser
|
||||||
|
| when flagged "secure" and the Same-Site attribute is set to "none".
|
||||||
|
|
|
||||||
|
*/
|
||||||
|
|
||||||
|
'partitioned' => env('SESSION_PARTITIONED_COOKIE', false),
|
||||||
|
|
||||||
|
/*
|
||||||
|
|--------------------------------------------------------------------------
|
||||||
|
| Session Serialization
|
||||||
|
|--------------------------------------------------------------------------
|
||||||
|
|
|
||||||
|
| This value controls the serialization strategy for session data, which
|
||||||
|
| is JSON by default. Setting this to "php" allows the storage of PHP
|
||||||
|
| objects in the session but can make an application vulnerable to
|
||||||
|
| "gadget chain" serialization attacks if the APP_KEY is leaked.
|
||||||
|
|
|
||||||
|
| Supported: "json", "php"
|
||||||
|
|
|
||||||
|
*/
|
||||||
|
|
||||||
|
'serialization' => 'json',
|
||||||
|
|
||||||
|
];
|
||||||
@@ -0,0 +1,37 @@
|
|||||||
|
#!/usr/bin/env php
|
||||||
|
<?php
|
||||||
|
|
||||||
|
use Illuminate\Foundation\Application;
|
||||||
|
use Symfony\Component\Console\Input\ArrayInput;
|
||||||
|
|
||||||
|
define('LARAVEL_START', microtime(true));
|
||||||
|
|
||||||
|
if (PHP_SAPI !== 'cli') {
|
||||||
|
http_response_code(403);
|
||||||
|
exit('Forbidden');
|
||||||
|
}
|
||||||
|
|
||||||
|
require __DIR__.'/vendor/autoload.php';
|
||||||
|
|
||||||
|
/** @var Application $app */
|
||||||
|
$app = require_once __DIR__.'/bootstrap/app.php';
|
||||||
|
|
||||||
|
$commands = [
|
||||||
|
['command' => 'contacts:sync-carddav'],
|
||||||
|
['command' => 'calendar:process-reminders', '--force-sync' => true],
|
||||||
|
['command' => 'sms-campaigns:send-due'],
|
||||||
|
['command' => 'sms-campaigns:reconcile'],
|
||||||
|
['command' => 'sms-campaigns:prune-history'],
|
||||||
|
];
|
||||||
|
|
||||||
|
$status = 0;
|
||||||
|
|
||||||
|
foreach ($commands as $command) {
|
||||||
|
$commandStatus = $app->handleCommand(new ArrayInput($command));
|
||||||
|
|
||||||
|
if ($commandStatus !== 0) {
|
||||||
|
$status = $commandStatus;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
exit($status);
|
||||||
@@ -0,0 +1 @@
|
|||||||
|
*.sqlite*
|
||||||
@@ -0,0 +1,45 @@
|
|||||||
|
<?php
|
||||||
|
|
||||||
|
namespace Database\Factories;
|
||||||
|
|
||||||
|
use App\Models\User;
|
||||||
|
use Illuminate\Database\Eloquent\Factories\Factory;
|
||||||
|
use Illuminate\Support\Facades\Hash;
|
||||||
|
use Illuminate\Support\Str;
|
||||||
|
|
||||||
|
/**
|
||||||
|
* @extends Factory<User>
|
||||||
|
*/
|
||||||
|
class UserFactory extends Factory
|
||||||
|
{
|
||||||
|
/**
|
||||||
|
* The current password being used by the factory.
|
||||||
|
*/
|
||||||
|
protected static ?string $password;
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Define the model's default state.
|
||||||
|
*
|
||||||
|
* @return array<string, mixed>
|
||||||
|
*/
|
||||||
|
public function definition(): array
|
||||||
|
{
|
||||||
|
return [
|
||||||
|
'name' => fake()->name(),
|
||||||
|
'email' => fake()->unique()->safeEmail(),
|
||||||
|
'email_verified_at' => now(),
|
||||||
|
'password' => static::$password ??= Hash::make('password'),
|
||||||
|
'remember_token' => Str::random(10),
|
||||||
|
];
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Indicate that the model's email address should be unverified.
|
||||||
|
*/
|
||||||
|
public function unverified(): static
|
||||||
|
{
|
||||||
|
return $this->state(fn (array $attributes) => [
|
||||||
|
'email_verified_at' => null,
|
||||||
|
]);
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,49 @@
|
|||||||
|
<?php
|
||||||
|
|
||||||
|
use Illuminate\Database\Migrations\Migration;
|
||||||
|
use Illuminate\Database\Schema\Blueprint;
|
||||||
|
use Illuminate\Support\Facades\Schema;
|
||||||
|
|
||||||
|
return new class extends Migration
|
||||||
|
{
|
||||||
|
/**
|
||||||
|
* Run the migrations.
|
||||||
|
*/
|
||||||
|
public function up(): void
|
||||||
|
{
|
||||||
|
Schema::create('users', function (Blueprint $table) {
|
||||||
|
$table->id();
|
||||||
|
$table->string('name');
|
||||||
|
$table->string('email')->unique();
|
||||||
|
$table->timestamp('email_verified_at')->nullable();
|
||||||
|
$table->string('password');
|
||||||
|
$table->rememberToken();
|
||||||
|
$table->timestamps();
|
||||||
|
});
|
||||||
|
|
||||||
|
Schema::create('password_reset_tokens', function (Blueprint $table) {
|
||||||
|
$table->string('email')->primary();
|
||||||
|
$table->string('token');
|
||||||
|
$table->timestamp('created_at')->nullable();
|
||||||
|
});
|
||||||
|
|
||||||
|
Schema::create('sessions', function (Blueprint $table) {
|
||||||
|
$table->string('id')->primary();
|
||||||
|
$table->foreignId('user_id')->nullable()->index();
|
||||||
|
$table->string('ip_address', 45)->nullable();
|
||||||
|
$table->text('user_agent')->nullable();
|
||||||
|
$table->longText('payload');
|
||||||
|
$table->integer('last_activity')->index();
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Reverse the migrations.
|
||||||
|
*/
|
||||||
|
public function down(): void
|
||||||
|
{
|
||||||
|
Schema::dropIfExists('users');
|
||||||
|
Schema::dropIfExists('password_reset_tokens');
|
||||||
|
Schema::dropIfExists('sessions');
|
||||||
|
}
|
||||||
|
};
|
||||||
@@ -0,0 +1,35 @@
|
|||||||
|
<?php
|
||||||
|
|
||||||
|
use Illuminate\Database\Migrations\Migration;
|
||||||
|
use Illuminate\Database\Schema\Blueprint;
|
||||||
|
use Illuminate\Support\Facades\Schema;
|
||||||
|
|
||||||
|
return new class extends Migration
|
||||||
|
{
|
||||||
|
/**
|
||||||
|
* Run the migrations.
|
||||||
|
*/
|
||||||
|
public function up(): void
|
||||||
|
{
|
||||||
|
Schema::create('cache', function (Blueprint $table) {
|
||||||
|
$table->string('key')->primary();
|
||||||
|
$table->mediumText('value');
|
||||||
|
$table->bigInteger('expiration')->index();
|
||||||
|
});
|
||||||
|
|
||||||
|
Schema::create('cache_locks', function (Blueprint $table) {
|
||||||
|
$table->string('key')->primary();
|
||||||
|
$table->string('owner');
|
||||||
|
$table->bigInteger('expiration')->index();
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Reverse the migrations.
|
||||||
|
*/
|
||||||
|
public function down(): void
|
||||||
|
{
|
||||||
|
Schema::dropIfExists('cache');
|
||||||
|
Schema::dropIfExists('cache_locks');
|
||||||
|
}
|
||||||
|
};
|
||||||
@@ -0,0 +1,59 @@
|
|||||||
|
<?php
|
||||||
|
|
||||||
|
use Illuminate\Database\Migrations\Migration;
|
||||||
|
use Illuminate\Database\Schema\Blueprint;
|
||||||
|
use Illuminate\Support\Facades\Schema;
|
||||||
|
|
||||||
|
return new class extends Migration
|
||||||
|
{
|
||||||
|
/**
|
||||||
|
* Run the migrations.
|
||||||
|
*/
|
||||||
|
public function up(): void
|
||||||
|
{
|
||||||
|
Schema::create('jobs', function (Blueprint $table) {
|
||||||
|
$table->id();
|
||||||
|
$table->string('queue')->index();
|
||||||
|
$table->longText('payload');
|
||||||
|
$table->unsignedSmallInteger('attempts');
|
||||||
|
$table->unsignedInteger('reserved_at')->nullable();
|
||||||
|
$table->unsignedInteger('available_at');
|
||||||
|
$table->unsignedInteger('created_at');
|
||||||
|
});
|
||||||
|
|
||||||
|
Schema::create('job_batches', function (Blueprint $table) {
|
||||||
|
$table->string('id')->primary();
|
||||||
|
$table->string('name');
|
||||||
|
$table->integer('total_jobs');
|
||||||
|
$table->integer('pending_jobs');
|
||||||
|
$table->integer('failed_jobs');
|
||||||
|
$table->longText('failed_job_ids');
|
||||||
|
$table->mediumText('options')->nullable();
|
||||||
|
$table->integer('cancelled_at')->nullable();
|
||||||
|
$table->integer('created_at');
|
||||||
|
$table->integer('finished_at')->nullable();
|
||||||
|
});
|
||||||
|
|
||||||
|
Schema::create('failed_jobs', function (Blueprint $table) {
|
||||||
|
$table->id();
|
||||||
|
$table->string('uuid')->unique();
|
||||||
|
$table->string('connection');
|
||||||
|
$table->string('queue');
|
||||||
|
$table->longText('payload');
|
||||||
|
$table->longText('exception');
|
||||||
|
$table->timestamp('failed_at')->useCurrent();
|
||||||
|
|
||||||
|
$table->index(['connection', 'queue', 'failed_at']);
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Reverse the migrations.
|
||||||
|
*/
|
||||||
|
public function down(): void
|
||||||
|
{
|
||||||
|
Schema::dropIfExists('jobs');
|
||||||
|
Schema::dropIfExists('job_batches');
|
||||||
|
Schema::dropIfExists('failed_jobs');
|
||||||
|
}
|
||||||
|
};
|
||||||
@@ -0,0 +1,24 @@
|
|||||||
|
<?php
|
||||||
|
|
||||||
|
use Illuminate\Database\Migrations\Migration;
|
||||||
|
use Illuminate\Database\Schema\Blueprint;
|
||||||
|
use Illuminate\Support\Facades\Schema;
|
||||||
|
|
||||||
|
return new class extends Migration
|
||||||
|
{
|
||||||
|
public function up(): void
|
||||||
|
{
|
||||||
|
Schema::create('app_settings', function (Blueprint $table) {
|
||||||
|
$table->id();
|
||||||
|
$table->string('key')->unique();
|
||||||
|
$table->text('value')->nullable();
|
||||||
|
$table->string('type')->default('string');
|
||||||
|
$table->timestamps();
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
|
public function down(): void
|
||||||
|
{
|
||||||
|
Schema::dropIfExists('app_settings');
|
||||||
|
}
|
||||||
|
};
|
||||||
@@ -0,0 +1,35 @@
|
|||||||
|
<?php
|
||||||
|
|
||||||
|
use Illuminate\Database\Migrations\Migration;
|
||||||
|
use Illuminate\Database\Schema\Blueprint;
|
||||||
|
use Illuminate\Support\Facades\Schema;
|
||||||
|
|
||||||
|
return new class extends Migration
|
||||||
|
{
|
||||||
|
public function up(): void
|
||||||
|
{
|
||||||
|
Schema::create('contacts', function (Blueprint $table) {
|
||||||
|
$table->id();
|
||||||
|
$table->string('source')->default('local')->index();
|
||||||
|
$table->string('external_id')->nullable();
|
||||||
|
$table->string('first_name')->nullable();
|
||||||
|
$table->string('last_name');
|
||||||
|
$table->string('organization')->nullable();
|
||||||
|
$table->string('email')->nullable();
|
||||||
|
$table->text('notes')->nullable();
|
||||||
|
$table->boolean('sms_opt_out')->default(false)->index();
|
||||||
|
$table->boolean('is_favorite')->default(false)->index();
|
||||||
|
$table->timestamp('synced_at')->nullable();
|
||||||
|
$table->timestamps();
|
||||||
|
$table->softDeletes();
|
||||||
|
|
||||||
|
$table->unique(['source', 'external_id']);
|
||||||
|
$table->index(['last_name', 'first_name']);
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
|
public function down(): void
|
||||||
|
{
|
||||||
|
Schema::dropIfExists('contacts');
|
||||||
|
}
|
||||||
|
};
|
||||||
@@ -0,0 +1,31 @@
|
|||||||
|
<?php
|
||||||
|
|
||||||
|
use Illuminate\Database\Migrations\Migration;
|
||||||
|
use Illuminate\Database\Schema\Blueprint;
|
||||||
|
use Illuminate\Support\Facades\Schema;
|
||||||
|
|
||||||
|
return new class extends Migration
|
||||||
|
{
|
||||||
|
public function up(): void
|
||||||
|
{
|
||||||
|
Schema::create('contact_groups', function (Blueprint $table) {
|
||||||
|
$table->id();
|
||||||
|
$table->string('source')->default('local')->index();
|
||||||
|
$table->string('external_id')->nullable();
|
||||||
|
$table->string('name');
|
||||||
|
$table->string('slug')->unique();
|
||||||
|
$table->text('description')->nullable();
|
||||||
|
$table->boolean('is_favorite')->default(false)->index();
|
||||||
|
$table->timestamp('synced_at')->nullable();
|
||||||
|
$table->timestamps();
|
||||||
|
$table->softDeletes();
|
||||||
|
|
||||||
|
$table->unique(['source', 'external_id']);
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
|
public function down(): void
|
||||||
|
{
|
||||||
|
Schema::dropIfExists('contact_groups');
|
||||||
|
}
|
||||||
|
};
|
||||||
@@ -0,0 +1,32 @@
|
|||||||
|
<?php
|
||||||
|
|
||||||
|
use Illuminate\Database\Migrations\Migration;
|
||||||
|
use Illuminate\Database\Schema\Blueprint;
|
||||||
|
use Illuminate\Support\Facades\Schema;
|
||||||
|
|
||||||
|
return new class extends Migration
|
||||||
|
{
|
||||||
|
public function up(): void
|
||||||
|
{
|
||||||
|
Schema::create('contact_phone_numbers', function (Blueprint $table) {
|
||||||
|
$table->id();
|
||||||
|
$table->foreignId('contact_id')->constrained()->cascadeOnDelete();
|
||||||
|
$table->string('label')->nullable();
|
||||||
|
$table->string('raw_number');
|
||||||
|
$table->string('normalized_number')->nullable()->index();
|
||||||
|
$table->string('country', 2)->nullable();
|
||||||
|
$table->boolean('is_valid')->default(false)->index();
|
||||||
|
$table->boolean('is_mobile')->default(false)->index();
|
||||||
|
$table->boolean('is_primary')->default(false);
|
||||||
|
$table->string('validation_error')->nullable();
|
||||||
|
$table->timestamps();
|
||||||
|
|
||||||
|
$table->index(['contact_id', 'is_primary']);
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
|
public function down(): void
|
||||||
|
{
|
||||||
|
Schema::dropIfExists('contact_phone_numbers');
|
||||||
|
}
|
||||||
|
};
|
||||||
@@ -0,0 +1,24 @@
|
|||||||
|
<?php
|
||||||
|
|
||||||
|
use Illuminate\Database\Migrations\Migration;
|
||||||
|
use Illuminate\Database\Schema\Blueprint;
|
||||||
|
use Illuminate\Support\Facades\Schema;
|
||||||
|
|
||||||
|
return new class extends Migration
|
||||||
|
{
|
||||||
|
public function up(): void
|
||||||
|
{
|
||||||
|
Schema::create('contact_contact_group', function (Blueprint $table) {
|
||||||
|
$table->foreignId('contact_id')->constrained()->cascadeOnDelete();
|
||||||
|
$table->foreignId('contact_group_id')->constrained()->cascadeOnDelete();
|
||||||
|
$table->timestamps();
|
||||||
|
|
||||||
|
$table->primary(['contact_id', 'contact_group_id']);
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
|
public function down(): void
|
||||||
|
{
|
||||||
|
Schema::dropIfExists('contact_contact_group');
|
||||||
|
}
|
||||||
|
};
|
||||||
@@ -0,0 +1,23 @@
|
|||||||
|
<?php
|
||||||
|
|
||||||
|
use Illuminate\Database\Migrations\Migration;
|
||||||
|
use Illuminate\Database\Schema\Blueprint;
|
||||||
|
use Illuminate\Support\Facades\Schema;
|
||||||
|
|
||||||
|
return new class extends Migration
|
||||||
|
{
|
||||||
|
public function up(): void
|
||||||
|
{
|
||||||
|
Schema::table('contacts', function (Blueprint $table) {
|
||||||
|
$table->string('remote_url')->nullable()->after('external_id');
|
||||||
|
$table->string('remote_etag')->nullable()->after('remote_url');
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
|
public function down(): void
|
||||||
|
{
|
||||||
|
Schema::table('contacts', function (Blueprint $table) {
|
||||||
|
$table->dropColumn(['remote_url', 'remote_etag']);
|
||||||
|
});
|
||||||
|
}
|
||||||
|
};
|
||||||
@@ -0,0 +1,30 @@
|
|||||||
|
<?php
|
||||||
|
|
||||||
|
use Illuminate\Database\Migrations\Migration;
|
||||||
|
use Illuminate\Database\Schema\Blueprint;
|
||||||
|
use Illuminate\Support\Facades\Schema;
|
||||||
|
|
||||||
|
return new class extends Migration
|
||||||
|
{
|
||||||
|
public function up(): void
|
||||||
|
{
|
||||||
|
Schema::create('source_sync_runs', function (Blueprint $table) {
|
||||||
|
$table->id();
|
||||||
|
$table->string('source')->index();
|
||||||
|
$table->string('status')->index();
|
||||||
|
$table->timestamp('started_at')->nullable();
|
||||||
|
$table->timestamp('finished_at')->nullable();
|
||||||
|
$table->unsignedInteger('fetched_contacts')->default(0);
|
||||||
|
$table->unsignedInteger('synced_contacts')->default(0);
|
||||||
|
$table->unsignedInteger('deleted_contacts')->default(0);
|
||||||
|
$table->text('message')->nullable();
|
||||||
|
$table->text('error')->nullable();
|
||||||
|
$table->timestamps();
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
|
public function down(): void
|
||||||
|
{
|
||||||
|
Schema::dropIfExists('source_sync_runs');
|
||||||
|
}
|
||||||
|
};
|
||||||
@@ -0,0 +1,37 @@
|
|||||||
|
<?php
|
||||||
|
|
||||||
|
use Illuminate\Database\Migrations\Migration;
|
||||||
|
use Illuminate\Database\Schema\Blueprint;
|
||||||
|
use Illuminate\Support\Facades\Schema;
|
||||||
|
|
||||||
|
return new class extends Migration
|
||||||
|
{
|
||||||
|
public function up(): void
|
||||||
|
{
|
||||||
|
Schema::create('sms_campaigns', function (Blueprint $table) {
|
||||||
|
$table->id();
|
||||||
|
$table->foreignId('user_id')->nullable()->constrained()->nullOnDelete();
|
||||||
|
$table->string('provider')->default('ovh')->index();
|
||||||
|
$table->string('status')->default('draft')->index();
|
||||||
|
$table->text('message');
|
||||||
|
$table->unsignedInteger('recipients_count')->default(0);
|
||||||
|
$table->unsignedInteger('sent_count')->default(0);
|
||||||
|
$table->unsignedInteger('failed_count')->default(0);
|
||||||
|
$table->string('provider_service_name')->nullable();
|
||||||
|
$table->string('provider_tag')->nullable()->index();
|
||||||
|
$table->string('provider_job_id')->nullable();
|
||||||
|
$table->json('request_payload')->nullable();
|
||||||
|
$table->json('response_payload')->nullable();
|
||||||
|
$table->text('error_message')->nullable();
|
||||||
|
$table->timestamp('sent_at')->nullable();
|
||||||
|
$table->timestamps();
|
||||||
|
|
||||||
|
$table->index(['created_at', 'status']);
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
|
public function down(): void
|
||||||
|
{
|
||||||
|
Schema::dropIfExists('sms_campaigns');
|
||||||
|
}
|
||||||
|
};
|
||||||
@@ -0,0 +1,33 @@
|
|||||||
|
<?php
|
||||||
|
|
||||||
|
use Illuminate\Database\Migrations\Migration;
|
||||||
|
use Illuminate\Database\Schema\Blueprint;
|
||||||
|
use Illuminate\Support\Facades\Schema;
|
||||||
|
|
||||||
|
return new class extends Migration
|
||||||
|
{
|
||||||
|
public function up(): void
|
||||||
|
{
|
||||||
|
Schema::create('sms_deliveries', function (Blueprint $table) {
|
||||||
|
$table->id();
|
||||||
|
$table->foreignId('sms_campaign_id')->constrained()->cascadeOnDelete();
|
||||||
|
$table->foreignId('contact_id')->nullable()->constrained()->nullOnDelete();
|
||||||
|
$table->foreignId('contact_phone_number_id')->nullable()->constrained()->nullOnDelete();
|
||||||
|
$table->string('contact_name');
|
||||||
|
$table->string('number')->index();
|
||||||
|
$table->string('status')->default('queued')->index();
|
||||||
|
$table->string('provider_message_id')->nullable();
|
||||||
|
$table->json('provider_response')->nullable();
|
||||||
|
$table->text('error_message')->nullable();
|
||||||
|
$table->timestamp('sent_at')->nullable();
|
||||||
|
$table->timestamps();
|
||||||
|
|
||||||
|
$table->index(['sms_campaign_id', 'status']);
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
|
public function down(): void
|
||||||
|
{
|
||||||
|
Schema::dropIfExists('sms_deliveries');
|
||||||
|
}
|
||||||
|
};
|
||||||
@@ -0,0 +1,28 @@
|
|||||||
|
<?php
|
||||||
|
|
||||||
|
use Illuminate\Database\Migrations\Migration;
|
||||||
|
use Illuminate\Database\Schema\Blueprint;
|
||||||
|
use Illuminate\Support\Facades\Schema;
|
||||||
|
|
||||||
|
return new class extends Migration
|
||||||
|
{
|
||||||
|
public function up(): void
|
||||||
|
{
|
||||||
|
Schema::table('sms_campaigns', function (Blueprint $table) {
|
||||||
|
$table->json('selected_contact_ids')->nullable()->after('recipients_count');
|
||||||
|
$table->json('selected_group_ids')->nullable()->after('selected_contact_ids');
|
||||||
|
$table->json('selected_group_names')->nullable()->after('selected_group_ids');
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
|
public function down(): void
|
||||||
|
{
|
||||||
|
Schema::table('sms_campaigns', function (Blueprint $table) {
|
||||||
|
$table->dropColumn([
|
||||||
|
'selected_contact_ids',
|
||||||
|
'selected_group_ids',
|
||||||
|
'selected_group_names',
|
||||||
|
]);
|
||||||
|
});
|
||||||
|
}
|
||||||
|
};
|
||||||
@@ -0,0 +1,35 @@
|
|||||||
|
<?php
|
||||||
|
|
||||||
|
use Illuminate\Database\Migrations\Migration;
|
||||||
|
use Illuminate\Database\Schema\Blueprint;
|
||||||
|
use Illuminate\Support\Facades\Schema;
|
||||||
|
|
||||||
|
return new class extends Migration
|
||||||
|
{
|
||||||
|
public function up(): void
|
||||||
|
{
|
||||||
|
Schema::create('calendar_events', function (Blueprint $table) {
|
||||||
|
$table->id();
|
||||||
|
$table->string('source')->index();
|
||||||
|
$table->string('external_id');
|
||||||
|
$table->string('remote_url')->nullable();
|
||||||
|
$table->string('remote_etag')->nullable();
|
||||||
|
$table->string('summary')->nullable();
|
||||||
|
$table->text('description')->nullable();
|
||||||
|
$table->string('location')->nullable();
|
||||||
|
$table->timestamp('starts_at')->nullable()->index();
|
||||||
|
$table->timestamp('ends_at')->nullable();
|
||||||
|
$table->json('attendees')->nullable();
|
||||||
|
$table->timestamp('synced_at')->nullable();
|
||||||
|
$table->timestamp('deleted_at')->nullable()->index();
|
||||||
|
$table->timestamps();
|
||||||
|
|
||||||
|
$table->unique(['source', 'external_id']);
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
|
public function down(): void
|
||||||
|
{
|
||||||
|
Schema::dropIfExists('calendar_events');
|
||||||
|
}
|
||||||
|
};
|
||||||
@@ -0,0 +1,33 @@
|
|||||||
|
<?php
|
||||||
|
|
||||||
|
use Illuminate\Database\Migrations\Migration;
|
||||||
|
use Illuminate\Database\Schema\Blueprint;
|
||||||
|
use Illuminate\Support\Facades\Schema;
|
||||||
|
|
||||||
|
return new class extends Migration
|
||||||
|
{
|
||||||
|
public function up(): void
|
||||||
|
{
|
||||||
|
Schema::create('calendar_reminders', function (Blueprint $table) {
|
||||||
|
$table->id();
|
||||||
|
$table->foreignId('calendar_event_id')->constrained()->cascadeOnDelete();
|
||||||
|
$table->foreignId('sms_campaign_id')->nullable()->constrained()->nullOnDelete();
|
||||||
|
$table->string('reminder_key');
|
||||||
|
$table->string('action')->default('DISPLAY')->index();
|
||||||
|
$table->integer('trigger_minutes')->nullable();
|
||||||
|
$table->timestamp('remind_at')->nullable()->index();
|
||||||
|
$table->string('status')->default('pending')->index();
|
||||||
|
$table->text('last_error')->nullable();
|
||||||
|
$table->timestamp('sent_at')->nullable();
|
||||||
|
$table->timestamps();
|
||||||
|
|
||||||
|
$table->unique(['calendar_event_id', 'reminder_key']);
|
||||||
|
$table->index(['status', 'remind_at']);
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
|
public function down(): void
|
||||||
|
{
|
||||||
|
Schema::dropIfExists('calendar_reminders');
|
||||||
|
}
|
||||||
|
};
|
||||||
@@ -0,0 +1,24 @@
|
|||||||
|
<?php
|
||||||
|
|
||||||
|
use Illuminate\Database\Migrations\Migration;
|
||||||
|
use Illuminate\Database\Schema\Blueprint;
|
||||||
|
use Illuminate\Support\Facades\Schema;
|
||||||
|
|
||||||
|
return new class extends Migration
|
||||||
|
{
|
||||||
|
public function up(): void
|
||||||
|
{
|
||||||
|
Schema::table('sms_campaigns', function (Blueprint $table) {
|
||||||
|
$table->timestamp('scheduled_at')->nullable()->after('error_message')->index();
|
||||||
|
$table->timestamp('canceled_at')->nullable()->after('sent_at');
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
|
public function down(): void
|
||||||
|
{
|
||||||
|
Schema::table('sms_campaigns', function (Blueprint $table) {
|
||||||
|
$table->dropIndex(['scheduled_at']);
|
||||||
|
$table->dropColumn(['scheduled_at', 'canceled_at']);
|
||||||
|
});
|
||||||
|
}
|
||||||
|
};
|
||||||
Some files were not shown because too many files have changed in this diff Show More
Reference in New Issue
Block a user