7 Commits
v0.1.7 ... main

28 changed files with 3838 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 Scheduling
<!-- govoplan-repository-type:start -->
**Repository type:** module (domain).
<!-- govoplan-repository-type:end -->
GovOPlaN Scheduling owns meeting scheduling and `Terminfindung`: finding GovOPlaN Scheduling owns meeting scheduling and `Terminfindung`: finding
suitable times across people, resources, calendars, constraints, and scheduling suitable times across people, resources, calendars, constraints, and scheduling
polls. polls.
This repository is currently a tag-only scaffold. It should gain package This repository is initialized as a discoverable module seed. It exposes the
metadata, a backend manifest, and a WebUI package together when the first module manifest, permission surface, role templates, and documentation metadata
implementation slice is designed. before runtime APIs, database models, migrations, and WebUI routes are
introduced.
The core boundary decision register is in The core boundary decision register is in
`/mnt/DATA/git/govoplan-core/docs/MODULE_ARCHITECTURE.md`. `/mnt/DATA/git/govoplan-core/docs/MODULE_ARCHITECTURE.md`.
@@ -15,7 +20,7 @@ The core boundary decision register is in
Scheduling owns: Scheduling owns:
- meeting scheduling polls and proposals - meeting scheduling polls and proposals built on `govoplan-poll`
- participant availability collection - participant availability collection
- time-window and resource constraints - time-window and resource constraints
- candidate-slot ranking and conflict explanation - candidate-slot ranking and conflict explanation
@@ -64,24 +69,52 @@ unless a configured process requires longer evidence retention.
- `scheduling.decisionHandoff` - `scheduling.decisionHandoff`
- `scheduling.portalParticipation` - `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 ## 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-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-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-mail` and `govoplan-notifications`: invitations, reminders, confirmations
- `govoplan-portal`: external participant scheduling flows - `govoplan-portal`: external participant scheduling flows
- `govoplan-workflow` and `govoplan-tasks`: follow-up work after a time is selected - `govoplan-workflow` and `govoplan-tasks`: follow-up work after a time is selected
## First Package Scaffold Decision ## First Package Scaffold Decision
The first scaffold should include both backend and WebUI package metadata once The first backend implementation slice adds runtime APIs and storage around
implementation starts: poll-backed scheduling requests:
- backend manifest, permissions, DTOs, and APIs for internal polls - scheduling request, candidate slot, and participant storage
- WebUI route contribution for poll creation and response collection - automatic `govoplan-poll` availability poll creation
- capability contracts for calendar free/busy, access/IDM lookup, - signed poll invitations for internal or external participants
mail/notification sending, portal participation links, appointment handoff, - request lifecycle APIs: draft, collecting, closed, decided, handed off, cancelled
and workflow/task follow-up - 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. 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.8"
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.8",
"govoplan-poll>=0.1.8",
]
[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.8"

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,143 @@
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)
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,182 @@
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.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_scheduling.backend.db import models as scheduling_models # noqa: F401 - populate Scheduling ORM metadata
MODULE_ID = "scheduling"
MODULE_NAME = "Scheduling"
MODULE_VERSION = "0.1.8"
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", "portal", "workflow", "tasks", "idm", "organizations", "addresses"),
optional_capabilities=(CAPABILITY_AUTH_PRINCIPAL_RESOLVER, CAPABILITY_AUTH_PERMISSION_EVALUATOR),
provides_interfaces=(
ModuleInterfaceProvider(name="scheduling.candidate_slots", version="0.1.8"),
ModuleInterfaceProvider(name="scheduling.decision_handoff", version="0.1.8"),
),
requires_interfaces=(
ModuleInterfaceRequirement(name="poll.availability_matrix", version_min="0.1.8", version_max_exclusive="0.2.0"),
ModuleInterfaceRequirement(name="poll.workflow_context", version_min="0.1.8", 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),
),
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,156 @@
"""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"
def upgrade() -> None:
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,74 @@
"""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
def upgrade() -> None:
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 @@
from __future__ import annotations

View File

@@ -0,0 +1,372 @@
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.db.session import get_session
from govoplan_poll.backend.schemas import PollResultSummaryResponse
from govoplan_scheduling.backend.manifest import READ_SCOPE, WRITE_SCOPE
from govoplan_scheduling.backend.schemas import (
SchedulingAddressLookupCandidate,
SchedulingAddressLookupResponse,
SchedulingCalendarActionResponse,
SchedulingDecisionRequest,
SchedulingNotificationCreateRequest,
SchedulingNotificationListResponse,
SchedulingNotificationResponse,
SchedulingRequestCreateRequest,
SchedulingRequestListResponse,
SchedulingRequestResponse,
SchedulingRequestUpdateRequest,
SchedulingStatusResponse,
SchedulingSummaryResponse,
)
from govoplan_scheduling.backend.runtime import get_registry
from govoplan_scheduling.backend.service import (
SchedulingError,
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_request,
list_scheduling_notifications,
list_scheduling_requests,
open_scheduling_request,
scheduling_notification_response,
scheduling_request_response,
scheduling_request_summary,
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 _scheduling_http_error(exc: SchedulingError) -> HTTPException:
if str(exc) == "Scheduling request not found":
return HTTPException(status_code=status.HTTP_404_NOT_FOUND, detail=str(exc))
return HTTPException(status_code=status.HTTP_400_BAD_REQUEST, detail=str(exc))
def _request_response(request, *, invitation_tokens: dict[str, str] | None = None) -> SchedulingRequestResponse:
return SchedulingRequestResponse.model_validate(
scheduling_request_response(request, invitation_tokens=invitation_tokens)
)
@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_scheduling_requests(session, tenant_id=principal.tenant_id, status=status_filter)
return SchedulingRequestListResponse(requests=[_request_response(request) for request in requests])
@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
return _request_response(request, invitation_tokens=invitation_tokens)
@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:
return _request_response(get_scheduling_request(session, tenant_id=principal.tenant_id, request_id=request_id))
except SchedulingError as exc:
raise _scheduling_http_error(exc) from exc
@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:
return _request_response(
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
@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
return SchedulingStatusResponse(request=_request_response(request))
@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
return SchedulingStatusResponse(request=_request_response(request))
@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,
)
except SchedulingError as exc:
raise _scheduling_http_error(exc) from exc
return SchedulingStatusResponse(request=_request_response(request))
@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)
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
return SchedulingCalendarActionResponse(
request=_request_response(request),
updated_slot_ids=[slot.id for slot in request.slots if slot.freebusy_checked_at is not None],
warnings=warnings,
)
@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)
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
return SchedulingCalendarActionResponse(
request=_request_response(request),
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,
)
@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)
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
return SchedulingCalendarActionResponse(
request=_request_response(request),
created_event_ids=[event_id] if event_id else [],
warnings=warnings,
)
@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
return SchedulingStatusResponse(request=_request_response(request))
@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_scheduling_request(session, tenant_id=principal.tenant_id, request_id=request_id)
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
return SchedulingSummaryResponse(
request=_request_response(request),
poll_summary=PollResultSummaryResponse.model_validate(summary),
)
@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_scheduling_notifications(
session,
tenant_id=principal.tenant_id,
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
return SchedulingNotificationListResponse(
notifications=[
SchedulingNotificationResponse.model_validate(scheduling_notification_response(notification))
for notification in notifications
]
)

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,224 @@
from __future__ import annotations
from datetime import datetime
from typing import Any, Literal
from pydantic import BaseModel, ConfigDict, Field, model_validator
from govoplan_poll.backend.schemas import PollResultSummaryResponse
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"]
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: datetime
end_at: datetime
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)
@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 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"
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)
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
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
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 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
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 SchedulingSummaryResponse(BaseModel):
request: SchedulingRequestResponse
poll_summary: PollResultSummaryResponse
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)

View File

