diff --git a/.gitignore b/.gitignore new file mode 100644 index 0000000000..0deead5ef5 --- /dev/null +++ b/.gitignore @@ -0,0 +1,33 @@ +# 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 + +# 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 +.env + +# Ignore simplecov and test data in simplecov report +/coverage.data +/coverage +.DS_Store 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/.vscode/settings.json b/.vscode/settings.json new file mode 100644 index 0000000000..9e63e70089 --- /dev/null +++ b/.vscode/settings.json @@ -0,0 +1,17 @@ +{ + "workbench.colorCustomizations": { + "activityBar.background": "#760c5f", + "activityBar.foreground": "#e7e7e7", + "activityBar.inactiveForeground": "#e7e7e799", + "activityBarBadge.background": "#74910f", + "activityBarBadge.foreground": "#e7e7e7", + "titleBar.activeBackground": "#48073a", + "titleBar.inactiveBackground": "#48073a99", + "titleBar.activeForeground": "#e7e7e7", + "titleBar.inactiveForeground": "#e7e7e799", + "statusBar.background": "#48073a", + "statusBarItem.hoverBackground": "#760c5f", + "statusBar.foreground": "#e7e7e7" + }, + "peacock.color": "#48073a" +} \ No newline at end of file diff --git a/Gemfile b/Gemfile new file mode 100644 index 0000000000..f2a7dca89d --- /dev/null +++ b/Gemfile @@ -0,0 +1,96 @@ +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] + gem 'pry-rails' + gem 'pry-byebug' +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' + gem 'dotenv-rails' +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' +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' +end + +group :test do + gem 'minitest-rails' + gem 'minitest-reporters' + gem 'simplecov', require: false +end + +gem "omniauth" +gem "omniauth-github" + + +gem 'bootstrap-multiselect-rails' diff --git a/Gemfile.lock b/Gemfile.lock new file mode 100644 index 0000000000..10c62e56f6 --- /dev/null +++ b/Gemfile.lock @@ -0,0 +1,326 @@ +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) + archive-zip (0.12.0) + io-like (~> 0.3.0) + arel (9.0.0) + autoprefixer-rails (9.6.5) + 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) + bootstrap-multiselect-rails (0.9.9) + rails (>= 4.0.0) + 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) + chromedriver-helper (2.1.1) + archive-zip (~> 0.10) + nokogiri (~> 1.8) + 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) + io-like (0.3.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-byebug (3.7.0) + byebug (~> 11.0) + pry (~> 0.10) + 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-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) + 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) + bootstrap-multiselect-rails + byebug + capybara (>= 2.15) + chromedriver-helper + 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-byebug + pry-rails + puma (~> 3.11) + rails (~> 5.2.3) + 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) + +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..36ee311c2d --- /dev/null +++ b/app/assets/javascripts/application.js @@ -0,0 +1,23 @@ +// 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 . + + +//= require bootstrap-multiselect \ No newline at end of file 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/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..4bc35ee9ae --- /dev/null +++ b/app/assets/stylesheets/application.scss @@ -0,0 +1,562 @@ +/* Custom bootstrap variables must be set or imported *before* bootstrap. */ +@import "bootstrap"; +/* Import scss content */ +@import "**/*"; + +.btn-pretty { + color: white; + background-color: #9D6AB9; +} + +.btn-pretty:hover { + color: white; + background-color: rgb(139, 57, 182); +} + +.btn-green { + background-color: rgb(94, 170, 95); + color: white; +} + +.btn-green:hover { + background-color: rgb(72, 135, 73); + color: white; +} + +nav { + font-family: 'Lato', sans-serif; +} + +.bg-merchant-nav { + background-color: rgb(94, 170, 95); +} + +.navbar-toggler-icon{ + background-image: url("data:image/svg+xml;charset=utf8,%3Csvg viewBox='0 0 32 32' xmlns='http://www.w3.org/2000/svg'%3E%3Cpath stroke='rgba(0,0,0, 0.5)' stroke-width='2' stroke-linecap='round' stroke-miterlimit='10' d='M4 8h24M4 16h24M4 24h24'/%3E%3C/svg%3E"); +} + +.top-brand-name { + font-family: 'Modak', cursive; + text-shadow: 0px 2px 3px #555; +} + +.top-brand-name a:hover { + color: rgb(254, 219, 105); +} + +p { + font-family: 'Lato', sans-serif; +} + +// navbar header on every page +.top-brand-name { + text-align: center; + font-size: 6rem; +} +.top-brand-name a, #dropdown-text { + color: white +} + +.all-nav-parts-container { + background-color: rgb(255, 172, 172); +} + +// login/logout and baskets +.login-loggout-container { + margin-top: 1%; + margin-right: 1.5%; +} + +.login-basket-nav { + display: flex; + justify-content: flex-end; + padding-top: 1%; + margin-right: 2%; + +} + +.logout-btn { + margin-top: 2% +} + +.basket-img { + max-width: 5vw; +} + +.cart-link { + margin-right: 1%; + background-color: transparent; +} + + +// main and footer on every page +main { + min-height: 100vh; + background-color: rgb(254, 219, 105); + font-family: 'Lato', sans-serif; +} + +footer { + text-align: center; + padding: 3%; + background-color: rgb(255, 172, 172); + color: white; +} + +.page-title { + padding: 1%; + background-color: rgb(94, 170, 95); + color: white; + margin-bottom: 1%; + border-radius: 15px; +} + +.page-container { + padding: 2%; +} + +// cards styling for products +.cards-container { + display: flex; + flex-wrap: wrap; + justify-content: space-evenly; + align-content: center; +} +.card { + display:flex; + justify-content:space-evenly; + padding: 1em; + margin-top: 3%; + margin: 1%; + position: relative; + text-align: center; + border: solid 10px #9D6AB9; + box-shadow: 4px 8px rgba(136, 136, 136, 0.5); +} + +.quick-add-btn { + position: absolute; + top: 5px; + right: 5px; +} + +.card-img-top { + max-height: 300px; + max-width: 300px; +} + +// Fruit Links Header +.fruit-img { + max-width: 7vw; +} + +.nav-fruit-img { + max-width: 2em; + margin-right: 1% +} + +.fruit-shape-links { + display: flex; + justify-content: space-evenly; + background-color: rgba(255, 255, 255, 0.8); +} + +.fruit-img:hover, .basket-img:hover { + /* Start the shake animation and make the animation last for 0.5 seconds */ + animation: shake 0.5s; + + /* When the animation is finished, start again */ + animation-iteration-count: infinite; +} + +@keyframes shake { + 0% { transform: translate(1px, 1px) rotate(0deg); } + 10% { transform: translate(-1px, -2px) rotate(-1deg); } + 20% { transform: translate(-3px, 0px) rotate(1deg); } + 30% { transform: translate(3px, 2px) rotate(0deg); } + 40% { transform: translate(1px, -1px) rotate(1deg); } + 50% { transform: translate(-1px, 2px) rotate(-1deg); } + 60% { transform: translate(-3px, 1px) rotate(0deg); } + 70% { transform: translate(3px, 1px) rotate(-1deg); } + 80% { transform: translate(-1px, -1px) rotate(1deg); } + 90% { transform: translate(1px, 2px) rotate(0deg); } + 100% { transform: translate(1px, -2px) rotate(-1deg); } +} + +// Homepage +.category-card-container { + display: flex; +} + +// General +ul { + list-style: none; +} + +form { + margin: 1em; +} + +a { + color: rgb(75, 140, 76); +} + +a:hover { + text-decoration: none; + color:#9D6AB9; +} + + +.product-thumbnail-cart { + max-width: 3em; + border: 3px solid #9D6AB9; +} + +.product-thumbnail { + max-width: 3em; +} + +.fruitstand-img { + max-width: 1.6em; +} + +.new-form-page { + min-height: 300vh; +} + +.homepage-container { + padding: 3%; + padding-bottom: 10% +} + +.homepage-container h2 { + margin-top: 2.5%; + margin-bottom: 2.5%; + padding: 1%; + font-weight: bold; + font-size: 2.5rem; + border-bottom: 2px solid #5EAA5F; +} + + +.new-product-form { + display: flex; + justify-content: flex-start; + padding: 3%; + max-width: 40%; + background-color: white; + border: 4px solid #9D6AB9; + box-shadow: 4px 8px rgba(136, 136, 136, 0.5); + color: #9D6AB9; + font-weight: bold; +} + +.review-product-form { + border: 4px solid #9D6AB9; + box-shadow: 4px 8px rgba(136, 136, 136, 0.5); + color: #9D6AB9; + font-weight: bold; + background-color: white; + padding: 2%; + max-width: 60%; +} + + +.text-fields { + margin-right: 5%; +} + +.table { + background-color: white; + border: 4px solid #9D6AB9; +} + +thead { + background-color: rgb(255, 172, 172); + text-align: center; + border: 4px solid #9D6AB9; +} + +th, th a{ + color:white; + font-weight: bold; +} + +// show product page + +.show-product-img { + max-height: 300px; + border: solid 10px #9D6AB9; + box-shadow: 4px 8px rgba(136, 136, 136, 0.5); + margin-right: 5%; + float: left; +} + +.product-show-head, .product-show-merchant { + margin-left: 5% +} + +.product-show-head { + margin-top: 2%; + margin-bottom: 2%; + font-weight: bolder; + color: rgb(113, 72, 134); +} + +.product-show-merchant { + margin-bottom: 2%; + font-weight: bold; +} + +.add-to-cart-form { + margin: 0.5% 0; +} + +.rating-form .btn { + margin-top: 2% +} + + +.product-show { + margin-left: 5% +} + +.product-show h5 { + font-weight: bold; + margin: 1% 0 +} + +.rating-form { + display: flex; + flex-direction: column; + margin-top: 10%; + border-top: grey 1px solid; + padding: 5% +} + +.rating-form h2 { + font-weight: bolder; + color: rgb(113, 72, 134); +} + +.rating-form form { + margin: 2% 0 +} + +.rating-form div.form-row { + padding: 1% 0; + +} +.product-details { + display: flex; + flex-direction: column; +} + +.rating-img { + max-width: 2rem; +} + +.review-containter { + line-height: 0.5rem; + margin: 2%; +} + +.all-reviews-container { + border-bottom: grey 1px solid; + border-top: grey 1px solid; + padding: 5% 0; +} + +.all-reviews-container h2 { + font-weight: bolder; + color: rgb(113, 72, 134); + margin-left: 5%; +} + +.review-containter { + margin: 5% 5% 2% 5% +} + +.review-containter h4, .review-containter p{ + margin: 1% 0 +} + +.form-row { + padding: 1%; + font-weight: bold; +} + +// Edit User Page +.edit-header { + padding: 1em; + font-weight:bold; + text-align:center; +} +.edit-user { + margin-left:25%; + margin-right:25%; +} + + +.cart-table{ + table-layout: fixed; + width: 75%; + margin-left: 10rem; + font-size: 1em; +} + + + #checkout-section { + display: flex; + flex-direction: column; + align-items: flex-end; + margin-right: 14rem; + } + +#checkout-button { + max-width: 8rem; +} + +.cart-quantity { + max-width: 4rem; +} + +.confirmation-img { + max-width: 10%; + border: solid 2px #9D6AB9; + box-shadow: 1px 3px rgba(136, 136, 136, 0.5); +} + +.confirmation-img-container { + display: flex; + justify-content: space-evenly; + margin: 5%; +} + +.confirmation-shipping-container { + max-width: 30%; + margin-right: 1%; +} + + +.confirmation-welcome, .checkout-welcome { + text-align: center; + margin-top: 3%; +} + +.confirmation-details-container { + display: flex; + justify-content: center; +} + +.customer-service { + text-align: center; + margin-bottom: 2%; +} + +.phone-icon { + max-width: 5%; + margin-bottom: 1%; +} + +// Checkout Page + +.checkout-header{ + margin-bottom:3%; +} + +.checkout-card { + margin-left:20%; + margin-right:20%; +} + +.checkout-billing-container { + margin-top: 5%; +} + +.checkout-container h2 { + margin-bottom: 2% +} + +.submit-btn { + margin-top: 2%; + margin-left: 15%; + margin-right:20%; +} + +.order-items-display { + margin-top: 30px; +} + +.cart-table > thead { + text-align: left; + font-size: 1.25em; +} + +.cart-img { + width: 5%; +} + +.cart-name { + width: 25%; +} + +.cart-price { + width: 10%; +} + +.cart-quantity { + width: 5%; +} + +.cart-update { + width: 5%; +} + +.cart-remove { + width: 10%; +} + +#large-cart { + display: block; + margin-left: auto; + margin-right: auto; + max-height: 50vh; + margin-bottom: 20px; +} + +.product-description { + color: rgb(94, 170, 95); +} +// current user page +.current-user tr { + text-align: center; +} + +.current-user h2 { + margin: 2% 0; +} + +.current-user h3 { + margin: 4% 0 2% 0 +} + +.current-user .username { + color: rgb(113, 72, 134); +} + +.order-show-page { + text-align: center; + padding: 2% +} + +.order-show-page h1 { + color: rgb(113, 72, 134); + margin: 2% +} + +.order-show-page section { + width: auto; + margin: 3% 30%; + padding: 2%; +} \ 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..2305c36d10 --- /dev/null +++ b/app/assets/stylesheets/homepages.scss @@ -0,0 +1,3 @@ +// 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/ 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..741506954d --- /dev/null +++ b/app/assets/stylesheets/orders.scss @@ -0,0 +1,3 @@ +// 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/ diff --git a/app/assets/stylesheets/products.scss b/app/assets/stylesheets/products.scss new file mode 100644 index 0000000000..bff386e55a --- /dev/null +++ b/app/assets/stylesheets/products.scss @@ -0,0 +1,3 @@ +// 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/ 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..31a2eacb84 --- /dev/null +++ b/app/assets/stylesheets/users.scss @@ -0,0 +1,3 @@ +// 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/ 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..181ccd3a1d --- /dev/null +++ b/app/controllers/application_controller.rb @@ -0,0 +1,19 @@ +class ApplicationController < ActionController::Base + before_action :require_login + before_action :find_order + + def current_user + @current_user ||= User.find(session[:user_id]) if session[:user_id] + end + + def require_login + if current_user.nil? + flash[:error] = "You must be logged in to do that." + redirect_to root_path + end + end + + def find_order + @current_order = Order.find_by(id: session[:cart_id]) + 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..614ba2df21 --- /dev/null +++ b/app/controllers/homepages_controller.rb @@ -0,0 +1,7 @@ +class HomepagesController < ApplicationController + skip_before_action :require_login + skip_before_action :find_order + + def index + end +end diff --git a/app/controllers/order_items_controller.rb b/app/controllers/order_items_controller.rb new file mode 100644 index 0000000000..f4d8bb18f4 --- /dev/null +++ b/app/controllers/order_items_controller.rb @@ -0,0 +1,80 @@ +class OrderItemsController < ApplicationController + skip_before_action :require_login + before_action :find_order + + def create + if @current_order.nil? + @current_order = Order.new_order + session[:cart_id] = @current_order.id + end + + @product = Product.find_by(id: params[:product_id]) + if @product.nil? + flash[:error] = "Product no longer exists." + return head :not_found + end + + input_quantity = order_item_params[:quantity].to_i + + if !@product.quantity_available?(input_quantity) + flash[:error] = "Quantity entered (#{input_quantity}) is greater than available stock for #{@product.name}." + return redirect_back(fallback_location: cart_path) + elsif !@current_order.order_items.where(product: @product).empty? + order_item = @current_order.order_items.where(product: @product).first + order_item.increase_quantity(input_quantity) + flash[:success] = "#{@product.name} successfully added to your basket! (quantity: #{input_quantity})" + return redirect_back(fallback_location: cart_path) + else + order_item = OrderItem.new( + product: @product, + order: @current_order, + quantity: input_quantity + ) + end + + if order_item.save + flash[:success] = "#{@product.name} successfully added to your basket! (quantity: #{input_quantity})" + return redirect_back(fallback_location: cart_path) + else + flash[:error] = "#{@product.name} was not added to your basket." + flash[:errors] = order_item.errors.messages + return redirect_back(fallback_location: :root) + end + end + + def update + order_item = OrderItem.find_by(id: params[:id]) + product = order_item.product + input_quantity = order_item_params[:quantity].to_i + + if product.quantity_available?(input_quantity) + if order_item.update(order_item_params) + flash[:success] = "#{product.name} successfully updated!" + else + flash[:error] = "Could not update quantity for #{product.name}." + flash[:errors] = order_item.errors.messages + end + else + flash[:error] = "Quantity entered (#{input_quantity}) is greater than available stock for #{product.name}." + end + return redirect_to cart_path + end + + def destroy + order_item = OrderItem.find_by(id: params[:id]) + if order_item + if order_item.destroy + flash[:success] = "#{order_item.product.name} successfully removed from your basket!" + else + flash.now[:error] = "A problem occurred. #{order_item.product.name} was not successfully removed from your basket." + end + end + return redirect_to cart_path + end + + private + + def order_item_params + return params.require(:order_item).permit(:product, :order, :quantity) + end +end diff --git a/app/controllers/orders_controller.rb b/app/controllers/orders_controller.rb new file mode 100644 index 0000000000..4de26e2326 --- /dev/null +++ b/app/controllers/orders_controller.rb @@ -0,0 +1,111 @@ +class OrdersController < ApplicationController + skip_before_action :require_login, only: [:cart, :checkout, :update_paid, :confirmation] + skip_before_action :find_order, only: [:show, :update_paid, :cancel_order, :complete_order] + before_action :find_order_params, only: [:show, :update_paid, :cancel_order, :complete_order] + + def show + if !@order + head :not_found + return + elsif !@order.contain_orderitems?(@current_user) + flash[:error] = "You cannot check this order details!" + return redirect_to root_path + end + end + + def cart + end + + def checkout + if !@current_order + head :not_found + return + elsif @current_order.order_items.empty? + flash[:error] = "No item in the cart! Please add some items then checkout!" + return redirect_to root_path + end + end + + def update_paid + if !@order + head :not_found + return + else + @order.status = "paid" + if @order.update(order_params) + @order.order_items.each do |item| + item.product.stock = item.product.update_quantity(item.quantity, @order.status) + item.product.save + end + flash[:success] = "Order #{@order.id} purchased successfully!" + return redirect_to confirmation_path + + else + flash[:error] = "Something went wrong! Order was not placed and your card was not billed." + flash[:errors] = @order.errors.messages + return redirect_to cart_path + end + end + end + + def confirmation + if @current_order && @current_order.status == 'paid' + session[:cart_id] = nil + else + head :not_found + return + end + end + + def cancel_order + if !@order + head :not_found + return + else + if @order.contain_orderitems?(@current_user) + if @order.update(status: "cancelled") + @order.order_items.each do |item| + item.product.stock = item.product.update_quantity(item.quantity, @order.status) + item.product.save + end + flash[:success] = "Order #{@order.id} has been cancelled successfully!" + else + flash[:error] = "Something went wrong, order is not cancelled!" + end + else + flash[:error] = "You're not allowed to cancel this order!" + end + return redirect_to current_user_path + end + end + + def complete_order + if !@order + head :not_found + return + else + if @order.contain_orderitems?(@current_user) + if @order.update(status: "completed") + flash[:success] = "Order #{@order.id} has been completed successfully!" + else + flash[:error] = "Something went wrong, order is not completed!" + end + else + flash[:error] = "You're not allowed to complete this order!" + end + return redirect_to current_user_path + end + end + + private + + def order_params + return params.require(:order).permit(:name, :email, :address, :cc_name, :cc_last4, :cc_exp, :cc_cvv, :billing_zip, status: "paid") + end + + def find_order_params + @order = Order.find_by(id: params[:id]) + end + +end + diff --git a/app/controllers/products_controller.rb b/app/controllers/products_controller.rb new file mode 100644 index 0000000000..e53f2c2499 --- /dev/null +++ b/app/controllers/products_controller.rb @@ -0,0 +1,99 @@ +class ProductsController < ApplicationController + before_action :find_product, only: [:show, :edit, :update] + skip_before_action :require_login, only: [:index, :show] + skip_before_action :find_order + + def index + category_id = params[:category_id] + + if category_id.nil? + if params[:search].nil? + @products = Product.active + else + @products = Product.search(params[:search].first) + @search_result = params[:search].first + params[:search] = nil + end + elsif category_id + @category = Category.find_by(id: category_id) + if @category + @products = @category.products.active + else + head :not_found + end + end + end + + def show + if @product.nil? + head :not_found + return + end + end + + def new + @product = Product.new + end + + def create + @product = Product.new(product_params) + + if params[:multiselect] + params[:multiselect].each do |id| + new_category = Category.where(id: id) + if !new_category.empty? + @product.categories << new_category + end + end + end + @product.user_id = session[:user_id] + + if @product.save + if @current_user.merchant_name.nil? + flash[:success] = "Product #{@product.name} has been added successfully" + flash[:message] = "You merchant name is currently empty. Please add a merchant name to list your fruit stand with Fruitsy Merchants." + return redirect_to edit_user_path + else + flash[:success] = "Product #{@product.name} has been added successfully" + redirect_to product_path(@product.id) + return + end + elsif !@product.errors.empty? + flash.now[:error] = "New product was not added. Fix required fields before adding!" + render :new + return + else + flash.now[:error] = "Something went wrong! Product was not added." + render :new + return + end + end + + def edit + if @product.nil? + redirect_to root_path + return + end + end + + def update + if @product.update(product_params) + flash[:success] = "Product #{@product.name} has been updated successfully" + else + flash[:error] = "Something went wrong! Product can not be edited." + flash[:errors] = @product.errors.messages + end + redirect_to current_user_path + return + end + + private + + def find_product + @product = Product.find_by(id: params[:id]) + end + + def product_params + return params.require(:product).permit(:name, :price, :stock, :img_url, :description, :active, category_ids: []) + end +end diff --git a/app/controllers/reviews_controller.rb b/app/controllers/reviews_controller.rb new file mode 100644 index 0000000000..ba4b97346d --- /dev/null +++ b/app/controllers/reviews_controller.rb @@ -0,0 +1,48 @@ +class ReviewsController < ApplicationController + skip_before_action :find_order + skip_before_action :require_login, only: [:create] + + def create + @review = Review.new(review_params) + + if @review.valid? + if current_user && @review.product.user_id == current_user.id + flash[:error] = "You can't review your own product!" + elsif current_user && !current_user.reviews.where(product_id: @review.product_id).empty? + flash[:error] = "You can't review a product more than once!" + elsif @review.save + flash[:success] = "Your #{Review.rating_sentiment(@review.rating)} review on #{@review.product.name} was added successfully!" + else + flash[:error] = "Something went wrong! Your review was not saved!" + end + else + flash[:error] = "Review was not added. Please check required fields before submitting." + flash[:errors] = @review.errors.messages + end + + return redirect_to product_path(@review.product.id) + end + + def destroy + review = Review.find_by(id: params[:id]) + if review + product = review.product + if review.user_id && review.user_id == session[:user_id] + review.destroy + flash[:success] = "Your review was deleted!" + else + flash[:error] = "You cannot delete a review that isn't yours" + end + return redirect_to product_path(product.id) + else + flash[:error] = "The review doesn't exist anymore!" + return redirect_to root_path + end + end + + private + + def review_params + return params.require(:review).permit(:rating, :title, :description, :user_id, :product_id) + end +end diff --git a/app/controllers/users_controller.rb b/app/controllers/users_controller.rb new file mode 100644 index 0000000000..d23c823337 --- /dev/null +++ b/app/controllers/users_controller.rb @@ -0,0 +1,78 @@ +class UsersController < ApplicationController + skip_before_action :require_login, only: [:create, :show] + skip_before_action :find_order + + def show + @user = User.find_by(id: params[:id]) + if @user.nil? + head :not_found + return + end + @products = @user.products.active + end + + def current + if params[:status].nil? + @order_items = [] + @current_user.find_order_items.each do |order_item| + @order_items << order_item if order_item.order.status != 'pending' + end + else + @order_items = @current_user.filter_order_items(params[:status]) + end + if params[:activestatus].nil? + @products = @current_user.products + else + @products = @current_user.products.where(active: params[:activestatus]) + end + end + + def create + auth_hash = request.env["omniauth.auth"] + user = User.find_by(uid: auth_hash[:uid], provider: params[:provider]) + if user + if user.merchant_name + flash[:success] = "Welcome back #{user.merchant_name}! Manage your fruitstand or browse Fruitsy! " + else + flash[:success] = "Welcome back #{user.username}! Enjoy browsing Fruitsy." + end + else + user = User.build_from_github(auth_hash) + if user.save + flash[:success] = "Welcome to Fruitsy, #{user.username}!" + else + flash[:error] = "Oops, something happened! Could not create user account, please try again." + return redirect_to root_path + end + end + session[:user_id] = user.id + redirect_to root_path + end + + def edit + end + + def update + if @current_user.update(user_params) + flash[:success] = "#{@current_user.username} updated successfully!" + return redirect_to current_user_path + else + flash.now[:error] = "Please provide all required fields to edit your account." + return render :edit + end + end + + def destroy + username = @current_user.username + session[:user_id] = nil + flash[:success] = "You are successfully logged out, #{username}!" + redirect_to root_path + end + + private + + def user_params + return params.require(:user).permit(:uid, :merchant_name, :email, :provider, :username) + end + +end diff --git a/app/helpers/application_helper.rb b/app/helpers/application_helper.rb new file mode 100644 index 0000000000..b8b3b3ac61 --- /dev/null +++ b/app/helpers/application_helper.rb @@ -0,0 +1,61 @@ +module ApplicationHelper + + def readable_date(date) + return "[unknown]" unless date.instance_of?(ActiveSupport::TimeWithZone) + return ( + "".html_safe + + date.strftime("%b %d, %Y")+ + "".html_safe + ) + end + + def currency_format(num) + return nil unless num.instance_of?(Integer) || num.instance_of?(Float) + return("$" + sprintf('%.2f', num)) + end + + def fruit_image(code, fruit) + category = Category.find_by(name: fruit) + if category + image = image_tag "https://live.staticflickr.com/65535/#{code}_o.png", alt:"#{fruit} vector image", class:"fruit-img" + return link_to image, category_products_path(category.id) + end + end + + def cart_empty_img_link + image = image_tag "https://live.staticflickr.com/65535/48971625503_83d9d1c039_o.png pcc", alt:"cart fruit basket empty image", class:"basket-img" + return link_to image, cart_path, data: { turbolinks: false } + end + + def cart_full_img_link + image = image_tag "https://live.staticflickr.com/65535/48971625483_e04b973cc8_o.png", alt:"cart fruit basket full image", class:"basket-img" + return link_to image, cart_path, data: { turbolinks: false } + end + + def product_img_link(product: product, img_url: img_url, product_class: product_class) + image = image_tag (product.img_url), class: product_class, alt:"#{product.name} product image" + return link_to image, product_path(product.id) + end + + def rating_img + rating_img = "https://live.staticflickr.com/65535/48983817713_d25a3fba98_o.png" + return image_tag (rating_img), alt:"pineapple rating image", class: "rating-img" + end + + def fruitstand_img + stand_img = "https://live.staticflickr.com/65535/48982995833_9783f655fb_o.png" + return image_tag (stand_img), alt:"fruitstand icon image", class: "fruitstand-img" + end + + def nav_fruit_img + image = "https://live.staticflickr.com/65535/48989157882_0b4f1fae44_o.png" + return image_tag (image), alt:"fruit icon image", class: "nav-fruit-img" + end + + def phone_icon + image = "https://live.staticflickr.com/65535/48994322702_80ca570ef1_o.png" + return image_tag (image), alt:"phone icon image", class: "phone-icon" + end +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..2310a240d7 --- /dev/null +++ b/app/helpers/users_helper.rb @@ -0,0 +1,2 @@ +module UsersHelper +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..25b72a9a62 --- /dev/null +++ b/app/models/category.rb @@ -0,0 +1,13 @@ +class Category < ApplicationRecord + validates :name, presence: true + has_and_belongs_to_many :products + + def self.products_by_category(category_name) + category = Category.find_by(name: category_name) + if category + return category.products + else + return nil + end + end +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..33e6c3591a --- /dev/null +++ b/app/models/order.rb @@ -0,0 +1,37 @@ +class Order < ApplicationRecord + has_many :order_items + + validates :status, presence: true + validates :name, presence: true, if: :not_pending? + validates :email, presence: true, format: { with: /@/, message: "Email format must be valid." } , if: :not_pending? + validates :address, presence: true, if: :not_pending? + validates :cc_name, presence: true, if: :not_pending? + validates_numericality_of :cc_last4, greater_than_or_equal_to: 1000, less_than_or_equal_to: 9999, if: :not_pending? + validates :cc_exp, presence: true, if: :not_pending? + validates_numericality_of :cc_cvv, greater_than_or_equal_to: 100, less_than_or_equal_to: 9999, if: :not_pending? + validates :billing_zip, presence: true, if: :not_pending? + + def not_pending? + status != 'pending' + end + + def contain_orderitems?(user) + self.order_items.each do |order_item| + return true if order_item.product.user_id == user.id + end + return false + end + + def total + total = 0 + self.order_items.each do |orderitem| + total += orderitem.total + end + return total + end + + def self.new_order + order = Order.create(status: "pending") + return order + end +end diff --git a/app/models/order_item.rb b/app/models/order_item.rb new file mode 100644 index 0000000000..5c34218b3d --- /dev/null +++ b/app/models/order_item.rb @@ -0,0 +1,17 @@ +class OrderItem < ApplicationRecord + belongs_to :product + belongs_to :order + + validates_numericality_of :quantity, greater_than: 0 + + def total + (self.quantity * self.product.price) + end + + def increase_quantity(quantity) + existing_quantity = self.quantity + new_quantity = existing_quantity + quantity + + return self.update(quantity: new_quantity) + end +end diff --git a/app/models/product.rb b/app/models/product.rb new file mode 100644 index 0000000000..0ab7ac8d73 --- /dev/null +++ b/app/models/product.rb @@ -0,0 +1,62 @@ +class Product < ApplicationRecord + validates :name, presence: true, uniqueness: {scope: :user_id} + validates_length_of :name, minimum: 1, maximum: 50 + validates :price, numericality: {greater_than: 0} + validates :stock, numericality: { only_integer: true, greater_than_or_equal_to: 0} + validates :user_id, presence: true + validates :img_url, presence: true + validates :description, presence: true + + belongs_to :user + has_many :order_items, dependent: :nullify + has_many :reviews, dependent: :nullify + has_and_belongs_to_many :categories + + + def self.random_products(num) + return Product.all.shuffle.first(num) + end + + def self.deals_under(price) + return Product.where("price < ?", price).shuffle + end + + def quantity_available?(quantity) + if quantity > self.stock + return false + else + return true + end + end + + def update_quantity(quantity, status) + if status == "paid" + self.stock -= quantity + elsif status == "cancelled" + self.stock += quantity + end + return self.stock + end + + def avg_rating + reviews = self.reviews + if reviews.empty? + return nil + else + ratings = reviews.map { |review| review.rating } + return (ratings.sum.to_f / ratings.length).round(1) + end + end + + def self.active + return self.where(active:true) + end + + def self.search(search) + products = [] + self.active.each do |product| + products << product if product.name.downcase.include?(search.downcase) + end + return products + end +end diff --git a/app/models/review.rb b/app/models/review.rb new file mode 100644 index 0000000000..aef5039035 --- /dev/null +++ b/app/models/review.rb @@ -0,0 +1,24 @@ +class Review < ApplicationRecord + validates :rating, numericality: { only_integer: true, greater_than: 0, less_than: 6 } + validates :title, presence: true + validates_length_of :title, minimum: 1, maximum: 150 + validates :description, presence: true + validates_length_of :description, minimum: 1, maximum: 350 + validates :product_id, presence: true + + belongs_to :product + belongs_to :user, optional: true + + def self.rating_sentiment(rating) + if rating > 5 || rating < 1 + return nil + elsif rating < 3 + return "negative" + elsif rating > 3 + return "positive" + elsif rating == 3 + return "neutral" + end + end + +end diff --git a/app/models/user.rb b/app/models/user.rb new file mode 100644 index 0000000000..af6831cfb5 --- /dev/null +++ b/app/models/user.rb @@ -0,0 +1,56 @@ +class User < ApplicationRecord + has_many :products + has_many :reviews, dependent: :nullify + + validates :uid, uniqueness: true, presence: true + validates :merchant_name, uniqueness: true, :allow_nil => true + validates_length_of :merchant_name, maximum: 50 + validates :username, uniqueness: true, presence: true + validates :email, uniqueness: true, presence: true, format: { with: /@/, message: "format must be valid." } + + 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 total_earned + all_order_items = self.find_order_items + total = 0 + all_order_items.each do |item| + status = item.order.status + if status == "paid" || status == "completed" + total += item.total + end + end + return total + end + + def find_order_items + all_products = self.find_products + all_order_items = [] + + all_products.each do |product| + all_order_items << product.order_items + end + return all_order_items.flatten + end + + def find_products + all_products = self.products + return all_products + end + + def filter_order_items(status) + order_items = [] + self.find_products.each do |product| + product.order_items.each do |order_item| + order_items << order_item if order_item.order.status == status + end + end + return order_items + end +end diff --git a/app/views/homepages/index.html.erb b/app/views/homepages/index.html.erb new file mode 100644 index 0000000000..92275549dd --- /dev/null +++ b/app/views/homepages/index.html.erb @@ -0,0 +1,56 @@ +
+

