20 Commits

Author SHA1 Message Date
4ddac65367 fix(migrations): adopt existing scheduling schema 2026-07-20 19:25:32 +02:00
2570192e06 fix(migrations): give scheduling revision a unique id 2026-07-20 19:10:21 +02:00
297e3ad96e chore(scheduling): bump contract version to 0.1.9 2026-07-20 18:49:24 +02:00
705ac823ce feat(webui): configure participant roster visibility 2026-07-20 18:47:46 +02:00
6141f39bf8 feat(scheduling): enforce participant roster privacy 2026-07-20 18:44:28 +02:00
d0b95eee58 fix(webui): submit scheduling option revisions 2026-07-20 18:36:10 +02:00
bbf503a7d7 fix(responses): reject stale scheduling answers 2026-07-20 18:35:57 +02:00
0f33e25c83 feat(responses): preserve editable availability history 2026-07-20 18:22:21 +02:00
6f298c36fe feat(scheduling): prefill participant availability 2026-07-20 18:18:18 +02:00
ec538f524d feat(scheduling): compose request editor from core UI 2026-07-20 18:10:48 +02:00
887e064ae9 feat(scheduling): add a task-focused poll workspace 2026-07-20 17:34:36 +02:00
fc418e63ac feat(scheduling): prioritize request worklists 2026-07-20 17:34:30 +02:00
de7e68c97a feat(scheduling): harden poll-backed request flows 2026-07-20 17:34:13 +02:00
2f1b7fb6b8 intermittent commit 2026-07-14 13:22:12 +02:00
c1afce7bdb Add scheduling calendar integration and WebUI 2026-07-12 19:00:54 +02:00
ace32a2a3d Add poll-backed scheduling backend 2026-07-12 18:12:20 +02:00
cfea0edb97 Model scheduling as poll-backed workflow 2026-07-12 17:32:07 +02:00
e9e2b56360 Make Access optional for Scheduling 2026-07-12 09:32:16 +02:00
99db968edf Initialize Scheduling module manifest 2026-07-12 09:23:18 +02:00
564635c776 Release v0.1.8 2026-07-11 16:49:04 +02:00
35 changed files with 8772 additions and 12 deletions

235
LICENSE Normal file
View File

@@ -0,0 +1,235 @@
GNU AFFERO GENERAL PUBLIC LICENSE
Version 3, 19 November 2007
Copyright (C) 2007 Free Software Foundation, Inc. <http://fsf.org/>
Everyone is permitted to copy and distribute verbatim copies of this license document, but changing it is not allowed.
Preamble
The GNU Affero General Public License is a free, copyleft license for software and other kinds of works, specifically designed to ensure cooperation with the community in the case of network server software.
The licenses for most software and other practical works are designed to take away your freedom to share and change the works. By contrast, our General Public Licenses are intended to guarantee your freedom to share and change all versions of a program--to make sure it remains free software for all its users.
When we speak of free software, we are referring to freedom, not price. Our General Public Licenses are designed to make sure that you have the freedom to distribute copies of free software (and charge for them if you wish), that you receive source code or can get it if you want it, that you can change the software or use pieces of it in new free programs, and that you know you can do these things.
Developers that use our General Public Licenses protect your rights with two steps: (1) assert copyright on the software, and (2) offer you this License which gives you legal permission to copy, distribute and/or modify the software.
A secondary benefit of defending all users' freedom is that improvements made in alternate versions of the program, if they receive widespread use, become available for other developers to incorporate. Many developers of free software are heartened and encouraged by the resulting cooperation. However, in the case of software used on network servers, this result may fail to come about. The GNU General Public License permits making a modified version and letting the public access it on a server without ever releasing its source code to the public.
The GNU Affero General Public License is designed specifically to ensure that, in such cases, the modified source code becomes available to the community. It requires the operator of a network server to provide the source code of the modified version running there to the users of that server. Therefore, public use of a modified version, on a publicly accessible server, gives the public access to the source code of the modified version.
An older license, called the Affero General Public License and published by Affero, was designed to accomplish similar goals. This is a different license, not a version of the Affero GPL, but Affero has released a new version of the Affero GPL which permits relicensing under this license.
The precise terms and conditions for copying, distribution and modification follow.
TERMS AND CONDITIONS
0. Definitions.
"This License" refers to version 3 of the GNU Affero General Public License.
"Copyright" also means copyright-like laws that apply to other kinds of works, such as semiconductor masks.
"The Program" refers to any copyrightable work licensed under this License. Each licensee is addressed as "you". "Licensees" and "recipients" may be individuals or organizations.
To "modify" a work means to copy from or adapt all or part of the work in a fashion requiring copyright permission, other than the making of an exact copy. The resulting work is called a "modified version" of the earlier work or a work "based on" the earlier work.
A "covered work" means either the unmodified Program or a work based on the Program.
To "propagate" a work means to do anything with it that, without permission, would make you directly or secondarily liable for infringement under applicable copyright law, except executing it on a computer or modifying a private copy. Propagation includes copying, distribution (with or without modification), making available to the public, and in some countries other activities as well.
To "convey" a work means any kind of propagation that enables other parties to make or receive copies. Mere interaction with a user through a computer network, with no transfer of a copy, is not conveying.
An interactive user interface displays "Appropriate Legal Notices" to the extent that it includes a convenient and prominently visible feature that (1) displays an appropriate copyright notice, and (2) tells the user that there is no warranty for the work (except to the extent that warranties are provided), that licensees may convey the work under this License, and how to view a copy of this License. If the interface presents a list of user commands or options, such as a menu, a prominent item in the list meets this criterion.
1. Source Code.
The "source code" for a work means the preferred form of the work for making modifications to it. "Object code" means any non-source form of a work.
A "Standard Interface" means an interface that either is an official standard defined by a recognized standards body, or, in the case of interfaces specified for a particular programming language, one that is widely used among developers working in that language.
The "System Libraries" of an executable work include anything, other than the work as a whole, that (a) is included in the normal form of packaging a Major Component, but which is not part of that Major Component, and (b) serves only to enable use of the work with that Major Component, or to implement a Standard Interface for which an implementation is available to the public in source code form. A "Major Component", in this context, means a major essential component (kernel, window system, and so on) of the specific operating system (if any) on which the executable work runs, or a compiler used to produce the work, or an object code interpreter used to run it.
The "Corresponding Source" for a work in object code form means all the source code needed to generate, install, and (for an executable work) run the object code and to modify the work, including scripts to control those activities. However, it does not include the work's System Libraries, or general-purpose tools or generally available free programs which are used unmodified in performing those activities but which are not part of the work. For example, Corresponding Source includes interface definition files associated with source files for the work, and the source code for shared libraries and dynamically linked subprograms that the work is specifically designed to require, such as by intimate data communication or control flow between those
subprograms and other parts of the work.
The Corresponding Source need not include anything that users can regenerate automatically from other parts of the Corresponding Source.
The Corresponding Source for a work in source code form is that same work.
2. Basic Permissions.
All rights granted under this License are granted for the term of copyright on the Program, and are irrevocable provided the stated conditions are met. This License explicitly affirms your unlimited permission to run the unmodified Program. The output from running a covered work is covered by this License only if the output, given its content, constitutes a covered work. This License acknowledges your rights of fair use or other equivalent, as provided by copyright law.
You may make, run and propagate covered works that you do not convey, without conditions so long as your license otherwise remains in force. You may convey covered works to others for the sole purpose of having them make modifications exclusively for you, or provide you with facilities for running those works, provided that you comply with the terms of this License in conveying all material for which you do not control copyright. Those thus making or running the covered works for you must do so exclusively on your behalf, under your direction and control, on terms that prohibit them from making any copies of your copyrighted material outside their relationship with you.
Conveying under any other circumstances is permitted solely under the conditions stated below. Sublicensing is not allowed; section 10 makes it unnecessary.
3. Protecting Users' Legal Rights From Anti-Circumvention Law.
No covered work shall be deemed part of an effective technological measure under any applicable law fulfilling obligations under article 11 of the WIPO copyright treaty adopted on 20 December 1996, or similar laws prohibiting or restricting circumvention of such measures.
When you convey a covered work, you waive any legal power to forbid circumvention of technological measures to the extent such circumvention is effected by exercising rights under this License with respect to the covered work, and you disclaim any intention to limit operation or modification of the work as a means of enforcing, against the work's users, your or third parties' legal rights to forbid circumvention of technological measures.
4. Conveying Verbatim Copies.
You may convey verbatim copies of the Program's source code as you receive it, in any medium, provided that you conspicuously and appropriately publish on each copy an appropriate copyright notice; keep intact all notices stating that this License and any non-permissive terms added in accord with section 7 apply to the code; keep intact all notices of the absence of any warranty; and give all recipients a copy of this License along with the Program.
You may charge any price or no price for each copy that you convey, and you may offer support or warranty protection for a fee.
5. Conveying Modified Source Versions.
You may convey a work based on the Program, or the modifications to produce it from the Program, in the form of source code under the terms of section 4, provided that you also meet all of these conditions:
a) The work must carry prominent notices stating that you modified it, and giving a relevant date.
b) The work must carry prominent notices stating that it is released under this License and any conditions added under section 7. This requirement modifies the requirement in section 4 to "keep intact all notices".
c) You must license the entire work, as a whole, under this License to anyone who comes into possession of a copy. This License will therefore apply, along with any applicable section 7 additional terms, to the whole of the work, and all its parts, regardless of how they are packaged. This License gives no permission to license the work in any other way, but it does not invalidate such permission if you have separately received it.
d) If the work has interactive user interfaces, each must display Appropriate Legal Notices; however, if the Program has interactive interfaces that do not display Appropriate Legal Notices, your work need not make them do so.
A compilation of a covered work with other separate and independent works, which are not by their nature extensions of the covered work, and which are not combined with it such as to form a larger program, in or on a volume of a storage or distribution medium, is called an "aggregate" if the compilation and its resulting copyright are not used to limit the access or legal rights of the compilation's users beyond what the individual works permit. Inclusion of a covered work in an aggregate does not cause this License to apply to the other parts of the aggregate.
6. Conveying Non-Source Forms.
You may convey a covered work in object code form under the terms of sections 4 and 5, provided that you also convey the machine-readable Corresponding Source under the terms of this License, in one of these ways:
a) Convey the object code in, or embodied in, a physical product (including a physical distribution medium), accompanied by the Corresponding Source fixed on a durable physical medium customarily used for software interchange.
b) Convey the object code in, or embodied in, a physical product (including a physical distribution medium), accompanied by a written offer, valid for at least three years and valid for as long as you offer spare parts or customer support for that product model, to give anyone who possesses the object code either (1) a copy of the Corresponding Source for all the software in the product that is covered by this License, on a durable physical medium customarily used for software interchange, for a price no more than your reasonable cost of physically performing this conveying of source, or (2) access to copy the Corresponding Source from a network server at no charge.
c) Convey individual copies of the object code with a copy of the written offer to provide the Corresponding Source. This alternative is allowed only occasionally and noncommercially, and only if you received the object code with such an offer, in accord with subsection 6b.
d) Convey the object code by offering access from a designated place (gratis or for a charge), and offer equivalent access to the Corresponding Source in the same way through the same place at no further charge. You need not require recipients to copy the Corresponding Source along with the object code. If the place to copy the object code is a network server, the Corresponding Source may be on a different server (operated by you or a third party) that supports equivalent copying facilities, provided you maintain clear directions next to the object code saying where to find the Corresponding Source. Regardless of what server hosts the Corresponding Source, you remain obligated to ensure that it is available for as long as needed to satisfy these requirements.
e) Convey the object code using peer-to-peer transmission, provided you inform other peers where the object code and Corresponding Source of the work are being offered to the general public at no charge under subsection 6d.
A separable portion of the object code, whose source code is excluded from the Corresponding Source as a System Library, need not be included in conveying the object code work.
A "User Product" is either (1) a "consumer product", which means any tangible personal property which is normally used for personal, family, or household purposes, or (2) anything designed or sold for incorporation into a dwelling. In determining whether a product is a consumer product, doubtful cases shall be resolved in favor of coverage. For a particular product received by a particular user, "normally used" refers to a typical or common use of that class of product, regardless of the status of the particular user or of the way in which the particular user actually uses, or expects or is expected to use, the product. A product is a consumer product regardless of whether the product has substantial commercial, industrial or non-consumer uses, unless such uses represent the only significant mode of use of the product.
"Installation Information" for a User Product means any methods, procedures, authorization keys, or other information required to install and execute modified versions of a covered work in that User Product from a modified version of its Corresponding Source. The information must suffice to ensure that the continued functioning of the modified object code is in no case prevented or interfered with solely because modification has been made.
If you convey an object code work under this section in, or with, or specifically for use in, a User Product, and the conveying occurs as part of a transaction in which the right of possession and use of the User Product is transferred to the recipient in perpetuity or for a fixed term (regardless of how the transaction is characterized), the Corresponding Source conveyed under this section must be accompanied by the Installation Information. But this requirement does not apply if neither you nor any third party retains the ability to install modified object code on the User Product (for example, the work has been installed in ROM).
The requirement to provide Installation Information does not include a requirement to continue to provide support service, warranty, or updates for a work that has been modified or installed by the recipient, or for the User Product in which it has been modified or installed. Access to a network may be denied when the modification itself materially and adversely affects the operation of the network or violates the rules and protocols for communication across the network.
Corresponding Source conveyed, and Installation Information provided, in accord with this section must be in a format that is publicly documented (and with an implementation available to the public in source code form), and must require no special password or key for unpacking, reading or copying.
7. Additional Terms.
"Additional permissions" are terms that supplement the terms of this License by making exceptions from one or more of its conditions. Additional permissions that are applicable to the entire Program shall be treated as though they were included in this License, to the extent that they are valid under applicable law. If additional permissions apply only to part of the Program, that part may be used separately under those permissions, but the entire Program remains governed by this License without regard to the additional permissions.
When you convey a copy of a covered work, you may at your option remove any additional permissions from that copy, or from any part of it. (Additional permissions may be written to require their own removal in certain cases when you modify the work.) You may place additional permissions on material, added by you to a covered work, for which you have or can give appropriate copyright permission.
Notwithstanding any other provision of this License, for material you add to a covered work, you may (if authorized by the copyright holders of that material) supplement the terms of this License with terms:
a) Disclaiming warranty or limiting liability differently from the terms of sections 15 and 16 of this License; or
b) Requiring preservation of specified reasonable legal notices or author attributions in that material or in the Appropriate Legal Notices displayed by works containing it; or
c) Prohibiting misrepresentation of the origin of that material, or requiring that modified versions of such material be marked in reasonable ways as different from the original version; or
d) Limiting the use for publicity purposes of names of licensors or authors of the material; or
e) Declining to grant rights under trademark law for use of some trade names, trademarks, or service marks; or
f) Requiring indemnification of licensors and authors of that material by anyone who conveys the material (or modified versions of it) with contractual assumptions of liability to the recipient, for any liability that these contractual assumptions directly impose on those licensors and authors.
All other non-permissive additional terms are considered "further restrictions" within the meaning of section 10. If the Program as you received it, or any part of it, contains a notice stating that it is governed by this License along with a term that is a further restriction, you may remove that term. If a license document contains a further restriction but permits relicensing or conveying under this License, you may add to a covered work material governed by the terms of that license document, provided that the further restriction does not survive such relicensing or conveying.
If you add terms to a covered work in accord with this section, you must place, in the relevant source files, a statement of the additional terms that apply to those files, or a notice indicating where to find the applicable terms.
Additional terms, permissive or non-permissive, may be stated in the form of a separately written license, or stated as exceptions; the above requirements apply either way.
8. Termination.
You may not propagate or modify a covered work except as expressly provided under this License. Any attempt otherwise to propagate or modify it is void, and will automatically terminate your rights under this License (including any patent licenses granted under the third paragraph of section 11).
However, if you cease all violation of this License, then your license from a particular copyright holder is reinstated (a) provisionally, unless and until the copyright holder explicitly and finally terminates your license, and (b) permanently, if the copyright holder fails to notify you of the violation by some reasonable means prior to 60 days after the cessation.
Moreover, your license from a particular copyright holder is reinstated permanently if the copyright holder notifies you of the violation by some reasonable means, this is the first time you have received notice of violation of this License (for any work) from that copyright holder, and you cure the violation prior to 30 days after your receipt of the notice.
Termination of your rights under this section does not terminate the licenses of parties who have received copies or rights from you under this License. If your rights have been terminated and not permanently reinstated, you do not qualify to receive new licenses for the same material under section 10.
9. Acceptance Not Required for Having Copies.
You are not required to accept this License in order to receive or run a copy of the Program. Ancillary propagation of a covered work occurring solely as a consequence of using peer-to-peer transmission to receive a copy likewise does not require acceptance. However, nothing other than this License grants you permission to propagate or modify any covered work. These actions infringe copyright if you do not accept this License. Therefore, by modifying or propagating a covered work, you indicate your acceptance of this License to do so.
10. Automatic Licensing of Downstream Recipients.
Each time you convey a covered work, the recipient automatically receives a license from the original licensors, to run, modify and propagate that work, subject to this License. You are not responsible for enforcing compliance by third parties with this License.
An "entity transaction" is a transaction transferring control of an organization, or substantially all assets of one, or subdividing an organization, or merging organizations. If propagation of a covered work results from an entity transaction, each party to that transaction who receives a copy of the work also receives whatever licenses to the work the party's predecessor in interest had or could give under the previous paragraph, plus a right to possession of the Corresponding Source of the work from the predecessor in interest, if the predecessor has it or can get it with reasonable efforts.
You may not impose any further restrictions on the exercise of the rights granted or affirmed under this License. For example, you may not impose a license fee, royalty, or other charge for exercise of rights granted under this License, and you may not initiate litigation (including a cross-claim or counterclaim in a lawsuit) alleging that any patent claim is infringed by making, using, selling, offering for sale, or importing the Program or any portion of it.
11. Patents.
A "contributor" is a copyright holder who authorizes use under this License of the Program or a work on which the Program is based. The work thus licensed is called the contributor's "contributor version".
A contributor's "essential patent claims" are all patent claims owned or controlled by the contributor, whether already acquired or hereafter acquired, that would be infringed by some manner, permitted by this License, of making, using, or selling its contributor version, but do not include claims that would be infringed only as a consequence of further modification of the contributor version. For purposes of this definition, "control" includes the right to grant patent sublicenses in a manner consistent with the requirements of this License.
Each contributor grants you a non-exclusive, worldwide, royalty-free patent license under the contributor's essential patent claims, to make, use, sell, offer for sale, import and otherwise run, modify and propagate the contents of its contributor version.
In the following three paragraphs, a "patent license" is any express agreement or commitment, however denominated, not to enforce a patent (such as an express permission to practice a patent or covenant not to sue for patent infringement). To "grant" such a patent license to a party means to make such an agreement or commitment not to enforce a patent against the party.
If you convey a covered work, knowingly relying on a patent license, and the Corresponding Source of the work is not available for anyone to copy, free of charge and under the terms of this License, through a publicly available network server or other readily accessible means, then you must either (1) cause the Corresponding Source to be so available, or (2) arrange to deprive yourself of the benefit of the patent license for this particular work, or (3) arrange, in a manner consistent with the requirements of this License, to extend the patent
license to downstream recipients. "Knowingly relying" means you have actual knowledge that, but for the patent license, your conveying the covered work in a country, or your recipient's use of the covered work in a country, would infringe one or more identifiable patents in that country that you have reason to believe are valid.
If, pursuant to or in connection with a single transaction or arrangement, you convey, or propagate by procuring conveyance of, a covered work, and grant a patent license to some of the parties receiving the covered work authorizing them to use, propagate, modify or convey a specific copy of the covered work, then the patent license you grant is automatically extended to all recipients of the covered work and works based on it.
A patent license is "discriminatory" if it does not include within the scope of its coverage, prohibits the exercise of, or is conditioned on the non-exercise of one or more of the rights that are specifically granted under this License. You may not convey a covered work if you are a party to an arrangement with a third party that is in the business of distributing software, under which you make payment to the third party based on the extent of your activity of conveying the work, and under which the third party grants, to any of the parties who would receive the covered work from you, a discriminatory patent license (a) in connection with copies of the covered work conveyed by you (or copies made from those copies), or (b) primarily for and in connection with specific products or compilations that contain the covered work, unless you entered into that arrangement, or that patent license was granted, prior to 28 March 2007.
Nothing in this License shall be construed as excluding or limiting any implied license or other defenses to infringement that may otherwise be available to you under applicable patent law.
12. No Surrender of Others' Freedom.
If conditions are imposed on you (whether by court order, agreement or otherwise) that contradict the conditions of this License, they do not excuse you from the conditions of this License. If you cannot convey a covered work so as to satisfy simultaneously your obligations under this License and any other pertinent obligations, then as a consequence you may
not convey it at all. For example, if you agree to terms that obligate you to collect a royalty for further conveying from those to whom you convey the Program, the only way you could satisfy both those terms and this License would be to refrain entirely from conveying the Program.
13. Remote Network Interaction; Use with the GNU General Public License.
Notwithstanding any other provision of this License, if you modify the Program, your modified version must prominently offer all users interacting with it remotely through a computer network (if your version supports such interaction) an opportunity to receive the Corresponding Source of your version by providing access to the Corresponding Source from a network server at no charge, through some standard or customary means of facilitating copying of software. This Corresponding Source shall include the Corresponding Source for any work covered by version 3 of the GNU General Public License that is incorporated pursuant to the following paragraph.
Notwithstanding any other provision of this License, you have permission to link or combine any covered work with a work licensed under version 3 of the GNU General Public License into a single combined work, and to convey the resulting work. The terms of this License will continue to apply to the part which is the covered work, but the work with which it is combined will remain governed by version 3 of the GNU General Public License.
14. Revised Versions of this License.
The Free Software Foundation may publish revised and/or new versions of the GNU Affero General Public License from time to time. Such new versions will be similar in spirit to the present version, but may differ in detail to address new problems or concerns.
Each version is given a distinguishing version number. If the Program specifies that a certain numbered version of the GNU Affero General Public License "or any later version" applies to it, you have the option of following the terms and conditions either of that numbered version or of any later version published by the Free Software Foundation. If the Program does not specify a version number of the GNU Affero General Public License, you may choose any version ever published by the Free Software Foundation.
If the Program specifies that a proxy can decide which future versions of the GNU Affero General Public License can be used, that proxy's public statement of acceptance of a version permanently authorizes you to choose that version for the Program.
Later license versions may give you additional or different permissions. However, no additional obligations are imposed on any author or copyright holder as a result of your choosing to follow a later version.
15. Disclaimer of Warranty.
THERE IS NO WARRANTY FOR THE PROGRAM, TO THE EXTENT PERMITTED BY APPLICABLE LAW. EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT HOLDERS AND/OR OTHER PARTIES PROVIDE THE PROGRAM "AS IS" WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE. THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE PROGRAM IS WITH YOU. SHOULD THE PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF ALL NECESSARY SERVICING, REPAIR OR CORRECTION.
16. Limitation of Liability.
IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MODIFIES AND/OR CONVEYS THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES, INCLUDING ANY GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED TO LOSS OF DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER PROGRAMS), EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF SUCH DAMAGES.
17. Interpretation of Sections 15 and 16.
If the disclaimer of warranty and limitation of liability provided above cannot be given local legal effect according to their terms, reviewing courts shall apply local law that most closely approximates an absolute waiver of all civil liability in connection with the Program, unless a warranty or assumption of liability accompanies a copy of the Program in return for a fee.
END OF TERMS AND CONDITIONS
How to Apply These Terms to Your New Programs
If you develop a new program, and you want it to be of the greatest possible use to the public, the best way to achieve this is to make it free software which everyone can redistribute and change under these terms.
To do so, attach the following notices to the program. It is safest to attach them to the start of each source file to most effectively state the exclusion of warranty; and each file should have at least the "copyright" line and a pointer to where the full notice is found.
govoplan-files
Copyright (C) 2026 add-ideas
This program is free software: you can redistribute it and/or modify it under the terms of the GNU Affero General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version.
This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Affero General Public License for more details.
You should have received a copy of the GNU Affero General Public License along with this program. If not, see <http://www.gnu.org/licenses/>.
Also add information on how to contact you by electronic and paper mail.
If your software can interact with users remotely through a computer network, you should also make sure that it provides a way for users to get its source. For example, if your program is a web application, its interface could display a "Source" link that leads users to an archive of the code. There are many ways you could offer source, and different solutions will be better for different programs; see section 13 for the specific requirements.
You should also get your employer (if you work as a programmer) or school, if any, to sign a "copyright disclaimer" for the program, if necessary. For more information on this, and how to apply and follow the GNU AGPL, see <http://www.gnu.org/licenses/>.

