def create_months_for_one_ad_for_one_campaign_dataset(token, start_date, end_date, ad_image, campaign_id):
    try:
        start = datetime.strptime(start_date, "%Y-%m-%d").date()
        end = datetime.strptime(end_date, "%Y-%m-%d").date()
        
        months = {"metadata": {"vol_start_date": start_date, "vol_end_date":
            end_date}, "data": {}}
        url = f"https://api.voluum.com/report?from={start_date}T00:00:00Z&to={end_date}T00:00:00Z&tz=America%2FLos_Angeles&filter={ad_image}&conversionTimeMode=VISIT&currency=USD&sort=month&direction=desc&columns=month&columns=customVariable5&columns=visits&columns=conversions&columns=revenue&columns=cost&columns=profit&columns=cv&columns=roi&columns=epv&groupBy=month&groupBy=custom-variable-5&offset=0&limit=1000&include=ACTIVE&filter1=campaign&filter1Value={campaign_id}"
        res = requests.get(url, headers = {"cwauth-token": token}).json()
        for row in res["rows"]:
            month = row["month"]
            clicks = row["visits"]
            cost = row["cost"]
            revenue = row["revenue"]
            profit = row["profit"]
            if month in months["data"]:
                months["data"][month]["clicks"] += clicks
                months["data"][month]["cost"] += cost
                months["data"][month]["revenue"] += revenue 
                months["data"][month]["profit"] += profit
            else:
                months["data"][month] = {"clicks": clicks,
                        "cost": cost, 
                        "revenue": revenue, 
                        "profit": profit, 
                        "leads": 0,
                        "sales": 0,
                        "month": month,
                        "month_index": find_month_index_number(month)

                        }

        with open(f'{os.environ.get("ULANMEDIAAPP")}/data/conversions_for_each_campaign/oneeighty_conversions_for_each_campaign_dataset.json', 'r') as file:
            json_file = json.load(file)
        conversions_for_each_campaign = json_file["data"]

        for conversion in conversions_for_each_campaign[campaign_id]:
            ad = conversion["customVariable5"]
            if ad != ad_image:
                continue
            month = int(conversion["visitTimestamp"].split('-')[1])
            conversion_type = conversion["transactionId"]
            if conversion_type == "account":
                if month in months["data"]:
                    months["data"][month]["leads"] += 1
            elif conversion_type == "deposit":
                if month in months["data"]:
                    months["data"][month]["sales"] += 1

        with open(f"{os.environ.get('ULANMEDIAAPP')}/data/months_for_one_ad_for_one_campaign/{ad_image}_{campaign_id}_months_for_one_ad_for_one_campaign_dataset.json", "w") as file:
            json.dump(months, file)

        return json.dumps(months)
    except:
        print("Failed - email sent")
        send_email("*****@*****.**", "Failed - create_months_for_one_ad_for_one_campaign_dataset()", "Failed - create_months_for_one_ad_for_one_campaign_dataset()")
        sys.exit()
def create_months_for_one_offer_for_all_campaigns_dataset(
        token, start_date, end_date, offer_name):
    try:
        start = datetime.strptime(start_date, "%Y-%m-%d").date()
        end = datetime.strptime(end_date, "%Y-%m-%d").date()

        months = {
            "metadata": {
                "vol_start_date": start_date,
                "vol_end_date": end_date
            },
            "data": {}
        }
        url = f"https://api.voluum.com/report?from={start_date}T00:00:00Z&to={end_date}T00:00:00Z&tz=America%2FLos_Angeles&filter={offer_name}&conversionTimeMode=VISIT&currency=USD&sort=month&direction=desc&columns=month&columns=offerName&columns=visits&columns=conversions&columns=revenue&columns=cost&columns=profit&columns=cv&columns=roi&columns=epv&groupBy=month&groupBy=offer&offset=0&limit=1000&include=ACTIVE&filter1=traffic-source&filter1Value=37bbd390-ed90-4978-9066-09affa682bcc"
        res = requests.get(url, headers={"cwauth-token": token}).json()
        for row in res["rows"]:
            month = row["month"]
            clicks = row["visits"]
            cost = row["cost"]
            revenue = row["revenue"]
            profit = row["profit"]
            month_index = find_month_index_number(month)

            months["data"][month] = {
                "month": month,
                "month_index": month_index,
                "clicks": clicks,
                "cost": cost,
                "revenue": revenue,
                "profit": profit,
                "leads": 0,
                "sales": 0
            }

        with open(
                f'{os.environ.get("ULANMEDIAAPP")}/data/conversions_for_each_campaign/oneeighty_conversions_for_each_campaign_dataset.json',
                'r') as file:
            json_file = json.load(file)
        conversions_for_each_campaign = json_file["data"]

        offer_pattern = re.compile(r'(\w* - \w* - )(.*)')

        for campaign in conversions_for_each_campaign:
            for conversion in conversions_for_each_campaign[campaign]:
                offer = list(
                    offer_pattern.findall(conversion["offerName"])[0])[1]
                if offer != offer_name:
                    continue
                month = int(conversion["visitTimestamp"].split('-')[1])
                conversion_type = conversion["transactionId"]
                if conversion_type == "account":
                    if month in months["data"]:
                        months["data"][month]["leads"] += 1
                elif conversion_type == "deposit":
                    if month in months["data"]:
                        months["data"][month]["sales"] += 1

        with open(
                f"{os.environ.get('ULANMEDIAAPP')}/data/months_for_one_offer_for_all_campaigns/{offer_name}_months_for_one_offer_for_all_campaigns_dataset.json",
                "w") as file:
            json.dump(months, file)

        return json.dumps(months)
    except:
        print("Failed - email sent")
        send_email(
            "*****@*****.**",
            "Failed - create_months_for_one_offer_for_all_campaigns_dataset()",
            "Failed - create_months_for_one_offer_for_all_campaigns_dataset()")
        sys.exit()
