From 8e2cf4ecc0e2b5bf67771850372f2eb8d0bf08d2 Mon Sep 17 00:00:00 2001 From: wyx Date: Fri, 24 Jul 2020 16:58:25 +0800 Subject: [PATCH 01/16] add column to users --- app/controllers/application_controller.rb | 1358 ++++++++--------- ...0200724085032_add_column_to_table_users.rb | 8 + db/structure.sql | 2 +- 3 files changed, 688 insertions(+), 680 deletions(-) create mode 100644 db/migrate/20200724085032_add_column_to_table_users.rb diff --git a/app/controllers/application_controller.rb b/app/controllers/application_controller.rb index baece64c..3f09c77f 100644 --- a/app/controllers/application_controller.rb +++ b/app/controllers/application_controller.rb @@ -1,798 +1,798 @@ require 'oauth2' class ApplicationController < ActionController::Base - include CodeExample - include RenderExpand - include RenderHelper - include ControllerRescueHandler - include LaboratoryHelper - include GitHelper - include LoggerHelper - include LoginHelper + include CodeExample + include RenderExpand + include RenderHelper + include ControllerRescueHandler + include LaboratoryHelper + include GitHelper + include LoggerHelper + include LoginHelper - protect_from_forgery prepend: true, unless: -> { request.format.json? } + protect_from_forgery prepend: true, unless: -> { request.format.json? } - before_action :check_sign - before_action :user_setup - #before_action :check_account + before_action :check_sign + before_action :user_setup + #before_action :check_account - # TODO - # check sql query time - before_action do + # TODO + # check sql query time + before_action do if request.subdomain === 'testforgeplus' || request.subdomain === "profiler" Rack::MiniProfiler.authorize_request end end - DCODES = %W(2 3 4 5 6 7 8 9 a b c f e f g h i j k l m n o p q r s t u v w x y z) - OPENKEY = "79e33abd4b6588941ab7622aed1e67e8" + DCODES = %W(2 3 4 5 6 7 8 9 a b c f e f g h i j k l m n o p q r s t u v w x y z) + OPENKEY = "79e33abd4b6588941ab7622aed1e67e8" - helper_method :current_user + helper_method :current_user - # 所有请求必须合法签名 - def check_sign - # if !Rails.env.development? - # Rails.logger.info("66666 #{params}") - # # suffix = request.url.split(".").last.split("?").first - # # suffix_arr = ["xls", "xlsx", "pdf", "zip"] # excel文件先注释 - # # unless suffix_arr.include?(suffix) - # if params[:client_key].present? - # randomcode = params[:randomcode] - # # tip_exception(501, "请求不合理") unless (Time.now.to_i - randomcode.to_i).between?(0,5) - # - # sign = Digest::MD5.hexdigest("#{OPENKEY}#{randomcode}") - # Rails.logger.info("2222 #{sign}") - # tip_exception(501, "请求不合理") if sign != params[:client_key] - # else - # tip_exception(501, "请求不合理") - # end - # # end - # end - end + # 所有请求必须合法签名 + def check_sign + # if !Rails.env.development? + # Rails.logger.info("66666 #{params}") + # # suffix = request.url.split(".").last.split("?").first + # # suffix_arr = ["xls", "xlsx", "pdf", "zip"] # excel文件先注释 + # # unless suffix_arr.include?(suffix) + # if params[:client_key].present? + # randomcode = params[:randomcode] + # # tip_exception(501, "请求不合理") unless (Time.now.to_i - randomcode.to_i).between?(0,5) + # + # sign = Digest::MD5.hexdigest("#{OPENKEY}#{randomcode}") + # Rails.logger.info("2222 #{sign}") + # tip_exception(501, "请求不合理") if sign != params[:client_key] + # else + # tip_exception(501, "请求不合理") + # end + # # end + # end + end - # 全局配置参数 - # 返回name对应的value - def edu_setting(name) - EduSetting.get(name) - end + # 全局配置参数 + # 返回name对应的value + def edu_setting(name) + EduSetting.get(name) + end - # 平台身份权限判断(学生用户无权限) - def identity_auth - ue = current_user.user_extension - tip_exception(403, "..") unless current_user.admin_or_business? || ue.teacher? || ue.professional? - end + # 平台身份权限判断(学生用户无权限) + def identity_auth + ue = current_user.user_extension + tip_exception(403, "..") unless current_user.admin_or_business? || ue.teacher? || ue.professional? + end - # 平台已认证身份判断(已认证的老师和专业人士) - def certi_identity_auth - ue = current_user.user_extension - tip_exception(403, "..") unless current_user.admin_or_business? || - (current_user.professional_certification && (ue.teacher? || ue.professional?)) - end + # 平台已认证身份判断(已认证的老师和专业人士) + def certi_identity_auth + ue = current_user.user_extension + tip_exception(403, "..") unless current_user.admin_or_business? || + (current_user.professional_certification && (ue.teacher? || ue.professional?)) + end - def shixun_marker - unless current_user.is_shixun_marker? || current_user.admin_or_business? - tip_exception(403, "..") - end - end + def shixun_marker + unless current_user.is_shixun_marker? || current_user.admin_or_business? + tip_exception(403, "..") + end + end - # 实训的访问权限 - def shixun_access_allowed - if !current_user.shixun_permission(@shixun) - tip_exception(403, "..") - end - end + # 实训的访问权限 + def shixun_access_allowed + if !current_user.shixun_permission(@shixun) + tip_exception(403, "..") + end + end - def admin_or_business? - User.current.admin? || User.current.business? - end + def admin_or_business? + User.current.admin? || User.current.business? + end - # 访问课堂时没权限直接弹加入课堂的弹框 :409 - def user_course_identity - @user_course_identity = current_user.course_identity(@course) - if @user_course_identity > Course::STUDENT && @course.is_public == 0 - tip_exception(401, "..") unless User.current.logged? - check_account - tip_exception(@course.excellent ? 410 : 409, "您没有权限进入") - end - if @user_course_identity > Course::CREATOR && @user_course_identity <= Course::STUDENT && @course.tea_id != current_user.id - # 实名认证和职业认证的身份判断 - tip_exception(411, "你的实名认证和职业认证审核未通过") if @course.authentication && - @course.professional_certification && (!current_user.authentication && !current_user.professional_certification) - tip_exception(411, "你的实名认证审核未通过") if @course.authentication && !current_user.authentication - tip_exception(411, "你的职业认证审核未通过") if @course.professional_certification && !current_user.professional_certification - end - uid_logger("###############user_course_identity:#{@user_course_identity}") - end + # 访问课堂时没权限直接弹加入课堂的弹框 :409 + def user_course_identity + @user_course_identity = current_user.course_identity(@course) + if @user_course_identity > Course::STUDENT && @course.is_public == 0 + tip_exception(401, "..") unless User.current.logged? + check_account + tip_exception(@course.excellent ? 410 : 409, "您没有权限进入") + end + if @user_course_identity > Course::CREATOR && @user_course_identity <= Course::STUDENT && @course.tea_id != current_user.id + # 实名认证和职业认证的身份判断 + tip_exception(411, "你的实名认证和职业认证审核未通过") if @course.authentication && + @course.professional_certification && (!current_user.authentication && !current_user.professional_certification) + tip_exception(411, "你的实名认证审核未通过") if @course.authentication && !current_user.authentication + tip_exception(411, "你的职业认证审核未通过") if @course.professional_certification && !current_user.professional_certification + end + uid_logger("###############user_course_identity:#{@user_course_identity}") + end - # 题库的访问权限 - def bank_visit_auth - tip_exception(-2,"未通过职业认证") if current_user.is_teacher? && !current_user.certification_teacher? && !current_user.admin_or_business? && @bank.user_id != current_user.id && @bank.is_public - tip_exception(403, "无权限") unless @bank.user_id == current_user.id || current_user.admin_or_business? || - (current_user.certification_teacher? && @bank.is_public) - end + # 题库的访问权限 + def bank_visit_auth + tip_exception(-2,"未通过职业认证") if current_user.is_teacher? && !current_user.certification_teacher? && !current_user.admin_or_business? && @bank.user_id != current_user.id && @bank.is_public + tip_exception(403, "无权限") unless @bank.user_id == current_user.id || current_user.admin_or_business? || + (current_user.certification_teacher? && @bank.is_public) + end - # 判断用户的邮箱或者手机是否可用 - # params[:type] 1: 注册;2:忘记密码;3:绑定 - def check_mail_and_phone_valid login, type - unless login =~ /^[a-zA-Z0-9]+([._\\]*[a-zA-Z0-9])*@([a-z0-9]+[-a-z0-9]*[a-z0-9]+.){1,63}[a-z0-9]+$/ || login =~ /^1\d{10}$/ || - login =~ /^[a-zA-Z0-9]+([._\\]*[a-zA-Z0-9])$/ - tip_exception(-2, "请输入正确的手机号或邮箱") - end - # 考虑到安全参数问题,多一次查询,去掉Union - user = User.where(phone: login).first || User.where(mail: login).first - if type.to_i == 1 && !user.nil? - tip_exception(-2, "该手机号码或邮箱已被注册") - elsif type.to_i == 2 && user.nil? - tip_exception(-2, "该手机号码或邮箱未注册") - elsif type.to_i == 3 && user.present? - tip_exception(-2, "该手机号码或邮箱已绑定") - end - sucess_status - end + # 判断用户的邮箱或者手机是否可用 + # params[:type] 1: 注册;2:忘记密码;3:绑定 + def check_mail_and_phone_valid login, type + unless login =~ /^[a-zA-Z0-9]+([._\\]*[a-zA-Z0-9])*@([a-z0-9]+[-a-z0-9]*[a-z0-9]+.){1,63}[a-z0-9]+$/ || login =~ /^1\d{10}$/ || + login =~ /^[a-zA-Z0-9]+([._\\]*[a-zA-Z0-9])$/ + tip_exception(-2, "请输入正确的手机号或邮箱") + end + # 考虑到安全参数问题,多一次查询,去掉Union + user = User.where(phone: login).first || User.where(mail: login).first + if type.to_i == 1 && !user.nil? + tip_exception(-2, "该手机号码或邮箱已被注册") + elsif type.to_i == 2 && user.nil? + tip_exception(-2, "该手机号码或邮箱未注册") + elsif type.to_i == 3 && user.present? + tip_exception(-2, "该手机号码或邮箱已绑定") + end + sucess_status + end - # 发送及记录激活码 - # 发送验证码:type 1:注册手机验证码 2:找回密码手机验证码 3:找回密码邮箱验证码 4:绑定手机 5:绑定邮箱 - # 6:手机验证码登录 7:邮箱验证码登录 8:邮箱注册验证码 9:验证手机号有效 - def check_verification_code(code, send_type, value) - case send_type - when 1, 2, 4, 9 - # 手机类型的发送 - sigle_para = {phone: value} - status = Educoder::Sms.send(mobile: value, code: code) - tip_exception(-2, code_msg(status)) if status != 0 - when 8, 3, 5 - # 邮箱类型的发送 - sigle_para = {email: value} - # 60s内不能重复发送 - send_email_limit_cache_key = "send_email_60_second_limit:#{value}" - tip_exception(-1, '请勿频繁操作') if Rails.cache.exist?(send_email_limit_cache_key) + # 发送及记录激活码 + # 发送验证码:type 1:注册手机验证码 2:找回密码手机验证码 3:找回密码邮箱验证码 4:绑定手机 5:绑定邮箱 + # 6:手机验证码登录 7:邮箱验证码登录 8:邮箱注册验证码 9:验证手机号有效 + def check_verification_code(code, send_type, value) + case send_type + when 1, 2, 4, 9 + # 手机类型的发送 + sigle_para = {phone: value} + status = Educoder::Sms.send(mobile: value, code: code) + tip_exception(-2, code_msg(status)) if status != 0 + when 8, 3, 5 + # 邮箱类型的发送 + sigle_para = {email: value} + # 60s内不能重复发送 + send_email_limit_cache_key = "send_email_60_second_limit:#{value}" + tip_exception(-1, '请勿频繁操作') if Rails.cache.exist?(send_email_limit_cache_key) - # 短时间内不能大量发送 - send_email_control = LimitForbidControl::SendEmailCode.new(value) - tip_exception(-1, '邮件发送太频繁,请稍后再试') if send_email_control.forbid? - begin - UserMailer.register_email(value, code).deliver_now + # 短时间内不能大量发送 + send_email_control = LimitForbidControl::SendEmailCode.new(value) + tip_exception(-1, '邮件发送太频繁,请稍后再试') if send_email_control.forbid? + begin + UserMailer.register_email(value, code).deliver_now - Rails.cache.write(send_email_limit_cache_key, 1, expires_in: 1.minute) - send_email_control.increment! - # Mailer.run.email_register(code, value) - rescue Exception => e - logger_error(e) - tip_exception(-2,"邮件发送失败,请稍后重试") - end - end - ver_params = {code_type: send_type, code: code}.merge(sigle_para) - VerificationCode.create!(ver_params) - end + Rails.cache.write(send_email_limit_cache_key, 1, expires_in: 1.minute) + send_email_control.increment! + # Mailer.run.email_register(code, value) + rescue Exception => e + logger_error(e) + tip_exception(-2,"邮件发送失败,请稍后重试") + end + end + ver_params = {code_type: send_type, code: code}.merge(sigle_para) + VerificationCode.create!(ver_params) + end - def code_msg status - case status - when 0 - "验证码已经发送到您的手机,请注意查收" - when 8 - "同一手机号30秒内重复提交相同的内容" - when 9 - "同一手机号5分钟内重复提交相同的内容超过3次" - when 22 - "1小时内同一手机号发送次数超过限制" - when 33 - "验证码发送次数超过频率" - when 43 - "一天内同一手机号发送次数超过限制" - when 53 - "手机号接收超过频率限制" - end - end + def code_msg status + case status + when 0 + "验证码已经发送到您的手机,请注意查收" + when 8 + "同一手机号30秒内重复提交相同的内容" + when 9 + "同一手机号5分钟内重复提交相同的内容超过3次" + when 22 + "1小时内同一手机号发送次数超过限制" + when 33 + "验证码发送次数超过频率" + when 43 + "一天内同一手机号发送次数超过限制" + when 53 + "手机号接收超过频率限制" + end + end - def find_course - return normal_status(2, '缺少course_id参数!') if params[:course_id].blank? - @course = Course.find(params[:course_id]) - tip_exception(404, "") if @course.is_delete == 1 && !current_user.admin_or_business? - rescue Exception => e - tip_exception(e.message) - end + def find_course + return normal_status(2, '缺少course_id参数!') if params[:course_id].blank? + @course = Course.find(params[:course_id]) + tip_exception(404, "") if @course.is_delete == 1 && !current_user.admin_or_business? + rescue Exception => e + tip_exception(e.message) + end - def course_manager - return normal_status(403, '只有课堂管理员才有权限') if @user_course_identity > Course::CREATOR - end + def course_manager + return normal_status(403, '只有课堂管理员才有权限') if @user_course_identity > Course::CREATOR + end - def find_board - return normal_status(2, "缺少board_id参数") if params[:board_id].blank? - @board = Board.find(params[:board_id]) - rescue Exception => e - uid_logger_error(e.message) - tip_exception(e.message) - end + def find_board + return normal_status(2, "缺少board_id参数") if params[:board_id].blank? + @board = Board.find(params[:board_id]) + rescue Exception => e + uid_logger_error(e.message) + tip_exception(e.message) + end - def validate_type(object_type) - normal_status(2, "参数") if params.has_key?(:sort_type) && !SORT_TYPE.include?(params[:sort_type].strip) - end + def validate_type(object_type) + normal_status(2, "参数") if params.has_key?(:sort_type) && !SORT_TYPE.include?(params[:sort_type].strip) + end - def set_pagination - @page = params[:page] || 1 - @page_size = params[:page_size] || 15 - end + def set_pagination + @page = params[:page] || 1 + @page_size = params[:page_size] || 15 + end - # 课堂教师权限 - def teacher_allowed - logger.info("#####identity: #{current_user.course_identity(@course)}") - unless current_user.course_identity(@course) < Course::STUDENT - normal_status(403, "") - end - end + # 课堂教师权限 + def teacher_allowed + logger.info("#####identity: #{current_user.course_identity(@course)}") + unless current_user.course_identity(@course) < Course::STUDENT + normal_status(403, "") + end + end - # 课堂教师、课堂管理员、超级管理员的权限(不包含助教) - def teacher_or_admin_allowed - unless current_user.course_identity(@course) < Course::ASSISTANT_PROFESSOR - normal_status(403, "") - end - end + # 课堂教师、课堂管理员、超级管理员的权限(不包含助教) + def teacher_or_admin_allowed + unless current_user.course_identity(@course) < Course::ASSISTANT_PROFESSOR + normal_status(403, "") + end + end - def require_admin - normal_status(403, "") unless User.current.admin? - end + def require_admin + normal_status(403, "") unless User.current.admin? + end - def require_business - normal_status(403, "") unless admin_or_business? - end + def require_business + normal_status(403, "") unless admin_or_business? + end - # 前端会捕捉401,弹登录弹框 - # 未授权的捕捉407,弹试用申请弹框 - def require_login - #6.13 -hs + # 前端会捕捉401,弹登录弹框 + # 未授权的捕捉407,弹试用申请弹框 + def require_login + #6.13 -hs - tip_exception(401, "请登录后再操作") unless User.current.logged? - end + tip_exception(401, "请登录后再操作") unless User.current.logged? + end - # 异常提醒 - def tip_exception(status = -1, message) - raise Educoder::TipException.new(status, message) - end + # 异常提醒 + def tip_exception(status = -1, message) + raise Educoder::TipException.new(status, message) + end - def missing_template - tip_exception(404, "...") - end + def missing_template + tip_exception(404, "...") + end - # 弹框提醒 - def tip_show_exception(status = -2, message) - raise Educoder::TipException.new(status, message) - end + # 弹框提醒 + def tip_show_exception(status = -2, message) + raise Educoder::TipException.new(status, message) + end - def normal_status(status = 0, message) - case status - when 403 - message = "您没有权限进行该操作" - when 404 - message = "您访问的页面不存在或已被删除" - end - render :json => { status: status, message: message } - end + def normal_status(status = 0, message) + case status + when 403 + message = "您没有权限进行该操作" + when 404 + message = "您访问的页面不存在或已被删除" + end + render :json => { status: status, message: message } + end - # 资料是否完善 - def check_account - if !current_user.profile_completed? - #info_url = '/account/profile' - tip_exception(402, nil) - end - end + # 资料是否完善 + def check_account + if !current_user.profile_completed? + #info_url = '/account/profile' + tip_exception(402, nil) + end + end - # 系统全局认证(暂时隐藏试用申请的判断) - def check_auth - # day_cer = UserDayCertification.find_by(user_id: current_user.id) - # # 如果注册超过24小时则需要完善资料及授权 - # if (Time.now.to_i - day_cer.try(:created_at).to_i) > 86400 - # if !current_user.profile_completed? - # info_url = '/account/profile' - # tip_exception(402, info_url) - # elsif current_user.certification != 1 - # if current_user.apply_actions.exists?(container_type: 'TrialAuthorization', status: 0) - # tip_exception(408, "您的试用申请正在审核中,请耐心等待") - # end - # tip_exception(407, "系统未授权") - # end - # end + # 系统全局认证(暂时隐藏试用申请的判断) + def check_auth + # day_cer = UserDayCertification.find_by(user_id: current_user.id) + # # 如果注册超过24小时则需要完善资料及授权 + # if (Time.now.to_i - day_cer.try(:created_at).to_i) > 86400 + # if !current_user.profile_completed? + # info_url = '/account/profile' + # tip_exception(402, info_url) + # elsif current_user.certification != 1 + # if current_user.apply_actions.exists?(container_type: 'TrialAuthorization', status: 0) + # tip_exception(408, "您的试用申请正在审核中,请耐心等待") + # end + # tip_exception(407, "系统未授权") + # end + # end - # if current_user.certification != 1 && current_user.apply_actions.exists?(container_type: 'TrialAuthorization', status: 0) - # tip_exception(408, "您的试用申请正在审核中,请耐心等待") - # elsif (Time.now.to_i - day_cer.try(:created_at).to_i) < 86400 - # if !current_user.profile_completed? - # info_url = '/account/profile' - # tip_exception(402, info_url) - # elsif current_user.certification != 1 - # day_cer = UserDayCertification.find_by(user_id: current_user.id) - # tip_exception(407, "系统未授权") unless (Time.now.to_i - day_cer.try(:created_at).to_i) < 86400 - # end - # end - end + # if current_user.certification != 1 && current_user.apply_actions.exists?(container_type: 'TrialAuthorization', status: 0) + # tip_exception(408, "您的试用申请正在审核中,请耐心等待") + # elsif (Time.now.to_i - day_cer.try(:created_at).to_i) < 86400 + # if !current_user.profile_completed? + # info_url = '/account/profile' + # tip_exception(402, info_url) + # elsif current_user.certification != 1 + # day_cer = UserDayCertification.find_by(user_id: current_user.id) + # tip_exception(407, "系统未授权") unless (Time.now.to_i - day_cer.try(:created_at).to_i) < 86400 + # end + # end + end - def user_setup - # # reacct静态资源加载不需要走这一步 - #return if params[:controller] == "main" - # Find the current user - #Rails.logger.info("current_laboratory is #{current_laboratory} domain is #{request.subdomain}") - User.current = find_current_user - uid_logger("user_setup: " + (User.current.logged? ? "#{User.current.try(:login)} (id=#{User.current.try(:id)})" : "anonymous")) + def user_setup + # # reacct静态资源加载不需要走这一步 + #return if params[:controller] == "main" + # Find the current user + #Rails.logger.info("current_laboratory is #{current_laboratory} domain is #{request.subdomain}") + User.current = find_current_user + uid_logger("user_setup: " + (User.current.logged? ? "#{User.current.try(:login)} (id=#{User.current.try(:id)})" : "anonymous")) - # 开放课程通过链接访问的用户 - if !User.current.logged? && !params[:chinaoocTimestamp].blank? && !params[:websiteName].blank? && !params[:chinaoocKey].blank? - content = "#{OPENKEY}#{params[:websiteName]}#{params[:chinaoocTimestamp]}" + # 开放课程通过链接访问的用户 + if !User.current.logged? && !params[:chinaoocTimestamp].blank? && !params[:websiteName].blank? && !params[:chinaoocKey].blank? + content = "#{OPENKEY}#{params[:websiteName]}#{params[:chinaoocTimestamp]}" - if Digest::MD5.hexdigest(content) == params[:chinaoocKey] - user = open_class_user - if user - start_user_session(user) - set_autologin_cookie(user) - end - User.current = user - end - end + if Digest::MD5.hexdigest(content) == params[:chinaoocKey] + user = open_class_user + if user + start_user_session(user) + set_autologin_cookie(user) + end + User.current = user + end + end - # if !User.current.logged? && Rails.env.development? - # User.current = User.find 1 - # end + # if !User.current.logged? && Rails.env.development? + # User.current = User.find 1 + # end - # 测试版前端需求 - logger.info("subdomain:#{request.subdomain}") - if request.subdomain != "www" - if params[:debug] == 'teacher' #todo 为了测试,记得讲debug删除 - User.current = User.find 81403 - elsif params[:debug] == 'student' - User.current = User.find 8686 - elsif params[:debug] == 'admin' - user = User.find 1 - User.current = user - cookies.signed[:user_id] = user.id - end - end - # User.current = User.find 81403 - end + # 测试版前端需求 + logger.info("subdomain:#{request.subdomain}") + if request.subdomain != "www" + if params[:debug] == 'teacher' #todo 为了测试,记得讲debug删除 + User.current = User.find 81403 + elsif params[:debug] == 'student' + User.current = User.find 8686 + elsif params[:debug] == 'admin' + user = User.find 1 + User.current = user + cookies.signed[:user_id] = user.id + end + end + # User.current = User.find 81403 + end - # Returns the current user or nil if no user is logged in - # and starts a session if needed - def find_current_user - uid_logger("user setup start: session[:user_id] is #{session[:user_id]}") - uid_logger("0000000000000user setup start: default_yun_session is #{default_yun_session}, session[:current_user_id] is #{session[:"#{default_yun_session}"]}") - current_domain_session = session[:"#{default_yun_session}"] - if current_domain_session - # existing session - User.current = (User.active.find(current_domain_session) rescue nil) - elsif autologin_user = try_to_autologin - autologin_user - elsif params[:format] == 'atom' && params[:key] && request.get? && accept_rss_auth? - # RSS key authentication does not start a session - User.find_by_rss_key(params[:key]) - end - end + # Returns the current user or nil if no user is logged in + # and starts a session if needed + def find_current_user + uid_logger("user setup start: session[:user_id] is #{session[:user_id]}") + uid_logger("0000000000000user setup start: default_yun_session is #{default_yun_session}, session[:current_user_id] is #{session[:"#{default_yun_session}"]}") + current_domain_session = session[:"#{default_yun_session}"] + if current_domain_session + # existing session + User.current = (User.active.find(current_domain_session) rescue nil) + elsif autologin_user = try_to_autologin + autologin_user + elsif params[:format] == 'atom' && params[:key] && request.get? && accept_rss_auth? + # RSS key authentication does not start a session + User.find_by_rss_key(params[:key]) + end + end - def try_to_autologin - if cookies[autologin_cookie_name] - # auto-login feature starts a new session - user = nil - Rails.logger.info("111111111111111111#{default_yun_session}, session is #{session[:"#{default_yun_session}"]} ") - user = User.try_to_autologin(cookies[autologin_cookie_name]) - # start_user_session(user) if user # TODO 解决sso退出不同步的问题 - user - end - end + def try_to_autologin + if cookies[autologin_cookie_name] + # auto-login feature starts a new session + user = nil + Rails.logger.info("111111111111111111#{default_yun_session}, session is #{session[:"#{default_yun_session}"]} ") + user = User.try_to_autologin(cookies[autologin_cookie_name]) + # start_user_session(user) if user # TODO 解决sso退出不同步的问题 + user + end + end - def api_request? - %w(xml json).include? params[:format] - end + def api_request? + %w(xml json).include? params[:format] + end - def current_user - if Rails.env.development? - User.current = User.find 1 - else - User.current - end - end + def current_user + if Rails.env.development? + User.current = User.find 1 + else + User.current + end + end - ## 默认输出json - def render_json - respond_to do |format| + ## 默认输出json + def render_json + respond_to do |format| format.json end - end + end - ## 输出错误信息 - def error_status(message = nil) - @status = -1 - @message = message - end + ## 输出错误信息 + def error_status(message = nil) + @status = -1 + @message = message + end - # 实训等对应的仓库地址 - def repo_ip_url(repo_path) - "#{edu_setting('git_address_ip')}/#{repo_path}" - end + # 实训等对应的仓库地址 + def repo_ip_url(repo_path) + "#{edu_setting('git_address_ip')}/#{repo_path}" + end - def repo_url(repo_path) - "#{edu_setting('git_address_domain')}/#{repo_path}" - end + def repo_url(repo_path) + "#{edu_setting('git_address_domain')}/#{repo_path}" + end - # 通关后,把最后一次成功的代码存到数据库 - # type 0 创始内容, 1 最新内容 - # def game_passed_code(path, myshixun, game_id) - # # 如果代码窗口是隐藏的,则不用保存代码 - # return if myshixun.shixun.hide_code || myshixun.shixun.vnc - # file_content = git_fle_content myshixun.repo_path, path - # #unless file_content.present? - # # raise("获取文件代码异常") - # #end - # logger.info("#######game_id:#{game_id}, file_content:#{file_content}") - # game_code = GameCode.where(:game_id => game_id, :path => path).first - # if game_code.nil? - # GameCode.create!(:game_id => game_id, :new_code => file_content, :path => path) - # else - # game_code.update_attributes!(:new_code => file_content) - # end + # 通关后,把最后一次成功的代码存到数据库 + # type 0 创始内容, 1 最新内容 + # def game_passed_code(path, myshixun, game_id) + # # 如果代码窗口是隐藏的,则不用保存代码 + # return if myshixun.shixun.hide_code || myshixun.shixun.vnc + # file_content = git_fle_content myshixun.repo_path, path + # #unless file_content.present? + # # raise("获取文件代码异常") + # #end + # logger.info("#######game_id:#{game_id}, file_content:#{file_content}") + # game_code = GameCode.where(:game_id => game_id, :path => path).first + # if game_code.nil? + # GameCode.create!(:game_id => game_id, :new_code => file_content, :path => path) + # else + # game_code.update_attributes!(:new_code => file_content) + # end # end - # Post请求 - def uri_post(uri, params) - begin - uid_logger_dubug("--uri_exec: params is #{params}, url is #{uri}") - uri = URI.parse(URI.encode(uri.strip)) - res = Net::HTTP.post_form(uri, params).body - uid_logger_dubug("--uri_exec: .....res is #{res}") - JSON.parse(res) - rescue Exception => e - uid_logger_error("--uri_exec: exception #{e.message}") - raise Educoder::TipException.new("实训平台繁忙(繁忙等级:84)") - end - end + # Post请求 + def uri_post(uri, params) + begin + uid_logger_dubug("--uri_exec: params is #{params}, url is #{uri}") + uri = URI.parse(URI.encode(uri.strip)) + res = Net::HTTP.post_form(uri, params).body + uid_logger_dubug("--uri_exec: .....res is #{res}") + JSON.parse(res) + rescue Exception => e + uid_logger_error("--uri_exec: exception #{e.message}") + raise Educoder::TipException.new("实训平台繁忙(繁忙等级:84)") + end + end - # 处理返回非0就报错的请求 - def interface_post(uri, params, status, message) - begin - uid_logger_dubug("--uri_exec: params is #{params}, url is #{uri}") - uri = URI.parse(URI.encode(uri.strip)) - res = Net::HTTP.post_form(uri, params).body - uid_logger_dubug("--uri_exec: .....res is #{res}") - res = JSON.parse(res) - if (res && res['code'] != 0) - tip_exception(status, message) - else - res - end - rescue Exception => e - uid_logger("--uri_exec: exception #{e.message}") - raise Educoder::TipException.new(message) - end - end + # 处理返回非0就报错的请求 + def interface_post(uri, params, status, message) + begin + uid_logger_dubug("--uri_exec: params is #{params}, url is #{uri}") + uri = URI.parse(URI.encode(uri.strip)) + res = Net::HTTP.post_form(uri, params).body + uid_logger_dubug("--uri_exec: .....res is #{res}") + res = JSON.parse(res) + if (res && res['code'] != 0) + tip_exception(status, message) + else + res + end + rescue Exception => e + uid_logger("--uri_exec: exception #{e.message}") + raise Educoder::TipException.new(message) + end + end - # json格式请求 - def interface_json_post(uri, params, status, message) - begin - uid_logger_dubug("--uri_exec: params is #{params}, url is #{uri}") - uri = URI.parse(URI.encode(uri.strip)) - res = Net::HTTP.start(uri.host, uri.port) do |http| - req = Net::HTTP::Post.new(uri) - req['Content-Type'] = 'application/json' - req.body = params.to_json - http.request(req) - end - uid_logger_dubug("--uri_exec: .....res is #{res.body}") - res = JSON.parse(res.body) - if (res && res['code'] != 0) - tip_exception(status, message) - else - res - end - rescue Exception => e - uid_logger("--uri_exec: exception #{e.message}") - raise Educoder::TipException.new("服务器繁忙") - end - end + # json格式请求 + def interface_json_post(uri, params, status, message) + begin + uid_logger_dubug("--uri_exec: params is #{params}, url is #{uri}") + uri = URI.parse(URI.encode(uri.strip)) + res = Net::HTTP.start(uri.host, uri.port) do |http| + req = Net::HTTP::Post.new(uri) + req['Content-Type'] = 'application/json' + req.body = params.to_json + http.request(req) + end + uid_logger_dubug("--uri_exec: .....res is #{res.body}") + res = JSON.parse(res.body) + if (res && res['code'] != 0) + tip_exception(status, message) + else + res + end + rescue Exception => e + uid_logger("--uri_exec: exception #{e.message}") + raise Educoder::TipException.new("服务器繁忙") + end + end - # 适用与已经用url_safe编码后,回调字符串形式 - def tran_base64_decode64(str) - s_size = str.size % 4 - if s_size != 0 - str += "=" * (4 - s_size) - end - if str.blank? - str - else - Base64.decode64(str.tr("-_", "+/")).force_encoding("utf-8") - end - end + # 适用与已经用url_safe编码后,回调字符串形式 + def tran_base64_decode64(str) + s_size = str.size % 4 + if s_size != 0 + str += "=" * (4 - s_size) + end + if str.blank? + str + else + Base64.decode64(str.tr("-_", "+/")).force_encoding("utf-8") + end + end - def sucess_status(message = 'success') - render :json => { status: 1, message: message } - end + def sucess_status(message = 'success') + render :json => { status: 1, message: message } + end - # 随机生成字符 - def generate_identifier(container, num, pre='') - code = DCODES.sample(num).join - if container == User - while container.exists?(login: pre+code) do - code = DCODES.sample(num).join - end - else - while container.exists?(identifier: code) do - code = DCODES.sample(num).join - end - end - code - end + # 随机生成字符 + def generate_identifier(container, num, pre='') + code = DCODES.sample(num).join + if container == User + while container.exists?(login: pre+code) do + code = DCODES.sample(num).join + end + else + while container.exists?(identifier: code) do + code = DCODES.sample(num).join + end + end + code + end - # 实训主类别列表,自带描述 - def shixun_main_type - list = [] - mirrors = MirrorRepository.select([:id, :type_name, :description, :name]).published_main_mirror - mirrors.try(:each) do |mirror| - list << {id: mirror.id, type_name: mirror.type_name, description: mirror.try(:description), mirror_name: mirror.name} - end - list - end + # 实训主类别列表,自带描述 + def shixun_main_type + list = [] + mirrors = MirrorRepository.select([:id, :type_name, :description, :name]).published_main_mirror + mirrors.try(:each) do |mirror| + list << {id: mirror.id, type_name: mirror.type_name, description: mirror.try(:description), mirror_name: mirror.name} + end + list + end - # 小类别列表 - def shixun_small_type - list = [] - mirrors = MirrorRepository.select([:id, :type_name, :description, :name]).published_small_mirror - mirrors.try(:each) do |mirror| - list << {id: mirror.id, type_name: mirror.type_name, description: mirror.description, mirror_name: mirror.name} - end - list - end + # 小类别列表 + def shixun_small_type + list = [] + mirrors = MirrorRepository.select([:id, :type_name, :description, :name]).published_small_mirror + mirrors.try(:each) do |mirror| + list << {id: mirror.id, type_name: mirror.type_name, description: mirror.description, mirror_name: mirror.name} + end + list + end - def container_limit(mirror_repositories) - container = [] - mirror_repositories.each do |mr| - if mr.name.present? - container << {:image => mr.name, :cpuLimit => mr.cpu_limit, :memoryLimit => "#{mr.memory_limit}M", :type => mr.try(:main_type) == "1" ? "main" : "sub"} - end - end - container.to_json - end + def container_limit(mirror_repositories) + container = [] + mirror_repositories.each do |mr| + if mr.name.present? + container << {:image => mr.name, :cpuLimit => mr.cpu_limit, :memoryLimit => "#{mr.memory_limit}M", :type => mr.try(:main_type) == "1" ? "main" : "sub"} + end + end + container.to_json + end - # 实训中间层pod配置 - def shixun_container_limit shixun - container = [] - shixun.shixun_service_configs.each do |config| - mirror = config.mirror_repository - if mirror.name.present? - # 资源限制没有就传默认值。 - cpu_limit = config.cpu_limit.presence || 1 - cpu_request = config.lower_cpu_limit.presence || 0.1 - memory_limit = config.memory_limit.presence || 1024 - request_limit = config.request_limit.presence || 10 - resource_limit = config.resource_limit.presence || 10000 - container << {:image => mirror.name, - :cpuLimit => cpu_limit, - :cpuRequest => cpu_request, - :memoryLimit => "#{memory_limit}M", - :memoryRequest => "#{request_limit}M", - :resourceLimit => "#{resource_limit}K", - :type => mirror.try(:main_type) == "1" ? "main" : "sub"} - end - end - container.to_json - end + # 实训中间层pod配置 + def shixun_container_limit shixun + container = [] + shixun.shixun_service_configs.each do |config| + mirror = config.mirror_repository + if mirror.name.present? + # 资源限制没有就传默认值。 + cpu_limit = config.cpu_limit.presence || 1 + cpu_request = config.lower_cpu_limit.presence || 0.1 + memory_limit = config.memory_limit.presence || 1024 + request_limit = config.request_limit.presence || 10 + resource_limit = config.resource_limit.presence || 10000 + container << {:image => mirror.name, + :cpuLimit => cpu_limit, + :cpuRequest => cpu_request, + :memoryLimit => "#{memory_limit}M", + :memoryRequest => "#{request_limit}M", + :resourceLimit => "#{resource_limit}K", + :type => mirror.try(:main_type) == "1" ? "main" : "sub"} + end + end + container.to_json + end - # 毕设任务列表的赛选 - def course_work(task, **option) - logger.info("#############{option}") - course = task.course - work_list = task.graduation_works.includes(user: [:user_extension]) - # 教师评阅搜索 0: 未评, 1 已评 - if option[:teacher_comment] - graduation_work_ids = GraduationWorkScore.where(graduation_work_id: work_list.map(&:id)).pluck(:graduation_work_id) - if option[:teacher_comment].zero? - work_list = work_list.where.not(id: graduation_work_ids) - elsif option[:teacher_comment] == 1 - work_list = work_list.where(id: graduation_work_ids).where.not(work_status: 0) - end - end + # 毕设任务列表的赛选 + def course_work(task, **option) + logger.info("#############{option}") + course = task.course + work_list = task.graduation_works.includes(user: [:user_extension]) + # 教师评阅搜索 0: 未评, 1 已评 + if option[:teacher_comment] + graduation_work_ids = GraduationWorkScore.where(graduation_work_id: work_list.map(&:id)).pluck(:graduation_work_id) + if option[:teacher_comment].zero? + work_list = work_list.where.not(id: graduation_work_ids) + elsif option[:teacher_comment] == 1 + work_list = work_list.where(id: graduation_work_ids).where.not(work_status: 0) + end + end - # 作品状态 0: 未提交, 1 按时提交, 2 延迟提交 - if option[:task_status] - work_list = work_list.where(work_status: option[:task_status]) - end + # 作品状态 0: 未提交, 1 按时提交, 2 延迟提交 + if option[:task_status] + work_list = work_list.where(work_status: option[:task_status]) + end - # 分班情况 - if option[:course_group] - group_user_ids = course.course_members.where(course_group_id: option[:course_group]).pluck(:user_id) - # 有分组只可能是老师身份查看列表 - work_list = work_list.where(user_id: group_user_ids) - end + # 分班情况 + if option[:course_group] + group_user_ids = course.course_members.where(course_group_id: option[:course_group]).pluck(:user_id) + # 有分组只可能是老师身份查看列表 + work_list = work_list.where(user_id: group_user_ids) + end - # 只看我的交叉评阅 - if option[:cross_comment] - graduation_work_id = task.graduation_work_comment_assignations.where(:user_id => current_user.id) - .pluck(:graduation_work_id).uniq if task.graduation_work_comment_assignations - work_list = work_list.where(id: graduation_work_id) - end + # 只看我的交叉评阅 + if option[:cross_comment] + graduation_work_id = task.graduation_work_comment_assignations.where(:user_id => current_user.id) + .pluck(:graduation_work_id).uniq if task.graduation_work_comment_assignations + work_list = work_list.where(id: graduation_work_id) + end - # 输入姓名和学号搜索 - # TODO user_extension 如果修改 请调整 - if option[:search] - work_list = work_list.joins(user: :user_extension).where("concat(lastname, firstname) like ? + # 输入姓名和学号搜索 + # TODO user_extension 如果修改 请调整 + if option[:search] + work_list = work_list.joins(user: :user_extension).where("concat(lastname, firstname) like ? or student_id like ?", "%#{option[:search]}%", "%#{option[:search]}%") - end + end - # 排序 - rorder = option[:order] || "updated_at" - b_order = option[:b_order] || "desc" - if rorder == "created_at" || rorder == "work_score" - work_list = work_list.order("graduation_works.#{rorder} #{b_order}") - elsif rorder == "student_id" - work_list = work_list.joins(user: :user_extension).order("user_extensions.#{rorder} #{b_order}") - end - work_list - end + # 排序 + rorder = option[:order] || "updated_at" + b_order = option[:b_order] || "desc" + if rorder == "created_at" || rorder == "work_score" + work_list = work_list.order("graduation_works.#{rorder} #{b_order}") + elsif rorder == "student_id" + work_list = work_list.joins(user: :user_extension).order("user_extensions.#{rorder} #{b_order}") + end + work_list + end - def strip_html(text, len=0, endss="...") - ss = "" - if !text.nil? && text.length>0 - ss=text.gsub(/<\/?.*?>/, '').strip - ss = ss.gsub(/ */, '') - ss = ss.gsub(/\r\n/,'') #新增 - ss = ss.gsub(/\n/,'') #新增 - if len > 0 && ss.length > len - ss = ss[0, len] + endss - elsif len > 0 && ss.length <= len - ss = ss - #ss = truncate(ss, :length => len) - end - end - ss - end + def strip_html(text, len=0, endss="...") + ss = "" + if !text.nil? && text.length>0 + ss=text.gsub(/<\/?.*?>/, '').strip + ss = ss.gsub(/ */, '') + ss = ss.gsub(/\r\n/,'') #新增 + ss = ss.gsub(/\n/,'') #新增 + if len > 0 && ss.length > len + ss = ss[0, len] + endss + elsif len > 0 && ss.length <= len + ss = ss + #ss = truncate(ss, :length => len) + end + end + ss + end - # Returns a string that can be used as filename value in Content-Disposition header - def filename_for_content_disposition(name) - request.env['HTTP_USER_AGENT'] =~ %r{MSIE|Trident|Edge} ? ERB::Util.url_encode(name) : name - end + # Returns a string that can be used as filename value in Content-Disposition header + def filename_for_content_disposition(name) + request.env['HTTP_USER_AGENT'] =~ %r{MSIE|Trident|Edge} ? ERB::Util.url_encode(name) : name + end - def format_time(time) - time.blank? ? '' : time.strftime("%Y-%m-%d %H:%M") - end + def format_time(time) + time.blank? ? '' : time.strftime("%Y-%m-%d %H:%M") + end - # 获取Oauth Client - def get_client(site) - client_id = Rails.configuration.educoder['client_id'] - client_secret = Rails.configuration.educoder['client_secret'] + # 获取Oauth Client + def get_client(site) + client_id = Rails.configuration.educoder['client_id'] + client_secret = Rails.configuration.educoder['client_secret'] - OAuth2::Client.new(client_id, client_secret, site: site) - end + OAuth2::Client.new(client_id, client_secret, site: site) + end - def paginate(relation) - limit = params[:limit] || params[:per_page] - limit = (limit.to_i.zero? || limit.to_i > 20) ? 20 : limit.to_i - page = params[:page].to_i.zero? ? 1 : params[:page].to_i - offset = (page - 1) * limit + def paginate(relation) + limit = params[:limit] || params[:per_page] + limit = (limit.to_i.zero? || limit.to_i > 20) ? 20 : limit.to_i + page = params[:page].to_i.zero? ? 1 : params[:page].to_i + offset = (page - 1) * limit - if relation.is_a?(Array) - relation[offset, limit] - else - relation.limit(limit).offset(offset) - end - end + if relation.is_a?(Array) + relation[offset, limit] + else + relation.limit(limit).offset(offset) + end + end - def kaminari_paginate(relation) - limit = params[:limit] || params[:per_page] - limit = (limit.to_i.zero? || limit.to_i > 15) ? 15 : limit.to_i - page = params[:page].to_i.zero? ? 1 : params[:page].to_i + def kaminari_paginate(relation) + limit = params[:limit] || params[:per_page] + limit = (limit.to_i.zero? || limit.to_i > 15) ? 15 : limit.to_i + page = params[:page].to_i.zero? ? 1 : params[:page].to_i - relation.page(page).per(limit) - end + relation.page(page).per(limit) + end - def strf_time(time) - time.blank? ? '' : time.strftime("%Y-%m-%d %H:%M:%S") - end + def strf_time(time) + time.blank? ? '' : time.strftime("%Y-%m-%d %H:%M:%S") + end - def strf_date(date) - date.blank? ? '' : date.to_date.strftime("%Y-%m-%d") - end + def strf_date(date) + date.blank? ? '' : date.to_date.strftime("%Y-%m-%d") + end - def logger_error(error) - Rails.logger.error(error.message) - error.backtrace.each { |msg| Rails.logger.error(msg) } - end + def logger_error(error) + Rails.logger.error(error.message) + error.backtrace.each { |msg| Rails.logger.error(msg) } + end - def find_user - @user = User.find_by_login params[:login] + def find_user + @user = User.find_by_login params[:login] render_not_found("未找到’#{params[:login]}’相关的用户") unless @user - end + end - def find_user_with_id - @user = User.find_by_id params[:user_id] + def find_user_with_id + @user = User.find_by_id params[:user_id] # render_not_found("未找到’#{params[:login]}’相关的用户") unless @user - render_error("未找到相关的用户") unless @user - end + render_error("未找到相关的用户") unless @user + end - def find_repository - @repo = @user.repositories.find_by_identifier params[:repo_identifier] + def find_repository + @repo = @user.repositories.find_by_identifier params[:repo_identifier] render_not_found("未找到’#{params[:repo_identifier]}’相关的项目") unless @repo - end + end - def find_repository_by_id - @repo = Repository.find params[:id] - end + def find_repository_by_id + @repo = Repository.find params[:id] + end - def find_project - project_id = params[:project_id] ? params[:project_id] : params[:id] - project = Project.where(identifier: project_id) - if project.exists? - @project = project.first - else - @project = Project.find project_id - end + def find_project + project_id = params[:project_id] ? params[:project_id] : params[:id] + project = Project.where(identifier: project_id) + if project.exists? + @project = project.first + else + @project = Project.find project_id + end - render_not_found("未找到’#{project}’相关的项目") unless @project - end + render_not_found("未找到’#{project}’相关的项目") unless @project + end - def find_project_with_identifier - @project = Project.find_by_identifier! params[:id] - render_not_found("未找到’#{params[:id]}’相关的项目") unless @project - end + def find_project_with_identifier + @project = Project.find_by_identifier! params[:id] + render_not_found("未找到’#{params[:id]}’相关的项目") unless @project + end - def find_project_with_id - @project = Project.find(params[:project_id] || params[:id]) - rescue Exception => e - logger_error(e.message) - tip_exception(e.message) - end + def find_project_with_id + @project = Project.find(params[:project_id] || params[:id]) + rescue Exception => e + logger_error(e.message) + tip_exception(e.message) + end - def render_response(interactor) - interactor.success? ? render_ok : render_error(interactor.error) - end + def render_response(interactor) + interactor.success? ? render_ok : render_error(interactor.error) + end private - def object_not_found - uid_logger("Missing template or cant't find record, responding with 404") - render json: {message: "您访问的页面不存在或已被删除", status: 404} - false - end + def object_not_found + uid_logger("Missing template or cant't find record, responding with 404") + render json: {message: "您访问的页面不存在或已被删除", status: 404} + false + end - def tip_show(exception) - uid_logger("Tip show status is #{exception.status}, message is #{exception.message}") - render json: exception.tip_json - end + def tip_show(exception) + uid_logger("Tip show status is #{exception.status}, message is #{exception.message}") + render json: exception.tip_json + end - def render_parameter_missing - render json: { status: -1, message: '参数缺失' } - end + def render_parameter_missing + render json: { status: -1, message: '参数缺失' } + end - def set_export_cookies - cookies[:fileDownload] = true - end + def set_export_cookies + cookies[:fileDownload] = true + end - # 149课程的评审用户数据创建(包含创建课堂学生) - def open_class_user - user = User.find_by(login: "OpenClassUser") - unless user - ActiveRecord::Base.transaction do - user_params = {status: 1, login: "OpenClassUser", lastname: "开放课程", - nickname: "开放课程", professional_certification: 1, certification: 1, grade: 0, - password: "12345678", phone: "11122223333", profile_completed: 1} - user = User.create!(user_params) + # 149课程的评审用户数据创建(包含创建课堂学生) + def open_class_user + user = User.find_by(login: "OpenClassUser") + unless user + ActiveRecord::Base.transaction do + user_params = {status: 1, login: "OpenClassUser", lastname: "开放课程", + nickname: "开放课程", professional_certification: 1, certification: 1, grade: 0, + password: "12345678", phone: "11122223333", profile_completed: 1} + user = User.create!(user_params) - UserExtension.create!(user_id: user.id, gender: 0, school_id: 3396, :identity => 1, :student_id => "openclassuser") # 3396 + UserExtension.create!(user_id: user.id, gender: 0, school_id: 3396, :identity => 1, :student_id => "openclassuser") # 3396 - subject = Subject.find_by(id: 149) - if subject - subject.courses.each do |course| - CourseMember.create!(course_id: course.id, role: 3, user_id: user.id) if !course.course_members.exists?(user_id: user.id) - end - end - end - end - user - end + subject = Subject.find_by(id: 149) + if subject + subject.courses.each do |course| + CourseMember.create!(course_id: course.id, role: 3, user_id: user.id) if !course.course_members.exists?(user_id: user.id) + end + end + end + end + user + end - # 记录热门搜索关键字 - def record_search_keyword - keyword = params[:keyword].to_s.strip - return if keyword.blank? || keyword.size <= 1 - return unless HotSearchKeyword.available? + # 记录热门搜索关键字 + def record_search_keyword + keyword = params[:keyword].to_s.strip + return if keyword.blank? || keyword.size <= 1 + return unless HotSearchKeyword.available? - HotSearchKeyword.add(keyword) - end + HotSearchKeyword.add(keyword) + end end \ No newline at end of file diff --git a/db/migrate/20200724085032_add_column_to_table_users.rb b/db/migrate/20200724085032_add_column_to_table_users.rb new file mode 100644 index 00000000..3fa706ac --- /dev/null +++ b/db/migrate/20200724085032_add_column_to_table_users.rb @@ -0,0 +1,8 @@ +class AddColumnToTableUsers < ActiveRecord::Migration[5.2] + def change + add_column :users, :description, :string, default: "" + add_column :users, :sponsor_certification, :integer, default: 0 + add_column :users, :sponsor_num, :integer, default: 0 + add_column :users, :sponsored_num, :integer, default: 0 + end +end diff --git a/db/structure.sql b/db/structure.sql index 9ad78c02..18662e23 100644 --- a/db/structure.sql +++ b/db/structure.sql @@ -55,7 +55,7 @@ CREATE TABLE `applied_contests` ( -- ---------------------------- -- Table structure for applied_messages -- ---------------------------- -DROP TABLE IF EXISTS `applied_messages`; +DROP TABLE IF /home/qyzh/datadict.txtpplied_messages`; CREATE TABLE `applied_messages` ( `id` int(11) NOT NULL AUTO_INCREMENT, `user_id` int(11) DEFAULT NULL, From cb089b1bb8c8383c09eec5fd3868e5f6308dcc25 Mon Sep 17 00:00:00 2001 From: wyx Date: Fri, 24 Jul 2020 17:21:16 +0800 Subject: [PATCH 02/16] create table sponsorship --- app/assets/javascripts/sponsorships.js | 2 + app/assets/stylesheets/scaffolds.scss | 84 +++++++++++ app/assets/stylesheets/sponsorships.scss | 3 + app/controllers/sponsorships_controller.rb | 74 +++++++++ app/helpers/sponsorships_helper.rb | 2 + app/models/sponsorship.rb | 5 + app/views/sponsorships/_form.html.erb | 16 ++ .../sponsorships/_sponsorship.json.jbuilder | 2 + app/views/sponsorships/edit.html.erb | 6 + app/views/sponsorships/index.html.erb | 33 ++++ app/views/sponsorships/index.json.jbuilder | 1 + app/views/sponsorships/new.html.erb | 5 + app/views/sponsorships/show.html.erb | 24 +++ app/views/sponsorships/show.json.jbuilder | 1 + config/routes.rb | 1 + .../20200724090750_create_sponsorships.rb | 12 ++ .../sponsorships_controller_spec.rb | 141 ++++++++++++++++++ spec/helpers/sponsorships_helper_spec.rb | 15 ++ spec/models/sponsorship_spec.rb | 5 + spec/requests/sponsorships_spec.rb | 10 ++ spec/routing/sponsorships_routing_spec.rb | 38 +++++ spec/views/sponsorships/edit.html.erb_spec.rb | 27 ++++ .../views/sponsorships/index.html.erb_spec.rb | 28 ++++ spec/views/sponsorships/new.html.erb_spec.rb | 27 ++++ spec/views/sponsorships/show.html.erb_spec.rb | 20 +++ 25 files changed, 582 insertions(+) create mode 100644 app/assets/javascripts/sponsorships.js create mode 100644 app/assets/stylesheets/scaffolds.scss create mode 100644 app/assets/stylesheets/sponsorships.scss create mode 100644 app/controllers/sponsorships_controller.rb create mode 100644 app/helpers/sponsorships_helper.rb create mode 100644 app/models/sponsorship.rb create mode 100644 app/views/sponsorships/_form.html.erb create mode 100644 app/views/sponsorships/_sponsorship.json.jbuilder create mode 100644 app/views/sponsorships/edit.html.erb create mode 100644 app/views/sponsorships/index.html.erb create mode 100644 app/views/sponsorships/index.json.jbuilder create mode 100644 app/views/sponsorships/new.html.erb create mode 100644 app/views/sponsorships/show.html.erb create mode 100644 app/views/sponsorships/show.json.jbuilder create mode 100644 db/migrate/20200724090750_create_sponsorships.rb create mode 100644 spec/controllers/sponsorships_controller_spec.rb create mode 100644 spec/helpers/sponsorships_helper_spec.rb create mode 100644 spec/models/sponsorship_spec.rb create mode 100644 spec/requests/sponsorships_spec.rb create mode 100644 spec/routing/sponsorships_routing_spec.rb create mode 100644 spec/views/sponsorships/edit.html.erb_spec.rb create mode 100644 spec/views/sponsorships/index.html.erb_spec.rb create mode 100644 spec/views/sponsorships/new.html.erb_spec.rb create mode 100644 spec/views/sponsorships/show.html.erb_spec.rb diff --git a/app/assets/javascripts/sponsorships.js b/app/assets/javascripts/sponsorships.js new file mode 100644 index 00000000..dee720fa --- /dev/null +++ b/app/assets/javascripts/sponsorships.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/scaffolds.scss b/app/assets/stylesheets/scaffolds.scss new file mode 100644 index 00000000..60451880 --- /dev/null +++ b/app/assets/stylesheets/scaffolds.scss @@ -0,0 +1,84 @@ +body { + background-color: #fff; + color: #333; + margin: 33px; + font-family: verdana, arial, helvetica, sans-serif; + font-size: 13px; + line-height: 18px; +} + +p, ol, ul, td { + font-family: verdana, arial, helvetica, sans-serif; + font-size: 13px; + line-height: 18px; +} + +pre { + background-color: #eee; + padding: 10px; + font-size: 11px; +} + +a { + color: #000; + + &:visited { + color: #666; + } + + &:hover { + color: #fff; + background-color: #000; + } +} + +th { + padding-bottom: 5px; +} + +td { + padding: 0 5px 7px; +} + +div { + &.field, &.actions { + margin-bottom: 10px; + } +} + +#notice { + color: green; +} + +.field_with_errors { + padding: 2px; + background-color: red; + display: table; +} + +#error_explanation { + width: 450px; + border: 2px solid red; + padding: 7px 7px 0; + margin-bottom: 20px; + background-color: #f0f0f0; + + h2 { + text-align: left; + font-weight: bold; + padding: 5px 5px 5px 15px; + font-size: 12px; + margin: -7px -7px 0; + background-color: #c00; + color: #fff; + } + + ul li { + font-size: 12px; + list-style: square; + } +} + +label { + display: block; +} diff --git a/app/assets/stylesheets/sponsorships.scss b/app/assets/stylesheets/sponsorships.scss new file mode 100644 index 00000000..3d9a20ea --- /dev/null +++ b/app/assets/stylesheets/sponsorships.scss @@ -0,0 +1,3 @@ +// Place all the styles related to the Sponsorships controller here. +// They will automatically be included in application.css. +// You can use Sass (SCSS) here: http://sass-lang.com/ diff --git a/app/controllers/sponsorships_controller.rb b/app/controllers/sponsorships_controller.rb new file mode 100644 index 00000000..508350f2 --- /dev/null +++ b/app/controllers/sponsorships_controller.rb @@ -0,0 +1,74 @@ +class SponsorshipsController < ApplicationController + before_action :set_sponsorship, only: [:show, :edit, :update, :destroy] + + # GET /sponsorships + # GET /sponsorships.json + def index + @sponsorships = Sponsorship.all + end + + # GET /sponsorships/1 + # GET /sponsorships/1.json + def show + end + + # GET /sponsorships/new + def new + @sponsorship = Sponsorship.new + end + + # GET /sponsorships/1/edit + def edit + end + + # POST /sponsorships + # POST /sponsorships.json + def create + @sponsorship = Sponsorship.new(sponsorship_params) + + respond_to do |format| + if @sponsorship.save + format.html { redirect_to @sponsorship, notice: 'Sponsorship was successfully created.' } + format.json { render :show, status: :created, location: @sponsorship } + else + format.html { render :new } + format.json { render json: @sponsorship.errors, status: :unprocessable_entity } + end + end + end + + # PATCH/PUT /sponsorships/1 + # PATCH/PUT /sponsorships/1.json + def update + respond_to do |format| + if @sponsorship.update(sponsorship_params) + format.html { redirect_to @sponsorship, notice: 'Sponsorship was successfully updated.' } + format.json { render :show, status: :ok, location: @sponsorship } + else + format.html { render :edit } + format.json { render json: @sponsorship.errors, status: :unprocessable_entity } + end + end + end + + # DELETE /sponsorships/1 + # DELETE /sponsorships/1.json + def destroy + @sponsorship.destroy + respond_to do |format| + format.html { redirect_to sponsorships_url, notice: 'Sponsorship was successfully destroyed.' } + format.json { head :no_content } + end + end + + private + # Use callbacks to share common setup or constraints between actions. + def set_sponsorship + @sponsorship = Sponsorship.find(params[:id]) + end + + # Only allow a list of trusted parameters through. + def sponsorship_params + params.require(:sponsorship).permit(:amount, :visible, :sponsor_id, :developer_id) + end +end diff --git a/app/helpers/sponsorships_helper.rb b/app/helpers/sponsorships_helper.rb new file mode 100644 index 00000000..f6ea1f0d --- /dev/null +++ b/app/helpers/sponsorships_helper.rb @@ -0,0 +1,2 @@ +module SponsorshipsHelper +end diff --git a/app/models/sponsorship.rb b/app/models/sponsorship.rb new file mode 100644 index 00000000..e2d44801 --- /dev/null +++ b/app/models/sponsorship.rb @@ -0,0 +1,5 @@ +class Sponsorship < ApplicationRecord + belongs_to :sponsor, class_name: 'User' + belongs_to :developer, class_name: 'User' + validates :amount, presence: true +end diff --git a/app/views/sponsorships/_form.html.erb b/app/views/sponsorships/_form.html.erb new file mode 100644 index 00000000..aba15064 --- /dev/null +++ b/app/views/sponsorships/_form.html.erb @@ -0,0 +1,16 @@ + +<%= simple_form_for(@sponsorship) do |f| %> + <%= f.error_notification %> + <%= f.error_notification message: f.object.errors[:base].to_sentence if f.object.errors[:base].present? %> + +
+ <%= f.input :amount %> + <%= f.input :visible %> + <%= f.input :sponsor_id %> + <%= f.input :developer_id %> +
+ +
+ <%= f.button :submit %> +
+<% end %> diff --git a/app/views/sponsorships/_sponsorship.json.jbuilder b/app/views/sponsorships/_sponsorship.json.jbuilder new file mode 100644 index 00000000..9b202d68 --- /dev/null +++ b/app/views/sponsorships/_sponsorship.json.jbuilder @@ -0,0 +1,2 @@ +json.extract! sponsorship, :id, :amount, :visible, :sponsor_id, :developer_id, :created_at, :updated_at +json.url sponsorship_url(sponsorship, format: :json) diff --git a/app/views/sponsorships/edit.html.erb b/app/views/sponsorships/edit.html.erb new file mode 100644 index 00000000..45d623bb --- /dev/null +++ b/app/views/sponsorships/edit.html.erb @@ -0,0 +1,6 @@ +

