DAG: nec_c4 ROOT: getDataAndSendToPSQL

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


nec_c4

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

    from datetime import 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 re

    import psycopg2
    from sqlalchemy import create_engine
    # print("All Dag moudules are sucessfully imported")

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

dRoW_api_end_url = "https://drow.cloud"

def getDrowToken(**context):
    # response = SimpleHttpOperator(
    #     task_id="getDrowToken",
    #     http_conn_id="getDrowToken",
    #     endpoint="https://uat2.drow.cloud/api/auth/authenticate", 
    #     method="POST",
    #     data={
    #     "username": "icwp2@drow.cloud",
    #     "password": "dGVzdDAxQHRlc3QuY29t"
    #     },
    #     xcom_push=True,
    # )

    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'])
    # return 'DLLM{}'.format(response)


def getMongoDB(**context):
    token = context.get("ti").xcom_pull(key="token")
    response = requests.get(
    url=f"{dRoW_api_end_url}/api/module/document-export/airflow/workflow/61e27b64b3e8d9753110ee97?export_type=0",
    headers={
    "x-access-token": f"Bearer {token}",
    }
    )
    # print('got_data')
    # print(response)
    Data = json.loads(response.text)
    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 Amount": "CE_PMI_Amount",
            "CE Increase / Decrease": "CE_Increase_Decrease",
            "Quotation Status": "Quotation_Status",
            "NEC Clause": "NEC_Clause",
            "Receive Date": "Receive_Date"
    }
    # print('start transform')
    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"

    # #cursor Type
    # cusrsorType            = pymysql.cursors.DictCursor



    #create_engine('mysql+mysqldb://root:password@localhost:3306/mydbname', echo = False)
    conn_string = ('postgres://' +
                           dbUserName + ':' + 
                           dbUserPassword +
                           '@' + host + ':' + port +
                           '/' + database)

    # df = context.get("ti").xcom_pull(key="InsertData")
    # print(df)
    # conn_string = 'postgres://user:password@host/data1'
    
    db = create_engine(conn_string)
    conn = db.connect()
    # print('db connected')
    df = pd.DataFrame()
    i=0
    with conn as conn:
        for x in Data:
            try:
                if len(x['data'].keys()) == 0:
                    continue
                df_nested_list = json_normalize(x['data'])
                # print('process 1')
                # print(x['data'].keys())
                df2 = df_nested_list.reindex(columns=Mapping.keys())
                df2['record_status'] = x['Status']
                df2['NEC Doc Title']=x['data']['NEC Doc Type']+x['data']['NEC Event No.']
                df2['Doc Org Ver']= x['data']['Doc Ver.']
                if x['data']['Receive Date']=='' or x['data']['Receive Date']==None:
                    # print('Doc Title:', df2['NEC Doc Title'])
                    # print('Data:', x['data'])
                    df2['withReceiveDate'] = False
                else:
                    df2['withReceiveDate'] = True
                if x['data']['Receive Date']=='' or x['data']['Receive Date']==None:
                    df2['Receive Date']=x['data']['Doc Date']
                
                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():
                        # print('ver',y)
                        y = int(ord(y)) - int(ord('A')) + 1
                        # print(y)
                    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):
                    # print (y)
                    # print('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'
                df2['NEC Doc Title With Version']=x['data']['NEC Doc Type']+x['data']['NEC Event No.']+'-'+str(y)
                
                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 y==0 and (x['Status'] == 'Receipt by Contractor' or x['Status'] == 'Closed'): # Add current status = Receipt by Contractor 
                    df2['From_Status'] = '3. CE implemented'
                else:
                    df2['From_Status'] = None

                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()
                        i = i+1
                        if 'Key Date' in change_to_time_table:
                            df3['Key Date'] = change_to_time_table['Key Date']
                        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']
                        if i >0:
                            df2['From_Status'] = None
                        df4 = df4.append(df3)
                    i = 0
                    df2 = df2.iloc[0:0]
                    df2=df2.append(df4)
                    # print('process 2')
                    # print('loading into DB')
                df = df.append(df2)
            except:
                continue
        # df['is_latest'].fillna('No',inplace=True)
        df.rename(columns=Mapping, inplace=True)
        fields_to_adjust = ['Doc_Date', 'Ori Completion Date', 'Revised Completion Date', 'Receive_Date']

        for field in fields_to_adjust:
            if field in df.columns:
                df[field] = df[field].apply(pd.to_datetime)
                df[field] = df[field] - pd.Timedelta(hours=8)
        # 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('/', '_')
        
        # Received_Date need +800
        def handle_quotation_status(row, df):
            if row['Quotation_Status'] == 'Quotation to be submitted':
                # Filter the DataFrame for the same event and specific document type
                same_event_df = df[(df['NEC_Event_No'] == row['NEC_Event_No']) & (df['NEC_Doc_Type'] == 'CSQ-')]

                # Check if the DataFrame is not empty
                if not same_event_df.empty:
                    # Get the latest document
                    latest_pmn = same_event_df.sort_values(by='Receive_Date', ascending=False).iloc[0] 
                    # Calculate the difference in months
                    months_diff = (row['Receive_Date'] - latest_pmn['Receive_Date']).days / 30
                    if months_diff > 24:
                        return 'Quotation to be submitted > 24 months'
                    else:
                        return 'Quotation to be submitted < 24 months'
                else:
                    # No CSQ records found, calculate the difference from today
                    latest_receive_date = row['Receive_Date']
                    today = pd.Timestamp.today().tz_localize(None).normalize()  # Make today timezone-naive
                    latest_receive_date = latest_receive_date.tz_localize(None).normalize()  # Make latest_receive_date timezone-naive
                    months_diff = (today - latest_receive_date).days / 30
                    if months_diff > 24:
                        return 'Quotation to be submitted > 24 months'
                    else:
                        return 'Quotation to be submitted < 24 months'

            elif row['Quotation_Status'] == 'Quotation to be assessed':
                # Filter the DataFrame for the same event and specific document type
                same_event_df = df[(df['NEC_Event_No'] == row['NEC_Event_No']) & (df['NEC_Doc_Type'] == 'QA-')]

                # Check if the DataFrame is not empty
                if not same_event_df.empty:
                    # Get the latest document
                    latest_pmn = same_event_df.sort_values(by='Receive_Date', ascending=False).iloc[0]
                    # Calculate the difference in months
                    months_diff = (row['Receive_Date'] - latest_pmn['Receive_Date']).days / 30
                    if months_diff > 24:
                        return 'Quotation to be assessed > 24 months'
                    else:
                        return 'Quotation to be assessed < 24 months'
                else:
                    latest_receive_date = row['Receive_Date']
                    today = pd.Timestamp.today().tz_localize(None).normalize()  # Make today timezone-naive
                    latest_receive_date = latest_receive_date.tz_localize(None).normalize()  # Make latest_receive_date timezone-naive
                    months_diff = (today - latest_receive_date).days / 30
                    if months_diff > 24:
                        return 'Quotation to be assessed > 24 months'
                    else:
                        return 'Quotation to be assessed < 24 months'
            else:
                return row['Quotation_Status']
        
        df['Quotation_Status'] = df.apply(lambda row: handle_quotation_status(row, df), axis=1)
        df['Receive_Date'] = df['Receive_Date'].apply(pd.to_datetime) + pd.Timedelta(hours=8)

        def handle_ce_status(row, df):
            same_event_df = df[df['NEC_Event_No'] == row['NEC_Event_No']]
            doc_types = same_event_df['NEC_Doc_Type'].unique()
            same_event_df.sort_values(by='Receive_Date', axis=0, ascending=False, inplace=True)
            today = pd.Timestamp.today().tz_localize(None).normalize()

            if 'QA-' in doc_types:
                latest_row = same_event_df[same_event_df['NEC_Doc_Type'] == 'QA-'].iloc[0]
                if row['NEC_Doc_Type'] == 'QA-' and row['Receive_Date'] == latest_row['Receive_Date']:
                    return 'CE implemented'

            elif 'CSQ-' in doc_types:
                latest_row = same_event_df[same_event_df['NEC_Doc_Type'] == 'CSQ-'].iloc[0]
                if row['NEC_Doc_Type'] == 'CSQ-' and row['Receive_Date'] == latest_row['Receive_Date']:
                    latest_receive_date = row['Receive_Date'].tz_localize(None).normalize()
                    months_diff = (today - latest_receive_date).days / 30
                    if months_diff > 24:
                        return 'Quotation to be assessed > 24 months'
                    else:
                        return 'Quotation to be assessed < 24 months'

            elif 'PMIQ-' in doc_types:
                latest_row = same_event_df[same_event_df['NEC_Doc_Type'] == 'PMIQ-'].iloc[0]
                if row['NEC_Doc_Type'] == 'PMIQ-' and row['Receive_Date'] == latest_row['Receive_Date']:
                    # Calculate the difference in months
                    latest_receive_date = row['Receive_Date'].tz_localize(None).normalize()
                    months_diff = (today - latest_receive_date).days / 30
                    if months_diff > 24:
                        return 'Quotation to be submitted > 24 months'
                    else:
                        return 'Quotation to be submitted < 24 months'

            elif 'PMN-' in doc_types:
                latest_row = same_event_df[same_event_df['NEC_Doc_Type'] == 'PMN-'].iloc[0]
                if row['NEC_Doc_Type'] == 'PMN-':
                    return 'CE to be notified'
            
            elif 'PMI-' in doc_types:
                latest_row = same_event_df[same_event_df['NEC_Doc_Type'] == 'PMI-'].iloc[0]
                if row['NEC_Doc_Type'] == 'PMI-':             
                    return 'CE to be notified'
            
            return ''
        
        df['CE_Status'] = df.apply(lambda row: handle_ce_status(row, df), axis=1)
        df['Receive_Date'] = df['Receive_Date'].apply(pd.to_datetime) + pd.Timedelta(hours=8)

        df.to_sql('nec_c04', con=conn, if_exists='replace', index= False)

# */2 * * * * Execute every two minute 
with DAG(
        dag_id="nec_c4",
        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:
    
    getDataAndSendToPSQL = PythonOperator(
        task_id="getDataAndSendToPSQL",
        python_callable=getMongoDB,
        op_kwargs={"name": "Dylan"},
        provide_context=True,
    )

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

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

getDrowToken >> getDataAndSendToPSQL