otrs2.rb 25 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968
  1. module Import
  2. end
  3. module Import::OTRS2
  4. =begin
  5. result = request_json('Subaction=List', 1)
  6. return
  7. { some json structure }
  8. result = request_json('Subaction=List')
  9. return
  10. "some data string"
  11. =end
  12. def self.request_json(part, data_only = false)
  13. response = request(part)
  14. if !response
  15. raise "Can't connect to Zammad Migrator"
  16. end
  17. if !response.success?
  18. raise "Can't connect to Zammad Migrator"
  19. end
  20. result = json(response)
  21. if !result
  22. raise "Invalid response"
  23. end
  24. if data_only
  25. result['Result']
  26. else
  27. result
  28. end
  29. end
  30. =begin
  31. start get request to backend, add auth data automatically
  32. result = request('Subaction=List')
  33. return
  34. "some data string"
  35. =end
  36. def self.request(part)
  37. url = Setting.get('import_otrs_endpoint') + part + ';Key=' + Setting.get('import_otrs_endpoint_key')
  38. puts 'GET: ' + url
  39. response = UserAgent.request(
  40. url,
  41. {
  42. :user => Setting.get('import_otrs_user'),
  43. :password => Setting.get('import_otrs_password'),
  44. },
  45. )
  46. if !response.success?
  47. puts "ERROR: #{response.error}"
  48. return
  49. end
  50. response
  51. end
  52. =begin
  53. start post request to backend, add auth data automatically
  54. result = request('Subaction=List')
  55. return
  56. "some data string"
  57. =end
  58. def self.post(data)
  59. url = Setting.get('import_otrs_endpoint')
  60. data['Key'] = Setting.get('import_otrs_endpoint_key')
  61. puts 'POST: ' + url
  62. response = UserAgent.request(
  63. url,
  64. {
  65. :method => 'post',
  66. :data => data,
  67. :user => Setting.get('import_otrs_user'),
  68. :password => Setting.get('import_otrs_password'),
  69. },
  70. )
  71. if !response.success?
  72. puts "ERROR: #{response.error}"
  73. return
  74. end
  75. response
  76. end
  77. =begin
  78. start post request to backend, add auth data automatically
  79. result = json('some response string')
  80. return
  81. {}
  82. =end
  83. def self.json(response)
  84. data = Encode.conv( 'utf8', response.body.to_s )
  85. JSON.parse( data )
  86. end
  87. def self.load( object, limit = '', offset = '' )
  88. request_json( ";Subaction=Export;Object=#{object};Limit=#{limit};Offset=#{offset}", 1 )
  89. end
  90. =begin
  91. start get request to backend to check connection
  92. result = connection_test
  93. return
  94. true | false
  95. =end
  96. def self.connection_test
  97. return self.request_json('')
  98. end
  99. =begin
  100. get object statisitic from server ans save it in cache
  101. result = get_statisitic('Subaction=List')
  102. return
  103. {
  104. 'Ticket' => 1234,
  105. 'User' => 123,
  106. 'SomeObject' => 999,
  107. }
  108. =end
  109. def self.get_statisitic
  110. # check cache
  111. cache = Cache.get('import_otrs_stats')
  112. if cache
  113. return cache
  114. end
  115. # retrive statistic
  116. statistic = self.request_json(';Subaction=List', 1)
  117. if statistic
  118. Cache.write('import_otrs_stats', statistic)
  119. end
  120. statistic
  121. end
  122. =begin
  123. return current import state
  124. result = get_current_state
  125. return
  126. {
  127. :Ticket => {
  128. :total => 1234,
  129. :done => 13,
  130. },
  131. :Base => {
  132. :total => 1234,
  133. :done => 13,
  134. },
  135. }
  136. =end
  137. def self.get_current_state
  138. data = self.get_statisitic
  139. base = Group.count + Ticket::State.count + Ticket::Priority.count
  140. base_total = data['Queue'] + data['State'] + data['Priority']
  141. user = User.count
  142. user_total = data['User'] + data['CustomerUser']
  143. data = {
  144. :Base => {
  145. :done => base,
  146. :total => base_total || 0,
  147. },
  148. :User => {
  149. :done => user,
  150. :total => user_total || 0,
  151. },
  152. :Ticket => {
  153. :done => Ticket.count,
  154. :total => data['Ticket'] || 0,
  155. },
  156. }
  157. data
  158. end
  159. #
  160. # start import
  161. #
  162. # Import::OTRS2.start
  163. #
  164. def self.start
  165. puts 'Start import...'
  166. # check if system is in import mode
  167. if !Setting.get('import_mode')
  168. raise "System is not in import mode!"
  169. end
  170. result = request_json('')
  171. if !result['Success']
  172. "API key not valid!"
  173. end
  174. # create states
  175. records = load('State')
  176. state(records)
  177. # create priorities
  178. records = load('Priority')
  179. priority(records)
  180. # create groups
  181. records = load('Queue')
  182. ticket_group(records)
  183. # create agents
  184. records = load('User')
  185. user(records)
  186. # create customers
  187. count = 0
  188. steps = 30
  189. run = true
  190. while run
  191. count += steps
  192. records = load('CustomerUser', steps, count-steps)
  193. if !records || !records[0]
  194. puts "all customers imported."
  195. run = false
  196. next
  197. end
  198. customer(records)
  199. end
  200. Thread.abort_on_exception = true
  201. thread_count = 8
  202. threads = {}
  203. count = 0
  204. locks = { :User => {} }
  205. (1..thread_count).each {|thread|
  206. threads[thread] = Thread.new {
  207. sleep thread * 3
  208. puts "Started import thread# #{thread} ..."
  209. run = true
  210. steps = 20
  211. while run
  212. count += steps
  213. sleep 1
  214. puts "loading... thread# #{thread} ..."
  215. offset = count-steps
  216. if offset != 0
  217. offset = count - steps + 1
  218. end
  219. records = load( 'Ticket', steps, count-steps )
  220. if !records || !records[0]
  221. puts "... thread# #{thread}, no more work."
  222. run = false
  223. next
  224. end
  225. _ticket_result(records, locks)
  226. end
  227. }
  228. }
  229. (1..thread_count).each {|thread|
  230. threads[thread].join
  231. }
  232. Setting.set( 'system_init_done', true )
  233. #Setting.set( 'import_mode', false )
  234. true
  235. end
  236. def self.diff_worker
  237. return if !Setting.get('import_mode')
  238. return if Setting.get('import_otrs_endpoint') == 'http://otrs_host/otrs'
  239. self.diff
  240. end
  241. def self.diff
  242. puts 'Start diff...'
  243. # check if system is in import mode
  244. if !Setting.get('import_mode')
  245. raise "System is not in import mode!"
  246. end
  247. # create states
  248. state
  249. # create priorities
  250. priority
  251. # create groups
  252. ticket_group
  253. # create agents
  254. user
  255. self.ticket_diff
  256. return
  257. end
  258. def self.ticket_diff()
  259. url = "public.pl?Action=Export;Type=TicketDiff;Limit=30"
  260. response = request( url )
  261. return if !response
  262. return if !response.success?
  263. result = json(response)
  264. self._ticket_result(result)
  265. end
  266. def self.ticket(ticket_ids)
  267. url = "public.pl?Action=Export;Type=Ticket;"
  268. ticket_ids.each {|ticket_id|
  269. url = url + "TicketID=#{CGI::escape ticket_id};"
  270. }
  271. response = request( url )
  272. return if !response
  273. return if !response.success?
  274. result = json(response)
  275. self._ticket_result(result)
  276. end
  277. def self._ticket_result(result, locks)
  278. # puts result.inspect
  279. map = {
  280. :Ticket => {
  281. :Changed => :updated_at,
  282. :Created => :created_at,
  283. :CreateBy => :created_by_id,
  284. :TicketNumber => :number,
  285. :QueueID => :group_id,
  286. :StateID => :state_id,
  287. :PriorityID => :priority_id,
  288. :Owner => :owner,
  289. :CustomerUserID => :customer,
  290. :Title => :title,
  291. :TicketID => :id,
  292. :FirstResponse => :first_response,
  293. # :FirstResponseTimeDestinationDate => :first_response_escal_date,
  294. # :FirstResponseInMin => :first_response_in_min,
  295. # :FirstResponseDiffInMin => :first_response_diff_in_min,
  296. :Closed => :close_time,
  297. # :SoltutionTimeDestinationDate => :close_time_escal_date,
  298. # :CloseTimeInMin => :close_time_in_min,
  299. # :CloseTimeDiffInMin => :close_time_diff_in_min,
  300. },
  301. :Article => {
  302. :SenderType => :sender,
  303. :ArticleType => :type,
  304. :TicketID => :ticket_id,
  305. :ArticleID => :id,
  306. :Body => :body,
  307. :From => :from,
  308. :To => :to,
  309. :Cc => :cc,
  310. :Subject => :subject,
  311. :InReplyTo => :in_reply_to,
  312. :MessageID => :message_id,
  313. # :ReplyTo => :reply_to,
  314. :References => :references,
  315. :Changed => :updated_at,
  316. :Created => :created_at,
  317. :ChangedBy => :updated_by_id,
  318. :CreatedBy => :created_by_id,
  319. },
  320. }
  321. result.each {|record|
  322. ticket_new = {
  323. :title => '',
  324. :created_by_id => 1,
  325. :updated_by_id => 1,
  326. }
  327. map[:Ticket].each { |key,value|
  328. if record[key.to_s] && record[key.to_s].class == String
  329. ticket_new[value] = Encode.conv( 'utf8', record[key.to_s] )
  330. else
  331. ticket_new[value] = record[key.to_s]
  332. end
  333. }
  334. ticket_old = Ticket.where( :id => ticket_new[:id] ).first
  335. # find owner
  336. if ticket_new[:owner]
  337. user = User.lookup( :login => ticket_new[:owner] )
  338. if user
  339. ticket_new[:owner_id] = user.id
  340. else
  341. ticket_new[:owner_id] = 1
  342. end
  343. ticket_new.delete(:owner)
  344. end
  345. # find customer
  346. if ticket_new[:customer]
  347. user = User.lookup( :login => ticket_new[:customer] )
  348. if user
  349. ticket_new[:customer_id] = user.id
  350. else
  351. ticket_new[:customer_id] = 1
  352. end
  353. ticket_new.delete(:customer)
  354. else
  355. ticket_new[:customer_id] = 1
  356. end
  357. # set state types
  358. if ticket_old
  359. puts "update Ticket.find(#{ticket_new[:id]})"
  360. ticket_old.update_attributes(ticket_new)
  361. else
  362. puts "add Ticket.find(#{ticket_new[:id]})"
  363. ticket = Ticket.new(ticket_new)
  364. ticket.id = ticket_new[:id]
  365. ticket.save
  366. end
  367. record['Articles'].each { |article|
  368. # get article values
  369. article_new = {
  370. :created_by_id => 1,
  371. :updated_by_id => 1,
  372. }
  373. map[:Article].each { |key,value|
  374. if article[key.to_s]
  375. article_new[value] = Encode.conv( 'utf8', article[key.to_s] )
  376. end
  377. }
  378. # create customer/sender if needed
  379. if article_new[:sender] == 'customer' && article_new[:created_by_id].to_i == 1 && !article_new[:from].empty?
  380. email = nil
  381. begin
  382. email = Mail::Address.new( article_new[:from] ).address
  383. rescue
  384. email = article_new[:from]
  385. if article_new[:from] =~ /<(.+?)>/
  386. email = $1
  387. end
  388. end
  389. # create article user if not exists
  390. while locks[:User][ email ]
  391. puts "user #{email} is locked"
  392. sleep 1
  393. end
  394. # lock user
  395. locks[:User][ email ] = true
  396. user = User.where( :email => email ).first
  397. if !user
  398. user = User.where( :login => email ).first
  399. end
  400. if !user
  401. begin
  402. display_name = Mail::Address.new( article_new[:from] ).display_name ||
  403. ( Mail::Address.new( article_new[:from] ).comments && Mail::Address.new( article_new[:from] ).comments[0] )
  404. rescue
  405. display_name = article_new[:from]
  406. end
  407. # do extra decoding because we needed to use field.value
  408. display_name = Mail::Field.new( 'X-From', display_name ).to_s
  409. roles = Role.lookup( :name => 'Customer' )
  410. user = User.create(
  411. :login => email,
  412. :firstname => display_name,
  413. :lastname => '',
  414. :email => email,
  415. :password => '',
  416. :active => true,
  417. :role_ids => [roles.id],
  418. :updated_by_id => 1,
  419. :created_by_id => 1,
  420. )
  421. end
  422. article_new[:created_by_id] = user.id
  423. # unlock user
  424. locks[:User][ email ] = false
  425. end
  426. if article_new[:sender] == 'customer'
  427. article_new[:sender_id] = Ticket::Article::Sender.lookup( :name => 'Customer' ).id
  428. article_new.delete( :sender )
  429. end
  430. if article_new[:sender] == 'agent'
  431. article_new[:sender_id] = Ticket::Article::Sender.lookup( :name => 'Agent' ).id
  432. article_new.delete( :sender )
  433. end
  434. if article_new[:sender] == 'system'
  435. article_new[:sender_id] = Ticket::Article::Sender.lookup( :name => 'System' ).id
  436. article_new.delete( :sender )
  437. end
  438. if article_new[:type] == 'email-external'
  439. article_new[:type_id] = Ticket::Article::Type.lookup( :name => 'email' ).id
  440. article_new[:internal] = false
  441. elsif article_new[:type] == 'email-internal'
  442. article_new[:type_id] = Ticket::Article::Type.lookup( :name => 'email' ).id
  443. article_new[:internal] = true
  444. elsif article_new[:type] == 'note-external'
  445. article_new[:type_id] = Ticket::Article::Type.lookup( :name => 'note' ).id
  446. article_new[:internal] = false
  447. elsif article_new[:type] == 'note-internal'
  448. article_new[:type_id] = Ticket::Article::Type.lookup( :name => 'note' ).id
  449. article_new[:internal] = true
  450. elsif article_new[:type] == 'phone'
  451. article_new[:type_id] = Ticket::Article::Type.lookup( :name => 'phone' ).id
  452. article_new[:internal] = false
  453. elsif article_new[:type] == 'webrequest'
  454. article_new[:type_id] = Ticket::Article::Type.lookup( :name => 'web' ).id
  455. article_new[:internal] = false
  456. else
  457. article_new[:type_id] = 9
  458. end
  459. article_new.delete( :type )
  460. article_old = Ticket::Article.where( :id => article_new[:id] ).first
  461. # set state types
  462. if article_old
  463. puts "update Ticket::Article.find(#{article_new[:id]})"
  464. article_old.update_attributes(article_new)
  465. else
  466. puts "add Ticket::Article.find(#{article_new[:id]})"
  467. article = Ticket::Article.new(article_new)
  468. article.id = article_new[:id]
  469. article.save
  470. end
  471. }
  472. record['History'].each { |history|
  473. if history['HistoryType'] == 'NewTicket'
  474. History.add(
  475. :id => history['HistoryID'],
  476. :o_id => history['TicketID'],
  477. :history_type => 'created',
  478. :history_object => 'Ticket',
  479. :created_at => history['CreateTime'],
  480. :created_by_id => history['CreateBy']
  481. )
  482. end
  483. if history['HistoryType'] == 'StateUpdate'
  484. data = history['Name']
  485. # "%%new%%open%%"
  486. from = nil
  487. to = nil
  488. if data =~ /%%(.+?)%%(.+?)%%/
  489. from = $1
  490. to = $2
  491. state_from = Ticket::State.lookup( :name => from )
  492. state_to = Ticket::State.lookup( :name => to )
  493. if state_from
  494. from_id = state_from.id
  495. end
  496. if state_to
  497. to_id = state_to.id
  498. end
  499. end
  500. History.add(
  501. :id => history['HistoryID'],
  502. :o_id => history['TicketID'],
  503. :history_type => 'updated',
  504. :history_object => 'Ticket',
  505. :history_attribute => 'state',
  506. :value_from => from,
  507. :id_from => from_id,
  508. :value_to => to,
  509. :id_to => to_id,
  510. :created_at => history['CreateTime'],
  511. :created_by_id => history['CreateBy']
  512. )
  513. end
  514. if history['HistoryType'] == 'Move'
  515. data = history['Name']
  516. # "%%Queue1%%5%%Postmaster%%1"
  517. from = nil
  518. to = nil
  519. if data =~ /%%(.+?)%%(.+?)%%(.+?)%%(.+?)$/
  520. from = $1
  521. from_id = $2
  522. to = $3
  523. to_id = $4
  524. end
  525. History.add(
  526. :id => history['HistoryID'],
  527. :o_id => history['TicketID'],
  528. :history_type => 'updated',
  529. :history_object => 'Ticket',
  530. :history_attribute => 'group',
  531. :value_from => from,
  532. :value_to => to,
  533. :id_from => from_id,
  534. :id_to => to_id,
  535. :created_at => history['CreateTime'],
  536. :created_by_id => history['CreateBy']
  537. )
  538. end
  539. if history['HistoryType'] == 'PriorityUpdate'
  540. data = history['Name']
  541. # "%%3 normal%%3%%5 very high%%5"
  542. from = nil
  543. to = nil
  544. if data =~ /%%(.+?)%%(.+?)%%(.+?)%%(.+?)$/
  545. from = $1
  546. from_id = $2
  547. to = $3
  548. to_id = $4
  549. end
  550. History.add(
  551. :id => history['HistoryID'],
  552. :o_id => history['TicketID'],
  553. :history_type => 'updated',
  554. :history_object => 'Ticket',
  555. :history_attribute => 'priority',
  556. :value_from => from,
  557. :value_to => to,
  558. :id_from => from_id,
  559. :id_to => to_id,
  560. :created_at => history['CreateTime'],
  561. :created_by_id => history['CreateBy']
  562. )
  563. end
  564. if history['ArticleID'] && history['ArticleID'] != 0
  565. History.add(
  566. :id => history['HistoryID'],
  567. :o_id => history['ArticleID'],
  568. :history_type => 'created',
  569. :history_object => 'Ticket::Article',
  570. :related_o_id => history['TicketID'],
  571. :related_history_object => 'Ticket',
  572. :created_at => history['CreateTime'],
  573. :created_by_id => history['CreateBy']
  574. )
  575. end
  576. }
  577. }
  578. end
  579. # sync ticket states
  580. def self.state(records)
  581. map = {
  582. :ChangeTime => :updated_at,
  583. :CreateTime => :created_at,
  584. :CreateBy => :created_by_id,
  585. :ChangeBy => :updated_by_id,
  586. :Name => :name,
  587. :ID => :id,
  588. :ValidID => :active,
  589. :Comment => :note,
  590. };
  591. # rename states to handle not uniq issues
  592. Ticket::State.all.each {|state|
  593. state.name = state.name + '_tmp'
  594. state.save
  595. }
  596. records.each { |state|
  597. _set_valid(state)
  598. # get new attributes
  599. state_new = {
  600. :created_by_id => 1,
  601. :updated_by_id => 1,
  602. }
  603. map.each { |key,value|
  604. if state[key.to_s]
  605. state_new[value] = state[key.to_s]
  606. end
  607. }
  608. # check if state already exists
  609. state_old = Ticket::State.where( :id => state_new[:id] ).first
  610. # puts 'st: ' + state['TypeName']
  611. # set state types
  612. if state['TypeName'] == 'pending auto'
  613. state['TypeName'] = 'pending action'
  614. end
  615. state_type = Ticket::StateType.where( :name => state['TypeName'] ).first
  616. state_new[:state_type_id] = state_type.id
  617. if state_old
  618. # puts 'TS: ' + state_new.inspect
  619. state_old.update_attributes(state_new)
  620. else
  621. state = Ticket::State.new(state_new)
  622. state.id = state_new[:id]
  623. state.save
  624. end
  625. }
  626. end
  627. # sync ticket priorities
  628. def self.priority(records)
  629. map = {
  630. :ChangeTime => :updated_at,
  631. :CreateTime => :created_at,
  632. :CreateBy => :created_by_id,
  633. :ChangeBy => :updated_by_id,
  634. :Name => :name,
  635. :ID => :id,
  636. :ValidID => :active,
  637. :Comment => :note,
  638. };
  639. records.each { |priority|
  640. _set_valid(priority)
  641. # get new attributes
  642. priority_new = {
  643. :created_by_id => 1,
  644. :updated_by_id => 1,
  645. }
  646. map.each { |key,value|
  647. if priority[key.to_s]
  648. priority_new[value] = priority[key.to_s]
  649. end
  650. }
  651. # check if state already exists
  652. priority_old = Ticket::Priority.where( :id => priority_new[:id] ).first
  653. # set state types
  654. if priority_old
  655. priority_old.update_attributes(priority_new)
  656. else
  657. priority = Ticket::Priority.new(priority_new)
  658. priority.id = priority_new[:id]
  659. priority.save
  660. end
  661. }
  662. end
  663. # sync ticket groups / queues
  664. def self.ticket_group(records)
  665. map = {
  666. :ChangeTime => :updated_at,
  667. :CreateTime => :created_at,
  668. :CreateBy => :created_by_id,
  669. :ChangeBy => :updated_by_id,
  670. :Name => :name,
  671. :QueueID => :id,
  672. :ValidID => :active,
  673. :Comment => :note,
  674. };
  675. records.each { |group|
  676. _set_valid(group)
  677. # get new attributes
  678. group_new = {
  679. :created_by_id => 1,
  680. :updated_by_id => 1,
  681. }
  682. map.each { |key,value|
  683. if group[key.to_s]
  684. group_new[value] = group[key.to_s]
  685. end
  686. }
  687. # check if state already exists
  688. group_old = Group.where( :id => group_new[:id] ).first
  689. # set state types
  690. if group_old
  691. group_old.update_attributes(group_new)
  692. else
  693. group = Group.new(group_new)
  694. group.id = group_new[:id]
  695. group.save
  696. end
  697. }
  698. end
  699. # sync agents
  700. def self.user(records)
  701. map = {
  702. :ChangeTime => :updated_at,
  703. :CreateTime => :created_at,
  704. :CreateBy => :created_by_id,
  705. :ChangeBy => :updated_by_id,
  706. :UserID => :id,
  707. :ValidID => :active,
  708. :Comment => :note,
  709. :UserEmail => :email,
  710. :UserFirstname => :firstname,
  711. :UserLastname => :lastname,
  712. # :UserTitle =>
  713. :UserLogin => :login,
  714. :UserPw => :password,
  715. };
  716. role = Role.lookup( :name => 'Agent' )
  717. records.each { |user|
  718. _set_valid(user)
  719. # get new attributes
  720. user_new = {
  721. :created_by_id => 1,
  722. :updated_by_id => 1,
  723. :source => 'OTRS Import',
  724. :role_ids => [ role.id ],
  725. }
  726. map.each { |key,value|
  727. if user[key.to_s]
  728. user_new[value] = user[key.to_s]
  729. end
  730. }
  731. if user_new[:password]
  732. user_new[:password] = "{sha2}#{user_new[:password]}"
  733. end
  734. # check if agent already exists
  735. user_old = User.where( :id => user_new[:id] ).first
  736. # create / update agent
  737. if user_old
  738. puts "update User.find(#{user_old[:id]})"
  739. # only update roles if different (reduce sql statements)
  740. if user_old.role_ids == user_new[:role_ids]
  741. user_new.delete( :role_ids )
  742. end
  743. user_old.update_attributes(user_new)
  744. else
  745. puts "add User.find(#{user_new[:id]})"
  746. user = User.new(user_new)
  747. user.id = user_new[:id]
  748. user.save
  749. end
  750. }
  751. end
  752. # sync customers
  753. def self.customer(records)
  754. map = {
  755. :ChangeTime => :updated_at,
  756. :CreateTime => :created_at,
  757. :CreateBy => :created_by_id,
  758. :ChangeBy => :updated_by_id,
  759. :ValidID => :active,
  760. :UserComment => :note,
  761. :UserEmail => :email,
  762. :UserFirstname => :firstname,
  763. :UserLastname => :lastname,
  764. # :UserTitle =>
  765. :UserLogin => :login,
  766. :UserPassword => :password,
  767. :UserPhone => :phone,
  768. :UserFax => :fax,
  769. :UserMobile => :mobile,
  770. :UserStreet => :street,
  771. :UserZip => :zip,
  772. :UserCity => :city,
  773. :UserCountry => :country,
  774. };
  775. role_agent = Role.lookup( :name => 'Agent' )
  776. role_customer = Role.lookup( :name => 'Customer' )
  777. records.each { |user|
  778. _set_valid(user)
  779. # get new attributes
  780. user_new = {
  781. :created_by_id => 1,
  782. :updated_by_id => 1,
  783. :source => 'OTRS Import',
  784. :role_ids => [ role_customer.id ],
  785. }
  786. map.each { |key,value|
  787. if user[key.to_s]
  788. user_new[value] = user[key.to_s]
  789. end
  790. }
  791. # check if customer already exists
  792. user_old = User.where( :login => user_new[:login] ).first
  793. # create / update agent
  794. if user_old
  795. # do not update user if it is already agent
  796. if !user_old.role_ids.include?( role_agent.id )
  797. # only update roles if different (reduce sql statements)
  798. if user_old.role_ids == user_new[:role_ids]
  799. user_new.delete( :role_ids )
  800. end
  801. puts "update User.find(#{user_old[:id]})"
  802. user_old.update_attributes(user_new)
  803. end
  804. else
  805. puts "add User.find(#{user_new[:id]})"
  806. user = User.new(user_new)
  807. user.save
  808. end
  809. }
  810. end
  811. # set translate valid ids to active = true|false
  812. def self._set_valid(record)
  813. # map
  814. if record['ValidID'].to_s == '3'
  815. record['ValidID'] = '2'
  816. end
  817. if record['ValidID'].to_s == '2'
  818. record['ValidID'] = false
  819. end
  820. if record['ValidID'].to_s == '1'
  821. record['ValidID'] = true
  822. end
  823. if record['ValidID'].to_s == '0'
  824. record['ValidID'] = false
  825. end
  826. end
  827. end