Editing Sponsorship

+ +<%= render 'form', sponsorship: @sponsorship %> + +<%= link_to 'Show', @sponsorship %> | +<%= link_to 'Back', sponsorships_path %> diff --git a/app/views/sponsorships/index.html.erb b/app/views/sponsorships/index.html.erb new file mode 100644 index 00000000..d539f213 --- /dev/null +++ b/app/views/sponsorships/index.html.erb @@ -0,0 +1,33 @@ +

<%= notice %>

+ +

Sponsorships

+ + + + + + + + + + + + + + <% @sponsorships.each do |sponsorship| %> + + + + + + + + + + <% end %> + +
AmountVisibleSponsorDeveloper
<%= sponsorship.amount %><%= sponsorship.visible %><%= sponsorship.sponsor_id %><%= sponsorship.developer_id %><%= link_to 'Show', sponsorship %><%= link_to 'Edit', edit_sponsorship_path(sponsorship) %><%= link_to 'Destroy', sponsorship, method: :delete, data: { confirm: 'Are you sure?' } %>
+ +
+ +<%= link_to 'New Sponsorship', new_sponsorship_path %> diff --git a/app/views/sponsorships/index.json.jbuilder b/app/views/sponsorships/index.json.jbuilder new file mode 100644 index 00000000..d02d0390 --- /dev/null +++ b/app/views/sponsorships/index.json.jbuilder @@ -0,0 +1 @@ +json.array! @sponsorships, partial: "sponsorships/sponsorship", as: :sponsorship diff --git a/app/views/sponsorships/new.html.erb b/app/views/sponsorships/new.html.erb new file mode 100644 index 00000000..914dc917 --- /dev/null +++ b/app/views/sponsorships/new.html.erb @@ -0,0 +1,5 @@ +

