diff --git a/app/controllers/api/v1/base_controller.rb b/app/controllers/api/v1/base_controller.rb index b937d798e..bcb0c4e86 100644 --- a/app/controllers/api/v1/base_controller.rb +++ b/app/controllers/api/v1/base_controller.rb @@ -20,10 +20,19 @@ class Api::V1::BaseController < ApplicationController # User.find(doorkeeper_token.resource_owner_id) if doorkeeper_token # end # end + + def kaminary_select_paginate(relation) + limit = params[:limit] || params[:per_page] + limit = (limit.to_i.zero? || limit.to_i > 200) ? 200 : limit.to_i + page = params[:page].to_i.zero? ? 1 : params[:page].to_i + + relation.page(page).per(limit) + end def limit params.fetch(:limit, 15) end + def page params.fetch(:page, 1) end @@ -43,7 +52,6 @@ class Api::V1::BaseController < ApplicationController # 具有仓库的操作权限或者fork仓库的操作权限 def require_operate_above_or_fork_project @project = load_project - puts !current_user.admin? && !@project.operator?(current_user) && !(@project.fork_project.present? && @project.fork_project.operator?(current_user)) return render_forbidden if !current_user.admin? && !@project.operator?(current_user) && !(@project.fork_project.present? && @project.fork_project.operator?(current_user)) end diff --git a/app/controllers/api/v1/issues/assigners_controller.rb b/app/controllers/api/v1/issues/assigners_controller.rb new file mode 100644 index 000000000..84476138f --- /dev/null +++ b/app/controllers/api/v1/issues/assigners_controller.rb @@ -0,0 +1,12 @@ +class Api::V1::Issues::AssignersController < Api::V1::BaseController + + before_action :require_public_and_member_above, only: [:index] + + # 负责人列表 + def index + @assigners = User.joins(assigned_issues: :project).where(projects: {id: @project&.id}) + @assigners = @assigners.order("users.id=#{current_user.id} desc").distinct + @assigners = @assigners.ransack(login_or_nickname_cont: params[:keyword]).result if params[:keyword].present? + @assigners = kaminary_select_paginate(@assigners) + end +end \ No newline at end of file diff --git a/app/controllers/api/v1/issues/authors_controller.rb b/app/controllers/api/v1/issues/authors_controller.rb new file mode 100644 index 000000000..d0242a517 --- /dev/null +++ b/app/controllers/api/v1/issues/authors_controller.rb @@ -0,0 +1,11 @@ +class Api::V1::Issues::AuthorsController < Api::V1::BaseController + before_action :require_public_and_member_above, only: [:index] + + # 发布人列表 + def index + @authors = User.joins(issues: :project).where(projects: {id: @project&.id}) + @authors = @authors.order("users.id=#{current_user.id} desc").distinct + @authors = @authors.ransack(login_or_nickname_cont: params[:keyword]).result if params[:keyword].present? + @authors = kaminary_select_paginate(@authors) + end +end \ No newline at end of file diff --git a/app/controllers/api/v1/issues/issue_priorities_controller.rb b/app/controllers/api/v1/issues/issue_priorities_controller.rb new file mode 100644 index 000000000..319994a28 --- /dev/null +++ b/app/controllers/api/v1/issues/issue_priorities_controller.rb @@ -0,0 +1,10 @@ +class Api::V1::Issues::IssuePrioritiesController < Api::V1::BaseController + + before_action :require_public_and_member_above, only: [:index] + + def index + @priorities = IssuePriority.order(position: :asc) + @priorities = @priorities.ransack(name_cont: params[:keyword]).result if params[:keyword] + @priorities = kaminary_select_paginate(@priorities) + end +end \ No newline at end of file diff --git a/app/controllers/api/v1/issues/issue_tags_controller.rb b/app/controllers/api/v1/issues/issue_tags_controller.rb new file mode 100644 index 000000000..fe2ecceab --- /dev/null +++ b/app/controllers/api/v1/issues/issue_tags_controller.rb @@ -0,0 +1,65 @@ +class Api::V1::Issues::IssueTagsController < Api::V1::BaseController + before_action :require_login, except: [:index] + before_action :require_public_and_member_above, only: [:index] + before_action :require_operate_above, only: [:create, :update, :destroy] + + def index + @issue_tags = @project.issue_tags.reorder("#{sort_by} #{sort_direction}") + @issue_tags = @issue_tags.ransack(name_cont: params[:keyword]).result if params[:keyword].present? + if params[:only_name] + @issue_tags = kaminary_select_paginate(@issue_tags.select(:id, :name, :color)) + else + @issue_tags = kaminari_paginate(@issue_tags.includes(:project, :user, :issue_issues, :pull_request_issues)) + end + end + + def create + @issue_tag = @project.issue_tags.new(issue_tag_params) + if @issue_tag.save! + render_ok + else + render_error("创建标记失败!") + end + end + + before_action :load_issue_tag, only: [:update, :destroy] + + def update + @issue_tag.attributes = issue_tag_params + if @issue_tag.save! + render_ok + else + render_error("更新标记失败!") + end + end + + def destroy + if @issue_tag.destroy! + render_ok + else + render_error("删除标记失败!") + end + end + + + private + def sort_by + sort_by = params.fetch(:sort_by, "created_at") + sort_by = IssueTag.column_names.include?(sort_by) ? sort_by : "created_at" + sort_by + end + + def sort_direction + sort_direction = params.fetch(:sort_direction, "desc").downcase + sort_direction = %w(desc asc).include?(sort_direction) ? sort_direction : "desc" + sort_direction + end + + def issue_tag_params + params.permit(:name, :description, :color) + end + + def load_issue_tag + @issue_tag = @project.issue_tags.find_by_id(params[:id]) + end +end \ No newline at end of file diff --git a/app/controllers/api/v1/issues/journals_controller.rb b/app/controllers/api/v1/issues/journals_controller.rb new file mode 100644 index 000000000..cee2b81e8 --- /dev/null +++ b/app/controllers/api/v1/issues/journals_controller.rb @@ -0,0 +1,63 @@ +class Api::V1::Issues::JournalsController < Api::V1::BaseController + before_action :require_login, except: [:index, :children_journals] + before_action :require_public_and_member_above + before_action :load_issue + before_action :load_journal, only: [:children_journals, :update, :destroy] + before_action :check_journal_operate_permission, only: [:update, :destroy] + + def index + @object_result = Api::V1::Issues::Journals::ListService.call(@issue, query_params, current_user) + @total_journals_count = @object_result[:total_journals_count] + @total_operate_journals_count = @object_result[:total_operate_journals_count] + @total_comment_journals_count = @object_result[:total_comment_journals_count] + @journals = kaminary_select_paginate(@object_result[:data]) + end + + def create + @object_result = Api::V1::Issues::Journals::CreateService.call(@issue, journal_params, current_user) + end + + def children_journals + @object_results = Api::V1::Issues::Journals::ChildrenListService.call(@issue, @journal, query_params, current_user) + @journals = kaminari_paginate(@object_results) + end + + def update + @object_result = Api::V1::Issues::Journals::UpdateService.call(@issue, @journal, journal_params, current_user) + end + + def destroy + if @journal.destroy! + render_ok + else + render_error("删除评论失败!") + end + end + + private + + def query_params + params.permit(:category, :keyword, :sort_by, :sort_direction) + end + + def journal_params + params.permit(:notes, :parent_id, :reply_id, :attachment_ids => [], :receivers_login => []) + end + + def load_issue + @issue = @project.issues.issue_issue.where(project_issues_index: params[:index]).where.not(id: params[:index]).take || Issue.find_by_id(params[:index]) + if @issue.blank? + render_not_found("疑修不存在!") + end + end + + def load_journal + @journal = Journal.find_by_id(params[:id]) + return render_not_found("评论不存在!") unless @journal.present? + end + + def check_journal_operate_permission + return render_forbidden("您没有操作权限!") unless @project.member?(current_user) || current_user.admin? || @issue.user == current_user || @journal.user == current_user || @journal.parent_journal&.user == current_user + end + +end \ No newline at end of file diff --git a/app/controllers/api/v1/issues/milestones_controller.rb b/app/controllers/api/v1/issues/milestones_controller.rb new file mode 100644 index 000000000..003a464dc --- /dev/null +++ b/app/controllers/api/v1/issues/milestones_controller.rb @@ -0,0 +1,87 @@ +class Api::V1::Issues::MilestonesController < Api::V1::BaseController + before_action :require_login, except: [:index, :show] + before_action :require_public_and_member_above, only: [:index, :show] + before_action :require_operate_above, only: [:create, :update, :destroy] + before_action :load_milestone, only: [:show, :update, :destroy] + + # 里程碑列表 + def index + @milestones = @project.versions + @milestones = @milestones.ransack(id_eq: params[:keyword]).result.or(@milestones.ransack(name_or_description_cont: params[:keyword]).result) if params[:keyword].present? + @closed_milestone_count = @milestones.closed.size + @opening_milestone_count = @milestones.opening.size + @milestones = params[:category] == "closed" ? @milestones.closed : @milestones.opening + @milestones = @milestones.reorder("versions.#{sort_by} #{sort_direction}") + if params[:only_name] + @milestones = @milestones.select(:id, :name) + @milestones = kaminary_select_paginate(@milestones) + else + @milestones = @milestones.includes(:issues, :closed_issues, :opened_issues) + @milestones = kaminari_paginate(@milestones) + end + end + + def create + @milestone = @project.versions.new(milestone_params) + if @milestone.save! + render_ok + else + render_error(@milestone.errors.full_messages.join(",")) + end + end + + # 里程碑详情 + def show + @object_result = Api::V1::Issues::Milestones::DetailIssuesService.call(@project, @milestone, query_params, current_user) + @total_issues_count = @object_result[:total_issues_count] + @opened_issues_count = @object_result[:opened_issues_count] + @closed_issues_count = @object_result[:closed_issues_count] + + @issues = kaminari_paginate(@object_result[:data]) + end + + def update + @milestone.attributes = milestone_params + if @milestone.save! + render_ok + else + render_error(@milestone.errors.full_messages.join(",")) + end + end + + def destroy + if @milestone.destroy! + render_ok + else + render_error("删除里程碑失败!") + end + end + + private + def milestone_params + params.permit(:name, :description, :effective_date) + end + + def query_params + params.permit(:category, :author_id, :assigner_id, :sort_by, :sort_direction, :issue_tag_ids) + end + + def load_milestone + @milestone = @project.versions.find_by_id(params[:id]) + return render_not_found('里程碑不存在!') unless @milestone.present? + end + + def sort_by + sort_by = params.fetch(:sort_by, "created_on") + sort_by = Version.column_names.include?(sort_by) ? sort_by : "created_on" + + sort_by + end + + def sort_direction + sort_direction = params.fetch(:sort_direction, "desc").downcase + sort_direction = %w(desc asc).include?(sort_direction) ? sort_direction : "desc" + sort_direction + end + +end \ No newline at end of file diff --git a/app/controllers/api/v1/issues/statues_controller.rb b/app/controllers/api/v1/issues/statues_controller.rb new file mode 100644 index 000000000..5a7fbc338 --- /dev/null +++ b/app/controllers/api/v1/issues/statues_controller.rb @@ -0,0 +1,11 @@ +class Api::V1::Issues::StatuesController < Api::V1::BaseController + + before_action :require_public_and_member_above, only: [:index] + + # 状态列表 + def index + @statues = IssueStatus.order("position asc") + @statues = @statues.ransack(name_cont: params[:keyword]).result if params[:keyword].present? + @statues = kaminary_select_paginate(@statues) + end +end \ No newline at end of file diff --git a/app/controllers/api/v1/issues_controller.rb b/app/controllers/api/v1/issues_controller.rb new file mode 100644 index 000000000..d07807202 --- /dev/null +++ b/app/controllers/api/v1/issues_controller.rb @@ -0,0 +1,116 @@ +class Api::V1::IssuesController < Api::V1::BaseController + before_action :require_login, except: [:index, :show] + before_action :require_public_and_member_above, only: [:index, :show, :create, :update, :destroy] + before_action :require_operate_above, only: [:batch_update, :batch_destroy] + + def index + IssueTag.init_data(@project.id) unless $redis_cache.hget("project_init_issue_tags", @project.id) + @object_result = Api::V1::Issues::ListService.call(@project, query_params, current_user) + @total_issues_count = @object_result[:total_issues_count] + @opened_issues_count = @object_result[:opened_issues_count] + @closed_issues_count = @object_result[:closed_issues_count] + if params[:only_name].present? + @issues = kaminary_select_paginate(@object_result[:data]) + else + @issues = kaminari_paginate(@object_result[:data]) + end + end + + def create + @object_result = Api::V1::Issues::CreateService.call(@project, issue_params, current_user) + end + + before_action :load_issue, only: [:show, :update, :destroy] + before_action :check_issue_operate_permission, only: [:update, :destroy] + + def show + @user_permission = current_user.present? && current_user.logged? && (@project.member?(current_user) || current_user.admin? || @issue.user == current_user) + end + + def update + @object_result = Api::V1::Issues::UpdateService.call(@project, @issue, issue_params, current_user) + end + + def destroy + @object_result = Api::V1::Issues::DeleteService.call(@project, @issue, current_user) + if @object_result + render_ok + else + render_error("删除疑修失败!") + end + end + + before_action :load_issues, only: [:batch_update, :batch_destroy] + + def batch_update + @object_result = Api::V1::Issues::BatchUpdateService.call(@project, @issues, batch_issue_params, current_user) + if @object_result + render_ok + else + render_error("批量更新疑修失败!") + end + end + + def batch_destroy + @object_result = Api::V1::Issues::BatchDeleteService.call(@project, @issues, current_user) + if @object_result + render_ok + else + render_error("批量删除疑修失败!") + end + end + + private + + def load_issue + @issue = @project.issues.issue_issue.where(project_issues_index: params[:index]).where.not(id: params[:index]).take || Issue.find_by_id(params[:index]) + if @issue.blank? + render_not_found("疑修不存在!") + end + end + + def load_issues + return render_error("请输入正确的ID数组!") unless params[:ids].is_a?(Array) + params[:ids].each do |id| + @issue = Issue.find_by_id(id) + if @issue.blank? + return render_not_found("ID为#{id}的疑修不存在!") + end + end + @issues = Issue.where(id: params[:ids]) + end + + def check_issue_operate_permission + return render_forbidden("您没有操作权限!") unless @project.member?(current_user) || current_user.admin? || @issue.user == current_user + end + + def query_params + params.permit( + :only_name, + :category, + :participant_category, + :keyword, :author_id, + :milestone_id, :assigner_id, + :status_id, + :sort_by, :sort_direction, + :issue_tag_ids) + end + + def issue_params + params.permit( + :status_id, :priority_id, :milestone_id, + :branch_name, :start_date, :due_date, + :subject, :description, :blockchain_token_num, + :issue_tag_ids => [], + :assigner_ids => [], + :attachment_ids => [], + :receivers_login => []) + end + + def batch_issue_params + params.permit( + :status_id, :priority_id, :milestone_id, + :issue_tag_ids => [], + :assigner_ids => []) + end +end \ No newline at end of file diff --git a/app/controllers/api/v1/projects/code_stats_controller.rb b/app/controllers/api/v1/projects/code_stats_controller.rb index 7ec671f3c..0f2b2dd36 100644 --- a/app/controllers/api/v1/projects/code_stats_controller.rb +++ b/app/controllers/api/v1/projects/code_stats_controller.rb @@ -3,6 +3,6 @@ class Api::V1::Projects::CodeStatsController < Api::V1::BaseController def index @result_object = Api::V1::Projects::CodeStats::ListService.call(@project, {ref: params[:ref]}, current_user&.gitea_token) - puts @result_object + # puts @result_object end end \ No newline at end of file diff --git a/app/controllers/api/v1/projects/collaborators_controller.rb b/app/controllers/api/v1/projects/collaborators_controller.rb new file mode 100644 index 000000000..cd9002a99 --- /dev/null +++ b/app/controllers/api/v1/projects/collaborators_controller.rb @@ -0,0 +1,10 @@ +class Api::V1::Projects::CollaboratorsController < Api::V1::BaseController + + before_action :require_public_and_member_above, only: [:index] + + def index + @collaborators = @project.all_collaborators.like(params[:keyword]) + @collaborators = kaminary_select_paginate(@collaborators) + end + +end \ No newline at end of file diff --git a/app/controllers/application_controller.rb b/app/controllers/application_controller.rb index 8129df8f1..ac99c30f5 100644 --- a/app/controllers/application_controller.rb +++ b/app/controllers/application_controller.rb @@ -832,6 +832,325 @@ class ApplicationController < ActionController::Base HotSearchKeyword.add(keyword) end + # author: zxh + # blockchain相关项目活动调用函数 + # return true: 表示上链操作成功; return false: 表示上链操作失败 + def push_activity_2_blockchain(activity_type, model) + if activity_type == "issue_create" + + project_id = model['project_id'] + project = Project.find(project_id) + if project['use_blockchain'] == 0 || project['use_blockchain'] == false + # 无需执行上链操作 + return true + end + + id = model['id'] + + owner_id = project['user_id'] + owner = User.find(owner_id) + ownername = owner['login'] + identifier = project['identifier'] + + author_id = project['user_id'] + author = User.find(author_id) + username = author['login'] + + action = 'opened' + + title = model['subject'] + content = model['description'] + created_at = model['created_on'] + updated_at = model['updated_on'] + + # 调用区块链接口 + params = { + "request-type": "upload issue info", + "issue_id": "gitlink-" + id.to_s, + "repo_id": "gitlink-" + project_id.to_s, + "issue_number": 0, # 暂时不需要改字段 + "reponame": identifier, + "ownername": ownername, + "username": username, + "action": action, + "title": title, + "content": content, + "created_at": created_at, + "updated_at": updated_at + }.to_json + resp_body = Blockchain::InvokeBlockchainApi.call(params) + if resp_body['status'] == 10 + raise ApplicationService::Error, resp_body['message'] + elsif resp_body['status'] != 0 + raise ApplicationService::Error, "区块链接口请求失败." + end + + elsif activity_type == "issue_comment_create" + issue_comment_id = model['id'] + issue_id = model['journalized_id'] + parent_id = model['parent_id'].nil? ? "" : model['parent_id'] + + issue = Issue.find(issue_id) + issue_classify = issue['issue_classify'] # issue或pull_request + project_id = issue['project_id'] + project = Project.find(project_id) + + if project['use_blockchain'] == 0 || project['use_blockchain'] == false + # 无需执行上链操作 + return + end + + identifier = project['identifier'] + owner_id = project['user_id'] + owner = User.find(owner_id) + ownername = owner['login'] + + author_id = model['user_id'] + author = User.find(author_id) + username = author['login'] + + action = 'created' + + content = model['notes'] + created_at = model['created_on'] + + if issue_classify == "issue" + params = { + "request-type": "upload issue comment info", + "issue_comment_id": "gitlink-" + issue_comment_id.to_s, + "issue_comment_number": 0, # 暂时不需要 + "issue_number": 0, # 暂时不需要 + "issue_id": "gitlink-" + issue_id.to_s, + "repo_id": "gitlink-" + project.id.to_s, + "parent_id": parent_id.to_s, + "reponame": identifier, + "ownername": ownername, + "username": username, + "action": action, + "content": content, + "created_at": created_at, + }.to_json + elsif issue_classify == "pull_request" + params = { + "request-type": "upload pull request comment info", + "pull_request_comment_id": "gitlink-" + issue_comment_id.to_s, + "pull_request_comment_number": 0, # 不考虑该字段 + "pull_request_number": 0, # 不考虑该字段 + "pull_request_id": "gitlink-" + issue_id.to_s, + "parent_id": parent_id.to_s, + "repo_id": "gitlink-" + project.id.to_s, + "reponame": identifier, + "ownername": ownername, + "username": username, + "action": action, + "content": content, + "created_at": created_at, + }.to_json + end + + # 调用区块链接口 + resp_body = Blockchain::InvokeBlockchainApi.call(params) + if resp_body['status'] == 10 + raise ApplicationService::Error, resp_body['message'] + elsif resp_body['status'] != 0 + raise ApplicationService::Error, "区块链接口请求失败." + end + elsif activity_type == "pull_request_create" + # 调用区块链接口 + project_id = model['project_id'] + project = Project.find(project_id) + if project['use_blockchain'] == 0 || project['use_blockchain'] == false + # 无需执行上链操作 + return + end + + pull_request_id = model['id'] + identifier = project['identifier'] + owner_id = project['user_id'] + owner = User.find(owner_id) + ownername = owner['login'] + + action = 'opened' + + title = model['title'] + content = model['body'] + + source_branch = model['head'] + source_repo_id = model['fork_project_id'].nil? ? project_id : model['fork_project_id'] + + target_branch = model['base'] + target_repo_id = project_id + + author_id = model['user_id'] + author = User.find(author_id) + username = author['login'] + + created_at = model['created_at'] + updated_at = model['updated_at'] + + # 查询pull request对应的commit信息 + commits = Gitea::PullRequest::CommitsService.call(ownername, identifier, model['gitea_number'], current_user&.gitea_token) + if commits.nil? + raise ApplicationService::Error, "区块链接口请求失败" # 获取pr中变更的commit信息失败 + end + commit_shas = [] + commits.each do |c| + commit_shas << c["Sha"] + end + params = { + "request-type": "upload pull request info", + "pull_request_id": "gitlink-" + pull_request_id.to_s, + "pull_request_number": 0, # trustie没有该字段 + "repo_id": "gitlink-" + project_id.to_s, + "ownername": ownername, + "reponame": identifier, + "username": username, + "action": action, + "title": title, + "content": content, + "source_branch": source_branch, + "target_branch": target_branch, + "reviewers": [], # trustie没有该字段 + "commit_shas": commit_shas, + "merge_user": "", # trustie没有该字段 + "created_at": created_at, + "updated_at": updated_at + }.to_json + resp_body = Blockchain::InvokeBlockchainApi.call(params) + if resp_body['status'] == 9 + raise ApplicationService::Error, resp_body['message'] + elsif resp_body['status'] != 0 + raise ApplicationService::Error, "区块链接口请求失败." + end + elsif activity_type == "pull_request_merge" + # 调用区块链接口 + project_id = model['project_id'] + project = Project.find(project_id) + if project['use_blockchain'] == 0 || project['use_blockchain'] == false + # 无需执行上链操作 + return + end + + pull_request_id = model['id'] + identifier = project['identifier'] + owner_id = project['user_id'] + owner = User.find(owner_id) + ownername = owner['login'] + + action = 'merged' + + created_at = model['created_at'] + updated_at = model['updated_at'] + + # 查询pull request对应的commit信息 + commits = Gitea::PullRequest::CommitsService.call(ownername, identifier, model['gitea_number'], current_user&.gitea_token) + if commits.nil? + raise ApplicationService::Error, "区块链接口请求失败" # 获取pr中变更的commit信息失败 + end + commit_shas = [] + commits.each do |c| + commit_shas << c["Sha"] + end + + # 将pull request相关信息写入链上 + params = { + "request-type": "upload pull request info", + "pull_request_id": "gitlink-" + pull_request_id.to_s, + "pull_request_number": 0, # trustie没有该字段 + "repo_id": "gitlink-" + project_id.to_s, + "ownername": ownername, + "reponame": identifier, + "username": username, + "action": action, + "title": title, + "content": content, + "source_branch": source_branch, + "target_branch": target_branch, + "reviewers": [], # trustie没有该字段 + "commit_shas": commit_shas, + "merge_user": "", # trustie没有该字段 + "created_at": created_at, + "updated_at": updated_at + }.to_json + resp_body = Blockchain::InvokeBlockchainApi.call(params) + if resp_body['status'] == 9 + raise ApplicationService::Error, resp_body['message'] + elsif resp_body['status'] != 0 + raise ApplicationService::Error, "区块链接口请求失败." + end + + + # 将commit相关信息写入链上 + commit_shas.each do |commit_sha| + commit_diff = Gitea::Commit::DiffService.call(ownername, identifier, commit_sha, owner['gitea_token']) + commit = Gitea::Commit::InfoService.call(ownername, identifier, commit_sha, owner['gitea_token']) + params = { + "request-type": "upload commit info", + "commit_hash": commit_sha, + "repo_id": "gitlink-" + project_id.to_s, + "author": commit['commit']['author']['name'], + "author_email": commit['commit']['author']['email'], + "committer": commit['commit']['committer']['name'], + "committer_email": commit['commit']['committer']['email'], + "author_time": commit['commit']['author']['date'], + "committer_time": commit['commit']['committer']['date'], + "content": commit['commit']['message'], + "commit_diff": commit_diff['Files'].to_s + }.to_json + resp_body = Blockchain::InvokeBlockchainApi.call(params) + if resp_body['status'] == 7 + raise ApplicationService::Error, resp_body['message'] + elsif resp_body['status'] != 0 + raise ApplicationService::Error, "区块链接口请求失败." + end + end + + elsif activity_type == "pull_request_refuse" + + # 调用区块链接口 + project_id = model['project_id'] + project = Project.find(project_id) + if project['use_blockchain'] == 0 || project['use_blockchain'] == false + # 无需执行上链操作 + return true + end + + pull_request_id = model['id'] + identifier = project['identifier'] + owner_id = project['user_id'] + owner = User.find(owner_id) + ownername = owner['login'] + + action = 'refused' + + # 将pull request相关信息写入链上 + params = { + "request-type": "upload pull request info", + "pull_request_id": "gitlink-" + pull_request_id.to_s, + "pull_request_number": 0, # trustie没有该字段 + "repo_id": "gitlink-" + project_id.to_s, + "ownername": ownername, + "reponame": identifier, + "username": username, + "action": action, + "title": title, + "content": content, + "source_branch": source_branch, + "target_branch": target_branch, + "reviewers": [], # trustie没有该字段 + "commit_shas": commit_shas, + "merge_user": "", # trustie没有该字段 + "created_at": created_at, + "updated_at": updated_at + }.to_json + resp_body = Blockchain::InvokeBlockchainApi.call(params) + if resp_body['status'] == 9 + raise ApplicationService::Error, resp_body['message'] + elsif resp_body['status'] != 0 + raise ApplicationService::Error, "区块链接口请求失败." + end + end + end def find_atme_receivers @atme_receivers = User.where(login: params[:receivers_login]) end diff --git a/app/controllers/installations_controller.rb b/app/controllers/installations_controller.rb index 20dd25e40..3379af47c 100644 --- a/app/controllers/installations_controller.rb +++ b/app/controllers/installations_controller.rb @@ -37,7 +37,7 @@ class InstallationsController < ApplicationController # 注册bot对应oauth应用 Doorkeeper::Application.create!(name: @bot.name, uid: @bot.client_id, secret: @bot.client_secret, redirect_uri: "https://gitlink.org.cn") # 注册bot对应用户 - result = autologin_register(User.generate_user_login('b'), nil, "#{SecureRandom.hex(6)}", 'bot', nickname: @bot.name) + result = autologin_register(User.generate_user_login('b'), nil, "#{SecureRandom.hex(6)}", 'bot', nil, nickname: @bot.name) tip_exception(-1, result[:message]) if result[:message].present? @bot.uid = result[:user][:id] @bot.save diff --git a/app/controllers/issues_controller.rb b/app/controllers/issues_controller.rb index efc7d3ea4..c1f2ea1f0 100644 --- a/app/controllers/issues_controller.rb +++ b/app/controllers/issues_controller.rb @@ -111,7 +111,9 @@ class IssuesController < ApplicationController issue_params = issue_send_params(params) Issues::CreateForm.new({subject: issue_params[:subject], description: issue_params[:description].blank? ? issue_params[:description] : issue_params[:description].b}).validate! @issue = Issue.new(issue_params) + @issue.project_issues_index = @project.get_last_project_issues_index + 1 if @issue.save! + @project.del_project_issue_cache_delete_count SendTemplateMessageJob.perform_later('IssueAssigned', current_user.id, @issue&.id) if Site.has_notice_menu? SendTemplateMessageJob.perform_later('ProjectIssue', current_user.id, @issue&.id) if Site.has_notice_menu? if params[:attachment_ids].present? @@ -149,6 +151,7 @@ class IssuesController < ApplicationController end @issue.project_trends.create(user_id: current_user.id, project_id: @project.id, action_type: "create") + @issue.project_trends.create(user_id: current_user.id, project_id: @project.id, action_type: ProjectTrend::CLOSE) if params[:status_id].to_i == 5 @@ -157,6 +160,17 @@ class IssuesController < ApplicationController # 新增时向grimoirelab推送事件 IssueWebhookJob.set(wait: 5.seconds).perform_later(@issue.id) + if Site.has_blockchain? && @project.use_blockchain + # author: zxh + # 扣除发起人的token + if @issue.blockchain_token_num > 0 + Blockchain::CreateIssue.call(user_id: @issue.author_id, project_id: @issue.project_id, token_num: @issue.blockchain_token_num) + end + + # 调用上链API存证 + push_activity_2_blockchain("issue_create", @issue) + end + render json: {status: 0, message: "创建成功", id: @issue.id} else normal_status(-1, "创建失败") @@ -304,6 +318,7 @@ class IssuesController < ApplicationController login = @issue.user.try(:login) SendTemplateMessageJob.perform_later('IssueDeleted', current_user.id, @issue&.subject, @issue.assigned_to_id, @issue.author_id) if Site.has_notice_menu? if @issue.destroy + @project.incre_project_issue_cache_delete_count if issue_type == "2" && status_id != 5 post_to_chain("add", token, login) end @@ -543,7 +558,8 @@ class IssuesController < ApplicationController branch_name: params[:branch_name].to_s, issue_classify: "issue", author_id: current_user.id, - project_id: @project.id + project_id: @project.id, + blockchain_token_num: params[:blockchain_token_num] } end diff --git a/app/controllers/journals_controller.rb b/app/controllers/journals_controller.rb index 6dc1e29c9..834cdbd4e 100644 --- a/app/controllers/journals_controller.rb +++ b/app/controllers/journals_controller.rb @@ -47,10 +47,15 @@ class JournalsController < ApplicationController Rails.logger.info "[ATME] maybe to at such users: #{@atme_receivers.pluck(:login)}" AtmeService.call(current_user, @atme_receivers, journal) if @atme_receivers.size > 0 # @issue.project_trends.create(user_id: current_user.id, project_id: @project.id, action_type: "journal") + + # author: zxh + # 调用上链API + push_activity_2_blockchain("issue_comment_create", journal) if Site.has_blockchain? && @project.use_blockchain + render :json => { status: 0, message: "评论成功", id: journal.id} - # normal_status(0, "评论成功") else normal_status(-1, "评论失败") + raise ActiveRecord::Rollback end end end diff --git a/app/controllers/organizations/projects_controller.rb b/app/controllers/organizations/projects_controller.rb index b36a76125..ab5c9ef5d 100644 --- a/app/controllers/organizations/projects_controller.rb +++ b/app/controllers/organizations/projects_controller.rb @@ -8,14 +8,17 @@ class Organizations::ProjectsController < Organizations::BaseController .joins(team_projects: {team: :team_users}) .where(team_users: {user_id: current_user.id}).to_sql @projects = Project.from("( #{ public_projects_sql} UNION #{ private_projects_sql } ) AS projects") - - @projects = @projects.ransack(name_or_identifier_cont: params[:search]).result if params[:search].present? + # 表情处理 + keywords = params[:search].to_s.each_char.select { |c| c.bytes.first < 240 }.join('') + @projects = @projects.ransack(name_or_identifier_cont: keywords).result if params[:search].present? @projects = @projects.includes(:owner).order("projects.#{sort} #{sort_direction}") @projects = paginate(@projects) end def search tip_exception("请输入搜索关键词") if params[:search].nil? + # 表情处理 + keywords = params[:search].to_s.each_char.select { |c| c.bytes.first < 240 }.join('') public_projects_sql = @organization.projects.where(is_public: true).to_sql private_projects_sql = @organization.projects .where(is_public: false) @@ -23,7 +26,7 @@ class Organizations::ProjectsController < Organizations::BaseController .where(team_users: {user_id: current_user.id}).to_sql @projects = Project.from("( #{ public_projects_sql} UNION #{ private_projects_sql } ) AS projects") - @projects = @projects.ransack(name_or_identifier_cont: params[:search]).result + @projects = @projects.ransack(name_or_identifier_cont: keywords).result @projects = @projects.includes(:owner).order("projects.#{sort} #{sort_direction}") end diff --git a/app/controllers/projects_controller.rb b/app/controllers/projects_controller.rb index 918b4533f..440379ac3 100644 --- a/app/controllers/projects_controller.rb +++ b/app/controllers/projects_controller.rb @@ -274,7 +274,8 @@ class ProjectsController < ApplicationController private def project_params params.permit(:user_id, :name, :description, :repository_name, :website, :lesson_url, :default_branch, :identifier, - :project_category_id, :project_language_id, :license_id, :ignore_id, :private) + :project_category_id, :project_language_id, :license_id, :ignore_id, :private, + :blockchain, :blockchain_token_all, :blockchain_init_token) end def mirror_params diff --git a/app/controllers/pull_requests_controller.rb b/app/controllers/pull_requests_controller.rb index 2b9bbbe6f..5401c96f0 100644 --- a/app/controllers/pull_requests_controller.rb +++ b/app/controllers/pull_requests_controller.rb @@ -6,6 +6,7 @@ class PullRequestsController < ApplicationController before_action :find_pull_request, except: [:index, :new, :create, :check_can_merge,:get_branches,:create_merge_infos, :files, :commits] before_action :load_pull_request, only: [:files, :commits] before_action :find_atme_receivers, only: [:create, :update] + include TagChosenHelper include ApplicationHelper @@ -73,6 +74,11 @@ class PullRequestsController < ApplicationController SendTemplateMessageJob.perform_later('ProjectPullRequest', current_user.id, @pull_request&.id) if Site.has_notice_menu? Rails.logger.info "[ATME] maybe to at such users: #{@atme_receivers.pluck(:login)}" AtmeService.call(current_user, @atme_receivers, @pull_request) if @atme_receivers.size > 0 + + # author: zxh + # 调用上链API + push_activity_2_blockchain("pull_request_create", @pull_request) if Site.has_blockchain? && @project.use_blockchain + else render_error("create pull request error: #{@gitea_pull_request[:status]}") raise ActiveRecord::Rollback @@ -119,7 +125,19 @@ class PullRequestsController < ApplicationController end else return normal_status(-1, "请输入正确的标记。") - end + end + end + if params[:attached_issue_ids].present? + if params[:attached_issue_ids].is_a?(Array) && params[:attached_issue_ids].size > 1 + return normal_status(-1, "最多只能关联一个疑修。") + elsif params[:attached_issue_ids].is_a?(Array) && params[:attached_issue_ids].size == 1 + @pull_request&.pull_attached_issues&.destroy_all + params[:attached_issue_ids].each do |issue| + PullAttachedIssue.create!(issue_id: issue, pull_request_id: @pull_request.id) + end + else + return normal_status(-1, "请输入正确的疑修。") + end end if params[:status_id].to_i == 5 @issue.issue_times.update_all(end_time: Time.now) @@ -149,12 +167,16 @@ class PullRequestsController < ApplicationController ActiveRecord::Base.transaction do begin colsed = PullRequests::CloseService.call(@owner, @repository, @pull_request, current_user) - if colsed === true + # author: zxh + # 调用上链API + push_activity_2_blockchain("pull_request_refuse", @pull_request) if Site.has_blockchain? && @project.use_blockchain + + if colsed === true @pull_request.project_trends.create!(user: current_user, project: @project,action_type: ProjectTrend::CLOSE) # 合并请求下issue处理为关闭 @issue&.update_attributes!({status_id:5}) SendTemplateMessageJob.perform_later('PullRequestClosed', current_user.id, @pull_request.id) if Site.has_notice_menu? - normal_status(1, "已拒绝") + normal_status(1, "已拒绝") else normal_status(-1, '合并失败') end @@ -198,6 +220,28 @@ class PullRequestsController < ApplicationController # @pull_request.project_trend_status! @pull_request.project_trends.create!(user: current_user, project: @project,action_type: ProjectTrend::MERGE) @issue&.custom_journal_detail("merge", "", "该合并请求已被合并", current_user&.id) + + # author: zxh + # 调用上链API + push_activity_2_blockchain("pull_request_merge", @pull_request) if Site.has_blockchain? && @project.use_blockchain + + # 查看是否fix了相关issue,如果fix就转账 + @pull_request.attached_issues.each do |issue| + next if PullAttachedIssue.exists?(issue_id: issue.id, fixed: true) + token_num = issue.blockchain_token_num + token_num = token_num.nil? ? 0 : token_num + author_id = @pull_request.user_id + if token_num > 0 + Blockchain::FixIssue.call({user_id: author_id.to_s, project_id: @project.id.to_s, token_num: token_num}) if Site.has_blockchain? && @project.use_blockchain + PullAttachedIssue.find_by(issue_id: issue.id, pull_request_id: @pull_request.id).update(fixed: true) + end + # update issue to state 5 + issue.issue_participants.create!({participant_type: "edited", participant_id: current_user.id}) unless issue.issue_participants.exists?(participant_type: "edited", participant_id: current_user.id) + journal = issue.journals.create!({user_id: current_user.id}) + journal.journal_details.create!({property: "attr", prop_key: "status_id", old_value: issue.status_id, value: 5}) + issue.update(status_id: 5) + end + # 合并请求下issue处理为关闭 @issue&.update_attributes!({status_id:5}) SendTemplateMessageJob.perform_later('PullRequestMerged', current_user.id, @pull_request.id) if Site.has_notice_menu? diff --git a/app/controllers/users/headmaps_controller.rb b/app/controllers/users/headmaps_controller.rb index 7c88b5681..7faba1e50 100644 --- a/app/controllers/users/headmaps_controller.rb +++ b/app/controllers/users/headmaps_controller.rb @@ -10,15 +10,15 @@ class Users::HeadmapsController < Users::BaseController private def start_stamp if params[:year].present? - Date.new(params[:year], 1).to_time.to_i + Date.new(params[:year].to_i, 1).to_time.to_i else - Date.today.to_time.to_i - 365*24*60*60 + (Date.today - 1.years).to_time.to_i end end def end_stamp if params[:year].present? - Date.new(params[:year], 1).to_time.to_i + 365*24*60*60 + (Date.new(params[:year].to_i, 1) + 1.years).to_time.to_i else Date.today.to_time.to_i end diff --git a/app/controllers/users/messages_controller.rb b/app/controllers/users/messages_controller.rb index 5116f580f..4feb4a98e 100644 --- a/app/controllers/users/messages_controller.rb +++ b/app/controllers/users/messages_controller.rb @@ -1,6 +1,7 @@ class Users::MessagesController < Users::BaseController before_action :private_user_resources! before_action :find_receivers, only: [:create] + before_action :check_auth def index limit = params[:limit] || params[:per_page] @@ -63,6 +64,10 @@ class Users::MessagesController < Users::BaseController end private + def check_auth + return render_forbidden unless current_user.admin? || observed_logged_user? + end + def message_type @message_type = begin case params[:type] diff --git a/app/controllers/users_controller.rb b/app/controllers/users_controller.rb index 33fd93f83..35f44b4e2 100644 --- a/app/controllers/users_controller.rb +++ b/app/controllers/users_controller.rb @@ -2,8 +2,8 @@ class UsersController < ApplicationController include ApplicationHelper include Ci::DbConnectable - before_action :load_user, only: [:show, :homepage_info, :sync_token, :sync_gitea_pwd, :projects, :watch_users, :fan_users, :hovercard] - before_action :check_user_exist, only: [:show, :homepage_info,:projects, :watch_users, :fan_users, :hovercard] + before_action :load_user, only: [:show, :homepage_info, :sync_token, :sync_gitea_pwd, :projects, :watch_users, :fan_users, :hovercard, :hovercard4proj] + before_action :check_user_exist, only: [:show, :homepage_info,:projects, :watch_users, :fan_users, :hovercard, :hovercard4proj] before_action :require_login, only: %i[me sync_user_info] before_action :connect_to_ci_db, only: [:get_user_info] before_action :convert_image!, only: [:update, :update_image] @@ -81,9 +81,134 @@ class UsersController < ApplicationController @watchers = paginate(watchers) end + def contribution_perc + project_id = params[:project_id] + @project = Project.find(project_id) + user_id = params[:id] + @user = User.find(user_id) + + def cal_perc(count_user, count_all) + (count_user * 1.0 / (count_all + 0.000000001)).round(5) + end + + if @project['use_blockchain'] == true or @project['use_blockchain'] == 1 + balance_user = Blockchain::BalanceQueryOneProject.call({"user_id": user_id, "project_id": project_id}) + balance_all = Blockchain::RepoBasicInfo.call({"project_id": project_id})["cur_supply"] + scores = { + "final" => cal_perc(balance_user, balance_all), + "blockchain" => true + } + else + # 获取所有行为对应的项目内记录总数和个人记录数 + features = { + "requirement" => {}, + "development" => {}, + "review" => {} + } + + # 1. issue创建 + issues = Issue.where(project_id: project_id, issue_classify: 'issue') + issue_all = issues.count + issue_user = issues.where(author_id: user_id).count + features["requirement"] = features["requirement"].merge({"issue" => {"all" => issue_all, "perc" => cal_perc(issue_user, issue_all)}}) + # 2. 里程碑创建 + milestones = Version.where(project_id: project_id) + milestone_all = milestones.count + milestone_user = milestones.where(user_id: user_id).count + features["requirement"] = features["requirement"].merge({"milestone" => {"all" => milestone_all, "perc" => cal_perc(milestone_user, milestone_all)}}) + # 3. issue评论 + issue_comments = Journal.joins("INNER JOIN issues on journals.journalized_id=issues.id").where("issues.project_id=#{project_id} and journalized_type='Issue' and issues.issue_classify='issue'") + issue_comment_all = issue_comments.count + issue_comment_user = issue_comments.where("journals.user_id=#{user_id}").count + features["requirement"] = features["requirement"].merge({"issue_comment" => {"all" => issue_comment_all, "perc" => cal_perc(issue_comment_user, issue_comment_all)}}) + # 4. 合并请求 + prs = PullRequest.where(project_id: project_id) + pr_all = prs.count + pr_user = prs.where(user_id: user_id).count + features["development"] = features["development"].merge({"pr" => {"all" => pr_all, "perc" => cal_perc(pr_user, pr_all)}}) + # 5. pr评论 + pr_comments = Journal.joins("INNER JOIN issues on journals.journalized_id=issues.id").where("issues.project_id=#{project_id} and journalized_type='Issue' and issues.issue_classify='pull_request'") + pr_comment_all = pr_comments.count + pr_comment_user = pr_comments.where("journals.user_id=#{user_id}").count + features["review"] = features["review"].merge({"pr_comment" => {"all" => pr_comment_all, "perc" => cal_perc(pr_comment_user, pr_comment_all)}}) + # 6. 代码行评论 + line_comments = Journal.joins("INNER JOIN pull_requests on journals.journalized_id=pull_requests.id").where("pull_requests.project_id=#{project_id} and journalized_type='PullRequest'") + line_comment_all = line_comments.count + line_comment_user = line_comments.where("journals.user_id=#{user_id}").count + features["review"] = features["review"].merge({"line_comment" => {"all" => line_comment_all, "perc" => cal_perc(line_comment_user, line_comment_all)}}) + # 7. 代码行、commit贡献统计 + code_contributions = Api::V1::Projects::CodeStats::ListService.call(@project, {ref: nil}) + commit_all = code_contributions["commit_count"] + addition_all = code_contributions["additions"] + deletion_all = code_contributions["deletions"] + + commit_user = 0 + addition_user = 0 + deletion_user = 0 + code_contributions["authors"].each do |author| + if author["name"] == @user.login + commit_user = author["commits"] + addition_user = author["additions"] + deletion_user = author["deletions"] + end + end + + features["development"] = features["development"].merge({"commit" => {"all" => commit_all, "perc" => cal_perc(commit_user, commit_all)}}) + features["development"] = features["development"].merge({"addition" => {"all" => addition_all, "perc" => cal_perc(addition_user, addition_all)}}) + features["development"] = features["development"].merge({"deletion" => {"all" => deletion_all, "perc" => cal_perc(deletion_user, deletion_all)}}) + + def cal_weight(features) + weights = {} # 计算每一项的权重 + categories = [] + features.each do |key, _| + categories << key + weights[key] = Hash.new + end + count_all = 0 + counts = {} + categories.each do |category| + count_1 = 0 + features[category].each do |_, value| + count_1 += value["all"] + end + count_all += count_1 + counts[category] = count_1 + features[category].each do |key, value| + weight = cal_perc(value["all"], count_1) + weights[category] = weights[category].merge({key => weight}) + end + end + categories.each do |category| + weight = cal_perc(counts[category], count_all) + weights[category] = weights[category].merge({"category_weight" => weight}) + end + return weights + end + + weights_categories = cal_weight(features) + scores = { + "final" => 0.0, + "blockchain" => false + } + features.each do |category, value_1| + category_score = 0.0 + value_1.each do |action, value_2| + category_score += weights_categories[category][action] * value_2["perc"] + end + scores["final"] += weights_categories[category]["category_weight"] * category_score.round(4) + scores = scores.merge({category => category_score.round(4)}) + end + end + render json: { scores: scores } + end + def hovercard end + # author: zxh, 查询贡献者的贡献度 + def hovercard4proj + end + def update return render_not_found unless @user = User.find_by(login: params[:id]) || User.find_by_id(params[:id]) return render_forbidden unless User.current.logged? && (current_user&.admin? || current_user.id == @user.id) @@ -94,11 +219,11 @@ class UsersController < ApplicationController end end - def update_image - return render_not_found unless @user = User.find_by(login: params[:id]) || User.find_by_id(params[:id]) + def update_image + return render_not_found unless @user = User.find_by(login: params[:id]) || User.find_by_id(params[:id]) return render_forbidden unless User.current.logged? && (current_user&.admin? || current_user.id == @user.id) - Util.write_file(@image, avatar_path(@user)) + Util.write_file(@image, avatar_path(@user)) return render_ok({message: '头像修改成功'}) rescue Exception => e uid_logger_error(e.message) @@ -284,6 +409,252 @@ class UsersController < ApplicationController @projects = paginate(scope) end + + # query all projects with tokens by a user + def blockchain_balance + #is_current_admin_user = User.current.logged? && (current_user&.admin? || current_user.id == params['user_id'].to_i) + is_current_admin_user = true + results = Blockchain::BalanceQuery.call(params, is_current_admin_user) + if results[:status] == 0 + @total_count = results[:total_count] + @projects = results[:projects] + else + @total_count = -1 + @projects = [] + end + + # render json: { status: results[:status], projects: @projects, total_count: @total_count } + end + + # query one balance + def blockchain_balance_one_project + #is_current_admin_user = User.current.logged? && (current_user&.admin? || current_user.id == params['user_id'].to_i) + is_current_admin_user = true + if is_current_admin_user + owner = User.find_by(login: params['owner_login']) + if owner.nil? + normal_status(-1, "创建者无法找到") + else + p = Project.find_by(user_id: owner.id, identifier: params['project_identifier']) + balance = Blockchain::BalanceQueryOneProject.call({"user_id": params['user_id'].to_i, "project_id": p.id.to_i}) + render json: { status: 0, balance: balance} + end + else + normal_status(-1, "缺少权限") + end + + end + + + def blockchain_transfer + #is_current_admin_user = User.current.logged? && (current_user&.admin? || current_user.id == params['payer_id'].to_i) + is_current_admin_user = true + + if is_current_admin_user + Blockchain::TransferService.call(params) + render json: {status: 2} # 重新查询余额 + else + normal_status(-1, "缺少权限") + end + rescue Exception => e + normal_status(-1, e.to_s) + end + + # exchange money + def blockchain_exchange + #is_current_admin_user = User.current.logged? && (current_user&.admin? || current_user.id == params['user_id'].to_i) + #require 'alipay' + ## setup the client to communicate with either production API or sandbox API + ## https://openapi.alipay.com/gateway.do (Production) + ## https://openapi.alipaydev.com/gateway.do (Sandbox) + #api_url = 'https://openapi.alipay.com/gateway.do' + # + ## setup your own credentials and certificates + #app_id = '2021002140631434' + #app_private_key="-----BEGIN RSA PRIVATE KEY-----\nMIIEvAIBADANBgkqhkiG9w0BAQEFAASCBKYwggSiAgEAAoIBAQCPDsgc0n0RWRnbe9OMqtUbde8gu88OyjuZm8cJXeiSING18HX56C5zV4DsHQ6K9/JmQi/NYCc7/2Prh66Bei0L4Xm5TysJTPYi90+WlbJJESFF6fqULi8sSqZXUtaoMKRcUyeR144l2GQgXbZWBbVSQeZW5DqUDlurTF0I7vQ21wGqxQqBjQK8PSVw5hF+aIsNOfAY9M1tzdD5Jzo2Y3FJdsbXIJNMyhJJCZ+7KHFqma7lpjkXdCoyh/nOISkQdGtFI29gI94sqewI2AMU84uxuBIE3h90iLT+8xrd2dQKdBS7qfhQ3PgkBPVNs5jxsVBqSFdSFT6zcqFdHJzulCUJAgMBAAECggEAWocAGz0X5+J6emnhdSKluLrol85BORrAnHP3f/XtNouOKZQBFCPZQSQecUvx5/7/ZbZ8iXpPWahDkshJpaWq29nTLXDryvboyze1JZWVPKeaZqOp7htLvrt+h8PkEoq1d7cnUyMU0N4eflzPBaCXHXaWTGYgq5Bqcfvg48ZSxGBYeHt5WWU2+GW5fpsaVBBYkdyxxGMoy/bzYzGhvfSJkexqnl0XkAAODa02mu3WsHrzRid6Mf+3syYbq/MfUodU6Vng2tbCqwnWrHCyrD4RYl6rg1TKuAv2YAfBhLzwBxHYVC4SRqzjs+8AaOQoF+lCjr4JklPhEuRThzD31YwIAQKBgQDAg4S7ciMmxvbNxR+1eimoAYLLF9jPpPU6w3VFNPb4rDu4tX77bNf082YplfJX5TYtZKjKPKyYG87K6slGunyPL4AFRW81WPB9u1uP26dihyPCBSUE01jKRPPfRrQnnru5fpm8LL3L03V3yA6J+GyQ8wltRJJi1eBSSm+IWRsZewKBgQC+PBD9J1LYOEIVeK9KvN8BpkA1ZIkk//VuJaoGfVXn+1EzM1yFB05fnsEQkHFynisvuCIr7pH63HcdyffQhe1YOnw9iDCG1zPjsi5uTe9WAM0dnb7xdsaLPr/Q2LyoDOTN9344Qovy1AAnpWtGTn6omgHst5nZpp/mHOuBlKiqSwKBgBKRXM77fjpyPEGyfpFxW+0xYB0YirfUUDa/vWLUbfGkIwp4ruuvHtEoXLUsGjiyCdys9b6zxW3SWMqnhIxG1la1HSLlBInfryphVL52UBmnsSI4fs6NV+YCaocheaTMoYyNkmRc6F1tYsoPyJ80D7yXRFR+paPUvxMQzNsYxQ1bAoGAHd2uSSBQWFPUxCwzUQd/93FTaU6EXYO103okTGqG/ymsoN4ya0wvWMHCy8fxl64PV6mP69fDoV/Vb57SwjEUhyJ/eOWVwMWuhtPliDnCFn1/tmOao6wjFZ9fW/l6/OMxVMjDTy/bat8vuwm0YtBWAEBVhwV4KPyI5AasTqa5KCsCgYB/usnqhVx2zt+MxpBt2Q9Vxc0zXcZxMDs69UUdTY86gjcJyCFGe3bbumUcyfSJzIznC2hfFX5ZyS0oMwiAzWtslRMh9LRh3kofD/6BogL3RKOlBk3iekvQ8Gn0tbwk2Qzr4WJgfA7A4GTf5r7Y+bvOfazzsUQAfSK6nUTIlOj2Ew==\n-----END RSA PRIVATE KEY-----\n" + #alipay_public_key="-----BEGIN PUBLIC KEY-----\nMIIBIjANBgkqhkiG9w0BAQEFAAOCAQ8AMIIBCgKCAQEAgHXLD1BshMymbqqtZVKNyo95FNfxzXzaw3P1eI0KeO6RaL+JzrWxzIBFfTjkWv/8WM9u/NcXMOFt2QO9q5KIDx6PkqjRDTd1hgP/cTgdjOHQqnVSihCrQDVCDBSOXIujC8Lk/P4pFVRhQkYeZqEb1qb8b/2tzTY8g9PKKBSCQv7SfgL2TBcpAVbb+9xdJ6VainC/wYGk8T+c+st1hXnuBJSS0m7LFxJOsYkNk0wbA0tfdZLrO3us2F7sjC9t4h/05nr+gSuDkzo+1kCEefYLqScexN+vnQiLoylp/C82wNiP6okxfhmHz3EcYfUqUyGTN/oFaFcPFPpUtFNS8jFV9QIDAQAB\n-----END PUBLIC KEY-----\n" + # + ## initialize a client to communicate with the Alipay API + #@alipay_client = Alipay::Client.new( + # url: api_url, + # app_id: app_id, + # app_private_key: app_private_key, + # alipay_public_key: alipay_public_key + #) + # + #return_result = @alipay_client.page_execute_url( + # method: 'alipay.trade.page.pay', + # biz_content: JSON.generate({ + # out_trade_no: '20210420104600', + # product_code: 'FAST_INSTANT_TRADE_PAY', + # total_amount: '0.01', + # subject: 'test' + # }, ascii_only: true), # ascii_only is important! + # timestamp: '2021-04-20 10:46:00' + #) + #render json: { pay_url: return_result } + # + + # 替代解决方案 + # 读取所有交易信息 + end + # # + # # def blockchain_create_trade + # # #is_current_admin_user = User.current.logged? && (current_user&.admin? || current_user.id == params['user_id'].to_i) + # # is_current_admin_user = true + # # if is_current_admin_user + # # user_id = params['user_id'].to_i + # # project_id = params['project_id'].to_i + # # money = params['money'].to_f + # # #description = params['description'] + # # token_num = params['token_num'].to_i + # # # 锁仓 + # # result = Blockchain::CreateTrade.call({user_id: user_id, project_id: project_id, token_num: token_num}) + # # if result == false + # # normal_status(-1, "创建交易失败") + # # else + # # bt = BlockchainTrade.new(user_id: user_id, project_id: project_id, token_num: token_num, money: money, state: 0) # state=0表示创建交易; state=1表示执行中; state=2表示执行完成 + # # bt.save() + # # status = 2 # 交易创建成功 + # # render json: { status: status } + # # end + # # else + # # normal_status(-1, "缺少权限") + # # end + # # end + # # + # # + # # def blockchain_get_trades + # # trades = BlockchainTrade.where(state: 0).all() + # # results = [] + # # trades.each do |t| + # # project_id = t.project_id + # # project = Project.find_by(id: project_id) + # # if !project.nil? + # # owner = User.find_by(id: project.user_id) + # # else + # # owner = nil + # # end + # # user_id = t.user_id + # # creator = User.find_by(id: user_id) + # # if project.nil? || owner.nil? || creator.nil? + # # else + # # results << [creator, owner, project, t] + # # end + # # end + # # render json: { results: results } + # # end + # # + # # def blockchain_trade + # # #is_current_admin_user = User.current.logged? && (current_user&.admin? || current_user.id == params['user_id'].to_i) + # # is_current_admin_user = true + # # if is_current_admin_user + # # user_id2 = params['user_id2'].to_i + # # trade_id = params['trade_id'].to_i + # # BlockchainTrade.find(trade_id).update(user_id2: user_id2, state: 1) # state=1表示锁定了,等待线下卖家发货 + # # render json: {status: 2} # window.location.reload() + # # else + # # normal_status(-1, "缺少权限") + # # end + # # end + # + # + # def blockchain_verify_trade + # #is_current_admin_user = User.current.logged? && (current_user&.admin? || current_user.id == params['user_id'].to_i) + # is_current_admin_user = true + # if is_current_admin_user + # trade_id = params['trade_id'].to_i + # BlockchainTrade.find(trade_id).update(state: 2) # state=2表示确认收货 + # render json: {status: 2} # window.location.reload() + # else + # normal_status(-1, "缺少权限") + # end + # end + # + # def blockchain_get_verify_trades + # #is_current_admin_user = User.current.logged? && (current_user&.admin? || current_user.id == params['user_id'].to_i) + # is_current_admin_user = true + # if is_current_admin_user + # trades = BlockchainTrade.where(state: 1).all() + # results = [] + # trades.each do |t| + # project_id = t.project_id + # project = Project.find_by(id: project_id) + # if !project.nil? + # owner = User.find_by(id: project.user_id) + # else + # owner = nil + # end + # user_id = t.user_id + # creator = User.find_by(id: user_id) + # user_id2 = t.user_id2 + # buyer = User.find_by(id: user_id2) + # if project.nil? || owner.nil? || creator.nil? || buyer.nil? + # else + # results << [creator, owner, project, t, buyer] + # end + # end + # render json: { results: results } + # else + # normal_status(-1, "缺少权限") + # end + # end + # + # def blockchain_get_history_trades + # #is_current_admin_user = User.current.logged? && (current_user&.admin? || current_user.id == params['user_id'].to_i) + # is_current_admin_user = true + # if is_current_admin_user + # trades = BlockchainTrade.where(state: 2).all() + # results = [] + # trades.each do |t| + # project_id = t.project_id + # project = Project.find_by(id: project_id) + # if !project.nil? + # owner = User.find_by(id: project.user_id) + # else + # owner = nil + # end + # user_id = t.user_id + # creator = User.find_by(id: user_id) + # user_id2 = t.user_id2 + # buyer = User.find_by(id: user_id2) + # if project.nil? || owner.nil? || creator.nil? || buyer.nil? + # else + # results << [creator, owner, project, t, buyer] + # end + # end + # render json: { results: results } + # else + # normal_status(-1, "缺少权限") + # end + # end + + + def blockchain_get_issue_token_num + issue_id = params["issue_id"]['orderId'].to_i + issue = Issue.find_by(id: issue_id) + project = Project.find(issue.project_id) + if project[:use_blockchain] + render json: {"blockchain_token_num": issue.blockchain_token_num} + else + render json: {"blockchain_token_num": -1} # 未使用blockchain + end + end + + + def blockchain_get_unclosed_issue_list + ownername = params["ownername"] + identifier = params["reponame"] + owner = User.find_by(login: ownername) + project = Project.find_by(user_id: owner.id, identifier: identifier) + unclosed_issues = Issue.where(project_id: project.id, issue_classify: "issue").where.not(status_id: 5) + results = [] + unclosed_issues.each do |i| + results << [i.id, i.subject] + end + render json: {unclosed_issues: results} + end + # TODO 其他平台登录时同步修改gitea平台对应用户的密码 # 该方法主要用于:别的平台初次部署对接forge平台,同步用户后,gitea平台对应的用户密码与forge平台用户密码不一致是问题 def sync_gitea_pwd @@ -322,7 +693,7 @@ class UsersController < ApplicationController end end - def email_search + def email_search return render_error('请输入email') if params[:email].blank? @user = User.find_by(mail: params[:email]) end diff --git a/app/forms/base_form.rb b/app/forms/base_form.rb index ca82fa4bb..44b5109c3 100644 --- a/app/forms/base_form.rb +++ b/app/forms/base_form.rb @@ -30,6 +30,14 @@ class BaseForm raise "项目名称已被使用." if Project.where(user_id: user_id, name: project_name.strip).exists? end + def check_blockchain_token_all(blockchain_token_all) + raise "请正确填写项目token总数." if (Float(blockchain_token_all) rescue false) == false or blockchain_token_all.to_i < 0 or Float(blockchain_token_all) != blockchain_token_all.to_i + end + + def check_blockchain_init_token(blockchain_init_token) + raise "请正确填写项目创始人token占比." if (Float(blockchain_init_token) rescue false) == false or blockchain_init_token.to_i < 0 or Float(blockchain_init_token) != blockchain_init_token.to_i + end + def check_reversed_keyword(repository_name) raise "项目标识已被占用." if ReversedKeyword.check_exists?(repository_name) end diff --git a/app/forms/projects/create_form.rb b/app/forms/projects/create_form.rb index c51c2c60f..c9fcb44e6 100644 --- a/app/forms/projects/create_form.rb +++ b/app/forms/projects/create_form.rb @@ -1,6 +1,7 @@ class Projects::CreateForm < BaseForm attr_accessor :user_id, :name, :description, :repository_name, :project_category_id, - :project_language_id, :ignore_id, :license_id, :private, :owner + :project_language_id, :ignore_id, :license_id, :private, :owner, + :blockchain, :blockchain_token_all, :blockchain_init_token validates :user_id, :name, :repository_name, presence: true validates :repository_name, format: { with: CustomRegexp::REPOSITORY_NAME_REGEX, multiline: true, message: "只能含有数字、字母、下划线且不能以下划线开头和结尾" } @@ -15,6 +16,8 @@ class Projects::CreateForm < BaseForm check_project_language(project_language_id) check_project_name(user_id, name) unless name.blank? check_repository_name(user_id, repository_name) unless repository_name.blank? + check_blockchain_token_all(blockchain_token_all) unless blockchain_token_all.blank? + check_blockchain_init_token(blockchain_init_token) unless blockchain_init_token.blank? end def check_license diff --git a/app/helpers/projects_helper.rb b/app/helpers/projects_helper.rb index b4c21e044..804e2aa46 100644 --- a/app/helpers/projects_helper.rb +++ b/app/helpers/projects_helper.rb @@ -66,6 +66,7 @@ module ProjectsHelper jianmu_devops: jianmu_devops_code(project, user), jianmu_devops_url: jianmu_devops_url, cloud_ide_saas_url: cloud_ide_saas_url(user), + open_blockchain: Site.has_blockchain? && project.use_blockchain, ignore_id: project.ignore_id }).compact @@ -138,6 +139,62 @@ module ProjectsHelper "#{saas_url}/oauth/login?product_account_id=PA1001218&tenant_code=TI1001383&oauth_url=#{oauth_url}&token=#{token.value}" end + def ai_shang_v1_url(project) + url = EduSetting.get("ai_shang_url") || "https://shang.gitlink.org.cn" + case project.identifier.to_s.downcase + when nil then "" + when 'rails' then "#{url}/v1/rails/entropy" + when 'jittor' then "#{url}/v1/jittor/entropy" + when 'paddle' then "#{url}/v1/Paddle/entropy" + when 'vue' then "#{url}/v1/vue/entropy" + when 'bootstrap' then "#{url}/v1/bootstrap/entropy" + when 'tensorflow' then "#{url}/v1/tensorflow/entropy" + else '' + end + end + + def ai_shang_v2_url(project) + url = EduSetting.get("ai_shang_url") || "https://shang.gitlink.org.cn" + case project.identifier.to_s.downcase + when nil then "" + when 'rails' then "#{url}/v2/getMediumData?repo_login=rails&repo_name=rails" + when 'jittor' then "#{url}/v2/getMediumData?repo_login=Jittor&repo_name=jittor" + when 'paddle' then "#{url}/v2/getMediumData?repo_login=PaddlePaddle&repo_name=Paddle" + when 'vue' then "#{url}/v2/getMediumData?repo_login=vuejs&repo_name=vue" + when 'bootstrap' then "#{url}/v2/getMediumData?repo_login=twbs&repo_name=bootstrap" + when 'tensorflow' then "#{url}/v2/getMediumData?repo_login=tensorflow&repo_name=tensorflow" + else '' + end + end + + def ai_shang_v4_url(project) + url = EduSetting.get("ai_shang_url") || "https://shang.gitlink.org.cn" + case project.identifier.to_s.downcase + when nil then "" + when 'rails' then "#{url}/v2/getIndexData?repo_login=rails&repo_name=rails" + when 'jittor' then "#{url}/v2/getIndexData?repo_login=Jittor&repo_name=jittor" + when 'paddle' then "#{url}/v2/getIndexData?repo_login=PaddlePaddle&repo_name=Paddle" + when 'vue' then "#{url}/v2/getIndexData?repo_login=vuejs&repo_name=vue" + when 'bootstrap' then "#{url}/v2/getIndexData?repo_login=twbs&repo_name=bootstrap" + when 'tensorflow' then "#{url}/v2/getIndexData?repo_login=tensorflow&repo_name=tensorflow" + else '' + end + end + + def ai_shang_v3_url(project) + url = EduSetting.get("ai_shang_v3_url") || "https://shang.gitlink.org.cn/v3" + case project.identifier.to_s.downcase + when nil then "" + when 'rails' then "#{url}/rails/entropy" + when 'jittor' then "#{url}/jittor/entropy" + when 'paddle' then "#{url}/paddle/entropy" + when 'vue' then "#{url}/vue/entropy" + when 'bootstrap' then "#{url}/bootstrap/entropy" + when 'tensorflow' then "#{url}/tensorflow/entropy" + else '' + end + end + def aes_encrypt(key, des_text) # des_text='{"access_key_id":"STS.NTuC9RVmWfJqj3JkcMzPnDf7X","access_key_secret":"E8NxRZWGNxxMfwgt5nFLnBFgg6AzgXCZkSNCyqygLuHM","end_point":"oss-accelerate.aliyuncs.com","security_token":"CAIS8gF1q6Ft5B2yfSjIr5fACIPmu7J20YiaaBX7j2MYdt9Cq6Ocujz2IHhMenVhA+8Wv/02n2hR7PcYlq9IS55VWEqc/VXLaywQo22beIPkl5Gfz95t0e+IewW6Dxr8w7WhAYHQR8/cffGAck3NkjQJr5LxaTSlWS7OU/TL8+kFCO4aRQ6ldzFLKc5LLw950q8gOGDWKOymP2yB4AOSLjIx6lAt2T8vs/7hmZPFukSFtjCglL9J/baWC4O/csxhMK14V9qIx+FsfsLDqnUIs0YWpf0p3P0doGyf54vMWUM05A6dduPS7txkLAJwerjVl1/ADxc0/hqAASXhPeiktbmDjwvnSn4iKcSGQ+xoQB468eHXNdvf13dUlbbE1+JhRi0pZIB2UCtN9oTsLHcwIHt+EJaoMd3+hGwPVmvHSXzECDFHylZ8l/pzTwlE/aCtZyVmI5cZEvmWu2xBa3GRbULo7lLvyeX1cHTVmVWf4Nk6D09PzTU8qlAj","bucket":"edu-bigfiles1","region":"oss-cn-hangzhou","callback_url":"https://data.educoder.net/api/buckets/callback.json","bucket_host":"data.educoder.net"}' # des = OpenSSL::Cipher::Cipher.new('aes-256-ctr') diff --git a/app/helpers/tag_chosen_helper.rb b/app/helpers/tag_chosen_helper.rb index 520b868fa..784efcf29 100644 --- a/app/helpers/tag_chosen_helper.rb +++ b/app/helpers/tag_chosen_helper.rb @@ -21,7 +21,8 @@ module TagChosenHelper "issue_tag": render_issue_tags(project), "issue_type": render_issue_species, "all_issues": all_issues, - "branches": render_branches(project) + "branches": render_branches(project), + "use_blockchain": project['use_blockchain'] } end diff --git a/app/jobs/open_project_dev_ops_job.rb b/app/jobs/open_project_dev_ops_job.rb index 64115f25f..b3fe99e6f 100644 --- a/app/jobs/open_project_dev_ops_job.rb +++ b/app/jobs/open_project_dev_ops_job.rb @@ -5,6 +5,7 @@ class OpenProjectDevOpsJob < ApplicationJob def perform(project_id, user_id) project = Project.find_by(id: project_id) + return if project.blank? user = User.find_by(id: user_id) code = jianmu_devops_code(project, user) uri = URI.parse("#{jianmu_devops_url}/activate?code=#{URI.encode_www_form_component(code)}") diff --git a/app/jobs/send_template_message_job.rb b/app/jobs/send_template_message_job.rb index 763708c38..c40a3c9bd 100644 --- a/app/jobs/send_template_message_job.rb +++ b/app/jobs/send_template_message_job.rb @@ -34,8 +34,8 @@ class SendTemplateMessageJob < ApplicationJob operator_id, issue_id = args[0], args[1] operator = User.find_by_id(operator_id) issue = Issue.find_by_id(issue_id) - return unless operator.present? && issue.present? - receivers = User.where(id: issue&.assigned_to_id).where.not(id: operator&.id) + return unless operator.present? && issue.present? + receivers = issue&.assigners.where.not(id: operator&.id) receivers_string, content, notification_url = MessageTemplate::IssueAssigned.get_message_content(receivers, operator, issue) Notice::Write::CreateService.call(receivers_string, content, notification_url, source, {operator_id: operator.id, issue_id: issue.id}) receivers.find_each do |receiver| @@ -56,7 +56,7 @@ class SendTemplateMessageJob < ApplicationJob operator = User.find_by_id(operator_id) issue = Issue.find_by_id(issue_id) return unless operator.present? && issue.present? - receivers = User.where(id: [issue&.assigned_to_id, issue&.author_id]).where.not(id: operator&.id) + receivers = User.where(id: issue.assigners.pluck(:id).append(issue&.author_id)).where.not(id: operator&.id) receivers_string, content, notification_url = MessageTemplate::IssueChanged.get_message_content(receivers, operator, issue, change_params.symbolize_keys) Notice::Write::CreateService.call(receivers_string, content, notification_url, source, {operator_id: operator.id, issue_id: issue.id, change_params: change_params.symbolize_keys}) receivers.find_each do |receiver| @@ -67,7 +67,7 @@ class SendTemplateMessageJob < ApplicationJob issue_id = args[0] issue = Issue.find_by_id(issue_id) return unless issue.present? - receivers = User.where(id: [issue&.assigned_to_id, issue&.author_id]) + receivers = User.where(id: issue.assigners.pluck(:id).append(issue&.author_id)) receivers_string, content, notification_url = MessageTemplate::IssueExpire.get_message_content(receivers, issue) Notice::Write::CreateService.call(receivers_string, content, notification_url, source, {issue_id: issue.id}) receivers.find_each do |receiver| @@ -78,7 +78,11 @@ class SendTemplateMessageJob < ApplicationJob operator_id, issue_title, issue_assigned_to_id, issue_author_id = args[0], args[1], args[2], args[3] operator = User.find_by_id(operator_id) return unless operator.present? - receivers = User.where(id: [issue_assigned_to_id, issue_author_id]).where.not(id: operator&.id) + if issue_assigned_to_id.is_a?(Array) + receivers = User.where(id: issue_assigned_to_id.append(issue_author_id)).where.not(id: operator&.id) + else + receivers = User.where(id: [issue_assigned_to_id, issue_author_id]).where.not(id: operator&.id) + end receivers_string, content, notification_url = MessageTemplate::IssueDeleted.get_message_content(receivers, operator, issue_title) Notice::Write::CreateService.call(receivers_string, content, notification_url, source, {operator_id: operator.id, issue_title: issue_title}) receivers.find_each do |receiver| diff --git a/app/libs/blockchain.rb b/app/libs/blockchain.rb new file mode 100644 index 000000000..e2c7804aa --- /dev/null +++ b/app/libs/blockchain.rb @@ -0,0 +1,20 @@ +class Blockchain + class << self + def blockchain_config + blockchain_config = {} + + begin + config = Rails.application.config_for(:configuration).symbolize_keys! + blockchain_config = config[:blockchain].symbolize_keys! + raise 'blockchain config missing' if blockchain_config.blank? + rescue => ex + raise ex if Rails.env.production? + + puts %Q{\033[33m [warning] blockchain config or configuration.yml missing, + please add it or execute 'cp config/configuration.yml.example config/configuration.yml' \033[0m} + blockchain_config = {} + end + blockchain_config + end + end +end \ No newline at end of file diff --git a/app/models/concerns/project_operable.rb b/app/models/concerns/project_operable.rb index 10b03cf72..0bac02ce6 100644 --- a/app/models/concerns/project_operable.rb +++ b/app/models/concerns/project_operable.rb @@ -194,7 +194,7 @@ module ProjectOperable if owner.is_a?(User) managers.exists?(user_id: user.id) elsif owner.is_a?(Organization) - managers.exists?(user_id: user.id) || owner.is_owner?(user.id) || owner.is_only_admin?(user.id) + managers.exists?(user_id: user.id) || owner.is_owner?(user.id) || (owner.is_only_admin?(user.id) && (teams.pluck(:id) & user.teams.pluck(:id)).size > 0) else false end @@ -205,7 +205,7 @@ module ProjectOperable if owner.is_a?(User) developers.exists?(user_id: user.id) elsif owner.is_a?(Organization) - developers.exists?(user_id: user.id) || owner.is_only_write?(user.id) + developers.exists?(user_id: user.id) || (owner.is_only_write?(user.id) && (teams.pluck(:id) & user.teams.pluck(:id)).size > 0) else false end diff --git a/app/models/concerns/watchable.rb b/app/models/concerns/watchable.rb index 008d382f3..dc2b67f67 100644 --- a/app/models/concerns/watchable.rb +++ b/app/models/concerns/watchable.rb @@ -1,45 +1,158 @@ -module Watchable - extend ActiveSupport::Concern - - included do - has_many :watchers, as: :watchable, dependent: :destroy - has_many :watcher_users, through: :watchers, source: :user, validate: false - - scope :watched_by, -> (user_id) { includes(:watchers).where(watchers: { user_id: user_id }) } - scope :following, -> (user_id) { watched_by(user_id) } - end - - def watched?(watchable) - watchable.watchers.exists?(user: self) - end - - def watch!(watchable) - watchable.watchers.create!(user: self, created_at: Time.current) - end - - def unwatch!(watchable) - obj = watchable.watchers.find_by(user: self) - obj.destroy! if obj.present? - end - - # 我正在关注的、我追随的 - def following - User.following(self.id) - end - - def following_count - following.size - end - - # 关注我的、我的粉丝、我的追随者 - def followers - watcher_users - end - - def followers_count - followers.size - end - - module ClassMethods - end -end +module Watchable + extend ActiveSupport::Concern + + included do + has_many :watchers, as: :watchable, dependent: :destroy + has_many :watcher_users, through: :watchers, source: :user, validate: false + + scope :watched_by, -> (user_id) { includes(:watchers).where(watchers: { user_id: user_id }) } + scope :following, -> (user_id) { watched_by(user_id) } + end + + def watched?(watchable) + watchable.watchers.exists?(user: self) + end + + def watch!(watchable) + watchable.watchers.create!(user: self, created_at: Time.current) + end + + def unwatch!(watchable) + obj = watchable.watchers.find_by(user: self) + obj.destroy! if obj.present? + end + + # 我正在关注的、我追随的 + def following + User.following(self.id) + end + + def following_count + following.size + end + + def contribution_perc(project) + @project = project + @user = self + + def cal_perc(count_user, count_all) + (count_user * 1.0 / (count_all + 0.000000001)).round(5) + end + + if @project['use_blockchain'] == true or @project['use_blockchain'] == 1 + balance_user = Blockchain::BalanceQueryOneProject.call({"user_id": @user.id, "project_id": @project.id}) + balance_all = Blockchain::RepoBasicInfo.call({"project_id": @project.id})["cur_supply"] + score = cal_perc(balance_user, balance_all) + else + # 获取所有行为对应的项目内记录总数和个人记录数 + features = { + "requirement" => {}, + "development" => {}, + "review" => {} + } + + # 1. issue创建 + issues = Issue.where(project_id: @project.id, issue_classify: 'issue') + issue_all = issues.count + issue_user = issues.where(author_id: @user.id).count + features["requirement"] = features["requirement"].merge({"issue" => {"all" => issue_all, "perc" => cal_perc(issue_user, issue_all)}}) + # 2. 里程碑创建 + milestones = Version.where(project_id: @project.id) + milestone_all = milestones.count + milestone_user = milestones.where(user_id: @user.id).count + features["requirement"] = features["requirement"].merge({"milestone" => {"all" => milestone_all, "perc" => cal_perc(milestone_user, milestone_all)}}) + # 3. issue评论 + issue_comments = Journal.joins("INNER JOIN issues on journals.journalized_id=issues.id").where("issues.project_id=#{@project.id} and journalized_type='Issue' and issues.issue_classify='issue'") + issue_comment_all = issue_comments.count + issue_comment_user = issue_comments.where("journals.user_id=#{@user.id}").count + features["requirement"] = features["requirement"].merge({"issue_comment" => {"all" => issue_comment_all, "perc" => cal_perc(issue_comment_user, issue_comment_all)}}) + # 4. 合并请求 + prs = PullRequest.where(project_id: @project.id) + pr_all = prs.count + pr_user = prs.where(user_id: @user.id).count + features["development"] = features["development"].merge({"pr" => {"all" => pr_all, "perc" => cal_perc(pr_user, pr_all)}}) + # 5. pr评论 + pr_comments = Journal.joins("INNER JOIN issues on journals.journalized_id=issues.id").where("issues.project_id=#{@project.id} and journalized_type='Issue' and issues.issue_classify='pull_request'") + pr_comment_all = pr_comments.count + pr_comment_user = pr_comments.where("journals.user_id=#{@user.id}").count + features["review"] = features["review"].merge({"pr_comment" => {"all" => pr_comment_all, "perc" => cal_perc(pr_comment_user, pr_comment_all)}}) + # 6. 代码行评论 + line_comments = Journal.joins("INNER JOIN pull_requests on journals.journalized_id=pull_requests.id").where("pull_requests.project_id=#{@project.id} and journalized_type='PullRequest'") + line_comment_all = line_comments.count + line_comment_user = line_comments.where("journals.user_id=#{@user.id}").count + features["review"] = features["review"].merge({"line_comment" => {"all" => line_comment_all, "perc" => cal_perc(line_comment_user, line_comment_all)}}) + # 7. 代码行、commit贡献统计 + code_contributions = Api::V1::Projects::CodeStats::ListService.call(@project, {ref: nil}) + commit_all = code_contributions["commit_count"] + addition_all = code_contributions["additions"] + deletion_all = code_contributions["deletions"] + + commit_user = 0 + addition_user = 0 + deletion_user = 0 + code_contributions["authors"].each do |author| + if author["name"] == @user.login + commit_user = author["commits"] + addition_user = author["additions"] + deletion_user = author["deletions"] + end + end + + features["development"] = features["development"].merge({"commit" => {"all" => commit_all, "perc" => cal_perc(commit_user, commit_all)}}) + features["development"] = features["development"].merge({"addition" => {"all" => addition_all, "perc" => cal_perc(addition_user, addition_all)}}) + features["development"] = features["development"].merge({"deletion" => {"all" => deletion_all, "perc" => cal_perc(deletion_user, deletion_all)}}) + + def cal_weight(features) + weights = {} # 计算每一项的权重 + categories = [] + features.each do |key, _| + categories << key + weights[key] = Hash.new + end + count_all = 0 + counts = {} + categories.each do |category| + count_1 = 0 + features[category].each do |_, value| + count_1 += value["all"] + end + count_all += count_1 + counts[category] = count_1 + features[category].each do |key, value| + weight = cal_perc(value["all"], count_1) + weights[category] = weights[category].merge({key => weight}) + end + end + categories.each do |category| + weight = cal_perc(counts[category], count_all) + weights[category] = weights[category].merge({"category_weight" => weight}) + end + return weights + end + + weights_categories = cal_weight(features) + score = 0.0 + features.each do |category, value_1| + category_score = 0.0 + value_1.each do |action, value_2| + category_score += weights_categories[category][action] * value_2["perc"] + end + score += weights_categories[category]["category_weight"] * category_score.round(4) + end + end + score + (score * 100).round(1).to_s + "%" + end + + # 关注我的、我的粉丝、我的追随者 + def followers + watcher_users + end + + def followers_count + followers.size + end + + module ClassMethods + end +end diff --git a/app/models/issue.rb b/app/models/issue.rb index a691f9e11..0fb5291e0 100644 --- a/app/models/issue.rb +++ b/app/models/issue.rb @@ -69,12 +69,26 @@ class Issue < ApplicationRecord has_many :issue_tags, through: :issue_tags_relates has_many :issue_times, dependent: :destroy has_many :issue_depends, dependent: :destroy + has_many :issue_assigners, dependent: :destroy + has_many :assigners, through: :issue_assigners + has_many :issue_participants, dependent: :destroy + has_many :participants, through: :issue_participants + has_many :show_participants, -> {joins(:issue_participants).where.not(issue_participants: {participant_type: "atme"}).distinct}, through: :issue_participants, source: :participant + has_many :show_assigners, -> {joins(:issue_assigners).distinct}, through: :issue_assigners, source: :assigner + has_many :show_issue_tags, -> {joins(:issue_tags_relates).distinct}, through: :issue_tags_relates, source: :issue_tag + + has_many :comment_journals, -> {where.not(notes: nil)}, class_name: "Journal", :as => :journalized + has_many :operate_journals, -> {where(notes: nil)}, class_name: "Journal", :as => :journalized + has_many :pull_attached_issues, dependent: :destroy + has_many :attach_pull_requests, through: :pull_attached_issues, source: :pull_request + scope :issue_includes, ->{includes(:user)} scope :issue_many_includes, ->{includes(journals: :user)} scope :issue_issue, ->{where(issue_classify: [nil,"issue"])} scope :issue_pull_request, ->{where(issue_classify: "pull_request")} scope :issue_index_includes, ->{includes(:tracker, :priority, :version, :issue_status, :journals,:issue_tags,user: :user_extension)} scope :closed, ->{where(status_id: 5)} + scope :opened, ->{where.not(status_id: 5)} after_create :incre_project_common, :incre_user_statistic, :incre_platform_statistic after_save :change_versions_count, :send_update_message_to_notice_system after_destroy :update_closed_issues_count_in_project!, :decre_project_common, :decre_user_statistic, :decre_platform_statistic diff --git a/app/models/issue_assigner.rb b/app/models/issue_assigner.rb new file mode 100644 index 000000000..a0836f214 --- /dev/null +++ b/app/models/issue_assigner.rb @@ -0,0 +1,20 @@ +# == Schema Information +# +# Table name: issue_assigners +# +# id :integer not null, primary key +# issue_id :integer +# assigner_id :integer +# created_at :datetime not null +# updated_at :datetime not null +# +# Indexes +# +# index_issue_assigners_on_assigner_id (assigner_id) +# index_issue_assigners_on_issue_id (issue_id) +# + +class IssueAssigner < ApplicationRecord + belongs_to :issue + belongs_to :assigner, class_name: "User" +end diff --git a/app/models/issue_participant.rb b/app/models/issue_participant.rb new file mode 100644 index 000000000..fa7be6980 --- /dev/null +++ b/app/models/issue_participant.rb @@ -0,0 +1,9 @@ +class IssueParticipant < ApplicationRecord + + belongs_to :issue + belongs_to :participant, class_name: "User" + + enum participant_type: {"authored": 0, "assigned": 1, "commented": 2, "edited": 3, "atme": 4} + + +end diff --git a/app/models/issue_priority.rb b/app/models/issue_priority.rb index 27865a70f..c8ef73299 100644 --- a/app/models/issue_priority.rb +++ b/app/models/issue_priority.rb @@ -15,4 +15,21 @@ class IssuePriority < ApplicationRecord has_many :issues + + def self.init_data + map = { + "1" => "低", + "2" => "正常", + "3" => "高", + "4" => "紧急" + } + IssuePriority.order(id: :asc).each do |prty| + if map["#{prty.id}"] == prty.name + IssuePriority.find_or_create_by(id: prty.id, name: prty.name) + else + Issue.where(priority_id: prty.id).each{|i| i.update_column(:priority_id, 2)} + prty.destroy! + end + end + end end diff --git a/app/models/issue_status.rb b/app/models/issue_status.rb index a58346ea7..fcce29c32 100644 --- a/app/models/issue_status.rb +++ b/app/models/issue_status.rb @@ -20,10 +20,28 @@ class IssueStatus < ApplicationRecord ADD = 1 SOLVING = 2 SOLVED = 3 - FEEDBACK = 4 + # FEEDBACK = 4 CLOSED = 5 REJECTED = 6 has_many :issues belongs_to :project, optional: true + + def self.init_data + map = { + "1" => "新增", + "2" => "正在解决", + "3" => "已解决", + "5" => "关闭", + "6" => "拒绝" + } + IssueStatus.order(id: :asc).each do |stat| + if map["#{stat.id}"] == stat.name + IssueStatus.find_or_create_by(id: stat.id, name: stat.name) + else + Issue.where(status_id: stat.id).each{|i| i.update_column(:status_id, 1)} + stat.destroy! + end + end + end end diff --git a/app/models/issue_tag.rb b/app/models/issue_tag.rb index bf2368654..c6b6af8aa 100644 --- a/app/models/issue_tag.rb +++ b/app/models/issue_tag.rb @@ -23,6 +23,34 @@ class IssueTag < ApplicationRecord has_many :issue_tags_relates, dependent: :destroy has_many :issues, through: :issue_tags_relates + has_many :issue_issues, -> {where(issue_classify: [nil,"issue"])}, source: :issue, through: :issue_tags_relates + has_many :pull_request_issues, -> {where(issue_classify: "pull_request")}, source: :issue, through: :issue_tags_relates belongs_to :project, optional: true, counter_cache: true + belongs_to :user, optional: true + + def self.init_data(project_id) + data = [ + ["缺陷", "表示项目存在问题", "#d92d4c"], + ["功能", "表示新功能申请", "#ee955a"], + ["疑问", "表示存在的问题", "#2d6ddc"], + ["支持", "表示特定功能或特定需求", "#019549"], + ["任务", "表示需要分配的任务", "#c1a30d"], + ["协助", "表示需要社区用户协助", "#2a0dc1"], + ["搁置", "表示此问题暂时不会继续处理", "#892794"], + ["文档", "表示文档材料补充", "#9ed600"], + ["测试", "表示需要测试的需求", "#2897b9"], + ["重复", "表示已存在类似的疑修", "#bb5332"] + ] + data.each do |item| + next if IssueTag.exists?(project_id: project_id, name: item[0]) + IssueTag.create!(project_id: project_id, name: item[0], description: item[1], color: item[2]) + end + $redis_cache.hset("project_init_issue_tags", project_id, 1) + end + + def reset_counter_field + self.update_column(:issues_count, issue_issues.size) + self.update_column(:pull_requests_count, pull_request_issues.size) + end end diff --git a/app/models/issue_tags_relate.rb b/app/models/issue_tags_relate.rb index df9fd81ae..fc753e95b 100644 --- a/app/models/issue_tags_relate.rb +++ b/app/models/issue_tags_relate.rb @@ -15,5 +15,29 @@ class IssueTagsRelate < ApplicationRecord belongs_to :issue - belongs_to :issue_tag, counter_cache: :issues_count + belongs_to :issue_tag + + after_create :increment_issue_tags_counter_cache + after_destroy :decrement_issue_tags_counter_cache + + def increment_issue_tags_counter_cache + Rails.logger.info "11111" + Rails.logger.info self.issue.issue_classify + + if self.issue.issue_classify == "issue" + IssueTag.increment_counter :issues_count, issue_tag_id + else + IssueTag.increment_counter :pull_requests_count, issue_tag_id + end + end + + def decrement_issue_tags_counter_cache + Rails.logger.info "2222222" + Rails.logger.info self.issue.issue_classify + if self.issue.issue_classify == "issue" + IssueTag.decrement_counter :issues_count, issue_tag_id + else + IssueTag.decrement_counter :pull_requests_count, issue_tag_id + end + end end diff --git a/app/models/journal.rb b/app/models/journal.rb index 20297dd99..a789f28cd 100644 --- a/app/models/journal.rb +++ b/app/models/journal.rb @@ -40,9 +40,12 @@ class Journal < ApplicationRecord belongs_to :journalized, polymorphic: true belongs_to :review, optional: true belongs_to :resolveer, class_name: 'User', foreign_key: :resolveer_id, optional: true + belongs_to :parent_journal, class_name: 'Journal', foreign_key: :parent_id, optional: true, counter_cache: :comments_count + belongs_to :reply_journal, class_name: 'Journal', foreign_key: :reply_id, optional: true has_many :journal_details, :dependent => :delete_all has_many :attachments, as: :container, dependent: :destroy - has_many :children_journals, class_name: 'Journal', foreign_key: :parent_id + has_many :first_ten_children_journals, -> { order(created_on: :asc).limit(10)}, class_name: 'Journal', foreign_key: :parent_id + has_many :children_journals, class_name: 'Journal', foreign_key: :parent_id, dependent: :destroy scope :journal_includes, ->{includes(:user, :journal_details, :attachments)} scope :parent_journals, ->{where(parent_id: nil)} @@ -54,6 +57,81 @@ class Journal < ApplicationRecord self.notes.blank? && self.journal_details.present? end + def operate_content + content = "" + detail = self.journal_details.take + case detail.property + when 'issue' + return "创建了疑修" + when 'attachment' + old_value = Attachment.where(id: detail.old_value.split(",")).pluck(:filename).join("、") + new_value = Attachment.where(id: detail.value.split(",")).pluck(:filename).join("、") + if old_value.nil? || old_value.blank? + content += "添加了#{new_value}附件" + else + new_value = "无" if new_value.blank? + content += "将附件由#{old_value}更改为#{new_value}" + end + when 'issue_tag' + old_value = IssueTag.where(id: detail.old_value.split(",")).pluck(:name).join("、") + new_value = IssueTag.where(id: detail.value.split(",")).pluck(:name).join("、") + if old_value.nil? || old_value.blank? + content += "添加了#{new_value}标记" + else + new_value = "无" if new_value.blank? + content += "将标记由#{old_value}更改为#{new_value}" + end + when 'assigner' + old_value = User.where(id: detail.old_value.split(",")).pluck(:nickname).join("、") + new_value = User.where(id: detail.value.split(",")).pluck(:nickname).join("、") + if old_value.nil? || old_value.blank? + content += "添加负责人#{new_value}" + else + new_value = "无" if new_value.blank? + content += "将负责人由#{old_value}更改为#{new_value}" + end + when 'attr' + content = "将" + case detail.prop_key + when 'subject' + return "修改了标题" + when 'description' + return "修改了描述" + when 'status_id' + old_value = IssueStatus.find_by_id(detail.old_value)&.name + new_value = IssueStatus.find_by_id(detail.value)&.name + content += "状态" + when 'priority_id' + old_value = IssuePriority.find_by_id(detail.old_value)&.name + new_value = IssuePriority.find_by_id(detail.value)&.name + content += "优先级" + when 'fixed_version_id' + old_value = Version.find_by_id(detail.old_value)&.name + new_value = Version.find_by_id(detail.value)&.name + content += "里程碑" + when 'branch_name' + old_value = detail.old_value + new_value = detail.value + content += "关联分支" + when 'start_date' + old_value = detail.old_value + new_value = detail.value + content += "开始日期" + when 'due_date' + old_value = detail.old_value + new_value = detail.value + content += "结束日期" + end + if old_value.nil? || old_value.blank? + content += "设置为#{new_value}" + else + new_value = "无" if new_value.blank? + content += "由#{old_value}更改为#{new_value}" + end + end + + end + def journal_content send_details = [] if self.is_journal_detail? diff --git a/app/models/message_template/issue_assigned.rb b/app/models/message_template/issue_assigned.rb index 7f8494f69..7973ed477 100644 --- a/app/models/message_template/issue_assigned.rb +++ b/app/models/message_template/issue_assigned.rb @@ -26,7 +26,7 @@ class MessageTemplate::IssueAssigned < MessageTemplate project = issue&.project owner = project&.owner content = sys_notice.gsub('{nickname1}', operator&.real_name).gsub('{nickname2}', owner&.real_name).gsub('{repository}', project&.name).gsub('{title}', issue&.subject) - url = notification_url.gsub('{owner}', owner&.login).gsub('{identifier}', project&.identifier).gsub('{id}', issue&.id.to_s) + url = notification_url.gsub('{owner}', owner&.login).gsub('{identifier}', project&.identifier).gsub('{id}', issue&.project_issues_index.to_s) return receivers_string(receivers), content, url rescue => e Rails.logger.info("MessageTemplate::IssueAssigned.get_message_content [ERROR] #{e}") @@ -52,7 +52,7 @@ class MessageTemplate::IssueAssigned < MessageTemplate content.gsub!('{repository}', project&.name) content.gsub!('{baseurl}', base_url) content.gsub!('{title}', issue&.subject) - content.gsub!('{id}', issue&.id.to_s) + content.gsub!('{id}', issue&.project_issues_index.to_s) content.gsub!('{platform}', PLATFORM) return receiver&.mail, title, content diff --git a/app/models/message_template/issue_assigner_expire.rb b/app/models/message_template/issue_assigner_expire.rb index 610c51175..8f9417a41 100644 --- a/app/models/message_template/issue_assigner_expire.rb +++ b/app/models/message_template/issue_assigner_expire.rb @@ -20,7 +20,7 @@ class MessageTemplate::IssueAssignerExpire < MessageTemplate project = issue&.project owner = project&.owner content = sys_notice.gsub('{title}', issue&.subject) - url = notification_url.gsub('{owner}', owner&.login).gsub('{identifier}', project&.identifier).gsub('{id}', issue&.id.to_s) + url = notification_url.gsub('{owner}', owner&.login).gsub('{identifier}', project&.identifier).gsub('{id}', issue&.project_issues_index.to_s) return receivers_string(receivers), content, url rescue => e Rails.logger.info("MessageTemplate::IssueAssignerExpire.get_message_content [ERROR] #{e}") diff --git a/app/models/message_template/issue_atme.rb b/app/models/message_template/issue_atme.rb index 04eb132e4..7709ed05f 100644 --- a/app/models/message_template/issue_atme.rb +++ b/app/models/message_template/issue_atme.rb @@ -20,7 +20,7 @@ class MessageTemplate::IssueAtme < MessageTemplate project = issue&.project owner = project&.owner content = sys_notice.gsub('{nickname}', operator&.real_name).gsub('{title}', issue&.subject) - url = notification_url.gsub('{owner}', owner&.login).gsub('{identifier}', project&.identifier).gsub('{id}', issue&.id.to_s) + url = notification_url.gsub('{owner}', owner&.login).gsub('{identifier}', project&.identifier).gsub('{id}', issue&.project_issues_index.to_s) return receivers_string(receivers), content, url rescue => e Rails.logger.info("MessageTemplate::IssueAtme.get_message_content [ERROR] #{e}") diff --git a/app/models/message_template/issue_changed.rb b/app/models/message_template/issue_changed.rb index e8a5e5cdb..43e2cee7d 100644 --- a/app/models/message_template/issue_changed.rb +++ b/app/models/message_template/issue_changed.rb @@ -27,20 +27,20 @@ class MessageTemplate::IssueChanged < MessageTemplate project = issue&.project owner = project&.owner content = MessageTemplate::IssueChanged.sys_notice.gsub('{nickname1}', operator&.real_name).gsub('{nickname2}', owner&.real_name).gsub('{repository}', project&.name).gsub('{title}', issue&.subject) - url = notification_url.gsub('{owner}', owner&.login).gsub('{identifier}', project&.identifier).gsub('{id}', issue&.id.to_s) + url = notification_url.gsub('{owner}', owner&.login).gsub('{identifier}', project&.identifier).gsub('{id}', issue&.project_issues_index.to_s) change_count = change_params.keys.size # 疑修负责人修改 if change_params[:assigned_to_id].present? - assigner1 = User.find_by_id(change_params[:assigned_to_id][0]) - assigner2 = User.find_by_id(change_params[:assigned_to_id][1]) + assigner1 = User.where(id: change_params[:assigned_to_id][0]) + assigner2 = User.where(id: change_params[:assigned_to_id][1]) if change_count > 1 content.sub!('{ifassigner}', '
') else content.sub!('{ifassigner}', '') end content.sub!('{endassigner}', '') - content.gsub!('{assigner1}', assigner1.present? ? assigner1&.real_name : '未指派成员') - content.gsub!('{assigner2}', assigner2.present? ? assigner2&.real_name : '未指派成员') + content.gsub!('{assigner1}', assigner1.present? ? assigner1.map{|a| a&.real_name}.join("、") : '未指派成员') + content.gsub!('{assigner2}', assigner2.present? ? assigner2.map{|a| a&.real_name}.join("、") : '未指派成员') else content.gsub!(/({ifassigner})(.*)({endassigner})/, '') end @@ -205,20 +205,20 @@ class MessageTemplate::IssueChanged < MessageTemplate content.gsub!('{identifier}', project&.identifier) content.gsub!('{repository}', project&.name) content.gsub!('{title}', issue&.subject) - content.gsub!('{id}', issue&.id.to_s) + content.gsub!('{id}', issue&.project_issues_index.to_s) change_count = change_params.keys.size # 疑修负责人修改 if change_params[:assigned_to_id].present? - assigner1 = User.find_by_id(change_params[:assigned_to_id][0]) - assigner2 = User.find_by_id(change_params[:assigned_to_id][1]) + assigner1 = User.where(id: change_params[:assigned_to_id][0]) + assigner2 = User.where(id: change_params[:assigned_to_id][1]) if change_count > 1 content.sub!('{ifassigner}', '
') else content.sub!('{ifassigner}', '') end content.sub!('{endassigner}', '') - content.gsub!('{assigner1}', assigner1.present? ? assigner1&.real_name : '未指派成员') - content.gsub!('{assigner2}', assigner2.present? ? assigner2&.real_name : '未指派成员') + content.gsub!('{assigner1}', assigner1.present? ? assigner1.map{|a| a&.real_name}.join("、") : '未指派成员') + content.gsub!('{assigner2}', assigner2.present? ? assigner2.map{|a| a&.real_name}.join("、") : '未指派成员') else content.gsub!(/({ifassigner})(.*)({endassigner})/, '') end diff --git a/app/models/message_template/issue_expire.rb b/app/models/message_template/issue_expire.rb index d77965f13..eedd53500 100644 --- a/app/models/message_template/issue_expire.rb +++ b/app/models/message_template/issue_expire.rb @@ -28,7 +28,7 @@ class MessageTemplate::IssueExpire < MessageTemplate project = issue&.project owner = project&.owner content = sys_notice.gsub('{title}', issue&.subject) - url = notification_url.gsub('{owner}', owner&.login).gsub('{identifier}', project&.identifier).gsub('{id}', issue&.id.to_s) + url = notification_url.gsub('{owner}', owner&.login).gsub('{identifier}', project&.identifier).gsub('{id}', issue&.project_issues_index.to_s) return receivers_string(receivers), content, url rescue => e @@ -53,7 +53,7 @@ class MessageTemplate::IssueExpire < MessageTemplate content.gsub!('{repository}', project&.name) content.gsub!('{baseurl}', base_url) content.gsub!('{title}', issue&.subject) - content.gsub!('{id}', issue&.id.to_s) + content.gsub!('{id}', issue&.project_issues_index.to_s) content.gsub!('{platform}', PLATFORM) return receiver&.mail, title, content diff --git a/app/models/message_template/project_issue.rb b/app/models/message_template/project_issue.rb index e04830836..e262cd589 100644 --- a/app/models/message_template/project_issue.rb +++ b/app/models/message_template/project_issue.rb @@ -27,7 +27,7 @@ class MessageTemplate::ProjectIssue < MessageTemplate receivers = managers + followers return '', '', '' if receivers.blank? content = sys_notice.gsub('{nickname1}', operator&.real_name).gsub('{nickname2}', owner&.real_name).gsub('{repository}', project&.name).gsub('{title}', issue&.subject) - url = notification_url.gsub('{owner}', owner&.login).gsub('{identifier}', project&.identifier).gsub('{id}', issue&.id.to_s) + url = notification_url.gsub('{owner}', owner&.login).gsub('{identifier}', project&.identifier).gsub('{id}', issue&.project_issues_index.to_s) return receivers_string(receivers), content, url rescue => e @@ -54,7 +54,7 @@ class MessageTemplate::ProjectIssue < MessageTemplate content.gsub!('{repository}', project&.name) content.gsub!('{login2}', owner&.login) content.gsub!('{identifier}', project&.identifier) - content.gsub!('{id}', issue&.id.to_s) + content.gsub!('{id}', issue&.project_issues_index.to_s) content.gsub!('{title}', issue&.subject) content.gsub!('{platform}', PLATFORM) diff --git a/app/models/organization.rb b/app/models/organization.rb index d61dda567..0432ba39b 100644 --- a/app/models/organization.rb +++ b/app/models/organization.rb @@ -156,6 +156,14 @@ class Organization < Owner organization_users.count end + def teams_count + teams.count + end + + def organization_users_count + organization_users.count + end + def real_name name = lastname + firstname name = name.blank? ? (nickname.blank? ? login : nickname) : name diff --git a/app/models/owner.rb b/app/models/owner.rb index 2763dc80f..d348970f0 100644 --- a/app/models/owner.rb +++ b/app/models/owner.rb @@ -69,6 +69,8 @@ class Owner < ApplicationRecord has_many :applied_transfer_projects, dependent: :destroy scope :like, lambda { |keywords| + # 表情处理 + keywords = keywords.to_s.each_char.select { |c| c.bytes.first < 240 }.join('') sql = "CONCAT(lastname, firstname) LIKE :search OR nickname LIKE :search OR login LIKE :search " where(sql, :search => "%#{keywords.strip}%") unless keywords.blank? } diff --git a/app/models/project.rb b/app/models/project.rb index e1670bf53..54d6ac520 100644 --- a/app/models/project.rb +++ b/app/models/project.rb @@ -240,6 +240,8 @@ class Project < ApplicationRecord end def self.search_project(search) + # 表情处理 + search = search.to_s.each_char.select { |c| c.bytes.first < 240 }.join('') ransack(name_or_identifier_cont: search) end # 创建者 @@ -421,4 +423,19 @@ class Project < ApplicationRecord raise("项目名称包含敏感词汇,请重新输入") if name && !HarmoniousDictionary.clean?(name) raise("项目描述包含敏感词汇,请重新输入") if description && !HarmoniousDictionary.clean?(description) end + + def get_last_project_issues_index + last_issue = self.issues.issue_issue.last + deleted_issue_count = ($redis_cache.hget("issue_cache_delete_count", self.id) || 0).to_i + + last_issue&.project_issues_index.present? ? last_issue.project_issues_index + deleted_issue_count : 0 + end + + def incre_project_issue_cache_delete_count(count=1) + $redis_cache.hincrby("issue_cache_delete_count", self.id, count) + end + + def del_project_issue_cache_delete_count + $redis_cache.hdel("issue_cache_delete_count", self.id) + end end diff --git a/app/models/pull_attached_issue.rb b/app/models/pull_attached_issue.rb new file mode 100644 index 000000000..abc6c3448 --- /dev/null +++ b/app/models/pull_attached_issue.rb @@ -0,0 +1,23 @@ +# == Schema Information +# +# Table name: pull_attached_issues +# +# id :integer not null, primary key +# pull_request_id :integer +# issue_id :integer +# created_at :datetime not null +# updated_at :datetime not null +# fixed :boolean default("0") +# +# Indexes +# +# index_pull_attached_issues_on_issue_id (issue_id) +# index_pull_attached_issues_on_pull_request_id (pull_request_id) +# + +class PullAttachedIssue < ApplicationRecord + + belongs_to :pull_request + belongs_to :issue + +end diff --git a/app/models/pull_request.rb b/app/models/pull_request.rb index 270e7dc76..648912f5a 100644 --- a/app/models/pull_request.rb +++ b/app/models/pull_request.rb @@ -44,6 +44,8 @@ class PullRequest < ApplicationRecord has_many :pull_requests_reviewers, dependent: :destroy has_many :reviewers, through: :pull_requests_reviewers has_many :mark_files, dependent: :destroy + has_many :pull_attached_issues, dependent: :destroy + has_many :attached_issues, through: :pull_attached_issues, source: :issue scope :merged_and_closed, ->{where.not(status: 0)} scope :opening, -> {where(status: 0)} diff --git a/app/models/site.rb b/app/models/site.rb index a8b725ef6..097306fb5 100644 --- a/app/models/site.rb +++ b/app/models/site.rb @@ -30,6 +30,10 @@ class Site < ApplicationRecord self.common.where(key: 'notice').present? end + def self.has_blockchain? + self.common.where(key: 'blockchain').present? + end + private def self.set_add_menu! adds= [ diff --git a/app/models/user.rb b/app/models/user.rb index b43e289ed..5e21212ab 100644 --- a/app/models/user.rb +++ b/app/models/user.rb @@ -178,9 +178,15 @@ class User < Owner has_many :user_trace_tasks, dependent: :destroy has_many :feedbacks, dependent: :destroy + has_many :issue_assigners, foreign_key: :assigner_id + has_many :assigned_issues, through: :issue_assigners, source: :issue + has_many :issue_participants, foreign_key: :participant_id + has_many :participant_issues, through: :issue_participants, source: :issue # Groups and active users scope :active, lambda { where(status: [STATUS_ACTIVE, STATUS_EDIT_INFO]) } scope :like, lambda { |keywords| + # 表情处理 + keywords = keywords.to_s.each_char.select { |c| c.bytes.first < 240 }.join('') sql = "CONCAT(lastname, firstname) LIKE :search OR nickname LIKE :search OR login LIKE :search OR mail LIKE :search OR nickname LIKE :search" where(sql, :search => "%#{keywords.strip}%") unless keywords.blank? } diff --git a/app/models/version.rb b/app/models/version.rb index 41256833a..1e14a135c 100644 --- a/app/models/version.rb +++ b/app/models/version.rb @@ -28,6 +28,9 @@ class Version < ApplicationRecord has_many :issues, class_name: "Issue", foreign_key: "fixed_version_id" belongs_to :user, optional: true + has_many :opened_issues, -> {where(issue_classify: "issue").where.not(status_id: 5)}, class_name: "Issue", foreign_key: :fixed_version_id + has_many :closed_issues, -> {where(issue_classify: "issue", status_id: 5)}, class_name: "Issue", foreign_key: :fixed_version_id + scope :version_includes, ->{includes(:issues, :user)} scope :closed, ->{where(status: 'closed')} scope :opening, ->{where(status: 'open')} @@ -43,6 +46,11 @@ class Version < ApplicationRecord after_create :send_create_message_to_notice_system after_save :send_update_message_to_notice_system + def issue_percent + issues_total_count = opened_issues.size + closed_issues.size + issues_total_count.zero? ? 0.0 : closed_issues.size.to_f / issues_total_count + end + def version_user User.select(:login, :lastname,:firstname, :nickname)&.find_by_id(self.user_id) end @@ -53,6 +61,6 @@ class Version < ApplicationRecord end def send_update_message_to_notice_system - SendTemplateMessageJob.perform_later('ProjectMilestoneCompleted', self.id) if Site.has_notice_menu? && self.percent == 1.0 + SendTemplateMessageJob.perform_later('ProjectMilestoneCompleted', self.id) if Site.has_notice_menu? && self.issue_percent == 1.0 end end diff --git a/app/queries/application_query.rb b/app/queries/application_query.rb index c66af94c0..e2d7c446f 100644 --- a/app/queries/application_query.rb +++ b/app/queries/application_query.rb @@ -6,4 +6,55 @@ class ApplicationQuery def strip_param(key) params[key].to_s.strip.presence end + + # find all the repos that a user has tokens + def find_repo_with_token(user_id, page=1, limit=10) + params = { + "request-type": "query user balance of all repos by page", + "username": user_id.to_s, + "page": page.to_i, + "page_num": limit.to_i + }.to_json + resp_body = Blockchain::InvokeBlockchainApi.call(params) + if resp_body['status'] != 0 + raise "区块链接口请求失败." + else + token_list = resp_body['UserBalanceList'].nil? ? [] : resp_body['UserBalanceList'] + return token_list, resp_body['total_count'] + end + end + + + # find one repo that a user has tokens + def find_one_balance(user_id, project_id) + # return 3 statuses: UnknownErr/ResUserNotExisted/Success + params = { + "request-type": "query user balance of single repo", + "username": user_id.to_s, + "token_name": project_id.to_s + }.to_json + resp_body = Blockchain::InvokeBlockchainApi.call(params) + if resp_body['status'] == 0 + return resp_body['balance'] + elsif resp_body['status'] == 100 + return 0 # 找不到用户返回0 + else + raise "区块链接口请求失败." + end + end + + # query the basic info of a repository + def find_blockchain_repo_info(project_id) + params = { + "request-type": "query repo basic info", + "token_name": project_id.to_s + }.to_json + resp_body = Blockchain::InvokeBlockchainApi.call(params) + if resp_body['status'] == 0 + return resp_body + else + raise "区块链接口请求失败." + end + end + end \ No newline at end of file diff --git a/app/queries/blockchain/balance_query.rb b/app/queries/blockchain/balance_query.rb new file mode 100644 index 000000000..f2c39c003 --- /dev/null +++ b/app/queries/blockchain/balance_query.rb @@ -0,0 +1,32 @@ +class Blockchain::BalanceQuery < ApplicationQuery + + attr_reader :params, :is_current_admin_user + + def initialize(params,is_current_admin_user) + @params = params + @is_current_admin_user = is_current_admin_user + end + + def call + if is_current_admin_user + token_list, total_count = find_repo_with_token(params["user_id"], (params["page"] || 1), (params["limit"] || 10)) + result_list = [] + token_list.each do |t| + project = Project.find_by(id: t['token_name'].to_i) + if project.nil? + result_list << {project: nil, balance: t['balance']} + next + end + owner = User.find_by(id: project.user_id) + if owner.nil? || project.nil? + else + balance = t['balance'] + result_list << {project: project, balance: balance} + end + end + results = {"status": 0, "projects": result_list, "total_count": total_count} + else + results = {"status": 1} # query failed + end + end +end diff --git a/app/queries/blockchain/balance_query_one_project.rb b/app/queries/blockchain/balance_query_one_project.rb new file mode 100644 index 000000000..c4ec19e21 --- /dev/null +++ b/app/queries/blockchain/balance_query_one_project.rb @@ -0,0 +1,12 @@ +class Blockchain::BalanceQueryOneProject < ApplicationQuery + + attr_reader :params, :is_current_admin_user + + def initialize(params) + @params = params + end + + def call + find_one_balance(params[:user_id].to_s, params[:project_id].to_s) + end +end diff --git a/app/queries/blockchain/repo_basic_info.rb b/app/queries/blockchain/repo_basic_info.rb new file mode 100644 index 000000000..df17b7a04 --- /dev/null +++ b/app/queries/blockchain/repo_basic_info.rb @@ -0,0 +1,13 @@ +class Blockchain::RepoBasicInfo < ApplicationQuery + + attr_reader :params, :is_current_admin_user + + def initialize(params) + @params = params + end + + def call + info = find_blockchain_repo_info(params[:project_id].to_s) + return info + end +end diff --git a/app/queries/projects/list_my_query.rb b/app/queries/projects/list_my_query.rb index 6c7f38d9c..31c17846a 100644 --- a/app/queries/projects/list_my_query.rb +++ b/app/queries/projects/list_my_query.rb @@ -38,6 +38,12 @@ class Projects::ListMyQuery < ApplicationQuery # projects = projects.visible.joins(:members).where(members: { user_id: user.id }) # elsif params[:category].to_s == "private" # projects = projects.is_private.joins(:members).where(members: { user_id: user.id }) + elsif params[:category].to_s == "blockchain_token" # 所有钱包中有token的项目有哪些 + token_list, total_count = find_repo_with_token(user.id) + project_names = token_list.map { |x| x['token_name'] } + projects = projects.where(name: project_names) + tokens = token_list.map { |x| x['balance'] } + puts "pause" end if params[:is_public].present? @@ -52,8 +58,10 @@ class Projects::ListMyQuery < ApplicationQuery elsif params[:project_type].to_s === "sync_mirror" projects = projects.sync_mirror end - - q = projects.ransack(name_or_identifier_cont: params[:search]) + + # 表情处理 + keywords = params[:search].to_s.each_char.select { |c| c.bytes.first < 240 }.join('') + q = projects.ransack(name_or_identifier_cont: keywords) scope = q.result.includes(:project_category, :project_language,:owner, :repository, :has_pinned_users) diff --git a/app/queries/projects/list_query.rb b/app/queries/projects/list_query.rb index 6b0843540..2b048bd87 100644 --- a/app/queries/projects/list_query.rb +++ b/app/queries/projects/list_query.rb @@ -51,7 +51,9 @@ class Projects::ListQuery < ApplicationQuery # items = items.where(id: @ids).by_name_or_identifier(params[:search]) items = items.where(id: @ids) else - items = items.by_name_or_identifier(params[:search]).or(main_collection.where(user_id: Owner.like(params[:search]).pluck(:id))) + # 表情处理 + keywords = params[:search].to_s.each_char.select { |c| c.bytes.first < 240 }.join('') + items = items.by_name_or_identifier(keywords).or(main_collection.where(user_id: Owner.like(keywords).pluck(:id))) end items end diff --git a/app/services/admins/delete_organization_service.rb b/app/services/admins/delete_organization_service.rb index f5760b364..d5c9bd2c5 100644 --- a/app/services/admins/delete_organization_service.rb +++ b/app/services/admins/delete_organization_service.rb @@ -6,9 +6,13 @@ class Admins::DeleteOrganizationService < Gitea::ClientService end def call + response = delete(url, params) + render_status(response) + Gitea::Organization::DeleteService.call(token,name) end + private def token { diff --git a/app/services/api/v1/issues/batch_delete_service.rb b/app/services/api/v1/issues/batch_delete_service.rb new file mode 100644 index 000000000..45821b373 --- /dev/null +++ b/app/services/api/v1/issues/batch_delete_service.rb @@ -0,0 +1,38 @@ +class Api::V1::Issues::BatchDeleteService < ApplicationService + include ActiveModel::Model + + attr_reader :project, :issues, :current_user + + validates :project, :issues, :current_user, presence: true + + def initialize(project, issues, current_user = nil) + @project = project + @issues = issues.includes(:assigners) + @current_user = current_user + end + + def call + raise Error, errors.full_messages.join(", ") unless valid? + try_lock("Api::V1::Issues::DeleteService:#{project.id}") # 开始写数据,加锁 + + delete_issues + + project.incre_project_issue_cache_delete_count(@issues.size) + + if Site.has_notice_menu? + @issues.each do |issue| + SendTemplateMessageJob.perform_later('IssueDeleted', current_user.id, @issue&.subject, @issue.assigners.pluck(:id), @issue.author_id) + end + end + + unlock("Api::V1::Issues::DeleteService:#{project.id}") + + return true + end + + private + + def delete_issues + raise Error, "批量删除疑修失败!" unless @issues.destroy_all + end +end \ No newline at end of file diff --git a/app/services/api/v1/issues/batch_update_service.rb b/app/services/api/v1/issues/batch_update_service.rb new file mode 100644 index 000000000..ccf783dca --- /dev/null +++ b/app/services/api/v1/issues/batch_update_service.rb @@ -0,0 +1,33 @@ +class Api::V1::Issues::BatchUpdateService < ApplicationService + include ActiveModel::Model + include Api::V1::Issues::Concerns::Checkable + include Api::V1::Issues::Concerns::Loadable + + attr_reader :project, :issues, :params, :current_user + attr_reader :status_id, :priority_id, :milestone_id + attr_reader :issue_tag_ids, :assigner_ids + + validates :project, :issues, :current_user, presence: true + + def initialize(project, issues, params, current_user = nil) + @project = project + @issues = issues + @params = params + @current_user = current_user + end + + def call + raise Error, errors.full_messages.join(", ") unless valid? + ActiveRecord::Base.transaction do + @issues.each do |issue| + if issue.issue_classify == "issue" + Api::V1::Issues::UpdateService.call(project, issue, params, current_user) + end + end + + return true + end + end + + +end \ No newline at end of file diff --git a/app/services/api/v1/issues/concerns/checkable.rb b/app/services/api/v1/issues/concerns/checkable.rb new file mode 100644 index 000000000..b19c245ed --- /dev/null +++ b/app/services/api/v1/issues/concerns/checkable.rb @@ -0,0 +1,53 @@ +module Api::V1::Issues::Concerns::Checkable + + def check_issue_status(status_id) + raise ApplicationService::Error, "IssueStatus不存在!" unless IssueStatus.find_by_id(status_id).present? + end + + def check_issue_priority(priority_id) + raise ApplicationService::Error, "IssuePriority不存在!" unless IssuePriority.find_by_id(priority_id).present? + end + + def check_milestone(milestone_id) + raise ApplicationService::Error, "Milestone不存在!" unless Version.find_by_id(milestone_id).present? + end + + def check_issue_tags(issue_tag_ids) + raise ApplicationService::Error, "请输入正确的标记ID数组!" unless issue_tag_ids.is_a?(Array) + raise ApplicationService::Error, "最多可选择3个标记" if issue_tag_ids.size > 3 + issue_tag_ids.each do |tid| + raise ApplicationService::Error, "请输入正确的标记ID!" unless IssueTag.exists?(id: tid) + end + end + + def check_assigners(assigner_ids) + raise ApplicationService::Error, "请输入正确的负责人ID数组!" unless assigner_ids.is_a?(Array) + raise ApplicationService::Error, "最多可选择5个负责人" if assigner_ids.size > 5 + assigner_ids.each do |aid| + raise ApplicationService::Error, "请输入正确的负责人ID!" unless User.exists?(id: aid) + end + end + + def check_attachments (attachment_ids) + raise ApplicationService::Error, "请输入正确的附件ID数组!" unless attachment_ids.is_a?(Array) + attachment_ids.each do |aid| + raise ApplicationService::Error, "请输入正确的附件ID!" unless Attachment.exists?(id: aid) + end + end + + def check_atme_receivers(receivers_login) + raise ApplicationService::Error, "请输入正确的用户标识数组!" unless receivers_login.is_a?(Array) + receivers_login.each do |rlogin| + raise ApplicationService::Error, "请输入正确的用户标识!" unless User.exists?(login: rlogin) + end + end + + def check_parent_journal(parent_id) + raise ApplicationService::Error, "ParentJournal不存在!" unless Journal.find_by_id(parent_id).present? + end + + def check_blockchain_token_num(user_id, project_id, blockchain_token_num, now_blockchain_token_num=0) + left_blockchain_token_num = Blockchain::BalanceQueryOneProject.call({"user_id": user_id, "project_id": project_id}) rescue 0 + raise ApplicationService::Error, "用户Token不足。" if blockchain_token_num.to_i > (left_blockchain_token_num+now_blockchain_token_num).to_i + end +end diff --git a/app/services/api/v1/issues/concerns/loadable.rb b/app/services/api/v1/issues/concerns/loadable.rb new file mode 100644 index 000000000..df30042e0 --- /dev/null +++ b/app/services/api/v1/issues/concerns/loadable.rb @@ -0,0 +1,19 @@ +module Api::V1::Issues::Concerns::Loadable + + def load_assigners(assigner_ids) + @assigners = User.where(id: assigner_ids) + end + + def load_issue_tags(issue_tag_ids) + @issue_tags = IssueTag.where(id: issue_tag_ids) + end + + def load_attachments(attachment_ids) + @attachments = Attachment.where(id: attachment_ids) + end + + def load_atme_receivers(receivers_login) + @atme_receivers = User.where(login: receivers_login) + end + +end \ No newline at end of file diff --git a/app/services/api/v1/issues/create_service.rb b/app/services/api/v1/issues/create_service.rb new file mode 100644 index 000000000..41b8ff64f --- /dev/null +++ b/app/services/api/v1/issues/create_service.rb @@ -0,0 +1,142 @@ +class Api::V1::Issues::CreateService < ApplicationService + include ActiveModel::Model + include Api::V1::Issues::Concerns::Checkable + include Api::V1::Issues::Concerns::Loadable + + attr_reader :project, :current_user + attr_reader :status_id, :priority_id, :milestone_id, :branch_name, :start_date, :due_date, :subject, :description, :blockchain_token_num + attr_reader :issue_tag_ids, :assigner_ids, :attachment_ids, :receivers_login + attr_accessor :created_issue + + validates :subject, presence: true + validates :status_id, :priority_id, presence: true + validates :project, :current_user, presence: true + validates :blockchain_token_num, numericality: {greater_than: 0}, allow_blank: true + + def initialize(project, params, current_user = nil) + @project = project + @current_user = current_user + @status_id = params[:status_id] + @priority_id = params[:priority_id] + @milestone_id = params[:milestone_id] + @branch_name = params[:branch_name] + @start_date = params[:start_date] + @due_date = params[:due_date] + @subject = params[:subject] + @description = params[:description] + @blockchain_token_num = params[:blockchain_token_num] + @issue_tag_ids = params[:issue_tag_ids] + @assigner_ids = params[:assigner_ids] + @attachment_ids = params[:attachment_ids] + @receivers_login = params[:receivers_login] + end + + def call + raise Error, errors.full_messages.join(", ") unless valid? + ActiveRecord::Base.transaction do + check_issue_status(status_id) + check_issue_priority(priority_id) + check_milestone(milestone_id) if milestone_id.present? + check_issue_tags(issue_tag_ids) unless issue_tag_ids.blank? + check_assigners(assigner_ids) unless assigner_ids.blank? + check_attachments(attachment_ids) unless attachment_ids.blank? + check_atme_receivers(receivers_login) unless receivers_login.blank? + check_blockchain_token_num(current_user.id, project.id, blockchain_token_num) if blockchain_token_num.present? + load_assigners(assigner_ids) unless assigner_ids.blank? + load_attachments(attachment_ids) unless attachment_ids.blank? + load_issue_tags(issue_tag_ids) unless issue_tag_ids.blank? + load_atme_receivers(receivers_login) unless receivers_login.blank? + + try_lock("Api::V1::Issues::CreateService:#{project.id}") # 开始写数据,加锁 + @created_issue = Issue.new(issue_attributes) + build_author_participants + build_assigner_participants unless assigner_ids.blank? + build_atme_participants if @atme_receivers.present? + build_issue_journal_details + build_issue_project_trends + @created_issue.assigners = @assigners unless assigner_ids.blank? + @created_issue.attachments = @attachments unless attachment_ids.blank? + @created_issue.issue_tags = @issue_tags unless issue_tag_ids.blank? + + @created_issue.issue_tags_value = @issue_tags.order("id asc").pluck(:id).join(",") unless issue_tag_ids.blank? + @created_issue.save! + + if Site.has_blockchain? && @project.use_blockchain + if @created_issue.blockchain_token_num.present? && @created_issue.blockchain_token_num > 0 + Blockchain::CreateIssue.call({user_id: current_user.id, project_id: @created_issue.project_id, token_num: @created_issue.blockchain_token_num}) + end + + push_activity_2_blockchain("issue_create", @created_issue) + end + + project.del_project_issue_cache_delete_count # 把缓存里存储项目删除issue的个数清除掉 + + # 新增时向grimoirelab推送事件 + IssueWebhookJob.set(wait: 5.seconds).perform_later(@created_issue.id) + + # @信息发送 + AtmeService.call(current_user, @atme_receivers, @created_issue) unless receivers_login.blank? + + # 发消息 + if Site.has_notice_menu? + SendTemplateMessageJob.perform_later('IssueAssigned', current_user.id, @created_issue&.id, assigner_ids) unless assigner_ids.blank? + SendTemplateMessageJob.perform_later('ProjectIssue', current_user.id, @created_issue&.id) + end + + unlock("Api::V1::Issues::CreateService:#{project.id}") # 结束写数据,解锁 + end + + return @created_issue + end + + private + + def issue_attributes + issue_attributes = { + subject: subject, + project_id: project.id, + author_id: current_user.id, + tracker_id: Tracker.first.id, + status_id: status_id, + priority_id: priority_id, + project_issues_index: (project.get_last_project_issues_index + 1), + issue_type: "1", + issue_classify: "issue" + } + + issue_attributes.merge!({description: description}) if description.present? + issue_attributes.merge!({fixed_version_id: milestone_id}) if milestone_id.present? + issue_attributes.merge!({start_date: start_date}) if start_date.present? + issue_attributes.merge!({due_date: due_date}) if due_date.present? + issue_attributes.merge!({branch_name: branch_name}) if branch_name.present? + issue_attributes.merge!({blockchain_token_num: blockchain_token_num}) if blockchain_token_num.present? + + issue_attributes + end + + def build_author_participants + @created_issue.issue_participants.new({participant_type: "authored", participant_id: current_user.id}) + end + + def build_assigner_participants + assigner_ids.each do |aid| + @created_issue.issue_participants.new({participant_type: "assigned", participant_id: aid}) + end + end + + def build_atme_participants + @atme_receivers.each do |receiver| + @created_issue.issue_participants.new({participant_type: "atme", participant_id: receiver.id}) + end + end + + def build_issue_project_trends + @created_issue.project_trends.new({user_id: current_user.id, project_id: @project.id, action_type: "create"}) + @created_issue.project_trends.new({user_id: current_user.id, project_id: @project.id, action_type: ProjectTrend::CLOSE}) if status_id.to_i == 5 + end + + def build_issue_journal_details + journal = @created_issue.journals.new({user_id: current_user.id}) + journal.journal_details.new({property: "issue", prop_key: 1, old_value: '', value: ''}) + end +end \ No newline at end of file diff --git a/app/services/api/v1/issues/delete_service.rb b/app/services/api/v1/issues/delete_service.rb new file mode 100644 index 000000000..b62733181 --- /dev/null +++ b/app/services/api/v1/issues/delete_service.rb @@ -0,0 +1,41 @@ +class Api::V1::Issues::DeleteService < ApplicationService + include ActiveModel::Model + + attr_reader :project, :issue, :current_user + + validates :project, :issue, :current_user, presence: true + + def initialize(project, issue, current_user = nil) + @project = project + @issue = issue + @current_user = current_user + end + + def call + raise Error, errors.full_messages.join(", ") unless valid? + try_lock("Api::V1::Issues::DeleteService:#{project.id}") # 开始写数据,加锁 + + delete_issue + + project.incre_project_issue_cache_delete_count + + if Site.has_blockchain? && @project.use_blockchain + unlock_balance_on_blockchain(@issue.author_id.to_s, @project.id.to_s, @issue.blockchain_token_num.to_i) if @issue.blockchain_token_num.present? + end + + if Site.has_notice_menu? + SendTemplateMessageJob.perform_later('IssueDeleted', current_user.id, @issue&.subject, @issue.assigners.pluck(:id), @issue.author_id) + end + + unlock("Api::V1::Issues::DeleteService:#{project.id}") + + return true + end + + private + + def delete_issue + raise Error, "删除疑修失败!" unless issue.destroy! + end + +end \ No newline at end of file diff --git a/app/services/api/v1/issues/journals/children_list_service.rb b/app/services/api/v1/issues/journals/children_list_service.rb new file mode 100644 index 000000000..d46f9fbbe --- /dev/null +++ b/app/services/api/v1/issues/journals/children_list_service.rb @@ -0,0 +1,42 @@ +class Api::V1::Issues::Journals::ChildrenListService < ApplicationService + + include ActiveModel::Model + + attr_reader :issue, :journal, :keyword, :sort_by, :sort_direction + attr_accessor :queried_journals + + validates :sort_by, inclusion: {in: Journal.column_names, message: '请输入正确的SortBy'}, allow_blank: true + validates :sort_direction, inclusion: {in: %w(asc desc), message: '请输入正确的SortDirection'}, allow_blank: true + + + def initialize(issue, journal, params, current_user=nil) + @issue = issue + @journal = journal + @keyword = params[:keyword] + @sort_by = params[:sort_by].present? ? params[:sort_by] : 'created_on' + @sort_direction = (params[:sort_direction].present? ? params[:sort_direction] : 'asc').downcase + end + + def call + raise Error, errors.full_messages.join(", ") unless valid? + begin + journal_query_data + + return @queried_journals + rescue + raise Error, "服务器错误,请联系系统管理员!" + + end + end + + private + def journal_query_data + @queried_journals = journal.children_journals + + @queried_journals = @queried_journals.ransack(notes_cont: keyword).result if keyword.present? + @queried_journals = @queried_journals.includes(:user, :attachments, :reply_journal) + @queried_journals = @queried_journals.reorder("journals.#{sort_by} #{sort_direction}").distinct + + @queried_journals + end +end \ No newline at end of file diff --git a/app/services/api/v1/issues/journals/create_service.rb b/app/services/api/v1/issues/journals/create_service.rb new file mode 100644 index 000000000..31ecc00cd --- /dev/null +++ b/app/services/api/v1/issues/journals/create_service.rb @@ -0,0 +1,77 @@ +class Api::V1::Issues::Journals::CreateService < ApplicationService + include ActiveModel::Model + include Api::V1::Issues::Concerns::Checkable + include Api::V1::Issues::Concerns::Loadable + + attr_reader :issue, :current_user, :notes, :parent_id, :reply_id, :attachment_ids, :receivers_login + attr_accessor :created_journal, :atme_receivers + + validates :notes, :issue, :current_user, presence: true + + def initialize(issue, params, current_user=nil) + @issue = issue + @notes = params[:notes] + @parent_id = params[:parent_id] + @reply_id = params[:reply_id] + @attachment_ids = params[:attachment_ids] + @receivers_login = params[:receivers_login] + @current_user = current_user + end + + def call + raise Error, errors.full_messages.join(", ") unless valid? + raise Error, "请输入回复的评论ID" if parent_id.present? && !reply_id.present? + ActiveRecord::Base.transaction do + check_parent_journal(parent_id) if parent_id.present? + check_parent_journal(reply_id) if reply_id.present? + check_attachments(attachment_ids) unless attachment_ids.nil? + check_atme_receivers(receivers_login) unless receivers_login.nil? + load_attachments(attachment_ids) unless attachment_ids.nil? + load_atme_receivers(receivers_login) unless receivers_login.nil? + + try_lock("Api::V1::Issues::Journals::CreateService:#{@issue.id}") + @created_journal = @issue.journals.new(journal_attributes) + + build_comment_participants + build_atme_participants if @atme_receivers.present? + @created_journal.attachments = @attachments unless attachment_ids.blank? + + @created_journal.save! + @issue.save! + + push_activity_2_blockchain("issue_comment_create", @created_journal) if Site.has_blockchain? && @issue.project&.use_blockchain + + # @信息发送 + AtmeService.call(current_user, @atme_receivers, @created_journal) unless receivers_login.blank? + + unlock("Api::V1::Issues::Journals::CreateService:#{@issue.id}") + + @created_journal + end + end + + private + + def journal_attributes + journal_attributes = { + notes: notes, + user_id: current_user.id + } + + journal_attributes.merge!({parent_id: parent_id}) if parent_id.present? + journal_attributes.merge!({reply_id: reply_id}) if reply_id.present? + + journal_attributes + end + + def build_comment_participants + @issue.issue_participants.new({participant_type: "commented", participant_id: current_user.id}) unless @issue.issue_participants.exists?(participant_type: "commented", participant_id: current_user.id) + end + + def build_atme_participants + @atme_receivers.each do |receiver| + next if @issue.issue_participants.exists?(participant_type: "atme", participant_id: receiver.id) + @issue.issue_participants.new({participant_type: "atme", participant_id: receiver.id}) + end + end +end \ No newline at end of file diff --git a/app/services/api/v1/issues/journals/list_service.rb b/app/services/api/v1/issues/journals/list_service.rb new file mode 100644 index 000000000..486fa5d3f --- /dev/null +++ b/app/services/api/v1/issues/journals/list_service.rb @@ -0,0 +1,56 @@ +class Api::V1::Issues::Journals::ListService < ApplicationService + + include ActiveModel::Model + + attr_reader :issue, :category, :keyword, :sort_by, :sort_direction + attr_accessor :queried_journals, :total_journals_count, :total_operate_journals_count, :total_comment_journals_count + + validates :category, inclusion: {in: %w(all comment operate), message: "请输入正确的Category"} + validates :sort_by, inclusion: {in: Journal.column_names, message: '请输入正确的SortBy'}, allow_blank: true + validates :sort_direction, inclusion: {in: %w(asc desc), message: '请输入正确的SortDirection'}, allow_blank: true + + def initialize(issue, params, current_user=nil) + @issue = issue + @keyword = params[:keyword] + @category = params[:category] || 'all' + @sort_by = params[:sort_by].present? ? params[:sort_by] : 'created_on' + @sort_direction = (params[:sort_direction].present? ? params[:sort_direction] : 'asc').downcase + end + + def call + raise Error, errors.full_messages.join(", ") unless valid? + begin + journal_query_data + + {data: @queried_journals, total_journals_count: @total_journals_count, total_operate_journals_count: total_operate_journals_count, total_comment_journals_count: total_comment_journals_count} + rescue + raise Error, "服务器错误,请联系系统管理员!" + end + end + + private + def journal_query_data + + @queried_journals = issue.journals + + @queried_journals = @queried_journals.parent_journals + + @queried_journals = @queried_journals.ransack(notes_cont: keyword).result if keyword.present? + + @total_journals_count = queried_journals.distinct.size + @total_operate_journals_count = @queried_journals.where(notes: nil).distinct.size + @total_comment_journals_count = @queried_journals.where.not(notes: nil).distinct.size + + case category + when 'comment' + @queried_journals = @queried_journals.where.not(notes: nil) + when 'operate' + @queried_journals = @queried_journals.where(notes: nil) + end + + @queried_journals = @queried_journals.includes(:journal_details, :user, :attachments, first_ten_children_journals: [:parent_journal, :reply_journal]) + @queried_journals = @queried_journals.reorder("journals.#{sort_by} #{sort_direction}").distinct + + @queried_journals + end +end \ No newline at end of file diff --git a/app/services/api/v1/issues/journals/update_service.rb b/app/services/api/v1/issues/journals/update_service.rb new file mode 100644 index 000000000..e5031aafe --- /dev/null +++ b/app/services/api/v1/issues/journals/update_service.rb @@ -0,0 +1,57 @@ +class Api::V1::Issues::Journals::UpdateService < ApplicationService + include ActiveModel::Model + include Api::V1::Issues::Concerns::Checkable + include Api::V1::Issues::Concerns::Loadable + + attr_reader :issue, :journal, :current_user, :notes, :attachment_ids, :receivers_login + attr_accessor :updated_journal, :atme_receivers + + validates :notes, :issue, :journal, :current_user, presence: true + + def initialize(issue, journal, params, current_user=nil) + @issue = issue + @journal = journal + @notes = params[:notes] + @attachment_ids = params[:attachment_ids] + @receivers_login = params[:receivers_login] + @current_user = current_user + end + + def call + raise Error, errors.full_messages.join(", ") unless valid? + ActiveRecord::Base.transaction do + check_attachments(attachment_ids) unless attachment_ids.nil? + check_atme_receivers(receivers_login) unless receivers_login.nil? + load_attachments(attachment_ids) unless attachment_ids.nil? + load_atme_receivers(receivers_login) unless receivers_login.nil? + + try_lock("Api::V1::Issues::Journals::UpdateService:#{@issue.id}:#{@journal.id}") + @updated_journal = @journal + @updated_journal.notes = notes + + build_atme_participants if @atme_receivers.present? + + @updated_journal.attachments = @attachments unless attachment_ids.nil? + + @updated_journal.save! + @issue.save! + + # @信息发送 + AtmeService.call(current_user, @atme_receivers, @created_journal) unless receivers_login.blank? + + unlock("Api::V1::Issues::Journals::UpdateService:#{@issue.id}:#{@journal.id}") + + @updated_journal + end + end + + private + + def build_atme_participants + @atme_receivers.each do |receiver| + next if @issue.issue_participants.exists?(participant_type: "atme", participant_id: receiver.id) + @issue.issue_participants.new({participant_type: "atme", participant_id: receiver.id}) + end + end + +end \ No newline at end of file diff --git a/app/services/api/v1/issues/list_service.rb b/app/services/api/v1/issues/list_service.rb new file mode 100644 index 000000000..faf1c1c31 --- /dev/null +++ b/app/services/api/v1/issues/list_service.rb @@ -0,0 +1,96 @@ +class Api::V1::Issues::ListService < ApplicationService + include ActiveModel::Model + + attr_reader :project, :only_name, :category, :participant_category, :keyword, :author_id, :issue_tag_ids + attr_reader :milestone_id, :assigner_id, :status_id, :sort_by, :sort_direction, :current_user + attr_accessor :queried_issues, :total_issues_count, :closed_issues_count, :opened_issues_count + + validates :category, inclusion: {in: %w(all opened closed), message: "请输入正确的Category"} + validates :participant_category, inclusion: {in: %w(all aboutme authoredme assignedme atme), message: "请输入正确的ParticipantCategory"} + validates :sort_by, inclusion: {in: ['issues.created_on', 'issues.updated_on', 'issues.blockchain_token_num', 'issue_priorities.position'], message: '请输入正确的SortBy'}, allow_blank: true + validates :sort_direction, inclusion: {in: %w(asc desc), message: '请输入正确的SortDirection'}, allow_blank: true + validates :current_user, presence: true + + def initialize(project, params, current_user=nil) + @project = project + @only_name = params[:only_name] + @category = params[:category] || 'all' + @participant_category = params[:participant_category] || 'all' + @keyword = params[:keyword] + @author_id = params[:author_id] + @issue_tag_ids = params[:issue_tag_ids].present? ? params[:issue_tag_ids].split(",") : [] + @milestone_id = params[:milestone_id] + @assigner_id = params[:assigner_id] + @status_id = params[:status_id] + @sort_by = params[:sort_by].present? ? params[:sort_by] : 'issues.updated_on' + @sort_direction = (params[:sort_direction].present? ? params[:sort_direction] : 'desc').downcase + @current_user = current_user + end + + def call + raise Error, errors.full_messages.join(", ") unless valid? + # begin + issue_query_data + + return {data: queried_issues, total_issues_count: @total_issues_count, closed_issues_count: @closed_issues_count, opened_issues_count: @opened_issues_count} + # rescue + # raise Error, "服务器错误,请联系系统管理员!" + # end + end + + private + def issue_query_data + issues = @project.issues.issue_issue + + case participant_category + when 'aboutme' # 关于我的 + issues = issues.joins(:issue_participants).where(issue_participants: {participant_type: %w(authored assigned atme), participant_id: current_user&.id}) + when 'authoredme' # 我创建的 + issues = issues.joins(:issue_participants).where(issue_participants: {participant_type: 'authored', participant_id: current_user&.id}) + when 'assignedme' # 我负责的 + issues = issues.joins(:issue_participants).where(issue_participants: {participant_type: 'assigned', participant_id: current_user&.id}) + when 'atme' # @我的 + issues = issues.joins(:issue_participants).where(issue_participants: {participant_type: 'atme', participant_id: current_user&.id}) + end + + # author_id + issues = issues.where(author_id: author_id) if author_id.present? + + # issue_tag_ids + issues = issues.ransack(issue_tags_value_cont: issue_tag_ids.sort!.join(",")).result unless issue_tag_ids.blank? + + # milestone_id + issues = issues.where(fixed_version_id: milestone_id) if milestone_id.present? + + # assigner_id + issues = issues.joins(:assigners).where(users: {id: assigner_id}) if assigner_id.present? + + # status_id + issues = issues.where(status_id: status_id) if status_id.present? + + # keyword + issues = issues.ransack(id_eq: keyword).result.or(issues.ransack(subject_or_description_cont: keyword).result) if keyword.present? + + @total_issues_count = issues.distinct.size + @closed_issues_count = issues.closed.distinct.size + @opened_issues_count = issues.opened.distinct.size + + case category + when 'closed' + issues = issues.closed + when 'opened' + issues = issues.opened + end + + if only_name.present? + scope = issues.select(:id, :subject, :project_issues_index) + scope = scope.reorder("project_issues_index asc").distinct + else + scope = issues.includes(:priority, :issue_status, :user, :show_assigners, :show_issue_tags, :version, :comment_journals) + scope = scope.reorder("#{sort_by} #{sort_direction}").distinct + end + + @queried_issues = scope + end + +end \ No newline at end of file diff --git a/app/services/api/v1/issues/milestones/detail_issues_service.rb b/app/services/api/v1/issues/milestones/detail_issues_service.rb new file mode 100644 index 000000000..8b6f69aed --- /dev/null +++ b/app/services/api/v1/issues/milestones/detail_issues_service.rb @@ -0,0 +1,65 @@ +class Api::V1::Issues::Milestones::DetailIssuesService < ApplicationService + include ActiveModel::Model + + attr_reader :project, :category, :author_id, :assigner_id, :issue_tag_ids, :sort_by, :sort_direction, :current_user + attr_accessor :queried_issues, :total_issues_count, :closed_issues_count, :opened_issues_count + + validates :category, inclusion: {in: %w(all opened closed), message: "请输入正确的Category"} + validates :sort_by, inclusion: {in: ['issues.created_on', 'issues.updated_on', 'issue_priorities.position'], message: '请输入正确的SortBy'}, allow_blank: true + validates :sort_direction, inclusion: {in: %w(asc desc), message: '请输入正确的SortDirection'}, allow_blank: true + validates :current_user, presence: true + + def initialize(project, milestone, params, current_user=nil) + @project = project + @milestone = milestone + @category = params[:category] || 'all' + @author_id = params[:author_id] + @assigner_id = params[:assigner_id] + @issue_tag_ids = params[:issue_tag_ids].present? ? params[:issue_tag_ids].split(",") : [] + @sort_by = params[:sort_by].present? ? params[:sort_by] : 'issues.updated_on' + @sort_direction = (params[:sort_direction].present? ? params[:sort_direction] : 'desc').downcase + @current_user = current_user + end + + def call + raise Error, errors.full_messages.join(", ") unless valid? + begin + issue_query_data + + return {data: queried_issues, total_issues_count: @total_issues_count, closed_issues_count: @closed_issues_count, opened_issues_count: @opened_issues_count} + rescue + raise Error, "服务器错误,请联系系统管理员!" + end + end + + private + def issue_query_data + issues = @milestone.issues.issue_issue + + # author_id + issues = issues.where(author_id: author_id) if author_id.present? + + # assigner_id + issues = issues.joins(:assigners).where(users: {id: assigner_id}).or(issues.joins(:assigners).where(assigned_to_id: assigner_id)) if assigner_id.present? + + issues = issues.ransack(issue_tags_value_cont: issue_tag_ids.sort!.join(",")).result unless issue_tag_ids.blank? + + @total_issues_count = issues.distinct.size + @closed_issues_count = issues.closed.distinct.size + @opened_issues_count = issues.opened.distinct.size + + case category + when 'closed' + issues = issues.closed + when 'opened' + issues = issues.opened + end + + scope = issues.includes(:priority, :issue_status, :user, :show_assigners, :version, :show_issue_tags, :comment_journals).references(:assigners) + + scope = scope.reorder("#{sort_by} #{sort_direction}").distinct + + @queried_issues = scope + end + +end \ No newline at end of file diff --git a/app/services/api/v1/issues/update_service.rb b/app/services/api/v1/issues/update_service.rb new file mode 100644 index 000000000..8a89bcf4f --- /dev/null +++ b/app/services/api/v1/issues/update_service.rb @@ -0,0 +1,257 @@ +class Api::V1::Issues::UpdateService < ApplicationService + include ActiveModel::Model + include Api::V1::Issues::Concerns::Checkable + include Api::V1::Issues::Concerns::Loadable + + attr_reader :project, :issue, :current_user + attr_reader :status_id, :priority_id, :milestone_id, :branch_name, :start_date, :due_date, :subject, :description, :blockchain_token_num + attr_reader :issue_tag_ids, :assigner_ids, :attachment_ids, :receivers_login + attr_accessor :add_assigner_ids, :previous_issue_changes, :updated_issue, :atme_receivers + + validates :project, :issue, :current_user, presence: true + validates :blockchain_token_num, numericality: {greater_than: 0}, allow_blank: true + + def initialize(project, issue, params, current_user = nil) + @project = project + @issue = issue + @current_user = current_user + @status_id = params[:status_id] + @priority_id = params[:priority_id] + @milestone_id = params[:milestone_id] + @branch_name = params[:branch_name] + @start_date = params[:start_date] + @due_date = params[:due_date] + @subject = params[:subject] + @description = params[:description] + @blockchain_token_num = params[:blockchain_token_num] + @issue_tag_ids = params[:issue_tag_ids] + @assigner_ids = params[:assigner_ids] + @attachment_ids = params[:attachment_ids] + @receivers_login = params[:receivers_login] + @add_assigner_ids = [] + @previous_issue_changes = {} + end + + def call + raise Error, errors.full_messages.join(", ") unless valid? + ActiveRecord::Base.transaction do + check_issue_status(status_id) if status_id.present? + check_issue_priority(priority_id) if priority_id.present? + check_milestone(milestone_id) if milestone_id.present? + check_issue_tags(issue_tag_ids) unless issue_tag_ids.nil? + check_assigners(assigner_ids) unless assigner_ids.nil? + check_attachments(attachment_ids) unless attachment_ids.nil? + check_atme_receivers(receivers_login) unless receivers_login.nil? + check_blockchain_token_num(issue.author_id, project.id, blockchain_token_num, (@issue.blockchain_token_num || 0)) if blockchain_token_num.present? && current_user.id == @issue.author_id && !PullAttachedIssue.exists?(issue_id: @issue, fixed: true) + load_assigners(assigner_ids) + load_attachments(attachment_ids) + load_issue_tags(issue_tag_ids) + load_atme_receivers(receivers_login) unless receivers_login.nil? + + try_lock("Api::V1::Issues::UpdateService:#{project.id}:#{issue.id}") + @updated_issue = @issue + issue_load_attributes + build_assigner_issue_journal_details unless assigner_ids.nil?# 操作记录 + build_attachment_issue_journal_details unless attachment_ids.nil? + build_issue_tag_issue_journal_details unless issue_tag_ids.nil? + build_issue_project_trends if status_id.present? # 开关时间记录 + build_assigner_participants unless assigner_ids.nil? # 负责人 + build_edit_participants + build_atme_participants if @atme_receivers.present? + unless assigner_ids.nil? + @previous_issue_changes.merge!(assigned_to_id: [@updated_issue.assigners.pluck(:id), @assigners.pluck(:id)]) + @updated_issue.assigners = @assigners || User.none + end + @updated_issue.attachments = @attachments || Attachment.none unless attachment_ids.nil? + @updated_issue.issue_tags_relates.destroy_all & @updated_issue.issue_tags = @issue_tags || IssueTag.none unless issue_tag_ids.nil? + @updated_issue.issue_tags_value = @issue_tags.order("id asc").pluck(:id).join(",") unless issue_tag_ids.nil? + + @updated_issue.updated_on = Time.now + @updated_issue.save! + + build_after_issue_journal_details if @updated_issue.previous_changes.present? # 操作记录 + build_previous_issue_changes + build_cirle_blockchain_token if blockchain_token_num.present? + + # @信息发送 + AtmeService.call(current_user, @atme_receivers, @issue) unless receivers_login.blank? + # 消息发送 + if Site.has_notice_menu? + SendTemplateMessageJob.perform_later('IssueChanged', current_user.id, @issue&.id, previous_issue_changes) unless previous_issue_changes.blank? + SendTemplateMessageJob.perform_later('IssueAssigned', current_user.id, @issue&.id, add_assigner_ids) unless add_assigner_ids.blank? + end + + unlock("Api::V1::Issues::UpdateService:#{project.id}:#{issue.id}") + + return @updated_issue + end + end + + private + + def issue_load_attributes + if current_user.id == @updated_issue.author_id && !PullAttachedIssue.exists?(issue_id: @updated_issue, fixed: true) + @updated_issue.blockchain_token_num = blockchain_token_num unless blockchain_token_num.nil? + end + @updated_issue.status_id = status_id if status_id.present? + @updated_issue.priority_id = priority_id if priority_id.present? + @updated_issue.fixed_version_id = milestone_id unless milestone_id.nil? + @updated_issue.branch_name = branch_name unless branch_name.nil? + @updated_issue.start_date = start_date unless start_date.nil? + @updated_issue.due_date = due_date unless due_date.nil? + @updated_issue.subject = subject if subject.present? + @updated_issue.description = description unless description.nil? + end + + def build_assigner_participants + if assigner_ids.blank? + @updated_issue.issue_participants.where(participant_type: "assigned").each(&:destroy!) + else + @updated_issue.issue_participants.where(participant_type: "assigned").where.not(participant_id: assigner_ids).each(&:destroy!) + assigner_ids.each do |aid| + next if @updated_issue.issue_participants.exists?(participant_type: "assigned", participant_id: aid) + @updated_issue.issue_participants.new({participant_type: "assigned", participant_id: aid}) + @add_assigner_ids << aid + end + end + end + + def build_edit_participants + @updated_issue.issue_participants.new({participant_type: "edited", participant_id: current_user.id}) unless @updated_issue.issue_participants.exists?(participant_type: "edited", participant_id: current_user.id) + end + + def build_atme_participants + @atme_receivers.each do |receiver| + next if @updated_issue.issue_participants.exists?(participant_type: "atme", participant_id: receiver.id) + @updated_issue.issue_participants.new({participant_type: "atme", participant_id: receiver.id}) + end + end + + def build_previous_issue_changes + @previous_issue_changes.merge!(@updated_issue.previous_changes.slice("status_id", "priority_id", "fixed_version_id", "issue_tags_value", "branch_name").symbolize_keys) + if @updated_issue.previous_changes[:start_date].present? + @previous_issue_changes.merge!(start_date: [@updated_issue.previous_changes[:start_date][0].to_s, @updated_issue.previous_changes[:start_date][1].to_s]) + end + if @updated_issue.previous_changes[:due_date].present? + @previous_issue_changes.merge!(due_date: [@updated_issue.previous_changes[:due_date][0].to_s, @updated_issue.previous_changes[:due_date][1].to_s]) + end + end + + def build_cirle_blockchain_token + if @updated_issue.previous_changes["blockchain_token_num"].present? + unlock_balance_on_blockchain(@updated_issue&.author_id.to_s, @updated_issue.project_id.to_s, @updated_issue.previous_changes["blockchain_token_num"][0].to_i) if @updated_issue.previous_changes["blockchain_token_num"][0].present? + lock_balance_on_blockchain(@updated_issue&.author_id.to_s, @updated_issue.project_id.to_s, @updated_issue.previous_changes["blockchain_token_num"][1].to_i) if @updated_issue.previous_changes["blockchain_token_num"][1].present? + end + end + + def build_issue_project_trends + if @updated_issue.previous_changes["status_id"].present? && @updated_issue.previous_changes["status_id"][1] == 5 + @updated_issue.project_trends.new({user_id: current_user.id, project_id: @project.id, action_type: ProjectTrend::CLOSE}) + end + if @updated_issue.previous_changes["status_id"].present? && @updated_issue.previous_changes["status_id"][0] == 5 + @updated_issue.project_trends.where(action_type: ProjectTrend::CLOSE).each(&:destroy!) + end + end + + def build_after_issue_journal_details + begin + # 更改标题 + if @updated_issue.previous_changes["subject"].present? + journal = @updated_issue.journals.create!({user_id: current_user.id}) + journal.journal_details.create!({property: "attr", prop_key: "subject", old_value: @updated_issue.previous_changes["subject"][0], value: @updated_issue.previous_changes["subject"][1]}) + end + + # 更改描述 + if @updated_issue.previous_changes["description"].present? + journal = @updated_issue.journals.create!({user_id: current_user.id}) + journal.journal_details.create!({property: "attr", prop_key: "description", old_value: @updated_issue.previous_changes["description"][0], value: @updated_issue.previous_changes["description"][1]}) + end + + # 修改状态 + if @updated_issue.previous_changes["status_id"].present? + journal = @updated_issue.journals.create!({user_id: current_user.id}) + journal.journal_details.create!({property: "attr", prop_key: "status_id", old_value: @updated_issue.previous_changes["status_id"][0], value: @updated_issue.previous_changes["status_id"][1]}) + end + + # 修改优先级 + if @updated_issue.previous_changes["priority_id"].present? + journal = @updated_issue.journals.create!({user_id: current_user.id}) + journal.journal_details.create!({property: "attr", prop_key: "priority_id", old_value: @updated_issue.previous_changes["priority_id"][0], value: @updated_issue.previous_changes["priority_id"][1]}) + end + + # 修改里程碑 + if @updated_issue.previous_changes["fixed_version_id"].present? + journal = @updated_issue.journals.create!({user_id: current_user.id}) + journal.journal_details.create!({property: "attr", prop_key: "fixed_version_id", old_value: @updated_issue.previous_changes["fixed_version_id"][0], value: @updated_issue.previous_changes["fixed_version_id"][1]}) + end + + # 更改分支 + if @updated_issue.previous_changes["branch_name"].present? + journal = @updated_issue.journals.create!({user_id: current_user.id}) + journal.journal_details.create!({property: "attr", prop_key: "branch_name", old_value: @updated_issue.previous_changes["branch_name"][0], value: @updated_issue.previous_changes["branch_name"][1]}) + end + + # 更改开始时间 + if @updated_issue.previous_changes["start_date"].present? + journal = @updated_issue.journals.create!({user_id: current_user.id}) + journal.journal_details.create!({property: "attr", prop_key: "start_date", old_value: @updated_issue.previous_changes["start_date"][0], value: @updated_issue.previous_changes["start_date"][1]}) + end + + # 更改结束时间 + if @updated_issue.previous_changes["due_date"].present? + journal = @updated_issue.journals.create!({user_id: current_user.id}) + journal.journal_details.create!({property: "attr", prop_key: "due_date", old_value: @updated_issue.previous_changes["due_date"][0], value: @updated_issue.previous_changes["due_date"][1]}) + end + rescue + raise Error, "创建操作记录失败!" + end + end + + def build_assigner_issue_journal_details + begin + # 更改负责人 + new_assigner_ids = @assigner_ids + new_assigner_ids = [] if @assigner_ids.nil? + now_assigner_ids = @updated_issue.assigners.pluck(:id) + if !(now_assigner_ids & assigner_ids).empty? || !(now_assigner_ids.empty? && new_assigner_ids.empty?) + journal = @updated_issue.journals.create!({user_id: current_user.id}) + journal.journal_details.create!({property: "assigner", prop_key: "#{new_assigner_ids.size}", old_value: now_assigner_ids.join(","), value: new_assigner_ids.join(",")}) + end + + rescue + raise Error, "创建操作记录失败!" + end + end + + def build_issue_tag_issue_journal_details + begin + # 更改标记 + new_issue_tag_ids = @issue_tag_ids + new_issue_tag_ids = [] if @issue_tag_ids.nil? + now_issue_tag_ids = @updated_issue.issue_tags.pluck(:id) + if !(now_issue_tag_ids & new_issue_tag_ids).empty? || !(now_issue_tag_ids.empty? && new_issue_tag_ids.empty?) + journal = @updated_issue.journals.create!({user_id: current_user.id}) + journal.journal_details.create!({property: "issue_tag", prop_key: "#{new_issue_tag_ids.size}", old_value: now_issue_tag_ids.join(","), value: new_issue_tag_ids.join(",")}) + end + rescue + raise Error, "创建操作记录失败!" + end + end + + + def build_attachment_issue_journal_details + begin + # 更改附件 + new_attachment_ids = @attachment_ids + new_attachment_ids = [] if @attachment_ids.nil? + now_attachment_ids = @updated_issue.attachments.pluck(:id) + if !(now_attachment_ids & new_attachment_ids).empty? || !(now_attachment_ids.empty? && new_attachment_ids.empty?) + journal = @updated_issue.journals.create!({user_id: current_user.id}) + journal.journal_details.create!({property: "attachment", prop_key: "#{new_attachment_ids.size}", old_value: now_attachment_ids.join(","), value: new_attachment_ids.join(",")}) + end + rescue + raise Error, "创建操作记录失败!" + end + end + +end \ No newline at end of file diff --git a/app/services/api/v1/projects/pulls/journals/create_service.rb b/app/services/api/v1/projects/pulls/journals/create_service.rb index df207771b..051c6777c 100644 --- a/app/services/api/v1/projects/pulls/journals/create_service.rb +++ b/app/services/api/v1/projects/pulls/journals/create_service.rb @@ -30,6 +30,8 @@ class Api::V1::Projects::Pulls::Journals::CreateService < ApplicationService create_comment_journal end + push_activity_2_blockchain("issue_comment_create", @journal) if Site.has_blockchain? && @project.use_blockchain + journal end diff --git a/app/services/api/v1/users/projects/list_service.rb b/app/services/api/v1/users/projects/list_service.rb index 8b3bffef0..47457c58c 100644 --- a/app/services/api/v1/users/projects/list_service.rb +++ b/app/services/api/v1/users/projects/list_service.rb @@ -73,8 +73,10 @@ class Api::V1::Users::Projects::ListService < ApplicationService end - projects = projects.with_project_type(project_type) + projects = projects.with_project_type(project_type) + # 表情处理 + search = search.to_s.each_char.select { |c| c.bytes.first < 240 }.join('') q = projects.ransack(name_or_identifier_cont: search) scope = q.result.includes(:project_category, :project_language,:owner, :repository, :has_pinned_users) diff --git a/app/services/application_service.rb b/app/services/application_service.rb index 81ecf5f7b..de9842f9d 100644 --- a/app/services/application_service.rb +++ b/app/services/application_service.rb @@ -1,26 +1,427 @@ -class ApplicationService - include Callable - - Error = Class.new(StandardError) - - def regix_emoji content - " " if content.blank? - regex = /[^a-zA-Z0-9\u4E00-\u9FFF]/ - content.gsub(regex, '') - end - - private - - def strip(str) - str.to_s.strip.presence - end - - def str_to_boolean str - ActiveModel::Type::Boolean.new.cast str - end - - def phone_mail_type value - value =~ /^1\d{10}$/ ? 1 : 0 - end - -end +class ApplicationService + include Callable + + Error = Class.new(StandardError) + + def regix_emoji content + " " if content.blank? + regex = /[^a-zA-Z0-9\u4E00-\u9FFF]/ + content.gsub(regex, '') + end + + protected + def try_lock(key) + raise Error, "请稍后再试!" unless $redis_cache.set(key, 1, nx: true, ex: 60.seconds) + end + + def unlock(key) + $redis_cache.del(key) + end + + private + + def strip(str) + str.to_s.strip.presence + end + + def str_to_boolean str + ActiveModel::Type::Boolean.new.cast str + end + + # params: params from index.js page + def create_repo_on_blockchain(params, project) + username = params['user_id'].to_s + token_name = project.id.to_s + total_supply = params['blockchain_token_all'].to_i + token_balance = [[username, params['blockchain_init_token'].to_i]] + + params = { + "request-type": "create repo", + "username": username, + "token_name": token_name, + "total_supply": total_supply, + "token_balance": token_balance + }.to_json + resp_body = Blockchain::InvokeBlockchainApi.call(params) + if resp_body['status'] != 0 + raise "区块链接口请求失败." + end + end + + + def transfer_balance_on_blockchain(payer, payee, token_name, amount) + + params = { + "request-type": "transfer amount", + "payer": payer, + "payee": payee, + "token_name": token_name, + "amount": amount + }.to_json + resp_body = Blockchain::InvokeBlockchainApi.call(params) + if resp_body['status'] == 5 or resp_body['status'] == 106 or resp_body['status'] == 105 + raise resp_body['message'] + elsif resp_body['status'] != 0 + raise "区块链接口请求失败." + else + end + end + + + def lock_balance_on_blockchain(username, tokenname, amount) + + params = { + "request-type": "lock user balance", + "username": username, + "token_name": tokenname, + "amount": amount + }.to_json + resp_body = Blockchain::InvokeBlockchainApi.call(params) + if resp_body['status'] == 5 or resp_body['status'] == 106 or resp_body['status'] == 103 + raise resp_body['message'] + elsif resp_body['status'] != 0 + raise "区块链接口请求失败." + else + end + end + + + def unlock_balance_on_blockchain(username, tokenname, amount) + + params = { + "request-type": "unlock user balance", + "username": username, + "token_name": tokenname, + "amount": amount + }.to_json + resp_body = Blockchain::InvokeBlockchainApi.call(params) + if resp_body['status'] == 5 or resp_body['status'] == 106 or resp_body['status'] == 104 + raise resp_body['message'] + elsif resp_body['status'] != 0 + raise "区块链接口请求失败." + else + end + end + + def push_activity_2_blockchain(activity_type, model) + if activity_type == "issue_create" + + project_id = model['project_id'] + project = Project.find(project_id) + if project['use_blockchain'] == 0 || project['use_blockchain'] == false + # 无需执行上链操作 + return true + end + + id = model['id'] + + owner_id = project['user_id'] + owner = User.find(owner_id) + ownername = owner['login'] + identifier = project['identifier'] + + author_id = project['user_id'] + author = User.find(author_id) + username = author['login'] + + action = 'opened' + + title = model['subject'] + content = model['description'] + created_at = model['created_on'] + updated_at = model['updated_on'] + + # 调用区块链接口 + params = { + "request-type": "upload issue info", + "issue_id": "gitlink-" + id.to_s, + "repo_id": "gitlink-" + project_id.to_s, + "issue_number": 0, # 暂时不需要改字段 + "reponame": identifier, + "ownername": ownername, + "username": username, + "action": action, + "title": title, + "content": content, + "created_at": created_at, + "updated_at": updated_at + }.to_json + resp_body = Blockchain::InvokeBlockchainApi.call(params) + if resp_body['status'] == 10 + raise Error, resp_body['message'] + elsif resp_body['status'] != 0 + raise Error, "区块链接口请求失败." + end + + elsif activity_type == "issue_comment_create" + issue_comment_id = model['id'] + issue_id = model['journalized_id'] + parent_id = model['parent_id'].nil? ? "" : model['parent_id'] + + issue = Issue.find(issue_id) + issue_classify = issue['issue_classify'] # issue或pull_request + project_id = issue['project_id'] + project = Project.find(project_id) + + if project['use_blockchain'] == 0 || project['use_blockchain'] == false + # 无需执行上链操作 + return + end + + identifier = project['identifier'] + owner_id = project['user_id'] + owner = User.find(owner_id) + ownername = owner['login'] + + author_id = model['user_id'] + author = User.find(author_id) + username = author['login'] + + action = 'created' + + content = model['notes'] + created_at = model['created_on'] + + if issue_classify == "issue" + params = { + "request-type": "upload issue comment info", + "issue_comment_id": "gitlink-" + issue_comment_id.to_s, + "issue_comment_number": 0, # 暂时不需要 + "issue_number": 0, # 暂时不需要 + "issue_id": "gitlink-" + issue_id.to_s, + "repo_id": "gitlink-" + project.id.to_s, + "parent_id": parent_id.to_s, + "reponame": identifier, + "ownername": ownername, + "username": username, + "action": action, + "content": content, + "created_at": created_at, + }.to_json + elsif issue_classify == "pull_request" + params = { + "request-type": "upload pull request comment info", + "pull_request_comment_id": "gitlink-" + issue_comment_id.to_s, + "pull_request_comment_number": 0, # 不考虑该字段 + "pull_request_number": 0, # 不考虑该字段 + "pull_request_id": "gitlink-" + issue_id.to_s, + "parent_id": parent_id.to_s, + "repo_id": "gitlink-" + project.id.to_s, + "reponame": identifier, + "ownername": ownername, + "username": username, + "action": action, + "content": content, + "created_at": created_at, + }.to_json + end + + # 调用区块链接口 + resp_body = Blockchain::InvokeBlockchainApi.call(params) + if resp_body['status'] == 10 + raise Error, resp_body['message'] + elsif resp_body['status'] != 0 + raise Error, "区块链接口请求失败." + end + elsif activity_type == "pull_request_create" + # 调用区块链接口 + project_id = model['project_id'] + project = Project.find(project_id) + if project['use_blockchain'] == 0 || project['use_blockchain'] == false + # 无需执行上链操作 + return + end + + pull_request_id = model['id'] + identifier = project['identifier'] + owner_id = project['user_id'] + owner = User.find(owner_id) + ownername = owner['login'] + + action = 'opened' + + title = model['title'] + content = model['body'] + + source_branch = model['head'] + source_repo_id = model['fork_project_id'].nil? ? project_id : model['fork_project_id'] + + target_branch = model['base'] + target_repo_id = project_id + + author_id = model['user_id'] + author = User.find(author_id) + username = author['login'] + + created_at = model['created_at'] + updated_at = model['updated_at'] + + # 查询pull request对应的commit信息 + commits = Gitea::PullRequest::CommitsService.call(ownername, identifier, model['gitea_number']) + if commits.nil? + raise Error, "区块链接口请求失败" # 获取pr中变更的commit信息失败 + end + commit_shas = [] + commits.each do |c| + commit_shas << c["Sha"] + end + params = { + "request-type": "upload pull request info", + "pull_request_id": "gitlink-" + pull_request_id.to_s, + "pull_request_number": 0, # trustie没有该字段 + "repo_id": "gitlink-" + project_id.to_s, + "ownername": ownername, + "reponame": identifier, + "username": username, + "action": action, + "title": title, + "content": content, + "source_branch": source_branch, + "target_branch": target_branch, + "reviewers": [], # trustie没有该字段 + "commit_shas": commit_shas, + "merge_user": "", # trustie没有该字段 + "created_at": created_at, + "updated_at": updated_at + }.to_json + resp_body = Blockchain::InvokeBlockchainApi.call(params) + if resp_body['status'] == 9 + raise Error, resp_body['message'] + elsif resp_body['status'] != 0 + raise Error, "区块链接口请求失败." + end + elsif activity_type == "pull_request_merge" + # 调用区块链接口 + project_id = model['project_id'] + project = Project.find(project_id) + if project['use_blockchain'] == 0 || project['use_blockchain'] == false + # 无需执行上链操作 + return + end + + pull_request_id = model['id'] + identifier = project['identifier'] + owner_id = project['user_id'] + owner = User.find(owner_id) + ownername = owner['login'] + + action = 'merged' + + created_at = model['created_at'] + updated_at = model['updated_at'] + + # 查询pull request对应的commit信息 + commits = Gitea::PullRequest::CommitsService.call(ownername, identifier, model['gitea_number']) + if commits.nil? + raise Error, "区块链接口请求失败" # 获取pr中变更的commit信息失败 + end + commit_shas = [] + commits.each do |c| + commit_shas << c["Sha"] + end + + # 将pull request相关信息写入链上 + params = { + "request-type": "upload pull request info", + "pull_request_id": "gitlink-" + pull_request_id.to_s, + "pull_request_number": 0, # trustie没有该字段 + "repo_id": "gitlink-" + project_id.to_s, + "ownername": ownername, + "reponame": identifier, + "username": username, + "action": action, + "title": title, + "content": content, + "source_branch": source_branch, + "target_branch": target_branch, + "reviewers": [], # trustie没有该字段 + "commit_shas": commit_shas, + "merge_user": "", # trustie没有该字段 + "created_at": created_at, + "updated_at": updated_at + }.to_json + resp_body = Blockchain::InvokeBlockchainApi.call(params) + if resp_body['status'] == 9 + raise Error, resp_body['message'] + elsif resp_body['status'] != 0 + raise Error, "区块链接口请求失败." + end + + + # 将commit相关信息写入链上 + commit_shas.each do |commit_sha| + commit_diff = Gitea::Commit::DiffService.call(ownername, identifier, commit_sha, owner['gitea_token']) + commit = Gitea::Commit::InfoService.call(ownername, identifier, commit_sha, owner['gitea_token']) + params = { + "request-type": "upload commit info", + "commit_hash": commit_sha, + "repo_id": "gitlink-" + project_id.to_s, + "author": commit['commit']['author']['name'], + "author_email": commit['commit']['author']['email'], + "committer": commit['commit']['committer']['name'], + "committer_email": commit['commit']['committer']['email'], + "author_time": commit['commit']['author']['date'], + "committer_time": commit['commit']['committer']['date'], + "content": commit['commit']['message'], + "commit_diff": commit_diff['Files'].to_s + }.to_json + resp_body = Blockchain::InvokeBlockchainApi.call(params) + if resp_body['status'] == 7 + raise Error, resp_body['message'] + elsif resp_body['status'] != 0 + raise Error, "区块链接口请求失败." + end + end + + elsif activity_type == "pull_request_refuse" + + # 调用区块链接口 + project_id = model['project_id'] + project = Project.find(project_id) + if project['use_blockchain'] == 0 || project['use_blockchain'] == false + # 无需执行上链操作 + return true + end + + pull_request_id = model['id'] + identifier = project['identifier'] + owner_id = project['user_id'] + owner = User.find(owner_id) + ownername = owner['login'] + + action = 'refused' + + # 将pull request相关信息写入链上 + params = { + "request-type": "upload pull request info", + "pull_request_id": "gitlink-" + pull_request_id.to_s, + "pull_request_number": 0, # trustie没有该字段 + "repo_id": "gitlink-" + project_id.to_s, + "ownername": ownername, + "reponame": identifier, + "username": username, + "action": action, + "title": title, + "content": content, + "source_branch": source_branch, + "target_branch": target_branch, + "reviewers": [], # trustie没有该字段 + "commit_shas": commit_shas, + "merge_user": "", # trustie没有该字段 + "created_at": created_at, + "updated_at": updated_at + }.to_json + resp_body = Blockchain::InvokeBlockchainApi.call(params) + if resp_body['status'] == 9 + raise Error, resp_body['message'] + elsif resp_body['status'] != 0 + raise Error, "区块链接口请求失败." + end + end + end + + def phone_mail_type value + value =~ /^1\d{10}$/ ? 1 : 0 + end + +end diff --git a/app/services/blockchain/create_issue.rb b/app/services/blockchain/create_issue.rb new file mode 100644 index 000000000..c3ab5ad49 --- /dev/null +++ b/app/services/blockchain/create_issue.rb @@ -0,0 +1,28 @@ +class Blockchain::CreateIssue < ApplicationService + + attr_reader :params + + def initialize(params) + @params = params + end + + def call + ActiveRecord::Base.transaction do + username = @params[:user_id].to_s + token_name = @params[:project_id].to_s + amount = @params[:token_num].to_i + + # 调用token锁仓函数 + lock_balance_on_blockchain(username, token_name, amount) + end + rescue => e + puts "转账失败: #{e.message}" + raise Error, e.message + end + + private + + def no_use + puts "this function does not have any usage" + end +end \ No newline at end of file diff --git a/app/services/blockchain/create_trade.rb b/app/services/blockchain/create_trade.rb new file mode 100644 index 000000000..a4de98783 --- /dev/null +++ b/app/services/blockchain/create_trade.rb @@ -0,0 +1,29 @@ +class Blockchain::CreateTrade < ApplicationService + + attr_reader :params + + def initialize(params) + @params = params + end + + def call + ActiveRecord::Base.transaction do + username = @params[:user_id].to_s + token_name = @params[:project_id].to_s + amount = @params[:token_num].to_i + + # 调用token锁仓函数 + results = lock_balance_on_blockchain(username, token_name, amount) + return results + end + rescue => e + puts "转账失败: #{e.message}" + raise Error, e.message + end + + private + + def no_use + puts "this function does not have any usage" + end +end \ No newline at end of file diff --git a/app/services/blockchain/fix_issue.rb b/app/services/blockchain/fix_issue.rb new file mode 100644 index 000000000..332202792 --- /dev/null +++ b/app/services/blockchain/fix_issue.rb @@ -0,0 +1,28 @@ +class Blockchain::FixIssue < ApplicationService + + attr_reader :params + + def initialize(params) + @params = params + end + + def call + ActiveRecord::Base.transaction do + username = @params[:user_id].to_s + token_name = @params[:project_id].to_s + amount = @params[:token_num].to_i + + # 调用token锁仓函数 + unlock_balance_on_blockchain(username, token_name, amount) + end + rescue => e + puts "关联issue失败: #{e.message}" + raise Error, e.message + end + + private + + def no_use + puts "this function does not have any usage" + end +end \ No newline at end of file diff --git a/app/services/blockchain/invoke_blockchain_api.rb b/app/services/blockchain/invoke_blockchain_api.rb new file mode 100644 index 000000000..d485e171c --- /dev/null +++ b/app/services/blockchain/invoke_blockchain_api.rb @@ -0,0 +1,34 @@ +class Blockchain::InvokeBlockchainApi < ApplicationService + # 调用blockchain + + attr_reader :params + + def initialize(params) + @params = params + end + + def call + begin + uri = Blockchain.blockchain_config[:api_url] + 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 + http.request(req) + end + if res.code.to_i != 200 + raise "区块链接口请求失败." + else + res_body = JSON.parse(res.body) + if res_body.has_key?("status") + else + raise "区块链接口请求失败." + end + end + return res_body + rescue Exception => e + raise "区块链接口请求失败." + end + end +end \ No newline at end of file diff --git a/app/services/blockchain/transfer_service.rb b/app/services/blockchain/transfer_service.rb new file mode 100644 index 000000000..4f7425e5d --- /dev/null +++ b/app/services/blockchain/transfer_service.rb @@ -0,0 +1,36 @@ +class Blockchain::TransferService < ApplicationService + + attr_reader :params + + def initialize(params) + @params = params + end + + def call + ActiveRecord::Base.transaction do + transfer_amount = params['transfer_amount'] + if (Float(transfer_amount) rescue false) == false or transfer_amount.to_i < 0 or Float(transfer_amount) != transfer_amount.to_i + raise Error, "请输入正确的转账金额" + end + transfer_amount = params['transfer_amount'].to_i + transfer_login = params['transfer_login'] + payer = params['payer_id'].to_s + payee = User.find_by(login: transfer_login) + if payee.nil? + raise Error, "未找到接收转账的用户" + else + payee = payee.id.to_s + token_name = params['project_id'].to_s + # 调用token转移函数 + transfer_balance_on_blockchain(payer, payee, token_name, transfer_amount) + end + end + end + + private + + def no_use + puts "this function does not have any usage" + end + +end \ No newline at end of file diff --git a/app/services/gitea/commit/diff_service.rb b/app/services/gitea/commit/diff_service.rb new file mode 100644 index 000000000..712302505 --- /dev/null +++ b/app/services/gitea/commit/diff_service.rb @@ -0,0 +1,40 @@ +# get the diff info for the commit +class Gitea::Commit::DiffService < Gitea::ClientService + attr_reader :owner, :repo, :sha, :token + + # GET /repos/{owner}/{repo}/commits/{sha}/diff + # owner: 用户 + # repo: 仓库名称/标识 + # sha: commit唯一标识 + # eg: + # Gitea::Commit::DiffService.call('jasder', 'repo_identifier', 'sha value') + def initialize(owner, repo, sha, token=nil) + @owner = owner + @repo = repo + @sha = sha + @token = token + end + + def call + response = get(url, params) + render_result(response) + end + + private + def params + Hash.new.merge(token: token) + end + + def url + "/repos/#{owner}/#{repo}/commits/#{sha}/diff".freeze + end + + def render_result(response) + case response.status + when 200 + JSON.parse(response.body) + else + nil + end + end +end diff --git a/app/services/gitea/commit/info_service.rb b/app/services/gitea/commit/info_service.rb new file mode 100644 index 000000000..d337071e8 --- /dev/null +++ b/app/services/gitea/commit/info_service.rb @@ -0,0 +1,39 @@ +class Gitea::Commit::InfoService < Gitea::ClientService + attr_reader :owner, :repo, :sha, :token + + # GET /repos/{owner}/{repo}/commits/{sha}/diff + # owner: 用户 + # repo: 仓库名称/标识 + # sha: commit唯一标识 + # eg: + # Gitea::Commit::InfoService.call('jasder', 'repo_identifier', 'sha value', token='gitea token') + def initialize(owner, repo, sha, token=nil) + @owner = owner + @repo = repo + @sha = sha + @token = token + end + + def call + response = get(url, params) + render_result(response) + end + + private + def params + Hash.new.merge(token: token) + end + + def url + "/repos/#{owner}/#{repo}/git/commits/#{sha}".freeze + end + + def render_result(response) + case response.status + when 200 + JSON.parse(response.body) + else + nil + end + end +end \ No newline at end of file diff --git a/app/services/projects/create_service.rb b/app/services/projects/create_service.rb index 2b4523bf5..c4f892f7f 100644 --- a/app/services/projects/create_service.rb +++ b/app/services/projects/create_service.rb @@ -14,9 +14,13 @@ class Projects::CreateService < ApplicationService ActiveRecord::Base.transaction do if @project.save! Project.update_common_projects_count! + IssueTag.init_data(@project.id) ProjectUnit.init_types(@project.id) Repositories::CreateService.new(user, @project, repository_params).call upgrade_project_category_private_projects_count + if repo_use_blockchain + create_repo_on_blockchain(params, @project) + end else Rails.logger.info("#############___________create_project_erros______###########{@project.errors.messages}") end @@ -29,7 +33,7 @@ class Projects::CreateService < ApplicationService private - def upgrade_project_category_private_projects_count + def upgrade_project_category_private_projects_count # 如果为空或者项目为公有项目直接返回 return unless params[:project_category_id].present? return if repo_is_public @@ -37,7 +41,7 @@ class Projects::CreateService < ApplicationService project_category.increment!(:private_projects_count, 1) end - def authroize_user_id_success + def authroize_user_id_success (user.id == params[:user_id].to_i) || (user.organizations.find_by_id(params[:user_id]).present?) end @@ -52,7 +56,8 @@ class Projects::CreateService < ApplicationService ignore_id: params[:ignore_id], license_id: params[:license_id], website: params[:website], - identifier: params[:repository_name] + identifier: params[:repository_name], + use_blockchain: repo_use_blockchain # 新增,zxh } end @@ -71,4 +76,8 @@ class Projects::CreateService < ApplicationService def repo_is_public params[:private].blank? ? true : !(ActiveModel::Type::Boolean.new.cast(params[:private]).nil? ? false : ActiveModel::Type::Boolean.new.cast(params[:private])) end + + def repo_use_blockchain + params[:blockchain].blank? ? false : params[:blockchain] + end end diff --git a/app/services/pull_requests/create_service.rb b/app/services/pull_requests/create_service.rb index 258d0e31b..2b4767f31 100644 --- a/app/services/pull_requests/create_service.rb +++ b/app/services/pull_requests/create_service.rb @@ -20,6 +20,7 @@ class PullRequests::CreateService < ApplicationService save_tiding! save_project_trend! save_custom_journal_detail! + save_pull_attached_issues! end [pull_request, gitea_pull_request] @@ -111,6 +112,20 @@ class PullRequests::CreateService < ApplicationService end end + def save_pull_attached_issues! + if attached_issue_ids.size > 1 + raise "最多只能关联一个疑修。" + else + attached_issue_ids.each do |issue| + PullAttachedIssue.create!(issue_id: issue, pull_request_id: pull_request&.id) + end + end + end + + def attached_issue_ids + Array(@params[:attached_issue_ids]) + end + def gitea_pull_request @gitea_pull_request ||= create_gitea_pull_request! end diff --git a/app/views/admins/organizations/index.html.erb b/app/views/admins/organizations/index.html.erb index d716313b3..7cd2ba8fa 100644 --- a/app/views/admins/organizations/index.html.erb +++ b/app/views/admins/organizations/index.html.erb @@ -5,10 +5,10 @@ <%= form_tag(admins_organizations_path, method: :get, class: 'form-inline search-form flex-1', remote: true) do %> <%= text_field_tag(:keyword, params[:keyword], class: 'form-control col-sm-2 ml-3', placeholder: 'login/昵称') %> - + <%= submit_tag('搜索', class: 'btn btn-primary ml-3', 'data-disable-with': '搜索中...') %> <% end %> - +
diff --git a/app/views/admins/organizations/index.js.erb b/app/views/admins/organizations/index.js.erb index 5cf62a739..c2778115e 100644 --- a/app/views/admins/organizations/index.js.erb +++ b/app/views/admins/organizations/index.js.erb @@ -1 +1 @@ -$('.organizations-list-container').html("<%= j( render partial: 'admins/organizations/shared/org_list', locals: { organizations: @orgs } ) %>"); \ No newline at end of file +$('.organizations-list-container').html("<%= j( render partial: 'admins/organizations/shared/org_list', locals: { organizations: @orgs } ) %>"); diff --git a/app/views/admins/projects_rank/index.html.erb b/app/views/admins/projects_rank/index.html.erb index 056e0a0da..d3a7926b7 100644 --- a/app/views/admins/projects_rank/index.html.erb +++ b/app/views/admins/projects_rank/index.html.erb @@ -19,15 +19,15 @@ 排名 - 项目 - 得分 - 访问数 - 关注数 - 点赞数 - fork数 - 疑修数 - 合并请求数 - 提交数 + 项目 + 得分 + 访问数 + 关注数 + 点赞数 + fork数 + 疑修数 + 合并请求数 + 提交数 @@ -38,7 +38,7 @@ <% owner_common = $redis_cache.hgetall("v2-owner-common:#{project_common["owner_id"]}")%> /<%= project_common["identifier"]%>"> - <%= project_common["name"] %> + <%= "#{owner_common["name"]}/#{project_common["name"]}" %> diff --git a/app/views/api/v1/attachments/_simple_detail.json.jbuilder b/app/views/api/v1/attachments/_simple_detail.json.jbuilder new file mode 100644 index 000000000..3d56eb82f --- /dev/null +++ b/app/views/api/v1/attachments/_simple_detail.json.jbuilder @@ -0,0 +1,7 @@ +json.id attachment.id +json.title attachment.title +json.filesize number_to_human_size(attachment.filesize) +json.is_pdf attachment.is_pdf? +json.url attachment.is_pdf? ? download_url(attachment,disposition:"inline") : download_url(attachment) +json.created_on attachment.created_on.strftime("%Y-%m-%d %H:%M") +json.content_type attachment.content_type diff --git a/app/views/api/v1/issues/_detail.json.jbuilder b/app/views/api/v1/issues/_detail.json.jbuilder new file mode 100644 index 000000000..712e7a960 --- /dev/null +++ b/app/views/api/v1/issues/_detail.json.jbuilder @@ -0,0 +1,47 @@ +json.(issue, :id, :subject, :project_issues_index, :description, :branch_name, :start_date, :due_date) +json.blockchain_token_num issue.project&.use_blockchain ? issue.blockchain_token_num : nil +json.created_at issue.created_on.strftime("%Y-%m-%d %H:%M") +json.updated_at issue.updated_on.strftime("%Y-%m-%d %H:%M") +json.tags issue.show_issue_tags.each do |tag| + json.partial! "api/v1/issues/issue_tags/simple_detail", locals: {tag: tag} +end +json.status do + if issue.issue_status.present? + json.partial! "api/v1/issues/statues/simple_detail", locals: {status: issue.issue_status} + else + json.nil! + end +end +json.priority do + if issue.priority.present? + json.partial! "api/v1/issues/issue_priorities/simple_detail", locals: {priority: issue.priority} + else + json.nil! + end +end +json.milestone do + if issue.version.present? + json.partial! "api/v1/issues/milestones/simple_detail", locals: {milestone: issue.version} + else + json.nil! + end +end +json.author do + if issue.user.present? + json.partial! "api/v1/users/simple_user", locals: {user: issue.user} + else + json.nil! + end +end +json.assigners issue.show_assigners.each do |assigner| + json.partial! "api/v1/users/simple_user", locals: {user: assigner} +end +json.participants issue.participants.distinct.each do |participant| + json.partial! "api/v1/users/simple_user", locals: {user: participant} +end +json.comment_journals_count issue.comment_journals.size +json.operate_journals_count issue.operate_journals.size +json.attachments issue.attachments.each do |attachment| + json.partial! "api/v1/attachments/simple_detail", locals: {attachment: attachment} +end +json.pull_fixed issue.pull_attached_issues.where(fixed: true).present? \ No newline at end of file diff --git a/app/views/api/v1/issues/_simple_detail.json.jbuilder b/app/views/api/v1/issues/_simple_detail.json.jbuilder new file mode 100644 index 000000000..4f288ce20 --- /dev/null +++ b/app/views/api/v1/issues/_simple_detail.json.jbuilder @@ -0,0 +1,21 @@ +json.(issue, :id, :subject, :project_issues_index) +json.blockchain_token_num issue.project&.use_blockchain ? issue.blockchain_token_num : nil +json.created_at issue.created_on.strftime("%Y-%m-%d %H:%M") +json.updated_at issue.updated_on.strftime("%Y-%m-%d %H:%M") +json.tags issue.show_issue_tags.each do |tag| + json.partial! "api/v1/issues/issue_tags/simple_detail", locals: {tag: tag} +end +json.status_name issue.issue_status&.name +json.priority_name issue.priority&.name +json.milestone_name issue.version&.name +json.author do + if issue.user.present? + json.partial! "api/v1/users/simple_user", locals: {user: issue.user} + else + json.nil! + end +end +json.assigners issue.show_assigners.each do |assigner| + json.partial! "api/v1/users/simple_user", locals: {user: assigner} +end +json.comment_journals_count issue.comment_journals.size \ No newline at end of file diff --git a/app/views/api/v1/issues/assigners/index.json.jbuilder b/app/views/api/v1/issues/assigners/index.json.jbuilder new file mode 100644 index 000000000..fbcf469a6 --- /dev/null +++ b/app/views/api/v1/issues/assigners/index.json.jbuilder @@ -0,0 +1,4 @@ +json.total_count @assigners.total_count +json.assigners @assigners.each do |assigner| + json.partial! 'api/v1/users/simple_user', locals: { user: assigner} +end \ No newline at end of file diff --git a/app/views/api/v1/issues/authors/index.json.jbuilder b/app/views/api/v1/issues/authors/index.json.jbuilder new file mode 100644 index 000000000..dd1a4174a --- /dev/null +++ b/app/views/api/v1/issues/authors/index.json.jbuilder @@ -0,0 +1,4 @@ +json.total_count @authors.total_count +json.authors @authors.each do |author| + json.partial! 'api/v1/users/simple_user', locals: { user: author} +end \ No newline at end of file diff --git a/app/views/api/v1/issues/create.json.jbuilder b/app/views/api/v1/issues/create.json.jbuilder new file mode 100644 index 000000000..f45ef5b2f --- /dev/null +++ b/app/views/api/v1/issues/create.json.jbuilder @@ -0,0 +1 @@ +json.partial! "api/v1/issues/detail", locals: {issue: @object_result} diff --git a/app/views/api/v1/issues/index.json.jbuilder b/app/views/api/v1/issues/index.json.jbuilder new file mode 100644 index 000000000..39a467dd4 --- /dev/null +++ b/app/views/api/v1/issues/index.json.jbuilder @@ -0,0 +1,12 @@ +json.total_issues_count @total_issues_count +json.opened_count @opened_issues_count +json.closed_count @closed_issues_count +json.total_count @issues.total_count +json.has_created_issues @project.issues.size > 0 +json.issues @issues.each do |issue| + if params[:only_name].present? + json.(issue, :id, :subject) + else + json.partial! "simple_detail", locals: {issue: issue} + end +end \ No newline at end of file diff --git a/app/views/api/v1/issues/issue_priorities/_simple_detail.json.jbuilder b/app/views/api/v1/issues/issue_priorities/_simple_detail.json.jbuilder new file mode 100644 index 000000000..b7c37147a --- /dev/null +++ b/app/views/api/v1/issues/issue_priorities/_simple_detail.json.jbuilder @@ -0,0 +1 @@ +json.(priority, :id, :name) diff --git a/app/views/api/v1/issues/issue_priorities/index.json.jbuilder b/app/views/api/v1/issues/issue_priorities/index.json.jbuilder new file mode 100644 index 000000000..c1b8ebb25 --- /dev/null +++ b/app/views/api/v1/issues/issue_priorities/index.json.jbuilder @@ -0,0 +1,4 @@ +json.total_count @priorities.total_count +json.priorities @priorities.each do |priority| + json.partial! "simple_detail", locals: {priority: priority} +end \ No newline at end of file diff --git a/app/views/api/v1/issues/issue_tags/_detail.json.jbuilder b/app/views/api/v1/issues/issue_tags/_detail.json.jbuilder new file mode 100644 index 000000000..8fef8b1f6 --- /dev/null +++ b/app/views/api/v1/issues/issue_tags/_detail.json.jbuilder @@ -0,0 +1,19 @@ +json.(tag,:id, :name, :description, :color) +json.issues_count tag.issues_count +json.pull_requests_count tag.pull_requests_count +json.project do + if tag.project.present? + json.partial! "api/v1/projects/simple_detail", project: tag.project + else + json.nil! + end +end +json.user do + if tag.user.present? + json.partial! "api/v1/users/simple_user", user: tag.user + else + json.nil! + end +end +json.created_at tag.created_at.strftime("%Y-%m-%d %H:%M") +json.updated_at tag.updated_at.strftime("%Y-%m-%d %H:%M") \ No newline at end of file diff --git a/app/views/api/v1/issues/issue_tags/_simple_detail.json.jbuilder b/app/views/api/v1/issues/issue_tags/_simple_detail.json.jbuilder new file mode 100644 index 000000000..8395a8e83 --- /dev/null +++ b/app/views/api/v1/issues/issue_tags/_simple_detail.json.jbuilder @@ -0,0 +1 @@ +json.(tag, :id, :name, :color) \ No newline at end of file diff --git a/app/views/api/v1/issues/issue_tags/index.json.jbuilder b/app/views/api/v1/issues/issue_tags/index.json.jbuilder new file mode 100644 index 000000000..0bd055b57 --- /dev/null +++ b/app/views/api/v1/issues/issue_tags/index.json.jbuilder @@ -0,0 +1,8 @@ +json.total_count @issue_tags.total_count +json.issue_tags @issue_tags.each do |tag| + if params[:only_name] + json.partial! "simple_detail", locals: {tag: tag} + else + json.partial! "detail", locals: {tag: tag} + end +end \ No newline at end of file diff --git a/app/views/api/v1/issues/journals/_children_detail.json.jbuilder b/app/views/api/v1/issues/journals/_children_detail.json.jbuilder new file mode 100644 index 000000000..3fbb438b3 --- /dev/null +++ b/app/views/api/v1/issues/journals/_children_detail.json.jbuilder @@ -0,0 +1,20 @@ +json.(journal, :id, :notes, :comments_count) +json.created_at journal.created_on.strftime("%Y-%m-%d %H:%M") +json.updated_at journal.updated_on.strftime("%Y-%m-%d %H:%M") +json.user do + if journal.user.present? + json.partial! "api/v1/users/simple_user", user: journal.user + else + json.nil! + end +end +json.reply_user do + if journal.reply_journal&.user&.present? + json.partial! "api/v1/users/simple_user", user: journal.reply_journal.user + else + json.nil! + end +end +json.attachments journal.attachments.each do |attachment| + json.partial! "api/v1/attachments/simple_detail", locals: {attachment: attachment} +end \ No newline at end of file diff --git a/app/views/api/v1/issues/journals/_detail.json.jbuilder b/app/views/api/v1/issues/journals/_detail.json.jbuilder new file mode 100644 index 000000000..264997bbd --- /dev/null +++ b/app/views/api/v1/issues/journals/_detail.json.jbuilder @@ -0,0 +1,25 @@ +json.id journal.id +json.is_journal_detail journal.is_journal_detail? +json.created_at journal.created_on.strftime("%Y-%m-%d %H:%M") +json.updated_at journal.updated_on.strftime("%Y-%m-%d %H:%M") +json.user do + if journal.user.present? + json.partial! "api/v1/users/simple_user", user: journal.user + else + json.nil! + end +end +if journal.is_journal_detail? + detail = journal.journal_details.take + json.operate_category detail.property == "attr" ? detail.prop_key : detail.property + json.operate_content journal.is_journal_detail? ? journal.operate_content : nil +else + json.notes journal.notes + json.comments_count journal.comments_count + json.children_journals journal.first_ten_children_journals.each do |journal| + json.partial! "children_detail", journal: journal + end + json.attachments journal.attachments do |attachment| + json.partial! "api/v1/attachments/simple_detail", locals: {attachment: attachment} + end +end diff --git a/app/views/api/v1/issues/journals/children_journals.json.jbuilder b/app/views/api/v1/issues/journals/children_journals.json.jbuilder new file mode 100644 index 000000000..c0cd04501 --- /dev/null +++ b/app/views/api/v1/issues/journals/children_journals.json.jbuilder @@ -0,0 +1,4 @@ +json.total_count @journals.total_count +json.journals @journals do |journal| + json.partial! "children_detail", journal: journal +end \ No newline at end of file diff --git a/app/views/api/v1/issues/journals/create.json.jbuilder b/app/views/api/v1/issues/journals/create.json.jbuilder new file mode 100644 index 000000000..91f3f3174 --- /dev/null +++ b/app/views/api/v1/issues/journals/create.json.jbuilder @@ -0,0 +1 @@ +json.partial! "detail", journal: @object_result \ No newline at end of file diff --git a/app/views/api/v1/issues/journals/index.json.jbuilder b/app/views/api/v1/issues/journals/index.json.jbuilder new file mode 100644 index 000000000..49f94aa37 --- /dev/null +++ b/app/views/api/v1/issues/journals/index.json.jbuilder @@ -0,0 +1,7 @@ +json.total_journals_count @total_journals_count +json.total_operate_journals_count @total_operate_journals_count +json.total_comment_journals_count @total_comment_journals_count +json.total_count @journals.total_count +json.journals @journals do |journal| + json.partial! "detail", journal: journal +end \ No newline at end of file diff --git a/app/views/api/v1/issues/journals/update.json.jbuilder b/app/views/api/v1/issues/journals/update.json.jbuilder new file mode 100644 index 000000000..91f3f3174 --- /dev/null +++ b/app/views/api/v1/issues/journals/update.json.jbuilder @@ -0,0 +1 @@ +json.partial! "detail", journal: @object_result \ No newline at end of file diff --git a/app/views/api/v1/issues/milestones/_detail.json.jbuilder b/app/views/api/v1/issues/milestones/_detail.json.jbuilder new file mode 100644 index 000000000..b71f41c7e --- /dev/null +++ b/app/views/api/v1/issues/milestones/_detail.json.jbuilder @@ -0,0 +1,7 @@ +json.(milestone, :id, :name, :description, :effective_date, :status) +json.issues_count milestone.opened_issues.size + milestone.closed_issues.size +json.opened_issues_count milestone.opened_issues.size +json.close_issues_count milestone.closed_issues.size +json.percent milestone.issue_percent +json.created_at milestone.created_on.strftime("%Y-%m-%d %H:%M") +json.updated_on milestone.updated_on.strftime("%Y-%m-%d %H:%M") diff --git a/app/views/api/v1/issues/milestones/_simple_detail.json.jbuilder b/app/views/api/v1/issues/milestones/_simple_detail.json.jbuilder new file mode 100644 index 000000000..667f7b6a7 --- /dev/null +++ b/app/views/api/v1/issues/milestones/_simple_detail.json.jbuilder @@ -0,0 +1 @@ +json.(milestone, :id, :name) \ No newline at end of file diff --git a/app/views/api/v1/issues/milestones/index.json.jbuilder b/app/views/api/v1/issues/milestones/index.json.jbuilder new file mode 100644 index 000000000..38623d2b4 --- /dev/null +++ b/app/views/api/v1/issues/milestones/index.json.jbuilder @@ -0,0 +1,10 @@ +json.closed_milestone_count @closed_milestone_count +json.opening_milestone_count @opening_milestone_count +json.total_count @milestones.total_count +json.milestones @milestones.each do |milestone| + if params[:only_name] + json.partial! "simple_detail", locals: {milestone: milestone} + else + json.partial! "detail", locals: {milestone: milestone} + end +end \ No newline at end of file diff --git a/app/views/api/v1/issues/milestones/show.json.jbuilder b/app/views/api/v1/issues/milestones/show.json.jbuilder new file mode 100644 index 000000000..ce1886522 --- /dev/null +++ b/app/views/api/v1/issues/milestones/show.json.jbuilder @@ -0,0 +1,12 @@ +json.milestone do + json.partial! "detail", locals: {milestone: @milestone} +end +json.total_issues_count @total_issues_count +json.closed_issues_count @closed_issues_count +json.opened_issues_count @opened_issues_count +json.total_count @issues.total_count +json.issues @issues.each do |issue| + if issue.issue_classify == "issue" + json.partial! "api/v1/issues/simple_detail", locals: {issue: issue} + end +end \ No newline at end of file diff --git a/app/views/api/v1/issues/show.json.jbuilder b/app/views/api/v1/issues/show.json.jbuilder new file mode 100644 index 000000000..55028fc64 --- /dev/null +++ b/app/views/api/v1/issues/show.json.jbuilder @@ -0,0 +1,2 @@ +json.partial! "api/v1/issues/detail", locals: {issue: @issue} +json.user_permission @user_permission diff --git a/app/views/api/v1/issues/statues/_simple_detail.json.jbuilder b/app/views/api/v1/issues/statues/_simple_detail.json.jbuilder new file mode 100644 index 000000000..f66b6c95a --- /dev/null +++ b/app/views/api/v1/issues/statues/_simple_detail.json.jbuilder @@ -0,0 +1 @@ +json.(status, :id, :name) diff --git a/app/views/api/v1/issues/statues/index.json.jbuilder b/app/views/api/v1/issues/statues/index.json.jbuilder new file mode 100644 index 000000000..9fb60acc2 --- /dev/null +++ b/app/views/api/v1/issues/statues/index.json.jbuilder @@ -0,0 +1,4 @@ +json.total_count @statues.total_count +json.statues @statues.each do |status| + json.partial! "simple_detail", locals: {status: status} +end \ No newline at end of file diff --git a/app/views/api/v1/issues/update.json.jbuilder b/app/views/api/v1/issues/update.json.jbuilder new file mode 100644 index 000000000..f45ef5b2f --- /dev/null +++ b/app/views/api/v1/issues/update.json.jbuilder @@ -0,0 +1 @@ +json.partial! "api/v1/issues/detail", locals: {issue: @object_result} diff --git a/app/views/api/v1/projects/code_stats/index.json.jbuilder b/app/views/api/v1/projects/code_stats/index.json.jbuilder index 0b64270f7..3f98fa1ee 100644 --- a/app/views/api/v1/projects/code_stats/index.json.jbuilder +++ b/app/views/api/v1/projects/code_stats/index.json.jbuilder @@ -4,7 +4,7 @@ json.change_files @result_object["change_files"] json.additions @result_object["additions"] json.deletions @result_object["deletions"] json.commit_count_in_all_branches @result_object["commit_count_in_all_branches"] -json.authors @result_object["authors"].each do |author| +json.authors @result_object["authors"].each do |author| json.author do json.partial! 'api/v1/users/commit_user_email', locals: { user: render_cache_commit_author(author), name: author['name'], email: author['email'] } end diff --git a/app/views/api/v1/projects/collaborators/index.json.jbuilder b/app/views/api/v1/projects/collaborators/index.json.jbuilder new file mode 100644 index 000000000..c0c33c6ba --- /dev/null +++ b/app/views/api/v1/projects/collaborators/index.json.jbuilder @@ -0,0 +1,4 @@ +json.total_count @collaborators.total_count +json.collaborators @collaborators.each do |collaborator| + json.partial! "api/v1/users/simple_user", locals: {user: collaborator} +end \ No newline at end of file diff --git a/app/views/api/v1/projects/issues/_simple_detail.json.jbuilder b/app/views/api/v1/projects/issues/_simple_detail.json.jbuilder deleted file mode 100644 index e69de29bb..000000000 diff --git a/app/views/project_trends/index.json.jbuilder b/app/views/project_trends/index.json.jbuilder index 6dca7bdb5..abfd651ef 100644 --- a/app/views/project_trends/index.json.jbuilder +++ b/app/views/project_trends/index.json.jbuilder @@ -14,4 +14,8 @@ json.project_trends do json.partial! "detail", trend: trend end end +json.ai_shang_v1_url ai_shang_v1_url(@project) +json.ai_shang_v2_url ai_shang_v2_url(@project) +json.ai_shang_v3_url ai_shang_v3_url(@project) +json.ai_shang_v4_url ai_shang_v4_url(@project) diff --git a/app/views/pull_requests/edit.json.jbuilder b/app/views/pull_requests/edit.json.jbuilder index 683b1961c..08cefcb91 100644 --- a/app/views/pull_requests/edit.json.jbuilder +++ b/app/views/pull_requests/edit.json.jbuilder @@ -12,4 +12,7 @@ json.issue_tag_ids @issue&.issue_tags_value&.split(",") json.commits_count @pull_request.commits_count json.files_count @pull_request.files_count json.comments_count @pull_request.comments_count -json.reviewers @pull_request.reviewers.pluck(:login) \ No newline at end of file +json.reviewers @pull_request.reviewers.pluck(:login) +json.attached_issues @pull_request.attached_issues.each do |issue| + json.(issue, :id, :subject, :project_issues_index) +end diff --git a/app/views/pull_requests/index.json.jbuilder b/app/views/pull_requests/index.json.jbuilder index ace52945c..9df36fae7 100644 --- a/app/views/pull_requests/index.json.jbuilder +++ b/app/views/pull_requests/index.json.jbuilder @@ -38,6 +38,9 @@ json.issues do json.version issue.version.try(:name) json.journals_count issue.get_journals_size json.issue_tags issue.get_issue_tags + json.attached_issues pr.attached_issues.each do |issue| + json.(issue, :id, :subject, :project_issues_index) + end end end diff --git a/app/views/pull_requests/show.json.jbuilder b/app/views/pull_requests/show.json.jbuilder index 27c393de5..71f0641b6 100644 --- a/app/views/pull_requests/show.json.jbuilder +++ b/app/views/pull_requests/show.json.jbuilder @@ -51,4 +51,8 @@ json.issue do json.issue_tags @issue.get_issue_tags end +json.attached_issues @pull_request.attached_issues.each do |issue| + json.(issue, :id, :subject, :project_issues_index) +end + json.conflict_files @pull_request.conflict_files diff --git a/app/views/repositories/_contributor.json.jbuilder b/app/views/repositories/_contributor.json.jbuilder index 56fa9ce86..d2caa53cd 100644 --- a/app/views/repositories/_contributor.json.jbuilder +++ b/app/views/repositories/_contributor.json.jbuilder @@ -13,4 +13,6 @@ else json.type user["type"] json.name user["name"] json.image_url user["avatar_url"] + db_user = User.find_by_id(user["id"]) + json.contribution_perc db_user.contribution_perc(project) end diff --git a/app/views/repositories/_simple_entry.json.jbuilder b/app/views/repositories/_simple_entry.json.jbuilder index aae0e613c..339214cc4 100644 --- a/app/views/repositories/_simple_entry.json.jbuilder +++ b/app/views/repositories/_simple_entry.json.jbuilder @@ -2,7 +2,7 @@ if @project.forge? is_dir = @sub_entries.is_a?(Array) file_name = entry['name'] file_type = file_name.starts_with?('.') ? file_name[1..-1] : File.extname(file_name.to_s)[1..-1] - direct_download = file_name.to_s.downcase != "Makefile".downcase && download_type(file_type) + direct_download = ["makefile","dockerfile"].exclude?(file_name.to_s.downcase) && download_type(file_type) image_type = image_type?(file_type) json.name file_name json.sha entry['sha'] diff --git a/app/views/repositories/contributors.json.jbuilder b/app/views/repositories/contributors.json.jbuilder index 2fb6abae8..4534de693 100644 --- a/app/views/repositories/contributors.json.jbuilder +++ b/app/views/repositories/contributors.json.jbuilder @@ -1,6 +1,6 @@ total_count = @contributors.size json.list @contributors.each do |contributor| - json.partial! 'contributor', locals: { contributor: contributor } + json.partial! 'contributor', locals: { contributor: contributor, project: @project } end json.total_count total_count diff --git a/app/views/users/blockchain_balance.json.jbuilder b/app/views/users/blockchain_balance.json.jbuilder new file mode 100644 index 000000000..9216733c2 --- /dev/null +++ b/app/views/users/blockchain_balance.json.jbuilder @@ -0,0 +1,7 @@ +json.total_count @total_count +json.projects @projects.each do |p| + if p[:project].present? + json.partial! 'projects/detail', locals: { project: p[:project] } + end + json.balance p[:balance] +end \ No newline at end of file diff --git a/app/views/users/get_user_info.json.jbuilder b/app/views/users/get_user_info.json.jbuilder index 68bfa6589..dc8315ea2 100644 --- a/app/views/users/get_user_info.json.jbuilder +++ b/app/views/users/get_user_info.json.jbuilder @@ -28,3 +28,4 @@ json.message_unread_total @message_unread_total json.has_trace_user @user.trace_user.present? json.is_new @user.login.present? && params[:login].to_s.include?("#{@user.login}") json.nps EduSetting.get("nps-on-off-switch").to_s == 'true' && UserNp.where(user_id: current_user.id).where("created_at >= ?", (Time.now - 30.days).beginning_of_day ).blank? +json.open_blockchain EduSetting.get("open_blockchain_users").to_s.split(",").include?(@user.id.to_s) || EduSetting.get("open_blockchain_users").to_s.split(",").include?(@user.login) diff --git a/config/configuration.yml.example b/config/configuration.yml.example index f056dee1b..6ae32e4f3 100644 --- a/config/configuration.yml.example +++ b/config/configuration.yml.example @@ -75,6 +75,9 @@ default: &default forum: domain: '' base_url: '/api' + # 区块链相关配置 + blockchain: + api_url: 'blockchain service url' production: <<: *default diff --git a/config/routes.rb b/config/routes.rb index 3488bacb4..c544c9198 100644 --- a/config/routes.rb +++ b/config/routes.rb @@ -123,6 +123,20 @@ Rails.application.routes.draw do put 'commons/unhidden', to: 'commons#unhidden' delete 'commons/delete', to: 'commons#delete' + # blockchain related routes + get 'users/blockchain/balance', to: 'users#blockchain_balance' + post 'users/blockchain/balance_project', to: 'users#blockchain_balance_one_project' + post 'users/blockchain/transfer', to: 'users#blockchain_transfer' + post 'users/blockchain/exchange', to: 'users#blockchain_exchange' + post 'users/blockchain/create_trade', to: 'users#blockchain_create_trade' + get '/users/blockchain/get_trades', to: 'users#blockchain_get_trades' + post '/users/blockchain/trade', to: 'users#blockchain_trade' + get '/users/blockchain/get_verify_trades', to: 'users#blockchain_get_verify_trades' + post '/users/blockchain/verify_trade', to: 'users#blockchain_verify_trade' + get '/users/blockchain/get_history_trades', to: 'users#blockchain_get_history_trades' + post '/blockchain/issue/get_token_num', to: 'users#blockchain_get_issue_token_num' + get '/projects/blockchain/get_unclosed_issue_list', to: 'users#blockchain_get_unclosed_issue_list' + resources :owners, only: [:index, :show] scope module: :organizations do @@ -243,6 +257,8 @@ Rails.application.routes.draw do get :watch_users get :fan_users get :hovercard + get :hovercard4proj # author: zxh, 获取用户对项目的贡献情况 + get :contribution_perc put :update_image get :get_image end diff --git a/config/routes/api.rb b/config/routes/api.rb index 31127c7bf..6e688a632 100644 --- a/config/routes/api.rb +++ b/config/routes/api.rb @@ -27,9 +27,31 @@ defaults format: :json do end end + resources :issues, param: :index, except: [:new, :edit] do + collection do + patch :batch_update + delete :batch_destroy + end + + member do + resources :journals, module: :issues, only: [:index, :create, :update, :destroy] do + member do + get :children_journals + end + end + end + end + scope module: :issues do + resources :issue_tags, except: [:new, :edit] + resources :milestones, except: [:new, :edit] + resources :issue_statues, only: [:index], controller: '/api/v1/issues/statues' + resources :issue_authors, only: [:index], controller: '/api/v1/issues/authors' + resources :issue_assigners, only: [:index], controller: '/api/v1/issues/assigners' + resources :issue_priorities, only: [:index] + end + # projects文件夹下的 scope module: :projects do - resources :issues resources :pulls, module: 'pulls' do resources :versions, only: [:index] do member do @@ -39,8 +61,7 @@ defaults format: :json do resources :journals, except: [:show, :edit] resources :reviews, only: [:index, :create] end - - resources :versions + resources :collaborators, only: [:index] resources :release_versions resources :webhooks do member do diff --git a/db/migrate/20201230070048_add_use_blockchain_to_projects.rb b/db/migrate/20201230070048_add_use_blockchain_to_projects.rb new file mode 100644 index 000000000..f7e2fdde0 --- /dev/null +++ b/db/migrate/20201230070048_add_use_blockchain_to_projects.rb @@ -0,0 +1,5 @@ +class AddUseBlockchainToProjects < ActiveRecord::Migration[5.2] + def change + add_column :projects, :use_blockchain, :boolean, default: 0 + end +end diff --git a/db/migrate/20210421081736_add_blockchain_token_num_to_issue.rb b/db/migrate/20210421081736_add_blockchain_token_num_to_issue.rb new file mode 100644 index 000000000..1391667e5 --- /dev/null +++ b/db/migrate/20210421081736_add_blockchain_token_num_to_issue.rb @@ -0,0 +1,5 @@ +class AddBlockchainTokenNumToIssue < ActiveRecord::Migration[5.2] + def change + add_column :issues, :blockchain_token_num, :integer + end +end diff --git a/db/migrate/20230207091507_create_issue_assigners.rb b/db/migrate/20230207091507_create_issue_assigners.rb new file mode 100644 index 000000000..1a25db213 --- /dev/null +++ b/db/migrate/20230207091507_create_issue_assigners.rb @@ -0,0 +1,10 @@ +class CreateIssueAssigners < ActiveRecord::Migration[5.2] + def change + create_table :issue_assigners do |t| + t.references :issue + t.references :assigner, references: :user + + t.timestamps + end + end +end diff --git a/db/migrate/20230208023811_create_issue_participants.rb b/db/migrate/20230208023811_create_issue_participants.rb new file mode 100644 index 000000000..834061053 --- /dev/null +++ b/db/migrate/20230208023811_create_issue_participants.rb @@ -0,0 +1,11 @@ +class CreateIssueParticipants < ActiveRecord::Migration[5.2] + def change + create_table :issue_participants do |t| + t.references :issue + t.references :participant, references: :user + t.integer :participant_type, default: 0 + + t.timestamps + end + end +end diff --git a/db/migrate/20230223065106_add_some_columns_to_issue_upgrade.rb b/db/migrate/20230223065106_add_some_columns_to_issue_upgrade.rb new file mode 100644 index 000000000..161328746 --- /dev/null +++ b/db/migrate/20230223065106_add_some_columns_to_issue_upgrade.rb @@ -0,0 +1,5 @@ +class AddSomeColumnsToIssueUpgrade < ActiveRecord::Migration[5.2] + def change + add_column :issue_tags, :pull_requests_count, :integer, default: 0 + end +end diff --git a/db/migrate/20230302063013_create_pull_attached_issues.rb b/db/migrate/20230302063013_create_pull_attached_issues.rb new file mode 100644 index 000000000..c3b4f6528 --- /dev/null +++ b/db/migrate/20230302063013_create_pull_attached_issues.rb @@ -0,0 +1,10 @@ +class CreatePullAttachedIssues < ActiveRecord::Migration[5.2] + def change + create_table :pull_attached_issues do |t| + t.references :pull_request + t.references :issue + + t.timestamps + end + end +end diff --git a/db/migrate/20230309095515_add_fixed_to_pull_attached_issues.rb b/db/migrate/20230309095515_add_fixed_to_pull_attached_issues.rb new file mode 100644 index 000000000..9f9952121 --- /dev/null +++ b/db/migrate/20230309095515_add_fixed_to_pull_attached_issues.rb @@ -0,0 +1,5 @@ +class AddFixedToPullAttachedIssues < ActiveRecord::Migration[5.2] + def change + add_column :pull_attached_issues, :fixed, :boolean, default: false + end +end diff --git a/lib/tasks/upgrade_issue_generate_data.rake b/lib/tasks/upgrade_issue_generate_data.rake new file mode 100644 index 000000000..07382a1e9 --- /dev/null +++ b/lib/tasks/upgrade_issue_generate_data.rake @@ -0,0 +1,59 @@ + + +namespace :upgrade_issue_generate_data do + # 执行示例 bundle exec rake upgrade_issue_generate_data:project_issues_index + # 线上环境执行示例 RAILS_ENV=production bundle exec rake upgrade_issue_generate_data:project_issues_index + desc "upgrade_issue_generate_data: fix issue project_issues_index" + + task project_issues_index: :environment do + puts "____________fix start________________" + + Issue.issue_issue.update_all(project_issues_index: nil) + count = 0 + Issue.issue_issue.where(project_issues_index: nil).group(:project_id).count.each do |pid, count| + p = Project.find_by_id(pid) + issues = p.issues.order(created_on: :asc) + issues.find_each.with_index do |issue, index| + count += 1 + issue.update_column(:project_issues_index, index+1) + end + end + puts "____________fix end_______total:#{count}_________" + end + + # 执行示例 bundle exec rake upgrade_issue_generate_data:project_init_issue_tags_and_status + # 线上环境执行示例 RAILS_ENV=production bundle exec rake upgrade_issue_generate_data:project_init_issue_tags_and_status + desc "upgrade_issue_generate_data: fix project init issue_tags" + + task project_init_issue_tags_and_status: :environment do + puts "____________fix start________________" + IssuePriority.init_data + IssueStatus.init_data + IssueTag.order(created_at: :desc).find_each do |it| + it.reset_counter_field + end + IssueTag.where(user_id: nil).destroy_all + count = 0 + Project.order(created_on: :desc).find_each do |project| + count += 1 + IssueTag.init_data(project.id) + end + puts "____________fix end____total:#{count}__________" + end + + # 执行示例 bundle exec rake upgrade_issue_generate_data:build_assigners_and_participants + # 线上环境执行示例 RAILS_ENV=production bundle exec rake upgrade_issue_generate_data:build_assigners_and_participants + desc "upgrade_issue_generate_data: fix issue assigners and participants" + + task build_assigners_and_participants: :environment do + puts "____________fix start________________" + count = 0 + Issue.order(created_on: :desc).find_each do |issue| + count += 1 + issue.issue_assigners.find_or_create_by(assigner_id: issue.assigned_to_id) + issue.issue_participants.find_or_create_by(participant_id: issue.assigned_to_id, participant_type: 'assigned') + issue.issue_participants.find_or_create_by(participant_id: issue.author_id, participant_type: 'authored') + end + puts "____________fix end____total:#{count}__________" + end +end \ No newline at end of file