diff --git a/.DS_Store b/.DS_Store new file mode 100644 index 0000000000..96d1c0a4b7 Binary files /dev/null and b/.DS_Store differ diff --git a/.env b/.env new file mode 100644 index 0000000000..13dfa493bb --- /dev/null +++ b/.env @@ -0,0 +1,2 @@ +GITHUB_CLIENT_ID: 27ec83359222828f81a9 +GITHUB_CLIENT_SECRET: 41dc9cd19938ea508d763c10cbfd1df965c92a93 diff --git a/.gitignore b/.gitignore new file mode 100644 index 0000000000..777a1eedfa --- /dev/null +++ b/.gitignore @@ -0,0 +1,30 @@ +# 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 +.env + +/coverage/* + +# Ignore master key for decrypting credentials and more. +/config/master.key diff --git a/.ruby-version b/.ruby-version new file mode 100644 index 0000000000..25c81fe399 --- /dev/null +++ b/.ruby-version @@ -0,0 +1 @@ +ruby-2.5.1 \ No newline at end of file diff --git a/Gemfile b/Gemfile new file mode 100644 index 0000000000..48a4ae2067 --- /dev/null +++ b/Gemfile @@ -0,0 +1,85 @@ +source 'https://rubygems.org' +git_source(:github) { |repo| "https://github.com/#{repo}.git" } + +ruby '2.5.1' + +# Bundle edge Rails instead: gem 'rails', github: 'rails/rails' +gem 'rails', '~> 5.2.1' +# 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' +gem 'omniauth' +gem 'omniauth-github' + +# 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 +gem 'faker' +group :development, :test do + # Call 'byebug' anywhere in the code to stop execution and get a debugger console + gem 'byebug', platforms: [:mri, :mingw, :x64_mingw] +end + +group :development do + # Access an interactive console on exception pages or by calling 'console' anywhere in the code. + gem 'web-console', '>= 3.3.0' + gem 'listen', '>= 3.0.5', '< 3.2' + # Spring speeds up development by keeping your application running in the background. Read more: https://github.com/rails/spring + gem 'spring' + gem 'spring-watcher-listen', '~> 2.0.0' +end + +group :test do + # Adds support for Capybara system testing and selenium driver + gem 'capybara', '>= 2.15' + gem 'selenium-webdriver' + # Easy installation and use of chromedriver to run system tests with Chrome + gem 'chromedriver-helper' +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 'better_errors' + gem 'binding_of_caller' + gem 'guard' + gem 'guard-minitest' + gem 'dotenv-rails' +end + +group :test do + gem 'minitest-rails' + gem 'minitest-reporters' + gem 'simplecov' +end diff --git a/Gemfile.lock b/Gemfile.lock new file mode 100644 index 0000000000..5ee914de71 --- /dev/null +++ b/Gemfile.lock @@ -0,0 +1,316 @@ +GEM + remote: https://rubygems.org/ + specs: + actioncable (5.2.1) + actionpack (= 5.2.1) + nio4r (~> 2.0) + websocket-driver (>= 0.6.1) + actionmailer (5.2.1) + actionpack (= 5.2.1) + actionview (= 5.2.1) + activejob (= 5.2.1) + mail (~> 2.5, >= 2.5.4) + rails-dom-testing (~> 2.0) + actionpack (5.2.1) + actionview (= 5.2.1) + activesupport (= 5.2.1) + rack (~> 2.0) + rack-test (>= 0.6.3) + rails-dom-testing (~> 2.0) + rails-html-sanitizer (~> 1.0, >= 1.0.2) + actionview (5.2.1) + activesupport (= 5.2.1) + builder (~> 3.1) + erubi (~> 1.4) + rails-dom-testing (~> 2.0) + rails-html-sanitizer (~> 1.0, >= 1.0.3) + activejob (5.2.1) + activesupport (= 5.2.1) + globalid (>= 0.3.6) + activemodel (5.2.1) + activesupport (= 5.2.1) + activerecord (5.2.1) + activemodel (= 5.2.1) + activesupport (= 5.2.1) + arel (>= 9.0) + activestorage (5.2.1) + actionpack (= 5.2.1) + activerecord (= 5.2.1) + marcel (~> 0.3.1) + activesupport (5.2.1) + concurrent-ruby (~> 1.0, >= 1.0.2) + i18n (>= 0.7, < 2) + minitest (~> 5.1) + tzinfo (~> 1.1) + addressable (2.5.2) + public_suffix (>= 2.0.2, < 4.0) + ansi (1.5.0) + archive-zip (0.11.0) + io-like (~> 0.3.0) + arel (9.0.0) + autoprefixer-rails (9.2.1) + execjs + better_errors (2.5.0) + coderay (>= 1.0.0) + erubi (>= 1.0.0) + rack (>= 0.9.0) + bindex (0.5.0) + binding_of_caller (0.8.0) + debug_inspector (>= 0.0.1) + bootsnap (1.3.2) + msgpack (~> 1.0) + bootstrap (4.1.3) + autoprefixer-rails (>= 6.0.3) + popper_js (>= 1.12.9, < 2) + sass (>= 3.5.2) + builder (3.2.3) + byebug (10.0.2) + capybara (3.9.0) + addressable + mini_mime (>= 0.1.3) + nokogiri (~> 1.8) + rack (>= 1.6.0) + rack-test (>= 0.6.3) + xpath (~> 3.1) + childprocess (0.9.0) + ffi (~> 1.0, >= 1.0.11) + chromedriver-helper (2.1.0) + archive-zip (~> 0.10) + nokogiri (~> 1.8) + coderay (1.1.2) + concurrent-ruby (1.0.5) + crass (1.0.4) + debug_inspector (0.0.3) + docile (1.3.1) + dotenv (2.5.0) + dotenv-rails (2.5.0) + dotenv (= 2.5.0) + railties (>= 3.2, < 6.0) + erubi (1.7.1) + execjs (2.7.0) + faker (1.9.1) + i18n (>= 0.7) + faraday (0.15.3) + multipart-post (>= 1.2, < 3) + ffi (1.9.25) + formatador (0.2.5) + globalid (0.4.1) + activesupport (>= 4.2.0) + guard (2.14.2) + 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.5.7) + i18n (1.1.1) + concurrent-ruby (~> 1.0) + io-like (0.3.0) + jbuilder (2.7.0) + activesupport (>= 4.2.0) + multi_json (>= 1.2) + jquery-rails (4.3.3) + 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.1.0) + listen (3.1.5) + rb-fsevent (~> 0.9, >= 0.9.4) + rb-inotify (~> 0.9, >= 0.9.7) + ruby_dep (~> 1.2) + loofah (2.2.2) + 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.0) + mimemagic (0.3.2) + mini_mime (1.0.1) + mini_portile2 (2.3.0) + minitest (5.11.3) + minitest-rails (3.0.0) + minitest (~> 5.8) + railties (~> 5.0) + minitest-reporters (1.3.5) + ansi + builder + minitest (>= 5.0) + ruby-progressbar + msgpack (1.2.4) + multi_json (1.13.1) + multi_xml (0.6.0) + multipart-post (2.0.0) + nenv (0.3.0) + nio4r (2.3.1) + nokogiri (1.8.5) + mini_portile2 (~> 2.3.0) + notiffany (0.1.1) + nenv (~> 0.1) + shellany (~> 0.0) + oauth2 (1.4.1) + faraday (>= 0.8, < 0.16.0) + jwt (>= 1.0, < 3.0) + multi_json (~> 1.3) + multi_xml (~> 0.5) + rack (>= 1.2, < 3) + omniauth (1.8.1) + hashie (>= 3.4.6, < 3.6.0) + rack (>= 1.6.2, < 3) + omniauth-github (1.3.0) + omniauth (~> 1.5) + omniauth-oauth2 (>= 1.4.0, < 2.0) + omniauth-oauth2 (1.5.0) + oauth2 (~> 1.1) + omniauth (~> 1.2) + pg (1.1.3) + popper_js (1.14.3) + pry (0.11.3) + coderay (~> 1.1.0) + method_source (~> 0.9.0) + pry-rails (0.3.6) + pry (>= 0.10.4) + public_suffix (3.0.3) + puma (3.12.0) + rack (2.0.5) + rack-test (1.1.0) + rack (>= 1.0, < 3) + rails (5.2.1) + actioncable (= 5.2.1) + actionmailer (= 5.2.1) + actionpack (= 5.2.1) + actionview (= 5.2.1) + activejob (= 5.2.1) + activemodel (= 5.2.1) + activerecord (= 5.2.1) + activestorage (= 5.2.1) + activesupport (= 5.2.1) + bundler (>= 1.3.0) + railties (= 5.2.1) + sprockets-rails (>= 2.0.0) + rails-dom-testing (2.0.3) + activesupport (>= 4.2.0) + nokogiri (>= 1.6) + rails-html-sanitizer (1.0.4) + loofah (~> 2.2, >= 2.2.2) + railties (5.2.1) + actionpack (= 5.2.1) + activesupport (= 5.2.1) + method_source + rake (>= 0.8.7) + thor (>= 0.19.0, < 2.0) + rake (12.3.1) + rb-fsevent (0.10.3) + rb-inotify (0.9.10) + ffi (>= 0.5.0, < 2) + ruby-progressbar (1.10.0) + ruby_dep (1.5.0) + rubyzip (1.2.2) + sass (3.6.0) + 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.0.7) + railties (>= 4.0.0, < 6) + sass (~> 3.1) + sprockets (>= 2.8, < 4.0) + sprockets-rails (>= 2.0, < 4.0) + tilt (>= 1.1, < 3) + selenium-webdriver (3.14.1) + childprocess (~> 0.5) + rubyzip (~> 1.2, >= 1.2.2) + shellany (0.0.1) + simplecov (0.16.1) + docile (~> 1.1) + json (>= 1.8, < 3) + simplecov-html (~> 0.10.0) + simplecov-html (0.10.2) + spring (2.0.2) + activesupport (>= 4.2) + 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.0) + thread_safe (0.3.6) + tilt (2.0.8) + turbolinks (5.2.0) + turbolinks-source (~> 5.2) + turbolinks-source (5.2.0) + tzinfo (1.2.5) + thread_safe (~> 0.1) + uglifier (4.1.19) + 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.0) + websocket-extensions (>= 0.1.0) + websocket-extensions (0.1.3) + xpath (3.2.0) + nokogiri (~> 1.8) + +PLATFORMS + ruby + +DEPENDENCIES + better_errors + binding_of_caller + bootsnap (>= 1.1.0) + bootstrap (~> 4.1.3) + byebug + capybara (>= 2.15) + chromedriver-helper + dotenv-rails + faker + guard + guard-minitest + jbuilder (~> 2.5) + jquery-rails + jquery-turbolinks + listen (>= 3.0.5, < 3.2) + minitest-rails + minitest-reporters + omniauth + omniauth-github + pg (>= 0.18, < 2.0) + pry-rails + puma (~> 3.11) + rails (~> 5.2.1) + 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.1p57 + +BUNDLED WITH + 1.16.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/.DS_Store b/app/.DS_Store new file mode 100644 index 0000000000..eb41bb41df Binary files /dev/null and b/app/.DS_Store differ diff --git a/app/assets/.DS_Store b/app/assets/.DS_Store new file mode 100644 index 0000000000..f97190ff94 Binary files /dev/null and b/app/assets/.DS_Store differ 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/.DS_Store b/app/assets/images/.DS_Store new file mode 100644 index 0000000000..1b8bb3f585 Binary files /dev/null and b/app/assets/images/.DS_Store differ diff --git a/app/assets/images/.keep b/app/assets/images/.keep new file mode 100644 index 0000000000..e69de29bb2 diff --git a/app/assets/images/1.jpg b/app/assets/images/1.jpg new file mode 100644 index 0000000000..50f686ea88 Binary files /dev/null and b/app/assets/images/1.jpg differ diff --git a/app/assets/images/10.jpg b/app/assets/images/10.jpg new file mode 100644 index 0000000000..ec4659d5c7 Binary files /dev/null and b/app/assets/images/10.jpg differ diff --git a/app/assets/images/2.jpg b/app/assets/images/2.jpg new file mode 100644 index 0000000000..5d5cc55a6c Binary files /dev/null and b/app/assets/images/2.jpg differ diff --git a/app/assets/images/3.jpg b/app/assets/images/3.jpg new file mode 100644 index 0000000000..7a7c0504cd Binary files /dev/null and b/app/assets/images/3.jpg differ diff --git a/app/assets/images/4.jpg b/app/assets/images/4.jpg new file mode 100644 index 0000000000..7238d49ba7 Binary files /dev/null and b/app/assets/images/4.jpg differ diff --git a/app/assets/images/5.jpg b/app/assets/images/5.jpg new file mode 100644 index 0000000000..db6e730b87 Binary files /dev/null and b/app/assets/images/5.jpg differ diff --git a/app/assets/images/6.jpg b/app/assets/images/6.jpg new file mode 100644 index 0000000000..7530e0dab9 Binary files /dev/null and b/app/assets/images/6.jpg differ diff --git a/app/assets/images/7.jpg b/app/assets/images/7.jpg new file mode 100644 index 0000000000..a13a654d23 Binary files /dev/null and b/app/assets/images/7.jpg differ diff --git a/app/assets/images/8.jpg b/app/assets/images/8.jpg new file mode 100644 index 0000000000..3ac20c90b3 Binary files /dev/null and b/app/assets/images/8.jpg differ diff --git a/app/assets/images/9.jpg b/app/assets/images/9.jpg new file mode 100644 index 0000000000..0eb2a5c78a Binary files /dev/null and b/app/assets/images/9.jpg differ diff --git a/app/assets/images/homepage-hero.jpg b/app/assets/images/homepage-hero.jpg new file mode 100644 index 0000000000..fd97e50901 Binary files /dev/null and b/app/assets/images/homepage-hero.jpg differ diff --git a/app/assets/javascripts/application.js b/app/assets/javascripts/application.js new file mode 100644 index 0000000000..4f73c21a7d --- /dev/null +++ b/app/assets/javascripts/application.js @@ -0,0 +1,20 @@ +// This is a manifest file that'll be compiled into application.js, which will include all the files +// listed below. +// +// Any JavaScript/Coffee file within this directory, lib/assets/javascripts, or any plugin's +// vendor/assets/javascripts directory can be referenced here using a relative path. +// +// It's not advisable to add code directly here, but if you do, it'll appear at the bottom of the +// compiled file. JavaScript code in this file should be added after the last require_* statement. +// +// Read Sprockets README (https://github.com/rails/sprockets#sprockets-directives) for details +// about supported directives. + //= require jquery3 + //= require popper + //= require bootstrap-sprockets + +// +//= require rails-ujs +//= require activestorage +//= require turbolinks +//= require_tree . diff --git a/app/assets/javascripts/cable.js b/app/assets/javascripts/cable.js new file mode 100644 index 0000000000..739aa5f022 --- /dev/null +++ b/app/assets/javascripts/cable.js @@ -0,0 +1,13 @@ +// Action Cable provides the framework to deal with WebSockets in Rails. +// You can generate new channels where WebSocket features live using the `rails generate channel` command. +// +//= require action_cable +//= require_self +//= require_tree ./channels + +(function() { + this.App || (this.App = {}); + + App.cable = ActionCable.createConsumer(); + +}).call(this); diff --git a/app/assets/javascripts/categories.js b/app/assets/javascripts/categories.js new file mode 100644 index 0000000000..dee720facd --- /dev/null +++ b/app/assets/javascripts/categories.js @@ -0,0 +1,2 @@ +// Place all the behaviors and hooks related to the matching controller here. +// All this logic will automatically be available in application.js. diff --git a/app/assets/javascripts/channels/.keep b/app/assets/javascripts/channels/.keep new file mode 100644 index 0000000000..e69de29bb2 diff --git a/app/assets/javascripts/home.js b/app/assets/javascripts/home.js new file mode 100644 index 0000000000..dee720facd --- /dev/null +++ b/app/assets/javascripts/home.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_products.js b/app/assets/javascripts/order_products.js new file mode 100644 index 0000000000..dee720facd --- /dev/null +++ b/app/assets/javascripts/order_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/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/sessions.js b/app/assets/javascripts/sessions.js new file mode 100644 index 0000000000..dee720facd --- /dev/null +++ b/app/assets/javascripts/sessions.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/user.js b/app/assets/javascripts/user.js new file mode 100644 index 0000000000..dee720facd --- /dev/null +++ b/app/assets/javascripts/user.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..dbe50582ba --- /dev/null +++ b/app/assets/stylesheets/application.scss @@ -0,0 +1,221 @@ +/* + * This is a manifest file that'll be compiled into application.css, which will include all the files + * listed below. + * + * Any CSS and SCSS file within this directory, lib/assets/stylesheets, or any plugin's + * vendor/assets/stylesheets directory can be referenced here using a relative path. + * + * You're free to add application-wide styles to this file and they'll appear at the bottom of the + * compiled file so the styles you add here take precedence over styles defined in any other CSS/SCSS + * files in this directory. Styles in this file should be added after the last require_* statement. + * It is generally better to create a new file per style scope. + * + */ + +/* Custom bootstrap variables must be set or imported *before* bootstrap. */ +@import "bootstrap"; +/* Import scss content */ +@import "**/*"; + +/* Sovietski color scheme */ +$white: #fefdff; + +$dark-grey: #343a40; +$light-grey: #d1d5d7; + +$dark-red: #b20023; +$light-red: #d6798c; + +$dark-blue: #007ea7; +$light-blue: #5cacc7; + +$dark-yellow: #f3ca40; +$light-yellow: #f7dd85; + + +/* +Google Fonts: +font-family: 'Bungee', cursive; +font-family: 'Bungee Shade', cursive; +font-family: 'Raleway', sans-serif; +*/ + +body { + background-color: $white; + color: $dark-grey; + font-family: 'Raleway', sans-serif; + margin-bottom: 2rem; +} + +article.main-content { + padding-right: 2rem; + padding-left: 2rem; + padding-bottom: 2rem; +} + +/* Material design icon styling */ +/* Rules for sizing the icon. */ +.material-icons.md-18 { font-size: 18px; } +.material-icons.md-24 { font-size: 24px; } +.material-icons.md-36 { font-size: 36px; } +.material-icons.md-48 { font-size: 48px; } + +/* Rules for using icons as black on a light background. */ +.material-icons.md-dark { color: rgba(0, 0, 0, 0.54); } +.material-icons.md-dark.md-inactive { color: rgba(0, 0, 0, 0.26); } + +/* Rules for using icons as white on a dark background. */ +.material-icons.md-light { color: rgba(255, 255, 255, 1); } +.material-icons.md-light.md-inactive { color: rgba(255, 255, 255, 0.3); } + +#sovietski-header { + justify-content: space-between; + padding: 2rem; +} + +h1.sovietski-logo { + text-align: center; +} + +a { + color: $dark-blue; +} + +a:hover { + color: $light-blue; + text-decoration: none; +} + +a.sovietski-logo { + font-family: 'Bungee', cursive; + font-size: 3rem; + color: $dark-grey; + text-decoration: none; + text-align: center; +} + +a.cart-button { + background-color: $dark-yellow; + border-color: $dark-yellow; + color: $dark-grey; + font-weight: bold; +} + +.btn-primary { + background-color: $dark-yellow; + border-color: $dark-yellow; + color: $dark-grey; +} + +.btn-primary:hover, input.btn-primary:hover { + background-color: $light-yellow; + border-color: $light-yellow; + color: $dark-grey; +} + +.btn-primary:not(:disabled):not(.disabled).active { + background-color: $dark-blue; + border-color: $dark-blue; +} + +div.cart-button { + display: flex; + align-content: center; + justify-content: center; +} + +#shopping-cart-icon { + padding-right: 0.5rem; +} + +nav ul { + list-style: none; +} + +.nav-link { + color: $dark-grey; +} + +.nav-link:hover { + color: $dark-yellow; +} + +.dropdown-item:hover { + background-color: $dark-yellow; +} + +li.user-nav { + margin-right: 1rem; +} + +.btn-danger { + background-color: $dark-red; + border-color: $dark-red; + color: $white; +} + +.btn-danger:hover { + background-color: $light-red; + border-color: $light-red; +} + +.btn-secondary { + background-color: $dark-blue; + border-color: $dark-blue; + color: $white; +} + +.btn-secondary:hover { + background-color: $light-blue; + border-color: $light-blue; +} + +.btn-outline-danger { + border-color: $dark-red; + color: $dark-red; +} + +.btn-outline-danger:hover { + background-color: $dark-red; + border-color: $dark-red; + color: $white; +} + +.btn-outline-secondary { + border-color: $dark-blue; + color: $dark-blue; +} + +.btn-outline-secondary:hover { + background-color: $dark-blue; + border-color: $dark-blue; + color: $white; +} + +h5.cart.card-title { + font-weight: bold; +} + +img.homepage-hero-img { + display: block; + width: 100%; +} + +a.login-btn { + margin-right: 0.5rem; +} + +footer { + padding: 1rem; + color: $light-grey; + text-align: center; +} + +footer a { + color: $light-yellow; +} + +footer a:hover { + color: $dark-yellow; + text-decoration: none; +} diff --git a/app/assets/stylesheets/categories.scss b/app/assets/stylesheets/categories.scss new file mode 100644 index 0000000000..b948799c17 --- /dev/null +++ b/app/assets/stylesheets/categories.scss @@ -0,0 +1,3 @@ +// Place all the styles related to the Categorys 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/home.scss b/app/assets/stylesheets/home.scss new file mode 100644 index 0000000000..7131aac4df --- /dev/null +++ b/app/assets/stylesheets/home.scss @@ -0,0 +1,3 @@ +// Place all the styles related to the Home 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_products.scss b/app/assets/stylesheets/order_products.scss new file mode 100644 index 0000000000..60fdc4e2da --- /dev/null +++ b/app/assets/stylesheets/order_products.scss @@ -0,0 +1,11 @@ +// Place all the styles related to the OrderProducts controller here. +// They will automatically be included in application.css. +// You can use Sass (SCSS) here: http://sass-lang.com/ + +form.product-quantity-form > .form-group > * { + margin-right: 0.5rem; +} + +input.form-control.quantity-field { + width: 4rem; +} diff --git a/app/assets/stylesheets/orders.scss b/app/assets/stylesheets/orders.scss new file mode 100644 index 0000000000..89edfc6c29 --- /dev/null +++ b/app/assets/stylesheets/orders.scss @@ -0,0 +1,35 @@ +// 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/ + +div.card-footer.order-product-actions { + display: flex; + flex-direction: row; + justify-content: flex-end; + align-items: center; + flex-wrap: wrap; +} + +.order-product-actions > a.btn { + margin-left: 0.5rem; +} + +article.checkout-actions { + display: flex; + flex-direction: column; + align-items: center; +} + +section.cart { + display: flex; + flex-direction: column; +} + +article.cart.card { + margin-top: 0.5rem; +} + +div.cart.container-fluid { + margin-top: 1rem; + padding: 0; +} diff --git a/app/assets/stylesheets/products.scss b/app/assets/stylesheets/products.scss new file mode 100644 index 0000000000..7a1302c792 --- /dev/null +++ b/app/assets/stylesheets/products.scss @@ -0,0 +1,31 @@ +// 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/ +.product-form { + display: flex; + flex-direction: column; + + margin: 2%; +} + +h4.category-badge { + display: inline; + margin-right: 0.5rem; +} + +section.product-show { + display: flex; + flex-direction: column; + align-items: center; + justify-content: center; + text-align: center; +} + +span.badge.category-tag { + font-size: 1rem; +} + +div.form-check-inline > input { + margin-left: 1rem; + margin-right: 0.5rem; +} 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/sessions.scss b/app/assets/stylesheets/sessions.scss new file mode 100644 index 0000000000..ccb1ed25b2 --- /dev/null +++ b/app/assets/stylesheets/sessions.scss @@ -0,0 +1,3 @@ +// Place all the styles related to the Sessions 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/user.scss b/app/assets/stylesheets/user.scss new file mode 100644 index 0000000000..c47a13e0c4 --- /dev/null +++ b/app/assets/stylesheets/user.scss @@ -0,0 +1,3 @@ +// Place all the styles related to the User 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..e00575aa78 --- /dev/null +++ b/app/controllers/application_controller.rb @@ -0,0 +1,34 @@ +class ApplicationController < ActionController::Base + protect_from_forgery with: :exception + + before_action :current_order + before_action :current_user + + + def current_order + if session[:order_id] + @current_order = Order.find_by(id: session[:order_id].to_i) + else + @current_order = generate_cart + end + end + + def current_user + if session[:user_id] + @current_user = User.find_by(id: session[:user_id]) + else + @current_user = User.create(uid: 0, provider: "sovietski") + end + end + + private + + def generate_cart + order = Order.new(status: "pending") + order.user_id = current_user.id + order.save + + return order + end + +end diff --git a/app/controllers/categories_controller.rb b/app/controllers/categories_controller.rb new file mode 100644 index 0000000000..5adaf348c2 --- /dev/null +++ b/app/controllers/categories_controller.rb @@ -0,0 +1,26 @@ +class CategoriesController < ApplicationController + def new + @category = Category.new + end + + def create + @category = Category.new(category_params) + if @category.save + flash[:success] = "Successfully created #{@category.name}!" + + redirect_to products_path + else + flash.now[:warning] = "Category is not created!" + @category.errors.messages.each do |field, messages| + flash.now[field] = messages + end + render :new, status: :bad_request + end + end + + private + + def category_params + return params.require(:category).permit(:name) + end +end diff --git a/app/controllers/concerns/.keep b/app/controllers/concerns/.keep new file mode 100644 index 0000000000..e69de29bb2 diff --git a/app/controllers/home_controller.rb b/app/controllers/home_controller.rb new file mode 100644 index 0000000000..95f29929ca --- /dev/null +++ b/app/controllers/home_controller.rb @@ -0,0 +1,4 @@ +class HomeController < ApplicationController + def index + end +end diff --git a/app/controllers/order_products_controller.rb b/app/controllers/order_products_controller.rb new file mode 100644 index 0000000000..cfa6a24428 --- /dev/null +++ b/app/controllers/order_products_controller.rb @@ -0,0 +1,73 @@ +class OrderProductsController < ApplicationController + + def create + # pull in product and quantity from form partial on product show page + product = Product.find_by(id: params[:order_product][:product_id].to_i) + quantity = params[:order_product][:quantity].to_i + + # create the orderproduct, add it to the current cart, and save it + if @current_order.save && @current_order.add_product(product, quantity) + # save the cart and update the session + @current_order.save + session[:order_id] = @current_order.id + + redirect_to cart_path + else + flash[:warning] = "Error: Could not add product to cart" + + redirect_back fallback_location: products_path + end + end + + def update + op = OrderProduct.find_by(id: params[:id].to_i) + new_quantity = params[:order_product][:quantity].to_i + + if @current_order.edit_quantity(op, new_quantity) && @current_order.save + if new_quantity == 0 + flash[:success] = "Removed #{op.product.name} from cart" + end + redirect_to cart_path + else + flash[:warning] = "Error: Could not update product order" + + redirect_back fallback_location: cart_path + end + end + + def change_status + op = OrderProduct.find_by(id: params[:id].to_i) + new_status = params[:status] + + if verify_merchant(op) && op.update(status: new_status) + flash[:success] = "Updated status for Product Order ##{op.id} to #{new_status}" + redirect_to merchant_dash_path(@current_user.id) + elsif verify_buyer(op) && op.update(status: new_status) + flash[:success] = "Cancelled Product Order ##{op.id}" + redirect_back fallback_location: root_path + else + flash[:warning] = "Could not update status for Product Order ##{op.id}" + redirect_back fallback_location: root_path + end + end + + def destroy + op = OrderProduct.find_by(id: params[:id]) + if op && op.destroy + flash[:success] = "Removed #{op.product.name} from cart" + else + flash[:warning] = "Error: Could not remove product from cart" + end + redirect_back fallback_location: cart_path + end + + private + + def verify_merchant(op) + return (op.product.user == @current_user && @current_user.is_a_merchant?) + end + + def verify_buyer(op) + return op.order.user == @current_user + end +end diff --git a/app/controllers/orders_controller.rb b/app/controllers/orders_controller.rb new file mode 100644 index 0000000000..f4b7dbd774 --- /dev/null +++ b/app/controllers/orders_controller.rb @@ -0,0 +1,41 @@ +class OrdersController < ApplicationController + def cart + end + + def checkout + unless @current_order.order_products.any? + redirect_to cart_path + flash[:warning] = "You must add something to your cart before you can checkout" + end + end + + def update + if @current_order.update(order_user_params) && @current_order.submit_order + + session[:paid_order_id] = session[:order_id] + session[:order_id] = nil + + redirect_to confirmation_path + else + redirect_to checkout_path + flash[:warning] = "Could not submit order" + end + end + + def confirmation + @paid_order = Order.find_by(id: session[:paid_order_id]) + + if @paid_order + session[:paid_order_id] = nil + else + redirect_to checkout_path + flash[:warning] = "Error: Order payment did not go through" + end + end + + private + + def order_user_params + return params.require(:order).permit(user_attributes: [:id, :name, :address, :email, :cc_num, :cc_csv, :cc_exp, :bill_zip]) + end +end diff --git a/app/controllers/products_controller.rb b/app/controllers/products_controller.rb new file mode 100644 index 0000000000..56283fa9ac --- /dev/null +++ b/app/controllers/products_controller.rb @@ -0,0 +1,137 @@ +class ProductsController < ApplicationController + before_action :find_product, only: [:show, :edit, :update, :retire] + before_action :find_merchant, only: [:edit, :update, :retire, :new, :create] + + def index + @products = Product.active_products + end + + def bycategory + id = params[:id].to_i + @category_selected = Category.find_by(id:id) + if @category_selected + @products_by_category = Product.category_list(id) + else + render :notfound, status: :not_found + end + end + + def bymerchant + id = params[:id].to_i + @merchant_selected = User.find_by(id:id) + if @merchant_selected + @products_by_merchant = Product.merchant_list(id) + else + render :notfound, status: :not_found + end + end + + def show + if @product.status == false ||@product.nil? + render :notfound, status: :not_found + end + if @current_order.valid? + @op = @current_order.order_products.find_by(product_id: params[:id]) + end + end + + def new + if session[:user_id] && @current_user.is_a_merchant? + @product = Product.new + + end + end + + def create + + if @current_user.is_a_merchant? + + @product = @current_user.products.new(product_params) + + category_ids = params[:product][:category_ids].select(&:present?).map(&:to_i) + category_ids.each do |id| + c = Category.find(id) + @product.categories << c + end + + if @product.save + flash[:success] = 'Product Created!' + redirect_to product_path(id: @product.id) + else + flash.now[:warning] = 'Product not created!' + render :new, status: :bad_request + end + else + flash.now[:warning] = 'Not a Merchant!' + end + end + + + + def edit; end + + def update + if @product && @product.update(product_params) + @product.categories = [] + category_ids = params[:product][:category_ids].select(&:present?).map(&:to_i) + category_ids.each do |id| + c = Category.find(id) + @product.categories << c + end + + redirect_to product_path(@product[:id]) + elsif @product + render :edit, status: :bad_request + end + end + + def retire + + @product.status = false + if @product.save + flash[:success] = "#{@product.name} retired" + redirect_to products_path + else + lash[:warning] = "#{@product.name} is not retired" + end + + end + + + + + private + def find_product + + @product = Product.find_by(id: params[:id].to_i) + + if @product.nil? + flash.now[:warning] = "Cannot find the product #{params[:id]}" + render :notfound, status: :not_found + end + end + + def find_merchant + @merchant = Merchant.find_by(id: session[:user_id].to_i) + if @merchant.nil? + flash.now[:warning] = "Cannot find the merchant #{session[:user_id]}" + render :notfound, status: :not_found + end + end + + def product_params + return params.require(:product).permit(:name, :price, :description, :stock, :photo_url).except(:category_ids) + end + + def category_params + return params.require(:category).permit(:id) + end + + def review_params + return params.require(:review).permit(:name, :rating, :comment) + end + + def render_404 + raise ActionController::RoutingError.new('Not Found') + end +end diff --git a/app/controllers/reviews_controller.rb b/app/controllers/reviews_controller.rb new file mode 100644 index 0000000000..a84d6427f8 --- /dev/null +++ b/app/controllers/reviews_controller.rb @@ -0,0 +1,5 @@ +class ReviewsController < ApplicationController + + + +end diff --git a/app/controllers/sessions_controller.rb b/app/controllers/sessions_controller.rb new file mode 100644 index 0000000000..0f1e52fa78 --- /dev/null +++ b/app/controllers/sessions_controller.rb @@ -0,0 +1,35 @@ +class SessionsController < ApplicationController + + def create + auth_hash = request.env['omniauth.auth'] + + current_user = User.find_by(uid: auth_hash[:uid], provider: 'github') + + if current_user + # session[:user_id] = current_user.id + flash[:success] = "Welcome back #{current_user.name}!" + redirect_to merchant_dash_path(current_user.id) + else + #try to make a new user + current_user = User.build_from_github(auth_hash) + current_user.type = "Merchant" + + if current_user.save + flash[:success] = "Welcome #{current_user.name}!" + redirect_to edit_user_path(current_user.id) + else + flash[:warning] = "Could not create account: #{current_user.errors.messages}" + redirect_to root_path + return + end + end + + session[:user_id] = current_user.id + end + + def destroy + session[:user_id] = nil + flash[:success] = "Bye!" + redirect_to root_path + end +end diff --git a/app/controllers/users_controller.rb b/app/controllers/users_controller.rb new file mode 100644 index 0000000000..396daea93a --- /dev/null +++ b/app/controllers/users_controller.rb @@ -0,0 +1,63 @@ +class UsersController < ApplicationController + before_action :check_permissions, only: [:show, :edit, :destroy, :merchant_dash] + + def index + @merchants = Merchant.all #adding merchants to index for viewing and sorting in views + # @users = User.all + end + + def show; end #TODO change this to be just user profile and create custom route for merchant shopping + + def update + if @current_user && @current_user.update(user_params) + flash[:success] = "Saved" + redirect_to edit_user_path(@current_user.id) + else + flash.now[:warning] = 'Please fill in all fields.' + render :edit, status: :bad_request + end + end + + def edit; end + + def destroy + unless @current_user.nil? + if @current_user.is_a_merchant? && @current_user.products.any? + @current_user.products.each do |product| + product.status = false + product.save + end + end + + @current_user.update(name: "Deleted User", email: nil, address: nil, cc_num: nil, cc_exp: nil, bill_zip: nil, cc_csv: nil, status: "inactive", uid: 0, provider: "none") + + flash[:success] = "#{@current_user.name}'s information deleted" + redirect_to root_path + end + end + + def merchant_dash + unless @current_user.is_a_merchant? + flash.now[:warning] = 'Not allowed.' + render :forbidden + end + end + + private + + def check_permissions + if params[:id].to_i != session[:user_id] + flash.now[:error] = 'Not allowed.' + render :forbidden + end + end + + def user_params + allowed_params = :name, :address, :email, :cc_num, :cc_csv, :cc_exp, :type, :bill_zip + unless @current_user.class == Merchant + params.require(:user).permit(allowed_params) + else + params.require(:merchant).permit(allowed_params) + end + end +end diff --git a/app/helpers/application_helper.rb b/app/helpers/application_helper.rb new file mode 100644 index 0000000000..68fa21a058 --- /dev/null +++ b/app/helpers/application_helper.rb @@ -0,0 +1,9 @@ +module ApplicationHelper + def format_money(price) + return sprintf("$%.2f", price) + end + + def format_date(date) + return date.strftime("%A, %b %d") + end +end diff --git a/app/helpers/categories_helper.rb b/app/helpers/categories_helper.rb new file mode 100644 index 0000000000..e06f31554c --- /dev/null +++ b/app/helpers/categories_helper.rb @@ -0,0 +1,2 @@ +module CategoriesHelper +end diff --git a/app/helpers/home_helper.rb b/app/helpers/home_helper.rb new file mode 100644 index 0000000000..23de56ac60 --- /dev/null +++ b/app/helpers/home_helper.rb @@ -0,0 +1,2 @@ +module HomeHelper +end diff --git a/app/helpers/order_products_helper.rb b/app/helpers/order_products_helper.rb new file mode 100644 index 0000000000..fb2828b523 --- /dev/null +++ b/app/helpers/order_products_helper.rb @@ -0,0 +1,2 @@ +module OrderProductsHelper +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/sessions_helper.rb b/app/helpers/sessions_helper.rb new file mode 100644 index 0000000000..309f8b2eb3 --- /dev/null +++ b/app/helpers/sessions_helper.rb @@ -0,0 +1,2 @@ +module SessionsHelper +end diff --git a/app/helpers/user_helper.rb b/app/helpers/user_helper.rb new file mode 100644 index 0000000000..0147c3fe6a --- /dev/null +++ b/app/helpers/user_helper.rb @@ -0,0 +1,2 @@ +module UserHelper +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..d14724547f --- /dev/null +++ b/app/models/category.rb @@ -0,0 +1,10 @@ +class Category < ApplicationRecord + has_and_belongs_to_many :products + validates :name, presence: true, uniqueness: true + + def self.category_list + return Category.all.map do |category| + [category.id, category.name] + 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/merchant.rb b/app/models/merchant.rb new file mode 100644 index 0000000000..29e8c22824 --- /dev/null +++ b/app/models/merchant.rb @@ -0,0 +1,14 @@ +class Merchant < User + validates :type, presence: true + validate :type_must_be_merchant + + #merchant inherits all things from user, but when a new merchant is created the 'type' is automagically set to merchant. + + #if a merchant type is set to nil, then the Merchant instance will become an instance of the superclass + def become_user(merchant) + merchant.becomes!(User) if !merchant.valid_merchant + end + + #create method to be sure it is not nil, then add to validation + #merchant needs ability to fulfill orders as 'shipped' +end diff --git a/app/models/order.rb b/app/models/order.rb new file mode 100644 index 0000000000..906833f32f --- /dev/null +++ b/app/models/order.rb @@ -0,0 +1,45 @@ +class Order < ApplicationRecord + belongs_to :user + has_many :order_products, dependent: :destroy + has_many :products, through: :order_products # might not need this, if so, update tests too + + accepts_nested_attributes_for :user, update_only: true + + validates :user, presence: true + validates :status, presence: true + validates :status, inclusion: { in: %w(pending paid shipped), + message: "%{value} is not a valid order status" } + + def total + return order_products.map { |op| op.valid? ? op.subtotal : 0 }.sum + end + + def add_product(product, quantity_ordered) + # check if product is already in cart + current_op = order_products.find_by(product_id: product.id) + + if product.available?(quantity_ordered) && self.user != product.user + if current_op + current_op.edit_quantity(quantity_ordered) + else + current_op = self.order_products.create(product_id: product.id, quantity: quantity_ordered, order_id: self.id, status: "pending") + end + return current_op.save + else + return false + end + end + + def edit_quantity(op, quantity_ordered) + return op.edit_quantity(quantity_ordered) + end + + def submit_order + if order_products.each { |op| op.submit_order } + self.status = "paid" + return self.save + else + return false + end + end +end diff --git a/app/models/order_product.rb b/app/models/order_product.rb new file mode 100644 index 0000000000..fcbccb04f8 --- /dev/null +++ b/app/models/order_product.rb @@ -0,0 +1,35 @@ +class OrderProduct < ApplicationRecord + belongs_to :order + belongs_to :product + + validates :quantity, presence: true + validates :quantity, numericality: { only_integer: true, greater_than: 0 } + validates :order, presence: true + validates :product, presence: true + validates :status, presence: true + validates :status, inclusion: { in: %w(pending paid shipped cancelled), + message: "%{value} is not a valid order status" } + + def subtotal + return product.price * quantity + end + + def submit_order + if product.update_stock(quantity) + self.status = "paid" + return self.save + else + return false + end + end + + def edit_quantity(quantity_ordered) + if quantity_ordered == 0 + return self.destroy + elsif product.available?(quantity_ordered) + return self.update(quantity: quantity_ordered) + else + return false + end + end +end diff --git a/app/models/product.rb b/app/models/product.rb new file mode 100644 index 0000000000..ec7700d1b6 --- /dev/null +++ b/app/models/product.rb @@ -0,0 +1,49 @@ +class Product < ApplicationRecord + belongs_to :user + has_and_belongs_to_many :categories + + has_many :reviews + has_many :order_products + + validates :name, presence: true + + + validates :user_id, presence: true + validates :stock, presence: true, numericality: { :only_integer => true, :greater_than_or_equal_to => 0} + + validates :price, presence: true, numericality: {:greater_than_or_equal_to => 0} + + + def self.active_products + return Product.all.select {|e| e.status == true} + end + + + def self.category_list(id) + selected_category = Category.find_by(id:id) + return self.active_products.select {|prod| prod.categories.include? selected_category} + end + + def self.merchant_list(id) + self.active_products.select {|prod| prod.user.id == id} + end + + def update_stock(quantity_ordered) + if self.available?(quantity_ordered) + self.stock -= quantity_ordered + return self.save + else + return false + end + end + + def available?(quantity_ordered) + return false unless (quantity_ordered >= 1 && (quantity_ordered.is_a? Integer)) + + if quantity_ordered <= self.stock + return true + else + return false + end + end +end diff --git a/app/models/review.rb b/app/models/review.rb new file mode 100644 index 0000000000..de9f48e95a --- /dev/null +++ b/app/models/review.rb @@ -0,0 +1,3 @@ +class Review < ApplicationRecord + +end diff --git a/app/models/user.rb b/app/models/user.rb new file mode 100644 index 0000000000..e4db2bbfce --- /dev/null +++ b/app/models/user.rb @@ -0,0 +1,49 @@ +class User < ApplicationRecord + has_many :products + has_many :orders + has_many :order_products, through: :products + + validates :cc_num, numericality: { only_integer: true }, allow_nil: true + + def self.build_from_github(auth_hash) + user = User.new + user.uid = auth_hash[:uid] + user.provider = 'github' + user.name = auth_hash['info']['name'] + user.email = auth_hash['info']['email'] + + # Note that the user has not been saved + return user + end + + def is_a_merchant? + return self.type == "Merchant" + end + + def total_revenue + return order_products.map { |op| op.valid? ? op.subtotal : 0 }.sum + end + + def total_revenue_by_status(op_status) + return order_products.map { |op| (op.valid? && op.status == op_status) ? op.subtotal : 0 }.sum + end + + def orders_by_status(op_status) + return order_products.where(status: op_status) + end + + def num_orders_by_status(op_status) + return orders_by_status(op_status).count + end + + #when a the type "Merchant" is added to a User instance, it will actually become an instance of Merchant rather than a User instance with type Merchant + def become_merchant + self.becomes!(Merchant) if self.type_must_be_merchant + self.save! + end + + #helper method + def type_must_be_merchant #custom validation to assure that only type merchant can be subclass Merchant + self.is_a_merchant? ? true : errors.add(:type, "the user's type must be set to Merchant") + end +end diff --git a/app/views/categories/new.html.erb b/app/views/categories/new.html.erb new file mode 100644 index 0000000000..7e3b99d2c9 --- /dev/null +++ b/app/views/categories/new.html.erb @@ -0,0 +1,19 @@ +
+