New Sponsorship

+ +<%= render 'form', sponsorship: @sponsorship %> + +<%= link_to 'Back', sponsorships_path %> diff --git a/app/views/sponsorships/show.html.erb b/app/views/sponsorships/show.html.erb new file mode 100644 index 00000000..d9ab06ff --- /dev/null +++ b/app/views/sponsorships/show.html.erb @@ -0,0 +1,24 @@ +

<%= notice %>

+ +

+ Amount: + <%= @sponsorship.amount %> +

+ +

+ Visible: + <%= @sponsorship.visible %> +

+ +

+ Sponsor: + <%= @sponsorship.sponsor_id %> +

+ +

+ Developer: + <%= @sponsorship.developer_id %> +

+ +<%= link_to 'Edit', edit_sponsorship_path(@sponsorship) %> | +<%= link_to 'Back', sponsorships_path %> diff --git a/app/views/sponsorships/show.json.jbuilder b/app/views/sponsorships/show.json.jbuilder new file mode 100644 index 00000000..87ded287 --- /dev/null +++ b/app/views/sponsorships/show.json.jbuilder @@ -0,0 +1 @@ +json.partial! "sponsorships/sponsorship", sponsorship: @sponsorship diff --git a/config/routes.rb b/config/routes.rb index 45ba4855..b4faefff 100644 --- a/config/routes.rb +++ b/config/routes.rb @@ -1,5 +1,6 @@ Rails.application.routes.draw do + resources :sponsorships require 'sidekiq/web' require 'admin_constraint' diff --git a/db/migrate/20200724090750_create_sponsorships.rb b/db/migrate/20200724090750_create_sponsorships.rb new file mode 100644 index 00000000..6feb9892 --- /dev/null +++ b/db/migrate/20200724090750_create_sponsorships.rb @@ -0,0 +1,12 @@ +class CreateSponsorships < ActiveRecord::Migration[5.2] + def change + create_table :sponsorships do |t| + t.integer :amount + t.integer :visible + t.integer :sponsor_id + t.integer :developer_id + + t.timestamps + end + end +end diff --git a/spec/controllers/sponsorships_controller_spec.rb b/spec/controllers/sponsorships_controller_spec.rb new file mode 100644 index 00000000..6098d4d6 --- /dev/null +++ b/spec/controllers/sponsorships_controller_spec.rb @@ -0,0 +1,141 @@ +require 'rails_helper' + +# This spec was generated by rspec-rails when you ran the scaffold generator. +# It demonstrates how one might use RSpec to specify the controller code that +# was generated by Rails when you ran the scaffold generator. +# +# It assumes that the implementation code is generated by the rails scaffold +# generator. If you are using any extension libraries to generate different +# controller code, this generated spec may or may not pass. +# +# It only uses APIs available in rails and/or rspec-rails. There are a number +# of tools you can use to make these specs even more expressive, but we're +# sticking to rails and rspec-rails APIs to keep things simple and stable. +# +# Compared to earlier versions of this generator, there is very limited use of +# stubs and message expectations in this spec. Stubs are only used when there +# is no simpler way to get a handle on the object needed for the example. +# Message expectations are only used when there is no simpler way to specify +# that an instance is receiving a specific message. +# +# Also compared to earlier versions of this generator, there are no longer any +# expectations of assigns and templates rendered. These features have been +# removed from Rails core in Rails 5, but can be added back in via the +# `rails-controller-testing` gem. + +RSpec.describe SponsorshipsController, type: :controller do + + # This should return the minimal set of attributes required to create a valid + # Sponsorship. As you add validations to Sponsorship, be sure to + # adjust the attributes here as well. + let(:valid_attributes) { + skip("Add a hash of attributes valid for your model") + } + + let(:invalid_attributes) { + skip("Add a hash of attributes invalid for your model") + } + + # This should return the minimal set of values that should be in the session + # in order to pass any filters (e.g. authentication) defined in + # SponsorshipsController. Be sure to keep this updated too. + let(:valid_session) { {} } + + describe "GET #index" do + it "returns a success response" do + Sponsorship.create! valid_attributes + get :index, params: {}, session: valid_session + expect(response).to be_successful + end + end + + describe "GET #show" do + it "returns a success response" do + sponsorship = Sponsorship.create! valid_attributes + get :show, params: {id: sponsorship.to_param}, session: valid_session + expect(response).to be_successful + end + end + + describe "GET #new" do + it "returns a success response" do + get :new, params: {}, session: valid_session + expect(response).to be_successful + end + end + + describe "GET #edit" do + it "returns a success response" do + sponsorship = Sponsorship.create! valid_attributes + get :edit, params: {id: sponsorship.to_param}, session: valid_session + expect(response).to be_successful + end + end + + describe "POST #create" do + context "with valid params" do + it "creates a new Sponsorship" do + expect { + post :create, params: {sponsorship: valid_attributes}, session: valid_session + }.to change(Sponsorship, :count).by(1) + end + + it "redirects to the created sponsorship" do + post :create, params: {sponsorship: valid_attributes}, session: valid_session + expect(response).to redirect_to(Sponsorship.last) + end + end + + context "with invalid params" do + it "returns a success response (i.e. to display the 'new' template)" do + post :create, params: {sponsorship: invalid_attributes}, session: valid_session + expect(response).to be_successful + end + end + end + + describe "PUT #update" do + context "with valid params" do + let(:new_attributes) { + skip("Add a hash of attributes valid for your model") + } + + it "updates the requested sponsorship" do + sponsorship = Sponsorship.create! valid_attributes + put :update, params: {id: sponsorship.to_param, sponsorship: new_attributes}, session: valid_session + sponsorship.reload + skip("Add assertions for updated state") + end + + it "redirects to the sponsorship" do + sponsorship = Sponsorship.create! valid_attributes + put :update, params: {id: sponsorship.to_param, sponsorship: valid_attributes}, session: valid_session + expect(response).to redirect_to(sponsorship) + end + end + + context "with invalid params" do + it "returns a success response (i.e. to display the 'edit' template)" do + sponsorship = Sponsorship.create! valid_attributes + put :update, params: {id: sponsorship.to_param, sponsorship: invalid_attributes}, session: valid_session + expect(response).to be_successful + end + end + end + + describe "DELETE #destroy" do + it "destroys the requested sponsorship" do + sponsorship = Sponsorship.create! valid_attributes + expect { + delete :destroy, params: {id: sponsorship.to_param}, session: valid_session + }.to change(Sponsorship, :count).by(-1) + end + + it "redirects to the sponsorships list" do + sponsorship = Sponsorship.create! valid_attributes + delete :destroy, params: {id: sponsorship.to_param}, session: valid_session + expect(response).to redirect_to(sponsorships_url) + end + end + +end diff --git a/spec/helpers/sponsorships_helper_spec.rb b/spec/helpers/sponsorships_helper_spec.rb new file mode 100644 index 00000000..229491bf --- /dev/null +++ b/spec/helpers/sponsorships_helper_spec.rb @@ -0,0 +1,15 @@ +require 'rails_helper' + +# Specs in this file have access to a helper object that includes +# the SponsorshipsHelper. For example: +# +# describe SponsorshipsHelper do +# describe "string concat" do +# it "concats two strings with spaces" do +# expect(helper.concat_strings("this","that")).to eq("this that") +# end +# end +# end +RSpec.describe SponsorshipsHelper, type: :helper do + pending "add some examples to (or delete) #{__FILE__}" +end diff --git a/spec/models/sponsorship_spec.rb b/spec/models/sponsorship_spec.rb new file mode 100644 index 00000000..d2e58e69 --- /dev/null +++ b/spec/models/sponsorship_spec.rb @@ -0,0 +1,5 @@ +require 'rails_helper' + +RSpec.describe Sponsorship, type: :model do + pending "add some examples to (or delete) #{__FILE__}" +end diff --git a/spec/requests/sponsorships_spec.rb b/spec/requests/sponsorships_spec.rb new file mode 100644 index 00000000..795504c7 --- /dev/null +++ b/spec/requests/sponsorships_spec.rb @@ -0,0 +1,10 @@ +require 'rails_helper' + +RSpec.describe "Sponsorships", type: :request do + describe "GET /sponsorships" do + it "works! (now write some real specs)" do + get sponsorships_path + expect(response).to have_http_status(200) + end + end +end diff --git a/spec/routing/sponsorships_routing_spec.rb b/spec/routing/sponsorships_routing_spec.rb new file mode 100644 index 00000000..4e0cd20b --- /dev/null +++ b/spec/routing/sponsorships_routing_spec.rb @@ -0,0 +1,38 @@ +require "rails_helper" + +RSpec.describe SponsorshipsController, type: :routing do + describe "routing" do + it "routes to #index" do + expect(:get => "/sponsorships").to route_to("sponsorships#index") + end + + it "routes to #new" do + expect(:get => "/sponsorships/new").to route_to("sponsorships#new") + end + + it "routes to #show" do + expect(:get => "/sponsorships/1").to route_to("sponsorships#show", :id => "1") + end + + it "routes to #edit" do + expect(:get => "/sponsorships/1/edit").to route_to("sponsorships#edit", :id => "1") + end + + + it "routes to #create" do + expect(:post => "/sponsorships").to route_to("sponsorships#create") + end + + it "routes to #update via PUT" do + expect(:put => "/sponsorships/1").to route_to("sponsorships#update", :id => "1") + end + + it "routes to #update via PATCH" do + expect(:patch => "/sponsorships/1").to route_to("sponsorships#update", :id => "1") + end + + it "routes to #destroy" do + expect(:delete => "/sponsorships/1").to route_to("sponsorships#destroy", :id => "1") + end + end +end diff --git a/spec/views/sponsorships/edit.html.erb_spec.rb b/spec/views/sponsorships/edit.html.erb_spec.rb new file mode 100644 index 00000000..e676afd1 --- /dev/null +++ b/spec/views/sponsorships/edit.html.erb_spec.rb @@ -0,0 +1,27 @@ +require 'rails_helper' + +RSpec.describe "sponsorships/edit", type: :view do + before(:each) do + @sponsorship = assign(:sponsorship, Sponsorship.create!( + :amount => 1, + :visible => 1, + :sponsor_id => 1, + :developer_id => 1 + )) + end + + it "renders the edit sponsorship form" do + render + + assert_select "form[action=?][method=?]", sponsorship_path(@sponsorship), "post" do + + assert_select "input[name=?]", "sponsorship[amount]" + + assert_select "input[name=?]", "sponsorship[visible]" + + assert_select "input[name=?]", "sponsorship[sponsor_id]" + + assert_select "input[name=?]", "sponsorship[developer_id]" + end + end +end diff --git a/spec/views/sponsorships/index.html.erb_spec.rb b/spec/views/sponsorships/index.html.erb_spec.rb new file mode 100644 index 00000000..c31533a1 --- /dev/null +++ b/spec/views/sponsorships/index.html.erb_spec.rb @@ -0,0 +1,28 @@ +require 'rails_helper' + +RSpec.describe "sponsorships/index", type: :view do + before(:each) do + assign(:sponsorships, [ + Sponsorship.create!( + :amount => 2, + :visible => 3, + :sponsor_id => 4, + :developer_id => 5 + ), + Sponsorship.create!( + :amount => 2, + :visible => 3, + :sponsor_id => 4, + :developer_id => 5 + ) + ]) + end + + it "renders a list of sponsorships" do + render + assert_select "tr>td", :text => 2.to_s, :count => 2 + assert_select "tr>td", :text => 3.to_s, :count => 2 + assert_select "tr>td", :text => 4.to_s, :count => 2 + assert_select "tr>td", :text => 5.to_s, :count => 2 + end +end diff --git a/spec/views/sponsorships/new.html.erb_spec.rb b/spec/views/sponsorships/new.html.erb_spec.rb new file mode 100644 index 00000000..9c816df1 --- /dev/null +++ b/spec/views/sponsorships/new.html.erb_spec.rb @@ -0,0 +1,27 @@ +require 'rails_helper' + +RSpec.describe "sponsorships/new", type: :view do + before(:each) do + assign(:sponsorship, Sponsorship.new( + :amount => 1, + :visible => 1, + :sponsor_id => 1, + :developer_id => 1 + )) + end + + it "renders new sponsorship form" do + render + + assert_select "form[action=?][method=?]", sponsorships_path, "post" do + + assert_select "input[name=?]", "sponsorship[amount]" + + assert_select "input[name=?]", "sponsorship[visible]" + + assert_select "input[name=?]", "sponsorship[sponsor_id]" + + assert_select "input[name=?]", "sponsorship[developer_id]" + end + end +end diff --git a/spec/views/sponsorships/show.html.erb_spec.rb b/spec/views/sponsorships/show.html.erb_spec.rb new file mode 100644 index 00000000..dffc5a4d --- /dev/null +++ b/spec/views/sponsorships/show.html.erb_spec.rb @@ -0,0 +1,20 @@ +require 'rails_helper' + +RSpec.describe "sponsorships/show", type: :view do + before(:each) do + @sponsorship = assign(:sponsorship, Sponsorship.create!( + :amount => 2, + :visible => 3, + :sponsor_id => 4, + :developer_id => 5 + )) + end + + it "renders attributes in

