def remove_subscribers(brand_id, segment_id, subscribers):
    status, current_segment = segment_by_id(brand_id, segment_id)
    if not status:
        return False, current_segment
    if current_segment.type != 'static':
        return False, "Only static segments can be removed from"
    brand = f.GetBrandByID(brand_id)
    if not brand:
        return False, "Error getting Brand"
    results = []
    for subscriber in subscribers:
        result = {}
        l_subscriber = current_segment.subscribers.filter(ListSubscriber.id == subscriber).first()
        if not l_subscriber:
            result = {'ID': subscriber, 'Message': 'Not Found'}
        else:
            l_list = List.query.get(l_subscriber.list_id)
            if not l_list:
                result = {'ID': l_subscriber.email_address, 'Message': 'List not found'}
            else:
                data_type = 'lists/%s/segments/%s/members' % (l_list.mailchimp_id, current_segment.mailchimp_id)
                status, response = f.delete_to_mailchimp(brand, data_type, l_subscriber.email_id)
                if not status:
                    result = {'ID': l_subscriber.email_address, 'Message': "Mailchimp Removal Failed - %s" % response}
                else:
                    try:
                        current_segment.subscribers.remove(l_subscriber)
                        db.session.commit()
                        result = {'ID': l_subscriber.email_address, 'Message': "OK"}
                    except Exception as e:
                        result = {'ID': l_subscriber.email_address, 'Message': "DB Removal Failed - %s" % str(e)}
        results.append(result)
    return True, results
Esempio n. 2
0
def template_to_mailchimp(brand_id,
                          folder_id,
                          name,
                          category_id,
                          active,
                          html="",
                          mailchimp_id=None):
    brand = f.GetBrandByID(brand_id)
    if not brand:
        return False, "Brand not found"
    status, folder = folders.get_folder_by_id(brand_id, folder_id)
    if not status:
        return False, folder
    data = {'name': name}

    if folder.mailchimp_id != None:
        data['folder_id'] = folder.mailchimp_id

    if mailchimp_id == None:
        data['html'] = "<p></p>"
        return f.post_to_mailchimp(brand, "templates", json.dumps(data))
    else:
        data['html'] = html
        return f.patch_to_mailchimp(brand, "templates", json.dumps(data),
                                    mailchimp_id)
def apply_segment_subscribers_from_mailchimp(brand_id, segment_id):
    brand = f.GetBrandByID(brand_id)
    if not brand:
        return False, "Brand not found"
    status, segment = segment_by_id(brand_id, segment_id)
    if not status:
        return False, segment
    current_list = lists.list_by_id(brand_id, segment.list_id)
    if not current_list:
        return False, "List Not Found"

    for subscriber in segment.subscribers.all():
        segment.subscribers.remove(subscriber)
    #db.session.flush()
    db.session.commit()

    status, response = f.post_to_mailchimp(brand, data_type='lists/%s/segments/%s/members' % (current_list.mailchimp_id, segment.mailchimp_id), method="GET")
    if not status:
        return False, response

    j_response = json.loads(response)
    members = j_response['members']
    ids = []
    for member in members:
        ids.append(member['id'])

    subscribers = lists.get_subscribers_by_id_list(brand_id, segment.list_id, ids)
    for subscriber in subscribers:
        segment.subscribers.append(subscriber)
    db.session.commit()

    return True, len(subscribers)
def delete_mailchimp_folder(brand_id, folder_type, mailchimp_id):
    brand = f.GetBrandByID(brand_id)
    if folder_type == "templates":
        data_type = "template-folders"
    elif folder_type == "campaigns":
        data_type = "campaign-folders"
    else:
        return False, "Mailchimp doesn't have folders of type '%s'" % folder_type

    return f.delete_to_mailchimp(brand, data_type, mailchimp_id)
def add_folder_to_mailchimp(brand_id, name, folder_type):
    brand = f.GetBrandByID(brand_id)
    data = {'name': name}
    if folder_type == "templates":
        data_type = "template-folders"
    elif folder_type in ("campaigns", 'ab_tests'):
        data_type = "campaign-folders"
    else:
        return False, "Mailchimp doesn't have folders of type '%s'" % folder_type

    return f.post_to_mailchimp(brand, data_type, json.dumps(data))
