diff --git a/.gitignore b/.gitignore new file mode 100644 index 0000000000..bc7cac1e83 --- /dev/null +++ b/.gitignore @@ -0,0 +1,34 @@ +# See https://help.github.com/articles/ignoring-files for more about ignoring files. +# +# If you find yourself ignoring temporary files generated by your text editor +# or operating system, you probably want to add a global ignore instead: +# git config --global core.excludesfile '~/.gitignore_global' + +# Ignore bundler config. +/.bundle +.env + +# Ignore all logfiles and tempfiles. +/log/* +/tmp/* +!/log/.keep +!/tmp/.keep + +# Ignore uploaded files in development +/storage/* +!/storage/.keep + +/node_modules +/yarn-error.log + +/public/assets +.byebug_history + +# Ignore master key for decrypting credentials and more. +/config/master.key + +# ignore github secrets +.env + +# ignore simplecov coveragecoverage +/coverage diff --git a/.ruby-version b/.ruby-version new file mode 100644 index 0000000000..160fe391c8 --- /dev/null +++ b/.ruby-version @@ -0,0 +1 @@ +2.5.5 \ No newline at end of file diff --git a/Gemfile b/Gemfile new file mode 100644 index 0000000000..ce80a9cd4b --- /dev/null +++ b/Gemfile @@ -0,0 +1,94 @@ +source 'https://rubygems.org' +git_source(:github) { |repo| "https://github.com/#{repo}.git" } + +ruby '2.5.5' + +# Bundle edge Rails instead: gem 'rails', github: 'rails/rails' +gem 'rails', '~> 5.2.3' +# Use postgresql as the database for Active Record +gem 'pg', '>= 0.18', '< 2.0' +# Use Puma as the app server +gem 'puma', '~> 3.11' +# Use SCSS for stylesheets +gem 'sass-rails', '~> 5.0' +# Use Uglifier as compressor for JavaScript assets +gem 'uglifier', '>= 1.3.0' +# See https://github.com/rails/execjs#readme for more supported runtimes +# gem 'mini_racer', platforms: :ruby + +# Use CoffeeScript for .coffee assets and views +# gem 'coffee-rails', '~> 4.2' +# Turbolinks makes navigating your web application faster. Read more: https://github.com/turbolinks/turbolinks +gem 'turbolinks', '~> 5' +# Build JSON APIs with ease. Read more: https://github.com/rails/jbuilder +gem 'jbuilder', '~> 2.5' +# Use Redis adapter to run Action Cable in production +# gem 'redis', '~> 4.0' +# Use ActiveModel has_secure_password +# gem 'bcrypt', '~> 3.1.7' + +# Use ActiveStorage variant +# gem 'mini_magick', '~> 4.8' + +# Use Capistrano for deployment +# gem 'capistrano-rails', group: :development + +# Reduces boot times through caching; required in config/boot.rb +gem 'bootsnap', '>= 1.1.0', require: false + +group :development, :test do + # Call 'byebug' anywhere in the code to stop execution and get a debugger console + gem 'byebug', platforms: [:mri, :mingw, :x64_mingw] +end + +group :development do + # Access an interactive console on exception pages or by calling 'console' anywhere in the code. + gem 'web-console', '>= 3.3.0' + gem 'listen', '>= 3.0.5', '< 3.2' + # Spring speeds up development by keeping your application running in the background. Read more: https://github.com/rails/spring + gem 'spring' + gem 'spring-watcher-listen', '~> 2.0.0' +end + +group :test do + # Adds support for Capybara system testing and selenium driver + gem 'capybara', '>= 2.15' + gem 'selenium-webdriver' + # Easy installation and use of chromedriver to run system tests with Chrome + # gem 'chromedriver-helper' + gem 'webdrivers', '~> 4.0' +end + +# Windows does not include zoneinfo files, so bundle the tzinfo-data gem +gem 'tzinfo-data', platforms: [:mingw, :mswin, :x64_mingw, :jruby] + +gem 'jquery-rails' +gem 'jquery-turbolinks' +gem 'bootstrap', '~> 4.1.3' +group :development, :test do + gem 'pry-rails' +end + +group :development do + gem 'debase', '>= 0.2.4.1' + gem 'ruby-debug-ide', '>= 0.7.0' +end + +group :development do + gem 'better_errors' + gem 'binding_of_caller' + gem 'guard' + gem 'guard-minitest' + gem 'dotenv-rails' +end + +group :test do + gem 'minitest-rails' + gem 'minitest-reporters' + gem 'simplecov' +end + +gem "omniauth" +gem "omniauth-github" + +gem 'rails-controller-testing' diff --git a/Gemfile.lock b/Gemfile.lock new file mode 100644 index 0000000000..bb74c40288 --- /dev/null +++ b/Gemfile.lock @@ -0,0 +1,322 @@ +GEM + remote: https://rubygems.org/ + specs: + actioncable (5.2.3) + actionpack (= 5.2.3) + nio4r (~> 2.0) + websocket-driver (>= 0.6.1) + actionmailer (5.2.3) + actionpack (= 5.2.3) + actionview (= 5.2.3) + activejob (= 5.2.3) + mail (~> 2.5, >= 2.5.4) + rails-dom-testing (~> 2.0) + actionpack (5.2.3) + actionview (= 5.2.3) + activesupport (= 5.2.3) + rack (~> 2.0) + rack-test (>= 0.6.3) + rails-dom-testing (~> 2.0) + rails-html-sanitizer (~> 1.0, >= 1.0.2) + actionview (5.2.3) + activesupport (= 5.2.3) + builder (~> 3.1) + erubi (~> 1.4) + rails-dom-testing (~> 2.0) + rails-html-sanitizer (~> 1.0, >= 1.0.3) + activejob (5.2.3) + activesupport (= 5.2.3) + globalid (>= 0.3.6) + activemodel (5.2.3) + activesupport (= 5.2.3) + activerecord (5.2.3) + activemodel (= 5.2.3) + activesupport (= 5.2.3) + arel (>= 9.0) + activestorage (5.2.3) + actionpack (= 5.2.3) + activerecord (= 5.2.3) + marcel (~> 0.3.1) + activesupport (5.2.3) + concurrent-ruby (~> 1.0, >= 1.0.2) + i18n (>= 0.7, < 2) + minitest (~> 5.1) + tzinfo (~> 1.1) + addressable (2.7.0) + public_suffix (>= 2.0.2, < 5.0) + ansi (1.5.0) + arel (9.0.0) + autoprefixer-rails (9.7.0) + execjs + better_errors (2.5.1) + coderay (>= 1.0.0) + erubi (>= 1.0.0) + rack (>= 0.9.0) + bindex (0.8.1) + binding_of_caller (0.8.0) + debug_inspector (>= 0.0.1) + bootsnap (1.4.5) + msgpack (~> 1.0) + bootstrap (4.1.3) + autoprefixer-rails (>= 6.0.3) + popper_js (>= 1.12.9, < 2) + sass (>= 3.5.2) + builder (3.2.3) + byebug (11.0.1) + capybara (3.29.0) + addressable + mini_mime (>= 0.1.3) + nokogiri (~> 1.8) + rack (>= 1.6.0) + rack-test (>= 0.6.3) + regexp_parser (~> 1.5) + xpath (~> 3.2) + childprocess (3.0.0) + coderay (1.1.2) + concurrent-ruby (1.1.5) + crass (1.0.5) + debase (0.2.4.1) + debase-ruby_core_source (>= 0.10.2) + debase-ruby_core_source (0.10.6) + debug_inspector (0.0.3) + docile (1.3.2) + dotenv (2.7.5) + dotenv-rails (2.7.5) + dotenv (= 2.7.5) + railties (>= 3.2, < 6.1) + erubi (1.9.0) + execjs (2.7.0) + faraday (0.17.0) + multipart-post (>= 1.2, < 3) + ffi (1.11.1) + formatador (0.2.5) + globalid (0.4.2) + activesupport (>= 4.2.0) + guard (2.15.1) + formatador (>= 0.2.4) + listen (>= 2.7, < 4.0) + lumberjack (>= 1.0.12, < 2.0) + nenv (~> 0.1) + notiffany (~> 0.0) + pry (>= 0.9.12) + shellany (~> 0.0) + thor (>= 0.18.1) + guard-compat (1.2.1) + guard-minitest (2.4.6) + guard-compat (~> 1.2) + minitest (>= 3.0) + hashie (3.6.0) + i18n (1.7.0) + concurrent-ruby (~> 1.0) + jbuilder (2.9.1) + activesupport (>= 4.2.0) + jquery-rails (4.3.5) + rails-dom-testing (>= 1, < 3) + railties (>= 4.2.0) + thor (>= 0.14, < 2.0) + jquery-turbolinks (2.1.0) + railties (>= 3.1.0) + turbolinks + json (2.1.0) + jwt (2.2.1) + listen (3.1.5) + rb-fsevent (~> 0.9, >= 0.9.4) + rb-inotify (~> 0.9, >= 0.9.7) + ruby_dep (~> 1.2) + loofah (2.3.1) + crass (~> 1.0.2) + nokogiri (>= 1.5.9) + lumberjack (1.0.13) + mail (2.7.1) + mini_mime (>= 0.1.1) + marcel (0.3.3) + mimemagic (~> 0.3.2) + method_source (0.9.2) + mimemagic (0.3.3) + mini_mime (1.0.2) + mini_portile2 (2.4.0) + minitest (5.12.2) + minitest-rails (5.2.0) + minitest (~> 5.10) + railties (~> 5.2.0) + minitest-reporters (1.4.1) + ansi + builder + minitest (>= 5.0) + ruby-progressbar + msgpack (1.3.1) + multi_json (1.14.1) + multi_xml (0.6.0) + multipart-post (2.1.1) + nenv (0.3.0) + nio4r (2.5.2) + nokogiri (1.10.4) + mini_portile2 (~> 2.4.0) + notiffany (0.1.3) + nenv (~> 0.1) + shellany (~> 0.0) + oauth2 (1.4.2) + faraday (>= 0.8, < 2.0) + jwt (>= 1.0, < 3.0) + multi_json (~> 1.3) + multi_xml (~> 0.5) + rack (>= 1.2, < 3) + omniauth (1.9.0) + hashie (>= 3.4.6, < 3.7.0) + rack (>= 1.6.2, < 3) + omniauth-github (1.3.0) + omniauth (~> 1.5) + omniauth-oauth2 (>= 1.4.0, < 2.0) + omniauth-oauth2 (1.6.0) + oauth2 (~> 1.1) + omniauth (~> 1.9) + pg (1.1.4) + popper_js (1.14.5) + pry (0.12.2) + coderay (~> 1.1.0) + method_source (~> 0.9.0) + pry-rails (0.3.9) + pry (>= 0.10.4) + public_suffix (4.0.1) + puma (3.12.1) + rack (2.0.7) + rack-test (1.1.0) + rack (>= 1.0, < 3) + rails (5.2.3) + actioncable (= 5.2.3) + actionmailer (= 5.2.3) + actionpack (= 5.2.3) + actionview (= 5.2.3) + activejob (= 5.2.3) + activemodel (= 5.2.3) + activerecord (= 5.2.3) + activestorage (= 5.2.3) + activesupport (= 5.2.3) + bundler (>= 1.3.0) + railties (= 5.2.3) + sprockets-rails (>= 2.0.0) + rails-controller-testing (1.0.4) + actionpack (>= 5.0.1.x) + actionview (>= 5.0.1.x) + activesupport (>= 5.0.1.x) + rails-dom-testing (2.0.3) + activesupport (>= 4.2.0) + nokogiri (>= 1.6) + rails-html-sanitizer (1.3.0) + loofah (~> 2.3) + railties (5.2.3) + actionpack (= 5.2.3) + activesupport (= 5.2.3) + method_source + rake (>= 0.8.7) + thor (>= 0.19.0, < 2.0) + rake (13.0.0) + rb-fsevent (0.10.3) + rb-inotify (0.10.0) + ffi (~> 1.0) + regexp_parser (1.6.0) + ruby-debug-ide (0.7.0) + rake (>= 0.8.1) + ruby-progressbar (1.10.1) + ruby_dep (1.5.0) + rubyzip (2.0.0) + sass (3.7.4) + sass-listen (~> 4.0.0) + sass-listen (4.0.0) + rb-fsevent (~> 0.9, >= 0.9.4) + rb-inotify (~> 0.9, >= 0.9.7) + sass-rails (5.1.0) + railties (>= 5.2.0) + sass (~> 3.1) + sprockets (>= 2.8, < 4.0) + sprockets-rails (>= 2.0, < 4.0) + tilt (>= 1.1, < 3) + selenium-webdriver (3.142.6) + childprocess (>= 0.5, < 4.0) + rubyzip (>= 1.2.2) + shellany (0.0.1) + simplecov (0.17.1) + docile (~> 1.1) + json (>= 1.8, < 3) + simplecov-html (~> 0.10.0) + simplecov-html (0.10.2) + spring (2.1.0) + spring-watcher-listen (2.0.1) + listen (>= 2.7, < 4.0) + spring (>= 1.2, < 3.0) + sprockets (3.7.2) + concurrent-ruby (~> 1.0) + rack (> 1, < 3) + sprockets-rails (3.2.1) + actionpack (>= 4.0) + activesupport (>= 4.0) + sprockets (>= 3.0.0) + thor (0.20.3) + thread_safe (0.3.6) + tilt (2.0.10) + turbolinks (5.2.1) + turbolinks-source (~> 5.2) + turbolinks-source (5.2.0) + tzinfo (1.2.5) + thread_safe (~> 0.1) + uglifier (4.2.0) + execjs (>= 0.3.0, < 3) + web-console (3.7.0) + actionview (>= 5.0) + activemodel (>= 5.0) + bindex (>= 0.4.0) + railties (>= 5.0) + webdrivers (4.1.3) + nokogiri (~> 1.6) + rubyzip (>= 1.3.0) + selenium-webdriver (>= 3.0, < 4.0) + websocket-driver (0.7.1) + websocket-extensions (>= 0.1.0) + websocket-extensions (0.1.4) + xpath (3.2.0) + nokogiri (~> 1.8) + +PLATFORMS + ruby + +DEPENDENCIES + better_errors + binding_of_caller + bootsnap (>= 1.1.0) + bootstrap (~> 4.1.3) + byebug + capybara (>= 2.15) + debase (>= 0.2.4.1) + dotenv-rails + guard + guard-minitest + jbuilder (~> 2.5) + jquery-rails + jquery-turbolinks + listen (>= 3.0.5, < 3.2) + minitest-rails + minitest-reporters + omniauth + omniauth-github + pg (>= 0.18, < 2.0) + pry-rails + puma (~> 3.11) + rails (~> 5.2.3) + rails-controller-testing + ruby-debug-ide (>= 0.7.0) + sass-rails (~> 5.0) + selenium-webdriver + simplecov + spring + spring-watcher-listen (~> 2.0.0) + turbolinks (~> 5) + tzinfo-data + uglifier (>= 1.3.0) + web-console (>= 3.3.0) + webdrivers (~> 4.0) + +RUBY VERSION + ruby 2.5.5p157 + +BUNDLED WITH + 2.0.2 diff --git a/Guardfile b/Guardfile new file mode 100644 index 0000000000..e34f706f4a --- /dev/null +++ b/Guardfile @@ -0,0 +1,9 @@ +guard :minitest, autorun: false, spring: true do + watch(%r{^app/(.+).rb$}) { |m| "test/#{m[1]}_test.rb" } + watch(%r{^app/controllers/application_controller.rb$}) { 'test/controllers' } + watch(%r{^app/controllers/(.+)_controller.rb$}) { |m| "test/integration/#{m[1]}_test.rb" } + watch(%r{^app/views/(.+)_mailer/.+}) { |m| "test/mailers/#{m[1]}_mailer_test.rb" } + watch(%r{^lib/(.+).rb$}) { |m| "test/lib/#{m[1]}_test.rb" } + watch(%r{^test/.+_test.rb$}) + watch(%r{^test/test_helper.rb$}) { 'test' } +end diff --git a/Rakefile b/Rakefile new file mode 100644 index 0000000000..e85f913914 --- /dev/null +++ b/Rakefile @@ -0,0 +1,6 @@ +# Add your own tasks in files placed in lib/tasks ending in .rake, +# for example lib/tasks/capistrano.rake, and they will automatically be available to Rake. + +require_relative 'config/application' + +Rails.application.load_tasks diff --git a/app/assets/config/manifest.js b/app/assets/config/manifest.js new file mode 100644 index 0000000000..b16e53d6d5 --- /dev/null +++ b/app/assets/config/manifest.js @@ -0,0 +1,3 @@ +//= link_tree ../images +//= link_directory ../javascripts .js +//= link_directory ../stylesheets .css diff --git a/app/assets/images/.keep b/app/assets/images/.keep new file mode 100644 index 0000000000..e69de29bb2 diff --git a/app/assets/javascripts/application.js b/app/assets/javascripts/application.js new file mode 100644 index 0000000000..9a4bf80bd5 --- /dev/null +++ b/app/assets/javascripts/application.js @@ -0,0 +1,20 @@ +// This is a manifest file that'll be compiled into application.js, which will include all the files +// listed below. +// +// Any JavaScript/Coffee file within this directory, lib/assets/javascripts, or any plugin's +// vendor/assets/javascripts directory can be referenced here using a relative path. +// +// It's not advisable to add code directly here, but if you do, it'll appear at the bottom of the +// compiled file. JavaScript code in this file should be added after the last require_* statement. +// +// Read Sprockets README (https://github.com/rails/sprockets#sprockets-directives) for details +// about supported directives. + + //= require jquery3 + //= require popper + //= require bootstrap-sprockets +// +//= require rails-ujs +//= require activestorage +//= require turbolinks +//= require_tree . diff --git a/app/assets/javascripts/cable.js b/app/assets/javascripts/cable.js new file mode 100644 index 0000000000..739aa5f022 --- /dev/null +++ b/app/assets/javascripts/cable.js @@ -0,0 +1,13 @@ +// Action Cable provides the framework to deal with WebSockets in Rails. +// You can generate new channels where WebSocket features live using the `rails generate channel` command. +// +//= require action_cable +//= require_self +//= require_tree ./channels + +(function() { + this.App || (this.App = {}); + + App.cable = ActionCable.createConsumer(); + +}).call(this); diff --git a/app/assets/javascripts/categories.js b/app/assets/javascripts/categories.js new file mode 100644 index 0000000000..dee720facd --- /dev/null +++ b/app/assets/javascripts/categories.js @@ -0,0 +1,2 @@ +// Place all the behaviors and hooks related to the matching controller here. +// All this logic will automatically be available in application.js. diff --git a/app/assets/javascripts/channels/.keep b/app/assets/javascripts/channels/.keep new file mode 100644 index 0000000000..e69de29bb2 diff --git a/app/assets/javascripts/homepages.js b/app/assets/javascripts/homepages.js new file mode 100644 index 0000000000..dee720facd --- /dev/null +++ b/app/assets/javascripts/homepages.js @@ -0,0 +1,2 @@ +// Place all the behaviors and hooks related to the matching controller here. +// All this logic will automatically be available in application.js. diff --git a/app/assets/javascripts/order_items.js b/app/assets/javascripts/order_items.js new file mode 100644 index 0000000000..dee720facd --- /dev/null +++ b/app/assets/javascripts/order_items.js @@ -0,0 +1,2 @@ +// Place all the behaviors and hooks related to the matching controller here. +// All this logic will automatically be available in application.js. diff --git a/app/assets/javascripts/orders.js b/app/assets/javascripts/orders.js new file mode 100644 index 0000000000..dee720facd --- /dev/null +++ b/app/assets/javascripts/orders.js @@ -0,0 +1,2 @@ +// Place all the behaviors and hooks related to the matching controller here. +// All this logic will automatically be available in application.js. diff --git a/app/assets/javascripts/products.js b/app/assets/javascripts/products.js new file mode 100644 index 0000000000..dee720facd --- /dev/null +++ b/app/assets/javascripts/products.js @@ -0,0 +1,2 @@ +// Place all the behaviors and hooks related to the matching controller here. +// All this logic will automatically be available in application.js. diff --git a/app/assets/javascripts/reviews.js b/app/assets/javascripts/reviews.js new file mode 100644 index 0000000000..dee720facd --- /dev/null +++ b/app/assets/javascripts/reviews.js @@ -0,0 +1,2 @@ +// Place all the behaviors and hooks related to the matching controller here. +// All this logic will automatically be available in application.js. diff --git a/app/assets/javascripts/users.js b/app/assets/javascripts/users.js new file mode 100644 index 0000000000..dee720facd --- /dev/null +++ b/app/assets/javascripts/users.js @@ -0,0 +1,2 @@ +// Place all the behaviors and hooks related to the matching controller here. +// All this logic will automatically be available in application.js. diff --git a/app/assets/stylesheets/application.scss b/app/assets/stylesheets/application.scss new file mode 100644 index 0000000000..dde8c19414 --- /dev/null +++ b/app/assets/stylesheets/application.scss @@ -0,0 +1,187 @@ +/* + * This is a manifest file that'll be compiled into application.css, which will include all the files + * listed below. + * + * Any CSS and SCSS file within this directory, lib/assets/stylesheets, or any plugin's + * vendor/assets/stylesheets directory can be referenced here using a relative path. + * + * You're free to add application-wide styles to this file and they'll appear at the bottom of the + * compiled file so the styles you add here take precedence over styles defined in any other CSS/SCSS + * files in this directory. Styles in this file should be added after the last require_* statement. + * It is generally better to create a new file per style scope. + * + */ + +/* Custom bootstrap variables must be set or imported *before* bootstrap. */ +@import "bootstrap"; +/* Import scss content */ +@import "**/*"; + +body { + font-family: 'Courier New', Courier, monospace; +} + +$green: #428625; +$lightgreen: #68a418; +$highlight_lightgreen: #5da22c; +$midgreen: #428625; +$darkgreen: #2e5e1a; +$verydarkgreen: #174326; +$brightgreen: #b7f702; +$palegreen: #c8eaaf; +$whitegreen: #d6efc3; + + +.app_header { + background-image: url(https://lh3.googleusercontent.com/i8VrQ6W2Gk-S8TvGyngqNVJMmoVRGqUljMHYqXyzUQC1hFmeey1eqVK3rE5WjvHrsyHROEnQaoLX67gP7G5NMRmsx1orzqR8fZmGv2LFrNeXqgRNlQYaZnLSKP2ccOaXDWpFJugmRA=w2400); + padding: 2.5rem; +} + +.app_header__title, .app_header__title a { + color: #ACDF87; + font-weight: bold; + margin-bottom: 2rem; + text-decoration: none; +} + +.top_nav { + display: flex; + flex-direction: row; + flex-wrap: wrap; +} + +.user_nav { + margin-left: auto; +} + +.flash { + margin-top: 2rem; + margin-bottom: 2rem; +} + +.page_nav a { + color: white; +} + +.btn-primary { + background-color: $lightgreen; + border-color: $green; +} + +.btn-primary:hover { + background-color: $green; + border-color: $midgreen; +} + +.btn-light { + background-color: $palegreen; + border-color: $whitegreen; +} + +.btn-light:hover { + background-color: $lightgreen; +} + +.btn-secondary { + color: #0a1d10; + background-color: $midgreen; + border-color: $green; +} + +.btn-secondary:hover { + color: $highlight_lightgreen; + background-color: #1a360f; + border-color: $midgreen; +} + +.btn-secondary:not(:disabled):not(.disabled):active, .btn-secondary:not(:disabled):not(.disabled).active, .show > .btn-secondary.dropdown-toggle { + background-color: $lightgreen; + border-color: $lightgreen; +} + +.shopping-cart:hover { + background-color: $highlight_lightgreen; +} + +.shopping-cart:hover .badge { + background-color: $palegreen; + color: $midgreen; +} + +.github-login { + color: $verydarkgreen; +} + +.fa-github { + color: $verydarkgreen; +} + +.fa-shopping-cart { + color: $midgreen; +} + +.btn-light:hover, .btn-light:hover .fa-shopping-cart { + color: $darkgreen; + color: $brightgreen; +} + +.footer { + display: grid; + grid-template-columns: 1fr 1fr; + grid-template-rows: 3fr 1fr; + + background-color: $darkgreen; +} + +.footer__site_buttons, .footer__offsite_buttons { + padding: 1rem 2rem 1rem 2rem; + align-self: center; +} + +.footer__site_buttons { + grid-column-start: 1; + grid-column-end: 2; + grid-row-start: 1; + grid-row-end: 2; + + display: flex; + flex-flow: column wrap; +} + +.footer__offsite_buttons { + grid-column-start: 2; + grid-column-end: 3; + grid-row-start: 1; + grid-row-end: 2; + justify-self: end; + + display: grid; + grid-template-columns: 1fr 1fr; + grid-template-rows: 1fr 1fr; + grid-gap: 1rem; +} + +.footer__offsite_buttons > * { + font-size: 1.5em; +} + +.footer__site_copywrite { + grid-column-start: 1; + grid-column-end: 3; + grid-row-start: 2; + grid-row-end: 3; + justify-self: stretch; + text-align: center; + + color: $green; + background-color: $verydarkgreen; + + display: flex; + flex-direction: column; + justify-content: center; +} + +.footer__site_buttons > * { + width: max-content; + margin: 0.5rem; +} diff --git a/app/assets/stylesheets/categories.scss b/app/assets/stylesheets/categories.scss new file mode 100644 index 0000000000..4e68008aee --- /dev/null +++ b/app/assets/stylesheets/categories.scss @@ -0,0 +1,70 @@ +// Place all the styles related to the Categories controller here. +// They will automatically be included in application.css. +// You can use Sass (SCSS) here: http://sass-lang.com/ + +$green: #428625; +$lightgreen: #68a418; +$darkgreen: #2e5e1a; +$verydarkgreen: #174326; +$brightgreen: #b7f702; +$midgreen: #428625; +$palegreen: #c8eaaf; + +.category_title, .category_nav { + text-align: center; + margin-bottom: 2%; + margin-left: 10%; + margin-right: 10%; + color: $verydarkgreen; + // border: 1px solid; + background-color: $palegreen; +} + +.index_page_category-container { + display: grid; + grid-template-columns: 1fr 1fr; + grid-template-rows: 1fr 1fr; + margin-left: 10%; + margin-right: 20%; + margin-bottom: 2%; + // border: 2px solid #431c5d; +} + +.category_text { + text-align: center; + color: $lightgreen; + margin-bottom: 5%; + margin-left: 18%; +} + +.product_image_category { + width: 300px; + height: 300px; + border-radius: 10%; + margin-left: 27%; + margin-right: 10%; + opacity: 0.9; + object-fit: cover +} + + +.index_page_category-container { + column-gap: 1em; + row-gap: 3em; + width: 60%; + margin: auto; + margin-bottom: 5rem; +} + +.category_title { + margin-bottom: 0; +} + +.category_nav { + margin-bottom: 2rem; +} + +.category_nav.nav-pills .nav-link.active, .category_nav.nav-pills .show > .nav-link { + background-color: $lightgreen; + font-style: italic; +} \ No newline at end of file diff --git a/app/assets/stylesheets/homepages.scss b/app/assets/stylesheets/homepages.scss new file mode 100644 index 0000000000..c60ec8c49a --- /dev/null +++ b/app/assets/stylesheets/homepages.scss @@ -0,0 +1,216 @@ +// Place all the styles related to the Homepages controller here. +// They will automatically be included in application.css. +// You can use Sass (SCSS) here: http://sass-lang.com/ + +$green: #428625; +$lightgreen: #68a418; +$highlight_lightgreen: #5da22c; +$midgreen: #428625; +$darkgreen: #2e5e1a; +$verydarkgreen: #174326; +$brightgreen: #b7f702; +$palegreen: #c8eaaf; +$whitegreen: #d6efc3; + +$transparent_palegreen: rgba(200,234,175,0.9); +$transparent_darkgreen: rgba(46, 94, 26,0.9); + +// CAROUSEL +#homepage_hero_carousel { + margin-top: 2rem; + border-top: 2px solid $green; + border-bottom: 2px solid $green; +} + +#homepage_hero_carousel img { + height: 35em; + width: 100%; + object-fit: cover; +} + +.carousel-caption { + color: white; + background-color: $transparent_darkgreen; + border-radius: 3rem; + + margin-bottom: 1.5rem; +} + +.carousel-caption h5 { + text-decoration: underline; +} + +.carousel-caption:hover { + background-color: $transparent_palegreen; + color: black; +} + +.carousel-caption:hover > *:last-child { + display: none; +} + +.carousel-caption:hover::after { + content: "See Product"; + font-size: 1.2em; + color: $brightgreen; + + background-color: $transparent_darkgreen; + border-radius: 1.2rem; + padding: 0.3rem 1rem; +} + + +// SHOP BY CATEGORY SECTION +.homepage__shop { + width: 90%; + margin: auto; +} + +.homepage_category_title { + background-color: $palegreen; + padding: 1rem; +} + +.homepage_category_wrapper { + margin: 3rem 0; + border: 2px solid $palegreen; + + text-align: center; + display: flex; + flex-direction: column; +} + +.homepage_product_card_wrapper { + display: flex; + overflow-x: auto; +} + +.card { + width: 20em; + min-width: 20em; + margin: 0 1rem; + text-align: center; + border-color: $palegreen; + border-radius: 0; + + margin-bottom: -1px; +} + +.card img { + height: 15em; + object-fit: cover; + border-radius: 0; +} + +// Register as Merchant Page + +.sign_up { + display: flex; + flex-direction: column; + text-align: center; + margin: 8rem 0; +} + +.sign_up h2 { + margin-bottom: 2rem; +} + +.sign_up a { + width: max-content; + margin: auto; + + font-size: 1.5em; + margin-top: 2rem; +} + +.sign_up .fa-github { + color: white; +} + +// About page + +.about_us > .main_header { + margin-top: 3rem; + text-align: center; + + padding: 1rem 0; + background-color: $palegreen; + border-top: 2px solid $green; + border-bottom: 2px solid $green; +} + +.about_us > section { + width: 90%; + margin: 5rem auto; +} + +.about_us .header { + border-bottom: 2px solid $lightgreen; + margin-bottom: 2rem; +} + +.team_member_photo { + border-radius: 1rem; + margin: 1rem; +} + +.team_member { + position: relative; +} + +.team_member_header { + position: absolute; + bottom: 45px; + left: 70px; + + background-color: $green; + color: white; + padding: 1rem 1.5rem; + border-radius: 0.2rem; +} + +.faq_container { + display: flex; + flex-direction: column; +} + +.faq_item { + margin: 3rem; +} + +.faq_question { + font-size: 1.2em; + background-color: $palegreen; + padding: 1.5rem; + border-radius: 0.2rem; +} + +.faq_question::before { + content: "Q: " +} + +.about_nav { + text-align: center; + display: flex; + flex-flow: row wrap; + justify-content: center; + padding: 1rem; +} + +.nav-item { + margin: 0 0.5rem; +} + +.about_nav_item + .about_nav_item::before { + content: "•"; + color: $darkgreen; +} + +.about_us .go_to_top { + display: none; + font-size: 0.9em; +} + +.about_us .header:hover .go_to_top { + display: inline; +} \ No newline at end of file diff --git a/app/assets/stylesheets/order_items.scss b/app/assets/stylesheets/order_items.scss new file mode 100644 index 0000000000..584862de9b --- /dev/null +++ b/app/assets/stylesheets/order_items.scss @@ -0,0 +1,3 @@ +// Place all the styles related to the OrderItems controller here. +// They will automatically be included in application.css. +// You can use Sass (SCSS) here: http://sass-lang.com/ diff --git a/app/assets/stylesheets/orders.scss b/app/assets/stylesheets/orders.scss new file mode 100644 index 0000000000..b4ff60fb9a --- /dev/null +++ b/app/assets/stylesheets/orders.scss @@ -0,0 +1,28 @@ +// Place all the styles related to the Orders controller here. +// They will automatically be included in application.css. +// You can use Sass (SCSS) here: http://sass-lang.com/ + +.order_data { + margin-top: 2%; + margin-left: 1%; + margin-right: 5%; + margin-bottom: 2%; +} + +.order-checkout-button { + margin-bottom: 2%; + margin-left: 35%; +} + +.order-num { + margin-left: 10%; +} + +.order_confirmation { + margin-left: 20%; +} + +.order_summary { + // margin-left: 5%; + margin-right: 20%; +} diff --git a/app/assets/stylesheets/products.scss b/app/assets/stylesheets/products.scss new file mode 100644 index 0000000000..cef5664b6d --- /dev/null +++ b/app/assets/stylesheets/products.scss @@ -0,0 +1,182 @@ +// Place all the styles related to the Products controller here. +// They will automatically be included in application.css. +// You can use Sass (SCSS) here: http://sass-lang.com/ + +$green: #428625; +$lightgreen: #68a418; +$darkgreen: #2e5e1a; +$verydarkgreen: #174326; +$brightgreen: #b7f702; +$midgreen: #428625; + +.show_page_product { + margin-left: 1%; + margin-top: 2%; + display: flex; + flex-direction: row; + flex-wrap: wrap; +} + +.show_page__header { + background-color: $palegreen; + margin-left: 10%; + margin-right: 10%; +} + +.product_image_show { + width: 300px; + height: 300px; + margin-bottom: 10%; + margin-left: 20%; + margin-top: 2%; + object-fit: cover; + border-radius: 10%; + opacity: 0.9; +} + +.product_data { + margin-top: 2%; + margin-left: 7%; + margin-bottom: 3%; +} + +.product_data_extra { + margin-top: 5%; + margin-left: 6%; +} + +.index_page_product-container { + display: grid; + grid-template-columns: 1fr 1fr 1fr; + grid-template-rows: 1fr 1fr 1fr; + margin-left: 10%; + margin-right: 10%; + margin-bottom: 4%; +} + +a { + text-decoration: none; + color: $darkgreen; +} + +a:hover { + text-decoration: none; + color: $lightgreen; +} + +.product_image { + width: 300px; + height: 300px; + border-radius: 10%; + margin-left: 5%; + opacity: 0.9; + object-fit: cover +} + +.product_text { + margin-right: 8%; + margin-bottom: 10%; + text-align: center; +} + +.checkbox-inline { + display: flex; + justify-content: space-between; + vertical-align: -1px; +} + +.product-forms { + margin-top: 2%; + margin-left: 10%; + margin-right: 10%; +} + +.table { + margin-top: 3%; + margin-left: 5%; + margin-right: 5%; + margin-bottom: 2%; +} + +.index_page_product-container { + column-gap: 1em; + row-gap: 3em; + width: 80%; + margin: auto; + margin-bottom: 5rem; +} + +@media only screen and (max-width: 1000px) { + .index_page_product-container, .index_page_category-container { + display: grid; + grid-template-columns: 1fr 1fr; + } +} + +@media only screen and (max-width: 650px) { + .index_page_product-container, .index_page_category-container { + display: grid; + grid-template-columns: 1fr; + } +} + +.product_data_index, .category_data_index { + display: flex; + flex-direction: column; + align-items: center; +} + +.product_data_index *, .category_data_index * { + margin: 0; +} + +.product_img_container { + // so that text will be relative to this + position: relative; +} + +.image { + // opacity faces in and out + transition: .5s ease; + margin-bottom: 1em; + border: 1px solid $darkgreen; +} + +.link { + // opacity faces in and out + transition: .5s ease; + // makes it invisible normally + opacity: 0; + // absolute relative to container + position: absolute; + // position 50% in from top and left + top: 50%; + left: 50%; + transform: translate(-50%, -50%); + -ms-transform: translate(-50%, -50%); + // align text center + text-align: center; +} + +.product_img_container:hover .image { + // make image fade on hover + opacity: 0.3; +} + +.product_img_container:hover .link { + // make text appear on hover + opacity: 1; +} + +.link_text { + background-color: $lightgreen; + color: white; + font-size: 1.2em; + padding: 0.8em 1.4em; +} + +.new_rating { + font-weight: bold; + margin-left: 5%; + margin-bottom: 3%; +} diff --git a/app/assets/stylesheets/reviews.scss b/app/assets/stylesheets/reviews.scss new file mode 100644 index 0000000000..11bbb12cd5 --- /dev/null +++ b/app/assets/stylesheets/reviews.scss @@ -0,0 +1,3 @@ +// Place all the styles related to the Reviews controller here. +// They will automatically be included in application.css. +// You can use Sass (SCSS) here: http://sass-lang.com/ diff --git a/app/assets/stylesheets/users.scss b/app/assets/stylesheets/users.scss new file mode 100644 index 0000000000..3efc507bdc --- /dev/null +++ b/app/assets/stylesheets/users.scss @@ -0,0 +1,591 @@ +// Place all the styles related to the Users controller here. +// They will automatically be included in application.css. +// You can use Sass (SCSS) here: http://sass-lang.com/ + +$green: #428625; +$lightgreen: #68a418; +$highlight_lightgreen: #5da22c; +$midgreen: #428625; +$darkgreen: #2e5e1a; +$verydarkgreen: #174326; +$brightgreen: #b7f702; +$palegreen: #c8eaaf; +$whitegreen: #d6efc3; + +caption { + display: none; +} + +.show_page { + margin-top: 3rem; + margin-bottom: 4.5rem; +} + +.show_page__header { + text-align: center; +} + +.no_products_error { + text-align: center; + padding: 4rem; +} + +.show_page__tiles { + width: 90%; + margin: auto; + display: grid; + grid-template-columns: repeat(auto-fit, minmax(20rem, 1fr)); + justify-content: center; + align-items: center; + grid-gap: 2rem; + margin-top: 3rem; +} + +.merchant_show__tiles { + display: flex; + flex-flow: row wrap; +} + +.merchant_tile { + padding: 3rem; + text-align: center; + background-color: $lightgreen; + font-size: 1.5em; + color: white; +} + +.merchant_tile:hover { + background-color: $brightgreen; + color: $verydarkgreen; + font-weight: bold; + text-decoration: none; +} + +.merchant_product_tile { + text-align: center; + position: relative; + align-self: center; + + width: 30em; + height: 30em; +} + +.merchant_product_tile__img { + width: 100%; + height: 100%; + object-fit: cover; + opacity: 0.8; +} + +// overlap positioning from https://www.w3schools.com/css/css_positioning.asp +.merchant_product_tile__data { + background-color: rgba(66,134,37,0.9); + position: absolute; + left: 0; + top: 50%; + width: 100%; + text-align: center; +} + +.merchant_product_tile__title a { + color: $brightgreen; +} + +.merchant_product_tile__title a:hover { + color: $verydarkgreen; + text-decoration: none; +} + +.show_page__merchant { + color: $darkgreen; +} + +.show_page__merchant:hover { + color: $brightgreen; + text-decoration: none; +} + + +// DASHBOARD + +.dashboard__line_break { + border-top: 2px solid $green; + margin-bottom: 0.5rem; +} + +.dashboard { + width: 80%; + margin: auto; + margin-top: 2rem; +} + +@media only screen and (max-width: 700px) { + .dashboard { + width: 90%; + margin: auto; + margin-top: 2rem; + } +} + +.dashboard__header { + display: flex; + flex-flow: column wrap; +} + +.dashboard__header ul { + list-style: none; + font-style: italic; +} + +.dashboard__header_title { + color: $darkgreen; +} + +.dashboard_options { + display: flex; + flex-flow: row wrap; + margin-bottom: 1rem; +} + +.dashboard_options__account_option, .dashboard_options__account_option a { + color: $lightgreen; +} + +.dashboard_options__account_option a:hover { + text-decoration: none; + font-weight: bold; +} + +.dashboard_options > *:last-child { + margin-left: auto; +} + +.btn-primary.dropdown-toggle { + border-color: $green; + + .fa-angle-down { + display: none; + } +} + +.btn-primary:not(:disabled):not(.disabled):active, .btn-primary:not(:disabled):not(.disabled).active, .show > .btn-primary.dropdown-toggle { + background-color: $darkgreen; + border-color: $verydarkgreen; + + // toggle between carets + .fa-angle-down { + display: inline; + } + + .fa-angle-left { + display: none; + } +} + +.dropdown-menu { + background-color: $palegreen; +} + +.dropdown-item:hover { + color: white; + background-color: $lightgreen; +} + +// dont' show bootstrap's default caret +.btn-primary.dropdown-toggle::after { + display: none; +} + +.breadcrumb { + border-radius: 0; + background-color: rgba(214,239,195,0.6); +} + +.breadcrumb-item { + color: $midgreen; +} + +.breadcrumb-item + .breadcrumb-item::before { + content: "|"; + color: $midgreen; +} + +.breadcrumb-item:hover { + color: $midgreen; + text-decoration: none; + font-weight: bold; +} + +.breadcrumb-item:hover::before { + font-weight: normal; +} + +.badge-primary { + background-color: $highlight_lightgreen; +} + +.dashboard__section { + margin-top: 4rem; + margin-bottom: 2rem; + text-align: center; + color: $darkgreen; +} + +.dashboard__line_break.dashboard_section__break { + width: 50%; +} + +.product_spotlight_container { + display: flex; + flex-direction: row; + justify-content: center; +} + +.product_spotlight { + background-color: $whitegreen; + padding: 2em 3em; +} + +.product_spotlight__top_product { + margin-top: 1.5em; + margin-bottom: 1em; + + display: flex; + flex-flow: row wrap; + justify-content: center; +} + +.product_spotlight__top_product > * { + height: max-content; + align-self: center; + margin-bottom: 0; +} + +.dashboard__products_container { + margin-top: 4rem; +} + +.dashboard__user_product, .dashboard__line_break.dashboard__product__break { + width: 90%; + margin: auto; +} + +.dashboard__user_product { + padding: 1rem; +} + +.dashboard__user_product__basic_info { + display: flex; + flex-flow: row wrap; +} + +.dashboard__user_product__basic_info > *:first-child { + font-weight: bold; + font-size: 1.2em; +} + +.header_item__subtitle { + font-size: 1em; +} + +.basic_info__header_item + .basic_info__header_item::before { + font-size: 1.2em; + content: "| "; + margin-left: 0.3em; +} + +.more_info__header { + margin-bottom: 0; + font-size: 1.2em; +} + +.more_info__description_container { + display: flex; + flex-flow: row wrap; +} + +.more_info__description_container > *:last-child { + margin-left: auto; +} + +.more_info__description_container > *, .more_info__price_container > * { + display: inline-block; +} + +.dashboard__line_break.dashboard__product__break { + margin-top: 0; +} + +// Untoggled State +.toggle__show_more { + display: flex; + flex-direction: row; + justify-content: flex-end; + // hard-coded; tweak to fix alignment with product header + margin-top: -1.5rem; +} + +// hide toggle name from visual user +.toggle__product, .toggle__product ~ label > *:first-child { + display: none; +} + +// hide toggle checkbox (so the font-awesome icons appear as the button) +.toggle__product ~ div { + display: none; +} + +.toggle__product ~ label > .toggle_to_off { + display: none; +} + +/* Toggled State */ +.toggle__product:checked ~ label > .toggle_to_on { + display: none; +} + +.toggle__product:checked ~ label > .toggle_to_off { + display: inline-block; +} + +.toggle__product:checked ~ div { + animation: 1.5s ease-in 0s 1 fadeIn; + + display: grid; +} + +.dashboard__edit_product { + display: flex; + flex-direction: row; + justify-content: flex-end; + clear: right; +} + +.edit_product_button { + padding: 0.3rem 0.5rem; + border-radius: 0.4rem; +} + +.merchant_product_image { + width: 10em; + height: 10em; + object-fit: cover; + border-radius: 1em; + + opacity: 1; + transition: .5s ease; + backface-visibility: hidden; +} + +.more_info__container { + width: 90%; + margin: 1em auto; + margin-top: 2em; + + display: grid; + grid-template-columns: 1fr 3fr; +} + +.dashboard__user_product__more_info { + margin-bottom: 1rem; +} + +.product_image_container { + grid-column-start: 1; + grid-column-end: 2; + grid-row-start: 1; + grid-row-end: 3; + + position: relative; +} + +.product_link_middle { + transition: .5s ease; + opacity: 0; + position: absolute; + top: 45%; + left: 17%; + text-align: center; +} + +.product_image_container:hover .merchant_product_image { + opacity: 0.3; +} + +.product_image_container:hover .product_link_middle { + opacity: 1; +} + +.product_link_text { + color: white; + background-color: $lightgreen; + padding: 0.4rem; +} + +.product_link_text:hover { + background-color: $whitegreen; + color: $darkgreen; +} + +.dashboard__user_product__details_container { + margin-top: 1.5rem; + display: flex; + flex-flow: row wrap; + justify-content: space-between; +} + +.more_info__header { + margin-bottom: 0.5em; +} + +.product_category { + background-color: yellowgreen; + padding: 0.2em; + border-radius: 1rem; + + display: flex; + flex-direction: row; + justify-content: center; + + margin: 0.5rem; +} + +// ORDER FULFILLMENT + +.dashboard__products_by_status { + justify-content: center; +} + +.orders_list { + text-align: center; + margin-bottom: 3rem; +} + +.orders__list--toggle__label { + background-color: rgba(214, 239, 195, 0.6); + padding: 0.6rem 1rem; + margin: 0; + border-radius: 0.2rem; +} + +.orders__list--toggle { + display: none; +} + +.orders__list--toggle:checked + .orders__list--toggle__label { + background-color: $lightgreen; + font-weight: bold; + color: white; +} + +.orders__list--toggle:checked + .orders__list--toggle__label .badge-primary { + background-color: $brightgreen; + color: $darkgreen; +} + +// from https://codersblock.com/blog/checkbox-trickery-with-css/ + +.status_all, +.status_pending, +.status_paid, +.status_cancelled, +.status_complete { + animation: 1.5s ease-in 0s 1 fadeIn; + display: none; +} + +#status_all:checked ~ .status_all, +#status_pending:checked ~ .status_pending, +#status_paid:checked ~ .status_paid, +#status_cancelled:checked ~ .status_cancelled, +#status_complete:checked ~ .status_complete { + animation: 1.5s ease-in 0s 1 fadeIn; + display: block; +} + +.orders__totals_per_status { + width: 60%; + margin: auto; + + display: grid; + grid-template-columns: 1fr 1fr; + grid-template-rows: 1fr 1fr; + column-gap: 6rem; + text-align: center; + align-items: end; + + margin-bottom: 4rem; + margin-top: 2rem; +} + +@media only screen and (max-width: 900px) { + .orders__totals_per_status { + width: 80%; + column-gap: 4rem; + } +} + +@media only screen and (max-width: 600px) { + .orders__totals_per_status { + width: 90%; + column-gap: 2rem; + } +} + +.per_order_info { + text-align: left; +} + +.order_table { + width: 90%; +} + +.order_total { + text-align: right; +} + +.orders__total_rev__title { + grid-column-start: 1; + grid-column-end: 2; + grid-row-start: 1; + grid-row-end: 2; +} + +.orders__total_rev { + grid-column-start: 1; + grid-column-end: 2; + grid-row-start: 2; + grid-row-end: 3; +} + +.orders__total { + padding: 1rem; + background-color: $lightgreen; + border: 1px solid $green; + color: white; + border-radius: 3em; +} + +.order__no_orders { + text-align: center; +} + +.order__header { + display: flex; + flex-flow: row wrap; +} + +.order__header > *:last-child { + margin-left: auto; +} + +.order__header_title__item + .order__header_title__item::before { + content: "|"; +} + +.order__buyer_info_container { + width: 70%; + margin-left: 2rem; + margin-top: -1rem; + margin-bottom: 3rem; +} diff --git a/app/channels/application_cable/channel.rb b/app/channels/application_cable/channel.rb new file mode 100644 index 0000000000..d672697283 --- /dev/null +++ b/app/channels/application_cable/channel.rb @@ -0,0 +1,4 @@ +module ApplicationCable + class Channel < ActionCable::Channel::Base + end +end diff --git a/app/channels/application_cable/connection.rb b/app/channels/application_cable/connection.rb new file mode 100644 index 0000000000..0ff5442f47 --- /dev/null +++ b/app/channels/application_cable/connection.rb @@ -0,0 +1,4 @@ +module ApplicationCable + class Connection < ActionCable::Connection::Base + end +end diff --git a/app/controllers/application_controller.rb b/app/controllers/application_controller.rb new file mode 100644 index 0000000000..8e7d1d085c --- /dev/null +++ b/app/controllers/application_controller.rb @@ -0,0 +1,13 @@ +class ApplicationController < ActionController::Base + private + + def logged_in? + user_id = session[:user_id] + + if user_id.nil? + return false + end + + return user_id + end +end diff --git a/app/controllers/categories_controller.rb b/app/controllers/categories_controller.rb new file mode 100644 index 0000000000..3f1ec49b82 --- /dev/null +++ b/app/controllers/categories_controller.rb @@ -0,0 +1,37 @@ +class CategoriesController < ApplicationController + def index + @categories = Category.order(:name) + end + + def new + logged_in_id = logged_in? + if !logged_in_id + flash[:error] = "A guest cannot create a category." + redirect_to products_path + return + else + @category = Category.new + end + end + + def create + user_id = session[:user_id] + @category = Category.new(category_params) + + if @category.save + flash[:success] = "Category successfully created." + redirect_to dashboard_path(user_id) + return + else + flash[:warning] = "Can't create category." + redirect_to dashboard_path(user_id) + return + end + end + + private + + def category_params + return params.require(:category).permit(:name) + end +end diff --git a/app/controllers/concerns/.keep b/app/controllers/concerns/.keep new file mode 100644 index 0000000000..e69de29bb2 diff --git a/app/controllers/homepages_controller.rb b/app/controllers/homepages_controller.rb new file mode 100644 index 0000000000..8eb71b7282 --- /dev/null +++ b/app/controllers/homepages_controller.rb @@ -0,0 +1,11 @@ +class HomepagesController < ApplicationController + def register + if logged_in? + flash[:error] = "You've already signed up!" + redirect_to root_path + return + end + end + + def about; end +end diff --git a/app/controllers/order_items_controller.rb b/app/controllers/order_items_controller.rb new file mode 100644 index 0000000000..3cf95ce947 --- /dev/null +++ b/app/controllers/order_items_controller.rb @@ -0,0 +1,98 @@ +class OrderItemsController < ApplicationController + before_action :find_order_item, only: [:show, :edit, :update, :destroy] + + # Create is adding a product to my cart + def create + order = Order.find_by(id: session[:order_id]) + + if session[:order_id].nil? || order.nil? + order = Order.create + session[:order_id] = order.id + end + + order_items = { + product_id: params[:product_id].to_i, + quantity: params[:quantity].to_i, + order_id: session[:order_id], + } + + order = Order.find(session[:order_id]) + # if order item already exists in cart, increase quantity. + order.order_items.each do |oi| + if oi.product.id == order_items[:product_id] + if oi.quantity + order_items[:quantity] > oi.product.stock + flash[:failure] = "Sorry, there are not enough items in stock." + redirect_to product_path(order_items[:product_id]) + return + else + oi.quantity += order_items[:quantity] + oi.save + + flash[:success] = "Successfully updated quantity." + redirect_to product_path(order_items[:product_id]) + return + end + end + end + + order_item = OrderItem.new(order_items) + if order_item.save + flash[:success] = "Successfully added item to your cart." + redirect_to product_path(order_items[:product_id]) + return + else + flash[:failure] = "Item could not be added to your cart." + redirect_to product_path(order_items[:product_id]) + return + end +end + +#Delete is going to be "remove products from my cart." +def destroy + @order_item.destroy + redirect_to order_path(@order_item.order_id) +end + +#Update is going to change the quantity of my cart." +def update + order_items_params = { + product_id: @order_item.product_id, + order_id: @order_item.order_id, + quantity: params[:quantity] +} + +if @order_item.update(order_items_params) + redirect_to order_path(@order_item.order_id) + return +end +end + +def complete + user_id = logged_in? + if user_id + oi_id = params[:id] + oi = OrderItem.find_by(id: oi_id) + + oi.status = "complete" + oi.save + + redirect_to dashboard_path(user_id) + return + end +end + +private + +def order_items_params + params.require(:order_item).permit(:quantity, :product_id, :order_id) +end + +def find_order_item + @order_item = OrderItem.find_by(id: params[:id]) +end + +def find_order_item + @order_item = OrderItem.find_by(id: params[:id]) +end + +end diff --git a/app/controllers/orders_controller.rb b/app/controllers/orders_controller.rb new file mode 100644 index 0000000000..1b70456b3e --- /dev/null +++ b/app/controllers/orders_controller.rb @@ -0,0 +1,55 @@ +class OrdersController < ApplicationController + before_action :find_order, only: [:show, :edit, :update, :destroy] + + def new + @order = Order.new + end + + def index + @orders = Order.all + end + + def show ; end + + def edit ; end + + def update + if @order.update(order_params) + @order.status = "paid" + @order.update_stock + @order.save + session[:order_id] = nil + + flash[:success] = "Your order is complete. Thank you for shopping at Plantsy!" + + redirect_to checkout_show_path(@order.id) + else + flash[:error] = @order.errors.full_messages + render :edit + end + end + + def create + @order = Order.new(order_params) + if @order.save + session[:order_id] = @order.id + flash[:success] = "Your order has been processed" + redirect_to root_path + return + end + end + + private + + def order_params + params.require(:order).permit(:email, :address, :name, :cc_num, :cvv_code, :exp_date, :zip) + end + + def find_order + @order = Order.find_by_id(params[:id]) + + if @order.nil? + redirect_to request.referrer + end + end +end diff --git a/app/controllers/products_controller.rb b/app/controllers/products_controller.rb new file mode 100644 index 0000000000..ea4a04e997 --- /dev/null +++ b/app/controllers/products_controller.rb @@ -0,0 +1,111 @@ +class ProductsController < ApplicationController + def index + @products = Product.all + end + + def show + @order = session[:order_id] # added for custom method in model + product_id = params[:id] + @product = Product.find_by(id: params[:id]) + + if @product.nil? + flash[:error] = "Invalid product." + redirect_to products_path + return + end + end + + def new + logged_in_id = logged_in? + if !logged_in_id + flash[:error] = "A guest cannot create a product." + redirect_to products_path + return + else + @product = Product.new + end + end + + def create + @product = Product.new(product_params) + + if @product.save + flash[:success] = "Product successfully created." + redirect_to product_path(@product.id) + return + else + flash[:warning] = "Can't create product." + redirect_to products_path + return + end + end + + def edit + @product = Product.find_by(id: params[:id]) + + if @product.nil? + flash[:warning] = "Can't edit, invalid product." + redirect_to products_path + return + end + + logged_in_id = logged_in? + if logged_in_id && @product.user_id != logged_in_id + flash[:error] = "You cannot edit another merchant's product." + redirect_to product_path(@product.id) + return + elsif !logged_in_id + flash[:error] = "A guest cannot edit a product." + redirect_to product_path(@product.id) + return + end + end + + def update + user_id = session[:user_id] + @product = Product.find_by(id: params[:id]) + logged_in_id = logged_in? + + if !logged_in_id + flash[:error] = "A guest cannot update a product." + redirect_to products_path + return + else + if @product.update(product_params) + flash[:success] = "Product successfully updated." + redirect_to dashboard_path(user_id) + return + else + flash[:warning] = "Can't update product." + render :edit + return + end + end + end + + # Method to retire a product + def toggle_retire + user_id = session[:user_id] + @product = Product.find_by(id: params[:id]) + + if user_id + if @product.available + @product.update!(available: false) + + flash[:success] = "Product #{@product.name} successfully RETIRED." + redirect_to dashboard_path(user_id) + else + @product.update(available: true) + flash[:success] = "Product #{@product.name} successfully REACTIVATED." + redirect_to dashboard_path(user_id) + end + return + end + end + + private + + def product_params + return params.require(:product).permit(:name, :user_id, :description, :price, :photo_url, :stock, :available, category_ids: []) + end +end diff --git a/app/controllers/reviews_controller.rb b/app/controllers/reviews_controller.rb new file mode 100644 index 0000000000..74d76bc4d6 --- /dev/null +++ b/app/controllers/reviews_controller.rb @@ -0,0 +1,47 @@ +class ReviewsController < ApplicationController + def new + @review = Review.new + @product_id = product_id_param + end + + def create + logged_in_id = logged_in? + product = Product.find_by(id: product_id_param) + + if logged_in_id && logged_in_id == product.user_id + flash[:error] = "You cannot review your own product" + redirect_to product_path(product.id) + return + else + review_info = { + comment: review_params[:comment], + rating: review_params[:rating], + product_id: product_id_param + } + @review = Review.new(review_info) + if @review.save + flash[:success] = "Your review was successfully submitted." + redirect_to product_path(product.id) + return + else + flash[:failure] = "Your review couldn't be submitted." + redirect_to products_path(product.id) + return + end + end +end + +private + +def review_params + if params[:review] + params.require(:review).permit(:rating, :comment) + else + params.permit(:rating, :comment) + end +end + +def product_id_param + params.require(:product_id) +end +end diff --git a/app/controllers/users_controller.rb b/app/controllers/users_controller.rb new file mode 100644 index 0000000000..461a687f76 --- /dev/null +++ b/app/controllers/users_controller.rb @@ -0,0 +1,82 @@ +class UsersController < ApplicationController + def create + auth_hash = request.env["omniauth.auth"] + + # user = User.find_by(uid: auth_hash[:uid], provider: "github") + + # you need this to be able to login as a seed + # otherwise, you'll get an 'email already in use' error + user = User.find_by(email: auth_hash[:info][:email]) + + if user + flash[:success] = "Successfully logged in as returning user #{user.username}" + else + user = User.build_from_github(auth_hash) + + if user.save + flash[:success] = "Successfully logged in as new user #{user.username}" + else + flash[:error] = "Could not create new user account: #{user.errors.messages}" + redirect_to root_path + return + end + end + + session[:user_id] = user.id + redirect_to dashboard_path(user.id) + return + end + + def destroy + if session[:user_id] + session[:user_id] = nil + flash[:success] = "Successfully logged out!" + else + flash[:error] = "No one logged in" + end + + redirect_to root_path + end + + def index + @users = User.list + end + + def show + @user = get_user + end + + def dashboard + # the person logged in + logged_in_id = logged_in? + # the person to whom the dashboard belongs + user = get_user + + # if the dashboard owner and the logged-in user are the same + if logged_in_id && (user.id == logged_in_id) + @user = user + elsif logged_in_id + # don't let a merchant see the dashboard of another merchant + flash[:error] = "Permission denied: you cannot view another merchant's dashboard" + redirect_to users_path + else + # don't let a guest see a merchant dashboard + flash[:error] = "Permission denied: please log in to view your dashboard" + redirect_to users_path + end + end + + private + + def get_user + user = User.find_by(id: params[:id]) + + if user.nil? + flash[:error] = "Could not find user with id: #{params[:id]}" + redirect_to users_path + return + end + + return user + end +end diff --git a/app/helpers/application_helper.rb b/app/helpers/application_helper.rb new file mode 100644 index 0000000000..4fbd19f949 --- /dev/null +++ b/app/helpers/application_helper.rb @@ -0,0 +1,37 @@ +module ApplicationHelper + def render_date(date) + return date.strftime("%b %e, %Y") + end + + def render_price(price) + return "%.2f" % price.floor(2) + end + + def render_rating(rating) + return "no rating" unless rating + + rating = rating.to_i + + filled_star = '' + empty_star = '' + + # make a list of all the filled stars + star_list = [] + until rating == 0 + star_list << filled_star + rating -= 1 + end + + # fill out the rest of the list with empty stars + until star_list.length == 5 + star_list << empty_star + end + + # convert star list to string + stars = star_list.join("") + + return ( + stars.html_safe + ) + end +end diff --git a/app/helpers/categories_helper.rb b/app/helpers/categories_helper.rb new file mode 100644 index 0000000000..e06f31554c --- /dev/null +++ b/app/helpers/categories_helper.rb @@ -0,0 +1,2 @@ +module CategoriesHelper +end diff --git a/app/helpers/homepages_helper.rb b/app/helpers/homepages_helper.rb new file mode 100644 index 0000000000..4bd8098f37 --- /dev/null +++ b/app/helpers/homepages_helper.rb @@ -0,0 +1,2 @@ +module HomepagesHelper +end diff --git a/app/helpers/order_items_helper.rb b/app/helpers/order_items_helper.rb new file mode 100644 index 0000000000..e197528ae1 --- /dev/null +++ b/app/helpers/order_items_helper.rb @@ -0,0 +1,2 @@ +module OrderItemsHelper +end diff --git a/app/helpers/orders_helper.rb b/app/helpers/orders_helper.rb new file mode 100644 index 0000000000..443227fd48 --- /dev/null +++ b/app/helpers/orders_helper.rb @@ -0,0 +1,2 @@ +module OrdersHelper +end diff --git a/app/helpers/products_helper.rb b/app/helpers/products_helper.rb new file mode 100644 index 0000000000..ab5c42b325 --- /dev/null +++ b/app/helpers/products_helper.rb @@ -0,0 +1,2 @@ +module ProductsHelper +end diff --git a/app/helpers/reviews_helper.rb b/app/helpers/reviews_helper.rb new file mode 100644 index 0000000000..682b7b1abc --- /dev/null +++ b/app/helpers/reviews_helper.rb @@ -0,0 +1,2 @@ +module ReviewsHelper +end diff --git a/app/helpers/users_helper.rb b/app/helpers/users_helper.rb new file mode 100644 index 0000000000..c31804b96e --- /dev/null +++ b/app/helpers/users_helper.rb @@ -0,0 +1,8 @@ +module UsersHelper + def mask_cc(cc_num) + return "[unknown]" unless cc_num + # from https://stackoverflow.com/questions/1904573/string-operation-in-ruby-for-credit-card-number + masked = cc_num.gsub(/.(?=....)/, '*') + return masked + end +end diff --git a/app/jobs/application_job.rb b/app/jobs/application_job.rb new file mode 100644 index 0000000000..a009ace51c --- /dev/null +++ b/app/jobs/application_job.rb @@ -0,0 +1,2 @@ +class ApplicationJob < ActiveJob::Base +end diff --git a/app/mailers/application_mailer.rb b/app/mailers/application_mailer.rb new file mode 100644 index 0000000000..286b2239d1 --- /dev/null +++ b/app/mailers/application_mailer.rb @@ -0,0 +1,4 @@ +class ApplicationMailer < ActionMailer::Base + default from: 'from@example.com' + layout 'mailer' +end diff --git a/app/models/application_record.rb b/app/models/application_record.rb new file mode 100644 index 0000000000..10a4cba84d --- /dev/null +++ b/app/models/application_record.rb @@ -0,0 +1,3 @@ +class ApplicationRecord < ActiveRecord::Base + self.abstract_class = true +end diff --git a/app/models/category.rb b/app/models/category.rb new file mode 100644 index 0000000000..554cbe9db2 --- /dev/null +++ b/app/models/category.rb @@ -0,0 +1,5 @@ +class Category < ApplicationRecord + has_and_belongs_to_many :products + + validates :name, presence: true, uniqueness: true +end diff --git a/app/models/concerns/.keep b/app/models/concerns/.keep new file mode 100644 index 0000000000..e69de29bb2 diff --git a/app/models/order.rb b/app/models/order.rb new file mode 100644 index 0000000000..16cbfd47ae --- /dev/null +++ b/app/models/order.rb @@ -0,0 +1,33 @@ +class Order < ApplicationRecord + has_many :order_items + + validates :address, :name, :cc_num, :cvv_code, :exp_date, :zip, presence: true, on: :update + validates :email, presence: true, format: { with: URI::MailTo::EMAIL_REGEXP }, on: :update + validates :exp_date, presence: true, format: { with: /\A(\d{2})\/(\d{2})\Z/ }, on: :update + + def total + total = 0 + self.order_items.each do |oi| + total += oi.subtotal + end + + return total + end + + def update_stock + self.order_items.each do |oi| + oi.product.stock -= oi.quantity + oi.product.save + end + + end + + def count_items + items = self.order_items + count = nil + + count = items.count + + return count + end +end diff --git a/app/models/order_item.rb b/app/models/order_item.rb new file mode 100644 index 0000000000..9abcb79421 --- /dev/null +++ b/app/models/order_item.rb @@ -0,0 +1,10 @@ +class OrderItem < ApplicationRecord + belongs_to :order + belongs_to :product + + validates :quantity, presence: true, numericality: { only_integer: true, greater_than: 0 } + + def subtotal + return self.quantity * self.product.price + end +end diff --git a/app/models/product.rb b/app/models/product.rb new file mode 100644 index 0000000000..87d4aaa5da --- /dev/null +++ b/app/models/product.rb @@ -0,0 +1,70 @@ +class Product < ApplicationRecord + has_many :order_items, dependent: :destroy + has_many :reviews, dependent: :destroy + belongs_to :user + has_and_belongs_to_many :categories + + validates :name, presence: true, uniqueness: true + validates :description, presence: true + validates :price, presence: true, numericality: {only_float: true, greater_than: 0} + validates :photo_url, presence: true + validates :stock, presence: true, numericality: {only_integer: true} + validates_inclusion_of :available, in: [true, false] + validates :user_id, presence: true + + def available_stock(order_id) + order = Order.find_by(id: order_id) + return self.stock if order.nil? + order.order_items.each do |oi| + if oi.product_id == self.id + return self.stock - oi.quantity.to_i + end + end + return self.stock + end + + def calculate_average_rating + reviews = self.reviews + + if reviews.blank? + average_rating = nil + else + product_ratings = [] + + reviews.each do |review| + product_ratings << review.rating + end + + total_rating = product_ratings.sum + average_rating = total_rating / product_ratings.length + end + + return average_rating + end + + def count_sold() + count = 0 + self.order_items.each do |oi| + if oi.status == "complete" || oi.status == "paid" + count += oi.quantity + end + end + return count + end + + def self.sample_products_for_homepage() + product_list = Product.order(Arel.sql("RANDOM()")).to_a + + sample_products_list = [] + + while sample_products_list.length < 5 && !product_list.empty? + product = product_list.pop() + + if product.available == true + sample_products_list << product + end + end + + return sample_products_list + end +end diff --git a/app/models/review.rb b/app/models/review.rb new file mode 100644 index 0000000000..fcfda55b27 --- /dev/null +++ b/app/models/review.rb @@ -0,0 +1,4 @@ +class Review < ApplicationRecord + belongs_to :product + validates :rating, presence: true, :inclusion => 1..5 +end diff --git a/app/models/user.rb b/app/models/user.rb new file mode 100644 index 0000000000..cdeb11b573 --- /dev/null +++ b/app/models/user.rb @@ -0,0 +1,174 @@ +class User < ApplicationRecord + has_many :products + + validates :username, uniqueness: true, presence: true + validates :email, uniqueness: true, presence: true, format: { with: URI::MailTo::EMAIL_REGEXP } + + def order_count + orders = self.find_orders + return orders.count + end + + def top_product + max = 0 + max_product = nil + self.products.each do |product| + + total_sold = product.count_sold() + + if total_sold > max + max = total_sold + max_product = product + end + end + + return max_product + end + + def find_orders + matching_orders = self.products.flat_map{ |prod| prod.order_items }.map{ |oi| oi.order }.uniq + return matching_orders + end + + def total_revenue_by_order(order_id) + order = Order.find(order_id) + total_cost = self.order_revenue(order) + return total_cost + end + + def order_revenue(order) + total_per_order = 0 + order.order_items.each do |oi| + product = Product.find_by(id: oi.product_id) + if product.user_id == self.id + total_per_order += oi.subtotal + end + end + return total_per_order + end + + def total_revenue() + orders = self.find_orders + + total_cost = 0.0 + orders.each do |order| + total_cost += self.order_revenue(order) + end + + return total_cost + end + + # I want the total revenue for a set of orders based on status + # I have find_orders_by_status, which will return a list of orders by status. + # Then I need to find the total revenue for each of those orders, for my merchant + def total_revenue_by_status(status) + all_orders = self.find_orders_by_status(status) + + total_revenue = 0.0 + if all_orders + all_orders.each do |order| + total_revenue += total_revenue_by_order(order.id) + end + end + + return total_revenue + end + + def find_orders_by_status(status) + if status == :all + return self.find_orders + else + orders_by_status = self.sort_orders_by_status() + return orders_by_status[status] + end + end + + def get_order_status(order) + result = find_order_statuses() + return result[:status_for_orders][order.id] + end + + def sort_orders_by_status() + result = find_order_statuses() + return result[:orders_by_status] + end + + def find_order_statuses() + orders = self.find_orders() + + orders_by_status = {} + status_for_orders = {} + + orders.each do |order| + # create a hash of this order's statuses + oi_statuses = {} + # start a count of this merchant's order items + oi_count = 0 + order.order_items.each do |oi| + product = Product.find_by(id: oi.product_id) + # if the oi belongs to this merchant + if product.user_id == self.id + # iterate the count of this merchant's order items + oi_count += 1 + # add order item status to hash + oi_status = oi.status.to_sym + if oi_statuses[oi_status] + oi_statuses[oi_status] += 1 + else + oi_statuses[oi_status] = 1 + end + # add order item status to possible order statuses hash + if orders_by_status[oi_status].nil? + orders_by_status[oi_status] = [] + end # if nil? + end # if user orderitem + end # each orderitem + + # now there's hash of the statuses of the order_items + # calculate the order status based on that + if oi_count == oi_statuses[:complete] + # if all members are complete, the order is complete + status = :complete + elsif oi_count == oi_statuses[:cancelled] + # if all members are cancelled, the order is cancelled + status = :cancelled + elsif oi_count == oi_statuses[:paid] + # if all members are paid, the order is paid + status = :paid + elsif oi_statuses[:cancelled] && oi_statuses[:complete] && oi_statuses[:paid].blank? && oi_statuses[:pending].blank? + # if some members are complete and some cancelled, the order is complete + status = :complete + elsif oi_statuses[:paid] && oi_statuses[:complete] && oi_statuses[:cancelled].blank? && oi_statuses[:pending].blank? + # if some members are paid and some are complete, the order is paid + status = :paid + else + # if all members are pending, the order is pending + status = :pending + end + + orders_by_status[status] << order + status_for_orders[order.id] = status + end + + result = { + orders_by_status: orders_by_status, + status_for_orders: status_for_orders, + } + + return result + end + + def self.build_from_github(auth_hash) + user = User.new + user.uid = auth_hash[:uid] + user.provider = "github" + user.username = auth_hash["info"]["nickname"] + user.email = auth_hash["info"]["email"] + + return user + end + + def self.list + return User.all.order(username: :asc) + end +end diff --git a/app/views/categories/_form.html.erb b/app/views/categories/_form.html.erb new file mode 100644 index 0000000000..05001d54c3 --- /dev/null +++ b/app/views/categories/_form.html.erb @@ -0,0 +1,20 @@ +
+
+

