DAG: c1_nec ROOT: pipelineProcess

schedule: 0 0,4,8,11,16 * * *


c1_nec

Toggle wrap
  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
try:

    from datetime import datetime, timezone, timedelta
    from airflow import DAG
    
    from airflow.operators.python_operator import PythonOperator
    from airflow.operators.http_operator import SimpleHttpOperator
    from datetime import datetime
    from pandas.io.json import json_normalize
    from airflow.operators.postgres_operator import PostgresOperator

    import pandas as pd
    import json
    import requests
    import numpy as np

    import psycopg2
    from sqlalchemy import create_engine

except Exception as e:
    print("Error {} ".format(e))

dRoW_api_end_url = "https://drow.cloud"

def getDrowToken(**context):
    response = requests.post(
    url=f"{dRoW_api_end_url}/api/auth/authenticate",
    data={
    "username": "icwp2@drow.cloud",
    "password": "dGVzdDAxQHRlc3QuY29t"
    }
    ).json()
    context["ti"].xcom_push(key="token", value=response['token'])

def getSheetData(token , sheetId):
    response = requests.get(
    url=f"{dRoW_api_end_url}/api/sheets/{sheetId}?with_records=true&fields=",
    headers={
    "x-access-token": f"Bearer {token}",
    }
    )
    sheet = json.loads(response.text)
    headers = sheet['header']
    record = sheet['record']
    dataToExtract=[]
    for d in record: 
        objectToPush = {}
        for v in d['values']:
            for c in headers:
                colNameToExtract = c['colName']
                if v['colName'] == colNameToExtract:
                    # # print(v)
                    if v.get('multValue') != None:
                        if v['multValue'] == True:
                            if v['colType'] == 'Table':
                                tObjectArray = []
                                for t in v['tableValue']:
                                    tObjectToPush = {}
                                    for s in t['subValues']:
                                        tObjectToPush[s['colName']] = s.value
                                    tObjectArray.push(tObjectToPush)
                            else:
                                objectToPush[v['colName']] = v['valueArray']
                        else:
                            if v.get('value') != None:
                                if v.get('value') == 'NA':
                                    objectToPush[v['colName']] = None
                                else:
                                    objectToPush[v['colName']] = v['value']
                            else:
                                objectToPush[v['colName']] = None
                    else:
                        if v.get('value') != None:
                            if v.get('value') == 'NA':
                                objectToPush[v['colName']] = None
                            else:
                                objectToPush[v['colName']] = v['value']
                        else:
                            objectToPush[v['colName']] = None
        dataToExtract.append(objectToPush)
    return dataToExtract

def getWorkflowData(token , workflowId):
    response = requests.get(
    url=f"{dRoW_api_end_url}/api/module/document-export/airflow/workflow/{workflowId}?export_type=0",
    headers={
    "x-access-token": f"Bearer {token}",
    }
    )
    return json.loads(response.text)

def changeTimeFormat(date_string):
    if date_string is None:
        return datetime.now() 
    if "GMT" in date_string:
        format_string = "%a %b %d %Y %H:%M:%S GMT%z"
        date_parts = date_string.split(' (')
        date_object = datetime.strptime(date_parts[0], format_string)
        date_object = date_object.replace(tzinfo=timezone.utc)  # make date_object timezone-aware
        date64_object = np.datetime64(date_object, utc=True)  # convert date_object to a datetime64 object
        return date64_object
        return dt
    else:
        return datetime.strptime(date_string, "%d-%b-%Y")

def getdrowPSQLConnectionString():
    host                  = 'drowdatewarehouse.crlwwhgepgi7.ap-east-1.rds.amazonaws.com'  

    # User name of the database server
    dbUserName            = 'dRowAdmin'  

    # Password for the database user
    dbUserPassword        = 'drowsuper'  

    # Name of the database 
    database              = 'drowDateWareHouse'

    # Character set
    charSet               = "utf8mb4"  

    port                  = "5432"

    conn_string = ('postgres://' +
                           dbUserName + ':' + 
                           dbUserPassword +
                           '@' + host + ':' + port +
                           '/' + database)
    return conn_string

