diff --git a/README.rdoc b/README.rdoc index f092fe45..3923debd 100644 --- a/README.rdoc +++ b/README.rdoc @@ -110,12 +110,9 @@ For more information on features, please refer to the user guide rake redmine:plugins:migrate NAME=redmine_wktime VERSION=0 RAILS_ENV=production -=== Release Notes for v4.7.5 +=== Release Notes for v4.8 -* *Bug* *fixes* - - Fixed month wise date sorting issue in Accounting module - - Fixed monthly closing balance total issue in Accounting module - - Fixed unable to save amount of less then 1 in Accounting module + - Redmine 6.0 compatibility. === Customization diff --git a/app/controllers/wkaccounting_controller.rb b/app/controllers/wkaccounting_controller.rb index db4506e4..14f1a474 100644 --- a/app/controllers/wkaccounting_controller.rb +++ b/app/controllers/wkaccounting_controller.rb @@ -15,24 +15,24 @@ # along with this program; if not, write to the Free Software # Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. -class WkaccountingController < WkbaseController - unloadable +class WkaccountingController < WkbaseController + before_action :require_login before_action :check_perm_and_redirect, :only => [:index, :edit, :update] before_action :check_ac_admin_and_redirect, :only => [:destroy] include WkaccountingHelper def index end - + def check_perm_and_redirect unless check_permission render_403 return false end end - + def check_ac_admin_and_redirect - unless validateERPPermission("A_ACC_PRVLG") + unless validateERPPermission("A_ACC_PRVLG") render_403 return false end @@ -40,6 +40,6 @@ def check_ac_admin_and_redirect def check_permission ret = false - return validateERPPermission("B_ACC_PRVLG") || validateERPPermission("A_ACC_PRVLG") + return validateERPPermission("B_ACC_PRVLG") || validateERPPermission("A_ACC_PRVLG") end end diff --git a/app/controllers/wkasset_controller.rb b/app/controllers/wkasset_controller.rb index 1e192ab3..da4feb32 100644 --- a/app/controllers/wkasset_controller.rb +++ b/app/controllers/wkasset_controller.rb @@ -15,7 +15,7 @@ # along with this program; if not, write to the Free Software # Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. class WkassetController < WkproductitemController - unloadable + menu_item :wkproduct include WktimeHelper include WkassetdepreciationHelper diff --git a/app/controllers/wkassetdepreciation_controller.rb b/app/controllers/wkassetdepreciation_controller.rb index b76f6f50..a09146e6 100644 --- a/app/controllers/wkassetdepreciation_controller.rb +++ b/app/controllers/wkassetdepreciation_controller.rb @@ -16,7 +16,7 @@ # Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. class WkassetdepreciationController < WkassetController - unloadable + menu_item :wkproduct include WktimeHelper include WkinventoryHelper diff --git a/app/controllers/wkattendance_controller.rb b/app/controllers/wkattendance_controller.rb index 3f72b0ee..c6ade5c7 100644 --- a/app/controllers/wkattendance_controller.rb +++ b/app/controllers/wkattendance_controller.rb @@ -16,7 +16,7 @@ # Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. class WkattendanceController < WkbaseController - unloadable + menu_item :wkattendance include WktimeHelper diff --git a/app/controllers/wkattributegroup_controller.rb b/app/controllers/wkattributegroup_controller.rb index 7c87e386..3761621f 100644 --- a/app/controllers/wkattributegroup_controller.rb +++ b/app/controllers/wkattributegroup_controller.rb @@ -16,7 +16,7 @@ # Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. class WkattributegroupController < WkinventoryController - unloadable + menu_item :wkproduct before_action :require_login before_action :check_perm_and_redirect, :only => [:index, :edit, :update, :destroy, :edit_product_attribute, :updateProductAttribute] @@ -42,7 +42,7 @@ def index end entries = entries.reorder(sort_clause) respond_to do |format| - format.html { + format.html { @groupEntries = formPagination(entries) } format.csv{ @@ -52,23 +52,23 @@ def index } end end - + def formPagination(entries) @entry_count = entries.count setLimitAndOffset() pageEntries = entries.limit(@limit).offset(@offset) pageEntries end - + def edit @groupEntry = nil unless params[:group_id].blank? @groupEntry = WkAttributeGroup.find(params[:group_id]) @groupAttrEntries = formPagination(@groupEntry.product_attributes) - end - end - - def update + end + end + + def update if params[:group_id].blank? attrGroup = WkAttributeGroup.new else @@ -84,7 +84,7 @@ def update flash[:error] = attrGroup.errors.full_messages.join("
") end end - + def destroy attrGroup = WkAttributeGroup.find(params[:group_id].to_i) if attrGroup.destroy @@ -94,15 +94,15 @@ def destroy end redirect_back_or_default :action => 'index', :tab => params[:tab] end - + def edit_product_attribute @attributeEntry = nil @groupEntry = WkAttributeGroup.find(params[:group_id].to_i) unless params[:product_attribute_id].blank? @attributeEntry = WkProductAttribute.find(params[:product_attribute_id]) - end + end end - + def updateProductAttribute if params[:product_attribute_id].blank? productAttr = WkProductAttribute.new @@ -120,7 +120,7 @@ def updateProductAttribute flash[:error] = product.errors.full_messages.join("
") end end - + def destroyProductAttribute productAttr = WkProductAttribute.find(params[:product_attribute_id].to_i) groupId = productAttr.group_id @@ -131,8 +131,8 @@ def destroyProductAttribute end redirect_back_or_default :action => 'edit' , :tab => 'wkattributegroup', :group_id => groupId end - - def setLimitAndOffset + + def setLimitAndOffset if api_request? @offset, @limit = api_offset_and_limit if !params[:limit].blank? @@ -145,7 +145,7 @@ def setLimitAndOffset @entry_pages = Paginator.new @entry_count, per_page_option, params['page'] @limit = @entry_pages.per_page @offset = @entry_pages.offset - end + end end def set_filter_session diff --git a/app/controllers/wkbase_controller.rb b/app/controllers/wkbase_controller.rb index ad169f96..c0fdab62 100644 --- a/app/controllers/wkbase_controller.rb +++ b/app/controllers/wkbase_controller.rb @@ -16,7 +16,7 @@ # Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. class WkbaseController < ApplicationController - unloadable + before_action :require_login before_action :clear_sort_session, :unseen before_action :check_update_user_permissions, :only => [:updateWkuserData, :getWkuserData, :updateWkuserVal] diff --git a/app/controllers/wkbrand_controller.rb b/app/controllers/wkbrand_controller.rb index 2586e465..01e6d7c7 100644 --- a/app/controllers/wkbrand_controller.rb +++ b/app/controllers/wkbrand_controller.rb @@ -16,7 +16,7 @@ # Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. class WkbrandController < WkinventoryController - unloadable + menu_item :wkproduct before_action :require_login before_action :check_perm_and_redirect, :only => [:index, :edit, :update, :destroy, :edit_product_model, :updateProductModel] diff --git a/app/controllers/wkcontact_controller.rb b/app/controllers/wkcontact_controller.rb index 772247bd..94d6d388 100644 --- a/app/controllers/wkcontact_controller.rb +++ b/app/controllers/wkcontact_controller.rb @@ -16,7 +16,7 @@ # Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. class WkcontactController < WkcrmController - unloadable + include WkaccountprojectHelper include WksalesquoteHelper diff --git a/app/controllers/wkcrm_controller.rb b/app/controllers/wkcrm_controller.rb index 3ddf4b69..d452b662 100644 --- a/app/controllers/wkcrm_controller.rb +++ b/app/controllers/wkcrm_controller.rb @@ -16,7 +16,7 @@ # Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. class WkcrmController < WkbaseController - unloadable + before_action :require_login before_action :check_perm_and_redirect, :only => [:index, :edit, :update] before_action :check_crm_admin_and_redirect, :only => [:destroy] diff --git a/app/controllers/wkcrmaccount_controller.rb b/app/controllers/wkcrmaccount_controller.rb index 0baf790f..2965a0d1 100644 --- a/app/controllers/wkcrmaccount_controller.rb +++ b/app/controllers/wkcrmaccount_controller.rb @@ -1,9 +1,9 @@ class WkcrmaccountController < WkaccountController - unloadable + menu_item :wklead accept_api_auth :index, :edit, :update def getAccountType 'A' - end + end end diff --git a/app/controllers/wkcrmactivity_controller.rb b/app/controllers/wkcrmactivity_controller.rb index b885ba73..c7109ad9 100644 --- a/app/controllers/wkcrmactivity_controller.rb +++ b/app/controllers/wkcrmactivity_controller.rb @@ -17,7 +17,7 @@ class WkcrmactivityController < WkcrmController - unloadable + menu_item :wklead include WktimeHelper include WkdocumentHelper diff --git a/app/controllers/wkcrmcontact_controller.rb b/app/controllers/wkcrmcontact_controller.rb index 627597a6..866a2b48 100644 --- a/app/controllers/wkcrmcontact_controller.rb +++ b/app/controllers/wkcrmcontact_controller.rb @@ -16,7 +16,7 @@ # Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. class WkcrmcontactController < WkcontactController - unloadable + menu_item :wklead accept_api_auth :index, :edit, :update diff --git a/app/controllers/wkcrmenumeration_controller.rb b/app/controllers/wkcrmenumeration_controller.rb index 3814eb7a..8b334393 100644 --- a/app/controllers/wkcrmenumeration_controller.rb +++ b/app/controllers/wkcrmenumeration_controller.rb @@ -16,11 +16,11 @@ # Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. class WkcrmenumerationController < WkbaseController - unloadable + include WktimeHelper before_action :require_login before_action :check_perm_and_redirect, :only => [:index, :edit, :update, :destroy] - + accept_api_auth :getCrmEnumerations include WkcrmenumerationHelper @@ -36,14 +36,14 @@ def index entries = nil if !enumName.blank? && !enumerationType.blank? entries = WkCrmEnumeration.where(:enum_type => enumerationType).where("LOWER(name) like LOWER(?)", "%#{enumName}%") - elsif enumName.blank? && !enumerationType.blank? + elsif enumName.blank? && !enumerationType.blank? entries = WkCrmEnumeration.where(:enum_type => enumerationType) elsif !enumName.blank? && enumerationType.blank? entries = WkCrmEnumeration.where("LOWER(name) like LOWER(?)", "%#{enumName}%") else entries = WkCrmEnumeration.all end - entries = entries.reorder(sort_clause) + entries = entries.reorder(sort_clause) respond_to do |format| format.html { formPagination(entries) @@ -55,16 +55,16 @@ def index } end end - + def edit @enumEntry = nil unless params[:enum_id].blank? @enumEntry = WkCrmEnumeration.find(params[:enum_id].to_i) end end - + def update - wkcrmenumeration = nil + wkcrmenumeration = nil unless params[:enum_id].blank? wkcrmenumeration = WkCrmEnumeration.find(params[:enum_id].to_i) else @@ -75,7 +75,7 @@ def update wkcrmenumeration.active = params[:enumActive] wkcrmenumeration.enum_type = params[:enumType] wkcrmenumeration.is_default = params[:enumDefaultValue] - if wkcrmenumeration.valid? + if wkcrmenumeration.valid? wkcrmenumeration.save redirect_to :controller => 'wkcrmenumeration',:action => 'index' , :tab => 'wkcrmenumeration' flash[:notice] = l(:notice_successful_update) @@ -84,19 +84,19 @@ def update redirect_to :controller => 'wkcrmenumeration',:action => 'edit' end end - + def set_filter_session filters = [:enumname, :enumType] super(filters) end - + def formPagination(entries) @entry_count = entries.count setLimitAndOffset() @crmenum = entries.limit(@limit).offset(@offset) end - - def setLimitAndOffset + + def setLimitAndOffset if api_request? @offset, @limit = api_offset_and_limit if !params[:limit].blank? @@ -109,16 +109,16 @@ def setLimitAndOffset @entry_pages = Paginator.new @entry_count, per_page_option, params['page'] @limit = @entry_pages.per_page @offset = @entry_pages.offset - end + end end - + def destroy WkCrmEnumeration.find(params[:enum_id].to_i).destroy - + flash[:notice] = l(:notice_successful_delete) redirect_back_or_default :action => 'index', :tab => params[:tab] end - + def check_perm_and_redirect unless User.current.admin? || hasSettingPerm render_403 diff --git a/app/controllers/wkdelivery_controller.rb b/app/controllers/wkdelivery_controller.rb index 3764c303..d45acd8d 100644 --- a/app/controllers/wkdelivery_controller.rb +++ b/app/controllers/wkdelivery_controller.rb @@ -16,7 +16,7 @@ # Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. class WkdeliveryController < WkinventoryController - unloadable + menu_item :wkproduct before_action :require_login @@ -46,23 +46,23 @@ def index elsif filter_type == '2' && contact_id.blank? parentType = 'WkCrmContact' end - + if filter_type == '3' && !account_id.blank? parentType = 'WkAccount' parentId = account_id elsif filter_type == '3' && account_id.blank? parentType = 'WkAccount' end - - unless parentId.blank? + + unless parentId.blank? sqlwhere = sqlwhere + " and wk_shipments.parent_id = '#{parentId}' " end - + unless parentType.blank? sqlwhere = sqlwhere + " and wk_shipments.parent_type = '#{parentType}' " end - - if !@from.blank? && !@to.blank? + + if !@from.blank? && !@to.blank? sqlwhere = sqlwhere + " and wk_shipments.shipment_date between '#{@from}' and '#{@to}' " end @@ -167,7 +167,7 @@ def update deliveryItem.org_selling_price = params["selling_price_#{i}"] end deliveryItem.currency = sysCurrency - deliveryItem.selling_price = getExchangedAmount(params["currency_#{i}"], params["selling_price_#{i}"]) + deliveryItem.selling_price = getExchangedAmount(params["currency_#{i}"], params["selling_price_#{i}"]) deliveryItem.serial_number = params["serial_number_#{i}"] deliveryItem.running_sn = params["running_sn_#{i}"] deliveryItem.notes = params["notes_#{i}"] @@ -184,8 +184,8 @@ def update end end i = i + 1 - end - if errorMsg.blank? + end + if errorMsg.blank? redirect_to action: 'index', controller: controller_name, tab: controller_name flash[:notice] = l(:notice_successful_update) else @@ -208,14 +208,14 @@ def set_filter_session filters = [:period_type, :period, :contact_id, :account_id, :project_id, :polymorphic_filter, :from, :to, :delivery_status] super(filters, {from: @from, to: @to}) end - + def formPagination(entries) @entry_count = entries.count setLimitAndOffset() @deliveryEntries = entries.limit(@limit).offset(@offset) end - - def setLimitAndOffset + + def setLimitAndOffset if api_request? @offset, @limit = api_offset_and_limit if !params[:limit].blank? @@ -228,13 +228,13 @@ def setLimitAndOffset @entry_pages = Paginator.new @entry_count, per_page_option, params['page'] @limit = @entry_pages.per_page @offset = @entry_pages.offset - end + end end - + def additionalContactType false end - + def additionalAccountType false end @@ -250,7 +250,7 @@ def getOrderContactType def getAccountDDLbl l(:field_account) end - + def getShipmentType 'O' end @@ -262,11 +262,11 @@ def showProjectDD def getAdditionalDD "wkdelivery/deliveryadditionaldd" end - + def textfield_size 6 end - + def populateProductItemDD itemArr = "" if params[:update_DD] =='inventory_item' @@ -304,5 +304,5 @@ def getInvoiceNos respond_to do |format| format.text { render :plain => invoiceArr } end - end + end end diff --git a/app/controllers/wkdocument_controller.rb b/app/controllers/wkdocument_controller.rb index fae742f2..96852526 100644 --- a/app/controllers/wkdocument_controller.rb +++ b/app/controllers/wkdocument_controller.rb @@ -16,11 +16,11 @@ # Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. class WkdocumentController < WkbaseController - unloadable + before_action :find_attachment, :only => [:destroy, :download] include WkdocumentHelper helper :attachments - + def new end @@ -70,7 +70,7 @@ def detect_content_type(attachment) end content_type.to_s end - + def disposition(attachment) if attachment.is_pdf? 'inline' diff --git a/app/controllers/wkexchangerate_controller.rb b/app/controllers/wkexchangerate_controller.rb index a3ce682a..c87fa832 100644 --- a/app/controllers/wkexchangerate_controller.rb +++ b/app/controllers/wkexchangerate_controller.rb @@ -1,9 +1,9 @@ class WkexchangerateController < WkbillingController - unloadable + menu_item :wkcrmenumeration def index - entries = WkExCurrencyRate.all + entries = WkExCurrencyRate.all formPagination(entries) end @@ -19,24 +19,24 @@ def update curExchanges.from_c = params[:from_currency][i] curExchanges.to_c = params[:to_currency][i] curExchanges.ex_rate = params[:rate][i] - curExchanges.save() + curExchanges.save() end - - if !arrId.blank? + + if !arrId.blank? WkExCurrencyRate.where(:id => arrId).delete_all end - + redirect_to :controller => 'wkexchangerate',:action => 'index' , :tab => 'wkexchangerate' flash[:notice] = l(:notice_successful_update) end - + def formPagination(entries) @entry_count = entries.count setLimitAndOffset() @curentry = entries.limit(@limit).offset(@offset) end - - def setLimitAndOffset + + def setLimitAndOffset if api_request? @offset, @limit = api_offset_and_limit if !params[:limit].blank? @@ -49,7 +49,7 @@ def setLimitAndOffset @entry_pages = Paginator.new @entry_count, per_page_option, params['page'] @limit = @entry_pages.per_page @offset = @entry_pages.offset - end + end end end diff --git a/app/controllers/wkexpense_controller.rb b/app/controllers/wkexpense_controller.rb index 046a5ebd..ceba1b11 100644 --- a/app/controllers/wkexpense_controller.rb +++ b/app/controllers/wkexpense_controller.rb @@ -16,7 +16,7 @@ # Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. class WkexpenseController < WktimeController - unloadable + menu_item :wktime before_action :find_optional_project, :only => [:reportdetail, :report] diff --git a/app/controllers/wkgltransaction_controller.rb b/app/controllers/wkgltransaction_controller.rb index c86b050e..404359cf 100644 --- a/app/controllers/wkgltransaction_controller.rb +++ b/app/controllers/wkgltransaction_controller.rb @@ -16,7 +16,7 @@ # Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. class WkgltransactionController < WkaccountingController - unloadable + include WkgltransactionHelper accept_api_auth :index, :edit, :update @@ -105,14 +105,14 @@ def index @summaryHash[key][:ledger_id] = entry.ledger_id end end - + dup_summary = sort_direction == "desc" ? @summaryHash.to_a.reverse.to_h : @summaryHash dup_summary.each do |key, value| getSummeryamount(key, value) @summaryHash[key][:CB] = @closeBal end @summaryHashFirstKey = dup_summary.keys.first - + else formPagination(transaction.reorder(sort_clause)) isSubCr = isSubtractCr(@selectedLedger.ledger_type) @@ -130,7 +130,7 @@ def index end transaction end - + def edit @transEntry = nil @transDetails = nil diff --git a/app/controllers/wkgrouppermission_controller.rb b/app/controllers/wkgrouppermission_controller.rb index d4d53730..08f81098 100644 --- a/app/controllers/wkgrouppermission_controller.rb +++ b/app/controllers/wkgrouppermission_controller.rb @@ -1,5 +1,5 @@ class WkgrouppermissionController < ApplicationController - unloadable + menu_item :wkcrmenumeration include WktimeHelper before_action :check_permission_tab_and_redirect, :only => [:index, :edit, :update] diff --git a/app/controllers/wkimportattendance_controller.rb b/app/controllers/wkimportattendance_controller.rb index bf362617..33a52aab 100644 --- a/app/controllers/wkimportattendance_controller.rb +++ b/app/controllers/wkimportattendance_controller.rb @@ -15,22 +15,22 @@ # along with this program; if not, write to the Free Software # Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. -class WkimportattendanceController < WkattendanceController -unloadable +class WkimportattendanceController < WkattendanceController + include WkimportattendanceHelper before_action :require_login before_action :check_ta_admin_and_redirect, :only => [:new] require 'csv' - + def new end - + def show file = params[:file] unless file.blank? - filePath = file.path + filePath = file.path begin isSuccess = importAttendance(filePath, false) rescue Exception => e @@ -42,12 +42,12 @@ def show redirect_to :action => 'new' end end - + def check_ta_admin_and_redirect unless validateERPPermission('A_TE_PRVLG') render_403 return false end end - + end diff --git a/app/controllers/wkinventory_controller.rb b/app/controllers/wkinventory_controller.rb index 98457b0b..d2faac63 100644 --- a/app/controllers/wkinventory_controller.rb +++ b/app/controllers/wkinventory_controller.rb @@ -1,5 +1,5 @@ class WkinventoryController < WkbaseController - unloadable + before_action :require_login diff --git a/app/controllers/wkinvoice_controller.rb b/app/controllers/wkinvoice_controller.rb index c90360e8..c5b2fe94 100644 --- a/app/controllers/wkinvoice_controller.rb +++ b/app/controllers/wkinvoice_controller.rb @@ -319,7 +319,7 @@ def getQuantityDetails spent = entry.spent items = {project_name: spent.project.name, issue: spent&.issue&.subject.to_s, user: spent.user&.name, date: spent.spent_on} if params[:itemType] == 'i' - items[:hour] = spent.try(:hours) + items[:hour] = format_hours(spent.try(:hours) || "") elsif params[:itemType] == 'e' items[:field_amount] = spent.try(:currency)+spent.try(:amount).to_s end @@ -339,7 +339,7 @@ def getUnbilledQtyDetails unbilledEntries.map do |entry| items = {project_name: entry.project.name, issue: entry.issue.to_s, user: entry.user.name, date: entry.spent_on} if params[:itemType] == 'i' - items[:hour] = entry.try(:hours) + items[:hour] = format_hours(entry.try(:hours) || "") elsif params[:itemType] == 'e' items[:amount] = entry.try(:currency)+entry.try(:amount).to_s end @@ -365,8 +365,7 @@ def generateTimeEntries lastArray = invIntervals.length - 1 todate = invIntervals[lastArray][1] timeEntries = WkInvoiceItem.getGenerateEntries(todate.to_date, fromDate.to_date, parent_id, parent_type, params[:projectID], TimeEntry, "time_entries") - - data1 = timeEntries.map{|e| {id: e.id, acc_name: (e&.name || e&.c_name), proj_name: e&.project&.name, subject: e.issue.to_s, usr_name: e&.user&.name, activity: e&.activity.to_s, spent_on: e.spent_on, hours: e.hours}} + data1 = timeEntries.map{|e| {id: e.id, acc_name: (e&.name || e&.c_name), proj_name: e&.project&.name, subject: e.issue.to_s, usr_name: e&.user&.name, activity: e&.activity.to_s, spent_on: e.spent_on, hours: format_hours(e.hours)}} listHeader1 = { acc_cont_name: l(:field_account), project_name: l(:label_project), issue: l(:label_invoice_name), user: l(:label_user), activity: l(:label_activity_type), date: l(:label_date), hour: l(:field_hours) } materialEntries = WkInvoiceItem.getGenerateEntries(todate.to_date, fromDate.to_date, parent_id, parent_type, params[:projectID], WkMaterialEntry, "wk_material_entries") diff --git a/app/controllers/wklead_controller.rb b/app/controllers/wklead_controller.rb index 3c272d8c..21f4e9c1 100644 --- a/app/controllers/wklead_controller.rb +++ b/app/controllers/wklead_controller.rb @@ -16,7 +16,7 @@ # Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. class WkleadController < WkcrmController - unloadable + include WktimeHelper include WkleadHelper include WkaccountprojectHelper diff --git a/app/controllers/wkledger_controller.rb b/app/controllers/wkledger_controller.rb index c3fdab9a..c1602c9e 100644 --- a/app/controllers/wkledger_controller.rb +++ b/app/controllers/wkledger_controller.rb @@ -16,7 +16,7 @@ # Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. class WkledgerController < WkaccountingController - unloadable + menu_item :wkgltransaction before_action :check_ac_admin_and_redirect, :only => [:update, :destroy] before_action :check_perm_and_redirect, :only => [:index, :edit] @@ -57,11 +57,11 @@ def index end end end - + def edit @ledgersDetail = WkLedger.where(:id => params[:ledger_id].to_i) end - + def update wkledger = nil errorMsg = nil @@ -72,7 +72,7 @@ def update end wkledger.name = params[:name] wkledger.ledger_type = params[:ledger_type] unless params[:ledger_type].blank? - wkledger.currency = Setting.plugin_redmine_wktime['wktime_currency'] + wkledger.currency = Setting.plugin_redmine_wktime['wktime_currency'] wkledger.opening_balance = params[:opening_balance].blank? ? 0 : params[:opening_balance] wkledger.owner = wkledger.ledger_type =='SY' ? 's' : 'u' unless wkledger.save() @@ -82,11 +82,11 @@ def update redirect_to :controller => 'wkledger',:action => 'index' , :tab => 'wkledger' flash[:notice] = l(:notice_successful_update) else - flash[:error] = errorMsg + flash[:error] = errorMsg redirect_to :controller => 'wkledger',:action => 'edit' end end - + def destroy ledger = WkLedger.find(params[:ledger_id].to_i) if ledger.ledger_type == 'SY' @@ -98,19 +98,19 @@ def destroy end redirect_back_or_default :action => 'index', :tab => params[:tab] end - + def set_filter_session filters = [:ledger_type, :name] super(filters) end - + def formPagination(entries) @entry_count = entries.count setLimitAndOffset() @ledgers = entries.order(:id).limit(@limit).offset(@offset) end - - def setLimitAndOffset + + def setLimitAndOffset if api_request? @offset, @limit = api_offset_and_limit if !params[:limit].blank? @@ -123,7 +123,7 @@ def setLimitAndOffset @entry_pages = Paginator.new @entry_count, per_page_option, params['page'] @limit = @entry_pages.per_page @offset = @entry_pages.offset - end + end end end diff --git a/app/controllers/wklocation_controller.rb b/app/controllers/wklocation_controller.rb index 5da88500..527e5dc3 100644 --- a/app/controllers/wklocation_controller.rb +++ b/app/controllers/wklocation_controller.rb @@ -16,7 +16,7 @@ # Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. class WklocationController < WkbaseController - unloadable + menu_item :wkcrmenumeration include WktimeHelper include WkdocumentHelper @@ -60,14 +60,14 @@ def index } end end - + def edit @locEntry = nil unless params[:location_id].blank? @locEntry = WkLocation.find(params[:location_id]) end end - + def update errorMsg = nil if params[:location_id].blank? || params[:location_id].to_i == 0 @@ -94,11 +94,11 @@ def update redirect_to :controller => controller_name,:action => 'index' , :tab => controller_name flash[:notice] = l(:notice_successful_update) else - flash[:error] = errorMsg + flash[:error] = errorMsg redirect_to :controller => controller_name,:action => 'edit', :location_id => locationObj.id end end - + def destroy location = WkLocation.find(params[:location_id].to_i) if location.destroy @@ -113,21 +113,21 @@ def set_filter_session filters = [:location_name, :location_type, :show_on_map] super(filters) end - + def check_perm_and_redirect unless User.current.admin? || hasSettingPerm render_403 return false end end - + def formPagination(entries) @entry_count = entries.count setLimitAndOffset() @locationObj = entries.limit(@limit).offset(@offset) end - - def setLimitAndOffset + + def setLimitAndOffset if api_request? @offset, @limit = api_offset_and_limit if !params[:limit].blank? @@ -140,7 +140,7 @@ def setLimitAndOffset @entry_pages = Paginator.new @entry_count, per_page_option, params['page'] @limit = @entry_pages.per_page @offset = @entry_pages.offset - end + end end def getlocations diff --git a/app/controllers/wklogmaterial_controller.rb b/app/controllers/wklogmaterial_controller.rb index e8d6967a..a20a8d72 100644 --- a/app/controllers/wklogmaterial_controller.rb +++ b/app/controllers/wklogmaterial_controller.rb @@ -1,5 +1,5 @@ class WklogmaterialController < TimelogController - unloadable + prepend_before_action :change_params_controller before_action :require_login accept_api_auth :loadSpentType, :index, :spent_log, :modifyProductDD, :create, :update diff --git a/app/controllers/wkopportunity_controller.rb b/app/controllers/wkopportunity_controller.rb index 5ad35420..861c2b34 100644 --- a/app/controllers/wkopportunity_controller.rb +++ b/app/controllers/wkopportunity_controller.rb @@ -1,5 +1,5 @@ class WkopportunityController < WkcrmController - unloadable + menu_item :wklead include WktimeHelper include WkopportunityHelper diff --git a/app/controllers/wkorderentity_controller.rb b/app/controllers/wkorderentity_controller.rb index da8caa1a..3fb2a308 100644 --- a/app/controllers/wkorderentity_controller.rb +++ b/app/controllers/wkorderentity_controller.rb @@ -16,7 +16,7 @@ # Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. class WkorderentityController < WkbillingController - unloadable + include WktimeHelper include WkinvoiceHelper include WkbillingHelper diff --git a/app/controllers/wkpayment_controller.rb b/app/controllers/wkpayment_controller.rb index 24f438ef..c68cd435 100644 --- a/app/controllers/wkpayment_controller.rb +++ b/app/controllers/wkpayment_controller.rb @@ -16,7 +16,7 @@ # Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. class WkpaymentController < WkpaymententityController - unloadable + menu_item :wkinvoice accept_api_auth :index, :edit, :update diff --git a/app/controllers/wkpaymententity_controller.rb b/app/controllers/wkpaymententity_controller.rb index e0a591cb..2e8e765d 100644 --- a/app/controllers/wkpaymententity_controller.rb +++ b/app/controllers/wkpaymententity_controller.rb @@ -16,7 +16,7 @@ # Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. class WkpaymententityController < WkbillingController - unloadable + include WkpaymentHelper include WkbillingHelper include WktimeHelper diff --git a/app/controllers/wkproduct_controller.rb b/app/controllers/wkproduct_controller.rb index 59143600..9e45691c 100644 --- a/app/controllers/wkproduct_controller.rb +++ b/app/controllers/wkproduct_controller.rb @@ -16,7 +16,7 @@ # Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. class WkproductController < WkinventoryController - unloadable + before_action :require_login before_action :check_perm_and_redirect, :only => [:index, :edit, :update, :destroy, :category, :updateCategory] @@ -56,22 +56,22 @@ def index } end end - + def formPagination(entries) @entry_count = entries.count setLimitAndOffset() @productEntries = entries.limit(@limit).offset(@offset) end - + def edit @productEntry = nil unless params[:product_id].blank? @productEntry = WkProduct.find(params[:product_id]) @applicableTaxes = @productEntry.taxes.map { |r| r.id } - end - end - - def update + end + end + + def update if params[:product_id].blank? product = WkProduct.new else @@ -87,10 +87,10 @@ def update product.ledger_id = params[:ledger_id] if product.save() unless product.id.blank? - taxId = params[:tax_id] + taxId = params[:tax_id] WkProductTax.where(:product_id => product.id).where.not(:tax_id => taxId).delete_all() unless taxId.blank? - taxId.collect{ |id| + taxId.collect{ |id| istaxid = WkProductTax.where("product_id = ? and tax_id = ? ", product.id, id).count unless istaxid > 0 productTax = WkProductTax.new @@ -99,7 +99,7 @@ def update if !productTax.save() errorMsg = productTax.errors.full_messages.join("
") end - end + end } end end @@ -110,7 +110,7 @@ def update flash[:error] = product.errors.full_messages.join("
") end end - + def destroy product = WkProduct.find(params[:product_id].to_i) if product.destroy @@ -122,7 +122,7 @@ def destroy end def category - entries = WkProductCategory.all + entries = WkProductCategory.all formPagination(entries) end @@ -137,23 +137,23 @@ def updateCategory end category.name = params[:name][i] category.description = params[:description][i] - category.save() + category.save() end - - if !arrId.blank? + + if !arrId.blank? WkProductCategory.where(:id => arrId).destroy_all end - + redirect_to :controller => 'wkproduct',:action => 'category' , :tab => 'wkproduct' flash[:notice] = l(:notice_successful_update) - end + end def set_filter_session filters = [:category_id, :name] super(filters) end - - def setLimitAndOffset + + def setLimitAndOffset if api_request? @offset, @limit = api_offset_and_limit if !params[:limit].blank? @@ -166,6 +166,6 @@ def setLimitAndOffset @entry_pages = Paginator.new @entry_count, per_page_option, params['page'] @limit = @entry_pages.per_page @offset = @entry_pages.offset - end + end end end \ No newline at end of file diff --git a/app/controllers/wkproductattribute_controller.rb b/app/controllers/wkproductattribute_controller.rb index 62ccfbf1..7f97b29d 100644 --- a/app/controllers/wkproductattribute_controller.rb +++ b/app/controllers/wkproductattribute_controller.rb @@ -1,5 +1,5 @@ class WkproductattributeController < WkinventoryController - unloadable + before_action :require_login def index diff --git a/app/controllers/wkproductcatagory_controller.rb b/app/controllers/wkproductcatagory_controller.rb index a16359ce..c4fd378c 100644 --- a/app/controllers/wkproductcatagory_controller.rb +++ b/app/controllers/wkproductcatagory_controller.rb @@ -1,5 +1,5 @@ class WkproductcatagoryController < WkinventoryController - unloadable + before_action :require_login diff --git a/app/controllers/wkproductitem_controller.rb b/app/controllers/wkproductitem_controller.rb index 247749dd..bc28e7cd 100644 --- a/app/controllers/wkproductitem_controller.rb +++ b/app/controllers/wkproductitem_controller.rb @@ -16,7 +16,7 @@ # Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. class WkproductitemController < WkinventoryController - unloadable + menu_item :wkproduct before_action :require_login before_action :check_perm_and_redirect, :only => [:index, :edit, :update, :destroy, :transfer, :updateTransfer] diff --git a/app/controllers/wkproductmodel_controller.rb b/app/controllers/wkproductmodel_controller.rb index f29c6d1c..e64e3e62 100644 --- a/app/controllers/wkproductmodel_controller.rb +++ b/app/controllers/wkproductmodel_controller.rb @@ -1,7 +1,7 @@ class WkproductmodelController < WkinventoryController - unloadable + before_action :require_login - + def index end diff --git a/app/controllers/wkpublicholiday_controller.rb b/app/controllers/wkpublicholiday_controller.rb index bb5bee43..94af90f8 100644 --- a/app/controllers/wkpublicholiday_controller.rb +++ b/app/controllers/wkpublicholiday_controller.rb @@ -15,7 +15,7 @@ # along with this program; if not, write to the Free Software # Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. class WkpublicholidayController < WkbaseController - unloadable + menu_item :wkattendance def index diff --git a/app/controllers/wkpurchaseorder_controller.rb b/app/controllers/wkpurchaseorder_controller.rb index db45ca01..bb94da3b 100644 --- a/app/controllers/wkpurchaseorder_controller.rb +++ b/app/controllers/wkpurchaseorder_controller.rb @@ -15,7 +15,7 @@ # along with this program; if not, write to the Free Software # Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. class WkpurchaseorderController < WksupplierorderentityController - unloadable + menu_item :wkrfq @@pomutex = Mutex.new diff --git a/app/controllers/wkquote_controller.rb b/app/controllers/wkquote_controller.rb index 6929280d..3fe3c6d2 100644 --- a/app/controllers/wkquote_controller.rb +++ b/app/controllers/wkquote_controller.rb @@ -16,18 +16,18 @@ # Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. class WkquoteController < WksupplierorderentityController - unloadable + menu_item :wkrfq - + @@quotemutex = Mutex.new - + def editOrderEntity super if params[:invoice_id].present? @rfgQuoteEntry = WkRfqQuote.find(@invoice.rfq_quote&.id) if @invoice&.rfq_quote.present? end end - + def newSupOrderEntity(parentId, parentType) msg = "" unless params[:rfq_id].blank? @@ -37,69 +37,69 @@ def newSupOrderEntity(parentId, parentType) redirect_to :action => 'new' end end - - # Synchronize the quote insert because maintain the sequence of invoice num key + + # Synchronize the quote insert because maintain the sequence of invoice num key def saveOrderInvoice(parentId, parentType, projectId, invDate, invoicePeriod, isgenerate, getInvoiceType) - begin - @@quotemutex.synchronize do - addInvoice(parentId, parentType, projectId, invDate, invoicePeriod, isgenerate, getInvoiceType) - end + begin + @@quotemutex.synchronize do + addInvoice(parentId, parentType, projectId, invDate, invoicePeriod, isgenerate, getInvoiceType) + end rescue => ex logger.error ex.message end - end - + end + def saveOrderRelations isWon = params[:quote_won].blank? ? nil : params[:quote_won] winNote = params[:winning_note].blank? ? "" : params[:winning_note] saveRfqQuotes(params[:rfq_quote_id], params[:rfq_id].to_i, @invoice.id, isWon, winNote) end - + def getInvoiceType 'Q' end - + def getLabelInvNum l(:label_quote_number) end - + def getLabelNewInv l(:label_new_quote) end - + def getHeaderLabel l(:label_quotes) end - + def getItemLabel l(:label_quote_items) end - + def getDateLbl l(:label_quote_date) end - + def addQuoteFields true end - + def getAdditionalDD "wkquote/quoteadditionaldd" end - + def editInvNumber true end - + def getOrderNumberPrefix 'wktime_quote_no_prefix' end - + def getNewHeaderLbl l(:label_new_quote) end - + def getOrderContract(invoice) contractStr = nil rfq = invoice.rfq_quote.rfq @@ -108,7 +108,7 @@ def getOrderContract(invoice) end contractStr end - + def getOrderComponetsId 'wktime_quote_components' end diff --git a/app/controllers/wkreferrals_controller.rb b/app/controllers/wkreferrals_controller.rb index 9b84c1bd..3f1cb1ca 100644 --- a/app/controllers/wkreferrals_controller.rb +++ b/app/controllers/wkreferrals_controller.rb @@ -16,7 +16,7 @@ # Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. class WkreferralsController < WkleadController - unloadable + before_action :require_login, :check_module_permission before_action :check_perm_and_redirect, only: [:update, :destroy] before_action :check_permission, only: :getEmpDetails diff --git a/app/controllers/wkreport_controller.rb b/app/controllers/wkreport_controller.rb index ad80b105..d382bdc5 100644 --- a/app/controllers/wkreport_controller.rb +++ b/app/controllers/wkreport_controller.rb @@ -16,7 +16,7 @@ # Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. class WkreportController < WkbaseController -unloadable + include WktimeHelper include WkreportHelper diff --git a/app/controllers/wkrfq_controller.rb b/app/controllers/wkrfq_controller.rb index b709f954..9d90391b 100644 --- a/app/controllers/wkrfq_controller.rb +++ b/app/controllers/wkrfq_controller.rb @@ -1,5 +1,5 @@ class WkrfqController < WkbaseController - unloadable + include WktimeHelper include WkorderentityHelper include WkrfqHelper @@ -43,7 +43,7 @@ def index } end end - + def formPagination(entries, sectiontype) @entry_count = entries.count setLimitAndOffset() @@ -53,16 +53,16 @@ def formPagination(entries, sectiontype) @invoiceEntries = entries.order(:id).limit(@limit).offset(@offset) end end - + def edit @rfqEntry = nil unless params[:rfq_id].blank? @rfqEntry = WkRfq.find(params[:rfq_id]) quoteList() end - end - - def update + end + + def update if params[:rfq_id].blank? rfq = WkRfq.new else @@ -81,7 +81,7 @@ def update flash[:error] = rfq.errors.full_messages.join("
") end end - + def destroy #WkRfq.find(params[:rfq_id].to_i).destroy #flash[:notice] = l(:notice_successful_delete) @@ -92,9 +92,9 @@ def destroy flash[:error] = rfq.errors.full_messages.join("
") end redirect_back_or_default :action => 'index', :tab => params[:tab] - end - - def setLimitAndOffset + end + + def setLimitAndOffset if api_request? @offset, @limit = api_offset_and_limit if !params[:limit].blank? @@ -107,49 +107,49 @@ def setLimitAndOffset @entry_pages = Paginator.new @entry_count, per_page_option, params['page'] @limit = @entry_pages.per_page @offset = @entry_pages.offset - end + end end - + def deletePermission validateERPPermission("A_PUR_PRVLG") end - + def check_perm_and_redirect unless check_permission render_403 return false end end - - def check_permission - return validateERPPermission("B_PUR_PRVLG") || validateERPPermission("A_PUR_PRVLG") + + def check_permission + return validateERPPermission("B_PUR_PRVLG") || validateERPPermission("A_PUR_PRVLG") end - + def check_pur_admin_and_redirect - unless validateERPPermission("A_PUR_PRVLG") + unless validateERPPermission("A_PUR_PRVLG") render_403 return false end end - + def quoteList rfqId = params[:rfq_id] invIds = getInvoiceIds(rfqId, 'Q', false) invEntries = WkInvoice.includes(:invoice_items).where( :id => invIds) formPagination(invEntries, "quote") end - + def getLabelInvNum l(:label_quote_number) end - + def getDateLbl l(:label_quote_date) end - + def isInvPaymentLink false - end + end def set_filter_session filters = [:rfq_name, :rfq_date] diff --git a/app/controllers/wkscheduling_controller.rb b/app/controllers/wkscheduling_controller.rb index df3bd674..763cd37d 100644 --- a/app/controllers/wkscheduling_controller.rb +++ b/app/controllers/wkscheduling_controller.rb @@ -15,7 +15,7 @@ # along with this program; if not, write to the Free Software # Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. class WkschedulingController < WkbaseController - unloadable + menu_item :wkattendance before_action :require_login rescue_from Query::StatementInvalid, :with => :query_statement_invalid diff --git a/app/controllers/wkshift_controller.rb b/app/controllers/wkshift_controller.rb index d2922b6d..be2aaf43 100644 --- a/app/controllers/wkshift_controller.rb +++ b/app/controllers/wkshift_controller.rb @@ -15,7 +15,7 @@ # along with this program; if not, write to the Free Software # Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. class WkshiftController < WkbaseController - unloadable + menu_item :wkattendance before_action :require_login diff --git a/app/controllers/wkshipment_controller.rb b/app/controllers/wkshipment_controller.rb index 0b6ea9d4..82188261 100644 --- a/app/controllers/wkshipment_controller.rb +++ b/app/controllers/wkshipment_controller.rb @@ -16,7 +16,7 @@ # Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. class WkshipmentController < WkinventoryController - unloadable + menu_item :wkproduct before_action :require_login diff --git a/app/controllers/wksupplieraccount_controller.rb b/app/controllers/wksupplieraccount_controller.rb index f5e20fbb..2b338162 100644 --- a/app/controllers/wksupplieraccount_controller.rb +++ b/app/controllers/wksupplieraccount_controller.rb @@ -1,36 +1,36 @@ class WksupplieraccountController < WkaccountController - unloadable + menu_item :wkrfq include WktimeHelper - + def getAccountType 'S' end - + def getContactType 'C' end - + def getContactController 'wksuppliercontact' end - - def check_permission - return validateERPPermission("B_PUR_PRVLG") || validateERPPermission("A_PUR_PRVLG") + + def check_permission + return validateERPPermission("B_PUR_PRVLG") || validateERPPermission("A_PUR_PRVLG") end - + def check_crm_admin_and_redirect - unless validateERPPermission("A_PUR_PRVLG") + unless validateERPPermission("A_PUR_PRVLG") render_403 return false end end - + def deletePermission validateERPPermission("A_PUR_PRVLG") end - + def getAccountLbl l(:label_supplier_account) end diff --git a/app/controllers/wksuppliercontact_controller.rb b/app/controllers/wksuppliercontact_controller.rb index 0d7cbe68..ba428b93 100644 --- a/app/controllers/wksuppliercontact_controller.rb +++ b/app/controllers/wksuppliercontact_controller.rb @@ -1,44 +1,44 @@ class WksuppliercontactController < WkcontactController - unloadable + menu_item :wkrfq include WktimeHelper - + def getContactType 'SC' end - + def getContactController 'wksuppliercontact' end - + def getAccountType 'S' end - - def check_permission - return validateERPPermission("B_PUR_PRVLG") || validateERPPermission("A_PUR_PRVLG") + + def check_permission + return validateERPPermission("B_PUR_PRVLG") || validateERPPermission("A_PUR_PRVLG") end - + def check_crm_admin_and_redirect - unless validateERPPermission("A_PUR_PRVLG") + unless validateERPPermission("A_PUR_PRVLG") render_403 return false end end - + def deletePermission validateERPPermission("A_PUR_PRVLG") end - + def getAccountLbl l(:label_supplier_account) end - + def lblNewContact l(:label_new_item, l(:label_supplier_contact)) end - + def contactLbl l(:label_supplier_contact) end diff --git a/app/controllers/wksupplierinvoice_controller.rb b/app/controllers/wksupplierinvoice_controller.rb index 7fe1bc86..b151f962 100644 --- a/app/controllers/wksupplierinvoice_controller.rb +++ b/app/controllers/wksupplierinvoice_controller.rb @@ -1,5 +1,5 @@ class WksupplierinvoiceController < WksupplierorderentityController - unloadable + menu_item :wkrfq @@simutex = Mutex.new diff --git a/app/controllers/wksupplierorderentity_controller.rb b/app/controllers/wksupplierorderentity_controller.rb index 84c8ea83..ea9c3e54 100644 --- a/app/controllers/wksupplierorderentity_controller.rb +++ b/app/controllers/wksupplierorderentity_controller.rb @@ -16,7 +16,7 @@ # Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. class WksupplierorderentityController < WkorderentityController - unloadable + def newOrderEntity(parentId, parentType) newSupOrderEntity(parentId, parentType) diff --git a/app/controllers/wksupplierpayment_controller.rb b/app/controllers/wksupplierpayment_controller.rb index b961de99..de00afdb 100644 --- a/app/controllers/wksupplierpayment_controller.rb +++ b/app/controllers/wksupplierpayment_controller.rb @@ -15,7 +15,7 @@ # along with this program; if not, write to the Free Software # Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. class WksupplierpaymentController < WkpaymententityController - unloadable + menu_item :wkrfq def getOrderAccountType diff --git a/app/controllers/wksurvey_controller.rb b/app/controllers/wksurvey_controller.rb index 9796b444..697f3832 100644 --- a/app/controllers/wksurvey_controller.rb +++ b/app/controllers/wksurvey_controller.rb @@ -17,7 +17,7 @@ class WksurveyController < WkbaseController - unloadable + before_action :require_login, :survey_url_validation, :check_perm_and_redirect before_action :check_permission , only: "survey_response" accept_api_auth :index, :save_survey, :find_survey_for, :survey, :update_survey, :survey_result, :survey_response diff --git a/app/controllers/wktime_controller.rb b/app/controllers/wktime_controller.rb index e6e2ca3c..8f1ecc24 100644 --- a/app/controllers/wktime_controller.rb +++ b/app/controllers/wktime_controller.rb @@ -16,7 +16,7 @@ # Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. class WktimeController < WkbaseController -unloadable + include WktimeHelper include WkcrmHelper diff --git a/app/controllers/wkunitofmeasurement_controller.rb b/app/controllers/wkunitofmeasurement_controller.rb index 7b2c58ec..4e4a61bc 100644 --- a/app/controllers/wkunitofmeasurement_controller.rb +++ b/app/controllers/wkunitofmeasurement_controller.rb @@ -1,19 +1,19 @@ class WkunitofmeasurementController < WkinventoryController - unloadable + before_action :require_login menu_item :wkproduct - + def index - entries = WkMesureUnit.all + entries = WkMesureUnit.all formPagination(entries) end def update - count = 0 + count = 0 errorMsg = "" arrId = Array.new unless params[:actual_ids].blank? - arrId = params[:actual_ids].split(",").map { |s| s.to_i } + arrId = params[:actual_ids].split(",").map { |s| s.to_i } end for i in 0..params[:uom_id].length-1 if params[:uom_id][i].blank? @@ -24,33 +24,33 @@ def update end curExchanges.name = params[:name][i] curExchanges.short_desc = params[:description][i] - curExchanges.save() + curExchanges.save() end - - if !arrId.blank? + + if !arrId.blank? arrId.each do |id| des = WkMesureUnit.find(id) if des.destroy - count = count + 1 + count = count + 1 else errorMsg = errorMsg + des.errors.full_messages.join("
") end end - + end - + redirect_to :controller => 'wkunitofmeasurement',:action => 'index' , :tab => 'wkunitofmeasurement' flash[:notice] = l(:notice_successful_update) flash[:error] = errorMsg unless errorMsg.blank? end - + def formPagination(entries) @entry_count = entries.count setLimitAndOffset() @curentry = entries.limit(@limit).offset(@offset) end - - def setLimitAndOffset + + def setLimitAndOffset if api_request? @offset, @limit = api_offset_and_limit if !params[:limit].blank? @@ -63,7 +63,7 @@ def setLimitAndOffset @entry_pages = Paginator.new @entry_count, per_page_option, params['page'] @limit = @entry_pages.per_page @offset = @entry_pages.offset - end + end end end diff --git a/app/helpers/wknotification_helper.rb b/app/helpers/wknotification_helper.rb index 0759ee71..a4c2f8b1 100644 --- a/app/helpers/wknotification_helper.rb +++ b/app/helpers/wknotification_helper.rb @@ -23,16 +23,16 @@ def formNotificationText(notification) notifyHash = {} case WkUserNotification.getnotificationAction(notification)&.first&.name when "fillSurvey" - notification.source.survey_for_id ||= User.current.id if notification.source.survey_for_type == 'User' - notifyHash['text'] = l(:label_complete_survey)+" "+notification.source.name.to_s - notifyHash['url'] = {controller:'wksurvey', action:'survey', surveyForID: notification.source.survey_for_id, surveyForType: notification.source.survey_for_type, survey_id: notification.source_id, id: notification.source_id} if notification.source.survey_for_type.blank? || notification.source.survey_for_type.present? && notification.source.survey_for_id.present? + notification.source.survey_for_id ||= User.current.id if notification.source.present? && notification&.source&.survey_for_type == 'User' + notifyHash['text'] = l(:label_complete_survey)+" "+notification&.source&.name.to_s + notifyHash['url'] = {controller:'wksurvey', action:'survey', surveyForID: notification&.source&.survey_for_id, surveyForType: notification&.source&.survey_for_type, survey_id: notification.source_id, id: notification.source_id} if notification&.source&.survey_for_type.blank? || notification&.source&.survey_for_type.present? && notification&.source&.survey_for_id.present? notifyHash['icon'] = "fa fa-file-text-o" when "leaveRequested" - notifyHash['text'] = l(:label_approve_leave)+" "+notification.source.user.name.to_s+" "+l(:label_on)+" "+notification.source.start_date.to_date.to_s + notifyHash['text'] = l(:label_approve_leave)+" "+notification&.source&.user.name.to_s+" "+l(:label_on)+" "+notification&.source&.start_date.to_date.to_s notifyHash['url'] = {controller:'wkleaverequest', action:'edit', id: notification.source_id} notifyHash['icon'] = "fa fa-user-circle" when "leaveApproved" - notifyHash['text'] = notification.source&.status == 'A' ? l(:label_your_leave)+" "+notification.source.start_date.to_date.to_s+" "+l(:label_is_approved) : l(:label_your_leave)+" "+notification.source.start_date.to_date.to_s+" "+l(:label_rejected) + notifyHash['text'] = notification.source&.status == 'A' ? l(:label_your_leave)+" "+notification&.source&.start_date.to_date.to_s+" "+l(:label_is_approved) : l(:label_your_leave)+" "+notification&.source&.start_date.to_date.to_s+" "+l(:label_rejected) notifyHash['url'] = {controller:'wkleaverequest', action:'edit', id: notification.source_id} notifyHash['icon'] = "fa fa-user-circle" when 'invoiceGenerated' @@ -44,42 +44,42 @@ def formNotificationText(notification) notifyHash['url'] = {controller:'wkpayment', action:'edit', payment_id: notification.source_id, id: notification.source_id} notifyHash['icon'] = "fa fa-usd" when 'contractSigned' - notifyHash['text'] = l(:label_contract)+" "+notification.source_id.to_s+" "+ l(:label_for)+" "+notification.source.parent.name.to_s+ " " +l(:label_has_created) + notifyHash['text'] = l(:label_contract)+" "+notification.source_id.to_s+" "+ l(:label_for)+" "+notification&.source&.parent.name.to_s+ " " +l(:label_has_created) notifyHash['url'] = {controller:'wkcontract', action:'edit', contract_id: notification.source_id, id: notification.source_id} notifyHash['icon'] = "fa fa-file-text-o" when "nonSubmission" - notifyHash['text'] = l(:button_submit)+" "+ l(:label_timesheet_on)+" "+notification.source.begin_date.to_s - notifyHash['url'] = {controller:'wktime', action:'edit', startday: notification.source.begin_date, user_id: notification.source.user_id} + notifyHash['text'] = l(:button_submit)+" "+ l(:label_timesheet_on)+" "+notification&.source&.begin_date.to_s + notifyHash['url'] = {controller:'wktime', action:'edit', startday: notification&.source&.begin_date, user_id: notification&.source&.user_id} notifyHash['icon'] = "fa fa-clock-o" when 'timeApproved' - notifyHash['text'] = l(:button_wk_approve)+" "+l(:label_timesheet_on)+" "+notification.source.begin_date.to_s+" "+l(:label_for)+" "+notification.source.user.name.to_s - notifyHash['url'] = {controller:'wktime', action:'edit', startday: notification.source.begin_date, user_id: notification.source.user_id} + notifyHash['text'] = l(:button_wk_approve)+" "+l(:label_timesheet_on)+" "+notification&.source&.begin_date.to_s+" "+l(:label_for)+" "+notification&.source&.user.name.to_s + notifyHash['url'] = {controller:'wktime', action:'edit', startday: notification&.source&.begin_date, user_id: notification&.source&.user_id} notifyHash['icon'] = "fa fa-clock-o" when 'timeRejected' - notifyHash['text'] = l(:label_timesheet_rejected)+" "+l(:label_on)+" "+notification.source.submitted_on.to_s - notifyHash['url'] = {controller:'wktime', action:'edit', startday: notification.source.begin_date, user_id: notification.source.user_id} + notifyHash['text'] = l(:label_timesheet_rejected)+" "+l(:label_on)+" "+notification&.source&.submitted_on.to_s + notifyHash['url'] = {controller:'wktime', action:'edit', startday: notification&.source&.begin_date, user_id: notification&.source&.user_id} notifyHash['icon'] = "fa fa-clock-o" when 'surveyClosed' - notifyHash['text'] = l(:label_survey)+" "+notification.source.name.to_s+" "+l(:label_has_closed) + notifyHash['text'] = l(:label_survey)+" "+notification&.source&.name.to_s+" "+l(:label_has_closed) notifyHash['url'] = {controller:'wksurvey', action:'survey', survey_id: notification.source_id, id: notification.source_id} notifyHash['icon'] = "fa fa-file-text-o" when 'leadGenerated' leadNotifyLabel(notification) - notifyHash['text'] = @label+" "+notification.source.name.to_s+" "+l(:label_has_created) + notifyHash['text'] = @label+" "+notification&.source&.name.to_s+" "+l(:label_has_created) notifyHash['url'] = {controller: @controller, action:'edit',lead_id: notification.source_id, id: notification.source_id} notifyHash['icon'] = "fa fa-user-circle" when 'leadConverted' leadNotifyLabel(notification) - notifyHash['text'] = @label+" "+notification.source.name.to_s+" "+ @text + notifyHash['text'] = @label+" "+notification&.source&.name.to_s+" "+ @text notifyHash['url'] = {controller: @controller, action:'edit',lead_id: notification.source_id, id: notification.source_id} notifyHash['icon'] = "fa fa-user-circle" when 'opportunityStatusChanged' status_name = getSaleStageHash[get_sales_stage(notification.source)].present? ? getSaleStageHash[get_sales_stage(notification.source)] : "" - notifyHash['text'] = l(:label_opportunity)+" "+notification.source.name.to_s+" "+l(:label_has_changed)+" "+status_name + notifyHash['text'] = l(:label_opportunity)+" "+notification&.source&.name.to_s+" "+l(:label_has_changed)+" "+status_name notifyHash['url'] = {controller:'wkopportunity', action:'edit',opp_id: notification.source_id, id: notification.source_id} notifyHash['icon'] = "fa fa-file-text-o" when 'salesActivityCompleted' - notifyHash['text'] = l(:report_sales_activity)+" "+notification.source.name.to_s+" "+l(:label_has_completed) + notifyHash['text'] = l(:report_sales_activity)+" "+notification&.source&.name.to_s+" "+l(:label_has_completed) notifyHash['url'] = {controller:'wkcrmactivity', action:'edit',activity_id: notification.source_id, id: notification.source_id} notifyHash['icon'] = "fa fa-file-text-o" when 'receiveGoods' @@ -87,27 +87,27 @@ def formNotificationText(notification) notifyHash['url'] = {controller:'wkshipment', action:'edit',shipment_id: notification.source_id, id: notification.source_id} notifyHash['icon'] = "fa fa-file-text-o" when 'disposeAsset' - notifyHash['text'] = l(:label_asset)+" "+notification.source.name.to_s+" "+l(:label_has_disposed) - notifyHash['url'] = {controller:'wkasset', action:'edit',inventory_item_id: notification.source.inventory_item_id, id: notification.source.inventory_item_id} + notifyHash['text'] = l(:label_asset)+" "+notification&.source&.name.to_s+" "+l(:label_has_disposed) + notifyHash['url'] = {controller:'wkasset', action:'edit',inventory_item_id: notification&.source&.inventory_item_id, id: notification&.source&.inventory_item_id} notifyHash['icon'] = "fa fa-file-text-o" when 'rfqCreated' - notifyHash['text'] = l(:label_rfq)+" "+notification.source.name.to_s+" "+l(:label_has_created) + notifyHash['text'] = l(:label_rfq)+" "+notification&.source&.name.to_s+" "+l(:label_has_created) notifyHash['url'] = {controller:'wkrfq', action:'edit',rfq_id: notification.source_id, id: notification.source_id} notifyHash['icon'] = "fa fa-file-text-o" when 'quoteReceived' notifyHash['text'] = l(:label_rfq)+" "+l(:label_quote)+" #"+notification.source&.quote&.invoice_number.to_s+" "+l(:label_has_received) - notifyHash['url'] = {controller:'wkquote', action:'edit',invoice_id: notification.source.quote_id, new_invoice: false, preview_billing:false, id: notification.source.quote_id} + notifyHash['url'] = {controller:'wkquote', action:'edit',invoice_id: notification&.source&.quote_id, new_invoice: false, preview_billing:false, id: notification&.source&.quote_id} notifyHash['icon'] = "fa fa-file-text-o" when 'purchaseOrderGenerated' notifyHash['text'] = l(:label_purchase_order)+" #"+notification.source&.purchase_order&.invoice_number.to_s+" "+l(:label_has_created) - notifyHash['url'] = {controller:'wkpurchaseorder', action:'edit',invoice_id: notification.source.purchase_order_id, new_invoice: false, preview_billing:false, id: notification.source.purchase_order_id} + notifyHash['url'] = {controller:'wkpurchaseorder', action:'edit',invoice_id: notification&.source&.purchase_order_id, new_invoice: false, preview_billing:false, id: notification&.source&.purchase_order_id} notifyHash['icon'] = "fa fa-file-text-o" when 'supplierInvoiceReceived' notifyHash['text'] = l(:label_supplier_invoice)+" "+notification.source&.invoice_items.first.original_currency.to_s+notification.source&.invoice_items.sum(:original_amount).to_s+" "+ l(:label_has_generated)+" "+ l(:label_for)+" "+notification.source&.parent&.name.to_s notifyHash['url'] = {controller:'wksupplierinvoice', action:'edit', invoice_id: notification.source_id, new_invoice: false, preview_billing: false, tab: 'wksupplierinvoice', id: notification.source_id} notifyHash['icon'] = "fa fa-usd" when 'supplierPaymentSent' - notifyHash['text'] = l(:label_received_sup_payment)+" "+notification.source.payment_items.first.original_currency.to_s+WkPayment.getPaymentItems(notification.source).to_s+" "+l(:label_from)+" "+notification.source.parent.name.to_s + notifyHash['text'] = l(:label_received_sup_payment)+" "+notification&.source&.payment_items.first.original_currency.to_s+WkPayment.getPaymentItems(notification.source).to_s+" "+l(:label_from)+" "+notification&.source&.parent.name.to_s notifyHash['url'] = {controller:'wksupplierpayment', action:'edit', payment_id: notification.source_id, id: notification.source_id} notifyHash['icon'] = "fa fa-usd" end diff --git a/app/helpers/wkscheduling_helper.rb b/app/helpers/wkscheduling_helper.rb index 705fb9b0..8db28aec 100644 --- a/app/helpers/wkscheduling_helper.rb +++ b/app/helpers/wkscheduling_helper.rb @@ -18,7 +18,7 @@ module WkschedulingHelper include WktimeHelper include WkattendanceHelper include WkcrmenumerationHelper - + def link_to_wkcalendar_display_day(calendarObject, options={}) s = "" scheduleType = "P" @@ -26,58 +26,58 @@ def link_to_wkcalendar_display_day(calendarObject, options={}) totalCount = 0 seeMore = false dayValue = calendarObject["#{options[:day]}"] - unless dayValue.blank? + unless dayValue.blank? totalCount = dayValue.length dayValue.each do | v | - sval = v.split("-") - content = sval[0].capitalize + sval = v.split("-") + content = sval[0].capitalize schedules = sval[2].strip if schedules == 'W' content << link_to(h(sval[1]), url_for(:controller => controller_name, :action => 'edit', :date => options[:day], :schedule_type=> sval[3].strip, :only_path => true), :class => 'icon icon-test', :style => "color:green;") else content << "