Add a Category

+ + <%= form_with model: @category, local: true do |f|%> +

More election categories? Excellent...

+ +
+ <%= f.label :name %> + <%= f.text_field :name, class: "form-control" %> +
+ + <% if @current_user.is_a_merchant? %> + <%= f.submit "Add category", class: "btn btn-primary" %> + <% else %> + <%= f.submit "Add category", class: "btn btn-primary", disabled: true %> + <% end %> + + <% end %> +
diff --git a/app/views/home/index.html.erb b/app/views/home/index.html.erb new file mode 100644 index 0000000000..6520f20b74 --- /dev/null +++ b/app/views/home/index.html.erb @@ -0,0 +1 @@ +<%= image_tag("homepage-hero.jpg", class: "homepage-hero-img") %> diff --git a/app/views/layouts/_form_errors.html.erb b/app/views/layouts/_form_errors.html.erb new file mode 100644 index 0000000000..ec72172d15 --- /dev/null +++ b/app/views/layouts/_form_errors.html.erb @@ -0,0 +1,14 @@ +<% if model.errors.any? %> + +<% end %> diff --git a/app/views/layouts/application.html.erb b/app/views/layouts/application.html.erb new file mode 100644 index 0000000000..e661b0c0b5 --- /dev/null +++ b/app/views/layouts/application.html.erb @@ -0,0 +1,84 @@ + + + + SoviƩtski + <%= csrf_meta_tags %> + <%= csp_meta_tag %> + + <%= stylesheet_link_tag 'application', media: 'all', 'data-turbolinks-track': 'reload' %> + <%= javascript_include_tag 'application', 'data-turbolinks-track': 'reload' %> + + + + + +
+
+ + +