View File

@@ -1,12 +1,17 @@
# GovOPlaN Scheduling
<!-- govoplan-repository-type:start -->
**Repository type:** module (domain).
<!-- govoplan-repository-type:end -->
GovOPlaN Scheduling owns meeting scheduling and `Terminfindung`: finding
suitable times across people, resources, calendars, constraints, and scheduling
polls.
This repository is currently a tag-only scaffold. It should gain package
metadata, a backend manifest, and a WebUI package together when the first
implementation slice is designed.
This repository is initialized as a discoverable module seed. It exposes the
module manifest, permission surface, role templates, and documentation metadata
before runtime APIs, database models, migrations, and WebUI routes are
introduced.
The core boundary decision register is in
`/mnt/DATA/git/govoplan-core/docs/MODULE_ARCHITECTURE.md`.
@@ -15,7 +20,7 @@ The core boundary decision register is in
Scheduling owns:
- meeting scheduling polls and proposals
- meeting scheduling polls and proposals built on `govoplan-poll`
- participant availability collection
- time-window and resource constraints
- candidate-slot ranking and conflict explanation
@@ -64,24 +69,52 @@ unless a configured process requires longer evidence retention.
- `scheduling.decisionHandoff`
- `scheduling.portalParticipation`
## Manifest Dependency Decision
The Scheduling manifest declares `poll` as a required dependency because
availability collection and option/date poll primitives belong in
`govoplan-poll`.
Scheduling should model each meeting-finding flow as a poll-backed workflow:
Poll owns candidate options, signed participation links, responses, visibility,
and result aggregation. Scheduling stores the scheduling-specific context and
uses Poll context fields to point back to its request or proposal resource.
Typical workflow steps are collect availability, rank candidates, decide, notify
participants, and hand off to Calendar or Appointments.
The manifest declares `access` and `evaluation` as optional dependencies.
Scheduling may use Access for identity, groups, and permissions, and may trigger
post-event or post-appointment feedback through Evaluation. It must not require
either module just to find a meeting time.
## Expected Integrations
- `govoplan-poll`: required availability matrix and lightweight poll primitives
- `govoplan-evaluation`: optional post-event, post-appointment, or process feedback
- `govoplan-calendar`: availability, calendars, resources, rooms, recurrence, Open-Xchange/calendar adapters
- `govoplan-appointments`: conversion from a selected meeting time into a booked appointment where appropriate
- `govoplan-access` and `govoplan-idm`: participants, groups, directory lookup, permissions
- `govoplan-access` and `govoplan-idm`: optional participants, groups, directory lookup, permissions
- `govoplan-mail` and `govoplan-notifications`: invitations, reminders, confirmations
- `govoplan-portal`: external participant scheduling flows
- `govoplan-workflow` and `govoplan-tasks`: follow-up work after a time is selected
## First Package Scaffold Decision
The first scaffold should include both backend and WebUI package metadata once
implementation starts:
The first backend implementation slice adds runtime APIs and storage around
poll-backed scheduling requests:
- backend manifest, permissions, DTOs, and APIs for internal polls
- WebUI route contribution for poll creation and response collection
- capability contracts for calendar free/busy, access/IDM lookup,
mail/notification sending, portal participation links, appointment handoff,
and workflow/task follow-up
- scheduling request, candidate slot, and participant storage
- automatic `govoplan-poll` availability poll creation
- signed poll invitations for internal or external participants
- request lifecycle APIs: draft, collecting, closed, decided, handed off, cancelled
- result summaries sourced from Poll response aggregation
- optional Calendar free/busy checks, tentative holds, and final event creation
- notification outbox jobs for invitations, reminders, decisions, and cancellations
- a first Scheduling WebUI package with request creation, slot matrix, Calendar
actions, decisions, and notification-job creation
The next slices should add real notification delivery workers, richer public
participant pages, Calendar hold cleanup after decision, and advanced scoring
constraints such as required participants and quorum rules.
The active backlog lives in Gitea issues.

25
pyproject.toml Normal file
View File

@@ -0,0 +1,25 @@
[build-system]
requires = ["setuptools>=69", "wheel"]
build-backend = "setuptools.build_meta"
[project]
name = "govoplan-scheduling"
version = "0.1.9"
description = "GovOPlaN meeting scheduling and Terminfindung module seed."
readme = "README.md"
requires-python = ">=3.12"
license = { file = "LICENSE" }
authors = [{ name = "GovOPlaN" }]
dependencies = [
"govoplan-core>=0.1.9",
"govoplan-poll>=0.1.9",
]
[tool.setuptools.packages.find]
where = ["src"]
[tool.setuptools.package-data]
govoplan_scheduling = ["py.typed"]
[project.entry-points."govoplan.modules"]
scheduling = "govoplan_scheduling.backend.manifest:get_manifest"

View File

@@ -0,0 +1,5 @@
"""GovOPlaN Scheduling module."""
__all__ = ["__version__"]
__version__ = "0.1.9"

View File

@@ -0,0 +1 @@
"""Backend package for the GovOPlaN Scheduling module."""

View File

@@ -0,0 +1,5 @@
from __future__ import annotations
from govoplan_scheduling.backend.db.models import SchedulingCandidateSlot, SchedulingNotification, SchedulingParticipant, SchedulingRequest
__all__ = ["SchedulingCandidateSlot", "SchedulingNotification", "SchedulingParticipant", "SchedulingRequest"]

View File

@@ -0,0 +1,144 @@
from __future__ import annotations
import uuid
from datetime import datetime
from typing import Any
from sqlalchemy import Boolean, DateTime, ForeignKey, Index, Integer, JSON, String, Text
from sqlalchemy.orm import Mapped, mapped_column, relationship
from govoplan_core.db.base import Base, TimestampMixin
def new_uuid() -> str:
return str(uuid.uuid4())
class SchedulingRequest(Base, TimestampMixin):
__tablename__ = "scheduling_requests"
__table_args__ = (
Index("ix_scheduling_requests_tenant_status", "tenant_id", "status"),
Index("ix_scheduling_requests_tenant_poll", "tenant_id", "poll_id"),
Index("ix_scheduling_requests_deadline", "tenant_id", "deadline_at"),
)
id: Mapped[str] = mapped_column(String(36), primary_key=True, default=new_uuid)
tenant_id: Mapped[str] = mapped_column(String(36), nullable=False, index=True)
title: Mapped[str] = mapped_column(String(500), nullable=False)
description: Mapped[str | None] = mapped_column(Text)
location: Mapped[str | None] = mapped_column(String(500))
timezone: Mapped[str] = mapped_column(String(100), default="UTC", nullable=False)
status: Mapped[str] = mapped_column(String(40), default="draft", nullable=False, index=True)
poll_id: Mapped[str | None] = mapped_column(String(36), nullable=True, index=True)
selected_slot_id: Mapped[str | None] = mapped_column(String(36), nullable=True, index=True)
organizer_user_id: Mapped[str | None] = mapped_column(String(36), nullable=True, index=True)
deadline_at: Mapped[datetime | None] = mapped_column(DateTime(timezone=True), nullable=True, index=True)
allow_external_participants: Mapped[bool] = mapped_column(Boolean, default=True, nullable=False)
allow_participant_updates: Mapped[bool] = mapped_column(Boolean, default=True, nullable=False)
result_visibility: Mapped[str] = mapped_column(String(30), default="after_close", nullable=False)
participant_visibility: Mapped[str] = mapped_column(String(32), default="aggregates_only", nullable=False)
calendar_integration_enabled: Mapped[bool] = mapped_column(Boolean, default=False, nullable=False)
calendar_id: Mapped[str | None] = mapped_column(String(36), nullable=True, index=True)
calendar_freebusy_enabled: Mapped[bool] = mapped_column(Boolean, default=False, nullable=False)
calendar_hold_enabled: Mapped[bool] = mapped_column(Boolean, default=False, nullable=False)
create_calendar_event_on_decision: Mapped[bool] = mapped_column(Boolean, default=False, nullable=False)
calendar_event_id: Mapped[str | None] = mapped_column(String(36), nullable=True, index=True)
handed_off_at: Mapped[datetime | None] = mapped_column(DateTime(timezone=True), nullable=True)
cancelled_at: Mapped[datetime | None] = mapped_column(DateTime(timezone=True), nullable=True)
deleted_at: Mapped[datetime | None] = mapped_column(DateTime(timezone=True), nullable=True, index=True)
metadata_: Mapped[dict[str, Any] | None] = mapped_column("metadata", JSON, nullable=True)
slots: Mapped[list["SchedulingCandidateSlot"]] = relationship(
back_populates="request",
cascade="all, delete-orphan",
order_by="SchedulingCandidateSlot.position",
)
participants: Mapped[list["SchedulingParticipant"]] = relationship(
back_populates="request",
cascade="all, delete-orphan",
order_by="SchedulingParticipant.created_at",
)
class SchedulingCandidateSlot(Base, TimestampMixin):
__tablename__ = "scheduling_candidate_slots"
__table_args__ = (
Index("ix_scheduling_candidate_slots_request_position", "request_id", "position"),
Index("ix_scheduling_candidate_slots_range", "tenant_id", "start_at", "end_at"),
)
id: Mapped[str] = mapped_column(String(36), primary_key=True, default=new_uuid)
tenant_id: Mapped[str] = mapped_column(String(36), nullable=False, index=True)
request_id: Mapped[str] = mapped_column(ForeignKey("scheduling_requests.id", ondelete="CASCADE"), nullable=False, index=True)
poll_option_id: Mapped[str | None] = mapped_column(String(36), nullable=True, index=True)
label: Mapped[str] = mapped_column(String(500), nullable=False)
description: Mapped[str | None] = mapped_column(Text)
start_at: Mapped[datetime] = mapped_column(DateTime(timezone=True), nullable=False, index=True)
end_at: Mapped[datetime] = mapped_column(DateTime(timezone=True), nullable=False, index=True)
timezone: Mapped[str] = mapped_column(String(100), default="UTC", nullable=False)
location: Mapped[str | None] = mapped_column(String(500))
position: Mapped[int] = mapped_column(Integer, default=0, nullable=False)
freebusy_checked_at: Mapped[datetime | None] = mapped_column(DateTime(timezone=True), nullable=True)
freebusy_status: Mapped[str | None] = mapped_column(String(40), nullable=True, index=True)
freebusy_conflicts: Mapped[list[dict[str, Any]]] = mapped_column(JSON, default=list, nullable=False)
tentative_hold_event_id: Mapped[str | None] = mapped_column(String(36), nullable=True, index=True)
deleted_at: Mapped[datetime | None] = mapped_column(DateTime(timezone=True), nullable=True, index=True)
metadata_: Mapped[dict[str, Any] | None] = mapped_column("metadata", JSON, nullable=True)
request: Mapped[SchedulingRequest] = relationship(back_populates="slots")
class SchedulingParticipant(Base, TimestampMixin):
__tablename__ = "scheduling_participants"
__table_args__ = (
Index("ix_scheduling_participants_request", "tenant_id", "request_id"),
Index("ix_scheduling_participants_request_email", "request_id", "email"),
Index("ix_scheduling_participants_request_respondent", "request_id", "respondent_id"),
)
id: Mapped[str] = mapped_column(String(36), primary_key=True, default=new_uuid)
tenant_id: Mapped[str] = mapped_column(String(36), nullable=False, index=True)
request_id: Mapped[str] = mapped_column(ForeignKey("scheduling_requests.id", ondelete="CASCADE"), nullable=False, index=True)
respondent_id: Mapped[str | None] = mapped_column(String(255), nullable=True, index=True)
display_name: Mapped[str | None] = mapped_column(String(500), nullable=True)
email: Mapped[str | None] = mapped_column(String(320), nullable=True, index=True)
participant_type: Mapped[str] = mapped_column(String(30), default="external", nullable=False, index=True)
required: Mapped[bool] = mapped_column(Boolean, default=True, nullable=False)
status: Mapped[str] = mapped_column(String(40), default="invited", nullable=False, index=True)
poll_invitation_id: Mapped[str | None] = mapped_column(String(36), nullable=True, index=True)
last_invited_at: Mapped[datetime | None] = mapped_column(DateTime(timezone=True), nullable=True)
responded_at: Mapped[datetime | None] = mapped_column(DateTime(timezone=True), nullable=True)
deleted_at: Mapped[datetime | None] = mapped_column(DateTime(timezone=True), nullable=True, index=True)
metadata_: Mapped[dict[str, Any] | None] = mapped_column("metadata", JSON, nullable=True)
request: Mapped[SchedulingRequest] = relationship(back_populates="participants")
class SchedulingNotification(Base, TimestampMixin):
__tablename__ = "scheduling_notifications"
__table_args__ = (
Index("ix_scheduling_notifications_request_status", "request_id", "status"),
Index("ix_scheduling_notifications_tenant_status", "tenant_id", "status"),
)
id: Mapped[str] = mapped_column(String(36), primary_key=True, default=new_uuid)
tenant_id: Mapped[str] = mapped_column(String(36), nullable=False, index=True)
request_id: Mapped[str] = mapped_column(ForeignKey("scheduling_requests.id", ondelete="CASCADE"), nullable=False, index=True)
participant_id: Mapped[str | None] = mapped_column(String(36), nullable=True, index=True)
event_kind: Mapped[str] = mapped_column(String(40), nullable=False, index=True)
channel: Mapped[str] = mapped_column(String(40), default="mail", nullable=False, index=True)
recipient: Mapped[str | None] = mapped_column(String(500), nullable=True, index=True)
status: Mapped[str] = mapped_column(String(40), default="pending", nullable=False, index=True)
payload: Mapped[dict[str, Any]] = mapped_column(JSON, default=dict, nullable=False)
error: Mapped[str | None] = mapped_column(Text)
sent_at: Mapped[datetime | None] = mapped_column(DateTime(timezone=True), nullable=True)
metadata_: Mapped[dict[str, Any] | None] = mapped_column("metadata", JSON, nullable=True)
__all__ = [
"SchedulingCandidateSlot",
"SchedulingNotification",
"SchedulingParticipant",
"SchedulingRequest",
"new_uuid",
]

View File

@@ -0,0 +1,193 @@
from __future__ import annotations
from pathlib import Path
from govoplan_core.core.access import CAPABILITY_AUTH_PERMISSION_EVALUATOR, CAPABILITY_AUTH_PRINCIPAL_RESOLVER
from govoplan_core.core.calendar import CAPABILITY_CALENDAR_SCHEDULING
from govoplan_core.core.module_guards import drop_table_retirement_provider, persistent_table_uninstall_guard
from govoplan_core.core.modules import (
DocumentationTopic,
FrontendModule,
MigrationSpec,
ModuleContext,
ModuleInterfaceProvider,
ModuleInterfaceRequirement,
ModuleManifest,
NavItem,
PermissionDefinition,
RoleTemplate,
)
from govoplan_core.db.base import Base
from govoplan_core.core.poll import CAPABILITY_POLL_SCHEDULING
from govoplan_core.core.policy import CAPABILITY_POLICY_SCHEDULING_PARTICIPANT_PRIVACY
from govoplan_scheduling.backend.db import models as scheduling_models # noqa: F401 - populate Scheduling ORM metadata
MODULE_ID = "scheduling"
MODULE_NAME = "Scheduling"
MODULE_VERSION = "0.1.9"
READ_SCOPE = "scheduling:schedule:read"
WRITE_SCOPE = "scheduling:schedule:write"
ADMIN_SCOPE = "scheduling:schedule:admin"
RESPOND_SCOPE = "scheduling:availability:write"
def _permission(scope: str, label: str, description: str) -> PermissionDefinition:
module_id, resource, action = scope.split(":", 2)
return PermissionDefinition(
scope=scope,
label=label,
description=description,
category="Scheduling",
level="tenant",
module_id=module_id,
resource=resource,
action=action,
)
PERMISSIONS = (
_permission(READ_SCOPE, "View scheduling", "Read scheduling polls, proposals, participant state, and selected outcomes."),
_permission(WRITE_SCOPE, "Manage scheduling", "Create and update scheduling polls, candidate slots, reminders, and decision handoff."),
_permission(ADMIN_SCOPE, "Administer scheduling", "Configure tenant-level scheduling policies, external participation, and retention defaults."),
_permission(RESPOND_SCOPE, "Respond to scheduling polls", "Submit and update own scheduling availability responses."),
)
ROLE_TEMPLATES = (
RoleTemplate(
slug="scheduling_manager",
name="Scheduling manager",
description="Create scheduling polls, manage candidate slots, and decide outcomes.",
permissions=(READ_SCOPE, WRITE_SCOPE, RESPOND_SCOPE),
),
RoleTemplate(
slug="scheduling_participant",
name="Scheduling participant",
description="Read assigned scheduling polls and submit own availability.",
permissions=(READ_SCOPE, RESPOND_SCOPE),
),
)
DOCUMENTATION = (
DocumentationTopic(
id="scheduling.module-boundary",
title="Scheduling module boundary",
summary="Meeting scheduling and Terminfindung built on reusable Poll availability primitives.",
body=(
"Scheduling owns meeting scheduling workflows, candidate slots, participant availability "
"collection, conflict explanation, reminders, and decision handoff. It depends on Poll "
"for reusable availability matrices and poll-backed workflow context, and can optionally "
"trigger Evaluation for post-event feedback. "
"Access is optional: when installed, Scheduling can use principal resolution, permission "
"evaluation, groups, and role templates; without it, reduced signed-link or local organizer "
"flows remain possible."
),
layer="available",
documentation_types=("admin",),
audience=("operator", "module_admin", "product_owner"),
related_modules=("poll", "evaluation", "calendar", "appointments", "mail", "notifications", "portal"),
metadata={"seed": True},
),
)
def _tenant_summary(session, tenant_id: str) -> dict[str, int]:
from govoplan_scheduling.backend.db.models import SchedulingCandidateSlot, SchedulingNotification, SchedulingParticipant, SchedulingRequest
return {
"scheduling_requests": (
session.query(SchedulingRequest)
.filter(SchedulingRequest.tenant_id == tenant_id, SchedulingRequest.deleted_at.is_(None))
.count()
),
"scheduling_candidate_slots": (
session.query(SchedulingCandidateSlot)
.filter(SchedulingCandidateSlot.tenant_id == tenant_id, SchedulingCandidateSlot.deleted_at.is_(None))
.count()
),
"scheduling_participants": (
session.query(SchedulingParticipant)
.filter(SchedulingParticipant.tenant_id == tenant_id, SchedulingParticipant.deleted_at.is_(None))
.count()
),
"scheduling_notifications": (
session.query(SchedulingNotification)
.filter(SchedulingNotification.tenant_id == tenant_id, SchedulingNotification.status == "pending")
.count()
),
}
def _scheduling_router(context: ModuleContext):
from govoplan_scheduling.backend.runtime import configure_runtime
from govoplan_scheduling.backend.router import router
configure_runtime(registry=context.registry, settings=context.settings)
return router
manifest = ModuleManifest(
id=MODULE_ID,
name=MODULE_NAME,
version=MODULE_VERSION,
dependencies=("poll",),
optional_dependencies=("access", "calendar", "appointments", "evaluation", "mail", "notifications", "policy", "portal", "workflow", "tasks", "idm", "organizations", "addresses"),
optional_capabilities=(
CAPABILITY_AUTH_PRINCIPAL_RESOLVER,
CAPABILITY_AUTH_PERMISSION_EVALUATOR,
CAPABILITY_CALENDAR_SCHEDULING,
CAPABILITY_POLICY_SCHEDULING_PARTICIPANT_PRIVACY,
),
required_capabilities=(CAPABILITY_POLL_SCHEDULING,),
provides_interfaces=(
ModuleInterfaceProvider(name="scheduling.candidate_slots", version="0.1.9"),
ModuleInterfaceProvider(name="scheduling.decision_handoff", version="0.1.9"),
),
requires_interfaces=(
ModuleInterfaceRequirement(name="poll.availability_matrix", version_min="0.1.9", version_max_exclusive="0.2.0"),
ModuleInterfaceRequirement(name="poll.response_collection", version_min="0.1.9", version_max_exclusive="0.2.0"),
ModuleInterfaceRequirement(name="poll.workflow_context", version_min="0.1.9", version_max_exclusive="0.2.0"),
ModuleInterfaceRequirement(name="poll.signed_participation", version_min="0.1.8", version_max_exclusive="0.2.0", optional=True),
ModuleInterfaceRequirement(name="evaluation.feedback", version_min="0.1.8", version_max_exclusive="0.2.0", optional=True),
ModuleInterfaceRequirement(name="notifications.dispatch", version_min="0.1.8", version_max_exclusive="0.2.0", optional=True),
ModuleInterfaceRequirement(name="addresses.lookup", version_min="0.1.0", version_max_exclusive="0.2.0", optional=True),
ModuleInterfaceRequirement(name="calendar.scheduling", version_min="0.1.8", version_max_exclusive="0.2.0", optional=True),
),
permissions=PERMISSIONS,
role_templates=ROLE_TEMPLATES,
nav_items=(NavItem(path="/scheduling", label="Scheduling", icon="calendar-clock", required_any=(READ_SCOPE,), order=56),),
frontend=FrontendModule(
module_id=MODULE_ID,
package_name="@govoplan/scheduling-webui",
nav_items=(NavItem(path="/scheduling", label="Scheduling", icon="calendar-clock", required_any=(READ_SCOPE,), order=56),),
),
route_factory=_scheduling_router,
tenant_summary_providers=(_tenant_summary,),
migration_spec=MigrationSpec(
module_id=MODULE_ID,
metadata=Base.metadata,
script_location=str(Path(__file__).with_name("migrations") / "versions"),
retirement_supported=True,
retirement_provider=drop_table_retirement_provider(
scheduling_models.SchedulingRequest,
scheduling_models.SchedulingCandidateSlot,
scheduling_models.SchedulingParticipant,
scheduling_models.SchedulingNotification,
label="Scheduling",
),
retirement_notes="Destructive retirement drops scheduling-owned database tables after the installer captures a database snapshot.",
),
uninstall_guard_providers=(
persistent_table_uninstall_guard(
scheduling_models.SchedulingRequest,
scheduling_models.SchedulingCandidateSlot,
scheduling_models.SchedulingParticipant,
scheduling_models.SchedulingNotification,
label="Scheduling",
),
),
documentation=DOCUMENTATION,
)
def get_manifest() -> ModuleManifest:
return manifest

