├── .editorconfig ├── .env.example ├── .eslintrc.json ├── .github ├── CODEOWNERS ├── ISSUE_TEMPLATE │ ├── bug_report.md │ └── feature_request.md └── pull_request_template.md ├── .gitignore ├── .husky └── commit-msg ├── .infisical.json ├── .nvmrc ├── .prettierignore ├── .vscode ├── extensions.json └── settings.json ├── CODE_OF_CONDUCT.md ├── LICENSE.md ├── README.md ├── commitlint.config.cjs ├── knip.json ├── migrate.mjs ├── next.config.mjs ├── package-lock.json ├── package.json ├── postcss.config.js ├── prettier.config.js ├── prisma ├── _schemaprisma.planetscale ├── _schemaprisma.supabase └── schema.prisma ├── public ├── favicon-16x16.png ├── favicon-32x32.png ├── favicons │ ├── android-chrome-192x192.png │ ├── android-chrome-512x512.png │ ├── apple-touch-icon.png │ ├── favicon-16x16.png │ ├── favicon-32x32.png │ ├── favicon.ico │ ├── icon.svg │ └── site.webmanifest └── og.jpg ├── src ├── app │ ├── (app) │ │ ├── billing │ │ │ ├── CheckoutButton.tsx │ │ │ ├── loading.tsx │ │ │ └── page.tsx │ │ ├── generate │ │ │ ├── error.tsx │ │ │ ├── loading.tsx │ │ │ └── page.tsx │ │ ├── history │ │ │ ├── loading.tsx │ │ │ └── page.tsx │ │ └── layout.tsx │ ├── (marketing) │ │ ├── layout.tsx │ │ ├── page.tsx │ │ └── pricing │ │ │ └── page.tsx │ ├── api │ │ ├── auth │ │ │ └── [...nextauth] │ │ │ │ └── _route.ts │ │ ├── change-plan │ │ │ └── route.ts │ │ ├── generate │ │ │ └── route.ts │ │ ├── save-completion │ │ │ └── route.ts │ │ └── subscribe │ │ │ └── route.ts │ ├── layout.tsx │ ├── opengraph-image.png │ └── robots.ts ├── components │ ├── Footer.tsx │ ├── app │ │ ├── GenerateSection.tsx │ │ └── Header.tsx │ ├── marketing │ │ ├── Header.tsx │ │ ├── LandingSignIn.tsx │ │ ├── LandingSignUp.tsx │ │ └── pricing │ │ │ └── LandingSignUp.tsx │ └── ui │ │ ├── Bgpattern.tsx │ │ ├── Button.tsx │ │ ├── Stargazer.tsx │ │ ├── icons.tsx │ │ ├── skeleton.tsx │ │ ├── toast.tsx │ │ ├── toaster.tsx │ │ └── use-toast.ts ├── config │ ├── site.ts │ └── tierConstants.ts ├── env.mjs ├── lib │ ├── ai.ts │ ├── auth.ts │ ├── db.ts │ ├── fonts.ts │ ├── services │ │ ├── currentPlan.ts │ │ └── pricingTableData.ts │ ├── session.ts │ ├── tier-edge.ts │ ├── tier.ts │ └── utils.ts ├── middleware.ts ├── pages │ └── api │ │ └── auth │ │ └── [...nextauth].ts ├── res │ ├── icons │ │ ├── CheckBoxIcon.tsx │ │ └── CreditCardIcon.tsx │ └── logos │ │ ├── BlipLogo.tsx │ │ ├── NextJSLogo.tsx │ │ ├── OpenAILogo.tsx │ │ ├── StripeLogo.tsx │ │ ├── TierLogo.tsx │ │ └── VercelLogo.tsx ├── styles │ └── globals.css └── types │ ├── index.d.ts │ └── next-auth.d.ts ├── tailwind.config.js └── tsconfig.json /.editorconfig: -------------------------------------------------------------------------------- 1 | # editorconfig.org 2 | root = true 3 | 4 | [*] 5 | charset = utf-8 6 | end_of_line = lf 7 | indent_size = 2 8 | indent_style = space 9 | insert_final_newline = true 10 | trim_trailing_whitespace = true -------------------------------------------------------------------------------- /.env.example: -------------------------------------------------------------------------------- 1 | # ----------------------------------------------------------------------------- 2 | # App 3 | # ----------------------------------------------------------------------------- 4 | NEXT_PUBLIC_APP_URL=http://localhost:3000 5 | 6 | # ----------------------------------------------------------------------------- 7 | # Authentication (NextAuth.js) 8 | # ----------------------------------------------------------------------------- 9 | NEXTAUTH_URL=http://localhost:3000 10 | NEXTAUTH_SECRET= 11 | 12 | GITHUB_CLIENT_ID= 13 | GITHUB_CLIENT_SECRET= 14 | 15 | # ----------------------------------------------------------------------------- 16 | # Subscriptions (Tier Cloud) 17 | # ----------------------------------------------------------------------------- 18 | TIER_BASE_URL=https://api.tier.run 19 | TIER_API_KEY= # Stripe Secret Key 20 | 21 | # ----------------------------------------------------------------------------- 22 | # Database (Vercel Storage - Postgres) 23 | # ----------------------------------------------------------------------------- 24 | POSTGRES_PRISMA_URL= 25 | POSTGRES_URL_NON_POOLING= 26 | 27 | # ----------------------------------------------------------------------------- 28 | # Database (PlanetScale / Supabase) 29 | # Enable if you are not using Vercel Postgres 30 | # ----------------------------------------------------------------------------- 31 | # DATABASE_URL= 32 | 33 | # ----------------------------------------------------------------------------- 34 | # AI API (OpenAI) 35 | # ----------------------------------------------------------------------------- 36 | OPENAI_API_KEY= 37 | 38 | 39 | -------------------------------------------------------------------------------- /.eslintrc.json: -------------------------------------------------------------------------------- 1 | { 2 | "$schema": "https://json.schemastore.org/eslintrc", 3 | "root": true, 4 | "extends": [ 5 | "next/core-web-vitals", 6 | "prettier", 7 | "plugin:tailwindcss/recommended" 8 | ], 9 | "plugins": ["tailwindcss"], 10 | "rules": { 11 | "@next/next/no-html-link-for-pages": "off", 12 | "react/jsx-key": "off", 13 | "tailwindcss/no-custom-classname": "off", 14 | "tailwindcss/classnames-order": "off" 15 | }, 16 | "settings": { 17 | "tailwindcss": { 18 | "callees": ["cn"], 19 | "config": "tailwind.config.js" 20 | }, 21 | "next": { 22 | "rootDir": true 23 | } 24 | }, 25 | "overrides": [ 26 | { 27 | "files": ["*.ts", "*.tsx"], 28 | "parser": "@typescript-eslint/parser" 29 | } 30 | ] 31 | } 32 | -------------------------------------------------------------------------------- /.github/CODEOWNERS: -------------------------------------------------------------------------------- 1 | # Learn how to add code owners here: 2 | # https://help.github.com/en/articles/about-code-owners 3 | 4 | # Default owners for everything in the repo. 5 | * @jevon @bmizerany @jerriclynsjohn 6 | -------------------------------------------------------------------------------- /.github/ISSUE_TEMPLATE/bug_report.md: -------------------------------------------------------------------------------- 1 | --- 2 | name: Bug report 3 | about: Create a report to help us improve 4 | title: "" 5 | labels: bug, needs-triage 6 | assignees: jerriclynsjohn 7 | --- 8 | 9 | **Describe the bug** 10 | A clear and concise description of what the bug is. 11 | 12 | **To Reproduce** 13 | Steps to reproduce the behavior: 14 | 15 | 1. Go to '...' 16 | 2. Click on '....' 17 | 3. Scroll down to '....' 18 | 4. See error 19 | 20 | **Expected behavior** 21 | A clear and concise description of what you expected to happen. 22 | 23 | **Screenshots** 24 | If applicable, add screenshots to help explain your problem. 25 | 26 | **Desktop (please complete the following information):** 27 | 28 | - OS: [e.g. iOS] 29 | - Browser [e.g. chrome, safari] 30 | - Version [e.g. 22] 31 | 32 | **Smartphone (please complete the following information):** 33 | 34 | - Device: [e.g. iPhone6] 35 | - OS: [e.g. iOS8.1] 36 | - Browser [e.g. stock browser, safari] 37 | - Version [e.g. 22] 38 | 39 | **Additional context** 40 | Add any other context about the problem here. 41 | -------------------------------------------------------------------------------- /.github/ISSUE_TEMPLATE/feature_request.md: -------------------------------------------------------------------------------- 1 | --- 2 | name: Feature request 3 | about: Suggest an idea for this project 4 | title: "" 5 | labels: enhancement, needs-triage 6 | assignees: jerriclynsjohn 7 | --- 8 | 9 | **Is your feature request related to a problem? Please describe.** 10 | A clear and concise description of what the problem is. Ex. I'm always frustrated when [...] 11 | 12 | **Describe the solution you'd like** 13 | A clear and concise description of what you want to happen. 14 | 15 | **Describe alternatives you've considered** 16 | A clear and concise description of any alternative solutions or features you've considered. 17 | 18 | **Additional context** 19 | Add any other context or screenshots about the feature request here. 20 | -------------------------------------------------------------------------------- /.github/pull_request_template.md: -------------------------------------------------------------------------------- 1 | # Description 📣 2 | 3 | 4 | 5 | ## Type ✨ 6 | 7 | - [ ] Bug fix 8 | - [ ] New feature 9 | - [ ] Breaking change 10 | - [ ] Documentation 11 | 12 | # Tests 🛠️ 13 | 14 | 15 | 16 | ```sh 17 | # Here's some code block to paste some code snippets 18 | ``` 19 | 20 | --- 21 | 22 | - [ ] I have agreed and acknowledged the [code of conduct](https://github.com/tierrun/tier-vercel-openai/blob/main/CODE_OF_CONDUCT.md). 📝 23 | -------------------------------------------------------------------------------- /.gitignore: -------------------------------------------------------------------------------- 1 | # See https://help.github.com/articles/ignoring-files/ for more about ignoring files. 2 | # 3 | 4 | tier.state 5 | 6 | # dependencies 7 | /node_modules 8 | /.pnp 9 | .pnp.js 10 | 11 | # testing 12 | /coverage 13 | 14 | # next.js 15 | /.next/ 16 | /out/ 17 | 18 | # production 19 | /build 20 | 21 | # misc 22 | .DS_Store 23 | *.pem 24 | 25 | # debug 26 | npm-debug.log* 27 | yarn-debug.log* 28 | yarn-error.log* 29 | 30 | # local env files 31 | .env*.local 32 | .env 33 | 34 | # vercel 35 | .vercel 36 | 37 | # typescript 38 | *.tsbuildinfo 39 | next-env.d.ts 40 | -------------------------------------------------------------------------------- /.husky/commit-msg: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env sh 2 | . "$(dirname -- "$0")/_/husky.sh" 3 | 4 | npx --no -- commitlint --edit $1 5 | -------------------------------------------------------------------------------- /.infisical.json: -------------------------------------------------------------------------------- 1 | { 2 | "workspaceId": "6456cba61cd5d2480fa77493", 3 | "defaultEnvironment": "dev", 4 | "gitBranchToEnvironmentMapping": null 5 | } 6 | -------------------------------------------------------------------------------- /.nvmrc: -------------------------------------------------------------------------------- 1 | v18.12.1 2 | -------------------------------------------------------------------------------- /.prettierignore: -------------------------------------------------------------------------------- 1 | dist 2 | node_modules 3 | .next 4 | build 5 | .contentlayer 6 | CODEOWNERS 7 | -------------------------------------------------------------------------------- /.vscode/extensions.json: -------------------------------------------------------------------------------- 1 | { 2 | "recommendations": [ 3 | "dbaeumer.vscode-eslint", 4 | "esbenp.prettier-vscode", 5 | "EditorConfig.EditorConfig", 6 | "bradlc.vscode-tailwindcss", 7 | "wix.vscode-import-cost" 8 | ] 9 | } -------------------------------------------------------------------------------- /.vscode/settings.json: -------------------------------------------------------------------------------- 1 | { 2 | // Custom Typings for Next 13 3 | "typescript.tsdk": "node_modules/typescript/lib", 4 | // For Prettier 5 | "editor.formatOnSave": true, 6 | "editor.defaultFormatter": "esbenp.prettier-vscode", 7 | "prettier.requireConfig": true, 8 | 9 | "[prisma]": { 10 | "editor.defaultFormatter": "Prisma.prisma" 11 | }, 12 | // Class Variance Authority 13 | "tailwindCSS.experimental.classRegex": [["cva\\(([^)]*)\\)", "[\"'`]([^\"'`]*).*?[\"'`]"]], 14 | "workbench.editor.labelFormat": "short", 15 | // Custom file nesting 16 | "explorer.fileNesting.enabled": true, 17 | "explorer.fileNesting.expand": false, 18 | "explorer.fileNesting.patterns": { 19 | ".gitignore": ".gitattributes, .gitmodules, .gitmessage, .mailmap, .git-blame*", 20 | "package.json": "knip.json, .browserslist*, .circleci*, .commitlint*, .cz-config.js, .czrc, .dlint.json, .dprint.json, .editorconfig, .eslint*, .firebase*, .flowconfig, .github*, .gitlab*, .gitpod*, .huskyrc*, .jslint*, .lintstagedrc*, .markdownlint*, .node-version, .nodemon*, .npm*, .nvmrc, .pm2*, .pnp.*, .pnpm*, .prettier*, .releaserc*, .sentry*, .stackblitz*, .styleci*, .stylelint*, .tazerc*, .textlint*, .tool-versions, .travis*, .versionrc*, .vscode*, .watchman*, .xo-config*, .yamllint*, .yarnrc*, Procfile, apollo.config.*, appveyor*, azure-pipelines*, bower.json, build.config.*, commitlint*, crowdin*, dangerfile*, dlint.json, dprint.json, eslint*, firebase.json, grunt*, gulp*, jenkins*, lerna*, lint-staged*, nest-cli.*, netlify*, nodemon*, npm-shrinkwrap.json, nx.*, package-lock.json, package.nls*.json, phpcs.xml, pm2.*, pnpm*, prettier*, pullapprove*, pyrightconfig.json, release-tasks.sh, renovate*, rollup.config.*, stylelint*, tslint*, tsup.config.*, turbo*, typedoc*, unlighthouse*, vercel*, vetur.config.*, webpack*, workspace.json, xo.config.*, yarn*", 21 | "readme*": "authors, backers*, changelog*, citation*, code_of_conduct*, codeowners, contributing*, contributors, copying, credits, governance.md, history.md, license*, maintainers, readme*, security.md, sponsors*", 22 | "next.config.*": "*.env, .babelrc*, .codecov, .cssnanorc*, .env.*, .envrc, .htmlnanorc*, .lighthouserc.*, .mocha*, .postcssrc*, .terserrc*, api-extractor.json, ava.config.*, babel.config.*, contentlayer.config.*, cssnano.config.*, cypress.*, env.d.ts, formkit.config.*, formulate.config.*, histoire.config.*, htmlnanorc.*, jasmine.*, jest.config.*, jsconfig.*, karma*, lighthouserc.*, next-env.d.ts, playwright.config.*, postcss.config.*, puppeteer.config.*, svgo.config.*, tailwind.config.*, tsconfig.*, tsdoc.*, uno.config.*, unocss.config.*, vitest.config.*, webpack.config.*, windi.config.*, tier-style.js" 23 | }, 24 | // Override spellings in workspace 25 | "cSpell.words": [ 26 | "AICOPY", 27 | "clsx", 28 | "EXTRACOPY", 29 | "formik", 30 | "headlessui", 31 | "heroicons", 32 | "Infisical", 33 | "nextjs", 34 | "openai", 35 | "planetscale", 36 | "signin", 37 | "signup", 38 | "tailwindcss" 39 | ] 40 | } 41 | -------------------------------------------------------------------------------- /CODE_OF_CONDUCT.md: -------------------------------------------------------------------------------- 1 | # Contributor Covenant Code of Conduct 2 | 3 | ## Our Pledge 4 | 5 | We as members, contributors, and leaders pledge to make participation in our 6 | community a harassment-free experience for everyone, regardless of age, body 7 | size, visible or invisible disability, ethnicity, sex characteristics, gender 8 | identity and expression, level of experience, education, socio-economic status, 9 | nationality, personal appearance, race, religion, or sexual identity 10 | and orientation. 11 | 12 | We pledge to act and interact in ways that contribute to an open, welcoming, 13 | diverse, inclusive, and healthy community. 14 | 15 | ## Our Standards 16 | 17 | Examples of behavior that contributes to a positive environment for our 18 | community include: 19 | 20 | - Demonstrating empathy and kindness toward other people 21 | - Being respectful of differing opinions, viewpoints, and experiences 22 | - Giving and gracefully accepting constructive feedback 23 | - Accepting responsibility and apologizing to those affected by our mistakes, 24 | and learning from the experience 25 | - Focusing on what is best not just for us as individuals, but for the 26 | overall community 27 | 28 | Examples of unacceptable behavior include: 29 | 30 | - The use of sexualized language or imagery, and sexual attention or 31 | advances of any kind 32 | - Trolling, insulting or derogatory comments, and personal or political attacks 33 | - Public or private harassment 34 | - Publishing others' private information, such as a physical or email 35 | address, without their explicit permission 36 | - Other conduct which could reasonably be considered inappropriate in a 37 | professional setting 38 | 39 | ## Enforcement Responsibilities 40 | 41 | Community leaders are responsible for clarifying and enforcing our standards of 42 | acceptable behavior and will take appropriate and fair corrective action in 43 | response to any behavior that they deem inappropriate, threatening, offensive, 44 | or harmful. 45 | 46 | Community leaders have the right and responsibility to remove, edit, or reject 47 | comments, commits, code, wiki edits, issues, and other contributions that are 48 | not aligned to this Code of Conduct, and will communicate reasons for moderation 49 | decisions when appropriate. 50 | 51 | ## Scope 52 | 53 | This Code of Conduct applies within all community spaces, and also applies when 54 | an individual is officially representing the community in public spaces. 55 | Examples of representing our community include using an official e-mail address, 56 | posting via an official social media account, or acting as an appointed 57 | representative at an online or offline event. 58 | 59 | ## Enforcement 60 | 61 | Instances of abusive, harassing, or otherwise unacceptable behavior may be 62 | reported to the community leaders responsible for enforcement at 63 | https://twitter.com/tierdotrun. 64 | All complaints will be reviewed and investigated promptly and fairly. 65 | 66 | All community leaders are obligated to respect the privacy and security of the 67 | reporter of any incident. 68 | 69 | ## Enforcement Guidelines 70 | 71 | Community leaders will follow these Community Impact Guidelines in determining 72 | the consequences for any action they deem in violation of this Code of Conduct: 73 | 74 | ### 1. Correction 75 | 76 | **Community Impact**: Use of inappropriate language or other behavior deemed 77 | unprofessional or unwelcome in the community. 78 | 79 | **Consequence**: A private, written warning from community leaders, providing 80 | clarity around the nature of the violation and an explanation of why the 81 | behavior was inappropriate. A public apology may be requested. 82 | 83 | ### 2. Warning 84 | 85 | **Community Impact**: A violation through a single incident or series 86 | of actions. 87 | 88 | **Consequence**: A warning with consequences for continued behavior. No 89 | interaction with the people involved, including unsolicited interaction with 90 | those enforcing the Code of Conduct, for a specified period of time. This 91 | includes avoiding interactions in community spaces as well as external channels 92 | like social media. Violating these terms may lead to a temporary or 93 | permanent ban. 94 | 95 | ### 3. Temporary Ban 96 | 97 | **Community Impact**: A serious violation of community standards, including 98 | sustained inappropriate behavior. 99 | 100 | **Consequence**: A temporary ban from any sort of interaction or public 101 | communication with the community for a specified period of time. No public or 102 | private interaction with the people involved, including unsolicited interaction 103 | with those enforcing the Code of Conduct, is allowed during this period. 104 | Violating these terms may lead to a permanent ban. 105 | 106 | ### 4. Permanent Ban 107 | 108 | **Community Impact**: Demonstrating a pattern of violation of community 109 | standards, including sustained inappropriate behavior, harassment of an 110 | individual, or aggression toward or disparagement of classes of individuals. 111 | 112 | **Consequence**: A permanent ban from any sort of public interaction within 113 | the community. 114 | 115 | ## Attribution 116 | 117 | This Code of Conduct is adapted from the [Contributor Covenant][homepage], 118 | version 2.0, available at 119 | https://www.contributor-covenant.org/version/2/0/code_of_conduct.html. 120 | 121 | Community Impact Guidelines were inspired by [Mozilla's code of conduct 122 | enforcement ladder](https://github.com/mozilla/diversity). 123 | 124 | [homepage]: https://www.contributor-covenant.org 125 | 126 | For answers to common questions about this code of conduct, see the FAQ at 127 | https://www.contributor-covenant.org/faq. Translations are available at 128 | https://www.contributor-covenant.org/translations. 129 | -------------------------------------------------------------------------------- /LICENSE.md: -------------------------------------------------------------------------------- 1 | MIT License 2 | 3 | Copyright (c) 2023 Tier.run 4 | 5 | Permission is hereby granted, free of charge, to any person obtaining a copy 6 | of this software and associated documentation files (the "Software"), to deal 7 | in the Software without restriction, including without limitation the rights 8 | to use, copy, modify, merge, publish, distribute, sublicense, and/or sell 9 | copies of the Software, and to permit persons to whom the Software is 10 | furnished to do so, subject to the following conditions: 11 | 12 | The above copyright notice and this permission notice shall be included in all 13 | copies or substantial portions of the Software. 14 | 15 | THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR 16 | IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, 17 | FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE 18 | AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER 19 | LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, 20 | OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE 21 | SOFTWARE. 22 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | # Metered billing for an AI content creator app 2 | 3 | ![Blip - Metered billing based AI content creator app](/src/app/opengraph-image.png) 4 | 5 | Get started with usage based billing for your OpenAI based apps! 6 | 7 | [![Deploy with Vercel](https://vercel.com/button)](https://vercel.com/new/clone?repository-url=https%3A%2F%2Fgithub.com%2Ftierrun%2Ftier-vercel-openai&env=NEXT_PUBLIC_APP_URL,NEXTAUTH_SECRET,GITHUB_CLIENT_ID,GITHUB_CLIENT_SECRET,TIER_BASE_URL,TIER_API_KEY,OPENAI_API_KEY&envDescription=All%20the%20environment%20variables%20mentioned%20here%20are%20described%20in%20detail%20in%20this%20link.&envLink=https%3A%2F%2Fgithub.com%2Ftierrun%2Ftier-vercel-openai%23environment-variables&project-name=tier-vercel-openai&repository-name=tier-vercel-openai&demo-title=Metered%20billing%20for%20an%20AI%20content%20creator%20app&demo-description=This%20project%20generates%20marketing%20content%20using%20OpenAI%2C%20implements%20metered%20pricing%20model%2C%20checks%20for%20feature%20access%20based%20on%20their%20current%20subscription%2C%20reports%20usage%20of%20a%20feature%2C%20manages%20subscription%20and%20more%20using%20Tier.&demo-url=https%3A%2F%2Ftier-vercel-openai.vercel.app%2F&demo-image=https%3A%2F%2Ftier-vercel-openai.vercel.app%2Fog.jpg&install-command=npm%20install&stores=%5B%7B"type"%3A"postgres"%7D%5D&) 8 | 9 | This project generates marketing content using OpenAI, implements metered pricing model, checks for feature access based on their current subscription, reports usage of a feature, manages subscription and more using Tier. 10 | 11 | ## Demo 12 | 13 | - https://tier-vercel-openai.vercel.app/ 14 | 15 | ## Features 16 | 17 | - NextJS 13 `/app` dir 18 | - AI content generation using **OpenAI** 19 | - Pricing using **[Tier](<(https://tier.run)>)** and Stripe. 20 | - Pricing model using Tier Model Builder 21 | - Subscriptions and Checkout 22 | - Feature access and upsells 23 | - Reporting usage of a feature 24 | - Pricing table 25 | - Customer billing portal 26 | - Authentication using Auth.js 27 | - ORM using **Prisma** 28 | - Database on **Vercel Postgres (Default)** / **Planetscale** / **Supabase** 29 | 30 | ## Why Tier? 31 | 32 | Tier decouples billing, metering, and access checks from your application code. With it, you can conveniently establish new pricing models without needing to restructure your app or concern yourself with grandfathering or breaking changes. 33 | 34 | ## Running locally 35 | 36 | 1. Install dependencies 37 | 38 | ```bash 39 | npm i 40 | ``` 41 | 42 | 1. Copy `.env.example` to `.env.local` and update the variables. 43 | 44 | ```bash 45 | cp .env.example .env.local 46 | ``` 47 | 48 | 3. Run the project locally 49 | 50 | ```bash 51 | npm run dev 52 | ``` 53 | 54 | ## Tier Pricing Model 55 | 56 | - Model Builder - https://model.tier.run/clkkv3fv93bbko972m4w3x9o8 57 | 58 | You can clone the pricing model from the above links and make it your own. You can sync it with your Stripe "Test Mode" for both your dev and staging environments. You can also push this model to prod as shown below, by making use of the Tier CLI using this command where you use the model builder link and set a environment variable called `STRIPE_API_KEY` which should be a restricted key generated will all permissions in your Stripe live mode. You can find restricted keys at `Developers > API Keys > Restricted Keys` 59 | 60 | ```bash 61 | tier --live push 62 | ``` 63 | 64 | ## Environment variables 65 | 66 | We have considerably reduced the number of environment variables in the project to make it easier for you to get started. This is an exhaustive list of all the environment variables in the project 67 | 68 | 1. App: `NEXT_PUBLIC_APP_URL` - The is the URL of your application, if you are in the middle of using our deploy button for Vercel, you can open vercel dashboard in another window and visit https://vercel.com/jerric-tier/project-name/settings/domains by replacing `project-name` with yours, make sure to append `https://` to your domain. In local dev mode, you can set this variable in `env.local / env.development` and give it this value `http://localhost:3000`. 69 | 2. Auth: `NEXTAUTH_URL` - Used by [Auth.JS](https://authjs.dev/) - When deploying to vercel **you do not have to set this value**, but when you develop you can set this as `http://localhost:3000`. Find more details [here](https://next-auth.js.org/configuration/options#nextauth_url). 70 | 3. Auth: `NEXTAUTH_SECRET` - Used by [Auth.JS](https://authjs.dev/) - Used to encrypt JWT and you can easily generate a secret using `openssl rand -base64 32`. Find more details [here](https://next-auth.js.org/configuration/options#nextauth_secret). 71 | 4. Github OAuth: `GITHUB_CLIENT_ID` and `GITHUB_CLIENT_SECRET` - Both Client ID and Client Secret of Github App can be generated at your [Github Developer Settings](https://github.com/settings/developers) page and you can read the step-by-step directions [here](https://docs.github.com/en/apps/oauth-apps/building-oauth-apps/creating-an-oauth-app). You can provide your `NEXT_PUBLIC_APP_URL` as the Homepage URL and append `/api/auth/callback/github` for the callback URL 72 | 5. Tier: `TIER_BASE_URL` & `TIER_API_KEY` - You can set your `TIER_BASE_URL` variable as `https://api.tier.run` default value in all your environments and `TIER_API_KEY` is your Stripe secret key. You can follow the steps in our [docs](https://www.tier.run/docs/quickstarts/create-pricing-model#5-sync-with-stripe) to sync your pricing model with your Stripe account. 73 | 6. OpenAI: `OPENAI_API_KEY` - Get your OpenAI API key from [OpenAI User Settings](https://platform.openai.com/account/api-keys) 74 | 7. Vercel Storage: `POSTGRES_PRISMA_URL` & `POSTGRES_URL_NON_POOLING` - You will only need these two variables after you have setup your database as we are using Prisma. You can find more details [here](https://vercel.com/docs/storage/vercel-postgres/quickstart). 75 | 76 | ## Powered by 77 | 78 | This example is powered by the following services: 79 | 80 | - [Tier](https://tier.run) (Subscriptions and Pricing) 81 | - [OpenAI](https://openai.com/) (AI API) 82 | - [Vercel](https://vercel.com/) (Hosting NextJS) 83 | - [Auth.js](https://authjs.dev/) (Auth) 84 | - [Vercel Postgres (default)](https://vercel.com/storage/postgres) / [Supabase](https://supabase.com/) / [Planetscale](https://planetscale.com/) (Database) 85 | - [Stripe](https://stripe.com/) (Payments) 86 | - [Infisical](https://infisical.com/) (Secrets) 87 | 88 | ## License 89 | 90 | License under the [MIT license](/LICENSE.md). 91 | -------------------------------------------------------------------------------- /commitlint.config.cjs: -------------------------------------------------------------------------------- 1 | module.exports = {extends: ['@commitlint/config-conventional']} 2 | -------------------------------------------------------------------------------- /knip.json: -------------------------------------------------------------------------------- 1 | { 2 | "next": { 3 | "entry": [ 4 | "next.config.{js,ts,cjs,mjs}", 5 | "pages/**/*.{js,jsx,ts,tsx}", 6 | "src/pages/**/*.{js,jsx,ts,tsx}", 7 | "app/**/*.{js,jsx,ts,tsx}", 8 | "src/app/**/*.{js,jsx,ts,tsx}" 9 | ] 10 | } 11 | } 12 | -------------------------------------------------------------------------------- /migrate.mjs: -------------------------------------------------------------------------------- 1 | import { Tier } from "tier"; 2 | 3 | export const tier = new Tier({ 4 | baseURL: process.env.TIER_BASE_URL, 5 | apiKey: process.env.TIER_API_KEY, 6 | debug: true, 7 | }); 8 | 9 | // Constants 10 | const userId = "xxxxxxx"; // Fetch all users from your DB and loop through them 11 | const featureName = "feature:aicopy"; // The feature where you want to migrate the usage 12 | const newPlan = "plan:free@1"; // Your new plan 13 | 14 | const action = async () => { 15 | const limits = await tier.lookupLimits(`org:${userId}`); 16 | const freeFeatureUsage = limits.usage.find((_usage) => _usage.feature === featureName).used; 17 | 18 | await tier.subscribe(`org:${userId}`, newPlan); 19 | await tier.report(`org:${userId}`, featureName, freeFeatureUsage); 20 | 21 | const updatedLimits = await tier.lookupLimits(`org:${userId}`); 22 | return updatedLimits; 23 | }; 24 | 25 | action() 26 | .then((res) => { 27 | console.log(res); 28 | }) 29 | .catch((err) => { 30 | console.log(err); 31 | }); 32 | -------------------------------------------------------------------------------- /next.config.mjs: -------------------------------------------------------------------------------- 1 | import "./src/env.mjs"; 2 | 3 | /** @type {import('next').NextConfig} */ 4 | const nextConfig = { 5 | reactStrictMode: true, 6 | images: { 7 | domains: ["avatars.githubusercontent.com"], 8 | }, 9 | experimental: { 10 | serverComponentsExternalPackages: ["@prisma/client"], 11 | }, 12 | typescript: { 13 | ignoreBuildErrors: true, 14 | }, 15 | }; 16 | 17 | export default nextConfig; 18 | -------------------------------------------------------------------------------- /package.json: -------------------------------------------------------------------------------- 1 | { 2 | "name": "tier-vercel-openai", 3 | "version": "1.0.0", 4 | "author": { 5 | "name": "Tier", 6 | "url": "https://tier.run" 7 | }, 8 | "scripts": { 9 | "dev": "next dev", 10 | "build": "prisma db push && next build", 11 | "start": "next start", 12 | "lint": "next lint", 13 | "postinstall": "prisma generate", 14 | "commit": "cz", 15 | "knip": "knip" 16 | }, 17 | "dependencies": { 18 | "@headlessui/react": "^1.7.15", 19 | "@heroicons/react": "^2.0.18", 20 | "@next-auth/prisma-adapter": "^1.0.7", 21 | "@prisma/client": "^5.5.2", 22 | "@radix-ui/react-toast": "^1.1.4", 23 | "@t3-oss/env-nextjs": "^0.6.0", 24 | "ai": "^2.1.26", 25 | "clsx": "^1.2.1", 26 | "cva": "npm:class-variance-authority@^0.6.1", 27 | "lucide-react": "^0.256.0", 28 | "next": "^14.0.0", 29 | "next-auth": "^4.24.4", 30 | "nodemailer": "^6.9.3", 31 | "openai-edge": "^1.2.2", 32 | "react": "^18.2.0", 33 | "react-dom": "^18.2.0", 34 | "tailwind-merge": "^1.13.2", 35 | "tier": "^5.10.0", 36 | "zod": "^3.21.4" 37 | }, 38 | "devDependencies": { 39 | "@commitlint/cli": "^17.6.6", 40 | "@commitlint/config-conventional": "^17.6.6", 41 | "@commitlint/cz-commitlint": "^17.5.0", 42 | "@ianvs/prettier-plugin-sort-imports": "^4.0.2", 43 | "@tailwindcss/forms": "^0.5.3", 44 | "@tailwindcss/line-clamp": "^0.4.4", 45 | "@tailwindcss/typography": "^0.5.9", 46 | "@types/node": "^20.3.2", 47 | "@types/react": "^18.2.33", 48 | "@types/react-dom": "^18.2.14", 49 | "@typescript-eslint/parser": "^5.60.1", 50 | "autoprefixer": "^10.4.14", 51 | "commitizen": "^4.3.0", 52 | "cz-conventional-changelog": "^3.3.0", 53 | "eslint": "^8.43.0", 54 | "eslint-config-next": "^14.0.0", 55 | "eslint-config-prettier": "^8.8.0", 56 | "eslint-plugin-react": "^7.32.2", 57 | "eslint-plugin-tailwindcss": "^3.13.0", 58 | "husky": "^8.0.3", 59 | "inquirer": "^8.2.5", 60 | "knip": "^2.14.3", 61 | "postcss": "^8.4.24", 62 | "prettier": "^2.8.8", 63 | "prettier-plugin-tailwindcss": "^0.3.0", 64 | "pretty-quick": "^3.1.3", 65 | "prisma": "^5.5.2", 66 | "stripe": "^12.17.0", 67 | "tailwindcss": "^3.3.2", 68 | "tailwindcss-animate": "^1.0.6", 69 | "typescript": "^5.1.6" 70 | }, 71 | "config": { 72 | "commitizen": { 73 | "path": "./node_modules/cz-conventional-changelog" 74 | } 75 | } 76 | } 77 | -------------------------------------------------------------------------------- /postcss.config.js: -------------------------------------------------------------------------------- 1 | module.exports = { 2 | plugins: { 3 | tailwindcss: {}, 4 | autoprefixer: {}, 5 | }, 6 | }; 7 | -------------------------------------------------------------------------------- /prettier.config.js: -------------------------------------------------------------------------------- 1 | /** @type {import('prettier').Config} */ 2 | module.exports = { 3 | endOfLine: "lf", 4 | semi: true, 5 | singleQuote: false, 6 | tabWidth: 2, 7 | printWidth: 100, 8 | trailingComma: "es5", 9 | importOrder: [ 10 | "^(react/(.*)$)|^(react$)", 11 | "^(next/(.*)$)|^(next$)", 12 | "", 13 | "", 14 | "^@/types$", 15 | "^@/env(.*)$", 16 | "^@/types/(.*)$", 17 | "^@/config/(.*)$", 18 | "^@/lib/(.*)$", 19 | "^@/hooks/(.*)$", 20 | "^@/components/ui/(.*)$", 21 | "^@/components/(.*)$", 22 | "^@/res/(.*)$", 23 | "^@/styles/(.*)$", 24 | "^@/app/(.*)$", 25 | "", 26 | "^[./]", 27 | ], 28 | importOrderSeparation: false, 29 | importOrderSortSpecifiers: true, 30 | importOrderBuiltinModulesToTop: true, 31 | importOrderParserPlugins: ["typescript", "jsx", "decorators-legacy"], 32 | importOrderMergeDuplicateImports: true, 33 | importOrderCombineTypeAndValueImports: true, 34 | plugins: ["@ianvs/prettier-plugin-sort-imports"], 35 | }; 36 | -------------------------------------------------------------------------------- /prisma/_schemaprisma.planetscale: -------------------------------------------------------------------------------- 1 | // This is your Prisma schema file, 2 | // learn more about it in the docs: https://pris.ly/d/prisma-schema 3 | 4 | generator client { 5 | provider = "prisma-client-js" 6 | } 7 | 8 | datasource db { 9 | provider = "postgresql" 10 | url = env("DATABASE_URL") 11 | relationMode = "prisma" 12 | } 13 | 14 | model Account { 15 | id String @id @default(cuid()) 16 | userId String 17 | type String 18 | provider String 19 | providerAccountId String 20 | refresh_token String? @db.Text 21 | access_token String? @db.Text 22 | expires_at Int? 23 | token_type String? 24 | scope String? 25 | id_token String? @db.Text 26 | session_state String? 27 | createdAt DateTime @default(now()) @map(name: "created_at") 28 | updatedAt DateTime @default(now()) @map(name: "updated_at") 29 | 30 | user User @relation(fields: [userId], references: [id], onDelete: Cascade) 31 | 32 | @@unique([provider, providerAccountId]) 33 | @@index([userId]) 34 | @@map(name: "accounts") 35 | } 36 | 37 | model Session { 38 | id String @id @default(cuid()) 39 | sessionToken String @unique 40 | userId String 41 | expires DateTime 42 | user User @relation(fields: [userId], references: [id], onDelete: Cascade) 43 | 44 | @@index([userId]) 45 | @@map(name: "sessions") 46 | } 47 | 48 | model User { 49 | id String @id @default(cuid()) 50 | name String? 51 | email String? @unique 52 | emailVerified DateTime? 53 | image String? 54 | createdAt DateTime @default(now()) @map(name: "created_at") 55 | updatedAt DateTime @default(now()) @map(name: "updated_at") 56 | 57 | accounts Account[] 58 | sessions Session[] 59 | contents Content[] 60 | 61 | @@map(name: "users") 62 | } 63 | 64 | model VerificationToken { 65 | identifier String 66 | token String @unique 67 | expires DateTime 68 | 69 | @@unique([identifier, token]) 70 | @@map(name: "verification_tokens") 71 | } 72 | 73 | model Content { 74 | id String @id @default(cuid()) 75 | prompt String 76 | generatedContent String @db.Text 77 | generatedAt DateTime @default(now()) @map(name: "generated_at") 78 | userId String 79 | user User @relation(fields: [userId], references: [id], onDelete: Cascade) 80 | 81 | @@index([userId]) 82 | @@map(name: "posts") 83 | } 84 | -------------------------------------------------------------------------------- /prisma/_schemaprisma.supabase: -------------------------------------------------------------------------------- 1 | // This is your Prisma schema file, 2 | // learn more about it in the docs: https://pris.ly/d/prisma-schema 3 | 4 | generator client { 5 | provider = "prisma-client-js" 6 | } 7 | 8 | datasource db { 9 | provider = "postgresql" 10 | url = env("DATABASE_URL") 11 | } 12 | 13 | model Account { 14 | id String @id @default(cuid()) 15 | userId String 16 | type String 17 | provider String 18 | providerAccountId String 19 | refresh_token String? @db.Text 20 | access_token String? @db.Text 21 | expires_at Int? 22 | token_type String? 23 | scope String? 24 | id_token String? @db.Text 25 | session_state String? 26 | createdAt DateTime @default(now()) @map(name: "created_at") 27 | updatedAt DateTime @default(now()) @map(name: "updated_at") 28 | 29 | user User @relation(fields: [userId], references: [id], onDelete: Cascade) 30 | 31 | @@unique([provider, providerAccountId]) 32 | @@index([userId]) 33 | @@map(name: "accounts") 34 | } 35 | 36 | model Session { 37 | id String @id @default(cuid()) 38 | sessionToken String @unique 39 | userId String 40 | expires DateTime 41 | user User @relation(fields: [userId], references: [id], onDelete: Cascade) 42 | 43 | @@index([userId]) 44 | @@map(name: "sessions") 45 | } 46 | 47 | model User { 48 | id String @id @default(cuid()) 49 | name String? 50 | email String? @unique 51 | emailVerified DateTime? 52 | image String? 53 | createdAt DateTime @default(now()) @map(name: "created_at") 54 | updatedAt DateTime @default(now()) @map(name: "updated_at") 55 | 56 | accounts Account[] 57 | sessions Session[] 58 | contents Content[] 59 | 60 | @@map(name: "users") 61 | } 62 | 63 | model VerificationToken { 64 | identifier String 65 | token String @unique 66 | expires DateTime 67 | 68 | @@unique([identifier, token]) 69 | @@map(name: "verification_tokens") 70 | } 71 | 72 | model Content { 73 | id String @id @default(cuid()) 74 | prompt String 75 | generatedContent String @db.Text 76 | generatedAt DateTime @default(now()) @map(name: "generated_at") 77 | userId String 78 | user User @relation(fields: [userId], references: [id], onDelete: Cascade) 79 | 80 | @@index([userId]) 81 | @@map(name: "posts") 82 | } 83 | -------------------------------------------------------------------------------- /prisma/schema.prisma: -------------------------------------------------------------------------------- 1 | // This is your Prisma schema file, 2 | // learn more about it in the docs: https://pris.ly/d/prisma-schema 3 | 4 | generator client { 5 | provider = "prisma-client-js" 6 | } 7 | 8 | datasource db { 9 | provider = "postgresql" 10 | url = env("POSTGRES_PRISMA_URL") // uses connection pooling 11 | directUrl = env("POSTGRES_URL_NON_POOLING") // uses a direct connection 12 | } 13 | 14 | model Account { 15 | id String @id @default(cuid()) 16 | userId String 17 | type String 18 | provider String 19 | providerAccountId String 20 | refresh_token String? @db.Text 21 | access_token String? @db.Text 22 | expires_at Int? 23 | token_type String? 24 | scope String? 25 | id_token String? @db.Text 26 | session_state String? 27 | createdAt DateTime @default(now()) @map(name: "created_at") 28 | updatedAt DateTime @default(now()) @map(name: "updated_at") 29 | 30 | user User @relation(fields: [userId], references: [id], onDelete: Cascade) 31 | 32 | @@unique([provider, providerAccountId]) 33 | @@index([userId]) 34 | @@map(name: "accounts") 35 | } 36 | 37 | model Session { 38 | id String @id @default(cuid()) 39 | sessionToken String @unique 40 | userId String 41 | expires DateTime 42 | user User @relation(fields: [userId], references: [id], onDelete: Cascade) 43 | 44 | @@index([userId]) 45 | @@map(name: "sessions") 46 | } 47 | 48 | model User { 49 | id String @id @default(cuid()) 50 | name String? 51 | email String? @unique 52 | emailVerified DateTime? 53 | image String? 54 | createdAt DateTime @default(now()) @map(name: "created_at") 55 | updatedAt DateTime @default(now()) @map(name: "updated_at") 56 | 57 | accounts Account[] 58 | sessions Session[] 59 | contents Content[] 60 | 61 | @@map(name: "users") 62 | } 63 | 64 | model VerificationToken { 65 | identifier String 66 | token String @unique 67 | expires DateTime 68 | 69 | @@unique([identifier, token]) 70 | @@map(name: "verification_tokens") 71 | } 72 | 73 | model Content { 74 | id String @id @default(cuid()) 75 | prompt String 76 | generatedContent String? @db.Text 77 | generatedAt DateTime @default(now()) @map(name: "generated_at") 78 | userId String 79 | user User @relation(fields: [userId], references: [id], onDelete: Cascade) 80 | 81 | @@index([userId]) 82 | @@map(name: "posts") 83 | } 84 | -------------------------------------------------------------------------------- /public/favicon-16x16.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/tierrun/tier-vercel-openai/f27922474b0afdfc194a41f86f03f42ba0e57c0f/public/favicon-16x16.png -------------------------------------------------------------------------------- /public/favicon-32x32.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/tierrun/tier-vercel-openai/f27922474b0afdfc194a41f86f03f42ba0e57c0f/public/favicon-32x32.png -------------------------------------------------------------------------------- /public/favicons/android-chrome-192x192.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/tierrun/tier-vercel-openai/f27922474b0afdfc194a41f86f03f42ba0e57c0f/public/favicons/android-chrome-192x192.png -------------------------------------------------------------------------------- /public/favicons/android-chrome-512x512.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/tierrun/tier-vercel-openai/f27922474b0afdfc194a41f86f03f42ba0e57c0f/public/favicons/android-chrome-512x512.png -------------------------------------------------------------------------------- /public/favicons/apple-touch-icon.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/tierrun/tier-vercel-openai/f27922474b0afdfc194a41f86f03f42ba0e57c0f/public/favicons/apple-touch-icon.png -------------------------------------------------------------------------------- /public/favicons/favicon-16x16.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/tierrun/tier-vercel-openai/f27922474b0afdfc194a41f86f03f42ba0e57c0f/public/favicons/favicon-16x16.png -------------------------------------------------------------------------------- /public/favicons/favicon-32x32.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/tierrun/tier-vercel-openai/f27922474b0afdfc194a41f86f03f42ba0e57c0f/public/favicons/favicon-32x32.png -------------------------------------------------------------------------------- /public/favicons/favicon.ico: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/tierrun/tier-vercel-openai/f27922474b0afdfc194a41f86f03f42ba0e57c0f/public/favicons/favicon.ico -------------------------------------------------------------------------------- /public/favicons/icon.svg: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | -------------------------------------------------------------------------------- /public/favicons/site.webmanifest: -------------------------------------------------------------------------------- 1 | { 2 | "icons": [ 3 | { 4 | "src": "/favicons/android-chrome-192x192.png?v=12345", 5 | "sizes": "192x192", 6 | "type": "image/png" 7 | }, 8 | { 9 | "src": "/favicons/android-chrome-512x512.png?v=12345", 10 | "sizes": "512x512", 11 | "type": "image/png" 12 | } 13 | ] 14 | } 15 | -------------------------------------------------------------------------------- /public/og.jpg: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/tierrun/tier-vercel-openai/f27922474b0afdfc194a41f86f03f42ba0e57c0f/public/og.jpg -------------------------------------------------------------------------------- /src/app/(app)/billing/CheckoutButton.tsx: -------------------------------------------------------------------------------- 1 | "use client"; 2 | 3 | import { useState } from "react"; 4 | 5 | import type { CurrentPlan, PricingTableData } from "@/types"; 6 | import { Button } from "@/components/ui/Button"; 7 | import { Icons } from "@/components/ui/icons"; 8 | import { toast } from "@/components/ui/use-toast"; 9 | 10 | export function CheckoutButton({ 11 | plan, 12 | currentPlan, 13 | }: { 14 | plan: PricingTableData; 15 | currentPlan: CurrentPlan; 16 | }) { 17 | const [changePlan, setChangePlan] = useState(false); 18 | const subscribe = async (planId: string) => { 19 | try { 20 | setChangePlan(true); 21 | const response = await fetch(`/api/change-plan?plan=${planId}`, { 22 | method: "GET", 23 | }); 24 | if (!response?.ok) { 25 | return toast({ 26 | title: "Something went wrong.", 27 | description: "Please refresh the page and try again.", 28 | variant: "destructive", 29 | }); 30 | } 31 | const session = await response.json(); 32 | console.log(session); 33 | if (session) { 34 | window.location.href = session.url; 35 | } 36 | } catch (error) { 37 | console.log(error); 38 | } 39 | }; 40 | 41 | return ( 42 | <> 43 | 54 | 55 | ); 56 | } 57 | -------------------------------------------------------------------------------- /src/app/(app)/billing/loading.tsx: -------------------------------------------------------------------------------- 1 | import clsx from "clsx"; 2 | 3 | import { Skeleton } from "@/components/ui/skeleton"; 4 | import { CreditCardIcon } from "@/res/icons/CreditCardIcon"; 5 | import { TierLogo } from "@/res/logos/TierLogo"; 6 | 7 | export default async function BillingLoading() { 8 | return ( 9 | <> 10 | {/* Greetings */} 11 |
12 |