" do + render + expect(rendered).to match(/2/) + expect(rendered).to match(/3/) + expect(rendered).to match(/4/) + expect(rendered).to match(/5/) + end +end From 0a460d1d377a3a4a1e983f3d24aa82cec214e8d8 Mon Sep 17 00:00:00 2001 From: wyx <414722560@qq.com> Date: Fri, 24 Jul 2020 17:38:31 +0800 Subject: [PATCH 03/16] create sponsor_tier --- app/assets/javascripts/sponsor_tiers.js | 2 + app/assets/stylesheets/sponsor_tiers.scss | 3 + app/controllers/sponsor_tiers_controller.rb | 74 +++++++++ app/helpers/sponsor_tiers_helper.rb | 2 + app/models/sponsor_tier.rb | 2 + app/views/sponsor_tiers/_form.html.erb | 13 ++ .../sponsor_tiers/_sponsor_tier.json.jbuilder | 2 + app/views/sponsor_tiers/edit.html.erb | 6 + app/views/sponsor_tiers/index.html.erb | 27 ++++ app/views/sponsor_tiers/index.json.jbuilder | 1 + app/views/sponsor_tiers/new.html.erb | 5 + app/views/sponsor_tiers/show.html.erb | 9 ++ app/views/sponsor_tiers/show.json.jbuilder | 1 + config/routes.rb | 1 + .../20200724093202_create_sponsor_tiers.rb | 9 ++ ...00724093530_add_column_to_sponsor_tiers.rb | 6 + .../sponsor_tiers_controller_spec.rb | 141 ++++++++++++++++++ spec/helpers/sponsor_tiers_helper_spec.rb | 15 ++ spec/models/sponsor_tier_spec.rb | 5 + spec/requests/sponsor_tiers_spec.rb | 10 ++ spec/routing/sponsor_tiers_routing_spec.rb | 38 +++++ .../views/sponsor_tiers/edit.html.erb_spec.rb | 18 +++ .../sponsor_tiers/index.html.erb_spec.rb | 19 +++ spec/views/sponsor_tiers/new.html.erb_spec.rb | 18 +++ .../views/sponsor_tiers/show.html.erb_spec.rb | 14 ++ 25 files changed, 441 insertions(+) create mode 100644 app/assets/javascripts/sponsor_tiers.js create mode 100644 app/assets/stylesheets/sponsor_tiers.scss create mode 100644 app/controllers/sponsor_tiers_controller.rb create mode 100644 app/helpers/sponsor_tiers_helper.rb create mode 100644 app/models/sponsor_tier.rb create mode 100644 app/views/sponsor_tiers/_form.html.erb create mode 100644 app/views/sponsor_tiers/_sponsor_tier.json.jbuilder create mode 100644 app/views/sponsor_tiers/edit.html.erb create mode 100644 app/views/sponsor_tiers/index.html.erb create mode 100644 app/views/sponsor_tiers/index.json.jbuilder create mode 100644 app/views/sponsor_tiers/new.html.erb create mode 100644 app/views/sponsor_tiers/show.html.erb create mode 100644 app/views/sponsor_tiers/show.json.jbuilder create mode 100644 db/migrate/20200724093202_create_sponsor_tiers.rb create mode 100644 db/migrate/20200724093530_add_column_to_sponsor_tiers.rb create mode 100644 spec/controllers/sponsor_tiers_controller_spec.rb create mode 100644 spec/helpers/sponsor_tiers_helper_spec.rb create mode 100644 spec/models/sponsor_tier_spec.rb create mode 100644 spec/requests/sponsor_tiers_spec.rb create mode 100644 spec/routing/sponsor_tiers_routing_spec.rb create mode 100644 spec/views/sponsor_tiers/edit.html.erb_spec.rb create mode 100644 spec/views/sponsor_tiers/index.html.erb_spec.rb create mode 100644 spec/views/sponsor_tiers/new.html.erb_spec.rb create mode 100644 spec/views/sponsor_tiers/show.html.erb_spec.rb diff --git a/app/assets/javascripts/sponsor_tiers.js b/app/assets/javascripts/sponsor_tiers.js new file mode 100644 index 00000000..dee720fa --- /dev/null +++ b/app/assets/javascripts/sponsor_tiers.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/sponsor_tiers.scss b/app/assets/stylesheets/sponsor_tiers.scss new file mode 100644 index 00000000..0b4b39a0 --- /dev/null +++ b/app/assets/stylesheets/sponsor_tiers.scss @@ -0,0 +1,3 @@ +// Place all the styles related to the SponsorTiers controller here. +// They will automatically be included in application.css. +// You can use Sass (SCSS) here: http://sass-lang.com/ diff --git a/app/controllers/sponsor_tiers_controller.rb b/app/controllers/sponsor_tiers_controller.rb new file mode 100644 index 00000000..3f1273ab --- /dev/null +++ b/app/controllers/sponsor_tiers_controller.rb @@ -0,0 +1,74 @@ +class SponsorTiersController < ApplicationController + before_action :set_sponsor_tier, only: [:show, :edit, :update, :destroy] + + # GET /sponsor_tiers + # GET /sponsor_tiers.json + def index + @sponsor_tiers = SponsorTier.all + end + + # GET /sponsor_tiers/1 + # GET /sponsor_tiers/1.json + def show + end + + # GET /sponsor_tiers/new + def new + @sponsor_tier = SponsorTier.new + end + + # GET /sponsor_tiers/1/edit + def edit + end + + # POST /sponsor_tiers + # POST /sponsor_tiers.json + def create + @sponsor_tier = SponsorTier.new(sponsor_tier_params) + + respond_to do |format| + if @sponsor_tier.save + format.html { redirect_to @sponsor_tier, notice: 'Sponsor tier was successfully created.' } + format.json { render :show, status: :created, location: @sponsor_tier } + else + format.html { render :new } + format.json { render json: @sponsor_tier.errors, status: :unprocessable_entity } + end + end + end + + # PATCH/PUT /sponsor_tiers/1 + # PATCH/PUT /sponsor_tiers/1.json + def update + respond_to do |format| + if @sponsor_tier.update(sponsor_tier_params) + format.html { redirect_to @sponsor_tier, notice: 'Sponsor tier was successfully updated.' } + format.json { render :show, status: :ok, location: @sponsor_tier } + else + format.html { render :edit } + format.json { render json: @sponsor_tier.errors, status: :unprocessable_entity } + end + end + end + + # DELETE /sponsor_tiers/1 + # DELETE /sponsor_tiers/1.json + def destroy + @sponsor_tier.destroy + respond_to do |format| + format.html { redirect_to sponsor_tiers_url, notice: 'Sponsor tier was successfully destroyed.' } + format.json { head :no_content } + end + end + + private + # Use callbacks to share common setup or constraints between actions. + def set_sponsor_tier + @sponsor_tier = SponsorTier.find(params[:id]) + end + + # Only allow a list of trusted parameters through. + def sponsor_tier_params + params.require(:sponsor_tier).permit(:tier) + end +end diff --git a/app/helpers/sponsor_tiers_helper.rb b/app/helpers/sponsor_tiers_helper.rb new file mode 100644 index 00000000..02b198bd --- /dev/null +++ b/app/helpers/sponsor_tiers_helper.rb @@ -0,0 +1,2 @@ +module SponsorTiersHelper +end diff --git a/app/models/sponsor_tier.rb b/app/models/sponsor_tier.rb new file mode 100644 index 00000000..5cc9ceee --- /dev/null +++ b/app/models/sponsor_tier.rb @@ -0,0 +1,2 @@ +class SponsorTier < ApplicationRecord +end diff --git a/app/views/sponsor_tiers/_form.html.erb b/app/views/sponsor_tiers/_form.html.erb new file mode 100644 index 00000000..1857620d --- /dev/null +++ b/app/views/sponsor_tiers/_form.html.erb @@ -0,0 +1,13 @@ + +<%= simple_form_for(@sponsor_tier) do |f| %> + <%= f.error_notification %> + <%= f.error_notification message: f.object.errors[:base].to_sentence if f.object.errors[:base].present? %> + +