@@ -0,0 +1,966 @@
from __future__ import annotations
from datetime import datetime, timezone
from typing import Any
from sqlalchemy.orm import Session
from govoplan_core.core.notifications import NotificationDispatchRequest, notification_dispatch_provider
from govoplan_core.db.base import utcnow
from govoplan_poll.backend.schemas import PollCreateRequest, PollDecisionRequest, PollInvitationCreateRequest, PollOptionInput
from govoplan_poll.backend.db.models import PollResponse
from govoplan_poll.backend.service import (
PollError,
close_poll,
create_poll,
create_poll_invitation,
decide_poll,
get_poll,
open_poll,
poll_result_summary_by_id,
)
from govoplan_scheduling.backend.db.models import SchedulingCandidateSlot, SchedulingNotification, SchedulingParticipant, SchedulingRequest
from govoplan_scheduling.backend.schemas import (
SchedulingDecisionRequest,
SchedulingRequestCreateRequest,
SchedulingRequestUpdateRequest,
)
from govoplan_scheduling.backend.runtime import get_registry
class SchedulingError(ValueError):
pass
WORKFLOW_DRAFT = "draft"
WORKFLOW_COLLECTING = "collecting_availability"
WORKFLOW_CLOSED = "availability_closed"
WORKFLOW_DECIDED = "slot_decided"
WORKFLOW_HANDED_OFF = "handed_off"
WORKFLOW_CANCELLED = "cancelled"
NOTIFICATION_KINDS = {"invitation", "reminder", "decision", "cancellation"}
def response_datetime(value: datetime | None) -> datetime | None:
if value is None:
return None
if value.tzinfo is None:
return value.replace(tzinfo=timezone.utc)
return value.astimezone(timezone.utc)
def _jsonable(value: Any) -> Any:
if isinstance(value, datetime):
normalized = response_datetime(value)
return normalized.isoformat() if normalized else None
if isinstance(value, dict):
return {str(key): _jsonable(item) for key, item in value.items()}
if isinstance(value, list):
return [_jsonable(item) for item in value]
return value
def _now() -> datetime:
return utcnow()
def _slot_label(start_at: datetime, end_at: datetime, *, timezone_name: str) -> str:
return f"{response_datetime(start_at).isoformat()} - {response_datetime(end_at).isoformat()} ({timezone_name})"
def _workflow_steps(state: str) -> list[dict[str, Any]]:
order = [
("draft", "Draft"),
("collecting_availability", "Collect availability"),
("availability_closed", "Close poll"),
("slot_decided", "Choose slot"),
("handed_off", "Hand off"),
]
active_index = next((index for index, (step_id, _label) in enumerate(order) if step_id == state), 0)
steps: list[dict[str, Any]] = []
for index, (step_id, label) in enumerate(order):
if step_id == state:
status = "active"
elif index < active_index:
status = "done"
else:
status = "pending"
steps.append({"id": step_id, "label": label, "status": status})
if state == WORKFLOW_CANCELLED:
steps.append({"id": "cancelled", "label": "Cancelled", "status": "active"})
return steps
def _poll_status_for_request(status: str) -> str:
if status == "collecting":
return "open"
return "draft"
def _active_slots(request: SchedulingRequest) -> list[SchedulingCandidateSlot]:
return [slot for slot in request.slots if slot.deleted_at is None]
def _active_participants(request: SchedulingRequest) -> list[SchedulingParticipant]:
return [participant for participant in request.participants if participant.deleted_at is None]
def _poll_option_inputs(request: SchedulingRequest) -> list[PollOptionInput]:
options: list[PollOptionInput] = []
for slot in _active_slots(request):
options.append(
PollOptionInput(
key=f"slot-{slot.position + 1}",
label=slot.label,
description=slot.description,
value={
"slot_id": slot.id,
"start_at": response_datetime(slot.start_at).isoformat(),
"end_at": response_datetime(slot.end_at).isoformat(),
"timezone": slot.timezone,
"location": slot.location,
},
metadata=slot.metadata_ or {},
)
)
return options
def _poll_workflow_state(request: SchedulingRequest) -> str:
return {
"draft": WORKFLOW_DRAFT,
"collecting": WORKFLOW_COLLECTING,
"closed": WORKFLOW_CLOSED,
"decided": WORKFLOW_DECIDED,
"handed_off": WORKFLOW_HANDED_OFF,
"cancelled": WORKFLOW_CANCELLED,
}.get(request.status, WORKFLOW_DRAFT)
def _sync_poll_workflow(session: Session, *, tenant_id: str, request: SchedulingRequest) -> None:
if request.poll_id is None:
return
poll = get_poll(session, tenant_id=tenant_id, poll_id=request.poll_id)
state = _poll_workflow_state(request)
poll.workflow_state = state
poll.workflow_steps = _workflow_steps(state)
poll.context_module = "scheduling"
poll.context_resource_type = "scheduling_request"
poll.context_resource_id = request.id
def _set_calendar_preferences(request: SchedulingRequest, payload) -> None:
calendar = payload.calendar
request.calendar_integration_enabled = calendar.enabled
request.calendar_id = calendar.calendar_id
request.calendar_freebusy_enabled = calendar.freebusy_enabled
request.calendar_hold_enabled = calendar.tentative_holds_enabled
request.create_calendar_event_on_decision = calendar.create_event_on_decision
if not calendar.enabled:
request.calendar_freebusy_enabled = False
request.calendar_hold_enabled = False
request.create_calendar_event_on_decision = False
def _calendar_api():
try:
from govoplan_calendar.backend.schemas import CalendarEventCreateRequest
from govoplan_calendar.backend.service import CalendarError, create_event, list_freebusy
except ModuleNotFoundError as exc:
raise SchedulingError("Calendar module is not installed") from exc
return CalendarEventCreateRequest, CalendarError, create_event, list_freebusy
def _require_calendar_enabled(request: SchedulingRequest) -> None:
if not request.calendar_integration_enabled:
raise SchedulingError("Calendar integration is not enabled for this scheduling request")
if not request.calendar_id:
raise SchedulingError("Scheduling request has no target calendar")
def _attendees_for_calendar_event(request: SchedulingRequest) -> list[dict[str, Any]]:
attendees: list[dict[str, Any]] = []
for participant in _active_participants(request):
if not participant.email and not participant.display_name:
continue
attendees.append(
{
"email": participant.email,
"name": participant.display_name,
"required": participant.required,
"participant_id": participant.id,
"participant_type": participant.participant_type,
}
)
return attendees
def _calendar_event_payload(
request: SchedulingRequest,
slot: SchedulingCandidateSlot,
*,
status: str,
summary_prefix: str | None = None,
) -> Any:
CalendarEventCreateRequest, _CalendarError, _create_event, _list_freebusy = _calendar_api()
summary = f"{summary_prefix}: {request.title}" if summary_prefix else request.title
return CalendarEventCreateRequest(
calendar_id=request.calendar_id,
summary=summary,
description=request.description,
location=slot.location or request.location,
status=status,
transparency="OPAQUE",
classification="PRIVATE" if status == "TENTATIVE" else "PUBLIC",
start_at=slot.start_at,
end_at=slot.end_at,
timezone=slot.timezone,
attendees=_attendees_for_calendar_event(request),
categories=["GovOPlaN", "Scheduling"],
related_to=[{"reltype": "SIBLING", "uid": request.poll_id, "type": "poll"}] if request.poll_id else [],
metadata={
"scheduling_request_id": request.id,
"scheduling_slot_id": slot.id,
"poll_id": request.poll_id,
"kind": "tentative_hold" if status == "TENTATIVE" else "scheduled_meeting",
},
)
def evaluate_calendar_freebusy(
session: Session,
*,
tenant_id: str,
request_id: str,
) -> tuple[SchedulingRequest, list[str]]:
request = get_scheduling_request(session, tenant_id=tenant_id, request_id=request_id)
_require_calendar_enabled(request)
if not request.calendar_freebusy_enabled:
raise SchedulingError("Calendar free/busy checks are not enabled for this scheduling request")
_CalendarEventCreateRequest, CalendarError, _create_event, list_freebusy = _calendar_api()
warnings: list[str] = []
for slot in _active_slots(request):
try:
conflicts = list_freebusy(
session,
tenant_id=tenant_id,
start_at=slot.start_at,
end_at=slot.end_at,
calendar_ids=[request.calendar_id] if request.calendar_id else None,
)
except CalendarError as exc:
slot.freebusy_checked_at = _now()
slot.freebusy_status = "error"
slot.freebusy_conflicts = [{"error": str(exc)}]
warnings.append(str(exc))
continue
slot.freebusy_checked_at = _now()
slot.freebusy_conflicts = _jsonable(conflicts)
slot.freebusy_status = "busy" if conflicts else "free"
session.flush()
return request, warnings
def create_tentative_calendar_holds(
session: Session,
*,
tenant_id: str,
user_id: str | None,
request_id: str,
) -> tuple[SchedulingRequest, list[str], list[str]]:
request = get_scheduling_request(session, tenant_id=tenant_id, request_id=request_id)
_require_calendar_enabled(request)
if not request.calendar_hold_enabled:
raise SchedulingError("Tentative calendar holds are not enabled for this scheduling request")
_CalendarEventCreateRequest, CalendarError, create_event, _list_freebusy = _calendar_api()
created_event_ids: list[str] = []
warnings: list[str] = []
for slot in _active_slots(request):
if slot.tentative_hold_event_id:
continue
try:
event = create_event(
session,
tenant_id=tenant_id,
user_id=user_id,
payload=_calendar_event_payload(request, slot, status="TENTATIVE", summary_prefix="Tentative hold"),
)
except CalendarError as exc:
warnings.append(str(exc))
continue
slot.tentative_hold_event_id = event.id
created_event_ids.append(event.id)
session.flush()
return request, created_event_ids, warnings
def create_final_calendar_event(
session: Session,
*,
tenant_id: str,
user_id: str | None,
request_id: str,
) -> tuple[SchedulingRequest, str | None, list[str]]:
request = get_scheduling_request(session, tenant_id=tenant_id, request_id=request_id)
_require_calendar_enabled(request)
if not request.create_calendar_event_on_decision:
raise SchedulingError("Final calendar event creation is not enabled for this scheduling request")
if request.calendar_event_id:
return request, request.calendar_event_id, []
if not request.selected_slot_id:
raise SchedulingError("Scheduling request has no selected slot")
slot = _selected_slot(request, slot_id=request.selected_slot_id)
_CalendarEventCreateRequest, CalendarError, create_event, _list_freebusy = _calendar_api()
try:
event = create_event(
session,
tenant_id=tenant_id,
user_id=user_id,
payload=_calendar_event_payload(request, slot, status="CONFIRMED"),
)
except CalendarError as exc:
request.metadata_ = {
**(request.metadata_ or {}),
"calendar_handoff": {"status": "error", "error": str(exc), "slot_id": slot.id, "calendar_id": request.calendar_id},
}
session.flush()
return request, None, [str(exc)]
request.calendar_event_id = event.id
request.handed_off_at = _now()
request.status = "handed_off"
request.metadata_ = {
**(request.metadata_ or {}),
"calendar_handoff": {"status": "created", "event_id": event.id, "slot_id": slot.id, "calendar_id": request.calendar_id},
}
_sync_poll_workflow(session, tenant_id=tenant_id, request=request)
session.flush()
return request, event.id, []
def create_scheduling_notification_jobs(
session: Session,
*,
tenant_id: str,
request_id: str,
event_kind: str,
channel: str = "mail",
metadata: dict[str, Any] | None = None,
) -> list[SchedulingNotification]:
if event_kind not in NOTIFICATION_KINDS:
raise SchedulingError(f"Unsupported scheduling notification kind: {event_kind}")
request = get_scheduling_request(session, tenant_id=tenant_id, request_id=request_id)
notifications: list[SchedulingNotification] = []
base_metadata = metadata or {}
for participant in _active_participants(request):
recipient = participant.email or participant.respondent_id
status = "pending" if recipient else "skipped"
notification = SchedulingNotification(
tenant_id=tenant_id,
request_id=request.id,
participant_id=participant.id,
event_kind=event_kind,
channel=channel,
recipient=recipient,
status=status,
payload={
"title": request.title,
"request_id": request.id,
"poll_id": request.poll_id,
"participant_id": participant.id,
"selected_slot_id": request.selected_slot_id,
"calendar_event_id": request.calendar_event_id,
},
metadata_=dict(base_metadata),
)
if status == "skipped":
notification.error = "Participant has no deliverable recipient address or id"
session.add(notification)
notifications.append(notification)
session.flush()
_mirror_scheduling_notifications_to_center(session, request=request, notifications=notifications)
return notifications
def _mirror_scheduling_notifications_to_center(
session: Session,
*,
request: SchedulingRequest,
notifications: list[SchedulingNotification],
) -> None:
provider = notification_dispatch_provider(get_registry())
if provider is None:
return
participants_by_id = {participant.id: participant for participant in _active_participants(request)}
for notification in notifications:
if notification.status == "skipped":
continue
participant = participants_by_id.get(notification.participant_id or "")
try:
response = provider.enqueue_notification(
session,
_notification_dispatch_request(request=request, participant=participant, notification=notification),
enqueue_delivery=True,
)
except Exception as exc: # noqa: BLE001 - mirroring must not block scheduling workflow.
notification.status = "failed"
notification.error = f"Notification center enqueue failed: {exc}"
continue
notification.metadata_ = {
**(notification.metadata_ or {}),
"notification_id": response.get("id"),
"notification_status": response.get("status"),
}
if response.get("status") in {"queued", "sending", "sent"}:
notification.status = str(response["status"])
elif response.get("status") == "skipped":
notification.status = "skipped"
notification.error = str(response.get("last_error") or "Notification center skipped delivery")
session.flush()
def _notification_dispatch_request(
*,
request: SchedulingRequest,
participant: SchedulingParticipant | None,
notification: SchedulingNotification,
) -> NotificationDispatchRequest:
payload = {
**(notification.payload or {}),
"scheduling_notification_id": notification.id,
"participant": {
"id": participant.id,
"display_name": participant.display_name,
"email": participant.email,
"required": participant.required,
"participant_type": participant.participant_type,
}
if participant
else None,
}
return NotificationDispatchRequest(
tenant_id=request.tenant_id,
source_module="scheduling",
source_resource_type="request",
source_resource_id=request.id,
event_kind=notification.event_kind,
channel=notification.channel,
recipient=notification.recipient,
recipient_type="scheduling_participant",
recipient_id=participant.id if participant else notification.participant_id,
recipient_label=participant.display_name if participant else None,
subject=_notification_subject(request, notification.event_kind),
body_text=_notification_body_text(request, participant, notification.event_kind),
action_url=f"/scheduling?request_id={request.id}",
payload=_jsonable(payload),
metadata={
**(notification.metadata_ or {}),
"scheduling_notification_id": notification.id,
"scheduling_request_id": request.id,
},
)
def _notification_subject(request: SchedulingRequest, event_kind: str) -> str:
labels = {
"invitation": "Scheduling invitation",
"reminder": "Scheduling reminder",
"decision": "Scheduling decision",
"cancellation": "Scheduling cancelled",
}
return f"{labels.get(event_kind, 'Scheduling update')}: {request.title}"
def _notification_body_text(
request: SchedulingRequest,
participant: SchedulingParticipant | None,
event_kind: str,
) -> str:
greeting = f"Hello {participant.display_name}," if participant and participant.display_name else "Hello,"
lines = [greeting, "", _notification_body_intro(request, event_kind)]
selected_slot = next((slot for slot in _active_slots(request) if slot.id == request.selected_slot_id), None)
if selected_slot is not None:
lines.append(f"Selected slot: {_slot_label(selected_slot.start_at, selected_slot.end_at, timezone_name=selected_slot.timezone)}")
if request.location:
lines.append(f"Location: {request.location}")
lines.append(f"Scheduling request: {request.title}")
return "\n".join(lines)
def _notification_body_intro(request: SchedulingRequest, event_kind: str) -> str:
if event_kind == "invitation":
return f"You are invited to respond to the scheduling poll for {request.title}."
if event_kind == "reminder":
return f"This is a reminder to respond to the scheduling poll for {request.title}."
if event_kind == "decision":
return f"A final slot was selected for {request.title}."
if event_kind == "cancellation":
return f"The scheduling request {request.title} was cancelled."
return f"There is an update for {request.title}."
def _emit_scheduling_center_notification(
session: Session,
*,
request: SchedulingRequest,
event_kind: str,
subject: str,
body_text: str,
participant: SchedulingParticipant | None = None,
priority: int = 0,
) -> None:
provider = notification_dispatch_provider(get_registry())
if provider is None:
return
try:
provider.enqueue_notification(
session,
NotificationDispatchRequest(
tenant_id=request.tenant_id,
source_module="scheduling",
source_resource_type="request",
source_resource_id=request.id,
event_kind=event_kind,
channel="inbox",
recipient_type="user" if request.organizer_user_id else None,
recipient_id=request.organizer_user_id,
subject=subject,
body_text=body_text,
action_url=f"/scheduling?request_id={request.id}",
priority=priority,
payload=_jsonable(
{
"request_id": request.id,
"poll_id": request.poll_id,
"participant_id": participant.id if participant else None,
}
),
metadata={"scheduling_request_id": request.id},
),
enqueue_delivery=False,
)
except Exception:
return
def list_scheduling_notifications(
session: Session,
*,
tenant_id: str,
request_id: str | None = None,
status: str | None = None,
) -> list[SchedulingNotification]:
query = session.query(SchedulingNotification).filter(SchedulingNotification.tenant_id == tenant_id)
if request_id:
query = query.filter(SchedulingNotification.request_id == request_id)
if status:
query = query.filter(SchedulingNotification.status == status)
return query.order_by(SchedulingNotification.created_at.desc(), SchedulingNotification.id.asc()).all()
def refresh_participant_response_state(session: Session, *, request: SchedulingRequest) -> None:
if request.poll_id is None:
return
by_invitation_id = {
participant.poll_invitation_id: participant
for participant in _active_participants(request)
if participant.poll_invitation_id is not None
}
if not by_invitation_id:
return
responses = (
session.query(PollResponse)
.filter(PollResponse.tenant_id == request.tenant_id, PollResponse.poll_id == request.poll_id, PollResponse.deleted_at.is_(None))
.all()
)
changed = False
for response in responses:
invitation_id = (response.metadata_ or {}).get("invitation_id")
participant = by_invitation_id.get(invitation_id)
if participant is not None and participant.status != "responded":
participant.status = "responded"
participant.responded_at = response_datetime(response.submitted_at)
_emit_scheduling_center_notification(
session,
request=request,
participant=participant,
event_kind="scheduling.participant_responded",
subject=f"Scheduling response: {request.title}",
body_text=f"{participant.display_name or participant.email or 'A participant'} responded to {request.title}.",
)
changed = True
if changed:
session.flush()
def create_scheduling_request(
session: Session,
*,
tenant_id: str,
user_id: str | None,
payload: SchedulingRequestCreateRequest,
) -> tuple[SchedulingRequest, dict[str, str]]:
if not payload.allow_external_participants:
for participant_input in payload.participants:
if participant_input.participant_type == "external":
raise SchedulingError("External participants are not allowed for this scheduling request")
request = SchedulingRequest(
tenant_id=tenant_id,
title=payload.title,
description=payload.description,
location=payload.location,
timezone=payload.timezone,
status=payload.status,
organizer_user_id=user_id,
deadline_at=payload.deadline_at,
allow_external_participants=payload.allow_external_participants,
allow_participant_updates=payload.allow_participant_updates,
result_visibility=payload.result_visibility,
metadata_=payload.metadata,
)
_set_calendar_preferences(request, payload)
session.add(request)
session.flush()
for position, slot_input in enumerate(payload.slots):
timezone_name = slot_input.timezone or payload.timezone
slot = SchedulingCandidateSlot(
tenant_id=tenant_id,
request_id=request.id,
label=slot_input.label or _slot_label(slot_input.start_at, slot_input.end_at, timezone_name=timezone_name),
description=slot_input.description,
start_at=slot_input.start_at,
end_at=slot_input.end_at,
timezone=timezone_name,
location=slot_input.location or payload.location,
position=position,
metadata_=slot_input.metadata,
)
session.add(slot)
for participant_input in payload.participants:
participant = SchedulingParticipant(
tenant_id=tenant_id,
request_id=request.id,
respondent_id=participant_input.respondent_id,
display_name=participant_input.display_name,
email=participant_input.email,
participant_type=participant_input.participant_type,
required=participant_input.required,
status="draft" if payload.status == "draft" else "invited",
metadata_=participant_input.metadata,
)
session.add(participant)
session.flush()
try:
poll = create_poll(
session,
tenant_id=tenant_id,
user_id=user_id,
payload=PollCreateRequest(
title=payload.title,
description=payload.description,
kind="availability",
status=_poll_status_for_request(payload.status),
visibility="unlisted" if payload.allow_external_participants else "tenant",
result_visibility=payload.result_visibility,
context_module="scheduling",
context_resource_type="scheduling_request",
context_resource_id=request.id,
workflow_state=_poll_workflow_state(request),
workflow_steps=_workflow_steps(_poll_workflow_state(request)),
allow_anonymous=False,
allow_response_update=payload.allow_participant_updates,
min_choices=1,
max_choices=len(_active_slots(request)),
opens_at=None,
closes_at=payload.deadline_at,
options=_poll_option_inputs(request),
metadata={"scheduling_request_id": request.id, "calendar": payload.calendar.model_dump()},
),
)
except PollError as exc:
raise SchedulingError(str(exc)) from exc
request.poll_id = poll.id
options_by_position = {option.position: option.id for option in poll.options}
for slot in _active_slots(request):
slot.poll_option_id = options_by_position.get(slot.position)
invitation_tokens: dict[str, str] = {}
if payload.create_participant_invitations:
for participant in _active_participants(request):
try:
invitation, token = create_poll_invitation(
session,
tenant_id=tenant_id,
poll_id=poll.id,
payload=PollInvitationCreateRequest(
respondent_id=participant.respondent_id,
respondent_label=participant.display_name,
email=participant.email,
expires_at=payload.deadline_at,
metadata={"scheduling_request_id": request.id, "scheduling_participant_id": participant.id},
),
)
except PollError as exc:
raise SchedulingError(str(exc)) from exc
participant.poll_invitation_id = invitation.id
participant.last_invited_at = _now()
participant.status = "invited"
invitation_tokens[participant.id] = token
create_scheduling_notification_jobs(
session,
tenant_id=tenant_id,
request_id=request.id,
event_kind="invitation",
metadata={"created_with_request": True},
)
session.flush()
return request, invitation_tokens
def list_scheduling_requests(session: Session, *, tenant_id: str, status: str | None = None) -> list[SchedulingRequest]:
query = session.query(SchedulingRequest).filter(SchedulingRequest.tenant_id == tenant_id, SchedulingRequest.deleted_at.is_(None))
if status:
query = query.filter(SchedulingRequest.status == status)
return query.order_by(SchedulingRequest.created_at.desc(), SchedulingRequest.title.asc()).all()
def get_scheduling_request(session: Session, *, tenant_id: str, request_id: str) -> SchedulingRequest:
request = (
session.query(SchedulingRequest)
.filter(SchedulingRequest.tenant_id == tenant_id, SchedulingRequest.id == request_id, SchedulingRequest.deleted_at.is_(None))
.first()
)
if request is None:
raise SchedulingError("Scheduling request not found")
return request
def update_scheduling_request(
session: Session,
*,
tenant_id: str,
request_id: str,
payload: SchedulingRequestUpdateRequest,
) -> SchedulingRequest:
request = get_scheduling_request(session, tenant_id=tenant_id, request_id=request_id)
if request.status in {"decided", "handed_off", "cancelled", "archived"}:
raise SchedulingError("Decided, handed off, cancelled, or archived scheduling requests cannot be edited")
for field in ("title", "description", "location", "deadline_at", "allow_external_participants", "allow_participant_updates", "result_visibility"):
value = getattr(payload, field)
if value is not None:
setattr(request, field, value)
if payload.calendar is not None:
_set_calendar_preferences(request, payload)
if payload.metadata is not None:
request.metadata_ = payload.metadata
session.flush()
return request
def open_scheduling_request(session: Session, *, tenant_id: str, request_id: str) -> SchedulingRequest:
request = get_scheduling_request(session, tenant_id=tenant_id, request_id=request_id)
if request.poll_id is None:
raise SchedulingError("Scheduling request has no backing poll")
try:
open_poll(session, tenant_id=tenant_id, poll_id=request.poll_id)
except PollError as exc:
raise SchedulingError(str(exc)) from exc
request.status = "collecting"
_sync_poll_workflow(session, tenant_id=tenant_id, request=request)
session.flush()
return request
def close_scheduling_request(session: Session, *, tenant_id: str, request_id: str) -> SchedulingRequest:
request = get_scheduling_request(session, tenant_id=tenant_id, request_id=request_id)
if request.poll_id is None:
raise SchedulingError("Scheduling request has no backing poll")
try:
close_poll(session, tenant_id=tenant_id, poll_id=request.poll_id)
except PollError as exc:
raise SchedulingError(str(exc)) from exc
request.status = "closed"
_sync_poll_workflow(session, tenant_id=tenant_id, request=request)
session.flush()
return request
def decide_scheduling_request(
session: Session,
*,
tenant_id: str,
request_id: str,
payload: SchedulingDecisionRequest,
user_id: str | None = None,
) -> SchedulingRequest:
request = get_scheduling_request(session, tenant_id=tenant_id, request_id=request_id)
if request.poll_id is None:
raise SchedulingError("Scheduling request has no backing poll")
slot = _selected_slot(request, slot_id=payload.slot_id, poll_option_id=payload.poll_option_id)
try:
decide_poll(
session,
tenant_id=tenant_id,
poll_id=request.poll_id,
payload=PollDecisionRequest(option_id=slot.poll_option_id),
)
except PollError as exc:
raise SchedulingError(str(exc)) from exc
request.selected_slot_id = slot.id
request.status = "decided"
should_handoff = payload.handoff_to_calendar or (
payload.handoff_to_calendar is None and request.create_calendar_event_on_decision
)
if should_handoff:
if request.calendar_integration_enabled and request.create_calendar_event_on_decision:
create_final_calendar_event(session, tenant_id=tenant_id, user_id=user_id, request_id=request.id)
else:
request.handed_off_at = _now()
request.status = "handed_off"
request.metadata_ = {
**(request.metadata_ or {}),
"calendar_handoff": {
"status": "pending",
"reason": "Calendar event creation is not enabled or Calendar is unavailable.",
"slot_id": slot.id,
"calendar_id": request.calendar_id,
},
}
create_scheduling_notification_jobs(session, tenant_id=tenant_id, request_id=request.id, event_kind="decision")
_sync_poll_workflow(session, tenant_id=tenant_id, request=request)
session.flush()
return request
def cancel_scheduling_request(session: Session, *, tenant_id: str, request_id: str) -> SchedulingRequest:
request = get_scheduling_request(session, tenant_id=tenant_id, request_id=request_id)
request.status = "cancelled"
request.cancelled_at = _now()
if request.poll_id is not None:
try:
poll = get_poll(session, tenant_id=tenant_id, poll_id=request.poll_id)
if poll.status not in {"closed", "decided", "archived"}:
close_poll(session, tenant_id=tenant_id, poll_id=request.poll_id)
except PollError as exc:
raise SchedulingError(str(exc)) from exc
_sync_poll_workflow(session, tenant_id=tenant_id, request=request)
create_scheduling_notification_jobs(session, tenant_id=tenant_id, request_id=request.id, event_kind="cancellation")
session.flush()
return request
def _selected_slot(
request: SchedulingRequest,
*,
slot_id: str | None = None,
poll_option_id: str | None = None,
) -> SchedulingCandidateSlot:
for slot in _active_slots(request):
if slot_id is not None and slot.id == slot_id:
return slot
if poll_option_id is not None and slot.poll_option_id == poll_option_id:
return slot
raise SchedulingError("Scheduling candidate slot not found")
def scheduling_request_summary(session: Session, *, tenant_id: str, request_id: str) -> dict[str, Any]:
request = get_scheduling_request(session, tenant_id=tenant_id, request_id=request_id)
if request.poll_id is None:
raise SchedulingError("Scheduling request has no backing poll")
try:
summary = poll_result_summary_by_id(session, tenant_id=tenant_id, poll_id=request.poll_id)
except PollError as exc:
raise SchedulingError(str(exc)) from exc
refresh_participant_response_state(session, request=request)
return summary
def scheduling_slot_response(slot: SchedulingCandidateSlot) -> dict[str, Any]:
return {
"id": slot.id,
"poll_option_id": slot.poll_option_id,
"label": slot.label,
"description": slot.description,
"start_at": response_datetime(slot.start_at),
"end_at": response_datetime(slot.end_at),
"timezone": slot.timezone,
"location": slot.location,
"position": slot.position,
"freebusy_checked_at": response_datetime(slot.freebusy_checked_at),
"freebusy_status": slot.freebusy_status,
"freebusy_conflicts": slot.freebusy_conflicts or [],
"tentative_hold_event_id": slot.tentative_hold_event_id,
"metadata": slot.metadata_ or {},
}
def scheduling_participant_response(participant: SchedulingParticipant, *, invitation_token: str | None = None) -> dict[str, Any]:
return {
"id": participant.id,
"respondent_id": participant.respondent_id,
"display_name": participant.display_name,
"email": participant.email,
"participant_type": participant.participant_type,
"required": participant.required,
"status": participant.status,
"poll_invitation_id": participant.poll_invitation_id,
"invitation_token": invitation_token,
"last_invited_at": response_datetime(participant.last_invited_at),
"responded_at": response_datetime(participant.responded_at),
"metadata": participant.metadata_ or {},
}
def scheduling_request_response(request: SchedulingRequest, *, invitation_tokens: dict[str, str] | None = None) -> dict[str, Any]:
invitation_tokens = invitation_tokens or {}
return {
"id": request.id,
"tenant_id": request.tenant_id,
"title": request.title,
"description": request.description,
"location": request.location,
"timezone": request.timezone,
"status": request.status,
"poll_id": request.poll_id,
"selected_slot_id": request.selected_slot_id,
"organizer_user_id": request.organizer_user_id,
"deadline_at": response_datetime(request.deadline_at),
"allow_external_participants": request.allow_external_participants,
"allow_participant_updates": request.allow_participant_updates,
"result_visibility": request.result_visibility,
"calendar_integration_enabled": request.calendar_integration_enabled,
"calendar_id": request.calendar_id,
"calendar_freebusy_enabled": request.calendar_freebusy_enabled,
"calendar_hold_enabled": request.calendar_hold_enabled,
"create_calendar_event_on_decision": request.create_calendar_event_on_decision,
"calendar_event_id": request.calendar_event_id,
"handed_off_at": response_datetime(request.handed_off_at),
"cancelled_at": response_datetime(request.cancelled_at),
"created_at": response_datetime(request.created_at),
"updated_at": response_datetime(request.updated_at),
"metadata": request.metadata_ or {},
"slots": [scheduling_slot_response(slot) for slot in _active_slots(request)],
"participants": [
scheduling_participant_response(participant, invitation_token=invitation_tokens.get(participant.id))
for participant in _active_participants(request)
],
}
def scheduling_notification_response(notification: SchedulingNotification) -> dict[str, Any]:
return {
"id": notification.id,
"request_id": notification.request_id,
"participant_id": notification.participant_id,
"event_kind": notification.event_kind,
"channel": notification.channel,
"recipient": notification.recipient,
"status": notification.status,
"payload": notification.payload or {},
"error": notification.error,
"sent_at": response_datetime(notification.sent_at),
"created_at": response_datetime(notification.created_at),
"updated_at": response_datetime(notification.updated_at),
"metadata": notification.metadata_ or {},
}