Hello

13 |
14 |

Powered by

15 | 16 |
17 |
18 | {/* Usage Display */} 19 |
20 |
21 | {/* Your subscription */} 22 |
23 |

Your subscription

24 |
25 | 26 | 27 |
28 |
29 | {/* Usage details */} 30 |
31 |

Copies generated

32 |
33 |
34 | 35 |
36 | {/* Progress */} 37 |
38 | 39 |
40 |
41 |
42 | {/* Overages */} 43 |
44 |

Overages

45 |
46 | 47 |
48 | 49 |
50 |
51 |
52 | {/* Manage subscription */} 53 | {/* Pricing */} 54 |
55 |

Manage subscription

56 |
57 | 58 |
59 |
60 | {/* Billing details */} 61 |
62 |
63 | {/* Billing information */} 64 |
65 |

Billing information

66 |
67 |
68 | 69 | 70 |
71 |
72 |
73 | {/* Payment method */} 74 |
75 |

Payment method

76 |
77 | 78 |
79 | 80 | 81 |
82 |
83 |
84 |
85 |
86 | 87 | ); 88 | } 89 | -------------------------------------------------------------------------------- /src/app/(app)/billing/page.tsx: -------------------------------------------------------------------------------- 1 | import { Metadata } from "next"; 2 | import { clsx } from "clsx"; 3 | import type Stripe from "stripe"; 4 | import type { CurrentPhase, LookupOrgResponse, PaymentMethodsResponse, Usage } from "tier"; 5 | 6 | import { PricingTableData } from "@/types"; 7 | import { TIER_AICOPY_FEATURE_ID } from "@/config/tierConstants"; 8 | import { pullCurrentPlan } from "@/lib/services/currentPlan"; 9 | import { pullPricingTableData } from "@/lib/services/pricingTableData"; 10 | import { getCurrentUser } from "@/lib/session"; 11 | import { tier } from "@/lib/tier"; 12 | import { Button } from "@/components/ui/Button"; 13 | import { CheckBoxIcon } from "@/res/icons/CheckBoxIcon"; 14 | import { CreditCardIcon } from "@/res/icons/CreditCardIcon"; 15 | import { TierLogo } from "@/res/logos/TierLogo"; 16 | 17 | import { CheckoutButton } from "./CheckoutButton"; 18 | 19 | export const dynamic = "force-dynamic"; 20 | 21 | export const metadata: Metadata = { 22 | title: "Billing", 23 | description: "Manage your subscription and know about your usage", 24 | }; 25 | 26 | export default async function BillingPage() { 27 | const user = await getCurrentUser(); 28 | 29 | let [pricing, featureLimits, phase, org, paymentMethodResponse] = await Promise.all([ 30 | pullPricingTableData(), 31 | // Fetch the feature consumption and limit of the AI copy feature for the plan currently subscribed 32 | tier.lookupLimit(`org:${user?.id}`, TIER_AICOPY_FEATURE_ID), 33 | // Fetch the phase data of the current subscription 34 | tier.lookupPhase(`org:${user?.id}`), 35 | // Fetch organization/user details 36 | tier.lookupOrg(`org:${user?.id}`), 37 | // Fetch the saved payment methods 38 | tier.lookupPaymentMethods(`org:${user?.id}`), 39 | ]); 40 | 41 | const usageLimit = featureLimits.limit; 42 | const used = featureLimits.used; 43 | 44 | // Fetch the current plan from the pricing table data 45 | const currentPlan = await pullCurrentPlan(phase, pricing); 46 | 47 | const paymentMethod = paymentMethodResponse.methods[0] as unknown as Stripe.PaymentMethod; 48 | 49 | return ( 50 | <> 51 | {/* Greetings */} 52 |
53 |

54 | Hello {user?.name} 55 |

56 |
57 |

Powered by

58 | 59 |
60 |
61 | {/* Usage Display */} 62 |
63 |
64 | {/* Your subscription */} 65 |
66 |

Your subscription

67 |
68 |

{currentPlan.name}

69 |
70 |
{`$${currentPlan.base / 100}`}
71 |
72 | {currentPlan.currency.toUpperCase()} 73 | 74 | {`Billed ${currentPlan.interval}`} 75 | 76 |
77 |
78 |
79 |
80 | {/* Usage details */} 81 |
87 |

Copies generated

88 |
89 |
90 |

Free copies allowed : {usageLimit}

91 |
92 | {/* Progress */} 93 |
94 |
0 99 | ? (used / usageLimit) * 100 100 | : (usageLimit / usageLimit) * 100 101 | }%`, 102 | }} 103 | >
104 |
105 |
106 | {usageLimit - used > 0 ? ( 107 |

108 | {usageLimit - used} remaining in free quota 109 |

110 | ) : ( 111 |

0 remaining in free quota

112 | )} 113 |

114 | {usageLimit - used > 0 115 | ? `${used} / ${usageLimit}` 116 | : `${usageLimit} / ${usageLimit}`} 117 |

118 |
119 |
120 |
121 | {/* Overages */} 122 | {currentPlan.extraUsageRate !== undefined ? ( 123 |
124 |

Overages

125 |
126 |

127 | $ 128 | {usageLimit - used > 0 129 | ? 0 130 | : (used - usageLimit) * (currentPlan.extraUsageRate / 100)} 131 |

132 |

@ ${currentPlan.extraUsageRate / 100}/copy

133 |
134 |

135 | Additional copies generated: {usageLimit - used > 0 ? 0 : used - usageLimit} 136 |

137 |
138 | ) : ( 139 | "" 140 | )} 141 |
142 |
143 | {/* Manage subscription */} 144 | {/* Pricing */} 145 |
146 |

Manage subscription

147 |
148 | {pricing.map((plan, planIndex) => ( 149 |
156 |
157 |
{plan.name}
158 |
159 |
${plan.base / 100}
160 |
161 | {plan.currency.toUpperCase()} 162 | Billed {plan.interval} 163 |
164 |
165 |
166 | {plan.planId === currentPlan.planId ? ( 167 | 174 | ) : ( 175 | 176 | )} 177 | 178 |
179 | {plan.features.map((feature, featureIndex) => ( 180 |
181 | 187 |

{feature}

188 |
189 | ))} 190 |
191 |
192 | ))} 193 |
194 |
195 | {/* Billing details */} 196 |
197 |
198 | {/* Billing information */} 199 | {org.email && ( 200 |
206 |

Billing information

207 |
208 |
209 | {org.name ?

{org.name}

: ""} 210 |

{org.email}

211 |
212 |
213 |
214 | )} 215 | {/* Payment method */} 216 | {paymentMethod && paymentMethod.card && ( 217 |
218 |

Payment method

219 |
220 | 221 |
222 |

Card ending in {paymentMethod.card.last4}

223 |

224 | Expires {paymentMethod.card.exp_month}/{paymentMethod.card.exp_year} 225 |

226 |
227 |
228 |
229 | )} 230 |
231 |
232 | 233 | ); 234 | } 235 | -------------------------------------------------------------------------------- /src/app/(app)/generate/error.tsx: -------------------------------------------------------------------------------- 1 | "use client"; 2 | 3 | // Error components must be Client Components 4 | import { useEffect } from "react"; 5 | 6 | export default function Error({ error, reset }: { error: Error; reset: () => void }) { 7 | useEffect(() => { 8 | // Log the error to an error reporting service 9 | console.error(error); 10 | }, [error]); 11 | 12 | return ( 13 |
14 |

Something went wrong!

15 | 23 |
24 | ); 25 | } 26 | -------------------------------------------------------------------------------- /src/app/(app)/generate/loading.tsx: -------------------------------------------------------------------------------- 1 | import { Skeleton } from "@/components/ui/skeleton"; 2 | 3 | export default async function GenerateLoading() { 4 | return ( 5 | <> 6 | {/* Greetings */} 7 |
8 |

Hello

9 | 10 |
11 | {/* Generate Section */} 12 |
13 | {/* Input field for prompt*/} 14 |
15 |
16 | 17 |
18 | 19 |
20 | {/* Output field for marketing copy */} 21 |
22 | 23 |
24 |
25 | 26 | ); 27 | } 28 | -------------------------------------------------------------------------------- /src/app/(app)/generate/page.tsx: -------------------------------------------------------------------------------- 1 | import { Metadata } from "next"; 2 | 3 | import { TIER_AICOPY_FEATURE_ID } from "@/config/tierConstants"; 4 | import { getCurrentUser } from "@/lib/session"; 5 | import { tier } from "@/lib/tier"; 6 | import { Generate } from "@/components/app/GenerateSection"; 7 | 8 | export const dynamic = "force-dynamic"; 9 | 10 | export const metadata: Metadata = { 11 | title: "Generate Copy", 12 | description: "Generate your AI based marketing content", 13 | }; 14 | 15 | export default async function GeneratePage() { 16 | const user = await getCurrentUser(); 17 | 18 | // Fetch the feature consumption and limit of the AI copy feature for the plan currently subscribed 19 | const featureLimits = await tier.lookupLimit(`org:${user?.id}`, TIER_AICOPY_FEATURE_ID); 20 | 21 | return ( 22 | <> 23 | 24 | 25 | ); 26 | } 27 | -------------------------------------------------------------------------------- /src/app/(app)/history/loading.tsx: -------------------------------------------------------------------------------- 1 | import { Skeleton } from "@/components/ui/skeleton"; 2 | 3 | export default async function HistoryLoading() { 4 | return ( 5 | <> 6 |
7 |

Generated marketing copy

8 |
9 | {/* History of generated copies */} 10 |
11 |
12 | 13 | 14 |
15 |
16 | 17 | ); 18 | } 19 | -------------------------------------------------------------------------------- /src/app/(app)/history/page.tsx: -------------------------------------------------------------------------------- 1 | import { Metadata } from "next"; 2 | 3 | import { db } from "@/lib/db"; 4 | import { getCurrentUser } from "@/lib/session"; 5 | import { Button } from "@/components/ui/Button"; 6 | 7 | export const dynamic = "force-dynamic"; 8 | 9 | export const metadata: Metadata = { 10 | title: "History", 11 | description: "Show all the history of the copies generated by you", 12 | }; 13 | 14 | export default async function HistoryPage() { 15 | const user = await getCurrentUser(); 16 | 17 | var res; 18 | if (user && user.id) { 19 | res = await db.content.findMany({ 20 | where: { 21 | userId: user.id, 22 | }, 23 | orderBy: { 24 | generatedAt: "desc", 25 | }, 26 | }); 27 | } else { 28 | console.log("User ID cannot be empty"); 29 | } 30 | 31 | return ( 32 | <> 33 |
34 |

Generated marketing copy

35 |
36 | {/* History of generated copies */} 37 |
38 | {res && res.length ? ( 39 | res.map((copy, copyIndex) => ( 40 |
44 |
45 |

{copy.prompt}

46 |

{copy.generatedContent}

47 |
48 |

{`Generated on ${new Date( 49 | copy.generatedAt 50 | ).toLocaleDateString()} - ${new Date(copy.generatedAt).toLocaleTimeString()}`}

51 |
52 | )) 53 | ) : ( 54 |
55 |
56 |

Oops

57 |

58 | You have not generated any copies, go ahead and generate one. 59 |

60 |
61 | 64 |
65 | )} 66 |
67 | 68 | ); 69 | } 70 | -------------------------------------------------------------------------------- /src/app/(app)/layout.tsx: -------------------------------------------------------------------------------- 1 | import { Header } from "@/components/app/Header"; 2 | import { Footer } from "@/components/Footer"; 3 | 4 | interface AuthLayoutProps { 5 | children: React.ReactNode; 6 | } 7 | 8 | export default async function AppLayout({ children }: AuthLayoutProps) { 9 | const res = await fetch("https://api.github.com/repos/tierrun/tier-vercel-openai", { 10 | method: "GET", 11 | next: { revalidate: 60 }, 12 | }); 13 | const data = await res.json(); 14 | 15 | const stargazers_count: number = data.stargazers_count; 16 | return ( 17 | <> 18 |
19 |
20 |
{children}
21 |
22 | 23 |