-
Notifications
You must be signed in to change notification settings - Fork 9
Expand file tree
/
Copy pathdelivery.ex
More file actions
1157 lines (912 loc) · 28.9 KB
/
Copy pathdelivery.ex
File metadata and controls
1157 lines (912 loc) · 28.9 KB
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
defmodule BikeBrigade.Delivery do
import Ecto.Query, warn: false
alias BikeBrigade.Repo
alias BikeBrigade.LocalizedDateTime
import Geo.PostGIS, only: [st_distance: 2]
alias BikeBrigade.Riders.Rider
alias BikeBrigade.History
alias BikeBrigade.Messaging
alias BikeBrigade.Delivery.{Task, CampaignRider}
import BikeBrigade.Utils, only: [task_count: 1, humanized_task_count: 1]
import BikeBrigade.Riders.Helpers, only: [first_name: 1]
# TODO this is for the details url. maybe move to a web/ module?
use Phoenix.VerifiedRoutes, endpoint: BikeBrigadeWeb.Endpoint, router: BikeBrigadeWeb.Router
@doc """
Returns the list of tasks.
## Examples
iex> list_tasks()
[%Task{}, ...]
"""
def list_tasks do
Repo.all(Task, preload: [:campaigns])
end
@doc """
Gets a single task.
Raises `Ecto.NoResultsError` if the Task does not exist.
## Examples
iex> get_task(123)
%Task{}
iex> get_task(456)
nil
"""
def get_task(id, opts \\ []) do
preload =
Keyword.get(opts, :prelaod, [
:assigned_rider,
:task_items,
:pickup_location,
:dropoff_location
])
from(t in Task,
as: :task,
where: t.id == ^id
)
|> task_load_location()
|> Repo.one()
|> Repo.preload(preload)
end
defp task_load_location(query) do
query
|> join(:inner, [task: t], pl in assoc(t, :pickup_location), as: :pickup_location)
|> join(:inner, [task: t], dl in assoc(t, :dropoff_location), as: :dropoff_location)
|> preload([pickup_location: pl, dropoff_location: dl],
pickup_location: pl,
dropoff_location: dl
)
|> select_merge([pickup_location: pl, dropoff_location: dl], %{
delivery_distance: st_distance(pl.coords, dl.coords)
})
end
@doc """
Creates a task.
## Examples
iex> create_task(%{field: value})
{:ok, %Task{}}
iex> create_task(%{field: bad_value})
{:error, %Ecto.Changeset{}}
"""
def create_task(attrs \\ %{}) do
%Task{}
|> Task.changeset(attrs)
|> Repo.insert()
end
@doc """
Updates a task.
## Examples
iex> update_task(task, %{field: new_value})
{:ok, %Task{}}
iex> update_task(task, %{field: bad_value})
{:error, %Ecto.Changeset{}}
"""
def update_task(%Task{} = task, attrs, opts \\ []) do
# TODO validate items unique index stuff
task
|> Task.changeset(attrs, opts)
|> Repo.update()
|> broadcast(:task_updated)
end
@doc """
Assign a task to a given rider (tracking the user that made the assignment)
"""
def assign_task(%Task{} = task, rider_id, user_id, opts \\ []) when is_list(opts) do
Repo.transaction(fn ->
{:ok, _log} =
History.create_task_assignment_log(%{
task_id: task.id,
rider_id: rider_id,
user_id: user_id,
action: :assigned
})
{:ok, task} =
update_task(task, %{assigned_rider_id: rider_id}, opts)
task
end)
end
@doc """
Unassign a task (tracking the user that made the unassignment)
"""
def unassign_task(%Task{assigned_rider_id: assigned_rider_id} = task, user_id, opts \\ [])
when not is_nil(assigned_rider_id) and is_list(opts) do
Repo.transaction(fn ->
{:ok, _log} =
History.create_task_assignment_log(%{
task_id: task.id,
rider_id: assigned_rider_id,
user_id: user_id,
action: :unassigned
})
{:ok, task} = update_task(task, %{assigned_rider_id: nil}, opts)
task
end)
end
@doc """
Deletes a task.
## Examples
iex> delete_task(task)
{:ok, %Task{}}
iex> delete_task(task)
{:error, %Ecto.Changeset{}}
"""
def delete_task(%Task{} = task) do
Repo.delete(task)
|> broadcast(:task_deleted)
end
@doc """
Returns an `%Ecto.Changeset{}` for tracking task changes.
## Examples
iex> change_task(task)
%Ecto.Changeset{data: %Task{}}
"""
def change_task(%Task{} = task, attrs \\ %{}, opts \\ []) do
Task.changeset(task, attrs, opts)
end
alias BikeBrigade.Delivery.Campaign
def list_campaigns(opts \\ []) do
preload = Keyword.get(opts, :preload, [:program])
query =
from c in Campaign,
as: :campaign,
inner_join: p in assoc(c, :program),
as: :program,
order_by: [desc: c.delivery_start],
where: ^campaigns_filter(opts)
Repo.all(query)
|> Repo.preload(preload)
end
defp campaigns_filter(opts) do
public = Keyword.get(opts, :public, nil)
campaign_ids = Keyword.get(opts, :campaign_ids, nil)
start_date = Keyword.get(opts, :start_date, nil)
end_date = Keyword.get(opts, :end_date, nil)
true
|> filter_public(public)
|> filter_campaign_ids(campaign_ids)
|> filter_start_date(start_date)
|> filter_end_date(end_date)
end
defp filter_public(filter, nil), do: filter
defp filter_public(filter, true) do
dynamic([program: p], ^filter and p.public == true)
end
defp filter_public(filter, false) do
dynamic([program: p], ^filter and p.public == false)
end
defp filter_campaign_ids(filter, nil), do: filter
defp filter_campaign_ids(filter, campaign_ids) when is_list(campaign_ids) do
dynamic([campaign: c], ^filter and c.id in ^campaign_ids)
end
defp filter_start_date(filter, nil), do: filter
defp filter_start_date(filter, date) do
date_time = LocalizedDateTime.new!(date, ~T[00:00:00])
dynamic([campaign: c], ^filter and c.delivery_start >= ^date_time)
end
defp filter_end_date(filter, nil), do: filter
defp filter_end_date(filter, date) do
date_time = LocalizedDateTime.new!(date, ~T[23:59:59])
dynamic([campaign: c], ^filter and c.delivery_start <= ^date_time)
end
@doc """
Gets campaigns that are happening between now and 48 hours from now, and have unassigned tasks.
Used on the rider's home page to let riders know about campaigns that could use the help.
"""
def list_urgent_campaigns() do
now = LocalizedDateTime.now()
forty_eight_hours_from_now = DateTime.add(now, 48, :hour)
query =
from c in Campaign,
distinct: [asc: c.id],
join: t in assoc(c, :tasks),
join: p in assoc(c, :program),
where:
c.delivery_start <= ^forty_eight_hours_from_now and
c.delivery_start >= ^now and
p.public == true and
is_nil(t.assigned_rider_id),
select: c
Repo.all(query)
|> Repo.preload([:program, :tasks])
end
@doc """
Fetches how many open vs filled tasks there are (optionally, by week)
and groups them by campaign ID.
Written in order to show how "full" a campaign is.
"""
def get_total_tasks_and_open_tasks(start_time \\ nil, end_time \\ nil) do
query =
from t in Task,
as: :task,
join: c in assoc(t, :campaign),
as: :campaign
query =
if start_time && end_time do
query
|> where(
[campaign: c],
c.delivery_start >= ^start_time and c.delivery_start <= ^end_time
)
else
query
end
query =
from [task: t, campaign: c] in query,
group_by: c.id,
select: %{
campaign_id: c.id,
total_tasks: count(t.id),
filled_tasks:
sum(fragment("CASE WHEN ? IS NULL THEN 0 ELSE 1 END", t.assigned_rider_id)),
rider_ids: fragment("array_agg(?)", t.assigned_rider_id)
}
Repo.all(query)
|> Enum.into(
%{},
fn x ->
{x.campaign_id,
%{
rider_ids_counts: Enum.frequencies(x.rider_ids),
total_tasks: x.total_tasks,
filled_tasks: x.filled_tasks
}}
end
)
end
alias BikeBrigade.Delivery.CampaignRider
def get_campaign_rider_by_id(campaign_id, rider_id) do
CampaignRider |> Repo.get_by(campaign_id: campaign_id, rider_id: rider_id)
end
def get_campaign_rider!(token) do
query =
from cr in CampaignRider,
join: c in assoc(cr, :campaign),
join: r in assoc(cr, :rider),
left_join: t in assoc(c, :tasks),
on: t.assigned_rider_id == r.id,
# TODO make this join dor distance some kind of function
left_join: pl in assoc(t, :pickup_location),
left_join: dl in assoc(t, :dropoff_location),
order_by: st_distance(pl.coords, dl.coords),
where: cr.token == ^token,
preload: [
campaign: [:program, :location],
rider: {r, [:location, assigned_tasks: {t, [:dropoff_location, task_items: :item]}]}
]
Repo.one!(query)
end
def create_campaign_rider(attrs \\ %{}) do
# Check if rider is already signed up as backup rider for this campaign
campaign_id = attrs["campaign_id"] || attrs[:campaign_id]
rider_id = attrs["rider_id"] || attrs[:rider_id]
case {campaign_id, rider_id} do
{nil, _} ->
create_campaign_rider_without_backup_check(attrs)
{_, nil} ->
create_campaign_rider_without_backup_check(attrs)
{campaign_id, rider_id} ->
case Repo.get_by(CampaignRider,
campaign_id: campaign_id,
rider_id: rider_id,
backup_rider: true
) do
nil ->
# No backup rider exists, proceed with normal signup
create_campaign_rider_without_backup_check(attrs)
_backup_rider ->
# Backup rider exists, prevent regular signup
changeset =
%CampaignRider{}
|> CampaignRider.changeset(attrs)
|> Ecto.Changeset.add_error(:rider_id, "already signed up as backup rider")
{:error, changeset}
end
end
end
def create_campaign_rider_without_backup_check(attrs) do
%CampaignRider{}
|> CampaignRider.changeset(attrs)
|> Repo.insert(
on_conflict: {:replace, [:rider_capacity, :notes, :pickup_window, :enter_building]},
conflict_target: [:rider_id, :campaign_id]
)
|> broadcast(:campaign_rider_created)
end
def update_campaign_rider(%CampaignRider{} = rider, attrs) do
rider
|> CampaignRider.changeset(attrs)
|> Repo.update()
|> broadcast(:campaign_rider_updated)
end
def delete_campaign_rider(%CampaignRider{} = campaign_rider) do
Repo.delete(campaign_rider)
|> broadcast(:campaign_rider_deleted)
end
def create_task_for_campaign(campaign, attrs \\ %{}, opts \\ []) do
# TODO handle conflicts for multiple task items here
# TODO this looks a lot like Task.changeset_for_campaign()
%Task{
pickup_location: campaign.location,
campaign_id: campaign.id
}
|> Task.changeset(attrs, opts)
|> Repo.insert()
|> broadcast(:task_created)
end
@doc """
Creates a campaign.
"""
def create_campaign(attrs \\ %{}) do
%Campaign{}
|> Campaign.changeset(attrs)
|> Repo.insert()
end
def new_campaign(attrs \\ %{}) do
today = LocalizedDateTime.today()
start_time = ~T[17:00:00]
end_time = ~T[19:30:00]
delivery_start = LocalizedDateTime.new!(today, start_time)
delivery_end = LocalizedDateTime.new!(today, end_time)
%Campaign{
delivery_start: delivery_start,
delivery_end: delivery_end
}
|> Campaign.changeset(attrs)
|> Ecto.Changeset.apply_changes()
end
def get_campaign(id, opts \\ []) do
preload = Keyword.get(opts, :preload, [:location, :program])
Repo.get(Campaign, id)
|> Repo.preload(preload)
end
def get_campaign!(id, opts \\ []) do
preload = Keyword.get(opts, :preload, [:location, :program])
Repo.get!(Campaign, id)
|> Repo.preload(preload)
end
@doc """
Returns a tuple of `{riders, tasks}` for a `campaign`. Riders are pre-loaded with their assigned tasks,
and tasks are pre-loaded with the assigned rider, and task_items/items.
"""
def campaign_riders_and_tasks(%Campaign{} = campaign) do
campaign =
campaign
|> Repo.preload(:location)
all_tasks =
from(t in Task,
as: :task,
where: t.campaign_id == ^campaign.id,
select: t
)
|> task_load_location()
|> order_by(:id)
|> Repo.all()
|> Repo.preload([:pickup_location, dropoff_location: [:neighborhood], task_items: [:item]])
all_riders =
Repo.all(
from cr in CampaignRider,
join: r in assoc(cr, :rider),
left_join: l in assoc(r, :location),
where: cr.campaign_id == ^campaign.id and cr.backup_rider == false,
order_by: r.name,
select: r,
select_merge: %{
distance: st_distance(l.coords, ^campaign.location.coords),
task_notes: cr.notes,
task_capacity: cr.rider_capacity,
task_enter_building: cr.enter_building,
pickup_window: cr.pickup_window,
delivery_url_token: cr.token
}
)
|> Repo.preload([:location, :total_stats])
# Does a nested preload to get tasks' assigned riders without doing an extra db query
tasks = Repo.preload(all_tasks, assigned_rider: fn _ -> all_riders end)
riders = Repo.preload(all_riders, assigned_tasks: fn _ -> all_tasks end)
{riders, tasks}
end
def get_backup_riders(%Campaign{} = campaign) do
backup_riders =
Repo.all(
from cr in CampaignRider,
join: r in assoc(cr, :rider),
where: cr.campaign_id == ^campaign.id and cr.backup_rider == true,
order_by: r.name,
select: r,
select_merge: %{
task_notes: cr.notes,
task_capacity: cr.rider_capacity,
task_enter_building: cr.enter_building,
pickup_window: cr.pickup_window,
delivery_url_token: cr.token
}
)
|> Repo.preload([:total_stats])
backup_riders
end
def create_backup_campaign_rider(attrs \\ %{}) do
attrs = Map.put(attrs, "backup_rider", true)
%CampaignRider{}
|> CampaignRider.changeset(attrs)
|> Repo.insert(
on_conflict:
{:replace, [:rider_capacity, :notes, :pickup_window, :enter_building, :backup_rider]},
conflict_target: [:rider_id, :campaign_id]
)
|> broadcast(:campaign_rider_created)
end
def remove_backup_rider_from_campaign(%Campaign{} = campaign, rider_id) do
case Repo.get_by(CampaignRider,
campaign_id: campaign.id,
rider_id: rider_id,
backup_rider: true
) do
nil ->
{:error, :not_found}
campaign_rider ->
Repo.delete(campaign_rider)
|> broadcast(:campaign_rider_deleted)
end
end
# TODO RENAME TO TODAYS TASKS
def latest_campaign_tasks(rider) do
# This is hacky, better to refigure out how we present this
today = LocalizedDateTime.today()
end_of_today = LocalizedDateTime.new!(today, ~T[23:59:59])
start_of_yesterday = Date.add(today, -1) |> LocalizedDateTime.new!(~T[00:00:00])
query =
from c in Campaign,
join: t in assoc(c, :tasks),
join: cr in CampaignRider,
on: cr.rider_id == ^rider.id and cr.campaign_id == c.id,
where: c.delivery_start <= ^end_of_today and c.delivery_start >= ^start_of_yesterday,
where: t.assigned_rider_id == ^rider.id,
select: c,
select_merge: %{delivery_url_token: cr.token},
order_by: [desc: c.delivery_start, asc: t.id],
preload: [tasks: t]
Repo.all(query)
|> Repo.preload([:program, tasks: [:dropoff_location, task_items: :item]])
end
def campaigns_per_rider(rider) do
query = from c in CampaignRider, where: c.rider_id == ^rider.id, select: count(c.id)
Repo.one(query)
end
def hacky_assign(%Campaign{} = campaign) do
riders_query =
from r in Rider,
join: cr in CampaignRider,
on: cr.rider_id == r.id and cr.campaign_id == ^campaign.id,
join: l in assoc(r, :location),
order_by: [
desc: cr.rider_capacity,
asc: r.max_distance - st_distance(l.coords, ^campaign.location.coords)
],
left_join: t in Task,
on: t.assigned_rider_id == r.id and t.campaign_id == ^campaign.id,
preload: [:location, assigned_tasks: {t, :task_items}],
select: {r, cr.rider_capacity}
riders = Repo.all(riders_query)
require Logger
for {rider, rider_capacity} <- riders do
if task_count(rider.assigned_tasks) < rider_capacity do
tasks =
if rider_capacity > 1 do
Repo.all(
from t in Task,
where: t.campaign_id == ^campaign.id and is_nil(t.assigned_rider_id),
join: pl in assoc(t, :pickup_location),
join: dl in assoc(t, :dropoff_location),
preload: [task_items: :item],
order_by: st_distance(pl.coords, dl.coords)
)
else
Repo.all(
from t in Task,
where: t.campaign_id == ^campaign.id and is_nil(t.assigned_rider_id),
join: dl in assoc(t, :dropoff_location),
preload: [task_items: :item],
order_by: st_distance(dl.coords, ^rider.location.coords)
)
end
|> Repo.preload([:assigned_rider])
{to_assign, _tasks} = Enum.split(tasks, rider_capacity)
Logger.info("Assigning #{Enum.count(to_assign)} items to #{rider.name}")
for task <- to_assign do
update_task(task, %{assigned_rider_id: rider.id})
end
end
end
end
def change_campaign(campaign, attrs \\ %{}) do
Campaign.changeset(campaign, attrs)
end
def update_campaign(campaign, attrs, opts \\ []) do
campaign
|> Campaign.changeset(attrs, opts)
|> Repo.update()
|> broadcast(:campaign_updated)
end
def delete_campaign(%Campaign{} = campaign) do
Repo.delete(campaign)
end
@campaign_message_directives ~w(rider_name program_name pickup_address delivery_date pickup_window delivery_details_url task_details task_count directions)
def campaign_message_directives do
@campaign_message_directives
end
def send_campaign_messages(%Campaign{} = campaign) do
campaign = Repo.preload(campaign, [:location, :instructions_template, :program])
{riders, _} = campaign_riders_and_tasks(campaign)
msgs =
for rider <- riders, rider != nil do
{:ok, msg} = send_campaign_message(%Campaign{} = campaign, rider)
msg
end
{:ok, msgs}
end
def send_campaign_message(%Campaign{} = campaign, rider) do
body =
render_campaign_message_for_rider(
campaign,
campaign.instructions_template.body,
rider
)
{:ok, msg} = Messaging.send_message_in_chunks(campaign, body, rider)
if rider.text_based_itinerary do
send_text_based_itinerary(rider, campaign)
end
{:ok, msg}
end
defp send_text_based_itinerary(rider, campaign) do
template = """
1. Pickup
• {{{task_count}}}
• {{{pickup_address}}}
• {{{pickup_window}}}
2. Drop-off
{{{task_details}}}
{{{directions}}}
"""
body =
render_campaign_message_for_rider(
campaign,
template,
rider
)
Messaging.send_message_in_chunks(campaign, body, rider)
end
def render_campaign_message_for_rider(campaign, nil, rider),
do: render_campaign_message_for_rider(campaign, "", rider)
def render_campaign_message_for_rider(%Campaign{} = campaign, message, %Rider{} = rider)
when is_binary(message) do
tasks =
rider.assigned_tasks
|> Enum.sort_by(& &1.delivery_distance)
# TODO: referncing CampaignHelpers here is bad!
# need to move this into Task or Delivery
pickup_window = BikeBrigadeWeb.CampaignHelpers.pickup_window(campaign, rider)
locations = [campaign.location | Enum.map(tasks, & &1.dropoff_location)]
task_details =
for task <- tasks do
"Name: #{task.dropoff_name}\nPhone: #{task.dropoff_phone}\nType: #{BikeBrigadeWeb.CampaignHelpers.request_type(task)}\nAddress: #{task.dropoff_location}\nNotes: #{task.delivery_instructions}"
end
|> Enum.join("\n\n")
directions = BikeBrigade.GoogleMaps.directions_url(rider.location, locations)
delivery_details_url = url(~p"/app/delivery/#{rider.delivery_url_token}")
campaign_date = LocalizedDateTime.to_date(campaign.delivery_start)
formatted_date =
"#{Calendar.strftime(campaign_date, "%a %b")} #{Inflex.ordinalize(campaign_date.day)}"
assigns = %{
rider_name: first_name(rider),
program_name: campaign.program.name,
pickup_address: campaign.location,
task_details: task_details,
directions: directions,
task_count: humanized_task_count(tasks),
pickup_window: pickup_window,
delivery_details_url: delivery_details_url,
delivery_date: formatted_date
}
Mustache.render(message, assigns)
end
def campaign_rider_token(%Campaign{} = campaign, %Rider{} = rider) do
# TODO
# this is very inefficient to look up each time, which we could cache these
query =
from cr in CampaignRider,
where: cr.rider_id == ^rider.id and cr.campaign_id == ^campaign.id
case Repo.one(query) do
%CampaignRider{token: nil} = cr ->
cr =
cr
|> CampaignRider.gen_token_changeset()
|> Repo.update!()
cr.token
%CampaignRider{token: token} ->
token
_ ->
nil
end
end
def remove_rider_from_campaign(campaign, rider_id) do
if cr = Repo.get_by(CampaignRider, campaign_id: campaign.id, rider_id: rider_id) do
delete_campaign_rider(cr)
end
tasks =
from(t in Task,
where: t.campaign_id == ^campaign.id and t.assigned_rider_id == ^rider_id
)
|> Repo.all()
for task <- tasks do
update_task(task, %{assigned_rider_id: nil})
end
end
alias BikeBrigade.Delivery.Program
@doc """
Returns the list of programs.
## Examples
iex> list_programs()
[%Program{}, ...]
"""
def list_programs(opts \\ []) do
preload = Keyword.get(opts, :preload, [])
query =
from p in Program,
as: :program,
order_by: [desc: p.active, asc: p.name]
query =
if search = opts[:search] do
query
|> where([program: p], ilike(p.name, ^"%#{search}%"))
else
query
end
query =
if opts[:with_campaign_count] do
from p in query,
left_join: c in assoc(p, :campaigns),
group_by: p.id,
select_merge: %{campaign_count: count(c)}
else
query
end
Repo.all(query)
|> Repo.preload(preload)
end
@doc """
Gets a single program.
Raises `Ecto.NoResultsError` if the Program does not exist.
## Examples
iex> get_program!(123)
%Program{}
iex> get_program!(456)
** (Ecto.NoResultsError)
"""
def get_program!(id, opts \\ []) do
preload = Keyword.get(opts, :preload, [])
Repo.get!(Program, id)
|> Repo.preload(preload)
end
def get_program_by_name(name, opts \\ []) do
preload = Keyword.get(opts, :preload, [])
Program
|> Repo.get_by(name: name)
|> Repo.preload(preload)
end
@doc """
Creates a program.
## Examples
iex> create_program(%{field: value})
{:ok, %Program{}}
iex> create_program(%{field: bad_value})
{:error, %Ecto.Changeset{}}
"""
def create_program(attrs \\ %{}) do
%Program{}
|> Program.changeset(attrs)
|> Repo.insert()
end
@doc """
Updates a program.
## Examples
iex> update_program(program, %{field: new_value})
{:ok, %Program{}}
iex> update_program(program, %{field: bad_value})
{:error, %Ecto.Changeset{}}
"""
def update_program(%Program{} = program, attrs) do
program
|> Program.changeset(attrs)
|> Repo.update()
end
@doc """
Deletes a program.
## Examples
iex> delete_program(program)
{:ok, %Program{}}
iex> delete_program(program)
{:error, %Ecto.Changeset{}}
"""
def delete_program(%Program{} = program) do
Repo.delete(program)
end
@doc """
Returns an `%Ecto.Changeset{}` for tracking program changes.
## Examples
iex> change_program(program)
%Ecto.Changeset{data: %Program{}}
"""
def change_program(%Program{} = program, attrs \\ %{}) do
Program.changeset(program, attrs)
end
def subscribe do
Phoenix.PubSub.subscribe(BikeBrigade.PubSub, "delivery")
end
defp broadcast({:error, _reason} = error, _event), do: error
defp broadcast({:ok, struct}, event) do
Phoenix.PubSub.broadcast(BikeBrigade.PubSub, "delivery", {event, struct})
{:ok, struct}
end
alias BikeBrigade.Delivery.Item
@doc """
Returns the list of items.
## Examples
iex> list_items()
[%Item{}, ...]
iex> list_items(42)
[%Item{program_id: 42, …}, …]
"""
def list_items(program_id \\ nil) do
query = from i in Item, order_by: i.name
query =
if program_id do
query
|> where([i], i.program_id == ^program_id)
else
query
end
Repo.all(query)
|> Repo.preload(:program)
end
@doc """
Gets a single item.
Raises `Ecto.NoResultsError` if the Item does not exist.
## Examples
iex> get_item!(123)
%Item{}
iex> get_item!(456)
** (Ecto.NoResultsError)
"""
def get_item!(id), do: Repo.get!(Item, id)
@doc """
Creates a item.
## Examples
iex> create_item(%{field: value})
{:ok, %Item{}}
iex> create_item(%{field: bad_value})
{:error, %Ecto.Changeset{}}
"""
def create_item(attrs \\ %{}) do
%Item{}
|> Item.changeset(attrs)
|> Repo.insert()
end
@doc """
Updates a item.