View File

@@ -0,0 +1 @@

33
tests/test_manifest.py Normal file
View File

@@ -0,0 +1,33 @@
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.assertFalse(manifest.required_capabilities)
self.assertIn("auth.principalResolver", 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.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})
if __name__ == "__main__":
unittest.main()

300
tests/test_service.py Normal file
View File

@@ -0,0 +1,300 @@
from __future__ import annotations
import unittest
from datetime import datetime, timedelta, timezone
from sqlalchemy import create_engine
from sqlalchemy.orm import Session, sessionmaker
from govoplan_core.db.base import Base
from govoplan_core.core.change_sequence import ChangeSequenceEntry
from govoplan_access.backend.db.models import Account, User
from govoplan_calendar.backend.db.models import CalendarCollection, CalendarEvent, CalendarSyncSource
from govoplan_poll.backend.db.models import Poll, PollInvitation, PollOption, PollResponse
from govoplan_poll.backend.schemas import PollAnswerInput, PollSubmitResponseRequest
from govoplan_poll.backend.service import get_poll, submit_poll_response_with_token
from govoplan_scheduling.backend.db.models import SchedulingCandidateSlot, SchedulingNotification, SchedulingParticipant, SchedulingRequest
from govoplan_scheduling.backend.schemas import (
SchedulingCalendarPreferences,
SchedulingCandidateSlotInput,
SchedulingDecisionRequest,
SchedulingParticipantInput,
SchedulingRequestCreateRequest,
)
from govoplan_scheduling.backend.service import (
SchedulingError,
close_scheduling_request,
create_final_calendar_event,
create_scheduling_notification_jobs,
create_scheduling_request,
create_tentative_calendar_holds,
decide_scheduling_request,
evaluate_calendar_freebusy,
list_scheduling_notifications,
scheduling_request_summary,
)
class SchedulingServiceTests(unittest.TestCase):
def setUp(self) -> None:
self.engine = create_engine("sqlite:///:memory:")
Base.metadata.create_all(
self.engine,
tables=[
Poll.__table__,
PollOption.__table__,
PollResponse.__table__,
PollInvitation.__table__,
CalendarCollection.__table__,
CalendarEvent.__table__,
CalendarSyncSource.__table__,
ChangeSequenceEntry.__table__,
Account.__table__,
User.__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=[
SchedulingParticipant.__table__,
SchedulingNotification.__table__,
SchedulingCandidateSlot.__table__,
SchedulingRequest.__table__,
User.__table__,
Account.__table__,
ChangeSequenceEntry.__table__,
CalendarSyncSource.__table__,
CalendarEvent.__table__,
CalendarCollection.__table__,
PollInvitation.__table__,
PollResponse.__table__,
PollOption.__table__,
Poll.__table__,
],
)
self.engine.dispose()
def _calendar(self) -> CalendarCollection:
calendar = CalendarCollection(
id="calendar-1",
tenant_id="tenant-1",
slug="team",
name="Team",
timezone="Europe/Berlin",
owner_type="tenant",
visibility="tenant",
is_default=True,
metadata_={},
)
self.session.add(calendar)
self.session.flush()
return calendar
def _payload(self) -> SchedulingRequestCreateRequest:
start = datetime(2026, 7, 20, 9, tzinfo=timezone.utc)
return SchedulingRequestCreateRequest(
title="Steering group",
description="Find a slot",
location="Room 1",
timezone="Europe/Berlin",
status="collecting",
deadline_at=start + timedelta(days=3),
calendar=SchedulingCalendarPreferences(
enabled=True,
calendar_id="calendar-1",
freebusy_enabled=True,
tentative_holds_enabled=True,
create_event_on_decision=True,
),
slots=[
SchedulingCandidateSlotInput(start_at=start, end_at=start + timedelta(hours=1), label="Monday 09:00"),
SchedulingCandidateSlotInput(start_at=start + timedelta(days=1), end_at=start + timedelta(days=1, hours=1), label="Tuesday 09:00"),
],
participants=[
SchedulingParticipantInput(display_name="Alice", email="alice@example.test"),
SchedulingParticipantInput(display_name="Bob", email="bob@example.test", required=False),
],
)
def test_create_request_creates_poll_slots_and_signed_invitations(self) -> None:
request, tokens = create_scheduling_request(
self.session,
tenant_id="tenant-1",
user_id="user-1",
payload=self._payload(),
)
poll = get_poll(self.session, tenant_id="tenant-1", poll_id=request.poll_id)
self.assertEqual(request.status, "collecting")
self.assertEqual(request.calendar_id, "calendar-1")
self.assertEqual(poll.kind, "availability")
self.assertEqual(poll.status, "open")
self.assertEqual(poll.context_module, "scheduling")
self.assertEqual(poll.context_resource_id, request.id)
self.assertEqual(len(request.slots), 2)
self.assertTrue(all(slot.poll_option_id for slot in request.slots))
self.assertEqual(len(tokens), 2)
self.assertTrue(all(participant.poll_invitation_id for participant in request.participants))
def test_signed_response_summary_and_decision_handoff(self) -> None:
payload = self._payload().model_copy(update={"calendar": SchedulingCalendarPreferences()})
request, tokens = create_scheduling_request(
self.session,
tenant_id="tenant-1",
user_id="user-1",
payload=payload,
)
first_participant = request.participants[0]
first_slot = request.slots[0]
second_slot = request.slots[1]
submit_poll_response_with_token(
self.session,
token=tokens[first_participant.id],
payload=PollSubmitResponseRequest(
answers=[
PollAnswerInput(option_id=first_slot.poll_option_id, value="available"),
PollAnswerInput(option_id=second_slot.poll_option_id, value="maybe"),
]
),
)
summary = scheduling_request_summary(self.session, tenant_id="tenant-1", request_id=request.id)
self.assertEqual(summary["response_count"], 1)
self.assertEqual(first_participant.status, "responded")
self.assertIsNotNone(first_participant.responded_at)
values = {result["option_id"]: result["values"] for result in summary["option_results"]}
self.assertEqual(values[first_slot.poll_option_id]["available"], 1)
self.assertEqual(values[second_slot.poll_option_id]["maybe"], 1)
close_scheduling_request(self.session, tenant_id="tenant-1", request_id=request.id)
decided = decide_scheduling_request(
self.session,
tenant_id="tenant-1",
request_id=request.id,
payload=SchedulingDecisionRequest(slot_id=first_slot.id, handoff_to_calendar=True),
)
poll = get_poll(self.session, tenant_id="tenant-1", poll_id=request.poll_id)
self.assertEqual(decided.status, "handed_off")
self.assertEqual(decided.selected_slot_id, first_slot.id)
self.assertEqual(decided.metadata_["calendar_handoff"]["status"], "pending")
self.assertEqual(poll.status, "decided")
self.assertEqual(poll.workflow_state, "handed_off")
def test_calendar_freebusy_holds_and_final_event_creation(self) -> None:
self._calendar()
payload = self._payload()
request, _tokens = create_scheduling_request(
self.session,
tenant_id="tenant-1",
user_id="user-1",
payload=payload,
)
first_slot = request.slots[0]
self.session.add(
CalendarEvent(
tenant_id="tenant-1",
calendar_id="calendar-1",
uid="busy@example.test",
sequence=0,
summary="Busy",
status="CONFIRMED",
transparency="OPAQUE",
classification="PUBLIC",
start_at=first_slot.start_at,
end_at=first_slot.end_at,
all_day=False,
attendees=[],
categories=[],
rdate=[],
exdate=[],
reminders=[],
attachments=[],
related_to=[],
source_kind="local",
icalendar={},
metadata_={},
)
)
self.session.flush()
request, warnings = evaluate_calendar_freebusy(self.session, tenant_id="tenant-1", request_id=request.id)
self.assertEqual(warnings, [])
self.assertEqual(request.slots[0].freebusy_status, "busy")
self.assertEqual(request.slots[1].freebusy_status, "free")
request, hold_event_ids, warnings = create_tentative_calendar_holds(
self.session,
tenant_id="tenant-1",
user_id="user-1",
request_id=request.id,
)
self.assertEqual(warnings, [])
self.assertEqual(len(hold_event_ids), 2)
self.assertTrue(all(slot.tentative_hold_event_id for slot in request.slots))
close_scheduling_request(self.session, tenant_id="tenant-1", request_id=request.id)
decided = decide_scheduling_request(
self.session,
tenant_id="tenant-1",
request_id=request.id,
payload=SchedulingDecisionRequest(slot_id=request.slots[1].id, handoff_to_calendar=False),
user_id="user-1",
)
decided, event_id, warnings = create_final_calendar_event(
self.session,
tenant_id="tenant-1",
user_id="user-1",
request_id=decided.id,
)
self.assertEqual(warnings, [])
self.assertIsNotNone(event_id)
self.assertEqual(decided.status, "handed_off")
self.assertEqual(decided.calendar_event_id, event_id)
self.assertEqual(decided.metadata_["calendar_handoff"]["status"], "created")
def test_notification_outbox_jobs_are_created_and_listed(self) -> None:
request, _tokens = create_scheduling_request(
self.session,
tenant_id="tenant-1",
user_id="user-1",
payload=self._payload(),
)
reminder_jobs = create_scheduling_notification_jobs(
self.session,
tenant_id="tenant-1",
request_id=request.id,
event_kind="reminder",
)
all_jobs = list_scheduling_notifications(self.session, tenant_id="tenant-1", request_id=request.id)
self.assertEqual(len(reminder_jobs), 2)
self.assertGreaterEqual(len(all_jobs), 4)
self.assertTrue(all(job.status == "pending" for job in reminder_jobs))
def test_external_participants_can_be_rejected(self) -> None:
payload = self._payload().model_copy(update={"allow_external_participants": False})
with self.assertRaisesRegex(SchedulingError, "External participants are not allowed"):
create_scheduling_request(
self.session,
tenant_id="tenant-1",
user_id="user-1",
payload=payload,
)
if __name__ == "__main__":
unittest.main()

31
webui/package.json Normal file
View File

@@ -0,0 +1,31 @@
{
"name": "@govoplan/scheduling-webui",
"version": "0.1.8",
"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"
},
"peerDependencies": {
"@govoplan/core-webui": "^0.1.8",
"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
}
}
}

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