View File

@@ -0,0 +1 @@
from __future__ import annotations

View File

@@ -0,0 +1,320 @@
"""v0.1.8 scheduling baseline
Revision ID: 3c4d5e6f7a8b
Revises: None
Create Date: 2026-07-12 00:00:00.000000
"""
from __future__ import annotations
from alembic import op
import sqlalchemy as sa
revision = "3c4d5e6f7a8b"
down_revision = None
branch_labels = None
depends_on = "2a3b4c5d6e7f"
_BASELINE_COLUMNS = {
"scheduling_requests": {
"id",
"tenant_id",
"title",
"description",
"location",
"timezone",
"status",
"poll_id",
"selected_slot_id",
"organizer_user_id",
"deadline_at",
"allow_external_participants",
"allow_participant_updates",
"result_visibility",
"calendar_integration_enabled",
"calendar_id",
"calendar_freebusy_enabled",
"calendar_hold_enabled",
"create_calendar_event_on_decision",
"calendar_event_id",
"handed_off_at",
"cancelled_at",
"deleted_at",
"metadata",
"created_at",
"updated_at",
},
"scheduling_candidate_slots": {
"id",
"tenant_id",
"request_id",
"poll_option_id",
"label",
"description",
"start_at",
"end_at",
"timezone",
"location",
"position",
"deleted_at",
"metadata",
"created_at",
"updated_at",
},
"scheduling_participants": {
"id",
"tenant_id",
"request_id",
"respondent_id",
"display_name",
"email",
"participant_type",
"required",
"status",
"poll_invitation_id",
"last_invited_at",
"responded_at",
"deleted_at",
"metadata",
"created_at",
"updated_at",
},
}
_BASELINE_INDEXES = {
"scheduling_requests": {
"ix_scheduling_requests_calendar_event_id",
"ix_scheduling_requests_calendar_id",
"ix_scheduling_requests_deadline",
"ix_scheduling_requests_deadline_at",
"ix_scheduling_requests_deleted_at",
"ix_scheduling_requests_organizer_user_id",
"ix_scheduling_requests_poll_id",
"ix_scheduling_requests_selected_slot_id",
"ix_scheduling_requests_status",
"ix_scheduling_requests_tenant_id",
"ix_scheduling_requests_tenant_poll",
"ix_scheduling_requests_tenant_status",
},
"scheduling_candidate_slots": {
"ix_scheduling_candidate_slots_deleted_at",
"ix_scheduling_candidate_slots_end_at",
"ix_scheduling_candidate_slots_poll_option_id",
"ix_scheduling_candidate_slots_range",
"ix_scheduling_candidate_slots_request_id",
"ix_scheduling_candidate_slots_request_position",
"ix_scheduling_candidate_slots_start_at",
"ix_scheduling_candidate_slots_tenant_id",
},
"scheduling_participants": {
"ix_scheduling_participants_deleted_at",
"ix_scheduling_participants_email",
"ix_scheduling_participants_last_invited_at",
"ix_scheduling_participants_participant_type",
"ix_scheduling_participants_poll_invitation_id",
"ix_scheduling_participants_request",
"ix_scheduling_participants_request_email",
"ix_scheduling_participants_request_id",
"ix_scheduling_participants_request_respondent",
"ix_scheduling_participants_responded_at",
"ix_scheduling_participants_respondent_id",
"ix_scheduling_participants_status",
"ix_scheduling_participants_tenant_id",
},
}
def _request_foreign_key_exists(inspector: sa.Inspector, table_name: str) -> bool:
return any(
tuple(item.get("constrained_columns") or ()) == ("request_id",)
and item.get("referred_table") == "scheduling_requests"
and tuple(item.get("referred_columns") or ()) == ("id",)
and str((item.get("options") or {}).get("ondelete", "")).upper() == "CASCADE"
for item in inspector.get_foreign_keys(table_name)
)
def _adopt_existing_baseline() -> bool:
"""Adopt the complete unversioned Scheduling baseline, never a partial one."""
inspector = sa.inspect(op.get_bind())
expected_tables = set(_BASELINE_COLUMNS)
present_tables = expected_tables.intersection(inspector.get_table_names())
if not present_tables:
return False
problems: list[str] = []
missing_tables = expected_tables - present_tables
if missing_tables:
problems.append(f"missing tables: {', '.join(sorted(missing_tables))}")
for table_name in sorted(present_tables):
columns = {item["name"] for item in inspector.get_columns(table_name)}
missing_columns = _BASELINE_COLUMNS[table_name] - columns
if missing_columns:
problems.append(f"{table_name} missing columns: {', '.join(sorted(missing_columns))}")
indexes = {item["name"] for item in inspector.get_indexes(table_name)}
missing_indexes = _BASELINE_INDEXES[table_name] - indexes
if missing_indexes:
problems.append(f"{table_name} missing indexes: {', '.join(sorted(missing_indexes))}")
primary_key = tuple(inspector.get_pk_constraint(table_name).get("constrained_columns") or ())
if primary_key != ("id",):
problems.append(f"{table_name} has unexpected primary key: {primary_key!r}")
for table_name in ("scheduling_candidate_slots", "scheduling_participants"):
if table_name in present_tables and not _request_foreign_key_exists(inspector, table_name):
problems.append(f"{table_name} is missing its cascading request_id foreign key")
if problems:
detail = "; ".join(problems)
raise RuntimeError(
"Cannot adopt the existing Scheduling v0.1.8 baseline because it is incomplete or ambiguous: "
f"{detail}"
)
return True
def upgrade() -> None:
if _adopt_existing_baseline():
return
op.create_table(
"scheduling_requests",
sa.Column("id", sa.String(length=36), nullable=False),
sa.Column("tenant_id", sa.String(length=36), nullable=False),
sa.Column("title", sa.String(length=500), nullable=False),
sa.Column("description", sa.Text(), nullable=True),
sa.Column("location", sa.String(length=500), nullable=True),
sa.Column("timezone", sa.String(length=100), nullable=False),
sa.Column("status", sa.String(length=40), nullable=False),
sa.Column("poll_id", sa.String(length=36), nullable=True),
sa.Column("selected_slot_id", sa.String(length=36), nullable=True),
sa.Column("organizer_user_id", sa.String(length=36), nullable=True),
sa.Column("deadline_at", sa.DateTime(timezone=True), nullable=True),
sa.Column("allow_external_participants", sa.Boolean(), nullable=False),
sa.Column("allow_participant_updates", sa.Boolean(), nullable=False),
sa.Column("result_visibility", sa.String(length=30), nullable=False),
sa.Column("calendar_integration_enabled", sa.Boolean(), nullable=False),
sa.Column("calendar_id", sa.String(length=36), nullable=True),
sa.Column("calendar_freebusy_enabled", sa.Boolean(), nullable=False),
sa.Column("calendar_hold_enabled", sa.Boolean(), nullable=False),
sa.Column("create_calendar_event_on_decision", sa.Boolean(), nullable=False),
sa.Column("calendar_event_id", sa.String(length=36), nullable=True),
sa.Column("handed_off_at", sa.DateTime(timezone=True), nullable=True),
sa.Column("cancelled_at", sa.DateTime(timezone=True), nullable=True),
sa.Column("deleted_at", sa.DateTime(timezone=True), nullable=True),
sa.Column("metadata", sa.JSON(), nullable=True),
sa.Column("created_at", sa.DateTime(timezone=True), nullable=False),
sa.Column("updated_at", sa.DateTime(timezone=True), nullable=False),
sa.PrimaryKeyConstraint("id", name=op.f("pk_scheduling_requests")),
)
op.create_index(op.f("ix_scheduling_requests_calendar_event_id"), "scheduling_requests", ["calendar_event_id"], unique=False)
op.create_index(op.f("ix_scheduling_requests_calendar_id"), "scheduling_requests", ["calendar_id"], unique=False)
op.create_index(op.f("ix_scheduling_requests_deadline_at"), "scheduling_requests", ["deadline_at"], unique=False)
op.create_index(op.f("ix_scheduling_requests_deleted_at"), "scheduling_requests", ["deleted_at"], unique=False)
op.create_index(op.f("ix_scheduling_requests_organizer_user_id"), "scheduling_requests", ["organizer_user_id"], unique=False)
op.create_index(op.f("ix_scheduling_requests_poll_id"), "scheduling_requests", ["poll_id"], unique=False)
op.create_index(op.f("ix_scheduling_requests_selected_slot_id"), "scheduling_requests", ["selected_slot_id"], unique=False)
op.create_index(op.f("ix_scheduling_requests_status"), "scheduling_requests", ["status"], unique=False)
op.create_index(op.f("ix_scheduling_requests_tenant_id"), "scheduling_requests", ["tenant_id"], unique=False)
op.create_index("ix_scheduling_requests_deadline", "scheduling_requests", ["tenant_id", "deadline_at"], unique=False)
op.create_index("ix_scheduling_requests_tenant_poll", "scheduling_requests", ["tenant_id", "poll_id"], unique=False)
op.create_index("ix_scheduling_requests_tenant_status", "scheduling_requests", ["tenant_id", "status"], unique=False)
op.create_table(
"scheduling_candidate_slots",
sa.Column("id", sa.String(length=36), nullable=False),
sa.Column("tenant_id", sa.String(length=36), nullable=False),
sa.Column("request_id", sa.String(length=36), nullable=False),
sa.Column("poll_option_id", sa.String(length=36), nullable=True),
sa.Column("label", sa.String(length=500), nullable=False),
sa.Column("description", sa.Text(), nullable=True),
sa.Column("start_at", sa.DateTime(timezone=True), nullable=False),
sa.Column("end_at", sa.DateTime(timezone=True), nullable=False),
sa.Column("timezone", sa.String(length=100), nullable=False),
sa.Column("location", sa.String(length=500), nullable=True),
sa.Column("position", sa.Integer(), nullable=False),
sa.Column("deleted_at", sa.DateTime(timezone=True), nullable=True),
sa.Column("metadata", sa.JSON(), nullable=True),
sa.Column("created_at", sa.DateTime(timezone=True), nullable=False),
sa.Column("updated_at", sa.DateTime(timezone=True), nullable=False),
sa.ForeignKeyConstraint(
["request_id"],
["scheduling_requests.id"],
name=op.f("fk_scheduling_candidate_slots_request_id_scheduling_requests"),
ondelete="CASCADE",
),
sa.PrimaryKeyConstraint("id", name=op.f("pk_scheduling_candidate_slots")),
)
op.create_index(op.f("ix_scheduling_candidate_slots_deleted_at"), "scheduling_candidate_slots", ["deleted_at"], unique=False)
op.create_index(op.f("ix_scheduling_candidate_slots_end_at"), "scheduling_candidate_slots", ["end_at"], unique=False)
op.create_index(op.f("ix_scheduling_candidate_slots_poll_option_id"), "scheduling_candidate_slots", ["poll_option_id"], unique=False)
op.create_index(op.f("ix_scheduling_candidate_slots_request_id"), "scheduling_candidate_slots", ["request_id"], unique=False)
op.create_index(op.f("ix_scheduling_candidate_slots_start_at"), "scheduling_candidate_slots", ["start_at"], unique=False)
op.create_index(op.f("ix_scheduling_candidate_slots_tenant_id"), "scheduling_candidate_slots", ["tenant_id"], unique=False)
op.create_index(
"ix_scheduling_candidate_slots_range",
"scheduling_candidate_slots",
["tenant_id", "start_at", "end_at"],
unique=False,
)
op.create_index(
"ix_scheduling_candidate_slots_request_position",
"scheduling_candidate_slots",
["request_id", "position"],
unique=False,
)
op.create_table(
"scheduling_participants",
sa.Column("id", sa.String(length=36), nullable=False),
sa.Column("tenant_id", sa.String(length=36), nullable=False),
sa.Column("request_id", sa.String(length=36), nullable=False),
sa.Column("respondent_id", sa.String(length=255), nullable=True),
sa.Column("display_name", sa.String(length=500), nullable=True),
sa.Column("email", sa.String(length=320), nullable=True),
sa.Column("participant_type", sa.String(length=30), nullable=False),
sa.Column("required", sa.Boolean(), nullable=False),
sa.Column("status", sa.String(length=40), nullable=False),
sa.Column("poll_invitation_id", sa.String(length=36), nullable=True),
sa.Column("last_invited_at", sa.DateTime(timezone=True), nullable=True),
sa.Column("responded_at", sa.DateTime(timezone=True), nullable=True),
sa.Column("deleted_at", sa.DateTime(timezone=True), nullable=True),
sa.Column("metadata", sa.JSON(), nullable=True),
sa.Column("created_at", sa.DateTime(timezone=True), nullable=False),
sa.Column("updated_at", sa.DateTime(timezone=True), nullable=False),
sa.ForeignKeyConstraint(
["request_id"],
["scheduling_requests.id"],
name=op.f("fk_scheduling_participants_request_id_scheduling_requests"),
ondelete="CASCADE",
),
sa.PrimaryKeyConstraint("id", name=op.f("pk_scheduling_participants")),
)
op.create_index(op.f("ix_scheduling_participants_deleted_at"), "scheduling_participants", ["deleted_at"], unique=False)
op.create_index(op.f("ix_scheduling_participants_email"), "scheduling_participants", ["email"], unique=False)
op.create_index(op.f("ix_scheduling_participants_last_invited_at"), "scheduling_participants", ["last_invited_at"], unique=False)
op.create_index(op.f("ix_scheduling_participants_participant_type"), "scheduling_participants", ["participant_type"], unique=False)
op.create_index(op.f("ix_scheduling_participants_poll_invitation_id"), "scheduling_participants", ["poll_invitation_id"], unique=False)
op.create_index(op.f("ix_scheduling_participants_request_id"), "scheduling_participants", ["request_id"], unique=False)
op.create_index(op.f("ix_scheduling_participants_responded_at"), "scheduling_participants", ["responded_at"], unique=False)
op.create_index(op.f("ix_scheduling_participants_respondent_id"), "scheduling_participants", ["respondent_id"], unique=False)
op.create_index(op.f("ix_scheduling_participants_status"), "scheduling_participants", ["status"], unique=False)
op.create_index(op.f("ix_scheduling_participants_tenant_id"), "scheduling_participants", ["tenant_id"], unique=False)
op.create_index("ix_scheduling_participants_request", "scheduling_participants", ["tenant_id", "request_id"], unique=False)
op.create_index("ix_scheduling_participants_request_email", "scheduling_participants", ["request_id", "email"], unique=False)
op.create_index(
"ix_scheduling_participants_request_respondent",
"scheduling_participants",
["request_id", "respondent_id"],
unique=False,
)
def downgrade() -> None:
op.drop_table("scheduling_participants")
op.drop_table("scheduling_candidate_slots")
op.drop_table("scheduling_requests")

View File

@@ -0,0 +1,195 @@
"""v0.1.8 scheduling calendar integration and notification outbox
Revision ID: 4d5e6f7a8b9c
Revises: 3c4d5e6f7a8b
Create Date: 2026-07-12 00:00:00.000000
"""
from __future__ import annotations
from alembic import op
import sqlalchemy as sa
revision = "4d5e6f7a8b9c"
down_revision = "3c4d5e6f7a8b"
branch_labels = None
depends_on = None
_CALENDAR_SLOT_COLUMNS = {
"freebusy_checked_at",
"freebusy_status",
"freebusy_conflicts",
"tentative_hold_event_id",
}
_CALENDAR_SLOT_INDEXES = {
"ix_scheduling_candidate_slots_freebusy_status",
"ix_scheduling_candidate_slots_tentative_hold_event_id",
}
_NOTIFICATION_COLUMNS = {
"id",
"tenant_id",
"request_id",
"participant_id",
"event_kind",
"channel",
"recipient",
"status",
"payload",
"error",
"sent_at",
"metadata",
"created_at",
"updated_at",
}
_NOTIFICATION_INDEXES = {
"ix_scheduling_notifications_channel",
"ix_scheduling_notifications_event_kind",
"ix_scheduling_notifications_participant_id",
"ix_scheduling_notifications_recipient",
"ix_scheduling_notifications_request_id",
"ix_scheduling_notifications_request_status",
"ix_scheduling_notifications_status",
"ix_scheduling_notifications_tenant_id",
"ix_scheduling_notifications_tenant_status",
}
def _adopt_existing_calendar_notifications() -> bool:
"""Adopt only the complete calendar/notification extension."""
inspector = sa.inspect(op.get_bind())
tables = set(inspector.get_table_names())
if "scheduling_candidate_slots" not in tables:
raise RuntimeError(
"Cannot apply the Scheduling calendar migration because scheduling_candidate_slots is missing"
)
slot_columns = {item["name"] for item in inspector.get_columns("scheduling_candidate_slots")}
present_slot_columns = _CALENDAR_SLOT_COLUMNS.intersection(slot_columns)
notification_exists = "scheduling_notifications" in tables
if not present_slot_columns and not notification_exists:
return False
problems: list[str] = []
missing_slot_columns = _CALENDAR_SLOT_COLUMNS - slot_columns
if missing_slot_columns:
problems.append(
"scheduling_candidate_slots missing columns: "
f"{', '.join(sorted(missing_slot_columns))}"
)
slot_indexes = {item["name"] for item in inspector.get_indexes("scheduling_candidate_slots")}
missing_slot_indexes = _CALENDAR_SLOT_INDEXES - slot_indexes
if missing_slot_indexes:
problems.append(
"scheduling_candidate_slots missing indexes: "
f"{', '.join(sorted(missing_slot_indexes))}"
)
if not notification_exists:
problems.append("missing table: scheduling_notifications")
else:
notification_columns = {
item["name"] for item in inspector.get_columns("scheduling_notifications")
}
missing_notification_columns = _NOTIFICATION_COLUMNS - notification_columns
if missing_notification_columns:
problems.append(
"scheduling_notifications missing columns: "
f"{', '.join(sorted(missing_notification_columns))}"
)
notification_indexes = {
item["name"] for item in inspector.get_indexes("scheduling_notifications")
}
missing_notification_indexes = _NOTIFICATION_INDEXES - notification_indexes
if missing_notification_indexes:
problems.append(
"scheduling_notifications missing indexes: "
f"{', '.join(sorted(missing_notification_indexes))}"
)
primary_key = tuple(
inspector.get_pk_constraint("scheduling_notifications").get("constrained_columns") or ()
)
if primary_key != ("id",):
problems.append(f"scheduling_notifications has unexpected primary key: {primary_key!r}")
request_foreign_key_exists = any(
tuple(item.get("constrained_columns") or ()) == ("request_id",)
and item.get("referred_table") == "scheduling_requests"
and tuple(item.get("referred_columns") or ()) == ("id",)
and str((item.get("options") or {}).get("ondelete", "")).upper() == "CASCADE"
for item in inspector.get_foreign_keys("scheduling_notifications")
)
if not request_foreign_key_exists:
problems.append("scheduling_notifications is missing its cascading request_id foreign key")
if problems:
detail = "; ".join(problems)
raise RuntimeError(
"Cannot adopt the existing Scheduling v0.1.8 calendar/notification schema because it is "
f"incomplete or ambiguous: {detail}"
)
return True
def upgrade() -> None:
if _adopt_existing_calendar_notifications():
return
op.add_column("scheduling_candidate_slots", sa.Column("freebusy_checked_at", sa.DateTime(timezone=True), nullable=True))
op.add_column("scheduling_candidate_slots", sa.Column("freebusy_status", sa.String(length=40), nullable=True))
op.add_column("scheduling_candidate_slots", sa.Column("freebusy_conflicts", sa.JSON(), nullable=False, server_default="[]"))
op.add_column("scheduling_candidate_slots", sa.Column("tentative_hold_event_id", sa.String(length=36), nullable=True))
op.create_index(op.f("ix_scheduling_candidate_slots_freebusy_status"), "scheduling_candidate_slots", ["freebusy_status"], unique=False)
op.create_index(
op.f("ix_scheduling_candidate_slots_tentative_hold_event_id"),
"scheduling_candidate_slots",
["tentative_hold_event_id"],
unique=False,
)
op.create_table(
"scheduling_notifications",
sa.Column("id", sa.String(length=36), nullable=False),
sa.Column("tenant_id", sa.String(length=36), nullable=False),
sa.Column("request_id", sa.String(length=36), nullable=False),
sa.Column("participant_id", sa.String(length=36), nullable=True),
sa.Column("event_kind", sa.String(length=40), nullable=False),
sa.Column("channel", sa.String(length=40), nullable=False),
sa.Column("recipient", sa.String(length=500), nullable=True),
sa.Column("status", sa.String(length=40), nullable=False),
sa.Column("payload", sa.JSON(), nullable=False),
sa.Column("error", sa.Text(), nullable=True),
sa.Column("sent_at", sa.DateTime(timezone=True), nullable=True),
sa.Column("metadata", sa.JSON(), nullable=True),
sa.Column("created_at", sa.DateTime(timezone=True), nullable=False),
sa.Column("updated_at", sa.DateTime(timezone=True), nullable=False),
sa.ForeignKeyConstraint(
["request_id"],
["scheduling_requests.id"],
name=op.f("fk_scheduling_notifications_request_id_scheduling_requests"),
ondelete="CASCADE",
),
sa.PrimaryKeyConstraint("id", name=op.f("pk_scheduling_notifications")),
)
op.create_index(op.f("ix_scheduling_notifications_channel"), "scheduling_notifications", ["channel"], unique=False)
op.create_index(op.f("ix_scheduling_notifications_event_kind"), "scheduling_notifications", ["event_kind"], unique=False)
op.create_index(op.f("ix_scheduling_notifications_participant_id"), "scheduling_notifications", ["participant_id"], unique=False)
op.create_index(op.f("ix_scheduling_notifications_recipient"), "scheduling_notifications", ["recipient"], unique=False)
op.create_index(op.f("ix_scheduling_notifications_request_id"), "scheduling_notifications", ["request_id"], unique=False)
op.create_index("ix_scheduling_notifications_request_status", "scheduling_notifications", ["request_id", "status"], unique=False)
op.create_index(op.f("ix_scheduling_notifications_status"), "scheduling_notifications", ["status"], unique=False)
op.create_index(op.f("ix_scheduling_notifications_tenant_id"), "scheduling_notifications", ["tenant_id"], unique=False)
op.create_index("ix_scheduling_notifications_tenant_status", "scheduling_notifications", ["tenant_id", "status"], unique=False)
def downgrade() -> None:
op.drop_table("scheduling_notifications")
op.drop_index(op.f("ix_scheduling_candidate_slots_tentative_hold_event_id"), table_name="scheduling_candidate_slots")
op.drop_index(op.f("ix_scheduling_candidate_slots_freebusy_status"), table_name="scheduling_candidate_slots")
op.drop_column("scheduling_candidate_slots", "tentative_hold_event_id")
op.drop_column("scheduling_candidate_slots", "freebusy_conflicts")
op.drop_column("scheduling_candidate_slots", "freebusy_status")
op.drop_column("scheduling_candidate_slots", "freebusy_checked_at")

View File

