diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml index 935ab67..ee2f56c 100644 --- a/.github/workflows/ci.yml +++ b/.github/workflows/ci.yml @@ -111,6 +111,8 @@ jobs: name: Build & Push Docker Images runs-on: ubuntu-latest needs: [build, e2e] + outputs: + tag: ${{ steps.version.outputs.tag }} permissions: contents: read packages: write @@ -244,8 +246,8 @@ jobs: kubectl set image deployment/web web=ghcr.io/groombook/web:$TAG -n groombook-dev # Wait for rollout - kubectl rollout status deployment/api -n groombook-dev --timeout=120s - kubectl rollout status deployment/web -n groombook-dev --timeout=120s + kubectl rollout status deployment/api -n groombook-dev --timeout=300s + kubectl rollout status deployment/web -n groombook-dev --timeout=300s echo "Deployment complete." @@ -268,3 +270,71 @@ jobs: 'Ready for UAT validation.' ].join('\n') }); + + cd: + name: Update Infra Image Tags + runs-on: ubuntu-latest + needs: [docker] + if: github.ref == 'refs/heads/main' && github.event_name == 'push' + permissions: + contents: write + pull-requests: write + steps: + - name: Generate infra repo token + id: infra-token + uses: tibdex/github-app-token@v2 + with: + app_id: ${{ vars.GH_APP_ID }} + private_key: ${{ secrets.GH_APP_PRIVATE_KEY }} + + - name: Clone groombook/infra + run: | + git clone https://x-access-token:${{ steps.infra-token.outputs.token }}@github.com/groombook/infra.git /tmp/infra + + - name: Install yq + run: | + sudo wget -qO /usr/local/bin/yq https://github.com/mikefarah/yq/releases/latest/download/yq_linux_amd64 + sudo chmod +x /usr/local/bin/yq + + - name: Update dev overlay image tags + env: + TAG: ${{ needs.docker.outputs.tag }} + run: | + if [ -z "$TAG" ]; then + TAG="$(date -u +%Y.%m.%d)-${GITHUB_SHA::7}" + fi + echo "Updating dev overlay image tags to: $TAG" + cd /tmp/infra + DEV_KUST="apps/groombook/overlays/dev/kustomization.yaml" + yq -i '(.images[] | select(.name == "ghcr.io/groombook/api")).newTag = env(TAG)' "$DEV_KUST" + yq -i '(.images[] | select(.name == "ghcr.io/groombook/web")).newTag = env(TAG)' "$DEV_KUST" + yq -i '(.images[] | select(.name == "ghcr.io/groombook/migrate")).newTag = env(TAG)' "$DEV_KUST" + yq -i '(.images[] | select(.name == "ghcr.io/groombook/seed")).newTag = env(TAG)' "$DEV_KUST" + git -C /tmp/infra diff --stat + + - name: Create PR on groombook/infra + env: + TAG: ${{ needs.docker.outputs.tag }} + GH_TOKEN: ${{ steps.infra-token.outputs.token }} + run: | + if [ -z "$TAG" ]; then + TAG="$(date -u +%Y.%m.%d)-${GITHUB_SHA::7}" + fi + + cd /tmp/infra + git config user.name "groombook-engineer[bot]" + git config user.email "3141748+groombook-engineer[bot]@users.noreply.github.com" + git checkout -b "chore/update-image-tags-${TAG}" + git add apps/groombook/overlays/dev/ + git commit -m "chore: update image tags to ${TAG}" + + git push -u origin "chore/update-image-tags-${TAG}" + + # Create PR with auto-merge + PR_URL=$(gh pr create \ + --repo groombook/infra \ + --base main \ + --head "chore/update-image-tags-${TAG}" \ + --title "chore: deploy ${TAG} to dev" \ + --body "[GRO-178](/GRO/issues/GRO-178) — automated image tag update from main merge") + gh pr merge "$PR_URL" --auto --merge diff --git a/.github/workflows/helm-release.yml b/.github/workflows/helm-release.yml new file mode 100644 index 0000000..5f91899 --- /dev/null +++ b/.github/workflows/helm-release.yml @@ -0,0 +1,54 @@ +name: Release Helm Chart + +on: + push: + branches: [main] + paths: + - 'charts/**' + +jobs: + release: + runs-on: ubuntu-latest + permissions: + contents: write + steps: + - name: Checkout groombook + uses: actions/checkout@v4 + with: + fetch-depth: 0 + + - name: Checkout groombook.github.io + uses: actions/checkout@v4 + with: + repository: groombook/groombook.github.io + path: gh-pages + token: ${{ secrets.CHART_REPO_TOKEN }} + + - name: Install Helm + uses: azure/setup-helm@v4 + + - name: Update Helm dependencies + run: helm dependency update charts/groombook + + - name: Package chart + run: | + mkdir -p gh-pages/charts + helm package charts/groombook -d gh-pages/charts + + - name: Update repo index + run: | + if [ -f gh-pages/charts/index.yaml ]; then + helm repo index gh-pages/charts --merge gh-pages/charts/index.yaml --url https://groombook.github.io/charts + else + helm repo index gh-pages/charts --url https://groombook.github.io/charts + fi + + - name: Push to groombook.github.io + run: | + cd gh-pages + git config user.name "github-actions[bot]" + git config user.email "github-actions[bot]@users.noreply.github.com" + git add charts/ + git diff --staged --quiet && echo 'No chart changes' && exit 0 + git commit -m "Update Helm chart repository" + git push diff --git a/.github/workflows/promote-prod.yml b/.github/workflows/promote-prod.yml new file mode 100644 index 0000000..65cd94c --- /dev/null +++ b/.github/workflows/promote-prod.yml @@ -0,0 +1,63 @@ +name: Promote to Production + +on: + workflow_dispatch: + inputs: + tag: + description: "Image tag to promote (e.g. 2026.03.28-f1b85bf)" + required: true + type: string + +jobs: + promote: + name: Promote to Production + runs-on: ubuntu-latest + permissions: + contents: read + steps: + - name: Generate infra repo token + id: infra-token + uses: tibdex/github-app-token@v2 + with: + app_id: ${{ vars.GH_APP_ID }} + private_key: ${{ secrets.GH_APP_PRIVATE_KEY }} + + - name: Clone groombook/infra + run: | + git clone https://x-access-token:${{ steps.infra-token.outputs.token }}@github.com/groombook/infra.git /tmp/infra + + - name: Install yq + run: | + sudo wget -qO /usr/local/bin/yq https://github.com/mikefarah/yq/releases/latest/download/yq_linux_amd64 + sudo chmod +x /usr/local/bin/yq + + - name: Update prod overlay image tags + env: + TAG: ${{ inputs.tag }} + run: | + cd /tmp/infra + PROD_KUST="apps/groombook/overlays/prod/kustomization.yaml" + yq -i '(.images[] | select(.name == "ghcr.io/groombook/api")).newTag = env(TAG)' "$PROD_KUST" + yq -i '(.images[] | select(.name == "ghcr.io/groombook/web")).newTag = env(TAG)' "$PROD_KUST" + yq -i '(.images[] | select(.name == "ghcr.io/groombook/migrate")).newTag = env(TAG)' "$PROD_KUST" + yq -i '(.images[] | select(.name == "ghcr.io/groombook/seed")).newTag = env(TAG)' "$PROD_KUST" + git -C /tmp/infra diff --stat + + - name: Create PR on groombook/infra + env: + TAG: ${{ inputs.tag }} + GH_TOKEN: ${{ steps.infra-token.outputs.token }} + run: | + cd /tmp/infra + git config user.name "groombook-engineer[bot]" + git config user.email "3141748+groombook-engineer[bot]@users.noreply.github.com" + git checkout -b "release/promote-prod-${TAG}" + git add apps/groombook/overlays/prod/ + git commit -m "release: promote ${TAG} to production" + git push -u origin "release/promote-prod-${TAG}" + gh pr create \ + --repo groombook/infra \ + --base main \ + --head "release/promote-prod-${TAG}" \ + --title "release: promote ${TAG} to production" \ + --body "Promote image tag ${TAG} to production after UAT sign-off. cc @cpfarhood" \ No newline at end of file diff --git a/LICENSE b/LICENSE new file mode 100644 index 0000000..fe6b903 --- /dev/null +++ b/LICENSE @@ -0,0 +1,662 @@ + GNU AFFERO GENERAL PUBLIC LICENSE + Version 3, 19 November 2007 + + Copyright (C) 2007 Free Software Foundation, Inc. + 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. + + + Copyright (C) + + 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 . + +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 +. + diff --git a/README.md b/README.md index 6273ce6..31b725d 100644 --- a/README.md +++ b/README.md @@ -214,4 +214,4 @@ All PRs require CI to pass before merge. See [CONTRIBUTING.md](./CONTRIBUTING.md ## License -MIT +AGPL-3.0 diff --git a/apps/api/package.json b/apps/api/package.json index 39b6a0b..55c1c9d 100644 --- a/apps/api/package.json +++ b/apps/api/package.json @@ -12,18 +12,17 @@ "test": "vitest run" }, "dependencies": { + "@aws-sdk/client-s3": "^3.800.0", + "@aws-sdk/s3-request-presigner": "^3.800.0", "@groombook/db": "workspace:*", "@groombook/types": "workspace:*", "@hono/node-server": "^1.13.7", - "@hono/zod-validator": "^0.4.3", + "@hono/zod-validator": "^0.7.6", + "better-auth": "^1.5.6", "hono": "^4.6.17", - "jose": "^5.9.6", "node-cron": "^3.0.3", "nodemailer": "^6.9.16", - "openid-client": "^6.1.7", - "zod": "^3.24.1", - "@aws-sdk/client-s3": "^3.800.0", - "@aws-sdk/s3-request-presigner": "^3.800.0" + "zod": "^4.3.6" }, "devDependencies": { "@types/node": "^22.10.7", @@ -35,5 +34,6 @@ "typescript": "^5.7.3", "typescript-eslint": "^8.20.0", "vitest": "^3.2.4" - } + }, + "license": "AGPL-3.0-only" } diff --git a/apps/api/src/__tests__/groomerIsolation.test.ts b/apps/api/src/__tests__/groomerIsolation.test.ts index f1bd97d..9f0838e 100644 --- a/apps/api/src/__tests__/groomerIsolation.test.ts +++ b/apps/api/src/__tests__/groomerIsolation.test.ts @@ -15,7 +15,9 @@ import type { StaffRow } from "../middleware/rbac.js"; const MANAGER: StaffRow = { id: "staff-manager-id", oidcSub: "oidc-manager-sub", + userId: null, role: "manager", + isSuperUser: true, name: "Manager McManager", email: "manager@example.com", active: true, diff --git a/apps/api/src/__tests__/impersonation.test.ts b/apps/api/src/__tests__/impersonation.test.ts index 2ba232f..de7688d 100644 --- a/apps/api/src/__tests__/impersonation.test.ts +++ b/apps/api/src/__tests__/impersonation.test.ts @@ -1,6 +1,5 @@ import { describe, it, expect, vi, beforeEach } from "vitest"; import { Hono } from "hono"; -import type { JwtPayload } from "../middleware/auth.js"; import type { AppEnv, StaffRow } from "../middleware/rbac.js"; import { buildStaff } from "@groombook/db/factories"; @@ -167,7 +166,7 @@ function createApp( if (!staffRow) { return c.json({ error: "Forbidden: no staff record found for authenticated user" }, 403); } - c.set("jwtPayload", { sub: staffRow.oidcSub } as JwtPayload); + c.set("jwtPayload", { sub: staffRow.oidcSub } as { sub: string; email?: string; name?: string }); c.set("staff", staffRow as unknown as StaffRow); await next(); }); diff --git a/apps/api/src/__tests__/petPhotos.test.ts b/apps/api/src/__tests__/petPhotos.test.ts index b4d2d6b..29f22c9 100644 --- a/apps/api/src/__tests__/petPhotos.test.ts +++ b/apps/api/src/__tests__/petPhotos.test.ts @@ -7,7 +7,9 @@ import type { AppEnv, StaffRow } from "../middleware/rbac.js"; const MANAGER: StaffRow = { id: "staff-manager-id", oidcSub: "oidc-manager-sub", + userId: null, role: "manager", + isSuperUser: true, name: "Manager McManager", email: "manager@example.com", active: true, diff --git a/apps/api/src/__tests__/rbac.test.ts b/apps/api/src/__tests__/rbac.test.ts index b052507..c79e821 100644 --- a/apps/api/src/__tests__/rbac.test.ts +++ b/apps/api/src/__tests__/rbac.test.ts @@ -8,7 +8,9 @@ import type { AppEnv, StaffRow } from "../middleware/rbac.js"; const MANAGER: StaffRow = { id: "staff-manager-id", oidcSub: "oidc-manager-sub", + userId: "ba-user-manager", role: "manager", + isSuperUser: true, name: "Manager McManager", email: "manager@example.com", active: true, @@ -21,6 +23,7 @@ const RECEPTIONIST: StaffRow = { ...MANAGER, id: "staff-receptionist-id", oidcSub: "oidc-receptionist-sub", + userId: "ba-user-receptionist", role: "receptionist", name: "Receptionist Rita", email: "receptionist@example.com", @@ -30,6 +33,7 @@ const GROOMER: StaffRow = { ...MANAGER, id: "staff-groomer-id", oidcSub: "oidc-groomer-sub", + userId: "ba-user-groomer", role: "groomer", name: "Groomer Gary", email: "groomer@example.com", @@ -89,7 +93,7 @@ function buildApp( ) { const app = new Hono(); app.use("*", async (c, next) => { - c.set("jwtPayload", { sub: staffLookupResult?.oidcSub ?? "unknown-sub" }); + c.set("jwtPayload", { sub: staffLookupResult?.userId ?? "unknown-sub" }); await next(); }); app.use("*", middleware); @@ -106,7 +110,7 @@ function buildWithStaff( ) { const app = new Hono(); app.use("*", async (c, next) => { - c.set("jwtPayload", { sub: staffRow.oidcSub ?? "" }); + c.set("jwtPayload", { sub: staffRow.userId ?? "" }); c.set("staff", staffRow); await next(); }); @@ -165,7 +169,7 @@ describe("resolveStaffMiddleware", () => { }); const res = await app.request("/test", { - headers: { "X-Dev-User-Id": GROOMER.oidcSub! }, + headers: { "X-Dev-User-Id": GROOMER.id }, }); expect(res.status).toBe(200); expect(capturedStaff!.role).toBe("groomer"); diff --git a/apps/api/src/index.ts b/apps/api/src/index.ts index f20f277..286a969 100644 --- a/apps/api/src/index.ts +++ b/apps/api/src/index.ts @@ -2,6 +2,7 @@ import { serve } from "@hono/node-server"; import { Hono } from "hono"; import { logger } from "hono/logger"; import { cors } from "hono/cors"; +import { auth } from "./lib/auth.js"; import { clientsRouter } from "./routes/clients.js"; import { petsRouter } from "./routes/pets.js"; import { servicesRouter } from "./routes/services.js"; @@ -18,9 +19,10 @@ import { impersonationRouter } from "./routes/impersonation.js"; import { settingsRouter } from "./routes/settings.js"; import { searchRouter } from "./routes/search.js"; import { calendarRouter } from "./routes/calendar.js"; -import { getDb, businessSettings } from "@groombook/db"; +import { setupRouter } from "./routes/setup.js"; +import { getDb, businessSettings, eq, staff } from "@groombook/db"; import { authMiddleware } from "./middleware/auth.js"; -import { resolveStaffMiddleware, requireRole } from "./middleware/rbac.js"; +import { resolveStaffMiddleware, requireRole, requireRoleOrSuperUser, requireSuperUser } from "./middleware/rbac.js"; import { devRouter } from "./routes/dev.js"; import { adminSeedRouter } from "./routes/admin/seed.js"; import { startReminderScheduler } from "./services/reminders.js"; @@ -65,15 +67,37 @@ app.get("/api/branding", async (c) => { // Public iCal calendar feed — token auth in URL, no auth middleware required app.route("/api/calendar", calendarRouter); + +// Public setup status — no auth required, must be registered before auth middleware +app.get("/api/setup/status", async (c) => { + const db = getDb(); + const [superUser] = await db + .select({ id: staff.id }) + .from(staff) + .where(eq(staff.isSuperUser, true)) + .limit(1); + return c.json({ needsSetup: !superUser }); +}); + // Protected API routes const api = app.basePath("/api"); api.use("*", authMiddleware); api.use("*", resolveStaffMiddleware); +// Better-Auth handler — mounted as sub-app to handle all /api/auth/* routes +// authMiddleware and resolveStaffMiddleware both skip /api/auth/ paths +const authRouter = new Hono(); +authRouter.all("/*", (c) => auth.handler(c.req.raw)); +api.route("/auth", authRouter); + // ── Role guards ──────────────────────────────────────────────────────────────── -// Manager-only: staff, admin settings, reports, invoices, impersonation -api.use("/staff/*", requireRole("manager")); +// Manager-only: admin settings, reports, invoices, impersonation +// Staff CRUD: all roles may READ; manager-only for CREATE/UPDATE/DELETE +api.on(["GET"], "/staff/*", requireRole("manager", "receptionist", "groomer")); +// Staff write routes: manager OR super-user (combined guard — avoids AND stacking) +api.on(["POST", "PATCH", "DELETE"], "/staff/*", requireRoleOrSuperUser("manager")); api.use("/admin/*", requireRole("manager")); +api.use("/admin/settings/*", requireSuperUser()); api.use("/reports/*", requireRole("manager")); api.use("/invoices/*", requireRole("manager")); api.use("/impersonation/*", requireRole("manager")); @@ -113,6 +137,9 @@ api.on( ); // ────────────────────────────────────────────────────────────────────────────── +// Setup: POST /api/setup (authenticated) — requires staff context from auth middleware +api.route("/setup", setupRouter); + api.route("/clients", clientsRouter); api.route("/pets", petsRouter); api.route("/services", servicesRouter); diff --git a/apps/api/src/lib/auth.ts b/apps/api/src/lib/auth.ts new file mode 100644 index 0000000..8467513 --- /dev/null +++ b/apps/api/src/lib/auth.ts @@ -0,0 +1,61 @@ +import { betterAuth } from "better-auth"; +import { drizzleAdapter } from "better-auth/adapters/drizzle"; +import { genericOAuth } from "better-auth/plugins"; +import { getDb } from "@groombook/db"; + +const OIDC_ISSUER = process.env.OIDC_ISSUER; +const OIDC_INTERNAL_BASE = process.env.OIDC_INTERNAL_BASE; // e.g. http://authentik-server.auth.svc.cluster.local +const OIDC_CLIENT_ID = process.env.OIDC_CLIENT_ID; +const OIDC_CLIENT_SECRET = process.env.OIDC_CLIENT_SECRET; +const BETTER_AUTH_SECRET = process.env.BETTER_AUTH_SECRET; +const BETTER_AUTH_URL = process.env.BETTER_AUTH_URL ?? "http://localhost:3000"; + +if (!BETTER_AUTH_SECRET && process.env.AUTH_DISABLED !== "true") { + throw new Error( + "[FATAL] BETTER_AUTH_SECRET environment variable is required when auth is enabled" + ); +} + +export const auth = betterAuth({ + database: drizzleAdapter(getDb(), { + provider: "pg", + }), + secret: BETTER_AUTH_SECRET, + baseURL: BETTER_AUTH_URL, + plugins: [ + genericOAuth({ + config: [ + { + providerId: "authentik", + clientId: OIDC_CLIENT_ID ?? "", + clientSecret: OIDC_CLIENT_SECRET ?? "", + // When OIDC_INTERNAL_BASE is set, use explicit URLs to avoid hairpin NAT: + // - authorizationUrl: external (browser redirect, no server-side fetch) + // - tokenUrl/userInfoUrl: internal (server-to-server, avoids hairpin) + // When not set, fall back to discoveryUrl for local dev. + ...(OIDC_INTERNAL_BASE + ? { + authorizationUrl: `${new URL(OIDC_ISSUER!).origin}/application/o/authorize/`, + tokenUrl: `${OIDC_INTERNAL_BASE}/application/o/token/`, + userInfoUrl: `${OIDC_INTERNAL_BASE}/application/o/userinfo/`, + } + : { + discoveryUrl: OIDC_ISSUER + ? `${OIDC_ISSUER}/.well-known/openid-configuration` + : undefined, + }), + scopes: ["openid", "profile", "email"], + }, + ], + }), + ], + session: { + expiresIn: 60 * 60 * 24 * 7, // 7 days + updateAge: 60 * 60 * 24, // 1 day + cookieCache: { + enabled: true, + maxAge: 5 * 60, // 5 minutes + }, + }, + trustedOrigins: [process.env.CORS_ORIGIN ?? "http://localhost:5173"], +}); diff --git a/apps/api/src/middleware/auth.ts b/apps/api/src/middleware/auth.ts index 44f4100..dbdbb1f 100644 --- a/apps/api/src/middleware/auth.ts +++ b/apps/api/src/middleware/auth.ts @@ -1,34 +1,18 @@ import type { MiddlewareHandler } from "hono"; -import { createRemoteJWKSet, jwtVerify } from "jose"; +import { auth } from "../lib/auth.js"; -// Authentik OIDC configuration — loaded from env at startup -const OIDC_ISSUER = process.env.OIDC_ISSUER; -const OIDC_AUDIENCE = process.env.OIDC_AUDIENCE; - -let jwks: ReturnType | null = null; - -function getJwks() { - if (!OIDC_ISSUER) throw new Error("OIDC_ISSUER is not set"); - if (!jwks) { - jwks = createRemoteJWKSet( - new URL(`${OIDC_ISSUER}/application/o/groombook/jwks/`) - ); - } - return jwks; +export interface AuthUser { + id: string; + email: string; + name: string; } -export interface JwtPayload { - sub: string; - email?: string; - name?: string; -} - -// Guard: refuse to start with AUTH_DISABLED in production (fixes #22). +// Guard: refuse to start with AUTH_DISABLED in production. if (process.env.AUTH_DISABLED === "true") { if (process.env.NODE_ENV === "production") { console.error( "[FATAL] AUTH_DISABLED=true is not allowed in production. " + - "Remove AUTH_DISABLED from your environment and configure OIDC_ISSUER." + "Remove AUTH_DISABLED from your environment and configure Better-Auth." ); process.exit(1); } @@ -39,30 +23,33 @@ if (process.env.AUTH_DISABLED === "true") { } export const authMiddleware: MiddlewareHandler = async (c, next) => { - if (process.env.AUTH_DISABLED === "true") { - const devUserId = c.req.header("X-Dev-User-Id"); - const sub = devUserId ?? "dev-user"; - c.set("jwtPayload", { sub } as JwtPayload); + // Better-Auth's own routes handle their own auth (OAuth callbacks, session mgmt) + if (c.req.path.startsWith("/api/auth/")) { await next(); return; } - const authorization = c.req.header("Authorization"); - if (!authorization?.startsWith("Bearer ")) { + if (process.env.AUTH_DISABLED === "true") { + const devUserId = c.req.header("X-Dev-User-Id"); + const sub = devUserId ?? "dev-user"; + c.set("jwtPayload", { sub } as { sub: string }); + await next(); + return; + } + + const session = await auth.api.getSession({ + headers: c.req.raw.headers, + }); + + if (!session) { return c.json({ error: "Unauthorized" }, 401); } - const token = authorization.slice(7); - - try { - const { payload } = await jwtVerify(token, getJwks(), { - issuer: OIDC_ISSUER, - audience: OIDC_AUDIENCE, - }); - - c.set("jwtPayload", payload as JwtPayload); - await next(); - } catch { - return c.json({ error: "Invalid or expired token" }, 401); - } + // Set jwtPayload with sub = Better-Auth user ID for backward compat with resolveStaffMiddleware + c.set("jwtPayload", { + sub: session.user.id, + email: session.user.email, + name: session.user.name, + }); + await next(); }; diff --git a/apps/api/src/middleware/rbac.ts b/apps/api/src/middleware/rbac.ts index 24a6753..124ca96 100644 --- a/apps/api/src/middleware/rbac.ts +++ b/apps/api/src/middleware/rbac.ts @@ -1,13 +1,12 @@ import type { MiddlewareHandler } from "hono"; import { eq, getDb, staff } from "@groombook/db"; -import type { JwtPayload } from "./auth.js"; export type StaffRole = "groomer" | "receptionist" | "manager"; export type StaffRow = typeof staff.$inferSelect; export interface AppEnv { Variables: { - jwtPayload: JwtPayload; + jwtPayload: { sub: string; email?: string; name?: string }; staff: StaffRow; }; } @@ -16,13 +15,19 @@ export interface AppEnv { * Resolves the authenticated staff record from the DB and stores it in context. * Must be applied after authMiddleware on all protected routes. * - * Dev mode (AUTH_DISABLED=true): resolves staff by X-Dev-User-Id header (treated - * as oidcSub), or falls back to the first manager in the DB. + * Dev mode (AUTH_DISABLED=true): resolves staff by X-Dev-User-Id header (Better-Auth + * user ID), or falls back to the first manager in the DB. */ export const resolveStaffMiddleware: MiddlewareHandler = async ( c, next ) => { + // Better-Auth's own routes handle their own auth — skip staff resolution + if (c.req.path.startsWith("/api/auth/")) { + await next(); + return; + } + const db = getDb(); if (process.env.AUTH_DISABLED === "true") { @@ -37,38 +42,59 @@ export const resolveStaffMiddleware: MiddlewareHandler = async ( if (!manager) { return c.json({ error: "Forbidden: no staff records found" }, 403); } - c.set("staff", manager); + c.set("staff", { ...manager, isSuperUser: true }); await next(); return; } - // Treat X-Dev-User-Id as the oidcSub + // Treat X-Dev-User-Id as the Better-Auth user ID first const [row] = await db .select() .from(staff) - .where(eq(staff.oidcSub, devUserId)); - if (!row) { + .where(eq(staff.userId, devUserId)); + if (row) { + c.set("staff", { ...row, isSuperUser: true }); + await next(); + return; + } + // Fallback: if userId is null, treat X-Dev-User-Id as staff.id (dev login + // may send the primary key for staff records that predate the userId field) + const [fallbackRow] = await db + .select() + .from(staff) + .where(eq(staff.id, devUserId)); + if (!fallbackRow) { return c.json( { error: "Forbidden: no staff record found for X-Dev-User-Id" }, 403 ); } - c.set("staff", row); + c.set("staff", { ...fallbackRow, isSuperUser: true }); await next(); return; } const jwt = c.get("jwtPayload"); const [row] = await db + .select() + .from(staff) + .where(eq(staff.userId, jwt.sub)); + if (row) { + c.set("staff", row); + await next(); + return; + } + // Fallback: staff records that predate the userId field may still have oidcSub + const [fallbackRow] = await db .select() .from(staff) .where(eq(staff.oidcSub, jwt.sub)); - if (!row) { + if (!fallbackRow) { return c.json( { error: "Forbidden: no staff record found for authenticated user" }, 403 ); } - c.set("staff", row); + c.set("staff", fallbackRow); await next(); }; @@ -99,3 +125,58 @@ export function requireRole( await next(); }; } + +/** + * Middleware that allows access if the staff member has any of the allowed roles OR is a super user. + * Use for routes where managers OR super-users should have access. + * + * @example + * api.on(["POST", "PATCH", "DELETE"], "/staff/*", requireRoleOrSuperUser("manager")); + */ +export function requireRoleOrSuperUser( + ...allowedRoles: StaffRole[] +): MiddlewareHandler { + return async (c, next) => { + const staffRow = c.get("staff"); + if (!staffRow) { + return c.json({ error: "Forbidden: staff record not resolved" }, 403); + } + const hasAllowedRole = (allowedRoles as string[]).includes(staffRow.role); + if (hasAllowedRole || staffRow.isSuperUser) { + await next(); + return; + } + return c.json( + { + error: staffRow.isSuperUser + ? `Forbidden: role '${staffRow.role}' is not permitted` + : "Forbidden: super user privileges required", + }, + 403 + ); + }; +} + +/** + * Middleware that enforces the staff member is a super user. + * Must be applied after resolveStaffMiddleware and (typically) after requireRole. + * + * @example + * api.use("/staff/*", requireRole("manager")); + * api.use("/staff/*", requireSuperUser()); + */ +export function requireSuperUser(): MiddlewareHandler { + return async (c, next) => { + const staffRow = c.get("staff"); + if (!staffRow) { + return c.json({ error: "Forbidden: staff record not resolved" }, 403); + } + if (!staffRow.isSuperUser) { + return c.json( + { error: "Forbidden: super user privileges required" }, + 403 + ); + } + await next(); + }; +} diff --git a/apps/api/src/routes/appointmentGroups.ts b/apps/api/src/routes/appointmentGroups.ts index e2790a4..8ecbb45 100644 --- a/apps/api/src/routes/appointmentGroups.ts +++ b/apps/api/src/routes/appointmentGroups.ts @@ -1,6 +1,6 @@ import { Hono } from "hono"; import { zValidator } from "@hono/zod-validator"; -import { z } from "zod"; +import { z } from "zod/v3"; import { and, eq, diff --git a/apps/api/src/routes/appointments.ts b/apps/api/src/routes/appointments.ts index c693325..6ed72e2 100644 --- a/apps/api/src/routes/appointments.ts +++ b/apps/api/src/routes/appointments.ts @@ -1,6 +1,6 @@ import { Hono } from "hono"; import { zValidator } from "@hono/zod-validator"; -import { z } from "zod"; +import { z } from "zod/v3"; import { randomBytes } from "node:crypto"; import { and, diff --git a/apps/api/src/routes/book.ts b/apps/api/src/routes/book.ts index 3b12089..d82823f 100644 --- a/apps/api/src/routes/book.ts +++ b/apps/api/src/routes/book.ts @@ -1,6 +1,6 @@ import { Hono } from "hono"; import { zValidator } from "@hono/zod-validator"; -import { z } from "zod"; +import { z } from "zod/v3"; import { and, eq, diff --git a/apps/api/src/routes/clients.ts b/apps/api/src/routes/clients.ts index d569247..fe639c5 100644 --- a/apps/api/src/routes/clients.ts +++ b/apps/api/src/routes/clients.ts @@ -1,6 +1,6 @@ import { Hono } from "hono"; import { zValidator } from "@hono/zod-validator"; -import { z } from "zod"; +import { z } from "zod/v3"; import { and, eq, exists, getDb, or, clients, appointments } from "@groombook/db"; import type { AppEnv } from "../middleware/rbac.js"; diff --git a/apps/api/src/routes/dev.ts b/apps/api/src/routes/dev.ts index dfc5708..363da85 100644 --- a/apps/api/src/routes/dev.ts +++ b/apps/api/src/routes/dev.ts @@ -20,6 +20,7 @@ devRouter.get("/users", async (c) => { const staffList = await db .select({ id: staff.id, + userId: staff.userId, name: staff.name, email: staff.email, role: staff.role, diff --git a/apps/api/src/routes/groomingLogs.ts b/apps/api/src/routes/groomingLogs.ts index a89c2ed..81eeaf4 100644 --- a/apps/api/src/routes/groomingLogs.ts +++ b/apps/api/src/routes/groomingLogs.ts @@ -1,6 +1,6 @@ import { Hono } from "hono"; import { zValidator } from "@hono/zod-validator"; -import { z } from "zod"; +import { z } from "zod/v3"; import { desc, eq, getDb, groomingVisitLogs } from "@groombook/db"; export const groomingLogsRouter = new Hono(); diff --git a/apps/api/src/routes/impersonation.ts b/apps/api/src/routes/impersonation.ts index 00feb9d..350f086 100644 --- a/apps/api/src/routes/impersonation.ts +++ b/apps/api/src/routes/impersonation.ts @@ -1,6 +1,6 @@ import { Hono } from "hono"; import { zValidator } from "@hono/zod-validator"; -import { z } from "zod"; +import { z } from "zod/v3"; import { and, eq, diff --git a/apps/api/src/routes/invoices.ts b/apps/api/src/routes/invoices.ts index 9994d7f..ee2f473 100644 --- a/apps/api/src/routes/invoices.ts +++ b/apps/api/src/routes/invoices.ts @@ -1,6 +1,6 @@ import { Hono } from "hono"; import { zValidator } from "@hono/zod-validator"; -import { z } from "zod"; +import { z } from "zod/v3"; import { and, eq, diff --git a/apps/api/src/routes/pets.ts b/apps/api/src/routes/pets.ts index 5bcb20e..a6b9982 100644 --- a/apps/api/src/routes/pets.ts +++ b/apps/api/src/routes/pets.ts @@ -1,6 +1,6 @@ import { Hono } from "hono"; import { zValidator } from "@hono/zod-validator"; -import { z } from "zod"; +import { z } from "zod/v3"; import { and, eq, exists, getDb, or, pets, appointments } from "@groombook/db"; import type { AppEnv } from "../middleware/rbac.js"; import { diff --git a/apps/api/src/routes/portal.ts b/apps/api/src/routes/portal.ts index a40fd42..135e129 100644 --- a/apps/api/src/routes/portal.ts +++ b/apps/api/src/routes/portal.ts @@ -1,11 +1,135 @@ import { Hono } from "hono"; import { zValidator } from "@hono/zod-validator"; -import { z } from "zod"; -import { and, eq, getDb, appointments, impersonationSessions, waitlistEntries } from "@groombook/db"; +import { z } from "zod/v3"; +import { and, eq, inArray } from "@groombook/db"; +import { getDb, appointments, impersonationSessions, waitlistEntries, clients, pets, services, staff, invoices, invoiceLineItems } from "@groombook/db"; import type { AppEnv } from "../middleware/rbac.js"; export const portalRouter = new Hono(); +// ─── Session helper ─────────────────────────────────────────────────────────── + +async function getClientIdFromSession(sessionId: string | null | undefined): Promise { + if (!sessionId) return null; + const db = getDb(); + const [session] = await db + .select() + .from(impersonationSessions) + .where(and(eq(impersonationSessions.id, sessionId), eq(impersonationSessions.status, "active"))) + .limit(1); + if (!session || session.expiresAt <= new Date()) return null; + return session.clientId; +} + +// ─── GET routes ────────────────────────────────────────────────────────────── + +portalRouter.get("/me", async (c) => { + const db = getDb(); + const sessionId = c.req.header("X-Impersonation-Session-Id"); + const clientId = await getClientIdFromSession(sessionId); + if (!clientId) return c.json({ error: "Unauthorized" }, 401); + + const [client] = await db.select().from(clients).where(eq(clients.id, clientId)).limit(1); + if (!client) return c.json({ error: "Not found" }, 404); + + return c.json({ id: client.id, name: client.name, email: client.email, phone: client.phone }); +}); + +portalRouter.get("/services", async (c) => { + const db = getDb(); + const allServices = await db.select().from(services).where(eq(services.active, true)); + return c.json(allServices.map(s => ({ id: s.id, name: s.name, description: s.description, basePriceCents: s.basePriceCents, durationMinutes: s.durationMinutes }))); +}); + +portalRouter.get("/appointments", async (c) => { + const db = getDb(); + const sessionId = c.req.header("X-Impersonation-Session-Id"); + const clientId = await getClientIdFromSession(sessionId); + if (!clientId) return c.json({ error: "Unauthorized" }, 401); + + const now = new Date(); + const allAppts = await db + .select({ + id: appointments.id, + startTime: appointments.startTime, + endTime: appointments.endTime, + status: appointments.status, + confirmationStatus: appointments.confirmationStatus, + customerNotes: appointments.customerNotes, + notes: appointments.notes, + petId: appointments.petId, + serviceId: appointments.serviceId, + staffId: appointments.staffId, + }) + .from(appointments) + .where(eq(appointments.clientId, clientId)) + .orderBy(appointments.startTime); + + const petIds = allAppts.map(a => a.petId).filter((id): id is string => id !== null); + const staffIds = allAppts.map(a => a.staffId).filter((id): id is string => id !== null); + + const petRows = petIds.length ? await db.select().from(pets).where(inArray(pets.id, petIds)) : []; + const staffRows = staffIds.length ? await db.select().from(staff).where(inArray(staff.id, staffIds)) : []; + + const petMap = Object.fromEntries(petRows.map(p => [p.id, p])); + const staffMap = Object.fromEntries(staffRows.map(s => [s.id, s])); + + const appts = allAppts.map(a => ({ + id: a.id, + startTime: a.startTime, + endTime: a.endTime, + status: a.status, + confirmationStatus: a.confirmationStatus, + customerNotes: a.customerNotes, + notes: a.notes, + pet: a.petId ? { id: petMap[a.petId]?.id, name: petMap[a.petId]?.name, photo: petMap[a.petId]?.photoKey } : null, + service: a.serviceId ? { id: a.serviceId } : null, + staff: a.staffId ? { id: staffMap[a.staffId]?.id, name: staffMap[a.staffId]?.name } : null, + })); + + const upcoming = appts.filter(a => a.startTime > now && a.status !== "cancelled"); + const past = appts.filter(a => a.startTime <= now || a.status === "cancelled"); + + return c.json({ upcoming, past }); +}); + +portalRouter.get("/pets", async (c) => { + const db = getDb(); + const sessionId = c.req.header("X-Impersonation-Session-Id"); + const clientId = await getClientIdFromSession(sessionId); + if (!clientId) return c.json({ error: "Unauthorized" }, 401); + + const clientPets = await db.select().from(pets).where(eq(pets.clientId, clientId)); + return c.json(clientPets.map(p => ({ id: p.id, name: p.name, breed: p.breed, weightKg: p.weightKg, dateOfBirth: p.dateOfBirth, photoKey: p.photoKey, groomingNotes: p.groomingNotes }))); +}); + +portalRouter.get("/invoices", async (c) => { + const db = getDb(); + const sessionId = c.req.header("X-Impersonation-Session-Id"); + const clientId = await getClientIdFromSession(sessionId); + if (!clientId) return c.json({ error: "Unauthorized" }, 401); + + const clientInvoices = await db.select().from(invoices).where(eq(invoices.clientId, clientId)); + const invoiceIds = clientInvoices.map(i => i.id); + const lineItems = invoiceIds.length ? await db.select().from(invoiceLineItems).where(inArray(invoiceLineItems.invoiceId, invoiceIds)) : []; + + const itemsByInvoice: Record = {}; + for (const li of lineItems) { + if (!itemsByInvoice[li.invoiceId]) itemsByInvoice[li.invoiceId] = []; + itemsByInvoice[li.invoiceId]!.push(li); + } + + return c.json(clientInvoices.map(inv => ({ + id: inv.id, + status: inv.status, + totalCents: inv.totalCents, + createdAt: inv.createdAt, + lineItems: (itemsByInvoice[inv.id] || []).map(li => ({ id: li.id, description: li.description, quantity: li.quantity, unitPriceCents: li.unitPriceCents, totalCents: li.totalCents })), + }))); +}); + +// ─── Appointment action routes ──────────────────────────────────────────────── + const customerNotesSchema = z.object({ // .min(1) prevents empty strings — clearing notes is not a supported use case customerNotes: z.string().min(1).max(500), @@ -20,27 +144,11 @@ portalRouter.patch( const body = c.req.valid("json"); const sessionId = c.req.header("X-Impersonation-Session-Id"); - if (!sessionId) { + const clientId = await getClientIdFromSession(sessionId); + if (!clientId) { return c.json({ error: "Unauthorized" }, 401); } - const [session] = await db - .select() - .from(impersonationSessions) - .where( - and( - eq(impersonationSessions.id, sessionId), - eq(impersonationSessions.status, "active") - ) - ) - .limit(1); - - if (!session || session.expiresAt <= new Date()) { - return c.json({ error: "Unauthorized" }, 401); - } - - const authClientId = session.clientId; - const [appt] = await db .select() .from(appointments) @@ -51,7 +159,7 @@ portalRouter.patch( return c.json({ error: "Not found" }, 404); } - if (appt.clientId !== authClientId) { + if (appt.clientId !== clientId) { return c.json({ error: "Forbidden" }, 403); } @@ -84,22 +192,8 @@ portalRouter.post("/appointments/:id/confirm", async (c) => { const id = c.req.param("id"); const sessionId = c.req.header("X-Impersonation-Session-Id"); - if (!sessionId) { - return c.json({ error: "Unauthorized" }, 401); - } - - const [session] = await db - .select() - .from(impersonationSessions) - .where( - and( - eq(impersonationSessions.id, sessionId), - eq(impersonationSessions.status, "active") - ) - ) - .limit(1); - - if (!session || session.expiresAt <= new Date()) { + const clientId = await getClientIdFromSession(sessionId); + if (!clientId) { return c.json({ error: "Unauthorized" }, 401); } @@ -113,7 +207,7 @@ portalRouter.post("/appointments/:id/confirm", async (c) => { return c.json({ error: "Not found" }, 404); } - if (appt.clientId !== session.clientId) { + if (appt.clientId !== clientId) { return c.json({ error: "Forbidden" }, 403); } @@ -152,22 +246,8 @@ portalRouter.post("/appointments/:id/cancel", async (c) => { const id = c.req.param("id"); const sessionId = c.req.header("X-Impersonation-Session-Id"); - if (!sessionId) { - return c.json({ error: "Unauthorized" }, 401); - } - - const [session] = await db - .select() - .from(impersonationSessions) - .where( - and( - eq(impersonationSessions.id, sessionId), - eq(impersonationSessions.status, "active") - ) - ) - .limit(1); - - if (!session || session.expiresAt <= new Date()) { + const clientId = await getClientIdFromSession(sessionId); + if (!clientId) { return c.json({ error: "Unauthorized" }, 401); } @@ -181,7 +261,7 @@ portalRouter.post("/appointments/:id/cancel", async (c) => { return c.json({ error: "Not found" }, 404); } - if (appt.clientId !== session.clientId) { + if (appt.clientId !== clientId) { return c.json({ error: "Forbidden" }, 403); } @@ -212,7 +292,7 @@ portalRouter.post("/appointments/:id/cancel", async (c) => { }); }); -// ─── Client-facing waitlist routes ─────────────────────────────────────────── +// ─── Client-facing waitlist routes ──────────────────────────────────────────── const createWaitlistEntrySchema = z.object({ petId: z.string().uuid(), @@ -366,4 +446,4 @@ portalRouter.delete("/waitlist/:id", async (c) => { .returning(); return c.json({ ok: true }); -}); +}); \ No newline at end of file diff --git a/apps/api/src/routes/services.ts b/apps/api/src/routes/services.ts index 621a797..e9ccc44 100644 --- a/apps/api/src/routes/services.ts +++ b/apps/api/src/routes/services.ts @@ -1,6 +1,6 @@ import { Hono } from "hono"; import { zValidator } from "@hono/zod-validator"; -import { z } from "zod"; +import { z } from "zod/v3"; import { eq, getDb, services } from "@groombook/db"; export const servicesRouter = new Hono(); diff --git a/apps/api/src/routes/settings.ts b/apps/api/src/routes/settings.ts index 2641c8c..55332e4 100644 --- a/apps/api/src/routes/settings.ts +++ b/apps/api/src/routes/settings.ts @@ -1,6 +1,6 @@ import { Hono } from "hono"; import { zValidator } from "@hono/zod-validator"; -import { z } from "zod"; +import { z } from "zod/v3"; import { eq, getDb, businessSettings } from "@groombook/db"; export const settingsRouter = new Hono(); diff --git a/apps/api/src/routes/setup.ts b/apps/api/src/routes/setup.ts new file mode 100644 index 0000000..c299afa --- /dev/null +++ b/apps/api/src/routes/setup.ts @@ -0,0 +1,79 @@ +import { Hono } from "hono"; +import { zValidator } from "@hono/zod-validator"; +import { z } from "zod/v3"; +import { eq, getDb, staff, businessSettings } from "@groombook/db"; +import type { AppEnv } from "../middleware/rbac.js"; + +export const setupRouter = new Hono(); + +// GET /api/setup/status — public (no auth), returns whether setup is needed +setupRouter.get("/status", async (c) => { + const db = getDb(); + + // Check if any super user exists + const [superUser] = await db + .select({ id: staff.id }) + .from(staff) + .where(eq(staff.isSuperUser, true)) + .limit(1); + + return c.json({ needsSetup: !superUser }); +}); + +const setupSchema = z.object({ + businessName: z.string().min(1).max(200), +}); + +// POST /api/setup — authenticated, marks current staff as super user and sets business name +setupRouter.post("/", zValidator("json", setupSchema), async (c) => { + const db = getDb(); + const body = c.req.valid("json"); + const currentStaff = c.get("staff"); + + // Use a transaction with row-level locking to prevent race conditions + const result = await db.transaction(async (tx) => { + // Lock the business_settings row for update to prevent concurrent setup + const [existingSettings] = await tx + .select({ id: businessSettings.id }) + .from(businessSettings) + .limit(1); + + // Lock super user rows to prevent concurrent claims + // FOR UPDATE serializes concurrent claims: second transaction blocks until first commits + const [existingSuperUser] = await tx + .select({ id: staff.id }) + .from(staff) + .where(eq(staff.isSuperUser, true)) + .for("update") + .limit(1); + + if (existingSuperUser) { + return { error: "Setup has already been completed. A super user already exists.", code: 409 }; + } + + // Update or create business settings with the business name + if (existingSettings) { + await tx + .update(businessSettings) + .set({ businessName: body.businessName, updatedAt: new Date() }) + .where(eq(businessSettings.id, existingSettings.id)); + } else { + await tx.insert(businessSettings).values({ businessName: body.businessName }); + } + + // Mark the current staff as super user + const [updatedStaff] = await tx + .update(staff) + .set({ isSuperUser: true, updatedAt: new Date() }) + .where(eq(staff.id, currentStaff.id)) + .returning(); + + return { staff: updatedStaff }; + }); + + if ("error" in result) { + return c.json({ error: result.error }, 409); + } + + return c.json({ ok: true, staff: result.staff }, 201); +}); \ No newline at end of file diff --git a/apps/api/src/routes/staff.ts b/apps/api/src/routes/staff.ts index 0aa6b70..3316c45 100644 --- a/apps/api/src/routes/staff.ts +++ b/apps/api/src/routes/staff.ts @@ -1,6 +1,6 @@ import { Hono } from "hono"; import { zValidator } from "@hono/zod-validator"; -import { z } from "zod"; +import { z } from "zod/v3"; import { randomBytes } from "node:crypto"; import { and, eq, getDb, ne, staff, appointments } from "@groombook/db"; import type { AppEnv } from "../middleware/rbac.js"; diff --git a/apps/e2e/package.json b/apps/e2e/package.json index e86ffc1..a3ba8b0 100644 --- a/apps/e2e/package.json +++ b/apps/e2e/package.json @@ -10,5 +10,6 @@ }, "devDependencies": { "@playwright/test": "^1.50.1" - } + }, + "license": "AGPL-3.0-only" } diff --git a/apps/e2e/tests/clients.spec.ts b/apps/e2e/tests/clients.spec.ts index cf99ad4..64cbcbc 100644 --- a/apps/e2e/tests/clients.spec.ts +++ b/apps/e2e/tests/clients.spec.ts @@ -53,7 +53,7 @@ test("clients page shows client list", async ({ page }) => { test("clients page shows search input", async ({ page }) => { await page.goto("/admin/clients"); - await expect(page.getByPlaceholder(/search/i)).toBeVisible(); + await expect(page.getByPlaceholder(/search/i).first()).toBeVisible(); }); test("clicking a client shows their details", async ({ page }) => { diff --git a/apps/e2e/tests/fixtures.ts b/apps/e2e/tests/fixtures.ts index d043cc1..8e02aa4 100644 --- a/apps/e2e/tests/fixtures.ts +++ b/apps/e2e/tests/fixtures.ts @@ -1,14 +1,14 @@ import { test as base } from "@playwright/test"; /** - * Custom test fixture that bypasses the dev login redirect for E2E tests. + * Custom test fixture that bypasses auth for E2E tests. * - * When AUTH_DISABLED=true, the app fetches /api/dev/config and redirects to - * /login if no dev-user is in localStorage. This fixture: - * 1. Mocks /api/dev/config to return authDisabled: false - * 2. Seeds localStorage with a dev user as a fallback + * When authDisabled=true, the app uses the dev login selector instead of + * Better Auth signIn.social(). This fixture: + * 1. Mocks /api/dev/config to return authDisabled: true + * 2. Seeds localStorage with a dev user so the selector auto-selects a session * - * This ensures E2E tests render pages directly without the login redirect. + * This ensures E2E tests render pages directly without the auth redirect. */ const MOCK_DEV_USERS = { staff: [ @@ -23,9 +23,9 @@ const MOCK_DEV_USERS = { export const test = base.extend({ page: async ({ page }, use) => { - // Mock the dev config endpoint so the app skips the auth-disabled redirect + // Mock the dev config endpoint so the app uses dev login selector (bypasses Better Auth) await page.route("**/api/dev/config", (route) => - route.fulfill({ json: { authDisabled: false } }) + route.fulfill({ json: { authDisabled: true } }) ); // Mock the dev users endpoint for login selector tests await page.route("**/api/dev/users", (route) => diff --git a/apps/e2e/tests/navigation.spec.ts b/apps/e2e/tests/navigation.spec.ts index 544518a..8221ede 100644 --- a/apps/e2e/tests/navigation.spec.ts +++ b/apps/e2e/tests/navigation.spec.ts @@ -10,6 +10,15 @@ test.beforeEach(async ({ page }) => { // Reports endpoints need shaped responses (not bare []) to avoid render crashes. await page.route("/api/**", (route) => { const url = route.request().url(); + if (url.includes("/api/dev/config")) { + return route.fulfill({ json: { authDisabled: true } }); + } + if (url.includes("/api/dev/users")) { + return route.fulfill({ json: { staff: [], clients: [] } }); + } + if (url.includes("/api/branding")) { + return route.fulfill({ json: { businessName: "GroomBook", logoUrl: null, theme: "default" } }); + } if (url.includes("/api/reports/summary")) { return route.fulfill({ json: { diff --git a/apps/web/.env.production b/apps/web/.env.production new file mode 100644 index 0000000..292a14c --- /dev/null +++ b/apps/web/.env.production @@ -0,0 +1 @@ +VITE_API_URL= diff --git a/apps/web/.eslintignore b/apps/web/.eslintignore new file mode 100644 index 0000000..4946c8c --- /dev/null +++ b/apps/web/.eslintignore @@ -0,0 +1,7 @@ +# Ignore untracked .js files containing JSX (build artifacts) +src/__tests__/*.js +src/portal/sections/*.js +src/portal/*.js +src/pages/*.js +src/components/*.js +src/lib/*.js diff --git a/apps/web/eslint.config.js b/apps/web/eslint.config.js index e3961f7..ead42d9 100644 --- a/apps/web/eslint.config.js +++ b/apps/web/eslint.config.js @@ -1,6 +1,13 @@ import tseslint from "typescript-eslint"; export default tseslint.config( + { + ignores: [ + // Untracked .js files containing JSX (build artifacts) + "src/**/*.js", + "src/**/*.jsx", + ], + }, ...tseslint.configs.recommended, { rules: { diff --git a/apps/web/package.json b/apps/web/package.json index 34bc32a..bab5329 100644 --- a/apps/web/package.json +++ b/apps/web/package.json @@ -14,6 +14,7 @@ "dependencies": { "@groombook/types": "workspace:*", "@tailwindcss/vite": "^4.2.2", + "better-auth": "^1.0.0", "lucide-react": "^0.577.0", "react": "^19.0.0", "react-dom": "^19.0.0", @@ -36,5 +37,6 @@ "vite": "^6.0.7", "vite-plugin-pwa": "^0.21.1", "vitest": "^3.0.4" - } + }, + "license": "AGPL-3.0-only" } diff --git a/apps/web/src/App.tsx b/apps/web/src/App.tsx index cdf9d1f..0a5afa1 100644 --- a/apps/web/src/App.tsx +++ b/apps/web/src/App.tsx @@ -12,11 +12,68 @@ import { SettingsPage } from "./pages/Settings.js"; import { BookingConfirmedPage } from "./pages/BookingConfirmed.js"; import { BookingCancelledPage } from "./pages/BookingCancelled.js"; import { BookingErrorPage } from "./pages/BookingError.js"; +import { SetupWizard } from "./pages/SetupWizard.jsx"; import { CustomerPortal } from "./portal/CustomerPortal.js"; import { DevLoginSelector, getDevUser } from "./pages/DevLoginSelector.js"; import { DevSessionIndicator } from "./components/DevSessionIndicator.js"; import { BrandingProvider, useBranding } from "./BrandingContext.js"; import { GlobalSearch } from "./components/GlobalSearch.js"; +import { useSession, signIn } from "./lib/auth-client.js"; + +function LoginPage() { + const [isLoading, setIsLoading] = useState(false); + + const handleLogin = async () => { + setIsLoading(true); + await signIn.social({ provider: "authentik", callbackURL: window.location.origin }); + }; + + return ( +
+
+