def pipelineProcess(**context):
    token = context.get("ti").xcom_pull(key="token")
    Data = getSheetData(token, "63fec465a01bde0cac754b4d")
    Data2 = getSheetData(token, "63fec436df8d4c0cb6f328bf")
    
    conn_string = getdrowPSQLConnectionString()
    db = create_engine(conn_string)
    conn = db.connect()

    df = pd.DataFrame()
    _df = pd.DataFrame()
    with conn as conn:
        for x in Data:
            df_nested_list = json_normalize(x)
            df2 = df_nested_list
            df = df.append(df2)        
        df['starting date']=df['starting date'].apply(pd.to_datetime)
        df['ori comp date']=df['ori comp date'].apply(pd.to_datetime)
        df.columns = df.columns.str.replace(' ', '_').str.replace('.', '').str.replace('(', '_').str.replace(')', '').str.replace('%', 'percent').str.replace('/', '_')
        df.to_sql('c1_nec_section_of_work', con=conn, if_exists='replace', index= False)
        
        for x in Data2:
            df_nested_list = json_normalize(x)
            df2=df_nested_list
            _df = _df.append(df2)
        _df['Starting Date']=_df['Starting Date'].apply(pd.to_datetime)
        _df['Original completion dates']=_df['Original completion dates'].apply(pd.to_datetime)
        _df.columns = _df.columns.str.replace(' ', '_').str.replace('.', '').str.replace('(', '_').str.replace(')', '').str.replace('%', 'percent').str.replace('/', '_')
        _df.to_sql('c1_nec_section_of_work_key_date', con=conn, if_exists='replace', index= False)
        
    Data = getSheetData(token, "63fec4f938237d0c7931f18c")
    df = pd.DataFrame.from_dict(Data)
    numerics = df.select_dtypes(include="number").columns
    df=df.apply(pd.to_numeric, errors='ignore')
    df[numerics]=df[numerics].apply(lambda x: np.round(x, decimals=5))
    df['IP No.']=df['IP No.'].astype(str)
    df['Month - Year']=df['Month - Year'].apply(pd.to_datetime)
    df.columns = df.columns.str.replace(' ', '_').str.replace('.', '_').str.replace('(', '_').str.replace(')', '').str.replace('%', 'percent')

    db = create_engine(conn_string)
    conn = db.connect()
    with conn as conn:
        df.to_sql('c1_finance_data', con=conn, if_exists='replace')
    conn.close()

    data = getSheetData(token, "63fec367a01bde0cac754807")
    df = pd.DataFrame.from_dict(data)
    numerics = df.select_dtypes(include="number").columns
    df=df.apply(pd.to_numeric, errors='ignore')
    df[numerics]=df[numerics].apply(lambda x: np.round(x, decimals=5))
    df['Month - Year']=df['Month - Year'].apply(pd.to_datetime)
    df.columns = df.columns.str.replace(' ', '_').str.replace('.', '_').str.replace('(', '_').str.replace(')', '').str.replace('%', 'percent')
    db = create_engine(conn_string)
    conn = db.connect()
    with conn as conn:
        df.to_sql('c1_finance_status_data', con=conn, if_exists='replace')
    conn.close()

    data = getSheetData(token, "63fc9ef84243400ca9af7c70")
    df = pd.DataFrame.from_dict(data)
    numerics = df.select_dtypes(include="number").columns
    df=df.apply(pd.to_numeric, errors='ignore')
    df[numerics]=df[numerics].apply(lambda x: np.round(x, decimals=5))
    df['Month - Year']=df['Month - Year'].apply(pd.to_datetime)
    df.columns = df.columns.str.replace(' ', '_').str.replace('.', '_').str.replace('(', '_').str.replace(')', '').str.replace('%', 'percent')
    db = create_engine(conn_string)
    conn = db.connect()
    with conn as conn:
        df.to_sql('c1_eot_data', con=conn, if_exists='replace')
    conn.close()

    data= getSheetData(token, "63fec3fca01bde0cac7549a8")
    if data:
        df = pd.DataFrame.from_dict(data)
        df['Submission Date']=df['Submission Date'].apply(changeTimeFormat)
        df['Acceptance Date']=df['Acceptance Date'].apply(changeTimeFormat)
        df.columns = df.columns.str.replace(' ', '_').str.replace('.', '_').str.replace('(', '_').str.replace(')', '').str.replace('%', 'percent')
        db = create_engine(conn_string)
        conn = db.connect()
        with conn as conn:
            df.to_sql('c1_programme_data', con=conn, if_exists='replace')
        conn.close()

    data = getSheetData(token, "63fec4a9df8d4c0cb6f32adf")
    df = pd.DataFrame.from_dict(data)
    df['Planned Completion Date(PCD)']=df['Planned Completion Date(PCD)'].apply(pd.to_datetime)
    df.columns = df.columns.str.replace(' ', '_').str.replace('.', '_').str.replace('(', '_').str.replace(')', '').str.replace('%', 'percent')
    db = create_engine(conn_string)
    conn = db.connect()
    with conn as conn:
        df.to_sql('c1_key_date_data', con=conn, if_exists='replace')
    conn.close()
    
    _Data = getWorkflowData(token, "637c7d22b38f8ca02f5c49ac")
    Mapping= {
            "Original Doc No.": "Original_Doc_No",
            "NEC Doc Type": "NEC_Doc_Type",
            "NEC Event No.": "NEC_Event_No",
            "Doc Ver.": "Doc_Ver",
            "Doc Date": "Doc_Date",
            "Subject": "Subject",
            "From": "From",
            "To": "To",
            "CE/PMI Amount": "CE_PMI_Amount",
            "CE Increase / Decrease": "CE_Increase_Decrease",
            "Quotation Status": "Quotation_Status",
            "NEC Clause": "NEC_Clause"
    }

    conn_string = getdrowPSQLConnectionString()
    db = create_engine(conn_string)
    conn = db.connect()
    df = pd.DataFrame()
    with conn as conn:
        for x in _Data:
            try:
                # print(x['data'])
                if len(x['data'].keys()) == 0:
                    continue
                df_nested_list = json_normalize(x['data'])
                df2 = df_nested_list.reindex(columns=Mapping.keys())
                df2['NEC Doc Title']=x['data']['NEC Doc Type']+x['data']['NEC Event No.']
                df2['Doc Org Ver']= x['data']['Doc Ver.']
                y=0
                if x['data']['Doc Ver.'] == None:
                    df2['Doc Ver.'] = y
                elif x['data']['Doc Ver.'].startswith('Rev. '):
                    y = x['data']['Doc Ver.'].replace('Rev. ', '')
                    y = int(y)
                else:
                    y = x['data']['Doc Ver.'].replace('-', '').replace('r','')
                    if y!='' and not y.isnumeric():
                        y = int(ord(y)) - int(ord('A')) + 1
                    elif y =='':
                        y = 0
                    else :
                        y = int(y)
                    df2['Doc Ver.'] = y
                if (not df2['NEC Doc Title'].empty and 'NEC Doc Title' in df.columns):
                    check_ver_df = df.loc[(df['NEC Doc Title'] == x['data']['NEC Doc Type']+x['data']['NEC Event No.'])]
                    if check_ver_df.empty:
                        df2['is_latest'] = 'Yes'
                    else :
                        check_ver_df2 = check_ver_df.loc[(check_ver_df['Doc Ver.'] > y)]
                        if not check_ver_df2.empty:
                            df2['is_latest'] = "No"
                        else:
                            df.loc[(df['NEC Doc Title'] == x['data']['NEC Doc Type']+x['data']['NEC Event No.']) & ( df['Doc Ver.']<y), 'is_latest'] = 'No'
                            df2['is_latest'] = 'Yes'
                else:
                    df2['is_latest'] = 'Yes'

                if (x['data'].get('NEC Doc Type') or '').strip().upper() == 'PMN-' and y==0 and (x['Status'] == 'Receipt by Contractor' or x['Status'] == 'Closed'):
                    df2['From_Status'] = '1. CE notified'
                elif (x['data'].get('NEC Doc Type') or '').strip().upper() == 'CSQ-' and y==0:
                    df2['From_Status'] = '2. Quotation Submitted'
                elif (x['data'].get('NEC Doc Type') or '').strip().upper() == 'QA-'  and (x['Status'] == 'Receipt by Contractor' or x['Status'] == 'Closed'):
                    df2['From_Status'] = '3. CE implemented'
                elif (x['data'].get('NEC Doc Type') or '').strip().upper() == 'PMIQ-' and y==0:
                    df['From_Status'] = '4. Quotation to be Submitted'
                else:
                    df2['From_Status'] = None

                df2['NEC Doc Title With Version']=x['data']['NEC Doc Type']+x['data']['NEC Event No.']+'-'+str(y)
                if len(x['data']['Change to Time'])>0 and x['data']['NEC Doc Type']!='EW':
                    df4=pd.DataFrame()
                    for change_to_time_table in x['data']['Change to Time']:
                        df3=df2.copy()
                        if 'Key Date' in change_to_time_table:
                            key_date_value = change_to_time_table['Key Date']
                            extracted_value = key_date_value.split(' (')[0]  # This assumes the format is consistent as 'Section 18 (Subject to excision)'
                            df3['Key Date'] = extracted_value
                        if 'Extension in days' in change_to_time_table:
                            df3['Extension in days'] = change_to_time_table['Extension in days']
                        if 'Ori Completion Date' in change_to_time_table:
                            df3['Ori Completion Date'] = change_to_time_table['Ori Completion Date']
                        if 'Revised Completion Date' in change_to_time_table:
                            df3['Revised Completion Date'] = change_to_time_table['Revised Completion Date']
                        df3['Status']=x['Status']
                        df4 = df4.append(df3)
                    df2 = df2.iloc[0:0]
                    df2=df2.append(df4)
                df2['Status']=x['Status']
                df = df.append(df2)
            except Exception as e:
                print(e)
                continue
        df.rename(columns=Mapping, inplace=True)
        df['Doc_Date']=df['Doc_Date'].apply(pd.to_datetime)
        df['Doc_Date'] = df['Doc_Date'] - pd.Timedelta(hours=8)
        df['Ori Completion Date']=df['Ori Completion Date'].apply(pd.to_datetime)
        # df['Ori Completion Date'] = df['Ori Completion Date'] - pd.Timedelta(hours=8)
        df['Revised Completion Date']=df['Revised Completion Date'].apply(pd.to_datetime)
        # df['Revised Completion Date'] = df['Revised Completion Date'] - pd.Timedelta(hours=8)
        df.columns = df.columns.str.replace(' ', '_').str.replace('.', '').str.replace('(', '_').str.replace(')', '').str.replace('%', 'percent').str.replace('/', '_')
        df.to_sql('c1_nec_cas', con=conn, if_exists='replace', index= False)
    conn.close()
    
    resData = getWorkflowData(token, "638b3316a1faf60c870384e2")
    resData = getSheetData(token, "64170431b6c1cf0cd799149c")
    db = create_engine(conn_string)
    conn = db.connect()
    df = pd.DataFrame()
    with conn as conn:
        for x in resData:
            df_nested_list = json_normalize(x)
            df2 = df_nested_list
            if x['Date of Early Warning  (EW)'] == None:
                Date_of_Early_Warning = datetime.now(timezone.utc)
            else:
                Date_of_Early_Warning = datetime.strptime(x['Date of Early Warning  (EW)'], '%Y-%m-%dT%H:%M:%S.%f%z')
            if x['Date of Close of EW'] == None:
                Date_of_Close_of_EW = datetime.now(timezone.utc)
            else: 
                Date_of_Close_of_EW = datetime.strptime(x['Date of Close of EW'], '%Y-%m-%dT%H:%M:%S.%f%z')
            # print((Date_of_Close_of_EW - Date_of_Early_Warning))
            if (Date_of_Close_of_EW - Date_of_Early_Warning) > np.timedelta64(24, 'h'):
                df2['Elapsed_Time'] = ((Date_of_Close_of_EW - Date_of_Early_Warning))
            else:
                df2['Elapsed_Time'] = np.timedelta64(0, 'D')
            if (df2['Elapsed_Time'] >= np.timedelta64(365, 'D')).bool():
                df2['Elapsed_Time_more_then_1_year'] = True
            else:
                df2['Elapsed_Time_more_then_1_year'] = False
            df2['Elapsed_Time'] = df2['Elapsed_Time'] / 1000 / 1000 / 86400000
            df = df.append(df2)

        df['Date of Close of EW']=df['Date of Close of EW'].apply(pd.to_datetime)
        df['Date of Close of EW'] = df['Date of Close of EW'] - pd.Timedelta(hours=8)
        df['Date of Early Warning']=df['Date of Early Warning  (EW)'].apply(pd.to_datetime)
        df['Date of Early Warning'] = df['Date of Early Warning'] - pd.Timedelta(hours=8)
        # df['Action Party (CEDD / AECOM / BKREJV)']=df['Action Party (CEDD / AECOM / BKREJV)']
        df.columns = df.columns.str.replace(' ', '_').str.replace('.', '_').str.replace('(', '_').str.replace(')', '').str.replace('/', '_').str.replace('%', 'percent')
        # df['Action_Party___CEDD_/_AECOM_/_DCK_JV']=np.array(df['Action_Party___CEDD_/_AECOM_/_DCK_JV'].tolist())
        df.to_sql('c1_nec_risk_register', con=conn, if_exists='replace', index= False)