+ <%=action_name%> Category +

+ +
+ <%= form_with model: @category do |f| %> +
+ + <%= f.text_field :name, class:"form-control" %> +
+ +
+ <%= f.submit "#{action_name}", class:"btn btn-primary" %> +
+ <% end %> +
+
+
diff --git a/app/views/categories/edit.html.erb b/app/views/categories/edit.html.erb new file mode 100644 index 0000000000..2b0c8672fe --- /dev/null +++ b/app/views/categories/edit.html.erb @@ -0,0 +1 @@ +<%=render partial: 'form', locals: {action_name: "Edit", verb_name: "update"}%> diff --git a/app/views/categories/index.html.erb b/app/views/categories/index.html.erb new file mode 100644 index 0000000000..0daf3b1422 --- /dev/null +++ b/app/views/categories/index.html.erb @@ -0,0 +1,44 @@ +
+
+

+ Products by Category +

+ +<% @categories.each do |category| %> + > +
+

<%= category.name.capitalize %>

+
+ + + +
+<% category.products.each do |product| %> + <% if product.available %> +
+ class="product_img_container"> + alt=<%= product.name %> class="image product_image"> + + + +
+

<%= link_to product.name, product_path(product.id) %>

+ <%= product.description.capitalize %> +
+
+<% end %> +<% end %> +
+ +<% end %> +
diff --git a/app/views/categories/new.html.erb b/app/views/categories/new.html.erb new file mode 100644 index 0000000000..37e73509cc --- /dev/null +++ b/app/views/categories/new.html.erb @@ -0,0 +1 @@ +<%=render partial: 'form', locals: {action_name: "Create new", verb_name: "create"}%> diff --git a/app/views/homepages/_carousel_caption.html.erb b/app/views/homepages/_carousel_caption.html.erb new file mode 100644 index 0000000000..94164e5964 --- /dev/null +++ b/app/views/homepages/_carousel_caption.html.erb @@ -0,0 +1,6 @@ +> + + \ No newline at end of file diff --git a/app/views/homepages/_faq_item.html.erb b/app/views/homepages/_faq_item.html.erb new file mode 100644 index 0000000000..2a8497e7dd --- /dev/null +++ b/app/views/homepages/_faq_item.html.erb @@ -0,0 +1,9 @@ +
+