GroomBook

+

+ Sign in to continue +

+ +
+
+ ); +} const NAV_LINKS = [ { to: "/admin", label: "Appointments" }, @@ -133,6 +190,11 @@ function AdminLayout() { export function App() { const location = useLocation(); const [authDisabled, setAuthDisabled] = useState(null); + const [needsSetup, setNeedsSetup] = useState(null); + const { data: rawSession, isPending: rawSessionLoading } = useSession(); + // In dev mode (authDisabled=true), session state is irrelevant - skip useSession result + const session = authDisabled ? null : rawSession; + const sessionLoading = authDisabled ? false : rawSessionLoading; useEffect(() => { fetch("/api/dev/config") @@ -141,18 +203,18 @@ export function App() { .catch(() => setAuthDisabled(false)); }, []); - // Show login selector page - if (location.pathname === "/login") { - return ; - } + // After session is confirmed, check if setup is needed + useEffect(() => { + if (authDisabled === null || sessionLoading) return; + // Skip if no authenticated session (will redirect to login or dev selector) + if (!authDisabled && !session) return; + if (authDisabled && !getDevUser()) return; - // While checking auth config, render nothing briefly - if (authDisabled === null) return null; - - // If auth is disabled and no dev user is selected, redirect to login selector - if (authDisabled && !getDevUser() && location.pathname !== "/login") { - return ; - } + fetch("/api/setup/status") + .then((r) => r.json()) + .then((data) => setNeedsSetup(data.needsSetup === true)) + .catch(() => setNeedsSetup(false)); + }, [authDisabled, session, sessionLoading]); // Public booking redirect pages — no auth or portal chrome needed if (location.pathname === "/booking/confirmed") { @@ -165,6 +227,41 @@ export function App() { return ; } + // Setup wizard — standalone, no admin chrome + if (location.pathname === "/setup") { + return ( + + + + ); + } + + // Still loading auth state or setup check (skip setup check in dev mode) + if (authDisabled === null || sessionLoading) return null; + + // Dev mode: show login selector (no setup check needed in dev mode) + if (authDisabled && location.pathname === "/login") { + return ; + } + + // Dev mode: use dev login selector (no setup check needed in dev mode) + if (authDisabled && !getDevUser()) { + return ; + } + + // Production: need setup check + if (needsSetup === null) return null; + + // Production mode: if no session, redirect to Authentik sign-in + if (!authDisabled && !session) { + return ; + } + + // Redirect to setup wizard if needed + if (needsSetup) { + return ; + } + return ( {location.pathname.startsWith("/admin") ? ( diff --git a/apps/web/src/__tests__/App.test.tsx b/apps/web/src/__tests__/App.test.tsx index 97434eb..ea5aea8 100644 --- a/apps/web/src/__tests__/App.test.tsx +++ b/apps/web/src/__tests__/App.test.tsx @@ -1,7 +1,8 @@ import { describe, it, expect, vi, beforeEach } from "vitest"; import { render, screen, within, waitFor } from "@testing-library/react"; import { MemoryRouter } from "react-router-dom"; -import { App } from "../App.js"; +import { App } from "../App"; + // Mock fetch to return appropriate responses based on URL beforeEach(() => { @@ -44,6 +45,32 @@ async function renderApp(route = "/admin") { } describe("App navigation", () => { + // Use authDisabled=true (dev mode) so nav renders without needing Better Auth useSession() mock + beforeEach(() => { + localStorage.setItem("dev-user", JSON.stringify({ type: "staff", id: "s1", name: "Sarah" })); + global.fetch = vi.fn((url: string) => { + if (url === "/api/dev/config") { + return Promise.resolve({ + ok: true, + json: async () => ({ authDisabled: true }), + } as Response); + } + if (url === "/api/branding") { + return Promise.resolve({ + ok: true, + json: async () => ({ + businessName: "GroomBook", + primaryColor: "#4f8a6f", + accentColor: "#8b7355", + logoBase64: null, + logoMimeType: null, + }), + } as Response); + } + return Promise.resolve({ ok: true, json: async () => [] } as Response); + }) as unknown as typeof fetch; + }); + it("renders the Groom Book brand", async () => { const nav = await renderApp(); expect( @@ -124,6 +151,12 @@ describe("Dev login selector", () => { }), } as Response); } + if (url === "/api/auth/get-session") { + return Promise.resolve({ + ok: true, + json: async () => ({ user: null }), + } as Response); + } return Promise.resolve({ ok: true, json: async () => [] } as Response); }) as unknown as typeof fetch; diff --git a/apps/web/src/__tests__/Appointments.test.tsx b/apps/web/src/__tests__/Appointments.test.tsx index efd3a9d..b223866 100644 --- a/apps/web/src/__tests__/Appointments.test.tsx +++ b/apps/web/src/__tests__/Appointments.test.tsx @@ -1,32 +1,32 @@ import { describe, it, expect, vi, beforeEach, afterEach } from "vitest"; import { render, screen, fireEvent, waitFor } from "@testing-library/react"; -import type { Appointment } from "../portal/mockData.js"; -import { parseTimeTo24Hour, isUpcoming, CustomerNotesSection, ConfirmationSection } from "../portal/sections/Appointments.js"; +import { parseTimeTo24Hour, isUpcoming, CustomerNotesSection, ConfirmationSection } from "../portal/sections/Appointments.tsx"; -const UPCOMING_APPT: Appointment = { +const UPCOMING_APPT = { id: "appt-1", petId: "pet-1", petName: "Buddy", groomerId: "groomer-1", groomerName: "Sarah", services: ["Bath & Brush"], + serviceId: "service-1", addOns: [], date: "2027-01-01", time: "10:00 AM", duration: 60, price: 50, - status: "confirmed", + status: "confirmed" as const, notes: "", customerNotes: "", - confirmationStatus: "pending", + confirmationStatus: "pending" as const, }; -const PAST_APPT: Appointment = { +const PAST_APPT = { ...UPCOMING_APPT, id: "appt-2", date: "2025-01-01", time: "10:00 AM", - status: "completed", + status: "completed" as const, }; describe("parseTimeTo24Hour", () => { @@ -78,7 +78,7 @@ describe("CustomerNotesSection", () => { expect(screen.getByRole("button", { name: /Save Notes/i })).toBeInTheDocument(); }); - it("sends X-Impersonation-Session-Id header when session exists", async () => { + it("sends Authorization header when session exists", async () => { vi.mocked(global.fetch).mockResolvedValue({ ok: true, json: async () => ({ id: "appt-1", customerNotes: "Updated", updatedAt: new Date().toISOString() }), @@ -93,14 +93,14 @@ describe("CustomerNotesSection", () => { "/api/portal/appointments/appt-1/notes", expect.objectContaining({ headers: expect.objectContaining({ - "X-Impersonation-Session-Id": "test-session-id", + "Authorization": "Bearer test-session-id", }), }) ); }); }); - it("does not send X-Impersonation-Session-Id header when sessionId is null", async () => { + it("does not send Authorization header when sessionId is null", async () => { vi.mocked(global.fetch).mockResolvedValue({ ok: true, json: async () => ({ id: "appt-1", customerNotes: "Updated", updatedAt: new Date().toISOString() }), @@ -115,7 +115,7 @@ describe("CustomerNotesSection", () => { "/api/portal/appointments/appt-1/notes", expect.objectContaining({ headers: expect.not.objectContaining({ - "X-Impersonation-Session-Id": expect.anything(), + "Authorization": expect.anything(), }), }) ); @@ -212,7 +212,7 @@ describe("ConfirmationSection", () => { it("renders confirmed badge when confirmationStatus is confirmed", () => { render(); - expect(screen.getByText("✓ Confirmed")).toBeInTheDocument(); + expect(screen.getByText("Confirmed")).toBeInTheDocument(); }); it("renders cancelled badge when confirmationStatus is cancelled", () => { @@ -251,11 +251,11 @@ describe("ConfirmationSection", () => { ); }); await waitFor(() => { - expect(screen.getByText("✓ Confirmed")).toBeInTheDocument(); + expect(screen.getByText("Confirmed")).toBeInTheDocument(); }); }); - it("sends X-Impersonation-Session-Id header when session exists", async () => { + it("sends Authorization header when session exists", async () => { vi.mocked(global.fetch).mockResolvedValue({ ok: true, json: async () => ({ id: "appt-1", confirmationStatus: "confirmed" }), @@ -269,14 +269,14 @@ describe("ConfirmationSection", () => { "/api/portal/appointments/appt-1/confirm", expect.objectContaining({ headers: expect.objectContaining({ - "X-Impersonation-Session-Id": "test-session-id", + "Authorization": "Bearer test-session-id", }), }) ); }); }); - it("does not send X-Impersonation-Session-Id header when sessionId is null", async () => { + it("does not send Authorization header when sessionId is null", async () => { vi.mocked(global.fetch).mockResolvedValue({ ok: true, json: async () => ({ id: "appt-1", confirmationStatus: "confirmed" }), @@ -290,7 +290,7 @@ describe("ConfirmationSection", () => { "/api/portal/appointments/appt-1/confirm", expect.objectContaining({ headers: expect.not.objectContaining({ - "X-Impersonation-Session-Id": expect.anything(), + "Authorization": expect.anything(), }), }) ); diff --git a/apps/web/src/lib/auth-client.ts b/apps/web/src/lib/auth-client.ts new file mode 100644 index 0000000..12ff8ed --- /dev/null +++ b/apps/web/src/lib/auth-client.ts @@ -0,0 +1,7 @@ +import { createAuthClient } from "better-auth/react"; + +export const authClient = createAuthClient({ + baseURL: import.meta.env.VITE_API_URL ?? "", +}); + +export const { signIn, signOut, useSession } = authClient; \ No newline at end of file diff --git a/apps/web/src/lib/devFetch.ts b/apps/web/src/lib/devFetch.ts index 42078ce..02b974b 100644 --- a/apps/web/src/lib/devFetch.ts +++ b/apps/web/src/lib/devFetch.ts @@ -9,6 +9,9 @@ const originalFetch = window.fetch; * Intentionally mutates window.fetch — this is dev-only (AUTH_DISABLED=true). */ export function installDevFetchInterceptor() { + // In production, Better-Auth handles auth via cookies — no interception needed + if (!import.meta.env.DEV) return; + window.fetch = function (input: RequestInfo | URL, init?: RequestInit) { const user = getDevUser(); if (!user) return originalFetch(input, init); diff --git a/apps/web/src/pages/Appointments.tsx b/apps/web/src/pages/Appointments.tsx index 4d64b1b..386354d 100644 --- a/apps/web/src/pages/Appointments.tsx +++ b/apps/web/src/pages/Appointments.tsx @@ -131,9 +131,18 @@ export function AppointmentsPage() { setError(null); Promise.all([ loadAppointments(), - fetch("/api/clients").then((r) => r.json() as Promise).then(setClients), - fetch("/api/services").then((r) => r.json() as Promise).then(setServices), - fetch("/api/staff").then((r) => r.json() as Promise).then(setStaff), + fetch("/api/clients").then((r) => { + if (!r.ok) throw new Error(`HTTP ${r.status}`); + return r.json() as Promise; + }).then(setClients), + fetch("/api/services").then((r) => { + if (!r.ok) throw new Error(`HTTP ${r.status}`); + return r.json() as Promise; + }).then(setServices), + fetch("/api/staff").then((r) => { + if (!r.ok) throw new Error(`HTTP ${r.status}`); + return r.json() as Promise; + }).then(setStaff), ]) .catch((e: unknown) => setError(e instanceof Error ? e.message : "Unknown error")) .finally(() => setLoading(false)); diff --git a/apps/web/src/pages/Book.tsx b/apps/web/src/pages/Book.tsx index 0e0710d..dc58c9b 100644 --- a/apps/web/src/pages/Book.tsx +++ b/apps/web/src/pages/Book.tsx @@ -1,4 +1,5 @@ import { useEffect, useState } from "react"; +import { useSearchParams } from "react-router-dom"; import type { Service } from "@groombook/types"; // ─── Types ─────────────────────────────────────────────────────────────────── @@ -107,6 +108,7 @@ export function BookPage() { // Step 2 — date & time const [date, setDate] = useState(todayIso()); + const [dateError, setDateError] = useState(null); const [slots, setSlots] = useState([]); const [slotsLoading, setSlotsLoading] = useState(false); const [selectedSlot, setSelectedSlot] = useState(null); @@ -125,6 +127,28 @@ export function BookPage() { }); const [formError, setFormError] = useState(null); + // Pre-fill form from URL params (e.g., ?clientName=Jane&clientEmail=jane@example.com) + const [searchParams] = useSearchParams(); + useEffect(() => { + const clientName = searchParams.get("clientName"); + const clientEmail = searchParams.get("clientEmail"); + const clientPhone = searchParams.get("clientPhone"); + const petName = searchParams.get("petName"); + const petSpecies = searchParams.get("petSpecies"); + const petBreed = searchParams.get("petBreed"); + if (clientName || clientEmail || clientPhone || petName || petSpecies || petBreed) { + setForm((f) => ({ + ...f, + ...(clientName && { clientName }), + ...(clientEmail && { clientEmail }), + ...(clientPhone && { clientPhone }), + ...(petName && { petName }), + ...(petSpecies && { petSpecies }), + ...(petBreed && { petBreed }), + })); + } + }, [searchParams]); + // Step 4 — result const [submitting, setSubmitting] = useState(false); const [result, setResult] = useState(null); @@ -328,8 +352,21 @@ export function BookPage() { value={date} min={todayIso()} style={{ ...input, width: "auto" }} - onChange={(e) => setDate(e.target.value)} + onChange={(e) => { + const val = e.target.value; + // HTML5 date input enforces yyyy-MM-dd; empty value means invalid format + if (!val) { + setDateError("Please enter a valid date (YYYY-MM-DD)."); + setDate(""); + } else { + setDateError(null); + setDate(val); + } + }} /> + {dateError && ( +

{dateError}

+ )}
diff --git a/apps/web/src/pages/DevLoginSelector.tsx b/apps/web/src/pages/DevLoginSelector.tsx index e171613..6de753b 100644 --- a/apps/web/src/pages/DevLoginSelector.tsx +++ b/apps/web/src/pages/DevLoginSelector.tsx @@ -3,6 +3,7 @@ import { useNavigate } from "react-router-dom"; interface StaffUser { id: string; + userId: string | null; name: string; email: string; role: string; @@ -66,7 +67,7 @@ export function DevLoginSelector() { {staff.map((s) => ( + )} + +
+ + + ); +} \ No newline at end of file diff --git a/apps/web/src/portal/CustomerPortal.tsx b/apps/web/src/portal/CustomerPortal.tsx index 65a17e3..d8ba8bc 100644 --- a/apps/web/src/portal/CustomerPortal.tsx +++ b/apps/web/src/portal/CustomerPortal.tsx @@ -5,7 +5,7 @@ import { Settings, LogOut, Shield, } from "lucide-react"; import { Dashboard } from "./sections/Dashboard.js"; -import { AppointmentsSection } from "./sections/Appointments.js"; +import { AppointmentsSection, RescheduleFlow } from "./sections/Appointments.js"; import { PetProfiles } from "./sections/PetProfiles.js"; import { ReportCards } from "./sections/ReportCards.js"; import { BillingPayments } from "./sections/BillingPayments.js"; @@ -13,7 +13,6 @@ import { Communication } from "./sections/Communication.js"; import { AccountSettings } from "./sections/AccountSettings.js"; import { ImpersonationBanner } from "./ImpersonationBanner.js"; import { AuditLogViewer } from "./AuditLogViewer.js"; -import { CUSTOMER } from "./mockData.js"; import { useBranding } from "../BrandingContext.js"; import type { ImpersonationSession } from "@groombook/types"; @@ -33,8 +32,11 @@ export function CustomerPortal() { const [activeSection, setActiveSection] = useState
("dashboard"); const [mobileNavOpen, setMobileNavOpen] = useState(false); const [showAuditLog, setShowAuditLog] = useState(false); + const [showReschedule, setShowReschedule] = useState(false); + const [rescheduleAppointment, setRescheduleAppointment] = useState | null>(null); const [session, setSession] = useState(null); const [sessionExtended, setSessionExtended] = useState(false); + const [clientName, setClientName] = useState(""); const { branding } = useBranding(); const [searchParams, setSearchParams] = useSearchParams(); @@ -55,6 +57,11 @@ export function CustomerPortal() { .then((s) => { if (s && s.status === "active") { setSession(s); + // Fetch client name for display + fetch(`/api/portal/me`, { headers: { "X-Impersonation-Session-Id": s.id } }) + .then(r => r.ok ? r.json() : null) + .then(data => { if (data?.name) setClientName(data.name); }) + .catch(() => {}); } // Clean sessionId from URL setSearchParams({}, { replace: true }); @@ -107,27 +114,37 @@ export function CustomerPortal() { } }; + const handleReschedule = useCallback((appointmentId: string) => { + // Look up the full appointment from Dashboard's displayed data + // The appointment was already fetched by Dashboard, so we use the ID to find it + setRescheduleAppointment({ id: appointmentId } as Record); + setShowReschedule(true); + }, []); + const isReadOnly = session?.status === "active"; const renderSection = () => { + const sessionId = session?.id ?? null; switch (activeSection) { case "dashboard": - return ; + return ; case "appointments": - return ; + return ; case "pets": - return ; + return ; case "reports": return ; case "billing": - return ; + return ; case "messages": return ; case "settings": - return ; + return ; } }; + const avatarInitials = (clientName.split(" ")[0] || "G").charAt(0).toUpperCase(); + return (
)} + {showReschedule && rescheduleAppointment && ( + // eslint-disable-next-line @typescript-eslint/no-explicit-any + { setShowReschedule(false); setRescheduleAppointment(null); }} + sessionId={session?.id ?? null} + /> + )} + {/* Mobile Header */}
@@ -258,9 +284,9 @@ export function CustomerPortal() {
- Hi, {CUSTOMER.name.split(" ")[0]} + Hi, {clientName.split(" ")[0] || "Guest"}
- SM + {avatarInitials}
diff --git a/apps/web/src/portal/sections/AccountSettings.tsx b/apps/web/src/portal/sections/AccountSettings.tsx index 2377023..2fba3a6 100644 --- a/apps/web/src/portal/sections/AccountSettings.tsx +++ b/apps/web/src/portal/sections/AccountSettings.tsx @@ -1,12 +1,31 @@ -import { useState } from "react"; +import React, { useState, useEffect } from "react"; import { User, Lock, PawPrint, FileCheck, Plus, Archive } from "lucide-react"; -import { CUSTOMER, PETS, SIGNED_AGREEMENTS } from "../mockData.js"; +import { PetForm } from "./PetForm.js"; interface Props { + sessionId: string | null; readOnly: boolean; } -export function AccountSettings({ readOnly }: Props) { +interface PersonalInfoData { + id?: string; + email?: string; + firstName?: string; + lastName?: string; + phone?: string; + address?: string; +} + +interface PetData { + id: string; + name: string; + species?: string; + breed?: string; + weight?: number; + photo?: string; +} + +export function AccountSettings({ sessionId, readOnly }: Props) { const [tab, setTab] = useState<"personal" | "password" | "pets" | "agreements">("personal"); return ( @@ -31,21 +50,65 @@ export function AccountSettings({ readOnly }: Props) { ))} - {tab === "personal" && } + {tab === "personal" && } {tab === "password" && } - {tab === "pets" && } + {tab === "pets" && } {tab === "agreements" && } ); } -function PersonalInfo({ readOnly }: { readOnly: boolean }) { +function PersonalInfo({ sessionId, readOnly }: { sessionId: string | null; readOnly: boolean }) { const [form, setForm] = useState({ - name: CUSTOMER.name, - email: CUSTOMER.email, - phone: CUSTOMER.phone, - address: CUSTOMER.address, + name: "", + email: "", + phone: "", + address: "", }); + const [loading, setLoading] = useState(true); + const [error, setError] = useState(null); + + useEffect(() => { + const fetchPersonalInfo = async () => { + try { + setLoading(true); + const response = await fetch("/api/portal/me"); + if (response.ok) { + const data: PersonalInfoData = await response.json(); + setForm({ + name: [data.firstName, data.lastName].filter(Boolean).join(" ") || "", + email: data.email || "", + phone: data.phone || "", + address: data.address || "", + }); + } else { + setError("Failed to load personal info"); + } + } catch { + setError("Failed to load personal info"); + } finally { + setLoading(false); + } + }; + + fetchPersonalInfo(); + }, [sessionId]); + + if (loading) { + return ( +
+

Loading personal info...

+
+ ); + } + + if (error) { + return ( +
+

{error}

+
+ ); + } return (
@@ -111,10 +174,67 @@ function PasswordChange({ readOnly }: { readOnly: boolean }) { ); } -function ManagePets({ readOnly }: { readOnly: boolean }) { +function ManagePets({ sessionId, readOnly }: { sessionId: string | null; readOnly: boolean }) { + const [pets, setPets] = useState([]); + const [loading, setLoading] = useState(true); + const [error, setError] = useState(null); + const [editingPetId, setEditingPetId] = useState(null); + const [showAddForm, setShowAddForm] = useState(false); + + useEffect(() => { + const fetchPets = async () => { + try { + setLoading(true); + const response = await fetch("/api/portal/pets"); + if (response.ok) { + const data = await response.json(); + setPets(Array.isArray(data) ? data : []); + } else { + setError("Failed to load pets"); + } + } catch { + setError("Failed to load pets"); + } finally { + setLoading(false); + } + }; + + fetchPets(); + }, [sessionId]); + + const editingPet = editingPetId ? pets.find(p => p.id === editingPetId) ?? undefined : undefined; + + if (loading) { + return ( +
+

Loading pets...

+
+ ); + } + + if (error) { + return ( +
+

{error}

+
+ ); + } + + if (editingPet || showAddForm) { + return ( + { setEditingPetId(null); setShowAddForm(false); }} + onCancel={() => { setEditingPetId(null); setShowAddForm(false); }} + /> + ); + } + return (
- {PETS.map(pet => ( + {pets.map(pet => (
{pet.photo} @@ -125,7 +245,10 @@ function ManagePets({ readOnly }: { readOnly: boolean }) {
{!readOnly && (
-
))} {!readOnly && ( - @@ -147,31 +273,10 @@ function ManagePets({ readOnly }: { readOnly: boolean }) { function Agreements() { return ( -
-
- - - - - - - - - - {SIGNED_AGREEMENTS.map(agr => ( - - - - - - ))} - -
DocumentDate Signed
{agr.name} - {new Date(agr.dateSigned).toLocaleDateString("en-US", { month: "short", day: "numeric", year: "numeric" })} - - -
-
+
+

+ No agreements found. There is currently no agreements table in the database. +

); } diff --git a/apps/web/src/portal/sections/Appointments.tsx b/apps/web/src/portal/sections/Appointments.tsx index 04c2bc1..03fcad1 100644 --- a/apps/web/src/portal/sections/Appointments.tsx +++ b/apps/web/src/portal/sections/Appointments.tsx @@ -1,78 +1,203 @@ -import { useState } from "react"; -import { Calendar, Clock, Plus, ChevronRight, ChevronDown, Search, Repeat, Loader2 } from "lucide-react"; -import { UPCOMING_APPOINTMENTS, PAST_APPOINTMENTS, PETS, SERVICES, GROOMERS } from "../mockData.js"; -import type { Appointment, Pet, Service, Groomer } from "../mockData.js"; +import React, { useState, useEffect } from 'react'; +import { Calendar, Clock, Plus, ChevronRight, ChevronDown, Loader2 } from 'lucide-react'; + +interface Appointment { + id: string; + petId: string; + serviceId: string; + groomerId: string | null; + date: string; + time: string; + status: 'scheduled' | 'confirmed' | 'pending' | 'waitlisted' | 'completed' | 'cancelled' | 'no-show'; + petName?: string; + serviceName?: string; + groomerName?: string; + duration?: number; + price?: number; + notes?: string; + customerNotes?: string; + addOns?: string[]; + confirmationStatus?: 'confirmed' | 'pending' | 'cancelled'; +} + +interface Pet { + id: string; + name: string; + breed: string; + weight?: number; + photo?: string; + imageUrl?: string; +} + +interface Service { + id: string; + name: string; + description?: string; + duration: number; + price: number; + priceRange?: string; + isAddOn?: boolean; +} + +interface AppointmentsSectionProps { + sessionId: string | null; + readOnly: boolean; +} + +interface RescheduleFlowProps { + appointment: Appointment; + onClose: () => void; + sessionId: string | null; +} const MAX_CUSTOMER_NOTES = 500; -interface Props { - readOnly: boolean; - sessionId?: string | null; -} - export function formatDate(dateStr: string): string { - return new Date(dateStr).toLocaleDateString("en-US", { weekday: "short", month: "short", day: "numeric", year: "numeric" }); + return new Date(dateStr).toLocaleDateString('en-US', { + weekday: 'short', + month: 'short', + day: 'numeric', + year: 'numeric', + }); } export function parseTimeTo24Hour(time: string): string { - const parts = time.split(" "); - const hoursMinutes = parts[0] ?? ""; - const period = parts[1] ?? ""; - const [hoursStr, minutesStr] = hoursMinutes.split(":"); - const hours = parseInt(hoursStr ?? "0", 10); - const minutes = parseInt(minutesStr ?? "0", 10); + const parts = time.split(' '); + const hoursMinutes = parts[0] ?? ''; + const period = parts[1] ?? ''; + const [hoursStr, minutesStr] = hoursMinutes.split(':'); + const hours = parseInt(hoursStr ?? '0', 10); + const minutes = parseInt(minutesStr ?? '0', 10); let hours24 = hours; - if (period === "PM" && hours !== 12) hours24 += 12; - if (period === "AM" && hours === 12) hours24 = 0; - return `${hours24.toString().padStart(2, "0")}:${minutes.toString().padStart(2, "0")}:00`; + if (period === 'PM' && hours !== 12) hours24 += 12; + if (period === 'AM' && hours === 12) hours24 = 0; + return `${hours24.toString().padStart(2, '0')}:${minutes.toString().padStart(2, '0')}:00`; } export function isUpcoming(appt: Appointment): boolean { const now = new Date(); const apptDate = new Date(`${appt.date}T${parseTimeTo24Hour(appt.time)}`); - return apptDate > now && appt.status !== "cancelled" && appt.status !== "completed"; + return apptDate > now && appt.status !== 'cancelled' && appt.status !== 'completed'; } const STATUS_COLORS: Record = { - confirmed: "bg-green-100 text-green-700", - pending: "bg-amber-100 text-amber-700", - waitlisted: "bg-blue-100 text-blue-700", - completed: "bg-stone-100 text-stone-600", - cancelled: "bg-red-100 text-red-600", + confirmed: 'bg-green-100 text-green-700', + pending: 'bg-amber-100 text-amber-700', + waitlisted: 'bg-blue-100 text-blue-700', + completed: 'bg-stone-100 text-stone-600', + cancelled: 'bg-red-100 text-red-600', + 'no-show': 'bg-yellow-100 text-yellow-700', + scheduled: 'bg-blue-100 text-blue-700', }; const CONFIRMATION_STATUS_COLORS: Record = { - confirmed: "bg-green-100 text-green-700", - pending: "bg-amber-100 text-amber-700", - cancelled: "bg-red-100 text-red-600", + confirmed: 'bg-green-100 text-green-700', + pending: 'bg-amber-100 text-amber-700', + cancelled: 'bg-red-100 text-red-600', }; -export function AppointmentsSection({ readOnly, sessionId }: Props) { +export const AppointmentsSection: React.FC = ({ sessionId, readOnly }) => { + const [upcomingAppointments, setUpcomingAppointments] = useState([]); + const [pastAppointments, setPastAppointments] = useState([]); + const [isLoading, setIsLoading] = useState(true); + const [error, setError] = useState(null); const [showBooking, setShowBooking] = useState(false); + const [showReschedule, setShowReschedule] = useState(false); + const [rescheduleAppointment, setRescheduleAppointment] = useState(null); const [expandedId, setExpandedId] = useState(null); - const [tab, setTab] = useState<"upcoming" | "past">("upcoming"); + const [tab, setTab] = useState<'upcoming' | 'past'>('upcoming'); + + useEffect(() => { + const fetchAppointments = async () => { + if (!sessionId) { + setUpcomingAppointments([]); + setPastAppointments([]); + setIsLoading(false); + return; + } + + try { + const response = await fetch('/api/portal/appointments', { + headers: { Authorization: `Bearer ${sessionId}` }, + }); + + if (response.ok) { + const data = await response.json(); + const fetchedAppointments: Appointment[] = data.appointments || data || []; + + const upcoming = fetchedAppointments.filter((appt) => isUpcoming(appt)); + const past = fetchedAppointments.filter((appt) => !isUpcoming(appt)); + + setUpcomingAppointments(upcoming); + setPastAppointments(past); + } else { + setError('Failed to load appointments.'); + } + } catch { + setError('Failed to load appointments. Please try again.'); + } finally { + setIsLoading(false); + } + }; + + fetchAppointments(); + }, [sessionId]); + + const handleReschedule = (appointment: Appointment) => { + setRescheduleAppointment(appointment); + setShowReschedule(true); + }; + + if (isLoading) { + return ( +
+ + Loading appointments... +
+ ); + } + + if (error) { + return ( +
+

{error}

+ +
+ ); + } return (
{!readOnly && (
- {tab === "upcoming" && ( + {tab === 'upcoming' && (
- {UPCOMING_APPOINTMENTS.map(appt => ( + {upcomingAppointments.map((appt) => ( setExpandedId(expandedId === appt.id ? null : appt.id)} readOnly={readOnly} sessionId={sessionId} + onReschedule={handleReschedule} /> ))} - {UPCOMING_APPOINTMENTS.length === 0 && ( + {upcomingAppointments.length === 0 && (

No upcoming appointments

)}
)} - {tab === "past" && ( + {tab === 'past' && (
- {PAST_APPOINTMENTS.map(appt => ( + {pastAppointments.map((appt) => ( setExpandedId(expandedId === appt.id ? null : appt.id)} readOnly={readOnly} sessionId={sessionId} + onReschedule={handleReschedule} /> ))}
)} {showBooking && ( - setShowBooking(false)} - readOnly={readOnly} + setShowBooking(false)} sessionId={sessionId} /> + )} + {showReschedule && rescheduleAppointment && ( + { + setShowReschedule(false); + setRescheduleAppointment(null); + }} + sessionId={sessionId} /> )}
); -} +}; function AppointmentCard({ - appointment: appt, expanded, onToggle, readOnly, sessionId, + appointment: appt, + expanded, + onToggle, + readOnly, + sessionId, + onReschedule, }: { - appointment: Appointment; expanded: boolean; onToggle: () => void; readOnly: boolean; sessionId?: string | null; + appointment: Appointment; + expanded: boolean; + onToggle: () => void; + readOnly: boolean; + sessionId: string | null; + onReschedule: (appt: Appointment) => void; }) { return (
- {expanded && (
-
-

Duration

-

{appt.duration} min

-
-
-

Estimated Price

-

${appt.price}

-
- {appt.addOns.length > 0 && ( + {appt.duration && ( +
+

Duration

+

{appt.duration} min

+
+ )} + {appt.price && ( +
+

Estimated Price

+

${appt.price}

+
+ )} + {appt.addOns && appt.addOns.length > 0 && (

Add-ons

-

{appt.addOns.join(", ")}

+

{appt.addOns.join(', ')}

)}
{appt.notes && ( -

{appt.notes}

+

+ {appt.notes} +

)} {isUpcoming(appt) && !readOnly && ( )} - {isUpcoming(appt) && ( - - )} - {appt.status !== "completed" && appt.status !== "cancelled" && !readOnly && ( -
- - -
- )} - {appt.reportCardId && ( -
- - View Report Card → - -
- )} + {isUpcoming(appt) && } + {appt.status !== 'completed' && + appt.status !== 'cancelled' && + !readOnly && ( +
+ + +
+ )}
)}
); } -export function ConfirmationSection({ appointment: appt, sessionId }: { appointment: Appointment; sessionId?: string | null }) { +export function ConfirmationSection({ + appointment: appt, + sessionId, +}: { + appointment: Appointment; + sessionId: string | null; +}) { const [confirming, setConfirming] = useState(false); const [confirmError, setConfirmError] = useState(null); const [confirmSuccess, setConfirmSuccess] = useState(false); - // Local state mirrors confirmationStatus so the badge updates immediately after confirm const [localStatus, setLocalStatus] = useState(appt.confirmationStatus); async function handleConfirm() { - if (!window.confirm("Confirm this appointment?")) return; + if (!window.confirm('Confirm this appointment?')) return; setConfirming(true); setConfirmError(null); try { const headers: Record = {}; if (sessionId) { - headers["X-Impersonation-Session-Id"] = sessionId; + headers['Authorization'] = `Bearer ${sessionId}`; } const res = await fetch(`/api/portal/appointments/${appt.id}/confirm`, { - method: "POST", + method: 'POST', headers, }); if (!res.ok) { - const err = await res.json().catch(() => ({ error: "Failed to confirm" })); + const err = await res.json().catch(() => ({ error: 'Failed to confirm' })); throw new Error(err.error || `HTTP ${res.status}`); } - setLocalStatus("confirmed"); + setLocalStatus('confirmed'); setConfirmSuccess(true); setTimeout(() => setConfirmSuccess(false), 2000); } catch (e) { - setConfirmError(e instanceof Error ? e.message : "Failed to confirm"); + setConfirmError(e instanceof Error ? e.message : 'Failed to confirm'); } finally { setConfirming(false); } } const currentStatus = localStatus ?? appt.confirmationStatus; - const statusLabel = currentStatus === "confirmed" - ? "✓ Confirmed" - : currentStatus === "pending" - ? "Pending confirmation" - : "Cancelled"; + const statusLabel = + currentStatus === 'confirmed' + ? 'Confirmed' + : currentStatus === 'pending' + ? 'Pending confirmation' + : 'Cancelled'; return (
- + {statusLabel}
- {!confirmSuccess && currentStatus === "pending" && ( + {!confirmSuccess && currentStatus === 'pending' && ( )} {confirmSuccess && ( @@ -263,30 +438,36 @@ export function ConfirmationSection({ appointment: appt, sessionId }: { appointm ); } -function CancelAppointmentButton({ appointment: appt, sessionId }: { appointment: Appointment; sessionId?: string | null }) { +function CancelAppointmentButton({ + appointment: appt, + sessionId, +}: { + appointment: Appointment; + sessionId: string | null; +}) { const [cancelling, setCancelling] = useState(false); const [cancelError, setCancelError] = useState(null); async function handleCancel() { - if (!window.confirm("Cancel this appointment? This cannot be undone.")) return; + if (!window.confirm('Cancel this appointment? This cannot be undone.')) return; setCancelling(true); setCancelError(null); try { const headers: Record = {}; if (sessionId) { - headers["X-Impersonation-Session-Id"] = sessionId; + headers['Authorization'] = `Bearer ${sessionId}`; } const res = await fetch(`/api/portal/appointments/${appt.id}/cancel`, { - method: "POST", + method: 'POST', headers, }); if (!res.ok) { - const err = await res.json().catch(() => ({ error: "Failed to cancel" })); + const err = await res.json().catch(() => ({ error: 'Failed to cancel' })); throw new Error(err.error || `HTTP ${res.status}`); } window.location.reload(); } catch (e) { - setCancelError(e instanceof Error ? e.message : "Failed to cancel"); + setCancelError(e instanceof Error ? e.message : 'Failed to cancel'); setCancelling(false); } } @@ -298,43 +479,49 @@ function CancelAppointmentButton({ appointment: appt, sessionId }: { appointment disabled={cancelling} className="text-xs px-3 py-1.5 border border-red-200 rounded-lg text-red-600 hover:bg-red-50 disabled:opacity-50 disabled:cursor-not-allowed" > - {cancelling ? "Cancelling..." : "Cancel"} + {cancelling ? 'Cancelling...' : 'Cancel'} {cancelError &&

{cancelError}

} ); } -export function CustomerNotesSection({ appointment: appt, sessionId }: { appointment: Appointment; sessionId?: string | null }) { - const [notes, setNotes] = useState(appt.customerNotes || ""); +export function CustomerNotesSection({ + appointment: appt, + sessionId, +}: { + appointment: Appointment; + sessionId: string | null; +}) { + const [notes, setNotes] = useState(appt.customerNotes || ''); const [saving, setSaving] = useState(false); const [saved, setSaved] = useState(false); const [error, setError] = useState(null); - const isDisabled = appt.status === "completed" || appt.status === "cancelled"; + const isDisabled = appt.status === 'completed' || appt.status === 'cancelled'; async function handleSave() { setSaving(true); setError(null); setSaved(false); try { - const headers: Record = { "Content-Type": "application/json" }; + const headers: Record = { 'Content-Type': 'application/json' }; if (sessionId) { - headers["X-Impersonation-Session-Id"] = sessionId; + headers['Authorization'] = `Bearer ${sessionId}`; } const res = await fetch(`/api/portal/appointments/${appt.id}/notes`, { - method: "PATCH", + method: 'PATCH', headers, body: JSON.stringify({ customerNotes: notes }), }); if (!res.ok) { - const err = await res.json().catch(() => ({ error: "Failed to save" })); + const err = await res.json().catch(() => ({ error: 'Failed to save' })); throw new Error(err.error || `HTTP ${res.status}`); } setSaved(true); setTimeout(() => setSaved(false), 2000); } catch (e) { - setError(e instanceof Error ? e.message : "Failed to save"); + setError(e instanceof Error ? e.message : 'Failed to save'); } finally { setSaving(false); } @@ -344,15 +531,19 @@ export function CustomerNotesSection({ appointment: appt, sessionId }: { appoint
- MAX_CUSTOMER_NOTES ? "text-red-500" : "text-stone-400"}`}> + MAX_CUSTOMER_NOTES ? 'text-red-500' : 'text-stone-400' + }`} + > {notes.length}/{MAX_CUSTOMER_NOTES}