@@ -0,0 +1,43 @@
"""v0.1.9 scheduling participant visibility
Revision ID: 9c2f4a7d1e6b
Revises: 4d5e6f7a8b9c
Create Date: 2026-07-20 00:00:00.000000
"""
from __future__ import annotations
from alembic import op
import sqlalchemy as sa
revision = "9c2f4a7d1e6b"
down_revision = "4d5e6f7a8b9c"
branch_labels = None
depends_on = None
def upgrade() -> None:
inspector = sa.inspect(op.get_bind())
columns = {item["name"]: item for item in inspector.get_columns("scheduling_requests")}
existing = columns.get("participant_visibility")
if existing is not None:
column_type = existing["type"]
if existing.get("nullable") or not isinstance(column_type, sa.String) or column_type.length != 32:
raise RuntimeError(
"Cannot adopt scheduling_requests.participant_visibility because its schema is unexpected"
)
return
op.add_column(
"scheduling_requests",
sa.Column(
"participant_visibility",
sa.String(length=32),
nullable=False,
server_default="aggregates_only",
),
)
def downgrade() -> None:
op.drop_column("scheduling_requests", "participant_visibility")

View File

@@ -0,0 +1 @@
from __future__ import annotations

View File

@@ -0,0 +1,569 @@
from __future__ import annotations
import dataclasses
from typing import Any
from fastapi import APIRouter, Depends, HTTPException, Query, status
from sqlalchemy.orm import Session
from govoplan_core.auth import ApiPrincipal, get_api_principal, has_scope
from govoplan_core.core.calendar import CALENDAR_AVAILABILITY_READ_SCOPE, CALENDAR_EVENT_WRITE_SCOPE
from govoplan_core.db.session import get_session
from govoplan_scheduling.backend.manifest import ADMIN_SCOPE, READ_SCOPE, RESPOND_SCOPE, WRITE_SCOPE
from govoplan_scheduling.backend.schemas import (
SchedulingAddressLookupCandidate,
SchedulingAddressLookupResponse,
SchedulingAvailabilityResponse,
SchedulingAvailabilityResponseRequest,
SchedulingCalendarActionResponse,
SchedulingCandidateSlotUpdateRequest,
SchedulingDecisionRequest,
SchedulingNotificationCreateRequest,
SchedulingNotificationListResponse,
SchedulingNotificationResponse,
SchedulingRequestCreateRequest,
SchedulingRequestListResponse,
SchedulingRequestResponse,
SchedulingRequestUpdateRequest,
SchedulingPollSummaryResponse,
SchedulingStatusResponse,
SchedulingSummaryResponse,
)
from govoplan_scheduling.backend.runtime import get_registry
from govoplan_scheduling.backend.service import (
SchedulingConflictError,
SchedulingError,
SchedulingPermissionError,
cancel_scheduling_request,
close_scheduling_request,
create_final_calendar_event,
create_scheduling_notification_jobs,
create_scheduling_request,
create_tentative_calendar_holds,
decide_scheduling_request,
evaluate_calendar_freebusy,
get_scheduling_availability_response,
get_visible_scheduling_request,
list_visible_scheduling_notifications,
list_visible_scheduling_requests,
open_scheduling_request,
refresh_participant_response_state,
require_visible_scheduling_results,
scheduling_notification_response,
scheduling_request_response,
scheduling_request_summary,
submit_scheduling_availability,
update_scheduling_candidate_slot,
update_scheduling_request,
)
router = APIRouter(prefix="/scheduling", tags=["scheduling"])
CAPABILITY_ADDRESSES_LOOKUP = "addresses.lookup"
def _capability_payload(value: object) -> dict[str, Any]:
if dataclasses.is_dataclass(value):
return dataclasses.asdict(value)
if isinstance(value, dict):
return dict(value)
payload: dict[str, Any] = {}
for key in (
"contact_id",
"address_book_id",
"display_name",
"email",
"email_label",
"organization",
"role_title",
"tags",
"source_kind",
"source_ref",
"source_revision",
"provenance",
):
if hasattr(value, key):
payload[key] = getattr(value, key)
return payload
def _registry_capability(name: str) -> object | None:
registry = get_registry()
if registry is None or not hasattr(registry, "has_capability") or not registry.has_capability(name):
return None
return registry.capability(name)
def _require_scope(principal: ApiPrincipal, scope: str) -> None:
if not has_scope(principal, scope):
raise HTTPException(status_code=status.HTTP_403_FORBIDDEN, detail=f"Missing scope: {scope}")
def _principal_actor_ids(principal: ApiPrincipal) -> tuple[str, ...]:
candidates = (
principal.account_id,
principal.membership_id,
getattr(principal.user, "id", None),
principal.identity_id,
principal.principal.service_account_id,
principal.email,
)
return tuple(dict.fromkeys(str(value) for value in candidates if value))
def _can_manage_scheduling(principal: ApiPrincipal) -> bool:
return has_scope(principal, WRITE_SCOPE) or has_scope(principal, ADMIN_SCOPE)
def _scheduling_http_error(exc: SchedulingError) -> HTTPException:
if isinstance(exc, SchedulingConflictError):
return HTTPException(status_code=status.HTTP_409_CONFLICT, detail=str(exc))
if isinstance(exc, SchedulingPermissionError):
return HTTPException(status_code=status.HTTP_403_FORBIDDEN, detail=str(exc))
if str(exc) == "Scheduling request not found":
return HTTPException(status_code=status.HTTP_404_NOT_FOUND, detail=str(exc))
if str(exc) == "Scheduling results are not visible":
return HTTPException(status_code=status.HTTP_403_FORBIDDEN, detail=str(exc))
return HTTPException(status_code=status.HTTP_400_BAD_REQUEST, detail=str(exc))
def _request_response(
request,
*,
principal: ApiPrincipal,
invitation_tokens: dict[str, str] | None = None,
) -> SchedulingRequestResponse:
return SchedulingRequestResponse.model_validate(
scheduling_request_response(
request,
invitation_tokens=invitation_tokens,
actor_ids=_principal_actor_ids(principal),
actor_user_id=principal.account_id,
can_manage=_can_manage_scheduling(principal),
)
)
@router.get("/address-lookup", response_model=SchedulingAddressLookupResponse)
def api_lookup_scheduling_addresses(
query: str = Query(min_length=1),
limit: int = Query(default=25, ge=1, le=100),
session: Session = Depends(get_session),
principal: ApiPrincipal = Depends(get_api_principal),
) -> SchedulingAddressLookupResponse:
_require_scope(principal, WRITE_SCOPE)
capability = _registry_capability(CAPABILITY_ADDRESSES_LOOKUP)
if capability is None or not hasattr(capability, "lookup"):
return SchedulingAddressLookupResponse(available=False, candidates=[])
candidates = getattr(capability, "lookup")(session, principal, query=query, limit=limit)
return SchedulingAddressLookupResponse(
available=True,
candidates=[SchedulingAddressLookupCandidate.model_validate(_capability_payload(candidate)) for candidate in candidates],
)
@router.get("/requests", response_model=SchedulingRequestListResponse)
def api_list_scheduling_requests(
status_filter: str | None = Query(default=None, alias="status"),
session: Session = Depends(get_session),
principal: ApiPrincipal = Depends(get_api_principal),
) -> SchedulingRequestListResponse:
_require_scope(principal, READ_SCOPE)
requests = list_visible_scheduling_requests(
session,
tenant_id=principal.tenant_id,
actor_ids=_principal_actor_ids(principal),
can_manage=_can_manage_scheduling(principal),
status=status_filter,
)
actor_ids = _principal_actor_ids(principal)
for request in requests:
refresh_participant_response_state(
session,
request=request,
actor_ids=actor_ids,
)
response = SchedulingRequestListResponse(
requests=[_request_response(request, principal=principal) for request in requests]
)
# Poll responses are authoritative, while Scheduling keeps a durable
# participant projection used by its task-oriented list.
session.commit()
return response
@router.post("/requests", response_model=SchedulingRequestResponse, status_code=status.HTTP_201_CREATED)
def api_create_scheduling_request(
payload: SchedulingRequestCreateRequest,
session: Session = Depends(get_session),
principal: ApiPrincipal = Depends(get_api_principal),
) -> SchedulingRequestResponse:
_require_scope(principal, WRITE_SCOPE)
try:
request, invitation_tokens = create_scheduling_request(
session,
tenant_id=principal.tenant_id,
user_id=principal.account_id,
payload=payload,
)
except SchedulingError as exc:
raise _scheduling_http_error(exc) from exc
response = _request_response(request, principal=principal, invitation_tokens=invitation_tokens)
session.commit()
return response
@router.post("/requests/{request_id}/responses", response_model=SchedulingStatusResponse)
def api_submit_scheduling_availability(
request_id: str,
payload: SchedulingAvailabilityResponseRequest,
session: Session = Depends(get_session),
principal: ApiPrincipal = Depends(get_api_principal),
) -> SchedulingStatusResponse:
_require_scope(principal, RESPOND_SCOPE)
try:
request = submit_scheduling_availability(
session,
tenant_id=principal.tenant_id,
request_id=request_id,
actor_ids=_principal_actor_ids(principal),
respondent_id=principal.account_id,
respondent_label=principal.display_name or principal.email,
payload=payload,
)
except SchedulingError as exc:
raise _scheduling_http_error(exc) from exc
response = SchedulingStatusResponse(
request=_request_response(request, principal=principal)
)
session.commit()
return response
@router.get("/requests/{request_id}/responses/me", response_model=SchedulingAvailabilityResponse)
def api_get_my_scheduling_availability(
request_id: str,
session: Session = Depends(get_session),
principal: ApiPrincipal = Depends(get_api_principal),
) -> SchedulingAvailabilityResponse:
_require_scope(principal, RESPOND_SCOPE)
try:
response = get_scheduling_availability_response(
session,
tenant_id=principal.tenant_id,
request_id=request_id,
actor_ids=_principal_actor_ids(principal),
respondent_id=principal.account_id,
)
except SchedulingError as exc:
raise _scheduling_http_error(exc) from exc
return SchedulingAvailabilityResponse.model_validate(response)
@router.get("/requests/{request_id}", response_model=SchedulingRequestResponse)
def api_get_scheduling_request(
request_id: str,
session: Session = Depends(get_session),
principal: ApiPrincipal = Depends(get_api_principal),
) -> SchedulingRequestResponse:
_require_scope(principal, READ_SCOPE)
try:
request = get_visible_scheduling_request(
session,
tenant_id=principal.tenant_id,
request_id=request_id,
actor_ids=_principal_actor_ids(principal),
can_manage=_can_manage_scheduling(principal),
)
refresh_participant_response_state(
session,
request=request,
actor_ids=_principal_actor_ids(principal),
)
except SchedulingError as exc:
raise _scheduling_http_error(exc) from exc
response = _request_response(request, principal=principal)
session.commit()
return response
@router.patch("/requests/{request_id}", response_model=SchedulingRequestResponse)
def api_update_scheduling_request(
request_id: str,
payload: SchedulingRequestUpdateRequest,
session: Session = Depends(get_session),
principal: ApiPrincipal = Depends(get_api_principal),
) -> SchedulingRequestResponse:
_require_scope(principal, WRITE_SCOPE)
try:
request = update_scheduling_request(
session,
tenant_id=principal.tenant_id,
request_id=request_id,
payload=payload,
)
except SchedulingError as exc:
raise _scheduling_http_error(exc) from exc
response = _request_response(request, principal=principal)
session.commit()
return response
@router.patch("/requests/{request_id}/slots/{slot_id}", response_model=SchedulingRequestResponse)
def api_update_scheduling_candidate_slot(
request_id: str,
slot_id: str,
payload: SchedulingCandidateSlotUpdateRequest,
session: Session = Depends(get_session),
principal: ApiPrincipal = Depends(get_api_principal),
) -> SchedulingRequestResponse:
_require_scope(principal, WRITE_SCOPE)
try:
request = update_scheduling_candidate_slot(
session,
tenant_id=principal.tenant_id,
request_id=request_id,
slot_id=slot_id,
payload=payload,
)
except SchedulingError as exc:
raise _scheduling_http_error(exc) from exc
response = _request_response(request, principal=principal)
session.commit()
return response
@router.post("/requests/{request_id}/open", response_model=SchedulingStatusResponse)
def api_open_scheduling_request(
request_id: str,
session: Session = Depends(get_session),
principal: ApiPrincipal = Depends(get_api_principal),
) -> SchedulingStatusResponse:
_require_scope(principal, WRITE_SCOPE)
try:
request = open_scheduling_request(session, tenant_id=principal.tenant_id, request_id=request_id)
except SchedulingError as exc:
raise _scheduling_http_error(exc) from exc
response = SchedulingStatusResponse(request=_request_response(request, principal=principal))
session.commit()
return response
@router.post("/requests/{request_id}/close", response_model=SchedulingStatusResponse)
def api_close_scheduling_request(
request_id: str,
session: Session = Depends(get_session),
principal: ApiPrincipal = Depends(get_api_principal),
) -> SchedulingStatusResponse:
_require_scope(principal, WRITE_SCOPE)
try:
request = close_scheduling_request(session, tenant_id=principal.tenant_id, request_id=request_id)
except SchedulingError as exc:
raise _scheduling_http_error(exc) from exc
response = SchedulingStatusResponse(request=_request_response(request, principal=principal))
session.commit()
return response
@router.post("/requests/{request_id}/decide", response_model=SchedulingStatusResponse)
def api_decide_scheduling_request(
request_id: str,
payload: SchedulingDecisionRequest,
session: Session = Depends(get_session),
principal: ApiPrincipal = Depends(get_api_principal),
) -> SchedulingStatusResponse:
_require_scope(principal, WRITE_SCOPE)
try:
request = decide_scheduling_request(
session,
tenant_id=principal.tenant_id,
request_id=request_id,
payload=payload,
user_id=principal.account_id,
allow_calendar_handoff=has_scope(
principal,
CALENDAR_EVENT_WRITE_SCOPE,
),
)
except SchedulingError as exc:
raise _scheduling_http_error(exc) from exc
response = SchedulingStatusResponse(request=_request_response(request, principal=principal))
session.commit()
return response
@router.post("/requests/{request_id}/calendar/freebusy", response_model=SchedulingCalendarActionResponse)
def api_evaluate_calendar_freebusy(
request_id: str,
session: Session = Depends(get_session),
principal: ApiPrincipal = Depends(get_api_principal),
) -> SchedulingCalendarActionResponse:
_require_scope(principal, WRITE_SCOPE)
_require_scope(principal, CALENDAR_AVAILABILITY_READ_SCOPE)
try:
request, warnings = evaluate_calendar_freebusy(session, tenant_id=principal.tenant_id, request_id=request_id)
except SchedulingError as exc:
raise _scheduling_http_error(exc) from exc
response = SchedulingCalendarActionResponse(
request=_request_response(request, principal=principal),
updated_slot_ids=[slot.id for slot in request.slots if slot.freebusy_checked_at is not None],
warnings=warnings,
)
session.commit()
return response
@router.post("/requests/{request_id}/calendar/holds", response_model=SchedulingCalendarActionResponse)
def api_create_tentative_calendar_holds(
request_id: str,
session: Session = Depends(get_session),
principal: ApiPrincipal = Depends(get_api_principal),
) -> SchedulingCalendarActionResponse:
_require_scope(principal, WRITE_SCOPE)
_require_scope(principal, CALENDAR_EVENT_WRITE_SCOPE)
try:
request, created_event_ids, warnings = create_tentative_calendar_holds(
session,
tenant_id=principal.tenant_id,
user_id=principal.account_id,
request_id=request_id,
)
except SchedulingError as exc:
raise _scheduling_http_error(exc) from exc
response = SchedulingCalendarActionResponse(
request=_request_response(request, principal=principal),
created_event_ids=created_event_ids,
updated_slot_ids=[slot.id for slot in request.slots if slot.tentative_hold_event_id in created_event_ids],
warnings=warnings,
)
session.commit()
return response
@router.post("/requests/{request_id}/calendar/event", response_model=SchedulingCalendarActionResponse)
def api_create_final_calendar_event(
request_id: str,
session: Session = Depends(get_session),
principal: ApiPrincipal = Depends(get_api_principal),
) -> SchedulingCalendarActionResponse:
_require_scope(principal, WRITE_SCOPE)
_require_scope(principal, CALENDAR_EVENT_WRITE_SCOPE)
try:
request, event_id, warnings = create_final_calendar_event(
session,
tenant_id=principal.tenant_id,
user_id=principal.account_id,
request_id=request_id,
)
except SchedulingError as exc:
raise _scheduling_http_error(exc) from exc
response = SchedulingCalendarActionResponse(
request=_request_response(request, principal=principal),
created_event_ids=[event_id] if event_id else [],
warnings=warnings,
)
session.commit()
return response
@router.post("/requests/{request_id}/cancel", response_model=SchedulingStatusResponse)
def api_cancel_scheduling_request(
request_id: str,
session: Session = Depends(get_session),
principal: ApiPrincipal = Depends(get_api_principal),
) -> SchedulingStatusResponse:
_require_scope(principal, WRITE_SCOPE)
try:
request = cancel_scheduling_request(session, tenant_id=principal.tenant_id, request_id=request_id)
except SchedulingError as exc:
raise _scheduling_http_error(exc) from exc
response = SchedulingStatusResponse(request=_request_response(request, principal=principal))
session.commit()
return response
@router.get("/requests/{request_id}/summary", response_model=SchedulingSummaryResponse)
def api_scheduling_summary(
request_id: str,
session: Session = Depends(get_session),
principal: ApiPrincipal = Depends(get_api_principal),
) -> SchedulingSummaryResponse:
_require_scope(principal, READ_SCOPE)
try:
request = get_visible_scheduling_request(
session,
tenant_id=principal.tenant_id,
request_id=request_id,
actor_ids=_principal_actor_ids(principal),
can_manage=_can_manage_scheduling(principal),
)
require_visible_scheduling_results(
session,
request=request,
actor_ids=_principal_actor_ids(principal),
can_manage=_can_manage_scheduling(principal),
)
summary = scheduling_request_summary(session, tenant_id=principal.tenant_id, request_id=request_id)
except SchedulingError as exc:
raise _scheduling_http_error(exc) from exc
response = SchedulingSummaryResponse(
request=_request_response(request, principal=principal),
poll_summary=SchedulingPollSummaryResponse.model_validate(summary),
)
# Refreshing the summary synchronizes participant response state and can
# enqueue response notifications, so persist that work before teardown.
session.commit()
return response
@router.get("/notifications", response_model=SchedulingNotificationListResponse)
def api_list_scheduling_notifications(
request_id: str | None = None,
status_filter: str | None = Query(default=None, alias="status"),
session: Session = Depends(get_session),
principal: ApiPrincipal = Depends(get_api_principal),
) -> SchedulingNotificationListResponse:
_require_scope(principal, READ_SCOPE)
notifications = list_visible_scheduling_notifications(
session,
tenant_id=principal.tenant_id,
actor_ids=_principal_actor_ids(principal),
can_manage=_can_manage_scheduling(principal),
request_id=request_id,
status=status_filter,
)
return SchedulingNotificationListResponse(
notifications=[
SchedulingNotificationResponse.model_validate(scheduling_notification_response(notification))
for notification in notifications
]
)
@router.post("/requests/{request_id}/notifications", response_model=SchedulingNotificationListResponse)
def api_create_scheduling_notifications(
request_id: str,
payload: SchedulingNotificationCreateRequest,
session: Session = Depends(get_session),
principal: ApiPrincipal = Depends(get_api_principal),
) -> SchedulingNotificationListResponse:
_require_scope(principal, WRITE_SCOPE)
try:
notifications = create_scheduling_notification_jobs(
session,
tenant_id=principal.tenant_id,
request_id=request_id,
event_kind=payload.event_kind,
channel=payload.channel,
metadata=payload.metadata,
)
except SchedulingError as exc:
raise _scheduling_http_error(exc) from exc
response = SchedulingNotificationListResponse(
notifications=[
SchedulingNotificationResponse.model_validate(scheduling_notification_response(notification))
for notification in notifications
]
)
session.commit()
return response

View File

@@ -0,0 +1,20 @@
from __future__ import annotations
_runtime_registry: object | None = None
_runtime_settings: object | None = None
def configure_runtime(*, registry: object | None = None, settings: object | None = None) -> None:
global _runtime_registry, _runtime_settings
if registry is not None:
_runtime_registry = registry
if settings is not None:
_runtime_settings = settings
def get_registry() -> object | None:
return _runtime_registry
def get_settings() -> object | None:
return _runtime_settings

View File