" + link_to(h(l(:label_day_off)), url_for(:controller => controller_name, :action => 'edit', :date => options[:day], :schedule_type=> sval[3].strip, :only_path => true), :style => "color:red;") +"

" end - + scheduleType = sval[3].strip - # content << " : " + content_tag(:span, (schedules == 'W' ? "Work" : "Off"), :style => "color:#{(schedules == 'W' ? "purple" : "red")};") - - s = s + content + "
".html_safe - if count >= 3 + # content << " : " + content_tag(:span, (schedules == 'W' ? "Work" : "Off"), :style => "color:#{(schedules == 'W' ? "purple" : "red")};") + + s = s + content + "
".html_safe + if count >= 3 seeMore = true break - end + end count = count + 1 end - end + end sm ="" if seeMore sm = "

..+#{totalCount} see more

" end if !s.blank? if scheduleType == 'S' - s = "
" + s + "
" .html_safe + s = "
" + s + "
" .html_safe elsif isChecked('wk_user_schedule_preference') - s = "
" + s + "
".html_safe + s = "
" + s + "
".html_safe end - s = "
" + s + sm + " #{render_calendar_tooltip calendarObject, :day => options[:day], :limit => nil}
".html_safe + s = "
" + s + sm + " #{render_calendar_tooltip calendarObject, :day => options[:day], :limit => nil}
".html_safe elsif options[:day].future? && isChecked('wk_user_schedule_preference') - s = "
" + link_to(h("Add Preference"), url_for(:controller => controller_name, :action => 'edit', :date => options[:day], :only_path => true), :class => 'icon icon-add') + "
".html_safe + s = "
" + link_to(sprite_icon('add', ("Add Preference")), url_for(:controller => controller_name, :action => 'edit', :date => options[:day], :only_path => true), :class => 'icon icon-add') + "
".html_safe end - + s.html_safe end - + def render_calendar_tooltip(calendarObject, options={}) content = "