+ <%= f.input :tier %> +
+ +
+ <%= f.button :submit %> +
+<% end %> diff --git a/app/views/sponsor_tiers/_sponsor_tier.json.jbuilder b/app/views/sponsor_tiers/_sponsor_tier.json.jbuilder new file mode 100644 index 00000000..3beeacb0 --- /dev/null +++ b/app/views/sponsor_tiers/_sponsor_tier.json.jbuilder @@ -0,0 +1,2 @@ +json.extract! sponsor_tier, :id, :tier, :created_at, :updated_at +json.url sponsor_tier_url(sponsor_tier, format: :json) diff --git a/app/views/sponsor_tiers/edit.html.erb b/app/views/sponsor_tiers/edit.html.erb new file mode 100644 index 00000000..5800149c --- /dev/null +++ b/app/views/sponsor_tiers/edit.html.erb @@ -0,0 +1,6 @@ +

Editing Sponsor Tier

+ +<%= render 'form', sponsor_tier: @sponsor_tier %> + +<%= link_to 'Show', @sponsor_tier %> | +<%= link_to 'Back', sponsor_tiers_path %> diff --git a/app/views/sponsor_tiers/index.html.erb b/app/views/sponsor_tiers/index.html.erb new file mode 100644 index 00000000..bd0f4113 --- /dev/null +++ b/app/views/sponsor_tiers/index.html.erb @@ -0,0 +1,27 @@ +