@@ -0,0 +1,339 @@
from __future__ import annotations
from datetime import datetime
from typing import Any, Literal
from zoneinfo import ZoneInfo, ZoneInfoNotFoundError
from pydantic import AwareDatetime, BaseModel, ConfigDict, Field, field_validator, model_validator
SchedulingStatus = Literal["draft", "collecting", "closed", "decided", "handed_off", "cancelled", "archived"]
SchedulingParticipantType = Literal["internal", "external", "resource"]
SchedulingParticipantStatus = Literal["draft", "invited", "responded", "declined", "removed"]
SchedulingResultVisibility = Literal["organizer", "after_response", "after_close", "public"]
SchedulingAvailabilityValue = Literal["available", "maybe", "unavailable"]
SchedulingParticipantVisibility = Literal["aggregates_only", "names_and_statuses"]
def _known_timezone(value: str | None) -> str | None:
if value is None:
return None
try:
ZoneInfo(value)
except ZoneInfoNotFoundError as exc:
raise ValueError("timezone must be a valid IANA timezone") from exc
return value
class SchedulingCalendarPreferences(BaseModel):
model_config = ConfigDict(extra="forbid")
enabled: bool = False
calendar_id: str | None = Field(default=None, max_length=36)
freebusy_enabled: bool = False
tentative_holds_enabled: bool = False
create_event_on_decision: bool = False
class SchedulingCandidateSlotInput(BaseModel):
model_config = ConfigDict(extra="forbid")
label: str | None = Field(default=None, max_length=500)
description: str | None = None
start_at: AwareDatetime
end_at: AwareDatetime
timezone: str | None = Field(default=None, max_length=100)
location: str | None = Field(default=None, max_length=500)
metadata: dict[str, Any] = Field(default_factory=dict)
_validate_timezone = field_validator("timezone")(_known_timezone)
@model_validator(mode="after")
def validate_range(self) -> "SchedulingCandidateSlotInput":
if self.end_at <= self.start_at:
raise ValueError("end_at must be after start_at")
return self
class SchedulingCandidateSlotUpdateRequest(BaseModel):
"""Partial update of one candidate slot.
A semantic option change invalidates existing answers for this slot in the
backing Poll. Exact repeats are safe no-ops.
"""
model_config = ConfigDict(extra="forbid")
label: str | None = Field(default=None, min_length=1, max_length=500)
description: str | None = None
start_at: AwareDatetime | None = None
end_at: AwareDatetime | None = None
timezone: str | None = Field(default=None, min_length=1, max_length=100)
location: str | None = Field(default=None, max_length=500)
metadata: dict[str, Any] | None = None
_validate_timezone = field_validator("timezone")(_known_timezone)
@model_validator(mode="after")
def validate_range(self) -> "SchedulingCandidateSlotUpdateRequest":
if self.start_at is not None and self.end_at is not None and self.end_at <= self.start_at:
raise ValueError("end_at must be after start_at")
return self
class SchedulingParticipantInput(BaseModel):
model_config = ConfigDict(extra="forbid")
respondent_id: str | None = Field(default=None, max_length=255)
display_name: str | None = Field(default=None, max_length=500)
email: str | None = Field(default=None, max_length=320)
participant_type: SchedulingParticipantType = "external"
required: bool = True
metadata: dict[str, Any] = Field(default_factory=dict)
class SchedulingRequestCreateRequest(BaseModel):
model_config = ConfigDict(extra="forbid")
title: str = Field(min_length=1, max_length=500)
description: str | None = None
location: str | None = Field(default=None, max_length=500)
timezone: str = Field(default="UTC", max_length=100)
status: Literal["draft", "collecting"] = "draft"
deadline_at: datetime | None = None
allow_external_participants: bool = True
allow_participant_updates: bool = True
result_visibility: SchedulingResultVisibility = "after_close"
participant_visibility: SchedulingParticipantVisibility = "aggregates_only"
calendar: SchedulingCalendarPreferences = Field(default_factory=SchedulingCalendarPreferences)
slots: list[SchedulingCandidateSlotInput] = Field(default_factory=list, min_length=1)
participants: list[SchedulingParticipantInput] = Field(default_factory=list)
create_participant_invitations: bool = True
metadata: dict[str, Any] = Field(default_factory=dict)
_validate_timezone = field_validator("timezone")(_known_timezone)
class SchedulingRequestUpdateRequest(BaseModel):
model_config = ConfigDict(extra="forbid")
title: str | None = Field(default=None, min_length=1, max_length=500)
description: str | None = None
location: str | None = Field(default=None, max_length=500)
deadline_at: datetime | None = None
allow_external_participants: bool | None = None
allow_participant_updates: bool | None = None
result_visibility: SchedulingResultVisibility | None = None
participant_visibility: SchedulingParticipantVisibility | None = None
calendar: SchedulingCalendarPreferences | None = None
metadata: dict[str, Any] | None = None
class SchedulingCandidateSlotResponse(BaseModel):
id: str
poll_option_id: str | None = None
label: str
description: str | None = None
start_at: datetime
end_at: datetime
timezone: str
location: str | None = None
position: int
revision: str
freebusy_checked_at: datetime | None = None
freebusy_status: str | None = None
freebusy_conflicts: list[dict[str, Any]] = Field(default_factory=list)
tentative_hold_event_id: str | None = None
metadata: dict[str, Any] = Field(default_factory=dict)
class SchedulingParticipantResponse(BaseModel):
id: str
respondent_id: str | None = None
display_name: str | None = None
email: str | None = None
participant_type: str
required: bool
status: str
poll_invitation_id: str | None = None
invitation_token: str | None = None
last_invited_at: datetime | None = None
responded_at: datetime | None = None
metadata: dict[str, Any] = Field(default_factory=dict)
class SchedulingParticipantAggregateResponse(BaseModel):
total: int = 0
status_counts: dict[str, int] = Field(default_factory=dict)
class SchedulingParticipantVisibilityDecisionResponse(BaseModel):
requested_visibility: SchedulingParticipantVisibility
effective_visibility: SchedulingParticipantVisibility
policy_applied: bool = False
reason: str | None = None
source_path: list[dict[str, Any]] = Field(default_factory=list)
details: dict[str, Any] = Field(default_factory=dict)
class SchedulingRequestResponse(BaseModel):
id: str
tenant_id: str
title: str
description: str | None = None
location: str | None = None
timezone: str
status: str
poll_id: str | None = None
selected_slot_id: str | None = None
organizer_user_id: str | None = None
deadline_at: datetime | None = None
allow_external_participants: bool
allow_participant_updates: bool
result_visibility: str
participant_visibility: SchedulingParticipantVisibility
effective_participant_visibility: SchedulingParticipantVisibility
participant_aggregate: SchedulingParticipantAggregateResponse
participant_visibility_decision: SchedulingParticipantVisibilityDecisionResponse
calendar_integration_enabled: bool
calendar_id: str | None = None
calendar_freebusy_enabled: bool
calendar_hold_enabled: bool
create_calendar_event_on_decision: bool
calendar_event_id: str | None = None
handed_off_at: datetime | None = None
cancelled_at: datetime | None = None
created_at: datetime
updated_at: datetime
metadata: dict[str, Any] = Field(default_factory=dict)
slots: list[SchedulingCandidateSlotResponse] = Field(default_factory=list)
participants: list[SchedulingParticipantResponse] = Field(default_factory=list)
class SchedulingRequestListResponse(BaseModel):
requests: list[SchedulingRequestResponse] = Field(default_factory=list)
class SchedulingStatusResponse(BaseModel):
request: SchedulingRequestResponse
class SchedulingDecisionRequest(BaseModel):
model_config = ConfigDict(extra="forbid")
slot_id: str | None = None
poll_option_id: str | None = None
handoff_to_calendar: bool | None = None
class SchedulingAvailabilityAnswerInput(BaseModel):
model_config = ConfigDict(extra="forbid")
slot_id: str
value: SchedulingAvailabilityValue
option_revision: str = Field(min_length=64, max_length=64, pattern=r"^[0-9a-f]{64}$")
class SchedulingAvailabilityResponseRequest(BaseModel):
model_config = ConfigDict(extra="forbid")
answers: list[SchedulingAvailabilityAnswerInput] = Field(min_length=1)
@model_validator(mode="after")
def validate_unique_slots(self) -> "SchedulingAvailabilityResponseRequest":
slot_ids = [answer.slot_id for answer in self.answers]
if len(slot_ids) != len(set(slot_ids)):
raise ValueError("Each scheduling slot can be answered only once")
return self
class SchedulingAvailabilityAnswerResponse(BaseModel):
slot_id: str
value: SchedulingAvailabilityValue
class SchedulingAvailabilityResponse(BaseModel):
request_id: str
participant_id: str
has_response: bool = False
submitted_at: datetime | None = None
answers: list[SchedulingAvailabilityAnswerResponse] = Field(default_factory=list)
class SchedulingPollOptionResultResponse(BaseModel):
option_id: str
option_key: str
label: str
count: int = 0
score: int = 0
values: dict[str, int] = Field(default_factory=dict)
ranks: dict[int, int] = Field(default_factory=dict)
class SchedulingPollSummaryResponse(BaseModel):
poll_id: str
kind: str
status: str
response_count: int
option_results: list[SchedulingPollOptionResultResponse] = Field(default_factory=list)
leading_option_ids: list[str] = Field(default_factory=list)
class SchedulingSummaryResponse(BaseModel):
request: SchedulingRequestResponse
poll_summary: SchedulingPollSummaryResponse
class SchedulingCalendarActionResponse(BaseModel):
request: SchedulingRequestResponse
created_event_ids: list[str] = Field(default_factory=list)
updated_slot_ids: list[str] = Field(default_factory=list)
warnings: list[str] = Field(default_factory=list)
class SchedulingNotificationResponse(BaseModel):
id: str
request_id: str
participant_id: str | None = None
event_kind: str
channel: str
recipient: str | None = None
status: str
payload: dict[str, Any] = Field(default_factory=dict)
error: str | None = None
sent_at: datetime | None = None
created_at: datetime
updated_at: datetime
metadata: dict[str, Any] = Field(default_factory=dict)
class SchedulingNotificationListResponse(BaseModel):
notifications: list[SchedulingNotificationResponse] = Field(default_factory=list)
class SchedulingNotificationCreateRequest(BaseModel):
model_config = ConfigDict(extra="forbid")
event_kind: Literal["invitation", "reminder", "decision", "cancellation"]
channel: str = Field(default="mail", max_length=40)
metadata: dict[str, Any] = Field(default_factory=dict)
class SchedulingAddressLookupCandidate(BaseModel):
contact_id: str
address_book_id: str
display_name: str
email: str | None = None
email_label: str | None = None
organization: str | None = None
role_title: str | None = None
tags: list[str] = Field(default_factory=list)
source_kind: str = "local"
source_ref: str | None = None
source_revision: str | None = None
provenance: dict[str, Any] = Field(default_factory=dict)
class SchedulingAddressLookupResponse(BaseModel):
available: bool = False
candidates: list[SchedulingAddressLookupCandidate] = Field(default_factory=list)

File diff suppressed because it is too large Load Diff

View File

@@ -0,0 +1 @@

43
tests/test_manifest.py Normal file
View File

@@ -0,0 +1,43 @@
from __future__ import annotations
import unittest
from govoplan_core.core.modules import ModuleManifest
from govoplan_scheduling.backend.manifest import get_manifest
class SchedulingManifestTests(unittest.TestCase):
def test_manifest_contract(self) -> None:
manifest = get_manifest()
self.assertIsInstance(manifest, ModuleManifest)
self.assertEqual(manifest.id, "scheduling")
self.assertIn("poll", manifest.dependencies)
self.assertNotIn("access", manifest.dependencies)
self.assertIn("access", manifest.optional_dependencies)
self.assertIn("addresses", manifest.optional_dependencies)
self.assertIn("policy", manifest.optional_dependencies)
self.assertEqual(("poll.scheduling",), manifest.required_capabilities)
self.assertIn("auth.principalResolver", manifest.optional_capabilities)
self.assertIn("poll.scheduling", manifest.required_capabilities)
self.assertIn("calendar.scheduling", manifest.optional_capabilities)
self.assertIn("policy.schedulingParticipantPrivacy", manifest.optional_capabilities)
self.assertIn("evaluation", manifest.optional_dependencies)
self.assertIsNotNone(manifest.route_factory)
self.assertIsNotNone(manifest.migration_spec)
self.assertIsNotNone(manifest.frontend)
self.assertIn("poll.availability_matrix", {interface.name for interface in manifest.requires_interfaces})
self.assertIn("poll.response_collection", {interface.name for interface in manifest.requires_interfaces})
self.assertIn("poll.workflow_context", {interface.name for interface in manifest.requires_interfaces})
self.assertIn("poll.signed_participation", {interface.name for interface in manifest.requires_interfaces})
self.assertIn("notifications.dispatch", {interface.name for interface in manifest.requires_interfaces})
self.assertIn("addresses.lookup", {interface.name for interface in manifest.requires_interfaces})
self.assertIn("calendar.scheduling", {interface.name for interface in manifest.requires_interfaces})
required_interfaces = {interface.name: interface for interface in manifest.requires_interfaces}
self.assertEqual("0.1.9", required_interfaces["poll.availability_matrix"].version_min)
self.assertEqual("0.1.9", required_interfaces["poll.response_collection"].version_min)
self.assertEqual("0.1.9", required_interfaces["poll.workflow_context"].version_min)
if __name__ == "__main__":
unittest.main()

224
tests/test_migrations.py Normal file
View File

@@ -0,0 +1,224 @@
from __future__ import annotations
import tempfile
import unittest
from datetime import datetime
from pathlib import Path
from alembic.runtime.migration import MigrationContext
from sqlalchemy import create_engine, func, inspect, select, text
from sqlalchemy.orm import Session
from govoplan_core.db.migrations import migrate_database
from govoplan_poll.backend.manifest import get_manifest as get_poll_manifest
from govoplan_scheduling.backend.db.models import (
SchedulingCandidateSlot,
SchedulingNotification,
SchedulingParticipant,
SchedulingRequest,
)
from govoplan_scheduling.backend.manifest import get_manifest as get_scheduling_manifest
_SCHEDULING_HEAD = "9c2f4a7d1e6b"
_ENABLED_MODULES = ("poll", "scheduling")
_MANIFEST_FACTORIES = (get_poll_manifest, get_scheduling_manifest)
class SchedulingMigrationTests(unittest.TestCase):
def _migrate(self, url: str) -> None:
migrate_database(
database_url=url,
enabled_modules=_ENABLED_MODULES,
manifest_factories=_MANIFEST_FACTORIES,
)
@staticmethod
def _remove_scheduling_revision(
connection, *, remove_privacy_column: bool = True
) -> None:
connection.execute(
text("DELETE FROM alembic_version WHERE version_num = :revision"),
{"revision": _SCHEDULING_HEAD},
)
if remove_privacy_column:
connection.execute(
text(
"ALTER TABLE scheduling_requests DROP COLUMN participant_visibility"
)
)
@staticmethod
def _seed_scheduling_rows(engine) -> None:
with Session(engine) as session:
request = SchedulingRequest(
id="request-1",
tenant_id="tenant-1",
title="Migration adoption probe",
)
request.slots.append(
SchedulingCandidateSlot(
id="slot-1",
tenant_id="tenant-1",
label="First slot",
start_at=datetime(2026, 7, 21, 8, 0),
end_at=datetime(2026, 7, 21, 9, 0),
)
)
request.participants.append(
SchedulingParticipant(
id="participant-1",
tenant_id="tenant-1",
display_name="Ada",
email="ada@example.test",
)
)
session.add(request)
session.flush()
session.add(
SchedulingNotification(
id="notification-1",
tenant_id="tenant-1",
request_id=request.id,
event_kind="invitation",
recipient="ada@example.test",
)
)
session.commit()
def test_adopts_complete_unversioned_v018_schema_and_preserves_rows(self) -> None:
with tempfile.TemporaryDirectory(
prefix="govoplan-scheduling-migration-"
) as directory:
url = f"sqlite:///{Path(directory) / 'scheduling.db'}"
self._migrate(url)
engine = create_engine(url)
try:
self._seed_scheduling_rows(engine)
with engine.begin() as connection:
self._remove_scheduling_revision(connection)
self._migrate(url)
with engine.connect() as connection:
heads = set(
MigrationContext.configure(connection).get_current_heads()
)
columns = {
item["name"]
for item in inspect(connection).get_columns(
"scheduling_requests"
)
}
visibility = connection.execute(
text(
"SELECT participant_visibility FROM scheduling_requests "
"WHERE id = 'request-1'"
)
).scalar_one()
counts = {
model.__tablename__: connection.execute(
select(func.count()).select_from(model)
).scalar_one()
for model in (
SchedulingRequest,
SchedulingCandidateSlot,
SchedulingParticipant,
SchedulingNotification,
)
}
self.assertIn(_SCHEDULING_HEAD, heads)
self.assertIn("participant_visibility", columns)
self.assertEqual(visibility, "aggregates_only")
self.assertEqual(set(counts.values()), {1})
finally:
engine.dispose()
def test_adopts_already_present_compatible_privacy_column(self) -> None:
with tempfile.TemporaryDirectory(
prefix="govoplan-scheduling-migration-"
) as directory:
url = f"sqlite:///{Path(directory) / 'scheduling.db'}"
self._migrate(url)
engine = create_engine(url)
try:
with engine.begin() as connection:
self._remove_scheduling_revision(
connection, remove_privacy_column=False
)
self._migrate(url)
with engine.connect() as connection:
heads = set(
MigrationContext.configure(connection).get_current_heads()
)
matching_columns = [
item
for item in inspect(connection).get_columns(
"scheduling_requests"
)
if item["name"] == "participant_visibility"
]
self.assertIn(_SCHEDULING_HEAD, heads)
self.assertEqual(len(matching_columns), 1)
finally:
engine.dispose()
def test_rejects_incomplete_existing_baseline(self) -> None:
with tempfile.TemporaryDirectory(
prefix="govoplan-scheduling-migration-"
) as directory:
url = f"sqlite:///{Path(directory) / 'scheduling.db'}"
self._migrate(url)
engine = create_engine(url)
try:
with engine.begin() as connection:
self._remove_scheduling_revision(connection)
connection.execute(text("DROP INDEX ix_scheduling_requests_status"))
with self.assertRaisesRegex(
RuntimeError,
"scheduling_requests missing indexes: ix_scheduling_requests_status",
):
self._migrate(url)
with engine.connect() as connection:
heads = set(
MigrationContext.configure(connection).get_current_heads()
)
self.assertNotIn(_SCHEDULING_HEAD, heads)
finally:
engine.dispose()
def test_rejects_partial_existing_calendar_extension(self) -> None:
with tempfile.TemporaryDirectory(
prefix="govoplan-scheduling-migration-"
) as directory:
url = f"sqlite:///{Path(directory) / 'scheduling.db'}"
self._migrate(url)
engine = create_engine(url)
try:
with engine.begin() as connection:
self._remove_scheduling_revision(connection)
connection.execute(text("DROP TABLE scheduling_notifications"))
with self.assertRaisesRegex(
RuntimeError,
"missing table: scheduling_notifications",
):
self._migrate(url)
with engine.connect() as connection:
heads = set(
MigrationContext.configure(connection).get_current_heads()
)
self.assertNotIn(_SCHEDULING_HEAD, heads)
finally:
engine.dispose()
if __name__ == "__main__":
unittest.main()

View File

@@ -0,0 +1,244 @@
from __future__ import annotations
import unittest
from sqlalchemy import create_engine
from sqlalchemy.orm import Session, sessionmaker
from govoplan_core.core.modules import ModuleContext, ModuleManifest
from govoplan_core.core.policy import (
CAPABILITY_POLICY_SCHEDULING_PARTICIPANT_PRIVACY,
PolicySourceStep,
SchedulingParticipantPrivacyDecision,
SchedulingParticipantPrivacyRequest,
)
from govoplan_core.core.registry import PlatformRegistry
from govoplan_core.db.base import Base
from govoplan_scheduling.backend.db.models import (
SchedulingCandidateSlot,
SchedulingParticipant,
SchedulingRequest,
)
from govoplan_scheduling.backend.runtime import configure_runtime
from govoplan_scheduling.backend.schemas import (
SchedulingCandidateSlotInput,
SchedulingRequestCreateRequest,
SchedulingRequestResponse,
SchedulingRequestUpdateRequest,
)
from govoplan_scheduling.backend.service import scheduling_request_response
class _PrivacyPolicy:
def __init__(self, effective_visibility: str) -> None:
self.effective_visibility = effective_visibility
self.requests: list[SchedulingParticipantPrivacyRequest] = []
def resolve_scheduling_participant_visibility(
self,
session: object,
*,
request: SchedulingParticipantPrivacyRequest,
) -> SchedulingParticipantPrivacyDecision:
self.requests.append(request)
return SchedulingParticipantPrivacyDecision(
effective_visibility=self.effective_visibility, # type: ignore[arg-type]
reason="Tenant participant privacy policy",
source_path=(
PolicySourceStep(
scope_type="tenant",
scope_id=request.tenant_id,
label="Tenant",
applied_fields=("scheduling_participant_visibility",),
),
),
details={"provider_session_available": session is not None},
)
class SchedulingParticipantPrivacyTests(unittest.TestCase):
def setUp(self) -> None:
configure_runtime(registry=PlatformRegistry())
self.engine = create_engine("sqlite:///:memory:")
Base.metadata.create_all(
self.engine,
tables=[
SchedulingRequest.__table__,
SchedulingCandidateSlot.__table__,
SchedulingParticipant.__table__,
],
)
self.Session = sessionmaker(bind=self.engine)
self.session: Session = self.Session()
def tearDown(self) -> None:
self.session.close()
Base.metadata.drop_all(
self.engine,
tables=[
SchedulingParticipant.__table__,
SchedulingCandidateSlot.__table__,
SchedulingRequest.__table__,
],
)
self.engine.dispose()
configure_runtime(registry=PlatformRegistry())
def _request(self, *, participant_visibility: str | None = None) -> SchedulingRequest:
values = {
"tenant_id": "tenant-1",
"title": "Privacy review",
"status": "collecting",
"organizer_user_id": "organizer-1",
}
if participant_visibility is not None:
values["participant_visibility"] = participant_visibility
request = SchedulingRequest(**values)
request.participants = [
SchedulingParticipant(
tenant_id="tenant-1",
respondent_id="alice-id",
display_name="Alice",
email="alice@example.test",
participant_type="internal",
status="responded",
metadata_={"private": "alice"},
),
SchedulingParticipant(
tenant_id="tenant-1",
respondent_id="bob-id",
display_name="Bob",
email="bob@example.test",
participant_type="external",
status="invited",
metadata_={"private": "bob"},
),
]
self.session.add(request)
self.session.flush()
return request
@staticmethod
def _participant_projection(request: SchedulingRequest) -> dict[str, object]:
return scheduling_request_response(
request,
actor_ids=("alice-id", "alice@example.test"),
actor_user_id="alice-account",
)
@staticmethod
def _configure_policy(provider: _PrivacyPolicy) -> None:
registry = PlatformRegistry()
registry.register(
ModuleManifest(
id="policy_test",
name="Policy test",
version="test",
capability_factories={
CAPABILITY_POLICY_SCHEDULING_PARTICIPANT_PRIVACY: lambda context: provider,
},
)
)
registry.configure_capability_context(ModuleContext(registry=registry, settings=object()))
configure_runtime(registry=registry)
def test_secure_default_returns_own_row_and_aggregate_counts(self) -> None:
request = self._request()
payload = self._participant_projection(request)
response = SchedulingRequestResponse.model_validate(payload)
self.assertEqual(request.participant_visibility, "aggregates_only")
self.assertEqual(response.participant_visibility, "aggregates_only")
self.assertEqual(response.effective_participant_visibility, "aggregates_only")
self.assertEqual([participant.display_name for participant in response.participants], ["Alice"])
self.assertEqual(response.participants[0].email, "alice@example.test")
self.assertEqual(response.participant_aggregate.total, 2)
self.assertEqual(response.participant_aggregate.status_counts["responded"], 1)
self.assertEqual(response.participant_aggregate.status_counts["invited"], 1)
def test_configured_roster_returns_other_names_and_statuses_with_sensitive_fields_redacted(self) -> None:
request = self._request(participant_visibility="names_and_statuses")
response = SchedulingRequestResponse.model_validate(self._participant_projection(request))
self.assertEqual(response.effective_participant_visibility, "names_and_statuses")
own = next(participant for participant in response.participants if participant.display_name == "Alice")
other = next(participant for participant in response.participants if participant.display_name == "Bob")
self.assertEqual(own.respondent_id, "alice-id")
self.assertEqual(own.email, "alice@example.test")
self.assertEqual(other.status, "invited")
self.assertIsNone(other.respondent_id)
self.assertIsNone(other.email)
self.assertIsNone(other.poll_invitation_id)
self.assertEqual(other.metadata, {})
def test_manager_and_organizer_bypass_participant_roster_restriction(self) -> None:
request = self._request()
manager = SchedulingRequestResponse.model_validate(
scheduling_request_response(
request,
actor_ids=("manager-1",),
actor_user_id="manager-1",
can_manage=True,
)
)
organizer = SchedulingRequestResponse.model_validate(
scheduling_request_response(
request,
actor_ids=("organizer-1",),
actor_user_id="organizer-1",
)
)
for response in (manager, organizer):
self.assertEqual(response.effective_participant_visibility, "names_and_statuses")
self.assertEqual({participant.email for participant in response.participants}, {
"alice@example.test",
"bob@example.test",
})
self.assertTrue(response.participant_visibility_decision.details["management_access"])
def test_optional_policy_can_reduce_but_cannot_broaden_visibility(self) -> None:
restricting_policy = _PrivacyPolicy("aggregates_only")
self._configure_policy(restricting_policy)
visible_request = self._request(participant_visibility="names_and_statuses")
reduced = SchedulingRequestResponse.model_validate(self._participant_projection(visible_request))
self.assertEqual(reduced.effective_participant_visibility, "aggregates_only")
self.assertEqual([participant.display_name for participant in reduced.participants], ["Alice"])
self.assertTrue(reduced.participant_visibility_decision.policy_applied)
self.assertEqual(reduced.participant_visibility_decision.reason, "Tenant participant privacy policy")
self.assertEqual(reduced.participant_visibility_decision.source_path[0]["path"], "tenant:tenant-1")
self.assertTrue(reduced.participant_visibility_decision.details["provider_session_available"])
self.assertEqual(restricting_policy.requests[0].actor_user_id, "alice-account")
widening_policy = _PrivacyPolicy("names_and_statuses")
self._configure_policy(widening_policy)
private_request = self._request()
clamped = SchedulingRequestResponse.model_validate(self._participant_projection(private_request))
self.assertEqual(clamped.effective_participant_visibility, "aggregates_only")
self.assertEqual([participant.display_name for participant in clamped.participants], ["Alice"])
self.assertEqual(widening_policy.requests[0].requested_visibility, "aggregates_only")
def test_create_and_update_schemas_expose_the_configuration(self) -> None:
slot = SchedulingCandidateSlotInput.model_validate(
{
"start_at": "2026-07-20T09:00:00Z",
"end_at": "2026-07-20T10:00:00Z",
}
)
created = SchedulingRequestCreateRequest(title="Privacy", slots=[slot])
updated = SchedulingRequestUpdateRequest(participant_visibility="names_and_statuses")
self.assertEqual(created.participant_visibility, "aggregates_only")
self.assertEqual(updated.participant_visibility, "names_and_statuses")
if __name__ == "__main__":
unittest.main()