<%= link_to "SoviƩtski", root_path, class: "sovietski-logo" %>

+ + +
+
+
+
+ <%flash.each do |name, message|%> + <% if message.class == Array %> + <%message.each do |msg|%> + + <%end%> + <%else%> + + <%end%> + <%end%> +
+ <%= yield %> +
+ + + diff --git a/app/views/layouts/mailer.html.erb b/app/views/layouts/mailer.html.erb new file mode 100644 index 0000000000..cbd34d2e9d --- /dev/null +++ b/app/views/layouts/mailer.html.erb @@ -0,0 +1,13 @@ + + + + + + + + + <%= yield %> + + diff --git a/app/views/layouts/mailer.text.erb b/app/views/layouts/mailer.text.erb new file mode 100644 index 0000000000..37f0bddbd7 --- /dev/null +++ b/app/views/layouts/mailer.text.erb @@ -0,0 +1 @@ +<%= yield %> diff --git a/app/views/layouts/not_found.html.erb b/app/views/layouts/not_found.html.erb new file mode 100644 index 0000000000..9b8bbf779b --- /dev/null +++ b/app/views/layouts/not_found.html.erb @@ -0,0 +1 @@ +

NOT FOUND

diff --git a/app/views/order_products/_form.html.erb b/app/views/order_products/_form.html.erb new file mode 100644 index 0000000000..673129382c --- /dev/null +++ b/app/views/order_products/_form.html.erb @@ -0,0 +1,14 @@ +
+ <% @op = op if op %> + + <%= form_with model: @op, class: "form-inline product-quantity-form", locals: true do |f|%> +
+ <%= f.label :quantity %> + <%= f.number_field :quantity, in: 0..(Product.find_by(id: product_id).stock), class: "form-control quantity-field" %> +
+ + <%= f.hidden_field :product_id, value: product_id %> + + <%= f.submit button_title, class: "btn btn-primary" %> + <% end %> +
diff --git a/app/views/orders/cart.html.erb b/app/views/orders/cart.html.erb new file mode 100644 index 0000000000..fe1f98688c --- /dev/null +++ b/app/views/orders/cart.html.erb @@ -0,0 +1,42 @@ +
+

Shopping Cart

+
+
+ <% if @current_order.order_products.any? %> +
+ <% @current_order.order_products.each do |op| %> +
+
+ <%= image_tag(op.product.photo_url, alt: op.product.name, class: "col-sm card-img") %> +
+
+
<%= op.product.name %>
+
+

+ <%= "Price: #{format_money(op.product.price)}" %>
+ <%= "Quantity: #{op.quantity}" %>
+ <%= "Subtotal: #{format_money(op.subtotal)}" %> +

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

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

+ <%= link_to "Continue to checkout", checkout_path, method: :get, class: "btn btn-secondary" %> +
+ <% else %> +
+

Nothing to see here... no collusion!

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

Kindly hand over your personal information.

+
+ +
+ <%= form_with model: @current_order, class: "form", locals: true do |f|%> + <%= f.fields_for :user do |u| %> +
+
Shipping Information
+
+ <%= u.label :name %> + <%= u.text_field :name, class: "form-control" %> +
+ +
+ <%= u.label :email %> + <%= u.text_field :email, class: "form-control" %> +
+ +
+ <%= u.label :address %> + <%= u.text_field :address, class: "form-control" %> +
+
+ +
+ +
+
Payment Information
+ +
+ <%= u.label "Credit card number" %> + <%= u.text_field :cc_num, class: "form-control" %> +
+ +
+ <%= u.label "Credit card CSV" %> + <%= u.text_field :cc_csv, class: "form-control" %> +
+ +
+ <%= u.label "Card expiration date" %> + <%= u.text_field :cc_exp, class: "form-control" %> +
+ +
+ <%= u.label "Billing zip code" %> + <%= u.text_field :bill_zip, class: "form-control" %> +
+
+ <% end %> + + <%= f.submit "Submit Order", class: "btn btn-secondary" %> + <% end %> +
+
diff --git a/app/views/orders/confirmation.html.erb b/app/views/orders/confirmation.html.erb new file mode 100644 index 0000000000..8ae10b03a8 --- /dev/null +++ b/app/views/orders/confirmation.html.erb @@ -0,0 +1,45 @@ +
+
+

Best of luck, comrade. We've placed your order!

+
+ +
+
+
+ <% @paid_order.order_products.each do |op| %> +
+
+ <%= image_tag(op.product.photo_url, alt: op.product.name, class: "col-sm card-img") %> +
+
+
<%= op.product.name %>
+
+

+ <%= "Price: #{format_money(op.product.price)}" %>
+ <%= "Quantity: #{op.quantity}" %>
+ <%= "Subtotal: #{format_money(op.subtotal)}" %>
+ <%= "Status: #{op.status.titleize}" %> +

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

Order number: <%= "#{@paid_order.id}" %>

+

Submitted on: <%= format_date(@paid_order.updated_at) %>

+

Status: <%= "#{@paid_order.status.titleize}" %>

+

Total: <%= format_money(@paid_order.total) %>

+
+
+
+
diff --git a/app/views/products/_form.html.erb b/app/views/products/_form.html.erb new file mode 100644 index 0000000000..dbaeee21ca --- /dev/null +++ b/app/views/products/_form.html.erb @@ -0,0 +1,41 @@ +
+

<%= action_name %>