+ <%= question %> +

+ +

+ <%= answer %> +

+
\ No newline at end of file diff --git a/app/views/homepages/about.html.erb b/app/views/homepages/about.html.erb new file mode 100644 index 0000000000..daef0c5769 --- /dev/null +++ b/app/views/homepages/about.html.erb @@ -0,0 +1,112 @@ +
+ +

About Us

+ + + +
+ +

Our Purpose + + + +

+ +
+

+ Plantsy + is dedicated to providing high-quality plants + for the discerning gardener, plant enthusiast, and botanist. +

+

+ Plantsy is the brainchild of one of our founders, Sam. + The site was born in October, 2019, and was created by four students of + ADA Developer's Academy's + Cohort 12: Sam, Hallie, Georgina, and Sabrina. + This site was created as part of a class project called bEtsy. +

+

+ You can read more about Cohort 12's bEtsy project + here. +

+
+
+ +
+ +

Meet The Team + + + +

+ +
+
+
+ random animal photo +

Georgina

+
+
+ random animal photo +

Hallie

+
+
+ +
+
+ random animal photo +

Sabrina

+
+
+ random animal photo +

Samantha

+
+
+
+
+ +
+ +

Frequently Asked Questions + + + +

+ + <% question = "Is this a real online store?" %> + <% answer = "No. It's fake. Please don't give us your real information." %> + <%= render partial: 'faq_item', locals: {question: question, answer: answer} %> + + <% question = "My plant did not arrive on time." %> + <% answer = "Once we hand our plants to our shipper, they're in hands of fate." %> + <%= render partial: 'faq_item', locals: {question: question, answer: answer} %> + + <% question = "I'm looking for a specific plant, but you don't carry it; why not?" %> + <% answer = "There are a lot of plants in the world. + At least a hundred plants. + Far too many for any one company to keep stocked, + and we have only a very small warehouse." %> + <%= render partial: 'faq_item', locals: {question: question, answer: answer} %> + + <% question = "I noticed you have a picture of x plant labeled as being a y plant; + this is clearly a mistake on your part, and makes it hard to trust your expertise." %> + <% answer = "We are not plant experts. We are students." %> + <%= render partial: 'faq_item', locals: {question: question, answer: answer} %> + + <% question = "Why don't you have a 'contact us' page?" %> + <% answer = "Because--and don't take this the wrong way--we don't want you to contact us." %> + <%= render partial: 'faq_item', locals: {question: question, answer: answer} %> + + +
+
\ No newline at end of file diff --git a/app/views/homepages/index.html.erb b/app/views/homepages/index.html.erb new file mode 100644 index 0000000000..6dab78934c --- /dev/null +++ b/app/views/homepages/index.html.erb @@ -0,0 +1,65 @@ +<%# feature carousel %> +<% carousel_products = Product.sample_products_for_homepage() %> +<% first_product = carousel_products.first %> + + + +<%# product tiles %> +<%# 'shop for x category' with a row of tiles %> +
+ <% categories = Category.all %> + + <% categories.each do |category| %> +
+

+ Shop for <%= category.name %> +

+ +
+ <% category.products.each do |product| %> +
+ alt=<%= product.name %> class="card-img-top"> +
+
<%= product.name %>
+

<%= product.description %>

+ class="btn btn-primary"> See Plant +
+
+ <% end %> +
+
+ <% end %> +
diff --git a/app/views/homepages/register.html.erb b/app/views/homepages/register.html.erb new file mode 100644 index 0000000000..80758832b5 --- /dev/null +++ b/app/views/homepages/register.html.erb @@ -0,0 +1,15 @@ +
+
+

Sign Up As A Merchant

+ +

+ Want to be one of our merchants? It's as easy as logging in! +

+ +

+ Log in with your Github account to get started building your shop! +

+ + class="btn btn-primary"> Login with Github +
+
\ No newline at end of file diff --git a/app/views/layouts/application.html.erb b/app/views/layouts/application.html.erb new file mode 100644 index 0000000000..aa1d77266e --- /dev/null +++ b/app/views/layouts/application.html.erb @@ -0,0 +1,109 @@ + + + + Betsy + <%= csrf_meta_tags %> + <%= csp_meta_tag %> + + <%= stylesheet_link_tag 'application', media: 'all', 'data-turbolinks-track': 'reload' %> + <%= javascript_include_tag 'application', 'data-turbolinks-track': 'reload' %> + + + + +
+ +

+ <%= link_to "plantsy", root_path %> +

+ +
+ + <% if flash.any? %> +
+ <% if flash[:success] %> +
+ <%= flash[:success] %> +
+ <% elsif flash[:error] && flash.keys.count > 1 %> +
+
+ A problem occurred: <%= flash[:error] %> +
+ +
+ <% else %> +
+
+ A problem occurred: +
+ +
+ <% end %> +
+ <% end %> + + <%= yield %> + + + + diff --git a/app/views/layouts/mailer.html.erb b/app/views/layouts/mailer.html.erb new file mode 100644 index 0000000000..cbd34d2e9d --- /dev/null +++ b/app/views/layouts/mailer.html.erb @@ -0,0 +1,13 @@ + + + + + + + + + <%= yield %> + + diff --git a/app/views/layouts/mailer.text.erb b/app/views/layouts/mailer.text.erb new file mode 100644 index 0000000000..37f0bddbd7 --- /dev/null +++ b/app/views/layouts/mailer.text.erb @@ -0,0 +1 @@ +<%= yield %> diff --git a/app/views/orders/_form.html.erb b/app/views/orders/_form.html.erb new file mode 100644 index 0000000000..bcfbffe64a --- /dev/null +++ b/app/views/orders/_form.html.erb @@ -0,0 +1,52 @@ +
+
+

+ Checkout +

+ +
+ <%= form_with model: @order, class: "ord-input" do |form| %> +
+ +
+
+ + <%= form.text_field :name, class:"form-control" %> +
+ +
+ + <%= form.text_field :address, class:"form-control"%> +
+ +
+ + <%= form.text_field :email, class:"form-control" %> +
+ +
+ + <%= form.text_field :cc_num, class:"form-control" %> +
+ +
+ + <%= form.text_field :exp_date, class:"form-control" %> +
+ +
+ + <%= form.text_field :cvv_code, class:"form-control" %> +
+ +
+ + <%= form.text_field :zip, class:"form-control" %> +
+ +
+ <%= form.submit "Complete order", class:"btn btn-primary" %> +
+ <% end %> +
+
diff --git a/app/views/orders/checkout_show.html.erb b/app/views/orders/checkout_show.html.erb new file mode 100644 index 0000000000..c6cd221b93 --- /dev/null +++ b/app/views/orders/checkout_show.html.erb @@ -0,0 +1,60 @@ +
+
+

+ Order Confirmation +

+ +
+
+ <% order = Order.find_by(id: params[:id]) %> +
+
+
+

Personal Information

+

Name: <%= order.name %>

+

Address: <%= order.address %>

+

Zip code: <%= order.zip %>

+

email: <%= order.email %>

+
+ +
+
+

Payment Information

+

Credit Card Number: <%= order.cc_num %>

+

Expiration Date: <%= order.exp_date %>

+

CVV: <%= order.cvv_code %>

+
+ +
+
+

Order Summary

+ + + + + + + + + + + + <% order.order_items.each do |oi| %> + + + + + + <% end %> + + + + + + + + +
Product NameQuantityPriceSubtotal
<%= oi.product.name %><%= oi.quantity %>$<%= render_price(oi.product.price) %>$<%= render_price(oi.subtotal) %>
TOTAL: $<%= render_price(order.total) %>
+
+
+
diff --git a/app/views/orders/edit.html.erb b/app/views/orders/edit.html.erb new file mode 100644 index 0000000000..e74e8f7513 --- /dev/null +++ b/app/views/orders/edit.html.erb @@ -0,0 +1 @@ +<%=render partial: 'form'%> diff --git a/app/views/orders/index.html.erb b/app/views/orders/index.html.erb new file mode 100644 index 0000000000..e69de29bb2 diff --git a/app/views/orders/new.html.erb b/app/views/orders/new.html.erb new file mode 100644 index 0000000000..ac232cd66a --- /dev/null +++ b/app/views/orders/new.html.erb @@ -0,0 +1 @@ +<%=render partial: 'form', locals: {action_name: "Create new", verb_name: "create"}%> \ No newline at end of file diff --git a/app/views/orders/show.html.erb b/app/views/orders/show.html.erb new file mode 100644 index 0000000000..594b9cede4 --- /dev/null +++ b/app/views/orders/show.html.erb @@ -0,0 +1,58 @@ +
+
+

+ Order Summary +

+ +
+
+

Order # <%= @order.id %>

+
+ + + + + + + + + + + + + + + <% @order.order_items.each do |oi| %> + + + + + + + + + <% end %> + + + + + + + + + + +
Product NameChange QuantityQuantityPriceSubtotal
<%= link_to oi.product.name, product_path(oi.product_id) %> + <%= form_with model: @order_items, url: order_item_path(oi.id) do |f| %> + + <%= f.select :quantity, (1..20) %> + <%= f.submit "Update", class:"btn btn-primary" %> + <% end %> + <%= oi.quantity %>$<%= render_price(oi.product.price) %>$<%= render_price(oi.subtotal) %><%= link_to "Remove", order_item_path(oi.id), method: :delete, class:"btn btn-primary" %>
TOTAL: $<%= render_price(@order.total) %>
+ +
+ <%= link_to "CONTINUE SHOPPING", products_path, method: :get, class:"btn btn-primary" %> + <%= link_to "CHECKOUT", edit_order_path, method: :get, class: "btn btn-primary" %> +
+
+
diff --git a/app/views/products/_form.html.erb b/app/views/products/_form.html.erb new file mode 100644 index 0000000000..09c56bd80c --- /dev/null +++ b/app/views/products/_form.html.erb @@ -0,0 +1,50 @@ +
+
+

+ <%=action_name%> Product +

+ +
+ <%= form_with model: @product do |f| %> +
+ <%= f.label :categories, class:"checkbox-inline" %> + <%= collection_check_boxes(:product, :category_ids, Category.all, :id, :name) %> +
+ +
+ + <%=f.text_field :name, class:"form-control"%> +
+ +
+ + <%=f.text_field :user_id, class:"form-control"%> +
+ +
+ + <%=f.text_field :price, class:"form-control"%> +
+ +
+ + <%=f.text_field :stock, class:"form-control"%> +
+ +
+ + <%=f.text_field :photo_url, class:"form-control"%> +
+ +
+ + <%=f.text_field :description, class:"form-control"%> +
+ +
+ <%= f.submit "#{action_name}", class:"btn btn-primary" %> +
+ <%end%> +
+
+
diff --git a/app/views/products/edit.html.erb b/app/views/products/edit.html.erb new file mode 100644 index 0000000000..2b0c8672fe --- /dev/null +++ b/app/views/products/edit.html.erb @@ -0,0 +1 @@ +<%=render partial: 'form', locals: {action_name: "Edit", verb_name: "update"}%> diff --git a/app/views/products/index.html.erb b/app/views/products/index.html.erb new file mode 100644 index 0000000000..82a681c91a --- /dev/null +++ b/app/views/products/index.html.erb @@ -0,0 +1,29 @@ +
+
+

+ All Products +

+
+ +
+<% @products.each do |product| %> + +<% if product.available %> +
+ + class="product_img_container"> + alt=<%= product.name %> class="image product_image"> + + + +
+

<%= link_to product.name, product_path(product.id) %>

+ Price: $<%= product.price %> +
+
+ <% end %> +<% end %> +
+
diff --git a/app/views/products/new.html.erb b/app/views/products/new.html.erb new file mode 100644 index 0000000000..37e73509cc --- /dev/null +++ b/app/views/products/new.html.erb @@ -0,0 +1 @@ +<%=render partial: 'form', locals: {action_name: "Create new", verb_name: "create"}%> diff --git a/app/views/products/show.html.erb b/app/views/products/show.html.erb new file mode 100644 index 0000000000..fca5958b6d --- /dev/null +++ b/app/views/products/show.html.erb @@ -0,0 +1,58 @@ +
+
+ +
+ alt=<%= @product.name %> class="product_image_show"> +
+ +
+

<%= @product.name %>

+

Ratings summary: <%= render_rating(@product.calculate_average_rating) %>

+
+

Description: <%= @product.description.capitalize %>

+

Stock: <%= @product.available_stock(session[:order_id]) %> units

+

Price: $<%= @product.price %>

+ <%= form_with model: @order_items, url: product_order_items_path(@product.id) do |f| %> + <%= f.select :quantity, (1..10) %> + <%= f.submit "ADD TO CART", class:"btn btn-primary" %> + <%end%> +
+ + + + + + + + + + + + <% @product.reviews.each do |review| %> + + + + + <% end %> + +
RatingReviews
<%= render_rating(review.rating) %><%= review.comment %>
+ +
+ <% if session[:user_id].nil? || session[:user_id] != @product.user_id %> + <%=render partial: 'shared/review_form'%> + <% end %> +
+
+
diff --git a/app/views/reviews/_form.html.erb b/app/views/reviews/_form.html.erb new file mode 100644 index 0000000000..d9734698eb --- /dev/null +++ b/app/views/reviews/_form.html.erb @@ -0,0 +1,17 @@ +
+ <%= form_with model: @review, url: "/products/#{(@product_id)}/reviews", class: "review-input" do |form| %> +
+ +
+ + <%= form.text_field :comment, class:"form-control"%> +
+
+ <%= form.submit "Submit", class: 'btn btn-primary' %> +
+
+ <% end %> +
\ No newline at end of file diff --git a/app/views/reviews/new.html.erb b/app/views/reviews/new.html.erb new file mode 100644 index 0000000000..9b508decb9 --- /dev/null +++ b/app/views/reviews/new.html.erb @@ -0,0 +1 @@ +<%=render partial: 'form'%> \ No newline at end of file diff --git a/app/views/shared/_review_form.html.erb b/app/views/shared/_review_form.html.erb new file mode 100644 index 0000000000..9bf8606540 --- /dev/null +++ b/app/views/shared/_review_form.html.erb @@ -0,0 +1,17 @@ +
+ <%= form_with model: @review, url: "/products/#{@product.id}/reviews", class: "review-input" do |form| %> +
+ +
+ + <%= form.text_field :comment, class:"form-control"%> +
+
+ <%= form.submit "Submit", class: 'btn btn-primary' %> +
+
+ <% end %> +
\ No newline at end of file diff --git a/app/views/users/_orders.html.erb b/app/views/users/_orders.html.erb new file mode 100644 index 0000000000..7bbd7553a5 --- /dev/null +++ b/app/views/users/_orders.html.erb @@ -0,0 +1,127 @@ +<% all_orders = @user.find_orders_by_status(given_status) %> + +
+

+ Total Revenue +

+
+ <% if given_status == :cancelled %> + $0.00 + <% else %> + $<%= render_price(@user.total_revenue_by_status(given_status)) %> + <% end %> +
+ +

+ Number of Orders +

+
+ <% if all_orders && all_orders.length > 0 %> + <%= all_orders.length %> + <% else %> + 0 + <% end %> +
+
+ +
+ <% if all_orders && all_orders.length > 0 %> + <% all_orders.each do |order| %> +
+
+ +
+ + + + + + + + + + + + + <% order.order_items.each do |oi| %> + <% product = Product.find_by(id: oi.product_id) %> + <% if product.user_id == @user.id %> + + + + + + + <% end %> + <% end %> + + + + + + + +
order itemstatusquantitysubtotal
+ <%= link_to product.name, product_path(product.id) %> + + <% if oi.status != "complete" %> + <%= link_to "mark completed", mark_complete_path(oi.id), method: :post %> + <% else %> + <%= oi.status %> + <% end %> + + <%= oi.quantity %> + + $<%= render_price(oi.subtotal) %> +
$<%= render_price(@user.total_revenue_by_order(order.id)) %>
+ +
+
Buyer
+ +
    +
  • + <%= order.name %> +
  • +
  • + <%= order.email %> +
  • +
  • + <%= order.address %> +
  • +
  • + <%= mask_cc(order.cc_num) %> +
  • +
  • + Card expires on <%= order.exp_date %> +
  • +
      +
+ +
+ <% end %> +
+ + <% else %> +
+ <% if given_status == :all %> + You do not yet have any orders + <% else %> + You do not have any <%= given_status.to_s %> orders + <% end %> +
+ <% end %> +
\ No newline at end of file diff --git a/app/views/users/dashboard.html.erb b/app/views/users/dashboard.html.erb new file mode 100644 index 0000000000..0819515de7 --- /dev/null +++ b/app/views/users/dashboard.html.erb @@ -0,0 +1,193 @@ +
+
+
+

+ <%= @user.username %> +

+
    +
  • <%= @user.email %>
  • +
+
+ +
+ +
+ + + + + +
+ +
+ + +
+
+

Products

+
+
+ + <% top_product = @user.top_product %> +
+
+

Top Selling Product

+ + <% if top_product %> +
+
<%= top_product.name %>
+
    +
  • <%= top_product.count_sold %> sold
  • +
  • <%= top_product.stock %> in stock
  • +
+
+ <% else %> +

You have not sold any products yet

+ <% end %> +
+
+ +
+ + <%# toggle %> + <% toggle_num = 0 %> + + <% @user.products.each do |product| %> +
+ + <%# toggle %> + <% toggle = "toggle_" + toggle_num.to_s %> + +
+ +
+ + <%= link_to product.name, product_path(product.id) %> + + <%= product.stock %> in stock +
+ + class="toggle__product"> + + +
+
+ alt=<%= product.name %> class="merchant_product_image"> + +
+
+ +
+
+ <%= product.description %> +
+
+ <%= link_to "edit product", edit_product_path(product.id), class: "btn btn-light edit_product_button" %> +
+
+ +
+
+
+

Price

+
+ $<%= product.price %> +
+
+ + <% if product.available %> +
+ Currently Available +
+
+ <%= link_to "Retire Product", retired_path(product), method: :patch, class: "availability btn btn-danger mark_retired" %> +
+ <% else %> +
+ Retired +
+
+ <%= link_to "Reactivate Product", retired_path(product), method: :patch, class: "availability btn btn-danger mark_available" %> +
+ <% end %> +
+ +
+

Categories

+ <% product.categories.each do |category| %> +
<%= category.name %>
+ <% end %> +
+
+
+
+ +
+ + <%# toggle %> + <% toggle_num += 1 %> + <% end %> +
+
+
+ +
+
+

Orders

+
+
+ +
+ <% all_statuses = ["all", "pending", "paid", "cancelled", "complete"] %> + + <%# you can't combine these loops, + because weird solutions have weird quirks %> + + + <% all_statuses.each do |status| %> + <% all_orders = @user.find_orders_by_status(status.to_sym) %> + + > + + <% end %> + + + <% all_statuses.each do |status| %> +
+ <%= render partial: "orders", locals: {given_status: status.to_sym} %> +
+ <% end %> +
+
+
+
+
diff --git a/app/views/users/edit.html.erb b/app/views/users/edit.html.erb new file mode 100644 index 0000000000..e69de29bb2 diff --git a/app/views/users/index.html.erb b/app/views/users/index.html.erb new file mode 100644 index 0000000000..1f1b1e755a --- /dev/null +++ b/app/views/users/index.html.erb @@ -0,0 +1,13 @@ +
+

+ All Merchants +

+ +
+ <% @users.each do |user| %> + class="merchant_tile"> + <%= user.username %> + + <% end %> +
+
\ No newline at end of file diff --git a/app/views/users/show.html.erb b/app/views/users/show.html.erb new file mode 100644 index 0000000000..c2f9a11bc3 --- /dev/null +++ b/app/views/users/show.html.erb @@ -0,0 +1,32 @@ +
+

+ Products by <%= @user.username %> +

+ + <% if @user.products.empty? %> +

+ Sorry, this merchant doesn't have any products yet +

