/
ticket.rb
1611 lines (1331 loc) · 54.1 KB
/
ticket.rb
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
# Copyright (C) 2012-2016 Zammad Foundation, http://zammad-foundation.org/
class Ticket < ApplicationModel
include CanBeImported
include HasActivityStreamLog
include ChecksClientNotification
include ChecksLatestChangeObserved
include CanCsvImport
include ChecksHtmlSanitized
include HasHistory
include HasTags
include HasSearchIndexBackend
include HasOnlineNotifications
include HasKarmaActivityLog
include HasLinks
include HasObjectManagerAttributesValidation
include Ticket::Escalation
include Ticket::Subject
include Ticket::Assets
include Ticket::SearchIndex
include Ticket::Search
store :preferences
before_create :check_generate, :check_defaults, :check_title, :set_default_state, :set_default_priority
before_update :check_defaults, :check_title, :reset_pending_time, :check_owner_active
validates :group_id, presence: true
activity_stream_permission 'ticket.agent'
activity_stream_attributes_ignored :organization_id, # organization_id will change automatically on user update
:create_article_type_id,
:create_article_sender_id,
:article_count,
:first_response_at,
:first_response_escalation_at,
:first_response_in_min,
:first_response_diff_in_min,
:close_at,
:close_escalation_at,
:close_in_min,
:close_diff_in_min,
:update_escalation_at,
:update_in_min,
:update_diff_in_min,
:last_contact_at,
:last_contact_agent_at,
:last_contact_customer_at,
:last_owner_update_at,
:preferences
history_attributes_ignored :create_article_type_id,
:create_article_sender_id,
:article_count,
:preferences
history_relation_object 'Ticket::Article'
sanitized_html :note
belongs_to :group, optional: true
belongs_to :organization, optional: true
has_many :articles, class_name: 'Ticket::Article', after_add: :cache_update, after_remove: :cache_update, dependent: :destroy, inverse_of: :ticket
has_many :ticket_time_accounting, class_name: 'Ticket::TimeAccounting', dependent: :destroy, inverse_of: :ticket
belongs_to :state, class_name: 'Ticket::State', optional: true
belongs_to :priority, class_name: 'Ticket::Priority', optional: true
belongs_to :owner, class_name: 'User', optional: true
belongs_to :customer, class_name: 'User', optional: true
belongs_to :created_by, class_name: 'User', optional: true
belongs_to :updated_by, class_name: 'User', optional: true
belongs_to :create_article_type, class_name: 'Ticket::Article::Type', optional: true
belongs_to :create_article_sender, class_name: 'Ticket::Article::Sender', optional: true
self.inheritance_column = nil
attr_accessor :callback_loop
=begin
get user access conditions
conditions = Ticket.access_condition( User.find(1) , 'full')
returns
result = [user1, user2, ...]
=end
def self.access_condition(user, access)
if user.permissions?('ticket.agent')
['group_id IN (?)', user.group_ids_access(access)]
elsif !user.organization || ( !user.organization.shared || user.organization.shared == false )
['tickets.customer_id = ?', user.id]
else
['(tickets.customer_id = ? OR tickets.organization_id = ?)', user.id, user.organization.id]
end
end
=begin
processes tickets which have reached their pending time and sets next state_id
processed_tickets = Ticket.process_pending
returns
processed_tickets = [<Ticket>, ...]
=end
def self.process_pending
result = []
# process pending action tickets
pending_action = Ticket::StateType.find_by(name: 'pending action')
ticket_states_pending_action = Ticket::State.where(state_type_id: pending_action)
.where.not(next_state_id: nil)
if ticket_states_pending_action.present?
next_state_map = {}
ticket_states_pending_action.each do |state|
next_state_map[state.id] = state.next_state_id
end
tickets = where(state_id: next_state_map.keys)
.where('pending_time <= ?', Time.zone.now)
tickets.find_each(batch_size: 500) do |ticket|
Transaction.execute do
ticket.state_id = next_state_map[ticket.state_id]
ticket.updated_at = Time.zone.now
ticket.updated_by_id = 1
ticket.save!
end
result.push ticket
end
end
# process pending reminder tickets
pending_reminder = Ticket::StateType.find_by(name: 'pending reminder')
ticket_states_pending_reminder = Ticket::State.where(state_type_id: pending_reminder)
if ticket_states_pending_reminder.present?
reminder_state_map = {}
ticket_states_pending_reminder.each do |state|
reminder_state_map[state.id] = state.next_state_id
end
tickets = where(state_id: reminder_state_map.keys)
.where('pending_time <= ?', Time.zone.now)
tickets.find_each(batch_size: 500) do |ticket|
article_id = nil
article = Ticket::Article.last_customer_agent_article(ticket.id)
if article
article_id = article.id
end
# send notification
Transaction::BackgroundJob.run(
object: 'Ticket',
type: 'reminder_reached',
object_id: ticket.id,
article_id: article_id,
user_id: 1,
)
result.push ticket
end
end
result
end
=begin
processes escalated tickets
processed_tickets = Ticket.process_escalation
returns
processed_tickets = [<Ticket>, ...]
=end
def self.process_escalation
result = []
# fetch all escalated and soon to be escalating tickets
where('escalation_at <= ?', Time.zone.now + 15.minutes).find_each(batch_size: 500) do |ticket|
article_id = nil
article = Ticket::Article.last_customer_agent_article(ticket.id)
if article
article_id = article.id
end
# send escalation
if ticket.escalation_at < Time.zone.now
Transaction::BackgroundJob.run(
object: 'Ticket',
type: 'escalation',
object_id: ticket.id,
article_id: article_id,
user_id: 1,
)
result.push ticket
next
end
# check if warning need to be sent
Transaction::BackgroundJob.run(
object: 'Ticket',
type: 'escalation_warning',
object_id: ticket.id,
article_id: article_id,
user_id: 1,
)
result.push ticket
end
result
end
=begin
processes tickets which auto unassign time has reached
processed_tickets = Ticket.process_auto_unassign
returns
processed_tickets = [<Ticket>, ...]
=end
def self.process_auto_unassign
# process pending action tickets
state_ids = Ticket::State.by_category(:work_on).pluck(:id)
return [] if state_ids.blank?
result = []
groups = Group.where(active: true).where('assignment_timeout IS NOT NULL AND groups.assignment_timeout != 0')
return [] if groups.blank?
groups.each do |group|
next if group.assignment_timeout.blank?
ticket_ids = Ticket.where('state_id IN (?) AND owner_id != 1 AND group_id = ? AND last_owner_update_at IS NOT NULL', state_ids, group.id).limit(600).pluck(:id)
ticket_ids.each do |ticket_id|
ticket = Ticket.find_by(id: ticket_id)
next if !ticket
minutes_since_last_assignment = Time.zone.now - ticket.last_owner_update_at
next if (minutes_since_last_assignment / 60) <= group.assignment_timeout
Transaction.execute do
ticket.owner_id = 1
ticket.updated_at = Time.zone.now
ticket.updated_by_id = 1
ticket.save!
end
result.push ticket
end
end
result
end
=begin
merge tickets
ticket = Ticket.find(123)
result = ticket.merge_to(
ticket_id: 123,
user_id: 123,
)
returns
result = true|false
=end
def merge_to(data)
# prevent cross merging tickets
target_ticket = Ticket.find_by(id: data[:ticket_id])
raise 'no target ticket given' if !target_ticket
raise Exceptions::UnprocessableEntity, 'ticket already merged, no merge into merged ticket possible' if target_ticket.state.state_type.name == 'merged'
# check different ticket ids
raise Exceptions::UnprocessableEntity, 'Can\'t merge ticket with it self!' if id == target_ticket.id
# update articles
Transaction.execute do
Ticket::Article.where(ticket_id: id).each(&:touch)
# quiet update of reassign of articles
Ticket::Article.where(ticket_id: id).update_all(['ticket_id = ?', data[:ticket_id]]) # rubocop:disable Rails/SkipsModelValidations
# mark target ticket as updated
# otherwise the "received_merge" history entry
# will be the same as the last updated_at
# which might be a long time ago
target_ticket.updated_at = Time.zone.now
# add merge event to both ticket's history (Issue #2469 - Add information "Ticket merged" to History)
target_ticket.history_log(
'received_merge',
data[:user_id],
id_to: target_ticket.id,
id_from: id,
)
history_log(
'merged_into',
data[:user_id],
id_to: target_ticket.id,
id_from: id,
)
# create new merge article
Ticket::Article.create(
ticket_id: id,
type_id: Ticket::Article::Type.lookup(name: 'note').id,
sender_id: Ticket::Article::Sender.lookup(name: 'Agent').id,
body: 'merged',
internal: false,
created_by_id: data[:user_id],
updated_by_id: data[:user_id],
)
# reassign links to the new ticket
# rubocop:disable Rails/SkipsModelValidations
Link.where(
link_object_source_id: Link::Object.find_by(name: 'Ticket').id,
link_object_source_value: id,
).update_all(link_object_source_value: data[:ticket_id])
Link.where(
link_object_target_id: Link::Object.find_by(name: 'Ticket').id,
link_object_target_value: id,
).update_all(link_object_target_value: data[:ticket_id])
# rubocop:enable Rails/SkipsModelValidations
# link tickets
Link.add(
link_type: 'parent',
link_object_source: 'Ticket',
link_object_source_value: data[:ticket_id],
link_object_target: 'Ticket',
link_object_target_value: id
)
# set state to 'merged'
self.state_id = Ticket::State.lookup(name: 'merged').id
# rest owner
self.owner_id = 1
# save ticket
save!
# touch new ticket (to broadcast change)
target_ticket.touch # rubocop:disable Rails/SkipsModelValidations
end
true
end
=begin
check if online notification should be shown in general as already seen with current state
ticket = Ticket.find(1)
seen = ticket.online_notification_seen_state(user_id_check)
returns
result = true # or false
=end
def online_notification_seen_state(user_id_check = nil)
state = Ticket::State.lookup(id: state_id)
state_type = Ticket::StateType.lookup(id: state.state_type_id)
# always to set unseen for ticket owner and users which did not the update
if state_type.name != 'merged'
if user_id_check
return false if user_id_check == owner_id && user_id_check != updated_by_id
end
end
# set all to seen if pending action state is a closed or merged state
if state_type.name == 'pending action' && state.next_state_id
state = Ticket::State.lookup(id: state.next_state_id)
state_type = Ticket::StateType.lookup(id: state.state_type_id)
end
# set all to seen if new state is pending reminder state
if state_type.name == 'pending reminder'
if user_id_check
return false if owner_id == 1
return false if updated_by_id != owner_id && user_id_check == owner_id
return true
end
return true
end
# set all to seen if new state is a closed or merged state
return true if state_type.name == 'closed'
return true if state_type.name == 'merged'
false
end
=begin
get count of tickets and tickets which match on selector
ticket_count, tickets = Ticket.selectors(params[:condition], limit: limit, current_user: current_user, access: 'full')
=end
def self.selectors(selectors, options)
limit = options[:limit] || 10
current_user = options[:current_user]
access = options[:access] || 'full'
raise 'no selectors given' if !selectors
query, bind_params, tables = selector2sql(selectors, current_user: current_user, execution_time: options[:execution_time])
return [] if !query
ActiveRecord::Base.transaction(requires_new: true) do
if !current_user
ticket_count = Ticket.distinct.where(query, *bind_params).joins(tables).count
tickets = Ticket.distinct.where(query, *bind_params).joins(tables).limit(limit)
return [ticket_count, tickets]
end
access_condition = Ticket.access_condition(current_user, access)
ticket_count = Ticket.distinct.where(access_condition).where(query, *bind_params).joins(tables).count
tickets = Ticket.distinct.where(access_condition).where(query, *bind_params).joins(tables).limit(limit)
return [ticket_count, tickets]
rescue ActiveRecord::StatementInvalid => e
Rails.logger.error e
raise ActiveRecord::Rollback
end
[]
end
=begin
generate condition query to search for tickets based on condition
query_condition, bind_condition, tables = selector2sql(params[:condition], current_user: current_user)
condition example
{
'ticket.title' => {
operator: 'contains', # contains not
value: 'some value',
},
'ticket.state_id' => {
operator: 'is',
value: [1,2,5]
},
'ticket.created_at' => {
operator: 'after (absolute)', # after,before
value: '2015-10-17T06:00:00.000Z',
},
'ticket.created_at' => {
operator: 'within next (relative)', # within next, within last, after, before
range: 'day', # minute|hour|day|month|year
value: '25',
},
'ticket.owner_id' => {
operator: 'is', # is not
pre_condition: 'current_user.id',
},
'ticket.owner_id' => {
operator: 'is', # is not
pre_condition: 'specific',
value: 4711,
},
'ticket.escalation_at' => {
operator: 'is not', # not
value: nil,
},
'ticket.tags' => {
operator: 'contains all', # contains all|contains one|contains all not|contains one not
value: 'tag1, tag2',
},
}
=end
def self.selector2sql(selectors, options = {})
current_user = options[:current_user]
current_user_id = UserInfo.current_user_id
if current_user
current_user_id = current_user.id
end
return if !selectors
# remember query and bind params
query = ''
bind_params = []
like = Rails.application.config.db_like
if selectors.respond_to?(:permit!)
selectors = selectors.permit!.to_h
end
# get tables to join
tables = ''
selectors.each_key do |attribute|
selector = attribute.split(/\./)
next if !selector[1]
next if selector[0] == 'ticket'
next if selector[0] == 'execution_time'
next if tables.include?(selector[0])
if query != ''
query += ' AND '
end
if selector[0] == 'customer'
tables += ', users customers'
query += 'tickets.customer_id = customers.id'
elsif selector[0] == 'organization'
tables += ', organizations'
query += 'tickets.organization_id = organizations.id'
elsif selector[0] == 'owner'
tables += ', users owners'
query += 'tickets.owner_id = owners.id'
elsif selector[0] == 'article'
tables += ', ticket_articles articles'
query += 'tickets.id = articles.ticket_id'
elsif selector[0] == 'ticket_state'
tables += ', ticket_states'
query += 'tickets.state_id = ticket_states.id'
else
raise "invalid selector #{attribute.inspect}->#{selector.inspect}"
end
end
# add conditions
no_result = false
selectors.each do |attribute, selector_raw|
# validation
raise "Invalid selector #{selector_raw.inspect}" if !selector_raw
raise "Invalid selector #{selector_raw.inspect}" if !selector_raw.respond_to?(:key?)
selector = selector_raw.stringify_keys
raise "Invalid selector, operator missing #{selector.inspect}" if !selector['operator']
raise "Invalid selector, operator #{selector['operator']} is invalid #{selector.inspect}" if !selector['operator'].match?(/^(is|is\snot|contains|contains\s(not|all|one|all\snot|one\snot)|(after|before)\s\(absolute\)|(within\snext|within\slast|after|before)\s\(relative\))|(is\sin\sworking\stime|is\snot\sin\sworking\stime)$/)
# validate value / allow blank but only if pre_condition exists and is not specific
if !selector.key?('value') ||
(selector['value'].class == Array && selector['value'].respond_to?(:blank?) && selector['value'].blank?) ||
(selector['operator'] =~ /^contains/ && selector['value'].respond_to?(:blank?) && selector['value'].blank?)
return nil if selector['pre_condition'].nil?
return nil if selector['pre_condition'].respond_to?(:blank?) && selector['pre_condition'].blank?
return nil if selector['pre_condition'] == 'specific'
end
# validate pre_condition values
return nil if selector['pre_condition'] && selector['pre_condition'] !~ /^(not_set|current_user\.|specific)/
# get attributes
attributes = attribute.split(/\./)
attribute = "#{ActiveRecord::Base.connection.quote_table_name("#{attributes[0]}s")}.#{ActiveRecord::Base.connection.quote_column_name(attributes[1])}"
# magic selectors
if attributes[0] == 'ticket' && attributes[1] == 'out_of_office_replacement_id'
attribute = "#{ActiveRecord::Base.connection.quote_table_name("#{attributes[0]}s")}.#{ActiveRecord::Base.connection.quote_column_name('owner_id')}"
end
if attributes[0] == 'ticket' && attributes[1] == 'tags'
selector['value'] = selector['value'].split(/,/).collect(&:strip)
end
if selector['operator'].include?('in working time')
next if attributes[1] != 'calendar_id'
raise 'Please enable execution_time feature to use it (currently only allowed for triggers and schedulers)' if !options[:execution_time]
biz = Calendar.lookup(id: selector['value'])&.biz
next if biz.blank?
if ( selector['operator'] == 'is in working time' && !biz.in_hours?(Time.zone.now) ) || ( selector['operator'] == 'is not in working time' && biz.in_hours?(Time.zone.now) )
no_result = true
break
end
# skip to next condition
next
end
if query != ''
query += ' AND '
end
if selector['operator'] == 'is'
if selector['pre_condition'] == 'not_set'
if attributes[1].match?(/^(created_by|updated_by|owner|customer|user)_id/)
query += "(#{attribute} IS NULL OR #{attribute} IN (?))"
bind_params.push 1
else
query += "#{attribute} IS NULL"
end
elsif selector['pre_condition'] == 'current_user.id'
raise "Use current_user.id in selector, but no current_user is set #{selector.inspect}" if !current_user_id
query += "#{attribute} IN (?)"
if attributes[1] == 'out_of_office_replacement_id'
bind_params.push User.find(current_user_id).out_of_office_agent_of.pluck(:id)
else
bind_params.push current_user_id
end
elsif selector['pre_condition'] == 'current_user.organization_id'
raise "Use current_user.id in selector, but no current_user is set #{selector.inspect}" if !current_user_id
query += "#{attribute} IN (?)"
user = User.find_by(id: current_user_id)
bind_params.push user.organization_id
else
# rubocop:disable Style/IfInsideElse
if selector['value'].nil?
query += "#{attribute} IS NULL"
else
if attributes[1] == 'out_of_office_replacement_id'
query += "#{attribute} IN (?)"
bind_params.push User.find(selector['value']).out_of_office_agent_of.pluck(:id)
else
if selector['value'].class != Array
selector['value'] = [selector['value']]
end
query += if selector['value'].include?('')
"(#{attribute} IN (?) OR #{attribute} IS NULL)"
else
"#{attribute} IN (?)"
end
bind_params.push selector['value']
end
end
# rubocop:enable Style/IfInsideElse
end
elsif selector['operator'] == 'is not'
if selector['pre_condition'] == 'not_set'
if attributes[1].match?(/^(created_by|updated_by|owner|customer|user)_id/)
query += "(#{attribute} IS NOT NULL AND #{attribute} NOT IN (?))"
bind_params.push 1
else
query += "#{attribute} IS NOT NULL"
end
elsif selector['pre_condition'] == 'current_user.id'
query += "(#{attribute} IS NULL OR #{attribute} NOT IN (?))"
if attributes[1] == 'out_of_office_replacement_id'
bind_params.push User.find(current_user_id).out_of_office_agent_of.pluck(:id)
else
bind_params.push current_user_id
end
elsif selector['pre_condition'] == 'current_user.organization_id'
query += "(#{attribute} IS NULL OR #{attribute} NOT IN (?))"
user = User.find_by(id: current_user_id)
bind_params.push user.organization_id
else
# rubocop:disable Style/IfInsideElse
if selector['value'].nil?
query += "#{attribute} IS NOT NULL"
else
if attributes[1] == 'out_of_office_replacement_id'
bind_params.push User.find(selector['value']).out_of_office_agent_of.pluck(:id)
query += "(#{attribute} IS NULL OR #{attribute} NOT IN (?))"
else
if selector['value'].class != Array
selector['value'] = [selector['value']]
end
query += if selector['value'].include?('')
"(#{attribute} IS NOT NULL AND #{attribute} NOT IN (?))"
else
"(#{attribute} IS NULL OR #{attribute} NOT IN (?))"
end
bind_params.push selector['value']
end
end
# rubocop:enable Style/IfInsideElse
end
elsif selector['operator'] == 'contains'
query += "#{attribute} #{like} (?)"
value = "%#{selector['value']}%"
bind_params.push value
elsif selector['operator'] == 'contains not'
query += "#{attribute} NOT #{like} (?)"
value = "%#{selector['value']}%"
bind_params.push value
elsif selector['operator'] == 'contains all' && attributes[0] == 'ticket' && attributes[1] == 'tags'
query += "? = (
SELECT
COUNT(*)
FROM
tag_objects,
tag_items,
tags
WHERE
tickets.id = tags.o_id AND
tag_objects.id = tags.tag_object_id AND
tag_objects.name = 'Ticket' AND
tag_items.id = tags.tag_item_id AND
tag_items.name IN (?)
)"
bind_params.push selector['value'].count
bind_params.push selector['value']
elsif selector['operator'] == 'contains one' && attributes[0] == 'ticket' && attributes[1] == 'tags'
tables += ', tag_objects, tag_items, tags'
query += "
tickets.id = tags.o_id AND
tag_objects.id = tags.tag_object_id AND
tag_objects.name = 'Ticket' AND
tag_items.id = tags.tag_item_id AND
tag_items.name IN (?)"
bind_params.push selector['value']
elsif selector['operator'] == 'contains all not' && attributes[0] == 'ticket' && attributes[1] == 'tags'
query += "0 = (
SELECT
COUNT(*)
FROM
tag_objects,
tag_items,
tags
WHERE
tickets.id = tags.o_id AND
tag_objects.id = tags.tag_object_id AND
tag_objects.name = 'Ticket' AND
tag_items.id = tags.tag_item_id AND
tag_items.name IN (?)
)"
bind_params.push selector['value']
elsif selector['operator'] == 'contains one not' && attributes[0] == 'ticket' && attributes[1] == 'tags'
query += "(
SELECT
COUNT(*)
FROM
tag_objects,
tag_items,
tags
WHERE
tickets.id = tags.o_id AND
tag_objects.id = tags.tag_object_id AND
tag_objects.name = 'Ticket' AND
tag_items.id = tags.tag_item_id AND
tag_items.name IN (?)
) BETWEEN 0 AND 0"
bind_params.push selector['value']
elsif selector['operator'] == 'before (absolute)'
query += "#{attribute} <= ?"
bind_params.push selector['value']
elsif selector['operator'] == 'after (absolute)'
query += "#{attribute} >= ?"
bind_params.push selector['value']
elsif selector['operator'] == 'within last (relative)'
query += "#{attribute} >= ?"
time = nil
if selector['range'] == 'minute'
time = Time.zone.now - selector['value'].to_i.minutes
elsif selector['range'] == 'hour'
time = Time.zone.now - selector['value'].to_i.hours
elsif selector['range'] == 'day'
time = Time.zone.now - selector['value'].to_i.days
elsif selector['range'] == 'month'
time = Time.zone.now - selector['value'].to_i.months
elsif selector['range'] == 'year'
time = Time.zone.now - selector['value'].to_i.years
else
raise "Unknown selector attributes '#{selector.inspect}'"
end
bind_params.push time
elsif selector['operator'] == 'within next (relative)'
query += "#{attribute} <= ?"
time = nil
if selector['range'] == 'minute'
time = Time.zone.now + selector['value'].to_i.minutes
elsif selector['range'] == 'hour'
time = Time.zone.now + selector['value'].to_i.hours
elsif selector['range'] == 'day'
time = Time.zone.now + selector['value'].to_i.days
elsif selector['range'] == 'month'
time = Time.zone.now + selector['value'].to_i.months
elsif selector['range'] == 'year'
time = Time.zone.now + selector['value'].to_i.years
else
raise "Unknown selector attributes '#{selector.inspect}'"
end
bind_params.push time
elsif selector['operator'] == 'before (relative)'
query += "#{attribute} <= ?"
time = nil
if selector['range'] == 'minute'
time = Time.zone.now - selector['value'].to_i.minutes
elsif selector['range'] == 'hour'
time = Time.zone.now - selector['value'].to_i.hours
elsif selector['range'] == 'day'
time = Time.zone.now - selector['value'].to_i.days
elsif selector['range'] == 'month'
time = Time.zone.now - selector['value'].to_i.months
elsif selector['range'] == 'year'
time = Time.zone.now - selector['value'].to_i.years
else
raise "Unknown selector attributes '#{selector.inspect}'"
end
bind_params.push time
elsif selector['operator'] == 'after (relative)'
query += "#{attribute} >= ?"
time = nil
if selector['range'] == 'minute'
time = Time.zone.now + selector['value'].to_i.minutes
elsif selector['range'] == 'hour'
time = Time.zone.now + selector['value'].to_i.hours
elsif selector['range'] == 'day'
time = Time.zone.now + selector['value'].to_i.days
elsif selector['range'] == 'month'
time = Time.zone.now + selector['value'].to_i.months
elsif selector['range'] == 'year'
time = Time.zone.now + selector['value'].to_i.years
else
raise "Unknown selector attributes '#{selector.inspect}'"
end
bind_params.push time
else
raise "Invalid operator '#{selector['operator']}' for '#{selector['value'].inspect}'"
end
end
return if no_result
[query, bind_params, tables]
end
=begin
perform changes on ticket
ticket.perform_changes({}, 'trigger', item, current_user_id)
=end
def perform_changes(perform, perform_origin, item = nil, current_user_id = nil)
logger.debug { "Perform #{perform_origin} #{perform.inspect} on Ticket.find(#{id})" }
article = begin
Ticket::Article.find_by(id: item.try(:dig, :article_id))
rescue ArgumentError
nil
end
# if the configuration contains the deletion of the ticket then
# we skip all other ticket changes because they does not matter
if perform['ticket.action'].present? && perform['ticket.action']['value'] == 'delete'
perform.each_key do |key|
(object_name, attribute) = key.split('.', 2)
next if object_name != 'ticket'
next if attribute == 'action'
perform.delete(key)
end
end
perform_notification = {}
perform_article = {}
changed = false
perform.each do |key, value|
(object_name, attribute) = key.split('.', 2)
raise "Unable to update object #{object_name}.#{attribute}, only can update tickets, send notifications and create articles!" if object_name != 'ticket' && object_name != 'article' && object_name != 'notification'
# send notification/create article (after changes are done)
if object_name == 'article'
perform_article[key] = value
next
end
if object_name == 'notification'
perform_notification[key] = value
next
end
# update tags
if key == 'ticket.tags'
next if value['value'].blank?
tags = value['value'].split(/,/)
if value['operator'] == 'add'
tags.each do |tag|
tag_add(tag, current_user_id || 1)
end
elsif value['operator'] == 'remove'
tags.each do |tag|
tag_remove(tag, current_user_id || 1)
end
else
logger.error "Unknown #{attribute} operator #{value['operator']}"
end
next
end
# delete ticket
if key == 'ticket.action'
next if value['value'].blank?
next if value['value'] != 'delete'
logger.info { "Deleted ticket from #{perform_origin} #{perform.inspect} Ticket.find(#{id})" }
destroy!
next
end
# lookup pre_condition
if value['pre_condition']
if value['pre_condition'].match?(/^not_set/)
value['value'] = 1
elsif value['pre_condition'].match?(/^current_user\./)
raise 'Unable to use current_user, got no current_user_id for ticket.perform_changes' if !current_user_id
value['value'] = current_user_id
end
end
# update ticket
next if self[attribute].to_s == value['value'].to_s
changed = true
self[attribute] = value['value']
logger.debug { "set #{object_name}.#{attribute} = #{value['value'].inspect} for ticket_id #{id}" }
end
if changed
save!
end
perform_article.each do |key, value|
raise 'Unable to create article, we only support article.note' if key != 'article.note'
Ticket::Article.create!(
ticket_id: id,
subject: value[:subject],
content_type: 'text/html',
body: value[:body],
internal: value[:internal],
sender: Ticket::Article::Sender.find_by(name: 'System'),
type: Ticket::Article::Type.find_by(name: 'note'),
preferences: {
perform_origin: perform_origin,
},
updated_by_id: 1,
created_by_id: 1,
)
end
perform_notification.each do |key, value|
# send notification
case key
when 'notification.sms'
send_sms_notification(value, article, perform_origin)
next
when 'notification.email'
send_email_notification(value, article, perform_origin)
end
end
true
end
=begin
perform active triggers on ticket
Ticket.perform_triggers(ticket, article, item, options)
=end
def self.perform_triggers(ticket, article, item, options = {})
recursive = Setting.get('ticket_trigger_recursive')
type = options[:type] || item[:type]
local_options = options.clone
local_options[:type] = type
local_options[:reset_user_id] = true
local_options[:disable] = ['Transaction::Notification']
local_options[:trigger_ids] ||= {}
local_options[:trigger_ids][ticket.id] ||= []
local_options[:loop_count] ||= 0