+ + <%= render partial: "layouts/form_errors", locals: { model: @product } %> + + <%= form_with model: @product, local: true do |f|%> + +
+ <%= f.label :name %> + <%= f.text_field :name, class: "form-control" %> +
+ + +
+ <%= f.label :categories %> + <%= collection_check_boxes(:product, :category_ids, Category.all, :id, :name) %> +
+ +
+ <%= f.label :description %> + <%= f.text_field :description, class: "form-control" %> +
+ +
+ <%= f.label :price %> + <%= f.text_field :price, class: "form-control" %> +
+ +
+ <%= f.label :stock %> + <%= f.text_field :stock, class: "form-control" %> +
+ +
+ <%= f.label :photo_url %> + <%= f.text_field :photo_url, class: "form-control" %> +
+ + <%= f.submit button_title, class: "btn btn-primary" %> + <% end %> +
diff --git a/app/views/products/_shopping.html.erb b/app/views/products/_shopping.html.erb new file mode 100644 index 0000000000..f3d34390e7 --- /dev/null +++ b/app/views/products/_shopping.html.erb @@ -0,0 +1,27 @@ +
+
+ <%= render partial: "shopping_nav", local: true %> + +
+
+ <% product_list.each do |product|%> +
+ <%= image_tag(product.photo_url, alt: product.name, class: "card-img-top") %> +
+
<%= link_to "#{product.name}", product_path(product.id) %>
+
+ Sold by: <%= link_to "#{product.user.name}", bymerchant_path(product.user.id) %>
+ + <%= "#{format_money(product.price)}" %>
+ + <% product.categories.each do |cat| %> + <%= cat.name %> + <% end %> +
+
+
+ <% end %> +
+
+
+
diff --git a/app/views/products/_shopping_nav.html.erb b/app/views/products/_shopping_nav.html.erb new file mode 100644 index 0000000000..84e856353c --- /dev/null +++ b/app/views/products/_shopping_nav.html.erb @@ -0,0 +1,17 @@ + diff --git a/app/views/products/bycategory.html.erb b/app/views/products/bycategory.html.erb new file mode 100644 index 0000000000..59f146bd8e --- /dev/null +++ b/app/views/products/bycategory.html.erb @@ -0,0 +1,3 @@ +<%= render partial: "shopping", locals: { product_list: @products_by_category } %> + + diff --git a/app/views/products/bymerchant.html.erb b/app/views/products/bymerchant.html.erb new file mode 100644 index 0000000000..fd8a1a6e63 --- /dev/null +++ b/app/views/products/bymerchant.html.erb @@ -0,0 +1,3 @@ +<%= render partial: "shopping", locals: { product_list: @products_by_merchant } %> + + diff --git a/app/views/products/edit.html.erb b/app/views/products/edit.html.erb new file mode 100644 index 0000000000..3ff43d1ffa --- /dev/null +++ b/app/views/products/edit.html.erb @@ -0,0 +1,3 @@ +<%= render partial: "form", + locals: { action_name: 'Edit product', + button_title: 'Edit' } %> diff --git a/app/views/products/index.html.erb b/app/views/products/index.html.erb new file mode 100644 index 0000000000..cb6a1b69a9 --- /dev/null +++ b/app/views/products/index.html.erb @@ -0,0 +1 @@ +<%= render partial: "shopping", locals: { product_list: @products } %> diff --git a/app/views/products/new.html.erb b/app/views/products/new.html.erb new file mode 100644 index 0000000000..69e186a356 --- /dev/null +++ b/app/views/products/new.html.erb @@ -0,0 +1,3 @@ +<%= render partial: "form", + locals: { action_name: 'Add a product', + button_title: 'Add product' } %> diff --git a/app/views/products/notfound.html.erb b/app/views/products/notfound.html.erb new file mode 100644 index 0000000000..c37ab2ebaa --- /dev/null +++ b/app/views/products/notfound.html.erb @@ -0,0 +1 @@ +

Not Found 404

diff --git a/app/views/products/show.html.erb b/app/views/products/show.html.erb new file mode 100644 index 0000000000..4fae07d2e1 --- /dev/null +++ b/app/views/products/show.html.erb @@ -0,0 +1,44 @@ +
+
+ <%= render partial: "shopping_nav", local: true %> + +
+

<%= @product.name %>

+

Sold by: <%= @product.user.name %>

+ + + +

+ <%= image_tag(@product.photo_url) %> +

+ +

+ <% @product.categories.each do |cat| %> + <%= cat.name %> + <% end %> +

+ + <% if @product.stock > 0 && @current_user != @product.user %> +

+ <% if @op %> + <%= render partial: "order_products/form", locals: { button_title: "Update cart", op: @op, product_id: @product.id } %> + <% else %> + <%= render partial: "order_products/form", locals: { button_title: "Add to cart", op: @current_order.order_products.new, product_id: @product.id } %> + <% end %> +

+ <%end%> + +

<%= @product.description%>

+

Price: <%= format_money(@product.price) %>

+
+ +
+
+
diff --git a/app/views/reviews/_form.htmil.erb b/app/views/reviews/_form.htmil.erb new file mode 100644 index 0000000000..e69de29bb2 diff --git a/app/views/reviews/new.html.erb b/app/views/reviews/new.html.erb new file mode 100644 index 0000000000..a5843d1a53 --- /dev/null +++ b/app/views/reviews/new.html.erb @@ -0,0 +1,3 @@ +<%= render partial: "form", + locals: { action_name: 'Create New Review', + button_title: 'Create' } %> diff --git a/app/views/users/_filtered_orders.html.erb b/app/views/users/_filtered_orders.html.erb new file mode 100644 index 0000000000..c6358e94e3 --- /dev/null +++ b/app/views/users/_filtered_orders.html.erb @@ -0,0 +1,33 @@ +<% if @current_user.orders_by_status(op_status).any? %> + <% @current_user.orders_by_status(op_status).each do |op| %> +
+
+ Product +
+
+
<%= link_to "#{op.product.name}", product_path(op.product.id) %>
+
+

+ <%= "Price: #{format_money(op.product.price)}" %>
+ <%= "Quantity: #{op.quantity}" %>
+ <%= "Total: #{format_money(op.subtotal)}" %>
+ <%= "Status: #{op.status.titleize}" %> +

+ <%= "Order placed on #{format_date(op.created_at)} by #{op.order.user.name}" %>
+ <%= "Email: #{op.order.user.email}" %>
+ <%= "Address: #{op.order.user.address}" %>
+ <%= "Payment: XXXXXXXX#{op.order.user.cc_num[-4..-1]} (expires #{format_date(op.order.user.cc_exp)})" %>
+

+
+
+
+
+ <% if op.status == "paid" %> + + <% end %> +
+ <% end %> +<% end %> diff --git a/app/views/users/_info.html.erb b/app/views/users/_info.html.erb new file mode 100644 index 0000000000..e016604347 --- /dev/null +++ b/app/views/users/_info.html.erb @@ -0,0 +1 @@ +# Merchant info for use on product page diff --git a/app/views/users/edit.html.erb b/app/views/users/edit.html.erb new file mode 100644 index 0000000000..e3fa07f69a --- /dev/null +++ b/app/views/users/edit.html.erb @@ -0,0 +1,52 @@ +
+

Account Information

+
+ + <%= form_with model: @current_user, local: true do |f|%> +
+
Shipping Information
+
+ <%= f.label :name %> + <%= f.text_field :name, class: "form-control" %> +
+ +
+ <%= f.label :email %> + <%= f.text_field :email, class: "form-control" %> +
+ +
+ <%= f.label :address %> + <%= f.text_field :address, class: "form-control" %> +
+
+ +
+ +
+
Payment Information
+ +
+ <%= f.label "Credit card number" %> + <%= f.text_field :cc_num, class: "form-control" %> +
+ +
+ <%= f.label "Credit card CSV" %> + <%= f.text_field :cc_csv, class: "form-control" %> +
+ +
+ <%= f.label "Card expiration date" %> + <%= f.text_field :cc_exp, class: "form-control" %> +
+ +
+ <%= f.label "Billing zip code" %> + <%= f.text_field :bill_zip, class: "form-control" %> +
+
+ + <%= f.submit "Update", class: "btn btn-primary" %> + <% end %> +
diff --git a/app/views/users/forbidden.html.erb b/app/views/users/forbidden.html.erb new file mode 100644 index 0000000000..cd54b4cfc3 --- /dev/null +++ b/app/views/users/forbidden.html.erb @@ -0,0 +1 @@ +

Are you a hacker or something!? You should come work for Sovietski...

diff --git a/app/views/users/index.html.erb b/app/views/users/index.html.erb new file mode 100644 index 0000000000..f03dbc757a --- /dev/null +++ b/app/views/users/index.html.erb @@ -0,0 +1,30 @@ +

Merchant List

+ +<% if @merchants.empty? %> +

There are no merchants yet

+<% else %> + + + + + + + + + + <% @merchants.each do |merchant| %> + + + + + + <% end %> + +
Storefront ImageStorefront NameJoined
+

img goes here

+
+ <%= link_to merchant.name, user_path(merchant.id) %> + + <%= "#{merchant.created_at.strftime("%b. %d, %Y")}" %> +
+<% end %> diff --git a/app/views/users/merchant_dash.html.erb b/app/views/users/merchant_dash.html.erb new file mode 100644 index 0000000000..1331ee5356 --- /dev/null +++ b/app/views/users/merchant_dash.html.erb @@ -0,0 +1,42 @@ +
+
+
+

Seller Summary

+

<%= "Total orders: #{@current_user.order_products.count}" %>

+
<%= "Total revenue: #{format_money(@current_user.total_revenue)}" %>
+
    + <% ["pending", "paid", "shipped", "cancelled"].each do |status| %> +
  • <%= "#{status.titleize}: #{format_money(@current_user.total_revenue_by_status(status))}" %>
  • + <% end %> +
+
+

Product Inventory

+
    + <% @current_user.products.each do |product| %> +
  • <%= link_to "#{product.name}", product_path(product.id) %>: <%= "#{product.stock}" %>
  • + <% end %> +
+
+

<%= link_to "Add a category", new_category_path, class: "btn btn-outline-secondary" %>

+

<%= link_to "Add a product", new_product_path, class: "btn btn-outline-secondary"%>

+
+ +
+
+
+ <% ["pending", "paid", "shipped", "cancelled"].each do |op_status| %> + + <% end %> +
+
+ <% ["pending", "paid", "shipped", "cancelled"].each do |op_status| %> +
+ <%= render partial: "filtered_orders", locals: { op_status: op_status } %> +
+ <% end %> +
+
+
+
diff --git a/app/views/users/not_found.html.erb b/app/views/users/not_found.html.erb new file mode 100644 index 0000000000..9b8bbf779b --- /dev/null +++ b/app/views/users/not_found.html.erb @@ -0,0 +1 @@ +

NOT FOUND

diff --git a/app/views/users/show.html.erb b/app/views/users/show.html.erb new file mode 100644 index 0000000000..2948bec370 --- /dev/null +++ b/app/views/users/show.html.erb @@ -0,0 +1,44 @@ + +<% if @current_user.type == "Merchant" %> +

<%= "#{@current_user.name}'s Good's Distribution Store" %>

+<% else %> +

Profile Information

+<% end %> +

+ Joined site on <%= "#{@current_user.created_at.strftime ("%b. %d, %Y")}" %> +

+ + + + + + + + + + + <% if @current_user.type != Merchant %> + + <% else %> + + + <% end %> + + + + <% @current_user.products.each do |product| %> + + + + + + <% if @current_user.id != product.user.id %> + + <% else %> + + + <% end %> + + <% end %> + +
Product PictureProduct NameQuantityCategoryAdd to CartRemove productEdit stock
product image <%= link_to "#{product.name}", product_path(product.id) %> <%= "#{product.stock}" %> <%= "#{product.categories}" %> add to cart delete product increase stock
diff --git a/app/views/users/update.html.erb b/app/views/users/update.html.erb new file mode 100644 index 0000000000..01ff3a6069 --- /dev/null +++ b/app/views/users/update.html.erb @@ -0,0 +1,2 @@ +

User#update

+

