diff --git a/.commitlintrc.json b/.commitlintrc.json new file mode 100644 index 0000000..c30e5a9 --- /dev/null +++ b/.commitlintrc.json @@ -0,0 +1,3 @@ +{ + "extends": ["@commitlint/config-conventional"] +} diff --git a/.env.example b/.env.example new file mode 100644 index 0000000..815a601 --- /dev/null +++ b/.env.example @@ -0,0 +1,35 @@ +# ----------------------------------------------------------------------------- +# App +# ----------------------------------------------------------------------------- +# NextAuth Secret (Generate using: `openssl rand -base64 32`) +NEXT_PUBLIC_APP_URL=https://yourdomain.com/ +NEXTAUTH_URL=http://localhost:3000 +NEXTAUTH_SECRET=YOUR_NEXTAUTH_SECRET + +# ----------------------------------------------------------------------------- +# Google OAuth +# ----------------------------------------------------------------------------- +GOOGLE_CLIENT_ID=YOUR_GOOGLE_CLIENT_ID +GOOGLE_CLIENT_SECRET=YOUR_GOOGLE_CLIENT_SECRET + +# ----------------------------------------------------------------------------- +# Database (Neon - PostgreSQL) +# ----------------------------------------------------------------------------- +DATABASE_URL="postgresql://username:password@host/database?sslmode=require" +DATABASE_URL_UNPOOLED="postgresql://username:password@host/database?sslmode=require" + +# ----------------------------------------------------------------------------- +# Resend API +# ----------------------------------------------------------------------------- +RESEND_API_KEY=YOUR_RESEND_API_KEY + +# ----------------------------------------------------------------------------- +# Stripe +# ----------------------------------------------------------------------------- +STRIPE_API_KEY=YOUR_STRIPE_API_KEY +STRIPE_WEBHOOK_SECRET=YOUR_STRIPE_WEBHOOK_SECRET +NEXT_PUBLIC_STRIPE_PRO_MONTHLY_PLAN_ID=price_xxx +NEXT_PUBLIC_STRIPE_PRO_YEARLY_PLAN_ID=price_xxx +NEXT_PUBLIC_STRIPE_BUSINESS_MONTHLY_PLAN_ID=price_xxx +NEXT_PUBLIC_STRIPE_BUSINESS_YEARLY_PLAN_ID=price_xxx + diff --git a/.github/ISSUE_TEMPLATE/bug_report.yml b/.github/ISSUE_TEMPLATE/bug_report.yml new file mode 100644 index 0000000..2f8edf5 --- /dev/null +++ b/.github/ISSUE_TEMPLATE/bug_report.yml @@ -0,0 +1,43 @@ +name: ๐Ÿ› Bug report +description: Create a bug report to help us improve ProjectX โœจ +title: "Bug: " +labels: [๐Ÿ‘€ Exploration Pending, ๐Ÿ› bug] +body: + - type: markdown + attributes: + value: | + Thanks for taking the time to fill out this bug report! + - type: textarea + attributes: + label: Describe the bug + description: A clear and concise description of what the bug is. + validations: + required: true + - type: textarea + attributes: + label: Steps to reproduce + description: Describe how to reproduce the behavior. + placeholder: | + 1. Go to '...' + 2. Click on '...' + 3. Scroll down to '...' + 4. See error + validations: + required: true + - type: dropdown + attributes: + multiple: true + label: Browsers + description: Select the browsers where the issue can be reproduced (that you know of). + options: + - "Chrome" + - "Firefox" + - "Safari" + - "Edge" + - "Opera" + - "Other (add additional context)" + - type: input + id: context + attributes: + label: Additional context (Is this in dev or production?) + description: Add any other context about the problem or helpful links here. diff --git a/.github/ISSUE_TEMPLATE/config.yml b/.github/ISSUE_TEMPLATE/config.yml new file mode 100644 index 0000000..73226dd --- /dev/null +++ b/.github/ISSUE_TEMPLATE/config.yml @@ -0,0 +1,5 @@ +blank_issues_enabled: true +contact_links: + - name: โ“ Ask a question + url: https://discord.gg/8BkX9hJRXs + about: Ask questions about ProjectX diff --git a/.github/ISSUE_TEMPLATE/feature_request.yml b/.github/ISSUE_TEMPLATE/feature_request.yml new file mode 100644 index 0000000..ad9b27b --- /dev/null +++ b/.github/ISSUE_TEMPLATE/feature_request.yml @@ -0,0 +1,43 @@ +name: ๐Ÿš€ Feature request +description: Suggest an idea for this project ๐Ÿ’ก +title: "Feature: " +labels: [๐Ÿ‘€ Exploration Pending, ๐Ÿ’ก feature] +body: + - type: markdown + attributes: + value: | + Thanks for taking the time to fill out this feature request! + - type: dropdown + attributes: + multiple: false + label: Type of feature + description: Select the type of feature request, the lowercase should also be the PR prefix. + options: + - "๐Ÿ’ก Feature" + - "๐Ÿ› Fix" + - "๐Ÿ“ Documentation" + - "๐ŸŽจ Style" + - "๐Ÿง‘โ€๐Ÿ’ป Refactor" + - "๐Ÿ”ฅ Performance" + - "โœ… Test" + - "๐Ÿค– Build" + - "๐Ÿ” CI" + - "๐Ÿ“ฆ Chore" + - "โฉ Revert" + validations: + required: true + - type: textarea + attributes: + label: Current behavior + description: Is your feature request related to a problem? Please describe. + validations: + required: true + - type: textarea + attributes: + label: Suggested solution + description: Describe the solution you'd like. + - type: input + id: context + attributes: + label: Additional context + description: Add any other context about the problem or helpful links here. diff --git a/.github/PULL_REQUEST_TEMPLATE.md b/.github/PULL_REQUEST_TEMPLATE.md new file mode 100644 index 0000000..c429bbe --- /dev/null +++ b/.github/PULL_REQUEST_TEMPLATE.md @@ -0,0 +1,66 @@ +## Description + + + +## What type of PR is this? (check all applicable) + +- [ ] ๐Ÿ’ก Feature +- [ ] ๐Ÿ› Bug Fix +- [ ] ๐Ÿ“ Documentation Update +- [ ] ๐ŸŽจ Style +- [ ] ๐Ÿง‘โ€๐Ÿ’ป Code Refactor +- [ ] ๐Ÿ”ฅ Performance Improvements +- [ ] โœ… Test +- [ ] ๐Ÿค– Build +- [ ] ๐Ÿ” CI +- [ ] ๐Ÿ“ฆ Chore (Release) +- [ ] โฉ Revert + +## Related Tickets & Documents + + + +## Mobile & Desktop Screenshots/Recordings + + + +## Steps to QA + + + +## Added to documentation? + +- [ ] ๐Ÿ“œ README.md +- [ ] ๐Ÿ™… no documentation needed + +## [optional] Are there any post-deployment tasks we need to perform? + +## [optional] What gif best describes this PR or how it makes you feel? + + + + diff --git a/.github/workflows/take-issue.yml b/.github/workflows/take-issue.yml new file mode 100644 index 0000000..978d01b --- /dev/null +++ b/.github/workflows/take-issue.yml @@ -0,0 +1,23 @@ +# .github/workflows/take.yml +name: Assign issue to contributor +on: + issue_comment: + +jobs: + assign: + name: Take an issue + runs-on: ubuntu-latest + permissions: + issues: write + steps: + - name: take the issue + uses: bdougie/take-action@main + with: + message: + Thanks for taking this issue! Let us know if you have any questions! + blockingLabels: in progress + blockingLabelsMessage: + This issue is already taken by someone else and is in progress. You + can find another one by surfing the issues page. + trigger: .take + token: ${{ secrets.GITHUB_TOKEN }} diff --git a/.gitignore b/.gitignore new file mode 100644 index 0000000..09ff7e3 --- /dev/null +++ b/.gitignore @@ -0,0 +1,52 @@ +# See https://help.github.com/articles/ignoring-files/ for more about ignoring files. + +# dependencies +node_modules +.pnp +.pnp.js + +# turbo +.turbo/ +.turbo/ + +# testing +coverage + +# next.js +.next/ +out/ + +# build +build +dist + +# misc +.DS_Store +*.pem + +# debug +npm-debug.log* +yarn-debug.log* +yarn-error.log* +.pnpm-debug.log* + +# local env files +.env*.local +.env + +# vercel +.vercel + +# typescript +*.tsbuildinfo +next-env.d.ts + +# email +.react-email/ + +.vscode +.contentlayer + +#API +.wrangler.toml +wrangler.toml diff --git a/.husky/commit-msg b/.husky/commit-msg new file mode 100755 index 0000000..4974c35 --- /dev/null +++ b/.husky/commit-msg @@ -0,0 +1,4 @@ +#!/usr/bin/env sh +. "$(dirname -- "$0")/_/husky.sh" + +npx commitlint --edit $1 diff --git a/.husky/pre-commit b/.husky/pre-commit new file mode 100755 index 0000000..0da96d6 --- /dev/null +++ b/.husky/pre-commit @@ -0,0 +1,4 @@ +#!/usr/bin/env sh +. "$(dirname -- "$0")/_/husky.sh" + +npx pretty-quick --staged diff --git a/.npmrc b/.npmrc new file mode 100644 index 0000000..3aba4f1 --- /dev/null +++ b/.npmrc @@ -0,0 +1,18 @@ +# Expo doesn't play nice with pnpm by default. +# The symbolic links of pnpm break the rules of Expo monorepos. +# @link https://docs.expo.dev/guides/monorepos/#common-issues +node-linker=hoisted + +# In order to cache Prisma correctly +public-hoist-pattern[]=*prisma* + +# FIXME: @prisma/client is required by the @acme/auth, +# but we don't want it installed there since it's already +# installed in the @acme/db package +strict-peer-dependencies=false + +# Prevent pnpm from adding the "workspace:"" prefix to local +# packages as it casues issues with manypkg +# @link https://pnpm.io/npmrc#prefer-workspace-packages +save-workspace-protocol=false +prefer-workspace-packages=true diff --git a/.nvmrc b/.nvmrc new file mode 100644 index 0000000..790e110 --- /dev/null +++ b/.nvmrc @@ -0,0 +1 @@ +v20.10.0 diff --git a/.prettierignore b/.prettierignore new file mode 100644 index 0000000..3aea320 --- /dev/null +++ b/.prettierignore @@ -0,0 +1,5 @@ +dist +node_modules +.next +build +.contentlayer \ No newline at end of file diff --git a/LICENSE.md b/LICENSE.md new file mode 100644 index 0000000..162676c --- /dev/null +++ b/LICENSE.md @@ -0,0 +1,661 @@ + 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 new file mode 100644 index 0000000..69cbb59 --- /dev/null +++ b/README.md @@ -0,0 +1,124 @@ + + +

Dingify

+
+ +

+ Start at full speed with Dingify ! +

+ + +

+ Introduction ยท + Installation ยท + Tech Stack + Features ยท + Author ยท + Credits +