The Sweetest Platform For All Things Fruit!

+ +

Discover Products

+
+ <% random_products = Product.random_products(3) %> + <% random_products.each do |product| %> +
+ <%= product_img_link(product: product, img_url: product.img_url, product_class: "card-img-top")%> +
+
+ <%= link_to product.name, product_path(product.id) %> + <%=currency_format(product.price)%> +
+
+
+ <% end %> +
+ +

Deals Under $10

+ <% deals = Product.deals_under(10).first(5) %> +
+ <% deals.each do |product| %> +
+ <%= product_img_link(product: product, img_url: product.img_url, product_class: "card-img-top")%> +
+
+ <%= link_to product.name, product_path(product.id) %> + <%=currency_format(product.price)%> +
+
+
+ <% end %> +
+ + <% ["citrus", "berry", "tropical"].each do |theme| %> +

<%= theme.capitalize %>

+ <% if Category.products_by_category(theme) %> + <% products = Category.products_by_category(theme).shuffle.first(3) %> +
+ <% products.each do |product| %> +
+ <%= product_img_link(product: product, img_url: product.img_url, product_class: "card-img-top")%> +
+
+ <%= link_to product.name, product_path(product.id) %> + <%=currency_format(product.price)%> +
+
+
+ <% end %> +
+ <% end %> + <%end%> + +
\ 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..03624a714e --- /dev/null +++ b/app/views/layouts/application.html.erb @@ -0,0 +1,179 @@ + + + + 🍉fruitsy🍊 + <%= csrf_meta_tags %> + <%= csp_meta_tag %> + + + + + + + + + + + + <%= stylesheet_link_tag 'application', media: 'all', 'data-turbolinks-track': 'reload' %> + <%= javascript_include_tag 'application', 'data-turbolinks-track': 'reload' %> + + + + + + + <%# Fruit Image Links Fixed Nav %> + + + <%# Merchant Nav Bar %> + <%if session[:user_id]%> + <% current_user = User.find_by(id: session[:user_id]) %> + + <%end%> + + + + <%# Flash Messages on each page %> +
+ <% flash.each do |name, message| %> + <% if name == "success" %> + + <% elsif name == "error"%> + + <% elsif name == "message"%> + + <% elsif name == "errors" %> + + <% end %> + <% end %> +
+ + <%# Main content on each page %> +
+ <%= yield %> +
+ + + <%# Footer on each page %> + + 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/cart.html.erb b/app/views/orders/cart.html.erb new file mode 100644 index 0000000000..9afc346192 --- /dev/null +++ b/app/views/orders/cart.html.erb @@ -0,0 +1,48 @@ +
+

Welcome to your Fruit Basket!

+ + <% if @current_order && @current_order.order_items.count > 0 %> +
+ + + + + + + + + + + + + <% @current_order.order_items.each do |order_item| %> + + + + + <%= form_with model: order_item, url: order_item_path(order_item.id) do |f| %> + + + <% end %> + + <% end %> + +
Product NameUnit PriceQuantity
+ <%= product_img_link(product: order_item.product, img_url: order_item.product.img_url, product_class: "product-thumbnail-cart")%><%= link_to order_item.product.name, product_path(order_item.product.id)%> + <%=currency_format(order_item.product.price)%> + <%= f.text_field :quantity, :size => "2", class: "form-control"%> + + <%= f.submit "Update", class: "btn btn-pretty"%> + + <%= link_to "Remove", order_item_path(order_item.id), method: :delete, data: {confirm: "Are you sure you want to remove this item from your basket?"}, class: "btn btn-pretty"%> +
+
+

Basket Total: <%=currency_format(@current_order.total)%>

+ <%= link_to "Checkout", checkout_path, class:"btn btn-green", id: "checkout-button" %> +
+
+ <% else %> + cart fruit basket empty image +

Your basket is empty.

+ <% end %> +
diff --git a/app/views/orders/checkout.html.erb b/app/views/orders/checkout.html.erb new file mode 100644 index 0000000000..5a4fc892b4 --- /dev/null +++ b/app/views/orders/checkout.html.erb @@ -0,0 +1,76 @@ +
+
+

Checkout

+

Please provide shipping and billing details to complete your order.

+
+ + <%= form_with model: @current_order, url: order_path(id: @current_order.id) do |f| %> +
+
+

Shipping Details

