1+
2+ from sqlalchemy .orm import sessionmaker
3+ from simple_salesforce import Salesforce
4+ from config import engine
5+
6+ import structlog
7+ logger = structlog .get_logger ()
8+
9+
10+ def get_updated_contact_data ():
11+ Session = sessionmaker (engine )
12+
13+ qry = """ -- Collect latest foster/volunteer dates
14+ with ev_dates as
15+ (select
16+ person_id,
17+ max(case when event_type=1 then time else null end) adopt,
18+ max(case when event_type=2 then time else null end) foster_out,
19+ -- max(case when event_type=3 then time else null end) rto,
20+ max(case when event_type=5 then time else null end) foster_return
21+
22+ from
23+ sl_animal_events sla
24+ left join sl_event_types sle on sle.id = sla.event_type
25+
26+ where sle.id in (1,2,5)
27+ group by person_id
28+ order by person_id
29+ )
30+
31+
32+ select json_agg (upd) as "cd" from (
33+ select
34+ slsf.source_id as "contactId" , -- long salesforce string
35+ slp.id as "personId" , -- short PAWS-local shelterluv id
36+
37+ case
38+ when
39+ (extract(epoch from now())::bigint - foster_out < 365*86400) -- foster out in last year
40+ or (extract(epoch from now())::bigint - foster_return < 365*86400) -- foster return
41+ then 'Active'
42+ else 'Inactive'
43+ end as "updatedFosterStatus" ,
44+
45+ (to_timestamp(foster_out ) at time zone 'America/New_York')::date as "updatedFosterStartDate",
46+ (to_timestamp(foster_return ) at time zone 'America/New_York')::date as "updatedFosterEndDate",
47+
48+ min(vs.from_date) as "updatedFirstVolunteerDate",
49+ max(vs.from_date) as "updatedLastVolunteerDate",
50+ vc.source_id as "volgisticsId"
51+
52+
53+ from
54+ ev_dates
55+ left join pdp_contacts slc on slc.source_id = person_id::text and slc.source_type = 'shelterluvpeople'
56+ left join pdp_contacts slsf on slsf.matching_id = slc.matching_id and slsf.source_type = 'salesforcecontacts'
57+ left join shelterluvpeople slp on slp.internal_id = person_id::text
58+ left join pdp_contacts vc on vc.matching_id = slc.matching_id and vc.source_type = 'volgistics'
59+ left join volgisticsshifts vs on vs.volg_id::text = vc.source_id
60+
61+ where
62+ slsf.source_id is not null
63+
64+ group by
65+ slsf.source_id,
66+ slp.id,
67+ vc.source_id,
68+ foster_out ,
69+ foster_return
70+
71+ ) upd ;
72+
73+
74+ """
75+
76+ with Session () as session :
77+ result = session .execute (qry )
78+ sfdata = result .fetchone ()[0 ]
79+ logger .debug ("Query for Salesforce update returned %d records" , len (sfdata ))
80+ return sfdata
0 commit comments