<%= notice %>

+ +

Sponsor Tiers

+ + + + + + + + + + + <% @sponsor_tiers.each do |sponsor_tier| %> + + + + + + + <% end %> + +
Tier
<%= sponsor_tier.tier %><%= link_to 'Show', sponsor_tier %><%= link_to 'Edit', edit_sponsor_tier_path(sponsor_tier) %><%= link_to 'Destroy', sponsor_tier, method: :delete, data: { confirm: 'Are you sure?' } %>
+ +
+ +<%= link_to 'New Sponsor Tier', new_sponsor_tier_path %> diff --git a/app/views/sponsor_tiers/index.json.jbuilder b/app/views/sponsor_tiers/index.json.jbuilder new file mode 100644 index 00000000..6a607957 --- /dev/null +++ b/app/views/sponsor_tiers/index.json.jbuilder @@ -0,0 +1 @@ +json.array! @sponsor_tiers, partial: "sponsor_tiers/sponsor_tier", as: :sponsor_tier diff --git a/app/views/sponsor_tiers/new.html.erb b/app/views/sponsor_tiers/new.html.erb new file mode 100644 index 00000000..928ca743 --- /dev/null +++ b/app/views/sponsor_tiers/new.html.erb @@ -0,0 +1,5 @@ +

New Sponsor Tier

+ +<%= render 'form', sponsor_tier: @sponsor_tier %> + +<%= link_to 'Back', sponsor_tiers_path %> diff --git a/app/views/sponsor_tiers/show.html.erb b/app/views/sponsor_tiers/show.html.erb new file mode 100644 index 00000000..ae7a4c1d --- /dev/null +++ b/app/views/sponsor_tiers/show.html.erb @@ -0,0 +1,9 @@ +

<%= notice %>

+ +

+ Tier: + <%= @sponsor_tier.tier %> +