@@ -0,0 +1,235 @@
import { apiFetch, type ApiSettings } from "@govoplan/core-webui";
export type SchedulingStatus = "draft" | "collecting" | "closed" | "decided" | "handed_off" | "cancelled" | "archived";
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;
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 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;
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";
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 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 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}`);
}

View File

@@ -0,0 +1,402 @@
import { useEffect, useMemo, useState, type FormEvent } from "react";
import { Bell, CalendarCheck, Check, Clock, Plus, RefreshCw, Send, XCircle } from "lucide-react";
import { Button, EmailAddressInput, hasScope, type ApiSettings, type AuthInfo, type MailboxAddress } from "@govoplan/core-webui";
import {
closeSchedulingRequest,
createSchedulingCalendarEvent,
createSchedulingHolds,
createSchedulingNotifications,
createSchedulingRequest,
decideSchedulingRequest,
evaluateSchedulingFreeBusy,
listSchedulingNotifications,
listSchedulingRequests,
lookupSchedulingAddresses,
openSchedulingRequest,
schedulingSummary,
type SchedulingNotification,
type SchedulingRequest,
type SchedulingSummaryResponse
} from "../../api/scheduling";
type SlotDraft = { label: string; start_at: string; end_at: string };
type ParticipantDraft = { display_name: string; email: string; required: boolean };
const now = new Date();
const defaultStart = new Date(now.getTime() + 24 * 60 * 60 * 1000);
defaultStart.setMinutes(0, 0, 0);
const defaultEnd = new Date(defaultStart.getTime() + 60 * 60 * 1000);
function localValue(date: Date): string {
const pad = (value: number) => value.toString().padStart(2, "0");
return `${date.getFullYear()}-${pad(date.getMonth() + 1)}-${pad(date.getDate())}T${pad(date.getHours())}:${pad(date.getMinutes())}`;
}
function isoFromLocal(value: string): string {
return new Date(value).toISOString();
}
export default function SchedulingPage({ settings, auth }: { settings: ApiSettings; auth: AuthInfo }) {
const [requests, setRequests] = useState<SchedulingRequest[]>([]);
const [selectedId, setSelectedId] = useState("");
const [summary, setSummary] = useState<SchedulingSummaryResponse | null>(null);
const [notifications, setNotifications] = useState<SchedulingNotification[]>([]);
const [loading, setLoading] = useState(true);
const [saving, setSaving] = useState(false);
const [error, setError] = useState("");
const [title, setTitle] = useState("Scheduling poll");
const [location, setLocation] = useState("");
const [calendarId, setCalendarId] = useState("");
const [calendarEnabled, setCalendarEnabled] = useState(false);
const [slots, setSlots] = useState<SlotDraft[]>([
{ label: "Option 1", start_at: localValue(defaultStart), end_at: localValue(defaultEnd) }
]);
const [participants, setParticipants] = useState<ParticipantDraft[]>([{ display_name: "", email: "", required: true }]);
const [addressLookupQuery, setAddressLookupQuery] = useState("");
const [addressSuggestions, setAddressSuggestions] = useState<MailboxAddress[]>([]);
const canWrite = hasScope(auth, "scheduling:schedule:write");
const selected = useMemo(() => requests.find((item) => item.id === selectedId) || requests[0] || null, [requests, selectedId]);
const optionResultById = useMemo(() => {
const map = new Map<string, SchedulingSummaryResponse["poll_summary"]["option_results"][number]>();
for (const result of summary?.poll_summary.option_results || []) map.set(result.option_id, result);
return map;
}, [summary]);
useEffect(() => {
void loadRequests();
}, [settings.apiBaseUrl, settings.apiKey, settings.accessToken]);
useEffect(() => {
if (!selected?.id) {
setSummary(null);
setNotifications([]);
return;
}
void loadDetails(selected.id);
}, [selected?.id]);
useEffect(() => {
const query = addressLookupQuery.trim();
if (!canWrite || query.length < 2) {
setAddressSuggestions([]);
return;
}
let cancelled = false;
const timer = window.setTimeout(() => {
void lookupSchedulingAddresses(settings, query).
then((response) => {
if (cancelled) return;
if (!response.available) {
setAddressSuggestions([]);
return;
}
setAddressSuggestions(
response.candidates
.map((candidate) => candidate.email ? { name: candidate.display_name || undefined, email: candidate.email } : null)
.filter((address): address is MailboxAddress => Boolean(address?.email))
);
}).
catch(() => {
if (!cancelled) setAddressSuggestions([]);
});
}, 200);
return () => {
cancelled = true;
window.clearTimeout(timer);
};
}, [addressLookupQuery, canWrite, settings.accessToken, settings.apiBaseUrl, settings.apiKey]);
async function loadRequests() {
setLoading(true);
setError("");
try {
const response = await listSchedulingRequests(settings);
setRequests(response.requests);
if (!selectedId && response.requests[0]) setSelectedId(response.requests[0].id);
} catch (err) {
setError(errorMessage(err));
} finally {
setLoading(false);
}
}
async function loadDetails(requestId: string) {
try {
const [summaryResponse, notificationResponse] = await Promise.all([
schedulingSummary(settings, requestId).catch(() => null),
listSchedulingNotifications(settings, requestId).catch(() => ({ notifications: [] }))
]);
setSummary(summaryResponse);
setNotifications(notificationResponse.notifications);
} catch (err) {
setError(errorMessage(err));
}
}
async function createRequest(event: FormEvent) {
event.preventDefault();
if (!canWrite) return;
setSaving(true);
setError("");
try {
const request = await createSchedulingRequest(settings, {
title,
location: location || null,
status: "collecting",
calendar: {
enabled: calendarEnabled,
calendar_id: calendarId || null,
freebusy_enabled: calendarEnabled,
tentative_holds_enabled: calendarEnabled,
create_event_on_decision: calendarEnabled
},
slots: slots.map((slot) => ({
label: slot.label || null,
start_at: isoFromLocal(slot.start_at),
end_at: isoFromLocal(slot.end_at),
location: location || null
})),
participants: participants
.filter((participant) => participant.email || participant.display_name)
.map((participant) => ({ ...participant, participant_type: "external" }))
});
setRequests((items) => [request, ...items]);
setSelectedId(request.id);
} catch (err) {
setError(errorMessage(err));
} finally {
setSaving(false);
}
}
async function runAction(action: () => Promise<{ request?: SchedulingRequest } | SchedulingSummaryResponse | unknown>) {
if (!selected || !canWrite) return;
setSaving(true);
setError("");
try {
const response = await action();
const updated = isRequestEnvelope(response) ? response.request : null;
if (updated) {
setRequests((items) => items.map((item) => (item.id === updated.id ? updated : item)));
}
await loadDetails(selected.id);
} catch (err) {
setError(errorMessage(err));
} finally {
setSaving(false);
}
}
return (
<main className="scheduling-page">
<div className="scheduling-shell">
<aside className="scheduling-sidebar">
<div className="scheduling-sidebar-bar">
<strong>Scheduling</strong>
<Button className="scheduling-icon-button" onClick={() => void loadRequests()} title="Refresh">
<RefreshCw size={16} />
</Button>
</div>
<div className="scheduling-list">
{loading ? <div className="scheduling-note">Loading</div> : null}
{requests.map((request) => (
<button
key={request.id}
className={`scheduling-list-item ${selected?.id === request.id ? "is-selected" : ""}`}
type="button"
onClick={() => setSelectedId(request.id)}
>
<span>{request.title}</span>
<small>{request.status}</small>
</button>
))}
</div>
</aside>
<section className="scheduling-workspace">
<div className="scheduling-topbar">
<div className="scheduling-title-line">
<CalendarCheck size={18} />
<strong>{selected?.title || "Scheduling"}</strong>
</div>
<div className="scheduling-actions">
<Button disabled={!selected || saving || !canWrite} onClick={() => void runAction(() => openSchedulingRequest(settings, selected!.id))}>
<Send size={16} /> Open
</Button>
<Button disabled={!selected || saving || !canWrite} onClick={() => void runAction(() => closeSchedulingRequest(settings, selected!.id))}>
<XCircle size={16} /> Close
</Button>
<Button disabled={!selected || saving || !canWrite} onClick={() => void runAction(() => evaluateSchedulingFreeBusy(settings, selected!.id))}>
<RefreshCw size={16} /> Free/busy
</Button>
<Button disabled={!selected || saving || !canWrite} onClick={() => void runAction(() => createSchedulingHolds(settings, selected!.id))}>
<Clock size={16} /> Holds
</Button>
<Button disabled={!selected || saving || !canWrite} onClick={() => void runAction(() => createSchedulingCalendarEvent(settings, selected!.id))}>
<CalendarCheck size={16} /> Event
</Button>
<Button disabled={!selected || saving || !canWrite} onClick={() => void runAction(() => createSchedulingNotifications(settings, selected!.id, "reminder"))}>
<Bell size={16} /> Reminder
</Button>
</div>
</div>
{error ? <div className="scheduling-alert">{error}</div> : null}
<div className="scheduling-content">
<form className="scheduling-create-panel" onSubmit={(event) => void createRequest(event)}>
<div className="scheduling-panel-heading">
<Plus size={16} />
<strong>New poll</strong>
</div>
<label>
<span>Title</span>
<input value={title} onChange={(event) => setTitle(event.target.value)} />
</label>
<label>
<span>Location</span>
<input value={location} onChange={(event) => setLocation(event.target.value)} />
</label>
<label className="scheduling-checkbox">
<input checked={calendarEnabled} type="checkbox" onChange={(event) => setCalendarEnabled(event.target.checked)} />
<span>Calendar</span>
</label>
{calendarEnabled ? (
<label>
<span>Calendar ID</span>
<input value={calendarId} onChange={(event) => setCalendarId(event.target.value)} />
</label>
) : null}
<div className="scheduling-form-section">
<div className="scheduling-mini-heading">
<span>Slots</span>
<Button type="button" onClick={() => setSlots((items) => [...items, { label: `Option ${items.length + 1}`, start_at: localValue(defaultStart), end_at: localValue(defaultEnd) }])}>
<Plus size={14} />
</Button>
</div>
{slots.map((slot, index) => (
<div className="scheduling-slot-draft" key={index}>
<input value={slot.label} onChange={(event) => updateSlot(index, "label", event.target.value)} />
<input type="datetime-local" value={slot.start_at} onChange={(event) => updateSlot(index, "start_at", event.target.value)} />
<input type="datetime-local" value={slot.end_at} onChange={(event) => updateSlot(index, "end_at", event.target.value)} />
</div>
))}
</div>
<div className="scheduling-form-section">
<div className="scheduling-mini-heading">
<span>Participants</span>
<Button type="button" onClick={() => setParticipants((items) => [...items, { display_name: "", email: "", required: true }])}>
<Plus size={14} />
</Button>
</div>
{participants.map((participant, index) => (
<div className="scheduling-participant-draft" key={index}>
<input placeholder="Name" value={participant.display_name} onChange={(event) => updateParticipant(index, "display_name", event.target.value)} />
<EmailAddressInput
value={participant.email ? [{ name: participant.display_name || undefined, email: participant.email }] : []}
suggestions={addressSuggestions}
onSuggestionQueryChange={setAddressLookupQuery}
allowMultiple={false}
disabled={!canWrite}
compact
addLabel="Add participant"
emptyText="Participant email"
onChange={(addresses) => {
const address = addresses[0];
updateParticipantDraft(index, {
display_name: address?.name ?? participant.display_name,
email: address?.email ?? ""
});
}} />
</div>
))}
</div>
<Button disabled={saving || !canWrite} type="submit" variant="primary">
<Plus size={16} /> Create
</Button>
</form>
<div className="scheduling-detail">
{selected ? (
<>
<div className="scheduling-status-row">
<span className={`scheduling-status scheduling-status-${selected.status}`}>{selected.status}</span>
<span>{selected.participants.length} participants</span>
<span>{summary?.poll_summary.response_count || 0} responses</span>
</div>
<div className="scheduling-slot-table">
{selected.slots.map((slot) => {
const result = slot.poll_option_id ? optionResultById.get(slot.poll_option_id) : null;
return (
<div className="scheduling-slot-row" key={slot.id}>
<div>
<strong>{slot.label}</strong>
<small>{formatRange(slot.start_at, slot.end_at)}</small>
</div>
<span className={`scheduling-freebusy ${slot.freebusy_status || "unknown"}`}>{slot.freebusy_status || "unchecked"}</span>
<span>{result?.values.available || 0} yes</span>
<span>{result?.values.maybe || 0} maybe</span>
<span>{result?.values.unavailable || 0} no</span>
<Button disabled={saving || !canWrite} onClick={() => void runAction(() => decideSchedulingRequest(settings, selected.id, { slot_id: slot.id, handoff_to_calendar: selected.create_calendar_event_on_decision }))}>
<Check size={16} /> Decide
</Button>
</div>
);
})}
</div>
<div className="scheduling-columns">
<div>
<div className="scheduling-panel-heading"><strong>Participants</strong></div>
{selected.participants.map((participant) => (
<div className="scheduling-compact-row" key={participant.id}>
<span>{participant.display_name || participant.email || participant.id}</span>
<small>{participant.status}</small>
</div>
))}
</div>
<div>
<div className="scheduling-panel-heading"><strong>Outbox</strong></div>
{notifications.map((notification) => (
<div className="scheduling-compact-row" key={notification.id}>
<span>{notification.event_kind}</span>
<small>{notification.status}</small>
</div>
))}
</div>
</div>
</>
) : (
<div className="scheduling-empty">No scheduling request</div>
)}
</div>
</div>
</section>
</div>
</main>
);
function updateSlot(index: number, field: keyof SlotDraft, value: string) {
setSlots((items) => items.map((item, itemIndex) => (itemIndex === index ? { ...item, [field]: value } : item)));
}
function updateParticipant(index: number, field: keyof ParticipantDraft, value: string) {
setParticipants((items) => items.map((item, itemIndex) => (itemIndex === index ? { ...item, [field]: value } : item)));
}
function updateParticipantDraft(index: number, patch: Partial<ParticipantDraft>) {
setParticipants((items) => items.map((item, itemIndex) => (itemIndex === index ? { ...item, ...patch } : item)));
}
}
function isRequestEnvelope(value: unknown): value is { request: SchedulingRequest } {
return Boolean(value && typeof value === "object" && "request" in value);
}
function formatRange(start: string, end: string): string {
const formatter = new Intl.DateTimeFormat(undefined, { dateStyle: "short", timeStyle: "short" });
return `${formatter.format(new Date(start))} - ${formatter.format(new Date(end))}`;
}
function errorMessage(error: unknown): string {
return error instanceof Error ? error.message : "Request failed";
}

View File

@@ -0,0 +1,4 @@
export const generatedTranslations = {
en: {},
de: {}
};

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,308 @@
.scheduling-page {
box-sizing: border-box;
height: calc(100vh - 115px);
min-height: 0;
padding: 0;
overflow: hidden;
color: var(--text);
background: var(--bg);
}
.scheduling-page *,
.scheduling-page *::before,
.scheduling-page *::after {
box-sizing: border-box;
}
.scheduling-shell {
min-height: 0;
height: 100%;
display: grid;
grid-template-columns: minmax(250px, 310px) minmax(0, 1fr);
border: var(--border-line);
background: var(--panel);
overflow: hidden;
}
.scheduling-sidebar {
min-width: 0;
min-height: 0;
display: flex;
flex-direction: column;
border-right: var(--border-line);
background: var(--panel-soft);
}
.scheduling-sidebar-bar,
.scheduling-topbar,
.scheduling-panel-heading,
.scheduling-mini-heading,
.scheduling-status-row,
.scheduling-actions,
.scheduling-title-line {
display: flex;
align-items: center;
gap: 8px;
}
.scheduling-sidebar-bar {
justify-content: space-between;
min-height: 54px;
padding: 10px 12px;
border-bottom: var(--border-line);
background: var(--panel-header);
}
.scheduling-icon-button.btn {
width: 34px;
min-width: 34px;
height: 34px;
padding: 0;
justify-content: center;
}
.scheduling-list {
min-height: 0;
overflow: auto;
padding: 8px;
}
.scheduling-list-item {
width: 100%;
display: grid;
grid-template-columns: minmax(0, 1fr) auto;
gap: 8px;
align-items: center;
min-height: 40px;
margin: 0 0 4px;
padding: 8px 9px;
border: 0;
border-radius: 6px;
color: var(--text);
background: transparent;
text-align: left;
cursor: pointer;
}
.scheduling-list-item:hover,
.scheduling-list-item.is-selected {
background: var(--hover-bg);
}
.scheduling-list-item span,
.scheduling-slot-row strong,
.scheduling-compact-row span {
min-width: 0;
overflow: hidden;
text-overflow: ellipsis;
white-space: nowrap;
}
.scheduling-list-item small,
.scheduling-slot-row small,
.scheduling-compact-row small,
.scheduling-note {
color: var(--muted);
font-size: 12px;
}
.scheduling-workspace {
min-width: 0;
min-height: 0;
display: flex;
flex-direction: column;
overflow: hidden;
}
.scheduling-topbar {
justify-content: space-between;
min-height: 54px;
padding: 9px 12px;
border-bottom: var(--border-line);
background: var(--panel-header);
}
.scheduling-title-line {
min-width: 180px;
}
.scheduling-actions {
flex-wrap: wrap;
justify-content: flex-end;
}
.scheduling-actions .btn,
.scheduling-create-panel .btn,
.scheduling-slot-row .btn {
min-height: 32px;
display: inline-flex;
align-items: center;
gap: 6px;
}
.scheduling-alert {
margin: 8px 12px 0;
padding: 8px 10px;
border: var(--border-line);
border-color: var(--danger);
border-radius: 6px;
color: var(--danger);
background: var(--danger-soft);
}
.scheduling-content {
min-height: 0;
display: grid;
grid-template-columns: minmax(280px, 360px) minmax(0, 1fr);
gap: 0;
overflow: hidden;
}
.scheduling-create-panel,
.scheduling-detail {
min-height: 0;
overflow: auto;
padding: 12px;
}
.scheduling-create-panel {
display: grid;
align-content: start;
gap: 10px;
border-right: var(--border-line);
background: var(--panel-soft);
}
.scheduling-create-panel label,
.scheduling-form-section {
display: grid;
gap: 5px;
}
.scheduling-create-panel label span,
.scheduling-mini-heading span {
color: var(--muted);
font-size: 12px;
font-weight: 700;
}
.scheduling-create-panel input {
width: 100%;
min-height: 34px;
padding: 6px 8px;
border: var(--border-line);
border-radius: 6px;
color: var(--text);
background: var(--input-bg);
}
.scheduling-checkbox {
grid-template-columns: auto minmax(0, 1fr);
align-items: center;
}
.scheduling-slot-draft,
.scheduling-participant-draft {
display: grid;
gap: 6px;
}
.scheduling-slot-draft {
grid-template-columns: minmax(0, 1fr);
}
.scheduling-status-row {
flex-wrap: wrap;
margin-bottom: 10px;
}
.scheduling-status {
padding: 4px 8px;
border-radius: 999px;
color: var(--text-strong);
background: var(--panel-soft);
font-size: 12px;
font-weight: 700;
}
.scheduling-status-collecting,
.scheduling-status-handed_off {
background: color-mix(in srgb, var(--accent) 18%, transparent);
}
.scheduling-slot-table {
display: grid;
gap: 6px;
}
.scheduling-slot-row {
display: grid;
grid-template-columns: minmax(180px, 1fr) auto auto auto auto auto;
gap: 8px;
align-items: center;
min-height: 46px;
padding: 8px;
border-bottom: var(--border-line);
}
.scheduling-slot-row:hover {
background: var(--hover-bg);
}
.scheduling-freebusy {
min-width: 74px;
padding: 3px 7px;
border-radius: 6px;
text-align: center;
font-size: 12px;
font-weight: 700;
background: var(--panel-soft);
}
.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;
margin-top: 16px;
}
.scheduling-compact-row {
display: grid;
grid-template-columns: minmax(0, 1fr) auto;
gap: 8px;
min-height: 34px;
align-items: center;
border-bottom: var(--border-line);
}
.scheduling-empty {
padding: 20px;
color: var(--muted);
}
@media (max-width: 980px) {
.scheduling-shell,
.scheduling-content,
.scheduling-columns {
grid-template-columns: minmax(0, 1fr);
}
.scheduling-sidebar,
.scheduling-create-panel {
border-right: 0;
border-bottom: var(--border-line);
}
.scheduling-slot-row {
grid-template-columns: minmax(0, 1fr) auto;
}
}

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;
}

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"]
}