def send_notification(activity_definition, activity_definition_type, results, show_results=True, additional_content="", failed=False):
    brand = f.GetBrandByID(activity_definition.brand_id)
    if hasattr(activity_definition, 'target_folder_id'):
        status, target_folder = folders.get_folders(brand.id, activity_definition.target_folder_id, None)
    else:
        status = True
        target_folder = ""
    sub = "Notification"
    if failed:
        sub = 'FAILED'
    if activity_definition_type == 'tracking_exports':
        subject = "%s %s %s" % (brand.client, inflection.singularize(activity_definition_type.replace('_', ' ').title()), sub)
    else:
        subject = "%s %s %s %s" % (brand.client, inflection.singularize(activity_definition.target_type.replace('_', ' ').title()), inflection.singularize(activity_definition_type.replace('_', ' ').title()), sub)
    from_alias = from_email = "*****@*****.**"
    content = "The following %s has completed on %s\n\n" % (inflection.singularize(activity_definition_type), datetime.datetime.now())
    content = '%sName: %s\n' % (content, activity_definition.name)
    if activity_definition_type == "imports":
        content = '%sSource: %s\n' % (content, activity_definition.file_path)
        if status:
            content = '%sDestination: %s\n\n' % (content, target_folder[0]['name'])
    elif activity_definition_type == "exports":
        content = '%sSource: %s\n' % (content, target_folder[0]['name'])
        content = '%sDestination: %s\n\n' % (content, activity_definition.file_path)
    elif activity_definition_type == 'tracking_exports':
        content = '%sSource: %ss\n' % (content, activity_definition.target_activity.title())
        content = '%sDestination: %s\n\n' % (content, activity_definition.file_path)
    if show_results:
        content = '%sRESULTS: \n' % content
        if 'total' in results:
            content = '%sTotal Records: %s\n\n' % (content, results['total'])
        for key, value in results.items():
            if key != 'total':
                content = '%s%s: %s\n' % (content, key.title(), value)
    
    if ('errors' in results and results['errors'] > 0) or ('ignored' in results and results['ignored'] > 0):
    	content = '%s\nRecords ignored or errors encountered have been logged to a delimited text file named %s.log and stored in the same folder as the source file' % (content, activity_definition.file_path)

    if additional_content != "":
        content = '%s\n\nAdditional Information:\n%s' % (content, additional_content)
    try:
        f.SendEmail(from_email, from_alias, activity_definition.notify_addresses, subject, content)
        return True, "Email Sent"
    except Exception as e:
        return False, str(e)
Esempio n. 7
0
def delete_template(brand_id, template_id):
    brand = f.GetBrandByID(brand_id)
    if not brand:
        return False, "Brand not found"
    template = Template.query.filter(
        and_(Template.brand_id == brand_id,
             Template.id == template_id)).first()
    if not template:
        return False, "Template not found"
    status, response = f.delete_to_mailchimp(brand, "templates",
                                             template.mailchimp_id)
    if not status:
        return False, response

    try:
        db.session.delete(template)
        db.session.commit()
        return True, "OK"
    except Exception as ex:
        return False, str(ex)
Esempio n. 8
0
def save_html(brand_id, template_id, content, user):
    brand = f.GetBrandByID(brand_id)
    if not brand:
        return False, "Brand not found"
    template = Template.query.filter(Template.brand_id == brand_id,
                                     Template.id == template_id).first()
    if not template:
        return False, "Template not found"

    data = {'name': template.name, 'html': content}
    status, response = f.patch_to_mailchimp(brand, "templates",
                                            json.dumps(data),
                                            template.mailchimp_id)
    if not status:
        return False, response

    try:
        j_response = json.loads(response)
        status, section_response = get_template_sections(
            brand_id, template.mailchimp_id)
        if not status:
            return False, section_response
        j_section_response = json.loads(section_response)
        if len(j_section_response['sections']) > 0:
            sections = j_section_response['sections']
            status, response = delete_sections_from_db(template.sections.all())
            if not status:
                return False, response
            status, response = add_sections_to_template_db(
                template.id, sections)
            if not status:
                return False, response
        template.thumbnail = j_response['thumbnail']
        template.html = content
        template.updated_by = user.id
        db.session.commit()
        return True, "OK"
    except Exception as ex:
        return False, str(ex)