+ +
+ <%= f.label :Name, class: "col-sm-5 col-form-label"%> +
+ <%= f.text_field :name, class: "form-control", type: "text", placeholder: "Bonnie Banana" %> +
+
+ +
+ <%= f.label :Email, class: "col-sm-5 col-form-label" %> +
+ <%= f.text_field :email, class: "form-control", type: "email", placeholder: "BBanana@example.com" %> +
+
+ +
+ <%= f.label :Address, class: "col-sm-5 col-form-label" %> +
+ <%= f.text_field :address, class: "form-control", type: "text", placeholder: "123 Kiwi Ave Apt. 23, Fruitville, WA 99999"%> +
+
+
+
+ +
+

Billing Details

+ +
+ <%= f.label "Credit Card Name", class: "col-sm-5 col-form-label" %> +
+ <%= f.text_field :cc_name, class: "form-control", type: "text", placeholder: "Bonnie B Banana" %> +
+
+ +
+ <%= f.label "Credit Card Last 4 Digits", class: "col-sm-5 col-form-label" %> +
+ <%= f.text_field :cc_last4, class: "form-control", type: "text", placeholder: "4321" %> +
+
+ +
+ <%= f.label "Exp Date", class: "col-sm-5 col-form-label" %> +
+ <%= f.text_field :cc_exp, class: "form-control", type: "text", placeholder: "01/21" %> +
+
+ +
+ <%= f.label "CVV", class: "col-sm-5 col-form-label" %> +
+ <%= f.text_field :cc_cvv, class: "form-control", type: "text", placeholder: "321" %> +
+
+ +
+ <%= f.label "Billing Zip Code", class: "col-sm-5 col-form-label" %> +
+ <%= f.text_field :billing_zip, class: "form-control", type: "text", placeholder: "99999" %> +
+
+ <%= f.submit "Submit Order", class:"btn btn-green submit-btn" %> +
+ <% end %> + +
diff --git a/app/views/orders/confirmation.html.erb b/app/views/orders/confirmation.html.erb new file mode 100644 index 0000000000..513706a3d0 --- /dev/null +++ b/app/views/orders/confirmation.html.erb @@ -0,0 +1,82 @@ +
+
+

Thank you for ordering on fruitsy!

+

We appreciate your business and hope to see you again soon.

+

You will receive a confirmation email shortly at + <%= @current_order.email %>

+

Order <%= @current_order.id %> status is + + <%= @current_order.status %> - <%= currency_format(@current_order.total) %> + +

+
+ + <% if @current_order.status == "paid" %> +
+ <% img_urls = @current_order.order_items.map do |order_item| %> + <% order_item.product.img_url %> + <% end %> + <% img_urls.each do |url| %> + <%= image_tag url, alt:"product image", class:"confirmation-img product-thumbnail" %> + <% end %> +
+ +
+
+ + + + + + + + + + + + + + + + + +
Shipping Details
Name: <%= @current_order.name %>
Email: <%= @current_order.email %>
Address: <%= @current_order.address %>
+
+ +
+ + + + + + + + + + + + + + + + + + + + + + + +
Billing Details
Name: <%= @current_order.cc_name %>
CC Last 4: <%= @current_order.cc_last4 %>
CC Exp: <%= @current_order.cc_exp %>
CC CVV: <%= @current_order.cc_cvv %>
Billing Zip: <%= @current_order.billing_zip %>
+
+ <% end %> +
+ +
+
<%= phone_icon %>
+

Please call customer service with any issues or to cancel your order at 1-800-BUY-FRUIT!

+
+ +
+ + diff --git a/app/views/orders/show.html.erb b/app/views/orders/show.html.erb new file mode 100644 index 0000000000..3247a58674 --- /dev/null +++ b/app/views/orders/show.html.erb @@ -0,0 +1,26 @@ +
+
+ +

Order Details

+ +

Order ID: <%= @order.id %>

+

Order Status: <%= @order.status %>

+ +
+

Shipping info:

+

Name: <%= @order.name %>

+

Email: <%= @order.email %>

+

Address: <%= @order.address %>

+
+ +
+

Payment info:

+

Name: <%= @order.cc_name %>

+

Card num: <%= @order.cc_last4 %>

+

Exp: <%= @order.cc_exp %>

+

CVV: <%= @order.cc_cvv %> +

Billing Zip: <%= @order.billing_zip %>

+
+ +
+
\ No newline at end of file diff --git a/app/views/products/_form.html.erb b/app/views/products/_form.html.erb new file mode 100644 index 0000000000..8547c28dbe --- /dev/null +++ b/app/views/products/_form.html.erb @@ -0,0 +1,74 @@ + + +
+
+

Add A New Product

+ + <%= form_with model: @product, method: :post, action: "/products", class: "form-horizontal new-product-form" do |f| %> + +
+
+ <%= f.label :Name %> + <%= f.text_field :name, class: "form-text" %> +
+ +
+ <%= f.label :Price %> + <%= f.text_field :price, class: "form-text" %> +
+ +
+ <%= f.label :Stock %> + <%= f.text_field :stock, class: "form-text" %> +
+ +
+ <%= f.label "Image URL" %> + <%= f.text_field :img_url, class: "form-text" %> +
+ +
+ <%= f.label :Description %> + <%= f.text_field :description, class: "form-text" %> +
+
+ +
+ <% ["fruit", "theme", "color", "category"].each do |type| %> + <% products = Category.where(category_type: type) %> + +
+ +
+ +
+
+ <% end %> + +
+
+ +
+
+
+<% end %> +
diff --git a/app/views/products/edit.html.erb b/app/views/products/edit.html.erb new file mode 100644 index 0000000000..8d673cbff8 --- /dev/null +++ b/app/views/products/edit.html.erb @@ -0,0 +1,13 @@ +

Edit Product Form

+ +<% if @product.errors.any? %> + +<% end %> + +<%= render partial: "form", locals: { submit_button_label: "Edit product", product_form_class: "edit-product-form" } %> \ No newline at end of file diff --git a/app/views/products/index.html.erb b/app/views/products/index.html.erb new file mode 100644 index 0000000000..ea4fe2dc07 --- /dev/null +++ b/app/views/products/index.html.erb @@ -0,0 +1,32 @@ +
+ <% if @category %> +

Shop All <%= @category.name.capitalize %> Products

+ <% elsif @search_result %> +

Search results for "<%= @search_result %>"

+ <% else %> +

Shop All Fruit Products

+ <% end %> + +
+ <% @products.shuffle.each do |product| %> +
+ <%= form_with model: OrderItem, url: product_order_items_path(product.id) do |f| %> + <%= f.hidden_field :quantity, :value => 1 %> + <%= f.submit "+", class: "btn btn-green quick-add-btn" %> + <% end %> + <%= product_img_link(product: product, img_url: product.img_url, product_class: "card-img-top")%> +
+
<%= link_to product.name, product_path(product.id) %> + <%=currency_format(product.price)%> +
+ <% if product.user.merchant_name %> +

<%= fruitstand_img %> <%= link_to product.user.merchant_name, user_path(product.user.id) %>

+ <% else %> +

<%= fruitstand_img %> <%=link_to product.user.username, user_path(product.user.id) %>

+ <% end %> +
+ +
+ <% end %> +
+
diff --git a/app/views/products/new.html.erb b/app/views/products/new.html.erb new file mode 100644 index 0000000000..bb85a9ab86 --- /dev/null +++ b/app/views/products/new.html.erb @@ -0,0 +1,14 @@ +
+<% if @product.errors.any? %> + +<% end %> + +<%= render partial: "form", locals: { submit_button_label: "Add product", product_form_class: "new-product-form" } %> + +
\ No newline at end of file diff --git a/app/views/products/show.html.erb b/app/views/products/show.html.erb new file mode 100644 index 0000000000..caaccd2ced --- /dev/null +++ b/app/views/products/show.html.erb @@ -0,0 +1,110 @@ + +
+ +

<%= @product.name %>

+ <% merchant = User.find_by(id: @product.user_id) %> + <% if merchant.merchant_name.empty? %> +
<%= fruitstand_img %> <%= link_to merchant.username, user_path(@product.user.id) %>
+ <% else %> +
<%= fruitstand_img %> <%= link_to merchant.merchant_name, user_path(@product.user.id) %>
+ <% end %> + +
+ <%= product_img_link(product: @product, img_url: @product.img_url, product_class: "show-product-img")%> +
+

<%=currency_format(@product.price) %>