+ <% else %> + + <% end %> +
diff --git a/bin/bundle b/bin/bundle new file mode 100755 index 0000000000..f19acf5b5c --- /dev/null +++ b/bin/bundle @@ -0,0 +1,3 @@ +#!/usr/bin/env ruby +ENV['BUNDLE_GEMFILE'] ||= File.expand_path('../Gemfile', __dir__) +load Gem.bin_path('bundler', 'bundle') diff --git a/bin/rails b/bin/rails new file mode 100755 index 0000000000..5badb2fde0 --- /dev/null +++ b/bin/rails @@ -0,0 +1,9 @@ +#!/usr/bin/env ruby +begin + load File.expand_path('../spring', __FILE__) +rescue LoadError => e + raise unless e.message.include?('spring') +end +APP_PATH = File.expand_path('../config/application', __dir__) +require_relative '../config/boot' +require 'rails/commands' diff --git a/bin/rake b/bin/rake new file mode 100755 index 0000000000..d87d5f5781 --- /dev/null +++ b/bin/rake @@ -0,0 +1,9 @@ +#!/usr/bin/env ruby +begin + load File.expand_path('../spring', __FILE__) +rescue LoadError => e + raise unless e.message.include?('spring') +end +require_relative '../config/boot' +require 'rake' +Rake.application.run diff --git a/bin/setup b/bin/setup new file mode 100755 index 0000000000..94fd4d7977 --- /dev/null +++ b/bin/setup @@ -0,0 +1,36 @@ +#!/usr/bin/env ruby +require 'fileutils' +include FileUtils + +# path to your application root. +APP_ROOT = File.expand_path('..', __dir__) + +def system!(*args) + system(*args) || abort("\n== Command #{args} failed ==") +end + +chdir APP_ROOT do + # This script is a starting point to setup your application. + # Add necessary setup steps to this file. + + puts '== Installing dependencies ==' + system! 'gem install bundler --conservative' + system('bundle check') || system!('bundle install') + + # Install JavaScript dependencies if using Yarn + # system('bin/yarn') + + # puts "\n== Copying sample files ==" + # unless File.exist?('config/database.yml') + # cp 'config/database.yml.sample', 'config/database.yml' + # end + + puts "\n== Preparing database ==" + system! 'bin/rails db:setup' + + puts "\n== Removing old logs and tempfiles ==" + system! 'bin/rails log:clear tmp:clear' + + puts "\n== Restarting application server ==" + system! 'bin/rails restart' +end diff --git a/bin/spring b/bin/spring new file mode 100755 index 0000000000..d89ee495fa --- /dev/null +++ b/bin/spring @@ -0,0 +1,17 @@ +#!/usr/bin/env ruby + +# This file loads Spring without using Bundler, in order to be fast. +# It gets overwritten when you run the `spring binstub` command. + +unless defined?(Spring) + require 'rubygems' + require 'bundler' + + lockfile = Bundler::LockfileParser.new(Bundler.default_lockfile.read) + spring = lockfile.specs.detect { |spec| spec.name == 'spring' } + if spring + Gem.use_paths Gem.dir, Bundler.bundle_path.to_s, *Gem.path + gem 'spring', spring.version + require 'spring/binstub' + end +end diff --git a/bin/update b/bin/update new file mode 100755 index 0000000000..58bfaed518 --- /dev/null +++ b/bin/update @@ -0,0 +1,31 @@ +#!/usr/bin/env ruby +require 'fileutils' +include FileUtils + +# path to your application root. +APP_ROOT = File.expand_path('..', __dir__) + +def system!(*args) + system(*args) || abort("\n== Command #{args} failed ==") +end + +chdir APP_ROOT do + # This script is a way to update your development environment automatically. + # Add necessary update steps to this file. + + puts '== Installing dependencies ==' + system! 'gem install bundler --conservative' + system('bundle check') || system!('bundle install') + + # Install JavaScript dependencies if using Yarn + # system('bin/yarn') + + puts "\n== Updating database ==" + system! 'bin/rails db:migrate' + + puts "\n== Removing old logs and tempfiles ==" + system! 'bin/rails log:clear tmp:clear' + + puts "\n== Restarting application server ==" + system! 'bin/rails restart' +end diff --git a/bin/yarn b/bin/yarn new file mode 100755 index 0000000000..460dd565b4 --- /dev/null +++ b/bin/yarn @@ -0,0 +1,11 @@ +#!/usr/bin/env ruby +APP_ROOT = File.expand_path('..', __dir__) +Dir.chdir(APP_ROOT) do + begin + exec "yarnpkg", *ARGV + rescue Errno::ENOENT + $stderr.puts "Yarn executable was not detected in the system." + $stderr.puts "Download Yarn at https://yarnpkg.com/en/docs/install" + exit 1 + end +end diff --git a/config.ru b/config.ru new file mode 100644 index 0000000000..f7ba0b527b --- /dev/null +++ b/config.ru @@ -0,0 +1,5 @@ +# This file is used by Rack-based servers to start the application. + +require_relative 'config/environment' + +run Rails.application diff --git a/config/application.rb b/config/application.rb new file mode 100644 index 0000000000..5c09a3eefc --- /dev/null +++ b/config/application.rb @@ -0,0 +1,25 @@ +require_relative 'boot' + +require 'rails/all' + +# Require the gems listed in Gemfile, including any gems +# you've limited to :test, :development, or :production. +Bundler.require(*Rails.groups) + +module Betsy + class Application < Rails::Application + config.generators do |g| + # Force new test files to be generated in the minitest-spec style + g.test_framework :minitest, spec: true + # Always use .js files, never .coffee + g.javascript_engine :js + end + # Initialize configuration defaults for originally generated Rails version. + config.load_defaults 5.2 + + # Settings in config/environments/* take precedence over those specified here. + # Application configuration can go into files in config/initializers + # -- all .rb files in that directory are automatically loaded after loading + # the framework and any gems in your application. + end +end diff --git a/config/boot.rb b/config/boot.rb new file mode 100644 index 0000000000..b9e460cef3 --- /dev/null +++ b/config/boot.rb @@ -0,0 +1,4 @@ +ENV['BUNDLE_GEMFILE'] ||= File.expand_path('../Gemfile', __dir__) + +require 'bundler/setup' # Set up gems listed in the Gemfile. +require 'bootsnap/setup' # Speed up boot time by caching expensive operations. diff --git a/config/cable.yml b/config/cable.yml new file mode 100644 index 0000000000..dd2a324c68 --- /dev/null +++ b/config/cable.yml @@ -0,0 +1,10 @@ +development: + adapter: async + +test: + adapter: async + +production: + adapter: redis + url: <%= ENV.fetch("REDIS_URL") { "redis://localhost:6379/1" } %> + channel_prefix: betsy_production diff --git a/config/credentials.yml.enc b/config/credentials.yml.enc new file mode 100644 index 0000000000..fc76b28814 --- /dev/null +++ b/config/credentials.yml.enc @@ -0,0 +1 @@ +E3LLP7Vwq0mXdSeioALPOsv21dYAkJdglfGY0pk6i1khlk7qhcKblVb7pxORCsjSX7syHOFk8P+AvFE8xD6HM+ghWgb3EL3DkMUkT4O2d2VhrkmeyZTiernu5KhszgLZSUiWo7Q8UvpsluIAhwlat3PDLdVo4RYA0kLc0b1Vw9g4NMKlq5gWXIYxfNHhXuEaC/wjg7h1oupecxoMLRrYjeZodflAXuj9mMhVJ8JDGWcdHRJUzftKaQOSla2CxcJ+x+w8A39pcDe/zgXUXU004VroH7GvslFDhbUeEkEUpw+6Mvssugb0PC0eakbnaD06fJWPjtMMCk5XFtcW2iTnPMYCeyFcxdPvDxQIEKG6HjsmdpUmG0hdVw75/ap7EsGA8bWocUbd4+YP/Xs6Et3EWBEoh9RwOr/Ashvy--5Zl8/kyjoPcqnSaH--1gukdSUjH8yBU6gFoSNG+g== \ No newline at end of file diff --git a/config/database.yml b/config/database.yml new file mode 100644 index 0000000000..6903bb6083 --- /dev/null +++ b/config/database.yml @@ -0,0 +1,85 @@ +# PostgreSQL. Versions 9.1 and up are supported. +# +# Install the pg driver: +# gem install pg +# On OS X with Homebrew: +# gem install pg -- --with-pg-config=/usr/local/bin/pg_config +# On OS X with MacPorts: +# gem install pg -- --with-pg-config=/opt/local/lib/postgresql84/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 + # http://guides.rubyonrails.org/configuring.html#database-pooling + pool: <%= ENV.fetch("RAILS_MAX_THREADS") { 5 } %> + +development: + <<: *default + database: betsy_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 that initialized the database. + #username: betsy + + # 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: betsy_test + +# As with config/secrets.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 as a unix environment variable when you boot +# the app. Read http://guides.rubyonrails.org/configuring.html#configuring-a-database +# for a full rundown on how to provide these environment variables in a +# production deployment. +# +# On Heroku and other platform providers, you may have a full connection URL +# available as an environment variable. For example: +# +# DATABASE_URL="postgres://myuser:mypass@localhost/somedatabase" +# +# You can use this database configuration with: +# +# production: +# url: <%= ENV['DATABASE_URL'] %> +# +production: + <<: *default + database: betsy_production + username: betsy + password: <%= ENV['BETSY_DATABASE_PASSWORD'] %> diff --git a/config/environment.rb b/config/environment.rb new file mode 100644 index 0000000000..426333bb46 --- /dev/null +++ b/config/environment.rb @@ -0,0 +1,5 @@ +# Load the Rails application. +require_relative 'application' + +# Initialize the Rails application. +Rails.application.initialize! diff --git a/config/environments/development.rb b/config/environments/development.rb new file mode 100644 index 0000000000..1311e3e4ef --- /dev/null +++ b/config/environments/development.rb @@ -0,0 +1,61 @@ +Rails.application.configure do + # Settings specified here will take precedence over those in config/application.rb. + + # In the development environment your application's code is reloaded on + # every request. This slows down response time but is perfect for development + # since you don't have to restart the web server when you make code changes. + config.cache_classes = false + + # Do not eager load code on boot. + config.eager_load = false + + # Show full error reports. + config.consider_all_requests_local = true + + # Enable/disable caching. By default caching is disabled. + # Run rails dev:cache to toggle caching. + if Rails.root.join('tmp', 'caching-dev.txt').exist? + config.action_controller.perform_caching = true + + config.cache_store = :memory_store + config.public_file_server.headers = { + 'Cache-Control' => "public, max-age=#{2.days.to_i}" + } + else + config.action_controller.perform_caching = false + + config.cache_store = :null_store + end + + # Store uploaded files on the local file system (see config/storage.yml for options) + config.active_storage.service = :local + + # Don't care if the mailer can't send. + config.action_mailer.raise_delivery_errors = false + + config.action_mailer.perform_caching = false + + # Print deprecation notices to the Rails logger. + config.active_support.deprecation = :log + + # Raise an error on page load if there are pending migrations. + config.active_record.migration_error = :page_load + + # Highlight code that triggered database queries in logs. + config.active_record.verbose_query_logs = true + + # Debug mode disables concatenation and preprocessing of assets. + # This option may cause significant delays in view rendering with a large + # number of complex assets. + config.assets.debug = true + + # Suppress logger output for asset requests. + config.assets.quiet = true + + # Raises error for missing translations + # config.action_view.raise_on_missing_translations = true + + # Use an evented file watcher to asynchronously detect changes in source code, + # routes, locales, etc. This feature depends on the listen gem. + config.file_watcher = ActiveSupport::EventedFileUpdateChecker +end diff --git a/config/environments/production.rb b/config/environments/production.rb new file mode 100644 index 0000000000..5f6f3058c6 --- /dev/null +++ b/config/environments/production.rb @@ -0,0 +1,94 @@ +Rails.application.configure do + # Settings specified here will take precedence over those in config/application.rb. + + # Code is not reloaded between requests. + config.cache_classes = true + + # Eager load code on boot. This eager loads most of Rails and + # your application in memory, allowing both threaded web servers + # and those relying on copy on write to perform better. + # Rake tasks automatically ignore this option for performance. + config.eager_load = true + + # Full error reports are disabled and caching is turned on. + config.consider_all_requests_local = false + config.action_controller.perform_caching = true + + # Ensures that a master key has been made available in either ENV["RAILS_MASTER_KEY"] + # or in config/master.key. This key is used to decrypt credentials (and other encrypted files). + # config.require_master_key = true + + # Disable serving static files from the `/public` folder by default since + # Apache or NGINX already handles this. + config.public_file_server.enabled = ENV['RAILS_SERVE_STATIC_FILES'].present? + + # Compress JavaScripts and CSS. + config.assets.js_compressor = :uglifier + # config.assets.css_compressor = :sass + + # Do not fallback to assets pipeline if a precompiled asset is missed. + config.assets.compile = false + + # `config.assets.precompile` and `config.assets.version` have moved to config/initializers/assets.rb + + # Enable serving of images, stylesheets, and JavaScripts from an asset server. + # config.action_controller.asset_host = 'http://assets.example.com' + + # Specifies the header that your server uses for sending files. + # config.action_dispatch.x_sendfile_header = 'X-Sendfile' # for Apache + # config.action_dispatch.x_sendfile_header = 'X-Accel-Redirect' # for NGINX + + # Store uploaded files on the local file system (see config/storage.yml for options) + config.active_storage.service = :local + + # Mount Action Cable outside main process or domain + # config.action_cable.mount_path = nil + # config.action_cable.url = 'wss://example.com/cable' + # config.action_cable.allowed_request_origins = [ 'http://example.com', /http:\/\/example.*/ ] + + # Force all access to the app over SSL, use Strict-Transport-Security, and use secure cookies. + # config.force_ssl = true + + # Use the lowest log level to ensure availability of diagnostic information + # when problems arise. + config.log_level = :debug + + # Prepend all log lines with the following tags. + config.log_tags = [ :request_id ] + + # Use a different cache store in production. + # config.cache_store = :mem_cache_store + + # Use a real queuing backend for Active Job (and separate queues per environment) + # config.active_job.queue_adapter = :resque + # config.active_job.queue_name_prefix = "betsy_#{Rails.env}" + + config.action_mailer.perform_caching = false + + # Ignore bad email addresses and do not raise email delivery errors. + # Set this to true and configure the email server for immediate delivery to raise delivery errors. + # config.action_mailer.raise_delivery_errors = false + + # Enable locale fallbacks for I18n (makes lookups for any locale fall back to + # the I18n.default_locale when a translation cannot be found). + config.i18n.fallbacks = true + + # Send deprecation notices to registered listeners. + config.active_support.deprecation = :notify + + # Use default logging formatter so that PID and timestamp are not suppressed. + config.log_formatter = ::Logger::Formatter.new + + # Use a different logger for distributed setups. + # require 'syslog/logger' + # config.logger = ActiveSupport::TaggedLogging.new(Syslog::Logger.new 'app-name') + + if ENV["RAILS_LOG_TO_STDOUT"].present? + logger = ActiveSupport::Logger.new(STDOUT) + logger.formatter = config.log_formatter + config.logger = ActiveSupport::TaggedLogging.new(logger) + end + + # Do not dump schema after migrations. + config.active_record.dump_schema_after_migration = false +end diff --git a/config/environments/test.rb b/config/environments/test.rb new file mode 100644 index 0000000000..0a38fd3ce9 --- /dev/null +++ b/config/environments/test.rb @@ -0,0 +1,46 @@ +Rails.application.configure do + # Settings specified here will take precedence over those in config/application.rb. + + # The test environment is used exclusively to run your application's + # test suite. You never need to work with it otherwise. Remember that + # your test database is "scratch space" for the test suite and is wiped + # and recreated between test runs. Don't rely on the data there! + config.cache_classes = true + + # Do not eager load code on boot. This avoids loading your whole application + # just for the purpose of running a single test. If you are using a tool that + # preloads Rails for running tests, you may have to set it to true. + config.eager_load = false + + # Configure public file server for tests with Cache-Control for performance. + config.public_file_server.enabled = true + config.public_file_server.headers = { + 'Cache-Control' => "public, max-age=#{1.hour.to_i}" + } + + # Show full error reports and disable caching. + config.consider_all_requests_local = true + config.action_controller.perform_caching = false + + # Raise exceptions instead of rendering exception templates. + config.action_dispatch.show_exceptions = false + + # Disable request forgery protection in test environment. + config.action_controller.allow_forgery_protection = false + + # Store uploaded files on the local file system in a temporary directory + config.active_storage.service = :test + + config.action_mailer.perform_caching = false + + # Tell Action Mailer not to deliver emails to the real world. + # The :test delivery method accumulates sent emails in the + # ActionMailer::Base.deliveries array. + config.action_mailer.delivery_method = :test + + # Print deprecation notices to the stderr. + config.active_support.deprecation = :stderr + + # Raises error for missing translations + # config.action_view.raise_on_missing_translations = true +end diff --git a/config/initializers/action_view.rb b/config/initializers/action_view.rb new file mode 100644 index 0000000000..142d382f87 --- /dev/null +++ b/config/initializers/action_view.rb @@ -0,0 +1 @@ +Rails.application.config.action_view.form_with_generates_remote_forms = false diff --git a/config/initializers/application_controller_renderer.rb b/config/initializers/application_controller_renderer.rb new file mode 100644 index 0000000000..89d2efab2b --- /dev/null +++ b/config/initializers/application_controller_renderer.rb @@ -0,0 +1,8 @@ +# Be sure to restart your server when you modify this file. + +# ActiveSupport::Reloader.to_prepare do +# ApplicationController.renderer.defaults.merge!( +# http_host: 'example.org', +# https: false +# ) +# end diff --git a/config/initializers/assets.rb b/config/initializers/assets.rb new file mode 100644 index 0000000000..4b828e80cb --- /dev/null +++ b/config/initializers/assets.rb @@ -0,0 +1,14 @@ +# Be sure to restart your server when you modify this file. + +# Version of your assets, change this if you want to expire all your assets. +Rails.application.config.assets.version = '1.0' + +# Add additional assets to the asset load path. +# Rails.application.config.assets.paths << Emoji.images_path +# Add Yarn node_modules folder to the asset load path. +Rails.application.config.assets.paths << Rails.root.join('node_modules') + +# Precompile additional assets. +# application.js, application.css, and all non-JS/CSS in the app/assets +# folder are already added. +# Rails.application.config.assets.precompile += %w( admin.js admin.css ) diff --git a/config/initializers/backtrace_silencers.rb b/config/initializers/backtrace_silencers.rb new file mode 100644 index 0000000000..59385cdf37 --- /dev/null +++ b/config/initializers/backtrace_silencers.rb @@ -0,0 +1,7 @@ +# Be sure to restart your server when you modify this file. + +# You can add backtrace silencers for libraries that you're using but don't wish to see in your backtraces. +# Rails.backtrace_cleaner.add_silencer { |line| line =~ /my_noisy_library/ } + +# You can also remove all the silencers if you're trying to debug a problem that might stem from framework code. +# Rails.backtrace_cleaner.remove_silencers! diff --git a/config/initializers/content_security_policy.rb b/config/initializers/content_security_policy.rb new file mode 100644 index 0000000000..d3bcaa5ec8 --- /dev/null +++ b/config/initializers/content_security_policy.rb @@ -0,0 +1,25 @@ +# Be sure to restart your server when you modify this file. + +# Define an application-wide content security policy +# For further information see the following documentation +# https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/Content-Security-Policy + +# Rails.application.config.content_security_policy do |policy| +# policy.default_src :self, :https +# policy.font_src :self, :https, :data +# policy.img_src :self, :https, :data +# policy.object_src :none +# policy.script_src :self, :https +# policy.style_src :self, :https + +# # Specify URI for violation reports +# # policy.report_uri "/csp-violation-report-endpoint" +# end + +# If you are using UJS then enable automatic nonce generation +# Rails.application.config.content_security_policy_nonce_generator = -> request { SecureRandom.base64(16) } + +# Report CSP violations to a specified URI +# For further information see the following documentation: +# https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/Content-Security-Policy-Report-Only +# Rails.application.config.content_security_policy_report_only = true diff --git a/config/initializers/cookies_serializer.rb b/config/initializers/cookies_serializer.rb new file mode 100644 index 0000000000..5a6a32d371 --- /dev/null +++ b/config/initializers/cookies_serializer.rb @@ -0,0 +1,5 @@ +# Be sure to restart your server when you modify this file. + +# Specify a serializer for the signed and encrypted cookie jars. +# Valid options are :json, :marshal, and :hybrid. +Rails.application.config.action_dispatch.cookies_serializer = :json diff --git a/config/initializers/filter_parameter_logging.rb b/config/initializers/filter_parameter_logging.rb new file mode 100644 index 0000000000..4a994e1e7b --- /dev/null +++ b/config/initializers/filter_parameter_logging.rb @@ -0,0 +1,4 @@ +# Be sure to restart your server when you modify this file. + +# Configure sensitive parameters which will be filtered from the log file. +Rails.application.config.filter_parameters += [:password] diff --git a/config/initializers/inflections.rb b/config/initializers/inflections.rb new file mode 100644 index 0000000000..ac033bf9dc --- /dev/null +++ b/config/initializers/inflections.rb @@ -0,0 +1,16 @@ +# Be sure to restart your server when you modify this file. + +# Add new inflection rules using the following format. Inflections +# are locale specific, and you may define rules for as many different +# locales as you wish. All of these examples are active by default: +# ActiveSupport::Inflector.inflections(:en) do |inflect| +# inflect.plural /^(ox)$/i, '\1en' +# inflect.singular /^(ox)en/i, '\1' +# inflect.irregular 'person', 'people' +# inflect.uncountable %w( fish sheep ) +# end + +# These inflection rules are supported but not enabled by default: +# ActiveSupport::Inflector.inflections(:en) do |inflect| +# inflect.acronym 'RESTful' +# end diff --git a/config/initializers/mime_types.rb b/config/initializers/mime_types.rb new file mode 100644 index 0000000000..dc1899682b --- /dev/null +++ b/config/initializers/mime_types.rb @@ -0,0 +1,4 @@ +# Be sure to restart your server when you modify this file. + +# Add new mime types for use in respond_to blocks: +# Mime::Type.register "text/richtext", :rtf diff --git a/config/initializers/omniauth.rb b/config/initializers/omniauth.rb new file mode 100644 index 0000000000..e32a45234e --- /dev/null +++ b/config/initializers/omniauth.rb @@ -0,0 +1,3 @@ +Rails.application.config.middleware.use OmniAuth::Builder do + provider :github, ENV["GITHUB_CLIENT_ID"], ENV["GITHUB_CLIENT_SECRET"], scope: "user:email" +end \ No newline at end of file diff --git a/config/initializers/wrap_parameters.rb b/config/initializers/wrap_parameters.rb new file mode 100644 index 0000000000..bbfc3961bf --- /dev/null +++ b/config/initializers/wrap_parameters.rb @@ -0,0 +1,14 @@ +# Be sure to restart your server when you modify this file. + +# This file contains settings for ActionController::ParamsWrapper which +# is enabled by default. + +# Enable parameter wrapping for JSON. You can disable this by setting :format to an empty array. +ActiveSupport.on_load(:action_controller) do + wrap_parameters format: [:json] +end + +# To enable root element in JSON for ActiveRecord objects. +# ActiveSupport.on_load(:active_record) do +# self.include_root_in_json = true +# end diff --git a/config/locales/en.yml b/config/locales/en.yml new file mode 100644 index 0000000000..decc5a8573 --- /dev/null +++ b/config/locales/en.yml @@ -0,0 +1,33 @@ +# Files in the config/locales directory are used for internationalization +# and are automatically loaded by Rails. If you want to use locales other +# than English, add the necessary files in this directory. +# +# To use the locales, use `I18n.t`: +# +# I18n.t 'hello' +# +# In views, this is aliased to just `t`: +# +# <%= t('hello') %> +# +# To use a different locale, set it with `I18n.locale`: +# +# I18n.locale = :es +# +# This would use the information in config/locales/es.yml. +# +# The following keys must be escaped otherwise they will not be retrieved by +# the default I18n backend: +# +# true, false, on, off, yes, no +# +# Instead, surround them with single quotes. +# +# en: +# 'true': 'foo' +# +# To learn more, please read the Rails Internationalization guide +# available at http://guides.rubyonrails.org/i18n.html. + +en: + hello: "Hello world" diff --git a/config/puma.rb b/config/puma.rb new file mode 100644 index 0000000000..a5eccf816b --- /dev/null +++ b/config/puma.rb @@ -0,0 +1,34 @@ +# Puma can serve each request in a thread from an internal thread pool. +# The `threads` method setting takes two numbers: a minimum and maximum. +# Any libraries that use thread pools should be configured to match +# the maximum value specified for Puma. Default is set to 5 threads for minimum +# and maximum; this matches the default thread size of Active Record. +# +threads_count = ENV.fetch("RAILS_MAX_THREADS") { 5 } +threads threads_count, threads_count + +# Specifies the `port` that Puma will listen on to receive requests; default is 3000. +# +port ENV.fetch("PORT") { 3000 } + +# Specifies the `environment` that Puma will run in. +# +environment ENV.fetch("RAILS_ENV") { "development" } + +# Specifies the number of `workers` to boot in clustered mode. +# Workers are forked webserver processes. If using threads and workers together +# the concurrency of the application would be max `threads` * `workers`. +# Workers do not work on JRuby or Windows (both of which do not support +# processes). +# +# workers ENV.fetch("WEB_CONCURRENCY") { 2 } + +# Use the `preload_app!` method when specifying a `workers` number. +# This directive tells Puma to first boot the application and load code +# before forking the application. This takes advantage of Copy On Write +# process behavior so workers use less memory. +# +# preload_app! + +# Allow puma to be restarted by `rails restart` command. +plugin :tmp_restart diff --git a/config/routes.rb b/config/routes.rb new file mode 100644 index 0000000000..d8c8cd4f8f --- /dev/null +++ b/config/routes.rb @@ -0,0 +1,34 @@ +Rails.application.routes.draw do + # For details on the DSL available within this file, see http://guides.rubyonrails.org/routing.html + # RESTful routes: + root 'homepages#index' + + resources :users, only: [:index, :show] + get '/users/:id/dashboard', to: "users#dashboard", as: "dashboard" + + resources :categories, only: [:index, :new, :create] + + resources :products, except: [:delete] do + resources :order_items, only: [:create] + resources :reviews, only: [:create, :index] + end + + resources :orders, except: [:delete] + resources :reviews, only: [:create] + resources :order_items, only: [:create, :show, :destroy, :update] + + #retiring a product on merchant view + patch 'product/:id/retire', to: 'products#toggle_retire', as: 'retired' + + get "/orders/:id/checkout", to: "orders#checkout_show", as: "checkout_show" + + # oath login and logout paths + get "/auth/github", as: "github_login" + get "/auth/:provider/callback", to: "users#create", as: "callback" + delete "/logout", to: "users#destroy", as: "logout" + + post '/order_items/:id/', to: 'order_items#complete', as: "mark_complete" + + get '/register', to: 'homepages#register', as: "register_account" + get '/about', to: 'homepages#about', as: "about" +end diff --git a/config/spring.rb b/config/spring.rb new file mode 100644 index 0000000000..9fa7863f99 --- /dev/null +++ b/config/spring.rb @@ -0,0 +1,6 @@ +%w[ + .ruby-version + .rbenv-vars + tmp/restart.txt + tmp/caching-dev.txt +].each { |path| Spring.watch(path) } diff --git a/config/storage.yml b/config/storage.yml new file mode 100644 index 0000000000..d32f76e8fb --- /dev/null +++ b/config/storage.yml @@ -0,0 +1,34 @@ +test: + service: Disk + root: <%= Rails.root.join("tmp/storage") %> + +local: + service: Disk + root: <%= Rails.root.join("storage") %> + +# Use rails credentials:edit to set the AWS secrets (as aws:access_key_id|secret_access_key) +# amazon: +# service: S3 +# access_key_id: <%= Rails.application.credentials.dig(:aws, :access_key_id) %> +# secret_access_key: <%= Rails.application.credentials.dig(:aws, :secret_access_key) %> +# region: us-east-1 +# bucket: your_own_bucket + +# Remember not to checkin your GCS keyfile to a repository +# google: +# service: GCS +# project: your_project +# credentials: <%= Rails.root.join("path/to/gcs.keyfile") %> +# bucket: your_own_bucket + +# Use rails credentials:edit to set the Azure Storage secret (as azure_storage:storage_access_key) +# microsoft: +# service: AzureStorage +# storage_account_name: your_account_name +# storage_access_key: <%= Rails.application.credentials.dig(:azure_storage, :storage_access_key) %> +# container: your_container_name + +# mirror: +# service: Mirror +# primary: local +# mirrors: [ amazon, google, microsoft ] diff --git a/db/category_seeds.csv b/db/category_seeds.csv new file mode 100644 index 0000000000..cfda43acd5 --- /dev/null +++ b/db/category_seeds.csv @@ -0,0 +1,6 @@ +name +Flowers +Succulents +Annuals +Indoor +Shade diff --git a/db/generate_starter_data.rb b/db/generate_starter_data.rb new file mode 100644 index 0000000000..1816a88518 --- /dev/null +++ b/db/generate_starter_data.rb @@ -0,0 +1,68 @@ +require "faker" +require "date" +require "csv" + +CSV.open("db/product_seeds.csv", "w", :write_headers => true, +:headers => ["name", "description", "price", "photo_url", "stock", "available", "user_id"]) do |csv| + 25.times do + name = Faker::Name.unique.name + description = Faker::Lorem.sentence + price = Faker::Commerce.price + photo_url = Faker::LoremPixel.image + stock = rand(1...50) + available = Faker::Boolean.boolean + user_id = rand(1..25) + + csv << [name, description, price, photo_url, stock, available, user_id] + end +end + + +CSV.open("db/user_seeds.csv", "w", :write_headers => true, +:headers => ["username", "email"]) do |csv| + 25.times do + username = Faker::Name.unique.name + email = Faker::Internet.email + + csv << [username, email] + end +end + + +CSV.open("db/order_seeds.csv", "w", :write_headers => true, +:headers => ["email", "address", "name", "cc_num", "cvv_code","zip"]) do |csv| + 25.times do + email = Faker::Internet.email + address = Faker::Address.street_address + name = Faker::Name.unique.name + cc_num = Faker::Business.credit_card_number + cvv_code = rand(100..999) + zip = Faker::Address.zip + + csv << [email, address, name, cc_num, cvv_code,zip] + end +end + + +CSV.open("db/review_seeds.csv", "w", :write_headers => true, +:headers => ["rating", "comment", "product_id"]) do |csv| + 25.times do + rating = rand(1..5) + comment = Faker::Lorem.sentence + product_id = rand(1..25) + + csv << [rating, comment, product_id] + end +end + + +CSV.open("db/order_item_seeds.csv", "w", :write_headers => true, +:headers => ["quantity", "product_id", "order_id"]) do |csv| + 25.times do + quantity = nil + product_id = rand(1..25) + order_id = rand(1..25) + + csv << [quantity, product_id, order_id] + end +end diff --git a/db/migrate/20191022225443_create_orders.rb b/db/migrate/20191022225443_create_orders.rb new file mode 100644 index 0000000000..195952f354 --- /dev/null +++ b/db/migrate/20191022225443_create_orders.rb @@ -0,0 +1,14 @@ +class CreateOrders < ActiveRecord::Migration[5.2] + def change + create_table :orders do |t| + t.string :email + t.string :address + t.string :name + t.string :cc_num + t.string :cvv_code + t.string :zip + + t.timestamps + end + end +end diff --git a/db/migrate/20191022225654_create_order_items.rb b/db/migrate/20191022225654_create_order_items.rb new file mode 100644 index 0000000000..cd9db5ef0d --- /dev/null +++ b/db/migrate/20191022225654_create_order_items.rb @@ -0,0 +1,9 @@ +class CreateOrderItems < ActiveRecord::Migration[5.2] + def change + create_table :order_items do |t| + t.integer :quantity + + t.timestamps + end + end +end diff --git a/db/migrate/20191022225754_create_products.rb b/db/migrate/20191022225754_create_products.rb new file mode 100644 index 0000000000..242b27bbe5 --- /dev/null +++ b/db/migrate/20191022225754_create_products.rb @@ -0,0 +1,13 @@ +class CreateProducts < ActiveRecord::Migration[5.2] + def change + create_table :products do |t| + t.string :description + t.float :price + t.string :photo_url + t.integer :stock + t.boolean :available, default: true + + t.timestamps + end + end +end diff --git a/db/migrate/20191022230107_create_users.rb b/db/migrate/20191022230107_create_users.rb new file mode 100644 index 0000000000..05c50ed1b4 --- /dev/null +++ b/db/migrate/20191022230107_create_users.rb @@ -0,0 +1,10 @@ +class CreateUsers < ActiveRecord::Migration[5.2] + def change + create_table :users do |t| + t.string :username + t.string :email + + t.timestamps + end + end +end diff --git a/db/migrate/20191022230147_create_reviews.rb b/db/migrate/20191022230147_create_reviews.rb new file mode 100644 index 0000000000..8248e3c6b3 --- /dev/null +++ b/db/migrate/20191022230147_create_reviews.rb @@ -0,0 +1,10 @@ +class CreateReviews < ActiveRecord::Migration[5.2] + def change + create_table :reviews do |t| + t.integer :rating + t.string :comment + + t.timestamps + end + end +end diff --git a/db/migrate/20191022230229_create_categories.rb b/db/migrate/20191022230229_create_categories.rb new file mode 100644 index 0000000000..6ccc3914a0 --- /dev/null +++ b/db/migrate/20191022230229_create_categories.rb @@ -0,0 +1,9 @@ +class CreateCategories < ActiveRecord::Migration[5.2] + def change + create_table :categories do |t| + t.string :name + + t.timestamps + end + end +end diff --git a/db/migrate/20191022231941_add_product_id_and_order_id_to_order_item.rb b/db/migrate/20191022231941_add_product_id_and_order_id_to_order_item.rb new file mode 100644 index 0000000000..427062b76e --- /dev/null +++ b/db/migrate/20191022231941_add_product_id_and_order_id_to_order_item.rb @@ -0,0 +1,6 @@ +class AddProductIdAndOrderIdToOrderItem < ActiveRecord::Migration[5.2] + def change + add_reference :order_items, :product, foreign_key: true + add_reference :order_items, :order, foreign_key: true + end +end diff --git a/db/migrate/20191022232212_add_user_id_to_product.rb b/db/migrate/20191022232212_add_user_id_to_product.rb new file mode 100644 index 0000000000..60725352ac --- /dev/null +++ b/db/migrate/20191022232212_add_user_id_to_product.rb @@ -0,0 +1,5 @@ +class AddUserIdToProduct < ActiveRecord::Migration[5.2] + def change + add_reference :products, :user, foreign_key: true + end +end diff --git a/db/migrate/20191022232347_create_category_product_join.rb b/db/migrate/20191022232347_create_category_product_join.rb new file mode 100644 index 0000000000..1a22fcb26b --- /dev/null +++ b/db/migrate/20191022232347_create_category_product_join.rb @@ -0,0 +1,8 @@ +class CreateCategoryProductJoin < ActiveRecord::Migration[5.2] + def change + create_table :categories_products do |t| + t.belongs_to :category, index: true + t.belongs_to :product, index: true + end + end +end diff --git a/db/migrate/20191022232526_add_product_id_to_review.rb b/db/migrate/20191022232526_add_product_id_to_review.rb new file mode 100644 index 0000000000..0cd70141a4 --- /dev/null +++ b/db/migrate/20191022232526_add_product_id_to_review.rb @@ -0,0 +1,5 @@ +class AddProductIdToReview < ActiveRecord::Migration[5.2] + def change + add_reference :reviews, :product, foreign_key: true + end +end diff --git a/db/migrate/20191023031436_add_name_to_products.rb b/db/migrate/20191023031436_add_name_to_products.rb new file mode 100644 index 0000000000..c85be39ba6 --- /dev/null +++ b/db/migrate/20191023031436_add_name_to_products.rb @@ -0,0 +1,5 @@ +class AddNameToProducts < ActiveRecord::Migration[5.2] + def change + add_column :products, :name, :string + end +end diff --git a/db/migrate/20191023212442_add_uid_and_provider_to_users.rb b/db/migrate/20191023212442_add_uid_and_provider_to_users.rb new file mode 100644 index 0000000000..31203ff40a --- /dev/null +++ b/db/migrate/20191023212442_add_uid_and_provider_to_users.rb @@ -0,0 +1,6 @@ +class AddUidAndProviderToUsers < ActiveRecord::Migration[5.2] + def change + add_column :users, :uid, :integer + add_column :users, :provider, :string + end +end diff --git a/db/migrate/20191024213520_add_status_to_orders.rb b/db/migrate/20191024213520_add_status_to_orders.rb new file mode 100644 index 0000000000..07d963cb46 --- /dev/null +++ b/db/migrate/20191024213520_add_status_to_orders.rb @@ -0,0 +1,5 @@ +class AddStatusToOrders < ActiveRecord::Migration[5.2] + def change + add_column :orders, :status, :string, :default => "pending" + end +end diff --git a/db/migrate/20191028210014_add_exp_date_to_orders.rb b/db/migrate/20191028210014_add_exp_date_to_orders.rb new file mode 100644 index 0000000000..986b02263a --- /dev/null +++ b/db/migrate/20191028210014_add_exp_date_to_orders.rb @@ -0,0 +1,5 @@ +class AddExpDateToOrders < ActiveRecord::Migration[5.2] + def change + add_column :orders, :exp_date, :string + end +end diff --git a/db/migrate/20191028213924_add_status_to_order_items.rb b/db/migrate/20191028213924_add_status_to_order_items.rb new file mode 100644 index 0000000000..abf537d1d8 --- /dev/null +++ b/db/migrate/20191028213924_add_status_to_order_items.rb @@ -0,0 +1,5 @@ +class AddStatusToOrderItems < ActiveRecord::Migration[5.2] + def change + add_column :order_items, :status, :string, :default => "pending" + end +end diff --git a/db/order_item_seeds.csv b/db/order_item_seeds.csv new file mode 100644 index 0000000000..04da691332 --- /dev/null +++ b/db/order_item_seeds.csv @@ -0,0 +1,26 @@ +quantity,product_id,order_id +2,7,12 +3,5,14 +1,9,14 +3,8,8 +2,3,10 +2,4,9 +3,10,11 +4,1,9 +3,4,18 +2,10,17 +2,9,22 +2,8,2 +2,3,12 +3,10,8 +1,9,8 +2,10,9 +3,9,2 +3,6,10 +2,3,13 +1,4,4 +2,5,3 +3,9,4 +2,2,8 +3,5,22 +2,1,6 diff --git a/db/order_seeds.csv b/db/order_seeds.csv new file mode 100644 index 0000000000..119b2d1db9 --- /dev/null +++ b/db/order_seeds.csv @@ -0,0 +1,26 @@ +email,address,name,cc_num,cvv_code,zip,exp_date +simonne@sanford.info,186 Cristie Forest,Mabel Goodwin,1234-2121-1221-1211,218,38721-4438,10/20 +jenni@bahringer.biz,8934 Troy Forks,Mabelle Dickinson,1234-2121-1221-1211,819,67248-8640,10/20 +glenn@schneider.com,765 Bahringer Roads,Mr. Loyd Boyle,1228-1221-1221-1431,871,84146-7881,10/20 +holley.rath@bartolettitromp.io,210 Gema Land,Micki Mosciski,1228-1221-1221-1431,597,75907,10/20 +heather@hauck.com,6570 Armanda Route,Karolyn Emard,1212-1221-1121-1234,192,68892,10/20 +esta@macejkovic.co,13638 Roni Overpass,Hunter Mraz,1234-2121-1221-1211,778,23969,10/20 +jina@turcotte.co,226 Brock Trail,Hugo Lang,1212-1221-1121-1234,703,44322-3703,10/20 +columbus.leffler@mueller.io,6964 Sanford Junctions,Mrs. Emil Halvorson,1212-1221-1121-1234,731,10684-4347,10/20 +lavon@criststiedemann.biz,663 Gleason Island,Dr. Kendra Schroeder,1212-1221-1121-1234,395,95006,10/20 +cyril@runolfon.com,93180 Bogan Center,Mr. Derek Kihn,1211-1221-1234-2201,398,15749-6384,10/20 +dimple@parkerwill.name,310 Green Drive,Dr. Ramona Sawayn,1234-2121-1221-1211,195,76676-2250,10/20 +magan.bashirian@lehner.io,77870 Daugherty Dale,Mrs. Damaris Goodwin,1211-1221-1234-2201,432,90044,10/20 +basil.romaguera@lemke.info,78407 Cummerata Plaza,Sammie Feil,1234-2121-1221-1211,842,95323,10/20 +kimberli@heller.net,459 Jewel Mission,Numbers Satterfield,1228-1221-1221-1431,650,65749-4439,10/20 +maryln.pfeffer@stamm.com,341 Gibson Roads,Johnna Emard,1212-1221-1121-1234,657,35477-4588,10/20 +trey@ziemann.net,1615 Suzy Junction,Mr. Jonah Kihn,1228-1221-1221-1431,753,61876-2463,10/20 +lynnette_mills@gibsonzemlak.info,377 Annita Fort,Ms. Amos Ruecker,1234-2121-1221-1211,788,33983,10/20 +daryl@frami.name,34325 Runolfsdottir Valley,Christoper O'Connell,1212-1221-1121-1234,872,47843-6088,10/20 +caroll_heathcote@grahamrohan.org,80713 Johnston Groves,Whitley Lemke,1228-1221-1221-1431,663,25424-2615,10/20 +wally@nikolaus.io,398 Clemente Falls,Frederic Altenwerth,1211-1221-1234-2201,125,00400-3462,10/20 +herb_bradtke@rathbayer.com,2694 Bode Circle,Oliva Larkin III,1234-2121-1221-1211,589,67873-2195,10/20 +lisha_bode@effertz.co,54445 Joshua Estate,Mr. Arron Schroeder,1211-1221-1234-2201,179,48798-8718,10/20 +thomasine.labadie@johnson.co,91838 Marks Club,Mrs. Antwan Considine,1228-1221-1221-1431,133,12809-8866,10/20 +clair@bernier.name,94974 Benedict Greens,Cory Hilpert,1228-1221-1221-1431,901,23083,10/20 +bud@mcclurehegmann.info,9212 Patrick Plaza,Ms. Cedric Kilback,1211-1221-1234-2201,524,29614-8411,10/20 diff --git a/db/product_seeds.csv b/db/product_seeds.csv new file mode 100644 index 0000000000..d6d409b9c0 --- /dev/null +++ b/db/product_seeds.csv @@ -0,0 +1,13 @@ +name,description,price,photo_url,stock,available,user_id +Roseum,Fun and delicate with spiky upright leaves.,33.31,https://lh3.googleusercontent.com/zRJkmU9KfCjQQuCr1bBY-qOT11FLEdnuGaK9hWPVOheCQKrOe0UV85lLHNRDUgpiWyo0CtW8JTGasmJ6-tPxFfth5pfd9T1IvVhsR4XYSnCmmCyuiBQDM49EZR0U4qCcmIiwBhGeVw=w2400,119,true,1 +Sempervivum tectorum,Unique with textured leaves.,18.48,https://lh3.googleusercontent.com/Cop0jWwuZArwddNDi7MRhEqVfbtqBnX1bdy9gXkNi4Iur9Unu8CT2v4_AeEWiw43SRyKc6swKm62PH9MF2fG3qz40zNotcR9Bhgkpxoce03zvRzSq3O392Vd0HTxPa8uXX4RBjOeRA=w2400,118,true,8 +Echeveria pulvinata,Impressive and tropical with glossy leaves.,42.49,https://lh3.googleusercontent.com/mQo-KSH87OJOlSysFERiX1R-Z_-FL0qaZzqMkBRJiW1W5oiktaA7CvRVkcsAXR3z3zKBCVKDpdr35wExLRazV8LlbBbxincX49505cbnvhx6D_EMl20S25jd_GSgorzc4swhAfRHMw=w2400,121,true,7 +Cotyledon orbiculata,Colorful and exotic.,19.20,https://lh3.googleusercontent.com/52cfkxN0IGP625BRBvIOwu5aioAfCmpH4dYNM3svJsnXAtkSVi-oXX4leBhS5bppntR837IsTYIEL1anRANUg5slexO2ZxFrV7aQID5WkS-YyGUfFisDjjB6P7p5X1SiEu8LgCcmSw=w2400,116,true,9 +Aeonium arboreum,A unique plant with exotic leaves.,22.34,https://lh3.googleusercontent.com/6FZLp3TJP1B6uoCXrFJ1qRGo815FcOFYA4quxV0hD43U9JIK1il0BXw5Uzh4T5FT6idVZJUfxecmistGZK_J7Gt81ZetgCegDNw9KeUrGOZW5YQx6jkIO5chVPaNn2OrLoA3tTq-IA=w2400,112,true,5 +Echeveria spp,Fun and whimsical with long curved leaves.,15.99,https://lh3.googleusercontent.com/p_VNXLedv3zOBb9YzskwKRJ2JnDjFBF6uFI52eqHPqeRyNaG_5wZtfYqUgkxK-0jHYDcSLntQHFux4OBzYa9ls_D9EeQ9bmsm_Xm0S5OLVxHdBVzI6GQqZPYg4qPstIpXOxCyGnB6w=w2400,118,true,4 +Aeonium davidbramwellii,Glossy colorful with silvery-green streaks.,29.45,https://lh3.googleusercontent.com/yk3A-Ihugp9SyYcYZCyUFiaYdaJ5tVYPdSKxg0J7jMgWaaS9YAmDjMTkFaEozHoAoQ-uR6G9f_gKiMpQ0YSqKjE9LmMP9xKObHUp2Il1aLPZLHibhOxDjDK3gOLPvi_v-I7B6eeMhw=w2400,112,true,3 +Parodia magnifica,Robust and dramatic with glossy leaves.,17.90,https://lh3.googleusercontent.com/rgf3dpdqj9mB37SE_k0xOISLINv0zMgO3ksXB8ySN_q09cYTmgstvzzvHumnFGSQTbK1Ozcf1039io_zl0PVYO0zPOjaMOO-IZ0Zb4wLG-vWMWupLUsk3P66sCDRG-PN-HZwFVBM-g=w2400,110,true,2 +Haworthia fasciata,Easy and graceful.,14.19,https://lh3.googleusercontent.com/KJQzhkpQjo7Z_-H3tSfSDJwEMq4eFx1TaVcaq6C-ebfHvreoOaLig21n2rn5K2i_Jj3X0IERb3C7b-G9m9ChcUSaiAznL3D9Ct0QiWlZgN5QziZi3wVN_vJPydZ6MSiqxyqJhcK15w=w2400,115,true,5 +Sansevieria trifasciata,Graceful combo with small leaves.,34.55,https://lh3.googleusercontent.com/9uyXRAcu6FTDI6dgZtXETZ6l_l5yhXAwKJrCkO6InV-U_F0x8V2fTpXSGj2pinEFfGy42Rv1StmK5GXcz74a1qX4xQqONeIPLaYw8tIqXTzA6R2gjziKMRwUg49G5xAugE_mGLrWdw=w2400,112,true,9 +Sedum morganianum,Unique plant with dark leaves.,22.98,https://lh3.googleusercontent.com/rNbN04QpSPqsMi3ld3NBZE_lE-USO1QY-gKAW9dsRCh2ui_1jLhVznGqQejEUAIERpOAJ5EKhIaPlDxc7AkiDELcJm4YBkMyZ0NcNX2hy86s0Oh5ZGDUxmnFA_8wMZoIGtW5fdx3yA=w2400,101,true,6 +Euphorbia milii,Impressive and exotic.,21.45,https://lh3.googleusercontent.com/p8Cdjk_JlPgVplP0rKgYuvSU-E3iHBb2Ze4FOkuzu5JbNl88SKjvFZNBjEJ0E1CcdJ_nfdYpi7wLlQkytHbDjKg4-j9aY32-nIhULvnSaVq4HxCyZt6REKQlCa3FFR1GpGfIvVKoIg=w2400,105,true,2 diff --git a/db/review_seeds.csv b/db/review_seeds.csv new file mode 100644 index 0000000000..94c1e5f181 --- /dev/null +++ b/db/review_seeds.csv @@ -0,0 +1,26 @@ +rating,comment,product_id +1,Plant came with darks leaves.,1 +2,Plant delivered without pot.,2 +1,I didn't receive the right plant.,3 +5,Love my new plant!,4 +5,Perfect for my house.,5 +5,Awesome plant!,6 +4,I want to buy another one.,7 +3,Nice plant just a little droopy.,8 +4,Amazing!,9 +5,Best plant ever!!!,10 +4,Nice plant.,1 +1,Shipment was late.,2 +4,Amazing plant!,3 +5,I love my new plant!,4 +2,Got the wrong plant!,5 +1,Got the wrong plant!,6 +5,Love my new plant!,7 +1,Returned,3 +4,Beautiful.,5 +3,Nice plant.,8 +3,Nice plant.,4 +5,Great plant!,3 +4,Very nice.,9 +4,I love my new plant!,10 +2,Don't recommend.,7 diff --git a/db/schema.rb b/db/schema.rb new file mode 100644 index 0000000000..c9fe7bad90 --- /dev/null +++ b/db/schema.rb @@ -0,0 +1,90 @@ +# This file is auto-generated from the current state of the database. Instead +# of editing this file, please use the migrations feature of Active Record to +# incrementally modify your database, and then regenerate this schema definition. +# +# Note that this schema.rb definition is the authoritative source for your +# database schema. If you need to create the application database on another +# system, you should be using db:schema:load, not running all the migrations +# from scratch. The latter is a flawed and unsustainable approach (the more migrations +# you'll amass, the slower it'll run and the greater likelihood for issues). +# +# It's strongly recommended that you check this file into your version control system. + +ActiveRecord::Schema.define(version: 2019_10_28_213924) do + + # These are extensions that must be enabled in order to support this database + enable_extension "plpgsql" + + create_table "categories", force: :cascade do |t| + t.string "name" + t.datetime "created_at", null: false + t.datetime "updated_at", null: false + end + + create_table "categories_products", force: :cascade do |t| + t.bigint "category_id" + t.bigint "product_id" + t.index ["category_id"], name: "index_categories_products_on_category_id" + t.index ["product_id"], name: "index_categories_products_on_product_id" + end + + create_table "order_items", force: :cascade do |t| + t.integer "quantity" + t.datetime "created_at", null: false + t.datetime "updated_at", null: false + t.bigint "product_id" + t.bigint "order_id" + t.string "status", default: "pending" + t.index ["order_id"], name: "index_order_items_on_order_id" + t.index ["product_id"], name: "index_order_items_on_product_id" + end + + create_table "orders", force: :cascade do |t| + t.string "email" + t.string "address" + t.string "name" + t.string "cc_num" + t.string "cvv_code" + t.string "zip" + t.datetime "created_at", null: false + t.datetime "updated_at", null: false + t.string "status", default: "pending" + t.string "exp_date" + end + + create_table "products", force: :cascade do |t| + t.string "description" + t.float "price" + t.string "photo_url" + t.integer "stock" + t.boolean "available", default: true + t.datetime "created_at", null: false + t.datetime "updated_at", null: false + t.bigint "user_id" + t.string "name" + t.index ["user_id"], name: "index_products_on_user_id" + end + + create_table "reviews", force: :cascade do |t| + t.integer "rating" + t.string "comment" + t.datetime "created_at", null: false + t.datetime "updated_at", null: false + t.bigint "product_id" + t.index ["product_id"], name: "index_reviews_on_product_id" + end + + create_table "users", force: :cascade do |t| + t.string "username" + t.string "email" + t.datetime "created_at", null: false + t.datetime "updated_at", null: false + t.integer "uid" + t.string "provider" + end + + add_foreign_key "order_items", "orders" + add_foreign_key "order_items", "products" + add_foreign_key "products", "users" + add_foreign_key "reviews", "products" +end diff --git a/db/seeds.rb b/db/seeds.rb new file mode 100644 index 0000000000..d01a59d4fa --- /dev/null +++ b/db/seeds.rb @@ -0,0 +1,176 @@ +# This file should contain all the record creation needed to seed the database with its default values. +# The data can then be loaded with the rails db:seed command (or created alongside the database with db:setup). +# +# Examples: +# +# movies = Movie.create([{ name: 'Star Wars' }, { name: 'Lord of the Rings' }]) +# Character.create(name: 'Luke', movie: movies.first) +require 'csv' + +ORDERS_FILE = Rails.root.join('db', 'order_seeds.csv') +puts "Loading raw orders data from #{ORDERS_FILE}" + +orders_failures = [] +CSV.foreach(ORDERS_FILE, :headers => true) do |row| + order = Order.new + order.email = row['email'] + order.address = row['address'] + order.name = row['name'] + order.cc_num = row['cc_num'] + order.cvv_code = row['cvv_code'] + order.zip = row['zip'] + order.exp_date = row['exp_date'] + + successful = order.save + if !successful + orders_failures << order + puts "Failed to save order: #{order.inspect}" + else + puts "Created order: #{order.inspect}" + end +end + +puts "Added #{Order.count} order records" +puts "#{orders_failures.length} orders failed to save" + +#------------------------------------------------------------ + +USERS_FILE = Rails.root.join('db', 'user_seeds.csv') +puts "Loading raw user data from #{USERS_FILE}" + +users_failures = [] +CSV.foreach(USERS_FILE, :headers => true) do |row| + user = User.new + user.username = row['username'] + user.email = row['email'] + + successful = user.save + if !successful + users_failures << user + puts "Failed to save user: #{user.inspect}" + else + puts "Created user: #{user.inspect}" + end +end + +puts "Added #{User.count} user records" +puts "#{users_failures.length} user failed to save" + +#------------------------------------------------------------ + +PRODUCTS_FILE = Rails.root.join('db', 'product_seeds.csv') +puts "Loading raw product data from #{PRODUCTS_FILE}" + +products_failures = [] +CSV.foreach(PRODUCTS_FILE, :headers => true) do |row| + product = Product.new + product.name = row['name'] + product.description = row['description'] + product.price = row['price'] + product.photo_url = row['photo_url'] + product.stock = row['stock'] + product.available = row['available'] + product.user_id = row['user_id'] + + successful = product.save + if !successful + products_failures << product + puts "Failed to save product: #{product.inspect}" + else + puts "Created product: #{product.inspect}" + end +end + +puts "Added #{Product.count} product records" +puts "#{products_failures.length} products failed to save" + +#------------------------------------------------------------ + +ORDER_ITEM_FILE = Rails.root.join('db', 'order_item_seeds.csv') +puts "Loading raw order_item data from #{ORDER_ITEM_FILE}" + +order_item_failures = [] +CSV.foreach(ORDER_ITEM_FILE, :headers => true) do |row| + order_item = OrderItem.new + order_item.quantity = row['quantity'] + order_item.product_id = row['product_id'] + order_item.order_id = row['order_id'] + successful = order_item.save + if !successful + order_item_failures << order_item + puts "Failed to save order_item: #{order_item.inspect}" + else + puts "Created order_item: #{order_item.inspect}" + end +end + +puts "Added #{OrderItem.count} order_item records" +puts "#{order_item_failures.length} order_items failed to save" + +#------------------------------------------------------------ + +REVIEWS_FILE = Rails.root.join('db', 'review_seeds.csv') +puts "Loading raw review data from #{REVIEWS_FILE}" + +reviews_failures = [] +CSV.foreach(REVIEWS_FILE, :headers => true) do |row| + review = Review.new + review.rating = row['rating'] + review.comment = row['comment'] + review.product_id = row['product_id'] + + successful = review.save + if !successful + reviews_failures << review + puts "Failed to save review: #{review.inspect}" + else + puts "Created review: #{review.inspect}" + end +end + +puts "Added #{Review.count} review records" +puts "#{reviews_failures.length} review failed to save" + +#------------------------------------------------------------ + +CATEGORY_FILE = Rails.root.join('db', 'category_seeds.csv') +puts "Loading raw category data from #{CATEGORY_FILE}" + +category_failures = [] +CSV.foreach(CATEGORY_FILE, :headers => true) do |row| + category = Category.new + category.name = row['name'] + successful = category.save + if !successful + category_failures << category + puts "Failed to save category: #{category.inspect}" + else + puts "Created category: #{category.inspect}" + end +end + +puts "Added #{Category.count} category records" +puts "#{category_failures.length} category failed to save" + +#------------------------------------------------------------ +# Connect products and categories via join table +products = Product.all +categories = Category.all +index = 0 + +products.each do |product| + if index == 5 # This should match the number of categories in the category.yml. If we have five categories, restart the counter. + index = 0 + end + if index % 2 != 0 # if it's an odd number, give it two categories - must have an odd number of categories for this to work properly. + 2.times { + product.categories << categories[index] + index += 1 + } + else + product.categories << categories[index] + index += 1 + end +end + +#------------------------------------------------------------ diff --git a/db/user_seeds.csv b/db/user_seeds.csv new file mode 100644 index 0000000000..1747b43303 --- /dev/null +++ b/db/user_seeds.csv @@ -0,0 +1,10 @@ +username,email +Golda Schuppe,dewitt@schultzweinat.co +Tyesha Hegmann I,collin_oconnell@cremin.io +Tory Schoen,reatha@langworthkeeling.org +Ines Buckridge,maximo@haag.co +Sherill Labadie DVM,terrell@larsonrohan.net +Gene Welch,joleen@abernathylowe.info +Hiram Smitham,thu@hyattullrich.org +Jaunita Ryan,jamar_emmerich@reilly.com +Eleonora Lubowitz,eleonora.lubowitz@gmail.com diff --git a/lib/assets/.keep b/lib/assets/.keep new file mode 100644 index 0000000000..e69de29bb2 diff --git a/lib/tasks/.keep b/lib/tasks/.keep new file mode 100644 index 0000000000..e69de29bb2 diff --git a/log/.keep b/log/.keep new file mode 100644 index 0000000000..e69de29bb2 diff --git a/package.json b/package.json new file mode 100644 index 0000000000..f874acf437 --- /dev/null +++ b/package.json @@ -0,0 +1,5 @@ +{ + "name": "betsy", + "private": true, + "dependencies": {} +} diff --git a/public/404.html b/public/404.html new file mode 100644 index 0000000000..2be3af26fc --- /dev/null +++ b/public/404.html @@ -0,0 +1,67 @@ + + + + The page you were looking for doesn't exist (404) + + + + + + +
+
+