#{options[:day]}

" scheduleType = "P" dayValue = calendarObject["#{options[:day]}"] - unless dayValue.blank? + unless dayValue.blank? #ss = dayValue.first(@limit*@entry_pages.page).last(@limit) dayValue.each do | v | content << "".html_safe - sval = v.split("-") - content << "".html_safe - + sval = v.split("-") + content << "".html_safe + scheduleType = sval[3].strip schedules = sval[2].strip if schedules == 'W' @@ -85,14 +85,14 @@ def render_calendar_tooltip(calendarObject, options={}) else content << "".html_safe end - content << "".html_safe - # content << "".html_safe + content << "".html_safe + # content << "".html_safe end end content << "
NameShift Name
" + sval[0].capitalize + "" + sval[0].capitalize + "" + "

" + link_to(h(l(:label_day_off)), url_for(:controller => controller_name, :action => 'edit', :date => options[:day], :schedule_type=> sval[3].strip, :only_path => true), :style => "color:red;") + "

" + content_tag(:span, (schedules == 'W' ? "Work" : "Off"), :style => "color:#{(schedules == 'W' ? "purple" : "red")};")+ "
" + content_tag(:span, (schedules == 'W' ? "Work" : "Off"), :style => "color:#{(schedules == 'W' ? "purple" : "red")};")+ "
".html_safe content.html_safe end - + def autoShiftScheduling begin @year ||= User.current.today.year @@ -107,11 +107,11 @@ def autoShiftScheduling Rails.logger.info "Job failed: #{e.message}" end end - + def getLocationDeptSql sqlStr = "select d.id as department_id, l.id as location_id from wk_locations l" + - " inner join wk_crm_enumerations d on (d.enum_type = 'DP')" - sqlStr + " inner join wk_crm_enumerations d on (d.enum_type = 'DP')" + sqlStr end - + end diff --git a/app/helpers/wktime_helper.rb b/app/helpers/wktime_helper.rb index 2aea2db6..f4119064 100644 --- a/app/helpers/wktime_helper.rb +++ b/app/helpers/wktime_helper.rb @@ -430,7 +430,7 @@ def getColumnValues(matrix, totals, unitLabel,rowNumberRequired, j=0, includeCom issueWritten = true j += 1 end - col_values[hoursIndex+i] = (entry.hours.blank? ? "" : ("%.2f" % entry.hours.to_s)) + col_values[hoursIndex+i] = (entry.hours.blank? ? "" : format_hours(entry.hours)) totals[i] += entry.hours unless entry.hours.blank? end end diff --git a/app/lib/application_helper_patch.rb b/app/lib/application_helper_patch.rb deleted file mode 100644 index 9313d055..00000000 --- a/app/lib/application_helper_patch.rb +++ /dev/null @@ -1,70 +0,0 @@ -module ApplicationHelper - def format_object(object, html=true, &block) - if block - object = yield object - end - case object - when Array - formatted_objects = object.map {|o| format_object(o, html)} - html ? safe_join(formatted_objects, ', ') : formatted_objects.join(', ') - when Time - format_time(object) - when Date - format_date(object) - when Integer - object.to_s - when Float - sprintf "%.2f", object - when User, Group - html ? link_to_principal(object) : object.to_s - when Project - html ? link_to_project(object) : object.to_s - when Version - html ? link_to_version(object) : object.to_s - when TrueClass - l(:general_text_Yes) - when FalseClass - l(:general_text_No) - when Issue - object.visible? && html ? link_to_issue(object) : "##{object.id}" - when Attachment - if html - content_tag( - :span, - link_to_attachment(object) + - link_to_attachment( - object, - :class => ['icon-only', 'icon-download'], - :title => l(:button_download), - :download => true - ) - ) - else - object.filename - end - # ============= ERPmine_patch Redmine 5.1 ===================== - when WkInventoryItem - brandName = object.product_item.brand.blank? ? "" : object.product_item.brand.name - modelName = object.product_item.product_model.blank? ? "" : object.product_item.product_model.name - str = "#{object.product_item.product.name} - #{brandName} - #{modelName}" - assetObj = object.asset_property - str = str + ' - ' +assetObj.name if object&.product_type != 'I' - str - # ============================= - when CustomValue, CustomFieldValue - return "" unless object.customized&.visible? - if object.custom_field - f = object.custom_field.format.formatted_custom_value(self, object, html) - if f.nil? || f.is_a?(String) - f - else - format_object(f, html, &block) - end - else - object.value.to_s - end - else - html ? h(object) : object.to_s - end - end -end \ No newline at end of file diff --git a/app/lib/ftte/nested_set/user_nested_set.rb b/app/lib/ftte/nested_set/user_nested_set.rb deleted file mode 100644 index 7f671147..00000000 --- a/app/lib/ftte/nested_set/user_nested_set.rb +++ /dev/null @@ -1,148 +0,0 @@ -module Ftte - module NestedSet - module UserNestedSet - def self.included(base) - base.class_eval do - - before_create :add_to_nested_set - before_update :move_in_nested_set, :if => lambda {|user| user.parent_id_changed? || user.lastname_changed?} - before_destroy :update_children #destroy_children - end - base.extend ClassMethods - base.send :include, Redmine::NestedSet::Traversing - end - - private - - def update_children - self.class.where(:parent_id => id).update_all(:parent_id => nil) - User.rebuild_tree! - end - - def target_lft - siblings_rgt = self.class.where(:parent_id => parent_id).where("lastname < ?", lastname).maximum(:rgt) - if siblings_rgt - siblings_rgt + 1 - elsif parent_id - parent_lft = self.class.where(:id => parent_id).pluck(:lft).first - raise "user id=#{id} with parent_id=#{parent_id}: parent missing or without 'lft' value" unless parent_lft - parent_lft + 1 - else - 1 - end - end - - def add_to_nested_set(lock=true) - lock_nested_set if lock - self.lft = target_lft - self.rgt = lft + 1 - self.class.where("lft >= ? OR rgt >= ?", lft, lft).update_all([ - "lft = CASE WHEN lft >= :lft THEN lft + 2 ELSE lft END, " + - "rgt = CASE WHEN rgt >= :lft THEN rgt + 2 ELSE rgt END", - {:lft => lft} - ]) - end - - def move_in_nested_set - lock_nested_set - reload_nested_set_values - a = lft - b = rgt - c = target_lft - unless c == a - if c > a - # Moving to the right - d = c - (b - a + 1) - scope = self.class.where(["lft BETWEEN :a AND :c - 1 OR rgt BETWEEN :a AND :c - 1", {:a => a, :c => c}]) - scope.update_all([ - "lft = CASE WHEN lft BETWEEN :a AND :b THEN lft + (:d - :a) WHEN lft BETWEEN :b + 1 AND :c - 1 THEN lft - (:b - :a + 1) ELSE lft END, " + - "rgt = CASE WHEN rgt BETWEEN :a AND :b THEN rgt + (:d - :a) WHEN rgt BETWEEN :b + 1 AND :c - 1 THEN rgt - (:b - :a + 1) ELSE rgt END", - {:a => a, :b => b, :c => c, :d => d} - ]) - - elsif c < a - # Moving to the left - scope = self.class.where("lft BETWEEN :c AND :b OR rgt BETWEEN :c AND :b", {:a => a, :b => b, :c => c}) - scope.update_all([ - "lft = CASE WHEN lft BETWEEN :a AND :b THEN lft - (:a - :c) WHEN lft BETWEEN :c AND :a - 1 THEN lft + (:b - :a + 1) ELSE lft END, " + - "rgt = CASE WHEN rgt BETWEEN :a AND :b THEN rgt - (:a - :c) WHEN rgt BETWEEN :c AND :a - 1 THEN rgt + (:b - :a + 1) ELSE rgt END", - {:a => a, :b => b, :c => c, :d => d} - ]) - end - reload_nested_set_values - end - end - - def destroy_children - unless @without_nested_set_update - lock_nested_set - reload_nested_set_values - end - children.each {|c| c.send :destroy_without_nested_set_update} - unless @without_nested_set_update - self.class.where("lft > ? OR rgt > ?", lft, lft).update_all([ - "lft = CASE WHEN lft > :lft THEN lft - :shift ELSE lft END, " + - "rgt = CASE WHEN rgt > :lft THEN rgt - :shift ELSE rgt END", - {:lft => lft, :shift => rgt - lft + 1} - ]) - end - end - - def destroy_without_nested_set_update - @without_nested_set_update = true - destroy - end - - def reload_nested_set_values - self.lft, self.rgt = User.where(:id => id).pluck(:lft, :rgt).first - - end - - def save_nested_set_values - self.class.where(:id => id).update_all(:lft => lft, :rgt => rgt) - end - - def move_possible?(user) - new_record? || !is_or_is_ancestor_of?(user) - end - - def lock_nested_set - lock = true - if self.class.connection.adapter_name =~ /sqlserver/i - lock = "WITH (ROWLOCK HOLDLOCK UPDLOCK)" - end - self.class.order(:id).lock(lock).ids - end - - def nested_set_scope - self.class.order(:lft) - end - - def same_nested_set_scope?(user) - true - end - - module ClassMethods - def rebuild_tree! - transaction do - reorder(:id).lock.ids - update_all(:lft => nil, :rgt => nil) - rebuild_nodes - end - end - - private - - def rebuild_nodes(parent_id = nil) - nodes = User.where(:parent_id => parent_id).where(:rgt => nil, :lft => nil, :type => 'User').reorder(:lastname) - - nodes.each do |node| - node.send :add_to_nested_set, false - node.send :save_nested_set_values - rebuild_nodes node.id - end - end - end - end - end -end diff --git a/app/lib/load_patch/allowedto_user_patch.rb b/app/lib/load_patch/allowedto_user_patch.rb new file mode 100644 index 00000000..0c49ca80 --- /dev/null +++ b/app/lib/load_patch/allowedto_user_patch.rb @@ -0,0 +1,75 @@ +module LoadPatch::AllowedtoUserPatch + def self.included(base) + base.class_eval do + + def allowed_to?(action, context, options={}, &block) + # ======= ERPmine_patch Redmine 6.0 ========== + wktime_helper = Object.new.extend(WktimeHelper) + valid_ERP_perm = wktime_helper.validateERPPermission('A_TE_PRVLG') + isSupervisor = wktime_helper.isSupervisor + # ============================= + if context && context.is_a?(Project) + # ======= ERPmine_patch Redmine 6.0 ========== + # For allow supervisor and TEadmin to view time_entry + if ((valid_ERP_perm || isSupervisor) && action.to_s == 'view_time_entries') && wktime_helper.overrideSpentTime + return true + end + + if (action.to_s == 'view_time_entries') && wktime_helper.overrideSpentTime + return (context.allows_to?(:log_time) || context.allows_to?(:edit_time_entries) || context.allows_to?(:edit_own_time_entries)) + end + # ============================= + + return false unless context.allows_to?(action) + # Admin users are authorized for anything else + return true if admin? + + roles = roles_for_project(context) + return false unless roles + roles.any? do |role| + (context.is_public? || role.member?) && + role.allowed_to?(action) && + (block ? yield(role, self) : true) + end + elsif context && context.is_a?(Array) + if context.empty? + false + else + # Authorize if user is authorized on every element of the array + context.map {|project| allowed_to?(action, project, options, &block)}.reduce(:&) + end + elsif context + raise ArgumentError.new("#allowed_to? context argument must be a Project, an Array of projects or nil") + elsif options[:global] + # Admin users are always authorized + return true if admin? + + # ======= ERPmine_patch Redmine 6.0 ========== + if ((valid_ERP_perm || isSupervisor) && action.to_s == 'view_time_entries') && wktime_helper.overrideSpentTime + return true + end + # User Log API + if( action.is_a?(Hash) && action[:controller] == "wklogmaterial" && action[:action] == "index") + return true + end + # ============================= + # authorize if user has at least one role that has this permission + roles = self.roles.to_a | [builtin_role] + roles.any? do |role| + # ======= ERPmine_patch Redmine 6.0 ========== + if (action.to_s == 'view_time_entries') && wktime_helper.overrideSpentTime + (role.allowed_to?(:log_time) || role.allowed_to?(:edit_time_entries) || role.allowed_to?(:edit_own_time_entries)) + else + # ============================= + role.allowed_to?(action) && + (block ? yield(role, self) : true) + end + end + else + false + end + end + + end + end +end \ No newline at end of file diff --git a/app/lib/load_patch/auth_app_controller_patch.rb b/app/lib/load_patch/auth_app_controller_patch.rb new file mode 100644 index 00000000..8d79e326 --- /dev/null +++ b/app/lib/load_patch/auth_app_controller_patch.rb @@ -0,0 +1,35 @@ +module LoadPatch::AuthAppControllerPatch + def self.included(base) + base.class_eval do + + def authorize(ctrl = params[:controller], action = params[:action], global = false) + allowed = User.current.allowed_to?({:controller => ctrl, :action => action}, @project || @projects, :global => global) + if allowed + true + else + # ============= ERPmine_patch Redmine 6.0 ===================== + wktime_helper = Object.new.extend(WktimeHelper) + # isSupervisor = wktime_helper.isSupervisor + # ============================= + if @project && @project.archived? + @archived_project = @project + render_403 :message => :notice_not_authorized_archived_project + # ============= ERPmine_patch Redmine 6.0 ===================== + elsif ((action == 'edit' || action == 'update' || action == 'destroy') && ctrl == 'timelog' && (wktime_helper.isSupervisor && wktime_helper.canSupervisorEdit)) && wktime_helper.overrideSpentTime + true + elsif ((action == 'index' || action == 'report') && ctrl == 'timelog') && wktime_helper.overrideSpentTime + #Object.new.extend(WktimeHelper).isAccountUser || isSupervisor + return true + # ============================= + elsif @project && !@project.allows_to?(:controller => ctrl, :action => action) + # Project module is disabled + render_403 + else + deny_access + end + end + end + + end + end +end \ No newline at end of file diff --git a/app/lib/load_patch/editableby_time_entry_patch.rb b/app/lib/load_patch/editableby_time_entry_patch.rb new file mode 100644 index 00000000..3fe1865c --- /dev/null +++ b/app/lib/load_patch/editableby_time_entry_patch.rb @@ -0,0 +1,20 @@ +module LoadPatch::EditablebyTimeEntryPatch + def self.included(base) + base.class_eval do + + def editable_by?(usr) + # === ERPmine_patch Redmine 6.0 for supervisor edit ===== + wktime_helper = Object.new.extend(WktimeHelper) + if ((!user.blank? && wktime_helper.isSupervisorForUser(user.id)) && wktime_helper.canSupervisorEdit) + true + else + # ============================= + visible?(usr) && ( + (usr == user && usr.allowed_to?(:edit_own_time_entries, project)) || usr.allowed_to?(:edit_time_entries, project) + ) + end + end + + end + end +end \ No newline at end of file diff --git a/app/lib/ftte/ftte_hook.rb b/app/lib/load_patch/ftte_hook.rb similarity index 98% rename from app/lib/ftte/ftte_hook.rb rename to app/lib/load_patch/ftte_hook.rb index 65be7564..1fb4d4d9 100644 --- a/app/lib/ftte/ftte_hook.rb +++ b/app/lib/load_patch/ftte_hook.rb @@ -1,4 +1,4 @@ -module Ftte +module LoadPatch class FtteHook < Redmine::Hook::ViewListener #Hook code to put Supervisor dropdown in Admin -> User edit page def view_users_form(context={}) diff --git a/app/lib/load_patch/scope_time_entry_query_patch.rb b/app/lib/load_patch/scope_time_entry_query_patch.rb new file mode 100644 index 00000000..d48f6186 --- /dev/null +++ b/app/lib/load_patch/scope_time_entry_query_patch.rb @@ -0,0 +1,135 @@ +module LoadPatch::ScopeTimeEntryQueryPatch + def self.included(base) + base.class_eval do + + # ============= ERPmine_patch Redmine 6.0 ===================== + def base_scope(options={}) + if options[:nonSpentTime].present? + TimeEntry. + joins("RIGHT JOIN issues ON time_entries.issue_id = issues.id"). + joins("INNER JOIN projects ON projects.id = time_entries.project_id OR projects.id = issues.project_id"). + joins("LEFT JOIN users ON users.id = time_entries.user_id AND users.type IN ('User', 'AnonymousUser')"). + joins("LEFT JOIN enumerations ON enumerations.id = time_entries.activity_id AND enumerations.type IN ('TimeEntryActivity')"). + where(custom_condition). + where(TimeEntry.visible_condition(User.current)) + else + # ====================================== + TimeEntry.visible. + joins(:project, :user). + includes(:activity). + references(:activity). + left_join_issue. + where(statement) + end + end + + def custom_condition + if (getSupervisorCondStr || "").include?("time_entries") + condstr = " projects.id = issues.project_id AND time_entries.id IS NULL" + projFilter = filters && filters["project_id"] + if filters.present? && projFilter.present? + projFilter[:values] = User.current.memberships.map(&:project_id).map(&:to_s) if projFilter[:values] && projFilter[:values].first == 'mine' + condstr += " AND " + sql_for_field("project_id", projFilter[:operator], projFilter[:values], "issues", "project_id") + end + condstr += " AND issues.project_id = #{project.id} " if project.present? + getSupervisorCondStr.insert(getSupervisorCondStr.index("time_entries"), condstr + " ) OR ( ") + else + getSupervisorCondStr + end + end + + def results_scope(options={}) + order_option = [group_by_sort_order, (options[:order] || sort_clause)].flatten.reject(&:blank?) + + order_option << "#{TimeEntry.table_name}.id ASC" + # ============= ERPmine_patch Redmine 6.0 ===================== + if options[:nonSpentTime].present? + base_scope(options) + else + # ====================================== + base_scope. + order(order_option). + joins(joins_for_order_statement(order_option.join(','))) + end + end + + #========= ERPmine_patch Redmine 6.0 for get supervision condition string ====== + def getSupervisorCondStr + orgCondStatement = statement + condStatement = orgCondStatement + + wktime_helper = Object.new.extend(WktimeHelper) + if wktime_helper.overrideSpentTime + valid_ERP_perm = wktime_helper.validateERPPermission('A_TE_PRVLG') + isSupervisor = wktime_helper.isSupervisor + projectIdArr = wktime_helper.getManageProject() + isManager = projectIdArr.blank? ? false : true + + if isSupervisor && !valid_ERP_perm && !User.current.admin? + userIdArr = Array.new + user_cond = "" + rptUsers = wktime_helper.getReportUsers(User.current.id) + userIdArr = rptUsers.collect(&:id) if !rptUsers.blank? + userIdArr = userIdArr << User.current.id.to_s + userIds = "#{userIdArr.join(',')}" + user_cond = "#{TimeEntry.table_name}.user_id IN (#{userIds})" + + if condStatement.blank? + condStatement = "(#{user_cond})" if !user_cond.blank? + else + if filters["user_id"].blank? + condStatement = user_cond.blank? ? condStatement : condStatement + " AND (#{user_cond})" + else + user_id = filters["user_id"][:values] + userIdStrArr = userIdArr.collect{|i| i.to_s} + filterUserIds = userIdStrArr & filters["user_id"][:values] + + if !filterUserIds.blank? + if user_id.is_a?(Array) && user_id.include?("me") + filterUserIds << (User.current.id).to_s + end + filters["user_id"][:values] = filterUserIds #overriding user filters to get query condition for supervisor + condStatement = statement + filters["user_id"][:values] = user_id #Setting the filter values to retain the filter on page + else + if user_id.is_a?(Array) && user_id.include?("me") + filters["user_id"][:values] = [User.current.id.to_s] + condStatement = statement + filters["user_id"][:values] = user_id + else + condStatement = "1=0" + end + end + end + end + if isManager + mgrCondStatement = "" + if !orgCondStatement.blank? + mgrCondStatement = orgCondStatement + " AND " + end + mgrCondStatement = mgrCondStatement + "(#{TimeEntry.table_name}.project_id in (" + projectIdArr.collect{|i| i.to_s}.join(',') + "))" + condStatement = condStatement.blank? ? condStatement : "(" + condStatement + ") OR (" + mgrCondStatement + ")" + end + else + #if (!Setting.plugin_redmine_wktime['ftte_view_only_own_spent_time'].blank? && + #Setting.plugin_redmine_wktime['ftte_view_only_own_spent_time'].to_i == 1) && + if !valid_ERP_perm && !User.current.admin? && !isManager + cond = " (#{TimeEntry.table_name}.user_id = " + User.current.id.to_s + ")" + condStatement = condStatement.blank? ? cond : condStatement + " AND #{cond}" + elsif isManager && !valid_ERP_perm && !User.current.admin? + user_id = filters["user_id"][:values] if !filters["user_id"].blank? + if !user_id.blank? && user_id.is_a?(Array) && (user_id.include?("me") || user_id.include?(User.current.id.to_s)) + condStatement = condStatement + else + condStatement = condStatement.blank? ? condStatement : "(" + condStatement + ") AND (#{TimeEntry.table_name}.project_id in (" + projectIdArr.collect{|i| i.to_s}.join(',') + "))" + end + end + end + end + condStatement + end + # ============================= + + end + end +end \ No newline at end of file diff --git a/app/lib/time_report_patch.rb b/app/lib/load_patch/time_report_patch.rb similarity index 91% rename from app/lib/time_report_patch.rb rename to app/lib/load_patch/time_report_patch.rb index cde32da3..98cde395 100644 --- a/app/lib/time_report_patch.rb +++ b/app/lib/load_patch/time_report_patch.rb @@ -1,15 +1,16 @@ -module TimeReportPatch +module LoadPatch::TimeReportPatch module Redmine::Helpers class TimeReport + attr_reader :criteria, :columns, :hours, :total_hours, :periods - # ============= ERPmine_patch Redmine 5.1 ===================== + # ============= ERPmine_patch Redmine 6.0 ===================== def initialize(project, criteria, columns, time_entry_scope, options={}) @options = options # ====================================== @project = project - # ============= ERPmine_patch Redmine 5.1 ===================== + # ============= ERPmine_patch Redmine 6.0 ===================== @scope = time_entry_scope # ====================================== @criteria = criteria || [] @@ -28,7 +29,7 @@ def run unless @criteria.empty? time_columns = %w(tyear tmonth tweek spent_on) @hours = [] - # ============= ERPmine_patch Redmine 5.1 ===================== + # ============= ERPmine_patch Redmine 6.0 ===================== scopeArr = @scope.attribute_names if scopeArr.include? "selling_price" # ====================================== @@ -37,7 +38,7 @@ def run reorder(nil). group(@criteria.collect{|criteria| @available_criteria[criteria][:sql]} + time_columns). joins(@criteria.filter_map{|criteria| @available_criteria[criteria][:joins]}). - # ============= ERPmine_patch Redmine 5.1 ===================== + # ============= ERPmine_patch Redmine 6.0 ===================== sum("wk_material_entries.selling_price * wk_material_entries.quantity").each do |hash, selling_price| h = {'hours' => selling_price} (@criteria + time_columns).each_with_index do |name, i| @@ -70,7 +71,7 @@ def run end @hours << h end - # ============= ERPmine_patch Redmine 5.1 ===================== + # ============= ERPmine_patch Redmine 6.0 ===================== end # ============================== @@ -81,14 +82,14 @@ def run when 'month' row['month'] = "#{row['tyear']}-#{row['tmonth']}" when 'week' - # ============= ERPmine_patch Redmine 5.1 ===================== + # ============= ERPmine_patch Redmine 6.0 ===================== row['week'] = "#{row['spent_on'].cwyear}-#{row['tweek']}" if row['spent_on'].present? # ============================== when 'day' row['day'] = "#{row['spent_on']}" end end - # ============= ERPmine_patch Redmine 5.1 ===================== + # ============= ERPmine_patch Redmine 6.0 ===================== min = @hours.pluck('spent_on').min @from = min ? min.to_date : User.current.today @@ -122,7 +123,7 @@ def run end def load_available_criteria - # ============= ERPmine_patch Redmine 5.1 ===================== + # ============= ERPmine_patch Redmine 6.0 ===================== scopeArr = @scope.attribute_names if scopeArr.include? "selling_price" model = WkMaterialEntry @@ -133,7 +134,7 @@ def load_available_criteria end # ================================== @available_criteria = { - # ============= ERPmine_patch Redmine 5.1 ===================== + # ============= ERPmine_patch Redmine 6.0 ===================== 'project' => {:sql => @options[:nonSpentTime].present? ? "coalesce(time_entries.project_id, issues.project_id)" : "#{model.table_name}.project_id", # ================================== :klass => Project, @@ -147,7 +148,7 @@ def load_available_criteria 'category' => {:sql => "#{Issue.table_name}.category_id", :klass => IssueCategory, :label => :field_category}, - # ============= ERPmine_patch Redmine 5.1 ===================== + # ============= ERPmine_patch Redmine 6.0 ===================== 'user' => {:sql => @options[:nonSpentTime].present? ? "coalesce(time_entries.user_id, issues.assigned_to_id)" : "#{model.table_name}.user_id", # ================================== :klass => User, @@ -157,7 +158,7 @@ def load_available_criteria :label => :label_tracker}, 'activity' => {:sql => "COALESCE(#{TimeEntryActivity.table_name}.parent_id, #{TimeEntryActivity.table_name}.id)", :klass => TimeEntryActivity, - # ============= ERPmine_patch Redmine 5.1 ===================== + # ============= ERPmine_patch Redmine 6.0 ===================== :label => :label_activity}, 'issue' => {:sql => @options[:nonSpentTime].present? ? "coalesce(time_entries.issue_id, issues.id)" : "#{model.table_name}.issue_id", # ================================== @@ -165,7 +166,7 @@ def load_available_criteria :label => :label_issue} } - # ============= ERPmine_patch Redmine 5.1 ===================== + # ============= ERPmine_patch Redmine 6.0 ===================== if scopeArr.include? "selling_price" hashval = { 'Product Item' => {:sql => "#{WkMaterialEntry.table_name}.inventory_item_id", @@ -196,5 +197,6 @@ def load_available_criteria @available_criteria end end + end end \ No newline at end of file diff --git a/app/lib/load_patch/user_nested_set.rb b/app/lib/load_patch/user_nested_set.rb new file mode 100644 index 00000000..0482c003 --- /dev/null +++ b/app/lib/load_patch/user_nested_set.rb @@ -0,0 +1,144 @@ +module LoadPatch + module UserNestedSet + def self.included(base) + base.class_eval do + + before_create :add_to_nested_set + before_update :move_in_nested_set, :if => lambda {|user| user.parent_id_changed? || user.lastname_changed?} + before_destroy :update_children #destroy_children + end + base.extend ClassMethods + base.send :include, Redmine::NestedSet::Traversing + end + + private + + def update_children + self.class.where(:parent_id => id).update_all(:parent_id => nil) + User.rebuild_tree! + end + + def target_lft + siblings_rgt = self.class.where(:parent_id => parent_id).where("lastname < ?", lastname).maximum(:rgt) + if siblings_rgt + siblings_rgt + 1 + elsif parent_id + parent_lft = self.class.where(:id => parent_id).pluck(:lft).first + raise "user id=#{id} with parent_id=#{parent_id}: parent missing or without 'lft' value" unless parent_lft + parent_lft + 1 + else + 1 + end + end + + def add_to_nested_set(lock=true) + lock_nested_set if lock + self.lft = target_lft + self.rgt = lft + 1 + self.class.where("lft >= ? OR rgt >= ?", lft, lft).update_all([ + "lft = CASE WHEN lft >= :lft THEN lft + 2 ELSE lft END, " + + "rgt = CASE WHEN rgt >= :lft THEN rgt + 2 ELSE rgt END", + {:lft => lft} + ]) + end + + def move_in_nested_set + lock_nested_set + reload_nested_set_values + a = lft + b = rgt + c = target_lft + unless c == a + if c > a + # Moving to the right + d = c - (b - a + 1) + scope = self.class.where(["lft BETWEEN :a AND :c - 1 OR rgt BETWEEN :a AND :c - 1", {:a => a, :c => c}]) + scope.update_all([ + "lft = CASE WHEN lft BETWEEN :a AND :b THEN lft + (:d - :a) WHEN lft BETWEEN :b + 1 AND :c - 1 THEN lft - (:b - :a + 1) ELSE lft END, " + + "rgt = CASE WHEN rgt BETWEEN :a AND :b THEN rgt + (:d - :a) WHEN rgt BETWEEN :b + 1 AND :c - 1 THEN rgt - (:b - :a + 1) ELSE rgt END", + {:a => a, :b => b, :c => c, :d => d} + ]) + elsif c < a + # Moving to the left + scope = self.class.where("lft BETWEEN :c AND :b OR rgt BETWEEN :c AND :b", {:a => a, :b => b, :c => c}) + scope.update_all([ + "lft = CASE WHEN lft BETWEEN :a AND :b THEN lft - (:a - :c) WHEN lft BETWEEN :c AND :a - 1 THEN lft + (:b - :a + 1) ELSE lft END, " + + "rgt = CASE WHEN rgt BETWEEN :a AND :b THEN rgt - (:a - :c) WHEN rgt BETWEEN :c AND :a - 1 THEN rgt + (:b - :a + 1) ELSE rgt END", + {:a => a, :b => b, :c => c, :d => d} + ]) + end + reload_nested_set_values + end + end + + def destroy_children + unless @without_nested_set_update + lock_nested_set + reload_nested_set_values + end + children.each {|c| c.send :destroy_without_nested_set_update} + unless @without_nested_set_update + self.class.where("lft > ? OR rgt > ?", lft, lft).update_all([ + "lft = CASE WHEN lft > :lft THEN lft - :shift ELSE lft END, " + + "rgt = CASE WHEN rgt > :lft THEN rgt - :shift ELSE rgt END", + {:lft => lft, :shift => rgt - lft + 1} + ]) + end + end + + def destroy_without_nested_set_update + @without_nested_set_update = true + destroy + end + + def reload_nested_set_values + self.lft, self.rgt = User.where(:id => id).pluck(:lft, :rgt).first + end + + def save_nested_set_values + self.class.where(:id => id).update_all(:lft => lft, :rgt => rgt) + end + + def move_possible?(user) + new_record? || !is_or_is_ancestor_of?(user) + end + + def lock_nested_set + lock = true + if self.class.connection.adapter_name =~ /sqlserver/i + lock = "WITH (ROWLOCK HOLDLOCK UPDLOCK)" + end + self.class.order(:id).lock(lock).ids + end + + def nested_set_scope + self.class.order(:lft) + end + + def same_nested_set_scope?(user) + true + end + + module ClassMethods + def rebuild_tree! + transaction do + reorder(:id).lock.ids + update_all(:lft => nil, :rgt => nil) + rebuild_nodes + end + end + + private + + def rebuild_nodes(parent_id = nil) + nodes = User.where(:parent_id => parent_id).where(:rgt => nil, :lft => nil, :type => 'User').reorder(:lastname) + + nodes.each do |node| + node.send :add_to_nested_set, false + node.send :save_nested_set_values + rebuild_nodes node.id + end + end + end + end +end diff --git a/app/lib/load_patch/wktime_hook.rb b/app/lib/load_patch/wktime_hook.rb new file mode 100644 index 00000000..ca5a74c7 --- /dev/null +++ b/app/lib/load_patch/wktime_hook.rb @@ -0,0 +1,81 @@ +module LoadPatch + class WktimeHook < Redmine::Hook::ViewListener + + def view_timelog_edit_form_bottom(context={ }) + showWarningMsg(context[:request],context[:time_entry].user_id, true) + end + + def view_issues_edit_notes_bottom(context={}) + showWarningMsg(context[:request], User.current.id, false) + end + + def showWarningMsg(req, user_id, log_time_page) + wktime_helper = Object.new.extend(WktimeHelper) + host_with_subdir = wktime_helper.getHostAndDir(req) + "
+ +
+ 'getStatus', :host => host_with_subdir, :only_path => true, :user_id => user_id)}'> + 'getTracker', :host => host_with_subdir, :only_path => true)}'> + + + " + end + + def controller_issues_edit_before_save(context={}) + if !context[:time_entry].blank? + if !context[:time_entry].hours.blank? && !context[:time_entry].activity_id.blank? + wktime_helper = Object.new.extend(WktimeHelper) + status= wktime_helper.getTimeEntryStatus(context[:time_entry].spent_on,context[:time_entry].user_id) + if !status.blank? && ('a' == status || 's' == status || 'l' == status) + raise "#{l(:label_warning_wktime_time_entry)}" + end + end + end + end + render_on :view_layouts_base_content, :partial => 'wktime/attendance_widget' + render_on :view_timelog_edit_form_bottom, :partial => 'wklogmaterial/log_material' + render_on :view_users_form, :partial => 'wkuser/wk_user', locals: { myaccount: false } + render_on :view_users_form_preferences, :partial => 'wkuser/wk_user_address', locals: { myaccount: false } + render_on :view_my_account, :partial => 'wkuser/wk_user', locals: { myaccount: true } + render_on :view_my_account_preferences, :partial => 'wkuser/wk_user_address', locals: { myaccount: true } + render_on :view_issues_form_details_bottom, :partial => 'wkissues/wk_issue_fields' + + def controller_issues_edit_before_save(context={}) + saveErpmineIssues(context[:issue], context[:params][:erpmineissues]) + saveErpmineIssueAssignee(context[:issue], context[:issue][:project_id], context[:params][:wk_issue_assignee]) + end + + def controller_issues_new_before_save(context={}) + saveErpmineIssues(context[:issue], context[:params][:erpmineissues]) + saveErpmineIssueAssignee(context[:issue], context[:issue][:project_id], context[:params][:wk_issue_assignee]) + end + + def saveErpmineIssues(issueObj, issueParm) + issueObj.erpmineissues.safe_attributes = issueParm + end + + def saveErpmineIssueAssignee(issueObj, projectId, userIdArr) + assigneeAttributes = Array.new + # userIdArr.each do |userId| + # assigneeAttributes << {user_id: userId.to_i, project_id: projectId} + # end + # issueObj.assignees_attributes = assigneeAttributes + WkIssueAssignee.where(:issue_id => issueObj.id).where.not(:user_id => userIdArr).delete_all() + unless userIdArr.blank? + userIdArr.collect{ |id| + iscount = WkIssueAssignee.where("issue_id = ? and user_id = ? ", issueObj.id, id).count + unless iscount > 0 + assigneeAttributes << {user_id: id.to_i, project_id: projectId} + end + } + end + issueObj.assignees_attributes = assigneeAttributes + end + + render_on :view_issues_show_description_bottom, :partial => 'wkissues/show_wk_issues' + render_on :view_layouts_base_html_head, :partial => 'wkbase/base_header' + render_on :view_projects_form, :partial => 'wkproject/project_settings' + + end +end \ No newline at end of file diff --git a/app/lib/load_patch/wktime_scheduler.rb b/app/lib/load_patch/wktime_scheduler.rb new file mode 100644 index 00000000..a905808c --- /dev/null +++ b/app/lib/load_patch/wktime_scheduler.rb @@ -0,0 +1,211 @@ +module LoadPatch::WktimeScheduler + Rails.configuration.to_prepare do + if ActiveRecord::Base.connection.table_exists? "#{Setting.table_name}" + if ActiveRecord::Base.connection.table_exists?("#{WkNotification.table_name}") && WkNotification.notify('nonSubmission') + + require 'rufus/scheduler' + + if (!Setting.plugin_redmine_wktime['wktime_use_approval_system'].blank? && Setting.plugin_redmine_wktime['wktime_use_approval_system'].to_i == 1) + submissionDeadline = Setting.plugin_redmine_wktime['wktime_submission_deadline'] + hr = Setting.plugin_redmine_wktime['wktime_nonsub_sch_hr'] + min = Setting.plugin_redmine_wktime['wktime_nonsub_sch_min'] + scheduler = Rufus::Scheduler.new #changed from start_new to new to make compatible with latest version rufus scheduler 3.0.3 + if hr == '0' && min == '0' + cronSt = "0 * * * #{submissionDeadline}" + else + cronSt = "#{min} #{hr} * * #{submissionDeadline}" + end + scheduler.cron cronSt do + begin + Rails.logger.info "==========Non submission mail job - Started==========" + wktime_helper = Object.new.extend(WktimeHelper) + wktime_helper.sendNonSubmissionMail() + rescue Exception => e + Rails.logger.info "Job failed: #{e.message}" + end + end + end + end + + if (!Setting.plugin_redmine_wktime['wktime_period_end_process'].blank? && Setting.plugin_redmine_wktime['wktime_period_end_process'].to_i == 1) + require 'rufus/scheduler' + scheduler2 = Rufus::Scheduler.new + #Scheduler will run at 12:01 AM on 1st of every month + cronSt = "01 00 01 * *" + scheduler2.cron cronSt do + begin + Rails.logger.info "==========Attendance job - Started==========" + wkattn_helper = Object.new.extend(WkattendanceHelper) + wkattn_helper.populateWkUserLeaves(Date.today) + Rails.logger.info "==========Attendance job - Completed==========" + rescue Exception => e + Rails.logger.info "Job failed: #{e.message}" + end + end + end + + if (!Setting.plugin_redmine_wktime['wktime_auto_import'].blank? && Setting.plugin_redmine_wktime['wktime_auto_import'].to_i == 1) + require 'rufus/scheduler' + importScheduler = Rufus::Scheduler.new + import_helper = Object.new.extend(WkimportattendanceHelper) + intervalMin = import_helper.calcSchdulerInterval + #Scheduler will run at every intervalMin + importScheduler.every intervalMin do + begin + Rails.logger.info "==========Import Attendance - Started==========" + filePath = Setting.plugin_redmine_wktime['wktime_file_to_import'] + # Sort the files by modified date ascending order + sortedFilesArr = Dir.entries(filePath).sort_by { |x| File.mtime(filePath + "/" + x) } + sortedFilesArr.each do |filename| + next if File.directory? filePath + "/" + filename + isSuccess = import_helper.importAttendance(filePath + "/" + filename, true ) + if !Dir.exists?("Processed") + FileUtils::mkdir_p filePath+'/Processed'#Dir.mkdir("Processed") + end + if isSuccess + FileUtils.mv filePath + "/" + filename, filePath+'/Processed', :force => true + Rails.logger.info("====== #{filename} moved processed directory=========") + end + end + rescue Exception => e + Rails.logger.error "Import failed: #{e.message}" + end + end + end + + if (!Setting.plugin_redmine_wktime['wktime_auto_generate_salary'].blank? && Setting.plugin_redmine_wktime['wktime_auto_generate_salary'].to_i == 1) + require 'rufus/scheduler' + salaryScheduler = Rufus::Scheduler.new + payperiod = Setting.plugin_redmine_wktime['wktime_pay_period'] + payDay = Setting.plugin_redmine_wktime['wktime_pay_day'] + if payperiod == 'm' + #Scheduler will run at 12:01 AM on 1st of every month + cronSt = "01 00 01 * *" + else + #Scheduler will run at 12:01 AM on payDay of every week + cronSt = "01 00 * * #{payDay}" + end + salaryScheduler.cron cronSt do + begin + currentMonthStart = Date.civil(Date.today.year, Date.today.month, Date.today.day) + runJob = true + # payperiod is bi-weekly then run scheduler every two weeks + if payperiod == 'bw' + salaryCount = WkSalary.where("salary_date between '#{currentMonthStart-14}' and '#{currentMonthStart-1}'").count + runJob = false if salaryCount > 0 + end + if runJob + Rails.logger.info "==========Payroll job - Started==========" + wkpayroll_helper = Object.new.extend(WkpayrollHelper) + errorMsg = wkpayroll_helper.generateSalaries(nil,currentMonthStart) + Rails.logger.info "===== Payroll generated Successfully =====" + end + rescue Exception => e + Rails.logger.info "Job failed: #{e.message}" + end + end + end + + if (!Setting.plugin_redmine_wktime['wktime_auto_generate_invoice'].blank? && Setting.plugin_redmine_wktime['wktime_auto_generate_invoice'].to_i == 1) + require 'rufus/scheduler' + invoiceScheduler = Rufus::Scheduler.new + invPeriod = Setting.plugin_redmine_wktime['wktime_generate_invoice_period'] + invDay = Setting.plugin_redmine_wktime['wktime_generate_invoice_day'] + genInvFrom = Setting.plugin_redmine_wktime['wktime_generate_invoice_from'].to_date + if invPeriod == 'm' || invPeriod == 'q' + #Scheduler will run at 12:01 AM on 1st of every month + cronSt = "01 00 01 * *" + else + #Scheduler will run at 12:01 AM on invDay of every week + cronSt = "01 00 * * #{invDay.blank? ? 0 : invDay}" + end + invoiceScheduler.cron cronSt do + begin + invoicePeriod = nil + fromDate = nil + currentMonthStart = Date.civil(Date.today.year, Date.today.month, Date.today.day) + runJob = true + case invPeriod + when 'q' + fromDate = currentMonthStart<<4 < genInvFrom ? genInvFrom : currentMonthStart<<4 + #Scheduler will run at 12:01 AM on 1st of every April, July, October and January months + runJob = false if (currentMonthStart.month%3)-1 > 0 + when 'w' + #Scheduler will run at 12:01 AM on invDay of every week + fromDate = currentMonthStart-7 < genInvFrom ? genInvFrom : currentMonthStart-7 + when 'bw' + invoiceCount = WkInvoice.where("invoice_date between '#{currentMonthStart-14}' and '#{currentMonthStart-1}'").count + runJob = false if invoiceCount > 0 + fromDate = currentMonthStart-14 < genInvFrom ? genInvFrom : currentMonthStart-14 + else + #Scheduler will run at 12:01 AM on 1st of every month + fromDate = (currentMonthStart-1).beginning_of_month < genInvFrom ? genInvFrom : (currentMonthStart-1).beginning_of_month + end + invoicePeriod = [fromDate, currentMonthStart-1] + if runJob + Rails.logger.info "==========Invoice job - Started==========" + invoiceHelper = Object.new.extend(WkinvoiceHelper) + allAccProjets = WkAccountProject.all + errorMsg = nil + allAccProjets.each do |accProj| + errorMsg = invoiceHelper.generateInvoices(accProj, nil, currentMonthStart, invoicePeriod)#account.id + end + if errorMsg.blank? + Rails.logger.info "===== Invoice generated Successfully =====" + else + if errorMsg.is_a?(Hash) + Rails.logger.info "===== Invoice generated Successfully =====" + Rails.logger.info "===== Job failed: #{errorMsg['trans']} =====" + else + Rails.logger.info "===== Job failed: #{errorMsg} =====" + end + end + end + rescue Exception => e + Rails.logger.info "Job failed: #{e.message}" + end + end + end + + if (!Setting.plugin_redmine_wktime['auto_apply_depreciation'].blank? && Setting.plugin_redmine_wktime['auto_apply_depreciation'].to_i == 1) + require 'rufus/scheduler' + deprScheduler = Rufus::Scheduler.new + wkpayroll_helper = Object.new.extend(WkpayrollHelper) + wkinventory_helper = Object.new.extend(WkinventoryHelper) + financialStart = wkpayroll_helper.getFinancialStart.to_i + depreciationFreq = wkinventory_helper.getFrequencyMonth(Setting.plugin_redmine_wktime['wktime_depreciation_frequency']) + #Scheduler will run at 12:01 AM on 1st of every month + cronSt = "01 00 01 * *" + deprScheduler.cron cronSt do + begin + unless (( financialStart - Date.today.month + 12)%depreciationFreq) > 0 + Rails.logger.info "==========Depreciation job - Started==========" + depreciation_helper = Object.new.extend(WkassetdepreciationHelper) + errorMsg = depreciation_helper.previewOrSaveDepreciation(Date.today - 1, Date.today - 1, nil, false) + Rails.logger.info "===== Depreciation applied Successfully =====" + end + rescue Exception => e + Rails.logger.info "Job failed: #{e.message}" + end + end + end + + if (!Setting.plugin_redmine_wktime['wk_auto_shift_scheduling'].blank? && Setting.plugin_redmine_wktime['wk_auto_shift_scheduling'].to_i == 1) + require 'rufus/scheduler' + shiftschedular = Rufus::Scheduler.new + #Scheduler will run at 12:01 AM on 1st of every month + cronSt = "01 00 01 * *" + shiftschedular.cron cronSt do + begin + Rails.logger.info "========== Shift Scheduling job - Started==========" + scheduling_helper = Object.new.extend(WkschedulingHelper) + scheduling_helper.autoShiftScheduling + Rails.logger.info "========== Shift Scheduling job - Finished==========" + rescue Exception => e + Rails.logger.info "Job failed: #{e.message}" + end + end + end + end + end +end \ No newline at end of file diff --git a/app/lib/queries_helper_patch.rb b/app/lib/queries_helper_patch.rb deleted file mode 100644 index b4b2a6e8..00000000 --- a/app/lib/queries_helper_patch.rb +++ /dev/null @@ -1,100 +0,0 @@ -module QueriesHelper - - # def self.included(base) - # base.send(:include, InstanceMethods) - - # base.class_eval do - # unloadable - # alias_method :column_value_without_wktime_projects, :column_value - # alias_method :column_value, :column_value_with_wktime_projects - # end - # end - - # module InstanceMethods - def column_value_with_wktime_projects(column, item, value) - case column.name - # ============= ERPmine_patch Redmine 5.1 ===================== - when :inventory_item_id - formProductItem(item) - when :selling_price - val = item.selling_price * item.quantity - value = val.blank? ? 0.00 : ("%.2f" % val) - when :resident_id - val = item.resident.name - value = val - when :resident_type - value = item.resident.location.name - when :apartment_id - value = item.apartment.blank? ? "" : item.apartment.asset_property.name - when :bed_id - value = item.bed.blank? ? "" : item.bed.asset_property.name - # ============================= - else - column_value_without_wktime_projects(column, item, value) - end - end - alias_method :column_value_without_wktime_projects, :column_value - alias_method :column_value, :column_value_with_wktime_projects - # end - - def render_query_totals(query) - return unless query.totalable_columns.present? - - totals = query.totalable_columns.map do |column| - # ============= ERPmine_patch Redmine 5.1 ===================== - if [:quantity, :selling_price].include? column.name - product_type = session[:timelog][:spent_type] == "M" ? 'I' : session[:timelog][:spent_type] - query[:filters]['product_type'] = {"operator":"=","values" => product_type} - end - # ============================= - total_tag(column, query.total_for(column)) - end - content_tag('p', totals.join(" ").html_safe, :class => "query-totals") - end - - def query_to_csv(items, query, options={}) - columns = query.columns - - Redmine::Export::CSV.generate(encoding: params[:encoding], field_separator: params[:field_separator]) do |csv| - # csv header fields - csv << columns.map {|c| c.caption.to_s} - # csv lines - items.each do |item| - # ============= ERPmine_patch Redmine 5.1 ===================== - csv << columns.map {|c| [:inventory_item_id].include?(c.name) ? wk_csv_content(item) : csv_content(c, item)} - # ============================= - end - end - end - - # ============= ERPmine_patch Redmine 5.1 ===================== - def wk_csv_content(item) - formProductItem(item) - end - - def formProductItem(item) - brandName = item.inventory_item&.product_item&.brand.blank? ? "" : item.inventory_item&.product_item&.brand&.name - modelName = item.inventory_item&.product_item&.product_model.blank? ? "" : item.inventory_item&.product_item&.product_model&.name - serialNo = item.inventory_item&.serial_number.blank? ? "" : item.inventory_item&.serial_number&.to_s - runSerialNo = item.inventory_item&.running_sn.blank? ? "" : item.inventory_item&.running_sn&.to_s - val = item.inventory_item.product_item.product.name - product_items = "#{brandName} - #{modelName} - #{serialNo + runSerialNo}" - assetObj = item.inventory_item.asset_property - value = item&.inventory_item&.product_type == 'I' ? val+' - '+product_items : val +' - '+ assetObj.name - end - # ============================= - - # Renders the list of queries for the sidebar - def render_sidebar_queries(klass, project) - # ============= ERPmine_patch Redmine 5.1 ===================== - spent_type = session[:timelog] && session[:timelog][:spent_type] - kclassName = spent_type == "M" || spent_type == "A" ? WkMaterialEntryQuery : (spent_type == 'E' ? WkExpenseEntryQuery : klass) - queries = sidebar_queries(kclassName, project) - # ============================= - - out = ''.html_safe - out << query_links(l(:label_my_queries), queries.select(&:is_private?)) - out << query_links(l(:label_query_plural), queries.reject(&:is_private?)) - out - end -end \ No newline at end of file diff --git a/app/lib/send_patch/application_helper_patch.rb b/app/lib/send_patch/application_helper_patch.rb new file mode 100644 index 00000000..f630f867 --- /dev/null +++ b/app/lib/send_patch/application_helper_patch.rb @@ -0,0 +1,92 @@ +module SendPatch::ApplicationHelperPatch + def self.included(base) + base.class_eval do + def format_object(object, *args, &block) + options = + if args.first.is_a?(Hash) + args.first + elsif !args.empty? + # Support the old syntax `format_object(object, html_flag)` + # TODO: Display a deprecation warning in a future version, then remove this + {:html => args.first} + else + {} + end + + html = options.fetch(:html, true) + thousands_delimiter = options.fetch(:thousands_delimiter, false) + delimiter_char = thousands_delimiter ? ::I18n.t('number.format.delimiter') : nil + + if block + object = yield object + end + case object + when Array + formatted_objects = object.map do |o| + format_object(o, html: html, thousands_delimiter: thousands_delimiter) + end + html ? safe_join(formatted_objects, ', ') : formatted_objects.join(', ') + when Time, ActiveSupport::TimeWithZone + format_time(object) + when Date + format_date(object) + when Integer + number_with_delimiter(object, delimiter: delimiter_char) + when Float + number_with_delimiter(sprintf('%.2f', object), delimiter: delimiter_char) + when User, Group + html ? link_to_principal(object) : object.to_s + when Project + html ? link_to_project(object) : object.to_s + when Version + html ? link_to_version(object) : object.to_s + when TrueClass + l(:general_text_Yes) + when FalseClass + l(:general_text_No) + when Issue + object.visible? && html ? link_to_issue(object) : "##{object.id}" + when Attachment + if html + content_tag( + :span, + link_to_attachment(object) + + link_to_attachment( + object, + :class => ['icon-only', 'icon-download'], + :title => l(:button_download), + :download => true + ) + ) + else + object.filename + end + # ============= ERPmine_patch Redmine 6.0 ===================== + when WkInventoryItem + brandName = object.product_item.brand.blank? ? "" : object.product_item.brand.name + modelName = object.product_item.product_model.blank? ? "" : object.product_item.product_model.name + str = "#{object.product_item.product.name} - #{brandName} - #{modelName}" + assetObj = object.asset_property + str = str + ' - ' +assetObj.name if object&.product_type != 'I' + str + # ============================= + when CustomValue, CustomFieldValue + return "" unless object.customized&.visible? + + if object.custom_field + f = object.custom_field.format.formatted_custom_value(self, object, html) + if f.nil? || f.is_a?(String) + f + else + format_object(f, html: html, thousands_delimiter: object.custom_field.thousands_delimiter?, &block) + end + else + object.value.to_s + end + else + html ? h(object) : object.to_s + end + end + end + end +end \ No newline at end of file diff --git a/app/lib/context_menus_controller_patch.rb b/app/lib/send_patch/context_menus_controller_patch.rb similarity index 87% rename from app/lib/context_menus_controller_patch.rb rename to app/lib/send_patch/context_menus_controller_patch.rb index fa6807e8..6250c773 100644 --- a/app/lib/context_menus_controller_patch.rb +++ b/app/lib/send_patch/context_menus_controller_patch.rb @@ -1,55 +1,55 @@ -module ContextMenusControllerPatch - def self.included(base) - base.class_eval do - - def time_entries - # ============= ERPmine_patch Redmine 5.1 ===================== - @options_by_custom_field = {} - if session[:timelog][:spent_type] === "T" - # ======================= - @time_entries = TimeEntry.where(:id => params[:ids]). - preload(:project => :time_entry_activities). - preload(:user).to_a - - (render_404; return) unless @time_entries.present? - if @time_entries.size == 1 - @time_entry = @time_entries.first - end - - @projects = @time_entries.filter_map(&:project).uniq - @project = @projects.first if @projects.size == 1 - @activities = @projects.map(&:activities).reduce(:&) - - edit_allowed = @time_entries.all? {|t| t.editable_by?(User.current)} - @can = {:edit => edit_allowed, :delete => edit_allowed} - @back = back_url - - @options_by_custom_field = {} - if @can[:edit] - custom_fields = @time_entries.map(&:editable_custom_fields).reduce(:&).reject(&:multiple?).select {|field| field.format.bulk_edit_supported} - custom_fields.each do |field| - values = field.possible_values_options(@projects) - if values.present? - @options_by_custom_field[field] = values - end - end - end - - # ============= ERPmine_patch Redmine 5.1 ===================== - elsif session[:timelog][:spent_type] === "E" - @time_entries = WkExpenseEntry.where(id: params[:ids]).to_a - @can = {:edit => true, :delete => true} - else - @time_entries = WkMaterialEntry.where(id: params[:ids]).to_a - @can = {:edit => true, :delete => true} - end - (render_404; return) unless @time_entries.present? - if @time_entries.size == 1 - @time_entry = @time_entries.first - end - # ======================= - render :layout => false - end - end - end -end +module SendPatch::ContextMenusControllerPatch + def self.included(base) + base.class_eval do + + def time_entries + # ============= ERPmine_patch Redmine 6.0 ===================== + @options_by_custom_field = {} + if session[:timelog][:spent_type] === "T" + # ======================= + @time_entries = TimeEntry.where(:id => params[:ids]). + preload(:project => :time_entry_activities). + preload(:user).to_a + + (render_404; return) unless @time_entries.present? + if @time_entries.size == 1 + @time_entry = @time_entries.first + end + + @projects = @time_entries.filter_map(&:project).uniq + @project = @projects.first if @projects.size == 1 + @activities = @projects.map(&:activities).reduce(:&) + + edit_allowed = @time_entries.all? {|t| t.editable_by?(User.current)} + @can = {:edit => edit_allowed, :delete => edit_allowed} + @back = back_url + + @options_by_custom_field = {} + if @can[:edit] + custom_fields = @time_entries.map(&:editable_custom_fields).reduce(:&).reject(&:multiple?).select {|field| field.format.bulk_edit_supported} + custom_fields.each do |field| + values = field.possible_values_options(@projects) + if values.present? + @options_by_custom_field[field] = values + end + end + end + + # ============= ERPmine_patch Redmine 6.0 ===================== + elsif session[:timelog][:spent_type] === "E" + @time_entries = WkExpenseEntry.where(id: params[:ids]).to_a + @can = {:edit => true, :delete => true} + else + @time_entries = WkMaterialEntry.where(id: params[:ids]).to_a + @can = {:edit => true, :delete => true} + end + (render_404; return) unless @time_entries.present? + if @time_entries.size == 1 + @time_entry = @time_entries.first + end + # ======================= + render :layout => false + end + end + end +end diff --git a/app/lib/send_patch/custom_fields_helper_patch.rb b/app/lib/send_patch/custom_fields_helper_patch.rb new file mode 100644 index 00000000..6741e826 --- /dev/null +++ b/app/lib/send_patch/custom_fields_helper_patch.rb @@ -0,0 +1,5 @@ +module SendPatch::CustomFieldsHelperPatch + def self.included(base) + CustomFieldsHelper::CUSTOM_FIELDS_TABS << {:name => 'WktimeCustomField', :partial => 'custom_fields/index', :label => :label_wk_time} + end +end \ No newline at end of file diff --git a/app/lib/send_patch/import_patch.rb b/app/lib/send_patch/import_patch.rb new file mode 100644 index 00000000..93fdcabe --- /dev/null +++ b/app/lib/send_patch/import_patch.rb @@ -0,0 +1,67 @@ +module SendPatch::ImportPatch + def self.included(base) + base.class_eval do + + def run(options={}) + max_items = options[:max_items] + max_time = options[:max_time] + current = 0 + imported = 0 + resume_after = items.maximum(:position) || 0 + interrupted = false + started_on = Time.now + + read_items do |row, position| + if (max_items && imported >= max_items) || (max_time && Time.now >= started_on + max_time) + interrupted = true + break + end + if position > resume_after + item = items.build + item.position = position + item.unique_id = row_value(row, 'unique_id') if use_unique_id? + + if object = build_object(row, item) + # ======= ERPmine_patch Redmine 6.0 ========== + if type == 'TimeEntryImport' + wktime_helper = Object.new.extend(WktimeHelper) + errorMsg = wktime_helper.statusValidation(object) + if errorMsg.blank? && object.save + spentForModel = wktime_helper.saveSpentFor(nil, nil, nil, object.id, object.class.name, (object.spent_on).to_date, '00', '00', nil) + item.obj_id = object.id + else + item.message = errorMsg + object.errors.full_messages.join("\n") + end + else + if object.save + item.obj_id = object.id + else + item.message = object.errors.full_messages.join("\n") + end + end + # ============================= + end + + item.save! + imported += 1 + + extend_object(row, item, object) if object.persisted? + do_callbacks(use_unique_id? ? item.unique_id : item.position, object) + end + current = position + end + + if imported == 0 || interrupted == false + if total_items.nil? + update_attribute :total_items, current + end + update_attribute :finished, true + remove_file + end + + current + end + + end + end +end \ No newline at end of file diff --git a/app/lib/send_patch/issue_patch.rb b/app/lib/send_patch/issue_patch.rb new file mode 100644 index 00000000..18dd3eb1 --- /dev/null +++ b/app/lib/send_patch/issue_patch.rb @@ -0,0 +1,17 @@ +module SendPatch::IssuePatch + def self.included(base) + base.class_eval do + + has_one :wk_issue, :dependent => :destroy, :class_name => 'WkIssue' + has_many :assignees, :dependent => :destroy, :class_name => 'WkIssueAssignee' + has_many :expense_entries, :dependent => :destroy, :class_name => 'WkExpenseEntry' + accepts_nested_attributes_for :assignees + accepts_nested_attributes_for :wk_issue + + def erpmineissues + self.wk_issue ||= WkIssue.new(:issue => self, :project => self.project) + end + + end + end +end \ No newline at end of file diff --git a/app/lib/issues_controller_patch.rb b/app/lib/send_patch/issues_controller_patch.rb similarity index 92% rename from app/lib/issues_controller_patch.rb rename to app/lib/send_patch/issues_controller_patch.rb index 4a7aaa4e..1b709d41 100644 --- a/app/lib/issues_controller_patch.rb +++ b/app/lib/send_patch/issues_controller_patch.rb @@ -1,4 +1,4 @@ -module IssuesControllerPatch +module SendPatch::IssuesControllerPatch def self.included(base) base.class_eval do @@ -10,7 +10,7 @@ def destroy time_entries = TimeEntry.where(:issue_id => issues_and_descendants_ids) @hours = time_entries.sum(:hours).to_f - # ============= ERPmine_patch Redmine 5.1 ===================== + # ============= ERPmine_patch Redmine 6.0 ===================== expense_entries = WkExpenseEntry.where(:issue_id => issues_and_descendants_ids) @amount = expense_entries.sum(:amount).to_f @@ -41,7 +41,7 @@ def destroy return else time_entries.update_all(:issue_id => nil) - # ============= ERPmine_patch Redmine 5.1 =========== + # ============= ERPmine_patch Redmine 6.0 =========== expense_entries.update_all(:issue_id => nil) material_entries.update_all(:issue_id => nil) #for material and resident entry update # ============================================== @@ -56,7 +56,7 @@ def destroy return else time_entries.update_all(:issue_id => reassign_to.id, :project_id => reassign_to.project_id) - # ============= ERPmine_patch Redmine 5.1 =========== + # ============= ERPmine_patch Redmine 6.0 =========== expense_entries.update_all(:issue_id => reassign_to.id, :project_id => reassign_to.project_id) #for material and resident entry update @@ -67,7 +67,7 @@ def destroy # display the destroy form if it's a user request return unless api_request? end - # ============= ERPmine_patch Redmine 5.1 =========== + # ============= ERPmine_patch Redmine 6.0 =========== end # ============================================== end diff --git a/app/lib/send_patch/my_controller_patch.rb b/app/lib/send_patch/my_controller_patch.rb new file mode 100644 index 00000000..6f2f8143 --- /dev/null +++ b/app/lib/send_patch/my_controller_patch.rb @@ -0,0 +1,8 @@ +# Shown users attachment in myaccount page +module SendPatch::MyControllerPatch + def self.included(base) + base.class_eval do + helper WkdocumentHelper + end + end +end \ No newline at end of file diff --git a/app/lib/send_patch/project_patch.rb b/app/lib/send_patch/project_patch.rb new file mode 100644 index 00000000..b4c842b3 --- /dev/null +++ b/app/lib/send_patch/project_patch.rb @@ -0,0 +1,15 @@ +module SendPatch::ProjectPatch + def self.included(base) + base.class_eval do + + has_many :account_projects, :dependent => :destroy, :class_name => 'WkAccountProject' + #has_many :parents, through: :account_projects + has_one :wk_project, :dependent => :destroy, :class_name => 'WkProject' + + def erpmineproject + self.wk_project ||= WkProject.new(:project => self) + end + + end + end +end \ No newline at end of file diff --git a/app/lib/send_patch/projects_controller_patch.rb b/app/lib/send_patch/projects_controller_patch.rb new file mode 100644 index 00000000..e13b6f2b --- /dev/null +++ b/app/lib/send_patch/projects_controller_patch.rb @@ -0,0 +1,106 @@ +module SendPatch::ProjectsControllerPatch + def self.included(base) + base.class_eval do + def create + @issue_custom_fields = IssueCustomField.sorted.to_a + @trackers = Tracker.sorted.to_a + @project = Project.new + @project.safe_attributes = params[:project] + + if @project.save + # ============= ERPmine_patch Redmine 6.0 ===================== + @project.erpmineproject.safe_attributes = params[:erpmineproject] + @project.erpmineproject.save + # ============================= + unless User.current.admin? + @project.add_default_member(User.current) + end + respond_to do |format| + format.html do + flash[:notice] = l(:notice_successful_create) + if params[:continue] + attrs = {:parent_id => @project.parent_id}.compact + redirect_to new_project_path(attrs) + else + redirect_to settings_project_path(@project) + end + end + format.api do + render( + :action => 'show', + :status => :created, + :location => url_for(:controller => 'projects', + :action => 'show', :id => @project.id) + ) + end + end + else + respond_to do |format| + format.html {render :action => 'new'} + format.api {render_validation_errors(@project)} + end + end + end + + def update + @project.safe_attributes = params[:project] + if @project.save + # ============= ERPmine_patch Redmine 6.0 ===================== + @project.erpmineproject.safe_attributes = params[:erpmineproject] + @project.erpmineproject.save + # ============================= + respond_to do |format| + format.html do + flash[:notice] = l(:notice_successful_update) + redirect_to settings_project_path(@project, params[:tab]) + end + format.api {render_api_ok} + end + else + respond_to do |format| + format.html do + settings + render :action => 'settings' + end + format.api {render_validation_errors(@project)} + end + end + end + + def destroy + unless @project.deletable? + deny_access + return + end + + @project_to_destroy = @project + if api_request? || params[:confirm] == @project_to_destroy.identifier + # ============= ERPmine_patch Redmine 6.0 ===================== + wktime_helper = Object.new.extend(WktimeHelper) + ret = wktime_helper.getStatus_Project_Issue(nil,@project_to_destroy.id) + if ret + #render_403 + #return false + flash.now[:error] = l(:error_project_issue_associate) + return + else + WkExpenseEntry.where(['project_id = ?', @project_to_destroy.id]).delete_all + # ============================= + DestroyProjectJob.schedule(@project_to_destroy) + flash[:notice] = l(:notice_successful_delete) + respond_to do |format| + format.html do + redirect_to( + User.current.admin? ? admin_projects_path : projects_path + ) + end + format.api {render_api_ok} + end + end + end + # hide project in layout + @project = nil + end + end + end +end \ No newline at end of file diff --git a/app/lib/queries_controller_patch.rb b/app/lib/send_patch/queries_controller_patch.rb similarity index 87% rename from app/lib/queries_controller_patch.rb rename to app/lib/send_patch/queries_controller_patch.rb index a3e3330b..8bd470d3 100644 --- a/app/lib/queries_controller_patch.rb +++ b/app/lib/send_patch/queries_controller_patch.rb @@ -1,6 +1,7 @@ -module QueriesControllerPatch +module SendPatch::QueriesControllerPatch def self.included(base) base.class_eval do + def redirect_to_wk_expense_entry_query(options) redirect_to _time_entries_path(@project, nil, options) end @@ -8,6 +9,7 @@ def redirect_to_wk_expense_entry_query(options) def redirect_to_wk_material_entry_query(options) redirect_to _time_entries_path(@project, nil, options) end + end end end \ No newline at end of file diff --git a/app/lib/send_patch/queries_helper_patch.rb b/app/lib/send_patch/queries_helper_patch.rb new file mode 100644 index 00000000..baccf3b2 --- /dev/null +++ b/app/lib/send_patch/queries_helper_patch.rb @@ -0,0 +1,94 @@ +module SendPatch::QueriesHelperPatch + def self.included(base) + base.class_eval do + + # module InstanceMethods + def column_value_with_wktime_projects(column, item, value) + case column.name + # ============= ERPmine_patch Redmine 6.0 ===================== + when :inventory_item_id + formProductItem(item) + when :selling_price + val = item.selling_price * item.quantity + value = val.blank? ? 0.00 : ("%.2f" % val) + when :resident_id + val = item.resident.name + value = val + when :resident_type + value = item.resident.location.name + when :apartment_id + value = item.apartment.blank? ? "" : item.apartment.asset_property.name + when :bed_id + value = item.bed.blank? ? "" : item.bed.asset_property.name + # ============================= + else + column_value_without_wktime_projects(column, item, value) + end + end + alias_method :column_value_without_wktime_projects, :column_value + alias_method :column_value, :column_value_with_wktime_projects + + def render_query_totals(query) + return unless query.totalable_columns.present? + + totals = query.totalable_columns.map do |column| + # ============= ERPmine_patch Redmine 6.0 ===================== + if [:quantity, :selling_price].include? column.name + product_type = session[:timelog][:spent_type] == "M" ? 'I' : session[:timelog][:spent_type] + query[:filters]['product_type'] = {"operator":"=","values" => product_type} + end + # ============================= + total_tag(column, query.total_for(column)) + end + content_tag('p', totals.join(" ").html_safe, :class => "query-totals") + end + + def query_to_csv(items, query, options={}) + columns = query.columns + + Redmine::Export::CSV.generate(encoding: params[:encoding], field_separator: params[:field_separator]) do |csv| + # csv header fields + csv << columns.map {|c| c.caption.to_s} + # csv lines + items.each do |item| + # ============= ERPmine_patch Redmine 6.0 ===================== + csv << columns.map {|c| [:inventory_item_id].include?(c.name) ? wk_csv_content(item) : csv_content(c, item)} + # ============================= + end + end + end + + # ============= ERPmine_patch Redmine 6.0 ===================== + def wk_csv_content(item) + formProductItem(item) + end + + def formProductItem(item) + brandName = item.inventory_item&.product_item&.brand.blank? ? "" : item.inventory_item&.product_item&.brand&.name + modelName = item.inventory_item&.product_item&.product_model.blank? ? "" : item.inventory_item&.product_item&.product_model&.name + serialNo = item.inventory_item&.serial_number.blank? ? "" : item.inventory_item&.serial_number&.to_s + runSerialNo = item.inventory_item&.running_sn.blank? ? "" : item.inventory_item&.running_sn&.to_s + val = item.inventory_item.product_item.product.name + product_items = "#{brandName} - #{modelName} - #{serialNo + runSerialNo}" + assetObj = item.inventory_item.asset_property + value = item&.inventory_item&.product_type == 'I' ? val+' - '+product_items : val +' - '+ assetObj.name + end + # ============================= + + # Renders the list of queries for the sidebar + def render_sidebar_queries(klass, project) + # ============= ERPmine_patch Redmine 6.0 ===================== + spent_type = session[:timelog] && session[:timelog][:spent_type] + kclassName = spent_type == "M" || spent_type == "A" ? WkMaterialEntryQuery : (spent_type == 'E' ? WkExpenseEntryQuery : klass) + queries = sidebar_queries(kclassName, project) + # ============================= + + out = ''.html_safe + out << query_links(l(:label_my_queries), queries.select(&:is_private?)) + out << query_links(l(:label_query_plural), queries.reject(&:is_private?)) + out + end + + end + end +end \ No newline at end of file diff --git a/app/lib/send_patch/time_entry_patch.rb b/app/lib/send_patch/time_entry_patch.rb new file mode 100644 index 00000000..b72621fb --- /dev/null +++ b/app/lib/send_patch/time_entry_patch.rb @@ -0,0 +1,21 @@ +module SendPatch::TimeEntryPatch + def self.included(base) + base.class_eval do + + has_one :spent_for, as: :spent, class_name: 'WkSpentFor', :dependent => :destroy + has_one :invoice_item, through: :spent_for + has_one :wkstatus, as: :status_for, class_name: "WkStatus", dependent: :destroy + has_many :attachments, -> {where(container_type: "TimeEntry")}, class_name: "Attachment", foreign_key: "container_id", dependent: :destroy + accepts_nested_attributes_for :spent_for, :attachments + + def attachments_editable?(user=User.current) + true + end + + def attachments_deletable?(user=User.current) + true + end + + end + end +end \ No newline at end of file diff --git a/app/lib/send_patch/timelog_controller_patch.rb b/app/lib/send_patch/timelog_controller_patch.rb new file mode 100644 index 00000000..3398b217 --- /dev/null +++ b/app/lib/send_patch/timelog_controller_patch.rb @@ -0,0 +1,706 @@ +module SendPatch::TimelogControllerPatch + include Redmine::Pagination + + def self.included(base) + base.class_eval do + + def index + # ============= ERPmine_patch Redmine 6.0 ===================== + set_filter_session + # ======================= + retrieve_time_entry_query + scope = time_entry_scope. + preload(:issue => [:project, :tracker, :status, :assigned_to, :priority]). + preload(:project, :user) + + # ============= ERPmine_patch Redmine 6.0 ===================== + if session[:timelog][:spent_type] === "A" || session[:timelog][:spent_type] === "M" + if session[:timelog][:spent_type] === "M" + productType = 'I' + else + productType = session[:timelog][:spent_type] + end + scope = scope.where("wk_inventory_items.product_type = '#{productType}' ") + end + hookQuery = call_hook(:time_entry_detail_where_query, :params => params) + unless hookQuery[0].blank? + scope = scope.where(hookQuery[0]) + end + # ================== + respond_to do |format| + format.html do + @entry_count = scope.count + @entry_pages = Paginator.new @entry_count, per_page_option, params['page'] + @entries = scope.offset(@entry_pages.offset).limit(@entry_pages.per_page).to_a + + render :layout => !request.xhr? + end + format.api do + @entry_count = scope.count + @offset, @limit = api_offset_and_limit + @entries = scope.offset(@offset).limit(@limit).preload(:custom_values => :custom_field).to_a + end + format.atom do + entries = scope.limit(Setting.feeds_limit.to_i).reorder("#{TimeEntry.table_name}.created_on DESC").to_a + render_feed(entries, :title => l(:label_spent_time)) + end + format.csv do + # Export all entries + entries = scope.to_a + send_data(query_to_csv(entries, @query, params), :type => 'text/csv; header=present', :filename => "#{filename_for_export(@query, 'timelog')}.csv") + end + end + end + + def report + set_filter_session + retrieve_time_entry_query + # ============= ERPmine_patch Redmine 6.0 ===================== + options = session[:timelog][:spent_type] == "T" ? {nonSpentTime: params[:non_spent_time]} : {} + scope = time_entry_scope(options) + if session[:timelog][:spent_type] === "A" || session[:timelog][:spent_type] === "M" + productType = session[:timelog][:spent_type] === "M" ? 'I' : 'A' + scope = scope.where("wk_inventory_items.product_type = '#{productType}' ") + end + hookQuery = call_hook(:time_entry_report_where_query, :params => params) + unless hookQuery[0].blank? + scope = scope.where(hookQuery[0]) + end + @report = Redmine::Helpers::TimeReport.new(@project, params[:criteria], params[:columns], scope, options) + # ================================ + + respond_to do |format| + format.html {render :layout => !request.xhr?} + format.csv do + send_data(report_to_csv(@report), :type => 'text/csv; header=present', + :filename => 'timelog.csv') + end + end + end + + def edit + # ============= ERPmine_patch Redmine 6.0 ===================== + @spentType = session[:timelog][:spent_type] + if @spentType === "T" + # ======================= + @time_entry.safe_attributes = params[:time_entry] + # ============= ERPmine_patch Redmine 6.0 ===================== + elsif @spentType === "E" + @expenseEntry = WkExpenseEntry.find(params[:id].to_i) + @time_entry.project_id = @expenseEntry.project_id + @time_entry.issue_id = @expenseEntry.issue_id + @time_entry.activity_id = @expenseEntry.activity_id + @time_entry.comments = @expenseEntry.comments + @time_entry.spent_on = @expenseEntry.spent_on + @time_entry.user_id = @expenseEntry.user_id + else + @materialEntry = WkMaterialEntry.find(params[:id].to_i) + @time_entry.project_id = @materialEntry.project_id + @time_entry.issue_id = @materialEntry.issue_id + @time_entry.activity_id = @materialEntry.activity_id + @time_entry.comments = @materialEntry.comments + @time_entry.spent_on = @materialEntry.spent_on + @time_entry.user_id = @materialEntry.user_id + end + # ======================= + end + + def retrieve_time_entry_query + # ============= ERPmine_patch Redmine 6.0 ===================== + if !session[:timelog].blank? && (session[:timelog][:spent_type] == "M" || session[:timelog][:spent_type] == "A") + retrieve_query(WkMaterialEntryQuery, false) + elsif !session[:timelog].blank? && session[:timelog][:spent_type] == "E" + retrieve_query(WkExpenseEntryQuery, false) + else + # ===================== + retrieve_query(TimeEntryQuery, false, :defaults => @default_columns_names) + # ============= ERPmine_patch Redmine 6.0 ===================== + end + hookModel = call_hook(:retrieve_time_entry_query_model, :params => params) + unless hookModel[0].blank? + retrieve_query(hookModel[0], false) + end + # ===================== + end + + def create + @time_entry ||= + TimeEntry.new(:project => @project, :issue => @issue, + :author => User.current, :user => User.current, + :spent_on => User.current.today) + # ============= ERPmine_patch Redmine 6.0 ===================== + paramEntry = getParams(params[:log_type], params) + @time_entry.safe_attributes = paramEntry + #===================== + if @time_entry.project && !User.current.allowed_to?(:log_time, @time_entry.project) + render_403 + return + end + + # ============= ERPmine_patch Redmine 6.0 ===================== + set_filter_session + model = nil + errorMsg = "" + timeErrorMsg = "" + errorMsg += l(:label_issue_error) if params[:clock_action] == "S" && paramEntry[:issue_id].blank? + wktime_helper = Object.new.extend(WktimeHelper) + if params[:log_type].blank? || params[:log_type] == 'T' + #===================== + call_hook(:controller_timelog_edit_before_save, + {:params => params, :time_entry => @time_entry}) + + # ============= ERPmine_patch Redmine 6.0 ===================== + errorMsg += wktime_helper.statusValidation(@time_entry) + unless errorMsg.blank? && @time_entry.save + timeErrorMsg = @time_entry.errors.full_messages.join("
") + end + else + errorMsg += validateMatterial(paramEntry) + if errorMsg.blank? + errorMsg += saveMatterial if params[:log_type] == 'M' || params[:log_type] == 'A' || params[:log_type] == @logType + errorMsg += saveExpense if params[:log_type] == 'E' + model = @modelEntry + end + end + if errorMsg.blank? && timeErrorMsg.blank? + model = model.blank? ? @time_entry : model + spentForModel = saveSpentFors(model) + end + #===================== + respond_to do |format| + format.html do + # ============= ERPmine_patch Redmine 6.0 ===================== + if errorMsg.blank? && timeErrorMsg.blank? + #===================== + flash[:notice] = l(:notice_successful_create) + # ============= ERPmine_patch Redmine 6.0 ===================== + if spentForModel.clock_action == "S" + redirect_to controller: 'timelog', action: 'edit', id: model.id + else + #===================== + if params[:continue] + options = { + :time_entry => { + # ============= ERPmine_patch Redmine 6.0 ===================== + :project_id => paramEntry[:project_id], + #===================== + :issue_id => @time_entry.issue_id, + :spent_on => @time_entry.spent_on, + :activity_id => @time_entry.activity_id + }, + :back_url => params[:back_url] + } + if params[:project_id] && @time_entry.project + options[:time_entry][:project_id] ||= @time_entry.project.id + redirect_to new_project_time_entry_path(@time_entry.project, options) + elsif params[:issue_id] && @time_entry.issue + redirect_to new_issue_time_entry_path(@time_entry.issue, options) + else + redirect_to new_time_entry_path(options) + end + else + redirect_back_or_default project_time_entries_path(@time_entry.project) + end + end + # ============= ERPmine_patch Redmine 6.0 ===================== + else + flash[:error] = errorMsg if errorMsg.present? + if @assetObj.present? && @assetObj.id.present? + redirect_to :controller => 'timelog',:action => 'edit' + else + render :action => 'new' + end + end + #===================== + end + format.api do + # ============= ERPmine_patch Redmine 6.0 ===================== + if errorMsg.blank? && timeErrorMsg.blank? + if params[:log_type].blank? || params[:log_type] == 'T' || params[:log_type] == 'A' + renderLog + else + render :plain => errorMsg, :layout => nil + end + else + errorMsg += timeErrorMsg if params[:log_type].blank? || params[:log_type] == 'T' + @error_messages = errorMsg.split('\n') + render :template => 'common/error_messages.api', :status => :unprocessable_entity, :layout => nil + end + #===================== + end + end + end + + # ============= ERPmine_patch Redmine 6.0 ===================== + def renderLog + data = {} + entry = params[:log_type] == 'A' ? @modelEntry : @time_entry + if(params[:log_type] == 'A') + inventoryItem = entry.inventory_item + assetObj = entry.inventory_item.asset_property + data = {log_type: 'A', id: entry.id, comments: entry.comments, spent_on: entry.spent_on, product_quantity: entry.quantity,product_sell_price: entry.selling_price, location_id: inventoryItem.location_id, rate_per: assetObj.rate_per, + product_id: inventoryItem.product_item.product.id, uom_id: entry.uom_id, product_item_id: inventoryItem.product_item_id, available_quantity: inventoryItem.available_quantity, is_done: assetObj.nil? || assetObj.matterial_entry_id.nil?, inventory_item_id: entry.inventory_item_id} + spentFor = WkMaterialEntry.find(entry.id).spent_for + else + data = {log_type: 'T', id: entry.id, hours: entry.hours, comments: entry.comments, spent_on: entry.spent_on} + spentFor = TimeEntry.find(entry.id).spent_for + end + data['project'] = {id: entry.project_id} + data['issue'] = {id: entry.issue_id} + data['activity'] = {id: entry.activity_id} + data['user'] = {id: entry.user_id} + data['spentFor'] = {id: spentFor.id, start_on: spentFor.spent_on_time, end_on: spentFor.end_on, clock_action: spentFor.clock_action} + render json: data.to_json + end + + def saveSpentFors(model) + spentForId = nil + spentFortype = nil + start_time = nil + end_time = nil + # ======Time Tracking======= + wktime_helper = Object.new.extend(WktimeHelper) + if wktime_helper.isChecked("label_enable_issue_logger") && ["T", "A"].include?(params[:log_type]) + dateTime = wktime_helper.get_current_DateTime(params[:offSet]) + start_time = params[:clock_action] == "S" && model.spent_for.blank? ? params[:start_on] && params[:start_on].to_time || dateTime : model.spent_for.spent_on_time if params[:clock_action].present? + end_time = params[:clock_action] == "E" && model.spent_for.end_on.blank? ? params[:end_on] && params[:end_on].to_time || dateTime : model.spent_for.end_on if params[:clock_action].present? && model.spent_for.present? + end + unless params[:spent_for].blank? + spentFors = params[:spent_for].split('|') + spentForVal = spentFors[1].split('_') + spentForId = spentForVal[1] + spentFortype = spentForVal[0] + end + model = wktime_helper.saveSpentFor(params[:spentForId], spentForId, spentFortype, model.id, model.class.name, model.spent_on, '00', '00', nil, start_time, end_time, params[:latitude], params[:longitude], params[:clock_action]) + end + + def validateMatterial(paramEntry) + errorMsg = "" + # if paramEntry[:project_id].blank? + # errorMsg = errorMsg + (errorMsg.blank? ? "" : "
") + l(:label_project_error) if params[:project_id].blank? + # end + if paramEntry[:issue_id].blank? + errorMsg = errorMsg + (errorMsg.blank? ? "" : "
") + l(:label_issue_error) + end + if params[:expense_amount].blank? && params[:log_type] == 'E' + errorMsg = errorMsg + (errorMsg.blank? ? "" : "
") + l(:error_expense_amount) + end + if paramEntry[:activity_id].blank? + errorMsg = errorMsg + (errorMsg.blank? ? "" : "
") + l(:label_activity_error) + end + + if params[:product_sell_price].blank? && (params[:log_type] == 'M' || params[:log_type] == 'A' || params[:log_type] == @logType) + errorMsg = errorMsg + (errorMsg.blank? ? "" : "
") + l(:label_selling_price_error) + end + if params[:product_quantity].blank? && (params[:log_type] == 'M' || params[:log_type] == 'A' || params[:log_type] == @logType) + errorMsg = errorMsg + (errorMsg.blank? ? "" : "
") + l(:label_quantity_error) + end + errorMsg + end + + def getParams(logtype, params) + hookType = call_hook(:update_time_entry_log_type, :params => params) + @logType = 'A' + unless hookType[0].blank? + @logType = hookType[0] + end + param = params[:time_entry] + param = params[:wk_expense_entry] if logtype == 'E' + param = params[:wk_material_entry] if logtype == 'M' || logtype == 'A' || params[:log_type] == @logType + param + end + # ======================== + + def update + # ============= ERPmine_patch Redmine 6.0 ===================== + paramEntry = getParams(params[:log_type], params) + @time_entry.safe_attributes = paramEntry + model = nil + errorMsg = "" + timeErrorMsg = "" + @spentType = params[:log_type].blank? ? "T" : params[:log_type] + wktime_helper = Object.new.extend(WktimeHelper) + if params[:log_type].blank? || params[:log_type] == 'T' + # ========================= + call_hook(:controller_timelog_edit_before_save, + {:params => params, :time_entry => @time_entry}) + # ============= ERPmine_patch Redmine 6.0 ===================== + if params[:clock_action] == "E" && @time_entry.spent_for.end_on.blank? + end_on = Time.now - (Time.now.utc_offset.seconds + (params[:offSet].to_i).minutes) + @time_entry.hours = ((end_on - @time_entry.spent_for.spent_on_time)/3600).round(2) + end + errorMsg += wktime_helper.statusValidation(@time_entry) + errorMsg += l(:error_issue_logger) if params[:clock_action] == "S" && @time_entry.spent_for.end_on.blank? + unless errorMsg.blank? && @time_entry.save + timeErrorMsg = @time_entry.errors.full_messages.join("
") + end + else + errorMsg = validateMatterial(paramEntry) + if errorMsg.blank? + errorMsg += saveMatterial if params[:log_type] == 'M' || params[:log_type] == 'A' || params[:log_type] == @logType + errorMsg += saveExpense if params[:log_type] == 'E' + model = @modelEntry + end + end + model = model.blank? ? @time_entry : model + if errorMsg.blank? && timeErrorMsg.blank? + spentForModel = saveSpentFors(model) + end + # ========================= + respond_to do |format| + format.html do + # ============= ERPmine_patch Redmine 6.0 ===================== + if errorMsg.blank? && timeErrorMsg.blank? + # ========================= + flash[:notice] = l(:notice_successful_update) + # ============= ERPmine_patch Redmine 6.0 ===================== + if spentForModel.clock_action == "E" && params[:commit] != "Save" + redirect_to controller: 'timelog', action: 'edit', id: model.id + else + # ========================= + redirect_back_or_default project_time_entries_path(@time_entry.project) + end + # ============= ERPmine_patch Redmine 6.0 ===================== + else + flash[:error] = (errorMsg + timeErrorMsg) + redirect_to controller: 'timelog', action: 'edit', id: model.id + end + end + format.api do + if errorMsg.blank? && timeErrorMsg.blank? + if params[:log_type].blank? || params[:log_type] == 'T' || params[:log_type] == 'A' + renderLog + else + render :plain => errorMsg, :layout => nil + end + else + errorMsg += timeErrorMsg if params[:log_type].blank? || params[:log_type] == 'T' + @error_messages = errorMsg.split('\n') + render :template => 'common/error_messages.api', :status => :unprocessable_entity, :layout => nil + # ========================= + end + end + end + end + + # ============= ERPmine_patch Redmine 6.0 ===================== + def saveMatterial + wklog_helper = Object.new.extend(WklogmaterialHelper) + wktime_helper = Object.new.extend(WktimeHelper) + setEntries(WkMaterialEntry, params[:matterial_entry_id], params[:wk_material_entry]) + selPrice = params[:product_sell_price].to_f + @modelEntry.selling_price = selPrice.blank? ? 0.00 : ("%.2f" % selPrice) + @modelEntry.uom_id = params[:uom_id] + inventoryId = "" + errorMsg = "" + if params[:clock_action] == "S" && @modelEntry.spent_for && @modelEntry.spent_for.end_on.blank? + errorMsg = l(:error_issue_logger) + else + inventoryItemObj = WkInventoryItem.find(params[:inventory_item_id].to_i) + if params[:log_type] == 'M' && !params[:inventory_item_id].blank? + inventoryObj = wklog_helper.updateParentInventoryItem(params[:inventory_item_id].to_i, params[:product_quantity].to_i, @modelEntry.quantity) + inventoryId = inventoryObj.id + currency = inventoryObj.currency + else + inventoryId = params[:inventory_item_id] + currency = Setting.plugin_redmine_wktime['wktime_currency'] + end + if inventoryId.blank? + errorMsg += l(:error_item_not_available) + elsif params[:product_quantity].to_i > inventoryItemObj.available_quantity.to_i + errorMsg += l(:error_product_qty_greater_avail_qty) + else + if params[:log_type] == "A" && params[:clock_action] == "S" && @modelEntry.spent_for.blank? + quantity = "0.1" + elsif params[:log_type] == "A" && params[:clock_action] == "E" && @modelEntry.spent_for.present? && @modelEntry.spent_for.end_on.blank? + quantity = wktime_helper.getAssetQuantity(@modelEntry.spent_for.spent_on_time, wktime_helper.get_current_DateTime(params[:offSet]), params[:inventory_item_id]) + else + quantity = params[:product_quantity] + end + @modelEntry.inventory_item_id = inventoryId.to_i + @modelEntry.quantity = quantity + @modelEntry.currency = currency + unless @modelEntry.valid? + errorMsg = @modelEntry.errors.full_messages.join("
") + else + @modelEntry.save + end + if params[:log_type] == 'A' || params[:log_type] == @logType + inventoryObj = WkInventoryItem.find(inventoryId.to_i) + @assetObj = inventoryObj.asset_property + if params[:matterial_entry_id].blank? ||(params[:is_done].blank? || params[:is_done] == "0") + @assetObj.matterial_entry_id = @modelEntry.id + else + @assetObj.matterial_entry_id = nil + end + @assetObj.save + end + # save serial number + wklog_helper.saveConsumedSN(JSON.parse(params[:hidden_sns]), @modelEntry) if errorMsg.blank? && params[:hidden_sns].present? + end + end + return errorMsg + end + + def setEntries(model, id, params={}) + if id.blank? + @modelEntry = model.new + else + @modelEntry = model.find(id.to_i) + end + projectId = Issue.find(params[:issue_id].to_i).project_id + @modelEntry.project_id = projectId + @modelEntry.user_id = params[:user_id].blank? ? User.current.id : params[:user_id].to_i + @modelEntry.issue_id = params[:issue_id].to_i + @modelEntry.comments = params[:comments] + @modelEntry.activity_id = params[:activity_id].to_i + @modelEntry.spent_on = params[:spent_on] + end + + def saveExpense + errorMsg = "" + setEntries(WkExpenseEntry, params[:expense_entry_id], params[:wk_expense_entry]) + @modelEntry.amount = params[:expense_amount] + @modelEntry.currency = params[:wktime_currency] + unless @modelEntry.valid? + errorMsg = @modelEntry.errors.full_messages.join("
") + else + @modelEntry.save + end + return errorMsg + end + + def set_filter_session + if params[:spent_type].blank? && params[:log_type].blank? + session[:timelog] = {:spent_type => "T"} if session[:timelog].blank? || session[:timelog][:spent_type].blank? + else + session[:timelog] = {} if session[:timelog].blank? + session[:timelog][:spent_type] = params[:log_type].blank? ? params[:spent_type] : params[:log_type] + session[:timelog][:show_on_map] = params[:show_on_map] + end + end + # ======================================= + + def find_time_entries + # ============= ERPmine_patch Redmine 6.0 ===================== + set_filter_session + if session[:timelog][:spent_type] === "T" + # ========================================== + @time_entries = TimeEntry.where(:id => params[:id] || params[:ids]). + preload(:project => :time_entry_activities). + preload(:user).to_a + raise Unauthorized unless @time_entries.all? {|t| t.editable_by?(User.current)} + # ============= ERPmine_patch Redmine 6.0 ===================== + elsif session[:timelog][:spent_type] === "E" + @time_entries = WkExpenseEntry.where(:id => params[:id] || params[:ids]) + else + @time_entries = WkMaterialEntry.where(:id => params[:id] || params[:ids]) + raise ActiveRecord::RecordNotFound if @time_entries.empty? + # =================================== + @projects = @time_entries.filter_map(&:project).uniq + end + @project = @projects.first if @projects.size == 1 + rescue ActiveRecord::RecordNotFound + render_404 + end + + def find_time_entry + # ============= ERPmine_patch Redmine 6.0 ===================== + set_filter_session + if session[:timelog][:spent_type] === "T" + # ======================== + @time_entry = TimeEntry.find(params[:id]) + # ============= ERPmine_patch Redmine 6.0 ===================== + elsif session[:timelog][:spent_type] === "E" + @time_entry = WkExpenseEntry.find(params[:id]) + else + @time_entry = WkMaterialEntry.find(params[:id]) + end + # ============================================== + @project = @time_entry.project + rescue ActiveRecord::RecordNotFound + render_404 + end + + def check_editability + # ============= ERPmine_patch Redmine 6.0 ===================== + wktime_helper = Object.new.extend(WktimeHelper) + set_filter_session + if session[:timelog][:spent_type] === "T" + # ============================= + unless @time_entry.editable_by?(User.current) + render_403 + return false + end + # ============= ERPmine_patch Redmine 6.0 ===================== + elsif session[:timelog][:spent_type] === "E" + return true + else + return wktime_helper.showInventory + end + # ============================= + end + + def bulk_edit + # ============= ERPmine_patch Redmine 6.0 ===================== + if session[:timelog][:spent_type] == "T" + # ============================= + @target_projects = Project.allowed_to(:log_time).to_a + @custom_fields = TimeEntry.first.available_custom_fields.select {|field| field.format.bulk_edit_supported} + if params[:time_entry] + @target_project = @target_projects.detect {|p| p.id.to_s == params[:time_entry][:project_id].to_s} + end + if @target_project + @available_activities = @target_project.activities + else + @available_activities = @projects.map(&:activities).reduce(:&) + end + # ============= ERPmine_patch Redmine 6.0 ===================== + else + render_404 + end + # ============================= + @time_entry_params = params[:time_entry] || {} + @time_entry_params[:custom_field_values] ||= {} + end + + def bulk_update + attributes = parse_params_for_bulk_update(params[:time_entry]) + + unsaved_time_entries = [] + saved_time_entries = [] + + @time_entries.each do |time_entry| + time_entry.reload + time_entry.safe_attributes = attributes + call_hook( + :controller_time_entries_bulk_edit_before_save, + {:params => params, :time_entry => time_entry} + ) + # ============= ERPmine_patch Redmine 6.0 ===================== + wktime_helper = Object.new.extend(WktimeHelper) + errorMsg = wktime_helper.statusValidation(time_entry) + if errorMsg.blank? && time_entry.save + # ============================= + saved_time_entries << time_entry + else + unsaved_time_entries << time_entry + end + end + + if unsaved_time_entries.empty? + flash[:notice] = l(:notice_successful_update) unless saved_time_entries.empty? + redirect_back_or_default project_time_entries_path(@projects.first) + else + @saved_time_entries = @time_entries + @unsaved_time_entries = unsaved_time_entries + @time_entries = TimeEntry.where(:id => unsaved_time_entries.map(&:id)). + preload(:project => :time_entry_activities). + preload(:user).to_a + + bulk_edit + render :action => 'bulk_edit' + end + end + + def destroy + # ============= ERPmine_patch Redmine 6.0 ===================== + wktime_helper = Object.new.extend(WktimeHelper) + errMsg = "" + if session[:timelog][:spent_type] === "T" + # ============================ + destroyed = TimeEntry.transaction do + @time_entries.each do |t| + # ============= ERPmine_patch Redmine 6.0 ===================== + status = wktime_helper.getTimeEntryStatus(t.spent_on, t.user_id) + if !status.blank? && ('a' == status || 's' == status || 'l' == status) + errMsg = "#{l(:error_time_entry_delete)}" + raise ActiveRecord::Rollback + end + if errMsg.blank? + # =========================== + unless t.destroy && t.destroyed? + # ============= ERPmine_patch Redmine 6.0 ===================== + errMsg = l(:notice_unable_delete_time_entry) + # ============================ + raise ActiveRecord::Rollback + end + end + end + # ============= ERPmine_patch Redmine 6.0 ===================== + end + elsif session[:timelog][:spent_type] === "E" + destroyed = WkExpenseEntry.transaction do + @time_entries.each do |e| + status = wktime_helper.getExpenseEntryStatus(e.spent_on, e.user_id) + errMsg = "#{l(:error_expense_delete)}" if !status.blank? && ('a' == status || 's' == status || 'l' == status) + raise ActiveRecord::Rollback unless errMsg.blank? && e.destroy && e.destroyed? + end + end + else + if wktime_helper.validateERPPermission("D_INV") + destroyed = WkMaterialEntry.transaction do + begin + if @time_entries.spent_for.blank? || @time_entries.spent_for.invoice_item_id.blank? + if session[:timelog][:spent_type] === "M" + inventoryItemObj = WkInventoryItem.find(@time_entries.inventory_item_id) + inventoryItemObj.available_quantity = inventoryItemObj.available_quantity + @time_entries.quantity + inventoryItemObj.save + end + @time_entries.destroy + else + errMsg = l(:error_material_delete_billed) + logger.error ex.message + raise ActiveRecord::Rollback + end + rescue => ex + errMsg = l(:error_material_delete) + logger.error ex.message + raise ActiveRecord::Rollback + end + end + destroyed = WkMaterialEntry.transaction do + @time_entries.each do |m| + if m.spent_for.blank? || m.spent_for.invoice_item_id.blank? + if session[:timelog][:spent_type] === "M" + inventoryItemObj = WkInventoryItem.find(m.inventory_item_id) + inventoryItemObj.available_quantity = inventoryItemObj.available_quantity + m.quantity + inventoryItemObj.save + end + raise ActiveRecord::Rollback unless m.destroy && m.destroyed? + else + errMsg = l(:error_material_delete_billed) + raise ActiveRecord::Rollback + end + end + end + else + render_403 + return false + end + end + # ========================================== + respond_to do |format| + format.html do + if destroyed + flash[:notice] = l(:notice_successful_delete) + else + # ============= ERPmine_patch Redmine 6.0 ===================== + flash[:error] = errMsg || l(:notice_unable_delete_time_entry) + # ========================================== + end + redirect_back_or_default project_time_entries_path(@projects.first), :referer => true + end + format.api do + if destroyed + render_api_ok + else + render_validation_errors(@time_entries) + end + end + end + end + + end + end +end diff --git a/app/lib/send_patch/timelog_helper_patch.rb b/app/lib/send_patch/timelog_helper_patch.rb new file mode 100644 index 00000000..a2502e29 --- /dev/null +++ b/app/lib/send_patch/timelog_helper_patch.rb @@ -0,0 +1,156 @@ +module SendPatch::TimelogHelperPatch + def self.included(base) + base.class_eval do + + def format_criteria_value(criteria_options, value, html=true) + if value.blank? + "[#{l(:label_none)}]" + elsif k = criteria_options[:klass] + obj = k.find_by_id(value.to_i) + if obj.is_a?(Issue) + if obj.visible? + html ? link_to_issue(obj) : "#{obj.tracker} ##{obj.id}: #{obj.subject}" + else + "##{obj.id}" + end + # ============= ERPmine_patch Redmine 6.0 ===================== + elsif obj.is_a?(WkInventoryItem) + brandName = obj.product_item.brand.blank? ? "" : obj.product_item.brand.name + modelName = obj.product_item.product_model.blank? ? "" : obj.product_item.product_model.name + str = "#{obj.product_item.product.name} - #{brandName} - #{modelName}" + assetObj = obj.asset_property + str = str + " - " +assetObj.name if obj&.product_type != 'I' + str + # ======================== + else + format_object(obj, html: html) + end + elsif cf = criteria_options[:custom_field] + format_value(value, cf) + else + value.to_s + end + end + + def report_to_csv(report) + Redmine::Export::CSV.generate(:encoding => params[:encoding]) do |csv| + # Column headers + # ============= ERPmine_patch Redmine 6.0 ===================== + @showEstimate = session[:timelog][:spent_type] == "T" ? true : false + # ======================== + headers = + report.criteria.collect do |criteria| + l_or_humanize(report.available_criteria[criteria][:label]) + end + headers += report.periods + headers << l(:label_total_time) + # ============= ERPmine_patch Redmine 6.0 ===================== + headers << l(:field_total_estimated_hours) if @showEstimate + # ======================== + csv << headers + # Content + report_criteria_to_csv(csv, report.available_criteria, report.columns, + report.criteria, report.periods, report.hours) + # Total row + str_total = l(:label_total_time) + row = [str_total] + [''] * (report.criteria.size - 1) + total = 0 + report.periods.each do |period| + sum = sum_hours(select_hours(report.hours, report.columns, period.to_s)) + total += sum + row << (sum > 0 ? sum : '') + end + row << total + # ============= ERPmine_patch Redmine 6.0 ===================== + row << @estimatedTotal if @showEstimate + # ======================== + csv << row + end + end + + # ============= ERPmine_patch Redmine 6.0 ===================== + + def report_criteria_to_csv(csv, available_criteria, columns, criteria, periods, hours, level=0, filters = {}) + # ================================== + hours.collect {|h| h[criteria[level]].to_s}.uniq.each do |value| + hours_for_value = select_hours(hours, criteria[level], value) + # ============= ERPmine_patch Redmine 6.0 ===================== + filters.each{|key, value| filters.except!(value) if level < key.to_i} + criteriaLevel = criteria[level].include?("cf_") ? "cf" : criteria[level] + filters[level] = criteriaLevel + filters[criteriaLevel] = criteria[level].include?("cf_") ? [ criteria[level].split('_').last, value ] : value + # ================================== + next if hours_for_value.empty? + + row = [''] * level + row << format_criteria_value(available_criteria[criteria[level]], value, false).to_s + row += [''] * (criteria.length - level - 1) + total = 0 + periods.each do |period| + sum = sum_hours(select_hours(hours_for_value, columns, period.to_s)) + total += sum + row << (sum > 0 ? sum : '') + end + row << total + # ============= ERPmine_patch Redmine 6.0 ===================== + estimatedHours = estimated_hours(filters, criteria[level]) + @estimatedTotal ||= 0 + @estimatedTotal += estimatedHours if level == 0 + row << estimatedHours if @showEstimate + # ================================== + csv << row + if criteria.length > level + 1 + report_criteria_to_csv(csv, available_criteria, columns, criteria, periods, hours_for_value, level + 1, filters) + end + end + end + + # ============= ERPmine_patch Redmine 6.0 ===================== + def estimated_hours(filters, criteria) + cf_id = nil + filters.each{|k, v| cf_id = v.first if k == "cf" } + customField = criteria.include?("cf_") || cf_id.present? ? CustomField.find(cf_id || criteria.split('_').last) : nil + if ["project", "issue", "category", "status", "version", "tracker", "user"].include?(criteria) || customField && customField.type == "IssueCustomField" + query = Issue.reorder(nil) + query = query.where("project_id = ?", @project.id) if @project.present? + filters.each do |key, value| + case key + when "project" + query = get_clause(query, value, "issues.project_id") + when "issue" + query = get_clause(query, value, "issues.id") + when "status" + query = get_clause(query, value, "issues.status_id") + when "version" + query = get_clause(query, value, "issues.fixed_version_id") + when "tracker" + query = get_clause(query, value, "issues.tracker_id") + when "category" + query = get_clause(query, value, "issues.category_id") + when "user" + query = get_clause(query, value, "issues.assigned_to_id") + when "cf" + if value.last.present? && customField + query = query.joins(:custom_values).where({ "custom_values.customized_type": "Issue", "custom_values.custom_field_id": customField.id, "custom_values.value": value }) + else + query = query.joins("LEFT JOIN ( + SELECT customized_id AS id FROM custom_values + WHERE customized_type = 'Issue' AND (value != '') + GROUP BY customized_id + ) AS CV ON CV.id = issues.id").where("CV.id IS NULL") + end + end + end + sum = query.sum(:estimated_hours) + end + sum || 0 + end + + def get_clause(query, filter, column) + condition = filter.present? ? ((filter.split(",")).include?("null") ? "#{column} IN (#{filter}) OR #{column} IS NULL" : "#{column} IN (#{filter})") : "#{column} IS NULL" + query = query.where(condition) + end + # ================================== + end + end +end \ No newline at end of file diff --git a/app/lib/send_patch/user_patch.rb b/app/lib/send_patch/user_patch.rb new file mode 100644 index 00000000..d03aa36c --- /dev/null +++ b/app/lib/send_patch/user_patch.rb @@ -0,0 +1,22 @@ +module SendPatch::UserPatch + def self.included(base) + base.class_eval do + + include LoadPatch::UserNestedSet + has_one :wk_user, :dependent => :destroy, :class_name => 'WkUser' + has_many :shift_schdules, :dependent => :destroy, :class_name => 'WkShiftSchedule' + belongs_to :supervisor, :class_name => 'User', :foreign_key => 'parent_id' + has_one :address, through: :wk_user + + safe_attributes 'parent_id', 'lft', 'rgt' + acts_as_attachable :view_permission => :view_files, + :edit_permission => :manage_files, + :delete_permission => :manage_files + + def erpmineuser + self.wk_user ||= WkUser.new(:user => self) + end + + end + end +end \ No newline at end of file diff --git a/app/lib/users_controller_patch.rb b/app/lib/send_patch/users_controller_patch.rb similarity index 95% rename from app/lib/users_controller_patch.rb rename to app/lib/send_patch/users_controller_patch.rb index 9795743a..5fa0b782 100644 --- a/app/lib/users_controller_patch.rb +++ b/app/lib/send_patch/users_controller_patch.rb @@ -1,6 +1,7 @@ -module UsersControllerPatch +module SendPatch::UsersControllerPatch def self.included(base) base.class_eval do + helper :attachments helper WkdocumentHelper include WkdocumentHelper @@ -19,7 +20,7 @@ def create if @user.save Mailer.deliver_account_information(@user, @user.password) if params[:send_information] - # ============= ERPmine_patch Redmine 5.1 ===================== + # ============= ERPmine_patch Redmine 6.0 ===================== #Below code for save wk users erpmineUserSave # To transfer attachments from Referral @@ -77,7 +78,7 @@ def update @user.pref.save Mailer.deliver_password_updated(@user, User.current) if is_updating_password - # ============= ERPmine_patch Redmine 5.1 ===================== + # ============= ERPmine_patch Redmine 6.0 ===================== #Below code for save wk users erpmineUserSave #for attachment save @@ -109,7 +110,7 @@ def update end end - # ============= ERPmine_patch Redmine 5.1 ===================== + # ============= ERPmine_patch Redmine 6.0 ===================== def erpmineUserSave @user.erpmineuser.safe_attributes = params[:erpmineuser] @user.erpmineuser.address_id = updateAddress diff --git a/app/lib/timelog_controller_patch.rb b/app/lib/timelog_controller_patch.rb deleted file mode 100644 index 3b90fd67..00000000 --- a/app/lib/timelog_controller_patch.rb +++ /dev/null @@ -1,706 +0,0 @@ -module TimelogControllerPatch - include Redmine::Pagination - - def self.included(base) - base.class_eval do - - def index - # ============= ERPmine_patch Redmine 5.1 ===================== - set_filter_session - # ======================= - retrieve_time_entry_query - scope = time_entry_scope. - preload(:issue => [:project, :tracker, :status, :assigned_to, :priority]). - preload(:project, :user) - - # ============= ERPmine_patch Redmine 5.1 ===================== - if session[:timelog][:spent_type] === "A" || session[:timelog][:spent_type] === "M" - if session[:timelog][:spent_type] === "M" - productType = 'I' - else - productType = session[:timelog][:spent_type] - end - scope = scope.where("wk_inventory_items.product_type = '#{productType}' ") - end - hookQuery = call_hook(:time_entry_detail_where_query, :params => params) - unless hookQuery[0].blank? - scope = scope.where(hookQuery[0]) - end - # ================== - respond_to do |format| - format.html do - @entry_count = scope.count - @entry_pages = Paginator.new @entry_count, per_page_option, params['page'] - @entries = scope.offset(@entry_pages.offset).limit(@entry_pages.per_page).to_a - - render :layout => !request.xhr? - end - format.api do - @entry_count = scope.count - @offset, @limit = api_offset_and_limit - @entries = scope.offset(@offset).limit(@limit).preload(:custom_values => :custom_field).to_a - end - format.atom do - entries = scope.limit(Setting.feeds_limit.to_i).reorder("#{TimeEntry.table_name}.created_on DESC").to_a - render_feed(entries, :title => l(:label_spent_time)) - end - format.csv do - # Export all entries - @entries = scope.to_a - send_data(query_to_csv(@entries, @query, params), :type => 'text/csv; header=present', :filename => "#{filename_for_export(@query, 'timelog')}.csv") - end - end - end - - def report - set_filter_session - retrieve_time_entry_query - # ============= ERPmine_patch Redmine 5.1 ===================== - options = session[:timelog][:spent_type] == "T" ? {nonSpentTime: params[:non_spent_time]} : {} - scope = time_entry_scope(options) - if session[:timelog][:spent_type] === "A" || session[:timelog][:spent_type] === "M" - productType = session[:timelog][:spent_type] === "M" ? 'I' : 'A' - scope = scope.where("wk_inventory_items.product_type = '#{productType}' ") - end - hookQuery = call_hook(:time_entry_report_where_query, :params => params) - unless hookQuery[0].blank? - scope = scope.where(hookQuery[0]) - end - @report = Redmine::Helpers::TimeReport.new(@project, params[:criteria], params[:columns], scope, options) - # ================================ - - respond_to do |format| - format.html {render :layout => !request.xhr?} - format.csv do - send_data(report_to_csv(@report), :type => 'text/csv; header=present', - :filename => 'timelog.csv') - end - end - end - - def edit - # ============= ERPmine_patch Redmine 5.1 ===================== - @spentType = session[:timelog][:spent_type] - if @spentType === "T" - # ======================= - @time_entry.safe_attributes = params[:time_entry] - # ============= ERPmine_patch Redmine 5.1 ===================== - elsif @spentType === "E" - @expenseEntry = WkExpenseEntry.find(params[:id].to_i) - @time_entry.project_id = @expenseEntry.project_id - @time_entry.issue_id = @expenseEntry.issue_id - @time_entry.activity_id = @expenseEntry.activity_id - @time_entry.comments = @expenseEntry.comments - @time_entry.spent_on = @expenseEntry.spent_on - @time_entry.user_id = @expenseEntry.user_id - else - @materialEntry = WkMaterialEntry.find(params[:id].to_i) - @time_entry.project_id = @materialEntry.project_id - @time_entry.issue_id = @materialEntry.issue_id - @time_entry.activity_id = @materialEntry.activity_id - @time_entry.comments = @materialEntry.comments - @time_entry.spent_on = @materialEntry.spent_on - @time_entry.user_id = @materialEntry.user_id - end - # ======================= - end - - def retrieve_time_entry_query - # ============= ERPmine_patch Redmine 5.1 ===================== - if !session[:timelog].blank? && (session[:timelog][:spent_type] == "M" || session[:timelog][:spent_type] == "A") - retrieve_query(WkMaterialEntryQuery, false) - elsif !session[:timelog].blank? && session[:timelog][:spent_type] == "E" - retrieve_query(WkExpenseEntryQuery, false) - else - # ===================== - retrieve_query(TimeEntryQuery, false, :defaults => @default_columns_names) - # ============= ERPmine_patch Redmine 5.1 ===================== - end - hookModel = call_hook(:retrieve_time_entry_query_model, :params => params) - unless hookModel[0].blank? - retrieve_query(hookModel[0], false) - end - # ===================== - end - - def create - @time_entry ||= - TimeEntry.new(:project => @project, :issue => @issue, - :author => User.current, :user => User.current, - :spent_on => User.current.today) - # ============= ERPmine_patch Redmine 5.1 ===================== - paramEntry = getParams(params[:log_type], params) - @time_entry.safe_attributes = paramEntry - #===================== - if @time_entry.project && !User.current.allowed_to?(:log_time, @time_entry.project) - render_403 - return - end - - # ============= ERPmine_patch Redmine 5.1 ===================== - set_filter_session - model = nil - errorMsg = "" - timeErrorMsg = "" - errorMsg += l(:label_issue_error) if params[:clock_action] == "S" && paramEntry[:issue_id].blank? - wktime_helper = Object.new.extend(WktimeHelper) - if params[:log_type].blank? || params[:log_type] == 'T' - #===================== - call_hook(:controller_timelog_edit_before_save, - {:params => params, :time_entry => @time_entry}) - - # ============= ERPmine_patch Redmine 5.1 ===================== - errorMsg += wktime_helper.statusValidation(@time_entry) - unless errorMsg.blank? && @time_entry.save - timeErrorMsg = @time_entry.errors.full_messages.join("
") - end - else - errorMsg += validateMatterial(paramEntry) - if errorMsg.blank? - errorMsg += saveMatterial if params[:log_type] == 'M' || params[:log_type] == 'A' || params[:log_type] == @logType - errorMsg += saveExpense if params[:log_type] == 'E' - model = @modelEntry - end - end - if errorMsg.blank? && timeErrorMsg.blank? - model = model.blank? ? @time_entry : model - spentForModel = saveSpentFors(model) - end - #===================== - respond_to do |format| - format.html do - # ============= ERPmine_patch Redmine 5.1 ===================== - if errorMsg.blank? && timeErrorMsg.blank? - #===================== - flash[:notice] = l(:notice_successful_create) - # ============= ERPmine_patch Redmine 5.1 ===================== - if spentForModel.clock_action == "S" - redirect_to controller: 'timelog', action: 'edit', id: model.id - else - #===================== - if params[:continue] - options = { - :time_entry => { - # ============= ERPmine_patch Redmine 5.1 ===================== - :project_id => paramEntry[:project_id], - #===================== - :issue_id => @time_entry.issue_id, - :spent_on => @time_entry.spent_on, - :activity_id => @time_entry.activity_id - }, - :back_url => params[:back_url] - } - if params[:project_id] && @time_entry.project - options[:time_entry][:project_id] ||= @time_entry.project.id - redirect_to new_project_time_entry_path(@time_entry.project, options) - elsif params[:issue_id] && @time_entry.issue - redirect_to new_issue_time_entry_path(@time_entry.issue, options) - else - redirect_to new_time_entry_path(options) - end - else - redirect_back_or_default project_time_entries_path(@time_entry.project) - end - end - # ============= ERPmine_patch Redmine 5.1 ===================== - else - flash[:error] = errorMsg if errorMsg.present? - if @assetObj.present? && @assetObj.id.present? - redirect_to :controller => 'timelog',:action => 'edit' - else - render :action => 'new' - end - end - #===================== - end - format.api do - # ============= ERPmine_patch Redmine 5.1 ===================== - if errorMsg.blank? && timeErrorMsg.blank? - if params[:log_type].blank? || params[:log_type] == 'T' || params[:log_type] == 'A' - renderLog - else - render :plain => errorMsg, :layout => nil - end - else - errorMsg += timeErrorMsg if params[:log_type].blank? || params[:log_type] == 'T' - @error_messages = errorMsg.split('\n') - render :template => 'common/error_messages.api', :status => :unprocessable_entity, :layout => nil - end - #===================== - end - end - end - - # ============= ERPmine_patch Redmine 5.1 ===================== - def renderLog - data = {} - entry = params[:log_type] == 'A' ? @modelEntry : @time_entry - if(params[:log_type] == 'A') - inventoryItem = entry.inventory_item - assetObj = entry.inventory_item.asset_property - data = {log_type: 'A', id: entry.id, comments: entry.comments, spent_on: entry.spent_on, product_quantity: entry.quantity,product_sell_price: entry.selling_price, location_id: inventoryItem.location_id, rate_per: assetObj.rate_per, - product_id: inventoryItem.product_item.product.id, uom_id: entry.uom_id, product_item_id: inventoryItem.product_item_id, available_quantity: inventoryItem.available_quantity, is_done: assetObj.nil? || assetObj.matterial_entry_id.nil?, inventory_item_id: entry.inventory_item_id} - spentFor = WkMaterialEntry.find(entry.id).spent_for - else - data = {log_type: 'T', id: entry.id, hours: entry.hours, comments: entry.comments, spent_on: entry.spent_on} - spentFor = TimeEntry.find(entry.id).spent_for - end - data['project'] = {id: entry.project_id} - data['issue'] = {id: entry.issue_id} - data['activity'] = {id: entry.activity_id} - data['user'] = {id: entry.user_id} - data['spentFor'] = {id: spentFor.id, start_on: spentFor.spent_on_time, end_on: spentFor.end_on, clock_action: spentFor.clock_action} - render json: data.to_json - end - - def saveSpentFors(model) - spentForId = nil - spentFortype = nil - start_time = nil - end_time = nil - # ======Time Tracking======= - wktime_helper = Object.new.extend(WktimeHelper) - if wktime_helper.isChecked("label_enable_issue_logger") && ["T", "A"].include?(params[:log_type]) - dateTime = wktime_helper.get_current_DateTime(params[:offSet]) - start_time = params[:clock_action] == "S" && model.spent_for.blank? ? params[:start_on] && params[:start_on].to_time || dateTime : model.spent_for.spent_on_time if params[:clock_action].present? - end_time = params[:clock_action] == "E" && model.spent_for.end_on.blank? ? params[:end_on] && params[:end_on].to_time || dateTime : model.spent_for.end_on if params[:clock_action].present? && model.spent_for.present? - end - unless params[:spent_for].blank? - spentFors = params[:spent_for].split('|') - spentForVal = spentFors[1].split('_') - spentForId = spentForVal[1] - spentFortype = spentForVal[0] - end - model = wktime_helper.saveSpentFor(params[:spentForId], spentForId, spentFortype, model.id, model.class.name, model.spent_on, '00', '00', nil, start_time, end_time, params[:latitude], params[:longitude], params[:clock_action]) - end - - def validateMatterial(paramEntry) - errorMsg = "" - # if paramEntry[:project_id].blank? - # errorMsg = errorMsg + (errorMsg.blank? ? "" : "
") + l(:label_project_error) if params[:project_id].blank? - # end - if paramEntry[:issue_id].blank? - errorMsg = errorMsg + (errorMsg.blank? ? "" : "
") + l(:label_issue_error) - end - if params[:expense_amount].blank? && params[:log_type] == 'E' - errorMsg = errorMsg + (errorMsg.blank? ? "" : "
") + l(:error_expense_amount) - end - if paramEntry[:activity_id].blank? - errorMsg = errorMsg + (errorMsg.blank? ? "" : "
") + l(:label_activity_error) - end - - if params[:product_sell_price].blank? && (params[:log_type] == 'M' || params[:log_type] == 'A' || params[:log_type] == @logType) - errorMsg = errorMsg + (errorMsg.blank? ? "" : "
") + l(:label_selling_price_error) - end - if params[:product_quantity].blank? && (params[:log_type] == 'M' || params[:log_type] == 'A' || params[:log_type] == @logType) - errorMsg = errorMsg + (errorMsg.blank? ? "" : "
") + l(:label_quantity_error) - end - errorMsg - end - - def getParams(logtype, params) - hookType = call_hook(:update_time_entry_log_type, :params => params) - @logType = 'A' - unless hookType[0].blank? - @logType = hookType[0] - end - param = params[:time_entry] - param = params[:wk_expense_entry] if logtype == 'E' - param = params[:wk_material_entry] if logtype == 'M' || logtype == 'A' || params[:log_type] == @logType - param - end - # ======================== - - def update - # ============= ERPmine_patch Redmine 5.1 ===================== - paramEntry = getParams(params[:log_type], params) - @time_entry.safe_attributes = paramEntry - model = nil - errorMsg = "" - timeErrorMsg = "" - @spentType = params[:log_type].blank? ? "T" : params[:log_type] - wktime_helper = Object.new.extend(WktimeHelper) - if params[:log_type].blank? || params[:log_type] == 'T' - # ========================= - call_hook(:controller_timelog_edit_before_save, - {:params => params, :time_entry => @time_entry}) - # ============= ERPmine_patch Redmine 5.1 ===================== - if params[:clock_action] == "E" && @time_entry.spent_for.end_on.blank? - end_on = Time.now - (Time.now.utc_offset.seconds + (params[:offSet].to_i).minutes) - @time_entry.hours = ((end_on - @time_entry.spent_for.spent_on_time)/3600).round(2) - end - errorMsg += wktime_helper.statusValidation(@time_entry) - errorMsg += l(:error_issue_logger) if params[:clock_action] == "S" && @time_entry.spent_for.end_on.blank? - unless errorMsg.blank? && @time_entry.save - timeErrorMsg = @time_entry.errors.full_messages.join("
") - end - else - errorMsg = validateMatterial(paramEntry) - if errorMsg.blank? - errorMsg += saveMatterial if params[:log_type] == 'M' || params[:log_type] == 'A' || params[:log_type] == @logType - errorMsg += saveExpense if params[:log_type] == 'E' - model = @modelEntry - end - end - model = model.blank? ? @time_entry : model - if errorMsg.blank? && timeErrorMsg.blank? - spentForModel = saveSpentFors(model) - end - # ========================= - respond_to do |format| - format.html do - # ============= ERPmine_patch Redmine 5.1 ===================== - if errorMsg.blank? && timeErrorMsg.blank? - # ========================= - flash[:notice] = l(:notice_successful_update) - # ============= ERPmine_patch Redmine 5.1 ===================== - if spentForModel.clock_action == "E" && params[:commit] != "Save" - redirect_to controller: 'timelog', action: 'edit', id: model.id - else - # ========================= - redirect_back_or_default project_time_entries_path(@time_entry.project) - end - # ============= ERPmine_patch Redmine 5.1 ===================== - else - flash[:error] = (errorMsg + timeErrorMsg) - redirect_to controller: 'timelog', action: 'edit', id: model.id - end - end - format.api do - if errorMsg.blank? && timeErrorMsg.blank? - if params[:log_type].blank? || params[:log_type] == 'T' || params[:log_type] == 'A' - renderLog - else - render :plain => errorMsg, :layout => nil - end - else - errorMsg += timeErrorMsg if params[:log_type].blank? || params[:log_type] == 'T' - @error_messages = errorMsg.split('\n') - render :template => 'common/error_messages.api', :status => :unprocessable_entity, :layout => nil - # ========================= - end - end - end - end - - # ============= ERPmine_patch Redmine 5.1 ===================== - def saveMatterial - wklog_helper = Object.new.extend(WklogmaterialHelper) - wktime_helper = Object.new.extend(WktimeHelper) - setEntries(WkMaterialEntry, params[:matterial_entry_id], params[:wk_material_entry]) - selPrice = params[:product_sell_price].to_f - @modelEntry.selling_price = selPrice.blank? ? 0.00 : ("%.2f" % selPrice) - @modelEntry.uom_id = params[:uom_id] - inventoryId = "" - errorMsg = "" - if params[:clock_action] == "S" && @modelEntry.spent_for && @modelEntry.spent_for.end_on.blank? - errorMsg = l(:error_issue_logger) - else - inventoryItemObj = WkInventoryItem.find(params[:inventory_item_id].to_i) - if params[:log_type] == 'M' && !params[:inventory_item_id].blank? - inventoryObj = wklog_helper.updateParentInventoryItem(params[:inventory_item_id].to_i, params[:product_quantity].to_i, @modelEntry.quantity) - inventoryId = inventoryObj.id - currency = inventoryObj.currency - else - inventoryId = params[:inventory_item_id] - currency = Setting.plugin_redmine_wktime['wktime_currency'] - end - if inventoryId.blank? - errorMsg += l(:error_item_not_available) - elsif params[:product_quantity].to_i > inventoryItemObj.available_quantity.to_i - errorMsg += l(:error_product_qty_greater_avail_qty) - else - if params[:log_type] == "A" && params[:clock_action] == "S" && @modelEntry.spent_for.blank? - quantity = "0.1" - elsif params[:log_type] == "A" && params[:clock_action] == "E" && @modelEntry.spent_for.present? && @modelEntry.spent_for.end_on.blank? - quantity = wktime_helper.getAssetQuantity(@modelEntry.spent_for.spent_on_time, wktime_helper.get_current_DateTime(params[:offSet]), params[:inventory_item_id]) - else - quantity = params[:product_quantity] - end - @modelEntry.inventory_item_id = inventoryId.to_i - @modelEntry.quantity = quantity - @modelEntry.currency = currency - unless @modelEntry.valid? - errorMsg = @modelEntry.errors.full_messages.join("
") - else - @modelEntry.save - end - if params[:log_type] == 'A' || params[:log_type] == @logType - inventoryObj = WkInventoryItem.find(inventoryId.to_i) - @assetObj = inventoryObj.asset_property - if params[:matterial_entry_id].blank? ||(params[:is_done].blank? || params[:is_done] == "0") - @assetObj.matterial_entry_id = @modelEntry.id - else - @assetObj.matterial_entry_id = nil - end - @assetObj.save - end - # save serial number - wklog_helper.saveConsumedSN(JSON.parse(params[:hidden_sns]), @modelEntry) if errorMsg.blank? && params[:hidden_sns].present? - end - end - return errorMsg - end - - def setEntries(model, id, params={}) - if id.blank? - @modelEntry = model.new - else - @modelEntry = model.find(id.to_i) - end - projectId = Issue.find(params[:issue_id].to_i).project_id - @modelEntry.project_id = projectId - @modelEntry.user_id = params[:user_id].blank? ? User.current.id : params[:user_id].to_i - @modelEntry.issue_id = params[:issue_id].to_i - @modelEntry.comments = params[:comments] - @modelEntry.activity_id = params[:activity_id].to_i - @modelEntry.spent_on = params[:spent_on] - end - - def saveExpense - errorMsg = "" - setEntries(WkExpenseEntry, params[:expense_entry_id], params[:wk_expense_entry]) - @modelEntry.amount = params[:expense_amount] - @modelEntry.currency = params[:wktime_currency] - unless @modelEntry.valid? - errorMsg = @modelEntry.errors.full_messages.join("
") - else - @modelEntry.save - end - return errorMsg - end - - def set_filter_session - if params[:spent_type].blank? && params[:log_type].blank? - session[:timelog] = {:spent_type => "T"} if session[:timelog].blank? || session[:timelog][:spent_type].blank? - else - session[:timelog] = {} if session[:timelog].blank? - session[:timelog][:spent_type] = params[:log_type].blank? ? params[:spent_type] : params[:log_type] - session[:timelog][:show_on_map] = params[:show_on_map] - end - end - # ======================================= - - def find_time_entries - # ============= ERPmine_patch Redmine 5.1 ===================== - set_filter_session - if session[:timelog][:spent_type] === "T" - # ========================================== - @time_entries = TimeEntry.where(:id => params[:id] || params[:ids]). - preload(:project => :time_entry_activities). - preload(:user).to_a - raise Unauthorized unless @time_entries.all? {|t| t.editable_by?(User.current)} - # ============= ERPmine_patch Redmine 5.1 ===================== - elsif session[:timelog][:spent_type] === "E" - @time_entries = WkExpenseEntry.where(:id => params[:id] || params[:ids]) - else - @time_entries = WkMaterialEntry.where(:id => params[:id] || params[:ids]) - end - raise ActiveRecord::RecordNotFound if @time_entries.empty? - # =================================== - @projects = @time_entries.filter_map(&:project).uniq - @project = @projects.first if @projects.size == 1 - rescue ActiveRecord::RecordNotFound - render_404 - end - - def find_time_entry - # ============= ERPmine_patch Redmine 5.1 ===================== - set_filter_session - if session[:timelog][:spent_type] === "T" - # ======================== - @time_entry = TimeEntry.find(params[:id]) - # ============= ERPmine_patch Redmine 5.1 ===================== - elsif session[:timelog][:spent_type] === "E" - @time_entry = WkExpenseEntry.find(params[:id]) - else - @time_entry = WkMaterialEntry.find(params[:id]) - end - # ============================================== - @project = @time_entry.project - rescue ActiveRecord::RecordNotFound - render_404 - end - - def check_editability - # ============= ERPmine_patch Redmine 5.1 ===================== - wktime_helper = Object.new.extend(WktimeHelper) - set_filter_session - if session[:timelog][:spent_type] === "T" - # ============================= - unless @time_entry.editable_by?(User.current) - render_403 - return false - end - # ============= ERPmine_patch Redmine 5.1 ===================== - elsif session[:timelog][:spent_type] === "E" - return true - else - return wktime_helper.showInventory - end - # ============================= - end - - def bulk_edit - # ============= ERPmine_patch Redmine 5.1 ===================== - if session[:timelog][:spent_type] == "T" - # ============================= - @target_projects = Project.allowed_to(:log_time).to_a - @custom_fields = TimeEntry.first.available_custom_fields.select {|field| field.format.bulk_edit_supported} - if params[:time_entry] - @target_project = @target_projects.detect {|p| p.id.to_s == params[:time_entry][:project_id].to_s} - end - if @target_project - @available_activities = @target_project.activities - else - @available_activities = @projects.map(&:activities).reduce(:&) - end - # ============= ERPmine_patch Redmine 5.1 ===================== - else - render_404 - end - # ============================= - @time_entry_params = params[:time_entry] || {} - @time_entry_params[:custom_field_values] ||= {} - end - - def bulk_update - attributes = parse_params_for_bulk_update(params[:time_entry]) - - unsaved_time_entries = [] - saved_time_entries = [] - - @time_entries.each do |time_entry| - time_entry.reload - time_entry.safe_attributes = attributes - call_hook( - :controller_time_entries_bulk_edit_before_save, - {:params => params, :time_entry => time_entry} - ) - # ============= ERPmine_patch Redmine 5.1 ===================== - wktime_helper = Object.new.extend(WktimeHelper) - errorMsg = wktime_helper.statusValidation(time_entry) - if errorMsg.blank? && time_entry.save - # ============================= - saved_time_entries << time_entry - else - unsaved_time_entries << time_entry - end - end - - if unsaved_time_entries.empty? - flash[:notice] = l(:notice_successful_update) unless saved_time_entries.empty? - redirect_back_or_default project_time_entries_path(@projects.first) - else - @saved_time_entries = @time_entries - @unsaved_time_entries = unsaved_time_entries - @time_entries = TimeEntry.where(:id => unsaved_time_entries.map(&:id)). - preload(:project => :time_entry_activities). - preload(:user).to_a - - bulk_edit - render :action => 'bulk_edit' - end - end - - def destroy - # ============= ERPmine_patch Redmine 5.1 ===================== - wktime_helper = Object.new.extend(WktimeHelper) - errMsg = "" - if session[:timelog][:spent_type] === "T" - # ============================ - destroyed = TimeEntry.transaction do - @time_entries.each do |t| - # ============= ERPmine_patch Redmine 5.1 ===================== - status = wktime_helper.getTimeEntryStatus(t.spent_on, t.user_id) - if !status.blank? && ('a' == status || 's' == status || 'l' == status) - errMsg = "#{l(:error_time_entry_delete)}" - raise ActiveRecord::Rollback - end - if errMsg.blank? - # =========================== - unless t.destroy && t.destroyed? - # ============= ERPmine_patch Redmine 5.1 ===================== - errMsg = l(:notice_unable_delete_time_entry) - # ============================ - raise ActiveRecord::Rollback - end - end - end - # ============= ERPmine_patch Redmine 5.1 ===================== - end - elsif session[:timelog][:spent_type] === "E" - destroyed = WkExpenseEntry.transaction do - @time_entries.each do |e| - status = wktime_helper.getExpenseEntryStatus(e.spent_on, e.user_id) - errMsg = "#{l(:error_expense_delete)}" if !status.blank? && ('a' == status || 's' == status || 'l' == status) - raise ActiveRecord::Rollback unless errMsg.blank? && e.destroy && e.destroyed? - end - end - else - if wktime_helper.validateERPPermission("D_INV") - destroyed = WkMaterialEntry.transaction do - begin - if @time_entries.spent_for.blank? || @time_entries.spent_for.invoice_item_id.blank? - if session[:timelog][:spent_type] === "M" - inventoryItemObj = WkInventoryItem.find(@time_entries.inventory_item_id) - inventoryItemObj.available_quantity = inventoryItemObj.available_quantity + @time_entries.quantity - inventoryItemObj.save - end - @time_entries.destroy - else - errMsg = l(:error_material_delete_billed) - logger.error ex.message - raise ActiveRecord::Rollback - end - rescue => ex - errMsg = l(:error_material_delete) - logger.error ex.message - raise ActiveRecord::Rollback - end - end - destroyed = WkMaterialEntry.transaction do - @time_entries.each do |m| - if m.spent_for.blank? || m.spent_for.invoice_item_id.blank? - if session[:timelog][:spent_type] === "M" - inventoryItemObj = WkInventoryItem.find(m.inventory_item_id) - inventoryItemObj.available_quantity = inventoryItemObj.available_quantity + m.quantity - inventoryItemObj.save - end - raise ActiveRecord::Rollback unless m.destroy && m.destroyed? - else - errMsg = l(:error_material_delete_billed) - raise ActiveRecord::Rollback - end - end - end - else - render_403 - return false - end - end - # ========================================== - respond_to do |format| - format.html do - if destroyed - flash[:notice] = l(:notice_successful_delete) - else - # ============= ERPmine_patch Redmine 5.1 ===================== - flash[:error] = errMsg || l(:notice_unable_delete_time_entry) - # ========================================== - end - redirect_back_or_default project_time_entries_path(@projects.first), :referer => true - end - format.api do - if destroyed - render_api_ok - else - render_validation_errors(@time_entries) - end - end - end - end - - end - end -end diff --git a/app/lib/timelog_helper_patch.rb b/app/lib/timelog_helper_patch.rb deleted file mode 100644 index 9000ac8d..00000000 --- a/app/lib/timelog_helper_patch.rb +++ /dev/null @@ -1,152 +0,0 @@ -module TimelogHelper - def format_criteria_value(criteria_options, value, html=true) - if value.blank? - "[#{l(:label_none)}]" - elsif k = criteria_options[:klass] - obj = k.find_by_id(value.to_i) - if obj.is_a?(Issue) - if obj.visible? - html ? link_to_issue(obj) : "#{obj.tracker} ##{obj.id}: #{obj.subject}" - else - "##{obj.id}" - end - # ============= ERPmine_patch Redmine 5.1 ===================== - elsif obj.is_a?(WkInventoryItem) - brandName = obj.product_item.brand.blank? ? "" : obj.product_item.brand.name - modelName = obj.product_item.product_model.blank? ? "" : obj.product_item.product_model.name - str = "#{obj.product_item.product.name} - #{brandName} - #{modelName}" - assetObj = obj.asset_property - str = str + " - " +assetObj.name if obj&.product_type != 'I' - str - # ======================== - else - format_object(obj, html) - end - elsif cf = criteria_options[:custom_field] - format_value(value, cf) - else - value.to_s - end - end - - def report_to_csv(report) - Redmine::Export::CSV.generate(:encoding => params[:encoding]) do |csv| - # Column headers - # ============= ERPmine_patch Redmine 5.1 ===================== - @showEstimate = session[:timelog][:spent_type] == "T" ? true : false - # ======================== - headers = - report.criteria.collect do |criteria| - l_or_humanize(report.available_criteria[criteria][:label]) - end - headers += report.periods - headers << l(:label_total_time) - # ============= ERPmine_patch Redmine 5.1 ===================== - headers << l(:field_total_estimated_hours) if @showEstimate - # ======================== - csv << headers - # Content - report_criteria_to_csv(csv, report.available_criteria, report.columns, - report.criteria, report.periods, report.hours) - # Total row - str_total = l(:label_total_time) - row = [str_total] + [''] * (report.criteria.size - 1) - total = 0 - report.periods.each do |period| - sum = sum_hours(select_hours(report.hours, report.columns, period.to_s)) - total += sum - row << (sum > 0 ? sum : '') - end - row << total - # ============= ERPmine_patch Redmine 5.1 ===================== - row << @estimatedTotal if @showEstimate - # ======================== - csv << row - end - end - - # ============= ERPmine_patch Redmine 5.1 ===================== - - def report_criteria_to_csv(csv, available_criteria, columns, criteria, periods, hours, level=0, filters = {}) - # ================================== - hours.collect {|h| h[criteria[level]].to_s}.uniq.each do |value| - hours_for_value = select_hours(hours, criteria[level], value) - # ============= ERPmine_patch Redmine 5.1 ===================== - filters.each{|key, value| filters.except!(value) if level < key.to_i} - criteriaLevel = criteria[level].include?("cf_") ? "cf" : criteria[level] - filters[level] = criteriaLevel - filters[criteriaLevel] = criteria[level].include?("cf_") ? [ criteria[level].split('_').last, value ] : value - # ================================== - next if hours_for_value.empty? - - row = [''] * level - row << format_criteria_value(available_criteria[criteria[level]], value, false).to_s - row += [''] * (criteria.length - level - 1) - total = 0 - periods.each do |period| - sum = sum_hours(select_hours(hours_for_value, columns, period.to_s)) - total += sum - row << (sum > 0 ? sum : '') - end - row << total - # ============= ERPmine_patch Redmine 5.1 ===================== - estimatedHours = estimated_hours(filters, criteria[level]) - @estimatedTotal ||= 0 - @estimatedTotal += estimatedHours if level == 0 - row << estimatedHours if @showEstimate - # ================================== - csv << row - if criteria.length > level + 1 - report_criteria_to_csv(csv, available_criteria, columns, criteria, periods, hours_for_value, level + 1, filters) - end - end - end - - # ============= ERPmine_patch Redmine 5.1 ===================== - def estimated_hours(filters, criteria) - cf_id = nil - filters.each{|k, v| cf_id = v.first if k == "cf" } - customField = criteria.include?("cf_") || cf_id.present? ? CustomField.find(cf_id || criteria.split('_').last) : nil - if ["project", "issue", "category", "status", "version", "tracker", "user"].include?(criteria) || customField && customField.type == "IssueCustomField" - query = Issue.reorder(nil) - query = query.where("project_id = ?", @project.id) if @project.present? - filters.each do |key, value| - case key - when "project" - query = get_clause(query, value, "issues.project_id") - when "issue" - query = get_clause(query, value, "issues.id") - when "status" - query = get_clause(query, value, "issues.status_id") - when "version" - query = get_clause(query, value, "issues.fixed_version_id") - when "tracker" - query = get_clause(query, value, "issues.tracker_id") - when "category" - query = get_clause(query, value, "issues.category_id") - when "user" - query = get_clause(query, value, "issues.assigned_to_id") - when "cf" - if value.last.present? && customField - query = query.joins(:custom_values).where({ "custom_values.customized_type": "Issue", "custom_values.custom_field_id": customField.id, "custom_values.value": value }) - else - query = query.joins("LEFT JOIN ( - SELECT customized_id AS id FROM custom_values - WHERE customized_type = 'Issue' AND (value != '') - GROUP BY customized_id - ) AS CV ON CV.id = issues.id").where("CV.id IS NULL") - end - end - end - sum = query.sum(:estimated_hours) - end - sum || 0 - end - - def get_clause(query, filter, column) - condition = filter.present? ? ((filter.split(",")).include?("null") ? "#{column} IN (#{filter}) OR #{column} IS NULL" : "#{column} IN (#{filter})") : "#{column} IS NULL" - query = query.where(condition) - end - # ================================== - -end \ No newline at end of file diff --git a/app/models/wk_acc_invoice_components.rb b/app/models/wk_acc_invoice_components.rb index 792b2bb9..65044067 100644 --- a/app/models/wk_acc_invoice_components.rb +++ b/app/models/wk_acc_invoice_components.rb @@ -15,7 +15,7 @@ # along with this program; if not, write to the Free Software # Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. -class WkAccInvoiceComponents < ActiveRecord::Base +class WkAccInvoiceComponents < ApplicationRecord belongs_to :invoice_comp, class_name: 'WkInvoiceComponents', foreign_key: 'invoice_component_id' belongs_to :acc_project, class_name: 'WkAccountProject', foreign_key: 'account_project_id' diff --git a/app/models/wk_acc_project_tax.rb b/app/models/wk_acc_project_tax.rb index 73d2c683..9e272dbe 100644 --- a/app/models/wk_acc_project_tax.rb +++ b/app/models/wk_acc_project_tax.rb @@ -15,8 +15,8 @@ # along with this program; if not, write to the Free Software # Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. -class WkAccProjectTax < ActiveRecord::Base - unloadable +class WkAccProjectTax < ApplicationRecord + belongs_to :account_project, :class_name => 'WkAccountProject', :foreign_key => 'account_project_id' belongs_to :tax, :class_name => 'WkTax' end diff --git a/app/models/wk_account.rb b/app/models/wk_account.rb index 6c6b2770..671b2c05 100644 --- a/app/models/wk_account.rb +++ b/app/models/wk_account.rb @@ -15,8 +15,8 @@ # along with this program; if not, write to the Free Software # Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. -class WkAccount < ActiveRecord::Base - unloadable +class WkAccount < ApplicationRecord + include Redmine::SafeAttributes safe_attributes( diff --git a/app/models/wk_account_project.rb b/app/models/wk_account_project.rb index fde06dd6..71c6a595 100644 --- a/app/models/wk_account_project.rb +++ b/app/models/wk_account_project.rb @@ -15,8 +15,8 @@ # along with this program; if not, write to the Free Software # Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. -class WkAccountProject < ActiveRecord::Base - unloadable +class WkAccountProject < ApplicationRecord + include Redmine::SafeAttributes diff --git a/app/models/wk_address.rb b/app/models/wk_address.rb index 03c93135..bf81f9d9 100644 --- a/app/models/wk_address.rb +++ b/app/models/wk_address.rb @@ -15,8 +15,8 @@ # along with this program; if not, write to the Free Software # Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. -class WkAddress < ActiveRecord::Base - unloadable +class WkAddress < ApplicationRecord + include Redmine::SafeAttributes diff --git a/app/models/wk_asset_depreciation.rb b/app/models/wk_asset_depreciation.rb index 75b9d4d0..2f47fe83 100644 --- a/app/models/wk_asset_depreciation.rb +++ b/app/models/wk_asset_depreciation.rb @@ -15,12 +15,12 @@ # along with this program; if not, write to the Free Software # Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. -class WkAssetDepreciation < ActiveRecord::Base - unloadable +class WkAssetDepreciation < ApplicationRecord + belongs_to :inventory_item, :class_name => 'WkInventoryItem' belongs_to :gl_transaction , :class_name => 'WkGlTransaction' before_destroy :remove_entry_from_gl_transaction - + def remove_entry_from_gl_transaction unless self.gl_transaction_id.blank? ledgerId = self.inventory_item.product_item.product.ledger_id @@ -50,5 +50,5 @@ def remove_entry_from_gl_transaction .where("wk_asset_depreciations.inventory_item_id = #{inventory_item_id} ") .select("wk_asset_depreciations.depreciation_date, wk_asset_depreciations.currency, wk_asset_depreciations.actual_amount - wk_asset_depreciations.depreciation_amount as current_value") } - + end \ No newline at end of file diff --git a/app/models/wk_asset_property.rb b/app/models/wk_asset_property.rb index f028b3a8..d3f4d750 100644 --- a/app/models/wk_asset_property.rb +++ b/app/models/wk_asset_property.rb @@ -15,9 +15,9 @@ # along with this program; if not, write to the Free Software # Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. -class WkAssetProperty < ActiveRecord::Base - unloadable - +class WkAssetProperty < ApplicationRecord + + belongs_to :inventory_item, :class_name => 'WkInventoryItem' belongs_to :material_entry, foreign_key: "matterial_entry_id", class_name: "WkMaterialEntry" scope :available_assets, -> { where(:matterial_entry_id => nil) } @@ -31,7 +31,7 @@ class WkAssetProperty < ActiveRecord::Base ) AS D ON D.inventory_item_id = ad.inventory_item_id AND D.depreciation_date = ad.depreciation_date") .joins("LEFT JOIN wk_inventory_items AS it ON wk_asset_properties.inventory_item_id = it.id") .joins("LEFT JOIN wk_shipments AS s ON it.shipment_id = s.id") - .where("wk_asset_properties.inventory_item_id =#{inventory_item_id} AND (ad.depreciation_date IS NULL OR + .where("wk_asset_properties.inventory_item_id =#{inventory_item_id} AND (ad.depreciation_date IS NULL OR ad.depreciation_date IS NOT NULL AND D.depreciation_date IS NOT NULL)") .select("wk_asset_properties.name, wk_asset_properties.id AS asset_property_id, wk_asset_properties.currency, is_disposed, disposed_rate, depreciation_amount, @@ -40,7 +40,7 @@ class WkAssetProperty < ActiveRecord::Base CASE WHEN D.depreciation_date IS NULL THEN shipment_date ELSE D.depreciation_date END AS depreciation_date, CASE WHEN depreciation_amount IS NOT NULL THEN actual_amount - depreciation_amount WHEN wk_asset_properties.current_value IS NOT NULL THEN wk_asset_properties.current_value - ELSE it.cost_price + it.over_head_price + ELSE it.cost_price + it.over_head_price END AS previous_value") } @@ -50,5 +50,5 @@ def self.dispose_asset_notification(assetProperty) userId = (WkPermission.permissionUser('V_INV') + WkPermission.permissionUser('D_INV')).uniq WkNotification.notification(userId, emailNotes, subject, assetProperty, "disposeAsset") end - + end diff --git a/app/models/wk_attendance.rb b/app/models/wk_attendance.rb index b996fd04..5be845b2 100644 --- a/app/models/wk_attendance.rb +++ b/app/models/wk_attendance.rb @@ -15,15 +15,15 @@ # along with this program; if not, write to the Free Software # Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. -class WkAttendance < ActiveRecord::Base - unloadable +class WkAttendance < ApplicationRecord + include Redmine::SafeAttributes - + belongs_to :user - + acts_as_customizable # attr_protected :user_id safe_attributes 'start_time', 'end_time' - + validates_presence_of :user_id end diff --git a/app/models/wk_attribute_group.rb b/app/models/wk_attribute_group.rb index 436240a6..8d2b9c26 100644 --- a/app/models/wk_attribute_group.rb +++ b/app/models/wk_attribute_group.rb @@ -15,8 +15,8 @@ # along with this program; if not, write to the Free Software # Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. -class WkAttributeGroup < ActiveRecord::Base - unloadable +class WkAttributeGroup < ApplicationRecord + has_many :products, foreign_key: "attribute_group_id", class_name: "WkProduct", :dependent => :restrict_with_error has_many :product_attributes, foreign_key: "group_id", class_name: "WkProductAttribute", :dependent => :destroy end diff --git a/app/models/wk_billing_schedule.rb b/app/models/wk_billing_schedule.rb index 5904b565..b1878ee2 100644 --- a/app/models/wk_billing_schedule.rb +++ b/app/models/wk_billing_schedule.rb @@ -15,12 +15,12 @@ # along with this program; if not, write to the Free Software # Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. -class WkBillingSchedule < ActiveRecord::Base - unloadable - +class WkBillingSchedule < ApplicationRecord + + belongs_to :account_project, :class_name => 'WkAccountProject', :foreign_key => 'account_project_id' belongs_to :invoice, :class_name => 'WkInvoice' - + validates_presence_of :milestone, :bill_date, :currency validates_numericality_of :amount, :allow_nil => false, :message => :invalid end diff --git a/app/models/wk_brand.rb b/app/models/wk_brand.rb index ed171489..9a826f9d 100644 --- a/app/models/wk_brand.rb +++ b/app/models/wk_brand.rb @@ -15,8 +15,8 @@ # along with this program; if not, write to the Free Software # Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. -class WkBrand < ActiveRecord::Base - unloadable +class WkBrand < ApplicationRecord + has_many :brand_products, foreign_key: "brand_id", class_name: "WkBrandProduct" has_many :products, through: :brand_products, :dependent => :restrict_with_error has_many :product_models, foreign_key: "brand_id", class_name: "WkProductModel", :dependent => :restrict_with_error diff --git a/app/models/wk_brand_product.rb b/app/models/wk_brand_product.rb index f531fedc..347e4d42 100644 --- a/app/models/wk_brand_product.rb +++ b/app/models/wk_brand_product.rb @@ -15,11 +15,11 @@ # along with this program; if not, write to the Free Software # Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. -class WkBrandProduct < ActiveRecord::Base - unloadable +class WkBrandProduct < ApplicationRecord + belongs_to :brand , :class_name => 'WkBrand' belongs_to :product , :class_name => 'WkProduct' # has_many :brands, foreign_key: "brand_id", class_name: "WkBrand" # has_many :products, foreign_key: "product_id", class_name: "WkProduct" - + end \ No newline at end of file diff --git a/app/models/wk_candidate.rb b/app/models/wk_candidate.rb index a6d573e9..ff14eea2 100644 --- a/app/models/wk_candidate.rb +++ b/app/models/wk_candidate.rb @@ -15,7 +15,7 @@ # along with this program; if not, write to the Free Software # Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. -class WkCandidate < ActiveRecord::Base - unloadable +class WkCandidate < ApplicationRecord + belongs_to :contact, class_name: 'WkCrmContact' end \ No newline at end of file diff --git a/app/models/wk_consumed_items.rb b/app/models/wk_consumed_items.rb index 96b8e0cf..be199be4 100644 --- a/app/models/wk_consumed_items.rb +++ b/app/models/wk_consumed_items.rb @@ -15,7 +15,7 @@ # along with this program; if not, write to the Free Software # Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. -class WkConsumedItems < ActiveRecord::Base +class WkConsumedItems < ApplicationRecord belongs_to :consumer, polymorphic: true scope :get_serial_nos, ->(id, type){ where(consumer_id: id, consumer_type: type)} diff --git a/app/models/wk_contract.rb b/app/models/wk_contract.rb index 7d17fa42..9755e590 100644 --- a/app/models/wk_contract.rb +++ b/app/models/wk_contract.rb @@ -15,8 +15,8 @@ # along with this program; if not, write to the Free Software # Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. -class WkContract < ActiveRecord::Base - unloadable +class WkContract < ApplicationRecord + acts_as_attachable :view_permission => :view_files, :edit_permission => :manage_files, :delete_permission => :manage_files @@ -26,12 +26,12 @@ class WkContract < ActiveRecord::Base validate :end_date_is_after_start_date # after_create_commit :send_notification has_many :notifications, as: :source, class_name: "WkUserNotification", :dependent => :destroy - + def end_date_is_after_start_date if !end_date.blank? - if end_date < start_date - errors.add(:end_date, "cannot be before the start date") - end + if end_date < start_date + errors.add(:end_date, "cannot be before the start date") + end end end diff --git a/app/models/wk_crm_activity.rb b/app/models/wk_crm_activity.rb index ed2a34d8..2785f262 100644 --- a/app/models/wk_crm_activity.rb +++ b/app/models/wk_crm_activity.rb @@ -15,8 +15,8 @@ # along with this program; if not, write to the Free Software # Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. -class WkCrmActivity < ActiveRecord::Base - unloadable +class WkCrmActivity < ApplicationRecord + belongs_to :parent, :polymorphic => true belongs_to :created_by_user, :class_name => 'User' belongs_to :assigned_user, :class_name => 'User' diff --git a/app/models/wk_crm_contact.rb b/app/models/wk_crm_contact.rb index ca0dd57b..9c379130 100644 --- a/app/models/wk_crm_contact.rb +++ b/app/models/wk_crm_contact.rb @@ -15,8 +15,8 @@ # along with this program; if not, write to the Free Software # Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. -class WkCrmContact < ActiveRecord::Base - unloadable +class WkCrmContact < ApplicationRecord + belongs_to :account, class_name: 'WkAccount' has_many :billable_projects, as: :parent, class_name: "WkAccountProject", dependent: :destroy belongs_to :address, class_name: 'WkAddress', dependent: :destroy diff --git a/app/models/wk_crm_enumeration.rb b/app/models/wk_crm_enumeration.rb index ef5a853f..978c0945 100644 --- a/app/models/wk_crm_enumeration.rb +++ b/app/models/wk_crm_enumeration.rb @@ -15,7 +15,7 @@ # along with this program; if not, write to the Free Software # Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. -class WkCrmEnumeration < ActiveRecord::Base +class WkCrmEnumeration < ApplicationRecord before_save :check_default validates_presence_of :name has_many :skillsets, class_name: :WkSkill, foreign_key: :skill_set_id, dependent: :destroy diff --git a/app/models/wk_delivery_item.rb b/app/models/wk_delivery_item.rb index b937c46d..7be37413 100644 --- a/app/models/wk_delivery_item.rb +++ b/app/models/wk_delivery_item.rb @@ -15,8 +15,8 @@ # along with this program; if not, write to the Free Software # Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. -class WkDeliveryItem < ActiveRecord::Base - unloadable +class WkDeliveryItem < ApplicationRecord + belongs_to :shipment, :class_name => 'WkShipment' belongs_to :inventory_item, :class_name => 'WkInventoryItem' end diff --git a/app/models/wk_ex_currency_rate.rb b/app/models/wk_ex_currency_rate.rb index 0765d56d..eb2f7793 100644 --- a/app/models/wk_ex_currency_rate.rb +++ b/app/models/wk_ex_currency_rate.rb @@ -15,7 +15,7 @@ # along with this program; if not, write to the Free Software # Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. -class WkExCurrencyRate < ActiveRecord::Base - unloadable - +class WkExCurrencyRate < ApplicationRecord + + end diff --git a/app/models/wk_expense_entry.rb b/app/models/wk_expense_entry.rb index e6ded5f9..ad7ea1d5 100644 --- a/app/models/wk_expense_entry.rb +++ b/app/models/wk_expense_entry.rb @@ -16,7 +16,7 @@ # Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. class WkExpenseEntry < TimeEntry - unloadable + self.table_name = "wk_expense_entries" belongs_to :project diff --git a/app/models/wk_gl_salary.rb b/app/models/wk_gl_salary.rb index 6054552b..c940064b 100644 --- a/app/models/wk_gl_salary.rb +++ b/app/models/wk_gl_salary.rb @@ -15,9 +15,9 @@ # along with this program; if not, write to the Free Software # Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. -class WkGlSalary < ActiveRecord::Base - unloadable +class WkGlSalary < ApplicationRecord + include Redmine::SafeAttributes - + belongs_to :gl_transaction, foreign_key: "gl_transaction_id", class_name: "WkGlTransaction", :dependent => :destroy end \ No newline at end of file diff --git a/app/models/wk_gl_transaction.rb b/app/models/wk_gl_transaction.rb index 538bf6ca..e6ae9dfe 100644 --- a/app/models/wk_gl_transaction.rb +++ b/app/models/wk_gl_transaction.rb @@ -15,8 +15,8 @@ # along with this program; if not, write to the Free Software # Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. -class WkGlTransaction < ActiveRecord::Base - unloadable +class WkGlTransaction < ApplicationRecord + has_many :transaction_details, foreign_key: "gl_transaction_id", class_name: "WkGlTransactionDetail", :dependent => :destroy has_one :invoice, foreign_key: "gl_transaction_id", class_name: "WkInvoice" has_many :gl_salaries, foreign_key: "gl_transaction_id", class_name: "WkGlSalary", :dependent => :destroy @@ -25,7 +25,7 @@ class WkGlTransaction < ActiveRecord::Base acts_as_attachable :view_permission => :view_files, :edit_permission => :manage_files, :delete_permission => :manage_files - + def trans_date=(date) super self.tyear = trans_date ? trans_date.year : nil diff --git a/app/models/wk_gl_transaction_detail.rb b/app/models/wk_gl_transaction_detail.rb index 9de00cbf..a6c9abd8 100644 --- a/app/models/wk_gl_transaction_detail.rb +++ b/app/models/wk_gl_transaction_detail.rb @@ -15,8 +15,8 @@ # along with this program; if not, write to the Free Software # Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. -class WkGlTransactionDetail < ActiveRecord::Base - unloadable +class WkGlTransactionDetail < ApplicationRecord + belongs_to :ledger, :class_name => 'WkLedger' belongs_to :wkgltransaction, :class_name => 'WkGlTransaction', :foreign_key => 'gl_transaction_id' end diff --git a/app/models/wk_group_permission.rb b/app/models/wk_group_permission.rb index cf4f365f..0ceff3f6 100644 --- a/app/models/wk_group_permission.rb +++ b/app/models/wk_group_permission.rb @@ -15,9 +15,9 @@ # along with this program; if not, write to the Free Software # Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. -class WkGroupPermission < ActiveRecord::Base - unloadable - +class WkGroupPermission < ApplicationRecord + + belongs_to :group , :class_name => 'Group' belongs_to :permission , :class_name => 'WkPermission' has_many :users, :through => :group diff --git a/app/models/wk_h_user_salary_components.rb b/app/models/wk_h_user_salary_components.rb index 8a340fd8..eb6d55c2 100644 --- a/app/models/wk_h_user_salary_components.rb +++ b/app/models/wk_h_user_salary_components.rb @@ -15,12 +15,12 @@ # along with this program; if not, write to the Free Software # Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. -class WkHUserSalaryComponents < ActiveRecord::Base - unloadable +class WkHUserSalaryComponents < ApplicationRecord + include Redmine::SafeAttributes - + belongs_to :user belongs_to :user_salary_component, :class_name => 'WkUserSalaryComponents', :foreign_key => 'user_salary_component_id' - + # attr_protected :user_id, :user_salary_component_id end diff --git a/app/models/wk_income_tax.rb b/app/models/wk_income_tax.rb index a955a2dc..66986a15 100644 --- a/app/models/wk_income_tax.rb +++ b/app/models/wk_income_tax.rb @@ -1,4 +1,4 @@ -class WkIncomeTax < ActiveRecord::Base +class WkIncomeTax < ApplicationRecord belongs_to :user end \ No newline at end of file diff --git a/app/models/wk_inventory_item.rb b/app/models/wk_inventory_item.rb index 7c8a88c7..53af6d28 100644 --- a/app/models/wk_inventory_item.rb +++ b/app/models/wk_inventory_item.rb @@ -15,8 +15,8 @@ # along with this program; if not, write to the Free Software # Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. -class WkInventoryItem < ActiveRecord::Base - unloadable +class WkInventoryItem < ApplicationRecord + belongs_to :shipment, :class_name => 'WkShipment' belongs_to :product_item, :class_name => 'WkProductItem' belongs_to :supplier_invoice, foreign_key: "supplier_invoice_id", class_name: "WkInvoice" diff --git a/app/models/wk_invoice.rb b/app/models/wk_invoice.rb index 50f4e952..212c821b 100644 --- a/app/models/wk_invoice.rb +++ b/app/models/wk_invoice.rb @@ -15,8 +15,8 @@ # along with this program; if not, write to the Free Software # Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. -class WkInvoice < ActiveRecord::Base - unloadable +class WkInvoice < ApplicationRecord + #belongs_to :account, :class_name => 'WkAccount' belongs_to :parent, :polymorphic => true belongs_to :modifier , :class_name => 'User' diff --git a/app/models/wk_invoice_components.rb b/app/models/wk_invoice_components.rb index 63534e71..cf451b86 100644 --- a/app/models/wk_invoice_components.rb +++ b/app/models/wk_invoice_components.rb @@ -15,14 +15,14 @@ # along with this program; if not, write to the Free Software # Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. -class WkInvoiceComponents < ActiveRecord::Base - +class WkInvoiceComponents < ApplicationRecord + has_many :acc_invoice_comps, foreign_key: "invoice_component_id", class_name: "WkAccInvoiceComponents", dependent: :destroy scope :getInvComp, ->{ self.where(comp_type: 'IC') } - + scope :getAccInvComp, ->(id){ joins("LEFT JOIN wk_acc_invoice_components AIC on wk_invoice_components.id = AIC.invoice_component_id and (account_project_id IN (#{id}) OR AIC.id is NULL)") .select("wk_invoice_components.id as ic_id, wk_invoice_components.name, wk_invoice_components.value as ic_value, AIC.*") diff --git a/app/models/wk_invoice_item.rb b/app/models/wk_invoice_item.rb index e2f712de..10e2b6cd 100644 --- a/app/models/wk_invoice_item.rb +++ b/app/models/wk_invoice_item.rb @@ -15,8 +15,8 @@ # along with this program; if not, write to the Free Software # Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. -class WkInvoiceItem < ActiveRecord::Base - unloadable +class WkInvoiceItem < ApplicationRecord + include Redmine::SafeAttributes belongs_to :invoice, :class_name => 'WkInvoice' belongs_to :modifier, :class_name => 'User' diff --git a/app/models/wk_issue.rb b/app/models/wk_issue.rb index 1889c0a0..6320d3b9 100644 --- a/app/models/wk_issue.rb +++ b/app/models/wk_issue.rb @@ -15,11 +15,11 @@ # along with this program; if not, write to the Free Software # Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. -class WkIssue < ActiveRecord::Base +class WkIssue < ApplicationRecord include Redmine::SafeAttributes belongs_to :project belongs_to :issue # attr_protected :others, :issue_id, :project_id - + safe_attributes 'project_id', 'issue_id', 'currency', 'rate', 'rate_per' end diff --git a/app/models/wk_issue_assignee.rb b/app/models/wk_issue_assignee.rb index 324e7dfd..68db1d7b 100644 --- a/app/models/wk_issue_assignee.rb +++ b/app/models/wk_issue_assignee.rb @@ -5,12 +5,12 @@ # along with this program; if not, write to the Free Software # Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. -class WkIssueAssignee < ActiveRecord::Base +class WkIssueAssignee < ApplicationRecord include Redmine::SafeAttributes belongs_to :project belongs_to :issue belongs_to :user # attr_protected :others, :issue_id - + safe_attributes 'user_id' end \ No newline at end of file diff --git a/app/models/wk_lead.rb b/app/models/wk_lead.rb index 148cd33c..57fc1a3f 100644 --- a/app/models/wk_lead.rb +++ b/app/models/wk_lead.rb @@ -15,8 +15,8 @@ # along with this program; if not, write to the Free Software # Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. -class WkLead < ActiveRecord::Base - unloadable +class WkLead < ApplicationRecord + has_many :activities, as: :parent, class_name: 'WkCrmActivity', :dependent => :destroy belongs_to :account, :class_name => 'WkAccount' belongs_to :created_by_user, :class_name => 'User' diff --git a/app/models/wk_leave_req.rb b/app/models/wk_leave_req.rb index 68bba9fa..d5921e07 100644 --- a/app/models/wk_leave_req.rb +++ b/app/models/wk_leave_req.rb @@ -15,7 +15,7 @@ # along with this program; if not, write to the Free Software # Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. -class WkLeaveReq < ActiveRecord::Base +class WkLeaveReq < ApplicationRecord belongs_to :user belongs_to :leave_type, class_name: "Issue" diff --git a/app/models/wk_ledger.rb b/app/models/wk_ledger.rb index b846b4c4..2a15913b 100644 --- a/app/models/wk_ledger.rb +++ b/app/models/wk_ledger.rb @@ -15,8 +15,8 @@ # along with this program; if not, write to the Free Software # Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. -class WkLedger < ActiveRecord::Base - unloadable - has_many :transaction_details, foreign_key: "ledger_id", class_name: "WkGlTransactionDetail", :dependent => :restrict_with_error +class WkLedger < ApplicationRecord + + has_many :transaction_details, foreign_key: "ledger_id", class_name: "WkGlTransactionDetail", :dependent => :restrict_with_error validates_presence_of :name end diff --git a/app/models/wk_location.rb b/app/models/wk_location.rb index 3dfc0e8b..17a7839a 100644 --- a/app/models/wk_location.rb +++ b/app/models/wk_location.rb @@ -15,8 +15,8 @@ # along with this program; if not, write to the Free Software # Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. -class WkLocation < ActiveRecord::Base - unloadable +class WkLocation < ApplicationRecord + belongs_to :address, :class_name => 'WkAddress', :dependent => :destroy has_many :inventory_items, foreign_key: "location_id", class_name: "WkInventoryItem", :dependent => :restrict_with_error belongs_to :location_type, :class_name => 'WkCrmEnumeration' diff --git a/app/models/wk_material_entry.rb b/app/models/wk_material_entry.rb index b954bc93..3e8b5347 100644 --- a/app/models/wk_material_entry.rb +++ b/app/models/wk_material_entry.rb @@ -16,7 +16,7 @@ # Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. class WkMaterialEntry < TimeEntry - unloadable + self.table_name = "wk_material_entries" diff --git a/app/models/wk_mesure_unit.rb b/app/models/wk_mesure_unit.rb index 0fdabd86..5edca701 100644 --- a/app/models/wk_mesure_unit.rb +++ b/app/models/wk_mesure_unit.rb @@ -15,7 +15,7 @@ # along with this program; if not, write to the Free Software # Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. -class WkMesureUnit < ActiveRecord::Base - unloadable +class WkMesureUnit < ApplicationRecord + has_many :product, foreign_key: "uom_id", class_name: "WkProduct", :dependent => :restrict_with_error end diff --git a/app/models/wk_notification.rb b/app/models/wk_notification.rb index 90a5a5f7..e575092c 100644 --- a/app/models/wk_notification.rb +++ b/app/models/wk_notification.rb @@ -15,9 +15,9 @@ # along with this program; if not, write to the Free Software # Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. -class WkNotification < ActiveRecord::Base +class WkNotification < ApplicationRecord has_many :wk_user_notifications, foreign_key: "notify_id", class_name: "WkUserNotification", :dependent => :destroy - + scope :getActiveNotification, -> { where(active: true) } scope :getUnseletedActions, ->(actionName){ where.not(name: actionName, active: false) } diff --git a/app/models/wk_opportunity.rb b/app/models/wk_opportunity.rb index e5927ead..5cc37d51 100644 --- a/app/models/wk_opportunity.rb +++ b/app/models/wk_opportunity.rb @@ -15,8 +15,8 @@ # along with this program; if not, write to the Free Software # Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. -class WkOpportunity < ActiveRecord::Base - unloadable +class WkOpportunity < ApplicationRecord + belongs_to :parent, :polymorphic => true belongs_to :assigned_user, :class_name => 'User' diff --git a/app/models/wk_payment.rb b/app/models/wk_payment.rb index 482458ce..0d6f836f 100644 --- a/app/models/wk_payment.rb +++ b/app/models/wk_payment.rb @@ -15,8 +15,8 @@ # along with this program; if not, write to the Free Software # Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. -class WkPayment < ActiveRecord::Base - unloadable +class WkPayment < ApplicationRecord + #belongs_to :account, :class_name => 'WkAccount' belongs_to :parent, :polymorphic => true belongs_to :account, -> { where(wk_payments: {parent_type: 'WkAccount'}) }, foreign_key: 'parent_id', :class_name => 'WkAccount' diff --git a/app/models/wk_payment_item.rb b/app/models/wk_payment_item.rb index 8334e4bc..0d852e4d 100644 --- a/app/models/wk_payment_item.rb +++ b/app/models/wk_payment_item.rb @@ -15,17 +15,17 @@ # along with this program; if not, write to the Free Software # Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. -class WkPaymentItem < ActiveRecord::Base - unloadable +class WkPaymentItem < ApplicationRecord + include Redmine::SafeAttributes belongs_to :payment, :class_name => 'WkPayment' belongs_to :modifier, :class_name => 'User' belongs_to :invoice, :class_name => 'WkInvoice' #belongs_to :gl_transaction , :class_name => 'WkGlTransaction', :dependent => :destroy scope :current_items, -> { where(is_deleted: false) } - + # attr_protected :modifier_id - + validates_presence_of :payment_id validates_numericality_of :amount, :allow_nil => true, :message => :invalid end diff --git a/app/models/wk_permission.rb b/app/models/wk_permission.rb index 16a2508d..e93d946f 100644 --- a/app/models/wk_permission.rb +++ b/app/models/wk_permission.rb @@ -15,8 +15,8 @@ # along with this program; if not, write to the Free Software # Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. -class WkPermission < ActiveRecord::Base - unloadable +class WkPermission < ApplicationRecord + has_many :grpPermission, foreign_key: "permission_id", :class_name => 'WkGroupPermission', :dependent => :destroy has_many :group , :through => :grpPermission diff --git a/app/models/wk_po_quote.rb b/app/models/wk_po_quote.rb index 1b1d37f9..6c602c82 100644 --- a/app/models/wk_po_quote.rb +++ b/app/models/wk_po_quote.rb @@ -15,8 +15,8 @@ # along with this program; if not, write to the Free Software # Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. -class WkPoQuote < ActiveRecord::Base - unloadable +class WkPoQuote < ApplicationRecord + belongs_to :purchase_order , :class_name => 'WkInvoice' belongs_to :quote , :class_name => 'WkInvoice' after_create_commit :send_notification @@ -34,7 +34,7 @@ def send_notification joins(:user).where("users.id = ? OR (users.parent_id = ?)", User.current.id, User.current.id) } - scope :getPurchaseOrder, -> { + scope :getPurchaseOrder, -> { where(:quote_id => nil) } end diff --git a/app/models/wk_po_supplier_invoice.rb b/app/models/wk_po_supplier_invoice.rb index 91624064..28fccae9 100644 --- a/app/models/wk_po_supplier_invoice.rb +++ b/app/models/wk_po_supplier_invoice.rb @@ -15,8 +15,8 @@ # along with this program; if not, write to the Free Software # Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. -class WkPoSupplierInvoice < ActiveRecord::Base - unloadable +class WkPoSupplierInvoice < ApplicationRecord + belongs_to :purchase_order , :class_name => 'WkInvoice' belongs_to :supplier_invoice , foreign_key: "supplier_inv_id", :class_name => 'WkInvoice' has_many :notifications, as: :source, class_name: "WkUserNotification", :dependent => :destroy diff --git a/app/models/wk_product.rb b/app/models/wk_product.rb index e0f418d7..cf732235 100644 --- a/app/models/wk_product.rb +++ b/app/models/wk_product.rb @@ -15,8 +15,8 @@ # along with this program; if not, write to the Free Software # Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. -class WkProduct < ActiveRecord::Base - unloadable +class WkProduct < ApplicationRecord + belongs_to :category, :class_name => 'WkProductCategory' has_many :product_items, foreign_key: "product_id", class_name: "WkProductItem", :dependent => :restrict_with_error has_many :inventory_items, through: :product_items @@ -29,7 +29,7 @@ class WkProduct < ActiveRecord::Base belongs_to :uom, class_name: "WkMesureUnit" has_many :product_taxes, foreign_key: "product_id", class_name: "WkProductTax", :dependent => :destroy has_many :taxes, through: :product_taxes - + validates_presence_of :category scope :getProducts, ->(type){ diff --git a/app/models/wk_product_attribute.rb b/app/models/wk_product_attribute.rb index d222d932..20ca4e32 100644 --- a/app/models/wk_product_attribute.rb +++ b/app/models/wk_product_attribute.rb @@ -15,8 +15,8 @@ # along with this program; if not, write to the Free Software # Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. -class WkProductAttribute < ActiveRecord::Base - unloadable +class WkProductAttribute < ApplicationRecord + belongs_to :attribute_group, foreign_key: "group_id", class_name: "WkAttributeGroup" has_many :inventory_items, foreign_key: "product_attribute_id", class_name: "WkInventoryItem", :dependent => :restrict_with_error diff --git a/app/models/wk_product_category.rb b/app/models/wk_product_category.rb index bed6342a..46236508 100644 --- a/app/models/wk_product_category.rb +++ b/app/models/wk_product_category.rb @@ -15,8 +15,8 @@ # along with this program; if not, write to the Free Software # Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. -class WkProductCategory < ActiveRecord::Base - unloadable +class WkProductCategory < ApplicationRecord + has_many :products, foreign_key: "category_id", class_name: "WkProduct", :dependent => :restrict_with_error - + end diff --git a/app/models/wk_product_item.rb b/app/models/wk_product_item.rb index 255d303d..dd984e0c 100644 --- a/app/models/wk_product_item.rb +++ b/app/models/wk_product_item.rb @@ -15,8 +15,8 @@ # along with this program; if not, write to the Free Software # Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. -class WkProductItem < ActiveRecord::Base - unloadable +class WkProductItem < ApplicationRecord + belongs_to :product, :class_name => 'WkProduct' belongs_to :brand, :class_name => 'WkBrand' belongs_to :product_model, :class_name => 'WkProductModel' diff --git a/app/models/wk_product_model.rb b/app/models/wk_product_model.rb index bc657086..8d5ba3f1 100644 --- a/app/models/wk_product_model.rb +++ b/app/models/wk_product_model.rb @@ -15,8 +15,8 @@ # along with this program; if not, write to the Free Software # Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. -class WkProductModel < ActiveRecord::Base - unloadable +class WkProductModel < ApplicationRecord + belongs_to :product, :class_name => 'WkProduct' belongs_to :brand, :class_name => 'WkProductBrand' has_many :product_items, foreign_key: "product_model_id", class_name: "WkProductItem", :dependent => :restrict_with_error diff --git a/app/models/wk_product_tax.rb b/app/models/wk_product_tax.rb index 18893aa9..81fbcb00 100644 --- a/app/models/wk_product_tax.rb +++ b/app/models/wk_product_tax.rb @@ -15,8 +15,8 @@ # along with this program; if not, write to the Free Software # Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. -class WkProductTax < ActiveRecord::Base - unloadable +class WkProductTax < ApplicationRecord + belongs_to :product, :class_name => 'WkProduct' belongs_to :tax, :class_name => 'WkTax' end \ No newline at end of file diff --git a/app/models/wk_project.rb b/app/models/wk_project.rb index 6e23389c..fce31545 100644 --- a/app/models/wk_project.rb +++ b/app/models/wk_project.rb @@ -1,4 +1,4 @@ -class WkProject < ActiveRecord::Base +class WkProject < ApplicationRecord include Redmine::SafeAttributes belongs_to :project diff --git a/app/models/wk_public_holiday.rb b/app/models/wk_public_holiday.rb index 3b09f5c5..819e4f3a 100644 --- a/app/models/wk_public_holiday.rb +++ b/app/models/wk_public_holiday.rb @@ -15,7 +15,7 @@ # along with this program; if not, write to the Free Software # Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. -class WkPublicHoliday < ActiveRecord::Base +class WkPublicHoliday < ApplicationRecord belongs_to :location, class_name: 'WkLocation' scope :getHolidays, ->(userID, holiday){ diff --git a/app/models/wk_rfq.rb b/app/models/wk_rfq.rb index 8e74387a..a8491b20 100644 --- a/app/models/wk_rfq.rb +++ b/app/models/wk_rfq.rb @@ -15,8 +15,8 @@ # along with this program; if not, write to the Free Software # Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. -class WkRfq < ActiveRecord::Base - unloadable +class WkRfq < ApplicationRecord + has_many :rfq_quotes, foreign_key: "rfq_id", class_name: "WkRfqQuote" has_many :quotes, through: :rfq_quotes, :dependent => :restrict_with_error has_many :purchase_orders, through: :quotes diff --git a/app/models/wk_rfq_quote.rb b/app/models/wk_rfq_quote.rb index e5a21d13..74b488bc 100644 --- a/app/models/wk_rfq_quote.rb +++ b/app/models/wk_rfq_quote.rb @@ -15,8 +15,8 @@ # along with this program; if not, write to the Free Software # Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. -class WkRfqQuote < ActiveRecord::Base - unloadable +class WkRfqQuote < ApplicationRecord + belongs_to :quote , :class_name => 'WkInvoice' belongs_to :rfq , :class_name => 'WkRfq' after_create_commit :send_notification diff --git a/app/models/wk_sal_comp_condition.rb b/app/models/wk_sal_comp_condition.rb index d54b5bc4..41619101 100644 --- a/app/models/wk_sal_comp_condition.rb +++ b/app/models/wk_sal_comp_condition.rb @@ -1,4 +1,4 @@ -class WkSalCompCondition < ActiveRecord::Base +class WkSalCompCondition < ApplicationRecord belongs_to :salary_comp_dep, :class_name => 'WkSalCompDependent' validates_presence_of :lhs, :operators, :rhs, :rhs2 end \ No newline at end of file diff --git a/app/models/wk_sal_comp_dependent.rb b/app/models/wk_sal_comp_dependent.rb index bdc36646..f41761ea 100644 --- a/app/models/wk_sal_comp_dependent.rb +++ b/app/models/wk_sal_comp_dependent.rb @@ -1,4 +1,4 @@ -class WkSalCompDependent < ActiveRecord::Base +class WkSalCompDependent < ApplicationRecord belongs_to :salary_comp, :class_name => 'WkSalaryComponents', :foreign_key => 'salary_component_id' has_one :salary_comp_cond, foreign_key: "sal_comp_dep_id", class_name: "WkSalCompCondition" diff --git a/app/models/wk_salary.rb b/app/models/wk_salary.rb index f931d687..08e241b2 100644 --- a/app/models/wk_salary.rb +++ b/app/models/wk_salary.rb @@ -15,8 +15,8 @@ # along with this program; if not, write to the Free Software # Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. -class WkSalary < ActiveRecord::Base - unloadable +class WkSalary < ApplicationRecord + include Redmine::SafeAttributes belongs_to :user diff --git a/app/models/wk_salary_components.rb b/app/models/wk_salary_components.rb index 14ab856d..03c4fad4 100644 --- a/app/models/wk_salary_components.rb +++ b/app/models/wk_salary_components.rb @@ -15,12 +15,12 @@ # along with this program; if not, write to the Free Software # Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. -class WkSalaryComponents < ActiveRecord::Base +class WkSalaryComponents < ApplicationRecord Redmine::SafeAttributes has_many :salaries, foreign_key: "salary_component_id", class_name: "WkSalary" has_many :salary_comp_deps, foreign_key: "salary_component_id", class_name: "WkSalCompDependent", dependent: :destroy accepts_nested_attributes_for :salary_comp_deps, allow_destroy: true - + def self.getReimburseID self.where({component_type: 'r'}).first&.id end diff --git a/app/models/wk_setting.rb b/app/models/wk_setting.rb index 6149c1e4..53135e4f 100644 --- a/app/models/wk_setting.rb +++ b/app/models/wk_setting.rb @@ -1,2 +1,2 @@ -class WkSetting < ActiveRecord::Base +class WkSetting < ApplicationRecord end \ No newline at end of file diff --git a/app/models/wk_shift.rb b/app/models/wk_shift.rb index cd22bf4b..9ff25b4d 100644 --- a/app/models/wk_shift.rb +++ b/app/models/wk_shift.rb @@ -15,7 +15,7 @@ # along with this program; if not, write to the Free Software # Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. -class WkShift < ActiveRecord::Base +class WkShift < ApplicationRecord has_many :shift_roles, foreign_key: "shift_id", class_name: "WkShiftRole", :dependent => :restrict_with_error has_many :shift_schedules, foreign_key: "shift_id", class_name: "WkShiftSchedule", :dependent => :restrict_with_error diff --git a/app/models/wk_shift_role.rb b/app/models/wk_shift_role.rb index 6fff6f30..6d10bbd7 100644 --- a/app/models/wk_shift_role.rb +++ b/app/models/wk_shift_role.rb @@ -15,7 +15,7 @@ # along with this program; if not, write to the Free Software # Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. -class WkShiftRole < ActiveRecord::Base +class WkShiftRole < ApplicationRecord belongs_to :role, class_name: "Role" belongs_to :shift, class_name: "WkShift" belongs_to :location, class_name: "WkLocation" diff --git a/app/models/wk_shift_schedule.rb b/app/models/wk_shift_schedule.rb index f4fbe80d..8f7899a3 100644 --- a/app/models/wk_shift_schedule.rb +++ b/app/models/wk_shift_schedule.rb @@ -15,7 +15,7 @@ # along with this program; if not, write to the Free Software # Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. -class WkShiftSchedule < ActiveRecord::Base +class WkShiftSchedule < ApplicationRecord belongs_to :shift, class_name: "WkShift"#, :dependent => :restrict_with_error belongs_to :user validates_presence_of :shift_id diff --git a/app/models/wk_shipment.rb b/app/models/wk_shipment.rb index 135f6a0a..cf70911f 100644 --- a/app/models/wk_shipment.rb +++ b/app/models/wk_shipment.rb @@ -15,8 +15,8 @@ # along with this program; if not, write to the Free Software # Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. -class WkShipment < ActiveRecord::Base - unloadable +class WkShipment < ApplicationRecord + #belongs_to :account, :class_name => 'WkAccount' belongs_to :parent, :polymorphic => true has_many :inventory_items, foreign_key: "shipment_id", class_name: "WkInventoryItem", :dependent => :destroy @@ -24,7 +24,7 @@ class WkShipment < ActiveRecord::Base belongs_to :gl_transaction , :class_name => 'WkGlTransaction', :dependent => :destroy belongs_to :supplier_invoice, foreign_key: "supplier_invoice_id", class_name: "WkInvoice" #belongs_to :purchase_order, foreign_key: "purchase_order_id", class_name: "WkInvoice" - belongs_to :product, foreign_key: "product_id", class_name: "WkProduct" + belongs_to :product, foreign_key: "product_id", class_name: "WkProduct" after_create_commit :send_notification has_many :notifications, as: :source, class_name: "WkUserNotification", :dependent => :destroy has_many :delivery_items, foreign_key: "shipment_id", class_name: "WkDeliveryItem", :dependent => :destroy @@ -44,5 +44,5 @@ def send_notification def current_status self ? self&.wkstatus&.last&.status : '' end - + end diff --git a/app/models/wk_skill.rb b/app/models/wk_skill.rb index fe6acd3a..7962027a 100644 --- a/app/models/wk_skill.rb +++ b/app/models/wk_skill.rb @@ -15,7 +15,7 @@ # along with this program; if not, write to the Free Software # Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. -class WkSkill < ActiveRecord::Base +class WkSkill < ApplicationRecord belongs_to :user belongs_to :skill_set, class_name: "WkCrmEnumeration" has_many :groups, through: :user diff --git a/app/models/wk_spent_for.rb b/app/models/wk_spent_for.rb index ad75fbfc..b3dd2b3e 100644 --- a/app/models/wk_spent_for.rb +++ b/app/models/wk_spent_for.rb @@ -15,7 +15,7 @@ # along with this program; if not, write to the Free Software # Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. -class WkSpentFor < ActiveRecord::Base +class WkSpentFor < ApplicationRecord include Redmine::SafeAttributes belongs_to :spent_for, :polymorphic => true belongs_to :spent, :polymorphic => true diff --git a/app/models/wk_status.rb b/app/models/wk_status.rb index 5a74a19d..e6b968b7 100644 --- a/app/models/wk_status.rb +++ b/app/models/wk_status.rb @@ -15,7 +15,7 @@ # along with this program; if not, write to the Free Software # Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. -class WkStatus < ActiveRecord::Base +class WkStatus < ApplicationRecord belongs_to :status_for, :polymorphic => true validates_presence_of :status_date, :status diff --git a/app/models/wk_survey.rb b/app/models/wk_survey.rb index df013329..75ffab0a 100644 --- a/app/models/wk_survey.rb +++ b/app/models/wk_survey.rb @@ -15,7 +15,7 @@ # along with this program; if not, write to the Free Software # Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. -class WkSurvey < ActiveRecord::Base +class WkSurvey < ApplicationRecord belongs_to :group , :class_name => 'Group' belongs_to :survey_for, :polymorphic => true diff --git a/app/models/wk_survey_answer.rb b/app/models/wk_survey_answer.rb index 56fee260..d02ab3bb 100644 --- a/app/models/wk_survey_answer.rb +++ b/app/models/wk_survey_answer.rb @@ -15,7 +15,7 @@ # along with this program; if not, write to the Free Software # Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. -class WkSurveyAnswer < ActiveRecord::Base +class WkSurveyAnswer < ApplicationRecord belongs_to :survey_choice , :class_name => 'WkSurveyChoice' belongs_to :survey_question , :class_name => 'WkSurveyQuestion' diff --git a/app/models/wk_survey_choice.rb b/app/models/wk_survey_choice.rb index 8b199782..1c469f9e 100644 --- a/app/models/wk_survey_choice.rb +++ b/app/models/wk_survey_choice.rb @@ -15,7 +15,7 @@ # along with this program; if not, write to the Free Software # Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. -class WkSurveyChoice < ActiveRecord::Base +class WkSurveyChoice < ApplicationRecord has_many :wk_survey_answers, foreign_key: "survey_choice_id", class_name: "WkSurveyAnswer", :dependent => :destroy belongs_to :survey_question , :class_name => 'WkSurveyQuestion' diff --git a/app/models/wk_survey_question.rb b/app/models/wk_survey_question.rb index 1de45456..d1bb75d7 100644 --- a/app/models/wk_survey_question.rb +++ b/app/models/wk_survey_question.rb @@ -15,7 +15,7 @@ # along with this program; if not, write to the Free Software # Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. -class WkSurveyQuestion < ActiveRecord::Base +class WkSurveyQuestion < ApplicationRecord belongs_to :survey , :class_name => 'WkSurvey' has_many :wk_survey_choices, foreign_key: "survey_question_id", class_name: "WkSurveyChoice", :dependent => :destroy diff --git a/app/models/wk_survey_response.rb b/app/models/wk_survey_response.rb index f4020119..0b365add 100644 --- a/app/models/wk_survey_response.rb +++ b/app/models/wk_survey_response.rb @@ -15,7 +15,7 @@ # along with this program; if not, write to the Free Software # Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. -class WkSurveyResponse < ActiveRecord::Base +class WkSurveyResponse < ApplicationRecord belongs_to :survey, :class_name => 'WkSurvey' belongs_to :user diff --git a/app/models/wk_survey_review.rb b/app/models/wk_survey_review.rb index 2d9b21ed..0bd23c2f 100644 --- a/app/models/wk_survey_review.rb +++ b/app/models/wk_survey_review.rb @@ -15,7 +15,7 @@ # along with this program; if not, write to the Free Software # Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. -class WkSurveyReview < ActiveRecord::Base +class WkSurveyReview < ApplicationRecord belongs_to :survey_response, :class_name => 'WkSurveyResponse' belongs_to :survey_question, :class_name => 'WkSurveyQuestion' belongs_to :user diff --git a/app/models/wk_tax.rb b/app/models/wk_tax.rb index a5a9142c..e92860c3 100644 --- a/app/models/wk_tax.rb +++ b/app/models/wk_tax.rb @@ -15,8 +15,8 @@ # along with this program; if not, write to the Free Software # Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. -class WkTax < ActiveRecord::Base - unloadable +class WkTax < ApplicationRecord + has_many :wk_project_taxes, foreign_key: "tax_id", class_name: "WkAccProjectTax", :dependent => :destroy has_many :product_taxes, foreign_key: "tax_id", class_name: "WkProductTax", :dependent => :destroy end diff --git a/app/models/wk_te_lock.rb b/app/models/wk_te_lock.rb index 252aeb2a..65d484f4 100644 --- a/app/models/wk_te_lock.rb +++ b/app/models/wk_te_lock.rb @@ -1,5 +1,5 @@ -class WkTeLock < ActiveRecord::Base - unloadable +class WkTeLock < ApplicationRecord + include Redmine::SafeAttributes belongs_to :creator, :class_name => 'User', :foreign_key => 'locked_by' belongs_to :updater, :class_name => 'User', :foreign_key => 'updated_by' @@ -7,11 +7,11 @@ class WkTeLock < ActiveRecord::Base # attr_protected :locked_by, :updated_by validates_presence_of :lock_date - + def initialize(attributes=nil, *args) super end - + def lock_date=(date) super if lock_date.is_a?(Time) diff --git a/app/models/wk_user.rb b/app/models/wk_user.rb index b86c85c4..22efe91c 100644 --- a/app/models/wk_user.rb +++ b/app/models/wk_user.rb @@ -15,7 +15,7 @@ # along with this program; if not, write to the Free Software # Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. -class WkUser < ActiveRecord::Base +class WkUser < ApplicationRecord include Redmine::SafeAttributes serialize :others require 'yaml' diff --git a/app/models/wk_user_leave.rb b/app/models/wk_user_leave.rb index 05491e2c..9168ef7a 100644 --- a/app/models/wk_user_leave.rb +++ b/app/models/wk_user_leave.rb @@ -15,8 +15,8 @@ # along with this program; if not, write to the Free Software # Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. -class WkUserLeave < ActiveRecord::Base - unloadable +class WkUserLeave < ApplicationRecord + include Redmine::SafeAttributes belongs_to :user belongs_to :issue, :class_name => 'Issue', :foreign_key => 'issue_id' diff --git a/app/models/wk_user_notification.rb b/app/models/wk_user_notification.rb index 3a34b10d..116799f4 100644 --- a/app/models/wk_user_notification.rb +++ b/app/models/wk_user_notification.rb @@ -15,7 +15,7 @@ # along with this program; if not, write to the Free Software # Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. -class WkUserNotification < ActiveRecord::Base +class WkUserNotification < ApplicationRecord belongs_to :notification , :class_name => 'WkNotification', :foreign_key => 'notify_id' belongs_to :source, :polymorphic => true diff --git a/app/models/wk_user_salary_components.rb b/app/models/wk_user_salary_components.rb index cee7e957..e6ee06b2 100644 --- a/app/models/wk_user_salary_components.rb +++ b/app/models/wk_user_salary_components.rb @@ -15,8 +15,8 @@ # along with this program; if not, write to the Free Software # Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. -class WkUserSalaryComponents < ActiveRecord::Base - unloadable +class WkUserSalaryComponents < ApplicationRecord + include Redmine::SafeAttributes belongs_to :user diff --git a/app/models/wkexpense.rb b/app/models/wkexpense.rb index 4289b68e..fbc020e9 100644 --- a/app/models/wkexpense.rb +++ b/app/models/wkexpense.rb @@ -16,18 +16,18 @@ # Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. class Wkexpense < Wktime - unloadable - + + self.table_name = "wkexpenses" - + validates_numericality_of :amount, :allow_nil => true, :message => :invalid - + #hours function of Wktime(base class) is overrided to use amount column of Wkexpense - + def validate_wktime errors.add :amount, :invalid if amount && (amount < 0) - end - + end + def hours=(h) write_attribute :amount, (h.is_a?(String) ? (h.to_i || h) : h) end diff --git a/app/models/wktime.rb b/app/models/wktime.rb index f144bba7..06196f0a 100644 --- a/app/models/wktime.rb +++ b/app/models/wktime.rb @@ -15,16 +15,16 @@ # along with this program; if not, write to the Free Software # Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. -class Wktime < ActiveRecord::Base -unloadable +class Wktime < ApplicationRecord + include Redmine::SafeAttributes belongs_to :user belongs_to :submitter, :class_name => 'User', :foreign_key => 'submitter_id' belongs_to :updater, :class_name => 'User', :foreign_key => 'statusupdater_id' - + acts_as_customizable - + # attr_protected :user_id, :submitter_id, :statusupdater_id safe_attributes 'hours', 'notes', 'begin_date', 'status', 'submitted_on', 'statusupdate_on' @@ -36,14 +36,14 @@ class Wktime < ActiveRecord::Base def initialize(attributes=nil, *args) super end - + def validate_wktime errors.add :hours, :invalid if hours && (hours < 0 || hours >= 1000) # errors.add :user_id, :invalid if user.nil? # errors.add :submitter_id, :invalid if submitter.nil? # errors.add :statusupdater_id, :invalid if approver.nil? end - + def hours=(h) write_attribute :hours, (h.is_a?(String) ? (h.to_hours || h) : h) end @@ -63,7 +63,7 @@ def submitted_on=(date) self.submitted_on = submitted_on.to_date end end - + def statusupdate_on=(date) super if statusupdate_on.is_a?(Time) diff --git a/app/views/timelog/report.html.erb b/app/views/timelog/report.html.erb index 0f888c10..852b8970 100644 --- a/app/views/timelog/report.html.erb +++ b/app/views/timelog/report.html.erb @@ -1,11 +1,11 @@
-<%= link_to l(:button_log_time), +<%= link_to sprite_icon('time-add', l(:button_log_time)), _new_time_entry_path(@project, @issue), :class => 'icon icon-time-add' if User.current.allowed_to?(:log_time, @project, :global => true) %>

<%= @query.new_record? ? l(:label_spent_time) : @query.name %>

- + <%= form_tag(_report_time_entries_path(@project, nil), :method => :get, :id => 'query_form') do %> @@ -29,8 +29,7 @@ <% if params[:spent_type].blank? || params[:spent_type] == "T" %>