+ +<%= link_to 'Edit', edit_sponsor_tier_path(@sponsor_tier) %> | +<%= link_to 'Back', sponsor_tiers_path %> diff --git a/app/views/sponsor_tiers/show.json.jbuilder b/app/views/sponsor_tiers/show.json.jbuilder new file mode 100644 index 00000000..9244b22f --- /dev/null +++ b/app/views/sponsor_tiers/show.json.jbuilder @@ -0,0 +1 @@ +json.partial! "sponsor_tiers/sponsor_tier", sponsor_tier: @sponsor_tier diff --git a/config/routes.rb b/config/routes.rb index b4faefff..939251c2 100644 --- a/config/routes.rb +++ b/config/routes.rb @@ -1,5 +1,6 @@ Rails.application.routes.draw do + resources :sponsor_tiers resources :sponsorships require 'sidekiq/web' require 'admin_constraint' diff --git a/db/migrate/20200724093202_create_sponsor_tiers.rb b/db/migrate/20200724093202_create_sponsor_tiers.rb new file mode 100644 index 00000000..14317f9a --- /dev/null +++ b/db/migrate/20200724093202_create_sponsor_tiers.rb @@ -0,0 +1,9 @@ +class CreateSponsorTiers < ActiveRecord::Migration[5.2] + def change + create_table :sponsor_tiers do |t| + t.integer :tier + + t.timestamps + end + end +end diff --git a/db/migrate/20200724093530_add_column_to_sponsor_tiers.rb b/db/migrate/20200724093530_add_column_to_sponsor_tiers.rb new file mode 100644 index 00000000..8210315d --- /dev/null +++ b/db/migrate/20200724093530_add_column_to_sponsor_tiers.rb @@ -0,0 +1,6 @@ +class AddColumnToSponsorTiers < ActiveRecord::Migration[5.2] + def change + add_column :sponsor_tiers, :description, :string, default: "" + add_column :sponsor_tiers, :user_id, :integer + end +end diff --git a/spec/controllers/sponsor_tiers_controller_spec.rb b/spec/controllers/sponsor_tiers_controller_spec.rb new file mode 100644 index 00000000..cf7bca64 --- /dev/null +++ b/spec/controllers/sponsor_tiers_controller_spec.rb @@ -0,0 +1,141 @@ +require 'rails_helper' + +# This spec was generated by rspec-rails when you ran the scaffold generator. +# It demonstrates how one might use RSpec to specify the controller code that +# was generated by Rails when you ran the scaffold generator. +# +# It assumes that the implementation code is generated by the rails scaffold +# generator. If you are using any extension libraries to generate different +# controller code, this generated spec may or may not pass. +# +# It only uses APIs available in rails and/or rspec-rails. There are a number +# of tools you can use to make these specs even more expressive, but we're +# sticking to rails and rspec-rails APIs to keep things simple and stable. +# +# Compared to earlier versions of this generator, there is very limited use of +# stubs and message expectations in this spec. Stubs are only used when there +# is no simpler way to get a handle on the object needed for the example. +# Message expectations are only used when there is no simpler way to specify +# that an instance is receiving a specific message. +# +# Also compared to earlier versions of this generator, there are no longer any +# expectations of assigns and templates rendered. These features have been +# removed from Rails core in Rails 5, but can be added back in via the +# `rails-controller-testing` gem. + +RSpec.describe SponsorTiersController, type: :controller do + + # This should return the minimal set of attributes required to create a valid + # SponsorTier. As you add validations to SponsorTier, be sure to + # adjust the attributes here as well. + let(:valid_attributes) { + skip("Add a hash of attributes valid for your model") + } + + let(:invalid_attributes) { + skip("Add a hash of attributes invalid for your model") + } + + # This should return the minimal set of values that should be in the session + # in order to pass any filters (e.g. authentication) defined in + # SponsorTiersController. Be sure to keep this updated too. + let(:valid_session) { {} } + + describe "GET #index" do + it "returns a success response" do + SponsorTier.create! valid_attributes + get :index, params: {}, session: valid_session + expect(response).to be_successful + end + end + + describe "GET #show" do + it "returns a success response" do + sponsor_tier = SponsorTier.create! valid_attributes + get :show, params: {id: sponsor_tier.to_param}, session: valid_session + expect(response).to be_successful + end + end + + describe "GET #new" do + it "returns a success response" do + get :new, params: {}, session: valid_session + expect(response).to be_successful + end + end + + describe "GET #edit" do + it "returns a success response" do + sponsor_tier = SponsorTier.create! valid_attributes + get :edit, params: {id: sponsor_tier.to_param}, session: valid_session + expect(response).to be_successful + end + end + + describe "POST #create" do + context "with valid params" do + it "creates a new SponsorTier" do + expect { + post :create, params: {sponsor_tier: valid_attributes}, session: valid_session + }.to change(SponsorTier, :count).by(1) + end + + it "redirects to the created sponsor_tier" do + post :create, params: {sponsor_tier: valid_attributes}, session: valid_session + expect(response).to redirect_to(SponsorTier.last) + end + end + + context "with invalid params" do + it "returns a success response (i.e. to display the 'new' template)" do + post :create, params: {sponsor_tier: invalid_attributes}, session: valid_session + expect(response).to be_successful + end + end + end + + describe "PUT #update" do + context "with valid params" do + let(:new_attributes) { + skip("Add a hash of attributes valid for your model") + } + + it "updates the requested sponsor_tier" do + sponsor_tier = SponsorTier.create! valid_attributes + put :update, params: {id: sponsor_tier.to_param, sponsor_tier: new_attributes}, session: valid_session + sponsor_tier.reload + skip("Add assertions for updated state") + end + + it "redirects to the sponsor_tier" do + sponsor_tier = SponsorTier.create! valid_attributes + put :update, params: {id: sponsor_tier.to_param, sponsor_tier: valid_attributes}, session: valid_session + expect(response).to redirect_to(sponsor_tier) + end + end + + context "with invalid params" do + it "returns a success response (i.e. to display the 'edit' template)" do + sponsor_tier = SponsorTier.create! valid_attributes + put :update, params: {id: sponsor_tier.to_param, sponsor_tier: invalid_attributes}, session: valid_session + expect(response).to be_successful + end + end + end + + describe "DELETE #destroy" do + it "destroys the requested sponsor_tier" do + sponsor_tier = SponsorTier.create! valid_attributes + expect { + delete :destroy, params: {id: sponsor_tier.to_param}, session: valid_session + }.to change(SponsorTier, :count).by(-1) + end + + it "redirects to the sponsor_tiers list" do + sponsor_tier = SponsorTier.create! valid_attributes + delete :destroy, params: {id: sponsor_tier.to_param}, session: valid_session + expect(response).to redirect_to(sponsor_tiers_url) + end + end + +end diff --git a/spec/helpers/sponsor_tiers_helper_spec.rb b/spec/helpers/sponsor_tiers_helper_spec.rb new file mode 100644 index 00000000..19ce39a7 --- /dev/null +++ b/spec/helpers/sponsor_tiers_helper_spec.rb @@ -0,0 +1,15 @@ +require 'rails_helper' + +# Specs in this file have access to a helper object that includes +# the SponsorTiersHelper. For example: +# +# describe SponsorTiersHelper do +# describe "string concat" do +# it "concats two strings with spaces" do +# expect(helper.concat_strings("this","that")).to eq("this that") +# end +# end +# end +RSpec.describe SponsorTiersHelper, type: :helper do + pending "add some examples to (or delete) #{__FILE__}" +end diff --git a/spec/models/sponsor_tier_spec.rb b/spec/models/sponsor_tier_spec.rb new file mode 100644 index 00000000..3ceab0b6 --- /dev/null +++ b/spec/models/sponsor_tier_spec.rb @@ -0,0 +1,5 @@ +require 'rails_helper' + +RSpec.describe SponsorTier, type: :model do + pending "add some examples to (or delete) #{__FILE__}" +end diff --git a/spec/requests/sponsor_tiers_spec.rb b/spec/requests/sponsor_tiers_spec.rb new file mode 100644 index 00000000..55ea2a06 --- /dev/null +++ b/spec/requests/sponsor_tiers_spec.rb @@ -0,0 +1,10 @@ +require 'rails_helper' + +RSpec.describe "SponsorTiers", type: :request do + describe "GET /sponsor_tiers" do + it "works! (now write some real specs)" do + get sponsor_tiers_path + expect(response).to have_http_status(200) + end + end +end diff --git a/spec/routing/sponsor_tiers_routing_spec.rb b/spec/routing/sponsor_tiers_routing_spec.rb new file mode 100644 index 00000000..f2c95b1e --- /dev/null +++ b/spec/routing/sponsor_tiers_routing_spec.rb @@ -0,0 +1,38 @@ +require "rails_helper" + +RSpec.describe SponsorTiersController, type: :routing do + describe "routing" do + it "routes to #index" do + expect(:get => "/sponsor_tiers").to route_to("sponsor_tiers#index") + end + + it "routes to #new" do + expect(:get => "/sponsor_tiers/new").to route_to("sponsor_tiers#new") + end + + it "routes to #show" do + expect(:get => "/sponsor_tiers/1").to route_to("sponsor_tiers#show", :id => "1") + end + + it "routes to #edit" do + expect(:get => "/sponsor_tiers/1/edit").to route_to("sponsor_tiers#edit", :id => "1") + end + + + it "routes to #create" do + expect(:post => "/sponsor_tiers").to route_to("sponsor_tiers#create") + end + + it "routes to #update via PUT" do + expect(:put => "/sponsor_tiers/1").to route_to("sponsor_tiers#update", :id => "1") + end + + it "routes to #update via PATCH" do + expect(:patch => "/sponsor_tiers/1").to route_to("sponsor_tiers#update", :id => "1") + end + + it "routes to #destroy" do + expect(:delete => "/sponsor_tiers/1").to route_to("sponsor_tiers#destroy", :id => "1") + end + end +end diff --git a/spec/views/sponsor_tiers/edit.html.erb_spec.rb b/spec/views/sponsor_tiers/edit.html.erb_spec.rb new file mode 100644 index 00000000..dc11f60a --- /dev/null +++ b/spec/views/sponsor_tiers/edit.html.erb_spec.rb @@ -0,0 +1,18 @@ +require 'rails_helper' + +RSpec.describe "sponsor_tiers/edit", type: :view do + before(:each) do + @sponsor_tier = assign(:sponsor_tier, SponsorTier.create!( + :tier => 1 + )) + end + + it "renders the edit sponsor_tier form" do + render + + assert_select "form[action=?][method=?]", sponsor_tier_path(@sponsor_tier), "post" do + + assert_select "input[name=?]", "sponsor_tier[tier]" + end + end +end diff --git a/spec/views/sponsor_tiers/index.html.erb_spec.rb b/spec/views/sponsor_tiers/index.html.erb_spec.rb new file mode 100644 index 00000000..56706612 --- /dev/null +++ b/spec/views/sponsor_tiers/index.html.erb_spec.rb @@ -0,0 +1,19 @@ +require 'rails_helper' + +RSpec.describe "sponsor_tiers/index", type: :view do + before(:each) do + assign(:sponsor_tiers, [ + SponsorTier.create!( + :tier => 2 + ), + SponsorTier.create!( + :tier => 2 + ) + ]) + end + + it "renders a list of sponsor_tiers" do + render + assert_select "tr>td", :text => 2.to_s, :count => 2 + end +end diff --git a/spec/views/sponsor_tiers/new.html.erb_spec.rb b/spec/views/sponsor_tiers/new.html.erb_spec.rb new file mode 100644 index 00000000..24ae0a5e --- /dev/null +++ b/spec/views/sponsor_tiers/new.html.erb_spec.rb @@ -0,0 +1,18 @@ +require 'rails_helper' + +RSpec.describe "sponsor_tiers/new", type: :view do + before(:each) do + assign(:sponsor_tier, SponsorTier.new( + :tier => 1 + )) + end + + it "renders new sponsor_tier form" do + render + + assert_select "form[action=?][method=?]", sponsor_tiers_path, "post" do + + assert_select "input[name=?]", "sponsor_tier[tier]" + end + end +end diff --git a/spec/views/sponsor_tiers/show.html.erb_spec.rb b/spec/views/sponsor_tiers/show.html.erb_spec.rb new file mode 100644 index 00000000..488e7c21 --- /dev/null +++ b/spec/views/sponsor_tiers/show.html.erb_spec.rb @@ -0,0 +1,14 @@ +require 'rails_helper' + +RSpec.describe "sponsor_tiers/show", type: :view do + before(:each) do + @sponsor_tier = assign(:sponsor_tier, SponsorTier.create!( + :tier => 2 + )) + end + + it "renders attributes in