+
<%= @product.description %>
+ <% if @product.avg_rating %> +
Average Rating: <%= @product.avg_rating %>
+ <% else %> +
Average Rating: no customer review yet :(
+ <% end %> +
Stock: + <% if @product.stock > 0 %> + <%= @product.stock %> + <% else %> +

Out of stock :(

+ <%end %> +
+ + <%= form_with model: OrderItem, url: product_order_items_path(@product.id), class: "add-to-cart-form" do |f| %> +
+
<%= f.label :quantity %>
+
+ <%= f.text_field :quantity, :value => 1, class: "form-control" %> +
+
+ <%= f.submit "add to cart", class: "btn btn-pretty", id: "add-cart-btn" %> + <% end %> + +
+ Categories: + <% categories = @product.categories.map do |category| %> + <%= link_to category.name, category_products_path(category.id) %> + <% if category != @product.categories.last %> + | + <% end %> + <% end %> +
+
+
+ +
+

Add a review for <%= @product.name %>

+ + <%= form_with model: Review, url: reviews_path, method: :post, class:"review-product-form" do |f| %> +
+ <%= f.label "Rating", class: "col-sm-2 col-form-label"%> + <%= f.select :rating, (1..5).to_a, class: "col-sm-2 col-form-label" %> +
+ +
+
+ <%= f.label "Title", class: "col-form-label" %> + <%= f.text_field :title, class: "form-control", type: "text", placeholder: "Example Review Title" %> +
+
+
+
+ <%= f.label "Review", class: "col-form-label"%> + <%= f.text_area :description, class: "form-control", type: "text", placeholder: "Leave reviews on Fruitsy products..." %> +
+
+ <%= f.hidden_field :user_id, :value => session[:user_id] %> + <%= f.hidden_field :product_id, :value => @product.id %> + + <%= f.submit "Submit", class: "btn btn-pretty" %> + <% end %> +
+ +<% if !@product.reviews.empty? %> +
+

<%= @product.name %> Reviews

+ <% @product.reviews.order(rating: :desc).each do |review| %> +
+
+ <% review.rating.times do %> + <%= rating_img %> + <% end %> +
+

<%= review.title %> + - + <% if review.user %> + <%= link_to review.user.username, user_path(review.user.id) %> + <% else %> + Guest + <% end %> + +

+

<%= review.description %>

+ <% if session[:user_id] && review.user_id == session[:user_id] %> + <%= link_to "Delete Your Review", review_path, method: :delete, data: { confirm: "Are you sure?" }, class: "btn btn-pretty" %> + <% end %> +
+ <% end %> +
+<% else %> +
+

There are no reviews for this product yet!

+
+<%end%> diff --git a/app/views/users/current.html.erb b/app/views/users/current.html.erb new file mode 100644 index 0000000000..4fb01193ce --- /dev/null +++ b/app/views/users/current.html.erb @@ -0,0 +1,131 @@ +
+

Hello, + <%if @current_user.merchant_name && !@current_user.merchant_name.empty? %> + <%= @current_user.merchant_name%>! + <%else%> + <%= @current_user.username%>! + <%end%> +

+

You can <%= link_to "edit", edit_user_path %> your profile here.

+ <% if @current_user.products.count > 0 %> +

Total revenue as of today: + <%= currency_format(@current_user.total_earned)%>

+ <% else %> +

You haven't sold any products yet! Why not <%= link_to "add a product", new_product_path%> to sell?

+ <% end %> +

+
+

Manage your products

+ + + + + + + + + + + + + + + + <%if @products %> + <% @products.sort_by{ |p| p.created_at}.reverse.each do |product| %> + + + + <%= form_with model: product, method: :patch, url: product_path(product.id) do |f| %> + + + + + + + <% end %> + + <% end %> + <% end %> + +
+ + + Product Title Price Stock Description Img url Active Edit
+ <% if product.active %> + Active + <% else %> + Inactive + <% end %> + <%= product_img_link(product: product, img_url: product.img_url, product_class:"product-thumbnail") %><%= f.text_field :name, :size=>"20" %>$<%= f.text_field :price, :value => (number_with_precision(f.object.price, :precision => 2) || 0), :size=>"4" %><%= f.text_field :stock, :size=>"3" %><%= f.text_field :description %><%= f.text_field :img_url, :size=>"10" %> + <%= f.check_box :active %><%= f.submit "Update", submit_button_label: "Edit Product", class: "btn btn-pretty" %>
+
+ +
+

Manage your orders

+ + + + + <%# #Will require a link to view individual order %> + + <%# #Will require a link to the product %> + + + + + + + + + <% if @current_user.products %> + <% @order_items.each do |order_item| %> + + <% order = order_item.order %> + + + + + + + <% elsif %> + + <% end %> + <%end%> + +
Order id Product Name Order date + + + Quantity Total Category
<%= link_to order.id, order_path(order.id) %><%= link_to order_item.product.name, product_path(order_item.product.id) %><%= readable_date(order.created_at) %> + <% if order.status == "paid" %> + + + <% else %> + <%= order.status.capitalize %> + <% end %> + <%= order_item.quantity %><%= order_item.total %> + <% if !order_item.product.categories.empty?%> + <%= order_item.product.categories.first.name %>

N/A

+ <% end %> +
+
+ <%= link_to "Back to Home", root_path, class: "btn btn-green" %> +
diff --git a/app/views/users/edit.html.erb b/app/views/users/edit.html.erb new file mode 100644 index 0000000000..dedd1b92e3 --- /dev/null +++ b/app/views/users/edit.html.erb @@ -0,0 +1,44 @@ +
+
+

Edit Fruisty Profile

+
+ <% if @current_user.errors.any? %> +
    + <% @current_user.errors.each do |column, message| %> +
  • + <%= column.capitalize %> <%= message %> +
  • + <% end %> +
+ <% end %> + + <%= form_with model: @current_user do |f| %> +
+ <%= f.label :merchant_name, class: "col-sm-5 col-form-label"%> +
+ <%= f.text_field :merchant_name, class: "form-control" %> +
+
+
+ <%= f.label :email, class: "col-sm-5 col-form-label"%> +
+ <%= f.text_field :email, class: "form-control" %> +
+
+
+
+ <%= f.label :username, class: "col-sm-5 col-form-label"%> +
+ <%= f.text_field :username, class: "form-control" %> +
+
+
+
+
+ <%= f.submit "Update", class: "btn btn-pretty" %> +
+
+ <% end %> +
+
+
diff --git a/app/views/users/show.html.erb b/app/views/users/show.html.erb new file mode 100644 index 0000000000..d419a6dc23 --- /dev/null +++ b/app/views/users/show.html.erb @@ -0,0 +1,34 @@ +
+

+ <%= fruitstand_img %> + Welcome to + <% if @user.merchant_name %> + <%= @user.merchant_name %> + <% else %> + <%= @user.username %> + <% end %> + 's Shop! +

+ + <% if @user.products.count > 0 %> +
+ <% @products.each do |product| %> +
+ <%= product_img_link(product: product, img_url: product.img_url, product_class: "card-img-top")%> +
+
<%= link_to product.name, product_path(product.id) %>
+

<%= currency_format(product.price) %>

+
+

+ <% product.categories.each do |category| %> + <%= link_to category.name, category_products_path(category.id) %> + <% end %> +

+ +
+ <% end %> +
+ <% else %> +

Merchant's fruit stand is empty.

+ <% end %> +
\ No newline at end of file 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..9f1b9c4a0d --- /dev/null +++ b/config/credentials.yml.enc @@ -0,0 +1 @@ +hJ/92UPtoOUfdDV7Vfw6/tL26grV/yHEgQdeSlAab668IGZ1js3O17XGAQLYSJUWma7kDd8XebESxUzAQ/N4x8dcqtjX43CY/AvBJemyOCEVHOqD1ElBB82lOdDUZyvoV1Ap2UIgLbZsaQegW9fYzI4HxTQhexCt2xZ6WGNq7uITYffn9cawM7/+lRGu9w31Bw+sJYmEE16PYKwFxyzh0Al174jz7ch6Z1Zyxhm1h6rUqwtvnZZOeGrfCkdceJsIp9KUjKCpBGrT1bUrLr40PRAr5QRpCvUHgQHumNZNOEmDLJPq0Z4aoZDiFv37tthd+3XsD9pQyJf5M8H+4NRp+swH+yfjSO4V+Ypdu+Ta3JFPAcEs5iDdTvKShxGlhxOPwCZqnfM+opPEq5pAiOW3BB1mhJrrRo5yIJHG--wX30JqlPnnzJ79SA--H76AYdWhkr5ldBQ29dmRCg== \ 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..85386c71c7 --- /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..a741783369 --- /dev/null +++ b/config/routes.rb @@ -0,0 +1,32 @@ +Rails.application.routes.draw do + root "homepages#index" + + resources :products do + resources :order_items, only: [:create] + end + + get "/auth/github", as: "github_login" + get "/auth/:provider/callback", to: "users#create", as: "auth_callback" + delete "/logout", to: "users#destroy", as: "logout" + + get "/users/current", to: "users#current", as: "current_user" + get "/users/current/edit", to: "users#edit", as: "edit_user" + + resources :users, only: [:show, :update] + + get "/orders/cart", to: "orders#cart", as: "cart" + get "/orders/checkout", to: "orders#checkout", as: "checkout" + get "/orders/confirmation", to: "orders#confirmation", as: "confirmation" + resources :orders, only: [:show] + patch "/orders/:id", to: "orders#update_paid" + patch "/orders/:id/cancel", to: "orders#cancel_order", as: "cancel_order" + patch "/orders/:id/complete", to: "orders#complete_order", as: "complete_order" + + resources :categories do + resources :products, only: [:index] + end + + resources :order_items, only: [:update, :destroy] + + resources :reviews, only: [:create, :destroy] +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/migrate/20191023021127_create_users.rb b/db/migrate/20191023021127_create_users.rb new file mode 100644 index 0000000000..73b8c80f02 --- /dev/null +++ b/db/migrate/20191023021127_create_users.rb @@ -0,0 +1,11 @@ +class CreateUsers < ActiveRecord::Migration[5.2] + def change + create_table :users do |t| + t.string :uid + t.string :name + t.string :email + + t.timestamps + end + end +end diff --git a/db/migrate/20191023021218_create_products.rb b/db/migrate/20191023021218_create_products.rb new file mode 100644 index 0000000000..65e38b98d4 --- /dev/null +++ b/db/migrate/20191023021218_create_products.rb @@ -0,0 +1,12 @@ +class CreateProducts < ActiveRecord::Migration[5.2] + def change + create_table :products do |t| + t.string :name + t.string :category + t.float :price + t.integer :quantity + + t.timestamps + end + end +end diff --git a/db/migrate/20191023021424_create_orders.rb b/db/migrate/20191023021424_create_orders.rb new file mode 100644 index 0000000000..2a99cb9035 --- /dev/null +++ b/db/migrate/20191023021424_create_orders.rb @@ -0,0 +1,17 @@ +class CreateOrders < ActiveRecord::Migration[5.2] + def change + create_table :orders do |t| + t.string :status + t.string :name + t.string :email + t.string :address + t.string :cc_name + t.integer :cc_last4 + t.string :cc_exp + t.integer :cc_cvv + t.string :billing_zip + + t.timestamps + end + end +end diff --git a/db/migrate/20191023021516_create_order_items.rb b/db/migrate/20191023021516_create_order_items.rb new file mode 100644 index 0000000000..cd9db5ef0d --- /dev/null +++ b/db/migrate/20191023021516_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/20191023032736_create_reviews.rb b/db/migrate/20191023032736_create_reviews.rb new file mode 100644 index 0000000000..dd05cb2062 --- /dev/null +++ b/db/migrate/20191023032736_create_reviews.rb @@ -0,0 +1,8 @@ +class CreateReviews < ActiveRecord::Migration[5.2] + def change + create_table :reviews do |t| + + t.timestamps + end + end +end diff --git a/db/migrate/20191023033236_add_columns_to_reviews.rb b/db/migrate/20191023033236_add_columns_to_reviews.rb new file mode 100644 index 0000000000..775ba50b73 --- /dev/null +++ b/db/migrate/20191023033236_add_columns_to_reviews.rb @@ -0,0 +1,6 @@ +class AddColumnsToReviews < ActiveRecord::Migration[5.2] + def change + add_column :reviews, :rating, :float + add_column :reviews, :description, :string + end +end diff --git a/db/migrate/20191023174508_add_relationships_to_product.rb b/db/migrate/20191023174508_add_relationships_to_product.rb new file mode 100644 index 0000000000..e13dc436df --- /dev/null +++ b/db/migrate/20191023174508_add_relationships_to_product.rb @@ -0,0 +1,6 @@ +class AddRelationshipsToProduct < ActiveRecord::Migration[5.2] + def change + add_reference :order_items, :product, foreign_key: true + add_reference :products, :user, foreign_key: true + end +end diff --git a/db/migrate/20191023175205_add_provider_and_username_columns.rb b/db/migrate/20191023175205_add_provider_and_username_columns.rb new file mode 100644 index 0000000000..16bd54d9b2 --- /dev/null +++ b/db/migrate/20191023175205_add_provider_and_username_columns.rb @@ -0,0 +1,6 @@ +class AddProviderAndUsernameColumns < ActiveRecord::Migration[5.2] + def change + add_column :users, :provider, :string + add_column :users, :username, :string + end +end diff --git a/db/migrate/20191023175637_change_name_column.rb b/db/migrate/20191023175637_change_name_column.rb new file mode 100644 index 0000000000..9ad79d5509 --- /dev/null +++ b/db/migrate/20191023175637_change_name_column.rb @@ -0,0 +1,5 @@ +class ChangeNameColumn < ActiveRecord::Migration[5.2] + def change + rename_column :users, :name, :merchant_name + end +end diff --git a/db/migrate/20191023180825_add_imageurl_column_to_products.rb b/db/migrate/20191023180825_add_imageurl_column_to_products.rb new file mode 100644 index 0000000000..f344b69576 --- /dev/null +++ b/db/migrate/20191023180825_add_imageurl_column_to_products.rb @@ -0,0 +1,5 @@ +class AddImageurlColumnToProducts < ActiveRecord::Migration[5.2] + def change + add_column :products, :img_url, :string + end +end diff --git a/db/migrate/20191023181252_create_categories.rb b/db/migrate/20191023181252_create_categories.rb new file mode 100644 index 0000000000..6cfb9a0962 --- /dev/null +++ b/db/migrate/20191023181252_create_categories.rb @@ -0,0 +1,9 @@ +class CreateCategories < ActiveRecord::Migration[5.2] + def change + create_table :categories do |t| + t.string :category + + t.timestamps + end + end +end diff --git a/db/migrate/20191023181328_create_products_category_join.rb b/db/migrate/20191023181328_create_products_category_join.rb new file mode 100644 index 0000000000..6c18fbca76 --- /dev/null +++ b/db/migrate/20191023181328_create_products_category_join.rb @@ -0,0 +1,8 @@ +class CreateProductsCategoryJoin < ActiveRecord::Migration[5.2] + def change + create_table :categories_products do |t| + t.belongs_to :product, index: true + t.belongs_to :category, index: true + end + end +end diff --git a/db/migrate/20191023182009_remove_category_column_from_products.rb b/db/migrate/20191023182009_remove_category_column_from_products.rb new file mode 100644 index 0000000000..aea76b9b4e --- /dev/null +++ b/db/migrate/20191023182009_remove_category_column_from_products.rb @@ -0,0 +1,5 @@ +class RemoveCategoryColumnFromProducts < ActiveRecord::Migration[5.2] + def change + remove_column :products, :category + end +end diff --git a/db/migrate/20191023211233_add_description_to_products.rb b/db/migrate/20191023211233_add_description_to_products.rb new file mode 100644 index 0000000000..c10c9afa30 --- /dev/null +++ b/db/migrate/20191023211233_add_description_to_products.rb @@ -0,0 +1,5 @@ +class AddDescriptionToProducts < ActiveRecord::Migration[5.2] + def change + add_column :products, :description, :string + end +end diff --git a/db/migrate/20191025173459_add_customer_id_to_orders.rb b/db/migrate/20191025173459_add_customer_id_to_orders.rb new file mode 100644 index 0000000000..40f35a5126 --- /dev/null +++ b/db/migrate/20191025173459_add_customer_id_to_orders.rb @@ -0,0 +1,5 @@ +class AddCustomerIdToOrders < ActiveRecord::Migration[5.2] + def change + add_column :orders, :customer_id, :integer + end +end diff --git a/db/migrate/20191025225946_add_order_i_dto_order_item.rb b/db/migrate/20191025225946_add_order_i_dto_order_item.rb new file mode 100644 index 0000000000..2ead75291b --- /dev/null +++ b/db/migrate/20191025225946_add_order_i_dto_order_item.rb @@ -0,0 +1,5 @@ +class AddOrderIDtoOrderItem < ActiveRecord::Migration[5.2] + def change + add_reference :order_items, :order, foreign_key: true + end +end diff --git a/db/migrate/20191026201207_change_category_to_name_add_type.rb b/db/migrate/20191026201207_change_category_to_name_add_type.rb new file mode 100644 index 0000000000..fbd57e6fda --- /dev/null +++ b/db/migrate/20191026201207_change_category_to_name_add_type.rb @@ -0,0 +1,6 @@ +class ChangeCategoryToNameAddType < ActiveRecord::Migration[5.2] + def change + rename_column :categories, :category, :name + add_column :categories, :type, :string + end +end diff --git a/db/migrate/20191026203648_change_type_to_categorytype.rb b/db/migrate/20191026203648_change_type_to_categorytype.rb new file mode 100644 index 0000000000..8f3f6dca80 --- /dev/null +++ b/db/migrate/20191026203648_change_type_to_categorytype.rb @@ -0,0 +1,5 @@ +class ChangeTypeToCategorytype < ActiveRecord::Migration[5.2] + def change + rename_column :categories, :type, :category_type + end +end diff --git a/db/migrate/20191028184043_add_product_relationships_to_review.rb b/db/migrate/20191028184043_add_product_relationships_to_review.rb new file mode 100644 index 0000000000..dcc6279058 --- /dev/null +++ b/db/migrate/20191028184043_add_product_relationships_to_review.rb @@ -0,0 +1,6 @@ +class AddProductRelationshipsToReview < ActiveRecord::Migration[5.2] + def change + add_reference :reviews, :user, foreign_key: true + add_reference :reviews, :product, foreign_key: true + end +end diff --git a/db/migrate/20191028233427_add_change_quantitycolumn_to_stock.rb b/db/migrate/20191028233427_add_change_quantitycolumn_to_stock.rb new file mode 100644 index 0000000000..fdfe4a71ac --- /dev/null +++ b/db/migrate/20191028233427_add_change_quantitycolumn_to_stock.rb @@ -0,0 +1,5 @@ +class AddChangeQuantitycolumnToStock < ActiveRecord::Migration[5.2] + def change + rename_column :products, :quantity, :stock + end +end diff --git a/db/migrate/20191029034632_change_rating_data_type_to_integer.rb b/db/migrate/20191029034632_change_rating_data_type_to_integer.rb new file mode 100644 index 0000000000..2ec84af381 --- /dev/null +++ b/db/migrate/20191029034632_change_rating_data_type_to_integer.rb @@ -0,0 +1,5 @@ +class ChangeRatingDataTypeToInteger < ActiveRecord::Migration[5.2] + def change + change_column :reviews, :rating, :integer + end +end diff --git a/db/migrate/20191029044211_add_hidden_to_product.rb b/db/migrate/20191029044211_add_hidden_to_product.rb new file mode 100644 index 0000000000..2281e68c99 --- /dev/null +++ b/db/migrate/20191029044211_add_hidden_to_product.rb @@ -0,0 +1,5 @@ +class AddHiddenToProduct < ActiveRecord::Migration[5.2] + def change + add_column :products, :active, :boolean + end +end diff --git a/db/migrate/20191029195437_add_title_to_reviews.rb b/db/migrate/20191029195437_add_title_to_reviews.rb new file mode 100644 index 0000000000..7ae2459c58 --- /dev/null +++ b/db/migrate/20191029195437_add_title_to_reviews.rb @@ -0,0 +1,5 @@ +class AddTitleToReviews < ActiveRecord::Migration[5.2] + def change + add_column :reviews, :title, :string + end +end diff --git a/db/migrate/20191029212317_change_active_to_default_true.rb b/db/migrate/20191029212317_change_active_to_default_true.rb new file mode 100644 index 0000000000..68570ad503 --- /dev/null +++ b/db/migrate/20191029212317_change_active_to_default_true.rb @@ -0,0 +1,6 @@ +class ChangeActiveToDefaultTrue < ActiveRecord::Migration[5.2] + def change + remove_column :products, :active + add_column :products, :active, :boolean, default: true + end +end diff --git a/db/migrate/20191031063304_remove_customer_id_from_orders.rb b/db/migrate/20191031063304_remove_customer_id_from_orders.rb new file mode 100644 index 0000000000..9cacb14320 --- /dev/null +++ b/db/migrate/20191031063304_remove_customer_id_from_orders.rb @@ -0,0 +1,5 @@ +class RemoveCustomerIdFromOrders < ActiveRecord::Migration[5.2] + def change + remove_column :orders, :customer_id + end +end diff --git a/db/schema.rb b/db/schema.rb new file mode 100644 index 0000000000..03f82e72f3 --- /dev/null +++ b/db/schema.rb @@ -0,0 +1,96 @@ +# 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_31_063304) 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 + t.string "category_type" + end + + create_table "categories_products", force: :cascade do |t| + t.bigint "product_id" + t.bigint "category_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.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 "status" + t.string "name" + t.string "email" + t.string "address" + t.string "cc_name" + t.integer "cc_last4" + t.string "cc_exp" + t.integer "cc_cvv" + t.string "billing_zip" + t.datetime "created_at", null: false + t.datetime "updated_at", null: false + end + + create_table "products", force: :cascade do |t| + t.string "name" + t.float "price" + t.integer "stock" + t.datetime "created_at", null: false + t.datetime "updated_at", null: false + t.bigint "user_id" + t.string "img_url" + t.string "description" + t.boolean "active", default: true + t.index ["user_id"], name: "index_products_on_user_id" + end + + create_table "reviews", force: :cascade do |t| + t.datetime "created_at", null: false + t.datetime "updated_at", null: false + t.integer "rating" + t.string "description" + t.bigint "user_id" + t.bigint "product_id" + t.string "title" + t.index ["product_id"], name: "index_reviews_on_product_id" + t.index ["user_id"], name: "index_reviews_on_user_id" + end + + create_table "users", force: :cascade do |t| + t.string "uid" + t.string "merchant_name" + t.string "email" + t.datetime "created_at", null: false + t.datetime "updated_at", null: false + t.string "provider" + t.string "username" + end + + add_foreign_key "order_items", "orders" + add_foreign_key "order_items", "products" + add_foreign_key "products", "users" + add_foreign_key "reviews", "products" + add_foreign_key "reviews", "users" +end diff --git a/db/seed_data/products.csv b/db/seed_data/products.csv new file mode 100644 index 0000000000..65879beacf --- /dev/null +++ b/db/seed_data/products.csv @@ -0,0 +1,149 @@ +merchant,img_url,name,fruit,fruit_theme,category,color +666,https://live.staticflickr.com/65535/48960934177_f0b975e6f7.jpg,You're One in a Melon Watermlon Card,watermelon,,cards,green +171717,https://live.staticflickr.com/65535/48960748931_29342cde2e_m.jpg,I Love You Berry Much Card,strawberry,berry,cards,red +111,https://live.staticflickr.com/65535/48960748971_d9f7c72310.jpg,"If You Were A Fruit, You'd By Fine-Apple Card",pineapple,tropical,cards,yellow +333,https://live.staticflickr.com/65535/48960731446_bc33f35083_n.jpg,Yellow Pineapple Fanta,pineapple,tropical,drinks,yellow +151515,https://live.staticflickr.com/65535/48960731466_acd78c02ce.jpg,Yellow Pineapple Fanta Glass Bottle,pineapple,tropical,drinks,yellow +141414,https://live.staticflickr.com/65535/48960915992_6b963dfa8c_o.jpg,Yellow Pineapple Iphone,pineapple,tropical,misc,yellow +101010,https://live.staticflickr.com/65535/48960181608_49af5d30ba_o.jpg,Watermelon Purse Tote,watermelon,,bags,"green,pink" +222,https://live.staticflickr.com/65535/48960731521_0d8d9aabfc_o.jpg,Watermlone Eraser,watermelon,,office,"green,pink" +999,https://live.staticflickr.com/65535/48960731546_b991f5fc22_o.png,Fruit Shoot Tropical Pineapple Drink,pineapple,tropical,drinks,yellow +121212,https://live.staticflickr.com/65535/48960731791_fd4bafd0c6.jpg,Stuffed Strawberry Key Chain,strawberry,berry,"accessories,toys",red +121212,https://live.staticflickr.com/65535/48960916072_74876b97e7.jpg,Redd's Wicked Apple Cider,apple,,drinks,red +101010,https://live.staticflickr.com/65535/48960879391_054aa0599f_o.jpg,Red Apple Iphone,apple,,misc,red +555,https://live.staticflickr.com/65535/48960916017_6a990f83ea_o.jpg,Watermelon Sponge,watermelon,,kitchen,"red,green" +131313,https://live.staticflickr.com/65535/48960181728_eeda5e43bf_o.jpg,Citrus Orange Sponge,orange,citrus,kitchen,"yellow,orange" +111111,https://live.staticflickr.com/65535/48960916182_f58891fd9c.jpg,Orange Fanta Drink,orange,citrus,drinks,orange +242424,https://live.staticflickr.com/65535/48960916217_040376b8cf_o.png,Apple Kiwi Drink,"apple,kiwi",,drinks,green +252525,https://live.staticflickr.com/65535/48960181768_f0f70f4acd.jpg,Green Mango Fizz Fanta Drink,mango,tropical,drinks,green +191919,https://live.staticflickr.com/65535/48960181793_072afd2388_o.jpg,Grape Sponge,grape,,sponges,purple +111111,https://live.staticflickr.com/65535/48960181808_24e66b678d_o.jpg,Grape Purple Fanta,grape,,drinks,purple +222,https://live.staticflickr.com/65535/48960731726_32509002fd_o.jpg,Fruit Pencil Cases,"dragonfruit,orange,watermelon",,office, +141414,https://live.staticflickr.com/65535/48960181858_56d7e3ab31_o.jpg,Blueberry Blackberry Drink,,berry,drinks,"blue,purple" +333,https://live.staticflickr.com/65535/48960181878_eddd5cae33_o.jpg,Blue Berry Iphone,,berry,misc,blue +131313,https://live.staticflickr.com/65535/48960181923_4a2b33d88f_n.jpg,Apple Snapple Drink,apple,,drinks,red +222,https://live.staticflickr.com/65535/48960620502_b9b690a4a6_o.jpg,Watermelon Word Melon Game,watermelon,,games,pink +141414,https://live.staticflickr.com/65535/48960434341_6493066856_o.jpg,Citrust Orange Bedding,orange,citrus,bedding,orange +111,https://live.staticflickr.com/65535/48960434356_dbe553616c_o.jpg,Watermelon Stuffed Friend,watermelon,,toys,"red,green" +555,https://live.staticflickr.com/65535/48960620582_25f04a8b84_b.jpg,Watermelon Notebook,watermelon,,books,red +111111,https://live.staticflickr.com/65535/48960620617_49a705ba30_o.jpg,Watermelon Vans,watermelon,,shoes,red +111,https://live.staticflickr.com/65535/48960620627_da27818ec6_o.jpg,Watermelon Gold Chain Purse,watermelon,,bags,red +222222,https://live.staticflickr.com/65535/48960434466_170b615f30_o.jpg,Watermelon Planner,watermelon,,office,"green,red" +212121,https://live.staticflickr.com/65535/48959883983_630aa86ff3_o.jpg,Watermelon Head Doll,watermelon,,toys,green +181818,https://live.staticflickr.com/65535/48959884003_9dbb77cff1_o.jpg,Watermelon Swivel Chair,watermelon,,furniture,"green,red" +131313,https://live.staticflickr.com/65535/48960434531_6060464d43_o.jpg,Banana Apeeling Card,banana,tropical,cards,yellow +212121,https://live.staticflickr.com/65535/48960434556_e65a8528d9_o.jpg,Stuffed Grapes Toy,grapes,,toys,purple +444,https://live.staticflickr.com/65535/48960620817_c8042f0bff_b.jpg,Pineapple Pants,pineapple,tropical,clothing,"pink,yellow" +101010,https://live.staticflickr.com/65535/48960620827_3fff7cda99_o.jpg,Giant Strawberry,strawberry,berry,misc,red +181818,https://live.staticflickr.com/65535/48959884103_05236062df.jpg,Strawberry High Tops,strawberry,berry,shoes,red +161616,https://live.staticflickr.com/65535/48960434641_f302a710bd_o.jpg,Strawberry Sandals,strawberry,berry,shoes,"pink,red" +222222,https://live.staticflickr.com/65535/48960623942_6031cb7a2b_o.jpg,Strawberry Hard Candies,strawberry,berry,misc,red +111,https://live.staticflickr.com/65535/48959887228_b64c64e10f.jpg,Strawberry Hair Clips,strawberry,berry,accessories, +191919,https://live.staticflickr.com/65535/48959884123_324e20b845_o.jpg,Pink Strawberry Couch,strawberry,berry,furniture,pink +191919,https://live.staticflickr.com/65535/48959884148_932bf8e38d_o.jpg,Strawberry Beanbag Chair,strawberry,berry,furniture,red +111111,https://live.staticflickr.com/65535/48960620932_ee3ccbdb42_o.jpg,Banana White Sweater,banana,tropical,clothing,yellow +212121,https://live.staticflickr.com/65535/48959884183_69306bcd7f_o.jpg,Pineapple Mickey Mouse,pineapple,tropical,toys,yellow +111111,https://live.staticflickr.com/65535/48959884213_303dd5a752.jpg,Orange Earrings,orange,tropical,earrings,orange +212121,https://live.staticflickr.com/65535/48960624027_19138827a2_b.jpg,Watermelon Berry Bedding,"watermelon,strawberry",berry,bedding,"pink,red" +333,https://live.staticflickr.com/65535/48960620982_3f742a4fb3_b.jpg,Strawberry Dog Costume,strawberry,berry,"animals,costumes",red +202020,https://live.staticflickr.com/65535/48960620992_a4db6cb9b1_o.jpg,Minimalist Pineapple Shirt,pineapple,tropical,clothing,yellow +777,https://live.staticflickr.com/65535/48960621007_e0143f9ce4_o.jpg,Pineapple Cross Purse,pineapple,tropical,bags,yellow +171717,https://live.staticflickr.com/65535/48959887328_97630922f2_o.jpg,Citrus Lemon Holder,lemon,citrus,kitchen, +777,https://live.staticflickr.com/65535/48960621142_11bae1c41c.jpg,Pineapple Cat House,pineapple,tropical,"animals,misc",yellow +212121,https://live.staticflickr.com/65535/48960621152_d3bf89ee82_o.jpg,Peach Round Purse,peach,,bags,pink +222,https://live.staticflickr.com/65535/48960621262_cb145abde8.jpg,Kiwi Chair,kiwi,,furniture,green +111111,https://live.staticflickr.com/65535/48959884388_d37bb76057.jpg,Banana Blue Bedding,banana,tropical,bedding,"blue,yellow" +111,https://live.staticflickr.com/65535/48959884393_6a1cc0090d.jpg,Mango Lotion,mango,tropical,lotion, +777,https://live.staticflickr.com/65535/48960621172_f251374b08_o.jpg,Mango Sandals,mango,tropical,shoes,"green,orange" +131313,https://live.staticflickr.com/65535/48960434896_a309854f2f_b.jpg,Takes Two to Mango Shirt,mango,tropical,clothing, +161616,https://live.staticflickr.com/65535/48959884428_46063f5226_b.jpg,Pineapple Shoes,pineapple,tropical,shoes,yellow +141414,https://live.staticflickr.com/65535/48959884443_3251f82037_o.jpg,Pineapple Soft Purse,pineapple,tropical,bags,yellow +151515,https://live.staticflickr.com/65535/48960624097_7dde7b850b_o.jpg,Lemon Soap Dispenser,lemon,citrus,kitchen,yellow +999,https://live.staticflickr.com/65535/48960621252_589ddeebc0_o.jpg,Kiwi Sunglasses,kiwi,,sunglasses,green +444,https://live.staticflickr.com/65535/48960434961_9891b61a5c.jpg,Strawberry Sunglasses,strawberry,berry,sunglasses,"red,green" +666,https://live.staticflickr.com/65535/48959884498_b8f195f4a3_o.jpg,Kiwi Shirt,kiwi,,clothing,green +333,https://live.staticflickr.com/65535/48960434971_a1cc825a0d_o.jpg,Simple Strawberry Mug,strawberry,berry,"mugs,kitchen","red,pink" +212121,https://live.staticflickr.com/65535/48959884513_b170ff44a5_o.jpg,Cantaloupe Earrings,cantaloupe,,earrings,orange +212121,https://live.staticflickr.com/65535/48959884523_27945ed347_o.jpg,Kiwi Soap Dispenser,kiwi,,soapdispenser,green +555,https://live.staticflickr.com/65535/48960434996_3637bb44b6_o.jpg,Apple Soap Dispenser,apple,,soapdispenser,red +444,https://live.staticflickr.com/65535/48959884548_86e9e46604_o.jpg,Watermelon Pot,watermelon,,kitchen,green +666,https://live.staticflickr.com/65535/48960435021_8b5f813eb8_o.jpg,Kiwi Neck Pillow,kiwi,,misc,green +333,https://live.staticflickr.com/65535/48960621347_d6f7a1a211_o.jpg,Orange Costume,orange,citrus,costumes,orange +212121,https://live.staticflickr.com/65535/48959884578_2ea5cdca86_o.jpg,Fuzzy Stuffed Peach,peach,,toys,pink +999,https://live.staticflickr.com/65535/48960621447_38d4029b90_o.png,Green Stuffed Kiwi Haird Friends,kiwi,,toys,green +333,https://live.staticflickr.com/65535/48959884663_ff712e37da_o.png,Kiwi Guitar,kiwi,,insturments,green +111111,https://live.staticflickr.com/65535/48960621497_39f5464c65_o.png,Avocado Guitar,avocado,,insturments,green +191919,https://live.staticflickr.com/65535/48960621587_f6a6ef585d_o.png,Dragonfruit Container,dragonfruit,tropical,misc,pink +222222,https://live.staticflickr.com/65535/48959884848_542b1ab4b1_o.png,Dragonfruit Bedding,dragonfruit,tropical,bedding, +181818,https://live.staticflickr.com/65535/48960621762_fb5d0740db_b.jpg,Dragonfruit Art,dragonfruit,tropical,misc,"blue,pink" +191919,https://live.staticflickr.com/65535/48960622017_46ae4287c2_o.jpg,Pineapple Bedding,pineapple,tropical,bedding, +171717,https://live.staticflickr.com/65535/48960435431_e04be8078e_o.png,Watermelon Cushion,watermelon,,furniture,green +161616,https://live.staticflickr.com/65535/48960435466_410ef75940_o.png,Avocado Hand Held Stuffed,avocado,,toys,green +555,https://live.staticflickr.com/65535/48960621887_74a26de8fa_o.png,Fruit Stuffed Pillows,,,bedding, +161616,https://live.staticflickr.com/65535/48959885183_bb0139729f_o.png,Red Strawberry Fanta,strawberry,berry,drinks,red +555,https://live.staticflickr.com/65535/48960621992_1da3ba550c_b.jpg,Banana Dog Costume,banana,tropical,"animals,costumes",yellow +161616,https://live.staticflickr.com/65535/48960435761_aacea68829_o.jpg,Artisan Peach Earrings,peach,,earrings,orange +141414,https://live.staticflickr.com/65535/48960622042_31a7e48773_o.jpg,Watermelon Dooramt,watermelon,,misc,red +777,https://live.staticflickr.com/65535/48960622062_eba6bdb82d.jpg,Green Grape Costume,grapes,,costumes,green +181818,https://live.staticflickr.com/65535/48960624167_7744aaf844_o.jpg,Fruit Frenzy Game,,,games, +151515,https://live.staticflickr.com/65535/48959887528_9935b66656.jpg,White Banana Socks,banana,tropical,socks,yellow +161616,https://live.staticflickr.com/65535/48960622072_06dc0105a5_o.jpg,Grape Dog Costume,grapes,,"animals,costumes",purple +242424,https://live.staticflickr.com/65535/48960435786_07fdf93f35_o.jpg,Watermelon Soap Dispenser,watermelon,,soapdispenser,red +777,https://live.staticflickr.com/65535/48960435791_77730d71a7_o.jpg,Blue Banana Socks,banana,tropical,socks,"blue,yellow" +222222,https://live.staticflickr.com/65535/48959885383_5f0130506a.jpg,Pineapple Hello Kitty,pineapple,tropical,toys,yellow +121212,https://live.staticflickr.com/65535/48960622107_0dbcb01505.jpg,Peach Squeeze Lotion,peach,,lotion,"pink,orange" +999,https://live.staticflickr.com/65535/48960435826_ac03bd4837_o.jpg,Orange Cushion,orange,citrus,furniture,orange +111,https://live.staticflickr.com/65535/48960435841_e50bbba962.jpg,Orange Citrus Shirt,orange,citrus,clothing,orange +131313,https://live.staticflickr.com/65535/48960435861_9c781cc0aa.jpg,Citrus Sparkly Purse,,citrus,bags,green +555,https://live.staticflickr.com/65535/48960435886_169922a058_o.jpg,Orange You Glad to See Me Shirt,orange,citrus,clothing,orange +252525,https://live.staticflickr.com/65535/48960622212_bf86671ee3_o.jpg,Bananagrams Game,banana,tropical,games,yellow +444,https://live.staticflickr.com/65535/48959885553_0c2aab3f92.jpg,Avocado Pack,avocado,,bags, +121212,https://live.staticflickr.com/65535/48960435901_0c2d8fea13_o.jpg,Banana Toothbrush,banana,tropical,misc,yellow +161616,https://live.staticflickr.com/65535/48960624342_fb16d29c06_o.jpg,Banana Cutter,banana,tropical,kitchen,yellow +555,https://live.staticflickr.com/65535/48959885508_077b1b4122_o.jpg,Banana Knit Slippers,banana,tropical,shoes,yellow +161616,https://live.staticflickr.com/65535/48959885523_8bfe1ee421_o.jpg,Banana Chair,banana,tropical,furniture,yellow +242424,https://live.staticflickr.com/65535/48960435936_5a26a2eaca_o.jpg,Avocado Wallet,avocado,,bags,green +181818,https://live.staticflickr.com/65535/48959885548_a40551c4ed_o.jpg,Avocado Pencil Sharpener,avocado,,misc,green +161616,https://live.staticflickr.com/65535/48960622262_b870203ef9_o.jpg,Avocado Backpack,avocado,,bags,green +161616,https://live.staticflickr.com/65535/48960622297_22e3e714f9_o.jpg,Wood Apple Cutting Board,apple,,kitchen, +555,https://live.staticflickr.com/65535/48959885593_4af92f825e.jpg,Peach Katy Perry Sandals,peach,,shoes,pink +131313,https://live.staticflickr.com/65535/48960435976_5fcd131c70_o.jpg,Banana Shorts,banana,tropical,clothing,yellow +666,https://live.staticflickr.com/65535/48960622312_ee6c6b39bb.jpg,Pineapple Sunglasses,pineapple,tropical,sunglasses,yellow +161616,https://live.staticflickr.com/65535/48960622382_66b00214d6.jpg,Papaya Costumes,,tropical,costumes,pink +141414,https://live.staticflickr.com/65535/48960622582_0932637cda_o.jpg,Peach Oven Mit Set,peach,,kitchen,"pink,orange" +232323,https://live.staticflickr.com/65535/48959885843_6ca9cd7d39.jpg,Mango Mandarin Lotion,"mango,orange",tropical,lotion,orange +444,https://live.staticflickr.com/65535/48959885933_981fd0d526.jpg,Apple Lotion,apple,,lotion,red +232323,https://live.staticflickr.com/65535/48960436306_319f1f7427_o.jpg,Peach Leather Purse,peach,,purses,pink +161616,https://live.staticflickr.com/65535/48960436326_bd649fce0d_o.jpg,Fuzzy Feelings Peach Mug,peach,,"mugs,kitchen",pink +202020,https://live.staticflickr.com/65535/48960622802_40947f3e06.jpg,Funny Banana Sweatshirt,banana,,clothing,"blue,yellow" +252525,https://live.staticflickr.com/65535/48960436386_b2c6c9f085.jpg,Banana Earrings,banana,,, +151515,https://live.staticflickr.com/65535/48960622907_053717bc8a.jpg,Stuffed Lemon,lemon,citrus,toys,yellow +222222,https://live.staticflickr.com/65535/48959886133_8b276c2b8a_w.jpg,Watermelon Earrings,watermelon,,earrings,red +232323,https://live.staticflickr.com/65535/48959886198_0bf757b407.jpg,Peach Wallet,peach,,bags,"orange,green" +444,https://live.staticflickr.com/65535/48959886223_5c0fd22fd7.jpg,Watermelon Mugs,watermelon,,"kitchen,mugs","red,green" +444,https://live.staticflickr.com/65535/48960623037_c251b250a5.jpg,Banana Lotion,banana,tropical,lotion,yellow +252525,https://live.staticflickr.com/65535/48960436561_c00f65d5ca.jpg,Watermelon Sunglasses,watermelon,,"sunglasses,accessories",red +222,https://live.staticflickr.com/65535/48960436596_7e7793b776.jpg,Pineapple Stuffed Toy,pineapple,tropical,toys,yellow +161616,https://live.staticflickr.com/65535/48960436631_f9f3a25d1c_o.png,Avocado Fuzzy Stuffed Friend,avocado,,toys,green +888,https://live.staticflickr.com/65535/48960623172_24bd5d01ec_o.jpg,Kiwi Keychain,kiwi,,misc,green +101010,https://live.staticflickr.com/65535/48959886478_80aba86e51.jpg,Stuffed Apple Toy,apple,,toys,red +191919,https://live.staticflickr.com/65535/48960436716_26430892a8.jpg,Watermelon Dog Costume,watermelon,,"costumes,animals","red,green" +191919,https://live.staticflickr.com/65535/48960623327_f12062d3f3.jpg,Pineapple Sweatshirt,pineapple,tropical,clothing,yellow +181818,https://live.staticflickr.com/65535/48960436791_8eab292959.jpg,Kiwi Shorts,kiwi,tropical,clothing,green +252525,https://live.staticflickr.com/65535/48960436831_a5447dafdb_o.jpg,Banana Sweatshirt,banana,,clothing,purple +222,https://live.staticflickr.com/65535/48959886623_7c611a48a9_o.jpg,Peach Sweatshirt,peach,,clothing,orange +222,https://live.staticflickr.com/65535/48959886673_5514dd4eb2.jpg,Pineapple Costume,pineapple,tropical,"clothing,costume",yellow +777,https://live.staticflickr.com/65535/48960623482_fdd88125cf_o.jpg,Peach Coin Purse,peach,,purse, +202020,https://live.staticflickr.com/65535/48959886743_126de4e62c.jpg,Lemon Shorts,lemon,citrus,clothing,yellow +111111,https://live.staticflickr.com/65535/48960623592_03e48683b0.jpg,Banana Leggings,banana,tropical,clothing,"blue,yellow" +222,https://live.staticflickr.com/65535/48959886813_215815cd86_o.jpg,Peach Leggings,peach,,clothing,"white,orange" +252525,https://live.staticflickr.com/65535/48960623657_50bf6a7cb4_o.jpg,Kiwi Leggings,kiwi,,clothing,green +121212,https://live.staticflickr.com/65535/48959886853_df0f3df4f6_o.jpg,Kiwi Mug,kiwi,tropical,kitchen,green +191919,https://live.staticflickr.com/65535/48960623682_7270044093_o.jpg,Apple Hello Kitty Toy,apple,,toys,red +222,https://live.staticflickr.com/65535/48960623717_495a3fba84_o.jpg,Mango Stuffed Friend,mango,tropical,toys,yellow +242424,https://live.staticflickr.com/65535/48959886978_aa60a3918f_o.jpg,50 Shades of Avocado,avocado,,books, +888,https://live.staticflickr.com/65535/48960623797_9f6e6bdfb8_o.jpg,Apple Sunglasses,apple,,"sunglasses,accessories",red +212121,https://live.staticflickr.com/65535/48960623857_64d606e624.jpg,Peach Earrings,peach,,"earrings,accessories",orange +222222,https://live.staticflickr.com/65535/48960437396_e39b37176f.jpg,Mango Earrings,mango,tropical,"earrings,accessories", +242424,https://live.staticflickr.com/65535/48959887138_69598f829c.jpg,Avocado Dog Costume,avocado,,"animals,costumes",green +222,https://live.staticflickr.com/65535/48959887033_8ee927e4de.jpg,Peach Lotion,peach,tropical,lotion, \ No newline at end of file diff --git a/db/seed_data/users.csv b/db/seed_data/users.csv new file mode 100644 index 0000000000..0fb2deec69 --- /dev/null +++ b/db/seed_data/users.csv @@ -0,0 +1,27 @@ +uid,merchant_name,email,provider,username +111,Abigail Apple,a_abigail@email.com,github,AppleAbigail +222,Banana Bob,b_bob@email.com,github,BananaBob +333,Cantalope Candice,c_candice@email.com,github,CantalopeCandice +444,Durian Daniel,d_daniel@email.com,github,DurianDaniel +555,Elderberry Emily,e_emily@email.com,github,ElderberryEmily +666,Fig Frannie,f_frannie@email.com,github,FigFrannie +777,Grapefruit Gus,g_gus@email.com,github,GrapefruitGus +888,Honeydew Hannah,h_hannah@email.com,github,HoneydewHannah +999,Indian Prune Ivana,i_ivana@email.com,github,IndianIvana +101010,Jackfruit Jack,j_jack@email.com,github,JackfruitJack +111111,Kiwi Karen,k_karen@email.com,github,KiwiKaren +121212,Lychee Lindsay,l_lindsay@email.com,github,LycheeLindsay +131313,Mango Mandy,m_mandy@email.com,github,MangoMandy +141414,Nectarine Nadine,n_nadine@email.com,github,NectarineNadine +151515,Orange Oliver,o_oliver@email.com,github,OrangeOliver +161616,Papaya Pete,p_pete@email.com,github,PapayaPete +171717,Queen Anne Cherry,q_cherry@email.com,github,QueenCherry +181818,Raspberry Ramone,r_ramone@email.com,github,RaspberryRamone +191919,Strawberry Steve,s_steve@email.com,github,StrawberrySteve +202020,Tangerine Tanya,t_tanya@email.com,github,TangerineTanya +212121,Ugli Fruit Ulma,u_ulma@email.com,github,UgliUlma +222222,Vanilla Bean Venessa,v_venessa@email.com,github,VanillaVenessa +232323,Watermelon Walter,w_walter@email.com,github,WatermelonWalter +242424,Xigua Xinran,x_xinran@email.com,github,XiguaXinran +252525,Yangmei Yoel,y_yoel@email.com,github,YangmeiYoel +262626,Zuchinni Zach,z_zach@email.com,github,ZuchinniZach \ No newline at end of file diff --git a/db/seeds.rb b/db/seeds.rb new file mode 100644 index 0000000000..301d45bd67 --- /dev/null +++ b/db/seeds.rb @@ -0,0 +1,128 @@ +require 'csv' + +USER_FILE = Rails.root.join('db', 'seed_data', 'users.csv') +puts "Loading raw user data from #{USER_FILE}" + +user_failures = [] +CSV.foreach(USER_FILE, :headers => true) do |row| + user = User.new + user.uid = row['uid'] + user.merchant_name = row['merchant_name'] + user.email = row['email'] + user.provider = row['provider'] + user.username = row['username'] + successful = user.save + if !successful + user_failures << user + puts "Failed to save user: #{user.inspect}" + else + puts "Created user: #{user.inspect}" + end +end + +puts "Added #{User.count} user records" +puts "#{user_failures.length} users failed to save" + +PRODUCTS_FILE = Rails.root.join('db', 'seed_data', 'products.csv') +puts "Loading raw product data from #{PRODUCTS_FILE}" + +product_failures = [] +CSV.foreach(PRODUCTS_FILE, :headers => true) do |row| + product = Product.new + product.img_url = row['img_url'] + product.name = row['name'] + product.description = "Here is a fun description about this fruit themed product!" + product.price = rand(1..100) + product.stock = rand(1..100) + + user = User.find_by(uid: row['merchant'] ) + product.user_id = user.id + + if (row['fruit']) + fruits = (row['fruit']).split(",") + fruits.each do |fruit| + cat = Category.find_by(name: fruit) + if cat + product.categories << cat + else + cat = Category.new(name: fruit, category_type: "fruit") + if cat.save + puts "Created category: #{cat.inspect}" + product.categories << cat + else + puts "Failed to save category: #{cat.inspect}" + end + end + end + end + + if (row['fruit_theme']) + fruit_themes = (row['fruit_theme']).split(",") + fruit_themes.each do |theme| + cat = Category.find_by(name: theme) + if cat + product.categories << cat + else + cat = Category.new(name: theme, category_type: "theme") + if cat.save + puts "Created category: #{cat.inspect}" + product.categories << cat + else + puts "Failed to save category: #{cat.inspect}" + end + end + end + end + + if (row['category']) + categories = (row['category']).split(",") + categories.each do |category| + cat = Category.find_by(name: category) + if cat + product.categories << cat + else + cat = Category.new(name: category, category_type: "category") + if cat.save + puts "Created category: #{cat.inspect}" + product.categories << cat + else + puts "Failed to save category: #{cat.inspect}" + end + end + end + end + + if (row['color']) + colors = (row['color']).split(",") + colors.each do |color| + cat = Category.find_by(name: color) + if cat + product.categories << cat + else + cat = Category.new(name: color, category_type: "color") + if cat.save + puts "Created category: #{cat.inspect}" + product.categories << cat + else + puts "Failed to save category: #{cat.inspect}" + end + end + end + end + + successful = product.save + if !successful + product_failures << product + puts "Failed to save product: #{product.inspect}" + else + puts "Created product: #{product.inspect}" + end +end + + +puts "Manually resetting PK sequence on each table" +ActiveRecord::Base.connection.tables.each do |t| + ActiveRecord::Base.connection.reset_pk_sequence!(t) +end + +puts "done" 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..1e43a7af7a --- /dev/null +++ b/public/404.html @@ -0,0 +1,66 @@ + + + + The page you were looking for doesn't exist (404) + + + + + + +
+
+ +

The page you were looking for doesn't exist.

+
+
+ + 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/homepages_controller_test.rb b/test/controllers/homepages_controller_test.rb new file mode 100644 index 0000000000..4cab426bea --- /dev/null +++ b/test/controllers/homepages_controller_test.rb @@ -0,0 +1,10 @@ +require "test_helper" + +describe HomepagesController do + describe "index" do + it "gives back a successful response" do + get root_path + must_respond_with :success + 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..b354328283 --- /dev/null +++ b/test/controllers/order_items_controller_test.rb @@ -0,0 +1,206 @@ +require "test_helper" + +describe OrderItemsController do + describe "create" do + before do + @product = Product.first + end + + it "successfully creates a new order item, if given valid params, and responds with a redirect" do + order_items_hash = { + order_item: { + quantity: 1 + } + } + + expect { + post product_order_items_path(@product.id), params: order_items_hash + }.must_differ 'OrderItem.count', 1 + + must_respond_with :redirect + assert_equal "#{@product.name} successfully added to your basket! (quantity: #{order_items_hash[:order_item][:quantity]})", flash[:success] + end + + it "does not create a new oder item if given invalid params and responds with a redirect" do + order_items_hash = { + order_item: { + quantity: 0 + } + } + + expect { + post product_order_items_path(@product.id), params: order_items_hash + }.wont_differ 'OrderItem.count' + + must_respond_with :redirect + assert_equal "#{@product.name} was not added to your basket.", flash[:error] + end + + it "does not create a new order item if the product does not exit and responds with a 404" do + product_id = -1 + order_items_hash = { + order_item: { + quantity: 0 + } + } + + expect { + post product_order_items_path(product_id), params: order_items_hash + }.wont_differ 'OrderItem.count' + + must_respond_with :not_found + assert_equal "Product no longer exists.", flash[:error] + end + + it "does not create a new order item if the quantity entered is greater than the product stock" do + product = products(:strawberry_shoes) + expect(product.stock).must_equal 2 + + order_item_hash = { + order_item: { + quantity: 7 + } + } + + expect { + post product_order_items_path(product.id), params: order_item_hash + }.wont_differ 'OrderItem.count' + + must_respond_with :redirect + assert_equal "Quantity entered (#{order_item_hash[:order_item][:quantity]}) is greater than available stock for #{product.name}.", flash[:error] + end + + it "does not create a new order item if the current order already contains an order item with the same product" do + OrderItem.destroy_all + product = products(:lemon_shirt) + product_id = product.id + order_item_hash = { + order_item: { + quantity: 1 + } + } + post product_order_items_path(product_id), params: order_item_hash + order = Order.last + + + order_item_hash_2 = { + order_item: { + quantity: 2 + } + } + + expect { + post product_order_items_path(product_id), params: order_item_hash_2 + }.wont_differ 'OrderItem.count' + + order_item = OrderItem.last + expect(order.order_items.length).must_equal 1 + expect(order_item.quantity).must_equal 3 + expect(order_item.product.name).must_equal product.name + end + end + + describe "update" do + before do + @order_item = OrderItem.first + end + + it "can update an existing order item accurately and redirects to the cart path" do + id = @order_item.id + + updated_order_item_hash = { + order_item: { + quantity: 7 + } + } + expect(@order_item.quantity).wont_equal updated_order_item_hash[:order_item][:quantity] + + expect { + patch order_item_path(id), params: updated_order_item_hash + }.wont_differ "OrderItem.count" + + expect(OrderItem.find_by(id: id).quantity).must_equal updated_order_item_hash[:order_item][:quantity] + must_redirect_to cart_path + assert_equal "#{@order_item.product.name} successfully updated!", flash[:success] + end + + it "does not update the order item if given invalid params and redirects to the cart path" do + id = @order_item.id + + invalid_order_item_hash = { + order_item: { + quantity: "a lot" + } + } + + expect { + patch order_item_path(id), params: invalid_order_item_hash + }.wont_differ "OrderItem.count" + + must_redirect_to cart_path + assert_equal "Could not update quantity for #{@order_item.product.name}.", flash[:error] + end + + it "does not update the order item if the quantity entered is greater than the product stock" do + product = products(:strawberry_shoes) + expect(product.stock).must_equal 2 + + order_item = order_items(:order_item_2) + id = order_item.id + + order_item_hash = { + order_item: { + quantity: 7 + } + } + + expect { + patch order_item_path(id), params: order_item_hash + }.wont_differ "OrderItem.count" + + must_redirect_to cart_path + assert_equal "Quantity entered (#{order_item_hash[:order_item][:quantity]}) is greater than available stock for #{product.name}.", flash[:error] + end + end + + describe "destroy" do + before do + @order_item = OrderItem.last + end + + it "successfully deletes an existing order item and redirects to the cart path" do + order_item = @order_item + id = order_item.id + + expect{ + delete order_item_path(id) + }.must_differ "OrderItem.count", -1 + + assert_nil(OrderItem.find_by(id: id)) + must_redirect_to cart_path + assert_equal "#{order_item.product.name} successfully removed from your basket!", flash[:success] + end + + it "redirects to the cart path and deletes no order items if the order item does not exist" do + invalid_id = -1 + + expect{ + delete order_item_path(invalid_id) + }.wont_differ "OrderItem.count" + + must_redirect_to cart_path + end + + it "redirects to the cart path and deletes no order items if the order item has already been deleted" do + id = @order_item.id + + OrderItem.destroy(id) + + expect{ + delete order_item_path(id) + }.wont_differ "OrderItem.count" + + must_redirect_to cart_path + 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..99156c81af --- /dev/null +++ b/test/controllers/orders_controller_test.rb @@ -0,0 +1,291 @@ +require "test_helper" + +describe OrdersController do + describe "show action" do + it "responds with a success when an order id given exists and the logged in user has products in this order" do + order = orders(:order_1) + user = users(:ada) + perform_login(user) + + get order_path(order.id) + must_respond_with :success + end + + it "responds with a redirect when an order id given exists and the logged in user didn't sell products in this order" do + order = orders(:order_1) + user = users(:betsy) + perform_login(user) + + get order_path(order.id) + must_redirect_to root_path + end + + it "responds with a not_found when id given does not exist" do + user = users(:betsy) + perform_login(user) + order_id = -10000 + + get order_path(order_id) + must_respond_with :not_found + end + end + + describe "cart action" do + it "gives back a successful response" do + product = products(:lemon_shirt) + product_id = product.id + order_item_hash = { + order_item: { + quantity: 1 + } + } + post product_order_items_path(product_id), params: order_item_hash + + get cart_path + must_respond_with :success + end + end + + describe "checkout action" do + before do + product = products(:lemon_shirt) + @product_id = product.id + @order_item_hash = { + order_item: { + quantity: 1 + } + } + end + + it "gives back a successful response if there are some items in the cart" do + post product_order_items_path(@product_id), params: @order_item_hash + + get checkout_path + + must_respond_with :success + end + + it "responses with redirect if no item is in the cart" do + post product_order_items_path(@product_id), params: @order_item_hash + + OrderItem.destroy_all + + get checkout_path + + must_redirect_to root_path + assert_equal "No item in the cart! Please add some items then checkout!", flash[:error] + end + + it "gives back a 404 response if order doesn't exist" do + post product_order_items_path(@product_id), params: @order_item_hash + + OrderItem.destroy_all + Order.destroy_all + + get checkout_path + + must_respond_with :not_found + end + end + + describe "update_paid action" do + let(:order){ + Order.create(status: "pending") + } + + let(:payment_params){ + { + order: { + name: "Gretchen Wieners", + email: "so_fetch@aol.com", + address: "124 Main Street", + cc_name: "Dave Wieners", + cc_last4: 6666, + cc_exp: "12/23", + cc_cvv: 365, + billing_zip: '98122' + } + } + } + + let(:empty_payment_params){ + { + order: { + name: nil, + email: nil, + address: nil, + cc_name: nil, + cc_last4: nil, + cc_exp: nil, + cc_cvv: nil, + billing_zip: nil + } + } + } + + it "updates the order information and changes the order status to paid, then redirects to confirmation page" do + order.save + + expect{ + patch order_path(order.id), params: payment_params + }.must_differ "Order.count", 0 + + find_order = Order.find_by(id: order.id) + + payment_params[:order].each do |k, v| + expect(find_order[k]).must_equal v + end + + expect(find_order.status).must_equal "paid" + + must_redirect_to confirmation_path + + assert_equal "Order #{find_order.id} purchased successfully!", flash[:success] + end + + it "redirects to the cart path if the params is invalid and doesn't change the order status" do + order.save + + expect{ + patch order_path(order.id), params: empty_payment_params + }.must_differ "Order.count", 0 + + find_order = Order.find_by(id: order.id) + + expect(find_order.status).must_equal "pending" + + must_redirect_to cart_path + + assert_equal "Something went wrong! Order was not placed and your card was not billed.", flash[:error] + end + + it "gives back a 404 response if order id is not found" do + patch order_path(-1), params: payment_params + + must_respond_with :not_found + end + end + + describe "confirmation action" do + before do + product = products(:lemon_shirt) + @product_id = product.id + @order_item_hash = { + order_item: { + quantity: 1 + } + } + end + + let(:payment_params){ + { + order: { + name: "Gretchen Wieners", + email: "so_fetch@aol.com", + address: "124 Main Street", + cc_name: "Dave Wieners", + cc_last4: 6666, + cc_exp: "12/23", + cc_cvv: 365, + billing_zip: '98122' + } + } + } + + it "gives back a successful response if the order is paid" do + post product_order_items_path(@product_id), params: @order_item_hash + order = Order.last + order.status = 'paid' + order.update(payment_params[:order]) + + get confirmation_path + must_respond_with :success + end + + it "gives back a 404 if current order does not exist" do + post product_order_items_path(@product_id), params: @order_item_hash + OrderItem.destroy_all + Order.destroy_all + + get confirmation_path + + must_respond_with :not_found + end + end + + describe "cancel_order action" do + before do + @order = orders(:order_1) + @user = users(:ada) + end + + it "changes the order status to cancelled and gives back a redirect response by logged in merchant who sells products in this order" do + perform_login(@user) + patch cancel_order_path(@order.id) + + find_order = Order.find(@order.id) + expect(find_order.status).must_equal 'cancelled' + + must_redirect_to current_user_path + + assert_equal "Order #{@order.id} has been cancelled successfully!", flash[:success] + end + + it "doesn't change the order status and gives back a redirect response by logged in merchant who doesn't sell products in this order" do + user = users(:gretchen) + perform_login(user) + patch cancel_order_path(@order.id) + + find_order = Order.find(@order.id) + expect(find_order.status).must_equal 'paid' + + must_redirect_to current_user_path + assert_equal "You're not allowed to cancel this order!", flash[:error] + end + + it "gives back a 404 response if order id is not found" do + perform_login(@user) + patch cancel_order_path(-1) + + must_respond_with :not_found + end + end + + describe "complete_order action" do + before do + @order = orders(:order_1) + @user = users(:ada) + end + + it "changes the order status to completed and gives back a redirect response by logged in merchant who sells products in this order" do + perform_login(@user) + patch complete_order_path(@order.id) + + find_order = Order.find(@order.id) + expect(find_order.status).must_equal 'completed' + + must_redirect_to current_user_path + + assert_equal "Order #{@order.id} has been completed successfully!", flash[:success] + end + + it "doesn't change the order status and gives back a redirect response by logged in merchant who doesn't sell products in this order" do + user = users(:gretchen) + perform_login(user) + patch complete_order_path(@order.id) + + find_order = Order.find(@order.id) + expect(find_order.status).must_equal 'paid' + + must_redirect_to current_user_path + assert_equal "You're not allowed to complete this order!", flash[:error] + end + + it "gives back a 404 response if order id is not found" do + perform_login(@user) + patch complete_order_path(-1) + + must_respond_with :not_found + 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..dad66be772 --- /dev/null +++ b/test/controllers/products_controller_test.rb @@ -0,0 +1,235 @@ +require "test_helper" + +describe ProductsController do + let(:product_hash) { + { + product: { + name: "new product", + price: 20.0, + stock: 20, + img_url: "new_img.com", + category_ids: [categories(:strawberry).id], + description: "description of a new product" + } + } + } + + let(:update_product_hash) { + { + product: { + name: "lemon product", + price: 20.0, + stock: 20, + img_url: "new_img.com", + category_ids: [categories(:strawberry).id], + description: "description of a new product" + } + } + } + + let(:invalid_product_hash) { + { + product: { + name: "new product", + price: nil, + stock: nil, + img_url: "new_img.com", + description: "description of a new product" + } + } + } + + describe "not logged in" do + describe "index action" do + it "gives back a successful response when provided no params" do + get products_path + must_respond_with :success + end + + it "gives back a successful response when provided category_id" do + category = categories(:lemon) + get category_products_path(category) + must_respond_with :success + end + + it "gives back a successful response when provided params[:search]" do + category = categories(:lemon) + get products_path, params: {search: 'lemon'} + must_respond_with :success + end + + it "returns 404 response when no category found" do + get category_products_path(-1) + must_respond_with :not_found + end + end + + describe "show action" do + it "responds with a success when id given exists" do + product = products(:lemon_shirt) + get product_path(product.id) + must_respond_with :success + end + + it "responds with a not_found when id given does not exist" do + get product_path(0) + must_respond_with :not_found + end + end + + describe "new action" do + it "redirects user to root path if no merchant logged in" do + get new_product_path + must_redirect_to root_path + end + end + + describe "create action" do + it "cannot create a new product if no merchant logged in, and redirects the user to root path" do + expect { + post products_path, params: product_hash + }.must_differ "Product.count", 0 + + must_redirect_to root_path + end + end + + describe "edit action" do + it "redirects user to root path if no merchant logged in" do + product = products(:lemon_shirt) + + get edit_product_path(product.id) + + must_redirect_to root_path + end + end + + describe "update action" do + it "cannot update a product if no merchant logged in, and redirects the user to the product page" do + existing_product = products(:lemon_shirt) + + expect { + patch product_path(existing_product.id), params: update_product_hash + }.wont_differ "Product.count" + + find_product = Product.find_by(id: existing_product.id) + + expect(find_product.name).must_equal existing_product.name + expect(find_product.price).must_equal existing_product.price + expect(find_product.stock).must_equal existing_product.stock + expect(find_product.img_url).must_equal existing_product.img_url + expect(find_product.description).must_equal existing_product.description + expect(find_product.category_ids.first).must_equal existing_product.categories.first.id + + must_redirect_to root_path + end + end + end + + describe "logged in user" do + before do + @user = users(:ada) + perform_login(@user) + end + + describe "new action" do + it "gives back a successful response if a merchant logged in" do + get new_product_path + must_respond_with :success + end + end + + describe "create action" do + it "creates a new product successfully with valid data by a logged in merchant and redirects to the product page if the user has a merchant name" do + expect { + post products_path, params: product_hash + }.must_differ "Product.count", 1 + + must_redirect_to product_path(Product.find_by(name: "new product")) + end + + it "creates a new product successfully with valid data by a logged in merchant and redirects to the edit user page if the user does not have a merchant name" do + user = User.create( + uid: 357, + email: "supercoolemail@email.com", + provider: "github", + username: "cool_vender" + ) + perform_login(user) + + expect { + post products_path, params: product_hash + }.must_differ "Product.count", 1 + + must_redirect_to edit_user_path + assert_equal "You merchant name is currently empty. Please add a merchant name to list your fruit stand with Fruitsy Merchants.", flash[:message] + end + + it "does not create a new product if given invalid params" do + expect { + post products_path, params: invalid_product_hash + }.wont_differ "Product.count" + + must_respond_with :success + assert_equal "New product was not added. Fix required fields before adding!", flash[:error] + end + end + + describe "edit action" do + it "gives back a successful response if a merchant is logged in" do + product = products(:lemon_shirt) + + get edit_product_path(product.id) + + must_respond_with :success + end + + it "redirects to the root path if given a product that does not exist" do + product_id = -1 + + get edit_product_path(product_id) + + must_redirect_to root_path + end + end + + describe "update action" do + it "updates an existing product successfully by a logged in merchant and redirects to the current user path" do + existing_product = products(:lemon_shirt) + + expect { + patch product_path(existing_product.id), params: update_product_hash + }.wont_differ "Product.count" + + product = Product.find_by(id: existing_product.id) + + expect(product.name).must_equal update_product_hash[:product][:name] + expect(product.price).must_equal update_product_hash[:product][:price] + expect(product.stock).must_equal update_product_hash[:product][:stock] + expect(product.img_url).must_equal update_product_hash[:product][:img_url] + expect(product.description).must_equal update_product_hash[:product][:description] + expect(product.category_ids.first).must_equal update_product_hash[:product][:category_ids].first + + must_redirect_to current_user_path + end + + it "does not update an existing product if given invalid params and redirects to the current user path" do + product = products(:lemon_shirt) + + expect { + patch product_path(product.id), params: invalid_product_hash + }.wont_differ "Product.count" + + product_after = Product.find_by(id: product.id) + + must_redirect_to current_user_path + expect(product_after.name).wont_equal invalid_product_hash[:product][:name] + expect(product_after.price).wont_equal invalid_product_hash[:product][:price] + expect(product_after.stock).wont_equal invalid_product_hash[:product][:stock] + expect(product_after.img_url).wont_equal invalid_product_hash[:product][:img_url] + expect(product_after.description).wont_equal invalid_product_hash[:product][:description] + assert_equal "Something went wrong! Product can not be edited.", flash[:error] + 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..66d2a976c6 --- /dev/null +++ b/test/controllers/reviews_controller_test.rb @@ -0,0 +1,146 @@ +require "test_helper" + +describe ReviewsController do + let(:lemon_shirt) { + products(:lemon_shirt) + } + let(:betsy) { + users(:betsy) + } + + let(:review_hash) { + { + review: { + rating: 2, + title: "Review Title", + description: "description of a new product", + user_id: betsy.id, + product_id: lemon_shirt.id, + } + } + } + + let(:invalid_review_hash) { + { + review: { + rating: 10, + title: 1, + description: "", + user_id: -1, + product_id: lemon_shirt.id, + } + } + } + describe "guest user" do + describe "create action" do + it "creates a new review successfully with valid data, and redirects the user to the product page" do + expect { + post reviews_path, params: review_hash + }.must_differ "Review.count", 1 + + must_redirect_to product_path(lemon_shirt.id) + end + + it "does not create new review when passed invalid data, and redirects user to the product page" do + expect { + post reviews_path, params: invalid_review_hash + }.must_differ "Review.count", 0 + + must_redirect_to product_path(lemon_shirt.id) + end + end + + describe 'destroy action' do + it 'does not destroy a review and redirects to the root path if the user is not logged in' do + review = Review.last + + expect { + delete review_path(review.id) + }.wont_differ "Review.count" + + must_redirect_to root_path + end + end + end + + describe "logged in user" do + before do + @user = users(:betsy) + perform_login(@user) + end + + describe "create action" do + it "does not create a review if the User tries to review their own product and redirects to the product path" do + product = products(:orange_costume) + + b_review_hash = { + review: { + rating: 2, + title: "Review Title", + description: "This product is totally worth $100!", + user_id: betsy.id, + product_id: product.id, + } + } + + expect { + post reviews_path, params: b_review_hash + }.wont_differ "Review.count" + + must_redirect_to product_path(product.id) + assert_equal "You can't review your own product!", flash[:error] + end + + it "does not create a review if the User tries to review the same product twice and redirects to the product path" do + post reviews_path, params: review_hash + + expect { + post reviews_path, params: review_hash + }.wont_differ "Review.count" + + must_redirect_to product_path(lemon_shirt.id) + assert_equal "You can't review a product more than once!", flash[:error] + end + end + + describe "destroy action" do + it 'destroys a review successfully if belongs to current user, and redirects to reviews product page' do + post reviews_path, params: review_hash + review = @user.reviews.first + product = review.product + + expect { + delete review_path(review.id) + }.must_differ "Review.count", -1 + + must_redirect_to product_path(product.id) + end + it 'will not destroy a review if product does not belong to current user, and redirects to reviews product page' do + post reviews_path, params: review_hash + review = @user.reviews.first + product = review.product + + other_user = users(:ada) + perform_login(other_user) + + expect { + delete review_path(review.id) + }.must_differ "Review.count", 0 + + must_redirect_to product_path(product.id) + end + + it 'will not destroy a review if review doesnt exist, and redirects to root path' do + post reviews_path, params: review_hash + review = @user.reviews.first + product = review.product + + expect { + delete review_path(-1) + }.must_differ "Review.count", 0 + + must_redirect_to root_path + 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..e6b606ad56 --- /dev/null +++ b/test/controllers/users_controller_test.rb @@ -0,0 +1,214 @@ +require "test_helper" + +describe UsersController do + + describe "auth_callback" do + it "logs in an existing user and redirects them to the root path" do + user = users(:gretchen) + + expect{ + perform_login(user) + }.wont_change "User.count" + + must_redirect_to root_path + expect(session[:user_id]).must_equal user.id + assert_equal "Welcome back #{user.username}! Enjoy browsing Fruitsy.", flash[:success] + end + + it "logs in a new user and redirects them back to the root path" do + user = User.new( + uid: "465", + email: "queen_mary@marysberries.com", + provider: "github", + username: "merryberry2" + ) + + expect { + perform_login(user) + }.must_differ "User.count", 1 + + user = User.find_by(uid: user.uid) + + must_redirect_to root_path + expect(session[:user_id]).must_equal user.id + assert_equal "Welcome to Fruitsy, #{user.username}!", flash[:success] + end + + it "redirects back to the root path for invalid callbacks" do + expect { + perform_login(User.new) + }.wont_change "User.count" + + must_redirect_to root_path + expect(session[:user_id]).must_be_nil + end + end + + describe "logged in user" do + before do + @user = User.first + perform_login(@user) + end + + describe "current" do + it "responds with success when a user has logged in" do + get current_user_path + + must_respond_with :success + end + end + + describe "show" do + it "responds with success when a user id exists" do + get user_path(users(:ada).id) + + must_respond_with :success + end + + it "responds with a not_found when a users id does not exist" do + get user_path(-1) + + must_respond_with :not_found + end + end + + describe "edit" do + it "can get to the edit page if the user is logged in" do + get edit_user_path + + must_respond_with :success + end + end + + describe "update" do + it "updates an existing user successfully, if logged in, and redirects to current user path" do + user = users(:gretchen) + perform_login(user) + + updated_user_data = { + user: { + uid: user.uid, + merchant_name: "Grapes?", + email: user.email, + provider: user.provider, + username: user.username + } + } + + expect { + patch current_user_path, params: updated_user_data + }.wont_change "User.count" + + expect(User.find_by(id: user.id).merchant_name).must_equal updated_user_data[:user][:merchant_name] + must_redirect_to current_user_path + assert_equal "#{user.username} updated successfully!", flash[:success] + end + + it "will not update an existing user if given invalid params" do + user = users(:ada) + perform_login(user) + updated_user_data = { + user: { + uid: nil, + merchant_name: "Grapes?", + email: nil, + provider: user.provider, + username: nil + } + } + + expect { + patch current_user_path, params: updated_user_data + }.wont_change "User.count" + + expect(User.find_by(id: user.id).uid).wont_be_nil + expect(User.find_by(id: user.id).email).wont_be_nil + expect(User.find_by(id: user.id).username).wont_be_nil + expect(flash[:error]).must_include "Please provide all required fields to edit your account." + end + end + + describe "destroy" do + it "successfully logs out a logged in user" do + expect { + delete logout_path + }.wont_change "User.count" + + must_redirect_to root_path + expect(session[:user_id]).must_be_nil + assert_equal "You are successfully logged out, #{@user.username}!", flash[:success] + end + + it "wont log out a nonexistent user" do + perform_login(User.new) + + expect{delete logout_path}.wont_change "User.count" + must_redirect_to root_path + end + end + end + + describe "logged out / guest user" do + + describe "current" do + it "responds with a redirect to the root path for the current user page" do + get current_user_path + + must_redirect_to root_path + end + end + + describe "show" do + it "responds with success when a user id exists" do + get user_path(users(:ada).id) + + must_respond_with :success + end + + it "responds with a not_found when a users id does not exist" do + get user_path(-1) + + must_respond_with :not_found + end + end + + describe "edit" do + it "does not show an edit page for guest user, responds with a redirect and error message" do + get edit_user_path + + must_redirect_to root_path + assert_equal "You must be logged in to do that.", flash[:error] + end + end + + describe "update" do + it "will redirect to the root path if the user is not logged in" do + user = users(:gretchen) + updated_user_data = { + user: { + uid: user.uid, + merchant_name: "Grapes?", + email: user.email, + provider: user.provider, + username: user.username + } + } + expect { + patch current_user_path, params: updated_user_data + }.wont_change "User.count" + must_redirect_to root_path + assert_equal "You must be logged in to do that.", flash[:error] + end + end + + describe "destroy" do + it "won't log out a user that is not logged in" do + delete logout_path + expect {delete logout_path}.wont_change "User.count" + + must_redirect_to root_path + expect(session[:user_id]).must_be_nil + 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..3390597267 --- /dev/null +++ b/test/fixtures/categories.yml @@ -0,0 +1,7 @@ +lemon: + name: "Lemon" + category_type: "fruit" + +strawberry: + name: "Strawberry" + category_type: "fruit" 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..6d97d233c8 --- /dev/null +++ b/test/fixtures/order_items.yml @@ -0,0 +1,24 @@ +order_item_1: + quantity: 4 + product: lemon_shirt + order: order_1 +order_item_2: + quantity: 1 + product: :strawberry_shoes + order: order_1 +order_item_3: + quantity: 7 + product: banana_sweatshirt + order: order_1 +order_item_4: + quantity: 4 + product: banana_sweatshirt + order: order_2 +order_item_5: + quantity: 1 + product: lemon_shirt + order: order_2 +order_item_6: + quantity: 2 + product: mango_slushie + order: order_3 diff --git a/test/fixtures/orders.yml b/test/fixtures/orders.yml new file mode 100644 index 0000000000..8f373e021a --- /dev/null +++ b/test/fixtures/orders.yml @@ -0,0 +1,30 @@ +order_1: + status: paid + name: Gretchen Wieners + email: so_fetch@aol.com + address: 124 Main Street + cc_name: Dave Wieners + cc_last4: 6666 + cc_exp: 12/23 + cc_cvv: 365 + billing_zip: 98122 +order_2: + status: pending + name: George Bluth + email: always$inthebananastand@bluthbananas.com + address: 345 Sudden Valley + cc_name: George M. Bluth + cc_last4: 7777 + cc_exp: 06/22 + cc_cvv: 888 + billing_zip: 90545 +order_3: + status: cancelled + name: Tommy Pickles + email: reptar@toys.com + address: 242 Toys Lane + cc_name: Tommy Pickles + cc_last4: 3843 + cc_exp: 02/22 + cc_cvv: 982 + billing_zip: 23924 diff --git a/test/fixtures/products.yml b/test/fixtures/products.yml new file mode 100644 index 0000000000..c3ebcfb32c --- /dev/null +++ b/test/fixtures/products.yml @@ -0,0 +1,40 @@ +lemon_shirt: + name: "Lemon Shirt" + price: 25 + stock: 5 + img_url: "https://img.com" + user: ada + description: "Here is a description" + categories: lemon +strawberry_shoes: + name: "Strawberry Shoes" + price: 55 + stock: 2 + img_url: "https://img.com" + user: ada + description: "Here is another description" + categories: strawberry +banana_sweatshirt: + name: "Banana Sweatshirt" + price: 25 + stock: 30 + img_url: http://fakeurl.com + user: ada + description: "Here is another description" + categories: banana +mango_slushie: + name: "mango slushie" + price: 200 + stock: 3 + img_url: http://fakeurl.com + user: betsy + description: "Delicious icy slushie" + categories: mango +orange_costume: + name: "Orange Costume" + price: 100 + stock: 20 + img_url: http://fakeurl.com + user: betsy + description: "It's got crystals." + diff --git a/test/fixtures/reviews.yml b/test/fixtures/reviews.yml new file mode 100644 index 0000000000..c0a7d41de4 --- /dev/null +++ b/test/fixtures/reviews.yml @@ -0,0 +1,18 @@ +bad_review: + rating: 1 + title: "Bad Review" + description: "This product sucks!!" + user: ada + product: lemon_shirt +okay_review: + rating: 3 + title: "Okay Review" + description: "This product is okay!!" + user: ada + product: strawberry_shoes +good_review: + rating: 5 + title: "Good Review" + description: "This product is the best!!" + user: gretchen + product: lemon_shirt diff --git a/test/fixtures/users.yml b/test/fixtures/users.yml new file mode 100644 index 0000000000..748079eb2d --- /dev/null +++ b/test/fixtures/users.yml @@ -0,0 +1,18 @@ +ada: + uid: 1111 + merchant_name: Ada's Apple Abyss + email: ada@fruitstand.com + provider: github + username: ada759 +betsy: + uid: 2222 + merchant_name: The Bluest Berry + email: bbb@blueberry.com + provider: github + username: btimes3 +gretchen: + uid: 3333 + merchant_name: + email: gretchen@fruitstand.com + provider: github + username: gretch_is_fetch 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..172ad1b207 --- /dev/null +++ b/test/helpers/application_helper_test.rb @@ -0,0 +1,79 @@ +require "test_helper" + +describe ApplicationHelper, :helper do + describe "readable date" do + it "returns a string with a date in 'Mon DD, YYYY' format if given a vaild date" do + date = ActiveSupport::TimeZone['UTC'].parse("03/10/2019") + + formatted_date = readable_date(date) + + expect(formatted_date).must_be_kind_of String + expect(formatted_date).must_include "Oct" + end + + it "returns '[unknown]' if given an invalid date" do + invalid_date = "a date" + + formatted_date = readable_date(invalid_date) + + expect(formatted_date).must_be_kind_of String + expect(formatted_date).must_equal "[unknown]" + end + + it "returns '[unknown]' if given nil" do + invalid_date = nil + + formatted_date = readable_date(invalid_date) + + expect(formatted_date).must_be_kind_of String + expect(formatted_date).must_equal "[unknown]" + end + end + + describe "currency format" do + it "returns a string in '$0.00' format if given an integer" do + num = 50 + num_2 = -8 + + formatted_num = currency_format(num) + formatted_num_2 = currency_format(num_2) + + expect(formatted_num).must_be_kind_of String + expect(formatted_num).must_equal "$50.00" + expect(formatted_num_2).must_be_kind_of String + expect(formatted_num_2).must_equal "$-8.00" + end + + it "returns a string in '$0.00' format if given a float" do + num = 5.55 + num_2 = -8.78 + + formatted_num = currency_format(num) + formatted_num_2 = currency_format(num_2) + + expect(formatted_num).must_be_kind_of String + expect(formatted_num).must_equal "$5.55" + expect(formatted_num_2).must_be_kind_of String + expect(formatted_num_2).must_equal "$-8.78" + end + + it "returns nil if given an invalid number" do + value = "7" + value_2 = "!" + + result = currency_format(value) + result_2 = currency_format(value_2) + + expect(result).must_be_nil + end + + it "returns nil if given nil" do + value = nil + + result = currency_format(value) + + expect(result).must_be_nil + end + end + +end 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..10d4c5b163 --- /dev/null +++ b/test/models/category_test.rb @@ -0,0 +1,77 @@ +require "test_helper" + +describe Category do + before do + @category = categories(:strawberry) + end + + it "can be instantiated" do + assert(@category.valid?) + end + + it "will have the required fields" do + [:name, :category_type ].each do |field| + expect(@category).must_respond_to field + end + end + + describe "relationships" do + it "can have many products" do + product = Product.create( + name: "Strawberrt Sunglasses", + price: 5, + stock: 10, + img_url: "https://img.com", + user: users(:ada), + description: "Here is a description" + ) + + @category.products << product + + expect(@category.products.count).must_be :>, 1 + expect(@category.products.first).must_be_instance_of Product + end + end + + describe "validations" do + describe 'name' do + it "must have a name" do + @category.name = nil + + refute(@category.valid?) + expect(@category.errors.messages).must_include :name + expect(@category.errors.messages[:name]).must_include "can't be blank" + end + end + end + + describe 'custom methods' do + describe 'products_by_category' do + it 'returns products for a give cateogry given the string name' do + category = Category.create(name: "lemon", category_type: "fruit") + + Product.create(name:"Lemon Thing", price: 25, stock: 5, img_url:"https://img.com", user: users(:ada), description: "description", category_ids: [category.id]) + lemon_products = Category.products_by_category("lemon") + expect(lemon_products.count).must_equal 1 + + Product.create(name:"Lemon Thing2", price: 25, stock: 5, img_url:"https://img.com", user: users(:ada), description: "description", category_ids: [category.id]) + lemon_products = Category.products_by_category("lemon") + expect(lemon_products.count).must_equal 2 + end + + it 'returns nil if unknown category given' do + category = Category.create(name: "lemon", category_type: "fruit") + Product.create(name:"Lemon Thing", price: 25, stock: 5, img_url:"https://img.com", user: users(:ada), description: "description", category_ids: [category.id]) + lemon_products = Category.products_by_category("invalid") + assert_nil(lemon_products) + end + + it 'returns [] if none in given category' do + category = Category.create(name: "lemon", category_type: "fruit") + lemon_products = Category.products_by_category("lemon") + expect(lemon_products).must_equal [] + end + 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..0f3538bc79 --- /dev/null +++ b/test/models/order_item_test.rb @@ -0,0 +1,115 @@ +require "test_helper" + +describe OrderItem do + before do + @order_items = OrderItem.all + end + + describe "validations" do + it "can be valid" do + @order_items.each do |item| + assert(item.valid?) + end + end + + it "will have the required fields" do + @order_items.each do |item| + [:product_id, :order_id, :quantity ].each do |field| + expect(item).must_respond_to field + end + end + end + + it "requires a quantity greater than 0" do + order_item = OrderItem.first + order_item.quantity = 0 + + refute(order_item.valid?) + end + + it "must have a quantity that is an integer" do + order_item = OrderItem.new(product: Product.first, order: Order.first, quantity: "a lot") + + refute(order_item.valid?) + end + + it "must have a valid product" do + invalid_order_item = OrderItem.new(quantity: 4, product_id: -1, order: Order.first) + + refute(invalid_order_item.valid?) + end + + it "must have a valid order" do + invalid_order_item = OrderItem.new(quantity: 4, product: Product.first, order_id: -1) + + refute(invalid_order_item.valid?) + end + end + + describe "relationships" do + before do + @product = Product.first + @order = Order.last + end + + it "can set the product through 'product'" do + order_item = OrderItem.new(quantity: 2, order: @order) + + order_item.product = @product + + expect(order_item.product_id).must_equal @product.id + end + + it "can set the product through 'product_id'" do + order_item = OrderItem.new(quantity: 2, order: @order) + + order_item.product_id = @product.id + + expect(order_item.product).must_equal @product + end + + it "can set the order through 'order'" do + order_item = OrderItem.new(quantity: 2, product: @product) + + order_item.order = @order + + expect(order_item.order_id).must_equal @order.id + end + + it "can set the order through 'order_id'" do + order_item = OrderItem.new(quantity: 2, product: @product) + + order_item.order_id = @order.id + + expect(order_item.order).must_equal @order + end + end + + describe "custom methods" do + describe "total" do + it "returns the total for each orderitem" do + orderitem = order_items(:order_item_1) + + expect(orderitem.total).must_equal 100 + end + + it "returns 0 for an order item with a quantity of 0" do + order_items(:order_item_1).quantity = 0 + orderitem = order_items(:order_item_1) + expect(orderitem.total).must_equal 0 + end + end + + describe "increase_quantity" do + it "accurately increases the quantity of an existing order item" do + order_item = OrderItem.first + expect(order_item.quantity).must_be :<, 5 + new_quantity = 5 + + order_item.increase_quantity(new_quantity) + + expect(order_item.quantity).must_be :>, 5 + end + end + end +end diff --git a/test/models/order_test.rb b/test/models/order_test.rb new file mode 100644 index 0000000000..455e3462af --- /dev/null +++ b/test/models/order_test.rb @@ -0,0 +1,178 @@ +require "test_helper" + +describe Order do + describe "validations" do + let(:all_orders){Order.all} + + it "can be valid" do + all_orders.each do |order| + assert(order.valid?) + end + end + + it "will have the required fields" do + all_orders.each do |order| + [:status, :name, :email, :address, :cc_name, :cc_last4, :cc_exp, :cc_cvv, :billing_zip].each do |field| + expect(order).must_respond_to field + end + end + end + + it "requires a status to be present" do + order = orders(:order_1) + order.status = nil + refute(order.valid?) + end + + it "requires a name to be present if order status is paid" do + order = orders(:order_1) + order.name = nil + refute(order.valid?) + end + + it "requires an email to be present with @ symbol if order status is paid" do + order = orders(:order_1) + order.email = "aaa" + refute(order.valid?) + end + + it "requires a address to be present if order status is paid" do + order = orders(:order_1) + order.address = nil + refute(order.valid?) + end + + it "requires a cc_name to be present if order status is paid" do + order = orders(:order_1) + order.cc_name = nil + refute(order.valid?) + end + + describe "cc_last4" do + it "requires a cc_last4 to be number if order status is paid" do + order = orders(:order_1) + order.cc_last4 = nil + refute(order.valid?) + expect(order.errors.messages).must_include :cc_last4 + expect(order.errors.messages[:cc_last4]).must_include "is not a number" + end + + it "requires a cc_last4 to be within range of 1000 to 9999 if order status is paid" do + order = orders(:order_1) + order.cc_last4 = 123 + refute(order.valid?) + expect(order.errors.messages).must_include :cc_last4 + expect(order.errors.messages[:cc_last4]).must_include "must be greater than or equal to 1000" + end + end + + it "requires a cc_exp to be present if order status is paid" do + order = orders(:order_1) + order.cc_exp = nil + refute(order.valid?) + end + + describe "cc_cvv" do + it "requires a cc_cvv to be number if order status is paid" do + order = orders(:order_1) + order.cc_cvv = nil + refute(order.valid?) + expect(order.errors.messages).must_include :cc_cvv + expect(order.errors.messages[:cc_cvv]).must_include "is not a number" + end + + it "requires a cc_cvv to be within range of 100 to 9999 if order status is paid" do + order = orders(:order_1) + order.cc_cvv = 1 + refute(order.valid?) + expect(order.errors.messages).must_include :cc_cvv + expect(order.errors.messages[:cc_cvv]).must_include "must be greater than or equal to 100" + end + end + + it "requires a billing zip to be present if order status is paid" do + order = orders(:order_1) + order.billing_zip = nil + refute(order.valid?) + end + end + + describe "relationships" do + it "can have many order items" do + order = orders(:order_1) + order_item1 = order_items(:order_item_1) + order_item2 = order_items(:order_item_2) + + order.order_items << order_item1 + order.order_items << order_item2 + + expect(order.order_items.count).must_be :>=, 0 + + order.order_items.each do |order_item| + expect(order_item).must_be_instance_of OrderItem + end + end + end + + describe "custom methods" do + + describe "not pending" do + it "returns true for an order that is not pending" do + + order = orders(:order_1) + assert(order.not_pending?) + + order.status = "cancelled" + assert(order.not_pending?) + + order.status = "completed" + assert(order.not_pending?) + end + + it "returns false for an order that is pending" do + order = orders(:order_2) + refute(order.not_pending?) + end + end + + describe "contain_orderitems?" do + it "returns true if the current user has a product in an order" do + order = orders(:order_1) + user = users(:ada) + + assert(order.contain_orderitems?(user)) + end + + it "returns false if the current user does not contain products in an order" do + user = users(:gretchen) + order = orders(:order_1) + refute(order.contain_orderitems?(user)) + end + end + + describe "total" do + it "returns the total for all orderitems inside of a paid order" do + order = orders(:order_1) + + expect(order.total).must_equal 330 + end + it "returns the total for all orderitems inside of a pending order" do + order = orders(:order_2) + + expect(order.total).must_equal 125 + end + end + + describe "self.new_order" do + it "creates a new order with the status of 'pending" do + expect{ + Order.new_order + }.must_differ "Order.count", 1 + + order = Order.last + + expect(order.status).must_equal "pending" + end + end + end +end diff --git a/test/models/product_test.rb b/test/models/product_test.rb new file mode 100644 index 0000000000..12917b0623 --- /dev/null +++ b/test/models/product_test.rb @@ -0,0 +1,285 @@ +require "test_helper" + +describe Product do + before do + @product = products(:lemon_shirt) + end + + it "can be instantiated" do + assert(@product.valid?) + end + + it "will have the required fields" do + [:name, :price, :stock, :img_url, :user_id, :categories, :description ].each do |field| + expect(@product).must_respond_to field + end + end + + describe "relationships" do + it "can have many order items" do + product = Product.create( + name: "Orange Soap Dispenser", + price: 20.00, + stock: 15, + img_url: "http:\\fakeurl.com", + user: users(:betsy), + description: "A soap dispenser shaped like an orange." + ) + + product.order_items << OrderItem.create(quantity: 2, product: product, order: Order.first) + product.order_items << OrderItem.create(quantity: 3, product: product, order: Order.last) + + expect(product.order_items.count).must_equal 2 + end + + it "can have many categories" do + expect(@product.categories.count).must_equal 1 + expect(@product.categories.first).must_equal categories(:lemon) + + @product.categories << categories(:strawberry) + expect(@product.categories.count).must_equal 2 + expect(@product.categories.last).must_equal categories(:lemon) + expect(@product.categories.first).must_equal categories(:strawberry) + end + + it "can have one user" do + expect(@product.user).must_equal users(:ada) + end + + it "can have many reviews" do + review1 = reviews(:good_review) + review2 = reviews(:bad_review) + expect(@product.reviews.count).must_equal 2 + expect(@product.reviews).must_include review1 + expect(@product.reviews).must_include review2 + end + end + + describe "validations" do + describe 'name' do + it "must have a name" do + @product.name = nil + + refute(@product.valid?) + expect(@product.errors.messages).must_include :name + expect(@product.errors.messages[:name]).must_include "can't be blank" + end + + it "must be unique in the scope of user_id" do + invalid_product = Product.create(name: "Lemon Shirt", price: 55, stock: 2, img_url: "img.com", user_id: users(:ada).id, description: "Here is another description", category_ids: [categories(:strawberry).id]) + + refute(invalid_product.valid?) + expect(invalid_product.errors.messages).must_include :name + expect(invalid_product.errors.messages[:name]).must_include "has already been taken" + end + + it "must be less than 50 characters" do + @product.name = "This is a supppppppper long product name. It should not be this long, this should just use the description if it's going to be this long." + + refute(@product.valid?) + expect(@product.errors.messages).must_include :name + expect(@product.errors.messages[:name]).must_include "is too long (maximum is 50 characters)" + end + + end + + describe 'price' do + it "must have a numeric price" do + @product.price = nil + + refute(@product.valid?) + expect(@product.errors.messages).must_include :price + expect(@product.errors.messages[:price]).must_include "is not a number" + end + + it "must have a numeric price greater than zero" do + @product.price = 0 + + refute(@product.valid?) + expect(@product.errors.messages).must_include :price + expect(@product.errors.messages[:price]).must_include "must be greater than 0" + end + end + + describe "quantity" do + it "must have a numeric quantity" do + @product.stock = nil + + refute(@product.valid?) + expect(@product.errors.messages).must_include :stock + expect(@product.errors.messages[:stock]).must_include "is not a number" + end + + it "must have a numeric quantity greater or equal to zero" do + @product.stock = -1 + + refute(@product.valid?) + expect(@product.errors.messages).must_include :stock + expect(@product.errors.messages[:stock]).must_include "must be greater than or equal to 0" + end + end + + it "must have a user_id" do + @product.user_id = nil + + refute(@product.valid?) + expect(@product.errors.messages).must_include :user_id + expect(@product.errors.messages[:user_id]).must_include "can't be blank" + end + + it "must have a img_url" do + @product.img_url = nil + + refute(@product.valid?) + expect(@product.errors.messages).must_include :img_url + expect(@product.errors.messages[:img_url]).must_include "can't be blank" + end + + it "must have a description" do + @product.description = nil + + refute(@product.valid?) + expect(@product.errors.messages).must_include :description + expect(@product.errors.messages[:description]).must_include "can't be blank" + end + end + + describe 'custom methods' do + describe 'random_products' do + it 'returns random given number of products' do + product = products(:lemon_shirt) + expect(Product.random_products(1).count).must_equal 1 + product2 = products(:strawberry_shoes) + product3 = products(:banana_sweatshirt) + + random_products = Product.random_products(2) + expect(random_products.count).must_equal 2 + + random_products.each do |product| + expect(product).must_be_instance_of Product + end + end + + it 'returns [] if no products' do + Product.destroy_all + expect(Product.random_products(1)).must_equal [] + end + end + + describe 'deals_under' do + it 'returns products under given price' do + product = products(:lemon_shirt) + product2 = products(:strawberry_shoes) + product3 = products(:banana_sweatshirt) + + expect(Product.deals_under(10).count).must_equal 0 + expect(Product.deals_under(30).count).must_equal 2 + expect(Product.deals_under(100).count).must_equal 3 + + Product.deals_under(100).each do |product| + expect(product).must_be_instance_of Product + end + end + + it 'returns [] if no products' do + Product.destroy_all + expect(Product.deals_under(100)).must_equal [] + end + end + + describe "quantity_available?" do + it "returns false if the orderitem quantity is greater than product stock" do + product = products(:strawberry_shoes) + quantity = product.stock + 1 + expect(product.quantity_available?(quantity)).must_equal false + end + + it "returns true if order item quantity is less than product stock" do + product = products(:strawberry_shoes) + quantity = product.stock + expect(product.quantity_available?(quantity)).must_equal true + end + end + + describe "update quantity" do + it "subtracts a products quantity when it is in a paid order" do + status = "paid" + product = products(:strawberry_shoes) + orderitem_quantity = product.stock + expect(product.update_quantity(orderitem_quantity, status)).must_equal 0 + end + + it "increases a products quantity when it is in a cancelled order" do + status = "cancelled" + product = products(:strawberry_shoes) + orderitem_quantity = product.stock + expect(product.update_quantity(orderitem_quantity, status)).must_equal 4 + end + + it "subtracts quantity in a paid order, and adds it again when the order is cancelled" do + status = "paid" + product = products(:strawberry_shoes) + orderitem_quantity = product.stock + expect(product.update_quantity(orderitem_quantity, status)).must_equal 0 + cancelled_status = "cancelled" + expect(product.update_quantity(orderitem_quantity, cancelled_status)).must_equal 2 + end + end + + describe "average rating" do + it "returns an accurate average rating for a product" do + product = products(:lemon_shirt) + expect(product.reviews.count).must_be :>, 1 + + result = product.avg_rating + expect(result).must_be_instance_of Float + expect(result).must_be_close_to 3.0, 0.01 + end + + it "returns nil if a product has no reviews" do + Review.destroy_all + product = Product.first + + result = product.avg_rating + expect(result).must_be_nil + end + end + + describe "self.active" do + it "returns an array of products that have an active status of true" do + products = Product.active + + products.each do |product| + expect(product.active).must_equal true + end + end + + it "returns an empty array of there are no products that are active" do + OrderItem.destroy_all + Product.destroy_all + + result = Product.active + expect(result).must_be_empty + end + end + + describe "self.search" do + it "returns an array of products that have an active status of true and the product's name includes the search keywords" do + products = Product.search('fruit') + + products.each do |product| + expect(product.active).must_equal true + expect(product.name).must_include 'fruit' + end + end + + it "returns an empty array of there are no products that are found" do + OrderItem.destroy_all + Product.destroy_all + + result = Product.search('nothing') + expect(result).must_be_empty + end + end + end +end diff --git a/test/models/review_test.rb b/test/models/review_test.rb new file mode 100644 index 0000000000..135b95d4ea --- /dev/null +++ b/test/models/review_test.rb @@ -0,0 +1,128 @@ +require "test_helper" + +describe Review do + before do + @review = reviews(:good_review) + end + + it "can be instantiated" do + assert(@review.valid?) + end + + it "will have the required fields" do + [:rating, :title, :description, :user_id, :product_id].each do |field| + expect(@review).must_respond_to field + end + end + + describe "relationships" do + it 'can have a user' do + expect(@review.user).must_equal users(:gretchen) + end + it 'can have a product' do + expect(@review.product).must_equal products(:lemon_shirt) + end + end + + describe "validations" do + + describe 'rating' do + it "must have a rating" do + assert(@review.valid?) + @review.rating = nil + + refute(@review.valid?) + end + + it "rating must be an integer" do + assert(@review.valid?) + @review.rating = 1.5 + + refute(@review.valid?) + end + + it 'rating must be > 1' do + assert(@review.valid?) + @review.rating = -1 + + refute(@review.valid?) + end + + it 'rating must be < 6' do + assert(@review.valid?) + @review.rating = 10 + + refute(@review.valid?) + end + end + + describe 'description' do + it "must have a description" do + assert(@review.valid?) + @review.description = nil + + refute(@review.valid?) + end + + it "description must be less than 350 char" do + assert(@review.valid?) + @review.description = (1..351).to_a.join('') + + refute(@review.valid?) + end + end + + describe 'title' do + it "must have a title" do + assert(@review.valid?) + @review.title = nil + + refute(@review.valid?) + end + + it "title must be less than 150 char" do + assert(@review.valid?) + @review.title = (1..151).to_a.join('') + + refute(@review.valid?) + end + end + + describe 'product id' do + it "must have a product_id" do + assert(@review.valid?) + @review.product_id = nil + + refute(@review.valid?) + end + end + end + + describe "custom methods" do + describe "rating sentiment" do + it "returns nil if rating number is not valid" do + rating = 10000 + result = Review.rating_sentiment(rating) + expect(result).must_be_nil + end + + it "returns negavie if rating number is not valid" do + rating = 1 + result = Review.rating_sentiment(rating) + expect(result).must_equal 'negative' + end + + it "returns nil if rating number is not valid" do + rating = 5 + result = Review.rating_sentiment(rating) + expect(result).must_equal 'positive' + end + + it "returns nil if rating number is not valid" do + rating = 3 + result = Review.rating_sentiment(rating) + expect(result).must_equal 'neutral' + end + end + end +end \ No newline at end of file diff --git a/test/models/user_test.rb b/test/models/user_test.rb new file mode 100644 index 0000000000..4de2cc038e --- /dev/null +++ b/test/models/user_test.rb @@ -0,0 +1,161 @@ +require "test_helper" + +describe User do + describe "validations" do + before do + @users = User.all + end + + it "can be valid" do + @users.each do |user| + assert(user.valid?) + end + end + + it "will have the required fields" do + @users.each do |user| + [:uid, :merchant_name, :email, :provider, :username].each do |field| + expect(user).must_respond_to field + end + end + end + + it "requires a unique uid" do + user = users(:ada) + taken_uid = users(:betsy).uid + user.uid = taken_uid + + refute(user.valid?) + end + + it "requires a unique username" do + user = users(:ada) + taken_username = users(:betsy).username + user.username = taken_username + + refute(user.valid?) + end + + it "requires a unique email address" do + user = users(:ada) + taken_email = users(:betsy).email + user.email = taken_email + + refute(user.valid?) + end + + it "must have a unique merchant name, if present" do + user = users(:ada) + taken_merchant_name = users(:betsy).merchant_name + user.merchant_name = taken_merchant_name + + refute(user.valid?) + end + + it "requires merchant_name to be less than 50 characters" do + user = users(:gretchen) + user.merchant_name = (0...51).map { ('a'..'z').to_a[rand(26)] }.join + + refute(user.valid?) + end + + it "requires an at symbol (@) to be present in the email address" do + user = users(:betsy) + user.email = "bfruitstand.com" + + refute(user.valid?) + end + end + + describe "relationships" do + it "can have many products" do + user = users(:ada) + product_1 = Product.first + product_2 = Product.last + + user.products << product_1 + user.products << product_2 + + expect(user.products.count).must_be :>=, 0 + + user.products.each do |product| + expect(product).must_be_instance_of Product + end + end + + it 'can have many reviews' do + review1 = reviews(:good_review) + review2 = reviews(:okay_review) + user = users(:ada) + + expect(user.reviews.count).must_equal 2 + user.reviews.each do |review| + expect(review).must_be_instance_of Review + end + end + end + + describe "custom methods" do + describe "total earned" do + it "returns the total revenue a user has earned on orders that are completed and/or paid" do + user = users(:ada) + expect(user.total_earned).must_be_instance_of Float + expect(user.total_earned).must_equal 330 + end + + it "returns 0 if the user has not sold any products" do + user = User.create(username: "aaaawooo", email: "werewolf@mail.com", uid: 23542) + expect(user.total_earned).must_equal 0 + end + + it "will not display total earned for orders that are cancelled " do + user = users(:betsy) + expect(user.total_earned).must_equal 0 + end + end + + describe "find order items" do + it "returns an array of all order items belonging to a user" do + user = users(:ada) + expect(user.find_order_items).must_be_instance_of Array + expect(user.find_order_items.first).must_be_kind_of OrderItem + end + + it "contains accurate orderitems for a user" do + user = users(:ada) + order_item = order_items(:order_item_1) + expect(user.find_order_items.first).must_equal order_item + expect(user.find_order_items.first.product.name).must_equal "Lemon Shirt" + end + end + + describe "find products" do + it "finds all products belonging to a user" do + user = users(:ada) + expect(user.find_products.first).must_be_kind_of Product + end + + it "won't return any products if a user has none" do + user = users(:gretchen) + expect(user.find_products.first).must_be_nil + end + end + + describe "filter order items" do + it "returns an array of all order items with a specific order status belonging to an user" do + user = users(:ada) + ["paid", "cancelled", "completed"].each do |status| + expect(user.filter_order_items(status)).must_be_instance_of Array + end + end + + it "contains accurate orderitems for a user" do + user = users(:ada) + order_item = order_items(:order_item_1) + order_items = user.filter_order_items('paid') + expect(order_items.first).must_equal order_item + expect(order_items.first.product.name).must_equal order_item.product.name + end + 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..f3ec0cb6ca --- /dev/null +++ b/test/test_helper.rb @@ -0,0 +1,50 @@ +require 'simplecov' +SimpleCov.start 'rails' do + add_filter 'app/channels/' + add_filter 'app/jobs/' + add_filter 'app/mailers/' + add_filter '/bin/' + add_filter '/db/' + 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 + + + def setup + 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 = User.first) + OmniAuth.config.mock_auth[:github] = OmniAuth::AuthHash.new(mock_auth_hash(user)) + + get auth_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