Find me in app/views/user/update.html.erb

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..fb2ec2ebb4 --- /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..f32aed5c4b --- /dev/null +++ b/config/application.rb @@ -0,0 +1,28 @@ +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. + + # Don't generate remote forms with form_with + config.action_view.form_with_generates_remote_forms = false + 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..3285252ed0 --- /dev/null +++ b/config/credentials.yml.enc @@ -0,0 +1 @@ +GXWq0KkwTw898gFPOUhWWvmu8GDv6fSl3vFgVmg/ryWeXcaOSvKT7Q5lJZBgnlED0XJTzLQxDk0+yRVsnnZfFQwAWidUpLTAzqS++CXuydWMSu1F7tWCSSSyVXqCHLTStG0pSZ+gTCd+Ephw4fEdIBOF8tt96n52U17KYeJ5oKBeWHkywhepuqBox5EA0aNOjqoDq3f2h7LrVcWwHK/9ZOSCqTwQvopuLpWG4mcmFsuJt5VCq0hRqwdq8caOT3RDKGG0ezVNF6kHmBsbn1Im+yHdVpzea1vv6FzJdT4xauoji2hB6xmei+cm8CFVfPt55PPoi4zZbuzctz0ZCRqlAhCwBPJ+5ZlP0eJQ4Rgr/usaTNTSsZ2t7jmrH4DgeV+E2gt/azZ95HEznF8sOZEXcwFt7FRx5GJdGOPZ--S1T1MFF4YoXwPmXG--g+7+Or7izUAf4ur433chfA== \ 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/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..fd4416122a --- /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 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..3311c285f5 --- /dev/null +++ b/config/routes.rb @@ -0,0 +1,28 @@ +Rails.application.routes.draw do + root "home#index" + get "/auth/:provider/callback", to: "sessions#create", as: 'auth_callback' + delete "/logout", to: "sessions#destroy", as: "logout" + + resources :users, except: [:new] + resources :products, except: [:destroy] + resources :categories, only: [:new, :create] + + get "/merchant/:id", to: "users#merchant_dash", as: "merchant_dash" + patch "/merchant/:id", to: "users#update", as: "merchant" + + resources :order_products, only: [:create, :update, :destroy] + patch "order_product/:id/:status", to: "order_products#change_status", as: "change_status" + + resources :orders, only: [:index, :update] + get "/cart", to: "orders#cart", as: "cart" + get "/checkout", to: "orders#checkout", as: "checkout" + get "/confirmation", to: "orders#confirmation", as: "confirmation" + + patch "/products/:id/retire", to: "products#retire", as: "retire" + get "/products/category/:id", to: "products#bycategory", as:"bycategory" + get "/products/merchant/:id", to: "products#bymerchant", as:"bymerchant" + + resources :reviews, only: [:new, :create] + + # For details on the DSL available within this file, see http://guides.rubyonrails.org/routing.html +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/20181017210800_create_users.rb b/db/migrate/20181017210800_create_users.rb new file mode 100644 index 0000000000..8006900e1a --- /dev/null +++ b/db/migrate/20181017210800_create_users.rb @@ -0,0 +1,8 @@ +class CreateUsers < ActiveRecord::Migration[5.2] + def change + create_table :users do |t| + + t.timestamps + end + end +end diff --git a/db/migrate/20181017210816_create_buyers.rb b/db/migrate/20181017210816_create_buyers.rb new file mode 100644 index 0000000000..cc419b7c8c --- /dev/null +++ b/db/migrate/20181017210816_create_buyers.rb @@ -0,0 +1,8 @@ +class CreateBuyers < ActiveRecord::Migration[5.2] + def change + create_table :buyers do |t| + + t.timestamps + end + end +end diff --git a/db/migrate/20181017212743_create_products.rb b/db/migrate/20181017212743_create_products.rb new file mode 100644 index 0000000000..ff23b568b3 --- /dev/null +++ b/db/migrate/20181017212743_create_products.rb @@ -0,0 +1,15 @@ +class CreateProducts < ActiveRecord::Migration[5.2] + def change + create_table :products do |t| + t.references :user, foreign_key: true + t.string :name + t.float :price + t.string :category + t.string :description + t.integer :stock + t.string :photo_url + + t.timestamps + end + end +end diff --git a/db/migrate/20181017213055_rename_buyer_to_merchant.rb b/db/migrate/20181017213055_rename_buyer_to_merchant.rb new file mode 100644 index 0000000000..0417e4b036 --- /dev/null +++ b/db/migrate/20181017213055_rename_buyer_to_merchant.rb @@ -0,0 +1,5 @@ +class RenameBuyerToMerchant < ActiveRecord::Migration[5.2] + def change + rename_table :buyers, :merchants + end +end diff --git a/db/migrate/20181017213808_create_columns_for_user_table.rb b/db/migrate/20181017213808_create_columns_for_user_table.rb new file mode 100644 index 0000000000..900e99274f --- /dev/null +++ b/db/migrate/20181017213808_create_columns_for_user_table.rb @@ -0,0 +1,10 @@ +class CreateColumnsForUserTable < ActiveRecord::Migration[5.2] + def change + create_table :columns_for_user_tables do |t| + add_column :users, :name, :string + add_column :users, :address, :string + add_column :users, :cc_num, :string + add_column :users, :type, :string + end + end +end diff --git a/db/migrate/20181017220137_create_reviews.rb b/db/migrate/20181017220137_create_reviews.rb new file mode 100644 index 0000000000..38ad5457c0 --- /dev/null +++ b/db/migrate/20181017220137_create_reviews.rb @@ -0,0 +1,12 @@ +class CreateReviews < ActiveRecord::Migration[5.2] + def change + create_table :reviews do |t| + t.references :product, foreign_key: true + t.integer :rating + t.string :name + t.string :comment + + t.timestamps + end + end +end diff --git a/db/migrate/20181017221330_create_orders.rb b/db/migrate/20181017221330_create_orders.rb new file mode 100644 index 0000000000..ac0f931eea --- /dev/null +++ b/db/migrate/20181017221330_create_orders.rb @@ -0,0 +1,9 @@ +class CreateOrders < ActiveRecord::Migration[5.2] + def change + create_table :orders do |t| + t.string :status + + t.timestamps + end + end +end diff --git a/db/migrate/20181017221402_create_order_items.rb b/db/migrate/20181017221402_create_order_items.rb new file mode 100644 index 0000000000..cd9db5ef0d --- /dev/null +++ b/db/migrate/20181017221402_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/20181017222202_add_product_and_order_i_ds_to_order_item.rb b/db/migrate/20181017222202_add_product_and_order_i_ds_to_order_item.rb new file mode 100644 index 0000000000..0e022e90aa --- /dev/null +++ b/db/migrate/20181017222202_add_product_and_order_i_ds_to_order_item.rb @@ -0,0 +1,6 @@ +class AddProductAndOrderIDsToOrderItem < ActiveRecord::Migration[5.2] + def change + add_reference :order_items, :product, foreign_key: true + add_reference :order_items, :order, foreign_key: true + end +end diff --git a/db/migrate/20181017222331_add_user_to_order.rb b/db/migrate/20181017222331_add_user_to_order.rb new file mode 100644 index 0000000000..85c311cf28 --- /dev/null +++ b/db/migrate/20181017222331_add_user_to_order.rb @@ -0,0 +1,5 @@ +class AddUserToOrder < ActiveRecord::Migration[5.2] + def change + add_reference :orders, :user, foreign_key: true + end +end diff --git a/db/migrate/20181017223632_rename_order_item_table.rb b/db/migrate/20181017223632_rename_order_item_table.rb new file mode 100644 index 0000000000..a34451cb95 --- /dev/null +++ b/db/migrate/20181017223632_rename_order_item_table.rb @@ -0,0 +1,5 @@ +class RenameOrderItemTable < ActiveRecord::Migration[5.2] + def change + rename_table :order_items, :order_product + end +end diff --git a/db/migrate/20181017223749_rename_order_product.rb b/db/migrate/20181017223749_rename_order_product.rb new file mode 100644 index 0000000000..9011d3cb75 --- /dev/null +++ b/db/migrate/20181017223749_rename_order_product.rb @@ -0,0 +1,5 @@ +class RenameOrderProduct < ActiveRecord::Migration[5.2] + def change + rename_table :order_product, :order_products + end +end diff --git a/db/migrate/20181017230015_add_cc_info_to_user.rb b/db/migrate/20181017230015_add_cc_info_to_user.rb new file mode 100644 index 0000000000..be4fb5d23a --- /dev/null +++ b/db/migrate/20181017230015_add_cc_info_to_user.rb @@ -0,0 +1,7 @@ +class AddCcInfoToUser < ActiveRecord::Migration[5.2] + def change + add_column :users, :cc_exp, :datetime + add_column :users, :bill_zip, :integer + add_column :users, :cc_csv, :integer + end +end diff --git a/db/migrate/20181018040120_change_reviews_column.rb b/db/migrate/20181018040120_change_reviews_column.rb new file mode 100644 index 0000000000..7cd38e6ef1 --- /dev/null +++ b/db/migrate/20181018040120_change_reviews_column.rb @@ -0,0 +1,6 @@ +class ChangeReviewsColumn < ActiveRecord::Migration[5.2] + def change + add_reference :reviews, :user, foreign_key: true + remove_column :reviews, :name + end +end diff --git a/db/migrate/20181018044236_create_categories.rb b/db/migrate/20181018044236_create_categories.rb new file mode 100644 index 0000000000..6ccc3914a0 --- /dev/null +++ b/db/migrate/20181018044236_create_categories.rb @@ -0,0 +1,9 @@ +class CreateCategories < ActiveRecord::Migration[5.2] + def change + create_table :categories do |t| + t.string :name + + t.timestamps + end + end +end diff --git a/db/migrate/20181018050221_add_category_fkey_to_product.rb b/db/migrate/20181018050221_add_category_fkey_to_product.rb new file mode 100644 index 0000000000..fdfa4e4eac --- /dev/null +++ b/db/migrate/20181018050221_add_category_fkey_to_product.rb @@ -0,0 +1,6 @@ +class AddCategoryFkeyToProduct < ActiveRecord::Migration[5.2] + def change + remove_column :products, :category + add_reference :products, :category, foreign_key: true + end +end diff --git a/db/migrate/20181018172139_add_auth_hash_info_to_users_table.rb b/db/migrate/20181018172139_add_auth_hash_info_to_users_table.rb new file mode 100644 index 0000000000..5ceeeb54f6 --- /dev/null +++ b/db/migrate/20181018172139_add_auth_hash_info_to_users_table.rb @@ -0,0 +1,7 @@ +class AddAuthHashInfoToUsersTable < ActiveRecord::Migration[5.2] + def change + add_column :users, :uid, :integer, null: false + add_column :users, :provider, :string, null: false + add_column :users, :email, :string + end +end diff --git a/db/migrate/20181018223725_remove_extra_table.rb b/db/migrate/20181018223725_remove_extra_table.rb new file mode 100644 index 0000000000..34038b84e2 --- /dev/null +++ b/db/migrate/20181018223725_remove_extra_table.rb @@ -0,0 +1,5 @@ +class RemoveExtraTable < ActiveRecord::Migration[5.2] + def change + drop_table :columns_for_user_tables + end +end diff --git a/db/migrate/20181023171757_add_status_to_pd.rb b/db/migrate/20181023171757_add_status_to_pd.rb new file mode 100644 index 0000000000..556b9f1a62 --- /dev/null +++ b/db/migrate/20181023171757_add_status_to_pd.rb @@ -0,0 +1,5 @@ +class AddStatusToPd < ActiveRecord::Migration[5.2] + def change + add_column :products, :status, :boolean, default: true + end +end diff --git a/db/migrate/20181023195454_add_status_to_op.rb b/db/migrate/20181023195454_add_status_to_op.rb new file mode 100644 index 0000000000..6b6758aced --- /dev/null +++ b/db/migrate/20181023195454_add_status_to_op.rb @@ -0,0 +1,5 @@ +class AddStatusToOp < ActiveRecord::Migration[5.2] + def change + add_column :order_products, :status, :string + end +end diff --git a/db/migrate/20181023221846_add_status_to_user.rb b/db/migrate/20181023221846_add_status_to_user.rb new file mode 100644 index 0000000000..f3a61bcd2b --- /dev/null +++ b/db/migrate/20181023221846_add_status_to_user.rb @@ -0,0 +1,5 @@ +class AddStatusToUser < ActiveRecord::Migration[5.2] + def change + add_column :users, :status, :string, default: "active" + end +end diff --git a/db/migrate/20181024213616_remove_fkey_from_review.rb b/db/migrate/20181024213616_remove_fkey_from_review.rb new file mode 100644 index 0000000000..0bdae22829 --- /dev/null +++ b/db/migrate/20181024213616_remove_fkey_from_review.rb @@ -0,0 +1,6 @@ +class RemoveFkeyFromReview < ActiveRecord::Migration[5.2] + def change + remove_reference :reviews, :user, foreign_key: true + add_column :reviews, :reviewer, :string + end +end diff --git a/db/migrate/20181025052500_products_categories_join.rb b/db/migrate/20181025052500_products_categories_join.rb new file mode 100644 index 0000000000..dabacc4378 --- /dev/null +++ b/db/migrate/20181025052500_products_categories_join.rb @@ -0,0 +1,8 @@ +class ProductsCategoriesJoin < ActiveRecord::Migration[5.2] + def change + create_table :products_categories do |t| + t.belongs_to :product, index: true + t.belongs_to :category, index: true + end + end +end diff --git a/db/migrate/20181025062434_remove_category_id_from_product.rb b/db/migrate/20181025062434_remove_category_id_from_product.rb new file mode 100644 index 0000000000..2508ca3dfd --- /dev/null +++ b/db/migrate/20181025062434_remove_category_id_from_product.rb @@ -0,0 +1,5 @@ +class RemoveCategoryIdFromProduct < ActiveRecord::Migration[5.2] + def change + remove_reference :products, :category, foreign_key: true + end +end diff --git a/db/migrate/20181025163059_delete_product_category_ralationtable.rb b/db/migrate/20181025163059_delete_product_category_ralationtable.rb new file mode 100644 index 0000000000..c5f8f3152d --- /dev/null +++ b/db/migrate/20181025163059_delete_product_category_ralationtable.rb @@ -0,0 +1,5 @@ +class DeleteProductCategoryRalationtable < ActiveRecord::Migration[5.2] + def change + drop_table :products_categories + end +end diff --git a/db/migrate/20181025163926_create_categories_products_relation_table.rb b/db/migrate/20181025163926_create_categories_products_relation_table.rb new file mode 100644 index 0000000000..a0e7271c47 --- /dev/null +++ b/db/migrate/20181025163926_create_categories_products_relation_table.rb @@ -0,0 +1,8 @@ +class CreateCategoriesProductsRelationTable < ActiveRecord::Migration[5.2] + def change + create_table :categories_products do |t| + t.belongs_to :category, index: true + t.belongs_to :product, index: true + end + end +end diff --git a/db/migrate/20181025171011_add_category_column_to_product.rb b/db/migrate/20181025171011_add_category_column_to_product.rb new file mode 100644 index 0000000000..da8f338d3c --- /dev/null +++ b/db/migrate/20181025171011_add_category_column_to_product.rb @@ -0,0 +1,5 @@ +class AddCategoryColumnToProduct < ActiveRecord::Migration[5.2] + def change + add_column :products, :category, :string + end +end diff --git a/db/migrate/20181025172603_fix_category_column_in_product.rb b/db/migrate/20181025172603_fix_category_column_in_product.rb new file mode 100644 index 0000000000..c168c69b96 --- /dev/null +++ b/db/migrate/20181025172603_fix_category_column_in_product.rb @@ -0,0 +1,6 @@ +class FixCategoryColumnInProduct < ActiveRecord::Migration[5.2] + def change + remove_column :products, :category + + end +end diff --git a/db/schema.rb b/db/schema.rb new file mode 100644 index 0000000000..28e3b82982 --- /dev/null +++ b/db/schema.rb @@ -0,0 +1,99 @@ +# 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: 2018_10_25_172603) do + + # These are extensions that must be enabled in order to support this database + enable_extension "plpgsql" + + create_table "categories", force: :cascade do |t| + t.string "name" + t.datetime "created_at", null: false + t.datetime "updated_at", null: false + end + + create_table "categories_products", force: :cascade do |t| + t.bigint "category_id" + t.bigint "product_id" + t.index ["category_id"], name: "index_categories_products_on_category_id" + t.index ["product_id"], name: "index_categories_products_on_product_id" + end + + create_table "merchants", force: :cascade do |t| + t.datetime "created_at", null: false + t.datetime "updated_at", null: false + end + + create_table "order_products", force: :cascade do |t| + t.integer "quantity" + t.datetime "created_at", null: false + t.datetime "updated_at", null: false + t.bigint "product_id" + t.bigint "order_id" + t.string "status" + t.index ["order_id"], name: "index_order_products_on_order_id" + t.index ["product_id"], name: "index_order_products_on_product_id" + end + + create_table "orders", force: :cascade do |t| + t.string "status" + t.datetime "created_at", null: false + t.datetime "updated_at", null: false + t.bigint "user_id" + t.index ["user_id"], name: "index_orders_on_user_id" + end + + create_table "products", force: :cascade do |t| + t.bigint "user_id" + t.string "name" + t.float "price" + t.string "description" + t.integer "stock" + t.string "photo_url" + t.datetime "created_at", null: false + t.datetime "updated_at", null: false + t.boolean "status", default: true + t.index ["user_id"], name: "index_products_on_user_id" + end + + create_table "reviews", force: :cascade do |t| + t.bigint "product_id" + t.integer "rating" + t.string "comment" + t.datetime "created_at", null: false + t.datetime "updated_at", null: false + t.string "reviewer" + t.index ["product_id"], name: "index_reviews_on_product_id" + end + + create_table "users", force: :cascade do |t| + t.datetime "created_at", null: false + t.datetime "updated_at", null: false + t.string "name" + t.string "address" + t.string "cc_num" + t.string "type" + t.datetime "cc_exp" + t.integer "bill_zip" + t.integer "cc_csv" + t.integer "uid", null: false + t.string "provider", null: false + t.string "email" + t.string "status", default: "active" + end + + add_foreign_key "order_products", "orders" + add_foreign_key "order_products", "products" + add_foreign_key "orders", "users" + add_foreign_key "products", "users" + add_foreign_key "reviews", "products" +end diff --git a/db/seeds.rb b/db/seeds.rb new file mode 100644 index 0000000000..9166c18b59 --- /dev/null +++ b/db/seeds.rb @@ -0,0 +1,107 @@ +# This file should contain all the record creation needed to seed the database with its default values. +# The data can then be loaded with the rails db:seed command (or created alongside the database with db:setup). +# +# Examples: +# +# movies = Movie.create([{ name: 'Star Wars' }, { name: 'Lord of the Rings' }]) +# Character.create(name: 'Luke', movie: movies.first) + +require 'faker' +require 'date' + +category_failures = [] + +cate_list = ["Senate", "House", "Midterms", "Swing"] + +cate_list.each do |cate| + category = Category.new + category.name = cate + successful = category.save + if !successful + category_failures << category + puts "Failed to save category: #{category.inspect}" + else + puts "Created category: #{category.inspect}" + end +end + +puts "Added #{Category.count} category records" +puts "#{category_failures.length} category failed to save" + + + +# user_failures = [] +# +# 5.times do |i| +# user_name = Faker::Name.name +# user = User.new +# user.name = user_name +# user.uid = rand(10) +# user.provider = "github" +# successful = user.save +# if !successful +# user_failures << user +# puts "Failed to save user: #{user.inspect}" # so user can check that work to see what happened +# else +# puts "Created user: #{user.inspect}" +# end +# end +# +# puts "Added #{User.count} user records" +# puts "#{user_failures.length} users failed to save" + +merchant_failures = [] + +10.times do |i| + merchant_name = Faker::GameOfThrones.unique.character + merchant = Merchant.new + merchant.type = "Merchant" + merchant.name = merchant_name + merchant.uid = rand(10) + merchant.provider = "github" + successful = merchant.save + if !successful + merchant_failures << merchant + puts "Failed to save merchant: #{merchant.inspect}" # so user can check that work to see what happened + else + puts "Created merchant: #{merchant.inspect}" + end +end + +puts "Added #{Merchant.count} merchant records" +puts "#{merchant_failures.length} merchant failed to save" + +product_failures = [] + +100.times do |i| + + merchant_list = Merchant.all + state = Faker::Address.state + product_name = "#{state} Election #{rand(10) + 1}" + + product = Product.new + product.name = product_name + product.stock = rand(15) + 1 + product.description = "I don't think anybody knows it was Russia that wrote Lorem Ipsum, but I don't know, maybe it was. It could be Russia, but it could also be China. It could also be lots of other people. It also could be some wordsmith sitting on their bed that weights 400 pounds. Ok? If Trump Ipsum weren’t my own words, perhaps I’d be dating it. Be careful, or I will spill the beans on your placeholder text. I think the only card she has is the Lorem card. When other websites give you text, they’re not sending the best. They’re not sending you, they’re sending words that have lots of problems and they’re bringing those problems with us. They’re bringing mistakes. They’re bringing misspellings. They’re typists… And some, I assume, are good words. I have a 10 year old son. He has words. He is so good with these words it's unbelievable." + product.price = rand(9000) + rand(900) + rand(90) + + product.user = merchant_list.sample + product.photo_url = "https://loremflickr.com/300/300/politics?random=#{i+1}" + successful = product.save + + if !successful + product_failures << product + puts "Failed to save product: #{product.inspect}" # so user can check that work to see what happened + else + puts "Created product: #{product.inspect}" + end +end + +puts "Added #{Product.count} product records" +puts "#{product_failures.length} products failed to save" + +Product.all.each do |prod| + a = Category.all.shuffle + prod.categories << a.first + prod.categories << a.last +end diff --git a/lib/assets/.keep b/lib/assets/.keep new file mode 100644 index 0000000000..e69de29bb2 diff --git a/lib/tasks/.keep b/lib/tasks/.keep new file mode 100644 index 0000000000..e69de29bb2 diff --git a/log/.keep b/log/.keep new file mode 100644 index 0000000000..e69de29bb2 diff --git a/package.json b/package.json new file mode 100644 index 0000000000..f874acf437 --- /dev/null +++ b/package.json @@ -0,0 +1,5 @@ +{ + "name": "betsy", + "private": true, + "dependencies": {} +} diff --git a/public/404.html b/public/404.html new file mode 100644 index 0000000000..2be3af26fc --- /dev/null +++ b/public/404.html @@ -0,0 +1,67 @@ + + + + The page you were looking for doesn't exist (404) + + + + + + +
+
+

The page you were looking for doesn't exist.

+

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

+
+

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

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

The change you wanted was rejected.

+

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

+
+

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

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

We're sorry, but something went wrong.

+
+

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