View File

@@ -0,0 +1,381 @@
from __future__ import annotations
import unittest
from datetime import datetime, timedelta, timezone
from types import SimpleNamespace
from fastapi import HTTPException
from pydantic import ValidationError
from sqlalchemy import create_engine
from sqlalchemy.orm import Session, sessionmaker
from govoplan_core.auth import ApiPrincipal
from govoplan_core.core.access import PrincipalRef
from govoplan_core.core.modules import ModuleContext
from govoplan_core.core.registry import PlatformRegistry
from govoplan_core.db.base import Base
from govoplan_poll.backend.db.models import Poll, PollInvitation, PollOption, PollResponse
from govoplan_poll.backend.manifest import get_manifest as get_poll_manifest
from govoplan_scheduling.backend.db.models import (
SchedulingCandidateSlot,
SchedulingNotification,
SchedulingParticipant,
SchedulingRequest,
)
from govoplan_scheduling.backend.manifest import RESPOND_SCOPE, WRITE_SCOPE
from govoplan_scheduling.backend.router import (
api_get_my_scheduling_availability,
api_submit_scheduling_availability,
api_update_scheduling_candidate_slot,
)
from govoplan_scheduling.backend.runtime import configure_runtime
from govoplan_scheduling.backend.schemas import (
SchedulingAvailabilityAnswerInput,
SchedulingAvailabilityResponseRequest,
SchedulingCalendarPreferences,
SchedulingCandidateSlotInput,
SchedulingCandidateSlotUpdateRequest,
SchedulingParticipantInput,
SchedulingRequestCreateRequest,
)
from govoplan_scheduling.backend.service import (
SchedulingError,
cancel_scheduling_request,
create_scheduling_request,
scheduling_request_summary,
scheduling_slot_revision,
update_scheduling_candidate_slot,
)
class SchedulingResponseEditingTests(unittest.TestCase):
def setUp(self) -> None:
registry = PlatformRegistry()
registry.register(get_poll_manifest())
registry.configure_capability_context(ModuleContext(registry=registry, settings=object()))
configure_runtime(registry=registry)
self.engine = create_engine("sqlite:///:memory:")
Base.metadata.create_all(
self.engine,
tables=[
Poll.__table__,
PollOption.__table__,
PollResponse.__table__,
PollInvitation.__table__,
SchedulingRequest.__table__,
SchedulingCandidateSlot.__table__,
SchedulingParticipant.__table__,
SchedulingNotification.__table__,
],
)
self.Session = sessionmaker(bind=self.engine)
self.session: Session = self.Session()
def tearDown(self) -> None:
self.session.close()
Base.metadata.drop_all(
self.engine,
tables=[
SchedulingNotification.__table__,
SchedulingParticipant.__table__,
SchedulingCandidateSlot.__table__,
SchedulingRequest.__table__,
PollInvitation.__table__,
PollResponse.__table__,
PollOption.__table__,
Poll.__table__,
],
)
self.engine.dispose()
@staticmethod
def _principal(account_id: str, *, email: str | None, scopes: set[str]) -> ApiPrincipal:
return ApiPrincipal(
principal=PrincipalRef(
account_id=account_id,
membership_id=f"membership-{account_id}",
tenant_id="tenant-1",
email=email,
display_name=account_id,
scopes=frozenset(scopes),
),
account=SimpleNamespace(id=account_id),
user=SimpleNamespace(id=f"membership-{account_id}"),
)
def _request(
self,
*,
status: str = "collecting",
allow_participant_updates: bool = True,
) -> SchedulingRequest:
start = datetime(2026, 7, 20, 9, tzinfo=timezone.utc)
request, _tokens = create_scheduling_request(
self.session,
tenant_id="tenant-1",
user_id="organizer-1",
payload=SchedulingRequestCreateRequest(
title="Response editing",
status=status,
allow_participant_updates=allow_participant_updates,
calendar=SchedulingCalendarPreferences(),
slots=[
SchedulingCandidateSlotInput(
label="Monday",
start_at=start,
end_at=start + timedelta(hours=1),
),
SchedulingCandidateSlotInput(
label="Tuesday",
start_at=start + timedelta(days=1),
end_at=start + timedelta(days=1, hours=1),
),
],
participants=[
SchedulingParticipantInput(
display_name="Alice",
email="alice@example.test",
)
],
),
)
return request
def _submit_both(self, request: SchedulingRequest) -> None:
api_submit_scheduling_availability(
request.id,
SchedulingAvailabilityResponseRequest(
answers=[
SchedulingAvailabilityAnswerInput(
slot_id=request.slots[0].id,
value="available",
option_revision=scheduling_slot_revision(request.slots[0]),
),
SchedulingAvailabilityAnswerInput(
slot_id=request.slots[1].id,
value="maybe",
option_revision=scheduling_slot_revision(request.slots[1]),
),
]
),
session=self.session,
principal=self._principal(
"alice-account",
email="alice@example.test",
scopes={RESPOND_SCOPE},
),
)
def test_current_participant_response_is_prefilled_and_changed_slot_is_invalidated(self) -> None:
request = self._request()
self._submit_both(request)
alice = self._principal(
"alice-account",
email="alice@example.test",
scopes={RESPOND_SCOPE},
)
before = api_get_my_scheduling_availability(
request.id,
session=self.session,
principal=alice,
)
self.assertTrue(before.has_response)
self.assertIsNotNone(before.submitted_at)
self.assertEqual(before.participant_id, request.participants[0].id)
self.assertEqual(
[(answer.slot_id, answer.value) for answer in before.answers],
[(request.slots[0].id, "available"), (request.slots[1].id, "maybe")],
)
api_update_scheduling_candidate_slot(
request.id,
request.slots[0].id,
SchedulingCandidateSlotUpdateRequest(label="Monday, revised"),
session=self.session,
principal=self._principal("organizer-1", email=None, scopes={WRITE_SCOPE}),
)
after = api_get_my_scheduling_availability(
request.id,
session=self.session,
principal=alice,
)
self.assertTrue(after.has_response)
self.assertEqual(
[(answer.slot_id, answer.value) for answer in after.answers],
[(request.slots[1].id, "maybe")],
)
poll_response = self.session.query(PollResponse).filter(PollResponse.poll_id == request.poll_id).one()
self.assertEqual(
[answer["option_id"] for answer in poll_response.answers],
[request.slots[1].poll_option_id],
)
# Re-submit and repeat the exact option snapshot: an idempotent no-op
# must preserve both current answers.
self._submit_both(request)
api_update_scheduling_candidate_slot(
request.id,
request.slots[0].id,
SchedulingCandidateSlotUpdateRequest(label="Monday, revised"),
session=self.session,
principal=self._principal("organizer-1", email=None, scopes={WRITE_SCOPE}),
)
unchanged = api_get_my_scheduling_availability(
request.id,
session=self.session,
principal=alice,
)
self.assertEqual(len(unchanged.answers), 2)
def test_calendar_hold_rejection_leaves_slot_and_answers_unchanged(self) -> None:
request = self._request()
self._submit_both(request)
slot = request.slots[0]
original_start = slot.start_at
slot.tentative_hold_event_id = "event-1"
self.session.flush()
with self.assertRaisesRegex(SchedulingError, "tentative calendar hold"):
update_scheduling_candidate_slot(
self.session,
tenant_id="tenant-1",
request_id=request.id,
slot_id=slot.id,
payload=SchedulingCandidateSlotUpdateRequest(
start_at=original_start.replace(tzinfo=timezone.utc) + timedelta(minutes=15),
),
)
self.assertEqual(slot.start_at, original_start)
response = self.session.query(PollResponse).filter(PollResponse.poll_id == request.poll_id).one()
self.assertEqual(len(response.answers), 2)
def test_cancelling_draft_request_preserves_draft_poll(self) -> None:
request = self._request(status="draft")
cancelled = cancel_scheduling_request(
self.session,
tenant_id="tenant-1",
request_id=request.id,
)
poll = self.session.query(Poll).filter(Poll.id == request.poll_id).one()
self.assertEqual(cancelled.status, "cancelled")
self.assertIsNotNone(cancelled.cancelled_at)
self.assertEqual(poll.status, "draft")
def test_fully_invalidated_response_becomes_unanswered(self) -> None:
request = self._request()
alice = self._principal(
"alice-account",
email="alice@example.test",
scopes={RESPOND_SCOPE},
)
api_submit_scheduling_availability(
request.id,
SchedulingAvailabilityResponseRequest(
answers=[
SchedulingAvailabilityAnswerInput(
slot_id=request.slots[0].id,
value="available",
option_revision=scheduling_slot_revision(request.slots[0]),
)
]
),
session=self.session,
principal=alice,
)
api_update_scheduling_candidate_slot(
request.id,
request.slots[0].id,
SchedulingCandidateSlotUpdateRequest(label="Monday, revised"),
session=self.session,
principal=self._principal("organizer-1", email=None, scopes={WRITE_SCOPE}),
)
current = api_get_my_scheduling_availability(
request.id,
session=self.session,
principal=alice,
)
self.assertFalse(current.has_response)
self.assertEqual(current.answers, [])
self.assertEqual(request.participants[0].status, "invited")
self.assertIsNone(request.participants[0].responded_at)
self.assertEqual(
scheduling_request_summary(self.session, tenant_id="tenant-1", request_id=request.id)["response_count"],
0,
)
def test_option_change_is_blocked_when_response_updates_are_disabled(self) -> None:
request = self._request(allow_participant_updates=False)
self._submit_both(request)
original_label = request.slots[0].label
with self.assertRaisesRegex(SchedulingError, "response updates are disabled"):
update_scheduling_candidate_slot(
self.session,
tenant_id="tenant-1",
request_id=request.id,
slot_id=request.slots[0].id,
payload=SchedulingCandidateSlotUpdateRequest(label="Monday, revised"),
)
self.assertEqual(request.slots[0].label, original_label)
response = self.session.query(PollResponse).filter(PollResponse.poll_id == request.poll_id).one()
self.assertEqual(len(response.answers), 2)
def test_stale_option_revision_is_rejected_without_writing_a_response(self) -> None:
request = self._request()
stale_revision = scheduling_slot_revision(request.slots[0])
api_update_scheduling_candidate_slot(
request.id,
request.slots[0].id,
SchedulingCandidateSlotUpdateRequest(label="Monday, revised"),
session=self.session,
principal=self._principal("organizer-1", email=None, scopes={WRITE_SCOPE}),
)
with self.assertRaises(HTTPException) as stale:
api_submit_scheduling_availability(
request.id,
SchedulingAvailabilityResponseRequest(
answers=[
SchedulingAvailabilityAnswerInput(
slot_id=request.slots[0].id,
value="available",
option_revision=stale_revision,
)
]
),
session=self.session,
principal=self._principal(
"alice-account",
email="alice@example.test",
scopes={RESPOND_SCOPE},
),
)
self.assertEqual(stale.exception.status_code, 409)
self.assertEqual(self.session.query(PollResponse).filter(PollResponse.poll_id == request.poll_id).count(), 0)
def test_slot_inputs_require_aware_datetimes_and_known_timezones(self) -> None:
with self.assertRaises(ValidationError):
SchedulingCandidateSlotInput(
start_at=datetime(2026, 7, 20, 9),
end_at=datetime(2026, 7, 20, 10),
)
with self.assertRaisesRegex(ValidationError, "valid IANA timezone"):
SchedulingCandidateSlotInput(
start_at=datetime(2026, 7, 20, 9, tzinfo=timezone.utc),
end_at=datetime(2026, 7, 20, 10, tzinfo=timezone.utc),
timezone="Mars/Olympus_Mons",
)
if __name__ == "__main__":
unittest.main()

1236
tests/test_service.py Normal file

File diff suppressed because it is too large Load Diff

35
webui/package.json Normal file
View File

@@ -0,0 +1,35 @@
{
"name": "@govoplan/scheduling-webui",
"version": "0.1.9",
"private": true,
"type": "module",
"main": "src/index.ts",
"module": "src/index.ts",
"types": "src/index.ts",
"exports": {
".": {
"types": "./src/index.ts",
"import": "./src/index.ts"
},
"./styles/scheduling.css": "./src/styles/scheduling.css"
},
"scripts": {
"test:view-model": "node --experimental-strip-types --test tests/scheduling-view-model.test.ts",
"test:ui-structure": "node scripts/test-scheduling-page-structure.mjs"
},
"peerDependencies": {
"@govoplan/core-webui": "^0.1.9",
"lucide-react": "^1.23.0",
"react": "^19.0.0",
"react-dom": "^19.0.0",
"react-router-dom": "^7.1.1",
"@vitejs/plugin-react": "^4.3.4",
"typescript": "^5.7.2",
"vite": "^6.0.6"
},
"peerDependenciesMeta": {
"@govoplan/core-webui": {
"optional": true
}
}
}

View File

