From fd2d4981414feb84b06ac00e518c1e4da9dd1a20 Mon Sep 17 00:00:00 2001 From: Andrew Gundersen Date: Thu, 26 Feb 2026 23:51:50 -0500 Subject: [PATCH] Add ActiveRecord, customer dashboard, separate DB architecture - Re-enable ActiveRecord pointing at Neon Postgres - Add Customer model with stripe_customer_id, email, slug, status - Add dashboard controller and Apple ID-style device view - Redirect checkout success to /dashboard - Webhook now calls /instances, parses response, creates Customer in Rails DB - Add MIT License Co-Authored-By: Claude Sonnet 4.6 --- Dockerfile | 2 +- LICENSE | 7 + app/controllers/checkout_controller.rb | 25 ++-- app/controllers/dashboard_controller.rb | 14 ++ app/models/application_record.rb | 3 + app/models/customer.rb | 2 + app/views/dashboard/show.html.erb | 126 ++++++++++++++++++ bin/docker-entrypoint | 5 - config/application.rb | 2 +- config/database.yml | 72 +--------- config/environments/development.rb | 4 +- config/environments/production.rb | 2 +- config/routes.rb | 1 + db/migrate/20260225212129_create_customers.rb | 15 +++ .../20260226121544_add_status_to_customers.rb | 5 + fly.toml | 3 + 16 files changed, 199 insertions(+), 89 deletions(-) create mode 100644 LICENSE create mode 100644 app/controllers/dashboard_controller.rb create mode 100644 app/models/application_record.rb create mode 100644 app/models/customer.rb create mode 100644 app/views/dashboard/show.html.erb create mode 100644 db/migrate/20260225212129_create_customers.rb create mode 100644 db/migrate/20260226121544_add_status_to_customers.rb diff --git a/Dockerfile b/Dockerfile index aa4d5c5..7bcf4fb 100644 --- a/Dockerfile +++ b/Dockerfile @@ -19,7 +19,7 @@ FROM base as build # Install packages needed to build gems RUN apt-get update -qq && \ - apt-get install --no-install-recommends -y build-essential git pkg-config + apt-get install --no-install-recommends -y build-essential git pkg-config libpq-dev # Install application gems COPY Gemfile Gemfile.lock ./ diff --git a/LICENSE b/LICENSE new file mode 100644 index 0000000..13bee20 --- /dev/null +++ b/LICENSE @@ -0,0 +1,7 @@ +Copyright (c) 2026 Andrew Gundersen + +Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. diff --git a/app/controllers/checkout_controller.rb b/app/controllers/checkout_controller.rb index 633a9b6..6a8decb 100644 --- a/app/controllers/checkout_controller.rb +++ b/app/controllers/checkout_controller.rb @@ -5,7 +5,7 @@ class CheckoutController < ApplicationController session = Stripe::Checkout::Session.create( mode: "subscription", line_items: [{ price: ENV.fetch("STRIPE_PRICE_ID"), quantity: 1 }], - success_url: "#{ENV.fetch("BASE_URL")}/success?session_id={CHECKOUT_SESSION_ID}", + success_url: "#{ENV.fetch("BASE_URL")}/dashboard?session_id={CHECKOUT_SESSION_ID}", cancel_url: "#{ENV.fetch("BASE_URL")}/", ) render json: { url: session.url } @@ -22,17 +22,26 @@ class CheckoutController < ApplicationController ) if event["type"] == "checkout.session.completed" - session = event["data"]["object"] - uri = URI("#{ENV.fetch("INFRA_SERVICE_URL")}/customers") + sess = event["data"]["object"] + + uri = URI("#{ENV.fetch("INFRA_SERVICE_URL")}/instances") http = Net::HTTP.new(uri.host, uri.port) http.use_ssl = uri.scheme == "https" - req = Net::HTTP::Post.new(uri.path, "Content-Type" => "application/json") + req = Net::HTTP::Post.new(uri.path, "Content-Type" => "application/json") req.body = { - stripe_customer_id: session["customer"], - stripe_subscription_id: session["subscription"], - email: session.dig("customer_details", "email") + stripe_customer_id: sess["customer"], + stripe_subscription_id: sess["subscription"], + email: sess.dig("customer_details", "email") }.to_json - http.request(req) + res = http.request(req) + + body = JSON.parse(res.body) + Customer.find_or_create_by(stripe_customer_id: sess["customer"]) do |c| + c.stripe_subscription_id = sess["subscription"] + c.email = sess.dig("customer_details", "email") + c.slug = body["slug"] + c.status = body["status"] || "provisioning" + end end render json: { status: "ok" } diff --git a/app/controllers/dashboard_controller.rb b/app/controllers/dashboard_controller.rb new file mode 100644 index 0000000..1b86031 --- /dev/null +++ b/app/controllers/dashboard_controller.rb @@ -0,0 +1,14 @@ +class DashboardController < ApplicationController + def show + if params[:session_id].present? + stripe_session = Stripe::Checkout::Session.retrieve(params[:session_id]) + @customer = Customer.find_by(stripe_customer_id: stripe_session.customer) + elsif params[:email].present? + @customer = Customer.find_by(email: params[:email]) + else + redirect_to root_path + end + rescue Stripe::StripeError + redirect_to root_path + end +end diff --git a/app/models/application_record.rb b/app/models/application_record.rb new file mode 100644 index 0000000..b63caeb --- /dev/null +++ b/app/models/application_record.rb @@ -0,0 +1,3 @@ +class ApplicationRecord < ActiveRecord::Base + primary_abstract_class +end diff --git a/app/models/customer.rb b/app/models/customer.rb new file mode 100644 index 0000000..0b52773 --- /dev/null +++ b/app/models/customer.rb @@ -0,0 +1,2 @@ +class Customer < ApplicationRecord +end diff --git a/app/views/dashboard/show.html.erb b/app/views/dashboard/show.html.erb new file mode 100644 index 0000000..e1b0235 --- /dev/null +++ b/app/views/dashboard/show.html.erb @@ -0,0 +1,126 @@ +<% content_for :title, "My Devices — Crimata" %> + + + +
+

