-
Notifications
You must be signed in to change notification settings - Fork 30
/
int_zendesk__ticket_schedules.sql
85 lines (63 loc) · 2.25 KB
/
int_zendesk__ticket_schedules.sql
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
{{ config(enabled=var('using_schedules', True)) }}
with ticket as (
select *
from {{ ref('stg_zendesk__ticket') }}
), ticket_schedule as (
select *
from {{ ref('stg_zendesk__ticket_schedule') }}
), schedule as (
select *
from {{ ref('stg_zendesk__schedule') }}
), default_schedule_events as (
-- Goal: understand the working schedules applied to tickets, so that we can then determine the applicable business hours/schedule.
-- Your default schedule is used for all tickets, unless you set up a trigger to apply a specific schedule to specific tickets.
-- This portion of the query creates ticket_schedules for these "default" schedules, as the ticket_schedule table only includes
-- trigger schedules
{% if execute %}
{% set default_schedule_id_query %}
with set_default_schedule_flag as (
select
row_number() over (order by created_at) = 1 as is_default_schedule,
id
from {{ source('zendesk','schedule') }}
where not coalesce(_fivetran_deleted, false)
)
select
id
from set_default_schedule_flag
where is_default_schedule
{% endset %}
{% set default_schedule_id = run_query(default_schedule_id_query).columns[0][0]|string %}
{% endif %}
select
ticket.ticket_id,
ticket.created_at as schedule_created_at,
'{{default_schedule_id}}' as schedule_id
from ticket
left join ticket_schedule as first_schedule
on first_schedule.ticket_id = ticket.ticket_id
and {{ fivetran_utils.timestamp_add('second', -5, 'first_schedule.created_at') }} <= ticket.created_at
and first_schedule.created_at >= ticket.created_at
where first_schedule.ticket_id is null
), schedule_events as (
select
*
from default_schedule_events
union all
select
ticket_id,
created_at as schedule_created_at,
schedule_id
from ticket_schedule
), ticket_schedules as (
select
ticket_id,
schedule_id,
schedule_created_at,
coalesce(lead(schedule_created_at) over (partition by ticket_id order by schedule_created_at)
, {{ fivetran_utils.timestamp_add("hour", 1000, "" ~ dbt.current_timestamp() ~ "") }} ) as schedule_invalidated_at
from schedule_events
)
select
*
from ticket_schedules