Exemplo n.º 3
0
def create_months_for_one_c_widget_for_all_campaigns_dataset(
        token, start_date, end_date, c_widget_id):
    try:

        start = datetime.strptime(start_date, "%Y-%m-%d").date()
        end = datetime.strptime(end_date, "%Y-%m-%d").date()

        months = {
            "metadata": {
                "vol_start_date": start_date,
                "vol_end_date": end_date
            },
            "data": {}
        }

        while (end - start).days >= 30:
            temp_start = (end - timedelta(30)).strftime("%Y-%m-%d")
            temp_end = end.strftime("%Y-%m-%d")
            # print(f"request from {temp_start} to {temp_end}")
            url = f"https://api.voluum.com/report?from={temp_start}T00:00:00Z&to={temp_end}T00:00:00Z&tz=America%2FLos_Angeles&filter={c_widget_id}&conversionTimeMode=VISIT&sort=month&direction=asc&columns=month&columns=customVariable1&columns=visits&columns=conversions&columns=revenue&columns=cost&columns=profit&columns=cv&columns=roi&columns=epv&groupBy=month&groupBy=custom-variable-1&offset=0&limit=1000000&include=ACTIVE&filter1=traffic-source&filter1Value=37bbd390-ed90-4978-9066-09affa682bcc"
            res = requests.get(url, headers={"cwauth-token": token}).json()
            for row in res["rows"]:
                month = row["month"]
                clicks = row["visits"]
                cost = row["cost"]
                revenue = row["revenue"]
                profit = row["profit"]
                if month in months["data"]:
                    months["data"][month]["clicks"] += clicks
                    months["data"][month]["cost"] += cost
                    months["data"][month]["revenue"] += revenue
                    months["data"][month]["profit"] += profit
                else:
                    months["data"][month] = {
                        "clicks": clicks,
                        "cost": cost,
                        "revenue": revenue,
                        "profit": profit,
                        "leads": 0,
                        "sales": 0,
                        "month": month,
                        "month_index": find_month_index_number(month)
                    }
            end = datetime.strptime(temp_start, "%Y-%m-%d").date()
        if (end - start).days > 0:
            # print(f"request from {start} to {end}")
            url = f"https://api.voluum.com/report?from={start}T00:00:00Z&to={end}T00:00:00Z&tz=America%2FLos_Angeles&filter={c_widget_id}&conversionTimeMode=VISIT&sort=month&direction=asc&columns=month&columns=customVariable1&columns=visits&columns=conversions&columns=revenue&columns=cost&columns=profit&columns=cv&columns=roi&columns=epv&groupBy=month&groupBy=custom-variable-1&offset=0&limit=1000000&include=ACTIVE&filter1=traffic-source&filter1Value=37bbd390-ed90-4978-9066-09affa682bcc"
            res = requests.get(url, headers={"cwauth-token": token}).json()
            for row in res["rows"]:
                month = row["month"]
                clicks = row["visits"]
                cost = row["cost"]
                revenue = row["revenue"]
                profit = row["profit"]
                if month in months["data"]:
                    months["data"][month]["clicks"] += clicks
                    months["data"][month]["cost"] += cost
                    months["data"][month]["revenue"] += revenue
                    months["data"][month]["profit"] += profit
                else:
                    months["data"][month] = {
                        "clicks": clicks,
                        "cost": cost,
                        "revenue": revenue,
                        "profit": profit,
                        "leads": 0,
                        "sales": 0,
                        "month": month,
                        "month_index": find_month_index_number(month)
                    }

        with open(
                f'{os.environ.get("ULANMEDIAAPP")}/data/conversions_for_each_campaign/oneeighty_conversions_for_each_campaign_dataset.json',
                'r') as file:
            json_file = json.load(file)
        conversions_for_each_campaign = json_file["data"]

        for campaign in conversions_for_each_campaign:
            for conversion in conversions_for_each_campaign[campaign]:
                widget_id = conversion["customVariable1"]
                if widget_id != c_widget_id:
                    continue
                month = int(conversion["visitTimestamp"].split('-')[1])
                conversion_type = conversion["transactionId"]
                if conversion_type == "account":
                    if month in months["data"]:
                        months["data"][month]["leads"] += 1
                elif conversion_type == "deposit":
                    if month in months["data"]:
                        months["data"][month]["sales"] += 1

        with open(
                f"{os.environ.get('ULANMEDIAAPP')}/data/months_for_one_c_widget_for_all_campaigns/{c_widget_id}_months_for_one_c_widget_for_all_campaigns_dataset.json",
                "w") as file:
            json.dump(months, file)

        return json.dumps(months)

    except:
        print("Failed - email sent")
        send_email(
            "*****@*****.**",
            "Failed - create_months_for_one_c_widget_for_all_campaigns_dataset()",
            "Failed - create_months_for_one_c_widget_for_all_campaigns_dataset()"
        )
        sys.exit()