+
+ +## Introduction + +Welcome to Dingify, where we're we are going to make your alerts easy for you + +## Directory Structure + +Dingify is a monorepo managed by [Turborepo](https://turbo.build/repo). The monorepo is split between `apps` and `packages` directories. + + . + โ”œโ”€โ”€ apps # Its app workspace which contains + โ”‚ โ”œโ”€โ”€ www # Nextjs app which is deployed in Vercel + โ”‚ โ”œโ”€โ”€ api # Hono app that is our REST-api for our SDK + โ”‚ โ””โ”€โ”€ ... + โ”œโ”€โ”€ packages # are the shared packages that are used by the apps + โ”‚ โ”œโ”€โ”€ db # Prisma DB connector + โ”‚ โ””โ”€โ”€ ui # Shared UI components (Shadcn) + โ”œโ”€โ”€ tooling # are the shared configuration that are used by the apps and packages + โ”‚ โ”œโ”€โ”€ eslint # Shared eslint presets + โ”‚ โ”œโ”€โ”€ prettier # Shared prettier configuration + โ”‚ โ”œโ”€โ”€ tailwind # Shared tailwind configuration + โ”‚ โ””โ”€โ”€ typescript # Shared tsconfig you can extend from + โ”œโ”€โ”€ LICENSE + โ””โ”€โ”€ README.md + +## Installation + +Clone & create this repo locally with the following command: + +```bash +git clone https://github.com/Codehagen/Dingify +``` + +1. Install dependencies using pnpm: + +```sh +pnpm install +``` + +2. Copy `.env.example` to `.env.local` and update the variables. + +```sh +cp .env.example .env.local +``` + +4. Input everything you need for the env. + + 1. Create [Neon Database](https://neon.tech/) Account + 2. Create [Stripe](https://stripe.com) Account + 3. Create [Google Console](https://console.cloud.google.com/) Account + 4. Create [Resend](https://resend.com/) Account + +5. Start the development server from either yarn or turbo: + +```sh +# To start the server +pnpm dev + +# To push the DB schema +pnpm --filter=db db:push +``` + +## REST-API Installation (optinal) + +If you want to use the REST-api you need to update the hono under `apps/api` + +```bash +[vars] +#MY_VAR = "my-variable" +#DATABASE_URL = "Use same link as your db URL" +``` + +If you want to deploy it on Cloudflare you need to go run +```bash +pnpm run deploy +``` + +## Tech Stack + Features + +### Frameworks + +- [Next.js](https://nextjs.org/) โ€“ React framework for building performant apps with the best developer experience +- [Auth.js](https://authjs.dev/) โ€“ Handle user authentication with ease with providers like Google, Twitter, GitHub, etc. +- [Prisma](https://www.prisma.io/) โ€“ Typescript-first ORM for Node.js +- [React Email](https://react.email/) โ€“ Versatile email framework for efficient and flexible email development + +### Platforms + +- [Vercel](https://vercel.com/) โ€“ Easily preview & deploy changes with git +- [PlanetScale](https://planetscale.com/) โ€“ A cutting-edge database platform for seamless, scalable data management +- [Resend](https://resend.com/) โ€“ A powerful email framework for streamlined email development + +## Contributing + +We love our contributors! Here's how you can contribute: + +- [Open an issue](https://github.com/Codehagen/Dingify/issues) if you believe you've encountered a bug. +- Make a [pull request](https://github.com/Codehagen/Dingify/pull) to add new features/make quality-of-life improvements/fix bugs. + + + + + +## Repo Activity + +![Nextify repo activity โ€“ generated by Axiom](https://repobeats.axiom.co/api/embed/ca3e357dc3abec5d0e392ee4d10896f5a8fdecb1.svg "Repobeats analytics image") diff --git a/apps/api/.gitignore b/apps/api/.gitignore new file mode 100644 index 0000000..0a410ba --- /dev/null +++ b/apps/api/.gitignore @@ -0,0 +1,13 @@ +node_modules +dist +.wrangler +.dev.vars +.wrangler.toml +wrangler.toml + + +# Change them to your taste: +package-lock.json +yarn.lock +pnpm-lock.yaml +bun.lockb \ No newline at end of file diff --git a/apps/api/README.md b/apps/api/README.md new file mode 100644 index 0000000..cc58e96 --- /dev/null +++ b/apps/api/README.md @@ -0,0 +1,8 @@ +``` +npm install +npm run dev +``` + +``` +npm run deploy +``` diff --git a/apps/api/package.json b/apps/api/package.json new file mode 100644 index 0000000..709bcb6 --- /dev/null +++ b/apps/api/package.json @@ -0,0 +1,28 @@ +{ + "name": "@dingify/api", + "version": "0.1.0", + "private": true, + "type": "module", + "exports": { + ".": { + "types": "./dist/index.d.ts", + "default": "./index.ts" + } + }, + "scripts": { + "dev": "wrangler dev", + "build": "tsc", + "deploy": "wrangler deploy --minify src/index.ts" + }, + "dependencies": { + "@dingify/db": "workspace:*", + "@hono/zod-openapi": "^0.11.0", + "hono": "^4.3.6", + "zod": "^3.23.4", + "zod-openapi": "^2.17.0" + }, + "devDependencies": { + "@cloudflare/workers-types": "^4.20240403.0", + "wrangler": "^3.54.0" + } +} diff --git a/apps/api/src/env.ts b/apps/api/src/env.ts new file mode 100644 index 0000000..dc9ca5a --- /dev/null +++ b/apps/api/src/env.ts @@ -0,0 +1,11 @@ +/* eslint-disable @typescript-eslint/consistent-type-definitions */ +import { z } from "zod"; + +export const zEnv = z.object({ + DATABASE_URL: z.string(), + ENVIRONMENT: z + .enum(["development", "preview", "production"]) + .default("development"), +}); + +export type Env = z.infer; diff --git a/apps/api/src/index.ts b/apps/api/src/index.ts new file mode 100644 index 0000000..aff7bbc --- /dev/null +++ b/apps/api/src/index.ts @@ -0,0 +1,59 @@ +import { Hono } from "hono"; + +import { Env, zEnv } from "./env"; +import { prisma } from "./lib/db"; +import channels from "./routes/channels"; +import events from "./routes/events"; +import projects from "./routes/projects"; +import users from "./routes/users"; + +const app = new Hono<{ + Bindings: Env; +}>(); + +app.use("/api/*", async (c, next) => { + // Skip API key check for user registration endpoint + if (c.req.path === "/api/users" && c.req.method === "POST") { + return next(); + } + + const apiKey = c.req.header("x-api-key"); + if (!apiKey) { + return c.json({ ok: false, message: "API key is required" }, 401); + } + + const user = await prisma(c.env).user.findUnique({ + where: { apiKey }, + }); + + if (!user) { + return c.json({ ok: false, message: "Invalid API key" }, 401); + } + + return next(); +}); + +// Routes // +app.route("/api/users", users); +app.route("/api/projects", projects); +app.route("/api/channels", channels); +app.route("/api/events", events); + +export default { + fetch: (req: Request, env: Env, exCtx: ExecutionContext) => { + const parsedEnv = zEnv.safeParse(env); + + if (!parsedEnv.success) { + return Response.json( + { + code: "BAD_ENVIRONMENT", + message: "Some environment variables are missing or are invalid", + errors: parsedEnv.error, + }, + { status: 500 }, + ); + } + + return app.fetch(req, parsedEnv.data, exCtx); + }, +}; diff --git a/apps/api/src/lib/db.ts b/apps/api/src/lib/db.ts new file mode 100644 index 0000000..be98827 --- /dev/null +++ b/apps/api/src/lib/db.ts @@ -0,0 +1,29 @@ +import type { Env } from "../env"; +import { PrismaClient, PrismaNeon, Pool } from "@dingify/db"; + +const pool = (env: Env) => new Pool({ connectionString: env.DATABASE_URL }); +const adapter = (env: Env) => new PrismaNeon(pool(env)); + +const createPrismaClient = (env: Env): PrismaClient => { + // Check if prisma client is already instantiated in global context + const globalPrisma = globalThis as { prisma?: PrismaClient }; + const existingPrismaClient = globalPrisma.prisma; + + if (existingPrismaClient) { + return existingPrismaClient; + } + const prismaClient = new PrismaClient({ + adapter: adapter(env), + log: + env.ENVIRONMENT === "development" + ? ["query", "error", "warn"] + : ["error"], + errorFormat: "pretty", + }); + if (env.ENVIRONMENT !== "production") { + globalPrisma.prisma = prismaClient; + } + return prismaClient; +}; + +export const prisma = (env: Env) => createPrismaClient(env); diff --git a/apps/api/src/lib/generateApiKey.ts b/apps/api/src/lib/generateApiKey.ts new file mode 100644 index 0000000..5dacc30 --- /dev/null +++ b/apps/api/src/lib/generateApiKey.ts @@ -0,0 +1,7 @@ +export function generateApiKey() { + const array = new Uint8Array(32); + crypto.getRandomValues(array); + return Array.from(array, (byte) => byte.toString(16).padStart(2, "0")).join( + "" + ); +} diff --git a/apps/api/src/lib/parsePrismaError.ts b/apps/api/src/lib/parsePrismaError.ts new file mode 100644 index 0000000..7aa8b42 --- /dev/null +++ b/apps/api/src/lib/parsePrismaError.ts @@ -0,0 +1,19 @@ +export function parsePrismaError(error: any): string { + // A simple error message parser that looks for missing arguments + const missingArgumentMatch = error.message.match( + /Argument `(\w+)` is missing./ + ); + if (missingArgumentMatch) { + let fieldName = missingArgumentMatch[1]; + let baseMessage = `The '${fieldName}' field is required but was not provided.`; + + // Specific instructions for known fields + if (fieldName === "channel") { + baseMessage += " You need to add 'channel' to your call to make it work."; + } + // Add more specific messages for other fields if necessary + return baseMessage; + } + // Default to returning the original error message if no known patterns are matched + return error.message; +} diff --git a/apps/api/src/notifications/discord/sendDiscordNotification.ts b/apps/api/src/notifications/discord/sendDiscordNotification.ts new file mode 100644 index 0000000..707d849 --- /dev/null +++ b/apps/api/src/notifications/discord/sendDiscordNotification.ts @@ -0,0 +1,42 @@ +export async function sendDiscordNotification( + webhook: string, + message: string, +) { + try { + console.log("Sending Discord notification to webhook URL:", webhook); + const response = await fetch(webhook, { + method: "POST", + headers: { + "Content-Type": "application/json", + }, + body: JSON.stringify({ + content: message, + }), + }); + if (!response.ok) { + console.error("Failed to send Discord notification"); + } + } catch (error) { + console.error("Error sending notification to Discord:", error); + } +} + +export async function sendSlackNotification(webhook: string, message: string) { + try { + console.log("Sending Slack notification to webhook URL:", webhook); + const response = await fetch(webhook, { + method: "POST", + headers: { + "Content-Type": "application/json", + }, + body: JSON.stringify({ + text: message, + }), + }); + if (!response.ok) { + console.error("Failed to send Slack notification"); + } + } catch (error) { + console.error("Error sending notification to Slack:", error); + } +} diff --git a/apps/api/src/routes/apiKeyMiddleware.ts b/apps/api/src/routes/apiKeyMiddleware.ts new file mode 100644 index 0000000..634ab08 --- /dev/null +++ b/apps/api/src/routes/apiKeyMiddleware.ts @@ -0,0 +1,24 @@ +import { Context } from "hono"; +import { prisma } from "../lib/db"; +import { Env } from "../env"; + +export async function apiKeyMiddleware( + c: Context<{ + Bindings: Env; + }>, + next: any, +) { + const apiKey = c.req.header("x-api-key"); + if (!apiKey) { + return c.json({ ok: false, message: "API key is required" }, 401); + } + + const user = await prisma(c.env).user.findUnique({ where: { apiKey } }); + if (!user) { + return c.json({ ok: false, message: "Invalid API key" }, 401); + } + + // Store user in context for downstream use + c.set("user", user); + return next(); +} diff --git a/apps/api/src/routes/channels.ts b/apps/api/src/routes/channels.ts new file mode 100644 index 0000000..585dcf7 --- /dev/null +++ b/apps/api/src/routes/channels.ts @@ -0,0 +1,114 @@ +import { Hono } from "hono"; +import { Env } from "../env"; +import { prisma } from "../lib/db"; + +const channels = new Hono<{ + Bindings: Env; +}>(); + +channels.post("/", async (c) => { + const apiKey = c.req.header("x-api-key"); + if (!apiKey) { + return c.json({ ok: false, message: "API key is required" }, 401); + } + + const user = await prisma(c.env).user.findUnique({ + where: { apiKey }, + }); + + if (!user) { + return c.json({ ok: false, message: "Invalid API key" }, 401); + } + + const { project, name } = await c.req.json(); + + if (!project) { + return c.json({ ok: false, message: "Project name is required" }, 400); + } + + const projectExists = await prisma(c.env).project.findFirst({ + where: { + name: project, + userId: user.id, + }, + }); + + if (!projectExists) { + return c.json( + { + ok: false, + message: "Project not found or does not belong to the user", + }, + 404, + ); + } + + const channelExists = await prisma(c.env).channel.findFirst({ + where: { + name, + projectId: projectExists.id, + }, + }); + + if (channelExists) { + return c.json( + { + ok: false, + message: "Channel with this name already exists in the project", + }, + 409, + ); + } + + const channel = await prisma(c.env).channel.create({ + data: { + name, + projectId: projectExists.id, + }, + }); + + return c.json({ ok: true, message: "Channel created", channel }); +}); + +channels.get("/", async (c) => { + const apiKey = c.req.header("x-api-key"); + if (!apiKey) { + return c.json({ ok: false, message: "API key is required" }, 401); + } + + const user = await prisma(c.env).user.findUnique({ + where: { apiKey }, + }); + + if (!user) { + return c.json({ ok: false, message: "Invalid API key" }, 401); + } + + const projects = await prisma(c.env).project.findMany({ + where: { userId: user.id }, + select: { id: true }, + }); + + if (!projects || projects.length === 0) { + return c.json( + { ok: false, message: "No projects found for the user" }, + 404, + ); + } + + const projectIds = projects.map((project) => project.id); + const channels = await prisma(c.env).channel.findMany({ + where: { projectId: { in: projectIds } }, + }); + + if (!channels || channels.length === 0) { + return c.json( + { ok: false, message: "No channels found for the user's projects" }, + 404, + ); + } + + return c.json({ ok: true, channels }); +}); + +export default channels; diff --git a/apps/api/src/routes/events.ts b/apps/api/src/routes/events.ts new file mode 100644 index 0000000..bd1427b --- /dev/null +++ b/apps/api/src/routes/events.ts @@ -0,0 +1,192 @@ +import { Hono } from "hono"; + +import { Env } from "../env"; +import { prisma } from "../lib/db"; +import { parsePrismaError } from "../lib/parsePrismaError"; +import { + sendDiscordNotification, + sendSlackNotification, +} from "../notifications/discord/sendDiscordNotification"; +import { EventSchema } from "../validators"; + +const events = new Hono<{ + Bindings: Env; +}>(); + +// POST - Create Event +events.post("/", async (c) => { + const apiKey = c.req.header("x-api-key"); + if (!apiKey) { + return c.json({ ok: false, message: "API key is required" }, 401); + } + + // Find user by API key + const user = await prisma(c.env).user.findUnique({ + where: { apiKey }, + }); + + if (!user) { + return c.json({ ok: false, message: "Invalid API key" }, 401); + } + + try { + const eventData = EventSchema.parse(await c.req.json()); + + // Destructure validated data + const { channel, name, icon, notify, tags, userId } = eventData; + + // Find the user's project + const project = await prisma(c.env).project.findFirst({ + where: { + userId: user.id, + }, + }); + + if (!project) { + return c.json( + { + ok: false, + message: + "No projects found for this user. Ensure the user has projects created.", + }, + 404, + ); + } + + // Find the channel by name + const channelExists = await prisma(c.env).channel.findFirst({ + where: { + name: channel, + projectId: project.id, + }, + }); + + if (!channelExists) { + const availableChannels = await prisma(c.env).channel.findMany({ + where: { projectId: project.id }, + select: { name: true }, + }); + + const channelNames = availableChannels.map((ch) => ch.name).join(", "); + + return c.json( + { + ok: false, + message: `No channel found with the provided channel name. You need to add it on the website. These are your available channels: ${channelNames}`, + availableChannels: availableChannels.map((ch) => ch.name), + }, + 404, + ); + } + + // Check if the customer exists based on user_id and project_id + let customer = await prisma(c.env).customer.findUnique({ + where: { + userId_projectId: { + userId: userId, + projectId: project.id, + }, + }, + }); + + // If the customer does not exist, create a new customer + if (!customer) { + try { + customer = await prisma(c.env).customer.create({ + data: { + projectId: project.id, + userId: userId, + name: "", // Assuming name and email are optional + email: "", + createdAt: new Date(), + }, + }); + console.log("New customer created:", customer); // Log the new customer + } catch (error) { + console.error("Error creating customer:", error); + throw error; + } + } else { + console.log("Existing customer found:", customer); // Log the existing customer + } + + // Create the event and associate it with the customer + const savedEvent = await prisma(c.env).event.create({ + data: { + name: name || "", + channelId: channelExists.id, + userId: userId, // userId here is a plain string + icon: icon || "", + notify, + tags: tags || {}, + customerId: customer.id, // Associate the event with the customer + }, + }); + + console.log("New event created:", savedEvent); // Log the new event + + // Update logs metrics for the project + const metrics = await prisma(c.env).metrics.findUnique({ + where: { projectId: project.id }, + }); + + if (metrics) { + await prisma(c.env).metrics.update({ + where: { id: metrics.id }, + data: { + logsUsed: { increment: 1 }, + }, + }); + // Fetch the updated metrics and log them + const updatedMetrics = await prisma(c.env).metrics.findUnique({ + where: { id: metrics.id }, + }); + console.log("Updated metrics:", updatedMetrics); + } else { + console.error("Metrics not found for the project"); + } + + // Fetch notification settings for the current user + const notificationSettings = await prisma( + c.env, + ).notificationSetting.findFirst({ + where: { userId: user.id }, + }); + console.log("Notification settings:", notificationSettings); + + if (notificationSettings) { + const { type, details } = notificationSettings; + const detailsParsed = details as { webhook: string }; + + if (type === "DISCORD" && detailsParsed?.webhook) { + await sendDiscordNotification( + detailsParsed.webhook, + `Event created: ${name}`, + ); + } else if (type === "SLACK" && detailsParsed?.webhook) { + await sendSlackNotification( + detailsParsed.webhook, + `Event created: ${name}`, + ); + } + } else { + console.log("No notification settings found for the user."); + } + + return c.json( + { ok: true, message: "Event logged!", event: savedEvent }, + 201, + ); // Return 201 status code + } catch (error: any) { + return c.json( + { + ok: false, + message: "Failed to log event", + error: parsePrismaError(error), + }, + 400, + ); + } +}); + +export default events; diff --git a/apps/api/src/routes/projects.ts b/apps/api/src/routes/projects.ts new file mode 100644 index 0000000..0bda44b --- /dev/null +++ b/apps/api/src/routes/projects.ts @@ -0,0 +1,96 @@ +import { Hono } from "hono"; + +import { Env } from "../env"; +import { prisma } from "../lib/db"; + +const projects = new Hono<{ + Bindings: Env; +}>(); + +projects.post("/", async (c) => { + const apiKey = c.req.header("x-api-key"); + if (!apiKey) { + return c.json({ ok: false, message: "API key is required" }, 401); + } + + const user = await prisma(c.env).user.findUnique({ + where: { apiKey }, + }); + + if (!user) { + return c.json({ ok: false, message: "Invalid API key" }, 401); + } + + // Parse and validate the request body + let result; + try { + result = await c.req.json(); + } catch (error) { + return c.json({ ok: false, message: "Invalid JSON body" }, 400); + } + + if (!result || typeof result.name !== "string") { + return c.json( + { + ok: false, + message: "Invalid project data", + errors: ["'name' is required and should be a string"], + }, + 400, + ); + } + + const { name } = result; + + const projectExists = await prisma(c.env).project.findFirst({ + where: { + name, + userId: user.id, + }, + }); + + if (projectExists) { + return c.json( + { ok: false, message: "Project with this name already exists" }, + 409, + ); + } + + const project = await prisma(c.env).project.create({ + data: { + name, + userId: user.id, + }, + }); + + return c.json({ ok: true, message: "Project created", project }); +}); + +projects.get("/", async (c) => { + const apiKey = c.req.header("x-api-key"); + if (!apiKey) { + return c.json({ ok: false, message: "API key is required" }, 401); + } + + const user = await prisma(c.env).user.findUnique({ + where: { apiKey }, + }); + + if (!user) { + return c.json({ ok: false, message: "Invalid API key" }, 401); + } + + const projects = await prisma(c.env).project.findMany({ + where: { + userId: user.id, + }, + }); + + if (!projects || projects.length === 0) { + return c.json({ ok: false, message: "No projects found" }, 404); + } + + return c.json({ ok: true, projects }); +}); + +export default projects; diff --git a/apps/api/src/routes/users.ts b/apps/api/src/routes/users.ts new file mode 100644 index 0000000..4617116 --- /dev/null +++ b/apps/api/src/routes/users.ts @@ -0,0 +1,77 @@ +// users.ts +import { Hono } from "hono"; + +import { Env } from "../env"; +import { prisma } from "../lib/db"; +import { generateApiKey } from "../lib/generateApiKey"; +import { parsePrismaError } from "../lib/parsePrismaError"; +import { UserSchema } from "../zod"; + +const users = new Hono<{ + Bindings: Env; +}>(); + +// POST - Create User +users.post("/", async (c) => { + const inputData = UserSchema.omit({ + id: true, + events: true, + }).parse(await c.req.json()); + const { email, name, plan } = inputData as Partial; + + if (!email) { + return c.json({ ok: false, message: "Missing required field: email" }, 400); + } + + const apiKey = generateApiKey(); + + try { + const user = await prisma(c.env).user.upsert({ + where: { email }, + update: { name, plan }, + create: { email, name: name || "", plan: plan || "", apiKey }, + }); + return c.json({ ok: true, message: "User created", user }); + } catch (error: any) { + return c.json( + { + ok: false, + message: "Failed to create or update user", + error: parsePrismaError(error), + }, + 500, + ); + } +}); + +// GET - Retrieve user with specific API key +users.get("/", async (c) => { + const apiKey = c.req.header("x-api-key"); + + if (!apiKey) { + return c.json({ ok: false, message: "API key is required" }, 401); + } + + try { + const user = await prisma(c.env).user.findUnique({ + where: { apiKey }, + }); + + if (!user) { + return c.json({ ok: false, message: "Invalid API key" }, 401); + } + + return c.json({ ok: true, user }); + } catch (error: any) { + return c.json( + { + ok: false, + message: "Failed to retrieve user", + error: error.message || "Unknown error", + }, + 500, + ); + } +}); + +export default users; diff --git a/apps/api/src/validators/index.ts b/apps/api/src/validators/index.ts new file mode 100644 index 0000000..5f4def8 --- /dev/null +++ b/apps/api/src/validators/index.ts @@ -0,0 +1,138 @@ +import { OpenAPIHono, z } from "@hono/zod-openapi"; +import * as yaml from "yaml"; +import { + createDocument, + extendZodWithOpenApi, + ZodOpenApiOperationObject, +} from "zod-openapi"; + +extendZodWithOpenApi(z); + +const app = new OpenAPIHono(); +const registry = app.openAPIRegistry; + +// Define the Event Schema with detailed OpenAPI extensions +export const EventSchema = z + .object({ + name: z.string().openapi({ + description: "The name of the event.", + example: "Annual Meetup", + }), + channel: z.string().openapi({ + description: "The channel name associated with the event.", + example: "Main Channel", + }), + userId: z.string().openapi({ + description: "Associated ID that you want to have on the user", + example: "user999 OR John Doe", + }), + icon: z.string().optional().openapi({ + description: "An optional icon for visual representation of the event.", + example: "icon_event.png", + }), + notify: z.boolean().openapi({ + description: + "Flag indicating whether users should be notified about the event.", + example: true, + }), + tags: z + .record(z.string()) + .optional() + .openapi({ + description: + "Tags providing additional context or categorization for the event.", + example: { Networking: "Yes", Tech: "Yes" }, + }), + }) + .openapi({ ref: "Event" }); + +// Schema for creating an event +export const EventCreateSchema = z + .object({ + name: z.string().openapi({ + description: "The name of the event.", + example: "You got a new payment", + }), + channel: z.string().openapi({ + description: "The channel name where the event is registered.", + example: "new-channel-name", + }), + userId: z.string().openapi({ + description: "The ID of the user associated with the event.", + example: "user-999", + }), + icon: z.string().optional().openapi({ + description: "An optional icon representing the event.", + example: "๐ŸŽ‰", + }), + notify: z.boolean().openapi({ + description: "Whether to notify users about the event.", + example: true, + }), + tags: z + .record(z.string()) + .optional() + .openapi({ + description: "Additional tags providing context for the event.", + example: { plan: "premium", cycle: "monthly" }, + }), + }) + .openapi({ ref: "EventCreate" }); + +// CRUD operations for Events +export const logEvent: ZodOpenApiOperationObject = { + operationId: "logEvent", + summary: "Log a new event", + description: "Logs a new event for a user in a specified channel.", + requestBody: { + description: "Details of the event to log.", + content: { + "application/json": { + schema: EventCreateSchema, + }, + }, + }, + responses: { + "201": { + description: "Event logged successfully.", + content: { + "application/json": { + schema: EventSchema, + }, + }, + }, + "404": { + description: "Channel or project not found.", + }, + "400": { + description: "Invalid input data.", + }, + }, +}; + +// Generate an OpenAPI document +const document = createDocument({ + openapi: "3.1.0", + info: { + title: "User and Event Management API", + description: "API for managing users, their events, and projects.", + version: "1.0.0", + }, + servers: [ + { + url: "https://example.com", + description: "The production server.", + }, + ], + paths: { + "/events": { post: logEvent }, + }, + components: { + schemas: { + Event: EventSchema, + EventCreate: EventCreateSchema, + }, + }, +}); + +console.log(yaml.stringify(document)); diff --git a/apps/api/src/validators/types.ts b/apps/api/src/validators/types.ts new file mode 100644 index 0000000..507fcb7 --- /dev/null +++ b/apps/api/src/validators/types.ts @@ -0,0 +1,19 @@ +interface User { + id: number; + name?: string; + email: string; + plan: string; + events: Event[]; + createdAt: Date; +} + +interface Event { + id: number; + channel: string; + event: string; + userId: number; + icon: string; + notify: boolean; + tags: Record; + createdAt: Date; +} diff --git a/apps/api/src/zod/index.ts b/apps/api/src/zod/index.ts new file mode 100644 index 0000000..4c7d35d --- /dev/null +++ b/apps/api/src/zod/index.ts @@ -0,0 +1,74 @@ +import { z } from "zod"; +import { extendZodWithOpenApi, createDocument } from "zod-openapi"; +import * as yaml from "yaml"; + +// Extend Zod with OpenAPI functionality +extendZodWithOpenApi(z); + +// Define the Event Schema with OpenAPI extensions +export const EventSchema = z.object({ + id: z.number().openapi({ + description: "The unique identifier of the event.", + example: 101, + }), + name: z.string().optional().openapi({ + description: "The user's name.", + example: "John Doe", + }), + channel: z.string().openapi({ + description: "The channel name associated with the event.", + example: "Main Channel", + }), + event: z.string().openapi({ + description: "The name of the event.", + example: "Annual Meetup", + }), + userId: z.number().openapi({ + description: "The ID of the user who created the event.", + example: 501, + }), + icon: z.string().optional().openapi({ + description: "An optional icon for the event.", + example: "icon.png", + }), + notify: z.boolean().openapi({ + description: "Flag to notify users about the event.", + example: true, + }), + tags: z + .record(z.string()) + .optional() + .openapi({ + description: "Optional tags for additional event metadata.", + example: { tag1: "Networking", tag2: "Tech" }, + }), + createdAt: z.date().openapi({ + description: "The creation date of the event.", + }), +}); + +// Define the User Schema with OpenAPI extensions +export const UserSchema = z.object({ + id: z.number().openapi({ + description: "The unique identifier of the user.", + example: 501, + }), + name: z.string().optional().openapi({ + description: "The user's name.", + example: "John Doe", + }), + email: z.string().email().openapi({ + description: "The user's email address.", + example: "john.doe@example.com", + }), + plan: z.string().openapi({ + description: "The subscription plan of the user.", + example: "Pro", + }), + events: z.array(EventSchema).openapi({ + description: "A list of events associated with the user.", + }), + createdAt: z.date().openapi({ + description: "The creation date of the user's account.", + }), +}); diff --git a/apps/api/tsconfig.json b/apps/api/tsconfig.json new file mode 100644 index 0000000..c00e6fb --- /dev/null +++ b/apps/api/tsconfig.json @@ -0,0 +1,17 @@ +{ + "compilerOptions": { + "target": "ESNext", + "module": "ESNext", + "moduleResolution": "Bundler", + "strict": true, + "skipLibCheck": true, + "lib": [ + "ESNext" + ], + "types": [ + "@cloudflare/workers-types" + ], + "jsx": "react-jsx", + "jsxImportSource": "hono/jsx" + }, +} \ No newline at end of file diff --git a/apps/www/contentlayer.config.js b/apps/www/contentlayer.config.js new file mode 100644 index 0000000..b6ed507 --- /dev/null +++ b/apps/www/contentlayer.config.js @@ -0,0 +1,191 @@ +import { defineDocumentType, makeSource } from "contentlayer/source-files"; +import rehypeAutolinkHeadings from "rehype-autolink-headings"; +import rehypePrettyCode from "rehype-pretty-code"; +import rehypeSlug from "rehype-slug"; +import remarkGfm from "remark-gfm"; + +/** @type {import('contentlayer/source-files').ComputedFields} */ +const computedFields = { + slug: { + type: "string", + resolve: (doc) => `/${doc._raw.flattenedPath}`, + }, + slugAsParams: { + type: "string", + resolve: (doc) => doc._raw.flattenedPath.split("/").slice(1).join("/"), + }, +}; + +export const Doc = defineDocumentType(() => ({ + name: "Doc", + filePathPattern: `docs/**/*.mdx`, + contentType: "mdx", + fields: { + title: { + type: "string", + required: true, + }, + description: { + type: "string", + }, + published: { + type: "boolean", + default: true, + }, + }, + computedFields, +})); + +export const Guide = defineDocumentType(() => ({ + name: "Guide", + filePathPattern: `guides/**/*.mdx`, + contentType: "mdx", + fields: { + title: { + type: "string", + required: true, + }, + description: { + type: "string", + }, + date: { + type: "date", + required: true, + }, + published: { + type: "boolean", + default: true, + }, + featured: { + type: "boolean", + default: false, + }, + }, + computedFields, +})); + +export const Post = defineDocumentType(() => ({ + name: "Post", + filePathPattern: `blog/**/*.mdx`, + contentType: "mdx", + fields: { + title: { + type: "string", + required: true, + }, + description: { + type: "string", + }, + date: { + type: "date", + required: true, + }, + published: { + type: "boolean", + default: true, + }, + image: { + type: "string", + required: true, + }, + authors: { + // Reference types are not embedded. + // Until this is fixed, we can use a simple list. + // type: "reference", + // of: Author, + type: "list", + of: { type: "string" }, + required: true, + }, + }, + computedFields, +})); + +export const Author = defineDocumentType(() => ({ + name: "Author", + filePathPattern: `authors/**/*.mdx`, + contentType: "mdx", + fields: { + title: { + type: "string", + required: true, + }, + description: { + type: "string", + }, + avatar: { + type: "string", + required: true, + }, + twitter: { + type: "string", + required: true, + }, + }, + computedFields, +})); + +export const Page = defineDocumentType(() => ({ + name: "Page", + filePathPattern: `pages/**/*.mdx`, + contentType: "mdx", + fields: { + title: { + type: "string", + required: true, + }, + description: { + type: "string", + }, + }, + computedFields, +})); + +export default makeSource({ + contentDirPath: "./content", + documentTypes: [Page, Doc, Guide, Post, Author], + mdx: { + remarkPlugins: [remarkGfm], + rehypePlugins: [ + rehypeSlug, + [ + rehypePrettyCode, + { + theme: "github-dark", + onVisitLine(node) { + // Prevent lines from collapsing in `display: grid` mode, and allow empty + // lines to be copy/pasted + if (node.children.length === 0) { + node.children = [{ type: "text", value: " " }]; + } + }, + onVisitHighlightedLine(node) { + // node.properties.className.push("line--highlighted") + + // FIX: I changed remark-gmf 4.0.0 to 3.0.1 (return a lot errors in mdx?) + // And solve error on onVisitHighlightedLine with code from : https://stackoverflow.com/questions/76549262/onvisithighlightedline-cannot-push-classname-using-rehype-pretty-code + const nodeClass = node.properties.className; + + if (nodeClass && nodeClass.length > 0) { + node.properties.className.push("line--highlighted"); + } else { + node.properties.className = ["line--highlighted"]; + } + }, + onVisitHighlightedWord(node) { + node.properties.className = ["word--highlighted"]; + }, + }, + ], + [ + rehypeAutolinkHeadings, + { + properties: { + className: ["subheading-anchor"], + ariaLabel: "Link to section", + }, + }, + ], + ], + }, +}); diff --git a/apps/www/eslint.config.js b/apps/www/eslint.config.js new file mode 100644 index 0000000..a8cde31 --- /dev/null +++ b/apps/www/eslint.config.js @@ -0,0 +1,35 @@ +import baseConfig from "@dingify/eslint-config/base"; +import nextjsConfig from "@dingify/eslint-config/nextjs"; +import reactConfig from "@dingify/eslint-config/react"; + +/** @type {import('typescript-eslint').Config} */ +export default [ + { + ignores: [".next/**"], + }, + ...baseConfig, + ...reactConfig, + ...nextjsConfig, + { + // TODO: Resolve errors when setting these rules to 'error' + rules: { + "@typescript-eslint/ban-ts-comment": "warn", + "@typescript-eslint/no-unsafe-member-access": "warn", + "@typescript-eslint/no-non-null-assertion": "warn", + "@typescript-eslint/consistent-type-definitions": "warn", + "@typescript-eslint/no-unnecessary-condition": "warn", + "@typescript-eslint/prefer-nullish-coalescing": "warn", + "@typescript-eslint/no-unsafe-argument": "warn", + "@typescript-eslint/no-unsafe-return": "warn", + "@typescript-eslint/no-unused-vars": "warn", + "@typescript-eslint/require-await": "warn", + "@typescript-eslint/no-explicit-any": "warn", + "@typescript-eslint/no-unsafe-assignment": "warn", + "@typescript-eslint/no-floating-promises": "warn", + "@typescript-eslint/no-non-null-asserted-optional-chain": "warn", + "@typescript-eslint/no-unsafe-call": "warn", + "@typescript-eslint/no-empty-function": "warn", + "@typescript-eslint/dot-notation": "warn", + }, + }, +]; diff --git a/apps/www/next.config.js b/apps/www/next.config.js new file mode 100644 index 0000000..83f5e5d --- /dev/null +++ b/apps/www/next.config.js @@ -0,0 +1,37 @@ +import { fileURLToPath } from "url"; +import createJiti from "jiti"; +import { createContentlayerPlugin } from "next-contentlayer"; + +// Import env files to validate at build time. Use jiti so we can load .ts files in here. +createJiti(fileURLToPath(import.meta.url))("./src/env"); + +/** @type {import("next").NextConfig} */ +const config = { + reactStrictMode: true, + swcMinify: true, + images: { + remotePatterns: [ + { + protocol: "https", + hostname: "avatars.githubusercontent.com", + }, + { + protocol: "https", + hostname: "lh3.googleusercontent.com", + }, + ], + }, + + /** Enables hot reloading for local packages without a build step */ + transpilePackages: ["@dingify/db", "@dingify/ui", "@dingify/db"], + + /** We already do linting and typechecking as separate tasks in CI */ + eslint: { ignoreDuringBuilds: true }, + typescript: { ignoreBuildErrors: true }, +}; + +const withContentlayer = createContentlayerPlugin({ + // Additional Contentlayer config options +}); + +export default withContentlayer(config); diff --git a/apps/www/package.json b/apps/www/package.json new file mode 100644 index 0000000..5842eff --- /dev/null +++ b/apps/www/package.json @@ -0,0 +1,101 @@ +{ + "name": "@dingify/www", + "version": "0.1.0", + "private": true, + "type": "module", + "scripts": { + "build": "pnpm with-env next build", + "clean": "git clean -xdf .next .turbo node_modules", + "dev": "pnpm with-env next dev", + "format": "prettier --check . --ignore-path ../../.gitignore", + "lint": "eslint ./src", + "start": "pnpm with-env next start", + "typecheck": "tsc --noEmit", + "with-env": "dotenv -e ../../.env --" + }, + "dependencies": { + "@dingify/db": "workspace:*", + "@dingify/ui": "workspace:*", + "@headlessui/react": "^1.7.17", + "@heroicons/react": "^2.0.18", + "@hookform/resolvers": "^3.3.2", + "@next-auth/prisma-adapter": "^1.0.7", + "@nivo/calendar": "^0.87.0", + "@nivo/funnel": "^0.86.0", + "@nivo/line": "^0.86.0", + "@react-email/button": "0.0.11", + "@react-email/components": "0.0.7", + "@react-email/html": "0.0.6", + "@t3-oss/env-nextjs": "^0.9.2", + "@tanstack/react-table": "^8.10.7", + "@typescript-eslint/parser": "^6.9.0", + "@vercel/analytics": "^1.1.1", + "@vercel/og": "^0.5.20", + "axios": "^1.6.7", + "canvas-confetti": "^1.9.3", + "class-variance-authority": "^0.7.0", + "clsx": "^2.0.0", + "cmdk": "^0.2.0", + "concurrently": "^8.2.2", + "contentlayer": "^0.3.4", + "date-fns": "^2.30.0", + "framer-motion": "^11.0.14", + "lucide-react": "^0.292.0", + "ms": "^2.1.3", + "next": "^14.2.3", + "next-auth": "4.24.4", + "next-contentlayer": "^0.3.4", + "next-themes": "^0.2.1", + "nodemailer": "^6.9.7", + "openai": "^4.16.1", + "postmark": "^3.1.1", + "prop-types": "^15.8.1", + "react": "18.2.0", + "react-activity-calendar": "^2.2.8", + "react-copy-to-clipboard": "^5.1.0", + "react-day-picker": "^8.9.1", + "react-dom": "18.2.0", + "react-dropzone": "^14.2.3", + "react-email": "1.9.5", + "react-facebook-pixel": "^1.0.4", + "react-hook-form": "^7.47.0", + "react-syntax-highlighter": "^15.5.0", + "react-textarea-autosize": "^8.5.3", + "react-wrap-balancer": "^1.1.0", + "recharts": "^2.12.7", + "resend": "^1.1.0", + "sharp": "^0.32.6", + "shiki": "^0.14.5", + "stripe": "^14.2.0", + "tailwind-merge": "^2.0.0", + "tailwindcss-animate": "^1.0.7", + "vaul": "^0.7.7", + "zod": "^3.23.4", + "zustand": "^4.4.5" + }, + "devDependencies": { + "@dingify/eslint-config": "workspace:*", + "@dingify/prettier-config": "workspace:*", + "@dingify/tailwind-config": "workspace:*", + "@dingify/tsconfig": "workspace:*", + "@types/node": "^20.12.5", + "@types/react": "^18.2.77", + "@types/react-dom": "^18.2.25", + "autoprefixer": "^10.4.16", + "dotenv-cli": "^7.4.1", + "jiti": "^1.21.0", + "mdast-util-toc": "^7.0.0", + "prettier": "^3.2.5", + "pretty-quick": "^3.1.3", + "rehype": "^13.0.1", + "rehype-autolink-headings": "^7.0.0", + "rehype-pretty-code": "^0.10.2", + "rehype-slug": "^6.0.0", + "remark": "^15.0.1", + "remark-gfm": "^3.0.1", + "tailwindcss": "^3.4.3", + "typescript": "^5.4.5", + "unist-util-visit": "^5.0.0" + }, + "prettier": "@dingify/prettier-config" +} diff --git a/apps/www/postcss.config.cjs b/apps/www/postcss.config.cjs new file mode 100644 index 0000000..ee5f90b --- /dev/null +++ b/apps/www/postcss.config.cjs @@ -0,0 +1,5 @@ +module.exports = { + plugins: { + tailwindcss: {}, + }, +}; diff --git a/apps/www/public/android-chrome-192x192.png b/apps/www/public/android-chrome-192x192.png new file mode 100644 index 0000000..fe8c79d Binary files /dev/null and b/apps/www/public/android-chrome-192x192.png differ diff --git a/apps/www/public/android-chrome-512x512.png b/apps/www/public/android-chrome-512x512.png new file mode 100644 index 0000000..ecc37e2 Binary files /dev/null and b/apps/www/public/android-chrome-512x512.png differ diff --git a/apps/www/public/apple-touch-icon.png b/apps/www/public/apple-touch-icon.png new file mode 100644 index 0000000..6ed1c85 Binary files /dev/null and b/apps/www/public/apple-touch-icon.png differ diff --git a/apps/www/public/favicon-16x16.png b/apps/www/public/favicon-16x16.png new file mode 100644 index 0000000..897b687 Binary files /dev/null and b/apps/www/public/favicon-16x16.png differ diff --git a/apps/www/public/favicon-32x32.png b/apps/www/public/favicon-32x32.png new file mode 100644 index 0000000..7ffdf7f Binary files /dev/null and b/apps/www/public/favicon-32x32.png differ diff --git a/apps/www/public/favicon.ico b/apps/www/public/favicon.ico new file mode 100644 index 0000000..74228e9 Binary files /dev/null and b/apps/www/public/favicon.ico differ diff --git a/apps/www/public/hero-dark.png b/apps/www/public/hero-dark.png new file mode 100644 index 0000000..0ab4fb5 Binary files /dev/null and b/apps/www/public/hero-dark.png differ diff --git a/apps/www/public/hero-dark2.png b/apps/www/public/hero-dark2.png new file mode 100644 index 0000000..cc6cfc1 Binary files /dev/null and b/apps/www/public/hero-dark2.png differ diff --git a/apps/www/public/hero-light.png b/apps/www/public/hero-light.png new file mode 100644 index 0000000..707eb77 Binary files /dev/null and b/apps/www/public/hero-light.png differ diff --git a/apps/www/public/hero-light2.png b/apps/www/public/hero-light2.png new file mode 100644 index 0000000..48f75e6 Binary files /dev/null and b/apps/www/public/hero-light2.png differ diff --git a/apps/www/public/images/avatars/shadcn.png b/apps/www/public/images/avatars/shadcn.png new file mode 100644 index 0000000..8acf77e Binary files /dev/null and b/apps/www/public/images/avatars/shadcn.png differ diff --git a/apps/www/public/images/blog/blog-post-1.jpg b/apps/www/public/images/blog/blog-post-1.jpg new file mode 100644 index 0000000..0cdc7d3 Binary files /dev/null and b/apps/www/public/images/blog/blog-post-1.jpg differ diff --git a/apps/www/public/images/blog/blog-post-2.jpg b/apps/www/public/images/blog/blog-post-2.jpg new file mode 100644 index 0000000..164d589 Binary files /dev/null and b/apps/www/public/images/blog/blog-post-2.jpg differ diff --git a/apps/www/public/images/blog/blog-post-3.jpg b/apps/www/public/images/blog/blog-post-3.jpg new file mode 100644 index 0000000..798d8c8 Binary files /dev/null and b/apps/www/public/images/blog/blog-post-3.jpg differ diff --git a/apps/www/public/images/blog/blog-post-4.jpg b/apps/www/public/images/blog/blog-post-4.jpg new file mode 100644 index 0000000..b17510c Binary files /dev/null and b/apps/www/public/images/blog/blog-post-4.jpg differ diff --git a/apps/www/public/images/download.svg b/apps/www/public/images/download.svg new file mode 100644 index 0000000..f0fd007 --- /dev/null +++ b/apps/www/public/images/download.svg @@ -0,0 +1,473 @@ + + + + + + + + + + + + + + + + + + + + + + + diff --git a/apps/www/public/images/hero.png b/apps/www/public/images/hero.png new file mode 100644 index 0000000..be32fbc Binary files /dev/null and b/apps/www/public/images/hero.png differ diff --git a/apps/www/public/og.jpg b/apps/www/public/og.jpg new file mode 100644 index 0000000..0680fe1 Binary files /dev/null and b/apps/www/public/og.jpg differ diff --git a/apps/www/public/og2.jpg b/apps/www/public/og2.jpg new file mode 100644 index 0000000..054e377 Binary files /dev/null and b/apps/www/public/og2.jpg differ diff --git a/apps/www/public/site.webmanifest b/apps/www/public/site.webmanifest new file mode 100644 index 0000000..4667dbd --- /dev/null +++ b/apps/www/public/site.webmanifest @@ -0,0 +1,19 @@ +{ + "name": "Propwrite", + "short_name": "Propwrite", + "icons": [ + { + "src": "/android-chrome-192x192.png", + "sizes": "192x192", + "type": "image/png" + }, + { + "src": "/android-chrome-512x512.png", + "sizes": "512x512", + "type": "image/png" + } + ], + "theme_color": "#ffffff", + "background_color": "#ffffff", + "display": "standalone" +} diff --git a/apps/www/public/vercel.svg b/apps/www/public/vercel.svg new file mode 100644 index 0000000..fbf0e25 --- /dev/null +++ b/apps/www/public/vercel.svg @@ -0,0 +1,4 @@ + + + \ No newline at end of file diff --git a/apps/www/src/actions/change-customer-details.ts b/apps/www/src/actions/change-customer-details.ts new file mode 100644 index 0000000..394b1a3 --- /dev/null +++ b/apps/www/src/actions/change-customer-details.ts @@ -0,0 +1,23 @@ +// actions/update-customer.ts +"use server"; + +import { revalidatePath } from "next/cache"; + +import { prisma } from "@/lib/db"; + +export async function changeCustomerDetails(customerId, data) { + try { + const updatedCustomer = await prisma.customer.update({ + where: { id: customerId }, + data, + }); + + // Revalidate the path after updating the customer + revalidatePath("/dashboard/users"); + + return { success: true, customer: updatedCustomer }; + } catch (error) { + console.error("Error updating customer:", error); + return { success: false, error: error.message }; + } +} diff --git a/apps/www/src/actions/change-notification-settings.ts b/apps/www/src/actions/change-notification-settings.ts new file mode 100644 index 0000000..bd321d0 --- /dev/null +++ b/apps/www/src/actions/change-notification-settings.ts @@ -0,0 +1,61 @@ +"use server"; + +import { NotificationType } from "@prisma/client"; + +import { prisma } from "@/lib/db"; +import { getCurrentUser } from "@/lib/session"; + +export async function updateNotificationSettings(data: { + name: string; + provider: string; + webhook: string; +}) { + const user = await getCurrentUser(); + const userId = user?.id; + + if (!userId) { + console.error("No user is currently logged in."); + return { success: false, error: "User not authenticated" }; + } + try { + // Find the existing notification setting based on userId + const existingSetting = await prisma.notificationSetting.findFirst({ + where: { userId }, + }); + + let updatedSettings; + + const providerType = data.provider.toUpperCase() as NotificationType; + + if (existingSetting) { + // Update the existing setting + updatedSettings = await prisma.notificationSetting.update({ + where: { id: existingSetting.id }, + data: { + type: providerType, + details: { + webhook: data.webhook, + name: data.name, + }, + }, + }); + } else { + // Create a new setting if it doesn't exist + updatedSettings = await prisma.notificationSetting.create({ + data: { + userId, + type: providerType, + details: { + webhook: data.webhook, + name: data.name, + }, + }, + }); + } + + return { success: true, settings: updatedSettings }; + } catch (error) { + console.error("Error updating notification settings:", error); + return { success: false, error: error.message }; + } +} diff --git a/apps/www/src/actions/create-channel.ts b/apps/www/src/actions/create-channel.ts new file mode 100644 index 0000000..b707dfa --- /dev/null +++ b/apps/www/src/actions/create-channel.ts @@ -0,0 +1,47 @@ +// actions/create-channel.ts +"use server"; + +import { revalidatePath } from "next/cache"; + +import { prisma } from "@/lib/db"; +import { getCurrentUser } from "@/lib/session"; + +export async function createChannel(channelName: string) { + const user = await getCurrentUser(); + const userId = user?.id; + + if (!userId) { + console.error("No user is currently logged in."); + return { success: false, error: "User not authenticated" }; + } + + try { + // Fetch the user's projects to associate the channel with the first project found + const projects = await prisma.project.findMany({ + where: { userId: userId }, + select: { id: true }, + }); + + if (projects.length === 0) { + throw new Error("No projects found for this user"); + } + + // Create a new channel within the first project + const newChannel = await prisma.channel.create({ + data: { + name: channelName, + projectId: projects[0]!.id, // associate with the first project + }, + }); + console.log( + `Created channel with ID: ${newChannel.id} for project ID: ${projects[0]!.id}.`, + ); + + revalidatePath("/dashboard"); // Updates the cache for the dashboard page + + return { success: true, channel: newChannel }; + } catch (error) { + console.error(`Error creating channel for user ID: ${userId}`, error); + return { success: false, error: error.message }; + } +} diff --git a/apps/www/src/actions/create-event.ts b/apps/www/src/actions/create-event.ts new file mode 100644 index 0000000..eeb2484 --- /dev/null +++ b/apps/www/src/actions/create-event.ts @@ -0,0 +1,150 @@ +// actions/create-event.js +"use server"; + +import { revalidatePath } from "next/cache"; + +import { prisma } from "@/lib/db"; +import { getCurrentUser } from "@/lib/session"; +import { sendDiscordNotification, sendSlackNotification } from "@/lib/utils"; + +type NotificationDetails = { + webhook: string; + name: string; +}; + +export async function createEvent(data) { + const currentUser = await getCurrentUser(); + if (!currentUser) { + throw new Error("User not authenticated"); + } + + const { channel, name, user_id, icon, notify } = data; + + if (!channel || !name || !user_id || !icon) { + throw new Error("All fields are required"); + } + + // Ensure the authenticated user's project exists + const project = await prisma.project.findFirst({ + where: { userId: currentUser.id }, + }); + + if (!project) { + throw new Error("Project not found for the authenticated user"); + } + + // Ensure the channel is unique within the project + const upsertChannel = await prisma.channel.upsert({ + where: { + projectId_name: { + projectId: project.id, + name: channel, + }, + }, + update: {}, + create: { + name: channel, + projectId: project.id, + }, + }); + + // Check if the customer exists based on user_id and project_id + let customer = await prisma.customer.findUnique({ + where: { + userId_projectId: { + userId: user_id, + projectId: project.id, + }, + }, + }); + + // If the customer does not exist, create a new customer + if (!customer) { + try { + customer = await prisma.customer.create({ + data: { + projectId: project.id, + userId: user_id, + name: "", // Assuming name and email are optional + email: "", + createdAt: new Date(), + }, + }); + console.log("New customer created:", customer); // Log the new customer + } catch (error) { + console.error("Error creating customer:", error); + throw error; + } + } else { + console.log("Existing customer found:", customer); // Log the existing customer + } + + // Create the event and associate it with the customer + try { + const newEvent = await prisma.event.create({ + data: { + name, + userId: user_id, // userId here is a plain string + icon, + notify, + tags: {}, // Provide an empty object or handle this according to your schema + channelId: upsertChannel.id, + customerId: customer.id, // Associate the event with the customer + }, + }); + + console.log("New event created:", newEvent); // Log the new event + + // Update logs metrics for the project + const metrics = await prisma.metrics.findUnique({ + where: { projectId: project.id }, + }); + + if (metrics) { + await prisma.metrics.update({ + where: { id: metrics.id }, + data: { + logsUsed: { increment: 1 }, + }, + }); + // Fetch the updated metrics and log them + const updatedMetrics = await prisma.metrics.findUnique({ + where: { id: metrics.id }, + }); + console.log("Updated metrics:", updatedMetrics); + } else { + console.error("Metrics not found for the project"); + } + + // Revalidate the path where the event is displayed + revalidatePath("/dashboard"); + + // Fetch notification settings for the current user + const notificationSettings = await prisma.notificationSetting.findFirst({ + where: { userId: currentUser.id }, + }); + + if (notificationSettings) { + const { type, details } = notificationSettings; + const detailsParsed = details as NotificationDetails; + + // Send notification based on the provider type + if (type === "DISCORD" && detailsParsed?.webhook) { + await sendDiscordNotification( + detailsParsed.webhook, + `Event created: ${name}`, + ); + } else if (type === "SLACK" && detailsParsed?.webhook) { + await sendSlackNotification( + detailsParsed.webhook, + `Event created: ${name}`, + ); + } + } + + return { success: true, event: newEvent }; + } catch (error) { + console.error("Error creating event:", error); + throw error; + } +} diff --git a/apps/www/src/actions/create-project-and-channel.ts b/apps/www/src/actions/create-project-and-channel.ts new file mode 100644 index 0000000..2793907 --- /dev/null +++ b/apps/www/src/actions/create-project-and-channel.ts @@ -0,0 +1,63 @@ +// actions/create-project-and-channel.js +"use server"; + +import { prisma } from "@/lib/db"; +import { getCurrentUser } from "@/lib/session"; + +export async function createProjectAndChannel(projectName) { + const user = await getCurrentUser(); + const userId = user?.id; + + if (!userId) { + console.error("No user is currently logged in."); + return { success: false, error: "User not authenticated" }; + } + + try { + // Create the new project + const newProject = await prisma.project.create({ + data: { + name: projectName, + userId: userId, + }, + }); + console.log( + `Created project with ID: ${newProject.id} for user ID: ${userId}.`, + ); + + // Create a new channel with a default name within the new project + const newChannel = await prisma.channel.create({ + data: { + name: "new-channel-name", + projectId: newProject.id, + }, + }); + console.log( + `Created channel with ID: ${newChannel.id} for project ID: ${newProject.id}.`, + ); + + // Create a metrics record for the new project + const newMetrics = await prisma.metrics.create({ + data: { + projectId: newProject.id, + logsUsed: 0, + logsLimit: 1000, + channelsUsed: 1, + channelsLimit: 3, + seatsUsed: 1, + projectsUsed: 1, + }, + }); + console.log( + `Created metrics with ID: ${newMetrics.id} for project ID: ${newProject.id}.`, + ); + + return { success: true, project: newProject, channel: newChannel }; + } catch (error) { + console.error( + `Error creating project and channel for user ID: ${userId}`, + error, + ); + return { success: false, error: error.message }; + } +} diff --git a/apps/www/src/actions/delete-customer.ts b/apps/www/src/actions/delete-customer.ts new file mode 100644 index 0000000..f04362f --- /dev/null +++ b/apps/www/src/actions/delete-customer.ts @@ -0,0 +1,22 @@ +// actions/delete-customer.ts +"use server"; + +import { revalidatePath } from "next/cache"; + +import { prisma } from "@/lib/db"; + +export async function deleteCustomer(customerId) { + try { + await prisma.customer.delete({ + where: { id: customerId }, + }); + + // Revalidate the path after deleting the customer + revalidatePath("/dashboard/users"); + + return { success: true }; + } catch (error) { + console.error("Error deleting customer:", error); + return { success: false, error: error.message }; + } +} diff --git a/apps/www/src/actions/delete-event.ts b/apps/www/src/actions/delete-event.ts new file mode 100644 index 0000000..c0af2f8 --- /dev/null +++ b/apps/www/src/actions/delete-event.ts @@ -0,0 +1,34 @@ +"use server"; + +import { prisma } from "@/lib/db"; +import { getCurrentUser } from "@/lib/session"; + +export async function deleteEvent(eventId) { + const user = await getCurrentUser(); + if (!user) { + throw new Error("User not authenticated"); + } + + const event = await prisma.event.findUnique({ + where: { id: eventId }, + include: { + channel: { + include: { + project: true, + }, + }, + }, + }); + + if (!event || event.channel.project.userId !== user.id) { + throw new Error( + "Event not found or you don't have permission to delete this event", + ); + } + + await prisma.event.delete({ + where: { id: eventId }, + }); + + return { success: true }; +} diff --git a/apps/www/src/actions/generate-api-key.ts b/apps/www/src/actions/generate-api-key.ts new file mode 100644 index 0000000..da8ebd4 --- /dev/null +++ b/apps/www/src/actions/generate-api-key.ts @@ -0,0 +1,54 @@ +// actions/generate-api-key.js +"use server"; + +import { revalidatePath } from "next/cache"; +import { createProjectAndChannel } from "@/actions/create-project-and-channel"; // Import the function + +import { prisma } from "@/lib/db"; +import { getCurrentUser } from "@/lib/session"; + +import { generateApiKey } from "../lib/crypto"; + +export async function generateAndSaveApiKey() { + const user = await getCurrentUser(); + const userId = user?.id; + + if (!userId) { + console.error("No user is currently logged in."); + return { success: false, error: "User not authenticated" }; + } + + const apiKey = generateApiKey(); + console.log(`Generated API key for user ID: ${userId}. API Key: ${apiKey}`); + + try { + const updatedUser = await prisma.user.update({ + where: { id: userId }, + data: { apiKey }, + }); + console.log(`API key saved successfully for user ID: ${userId}.`); + + // Create a new project and channel + const projectResponse = await createProjectAndChannel("Project1"); + if (!projectResponse.success) { + throw new Error(projectResponse.error); + } + + console.log( + `Project and channel created successfully for user ID: ${userId}.`, + ); + + // revalidatePath("/dashboard"); + + return { + success: true, + user: updatedUser, + apiKey, + project: projectResponse.project, + channel: projectResponse.channel, + }; + } catch (error) { + console.error(`Error saving API key for user ID: ${userId}`, error); + return { success: false, error: error.message }; + } +} diff --git a/apps/www/src/actions/generate-description.ts b/apps/www/src/actions/generate-description.ts new file mode 100644 index 0000000..d802b01 --- /dev/null +++ b/apps/www/src/actions/generate-description.ts @@ -0,0 +1,79 @@ +"use server"; + +import { prisma } from "@dingify/db"; +import { getCurrentUser } from "@/lib/session"; +import axios from "axios"; + +export async function generateDescription(propertyId, seed = 12345) { + console.log("Fetching images for property ID:", propertyId); // Log the property ID being queried + const openaiApiKey = process.env.OPENAI_API_KEY; + const user = await getCurrentUser(); + const userlang = await prisma.user.findUnique({ + where: { id: user?.id }, + }); + + const userLanguage = userlang?.language || "english"; + + const descriptionPrompts = { + english: + "I need you to act as a real estate agent creating a sales ad. I always need a title and the description below. Please format it in JSON. The JSON should always use only title, description, section, details.", + swedish: + "Jag behรถver att du agerar som en fastighetsmรคklare som ska skapa en fรถrsรคljningsannons. Jag behรถver alltid en titel och beskrivningen nedan. Formatera det i JSON-format. JSON bรถr alltid bara anvรคnda titel, beskrivning, avsnitt, detaljer.", + norwegian: + "Jeg trenger at du opptrer som en eiendomsmegler som skal lage en salgsannonse. Jeg trenger alltid en tittel og beskrivelsen nedenfor gjerne ha den utfyllende. Formater det i et JSON-format. JSON bรธr alltid bare bruke tittel, beskrivelse, seksjon, detaljer.", + }; + + let propertyDescriptionText; + try { + const images = await prisma.image.findMany({ + where: { propertyId }, + select: { selectedOption: true }, + }); + + propertyDescriptionText = images + .map((image) => image.selectedOption) + .filter((text) => text != null) // Ensure no null values are included + .join(" "); + } catch (fetchError) { + console.error("Error fetching images from the database:", fetchError); + throw new Error("Error fetching images from the database"); + } + + if (!openaiApiKey) { + console.error("OpenAI API key is not set in environment variables."); + throw new Error("OpenAI API key not found"); + } + + const headers = { + Authorization: `Bearer ${openaiApiKey}`, + "Content-Type": "application/json", + }; + + const requestBody = { + model: "gpt-4-1106-preview", // or another model as needed + response_format: { type: "json_object" }, + messages: [ + { + role: "system", + content: descriptionPrompts[userLanguage], + }, + { role: "user", content: propertyDescriptionText }, + ], + }; + + console.log("Sending request to OpenAI with requestBody:", requestBody); // Log the requestBody being sent + + try { + const response = await axios.post( + "https://api.openai.com/v1/chat/completions", + requestBody, + { headers } + ); + const generatedDescription = response.data.choices[0].message.content; + console.log("Received response from OpenAI:", generatedDescription); // Log the OpenAI response + return generatedDescription; + } catch (error) { + console.error("Error generating property description with OpenAI:", error); + throw new Error("Error generating property description with OpenAI"); + } +} diff --git a/apps/www/src/actions/generate-options.ts b/apps/www/src/actions/generate-options.ts new file mode 100644 index 0000000..7445397 --- /dev/null +++ b/apps/www/src/actions/generate-options.ts @@ -0,0 +1,90 @@ +// actions/generate-options.js + +import axios from "axios"; + +import { prisma } from "@dingify/db"; + +export const maxDuration = 50; + +export async function generateOptions( + imageId, + imageUrl, + language = "norwegian" +) { + "use server"; // This directive ensures that this function is server-only + + const openaiApiKey = process.env.OPENAI_API_KEY; + + if (!openaiApiKey) { + console.error("OpenAI API key is not set in environment variables."); + throw new Error("OpenAI API key not found"); + } + + const headers = { + Authorization: `Bearer ${openaiApiKey}`, + "Content-Type": "application/json", + }; + + const prompts = { + english: + "I want you to act as a real estate agent. I would like you to create text based on the image you receive, writing a detailed and appealing property description. The style should be professional, and the description should be about one line long. I want 3 different lines so I can choose. Include unique features and highlight what makes this property special. Don't use '' in the response", + swedish: + "Jag vill att du agerar som en fastighetsmรคklare. Jag skulle vilja att du skapar text baserad pรฅ den bild du fรฅr, och skriver en detaljerad och tilltalande egendomsbeskrivning. Stilen bรถr vara professionell, och beskrivningen bรถr vara ungefรคr en mening lรฅng. Jag vill ha 3 olika meningar sรฅ att jag kan vรคlja. Inkludera unika funktioner och framhรคv vad som gรถr denna egendom speciell.", + norwegian: + "Jeg รธnsker at du skal opptre som en eiendomsmegler. Jeg vil at du skal lage tekst basert pรฅ bildet du mottar, og skrive en detaljert og tiltalende eiendomsbeskrivelse. Stilen skal vรฆre profesjonell, og beskrivelsen skal vรฆre omtrent รฉn setning lang. Jeg รธnsker 3 forskjellige setninger slik at jeg kan velge. Inkluder unike funksjoner og fremhev hva som gjรธr denne eiendommen spesiell. Jeg รธnsker at du skriver teksten pรฅ norsk.", + }; + + const requestBody = { + model: "gpt-4-vision-preview", + messages: [ + { + role: "user", + content: [ + { type: "text", text: prompts[language] }, + { type: "image_url", image_url: imageUrl }, + ], + }, + ], + max_tokens: 300, + }; + + console.log(`Sending request to OpenAI for image ${imageUrl}`); + + try { + const response = await axios.post( + "https://api.openai.com/v1/chat/completions", + requestBody, + { headers } + ); + + console.log( + `Received response from OpenAI for image ${imageUrl}:`, + response.data + ); + + const options = response.data.choices[0].message.content + .split("\n") + .filter((text) => text.trim() !== ""); + + if (options.length < 3) { + throw new Error("Not enough options returned from Ai."); + } + + await prisma.image.update({ + where: { id: imageId }, + data: { + option1: options[0], + option2: options[1], + option3: options[2], + }, + }); + + console.log(`Options generated for image ${imageId}:`, options); + } catch (error) { + console.error( + `Error when generating options for image ${imageId}:`, + error.response ? error.response.data : error + ); + throw new Error("Failed to generate options"); + } +} diff --git a/apps/www/src/actions/generate-user-stripe.ts b/apps/www/src/actions/generate-user-stripe.ts new file mode 100644 index 0000000..ecd5688 --- /dev/null +++ b/apps/www/src/actions/generate-user-stripe.ts @@ -0,0 +1,68 @@ +"use server"; + +import { redirect } from "next/navigation"; +import { authOptions } from "@/lib/auth"; +import { stripe } from "@/lib/stripe"; +import { getUserSubscriptionPlan } from "@/lib/subscription"; +import { absoluteUrl } from "@/lib/utils"; +import { getServerSession } from "next-auth"; + +export interface responseAction { + status: "success" | "error"; + stripeUrl?: string; +} + +// const billingUrl = absoluteUrl("/dashboard/billing") +const billingUrl = absoluteUrl("/pricing"); + +export async function generateUserStripe( + priceId: string +): Promise { + let redirectUrl = ""; + + try { + const session = await getServerSession(authOptions); + + if (!session?.user || !session.user.email) { + throw new Error("Unauthorized"); + } + + const subscriptionPlan = await getUserSubscriptionPlan(session.user.id); + + if (subscriptionPlan.isPaid && subscriptionPlan.stripeCustomerId) { + // User on Paid Plan - Create a portal session to manage subscription. + const stripeSession = await stripe.billingPortal.sessions.create({ + customer: subscriptionPlan.stripeCustomerId, + return_url: billingUrl, + }); + + redirectUrl = stripeSession.url; + } else { + // User on Free Plan - Create a checkout session to upgrade. + const stripeSession = await stripe.checkout.sessions.create({ + success_url: billingUrl, + cancel_url: billingUrl, + payment_method_types: ["card"], + mode: "subscription", + billing_address_collection: "auto", + customer_email: session.user.email, + line_items: [ + { + price: priceId, + quantity: 1, + }, + ], + metadata: { + userId: session.user.id, + }, + }); + + redirectUrl = stripeSession.url!; + } + } catch (error) { + throw new Error("Failed to generate user stripe session"); + } + + // no revalidatePath because redirect + redirect(redirectUrl); +} diff --git a/apps/www/src/actions/get-channel-details.ts b/apps/www/src/actions/get-channel-details.ts new file mode 100644 index 0000000..5fadd2b --- /dev/null +++ b/apps/www/src/actions/get-channel-details.ts @@ -0,0 +1,31 @@ +"use server"; + +import { prisma } from "@/lib/db"; +import { getCurrentUser } from "@/lib/session"; + +export async function getChannelDetails(channelId: string) { + const user = await getCurrentUser(); + const userId = user?.id; + + if (!userId) { + throw new Error("User not authenticated"); + } + + if (!channelId || typeof channelId !== "string") { + throw new Error("Channel ID is required and must be a string"); + } + + const channel = await prisma.channel.findUnique({ + where: { id: channelId }, + include: { + project: true, + events: true, + }, + }); + + if (!channel || channel.project.userId !== userId) { + throw new Error("Channel not found or you do not have access to it"); + } + + return channel; +} diff --git a/apps/www/src/actions/get-channels.ts b/apps/www/src/actions/get-channels.ts new file mode 100644 index 0000000..f60b6e7 --- /dev/null +++ b/apps/www/src/actions/get-channels.ts @@ -0,0 +1,40 @@ +"use server"; + +// actions/get-channels.ts +import { prisma } from "@/lib/db"; +import { getCurrentUser } from "@/lib/session"; + +export async function getUserChannels() { + const user = await getCurrentUser(); + if (!user) { + throw new Error("User not authenticated"); + } + + // Fetch projects associated with the user + const projects = await prisma.project.findMany({ + where: { + userId: user.id, + }, + select: { + id: true, + }, + }); + + // Extract project IDs + const projectIds = projects.map((project) => project.id); + + // Fetch channels for the user's projects + const channels = await prisma.channel.findMany({ + where: { + projectId: { + in: projectIds, + }, + }, + select: { + id: true, + name: true, + }, + }); + + return channels; +} diff --git a/apps/www/src/actions/get-credits.ts b/apps/www/src/actions/get-credits.ts new file mode 100644 index 0000000..da67a42 --- /dev/null +++ b/apps/www/src/actions/get-credits.ts @@ -0,0 +1,36 @@ +// actions/get-user-credits.js +"use server"; + +import { getCurrentUser } from "@/lib/session"; + +import { prisma } from "@dingify/db"; + +export async function getUserCredits() { + const user = await getCurrentUser(); + const userId = user?.id; + + if (!userId) { + console.error("No user found for fetching credits."); + return { success: false, error: "No user found." }; + } + + try { + const userWithCredits = await prisma.user.findUnique({ + where: { id: userId }, + select: { credits: true }, + }); + + if (userWithCredits) { + console.log( + `Credits for user ID: ${userId} are ${userWithCredits.credits}` + ); + return { success: true, credits: userWithCredits.credits }; + } else { + console.error(`No user found with ID: ${userId}`); + return { success: false, error: "User not found." }; + } + } catch (error) { + console.error(`Error fetching credits for user ID: ${userId}`, error); + return { success: false, error: error.message }; + } +} diff --git a/apps/www/src/actions/get-customer-details.ts b/apps/www/src/actions/get-customer-details.ts new file mode 100644 index 0000000..792f487 --- /dev/null +++ b/apps/www/src/actions/get-customer-details.ts @@ -0,0 +1,71 @@ +// actions/get-customer-details.ts +"use server"; + +import { subDays } from "date-fns"; + +import { prisma } from "@/lib/db"; + +export async function getCustomerDetails(customerId: string) { + try { + const customer = await prisma.customer.findUnique({ + where: { id: customerId }, + include: { + events: { + orderBy: { + createdAt: "asc", + }, + include: { + channel: true, + }, + }, + }, + }); + + if (!customer) { + throw new Error("Customer not found"); + } + + const now = new Date(); + const fourteenDaysAgo = subDays(now, 14); + + // Calculate events in the last 14 days + const recentEvents = customer.events.filter( + (event) => new Date(event.createdAt) >= fourteenDaysAgo, + ); + + const eventCountLast14Days = recentEvents.length; + + let userStatus = "Idle User ๐Ÿ˜ด"; + if (eventCountLast14Days > 10) { + userStatus = "Power User ๐Ÿ”ฅ"; + } else if (eventCountLast14Days >= 1) { + userStatus = "Engaged User ๐Ÿ‘"; + } + + // Calculate the first and last seen dates and most used feature + const firstSeen = customer.events[0]?.createdAt || null; + const lastSeen = + customer.events[customer.events.length - 1]?.createdAt || null; + + // Calculate the most used feature + const featureUsage = customer.events.reduce((acc, event) => { + acc[event.name] = (acc[event.name] || 0) + 1; + return acc; + }, {}); + const mostUsedFeature = Object.keys(featureUsage).reduce( + (a, b) => (featureUsage[a] > featureUsage[b] ? a : b), + "", + ); + + return { + ...customer, + firstSeen, + lastSeen, + mostUsedFeature, + userStatus, + }; + } catch (error) { + console.error("Error fetching customer details:", error); + throw error; + } +} diff --git a/apps/www/src/actions/get-customers-all.ts b/apps/www/src/actions/get-customers-all.ts new file mode 100644 index 0000000..96bcb6d --- /dev/null +++ b/apps/www/src/actions/get-customers-all.ts @@ -0,0 +1,35 @@ +import { authOptions } from "@/lib/auth"; +import { prisma } from "@/lib/db"; +import { getCurrentUser } from "@/lib/session"; + +export async function getAllCustomersForUser() { + const user = await getCurrentUser(); + + if (!user) { + throw new Error("User not authenticated"); + } + + // Fetch projects associated with the user + const projects = await prisma.project.findMany({ + where: { + userId: user.id, + }, + select: { + id: true, + }, + }); + + // Extract project IDs + const projectIds = projects.map((project) => project.id); + + // Fetch customers associated with the user's projects + const customers = await prisma.customer.findMany({ + where: { + projectId: { + in: projectIds, + }, + }, + }); + + return customers; +} diff --git a/apps/www/src/actions/get-metrics-user.ts b/apps/www/src/actions/get-metrics-user.ts new file mode 100644 index 0000000..d60ee0f --- /dev/null +++ b/apps/www/src/actions/get-metrics-user.ts @@ -0,0 +1,20 @@ +import { prisma } from "@/lib/db"; +import { getCurrentUser } from "@/lib/session"; + +export async function getMetricsForUser() { + const user = await getCurrentUser(); + + if (!user) { + throw new Error("User not authenticated"); + } + + const metrics = await prisma.metrics.findFirst({ + where: { + project: { + userId: user.id, + }, + }, + }); + + return metrics; +} diff --git a/apps/www/src/actions/get-notification-settings.ts b/apps/www/src/actions/get-notification-settings.ts new file mode 100644 index 0000000..2527627 --- /dev/null +++ b/apps/www/src/actions/get-notification-settings.ts @@ -0,0 +1,19 @@ +// actions/get-notification-settings.ts +"use server"; + +import { prisma } from "@/lib/db"; +import { getCurrentUser } from "@/lib/session"; + +export async function getNotificationSettings() { + const user = await getCurrentUser(); + + if (!user) { + throw new Error("User not authenticated"); + } + + const settings = await prisma.notificationSetting.findFirst({ + where: { userId: user.id }, + }); + + return settings; +} diff --git a/apps/www/src/actions/get-user-details.ts b/apps/www/src/actions/get-user-details.ts new file mode 100644 index 0000000..4705ebf --- /dev/null +++ b/apps/www/src/actions/get-user-details.ts @@ -0,0 +1,28 @@ +// actions/get-user-data.ts +"use server"; + +import { prisma } from "@/lib/db"; +import { getCurrentUser } from "@/lib/session"; + +export async function getUserData() { + const user = await getCurrentUser(); + if (!user) { + throw new Error("User not authenticated"); + } + + const userData = await prisma.user.findUnique({ + where: { id: user.id }, + select: { + apiKey: true, + name: true, + email: true, + // add other fields you might need + }, + }); + + if (!userData) { + throw new Error("User not found"); + } + + return userData; +} diff --git a/apps/www/src/actions/select-option.ts b/apps/www/src/actions/select-option.ts new file mode 100644 index 0000000..462f058 --- /dev/null +++ b/apps/www/src/actions/select-option.ts @@ -0,0 +1,30 @@ +// actions/select-option.js +"use server"; + +import { prisma } from "@dingify/db"; + +export async function selectOption(imageId, selectedOptionKey) { + console.log( + `Attempting to update selected option for imageId: ${imageId} with selectedOptionKey: ${selectedOptionKey}` + ); + + try { + const updateResponse = await prisma.image.update({ + where: { id: imageId }, + data: { + selectedOption: selectedOptionKey, + }, + }); + + console.log(`Update response from Prisma:`, updateResponse); + console.log(`Selected option updated successfully for image ${imageId}`); + + return { success: true }; + } catch (error) { + console.error( + `Error when calling prisma.image.update for imageId ${imageId} with selectedOptionKey ${selectedOptionKey}:`, + error + ); + return { success: false, error: "Failed to update selected option" }; + } +} diff --git a/apps/www/src/actions/send-onboarding-email.ts b/apps/www/src/actions/send-onboarding-email.ts new file mode 100644 index 0000000..9ce7e42 --- /dev/null +++ b/apps/www/src/actions/send-onboarding-email.ts @@ -0,0 +1,37 @@ +"use server"; + +// src/utils/sendOnboardingEmail.ts +import WelcomeEmail from "@/emails/welcome-email"; + +import { prisma } from "@/lib/db"; +import { resend } from "@/lib/email"; + +// import { prisma } from "@dingify/db"; + +async function sendOnboardingEmail(email: string, name: string) { + try { + const emailResult = await resend.emails.send({ + from: "Dingify ", + to: email, + subject: "Unlock the Future of Real Estate with Dingify!", + react: WelcomeEmail({ + name: name || "Valued User", + email: email, + }), + headers: { + "X-Entity-Ref-ID": new Date().getTime() + "", + }, + }); + + // Update the onboardingEmailSent flag for the user + await prisma.user.update({ + where: { email }, + data: { onboardingEmailSent: true }, + }); + } catch (error) { + console.error("Error sending onboarding email:", error); + throw new Error("Failed to send onboarding email.", error); + } +} + +export default sendOnboardingEmail; diff --git a/apps/www/src/actions/stats/get-analytics-stats.ts b/apps/www/src/actions/stats/get-analytics-stats.ts new file mode 100644 index 0000000..78b0935 --- /dev/null +++ b/apps/www/src/actions/stats/get-analytics-stats.ts @@ -0,0 +1,90 @@ +"use server"; + +import { endOfMonth, startOfMonth, subMonths } from "date-fns"; + +import { prisma } from "@/lib/db"; +import { getCurrentUser } from "@/lib/session"; + +export async function getAnalyticsStats() { + const user = await getCurrentUser(); + if (!user) { + throw new Error("User not authenticated"); + } + + // Fetch projects associated with the user + const projects = await prisma.project.findMany({ + where: { userId: user.id }, + select: { id: true }, + }); + + const projectIds = projects.map((project) => project.id); + + const channels = await prisma.channel.findMany({ + where: { projectId: { in: projectIds } }, + select: { id: true }, + }); + + const channelIds = channels.map((channel) => channel.id); + + const today = new Date(); + const startOfCurrentYear = new Date(today.getFullYear(), 0, 1); + const endOfCurrentYear = new Date(today.getFullYear(), 11, 31); + + // Fetch monthly event data for the current year + const monthlyEvents = await prisma.event.findMany({ + where: { + channelId: { in: channelIds }, + createdAt: { + gte: startOfCurrentYear, + lte: endOfCurrentYear, + }, + }, + select: { + createdAt: true, + }, + }); + + const monthlyEventsCount = monthlyEvents.reduce((acc, event) => { + const month = event.createdAt.toLocaleString("default", { month: "short" }); + if (!acc[month]) { + acc[month] = 0; + } + acc[month]++; + return acc; + }, {}); + + const formattedMonthlyEvents = Object.entries(monthlyEventsCount).map( + ([month, events]) => ({ + month, + events, + }), + ); + + // Fetch event type breakdown + const eventTypeBreakdown = await prisma.event.groupBy({ + by: ["name"], + where: { + channelId: { in: channelIds }, + }, + _count: { + name: true, + }, + orderBy: { + _count: { + name: "desc", + }, + }, + take: 10, + }); + + // Format the event type breakdown data + const formattedEventTypeBreakdown = eventTypeBreakdown.map((item) => ({ + eventType: item.name, + count: item._count.name, + })); + + return { + monthlyEvents: formattedMonthlyEvents, + eventTypeBreakdown: formattedEventTypeBreakdown, + }; +} diff --git a/apps/www/src/actions/stats/get-events-stats.ts b/apps/www/src/actions/stats/get-events-stats.ts new file mode 100644 index 0000000..884102a --- /dev/null +++ b/apps/www/src/actions/stats/get-events-stats.ts @@ -0,0 +1,133 @@ +// actions/get-event-stats.js +import { + endOfMonth, + endOfWeek, + formatISO, + startOfMonth, + startOfWeek, + subDays, + subMonths, +} from "date-fns"; + +import { prisma } from "@/lib/db"; +import { getCurrentUser } from "@/lib/session"; + +export async function getEventStats() { + const user = await getCurrentUser(); + if (!user) { + throw new Error("User not authenticated"); + } + + // Fetch projects associated with the user + const projects = await prisma.project.findMany({ + where: { + userId: user.id, + }, + select: { + id: true, + }, + }); + + // Extract project IDs + const projectIds = projects.map((project) => project.id); + + // Fetch channels for the user's projects + const channels = await prisma.channel.findMany({ + where: { + projectId: { + in: projectIds, + }, + }, + select: { + id: true, + }, + }); + + // Extract channel IDs + const channelIds = channels.map((channel) => channel.id); + + const today = new Date(); + + // Dates for the current and previous weeks + const startOfCurrentWeek = startOfWeek(today); + const endOfCurrentWeek = endOfWeek(today); + const startOfLastWeek = startOfWeek(subDays(today, 7)); + const endOfLastWeek = endOfWeek(subDays(today, 7)); + + // Fetch events for the current week + const currentWeekEvents = await prisma.event.count({ + where: { + channelId: { + in: channelIds, + }, + createdAt: { + gte: formatISO(startOfCurrentWeek), + lte: formatISO(endOfCurrentWeek), + }, + }, + }); + + // Fetch events for the previous week + const lastWeekEvents = await prisma.event.count({ + where: { + channelId: { + in: channelIds, + }, + createdAt: { + gte: formatISO(startOfLastWeek), + lte: formatISO(endOfLastWeek), + }, + }, + }); + + // Calculate the weekly percentage change + const weeklyChange = + lastWeekEvents !== 0 + ? ((currentWeekEvents - lastWeekEvents) / lastWeekEvents) * 100 + : 0; + + // Dates for the current and previous months + const startOfCurrentMonth = startOfMonth(today); + const endOfCurrentMonth = endOfMonth(today); + const startOfLastMonth = startOfMonth(subMonths(today, 1)); + const endOfLastMonth = endOfMonth(subMonths(today, 1)); + + // Fetch events for the current month + const currentMonthEvents = await prisma.event.count({ + where: { + channelId: { + in: channelIds, + }, + createdAt: { + gte: formatISO(startOfCurrentMonth), + lte: formatISO(endOfCurrentMonth), + }, + }, + }); + + // Fetch events for the previous month + const lastMonthEvents = await prisma.event.count({ + where: { + channelId: { + in: channelIds, + }, + createdAt: { + gte: formatISO(startOfLastMonth), + lte: formatISO(endOfLastMonth), + }, + }, + }); + + // Calculate the monthly percentage change + const monthlyChange = + lastMonthEvents !== 0 + ? ((currentMonthEvents - lastMonthEvents) / lastMonthEvents) * 100 + : 0; + + return { + currentWeekEvents, + weeklyChange, + currentMonthEvents, + monthlyChange, + }; +} diff --git a/apps/www/src/actions/stats/get-users-stats.ts b/apps/www/src/actions/stats/get-users-stats.ts new file mode 100644 index 0000000..2a94ee8 --- /dev/null +++ b/apps/www/src/actions/stats/get-users-stats.ts @@ -0,0 +1,63 @@ +// actions/get-user-stats.js +import { startOfDay, startOfMonth, startOfWeek } from "date-fns"; + +import { prisma } from "@/lib/db"; +import { getCurrentUser } from "@/lib/session"; + +export async function getUserStats() { + const user = await getCurrentUser(); + if (!user) { + throw new Error("User not authenticated"); + } + + const today = new Date(); + const startOfToday = startOfDay(today); + const startOfThisWeek = startOfWeek(today); + const startOfThisMonth = startOfMonth(today); + + // Fetch total unique users involved in events + const totalUsersResult = await prisma.event.groupBy({ + by: ["userId"], + }); + const totalUsers = totalUsersResult.length; + + // Fetch unique users involved in events created today + const usersTodayResult = await prisma.event.groupBy({ + by: ["userId"], + where: { + createdAt: { + gte: startOfToday, + }, + }, + }); + const usersToday = usersTodayResult.length; + + // Fetch unique users involved in events created this week + const usersThisWeekResult = await prisma.event.groupBy({ + by: ["userId"], + where: { + createdAt: { + gte: startOfThisWeek, + }, + }, + }); + const usersThisWeek = usersThisWeekResult.length; + + // Fetch unique users involved in events created this month + const usersThisMonthResult = await prisma.event.groupBy({ + by: ["userId"], + where: { + createdAt: { + gte: startOfThisMonth, + }, + }, + }); + const usersThisMonth = usersThisMonthResult.length; + + return { + totalUsers, + usersToday, + usersThisWeek, + usersThisMonth, + }; +} diff --git a/apps/www/src/actions/testwebhook.ts b/apps/www/src/actions/testwebhook.ts new file mode 100644 index 0000000..b160b33 --- /dev/null +++ b/apps/www/src/actions/testwebhook.ts @@ -0,0 +1,59 @@ +// actions/test-webhook.ts +"use server"; + +import { getCurrentUser } from "@/lib/session"; + +export async function testWebhook(data: { + name: string; + provider: string; + webhook: string; +}) { + const user = await getCurrentUser(); + const userId = user?.id; + + if (!userId) { + console.error("No user is currently logged in."); + return { success: false, error: "User not authenticated" }; + } + + try { + // Send a test message to the specified Discord webhook URL + if (data.provider.toUpperCase() === "DISCORD") { + const response = await fetch(data.webhook, { + method: "POST", + headers: { + "Content-Type": "application/json", + }, + body: JSON.stringify({ + content: `Test message from ${data.name}`, + }), + }); + + if (!response.ok) { + throw new Error("Failed to send Discord notification"); + } + } + + // Send a test message to the specified Slack webhook URL + if (data.provider.toUpperCase() === "SLACK") { + const response = await fetch(data.webhook, { + method: "POST", + headers: { + "Content-Type": "application/json", + }, + body: JSON.stringify({ + text: `Test message from ${data.name}`, + }), + }); + + if (!response.ok) { + throw new Error("Failed to send Slack notification"); + } + } + + return { success: true }; + } catch (error) { + console.error("Error testing webhook:", error); + return { success: false, error: error.message }; + } +} diff --git a/apps/www/src/actions/update-language.tsx b/apps/www/src/actions/update-language.tsx new file mode 100644 index 0000000..8000333 --- /dev/null +++ b/apps/www/src/actions/update-language.tsx @@ -0,0 +1,29 @@ +// actions/update-user-language.js +"use server"; + +import { getCurrentUser } from "@/lib/session"; + +import { prisma } from "@dingify/db"; + +export async function updateUserLanguage(language) { + const user = await getCurrentUser(); + const userId = user?.id; + + console.log( + `Request received to update language. User ID: ${userId}, Language: ${language}` + ); + + try { + const updatedUser = await prisma.user.update({ + where: { id: userId }, + data: { language }, + }); + console.log( + `Language updated successfully for user ID: ${userId}. New language: ${language}` + ); + return { success: true, user: updatedUser }; + } catch (error) { + console.error(`Error updating user language for user ID: ${userId}`, error); + return { success: false, error: error.message }; + } +} diff --git a/apps/www/src/actions/update-property-description.tsx b/apps/www/src/actions/update-property-description.tsx new file mode 100644 index 0000000..550e4f8 --- /dev/null +++ b/apps/www/src/actions/update-property-description.tsx @@ -0,0 +1,27 @@ +"use server"; + +import { prisma } from "@dingify/db"; + +export async function updatePropertyDescription(propertyId, description) { + console.log( + `Request received to update property description. Property ID: ${propertyId}` + ); + + try { + const updatedProperty = await prisma.property.update({ + where: { id: propertyId }, + data: { detailedDescription: description }, + }); + + console.log( + `Description updated successfully for property ID: ${propertyId}.` + ); + return { success: true, property: updatedProperty }; + } catch (error) { + console.error( + `Error updating property description for property ID: ${propertyId}`, + error + ); + return { success: false, error: error.message }; + } +} diff --git a/apps/www/src/actions/update-property-form.tsx b/apps/www/src/actions/update-property-form.tsx new file mode 100644 index 0000000..ab2368b --- /dev/null +++ b/apps/www/src/actions/update-property-form.tsx @@ -0,0 +1,32 @@ +"use server"; + +import { prisma } from "@dingify/db"; + +export async function updatePropertyDetails(propertyId, data) { + console.log( + `Request received to update property details. Property ID: ${propertyId}` + ); + + try { + const updatedProperty = await prisma.property.update({ + where: { id: propertyId }, + data: { + pris: data.pris, + p_rom: data.p_rom, + bra: data.bra, + // ... other fields as necessary + }, + }); + + console.log( + `Property details updated successfully for property ID: ${propertyId}.` + ); + return { success: true, property: updatedProperty }; + } catch (error) { + console.error( + `Error updating property details for property ID: ${propertyId}`, + error + ); + return { success: false, error: error.message }; + } +} diff --git a/apps/www/src/actions/update-property-status.ts b/apps/www/src/actions/update-property-status.ts new file mode 100644 index 0000000..1d15972 --- /dev/null +++ b/apps/www/src/actions/update-property-status.ts @@ -0,0 +1,33 @@ +"use server"; + +import { prisma } from "@dingify/db"; + +export async function updatePropertyStatus(propertyId, newStatus) { + if (!propertyId || !newStatus) { + console.error("Property ID and new status are required."); + return { success: false, error: "Missing parameters." }; + } + + try { + const updatedProperty = await prisma.property.update({ + where: { id: propertyId }, + data: { status: newStatus }, + }); + + if (updatedProperty) { + console.log( + `Status updated for property ID: ${propertyId} to ${newStatus}` + ); + return { success: true, property: updatedProperty }; + } else { + console.error(`No property found with ID: ${propertyId}`); + return { success: false, error: "Property not found." }; + } + } catch (error) { + console.error( + `Error updating status for property ID: ${propertyId}`, + error + ); + return { success: false, error: error.message }; + } +} diff --git a/apps/www/src/actions/update-user-name.ts b/apps/www/src/actions/update-user-name.ts new file mode 100644 index 0000000..2ad0325 --- /dev/null +++ b/apps/www/src/actions/update-user-name.ts @@ -0,0 +1,40 @@ +"use server"; + +import { revalidatePath } from "next/cache"; +import { getServerSession } from "next-auth"; + +import { authOptions } from "@/lib/auth"; +import { prisma } from "@/lib/db"; +import { userNameSchema } from "@/lib/validations/user"; + +export interface FormData { + name: string; +} + +export async function updateUserName(userId: string, data: FormData) { + try { + const session = await getServerSession(authOptions); + + if (!session?.user || session.user.id !== userId) { + throw new Error("Unauthorized"); + } + + const { name } = userNameSchema.parse(data); + + // Update the user name. + await prisma.user.update({ + where: { + id: userId, + }, + data: { + name: name, + }, + }); + + revalidatePath("/dashboard/settings"); + return { status: "success" }; + } catch (error) { + console.log(error); + return { status: "error" }; + } +} diff --git a/apps/www/src/actions/upload-images.ts b/apps/www/src/actions/upload-images.ts new file mode 100644 index 0000000..b4277d8 --- /dev/null +++ b/apps/www/src/actions/upload-images.ts @@ -0,0 +1,49 @@ +"use server"; + +import { authOptions } from "@/lib/auth"; +import { getCurrentUser } from "@/lib/session"; +import { getServerSession } from "next-auth"; + +import { prisma } from "@dingify/db"; + +import { generateOptions } from "./generate-options"; + +export async function uploadImages(propertyId, imageUrls) { + const session = await getServerSession(authOptions); + const user = await prisma.user.findUnique({ + where: { id: session?.user.id }, + }); + console.log(user); + + const userLanguage = user?.language || "english"; + + try { + const imageRecords = await prisma.$transaction( + imageUrls.map((imageUrl) => { + return prisma.image.create({ + data: { + url: imageUrl, + propertyId, + option1: "Generating...", // Placeholder text + option2: "Generating...", // Placeholder text + option3: "Generating...", // Placeholder text + }, + }); + }) + ); + + // Generate options for all images and wait for them to complete + const generationPromises = imageRecords.map((imageRecord) => + generateOptions(imageRecord.id, imageRecord.url, userLanguage) + ); + + // Wait for all generation promises to resolve + await Promise.all(generationPromises); + + // After all options are generated, then return success + return { success: true, images: imageRecords }; + } catch (error) { + console.error("Error uploading images:", error); + return { success: false, error: "Error uploading images" }; + } +} diff --git a/apps/www/src/app/(auth)/layout.tsx b/apps/www/src/app/(auth)/layout.tsx new file mode 100644 index 0000000..a8e6032 --- /dev/null +++ b/apps/www/src/app/(auth)/layout.tsx @@ -0,0 +1,7 @@ +interface AuthLayoutProps { + children: React.ReactNode; +} + +export default function AuthLayout({ children }: AuthLayoutProps) { + return
{children}
; +} diff --git a/apps/www/src/app/(auth)/login/page.tsx b/apps/www/src/app/(auth)/login/page.tsx new file mode 100644 index 0000000..acc5523 --- /dev/null +++ b/apps/www/src/app/(auth)/login/page.tsx @@ -0,0 +1,54 @@ +import type { Metadata } from "next"; +import { Suspense } from "react"; +import Link from "next/link"; +import { UserAuthForm } from "@/components/forms/user-auth-form"; +import { Icons } from "@/components/shared/icons"; +import { cn } from "@/lib/utils"; + +import { buttonVariants } from "@dingify/ui/components/button"; + +export const metadata: Metadata = { + title: "Login", + description: "Login to your account", +}; + +export default function LoginPage() { + return ( +
+ + <> + + Back + + +
+
+ +

+ Welcome back +

+

+ Enter your email to sign in to your account +

+
+ + + +

+ + Don't have an account? Sign Up + +

+
+
+ ); +} diff --git a/apps/www/src/app/(auth)/register/page.tsx b/apps/www/src/app/(auth)/register/page.tsx new file mode 100644 index 0000000..e34323b --- /dev/null +++ b/apps/www/src/app/(auth)/register/page.tsx @@ -0,0 +1,62 @@ +import { Suspense } from "react"; +import Link from "next/link"; +import { UserAuthForm } from "@/components/forms/user-auth-form"; +import { Icons } from "@/components/shared/icons"; +import { cn } from "@/lib/utils"; + +import { buttonVariants } from "@dingify/ui/components/button"; + +export const metadata = { + title: "Create an account", + description: "Create an account to get started.", +}; + +export default function RegisterPage() { + return ( +
+ + Login + +
+
+
+
+ +

+ Create an account +

+

+ Enter your email below to create your account +

+
+ + + +

+ By clicking continue, you agree to our{" "} + + Terms of Service + {" "} + and{" "} + + Privacy Policy + + . +

+
+
+
+ ); +} diff --git a/apps/www/src/app/(dashboard)/dashboard/[id]/page.tsx b/apps/www/src/app/(dashboard)/dashboard/[id]/page.tsx new file mode 100644 index 0000000..2c7cbc1 --- /dev/null +++ b/apps/www/src/app/(dashboard)/dashboard/[id]/page.tsx @@ -0,0 +1,57 @@ +import { getChannelDetails } from "@/actions/get-channel-details"; + +import { DashboardHeader } from "@/components/dashboard/header"; +import { DashboardShell } from "@/components/dashboard/shell"; +import NoPhotoPlaceholder from "@/components/properties/NoPhotoPlaceholder copy"; + +export default async function ChannelPage({ + params, +}: { + params: { id: string }; +}) { + const channelId = params.id; + + if (!channelId) { + return ( + + + + ); + } + + try { + const channelDetails = await getChannelDetails(channelId); + + if (!channelDetails) { + return ( + + + + ); + } + + return ( + + +
+ +
+
+ ); + } catch (error) { + return ( + + + + ); + } +} diff --git a/apps/www/src/app/(dashboard)/dashboard/analytics/page.tsx b/apps/www/src/app/(dashboard)/dashboard/analytics/page.tsx new file mode 100644 index 0000000..f3589ed --- /dev/null +++ b/apps/www/src/app/(dashboard)/dashboard/analytics/page.tsx @@ -0,0 +1,60 @@ +import { redirect } from "next/navigation"; +import { getAnalyticsStats } from "@/actions/stats/get-analytics-stats"; +import { getUserStats } from "@/actions/stats/get-users-stats"; + +import { authOptions } from "@/lib/auth"; +import { getCurrentUser } from "@/lib/session"; +import CardSection from "@/components/analytics/CardSection"; +import EventsTrendOverTimeChart from "@/components/dashboard/charts/EventsTrendOverTime"; +import UserGrowthTrend from "@/components/dashboard/charts/UserGrowthChart"; +import { DashboardHeader } from "@/components/dashboard/header"; +import { DashboardShell } from "@/components/dashboard/shell"; +import { EmptyPlaceholder } from "@/components/shared/empty-placeholder"; + +export const metadata = { + title: "Dingify Analytics - Your Alerts Overview", + description: + "Monitor and analyze all your critical events in real-time. Access key metrics, track important journeys, and make data-driven decisions to optimize your business performance on the Dingify Dashboard.", +}; + +export default async function DashboardPage() { + const user = await getCurrentUser(); + + if (!user) { + redirect(authOptions.pages?.signIn || "/login"); + } + + //TODO Make these calls dynamic + // const { monthlyEvents, eventTypeBreakdown } = await getAnalyticsStats(); + // const { totalUsers, usersToday, usersThisWeek, usersThisMonth } = + // await getUserStats(); + // console.log( + // "monthlyEvents", + // totalUsers, + // usersToday, + // usersThisWeek, + // usersThisMonth, + // ); + + return ( + + +
+ + + +
+
+ ); +} diff --git a/apps/www/src/app/(dashboard)/dashboard/billing/loading.tsx b/apps/www/src/app/(dashboard)/dashboard/billing/loading.tsx new file mode 100644 index 0000000..fe447d4 --- /dev/null +++ b/apps/www/src/app/(dashboard)/dashboard/billing/loading.tsx @@ -0,0 +1,17 @@ +import { DashboardHeader } from "@/components/dashboard/header"; +import { DashboardShell } from "@/components/dashboard/shell"; +import { CardSkeleton } from "@/components/shared/card-skeleton"; + +export default function DashboardBillingLoading() { + return ( + + +
+ +
+
+ ); +} diff --git a/apps/www/src/app/(dashboard)/dashboard/billing/page.tsx b/apps/www/src/app/(dashboard)/dashboard/billing/page.tsx new file mode 100644 index 0000000..852aa16 --- /dev/null +++ b/apps/www/src/app/(dashboard)/dashboard/billing/page.tsx @@ -0,0 +1,61 @@ +import { redirect } from "next/navigation"; +import { BillingInfo } from "@/components/billing-info"; +import { LanugageButton } from "@/components/buttons/LanguageButton"; +import { DashboardHeader } from "@/components/dashboard/header"; +import { DashboardShell } from "@/components/dashboard/shell"; +import { Icons } from "@/components/shared/icons"; +import { authOptions } from "@/lib/auth"; +import { getCurrentUser } from "@/lib/session"; +import { getUserSubscriptionPlan } from "@/lib/subscription"; + +import { + Alert, + AlertDescription, + AlertTitle, +} from "@dingify/ui/components/alert"; + +export const metadata = { + title: "Dingity Billing - Subscription Management", + description: + "Access and manage your billing information, view subscription plans, and update payment methods on Dingity's Billing page.", +}; + +export default async function BillingPage() { + const user = await getCurrentUser(); + + if (!user) { + redirect(authOptions.pages?.signIn || "/login"); + } + + const subscriptionPlan = await getUserSubscriptionPlan(user.id); + + return ( + + +
+ {/* + + This is a demo app. + + Propwrite app is a demo app using a Stripe test environment. You can + find a list of test card numbers on the{" "} + + Stripe docs + + . + + */} + +
+ {/* */} +
+ ); +} diff --git a/apps/www/src/app/(dashboard)/dashboard/channels/[id]/page.tsx b/apps/www/src/app/(dashboard)/dashboard/channels/[id]/page.tsx new file mode 100644 index 0000000..be8eb27 --- /dev/null +++ b/apps/www/src/app/(dashboard)/dashboard/channels/[id]/page.tsx @@ -0,0 +1,73 @@ +import { getChannelDetails } from "@/actions/get-channel-details"; + +import { ChannelCard } from "@/components/channels/ChannelCard"; +import { DashboardHeader } from "@/components/dashboard/header"; +import { DashboardShell } from "@/components/dashboard/shell"; +import NoPhotoPlaceholder from "@/components/properties/NoPhotoPlaceholder copy"; + +export default async function ChannelPage({ + params, +}: { + params: { id: string }; +}) { + const channelId = params.id; + + console.log("Channel ID from params:", channelId); // Debugging log + + if (!channelId) { + return ( + + + + ); + } + + try { + const channelDetails = await getChannelDetails(channelId); + + if (!channelDetails) { + return ( + + + + + ); + } + + if (channelDetails.events.length === 0) { + return ( + + + + + ); + } + + return ( + + +
+ +
+
+ ); + } catch (error) { + return ( + + + + ); + } +} diff --git a/apps/www/src/app/(dashboard)/dashboard/dev/page.tsx b/apps/www/src/app/(dashboard)/dashboard/dev/page.tsx new file mode 100644 index 0000000..72258b4 --- /dev/null +++ b/apps/www/src/app/(dashboard)/dashboard/dev/page.tsx @@ -0,0 +1,89 @@ +"use client"; + +import React, { useState } from "react"; +import { Loader2 as Spinner } from "lucide-react"; + +export default function PricingPage() { + const [imageUrl, setImageUrl] = useState(""); + const [isLoading, setIsLoading] = useState(false); + const [results, setResults] = useState([]); + const [language, setLanguage] = useState("english"); + + const handleSubmit = async (event) => { + event.preventDefault(); + setIsLoading(true); + + const response = await fetch("/api/ai/analyzeImage", { + method: "POST", + headers: { "Content-Type": "application/json" }, + body: JSON.stringify({ imageUrl, language }), + }); + + const responseData = await response.json(); + setIsLoading(false); + + if (responseData.choices && responseData.choices.length > 0) { + const options = responseData.choices[0].message.content + .split("\n") + .filter((line) => line.trim() !== "") + .map((line) => line.replace(/"/g, "")); + setResults(options); + } else { + setResults(["No analysis result found."]); + } + }; + + return ( +
+
+ {imageUrl && ( + Preview + )} + setImageUrl(e.target.value)} + placeholder="Paste image URL here" + className="w-full rounded-md border border-gray-300 px-4 py-2" + /> + + + + {results.map((result, index) => ( +
+

Option {index + 1}:

+

{result}

+
+ ))} +
+
+ ); +} diff --git a/apps/www/src/app/(dashboard)/dashboard/layout.tsx b/apps/www/src/app/(dashboard)/dashboard/layout.tsx new file mode 100644 index 0000000..d9059ad --- /dev/null +++ b/apps/www/src/app/(dashboard)/dashboard/layout.tsx @@ -0,0 +1,48 @@ +import { notFound } from "next/navigation"; +import { getUserChannels } from "@/actions/get-channels"; + +import { dashboardConfig } from "@/config/dashboard"; +import { getCurrentUser } from "@/lib/session"; +import { DashboardNav } from "@/components/layout/nav"; +import { NavBar } from "@/components/layout/navbar"; +import { SiteFooter } from "@/components/layout/site-footer"; + +interface DashboardLayoutProps { + children?: React.ReactNode; +} + +export default async function DashboardLayout({ + children, +}: DashboardLayoutProps) { + const user = await getCurrentUser(); + + if (!user) { + return notFound(); + } + + const userChannels = await getUserChannels(); + + const sidebarNavItems = [ + ...dashboardConfig.sidebarNav, + ...userChannels.map((channel) => ({ + title: channel.name, + href: `/dashboard/channels/${channel.id}`, // Use ID instead of name + })), + ]; + + return ( +
+ + +
+ +
+ {children} +
+
+ +
+ ); +} diff --git a/apps/www/src/app/(dashboard)/dashboard/loading.tsx b/apps/www/src/app/(dashboard)/dashboard/loading.tsx new file mode 100644 index 0000000..ea4980b --- /dev/null +++ b/apps/www/src/app/(dashboard)/dashboard/loading.tsx @@ -0,0 +1,21 @@ +import { Button } from "@dingify/ui/components/button"; + +import { DashboardHeader } from "@/components/dashboard/header"; +import { DashboardShell } from "@/components/dashboard/shell"; +import { CardSkeleton } from "@/components/shared/card-skeleton"; + +export default function DashboardLoading() { + return ( + + + + +
+ + + + +
+
+ ); +} diff --git a/apps/www/src/app/(dashboard)/dashboard/notifications/loading.tsx b/apps/www/src/app/(dashboard)/dashboard/notifications/loading.tsx new file mode 100644 index 0000000..bbf8d7b --- /dev/null +++ b/apps/www/src/app/(dashboard)/dashboard/notifications/loading.tsx @@ -0,0 +1,17 @@ +import { DashboardHeader } from "@/components/dashboard/header"; +import { DashboardShell } from "@/components/dashboard/shell"; +import { CardSkeleton } from "@/components/shared/card-skeleton"; + +export default function DashboardSettingsLoading() { + return ( + + +
+ +
+
+ ); +} diff --git a/apps/www/src/app/(dashboard)/dashboard/notifications/page.tsx b/apps/www/src/app/(dashboard)/dashboard/notifications/page.tsx new file mode 100644 index 0000000..35032f7 --- /dev/null +++ b/apps/www/src/app/(dashboard)/dashboard/notifications/page.tsx @@ -0,0 +1,47 @@ +import { redirect } from "next/navigation"; +import { getMetricsForUser } from "@/actions/get-metrics-user"; +import { getNotificationSettings } from "@/actions/get-notification-settings"; + +import { + Card, + CardContent, + CardDescription, + CardFooter, + CardHeader, + CardTitle, +} from "@dingify/ui/components/card"; + +import { authOptions } from "@/lib/auth"; +import { getCurrentUser } from "@/lib/session"; +import { DashboardHeader } from "@/components/dashboard/header"; +import { DashboardShell } from "@/components/dashboard/shell"; +import { LanguageForm2 } from "@/components/forms/language-form2"; +import { UserNameForm } from "@/components/forms/user-name-form"; +import { NotificationAlert } from "@/components/notifications/NotificationAlert"; + +export const metadata = { + title: "Dingify Notifications - Customize Your Alerts", + description: + "Adjust your Dingify notification settings for a personalized real-time monitoring experience. Manage alert preferences, notification channels, and more.", +}; + +export default async function SettingsPage() { + const user = await getCurrentUser(); + + if (!user) { + redirect(authOptions.pages?.signIn || "/login"); + } + // How to get the metrics for the user + const metrics = await getMetricsForUser(); + const settings = await getNotificationSettings(); + + return ( + + + + + ); +} diff --git a/apps/www/src/app/(dashboard)/dashboard/page.tsx b/apps/www/src/app/(dashboard)/dashboard/page.tsx new file mode 100644 index 0000000..6e4d558 --- /dev/null +++ b/apps/www/src/app/(dashboard)/dashboard/page.tsx @@ -0,0 +1,144 @@ +import { redirect } from "next/navigation"; +import { getUserCredits } from "@/actions/get-credits"; +import { getEventStats } from "@/actions/stats/get-events-stats"; + +import { authOptions } from "@/lib/auth"; +import { prisma } from "@/lib/db"; +import { getCurrentUser } from "@/lib/session"; +import { AddApiKeyButton } from "@/components/buttons/AddApiKeyButton"; +import { AddChannelButton } from "@/components/buttons/AddChannelButton"; +import { AddProjectButton } from "@/components/buttons/AddProjectButton"; +import { AddPropertyButton } from "@/components/buttons/AddPropertyButton"; +import EventsDashboard from "@/components/dashboard/EventsDashboard"; +import { DashboardHeader } from "@/components/dashboard/header"; +import { DashboardShell } from "@/components/dashboard/shell"; +import { EmptyPlaceholder } from "@/components/shared/empty-placeholder"; + +export const metadata = { + title: "Dingify Dashboard - Your Alerts Overview", + description: + "Monitor and analyze all your critical events in real-time. Access key metrics, track important journeys, and make data-driven decisions to optimize your business performance on the Dingify Dashboard.", +}; + +export default async function DashboardPage() { + const user = await getCurrentUser(); + const userCredits = await getUserCredits(); + const eventStats = await getEventStats(); + + if (!user) { + redirect(authOptions.pages?.signIn || "/login"); + } + + // Fetch projects associated with the user + const projects = await prisma.project.findMany({ + where: { + userId: user.id, + }, + select: { + id: true, + }, + }); + + // Extract project IDs + const projectIds = projects.map((project) => project.id); + + // Fetch customers associated with the user's projects + const customers = await prisma.customer.findMany({ + where: { + projectId: { + in: projectIds, + }, + }, + }); + console.log(customers); + + // Fetch channels for the user's projects + const channels = await prisma.channel.findMany({ + where: { + projectId: { + in: projectIds, + }, + }, + select: { + id: true, + name: true, + createdAt: true, + }, + orderBy: { + createdAt: "desc", + }, + }); + + // Extract channel IDs + const channelIds = channels.map((channel) => channel.id); + + // Fetch events for the user's channels with project and channel names + const events = await prisma.event.findMany({ + where: { + channelId: { + in: channelIds, + }, + }, + select: { + id: true, + name: true, + channelId: true, + userId: true, + icon: true, + tags: true, + notify: true, + createdAt: true, + customerId: true, + channel: { + select: { + name: true, + project: { + select: { + name: true, + }, + }, + }, + }, + }, + orderBy: { + createdAt: "desc", + }, + }); + + // Ensure userCredits.credits is defined, default to 0 if undefined + const availableCredits = userCredits.credits ?? 0; + + return ( + + + {userCredits.success && availableCredits > 0 ? ( + + ) : ( + // + // + + )} + +
+ {channels.length === 0 ? ( + // Render EmptyPlaceholder if there are no channels + + + + There are no channels + + + You need to generate an API key first + + + + ) : ( + // Render EventsTable if there are Events + + )} +
+
+ ); +} diff --git a/apps/www/src/app/(dashboard)/dashboard/settings/loading.tsx b/apps/www/src/app/(dashboard)/dashboard/settings/loading.tsx new file mode 100644 index 0000000..6f431b2 --- /dev/null +++ b/apps/www/src/app/(dashboard)/dashboard/settings/loading.tsx @@ -0,0 +1,17 @@ +import { DashboardHeader } from "@/components/dashboard/header"; +import { DashboardShell } from "@/components/dashboard/shell"; +import { CardSkeleton } from "@/components/shared/card-skeleton"; + +export default function DashboardSettingsLoading() { + return ( + + +
+ +
+
+ ); +} diff --git a/apps/www/src/app/(dashboard)/dashboard/settings/page.tsx b/apps/www/src/app/(dashboard)/dashboard/settings/page.tsx new file mode 100644 index 0000000..2c7eb85 --- /dev/null +++ b/apps/www/src/app/(dashboard)/dashboard/settings/page.tsx @@ -0,0 +1,153 @@ +import { redirect } from "next/navigation"; +import { getMetricsForUser } from "@/actions/get-metrics-user"; + +import { + Card, + CardContent, + CardDescription, + CardFooter, + CardHeader, + CardTitle, +} from "@dingify/ui/components/card"; + +import { authOptions } from "@/lib/auth"; +import { getCurrentUser } from "@/lib/session"; +import { DashboardHeader } from "@/components/dashboard/header"; +import { DashboardShell } from "@/components/dashboard/shell"; +import { LanguageForm2 } from "@/components/forms/language-form2"; +import { UserNameForm } from "@/components/forms/user-name-form"; + +export const metadata = { + title: "Dingify Settings - Customize Your Experience", + description: + "Adjust your Dingify account settings for a personalized real-time monitoring experience. Manage language preferences, account details, and more.", +}; + +export default async function SettingsPage() { + const user = await getCurrentUser(); + + if (!user) { + redirect(authOptions.pages?.signIn || "/login"); + } + + const metrics = await getMetricsForUser(); + + const formatNumber = (number) => { + return new Intl.NumberFormat("en-US").format(number); + }; + + return ( + + + +
+ + + Logs + + {metrics + ? `${formatNumber(metrics.logsUsed)} / ${formatNumber(metrics.logsLimit)}` + : "N/A"} + + + + + Total logs for this month + + + + + Seats + + {metrics ? `${formatNumber(metrics.seatsUsed)} / 1` : "N/A"} + + + + + Seats used in your plan + + + + + Projects + + {metrics ? `${formatNumber(metrics.projectsUsed)} / โˆž` : "N/A"} + + + + + Total projects in your account + + +
+
+ +
+
+ ); +} + +function FolderIcon(props) { + return ( + + + + ); +} + +function LayersIcon(props) { + return ( + + + + + + ); +} + +function UsersIcon(props) { + return ( + + + + + + + ); +} diff --git a/apps/www/src/app/(dashboard)/dashboard/users/[id]/page.tsx b/apps/www/src/app/(dashboard)/dashboard/users/[id]/page.tsx new file mode 100644 index 0000000..b9d73d4 --- /dev/null +++ b/apps/www/src/app/(dashboard)/dashboard/users/[id]/page.tsx @@ -0,0 +1,69 @@ +import { getCustomerDetails } from "@/actions/get-customer-details"; + +import { DashboardHeader } from "@/components/dashboard/header"; +import { DashboardShell } from "@/components/dashboard/shell"; +import NoPhotoPlaceholder from "@/components/properties/NoPhotoPlaceholder copy"; +import UserCard from "@/components/users/UserCard"; + +export default async function UserPage({ params }: { params: { id: string } }) { + const customerId = params.id; + + console.log("Customer ID from params:", customerId); // Debugging log + + if (!customerId) { + return ( + + + + ); + } + + try { + const customerDetails = await getCustomerDetails(customerId); + + if (!customerDetails) { + return ( + + + + + ); + } + + if (customerDetails.events.length === 0) { + return ( + + + + + ); + } + + return ( + + +
+ +
+
+ ); + } catch (error) { + return ( + + + + ); + } +} diff --git a/apps/www/src/app/(dashboard)/dashboard/users/page.tsx b/apps/www/src/app/(dashboard)/dashboard/users/page.tsx new file mode 100644 index 0000000..e5e92a9 --- /dev/null +++ b/apps/www/src/app/(dashboard)/dashboard/users/page.tsx @@ -0,0 +1,25 @@ +import { getChannelDetails } from "@/actions/get-channel-details"; +import { getAllCustomersForUser } from "@/actions/get-customers-all"; + +import { ChannelCard } from "@/components/channels/ChannelCard"; +import { DashboardHeader } from "@/components/dashboard/header"; +import { DashboardShell } from "@/components/dashboard/shell"; +import NoPhotoPlaceholder from "@/components/properties/NoPhotoPlaceholder copy"; +import { AllUsersCards } from "@/components/users/AllUsersCard"; + +export default async function UsersPage({ + params, +}: { + params: { id: string }; +}) { + const customers = await getAllCustomersForUser(); + + return ( + + +
+ +
+
+ ); +} diff --git a/apps/www/src/app/(docs)/docs/[[...slug]]/page.tsx b/apps/www/src/app/(docs)/docs/[[...slug]]/page.tsx new file mode 100644 index 0000000..ac9d5e4 --- /dev/null +++ b/apps/www/src/app/(docs)/docs/[[...slug]]/page.tsx @@ -0,0 +1,106 @@ +import { notFound } from "next/navigation"; +import { Mdx } from "@/components/content/mdx-components"; +import { DocsPageHeader } from "@/components/docs/page-header"; +import { DocsPager } from "@/components/docs/pager"; +import { DashboardTableOfContents } from "@/components/shared/toc"; +import { getTableOfContents } from "@/lib/toc"; +import { allDocs } from "contentlayer/generated"; + +import "@/styles/mdx.css"; + +import type { Metadata } from "next"; +import { env } from "@/env"; +import { absoluteUrl } from "@/lib/utils"; + +interface DocPageProps { + params: { + slug: string[]; + }; +} + +async function getDocFromParams(params) { + const slug = params.slug?.join("/") || ""; + const doc = allDocs.find((doc) => doc.slugAsParams === slug); + + if (!doc) { + null; + } + + return doc; +} + +export async function generateMetadata({ + params, +}: DocPageProps): Promise { + const doc = await getDocFromParams(params); + + if (!doc) { + return {}; + } + + const url = env.NEXT_PUBLIC_APP_URL; + + const ogUrl = new URL(`${url}/api/og`); + ogUrl.searchParams.set("heading", doc.description ?? doc.title); + ogUrl.searchParams.set("type", "Documentation"); + ogUrl.searchParams.set("mode", "dark"); + + return { + title: doc.title, + description: doc.description, + openGraph: { + title: doc.title, + description: doc.description, + type: "article", + url: absoluteUrl(doc.slug), + images: [ + { + url: ogUrl.toString(), + width: 1200, + height: 630, + alt: doc.title, + }, + ], + }, + twitter: { + card: "summary_large_image", + title: doc.title, + description: doc.description, + images: [ogUrl.toString()], + }, + }; +} + +export async function generateStaticParams(): Promise< + DocPageProps["params"][] +> { + return allDocs.map((doc) => ({ + slug: doc.slugAsParams.split("/"), + })); +} + +export default async function DocPage({ params }: DocPageProps) { + const doc = await getDocFromParams(params); + + if (!doc) { + notFound(); + } + + const toc = await getTableOfContents(doc.body.raw); + + return ( +
+
+ + +
+ +
+
+
+ +
+
+
+ ); +} diff --git a/apps/www/src/app/(docs)/docs/layout.tsx b/apps/www/src/app/(docs)/docs/layout.tsx new file mode 100644 index 0000000..ed68c28 --- /dev/null +++ b/apps/www/src/app/(docs)/docs/layout.tsx @@ -0,0 +1,17 @@ +import { DocsSidebarNav } from "@/components/docs/sidebar-nav"; +import { docsConfig } from "@/config/docs"; + +interface DocsLayoutProps { + children: React.ReactNode; +} + +export default function DocsLayout({ children }: DocsLayoutProps) { + return ( +
+ + {children} +
+ ); +} diff --git a/apps/www/src/app/(docs)/guides/[...slug]/page.tsx b/apps/www/src/app/(docs)/guides/[...slug]/page.tsx new file mode 100644 index 0000000..2b3d1bf --- /dev/null +++ b/apps/www/src/app/(docs)/guides/[...slug]/page.tsx @@ -0,0 +1,117 @@ +import Link from "next/link"; +import { notFound } from "next/navigation"; +import { Mdx } from "@/components/content/mdx-components"; +import { DocsPageHeader } from "@/components/docs/page-header"; +import { Icons } from "@/components/shared/icons"; +import { DashboardTableOfContents } from "@/components/shared/toc"; +import { getTableOfContents } from "@/lib/toc"; +import { allGuides } from "contentlayer/generated"; + +import "@/styles/mdx.css"; + +import type { Metadata } from "next"; +import { env } from "@/env"; +import { absoluteUrl, cn } from "@/lib/utils"; + +import { buttonVariants } from "@dingify/ui/components/button"; + +interface GuidePageProps { + params: { + slug: string[]; + }; +} + +async function getGuideFromParams(params) { + const slug = params?.slug?.join("/"); + const guide = allGuides.find((guide) => guide.slugAsParams === slug); + + if (!guide) { + null; + } + + return guide; +} + +export async function generateMetadata({ + params, +}: GuidePageProps): Promise { + const guide = await getGuideFromParams(params); + + if (!guide) { + return {}; + } + + const url = env.NEXT_PUBLIC_APP_URL; + + const ogUrl = new URL(`${url}/api/og`); + ogUrl.searchParams.set("heading", guide.title); + ogUrl.searchParams.set("type", "Guide"); + ogUrl.searchParams.set("mode", "dark"); + + return { + title: guide.title, + description: guide.description, + openGraph: { + title: guide.title, + description: guide.description, + type: "article", + url: absoluteUrl(guide.slug), + images: [ + { + url: ogUrl.toString(), + width: 1200, + height: 630, + alt: guide.title, + }, + ], + }, + twitter: { + card: "summary_large_image", + title: guide.title, + description: guide.description, + images: [ogUrl.toString()], + }, + }; +} + +export async function generateStaticParams(): Promise< + GuidePageProps["params"][] +> { + return allGuides.map((guide) => ({ + slug: guide.slugAsParams.split("/"), + })); +} + +export default async function GuidePage({ params }: GuidePageProps) { + const guide = await getGuideFromParams(params); + + if (!guide) { + notFound(); + } + + const toc = await getTableOfContents(guide.body.raw); + + return ( +
+
+ + +
+
+ + + See all guides + +
+
+
+
+ +
+
+
+ ); +} diff --git a/apps/www/src/app/(docs)/guides/layout.tsx b/apps/www/src/app/(docs)/guides/layout.tsx new file mode 100644 index 0000000..190ec4e --- /dev/null +++ b/apps/www/src/app/(docs)/guides/layout.tsx @@ -0,0 +1,7 @@ +interface GuidesLayoutProps { + children: React.ReactNode; +} + +export default function GuidesLayout({ children }: GuidesLayoutProps) { + return
{children}
; +} diff --git a/apps/www/src/app/(docs)/guides/page.tsx b/apps/www/src/app/(docs)/guides/page.tsx new file mode 100644 index 0000000..0c6a3d1 --- /dev/null +++ b/apps/www/src/app/(docs)/guides/page.tsx @@ -0,0 +1,64 @@ +import Link from "next/link"; +import { DocsPageHeader } from "@/components/docs/page-header"; +import { formatDate } from "@/lib/utils"; +import { allGuides } from "contentlayer/generated"; +import { compareDesc } from "date-fns"; + +export const metadata = { + title: "Guides", + description: + "This section includes end-to-end guides for developing Next.js 13 apps.", +}; + +export default function GuidesPage() { + const guides = allGuides + .filter((guide) => guide.published) + .sort((a, b) => { + return compareDesc(new Date(a.date), new Date(b.date)); + }); + + return ( +
+ + {guides.length ? ( +
+ {guides.map((guide) => ( +
+ {guide.featured && ( + + Featured + + )} +
+
+

+ {guide.title} +

+ {guide.description && ( +

{guide.description}

+ )} +
+ {guide.date && ( +

+ {formatDate(guide.date)} +

+ )} +
+ + View + +
+ ))} +
+ ) : ( +

No guides published.

+ )} +
+ ); +} diff --git a/apps/www/src/app/(docs)/layout.tsx b/apps/www/src/app/(docs)/layout.tsx new file mode 100644 index 0000000..04ac128 --- /dev/null +++ b/apps/www/src/app/(docs)/layout.tsx @@ -0,0 +1,48 @@ +import Link from "next/link"; +import { DocsSearch } from "@/components/docs/search"; +import { DocsSidebarNav } from "@/components/docs/sidebar-nav"; +import { NavBar } from "@/components/layout/navbar"; +import { SiteFooter } from "@/components/layout/site-footer"; +import { Icons } from "@/components/shared/icons"; +import { docsConfig } from "@/config/docs"; +import { siteConfig } from "@/config/site"; +import { getCurrentUser } from "@/lib/session"; + +interface DocsLayoutProps { + children: React.ReactNode; +} + +const rightHeader = () => ( +
+
+ +
+
+ +
+ +
+); + +export default async function DocsLayout({ children }: DocsLayoutProps) { + const user = await getCurrentUser(); + + return ( +
+ + + +
{children}
+ +
+ ); +} diff --git a/apps/www/src/app/(marketing)/[...slug]/page.tsx b/apps/www/src/app/(marketing)/[...slug]/page.tsx new file mode 100644 index 0000000..809d1d7 --- /dev/null +++ b/apps/www/src/app/(marketing)/[...slug]/page.tsx @@ -0,0 +1,98 @@ +import { notFound } from "next/navigation"; +import { Mdx } from "@/components/content/mdx-components"; +import { allPages } from "contentlayer/generated"; + +import "@/styles/mdx.css"; + +import type { Metadata } from "next"; +import { siteConfig } from "@/config/site"; +import { env } from "@/env"; +import { absoluteUrl } from "@/lib/utils"; + +interface PageProps { + params: { + slug: string[]; + }; +} + +async function getPageFromParams(params) { + const slug = params?.slug?.join("/"); + const page = allPages.find((page) => page.slugAsParams === slug); + + if (!page) { + null; + } + + return page; +} + +export async function generateMetadata({ + params, +}: PageProps): Promise { + const page = await getPageFromParams(params); + + if (!page) { + return {}; + } + + const url = env.NEXT_PUBLIC_APP_URL; + + const ogUrl = new URL(`${url}/api/og`); + ogUrl.searchParams.set("heading", page.title); + ogUrl.searchParams.set("type", siteConfig.name); + ogUrl.searchParams.set("mode", "light"); + + return { + title: page.title, + description: page.description, + openGraph: { + title: page.title, + description: page.description, + type: "article", + url: absoluteUrl(page.slug), + images: [ + { + url: ogUrl.toString(), + width: 1200, + height: 630, + alt: page.title, + }, + ], + }, + twitter: { + card: "summary_large_image", + title: page.title, + description: page.description, + images: [ogUrl.toString()], + }, + }; +} + +export async function generateStaticParams(): Promise { + return allPages.map((page) => ({ + slug: page.slugAsParams.split("/"), + })); +} + +export default async function PagePage({ params }: PageProps) { + const page = await getPageFromParams(params); + + if (!page) { + notFound(); + } + + return ( +
+
+

+ {page.title} +

+ {page.description && ( +

{page.description}

+ )} +
+
+ +
+ ); +} diff --git a/apps/www/src/app/(marketing)/blog/[...slug]/page.tsx b/apps/www/src/app/(marketing)/blog/[...slug]/page.tsx new file mode 100644 index 0000000..41c5982 --- /dev/null +++ b/apps/www/src/app/(marketing)/blog/[...slug]/page.tsx @@ -0,0 +1,170 @@ +import { notFound } from "next/navigation"; +import { Mdx } from "@/components/content/mdx-components"; +import { allAuthors, allPosts } from "contentlayer/generated"; + +import "@/styles/mdx.css"; + +import type { Metadata } from "next"; +import Image from "next/image"; +import Link from "next/link"; +import { Icons } from "@/components/shared/icons"; +import { env } from "@/env"; +import { absoluteUrl, cn, formatDate } from "@/lib/utils"; +import Balancer from "react-wrap-balancer"; + +import { buttonVariants } from "@dingify/ui/components/button"; + +interface PostPageProps { + params: { + slug: string[]; + }; +} + +async function getPostFromParams(params) { + const slug = params?.slug?.join("/"); + const post = allPosts.find((post) => post.slugAsParams === slug); + + if (!post) { + null; + } + + return post; +} + +export async function generateMetadata({ + params, +}: PostPageProps): Promise { + const post = await getPostFromParams(params); + + if (!post) { + return {}; + } + + const url = env.NEXT_PUBLIC_APP_URL; + + const ogUrl = new URL(`${url}/api/og`); + ogUrl.searchParams.set("heading", post.title); + ogUrl.searchParams.set("type", "Blog Post"); + ogUrl.searchParams.set("mode", "dark"); + + return { + title: post.title, + description: post.description, + authors: post.authors.map((author) => ({ + name: author, + })), + openGraph: { + title: post.title, + description: post.description, + type: "article", + url: absoluteUrl(post.slug), + images: [ + { + url: ogUrl.toString(), + width: 1200, + height: 630, + alt: post.title, + }, + ], + }, + twitter: { + card: "summary_large_image", + title: post.title, + description: post.description, + images: [ogUrl.toString()], + }, + }; +} + +export async function generateStaticParams(): Promise< + PostPageProps["params"][] +> { + return allPosts.map((post) => ({ + slug: post.slugAsParams.split("/"), + })); +} + +export default async function PostPage({ params }: PostPageProps) { + const post = await getPostFromParams(params); + + if (!post) { + notFound(); + } + + const authors = post.authors.map((author) => + allAuthors.find(({ slug }) => slug === `/authors/${author}`) + ); + + return ( +
+ + + See all posts + +
+ {post.date && ( + + )} +

+ {post.title} +

+ {authors.length ? ( +
+ {authors.map((author) => + author ? ( + + {author.title} +
+

{author.title}

+

+ @{author.twitter} +

+
+ + ) : null + )} +
+ ) : null} +
+ {post.image && ( + {post.title} + )} + +
+
+ + + See all posts + +
+
+ ); +} diff --git a/apps/www/src/app/(marketing)/blog/page.tsx b/apps/www/src/app/(marketing)/blog/page.tsx new file mode 100644 index 0000000..08a45d6 --- /dev/null +++ b/apps/www/src/app/(marketing)/blog/page.tsx @@ -0,0 +1,23 @@ +import { BlogPosts } from "@/components/blog-posts"; +import { allPosts } from "contentlayer/generated"; +import { compareDesc } from "date-fns"; + +export const metadata = { + title: "Dingify Blog - Insights on Real-Time Monitoring & Analytics", + description: + "Explore the latest insights on real-time monitoring, data analytics, and journey tracking strategies in the Dingify blog. Stay ahead with innovative business analytics and industry trends.", +}; + +export default async function BlogPage() { + const posts = allPosts + .filter((post) => post.published) + .sort((a, b) => { + return compareDesc(new Date(a.date), new Date(b.date)); + }); + + return ( +
+ +
+ ); +} diff --git a/apps/www/src/app/(marketing)/error.tsx b/apps/www/src/app/(marketing)/error.tsx new file mode 100644 index 0000000..55262f8 --- /dev/null +++ b/apps/www/src/app/(marketing)/error.tsx @@ -0,0 +1,14 @@ +"use client"; + +import { Button } from "@dingify/ui/components/button"; + +export default function Error({ reset }: { reset: () => void }) { + return ( +
+

Something went wrong!

+ +
+ ); +} diff --git a/apps/www/src/app/(marketing)/layout.tsx b/apps/www/src/app/(marketing)/layout.tsx new file mode 100644 index 0000000..ae2f956 --- /dev/null +++ b/apps/www/src/app/(marketing)/layout.tsx @@ -0,0 +1,26 @@ +import { Suspense } from "react"; + +import { marketingConfig } from "@/config/marketing"; +import { getCurrentUser } from "@/lib/session"; +import { NavBar } from "@/components/layout/navbar"; +import { SiteFooter } from "@/components/layout/site-footer"; + +interface MarketingLayoutProps { + children: React.ReactNode; +} + +export default async function MarketingLayout({ + children, +}: MarketingLayoutProps) { + const user = await getCurrentUser(); + + return ( +
+ + + +
{children}
+ +
+ ); +} diff --git a/apps/www/src/app/(marketing)/open/loading.tsx b/apps/www/src/app/(marketing)/open/loading.tsx new file mode 100644 index 0000000..3795ac1 --- /dev/null +++ b/apps/www/src/app/(marketing)/open/loading.tsx @@ -0,0 +1,28 @@ +import { Skeleton } from "@dingify/ui/components/skeleton"; + +export default function Loading() { + return ( +
+
+
+ + + +
+ +
+ + + +
+ +
+ + +
+
+ +
+
+ ); +} diff --git a/apps/www/src/app/(marketing)/open/page.tsx b/apps/www/src/app/(marketing)/open/page.tsx new file mode 100644 index 0000000..66aa503 --- /dev/null +++ b/apps/www/src/app/(marketing)/open/page.tsx @@ -0,0 +1,39 @@ +import { Suspense } from "react"; + +import { getCurrentUser } from "@/lib/session"; +import { fetchGithubData } from "@/lib/utils"; +import OpenCardSection from "@/components/open-page/OpenCardsSection"; +import OpenMiddleSection from "@/components/open-page/OpenMiddleSection"; +import { OpenSalaryTable } from "@/components/open-page/OpenSalaryTable"; +import OpenStartupSection from "@/components/open-page/OpenStartupSection"; +import { OpenTableTeam } from "@/components/open-page/OpenTableTeam"; +import OpenUsersDiagram from "@/components/open-page/OpenUsersDiagram"; +import OpenUsersFunding from "@/components/open-page/OpenUsersFunding"; +import OpenUsersText from "@/components/open-page/OpenUsersText"; + +export const metadata = { + title: "Badget Open - Everything open", + description: + "All our metrics, finances, and learnings are public. We believe in transparency.", +}; + +export default async function PricingPage() { + const user = await getCurrentUser(); + // const subscriptionPlan = await api.auth.mySubscription.query(); + const Githubstats = await fetchGithubData(); + // const x = await api.customer.getAllCustomers.query(); + // console.log(x); + + return ( +
+ + + + + + + + +
+ ); +} diff --git a/apps/www/src/app/(marketing)/page.tsx b/apps/www/src/app/(marketing)/page.tsx new file mode 100644 index 0000000..034de90 --- /dev/null +++ b/apps/www/src/app/(marketing)/page.tsx @@ -0,0 +1,118 @@ +import Link from "next/link"; +import Balancer from "react-wrap-balancer"; + +import { buttonVariants } from "@dingify/ui/components/button"; + +import { siteConfig } from "@/config/site"; +import { cn, nFormatter } from "@/lib/utils"; +import Particles from "@/components/ui/particles"; +import { SphereMask } from "@/components/ui/sphere-mask"; +import { GetStartedButton } from "@/components/buttons/GetStartedButton"; +import { BeamSection } from "@/components/dashboard/beam-section"; +import { BusinessLine } from "@/components/dashboard/businessline"; +import CallToActionComponent from "@/components/dashboard/calltoaction"; +import Featuressection from "@/components/dashboard/feautressection"; +import HeroSection from "@/components/dashboard/herosection"; +import HeroSection2 from "@/components/dashboard/herosection2"; +import BottomSectionLanding from "@/components/landing/bottom-section-landing"; +import CallToActionSection from "@/components/landing/cta-section"; +import EventsSectionLanding from "@/components/landing/events-section-landing"; +import HeroSectionNew2 from "@/components/landing/hero-section"; +import { IntegrationsSectionLanding } from "@/components/landing/Integrations-section-landing"; +import { Icons } from "@/components/shared/icons"; + +export default async function IndexPage() { + return ( + <> + + + + + + + + + + + + {/* */} + {/* */} + {/*
+
+ + Introducing on + + +

+ + Get Alerts, with{" "} + + Dingify + + +

+ +

+ + We made it so easy that you can track and get alerts within 60 + seconds after sign up + +

+ +
+ + + +

+ Lets explore{" "} + Dingify{" "} +

+ +
+
+
*/} + {/* */} + {/*
+ +
+
+ +
*/} + {/*
+ +
*/} + + ); +} diff --git a/apps/www/src/app/(marketing)/pricing/loading.tsx b/apps/www/src/app/(marketing)/pricing/loading.tsx new file mode 100644 index 0000000..3795ac1 --- /dev/null +++ b/apps/www/src/app/(marketing)/pricing/loading.tsx @@ -0,0 +1,28 @@ +import { Skeleton } from "@dingify/ui/components/skeleton"; + +export default function Loading() { + return ( +
+
+
+ + + +
+ +
+ + + +
+ +
+ + +
+
+ +
+
+ ); +} diff --git a/apps/www/src/app/(marketing)/pricing/page.tsx b/apps/www/src/app/(marketing)/pricing/page.tsx new file mode 100644 index 0000000..8e4424a --- /dev/null +++ b/apps/www/src/app/(marketing)/pricing/page.tsx @@ -0,0 +1,29 @@ +import { PricingCards } from "@/components/pricing-cards"; +import { PricingFaq } from "@/components/pricing-faq"; +import { getCurrentUser } from "@/lib/session"; +import { getUserSubscriptionPlan } from "@/lib/subscription"; + +import { Skeleton } from "@dingify/ui/components/skeleton"; + +export const metadata = { + title: "Dingify Pricing - Tailored Plans for Your Monitoring Needs", + description: + "Explore competitive pricing plans for Dingify. Find the perfect package to enhance your real-time monitoring, event tracking, and data analytics.", +}; + +export default async function PricingPage() { + const user = await getCurrentUser(); + let subscriptionPlan; + + if (user) { + subscriptionPlan = await getUserSubscriptionPlan(user.id); + } + + return ( +
+ +
+ +
+ ); +} diff --git a/apps/www/src/app/(property)/property/[id]/layout.tsx b/apps/www/src/app/(property)/property/[id]/layout.tsx new file mode 100644 index 0000000..4bcace3 --- /dev/null +++ b/apps/www/src/app/(property)/property/[id]/layout.tsx @@ -0,0 +1,40 @@ +import { notFound } from "next/navigation"; +import { DashboardNav } from "@/components/layout/nav"; +import { NavBar } from "@/components/layout/navbar"; +import { SiteFooter } from "@/components/layout/site-footer"; +import { propertyConfig } from "@/config/property"; +import { getCurrentUser } from "@/lib/session"; + +interface DashboardLayoutProps { + children?: React.ReactNode; + params: { id: string }; +} + +export default async function DashboardLayout({ + children, + params, +}: DashboardLayoutProps) { + const user = await getCurrentUser(); + + if (!user) { + return notFound(); + } + + const slug = params.id; + + return ( +
+ + +
+ +
+ {children} +
+
+ +
+ ); +} diff --git a/apps/www/src/app/(property)/property/[id]/loading.tsx b/apps/www/src/app/(property)/property/[id]/loading.tsx new file mode 100644 index 0000000..3b3d0d4 --- /dev/null +++ b/apps/www/src/app/(property)/property/[id]/loading.tsx @@ -0,0 +1,21 @@ +import { DashboardHeader } from "@/components/dashboard/header"; +import { DashboardShell } from "@/components/dashboard/shell"; +import { CardSkeleton } from "@/components/shared/card-skeleton"; + +import { Button } from "@dingify/ui/components/button"; + +export default function DashboardLoading() { + return ( + + + + +
+ + + + +
+
+ ); +} diff --git a/apps/www/src/app/(property)/property/[id]/page.tsx b/apps/www/src/app/(property)/property/[id]/page.tsx new file mode 100644 index 0000000..2b28453 --- /dev/null +++ b/apps/www/src/app/(property)/property/[id]/page.tsx @@ -0,0 +1,91 @@ +import React, { useState } from "react"; +import Generatedtext from "@/components/dashboard/generatedtext"; +import { DashboardHeader } from "@/components/dashboard/header"; +import { DashboardShell } from "@/components/dashboard/shell"; +import { InputRightSideTest } from "@/components/dashboard/test"; +import { UpdatePropertyForm2 } from "@/components/dashboard/updatepropertyform2"; +import { UpdatePropertyForm } from "@/components/forms/update-property-form"; +import NoPhotoPlaceholder from "@/components/properties/NoPhotoPlaceholder copy"; + +import { prisma } from "@dingify/db"; + +export const metadata = { + title: "Property Details - Propwrite Dashboard", + description: + "View and edit your property details, add images, and customize listings to attract potential buyers. Your one-stop destination for managing individual real estate listings on Propwrite.", +}; + +export const maxDuration = 50; + +export default async function PropertyPage({ + params, +}: { + params: { id: string }; +}) { + const propertyId = params.id; + const propertyData = await getPropertyData(); + const hasPhotos = propertyData?.images && propertyData.images.length > 0; + + async function getPropertyData() { + try { + // Fetch the property data including images using Prisma + const propertyData = await prisma.property.findUnique({ + where: { id: propertyId }, + include: { images: true }, // Include the images in the response + }); + return propertyData; + } catch (error) { + console.error("Error fetching property:", error); + return null; + } + } + + // Extract the default values from the property data + const defaultFormValues = { + address: propertyData?.address || "", + description: propertyData?.description || "", + p_rom: propertyData?.p_rom || "", + bra: propertyData?.bra || "", + soverom: propertyData?.soverom || "", + pris: propertyData?.pris || "", + takst_text: propertyData?.takst_text || "", + }; + + if (!hasPhotos) { + return ( + + +
+ +
+
+ ); + } + + return ( + + +
+
+ +
+
+ +
+
+
+
+ ); +} diff --git a/apps/www/src/app/(property)/property/[id]/pictures/loading.tsx b/apps/www/src/app/(property)/property/[id]/pictures/loading.tsx new file mode 100644 index 0000000..eab671f --- /dev/null +++ b/apps/www/src/app/(property)/property/[id]/pictures/loading.tsx @@ -0,0 +1,32 @@ +import { Skeleton } from "@dingify/ui/components/skeleton"; + +export default function PicturesLoading() { + return ( +
+
+ + +
+
+
+ +
+
+ + + +
+
+
+
+ +
+
+ + + +
+
+
+ ); +} diff --git a/apps/www/src/app/(property)/property/[id]/pictures/page.tsx b/apps/www/src/app/(property)/property/[id]/pictures/page.tsx new file mode 100644 index 0000000..10ae2be --- /dev/null +++ b/apps/www/src/app/(property)/property/[id]/pictures/page.tsx @@ -0,0 +1,62 @@ +import React from "react"; +import Link from "next/link"; +import { DashboardHeader } from "@/components/dashboard/header"; +import { DashboardShell } from "@/components/dashboard/shell"; +import NoPhotoPlaceholder from "@/components/properties/NoPhotoPlaceholder copy"; +import PropertyImageWithOptions from "@/components/properties/PropertyImageWithOptions"; + +import { prisma } from "@dingify/db"; +import { Button } from "@dingify/ui/components/button"; + +const MAX_PHOTOS = 20; // Set the maximum number of photos allowed + +export default async function PropertyPage({ params }) { + const propertyId = params.id; + + // Fetch property data + const propertyData = await getPropertyData(propertyId); + const hasPhotos = (propertyData?.images.length ?? 0) > 0; + const canAddMorePhotos = (propertyData?.images.length ?? 0) < MAX_PHOTOS; + MAX_PHOTOS; + + // Function to get property data + async function getPropertyData(id) { + try { + return await prisma.property.findUnique({ + where: { id }, + include: { images: true }, + }); + } catch (error) { + console.error("Error fetching property:", error); + return null; + } + } + + return ( + + + {canAddMorePhotos ? ( + + )} + + +
+ {hasPhotos ? ( + propertyData?.images.map((image) => ( + + )) + ) : ( + + )} +
+ + + +
+ ); +} diff --git a/apps/www/src/app/(property)/property/[id]/report/page.tsx b/apps/www/src/app/(property)/property/[id]/report/page.tsx new file mode 100644 index 0000000..9b3c271 --- /dev/null +++ b/apps/www/src/app/(property)/property/[id]/report/page.tsx @@ -0,0 +1,11 @@ +export default function Report(props: { params: { id: string } }) { + return ( +
+

{"Nothing to see here..."}

+ Nothing here yet +
+ ); +} diff --git a/apps/www/src/app/(property)/property/[id]/settings/loading.tsx b/apps/www/src/app/(property)/property/[id]/settings/loading.tsx new file mode 100644 index 0000000..6f431b2 --- /dev/null +++ b/apps/www/src/app/(property)/property/[id]/settings/loading.tsx @@ -0,0 +1,17 @@ +import { DashboardHeader } from "@/components/dashboard/header"; +import { DashboardShell } from "@/components/dashboard/shell"; +import { CardSkeleton } from "@/components/shared/card-skeleton"; + +export default function DashboardSettingsLoading() { + return ( + + +
+ +
+
+ ); +} diff --git a/apps/www/src/app/(property)/property/[id]/settings/page.tsx b/apps/www/src/app/(property)/property/[id]/settings/page.tsx new file mode 100644 index 0000000..fd18350 --- /dev/null +++ b/apps/www/src/app/(property)/property/[id]/settings/page.tsx @@ -0,0 +1,31 @@ +import { redirect } from "next/navigation"; +import { DashboardHeader } from "@/components/dashboard/header"; +import { DashboardShell } from "@/components/dashboard/shell"; +import { UserNameForm } from "@/components/forms/user-name-form"; +import { authOptions } from "@/lib/auth"; +import { getCurrentUser } from "@/lib/session"; + +export const metadata = { + title: "Settings", + description: "Manage account and website settings.", +}; + +export default async function SettingsPage() { + const user = await getCurrentUser(); + + if (!user) { + redirect(authOptions.pages?.signIn || "/login"); + } + + return ( + + +
+ +
+
+ ); +} diff --git a/apps/www/src/app/api/ai/analyzeImage/route.ts b/apps/www/src/app/api/ai/analyzeImage/route.ts new file mode 100644 index 0000000..5116fe2 --- /dev/null +++ b/apps/www/src/app/api/ai/analyzeImage/route.ts @@ -0,0 +1,68 @@ +import { NextRequest, NextResponse } from "next/server"; +import axios from "axios"; + +export async function POST(request: NextRequest) { + const openaiApiKey = process.env.OPENAI_API_KEY; + + if (!openaiApiKey) { + console.error("OpenAI API key is not set in environment variables."); + return NextResponse.json( + { error: "OpenAI API key not found" }, + { status: 500 }, + ); + } + + const config = { + headers: { + Authorization: `Bearer ${openaiApiKey}`, + "Content-Type": "application/json", + }, + }; + + const requestBody = await request.json(); + const imageUrl = requestBody.imageUrl; + const language = requestBody.language; + + const requestTexts = { + english: + "I want you to act as a real estate agent. I would like you to create text based on the image you receive, writing a detailed and appealing property description. The style should be professional, and the description should be about one line long. I want 3 different lines so I can choose. Include unique features and highlight what makes this property special.", + swedish: + "Jag vill att du agerar som en fastighetsmรคklare. Jag skulle vilja att du skapar text baserad pรฅ den bild du fรฅr, och skriver en detaljerad och tilltalande egendomsbeskrivning. Stilen bรถr vara professionell, och beskrivningen bรถr vara ungefรคr en mening lรฅng. Jag vill ha 3 olika meningar sรฅ att jag kan vรคlja. Inkludera unika funktioner och framhรคv vad som gรถr denna egendom speciell.", + norwegian: + "Jeg รธnsker at du skal opptre som en eiendomsmegler. Jeg vil at du skal lage tekst basert pรฅ bildet du mottar, og skrive en detaljert og tiltalende eiendomsbeskrivelse. Stilen skal vรฆre profesjonell, og beskrivelsen skal vรฆre omtrent รฉn setning lang. Jeg รธnsker 3 forskjellige setninger slik at jeg kan velge. Inkluder unike funksjoner og fremhev hva som gjรธr denne eiendommen spesiell.", + }; + + const requestText = requestTexts[language] || requestTexts["english"]; + + try { + const response = await axios.post( + "https://api.openai.com/v1/chat/completions", + { + model: "gpt-4-vision-preview", + messages: [ + { + role: "user", + content: [ + { type: "text", text: requestText }, + { type: "image_url", image_url: imageUrl }, + ], + }, + ], + max_tokens: 300, + }, + config, + ); + + console.log( + "Image analysis completed, response data:", + JSON.stringify(response.data, null, 2), + ); + return NextResponse.json(response.data); + } catch (error) { + console.error("Failed to analyze image, caught error:", error); + return NextResponse.json( + { error: "Failed to analyze image" }, + { status: 500 }, + ); + } +} diff --git a/apps/www/src/app/api/ai/generateDescription/route.ts b/apps/www/src/app/api/ai/generateDescription/route.ts new file mode 100644 index 0000000..64ba49c --- /dev/null +++ b/apps/www/src/app/api/ai/generateDescription/route.ts @@ -0,0 +1,54 @@ +// app/api/ai/generateDescription/route.ts +import { NextRequest, NextResponse } from "next/server"; +import axios from "axios"; + +export async function POST(request: NextRequest) { + const requestBody = await request.json(); + const { allResponses, text } = requestBody; + + // Construct messages for the chat completion request + const messages = allResponses.map((response) => { + return { + role: "user", + content: `Options: ${response.options.join(", ")}.`, + }; + }); + + console.log(messages); + + // Add the specific request text + messages.push({ + role: "system", + content: + "I need you to act like a real estate agent and write a description for this house. I need a title and a description", + }); + messages.push({ role: "user", content: text }); + + try { + const openaiResponse = await axios.post( + "https://api.openai.com/v1/chat/completions", + { + model: "gpt-4", + messages: messages, + }, + { + headers: { + Authorization: `Bearer ${process.env.OPENAI_API_KEY}`, + "Content-Type": "application/json", + }, + }, + ); + + // Extracting the assistant's response + const completion = openaiResponse.data.choices[0].message.content; + + // Send the assistant's response back to the client + return NextResponse.json({ description: completion }); + } catch (error) { + console.error("Error in generating description:", error); + return NextResponse.json( + { error: "Failed to generate description" }, + { status: 500 }, + ); + } +} diff --git a/apps/www/src/app/api/auth/[...nextauth]/route.ts b/apps/www/src/app/api/auth/[...nextauth]/route.ts new file mode 100644 index 0000000..ca0b5b4 --- /dev/null +++ b/apps/www/src/app/api/auth/[...nextauth]/route.ts @@ -0,0 +1,6 @@ +import { authOptions } from "@/lib/auth"; +import NextAuth from "next-auth"; + +const handler = NextAuth(authOptions); + +export { handler as GET, handler as POST }; diff --git a/apps/www/src/app/api/og/route.tsx b/apps/www/src/app/api/og/route.tsx new file mode 100644 index 0000000..7021bc3 --- /dev/null +++ b/apps/www/src/app/api/og/route.tsx @@ -0,0 +1,142 @@ +import { ogImageSchema } from "@/lib/validations/og"; +import { ImageResponse } from "@vercel/og"; + +export const runtime = "edge"; + +const interRegular = fetch( + new URL("../../../assets/fonts/Inter-Regular.ttf", import.meta.url) +).then((res) => res.arrayBuffer()); + +const interBold = fetch( + new URL("../../../assets/fonts/CalSans-SemiBold.ttf", import.meta.url) +).then((res) => res.arrayBuffer()); + +export async function GET(req: Request) { + try { + const fontRegular = await interRegular; + const fontBold = await interBold; + + const url = new URL(req.url); + const values = ogImageSchema.parse(Object.fromEntries(url.searchParams)); + const heading = + values.heading.length > 80 + ? `${values.heading.substring(0, 100)}...` + : values.heading; + + const { mode } = values; + const paint = mode === "dark" ? "#fff" : "#000"; + + const fontSize = heading.length > 80 ? "60px" : "80px"; + + const githubName = "mickasmt"; + + return new ImageResponse( + ( +
+
+ Propwrite +
+ +
+ {/* Type : Blog or Doc */} +
+ {values.type} +
+ {/* Title */} +
+ {heading} +
+
+ +
+
+
+
+ Propwrite +
+
List Smarter, Sell Faster
+
+
+ +
+ {/* + + + */} +
+
+
+ ), + { + width: 1200, + height: 630, + fonts: [ + { + name: "Inter", + data: fontRegular, + weight: 400, + style: "normal", + }, + { + name: "Cal Sans", + data: fontBold, + weight: 700, + style: "normal", + }, + ], + } + ); + } catch (error) { + return new Response(`Failed to generate image`, { + status: 500, + }); + } +} diff --git a/apps/www/src/app/api/property/addproperty/route.tsx b/apps/www/src/app/api/property/addproperty/route.tsx new file mode 100644 index 0000000..31c7ac7 --- /dev/null +++ b/apps/www/src/app/api/property/addproperty/route.tsx @@ -0,0 +1,69 @@ +import type { NextRequest } from "next/server"; +import { revalidatePath } from "next/cache"; +import { NextResponse } from "next/server"; +import { getUserCredits } from "@/actions/get-credits"; +import { getCurrentUser } from "@/lib/session"; + +import { prisma } from "@dingify/db"; + +export async function POST(request: NextRequest) { + const user = await getCurrentUser(); + const userCreditsResponse = await getUserCredits(); + + if (!user) { + console.error("Unauthorized: No user found."); + return new NextResponse(JSON.stringify({ message: "Unauthorized" }), { + status: 401, + }); + } + + const requestBody = await request.json(); + const { address, type } = requestBody; + + if (!address) { + console.error("Bad request: Address is required."); + return new NextResponse( + JSON.stringify({ message: "Address is required" }), + { status: 400 } + ); + } + + // Ensure userCredits is defined, default to 0 if undefined + const availableCredits = userCreditsResponse.credits ?? 0; + + try { + // Check if the user has enough credits + if (availableCredits <= 0) { + return new NextResponse( + JSON.stringify({ message: "Insufficient credits" }), + { status: 400 } + ); + } + + // Create new property + const newProperty = await prisma.property.create({ + data: { + address, + label: type || "PROPERTY", + userId: user.id, + }, + }); + + // Deduct a credit from the user + await prisma.user.update({ + where: { id: user.id }, + data: { credits: { decrement: 1 } }, + }); + + revalidatePath("/dashboard"); // Revalidate the dashboard to update the property list + + console.log("Property created:", newProperty); + return new NextResponse(JSON.stringify(newProperty), { status: 201 }); + } catch (error) { + console.error("Internal server error:", error); + return new NextResponse( + JSON.stringify({ message: "Error creating property" }), + { status: 500 } + ); + } +} diff --git a/apps/www/src/app/api/webhooks/stripe/route.ts b/apps/www/src/app/api/webhooks/stripe/route.ts new file mode 100644 index 0000000..fc534d5 --- /dev/null +++ b/apps/www/src/app/api/webhooks/stripe/route.ts @@ -0,0 +1,106 @@ +import type Stripe from "stripe"; +import { headers } from "next/headers"; +import { env } from "@/env"; +import { stripe } from "@/lib/stripe"; + +import { prisma } from "@dingify/db"; + +export async function POST(req: Request) { + const body = await req.text(); + const signature = headers().get("Stripe-Signature")!; + + let event: Stripe.Event; + + try { + event = stripe.webhooks.constructEvent( + body, + signature, + env.STRIPE_WEBHOOK_SECRET + ); + } catch (error) { + console.error("Webhook Error:", error); + return new Response(`Webhook Error: ${error.message}`, { status: 400 }); + } + + console.log("Received Stripe event:", event); + + // Handling checkout.session.completed event + if (event.type === "checkout.session.completed") { + const session = event.data.object; + console.log("Session details:", session); + + try { + const subscription = await stripe.subscriptions.retrieve( + session.subscription as string + ); + console.log("Subscription details for session completed:", subscription); + + const updatedUser = await prisma.user.update({ + where: { + id: session.metadata?.userId, + }, + data: { + stripeSubscriptionId: subscription.id, + stripeCustomerId: subscription.customer as string, + // @ts-expect-error + stripePriceId: subscription.items.data[0].price.id, + stripeCurrentPeriodEnd: new Date( + subscription.current_period_end * 1000 + ), + }, + select: { + stripeSubscriptionId: true, + stripeCustomerId: true, + stripePriceId: true, + stripeCurrentPeriodEnd: true, + }, + }); + + console.log( + "User updated successfully for session completed:", + updatedUser + ); + } catch (error) { + console.error("Error updating user for session completed:", error); + } + } + + // Handling invoice.payment_succeeded event + if (event.type === "invoice.payment_succeeded") { + const invoice = event.data.object; + console.log("Invoice details:", invoice); + + try { + const subscription = await stripe.subscriptions.retrieve( + invoice.subscription as string + ); + console.log("Subscription details for payment succeeded:", subscription); + + const updatedUser = await prisma.user.update({ + where: { + stripeSubscriptionId: subscription.id, + }, + data: { + // @ts-expect-error + stripePriceId: subscription.items.data[0].price.id, + stripeCurrentPeriodEnd: new Date( + subscription.current_period_end * 1000 + ), + }, + select: { + stripePriceId: true, + stripeCurrentPeriodEnd: true, + }, + }); + + console.log( + "User updated successfully for payment succeeded:", + updatedUser + ); + } catch (error) { + console.error("Error updating user for payment succeeded:", error); + } + } + + return new Response(null, { status: 200 }); +} diff --git a/apps/www/src/app/layout.tsx b/apps/www/src/app/layout.tsx new file mode 100644 index 0000000..076a3d8 --- /dev/null +++ b/apps/www/src/app/layout.tsx @@ -0,0 +1,89 @@ +import "../styles/globals.css"; + +import { Metadata } from "next"; +import { fontHeading, fontSans, fontUrban } from "@/assets/fonts"; + +import { Toaster } from "@dingify/ui/components/sonner"; + +import { siteConfig } from "@/config/site"; +import { cn } from "@/lib/utils"; +import { Analytics } from "@/components/analytics"; +import { ModalProvider } from "@/components/modal-provider"; +import { Providers } from "@/components/providers"; +import { TailwindIndicator } from "@/components/tailwind-indicator"; + +interface RootLayoutProps { + children: React.ReactNode; +} + +export const metadata = { + title: { + default: siteConfig.name, + template: `%s | ${siteConfig.name}`, + }, + description: siteConfig.description, + keywords: [ + "Real-time monitoring", + "Business analytics", + "Event tracking", + "Journey tracking", + "Real-time alerts", + "Performance insights", + "Data-driven decisions", + "KPI tracking", + "Seamless monitoring", + "User journeys analytics", + ], + authors: [ + { + name: "christer", + }, + ], + creator: "codehagen", + metadataBase: new URL(siteConfig.url), + openGraph: { + type: "website", + locale: "en_US", + url: siteConfig.url, + title: siteConfig.name, + description: siteConfig.description, + siteName: siteConfig.name, + }, + twitter: { + card: "summary_large_image", + title: siteConfig.name, + description: siteConfig.description, + images: [siteConfig.ogImage], + creator: "@codehagen", + }, + icons: { + icon: "/favicon.ico", + shortcut: "/favicon-16x16.png", + apple: "/apple-touch-icon.png", + }, + manifest: `${siteConfig.url}/site.webmanifest`, +}; + +export default function RootLayout({ children }: RootLayoutProps) { + return ( + + + + + {children} + + + + + + + + ); +} diff --git a/apps/www/src/app/robots.ts b/apps/www/src/app/robots.ts new file mode 100644 index 0000000..fc42c63 --- /dev/null +++ b/apps/www/src/app/robots.ts @@ -0,0 +1,10 @@ +import { MetadataRoute } from "next"; + +export default function robots(): MetadataRoute.Robots { + return { + rules: { + userAgent: "*", + allow: "/", + }, + }; +} diff --git a/apps/www/src/app/sitemap.ts b/apps/www/src/app/sitemap.ts new file mode 100644 index 0000000..13a026e --- /dev/null +++ b/apps/www/src/app/sitemap.ts @@ -0,0 +1,36 @@ +import { MetadataRoute } from "next"; +import { allPages, allPosts } from "contentlayer/generated"; + +export default async function sitemap(): Promise { + const domain = "dingify.io"; // Replace with your actual domain + + // Manually added static pages with today's date + const staticPagesSitemap = [ + { + url: `https://${domain}/`, // Home page + lastModified: new Date("2023-11-28"), // Set to November 28, 2023 + }, + { + url: `https://${domain}/pricing`, // Pricing page + lastModified: new Date("2023-11-28"), // Set to November 28, 2023 + }, + // Add other static pages here if necessary + ]; + + // // Sitemap for dynamic pages + // const pagesSitemap = allPages.map((page) => ({ + // url: `https://${domain}/${page.slug.replace(/^\/+/g, "")}`, // Remove leading + // // lastModified can be included if available + // })); + + // Sitemap for blog posts + const postsSitemap = allPosts + .filter((post) => post.published) + .map((post) => ({ + url: `https://${domain}/${post.slug.replace(/^\/+/g, "")}`, // Correct path and remove leading slashes + lastModified: new Date(post.date), + })); + + // Combine sitemaps + return [...staticPagesSitemap, ...postsSitemap]; +} diff --git a/apps/www/src/assets/fonts/CalSans-SemiBold.ttf b/apps/www/src/assets/fonts/CalSans-SemiBold.ttf new file mode 100644 index 0000000..4a2950a Binary files /dev/null and b/apps/www/src/assets/fonts/CalSans-SemiBold.ttf differ diff --git a/apps/www/src/assets/fonts/CalSans-SemiBold.woff2 b/apps/www/src/assets/fonts/CalSans-SemiBold.woff2 new file mode 100644 index 0000000..36d71b7 Binary files /dev/null and b/apps/www/src/assets/fonts/CalSans-SemiBold.woff2 differ diff --git a/apps/www/src/assets/fonts/Inter-Bold.ttf b/apps/www/src/assets/fonts/Inter-Bold.ttf new file mode 100644 index 0000000..8e82c70 Binary files /dev/null and b/apps/www/src/assets/fonts/Inter-Bold.ttf differ diff --git a/apps/www/src/assets/fonts/Inter-Regular.ttf b/apps/www/src/assets/fonts/Inter-Regular.ttf new file mode 100644 index 0000000..8d4eebf Binary files /dev/null and b/apps/www/src/assets/fonts/Inter-Regular.ttf differ diff --git a/apps/www/src/assets/fonts/index.ts b/apps/www/src/assets/fonts/index.ts new file mode 100644 index 0000000..f7f901d --- /dev/null +++ b/apps/www/src/assets/fonts/index.ts @@ -0,0 +1,17 @@ +import { Inter as FontSans, Urbanist } from "next/font/google"; +import localFont from "next/font/local"; + +export const fontSans = FontSans({ + subsets: ["latin"], + variable: "--font-sans", +}); + +export const fontUrban = Urbanist({ + subsets: ["latin"], + variable: "--font-urban", +}); + +export const fontHeading = localFont({ + src: "./CalSans-SemiBold.woff2", + variable: "--font-heading", +}); diff --git a/apps/www/src/components/UserBadge.tsx b/apps/www/src/components/UserBadge.tsx new file mode 100644 index 0000000..67cce33 --- /dev/null +++ b/apps/www/src/components/UserBadge.tsx @@ -0,0 +1,18 @@ +// components/shared/ClickableBadge.tsx +import { Badge } from "@dingify/ui/components/badge"; + +export function UserBadge({ customerId, userId, variant, onClick }) { + const handleClick = (e) => { + onClick(customerId); + }; + + return ( + + {userId} + + ); +} diff --git a/apps/www/src/components/analytics.tsx b/apps/www/src/components/analytics.tsx new file mode 100644 index 0000000..52e59d2 --- /dev/null +++ b/apps/www/src/components/analytics.tsx @@ -0,0 +1,7 @@ +"use client"; + +import { Analytics as VercelAnalytics } from "@vercel/analytics/react"; + +export function Analytics() { + return ; +} diff --git a/apps/www/src/components/analytics/CardSection.tsx b/apps/www/src/components/analytics/CardSection.tsx new file mode 100644 index 0000000..6838a79 --- /dev/null +++ b/apps/www/src/components/analytics/CardSection.tsx @@ -0,0 +1,111 @@ +import { + Card, + CardContent, + CardHeader, + CardTitle, +} from "@dingify/ui/components/card"; + +export default function CardSection( + { + // totalUsers, + // usersToday, + // usersThisWeek, + // usersThisMonth, + }, +) { + return ( +
+ + + Today's Users + + + + + +
14
+

New users today

+
+
+ + + + This Week's Users + + + + + + + + +
28
+

New users this week

+
+
+ + + + This Month's Users + + + + + + + +
114
+

New users this month

+
+
+ + + All Users + + + + + +
573
+

Total users

+
+
+
+ ); +} diff --git a/apps/www/src/components/animate-beam.tsx b/apps/www/src/components/animate-beam.tsx new file mode 100644 index 0000000..2f64c65 --- /dev/null +++ b/apps/www/src/components/animate-beam.tsx @@ -0,0 +1,188 @@ +"use client"; + +import { RefObject, useEffect, useId, useState } from "react"; +import { motion } from "framer-motion"; + +import { cn } from "@/lib/utils"; + +export interface AnimatedBeamProps { + className?: string; + containerRef: RefObject; // Container ref + fromRef: RefObject; + toRef: RefObject; + curvature?: number; + reverse?: boolean; + pathColor?: string; + pathWidth?: number; + pathOpacity?: number; + gradientStartColor?: string; + gradientStopColor?: string; + delay?: number; + duration?: number; + startXOffset?: number; + startYOffset?: number; + endXOffset?: number; + endYOffset?: number; +} + +export const AnimatedBeam: React.FC = ({ + className, + containerRef, + fromRef, + toRef, + curvature = 0, + reverse = false, // Include the reverse prop + duration = Math.random() * 3 + 4, + delay = 0, + pathColor = "gray", + pathWidth = 2, + pathOpacity = 0.2, + gradientStartColor = "#ffaa40", + gradientStopColor = "#9c40ff", + startXOffset = 0, + startYOffset = 0, + endXOffset = 0, + endYOffset = 0, +}) => { + const id = useId(); + const [pathD, setPathD] = useState(""); + const [svgDimensions, setSvgDimensions] = useState({ width: 0, height: 0 }); + + // Calculate the gradient coordinates based on the reverse prop + const gradientCoordinates = reverse + ? { + x1: ["90%", "-10%"], + x2: ["100%", "0%"], + y1: ["0%", "0%"], + y2: ["0%", "0%"], + } + : { + x1: ["10%", "110%"], + x2: ["0%", "100%"], + y1: ["0%", "0%"], + y2: ["0%", "0%"], + }; + + useEffect(() => { + const updatePath = () => { + if (containerRef.current && fromRef.current && toRef.current) { + const containerRect = containerRef.current.getBoundingClientRect(); + const rectA = fromRef.current.getBoundingClientRect(); + const rectB = toRef.current.getBoundingClientRect(); + + const svgWidth = containerRect.width; + const svgHeight = containerRect.height; + setSvgDimensions({ width: svgWidth, height: svgHeight }); + + const startX = + rectA.left - containerRect.left + rectA.width / 2 + startXOffset; + const startY = + rectA.top - containerRect.top + rectA.height / 2 + startYOffset; + const endX = + rectB.left - containerRect.left + rectB.width / 2 + endXOffset; + const endY = + rectB.top - containerRect.top + rectB.height / 2 + endYOffset; + + const controlY = startY - curvature; + const d = `M ${startX},${startY} Q ${ + (startX + endX) / 2 + },${controlY} ${endX},${endY}`; + setPathD(d); + } + }; + + // Initialize ResizeObserver + const resizeObserver = new ResizeObserver((entries) => { + // For all entries, recalculate the path + for (let entry of entries) { + updatePath(); + } + }); + + // Observe the container element + if (containerRef.current) { + resizeObserver.observe(containerRef.current); + } + + // Call the updatePath initially to set the initial path + updatePath(); + + // Clean up the observer on component unmount + return () => { + resizeObserver.disconnect(); + }; + }, [ + containerRef, + fromRef, + toRef, + curvature, + startXOffset, + startYOffset, + endXOffset, + endYOffset, + ]); + + return ( + + + + + + + + + + + + + ); +}; diff --git a/apps/www/src/components/billing-info.tsx b/apps/www/src/components/billing-info.tsx new file mode 100644 index 0000000..82502be --- /dev/null +++ b/apps/www/src/components/billing-info.tsx @@ -0,0 +1,49 @@ +"use client"; + +import type { UserSubscriptionPlan } from "@/types"; +import * as React from "react"; +import Link from "next/link"; +import { cn, formatDate } from "@/lib/utils"; + +import { buttonVariants } from "@dingify/ui/components/button"; +import { + Card, + CardContent, + CardDescription, + CardFooter, + CardHeader, + CardTitle, +} from "@dingify/ui/components/card"; + +interface BillingInfoProps extends React.HTMLAttributes { + subscriptionPlan: UserSubscriptionPlan; +} + +export function BillingInfo({ subscriptionPlan }: BillingInfoProps) { + return ( + + + Subscription Plan + + You are currently on the {subscriptionPlan.title}{" "} + plan. + + + {subscriptionPlan.description} + + + {subscriptionPlan.isPaid ? "Manage Subscription" : "Upgrade now"} + + + {subscriptionPlan.isPaid ? ( +

+ {subscriptionPlan.isCanceled + ? "Your plan will be canceled on " + : "Your plan renews on "} + {formatDate(subscriptionPlan.stripeCurrentPeriodEnd)}. +

+ ) : null} +
+
+ ); +} diff --git a/apps/www/src/components/blog-posts.tsx b/apps/www/src/components/blog-posts.tsx new file mode 100644 index 0000000..3e8246b --- /dev/null +++ b/apps/www/src/components/blog-posts.tsx @@ -0,0 +1,78 @@ +import Image from "next/image"; +import Link from "next/link"; +import { formatDate } from "@/lib/utils"; +import Balancer from "react-wrap-balancer"; + +export function BlogPosts({ posts }) { + return ( +
+
+

Last Post

+
+
+ {posts[0].image && ( + {posts[0].title} + )} +
+
+

+ {posts[0].title} +

+ {posts[0].description && ( +

+ {posts[0].description} +

+ )} + + View Article + +
+
+
+ +
+

Blog Posts

+
+ {posts.slice(1).map((post) => ( +
+ {post.image && ( + {post.title} + )} +

+ {post.title} +

+ {post.description && ( +

+ {post.description} +

+ )} + {post.date && ( +

+ {formatDate(post.date)} +

+ )} + + View Article + +
+ ))} +
+
+
+ ); +} diff --git a/apps/www/src/components/buttons/AddApiKeyButton.tsx b/apps/www/src/components/buttons/AddApiKeyButton.tsx new file mode 100644 index 0000000..1ac264c --- /dev/null +++ b/apps/www/src/components/buttons/AddApiKeyButton.tsx @@ -0,0 +1,226 @@ +"use client"; + +import { useEffect, useState } from "react"; +import { useRouter } from "next/navigation"; +import { generateAndSaveApiKey } from "@/actions/generate-api-key"; + +import { Button } from "@dingify/ui/components/button"; +import { + Dialog, + DialogContent, + DialogDescription, + DialogFooter, + DialogHeader, + DialogTitle, + DialogTrigger, +} from "@dingify/ui/components/dialog"; +import { Input } from "@dingify/ui/components/input"; +import { Label } from "@dingify/ui/components/label"; +import { + Tooltip, + TooltipContent, + TooltipTrigger, +} from "@dingify/ui/components/tooltip"; +import { toast } from "sonner"; + +export function AddApiKeyButton() { + const [apiKey, setApiKey] = useState(""); + const [isLoading, setIsLoading] = useState(false); + const [hasCopied, setHasCopied] = useState(false); + const [showKey, setShowKey] = useState(false); + const router = useRouter(); + + useEffect(() => { + const timer = setTimeout(() => { + setHasCopied(false); + }, 2000); + return () => clearTimeout(timer); + }, [hasCopied]); + + const handleSubmit = async (e) => { + e.preventDefault(); + setIsLoading(true); + + const response = await generateAndSaveApiKey(); + + if (response.success) { + setApiKey(response.apiKey as string); + + toast.success("Your new API key has been generated successfully."); + } else { + console.error(response.error); + toast.error("There was an error generating the API key."); + } + + setIsLoading(false); + }; + + const handleCopy = (e) => { + e.preventDefault(); + navigator.clipboard.writeText(apiKey); + setHasCopied(true); + toast.success("API key has been copied to clipboard."); + }; + + return ( + + + + + +
+ + Create a new API key + + Generate a new API key to get some Dings. + + +
+
+ +
+ + + + + + + Copy API key + +
+
+
+ + + +
+
+
+ ); +} + +function CopyIcon(props) { + return ( + + + + + ); +} + +function CheckIcon(props) { + return ( + + + + ); +} + +function EyeSlashIcon(props) { + return ( + + + + ); +} + +function EyeIcon(props) { + return ( + + + + + ); +} diff --git a/apps/www/src/components/buttons/AddChannelButton.tsx b/apps/www/src/components/buttons/AddChannelButton.tsx new file mode 100644 index 0000000..8a5aa52 --- /dev/null +++ b/apps/www/src/components/buttons/AddChannelButton.tsx @@ -0,0 +1,94 @@ +"use client"; + +import { useState } from "react"; +import { useRouter } from "next/navigation"; +import { createChannel } from "@/actions/create-channel"; + +import { Button } from "@dingify/ui/components/button"; +import { + Dialog, + DialogContent, + DialogDescription, + DialogFooter, + DialogHeader, + DialogTitle, + DialogTrigger, +} from "@dingify/ui/components/dialog"; +import { Input } from "@dingify/ui/components/input"; +import { Label } from "@dingify/ui/components/label"; +import { toast } from "sonner"; + +export function AddChannelButton() { + const [channelName, setChannelName] = useState(""); + const [isLoading, setIsLoading] = useState(false); + const router = useRouter(); + + const handleSubmit = async (event) => { + event.preventDefault(); + setIsLoading(true); + + try { + const result = await createChannel(channelName); + + if (!result.success) { + throw new Error(result.error || "Failed to add channel"); + } + + toast.success(`Channel "${channelName}" created successfully.`); + + // Optionally, you can refresh the page or navigate to the new channel + router.push(`/dashboard/channels/${result.channel?.id}`); + } catch (error) { + toast.error(error.message); + console.error(error); + } finally { + setIsLoading(false); + } + }; + + return ( + + + + + +
+ + Add new channel + + Enter the name of the new channel. + + +
+
+ + setChannelName(e.target.value)} + required + disabled={isLoading} + /> +
+
+ + + +
+
+
+ ); +} diff --git a/apps/www/src/components/buttons/AddProjectButton.tsx b/apps/www/src/components/buttons/AddProjectButton.tsx new file mode 100644 index 0000000..3fd8ce6 --- /dev/null +++ b/apps/www/src/components/buttons/AddProjectButton.tsx @@ -0,0 +1,94 @@ +"use client"; + +import { useState } from "react"; +import { useRouter } from "next/navigation"; +import { createProjectAndChannel } from "@/actions/create-project-and-channel"; + +import { Button } from "@dingify/ui/components/button"; +import { + Dialog, + DialogContent, + DialogDescription, + DialogFooter, + DialogHeader, + DialogTitle, + DialogTrigger, +} from "@dingify/ui/components/dialog"; +import { Input } from "@dingify/ui/components/input"; +import { Label } from "@dingify/ui/components/label"; +import { toast } from "sonner"; + +export function AddProjectButton() { + const [projectName, setProjectName] = useState(""); + const [isLoading, setIsLoading] = useState(false); + const router = useRouter(); + + const handleSubmit = async (event) => { + event.preventDefault(); + setIsLoading(true); + + try { + const result = await createProjectAndChannel(projectName); + + if (!result.success) { + throw new Error(result.error || "Failed to add project"); + } + + toast.success(`Project "${projectName}" created successfully.`); + + // router.push(`/project/${result.project?.id}`); + } catch (error) { + toast.error(error.message); + console.error(error); + } finally { + setIsLoading(false); + } + }; + + return ( + + + + + +
+ + Add new project + + Enter the name of the new project and a channel will be created + automatically. + + +
+
+ + setProjectName(e.target.value)} + required + disabled={isLoading} + /> +
+
+ + + +
+
+
+ ); +} diff --git a/apps/www/src/components/buttons/AddPropertyButton.tsx b/apps/www/src/components/buttons/AddPropertyButton.tsx new file mode 100644 index 0000000..d89a307 --- /dev/null +++ b/apps/www/src/components/buttons/AddPropertyButton.tsx @@ -0,0 +1,120 @@ +"use client"; + +import { useState } from "react"; +import { useRouter } from "next/navigation"; + +import { Button } from "@dingify/ui/components/button"; +import { + Dialog, + DialogContent, + DialogDescription, + DialogFooter, + DialogHeader, + DialogTitle, + DialogTrigger, +} from "@dingify/ui/components/dialog"; +import { Input } from "@dingify/ui/components/input"; +import { Label } from "@dingify/ui/components/label"; +import { + Select, + SelectContent, + SelectItem, + SelectTrigger, + SelectValue, +} from "@dingify/ui/components/select"; + +export function AddPropertyButton() { + const [address, setAddress] = useState(""); + const [propertyType, setPropertyType] = useState(""); + const [isLoading, setIsLoading] = useState(false); + const router = useRouter(); + + const handleSubmit = async (event) => { + event.preventDefault(); + setIsLoading(true); + + try { + const response = await fetch("/api/property/addproperty", { + method: "POST", + headers: { + "Content-Type": "application/json", + }, + body: JSON.stringify({ address, type: propertyType }), // Include propertyType in the request + }); + + if (!response.ok) { + throw new Error("Failed to add property"); + } + + const newProperty = await response.json(); + // toast.success('Property added successfully!'); + router.push(`/property/${newProperty.id}`); // Update with the correct path to view the property + } catch (error) { + // toast.error('Error adding property. Please try again.'); + console.error(error); + } finally { + setIsLoading(false); + } + }; + + return ( + + + + + +
+ + Add new property + + Write in the street address and let us make your job easier. + + +
+
+ + setAddress(e.target.value)} + required + disabled={isLoading} + /> +
+
+ + +
+
+ + + +
+
+
+ ); +} diff --git a/apps/www/src/components/buttons/CreatEventButton.tsx b/apps/www/src/components/buttons/CreatEventButton.tsx new file mode 100644 index 0000000..7b6769f --- /dev/null +++ b/apps/www/src/components/buttons/CreatEventButton.tsx @@ -0,0 +1,164 @@ +"use client"; + +import { useEffect, useState } from "react"; +import { createEvent } from "@/actions/create-event"; // Import the createEvent action +import { getUserData } from "@/actions/get-user-details"; +import { CopyIcon } from "@radix-ui/react-icons"; +import { CopyToClipboard } from "react-copy-to-clipboard"; +import { Light as SyntaxHighlighter } from "react-syntax-highlighter"; +import json from "react-syntax-highlighter/dist/esm/languages/hljs/json"; +import { dracula } from "react-syntax-highlighter/dist/esm/styles/hljs"; +import { toast } from "sonner"; // Import toast from sonner + +import { Button } from "@dingify/ui/components/button"; +import { + Dialog, + DialogContent, + DialogDescription, + DialogFooter, + DialogHeader, + DialogTitle, + DialogTrigger, +} from "@dingify/ui/components/dialog"; + +import { Confetti } from "../ui/confetti"; + +SyntaxHighlighter.registerLanguage("json", json); + +const handleClick = () => { + const duration = 2.5 * 1000; + const animationEnd = Date.now() + duration; + const defaults = { startVelocity: 30, spread: 360, ticks: 60, zIndex: 0 }; + + const randomInRange = (min, max) => Math.random() * (max - min) + min; + + const interval = window.setInterval(() => { + const timeLeft = animationEnd - Date.now(); + + if (timeLeft <= 0) { + return clearInterval(interval); + } + + const particleCount = 50 * (timeLeft / duration); + Confetti({ + ...defaults, + particleCount, + origin: { x: randomInRange(0.1, 0.3), y: Math.random() - 0.2 }, + }); + Confetti({ + ...defaults, + particleCount, + origin: { x: randomInRange(0.7, 0.9), y: Math.random() - 0.2 }, + }); + }, 250); +}; + +export function CreateEventButton() { + const [isLoading, setIsLoading] = useState(false); + const [copied, setCopied] = useState(false); + const [isOpen, setIsOpen] = useState(false); + const [apiKey, setApiKey] = useState(""); + + useEffect(() => { + async function fetchUserData() { + try { + const data = await getUserData(); + setApiKey(data.apiKey as string); + } catch (error) { + console.error("Failed to fetch user data", error); + } + } + + fetchUserData(); + }, []); + + const handleButtonClick = async (event) => { + event.preventDefault(); + setIsLoading(true); + + // Hardcoded event data for now; modify this to collect data from a form if needed + const eventData = { + channel: "new-channel-name", + name: "New-payment", + user_id: "user-123", + icon: "๐Ÿคฉ", + notify: true, + }; + + try { + await createEvent(eventData); // Call the createEvent action with event data + handleClick(); + setIsOpen(false); // Close the dialog after the event is created + } catch (error) { + console.error("Error creating event", error); + } finally { + setIsLoading(false); + } + }; + + const handleCopy = () => { + setCopied(true); + toast.success("cURL command copied to clipboard."); + }; + + const curlCommand = ` + curl -X POST https://api.dingify.workers.dev/api/events \\ + -H "Content-Type: application/json" \\ + -H "x-api-key: ${apiKey}" \\ + -d '{ + "channel": "new-channel-name", + "name": "New-payment", + "userId": "user-123", + "icon": "๐Ÿคฉ", + "notify": true, + "tags": { + "plan": "premium", + "cycle": "monthly" + } + }' + `; + + return ( + <> + + + + + Create Event + + Post this into your terminal to create a new event or press the + button. + + +
+ + {curlCommand} + + + + +
+
+ + + +
+
+
+ + ); +} diff --git a/apps/www/src/components/buttons/DocsButton.tsx b/apps/www/src/components/buttons/DocsButton.tsx new file mode 100644 index 0000000..91dca83 --- /dev/null +++ b/apps/www/src/components/buttons/DocsButton.tsx @@ -0,0 +1,16 @@ +import Link from "next/link"; + +import { buttonVariants } from "@dingify/ui/components/button"; + +import { cn } from "@/lib/utils"; + +export function DocsButton() { + return ( + + Explore Docs + + ); +} diff --git a/apps/www/src/components/buttons/GenerateDescriptionButton2.tsx b/apps/www/src/components/buttons/GenerateDescriptionButton2.tsx new file mode 100644 index 0000000..731074b --- /dev/null +++ b/apps/www/src/components/buttons/GenerateDescriptionButton2.tsx @@ -0,0 +1,53 @@ +import { useState } from "react"; +import { generateDescription } from "@/actions/generate-description"; +import { updatePropertyDescription } from "@/actions/update-property-description"; +import { updatePropertyStatus } from "@/actions/update-property-status"; +import { Loader2 as Spinner } from "lucide-react"; + +import { Button } from "@dingify/ui/components/button"; + +const GenerateDescriptionButton2 = ({ propertyId, onDescriptionGenerated }) => { + const [isLoading, setIsLoading] = useState(false); + + async function handleGenerateDescription() { + console.log("Generating description..."); // Log when the process starts + setIsLoading(true); + try { + const description = await generateDescription(propertyId); + console.log("Generated description:", description); + onDescriptionGenerated(description); + + // Update the property description + const updateproperty = await updatePropertyDescription( + propertyId, + description + ); + + // If description update is successful, update the status to DONE + if (updateproperty.success) { + const statusUpdateResult = await updatePropertyStatus( + propertyId, + "DONE" + ); + console.log("Status updated to DONE:", statusUpdateResult); + } + } catch (error) { + console.error("Error generating description:", error); + } + setIsLoading(false); + } + + return ( + + ); +}; + +export default GenerateDescriptionButton2; diff --git a/apps/www/src/components/buttons/GenerateDescriptionsButton.tsx b/apps/www/src/components/buttons/GenerateDescriptionsButton.tsx new file mode 100644 index 0000000..0a022ce --- /dev/null +++ b/apps/www/src/components/buttons/GenerateDescriptionsButton.tsx @@ -0,0 +1,27 @@ +"use client"; + +import React from "react"; +import { generateDescription } from "@/actions/generate-description"; + +import { Button } from "@dingify/ui/components/button"; + +const GenerateDescriptionButton = ({ propertyId }) => { + async function handleGenerateDescription() { + try { + // Replace this with the actual API call to your server function + const description = await generateDescription(propertyId); + console.log("Generated Property Description:", description); + + const descriptionObject = JSON.parse(description); + console.log("Generated Property Description:", descriptionObject); + } catch (error) { + console.error("Error generating description:", error); + } + } + + return ( + + ); +}; + +export default GenerateDescriptionButton; diff --git a/apps/www/src/components/buttons/GetStartedButton.tsx b/apps/www/src/components/buttons/GetStartedButton.tsx new file mode 100644 index 0000000..ddfed8b --- /dev/null +++ b/apps/www/src/components/buttons/GetStartedButton.tsx @@ -0,0 +1,38 @@ +"use client"; + +import { useRouter } from "next/navigation"; +import { ArrowRightIcon } from "@radix-ui/react-icons"; +import { useSession } from "next-auth/react"; + +import { Button, buttonVariants } from "@dingify/ui/components/button"; + +import { cn } from "@/lib/utils"; +import { useSigninModal } from "@/hooks/use-signin-modal"; + +export function GetStartedButton() { + const signInModal = useSigninModal(); + const { data: session } = useSession(); + const router = useRouter(); + + const handleClick = () => { + if (!session) { + signInModal.onOpen(); + return; + } + + router.push("/dashboard"); + }; + + return ( + + ); +} diff --git a/apps/www/src/components/buttons/LanguageButton.tsx b/apps/www/src/components/buttons/LanguageButton.tsx new file mode 100644 index 0000000..0bb075d --- /dev/null +++ b/apps/www/src/components/buttons/LanguageButton.tsx @@ -0,0 +1,20 @@ +"use client"; + +import { useLanguageModal } from "@/hooks/use-language-modal"; +import { useSigninModal } from "@/hooks/use-signin-modal"; +import { cn } from "@/lib/utils"; + +import { Button, buttonVariants } from "@dingify/ui/components/button"; + +export function LanugageButton({ userId }) { + const signInModal = useLanguageModal(); + + return ( + + ); +} diff --git a/apps/www/src/components/buttons/SubmitProperty.tsx b/apps/www/src/components/buttons/SubmitProperty.tsx new file mode 100644 index 0000000..e8dcb39 --- /dev/null +++ b/apps/www/src/components/buttons/SubmitProperty.tsx @@ -0,0 +1,37 @@ +import Link from "next/link"; + +import { Button } from "@dingify/ui/components/button"; +import { + Dialog, + DialogContent, + DialogDescription, + DialogFooter, + DialogHeader, + DialogTitle, + DialogTrigger, +} from "@dingify/ui/components/dialog"; +import { Input } from "@dingify/ui/components/input"; +import { Label } from "@dingify/ui/components/label"; + +export function SubmitProperty() { + return ( + + + + + + + Do you want to submit your property? + + Lets send this to your provider (Finn.no) + + + + + + + + + + ); +} diff --git a/apps/www/src/components/buttons/ViewDetailsButton.tsx b/apps/www/src/components/buttons/ViewDetailsButton.tsx new file mode 100644 index 0000000..d822fd4 --- /dev/null +++ b/apps/www/src/components/buttons/ViewDetailsButton.tsx @@ -0,0 +1,91 @@ +"use client"; + +import { BellIcon, InfoIcon } from "lucide-react"; + +import { Button } from "@dingify/ui/components/button"; +import { + Card, + CardContent, + CardDescription, + CardHeader, + CardTitle, +} from "@dingify/ui/components/card"; +import { + Dialog, + DialogContent, + DialogDescription, + DialogFooter, + DialogHeader, + DialogTrigger, +} from "@dingify/ui/components/dialog"; + +export function ViewDetailsButton({ event }) { + return ( + + + + + + + + + +
+ Event Notification + + Real-time alert for your team + +
+
+ +
+
+

+ Event Type +

+

{event?.name}

+
+
+

+ Channel +

+

+ {event?.channel?.name || "No Channel"} +

+
+
+
+
+

+ Project +

+

+ {event?.channel?.project?.name || "No Project"} +

+
+
+

+ User +

+

{event?.userId}

+
+
+
+

+ Description +

+

{event?.description || "No Description"}

+
+
+
+
+ +
+
+ ); +} diff --git a/apps/www/src/components/channels/ChannelCard.tsx b/apps/www/src/components/channels/ChannelCard.tsx new file mode 100644 index 0000000..e439fb1 --- /dev/null +++ b/apps/www/src/components/channels/ChannelCard.tsx @@ -0,0 +1,112 @@ +"use client"; + +import { useRouter } from "next/navigation"; +import { deleteEvent } from "@/actions/delete-event"; +import { + ChevronDownIcon, + CircleIcon, + PlusIcon, + StarIcon, +} from "@radix-ui/react-icons"; +import { format } from "date-fns"; +import { BellIcon, BellOffIcon, Tag, TrashIcon } from "lucide-react"; +import { toast } from "sonner"; + +import { Badge } from "@dingify/ui/components/badge"; +import { Button } from "@dingify/ui/components/button"; +import { + Card, + CardContent, + CardDescription, + CardHeader, + CardTitle, +} from "@dingify/ui/components/card"; +import { + DropdownMenu, + DropdownMenuContent, + DropdownMenuItem, + DropdownMenuLabel, + DropdownMenuSeparator, + DropdownMenuTrigger, +} from "@dingify/ui/components/dropdown-menu"; +import { Separator } from "@dingify/ui/components/separator"; + +export function ChannelCard({ channelDetails }) { + const router = useRouter(); + + const handleDelete = async (eventId) => { + try { + await deleteEvent(eventId); + toast.success("The event has been deleted successfully."); + router.refresh(); + } catch (error) { + toast.error("There was an error deleting the event."); + console.error("Error deleting event:", error); + } + }; + + return ( +
+ {channelDetails.events.map((event) => ( + + +
+ + {event.name} {event.icon} + + {event.userId} +
+
+ + + + + + + + Actions + + handleDelete(event.id)}> + + Delete + + + + Placeholder + + + +
+
+ +
+
+ + Placeholder +
+
+ + Placeholder +
+
{format(new Date(event.createdAt), "dd.MM.yyyy HH:mm")}
+
+
+
+ ))} +
+ ); +} diff --git a/apps/www/src/components/channels/ChannelCard2.tsx b/apps/www/src/components/channels/ChannelCard2.tsx new file mode 100644 index 0000000..3be086b --- /dev/null +++ b/apps/www/src/components/channels/ChannelCard2.tsx @@ -0,0 +1,91 @@ +import { + ChevronDownIcon, + CircleIcon, + PlusIcon, + StarIcon, +} from "@radix-ui/react-icons"; + +import { Button } from "@dingify/ui/components/button"; +import { + Card, + CardContent, + CardDescription, + CardHeader, + CardTitle, +} from "@dingify/ui/components/card"; +import { + DropdownMenu, + DropdownMenuCheckboxItem, + DropdownMenuContent, + DropdownMenuItem, + DropdownMenuLabel, + DropdownMenuSeparator, + DropdownMenuTrigger, +} from "@dingify/ui/components/dropdown-menu"; +import { Separator } from "@dingify/ui/components/separator"; + +export function ChannelCard2({ channelDetails }) { + return ( +
+ {channelDetails.events.map((event) => ( + + +
+ {event.name} + + Created At: {new Date(event.createdAt).toLocaleDateString()} + +
+
+ + + + + + + + Suggested Lists + + + Future Ideas + + My Stack + + Inspiration + + + + Create List + + + +
+
+ +
+
+ + TypeScript +
+
+ + 20k +
+
Updated April 2023
+
+
+
+ ))} +
+ ); +} diff --git a/apps/www/src/components/content/mdx-card.tsx b/apps/www/src/components/content/mdx-card.tsx new file mode 100644 index 0000000..5ec0ac6 --- /dev/null +++ b/apps/www/src/components/content/mdx-card.tsx @@ -0,0 +1,37 @@ +import Link from "next/link"; +import { cn } from "@/lib/utils"; + +interface CardProps extends React.HTMLAttributes { + href?: string; + disabled?: boolean; +} + +export function MdxCard({ + href, + className, + children, + disabled, + ...props +}: CardProps) { + return ( +
+
+
+ {children} +
+
+ {href && ( + + View + + )} +
+ ); +} diff --git a/apps/www/src/components/content/mdx-components.tsx b/apps/www/src/components/content/mdx-components.tsx new file mode 100644 index 0000000..e3173ad --- /dev/null +++ b/apps/www/src/components/content/mdx-components.tsx @@ -0,0 +1,168 @@ +import type { ImageProps } from "next/image"; +import * as React from "react"; +import NextImage from "next/image"; +import { MdxCard } from "@/components/content/mdx-card"; +import { Callout } from "@/components/shared/callout"; +import { cn } from "@/lib/utils"; +import { useMDXComponent } from "next-contentlayer/hooks"; + +const components = { + h1: ({ className, ...props }) => ( +

+ ), + h2: ({ className, ...props }) => ( +

+ ), + h3: ({ className, ...props }) => ( +

+ ), + h4: ({ className, ...props }) => ( +

+ ), + h5: ({ className, ...props }) => ( +

+ ), + h6: ({ className, ...props }) => ( +
+ ), + a: ({ className, ...props }) => ( + + ), + p: ({ className, ...props }) => ( +

+ ), + ul: ({ className, ...props }) => ( +

    + ), + ol: ({ className, ...props }) => ( +
      + ), + li: ({ className, ...props }) => ( +
    1. + ), + blockquote: ({ className, ...props }) => ( +
      *]:text-muted-foreground", + className + )} + {...props} + /> + ), + img: ({ + className, + alt, + ...props + }: React.ImgHTMLAttributes) => ( + // eslint-disable-next-line @next/next/no-img-element + {alt} + ), + hr: ({ ...props }) =>
      , + table: ({ className, ...props }: React.HTMLAttributes) => ( +
      + + + ), + tr: ({ className, ...props }: React.HTMLAttributes) => ( + + ), + th: ({ className, ...props }) => ( +
      + ), + td: ({ className, ...props }) => ( + + ), + pre: ({ className, ...props }) => ( +
      +  ),
      +  code: ({ className, ...props }) => (
      +    
      +  ),
      +  Image: (props: ImageProps) => ,
      +  Callout,
      +  Card: MdxCard,
      +};
      +
      +interface MdxProps {
      +  code: string;
      +}
      +
      +export function Mdx({ code }: MdxProps) {
      +  const Component = useMDXComponent(code);
      +
      +  return (
      +    
      + {/* @ts-expect-error */} + +
      + ); +} diff --git a/apps/www/src/components/content/templete-blog/deploying-next-apps.mdx b/apps/www/src/components/content/templete-blog/deploying-next-apps.mdx new file mode 100644 index 0000000..2599430 --- /dev/null +++ b/apps/www/src/components/content/templete-blog/deploying-next-apps.mdx @@ -0,0 +1,219 @@ +--- +title: Deploying Next.js Apps +description: How to deploy your Next.js apps on Vercel. +image: /images/blog/blog-post-3.jpg +date: "2023-01-02" +authors: + - shadcn +--- + + + The text below is from the [Tailwind + CSS](https://play.tailwindcss.com/uj1vGACRJA?layout=preview) docs. I copied it + here to test the markdown styles. **Tailwind is awesome. You should use it.** + + +Until now, trying to style an article, document, or blog post with Tailwind has been a tedious task that required a keen eye for typography and a lot of complex custom CSS. + +By default, Tailwind removes all of the default browser styling from paragraphs, headings, lists and more. This ends up being really useful for building application UIs because you spend less time undoing user-agent styles, but when you _really are_ just trying to style some content that came from a rich-text editor in a CMS or a markdown file, it can be surprising and unintuitive. + +We get lots of complaints about it actually, with people regularly asking us things like: + +> Why is Tailwind removing the default styles on my `h1` elements? How do I disable this? What do you mean I lose all the other base styles too? +> We hear you, but we're not convinced that simply disabling our base styles is what you really want. You don't want to have to remove annoying margins every time you use a `p` element in a piece of your dashboard UI. And I doubt you really want your blog posts to use the user-agent styles either โ€” you want them to look _awesome_, not awful. + +The `@tailwindcss/typography` plugin is our attempt to give you what you _actually_ want, without any of the downsides of doing something stupid like disabling our base styles. + +It adds a new `prose` class that you can slap on any block of vanilla HTML content and turn it into a beautiful, well-formatted document: + +```html +
      +

      Garlic bread with cheese: What the science tells us

      +

      + For years parents have espoused the health benefits of eating garlic bread + with cheese to their children, with the food earning such an iconic status + in our culture that kids will often dress up as warm, cheesy loaf for + Halloween. +

      +

      + But a recent study shows that the celebrated appetizer may be linked to a + series of rabies cases springing up around the country. +

      +
      +``` + +For more information about how to use the plugin and the features it includes, [read the documentation](https://github.com/tailwindcss/typography/blob/master/README.md). + +--- + +## What to expect from here on out + +What follows from here is just a bunch of absolute nonsense I've written to dogfood the plugin itself. It includes every sensible typographic element I could think of, like **bold text**, unordered lists, ordered lists, code blocks, block quotes, _and even italics_. + +It's important to cover all of these use cases for a few reasons: + +1. We want everything to look good out of the box. +2. Really just the first reason, that's the whole point of the plugin. +3. Here's a third pretend reason though a list with three items looks more realistic than a list with two items. + +Now we're going to try out another header style. + +### Typography should be easy + +So that's a header for you โ€” with any luck if we've done our job correctly that will look pretty reasonable. + +Something a wise person once told me about typography is: + +> Typography is pretty important if you don't want your stuff to look like trash. Make it good then it won't be bad. + +It's probably important that images look okay here by default as well: + +Image + +Contrary to popular belief, Lorem Ipsum is not simply random text. It has roots in a piece of classical Latin literature from 45 BC, making it over 2000 years old. + +Now I'm going to show you an example of an unordered list to make sure that looks good, too: + +- So here is the first item in this list. +- In this example we're keeping the items short. +- Later, we'll use longer, more complex list items. + +And that's the end of this section. + +## What if we stack headings? + +### We should make sure that looks good, too. + +Sometimes you have headings directly underneath each other. In those cases you often have to undo the top margin on the second heading because it usually looks better for the headings to be closer together than a paragraph followed by a heading should be. + +### When a heading comes after a paragraph โ€ฆ + +When a heading comes after a paragraph, we need a bit more space, like I already mentioned above. Now let's see what a more complex list would look like. + +- **I often do this thing where list items have headings.** + + For some reason I think this looks cool which is unfortunate because it's pretty annoying to get the styles right. + + I often have two or three paragraphs in these list items, too, so the hard part is getting the spacing between the paragraphs, list item heading, and separate list items to all make sense. Pretty tough honestly, you could make a strong argument that you just shouldn't write this way. + +- **Since this is a list, I need at least two items.** + + I explained what I'm doing already in the previous list item, but a list wouldn't be a list if it only had one item, and we really want this to look realistic. That's why I've added this second list item so I actually have something to look at when writing the styles. + +- **It's not a bad idea to add a third item either.** + + I think it probably would've been fine to just use two items but three is definitely not worse, and since I seem to be having no trouble making up arbitrary things to type, I might as well include it. + +After this sort of list I usually have a closing statement or paragraph, because it kinda looks weird jumping right to a heading. + +## Code should look okay by default. + +I think most people are going to use [highlight.js](https://highlightjs.org/) or [Prism](https://prismjs.com/) or something if they want to style their code blocks but it wouldn't hurt to make them look _okay_ out of the box, even with no syntax highlighting. + +Here's what a default `tailwind.config.js` file looks like at the time of writing: + +```js +module.exports = { + purge: [], + theme: { + extend: {}, + }, + variants: {}, + plugins: [], +}; +``` + +Hopefully that looks good enough to you. + +### What about nested lists? + +Nested lists basically always look bad which is why editors like Medium don't even let you do it, but I guess since some of you goofballs are going to do it we have to carry the burden of at least making it work. + +1. **Nested lists are rarely a good idea.** + - You might feel like you are being really "organized" or something but you are just creating a gross shape on the screen that is hard to read. + - Nested navigation in UIs is a bad idea too, keep things as flat as possible. + - Nesting tons of folders in your source code is also not helpful. +2. **Since we need to have more items, here's another one.** + - I'm not sure if we'll bother styling more than two levels deep. + - Two is already too much, three is guaranteed to be a bad idea. + - If you nest four levels deep you belong in prison. +3. **Two items isn't really a list, three is good though.** + - Again please don't nest lists if you want people to actually read your content. + - Nobody wants to look at this. + - I'm upset that we even have to bother styling this. + +The most annoying thing about lists in Markdown is that `
    2. ` elements aren't given a child `

      ` tag unless there are multiple paragraphs in the list item. That means I have to worry about styling that annoying situation too. + +- **For example, here's another nested list.** + + But this time with a second paragraph. + + - These list items won't have `

      ` tags + - Because they are only one line each + +- **But in this second top-level list item, they will.** + + This is especially annoying because of the spacing on this paragraph. + + - As you can see here, because I've added a second line, this list item now has a `

      ` tag. + + This is the second line I'm talking about by the way. + + - Finally here's another list item so it's more like a list. + +- A closing list item, but with no nested list, because why not? + +And finally a sentence to close off this section. + +## There are other elements we need to style + +I almost forgot to mention links, like [this link to the Tailwind CSS website](https://tailwindcss.com). We almost made them blue but that's so yesterday, so we went with dark gray, feels edgier. + +We even included table styles, check it out: + +| Wrestler | Origin | Finisher | +| ----------------------- | ------------ | ------------------ | +| Bret "The Hitman" Hart | Calgary, AB | Sharpshooter | +| Stone Cold Steve Austin | Austin, TX | Stone Cold Stunner | +| Randy Savage | Sarasota, FL | Elbow Drop | +| Vader | Boulder, CO | Vader Bomb | +| Razor Ramon | Chuluota, FL | Razor's Edge | + +We also need to make sure inline code looks good, like if I wanted to talk about `` elements or tell you the good news about `@tailwindcss/typography`. + +### Sometimes I even use `code` in headings + +Even though it's probably a bad idea, and historically I've had a hard time making it look good. This _"wrap the code blocks in backticks"_ trick works pretty well though really. + +Another thing I've done in the past is put a `code` tag inside of a link, like if I wanted to tell you about the [`tailwindcss/docs`](https://github.com/tailwindcss/docs) repository. I don't love that there is an underline below the backticks but it is absolutely not worth the madness it would require to avoid it. + +#### We haven't used an `h4` yet + +But now we have. Please don't use `h5` or `h6` in your content, Medium only supports two heading levels for a reason, you animals. I honestly considered using a `before` pseudo-element to scream at you if you use an `h5` or `h6`. + +We don't style them at all out of the box because `h4` elements are already so small that they are the same size as the body copy. What are we supposed to do with an `h5`, make it _smaller_ than the body copy? No thanks. + +### We still need to think about stacked headings though. + +#### Let's make sure we don't screw that up with `h4` elements, either. + +Phew, with any luck we have styled the headings above this text and they look pretty good. + +Let's add a closing paragraph here so things end with a decently sized block of text. I can't explain why I want things to end that way but I have to assume it's because I think things will look weird or unbalanced if there is a heading too close to the end of the document. + +What I've written here is probably long enough, but adding this final sentence can't hurt. + +## GitHub Flavored Markdown + +I've also added support for GitHub Flavored Mardown using `remark-gfm`. + +With `remark-gfm`, we get a few extra features in our markdown. Example: autolink literals. + +A link like www.example.com or https://example.com would automatically be converted into an `a` tag. + +This works for email links too: contact@example.com. diff --git a/apps/www/src/components/content/templete-blog/dynamic-routing-static-regeneration copy.mdx b/apps/www/src/components/content/templete-blog/dynamic-routing-static-regeneration copy.mdx new file mode 100644 index 0000000..5a0ac70 --- /dev/null +++ b/apps/www/src/components/content/templete-blog/dynamic-routing-static-regeneration copy.mdx @@ -0,0 +1,219 @@ +--- +title: Dynamic Routing and Static Regeneration +description: How to use incremental static regeneration using dynamic routes. +image: /images/blog/blog-post-2.jpg +date: "2023-03-04" +authors: + - codehagen +--- + + + The text below is from the [Tailwind + CSS](https://play.tailwindcss.com/uj1vGACRJA?layout=preview) docs. I copied it + here to test the markdown styles. **Tailwind is awesome. You should use it.** + + +Until now, trying to style an article, document, or blog post with Tailwind has been a tedious task that required a keen eye for typography and a lot of complex custom CSS. + +By default, Tailwind removes all of the default browser styling from paragraphs, headings, lists and more. This ends up being really useful for building application UIs because you spend less time undoing user-agent styles, but when you _really are_ just trying to style some content that came from a rich-text editor in a CMS or a markdown file, it can be surprising and unintuitive. + +We get lots of complaints about it actually, with people regularly asking us things like: + +> Why is Tailwind removing the default styles on my `h1` elements? How do I disable this? What do you mean I lose all the other base styles too? +> We hear you, but we're not convinced that simply disabling our base styles is what you really want. You don't want to have to remove annoying margins every time you use a `p` element in a piece of your dashboard UI. And I doubt you really want your blog posts to use the user-agent styles either โ€” you want them to look _awesome_, not awful. + +The `@tailwindcss/typography` plugin is our attempt to give you what you _actually_ want, without any of the downsides of doing something stupid like disabling our base styles. + +It adds a new `prose` class that you can slap on any block of vanilla HTML content and turn it into a beautiful, well-formatted document: + +```html +

      +

      Garlic bread with cheese: What the science tells us

      +

      + For years parents have espoused the health benefits of eating garlic bread + with cheese to their children, with the food earning such an iconic status + in our culture that kids will often dress up as warm, cheesy loaf for + Halloween. +

      +

      + But a recent study shows that the celebrated appetizer may be linked to a + series of rabies cases springing up around the country. +

      +
      +``` + +For more information about how to use the plugin and the features it includes, [read the documentation](https://github.com/tailwindcss/typography/blob/master/README.md). + +--- + +## What to expect from here on out + +What follows from here is just a bunch of absolute nonsense I've written to dogfood the plugin itself. It includes every sensible typographic element I could think of, like **bold text**, unordered lists, ordered lists, code blocks, block quotes, _and even italics_. + +It's important to cover all of these use cases for a few reasons: + +1. We want everything to look good out of the box. +2. Really just the first reason, that's the whole point of the plugin. +3. Here's a third pretend reason though a list with three items looks more realistic than a list with two items. + +Now we're going to try out another header style. + +### Typography should be easy + +So that's a header for you โ€” with any luck if we've done our job correctly that will look pretty reasonable. + +Something a wise person once told me about typography is: + +> Typography is pretty important if you don't want your stuff to look like trash. Make it good then it won't be bad. + +It's probably important that images look okay here by default as well: + +Image + +Contrary to popular belief, Lorem Ipsum is not simply random text. It has roots in a piece of classical Latin literature from 45 BC, making it over 2000 years old. + +Now I'm going to show you an example of an unordered list to make sure that looks good, too: + +- So here is the first item in this list. +- In this example we're keeping the items short. +- Later, we'll use longer, more complex list items. + +And that's the end of this section. + +## What if we stack headings? + +### We should make sure that looks good, too. + +Sometimes you have headings directly underneath each other. In those cases you often have to undo the top margin on the second heading because it usually looks better for the headings to be closer together than a paragraph followed by a heading should be. + +### When a heading comes after a paragraph โ€ฆ + +When a heading comes after a paragraph, we need a bit more space, like I already mentioned above. Now let's see what a more complex list would look like. + +- **I often do this thing where list items have headings.** + + For some reason I think this looks cool which is unfortunate because it's pretty annoying to get the styles right. + + I often have two or three paragraphs in these list items, too, so the hard part is getting the spacing between the paragraphs, list item heading, and separate list items to all make sense. Pretty tough honestly, you could make a strong argument that you just shouldn't write this way. + +- **Since this is a list, I need at least two items.** + + I explained what I'm doing already in the previous list item, but a list wouldn't be a list if it only had one item, and we really want this to look realistic. That's why I've added this second list item so I actually have something to look at when writing the styles. + +- **It's not a bad idea to add a third item either.** + + I think it probably would've been fine to just use two items but three is definitely not worse, and since I seem to be having no trouble making up arbitrary things to type, I might as well include it. + +After this sort of list I usually have a closing statement or paragraph, because it kinda looks weird jumping right to a heading. + +## Code should look okay by default. + +I think most people are going to use [highlight.js](https://highlightjs.org/) or [Prism](https://prismjs.com/) or something if they want to style their code blocks but it wouldn't hurt to make them look _okay_ out of the box, even with no syntax highlighting. + +Here's what a default `tailwind.config.js` file looks like at the time of writing: + +```js +module.exports = { + purge: [], + theme: { + extend: {}, + }, + variants: {}, + plugins: [], +}; +``` + +Hopefully that looks good enough to you. + +### What about nested lists? + +Nested lists basically always look bad which is why editors like Medium don't even let you do it, but I guess since some of you goofballs are going to do it we have to carry the burden of at least making it work. + +1. **Nested lists are rarely a good idea.** + - You might feel like you are being really "organized" or something but you are just creating a gross shape on the screen that is hard to read. + - Nested navigation in UIs is a bad idea too, keep things as flat as possible. + - Nesting tons of folders in your source code is also not helpful. +2. **Since we need to have more items, here's another one.** + - I'm not sure if we'll bother styling more than two levels deep. + - Two is already too much, three is guaranteed to be a bad idea. + - If you nest four levels deep you belong in prison. +3. **Two items isn't really a list, three is good though.** + - Again please don't nest lists if you want people to actually read your content. + - Nobody wants to look at this. + - I'm upset that we even have to bother styling this. + +The most annoying thing about lists in Markdown is that `
    3. ` elements aren't given a child `

      ` tag unless there are multiple paragraphs in the list item. That means I have to worry about styling that annoying situation too. + +- **For example, here's another nested list.** + + But this time with a second paragraph. + + - These list items won't have `

      ` tags + - Because they are only one line each + +- **But in this second top-level list item, they will.** + + This is especially annoying because of the spacing on this paragraph. + + - As you can see here, because I've added a second line, this list item now has a `

      ` tag. + + This is the second line I'm talking about by the way. + + - Finally here's another list item so it's more like a list. + +- A closing list item, but with no nested list, because why not? + +And finally a sentence to close off this section. + +## There are other elements we need to style + +I almost forgot to mention links, like [this link to the Tailwind CSS website](https://tailwindcss.com). We almost made them blue but that's so yesterday, so we went with dark gray, feels edgier. + +We even included table styles, check it out: + +| Wrestler | Origin | Finisher | +| ----------------------- | ------------ | ------------------ | +| Bret "The Hitman" Hart | Calgary, AB | Sharpshooter | +| Stone Cold Steve Austin | Austin, TX | Stone Cold Stunner | +| Randy Savage | Sarasota, FL | Elbow Drop | +| Vader | Boulder, CO | Vader Bomb | +| Razor Ramon | Chuluota, FL | Razor's Edge | + +We also need to make sure inline code looks good, like if I wanted to talk about `` elements or tell you the good news about `@tailwindcss/typography`. + +### Sometimes I even use `code` in headings + +Even though it's probably a bad idea, and historically I've had a hard time making it look good. This _"wrap the code blocks in backticks"_ trick works pretty well though really. + +Another thing I've done in the past is put a `code` tag inside of a link, like if I wanted to tell you about the [`tailwindcss/docs`](https://github.com/tailwindcss/docs) repository. I don't love that there is an underline below the backticks but it is absolutely not worth the madness it would require to avoid it. + +#### We haven't used an `h4` yet + +But now we have. Please don't use `h5` or `h6` in your content, Medium only supports two heading levels for a reason, you animals. I honestly considered using a `before` pseudo-element to scream at you if you use an `h5` or `h6`. + +We don't style them at all out of the box because `h4` elements are already so small that they are the same size as the body copy. What are we supposed to do with an `h5`, make it _smaller_ than the body copy? No thanks. + +### We still need to think about stacked headings though. + +#### Let's make sure we don't screw that up with `h4` elements, either. + +Phew, with any luck we have styled the headings above this text and they look pretty good. + +Let's add a closing paragraph here so things end with a decently sized block of text. I can't explain why I want things to end that way but I have to assume it's because I think things will look weird or unbalanced if there is a heading too close to the end of the document. + +What I've written here is probably long enough, but adding this final sentence can't hurt. + +## GitHub Flavored Markdown + +I've also added support for GitHub Flavored Mardown using `remark-gfm`. + +With `remark-gfm`, we get a few extra features in our markdown. Example: autolink literals. + +A link like www.example.com or https://example.com would automatically be converted into an `a` tag. + +This works for email links too: contact@example.com. diff --git a/apps/www/src/components/content/templete-blog/preview-mode-headless-cms.mdx b/apps/www/src/components/content/templete-blog/preview-mode-headless-cms.mdx new file mode 100644 index 0000000..e90e247 --- /dev/null +++ b/apps/www/src/components/content/templete-blog/preview-mode-headless-cms.mdx @@ -0,0 +1,219 @@ +--- +title: Preview Mode for Headless CMS +description: How to implement preview mode in your headless CMS. +date: "2023-04-09" +image: /images/blog/blog-post-1.jpg +authors: + - shadcn +--- + + + The text below is from the [Tailwind + CSS](https://play.tailwindcss.com/uj1vGACRJA?layout=preview) docs. I copied it + here to test the markdown styles. **Tailwind is awesome. You should use it.** + + +Until now, trying to style an article, document, or blog post with Tailwind has been a tedious task that required a keen eye for typography and a lot of complex custom CSS. + +By default, Tailwind removes all of the default browser styling from paragraphs, headings, lists and more. This ends up being really useful for building application UIs because you spend less time undoing user-agent styles, but when you _really are_ just trying to style some content that came from a rich-text editor in a CMS or a markdown file, it can be surprising and unintuitive. + +We get lots of complaints about it actually, with people regularly asking us things like: + +> Why is Tailwind removing the default styles on my `h1` elements? How do I disable this? What do you mean I lose all the other base styles too? +> We hear you, but we're not convinced that simply disabling our base styles is what you really want. You don't want to have to remove annoying margins every time you use a `p` element in a piece of your dashboard UI. And I doubt you really want your blog posts to use the user-agent styles either โ€” you want them to look _awesome_, not awful. + +The `@tailwindcss/typography` plugin is our attempt to give you what you _actually_ want, without any of the downsides of doing something stupid like disabling our base styles. + +It adds a new `prose` class that you can slap on any block of vanilla HTML content and turn it into a beautiful, well-formatted document: + +```html +

      +

      Garlic bread with cheese: What the science tells us

      +

      + For years parents have espoused the health benefits of eating garlic bread + with cheese to their children, with the food earning such an iconic status + in our culture that kids will often dress up as warm, cheesy loaf for + Halloween. +

      +

      + But a recent study shows that the celebrated appetizer may be linked to a + series of rabies cases springing up around the country. +

      +
      +``` + +For more information about how to use the plugin and the features it includes, [read the documentation](https://github.com/tailwindcss/typography/blob/master/README.md). + +--- + +## What to expect from here on out + +What follows from here is just a bunch of absolute nonsense I've written to dogfood the plugin itself. It includes every sensible typographic element I could think of, like **bold text**, unordered lists, ordered lists, code blocks, block quotes, _and even italics_. + +It's important to cover all of these use cases for a few reasons: + +1. We want everything to look good out of the box. +2. Really just the first reason, that's the whole point of the plugin. +3. Here's a third pretend reason though a list with three items looks more realistic than a list with two items. + +Now we're going to try out another header style. + +### Typography should be easy + +So that's a header for you โ€” with any luck if we've done our job correctly that will look pretty reasonable. + +Something a wise person once told me about typography is: + +> Typography is pretty important if you don't want your stuff to look like trash. Make it good then it won't be bad. + +It's probably important that images look okay here by default as well: + +Image + +Contrary to popular belief, Lorem Ipsum is not simply random text. It has roots in a piece of classical Latin literature from 45 BC, making it over 2000 years old. + +Now I'm going to show you an example of an unordered list to make sure that looks good, too: + +- So here is the first item in this list. +- In this example we're keeping the items short. +- Later, we'll use longer, more complex list items. + +And that's the end of this section. + +## What if we stack headings? + +### We should make sure that looks good, too. + +Sometimes you have headings directly underneath each other. In those cases you often have to undo the top margin on the second heading because it usually looks better for the headings to be closer together than a paragraph followed by a heading should be. + +### When a heading comes after a paragraph โ€ฆ + +When a heading comes after a paragraph, we need a bit more space, like I already mentioned above. Now let's see what a more complex list would look like. + +- **I often do this thing where list items have headings.** + + For some reason I think this looks cool which is unfortunate because it's pretty annoying to get the styles right. + + I often have two or three paragraphs in these list items, too, so the hard part is getting the spacing between the paragraphs, list item heading, and separate list items to all make sense. Pretty tough honestly, you could make a strong argument that you just shouldn't write this way. + +- **Since this is a list, I need at least two items.** + + I explained what I'm doing already in the previous list item, but a list wouldn't be a list if it only had one item, and we really want this to look realistic. That's why I've added this second list item so I actually have something to look at when writing the styles. + +- **It's not a bad idea to add a third item either.** + + I think it probably would've been fine to just use two items but three is definitely not worse, and since I seem to be having no trouble making up arbitrary things to type, I might as well include it. + +After this sort of list I usually have a closing statement or paragraph, because it kinda looks weird jumping right to a heading. + +## Code should look okay by default. + +I think most people are going to use [highlight.js](https://highlightjs.org/) or [Prism](https://prismjs.com/) or something if they want to style their code blocks but it wouldn't hurt to make them look _okay_ out of the box, even with no syntax highlighting. + +Here's what a default `tailwind.config.js` file looks like at the time of writing: + +```js +module.exports = { + purge: [], + theme: { + extend: {}, + }, + variants: {}, + plugins: [], +}; +``` + +Hopefully that looks good enough to you. + +### What about nested lists? + +Nested lists basically always look bad which is why editors like Medium don't even let you do it, but I guess since some of you goofballs are going to do it we have to carry the burden of at least making it work. + +1. **Nested lists are rarely a good idea.** + - You might feel like you are being really "organized" or something but you are just creating a gross shape on the screen that is hard to read. + - Nested navigation in UIs is a bad idea too, keep things as flat as possible. + - Nesting tons of folders in your source code is also not helpful. +2. **Since we need to have more items, here's another one.** + - I'm not sure if we'll bother styling more than two levels deep. + - Two is already too much, three is guaranteed to be a bad idea. + - If you nest four levels deep you belong in prison. +3. **Two items isn't really a list, three is good though.** + - Again please don't nest lists if you want people to actually read your content. + - Nobody wants to look at this. + - I'm upset that we even have to bother styling this. + +The most annoying thing about lists in Markdown is that `
    4. ` elements aren't given a child `

      ` tag unless there are multiple paragraphs in the list item. That means I have to worry about styling that annoying situation too. + +- **For example, here's another nested list.** + + But this time with a second paragraph. + + - These list items won't have `

      ` tags + - Because they are only one line each + +- **But in this second top-level list item, they will.** + + This is especially annoying because of the spacing on this paragraph. + + - As you can see here, because I've added a second line, this list item now has a `

      ` tag. + + This is the second line I'm talking about by the way. + + - Finally here's another list item so it's more like a list. + +- A closing list item, but with no nested list, because why not? + +And finally a sentence to close off this section. + +## There are other elements we need to style + +I almost forgot to mention links, like [this link to the Tailwind CSS website](https://tailwindcss.com). We almost made them blue but that's so yesterday, so we went with dark gray, feels edgier. + +We even included table styles, check it out: + +| Wrestler | Origin | Finisher | +| ----------------------- | ------------ | ------------------ | +| Bret "The Hitman" Hart | Calgary, AB | Sharpshooter | +| Stone Cold Steve Austin | Austin, TX | Stone Cold Stunner | +| Randy Savage | Sarasota, FL | Elbow Drop | +| Vader | Boulder, CO | Vader Bomb | +| Razor Ramon | Chuluota, FL | Razor's Edge | + +We also need to make sure inline code looks good, like if I wanted to talk about `` elements or tell you the good news about `@tailwindcss/typography`. + +### Sometimes I even use `code` in headings + +Even though it's probably a bad idea, and historically I've had a hard time making it look good. This _"wrap the code blocks in backticks"_ trick works pretty well though really. + +Another thing I've done in the past is put a `code` tag inside of a link, like if I wanted to tell you about the [`tailwindcss/docs`](https://github.com/tailwindcss/docs) repository. I don't love that there is an underline below the backticks but it is absolutely not worth the madness it would require to avoid it. + +#### We haven't used an `h4` yet + +But now we have. Please don't use `h5` or `h6` in your content, Medium only supports two heading levels for a reason, you animals. I honestly considered using a `before` pseudo-element to scream at you if you use an `h5` or `h6`. + +We don't style them at all out of the box because `h4` elements are already so small that they are the same size as the body copy. What are we supposed to do with an `h5`, make it _smaller_ than the body copy? No thanks. + +### We still need to think about stacked headings though. + +#### Let's make sure we don't screw that up with `h4` elements, either. + +Phew, with any luck we have styled the headings above this text and they look pretty good. + +Let's add a closing paragraph here so things end with a decently sized block of text. I can't explain why I want things to end that way but I have to assume it's because I think things will look weird or unbalanced if there is a heading too close to the end of the document. + +What I've written here is probably long enough, but adding this final sentence can't hurt. + +## GitHub Flavored Markdown + +I've also added support for GitHub Flavored Mardown using `remark-gfm`. + +With `remark-gfm`, we get a few extra features in our markdown. Example: autolink literals. + +A link like www.example.com or https://example.com would automatically be converted into an `a` tag. + +This works for email links too: contact@example.com. diff --git a/apps/www/src/components/content/templete-blog/server-client-components.mdx b/apps/www/src/components/content/templete-blog/server-client-components.mdx new file mode 100644 index 0000000..f71d58c --- /dev/null +++ b/apps/www/src/components/content/templete-blog/server-client-components.mdx @@ -0,0 +1,219 @@ +--- +title: Server and Client Components +description: React Server Components allow developers to build applications that span the server and client. +image: /images/blog/blog-post-4.jpg +date: "2023-01-08" +authors: + - shadcn +--- + + + The text below is from the [Tailwind + CSS](https://play.tailwindcss.com/uj1vGACRJA?layout=preview) docs. I copied it + here to test the markdown styles. **Tailwind is awesome. You should use it.** + + +Until now, trying to style an article, document, or blog post with Tailwind has been a tedious task that required a keen eye for typography and a lot of complex custom CSS. + +By default, Tailwind removes all of the default browser styling from paragraphs, headings, lists and more. This ends up being really useful for building application UIs because you spend less time undoing user-agent styles, but when you _really are_ just trying to style some content that came from a rich-text editor in a CMS or a markdown file, it can be surprising and unintuitive. + +We get lots of complaints about it actually, with people regularly asking us things like: + +> Why is Tailwind removing the default styles on my `h1` elements? How do I disable this? What do you mean I lose all the other base styles too? +> We hear you, but we're not convinced that simply disabling our base styles is what you really want. You don't want to have to remove annoying margins every time you use a `p` element in a piece of your dashboard UI. And I doubt you really want your blog posts to use the user-agent styles either โ€” you want them to look _awesome_, not awful. + +The `@tailwindcss/typography` plugin is our attempt to give you what you _actually_ want, without any of the downsides of doing something stupid like disabling our base styles. + +It adds a new `prose` class that you can slap on any block of vanilla HTML content and turn it into a beautiful, well-formatted document: + +```html +

      +

      Garlic bread with cheese: What the science tells us

      +

      + For years parents have espoused the health benefits of eating garlic bread + with cheese to their children, with the food earning such an iconic status + in our culture that kids will often dress up as warm, cheesy loaf for + Halloween. +

      +

      + But a recent study shows that the celebrated appetizer may be linked to a + series of rabies cases springing up around the country. +

      +
      +``` + +For more information about how to use the plugin and the features it includes, [read the documentation](https://github.com/tailwindcss/typography/blob/master/README.md). + +--- + +## What to expect from here on out + +What follows from here is just a bunch of absolute nonsense I've written to dogfood the plugin itself. It includes every sensible typographic element I could think of, like **bold text**, unordered lists, ordered lists, code blocks, block quotes, _and even italics_. + +It's important to cover all of these use cases for a few reasons: + +1. We want everything to look good out of the box. +2. Really just the first reason, that's the whole point of the plugin. +3. Here's a third pretend reason though a list with three items looks more realistic than a list with two items. + +Now we're going to try out another header style. + +### Typography should be easy + +So that's a header for you โ€” with any luck if we've done our job correctly that will look pretty reasonable. + +Something a wise person once told me about typography is: + +> Typography is pretty important if you don't want your stuff to look like trash. Make it good then it won't be bad. + +It's probably important that images look okay here by default as well: + +Image + +Contrary to popular belief, Lorem Ipsum is not simply random text. It has roots in a piece of classical Latin literature from 45 BC, making it over 2000 years old. + +Now I'm going to show you an example of an unordered list to make sure that looks good, too: + +- So here is the first item in this list. +- In this example we're keeping the items short. +- Later, we'll use longer, more complex list items. + +And that's the end of this section. + +## What if we stack headings? + +### We should make sure that looks good, too. + +Sometimes you have headings directly underneath each other. In those cases you often have to undo the top margin on the second heading because it usually looks better for the headings to be closer together than a paragraph followed by a heading should be. + +### When a heading comes after a paragraph โ€ฆ + +When a heading comes after a paragraph, we need a bit more space, like I already mentioned above. Now let's see what a more complex list would look like. + +- **I often do this thing where list items have headings.** + + For some reason I think this looks cool which is unfortunate because it's pretty annoying to get the styles right. + + I often have two or three paragraphs in these list items, too, so the hard part is getting the spacing between the paragraphs, list item heading, and separate list items to all make sense. Pretty tough honestly, you could make a strong argument that you just shouldn't write this way. + +- **Since this is a list, I need at least two items.** + + I explained what I'm doing already in the previous list item, but a list wouldn't be a list if it only had one item, and we really want this to look realistic. That's why I've added this second list item so I actually have something to look at when writing the styles. + +- **It's not a bad idea to add a third item either.** + + I think it probably would've been fine to just use two items but three is definitely not worse, and since I seem to be having no trouble making up arbitrary things to type, I might as well include it. + +After this sort of list I usually have a closing statement or paragraph, because it kinda looks weird jumping right to a heading. + +## Code should look okay by default. + +I think most people are going to use [highlight.js](https://highlightjs.org/) or [Prism](https://prismjs.com/) or something if they want to style their code blocks but it wouldn't hurt to make them look _okay_ out of the box, even with no syntax highlighting. + +Here's what a default `tailwind.config.js` file looks like at the time of writing: + +```js +module.exports = { + purge: [], + theme: { + extend: {}, + }, + variants: {}, + plugins: [], +}; +``` + +Hopefully that looks good enough to you. + +### What about nested lists? + +Nested lists basically always look bad which is why editors like Medium don't even let you do it, but I guess since some of you goofballs are going to do it we have to carry the burden of at least making it work. + +1. **Nested lists are rarely a good idea.** + - You might feel like you are being really "organized" or something but you are just creating a gross shape on the screen that is hard to read. + - Nested navigation in UIs is a bad idea too, keep things as flat as possible. + - Nesting tons of folders in your source code is also not helpful. +2. **Since we need to have more items, here's another one.** + - I'm not sure if we'll bother styling more than two levels deep. + - Two is already too much, three is guaranteed to be a bad idea. + - If you nest four levels deep you belong in prison. +3. **Two items isn't really a list, three is good though.** + - Again please don't nest lists if you want people to actually read your content. + - Nobody wants to look at this. + - I'm upset that we even have to bother styling this. + +The most annoying thing about lists in Markdown is that `
    5. ` elements aren't given a child `

      ` tag unless there are multiple paragraphs in the list item. That means I have to worry about styling that annoying situation too. + +- **For example, here's another nested list.** + + But this time with a second paragraph. + + - These list items won't have `

      ` tags + - Because they are only one line each + +- **But in this second top-level list item, they will.** + + This is especially annoying because of the spacing on this paragraph. + + - As you can see here, because I've added a second line, this list item now has a `

      ` tag. + + This is the second line I'm talking about by the way. + + - Finally here's another list item so it's more like a list. + +- A closing list item, but with no nested list, because why not? + +And finally a sentence to close off this section. + +## There are other elements we need to style + +I almost forgot to mention links, like [this link to the Tailwind CSS website](https://tailwindcss.com). We almost made them blue but that's so yesterday, so we went with dark gray, feels edgier. + +We even included table styles, check it out: + +| Wrestler | Origin | Finisher | +| ----------------------- | ------------ | ------------------ | +| Bret "The Hitman" Hart | Calgary, AB | Sharpshooter | +| Stone Cold Steve Austin | Austin, TX | Stone Cold Stunner | +| Randy Savage | Sarasota, FL | Elbow Drop | +| Vader | Boulder, CO | Vader Bomb | +| Razor Ramon | Chuluota, FL | Razor's Edge | + +We also need to make sure inline code looks good, like if I wanted to talk about `` elements or tell you the good news about `@tailwindcss/typography`. + +### Sometimes I even use `code` in headings + +Even though it's probably a bad idea, and historically I've had a hard time making it look good. This _"wrap the code blocks in backticks"_ trick works pretty well though really. + +Another thing I've done in the past is put a `code` tag inside of a link, like if I wanted to tell you about the [`tailwindcss/docs`](https://github.com/tailwindcss/docs) repository. I don't love that there is an underline below the backticks but it is absolutely not worth the madness it would require to avoid it. + +#### We haven't used an `h4` yet + +But now we have. Please don't use `h5` or `h6` in your content, Medium only supports two heading levels for a reason, you animals. I honestly considered using a `before` pseudo-element to scream at you if you use an `h5` or `h6`. + +We don't style them at all out of the box because `h4` elements are already so small that they are the same size as the body copy. What are we supposed to do with an `h5`, make it _smaller_ than the body copy? No thanks. + +### We still need to think about stacked headings though. + +#### Let's make sure we don't screw that up with `h4` elements, either. + +Phew, with any luck we have styled the headings above this text and they look pretty good. + +Let's add a closing paragraph here so things end with a decently sized block of text. I can't explain why I want things to end that way but I have to assume it's because I think things will look weird or unbalanced if there is a heading too close to the end of the document. + +What I've written here is probably long enough, but adding this final sentence can't hurt. + +## GitHub Flavored Markdown + +I've also added support for GitHub Flavored Mardown using `remark-gfm`. + +With `remark-gfm`, we get a few extra features in our markdown. Example: autolink literals. + +A link like www.example.com or https://example.com would automatically be converted into an `a` tag. + +This works for email links too: contact@example.com. diff --git a/apps/www/src/components/dashboard/EventsDashboard.tsx b/apps/www/src/components/dashboard/EventsDashboard.tsx new file mode 100644 index 0000000..fec5c60 --- /dev/null +++ b/apps/www/src/components/dashboard/EventsDashboard.tsx @@ -0,0 +1,50 @@ +"use client"; + +import { useState } from "react"; + +import { AddApiKeyButton } from "@/components/buttons/AddApiKeyButton"; +import { EmptyPlaceholder } from "@/components/shared/empty-placeholder"; + +import { DocsButton } from "../buttons/DocsButton"; +import { EventDashboardDetailsSheet } from "./EventsDashboardComponents/EventDashboardDetailsSheet"; +import EventsDashboardCards from "./EventsDashboardComponents/EventsDashboardCards"; +import EventsDashboardDetails from "./EventsDashboardComponents/EventsDashboardDetails"; +import EventsDashboardTable from "./EventsDashboardComponents/EventsDashboardTable"; + +export default function EventsDashboard({ events, eventStats }) { + const [selectedEventId, setSelectedEventId] = useState(events[0]?.id); + + const selectedEvent = events.find((event) => event.id === selectedEventId); + + return ( +

      +
      +
      + +
      + {events.length > 0 ? ( + + ) : ( + + + There are no events + + You need to create an event first to see it here + +
      + + +
      +
      + )} +
      +
      + +
      +
      + ); +} diff --git a/apps/www/src/components/dashboard/EventsDashboardComponents/EventDashboardDetailsSheet.tsx b/apps/www/src/components/dashboard/EventsDashboardComponents/EventDashboardDetailsSheet.tsx new file mode 100644 index 0000000..0949d63 --- /dev/null +++ b/apps/www/src/components/dashboard/EventsDashboardComponents/EventDashboardDetailsSheet.tsx @@ -0,0 +1,213 @@ +"use client"; + +import Link from "next/link"; +import { createEvent } from "@/actions/create-event"; +import { zodResolver } from "@hookform/resolvers/zod"; +import { useForm } from "react-hook-form"; +import { z } from "zod"; + +import { Button } from "@dingify/ui/components/button"; +import { Checkbox } from "@dingify/ui/components/checkbox"; +import { + Form, + FormControl, + FormDescription, + FormField, + FormItem, + FormLabel, + FormMessage, +} from "@dingify/ui/components/form"; +import { Input } from "@dingify/ui/components/input"; +import { + Sheet, + SheetClose, + SheetContent, + SheetDescription, + SheetFooter, + SheetHeader, + SheetTitle, + SheetTrigger, +} from "@dingify/ui/components/sheet"; +import { toast } from "sonner"; + +// Define the validation schema +const FormSchema = z.object({ + channel: z.string().min(1, "Channel is required"), + name: z.string().min(1, "Name is required"), + event: z.string().min(1, "Event is required"), + user_id: z.string().min(1, "User ID is required"), + icon: z.string().min(1, "Icon is required"), + notify: z.boolean(), +}); + +export function EventDashboardDetailsSheet() { + const form = useForm({ + resolver: zodResolver(FormSchema), + defaultValues: { + channel: "", + name: "", + event: "", + user_id: "", + icon: "", + notify: true, + }, + }); + + const onSubmit = async (data) => { + console.log("Form data to submit:", data); // Log form dat + try { + const result = await createEvent(data); + if (result.success) { + toast.message( +
      + Event Created. +
      +              
      +                {JSON.stringify(data, null, 2)}
      +              
      +            
      +
      ); + console.log("Event created:", result.event); // Log the created event + // Optionally refresh the page or clear the form + form.reset(); + } + } catch (error) { + toast.error("There was an error creating the event."); + console.error("Error creating event:", error); // Log any error + } + }; + + return ( + + + + + + + Create Event + + Fill in the details to create a new event. + + +
      + + ( + + Channel + + + + + + )} + /> + ( + + Name + + + + + + )} + /> + ( + + Event + + + + + + )} + /> + ( + + User ID + + + + + + )} + /> + ( + + Icon + + + + + + )} + /> + ( + + + + + Notify + + You can manage your notifications in the{" "} + settings page. + + + + )} + /> + {/* ( + + Plan + + + + + + )} + /> */} + {/* ( + + Cycle + + + + + + )} + /> */} + + + + + +
      +
      + ); +} diff --git a/apps/www/src/components/dashboard/EventsDashboardComponents/EventsDashboardCards.tsx b/apps/www/src/components/dashboard/EventsDashboardComponents/EventsDashboardCards.tsx new file mode 100644 index 0000000..802355c --- /dev/null +++ b/apps/www/src/components/dashboard/EventsDashboardComponents/EventsDashboardCards.tsx @@ -0,0 +1,78 @@ +import { Button } from "@dingify/ui/components/button"; +import { + Card, + CardContent, + CardDescription, + CardFooter, + CardHeader, + CardTitle, +} from "@dingify/ui/components/card"; +import { Progress } from "@dingify/ui/components/progress"; + +import { CreateEventButton } from "@/components/buttons/CreatEventButton"; + +import { EventDashboardDetailsSheet } from "./EventDashboardDetailsSheet"; + +export default function EventsDashboardCards({ eventStats }) { + return ( + <> + + + Your Events + + Introducing Our Dynamic Orders Dashboard for Seamless Management and + Insightful Analysis. + + + + {/* */} + + + + + + This Week + + {eventStats.currentWeekEvents} + + + +
      + {eventStats.weeklyChange >= 0 + ? `+${eventStats.weeklyChange.toFixed(2)}%` + : `${eventStats.weeklyChange.toFixed(2)}%`}{" "} + from last week +
      +
      + + + +
      + + + This Month + + {eventStats.currentMonthEvents} + + + +
      + {eventStats.monthlyChange >= 0 + ? `+${eventStats.monthlyChange.toFixed(2)}%` + : `${eventStats.monthlyChange.toFixed(2)}%`}{" "} + from last month +
      +
      + + + +
      + + ); +} diff --git a/apps/www/src/components/dashboard/EventsDashboardComponents/EventsDashboardDetails.tsx b/apps/www/src/components/dashboard/EventsDashboardComponents/EventsDashboardDetails.tsx new file mode 100644 index 0000000..20ad182 --- /dev/null +++ b/apps/www/src/components/dashboard/EventsDashboardComponents/EventsDashboardDetails.tsx @@ -0,0 +1,254 @@ +import { useRouter } from "next/navigation"; +import { deleteEvent } from "@/actions/delete-event"; +import { format } from "date-fns"; +import { File, Pencil, Trash } from "lucide-react"; +import { toast } from "sonner"; + +import { Badge } from "@dingify/ui/components/badge"; +import { Button } from "@dingify/ui/components/button"; +import { + Card, + CardContent, + CardDescription, + CardFooter, + CardHeader, + CardTitle, +} from "@dingify/ui/components/card"; +import { + DropdownMenu, + DropdownMenuContent, + DropdownMenuItem, + DropdownMenuSeparator, + DropdownMenuShortcut, + DropdownMenuTrigger, +} from "@dingify/ui/components/dropdown-menu"; +import { Separator } from "@dingify/ui/components/separator"; + +import { ViewDetailsButton } from "@/components/buttons/ViewDetailsButton"; +import { UserBadge } from "@/components/UserBadge"; + +export default function EventsDashboardDetails({ event }) { + const router = useRouter(); + + const handleDelete = async () => { + try { + await deleteEvent(event.id); + toast.success("The event has been deleted successfully."); + router.refresh(); + } catch (error) { + toast.error("There was an error deleting the event."); + console.error("Error deleting event:", error); + } + }; + + const handleUserClick = (customerId) => { + router.push(`dashboard/users/${customerId}`); + }; + + return ( + <> + + +
      + + {event?.name} + + + + Date:{" "} + {event?.createdAt ? format(event?.createdAt, "MM/dd/yyyy") : ""} + +
      +
      + + + + + + + + + Edit + + + + Export + + + + + Delete + + + +
      +
      + +
      +
      Event Details
      +
        +
      • + Event Type + {event?.name} +
      • +
      • + Channel + + + {event?.channel ? event?.channel.name : "No Channel"} + + +
      • +
      • + Project + + + {event?.channel && event?.channel.project + ? event?.channel.project.name + : "No Project"} + + +
      • +
      + +
        +
      • + User + + + +
      • +
      • + Description + {event?.name} +
      • +
      • + Icon + {event?.icon} +
      • +
      • + Notify + + + {event?.notify.toString()} + + +
      • +
      +
      + +
      +
      Meta Tags
      +
      +
      +
      Plan
      +
      + + {event?.tags.plan} + +
      +
      +
      +
      Cycle
      +
      + + {event?.tags.cycle} + +
      +
      +
      +
      +
      + +
      + Updated + {/* */} +
      +
      +
      + + ); +} + +function TruckIcon(props) { + return ( + + + + + + + + ); +} + +function MoveVerticalIcon(props) { + return ( + + + + + + ); +} + +function InfoIcon(props) { + return ( + + + + + + ); +} diff --git a/apps/www/src/components/dashboard/EventsDashboardComponents/EventsDashboardTable.tsx b/apps/www/src/components/dashboard/EventsDashboardComponents/EventsDashboardTable.tsx new file mode 100644 index 0000000..7049aae --- /dev/null +++ b/apps/www/src/components/dashboard/EventsDashboardComponents/EventsDashboardTable.tsx @@ -0,0 +1,194 @@ +import { useRouter } from "next/navigation"; + +import { Badge } from "@dingify/ui/components/badge"; +import { + Card, + CardContent, + CardDescription, + CardFooter, + CardHeader, + CardTitle, +} from "@dingify/ui/components/card"; +import { + Table, + TableBody, + TableCell, + TableHead, + TableHeader, + TableRow, +} from "@dingify/ui/components/table"; +import { + Tabs, + TabsContent, + TabsList, + TabsTrigger, +} from "@dingify/ui/components/tabs"; + +import { UserBadge } from "@/components/UserBadge"; + +export default function EventsDashboardTable({ + events, + setSelectedEventId, + selectedEventId, +}) { + const router = useRouter(); + + const handleUserClick = (customerId) => { + router.push(`dashboard/users/${customerId}`); + }; + + return ( + <> + +
      + {/* + Week + Month + Year + */} + {/*
      + + + + + + Filter by + + + Fulfilled + + Declined + Refunded + + + +
      */} +
      + + + + Events + + Monitor your app's real-time events. + + + + + + + Channel + Name + + UserID + + Icon + Notify + + + + {events.map((event) => ( + setSelectedEventId(event.id)} + className={ + selectedEventId === event.id ? "bg-accent" : "" + } + > + + {event.channel && event.channel.name && ( +
      + {event.channel.name} +
      + )} + {event.channel && + event.channel.project && + event.channel.project.name && ( +
      + {event.channel.project.name} +
      + )} +
      + + {event.name} + + + + + + {event.icon} + + + + {event.notify.toString()} + + +
      + ))} +
      +
      +
      +
      +
      +
      + + ); +} + +function FileIcon(props) { + return ( + + + + + ); +} + +function ListFilterIcon(props) { + return ( + + + + + + ); +} diff --git a/apps/www/src/components/dashboard/beam-section.tsx b/apps/www/src/components/dashboard/beam-section.tsx new file mode 100644 index 0000000..ed00950 --- /dev/null +++ b/apps/www/src/components/dashboard/beam-section.tsx @@ -0,0 +1,40 @@ +"use client"; + +import React, { forwardRef, useRef } from "react"; + +import { BentoSectionLanding } from "../ui/bento-section-landing"; + +export function BeamSection() { + const containerRef = useRef(null); + + return ( +
      +
      +
      + {/*

      + Pricing +

      */} + +

      + Easy to integrate +

      + +

      + It only takes a single HTTP request to get started. + Integrate seamlessly with your our SDK and tools to simplify the + process. +

      +
      +
      + +
      +
      + +
      +
      +
      + ); +} diff --git a/apps/www/src/components/dashboard/bento-section.tsx b/apps/www/src/components/dashboard/bento-section.tsx new file mode 100644 index 0000000..7653e71 --- /dev/null +++ b/apps/www/src/components/dashboard/bento-section.tsx @@ -0,0 +1,80 @@ +"use client"; + +import React, { forwardRef, useRef } from "react"; + +import { cn } from "@/lib/utils"; + +import { AnimatedBeam } from "../animate-beam"; +import { Icons } from "../shared/icons"; + +const Circle = forwardRef< + HTMLDivElement, + { className?: string; children?: React.ReactNode } +>(({ className, children }, ref) => { + return ( +
      + {children} +
      + ); +}); + +export function BentoSection() { + const containerRef = useRef(null); + const div1Ref = useRef(null); + const div2Ref = useRef(null); + + return ( +
      +
      +
      + {/*

      + Pricing +

      */} + +

      + Easy to integrate +

      + +

      + Choose an affordable plan that's packed with + the best features for engaging your audience, creating customer + loyalty, and driving sales. +

      +
      +
      + +
      + {" "} + {/* Reduced margins */} +
      +
      +
      + + + + + + +
      +
      + + +
      +
      +
      + ); +} diff --git a/apps/www/src/components/dashboard/businessline.tsx b/apps/www/src/components/dashboard/businessline.tsx new file mode 100644 index 0000000..a169b50 --- /dev/null +++ b/apps/www/src/components/dashboard/businessline.tsx @@ -0,0 +1,211 @@ +import Link from "next/link"; + +export function BusinessLine() { + return ( +
      +
      +

      + The worlds most innovative companies use our app +

      + +
      + {features.map((feature) => ( + + {feature.icon} + + ))} +
      +
      +
      + ); +} + +const features = [ + { + title: "Next.js 14", + href: "https://nextjs.org/", + icon: ( + + + + ), + }, + { + title: "Prisma", + href: "https://www.prisma.io/", + icon: ( + + + + ), + }, + { + title: "PlanetScale", + href: "https://planetscale.com/", + icon: ( + + + + + + + + + + + + + + + + + + ), + }, + { + title: "Auth.js", + href: "https://authjs.dev/", + icon: ( + + + + ), + }, + { + title: "Resend", + href: "https://resend.com/", + icon: ( + + + + + + + + + ), + }, + { + title: "shadcn/ui", + href: "https://ui.shadcn.com/", + icon: ( + + + + + + ), + }, + { + title: "Stripe", + href: "https://stripe.com/", + icon: ( + + + + ), + }, +]; diff --git a/apps/www/src/components/dashboard/calltoaction.tsx b/apps/www/src/components/dashboard/calltoaction.tsx new file mode 100644 index 0000000..1dc7b30 --- /dev/null +++ b/apps/www/src/components/dashboard/calltoaction.tsx @@ -0,0 +1,34 @@ +import { Balancer } from "react-wrap-balancer"; + +import { GetStartedButton } from "../buttons/GetStartedButton"; + +const CallToActionComponent = () => { + return ( +
      +

      + Boost your productivity today +

      +

      + + Streamline your property listings and client interactions with the + precision of AI. Propwrite delivers a suite of tools that elevate your + efficiency and let you focus on closing deals โ€“ not on paperwork. + +

      +
      + +
      +
      + ); +}; + +export default CallToActionComponent; diff --git a/apps/www/src/components/dashboard/charts/AlertsOverviewChart.tsx b/apps/www/src/components/dashboard/charts/AlertsOverviewChart.tsx new file mode 100644 index 0000000..ab1e0c5 --- /dev/null +++ b/apps/www/src/components/dashboard/charts/AlertsOverviewChart.tsx @@ -0,0 +1,91 @@ +"use client"; + +import { ResponsiveLine } from "@nivo/line"; + +export default function AlertsOverviewChart(props) { + const data = [ + { + id: "Critical", + data: [ + { x: "Jan", y: 30 }, + { x: "Feb", y: 60 }, + { x: "Mar", y: 90 }, + { x: "Apr", y: 120 }, + { x: "May", y: 50 }, + { x: "Jun", y: 40 }, + ], + }, + { + id: "Warning", + data: [ + { x: "Jan", y: 50 }, + { x: "Feb", y: 80 }, + { x: "Mar", y: 100 }, + { x: "Apr", y: 110 }, + { x: "May", y: 80 }, + { x: "Jun", y: 100 }, + ], + }, + { + id: "Info", + data: [ + { x: "Jan", y: 20 }, + { x: "Feb", y: 50 }, + { x: "Mar", y: 60 }, + { x: "Apr", y: 70 }, + { x: "May", y: 90 }, + { x: "Jun", y: 120 }, + ], + }, + ]; + + return ( +
      + +
      + ); +} diff --git a/apps/www/src/components/dashboard/charts/EventsTrendOverTime.tsx b/apps/www/src/components/dashboard/charts/EventsTrendOverTime.tsx new file mode 100644 index 0000000..66ac59d --- /dev/null +++ b/apps/www/src/components/dashboard/charts/EventsTrendOverTime.tsx @@ -0,0 +1,181 @@ +"use client"; + +import { + Bar, + BarChart, + CartesianGrid, + Legend, + Line, + LineChart, + ResponsiveContainer, + Tooltip, + XAxis, + YAxis, +} from "recharts"; + +import { + Card, + CardContent, + CardHeader, + CardTitle, +} from "@dingify/ui/components/card"; + +const lineChartData = [ + { month: "Jan", events: 400 }, + { month: "Feb", events: 300 }, + { month: "Mar", events: 200 }, + { month: "Apr", events: 278 }, + { month: "May", events: 189 }, + { month: "Jun", events: 239 }, + { month: "Jul", events: 349 }, + { month: "Aug", events: 430 }, + { month: "Sep", events: 480 }, + { month: "Oct", events: 390 }, + { month: "Nov", events: 139 }, + { month: "Dec", events: 240 }, +]; + +const barChartData = [ + { eventType: "Login", count: 120 }, + { eventType: "Logout", count: 98 }, + { eventType: "Purchase", count: 140 }, + { eventType: "Signup", count: 80 }, + { eventType: "Profile Update", count: 150 }, + { eventType: "Password Reset", count: 60 }, +]; + +export default function EventsTrendOverTimeChart( + { + // lineChartData, + // barChartData, + }, +) { + return ( +
      + + + + Monthly Events + + + +
      Event Trends Over Time
      +

      + Number of events created each month over the last year. +

      +
      + + + + + + { + if (active && payload && payload.length) { + return ( +
      +
      +
      + + Month + + + {payload[0]?.payload.month} + +
      +
      + + Events + + + {payload[0]?.value} + +
      +
      +
      + ); + } + + return null; + }} + /> + + +
      +
      +
      +
      +
      + + + + Top Event Types + + + +
      Event Type Breakdown
      +

      + Number of each event type over the last year. +

      +
      + + + + + + { + if (active && payload && payload.length) { + return ( +
      +
      +
      + + Event Type + + + {payload[0]?.payload.eventType} + +
      +
      + + Count + + + {payload[0]?.value} + +
      +
      +
      + ); + } + + return null; + }} + /> + + +
      +
      +
      +
      +
      +
      + ); +} diff --git a/apps/www/src/components/dashboard/charts/SalesFunnelChart.tsx b/apps/www/src/components/dashboard/charts/SalesFunnelChart.tsx new file mode 100644 index 0000000..6e55dcb --- /dev/null +++ b/apps/www/src/components/dashboard/charts/SalesFunnelChart.tsx @@ -0,0 +1,72 @@ +"use client"; + +import { ResponsiveFunnel } from "@nivo/funnel"; + +export default function SalesFunnelChart(props) { + const data = [ + { + id: "step_sent", + value: 92558, + label: "Sent", + }, + { + id: "step_viewed", + value: 59485, + label: "Viewed", + }, + { + id: "step_clicked", + value: 37627, + label: "Clicked", + }, + { + id: "step_add_to_card", + value: 33080, + label: "Add To Cart", + }, + { + id: "step_purchased", + value: 26116, + label: "Purchased", + }, + ]; + + return ( +
      + +
      + ); +} diff --git a/apps/www/src/components/dashboard/charts/UserGrowthChart.tsx b/apps/www/src/components/dashboard/charts/UserGrowthChart.tsx new file mode 100644 index 0000000..396d422 --- /dev/null +++ b/apps/www/src/components/dashboard/charts/UserGrowthChart.tsx @@ -0,0 +1,75 @@ +"use client"; + +import { + Area, + AreaChart, + CartesianGrid, + ResponsiveContainer, + Tooltip, + XAxis, + YAxis, +} from "recharts"; + +import { + Card, + CardContent, + CardHeader, + CardTitle, +} from "@dingify/ui/components/card"; + +// Placeholder data for the past week +const PREVIOUS_WEEK_DATA = [ + { name: "30th Nov", users: 30 }, + { name: "1st Dec", users: 50 }, + { name: "2nd Dec", users: 45 }, + { name: "3rd Dec", users: 60 }, + { name: "4th Dec", users: 70 }, + { name: "5th Dec", users: 65 }, +]; + +export default function UserGrowthTrend() { + return ( +
      + + + + User Growth Trend + + + +
      Estimated Growth of Users
      +

      + Growth trend over the past week. +

      +
      + + + + + + + + + + + + + + + +
      +
      +
      +
      + ); +} diff --git a/apps/www/src/components/dashboard/descriptiondisplay.tsx b/apps/www/src/components/dashboard/descriptiondisplay.tsx new file mode 100644 index 0000000..14992cd --- /dev/null +++ b/apps/www/src/components/dashboard/descriptiondisplay.tsx @@ -0,0 +1,96 @@ +import React from "react"; + +import { + Card, + CardContent, + CardFooter, + CardHeader, + CardTitle, +} from "@dingify/ui/components/card"; + +import GenerateDescriptionButton2 from "../buttons/GenerateDescriptionButton2"; +import NoTextPlaceholder from "../properties/NoTextPlaceholder"; + +const DescriptionDisplay = ({ + descriptionData, + propertyId, + setDescriptionData, +}) => { + // Check if descriptionData is empty + if (!descriptionData) { + return ( + + ); + } + + let parsedData; + try { + // Attempt to parse the JSON string in descriptionData + parsedData = JSON.parse(descriptionData.replace(/```json\n|\n```/g, "")); + // parsedData = JSON.parse("invalid json"); // For testing error message + } catch (error) { + console.error( + `Error parsing description data for property ID ${propertyId}:`, + error + ); + + // Render a user-friendly error message with a retry option + return ( + + +

      + We encountered an issue displaying this property description. +

      +

      + Please try again or contact support if the issue persists. +

      +
      + + + +
      + ); + } + + // Function to recursively render content + const renderContent = (data, isNested = false) => { + if (typeof data === "object" && !Array.isArray(data) && data !== null) { + return Object.entries(data).map(([key, value], index) => ( +
      +

      {key}

      + {renderContent(value, true)} +
      + )); + } else if (Array.isArray(data)) { + return data.map((item, index) => ( +
      + {item.title &&

      {item.title}

      } + {renderContent(item.details || item, true)} +
      + )); + } else { + return

      {data}

      ; + } + }; + + // Render the parsed content + return ( + + {renderContent(parsedData)} + + + + + ); +}; + +export default DescriptionDisplay; diff --git a/apps/www/src/components/dashboard/featuresection1.tsx b/apps/www/src/components/dashboard/featuresection1.tsx new file mode 100644 index 0000000..36ab7c3 --- /dev/null +++ b/apps/www/src/components/dashboard/featuresection1.tsx @@ -0,0 +1,91 @@ +import { + ArrowPathIcon, + CloudArrowUpIcon, + Cog6ToothIcon, + FingerPrintIcon, + LockClosedIcon, + ServerIcon, +} from "@heroicons/react/20/solid"; +import { Balancer } from "react-wrap-balancer"; + +const FeatureSection1 = () => { + const features = [ + { + icon: CloudArrowUpIcon, + title: "Instant Listing Drafts", + description: + "Harness AI to generate captivating property listings instantly. Save time and attract more buyers with eloquent, detail-rich descriptions that stand out.", + }, + { + icon: LockClosedIcon, + title: "Secure Data Handling", + description: + "With our robust SSL encryption, your sensitive property data and client information are safeguarded at every step.", + }, + { + icon: ArrowPathIcon, + title: "Effortless Organization", + description: + "Manage queues of properties with ease. Our system simplifies task management, making follow-ups and updates a breeze.", + }, + // Add the rest of your features here + ]; + + return ( +
      +
      +
      +

      + Streamlined Real Estate Efficiency +

      +

      + + Redefine property listing management with state-of-the-art AI, + delivering unparalleled efficiency and precision. + +

      +
      +
      +
      {/* ... */}
      +
      +
      +
      + {features.map((feature, index) => ( +
      +
      +
      +
      + {feature.title} +
      +
      + {feature.description} +
      + + Learn more โ†’ + +
      + ))} +
      +
      +
      +
      + ); +}; + +export default FeatureSection1; diff --git a/apps/www/src/components/dashboard/feautressection.tsx b/apps/www/src/components/dashboard/feautressection.tsx new file mode 100644 index 0000000..f5fe5ee --- /dev/null +++ b/apps/www/src/components/dashboard/feautressection.tsx @@ -0,0 +1,122 @@ +import { + ArrowPathIcon, + CloudArrowUpIcon, + Cog6ToothIcon, + FingerPrintIcon, + LockClosedIcon, + ServerIcon, +} from "@heroicons/react/20/solid"; +import { Balancer } from "react-wrap-balancer"; + +const features = [ + { + name: "Revolutionizing Real Estate: AI-Powered Listings", + description: + "Instantly draft standout property listings with our advanced AI editor, designed to captivate and attract potential buyers through eloquent, detail-rich descriptions.", + icon: CloudArrowUpIcon, + }, + { + name: "Elevate Your Realty Game with Propwrite", + description: + "Empower your real estate business with Propwrite's SSL encryption, ensuring that all client information and property data are secure and protected.", + icon: LockClosedIcon, + }, + { + name: "Next-Gen Property Management: AI Meets Real Estate", + description: + "Our platform simplifies property management by automating follow-ups and updates, freeing you to focus on what you do best โ€“ closing deals.", + icon: ArrowPathIcon, + }, + { + name: "AI-Enhanced Listings for Smart Agents", + description: + "Stay ahead of security threats with real-time monitoring and automatic updates, safeguarding your listings with the latest in AI technology.", + icon: FingerPrintIcon, + }, + { + name: "Maximize Sales with Intelligent Real Estate Solutions", + description: + "Integrate Propwrite's comprehensive API with your current tools for a seamless experience that enhances your workflow and maximizes efficiency.", + icon: Cog6ToothIcon, + }, + { + name: "Unlock Real Estate Potential with AI Efficiency", + description: + "Ensure your listings are always current and never lost with our reliable backup solutions, providing peace of mind and data security.", + icon: ServerIcon, + }, +]; + +export default function Featuressection() { + return ( +
      +
      +
      +

      + + Propwrite + +

      + +

      + Streamlined Real Estate Efficiency +

      + +

      + + Propwrite redefines property listing management with + state-of-the-art AI, delivering unparalleled efficiency and + precision. Experience the future of real estateโ€”where technology + enhances every transaction, every client interaction, and every + sale + +

      +
      +
      +
      +
      + App screenshot + +
      +
      +
      + {features.map((feature) => ( +
      +
      +
      +
      + {feature.description} +
      +
      + ))} +
      +
      +
      + ); +} diff --git a/apps/www/src/components/dashboard/generatedtext.tsx b/apps/www/src/components/dashboard/generatedtext.tsx new file mode 100644 index 0000000..7401885 --- /dev/null +++ b/apps/www/src/components/dashboard/generatedtext.tsx @@ -0,0 +1,22 @@ +"use client"; + +import { useState } from "react"; + +import DescriptionDisplay from "./descriptiondisplay"; + +const Generatedtext = ({ propertyId, descriptionData }) => { + const [localDescriptionData, setLocalDescriptionData] = + useState(descriptionData); + + return ( +
      + +
      + ); +}; + +export default Generatedtext; diff --git a/apps/www/src/components/dashboard/header.tsx b/apps/www/src/components/dashboard/header.tsx new file mode 100644 index 0000000..b1a4146 --- /dev/null +++ b/apps/www/src/components/dashboard/header.tsx @@ -0,0 +1,21 @@ +interface DashboardHeaderProps { + heading: string; + text?: string; + children?: React.ReactNode; +} + +export function DashboardHeader({ + heading, + text, + children, +}: DashboardHeaderProps) { + return ( +
      +
      +

      {heading}

      + {text &&

      {text}

      } +
      + {children} +
      + ); +} diff --git a/apps/www/src/components/dashboard/herosection.tsx b/apps/www/src/components/dashboard/herosection.tsx new file mode 100644 index 0000000..afa31b5 --- /dev/null +++ b/apps/www/src/components/dashboard/herosection.tsx @@ -0,0 +1,82 @@ +"use client"; + +import Link from "next/link"; +import Balancer from "react-wrap-balancer"; + +import { buttonVariants } from "@dingify/ui/components/button"; +import { + Card, + CardContent, + CardDescription, + CardHeader, + CardTitle, +} from "@dingify/ui/components/card"; + +import { cn } from "../../lib/utils"; +import { GetStartedButton } from "../buttons/GetStartedButton"; +import { Icons } from "../shared/icons"; +import AlertsOverviewChart from "./charts/AlertsOverviewChart"; + +export default function HeroSection() { + return ( +
      +
      +
      +
      +
      +

      + Real-Time Monitoring with Dingify +

      +

      + Unlock the power of seamless real-time monitoring that + captivates your audience and drives results. +

      +
      +
      + + + +

      + Explore{" "} + Dingify{" "} +

      + +
      +
      + + + Alerts Overview + + A graph showing the different alert types over time. + + + + + + +
      +
      +
      + ); +} diff --git a/apps/www/src/components/dashboard/herosection2.tsx b/apps/www/src/components/dashboard/herosection2.tsx new file mode 100644 index 0000000..85d607d --- /dev/null +++ b/apps/www/src/components/dashboard/herosection2.tsx @@ -0,0 +1,87 @@ +"use client"; + +import Link from "next/link"; +import Balancer from "react-wrap-balancer"; + +import { buttonVariants } from "@dingify/ui/components/button"; +import { + Card, + CardContent, + CardDescription, + CardHeader, + CardTitle, +} from "@dingify/ui/components/card"; + +import { getGreeting } from "@/lib/utils"; + +import { cn } from "../../lib/utils"; +import { GetStartedButton } from "../buttons/GetStartedButton"; +import SalesFunnelChart from "./charts/SalesFunnelChart"; + +export default function HeroSection2() { + const greeting = getGreeting(); + return ( +
      +
      +
      + + + Sales Funnel Overview + + A graph showing conversion rates over different steps. + + + + + + + +
      +
      +

      + Track your Important Events this {greeting} +

      +

      + Unlock the power of seamless real-time monitoring that + captivates your audience and drives results. +

      +
      +
      + + + Explore Dingity + +
      +
      +
      +
      +
      + ); +} diff --git a/apps/www/src/components/dashboard/shell.tsx b/apps/www/src/components/dashboard/shell.tsx new file mode 100644 index 0000000..62127e9 --- /dev/null +++ b/apps/www/src/components/dashboard/shell.tsx @@ -0,0 +1,16 @@ +import * as React from "react"; +import { cn } from "@/lib/utils"; + +type DashboardShellProps = React.HTMLAttributes; + +export function DashboardShell({ + children, + className, + ...props +}: DashboardShellProps) { + return ( +
      + {children} +
      + ); +} diff --git a/apps/www/src/components/dashboard/test.tsx b/apps/www/src/components/dashboard/test.tsx new file mode 100644 index 0000000..4b00bad --- /dev/null +++ b/apps/www/src/components/dashboard/test.tsx @@ -0,0 +1,85 @@ +"use client"; + +import { Button } from "@dingify/ui/components/button"; +import { + Card, + CardContent, + CardDescription, + CardFooter, + CardHeader, + CardTitle, +} from "@dingify/ui/components/card"; +import { Input } from "@dingify/ui/components/input"; +import { Label } from "@dingify/ui/components/label"; +import { + Select, + SelectContent, + SelectItem, + SelectTrigger, + SelectValue, +} from "@dingify/ui/components/select"; +import { Textarea } from "@dingify/ui/components/textarea"; + +export function InputRightSideTest() { + return ( + + + Report an issue + + What area are you having problems with? + + + +
      +
      + + +
      +
      + + +
      +
      +
      + + +
      +
      + +