The page you were looking for doesn't exist.

+

You may have mistyped the address or the page may have moved.

+
+

If you are the application owner check the logs for more information.

+
+ + diff --git a/public/422.html b/public/422.html new file mode 100644 index 0000000000..c08eac0d1d --- /dev/null +++ b/public/422.html @@ -0,0 +1,67 @@ + + + + The change you wanted was rejected (422) + + + + + + +
+
+

The change you wanted was rejected.

+

Maybe you tried to change something you didn't have access to.

+
+

If you are the application owner check the logs for more information.

+
+ + diff --git a/public/500.html b/public/500.html new file mode 100644 index 0000000000..78a030af22 --- /dev/null +++ b/public/500.html @@ -0,0 +1,66 @@ + + + + We're sorry, but something went wrong (500) + + + + + + +
+
+

We're sorry, but something went wrong.

+
+

If you are the application owner check the logs for more information.

+
+ + diff --git a/public/apple-touch-icon-precomposed.png b/public/apple-touch-icon-precomposed.png new file mode 100644 index 0000000000..e69de29bb2 diff --git a/public/apple-touch-icon.png b/public/apple-touch-icon.png new file mode 100644 index 0000000000..e69de29bb2 diff --git a/public/favicon.ico b/public/favicon.ico new file mode 100644 index 0000000000..e69de29bb2 diff --git a/public/robots.txt b/public/robots.txt new file mode 100644 index 0000000000..37b576a4a0 --- /dev/null +++ b/public/robots.txt @@ -0,0 +1 @@ +# See http://www.robotstxt.org/robotstxt.html for documentation on how to use the robots.txt file diff --git a/storage/.keep b/storage/.keep new file mode 100644 index 0000000000..e69de29bb2 diff --git a/test/application_system_test_case.rb b/test/application_system_test_case.rb new file mode 100644 index 0000000000..d19212abd5 --- /dev/null +++ b/test/application_system_test_case.rb @@ -0,0 +1,5 @@ +require "test_helper" + +class ApplicationSystemTestCase < ActionDispatch::SystemTestCase + driven_by :selenium, using: :chrome, screen_size: [1400, 1400] +end diff --git a/test/controllers/.keep b/test/controllers/.keep new file mode 100644 index 0000000000..e69de29bb2 diff --git a/test/controllers/categories_controller_test.rb b/test/controllers/categories_controller_test.rb new file mode 100644 index 0000000000..0c3edf1002 --- /dev/null +++ b/test/controllers/categories_controller_test.rb @@ -0,0 +1,63 @@ +require "test_helper" + +describe CategoriesController do + describe 'guest users' do + describe "index" do + it "gives back a susccesful response" do + get categories_path + must_respond_with :success + end + + it "can get the root path" do + get root_path + must_respond_with :success + end + end + end + + describe "Logged in users" do + before do + user = users(:orchid) + perform_login(user) + end + + describe "index" do + it "gives back a susccesful response" do + get categories_path + must_respond_with :success + end + + it "can get the root path" do + get root_path + must_respond_with :success + end + end + + describe "create" do + it "lets a logged in user create a category" do + params_hash = { + category: { + name: "flower" + } + } + + expect { + post '/categories', params: params_hash + }.must_differ "Category.count", 1 + end + + it "can't create a category with wrong params" do + params_hash = { + category: { + name: nil + } + } + + post '/categories', params: params_hash + # must_redirect_to dashboard_path(user.id) + expect(flash[:warning]).must_equal "Can't create category." + end + end + end +end + diff --git a/test/controllers/homepages_controller_test.rb b/test/controllers/homepages_controller_test.rb new file mode 100644 index 0000000000..97121250e2 --- /dev/null +++ b/test/controllers/homepages_controller_test.rb @@ -0,0 +1,32 @@ +require "test_helper" + +describe HomepagesController do + it "can get the root path" do + get root_path + + must_respond_with :success + end + + it "can get the about_us path" do + get about_path + + must_respond_with :success + end + + describe "register as merchant" do + it "can get the register-as-merchant page" do + get register_account_path + + must_respond_with :success + end + + it "can't be accessed if you're logged in" do + perform_login() + + get register_account_path + + must_redirect_to root_path + expect(flash[:error]).must_equal "You've already signed up!" + end + end +end diff --git a/test/controllers/order_items_controller_test.rb b/test/controllers/order_items_controller_test.rb new file mode 100644 index 0000000000..d62f444148 --- /dev/null +++ b/test/controllers/order_items_controller_test.rb @@ -0,0 +1,308 @@ +require "test_helper" + +describe OrderItemsController do + describe 'guest users' do + describe "create" do + before do + @user = User.create(username: "georgina", email: "geor@gmail.com") + @product_cactus = Product.create(user_id: @user.id, name: "cactus", description: "cool product", price: 1.9, photo_url: "url", stock: 3) + @product_flower = Product.create(user_id: @user.id, name: "flower", description: "cool flower", price: 1.5, photo_url: "url", stock: 3) + @order = Order.create(address: "x", name: "x", cc_num: "x", cvv_code: "x", zip: "x", email: "blank@blank.com", exp_date: "10/20") + @order_item_hash = { + order_item: { + product_id: @product_cactus.id, + quantity: 3, + order_id: @order.id, + } + } + end + + it 'creates a new order_item successfully with valid data while not logged in, and redirects the user to the products page' do + expect { + post order_items_path, params: @order_item_hash[:order_item] + }.must_differ 'OrderItem.count', 1 + + must_redirect_to product_path(@product_cactus.id) + expect(flash[:success]).must_equal "Successfully added item to your cart." + end + + it 'does not create a new order_item given invalid data while not logged in, and redirects the user to the products page' do + invalid_item_hash = { + order_item: { + product_id: @product_cactus.id, + order_id: @order.id, + } + } + expect { + post order_items_path, params: invalid_item_hash[:order_item] + }.must_differ 'OrderItem.count', 0 + + must_redirect_to product_path(@product_cactus.id) + expect(flash[:failure]).must_equal "Item could not be added to your cart." + end + + it "increments the order_item quantity of an existing product" do + @product_cactus.stock = 6 + @product_cactus.save + + # add 3 product_cactus to cart + post order_items_path, params: @order_item_hash[:order_item] + + new_order_item = OrderItem.find_by(product_id: @product_cactus.id) + expect(new_order_item.quantity).must_equal 3 + + # attempt to add 3 more product_cactus to cart + expect { + post order_items_path, params: @order_item_hash[:order_item] + }.wont_differ 'OrderItem.count' + + updated_order_item = OrderItem.find_by(product_id: @product_cactus.id) + expect(updated_order_item.quantity).must_equal 6 + + must_redirect_to product_path(@product_cactus.id) + expect(flash[:success]).must_equal "Successfully updated quantity." + end + + it "gives an error if the order_item quantity is greater than the stock" do + # add 3 product_cactus to cart + post order_items_path, params: @order_item_hash[:order_item] + + new_order_item = OrderItem.find_by(product_id: @product_cactus.id) + expect(new_order_item.quantity).must_equal 3 + + # attempt to add 3 more product_cactus to cart, + # but there aren't three more product_cactus in stock + expect { + post order_items_path, params: @order_item_hash[:order_item] + }.wont_differ 'OrderItem.count' + + updated_order_item = OrderItem.find_by(product_id: @product_cactus.id) + expect(updated_order_item.quantity).must_equal 3 + + must_redirect_to product_path(@product_cactus.id) + expect(flash[:failure]).must_equal "Sorry, there are not enough items in stock." + end + end + + describe 'delete' do + before do + @user = User.create(username: "georgina", email: "geor@gmail.com") + @product_cactus = Product.create(user_id: @user.id, name: "cactus", description: "cool product", price: 1.9, photo_url: "url", stock: 3) + @product_flower = Product.create(user_id: @user.id, name: "flower", description: "cool flower", price: 1.5, photo_url: "url", stock: 3) + @order = Order.create(address: "x", name: "x", cc_num: "x", cvv_code: "x", zip: "x", email: "blank@blank.com", exp_date: "10/20") + end + + it 'can delete an order_item successfully while not logged in' do + new_order_item = OrderItem.create(product_id: @product_cactus.id, quantity: 3, order_id: @order.id,) + expect { + delete order_item_path(new_order_item.id) + }.must_change 'OrderItem.count', 1 + end + end + + describe 'update' do + before do + @user = User.create(username: "georgina", email: "geor@gmail.com") + @product_cactus = Product.create(user_id: @user.id, name: "cactus", description: "cool product", price: 1.9, photo_url: "url", stock: 3) + @product_flower = Product.create(user_id: @user.id, name: "flower", description: "cool flower", price: 1.5, photo_url: "url", stock: 3) + @order = Order.create(address: "x", name: "x", cc_num: "x", cvv_code: "x", zip: "x", email: "blank@blank.com", exp_date: "10/20") + @new_order_item = OrderItem.create(product_id: @product_cactus.id, quantity: 3, order_id: @order.id,) + @updated_order_item_hash = { + order_item: { + product_id: @product_cactus.id, + quantity: 5, + order_id: @order.id, + } + } + end + + it 'cannot add more items to cart than are available in stock' do + @updated_order_item_hash[:order_item][:quantity] = 500 + + expect{ + patch "/order_items/#{@new_order_item.id}", params: @updated_order_item_hash + }.wont_differ "@order.order_items.count" + + expect(@order.errors).wont_be_nil + + end + + it "can update an existing order_item while not logged in" do + patch "/order_items/#{@new_order_item.id}", params: @updated_order_item_hash + + expect(OrderItem.find_by(id: @new_order_item.id).quantity).must_equal 5 + end + end + + describe "complete" do + it "does not effect the status" do + oi = order_items(:bear_treeivy) + oi_status = oi.status + + expect { + post mark_complete_path(oi.id) + }.wont_differ "OrderItem.count" + + expect(OrderItem.find_by(id: oi.id).status).must_equal oi_status + end + end + end + + describe "Logged in users" do + before do + perform_login(users(:begonia)) + end + + describe "create" do + before do + @user = User.create(username: "georgina", email: "geor@gmail.com") + @product_cactus = Product.create(user_id: @user.id, name: "cactus", description: "cool product", price: 1.9, photo_url: "url", stock: 3) + @product_flower = Product.create(user_id: @user.id, name: "flower", description: "cool flower", price: 1.5, photo_url: "url", stock: 3) + @order = Order.create(address: "x", name: "x", cc_num: "x", cvv_code: "x", zip: "x", email: "blank@blank.com", exp_date: "10/20") + @order_item_hash = { + order_item: { + product_id: @product_cactus.id, + quantity: 3, + order_id: @order.id, + } + } + end + + it 'creates a new order_item successfully with valid data while logged in, and redirects the user to the product page' do + + expect { + post order_items_path, params: @order_item_hash[:order_item] + }.must_differ 'OrderItem.count', 1 + must_redirect_to product_path(@product_cactus.id) + expect(flash[:success]).must_equal "Successfully added item to your cart." + end + + it 'does not create a new order_item given invalid data while logged in, and redirects the user to the products page' do + invalid_item_hash = { + order_item: { + product_id: @product_cactus.id, + order_id: @order.id, + } + } + expect { + post order_items_path, params: invalid_item_hash[:order_item] + }.must_differ 'OrderItem.count', 0 + + must_redirect_to product_path(@product_cactus.id) + expect(flash[:failure]).must_equal "Item could not be added to your cart." + end + + it "increments the order_item quantity of an existing product" do + @product_cactus.stock = 6 + @product_cactus.save + + # add 3 product_cactus to cart + post order_items_path, params: @order_item_hash[:order_item] + + new_order_item = OrderItem.find_by(product_id: @product_cactus.id) + expect(new_order_item.quantity).must_equal 3 + + # attempt to add 3 more product_cactus to cart + expect { + post order_items_path, params: @order_item_hash[:order_item] + }.wont_differ 'OrderItem.count' + + updated_order_item = OrderItem.find_by(product_id: @product_cactus.id) + expect(updated_order_item.quantity).must_equal 6 + + must_redirect_to product_path(@product_cactus.id) + expect(flash[:success]).must_equal "Successfully updated quantity." + end + + it "gives an error if the order_item quantity is greater than the stock" do + # add 3 product_cactus to cart + post order_items_path, params: @order_item_hash[:order_item] + + new_order_item = OrderItem.find_by(product_id: @product_cactus.id) + expect(new_order_item.quantity).must_equal 3 + + # attempt to add 3 more product_cactus to cart, + # but there aren't three more product_cactus in stock + expect { + post order_items_path, params: @order_item_hash[:order_item] + }.wont_differ 'OrderItem.count' + + updated_order_item = OrderItem.find_by(product_id: @product_cactus.id) + expect(updated_order_item.quantity).must_equal 3 + + must_redirect_to product_path(@product_cactus.id) + expect(flash[:failure]).must_equal "Sorry, there are not enough items in stock." + end + end + + describe 'delete' do + before do + @user = User.create(username: "georgina", email: "geor@gmail.com") + @product_cactus = Product.create(user_id: @user.id, name: "cactus", description: "cool product", price: 1.9, photo_url: "url", stock: 3) + @product_flower = Product.create(user_id: @user.id, name: "flower", description: "cool flower", price: 1.5, photo_url: "url", stock: 3) + @order = Order.create(address: "x", name: "x", cc_num: "x", cvv_code: "x", zip: "x", email: "blank@blank.com", exp_date: "10/20") + end + + it 'can delete an order_item successfully while logged in' do + new_order_item = OrderItem.create(product_id: @product_cactus.id, quantity: 3, order_id: @order.id,) + expect { + delete "/order_items/#{new_order_item.id}" + }.must_change 'OrderItem.count', 1 + end + end + + describe 'update' do + before do + @user = User.create(username: "georgina", email: "geor@gmail.com") + @product_cactus = Product.create(user_id: @user.id, name: "cactus", description: "cool product", price: 1.9, photo_url: "url", stock: 3) + @product_flower = Product.create(user_id: @user.id, name: "flower", description: "cool flower", price: 1.5, photo_url: "url", stock: 3) + @order = Order.create(address: "x", name: "x", cc_num: "x", cvv_code: "x", zip: "x", email: "blank@blank.com", exp_date: "10/20") + @order = Order.create + @new_order_item = OrderItem.create(product_id: @product_cactus.id, quantity: 3, order_id: @order.id,) + @updated_order_item_hash = { + order_item: { + product_id: @product_cactus.id, + quantity: 5, + order_id: @order.id, + } + } + end + it "can update an existing order_item while logged in" do + patch "/order_items/#{@new_order_item.id}", params: @updated_order_item_hash + + expect(OrderItem.find_by(id: @new_order_item.id).quantity).must_equal 5 + end + end + + describe "complete" do + it "changes the status to complete" do + user = users(:orchid) + perform_login(user) + + oi = order_items(:bear_treeivy) + oi_status = oi.status + + expect { + post mark_complete_path(oi.id) + }.wont_differ "OrderItem.count" + + must_redirect_to dashboard_path(user.id) + expect(OrderItem.find_by(id: oi.id).status).must_equal "complete" + end + + it "is idempotent" do + user = users(:orchid) + perform_login(user) + + oi = order_items(:bear_treeivy) + oi_status = oi.status + + post mark_complete_path(oi.id) + post mark_complete_path(oi.id) + + must_redirect_to dashboard_path(user.id) + expect(OrderItem.find_by(id: oi.id).status).must_equal "complete" + end + end + end +end diff --git a/test/controllers/orders_controller_test.rb b/test/controllers/orders_controller_test.rb new file mode 100644 index 0000000000..211f96a714 --- /dev/null +++ b/test/controllers/orders_controller_test.rb @@ -0,0 +1,279 @@ +require "test_helper" + +describe OrdersController do + describe 'guest users' do + describe "index" do + it "gives back a susccesful response" do + get orders_path + must_respond_with :success + end + + it "can get the root path" do + get root_path + must_respond_with :success + end + end + + describe "show" do + it "gives back a successful response" do + order = Order.create + get order_path(order.id) + + must_respond_with :success + end + end + + describe "create" do + before do + @order_hash = { + order: { + address: "Redmond", + name: "Georgina", + cc_num: "1111111111111111", + cvv_code: "123", + zip: "98004", + email: "blank@gmail.com", + status: "pending" + } + } + end + + it 'creates a new order successfully with valid data while not logged in, and redirects the user to the products page' do + order_hash = { + order: { + address: "Redmond", + name: "Georgina", + cc_num: "1111111111111111", + cvv_code: "123", + zip: "98004", + exp_date: "10/20", + email: "blank@gmail.com", + status: "pending" + } + } + + expect { + post orders_path, params: order_hash + }.must_differ 'Order.count', 1 + must_redirect_to root_path + end + + it "takes the date using the regex in order to create the order" do + + order_hash = { + order: { + address: "Redmond", + name: "Georgina", + cc_num: "1111111111111111", + cvv_code: "123", + zip: "98004", + exp_date: "10/20", + email: "blank@gmail.com", + status: "pending" + } + } + + new_order = Order.create(order_hash[:order]) + new_order.update(address: "Redmond", name: "Georgina", cc_num: "1111111111111111", cvv_code: "123", zip: "98004", exp_date: "abc10/2020", email: "blank@gmail.com", status: "pending") + updated_order = Order.find_by(id: new_order.id) + expect(updated_order.exp_date).must_equal "10/20" + end + end + + describe "update" do + before do + @new_order = Order.create + @product = products(:orchid) + @order_item = OrderItem.create(product_id: @product.id, order_id: @new_order.id, quantity: 10) + + end + + it "updates order status to 'paid' and reduces the stock quantity" do + order_hash = { + order: { + address: "Redmond", + name: "Georgina", + cc_num: "1111111111111111", + cvv_code: "123", + zip: "98004", + exp_date: "10/20", + email: "blank@gmail.com", + status: "pending" + } + } + + expect { patch order_path(@new_order.id), params: order_hash }.wont_change "Order.count" + + updated_order = Order.find(@new_order.id) + updated_product = Product.find(@product.id) + + expect(updated_order.status).must_equal "paid" + expect(updated_product.stock).must_equal 90 + expect(session[:order_id]).must_be_nil + must_redirect_to checkout_show_path(updated_order.id) + end + + it "flashes an error with incomplete input" do + invalid_order = @new_order.update(email: "geob@gmail.com", name: "georgina", address: "bellevue", cvv_code: "111", cc_num: "1111111111111111", exp_date: "10/20") + + expect(@new_order.errors.full_messages.to_sentence).must_include "Zip" + + + end + + it 'renders the same page' do + order_hash = { + order: { + address: "Redmond", + name: "Georgina", + cc_num: "1111111111111111", + cvv_code: "123", + exp_date: "10/20", + email: "blank@gmail.com", + status: "pending" + } + } + + patch order_path(@new_order.id), params: order_hash + assert_template :edit + end + end + end + + + describe "Logged in users" do + before do + perform_login(users(:begonia)) + end + + describe "index" do + it "gives back a susccesful response" do + get orders_path + + must_respond_with :success + end + + it "can get the root path" do + get root_path + must_respond_with :success + end + end + + describe "show" do + it "gives back a successful response" do + order = Order.create + get order_path(order.id) + must_respond_with :success + end + end + + describe "create" do + it 'creates a new order successfully with valid data while logged in, and redirects the user to the products page' do + order_hash = { + order: { + address: "Redmond", + name: "Georgina", + cc_num: "1111111111111111", + cvv_code: "123", + zip: "98004", + email: "blank@gmail.com", + exp_date: "10/20", + status: "pending" + } + } + + expect { + post orders_path, params: order_hash + }.must_differ 'Order.count', 1 + must_redirect_to root_path + end + + describe "show" do + it "gives back a successful response" do + order = Order.create(address: "Redmond", name: "Georgina", cc_num: "1111111111111111", cvv_code: "123", zip: "98004", email: "blank@gmail.com", status: "pending") + get order_path(order.id) + must_respond_with :success + end + end + + describe "create" do + it 'creates a new order successfully with valid data while logged in, and redirects the user to the products page' do + order_hash = { + order: { + address: "Redmond", + name: "Georgina", + cc_num: "1111111111111111", + cvv_code: "123", + zip: "98004", + email: "blank@gmail.com", + status: "pending" + } + } + + expect { + post orders_path, params: order_hash + }.must_differ 'Order.count', 1 + must_redirect_to root_path + end + end + end + + describe "update" do + before do + @new_order = Order.create + @product = products(:orchid) + @order_item = OrderItem.new(product_id: @product.id, order_id: @new_order.id, quantity: 10) + + end + + it "updates order status to 'paid', and reduce available stock upon purchase" do + order_hash = { + order: { + address: "Redmond", + name: "Georgina", + cc_num: "1111111111111111", + cvv_code: "123", + zip: "98004", + exp_date: "10/20", + email: "blank@gmail.com", + status: "pending" + } + } + + expect { patch order_path(@new_order.id), params: order_hash }.wont_change "Order.count" + + updated_order = Order.find(@new_order.id) + updated_product = Product.find(@product.id) + + expect(updated_order.status).must_equal "paid" + #expect(updated_product.stock).must_equal 90 + must_redirect_to checkout_show_path(updated_order.id) + end + + it "flashes an error with incomplete input" do + invalid_order = @new_order.update(email: "geob@gmail.com", name: "georgina", address: "bellevue", cvv_code: "111", cc_num: "1111111111111111", exp_date: "10/20") + + expect(@new_order.errors.full_messages.to_sentence).must_include "Zip" + + + end + + it 'renders the same page' do + order_hash = { + order: { + address: "Redmond", + name: "Georgina", + cc_num: "1111111111111111", + cvv_code: "123", + exp_date: "10/20", + email: "blank@gmail.com", + status: "pending" + } + } + + patch order_path(@new_order.id), params: order_hash + assert_template :edit + end + end + end +end diff --git a/test/controllers/products_controller_test.rb b/test/controllers/products_controller_test.rb new file mode 100644 index 0000000000..031242acb0 --- /dev/null +++ b/test/controllers/products_controller_test.rb @@ -0,0 +1,237 @@ +require "test_helper" + +describe ProductsController do + + before do + @user = User.create(username: "test user", email: "test_email@example.com") + @category1 = Category.create(name: "flower") + @category2 = Category.create(name: "specialty") + @product = Product.create(user_id: @user.id, name: "test product", description: "cool product", price: 1.99, photo_url: "url", stock: 3) + + @review1 = Review.create(product_id: @product.id, rating: 5, comment: "great product") + @review2 = Review.create(product_id: @product.id, rating: 2, comment: "bad product") + + @order = Order.create(email: "test email", address: "test address", name: "test user name", cc_num: 1234, zip: 98111) + @order_item1 = OrderItem.create(product_id: @product.id, order_id: @order.id, quantity: 2) + @order_item2 = OrderItem.create(product_id: @product.id, order_id: @order.id, quantity: 4) + end + + describe "Logged in users" do + before do + perform_login(users(:begonia)) + end + + describe "index" do + it "gives back success when products saved" do + get products_path + must_respond_with :success + end + + it "can get the root path" do + get root_path + must_respond_with :success + end + + it "responds with sucess when no products saved" do + Product.destroy_all + + expect(Product.count).must_equal 0 + get products_path + must_respond_with :success + end + end + + describe "show" do + it "can get a valid product" do + get product_path(@product.id) + must_respond_with :success + end + + it "will redirect for an invalid product id" do + get product_path(-1111) + must_redirect_to products_path + end + end + + describe "new" do + it "can get the new product page" do + get new_product_path + must_respond_with :success + end + end + + describe "create" do + it "can create a new product with valid information" do + product_hash = { + product: { + user_id: @user.id, + name: "new product", + description: "new description", + price: 1.99, + stock: 49, + photo_url: "new_photo url" + } + } + + expect { + post products_path, params: product_hash + }.must_change "Product.count", 1 + + new_product = Product.find_by(name: product_hash[:product][:name]) + expect(new_product.price).must_equal product_hash[:product][:price] + expect(new_product.stock).must_equal product_hash[:product][:stock] + expect(new_product.photo_url).must_equal product_hash[:product][:photo_url] + expect(new_product.description).must_equal product_hash[:product][:description] + + must_respond_with :redirect + must_redirect_to product_path(new_product.id) + end + end + + describe "edit" do + it "can get the edit page for an existing product" do + user = users(:orchid) + # hollyhock is orchid's product + product = products(:hollyhock) + + perform_login(user) + get edit_product_path(product.id) + + must_respond_with :success + end + + it "cannot get the edit page for someone else's product" do + user = users(:orchid) + # treeivy is begonia's product + product = products(:treeivy) + + perform_login(user) + get edit_product_path(product.id) + + must_redirect_to product_path(product.id) + expect(flash[:error]).must_equal "You cannot edit another merchant's product" + end + + it "won't edit an invalid product id and redirect" do + get edit_product_path(-111) + must_respond_with :redirect + end + end + + describe "update" do + it "can update an existing product" do + updated_product_hash = { + product: { + user_id: @user.id, + name: "updated product", + description: "updated description", + price: 2.00, + stock: 50, + photo_url: "updated photo_url" + } + } + + expect { + patch product_path(@product.id), params: updated_product_hash + }.wont_change "Product.count" + + expect(Product.find_by(id: @product.id).name).must_equal "updated product" + expect(Product.find_by(id: @product.id).description).must_equal "updated description" + expect(Product.find_by(id: @product.id).photo_url).must_equal "updated photo_url" + expect(Product.find_by(id: @product.id).price).must_equal 2.00 + expect(Product.find_by(id: @product.id).stock).must_equal 50 + + must_respond_with :redirect + must_redirect_to dashboard_path(users(:begonia).id) + end + + it "can't update an existing product with wrong params" do + bad_product_hash = { + product: { + user_id: @user.id, + name: nil, + description: nil, + price: nil, + stock: nil, + photo_url: nil + } + } + + patch product_path(@product.id), params: bad_product_hash + expect(Product.find_by(id: @product.id).name).must_equal "test product" + end + + it "will redirect to the root page if given an invalid id" do + get product_path(-1) + must_respond_with :redirect + end + end + + describe "toggle" do + it "retires a product" do + product = products(:orchid) + patch retired_path(product.id) + expect(Product.find_by(id: product.id).available).wont_equal true + end + end + end + + describe "guest users" do + describe "update" do + it "can not create a product" do + product_hash = { + product: { + user_id: nil, + name: "new product", + description: "new description", + price: 1.99, + stock: 49, + photo_url: "new_photo url" + } + } + + expect { + post products_path, params: product_hash + }.wont_change "Product.count" + end + + it "can not update a product" do + product = products(:orchid) + product_hash = { + product: { + user_id: nil, + name: "new product", + description: "new description", + price: 14, + stock: 100, + photo_url: "new_photo url" + } + } + + patch product_path(product.id), params: product_hash + expect(flash[:error]).must_equal "A guest cannot update a product." + end + end + + describe "edit" do + it "cannot get the edit page for a product" do + product = products(:treeivy) + + get edit_product_path(product.id) + + must_redirect_to product_path(product.id) + expect(flash[:error]).must_equal "A guest cannot edit a product" + end + end + + describe "new" do + it "cannot get the new page for a product" do + get new_product_path + + must_redirect_to products_path + expect(flash[:error]).must_equal "A guest cannot create a product" + end + end + end +end + diff --git a/test/controllers/reviews_controller_test.rb b/test/controllers/reviews_controller_test.rb new file mode 100644 index 0000000000..83d3fa2d90 --- /dev/null +++ b/test/controllers/reviews_controller_test.rb @@ -0,0 +1,76 @@ +require "test_helper" + +describe ReviewsController do + describe "guest user" do + describe "create" do + it "lets a guest user review a product" do + params_hash = { + review: { + rating: 5, + comment: "great plant" + } + } + + product = products(:treeivy) + + expect { + post product_reviews_path(product.id), params: params_hash + }.must_differ "Review.count", 1 + + new_review = Review.last + expect(new_review.comment).must_equal params_hash[:review][:comment] + expect(new_review.rating).must_equal params_hash[:review][:rating] + expect(flash[:success]).must_equal "Your review was successfully submitted." + end + end + end + + describe "logged in user" do + describe "create" do + before do + user = users(:orchid) + perform_login(user) + end + + it "lets a logged in user review another user's product" do + params_hash = { + review: { + rating: 5, + comment: "great plant" + } + } + + # treeivy is not orchid's product + product = products(:treeivy) + + expect { + post product_reviews_path(product.id), params: params_hash + }.must_differ "Review.count", 1 + + new_review = Review.last + expect(new_review.comment).must_equal params_hash[:review][:comment] + expect(new_review.rating).must_equal params_hash[:review][:rating] + expect(flash[:success]).must_equal "Your review was successfully submitted." + end + + it "does not let a logged in user review their own product" do + params_hash = { + review: { + rating: 5, + comment: "great plant" + } + } + + # hollyhock is one of orchid's products + product = products(:hollyhock) + + expect { + post product_reviews_path(product.id), params: params_hash + }.wont_change "Review.count" + + must_redirect_to product_path(product.id) + expect(flash[:error]).must_equal "You cannot review your own product" + end + end + end +end diff --git a/test/controllers/users_controller_test.rb b/test/controllers/users_controller_test.rb new file mode 100644 index 0000000000..14a4871109 --- /dev/null +++ b/test/controllers/users_controller_test.rb @@ -0,0 +1,156 @@ +require "test_helper" + +describe UsersController do + describe "create" do + it "logs in an existing user and redirects to the dashboard" do + start_count = User.count + user = users(:begonia) + + perform_login(user) + + must_redirect_to dashboard_path(user.id) + expect(session[:user_id]).must_equal user.id + expect(flash[:success]).must_include "Successfully logged in as returning user" + expect(User.count).must_equal start_count + end + + it "creates an account for a new user and redirects to the dashboard" do + start_count = User.count + new_user = User.new(provider: "github", uid: 888444, username: "newbie", email: "test@example.com") + + OmniAuth.config.mock_auth[:github] = OmniAuth::AuthHash.new(mock_auth_hash(new_user)) + + get callback_path(:github) + + must_redirect_to dashboard_path(User.last.id) + expect(session[:user_id]).must_equal User.last.id + expect(flash[:success]).must_include "Successfully logged in as new user" + expect(User.count).must_equal start_count + 1 + end + + it "redirects to the login route if given invalid user data" do + start_count = User.count + new_user = User.new(provider: "github", uid: 888444, email: "test@example.com") + + OmniAuth.config.mock_auth[:github] = OmniAuth::AuthHash.new(mock_auth_hash(new_user)) + + get callback_path(:github) + + must_redirect_to root_path + expect(flash[:error]).wont_be_nil + expect(User.count).must_equal start_count + end + end + + describe "Logged in users" do + describe "destroy" do + it "logs out a user" do + start_count = User.count + user = users(:begonia) + + perform_login(user) + # check that there is a logged in user to log out + expect(session[:user_id]).must_equal user.id + + delete logout_path + + must_redirect_to root_path + expect(session[:user_id]).must_be_nil + expect(flash[:success]).must_equal "Successfully logged out!" + # make sure the user did not get deleted from the database + expect(User.count).must_equal start_count + end + end + + describe "index" do + it "can see the merchant index" do + user = users(:begonia) + + perform_login(user) + + get users_path + + must_respond_with :success + end + end + + describe "show" do + it "can see the product-by-merchant list page" do + user = users(:begonia) + + get user_path(user) + + must_respond_with :success + end + end + + describe "dashboard" do + it "can be viewed by its own merchant" do + user = users(:begonia) + perform_login(user) + + get dashboard_path(user) + + must_respond_with :success + end + + it "can't be viewed by another merchant" do + begonia = users(:begonia) + orchid = users(:orchid) + + perform_login(begonia) + + get dashboard_path(orchid) + + must_respond_with :redirect + must_redirect_to users_path + expect(flash[:error]).must_equal "Permission denied: you cannot view another merchant's dashboard" + end + end + end + + describe "Guest users" do + describe "destroy" do + it "doesn't effect an logged-out user" do + start_count = User.count + + delete logout_path + + expect(session[:user_id]).must_be_nil + expect(flash[:success]).must_be_nil + expect(flash[:error]).must_equal "No one logged in" + expect(User.count).must_equal start_count + end + end + + describe "index" do + it "can see the merchant index" do + get users_path + + must_respond_with :success + end + end + + describe "show" do + it "can see the product-by-merchant list page" do + user = users(:begonia) + + get user_path(user) + + must_respond_with :success + end + end + + describe "dashboard" do + it "cannot be viewed by a guest" do + user = users(:begonia) + + get dashboard_path(user) + + must_respond_with :redirect + must_redirect_to users_path + expect(flash[:error]).must_equal "Permission denied: please log in to view your dashboard" + end + end + end +end diff --git a/test/fixtures/.keep b/test/fixtures/.keep new file mode 100644 index 0000000000..e69de29bb2 diff --git a/test/fixtures/categories.yml b/test/fixtures/categories.yml new file mode 100644 index 0000000000..7248c3a0fa --- /dev/null +++ b/test/fixtures/categories.yml @@ -0,0 +1,35 @@ +annual: + name: annual + products: tarsha, sal, palmer + +evergreen: + name: evergreen + products: loyd + +flower: + name: Flower + products: begonia, tarsha, wilfred, mario, palmer + +full_sun: + name: Full Sun + products: + +houseplant: + name: houseplant + products: christopher + +shade: + name: Shade + products: brad + +specialty: + name: Specialty + products: orchid, begonia, tarsha, wilfred, tereasa, sal + +succulent: + name: succulent + products: mario, kenda + +perennial: + name: perennial + products: ester diff --git a/test/fixtures/files/.keep b/test/fixtures/files/.keep new file mode 100644 index 0000000000..e69de29bb2 diff --git a/test/fixtures/order_items.yml b/test/fixtures/order_items.yml new file mode 100644 index 0000000000..61078fcd56 --- /dev/null +++ b/test/fixtures/order_items.yml @@ -0,0 +1,228 @@ +ducky_bellflower: + quantity: 1 + order: ducky_orchid_bellflower + product: bellflower + status: paid +bear_hollyhock: + quantity: 2 + order: bear_orchid_hollyhock + product: hollyhock + status: complete +bear_treeivy: + quantity: 3 + order: bear_orchid_hollyhock + product: treeivy + status: complete +# sort by status testing +guavashop_guava_rockfoil: + quantity: 1 + order: guava_shop_order + product: rockfoil + status: paid +guavashop_guava_obedient: + quantity: 1 + order: guava_shop_order + product: obedientplant + status: paid +# ############ +pineappleshop_pineapple_plumbago: + quantity: 1 + order: pineapple_shop_order + product: plumbago + status: complete +pineappleshop_pineapple_sage: + quantity: 1 + order: pineapple_shop_order + product: sage + status: paid +# ############ +orangeshop_orange_pilea: + quantity: 1 + order: orange_shop_order + product: pilea + status: complete +orangeshop_orange_spider: + quantity: 1 + order: orange_shop_order + product: spiderflower + status: cancelled +# ############ +plumshop_plum_aster: + quantity: 1 + order: plum_shop_order + product: aster + status: complete +plumshop_plum_clematis: + quantity: 1 + order: plum_shop_order + product: clematis + status: complete +# ############ +peachshop_peach_lewisia: + quantity: 1 + order: peach_shop_order + product: lewisia + status: paid +peachshop_peach_shield: + quantity: 1 + order: peach_shop_order + product: persianshield + status: paid +peachshop_kiwi_crossandra: + quantity: 1 + order: peach_shop_order + product: crossandra + status: complete +# ############ +carrotshop_carrot_henchicks: + quantity: 1 + order: carrot_shop_order + product: henchicks + status: complete +carrotshop_carrot_agastache: + quantity: 1 + order: carrot_shop_order + product: agastache + status: paid +carrotshop_kiwi_crossandra: + quantity: 1 + order: carrot_shop_order + product: crossandra + status: paid +# ############ +berryshop_berry_foam: + quantity: 1 + order: berry_shop_order + product: foamflower + status: complete +berryshop_peach_zebra: + quantity: 1 + order: berry_shop_order + product: zebraplant + status: cancelled +berryshop_kiwi_crossandra: + quantity: 1 + order: berry_shop_order + product: crossandra + status: paid +# ############ +melonshop_melon_sunflower: + quantity: 1 + order: melon_shop_order + product: sunflower + status: complete +melonshop_melon_daisy: + quantity: 1 + order: melon_shop_order + product: daisy + status: complete +melonshop_kiwi_crossandra: + quantity: 1 + order: melon_shop_order + product: crossandra + status: paid +# ############ +grapefruitshop_grapefruit_thyme: + quantity: 1 + order: grapefruit_shop_order + product: thyme + status: cancelled +grapefruitshop_grapefruit_heuchera: + quantity: 1 + order: grapefruit_shop_order + product: heuchera + status: cancelled +grapefruitshop_kiwi_crossandra: + quantity: 1 + order: grapefruit_shop_order + product: crossandra + status: paid +# ############ +apricotshop_apricot_orchidcactus: + quantity: 1 + order: apricot_shop_order + product: orchidcactus + status: pending +apricotshop_apricot_boliviansunset: + quantity: 1 + order: apricot_shop_order + product: boliviansunset + status: pending +apricotshop_kiwi_crossandra: + quantity: 1 + order: apricot_shop_order + product: crossandra + status: pending +# ############ +mangoshop_mango_complete_1: + quantity: 1 + order: mango_shop_complete_1 + product: goldenrod + status: complete +mangoshop_mango_complete_2: + quantity: 1 + order: mango_shop_complete_2 + product: englishdaisy + status: complete +mangoshop_mango_cancelled: + quantity: 1 + order: mango_shop_cancelled + product: goldenrod + status: cancelled +mangoshop_mango_paid_1: + quantity: 1 + order: mango_shop_paid_1 + product: goldenrod + status: paid +mangoshop_mango_paid_2: + quantity: 1 + order: mango_shop_paid_2 + product: englishdaisy + status: paid +mangoshop_mango_pending: + quantity: 1 + order: mango_shop_pending + product: goldenrod + status: pending +# ############ +crabappleshop_crabapple_ghostfern: + quantity: 1 + order: crabapple_shop_order + product: ghostfern + status: complete +crabappleshop_crabapple_desertrose: + quantity: 1 + order: crabapple_shop_order + product: desertrose + status: paid +# ############ +pearshop_pear_aloe_pending: + quantity: 3 + order: pear_shop_aloe_pending + product: aloe + status: pending +pearshop_pear_aloe_paid: + quantity: 2 + order: pear_shop_aloe_paid + product: aloe + status: paid +pearshop_pear_aloe_complete: + quantity: 2 + order: pear_shop_aloe_complete + product: aloe + status: complete +pearshop_pear_aloe_cancelled: + quantity: 3 + order: pear_shop_aloe_cancelled + product: aloe + status: cancelled +pearshop_pear_snakeplant: + quantity: 8 + order: pear_shop_snakeplant + product: snakeplant + status: complete +watercressshop_watercress_viola: + quantity: 5 + order: watercress_shop_order + product: viola + status: pending \ No newline at end of file diff --git a/test/fixtures/orders.yml b/test/fixtures/orders.yml new file mode 100644 index 0000000000..3ab70588bd --- /dev/null +++ b/test/fixtures/orders.yml @@ -0,0 +1,251 @@ +myrta_order: + email: darren@turcotte.io + address: 1950 Hugh Valley + name: Myrta Bauch + cc_num: 1234-2121-1221-1211 + cvv_code: 411 + zip: 33515-6343 + +geri_order: + email: mona@mohr.biz + address: 527 Gary Place + name: Geri Skiles + cc_num: 1234-2121-1221-1211 + cvv_code: 429 + zip: 84847-0917 + +anita_order: + email: serena.bauch@lynch.com + address: 9481 Padberg Inlet + name: Anita Deckow + cc_num: 1212-1221-1121-1234 + cvv_code: 845 + zip: 01196 + +lona_order: + email: suzann@paucek.biz + address: 50288 Sanford Mission + name: Lona Block + cc_num: 1212-1221-1121-1234 + cvv_code: 878 + zip: 54170-6817 + +ora_order: + email: ciera.wyman@purdymaggio.io + address: 73457 Grant Burgs + name: Ora Corkery + cc_num: 1234-2121-1221-1211 + cvv_code: 832 + zip: 10824 + +georgina_order: + email: geo@gmail.com + address: bellevue + name: Georgina + cc_num: 1234-2121-1221-1211 + cvv_code: 111 + zip: 98004 + +sam_order: + email: sam@gmail.com + address: seattle + name: Sam + cc_num: 1234-2121-1221-1211 + cvv_code: 222 + zip: 98005 + +hallie_order: + email: hall@gmail.com + address: redmond + name: Hallie + cc_num: 1234-2121-1221-1211 + cvv_code: 333 + zip: 98006 + +sabrina_order: + email: sab@gmail.com + address: kirkland + name: Sabrina + cc_num: 1234-2121-1221-1211 + cvv_code: 444 + zip: 98007 + +ducky_orchid_bellflower: + email: sab@gmail.com + address: kirkland + name: Ducky + cc_num: 1234-2121-1221-1211 + cvv_code: 444 + zip: 98002 + +bear_orchid_hollyhock: + email: placebear@gmail.com + address: Bear Creek + name: Place Bear + cc_num: 1234-2121-1221-1211 + cvv_code: 444 + zip: 98002 + +# sort by status testing +guava_shop_order: + email: lilkitten@gmail.com + address: Kitten Creek + name: Guava Shopper + cc_num: 1234-2121-1221-1211 + cvv_code: 444 + zip: 98002 +pineapple_shop_order: + email: lilkitten@gmail.com + address: Kitten Creek + name: Pineapple Shopper + cc_num: 1234-2121-1221-1211 + cvv_code: 444 + zip: 98002 +orange_shop_order: + email: lilkitten@gmail.com + address: Kitten Creek + name: Orange Shopper + cc_num: 1234-2121-1221-1211 + cvv_code: 444 + zip: 98002 +plum_shop_order: + email: lilkitten@gmail.com + address: Kitten Creek + name: Plum Shopper + cc_num: 1234-2121-1221-1211 + cvv_code: 444 + zip: 98002 +peach_shop_order: + email: lilkitten@gmail.com + address: Kitten Creek + name: Peach Shopper + cc_num: 1234-2121-1221-1211 + cvv_code: 444 + zip: 98002 +carrot_shop_order: + email: lilkitten@gmail.com + address: Kitten Creek + name: Carrot Shopper + cc_num: 1234-2121-1221-1211 + cvv_code: 444 + zip: 98002 +berry_shop_order: + email: lilkitten@gmail.com + address: Kitten Creek + name: Berry Shopper + cc_num: 1234-2121-1221-1211 + cvv_code: 444 + zip: 98002 +melon_shop_order: + email: lilkitten@gmail.com + address: Kitten Creek + name: Melon Shopper + cc_num: 1234-2121-1221-1211 + cvv_code: 444 + zip: 98002 +grapefruit_shop_order: + email: lilkitten@gmail.com + address: Kitten Creek + name: Grapefruit Shopper + cc_num: 1234-2121-1221-1211 + cvv_code: 444 + zip: 98002 +apricot_shop_order: + email: lilkitten@gmail.com + address: Kitten Creek + name: Grapefruit Shopper + cc_num: 1234-2121-1221-1211 + cvv_code: 444 + zip: 98002 +mango_shop_complete_1: + email: lilkitten@gmail.com + address: Kitten Creek + name: Mango Shopper 1 + cc_num: 1234-2121-1221-1211 + cvv_code: 444 + zip: 98002 +mango_shop_complete_2: + email: lilkitten@gmail.com + address: Kitten Creek + name: Mango Shopper 2 + cc_num: 1234-2121-1221-1211 + cvv_code: 444 + zip: 98002 +mango_shop_cancelled: + email: lilkitten@gmail.com + address: Kitten Creek + name: Mango Shopper 3 + cc_num: 1234-2121-1221-1211 + cvv_code: 444 + zip: 98002 +mango_shop_paid_1: + email: lilkitten@gmail.com + address: Kitten Creek + name: Mango Shopper 4 + cc_num: 1234-2121-1221-1211 + cvv_code: 444 + zip: 98002 +mango_shop_paid_2: + email: lilkitten@gmail.com + address: Kitten Creek + name: Mango Shopper 5 + cc_num: 1234-2121-1221-1211 + cvv_code: 444 + zip: 98002 +mango_shop_pending: + email: lilkitten@gmail.com + address: Kitten Creek + name: Mango Shopper 6 + cc_num: 1234-2121-1221-1211 + cvv_code: 444 + zip: 98002 +crabapple_shop_order: + email: lilkitten@gmail.com + address: Kitten Creek + name: Crabapple Shopper + cc_num: 1234-2121-1221-1211 + cvv_code: 444 + zip: 98002 +# ########## +pear_shop_aloe_pending: + email: lilkitten@gmail.com + address: Kitten Creek + name: Pear Shopper 1 + cc_num: 1234-2121-1221-1211 + cvv_code: 444 + zip: 98002 +pear_shop_aloe_paid: + email: lilkitten@gmail.com + address: Kitten Creek + name: Pear Shopper 2 + cc_num: 1234-2121-1221-1211 + cvv_code: 444 + zip: 98002 +pear_shop_aloe_complete: + email: lilkitten@gmail.com + address: Kitten Creek + name: Pear Shopper 3 + cc_num: 1234-2121-1221-1211 + cvv_code: 444 + zip: 98002 +pear_shop_aloe_cancelled: + email: lilkitten@gmail.com + address: Kitten Creek + name: Pear Shopper 4 + cc_num: 1234-2121-1221-1211 + cvv_code: 444 + zip: 98002 +pear_shop_snakeplant: + email: lilkitten@gmail.com + address: Kitten Creek + name: Pear Shopper 5 + cc_num: 1234-2121-1221-1211 + cvv_code: 444 + zip: 98002 +watercress_shop_order: + email: lilkitten@gmail.com + address: Kitten Creek + name: Watercress Shopper + cc_num: 1234-2121-1221-1211 + cvv_code: 444 + zip: 98002 \ No newline at end of file diff --git a/test/fixtures/products.yml b/test/fixtures/products.yml new file mode 100644 index 0000000000..4046a40483 --- /dev/null +++ b/test/fixtures/products.yml @@ -0,0 +1,445 @@ +orchid: + name: Ada Orchid + description: Cool + price: 12.99 + photo_url: https://lorempixel.com/300/300 + stock: 100 + available: true + user_id: 2 + categories: + +begonia: + name: Begonia Flower + description: Cool + price: 8.99 + photo_url: https://lorempixel.com/300/300 + stock: 200 + available: true + user_id: 2 + categories: + +tarsha: + name: Tarsha Aufderhar + description: Et iste sed aut. + price: 66.31 + photo_url: https://lorempixel.com/300/300 + stock: 39 + available: true + user_id: 13 + categories: + +brad: + name: Brad Crist DVM + description: Qui aut rerum totam. + price: 76.73 + photo_url: https://lorempixel.com/300/300 + stock: 47 + available: true + user_id: 12 + categories: + +loyd: + name: Loyd Toy Jr. + description: Tempore velit aut eaque. + price: 18.48 + photo_url: https://lorempixel.com/300/300 + stock: 18 + available: true + user_id: 8 + categories: + +christopher: + name: Christoper Cormier + description: Veritatis et qui sed. + price: 74.99 + photo_url: https://lorempixel.com/300/300 + stock: 16 + available: true + user_id: 15 + categories: + +wilfred: + name: Wilfred Tremblay + description: Vel et tempora recusandae. + price: 68.13 + photo_url: https://lorempixel.com/300/300 + stock: 21 + available: true + user_id: 20 + categories: + +tereasa: + name: Tereasa Kunze + description: Sint aliquam ipsum fugiat. + price: 71.73 + photo_url: https://lorempixel.com/300/300 + stock: 32 + available: false + user_id: 24 + categories: + +sal: + name: Sal Considine + description: Dolor adipisci quia odit. + price: 51.89 + photo_url: https://lorempixel.com/300/300 + stock: 28 + available: false + user_id: 6 + categories: + +mario: + name: Mario Medhurst + description: In aut placeat iste. + price: 19.2 + photo_url: https://lorempixel.com/300/300 + stock: 6 + available: true + user_id: 16 + categories: + +kenda: + name: Kenda Barton + description: Vitae itaque esse non. + price: 81.25 + photo_url: https://lorempixel.com/300/300 + stock: 43 + available: false + user_id: 2 + categories: + +palmer: + name: Palmer Terry III + description: Dolore asperiores magni qui. + price: 78.69 + photo_url: https://lorempixel.com/300/300 + stock: 1 + available: false + user_id: 4 + categories: + +ester: + name: Mr. Ester Toy + description: Placeat nihil molestiae ad. + price: 87.74 + photo_url: https://lorempixel.com/300/300 + stock: 19 + available: true + user_id: 25 + categories: + +hollyhock: + name: Alcea rosea + description: Sun-loving, flowering plant that grows from 4 to 6 feet tall. + price: 12.75 + photo_url: https://lorempixel.com/300/300 + stock: 5 + available: true + user: orchid + categories: + +bellflower: + name: Campanula spp. + description: A short, easy-growing plant with lovely blue flowers. + price: 12.75 + photo_url: https://lorempixel.com/300/300 + stock: 5 + available: true + user: orchid + categories: + +treeivy: + name: Fatshedera spp. + description: A fun houseplant with ivy-like leaves and an upright, shrubby growth orientation. + price: 12.75 + photo_url: https://lorempixel.com/300/300 + stock: 5 + available: true + user: begonia + categories: + +teddybearvine: + name: Cyanotis kewensis + description: A unique houseplant with trailing stems decorated with teardrop-shaped fuzzy leaves. + price: 18.80 + photo_url: https://lorempixel.com/300/300 + stock: 2 + available: true + user: rose + categories: + +# sort by status testing +rockfoil: + name: Saxifraga spp. + description: A unique plant that thrives on hillsides and slopes. + price: 18.80 + photo_url: https://lorempixel.com/300/300 + stock: 3 + available: true + user: guava + categories: +obedientplant: + name: Physostegia spp. + description: A quick-growing perennial that will easily carpet and area in beautiful purple flowers. + price: 18.80 + photo_url: https://lorempixel.com/300/300 + stock: 3 + available: true + user: guava + categories: +# ############ +plumbago: + name: Ceratostigma plumbaginoides + description: A summer bloomer that offers dainty blue flowers. + price: 18.80 + photo_url: https://lorempixel.com/300/300 + stock: 3 + available: true + user: pineapple + categories: +sage: + name: Salvia spp. + description: A gorgeous plant with stalks of beautifully-scented, brightly-colored flowers. Favored by pollinators. + price: 18.80 + photo_url: https://lorempixel.com/300/300 + stock: 3 + available: true + user: pineapple + categories: +# ############ +pilea: + name: Pilea spp. + description: An easy-to-grow houseplant that offers large, variagated leaves for a unique look. + price: 18.80 + photo_url: https://lorempixel.com/300/300 + stock: 3 + available: true + user: orange + categories: +spiderflower: + name: Cleome + description: An easy-to-grow flower that bursts into armloads of blooms around slender stamens. + price: 18.80 + photo_url: https://lorempixel.com/300/300 + stock: 3 + available: true + user: orange + categories: +# ############ +aster: + name: Aster spp. + description: Sun-loving perennials that will blanket garden beds and containers in color. + price: 18.80 + photo_url: https://lorempixel.com/300/300 + stock: 3 + available: true + user: plum + categories: +clematis: + name: Clematis spp. + description: An easy-to-care-for vine that explodes into large, vivid flowers in the spring and summer. + price: 18.80 + photo_url: https://lorempixel.com/300/300 + stock: 3 + available: true + user: plum + categories: +# ############ +lewisia: + name: Lewisia spp. + description: Delightful, daisy-shaped flowers. + price: 18.80 + photo_url: https://lorempixel.com/300/300 + stock: 3 + available: true + user: peach + categories: +persianshield: + name: Strobilanthes dyerianus + description: An easy-growing tropical shrub with iridescent purple foliage. + price: 18.80 + photo_url: https://lorempixel.com/300/300 + stock: 3 + available: true + user: peach + categories: +# ############ +henchicks: + name: Sempervivum spp. + description: Short plant that produces colorful rosettes. + price: 18.80 + photo_url: https://lorempixel.com/300/300 + stock: 3 + available: true + user: carrot + categories: +agastache: + name: Agastache spp. + description: A rugged, sun-loving perennial. + price: 18.80 + photo_url: https://lorempixel.com/300/300 + stock: 3 + available: true + user: carrot + categories: +# ############ +foamflower: + name: Tiarella cordifolia + description: Native to the North American woodlands, this shrub is ideal for shady gardens. + price: 18.80 + photo_url: https://lorempixel.com/300/300 + stock: 3 + available: true + user: berry + categories: +zebraplant: + name: Aphelandra squarrosa + description: A stunning houseplant with large, striped leaves. + price: 18.80 + photo_url: https://lorempixel.com/300/300 + stock: 3 + available: true + user: berry + categories: +# ############ +sunflower: + name: Helianthus annuus + description: A fast-growing, cheerful plant with a large, bobbing head of seeds and yellow petals. + price: 18.80 + photo_url: https://lorempixel.com/300/300 + stock: 3 + available: true + user: melon + categories: +daisy: + name: Gerbera spp. + description: One of the most popular flowers in the world, a daisy speaks for itself. + price: 18.80 + photo_url: https://lorempixel.com/300/300 + stock: 3 + available: true + user: melon + categories: +# ############ +crossandra: + name: Crossandra infundibuliformis + description: A versatile plant prized for its orange flowers and shiny foliage. + price: 18.80 + photo_url: https://lorempixel.com/300/300 + stock: 3 + available: true + user: kiwi + categories: +# ############ +thyme: + name: Thymus spp. + description: A short, edible plant with fragrant leaves. + price: 18.80 + photo_url: https://lorempixel.com/300/300 + stock: 4 + available: true + user: grapefruit + categories: +heuchera: + name: Heuchera spp. + description: A shade-loving perennial that comes in a wide variety of bold colors. + price: 18.80 + photo_url: https://lorempixel.com/300/300 + stock: 4 + available: true + user: grapefruit + categories: +# ############ +orchidcactus: + name: Epiphyllum guatemalense monstrose + description: An easy-to-grow houseplant with long, curling leaves. + price: 18.80 + photo_url: https://lorempixel.com/300/300 + stock: 4 + available: true + user: apricot + categories: +boliviansunset: + name: Gloxinia sylvatica + description: A gorgeous winter-flowering shrub with bright red blooms. + price: 18.80 + photo_url: https://lorempixel.com/300/300 + stock: 4 + available: true + user: apricot + categories: +# ############ +goldenrod: + name: Solidago spp. + description: Sun-loving perennial that produces long stalks of yellow-gold flowers. A classic. + price: 18.80 + photo_url: https://lorempixel.com/300/300 + stock: 12 + available: true + user: mango + categories: +englishdaisy: + name: Bellis spp. + description: Cheerful, diminutive plant with pom-pom flowers. A classic. + price: 18.80 + photo_url: https://lorempixel.com/300/300 + stock: 9 + available: true + user: mango + categories: +# ############ +ghostfern: + name: Athyrium 'Ghost' + description: A lovely, Japanese-hybrid fern. Slow-growing. + price: 15.00 + photo_url: https://lorempixel.com/300/300 + stock: 12 + available: true + user: crabapple + categories: +desertrose: + name: Adenium obesum + description: A vibrant, low-water succulent. Not spiky. + price: 20.00 + photo_url: https://lorempixel.com/300/300 + stock: 9 + available: true + user: crabapple + categories: +# ############ +snakeplant: + name: Sansevieria trifasciata + description: A hardy, indoor favorite. + price: 15.00 + photo_url: https://lorempixel.com/300/300 + stock: 12 + available: true + user: pear + categories: +aloe: + name: Aloe spp. + description: An easy-to-care for indoor plant that loves sun. + price: 20.00 + photo_url: https://lorempixel.com/300/300 + stock: 9 + available: true + user: pear + categories: +knautia: + name: Knautia macedonica + description: An unsung perennial. + price: 20.00 + photo_url: https://lorempixel.com/300/300 + stock: 9 + available: true + user: pear + categories: +viola: + name: Viola spp. + description: A lovely, purple perennial flower. + price: 20.00 + photo_url: https://lorempixel.com/300/300 + stock: 9 + available: true + user: watercress + categories: \ No newline at end of file diff --git a/test/fixtures/reviews.yml b/test/fixtures/reviews.yml new file mode 100644 index 0000000000..1b7b43ac96 --- /dev/null +++ b/test/fixtures/reviews.yml @@ -0,0 +1,16 @@ +bellflower_review_1: + rating: 1 + comment: "dead on arrival" + product: bellflower +bellflower_review_2: + rating: 5 + comment: "my new favorite plant" + product: bellflower +hollyhock_review_1: + rating: 4 + comment: "pretty great" + product: hollyhock +hollyhock_review_2: + rating: 5 + comment: "love it" + product: hollyhock \ No newline at end of file diff --git a/test/fixtures/users.yml b/test/fixtures/users.yml new file mode 100644 index 0000000000..8bb61c2db0 --- /dev/null +++ b/test/fixtures/users.yml @@ -0,0 +1,105 @@ +begonia: + id: 2 + provider: github + uid: 13371337 + email: grace@hooper.net + username: brilliant_begonia +orchid: + provider: github + uid: 424242 + email: ada@adadevelopersacademy.org + username: awesome_orchid +petunia: + provider: github + uid: 635635 + email: pretty_petunia@example.com + username: pretty_petunia +rose: + provider: github + uid: 999888 + email: ruby_rose@example.com + username: ruby_rose +# sort by status testing +guava: + provider: github + uid: 999888 + email: great_guava@example.com + username: great_guava +pineapple: + provider: github + uid: 999888 + email: personable_pinapple@example.com + username: personable_pinapple +orange: + provider: github + uid: 999888 + email: extraordinary_orange@example.com + username: extraordinary_orange +plum: + provider: github + uid: 999888 + email: powerful_plum@example.com + username: powerful_plum +kiwi: + provider: github + uid: 999888 + email: kute_kiwi@example.com + username: kute_kiwi +peach: + provider: github + uid: 999888 + email: passionate_peach@example.com + username: passionate_peach +carrot: + provider: github + uid: 999888 + email: cute_carrot@example.com + username: cute_carrot +berry: + provider: github + uid: 999888 + email: beautiful_berry@example.com + username: beautiful_berry +melon: + provider: github + uid: 999888 + email: merry_melon@example.com + username: merry_melon +grapefruit: + provider: github + uid: 999888 + email: genius_grapefruit@example.com + username: genius_grapefruit +apricot: + provider: github + uid: 999888 + email: happy_apricot@example.com + username: happy_apricot +mango: + provider: github + uid: 999888 + email: marvelous_mango@example.com + username: marvelous_mango +crabapple: + provider: github + uid: 999888 + email: crabby_crabapple@example.com + username: crabby_crabapple +# ######### +cherry: + provider: github + uid: 999888 + email: cheerful_cherry@example.com + username: cheerful_cherry +# ######### +pear: + provider: github + uid: 999888 + email: pleasing_pear@example.com + username: pleasing_pear +# ######### +watercress: + provider: github + uid: 999888 + email: willful_watercress@example.com + username: willful_watercress \ No newline at end of file diff --git a/test/helpers/.keep b/test/helpers/.keep new file mode 100644 index 0000000000..e69de29bb2 diff --git a/test/helpers/application_helper_test.rb b/test/helpers/application_helper_test.rb new file mode 100644 index 0000000000..5eb6d26dbf --- /dev/null +++ b/test/helpers/application_helper_test.rb @@ -0,0 +1,66 @@ +require "test_helper" + +describe ApplicationHelper do + include ApplicationHelper + + describe 'render_date' do + it "displays a date in a human-readable format" do + date = Date.parse("october 20 2019") + + result = render_date(date) + + expect(result).must_equal "Oct 20, 2019" + end + end + + describe 'render_price' do + it "displays a price with two digits after the decimal" do + price = 57.599999999999994 + + result = render_price(price) + + expect(result).must_equal "57.59" + end + + it "displays 0.00 for 0" do + price = 0 + + result = render_price(price) + + expect(result).must_equal "0.00" + end + end + + describe "render_rating" do + it "displays a rating of 5 as 5 filled stars" do + rating = 5 + result = render_rating(rating) + expect(result).must_equal '' + end + + it "displays a rating of 3 as 3 filled stars and 2 empty" do + rating = 3 + result = render_rating(rating) + expect(result).must_equal '' + end + + it "displays a rating of 1 as 1 filled star and 4 empty" do + rating = 1 + result = render_rating(rating) + # assert_dom_equal(%{}, result) + expect(result).must_equal '' + end + + it "returns 'no rating' if the rating is nil" do + rating = nil + result = render_rating(rating) + expect(result).must_equal "no rating" + end + end +end + +# test "should return the user's full name" do +# user = users(:david) + +# assert_dom_equal %{David Heinemeier Hansson}, link_to_user(user) +# end \ No newline at end of file diff --git a/test/helpers/users_helper_test.rb b/test/helpers/users_helper_test.rb new file mode 100644 index 0000000000..79b85095cb --- /dev/null +++ b/test/helpers/users_helper_test.rb @@ -0,0 +1,22 @@ +require "test_helper" + +describe UsersHelper do + include UsersHelper + + describe 'mask_cc' do + let(:cc_num) { + "123456789123456789" + } + let(:masked) { + mask_cc(cc_num) + } + + it "returns a string of the same length" do + expect(masked.length).must_equal cc_num.length + end + + it "turns all chars except the last four into asterisks" do + expect(masked).must_equal "**************6789" + end + end +end \ No newline at end of file diff --git a/test/integration/.keep b/test/integration/.keep new file mode 100644 index 0000000000..e69de29bb2 diff --git a/test/mailers/.keep b/test/mailers/.keep new file mode 100644 index 0000000000..e69de29bb2 diff --git a/test/models/.keep b/test/models/.keep new file mode 100644 index 0000000000..e69de29bb2 diff --git a/test/models/category_test.rb b/test/models/category_test.rb new file mode 100644 index 0000000000..edcf81c81e --- /dev/null +++ b/test/models/category_test.rb @@ -0,0 +1,51 @@ +require "test_helper" + +describe Category do + describe 'relations' do + let(:full_sun) { categories(:full_sun)} + let(:shade) { categories(:shade) } + let(:begonia) { products(:begonia) } + let(:orchid) { products(:orchid) } + + it 'can have many products' do + full_sun.products << begonia + full_sun.products << orchid + + expect(full_sun.products.count).must_equal 2 + end + + it 'can belong to many products' do + full_sun.products << begonia + full_sun.products << orchid + + assert_not_nil(begonia.categories) + assert_not_nil(orchid.categories) + end + end + + describe 'validations' do + let(:full_sun) { categories(:full_sun) } + + it 'is valid when name is present' do + expect(full_sun.valid?).must_equal true + end + + it 'is invalid without a name' do + full_sun.name = nil + + expect(full_sun.valid?).must_equal false + end + + it 'is valid when the name is unique' do + expect(categories(:full_sun).valid?).must_equal true + end + + it 'is invalid when the name is not unique' do + existing_category = categories(:full_sun) + new_category = Category.create(name: "Full Sun") + + expect(new_category.valid?).must_equal false + expect(new_category.errors.messages).must_include :name + end + end +end diff --git a/test/models/order_item_test.rb b/test/models/order_item_test.rb new file mode 100644 index 0000000000..689b0c264d --- /dev/null +++ b/test/models/order_item_test.rb @@ -0,0 +1,54 @@ +require "test_helper" + +describe OrderItem do + describe 'relations' do + before do + @product = products(:begonia) + @order = orders(:myrta_order) + @order_item = OrderItem.new(quantity: 1, product_id: @product.id, order_id: @order.id) + end + + it 'an order_item belongs to a product' do + expect(@order_item.product_id).must_equal @product.id + end + + it 'an order_item belongs to an order' do + expect(@order_item.order_id).must_equal @order.id + end + end + + describe 'validations' do + let(:product) { products(:begonia) } + let(:order) { orders(:myrta_order) } + let(:order_item) { OrderItem.new(quantity: 1, product_id: product.id, order_id: order.id) } + + it 'is valid when a quantity of 1 or more is entered' do + # Default quantity is 1 + expect(order_item.valid?).must_equal true + + order_item.quantity = 2 + expect(order_item.valid?).must_equal true + end + + it 'is not valid when a quantity of less than 1 is entered' do + order_item.quantity = 0 + expect(order_item.valid?).must_equal false + + order_item.quantity = -1 + expect(order_item.valid?).must_equal false + end + + it 'is not valid with a quantity that is not an integer' do + order_item.quantity = "three" + expect(order_item.valid?).must_equal false + end + end + + describe 'subtotal' do + let(:order_item) { order_items(:bear_hollyhock) } + + it 'calcualtes the correct subtotal' do + expect(order_item.subtotal).must_equal 25.5 + end + end +end diff --git a/test/models/order_test.rb b/test/models/order_test.rb new file mode 100644 index 0000000000..43b63531e7 --- /dev/null +++ b/test/models/order_test.rb @@ -0,0 +1,133 @@ +require "test_helper" + +describe Order do + let (:order) { + Order.create + } + + let (:update_hash) { + { + name: "georgina", + address: "bellevue", + cc_num: "1111111111111111", + cvv_code: "111", + zip: "98003", + exp_date: "10/20", + email: "geo@fake.com" + } + } + + describe 'validations' do + it 'is valid when all fields are present' do + edit_order = order.update(update_hash) + expect(edit_order).must_equal true + end + + it "is not valid without an email" do + invalid_order = order.update(name: "georgina", address: "bellevue", cc_num: "1111111111111111", cvv_code: "111", zip: "98003", exp_date: "10/20") + expect(invalid_order).must_equal false + expect(order.errors.full_messages.to_sentence).must_include "Email" + end + + it "is not valid without an address" do + invalid_order = order.update(email: "geob@gmail.com", name: "georgina", cc_num: "1111111111111111", cvv_code: "111", zip: "98003", exp_date: "10/20") + expect(invalid_order).must_equal false + expect(order.errors.full_messages.to_sentence).must_include "Address" + end + + it "is not valid without an cc_num" do + invalid_order = order.update(email: "geob@gmail.com", name: "georgina", address: "bellevue", cvv_code: "111", zip: "98003", exp_date: "10/20") + expect(invalid_order).must_equal false + expect(order.errors.full_messages.to_sentence).must_include "Cc num" + end + + it "is not valid without an cvv_code" do + invalid_order = order.update(email: "geob@gmail.com", name: "georgina", cc_num: "1111111111111111", address: "bellevue", zip: "98003", exp_date: "10/20") + expect(invalid_order).must_equal false + expect(order.errors.full_messages.to_sentence).must_include "Cvv code" + end + + it "is not valid without an zip" do + invalid_order = order.update(email: "geob@gmail.com", name: "georgina", address: "bellevue", cvv_code: "111", cc_num: "1111111111111111", exp_date: "10/20") + expect(invalid_order).must_equal false + expect(order.errors.full_messages.to_sentence).must_include "Zip" + end + + it "is not valid without an email" do + update_hash[:email] = nil + + invalid_order = order.update(update_hash) + expect(invalid_order).must_equal false + expect(order.errors.full_messages.to_sentence).must_include "Email" + end + + it "is not valid without an exp_date" do + invalid_order = order.update(email: "geob@gmail.com", name: "georgina", address: "bellevue", cc_num: "1111111111111111", cvv_code: "111", zip: "98003") + expect(invalid_order).must_equal false + expect(order.errors.full_messages.to_sentence).must_include "Exp date" + end + end + + describe "relationships" do + it "has many order_items" do + # Arrange + user = User.create(username: "georgina", email: "geor@gmail.com") + product_cactus = Product.create(user_id: user.id, name: "cactus", description: "cool product", price: 1.9, photo_url: "url", stock: 3) + product_flower = Product.create(user_id: user.id, name: "flower", description: "cool flower", price: 1.5, photo_url: "url", stock: 3) + new_order = Order.create(address: "x", name: "x", cc_num: "x", cvv_code: "x", zip: "x", email: "blank@blank.com", exp_date: "10/20") + order_items_1 = OrderItem.create(product_id: product_cactus.id, order_id: new_order.id, quantity: 3) + order_items_2 = OrderItem.create(product_id: product_flower.id, order_id: new_order.id, quantity: 1) + + expect(new_order.order_items.count).must_be :>, 0 + new_order.order_items.each do |order| + expect(order).must_be_instance_of OrderItem + end + end + end + + describe 'custom methods' do + describe 'total' do + let(:order) { orders(:bear_orchid_hollyhock)} + + it "calculates the correct total for an order" do + expect(order.total).must_equal 63.75 + end + end + + describe 'update_stock' do + # let(:order) { orders(:bear_orchid_hollyhock)} + it 'decreases the stock for a particular item' do + product = products(:begonia) + expect(product.stock).must_equal 200 + + order = Order.create! + order_item = OrderItem.create!(product_id: product.id, order_id: order.id, quantity: 10) + + order.update_stock + + product.reload + expect(product.stock).must_equal 190 + + end + end + + describe "count_items" do + it "can total the number of order-items in the order" do + order = orders(:bear_orchid_hollyhock) + # this order has two order-items + + count = order.count_items() + + expect(count).must_equal 2 + end + + it "returns zero if the order is empty" do + order = Order.create() + + count = order.count_items() + + expect(count).must_equal 0 + end + end + end +end diff --git a/test/models/product_test.rb b/test/models/product_test.rb new file mode 100644 index 0000000000..5cd72ef659 --- /dev/null +++ b/test/models/product_test.rb @@ -0,0 +1,227 @@ +require "test_helper" + +describe Product do + describe "validations" do + before do + @user = User.create(username: "test user", email: "test_email@example.com") + @product = Product.create(user_id: @user.id, name: "test product", description: "cool product", price: 1.9, photo_url: "url", stock: 3) + end + + it "is valid when all fields are present" do + result = @product.valid? + expect(result).must_equal true + end + + it "is invalid without a name" do + @product.name = nil + result = @product.valid? + expect(result).must_equal false + end + + it "is invalid if name is not unique" do + @product.name = products(:orchid).name + expect(@product.valid?).must_equal false + expect(@product.errors.messages).must_include :name + end + + it "is invalid without a description" do + @product.description = nil + result = @product.valid? + expect(result).must_equal false + end + + it "is invalid without a price" do + @product.price = nil + result = @product.valid? + expect(result).must_equal false + end + + it "is invalid if price is not a number" do + @product.price = "nine" + result = @product.valid? + expect(result).must_equal false + end + + it "is invalid if price is not greater than 0" do + @product.price = 0 + result = @product.valid? + expect(result).must_equal false + end + + it "is invalid wihout a photo url" do + @product.photo_url = nil + result = @product.valid? + expect(result).must_equal false + end + + it "is invalid without stock quantity" do + @product.stock= nil + result = @product.valid? + expect(result).must_equal false + end + + it "is invalid without if stock quantity is not a number" do + @product.stock = "eleven" + result = @product.valid? + expect(result).must_equal false + end + + it "is invalid without availability status" do + @product.available = nil + result = @product.valid? + expect(result).must_equal false + end + + it "is invalid without a user id" do + @product.user_id = nil + result = @product.valid? + expect(result).must_equal false + end + end + + describe "relationships" do + before do + @user = User.create(username: "test user", email: "test-email@example.com") + @category1 = Category.create(name: "flower") + @category2 = Category.create(name: "specialty") + @product = Product.create(user_id: @user.id, name: "test product", description: "cool product", price: 1.9, photo_url: "url", stock: 3, categories: [@category1, @category2]) + + @review1 = Review.create(product_id: @product.id, rating: 5, comment: "great product") + @review2 = Review.create(product_id: @product.id, rating: 2, comment: "bad product") + + @order = Order.create(email: "testemail@example.com", address: "test address", name: "test user name", cc_num: 1234, zip: 98111, cvv_code: 123) + + @order_item1 = OrderItem.create(product_id: @product.id, order_id: @order.id, quantity: 2) + @order_item2 = OrderItem.create(product_id: @product.id, order_id: @order.id, quantity: 4) + end + + it "can have many reviews" do + expect(@product.reviews.count).must_equal 2 + end + + it "can have many order items" do + expect(@product.order_items.count).must_equal 2 + end + + it "can have many categories" do + expect(@product.categories.count).must_equal 2 + end + + it "belongs to a user" do + assert_not_nil(@product.user_id) + end + end + + describe "calculate average rating" do + it "returns an integer average rating from reviews" do + product = products(:bellflower) + # has two reviews, with a rating of 1 and 5, respectively + + average = product.calculate_average_rating() + + expect(average).must_equal 3 + end + + it "wont return a float average rating" do + product = products(:hollyhock) + # has two reviews, with a rating of 4 and 5, respectively + + average = product.calculate_average_rating() + + # it should round down from 4.5 to 5 + expect(average).must_equal 4 + end + + it "returns nil if there are no reviews" do + product = products(:treeivy) + # there are no reviews on treeivy + + average = product.calculate_average_rating() + + expect(average).must_be_nil + end + end + + describe "sample_products_for_homepage" do + it "can get a list of products from the database" do + result = Product.sample_products_for_homepage() + + expect(result).wont_be_nil + + result.each do |item| + expect(item).must_be_instance_of Product + end + + expect(result.length).must_equal 5 + end + + it "won't return an unavailable product and won't return more than five" do + all_yml_order_items = OrderItem.all + all_yml_order_items.each do |oi| + oi.delete() + end + + all_yml_reviews = Review.all + all_yml_reviews.each do |review| + review.delete() + end + + all_yml_products = Product.all + all_yml_products.each do |product| + product.delete() + end + + user = users(:cherry) + + available_product_1 = Product.create(name: "plant 1", description: "a cool plant", price: 12.00, photo_url: "https://lorempixel.com/300/300", stock: 5, available: true, user_id: user.id) + available_product_2 = Product.create(name: "plant 2", description: "a cool plant", price: 12.00, photo_url: "https://lorempixel.com/300/300", stock: 5, available: true, user_id: user.id) + available_product_3 = Product.create(name: "plant 3", description: "a cool plant", price: 12.00, photo_url: "https://lorempixel.com/300/300", stock: 5, available: true, user_id: user.id) + unavailable_product = Product.create(name: "plant unavailable", description: "a cool plant", price: 12.00, photo_url: "https://lorempixel.com/300/300", stock: 5, available: false, user_id: user.id) + + sample_list = Product.sample_products_for_homepage() + + expect(sample_list).wont_include unavailable_product + expect(sample_list).must_include available_product_1 + expect(sample_list).must_include available_product_2 + expect(sample_list).must_include available_product_3 + + available_product_4 = Product.create(name: "plant 4", description: "a cool plant", price: 12.00, photo_url: "https://lorempixel.com/300/300", stock: 5, available: true, user_id: user.id) + available_product_5 = Product.create(name: "plant 5", description: "a cool plant", price: 12.00, photo_url: "https://lorempixel.com/300/300", stock: 5, available: true, user_id: user.id) + available_product_6 = Product.create(name: "plant 6", description: "a cool plant", price: 12.00, photo_url: "https://lorempixel.com/300/300", stock: 5, available: true, user_id: user.id) + + sample_list = Product.sample_products_for_homepage() + expect(sample_list.length).must_equal 5 + end + end + + describe "count_sold" do + it "will return an integer of items sold" do + product = products(:snakeplant) + # snakeplant has one complete order + + count = product.count_sold() + + expect(count).must_equal 8 + end + + it "will only count paid and completed orders" do + product = products(:aloe) + # aloe has four orders, + # one paid, one completed, one cancelled, and one pending + # paid and complete have a quantity of 2 and 2 + # cancelled and pending have a quantity of 3 and 3 + + count = product.count_sold() + + expect(count).must_equal 4 + end + + it "will return zero if there are none sold" do + product = products(:knautia) + + count = product.count_sold() + + expect(count).must_equal 0 + end + end +end diff --git a/test/models/review_test.rb b/test/models/review_test.rb new file mode 100644 index 0000000000..1be7a7969d --- /dev/null +++ b/test/models/review_test.rb @@ -0,0 +1,57 @@ +require "test_helper" + +describe Review do + describe 'relations' do + before do + @product = products(:begonia) + @review = Review.create!(rating: 4, comment: "I love the pretty flowers!", product_id: @product.id) + end + + it 'belongs to a product' do + expect(@review.product_id).must_equal @product.id + end + end + + describe 'validations' do + let(:product) { products(:begonia) } + let(:review) { Review.create!(rating: 4, comment: "I love the pretty flowers!", product_id: product.id) } + + it 'is invalid without a product_id' do + review.product_id = nil + expect(review.valid?).must_equal false + end + + it 'is valid when there is a rating between 1 and 5 entered' do + expect(review.valid?).must_equal true + + review.rating = 1 + expect(review.valid?).must_equal true + + review.rating = 5 + expect(review.valid?).must_equal true + end + + it 'is not valid with a rating that is not between 1 and 5' do + review.rating = 0 + expect(review.valid?).must_equal false + + review.rating = 6 + expect(review.valid?).must_equal false + end + + it 'is not valid when rating is nil' do + review.rating = nil + expect(review.valid?).must_equal false + end + + it 'is not valid when rating is not an integer' do + review.rating = "three" + expect(review.valid?).must_equal false + end + + it 'is still valid without a comment' do + review.comment = nil + expect(review.valid?).must_equal true + end + end +end diff --git a/test/models/user_test.rb b/test/models/user_test.rb new file mode 100644 index 0000000000..a89fe7a706 --- /dev/null +++ b/test/models/user_test.rb @@ -0,0 +1,768 @@ +require "test_helper" + +describe User do + describe "relationships" do + let(:merchant) { + User.create(username: "Begonia", email: "b_begonia@example.com") + } + let(:photo_url) { + "https://example_photo.com" + } + + it "can have a single product" do + merchant_id = merchant.id + description = "a small fern" + + small_fern = Product.create(name: "small fern", description: description, price: 5.25, stock: 3, user_id: merchant_id, photo_url: photo_url) + saved_product = Product.find_by(description: description) + + expect(merchant.products).must_include saved_product + end + + it "can have multiple products" do + merchant_id = merchant.id + fern_description = "a small fern" + cactus_description = "a large cactus" + + small_fern = Product.create(name: "small fern", description: fern_description, price: 5.25, stock: 3, user_id: merchant_id, photo_url: photo_url) + large_cactus = Product.create(name: "large cactus", description: cactus_description, price: 5.25, stock: 3, user_id: merchant_id, photo_url: photo_url) + + saved_fern = Product.find_by(description: fern_description) + saved_cactus = Product.find_by(description: cactus_description) + + expect(merchant.products).must_include saved_fern + expect(merchant.products).must_include saved_cactus + end + end + + describe "validations" do + let(:username) { + "Begonia" + } + + let(:email) { + "b_begonia@example.com" + } + + let(:merchant) { + User.new(username: username, email: email) + } + + it "is valid with a username and email" do + expect(merchant.valid?).must_equal true + end + + it "can be created with a username and email" do + merchant.save! + saved_merchant = User.find_by(username: username) + + expect(saved_merchant).wont_be_nil + expect(saved_merchant.username).must_equal username + expect(saved_merchant.email).must_equal email + end + + it "is not valid without a username" do + merchant = User.new(email: email) + expect(merchant.valid?).must_equal false + expect(merchant.errors.messages).must_include :username + end + + it "is not valid without an email" do + merchant = User.new(username: username) + expect(merchant.valid?).must_equal false + expect(merchant.errors.messages).must_include :email + end + + it "is not valid without a unique username" do + merchant.save! + + new_merchant = User.new(username: username, email: "o_orchid@example.com") + + expect(new_merchant.valid?).must_equal false + expect(new_merchant.errors.messages).must_include :username + end + + it "is not valid without a unique email" do + merchant.save! + + new_merchant = User.new(username: "Orchid", email: email) + + expect(new_merchant.valid?).must_equal false + expect(new_merchant.errors.messages).must_include :email + end + + describe "email validations" do + # email validation cases from https://en.wikipedia.org/wiki/Email_address + + it "is valid with a hyphen" do + email = "local-part@domain.com" + merchant = User.new(username: username, email: email) + + expect(merchant.valid?).must_equal true + end + + it "is valid with a period" do + email = "very.common@example.com" + merchant = User.new(username: username, email: email) + + expect(merchant.valid?).must_equal true + end + + it "is valid with periods and a plus sign" do + email = "disposable.style.email.with+symbol@example.com" + merchant = User.new(username: username, email: email) + + expect(merchant.valid?).must_equal true + end + + it "is valid with a period and hyphens" do + email = "other.email-with-hyphen@example.com" + merchant = User.new(username: username, email: email) + + expect(merchant.valid?).must_equal true + end + + it "is valid with a single character" do + email = "x@example.com" + merchant = User.new(username: username, email: email) + + expect(merchant.valid?).must_equal true + end + + it "is valid with a hyphen in domain" do + email = "example-indeed@strange-example.com" + merchant = User.new(username: username, email: email) + + expect(merchant.valid?).must_equal true + end + + it "is valid with a period in domain" do + email = "example@s.example" + merchant = User.new(username: username, email: email) + + expect(merchant.valid?).must_equal true + end + + it "is valid with a bang" do + email = "mailhost!username@example.org" + merchant = User.new(username: username, email: email) + + expect(merchant.valid?).must_equal true + end + + it "is valid with a percent" do + email = "user%example.com@example.org" + merchant = User.new(username: username, email: email) + + expect(merchant.valid?).must_equal true + end + + it "is invalid without an @ sign" do + invalid = "Abc.example.com" + merchant = User.new(username: username, email: invalid) + + expect(merchant.valid?).must_equal false + expect(merchant.errors.messages).must_include :email + end + + it "is invalid if it has multiple @ signs" do + invalid = "A@b@c@example.com" + merchant = User.new(username: username, email: invalid) + + expect(merchant.valid?).must_equal false + expect(merchant.errors.messages).must_include :email + end + + it "is invalid if it has special characters" do + invalid = "a\"b(c)d,e:f;gi[j\k]l@example.com" + merchant = User.new(username: username, email: invalid) + + expect(merchant.valid?).must_equal false + expect(merchant.errors.messages).must_include :email + end + + it "is invalid if it contains quoted strings" do + invalid = "just\"not\"right@example.com" + merchant = User.new(username: username, email: invalid) + + expect(merchant.valid?).must_equal false + expect(merchant.errors.messages).must_include :email + end + + it "is invalid if it contains special characters" do + invalid = "this\ still\"not\\allowed@example.com" + merchant = User.new(username: username, email: invalid) + + expect(merchant.valid?).must_equal false + expect(merchant.errors.messages).must_include :email + end + end + end + + describe "list" do + let(:list) { + User.list + } + it "returns a list of all users" do + expect(list.length).must_equal User.count + + list.each do |item| + expect(item).must_be_instance_of User + end + end + + it "returns an alphabetized list" do + # relies on "awesome_orchid" being + # the alphabetical first name in test database + first_name = users(:orchid) + + expect(list.first).must_equal first_name + end + end + + describe "order count" do + it "returns count of orders containing this user's product" do + user = users(:orchid) + # orchid has two products + # for product 1, there is one order of one quantity + # for product 2, there is one order of two quantity + + order_count = user.order_count + + expect(order_count).must_equal 2 + end + + it "returns zero if the user has no products" do + user = users(:petunia) + # petunia has no products + + order_count = user.order_count + + expect(order_count).must_equal 0 + end + + it "returns zero if there are no associated orders" do + user = users(:rose) + # rose has one product + # it does not have any orders + + order_count = user.order_count + + expect(order_count).must_equal 0 + end + end + + describe "find_orders" do + it "returns a list of orders for a given merchant" do + user = users(:orchid) + + # there are two orders that contain orchid's products + + # order's for orchid's products: + # ducky_orchid_bellflower + # bear_orchid_hollyhock + + # each has one of orchid's order-item: + # ducky_bellflower: + # quantity: 1 + # bear_hollyhock: + # quantity: 2 + + # one order also has one of begonia's products + # bear_orchid_hollyhock + # bear_treeivy: + # quantity: 3 + + orders = user.find_orders + + expect(orders).wont_be_nil + expect(orders.length).must_equal 2 + + first_order = orders.first + expect(first_order.order_items).wont_be_nil + # begonia's product should not be filtered out + # the view will filter what the merchant should see + expect(first_order.order_items.length).must_equal 2 + + last_order = orders.last + expect(last_order.order_items).wont_be_nil + expect(last_order.order_items.length).must_equal 1 + end + + it "returns an empty list if there are no orders" do + user = users(:rose) + + # rose has one product with no orders + + orders = user.find_orders + + expect(orders).wont_be_nil + expect(orders.empty?).must_equal true + end + + it "returns an empty list if there are no products" do + user = users(:petunia) + + # petunia has no products + + orders = user.find_orders + + expect(orders).wont_be_nil + expect(orders.empty?).must_equal true + end + end + + describe "top_product" do + it "can find a users's top-selling product" do + user = users(:orchid) + # orchid has two orders + # one with one bellflower + # and one with two hollyhock + top = products(:hollyhock) + + top_product = user.top_product + + expect(top_product).must_equal top + end + + it "returns nil if the user has no products" do + user = users(:petunia) + # petunia has no products + + top_product = user.top_product + + expect(top_product).must_be_nil + end + + it "returns nil if the user hasn't sold any products" do + # rose has one product with no orders + user = users(:rose) + + top_product = user.top_product + + expect(top_product).must_be_nil + end + + it "returns nil if the user has no paid/completed orders" do + # watercress has one product with one pending order-item + user = users(:watercress) + + top_product = user.top_product + + expect(top_product).must_be_nil + end + end + + describe "total_revenue_by_order" do + it "calculates the user's total revenue for a given order" do + # orchid has two orders + user = users(:orchid) + + order_1_id = orders(:ducky_orchid_bellflower).id + order_2_id = orders(:bear_orchid_hollyhock).id + + # ducky_bellflower: + # quantity: 1 + # product: bellflower + # status: paid + # => total: 12.75 + # bear_hollyhock: + # quantity: 2 + # product: hollyhock + # status: complete + # => total: 25.5 + + result_1 = user.total_revenue_by_order(order_1_id) + expect(result_1).must_equal 12.75 + + result_2 = user.total_revenue_by_order(order_2_id) + expect(result_2).must_equal 25.5 + end + end + + describe "total revenue" do + it "calculates the user's total revenue" do + # orchid has two orders + user = users(:orchid) + + # hollyhock: + # price: 12.75 + # bellflower: + # price: 12.75 + + # ducky_bellflower: + # quantity: 1 + # product: bellflower + # status: paid + # => total: 12.75 + # bear_hollyhock: + # quantity: 2 + # product: hollyhock + # status: complete + # => total: 25.5 + + result = user.total_revenue() + + expect(result).must_equal 38.25 + end + + it "returns zero if there are no orders" do + # rose has one product with no orders + user = users(:rose) + + result = user.total_revenue() + + expect(result).must_equal 0.00 + end + + it "returns zero if there are no products" do + # petunia has no products + user = users(:petunia) + + result = user.total_revenue() + + expect(result).must_equal 0.00 + end + end + + describe "total revenue by status" do + it "calculates the user's total revenue for their orders per status" do + # orchid has two orders + user = users(:orchid) + + # hollyhock: + # price: 12.75 + # bellflower: + # price: 12.75 + + # ducky_bellflower: + # quantity: 1 + # product: bellflower + # status: paid + # => total: 12.75 + # bear_hollyhock: + # quantity: 2 + # product: hollyhock + # status: complete + # => total: 25.5 + + complete_result = user.total_revenue_by_status(:complete) + expect(complete_result).must_equal 25.5 + + paid_result = user.total_revenue_by_status(:paid) + expect(paid_result).must_equal 12.75 + end + + it "calculates the user's total revenue for their orders per status" do + # crabapple has one order with two order_items + user = users(:crabapple) + + # one order_item is complete + # one is only paid + + # the order is not complete, so no order_item, + # regardless of its individual status, + # should count toward this total + complete_result = user.total_revenue_by_status(:complete) + expect(complete_result).must_equal 0.00 + + # the order is paid, so each order_item, + # regardless of its individual status, + # should count toward this total + paid_result = user.total_revenue_by_status(:paid) + expect(paid_result).must_equal 35.00 + end + + it "returns 0.00 for any nonexistent statuses" do + # crabapple has one order with two order_items + user = users(:crabapple) + + # one order_item is complete + # one is only paid + + complete_result = user.total_revenue_by_status(:pending) + expect(complete_result).must_equal 0.00 + + complete_result = user.total_revenue_by_status(:cancelled) + expect(complete_result).must_equal 0.00 + end + end + + describe "sort orders by status" do + # if a user has no orders + it "returns empty if there are no orders" do + # rose has one product with no orders + user = users(:rose) + + response = user.sort_orders_by_status() + + expect(response).wont_be_nil + expect(response.empty?).must_equal true + end + + # if a user has no products + it "returns empty if there are no products" do + # petunia has no products + user = users(:petunia) + + response = user.sort_orders_by_status() + + expect(response).wont_be_nil + expect(response.empty?).must_equal true + end + + # if a user has one order, all their order_items, and they are all paid (order should be paid) + # => {paid: [order]}, guava_shop_order + it "is paid if all the order items are paid" do + user = users(:guava) + response = user.sort_orders_by_status() + + expect(response[:paid]).wont_be_nil + expect(response[:paid]).must_include orders(:guava_shop_order) + end + + # if a user has one order, all their order_items, and they are all complete but one is paid (order should be paid) + # => {paid: [order]}, pineapple_shop_order + # WRONG, pending + it "is paid if one order item is complete and one is paid" do + user = users(:pineapple) + response = user.sort_orders_by_status() + + expect(response[:paid]).wont_be_nil + expect(response[:paid]).must_include orders(:pineapple_shop_order) + end + + # if a user has one order, all their order_items, and they are all complete but one is cancelled (order should be complete) + # => {complete: [order]}, orange_shop_order + # WRONG, pending + it "is complete if one order item is complete and one is cancelled" do + user = users(:orange) + response = user.sort_orders_by_status() + + expect(response[:complete]).wont_be_nil + expect(response[:complete]).must_include orders(:orange_shop_order) + end + + # if a user has one order, all their order_items, and they are all complete (order should be complete) + # => {complete: [order]}, plum_shop_order + it "is complete if all the order items are complete" do + user = users(:plum) + response = user.sort_orders_by_status() + + expect(response[:complete]).wont_be_nil + expect(response[:complete]).must_include orders(:plum_shop_order) + end + + # if a user has one order, half their order_items, and they are all paid & other half is complete (order should be paid) + # => {paid: [order]}, peach_shop_order + it "is paid if all this users's order items are paid" do + user = users(:peach) + response = user.sort_orders_by_status() + + expect(response[:paid]).wont_be_nil + expect(response[:paid]).must_include orders(:peach_shop_order) + end + + # if a user has one order, half their order_items, and they are all complete but one is paid & other half is paid (order should be paid) + # => {paid: [order]}, carrot_shop_order + # WRONG, pending + it "is paid if one of this users's order items is complete and one is paid" do + user = users(:carrot) + response = user.sort_orders_by_status() + + expect(response[:paid]).wont_be_nil + expect(response[:paid]).must_include orders(:carrot_shop_order) + end + + # if a user has one order, half their order_items, and they are all complete but one is cancelled & other half is paid (order should be complete) + # => {complete: [order]}, berry_shop_order + # WRONG, pending + it "is paid if one of this users's order items is complete and one is cancelled" do + user = users(:berry) + response = user.sort_orders_by_status() + + expect(response[:complete]).wont_be_nil + expect(response[:complete]).must_include orders(:berry_shop_order) + end + + # if a user has one order, half their order_items, and they are all complete & other half is paid (order should be complete) + # => {complete: [order]}, melon_shop_order + it "is paid if all this users's order items are complete" do + user = users(:melon) + response = user.sort_orders_by_status() + + expect(response[:complete]).wont_be_nil + expect(response[:complete]).must_include orders(:melon_shop_order) + end + + # if a user has one order, half their order_items, and they are all cancelled & other half is paid (order should be cancelled) + # => {cancelled: [order]}, grapefruit_shop_order + it "is cancelled if all this users's order items are cancelled" do + user = users(:grapefruit) + response = user.sort_orders_by_status() + + expect(response[:cancelled]).wont_be_nil + expect(response[:cancelled]).must_include orders(:grapefruit_shop_order) + end + + # if a user has one order, half their order_items, and they are all pending & other half is paid (order should be pending) + # => {pending: [order]}, apricot_shop_order + it "is pending if all this users's order items are pending" do + user = users(:apricot) + response = user.sort_orders_by_status() + + expect(response[:pending]).wont_be_nil + expect(response[:pending]).must_include orders(:apricot_shop_order) + end + end + + describe "get order status" do + # if a user has one order, all their order_items, and they are all paid (order should be paid) + # => {paid: [order]}, guava_shop_order + it "is paid if all the order items are paid" do + user = users(:guava) + response = user.get_order_status(orders(:guava_shop_order)) + + expect(response).must_equal :paid + end + + # if a user has one order, all their order_items, and they are all complete but one is paid (order should be paid) + # => {paid: [order]}, pineapple_shop_order + it "is paid if one order item is complete and one is paid" do + user = users(:pineapple) + response = user.get_order_status(orders(:pineapple_shop_order)) + + expect(response).must_equal :paid + end + + # if a user has one order, all their order_items, and they are all complete but one is cancelled (order should be complete) + # => {complete: [order]}, orange_shop_order + it "is complete if one order item is complete and one is cancelled" do + user = users(:orange) + response = user.get_order_status(orders(:orange_shop_order)) + + expect(response).must_equal :complete + end + + # if a user has one order, all their order_items, and they are all complete (order should be complete) + # => {complete: [order]}, plum_shop_order + it "is complete if all the order items are complete" do + user = users(:plum) + response = user.get_order_status(orders(:plum_shop_order)) + + expect(response).must_equal :complete + end + + # if a user has one order, half their order_items, and they are all paid & other half is complete (order should be paid) + # => {paid: [order]}, peach_shop_order + it "is paid if all this users's order items are paid" do + user = users(:peach) + response = user.get_order_status(orders(:peach_shop_order)) + + expect(response).must_equal :paid + end + + # if a user has one order, half their order_items, and they are all complete but one is paid & other half is paid (order should be paid) + # => {paid: [order]}, carrot_shop_order + it "is paid if one of this users's order items is complete and one is paid" do + user = users(:carrot) + response = user.get_order_status(orders(:carrot_shop_order)) + + expect(response).must_equal :paid + end + + # if a user has one order, half their order_items, and they are all complete but one is cancelled & other half is paid (order should be complete) + # => {complete: [order]}, berry_shop_order + it "is paid if one of this users's order items is complete and one is cancelled" do + user = users(:berry) + response = user.get_order_status(orders(:berry_shop_order)) + + expect(response).must_equal :complete + end + + # if a user has one order, half their order_items, and they are all complete & other half is paid (order should be complete) + # => {complete: [order]}, melon_shop_order + it "is paid if all this users's order items are complete" do + user = users(:melon) + response = user.get_order_status(orders(:melon_shop_order)) + + expect(response).must_equal :complete + end + + # if a user has one order, half their order_items, and they are all cancelled & other half is paid (order should be cancelled) + # => {cancelled: [order]}, grapefruit_shop_order + it "is cancelled if all this users's order items are cancelled" do + user = users(:grapefruit) + response = user.get_order_status(orders(:grapefruit_shop_order)) + + expect(response).must_equal :cancelled + end + + # if a user has one order, half their order_items, and they are all pending & other half is paid (order should be pending) + # => {pending: [order]}, apricot_shop_order + it "is pending if all this users's order items are pending" do + user = users(:apricot) + response = user.get_order_status(orders(:apricot_shop_order)) + + expect(response).must_equal :pending + end + end + + describe "find orders by status" do + let(:user) { + users(:mango) + } + + # if a user has six orders, + # and two are complete, one is cancelled, two are paid, one is pending, + # they should be able to see a list of all of them + it "returns any complete orders" do + response = user.find_orders_by_status(:complete) + + expect(response).wont_be_nil + expect(response.length).must_equal 2 + expect(response).must_include orders(:mango_shop_complete_1) + expect(response).must_include orders(:mango_shop_complete_2) + end + + it "returns any cancelled orders" do + response = user.find_orders_by_status(:cancelled) + + expect(response).wont_be_nil + expect(response.length).must_equal 1 + expect(response).must_include orders(:mango_shop_cancelled) + end + + it "returns any paid orders" do + response = user.find_orders_by_status(:paid) + + expect(response).wont_be_nil + expect(response.length).must_equal 2 + expect(response).must_include orders(:mango_shop_paid_1) + expect(response).must_include orders(:mango_shop_paid_2) + end + + it "returns any pending orders" do + response = user.find_orders_by_status(:pending) + + expect(response).wont_be_nil + expect(response.length).must_equal 1 + expect(response).must_include orders(:mango_shop_pending) + end + + it "returns all orders if you pass in all" do + response = user.find_orders_by_status(:all) + + expect(response).wont_be_nil + expect(response.length).must_equal 6 + expect(response).must_include orders(:mango_shop_complete_1) + expect(response).must_include orders(:mango_shop_complete_2) + expect(response).must_include orders(:mango_shop_cancelled) + expect(response).must_include orders(:mango_shop_paid_1) + expect(response).must_include orders(:mango_shop_paid_2) + expect(response).must_include orders(:mango_shop_pending) + end + + end + +end diff --git a/test/system/.keep b/test/system/.keep new file mode 100644 index 0000000000..e69de29bb2 diff --git a/test/test_helper.rb b/test/test_helper.rb new file mode 100644 index 0000000000..b39a8101bd --- /dev/null +++ b/test/test_helper.rb @@ -0,0 +1,47 @@ +require 'simplecov' +SimpleCov.start do + add_filter 'test/' +end + +ENV['RAILS_ENV'] ||= 'test' +require_relative '../config/environment' +require 'rails/test_help' + +require 'minitest/rails' +require 'minitest/autorun' +require 'minitest/reporters' + +Minitest::Reporters.use! Minitest::Reporters::SpecReporter.new + +class ActiveSupport::TestCase + # Setup all fixtures in test/fixtures/*.yml for all tests in alphabetical order. + fixtures :all + + # Add more helper methods to be used by all tests here... + def setup + # Once you have enabled test mode, all requests + # to OmniAuth will be short circuited to use the mock authentication hash. + # A request to /auth/provider will redirect immediately to /auth/provider/callback. + OmniAuth.config.test_mode = true + end + + def mock_auth_hash(user) + return { + provider: user.provider, + uid: user.uid, + info: { + email: user.email, + nickname: user.username + } + } + end + + def perform_login(user = nil) + user ||= User.first + + OmniAuth.config.mock_auth[:github] = OmniAuth::AuthHash.new(mock_auth_hash(user)) + get callback_path(:github) + + return user + end +end diff --git a/tmp/.keep b/tmp/.keep new file mode 100644 index 0000000000..e69de29bb2 diff --git a/vendor/.keep b/vendor/.keep new file mode 100644 index 0000000000..e69de29bb2