@@ -0,0 +1,71 @@
import assert from "node:assert/strict";
import { readFileSync } from "node:fs";
import { fileURLToPath } from "node:url";
const pagePath = fileURLToPath(new URL("../src/features/scheduling/SchedulingPage.tsx", import.meta.url));
const apiPath = fileURLToPath(new URL("../src/api/scheduling.ts", import.meta.url));
const page = readFileSync(pagePath, "utf8");
const api = readFileSync(apiPath, "utf8");
assert.match(page, /usePlatformUiCapability<CalendarPickerUiCapability>\("calendar\.picker"\)/);
assert.match(page, /hasScope\(auth, "calendar:calendar:read"\)/);
assert.match(page, /Boolean\(calendarPickerCapability\) && canReadCalendars && canReadAvailability && canWriteCalendarEvent/);
assert.doesNotMatch(page, /@govoplan\/calendar-webui|govoplan-calendar\/webui/);
assert.match(page, /Card,[\s\S]*DataGrid,[\s\S]*DataGridEmptyAction,[\s\S]*DataGridRowActions,[\s\S]*ModuleSubnav,[\s\S]*ToggleSwitch,[\s\S]*from "@govoplan\/core-webui"/);
assert.doesNotMatch(page, /@govoplan\/core-webui\/src\//);
assert.match(page, /className="scheduling-full-editor"/);
assert.match(page, /className="scheduling-page-actions"/);
const editorActions = page.slice(
page.indexOf('<div className="scheduling-page-actions">'),
page.indexOf('</div>', page.indexOf('<div className="scheduling-page-actions">'))
);
assert.ok(editorActions.indexOf("I18N.discard") < editorActions.indexOf("I18N.save"));
assert.match(editorActions, /form="scheduling-create-form"/);
const createBranchStart = page.indexOf(" if (creating) {");
const createReturnStart = page.indexOf("\n return (", createBranchStart);
const browseBranchStart = page.indexOf("\n return (", createReturnStart + 1);
const createBranch = page.slice(createBranchStart, browseBranchStart);
const browseBranch = page.slice(browseBranchStart);
assert.match(createBranch, /<ModuleSubnav/);
assert.match(createBranch, /className="scheduling-create-subnav"/);
assert.doesNotMatch(browseBranch, /scheduling-sidebar|<aside/);
assert.match(browseBranch, /<h1>\{I18N\.requests\}<\/h1>/);
assert.match(browseBranch, /<Plus aria-hidden="true" size=\{16\} \/> \{I18N\.add\}/);
assert.match(page, /title=\{I18N\.myRequests\}/);
assert.match(page, /title=\{I18N\.invitedRequests\}/);
assert.match(createBranch, /<Card title=\{I18N\.basicInformation\}>/);
assert.match(createBranch, /<Card title=\{I18N\.calendarIntegration\}>/);
assert.match(page, /<Card title=\{I18N\.candidateSlots\}>/);
assert.match(page, /<Card title=\{I18N\.participants\}>/);
assert.match(createBranch, /<ToggleSwitch[\s\S]*checked=\{calendarEnabled\}/);
assert.match(page, /<ToggleSwitch[\s\S]*checked=\{participantRosterVisible\}/);
assert.match(page, /participant_visibility: participantRosterVisible \? "names_and_statuses" : "aggregates_only"/);
assert.match(page, /id="scheduling-create-candidate-slots-grid"/);
assert.match(page, /id="scheduling-create-participants-grid"/);
assert.match(page, /id="scheduling-candidate-slots-grid"/);
assert.match(page, /id="scheduling-participants-grid"/);
assert.match(page, /<DataGridRowActions/);
assert.match(page, /<DataGridEmptyAction/);
assert.doesNotMatch(page, /EmailAddressInput|MailboxAddress|addressSuggestions|addressLookupQuery/);
assert.match(page, /type="email"[\s\S]*aria-label=\{I18N\.participantEmail\}/);
assert.doesNotMatch(page, /header: I18N\.required|<table|scheduling-table|scheduling-card(?:\s|"|`)/);
assert.match(page, /aria-label=\{i18nMessage\("i18n:govoplan-scheduling\.decide_on_value/);
assert.match(page, /submitSchedulingAvailability\(settings, selected\.id/);
assert.match(page, /option_revision: slot\.revision/);
assert.match(page, /getSchedulingAvailabilityResponse\(settings, selected\.id\)/);
assert.match(page, /setAvailability\(Object\.fromEntries\(response\.answers\.map/);
assert.match(page, /selected\.participant_aggregate\.total/);
assert.match(page, /selected\.effective_participant_visibility === "names_and_statuses"/);
assert.match(api, /participant_visibility: SchedulingParticipantVisibility/);
assert.match(api, /participant_aggregate: SchedulingParticipantAggregate/);
assert.doesNotMatch(page, /<p>\{selected\.calendar_id\}<\/p>/);
assert.match(page, /className="scheduling-selected-calendar"/);
assert.match(page, /showPlanningCalendarActions/);
assert.match(page, /title=\{!canReadAvailability \? I18N\.requiresAvailabilityRead/);
assert.match(api, /\/api\/v1\/scheduling\/requests\/\$\{requestId\}\/responses/);
assert.match(api, /\/api\/v1\/scheduling\/requests\/\$\{requestId\}\/responses\/me/);
console.log("Scheduling page structure satisfies the focused list/create/respond contract.");

299
webui/src/api/scheduling.ts Normal file
View File

@@ -0,0 +1,299 @@
import { apiFetch, type ApiSettings } from "@govoplan/core-webui";
export type SchedulingStatus = "draft" | "collecting" | "closed" | "decided" | "handed_off" | "cancelled" | "archived";
export type SchedulingParticipantVisibility = "aggregates_only" | "names_and_statuses";
export type SchedulingCandidateSlot = {
id: string;
poll_option_id?: string | null;
label: string;
description?: string | null;
start_at: string;
end_at: string;
timezone: string;
location?: string | null;
position: number;
revision: string;
freebusy_checked_at?: string | null;
freebusy_status?: string | null;
freebusy_conflicts: Record<string, unknown>[];
tentative_hold_event_id?: string | null;
metadata?: Record<string, unknown>;
};
export type SchedulingParticipant = {
id: string;
respondent_id?: string | null;
display_name?: string | null;
email?: string | null;
participant_type: string;
required: boolean;
status: string;
poll_invitation_id?: string | null;
invitation_token?: string | null;
last_invited_at?: string | null;
responded_at?: string | null;
metadata?: Record<string, unknown>;
};
export type SchedulingParticipantAggregate = {
total: number;
status_counts: Record<string, number>;
};
export type SchedulingParticipantVisibilityDecision = {
requested_visibility: SchedulingParticipantVisibility;
effective_visibility: SchedulingParticipantVisibility;
policy_applied: boolean;
reason?: string | null;
source_path: Record<string, unknown>[];
details: Record<string, unknown>;
};
export type SchedulingRequest = {
id: string;
tenant_id: string;
title: string;
description?: string | null;
location?: string | null;
timezone: string;
status: SchedulingStatus;
poll_id?: string | null;
selected_slot_id?: string | null;
organizer_user_id?: string | null;
deadline_at?: string | null;
allow_external_participants: boolean;
allow_participant_updates: boolean;
result_visibility: string;
participant_visibility: SchedulingParticipantVisibility;
effective_participant_visibility: SchedulingParticipantVisibility;
participant_aggregate: SchedulingParticipantAggregate;
participant_visibility_decision: SchedulingParticipantVisibilityDecision;
calendar_integration_enabled: boolean;
calendar_id?: string | null;
calendar_freebusy_enabled: boolean;
calendar_hold_enabled: boolean;
create_calendar_event_on_decision: boolean;
calendar_event_id?: string | null;
handed_off_at?: string | null;
cancelled_at?: string | null;
created_at: string;
updated_at: string;
metadata?: Record<string, unknown>;
slots: SchedulingCandidateSlot[];
participants: SchedulingParticipant[];
};
export type SchedulingRequestListResponse = { requests: SchedulingRequest[] };
export type SchedulingStatusResponse = { request: SchedulingRequest };
export type SchedulingCandidateSlotPayload = {
label?: string | null;
description?: string | null;
start_at: string;
end_at: string;
timezone?: string | null;
location?: string | null;
metadata?: Record<string, unknown>;
};
export type SchedulingParticipantPayload = {
respondent_id?: string | null;
display_name?: string | null;
email?: string | null;
participant_type?: "internal" | "external" | "resource";
required?: boolean;
metadata?: Record<string, unknown>;
};
export type SchedulingRequestCreatePayload = {
title: string;
description?: string | null;
location?: string | null;
timezone?: string;
status?: "draft" | "collecting";
deadline_at?: string | null;
allow_external_participants?: boolean;
allow_participant_updates?: boolean;
result_visibility?: "organizer" | "after_response" | "after_close" | "public";
participant_visibility?: SchedulingParticipantVisibility;
calendar?: {
enabled?: boolean;
calendar_id?: string | null;
freebusy_enabled?: boolean;
tentative_holds_enabled?: boolean;
create_event_on_decision?: boolean;
};
slots: SchedulingCandidateSlotPayload[];
participants?: SchedulingParticipantPayload[];
create_participant_invitations?: boolean;
metadata?: Record<string, unknown>;
};
export type SchedulingDecisionPayload = {
slot_id?: string | null;
poll_option_id?: string | null;
handoff_to_calendar?: boolean | null;
};
export type SchedulingAvailabilityValue = "available" | "maybe" | "unavailable";
export type SchedulingAvailabilityPayload = {
answers: Array<{
slot_id: string;
value: SchedulingAvailabilityValue;
option_revision: string;
}>;
};
export type SchedulingAvailabilityResponse = {
request_id: string;
participant_id: string;
has_response: boolean;
submitted_at?: string | null;
answers: Array<{
slot_id: string;
value: SchedulingAvailabilityValue;
}>;
};
export type SchedulingCalendarActionResponse = {
request: SchedulingRequest;
created_event_ids: string[];
updated_slot_ids: string[];
warnings: string[];
};
export type SchedulingNotification = {
id: string;
request_id: string;
participant_id?: string | null;
event_kind: string;
channel: string;
recipient?: string | null;
status: string;
payload: Record<string, unknown>;
error?: string | null;
sent_at?: string | null;
created_at: string;
updated_at: string;
metadata?: Record<string, unknown>;
};
export type SchedulingNotificationListResponse = { notifications: SchedulingNotification[] };
export type SchedulingPollOptionResult = {
option_id: string;
option_key: string;
label: string;
count: number;
score: number;
values: Record<string, number>;
};
export type SchedulingSummaryResponse = {
request: SchedulingRequest;
poll_summary: {
poll_id: string;
kind: string;
status: string;
response_count: number;
option_results: SchedulingPollOptionResult[];
leading_option_ids: string[];
};
};
export type SchedulingAddressLookupCandidate = {
contact_id: string;
address_book_id: string;
display_name: string;
email?: string | null;
email_label?: string | null;
organization?: string | null;
role_title?: string | null;
tags: string[];
source_kind: string;
source_ref?: string | null;
source_revision?: string | null;
provenance: Record<string, unknown>;
};
export type SchedulingAddressLookupResponse = {
available: boolean;
candidates: SchedulingAddressLookupCandidate[];
};
const json = (payload: unknown) => ({ method: "POST", body: JSON.stringify(payload ?? {}) });
export function lookupSchedulingAddresses(settings: ApiSettings, query: string, limit = 25): Promise<SchedulingAddressLookupResponse> {
const params = new URLSearchParams({ query, limit: String(limit) });
return apiFetch<SchedulingAddressLookupResponse>(settings, `/api/v1/scheduling/address-lookup?${params.toString()}`);
}
export function listSchedulingRequests(settings: ApiSettings, status?: string): Promise<SchedulingRequestListResponse> {
const query = status ? `?status=${encodeURIComponent(status)}` : "";
return apiFetch<SchedulingRequestListResponse>(settings, `/api/v1/scheduling/requests${query}`);
}
export function createSchedulingRequest(settings: ApiSettings, payload: SchedulingRequestCreatePayload): Promise<SchedulingRequest> {
return apiFetch<SchedulingRequest>(settings, "/api/v1/scheduling/requests", json(payload));
}
export function submitSchedulingAvailability(
settings: ApiSettings,
requestId: string,
payload: SchedulingAvailabilityPayload
): Promise<SchedulingStatusResponse> {
return apiFetch<SchedulingStatusResponse>(
settings,
`/api/v1/scheduling/requests/${requestId}/responses`,
json(payload)
);
}
export function getSchedulingAvailabilityResponse(
settings: ApiSettings,
requestId: string
): Promise<SchedulingAvailabilityResponse> {
return apiFetch<SchedulingAvailabilityResponse>(
settings,
`/api/v1/scheduling/requests/${requestId}/responses/me`
);
}
export function openSchedulingRequest(settings: ApiSettings, requestId: string): Promise<SchedulingStatusResponse> {
return apiFetch<SchedulingStatusResponse>(settings, `/api/v1/scheduling/requests/${requestId}/open`, json({}));
}
export function closeSchedulingRequest(settings: ApiSettings, requestId: string): Promise<SchedulingStatusResponse> {
return apiFetch<SchedulingStatusResponse>(settings, `/api/v1/scheduling/requests/${requestId}/close`, json({}));
}
export function decideSchedulingRequest(settings: ApiSettings, requestId: string, payload: SchedulingDecisionPayload): Promise<SchedulingStatusResponse> {
return apiFetch<SchedulingStatusResponse>(settings, `/api/v1/scheduling/requests/${requestId}/decide`, json(payload));
}
export function evaluateSchedulingFreeBusy(settings: ApiSettings, requestId: string): Promise<SchedulingCalendarActionResponse> {
return apiFetch<SchedulingCalendarActionResponse>(settings, `/api/v1/scheduling/requests/${requestId}/calendar/freebusy`, json({}));
}
export function createSchedulingHolds(settings: ApiSettings, requestId: string): Promise<SchedulingCalendarActionResponse> {
return apiFetch<SchedulingCalendarActionResponse>(settings, `/api/v1/scheduling/requests/${requestId}/calendar/holds`, json({}));
}
export function createSchedulingCalendarEvent(settings: ApiSettings, requestId: string): Promise<SchedulingCalendarActionResponse> {
return apiFetch<SchedulingCalendarActionResponse>(settings, `/api/v1/scheduling/requests/${requestId}/calendar/event`, json({}));
}
export function schedulingSummary(settings: ApiSettings, requestId: string): Promise<SchedulingSummaryResponse> {
return apiFetch<SchedulingSummaryResponse>(settings, `/api/v1/scheduling/requests/${requestId}/summary`);
}
export function createSchedulingNotifications(settings: ApiSettings, requestId: string, eventKind: string): Promise<SchedulingNotificationListResponse> {
return apiFetch<SchedulingNotificationListResponse>(settings, `/api/v1/scheduling/requests/${requestId}/notifications`, json({ event_kind: eventKind }));
}
export function listSchedulingNotifications(settings: ApiSettings, requestId?: string): Promise<SchedulingNotificationListResponse> {
const query = requestId ? `?request_id=${encodeURIComponent(requestId)}` : "";
return apiFetch<SchedulingNotificationListResponse>(settings, `/api/v1/scheduling/notifications${query}`);
}

File diff suppressed because it is too large Load Diff

View File

@@ -0,0 +1,146 @@
import type { SchedulingParticipant, SchedulingRequest } from "../../api/scheduling";
export type SchedulingActor = {
accountId?: string | null;
userId?: string | null;
membershipId?: string | null;
identityId?: string | null;
email?: string | null;
};
export type SchedulingRequestGroups = {
owned: SchedulingRequest[];
invited: SchedulingRequest[];
other: SchedulingRequest[];
};
export type SchedulingSortPhase =
| "unanswered"
| "answered"
| "closed"
| "determined"
| "past";
export function schedulingActorIds(actor: SchedulingActor): string[] {
return Array.from(new Set([
actor.accountId,
actor.userId,
actor.membershipId,
actor.identityId,
actor.email
].filter((value): value is string => Boolean(value))));
}
export function schedulingParticipantForActor(
request: SchedulingRequest,
actor: SchedulingActor
): SchedulingParticipant | null {
const ids = new Set(schedulingActorIds(actor));
return request.participants.find((participant) =>
Boolean(
(participant.respondent_id && ids.has(participant.respondent_id)) ||
(participant.email && ids.has(participant.email))
)
) ?? null;
}
export function schedulingRequestIsOwned(
request: SchedulingRequest,
actor: SchedulingActor
): boolean {
return Boolean(
request.organizer_user_id &&
schedulingActorIds(actor).includes(request.organizer_user_id)
);
}
export function schedulingSortPhase(
request: SchedulingRequest,
actor: SchedulingActor,
now = new Date()
): SchedulingSortPhase {
if (schedulingRequestIsPast(request, now)) return "past";
if (["decided", "handed_off"].includes(request.status)) return "determined";
if (["closed", "cancelled", "archived"].includes(request.status)) return "closed";
if (schedulingRequestIsOwned(request, actor)) return "unanswered";
const participant = schedulingParticipantForActor(request, actor);
return participant && ["responded", "declined"].includes(participant.status)
? "answered"
: "unanswered";
}
export function compareSchedulingRequests(
left: SchedulingRequest,
right: SchedulingRequest,
actor: SchedulingActor,
now = new Date()
): number {
const leftPhase = schedulingSortPhase(left, actor, now);
const rightPhase = schedulingSortPhase(right, actor, now);
const phaseDifference = SORT_PHASE_ORDER[leftPhase] - SORT_PHASE_ORDER[rightPhase];
if (phaseDifference !== 0) return phaseDifference;
const leftDate = schedulingRelevantTimestamp(left, now);
const rightDate = schedulingRelevantTimestamp(right, now);
const dateDifference = leftPhase === "past"
? rightDate - leftDate
: leftDate - rightDate;
if (dateDifference !== 0) return dateDifference;
const titleDifference = left.title.localeCompare(right.title);
return titleDifference || left.id.localeCompare(right.id);
}
export function groupSchedulingRequests(
requests: SchedulingRequest[],
actor: SchedulingActor,
now = new Date()
): SchedulingRequestGroups {
const groups: SchedulingRequestGroups = { owned: [], invited: [], other: [] };
for (const request of requests) {
if (schedulingRequestIsOwned(request, actor)) {
groups.owned.push(request);
} else if (schedulingParticipantForActor(request, actor)) {
groups.invited.push(request);
} else {
groups.other.push(request);
}
}
for (const group of Object.values(groups)) {
group.sort((left, right) => compareSchedulingRequests(left, right, actor, now));
}
return groups;
}
export function schedulingRelevantTimestamp(
request: SchedulingRequest,
now = new Date()
): number {
const nowValue = now.getTime();
const futureStarts = request.slots
.map((slot) => Date.parse(slot.start_at))
.filter((value) => Number.isFinite(value) && value >= nowValue)
.sort((left, right) => left - right);
if (futureStarts[0] !== undefined) return futureStarts[0];
const slotEnds = request.slots
.map((slot) => Date.parse(slot.end_at))
.filter(Number.isFinite);
if (slotEnds.length) return Math.max(...slotEnds);
const fallback = Date.parse(request.deadline_at || request.updated_at || request.created_at);
return Number.isFinite(fallback) ? fallback : Number.MAX_SAFE_INTEGER;
}
export function schedulingRequestIsPast(
request: SchedulingRequest,
now = new Date()
): boolean {
if (!request.slots.length) return false;
const slotEnds = request.slots.map((slot) => Date.parse(slot.end_at));
return slotEnds.every((value) => Number.isFinite(value) && value < now.getTime());
}
const SORT_PHASE_ORDER: Record<SchedulingSortPhase, number> = {
unanswered: 0,
answered: 1,
closed: 2,
determined: 3,
past: 4
};

View File

@@ -0,0 +1,218 @@
export const generatedTranslations = {
en: {
"i18n:govoplan-scheduling.add_participant.6cff957d": "Add participant",
"i18n:govoplan-scheduling.add_scheduling_request.3c71be15": "Add scheduling request",
"i18n:govoplan-scheduling.add_slot.9fcff3ed": "Add slot",
"i18n:govoplan-scheduling.answered.e0aafffa": "Answered",
"i18n:govoplan-scheduling.available.7c62a142": "Available",
"i18n:govoplan-scheduling.awaiting_response.ee646ea9": "Awaiting response",
"i18n:govoplan-scheduling.basic_information.d8bc7383": "Basic information",
"i18n:govoplan-scheduling.busy.592a9d16": "Busy",
"i18n:govoplan-scheduling.calendar.adab5090": "Calendar",
"i18n:govoplan-scheduling.calendar_coordination.291ab00a": "Calendar coordination",
"i18n:govoplan-scheduling.configured_calendar.e2e8ebd5": "Configured calendar",
"i18n:govoplan-scheduling.calendar_integration.181ad18b": "Calendar integration",
"i18n:govoplan-scheduling.calendar_integration_requires_the_calendar_module_plus_c.f892cb1e": "Calendar integration requires the Calendar module plus calendar-read, availability-read, and event-write access.",
"i18n:govoplan-scheduling.candidate_availability.9541c4b5": "Candidate availability",
"i18n:govoplan-scheduling.candidate_slots.c414946b": "Candidate slots",
"i18n:govoplan-scheduling.check_free_busy.e9700e00": "Check free/busy",
"i18n:govoplan-scheduling.choose_availability.ac95b8f6": "Choose availability",
"i18n:govoplan-scheduling.choose_availability_for_at_least_one_candidate_slot.28d2111f": "Choose availability for at least one candidate slot.",
"i18n:govoplan-scheduling.close_poll.a6a18916": "Close poll",
"i18n:govoplan-scheduling.close_stops_accepting_new_availability_responses.a1d57519": "Close stops accepting new availability responses.",
"i18n:govoplan-scheduling.closed.88d86b77": "Closed",
"i18n:govoplan-scheduling.create_and_open_scheduling_request.1dbc9345": "Create and open scheduling request",
"i18n:govoplan-scheduling.create_calendar_event.0b87cfcf": "Create calendar event",
"i18n:govoplan-scheduling.create_tentative_holds.51c4744e": "Create tentative holds",
"i18n:govoplan-scheduling.cancellation.319aaae4": "Cancellation",
"i18n:govoplan-scheduling.decision.7f59a1f1": "Decision",
"i18n:govoplan-scheduling.declined.ff59b80f": "Declined",
"i18n:govoplan-scheduling.decide_on_value.196409cd": "Decide on {value0}",
"i18n:govoplan-scheduling.description.55f8ebc8": "Description",
"i18n:govoplan-scheduling.determined.9f23293d": "Determined",
"i18n:govoplan-scheduling.discard.36fff63c": "Discard",
"i18n:govoplan-scheduling.discard_this_unsaved_scheduling_request.4a956be2": "Discard this unsaved scheduling request?",
"i18n:govoplan-scheduling.draft.23d33e22": "Draft",
"i18n:govoplan-scheduling.end.a2bb9d34": "End",
"i18n:govoplan-scheduling.error.7f2f6a15": "Error",
"i18n:govoplan-scheduling.every_candidate_slot_must_end_after_it_starts.47836010": "Every candidate slot must end after it starts.",
"i18n:govoplan-scheduling.failed.09fef5d8": "Failed",
"i18n:govoplan-scheduling.free.75f52718": "Free",
"i18n:govoplan-scheduling.free_busy_checks_each_candidate_slot_against_the_selecte.50f0371a": "Free/busy checks each candidate slot against the selected calendar.",
"i18n:govoplan-scheduling.loading_scheduling_requests.f42be95d": "Loading scheduling requests…",
"i18n:govoplan-scheduling.invitation.6306ef74": "Invitation",
"i18n:govoplan-scheduling.invited.53469df1": "Invited",
"i18n:govoplan-scheduling.location.d219c681": "Location",
"i18n:govoplan-scheduling.managed_scheduling_requests.7a45972f": "Managed scheduling requests",
"i18n:govoplan-scheduling.maybe.56dd8d0b": "Maybe",
"i18n:govoplan-scheduling.my_scheduling_requests.d28ef235": "My scheduling requests",
"i18n:govoplan-scheduling.name.709a2322": "Name",
"i18n:govoplan-scheduling.new_scheduling_request.2080f675": "New scheduling request",
"i18n:govoplan-scheduling.no_notifications_have_been_created.c8d43ca3": "No notifications have been created.",
"i18n:govoplan-scheduling.no_participants.73a89101": "No participants",
"i18n:govoplan-scheduling.no_requests_in_this_group.a63c1b40": "No requests in this group",
"i18n:govoplan-scheduling.no_scheduling_request_selected.ac940664": "No scheduling request selected",
"i18n:govoplan-scheduling.notifications.753a22b2": "Notifications",
"i18n:govoplan-scheduling.open.cf9b7706": "Open",
"i18n:govoplan-scheduling.open_poll.2beac9a7": "Open poll",
"i18n:govoplan-scheduling.open_starts_collecting_availability_responses.c8ec34e5": "Open starts collecting availability responses.",
"i18n:govoplan-scheduling.option_value.3f643dc0": "Option {value0}",
"i18n:govoplan-scheduling.other_scheduling_requests.5cb6eb30": "Other scheduling requests",
"i18n:govoplan-scheduling.participant_email.2cadfd9e": "Participant email",
"i18n:govoplan-scheduling.participant_names_and_statuses_are_hidden_aggregate_counts_r.d811a69a": "Participant names and statuses are hidden. Aggregate counts remain visible.",
"i18n:govoplan-scheduling.share_participant_names_and_response_statuses.df0bf9e0": "Share participant names and response statuses",
"i18n:govoplan-scheduling.when_enabled_participants_can_see_other_participants_names.3ac78361": "When enabled, participants can see other participants' names and response statuses. Email addresses and invitation details remain private.",
"i18n:govoplan-scheduling.participants.cd56e083": "Participants",
"i18n:govoplan-scheduling.past.405c12fb": "Past",
"i18n:govoplan-scheduling.pending.96f608c1": "Pending",
"i18n:govoplan-scheduling.queued.6a599877": "Queued",
"i18n:govoplan-scheduling.refresh_requests.0a3ed7a1": "Refresh requests",
"i18n:govoplan-scheduling.reminder_creates_a_notification_job_for_every_active_par.7ec68797": "Reminder creates a notification job for every active participant.",
"i18n:govoplan-scheduling.remove.e963907d": "Remove",
"i18n:govoplan-scheduling.remove_participant_value.e55f2b70": "Remove participant {value0}",
"i18n:govoplan-scheduling.remove_slot_value.3adc7576": "Remove slot {value0}",
"i18n:govoplan-scheduling.removed.b5e77c5c": "Removed",
"i18n:govoplan-scheduling.reminder.b87a1929": "Reminder",
"i18n:govoplan-scheduling.request_failed.9fcda32c": "Request failed",
"i18n:govoplan-scheduling.required.eed6bfb4": "Required",
"i18n:govoplan-scheduling.requires_calendar_availability_read_access.b48ed91b": "Requires Calendar availability-read access.",
"i18n:govoplan-scheduling.requires_calendar_event_write_access.887b0763": "Requires Calendar event-write access.",
"i18n:govoplan-scheduling.responses_may_be_updated_while_this_request_remains_open.4faecbbe": "Responses may be updated while this request remains open.",
"i18n:govoplan-scheduling.responded.4f218211": "Responded",
"i18n:govoplan-scheduling.save.efc007a3": "Save",
"i18n:govoplan-scheduling.saving.56a2285c": "Saving…",
"i18n:govoplan-scheduling.scheduling_requests.b3c12f4d": "Scheduling requests",
"i18n:govoplan-scheduling.scheduling_request_title_is_required.a27338be": "Scheduling request title is required.",
"i18n:govoplan-scheduling.scheduling_requests_for_me.1d521aba": "Scheduling requests for me",
"i18n:govoplan-scheduling.select_a_calendar.f6af95bb": "Select a calendar",
"i18n:govoplan-scheduling.select_a_calendar_or_turn_off_calendar_integration.cc3652a9": "Select a calendar or turn off Calendar integration.",
"i18n:govoplan-scheduling.send_reminder.cf5eb3bf": "Send reminder",
"i18n:govoplan-scheduling.sending.ceafde86": "Sending",
"i18n:govoplan-scheduling.sent.35f49dcf": "Sent",
"i18n:govoplan-scheduling.skipped.5a000ad7": "Skipped",
"i18n:govoplan-scheduling.start.952f3754": "Start",
"i18n:govoplan-scheduling.status.bae7d5be": "Status",
"i18n:govoplan-scheduling.submit_response.a5f0c053": "Submit response",
"i18n:govoplan-scheduling.tentative_holds_create_one_provisional_calendar_event_pe.ff3f1884": "Tentative holds create one provisional calendar event per candidate slot.",
"i18n:govoplan-scheduling.the_final_event_is_created_only_for_the_selected_slot.e3621252": "The final event is created only for the selected slot.",
"i18n:govoplan-scheduling.the_response_replaces_your_previous_availability_choices.74c16d53": "The response replaces your previous availability choices.",
"i18n:govoplan-scheduling.title.768e0c1c": "Title",
"i18n:govoplan-scheduling.unavailable.2c9c1f79": "Unavailable",
"i18n:govoplan-scheduling.unchecked.1b927dec": "Unchecked",
"i18n:govoplan-scheduling.update_response.346233cf": "Update response",
"i18n:govoplan-scheduling.use_a_calendar_for_availability_checks_tentative_holds_a.20ccc1fa": "Use a calendar for availability checks, tentative holds, and the final event.",
"i18n:govoplan-scheduling.value_participants.e776b092": "{value0} participants",
"i18n:govoplan-scheduling.value_responses.ba17af9a": "{value0} responses",
"i18n:govoplan-scheduling.what_do_these_actions_do.9a9aee0e": "What do these actions do?",
"i18n:govoplan-scheduling.you_can_respond_here_or_use_the_invitation_link_you_rece.1a25fd53": "You can respond here or use the invitation link you received.",
"i18n:govoplan-scheduling.your_response_has_been_recorded.b855088d": "Your response has been recorded."
},
de: {
"i18n:govoplan-scheduling.add_participant.6cff957d": "Teilnehmende Person hinzufügen",
"i18n:govoplan-scheduling.add_scheduling_request.3c71be15": "Terminanfrage hinzufügen",
"i18n:govoplan-scheduling.add_slot.9fcff3ed": "Terminvorschlag hinzufügen",
"i18n:govoplan-scheduling.answered.e0aafffa": "Beantwortet",
"i18n:govoplan-scheduling.available.7c62a142": "Verfügbar",
"i18n:govoplan-scheduling.awaiting_response.ee646ea9": "Antwort ausstehend",
"i18n:govoplan-scheduling.basic_information.d8bc7383": "Grunddaten",
"i18n:govoplan-scheduling.busy.592a9d16": "Belegt",
"i18n:govoplan-scheduling.calendar.adab5090": "Kalender",
"i18n:govoplan-scheduling.calendar_coordination.291ab00a": "Kalenderabgleich",
"i18n:govoplan-scheduling.configured_calendar.e2e8ebd5": "Ausgewählter Kalender",
"i18n:govoplan-scheduling.calendar_integration.181ad18b": "Kalenderintegration",
"i18n:govoplan-scheduling.calendar_integration_requires_the_calendar_module_plus_c.f892cb1e": "Die Kalenderintegration benötigt das Kalendermodul sowie Leserechte für Kalender und Verfügbarkeiten und Schreibrechte für Termine.",
"i18n:govoplan-scheduling.candidate_availability.9541c4b5": "Verfügbarkeit zu den Vorschlägen",
"i18n:govoplan-scheduling.candidate_slots.c414946b": "Terminvorschläge",
"i18n:govoplan-scheduling.check_free_busy.e9700e00": "Frei/Belegt prüfen",
"i18n:govoplan-scheduling.choose_availability.ac95b8f6": "Verfügbarkeit auswählen",
"i18n:govoplan-scheduling.choose_availability_for_at_least_one_candidate_slot.28d2111f": "Wählen Sie für mindestens einen Terminvorschlag eine Verfügbarkeit aus.",
"i18n:govoplan-scheduling.close_poll.a6a18916": "Abstimmung schließen",
"i18n:govoplan-scheduling.close_stops_accepting_new_availability_responses.a1d57519": "Schließen beendet die Annahme neuer Verfügbarkeitsantworten.",
"i18n:govoplan-scheduling.closed.88d86b77": "Geschlossen",
"i18n:govoplan-scheduling.create_and_open_scheduling_request.1dbc9345": "Terminanfrage erstellen und öffnen",
"i18n:govoplan-scheduling.create_calendar_event.0b87cfcf": "Kalendertermin erstellen",
"i18n:govoplan-scheduling.create_tentative_holds.51c4744e": "Vorläufige Reservierungen erstellen",
"i18n:govoplan-scheduling.cancellation.319aaae4": "Stornierung",
"i18n:govoplan-scheduling.decision.7f59a1f1": "Entscheidung",
"i18n:govoplan-scheduling.declined.ff59b80f": "Abgelehnt",
"i18n:govoplan-scheduling.decide_on_value.196409cd": "{value0} als Termin festlegen",
"i18n:govoplan-scheduling.description.55f8ebc8": "Beschreibung",
"i18n:govoplan-scheduling.determined.9f23293d": "Festgelegt",
"i18n:govoplan-scheduling.discard.36fff63c": "Verwerfen",
"i18n:govoplan-scheduling.discard_this_unsaved_scheduling_request.4a956be2": "Diese ungespeicherte Terminanfrage verwerfen?",
"i18n:govoplan-scheduling.draft.23d33e22": "Entwurf",
"i18n:govoplan-scheduling.end.a2bb9d34": "Ende",
"i18n:govoplan-scheduling.error.7f2f6a15": "Fehler",
"i18n:govoplan-scheduling.every_candidate_slot_must_end_after_it_starts.47836010": "Jeder Terminvorschlag muss nach seinem Beginn enden.",
"i18n:govoplan-scheduling.failed.09fef5d8": "Fehlgeschlagen",
"i18n:govoplan-scheduling.free.75f52718": "Frei",
"i18n:govoplan-scheduling.free_busy_checks_each_candidate_slot_against_the_selecte.50f0371a": "Frei/Belegt prüft jeden Terminvorschlag gegen den ausgewählten Kalender.",
"i18n:govoplan-scheduling.loading_scheduling_requests.f42be95d": "Terminanfragen werden geladen …",
"i18n:govoplan-scheduling.invitation.6306ef74": "Einladung",
"i18n:govoplan-scheduling.invited.53469df1": "Eingeladen",
"i18n:govoplan-scheduling.location.d219c681": "Ort",
"i18n:govoplan-scheduling.managed_scheduling_requests.7a45972f": "Verwaltete Terminanfragen",
"i18n:govoplan-scheduling.maybe.56dd8d0b": "Vielleicht",
"i18n:govoplan-scheduling.my_scheduling_requests.d28ef235": "Meine Terminanfragen",
"i18n:govoplan-scheduling.name.709a2322": "Name",
"i18n:govoplan-scheduling.new_scheduling_request.2080f675": "Neue Terminanfrage",
"i18n:govoplan-scheduling.no_notifications_have_been_created.c8d43ca3": "Es wurden noch keine Benachrichtigungen erstellt.",
"i18n:govoplan-scheduling.no_participants.73a89101": "Keine Teilnehmenden",
"i18n:govoplan-scheduling.no_requests_in_this_group.a63c1b40": "Keine Anfragen in dieser Gruppe",
"i18n:govoplan-scheduling.no_scheduling_request_selected.ac940664": "Keine Terminanfrage ausgewählt",
"i18n:govoplan-scheduling.notifications.753a22b2": "Benachrichtigungen",
"i18n:govoplan-scheduling.open.cf9b7706": "Offen",
"i18n:govoplan-scheduling.open_poll.2beac9a7": "Abstimmung öffnen",
"i18n:govoplan-scheduling.open_starts_collecting_availability_responses.c8ec34e5": "Öffnen startet die Erfassung von Verfügbarkeitsantworten.",
"i18n:govoplan-scheduling.option_value.3f643dc0": "Vorschlag {value0}",
"i18n:govoplan-scheduling.other_scheduling_requests.5cb6eb30": "Andere Terminanfragen",
"i18n:govoplan-scheduling.participant_email.2cadfd9e": "E-Mail der teilnehmenden Person",
"i18n:govoplan-scheduling.participant_names_and_statuses_are_hidden_aggregate_counts_r.d811a69a": "Namen und Antwortstatus der Teilnehmenden sind ausgeblendet. Zusammengefasste Anzahlen bleiben sichtbar.",
"i18n:govoplan-scheduling.share_participant_names_and_response_statuses.df0bf9e0": "Namen und Antwortstatus der Teilnehmenden freigeben",
"i18n:govoplan-scheduling.when_enabled_participants_can_see_other_participants_names.3ac78361": "Wenn aktiviert, sehen Teilnehmende die Namen und Antwortstatus anderer Teilnehmender. E-Mail-Adressen und Einladungsdetails bleiben privat.",
"i18n:govoplan-scheduling.participants.cd56e083": "Teilnehmende",
"i18n:govoplan-scheduling.past.405c12fb": "Vergangen",
"i18n:govoplan-scheduling.pending.96f608c1": "Ausstehend",
"i18n:govoplan-scheduling.queued.6a599877": "Eingereiht",
"i18n:govoplan-scheduling.refresh_requests.0a3ed7a1": "Anfragen aktualisieren",
"i18n:govoplan-scheduling.reminder_creates_a_notification_job_for_every_active_par.7ec68797": "Erinnern erstellt für jede aktive teilnehmende Person einen Benachrichtigungsauftrag.",
"i18n:govoplan-scheduling.remove.e963907d": "Entfernen",
"i18n:govoplan-scheduling.remove_participant_value.e55f2b70": "Teilnehmende Person {value0} entfernen",
"i18n:govoplan-scheduling.remove_slot_value.3adc7576": "Terminvorschlag {value0} entfernen",
"i18n:govoplan-scheduling.removed.b5e77c5c": "Entfernt",
"i18n:govoplan-scheduling.reminder.b87a1929": "Erinnerung",
"i18n:govoplan-scheduling.request_failed.9fcda32c": "Anfrage fehlgeschlagen",
"i18n:govoplan-scheduling.required.eed6bfb4": "Erforderlich",
"i18n:govoplan-scheduling.requires_calendar_availability_read_access.b48ed91b": "Erfordert Leserechte für Kalenderverfügbarkeiten.",
"i18n:govoplan-scheduling.requires_calendar_event_write_access.887b0763": "Erfordert Schreibrechte für Kalendertermine.",
"i18n:govoplan-scheduling.responses_may_be_updated_while_this_request_remains_open.4faecbbe": "Antworten können aktualisiert werden, solange diese Anfrage offen ist.",
"i18n:govoplan-scheduling.responded.4f218211": "Geantwortet",
"i18n:govoplan-scheduling.save.efc007a3": "Speichern",
"i18n:govoplan-scheduling.saving.56a2285c": "Wird gespeichert …",
"i18n:govoplan-scheduling.scheduling_requests.b3c12f4d": "Terminanfragen",
"i18n:govoplan-scheduling.scheduling_request_title_is_required.a27338be": "Für die Terminanfrage ist ein Titel erforderlich.",
"i18n:govoplan-scheduling.scheduling_requests_for_me.1d521aba": "Terminanfragen an mich",
"i18n:govoplan-scheduling.select_a_calendar.f6af95bb": "Kalender auswählen",
"i18n:govoplan-scheduling.select_a_calendar_or_turn_off_calendar_integration.cc3652a9": "Wählen Sie einen Kalender aus oder schalten Sie die Kalenderintegration aus.",
"i18n:govoplan-scheduling.send_reminder.cf5eb3bf": "Erinnerung senden",
"i18n:govoplan-scheduling.sending.ceafde86": "Wird gesendet",
"i18n:govoplan-scheduling.sent.35f49dcf": "Gesendet",
"i18n:govoplan-scheduling.skipped.5a000ad7": "Übersprungen",
"i18n:govoplan-scheduling.start.952f3754": "Beginn",
"i18n:govoplan-scheduling.status.bae7d5be": "Status",
"i18n:govoplan-scheduling.submit_response.a5f0c053": "Antwort senden",
"i18n:govoplan-scheduling.tentative_holds_create_one_provisional_calendar_event_pe.ff3f1884": "Vorläufige Reservierungen erstellen je Terminvorschlag einen provisorischen Kalendereintrag.",
"i18n:govoplan-scheduling.the_final_event_is_created_only_for_the_selected_slot.e3621252": "Der endgültige Kalendereintrag wird nur für den ausgewählten Termin erstellt.",
"i18n:govoplan-scheduling.the_response_replaces_your_previous_availability_choices.74c16d53": "Die Antwort ersetzt Ihre vorherige Verfügbarkeitsauswahl.",
"i18n:govoplan-scheduling.title.768e0c1c": "Titel",
"i18n:govoplan-scheduling.unavailable.2c9c1f79": "Nicht verfügbar",
"i18n:govoplan-scheduling.unchecked.1b927dec": "Nicht geprüft",
"i18n:govoplan-scheduling.update_response.346233cf": "Antwort aktualisieren",
"i18n:govoplan-scheduling.use_a_calendar_for_availability_checks_tentative_holds_a.20ccc1fa": "Einen Kalender für Verfügbarkeitsprüfungen, vorläufige Reservierungen und den endgültigen Termin verwenden.",
"i18n:govoplan-scheduling.value_participants.e776b092": "{value0} Teilnehmende",
"i18n:govoplan-scheduling.value_responses.ba17af9a": "{value0} Antworten",
"i18n:govoplan-scheduling.what_do_these_actions_do.9a9aee0e": "Was bewirken diese Aktionen?",
"i18n:govoplan-scheduling.you_can_respond_here_or_use_the_invitation_link_you_rece.1a25fd53": "Sie können hier oder über den erhaltenen Einladungslink antworten.",
"i18n:govoplan-scheduling.your_response_has_been_recorded.b855088d": "Ihre Antwort wurde gespeichert."
}
};

2
webui/src/index.ts Normal file
View File

@@ -0,0 +1,2 @@
export { schedulingModule as default, schedulingModule } from "./module";
export * from "./api/scheduling";

23
webui/src/module.ts Normal file
View File

@@ -0,0 +1,23 @@
import { createElement, lazy } from "react";
import type { PlatformWebModule } from "@govoplan/core-webui";
import { generatedTranslations } from "./i18n/generatedTranslations";
import "./styles/scheduling.css";
const SchedulingPage = lazy(() => import("./features/scheduling/SchedulingPage"));
const scheduleRead = ["scheduling:schedule:read"];
export const schedulingModule: PlatformWebModule = {
id: "scheduling",
label: "Scheduling",
version: "1.0.0",
dependencies: ["poll"],
optionalDependencies: ["calendar", "mail", "notifications", "workflow", "appointments", "addresses"],
translations: generatedTranslations,
navItems: [{ to: "/scheduling", label: "Scheduling", iconName: "calendar-clock", anyOf: scheduleRead, order: 56 }],
routes: [
{ path: "/scheduling", anyOf: scheduleRead, order: 56, render: ({ settings, auth }) => createElement(SchedulingPage, { settings, auth }) }
]
};
export default schedulingModule;

View File

@@ -0,0 +1,434 @@
.scheduling-page {
box-sizing: border-box;
height: calc(100vh - 115px);
min-height: 0;
overflow: hidden;
color: var(--text);
background: var(--bg);
}
.scheduling-page *,
.scheduling-page *::before,
.scheduling-page *::after {
box-sizing: border-box;
}
.scheduling-workspace,
.scheduling-full-editor {
width: 100%;
height: 100%;
min-width: 0;
min-height: 0;
display: flex;
flex-direction: column;
overflow: hidden;
border: var(--border-line);
background: var(--bg);
}
.scheduling-page-header {
min-height: 58px;
flex: 0 0 auto;
display: flex;
align-items: center;
justify-content: space-between;
gap: 12px;
padding: 10px 14px;
border-bottom: var(--border-line);
background: var(--panel-header);
}
.scheduling-page-title,
.scheduling-page-actions,
.scheduling-card-actions,
.scheduling-actions,
.scheduling-status-row {
display: flex;
align-items: center;
gap: 8px;
}
.scheduling-page-title {
min-width: 0;
}
.scheduling-page-title > div {
min-width: 0;
}
.scheduling-page-title h1 {
margin: 0;
color: var(--text-strong);
font-size: 19px;
}
.scheduling-page-title p {
margin: 3px 0 0;
color: var(--muted);
font-size: 12px;
}
.scheduling-page-actions,
.scheduling-card-actions,
.scheduling-actions {
flex-wrap: wrap;
justify-content: flex-end;
}
.scheduling-page-actions {
margin-left: auto;
}
.scheduling-page-actions .btn,
.scheduling-card-actions .btn,
.scheduling-actions .btn,
.scheduling-response-card + .btn {
min-height: 34px;
display: inline-flex;
align-items: center;
gap: 6px;
}
.scheduling-icon-button.btn {
width: 34px;
min-width: 34px;
height: 34px;
min-height: 34px;
padding: 0;
justify-content: center;
}
.scheduling-alert,
.scheduling-success {
margin: 10px 14px 0;
padding: 9px 11px;
border: var(--border-line);
border-radius: 7px;
}
.scheduling-alert {
border-color: var(--danger);
color: var(--danger);
background: var(--danger-soft);
}
.scheduling-success {
border-color: var(--success);
color: var(--success);
background: color-mix(in srgb, var(--success) 10%, var(--panel));
}
.scheduling-detail,
.scheduling-editor-scroll {
min-width: 0;
min-height: 0;
overflow: auto;
padding: 14px;
}
.scheduling-detail,
.scheduling-editor-scroll {
display: grid;
align-content: start;
gap: 12px;
}
.scheduling-request-groups {
display: grid;
grid-template-columns: repeat(auto-fit, minmax(280px, 1fr));
gap: 12px;
}
.scheduling-list-group {
min-height: 52px;
max-height: 270px;
overflow: auto;
}
.scheduling-list-item {
width: 100%;
min-height: 50px;
display: grid;
grid-template-columns: minmax(0, 1fr) auto;
gap: 10px;
align-items: center;
margin: 0 0 4px;
padding: 8px 10px;
border: 1px solid transparent;
border-radius: 7px;
color: var(--text);
background: transparent;
text-align: left;
cursor: pointer;
}
.scheduling-list-item:hover {
background: var(--hover-bg);
}
.scheduling-list-item.is-selected {
border-color: color-mix(in srgb, var(--accent) 45%, transparent);
background: color-mix(in srgb, var(--accent) 10%, var(--panel));
}
.scheduling-list-item > span {
min-width: 0;
display: grid;
gap: 3px;
}
.scheduling-list-item strong,
.scheduling-list-item small,
.scheduling-compact-row span {
min-width: 0;
overflow: hidden;
text-overflow: ellipsis;
white-space: nowrap;
}
.scheduling-list-item small,
.scheduling-note,
.scheduling-list-empty,
.scheduling-compact-row small {
color: var(--muted);
font-size: 12px;
}
.scheduling-list-status {
max-width: 120px;
padding: 3px 7px;
border-radius: 999px;
background: var(--panel-soft);
font-weight: 700;
}
.scheduling-list-empty {
margin: 3px 0 8px;
}
.scheduling-status-row {
flex-wrap: wrap;
}
.scheduling-status {
padding: 4px 8px;
border-radius: 999px;
color: var(--text-strong);
background: var(--panel-soft);
font-size: 12px;
font-weight: 800;
}
.scheduling-status-collecting,
.scheduling-status-handed_off {
background: color-mix(in srgb, var(--accent) 18%, transparent);
}
.scheduling-slot-title {
min-width: 0;
display: grid;
justify-items: start;
}
.scheduling-freebusy {
display: inline-block;
margin-top: 3px;
padding: 2px 6px;
border-radius: 5px;
color: var(--muted);
background: var(--panel-soft);
font-size: 11px;
font-weight: 700;
}
.scheduling-freebusy.free {
color: var(--success);
}
.scheduling-freebusy.busy,
.scheduling-freebusy.error {
color: var(--danger);
}
.scheduling-columns {
display: grid;
grid-template-columns: repeat(2, minmax(0, 1fr));
gap: 12px;
}
.scheduling-compact-row {
min-height: 36px;
display: grid;
grid-template-columns: minmax(0, 1fr) auto;
gap: 8px;
align-items: center;
border-bottom: var(--border-line);
}
.scheduling-compact-row:last-child {
border-bottom: 0;
}
.scheduling-response-card {
display: grid;
gap: 12px;
}
.scheduling-response-card > p {
margin: 0;
}
.scheduling-response-grid {
display: grid;
gap: 6px;
}
.scheduling-response-grid label {
min-width: 0;
display: grid;
grid-template-columns: minmax(220px, 1fr) minmax(160px, 240px);
gap: 12px;
align-items: center;
padding: 8px 0;
border-bottom: var(--border-line);
}
.scheduling-response-grid label:last-child {
border-bottom: 0;
}
.scheduling-response-grid label > span {
min-width: 0;
display: grid;
gap: 3px;
}
.scheduling-response-grid small {
color: var(--muted);
}
.scheduling-response-grid select,
.scheduling-field input,
.scheduling-field textarea,
.scheduling-grid-input {
width: 100%;
min-height: 36px;
padding: 7px 9px;
border: var(--border-line);
border-radius: 6px;
color: var(--text);
background: var(--input-bg);
font: inherit;
}
.scheduling-action-help {
margin: 0;
}
.scheduling-empty {
padding: 28px;
color: var(--muted);
text-align: center;
}
.scheduling-editor-page {
background: var(--panel);
}
.scheduling-editor-layout {
min-width: 0;
min-height: 0;
flex: 1 1 auto;
display: grid;
grid-template-columns: 198px minmax(0, 1fr);
overflow: hidden;
}
.scheduling-create-subnav {
min-height: 0;
}
.scheduling-create-section {
min-width: 0;
scroll-margin-top: 14px;
}
.scheduling-form-grid {
display: grid;
grid-template-columns: repeat(2, minmax(0, 1fr));
gap: 12px;
}
.scheduling-field-wide {
grid-column: 1 / -1;
}
.scheduling-field {
display: grid;
gap: 5px;
}
.scheduling-field > span {
color: var(--muted);
font-size: 12px;
font-weight: 800;
}
.scheduling-capability-note {
margin: 10px 0 0;
color: var(--muted);
font-size: 12px;
}
.scheduling-selected-calendar {
max-width: 520px;
}
@media (max-width: 900px) {
.scheduling-editor-layout {
grid-template-columns: minmax(0, 1fr);
}
}
@media (max-width: 820px) {
.scheduling-page {
height: auto;
min-height: calc(100vh - 115px);
overflow: auto;
}
.scheduling-workspace,
.scheduling-full-editor,
.scheduling-editor-layout,
.scheduling-detail,
.scheduling-editor-scroll {
height: auto;
overflow: visible;
}
.scheduling-columns,
.scheduling-form-grid {
grid-template-columns: minmax(0, 1fr);
}
.scheduling-page-header {
align-items: flex-start;
flex-wrap: wrap;
}
.scheduling-page-actions,
.scheduling-card-actions,
.scheduling-actions {
width: 100%;
}
.scheduling-page-actions .btn:last-child,
.scheduling-card-actions .btn:last-child,
.scheduling-actions .btn:last-child {
margin-left: auto;
}
.scheduling-response-grid label {
grid-template-columns: minmax(0, 1fr);
}
}

13
webui/src/vite-env.d.ts vendored Normal file
View File

@@ -0,0 +1,13 @@
interface ImportMetaEnv {
readonly VITE_API_BASE_URL?: string;
readonly VITE_CSRF_COOKIE_NAME?: string;
}
interface ImportMeta {
readonly env: ImportMetaEnv;
}
declare module "virtual:govoplan-installed-modules" {
const modules: any[];
export default modules;
}

View File

@@ -0,0 +1,124 @@
import assert from "node:assert/strict";
import test from "node:test";
import type { SchedulingRequest } from "../src/api/scheduling.ts";
import {
groupSchedulingRequests,
schedulingSortPhase,
type SchedulingActor
} from "../src/features/scheduling/schedulingViewModel.ts";
const now = new Date("2026-07-20T10:00:00Z");
const actor: SchedulingActor = {
accountId: "account-1",
membershipId: "membership-1",
email: "person@example.test"
};
function request(
id: string,
options: {
organizer?: string;
participantStatus?: string;
status?: SchedulingRequest["status"];
start?: string;
end?: string;
} = {}
): SchedulingRequest {
return {
id,
tenant_id: "tenant-1",
title: id,
timezone: "UTC",
status: options.status ?? "collecting",
organizer_user_id: options.organizer ?? "organizer-elsewhere",
allow_external_participants: true,
allow_participant_updates: true,
result_visibility: "after_close",
participant_visibility: "aggregates_only",
effective_participant_visibility: "aggregates_only",
participant_aggregate: {
total: options.participantStatus ? 1 : 0,
status_counts: options.participantStatus ? { [options.participantStatus]: 1 } : {}
},
participant_visibility_decision: {
requested_visibility: "aggregates_only",
effective_visibility: "aggregates_only",
policy_applied: false,
source_path: [],
details: {}
},
calendar_integration_enabled: false,
calendar_freebusy_enabled: false,
calendar_hold_enabled: false,
create_calendar_event_on_decision: false,
created_at: "2026-07-01T00:00:00Z",
updated_at: "2026-07-01T00:00:00Z",
metadata: {},
slots: [{
id: `slot-${id}`,
label: id,
start_at: options.start ?? "2026-07-21T09:00:00Z",
end_at: options.end ?? "2026-07-21T10:00:00Z",
timezone: "UTC",
position: 0,
freebusy_conflicts: [],
metadata: {}
}],
participants: options.participantStatus ? [{
id: `participant-${id}`,
respondent_id: "membership-1",
email: "person@example.test",
participant_type: "internal",
required: true,
status: options.participantStatus,
metadata: {}
}] : []
};
}
test("groups owned, invited, and administrator-only requests without hiding any", () => {
const groups = groupSchedulingRequests([
request("managed"),
request("mine", { organizer: "account-1" }),
request("invited", { participantStatus: "invited" })
], actor, now);
assert.deepEqual(groups.owned.map((item) => item.id), ["mine"]);
assert.deepEqual(groups.invited.map((item) => item.id), ["invited"]);
assert.deepEqual(groups.other.map((item) => item.id), ["managed"]);
});
test("keeps an organizer's active request in the open phase even if they also responded", () => {
const owned = request("mine-and-invited", {
organizer: "account-1",
participantStatus: "responded"
});
assert.equal(schedulingSortPhase(owned, actor, now), "unanswered");
});
test("orders unanswered by nearest slot before answered, closed, determined, and past", () => {
const groups = groupSchedulingRequests([
request("past", {
participantStatus: "invited",
start: "2026-07-18T09:00:00Z",
end: "2026-07-18T10:00:00Z"
}),
request("determined", { participantStatus: "invited", status: "decided" }),
request("closed", { participantStatus: "invited", status: "closed" }),
request("answered", { participantStatus: "responded" }),
request("later", { participantStatus: "invited", start: "2026-07-23T09:00:00Z" }),
request("nearer", { participantStatus: "invited", start: "2026-07-21T09:00:00Z" })
], actor, now);
assert.deepEqual(groups.invited.map((item) => item.id), [
"nearer",
"later",
"answered",
"closed",
"determined",
"past"
]);
assert.equal(schedulingSortPhase(groups.invited[0], actor, now), "unanswered");
assert.equal(schedulingSortPhase(groups.invited.at(-1)!, actor, now), "past");
});

31
webui/tsconfig.json Normal file
View File

@@ -0,0 +1,31 @@
{
"compilerOptions": {
"target": "ES2020",
"useDefineForClassFields": true,
"lib": ["DOM", "DOM.Iterable", "ES2020"],
"allowJs": false,
"skipLibCheck": true,
"esModuleInterop": true,
"allowSyntheticDefaultImports": true,
"strict": true,
"noUnusedLocals": true,
"noUnusedParameters": true,
"forceConsistentCasingInFileNames": true,
"module": "ESNext",
"moduleResolution": "Bundler",
"resolveJsonModule": true,
"isolatedModules": true,
"noEmit": true,
"jsx": "react-jsx",
"preserveSymlinks": true,
"baseUrl": ".",
"paths": {
"@govoplan/core-webui": ["../../govoplan-core/webui/src/index.ts"],
"@govoplan/core-webui/*": ["../../govoplan-core/webui/src/*"],
"lucide-react": ["../../govoplan-core/webui/node_modules/lucide-react/dist/lucide-react.d.ts"],
"react": ["../../govoplan-core/webui/node_modules/@types/react/index.d.ts"],
"react/jsx-runtime": ["../../govoplan-core/webui/node_modules/@types/react/jsx-runtime.d.ts"]
}
},
"include": ["src"]
}