increment.rb 2.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687
  1. # Copyright (C) 2012-2014 Zammad Foundation, http://zammad-foundation.org/
  2. module Ticket::Number::Increment
  3. extend self
  4. def generate
  5. # get config
  6. config = Setting.get('ticket_number_increment')
  7. # read counter
  8. min_digs = config[:min_size] || 4;
  9. counter_increment = nil
  10. Ticket::Counter.transaction do
  11. counter = Ticket::Counter.where( :generator => 'Increment' ).lock(true).first
  12. if !counter
  13. counter = Ticket::Counter.new( :generator => 'Increment', :content => '0' )
  14. end
  15. counter_increment = counter.content.to_i
  16. # increase counter
  17. counter_increment += 1
  18. # store new counter value
  19. counter.content = counter_increment.to_s
  20. counter.save
  21. end
  22. # fill up number counter
  23. if config[:checksum]
  24. min_digs = min_digs.to_i - 1
  25. end
  26. fillup = Setting.get('system_id') || '1'
  27. ( 1..100 ).each do |i|
  28. if ( fillup.length.to_i + counter_increment.to_s.length.to_i ) < min_digs.to_i
  29. fillup = fillup + '0'
  30. end
  31. end
  32. number = fillup.to_s + counter_increment.to_s
  33. # calculate a checksum
  34. # The algorithm to calculate the checksum is derived from the one
  35. # Deutsche Bundesbahn (german railway company) uses for calculation
  36. # of the check digit of their vehikel numbering.
  37. # The checksum is calculated by alternately multiplying the digits
  38. # with 1 and 2 and adding the resulsts from left to right of the
  39. # vehikel number. The modulus to 10 of this sum is substracted from
  40. # 10. See: http://www.pruefziffernberechnung.de/F/Fahrzeugnummer.shtml
  41. # (german)
  42. if config[:checksum]
  43. chksum = 0
  44. mult = 1
  45. (1..number.length).each do |i|
  46. digit = number.to_s[i, 1]
  47. chksum = chksum + ( mult * digit.to_i )
  48. mult += 1
  49. if mult == 3
  50. mult = 1
  51. end
  52. end
  53. chksum %= 10
  54. chksum = 10 - chksum
  55. if chksum == 10
  56. chksum = 1
  57. end
  58. number += chksum.to_s
  59. end
  60. return number
  61. end
  62. def check(string)
  63. # get config
  64. system_id = Setting.get('system_id') || ''
  65. ticket_hook = Setting.get('ticket_hook')
  66. ticket_hook_divider = Setting.get('ticket_hook_divider') || ''
  67. ticket = nil
  68. # probe format
  69. if string =~ /#{ticket_hook}#{ticket_hook_divider}(#{system_id}\d{2,48})/i then
  70. ticket = Ticket.where( :number => $1 ).first
  71. elsif string =~ /#{ticket_hook}\s{0,2}(#{system_id}\d{2,48})/i then
  72. ticket = Ticket.where( :number => $1 ).first
  73. end
  74. return ticket
  75. end
  76. end