def segment_to_mailchimp(brand_id, list_id, name, match, conditions=[], static_segment_subscribers=[], mailchimp_id=None):
    brand = f.GetBrandByID(brand_id)
    if not brand:
        return False, "Brand not found"
    current_list = lists.list_by_id(brand_id, list_id)
    if not current_list:
        return False, "List Not Found"

    data = {'name': name}
    if len(conditions) > 0:
        data['options'] = {'match': match, 'conditions': []}
        for condition in conditions:
            data['options']['conditions'].append({'condition_type': condition.type, 'field': condition.field, 'op': condition.op, 'value': condition.value})
    elif len(static_segment_subscribers) > 0:
        data['static_segment'] = static_segment_subscribers

    data_str = json.dumps(data)
    #print data_str
    #return False, "TEST"

    if mailchimp_id == None:
        return f.post_to_mailchimp(brand, data_str=data_str, data_type="lists/%s/segments" % current_list.mailchimp_id)
    else:
        return f.patch_to_mailchimp(brand, data_str=data_str, data_type="lists/%s/segments" % current_list.mailchimp_id, id=mailchimp_id)
def delete_mailchimp_segment(brand_id, segment_id, list_id):
    brand = f.GetBrandByID(brand_id)
    return f.delete_to_mailchimp(brand, data_type="lists/%s/segments" % list_id, id=segment_id)
Esempio n. 11
0
def import_categories(import_def, reader, writer):
    brand = f.GetBrandByID(import_def.brand_id)
    user = User.query.get(import_def.created_by)
    results = {
        'total': 0,
        'inserted': 0,
        'updated': 0,
        'ignored': 0,
        'errors': 0
    }
    if not brand:
        return False, "Brand not found"
    if not user:
        return False, "User not found"
    headers = {}
    row_count = 0
    for row in reader:
        row_count += 1
        if row_count == 1:
            for fld in range(0, len(row)):
                header = row[fld]
                dest = activities.get_mapped_field(header, import_def.mappings,
                                                   import_def.id)
                if dest != None:
                    headers[header] = {'idx': fld, 'dest': dest}
            continue
        results['total'] += 1
        name_idx = headers['name']['idx']
        existing = template_category_exists(import_def.brand_id, row[name_idx])
        if import_def.import_type == 2:
            if existing:
                results['ignored'] += 1
                writer.writerow([
                    row_count, ','.join(row),
                    "Template Category '%s' already exists" % row[name_idx]
                ])
                continue
        elif import_def.import_type == 3:
            if not existing:
                results['ignored'] += 1
                writer.writerow([
                    row_count, ','.join(row),
                    "Template Category '%s' does not exist" % row[name_idx]
                ])
                continue
        else:
            request = {}
            for src, header in headers.items():
                request_col = 'template_categories_%s' % header['dest']
                request[request_col] = row[header['idx']]
            if not existing:
                status, resp = add_template_category(
                    brand.id, row[name_idx], import_def.target_folder_id,
                    user.id)
                if status:
                    results['inserted'] += 1
                else:
                    msg = 'DB Create Failed: %s' % resp
                    results['errors'] += 1
                    writer.writerow([row_count, ','.join(row), msg])
            else:
                current_category = TemplateCategory.query.filter(
                    and_(TemplateCategory.brand_id == brand.id,
                         TemplateCategory.name == row[name_idx])).first()
                if not current_category:
                    results['errors'] += 1
                    writer.writerow([
                        row_count, ','.join(row),
                        "Template Category '%s' not found" % row[name_idx]
                    ])
                    continue

                status, resp = update_template_category(
                    current_category, row[name_idx], user.id)
                if status:
                    results['updated'] += 1
                else:
                    msg = 'DB Update Failed: %s' % resp
                    results['errors'] += 1
                    writer.writerow([row_count, ','.join(row), msg])
    return True, results
Esempio n. 12
0
def get_template_sections(brand_id, id):
    brand = f.GetBrandByID(brand_id)
    if not brand:
        return False, "Brand not found"
    data_type = 'templates/%s/default-content' % id
    return f.post_to_mailchimp(brand, data_type, None, method="GET")