forked from OpenACD/OpenACD
/
cook.erl
1723 lines (1655 loc) · 57.9 KB
/
cook.erl
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
%% The contents of this file are subject to the Common Public Attribution
%% License Version 1.0 (the “License”); you may not use this file except
%% in compliance with the License. You may obtain a copy of the License at
%% http://opensource.org/licenses/cpal_1.0. The License is based on the
%% Mozilla Public License Version 1.1 but Sections 14 and 15 have been
%% added to cover use of software over a computer network and provide for
%% limited attribution for the Original Developer. In addition, Exhibit A
%% has been modified to be consistent with Exhibit B.
%%
%% Software distributed under the License is distributed on an “AS IS”
%% basis, WITHOUT WARRANTY OF ANY KIND, either express or implied. See the
%% License for the specific language governing rights and limitations
%% under the License.
%%
%% The Original Code is OpenACD.
%%
%% The Initial Developers of the Original Code is
%% Andrew Thompson and Micah Warren.
%%
%% All portions of the code written by the Initial Developers are Copyright
%% (c) 2008-2009 SpiceCSM.
%% All Rights Reserved.
%%
%% Contributor(s):
%%
%% Andrew Thompson <andrew at hijacked dot us>
%% Micah Warren <micahw at fusedsolutions dot com>
%%
%% @doc The cook is a process that is spawned per call in queue, it
%% executes the queue's 'recipe' on the call and handles call delivery to an
%% agent. When it finds one or more dispatchers bound to its call it requests
%% that each dispatcher generate a list of local agents matching the call's
%% criteria and selects the best one to offer it to.
-module(cook).
-author("Micah").
-behaviour(gen_server).
-include("log.hrl").
-include("call.hrl").
-include("agent.hrl").
-include("queue.hrl").
-ifdef(TEST).
-include_lib("eunit/include/eunit.hrl").
-define(TICK_LENGTH, 500).
-define(RINGOUT, 3).
-else.
-define(TICK_LENGTH, 1000).
-define(RINGOUT, 60).
-endif.
-define(DEFAULT_PATHCOST, 15).
%% API
-export([
start_link/5,
start/5,
stop/1,
restart_tick/1,
stop_tick/1,
start_at/6
]).
%% gen_server callbacks
-export([init/1, handle_call/3, handle_cast/2, handle_info/2,
terminate/2, code_change/3]).
-type(call_key() :: {pos_integer(), {pos_integer(), pos_integer(), pos_integer()}}).
-record(state, {
recipe = [] :: recipe(),
ticked = 1 :: pos_integer(), % number of ticks we've done
call :: pid() | 'undefined',
callid :: string,
queue :: string(),
qpid :: pid(),
key :: call_key(),
ringstate = none :: 'none' | 'ringing',
tref :: any() % timer reference
}).
-type(state() :: #state{}).
-define(GEN_SERVER, true).
-include("gen_spec.hrl").
%%====================================================================
%% API
%%====================================================================
%% @doc Starts a cook linked to the parent process for `Call' processed by `Recipe' for call_queue named `Queue'.
-spec(start_link/5 :: (Call :: pid(), Recipe :: recipe(), Queue :: string(), Qpid :: pid(), Key :: call_key()) -> {'ok', pid()} | 'ignore' | {'error', any()}).
start_link(Call, Recipe, Queue, Qpid, Key) when is_pid(Call) ->
gen_server:start_link(?MODULE, [Call, Recipe, Queue, Qpid, Key], []).
%% @doc Starts a cook not linked to the parent process for `Call' processed by `Recipe' for call_queue named `Queue'.
-spec(start/5 :: (Call :: pid(), Recipe :: recipe(), Queue :: string(), Qpid :: pid(), Key :: call_key()) -> {'ok', pid()} | 'ignore' | {'error', any()}).
start(Call, Recipe, Queue, Qpid, Key) when is_pid(Call) ->
gen_server:start(?MODULE, [Call, Recipe, Queue, Qpid, Key], []).
%% @doc starts a new cook on the give `node()' `Node' for `Call' to be process by `Recipe' for the call_queue named `Queue'.
%% This is used in place of start and start_link to allow a queue on a different node to start the cook on the same node
%% the media exists on.
-spec(start_at/6 :: (Node :: atom(), Call :: pid(), Recipe :: recipe(), Queue :: string(), Qpid :: pid(), Key :: call_key()) -> {'ok', pid()} | 'ignore' | {'error', any()}).
start_at(Node, Call, Recipe, Queue, Qpid, Key) ->
F = fun() ->
{ok, State} = init([Call, Recipe, Queue, Qpid, Key]),
?DEBUG("about to enter loop ~p, ~p", [get('$ancestors'), Call]),
put('$ancestors', [Call]), % we don't want to die with the queue
gen_server:enter_loop(?MODULE, [], State)
end,
{ok, proc_lib:spawn_link(Node, F)}.
%%====================================================================
%% gen_server callbacks
%%====================================================================
%% @private
init([Call, InRecipe, Queue, Qpid, {_Priority, {MSec, Sec, _MsSec}} = Key]) ->
CallRec = gen_media:get_call(Call),
?DEBUG("Cook starting for call ~p from queue ~p", [CallRec#call.id, Queue]),
?DEBUG("node check. self: ~p; call: ~p", [node(self()), node(Call)]),
process_flag(trap_exit, true),
Tref = erlang:send_after(?TICK_LENGTH, self(), do_tick),
OptRecipe = optimize_recipe(InRecipe),
Now = util:now(),
Recipe = case round(Now - (MSec * 1000000 + Sec)) of
Ticked when Ticked > 1 ->
fast_forward(OptRecipe, Ticked / (?TICK_LENGTH / 1000), Qpid, Call);
_Else ->
OptRecipe
end,
State = #state{recipe=Recipe, call=Call, queue=Queue, qpid = Qpid, tref=Tref, key = Key, callid = CallRec#call.id},
{ok, State}.
%%--------------------------------------------------------------------
%% Description: Handling call messages
%%--------------------------------------------------------------------
%% @private
handle_call(stop, From, #state{callid = CallID} = State) ->
?NOTICE("Stop requested from ~p for ~p", [From, CallID]),
{stop, normal, ok, State};
handle_call({stop, Reason}, From, #state{callid = CallID} = State) ->
?NOTICE("Stop requested from ~p for ~p with reason ~p.", [From, CallID, Reason]),
{stop, {normal, Reason}, ok, State};
handle_call(Request, _From, State) ->
{reply, {unknown_call, Request}, State}.
%%--------------------------------------------------------------------
%% Description: Handling cast messages
%%--------------------------------------------------------------------
%% @private
handle_cast(restart_tick, #state{qpid = Qpid} = State) ->
case do_route(State#state.ringstate, Qpid, State#state.call) of
nocall ->
{stop, {call_not_queued, State#state.call}, State};
Ringstate ->
State2 = State#state{ringstate = Ringstate},
NewRecipe = do_recipe(State2#state.recipe, State2#state.ticked, Qpid, State2#state.call),
State3 = State2#state{ticked = State2#state.ticked + 1, recipe = NewRecipe},
Tref = erlang:send_after(?TICK_LENGTH, self(), do_tick),
{noreply, State3#state{tref=Tref}}
end;
handle_cast(stop_ringing, #state{qpid = Qpid} = State) ->
?DEBUG("rang out or ring aborted, trying to find new candidate", []),
case do_route(none, Qpid, State#state.call) of
nocall ->
{stop, {call_not_queued, State#state.call}, State};
Ringstate ->
State2 = State#state{ringstate = Ringstate},
{noreply, State2}
end;
handle_cast({ring_to, Apid, QCall}, State) ->
Agent = agent:dump_state(Apid),
Newstate = case offer_call([{Agent#agent.login, Apid, Agent}], QCall) of
ringing ->
State#state{ringstate = ringing};
none ->
State
end,
{noreply, Newstate};
handle_cast(stop_tick, State) ->
erlang:cancel_timer(State#state.tref),
{noreply, State#state{tref=undefined}};
handle_cast(stop, State) ->
{stop, normal, State};
handle_cast(Msg, #state{callid = CallID} = State) ->
?DEBUG("unhandled cast ~p ~p", [Msg, CallID]),
{noreply, State}.
%%--------------------------------------------------------------------
%% Description: Handling all non call/cast messages
%%--------------------------------------------------------------------
%% @private
handle_info(do_tick, #state{qpid = Qpid} = State) ->
NewRecipe = do_recipe(State#state.recipe, State#state.ticked, Qpid, State#state.call),
Tref = case NewRecipe of
[] ->
% empty recipe, don't wake up later
undefined;
_ ->
% TODO calculate if we can sleep longer here
erlang:send_after(?TICK_LENGTH, self(), do_tick)
end,
State2 = State#state{ticked = State#state.ticked + 1, recipe = NewRecipe, tref = Tref},
{noreply, State2};
handle_info(grab, #state{qpid = Qpid} = State) ->
% TODO - we should wait to see if more nodes want to bind to make distributed delivery fairer
?DEBUG("a dispatcher grabbed the call", []),
case do_route(State#state.ringstate, Qpid, State#state.call) of
nocall ->
{stop, {call_not_queued, State#state.call}, State};
Ringstate ->
State2 = State#state{ringstate = Ringstate},
{noreply, State2}
end;
handle_info({'EXIT', From, Reason}, #state{qpid = From} = State) when Reason == shutdown; Reason == normal ->
{stop, Reason, State};
handle_info({'EXIT', From, _Reason}, #state{qpid = From, callid = CallID} = State) ->
?NOTICE("queue ~p died unexpectedly - trying to add call ~p back into the new queue", [State#state.queue, CallID]),
Qpid = wait_for_queue(State#state.queue),
call_queue:add_at(Qpid, State#state.key, State#state.call),
gen_media:set_queue(State#state.call, Qpid),
{stop, normal, State};
handle_info(Info, #state{callid = CallID} = State) ->
?DEBUG("received random info message: ~p ~p", [Info, CallID]),
{noreply, State}.
%%--------------------------------------------------------------------
%% Function: terminate(Reason, State) -> void()
%%--------------------------------------------------------------------
%% @private
terminate(normal, #state{callid = CallID}) ->
?DEBUG("normal cook death for ~p", [CallID]),
ok;
terminate(shutdown, #state{callid = CallID}) ->
?DEBUG("shutdown cook death for ~p", [CallID]),
ok;
terminate({normal, Reason}, #state{callid = CallID}) ->
?NOTICE("An inelegant cook shutdown requested for ~p with reason ~p", [CallID, Reason]),
ok;
terminate(Reason, #state{callid = CallID}) ->
?WARNING("Unusual cook death for ~p with reason ~p", [CallID, Reason]),
%erlang:cancel_timer(State#state.tref),
%Qpid = wait_for_queue(State#state.queue),
%?INFO("Looks like the queue ~s recovered (~w), dieing now",[State#state.queue, Qpid]),
%case call_queue:get_call(Qpid, State#state.call) of
%none ->
%?INFO("Call was not in queue ~s - adding it", [State#state.queue]),
%call_queue:add_at(Qpid, State#state.key, State#state.call);
%_ ->
%ok
%end,
ok.
%%--------------------------------------------------------------------
%% Func: code_change(OldVsn, State, Extra) -> {ok, NewState}
%%--------------------------------------------------------------------
%% @private
code_change(_OldVsn, State, _Extra) ->
{ok, State}.
%%--------------------------------------------------------------------
%%% Internal functions
%%--------------------------------------------------------------------
%% @doc Restart the cook at `Pid'.
-spec(restart_tick/1 :: (Pid :: pid()) -> 'ok').
restart_tick(Pid) ->
gen_server:cast(Pid, restart_tick).
%% @doc Pause the cook running at `Pid'.
-spec(stop_tick/1 :: (Pid :: pid()) -> 'ok').
stop_tick(Pid) ->
gen_server:cast(Pid, stop_tick).
%% @private
wait_for_queue(Qname) ->
case whereis(queue_manager) of
undefined ->
?INFO("Waiting on the queue manager", []),
receive
after 1000 ->
ok
end;
QMPid when is_pid(QMPid) ->
?DEBUG("Queue manager is available", []),
ok
end,
case queue_manager:get_queue(Qname) of
undefined ->
?INFO("Waiting on queue ~p" , [Qname]),
receive
after 300 ->
ok
end,
wait_for_queue(Qname);
Qpid when is_pid(Qpid) ->
?DEBUG("Queue ~p is back up", [Qname]),
Qpid
end.
%% @doc Stop the cook with reason `normal'.
-spec(stop/1 :: (Pid :: pid()) -> 'ok').
stop(Pid) ->
gen_server:call(Pid, stop).
%% @private
-spec(do_route/3 :: (Ringstate :: 'ringing' | 'none', Queue :: pid(), Callpid :: pid()) -> 'nocall' | 'ringing' | 'none').
do_route(ringing, _Qpid, _Callpid) ->
%?DEBUG("still ringing", []),
ringing;
do_route(none, Qpid, Callpid) ->
%?DEBUG("Searching for agent to ring to...",[]),
case call_queue:get_call(Qpid, Callpid) of
{_Key, Call} ->
Dispatchers = Call#queued_call.dispatchers,
Agents = sort_agent_list(Dispatchers),
%?DEBUG("Dispatchers: ~p; Agents: ~p", [Dispatchers, Agents]),
offer_call(Agents, Call);
none ->
?DEBUG("No call to ring",[]),
nocall
end.
%% @private
-spec(sort_agent_list/1 :: (Dispatchers :: [pid()]) -> [{string(), pid(), #agent{}}]).
sort_agent_list([]) ->
[];
sort_agent_list(Dispatchers) when is_list(Dispatchers) ->
F = fun(Dpid) ->
try dispatcher:get_agents(Dpid) of
{_, []} ->
%?DEBUG("empty list, might as well tell this dispatcher to regrab", []),
dispatcher:regrab(Dpid),
[];
{Count, Ag} ->
[{K, V, TimeAvail, AgSkills, {node(Dpid), Count}} || {K, V, TimeAvail, AgSkills} <- Ag]
catch
What:Why ->
?INFO("Caught: ~p:~p", [What, Why]),
[]
end
end,
Agents = lists:map(F, Dispatchers),
Agents2 = lists:flatten(Agents),
% XXX - sort_agents_by_elegibility doesn't sort by pathcost yet
Agents3 = agent_manager:sort_agents_by_elegibility(Agents2),
Out = agent_manager:rotate_based_on_list_count(Agents3),
?DEBUG("The out: ~p", [Out]),
Out.
%% @private
-spec(offer_call/2 :: (Agents :: [{string(), pid(), #agent{}}], Call :: #queued_call{}) -> 'none' | 'ringing').
offer_call([], _Call) ->
%?DEBUG("No valid agents found", []),
none;
offer_call([{Login, Apid, _Time, _Skills, _Ignorable} | Tail], Call) ->
case gen_media:ring(Call#queued_call.media, Apid, Call, ?TICK_LENGTH * ?RINGOUT) of
ok ->
Callrec = gen_media:get_call(Call#queued_call.media),
?INFO("cook offering call: ~p to ~p", [Callrec#call.id, Login]),
ringing;
invalid ->
offer_call(Tail, Call)
end.
%% @private
-spec(check_conditions/4 :: (Conditions :: [recipe_condition()], Ticked :: non_neg_integer(), Qpid :: pid(), Call :: pid()) -> 'true' | 'false').
check_conditions([], _Ticked, _Qpid, _Call) ->
true;
check_conditions([{ticks, Ticks} | Conditions], Ticked, Qpid, Call) when Ticked > 0 andalso (Ticked rem Ticks) == 0 ->
check_conditions(Conditions, Ticked, Qpid, Call);
check_conditions([{ticks, _Ticks} | _Conditions], _Ticked, _Qpid, _Call) ->
false;
check_conditions([{available_agents, Comparision, Number} | Conditions], Ticked, Qpid, Call) ->
{_Key, Callrec} = call_queue:get_call(Qpid, Call),
L = agent_manager:find_avail_agents_by_skill(Callrec#queued_call.skills),
Agents = length(L),
case Comparision of
'>' when Agents > Number ->
check_conditions(Conditions, Ticked, Qpid, Call);
'<' when Agents < Number ->
check_conditions(Conditions, Ticked, Qpid, Call);
'=' when Agents =:= Number ->
check_conditions(Conditions, Ticked, Qpid, Call);
_Else ->
false
end;
check_conditions([{eligible_agents, Comparision, Number} | Conditions], Ticked, Qpid, Call) ->
{_Key, Callrec} = call_queue:get_call(Qpid, Call),
L = agent_manager:find_by_skill(Callrec#queued_call.skills),
Agents = length(L),
%?DEBUG("Number: ~p; agents: ~p", [Number, Agents]),
case Comparision of
'>' when Agents > Number ->
check_conditions(Conditions, Ticked, Qpid, Call);
'<' when Agents < Number ->
check_conditions(Conditions, Ticked, Qpid, Call);
'=' when Number =:= Agents ->
check_conditions(Conditions, Ticked, Qpid, Call);
_Else ->
false
end;
check_conditions([{calls_queued, Comparision, Number} | Conditions], Ticked, Qpid, Call) ->
Count = call_queue:call_count(Qpid),
case Comparision of
'>' when Count > Number ->
check_conditions(Conditions, Ticked, Qpid, Call);
'<' when Count < Number ->
check_conditions(Conditions, Ticked, Qpid, Call);
'=' when Number =:= Count ->
check_conditions(Conditions, Ticked, Qpid, Call);
_Else ->
false
end;
check_conditions([{client_calls_queued, Comparision, Number} | Conditions], Ticked, Qpid, Call) ->
Callrec = gen_media:get_call(Call),
Count = call_queue:call_count_by_client(Qpid, Callrec#call.client),
case Comparision of
'>' when Count > Number ->
check_conditions(Conditions, Ticked, Qpid, Call);
'<' when Count < Number ->
check_conditions(Conditions, Ticked, Qpid, Call);
'=' when Number =:= Count ->
check_conditions(Conditions, Ticked, Qpid, Call);
_Else ->
false
end;
check_conditions([{queue_position, Comparision, Number} | Conditions], Ticked, Qpid, Call) ->
Calls = call_queue:to_list(Qpid),
Test = fun(Needle, #queued_call{media = Mpid}) ->
Needle =:= Mpid
end,
Position = util:list_index(Test, Call, Calls),
case Comparision of
'>' when Position > Number ->
check_conditions(Conditions, Ticked, Qpid, Call);
'<' when Position < Number, Position > 0 ->
check_conditions(Conditions, Ticked, Qpid, Call);
'=' when Position =:= Number ->
check_conditions(Conditions, Ticked, Qpid, Call);
_Else ->
false
end;
check_conditions([{client, Comparision, ClientID} | Conditions], Ticked, Qpid, Call) ->
Callrec = gen_media:get_call(Call),
Client = Callrec#call.client,
case Comparision of
'=' when Client#client.id == ClientID ->
check_conditions(Conditions, Ticked, Qpid, Call);
'!=' when Client#client.id =/= ClientID ->
check_conditions(Conditions, Ticked, Qpid, Call);
_Else ->
false
end;
check_conditions([{hour, Comparision, CHour} | Conditions], Ticked, Qpid, Call) ->
{_, {Hour, _, _}} = calendar:local_time(),
case Comparision of
'>' when Hour > CHour ->
check_conditions(Conditions, Ticked, Qpid, Call);
'<' when Hour < CHour ->
check_conditions(Conditions, Ticked, Qpid, Call);
'=' when Hour == CHour ->
check_conditions(Conditions, Ticked, Qpid, Call);
_Else ->
false
end;
check_conditions([{weekday, Comparision, CDay} | Conditions], Ticked, Qpid, Call) ->
Day = calendar:day_of_the_week(calendar:local_time()),
case Comparision of
'>' when Day > CDay ->
check_conditions(Conditions, Ticked, Qpid, Call);
'<' when Day < CDay ->
check_conditions(Conditions, Ticked, Qpid, Call);
'=' when Day == CDay ->
check_conditions(Conditions, Ticked, Qpid, Call);
_Else ->
false
end;
check_conditions([{type, Comparision, CType} | Conditions], Ticked, Qpid, Call) ->
Callrec = gen_media:get_call(Call),
Type = Callrec#call.type,
case Comparision of
'=' when Type == CType ->
check_conditions(Conditions, Ticked, Qpid, Call);
'!=' when Type =/= CType ->
check_conditions(Conditions, Ticked, Qpid, Call);
_Else ->
false
end.
%% @private
-spec(do_recipe/4 :: (Recipe :: recipe(), Ticked :: non_neg_integer(), Qpid :: pid(), Call :: pid()) -> recipe()).
do_recipe([], _Ticked, _Qpid, _Call) ->
[];
do_recipe(Recipe, Ticked, Qpid, Call) when is_pid(Qpid), is_pid(Call) ->
do_recipe(Recipe, Ticked, Qpid, Call, []).
do_recipe([], _Ticked, Qpid, Call, Acc) ->
Acc;
do_recipe([{Conditions, Op, Runs, _Comment} = OldAction | Recipe], Ticked, Qpid, Call, Acc) ->
case check_conditions(Conditions, Ticked, Qpid, Call) of
true ->
Doneop = do_operation(Op, Qpid, Call),
case Runs of
run_once ->
do_recipe(Recipe, Ticked, Qpid, Call, lists:append(Doneop, Acc));
run_many ->
do_recipe(Recipe, Ticked, Qpid, Call, lists:append([Doneop, [OldAction], Acc]))
end;
false ->
do_recipe(Recipe, Ticked, Qpid, Call, lists:append([OldAction], Acc))
end.
%% @private
-spec(fast_forward/4 :: (Recipe :: recipe(), Ticked :: non_neg_integer(), Qpid :: pid(), Call :: pid()) -> recipe()).
fast_forward(Recipe, Ticked, Qpid, Call) ->
fast_forward(Recipe, Ticked, Qpid, Call, 0, []).
fast_forward([], Ticked, _Qpid, _Call, Ticked, Acc) ->
lists:reverse(Acc);
fast_forward([], ToTick, Qpid, Call, Ticked, Acc) ->
fast_forward(lists:reverse(Acc), ToTick, Qpid, Call, Ticked + 1, []);
fast_forward([{Conditions, Ops, Runs, _Comment} = OldAction | Recipe], ToTick, Qpid, Call, Ticked, Acc) ->
case fast_forward_check_conditions(Conditions, Ticked, Qpid, Call) of
true ->
Doneop = fast_forward_do_op(Ops, Qpid, Call),
case Runs of
run_once ->
fast_forward(Recipe, ToTick, Qpid, Call, Ticked, lists:append(Doneop, Acc));
run_many ->
fast_forward(Recipe, ToTick, Qpid, Call, Ticked, lists:append([Doneop, [OldAction], Acc]))
end;
false ->
fast_forward(Recipe, ToTick, Qpid, Call, Ticked, lists:append([OldAction], Acc))
end.
fast_forward_check_conditions([], _Ticked, _Qpid, _Call) ->
true;
fast_forward_check_conditions([Condition | Tail], Ticked, Qpid, Call) ->
AssumeFalse = [available_agents, eligible_agents, calls_queued, client_calls_queued, queue_position],
case lists:member(element(1, Condition), AssumeFalse) of
true ->
false;
false ->
case check_conditions([Condition], Ticked, Qpid, Call) of
true ->
fast_forward_check_conditions(Tail, Ticked, Qpid, Call);
false ->
false
end
end.
fast_forward_do_op(Ops, Qpid, Call) ->
fast_forward_do_op(Ops, Qpid, Call, []).
fast_forward_do_op([], _, _, Acc) ->
lists:reverse(Acc);
fast_forward_do_op([{Op, Args} | Tail], Qpid, Call, Acc) ->
Out = case Op of
add_recipe ->
list_to_tuple(Args);
_ ->
ok
end,
Newacc = case Out of
ok ->
Acc;
_ ->
[Out | Acc]
end,
fast_forward_do_op(Tail, Qpid, Call, Newacc).
%% @private
-spec(do_operation/3 :: (Operations :: [recipe_operation()], Qpid :: pid(), Callpid :: pid()) -> [recipe_step()]).
do_operation(Operations, Qpid, Callpid) when is_pid(Qpid), is_pid(Callpid) ->
do_operation(Operations, Qpid, Callpid, []).
-spec(do_operation/4 :: (Operations :: [recipe_operation()], Qpid :: pid(), Callpid :: pid(), Acc :: [recipe_step()]) -> [recipe_step()]).
do_operation([], _Qpid, _Callpid, Acc) ->
lists:reverse(Acc);
do_operation([{Op, Args} | Tail], Qpid, Callpid, Acc) ->
Out = case Op of
add_skills ->
call_queue:add_skills(Qpid, Callpid, Args),
ok;
remove_skills ->
call_queue:remove_skills(Qpid, Callpid, Args),
ok;
set_priority ->
call_queue:set_priority(Qpid, Callpid, Args),
ok;
prioritize ->
{{Prior, _Time}, _Call} = call_queue:get_call(Qpid, Callpid),
call_queue:set_priority(Qpid, Callpid, Prior + 1),
ok;
deprioritize ->
{{Prior, _Time}, _Call} = call_queue:get_call(Qpid, Callpid),
call_queue:set_priority(Qpid, Callpid, Prior - 1),
ok;
voicemail ->
case gen_media:voicemail(Callpid) of
ok ->
?DEBUG("voicemail successfully, removing from queue", []),
call_queue:bgremove(Qpid, Callpid);
invalid ->
?WARNING("voicemail failed.", []),
ok
end;
add_recipe ->
list_to_tuple(Args);
announce ->
gen_media:announce(Callpid, Args),
ok
end,
Newacc = case Out of
ok ->
Acc;
_ ->
[Out | Acc]
end,
do_operation(Tail, Qpid, Callpid, Newacc).
optimize_recipe(Recipe) ->
optimize_recipe(Recipe, []).
optimize_recipe([], Acc) ->
lists:reverse(Acc);
optimize_recipe([{Conds, Op, Runs, Comment} | Tail], Acc) ->
Newacc = [{sort_conditions(Conds), Op, Runs, Comment} | Acc],
optimize_recipe(Tail, Newacc).
sort_conditions(Conditions) ->
lists:sort(fun sort_conditions_compare/2, Conditions).
sort_conditions_compare(CondA, CondB) ->
Condlist = [type, client, ticks, hour, weekday, calls_queued, queue_position, client_calls_queued, available_agents, eligible_agents],
A = element(1, CondA),
B = element(1, CondB),
util:list_index(A, Condlist) < util:list_index(B, Condlist).
-ifdef(TEST).
fast_forward_test_() ->
% if an no_gen_server_mock_expectation occurs, it may be due to a
% recipe looping forward too many times.
{setup,
fun() ->
{ok, MediaPid} = gen_server_mock:new(),
{ok, Qpid} = gen_server_mock:new(),
MakeTime = fun(Seconds) ->
Fulltime = util:now() - Seconds,
Msec = util:floor(Fulltime / 1000000),
Sec = Fulltime - Msec,
{Msec, Sec, 0}
end,
Client = #client{label = "testclient", id="testclient"},
MediaRec = #call{id = "testmedia", source = MediaPid, client = Client},
SeedMedia = fun() ->
gen_server_mock:expect_call(MediaPid, fun(A, B, State) ->
{ok, MediaRec, State}
end)
end,
?DEBUG("dsaflhadslkfhkjsadfL ~p", [MediaRec]),
{MediaRec, Qpid, MakeTime, SeedMedia}
end,
fun({Media, Qpid, _, _}) ->
gen_server_mock:stop(Media#call.source),
gen_server_mock:stop(Qpid)
end,
fun({Media, Qpid, MakeTime, SeedMedia}) ->
[{"Simple fast forward (ticks only)",
fun() ->
InRecipe = [{[{ticks, 5}], [{prioritize, []}], run_once, <<"test">>}],
?assertEqual([], fast_forward(InRecipe, 10, Qpid, Media#call.source))
end},
{"Fast forward run may (ticks only)",
fun() ->
InRecipe = [{[{ticks, 5}], [{prioritize, []}], run_many, <<"test">>}],
?assertEqual(InRecipe, fast_forward(InRecipe, 10, Qpid, Media#call.source))
end},
{"Fast forward client check matches, run_once",
fun() ->
SeedMedia(),
InRecipe = [{[{client, '=', "testclient"}], [{prioritize, []}], run_once, <<"test">>}],
?assertEqual([], fast_forward(InRecipe, 5, Qpid, Media#call.source))
end},
{"Fast forward client check mismatch, run_once",
fun() ->
InRecipe = [{[{client, '=', "goober"}], [{prioritize, []}], run_once, <<"test">>}],
[SeedMedia() || _ <- lists:seq(0, 5)],
?assertEqual(InRecipe, fast_forward(InRecipe, 5, Qpid, Media#call.source))
end},
{"Fast forward client check mismatch, run_many",
fun() ->
[SeedMedia() || _ <- lists:seq(0, 5)],
InRecipe = [{[{client, '=', "goober"}], [{prioritize, []}], run_many, <<"test">>}],
?assertEqual(InRecipe, fast_forward(InRecipe, 5, Qpid, Media#call.source))
end},
{"Fast forward media type check mismatch run_once",
fun() ->
[SeedMedia() || _ <- lists:seq(0, 5)],
InRecipe = [{[{type, '!=', voice}], [{prioritize, []}], run_once, <<"test">>}],
?assertEqual(InRecipe, fast_forward(InRecipe, 5, Qpid, Media#call.source))
end},
{"Fast forward media type check mismatch run_many",
fun() ->
[SeedMedia() || _ <- lists:seq(0, 5)],
InRecipe = [{[{type, '!=', voice}], [{prioritize, []}], run_many, <<"test">>}],
?assertEqual(InRecipe, fast_forward(InRecipe, 5, Qpid, Media#call.source))
end},
{"Fast forward ticks and media type (both match) run_once",
fun() ->
[SeedMedia() || _ <- lists:seq(0, 5)],
InRecipe = [{[{type, '=', voice}, {ticks, 5}], [{prioritize, []}], run_once, <<"test">>}],
?assertEqual([], fast_forward(InRecipe, 10, Qpid, Media#call.source))
end},
{"Fast forward ticks and media type, insufficent ticks, run_once",
fun() ->
[SeedMedia() || _ <- lists:seq(0, 10)],
InRecipe = [{[{type, '=', voice}, {ticks, 20}], [{prioritize, []}], run_once, <<"test">>}],
?assertEqual(InRecipe, fast_forward(InRecipe, 10, Qpid, Media#call.source))
end},
{"Fast forward adding recipe run_once",
fun() ->
InRecipe = [{[{ticks, 5}], [{add_recipe, [[{ticks, 10}], [{prioritize, []}], run_once, <<"inner test">>]}], run_once, <<"test">>}],
OutRecipe = [{[{ticks, 10}], [{prioritize, []}], run_once, <<"inner test">>}],
?assertEqual(OutRecipe, fast_forward(InRecipe, 6, Qpid, Media#call.source))
end},
{"Fast forward adding multiple recipes",
fun() ->
InRecipe = [{[{ticks, 5}], [{add_recipe, [[{ticks, 30}], [{prioritize, []}], run_once, <<"inner test">>]}], run_many, <<"test">>}],
OutRecipe = [{[{ticks, 5}], [{add_recipe, [[{ticks, 30}], [{prioritize, []}], run_once, <<"inner test">>]}], run_many, <<"test">>}, {[{ticks, 30}], [{prioritize, []}], run_once, <<"inner test">>}, {[{ticks, 30}], [{prioritize, []}], run_once, <<"inner test">>}],
?assertEqual(OutRecipe, fast_forward(InRecipe, 10, Qpid, Media#call.source))
end},
{"Fast forward added recipe runs",
fun() ->
InRecipe = [{[{ticks, 5}], [{add_recipe, [[{ticks, 5}], [{prioritize, []}], run_once, <<"inner test">>]}], run_once, <<"test">>}],
?assertEqual([], fast_forward(InRecipe, 12, Qpid, Media#call.source))
end}]
end}.
sort_conditions_test() ->
[{"Simple comparison",
fun() ->
Input = [{eligible_agents, '=', "Doesn't matter"}, {queue_position, '=', "Doesn't matter"}, {type, '=', "Doesn't matter"}],
Expected = [{type, '=', "Doesn't matter"}, {queue_position, '=', "Doesn't matter"}, {eligible_agents, '=', "Doesn't matter"}],
?assertEqual(Expected, sort_conditions(Input))
end},
{"It's a reverse",
fun() ->
Expected = [
{type, nomatter, nomatter},
{client, nomatter, nomatter},
{ticks, nomatter, nomatter},
{hour, nomatter, nomatter},
{weekday, nomatter, nomatter},
{calls_queued, nomatter, nomatter},
{queue_position, nomatter, nomatter},
{client_calls_queued, nomatter, nomatter},
{available_agents, nomatter, nomatter},
{eligible_agents, nomatter, nomatter}
],
Input = lists:reverse(Expected),
?assertEqual(Expected, sort_conditions(Input))
end}].
test_primer() ->
["testpx", _Host] = string:tokens(atom_to_list(node()), "@"),
mnesia:stop(),
mnesia:delete_schema([node()]),
mnesia:create_schema([node()]),
mnesia:start().
do_operation_test_() ->
{foreach,
fun() ->
{ok, QMPid} = gen_leader_mock:start(queue_manager),
{ok, QPid} = gen_server_mock:new(),
{ok, Mpid} = gen_server_mock:new(),
Assertmocks = fun() ->
gen_leader_mock:assert_expectations(QMPid),
gen_server_mock:assert_expectations(QPid),
gen_server_mock:assert_expectations(Mpid)
end,
?CONSOLE("Start args: ~p", [{QMPid, QPid, Mpid, Assertmocks}]),
{QMPid, QPid, Mpid, Assertmocks}
end,
fun({QMPid, QPid, Mpid, _Assertmocks}) ->
gen_server_mock:stop(QPid),
gen_leader_mock:stop(QMPid),
gen_server_mock:stop(Mpid),
timer:sleep(10)
end,
[fun({_QMPid, QPid, Mpid, Assertmocks}) ->
{"add skills",
fun() ->
gen_server_mock:expect_call(Mpid, fun('$gen_media_get_call', _From, State) ->
{ok, #call{id = "testcall", source = Mpid}, State}
end),
gen_server_mock:expect_call(QPid, fun({add_skills, "testcall", [skill1, skill2]}, _From, _State) -> ok end),
?assertEqual([], do_operation([{add_skills, [skill1, skill2]}], QPid, Mpid)),
Assertmocks()
end}
end,
fun({_QMPid, QPid, Mpid, Assertmocks}) ->
{"remove skills",
fun() ->
gen_server_mock:expect_call(Mpid, fun('$gen_media_get_call', _From, State) ->
{ok, #call{id = "testcall", source = Mpid}, State}
end),
gen_server_mock:expect_call(QPid, fun({remove_skills, "testcall", [english]}, _From, _State) -> ok end),
?assertEqual([], do_operation([{remove_skills, [english]}], QPid, Mpid)),
Assertmocks()
end}
end,
fun({_QMPid, QPid, Mpid, Assertmocks}) ->
{"set priority",
fun() ->
gen_server_mock:expect_call(QPid, fun({set_priority, Incpid, 5}, _From, _State) ->
Incpid = Mpid,
ok
end),
?assertEqual([], do_operation([{set_priority, 5}], QPid, Mpid)),
Assertmocks()
end}
end,
fun({_QMPid, QPid, Mpid, Assertmocks}) ->
{"prioritize",
fun() ->
gen_server_mock:expect_call(QPid, fun({get_call, Incpid}, _From, State) ->
Incpid = Mpid,
{ok, {{7, now()}, #call{id = "testcall", source = Mpid}}, State}
end),
gen_server_mock:expect_call(QPid, fun({set_priority, Incpid, 8}, _Fun, _State) ->
Incpid = Mpid,
ok
end),
?assertEqual([], do_operation([{prioritize, "doesn't matter"}], QPid, Mpid)),
Assertmocks()
end}
end,
fun({_QMPid, QPid, Mpid, Assertmocks}) ->
{"deprioritize",
fun() ->
gen_server_mock:expect_call(QPid, fun({get_call, Incpid}, _From, State) ->
Incpid = Mpid,
{ok, {{27, now()}, #call{id = "testcall", source = Mpid}}, State}
end),
gen_server_mock:expect_call(QPid, fun({set_priority, Incpid, 26}, _Fun, _State) ->
Incpid = Mpid,
ok
end),
?assertEqual([], do_operation([{deprioritize, "doesn't matter"}], QPid, Mpid)),
Assertmocks()
end}
end,
fun({_QMPid, QPid, Mpid, Assertmocks}) ->
{"voicemail with media that can handle it",
fun() ->
gen_server_mock:expect_call(Mpid, fun('$gen_media_voicemail', _From, State) ->
{ok, ok, State}
end),
gen_server_mock:expect_cast(QPid, fun({remove, Incpid}, _State) ->
Incpid = Mpid,
ok
end),
?assertEqual([], do_operation([{voicemail, "doesn't matter"}], QPid, Mpid)),
Assertmocks()
end}
end,
fun({_QMPid, QPid, Mpid, Assertmocks}) ->
{"voicemail with media that doesn't support it",
fun() ->
gen_server_mock:expect_call(Mpid, fun('$gen_media_voicemail', _From, State) ->
{ok, invalid, State}
end),
?assertEqual([], do_operation([{voicemail, "doesn't matter"}], QPid, Mpid)),
Assertmocks()
end}
end,
fun({_QMPid, QPid, Mpid, Assertmocks}) ->
{"add recipe",
fun() ->
?assertEqual([{1, 2, 3}], do_operation([{add_recipe, [1, 2, 3]}], QPid, Mpid)),
Assertmocks()
end}
end,
fun({_QMPid, QPid, Mpid, Assertmocks}) ->
{"announce",
fun() ->
gen_server_mock:expect_call(Mpid, fun({'$gen_media_announce', "do the robot"}, _From, _State) -> ok end),
?assertEqual([], do_operation([{announce, "do the robot"}], QPid, Mpid)),
Assertmocks()
end}
end]}.
check_conditions_test_() ->
[{"ticks tests",
{foreach,
fun() ->
{ok, QMPid} = gen_leader_mock:start(queue_manager),
{ok, QPid} = gen_server_mock:new(),
{ok, Mpid} = gen_server_mock:new(),
{ok, AMpid} = gen_leader_mock:start(agent_manager),
Assertmocks = fun() ->
gen_leader_mock:assert_expectations(QMPid),
gen_server_mock:assert_expectations(QPid),
gen_server_mock:assert_expectations(Mpid)
end,
?CONSOLE("Start args: ~p", [{QMPid, QPid, Mpid, Assertmocks}]),
{QMPid, QPid, Mpid, AMpid, Assertmocks}
end,
fun({QMPid, QPid, Mpid, AMpid, _Assertmocks}) ->
gen_server_mock:stop(QPid),
gen_leader_mock:stop(QMPid),
gen_server_mock:stop(Mpid),
gen_leader_mock:stop(AMpid),
timer:sleep(10)
end,
[fun({_QMPid, _QPid, _Mpid, _AMpid, Assertmocks}) ->
{"no more conditions to check",
fun() ->
?assert(check_conditions([], "ticked doesn't matter", "queue doesn't matter", "call doesn't matter")),
Assertmocks()
end}
end,
fun({_QMPid, QPid, _Mpid, _AMpid, Assertmocks}) ->
{"checking ticks",
fun() ->
?assert(check_conditions([{ticks, 5}], 5, QPid, "call")),
Assertmocks()
end}
end,
fun({_QMPid, QPid, _Mpid, _AMpid, Assertmocks}) ->
{"checking ticks that aren't equal, but at right frequency",
fun() ->
?assert(check_conditions([{ticks, 7}], 42, QPid, "call")),
Assertmocks()
end}
end,
fun({_, QPid, _, _, Assertmocks}) ->
{"checking ticks not at the right frequency",
fun() ->
?assertNot(check_conditions([{ticks, 3}], 7, QPid, "call")),
Assertmocks()
end}
end]}},
{"available agents",
{foreach,
fun() ->
{ok, QMPid} = gen_leader_mock:start(queue_manager),
{ok, QPid} = gen_server_mock:new(),
{ok, Mpid} = gen_server_mock:new(),
{ok, AMpid} = gen_leader_mock:start(agent_manager),
Assertmocks = fun() ->
gen_leader_mock:assert_expectations(QMPid),
gen_server_mock:assert_expectations(QPid),
gen_server_mock:assert_expectations(Mpid),
gen_leader_mock:assert_expectations(AMpid)
end,
?CONSOLE("Start args: ~p", [{QMPid, QPid, Mpid, AMpid, Assertmocks}]),
gen_server_mock:expect_call(QPid, fun({get_call, Incpid}, _From, State) ->
?CONSOLE("get_call", []),
Mpid = Incpid,
{ok, {"key", #queued_call{id = "testcall", media = Mpid, skills = [english]}}, State}
end),
AgentList = [#agent{login = "agent1", id = "agent1", skills = ['_all'], state = idle},
#agent{login = "agent2", id = "agent2", skills = ['_all'], state = idle},
#agent{login = "agent3", id = "agent3", skills = ['_all'], state = idle}],
Outlist = [begin
gen_leader_mock:expect_cast(AMpid, fun({update_skill_list, _, _}, _, _) ->
ok
end),
{ok, P} = agent:start_link(Rec),
{Rec#agent.login, {P, Rec#agent.id, util:now(), Rec#agent.skills}}
end || Rec <- AgentList ],
gen_leader_mock:expect_call(AMpid, fun(list_agents, _From, State, _Elec) ->
{ok, Outlist, State}
end),
{QMPid, QPid, Mpid, AMpid, Assertmocks}
end,
fun({QMPid, QPid, Mpid, AMpid, _Assertmocks}) ->
gen_server_mock:stop(QPid),
gen_leader_mock:stop(QMPid),
gen_server_mock:stop(Mpid),
gen_leader_mock:stop(AMpid),
timer:sleep(10)
end,
[fun({_QMPid, QPid, Mpid, _AMpid, Assertmocks}) ->
{"available agents > condition is true",
fun() ->
?assert(check_conditions([{available_agents, '>', 2}], "doesn't matter", QPid, Mpid)),
Assertmocks()
end}