# */2 * * * * Execute every two minute 
with DAG(
        dag_id="c1_nec",
        schedule_interval="0 0,4,8,11,16 * * *",
        default_args={
            "owner": "airflow",
            "retries": 1,
            "retry_delay": timedelta(minutes=5),
            "start_date": datetime(2022, 10, 24)
        },
        catchup=False) as f:
    
    pipelineProcess = PythonOperator(
        task_id="pipelineProcess",
        python_callable=pipelineProcess,
        provide_context=True,
    )
    
    # getWorkflowRecords = PythonOperator(
    #     task_id="getWorkflowRecords",
    #     python_callable=getWorkflowRecords,
    #     provide_context=True,
    # )

    getDrowToken = PythonOperator(
        task_id="getDrowToken",
        python_callable=getDrowToken,
        provide_context=True,
        # op_kwargs={"name": "Dylan"}
    )
    

    # create_table = PostgresOperator(
    #     sql = create_table_sql_query,
    #     task_id = "create_table_task",
    #     postgres_conn_id = "postgres_rds",
    # )

    # insert_data = PostgresOperator(
    #     sql = insert_data_sql_query,
    #     task_id = "insertData_sql_query_task",
    #     postgres_conn_id = "postgres_rds",
    # )

# getDrowToken >> pipelineProcess >> getWorkflowRecords
getDrowToken >> pipelineProcess