" do + render + expect(rendered).to match(/2/) + end +end From 46b906d2acec4bacf45cd221925e665c703e8139 Mon Sep 17 00:00:00 2001 From: wyx <414722560@qq.com> Date: Fri, 24 Jul 2020 17:40:58 +0800 Subject: [PATCH 04/16] create stoppedsponsorship --- app/models/stopped_sponsorship.rb | 2 ++ .../20200724094030_create_stopped_sponsorships.rb | 11 +++++++++++ spec/models/stopped_sponsorship_spec.rb | 5 +++++ 3 files changed, 18 insertions(+) create mode 100644 app/models/stopped_sponsorship.rb create mode 100644 db/migrate/20200724094030_create_stopped_sponsorships.rb create mode 100644 spec/models/stopped_sponsorship_spec.rb diff --git a/app/models/stopped_sponsorship.rb b/app/models/stopped_sponsorship.rb new file mode 100644 index 00000000..0290fb77 --- /dev/null +++ b/app/models/stopped_sponsorship.rb @@ -0,0 +1,2 @@ +class StoppedSponsorship < ApplicationRecord +end diff --git a/db/migrate/20200724094030_create_stopped_sponsorships.rb b/db/migrate/20200724094030_create_stopped_sponsorships.rb new file mode 100644 index 00000000..b639dc4b --- /dev/null +++ b/db/migrate/20200724094030_create_stopped_sponsorships.rb @@ -0,0 +1,11 @@ +class CreateStoppedSponsorships < ActiveRecord::Migration[5.2] + def change + create_table :stopped_sponsorships do |t| + t.integer :amount + t.integer :sponsor_id + t.integer :developer_id + + t.timestamps + end + end +end diff --git a/spec/models/stopped_sponsorship_spec.rb b/spec/models/stopped_sponsorship_spec.rb new file mode 100644 index 00000000..3e4503dd --- /dev/null +++ b/spec/models/stopped_sponsorship_spec.rb @@ -0,0 +1,5 @@ +require 'rails_helper' + +RSpec.describe StoppedSponsorship, type: :model do + pending "add some examples to (or delete) #{__FILE__}" +end From 33951af37dfe6ee759d44c06a2b7327e9034880a Mon Sep 17 00:00:00 2001 From: wyx <414722560@qq.com> Date: Fri, 24 Jul 2020 17:45:29 +0800 Subject: [PATCH 05/16] create table wallet --- app/models/wallet.rb | 2 ++ db/migrate/20200724094458_create_wallets.rb | 10 ++++++++++ spec/models/wallet_spec.rb | 5 +++++ 3 files changed, 17 insertions(+) create mode 100644 app/models/wallet.rb create mode 100644 db/migrate/20200724094458_create_wallets.rb create mode 100644 spec/models/wallet_spec.rb diff --git a/app/models/wallet.rb b/app/models/wallet.rb new file mode 100644 index 00000000..987db9e8 --- /dev/null +++ b/app/models/wallet.rb @@ -0,0 +1,2 @@ +class Wallet < ApplicationRecord +end diff --git a/db/migrate/20200724094458_create_wallets.rb b/db/migrate/20200724094458_create_wallets.rb new file mode 100644 index 00000000..eab5a06d --- /dev/null +++ b/db/migrate/20200724094458_create_wallets.rb @@ -0,0 +1,10 @@ +class CreateWallets < ActiveRecord::Migration[5.2] + def change + create_table :wallets do |t| + t.integer :balance + t.integer :user_id + + t.timestamps + end + end +end diff --git a/spec/models/wallet_spec.rb b/spec/models/wallet_spec.rb new file mode 100644 index 00000000..768de3cd --- /dev/null +++ b/spec/models/wallet_spec.rb @@ -0,0 +1,5 @@ +require 'rails_helper' + +RSpec.describe Wallet, type: :model do + pending "add some examples to (or delete) #{__FILE__}" +end From 98176f839d221ce6b5e114d57a4de9ec8fe09cf0 Mon Sep 17 00:00:00 2001 From: wyx <414722560@qq.com> Date: Fri, 24 Jul 2020 17:49:07 +0800 Subject: [PATCH 06/16] create coinchange --- app/models/coin_change.rb | 2 ++ db/migrate/20200724094729_create_coin_changes.rb | 13 +++++++++++++ spec/models/coin_change_spec.rb | 5 +++++ 3 files changed, 20 insertions(+) create mode 100644 app/models/coin_change.rb create mode 100644 db/migrate/20200724094729_create_coin_changes.rb create mode 100644 spec/models/coin_change_spec.rb diff --git a/app/models/coin_change.rb b/app/models/coin_change.rb new file mode 100644 index 00000000..9722a133 --- /dev/null +++ b/app/models/coin_change.rb @@ -0,0 +1,2 @@ +class CoinChange < ApplicationRecord +end diff --git a/db/migrate/20200724094729_create_coin_changes.rb b/db/migrate/20200724094729_create_coin_changes.rb new file mode 100644 index 00000000..6999312b --- /dev/null +++ b/db/migrate/20200724094729_create_coin_changes.rb @@ -0,0 +1,13 @@ +class CreateCoinChanges < ActiveRecord::Migration[5.2] + def change + create_table :coin_changes do |t| + t.integer :amount + t.string :description + t.string :reason + t.integer :to_wallet_id + t.integer :from_wallet_id + + t.timestamps + end + end +end diff --git a/spec/models/coin_change_spec.rb b/spec/models/coin_change_spec.rb new file mode 100644 index 00000000..313ecf1f --- /dev/null +++ b/spec/models/coin_change_spec.rb @@ -0,0 +1,5 @@ +require 'rails_helper' + +RSpec.describe CoinChange, type: :model do + pending "add some examples to (or delete) #{__FILE__}" +end From 94ad4ce56c6d224881d93ee83fd706adeadf7f09 Mon Sep 17 00:00:00 2001 From: wyx <414722560@qq.com> Date: Fri, 24 Jul 2020 17:50:25 +0800 Subject: [PATCH 07/16] create waitlist --- app/models/waitlist.rb | 2 ++ db/migrate/20200724095001_create_waitlists.rb | 10 ++++++++++ spec/models/waitlist_spec.rb | 5 +++++ 3 files changed, 17 insertions(+) create mode 100644 app/models/waitlist.rb create mode 100644 db/migrate/20200724095001_create_waitlists.rb create mode 100644 spec/models/waitlist_spec.rb diff --git a/app/models/waitlist.rb b/app/models/waitlist.rb new file mode 100644 index 00000000..4bafef80 --- /dev/null +++ b/app/models/waitlist.rb @@ -0,0 +1,2 @@ +class Waitlist < ApplicationRecord +end diff --git a/db/migrate/20200724095001_create_waitlists.rb b/db/migrate/20200724095001_create_waitlists.rb new file mode 100644 index 00000000..d0df8a23 --- /dev/null +++ b/db/migrate/20200724095001_create_waitlists.rb @@ -0,0 +1,10 @@ +class CreateWaitlists < ActiveRecord::Migration[5.2] + def change + create_table :waitlists do |t| + t.integer :applicant_id + t.integer :reviewer_id + + t.timestamps + end + end +end diff --git a/spec/models/waitlist_spec.rb b/spec/models/waitlist_spec.rb new file mode 100644 index 00000000..1b8f43be --- /dev/null +++ b/spec/models/waitlist_spec.rb @@ -0,0 +1,5 @@ +require 'rails_helper' + +RSpec.describe Waitlist, type: :model do + pending "add some examples to (or delete) #{__FILE__}" +end From 769bf2b90eeab74e3ff8ea12820df8be232f391a Mon Sep 17 00:00:00 2001 From: wyx <414722560@qq.com> Date: Fri, 24 Jul 2020 17:51:14 +0800 Subject: [PATCH 08/16] create passedlist --- app/models/passed_waitlist.rb | 2 ++ db/migrate/20200724095057_create_passed_waitlists.rb | 12 ++++++++++++ spec/models/passed_waitlist_spec.rb | 5 +++++ 3 files changed, 19 insertions(+) create mode 100644 app/models/passed_waitlist.rb create mode 100644 db/migrate/20200724095057_create_passed_waitlists.rb create mode 100644 spec/models/passed_waitlist_spec.rb diff --git a/app/models/passed_waitlist.rb b/app/models/passed_waitlist.rb new file mode 100644 index 00000000..90cfb57a --- /dev/null +++ b/app/models/passed_waitlist.rb @@ -0,0 +1,2 @@ +class PassedWaitlist < ApplicationRecord +end diff --git a/db/migrate/20200724095057_create_passed_waitlists.rb b/db/migrate/20200724095057_create_passed_waitlists.rb new file mode 100644 index 00000000..6d8b4b81 --- /dev/null +++ b/db/migrate/20200724095057_create_passed_waitlists.rb @@ -0,0 +1,12 @@ +class CreatePassedWaitlists < ActiveRecord::Migration[5.2] + def change + create_table :passed_waitlists do |t| + t.string :applicant_id + t.string :integer + t.string :reviewer_id + t.string :integer + + t.timestamps + end + end +end diff --git a/spec/models/passed_waitlist_spec.rb b/spec/models/passed_waitlist_spec.rb new file mode 100644 index 00000000..5124c945 --- /dev/null +++ b/spec/models/passed_waitlist_spec.rb @@ -0,0 +1,5 @@ +require 'rails_helper' + +RSpec.describe PassedWaitlist, type: :model do + pending "add some examples to (or delete) #{__FILE__}" +end From c546eda5371698a34ecc882db36966a75277fbf7 Mon Sep 17 00:00:00 2001 From: wyx <414722560@qq.com> Date: Sat, 25 Jul 2020 10:57:45 +0800 Subject: [PATCH 09/16] update table waitlist and passed_waitlist --- app/models/user.rb | 9 +++++++++ ...e_waitlists.rb => 20200725025555_create_waitlists.rb} | 6 ++++-- ...ists.rb => 20200725025657_create_passed_waitlists.rb} | 0 3 files changed, 13 insertions(+), 2 deletions(-) rename db/migrate/{20200724095001_create_waitlists.rb => 20200725025555_create_waitlists.rb} (56%) rename db/migrate/{20200724095057_create_passed_waitlists.rb => 20200725025657_create_passed_waitlists.rb} (100%) diff --git a/app/models/user.rb b/app/models/user.rb index f919ed1b..e7b2cbc1 100644 --- a/app/models/user.rb +++ b/app/models/user.rb @@ -92,6 +92,15 @@ class User < ApplicationRecord # has_many :libraries, dependent: :destroy has_many :project_trends, dependent: :destroy + # sponsor + has_many :as_sponsors, class_name: 'Sponsorship', foreign_key: 'sponsor_id', dependent: :destroy + has_many :as_sponsored, class_name: 'Sponsorship', foreign_key: 'developer_id', dependent: :destroy + has_many :stopped_sponsors, class_name: 'StoppedSponsorship', foreign_key: 'sponsor_id', dependent: :destroy + has_many :stopped_sponsored, class_name: 'StoppedSponsorship', foreign_key: 'developer_id', dependent: :destroy + has_many :sponsor_tier, dependent: :destroy + has_one :wallet, dependent: :destroy + # has_many :waitlist + # Groups and active users scope :active, lambda { where(status: STATUS_ACTIVE) } scope :like, lambda { |keywords| diff --git a/db/migrate/20200724095001_create_waitlists.rb b/db/migrate/20200725025555_create_waitlists.rb similarity index 56% rename from db/migrate/20200724095001_create_waitlists.rb rename to db/migrate/20200725025555_create_waitlists.rb index d0df8a23..701006e9 100644 --- a/db/migrate/20200724095001_create_waitlists.rb +++ b/db/migrate/20200725025555_create_waitlists.rb @@ -1,8 +1,10 @@ class CreateWaitlists < ActiveRecord::Migration[5.2] def change create_table :waitlists do |t| - t.integer :applicant_id - t.integer :reviewer_id + t.string :applicant_id + t.string :integer + t.string :reviewer_id + t.string :integer t.timestamps end diff --git a/db/migrate/20200724095057_create_passed_waitlists.rb b/db/migrate/20200725025657_create_passed_waitlists.rb similarity index 100% rename from db/migrate/20200724095057_create_passed_waitlists.rb rename to db/migrate/20200725025657_create_passed_waitlists.rb From 9915c10bcfbd12e849813d52937d5ec9805790d8 Mon Sep 17 00:00:00 2001 From: wyx <414722560@qq.com> Date: Sat, 25 Jul 2020 11:21:44 +0800 Subject: [PATCH 10/16] update model user --- app/models/user.rb | 6 +++++- 1 file changed, 5 insertions(+), 1 deletion(-) diff --git a/app/models/user.rb b/app/models/user.rb index e7b2cbc1..0ad5f541 100644 --- a/app/models/user.rb +++ b/app/models/user.rb @@ -99,7 +99,11 @@ class User < ApplicationRecord has_many :stopped_sponsored, class_name: 'StoppedSponsorship', foreign_key: 'developer_id', dependent: :destroy has_many :sponsor_tier, dependent: :destroy has_one :wallet, dependent: :destroy - # has_many :waitlist + has_many :waitlist, class_name: 'Waitlist', foreign_key: 'reviewer_id', optional: true + has_many :passed_waitlist, class_name: 'PassedWaitlist', foreign_key: 'reviewer_id', optional: true #as reviewer + has_one :application, class_name: 'Waitlist', foreign_key: 'applicant_id', optional: true + has_one :passed_application, class_name: 'PassedWaitlist', foreign_key: 'applicant_id', optional: true + # Groups and active users scope :active, lambda { where(status: STATUS_ACTIVE) } From 50bef66261cccabd0e4d2a460165cf412610506e Mon Sep 17 00:00:00 2001 From: wyx <414722560@qq.com> Date: Sat, 25 Jul 2020 11:22:53 +0800 Subject: [PATCH 11/16] update model sponsor_tier --- app/models/sponsor_tier.rb | 1 + 1 file changed, 1 insertion(+) diff --git a/app/models/sponsor_tier.rb b/app/models/sponsor_tier.rb index 5cc9ceee..20aed963 100644 --- a/app/models/sponsor_tier.rb +++ b/app/models/sponsor_tier.rb @@ -1,2 +1,3 @@ class SponsorTier < ApplicationRecord + belongs_to :user end From d480deee6460640e1d6b011eaeca625bc425c22f Mon Sep 17 00:00:00 2001 From: wyx <414722560@qq.com> Date: Sat, 25 Jul 2020 11:23:57 +0800 Subject: [PATCH 12/16] update model stopped_sponsorship --- app/models/stopped_sponsorship.rb | 3 +++ 1 file changed, 3 insertions(+) diff --git a/app/models/stopped_sponsorship.rb b/app/models/stopped_sponsorship.rb index 0290fb77..b73ba273 100644 --- a/app/models/stopped_sponsorship.rb +++ b/app/models/stopped_sponsorship.rb @@ -1,2 +1,5 @@ class StoppedSponsorship < ApplicationRecord + belongs_to :sponsor, class_name: 'User' + belongs_to :developer, class_name: 'User' + validates :amount, presence: true end From 0f692554226e77f03f841d8d75f12bd34703a52b Mon Sep 17 00:00:00 2001 From: wyx <414722560@qq.com> Date: Sat, 25 Jul 2020 12:12:34 +0800 Subject: [PATCH 13/16] update model wallet --- app/models/wallet.rb | 4 ++++ 1 file changed, 4 insertions(+) diff --git a/app/models/wallet.rb b/app/models/wallet.rb index 987db9e8..e7e78671 100644 --- a/app/models/wallet.rb +++ b/app/models/wallet.rb @@ -1,2 +1,6 @@ class Wallet < ApplicationRecord + belongs_to :user + has_many :outcome, class_name: 'CoinChange', foreign_key: 'from_wallet_id', dependent: :destroy + has_many :income, class_name: 'CoinChange', foreign_key: 'to_wallet_id', dependent: :destroy + validates :balance, presence: true end From 0ebcf3d7f7224a28d4eb887e6efe516c5cbf38b0 Mon Sep 17 00:00:00 2001 From: wyx <414722560@qq.com> Date: Sat, 25 Jul 2020 12:17:46 +0800 Subject: [PATCH 14/16] update model coin_change --- app/models/coin_change.rb | 3 +++ 1 file changed, 3 insertions(+) diff --git a/app/models/coin_change.rb b/app/models/coin_change.rb index 9722a133..f5e066fb 100644 --- a/app/models/coin_change.rb +++ b/app/models/coin_change.rb @@ -1,2 +1,5 @@ class CoinChange < ApplicationRecord + belongs_to :to_wallet, class_name: 'Wallet' + belongs_to :from_wallet, class_name: 'Wallet' + validates :amount, presence: true end From 80d6cbf823834088a5774fa859153abd51cefec4 Mon Sep 17 00:00:00 2001 From: wyx <414722560@qq.com> Date: Sat, 25 Jul 2020 12:18:49 +0800 Subject: [PATCH 15/16] update model waitlist --- app/models/waitlist.rb | 2 ++ 1 file changed, 2 insertions(+) diff --git a/app/models/waitlist.rb b/app/models/waitlist.rb index 4bafef80..0c058eb7 100644 --- a/app/models/waitlist.rb +++ b/app/models/waitlist.rb @@ -1,2 +1,4 @@ class Waitlist < ApplicationRecord + belongs_to :applicant, class_name: 'User' + belongs_to :reviewer, class_name: 'User', optional: true end From 1c45b48063d1ad8528c12ac01a462f6b19425826 Mon Sep 17 00:00:00 2001 From: wyx <414722560@qq.com> Date: Sat, 25 Jul 2020 12:19:16 +0800 Subject: [PATCH 16/16] update model passed_waitlist --- app/models/passed_waitlist.rb | 2 ++ 1 file changed, 2 insertions(+) diff --git a/app/models/passed_waitlist.rb b/app/models/passed_waitlist.rb index 90cfb57a..a658cb7d 100644 --- a/app/models/passed_waitlist.rb +++ b/app/models/passed_waitlist.rb @@ -1,2 +1,4 @@ class PassedWaitlist < ApplicationRecord + belongs_to :applicant, class_name: 'User' + belongs_to :reviewer, class_name: 'User' end