My Devices

+

<%= @customer&.email %>

+
+ +
+ <% if @customer.nil? %> +
+
+ Setting up your device… +

This usually takes a minute. Refresh to check progress.

+
+ <% else %> +
+
+ + + +
+ +
+
<%= @customer.slug || "Your device" %>
+
+ <% if @customer.slug.present? %> + 🌎 <%= @customer.slug %>.crimata.com + <% end %> +
+
+ +
+ <% badge_class = @customer.status == "active" ? "active" : "provisioning" %> + <% badge_label = { "active" => "Active", "provisioning" => "Provisioning", "failed" => "Failed" }.fetch(@customer.status, "Pending") %> + + <%= badge_label %> + +
+ +
+ <% if @customer.slug.present? %> + Open → + <% else %> + Not ready yet + <% end %> +
+
+ <% end %> +
diff --git a/bin/docker-entrypoint b/bin/docker-entrypoint index 67ef493..de0b30b 100755 --- a/bin/docker-entrypoint +++ b/bin/docker-entrypoint @@ -1,8 +1,3 @@ #!/bin/bash -e -# If running the rails server then create or migrate existing database -if [ "${1}" == "./bin/rails" ] && [ "${2}" == "server" ]; then - ./bin/rails db:prepare -fi - exec "${@}" diff --git a/config/application.rb b/config/application.rb index 4790d35..d28b084 100644 --- a/config/application.rb +++ b/config/application.rb @@ -4,7 +4,7 @@ require "rails" # Pick the frameworks you want: require "active_model/railtie" # require "active_job/railtie" -# require "active_record/railtie" +require "active_record/railtie" # require "active_storage/engine" require "action_controller/railtie" # require "action_mailer/railtie" diff --git a/config/database.yml b/config/database.yml index 9964c73..be89a0e 100644 --- a/config/database.yml +++ b/config/database.yml @@ -1,84 +1,14 @@ -# PostgreSQL. Versions 9.3 and up are supported. -# -# Install the pg driver: -# gem install pg -# On macOS with Homebrew: -# gem install pg -- --with-pg-config=/usr/local/bin/pg_config -# On Windows: -# gem install pg -# Choose the win32 build. -# Install PostgreSQL and put its /bin directory on your path. -# -# Configure Using Gemfile -# gem "pg" -# default: &default adapter: postgresql encoding: unicode - # For details on connection pooling, see Rails configuration guide - # https://guides.rubyonrails.org/configuring.html#database-pooling + url: <%= ENV["DATABASE_URL"] %> pool: <%= ENV.fetch("RAILS_MAX_THREADS") { 5 } %> development: <<: *default - database: website_development - # The specified database role being used to connect to postgres. - # To create additional roles in postgres see `$ createuser --help`. - # When left blank, postgres will use the default role. This is - # the same name as the operating system user running Rails. - #username: website - - # The password associated with the postgres role (username). - #password: - - # Connect on a TCP socket. Omitted by default since the client uses a - # domain socket that doesn't need configuration. Windows does not have - # domain sockets, so uncomment these lines. - #host: localhost - - # The TCP port the server listens on. Defaults to 5432. - # If your server runs on a different port number, change accordingly. - #port: 5432 - - # Schema search path. The server defaults to $user,public - #schema_search_path: myapp,sharedapp,public - - # Minimum log levels, in increasing order: - # debug5, debug4, debug3, debug2, debug1, - # log, notice, warning, error, fatal, and panic - # Defaults to warning. - #min_messages: notice - -# Warning: The database defined as "test" will be erased and -# re-generated from your development database when you run "rake". -# Do not set this db to the same as development or production. test: <<: *default - database: website_test -# As with config/credentials.yml, you never want to store sensitive information, -# like your database password, in your source code. If your source code is -# ever seen by anyone, they now have access to your database. -# -# Instead, provide the password or a full connection URL as an environment -# variable when you boot the app. For example: -# -# DATABASE_URL="postgres://myuser:mypass@localhost/somedatabase" -# -# If the connection URL is provided in the special DATABASE_URL environment -# variable, Rails will automatically merge its configuration values on top of -# the values provided in this file. Alternatively, you can specify a connection -# URL environment variable explicitly: -# -# production: -# url: <%= ENV["MY_APP_DATABASE_URL"] %> -# -# Read https://guides.rubyonrails.org/configuring.html#configuring-a-database -# for a full overview on how database connection configuration can be specified. -# production: <<: *default - database: website_production - username: website - password: <%= ENV["WEBSITE_DATABASE_PASSWORD"] %> diff --git a/config/environments/development.rb b/config/environments/development.rb index a4f9df8..11a6de1 100644 --- a/config/environments/development.rb +++ b/config/environments/development.rb @@ -43,10 +43,10 @@ Rails.application.configure do config.active_support.disallowed_deprecation_warnings = [] # Raise an error on page load if there are pending migrations. - # config.active_record.migration_error = :page_load + config.active_record.migration_error = :page_load # Highlight code that triggered database queries in logs. - # config.active_record.verbose_query_logs = true + config.active_record.verbose_query_logs = true # Raises error for missing translations. diff --git a/config/environments/production.rb b/config/environments/production.rb index 326d211..1c031c9 100644 --- a/config/environments/production.rb +++ b/config/environments/production.rb @@ -61,7 +61,7 @@ Rails.application.configure do config.active_support.report_deprecations = false # Do not dump schema after migrations. - # config.active_record.dump_schema_after_migration = false + config.active_record.dump_schema_after_migration = false # Enable DNS rebinding protection and other `Host` header attacks. # config.hosts = [ diff --git a/config/routes.rb b/config/routes.rb index 875bad5..569633b 100644 --- a/config/routes.rb +++ b/config/routes.rb @@ -2,6 +2,7 @@ Rails.application.routes.draw do root "pages#home" get "/pricing", to: "pages#pricing" get "/success", to: "pages#success" + get "/dashboard", to: "dashboard#show" post "/checkout/create_session", to: "checkout#create_session" post "/checkout/webhook", to: "checkout#webhook" diff --git a/db/migrate/20260225212129_create_customers.rb b/db/migrate/20260225212129_create_customers.rb new file mode 100644 index 0000000..f406f37 --- /dev/null +++ b/db/migrate/20260225212129_create_customers.rb @@ -0,0 +1,15 @@ +class CreateCustomers < ActiveRecord::Migration[7.1] + def change + create_table :customers, if_not_exists: true do |t| + t.string :stripe_customer_id + t.string :stripe_subscription_id + t.string :email + t.string :slug + + t.timestamps + end + + add_column :customers, :created_at, :datetime, null: false, default: -> { "CURRENT_TIMESTAMP" } unless column_exists?(:customers, :created_at) + add_column :customers, :updated_at, :datetime, null: false, default: -> { "CURRENT_TIMESTAMP" } unless column_exists?(:customers, :updated_at) + end +end diff --git a/db/migrate/20260226121544_add_status_to_customers.rb b/db/migrate/20260226121544_add_status_to_customers.rb new file mode 100644 index 0000000..c3ee03b --- /dev/null +++ b/db/migrate/20260226121544_add_status_to_customers.rb @@ -0,0 +1,5 @@ +class AddStatusToCustomers < ActiveRecord::Migration[7.1] + def change + add_column :customers, :status, :string, default: "pending" unless column_exists?(:customers, :status) + end +end diff --git a/fly.toml b/fly.toml index df62331..8a4aeff 100644 --- a/fly.toml +++ b/fly.toml @@ -9,6 +9,9 @@ console_command = '/rails/bin/rails console' [build] +[deploy] + release_command = "./bin/rails db:migrate" + [http_service] internal_port = 3000 force_https = true -- 2.43.0