+
+ + diff --git a/public/apple-touch-icon-precomposed.png b/public/apple-touch-icon-precomposed.png new file mode 100644 index 0000000000..e69de29bb2 diff --git a/public/apple-touch-icon.png b/public/apple-touch-icon.png new file mode 100644 index 0000000000..e69de29bb2 diff --git a/public/favicon.ico b/public/favicon.ico new file mode 100644 index 0000000000..e69de29bb2 diff --git a/public/robots.txt b/public/robots.txt new file mode 100644 index 0000000000..37b576a4a0 --- /dev/null +++ b/public/robots.txt @@ -0,0 +1 @@ +# See http://www.robotstxt.org/robotstxt.html for documentation on how to use the robots.txt file diff --git a/storage/.keep b/storage/.keep new file mode 100644 index 0000000000..e69de29bb2 diff --git a/test/application_system_test_case.rb b/test/application_system_test_case.rb new file mode 100644 index 0000000000..d19212abd5 --- /dev/null +++ b/test/application_system_test_case.rb @@ -0,0 +1,5 @@ +require "test_helper" + +class ApplicationSystemTestCase < ActionDispatch::SystemTestCase + driven_by :selenium, using: :chrome, screen_size: [1400, 1400] +end diff --git a/test/controllers/.keep b/test/controllers/.keep new file mode 100644 index 0000000000..e69de29bb2 diff --git a/test/controllers/categories_controller_test.rb b/test/controllers/categories_controller_test.rb new file mode 100644 index 0000000000..9aa78a5f99 --- /dev/null +++ b/test/controllers/categories_controller_test.rb @@ -0,0 +1,66 @@ +require "test_helper" + +describe CategoriesController do + # it "must be a real test" do + # flunk "Need real tests" + # end + describe "new" do + it "can get the new category page" do + + # Act + get new_category_path + + # Assert + must_respond_with :success + end + + it "can get the form with the new_category_path" do + # Arrange + id = categories(:category1).id + + # Act + get new_category_path(id) + + # Assert + must_respond_with :success + end + end + + let (:category_hash) do + { + category: { + name: 'Sports', + } + } + end + + + describe "create" do + it "can create a new category given valid params" do + # Act-Assert + expect { + post categories_path, params: category_hash + }.must_change 'Category.count', 1 + + must_respond_with :redirect + must_redirect_to products_path + + + expect(Category.last.name).must_equal category_hash[:category][:name] + + end + + it "responds with an error for invalid params" do + # Arranges + category_hash[:category][:name] = nil + + # Act-Assert + expect { + post categories_path, params: category_hash + }.wont_change 'Category.count' + + must_respond_with :bad_request + + end + end +end diff --git a/test/controllers/home_controller_test.rb b/test/controllers/home_controller_test.rb new file mode 100644 index 0000000000..4289bf5c81 --- /dev/null +++ b/test/controllers/home_controller_test.rb @@ -0,0 +1,13 @@ +require "test_helper" + +describe HomeController do + describe "index" do + it "succeeds" do + # Act + get root_path + + # Assert + must_respond_with :success + end + end +end diff --git a/test/controllers/order_products_controller_test.rb b/test/controllers/order_products_controller_test.rb new file mode 100644 index 0000000000..ac293e6427 --- /dev/null +++ b/test/controllers/order_products_controller_test.rb @@ -0,0 +1,222 @@ +require "test_helper" + +describe OrderProductsController do + let (:dress) { products(:dress) } + let (:dresses) { order_products(:dresses) } + let (:mumu) { products(:mumu) } + let (:pending_order) { orders(:pending_order) } + let (:op_hash) { { order_product: { + product_id: mumu.id, + status: "pending", + quantity: 2 + } + + } } + + describe "create" do + it "creates a new order product with valid data" do + # Arrange + get product_path(mumu.id) + + # Act + expect { + post order_products_path, params: op_hash + }.must_change 'OrderProduct.count', 1 + + expect(Order.find_by(id: session[:order_id]).order_products.count).must_equal 1 + + must_respond_with :redirect + must_redirect_to cart_path + + expect(OrderProduct.last.product.id).must_equal op_hash[:order_product][:product_id] + expect(OrderProduct.last.order_id).must_equal session[:order_id] + expect(OrderProduct.last.status).must_equal op_hash[:order_product][:status] + expect(OrderProduct.last.quantity).must_equal op_hash[:order_product][:quantity] + + expect(session[:order_id]).must_equal (OrderProduct.last.order.id) + end + + it "redirects back to the product page and does not update the DB for bogus data" do + # Arrange + op_hash = { + order_product: { + product_id: mumu.id, + status: "pending", + quantity: 20 + } + } + + # Act + expect { + post order_products_path, params: op_hash + }.wont_change 'OrderProduct.count' + + expect(Order.find_by(id: session[:order_id])).must_be_nil + + must_respond_with :redirect + must_redirect_to products_path + + expect(flash[:warning]).must_equal "Error: Could not add product to cart" + end + end + + describe "update" do + it "succeeds for valid data and an existing order_product" do + # Arrange + post order_products_path, params: op_hash + op = OrderProduct.last + order = Order.find_by(id: op.order.id) + start_count = order.order_products.count + + op_hash2 = { + order_product: { + quantity: 1 + } + } + + expect { + patch order_product_path(op.id), params: op_hash2 + }.wont_change 'OrderProduct.count' + + # TODO: not saving to pending_order, likely because creating new order in @current_order + expect(order.order_products.count).must_equal start_count + + must_respond_with :redirect + must_redirect_to cart_path + + expect(OrderProduct.last.product_id).must_equal op_hash[:order_product][:product_id] + expect(OrderProduct.last.order.id).must_equal session[:order_id] + expect(OrderProduct.last.status).must_equal op_hash[:order_product][:status] + expect(OrderProduct.last.quantity).must_equal op_hash2[:order_product][:quantity] + end + + it "redirects back to the product page and does not update the DB for bogus data" do + # Arrange + post order_products_path, params: op_hash + op = OrderProduct.last + order = Order.find_by(id: op.order.id) + start_count = order.order_products.count + + op_hash2 = { + order_product: { + quantity: 100 + } + } + + expect { + patch order_product_path(op.id), params: op_hash2 + }.wont_change 'OrderProduct.count' + + # TODO: not saving to pending_order, likely because creating new order in @current_order + expect(order.order_products.count).must_equal start_count + + must_respond_with :redirect + must_redirect_to cart_path + + expect(flash[:warning]).must_equal "Error: Could not update product order" + end + + it "reduces the order product count by 1 if quantity is adjusted to 0" do + # Arrange + post order_products_path, params: op_hash + op = OrderProduct.last + order = Order.find_by(id: op.order.id) + start_count = order.order_products.count + + op_hash2 = { + order_product: { + quantity: 0 + } + } + + expect { + patch order_product_path(op.id), params: op_hash2 + }.must_change 'OrderProduct.count', -1 + + expect(order.order_products.count).must_equal (start_count - 1) + + must_respond_with :redirect + must_redirect_to cart_path + + expect(flash[:success]).must_equal "Removed #{op.product.name} from cart" + end + end + + describe "destroy" do + it "succeeds for an existing order product ID" do + # Arrange done with let + + # Act + expect { + delete order_product_path(dresses.id) + }.must_change 'OrderProduct.count', -1 + + must_respond_with :redirect + must_redirect_to cart_path + + expect(flash[:success]).must_equal "Removed #{dresses.product.name} from cart" + + expect(OrderProduct.find_by(id: dresses.id)).must_be_nil + end + + it "displays a flash message and does not update the DB for a bogus order product" do + id = -1 + + expect { + delete order_product_path(id) + }.wont_change 'OrderProduct.count' + + must_respond_with :redirect + must_redirect_to cart_path + + expect(flash[:warning]).must_equal "Error: Could not remove product from cart" + end + end + + describe "change_status" do + it "updates the order product status if current user is the product seller" do + # Arrange + dresses.status = "paid" + dresses.save + + perform_login(merchants(:merchant)) + + patch change_status_path(dresses.id, "shipped") + + must_respond_with :redirect + must_redirect_to merchant_dash_path(merchants(:merchant).id) + + expect(flash[:success]).must_equal "Updated status for Product Order ##{dresses.id} to shipped" + end + + it "updates the order product status if current user is the buyer" do + # Arrange + dresses.status = "paid" + dresses.save + + perform_login(users(:user1)) + + patch change_status_path(dresses.id, "cancelled") + + must_respond_with :redirect + must_redirect_to root_path + + expect(flash[:success]).must_equal "Cancelled Product Order ##{dresses.id}" + end + + it "does not update the status if the current user doesn't have appropriate permissions" do + # Arrange + dresses.status = "paid" + dresses.save + + perform_login(users(:no_order_user)) + + patch change_status_path(dresses.id, "cancelled") + + must_respond_with :redirect + must_redirect_to root_path + + expect(flash[:warning]).must_equal "Could not update status for Product Order ##{dresses.id}" + 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..1f5fa6ddd9 --- /dev/null +++ b/test/controllers/orders_controller_test.rb @@ -0,0 +1,187 @@ +require "test_helper" + +describe OrdersController do + let(:pending_order) { orders(:pending_order) } + let(:empty_order) { orders(:empty_order) } + let(:dress) { products(:dress) } + let(:dress_hash) { + dress_hash = { + order_product: { + product_id: products(:dress).id, + quantity: 1, + } + } + } + + describe "cart" do + it "succeeds when things are in the cart" do + # Arrange + get product_path(dress.id) + post order_products_path, params: dress_hash + + # Act + get cart_path + + # Assert + must_respond_with :success + expect(Order.find_by(id: session[:order_id]).order_products.any?).must_equal true + end + + it "succeeds when nothing is in the cart" do + # Arrange + get root_path + + # Act + get cart_path + + # Assert + must_respond_with :success + expect(session[:order_id]).must_be_nil + end + end + + describe "checkout" do + it "succeeds when things are in the cart" do + # Arrange + get product_path(dress.id) + post order_products_path, params: dress_hash + + # Act + get checkout_path + + # Assert + must_respond_with :success + expect(Order.find_by(id: session[:order_id]).order_products.any?).must_equal true + end + + it "redirects back to the cart when the cart is empty" do + # Arrange + get root_path + + # Act + get checkout_path + + # Assert + must_respond_with :redirect + must_redirect_to cart_path + expect(flash[:warning]).must_equal "You must add something to your cart before you can checkout" + end + end + + describe "update" do + it "succeeds for valid data and an existing order ID" do + # Arrange done with let + get product_path(dress.id) + post order_products_path, params: dress_hash + + order = Order.find_by(id: session[:order_id]) + + order_user_hash = { + order: { + user_attributes: { + id: order.user.id, + name: "Henrietta", + email: 'email@email.com', + provider: 'github', + cc_num: 8790451276789084, + cc_csv: 678, + cc_exp: '09/08/22', + address: '123 Main St USA', + bill_zip: 10012 + } + } + } + + expect { + patch order_path(order.id), params: order_user_hash + }.wont_change 'Order.count' + + must_respond_with :redirect + must_redirect_to confirmation_path + + expect(Order.find_by(id: order.id).status).must_equal "paid" + expect(session[:order_id]).must_be_nil + end + + it "redirects when given bogus data" do + get product_path(dress.id) + post order_products_path, params: dress_hash + + order = Order.find_by(id: session[:order_id]) + + order_user_hash = { + order: { + user_attributes: { + id: order.user.id, + name: "Henrietta", + email: 'email@email.com', + cc_num: 'should be invalid', + cc_csv: 123, + cc_exp: '09/08/22', + address: '123 Main St USA', + bill_zip: 10012 + } + } + } + + expect { + patch order_path(order.id), params: order_user_hash + }.wont_change 'Order.count' + + must_respond_with :redirect + must_redirect_to checkout_path + expect(order.status).must_equal "pending" + expect(flash[:warning]).must_equal "Could not submit order" + expect(session[:order_id]).must_equal order.id + end + end + + describe "confirmation" do + it "succeeds when given valid data" do + # Arrange + get product_path(dress.id) + post order_products_path, params: dress_hash + + order = Order.find_by(id: session[:order_id]) + + order_user_hash = { + order: { + user_attributes: { + id: order.user.id, + name: "Henrietta", + email: 'email@email.com', + provider: 'github', + cc_num: 8790451276789084, + cc_csv: 678, + cc_exp: '09/08/22', + address: '123 Main St USA', + bill_zip: 10012 + } + } + } + + # Act - Assert + patch order_path(order.id), params: order_user_hash + expect(session[:paid_order_id]).must_equal order.id + + get confirmation_path + + must_respond_with :success + expect(session[:paid_order_id]).must_be_nil + end + + it "fails if order has not been paid for" do + get product_path(dress.id) + post order_products_path, params: dress_hash + + order = Order.find_by(id: session[:order_id]) + + get checkout_path + get confirmation_path + + must_respond_with :redirect + must_redirect_to checkout_path + expect(flash[:warning]).must_equal "Error: Order payment did not go through" + 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..71aaba293c --- /dev/null +++ b/test/controllers/products_controller_test.rb @@ -0,0 +1,348 @@ +require "test_helper" +require 'pry' + +describe ProductsController do + let(:product) { products(:shirt) } + let(:product2) {products(:dress)} + let(:user) { users(:user1) } + let(:cc_user) { users(:cc_user) } + let(:cc_merchant) { merchants(:cc_merchant) } + let(:merchant) { merchants(:merchant) } + let(:category1) {categories(:category1)} + let(:category2) {categories(:category2)} + + + it "should get index" do + get products_path + + must_respond_with :success + end + + describe "show" do + it "should get a product's show page" do + # Arrange + id = products(:shirt).id + + # Act + get product_path(id) + + # Assert + must_respond_with :success + end + + it "should respond with not_found if given an invalid id" do + # Arrange - invalid id + id = -1 + + # Act + get product_path(id) + + # Assert + must_respond_with :not_found + end + end + + describe "bycategory" do + it "should get the bycategory page for valid category id" do + # Arrange + id = category1.id + + # Act + get bycategory_path(id) + + # Assert + must_respond_with :success + end + + it "should respond with not_found if given an invalid id" do + # Arrange - invalid id + id = -1 + + # Act + get bycategory_path(id) + + # Assert + must_respond_with :not_found + end + end + + describe "bymerchant" do + it "should get the bymerchant page for valid merchant id" do + # Arrange + id = cc_user.id + + # Act + get bymerchant_path(id) + + # Assert + must_respond_with :success + end + + it "should respond with not_found if given an invalid id" do + # Arrange - invalid id + id = -1 + + # Act + get bymerchant_path(id) + + # Assert + must_respond_with :not_found + end + end + + + + + describe "new" do + it "can get the new product page" do + + # Act + get new_product_path + + # Assert + + end + + it "can get the form with the new_product_path with user logged in" do + # Arrange + + user = users(:cc_user) + perform_login(user) + expect(session[:user_id]).wont_be_nil + + id = product.id + + # Act + get new_product_path(id) + # Assert + must_respond_with :success + end + + + end + + describe "edit" do + it "can get the edit page for a valid product sold by a logged in merchant" do + # Arrange + id = product.id + product.user = cc_user + perform_login(cc_user) + # Act + get edit_product_path(id) + + # Assert + must_respond_with :success + end + + it "cannot get the edit page for a valid product not sold by a logged in merchant" do + # Arrange + id = product.id + + perform_login(cc_user) + # Act + expect{get edit_product_path(id)} + + # Assert + + end + + it "should respond with not_found if given an invalid id" do + # Arrange - invalid id + id = -1 + + # Act + get edit_product_path(id) + + # Assert + expect(response).must_be :not_found? + must_respond_with :not_found + expect(flash[:warning]).must_equal "Cannot find the product -1" + end + + # not log in user cannot edit + + # log in user can edit own + + # logn in user cannot edit others + + # display not found for invalid post id.. + + + end + + describe "retire" do + it "can retire a product by the logged merchant who created the product" do + # Arrange + id = product.id + name = product.id + + perform_login(cc_user) + product.user = cc_user + + # Act - Assert + expect { + patch retire_path(id) + }.must_change 'Product.active_products.count', -1 + + must_respond_with :redirect + must_redirect_to products_path + expect(flash[:success]).must_equal "#{product.name} retired" + expect(Product.find_by(id: id).status).must_equal false + end + + it "should respond with not_found for an invalid product id" do + id = -1 + + expect { + patch product_path(id) + # }.must_change 'Book.count', 0 + }.wont_change 'Product.active_products.count' + + must_respond_with :not_found + expect(flash.now[:warning]).must_equal "Cannot find the product #{id}" + end + + # it "should respond with not_found for a user not logged in" do + # + # end + end + + describe "create & update" do + + + let (:product_hash) do + { + product: { + name: 'White Teeth', + user_id: cc_merchant.id, + price: 10, + stock: 5, + description: 'Good book', + category_ids: [category1.id] + } + } + + + end + + + describe "create" do + it "can create a new product given valid params by logged in merchant" do + # Act-Assert + merchant = merchants(:cc_merchant) + # Make fake session + # Tell OmniAuth to use this user's info when it sees + # an auth callback from github + OmniAuth.config.mock_auth[:github] = OmniAuth::AuthHash.new(mock_auth_hash(merchant)) + get auth_callback_path('github') + + + expect { + post products_path, params: product_hash + }.must_change 'Product.count', 1 + + + must_respond_with :redirect + + expect(Product.last.name).must_equal product_hash[:product][:name] + expect(Product.last.user).must_equal merchant + + expect(Product.last.stock).must_equal product_hash[:product][:stock] + expect(Product.last.price).must_equal product_hash[:product][:price] + end + + it "responds with an error for invalid params" do + # Arranges + merchant = merchants(:cc_merchant) + + OmniAuth.config.mock_auth[:github] = OmniAuth::AuthHash.new(mock_auth_hash(merchant)) + get auth_callback_path('github') + product_hash[:product][:name] = nil + + # Act-Assert + expect { + post products_path, params: product_hash + }.wont_change 'Product.count' + + must_respond_with :bad_request + + end + end + + describe "update" do + let (:update_hash) do + { + product: { + name: 'White Teeth', + user_id: merchant.id, + price: 10, + stock: 5, + description: 'Good book', + category_ids: [category1.id] + } + } + end + + + it "can update a product with valid params by logged in user" do + + merchant = merchants(:merchant) + + OmniAuth.config.mock_auth[:github] = OmniAuth::AuthHash.new(mock_auth_hash(merchant)) + get auth_callback_path('github') + + id = product.id + + expect { + patch product_path(id), params: update_hash + }.wont_change 'Product.count' + + + must_respond_with :redirect + must_redirect_to product_path(id) + + new_product= Product.find_by(id: id) + + expect(new_product.name).must_equal product_hash[:product][:name] + expect(new_product.user).must_equal merchant + expect(new_product.stock).must_equal product_hash[:product][:stock] + expect(new_product.price).must_equal product_hash[:product][:price] + end + it "gives an error if the product params are invalid" do + # Arrange + product_hash[:product][:name] = nil + merchant = merchants(:merchant) + + + OmniAuth.config.mock_auth[:github] = OmniAuth::AuthHash.new(mock_auth_hash(merchant)) + get auth_callback_path('github') + + id = product.id + + + expect { + patch product_path(id), params: product_hash + }.wont_change 'Product.count' + new_product = Product.find(id) + + must_respond_with :bad_request + expect(product.name).must_equal new_product.name + expect(product.user).must_equal merchant + expect(product.price).must_equal new_product.price + expect(product.stock).must_equal new_product.stock + end + it "gives not_found for a product that doesn't exist" do + id = -1 + + expect { + patch product_path(id), params: product_hash + }.wont_change 'Product.count' + + must_respond_with :not_found + + 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..386065239a --- /dev/null +++ b/test/controllers/reviews_controller_test.rb @@ -0,0 +1,7 @@ +require "test_helper" + +describe ReviewsController do + # it "must be a real test" do + # flunk "Need real tests" + # end +end diff --git a/test/controllers/sessions_controller_test.rb b/test/controllers/sessions_controller_test.rb new file mode 100644 index 0000000000..66d31af6eb --- /dev/null +++ b/test/controllers/sessions_controller_test.rb @@ -0,0 +1,31 @@ +require "test_helper" + +describe SessionsController do + describe "create" do + #remember merchants are a subclass of user, so will be included in count as well + it "Can log in an existing user" do + # Arrange + user = users(:cc_user) + + #Act/Assert + expect {perform_login(user)}.wont_change('User.count') + must_redirect_to root_path + expect(session[:user_id]).must_equal user.id + end + + it "Can log in a new user with good data" do + # Arrange + user = users(:no_order_user) + user.destroy + + #Act/Assert + expect{perform_login(user)}.must_change('User.count', -1) + must_redirect_to edit_user_path(session:user_id) + expect(session[:user_id]).wont_be_nil + end + + it "Rejects a user with invalid data" do + + end + end +end diff --git a/test/controllers/user_controller_test.rb b/test/controllers/user_controller_test.rb new file mode 100644 index 0000000000..a21a846910 --- /dev/null +++ b/test/controllers/user_controller_test.rb @@ -0,0 +1,107 @@ +require "test_helper" + +describe UsersController do + let(:user) {users(:user1)} + + # describe Merchant do + # + # it "should allow edits to own products" do + # + # end + # + # it "should not allow type-merchant to purchase own products" do + # + # + # + # end + # + # it "allows a merchant to downgrade to a regular user" do + # + # end + # + # end #merchant tests end + + it "logs in an existing user" do + start_count = User.count + + perform_login(user) + session[:user_id].must_equal user.id + + # Should *not* have created a new user + User.count.must_equal start_count + end + + it "assigns instances created with User.new with type: 'Merchant' to the Merchant subclass" do + #testing User.new with type: Merchant rather than Merchant.new + user = User.new(name: "Sadie", type: "Merchant", uid: 98900, provider: "sovietski") + + expect(user).must_be_instance_of Merchant + expect(user).must_be_kind_of User + expect(user).wont_be_instance_of User + end + + # it "does not allow edits to products" do + # + # end + # + # it "does not allow deletion of products" do + # + # end + # + # it "allows user to edit quantity in order(shopping cart)" do + # + # end + # + # it "allows user to remove items to cart" do + # + # end + # + # it "allows user to add items to cart" do + # + # end + # + # it "allows user to edit their user information" do + # + # end + # + # it "allows a user to become a merchant" do + # + # end + + + # it "should get index" do + # get user_index + # value(response).must_be :success? + # end + # + # it "should get new" do + # get user_new + # value(response).must_be :success? + # end + # + # it "should get show" do + # get user_show + # value(response).must_be :success? + # end + # + # it "should get update" do + # get user_update + # value(response).must_be :success? + # end + # + # it "should get destroy" do + # get user_destroy + # value(response).must_be :success? + # end + # + # it "should get edit" do + # get user_edit + # value(response).must_be :success? + # end + # + # it "should get create" do + # get user_create + # value(response).must_be :success? + # 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..75fab053a0 --- /dev/null +++ b/test/fixtures/categories.yml @@ -0,0 +1,7 @@ +# Read about fixtures at http://api.rubyonrails.org/classes/ActiveRecord/FixtureSet.html + +category1: + name: "category 1" + +category2: + name: "category 2" diff --git a/test/fixtures/files/.keep b/test/fixtures/files/.keep new file mode 100644 index 0000000000..e69de29bb2 diff --git a/test/fixtures/merchants.yml b/test/fixtures/merchants.yml new file mode 100644 index 0000000000..3e774ab7d7 --- /dev/null +++ b/test/fixtures/merchants.yml @@ -0,0 +1,40 @@ +# Read about fixtures at http://api.rubyonrails.org/classes/ActiveRecord/FixtureSet.html + +# This model initially had no columns defined. If you add columns to the +# model remove the "{}" from the fixture names and add the columns immediately +# below each fixture, per the syntax in the comments below +# +merchant: + name: leanne + uid: 897 + type: Merchant + provider: github + +# column: value +# +email_merchant: + name: jackie + uid: 9076 + type: Merchant + email: jackie@jackie.com + provider: github +# column: value + +git_merchant: + name: jessie + type: Merchant + email: jessie@jessie.com + uid: 34578908 + provider: github + +cc_merchant: + name: charles + uid: 9876 + type: Merchant + uid: 97532187 + provider: github + cc_num: 8790451276789084 + cc_csv: 678 + cc_exp: 09/08/22 + address: 123 Main St USA + bill_zip: 10012 diff --git a/test/fixtures/order_products.yml b/test/fixtures/order_products.yml new file mode 100644 index 0000000000..882a859efb --- /dev/null +++ b/test/fixtures/order_products.yml @@ -0,0 +1,13 @@ +# Read about fixtures at http://api.rubyonrails.org/classes/ActiveRecord/FixtureSet.html + +shirts: + quantity: 1 + order: pending_order + product: shirt + status: pending + +dresses: + quantity: 2 + order: pending_order + product: dress + status: pending diff --git a/test/fixtures/orders.yml b/test/fixtures/orders.yml new file mode 100644 index 0000000000..7e0662aa53 --- /dev/null +++ b/test/fixtures/orders.yml @@ -0,0 +1,9 @@ +# Read about fixtures at http://api.rubyonrails.org/classes/ActiveRecord/FixtureSet.html + +pending_order: + status: "pending" + user: user1 + +empty_order: + status: "pending" + user: cc_user diff --git a/test/fixtures/products.yml b/test/fixtures/products.yml new file mode 100644 index 0000000000..5b1c1e82e3 --- /dev/null +++ b/test/fixtures/products.yml @@ -0,0 +1,28 @@ +# Read about fixtures at http://api.rubyonrails.org/classes/ActiveRecord/FixtureSet.html + +shirt: + user: merchant + name: "Shirt" + price: 1.5 + description: "a nice shirt" + stock: 1 + photo_url: "https://loremflickr.com/cache/resized/791_41048349621_da0130f444_300_300_nofilter.jpg" + status: true + +dress: + user: merchant + name: "Dress" + price: 1.5 + description: "a nice dress" + stock: 5 + photo_url: "https://loremflickr.com/cache/resized/791_41048349621_da0130f444_300_300_nofilter.jpg" + status: true + +mumu: + user: merchant + name: "Mumu" + price: 2 + description: "a nice mumu" + stock: 5 + photo_url: "https://loremflickr.com/cache/resized/791_41048349621_da0130f444_300_300_nofilter.jpg" + status: true diff --git a/test/fixtures/reviews.yml b/test/fixtures/reviews.yml new file mode 100644 index 0000000000..2facadd460 --- /dev/null +++ b/test/fixtures/reviews.yml @@ -0,0 +1,12 @@ +# Read about fixtures at http://api.rubyonrails.org/classes/ActiveRecord/FixtureSet.html + +one: + # product: shirt + rating: 1 + comment: MyString + # user: user1 +two: + # product: dress + rating: 2 + comment: MyString + # user: user1 diff --git a/test/fixtures/users.yml b/test/fixtures/users.yml new file mode 100644 index 0000000000..ea0ee1c1a0 --- /dev/null +++ b/test/fixtures/users.yml @@ -0,0 +1,34 @@ +# Read about fixtures at http://api.rubyonrails.org/classes/ActiveRecord/FixtureSet.html + +# This model initially had no columns defined. If you add columns to the +# model remove the "{}" from the fixture names and add the columns immediately +# below each fixture, per the syntax in the comments below +# +user1: + name: jazz + uid: 89076543 + provider: github + cc_num: 8790451276789084 + +# column: value +# +cc_user: + name: hannah + uid: 97532187 + provider: github + cc_num: 8790451276789084 + cc_csv: 678 + cc_exp: 09/08/22 + address: 123 Main St USA + bill_zip: 10012 +# column: value + +no_order_user: + name: daniela + uid: 38039384 + provider: github + cc_num: 8830108373292223 + cc_csv: 678 + cc_exp: 09/08/22 + address: 123 Main St USA + bill_zip: 10012 diff --git a/test/helpers/.keep b/test/helpers/.keep new file mode 100644 index 0000000000..e69de29bb2 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..9c2ed344c0 --- /dev/null +++ b/test/models/category_test.rb @@ -0,0 +1,63 @@ +require "test_helper" + +describe Category do + let(:category) {categories(:category1)} + let(:category2) {categories(:category2)} + + it "must be valid" do + expect(category).must_be :valid? + end + + +it 'has required fields' do + fields = [:name] + + fields.each do |field| + expect(category).must_respond_to field + end +end + +describe 'Relationships' do + + it 'can have many products' do + # Arrange, did with let + + # Act + category.products << Product.first + products = category.products + + # Assert + expect(products.length).must_be :>=, 1 + products.each do |prod| + expect(prod).must_be_instance_of Product + end + end +end + +describe 'validations' do + it 'must have a name' do + # Arrange + + category.name = nil + + + valid = category.save + + # Assert + expect(valid).must_equal false + expect(category.errors.messages).must_include :name + expect(category.errors.messages[:name]).must_equal ["can't be blank"] + end + + + it 'requires a unique name' do + + category2.name = category.name + + valid = category2.valid? + + expect(valid).must_equal false + expect(category2.errors.messages).must_include :name + end +end +end diff --git a/test/models/merchant_test.rb b/test/models/merchant_test.rb new file mode 100644 index 0000000000..10ae8f22cf --- /dev/null +++ b/test/models/merchant_test.rb @@ -0,0 +1,78 @@ +require 'test_helper' + +describe Merchant do + let (:merchant) {merchants(:merchant)} + + it "must be valid" do + value(merchant).must_be :valid? + end + + it "must be an instance of Merchant" do + expect(merchant).must_be_instance_of Merchant + end + + it "must be kind of User" do + expect(merchant).must_be_kind_of User + end + + it "only users with type merchant are instance of merchant" do + not_merchant = users(:user1) + + expect(not_merchant).must_be_instance_of User + expect(not_merchant).wont_be_instance_of Merchant + end + + it "will not create a new merchant if type is nil" do + not_a_merchant = Merchant.new( + name: 'Newbie', + uid: 890, + provider: 'github', + email: 'newbie@newbs.com', + type: nil + ) + + assert_nil(not_a_merchant.type) + expect(not_a_merchant).wont_be_instance_of Merchant + + end + +describe "custom model method: is_a_merchant?" do + let (:merchant) {merchants(:merchant)} + + it "returns true if model is merchant" do + #Act/Assert + expect(merchant).must_be_instance_of Merchant + expect(merchant.is_a_merchant?).must_equal true + end + + it "returns false if model is not a user" do + #Arrange + user = users(:cc_user) + #Act/Assert + expect(user).wont_be_instance_of Merchant + expect(user.is_a_merchant?).must_equal false + end + + it "flips from false to true if user becomes merchant" do + user = users(:user1) + + expect(user.is_a_merchant?).must_equal false #testing turthiness of before value + + user.type = "Merchant" + + expect(user.is_a_merchant?).must_equal true #testing truthiness after change made + end + + it "flops from true to false if a merchant becomes a user" do + expect(merchant.is_a_merchant?).must_equal true #before + + #Assert + merchant.type = nil + + assert_nil(merchant.type) #to be certain change in type made + expect(merchant.is_a_merchant?).must_equal false #after + + end + +end +end diff --git a/test/models/order_product_test.rb b/test/models/order_product_test.rb new file mode 100644 index 0000000000..b44b9b16a2 --- /dev/null +++ b/test/models/order_product_test.rb @@ -0,0 +1,323 @@ +require "test_helper" + +describe OrderProduct do + let(:shirts) { order_products(:shirts) } + let(:dresses) { order_products(:dresses) } + let(:dress) { products(:dress) } + + it "must be valid" do + value(shirts).must_be :valid? + end + + it 'has required fields' do + fields = [:quantity, :order, :product, :status] + + fields.each do |field| + expect(shirts).must_respond_to field + end + end + + describe "relationships" do + it "must belong to an order" do + # Arrange is done with let + + # Act + order = shirts.order + + # Assert + expect(order).must_be_instance_of Order + end + + it "must belong to a product" do + # Arrange is done with let + + # Act + product = shirts.product + + # Assert + expect(product).must_be_instance_of Product + end + end + + describe "validations" do + it "must have a quantity" do + # Arrange + shirts.quantity = nil + + # Act + valid = shirts.valid? + + # Assert + expect(valid).must_equal false + expect(shirts.errors.messages).must_include :quantity + expect(shirts.errors.messages[:quantity]).must_include "can't be blank", "is not a number" + + # Rearrange + shirts.quantity = 2 + + # Re-Act + valid = shirts.valid? + + # Reassert + expect(valid).must_equal true + end + + it "must have an integer quantity greater than 0" do + # Arrange done with let + + # Act + qt = shirts.quantity + + # Assert + expect(qt).must_be_instance_of Integer + expect(qt).must_be :>, 0 + end + + it "must have an order" do + # Arrange + shirts.order = nil + + # Act + valid = shirts.valid? + + # Assert + expect(valid).must_equal false + expect(shirts.errors.messages).must_include :order + expect(shirts.errors.messages[:order]).must_include "can't be blank", "must exist" + + # Rearrange + shirts.order = orders(:pending_order) + + # Re-Act + valid = shirts.valid? + + # Reassert + expect(valid).must_equal true + end + + it "must have a product" do + # Arrange + shirts.product = nil + + # Act + valid = shirts.valid? + + # Assert + expect(valid).must_equal false + expect(shirts.errors.messages).must_include :product + expect(shirts.errors.messages[:product]).must_include "can't be blank", "must exist" + + # Rearrange + shirts.product = products(:shirt) + + # Re-Act + valid = shirts.valid? + + # Reassert + expect(valid).must_equal true + end + + it "must have a status" do + # Arrange + dresses.status = nil + + # Act + valid = dresses.valid? + + # Assert + expect(valid).must_equal false + expect(dresses.errors.messages).must_include :status + expect(dresses.errors.messages[:status]).must_include "can't be blank", "must exist" + + # Rearrange + dresses.status = "pending" + + # Re-Act + valid = dresses.valid? + + # Reassert + expect(valid).must_equal true + end + + it "must have a status equal to pending, paid, shipped, or cancelled" do + # Arrange + dresses.status = "test" + + # Act + valid = dresses.valid? + + # Assert + expect(valid).must_equal false + expect(dresses.errors.messages).must_include :status + expect(dresses.errors.messages[:status]).must_include "test is not a valid order status" + + # Rearrange + dresses.status = "pending" + + # Re-Act + valid = dresses.valid? + + # Reassert + expect(valid).must_equal true + + # Rearrange + dresses.status = "paid" + + # Re-Act + valid = dresses.valid? + + # Reassert + expect(valid).must_equal true + + # Rearrange + dresses.status = "shipped" + + # Re-Act + valid = dresses.valid? + + # Reassert + expect(valid).must_equal true + + # Rearrange + dresses.status = "cancelled" + + # Re-Act + valid = dresses.valid? + + # Reassert + expect(valid).must_equal true + end + end + + describe "subtotal" do + it "must return a float" do + # Arrange done with let + + # Act + result = dresses.subtotal + + # Assert + expect(result).must_be_instance_of Float + end + + it "must return the cost of the product times its quantity" do + # Arrange done with let + + # Act + result = dresses.subtotal + + # Assert + expect(result).must_equal dresses.quantity * dress.price + end + end + + describe "edit_quantity" do + it "updates the quantity to the designated value" do + # Arrange done with let + + # Act + dresses.edit_quantity(1) + + # Assert + expect(dresses.quantity).must_equal 1 + end + + it "cannot update the quantity to a negative or non-integer value" do + # Arrange done with let + + # Act - Assert + expect{ + dresses.edit_quantity(-1) + }.wont_change 'dresses.quantity' + + expect{ + dresses.edit_quantity(2.5) + }.wont_change 'dresses.quantity' + end + + it "destroys the order product if quantity selected is 0" do + # Arrange + id = dresses.id + + # Act + dresses.edit_quantity(0) + + # Assert + expect(OrderProduct.find_by(id: id)).must_be_nil + end + + it "must return true when successful" do + # Arrange done with let + + # Act - Assert + expect(dresses.edit_quantity(3)).must_equal true + end + + it "must return false when unsuccessful" do + # Arrange done with let + + # Act - Assert + expect(dresses.edit_quantity(-2)).must_equal false + end + + it "cannot increase the quantity beyond the available stock" do + # Arrange done with let + + # Act - Assert + expect{ + dresses.edit_quantity(dress.stock + 1) + }.wont_change 'dresses.quantity' + + expect(dresses.edit_quantity(dress.stock + 1)).must_equal false + end + end + + describe "submit_order" do + it "reduces the stock by the quantity ordered" do + expect{ + dresses.submit_order + }.must_change 'dresses.product.stock', -2 + end + + it "returns true if successful" do + expect(shirts.submit_order).must_equal true + end + + it "returns false if unsuccessful" do + # Arrange + dresses.update(quantity: dresses.product.stock + 1) + op = OrderProduct.find_by(id: dresses.id) + + # Act - Assert + expect(op.submit_order).must_equal false + end + + it "cannot reduce the stock below 0 or to a non-integer" do + # Arrange done with let + + # Act - Assert + expect{ + dresses.update(quantity: dresses.product.stock + 1) + op = OrderProduct.find_by(id: dresses.id) + op.submit_order + }.wont_change 'dress.stock' + + expect{ + dresses.update(quantity: 1.5) + op = OrderProduct.find_by(id: dresses.id) + op.submit_order + }.wont_change 'dress.stock' + end + + it "updates the order product status from pending to paid" do + # Arrange done with let + + # Act - Assert + expect(dresses.status).must_equal "pending" + + dresses.submit_order + + expect(dresses.status).must_equal "paid" + end + end +end diff --git a/test/models/order_test.rb b/test/models/order_test.rb new file mode 100644 index 0000000000..7f6f76d8e2 --- /dev/null +++ b/test/models/order_test.rb @@ -0,0 +1,371 @@ +require "test_helper" + +describe Order do + let(:pending_order) { orders(:pending_order) } + + it "must be valid" do + value(pending_order).must_be :valid? + end + + it 'has required fields' do + fields = [:status, :user_id, :order_products, :products] + + fields.each do |field| + expect(pending_order).must_respond_to field + end + end + + describe "relationships" do + it "belongs to a user" do + # Arrange is done with let + + # Act + user = pending_order.user + + # Assert + expect(pending_order).must_be_instance_of Order + expect(user).must_be_instance_of User + end + + it "can have many order products" do + # Arrange is done with let + + # Act + ops = pending_order.order_products + + # Assert + expect(pending_order).must_be_instance_of Order + + expect(ops.length).must_be :>=, 1 + ops.each do |op| + expect(op).must_be_instance_of OrderProduct + end + end + + it "can have 0 order products when status is pending" do + # Arrange + pending_order.order_products.each do |op| + op.destroy + end + + # Act + order = Order.find_by(id: pending_order.id) + ops = order.order_products + + # Assert + expect(order.status).must_equal "pending" + expect(ops.length).must_equal 0 + end + + it "can have many products through orderproducts" do + # Arrange is done with let + + # Act + products_in_order = pending_order.products + + # Assert + expect(products_in_order.length).must_be :>=, 1 + products_in_order.each do |product| + expect(product).must_be_instance_of Product + end + end + + it "can have 0 products through orderproducts when status is pending" do + # Arrange + pending_order.order_products.each do |op| + op.destroy + end + + # Act + products_in_order = pending_order.products + + # Assert + expect(pending_order.status).must_equal "pending" + expect(products_in_order.length).must_equal 0 + end + end + + describe "validations" do + it "must have a user" do + # Arrange + pending_order.user = nil + + # Act + valid = pending_order.valid? + + # Assert + expect(valid).must_equal false + expect(pending_order.errors.messages).must_include :user + expect(pending_order.errors.messages[:user]).must_include "can't be blank", "must exist" + + # Rearrange + pending_order.user = users(:user1) + + # Re-Act + valid = pending_order.valid? + + # Reassert + expect(valid).must_equal true + end + + it "must have a status" do + # Arrange + pending_order.status = nil + + # Act + valid = pending_order.valid? + + # Assert + expect(valid).must_equal false + expect(pending_order.errors.messages).must_include :status + expect(pending_order.errors.messages[:status]).must_include "can't be blank", "must exist" + + # Rearrange + pending_order.status = "pending" + + # Re-Act + valid = pending_order.valid? + + # Reassert + expect(valid).must_equal true + end + + it "must have a status equal to pending, paid, or shipped" do + # Arrange + pending_order.status = "test" + + # Act + valid = pending_order.valid? + + # Assert + expect(valid).must_equal false + expect(pending_order.errors.messages).must_include :status + expect(pending_order.errors.messages[:status]).must_include "test is not a valid order status" + + # Rearrange + pending_order.status = "pending" + + # Re-Act + valid = pending_order.valid? + + # Reassert + expect(valid).must_equal true + + # Rearrange + pending_order.status = "paid" + + # Re-Act + valid = pending_order.valid? + + # Reassert + expect(valid).must_equal true + + # Rearrange + pending_order.status = "shipped" + + # Re-Act + valid = pending_order.valid? + + # Reassert + expect(valid).must_equal true + end + end + + describe "total" do + it "returns the sum of all of the order's order product subtotals" do + # Arrange done with let + + # Act + result = pending_order.total + subtotals = pending_order.order_products.map { |op| op.subtotal } + + # Assert + expect(result).must_equal subtotals.sum + end + + it "returns a float" do + # Arrange done with let + + # Act + result = pending_order.total + + # Assert + expect(result).must_be_instance_of Float + end + end + + describe "add_product" do + let (:new_product) { + Product.new( + user: merchants(:merchant), + name: "pants", + price: 3, + description: "a nice pair of pants", + stock: 10, + photo_url: "photo" + ) + } + + it "adds a new order product with the designated quantity and pending status to the order if product not in cart" do + # Arrange done with let + + # Act - Assert + expect { + pending_order.add_product(new_product, 2) + }.must_change 'pending_order.order_products.length', 1 + + expect(pending_order.order_products.last).must_be_instance_of OrderProduct + expect(pending_order.order_products.last.quantity).must_equal 2 + expect(pending_order.order_products.last.status).must_equal "pending" + end + + it "updates the existing order product quantity if the product is already in the cart" do + # Arrange done with let and fixtures + + # Before addition + expect(order_products(:dresses).quantity).must_equal 2 + + expect { + pending_order.add_product(products(:dress), 3) + }.wont_change 'pending_order.order_products.length' + + # After addition + op = OrderProduct.find_by(id: order_products(:dresses).id) + expect(op.quantity).must_equal 3 + end + + it "will return true if successful" do + # Arrange + new_product.save + + # Act - Assert + expect(pending_order.add_product(products(:dress), 2)).must_equal true + expect(pending_order.add_product(new_product, 2)).must_equal true + end + + it "will return false if requested quantity exceeds stock" do + # Arrange done with let and before + + # Act - Assert + expect(pending_order.add_product(products(:dress), 20)).must_equal false + expect(pending_order.add_product(new_product, 20)).must_equal false + end + + it "will return false if requested quantity is less than 1 or a non-integer" do + # Arrange done with let and before + + # Act - Assert + expect(pending_order.add_product(products(:dress), 0)).must_equal false + expect(pending_order.add_product(new_product, -2)).must_equal false + expect(pending_order.add_product(new_product, 1.5)).must_equal false + end + end + + describe "edit_quantity" do + let (:dresses) { order_products(:dresses) } + + it "updates the quantity to the designated value" do + # Arrange done with let + + # Act + pending_order.edit_quantity(dresses, 3) + + # Assert + expect(dresses.quantity).must_equal 3 + end + + it "cannot update the quantity to a value less than 1 or a non-integer" do + # Arrange done with let + + # Act - Assert + expect{ + pending_order.edit_quantity(dresses, 0) + }.wont_change 'dresses.quantity' + + expect{ + pending_order.edit_quantity(dresses, -1) + }.wont_change 'dresses.quantity' + + expect{ + pending_order.edit_quantity(dresses, 2.5) + }.wont_change 'dresses.quantity' + end + + it "must return true when successful" do + # Arrange done with let + + # Act - Assert + expect(pending_order.edit_quantity(dresses, 3)).must_equal true + end + + it "must return false when unsuccessful" do + # Arrange done with let + + # Act - Assert + expect(pending_order.edit_quantity(dresses, -2)).must_equal false + end + + it "cannot increase the quantity beyond the available stock" do + # Arrange done with let + + # Act - Assert + expect{ + pending_order.edit_quantity(dresses, products(:dress).stock + 1) + }.wont_change 'dresses.quantity' + + expect(pending_order.edit_quantity(dresses, products(:dress).stock + 1)).must_equal false + end + end + + describe "submit_order" do + it "updates the order status from pending to paid" do + # Arrange done with let + + # Act - Assert + expect(pending_order.status).must_equal "pending" + pending_order.submit_order + + expect(pending_order.status).must_equal "paid" + end + + it "updates the order's order products' statuses from pending to paid" do + # Arrange done with let + + # Act - Assert + pending_order.order_products.each do |op| + expect(op.status).must_equal "pending" + end + + pending_order.submit_order + + pending_order.order_products.each do |op| + expect(op.status).must_equal "paid" + end + end + + it "updates the stock of the product on order" do + # Arrange + change = -(order_products(:dresses).quantity) + + # Act - Assert + expect{ + pending_order.submit_order + }.must_change 'Product.find_by(id: order_products(:dresses).product.id).stock', change + end + + it "returns false if order submission fails" do + # Arrange + pending_order.user = nil + + # Act - Assert + expect(pending_order.submit_order).must_equal false + end + + it "returns true if order submission succeeds" do + # Arrange done with let + + # Act - Assert + expect(pending_order.submit_order).must_equal true + end + end +end diff --git a/test/models/product_test.rb b/test/models/product_test.rb new file mode 100644 index 0000000000..3acf891fbb --- /dev/null +++ b/test/models/product_test.rb @@ -0,0 +1,198 @@ +require "test_helper" + +describe Product do + let(:product) { products(:shirt) } + let(:product2) {products(:dress)} + let(:product3) {products(:mumu)} + let(:user) { users(:user1) } + let(:category1) {categories(:category1)} + let(:category2) {categories(:category2)} + before do + product.categories << category1 + product.categories << category2 + end + + it "must be valid" do + expect(product).must_be :valid? + end + + it 'has required fields' do + fields = [:name, :user_id, :stock, :price, :status] + + fields.each do |field| + expect(product).must_respond_to field + end + end + + describe 'Relationships' do + it 'belongs to an user' do + + user = product.user + + expect(user).must_be_instance_of Merchant + expect(user.id).must_equal product.user_id + end + +end + + describe "validations" do + it "requires a name" do + product.name = nil + product.valid?.must_equal false + product.errors.messages.must_include :name + end + + + + it "requires a user_id" do + product.user_id = nil + product.valid?.must_equal false + product.errors.messages.must_include :user_id + end + + + + it "reject a invalid stock value" do + product.stock = nil + product.valid?.must_equal false + product.errors.messages.must_include :stock + end + + + it " stock value cannot be negative" do + product.stock = -1 + product.valid?.must_equal false + + end + + it " stock value can be 0" do + last = Product.all.count + + prod2 = Product.new(name: "Polo shirt") + prod2.user = user + prod2.stock = 0 + prod2.price = 5 + prod2.categories << category2 + + prod2.save! + expect(Product.all.count).must_equal last+1 + end + + it "it only accept integers as stock quantity" do + product.stock = 2.1 + + product.valid?.must_equal false + + end + + it "reject invalid price" do + product.price = nil + product.valid?.must_equal false + product.errors.messages.must_include :price + end + + it "accept 0 price" do + last = Product.all.count + + prod2 = Product.new(name: "Polo shirt") + prod2.user = user + prod2.stock = 0 + prod2.price = 0 + prod2.categories << category2 + + prod2.save! + expect(Product.all.count).must_equal last+1 + end + end + + + describe "active_products" do + it "returns an array" do + products = Product.active_products + expect(products).must_be_instance_of Array + end + + it "returns an empty array if no active products" do + Product.all.each do |product| + product.status = false + product.save + end + + expect(Product.active_products.empty?).must_equal true + end + + it "returns an array of product" do + expect(Product.active_products.first).must_be_kind_of Product + end + + it "The array length will be added by 1 for a newly created product" do + prod2 = Product.new(name: "Polo shirt") + prod2.user = user + prod2.stock = 2 + prod2.price = 1 + prod2.categories << category2 + count = Product.active_products.length + prod2.save! + + expect(Product.active_products.length).must_equal count+1 + + end + + it "The array will include all the valid product" do + expect(Product.active_products.first).must_equal product + expect(Product.active_products[1]).must_equal product2 + + end + end + + + describe "self.category_list" do + + it "returns an array of correct product " do + list1 = Product.category_list(category1.id) + + expect(list1.count).must_equal 1 + + list1.each do |prod| + prod.must_be_kind_of Product + prod.categories.must_include category1 + end + end + + it "returns an empty array if no product in that category" do + category3 = Category.new(name:"outdoor") + list2 = Product.category_list(category3.id) + + expect(list2.empty?).must_equal true + end + end + + describe "self.by_merchant" do + before do + @user2 = User.create( + name: "jas", + uid: 89076544, + provider: "github" + ) + @user2.type = "Merchant" + @user2.save + + @id = product.user_id + + end + + it "returns an array of correct product " do + list1 = Product.merchant_list(@id) + expect(list1.count).must_equal 3 + + expect(list1.first).must_be_kind_of Product + expect(list1.first.user_id).must_equal @id + + end + + it "returns an empty array if no product in that merchant" do + list2 = Product.merchant_list(@user2.id) + expect(list2.empty?).must_equal true + end + end +end diff --git a/test/models/review_test.rb b/test/models/review_test.rb new file mode 100644 index 0000000000..9ebb785ef3 --- /dev/null +++ b/test/models/review_test.rb @@ -0,0 +1,5 @@ +require "test_helper" + +describe Review do + +end diff --git a/test/models/user_test.rb b/test/models/user_test.rb new file mode 100644 index 0000000000..2bea6c1052 --- /dev/null +++ b/test/models/user_test.rb @@ -0,0 +1,71 @@ +require "test_helper" + +describe User do + + let(:user) { users(:user1) } + + it "must be valid" do + value(user).must_be :valid? + end + + describe "custom model method: is_a_merchant?" do #this method is imparted to Merchant model + let (:merchant) {merchants(:merchant)} + + it "returns true if model is merchant" do + #Act/Assert + expect(merchant).must_be_instance_of Merchant + expect(merchant.is_a_merchant?).must_equal true + end + + it "returns false if model is not a user" do + #Arrange + user = users(:cc_user) + #Act/Assert + expect(user).wont_be_instance_of Merchant + expect(user.is_a_merchant?).must_equal false + end + + it "flips from false to true if user becomes merchant" do + user = users(:user1) + + expect(user.is_a_merchant?).must_equal false #testing turthiness of before value + + user.type = "Merchant" + + expect(user.is_a_merchant?).must_equal true #testing truthiness after change made + end + + it "flops from true to false if a merchant becomes a user" do + expect(merchant.is_a_merchant?).must_equal true #before + + #Assert + merchant.type = nil + + assert_nil(merchant.type) #to be certain change in type made + expect(merchant.is_a_merchant?).must_equal false #after + + end + end + + describe "custom model method: become Merchant" do + let(:user) { users(:cc_user) } + + it "changes a user instance into a merchant instance if type is set to Merchant" do + #before! + assert_nil(user.type) #making sure type is nil + expect(user).must_be_instance_of User #user is a User + + #Arrange + user.type = "Merchant" + user.become_merchant #the method to switch the STI class of instance + + #after! + expect(user.type).must_equal "Merchant" #type has changed from nil + expect(user).wont_be_instance_of User #user is no longer a User instance + expect(user).must_be_instance_of Merchant #user has been changed into an instance of Merchant + + 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..e9a59b7408 --- /dev/null +++ b/test/test_helper.rb @@ -0,0 +1,50 @@ +ENV["RAILS_ENV"] = "test" +require File.expand_path("../../config/environment", __FILE__) +require "rails/test_help" +require "minitest/rails" +require "minitest/reporters" # for Colorized output +require 'simplecov' +SimpleCov.start + +Minitest::Reporters.use!( + Minitest::Reporters::SpecReporter.new, + ENV, + Minitest.backtrace_filter +) + + +# To add Capybara feature tests add `gem "minitest-rails-capybara"` +# to the test group in the Gemfile and uncomment the following: +# require "minitest/rails/capybara" + +# Uncomment for awesome colorful output +# require "minitest/pride" + +class ActiveSupport::TestCase + # Setup all fixtures in test/fixtures/*.yml for all tests in alphabetical order. + fixtures :all + # Add more helper methods to be used by all tests here... + def setup + # !!!! Once you have enabled test mode, all requests to OmniAuth will be short circuited to use the mock authentication hash. + # A request to /auth/provider will redirect immediately to /auth/provider/callback !!!! + OmniAuth.config.test_mode = true + end + + # Test helper method to generate a mock auth hash for fixture data + def mock_auth_hash(user) + return { + provider: user.provider, + uid: user.uid, + info: { + email: user.email, + name: user.name + } + } + end + + #used to dry up code in our tests, since logins will be performed often during testing + def perform_login(user) + OmniAuth.config.mock_auth[:github] = OmniAuth::AuthHash.new(mock_auth_hash(user)) + get auth_callback_path(:github) + 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